Open History to see the last commit
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: { threadAtom: () => 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 undoComposerDraftMerge: vi.fn(),
155 updateComposerDraftSettings: vi.fn(),
156 waitForComposerDraftsLoaded: vi.fn(),
157 };
158});
159
160import { appAtomRegistry } from "./atom-registry";
161import { environmentSession } from "./session";
162import { dispatchingQueuedMessageIdAtom, editingQueuedMessageIdsAtom } from "./use-thread-outbox";
163import { createThreadOutboxDelivery } from "./threadOutboxDelivery";
164
165const message = (overrides: Partial<QueuedThreadMessage> = {}): QueuedThreadMessage => ({
166 environmentId: EnvironmentId.make("secondary"),
167 threadId: ThreadId.make("thread"),
168 commandId: CommandId.make("command"),
169 messageId: MessageId.make("message"),
170 text: "Keep this queued",
171 attachments: [],
172 createdAt: "2026-09-05T00:00:00.000Z",
173 ...overrides,
174});
175const remaining = () =>
176 Object.values(appAtomRegistry.get(state.manager.queuedMessagesByThreadKeyAtom)).flat();
177
178function setOperateGrant(environmentId: string, granted: boolean): void {
179 // The mocked session atom holds the grant itself (see the ./session mock).
180 const sessionAtom = environmentSession.sessionStateAtom(EnvironmentId.make(environmentId));
181 appAtomRegistry.set(sessionAtom as unknown as Atom.Writable<boolean>, granted);
182}
183
184function runDrain() {
185 const settled = Promise.withResolvers<void>();
186 const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdAtom, (id) => {
187 if (id === null) settled.resolve();
188 });
189 startDelivery();
190 return settled.promise.finally(release);
191}
192
193/** Starts the service once per test; later calls run another drain pass. */
194function startDelivery(): void {
195 if (state.delivery !== null) {
196 state.delivery.drain();
197 return;
198 }
199 const delivery = createThreadOutboxDelivery();
200 state.delivery = delivery;
201 state.cleanups.push(() => {
202 delivery.dispose();
203 state.delivery = null;
204 });
205}
206
207beforeEach(() => {
208 setOperateGrant("primary", true);
209 setOperateGrant("secondary", false);
210 state.draftText = "Keep this draft separate";
211 state.config.shellThreadFamilies = false;
212 state.modelUnavailable.mockReset().mockReturnValue(false);
213 state.familyMount.mockReset().mockReturnValue(() => {});
214 appAtomRegistry.set(state.threadShells, [state.thread]);
215 appAtomRegistry.set(state.manager.queuedMessagesByThreadKeyAtom, {});
216 appAtomRegistry.set(dispatchingQueuedMessageIdAtom, null);
217 appAtomRegistry.set(editingQueuedMessageIdsAtom, {});
218 for (const command of [
219 state.start,
220 state.metadata,
221 state.runtime,
222 state.interaction,
223 state.checkout,
224 ]) {
225 command.mockReset().mockResolvedValue(AsyncResult.success(undefined));
226 }
227 state.prepare.mockReset().mockImplementation(async ({ attachments }) => ({
228 status: "ready",
229 attachments: [],
230 draftAttachments: attachments,
231 pendingAttachmentIds: [],
232 }));
233});
234
235describe("queued PR checkout", () => {
236 const queuedPullRequest = () =>
237 message({
238 threadId: ThreadId.make("new-pr-thread"),
239 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
240 creation: {
241 projectId: ProjectId.make("project"),
242 projectCwd: "/repo",
243 workspaceMode: "worktree",
244 branch: "fork/feature",
245 worktreePath: null,
246 pullRequestReference: "https://github.com/acme/repo/pull/123",
247 },
248 });
249 const preparedCheckout = {
250 branch: "pr-123",
251 worktreePath: "/repo/.t3/worktrees/pr-123",
252 isOnPullRequestHead: true,
253 };
254
255 it("waits for the provider's PR checkout and launches in that worktree", async () => {
256 setOperateGrant("secondary", true);
257 await state.manager.enqueue(queuedPullRequest());
258 const started = Promise.withResolvers<void>();
259 const checkout =
260 Promise.withResolvers<AsyncResult.AsyncResult<typeof preparedCheckout, Error>>();
261 state.checkout.mockImplementationOnce(() => {
262 started.resolve();
263 return checkout.promise;
264 });
265 const drained = runDrain();
266 await started.promise;
267 expect(state.start).not.toHaveBeenCalled();
268 expect(state.checkout).toHaveBeenCalledWith({
269 environmentId: "secondary",
270 input: { cwd: "/repo", reference: "https://github.com/acme/repo/pull/123", mode: "worktree" },
271 });
272 checkout.resolve(AsyncResult.success(preparedCheckout));
273 await drained;
274 expect(state.start).toHaveBeenCalledOnce();
275 const bootstrap = state.start.mock.calls[0]?.[0].input.bootstrap;
276 expect(bootstrap.createThread).toMatchObject({
277 branch: "pr-123",
278 worktreePath: preparedCheckout.worktreePath,
279 });
280 expect(bootstrap.prepareWorktree).toBeUndefined();
281 expect(remaining()).toEqual([]);
282 });
283
284 it("keeps the PR source queued on a transport failure without starting the agent", async () => {
285 setOperateGrant("secondary", true);
286 const queued = queuedPullRequest();
287 await state.manager.enqueue(queued);
288 state.checkout.mockResolvedValueOnce(
289 AsyncResult.failure(Cause.fail(new Error("Socket is not connected"))),
290 );
291 await runDrain();
292 expect(state.start).not.toHaveBeenCalled();
293 expect(remaining()).toEqual([queued]);
294 });
295
296 it("stops launch if operation access is revoked while checking out the PR", async () => {
297 setOperateGrant("secondary", true);
298 const queued = queuedPullRequest();
299 await state.manager.enqueue(queued);
300 state.checkout.mockImplementationOnce(async () => {
301 setOperateGrant("secondary", false);
302 return AsyncResult.success(preparedCheckout);
303 });
304 await runDrain();
305 expect(state.start).not.toHaveBeenCalled();
306 expect(remaining()).toEqual([queued]);
307 });
308
309 it("does not launch a stale task edited while the PR checkout was running", async () => {
310 setOperateGrant("secondary", true);
311 const queued = queuedPullRequest();
312 await state.manager.enqueue(queued);
313 const edited = { ...queued, text: "Updated instructions" };
314 state.checkout.mockImplementationOnce(async () => {
315 await state.manager.update(edited);
316 return AsyncResult.success(preparedCheckout);
317 });
318 await runDrain();
319 expect(state.start).not.toHaveBeenCalled();
320 expect(remaining()).toEqual([edited]);
321 });
322});
323afterEach(() => {
324 state.cleanups.splice(0).forEach((cleanup) => cleanup());
325});
326
327describe("queued task operation access", () => {
328 it("parks a connected read-only target, then delivers its unchanged queue after a grant", async () => {
329 const queued = message();
330 await state.manager.enqueue(queued);
331 startDelivery();
332 expect(state.start).not.toHaveBeenCalled();
333 expect(state.prepare).not.toHaveBeenCalled();
334 expect(remaining()).toEqual([queued]);
335 setOperateGrant("secondary", true);
336 await runDrain();
337 expect(state.start).toHaveBeenCalledOnce();
338 expect(remaining()).toEqual([]);
339 });
340
341 it("backs off instead of redelivering at once when a delivery hits a defect", async () => {
342 setOperateGrant("secondary", true);
343 const queued = message();
344 await state.manager.enqueue(queued);
345 // Awaited steps catch their own failures, so a defect in the delivery's own code is what
346 // rejects a delivery.
347 state.modelUnavailable.mockImplementationOnce(() => {
348 throw new TypeError("Cannot read properties of undefined");
349 });
350 await runDrain();
351 expect(state.modelUnavailable).toHaveBeenCalledOnce();
352 expect(state.prepare).not.toHaveBeenCalled();
353 expect(state.start).not.toHaveBeenCalled();
354 expect(appAtomRegistry.get(dispatchingQueuedMessageIdAtom)).toBeNull();
355 expect(remaining()).toEqual([queued]);
356 });
357
358 it("starts one delivery when mounting a thread family changes the rows mid-pass", async () => {
359 setOperateGrant("secondary", true);
360 state.config.shellThreadFamilies = true;
361 const subAgentThread = { ...state.thread, id: "sub-agent" };
362 // A cached family merges its rows into the shell list as soon as it is mounted.
363 state.familyMount.mockImplementationOnce(() => {
364 appAtomRegistry.set(state.threadShells, [state.thread, subAgentThread]);
365 return () => {};
366 });
367 const queued = message({ threadId: ThreadId.make("sub-agent") });
368 startDelivery();
369 appAtomRegistry.set(editingQueuedMessageIdsAtom, { [queued.messageId]: true });
370 await state.manager.enqueue(queued);
371 using confirm = vi.spyOn(state.manager, "confirmQueued");
372 const delivered = Promise.withResolvers<void>();
373 const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdAtom, (id) => {
374 if (id === null) delivered.resolve();
375 });
376 // Ending the edit wakes the drain through a registry notification, the path on which the
377 // mount's synchronous row change notifies the drain again mid-pass.
378 appAtomRegistry.set(editingQueuedMessageIdsAtom, {});
379 expect(state.familyMount).toHaveBeenCalledOnce();
380 expect(confirm).toHaveBeenCalledOnce();
381 await delivered.promise.finally(release);
382 expect(state.start).toHaveBeenCalledOnce();
383 expect(remaining()).toEqual([]);
384 });
385
386 it("stops the remaining settings and turn commands when an earlier update loses access", async () => {
387 setOperateGrant("secondary", true);
388 const queued = message({
389 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "different-model" },
390 runtimeMode: "approval-required",
391 interactionMode: "plan",
392 });
393 await state.manager.enqueue(queued);
394 state.runtime.mockImplementationOnce(async () => {
395 setOperateGrant("secondary", false);
396 return AsyncResult.success(undefined);
397 });
398 await runDrain();
399 expect(state.runtime).toHaveBeenCalledOnce();
400 expect(state.interaction).not.toHaveBeenCalled();
401 expect(state.prepare).not.toHaveBeenCalled();
402 expect(state.start).not.toHaveBeenCalled();
403 expect(remaining()).toEqual([queued]);
404 });
405
406 it.each([
407 { isCreation: false, accepted: false },
408 { isCreation: true, accepted: true },
409 ])(
410 "preserves a rejected queue but removes an accepted turn after access loss (new task: $isCreation, accepted: $accepted)",
411 async ({ isCreation, accepted }) => {
412 setOperateGrant("secondary", true);
413 const queued = message(
414 isCreation
415 ? {
416 threadId: ThreadId.make("new-thread"),
417 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
418 creation: {
419 projectId: ProjectId.make("project"),
420 projectCwd: "/repo",
421 workspaceMode: "local",
422 branch: null,
423 worktreePath: null,
424 },
425 }
426 : {},
427 );
428 await state.manager.enqueue(queued);
429 const started = Promise.withResolvers<void>();
430 const delivery = Promise.withResolvers<AsyncResult.AsyncResult<void, Error>>();
431 state.start.mockImplementationOnce(() => {
432 started.resolve();
433 return delivery.promise;
434 });
435 const drained = runDrain();
436 await started.promise;
437 setOperateGrant("secondary", false);
438 delivery.resolve(
439 accepted
440 ? AsyncResult.success(undefined)
441 : AsyncResult.failure(Cause.fail(new Error("This connection cannot control this task."))),
442 );
443 await drained;
444
445 expect(remaining()).toEqual(accepted ? [] : [queued]);
446 expect(state.draftText).toBe("Keep this draft separate");
447 if (!accepted) {
448 setOperateGrant("secondary", true);
449 await runDrain();
450 expect(state.start).toHaveBeenCalledTimes(2);
451 expect(remaining()).toEqual([]);
452 expect(state.draftText).toBe("Keep this draft separate");
453 }
454 },
455 );
456
457 it.each([
458 { isCreation: false, uploadFails: false },
459 { isCreation: true, uploadFails: false },
460 { isCreation: false, uploadFails: true },
461 { isCreation: true, uploadFails: true },
462 ])(
463 "keeps the message queued after upload revocation (new task: $isCreation, upload fails: $uploadFails)",
464 async ({ isCreation, uploadFails }) => {
465 setOperateGrant("secondary", true);
466 const queued = message(
467 isCreation
468 ? {
469 threadId: ThreadId.make("new-thread"),
470 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
471 creation: {
472 projectId: ProjectId.make("project"),
473 projectCwd: "/repo",
474 workspaceMode: "local",
475 branch: null,
476 worktreePath: null,
477 },
478 }
479 : {},
480 );
481 await state.manager.enqueue(queued);
482 state.prepare.mockImplementationOnce(async ({ attachments }) => {
483 setOperateGrant("secondary", false);
484 if (uploadFails) throw new Error("This connection cannot upload attachments.");
485 return {
486 status: "ready",
487 attachments: [],
488 draftAttachments: attachments,
489 pendingAttachmentIds: [],
490 };
491 });
492 await runDrain();
493 expect(state.prepare).toHaveBeenCalledOnce();
494 expect(state.start).not.toHaveBeenCalled();
495 expect(remaining()).toEqual([queued]);
496 },
497 );
498});