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: { 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 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.start.mockResolvedValue(AsyncResult.success({}));
228 state.prepare.mockReset().mockImplementation(async ({ attachments }) => ({
229 status: "ready",
230 attachments: [],
231 draftAttachments: attachments,
232 pendingAttachmentIds: [],
233 }));
234});
235
236describe("queued PR checkout", () => {
237 const queuedPullRequest = () =>
238 message({
239 threadId: ThreadId.make("new-pr-thread"),
240 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
241 creation: {
242 projectId: ProjectId.make("project"),
243 projectCwd: "/repo",
244 workspaceMode: "worktree",
245 branch: "fork/feature",
246 worktreePath: null,
247 pullRequestReference: "https://github.com/acme/repo/pull/123",
248 },
249 });
250 const preparedCheckout = {
251 branch: "pr-123",
252 worktreePath: "/repo/.t3/worktrees/pr-123",
253 isOnPullRequestHead: true,
254 };
255
256 it("waits for the provider's PR checkout and launches in that worktree", async () => {
257 setOperateGrant("secondary", true);
258 await state.manager.enqueue(queuedPullRequest());
259 const started = Promise.withResolvers<void>();
260 const checkout =
261 Promise.withResolvers<AsyncResult.AsyncResult<typeof preparedCheckout, Error>>();
262 state.checkout.mockImplementationOnce(() => {
263 started.resolve();
264 return checkout.promise;
265 });
266 const drained = runDrain();
267 await started.promise;
268 expect(state.start).not.toHaveBeenCalled();
269 expect(state.checkout).toHaveBeenCalledWith({
270 environmentId: "secondary",
271 input: { cwd: "/repo", reference: "https://github.com/acme/repo/pull/123", mode: "worktree" },
272 });
273 checkout.resolve(AsyncResult.success(preparedCheckout));
274 await drained;
275 expect(state.start).toHaveBeenCalledOnce();
276 const bootstrap = state.start.mock.calls[0]?.[0].input.bootstrap;
277 expect(bootstrap.createThread).toMatchObject({
278 branch: "pr-123",
279 worktreePath: preparedCheckout.worktreePath,
280 });
281 expect(bootstrap.prepareWorktree).toBeUndefined();
282 expect(remaining()).toEqual([]);
283 });
284
285 it("keeps the PR source queued on a transport failure without starting the agent", async () => {
286 setOperateGrant("secondary", true);
287 const queued = queuedPullRequest();
288 await state.manager.enqueue(queued);
289 state.checkout.mockResolvedValueOnce(
290 AsyncResult.failure(Cause.fail(new Error("Socket is not connected"))),
291 );
292 await runDrain();
293 expect(state.start).not.toHaveBeenCalled();
294 expect(remaining()).toEqual([queued]);
295 });
296
297 it("stops launch if operation access is revoked while checking out the PR", async () => {
298 setOperateGrant("secondary", true);
299 const queued = queuedPullRequest();
300 await state.manager.enqueue(queued);
301 state.checkout.mockImplementationOnce(async () => {
302 setOperateGrant("secondary", false);
303 return AsyncResult.success(preparedCheckout);
304 });
305 await runDrain();
306 expect(state.start).not.toHaveBeenCalled();
307 expect(remaining()).toEqual([queued]);
308 });
309
310 it("does not launch a stale task edited while the PR checkout was running", async () => {
311 setOperateGrant("secondary", true);
312 const queued = queuedPullRequest();
313 await state.manager.enqueue(queued);
314 const edited = { ...queued, text: "Updated instructions" };
315 state.checkout.mockImplementationOnce(async () => {
316 await state.manager.update(edited);
317 return AsyncResult.success(preparedCheckout);
318 });
319 await runDrain();
320 expect(state.start).not.toHaveBeenCalled();
321 expect(remaining()).toEqual([edited]);
322 });
323});
324afterEach(() => {
325 state.cleanups.splice(0).forEach((cleanup) => cleanup());
326});
327
328describe("queued task operation access", () => {
329 it("parks a connected read-only target, then delivers its unchanged queue after a grant", async () => {
330 const queued = message();
331 await state.manager.enqueue(queued);
332 startDelivery();
333 expect(state.start).not.toHaveBeenCalled();
334 expect(state.prepare).not.toHaveBeenCalled();
335 expect(remaining()).toEqual([queued]);
336 setOperateGrant("secondary", true);
337 await runDrain();
338 expect(state.start).toHaveBeenCalledOnce();
339 expect(remaining()).toEqual([]);
340 });
341
342 it("backs off instead of redelivering at once when a delivery hits a defect", async () => {
343 setOperateGrant("secondary", true);
344 const queued = message();
345 await state.manager.enqueue(queued);
346 // Awaited steps catch their own failures, so a defect in the delivery's own code is what
347 // rejects a delivery.
348 state.modelUnavailable.mockImplementationOnce(() => {
349 throw new TypeError("Cannot read properties of undefined");
350 });
351 await runDrain();
352 expect(state.modelUnavailable).toHaveBeenCalledOnce();
353 expect(state.prepare).not.toHaveBeenCalled();
354 expect(state.start).not.toHaveBeenCalled();
355 expect(appAtomRegistry.get(dispatchingQueuedMessageIdAtom)).toBeNull();
356 expect(remaining()).toEqual([queued]);
357 });
358
359 it("starts one delivery when mounting a thread family changes the rows mid-pass", async () => {
360 setOperateGrant("secondary", true);
361 state.config.shellThreadFamilies = true;
362 const subAgentThread = { ...state.thread, id: "sub-agent" };
363 // A cached family merges its rows into the shell list as soon as it is mounted.
364 state.familyMount.mockImplementationOnce(() => {
365 appAtomRegistry.set(state.threadShells, [state.thread, subAgentThread]);
366 return () => {};
367 });
368 const queued = message({ threadId: ThreadId.make("sub-agent") });
369 startDelivery();
370 appAtomRegistry.set(editingQueuedMessageIdsAtom, { [queued.messageId]: true });
371 await state.manager.enqueue(queued);
372 using confirm = vi.spyOn(state.manager, "confirmQueued");
373 const delivered = Promise.withResolvers<void>();
374 const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdAtom, (id) => {
375 if (id === null) delivered.resolve();
376 });
377 // Ending the edit wakes the drain through a registry notification, the path on which the
378 // mount's synchronous row change notifies the drain again mid-pass.
379 appAtomRegistry.set(editingQueuedMessageIdsAtom, {});
380 expect(state.familyMount).toHaveBeenCalledOnce();
381 expect(confirm).toHaveBeenCalledOnce();
382 await delivered.promise.finally(release);
383 expect(state.start).toHaveBeenCalledOnce();
384 expect(remaining()).toEqual([]);
385 });
386
387 it("stops the remaining settings and turn commands when an earlier update loses access", async () => {
388 setOperateGrant("secondary", true);
389 const queued = message({
390 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "different-model" },
391 runtimeMode: "approval-required",
392 interactionMode: "plan",
393 });
394 await state.manager.enqueue(queued);
395 state.runtime.mockImplementationOnce(async () => {
396 setOperateGrant("secondary", false);
397 return AsyncResult.success(undefined);
398 });
399 await runDrain();
400 expect(state.runtime).toHaveBeenCalledOnce();
401 expect(state.interaction).not.toHaveBeenCalled();
402 expect(state.prepare).not.toHaveBeenCalled();
403 expect(state.start).not.toHaveBeenCalled();
404 expect(remaining()).toEqual([queued]);
405 });
406
407 it.each([
408 { isCreation: false, accepted: false },
409 { isCreation: true, accepted: true },
410 ])(
411 "preserves a rejected queue but removes an accepted turn after access loss (new task: $isCreation, accepted: $accepted)",
412 async ({ isCreation, accepted }) => {
413 setOperateGrant("secondary", true);
414 const queued = message(
415 isCreation
416 ? {
417 threadId: ThreadId.make("new-thread"),
418 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
419 creation: {
420 projectId: ProjectId.make("project"),
421 projectCwd: "/repo",
422 workspaceMode: "local",
423 branch: null,
424 worktreePath: null,
425 },
426 }
427 : {},
428 );
429 await state.manager.enqueue(queued);
430 const started = Promise.withResolvers<void>();
431 const delivery =
432 Promise.withResolvers<AsyncResult.AsyncResult<{ readonly sequence?: number }, Error>>();
433 state.start.mockImplementationOnce(() => {
434 started.resolve();
435 return delivery.promise;
436 });
437 const drained = runDrain();
438 await started.promise;
439 setOperateGrant("secondary", false);
440 delivery.resolve(
441 accepted
442 ? AsyncResult.success({})
443 : AsyncResult.failure(Cause.fail(new Error("This connection cannot control this task."))),
444 );
445 await drained;
446
447 expect(remaining()).toEqual(accepted ? [] : [queued]);
448 expect(state.draftText).toBe("Keep this draft separate");
449 if (!accepted) {
450 setOperateGrant("secondary", true);
451 await runDrain();
452 expect(state.start).toHaveBeenCalledTimes(2);
453 expect(remaining()).toEqual([]);
454 expect(state.draftText).toBe("Keep this draft separate");
455 }
456 },
457 );
458
459 it.each([
460 { isCreation: false, uploadFails: false },
461 { isCreation: true, uploadFails: false },
462 { isCreation: false, uploadFails: true },
463 { isCreation: true, uploadFails: true },
464 ])(
465 "keeps the message queued after upload revocation (new task: $isCreation, upload fails: $uploadFails)",
466 async ({ isCreation, uploadFails }) => {
467 setOperateGrant("secondary", true);
468 const queued = message(
469 isCreation
470 ? {
471 threadId: ThreadId.make("new-thread"),
472 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
473 creation: {
474 projectId: ProjectId.make("project"),
475 projectCwd: "/repo",
476 workspaceMode: "local",
477 branch: null,
478 worktreePath: null,
479 },
480 }
481 : {},
482 );
483 await state.manager.enqueue(queued);
484 state.prepare.mockImplementationOnce(async ({ attachments }) => {
485 setOperateGrant("secondary", false);
486 if (uploadFails) throw new Error("This connection cannot upload attachments.");
487 return {
488 status: "ready",
489 attachments: [],
490 draftAttachments: attachments,
491 pendingAttachmentIds: [],
492 };
493 });
494 await runDrain();
495 expect(state.prepare).toHaveBeenCalledOnce();
496 expect(state.start).not.toHaveBeenCalled();
497 expect(remaining()).toEqual([queued]);
498 },
499 );
500});