Skip to content
TypeScript

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

Julius Marminge451bb459f114
diff --git a/apps/web/src/components/chat/AgentElapsed.tsx b/apps/web/src/components/chat/AgentElapsed.tsx
index fba20f7e959..149c4b735b2 100644
--- a/apps/web/src/components/chat/AgentElapsed.tsx
+++ b/apps/web/src/components/chat/AgentElapsed.tsx
@@ -1,7 +1,7 @@
import type { RuntimeSubagent } from "@t3tools/client-runtime/state/subagentRuntime";
import { isOrchestrationV2WorkActive } from "@t3tools/contracts";
import { deriveSubagentElapsedMs } from "@t3tools/shared/orchestrationTiming";
-import { useEffect, useRef } from "react";
+import { tickTextContent } from "~/lib/tickTextContent";
function formatElapsedSeconds(totalSeconds: number): string {
const seconds = Math.max(0, Math.floor(totalSeconds));
@@ -33,38 +33,18 @@ export function AgentElapsed({
compact?: boolean;
}) {
const format = compact ? formatCompactElapsedSeconds : formatElapsedSeconds;
- const textRef = useRef<HTMLSpanElement>(null);
const live = isOrchestrationV2WorkActive(agent.status);
- const startedAt = agent.startedAt;
- const completedAt = agent.completedAt;
-
- useEffect(() => {
- if (!startedAt) {
- return;
- }
- const update = () => {
- if (textRef.current) {
- const elapsedMs = deriveSubagentElapsedMs(
- { status: agent.status, startedAt, completedAt },
- Date.now(),
- );
- const text = elapsedMs === null ? "" : format(elapsedMs / 1000);
- if (textRef.current.textContent !== text) textRef.current.textContent = text;
- }
- };
- update();
- if (!live) return;
- const id = setInterval(update, 1000);
- return () => clearInterval(id);
- }, [live, startedAt, completedAt, agent.status, format]);
-
- const elapsedMs = deriveSubagentElapsedMs(agent, 0);
- if (elapsedMs === null) {
+ const { status, startedAt, completedAt } = agent;
+ if (deriveSubagentElapsedMs(agent, 0) === null) {
return null;
}
return (
- <span ref={textRef} className="tabular-nums">
- {format(elapsedMs / 1000)}
- </span>
+ <span
+ ref={tickTextContent((nowMs) => {
+ const elapsedMs = deriveSubagentElapsedMs({ status, startedAt, completedAt }, nowMs);
+ return elapsedMs === null ? "" : format(elapsedMs / 1000);
+ }, live)}
+ className="tabular-nums"
+ />
);
}
diff --git a/apps/web/src/components/chat/ProviderSubagentBar.tsx b/apps/web/src/components/chat/ProviderSubagentBar.tsx
index a3763c96d11..6aa8799c70b 100644
--- a/apps/web/src/components/chat/ProviderSubagentBar.tsx
+++ b/apps/web/src/components/chat/ProviderSubagentBar.tsx
@@ -4,8 +4,8 @@ import {
} from "@t3tools/client-runtime/state/thread-execution";
import { isOrchestrationV2WorkActive } from "@t3tools/contracts";
import { ArrowUpLeftIcon } from "lucide-react";
-import { useLayoutEffect, useRef } from "react";
+import { tickTextContent } from "~/lib/tickTextContent";
import type { ProviderInstanceEntry } from "../../providerInstances";
import { Button } from "../ui/button";
import { ProviderInstanceIcon } from "./ProviderInstanceIcon";
@@ -18,7 +18,6 @@ export function ProviderSubagentBar(props: {
readonly status: ProviderSubagentStatus | null;
readonly onOpenParent: (() => void) | null;
}) {
- const statusRef = useRef<HTMLSpanElement>(null);
const { status } = props;
const live = status !== null && isOrchestrationV2WorkActive(status.status);
const modelDescription =
@@ -28,19 +27,6 @@ export function ProviderSubagentBar(props: {
0,
);
- // Write timer labels to the DOM to avoid chat renders on each tick.
- useLayoutEffect(() => {
- const update = () => {
- if (statusRef.current) {
- statusRef.current.textContent = formatProviderSubagentStatus(status, Date.now());
- }
- };
- update();
- if (!live) return;
- const id = setInterval(update, 1_000);
- return () => clearInterval(id);
- }, [live, status]);
-
// Sized by the composer, not the viewport: a docked side panel narrows the
// chat column on a wide window, and one row there squeezes out the model
// and status, so the status drops to its own line instead.
@@ -67,7 +53,7 @@ export function ProviderSubagentBar(props: {
)}
</span>
<span
- ref={statusRef}
+ ref={tickTextContent((nowMs) => formatProviderSubagentStatus(status, nowMs), live)}
aria-hidden
className="min-w-0 max-w-full truncate text-muted-foreground tabular-nums @max-[560px]/composer-surface:text-xs"
/>
diff --git a/apps/web/src/components/chat/TimelineMinimap.tsx b/apps/web/src/components/chat/TimelineMinimap.tsx
index 773bc14ff7b..4e87edfe594 100644
--- a/apps/web/src/components/chat/TimelineMinimap.tsx
+++ b/apps/web/src/components/chat/TimelineMinimap.tsx
@@ -1,5 +1,5 @@
import { resolveTimelineMinimapPreview, type TimelineMinimapItem } from "./timelineMinimapItems";
-import { useEffect, useRef, useState, type MouseEvent } from "react";
+import { useRef, useState, type MouseEvent } from "react";
import { ChevronDownIcon, ChevronUpIcon } from "lucide-react";
import { Button } from "../ui/button";
import {
@@ -61,11 +61,6 @@ export function TimelineMinimap({
const pressedOnStripRef = useRef(false);
const [passThrough, setPassThrough] = useState(false);
- useEffect(() => {
- if (!passThrough) return;
- return onMouseButtonsReleased(() => setPassThrough(false));
- }, [passThrough]);
-
const resolvedActiveIndex =
activeIndex !== null && activeIndex < items.length ? activeIndex : null;
const activeItem = resolveTimelineMinimapPreview(
@@ -143,7 +138,9 @@ export function TimelineMinimap({
});
}}
onMouseMove={(event) => {
- if (event.buttons !== 0 && !pressedOnStripRef.current) setPassThrough(true);
+ if (event.buttons === 0 || pressedOnStripRef.current || passThrough) return;
+ setPassThrough(true);
+ onMouseButtonsReleased(() => setPassThrough(false));
}}
style={{
height: resolveTimelineMinimapHeightStyle(items.length),
diff --git a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx
index 90e15502e0a..c122caa96f3 100644
--- a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx
+++ b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx
@@ -9,8 +9,9 @@ import { type ToolActivityIcon } from "@t3tools/contracts";
import { liveThoughtLine } from "@t3tools/client-runtime/work-log/presentation";
import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor";
import { observeResize } from "~/lib/observeResize";
+import { tickTextContent } from "~/lib/tickTextContent";
import { observeVisibleAnimation } from "../../lib/visibleAnimation";
-import { memo, use, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
+import { memo, use, useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { LegendList, type LegendListRef } from "@legendapp/list/react";
import { workEntryDisplayIndicatesToolFailure } from "../../session-logic";
import ChatMarkdown from "../ChatMarkdown";
@@ -109,24 +110,11 @@ export const WorkGroupSection = memo(function WorkGroupSection({
});
function WorkingTimer({ createdAt }: { createdAt: string }) {
- const textRef = useRef<HTMLSpanElement>(null);
- const initialText = formatWorkingTimerNow(createdAt);
-
- useEffect(() => {
- const updateText = () => {
- if (textRef.current) {
- textRef.current.textContent = formatWorkingTimerNow(createdAt);
- }
- };
- updateText();
- const id = setInterval(updateText, 1000);
- return () => clearInterval(id);
- }, [createdAt]);
-
return (
- <span ref={textRef} className="tabular-nums">
- {initialText}
- </span>
+ <span
+ ref={tickTextContent(() => formatWorkingTimerNow(createdAt), true)}
+ className="tabular-nums"
+ />
);
}
diff --git a/apps/web/src/components/chat/WorktreeSetupCard.browser.test.tsx b/apps/web/src/components/chat/WorktreeSetupCard.browser.test.tsx
new file mode 100644
index 00000000000..1a34f537efd
--- /dev/null
+++ b/apps/web/src/components/chat/WorktreeSetupCard.browser.test.tsx
@@ -0,0 +1,78 @@
+import { ThreadId, type WorktreeSetupSnapshot } from "@t3tools/contracts";
+import { expect, it, vi } from "vite-plus/test";
+
+import { act, fakeTimers, render } from "../../../test/render";
+import { WorktreeSetupCard } from "./WorktreeSetupCard";
+
+const NOW = new Date("2026-10-26T12:00:10.000Z");
+
+function snapshot(overrides: Partial<WorktreeSetupSnapshot>): WorktreeSetupSnapshot {
+ return {
+ threadId: ThreadId.make("thread-1"),
+ phase: "running",
+ startedAt: "2026-10-26T12:00:00.000Z",
+ endedAt: null,
+ branch: "t3/feature",
+ baseRef: "main",
+ worktreePath: "/repo/.t3/worktrees/feature",
+ setupScript: null,
+ stages: [
+ {
+ id: "fetch",
+ status: "done",
+ startedAt: "2026-10-26T12:00:00.000Z",
+ endedAt: "2026-10-26T12:00:03.000Z",
+ percent: null,
+ detail: null,
+ tail: [],
+ },
+ {
+ id: "checkout",
+ status: "running",
+ startedAt: "2026-10-26T12:00:03.000Z",
+ endedAt: null,
+ percent: null,
+ detail: null,
+ tail: [],
+ },
+ ],
+ error: null,
+ sequence: 1,
+ ...overrides,
+ };
+}
+
+const card = (value: WorktreeSetupSnapshot) => (
+ <WorktreeSetupCard snapshot={value} onCancel={null} onWorkLocally={null} onOpenTerminal={null} />
+);
+
+it("ticks the running stage while finished stages keep their duration", async () => {
+ using _timers = fakeTimers();
+ vi.setSystemTime(NOW);
+ await using screen = await render(card(snapshot({})));
+ // Assert synchronously: expect.element polls on timers these tests fake.
+ const section = screen.getByRole("region", { name: "Worktree setup" });
+
+ expect(section.element().textContent).toContain("Fetch base branch3.0s");
+ expect(section.element().textContent).toContain("Check out files7.0s");
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5_000);
+ });
+ expect(section.element().textContent).toContain("Fetch base branch3.0s");
+ expect(section.element().textContent).toContain("Check out files12s");
+});
+
+it("stops a stage interrupted by the setup ending at the setup's end", async () => {
+ using _timers = fakeTimers();
+ vi.setSystemTime(NOW);
+ const failed = snapshot({ phase: "failed", endedAt: "2026-10-26T12:00:05.000Z" });
+ await using screen = await render(card(failed));
+ const section = screen.getByRole("region", { name: "Worktree setup" });
+
+ expect(section.element().textContent).toContain("Check out files2.0s");
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5_000);
+ });
+ expect(section.element().textContent).toContain("Check out files2.0s");
+});
diff --git a/apps/web/src/components/chat/WorktreeSetupCard.tsx b/apps/web/src/components/chat/WorktreeSetupCard.tsx
index be40305f4c5..2f8f514bed4 100644
--- a/apps/web/src/components/chat/WorktreeSetupCard.tsx
+++ b/apps/web/src/components/chat/WorktreeSetupCard.tsx
@@ -14,7 +14,7 @@ import {
XIcon,
} from "lucide-react";
import { ChevronDown, ChevronRight } from "lucide";
-import { useEffect, useState, type ReactNode } from "react";
+import { useState, type ReactNode } from "react";
import { Button } from "~/components/ui/button";
import { MorphIcon } from "~/components/MorphIcon";
@@ -22,6 +22,7 @@ import { Spinner } from "~/components/ui/spinner";
import { MiddleTruncate } from "../ui/middle-truncate";
import { observeVisibleAnimation } from "~/lib/visibleAnimation";
import { cn } from "~/lib/utils";
+import { useNowSecond } from "~/hooks/useNowSecond";
import { WorkLogRow } from "./WorkLog";
interface WorktreeSetupCardProps {
@@ -31,22 +32,35 @@ interface WorktreeSetupCardProps {
onOpenTerminal: (() => void) | null;
}
-function stageElapsedMs(stage: WorktreeSetupStage, nowMs: number): number | null {
- if (!stage.startedAt) return null;
- const start = Date.parse(stage.startedAt);
- const end = stage.endedAt ? Date.parse(stage.endedAt) : nowMs;
- if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
- return Math.max(0, end - start);
+function elapsedMs(startedAt: string | null, endMs: number): number | null {
+ if (!startedAt) return null;
+ const start = Date.parse(startedAt);
+ if (!Number.isFinite(start) || !Number.isFinite(endMs)) return null;
+ return Math.max(0, endMs - start);
}
-function useNowWhile(active: boolean): number {
- const [nowMs, setNowMs] = useState(() => Date.now());
- useEffect(() => {
- if (!active) return;
- const id = setInterval(() => setNowMs(Date.now()), 1_000);
- return () => clearInterval(id);
- }, [active]);
- return nowMs;
+/** Mounted only while setup runs, so finished setups never subscribe to the tick. */
+function LiveElapsed({ startedAt }: { startedAt: string }) {
+ const elapsed = elapsedMs(startedAt, useNowSecond());
+ return elapsed === null ? null : <>{formatDuration(elapsed)}</>;
+}
+
+/** A finished duration, or a ticking one while setup is still running. */
+function Elapsed({
+ startedAt,
+ endedAt,
+ live,
+}: {
+ startedAt: string | null;
+ endedAt: string | null;
+ live: boolean;
+}) {
+ if (!startedAt) return null;
+ if (endedAt) {
+ const elapsed = elapsedMs(startedAt, Date.parse(endedAt));
+ return elapsed === null ? null : <>{formatDuration(elapsed)}</>;
+ }
+ return live ? <LiveElapsed startedAt={startedAt} /> : null;
}
function StageIcon({ status }: { status: WorktreeSetupStage["status"] }) {
@@ -110,13 +124,7 @@ function headerLabel(snapshot: WorktreeSetupSnapshot): string {
}
}
-function SetupHeaderRow({
- snapshot,
- totalElapsed,
-}: {
- snapshot: WorktreeSetupSnapshot;
- totalElapsed: number | null;
-}) {
+function SetupHeaderRow({ snapshot }: { snapshot: WorktreeSetupSnapshot }) {
const running = snapshot.phase === "running";
const failed = snapshot.phase === "failed";
const finishedWithFailedStage =
@@ -142,11 +150,9 @@ function SetupHeaderRow({
<span className="block truncate">{text}</span>
{running ? <ShimmerOverlay>{text}</ShimmerOverlay> : null}
</span>
- {totalElapsed !== null ? (
- <span className="ml-auto shrink-0 text-xs text-muted-foreground">
- {formatDuration(totalElapsed)}
- </span>
- ) : null}
+ <span className="ml-auto shrink-0 text-xs text-muted-foreground empty:hidden">
+ <Elapsed startedAt={snapshot.startedAt} endedAt={snapshot.endedAt} live={running} />
+ </span>
</div>
</div>
);
@@ -154,14 +160,15 @@ function SetupHeaderRow({
function StageRow({
stage,
- nowMs,
+ setupRunning,
+ setupEndedAt,
scriptName,
}: {
stage: WorktreeSetupStage;
- nowMs: number;
+ setupRunning: boolean;
+ setupEndedAt: string | null;
scriptName: string | null;
}) {
- const elapsed = stageElapsedMs(stage, nowMs);
const label =
stage.id === "setup-script" && scriptName ? scriptName : worktreeSetupStageLabel(stage.id);
const running = stage.status === "running";
@@ -198,9 +205,14 @@ function StageRow({
{trailing}
</span>
) : null}
- {elapsed !== null && stage.status !== "skipped" && stage.status !== "pending" ? (
- <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
- {formatDuration(elapsed)}
+ {stage.status !== "skipped" && stage.status !== "pending" ? (
+ <span className="shrink-0 text-xs text-muted-foreground tabular-nums empty:hidden">
+ <Elapsed
+ startedAt={stage.startedAt}
+ // A stage interrupted by the setup ending stops with it.
+ endedAt={stage.endedAt ?? setupEndedAt}
+ live={setupRunning}
+ />
</span>
) : null}
</>
@@ -272,13 +284,7 @@ function SetupDetails({ snapshot }: { snapshot: WorktreeSetupSnapshot }) {
);
}
-function CollapsedSummaryRow({
- snapshot,
- totalElapsed,
-}: {
- snapshot: WorktreeSetupSnapshot;
- totalElapsed: number | null;
-}) {
+function CollapsedSummaryRow({ snapshot }: { snapshot: WorktreeSetupSnapshot }) {
const status: WorktreeSetupStage["status"] =
snapshot.phase === "failed" || snapshot.phase === "cancelled"
? "failed"
@@ -297,11 +303,9 @@ function CollapsedSummaryRow({
}
label={<span className={stageRowClassName(status)}>{label}</span>}
trailing={
- totalElapsed !== null ? (
- <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
- {formatDuration(totalElapsed)}
- </span>
- ) : null
+ <span className="shrink-0 text-xs text-muted-foreground tabular-nums empty:hidden">
+ <Elapsed startedAt={snapshot.startedAt} endedAt={snapshot.endedAt} live={false} />
+ </span>
}
/>
);
@@ -317,13 +321,7 @@ export function WorktreeSetupCard({
embedded?: boolean;
}) {
const running = snapshot.phase === "running";
- const nowMs = useNowWhile(running);
const [detailsOpen, setDetailsOpen] = useState(false);
- const totalElapsed = (() => {
- const start = Date.parse(snapshot.startedAt);
- const end = snapshot.endedAt ? Date.parse(snapshot.endedAt) : nowMs;
- return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null;
- })();
const setupStage = snapshot.stages.find((stage) => stage.id === "setup-script");
const showTerminal = onOpenTerminal && setupStage && setupStage.status !== "pending";
const collapsed = embedded && !running;
@@ -335,16 +333,17 @@ export function WorktreeSetupCard({
return (
<section aria-label="Worktree setup" data-worktree-setup-phase={snapshot.phase}>
- {showHeader ? <SetupHeaderRow snapshot={snapshot} totalElapsed={totalElapsed} /> : null}
+ {showHeader ? <SetupHeaderRow snapshot={snapshot} /> : null}
{collapsed ? (
- <CollapsedSummaryRow snapshot={snapshot} totalElapsed={totalElapsed} />
+ <CollapsedSummaryRow snapshot={snapshot} />
) : (
<div className={showHeader ? "pt-1.5" : undefined}>
{snapshot.stages.map((stage) => (
<div key={stage.id}>
<StageRow
stage={stage}
- nowMs={nowMs}
+ setupRunning={running}
+ setupEndedAt={snapshot.endedAt}
scriptName={snapshot.setupScript?.name ?? null}
/>
{stage.id === "setup-script" && showTail ? (
diff --git a/apps/web/src/components/chat/useThreadLifecycle.tsx b/apps/web/src/components/chat/useThreadLifecycle.tsx
index d992a11315d..2cab98f8d0e 100644
--- a/apps/web/src/components/chat/useThreadLifecycle.tsx
+++ b/apps/web/src/components/chat/useThreadLifecycle.tsx
@@ -12,6 +12,7 @@ import {
makeThreadErrorSetter,
} from "../ChatView.logic";
import { useStableCallback } from "../../hooks/useStableCallback";
+import { useNowAfter } from "../../hooks/useDeadline";
import type { usePendingThreadRequests } from "./usePendingThreadRequests";
import {
AuthOrchestrationOperateScope,
@@ -32,7 +33,7 @@ import { settleAndAdvance } from "../../settleAndAdvance";
import type { ChatShortcutCommands } from "./useChatShortcuts";
import { resolveThreadLastVisitedAt } from "../Sidebar.logic";
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
-import { type SetStateAction, useEffect, useRef, useState } from "react";
+import { type SetStateAction, useRef, useState } from "react";
import { useNavigate, useRouter } from "@tanstack/react-router";
import {
isAtomCommandInterrupted,
@@ -171,33 +172,15 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
const supportsPinning = serverConfig?.environment.capabilities.threadPinning === true;
const activeThreadPinned = supportsPinning && activeThreadShell?.pinnedAt != null;
- // The compiler caches render results on their inputs, so a clock read in render
- // stays frozen until the shell changes. The clock is state: reset with the shell,
- // and moved by the wake timer.
- const [snoozeClockState, setSnoozeClockState] = useState(() => ({
- shell: activeThreadShell,
- now: new Date().toISOString(),
- }));
- if (snoozeClockState.shell !== activeThreadShell) {
- // oxlint-disable-next-line react/purity -- Reseeds the snooze clock only in the render-phase adjustment that runs when the shell changes.
- setSnoozeClockState({ shell: activeThreadShell, now: new Date().toISOString() });
- }
- const snoozeClock = snoozeClockState.now;
+ // A clock read in render would stay frozen in the compiler's cache, so the
+ // snooze checks read a snapshot that moves when the wake time changes or passes.
+ const snoozeClock = new Date(
+ useNowAfter(Date.parse(activeThreadShell?.snoozedUntil ?? "") || null),
+ ).toISOString();
const activeThreadSnoozed =
activeThreadShell !== null &&
supportsSnooze &&
effectiveSnoozed(activeThreadShell, { now: snoozeClock });
- useEffect(() => {
- if (!activeThreadSnoozed) return;
- const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? "");
- if (!Number.isFinite(wakeAtMs)) return;
- const id = window.setTimeout(
- () => setSnoozeClockState((clock) => ({ ...clock, now: new Date().toISOString() })),
- Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647),
- );
- return () => window.clearTimeout(id);
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A clock that lands before the wake time (timer clamping, clock skew) re-arms the timer.
- }, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeClock]);
const activeThreadWokeAt =
activeThreadShell !== null && supportsSnooze
? threadWokeAt(activeThreadShell, { now: snoozeClock })
diff --git a/apps/web/src/hooks/useDeadline.browser.test.tsx b/apps/web/src/hooks/useDeadline.browser.test.tsx
new file mode 100644
index 00000000000..f261af96f3b
--- /dev/null
+++ b/apps/web/src/hooks/useDeadline.browser.test.tsx
@@ -0,0 +1,25 @@
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import { act, fakeTimers, render } from "../../test/render";
+import { useNowAfter } from "./useDeadline";
+
+function Probe(props: { deadlineMs: number }) {
+ const nowMs = useNowAfter(props.deadlineMs);
+ return <output>{nowMs >= props.deadlineMs ? "passed" : "pending"}</output>;
+}
+
+describe("useNowAfter", () => {
+ it("reads a fresh clock when a later deadline passes", async () => {
+ // The first render reads the clock.
+ using _timers = fakeTimers({ now: 0 });
+ await using screen = await render(<Probe deadlineMs={1_000} />, {
+ // A bare hook probe; nothing here navigates.
+ router: false,
+ });
+ await screen.rerender(<Probe deadlineMs={2_000} />);
+ await expect.element(screen.getByText("pending")).toBeInTheDocument();
+
+ await act(() => vi.advanceTimersByTime(2_000));
+ await expect.element(screen.getByText("passed")).toBeInTheDocument();
+ });
+});
diff --git a/apps/web/src/hooks/useDeadline.ts b/apps/web/src/hooks/useDeadline.ts
index 47227cda2d8..71634d67cd6 100644
--- a/apps/web/src/hooks/useDeadline.ts
+++ b/apps/web/src/hooks/useDeadline.ts
@@ -1,8 +1,23 @@
import { deadlineStore } from "@t3tools/client-runtime/clock";
-import { useSyncExternalStore } from "react";
+import { useState, useSyncExternalStore } from "react";
/** Re-renders once when `deadlineMs` (epoch ms) is reached; `null` never passes. */
export function useDeadlinePassed(deadlineMs: number | null): boolean {
const store = deadlineStore(deadlineMs);
return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
}
+
+/**
+ * `Date.now()` captured at mount and re-read when `deadlineMs` changes or
+ * passes, so comparisons against the deadline flip exactly once.
+ */
+export function useNowAfter(deadlineMs: number | null): number {
+ const passed = useDeadlinePassed(deadlineMs);
+ const readNow = () => ({ deadlineMs, passed, nowMs: Date.now() });
+ const [snapshot, setSnapshot] = useState(readNow);
+ // The clock is read inside the updater: the compiler caches a bare
+ // `Date.now()` in render once per instance, so a later adjustment would reuse
+ // the first reading. React discards this render and re-runs with the update.
+ if (snapshot.deadlineMs !== deadlineMs || snapshot.passed !== passed) setSnapshot(readNow);
+ return snapshot.nowMs;
+}
diff --git a/apps/web/src/lib/tickTextContent.ts b/apps/web/src/lib/tickTextContent.ts
new file mode 100644
index 00000000000..c587acf9df1
--- /dev/null
+++ b/apps/web/src/lib/tickTextContent.ts
@@ -0,0 +1,18 @@
+import { secondTick } from "@t3tools/client-runtime/clock";
+
+/**
+ * Ref callback that writes `format(Date.now())` into a node and, while `live`,
+ * rewrites it on the shared second tick. Running timers update through the DOM
+ * so a ticking label never re-renders the timeline or composer around it.
+ */
+export function tickTextContent(format: (nowMs: number) => string, live: boolean) {
+ return (node: HTMLElement | null) => {
+ if (!node) return;
+ const write = () => {
+ const text = format(Date.now());
+ if (node.textContent !== text) node.textContent = text;
+ };
+ write();
+ return live ? secondTick.subscribe(write) : undefined;
+ };
+}