diff --git a/apps/web/src/hooks/useInboxThreads.ts b/apps/web/src/hooks/useInboxThreads.ts index b86260697..0cd291283 100644 --- a/apps/web/src/hooks/useInboxThreads.ts +++ b/apps/web/src/hooks/useInboxThreads.ts @@ -44,12 +44,14 @@ import { import type { Project, SidebarThreadSummary } from "../types"; import { leadThreadKeysOf } from "../leadChat"; import { useUiStateStore } from "../uiStateStore"; -import { useRelativeTimeTick } from "./useRelativeTimeTick"; import { useSettings } from "./useSettings"; +import { useSharedTimeTick } from "./useSharedTimeTick"; import { useSidebarProjectSnapshots } from "./useSidebarProjectSnapshots"; // The queued-turn grace window is measured in minutes, so a coarse clock is // enough to keep "can this be marked done" honest without re-rendering often. +// It is shared: the sidebar, the family tabs and the rest file threads at the +// same moment, so a child that leaves its family leaves everywhere at once. const INBOX_CLOCK_INTERVAL_MS = 30_000; /** One inbox row's thread, filed and labelled the way the sidebar draws it. */ @@ -144,7 +146,7 @@ export function useInboxThreads(): InboxThreads { const wrapUpOnPullRequestSettled = useSettings((s) => s.wrapUpThreadsOnPullRequestSettled); const wrapUpChildThreadsOnFinish = useSettings((s) => s.wrapUpChildThreadsOnFinish); const wrapUpIdleThreads = useSettings((s) => s.wrapUpIdleThreads); - const nowMs = useRelativeTimeTick(INBOX_CLOCK_INTERVAL_MS); + const nowMs = useSharedTimeTick(INBOX_CLOCK_INTERVAL_MS); const nowIso = useMemo(() => new Date(nowMs).toISOString(), [nowMs]); const physicalToLogicalKey = useMemo( diff --git a/apps/web/src/hooks/useRelativeTimeTick.ts b/apps/web/src/hooks/useRelativeTimeTick.ts index bdc57546a..9ceac91ad 100644 --- a/apps/web/src/hooks/useRelativeTimeTick.ts +++ b/apps/web/src/hooks/useRelativeTimeTick.ts @@ -1,6 +1,10 @@ import { useEffect, useState } from "react"; -/** Re-render every `intervalMs`; return a stable timestamp snapshot for render-time relative labels. */ +/** + * Re-render every `intervalMs`; return a stable timestamp snapshot for render-time relative labels. + * Each caller keeps its own clock, fresh when it mounts. Views that must agree on the time use + * `useSharedTimeTick`. + */ export function useRelativeTimeTick(intervalMs = 1_000) { const [nowMs, setNowMs] = useState(() => Date.now()); useEffect(() => { diff --git a/apps/web/src/hooks/useSharedTimeTick.test.ts b/apps/web/src/hooks/useSharedTimeTick.test.ts new file mode 100644 index 000000000..f4d1b1871 --- /dev/null +++ b/apps/web/src/hooks/useSharedTimeTick.test.ts @@ -0,0 +1,58 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; + +import { sharedClock } from "./useSharedTimeTick"; + +describe("sharedClock", () => { + beforeEach(() => { + vi.useFakeTimers({ now: 1_000_000 }); + }); + afterEach(() => { + vi.useRealTimers(); + }); + + it("gives a reader that starts mid-interval the same time as one already reading, and ticks them together", () => { + const clock = sharedClock(30_001); + const first = vi.fn(); + const stopFirst = clock.subscribe(first); + const startedAt = clock.getSnapshot(); + + vi.advanceTimersByTime(20_000); + const second = vi.fn(); + const stopSecond = clock.subscribe(second); + expect(clock.getSnapshot()).toBe(startedAt); + + vi.advanceTimersByTime(10_001); + expect(first).toHaveBeenCalledTimes(1); + expect(second).toHaveBeenCalledTimes(1); + expect(clock.getSnapshot()).toBe(startedAt + 30_001); + stopFirst(); + stopSecond(); + }); + + it("stops ticking when nobody reads it, and never hands out a time older than one interval", () => { + const clock = sharedClock(30_002); + const reader = vi.fn(); + clock.subscribe(reader)(); + + vi.advanceTimersByTime(120_000); + expect(reader).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(0); + expect(clock.getSnapshot()).toBe(Date.now()); + }); + + it("catches up a late tick for every reader at the first read", async () => { + const clock = sharedClock(30_003); + const first = vi.fn(); + const second = vi.fn(); + const stopFirst = clock.subscribe(first); + const stopSecond = clock.subscribe(second); + // A sleeping computer: the clock moves on but the timer hasn't run. + vi.setSystemTime(Date.now() + 120_000); + expect(clock.getSnapshot()).toBe(Date.now()); + await Promise.resolve(); + expect(first).toHaveBeenCalledTimes(1); + expect(second).toHaveBeenCalledTimes(1); + stopFirst(); + stopSecond(); + }); +}); diff --git a/apps/web/src/hooks/useSharedTimeTick.ts b/apps/web/src/hooks/useSharedTimeTick.ts new file mode 100644 index 000000000..65def1f8d --- /dev/null +++ b/apps/web/src/hooks/useSharedTimeTick.ts @@ -0,0 +1,75 @@ +import { useSyncExternalStore } from "react"; + +/** + * One clock per interval that every caller reads together. Use it where two + * views decide the same thing from the time and must agree, like the sidebar + * and the family tabs filing threads (`useInboxThreads`). A label that only + * shows its own age wants `useRelativeTimeTick` instead, which starts fresh + * when it mounts. + * + * It ticks only while something reads it, and its time is never older than + * one interval: a caller that mounts after a quiet spell gets the time now. + */ +export interface SharedClock { + readonly subscribe: (onTick: () => void) => () => void; + readonly getSnapshot: () => number; +} + +const clocks = new Map(); + +export function sharedClock(intervalMs: number): SharedClock { + const existing = clocks.get(intervalMs); + if (existing !== undefined) return existing; + let nowMs = Date.now(); + let timer: ReturnType | null = null; + const listeners = new Set<() => void>(); + const notify = () => { + for (const listener of listeners) listener(); + }; + // Each tick lands one interval after the last reading, so no reading outlives it. + const schedule = () => { + timer = setTimeout( + () => { + nowMs = Date.now(); + schedule(); + notify(); + }, + Math.max(0, nowMs + intervalMs - Date.now()), + ); + }; + const clock: SharedClock = { + subscribe: (onTick) => { + listeners.add(onTick); + if (timer === null) schedule(); + return () => { + listeners.delete(onTick); + if (listeners.size === 0 && timer !== null) { + clearTimeout(timer); + timer = null; + } + }; + }, + getSnapshot: () => { + // Too old to share: nothing kept it ticking, or its tick is late (a sleeping computer, + // a background tab). Read the time now; a ticking clock tells every reader after this + // render, and restarts its interval from here. + if (Date.now() - nowMs >= intervalMs) { + nowMs = Date.now(); + if (timer !== null) { + clearTimeout(timer); + schedule(); + queueMicrotask(notify); + } + } + return nowMs; + }, + }; + clocks.set(intervalMs, clock); + return clock; +} + +/** The shared clock's time for `intervalMs`, re-rendering on each tick. */ +export function useSharedTimeTick(intervalMs: number): number { + const clock = sharedClock(intervalMs); + return useSyncExternalStore(clock.subscribe, clock.getSnapshot); +}