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

threadOutboxDelivery.permissions.test.ts

779 lines30.0 KB

1import {
2 AuthOrchestrationOperateScope,
3 CommandId,
4 EnvironmentId,
5 MessageId,
6 ProjectId,
7 ProviderInstanceId,
8 ThreadId,
9} from "@t3tools/contracts";
10import { attachmentUploadError } from "@t3tools/client-runtime/state/attachment-uploads";
11import * as Effect from "effect/Effect";
12import * as Cause from "effect/Cause";
13import { AsyncResult, type Atom } from "effect/reactivity";
14import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
15import { threadOutboxRetryDelayMs, type QueuedThreadMessage } from "./thread-outbox-model";
16​
17const state = vi.hoisted(() => ({
18 draftText: "Keep this draft separate",
19 cleanups: [] as Array<() => void>,
20 delivery: null as {
21 readonly drain: () => void;
22 readonly dispose: () => void;
23 } | null,
24 start: vi.fn(),
25 metadata: vi.fn(),
26 runtime: vi.fn(),
27 interaction: vi.fn(),
28 prepare: vi.fn(),
29 checkout: vi.fn(),
30 modelUnavailable: vi.fn(() => false),
31 familyMount: vi.fn(() => () => {}),
32 threadShells: null as unknown as Atom.Writable<ReadonlyArray<unknown>>,
33 manager: null as unknown as ReturnType<
34 typeof import("./thread-outbox-manager").createThreadOutboxManager
35 >,
36 thread: {
37 environmentId: "secondary",
38 id: "thread",
39 modelSelection: { instanceId: "codex", model: "gpt-5.4" },
40 runtimeMode: "full-access",
41 interactionMode: "default",
42 session: null,
43 },
44 config: {
45 shellThreadFamilies: false,
46 providers: [{ instanceId: "codex", driver: "codex", models: [] }],
47 environment: { capabilities: {} },
48 },
49}));
50vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
51vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({
52 ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
53 runAtomCommand: (_registry: unknown, command: (input: unknown) => unknown, input: unknown) =>
54 command(input),
55}));
56vi.mock("./session", async () => {
57 const { Atom } = await import("effect/reactivity");
58 const { appAtomRegistry } = await import("./atom-registry");
59 // A session's state is reduced to whether it grants the operate scope.
60 const sessionStateAtom = Atom.family((_id: string) => Atom.make(false).pipe(Atom.keepAlive));
61 const sessionHasScope = (granted: boolean, scope: string) =>
62 granted && scope === AuthOrchestrationOperateScope;
63 return {
64 environmentSession: { sessionStateAtom },
65 sessionHasScope,
66 readEnvironmentScope: (environmentId: string, scope: string) =>
67 sessionHasScope(appAtomRegistry.get(sessionStateAtom(environmentId)), scope),
68 };
69});
70vi.mock("./projects", async () => {
71 const { Atom } = await import("effect/reactivity");
72 return { environmentProjects: { projectsAtom: Atom.make([]) } };
73});
74vi.mock("./workspace", async () => {
75 const { Atom } = await import("effect/reactivity");
76 return {
77 workspaceConnections: {
78 environmentsAtom: Atom.make([{ environmentId: "secondary", connectionState: "connected" }]),
79 },
80 };
81});
82vi.mock("./server", async () => {
83 const { Atom } = await import("effect/reactivity");
84 return {
85 serverEnvironment: { configValueAtom: Atom.family((_id: string) => Atom.make(state.config)) },
86 environmentServerConfigsAtom: Atom.make(new Map([["secondary", state.config]])),
87 };
88});
89vi.mock("./threads", async () => {
90 const { Atom, AsyncResult } = await import("effect/reactivity");
91 state.threadShells = Atom.make<ReadonlyArray<unknown>>([state.thread]).pipe(Atom.keepAlive);
92 return {
93 threadEnvironment: {
94 startTurn: state.start,
95 updateMetadata: state.metadata,
96 setRuntimeMode: state.runtime,
97 setInteractionMode: state.interaction,
98 },
99 environmentThreadShells: { threadShellsAtom: state.threadShells },
100 threadFamilies: {
101 mount: state.familyMount,
102 familyAtom: () => Atom.make(AsyncResult.success({})),
103 refresh: vi.fn(),
104 },
105 environmentThreadDetails: { stateAtom: () => Atom.make(null) },
106 };
107});
108vi.mock("./git", () => ({ gitEnvironment: { preparePullRequestThread: state.checkout } }));
109vi.mock("../lib/modelOptions", () => ({ isModelSelectionUnavailable: state.modelUnavailable }));
110vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "abcd" }));
111vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: state.prepare }));
112vi.mock("./composer-attachment-uploads", () => ({ uploadComposerAttachmentShared: vi.fn() }));
113vi.mock("./thread-outbox", async () => {
114 const { createThreadOutboxManager } = await import("./thread-outbox-manager");
115 const { appAtomRegistry } = await import("./atom-registry");
116 state.manager = createThreadOutboxManager({
117 registry: appAtomRegistry,
118 storage: {
119 load: async () => ({ messages: [], errors: [] }),
120 write: async () => {},
121 remove: async () => {},
122 },
123 });
124 return {
125 threadOutboxManager: state.manager,
126 threadOutboxRevision: (id: MessageId) => state.manager.revisionOf(id),
127 confirmThreadOutboxMessageQueued: (message: QueuedThreadMessage) =>
128 state.manager.confirmQueued(message),
129 updateThreadOutboxMessage: (message: QueuedThreadMessage, revision?: number) =>
130 state.manager.update(message, revision),
131 };
132});
133vi.mock("./thread-outbox-removal", () => ({
134 removeThreadOutboxMessage: (message: QueuedThreadMessage, revision?: number) =>
135 state.manager.remove(message, revision),
136}));
137vi.mock("./use-thread-outbox", async () => {
138 const { Atom } = await import("effect/reactivity");
139 return {
140 editingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive),
141 dispatchingQueuedMessageIdsAtom: Atom.make<Readonly<Record<MessageId, true>>>({}).pipe(
142 Atom.keepAlive,
143 ),
144 retryingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive),
145 threadOutboxShellStatusesAtom: Atom.make(new Map([["secondary", "live"]])),
146 };
147});
148vi.mock("./use-composer-drafts", async () => {
149 const { Atom } = await import("effect/reactivity");
150 return {
151 composerDraftsAtom: Atom.make({}),
152 removeDeliveredCloudQueuedMessage: async () => {},
153 appendComposerDraftAttachments: vi.fn(),
154 flushComposerDrafts: vi.fn(async () => {}),
155 getComposerDraftSnapshot: vi.fn(() => ({ text: state.draftText, attachments: [] })),
156 mergeComposerDraftContent: vi.fn(async (_key: string, input: { text: string }) => {
157 state.draftText += `\n${input.text}`;
158 }),
159 replaceComposerDraftAttachments: vi.fn(),
160 setFreshSessionPending: vi.fn(),
161 undoComposerDraftMerge: vi.fn(),
162 updateComposerDraftSettings: vi.fn(),
163 waitForComposerDraftsLoaded: vi.fn(),
164 };
165});
166​
167import { appAtomRegistry } from "./atom-registry";
168import { environmentSession } from "./session";
169import { dispatchingQueuedMessageIdsAtom, editingQueuedMessageIdsAtom } from "./use-thread-outbox";
170​
171const sendingMessageIds = () => Object.keys(appAtomRegistry.get(dispatchingQueuedMessageIdsAtom));
172import { createThreadOutboxDelivery } from "./threadOutboxDelivery";
173import { workspaceConnections } from "./workspace";
174​
175const message = (overrides: Partial<QueuedThreadMessage> = {}): QueuedThreadMessage => ({
176 environmentId: EnvironmentId.make("secondary"),
177 threadId: ThreadId.make("thread"),
178 commandId: CommandId.make("command"),
179 messageId: MessageId.make("message"),
180 text: "Keep this queued",
181 attachments: [],
182 createdAt: "2026-09-05T00:00:00.000Z",
183 ...overrides,
184});
185const remaining = () =>
186 Object.values(appAtomRegistry.get(state.manager.queuedMessagesByThreadKeyAtom)).flat();
187​
188function setOperateGrant(environmentId: string, granted: boolean): void {
189 // The mocked session atom holds the grant itself (see the ./session mock).
190 const sessionAtom = environmentSession.sessionStateAtom(EnvironmentId.make(environmentId));
191 appAtomRegistry.set(sessionAtom as unknown as Atom.Writable<boolean>, granted);
193​
194function runDrain() {
195 const settled = Promise.withResolvers<void>();
196 const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdsAtom, (ids) => {
197 if (Object.keys(ids).length === 0) settled.resolve();
198 });
199 startDelivery();
200 return settled.promise.finally(release);
202​
203/** Starts the service once per test; later calls run another drain pass. */
204function startDelivery(): void {
205 if (state.delivery !== null) {
206 state.delivery.drain();
207 return;
208 }
209 const delivery = createThreadOutboxDelivery();
210 state.delivery = delivery;
211 state.cleanups.push(() => {
212 delivery.dispose();
213 state.delivery = null;
214 });
216​
217beforeEach(() => {
218 setOperateGrant("primary", true);
219 setOperateGrant("secondary", false);
220 state.draftText = "Keep this draft separate";
221 state.config.shellThreadFamilies = false;
222 state.modelUnavailable.mockReset().mockReturnValue(false);
223 state.familyMount.mockReset().mockReturnValue(() => {});
224 appAtomRegistry.set(state.threadShells, [state.thread]);
225 appAtomRegistry.set(state.manager.queuedMessagesByThreadKeyAtom, {});
226 appAtomRegistry.set(dispatchingQueuedMessageIdsAtom, {});
227 appAtomRegistry.set(editingQueuedMessageIdsAtom, {});
228 for (const command of [
229 state.start,
230 state.metadata,
231 state.runtime,
232 state.interaction,
233 state.checkout,
234 ]) {
235 command.mockReset().mockResolvedValue(AsyncResult.success(undefined));
236 }
237 state.start.mockResolvedValue(AsyncResult.success({}));
238 state.prepare.mockReset().mockImplementation(({ attachments }) =>
239 Effect.succeed({
240 status: "ready",
241 attachments: [],
242 draftAttachments: attachments,
243 pendingAttachmentIds: [],
244 }),
245 );
246});
247​
248describe("queued PR checkout", () => {
249 const queuedPullRequest = () =>
250 message({
251 threadId: ThreadId.make("new-pr-thread"),
252 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
253 creation: {
254 projectId: ProjectId.make("project"),
255 projectCwd: "/repo",
256 workspaceMode: "worktree",
257 branch: "fork/feature",
258 worktreePath: null,
259 pullRequestReference: "https://github.com/acme/repo/pull/123",
260 },
261 });
262 const preparedCheckout = {
263 branch: "pr-123",
264 worktreePath: "/repo/.t3/worktrees/pr-123",
265 isOnPullRequestHead: true,
266 };
267​
268 it("waits for the provider's PR checkout and launches in that worktree", async () => {
269 setOperateGrant("secondary", true);
270 await state.manager.enqueue(queuedPullRequest());
271 const started = Promise.withResolvers<void>();
272 const checkout =
273 Promise.withResolvers<AsyncResult.AsyncResult<typeof preparedCheckout, Error>>();
274 state.checkout.mockImplementationOnce(() => {
275 started.resolve();
276 return checkout.promise;
277 });
278 const drained = runDrain();
279 await started.promise;
280 expect(state.start).not.toHaveBeenCalled();
281 expect(state.checkout).toHaveBeenCalledWith({
282 environmentId: "secondary",
283 input: { cwd: "/repo", reference: "https://github.com/acme/repo/pull/123", mode: "worktree" },
284 });
285 checkout.resolve(AsyncResult.success(preparedCheckout));
286 await drained;
287 expect(state.start).toHaveBeenCalledOnce();
288 const bootstrap = state.start.mock.calls[0]?.[0].input.bootstrap;
289 expect(bootstrap.createThread).toMatchObject({
290 branch: "pr-123",
291 worktreePath: preparedCheckout.worktreePath,
292 });
293 expect(bootstrap.prepareWorktree).toBeUndefined();
294 expect(remaining()).toEqual([]);
295 });
296​
297 it("keeps the PR source queued on a transport failure without starting the agent", async () => {
298 setOperateGrant("secondary", true);
299 const queued = queuedPullRequest();
300 await state.manager.enqueue(queued);
301 state.checkout.mockResolvedValueOnce(
302 AsyncResult.failure(Cause.fail(new Error("Socket is not connected"))),
303 );
304 await runDrain();
305 expect(state.start).not.toHaveBeenCalled();
306 expect(remaining()).toEqual([queued]);
307 });
308​
309 it("stops launch if operation access is revoked while checking out the PR", async () => {
310 setOperateGrant("secondary", true);
311 const queued = queuedPullRequest();
312 await state.manager.enqueue(queued);
313 state.checkout.mockImplementationOnce(async () => {
314 setOperateGrant("secondary", false);
315 return AsyncResult.success(preparedCheckout);
316 });
317 await runDrain();
318 expect(state.start).not.toHaveBeenCalled();
319 expect(remaining()).toEqual([queued]);
320 });
321​
322 it("does not launch a stale task edited while the PR checkout was running", async () => {
323 setOperateGrant("secondary", true);
324 const queued = queuedPullRequest();
325 await state.manager.enqueue(queued);
326 const edited = { ...queued, text: "Updated instructions" };
327 state.checkout.mockImplementationOnce(async () => {
328 await state.manager.update(edited);
329 return AsyncResult.success(preparedCheckout);
330 });
331 await runDrain();
332 expect(state.start).not.toHaveBeenCalled();
333 expect(remaining()).toEqual([edited]);
334 });
335});
336afterEach(() => {
337 state.cleanups.splice(0).forEach((cleanup) => cleanup());
338});
339​
340describe("queued task operation access", () => {
341 it("parks a connected read-only target, then delivers its unchanged queue after a grant", async () => {
342 const queued = message();
343 await state.manager.enqueue(queued);
344 startDelivery();
345 expect(state.start).not.toHaveBeenCalled();
346 expect(state.prepare).not.toHaveBeenCalled();
347 expect(remaining()).toEqual([queued]);
348 setOperateGrant("secondary", true);
349 await runDrain();
350 expect(state.start).toHaveBeenCalledOnce();
351 expect(remaining()).toEqual([]);
352 });
353​
354 it("backs off instead of redelivering at once when a delivery hits a defect", async () => {
355 setOperateGrant("secondary", true);
356 const queued = message();
357 await state.manager.enqueue(queued);
358 // Awaited steps catch their own failures, so a defect in the delivery's own code is what
359 // rejects a delivery.
360 state.modelUnavailable.mockImplementationOnce(() => {
361 throw new TypeError("Cannot read properties of undefined");
362 });
363 await runDrain();
364 expect(state.modelUnavailable).toHaveBeenCalledOnce();
365 expect(state.prepare).not.toHaveBeenCalled();
366 expect(state.start).not.toHaveBeenCalled();
367 expect(sendingMessageIds()).toEqual([]);
368 expect(remaining()).toEqual([queued]);
369 });
370​
371 it("starts one delivery when mounting a thread family changes the rows mid-pass", async () => {
372 setOperateGrant("secondary", true);
373 state.config.shellThreadFamilies = true;
374 const subAgentThread = { ...state.thread, id: "sub-agent" };
375 // A cached family merges its rows into the shell list as soon as it is mounted.
376 state.familyMount.mockImplementationOnce(() => {
377 appAtomRegistry.set(state.threadShells, [state.thread, subAgentThread]);
378 return () => {};
379 });
380 const queued = message({ threadId: ThreadId.make("sub-agent") });
381 startDelivery();
382 appAtomRegistry.set(editingQueuedMessageIdsAtom, { [queued.messageId]: true });
383 await state.manager.enqueue(queued);
384 const delivered = Promise.withResolvers<void>();
385 const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdsAtom, (ids) => {
386 if (Object.keys(ids).length === 0) delivered.resolve();
387 });
388 // Ending the edit wakes the thread through a registry notification, the path on which the
389 // mount's synchronous row change wakes it again while it is deciding.
390 appAtomRegistry.set(editingQueuedMessageIdsAtom, {});
391 await delivered.promise.finally(release);
392 expect(state.familyMount).toHaveBeenCalledOnce();
393 // One fiber took the message: a second would have prepared it again.
394 expect(state.prepare).toHaveBeenCalledOnce();
395 expect(state.start).toHaveBeenCalledOnce();
396 expect(remaining()).toEqual([]);
397 });
398​
399 it("stops the remaining settings and turn commands when an earlier update loses access", async () => {
400 setOperateGrant("secondary", true);
401 const queued = message({
402 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "different-model" },
403 runtimeMode: "approval-required",
404 interactionMode: "plan",
405 });
406 await state.manager.enqueue(queued);
407 state.runtime.mockImplementationOnce(async () => {
408 setOperateGrant("secondary", false);
409 return AsyncResult.success(undefined);
410 });
411 await runDrain();
412 expect(state.runtime).toHaveBeenCalledOnce();
413 expect(state.interaction).not.toHaveBeenCalled();
414 expect(state.prepare).not.toHaveBeenCalled();
415 expect(state.start).not.toHaveBeenCalled();
416 expect(remaining()).toEqual([queued]);
417 });
418​
419 it.each([
420 { isCreation: false, accepted: false },
421 { isCreation: true, accepted: true },
422 ])(
423 "preserves a rejected queue but removes an accepted turn after access loss (new task: $isCreation, accepted: $accepted)",
424 async ({ isCreation, accepted }) => {
425 setOperateGrant("secondary", true);
426 const queued = message(
427 isCreation
428 ? {
429 threadId: ThreadId.make("new-thread"),
430 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
431 creation: {
432 projectId: ProjectId.make("project"),
433 projectCwd: "/repo",
434 workspaceMode: "local",
435 branch: null,
436 worktreePath: null,
437 },
438 }
439 : {},
440 );
441 await state.manager.enqueue(queued);
442 const started = Promise.withResolvers<void>();
443 const delivery =
444 Promise.withResolvers<AsyncResult.AsyncResult<{ readonly sequence?: number }, Error>>();
445 state.start.mockImplementationOnce(() => {
446 started.resolve();
447 return delivery.promise;
448 });
449 const drained = runDrain();
450 await started.promise;
451 setOperateGrant("secondary", false);
452 delivery.resolve(
453 accepted
454 ? AsyncResult.success({})
455 : AsyncResult.failure(Cause.fail(new Error("This connection cannot control this task."))),
456 );
457 await drained;
458​
459 expect(remaining()).toEqual(accepted ? [] : [queued]);
460 expect(state.draftText).toBe("Keep this draft separate");
461 if (!accepted) {
462 setOperateGrant("secondary", true);
463 await runDrain();
464 expect(state.start).toHaveBeenCalledTimes(2);
465 expect(remaining()).toEqual([]);
466 expect(state.draftText).toBe("Keep this draft separate");
467 }
468 },
469 );
470​
471 it.each([
472 { isCreation: false, uploadFails: false },
473 { isCreation: true, uploadFails: false },
474 { isCreation: false, uploadFails: true },
475 { isCreation: true, uploadFails: true },
476 ])(
477 "keeps the message queued after upload revocation (new task: $isCreation, upload fails: $uploadFails)",
478 async ({ isCreation, uploadFails }) => {
479 setOperateGrant("secondary", true);
480 const queued = message(
481 isCreation
482 ? {
483 threadId: ThreadId.make("new-thread"),
484 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
485 creation: {
486 projectId: ProjectId.make("project"),
487 projectCwd: "/repo",
488 workspaceMode: "local",
489 branch: null,
490 worktreePath: null,
491 },
492 }
493 : {},
494 );
495 await state.manager.enqueue(queued);
496 state.prepare.mockImplementationOnce(({ attachments }) =>
497 Effect.suspend(() => {
498 setOperateGrant("secondary", false);
499 return uploadFails
500 ? Effect.fail(
501 attachmentUploadError(new Error("This connection cannot upload attachments.")),
502 )
503 : Effect.succeed({
504 status: "ready",
505 attachments: [],
506 draftAttachments: attachments,
507 pendingAttachmentIds: [],
508 });
509 }),
510 );
511 await runDrain();
512 expect(state.prepare).toHaveBeenCalledOnce();
513 expect(state.start).not.toHaveBeenCalled();
514 expect(remaining()).toEqual([queued]);
515 },
516 );
517});
518​
519describe("queued task whose launch reply is lost", () => {
520 const queuedTask = (creation: Partial<NonNullable<QueuedThreadMessage["creation"]>> = {}) =>
521 message({
522 threadId: ThreadId.make("new-thread"),
523 text: "My dictated idea",
524 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
525 creation: {
526 projectId: ProjectId.make("project"),
527 projectCwd: "/repo",
528 workspaceMode: "local",
529 branch: null,
530 worktreePath: null,
531 ...creation,
532 },
533 });
534​
535 /** The server creates the thread, but the launch reply is lost; the thread then shows up. */
536 async function loseLaunchReply(queued: QueuedThreadMessage, edit?: string): Promise<void> {
537 setOperateGrant("secondary", true);
538 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
539 state.cleanups.push(() => vi.useRealTimers());
540 await state.manager.enqueue(queued);
541 state.start.mockImplementationOnce(async () => {
542 if (edit !== undefined) await state.manager.update({ ...queued, text: edit });
543 return AsyncResult.failure(Cause.fail(new Error("Socket is not connected")));
544 });
545 await runDrain();
546 expect(remaining()).toHaveLength(1);
547 appAtomRegistry.set(state.threadShells, [state.thread, { ...state.thread, id: "new-thread" }]);
548 }
549​
550 async function fireRetry(): Promise<void> {
551 const settled = Promise.withResolvers<void>();
552 const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdsAtom, (ids) => {
553 if (Object.keys(ids).length === 0) settled.resolve();
554 });
555 vi.advanceTimersByTime(threadOutboxRetryDelayMs(1));
556 await settled.promise.finally(release);
557 }
558​
559 it("resends an unedited launch instead of handing its text back", async () => {
560 await loseLaunchReply(queuedTask());
561 await fireRetry();
562​
563 expect(state.draftText).toBe("Keep this draft separate");
564 // The resend reuses the launch's command and message ids, so the server replays it.
565 const [first, resent] = state.start.mock.calls.map(([call]) => call.input);
566 expect(state.start).toHaveBeenCalledTimes(2);
567 expect(resent.commandId).toBe(first.commandId);
568 expect(resent.message.messageId).toBe(first.message.messageId);
569 expect(remaining()).toEqual([]);
570 });
571​
572 it("hands back a task edited while its launch was in flight", async () => {
573 await loseLaunchReply(queuedTask(), "Edited idea");
574 await fireRetry();
575​
576 expect(state.draftText).toBe("Keep this draft separate\nEdited idea");
577 expect(state.start).toHaveBeenCalledOnce();
578 expect(remaining()).toEqual([]);
579 });
580​
581 it("holds the resend while operation access is missing", async () => {
582 await loseLaunchReply(queuedTask());
583 setOperateGrant("secondary", false);
584 vi.advanceTimersByTime(threadOutboxRetryDelayMs(1));
585 expect(sendingMessageIds()).toEqual([]);
586 expect(state.start).toHaveBeenCalledOnce();
587 expect(remaining()).toHaveLength(1);
588​
589 setOperateGrant("secondary", true);
590 await runDrain();
591 expect(state.start).toHaveBeenCalledTimes(2);
592 expect(state.draftText).toBe("Keep this draft separate");
593 expect(remaining()).toEqual([]);
594 });
595​
596 it("resends a pull request task in its launched worktree without checking out again", async () => {
597 state.checkout.mockResolvedValueOnce(
598 AsyncResult.success({
599 branch: "pr-123",
600 worktreePath: "/repo/.t3/worktrees/pr-123",
601 isOnPullRequestHead: true,
602 }),
603 );
604 await loseLaunchReply(
605 queuedTask({
606 workspaceMode: "worktree",
607 branch: "fork/feature",
608 pullRequestReference: "https://github.com/acme/repo/pull/123",
609 }),
610 );
611 await fireRetry();
612​
613 expect(state.checkout).toHaveBeenCalledOnce();
614 const [first, resent] = state.start.mock.calls.map(([call]) => call.input);
615 expect(resent.bootstrap.createThread.worktreePath).toBe("/repo/.t3/worktrees/pr-123");
616 expect(resent.bootstrap).toEqual(first.bootstrap);
617 expect(remaining()).toEqual([]);
618 });
619});
620​
621describe("compaction before a queued send", () => {
622 const compactTurn = {
623 commandId: "command:compact",
624 message: {
625 messageId: "message:compact",
626 role: "user",
627 text: "/compact",
628 attachments: [],
629 idleCompaction: "onReturn",
630 },
631 dispatchMode: "queue",
632 };
633​
634 it("queues /compact ahead of the message and resends the same /compact on a retry", async () => {
635 setOperateGrant("secondary", true);
636 const queued = message({ compactBeforeSend: true, dispatchMode: "queue" });
637 await state.manager.enqueue(queued);
638 state.start
639 .mockResolvedValueOnce(AsyncResult.success({}))
640 .mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Socket is not connected"))));
641 await runDrain();
642 expect(remaining()).toEqual([queued]);
643​
644 // A restarted app delivers the persisted message again.
645 state.cleanups.splice(0).forEach((cleanup) => cleanup());
646 await runDrain();
647 expect(state.start.mock.calls.map(([call]) => call.input)).toEqual([
648 expect.objectContaining(compactTurn),
649 expect.objectContaining({ commandId: "command", dispatchMode: "queue" }),
650 expect.objectContaining(compactTurn),
651 expect.objectContaining({ commandId: "command", dispatchMode: "queue" }),
652 ]);
653 expect(remaining()).toEqual([]);
654 });
655​
656 it("holds the message when its /compact cannot be sent", async () => {
657 setOperateGrant("secondary", true);
658 const queued = message({ compactBeforeSend: true, dispatchMode: "queue" });
659 await state.manager.enqueue(queued);
660 state.start.mockResolvedValueOnce(
661 AsyncResult.failure(Cause.fail(new Error("Socket is not connected"))),
662 );
663 await runDrain();
664 expect(state.start).toHaveBeenCalledOnce();
665 expect(state.start.mock.calls[0]?.[0].input).toMatchObject(compactTurn);
666 expect(remaining()).toEqual([queued]);
667 });
668});
669​
670describe("queued delivery timing", () => {
671 /** Runs `change`, then resolves once the delivery it starts has settled. */
672 async function deliveryAfter(change: () => void): Promise<void> {
673 const started = Promise.withResolvers<void>();
674 const settled = Promise.withResolvers<void>();
675 const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdsAtom, (ids) => {
676 if (Object.keys(ids).length > 0) started.resolve();
677 else settled.resolve();
678 });
679 change();
680 await started.promise;
681 await settled.promise.finally(release);
682 }
683​
684 it("starts a thread's next message only after its interrupted send has finished", async () => {
685 setOperateGrant("secondary", true);
686 const firstStarted = Promise.withResolvers<void>();
687 const finishFirst = Promise.withResolvers<AsyncResult.AsyncResult<object, never>>();
688 state.start.mockImplementationOnce(async () => {
689 firstStarted.resolve();
690 return finishFirst.promise;
691 });
692 const first = message();
693 await state.manager.enqueue(first);
694 startDelivery();
695 await firstStarted.promise;
696 // The queue empties under the running send, then the thread gets its next message.
697 await state.manager.remove(first);
698 const allDelivered = Promise.withResolvers<void>();
699 const release = appAtomRegistry.subscribe(state.manager.queuedMessagesByThreadKeyAtom, () => {
700 if (remaining().length === 0) allDelivered.resolve();
701 });
702 await state.manager.enqueue(
703 message({ messageId: MessageId.make("next"), commandId: CommandId.make("next-command") }),
704 );
705 // The next message waits; only the interrupted send is still marked as sending.
706 expect(sendingMessageIds()).toEqual(["message"]);
707 expect(state.start).toHaveBeenCalledOnce();
708 finishFirst.resolve(AsyncResult.success({}));
709 await allDelivered.promise.finally(release);
710 expect(state.start).toHaveBeenCalledTimes(2);
711 });
712​
713 it("sends another thread's message while one thread's send is still running", async () => {
714 setOperateGrant("secondary", true);
715 const other = { ...state.thread, id: "other" };
716 appAtomRegistry.set(state.threadShells, [state.thread, other]);
717 const slowStarted = Promise.withResolvers<void>();
718 const finishSlow = Promise.withResolvers<AsyncResult.AsyncResult<object, never>>();
719 state.start.mockImplementation(async ({ input }: { input: { threadId: string } }) => {
720 if (input.threadId !== "thread") return AsyncResult.success({});
721 slowStarted.resolve();
722 return finishSlow.promise;
723 });
724 /** Resolves once only these message ids are still queued. */
725 const queuedBecomes = (ids: ReadonlyArray<string>) => {
726 const reached = Promise.withResolvers<void>();
727 const release = appAtomRegistry.subscribe(state.manager.queuedMessagesByThreadKeyAtom, () => {
728 if (
729 remaining()
730 .map((queued) => queued.messageId)
731 .join() === ids.join()
732 ) {
733 reached.resolve();
734 }
735 });
736 return reached.promise.finally(release);
737 };
738 await state.manager.enqueue(message());
739 startDelivery();
740 await slowStarted.promise;
741 const otherDelivered = queuedBecomes(["message"]);
742 await state.manager.enqueue(
743 message({
744 threadId: ThreadId.make("other"),
745 messageId: MessageId.make("other-message"),
746 commandId: CommandId.make("other-command"),
747 }),
748 );
749 await otherDelivered;
750 const allDelivered = queuedBecomes([]);
751 finishSlow.resolve(AsyncResult.success({}));
752 await allDelivered;
753 expect(state.start).toHaveBeenCalledTimes(2);
754 });
755​
756 it("sends at once when its environment reconnects instead of waiting out the backoff", async () => {
757 setOperateGrant("secondary", true);
758 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
759 state.cleanups.push(() => vi.useRealTimers());
760 const environments = workspaceConnections.environmentsAtom as unknown as Atom.Writable<
761 ReadonlyArray<{ environmentId: string; connectionState: string }>
762 >;
763 const connected = [{ environmentId: "secondary", connectionState: "connected" }];
764 state.cleanups.push(() => appAtomRegistry.set(environments, connected));
765 await state.manager.enqueue(message());
766 state.start.mockResolvedValueOnce(
767 AsyncResult.failure(Cause.fail(new Error("Socket is not connected"))),
768 );
769 await runDrain();
770 expect(state.start).toHaveBeenCalledOnce();
771​
772 appAtomRegistry.set(environments, [
773 { environmentId: "secondary", connectionState: "disconnected" },
774 ]);
775 await deliveryAfter(() => appAtomRegistry.set(environments, connected));
776 expect(state.start).toHaveBeenCalledTimes(2);
777 expect(remaining()).toEqual([]);
778 });
779});