The best way to control Claude Code, Codex and more from any computer or phone

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