Open History to see the last commit
1import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
4import { expect, it, vi } from "vite-plus/test";
5
6import type { VisitThreadInput } from "../operations/commands.ts";
7import type { AtomCommandResult } from "./runtime.ts";
8import { claimThreadOpen } from "./threadSearch.ts";
9import { createThreadVisitTracker, VISIT_DISPATCH_THROTTLE_MS } from "./threadVisits.ts";
10
11const environmentId = EnvironmentId.make("env-visits");
12
13interface Shell {
14 readonly environmentId: EnvironmentId;
15 readonly id: ThreadId;
16 readonly updatedAt: string;
17 readonly lastVisitedAt?: string | null;
18 readonly latestRun: { readonly completedAt: string | null } | null;
19 readonly wokeAt?: string | null;
20}
21
22function at(seconds: number) {
23 return `2026-01-01T00:00:${String(seconds).padStart(2, "0")}.000Z`;
24}
25
26// claimThreadOpen dedupes per thread in module state, so each test opens its own thread.
27function setup(threadName: string, initial: Omit<Shell, "environmentId" | "id"> | null) {
28 vi.useFakeTimers({ now: Date.UTC(2026, 0, 1) });
29 const threadId = ThreadId.make(threadName);
30 const ref = { environmentId, threadId };
31 const shellAtom = Atom.make<Shell | null>(
32 initial === null ? null : { environmentId, id: threadId, ...initial },
33 );
34 // Visits the server accepted; offline ones fail without reaching it.
35 const visits: Array<VisitThreadInput> = [];
36 const localVisits: Array<string> = [];
37 let online = true;
38 let pendingResult: Promise<AtomCommandResult<void, string>> | undefined;
39 const attempts: Array<VisitThreadInput> = [];
40 const sessionGenerationAtom = Atom.make(1);
41 const tracker = createThreadVisitTracker({
42 threadShellAtom: () => shellAtom,
43 sessionGenerationAtom: () => sessionGenerationAtom,
44 visit: {
45 label: "test-visit",
46 run: async (_registry, value) => {
47 attempts.push(value.input);
48 const pending = pendingResult;
49 pendingResult = undefined;
50 if (online) visits.push(value.input);
51 if (pending) return pending;
52 if (!online) return AsyncResult.failure(Cause.fail("disconnected"));
53 return AsyncResult.success(undefined);
54 },
55 },
56 markLocalVisit: (_ref, visitedAt) => localVisits.push(visitedAt),
57 });
58 const registry = AtomRegistry.make();
59 return {
60 ref,
61 visits,
62 localVisits,
63 attempts,
64 deferNextVisit: () => {
65 const deferred = Promise.withResolvers<AtomCommandResult<void, string>>();
66 pendingResult = deferred.promise;
67 return () => deferred.resolve(AsyncResult.failure(Cause.fail("disconnected")));
68 },
69 reconnect: () => registry.set(sessionGenerationAtom, registry.get(sessionGenerationAtom) + 1),
70 mount: () => registry.mount(tracker(ref)),
71 setOnline: (value: boolean) => {
72 online = value;
73 },
74 update: (patch: Partial<Shell>) => {
75 const current = registry.get(shellAtom);
76 registry.set(shellAtom, {
77 environmentId,
78 id: threadId,
79 updatedAt: at(0),
80 latestRun: null,
81 ...current,
82 ...patch,
83 });
84 },
85 [Symbol.dispose]: () => vi.useRealTimers(),
86 };
87}
88
89it("records the open once, then throttles streaming visits", () => {
90 using t = setup("thread-throttle", {
91 updatedAt: at(10),
92 lastVisitedAt: at(0),
93 latestRun: null,
94 });
95 t.mount();
96 expect(t.visits).toEqual([{ threadId: t.ref.threadId, visitedAt: at(10), opened: true }]);
97
98 vi.advanceTimersByTime(1_000);
99 t.update({ updatedAt: at(11) });
100 t.update({ updatedAt: at(12) });
101 expect(t.visits).toHaveLength(1);
102
103 vi.advanceTimersByTime(VISIT_DISPATCH_THROTTLE_MS - 1_000);
104 expect(t.visits.slice(1)).toEqual([{ threadId: t.ref.threadId, visitedAt: at(12) }]);
105});
106
107it("sends an unseen completion without waiting for the throttle", () => {
108 using t = setup("thread-completion", {
109 updatedAt: at(10),
110 lastVisitedAt: at(0),
111 latestRun: null,
112 });
113 t.mount();
114 t.update({ updatedAt: at(20), latestRun: { completedAt: at(20) } });
115 expect(t.visits.slice(1)).toEqual([{ threadId: t.ref.threadId, visitedAt: at(20) }]);
116});
117
118it("does not resend the open a palette pick already sent", () => {
119 using t = setup("thread-palette", { updatedAt: at(10), lastVisitedAt: at(0), latestRun: null });
120 claimThreadOpen(environmentId, t.ref.threadId, Date.UTC(2026, 0, 1));
121 t.mount();
122 expect(t.visits).toEqual([{ threadId: t.ref.threadId, visitedAt: at(10) }]);
123});
124
125it("keeps a mark-unread on the open thread until new activity lands", () => {
126 using t = setup("thread-unread", { updatedAt: at(10), lastVisitedAt: at(0), latestRun: null });
127 t.mount();
128 t.update({ lastVisitedAt: at(10) });
129 t.update({ lastVisitedAt: at(5) });
130 vi.advanceTimersByTime(VISIT_DISPATCH_THROTTLE_MS);
131 expect(t.visits).toHaveLength(1);
132
133 t.update({ updatedAt: at(30) });
134 expect(t.visits.slice(1)).toEqual([{ threadId: t.ref.threadId, visitedAt: at(30) }]);
135});
136
137it("keeps a mark-unread on a read thread reopened within the open dedupe window", () => {
138 using t = setup("thread-unread-reopened", {
139 updatedAt: at(10),
140 lastVisitedAt: at(10),
141 latestRun: { completedAt: at(9) },
142 });
143 claimThreadOpen(environmentId, t.ref.threadId, Date.UTC(2026, 0, 1));
144 t.mount();
145 t.update({ lastVisitedAt: at(8) });
146 vi.advanceTimersByTime(VISIT_DISPATCH_THROTTLE_MS);
147 expect(t.visits).toEqual([]);
148
149 // An authoritative snapshot can briefly replace the row with an older one.
150 t.update({ updatedAt: at(5), lastVisitedAt: at(5), latestRun: { completedAt: at(4) } });
151 t.update({ updatedAt: at(10), lastVisitedAt: at(8), latestRun: { completedAt: at(9) } });
152 vi.advanceTimersByTime(VISIT_DISPATCH_THROTTLE_MS);
153 expect(t.visits).toEqual([]);
154});
155
156it("keeps mark unread sticky after an expired wake is retired", () => {
157 using t = setup("thread-unread-retired-wake", {
158 updatedAt: at(10),
159 lastVisitedAt: at(0),
160 latestRun: { completedAt: at(9) },
161 wokeAt: at(15),
162 });
163 t.mount();
164 expect(t.visits).toEqual([{ threadId: t.ref.threadId, visitedAt: at(15), opened: true }]);
165 t.update({ lastVisitedAt: at(15) });
166 t.update({ lastVisitedAt: at(8), wokeAt: null });
167 vi.advanceTimersByTime(VISIT_DISPATCH_THROTTLE_MS);
168 expect(t.visits).toHaveLength(1);
169
170 t.update({ updatedAt: at(30) });
171 expect(t.visits.slice(1)).toEqual([{ threadId: t.ref.threadId, visitedAt: at(30) }]);
172});
173
174it("waits for the shell and records local visits for servers without tracking", () => {
175 using t = setup("thread-local", null);
176 t.mount();
177 expect(t.visits).toEqual([]);
178 t.update({ updatedAt: at(10), latestRun: null });
179 t.update({ updatedAt: at(11) });
180 expect(t.visits).toEqual([]);
181 expect(t.localVisits).toEqual([at(10), at(11)]);
182});
183
184it("drops a pending visit when the thread is no longer viewed", () => {
185 using t = setup("thread-unmount", { updatedAt: at(10), lastVisitedAt: at(0), latestRun: null });
186 const unmount = t.mount();
187 t.update({ updatedAt: at(11) });
188 unmount();
189 vi.advanceTimersByTime(VISIT_DISPATCH_THROTTLE_MS);
190 expect(t.visits).toHaveLength(1);
191});
192
193it("sends the open with the first visit when the shell arrives after the thread is shown", () => {
194 using t = setup("thread-shell-missing", null);
195 t.mount();
196 expect(claimThreadOpen(environmentId, t.ref.threadId, Date.UTC(2026, 0, 1))).toBe(false);
197 expect(t.visits).toEqual([]);
198
199 t.update({ updatedAt: at(10), lastVisitedAt: at(0), latestRun: null });
200 expect(t.visits).toEqual([{ threadId: t.ref.threadId, visitedAt: at(10), opened: true }]);
201
202 t.update({ updatedAt: at(10), lastVisitedAt: at(10) });
203 vi.advanceTimersByTime(VISIT_DISPATCH_THROTTLE_MS);
204 expect(t.visits).toHaveLength(1);
205});
206
207it("advances the watermark to a wake without waiting for the throttle", () => {
208 using t = setup("thread-wake", { updatedAt: at(10), lastVisitedAt: at(0), latestRun: null });
209 t.mount();
210 t.update({ wokeAt: at(15) });
211 expect(t.visits.slice(1)).toEqual([{ threadId: t.ref.threadId, visitedAt: at(15) }]);
212
213 vi.advanceTimersByTime(1_000);
214 t.update({ updatedAt: at(16) });
215 expect(t.visits).toHaveLength(2);
216});
217
218it("retries a failed visit when the same shell returns after reconnect", async () => {
219 using t = setup("thread-retry-failed", {
220 updatedAt: at(10),
221 lastVisitedAt: at(0),
222 latestRun: null,
223 });
224 t.setOnline(false);
225 t.mount();
226 await vi.advanceTimersByTimeAsync(0);
227 expect(t.visits).toEqual([]);
228
229 t.setOnline(true);
230 t.reconnect();
231 await vi.advanceTimersByTimeAsync(VISIT_DISPATCH_THROTTLE_MS);
232 expect(t.visits).toEqual([{ threadId: t.ref.threadId, visitedAt: at(10), opened: true }]);
233});
234
235it("does not retry a failed visit the server already shows as seen", async () => {
236 using t = setup("thread-failed-seen", {
237 updatedAt: at(10),
238 lastVisitedAt: at(0),
239 latestRun: null,
240 });
241 t.setOnline(false);
242 t.mount();
243 t.update({ lastVisitedAt: at(10) });
244 await vi.advanceTimersByTimeAsync(0);
245
246 t.setOnline(true);
247 t.reconnect();
248 t.update({ lastVisitedAt: at(0) });
249 await vi.advanceTimersByTimeAsync(VISIT_DISPATCH_THROTTLE_MS);
250 expect(t.visits).toEqual([]);
251});
252
253it("preserves mark unread when an accepted visit fails after the rewind", async () => {
254 using t = setup("thread-accepted-rewound-failure", {
255 updatedAt: at(10),
256 lastVisitedAt: at(0),
257 latestRun: null,
258 });
259 const fail = t.deferNextVisit();
260 t.mount();
261 t.update({ lastVisitedAt: at(10) });
262 t.update({ lastVisitedAt: at(5) });
263 fail();
264 await vi.advanceTimersByTimeAsync(0);
265 t.reconnect();
266 t.update({});
267 await vi.advanceTimersByTimeAsync(VISIT_DISPATCH_THROTTLE_MS);
268 expect(t.attempts).toEqual([{ threadId: t.ref.threadId, visitedAt: at(10), opened: true }]);
269});
270
271it.each(["unchanged shell", "new shell snapshot"] as const)(
272 "retries with %s when reconnect arrives before the pending visit fails",
273 async (snapshot) => {
274 using t = setup(`thread-reconnect-before-failure-${snapshot}`, {
275 updatedAt: at(10),
276 lastVisitedAt: at(0),
277 latestRun: null,
278 });
279 t.setOnline(false);
280 const fail = t.deferNextVisit();
281 t.mount();
282 t.setOnline(true);
283 t.reconnect();
284 if (snapshot === "new shell snapshot") t.update({});
285 fail();
286 await vi.advanceTimersByTimeAsync(VISIT_DISPATCH_THROTTLE_MS);
287 expect(t.visits).toEqual([{ threadId: t.ref.threadId, visitedAt: at(10), opened: true }]);
288 },
289);
290
291it("retries rejected opens only once per connection generation", async () => {
292 using t = setup("thread-rejection-throttle", {
293 updatedAt: at(10),
294 lastVisitedAt: at(0),
295 latestRun: null,
296 });
297 t.setOnline(false);
298 t.mount();
299 await vi.advanceTimersByTimeAsync(0);
300 for (let second = 1; second < 10; second++) {
301 await vi.advanceTimersByTimeAsync(1_000);
302 t.update({});
303 await vi.advanceTimersByTimeAsync(0);
304 }
305 expect(t.attempts).toHaveLength(1);
306 await vi.advanceTimersByTimeAsync(1_000);
307 expect(t.attempts).toHaveLength(1);
308 t.reconnect();
309 await vi.advanceTimersByTimeAsync(0);
310 expect(t.attempts).toHaveLength(2);
311 t.update({ updatedAt: at(20), latestRun: { completedAt: at(20) } });
312 await vi.advanceTimersByTimeAsync(3 * VISIT_DISPATCH_THROTTLE_MS);
313 expect(t.attempts).toHaveLength(2);
314});