Skip to content
TypeScript

refactor(mobile): thread visits are tracked outside React (#24973)

Julius Marminged99776351c20
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
index 708b1d2aa76..1111eddc860 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -6,9 +6,11 @@ import {
settlePromise,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
-import { AsyncResult } from "effect/reactivity";
+import { AsyncResult, Atom } from "effect/reactivity";
import * as Dialog from "../../components/ui/Dialog";
-import { useAtomValue } from "@effect/atom-react";
+import { useAtomMount, useAtomValue } from "@effect/atom-react";
+import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entities";
+import { createThreadVisitTracker } from "@t3tools/client-runtime/state/thread-visits";
import {
useChildThreadInputs,
useThreadReportedModelSelection,
@@ -142,7 +144,6 @@ import { ThreadBrowserFloat } from "../browser/ThreadBrowserFloat";
import { useThreadServerBrowserTabs } from "../../state/preview";
import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
import { scopedThreadKey } from "../../lib/scopedEntities";
-import { claimThreadOpen } from "@t3tools/client-runtime/state/thread-search";
import {
finishThreadMessageJump,
pendingThreadMessageJump,
@@ -152,7 +153,7 @@ import {
clearThreadComposerError,
threadComposerErrorsAtom,
} from "../../state/thread-composer-error";
-import { threadEnvironment } from "../../state/threads";
+import { environmentThreadShells, threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import { useDelayedStatus } from "../../lib/useDelayedStatus";
import type {
@@ -380,125 +381,32 @@ const USER_INPUT_TOGGLE_TIMING = {
easing: Easing.out(Easing.cubic),
};
-// The visit watermark follows the shell's updatedAt, which ticks while a run
-// streams. Keeping it in a leaf lets the screen read the quiet shell.
-function ThreadVisitWatermark(props: {
- readonly environmentId: EnvironmentId;
- readonly selectedThread: EnvironmentThreadShell;
- readonly showContent: boolean;
-}) {
- const liveThread = useThreadShell({
- environmentId: props.environmentId,
- threadId: props.selectedThread.id,
- });
- const thread = liveThread ?? props.selectedThread;
- const showContent = props.showContent;
- const selectedThreadKey = scopedThreadKey(props.environmentId, thread.id);
- const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
- const lastDispatchedVisitRef = useRef<string | null>(null);
- const lastVisitDispatchRef = useRef({ threadKey: selectedThreadKey, at: 0 });
- const selectedThreadId = thread.id;
- const snoozedUntil = thread.snoozedUntil;
- // Keep the clock in state so React Compiler invalidates the wake calculation.
- const [wakeNow, setWakeNow] = useState(() => new Date().toISOString());
- useEffect(() => {
- if (!showContent || snoozedUntil == null) return;
- const delay = Date.parse(snoozedUntil) - Date.now();
- if (!Number.isFinite(delay)) return;
- const timer = setTimeout(() => setWakeNow(new Date().toISOString()), Math.max(0, delay) + 50);
- return () => clearTimeout(timer);
- }, [showContent, snoozedUntil]);
- const selectedThreadWokeAt = threadWokeAt(thread, {
- now: wakeNow,
- });
- // A scheduled wake can happen without a newer server update.
- const selectedThreadUpdatedAt =
- selectedThreadWokeAt !== null && Date.parse(selectedThreadWokeAt) > Date.parse(thread.updatedAt)
- ? selectedThreadWokeAt
- : thread.updatedAt;
- const wakeIsLatestUpdate = selectedThreadUpdatedAt === selectedThreadWokeAt;
- const selectedThreadLastVisitedAt = thread.lastVisitedAt;
- const selectedThreadCompletedAt = thread.latestRun?.completedAt;
- // Opening a thread is one visit that also counts toward search ranking; a
- // palette pick already sent it with the query. The watermark effect below
- // skips it.
- const recordedOpenRef = useRef<string | null>(null);
- useEffect(() => {
- if (!showContent) return;
- if (recordedOpenRef.current === selectedThreadKey) return;
- recordedOpenRef.current = selectedThreadKey;
- // Recorded here even when the server cannot take opens, so recents follow it.
- const claimed = claimThreadOpen(props.environmentId, selectedThreadId, Date.now());
- if (!claimed || selectedThreadLastVisitedAt === undefined) return;
- lastDispatchedVisitRef.current = `${selectedThreadKey}:${selectedThreadUpdatedAt}`;
- lastVisitDispatchRef.current = { threadKey: selectedThreadKey, at: Date.now() };
- void visitThread({
- environmentId: props.environmentId,
- input: {
- threadId: selectedThreadId,
- visitedAt: selectedThreadUpdatedAt,
- opened: true,
- },
- });
- }, [
- props.environmentId,
- selectedThreadId,
- selectedThreadKey,
- selectedThreadLastVisitedAt,
- selectedThreadUpdatedAt,
- showContent,
- visitThread,
- ]);
- useEffect(() => {
- if (!showContent || selectedThreadLastVisitedAt === undefined) return;
- const threadUpdatedAtMs = Date.parse(selectedThreadUpdatedAt);
- if (Number.isNaN(threadUpdatedAtMs)) return;
- const lastVisitedAtMs = selectedThreadLastVisitedAt
- ? Date.parse(selectedThreadLastVisitedAt)
- : NaN;
- if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= threadUpdatedAtMs) return;
- const dispatchKey = `${selectedThreadKey}:${selectedThreadUpdatedAt}`;
- if (lastDispatchedVisitRef.current === dispatchKey) return;
- const dispatch = () => {
- lastDispatchedVisitRef.current = dispatchKey;
- lastVisitDispatchRef.current = { threadKey: selectedThreadKey, at: Date.now() };
- void visitThread({
- environmentId: props.environmentId,
- input: { threadId: selectedThreadId, visitedAt: selectedThreadUpdatedAt },
- });
- };
- const completedAtMs = selectedThreadCompletedAt ? Date.parse(selectedThreadCompletedAt) : NaN;
- const hasUnseenCompletion =
- !Number.isNaN(completedAtMs) &&
- (Number.isNaN(lastVisitedAtMs) || completedAtMs > lastVisitedAtMs);
- const previous = lastVisitDispatchRef.current;
- const elapsed = Date.now() - previous.at;
- // Like a completion, a wake the user is looking at must not wait out the throttle:
- // leaving within it would cancel the dispatch and keep Woke in the list.
- if (
- previous.threadKey !== selectedThreadKey ||
- hasUnseenCompletion ||
- wakeIsLatestUpdate ||
- elapsed >= 10_000
- ) {
- dispatch();
- return;
+// A scheduled wake can happen without a newer server update, so the tracker
+// is told when one takes effect. The shell's updatedAt ticks while a run
+// streams; the tracker follows it outside React.
+const wakeAwareVisitShell = Atom.family((key: string) => {
+ const ref = parseThreadKey(key);
+ return Atom.make((get) => {
+ const shell = get(environmentThreadShells.threadShellAtom(ref));
+ if (shell === null) return null;
+ const nowMs = Date.now();
+ const wokeAt = threadWokeAt(shell, { now: new Date(nowMs).toISOString() });
+ const wakeAtMs = shell.snoozedUntil == null ? NaN : Date.parse(shell.snoozedUntil);
+ if (wokeAt === null && wakeAtMs > nowMs) {
+ const timer = setTimeout(
+ () => get.refreshSelf(),
+ Math.min(wakeAtMs - nowMs + 50, 2_147_483_647),
+ );
+ get.addFinalizer(() => clearTimeout(timer));
}
- const timer = setTimeout(dispatch, 10_000 - elapsed);
- return () => clearTimeout(timer);
- }, [
- props.environmentId,
- selectedThreadId,
- selectedThreadKey,
- selectedThreadLastVisitedAt,
- selectedThreadCompletedAt,
- selectedThreadUpdatedAt,
- showContent,
- visitThread,
- wakeIsLatestUpdate,
- ]);
- return null;
-}
+ return { ...shell, wokeAt };
+ }).pipe(Atom.withLabel(`mobile-thread-visit-shell:${key}`));
+});
+
+const threadVisitTracker = createThreadVisitTracker({
+ threadShellAtom: (ref) => wakeAwareVisitShell(threadKey(ref)),
+ visit: threadEnvironment.visit,
+});
// Past the composer's 180 ms height animation.
const COMPOSER_HEIGHT_SETTLE_MS = 220;
@@ -1171,6 +1079,14 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
userInputInsetProgress.set(1);
}, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
const showContent = props.showContent ?? true;
+ // Showing the thread counts as viewing it, before its live shell arrives too.
+ useAtomMount(
+ threadVisitTracker(
+ showContent && !props.draftMode
+ ? { environmentId: props.environmentId, threadId: props.selectedThread.id }
+ : null,
+ ),
+ );
const layoutVariant = props.layoutVariant ?? "compact";
const isSplitLayout = layoutVariant === "split";
const contentMaxWidth =
@@ -1439,11 +1355,6 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
return (
<View className="flex-1" onLayout={handleScreenLayout}>
{!usesNativeWorkspaceColumns ? <NativeLayoutObserver onChange={setScreenMetrics} /> : null}
- <ThreadVisitWatermark
- environmentId={props.environmentId}
- selectedThread={props.selectedThread}
- showContent={showContent && !props.draftMode}
- />
{props.draftMode ? (
props.draftMode.content(
navigationHeaderHeight,
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index a58a39bc345..c6028a2832f 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -335,6 +335,10 @@
"types": "./src/state/threadSearch.ts",
"default": "./src/state/threadSearch.ts"
},
+ "./state/thread-visits": {
+ "types": "./src/state/threadVisits.ts",
+ "default": "./src/state/threadVisits.ts"
+ },
"./state/turn-item-presentation": {
"types": "./src/state/turnItemPresentation.ts",
"default": "./src/state/turnItemPresentation.ts"
diff --git a/packages/client-runtime/src/state/threadVisits.test.ts b/packages/client-runtime/src/state/threadVisits.test.ts
new file mode 100644
index 00000000000..98252a12a3a
--- /dev/null
+++ b/packages/client-runtime/src/state/threadVisits.test.ts
@@ -0,0 +1,151 @@
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
+import { expect, it, vi } from "vite-plus/test";
+
+import type { VisitThreadInput } from "./threadCommands.ts";
+import { claimThreadOpen } from "./threadSearch.ts";
+import { createThreadVisitTracker, VISIT_DISPATCH_THROTTLE_MS } from "./threadVisits.ts";
+
+const environmentId = EnvironmentId.make("env-visits");
+
+interface Shell {
+ readonly environmentId: EnvironmentId;
+ readonly id: ThreadId;
+ readonly updatedAt: string;
+ readonly lastVisitedAt?: string | null;
+ readonly latestRun: { readonly completedAt: string | null } | null;
+ readonly wokeAt?: string | null;
+}
+
+function at(seconds: number) {
+ return `2026-01-01T00:00:${String(seconds).padStart(2, "0")}.000Z`;
+}
+
+// claimThreadOpen dedupes per thread in module state, so each test opens its own thread.
+function setup(threadName: string, initial: Omit<Shell, "environmentId" | "id"> | null) {
+ vi.useFakeTimers({ now: Date.UTC(2026, 0, 1) });
+ const threadId = ThreadId.make(threadName);
+ const ref = { environmentId, threadId };
+ const shellAtom = Atom.make<Shell | null>(
+ initial === null ? null : { environmentId, id: threadId, ...initial },
+ );
+ const visits: Array<VisitThreadInput> = [];
+ const localVisits: Array<string> = [];
+ const tracker = createThreadVisitTracker({
+ threadShellAtom: () => shellAtom,
+ visit: {
+ label: "test-visit",
+ run: async (_registry, value) => {
+ visits.push(value.input);
+ return AsyncResult.success(undefined);
+ },
+ },
+ markLocalVisit: (_ref, visitedAt) => localVisits.push(visitedAt),
+ });
+ const registry = AtomRegistry.make();
+ return {
+ ref,
+ visits,
+ localVisits,
+ mount: () => registry.mount(tracker(ref)),
+ update: (patch: Partial<Shell>) => {
+ const current = registry.get(shellAtom);
+ registry.set(shellAtom, {
+ environmentId,
+ id: threadId,
+ updatedAt: at(0),
+ latestRun: null,
+ ...current,
+ ...patch,
+ });
+ },
+ [Symbol.dispose]: () => vi.useRealTimers(),
+ };
+}
+
+it("records the open once, then throttles streaming visits", () => {
+ using t = setup("thread-throttle", {
+ updatedAt: at(10),
+ lastVisitedAt: at(0),
+ latestRun: null,
+ });
+ t.mount();
+ expect(t.visits).toEqual([{ threadId: t.ref.threadId, visitedAt: at(10), opened: true }]);
+
+ vi.advanceTimersByTime(1_000);
+ t.update({ updatedAt: at(11) });
+ t.update({ updatedAt: at(12) });
+ expect(t.visits).toHaveLength(1);
+
+ vi.advanceTimersByTime(VISIT_DISPATCH_THROTTLE_MS - 1_000);
+ expect(t.visits.slice(1)).toEqual([{ threadId: t.ref.threadId, visitedAt: at(12) }]);
+});
+
+it("sends an unseen completion without waiting for the throttle", () => {
+ using t = setup("thread-completion", {
+ updatedAt: at(10),
+ lastVisitedAt: at(0),
+ latestRun: null,
+ });
+ t.mount();
+ t.update({ updatedAt: at(20), latestRun: { completedAt: at(20) } });
+ expect(t.visits.slice(1)).toEqual([{ threadId: t.ref.threadId, visitedAt: at(20) }]);
+});
+
+it("does not resend the open a palette pick already sent", () => {
+ using t = setup("thread-palette", { updatedAt: at(10), lastVisitedAt: at(0), latestRun: null });
+ claimThreadOpen(environmentId, t.ref.threadId, Date.UTC(2026, 0, 1));
+ t.mount();
+ expect(t.visits).toEqual([{ threadId: t.ref.threadId, visitedAt: at(10) }]);
+});
+
+it("keeps a mark-unread on the open thread until new activity lands", () => {
+ using t = setup("thread-unread", { updatedAt: at(10), lastVisitedAt: at(0), latestRun: null });
+ t.mount();
+ t.update({ lastVisitedAt: at(10) });
+ t.update({ lastVisitedAt: at(5) });
+ vi.advanceTimersByTime(VISIT_DISPATCH_THROTTLE_MS);
+ expect(t.visits).toHaveLength(1);
+
+ t.update({ updatedAt: at(30) });
+ expect(t.visits.slice(1)).toEqual([{ threadId: t.ref.threadId, visitedAt: at(30) }]);
+});
+
+it("waits for the shell and records local visits for servers without tracking", () => {
+ using t = setup("thread-local", null);
+ t.mount();
+ expect(t.visits).toEqual([]);
+ t.update({ updatedAt: at(10), latestRun: null });
+ t.update({ updatedAt: at(11) });
+ expect(t.visits).toEqual([]);
+ expect(t.localVisits).toEqual([at(10), at(11)]);
+});
+
+it("drops a pending visit when the thread is no longer viewed", () => {
+ using t = setup("thread-unmount", { updatedAt: at(10), lastVisitedAt: at(0), latestRun: null });
+ const unmount = t.mount();
+ t.update({ updatedAt: at(11) });
+ unmount();
+ vi.advanceTimersByTime(VISIT_DISPATCH_THROTTLE_MS);
+ expect(t.visits).toHaveLength(1);
+});
+
+it("records the open while the thread is shown before its shell arrives", () => {
+ using t = setup("thread-shell-missing", null);
+ t.mount();
+ expect(claimThreadOpen(environmentId, t.ref.threadId, Date.UTC(2026, 0, 1))).toBe(false);
+
+ t.update({ updatedAt: at(10), lastVisitedAt: at(0), latestRun: null });
+ expect(t.visits).toEqual([{ threadId: t.ref.threadId, visitedAt: at(10) }]);
+});
+
+it("advances the watermark to a wake without waiting for the throttle", () => {
+ using t = setup("thread-wake", { updatedAt: at(10), lastVisitedAt: at(0), latestRun: null });
+ t.mount();
+ t.update({ wokeAt: at(15) });
+ expect(t.visits.slice(1)).toEqual([{ threadId: t.ref.threadId, visitedAt: at(15) }]);
+
+ vi.advanceTimersByTime(1_000);
+ t.update({ updatedAt: at(16) });
+ expect(t.visits).toHaveLength(2);
+});
diff --git a/packages/client-runtime/src/state/threadVisits.ts b/packages/client-runtime/src/state/threadVisits.ts
new file mode 100644
index 00000000000..4185b982e18
--- /dev/null
+++ b/packages/client-runtime/src/state/threadVisits.ts
@@ -0,0 +1,144 @@
+// @effect-diagnostics globalTimers:off globalDate:off - The tracker runs in atom subscriptions, outside an Effect runtime.
+import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
+import { Atom } from "effect/reactivity";
+
+import { parseThreadKey, threadKey } from "./entities.ts";
+import { type AtomCommand, runAtomCommand } from "./runtime.ts";
+import { claimThreadOpen } from "./threadSearch.ts";
+import type { VisitThreadInput } from "./threadCommands.ts";
+
+// During an active turn the thread's updatedAt advances several times per
+// second, and every server-side visit is a full command dispatch plus a
+// broadcast to all shell subscribers.
+export const VISIT_DISPATCH_THROTTLE_MS = 10_000;
+
+const IDLE_TRACKER: Atom.Atom<void> = Atom.make(undefined).pipe(
+ Atom.withLabel("thread-visit-tracker:idle"),
+);
+
+interface VisitedShell {
+ readonly environmentId: EnvironmentId;
+ readonly id: ThreadId;
+ readonly updatedAt: string;
+ readonly lastVisitedAt?: string | null | undefined;
+ readonly latestRun: { readonly completedAt: string | null } | null;
+ /**
+ * When a scheduled wake the user is looking at took effect. A wake later
+ * than `updatedAt` is an update the server never sent, so the watermark
+ * advances to it, and at once: leaving within the throttle would cancel
+ * the dispatch and keep the thread marked Woke.
+ */
+ readonly wokeAt?: string | null | undefined;
+}
+
+export interface ThreadVisitTrackerOptions {
+ readonly threadShellAtom: (ref: ScopedThreadRef) => Atom.Atom<VisitedShell | null>;
+ readonly visit: AtomCommand<
+ { readonly environmentId: EnvironmentId; readonly input: VisitThreadInput },
+ unknown,
+ unknown
+ >;
+ /**
+ * Servers without visit tracking leave `lastVisitedAt` undefined; a client
+ * that keeps its own watermark for them records the visit here instead.
+ */
+ readonly markLocalVisit?: (ref: ScopedThreadRef, visitedAt: string) => void;
+}
+
+/**
+ * While mounted, a tracker counts as the user viewing the thread: mounting it
+ * records one open (which also feeds search ranking), and every shell update
+ * after that advances the visit watermark, throttled while a run streams.
+ */
+export function createThreadVisitTracker(options: ThreadVisitTrackerOptions) {
+ const family = Atom.family((key: string) => {
+ const ref = parseThreadKey(key);
+ return Atom.make((get) => {
+ const registry = get.registry;
+ // Showing the thread is the open, whether or not its shell has arrived;
+ // the shell only decides whether the server hears about it now.
+ // Recorded even when the server cannot take opens, so recents follow
+ // it. A palette pick already sent the open with its query.
+ let openPending = claimThreadOpen(ref.environmentId, ref.threadId, Date.now());
+ // Dedupe per watermark: the shell updates again before the command's echo
+ // lands. It also keeps a mark-unread on the open thread sticky, since the
+ // rewind leaves updatedAt untouched.
+ let lastDispatchedUpdatedAt: string | null = null;
+ let lastDispatchAt = 0;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const clearTimer = () => {
+ if (timer === undefined) return;
+ clearTimeout(timer);
+ timer = undefined;
+ };
+ get.addFinalizer(clearTimer);
+
+ const dispatch = (shell: VisitedShell, visitedAt: string, opened: boolean) => {
+ clearTimer();
+ lastDispatchedUpdatedAt = visitedAt;
+ lastDispatchAt = Date.now();
+ void runAtomCommand(
+ registry,
+ options.visit,
+ {
+ environmentId: shell.environmentId,
+ input: {
+ threadId: shell.id,
+ visitedAt,
+ ...(opened ? { opened: true } : {}),
+ },
+ },
+ { reportFailure: false },
+ );
+ };
+
+ const onShell = (shell: VisitedShell | null) => {
+ clearTimer();
+ // Only a shell present when the thread is shown carries the open; one
+ // that arrives later is an ordinary visit.
+ const opened = openPending;
+ openPending = false;
+ if (shell === null) return;
+
+ const shellUpdatedAtMs = Date.parse(shell.updatedAt);
+ if (Number.isNaN(shellUpdatedAtMs)) return;
+ const wokeAtMs = shell.wokeAt ? Date.parse(shell.wokeAt) : NaN;
+ const wakeIsLatest = wokeAtMs > shellUpdatedAtMs;
+ const visitedAt = wakeIsLatest && shell.wokeAt ? shell.wokeAt : shell.updatedAt;
+ const updatedAtMs = wakeIsLatest ? wokeAtMs : shellUpdatedAtMs;
+ if (shell.lastVisitedAt === undefined) {
+ options.markLocalVisit?.(ref, visitedAt);
+ return;
+ }
+ if (opened) {
+ dispatch(shell, visitedAt, true);
+ return;
+ }
+ const lastVisitedAtMs = shell.lastVisitedAt ? Date.parse(shell.lastVisitedAt) : NaN;
+ if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= updatedAtMs) return;
+ if (lastDispatchedUpdatedAt === visitedAt) return;
+
+ const completedAtMs = shell.latestRun?.completedAt
+ ? Date.parse(shell.latestRun.completedAt)
+ : NaN;
+ const hasUnseenCompletion =
+ !Number.isNaN(completedAtMs) &&
+ (Number.isNaN(lastVisitedAtMs) || completedAtMs > lastVisitedAtMs);
+ const elapsed = Date.now() - lastDispatchAt;
+ if (hasUnseenCompletion || wakeIsLatest || elapsed >= VISIT_DISPATCH_THROTTLE_MS) {
+ dispatch(shell, visitedAt, false);
+ return;
+ }
+ timer = setTimeout(
+ () => dispatch(shell, visitedAt, false),
+ VISIT_DISPATCH_THROTTLE_MS - elapsed,
+ );
+ };
+
+ // `subscribe`, not `get`: a rebuild would reset the open and throttle
+ // state on every streaming tick.
+ get.subscribe(options.threadShellAtom(ref), onShell, { immediate: true });
+ }).pipe(Atom.withLabel(`thread-visit-tracker:${key}`));
+ });
+ return (ref: ScopedThreadRef | null) => (ref === null ? IDLE_TRACKER : family(threadKey(ref)));
+}