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

threadOutboxDelivery.permissions.test.ts

550 lines20.6 KB

1import {
2 AuthOrchestrationOperateScope,
3 CommandId,
4 EnvironmentId,
5 MessageId,
6 ProjectId,
7 ProviderInstanceId,
8 ThreadId,
9} from "@t3tools/contracts";
10import * as Cause from "effect/Cause";
11import { AsyncResult, type Atom } from "effect/reactivity";
12import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
13import type { QueuedThreadMessage } from "./thread-outbox-model";
14​
15const state = vi.hoisted(() => ({
16 draftText: "Keep this draft separate",
17 cleanups: [] as Array<() => void>,
18 delivery: null as {
19 readonly drain: () => void;
20 readonly dispose: () => void;
21 } | null,
22 start: vi.fn(),
23 metadata: vi.fn(),
24 runtime: vi.fn(),
25 interaction: vi.fn(),
26 prepare: vi.fn(),
27 checkout: vi.fn(),
28 modelUnavailable: vi.fn(() => false),
29 familyMount: vi.fn(() => () => {}),
30 threadShells: null as unknown as Atom.Writable<ReadonlyArray<unknown>>,
31 manager: null as unknown as ReturnType<
32 typeof import("./thread-outbox-manager").createThreadOutboxManager
33 >,
34 thread: {
35 environmentId: "secondary",
36 id: "thread",
37 modelSelection: { instanceId: "codex", model: "gpt-5.4" },
38 runtimeMode: "full-access",
39 interactionMode: "default",
40 session: null,
41 },
42 config: {
43 shellThreadFamilies: false,
44 providers: [{ instanceId: "codex", driver: "codex" }],
45 environment: { capabilities: {} },
46 },
47}));
48vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
49vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({
50 ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
51 runAtomCommand: (_registry: unknown, command: (input: unknown) => unknown, input: unknown) =>
52 command(input),
53}));
54vi.mock("./session", async () => {
55 const { Atom } = await import("effect/reactivity");
56 const { appAtomRegistry } = await import("./atom-registry");
57 // A session's state is reduced to whether it grants the operate scope.
58 const sessionStateAtom = Atom.family((_id: string) => Atom.make(false).pipe(Atom.keepAlive));
59 const sessionHasScope = (granted: boolean, scope: string) =>
60 granted && scope === AuthOrchestrationOperateScope;
61 return {
62 environmentSession: { sessionStateAtom },
63 sessionHasScope,
64 readEnvironmentScope: (environmentId: string, scope: string) =>
65 sessionHasScope(appAtomRegistry.get(sessionStateAtom(environmentId)), scope),
66 };
67});
68vi.mock("./projects", async () => {
69 const { Atom } = await import("effect/reactivity");
70 return { environmentProjects: { projectsAtom: Atom.make([]) } };
71});
72vi.mock("./workspace", async () => {
73 const { Atom } = await import("effect/reactivity");
74 return {
75 workspaceConnections: {
76 environmentsAtom: Atom.make([{ environmentId: "secondary", connectionState: "connected" }]),
77 },
78 };
79});
80vi.mock("./server", async () => {
81 const { Atom } = await import("effect/reactivity");
82 return {
83 serverEnvironment: { configValueAtom: Atom.family((_id: string) => Atom.make(state.config)) },
84 environmentServerConfigsAtom: Atom.make(new Map([["secondary", state.config]])),
85 };
86});
87vi.mock("./threads", async () => {
88 const { Atom, AsyncResult } = await import("effect/reactivity");
89 state.threadShells = Atom.make<ReadonlyArray<unknown>>([state.thread]).pipe(Atom.keepAlive);
90 return {
91 threadEnvironment: {
92 startTurn: state.start,
93 updateMetadata: state.metadata,
94 setRuntimeMode: state.runtime,
95 setInteractionMode: state.interaction,
96 },
97 environmentThreadShells: { threadShellsAtom: state.threadShells },
98 threadFamilies: {
99 mount: state.familyMount,
100 familyAtom: () => Atom.make(AsyncResult.success({})),
101 refresh: vi.fn(),
102 },
103 environmentThreadDetails: { stateAtom: () => Atom.make(null) },
104 };
105});
106vi.mock("./git", () => ({ gitEnvironment: { preparePullRequestThread: state.checkout } }));
107vi.mock("../lib/modelOptions", () => ({ isModelSelectionUnavailable: state.modelUnavailable }));
108vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "abcd" }));
109vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: state.prepare }));
110vi.mock("./thread-outbox", async () => {
111 const { createThreadOutboxManager } = await import("./thread-outbox-manager");
112 const { appAtomRegistry } = await import("./atom-registry");
113 state.manager = createThreadOutboxManager({
114 registry: appAtomRegistry,
115 storage: {
116 load: async () => ({ messages: [], errors: [] }),
117 write: async () => {},
118 remove: async () => {},
119 },
120 });
121 return {
122 threadOutboxManager: state.manager,
123 threadOutboxRevision: (id: MessageId) => state.manager.revisionOf(id),
124 confirmThreadOutboxMessageQueued: (message: QueuedThreadMessage) =>
125 state.manager.confirmQueued(message),
126 updateThreadOutboxMessage: (message: QueuedThreadMessage, revision?: number) =>
127 state.manager.update(message, revision),
128 };
129});
130vi.mock("./thread-outbox-removal", () => ({
131 removeThreadOutboxMessage: (message: QueuedThreadMessage, revision?: number) =>
132 state.manager.remove(message, revision),
133}));
134vi.mock("./use-thread-outbox", async () => {
135 const { Atom } = await import("effect/reactivity");
136 return {
137 editingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive),
138 dispatchingQueuedMessageIdAtom: Atom.make<MessageId | null>(null).pipe(Atom.keepAlive),
139 threadOutboxShellStatusesAtom: Atom.make(new Map([["secondary", "live"]])),
140 };
141});
142vi.mock("./use-composer-drafts", async () => {
143 const { Atom } = await import("effect/reactivity");
144 return {
145 composerDraftsAtom: Atom.make({}),
146 removeDeliveredCloudQueuedMessage: async () => {},
147 appendComposerDraftAttachments: vi.fn(),
148 flushComposerDrafts: vi.fn(),
149 getComposerDraftSnapshot: vi.fn(() => ({ text: state.draftText, attachments: [] })),
150 mergeComposerDraftContent: vi.fn(async (_key: string, input: { text: string }) => {
151 state.draftText += `\n${input.text}`;
152 }),
153 replaceComposerDraftAttachments: vi.fn(),
154 setFreshSessionPending: vi.fn(),
155 undoComposerDraftMerge: vi.fn(),
156 updateComposerDraftSettings: vi.fn(),
157 waitForComposerDraftsLoaded: vi.fn(),
158 };
159});
160​
161import { appAtomRegistry } from "./atom-registry";
162import { environmentSession } from "./session";
163import { dispatchingQueuedMessageIdAtom, editingQueuedMessageIdsAtom } from "./use-thread-outbox";
164import { createThreadOutboxDelivery } from "./threadOutboxDelivery";
165​
166const message = (overrides: Partial<QueuedThreadMessage> = {}): QueuedThreadMessage => ({
167 environmentId: EnvironmentId.make("secondary"),
168 threadId: ThreadId.make("thread"),
169 commandId: CommandId.make("command"),
170 messageId: MessageId.make("message"),
171 text: "Keep this queued",
172 attachments: [],
173 createdAt: "2026-09-05T00:00:00.000Z",
174 ...overrides,
175});
176const remaining = () =>
177 Object.values(appAtomRegistry.get(state.manager.queuedMessagesByThreadKeyAtom)).flat();
178​
179function setOperateGrant(environmentId: string, granted: boolean): void {
180 // The mocked session atom holds the grant itself (see the ./session mock).
181 const sessionAtom = environmentSession.sessionStateAtom(EnvironmentId.make(environmentId));
182 appAtomRegistry.set(sessionAtom as unknown as Atom.Writable<boolean>, granted);
184​
185function runDrain() {
186 const settled = Promise.withResolvers<void>();
187 const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdAtom, (id) => {
188 if (id === null) settled.resolve();
189 });
190 startDelivery();
191 return settled.promise.finally(release);
193​
194/** Starts the service once per test; later calls run another drain pass. */
195function startDelivery(): void {
196 if (state.delivery !== null) {
197 state.delivery.drain();
198 return;
199 }
200 const delivery = createThreadOutboxDelivery();
201 state.delivery = delivery;
202 state.cleanups.push(() => {
203 delivery.dispose();
204 state.delivery = null;
205 });
207​
208beforeEach(() => {
209 setOperateGrant("primary", true);
210 setOperateGrant("secondary", false);
211 state.draftText = "Keep this draft separate";
212 state.config.shellThreadFamilies = false;
213 state.modelUnavailable.mockReset().mockReturnValue(false);
214 state.familyMount.mockReset().mockReturnValue(() => {});
215 appAtomRegistry.set(state.threadShells, [state.thread]);
216 appAtomRegistry.set(state.manager.queuedMessagesByThreadKeyAtom, {});
217 appAtomRegistry.set(dispatchingQueuedMessageIdAtom, null);
218 appAtomRegistry.set(editingQueuedMessageIdsAtom, {});
219 for (const command of [
220 state.start,
221 state.metadata,
222 state.runtime,
223 state.interaction,
224 state.checkout,
225 ]) {
226 command.mockReset().mockResolvedValue(AsyncResult.success(undefined));
227 }
228 state.start.mockResolvedValue(AsyncResult.success({}));
229 state.prepare.mockReset().mockImplementation(async ({ attachments }) => ({
230 status: "ready",
231 attachments: [],
232 draftAttachments: attachments,
233 pendingAttachmentIds: [],
234 }));
235});
236​
237describe("queued PR checkout", () => {
238 const queuedPullRequest = () =>
239 message({
240 threadId: ThreadId.make("new-pr-thread"),
241 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
242 creation: {
243 projectId: ProjectId.make("project"),
244 projectCwd: "/repo",
245 workspaceMode: "worktree",
246 branch: "fork/feature",
247 worktreePath: null,
248 pullRequestReference: "https://github.com/acme/repo/pull/123",
249 },
250 });
251 const preparedCheckout = {
252 branch: "pr-123",
253 worktreePath: "/repo/.t3/worktrees/pr-123",
254 isOnPullRequestHead: true,
255 };
256​
257 it("waits for the provider's PR checkout and launches in that worktree", async () => {
258 setOperateGrant("secondary", true);
259 await state.manager.enqueue(queuedPullRequest());
260 const started = Promise.withResolvers<void>();
261 const checkout =
262 Promise.withResolvers<AsyncResult.AsyncResult<typeof preparedCheckout, Error>>();
263 state.checkout.mockImplementationOnce(() => {
264 started.resolve();
265 return checkout.promise;
266 });
267 const drained = runDrain();
268 await started.promise;
269 expect(state.start).not.toHaveBeenCalled();
270 expect(state.checkout).toHaveBeenCalledWith({
271 environmentId: "secondary",
272 input: { cwd: "/repo", reference: "https://github.com/acme/repo/pull/123", mode: "worktree" },
273 });
274 checkout.resolve(AsyncResult.success(preparedCheckout));
275 await drained;
276 expect(state.start).toHaveBeenCalledOnce();
277 const bootstrap = state.start.mock.calls[0]?.[0].input.bootstrap;
278 expect(bootstrap.createThread).toMatchObject({
279 branch: "pr-123",
280 worktreePath: preparedCheckout.worktreePath,
281 });
282 expect(bootstrap.prepareWorktree).toBeUndefined();
283 expect(remaining()).toEqual([]);
284 });
285​
286 it("keeps the PR source queued on a transport failure without starting the agent", async () => {
287 setOperateGrant("secondary", true);
288 const queued = queuedPullRequest();
289 await state.manager.enqueue(queued);
290 state.checkout.mockResolvedValueOnce(
291 AsyncResult.failure(Cause.fail(new Error("Socket is not connected"))),
292 );
293 await runDrain();
294 expect(state.start).not.toHaveBeenCalled();
295 expect(remaining()).toEqual([queued]);
296 });
297​
298 it("stops launch if operation access is revoked while checking out the PR", async () => {
299 setOperateGrant("secondary", true);
300 const queued = queuedPullRequest();
301 await state.manager.enqueue(queued);
302 state.checkout.mockImplementationOnce(async () => {
303 setOperateGrant("secondary", false);
304 return AsyncResult.success(preparedCheckout);
305 });
306 await runDrain();
307 expect(state.start).not.toHaveBeenCalled();
308 expect(remaining()).toEqual([queued]);
309 });
310​
311 it("does not launch a stale task edited while the PR checkout was running", async () => {
312 setOperateGrant("secondary", true);
313 const queued = queuedPullRequest();
314 await state.manager.enqueue(queued);
315 const edited = { ...queued, text: "Updated instructions" };
316 state.checkout.mockImplementationOnce(async () => {
317 await state.manager.update(edited);
318 return AsyncResult.success(preparedCheckout);
319 });
320 await runDrain();
321 expect(state.start).not.toHaveBeenCalled();
322 expect(remaining()).toEqual([edited]);
323 });
324});
325afterEach(() => {
326 state.cleanups.splice(0).forEach((cleanup) => cleanup());
327});
328​
329describe("queued task operation access", () => {
330 it("parks a connected read-only target, then delivers its unchanged queue after a grant", async () => {
331 const queued = message();
332 await state.manager.enqueue(queued);
333 startDelivery();
334 expect(state.start).not.toHaveBeenCalled();
335 expect(state.prepare).not.toHaveBeenCalled();
336 expect(remaining()).toEqual([queued]);
337 setOperateGrant("secondary", true);
338 await runDrain();
339 expect(state.start).toHaveBeenCalledOnce();
340 expect(remaining()).toEqual([]);
341 });
342​
343 it("backs off instead of redelivering at once when a delivery hits a defect", async () => {
344 setOperateGrant("secondary", true);
345 const queued = message();
346 await state.manager.enqueue(queued);
347 // Awaited steps catch their own failures, so a defect in the delivery's own code is what
348 // rejects a delivery.
349 state.modelUnavailable.mockImplementationOnce(() => {
350 throw new TypeError("Cannot read properties of undefined");
351 });
352 await runDrain();
353 expect(state.modelUnavailable).toHaveBeenCalledOnce();
354 expect(state.prepare).not.toHaveBeenCalled();
355 expect(state.start).not.toHaveBeenCalled();
356 expect(appAtomRegistry.get(dispatchingQueuedMessageIdAtom)).toBeNull();
357 expect(remaining()).toEqual([queued]);
358 });
359​
360 it("starts one delivery when mounting a thread family changes the rows mid-pass", async () => {
361 setOperateGrant("secondary", true);
362 state.config.shellThreadFamilies = true;
363 const subAgentThread = { ...state.thread, id: "sub-agent" };
364 // A cached family merges its rows into the shell list as soon as it is mounted.
365 state.familyMount.mockImplementationOnce(() => {
366 appAtomRegistry.set(state.threadShells, [state.thread, subAgentThread]);
367 return () => {};
368 });
369 const queued = message({ threadId: ThreadId.make("sub-agent") });
370 startDelivery();
371 appAtomRegistry.set(editingQueuedMessageIdsAtom, { [queued.messageId]: true });
372 await state.manager.enqueue(queued);
373 using confirm = vi.spyOn(state.manager, "confirmQueued");
374 const delivered = Promise.withResolvers<void>();
375 const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdAtom, (id) => {
376 if (id === null) delivered.resolve();
377 });
378 // Ending the edit wakes the drain through a registry notification, the path on which the
379 // mount's synchronous row change notifies the drain again mid-pass.
380 appAtomRegistry.set(editingQueuedMessageIdsAtom, {});
381 expect(state.familyMount).toHaveBeenCalledOnce();
382 expect(confirm).toHaveBeenCalledOnce();
383 await delivered.promise.finally(release);
384 expect(state.start).toHaveBeenCalledOnce();
385 expect(remaining()).toEqual([]);
386 });
387​
388 it("stops the remaining settings and turn commands when an earlier update loses access", async () => {
389 setOperateGrant("secondary", true);
390 const queued = message({
391 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "different-model" },
392 runtimeMode: "approval-required",
393 interactionMode: "plan",
394 });
395 await state.manager.enqueue(queued);
396 state.runtime.mockImplementationOnce(async () => {
397 setOperateGrant("secondary", false);
398 return AsyncResult.success(undefined);
399 });
400 await runDrain();
401 expect(state.runtime).toHaveBeenCalledOnce();
402 expect(state.interaction).not.toHaveBeenCalled();
403 expect(state.prepare).not.toHaveBeenCalled();
404 expect(state.start).not.toHaveBeenCalled();
405 expect(remaining()).toEqual([queued]);
406 });
407​
408 it.each([
409 { isCreation: false, accepted: false },
410 { isCreation: true, accepted: true },
411 ])(
412 "preserves a rejected queue but removes an accepted turn after access loss (new task: $isCreation, accepted: $accepted)",
413 async ({ isCreation, accepted }) => {
414 setOperateGrant("secondary", true);
415 const queued = message(
416 isCreation
417 ? {
418 threadId: ThreadId.make("new-thread"),
419 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
420 creation: {
421 projectId: ProjectId.make("project"),
422 projectCwd: "/repo",
423 workspaceMode: "local",
424 branch: null,
425 worktreePath: null,
426 },
427 }
428 : {},
429 );
430 await state.manager.enqueue(queued);
431 const started = Promise.withResolvers<void>();
432 const delivery =
433 Promise.withResolvers<AsyncResult.AsyncResult<{ readonly sequence?: number }, Error>>();
434 state.start.mockImplementationOnce(() => {
435 started.resolve();
436 return delivery.promise;
437 });
438 const drained = runDrain();
439 await started.promise;
440 setOperateGrant("secondary", false);
441 delivery.resolve(
442 accepted
443 ? AsyncResult.success({})
444 : AsyncResult.failure(Cause.fail(new Error("This connection cannot control this task."))),
445 );
446 await drained;
447​
448 expect(remaining()).toEqual(accepted ? [] : [queued]);
449 expect(state.draftText).toBe("Keep this draft separate");
450 if (!accepted) {
451 setOperateGrant("secondary", true);
452 await runDrain();
453 expect(state.start).toHaveBeenCalledTimes(2);
454 expect(remaining()).toEqual([]);
455 expect(state.draftText).toBe("Keep this draft separate");
456 }
457 },
458 );
459​
460 it.each([
461 { isCreation: false, uploadFails: false },
462 { isCreation: true, uploadFails: false },
463 { isCreation: false, uploadFails: true },
464 { isCreation: true, uploadFails: true },
465 ])(
466 "keeps the message queued after upload revocation (new task: $isCreation, upload fails: $uploadFails)",
467 async ({ isCreation, uploadFails }) => {
468 setOperateGrant("secondary", true);
469 const queued = message(
470 isCreation
471 ? {
472 threadId: ThreadId.make("new-thread"),
473 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
474 creation: {
475 projectId: ProjectId.make("project"),
476 projectCwd: "/repo",
477 workspaceMode: "local",
478 branch: null,
479 worktreePath: null,
480 },
481 }
482 : {},
483 );
484 await state.manager.enqueue(queued);
485 state.prepare.mockImplementationOnce(async ({ attachments }) => {
486 setOperateGrant("secondary", false);
487 if (uploadFails) throw new Error("This connection cannot upload attachments.");
488 return {
489 status: "ready",
490 attachments: [],
491 draftAttachments: attachments,
492 pendingAttachmentIds: [],
493 };
494 });
495 await runDrain();
496 expect(state.prepare).toHaveBeenCalledOnce();
497 expect(state.start).not.toHaveBeenCalled();
498 expect(remaining()).toEqual([queued]);
499 },
500 );
501});
502​
503describe("compaction before a queued send", () => {
504 const compactTurn = {
505 commandId: "command:compact",
506 message: {
507 messageId: "message:compact",
508 role: "user",
509 text: "/compact",
510 attachments: [],
511 idleCompaction: "onReturn",
512 },
513 dispatchMode: "queue",
514 };
515​
516 it("queues /compact ahead of the message and resends the same /compact on a retry", async () => {
517 setOperateGrant("secondary", true);
518 const queued = message({ compactBeforeSend: true, dispatchMode: "queue" });
519 await state.manager.enqueue(queued);
520 state.start
521 .mockResolvedValueOnce(AsyncResult.success({}))
522 .mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Socket is not connected"))));
523 await runDrain();
524 expect(remaining()).toEqual([queued]);
525​
526 // A restarted app delivers the persisted message again.
527 state.cleanups.splice(0).forEach((cleanup) => cleanup());
528 await runDrain();
529 expect(state.start.mock.calls.map(([call]) => call.input)).toEqual([
530 expect.objectContaining(compactTurn),
531 expect.objectContaining({ commandId: "command", dispatchMode: "queue" }),
532 expect.objectContaining(compactTurn),
533 expect.objectContaining({ commandId: "command", dispatchMode: "queue" }),
534 ]);
535 expect(remaining()).toEqual([]);
536 });
537​
538 it("holds the message when its /compact cannot be sent", async () => {
539 setOperateGrant("secondary", true);
540 const queued = message({ compactBeforeSend: true, dispatchMode: "queue" });
541 await state.manager.enqueue(queued);
542 state.start.mockResolvedValueOnce(
543 AsyncResult.failure(Cause.fail(new Error("Socket is not connected"))),
544 );
545 await runDrain();
546 expect(state.start).toHaveBeenCalledOnce();
547 expect(state.start.mock.calls[0]?.[0].input).toMatchObject(compactTurn);
548 expect(remaining()).toEqual([queued]);
549 });
550});