17
let nextWriteBarrier: Promise<void> | null = null;
18
let onWrite: (() => void) | null = null;
19
const writes: string[] = [];
20
+ const readImage = vi.fn(async () => "YWJj");
21
22
return {
23
+ readImage,
24
blockRead() {
25
readBarrier = new Promise<void>((resolve) => {
26
releaseRead = resolve;
75
return document;
76
}
77
78
+ async base64() {
79
+ return readImage();
80
+ }
81
+
82
write(value: string) {
83
if (writeError) {
84
throw writeError;
114
vi.mock("expo-file-system", () => ({
115
Directory: composerDraftFileMocks.Directory,
116
File: composerDraftFileMocks.File,
111
- Paths: { document: "/documents" },
117
+ Paths: { document: { uri: "file:///documents" } },
118
}));
119
114
-vi.mock("../lib/composerImages", () => ({
120
+vi.mock("../lib/composerImages", async (importOriginal) => ({
121
+ ...(await importOriginal<typeof import("../lib/composerImages")>()),
122
removePersistedComposerAttachmentFile: composerAttachmentCleanupMocks.remove,
123
}));
124
125
+vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "0000" }));
126
+vi.mock("./assets", () => ({ assetEnvironment: {} }));
127
+vi.mock("./attachments", () => ({ attachmentEnvironment: {} }));
128
+vi.mock("./session", () => ({ environmentSession: {} }));
129
+vi.mock("@t3tools/client-runtime/state/runtime", () => ({
130
+ createEnvironmentRpcCommand: () => Symbol("rpc-command"),
131
+ executeAtomQuery: () => {
132
+ throw new Error("Unexpected network query in the inline read test");
133
+ },
134
+ runAtomCommand: () => {
135
+ throw new Error("Unexpected network command in the inline read test");
136
+ },
137
+ squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error,
138
+}));
139
+
140
vi.mock("../lib/attachmentUpload", () => ({
141
releasePendingAttachmentUploads: composerAttachmentCleanupMocks.releaseUploads,
142
}));
150
import {
151
appendComposerDraftAttachments,
152
archiveCloudComposerDrafts,
153
+ clearComposerDraftContent,
154
clearComposerDraftContentState,
155
clearComposerDraftsEnvironment,
156
ComposerDraftPersistenceError,
194
composerDraftFileMocks.setNextWriteBarrier(null);
195
composerDraftFileMocks.setOnWrite(null);
196
composerDraftFileMocks.resetWrites();
197
+ composerDraftFileMocks.readImage.mockReset();
198
+ composerDraftFileMocks.readImage.mockResolvedValue("YWJj");
199
appAtomRegistry.set(composerDraftsAtom, {});
200
appAtomRegistry.set(composerCloudDraftsAtom, { accountId: null, signedOut: {} });
201
appAtomRegistry.set(stickyComposerModelSelectionAtom, null);
338
expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(file.fileUri);
339
});
340
341
+ it("retains a referenced file-backed image and releases it once unreferenced", async () => {
342
+ const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
343
+ onTestFinished(() => outboxLoad.mockRestore());
344
+ const image = {
345
+ id: "image-1",
346
+ type: "image" as const,
347
+ name: "photo.png",
348
+ mimeType: "image/png",
349
+ sizeBytes: 3,
350
+ fileUri: "file:///documents/t3-composer-attachments/photo.png",
351
+ previewUri: "file:///documents/t3-composer-attachments/photo.png",
352
+ };
353
+ appAtomRegistry.set(composerDraftsAtom, {
354
+ "environment-1:thread-1": { text: "look at this", attachments: [image] },
355
+ });
356
+
357
+ await releaseUnusedComposerAttachmentFiles([image]);
358
+ expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
359
+
360
+ // A queued outbox message must keep the bytes alive after the draft clears.
361
+ appAtomRegistry.set(composerDraftsAtom, {});
362
+ appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {
363
+ "environment-1:thread-1": [
364
+ {
365
+ environmentId: EnvironmentId.make("environment-1"),
366
+ threadId: ThreadId.make("thread-1"),
367
+ messageId: MessageId.make("queued-image"),
368
+ commandId: CommandId.make("command-image"),
369
+ text: "look at this",
370
+ attachments: [image],
371
+ createdAt: "2026-08-31T12:00:00.000Z",
372
+ },
373
+ ],
374
+ });
375
+ await releaseUnusedComposerAttachmentFiles([image]);
376
+ expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
377
+
378
+ appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
379
+ await releaseUnusedComposerAttachmentFiles([image]);
380
+ expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledExactlyOnceWith(image.fileUri);
381
+ });
382
+
383
+ it("keeps an image through an inline read after its draft is removed", async () => {
384
+ const { prepareTurnAttachments } =
385
+ await vi.importActual<typeof import("../lib/attachmentUpload")>("../lib/attachmentUpload");
386
+ const image = {
387
+ id: "image-reading",
388
+ type: "image" as const,
389
+ name: "photo.png",
390
+ mimeType: "image/png",
391
+ sizeBytes: 3,
392
+ fileUri: "file:///documents/t3-composer-attachments/photo.png",
393
+ previewUri: "file:///documents/t3-composer-attachments/photo.png",
394
+ };
395
+ const readStarted = Promise.withResolvers<void>();
396
+ const read = Promise.withResolvers<void>();
397
+ const removed = Promise.withResolvers<void>();
398
+ let imageExists = true;
399
+ composerDraftFileMocks.readImage.mockImplementation(async () => {
400
+ readStarted.resolve();
401
+ await read.promise;
402
+ if (!imageExists) throw new Error("The image was deleted during its read");
403
+ return "YWJj";
404
+ });
405
+ composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
406
+ imageExists = false;
407
+ removed.resolve();
408
+ });
409
+ appendComposerDraftAttachments("environment-1:thread-1", [image]);
410
+ await flushComposerDrafts();
411
+ const preparing = prepareTurnAttachments({
412
+ environmentId: EnvironmentId.make("environment-1"),
413
+ attachments: [image],
414
+ });
415
+ onTestFinished(async () => {
416
+ read.resolve();
417
+ await preparing.catch(() => undefined);
418
+ });
419
+ await readStarted.promise;
420
+ clearComposerDraftContent("environment-1:thread-1", { deferAttachmentCleanup: true });
421
+ await releaseUnusedComposerAttachmentFiles([image]);
422
+ expect(imageExists).toBe(true);
423
+
424
+ read.resolve();
425
+ const prepared = await preparing;
426
+ expect(prepared.status).toBe("ready");
427
+ if (prepared.status !== "ready") return;
428
+ expect(prepared.attachments).toEqual([
429
+ {
430
+ type: "image",
431
+ name: "photo.png",
432
+ mimeType: "image/png",
433
+ sizeBytes: 3,
434
+ dataUrl: "data:image/png;base64,YWJj",
435
+ },
436
+ ]);
437
+ await removed.promise;
438
+ expect(imageExists).toBe(false);
439
+ });
440
+
441
it("keeps a failed-send draft's pending upload for retry", async () => {
442
const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
443
onTestFinished(() => outboxLoad.mockRestore());
519
expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
520
});
521
397
- it("keeps signed-out files through cleanup and restart, and restores only the owning account", async () => {
398
- const load = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
399
- onTestFinished(() => load.mockRestore());
400
- await waitForComposerDraftsLoaded();
401
- const environmentId = EnvironmentId.make("cloud-environment");
402
- const key = `${environmentId}:thread-1`;
403
- const file = {
404
- id: "local-pdf",
405
- type: "file" as const,
406
- name: "notes.pdf",
407
- mimeType: "application/pdf",
408
- sizeBytes: 42,
409
- fileUri: "file:///documents/t3-composer-attachments/notes.pdf",
410
- uploadEnvironmentId: environmentId,
411
- uploadedAttachmentId: "pending-pdf",
412
- };
413
- const queued = {
414
- environmentId,
415
- threadId: ThreadId.make("thread-2"),
416
- messageId: MessageId.make("queued-1"),
417
- commandId: CommandId.make("command-1"),
418
- text: "Send later",
419
- attachments: [file],
420
- createdAt: "2026-08-31T12:00:00.000Z",
421
- };
422
- appAtomRegistry.set(composerDraftsAtom, {
423
- [key]: { text: "Unsent notes", attachments: [file] },
424
- "direct-environment:thread-1": DRAFT,
425
- "pending-task:queued-1": { text: "Edited queued task", attachments: [file] },
426
- });
427
- appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, { queued: [queued] });
428
- await archiveCloudComposerDrafts("account-a", new Set([environmentId]));
429
- expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({
430
- "direct-environment:thread-1": DRAFT,
431
- });
432
- // The registry can remove the active outbox and drafts after the backup lands.
433
- appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
434
- await clearComposerDraftsEnvironment(environmentId);
435
- await releaseUnusedComposerAttachmentFiles([file]);
436
- expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
437
- expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled();
522
+ it.each(["file", "image"] as const)(
523
+ "keeps signed-out %s attachments through cleanup and restart, and restores only the owning account",
524
+ async (type) => {
525
+ const load = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
526
+ onTestFinished(() => load.mockRestore());
527
+ await waitForComposerDraftsLoaded();
528
+ const environmentId = EnvironmentId.make("cloud-environment");
529
+ const key = `${environmentId}:thread-1`;
530
+ const name = type === "image" ? "notes.png" : "notes.pdf";
531
+ const metadata = {
532
+ id: "local-notes",
533
+ name,
534
+ mimeType: type === "image" ? "image/png" : "application/pdf",
535
+ sizeBytes: 42,
536
+ fileUri: `file:///documents/t3-composer-attachments/${name}`,
537
+ uploadEnvironmentId: environmentId,
538
+ uploadedAttachmentId: "pending-notes",
539
+ };
540
+ const file =
541
+ type === "image"
542
+ ? { ...metadata, type, previewUri: metadata.fileUri }
543
+ : { ...metadata, type };
544
+ const queued = {
545
+ environmentId,
546
+ threadId: ThreadId.make("thread-2"),
547
+ messageId: MessageId.make("queued-1"),
548
+ commandId: CommandId.make("command-1"),
549
+ text: "Send later",
550
+ attachments: [file],
551
+ createdAt: "2026-08-31T12:00:00.000Z",
552
+ };
553
+ appAtomRegistry.set(composerDraftsAtom, {
554
+ [key]: { text: "Unsent notes", attachments: [file] },
555
+ "direct-environment:thread-1": DRAFT,
556
+ "pending-task:queued-1": { text: "Edited queued task", attachments: [file] },
557
+ });
558
+ appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, { queued: [queued] });
559
+ await archiveCloudComposerDrafts("account-a", new Set([environmentId]));
560
+ expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({
561
+ "direct-environment:thread-1": DRAFT,
562
+ });
563
+ // The registry can remove the active outbox and drafts after the backup lands.
564
+ appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
565
+ await clearComposerDraftsEnvironment(environmentId);
566
+ await releaseUnusedComposerAttachmentFiles([file]);
567
+ expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
568
+ expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled();
569
439
- appAtomRegistry.set(composerDraftsAtom, {});
440
- appAtomRegistry.set(composerCloudDraftsAtom, { accountId: null, signedOut: {} });
441
- resetComposerDraftsLoadState();
442
- await waitForComposerDraftsLoaded();
443
- await restoreCloudComposerDrafts("account-b");
444
- expect(getComposerDraftSnapshot(key).attachments).toEqual([]);
445
- expect(appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom)).toEqual({});
446
- const enqueue = vi.spyOn(threadOutboxManager, "enqueue").mockResolvedValue();
447
- onTestFinished(() => enqueue.mockRestore());
448
- await restoreCloudComposerDrafts("account-a");
449
- expect(getComposerDraftSnapshot(key)).toEqual({ text: "Unsent notes", attachments: [file] });
450
- expect(getComposerDraftSnapshot("pending-task:queued-1").text).toBe("Edited queued task");
451
- expect(enqueue).toHaveBeenCalledExactlyOnceWith(queued);
452
- expect(appAtomRegistry.get(composerCloudDraftsAtom).signedOut).toEqual({});
453
- const persisted = decodePersistedComposerState(
454
- JSON.parse(composerDraftFileMocks.getDocument()),
455
- );
456
- expect(persisted.drafts[key]?.attachments).toEqual([file]);
457
- expect(persisted.cloudDrafts.accountId).toBe("account-a");
458
- });
570
+ appAtomRegistry.set(composerDraftsAtom, {});
571
+ appAtomRegistry.set(composerCloudDraftsAtom, { accountId: null, signedOut: {} });
572
+ resetComposerDraftsLoadState();
573
+ await waitForComposerDraftsLoaded();
574
+ await restoreCloudComposerDrafts("account-b");
575
+ expect(getComposerDraftSnapshot(key).attachments).toEqual([]);
576
+ expect(appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom)).toEqual({});
577
+ const enqueue = vi.spyOn(threadOutboxManager, "enqueue").mockResolvedValue();
578
+ onTestFinished(() => enqueue.mockRestore());
579
+ await restoreCloudComposerDrafts("account-a");
580
+ expect(getComposerDraftSnapshot(key)).toEqual({ text: "Unsent notes", attachments: [file] });
581
+ expect(getComposerDraftSnapshot("pending-task:queued-1").text).toBe("Edited queued task");
582
+ expect(enqueue).toHaveBeenCalledExactlyOnceWith(queued);
583
+ expect(appAtomRegistry.get(composerCloudDraftsAtom).signedOut).toEqual({});
584
+ const persisted = decodePersistedComposerState(
585
+ JSON.parse(composerDraftFileMocks.getDocument()),
586
+ );
587
+ expect(persisted.drafts[key]?.attachments).toEqual([file]);
588
+ expect(persisted.cloudDrafts.accountId).toBe("account-a");
589
+ },
590
+ );
591
592
it("fails sign-out preservation before cleanup if a durable backup cannot be written", async () => {
593
const load = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
612
).toEqual(DRAFT);
613
});
614
483
- it("keeps a removed file until both playback and a share copy finish", async () => {
484
- const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
485
- onTestFinished(() => outboxLoad.mockRestore());
486
- const fileName = "33333333-3333-4333-8333-333333333333-recording.mp4";
487
- const file = {
488
- id: "file-preview",
489
- type: "file" as const,
490
- name: "recording.mp4",
491
- mimeType: "video/mp4",
492
- sizeBytes: 42,
493
- fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`,
494
- };
495
- const currentFile = {
496
- ...file,
497
- fileUri: `file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents/t3-composer-attachments/${fileName}`,
498
- };
499
- const releasePlayback = retainComposerAttachmentFileForPreview(file);
500
- const releaseShareCopy = retainComposerAttachmentFileForPreview(currentFile);
501
- onTestFinished(releasePlayback);
502
- onTestFinished(releaseShareCopy);
615
+ it.each(["file", "image"] as const)(
616
+ "keeps a removed %s until both preview and a share copy finish",
617
+ async (type) => {
618
+ const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
619
+ onTestFinished(() => outboxLoad.mockRestore());
620
+ const name = type === "image" ? "photo.png" : "recording.mp4";
621
+ const fileName = `33333333-3333-4333-8333-333333333333-${name}`;
622
+ const metadata = {
623
+ id: "file-preview",
624
+ name,
625
+ mimeType: type === "image" ? "image/png" : "video/mp4",
626
+ sizeBytes: 42,
627
+ fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`,
628
+ };
629
+ const file =
630
+ type === "image"
631
+ ? { ...metadata, type, previewUri: metadata.fileUri }
632
+ : { ...metadata, type };
633
+ const currentFile = {
634
+ ...file,
635
+ fileUri: `file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents/t3-composer-attachments/${fileName}`,
636
+ };
637
+ const releasePlayback = retainComposerAttachmentFileForPreview(file);
638
+ const releaseShareCopy = retainComposerAttachmentFileForPreview(currentFile);
639
+ onTestFinished(releasePlayback);
640
+ onTestFinished(releaseShareCopy);
641
504
- await releaseUnusedComposerAttachmentFiles([currentFile]);
505
- expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
642
+ await releaseUnusedComposerAttachmentFiles([currentFile]);
643
+ expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
644
507
- releasePlayback();
508
- releasePlayback();
509
- await releaseUnusedComposerAttachmentFiles([file]);
510
- expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
645
+ releasePlayback();
646
+ releasePlayback();
647
+ await releaseUnusedComposerAttachmentFiles([file]);
648
+ expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
649
512
- const deleted = Promise.withResolvers<void>();
513
- composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
514
- deleted.resolve();
515
- return undefined;
516
- });
517
- releaseShareCopy();
518
- await deleted.promise;
650
+ const deleted = Promise.withResolvers<void>();
651
+ composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
652
+ deleted.resolve();
653
+ return undefined;
654
+ });
655
+ releaseShareCopy();
656
+ await deleted.promise;
657
520
- expect(composerAttachmentCleanupMocks.remove.mock.calls).toEqual([[currentFile.fileUri]]);
521
- });
658
+ expect(composerAttachmentCleanupMocks.remove.mock.calls).toEqual([[currentFile.fileUri]]);
659
+ },
660
+ );
661
662
it("preserves a preview opened while cleanup is checking the incoming inbox", async () => {
663
const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
985
}
986
});
987
988
+ it("rejects persisted images without image bytes or a file URI", () => {
989
+ expect(() =>
990
+ decodePersistedComposerDrafts({
991
+ schemaVersion: 1,
992
+ drafts: {
993
+ "environment-1:thread-1": {
994
+ text: "Saved image",
995
+ attachments: [
996
+ {
997
+ id: "image-1",
998
+ type: "image",
999
+ name: "photo.png",
1000
+ mimeType: "image/png",
1001
+ sizeBytes: 3,
1002
+ previewUri: "file:///photo.png",
1003
+ },
1004
+ ],
1005
+ },
1006
+ },
1007
+ }),
1008
+ ).toThrow();
1009
+ });
1010
+
1011
it("hydrates selector state even when the message content is empty", () => {
1012
expect(
1013
decodePersistedComposerDrafts({