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

use-composer-drafts.test.ts

1,317 lines43.2 KB

1import { afterEach, describe, expect, it } from "@effect/vitest";
2import {
3 CommandId,
4 EnvironmentId,
5 MessageId,
6 ProviderInstanceId,
7 ThreadId,
8} from "@t3tools/contracts";
9import { onTestFinished, vi } from "vite-plus/test";
10​
11const composerDraftFileMocks = vi.hoisted(() => {
12 let document = "";
13 let writeError: Error | null = null;
14 let releaseRead: (() => void) | null = null;
15 let readBarrier = Promise.resolve();
16 let nextWriteBarrier: Promise<void> | null = null;
17 let onWrite: (() => void) | null = null;
18 const writes: string[] = [];
19​
20 return {
21 blockRead() {
22 readBarrier = new Promise<void>((resolve) => {
23 releaseRead = resolve;
24 });
25 },
26 releaseRead() {
27 releaseRead?.();
28 releaseRead = null;
29 },
30 getDocument() {
31 return document;
32 },
33 setDocument(value: unknown) {
34 document = JSON.stringify(value);
35 },
36 setWriteError(error: Error | null) {
37 writeError = error;
38 },
39 setNextWriteBarrier(barrier: Promise<void> | null) {
40 nextWriteBarrier = barrier;
41 },
42 setOnWrite(callback: (() => void) | null) {
43 onWrite = callback;
44 },
45 getWrites(): ReadonlyArray<string> {
46 return writes;
47 },
48 resetWrites() {
49 writes.length = 0;
50 },
51 Directory: class {
52 create() {}
53 },
54 File: class {
55 exists = true;
56 parentDirectory = null;
57​
58 create() {}
59​
60 moveSync() {}
61​
62 async text() {
63 await readBarrier;
64 return document;
65 }
66​
67 write(value: string) {
68 if (writeError) {
69 throw writeError;
70 }
71 if (nextWriteBarrier) {
72 const barrier = nextWriteBarrier;
73 nextWriteBarrier = null;
74 return barrier.then(() => {
75 document = value;
76 writes.push(value);
77 onWrite?.();
78 });
79 }
80 document = value;
81 writes.push(value);
82 onWrite?.();
83 }
84 },
85 };
86});
87​
88const composerAttachmentCleanupMocks = vi.hoisted(() => ({
89 remove: vi.fn(async () => undefined),
90 releaseUploads: vi.fn(async () => undefined),
91}));
92​
93const incomingShareStorageMocks = vi.hoisted(() => ({
94 load: vi.fn<typeof import("../features/sharing/incoming-share-storage").loadIncomingShareDrafts>(
95 async () => [],
96 ),
97}));
98​
99vi.mock("expo-file-system", () => ({
100 Directory: composerDraftFileMocks.Directory,
101 File: composerDraftFileMocks.File,
102 Paths: { document: "/documents" },
103}));
104​
105vi.mock("../lib/composerImages", () => ({
106 removePersistedComposerAttachmentFile: composerAttachmentCleanupMocks.remove,
107}));
108​
109vi.mock("../lib/attachmentUpload", () => ({
110 releasePendingAttachmentUploads: composerAttachmentCleanupMocks.releaseUploads,
111}));
112​
113vi.mock("../features/sharing/incoming-share-storage", () => ({
114 loadIncomingShareDrafts: incomingShareStorageMocks.load,
115}));
116​
117import { appAtomRegistry } from "./atom-registry";
118import { threadOutboxManager } from "./thread-outbox";
119import {
120 appendComposerDraftAttachments,
121 clearComposerDraftContentState,
122 clearComposerDraftsEnvironment,
123 ComposerDraftPersistenceError,
124 composerDraftsAtom,
125 copyComposerDraftContentIfEmpty,
126 copyComposerDraftContentState,
127 decodePersistedComposerState,
128 decodePersistedComposerDrafts,
129 ensureComposerDraftsLoaded,
130 type ComposerDraft,
131 flushComposerDrafts,
132 getComposerDraftSnapshot,
133 mergeComposerDraftContentState,
134 releaseUnusedComposerAttachmentFiles,
135 removeComposerDraftsForEnvironment,
136 resetComposerDraftsLoadState,
137 restoreComposerDraftSnapshotState,
138 setComposerDraftText,
139 setStickyComposerModelSelection,
140 stickyComposerModelSelectionAtom,
141 undoComposerDraftMerge,
142 undoComposerDraftMergeState,
143} from "./use-composer-drafts";
144​
145const DRAFT: ComposerDraft = {
146 text: "hello",
147 attachments: [],
148};
149​
150afterEach(() => {
151 vi.useRealTimers();
152 resetComposerDraftsLoadState();
153 composerDraftFileMocks.setDocument("");
154 composerDraftFileMocks.setWriteError(null);
155 composerDraftFileMocks.setNextWriteBarrier(null);
156 composerDraftFileMocks.setOnWrite(null);
157 composerDraftFileMocks.resetWrites();
158 appAtomRegistry.set(composerDraftsAtom, {});
159 appAtomRegistry.set(stickyComposerModelSelectionAtom, null);
160 appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
161 composerAttachmentCleanupMocks.remove.mockClear();
162 composerAttachmentCleanupMocks.releaseUploads.mockReset();
163 composerAttachmentCleanupMocks.releaseUploads.mockResolvedValue(undefined);
164 incomingShareStorageMocks.load.mockReset();
165 incomingShareStorageMocks.load.mockResolvedValue([]);
166});
167​
168describe("mobile composer drafts", () => {
169 // Hydration is one-shot per module instance and the attachment sweep now
170 // triggers it too, so this test must observe it before any sweep test runs.
171 it("waits for persisted drafts before copying content between projects", async () => {
172 const sourceKey = "new-task:environment-1:project-1";
173 const targetKey = "new-task:environment-1:project-2";
174 const unrelatedKey = "environment-1:thread-1";
175 const source = { text: "Current task", attachments: [] } satisfies ComposerDraft;
176 const target = { text: "Persisted target", attachments: [] } satisfies ComposerDraft;
177 const unrelated = { text: "Keep me", attachments: [] } satisfies ComposerDraft;
178​
179 composerDraftFileMocks.setDocument({
180 schemaVersion: 1,
181 drafts: {
182 [targetKey]: target,
183 [unrelatedKey]: unrelated,
184 },
185 });
186 composerDraftFileMocks.blockRead();
187 appAtomRegistry.set(composerDraftsAtom, { [sourceKey]: source });
188​
189 const copy = copyComposerDraftContentIfEmpty(sourceKey, targetKey);
190 expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({ [sourceKey]: source });
191​
192 composerDraftFileMocks.releaseRead();
193 await copy;
194​
195 expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({
196 [sourceKey]: source,
197 [targetKey]: target,
198 [unrelatedKey]: unrelated,
199 });
200 });
201​
202 it("hydrates generic file attachments from their saved local paths", () => {
203 const file = {
204 id: "file-1",
205 type: "file" as const,
206 name: "report.pdf",
207 mimeType: "application/pdf",
208 sizeBytes: 42,
209 fileUri: "file:///documents/report.pdf",
210 };
211​
212 expect(
213 decodePersistedComposerDrafts({
214 schemaVersion: 1,
215 drafts: {
216 "environment-1:thread-1": { text: "Review this file", attachments: [file] },
217 },
218 }),
219 ).toEqual({
220 "environment-1:thread-1": { text: "Review this file", attachments: [file] },
221 });
222 });
223​
224 it("caps appended attachments at the send limit against the live draft", () => {
225 const makeAttachment = (id: string) => ({
226 id,
227 type: "file" as const,
228 name: `${id}.pdf`,
229 mimeType: "application/pdf",
230 sizeBytes: 42,
231 fileUri: `file:///documents/t3-composer-attachments/${id}.pdf`,
232 });
233 const existing = Array.from({ length: 7 }, (_, index) => makeAttachment(`held-${index}`));
234 appAtomRegistry.set(composerDraftsAtom, {
235 "environment-1:thread-cap": { text: "send this", attachments: existing },
236 });
237​
238 const rejected = appendComposerDraftAttachments("environment-1:thread-cap", [
239 makeAttachment("incoming-1"),
240 makeAttachment("incoming-2"),
241 ]);
242​
243 expect(rejected).toBe(1);
244 const draft = appAtomRegistry.get(composerDraftsAtom)["environment-1:thread-cap"];
245 expect(draft?.attachments).toHaveLength(8);
246 expect(draft?.attachments.at(-1)?.id).toBe("incoming-1");
247​
248 // Restore paths bypass the cap so a failed send never drops its files.
249 const overflowRejected = appendComposerDraftAttachments(
250 "environment-1:thread-cap",
251 [makeAttachment("restored-1")],
252 { allowOverflow: true },
253 );
254 expect(overflowRejected).toBe(0);
255 expect(
256 appAtomRegistry.get(composerDraftsAtom)["environment-1:thread-cap"]?.attachments,
257 ).toHaveLength(9);
258 });
259​
260 it("keeps shared attachment files until every draft releases them", async () => {
261 const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
262 onTestFinished(() => outboxLoad.mockRestore());
263 const file = {
264 id: "file-1",
265 type: "file" as const,
266 name: "report.pdf",
267 mimeType: "application/pdf",
268 sizeBytes: 42,
269 fileUri: "file:///documents/t3-composer-attachments/report.pdf",
270 };
271 appAtomRegistry.set(composerDraftsAtom, {
272 source: { text: "First draft", attachments: [file] },
273 copied: { text: "Second draft", attachments: [file] },
274 });
275​
276 await releaseUnusedComposerAttachmentFiles([file]);
277 expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
278​
279 appAtomRegistry.set(composerDraftsAtom, {
280 copied: { text: "Second draft", attachments: [file] },
281 });
282 await releaseUnusedComposerAttachmentFiles([file]);
283 expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
284​
285 appAtomRegistry.set(composerDraftsAtom, {});
286 await releaseUnusedComposerAttachmentFiles([file]);
287 expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(file.fileUri);
288 });
289​
290 it("keeps a failed-send draft's pending upload for retry", async () => {
291 const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
292 onTestFinished(() => outboxLoad.mockRestore());
293 const file = {
294 id: "file-failed-send",
295 type: "file" as const,
296 name: "report.pdf",
297 mimeType: "application/pdf",
298 sizeBytes: 42,
299 fileUri: "file:///documents/t3-composer-attachments/failed-send.pdf",
300 uploadedAttachmentId: "pending-failed-send",
301 uploadEnvironmentId: EnvironmentId.make("environment-1"),
302 };
303 appAtomRegistry.set(composerDraftsAtom, {
304 "environment-1:thread-1": { text: "Retry this send", attachments: [file] },
305 });
306​
307 await releaseUnusedComposerAttachmentFiles([file]);
308​
309 expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
310 expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled();
311 });
312​
313 it("removes an unreferenced local file and its pending upload", async () => {
314 const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
315 onTestFinished(() => outboxLoad.mockRestore());
316 const environmentId = EnvironmentId.make("environment-1");
317 const file = {
318 id: "file-discarded",
319 type: "file" as const,
320 name: "report.pdf",
321 mimeType: "application/pdf",
322 sizeBytes: 42,
323 fileUri: "file:///documents/t3-composer-attachments/discarded.pdf",
324 uploadedAttachmentId: "pending-discarded",
325 uploadEnvironmentId: environmentId,
326 };
327​
328 await releaseUnusedComposerAttachmentFiles([file]);
329​
330 expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(file.fileUri);
331 expect(composerAttachmentCleanupMocks.releaseUploads).toHaveBeenCalledWith(environmentId, [
332 "pending-discarded",
333 ]);
334 });
335​
336 it("keeps a pending upload referenced through another local file", async () => {
337 const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
338 onTestFinished(() => outboxLoad.mockRestore());
339 const environmentId = EnvironmentId.make("environment-1");
340 const discarded = {
341 id: "file-discarded-copy",
342 type: "file" as const,
343 name: "report.pdf",
344 mimeType: "application/pdf",
345 sizeBytes: 42,
346 fileUri: "file:///documents/t3-composer-attachments/discarded-copy.pdf",
347 uploadedAttachmentId: "pending-shared",
348 uploadEnvironmentId: environmentId,
349 };
350 const retained = {
351 ...discarded,
352 id: "file-retained-copy",
353 fileUri: "file:///documents/t3-composer-attachments/retained-copy.pdf",
354 };
355 appAtomRegistry.set(composerDraftsAtom, {
356 "environment-1:thread-1": { text: "Keep this copy", attachments: [retained] },
357 });
358​
359 await releaseUnusedComposerAttachmentFiles([discarded]);
360​
361 expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(discarded.fileUri);
362 expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled();
363 });
364​
365 it("completes local cleanup when pending upload deletion fails", async () => {
366 const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
367 onTestFinished(() => outboxLoad.mockRestore());
368 const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined);
369 onTestFinished(() => warning.mockRestore());
370 composerAttachmentCleanupMocks.releaseUploads.mockRejectedValueOnce(
371 new Error("environment disconnected"),
372 );
373 const file = {
374 id: "file-delete-failed",
375 type: "file" as const,
376 name: "report.pdf",
377 mimeType: "application/pdf",
378 sizeBytes: 42,
379 fileUri: "file:///documents/t3-composer-attachments/delete-failed.pdf",
380 uploadedAttachmentId: "pending-delete-failed",
381 uploadEnvironmentId: EnvironmentId.make("environment-1"),
382 };
383​
384 await expect(releaseUnusedComposerAttachmentFiles([file])).resolves.toBeUndefined();
385​
386 expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(file.fileUri);
387 expect(warning).toHaveBeenCalledWith(
388 "[composer-attachments] could not remove pending upload",
389 expect.objectContaining({ attachmentId: "pending-delete-failed" }),
390 );
391 });
392​
393 it("keeps local attachment files while an outbox message still needs them", async () => {
394 const file = {
395 id: "file-queued",
396 type: "file" as const,
397 name: "report.pdf",
398 mimeType: "application/pdf",
399 sizeBytes: 42,
400 fileUri: "file:///documents/t3-composer-attachments/report.pdf",
401 };
402 appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {
403 "environment-1:thread-1": [
404 {
405 environmentId: EnvironmentId.make("environment-1"),
406 threadId: ThreadId.make("thread-1"),
407 messageId: MessageId.make("message-1"),
408 commandId: CommandId.make("command-1"),
409 text: "Review the report",
410 attachments: [file],
411 createdAt: "2026-08-24T12:00:00.000Z",
412 },
413 ],
414 });
415​
416 await releaseUnusedComposerAttachmentFiles([file]);
417​
418 expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
419 });
420​
421 it("loads persisted outbox messages before deciding an attachment file is unused", async () => {
422 const file = {
423 id: "file-persisted",
424 type: "file" as const,
425 name: "report.pdf",
426 mimeType: "application/pdf",
427 sizeBytes: 42,
428 fileUri: "file:///documents/t3-composer-attachments/report.pdf",
429 };
430 const load = vi.spyOn(threadOutboxManager, "load").mockImplementation(async () => {
431 appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {
432 "environment-1:thread-1": [
433 {
434 environmentId: EnvironmentId.make("environment-1"),
435 threadId: ThreadId.make("thread-1"),
436 messageId: MessageId.make("message-persisted"),
437 commandId: CommandId.make("command-persisted"),
438 text: "Review the report",
439 attachments: [file],
440 createdAt: "2026-08-24T12:00:00.000Z",
441 },
442 ],
443 });
444 return true;
445 });
446​
447 try {
448 await releaseUnusedComposerAttachmentFiles([file]);
449​
450 expect(load).toHaveBeenCalledOnce();
451 expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
452 } finally {
453 load.mockRestore();
454 }
455 });
456​
457 it("keeps a file until its incoming share is consumed", async () => {
458 const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
459 onTestFinished(() => outboxLoad.mockRestore());
460 const file = {
461 id: "file-incoming",
462 type: "file" as const,
463 name: "report.pdf",
464 mimeType: "application/pdf",
465 sizeBytes: 42,
466 fileUri: "file:///documents/t3-composer-attachments/incoming.pdf",
467 };
468 incomingShareStorageMocks.load
469 .mockResolvedValueOnce([
470 {
471 schemaVersion: 1,
472 id: "share-1",
473 createdAt: "2026-08-28T12:00:00.000Z",
474 text: "Review this file",
475 attachments: [file],
476 warnings: [],
477 },
478 ])
479 .mockResolvedValueOnce([]);
480​
481 await releaseUnusedComposerAttachmentFiles([file]);
482​
483 expect(incomingShareStorageMocks.load).toHaveBeenLastCalledWith({ strict: true });
484 expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
485​
486 await releaseUnusedComposerAttachmentFiles([file]);
487​
488 expect(incomingShareStorageMocks.load).toHaveBeenCalledTimes(2);
489 expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(file.fileUri);
490 });
491​
492 it("does not delete files when incoming share ownership cannot be loaded", async () => {
493 const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
494 onTestFinished(() => outboxLoad.mockRestore());
495 const file = {
496 id: "file-incoming-unknown",
497 type: "file" as const,
498 name: "report.pdf",
499 mimeType: "application/pdf",
500 sizeBytes: 42,
501 fileUri: "file:///documents/t3-composer-attachments/incoming-unknown.pdf",
502 };
503 const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined);
504 incomingShareStorageMocks.load.mockRejectedValueOnce(new Error("inbox unavailable"));
505 onTestFinished(() => warning.mockRestore());
506​
507 await releaseUnusedComposerAttachmentFiles([file]);
508​
509 expect(incomingShareStorageMocks.load).toHaveBeenCalledWith({ strict: true });
510 expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
511 });
512​
513 it.each(["draft", "outbox", "inbox"] as const)(
514 "preserves relocated files still referenced by a persisted %s",
515 async (owner) => {
516 const fileName = "33333333-3333-4333-8333-333333333333-report.pdf";
517 const oldFile = {
518 id: "file-relocated",
519 type: "file" as const,
520 name: "report.pdf",
521 mimeType: "application/pdf",
522 sizeBytes: 42,
523 fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`,
524 };
525 const currentFile = {
526 ...oldFile,
527 fileUri: `file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents/t3-composer-attachments/${fileName}`,
528 };
529 const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
530 onTestFinished(() => outboxLoad.mockRestore());
531 if (owner === "draft") {
532 composerDraftFileMocks.setDocument({
533 schemaVersion: 1,
534 drafts: { "environment-1:thread-1": { text: "Saved draft", attachments: [oldFile] } },
535 });
536 resetComposerDraftsLoadState();
537 } else if (owner === "outbox") {
538 outboxLoad.mockImplementation(async () => {
539 appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {
540 "environment-1:thread-1": [
541 {
542 environmentId: EnvironmentId.make("environment-1"),
543 threadId: ThreadId.make("thread-1"),
544 messageId: MessageId.make("message-relocated"),
545 commandId: CommandId.make("command-relocated"),
546 text: "Queued draft",
547 attachments: [oldFile],
548 createdAt: "2026-08-28T12:00:00.000Z",
549 },
550 ],
551 });
552 return true;
553 });
554 } else {
555 incomingShareStorageMocks.load.mockResolvedValue([
556 {
557 schemaVersion: 1,
558 id: "share-relocated",
559 createdAt: "2026-08-28T12:00:00.000Z",
560 text: "Incoming file",
561 attachments: [oldFile],
562 warnings: [],
563 },
564 ]);
565 }
566​
567 await releaseUnusedComposerAttachmentFiles([currentFile]);
568​
569 expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
570​
571 appAtomRegistry.set(composerDraftsAtom, {});
572 appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
573 outboxLoad.mockResolvedValue(true);
574 incomingShareStorageMocks.load.mockResolvedValue([]);
575 await releaseUnusedComposerAttachmentFiles([currentFile]);
576​
577 expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(currentFile.fileUri);
578 },
579 );
580​
581 it("does not delete attachment files when the draft removal cannot be saved", async () => {
582 const file = {
583 id: "file-unsaved",
584 type: "file" as const,
585 name: "report.pdf",
586 mimeType: "application/pdf",
587 sizeBytes: 42,
588 fileUri: "file:///documents/t3-composer-attachments/report.pdf",
589 };
590 setComposerDraftText("environment-1:thread-1", "Unsaved draft");
591 composerDraftFileMocks.setWriteError(new Error("storage unavailable"));
592​
593 try {
594 await expect(releaseUnusedComposerAttachmentFiles([file])).rejects.toBeInstanceOf(
595 ComposerDraftPersistenceError,
596 );
597 expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
598 } finally {
599 composerDraftFileMocks.setWriteError(null);
600 }
601 });
602​
603 it("hydrates selector state even when the message content is empty", () => {
604 expect(
605 decodePersistedComposerDrafts({
606 schemaVersion: 1,
607 drafts: {
608 "new-task:environment-1:project-1": {
609 text: "",
610 attachments: [],
611 modelSelection: {
612 instanceId: "codex",
613 model: "gpt-5.4",
614 options: [{ id: "reasoningEffort", value: "xhigh" }],
615 },
616 runtimeMode: "approval-required",
617 interactionMode: "plan",
618 workspaceSelection: {
619 mode: "worktree",
620 branch: "main",
621 worktreePath: null,
622 },
623 },
624 },
625 }),
626 ).toEqual({
627 "new-task:environment-1:project-1": {
628 text: "",
629 attachments: [],
630 modelSelection: {
631 instanceId: "codex",
632 model: "gpt-5.4",
633 options: [{ id: "reasoningEffort", value: "xhigh" }],
634 },
635 runtimeMode: "approval-required",
636 interactionMode: "plan",
637 workspaceSelection: {
638 mode: "worktree",
639 branch: "main",
640 worktreePath: null,
641 },
642 },
643 });
644 });
645​
646 it("keeps legacy content-only drafts and rejects invalid selector state", () => {
647 expect(
648 decodePersistedComposerDrafts({
649 schemaVersion: 1,
650 drafts: {
651 "environment-1:thread-1": DRAFT,
652 },
653 }),
654 ).toEqual({
655 "environment-1:thread-1": DRAFT,
656 });
657​
658 expect(() =>
659 decodePersistedComposerDrafts({
660 schemaVersion: 1,
661 drafts: {
662 "environment-1:thread-1": {
663 ...DRAFT,
664 runtimeMode: "sometimes-safe",
665 },
666 },
667 }),
668 ).toThrow();
669 });
670​
671 it("keeps share-import receipts on otherwise contentless new-task drafts", () => {
672 const receiptDraft: ComposerDraft = {
673 text: "",
674 attachments: [],
675 importedShareIds: ["share-1"],
676 };
677 // The stale-model strip must not touch receipt-bearing drafts, and the
678 // empty filter must keep them — or the same share would re-import after
679 // restart.
680 expect(
681 decodePersistedComposerState({
682 schemaVersion: 1,
683 drafts: {
684 "new-task:environment-1:project-1": {
685 ...receiptDraft,
686 modelSelection: {
687 instanceId: "codex",
688 model: "gpt-5.4",
689 },
690 },
691 },
692 }).drafts,
693 ).toEqual({
694 "new-task:environment-1:project-1": {
695 text: "",
696 attachments: [],
697 importedShareIds: ["share-1"],
698 },
699 });
700​
701 expect(
702 decodePersistedComposerState({
703 schemaVersion: 1,
704 drafts: { "new-task:environment-1:project-1": receiptDraft },
705 }).drafts,
706 ).toEqual({ "new-task:environment-1:project-1": receiptDraft });
707 });
708​
709 it("hydrates the global sticky model selection", () => {
710 expect(
711 decodePersistedComposerState({
712 schemaVersion: 1,
713 drafts: {},
714 stickyModelSelection: {
715 instanceId: "codex",
716 model: "gpt-5.6-sol",
717 },
718 }).stickyModelSelection,
719 ).toEqual({
720 instanceId: "codex",
721 model: "gpt-5.6-sol",
722 });
723 });
724​
725 it("waits for hydration before persisting the latest composer state", async () => {
726 vi.useFakeTimers();
727 composerDraftFileMocks.setDocument({
728 schemaVersion: 1,
729 drafts: {
730 "environment-1:thread-1": DRAFT,
731 },
732 stickyModelSelection: {
733 instanceId: "codex",
734 model: "gpt-5.6-sol",
735 },
736 });
737 composerDraftFileMocks.blockRead();
738 composerDraftFileMocks.resetWrites();
739​
740 ensureComposerDraftsLoaded();
741 await Promise.resolve();
742 // The read is blocked, hydration is pending.
743 setComposerDraftText("new-task:environment-1:project-1", "New prompt");
744 await vi.advanceTimersByTimeAsync(200);
745​
746 // Write should still be deferred — hydration has not resolved.
747 expect(composerDraftFileMocks.getWrites()).toHaveLength(0);
748​
749 composerDraftFileMocks.releaseRead();
750 // Let the loadPromise settle and chain into the deferred persist.
751 await vi.runAllTimersAsync();
752​
753 expect(JSON.parse(composerDraftFileMocks.getWrites()[0]!)).toEqual({
754 schemaVersion: 1,
755 drafts: {
756 "environment-1:thread-1": DRAFT,
757 "new-task:environment-1:project-1": {
758 text: "New prompt",
759 attachments: [],
760 },
761 },
762 stickyModelSelection: {
763 instanceId: "codex",
764 model: "gpt-5.6-sol",
765 },
766 });
767 });
768​
769 it("flush waits for pending hydration instead of clobbering disk", async () => {
770 vi.useFakeTimers();
771 composerDraftFileMocks.setDocument({
772 schemaVersion: 1,
773 drafts: {
774 "environment-1:thread-1": DRAFT,
775 },
776 stickyModelSelection: {
777 instanceId: "codex",
778 model: "gpt-5.6-sol",
779 },
780 });
781 composerDraftFileMocks.blockRead();
782 composerDraftFileMocks.resetWrites();
783​
784 ensureComposerDraftsLoaded();
785 await Promise.resolve();
786 // An edit lands before hydration finishes; its debounced write is gated
787 // behind the blocked read.
788 setComposerDraftText("new-task:environment-1:project-1", "New prompt");
789​
790 const flush = flushComposerDrafts();
791 await vi.advanceTimersByTimeAsync(200);
792 // The flush must not have written the pre-hydration snapshot over disk.
793 expect(composerDraftFileMocks.getWrites()).toHaveLength(0);
794​
795 composerDraftFileMocks.releaseRead();
796 await flush;
797​
798 const written = JSON.parse(composerDraftFileMocks.getDocument());
799 expect(written.drafts["environment-1:thread-1"]).toEqual(DRAFT);
800 expect(written.drafts["new-task:environment-1:project-1"]).toEqual({
801 text: "New prompt",
802 attachments: [],
803 });
804 expect(written.stickyModelSelection).toEqual({
805 instanceId: "codex",
806 model: "gpt-5.6-sol",
807 });
808 });
809​
810 it("serializes environment cleanup after an older queued write", async () => {
811 vi.useFakeTimers();
812 composerDraftFileMocks.setDocument(JSON.stringify({ schemaVersion: 1, drafts: {} }));
813 composerDraftFileMocks.resetWrites();
814 let releaseFirstWrite!: () => void;
815 const firstWriteBarrier = new Promise<void>((resolve) => {
816 releaseFirstWrite = resolve;
817 });
818 composerDraftFileMocks.setNextWriteBarrier(firstWriteBarrier);
819 let writeCount = 0;
820 const bothWritesCommitted = new Promise<void>((resolve) => {
821 composerDraftFileMocks.setOnWrite(() => {
822 writeCount += 1;
823 if (writeCount === 2) {
824 resolve();
825 }
826 });
827 });
828​
829 appAtomRegistry.set(composerDraftsAtom, {
830 "environment-1:thread-1": DRAFT,
831 "environment-2:thread-2": { text: "keep", attachments: [] },
832 });
833 setStickyComposerModelSelection({
834 instanceId: ProviderInstanceId.make("codex"),
835 model: "gpt-5.6-sol",
836 });
837 await vi.advanceTimersByTimeAsync(200);
838​
839 const clear = clearComposerDraftsEnvironment(EnvironmentId.make("environment-1"));
840 await Promise.resolve();
841 // Cleanup write is queued behind the still-blocked debounced write.
842 expect(composerDraftFileMocks.getWrites()).toHaveLength(0);
843​
844 releaseFirstWrite();
845 await clear;
846 await bothWritesCommitted;
847​
848 expect(JSON.parse(composerDraftFileMocks.getDocument())).toEqual({
849 schemaVersion: 1,
850 drafts: {
851 "environment-2:thread-2": { text: "keep", attachments: [] },
852 },
853 stickyModelSelection: {
854 instanceId: "codex",
855 model: "gpt-5.6-sol",
856 },
857 });
858 });
859​
860 it("clears sent content without clearing the selected model or workspace", () => {
861 const draftKey = "environment-1:thread-1";
862 const draft: ComposerDraft = {
863 text: "send this",
864 attachments: [],
865 importedShareIds: ["share-1"],
866 modelSelection: {
867 instanceId: ProviderInstanceId.make("codex"),
868 model: "gpt-5.4",
869 options: [{ id: "reasoningEffort", value: "xhigh" }],
870 },
871 workspaceSelection: {
872 mode: "worktree",
873 branch: "main",
874 worktreePath: null,
875 },
876 };
877​
878 expect(clearComposerDraftContentState({ [draftKey]: draft }, draftKey)).toEqual({
879 [draftKey]: {
880 modelSelection: draft.modelSelection,
881 workspaceSelection: draft.workspaceSelection,
882 text: "",
883 attachments: [],
884 },
885 });
886 });
887​
888 it("drops draft-local model and workspace selections after sending a new task", () => {
889 const draftKey = "new-task:environment-1:project-1";
890 const draft: ComposerDraft = {
891 text: "send this",
892 attachments: [],
893 modelSelection: {
894 instanceId: ProviderInstanceId.make("codex"),
895 model: "gpt-5.4",
896 },
897 workspaceSelection: {
898 mode: "worktree",
899 branch: "main",
900 worktreePath: null,
901 startFromOrigin: false,
902 },
903 };
904​
905 expect(
906 clearComposerDraftContentState({ [draftKey]: draft }, draftKey, {
907 clearModelSelection: true,
908 clearWorkspaceSelection: true,
909 }),
910 ).toEqual({});
911 });
912​
913 it("reads the latest selector state synchronously for send", () => {
914 const draftKey = "environment-1:thread-1";
915 const selectedDraft: ComposerDraft = {
916 text: "send this",
917 attachments: [],
918 modelSelection: {
919 instanceId: ProviderInstanceId.make("codex"),
920 model: "gpt-5.4",
921 options: [{ id: "reasoningEffort", value: "xhigh" }],
922 },
923 };
924 appAtomRegistry.set(composerDraftsAtom, { [draftKey]: selectedDraft });
925​
926 expect(getComposerDraftSnapshot(draftKey)).toEqual(selectedDraft);
927 });
928​
929 it("carries unfinished content to a newly selected project without overwriting its settings", () => {
930 const sourceKey = "new-task:environment-1:project-1";
931 const targetKey = "new-task:environment-1:project-2";
932 const source: ComposerDraft = {
933 text: "Keep this task",
934 attachments: [],
935 importedShareIds: ["share-1"],
936 workspaceSelection: {
937 mode: "worktree",
938 branch: "feature/source",
939 worktreePath: null,
940 },
941 };
942 const target: ComposerDraft = {
943 text: "",
944 attachments: [],
945 runtimeMode: "approval-required",
946 };
947​
948 expect(
949 copyComposerDraftContentState(
950 { [sourceKey]: source, [targetKey]: target },
951 sourceKey,
952 targetKey,
953 ),
954 ).toEqual({
955 [sourceKey]: source,
956 [targetKey]: {
957 ...target,
958 text: source.text,
959 attachments: source.attachments,
960 importedShareIds: source.importedShareIds,
961 },
962 });
963 });
964​
965 it("does not overwrite unfinished content already stored for the selected project", () => {
966 const sourceKey = "new-task:environment-1:project-1";
967 const targetKey = "new-task:environment-1:project-2";
968 const drafts: Record<string, ComposerDraft> = {
969 [sourceKey]: { text: "Source task", attachments: [] },
970 [targetKey]: { text: "Target task", attachments: [] },
971 };
972​
973 expect(copyComposerDraftContentState(drafts, sourceKey, targetKey)).toBe(drafts);
974 });
975​
976 it("merges shared content into a project draft without duplicating retries", () => {
977 const draftKey = "new-task:environment-1:project-1";
978 const sharedAttachment = {
979 id: "share-1:image:0",
980 type: "image" as const,
981 name: "Screenshot.png",
982 mimeType: "image/png",
983 sizeBytes: 3,
984 dataUrl: "data:image/png;base64,YWJj",
985 previewUri: "data:image/png;base64,YWJj",
986 };
987 const existing: Record<string, ComposerDraft> = {
988 [draftKey]: { text: "Existing context", attachments: [] },
989 };
990 const content = {
991 text: "Shared note",
992 attachments: [sharedAttachment],
993 sourceShareId: "share-1",
994 };
995​
996 const merged = mergeComposerDraftContentState(existing, draftKey, content);
997 expect(merged[draftKey]).toMatchObject({
998 text: "Existing context\n\nShared note",
999 attachments: [sharedAttachment],
1000 importedShareIds: ["share-1"],
1001 });
1002 expect(mergeComposerDraftContentState(merged, draftKey, content)).toBe(merged);
1003​
1004 const edited = {
1005 ...merged,
1006 [draftKey]: { ...merged[draftKey]!, text: "User edited the imported context" },
1007 };
1008 expect(mergeComposerDraftContentState(edited, draftKey, content)).toBe(edited);
1009 });
1010​
1011 it("preserves existing images when shared content exceeds the draft attachment limit", () => {
1012 const draftKey = "new-task:environment-1:project-1";
1013 const image = (id: string) => ({
1014 id,
1015 type: "image" as const,
1016 name: `${id}.png`,
1017 mimeType: "image/png",
1018 sizeBytes: 3,
1019 dataUrl: "data:image/png;base64,YWJj",
1020 previewUri: "data:image/png;base64,YWJj",
1021 });
1022 const existingImage = image("existing");
1023 const sharedImages = Array.from({ length: 8 }, (_, index) => image(`shared-${index}`));
1024​
1025 const merged = mergeComposerDraftContentState(
1026 { [draftKey]: { text: "", attachments: [existingImage] } },
1027 draftKey,
1028 { text: "", attachments: sharedImages },
1029 );
1030​
1031 expect(merged[draftKey]?.attachments).toHaveLength(8);
1032 expect(merged[draftKey]?.attachments[0]).toEqual(existingImage);
1033 expect(merged[draftKey]?.attachments.at(-1)?.id).toBe("shared-6");
1034 });
1035​
1036 it("restores the exact draft captured before an interrupted share import", () => {
1037 const draftKey = "new-task:environment-1:project-1";
1038 const beforeImport: ComposerDraft = {
1039 text: "Existing context",
1040 attachments: [],
1041 runtimeMode: "approval-required",
1042 };
1043 const imported: ComposerDraft = {
1044 ...beforeImport,
1045 text: "Existing context\n\nShared note",
1046 importedShareIds: ["share-1"],
1047 };
1048​
1049 expect(
1050 restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, beforeImport),
1051 ).toEqual({ [draftKey]: beforeImport });
1052 expect(
1053 restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, {
1054 text: "",
1055 attachments: [],
1056 }),
1057 ).toEqual({});
1058 });
1059​
1060 it("removes only drafts owned by the selected environment", () => {
1061 const environmentId = EnvironmentId.make("environment-cloud");
1062 const retainedEnvironmentId = EnvironmentId.make("environment-local");
1063​
1064 expect(
1065 removeComposerDraftsForEnvironment(
1067 [`${environmentId}:thread-cloud`]: DRAFT,
1068 [`new-task:${environmentId}:project-cloud`]: DRAFT,
1069 [`${retainedEnvironmentId}:thread-local`]: DRAFT,
1070 [`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
1071 },
1072 environmentId,
1073 ),
1074 ).toEqual({
1075 [`${retainedEnvironmentId}:thread-local`]: DRAFT,
1076 [`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
1077 });
1078 });
1079​
1080 it("lands a still-debounced draft write when flushed", async () => {
1081 const draftKey = "environment-1:thread-1";
1082 setComposerDraftText(draftKey, "typed right before the restart");
1083​
1084 await flushComposerDrafts();
1085​
1086 expect(JSON.parse(composerDraftFileMocks.getDocument())).toMatchObject({
1087 drafts: { [draftKey]: { text: "typed right before the restart" } },
1088 });
1089 });
1090​
1091 it("propagates a flush write failure instead of resolving as saved", async () => {
1092 const draftKey = "environment-1:thread-1";
1093 setComposerDraftText(draftKey, "unsaved");
1094 composerDraftFileMocks.setWriteError(new Error("storage unavailable"));
1095​
1096 try {
1097 await expect(flushComposerDrafts()).rejects.toBeInstanceOf(ComposerDraftPersistenceError);
1098 } finally {
1099 composerDraftFileMocks.setWriteError(null);
1101 });
1102​
1103 it("restores the pre-merge snapshot when the draft is untouched since the merge", () => {
1104 const draftKey = "environment-1:thread-1";
1105 const snapshot: ComposerDraft = { text: "typed before", attachments: [] };
1106 const merged: ComposerDraft = {
1107 text: "typed before\n\nqueued text",
1108 attachments: [],
1109 runtimeMode: "approval-required",
1110 };
1111​
1112 expect(undoComposerDraftMergeState({ [draftKey]: merged }, draftKey, snapshot, merged)).toEqual(
1113 { [draftKey]: snapshot },
1114 );
1115 expect(
1116 undoComposerDraftMergeState(
1117 { [draftKey]: merged },
1118 draftKey,
1119 { text: "", attachments: [] },
1120 merged,
1121 ),
1122 ).toEqual({});
1123 });
1124​
1125 it("persists an async merge rollback with the sticky model selection", async () => {
1126 const draftKey = "environment-1:thread-1";
1127 const snapshot: ComposerDraft = { text: "typed before", attachments: [] };
1128 const merged: ComposerDraft = {
1129 text: "typed before\n\nqueued text",
1130 attachments: [],
1131 };
1132 composerDraftFileMocks.setDocument({
1133 schemaVersion: 1,
1134 drafts: { [draftKey]: merged },
1135 stickyModelSelection: {
1136 instanceId: "codex",
1137 model: "gpt-5.6-sol",
1138 },
1139 });
1140​
1141 await undoComposerDraftMerge(draftKey, snapshot, merged);
1142​
1143 expect(JSON.parse(composerDraftFileMocks.getDocument())).toEqual({
1144 schemaVersion: 1,
1145 drafts: { [draftKey]: snapshot },
1146 stickyModelSelection: {
1147 instanceId: "codex",
1148 model: "gpt-5.6-sol",
1149 },
1150 });
1151 });
1152​
1153 it("returns merge-written settings to the snapshot but keeps user-edited ones", () => {
1154 const draftKey = "environment-1:thread-1";
1155 const snapshot: ComposerDraft = {
1156 text: "typed before",
1157 attachments: [],
1158 runtimeMode: "approval-required",
1159 interactionMode: "default",
1160 };
1161 const merged: ComposerDraft = {
1162 text: "typed before\n\nqueued text",
1163 attachments: [],
1164 runtimeMode: "full-access",
1165 interactionMode: "default",
1166 };
1167 // The user edited the text (forcing the partial undo) and also switched
1168 // interaction mode, but never touched the merge-written runtime mode.
1169 const edited: ComposerDraft = {
1170 text: "typed EDITED before\n\nqueued text",
1171 attachments: [],
1172 runtimeMode: "full-access",
1173 interactionMode: "plan",
1174 };
1175​
1176 expect(undoComposerDraftMergeState({ [draftKey]: edited }, draftKey, snapshot, merged)).toEqual(
1178 [draftKey]: {
1179 text: "typed EDITED before",
1180 attachments: [],
1181 runtimeMode: "approval-required",
1182 interactionMode: "plan",
1183 },
1184 },
1185 );
1186 });
1187​
1188 it("takes out only what the merge inserted when the user edited during it", () => {
1189 const draftKey = "environment-1:thread-1";
1190 const keptAttachment = {
1191 id: "kept",
1192 type: "file" as const,
1193 name: "kept.pdf",
1194 mimeType: "application/pdf",
1195 sizeBytes: 1,
1196 fileUri: "file:///documents/t3-composer-attachments/kept.pdf",
1197 };
1198 const insertedAttachment = {
1199 id: "inserted",
1200 type: "file" as const,
1201 name: "inserted.pdf",
1202 mimeType: "application/pdf",
1203 sizeBytes: 1,
1204 fileUri: "file:///documents/t3-composer-attachments/inserted.pdf",
1205 };
1206 const userAttachment = { ...keptAttachment, id: "user-added" };
1207 const snapshot: ComposerDraft = { text: "typed before", attachments: [keptAttachment] };
1208 const merged: ComposerDraft = {
1209 text: "typed before\n\nqueued text",
1210 attachments: [keptAttachment, insertedAttachment],
1211 };
1212 // The user rewrote the leading text and attached a file mid-recovery.
1213 const edited: ComposerDraft = {
1214 text: "typed EDITED before\n\nqueued text",
1215 attachments: [keptAttachment, insertedAttachment, userAttachment],
1216 };
1217​
1218 expect(undoComposerDraftMergeState({ [draftKey]: edited }, draftKey, snapshot, merged)).toEqual(
1220 [draftKey]: {
1221 text: "typed EDITED before",
1222 attachments: [keptAttachment, userAttachment],
1223 },
1224 },
1225 );
1226​
1227 // Edits that broke the merged suffix keep their text untouched; only the
1228 // inserted attachments still come out.
1229 const rewritten: ComposerDraft = {
1230 text: "totally rewritten",
1231 attachments: [insertedAttachment],
1232 };
1233 expect(
1234 undoComposerDraftMergeState({ [draftKey]: rewritten }, draftKey, snapshot, merged),
1235 ).toEqual({
1236 [draftKey]: { text: "totally rewritten", attachments: [] },
1237 });
1238 });
1239​
1240 it("keeps text appended after a merge when rolling it back", () => {
1241 const draftKey = "environment-1:thread-1";
1242 const snapshot: ComposerDraft = { text: "typed before", attachments: [] };
1243 const content = { text: "queued text", attachments: [] };
1244 const merged = mergeComposerDraftContentState({ [draftKey]: snapshot }, draftKey, content)[
1245 draftKey
1246 ]!;
1247 const edited: ComposerDraft = {
1248 ...merged,
1249 text: `${merged.text}\n\nuser follow-up`,
1250 };
1251​
1252 const rolledBack = undoComposerDraftMergeState(
1253 { [draftKey]: edited },
1254 draftKey,
1255 snapshot,
1256 merged,
1257 );
1258​
1259 expect(rolledBack[draftKey]?.text).toBe("typed before\n\nuser follow-up");
1260 const retried = mergeComposerDraftContentState(rolledBack, draftKey, content);
1261 expect(retried[draftKey]?.text.match(/queued text/g)).toHaveLength(1);
1262 });
1263​
1264 it("spares a file re-owned between the sweep's scan and its deletion", async () => {
1265 const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
1266 onTestFinished(() => outboxLoad.mockRestore());
1267 const fileFor = (id: string) => ({
1268 id,
1269 type: "file" as const,
1270 name: `${id}.pdf`,
1271 mimeType: "application/pdf",
1272 sizeBytes: 42,
1273 fileUri: `file:///documents/t3-composer-attachments/${id}.pdf`,
1274 });
1275 const first = fileFor("file-first");
1276 const reowned = fileFor("file-reowned");
1277 // A restore re-owns the second file while the first deletion is in
1278 // flight, after the sweep already decided both were unused.
1279 composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
1280 appAtomRegistry.set(composerDraftsAtom, {
1281 "environment-1:thread-1": { text: "restored", attachments: [reowned] },
1282 });
1283 });
1284​
1285 await releaseUnusedComposerAttachmentFiles([first, reowned]);
1286​
1287 expect(composerAttachmentCleanupMocks.remove.mock.calls).toEqual([[first.fileUri]]);
1288 });
1289​
1290 // Uses a fresh module instance (hydration is one-shot), so it stays last.
1291 it("hydrates persisted drafts before a cold-start sweep deletes their files", async () => {
1292 const file = {
1293 id: "file-cold-start",
1294 type: "file" as const,
1295 name: "report.pdf",
1296 mimeType: "application/pdf",
1297 sizeBytes: 42,
1298 fileUri: "file:///documents/t3-composer-attachments/report.pdf",
1299 };
1300 composerDraftFileMocks.setDocument({
1301 schemaVersion: 1,
1302 drafts: {
1303 "environment-1:thread-1": { text: "Persisted draft", attachments: [file] },
1304 },
1305 });
1306 vi.resetModules();
1307 const fresh = await import("./use-composer-drafts");
1308 const freshRegistry = (await import("./atom-registry")).appAtomRegistry;
1309​
1310 await fresh.releaseUnusedComposerAttachmentFiles([file]);
1311​
1312 expect(freshRegistry.get(fresh.composerDraftsAtom)).toEqual({
1313 "environment-1:thread-1": { text: "Persisted draft", attachments: [file] },
1314 });
1315 expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
1316 });
1317});