Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadVisitWatermark.tsx

117 lines5.0 KB

1import { type ScopedThreadRef } from "@t3tools/contracts";
2import { resolveThreadLastVisitedAt } from "../Sidebar.logic";
3import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
4import { claimThreadOpen } from "@t3tools/client-runtime/state/thread-search";
5import { useEffect, useRef } from "react";
6import { useUiStateStore } from "../../uiStateStore";
7import { threadEnvironment } from "../../state/threads";
8import { useThreadShell } from "../../state/entities";
9import { useAtomCommand } from "../../state/use-atom-command";
10​
11// During an active turn the thread's updatedAt advances several times per
12// second, and every server-side visit is a full command dispatch plus a
13// broadcast to all shell subscribers.
14const VISIT_DISPATCH_THROTTLE_MS = 10_000;
15​
16// The visit watermark is the one part of the chat view that follows the
17// shell's updatedAt, which ticks while a run streams. Keeping it in a leaf lets
18// ChatView read the quiet shell.
19export function ThreadVisitWatermark(props: { readonly threadRef: ScopedThreadRef }) {
20 const serverThread = useThreadShell(props.threadRef);
21 const threadKey = scopedThreadKey(props.threadRef);
22 const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
23 const activeThreadLocalLastVisitedAt = useUiStateStore(
24 (store) => store.threadLastVisitedAtById[threadKey],
25 );
26 const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
27 const lastDispatchedVisitRef = useRef<string | null>(null);
28 const lastVisitDispatchAtRef = useRef(0);
29 const recordedOpenRef = useRef<string | null>(null);
30​
31 // Opening a thread is one visit that also counts toward search ranking. A
32 // palette pick already sent it with the query. It runs before the watermark
33 // effect, which then sees this watermark as sent.
34 useEffect(() => {
35 if (!serverThread?.id) return;
36 if (recordedOpenRef.current === threadKey) return;
37 recordedOpenRef.current = threadKey;
38 // Recorded here even when the server cannot take opens, so recents follow it.
39 const claimed = claimThreadOpen(serverThread.environmentId, serverThread.id, Date.now());
40 if (!claimed || serverThread.lastVisitedAt === undefined) return;
41 lastDispatchedVisitRef.current = `${threadKey}:${serverThread.updatedAt}`;
42 lastVisitDispatchAtRef.current = Date.now();
43 void visitThreadMutation({
44 environmentId: serverThread.environmentId,
45 input: {
46 threadId: serverThread.id,
47 visitedAt: serverThread.updatedAt,
48 opened: true,
49 },
50 });
51 }, [
52 threadKey,
53 serverThread?.environmentId,
54 serverThread?.id,
55 serverThread?.lastVisitedAt,
56 serverThread?.updatedAt,
57 visitThreadMutation,
58 ]);
59​
60 useEffect(() => {
61 if (!serverThread?.id) return;
62 const threadUpdatedAt = Date.parse(serverThread.updatedAt);
63 if (Number.isNaN(threadUpdatedAt)) return;
64 const effectiveLastVisitedAt = resolveThreadLastVisitedAt(
65 serverThread.lastVisitedAt,
66 activeThreadLocalLastVisitedAt,
67 );
68 const lastVisitedAt = effectiveLastVisitedAt ? Date.parse(effectiveLastVisitedAt) : NaN;
69 if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= threadUpdatedAt) return;
70​
71 if (serverThread.lastVisitedAt !== undefined) {
72 // Dedupe per watermark — the effect re-runs before the command's echo
73 // lands. The dedupe also keeps a mark-unread on the open thread sticky:
74 // the rewind leaves updatedAt untouched, so the already-dispatched key
75 // skips a fresh visit until new activity lands or the thread is reopened.
76 const dispatchKey = `${threadKey}:${serverThread.updatedAt}`;
77 if (lastDispatchedVisitRef.current === dispatchKey) return;
78 const dispatch = () => {
79 lastDispatchedVisitRef.current = dispatchKey;
80 lastVisitDispatchAtRef.current = Date.now();
81 void visitThreadMutation({
82 environmentId: serverThread.environmentId,
83 input: { threadId: serverThread.id, visitedAt: serverThread.updatedAt },
84 });
85 };
86 const latestRunCompletedAtMs = serverThread.latestRun?.completedAt
87 ? Date.parse(serverThread.latestRun.completedAt)
88 : NaN;
89 const hasUnseenCompletion =
90 !Number.isNaN(latestRunCompletedAtMs) &&
91 (Number.isNaN(lastVisitedAt) || latestRunCompletedAtMs > lastVisitedAt);
92 const elapsed = Date.now() - lastVisitDispatchAtRef.current;
93 if (hasUnseenCompletion || elapsed >= VISIT_DISPATCH_THROTTLE_MS) {
94 dispatch();
95 return;
96 }
97 const timer = setTimeout(dispatch, VISIT_DISPATCH_THROTTLE_MS - elapsed);
98 return () => clearTimeout(timer);
99 }
100​
101 markThreadVisited(
102 scopedThreadKey(scopeThreadRef(serverThread.environmentId, serverThread.id)),
103 serverThread.updatedAt,
104 );
105 }, [
106 activeThreadLocalLastVisitedAt,
107 markThreadVisited,
108 threadKey,
109 serverThread?.environmentId,
110 serverThread?.id,
111 serverThread?.lastVisitedAt,
112 serverThread?.latestRun?.completedAt,
113 serverThread?.updatedAt,
114 visitThreadMutation,
115 ]);
116 return null;