@devries-cameron20 / t3code-1 / commits / 451bb459f1
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

refactor(web): running timers share one clock instead of an interval each (#25616)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 26, 2026 at 14:50 UTC 451bb459f11479ce8953f9931f7c7f742e04a5c5
10 files changed +219 -150
apps/web/src/components/chat/AgentElapsed.tsx
+10 -30
@@ -1,7 +1,7 @@
1 import type { RuntimeSubagent } from "@t3tools/client-runtime/state/subagentRuntime";
2 import { isOrchestrationV2WorkActive } from "@t3tools/contracts";
3 import { deriveSubagentElapsedMs } from "@t3tools/shared/orchestrationTiming";
4 -import { useEffect, useRef } from "react";
4 +import { tickTextContent } from "~/lib/tickTextContent";
5
6 function formatElapsedSeconds(totalSeconds: number): string {
7 const seconds = Math.max(0, Math.floor(totalSeconds));
@@ -33,38 +33,18 @@ export function AgentElapsed({
33 compact?: boolean;
34 }) {
35 const format = compact ? formatCompactElapsedSeconds : formatElapsedSeconds;
36 - const textRef = useRef<HTMLSpanElement>(null);
36 const live = isOrchestrationV2WorkActive(agent.status);
38 - const startedAt = agent.startedAt;
39 - const completedAt = agent.completedAt;
40 -
41 - useEffect(() => {
42 - if (!startedAt) {
43 - return;
44 - }
45 - const update = () => {
46 - if (textRef.current) {
47 - const elapsedMs = deriveSubagentElapsedMs(
48 - { status: agent.status, startedAt, completedAt },
49 - Date.now(),
50 - );
51 - const text = elapsedMs === null ? "" : format(elapsedMs / 1000);
52 - if (textRef.current.textContent !== text) textRef.current.textContent = text;
53 - }
54 - };
55 - update();
56 - if (!live) return;
57 - const id = setInterval(update, 1000);
58 - return () => clearInterval(id);
59 - }, [live, startedAt, completedAt, agent.status, format]);
60 -
61 - const elapsedMs = deriveSubagentElapsedMs(agent, 0);
62 - if (elapsedMs === null) {
37 + const { status, startedAt, completedAt } = agent;
38 + if (deriveSubagentElapsedMs(agent, 0) === null) {
39 return null;
40 }
41 return (
66 - <span ref={textRef} className="tabular-nums">
67 - {format(elapsedMs / 1000)}
68 - </span>
42 + <span
43 + ref={tickTextContent((nowMs) => {
44 + const elapsedMs = deriveSubagentElapsedMs({ status, startedAt, completedAt }, nowMs);
45 + return elapsedMs === null ? "" : format(elapsedMs / 1000);
46 + }, live)}
47 + className="tabular-nums"
48 + />
49 );
50 }
apps/web/src/components/chat/ProviderSubagentBar.tsx
+2 -16
@@ -4,8 +4,8 @@ import {
4 } from "@t3tools/client-runtime/state/thread-execution";
5 import { isOrchestrationV2WorkActive } from "@t3tools/contracts";
6 import { ArrowUpLeftIcon } from "lucide-react";
7 -import { useLayoutEffect, useRef } from "react";
7
8 +import { tickTextContent } from "~/lib/tickTextContent";
9 import type { ProviderInstanceEntry } from "../../providerInstances";
10 import { Button } from "../ui/button";
11 import { ProviderInstanceIcon } from "./ProviderInstanceIcon";
@@ -18,7 +18,6 @@ export function ProviderSubagentBar(props: {
18 readonly status: ProviderSubagentStatus | null;
19 readonly onOpenParent: (() => void) | null;
20 }) {
21 - const statusRef = useRef<HTMLSpanElement>(null);
21 const { status } = props;
22 const live = status !== null && isOrchestrationV2WorkActive(status.status);
23 const modelDescription =
@@ -28,19 +27,6 @@ export function ProviderSubagentBar(props: {
27 0,
28 );
29
31 - // Write timer labels to the DOM to avoid chat renders on each tick.
32 - useLayoutEffect(() => {
33 - const update = () => {
34 - if (statusRef.current) {
35 - statusRef.current.textContent = formatProviderSubagentStatus(status, Date.now());
36 - }
37 - };
38 - update();
39 - if (!live) return;
40 - const id = setInterval(update, 1_000);
41 - return () => clearInterval(id);
42 - }, [live, status]);
43 -
30 // Sized by the composer, not the viewport: a docked side panel narrows the
31 // chat column on a wide window, and one row there squeezes out the model
32 // and status, so the status drops to its own line instead.
@@ -67,7 +53,7 @@ export function ProviderSubagentBar(props: {
53 )}
54 </span>
55 <span
70 - ref={statusRef}
56 + ref={tickTextContent((nowMs) => formatProviderSubagentStatus(status, nowMs), live)}
57 aria-hidden
58 className="min-w-0 max-w-full truncate text-muted-foreground tabular-nums @max-[560px]/composer-surface:text-xs"
59 />
apps/web/src/components/chat/TimelineMinimap.tsx
+4 -7
@@ -1,5 +1,5 @@
1 import { resolveTimelineMinimapPreview, type TimelineMinimapItem } from "./timelineMinimapItems";
2 -import { useEffect, useRef, useState, type MouseEvent } from "react";
2 +import { useRef, useState, type MouseEvent } from "react";
3 import { ChevronDownIcon, ChevronUpIcon } from "lucide-react";
4 import { Button } from "../ui/button";
5 import {
@@ -61,11 +61,6 @@ export function TimelineMinimap({
61 const pressedOnStripRef = useRef(false);
62 const [passThrough, setPassThrough] = useState(false);
63
64 - useEffect(() => {
65 - if (!passThrough) return;
66 - return onMouseButtonsReleased(() => setPassThrough(false));
67 - }, [passThrough]);
68 -
64 const resolvedActiveIndex =
65 activeIndex !== null && activeIndex < items.length ? activeIndex : null;
66 const activeItem = resolveTimelineMinimapPreview(
@@ -143,7 +138,9 @@ export function TimelineMinimap({
138 });
139 }}
140 onMouseMove={(event) => {
146 - if (event.buttons !== 0 && !pressedOnStripRef.current) setPassThrough(true);
141 + if (event.buttons === 0 || pressedOnStripRef.current || passThrough) return;
142 + setPassThrough(true);
143 + onMouseButtonsReleased(() => setPassThrough(false));
144 }}
145 style={{
146 height: resolveTimelineMinimapHeightStyle(items.length),
apps/web/src/components/chat/TimelineWorkGroupRows.tsx
+6 -18
@@ -9,8 +9,9 @@ import { type ToolActivityIcon } from "@t3tools/contracts";
9 import { liveThoughtLine } from "@t3tools/client-runtime/work-log/presentation";
10 import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor";
11 import { observeResize } from "~/lib/observeResize";
12 +import { tickTextContent } from "~/lib/tickTextContent";
13 import { observeVisibleAnimation } from "../../lib/visibleAnimation";
13 -import { memo, use, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
14 +import { memo, use, useLayoutEffect, useRef, useState, type ReactNode } from "react";
15 import { LegendList, type LegendListRef } from "@legendapp/list/react";
16 import { workEntryDisplayIndicatesToolFailure } from "../../session-logic";
17 import ChatMarkdown from "../ChatMarkdown";
@@ -109,24 +110,11 @@ export const WorkGroupSection = memo(function WorkGroupSection({
110 });
111
112 function WorkingTimer({ createdAt }: { createdAt: string }) {
112 - const textRef = useRef<HTMLSpanElement>(null);
113 - const initialText = formatWorkingTimerNow(createdAt);
114 -
115 - useEffect(() => {
116 - const updateText = () => {
117 - if (textRef.current) {
118 - textRef.current.textContent = formatWorkingTimerNow(createdAt);
119 - }
120 - };
121 - updateText();
122 - const id = setInterval(updateText, 1000);
123 - return () => clearInterval(id);
124 - }, [createdAt]);
125 -
113 return (
127 - <span ref={textRef} className="tabular-nums">
128 - {initialText}
129 - </span>
114 + <span
115 + ref={tickTextContent(() => formatWorkingTimerNow(createdAt), true)}
116 + className="tabular-nums"
117 + />
118 );
119 }
120
apps/web/src/components/chat/WorktreeSetupCard.browser.test.tsx new
+78
@@ -0,0 +1,78 @@
1 +import { ThreadId, type WorktreeSetupSnapshot } from "@t3tools/contracts";
2 +import { expect, it, vi } from "vite-plus/test";
3 +
4 +import { act, fakeTimers, render } from "../../../test/render";
5 +import { WorktreeSetupCard } from "./WorktreeSetupCard";
6 +
7 +const NOW = new Date("2026-10-26T12:00:10.000Z");
8 +
9 +function snapshot(overrides: Partial<WorktreeSetupSnapshot>): WorktreeSetupSnapshot {
10 + return {
11 + threadId: ThreadId.make("thread-1"),
12 + phase: "running",
13 + startedAt: "2026-10-26T12:00:00.000Z",
14 + endedAt: null,
15 + branch: "t3/feature",
16 + baseRef: "main",
17 + worktreePath: "/repo/.t3/worktrees/feature",
18 + setupScript: null,
19 + stages: [
20 + {
21 + id: "fetch",
22 + status: "done",
23 + startedAt: "2026-10-26T12:00:00.000Z",
24 + endedAt: "2026-10-26T12:00:03.000Z",
25 + percent: null,
26 + detail: null,
27 + tail: [],
28 + },
29 + {
30 + id: "checkout",
31 + status: "running",
32 + startedAt: "2026-10-26T12:00:03.000Z",
33 + endedAt: null,
34 + percent: null,
35 + detail: null,
36 + tail: [],
37 + },
38 + ],
39 + error: null,
40 + sequence: 1,
41 + ...overrides,
42 + };
43 +}
44 +
45 +const card = (value: WorktreeSetupSnapshot) => (
46 + <WorktreeSetupCard snapshot={value} onCancel={null} onWorkLocally={null} onOpenTerminal={null} />
47 +);
48 +
49 +it("ticks the running stage while finished stages keep their duration", async () => {
50 + using _timers = fakeTimers();
51 + vi.setSystemTime(NOW);
52 + await using screen = await render(card(snapshot({})));
53 + // Assert synchronously: expect.element polls on timers these tests fake.
54 + const section = screen.getByRole("region", { name: "Worktree setup" });
55 +
56 + expect(section.element().textContent).toContain("Fetch base branch3.0s");
57 + expect(section.element().textContent).toContain("Check out files7.0s");
58 +
59 + await act(async () => {
60 + await vi.advanceTimersByTimeAsync(5_000);
61 + });
62 + expect(section.element().textContent).toContain("Fetch base branch3.0s");
63 + expect(section.element().textContent).toContain("Check out files12s");
64 +});
65 +
66 +it("stops a stage interrupted by the setup ending at the setup's end", async () => {
67 + using _timers = fakeTimers();
68 + vi.setSystemTime(NOW);
69 + const failed = snapshot({ phase: "failed", endedAt: "2026-10-26T12:00:05.000Z" });
70 + await using screen = await render(card(failed));
71 + const section = screen.getByRole("region", { name: "Worktree setup" });
72 +
73 + expect(section.element().textContent).toContain("Check out files2.0s");
74 + await act(async () => {
75 + await vi.advanceTimersByTimeAsync(5_000);
76 + });
77 + expect(section.element().textContent).toContain("Check out files2.0s");
78 +});
apps/web/src/components/chat/WorktreeSetupCard.tsx
+53 -54
@@ -14,7 +14,7 @@ import {
14 XIcon,
15 } from "lucide-react";
16 import { ChevronDown, ChevronRight } from "lucide";
17 -import { useEffect, useState, type ReactNode } from "react";
17 +import { useState, type ReactNode } from "react";
18
19 import { Button } from "~/components/ui/button";
20 import { MorphIcon } from "~/components/MorphIcon";
@@ -22,6 +22,7 @@ import { Spinner } from "~/components/ui/spinner";
22 import { MiddleTruncate } from "../ui/middle-truncate";
23 import { observeVisibleAnimation } from "~/lib/visibleAnimation";
24 import { cn } from "~/lib/utils";
25 +import { useNowSecond } from "~/hooks/useNowSecond";
26 import { WorkLogRow } from "./WorkLog";
27
28 interface WorktreeSetupCardProps {
@@ -31,22 +32,35 @@ interface WorktreeSetupCardProps {
32 onOpenTerminal: (() => void) | null;
33 }
34
34 -function stageElapsedMs(stage: WorktreeSetupStage, nowMs: number): number | null {
35 - if (!stage.startedAt) return null;
36 - const start = Date.parse(stage.startedAt);
37 - const end = stage.endedAt ? Date.parse(stage.endedAt) : nowMs;
38 - if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
39 - return Math.max(0, end - start);
35 +function elapsedMs(startedAt: string | null, endMs: number): number | null {
36 + if (!startedAt) return null;
37 + const start = Date.parse(startedAt);
38 + if (!Number.isFinite(start) || !Number.isFinite(endMs)) return null;
39 + return Math.max(0, endMs - start);
40 }
41
42 -function useNowWhile(active: boolean): number {
43 - const [nowMs, setNowMs] = useState(() => Date.now());
44 - useEffect(() => {
45 - if (!active) return;
46 - const id = setInterval(() => setNowMs(Date.now()), 1_000);
47 - return () => clearInterval(id);
48 - }, [active]);
49 - return nowMs;
42 +/** Mounted only while setup runs, so finished setups never subscribe to the tick. */
43 +function LiveElapsed({ startedAt }: { startedAt: string }) {
44 + const elapsed = elapsedMs(startedAt, useNowSecond());
45 + return elapsed === null ? null : <>{formatDuration(elapsed)}</>;
46 +}
47 +
48 +/** A finished duration, or a ticking one while setup is still running. */
49 +function Elapsed({
50 + startedAt,
51 + endedAt,
52 + live,
53 +}: {
54 + startedAt: string | null;
55 + endedAt: string | null;
56 + live: boolean;
57 +}) {
58 + if (!startedAt) return null;
59 + if (endedAt) {
60 + const elapsed = elapsedMs(startedAt, Date.parse(endedAt));
61 + return elapsed === null ? null : <>{formatDuration(elapsed)}</>;
62 + }
63 + return live ? <LiveElapsed startedAt={startedAt} /> : null;
64 }
65
66 function StageIcon({ status }: { status: WorktreeSetupStage["status"] }) {
@@ -110,13 +124,7 @@ function headerLabel(snapshot: WorktreeSetupSnapshot): string {
124 }
125 }
126
113 -function SetupHeaderRow({
114 - snapshot,
115 - totalElapsed,
116 -}: {
117 - snapshot: WorktreeSetupSnapshot;
118 - totalElapsed: number | null;
119 -}) {
127 +function SetupHeaderRow({ snapshot }: { snapshot: WorktreeSetupSnapshot }) {
128 const running = snapshot.phase === "running";
129 const failed = snapshot.phase === "failed";
130 const finishedWithFailedStage =
@@ -142,11 +150,9 @@ function SetupHeaderRow({
150 <span className="block truncate">{text}</span>
151 {running ? <ShimmerOverlay>{text}</ShimmerOverlay> : null}
152 </span>
145 - {totalElapsed !== null ? (
146 - <span className="ml-auto shrink-0 text-xs text-muted-foreground">
147 - {formatDuration(totalElapsed)}
148 - </span>
149 - ) : null}
153 + <span className="ml-auto shrink-0 text-xs text-muted-foreground empty:hidden">
154 + <Elapsed startedAt={snapshot.startedAt} endedAt={snapshot.endedAt} live={running} />
155 + </span>
156 </div>
157 </div>
158 );
@@ -154,14 +160,15 @@ function SetupHeaderRow({
160
161 function StageRow({
162 stage,
157 - nowMs,
163 + setupRunning,
164 + setupEndedAt,
165 scriptName,
166 }: {
167 stage: WorktreeSetupStage;
161 - nowMs: number;
168 + setupRunning: boolean;
169 + setupEndedAt: string | null;
170 scriptName: string | null;
171 }) {
164 - const elapsed = stageElapsedMs(stage, nowMs);
172 const label =
173 stage.id === "setup-script" && scriptName ? scriptName : worktreeSetupStageLabel(stage.id);
174 const running = stage.status === "running";
@@ -198,9 +205,14 @@ function StageRow({
205 {trailing}
206 </span>
207 ) : null}
201 - {elapsed !== null && stage.status !== "skipped" && stage.status !== "pending" ? (
202 - <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
203 - {formatDuration(elapsed)}
208 + {stage.status !== "skipped" && stage.status !== "pending" ? (
209 + <span className="shrink-0 text-xs text-muted-foreground tabular-nums empty:hidden">
210 + <Elapsed
211 + startedAt={stage.startedAt}
212 + // A stage interrupted by the setup ending stops with it.
213 + endedAt={stage.endedAt ?? setupEndedAt}
214 + live={setupRunning}
215 + />
216 </span>
217 ) : null}
218 </>
@@ -272,13 +284,7 @@ function SetupDetails({ snapshot }: { snapshot: WorktreeSetupSnapshot }) {
284 );
285 }
286
275 -function CollapsedSummaryRow({
276 - snapshot,
277 - totalElapsed,
278 -}: {
279 - snapshot: WorktreeSetupSnapshot;
280 - totalElapsed: number | null;
281 -}) {
287 +function CollapsedSummaryRow({ snapshot }: { snapshot: WorktreeSetupSnapshot }) {
288 const status: WorktreeSetupStage["status"] =
289 snapshot.phase === "failed" || snapshot.phase === "cancelled"
290 ? "failed"
@@ -297,11 +303,9 @@ function CollapsedSummaryRow({
303 }
304 label={<span className={stageRowClassName(status)}>{label}</span>}
305 trailing={
300 - totalElapsed !== null ? (
301 - <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
302 - {formatDuration(totalElapsed)}
303 - </span>
304 - ) : null
306 + <span className="shrink-0 text-xs text-muted-foreground tabular-nums empty:hidden">
307 + <Elapsed startedAt={snapshot.startedAt} endedAt={snapshot.endedAt} live={false} />
308 + </span>
309 }
310 />
311 );
@@ -317,13 +321,7 @@ export function WorktreeSetupCard({
321 embedded?: boolean;
322 }) {
323 const running = snapshot.phase === "running";
320 - const nowMs = useNowWhile(running);
324 const [detailsOpen, setDetailsOpen] = useState(false);
322 - const totalElapsed = (() => {
323 - const start = Date.parse(snapshot.startedAt);
324 - const end = snapshot.endedAt ? Date.parse(snapshot.endedAt) : nowMs;
325 - return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null;
326 - })();
325 const setupStage = snapshot.stages.find((stage) => stage.id === "setup-script");
326 const showTerminal = onOpenTerminal && setupStage && setupStage.status !== "pending";
327 const collapsed = embedded && !running;
@@ -335,16 +333,17 @@ export function WorktreeSetupCard({
333
334 return (
335 <section aria-label="Worktree setup" data-worktree-setup-phase={snapshot.phase}>
338 - {showHeader ? <SetupHeaderRow snapshot={snapshot} totalElapsed={totalElapsed} /> : null}
336 + {showHeader ? <SetupHeaderRow snapshot={snapshot} /> : null}
337 {collapsed ? (
340 - <CollapsedSummaryRow snapshot={snapshot} totalElapsed={totalElapsed} />
338 + <CollapsedSummaryRow snapshot={snapshot} />
339 ) : (
340 <div className={showHeader ? "pt-1.5" : undefined}>
341 {snapshot.stages.map((stage) => (
342 <div key={stage.id}>
343 <StageRow
344 stage={stage}
347 - nowMs={nowMs}
345 + setupRunning={running}
346 + setupEndedAt={snapshot.endedAt}
347 scriptName={snapshot.setupScript?.name ?? null}
348 />
349 {stage.id === "setup-script" && showTail ? (
apps/web/src/components/chat/useThreadLifecycle.tsx
+7 -24
@@ -12,6 +12,7 @@ import {
12 makeThreadErrorSetter,
13 } from "../ChatView.logic";
14 import { useStableCallback } from "../../hooks/useStableCallback";
15 +import { useNowAfter } from "../../hooks/useDeadline";
16 import type { usePendingThreadRequests } from "./usePendingThreadRequests";
17 import {
18 AuthOrchestrationOperateScope,
@@ -32,7 +33,7 @@ import { settleAndAdvance } from "../../settleAndAdvance";
33 import type { ChatShortcutCommands } from "./useChatShortcuts";
34 import { resolveThreadLastVisitedAt } from "../Sidebar.logic";
35 import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
35 -import { type SetStateAction, useEffect, useRef, useState } from "react";
36 +import { type SetStateAction, useRef, useState } from "react";
37 import { useNavigate, useRouter } from "@tanstack/react-router";
38 import {
39 isAtomCommandInterrupted,
@@ -171,33 +172,15 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
172 const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
173 const supportsPinning = serverConfig?.environment.capabilities.threadPinning === true;
174 const activeThreadPinned = supportsPinning && activeThreadShell?.pinnedAt != null;
174 - // The compiler caches render results on their inputs, so a clock read in render
175 - // stays frozen until the shell changes. The clock is state: reset with the shell,
176 - // and moved by the wake timer.
177 - const [snoozeClockState, setSnoozeClockState] = useState(() => ({
178 - shell: activeThreadShell,
179 - now: new Date().toISOString(),
180 - }));
181 - if (snoozeClockState.shell !== activeThreadShell) {
182 - // oxlint-disable-next-line react/purity -- Reseeds the snooze clock only in the render-phase adjustment that runs when the shell changes.
183 - setSnoozeClockState({ shell: activeThreadShell, now: new Date().toISOString() });
184 - }
185 - const snoozeClock = snoozeClockState.now;
175 + // A clock read in render would stay frozen in the compiler's cache, so the
176 + // snooze checks read a snapshot that moves when the wake time changes or passes.
177 + const snoozeClock = new Date(
178 + useNowAfter(Date.parse(activeThreadShell?.snoozedUntil ?? "") || null),
179 + ).toISOString();
180 const activeThreadSnoozed =
181 activeThreadShell !== null &&
182 supportsSnooze &&
183 effectiveSnoozed(activeThreadShell, { now: snoozeClock });
190 - useEffect(() => {
191 - if (!activeThreadSnoozed) return;
192 - const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? "");
193 - if (!Number.isFinite(wakeAtMs)) return;
194 - const id = window.setTimeout(
195 - () => setSnoozeClockState((clock) => ({ ...clock, now: new Date().toISOString() })),
196 - Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647),
197 - );
198 - return () => window.clearTimeout(id);
199 - // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A clock that lands before the wake time (timer clamping, clock skew) re-arms the timer.
200 - }, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeClock]);
184 const activeThreadWokeAt =
185 activeThreadShell !== null && supportsSnooze
186 ? threadWokeAt(activeThreadShell, { now: snoozeClock })
apps/web/src/hooks/useDeadline.browser.test.tsx new
+25
@@ -0,0 +1,25 @@
1 +import { describe, expect, it, vi } from "vite-plus/test";
2 +
3 +import { act, fakeTimers, render } from "../../test/render";
4 +import { useNowAfter } from "./useDeadline";
5 +
6 +function Probe(props: { deadlineMs: number }) {
7 + const nowMs = useNowAfter(props.deadlineMs);
8 + return <output>{nowMs >= props.deadlineMs ? "passed" : "pending"}</output>;
9 +}
10 +
11 +describe("useNowAfter", () => {
12 + it("reads a fresh clock when a later deadline passes", async () => {
13 + // The first render reads the clock.
14 + using _timers = fakeTimers({ now: 0 });
15 + await using screen = await render(<Probe deadlineMs={1_000} />, {
16 + // A bare hook probe; nothing here navigates.
17 + router: false,
18 + });
19 + await screen.rerender(<Probe deadlineMs={2_000} />);
20 + await expect.element(screen.getByText("pending")).toBeInTheDocument();
21 +
22 + await act(() => vi.advanceTimersByTime(2_000));
23 + await expect.element(screen.getByText("passed")).toBeInTheDocument();
24 + });
25 +});
apps/web/src/hooks/useDeadline.ts
+16 -1
@@ -1,8 +1,23 @@
1 import { deadlineStore } from "@t3tools/client-runtime/clock";
2 -import { useSyncExternalStore } from "react";
2 +import { useState, useSyncExternalStore } from "react";
3
4 /** Re-renders once when `deadlineMs` (epoch ms) is reached; `null` never passes. */
5 export function useDeadlinePassed(deadlineMs: number | null): boolean {
6 const store = deadlineStore(deadlineMs);
7 return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
8 }
9 +
10 +/**
11 + * `Date.now()` captured at mount and re-read when `deadlineMs` changes or
12 + * passes, so comparisons against the deadline flip exactly once.
13 + */
14 +export function useNowAfter(deadlineMs: number | null): number {
15 + const passed = useDeadlinePassed(deadlineMs);
16 + const readNow = () => ({ deadlineMs, passed, nowMs: Date.now() });
17 + const [snapshot, setSnapshot] = useState(readNow);
18 + // The clock is read inside the updater: the compiler caches a bare
19 + // `Date.now()` in render once per instance, so a later adjustment would reuse
20 + // the first reading. React discards this render and re-runs with the update.
21 + if (snapshot.deadlineMs !== deadlineMs || snapshot.passed !== passed) setSnapshot(readNow);
22 + return snapshot.nowMs;
23 +}
apps/web/src/lib/tickTextContent.ts new
+18
@@ -0,0 +1,18 @@
1 +import { secondTick } from "@t3tools/client-runtime/clock";
2 +
3 +/**
4 + * Ref callback that writes `format(Date.now())` into a node and, while `live`,
5 + * rewrites it on the shared second tick. Running timers update through the DOM
6 + * so a ticking label never re-renders the timeline or composer around it.
7 + */
8 +export function tickTextContent(format: (nowMs: number) => string, live: boolean) {
9 + return (node: HTMLElement | null) => {
10 + if (!node) return;
11 + const write = () => {
12 + const text = format(Date.now());
13 + if (node.textContent !== text) node.textContent = text;
14 + };
15 + write();
16 + return live ? secondTick.subscribe(write) : undefined;
17 + };
18 +}