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

thread-outbox.test.ts

497 lines15.0 KB

1import { describe, expect, it } from "@effect/vitest";
2import {
3 CommandId,
4 EnvironmentId,
5 MessageId,
6 ProjectId,
7 ProviderInstanceId,
8 ThreadId,
9} from "@t3tools/contracts";
10import { AtomRegistry } from "effect/unstable/reactivity";
11​
12import {
13 decodeQueuedThreadMessage,
14 encodeQueuedThreadMessage,
15 groupQueuedThreadMessages,
16 isQueuedThreadCreationSendable,
17 modelSelectionsEqual,
18 resolveThreadOutboxDeliveryAction,
19 resolveThreadOutboxFailureAction,
20 resolveQueuedThreadSettings,
21 shouldRetryThreadOutboxDelivery,
22 threadOutboxRetryDelayMs,
23 type QueuedThreadMessage,
24} from "./thread-outbox-model";
25import { createThreadOutboxManager, ThreadOutboxManagerError } from "./thread-outbox-manager";
26import type { ThreadOutboxStorage } from "./thread-outbox-storage";
27​
28function queuedMessage(input: {
29 readonly environmentId?: string;
30 readonly threadId?: string;
31 readonly messageId: string;
32 readonly createdAt: string;
33}): QueuedThreadMessage {
34 return {
35 environmentId: EnvironmentId.make(input.environmentId ?? "environment-1"),
36 threadId: ThreadId.make(input.threadId ?? "thread-1"),
37 messageId: MessageId.make(input.messageId),
38 commandId: CommandId.make(`command-${input.messageId}`),
39 text: input.messageId,
40 attachments: [],
41 createdAt: input.createdAt,
42 };
44​
45describe("thread outbox", () => {
46 it("groups messages by scoped thread and preserves creation order", () => {
47 const later = queuedMessage({
48 messageId: "message-2",
49 createdAt: "2026-06-08T10:00:02.000Z",
50 });
51 const earlier = queuedMessage({
52 messageId: "message-1",
53 createdAt: "2026-06-08T10:00:01.000Z",
54 });
55​
56 expect(groupQueuedThreadMessages([later, earlier])).toEqual({
57 "environment-1:thread-1": [earlier, later],
58 });
59 });
60​
61 it("decodes the persisted schema and rejects incomplete messages", () => {
62 const message = queuedMessage({
63 messageId: "message-1",
64 createdAt: "2026-06-08T10:00:01.000Z",
65 });
66​
67 expect(
68 decodeQueuedThreadMessage({
69 schemaVersion: 1,
70 ...message,
71 }),
72 ).toEqual(message);
73 expect(() =>
74 decodeQueuedThreadMessage({
75 schemaVersion: 1,
76 environmentId: "environment-1",
77 }),
78 ).toThrow();
79 });
80​
81 it("persists the exact selector snapshot while remaining compatible with v1 messages", () => {
82 const legacyMessage = queuedMessage({
83 messageId: "message-1",
84 createdAt: "2026-06-08T10:00:01.000Z",
85 });
86 const selectedMessage = {
87 ...legacyMessage,
88 modelSelection: {
89 instanceId: ProviderInstanceId.make("codex"),
90 model: "gpt-5.4",
91 options: [{ id: "reasoningEffort", value: "xhigh" }],
92 },
93 runtimeMode: "approval-required",
94 interactionMode: "plan",
95 } satisfies QueuedThreadMessage;
96​
97 expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(selectedMessage))).toEqual(
98 selectedMessage,
99 );
100 expect(
101 resolveQueuedThreadSettings(legacyMessage, {
102 modelSelection: selectedMessage.modelSelection,
103 runtimeMode: selectedMessage.runtimeMode,
104 interactionMode: selectedMessage.interactionMode,
105 }),
106 ).toEqual({
107 modelSelection: selectedMessage.modelSelection,
108 runtimeMode: selectedMessage.runtimeMode,
109 interactionMode: selectedMessage.interactionMode,
110 });
111 });
112​
113 it("compares model options as part of the queued settings change", () => {
114 const base = {
115 instanceId: ProviderInstanceId.make("codex"),
116 model: "gpt-5.4",
117 options: [{ id: "reasoningEffort", value: "medium" }],
118 } as const;
119​
120 expect(modelSelectionsEqual(base, base)).toBe(true);
121 expect(
122 modelSelectionsEqual(base, {
123 ...base,
124 options: [{ id: "reasoningEffort", value: "xhigh" }],
125 }),
126 ).toBe(false);
127 });
128​
129 it("backs off queued delivery retries and caps them at sixteen seconds", () => {
130 expect([1, 2, 3, 4, 5, 6].map(threadOutboxRetryDelayMs)).toEqual([
131 1_000, 2_000, 4_000, 8_000, 16_000, 16_000,
132 ]);
133 });
134​
135 it("serializes mutations even when an earlier mutation is slower", async () => {
136 const registry = AtomRegistry.make();
137 const manager = createThreadOutboxManager({
138 registry,
139 storage: {
140 load: async () => [],
141 write: async () => undefined,
142 remove: async () => undefined,
143 },
144 });
145 const order: string[] = [];
146 let releaseFirst!: () => void;
147 const firstBlocked = new Promise<void>((resolve) => {
148 releaseFirst = resolve;
149 });
150​
151 const first = manager.serialize(async () => {
152 order.push("first:start");
153 await firstBlocked;
154 order.push("first:end");
155 });
156 const second = manager.serialize(async () => {
157 order.push("second");
158 });
159​
160 await Promise.resolve();
161 expect(order).toEqual(["first:start"]);
162 releaseFirst();
163 await Promise.all([first, second]);
164 expect(order).toEqual(["first:start", "first:end", "second"]);
165 registry.dispose();
166 });
167​
168 it("holds the mutation queue while persisted messages are loading", async () => {
169 const registry = AtomRegistry.make();
170 const message = queuedMessage({
171 messageId: "message-1",
172 createdAt: "2026-06-08T10:00:01.000Z",
173 });
174 const stored = new Map([[message.messageId, message]]);
175 let loadCalls = 0;
176 let removeCalls = 0;
177 let releaseInitialLoad!: () => void;
178 const initialLoadBlocked = new Promise<void>((resolve) => {
179 releaseInitialLoad = resolve;
180 });
181 const storage: ThreadOutboxStorage = {
182 load: async () => {
183 loadCalls += 1;
184 if (loadCalls === 1) {
185 await initialLoadBlocked;
186 }
187 return [...stored.values()];
188 },
189 write: async () => undefined,
190 remove: async (candidate) => {
191 removeCalls += 1;
192 stored.delete(candidate.messageId);
193 },
194 };
195 const manager = createThreadOutboxManager({ registry, storage });
196​
197 const loading = manager.load();
198 await Promise.resolve();
199 const clearing = manager.clearEnvironment(message.environmentId);
200 await Promise.resolve();
201 await Promise.resolve();
202​
203 expect(loadCalls).toBe(1);
204 expect(removeCalls).toBe(0);
205​
206 releaseInitialLoad();
207 await Promise.all([loading, clearing]);
208 expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({});
209 registry.dispose();
210 });
211​
212 it("reports structured load failures and permits a retry", async () => {
213 const registry = AtomRegistry.make();
214 const loadCause = new Error("storage unavailable");
215 const warnings: Array<{ message: string; error: unknown }> = [];
216 let loadCalls = 0;
217 const manager = createThreadOutboxManager({
218 registry,
219 storage: {
220 load: async () => {
221 loadCalls += 1;
222 if (loadCalls === 1) throw loadCause;
223 return [];
224 },
225 write: async () => undefined,
226 remove: async () => undefined,
227 },
228 warn: (message, error) => warnings.push({ message, error }),
229 });
230​
231 await manager.load();
232 expect(warnings).toEqual([
233 {
234 message: "[thread-outbox] failed to load persisted messages",
235 error: new ThreadOutboxManagerError({
236 operation: "load",
237 environmentId: null,
238 threadId: null,
239 messageId: null,
240 cause: loadCause,
241 }),
242 },
243 ]);
244​
245 await manager.load();
246 expect(loadCalls).toBe(2);
247 registry.dispose();
248 });
249​
250 it("keeps atom state aligned with durable writes and removals", async () => {
251 const registry = AtomRegistry.make();
252 const stored = new Map<MessageId, QueuedThreadMessage>();
253 const removalCause = new Error("remove failed");
254 let failRemoval = true;
255 const storage: ThreadOutboxStorage = {
256 load: async () => [...stored.values()],
257 write: async (message) => {
258 stored.set(message.messageId, message);
259 },
260 remove: async (message) => {
261 if (failRemoval) {
262 throw removalCause;
263 }
264 stored.delete(message.messageId);
265 },
266 };
267 const manager = createThreadOutboxManager({ registry, storage });
268 const message = queuedMessage({
269 messageId: "message-1",
270 createdAt: "2026-06-08T10:00:01.000Z",
271 });
272​
273 await manager.enqueue(message);
274 expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
275 "environment-1:thread-1": [message],
276 });
277​
278 await expect(manager.remove(message)).rejects.toEqual(
279 new ThreadOutboxManagerError({
280 operation: "remove",
281 environmentId: message.environmentId,
282 threadId: message.threadId,
283 messageId: message.messageId,
284 cause: removalCause,
285 }),
286 );
287 expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
288 "environment-1:thread-1": [message],
289 });
290​
291 failRemoval = false;
292 await manager.remove(message);
293 expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({});
294 registry.dispose();
295 });
296​
297 it("replaces an existing message when an enqueue retry uses the same id", async () => {
298 const registry = AtomRegistry.make();
299 const manager = createThreadOutboxManager({
300 registry,
301 storage: {
302 load: async () => [],
303 write: async () => undefined,
304 remove: async () => undefined,
305 },
306 });
307 const message = queuedMessage({
308 messageId: "message-1",
309 createdAt: "2026-06-08T10:00:01.000Z",
310 });
311 const retried = { ...message, text: "retried" };
312​
313 await manager.enqueue(message);
314 await manager.enqueue(retried);
315​
316 expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
317 "environment-1:thread-1": [retried],
318 });
319 registry.dispose();
320 });
321​
322 it("updates a queued message in place but never resurrects a removed one", async () => {
323 const registry = AtomRegistry.make();
324 const stored = new Map<MessageId, QueuedThreadMessage>();
325 const storage: ThreadOutboxStorage = {
326 load: async () => [...stored.values()],
327 write: async (message) => {
328 stored.set(message.messageId, message);
329 },
330 remove: async (message) => {
331 stored.delete(message.messageId);
332 },
333 };
334 const manager = createThreadOutboxManager({ registry, storage });
335 const message = queuedMessage({
336 messageId: "message-1",
337 createdAt: "2026-06-08T10:00:01.000Z",
338 });
339​
340 await manager.enqueue(message);
341 const edited = { ...message, text: "edited" };
342 await expect(manager.update(edited)).resolves.toBe(true);
343 expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
344 "environment-1:thread-1": [edited],
345 });
346 expect(stored.get(message.messageId)).toEqual(edited);
347​
348 await manager.remove(edited);
349 await expect(manager.update({ ...message, text: "stale flush" })).resolves.toBe(false);
350 expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({});
351 expect(stored.size).toBe(0);
352 registry.dispose();
353 });
354​
355 it("only removes a missing-thread message after shell synchronization is live", () => {
356 expect(
357 resolveThreadOutboxDeliveryAction({
358 isCreation: false,
359 threadExists: false,
360 shellStatus: "synchronizing",
361 environmentConnected: true,
362 threadBusy: false,
363 }),
364 ).toBe("wait");
365 expect(
366 resolveThreadOutboxDeliveryAction({
367 isCreation: false,
368 threadExists: false,
369 shellStatus: "live",
370 environmentConnected: true,
371 threadBusy: false,
372 }),
373 ).toBe("remove");
374 expect(
375 resolveThreadOutboxDeliveryAction({
376 isCreation: false,
377 threadExists: true,
378 shellStatus: "live",
379 environmentConnected: true,
380 threadBusy: false,
381 }),
382 ).toBe("send");
383 });
384​
385 it("sends queued creations once connected and live, removing already-created ones", () => {
386 expect(
387 resolveThreadOutboxDeliveryAction({
388 isCreation: true,
389 threadExists: false,
390 shellStatus: "cached",
391 environmentConnected: false,
392 threadBusy: false,
393 }),
394 ).toBe("wait");
395 // Connected but not yet synchronized: a previously delivered creation may
396 // simply not be visible yet — sending now could duplicate the thread.
397 expect(
398 resolveThreadOutboxDeliveryAction({
399 isCreation: true,
400 threadExists: false,
401 shellStatus: "synchronizing",
402 environmentConnected: true,
403 threadBusy: false,
404 }),
405 ).toBe("wait");
406 expect(
407 resolveThreadOutboxDeliveryAction({
408 isCreation: true,
409 threadExists: false,
410 shellStatus: "live",
411 environmentConnected: true,
412 threadBusy: false,
413 }),
414 ).toBe("send");
415 expect(
416 resolveThreadOutboxDeliveryAction({
417 isCreation: true,
418 threadExists: true,
419 shellStatus: "live",
420 environmentConnected: true,
421 threadBusy: true,
422 }),
423 ).toBe("remove");
424 });
425​
426 it("round-trips queued creations and gates incomplete ones from sending", () => {
427 const base = queuedMessage({
428 messageId: "message-1",
429 createdAt: "2026-06-08T10:00:01.000Z",
430 });
431 const creationMessage = {
432 ...base,
433 modelSelection: {
434 instanceId: ProviderInstanceId.make("codex"),
435 model: "gpt-5.4",
436 },
437 creation: {
438 projectId: ProjectId.make("project-1"),
439 workspaceMode: "worktree",
440 branch: "main",
441 worktreePath: null,
442 startFromOrigin: true,
443 },
444 } satisfies QueuedThreadMessage;
445​
446 expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(creationMessage))).toEqual(
447 creationMessage,
448 );
449 expect(isQueuedThreadCreationSendable(creationMessage)).toBe(true);
450 expect(
451 isQueuedThreadCreationSendable({
452 ...creationMessage,
453 creation: { ...creationMessage.creation, branch: null },
454 }),
455 ).toBe(false);
456 expect(
457 isQueuedThreadCreationSendable({
458 ...creationMessage,
459 creation: { ...creationMessage.creation, branch: "" },
460 }),
461 ).toBe(false);
462 expect(isQueuedThreadCreationSendable({ ...creationMessage, modelSelection: undefined })).toBe(
463 false,
464 );
465 expect(isQueuedThreadCreationSendable(base)).toBe(false);
466 });
467​
468 it("retries transport failures but drops deterministic command failures", () => {
469 expect(shouldRetryThreadOutboxDelivery(new Error("Socket is not connected"))).toBe(true);
470 expect(
471 shouldRetryThreadOutboxDelivery({
472 _tag: "ConnectionTransientError",
473 message: "temporarily unavailable",
474 }),
475 ).toBe(true);
476 expect(shouldRetryThreadOutboxDelivery(new Error("Thread no longer exists"))).toBe(false);
477 });
478​
479 it("retains queued messages when settings synchronization fails before startTurn", () => {
480 const deterministicFailure = new Error("Thread no longer exists");
481​
482 expect(
483 resolveThreadOutboxFailureAction({
484 stage: "settings-sync",
485 error: deterministicFailure,
486 interrupted: false,
487 }),
488 ).toBe("retry");
489 expect(
490 resolveThreadOutboxFailureAction({
491 stage: "start-turn",
492 error: deterministicFailure,
493 interrupted: false,
494 }),
495 ).toBe("discard");
496 });
497});