The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as Fiber from "effect/Fiber"; |
| 4 | import { createEnvironmentThreadShellAtoms } from "@t3tools/client-runtime/state/threads"; |
| 5 | import { |
| 6 | applyShellStreamEvent, |
| 7 | createEnvironmentSnapshotAtom, |
| 8 | EMPTY_SHELL_STATE, |
| 9 | type EnvironmentShellState, |
| 10 | type EnvironmentShellStatus, |
| 11 | } from "@t3tools/client-runtime/state/shell"; |
| 12 | import { |
| 13 | v2ShellSnapshot, |
| 14 | v2ThreadShell, |
| 15 | } from "../../../../packages/client-runtime/src/state/orchestrationV2TestFixtures"; |
| 16 | import * as Option from "effect/Option"; |
| 17 | import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; |
| 18 | import { afterEach, describe, expect, it } from "@effect/vitest"; |
| 19 | import { |
| 20 | CommandId, |
| 21 | ComposerContextId, |
| 22 | EnvironmentId, |
| 23 | MessageId, |
| 24 | ProjectId, |
| 25 | ProviderInstanceId, |
| 26 | RuntimeRequestId, |
| 27 | ThreadId, |
| 28 | type OrchestrationV2ThreadShell, |
| 29 | type OrchestrationV2ShellSnapshot, |
| 30 | type ModelSelection, |
| 31 | } from "@t3tools/contracts"; |
| 32 | import { onTestFinished, vi } from "vite-plus/test"; |
| 33 | |
| 34 | import { buildIncomingShareDraft } from "../features/sharing/incoming-share-model"; |
| 35 | import { composerContextSendBlockReason } from "../lib/composerContext"; |
| 36 | |
| 37 | const composerDraftFileMocks = vi.hoisted(() => { |
| 38 | let document = JSON.stringify({ schemaVersion: 1, drafts: {} }); |
| 39 | let readError: Error | null = null; |
| 40 | let writeError: Error | null = null; |
| 41 | let releaseRead: (() => void) | null = null; |
| 42 | let readBarrier = Promise.resolve(); |
| 43 | let nextWriteBarrier: Promise<void> | null = null; |
| 44 | let onWrite: (() => void) | null = null; |
| 45 | const writes: string[] = []; |
| 46 | const readImage = vi.fn(async () => "YWJj"); |
| 47 | |
| 48 | return { |
| 49 | readImage, |
| 50 | blockRead() { |
| 51 | readBarrier = new Promise<void>((resolve) => { |
| 52 | releaseRead = resolve; |
| 53 | }); |
| 54 | }, |
| 55 | releaseRead() { |
| 56 | releaseRead?.(); |
| 57 | releaseRead = null; |
| 58 | }, |
| 59 | getDocument() { |
| 60 | return document; |
| 61 | }, |
| 62 | setDocument(value: unknown) { |
| 63 | document = JSON.stringify(value); |
| 64 | }, |
| 65 | setReadError(error: Error | null) { |
| 66 | readError = error; |
| 67 | }, |
| 68 | setWriteError(error: Error | null) { |
| 69 | writeError = error; |
| 70 | }, |
| 71 | setNextWriteBarrier(barrier: Promise<void> | null) { |
| 72 | nextWriteBarrier = barrier; |
| 73 | }, |
| 74 | setOnWrite(callback: (() => void) | null) { |
| 75 | onWrite = callback; |
| 76 | }, |
| 77 | getWrites(): ReadonlyArray<string> { |
| 78 | return writes; |
| 79 | }, |
| 80 | resetWrites() { |
| 81 | writes.length = 0; |
| 82 | }, |
| 83 | Directory: class { |
| 84 | create() {} |
| 85 | |
| 86 | list() { |
| 87 | return []; |
| 88 | } |
| 89 | }, |
| 90 | File: class { |
| 91 | exists = true; |
| 92 | size = 3; |
| 93 | parentDirectory = null; |
| 94 | |
| 95 | create() {} |
| 96 | |
| 97 | moveSync() {} |
| 98 | |
| 99 | async text() { |
| 100 | await readBarrier; |
| 101 | if (readError) throw readError; |
| 102 | return document; |
| 103 | } |
| 104 | |
| 105 | async base64() { |
| 106 | return readImage(); |
| 107 | } |
| 108 | |
| 109 | write(value: string) { |
| 110 | if (writeError) { |
| 111 | throw writeError; |
| 112 | } |
| 113 | if (nextWriteBarrier) { |
| 114 | const barrier = nextWriteBarrier; |
| 115 | nextWriteBarrier = null; |
| 116 | return barrier.then(() => { |
| 117 | document = value; |
| 118 | writes.push(value); |
| 119 | onWrite?.(); |
| 120 | }); |
| 121 | } |
| 122 | document = value; |
| 123 | writes.push(value); |
| 124 | onWrite?.(); |
| 125 | } |
| 126 | }, |
| 127 | }; |
| 128 | }); |
| 129 | |
| 130 | const composerAttachmentCleanupMocks = vi.hoisted(() => ({ |
| 131 | remove: vi.fn(async () => undefined), |
| 132 | releaseUploads: vi.fn(async () => undefined), |
| 133 | })); |
| 134 | |
| 135 | const pickMedia = vi.hoisted(() => vi.fn()); |
| 136 | vi.mock("expo-image-picker", () => ({ launchImageLibraryAsync: pickMedia })); |
| 137 | |
| 138 | const incomingShareStorageMocks = vi.hoisted(() => ({ |
| 139 | load: vi.fn<typeof import("../features/sharing/incoming-share-storage").loadIncomingShareDrafts>( |
| 140 | async () => [], |
| 141 | ), |
| 142 | })); |
| 143 | |
| 144 | vi.mock("expo-file-system", () => ({ |
| 145 | Directory: composerDraftFileMocks.Directory, |
| 146 | File: composerDraftFileMocks.File, |
| 147 | Paths: { document: { uri: "file:///documents" } }, |
| 148 | })); |
| 149 | |
| 150 | vi.mock("../lib/composerImages", async (importOriginal) => ({ |
| 151 | ...(await importOriginal<typeof import("../lib/composerImages")>()), |
| 152 | removePersistedComposerAttachmentFile: composerAttachmentCleanupMocks.remove, |
| 153 | })); |
| 154 | |
| 155 | vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "0000" })); |
| 156 | vi.mock("./assets", () => ({ assetEnvironment: {} })); |
| 157 | vi.mock("./attachments", () => ({ attachmentEnvironment: {} })); |
| 158 | vi.mock("./session", () => ({ environmentSession: {} })); |
| 159 | vi.mock("@t3tools/client-runtime/state/runtime", () => ({ |
| 160 | createEnvironmentRpcCommand: () => Symbol("rpc-command"), |
| 161 | executeAtomQuery: () => { |
| 162 | throw new Error("Unexpected network query in the inline read test"); |
| 163 | }, |
| 164 | runAtomCommand: () => { |
| 165 | throw new Error("Unexpected network command in the inline read test"); |
| 166 | }, |
| 167 | squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error, |
| 168 | })); |
| 169 | |
| 170 | vi.mock("../lib/attachmentUpload", () => ({ |
| 171 | releasePendingAttachmentUploads: composerAttachmentCleanupMocks.releaseUploads, |
| 172 | })); |
| 173 | |
| 174 | vi.mock("../features/sharing/incoming-share-storage", () => ({ |
| 175 | loadIncomingShareDrafts: incomingShareStorageMocks.load, |
| 176 | })); |
| 177 | |
| 178 | import type { DraftComposerAttachment } from "../lib/composerImages"; |
| 179 | import { |
| 180 | collectComposerContextReferences, |
| 181 | formatComposerContextReference, |
| 182 | } from "@t3tools/shared/composerContextReferences"; |
| 183 | import { appAtomRegistry } from "./atom-registry"; |
| 184 | import { startComposerDraftOperation } from "./composerDraftOperations"; |
| 185 | import { questionAttachmentDraftKey } from "./question-attachments"; |
| 186 | import { |
| 187 | pickQuestionAttachments, |
| 188 | resolveQuestionImagePreparations, |
| 189 | } from "./question-attachment-preparation"; |
| 190 | import { threadOutboxManager } from "./thread-outbox"; |
| 191 | import { |
| 192 | appendComposerDraftAttachments, |
| 193 | captureComposerDraftInsertion, |
| 194 | countComposerDraftAttachmentsAfterSelection, |
| 195 | getComposerDraftAfterSelection, |
| 196 | archiveCloudComposerDrafts, |
| 197 | clearComposerDraftContent, |
| 198 | clearComposerDraftContentState, |
| 199 | subscribeComposerDraftModelReconciliation, |
| 200 | clearComposerDraftsEnvironment, |
| 201 | ComposerDraftPersistenceError, |
| 202 | composerDraftsAtom, |
| 203 | composerCloudDraftsAtom, |
| 204 | createNewTaskDraft, |
| 205 | createComposerDraftContextHistory, |
| 206 | setComposerDraftContext, |
| 207 | decodePersistedComposerState, |
| 208 | ensureComposerDraftsLoaded, |
| 209 | type ComposerDraft, |
| 210 | findNewTaskDraftKeys, |
| 211 | flushComposerDrafts, |
| 212 | getComposerDraftSnapshot, |
| 213 | mergeComposerDraftContentState, |
| 214 | migrateLegacyNewTaskDraft, |
| 215 | modelOptionMemoryAtom, |
| 216 | releaseUnusedComposerAttachmentFiles, |
| 217 | removeComposerDraftsForEnvironment, |
| 218 | replaceComposerDraftAttachments, |
| 219 | resetComposerDraftsLoadState, |
| 220 | restoreComposerDraftSnapshotState, |
| 221 | restoreCloudComposerDrafts, |
| 222 | retargetNewTaskDraft, |
| 223 | retargetSavedNewTaskDraft, |
| 224 | setComposerDraftText, |
| 225 | insertComposerDraftContext, |
| 226 | insertComposerDraftText, |
| 227 | rememberComposerDraftSelection, |
| 228 | setComposerDraftAttachmentUpload, |
| 229 | waitForComposerDraftsLoaded, |
| 230 | setStickyComposerModelSelection, |
| 231 | stickyComposerModelSelectionAtom, |
| 232 | undoComposerDraftMergeState, |
| 233 | updateComposerDraftSettings, |
| 234 | } from "./use-composer-drafts"; |
| 235 | import { retainComposerAttachmentFileForPreview } from "../lib/composerAttachmentPreviewRetention"; |
| 236 | |
| 237 | const DRAFT: ComposerDraft = { |
| 238 | text: "hello", |
| 239 | attachments: [], |
| 240 | }; |
| 241 | |
| 242 | it.each(["picker open", "reading image"] as const)( |
| 243 | "recovers only accepted screenshots when a question is cancelled while %s", |
| 244 | async (stage) => { |
| 245 | const questionKey = questionAttachmentDraftKey( |
| 246 | EnvironmentId.make("environment"), |
| 247 | ThreadId.make("thread"), |
| 248 | RuntimeRequestId.make("input"), |
| 249 | "language", |
| 250 | ); |
| 251 | const threadKey = "environment:thread"; |
| 252 | const screenshot = { |
| 253 | canceled: false, |
| 254 | assets: [ |
| 255 | { |
| 256 | uri: "file:///picker/screenshot.png", |
| 257 | fileName: "screenshot.png", |
| 258 | type: "image", |
| 259 | mimeType: "image/png", |
| 260 | }, |
| 261 | ], |
| 262 | } as const; |
| 263 | const opened = Promise.withResolvers<void>(); |
| 264 | const selection = Promise.withResolvers<typeof screenshot>(); |
| 265 | const reading = Promise.withResolvers<void>(); |
| 266 | const bytes = Promise.withResolvers<string>(); |
| 267 | composerDraftFileMocks.readImage.mockImplementationOnce(() => { |
| 268 | reading.resolve(); |
| 269 | return bytes.promise; |
| 270 | }); |
| 271 | pickMedia.mockImplementationOnce(() => { |
| 272 | opened.resolve(); |
| 273 | return selection.promise; |
| 274 | }); |
| 275 | const picking = pickQuestionAttachments({ |
| 276 | key: questionKey, |
| 277 | kind: "media", |
| 278 | isActive: () => true, |
| 279 | append: (attachments) => appendComposerDraftAttachments(questionKey, attachments), |
| 280 | }); |
| 281 | if (stage === "reading image") { |
| 282 | selection.resolve(screenshot); |
| 283 | await Promise.race([reading.promise, picking]); |
| 284 | } else { |
| 285 | await Promise.race([opened.promise, picking]); |
| 286 | } |
| 287 | resolveQuestionImagePreparations(questionKey, threadKey); |
| 288 | selection.resolve(screenshot); |
| 289 | bytes.resolve("YWJj"); |
| 290 | await picking; |
| 291 | |
| 292 | expect(getComposerDraftSnapshot(questionKey).attachments).toEqual([]); |
| 293 | expect(getComposerDraftSnapshot(threadKey).attachments).toEqual( |
| 294 | stage === "picker open" |
| 295 | ? [] |
| 296 | : [ |
| 297 | expect.objectContaining({ |
| 298 | type: "image", |
| 299 | name: "screenshot.png", |
| 300 | dataUrl: "data:image/png;base64,YWJj", |
| 301 | }), |
| 302 | ], |
| 303 | ); |
| 304 | }, |
| 305 | ); |
| 306 | |
| 307 | afterEach(() => { |
| 308 | vi.useRealTimers(); |
| 309 | resetComposerDraftsLoadState(); |
| 310 | composerDraftFileMocks.setDocument({ schemaVersion: 1, drafts: {} }); |
| 311 | composerDraftFileMocks.setReadError(null); |
| 312 | composerDraftFileMocks.setWriteError(null); |
| 313 | composerDraftFileMocks.setNextWriteBarrier(null); |
| 314 | composerDraftFileMocks.setOnWrite(null); |
| 315 | composerDraftFileMocks.resetWrites(); |
| 316 | composerDraftFileMocks.readImage.mockReset(); |
| 317 | composerDraftFileMocks.readImage.mockResolvedValue("YWJj"); |
| 318 | appAtomRegistry.set(composerDraftsAtom, {}); |
| 319 | appAtomRegistry.set(composerCloudDraftsAtom, { accountId: null, signedOut: {} }); |
| 320 | appAtomRegistry.set(stickyComposerModelSelectionAtom, null); |
| 321 | appAtomRegistry.set(modelOptionMemoryAtom, {}); |
| 322 | appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {}); |
| 323 | composerAttachmentCleanupMocks.remove.mockClear(); |
| 324 | composerAttachmentCleanupMocks.releaseUploads.mockReset(); |
| 325 | composerAttachmentCleanupMocks.releaseUploads.mockResolvedValue(undefined); |
| 326 | incomingShareStorageMocks.load.mockReset(); |
| 327 | incomingShareStorageMocks.load.mockResolvedValue([]); |
| 328 | }); |
| 329 | |
| 330 | function contextDraft(start: number, count: number): ComposerDraft { |
| 331 | const records = Array.from({ length: count }, (_, index) => ({ |
| 332 | version: 1 as const, |
| 333 | contextId: ComposerContextId.make(`skill-${start + index}`), |
| 334 | kind: "skill" as const, |
| 335 | label: "Skill", |
| 336 | name: "skill", |
| 337 | })); |
| 338 | return { |
| 339 | text: records.map((record) => `[Skill](t3-context://v1/skill/${record.contextId})`).join(" "), |
| 340 | context: { version: 1, records }, |
| 341 | attachments: [], |
| 342 | }; |
| 343 | } |
| 344 | |
| 345 | function modelReconciliationHarness( |
| 346 | environmentId: EnvironmentId, |
| 347 | threadId: ThreadId, |
| 348 | initialStatus: EnvironmentShellStatus = "live", |
| 349 | ) { |
| 350 | const tasks: Array<() => void> = []; |
| 351 | const registry = AtomRegistry.make({ |
| 352 | scheduleTask: (task) => { |
| 353 | tasks.push(task); |
| 354 | return () => {}; |
| 355 | }, |
| 356 | }); |
| 357 | onTestFinished(() => registry.dispose()); |
| 358 | const flush = () => { |
| 359 | for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task(); |
| 360 | }; |
| 361 | const selectedThreadId = ThreadId.make("another-selected-thread"); |
| 362 | const initialSnapshot: OrchestrationV2ShellSnapshot = { |
| 363 | ...v2ShellSnapshot, |
| 364 | threads: [ |
| 365 | { ...v2ThreadShell, id: threadId }, |
| 366 | { ...v2ThreadShell, id: selectedThreadId }, |
| 367 | ], |
| 368 | }; |
| 369 | const shellStateAtom = Atom.make<EnvironmentShellState>({ |
| 370 | ...EMPTY_SHELL_STATE, |
| 371 | snapshot: Option.some(initialSnapshot), |
| 372 | status: initialStatus, |
| 373 | }); |
| 374 | const shellResultAtom = Atom.map(shellStateAtom, AsyncResult.success); |
| 375 | const snapshotAtom = createEnvironmentSnapshotAtom(() => shellResultAtom)(environmentId); |
| 376 | const catalogValueAtom = Atom.make({ |
| 377 | isReady: true, |
| 378 | entries: new Map([ |
| 379 | [ |
| 380 | environmentId, |
| 381 | { |
| 382 | target: new PrimaryConnectionTarget({ |
| 383 | environmentId, |
| 384 | label: "Environment", |
| 385 | httpBaseUrl: "https://example.test", |
| 386 | wsBaseUrl: "wss://example.test", |
| 387 | }), |
| 388 | profile: Option.none(), |
| 389 | enabled: true, |
| 390 | }, |
| 391 | ], |
| 392 | ]), |
| 393 | }); |
| 394 | const noPendingThreadIdsAtom = Atom.make((): ReadonlySet<ThreadId> => new Set()); |
| 395 | const shells = createEnvironmentThreadShellAtoms({ |
| 396 | catalogValueAtom, |
| 397 | snapshotAtom: () => snapshotAtom, |
| 398 | hiddenThreadTagsAtom: () => Atom.make(null), |
| 399 | }); |
| 400 | const selectedShell = shells.threadShellAtom({ environmentId, threadId: selectedThreadId }); |
| 401 | onTestFinished(registry.mount(selectedShell)); |
| 402 | onTestFinished( |
| 403 | subscribeComposerDraftModelReconciliation({ |
| 404 | registry, |
| 405 | threadShellAtom: shells.threadShellAtom, |
| 406 | threadRefsAtom: shells.threadRefsAtom, |
| 407 | shellStateAtom: () => shellResultAtom, |
| 408 | pendingThreadIdsAtom: () => noPendingThreadIdsAtom, |
| 409 | }), |
| 410 | ); |
| 411 | flush(); |
| 412 | return { |
| 413 | flush, |
| 414 | setStatus(status: EnvironmentShellStatus) { |
| 415 | registry.set(shellStateAtom, { ...registry.get(shellStateAtom), status }); |
| 416 | flush(); |
| 417 | }, |
| 418 | update(changes: Partial<OrchestrationV2ThreadShell>, status?: EnvironmentShellStatus) { |
| 419 | const state = registry.get(shellStateAtom); |
| 420 | const snapshot = Option.getOrThrow(state.snapshot); |
| 421 | registry.set(shellStateAtom, { |
| 422 | ...state, |
| 423 | status: status ?? state.status, |
| 424 | snapshot: Option.some( |
| 425 | applyShellStreamEvent(snapshot, { |
| 426 | kind: "thread.updated", |
| 427 | location: "active", |
| 428 | sequence: snapshot.snapshotSequence + 1, |
| 429 | thread: { ...snapshot.threads[0]!, ...changes }, |
| 430 | }), |
| 431 | ), |
| 432 | }); |
| 433 | flush(); |
| 434 | expect(registry.get(selectedShell)?.id).toBe(selectedThreadId); |
| 435 | }, |
| 436 | model: () => registry.get(shells.threadShellAtom({ environmentId, threadId }))!.modelSelection, |
| 437 | }; |
| 438 | } |
| 439 | |
| 440 | describe("mobile composer drafts", () => { |
| 441 | it.each([false, true])( |
| 442 | "restores visible file chips from legacy drafts (archived: %s)", |
| 443 | async (archived) => { |
| 444 | const file = { |
| 445 | type: "file" as const, |
| 446 | id: "legacy-file", |
| 447 | name: "notes.txt", |
| 448 | mimeType: "text/plain", |
| 449 | sizeBytes: 10, |
| 450 | fileUri: "file:///notes.txt", |
| 451 | }; |
| 452 | const image = { ...file, id: "photo", name: "photo.png", mimeType: "image/png" }; |
| 453 | const video = { ...file, id: "video", name: "clip.mp4", mimeType: "video/mp4" }; |
| 454 | const legacy = { text: "Review these", attachments: [file, image, video] }; |
| 455 | const document = { |
| 456 | schemaVersion: 1, |
| 457 | drafts: archived ? {} : { thread: legacy }, |
| 458 | ...(archived |
| 459 | ? { signedOutDrafts: { account: { drafts: { thread: legacy }, queuedMessages: [] } } } |
| 460 | : {}), |
| 461 | }; |
| 462 | const decoded = decodePersistedComposerState(document); |
| 463 | const restored = archived |
| 464 | ? decoded.cloudDrafts.signedOut.account?.drafts.thread |
| 465 | : decoded.drafts.thread; |
| 466 | expect(restored?.text).toBe("Review these [notes.txt](t3-context://v1/file/legacy-file) "); |
| 467 | expect(restored?.attachments).toEqual(legacy.attachments); |
| 468 | expect(restored?.context?.records).toEqual([ |
| 469 | expect.objectContaining({ kind: "file", attachmentId: file.id }), |
| 470 | ]); |
| 471 | expect( |
| 472 | decodePersistedComposerState({ schemaVersion: 1, drafts: { thread: restored } }).drafts |
| 473 | .thread, |
| 474 | ).toEqual(restored); |
| 475 | appAtomRegistry.set(composerDraftsAtom, { thread: restored! }); |
| 476 | setComposerDraftText("thread", "Review these"); |
| 477 | expect(getComposerDraftSnapshot("thread").attachments).toEqual([image, video]); |
| 478 | await releaseUnusedComposerAttachmentFiles([file]); |
| 479 | }, |
| 480 | ); |
| 481 | |
| 482 | it("restores a missing file reference without duplicating its record or replacing another record's id", () => { |
| 483 | const file = { |
| 484 | type: "file" as const, |
| 485 | id: "file", |
| 486 | name: "notes.txt", |
| 487 | mimeType: "text/plain", |
| 488 | sizeBytes: 10, |
| 489 | fileUri: "file:///notes.txt", |
| 490 | }; |
| 491 | const existing = { |
| 492 | version: 1, |
| 493 | contextId: "original", |
| 494 | kind: "file", |
| 495 | label: file.name, |
| 496 | attachmentId: file.id, |
| 497 | name: file.name, |
| 498 | mimeType: file.mimeType, |
| 499 | sizeBytes: file.sizeBytes, |
| 500 | }; |
| 501 | const skill = { version: 1, contextId: "file", kind: "skill", label: "Skill", name: "skill" }; |
| 502 | for (const records of [[existing, skill], [skill]]) { |
| 503 | const restored = decodePersistedComposerState({ |
| 504 | schemaVersion: 1, |
| 505 | drafts: { |
| 506 | thread: { text: "", attachments: [file], context: { version: 1, records } }, |
| 507 | }, |
| 508 | }).drafts.thread; |
| 509 | expect(restored?.context?.records).toHaveLength(2); |
| 510 | expect(restored?.context?.records).toContainEqual(skill); |
| 511 | expect(restored?.text).toBe( |
| 512 | `[notes.txt](t3-context://v1/file/${records.length === 2 ? "original" : "file_2"}) `, |
| 513 | ); |
| 514 | } |
| 515 | }); |
| 516 | it.each([false, true])( |
| 517 | "restores deleted file chips and releases undo history (uploaded: %s)", |
| 518 | async (uploaded) => { |
| 519 | const key = "environment:undo-file"; |
| 520 | const file = { |
| 521 | type: "file" as const, |
| 522 | id: "undo-file", |
| 523 | name: "notes.txt", |
| 524 | mimeType: "text/plain", |
| 525 | sizeBytes: 1, |
| 526 | fileUri: "file:///documents/t3-composer-attachments/undo-file.txt", |
| 527 | ...(uploaded |
| 528 | ? { |
| 529 | uploadedAttachmentId: "pending-upload", |
| 530 | uploadEnvironmentId: EnvironmentId.make("environment"), |
| 531 | } |
| 532 | : {}), |
| 533 | }; |
| 534 | appendComposerDraftAttachments(key, [file], { appendReference: true }); |
| 535 | const original = getComposerDraftSnapshot(key); |
| 536 | const history = createComposerDraftContextHistory(); |
| 537 | const changeText = (text: string) => { |
| 538 | const restored = history.restore(text, getComposerDraftSnapshot(key)); |
| 539 | setComposerDraftText(key, text); |
| 540 | setComposerDraftContext(key, restored.context); |
| 541 | appendComposerDraftAttachments(key, restored.attachments, { restore: true }); |
| 542 | }; |
| 543 | try { |
| 544 | changeText(""); |
| 545 | expect(getComposerDraftSnapshot(key).attachments).toEqual([]); |
| 546 | await releaseUnusedComposerAttachmentFiles([file]); |
| 547 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalledWith(file.fileUri); |
| 548 | changeText(original.text); |
| 549 | expect(getComposerDraftSnapshot(key).context).toEqual(original.context); |
| 550 | expect(getComposerDraftSnapshot(key).attachments).toEqual([ |
| 551 | { ...file, uploadedAttachmentId: undefined, uploadEnvironmentId: undefined }, |
| 552 | ]); |
| 553 | changeText(""); |
| 554 | } finally { |
| 555 | history.dispose(); |
| 556 | } |
| 557 | await releaseUnusedComposerAttachmentFiles([file]); |
| 558 | expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(file.fileUri); |
| 559 | }, |
| 560 | ); |
| 561 | |
| 562 | it("retains a pick matching cached state until the live shell confirms it", () => { |
| 563 | const environmentId = EnvironmentId.make("environment-1"); |
| 564 | const threadId = ThreadId.make("thread-1"); |
| 565 | const key = `${environmentId}:${threadId}`; |
| 566 | const h = modelReconciliationHarness(environmentId, threadId, "cached"); |
| 567 | const pick = h.model(); |
| 568 | updateComposerDraftSettings(key, { modelSelection: pick }); |
| 569 | h.flush(); |
| 570 | const before = getComposerDraftSnapshot(key); |
| 571 | expect(before.modelSelection).toEqual(pick); |
| 572 | |
| 573 | for (const status of ["empty", "synchronizing", "cached"] as const) { |
| 574 | h.setStatus(status); |
| 575 | expect(getComposerDraftSnapshot(key)).toEqual(before); |
| 576 | } |
| 577 | h.update({ modelSelection: { ...pick, model: "remote-model" } }, "live"); |
| 578 | expect(getComposerDraftSnapshot(key)).toEqual(before); |
| 579 | h.update({ modelSelection: pick }, "synchronizing"); |
| 580 | expect(getComposerDraftSnapshot(key)).toEqual(before); |
| 581 | h.setStatus("live"); |
| 582 | expect(appAtomRegistry.get(composerDraftsAtom)[key]).toBeUndefined(); |
| 583 | }); |
| 584 | |
| 585 | it("releases an inactive thread pick only after its queued model becomes durable", () => { |
| 586 | const environmentId = EnvironmentId.make("environment-1"); |
| 587 | const threadId = ThreadId.make("thread-1"); |
| 588 | const key = `${environmentId}:${threadId}`; |
| 589 | const pick = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.5" }; |
| 590 | setComposerDraftText(key, "keep this unsent follow-up"); |
| 591 | appendComposerDraftAttachments( |
| 592 | key, |
| 593 | [ |
| 594 | { |
| 595 | type: "file", |
| 596 | id: "file", |
| 597 | name: "notes.txt", |
| 598 | mimeType: "text/plain", |
| 599 | sizeBytes: 4, |
| 600 | fileUri: "file:///notes.txt", |
| 601 | }, |
| 602 | ], |
| 603 | { appendReference: true }, |
| 604 | ); |
| 605 | updateComposerDraftSettings(key, { |
| 606 | modelSelection: pick, |
| 607 | runtimeMode: "approval-required", |
| 608 | interactionMode: "plan", |
| 609 | }); |
| 610 | const before = getComposerDraftSnapshot(key); |
| 611 | const remoteKey = `environment-remote:${threadId}`; |
| 612 | updateComposerDraftSettings(remoteKey, { modelSelection: pick }); |
| 613 | const remoteBefore = getComposerDraftSnapshot(remoteKey); |
| 614 | const h = modelReconciliationHarness(environmentId, threadId); |
| 615 | |
| 616 | h.update({ status: "queued" }); |
| 617 | expect(getComposerDraftSnapshot(key)).toEqual(before); |
| 618 | h.update({ |
| 619 | status: "running", |
| 620 | modelSelection: { ...pick, options: [{ id: "fastMode", value: false }] }, |
| 621 | }); |
| 622 | expect(getComposerDraftSnapshot(key)).toEqual({ ...before, modelSelection: undefined }); |
| 623 | expect(getComposerDraftSnapshot(remoteKey)).toEqual(remoteBefore); |
| 624 | |
| 625 | h.update({ |
| 626 | modelSelection: { |
| 627 | instanceId: ProviderInstanceId.make("claudeAgent"), |
| 628 | model: "claude-opus-5-5", |
| 629 | }, |
| 630 | }); |
| 631 | expect(getComposerDraftSnapshot(key).modelSelection ?? h.model()).toEqual(h.model()); |
| 632 | expect(getComposerDraftSnapshot(key)).toEqual({ ...before, modelSelection: undefined }); |
| 633 | }); |
| 634 | |
| 635 | it("retains an unavailable provider pick through differing durable model updates", () => { |
| 636 | const environmentId = EnvironmentId.make("environment-1"); |
| 637 | const threadId = ThreadId.make("thread-1"); |
| 638 | const key = `${environmentId}:${threadId}`; |
| 639 | const pick: ModelSelection = { |
| 640 | instanceId: ProviderInstanceId.make("codex-secondary"), |
| 641 | model: "gpt-5.5", |
| 642 | options: [ |
| 643 | { id: "reasoningEffort", value: "high" }, |
| 644 | { id: "fastMode", value: true }, |
| 645 | ], |
| 646 | }; |
| 647 | updateComposerDraftSettings(key, { modelSelection: pick }); |
| 648 | const before = getComposerDraftSnapshot(key); |
| 649 | const h = modelReconciliationHarness(environmentId, threadId); |
| 650 | expect(getComposerDraftSnapshot(key)).toEqual(before); |
| 651 | for (const modelSelection of [ |
| 652 | { ...pick, instanceId: ProviderInstanceId.make("codex") }, |
| 653 | { ...pick, model: "gpt-5.4" }, |
| 654 | { ...pick, options: [{ id: "reasoningEffort", value: "high" }] }, |
| 655 | { |
| 656 | ...pick, |
| 657 | options: [ |
| 658 | { id: "reasoningEffort", value: "low" }, |
| 659 | { id: "fastMode", value: true }, |
| 660 | ], |
| 661 | }, |
| 662 | ]) { |
| 663 | h.update({ modelSelection }); |
| 664 | expect(getComposerDraftSnapshot(key)).toEqual(before); |
| 665 | } |
| 666 | h.update({ modelSelection: { ...pick, options: pick.options!.toReversed() } }); |
| 667 | expect(appAtomRegistry.get(composerDraftsAtom)[key]).toBeUndefined(); |
| 668 | }); |
| 669 | |
| 670 | it("drops chips and records for attachments a replace no longer keeps", () => { |
| 671 | const key = "new-task:draft-1"; |
| 672 | const kept = { |
| 673 | type: "file" as const, |
| 674 | id: "kept-file", |
| 675 | name: "kept.txt", |
| 676 | mimeType: "text/plain", |
| 677 | sizeBytes: 1, |
| 678 | fileUri: "file:///kept.txt", |
| 679 | }; |
| 680 | const dropped = { |
| 681 | type: "file" as const, |
| 682 | id: "dropped-file", |
| 683 | name: "dropped.txt", |
| 684 | mimeType: "text/plain", |
| 685 | sizeBytes: 1, |
| 686 | fileUri: "file:///dropped.txt", |
| 687 | }; |
| 688 | appendComposerDraftAttachments(key, [kept, dropped], { appendReference: true }); |
| 689 | |
| 690 | const before = getComposerDraftSnapshot(key); |
| 691 | expect(before.text).toContain("dropped.txt"); |
| 692 | expect(before.context?.records).toHaveLength(2); |
| 693 | |
| 694 | replaceComposerDraftAttachments(key, [kept]); |
| 695 | |
| 696 | const after = getComposerDraftSnapshot(key); |
| 697 | expect(after.attachments.map((attachment) => attachment.id)).toEqual([kept.id]); |
| 698 | expect(after.text).not.toContain("dropped.txt"); |
| 699 | expect(after.context?.records.map((record) => record.contextId)).toEqual([ |
| 700 | before.context?.records[0]?.contextId, |
| 701 | ]); |
| 702 | }); |
| 703 | |
| 704 | it("keeps over-limit recovery context reloadable without losing other drafts", () => { |
| 705 | const key = "environment-1:recovery"; |
| 706 | const merged = mergeComposerDraftContentState( |
| 707 | { [key]: contextDraft(0, 200), other: DRAFT }, |
| 708 | key, |
| 709 | contextDraft(200, 200), |
| 710 | ); |
| 711 | expect(merged[key]?.context?.records).toHaveLength(400); |
| 712 | const reloaded = decodePersistedComposerState( |
| 713 | JSON.parse(JSON.stringify({ schemaVersion: 1, drafts: merged })), |
| 714 | ).drafts; |
| 715 | expect(reloaded[key]).toEqual(merged[key]); |
| 716 | expect(reloaded.other).toEqual(DRAFT); |
| 717 | }); |
| 718 | |
| 719 | it("prunes unreferenced context during a content merge", () => { |
| 720 | const existing = contextDraft(0, 2); |
| 721 | const incoming = contextDraft(2, 2); |
| 722 | const merged = mergeComposerDraftContentState( |
| 723 | { key: { ...existing, text: "[Skill](t3-context://v1/skill/skill-0)" } }, |
| 724 | "key", |
| 725 | { ...incoming, text: "[Skill](t3-context://v1/skill/skill-2)" }, |
| 726 | ); |
| 727 | expect(merged.key?.context?.records.map((record) => record.contextId)).toEqual([ |
| 728 | "skill-0", |
| 729 | "skill-2", |
| 730 | ]); |
| 731 | }); |
| 732 | |
| 733 | it("restores and persists both full cloud and live context drafts", async () => { |
| 734 | const load = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 735 | onTestFinished(() => load.mockRestore()); |
| 736 | await waitForComposerDraftsLoaded(); |
| 737 | const key = "environment-1:restored"; |
| 738 | appAtomRegistry.set(composerDraftsAtom, { [key]: contextDraft(0, 200) }); |
| 739 | appAtomRegistry.set(composerCloudDraftsAtom, { |
| 740 | accountId: null, |
| 741 | signedOut: { account: { drafts: { [key]: contextDraft(200, 200) }, queuedMessages: [] } }, |
| 742 | }); |
| 743 | await restoreCloudComposerDrafts("account"); |
| 744 | expect(getComposerDraftSnapshot(key).context?.records).toHaveLength(400); |
| 745 | const reloaded = decodePersistedComposerState(JSON.parse(composerDraftFileMocks.getDocument())); |
| 746 | expect(reloaded.drafts[key]?.context?.records).toHaveLength(400); |
| 747 | expect(reloaded.cloudDrafts.signedOut).toEqual({}); |
| 748 | }); |
| 749 | |
| 750 | it.each([ |
| 751 | { name: "notes.txt", mimeType: "text/plain" }, |
| 752 | { name: "document-photo.png", mimeType: "image/png" }, |
| 753 | { name: "recording.mp4", mimeType: "video/mp4" }, |
| 754 | ])( |
| 755 | "removes $name after its last reference is deleted, while retaining native images", |
| 756 | async ({ name, mimeType }) => { |
| 757 | const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 758 | onTestFinished(() => outboxLoad.mockRestore()); |
| 759 | const cleanup = Promise.withResolvers<void>(); |
| 760 | composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => { |
| 761 | cleanup.resolve(); |
| 762 | }); |
| 763 | const key = "environment-1:remove-context-files"; |
| 764 | const file = { |
| 765 | id: "file-1", |
| 766 | type: "file" as const, |
| 767 | name, |
| 768 | mimeType, |
| 769 | sizeBytes: 4, |
| 770 | fileUri: `file:///${name}`, |
| 771 | }; |
| 772 | const image = { |
| 773 | ...file, |
| 774 | id: "image-1", |
| 775 | type: "image" as const, |
| 776 | name: "image.png", |
| 777 | mimeType: "image/png", |
| 778 | fileUri: "file:///image.png", |
| 779 | previewUri: "file:///image.png", |
| 780 | }; |
| 781 | appendComposerDraftAttachments(key, [file, image], { appendReference: true }); |
| 782 | const fileLink = formatComposerContextReference( |
| 783 | getComposerDraftSnapshot(key).context!.records[0]!, |
| 784 | ); |
| 785 | setComposerDraftText(key, `${fileLink} ${fileLink}`); |
| 786 | expect(getComposerDraftSnapshot(key).attachments).toEqual([file, image]); |
| 787 | setComposerDraftText(key, fileLink); |
| 788 | expect(getComposerDraftSnapshot(key).attachments).toEqual([file, image]); |
| 789 | expect( |
| 790 | countComposerDraftAttachmentsAfterSelection(key, { |
| 791 | text: fileLink, |
| 792 | start: 0, |
| 793 | end: fileLink.length, |
| 794 | }), |
| 795 | ).toBe(1); |
| 796 | setComposerDraftText(key, "plain text"); |
| 797 | expect(getComposerDraftSnapshot(key).attachments).toEqual([image]); |
| 798 | await cleanup.promise; |
| 799 | }, |
| 800 | ); |
| 801 | |
| 802 | it("rejects attachments atomically when no context slots remain", async () => { |
| 803 | const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 804 | onTestFinished(() => outboxLoad.mockRestore()); |
| 805 | const cleanup = Promise.withResolvers<void>(); |
| 806 | composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => { |
| 807 | cleanup.resolve(); |
| 808 | }); |
| 809 | const key = "environment-1:full-context"; |
| 810 | const records = Array.from({ length: 200 }, (_, index) => ({ |
| 811 | version: 1 as const, |
| 812 | contextId: `ctx-${index}` as never, |
| 813 | kind: "skill" as const, |
| 814 | label: "Skill", |
| 815 | name: "skill", |
| 816 | })); |
| 817 | appAtomRegistry.set(composerDraftsAtom, { |
| 818 | [key]: { |
| 819 | text: records |
| 820 | .map((record) => `[Skill](t3-context://v1/skill/${record.contextId})`) |
| 821 | .join(" "), |
| 822 | context: { version: 1, records }, |
| 823 | attachments: [], |
| 824 | }, |
| 825 | }); |
| 826 | const before = getComposerDraftSnapshot(key); |
| 827 | expect( |
| 828 | appendComposerDraftAttachments( |
| 829 | key, |
| 830 | [ |
| 831 | { |
| 832 | id: "overflow", |
| 833 | type: "file", |
| 834 | name: "notes.txt", |
| 835 | mimeType: "text/plain", |
| 836 | sizeBytes: 4, |
| 837 | fileUri: "file:///overflow.txt", |
| 838 | }, |
| 839 | ], |
| 840 | { appendReference: true }, |
| 841 | ), |
| 842 | ).toBe(1); |
| 843 | expect(getComposerDraftSnapshot(key)).toEqual(before); |
| 844 | await cleanup.promise; |
| 845 | }); |
| 846 | it.each(["environment-1:thread", "environment-1:new-task:draft"])( |
| 847 | "preserves the captured paste selection across async writes in %s", |
| 848 | async (key) => { |
| 849 | const file = { |
| 850 | id: "paste", |
| 851 | type: "file" as const, |
| 852 | name: "pasted-text.txt", |
| 853 | mimeType: "text/plain", |
| 854 | sizeBytes: 40_000, |
| 855 | fileUri: "file:///paste.txt", |
| 856 | }; |
| 857 | setComposerDraftText(key, "before selected after"); |
| 858 | const insertion = captureComposerDraftInsertion(key, { start: 7, end: 15 }); |
| 859 | const write = Promise.withResolvers<typeof file>(); |
| 860 | const pending = write.promise.then((attachment) => |
| 861 | appendComposerDraftAttachments(key, [attachment], { appendReference: true, insertion }), |
| 862 | ); |
| 863 | rememberComposerDraftSelection(key, insertion.text, { start: 0, end: 6 }); |
| 864 | rememberComposerDraftSelection("another-draft", "unrelated", { start: 0, end: 9 }); |
| 865 | write.resolve(file); |
| 866 | expect(await pending).toBe(0); |
| 867 | const draft = getComposerDraftSnapshot(key); |
| 868 | expect(draft.text).toBe("before [pasted-text.txt](t3-context://v1/file/paste) after"); |
| 869 | expect(draft.attachments).toEqual([file]); |
| 870 | }, |
| 871 | ); |
| 872 | |
| 873 | it("preserves edits made while a paste is pending instead of deleting stale offsets", async () => { |
| 874 | const key = "environment-1:typing-during-paste"; |
| 875 | setComposerDraftText(key, "old selection"); |
| 876 | const insertion = captureComposerDraftInsertion(key, { start: 0, end: 13 }); |
| 877 | const write = Promise.withResolvers<void>(); |
| 878 | const pending = write.promise.then(() => insertComposerDraftText(key, " pasted", insertion)); |
| 879 | setComposerDraftText(key, "keep newly typed text"); |
| 880 | write.resolve(); |
| 881 | await pending; |
| 882 | expect(getComposerDraftSnapshot(key).text).toBe("keep newly typed text pasted"); |
| 883 | }); |
| 884 | |
| 885 | it("keeps a pending paste before text typed at its caret, and the caret after that text", async () => { |
| 886 | const key = "environment-1:typing-at-paste-point"; |
| 887 | const image = { |
| 888 | id: "image", |
| 889 | type: "file" as const, |
| 890 | name: "picture.png", |
| 891 | mimeType: "text/plain", |
| 892 | sizeBytes: 4, |
| 893 | fileUri: "file:///picture.png", |
| 894 | }; |
| 895 | setComposerDraftText(key, "Before "); |
| 896 | const insertion = captureComposerDraftInsertion(key, { start: 7, end: 7 }); |
| 897 | const write = Promise.withResolvers<void>(); |
| 898 | const pending = write.promise.then(() => |
| 899 | appendComposerDraftAttachments(key, [image], { appendReference: true, insertion }), |
| 900 | ); |
| 901 | setComposerDraftText(key, "Before yaz"); |
| 902 | rememberComposerDraftSelection(key, "Before yaz", { start: 10, end: 10 }); |
| 903 | write.resolve(); |
| 904 | expect(await pending).toBe(0); |
| 905 | const link = "[picture.png](t3-context://v1/file/image)"; |
| 906 | expect(getComposerDraftSnapshot(key).text).toBe(`Before ${link} yaz`); |
| 907 | const caret = `Before ${link} yaz`.length; |
| 908 | expect(captureComposerDraftInsertion(key)).toMatchObject({ start: caret, end: caret }); |
| 909 | }); |
| 910 | |
| 911 | it.each(["attachment", "context", "imported context"])( |
| 912 | "releases a selected file when replaced by %s", |
| 913 | async (kind) => { |
| 914 | const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 915 | onTestFinished(() => outboxLoad.mockRestore()); |
| 916 | const cleanup = Promise.withResolvers<void>(); |
| 917 | composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => { |
| 918 | cleanup.resolve(); |
| 919 | return undefined; |
| 920 | }); |
| 921 | const key = "environment-1:replace-file"; |
| 922 | const files = Array.from({ length: 100 }, (_, index) => ({ |
| 923 | id: `file-${index}`, |
| 924 | type: "file" as const, |
| 925 | name: `notes-${index}.txt`, |
| 926 | mimeType: "text/plain", |
| 927 | sizeBytes: 4, |
| 928 | fileUri: `file:///notes-${index}.txt`, |
| 929 | })); |
| 930 | appendComposerDraftAttachments(key, files, { appendReference: true }); |
| 931 | const firstLink = "[notes-0.txt](t3-context://v1/file/file-0)"; |
| 932 | const insertion = captureComposerDraftInsertion(key, { start: 0, end: firstLink.length }); |
| 933 | expect(countComposerDraftAttachmentsAfterSelection(key, insertion)).toBe(99); |
| 934 | expect(getComposerDraftAfterSelection(key, insertion).context?.records).toHaveLength(99); |
| 935 | const replacement = { ...files[0]!, id: "replacement", fileUri: "file:///replacement.txt" }; |
| 936 | if (kind === "attachment") { |
| 937 | expect( |
| 938 | appendComposerDraftAttachments(key, [replacement], { appendReference: true, insertion }), |
| 939 | ).toBe(0); |
| 940 | } else if (kind === "imported context") { |
| 941 | const record = { |
| 942 | version: 1 as const, |
| 943 | kind: "file" as const, |
| 944 | contextId: ComposerContextId.make("replacement"), |
| 945 | attachmentId: replacement.id, |
| 946 | label: replacement.name, |
| 947 | name: replacement.name, |
| 948 | mimeType: replacement.mimeType, |
| 949 | sizeBytes: replacement.sizeBytes, |
| 950 | }; |
| 951 | expect( |
| 952 | insertComposerDraftContext( |
| 953 | key, |
| 954 | { |
| 955 | text: formatComposerContextReference(record), |
| 956 | context: { version: 1, records: [record] }, |
| 957 | attachments: [replacement], |
| 958 | }, |
| 959 | insertion, |
| 960 | ), |
| 961 | ).toBe(true); |
| 962 | expect(getComposerDraftSnapshot(key).attachments).toHaveLength(100); |
| 963 | expect(getComposerDraftSnapshot(key).context?.records).toContainEqual(record); |
| 964 | expect(getComposerDraftSnapshot(key).text).toBe( |
| 965 | `${formatComposerContextReference(record)}${insertion.text.slice(firstLink.length)}`, |
| 966 | ); |
| 967 | } else { |
| 968 | insertComposerDraftContext( |
| 969 | key, |
| 970 | { text: "replacement", context: { version: 1, records: [] } }, |
| 971 | insertion, |
| 972 | ); |
| 973 | } |
| 974 | const draft = getComposerDraftSnapshot(key); |
| 975 | expect(draft.attachments.map((file) => file.id)).not.toContain("file-0"); |
| 976 | expect(draft.attachments.slice(0, 99)).toEqual(files.slice(1)); |
| 977 | expect(draft.context?.records.some((record) => record.contextId === "file-0")).toBe(false); |
| 978 | await cleanup.promise; |
| 979 | expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(files[0]!.fileUri); |
| 980 | }, |
| 981 | ); |
| 982 | |
| 983 | it("rejects an imported file atomically when edits during import use up its replacement slot", async () => { |
| 984 | const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 985 | onTestFinished(() => outboxLoad.mockRestore()); |
| 986 | const cleanup = Promise.withResolvers<void>(); |
| 987 | composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => { |
| 988 | cleanup.resolve(); |
| 989 | return undefined; |
| 990 | }); |
| 991 | const key = "environment-1:concurrent-import"; |
| 992 | const files = Array.from({ length: 100 }, (_, index) => ({ |
| 993 | id: `existing-${index}`, |
| 994 | type: "file" as const, |
| 995 | name: `notes-${index}.txt`, |
| 996 | mimeType: "text/plain", |
| 997 | sizeBytes: 4, |
| 998 | fileUri: `file:///notes-${index}.txt`, |
| 999 | })); |
| 1000 | appendComposerDraftAttachments(key, files, { appendReference: true }); |
| 1001 | const firstLink = "[notes-0.txt](t3-context://v1/file/existing-0)"; |
| 1002 | const insertion = captureComposerDraftInsertion(key, { start: 0, end: firstLink.length }); |
| 1003 | setComposerDraftText(key, `New edit ${insertion.text}`); |
| 1004 | const edited = getComposerDraftSnapshot(key); |
| 1005 | const imported = { ...files[0]!, id: "imported", fileUri: "file:///imported.txt" }; |
| 1006 | const record = { |
| 1007 | version: 1 as const, |
| 1008 | kind: "file" as const, |
| 1009 | contextId: ComposerContextId.make("imported"), |
| 1010 | attachmentId: imported.id, |
| 1011 | label: imported.name, |
| 1012 | name: imported.name, |
| 1013 | mimeType: imported.mimeType, |
| 1014 | sizeBytes: imported.sizeBytes, |
| 1015 | }; |
| 1016 | expect( |
| 1017 | insertComposerDraftContext( |
| 1018 | key, |
| 1019 | { |
| 1020 | text: formatComposerContextReference(record), |
| 1021 | context: { version: 1, records: [record] }, |
| 1022 | attachments: [imported], |
| 1023 | }, |
| 1024 | insertion, |
| 1025 | ), |
| 1026 | ).toBe(false); |
| 1027 | expect(getComposerDraftSnapshot(key)).toEqual(edited); |
| 1028 | await cleanup.promise; |
| 1029 | expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(imported.fileUri); |
| 1030 | }); |
| 1031 | |
| 1032 | it("retains a file when replacing only one of its repeated references", () => { |
| 1033 | const key = "environment-1:repeat-reference"; |
| 1034 | const file = { |
| 1035 | id: "repeat", |
| 1036 | type: "file" as const, |
| 1037 | name: "notes.txt", |
| 1038 | mimeType: "text/plain", |
| 1039 | sizeBytes: 4, |
| 1040 | fileUri: "file:///repeat.txt", |
| 1041 | }; |
| 1042 | appendComposerDraftAttachments(key, [file], { appendReference: true }); |
| 1043 | const link = getComposerDraftSnapshot(key).text; |
| 1044 | setComposerDraftText(key, `${link} ${link}`); |
| 1045 | const insertion = captureComposerDraftInsertion(key, { start: 0, end: link.length }); |
| 1046 | expect(countComposerDraftAttachmentsAfterSelection(key, insertion)).toBe(1); |
| 1047 | insertComposerDraftContext( |
| 1048 | key, |
| 1049 | { text: "replaced", context: { version: 1, records: [] } }, |
| 1050 | insertion, |
| 1051 | ); |
| 1052 | expect(getComposerDraftSnapshot(key).attachments).toEqual([file]); |
| 1053 | expect(getComposerDraftSnapshot(key).text).toBe(`replaced ${link}`); |
| 1054 | }); |
| 1055 | |
| 1056 | it("inserts context at the saved caret and retains its payload through persistence and restore", () => { |
| 1057 | const draftKey = "context-environment:context-thread"; |
| 1058 | const record = { |
| 1059 | version: 1 as const, |
| 1060 | kind: "terminal" as const, |
| 1061 | contextId: ComposerContextId.make("context-terminal"), |
| 1062 | label: "Build output", |
| 1063 | terminalId: "main", |
| 1064 | terminalLabel: "Terminal", |
| 1065 | lineStart: 1, |
| 1066 | lineEnd: 1, |
| 1067 | text: "Build failed", |
| 1068 | }; |
| 1069 | const reference = "[Build output](t3-context://v1/terminal/context-terminal)"; |
| 1070 | setComposerDraftText(draftKey, "Fix this next"); |
| 1071 | rememberComposerDraftSelection(draftKey, "Fix this next", { start: 4, end: 8 }); |
| 1072 | insertComposerDraftContext(draftKey, { |
| 1073 | text: reference, |
| 1074 | context: { version: 1, records: [record] }, |
| 1075 | }); |
| 1076 | const draft = getComposerDraftSnapshot(draftKey); |
| 1077 | expect(draft.text).toBe(`Fix ${reference} next`); |
| 1078 | const decoded = decodePersistedComposerState( |
| 1079 | JSON.parse(JSON.stringify({ schemaVersion: 1, drafts: { [draftKey]: draft } })), |
| 1080 | ).drafts[draftKey]; |
| 1081 | expect(decoded?.context?.records).toEqual([record]); |
| 1082 | const restored = mergeComposerDraftContentState( |
| 1083 | { [draftKey]: { text: "Additional work", attachments: [] } }, |
| 1084 | draftKey, |
| 1085 | decoded!, |
| 1086 | ); |
| 1087 | expect(restored[draftKey]?.text).toContain(reference); |
| 1088 | expect(restored[draftKey]?.context?.records).toEqual([record]); |
| 1089 | expect(clearComposerDraftContentState(restored, draftKey)[draftKey]?.context).toBeUndefined(); |
| 1090 | setComposerDraftText(draftKey, "Fix next"); |
| 1091 | expect(getComposerDraftSnapshot(draftKey).context).toBeUndefined(); |
| 1092 | }); |
| 1093 | |
| 1094 | it("keeps each draft's caret when another composer moves its own caret", () => { |
| 1095 | const threadKey = "caret-environment:caret-thread"; |
| 1096 | const newTaskKey = "caret-environment:new-task:caret-draft"; |
| 1097 | setComposerDraftText(threadKey, "Fix this next"); |
| 1098 | setComposerDraftText(newTaskKey, "Another task"); |
| 1099 | rememberComposerDraftSelection(threadKey, "Fix this next", { start: 4, end: 8 }); |
| 1100 | rememberComposerDraftSelection(newTaskKey, "Another task", { start: 2, end: 2 }); |
| 1101 | insertComposerDraftContext(threadKey, { |
| 1102 | text: "[Build output](t3-context://v1/terminal/caret-terminal)", |
| 1103 | context: { |
| 1104 | version: 1, |
| 1105 | records: [ |
| 1106 | { |
| 1107 | version: 1, |
| 1108 | kind: "terminal", |
| 1109 | contextId: ComposerContextId.make("caret-terminal"), |
| 1110 | label: "Build output", |
| 1111 | terminalId: "main", |
| 1112 | terminalLabel: "Terminal", |
| 1113 | lineStart: 1, |
| 1114 | lineEnd: 1, |
| 1115 | text: "Build failed", |
| 1116 | }, |
| 1117 | ], |
| 1118 | }, |
| 1119 | }); |
| 1120 | expect(getComposerDraftSnapshot(threadKey).text).toBe( |
| 1121 | "Fix [Build output](t3-context://v1/terminal/caret-terminal) next", |
| 1122 | ); |
| 1123 | }); |
| 1124 | |
| 1125 | it("releases videos rejected by the live draft limit and keeps accepted files", async () => { |
| 1126 | const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 1127 | onTestFinished(() => outboxLoad.mockRestore()); |
| 1128 | const cleanup = Promise.withResolvers<void>(); |
| 1129 | composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => { |
| 1130 | cleanup.resolve(); |
| 1131 | }); |
| 1132 | const makeAttachment = (id: string) => ({ |
| 1133 | id, |
| 1134 | type: "file" as const, |
| 1135 | name: `${id}.mov`, |
| 1136 | mimeType: "video/quicktime", |
| 1137 | sizeBytes: 42, |
| 1138 | fileUri: `file:///documents/t3-composer-attachments/${id}.mov`, |
| 1139 | }); |
| 1140 | const draftKey = "new-task:environment-1:project-cap"; |
| 1141 | const existing = Array.from({ length: 99 }, (_, index) => makeAttachment(`held-${index}`)); |
| 1142 | appAtomRegistry.set(composerDraftsAtom, { |
| 1143 | [draftKey]: { text: "send this", attachments: existing }, |
| 1144 | }); |
| 1145 | |
| 1146 | const rejected = appendComposerDraftAttachments(draftKey, [ |
| 1147 | makeAttachment("incoming-1"), |
| 1148 | makeAttachment("incoming-2"), |
| 1149 | ]); |
| 1150 | |
| 1151 | expect(rejected).toBe(1); |
| 1152 | const draft = appAtomRegistry.get(composerDraftsAtom)[draftKey]; |
| 1153 | expect(draft?.attachments).toHaveLength(100); |
| 1154 | expect(draft?.attachments.at(-1)?.id).toBe("incoming-1"); |
| 1155 | await cleanup.promise; |
| 1156 | expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledExactlyOnceWith( |
| 1157 | makeAttachment("incoming-2").fileUri, |
| 1158 | ); |
| 1159 | |
| 1160 | const overflowRejected = appendComposerDraftAttachments( |
| 1161 | draftKey, |
| 1162 | [makeAttachment("restored-1")], |
| 1163 | { restore: true }, |
| 1164 | ); |
| 1165 | expect(overflowRejected).toBe(0); |
| 1166 | expect(appAtomRegistry.get(composerDraftsAtom)[draftKey]?.attachments).toHaveLength(101); |
| 1167 | }); |
| 1168 | |
| 1169 | it("drops duplicate attachments, releases their files, and keeps them on restore", async () => { |
| 1170 | const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 1171 | onTestFinished(() => outboxLoad.mockRestore()); |
| 1172 | const cleanup = Promise.withResolvers<void>(); |
| 1173 | composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => { |
| 1174 | cleanup.resolve(); |
| 1175 | }); |
| 1176 | const makeVideo = (id: string) => ({ |
| 1177 | id, |
| 1178 | type: "file" as const, |
| 1179 | name: "clip.mov", |
| 1180 | mimeType: "video/quicktime", |
| 1181 | sizeBytes: 42, |
| 1182 | fileUri: `file:///documents/t3-composer-attachments/${id}.mov`, |
| 1183 | }); |
| 1184 | const draftKey = "new-task:environment-1:project-duplicates"; |
| 1185 | appAtomRegistry.set(composerDraftsAtom, { |
| 1186 | [draftKey]: { text: "", attachments: [makeVideo("held")] }, |
| 1187 | }); |
| 1188 | |
| 1189 | expect( |
| 1190 | appendComposerDraftAttachments(draftKey, [makeVideo("again"), makeVideo("again-2")]), |
| 1191 | ).toBe(0); |
| 1192 | expect(appAtomRegistry.get(composerDraftsAtom)[draftKey]?.attachments).toEqual([ |
| 1193 | makeVideo("held"), |
| 1194 | ]); |
| 1195 | await cleanup.promise; |
| 1196 | expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(makeVideo("again").fileUri); |
| 1197 | |
| 1198 | appendComposerDraftAttachments(draftKey, [makeVideo("restored")], { restore: true }); |
| 1199 | expect(appAtomRegistry.get(composerDraftsAtom)[draftKey]?.attachments).toHaveLength(2); |
| 1200 | |
| 1201 | // Every native paste is named pasted-image.png, so only the bytes tell two pastes apart. |
| 1202 | const makePaste = (id: string, base64: string) => ({ |
| 1203 | id, |
| 1204 | type: "image" as const, |
| 1205 | name: "pasted-image.png", |
| 1206 | mimeType: "image/png", |
| 1207 | sizeBytes: 3, |
| 1208 | dataUrl: `data:image/png;base64,${base64}`, |
| 1209 | previewUri: `data:image/png;base64,${base64}`, |
| 1210 | }); |
| 1211 | const pasteKey = "new-task:environment-1:project-pastes"; |
| 1212 | appendComposerDraftAttachments(pasteKey, [makePaste("red", "AQID")]); |
| 1213 | appendComposerDraftAttachments(pasteKey, [ |
| 1214 | makePaste("blue", "BAUG"), |
| 1215 | makePaste("red-2", "AQID"), |
| 1216 | ]); |
| 1217 | expect( |
| 1218 | appAtomRegistry.get(composerDraftsAtom)[pasteKey]?.attachments.map(({ id }) => id), |
| 1219 | ).toEqual(["red", "blue"]); |
| 1220 | }); |
| 1221 | |
| 1222 | it("keeps shared attachment files until every draft releases them", async () => { |
| 1223 | const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 1224 | onTestFinished(() => outboxLoad.mockRestore()); |
| 1225 | const file = { |
| 1226 | id: "file-1", |
| 1227 | type: "file" as const, |
| 1228 | name: "report.pdf", |
| 1229 | mimeType: "application/pdf", |
| 1230 | sizeBytes: 42, |
| 1231 | fileUri: "file:///documents/t3-composer-attachments/report.pdf", |
| 1232 | }; |
| 1233 | appAtomRegistry.set(composerDraftsAtom, { |
| 1234 | source: { text: "First draft", attachments: [file] }, |
| 1235 | copied: { text: "Second draft", attachments: [file] }, |
| 1236 | }); |
| 1237 | |
| 1238 | await releaseUnusedComposerAttachmentFiles([file]); |
| 1239 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 1240 | |
| 1241 | appAtomRegistry.set(composerDraftsAtom, { |
| 1242 | copied: { text: "Second draft", attachments: [file] }, |
| 1243 | }); |
| 1244 | await releaseUnusedComposerAttachmentFiles([file]); |
| 1245 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 1246 | |
| 1247 | appAtomRegistry.set(composerDraftsAtom, {}); |
| 1248 | await releaseUnusedComposerAttachmentFiles([file]); |
| 1249 | expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(file.fileUri); |
| 1250 | }); |
| 1251 | |
| 1252 | it("retains a referenced file-backed image and releases it once unreferenced", async () => { |
| 1253 | const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 1254 | onTestFinished(() => outboxLoad.mockRestore()); |
| 1255 | const image = { |
| 1256 | id: "image-1", |
| 1257 | type: "image" as const, |
| 1258 | name: "photo.png", |
| 1259 | mimeType: "image/png", |
| 1260 | sizeBytes: 3, |
| 1261 | fileUri: "file:///documents/t3-composer-attachments/photo.png", |
| 1262 | previewUri: "file:///documents/t3-composer-attachments/photo.png", |
| 1263 | }; |
| 1264 | appAtomRegistry.set(composerDraftsAtom, { |
| 1265 | "environment-1:thread-1": { text: "look at this", attachments: [image] }, |
| 1266 | }); |
| 1267 | |
| 1268 | await releaseUnusedComposerAttachmentFiles([image]); |
| 1269 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 1270 | |
| 1271 | appAtomRegistry.set(composerDraftsAtom, {}); |
| 1272 | appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, { |
| 1273 | "environment-1:thread-1": [ |
| 1274 | { |
| 1275 | environmentId: EnvironmentId.make("environment-1"), |
| 1276 | threadId: ThreadId.make("thread-1"), |
| 1277 | messageId: MessageId.make("queued-image"), |
| 1278 | commandId: CommandId.make("command-image"), |
| 1279 | text: "look at this", |
| 1280 | attachments: [image], |
| 1281 | createdAt: "2026-08-31T12:00:00.000Z", |
| 1282 | }, |
| 1283 | ], |
| 1284 | }); |
| 1285 | await releaseUnusedComposerAttachmentFiles([image]); |
| 1286 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 1287 | |
| 1288 | appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {}); |
| 1289 | await releaseUnusedComposerAttachmentFiles([image]); |
| 1290 | expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledExactlyOnceWith(image.fileUri); |
| 1291 | }); |
| 1292 | |
| 1293 | it.effect("keeps an image through an inline read after its draft is removed", () => |
| 1294 | Effect.gen(function* () { |
| 1295 | const { prepareTurnAttachments } = yield* Effect.promise(() => |
| 1296 | vi.importActual<typeof import("../lib/attachmentUpload")>("../lib/attachmentUpload"), |
| 1297 | ); |
| 1298 | const image = { |
| 1299 | id: "image-reading", |
| 1300 | type: "image" as const, |
| 1301 | name: "photo.png", |
| 1302 | mimeType: "image/png", |
| 1303 | sizeBytes: 3, |
| 1304 | fileUri: "file:///documents/t3-composer-attachments/photo.png", |
| 1305 | previewUri: "file:///documents/t3-composer-attachments/photo.png", |
| 1306 | }; |
| 1307 | const readStarted = Promise.withResolvers<void>(); |
| 1308 | const read = Promise.withResolvers<void>(); |
| 1309 | const removed = Promise.withResolvers<void>(); |
| 1310 | let imageExists = true; |
| 1311 | composerDraftFileMocks.readImage.mockImplementation(async () => { |
| 1312 | readStarted.resolve(); |
| 1313 | await read.promise; |
| 1314 | if (!imageExists) throw new Error("The image was deleted during its read"); |
| 1315 | return "YWJj"; |
| 1316 | }); |
| 1317 | composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => { |
| 1318 | imageExists = false; |
| 1319 | removed.resolve(); |
| 1320 | }); |
| 1321 | appendComposerDraftAttachments("environment-1:thread-1", [image]); |
| 1322 | yield* Effect.promise(() => flushComposerDrafts()); |
| 1323 | // Without image uploads the image is inlined, so nothing goes through the upload registry. |
| 1324 | const preparing = yield* Effect.forkChild( |
| 1325 | prepareTurnAttachments({ |
| 1326 | environmentId: EnvironmentId.make("environment-1"), |
| 1327 | attachments: [image], |
| 1328 | uploadAttachment: vi.fn(), |
| 1329 | }), |
| 1330 | ); |
| 1331 | onTestFinished(() => read.resolve()); |
| 1332 | yield* Effect.promise(() => readStarted.promise); |
| 1333 | clearComposerDraftContent("environment-1:thread-1", { deferAttachmentCleanup: true }); |
| 1334 | yield* Effect.promise(() => releaseUnusedComposerAttachmentFiles([image])); |
| 1335 | expect(imageExists).toBe(true); |
| 1336 | |
| 1337 | read.resolve(); |
| 1338 | const prepared = yield* Fiber.join(preparing); |
| 1339 | expect(prepared.status).toBe("ready"); |
| 1340 | if (prepared.status !== "ready") return; |
| 1341 | expect(prepared.attachments).toEqual([ |
| 1342 | { |
| 1343 | type: "image", |
| 1344 | name: "photo.png", |
| 1345 | mimeType: "image/png", |
| 1346 | sizeBytes: 3, |
| 1347 | dataUrl: "data:image/png;base64,YWJj", |
| 1348 | }, |
| 1349 | ]); |
| 1350 | yield* Effect.promise(() => removed.promise); |
| 1351 | expect(imageExists).toBe(false); |
| 1352 | }), |
| 1353 | ); |
| 1354 | |
| 1355 | it("keeps a failed-send draft's pending upload for retry", async () => { |
| 1356 | const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 1357 | onTestFinished(() => outboxLoad.mockRestore()); |
| 1358 | const file = { |
| 1359 | id: "file-failed-send", |
| 1360 | type: "file" as const, |
| 1361 | name: "report.pdf", |
| 1362 | mimeType: "application/pdf", |
| 1363 | sizeBytes: 42, |
| 1364 | fileUri: "file:///documents/t3-composer-attachments/failed-send.pdf", |
| 1365 | uploadedAttachmentId: "pending-failed-send", |
| 1366 | uploadEnvironmentId: EnvironmentId.make("environment-1"), |
| 1367 | }; |
| 1368 | appAtomRegistry.set(composerDraftsAtom, { |
| 1369 | "environment-1:thread-1": { text: "Retry this send", attachments: [file] }, |
| 1370 | }); |
| 1371 | |
| 1372 | await releaseUnusedComposerAttachmentFiles([file]); |
| 1373 | |
| 1374 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 1375 | expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled(); |
| 1376 | }); |
| 1377 | |
| 1378 | it("retains offline image bytes and newer edits when an early upload finishes", async () => { |
| 1379 | const key = "environment-1:thread-1"; |
| 1380 | const image = { |
| 1381 | id: "photo", |
| 1382 | type: "image" as const, |
| 1383 | name: "photo.png", |
| 1384 | mimeType: "image/png", |
| 1385 | sizeBytes: 3, |
| 1386 | dataUrl: "data:image/png;base64,YWJj", |
| 1387 | previewUri: "file:///photo.png", |
| 1388 | }; |
| 1389 | const second = { ...image, id: "second", name: "second.png" }; |
| 1390 | const uploaded = { |
| 1391 | ...image, |
| 1392 | uploadedAttachmentId: "pending-photo", |
| 1393 | uploadEnvironmentId: EnvironmentId.make("environment-1"), |
| 1394 | }; |
| 1395 | composerDraftFileMocks.setDocument({ schemaVersion: 1, drafts: {} }); |
| 1396 | appendComposerDraftAttachments(key, [image]); |
| 1397 | setComposerDraftText(key, "Edited while uploading"); |
| 1398 | appendComposerDraftAttachments(key, [second]); |
| 1399 | expect(setComposerDraftAttachmentUpload(key, uploaded)).toBe(true); |
| 1400 | await flushComposerDrafts(); |
| 1401 | |
| 1402 | appAtomRegistry.set(composerDraftsAtom, {}); |
| 1403 | resetComposerDraftsLoadState(); |
| 1404 | await waitForComposerDraftsLoaded(); |
| 1405 | expect(getComposerDraftSnapshot(key)).toMatchObject({ |
| 1406 | text: "Edited while uploading", |
| 1407 | attachments: [uploaded, second], |
| 1408 | }); |
| 1409 | expect(setComposerDraftAttachmentUpload(key, { ...uploaded, id: "removed-photo" })).toBe(false); |
| 1410 | expect(getComposerDraftSnapshot(key).attachments).toHaveLength(2); |
| 1411 | }); |
| 1412 | |
| 1413 | it.each(["file", "image"] as const)( |
| 1414 | "keeps signed-out %s attachments through cleanup and restart, and restores only the owning account", |
| 1415 | async (type) => { |
| 1416 | const load = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 1417 | onTestFinished(() => load.mockRestore()); |
| 1418 | await waitForComposerDraftsLoaded(); |
| 1419 | const environmentId = EnvironmentId.make("cloud-environment"); |
| 1420 | const key = `${environmentId}:thread-1`; |
| 1421 | const name = type === "image" ? "notes.png" : "notes.pdf"; |
| 1422 | const metadata = { |
| 1423 | id: "local-notes", |
| 1424 | name, |
| 1425 | mimeType: type === "image" ? "image/png" : "application/pdf", |
| 1426 | sizeBytes: 42, |
| 1427 | fileUri: `file:///documents/t3-composer-attachments/${name}`, |
| 1428 | uploadEnvironmentId: environmentId, |
| 1429 | uploadedAttachmentId: "pending-notes", |
| 1430 | }; |
| 1431 | const file = |
| 1432 | type === "image" |
| 1433 | ? { ...metadata, type, previewUri: metadata.fileUri } |
| 1434 | : { ...metadata, type }; |
| 1435 | const queued = { |
| 1436 | environmentId, |
| 1437 | threadId: ThreadId.make("thread-2"), |
| 1438 | messageId: MessageId.make("queued-1"), |
| 1439 | commandId: CommandId.make("command-1"), |
| 1440 | text: "Send later", |
| 1441 | attachments: [file], |
| 1442 | createdAt: "2026-08-31T12:00:00.000Z", |
| 1443 | }; |
| 1444 | appAtomRegistry.set(composerDraftsAtom, { |
| 1445 | [key]: { text: "Unsent notes", attachments: [file] }, |
| 1446 | "direct-environment:thread-1": DRAFT, |
| 1447 | "pending-task:queued-1": { text: "Edited queued task", attachments: [file] }, |
| 1448 | }); |
| 1449 | appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, { queued: [queued] }); |
| 1450 | await archiveCloudComposerDrafts("account-a", new Set([environmentId]), [ |
| 1451 | environmentId, |
| 1452 | EnvironmentId.make("direct-environment"), |
| 1453 | ]); |
| 1454 | expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({ |
| 1455 | "direct-environment:thread-1": DRAFT, |
| 1456 | }); |
| 1457 | |
| 1458 | appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {}); |
| 1459 | await clearComposerDraftsEnvironment(environmentId); |
| 1460 | await releaseUnusedComposerAttachmentFiles([file]); |
| 1461 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 1462 | expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled(); |
| 1463 | |
| 1464 | appAtomRegistry.set(composerDraftsAtom, {}); |
| 1465 | appAtomRegistry.set(composerCloudDraftsAtom, { accountId: null, signedOut: {} }); |
| 1466 | resetComposerDraftsLoadState(); |
| 1467 | await waitForComposerDraftsLoaded(); |
| 1468 | await restoreCloudComposerDrafts("account-b"); |
| 1469 | expect(getComposerDraftSnapshot(key).attachments).toEqual([]); |
| 1470 | expect(appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom)).toEqual({}); |
| 1471 | const enqueue = vi.spyOn(threadOutboxManager, "enqueue").mockResolvedValue(); |
| 1472 | onTestFinished(() => enqueue.mockRestore()); |
| 1473 | await restoreCloudComposerDrafts("account-a"); |
| 1474 | expect(getComposerDraftSnapshot(key)).toEqual( |
| 1475 | type === "image" |
| 1476 | ? { text: "Unsent notes", attachments: [file] } |
| 1477 | : { |
| 1478 | text: "Unsent notes [notes.pdf](t3-context://v1/file/local-notes) ", |
| 1479 | attachments: [file], |
| 1480 | context: { |
| 1481 | version: 1, |
| 1482 | records: [ |
| 1483 | { |
| 1484 | version: 1, |
| 1485 | contextId: file.id, |
| 1486 | kind: "file", |
| 1487 | label: file.name, |
| 1488 | attachmentId: file.id, |
| 1489 | name: file.name, |
| 1490 | mimeType: file.mimeType, |
| 1491 | sizeBytes: file.sizeBytes, |
| 1492 | }, |
| 1493 | ], |
| 1494 | }, |
| 1495 | }, |
| 1496 | ); |
| 1497 | expect(getComposerDraftSnapshot("pending-task:queued-1").text).toBe( |
| 1498 | type === "image" |
| 1499 | ? "Edited queued task" |
| 1500 | : "Edited queued task [notes.pdf](t3-context://v1/file/local-notes) ", |
| 1501 | ); |
| 1502 | expect(enqueue).toHaveBeenCalledExactlyOnceWith(queued); |
| 1503 | expect(appAtomRegistry.get(composerCloudDraftsAtom).signedOut).toEqual({}); |
| 1504 | const persisted = decodePersistedComposerState( |
| 1505 | JSON.parse(composerDraftFileMocks.getDocument()), |
| 1506 | ); |
| 1507 | expect(persisted.drafts[key]?.attachments).toEqual([file]); |
| 1508 | expect(persisted.cloudDrafts.accountId).toBe("account-a"); |
| 1509 | }, |
| 1510 | ); |
| 1511 | |
| 1512 | it("fails sign-out preservation before cleanup if a durable backup cannot be written", async () => { |
| 1513 | const load = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 1514 | onTestFinished(() => load.mockRestore()); |
| 1515 | await waitForComposerDraftsLoaded(); |
| 1516 | appAtomRegistry.set(composerDraftsAtom, { "environment-1:thread-1": DRAFT }); |
| 1517 | composerDraftFileMocks.setWriteError(new Error("Storage is full")); |
| 1518 | await expect( |
| 1519 | archiveCloudComposerDrafts("account-a", new Set([EnvironmentId.make("environment-1")]), [ |
| 1520 | EnvironmentId.make("environment-1"), |
| 1521 | ]), |
| 1522 | ).rejects.toThrow(); |
| 1523 | expect( |
| 1524 | appAtomRegistry.get(composerCloudDraftsAtom).signedOut["account-a"]?.drafts[ |
| 1525 | "environment-1:thread-1" |
| 1526 | ], |
| 1527 | ).toEqual(DRAFT); |
| 1528 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 1529 | composerDraftFileMocks.setWriteError(null); |
| 1530 | await archiveCloudComposerDrafts(null, new Set([EnvironmentId.make("environment-1")]), [ |
| 1531 | EnvironmentId.make("environment-1"), |
| 1532 | ]); |
| 1533 | expect( |
| 1534 | decodePersistedComposerState(JSON.parse(composerDraftFileMocks.getDocument())).cloudDrafts |
| 1535 | .signedOut["account-a"]?.drafts["environment-1:thread-1"], |
| 1536 | ).toEqual(DRAFT); |
| 1537 | }); |
| 1538 | |
| 1539 | it.each(["file", "image"] as const)( |
| 1540 | "keeps a removed %s until both preview and a share copy finish", |
| 1541 | async (type) => { |
| 1542 | const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 1543 | onTestFinished(() => outboxLoad.mockRestore()); |
| 1544 | const name = type === "image" ? "photo.png" : "recording.mp4"; |
| 1545 | const fileName = `33333333-3333-4333-8333-333333333333-${name}`; |
| 1546 | const metadata = { |
| 1547 | id: "file-preview", |
| 1548 | name, |
| 1549 | mimeType: type === "image" ? "image/png" : "video/mp4", |
| 1550 | sizeBytes: 42, |
| 1551 | fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`, |
| 1552 | }; |
| 1553 | const file = |
| 1554 | type === "image" |
| 1555 | ? { ...metadata, type, previewUri: metadata.fileUri } |
| 1556 | : { ...metadata, type }; |
| 1557 | const currentFile = { |
| 1558 | ...file, |
| 1559 | fileUri: `file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents/t3-composer-attachments/${fileName}`, |
| 1560 | }; |
| 1561 | const releasePlayback = retainComposerAttachmentFileForPreview(file); |
| 1562 | const releaseShareCopy = retainComposerAttachmentFileForPreview(currentFile); |
| 1563 | onTestFinished(releasePlayback); |
| 1564 | onTestFinished(releaseShareCopy); |
| 1565 | |
| 1566 | await releaseUnusedComposerAttachmentFiles([currentFile]); |
| 1567 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 1568 | |
| 1569 | releasePlayback(); |
| 1570 | releasePlayback(); |
| 1571 | await releaseUnusedComposerAttachmentFiles([file]); |
| 1572 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 1573 | |
| 1574 | const deleted = Promise.withResolvers<void>(); |
| 1575 | composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => { |
| 1576 | deleted.resolve(); |
| 1577 | return undefined; |
| 1578 | }); |
| 1579 | releaseShareCopy(); |
| 1580 | await deleted.promise; |
| 1581 | |
| 1582 | expect(composerAttachmentCleanupMocks.remove.mock.calls).toEqual([[currentFile.fileUri]]); |
| 1583 | }, |
| 1584 | ); |
| 1585 | |
| 1586 | it("preserves a preview opened while cleanup is checking the incoming inbox", async () => { |
| 1587 | const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 1588 | onTestFinished(() => outboxLoad.mockRestore()); |
| 1589 | const file = { |
| 1590 | id: "file-opening-preview", |
| 1591 | type: "file" as const, |
| 1592 | name: "recording.mp4", |
| 1593 | mimeType: "video/mp4", |
| 1594 | sizeBytes: 42, |
| 1595 | fileUri: "file:///documents/t3-composer-attachments/recording.mp4", |
| 1596 | }; |
| 1597 | const ownershipReadStarted = Promise.withResolvers<void>(); |
| 1598 | const ownershipRead = Promise.withResolvers<[]>(); |
| 1599 | incomingShareStorageMocks.load.mockImplementationOnce(() => { |
| 1600 | ownershipReadStarted.resolve(); |
| 1601 | return ownershipRead.promise; |
| 1602 | }); |
| 1603 | |
| 1604 | const cleanup = releaseUnusedComposerAttachmentFiles([file]); |
| 1605 | await ownershipReadStarted.promise; |
| 1606 | const release = retainComposerAttachmentFileForPreview(file); |
| 1607 | onTestFinished(release); |
| 1608 | ownershipRead.resolve([]); |
| 1609 | await cleanup; |
| 1610 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 1611 | |
| 1612 | const deleted = Promise.withResolvers<void>(); |
| 1613 | composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => { |
| 1614 | deleted.resolve(); |
| 1615 | return undefined; |
| 1616 | }); |
| 1617 | release(); |
| 1618 | await deleted.promise; |
| 1619 | expect(composerAttachmentCleanupMocks.remove.mock.calls).toEqual([[file.fileUri]]); |
| 1620 | }); |
| 1621 | |
| 1622 | it("removes an unreferenced local file and its pending upload", async () => { |
| 1623 | const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 1624 | onTestFinished(() => outboxLoad.mockRestore()); |
| 1625 | const environmentId = EnvironmentId.make("environment-1"); |
| 1626 | const file = { |
| 1627 | id: "file-discarded", |
| 1628 | type: "file" as const, |
| 1629 | name: "report.pdf", |
| 1630 | mimeType: "application/pdf", |
| 1631 | sizeBytes: 42, |
| 1632 | fileUri: "file:///documents/t3-composer-attachments/discarded.pdf", |
| 1633 | uploadedAttachmentId: "pending-discarded", |
| 1634 | uploadEnvironmentId: environmentId, |
| 1635 | }; |
| 1636 | |
| 1637 | await releaseUnusedComposerAttachmentFiles([file]); |
| 1638 | |
| 1639 | expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(file.fileUri); |
| 1640 | expect(composerAttachmentCleanupMocks.releaseUploads).toHaveBeenCalledWith(environmentId, [ |
| 1641 | "pending-discarded", |
| 1642 | ]); |
| 1643 | }); |
| 1644 | |
| 1645 | it("keeps a pending upload referenced through another local file", async () => { |
| 1646 | const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 1647 | onTestFinished(() => outboxLoad.mockRestore()); |
| 1648 | const environmentId = EnvironmentId.make("environment-1"); |
| 1649 | const discarded = { |
| 1650 | id: "file-discarded-copy", |
| 1651 | type: "file" as const, |
| 1652 | name: "report.pdf", |
| 1653 | mimeType: "application/pdf", |
| 1654 | sizeBytes: 42, |
| 1655 | fileUri: "file:///documents/t3-composer-attachments/discarded-copy.pdf", |
| 1656 | uploadedAttachmentId: "pending-shared", |
| 1657 | uploadEnvironmentId: environmentId, |
| 1658 | }; |
| 1659 | const retained = { |
| 1660 | ...discarded, |
| 1661 | id: "file-retained-copy", |
| 1662 | fileUri: "file:///documents/t3-composer-attachments/retained-copy.pdf", |
| 1663 | }; |
| 1664 | appAtomRegistry.set(composerDraftsAtom, { |
| 1665 | "environment-1:thread-1": { text: "Keep this copy", attachments: [retained] }, |
| 1666 | }); |
| 1667 | |
| 1668 | await releaseUnusedComposerAttachmentFiles([discarded]); |
| 1669 | |
| 1670 | expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(discarded.fileUri); |
| 1671 | expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled(); |
| 1672 | }); |
| 1673 | |
| 1674 | it("completes local cleanup when pending upload deletion fails", async () => { |
| 1675 | const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 1676 | onTestFinished(() => outboxLoad.mockRestore()); |
| 1677 | const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); |
| 1678 | onTestFinished(() => warning.mockRestore()); |
| 1679 | composerAttachmentCleanupMocks.releaseUploads.mockRejectedValueOnce( |
| 1680 | new Error("environment disconnected"), |
| 1681 | ); |
| 1682 | const file = { |
| 1683 | id: "file-delete-failed", |
| 1684 | type: "file" as const, |
| 1685 | name: "report.pdf", |
| 1686 | mimeType: "application/pdf", |
| 1687 | sizeBytes: 42, |
| 1688 | fileUri: "file:///documents/t3-composer-attachments/delete-failed.pdf", |
| 1689 | uploadedAttachmentId: "pending-delete-failed", |
| 1690 | uploadEnvironmentId: EnvironmentId.make("environment-1"), |
| 1691 | }; |
| 1692 | |
| 1693 | await expect(releaseUnusedComposerAttachmentFiles([file])).resolves.toBeUndefined(); |
| 1694 | |
| 1695 | expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(file.fileUri); |
| 1696 | expect(warning).toHaveBeenCalledWith( |
| 1697 | "[composer-attachments] could not remove pending upload", |
| 1698 | expect.objectContaining({ attachmentId: "pending-delete-failed" }), |
| 1699 | ); |
| 1700 | }); |
| 1701 | |
| 1702 | it("keeps local attachment files while an outbox message still needs them", async () => { |
| 1703 | const file = { |
| 1704 | id: "file-queued", |
| 1705 | type: "file" as const, |
| 1706 | name: "report.pdf", |
| 1707 | mimeType: "application/pdf", |
| 1708 | sizeBytes: 42, |
| 1709 | fileUri: "file:///documents/t3-composer-attachments/report.pdf", |
| 1710 | }; |
| 1711 | appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, { |
| 1712 | "environment-1:thread-1": [ |
| 1713 | { |
| 1714 | environmentId: EnvironmentId.make("environment-1"), |
| 1715 | threadId: ThreadId.make("thread-1"), |
| 1716 | messageId: MessageId.make("message-1"), |
| 1717 | commandId: CommandId.make("command-1"), |
| 1718 | text: "Review the report", |
| 1719 | attachments: [file], |
| 1720 | createdAt: "2026-08-24T12:00:00.000Z", |
| 1721 | }, |
| 1722 | ], |
| 1723 | }); |
| 1724 | |
| 1725 | await releaseUnusedComposerAttachmentFiles([file]); |
| 1726 | |
| 1727 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 1728 | }); |
| 1729 | |
| 1730 | it("loads persisted outbox messages before deciding an attachment file is unused", async () => { |
| 1731 | const file = { |
| 1732 | id: "file-persisted", |
| 1733 | type: "file" as const, |
| 1734 | name: "report.pdf", |
| 1735 | mimeType: "application/pdf", |
| 1736 | sizeBytes: 42, |
| 1737 | fileUri: "file:///documents/t3-composer-attachments/report.pdf", |
| 1738 | }; |
| 1739 | const load = vi.spyOn(threadOutboxManager, "load").mockImplementation(async () => { |
| 1740 | appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, { |
| 1741 | "environment-1:thread-1": [ |
| 1742 | { |
| 1743 | environmentId: EnvironmentId.make("environment-1"), |
| 1744 | threadId: ThreadId.make("thread-1"), |
| 1745 | messageId: MessageId.make("message-persisted"), |
| 1746 | commandId: CommandId.make("command-persisted"), |
| 1747 | text: "Review the report", |
| 1748 | attachments: [file], |
| 1749 | createdAt: "2026-08-24T12:00:00.000Z", |
| 1750 | }, |
| 1751 | ], |
| 1752 | }); |
| 1753 | return true; |
| 1754 | }); |
| 1755 | |
| 1756 | try { |
| 1757 | await releaseUnusedComposerAttachmentFiles([file]); |
| 1758 | |
| 1759 | expect(load).toHaveBeenCalledOnce(); |
| 1760 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 1761 | } finally { |
| 1762 | load.mockRestore(); |
| 1763 | } |
| 1764 | }); |
| 1765 | |
| 1766 | it("keeps a file until its incoming share is consumed", async () => { |
| 1767 | const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 1768 | onTestFinished(() => outboxLoad.mockRestore()); |
| 1769 | const file = { |
| 1770 | id: "file-incoming", |
| 1771 | type: "file" as const, |
| 1772 | name: "report.pdf", |
| 1773 | mimeType: "application/pdf", |
| 1774 | sizeBytes: 42, |
| 1775 | fileUri: "file:///documents/t3-composer-attachments/incoming.pdf", |
| 1776 | }; |
| 1777 | incomingShareStorageMocks.load |
| 1778 | .mockResolvedValueOnce([ |
| 1779 | { |
| 1780 | schemaVersion: 1, |
| 1781 | id: "share-1", |
| 1782 | createdAt: "2026-08-28T12:00:00.000Z", |
| 1783 | text: "Review this file", |
| 1784 | attachments: [file], |
| 1785 | warnings: [], |
| 1786 | }, |
| 1787 | ]) |
| 1788 | .mockResolvedValueOnce([]); |
| 1789 | |
| 1790 | await releaseUnusedComposerAttachmentFiles([file]); |
| 1791 | |
| 1792 | expect(incomingShareStorageMocks.load).toHaveBeenLastCalledWith({ strict: true }); |
| 1793 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 1794 | |
| 1795 | await releaseUnusedComposerAttachmentFiles([file]); |
| 1796 | |
| 1797 | expect(incomingShareStorageMocks.load).toHaveBeenCalledTimes(2); |
| 1798 | expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(file.fileUri); |
| 1799 | }); |
| 1800 | |
| 1801 | it("does not delete files when incoming share ownership cannot be loaded", async () => { |
| 1802 | const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 1803 | onTestFinished(() => outboxLoad.mockRestore()); |
| 1804 | const file = { |
| 1805 | id: "file-incoming-unknown", |
| 1806 | type: "file" as const, |
| 1807 | name: "report.pdf", |
| 1808 | mimeType: "application/pdf", |
| 1809 | sizeBytes: 42, |
| 1810 | fileUri: "file:///documents/t3-composer-attachments/incoming-unknown.pdf", |
| 1811 | }; |
| 1812 | const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined); |
| 1813 | incomingShareStorageMocks.load.mockRejectedValueOnce(new Error("inbox unavailable")); |
| 1814 | onTestFinished(() => warning.mockRestore()); |
| 1815 | |
| 1816 | await releaseUnusedComposerAttachmentFiles([file]); |
| 1817 | |
| 1818 | expect(incomingShareStorageMocks.load).toHaveBeenCalledWith({ strict: true }); |
| 1819 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 1820 | }); |
| 1821 | |
| 1822 | it.each(["draft", "outbox", "inbox"] as const)( |
| 1823 | "preserves relocated files still referenced by a persisted %s", |
| 1824 | async (owner) => { |
| 1825 | const fileName = "33333333-3333-4333-8333-333333333333-report.pdf"; |
| 1826 | const oldFile = { |
| 1827 | id: "file-relocated", |
| 1828 | type: "file" as const, |
| 1829 | name: "report.pdf", |
| 1830 | mimeType: "application/pdf", |
| 1831 | sizeBytes: 42, |
| 1832 | fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`, |
| 1833 | }; |
| 1834 | const currentFile = { |
| 1835 | ...oldFile, |
| 1836 | fileUri: `file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents/t3-composer-attachments/${fileName}`, |
| 1837 | }; |
| 1838 | const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 1839 | onTestFinished(() => outboxLoad.mockRestore()); |
| 1840 | if (owner === "draft") { |
| 1841 | composerDraftFileMocks.setDocument({ |
| 1842 | schemaVersion: 1, |
| 1843 | drafts: { "environment-1:thread-1": { text: "Saved draft", attachments: [oldFile] } }, |
| 1844 | }); |
| 1845 | resetComposerDraftsLoadState(); |
| 1846 | } else if (owner === "outbox") { |
| 1847 | outboxLoad.mockImplementation(async () => { |
| 1848 | appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, { |
| 1849 | "environment-1:thread-1": [ |
| 1850 | { |
| 1851 | environmentId: EnvironmentId.make("environment-1"), |
| 1852 | threadId: ThreadId.make("thread-1"), |
| 1853 | messageId: MessageId.make("message-relocated"), |
| 1854 | commandId: CommandId.make("command-relocated"), |
| 1855 | text: "Queued draft", |
| 1856 | attachments: [oldFile], |
| 1857 | createdAt: "2026-08-28T12:00:00.000Z", |
| 1858 | }, |
| 1859 | ], |
| 1860 | }); |
| 1861 | return true; |
| 1862 | }); |
| 1863 | } else { |
| 1864 | incomingShareStorageMocks.load.mockResolvedValue([ |
| 1865 | { |
| 1866 | schemaVersion: 1, |
| 1867 | id: "share-relocated", |
| 1868 | createdAt: "2026-08-28T12:00:00.000Z", |
| 1869 | text: "Incoming file", |
| 1870 | attachments: [oldFile], |
| 1871 | warnings: [], |
| 1872 | }, |
| 1873 | ]); |
| 1874 | } |
| 1875 | |
| 1876 | await releaseUnusedComposerAttachmentFiles([currentFile]); |
| 1877 | |
| 1878 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 1879 | |
| 1880 | appAtomRegistry.set(composerDraftsAtom, {}); |
| 1881 | appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {}); |
| 1882 | outboxLoad.mockResolvedValue(true); |
| 1883 | incomingShareStorageMocks.load.mockResolvedValue([]); |
| 1884 | await releaseUnusedComposerAttachmentFiles([currentFile]); |
| 1885 | |
| 1886 | expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(currentFile.fileUri); |
| 1887 | }, |
| 1888 | ); |
| 1889 | |
| 1890 | it("does not delete attachment files when the draft removal cannot be saved", async () => { |
| 1891 | const file = { |
| 1892 | id: "file-unsaved", |
| 1893 | type: "file" as const, |
| 1894 | name: "report.pdf", |
| 1895 | mimeType: "application/pdf", |
| 1896 | sizeBytes: 42, |
| 1897 | fileUri: "file:///documents/t3-composer-attachments/report.pdf", |
| 1898 | }; |
| 1899 | setComposerDraftText("environment-1:thread-1", "Unsaved draft"); |
| 1900 | composerDraftFileMocks.setWriteError(new Error("storage unavailable")); |
| 1901 | |
| 1902 | try { |
| 1903 | await expect(releaseUnusedComposerAttachmentFiles([file])).rejects.toBeInstanceOf( |
| 1904 | ComposerDraftPersistenceError, |
| 1905 | ); |
| 1906 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 1907 | } finally { |
| 1908 | composerDraftFileMocks.setWriteError(null); |
| 1909 | } |
| 1910 | }); |
| 1911 | |
| 1912 | it("hydrates selector state even when the message content is empty", () => { |
| 1913 | const hydrated = Object.entries( |
| 1914 | decodePersistedComposerState({ |
| 1915 | schemaVersion: 1, |
| 1916 | drafts: { |
| 1917 | "new-task:environment-1:project-1": { |
| 1918 | text: "", |
| 1919 | attachments: [], |
| 1920 | modelSelection: { |
| 1921 | instanceId: "codex", |
| 1922 | model: "gpt-5.4", |
| 1923 | options: [{ id: "reasoningEffort", value: "xhigh" }], |
| 1924 | }, |
| 1925 | runtimeMode: "approval-required", |
| 1926 | interactionMode: "plan", |
| 1927 | workspaceSelection: { |
| 1928 | mode: "worktree", |
| 1929 | branch: "main", |
| 1930 | worktreePath: null, |
| 1931 | }, |
| 1932 | }, |
| 1933 | }, |
| 1934 | }).drafts, |
| 1935 | ); |
| 1936 | expect(hydrated).toHaveLength(1); |
| 1937 | const [key, draft] = hydrated[0]!; |
| 1938 | |
| 1939 | expect(key).toMatch(/^new-task:[0-9a-z-]+$/); |
| 1940 | expect(draft).toEqual({ |
| 1941 | text: "", |
| 1942 | attachments: [], |
| 1943 | modelSelection: { |
| 1944 | instanceId: "codex", |
| 1945 | model: "gpt-5.4", |
| 1946 | options: [{ id: "reasoningEffort", value: "xhigh" }], |
| 1947 | }, |
| 1948 | runtimeMode: "approval-required", |
| 1949 | interactionMode: "plan", |
| 1950 | workspaceSelection: { |
| 1951 | mode: "worktree", |
| 1952 | branch: "main", |
| 1953 | worktreePath: null, |
| 1954 | }, |
| 1955 | project: { |
| 1956 | environmentId: "environment-1", |
| 1957 | projectId: "project-1", |
| 1958 | createdAt: expect.any(String), |
| 1959 | }, |
| 1960 | }); |
| 1961 | }); |
| 1962 | |
| 1963 | it("keeps share-import receipts on otherwise contentless new-task drafts", () => { |
| 1964 | const receiptDraft: ComposerDraft = { |
| 1965 | text: "", |
| 1966 | attachments: [], |
| 1967 | importedShareIds: ["share-1"], |
| 1968 | }; |
| 1969 | |
| 1970 | const stripped = Object.values( |
| 1971 | decodePersistedComposerState({ |
| 1972 | schemaVersion: 1, |
| 1973 | drafts: { |
| 1974 | "new-task:environment-1:project-1": { |
| 1975 | ...receiptDraft, |
| 1976 | modelSelection: { |
| 1977 | instanceId: "codex", |
| 1978 | model: "gpt-5.4", |
| 1979 | }, |
| 1980 | }, |
| 1981 | }, |
| 1982 | }).drafts, |
| 1983 | ); |
| 1984 | expect(stripped).toHaveLength(1); |
| 1985 | expect(stripped[0]).toMatchObject({ |
| 1986 | text: "", |
| 1987 | attachments: [], |
| 1988 | importedShareIds: ["share-1"], |
| 1989 | project: { environmentId: "environment-1", projectId: "project-1" }, |
| 1990 | }); |
| 1991 | expect(stripped[0]?.modelSelection).toBeUndefined(); |
| 1992 | |
| 1993 | const kept = Object.values( |
| 1994 | decodePersistedComposerState({ |
| 1995 | schemaVersion: 1, |
| 1996 | drafts: { "new-task:environment-1:project-1": receiptDraft }, |
| 1997 | }).drafts, |
| 1998 | ); |
| 1999 | expect(kept).toHaveLength(1); |
| 2000 | expect(kept[0]).toMatchObject(receiptDraft); |
| 2001 | }); |
| 2002 | |
| 2003 | it("migrates project-keyed new-task drafts to id keys with the project stamped in", () => { |
| 2004 | const now = "2026-09-05T12:00:00.000Z"; |
| 2005 | const [key, draft] = migrateLegacyNewTaskDraft( |
| 2006 | "new-task:environment-1:project-1", |
| 2007 | { text: "keep me", attachments: [] }, |
| 2008 | now, |
| 2009 | ); |
| 2010 | |
| 2011 | expect(key).toMatch(/^new-task:[0-9a-z-]+$/); |
| 2012 | expect(draft).toEqual({ |
| 2013 | text: "keep me", |
| 2014 | attachments: [], |
| 2015 | project: { |
| 2016 | environmentId: EnvironmentId.make("environment-1"), |
| 2017 | projectId: ProjectId.make("project-1"), |
| 2018 | createdAt: now, |
| 2019 | }, |
| 2020 | }); |
| 2021 | |
| 2022 | const stamped: ComposerDraft = { |
| 2023 | text: "x", |
| 2024 | attachments: [], |
| 2025 | project: { |
| 2026 | environmentId: EnvironmentId.make("environment-1"), |
| 2027 | projectId: ProjectId.make("project-1"), |
| 2028 | createdAt: now, |
| 2029 | }, |
| 2030 | }; |
| 2031 | expect(migrateLegacyNewTaskDraft("new-task:some-id", stamped, now)).toEqual([ |
| 2032 | "new-task:some-id", |
| 2033 | stamped, |
| 2034 | ]); |
| 2035 | expect(migrateLegacyNewTaskDraft("environment-1:thread-1", DRAFT, now)).toEqual([ |
| 2036 | "environment-1:thread-1", |
| 2037 | DRAFT, |
| 2038 | ]); |
| 2039 | expect(migrateLegacyNewTaskDraft("pending-task:message-1", DRAFT, now)).toEqual([ |
| 2040 | "pending-task:message-1", |
| 2041 | DRAFT, |
| 2042 | ]); |
| 2043 | }); |
| 2044 | |
| 2045 | it("keeps a freshly minted new-task draft bound until content arrives, then lists it per project", () => { |
| 2046 | const project = { |
| 2047 | environmentId: EnvironmentId.make("environment-1"), |
| 2048 | projectId: ProjectId.make("project-1"), |
| 2049 | }; |
| 2050 | const first = createNewTaskDraft(project); |
| 2051 | const second = createNewTaskDraft(project); |
| 2052 | expect(first).not.toBe(second); |
| 2053 | |
| 2054 | expect(appAtomRegistry.get(composerDraftsAtom)[first]?.project).toMatchObject(project); |
| 2055 | |
| 2056 | setComposerDraftText(first, "first idea"); |
| 2057 | setComposerDraftText(second, "second idea"); |
| 2058 | expect(findNewTaskDraftKeys(appAtomRegistry.get(composerDraftsAtom), project)).toEqual( |
| 2059 | expect.arrayContaining([first, second]), |
| 2060 | ); |
| 2061 | |
| 2062 | clearComposerDraftContent(first, { clearModelSelection: true, clearWorkspaceSelection: true }); |
| 2063 | expect(appAtomRegistry.get(composerDraftsAtom)[first]).toBeUndefined(); |
| 2064 | expect(getComposerDraftSnapshot(second).text).toBe("second idea"); |
| 2065 | }); |
| 2066 | |
| 2067 | it("retargets a new-task draft to another project, keeping only a pull request workspace", () => { |
| 2068 | const from = { |
| 2069 | environmentId: EnvironmentId.make("environment-1"), |
| 2070 | projectId: ProjectId.make("project-1"), |
| 2071 | }; |
| 2072 | const to = { |
| 2073 | environmentId: EnvironmentId.make("environment-2"), |
| 2074 | projectId: ProjectId.make("project-2"), |
| 2075 | }; |
| 2076 | const key = createNewTaskDraft(from); |
| 2077 | setComposerDraftText(key, "moving house"); |
| 2078 | appAtomRegistry.set(composerDraftsAtom, { |
| 2079 | ...appAtomRegistry.get(composerDraftsAtom), |
| 2080 | [key]: { |
| 2081 | ...getComposerDraftSnapshot(key), |
| 2082 | runtimeMode: "approval-required", |
| 2083 | workspaceSelection: { mode: "worktree", branch: "feature/a", worktreePath: null }, |
| 2084 | }, |
| 2085 | }); |
| 2086 | const createdAt = getComposerDraftSnapshot(key).project?.createdAt; |
| 2087 | |
| 2088 | retargetNewTaskDraft(key, to, { keepPullRequestWorkspace: true }); |
| 2089 | |
| 2090 | const moved = getComposerDraftSnapshot(key); |
| 2091 | expect(moved.text).toBe("moving house"); |
| 2092 | expect(moved.runtimeMode).toBe("approval-required"); |
| 2093 | |
| 2094 | expect(moved.workspaceSelection).toBeUndefined(); |
| 2095 | expect(moved.project).toEqual({ ...to, createdAt }); |
| 2096 | expect(findNewTaskDraftKeys(appAtomRegistry.get(composerDraftsAtom), from)).toEqual([]); |
| 2097 | expect(findNewTaskDraftKeys(appAtomRegistry.get(composerDraftsAtom), to)).toEqual([key]); |
| 2098 | |
| 2099 | const pullRequestSelection = { |
| 2100 | mode: "worktree" as const, |
| 2101 | branch: "feature/pr-head", |
| 2102 | worktreePath: "/old-machine/worktrees/pr-42", |
| 2103 | startFromOrigin: false, |
| 2104 | pullRequestReference: "https://github.com/acme/repo/pull/42", |
| 2105 | }; |
| 2106 | updateComposerDraftSettings(key, { workspaceSelection: pullRequestSelection }); |
| 2107 | retargetNewTaskDraft(key, from, { keepPullRequestWorkspace: true }); |
| 2108 | expect(getComposerDraftSnapshot(key).workspaceSelection).toEqual({ |
| 2109 | ...pullRequestSelection, |
| 2110 | worktreePath: null, |
| 2111 | }); |
| 2112 | retargetNewTaskDraft(key, to); |
| 2113 | expect(getComposerDraftSnapshot(key).workspaceSelection).toBeUndefined(); |
| 2114 | }); |
| 2115 | |
| 2116 | it("retargets a saved new-task draft only after drafts load", async () => { |
| 2117 | const from = { |
| 2118 | environmentId: EnvironmentId.make("environment-1"), |
| 2119 | projectId: ProjectId.make("project-1"), |
| 2120 | }; |
| 2121 | const to = { |
| 2122 | environmentId: EnvironmentId.make("environment-1"), |
| 2123 | projectId: ProjectId.make("project-2"), |
| 2124 | }; |
| 2125 | const key = createNewTaskDraft(from); |
| 2126 | setComposerDraftText(key, "kept through a cold start"); |
| 2127 | await flushComposerDrafts(); |
| 2128 | appAtomRegistry.set(composerDraftsAtom, {}); |
| 2129 | resetComposerDraftsLoadState(); |
| 2130 | |
| 2131 | composerDraftFileMocks.blockRead(); |
| 2132 | const controller = new AbortController(); |
| 2133 | const cancelled = retargetSavedNewTaskDraft(key, to, controller.signal); |
| 2134 | controller.abort(); |
| 2135 | composerDraftFileMocks.releaseRead(); |
| 2136 | await expect(cancelled).resolves.toBe(false); |
| 2137 | expect(getComposerDraftSnapshot(key).project).toMatchObject(from); |
| 2138 | |
| 2139 | await expect(retargetSavedNewTaskDraft(key, to)).resolves.toBe(true); |
| 2140 | expect(getComposerDraftSnapshot(key)).toMatchObject({ |
| 2141 | text: "kept through a cold start", |
| 2142 | project: to, |
| 2143 | }); |
| 2144 | await expect(retargetSavedNewTaskDraft(`${key}-gone`, to)).resolves.toBe(false); |
| 2145 | expect(appAtomRegistry.get(composerDraftsAtom)[`${key}-gone`]).toBeUndefined(); |
| 2146 | }); |
| 2147 | |
| 2148 | it("merges persisted option memory without replacing newer choices", async () => { |
| 2149 | composerDraftFileMocks.setDocument({ |
| 2150 | schemaVersion: 1, |
| 2151 | drafts: {}, |
| 2152 | modelOptionMemory: { |
| 2153 | pi: { |
| 2154 | "xai/grok-4.6": [{ id: "thinking", value: "high" }], |
| 2155 | "openai/gpt-5.4": [{ id: "thinking", value: "medium" }], |
| 2156 | }, |
| 2157 | }, |
| 2158 | }); |
| 2159 | appAtomRegistry.set(modelOptionMemoryAtom, { |
| 2160 | pi: { "xai/grok-4.6": [{ id: "thinking", value: "xhigh" }] }, |
| 2161 | }); |
| 2162 | |
| 2163 | ensureComposerDraftsLoaded(); |
| 2164 | await waitForComposerDraftsLoaded(); |
| 2165 | |
| 2166 | expect(appAtomRegistry.get(modelOptionMemoryAtom)).toEqual({ |
| 2167 | pi: { |
| 2168 | "xai/grok-4.6": [{ id: "thinking", value: "xhigh" }], |
| 2169 | "openai/gpt-5.4": [{ id: "thinking", value: "medium" }], |
| 2170 | }, |
| 2171 | }); |
| 2172 | }); |
| 2173 | |
| 2174 | it("flush waits for pending hydration instead of clobbering disk", async () => { |
| 2175 | vi.useFakeTimers(); |
| 2176 | composerDraftFileMocks.setDocument({ |
| 2177 | schemaVersion: 1, |
| 2178 | drafts: { |
| 2179 | "environment-1:thread-1": DRAFT, |
| 2180 | }, |
| 2181 | stickyModelSelection: { |
| 2182 | instanceId: "codex", |
| 2183 | model: "gpt-5.6-sol", |
| 2184 | }, |
| 2185 | }); |
| 2186 | composerDraftFileMocks.blockRead(); |
| 2187 | composerDraftFileMocks.resetWrites(); |
| 2188 | |
| 2189 | ensureComposerDraftsLoaded(); |
| 2190 | await Promise.resolve(); |
| 2191 | |
| 2192 | setComposerDraftText("new-task:environment-1:project-1", "New prompt"); |
| 2193 | |
| 2194 | const flush = flushComposerDrafts(); |
| 2195 | await vi.advanceTimersByTimeAsync(200); |
| 2196 | |
| 2197 | expect(composerDraftFileMocks.getWrites()).toHaveLength(0); |
| 2198 | |
| 2199 | composerDraftFileMocks.releaseRead(); |
| 2200 | await flush; |
| 2201 | |
| 2202 | const written = JSON.parse(composerDraftFileMocks.getDocument()); |
| 2203 | expect(written.drafts["environment-1:thread-1"]).toEqual(DRAFT); |
| 2204 | expect(written.drafts["new-task:environment-1:project-1"]).toEqual({ |
| 2205 | text: "New prompt", |
| 2206 | attachments: [], |
| 2207 | }); |
| 2208 | expect(written.stickyModelSelection).toEqual({ |
| 2209 | instanceId: "codex", |
| 2210 | model: "gpt-5.6-sol", |
| 2211 | }); |
| 2212 | }); |
| 2213 | |
| 2214 | it.each(["read", "decode"] as const)( |
| 2215 | "preserves saved drafts and attachment files when the draft %s fails", |
| 2216 | async (failure) => { |
| 2217 | vi.useFakeTimers(); |
| 2218 | const file = { |
| 2219 | id: "saved-file", |
| 2220 | type: "file" as const, |
| 2221 | name: "report.pdf", |
| 2222 | mimeType: "application/pdf", |
| 2223 | sizeBytes: 42, |
| 2224 | fileUri: "file:///documents/t3-composer-attachments/report.pdf", |
| 2225 | }; |
| 2226 | composerDraftFileMocks.setDocument({ |
| 2227 | schemaVersion: failure === "decode" ? 999 : 1, |
| 2228 | drafts: { "environment-1:saved": { text: "Saved draft", attachments: [file] } }, |
| 2229 | }); |
| 2230 | const original = composerDraftFileMocks.getDocument(); |
| 2231 | if (failure === "read") { |
| 2232 | composerDraftFileMocks.setReadError(new Error("storage unavailable")); |
| 2233 | } |
| 2234 | |
| 2235 | await expect(releaseUnusedComposerAttachmentFiles([file])).rejects.toMatchObject({ |
| 2236 | operation: failure, |
| 2237 | }); |
| 2238 | setComposerDraftText("environment-1:new", "Keep my new edits too"); |
| 2239 | await expect(flushComposerDrafts()).rejects.toMatchObject({ operation: failure }); |
| 2240 | |
| 2241 | expect(composerDraftFileMocks.getDocument()).toBe(original); |
| 2242 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 2243 | }, |
| 2244 | ); |
| 2245 | |
| 2246 | it("serializes environment cleanup after an older queued write", async () => { |
| 2247 | vi.useFakeTimers(); |
| 2248 | composerDraftFileMocks.setDocument({ schemaVersion: 1, drafts: {} }); |
| 2249 | composerDraftFileMocks.resetWrites(); |
| 2250 | let releaseFirstWrite!: () => void; |
| 2251 | const firstWriteBarrier = new Promise<void>((resolve) => { |
| 2252 | releaseFirstWrite = resolve; |
| 2253 | }); |
| 2254 | composerDraftFileMocks.setNextWriteBarrier(firstWriteBarrier); |
| 2255 | let writeCount = 0; |
| 2256 | const bothWritesCommitted = new Promise<void>((resolve) => { |
| 2257 | composerDraftFileMocks.setOnWrite(() => { |
| 2258 | writeCount += 1; |
| 2259 | if (writeCount === 2) { |
| 2260 | resolve(); |
| 2261 | } |
| 2262 | }); |
| 2263 | }); |
| 2264 | |
| 2265 | appAtomRegistry.set(composerDraftsAtom, { |
| 2266 | "environment-1:thread-1": DRAFT, |
| 2267 | "environment-2:thread-2": { text: "keep", attachments: [] }, |
| 2268 | }); |
| 2269 | setStickyComposerModelSelection({ |
| 2270 | instanceId: ProviderInstanceId.make("codex"), |
| 2271 | model: "gpt-5.6-sol", |
| 2272 | }); |
| 2273 | await vi.advanceTimersByTimeAsync(200); |
| 2274 | |
| 2275 | const clear = clearComposerDraftsEnvironment(EnvironmentId.make("environment-1")); |
| 2276 | await Promise.resolve(); |
| 2277 | |
| 2278 | expect(composerDraftFileMocks.getWrites()).toHaveLength(0); |
| 2279 | |
| 2280 | releaseFirstWrite(); |
| 2281 | await clear; |
| 2282 | await bothWritesCommitted; |
| 2283 | |
| 2284 | expect(JSON.parse(composerDraftFileMocks.getDocument())).toEqual({ |
| 2285 | schemaVersion: 1, |
| 2286 | drafts: { |
| 2287 | "environment-2:thread-2": { text: "keep", attachments: [] }, |
| 2288 | }, |
| 2289 | stickyModelSelection: { |
| 2290 | instanceId: "codex", |
| 2291 | model: "gpt-5.6-sol", |
| 2292 | }, |
| 2293 | }); |
| 2294 | }); |
| 2295 | |
| 2296 | it("clears sent content without clearing the selected model or workspace", () => { |
| 2297 | const draftKey = "environment-1:thread-1"; |
| 2298 | const draft: ComposerDraft = { |
| 2299 | text: "send this", |
| 2300 | attachments: [], |
| 2301 | importedShareIds: ["share-1"], |
| 2302 | modelSelection: { |
| 2303 | instanceId: ProviderInstanceId.make("codex"), |
| 2304 | model: "gpt-5.4", |
| 2305 | options: [{ id: "reasoningEffort", value: "xhigh" }], |
| 2306 | }, |
| 2307 | workspaceSelection: { |
| 2308 | mode: "worktree", |
| 2309 | branch: "main", |
| 2310 | worktreePath: null, |
| 2311 | }, |
| 2312 | }; |
| 2313 | |
| 2314 | expect(clearComposerDraftContentState({ [draftKey]: draft }, draftKey)).toEqual({ |
| 2315 | [draftKey]: { |
| 2316 | modelSelection: draft.modelSelection, |
| 2317 | workspaceSelection: draft.workspaceSelection, |
| 2318 | text: "", |
| 2319 | attachments: [], |
| 2320 | }, |
| 2321 | }); |
| 2322 | }); |
| 2323 | |
| 2324 | it("drops another environment's upload stamp when a draft moves across machines", () => { |
| 2325 | const uploadedElsewhere: DraftComposerAttachment = { |
| 2326 | id: "image-1", |
| 2327 | type: "image", |
| 2328 | name: "screen.png", |
| 2329 | mimeType: "image/png", |
| 2330 | sizeBytes: 1, |
| 2331 | previewUri: "file:///drafts/screen.png", |
| 2332 | fileUri: "file:///drafts/screen.png", |
| 2333 | uploadedAttachmentId: "upload-1", |
| 2334 | uploadEnvironmentId: EnvironmentId.make("environment-1"), |
| 2335 | }; |
| 2336 | const uploadedOnTarget: DraftComposerAttachment = { |
| 2337 | ...uploadedElsewhere, |
| 2338 | id: "image-2", |
| 2339 | uploadedAttachmentId: "upload-2", |
| 2340 | uploadEnvironmentId: EnvironmentId.make("environment-2"), |
| 2341 | }; |
| 2342 | const key = createNewTaskDraft({ |
| 2343 | environmentId: EnvironmentId.make("environment-1"), |
| 2344 | projectId: ProjectId.make("project-1"), |
| 2345 | }); |
| 2346 | appAtomRegistry.set(composerDraftsAtom, { |
| 2347 | ...appAtomRegistry.get(composerDraftsAtom), |
| 2348 | [key]: { |
| 2349 | ...getComposerDraftSnapshot(key), |
| 2350 | text: "Ship it", |
| 2351 | attachments: [uploadedElsewhere, uploadedOnTarget], |
| 2352 | }, |
| 2353 | }); |
| 2354 | |
| 2355 | retargetNewTaskDraft(key, { |
| 2356 | environmentId: EnvironmentId.make("environment-2"), |
| 2357 | projectId: ProjectId.make("project-2"), |
| 2358 | }); |
| 2359 | |
| 2360 | expect(getComposerDraftSnapshot(key).attachments).toEqual([ |
| 2361 | { |
| 2362 | id: "image-1", |
| 2363 | type: "image", |
| 2364 | name: "screen.png", |
| 2365 | mimeType: "image/png", |
| 2366 | sizeBytes: 1, |
| 2367 | previewUri: "file:///drafts/screen.png", |
| 2368 | fileUri: "file:///drafts/screen.png", |
| 2369 | }, |
| 2370 | uploadedOnTarget, |
| 2371 | ]); |
| 2372 | }); |
| 2373 | |
| 2374 | it("merges shared content into a project draft without duplicating retries", () => { |
| 2375 | const draftKey = "new-task:environment-1:project-1"; |
| 2376 | const sharedAttachment = { |
| 2377 | id: "share-1-image-0", |
| 2378 | type: "image" as const, |
| 2379 | name: "Screenshot.png", |
| 2380 | mimeType: "image/png", |
| 2381 | sizeBytes: 3, |
| 2382 | dataUrl: "data:image/png;base64,YWJj", |
| 2383 | previewUri: "data:image/png;base64,YWJj", |
| 2384 | }; |
| 2385 | const existing: Record<string, ComposerDraft> = { |
| 2386 | [draftKey]: { text: "Existing context", attachments: [] }, |
| 2387 | }; |
| 2388 | const content = { |
| 2389 | text: "Shared note", |
| 2390 | attachments: [sharedAttachment], |
| 2391 | sourceShareId: "share-1", |
| 2392 | }; |
| 2393 | |
| 2394 | const merged = mergeComposerDraftContentState(existing, draftKey, content); |
| 2395 | expect(merged[draftKey]).toMatchObject({ |
| 2396 | text: "Existing context\n\nShared note", |
| 2397 | attachments: [sharedAttachment], |
| 2398 | importedShareIds: ["share-1"], |
| 2399 | }); |
| 2400 | expect(mergeComposerDraftContentState(merged, draftKey, content)).toBe(merged); |
| 2401 | |
| 2402 | const edited = { |
| 2403 | ...merged, |
| 2404 | [draftKey]: { ...merged[draftKey]!, text: "User edited the imported context" }, |
| 2405 | }; |
| 2406 | expect(mergeComposerDraftContentState(edited, draftKey, content)).toBe(edited); |
| 2407 | }); |
| 2408 | |
| 2409 | it("shows a shared non-image file as a composer chip", () => { |
| 2410 | const draftKey = "new-task:environment-1:project-1"; |
| 2411 | const sharedFile = { |
| 2412 | id: "share-1-file-0", |
| 2413 | type: "file" as const, |
| 2414 | name: "backup.json", |
| 2415 | mimeType: "application/json", |
| 2416 | sizeBytes: 41, |
| 2417 | fileUri: "file:///documents/backup.json", |
| 2418 | }; |
| 2419 | |
| 2420 | const existingFile = { ...sharedFile, id: "existing-file", name: "notes.txt" }; |
| 2421 | |
| 2422 | const merged = mergeComposerDraftContentState( |
| 2423 | { [draftKey]: { text: "", attachments: [existingFile] } }, |
| 2424 | draftKey, |
| 2425 | { text: "", attachments: [sharedFile], sourceShareId: "share-1" }, |
| 2426 | )[draftKey]!; |
| 2427 | |
| 2428 | expect(merged.attachments).toEqual([existingFile, sharedFile]); |
| 2429 | const references = collectComposerContextReferences(merged.text); |
| 2430 | expect(references).toHaveLength(1); |
| 2431 | expect(merged.context?.records).toEqual([ |
| 2432 | expect.objectContaining({ |
| 2433 | kind: "file", |
| 2434 | contextId: references[0]!.contextId, |
| 2435 | attachmentId: sharedFile.id, |
| 2436 | }), |
| 2437 | ]); |
| 2438 | |
| 2439 | // A recovery merge carries its own text; a chip appended to it would |
| 2440 | // break the duplicate-text check when the merge is retried. |
| 2441 | const recovered = { text: "Retry this", attachments: [sharedFile] }; |
| 2442 | const once = mergeComposerDraftContentState({}, draftKey, recovered); |
| 2443 | expect(once[draftKey]?.text).toBe("Retry this"); |
| 2444 | expect(mergeComposerDraftContentState(once, draftKey, recovered)).toBe(once); |
| 2445 | }); |
| 2446 | |
| 2447 | it("lets a shared file through the send check", async () => { |
| 2448 | const { attachments } = await buildIncomingShareDraft({ |
| 2449 | id: "share-1", |
| 2450 | createdAt: "2026-07-15T10:00:00.000Z", |
| 2451 | payloads: [ |
| 2452 | { |
| 2453 | shareType: "file", |
| 2454 | value: "file:///shared/report.xlsx", |
| 2455 | mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", |
| 2456 | originalName: "report.xlsx", |
| 2457 | }, |
| 2458 | ], |
| 2459 | resolvedPayloads: [], |
| 2460 | fileReader: { |
| 2461 | readBase64: async () => "", |
| 2462 | readSize: async () => 42, |
| 2463 | removeOwnedFile: async () => {}, |
| 2464 | }, |
| 2465 | }); |
| 2466 | const draftKey = "new-task:environment-1:project-1"; |
| 2467 | |
| 2468 | const merged = mergeComposerDraftContentState({}, draftKey, { |
| 2469 | text: "", |
| 2470 | attachments, |
| 2471 | sourceShareId: "share-1", |
| 2472 | })[draftKey]!; |
| 2473 | |
| 2474 | expect(merged.context?.records).toHaveLength(1); |
| 2475 | expect(composerContextSendBlockReason(merged.context)).toBeNull(); |
| 2476 | }); |
| 2477 | |
| 2478 | it("preserves existing images when shared content exceeds the draft attachment limit", () => { |
| 2479 | const draftKey = "new-task:environment-1:project-1"; |
| 2480 | const image = (id: string) => ({ |
| 2481 | id, |
| 2482 | type: "image" as const, |
| 2483 | name: `${id}.png`, |
| 2484 | mimeType: "image/png", |
| 2485 | sizeBytes: 3, |
| 2486 | dataUrl: "data:image/png;base64,YWJj", |
| 2487 | previewUri: "data:image/png;base64,YWJj", |
| 2488 | }); |
| 2489 | const existingImage = image("existing"); |
| 2490 | const sharedImages = Array.from({ length: 100 }, (_, index) => image(`shared-${index}`)); |
| 2491 | |
| 2492 | const merged = mergeComposerDraftContentState( |
| 2493 | { [draftKey]: { text: "", attachments: [existingImage] } }, |
| 2494 | draftKey, |
| 2495 | { text: "", attachments: sharedImages }, |
| 2496 | ); |
| 2497 | |
| 2498 | expect(merged[draftKey]?.attachments).toHaveLength(100); |
| 2499 | expect(merged[draftKey]?.attachments[0]).toEqual(existingImage); |
| 2500 | expect(merged[draftKey]?.attachments.at(-1)?.id).toBe("shared-98"); |
| 2501 | }); |
| 2502 | |
| 2503 | it("restores the exact draft captured before an interrupted share import", () => { |
| 2504 | const draftKey = "new-task:environment-1:project-1"; |
| 2505 | const beforeImport: ComposerDraft = { |
| 2506 | text: "Existing context", |
| 2507 | attachments: [], |
| 2508 | runtimeMode: "approval-required", |
| 2509 | }; |
| 2510 | const imported: ComposerDraft = { |
| 2511 | ...beforeImport, |
| 2512 | text: "Existing context\n\nShared note", |
| 2513 | importedShareIds: ["share-1"], |
| 2514 | }; |
| 2515 | |
| 2516 | expect( |
| 2517 | restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, beforeImport), |
| 2518 | ).toEqual({ [draftKey]: beforeImport }); |
| 2519 | expect( |
| 2520 | restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, { |
| 2521 | text: "", |
| 2522 | attachments: [], |
| 2523 | }), |
| 2524 | ).toEqual({}); |
| 2525 | }); |
| 2526 | |
| 2527 | it("removes only drafts owned by the selected environment", () => { |
| 2528 | const environmentId = EnvironmentId.make("environment-cloud"); |
| 2529 | const retainedEnvironmentId = EnvironmentId.make("environment-local"); |
| 2530 | |
| 2531 | const cloudDraft: ComposerDraft = { |
| 2532 | ...DRAFT, |
| 2533 | project: { |
| 2534 | environmentId, |
| 2535 | projectId: ProjectId.make("project-cloud"), |
| 2536 | createdAt: "2026-09-05T00:00:00.000Z", |
| 2537 | }, |
| 2538 | }; |
| 2539 | const localDraft: ComposerDraft = { |
| 2540 | ...DRAFT, |
| 2541 | project: { |
| 2542 | environmentId: retainedEnvironmentId, |
| 2543 | projectId: ProjectId.make("project-local"), |
| 2544 | createdAt: "2026-09-05T00:00:00.000Z", |
| 2545 | }, |
| 2546 | }; |
| 2547 | |
| 2548 | expect( |
| 2549 | removeComposerDraftsForEnvironment( |
| 2550 | { |
| 2551 | [`${environmentId}:thread-cloud`]: DRAFT, |
| 2552 | "new-task:cloud-draft": cloudDraft, |
| 2553 | [`${retainedEnvironmentId}:thread-local`]: DRAFT, |
| 2554 | "new-task:local-draft": localDraft, |
| 2555 | }, |
| 2556 | environmentId, |
| 2557 | ), |
| 2558 | ).toEqual({ |
| 2559 | [`${retainedEnvironmentId}:thread-local`]: DRAFT, |
| 2560 | "new-task:local-draft": localDraft, |
| 2561 | }); |
| 2562 | }); |
| 2563 | |
| 2564 | it("aborts operations running for drafts an environment removal drops", async () => { |
| 2565 | const environmentId = EnvironmentId.make("environment-removed"); |
| 2566 | composerDraftFileMocks.setDocument({ schemaVersion: 1, drafts: {} }); |
| 2567 | appAtomRegistry.set(composerDraftsAtom, { |
| 2568 | "new-task:removed-draft": { |
| 2569 | ...DRAFT, |
| 2570 | project: { |
| 2571 | environmentId, |
| 2572 | projectId: ProjectId.make("project-removed"), |
| 2573 | createdAt: "2026-09-05T00:00:00.000Z", |
| 2574 | }, |
| 2575 | }, |
| 2576 | "environment-kept:thread-kept": DRAFT, |
| 2577 | }); |
| 2578 | const newTask = startComposerDraftOperation("new-task:removed-draft"); |
| 2579 | const emptyThread = startComposerDraftOperation(`${environmentId}:thread-empty`); |
| 2580 | const kept = startComposerDraftOperation("environment-kept:thread-kept"); |
| 2581 | |
| 2582 | await clearComposerDraftsEnvironment(environmentId); |
| 2583 | |
| 2584 | expect(newTask.signal.aborted).toBe(true); |
| 2585 | expect(emptyThread.signal.aborted).toBe(true); |
| 2586 | expect(kept.signal.aborted).toBe(false); |
| 2587 | kept.finish(); |
| 2588 | }); |
| 2589 | |
| 2590 | it("lands a still-debounced draft write when flushed", async () => { |
| 2591 | const draftKey = "environment-1:thread-1"; |
| 2592 | setComposerDraftText(draftKey, "typed right before the restart"); |
| 2593 | |
| 2594 | await flushComposerDrafts(); |
| 2595 | |
| 2596 | expect(JSON.parse(composerDraftFileMocks.getDocument())).toMatchObject({ |
| 2597 | drafts: { [draftKey]: { text: "typed right before the restart" } }, |
| 2598 | }); |
| 2599 | }); |
| 2600 | |
| 2601 | it("propagates a flush write failure instead of resolving as saved", async () => { |
| 2602 | const draftKey = "environment-1:thread-1"; |
| 2603 | setComposerDraftText(draftKey, "unsaved"); |
| 2604 | composerDraftFileMocks.setWriteError(new Error("storage unavailable")); |
| 2605 | |
| 2606 | try { |
| 2607 | await expect(flushComposerDrafts()).rejects.toBeInstanceOf(ComposerDraftPersistenceError); |
| 2608 | } finally { |
| 2609 | composerDraftFileMocks.setWriteError(null); |
| 2610 | } |
| 2611 | }); |
| 2612 | |
| 2613 | it("restores the pre-merge snapshot when the draft is untouched since the merge", () => { |
| 2614 | const draftKey = "environment-1:thread-1"; |
| 2615 | const snapshot: ComposerDraft = { text: "typed before", attachments: [] }; |
| 2616 | const merged: ComposerDraft = { |
| 2617 | text: "typed before\n\nqueued text", |
| 2618 | attachments: [], |
| 2619 | runtimeMode: "approval-required", |
| 2620 | }; |
| 2621 | |
| 2622 | expect(undoComposerDraftMergeState({ [draftKey]: merged }, draftKey, snapshot, merged)).toEqual( |
| 2623 | { [draftKey]: snapshot }, |
| 2624 | ); |
| 2625 | expect( |
| 2626 | undoComposerDraftMergeState( |
| 2627 | { [draftKey]: merged }, |
| 2628 | draftKey, |
| 2629 | { text: "", attachments: [] }, |
| 2630 | merged, |
| 2631 | ), |
| 2632 | ).toEqual({}); |
| 2633 | }); |
| 2634 | |
| 2635 | it("returns merge-written settings to the snapshot but keeps user-edited ones", () => { |
| 2636 | const draftKey = "environment-1:thread-1"; |
| 2637 | const snapshot: ComposerDraft = { |
| 2638 | text: "typed before", |
| 2639 | attachments: [], |
| 2640 | runtimeMode: "approval-required", |
| 2641 | interactionMode: "default", |
| 2642 | }; |
| 2643 | const merged: ComposerDraft = { |
| 2644 | text: "typed before\n\nqueued text", |
| 2645 | attachments: [], |
| 2646 | runtimeMode: "full-access", |
| 2647 | interactionMode: "default", |
| 2648 | }; |
| 2649 | |
| 2650 | const edited: ComposerDraft = { |
| 2651 | text: "typed EDITED before\n\nqueued text", |
| 2652 | attachments: [], |
| 2653 | runtimeMode: "full-access", |
| 2654 | interactionMode: "plan", |
| 2655 | }; |
| 2656 | |
| 2657 | expect(undoComposerDraftMergeState({ [draftKey]: edited }, draftKey, snapshot, merged)).toEqual( |
| 2658 | { |
| 2659 | [draftKey]: { |
| 2660 | text: "typed EDITED before", |
| 2661 | attachments: [], |
| 2662 | runtimeMode: "approval-required", |
| 2663 | interactionMode: "plan", |
| 2664 | }, |
| 2665 | }, |
| 2666 | ); |
| 2667 | }); |
| 2668 | |
| 2669 | it("takes out only what the merge inserted when the user edited during it", () => { |
| 2670 | const draftKey = "environment-1:thread-1"; |
| 2671 | const keptAttachment = { |
| 2672 | id: "kept", |
| 2673 | type: "file" as const, |
| 2674 | name: "kept.pdf", |
| 2675 | mimeType: "application/pdf", |
| 2676 | sizeBytes: 1, |
| 2677 | fileUri: "file:///documents/t3-composer-attachments/kept.pdf", |
| 2678 | }; |
| 2679 | const insertedAttachment = { |
| 2680 | id: "inserted", |
| 2681 | type: "file" as const, |
| 2682 | name: "inserted.pdf", |
| 2683 | mimeType: "application/pdf", |
| 2684 | sizeBytes: 1, |
| 2685 | fileUri: "file:///documents/t3-composer-attachments/inserted.pdf", |
| 2686 | }; |
| 2687 | const userAttachment = { ...keptAttachment, id: "user-added" }; |
| 2688 | const snapshot: ComposerDraft = { text: "typed before", attachments: [keptAttachment] }; |
| 2689 | const merged: ComposerDraft = { |
| 2690 | text: "typed before\n\nqueued text", |
| 2691 | attachments: [keptAttachment, insertedAttachment], |
| 2692 | }; |
| 2693 | |
| 2694 | const edited: ComposerDraft = { |
| 2695 | text: "typed EDITED before\n\nqueued text", |
| 2696 | attachments: [keptAttachment, insertedAttachment, userAttachment], |
| 2697 | }; |
| 2698 | |
| 2699 | expect(undoComposerDraftMergeState({ [draftKey]: edited }, draftKey, snapshot, merged)).toEqual( |
| 2700 | { |
| 2701 | [draftKey]: { |
| 2702 | text: "typed EDITED before", |
| 2703 | attachments: [keptAttachment, userAttachment], |
| 2704 | }, |
| 2705 | }, |
| 2706 | ); |
| 2707 | |
| 2708 | const rewritten: ComposerDraft = { |
| 2709 | text: "totally rewritten", |
| 2710 | attachments: [insertedAttachment], |
| 2711 | }; |
| 2712 | expect( |
| 2713 | undoComposerDraftMergeState({ [draftKey]: rewritten }, draftKey, snapshot, merged), |
| 2714 | ).toEqual({ |
| 2715 | [draftKey]: { text: "totally rewritten", attachments: [] }, |
| 2716 | }); |
| 2717 | }); |
| 2718 | |
| 2719 | it("keeps text appended after a merge when rolling it back", () => { |
| 2720 | const draftKey = "environment-1:thread-1"; |
| 2721 | const snapshot: ComposerDraft = { text: "typed before", attachments: [] }; |
| 2722 | const content = { text: "queued text", attachments: [] }; |
| 2723 | const merged = mergeComposerDraftContentState({ [draftKey]: snapshot }, draftKey, content)[ |
| 2724 | draftKey |
| 2725 | ]!; |
| 2726 | const edited: ComposerDraft = { |
| 2727 | ...merged, |
| 2728 | text: `${merged.text}\n\nuser follow-up`, |
| 2729 | }; |
| 2730 | |
| 2731 | const rolledBack = undoComposerDraftMergeState( |
| 2732 | { [draftKey]: edited }, |
| 2733 | draftKey, |
| 2734 | snapshot, |
| 2735 | merged, |
| 2736 | ); |
| 2737 | |
| 2738 | expect(rolledBack[draftKey]?.text).toBe("typed before\n\nuser follow-up"); |
| 2739 | const retried = mergeComposerDraftContentState(rolledBack, draftKey, content); |
| 2740 | expect(retried[draftKey]?.text.match(/queued text/g)).toHaveLength(1); |
| 2741 | }); |
| 2742 | |
| 2743 | it("spares a file re-owned between the sweep's scan and its deletion", async () => { |
| 2744 | const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); |
| 2745 | onTestFinished(() => outboxLoad.mockRestore()); |
| 2746 | const fileFor = (id: string) => ({ |
| 2747 | id, |
| 2748 | type: "file" as const, |
| 2749 | name: `${id}.pdf`, |
| 2750 | mimeType: "application/pdf", |
| 2751 | sizeBytes: 42, |
| 2752 | fileUri: `file:///documents/t3-composer-attachments/${id}.pdf`, |
| 2753 | }); |
| 2754 | const first = fileFor("file-first"); |
| 2755 | const reowned = fileFor("file-reowned"); |
| 2756 | |
| 2757 | composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => { |
| 2758 | appAtomRegistry.set(composerDraftsAtom, { |
| 2759 | "environment-1:thread-1": { text: "restored", attachments: [reowned] }, |
| 2760 | }); |
| 2761 | }); |
| 2762 | |
| 2763 | await releaseUnusedComposerAttachmentFiles([first, reowned]); |
| 2764 | |
| 2765 | expect(composerAttachmentCleanupMocks.remove.mock.calls).toEqual([[first.fileUri]]); |
| 2766 | }); |
| 2767 | |
| 2768 | it("keeps attachment files and uploads after a recovered message leaves an incomplete outbox", async () => { |
| 2769 | vi.resetModules(); |
| 2770 | const drafts = await import("./use-composer-drafts"); |
| 2771 | const { threadOutboxManager: manager } = await import("./thread-outbox"); |
| 2772 | const { expoThreadOutboxStorage: storage, ThreadOutboxStorageError } = |
| 2773 | await import("./thread-outbox-storage"); |
| 2774 | const { removeThreadOutboxMessage } = await import("./thread-outbox-removal"); |
| 2775 | const { appAtomRegistry: registry } = await import("./atom-registry"); |
| 2776 | onTestFinished(() => registry.dispose()); |
| 2777 | const warning = vi.spyOn(console, "warn").mockImplementation(() => {}); |
| 2778 | onTestFinished(() => warning.mockRestore()); |
| 2779 | const file = { |
| 2780 | id: "file-partial-outbox", |
| 2781 | type: "file" as const, |
| 2782 | name: "shared.pdf", |
| 2783 | mimeType: "application/pdf", |
| 2784 | sizeBytes: 42, |
| 2785 | fileUri: "file:///documents/t3-composer-attachments/shared.pdf", |
| 2786 | uploadEnvironmentId: EnvironmentId.make("environment-1"), |
| 2787 | uploadedAttachmentId: "pending-partial-outbox", |
| 2788 | }; |
| 2789 | const readable = { |
| 2790 | environmentId: EnvironmentId.make("environment-1"), |
| 2791 | threadId: ThreadId.make("thread-1"), |
| 2792 | messageId: MessageId.make("message-readable"), |
| 2793 | commandId: CommandId.make("command-readable"), |
| 2794 | text: "Send the readable message", |
| 2795 | attachments: [file], |
| 2796 | createdAt: "2026-09-04T00:00:00.000Z", |
| 2797 | }; |
| 2798 | const saved = new Map([[readable.messageId, readable]]); |
| 2799 | let unreadable = true; |
| 2800 | const load = vi.spyOn(storage, "load").mockImplementation(async () => ({ |
| 2801 | messages: [...saved.values()], |
| 2802 | errors: unreadable |
| 2803 | ? [ |
| 2804 | new ThreadOutboxStorageError({ |
| 2805 | operation: "read-message", |
| 2806 | environmentId: null, |
| 2807 | threadId: null, |
| 2808 | messageId: null, |
| 2809 | fileName: "unreadable.json", |
| 2810 | cause: new Error("unreadable record"), |
| 2811 | }), |
| 2812 | ] |
| 2813 | : [], |
| 2814 | })); |
| 2815 | const remove = vi.spyOn(storage, "remove").mockImplementation(async (message) => { |
| 2816 | saved.delete(message.messageId); |
| 2817 | }); |
| 2818 | onTestFinished(() => { |
| 2819 | load.mockRestore(); |
| 2820 | remove.mockRestore(); |
| 2821 | }); |
| 2822 | |
| 2823 | await expect(manager.load()).resolves.toBe(false); |
| 2824 | await expect(manager.confirmQueued(readable)).resolves.toBe(true); |
| 2825 | await expect(removeThreadOutboxMessage(readable)).resolves.toBe(true); |
| 2826 | await drafts.releaseUnusedComposerAttachmentFiles([file]); |
| 2827 | expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({}); |
| 2828 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 2829 | expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled(); |
| 2830 | |
| 2831 | const recovered = { |
| 2832 | ...readable, |
| 2833 | environmentId: EnvironmentId.make("environment-2"), |
| 2834 | messageId: MessageId.make("message-recovered"), |
| 2835 | commandId: CommandId.make("command-recovered"), |
| 2836 | }; |
| 2837 | saved.set(recovered.messageId, recovered); |
| 2838 | unreadable = false; |
| 2839 | await expect(manager.load()).resolves.toBe(true); |
| 2840 | await drafts.releaseUnusedComposerAttachmentFiles([file]); |
| 2841 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 2842 | expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled(); |
| 2843 | |
| 2844 | await removeThreadOutboxMessage(recovered); |
| 2845 | await drafts.releaseUnusedComposerAttachmentFiles([file]); |
| 2846 | expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(file.fileUri); |
| 2847 | expect(composerAttachmentCleanupMocks.releaseUploads).toHaveBeenCalledWith( |
| 2848 | file.uploadEnvironmentId, |
| 2849 | [file.uploadedAttachmentId], |
| 2850 | ); |
| 2851 | }); |
| 2852 | |
| 2853 | it("hydrates persisted drafts before a cold-start sweep deletes their files", async () => { |
| 2854 | const file = { |
| 2855 | id: "file-cold-start", |
| 2856 | type: "file" as const, |
| 2857 | name: "report.pdf", |
| 2858 | mimeType: "application/pdf", |
| 2859 | sizeBytes: 42, |
| 2860 | fileUri: "file:///documents/t3-composer-attachments/report.pdf", |
| 2861 | }; |
| 2862 | composerDraftFileMocks.setDocument({ |
| 2863 | schemaVersion: 1, |
| 2864 | drafts: { |
| 2865 | "environment-1:thread-1": { text: "Persisted draft", attachments: [file] }, |
| 2866 | }, |
| 2867 | }); |
| 2868 | vi.resetModules(); |
| 2869 | const fresh = await import("./use-composer-drafts"); |
| 2870 | const freshRegistry = (await import("./atom-registry")).appAtomRegistry; |
| 2871 | |
| 2872 | await fresh.releaseUnusedComposerAttachmentFiles([file]); |
| 2873 | |
| 2874 | expect(freshRegistry.get(fresh.composerDraftsAtom)).toEqual({ |
| 2875 | "environment-1:thread-1": { |
| 2876 | text: "Persisted draft [report.pdf](t3-context://v1/file/file-cold-start) ", |
| 2877 | attachments: [file], |
| 2878 | context: { |
| 2879 | version: 1, |
| 2880 | records: [ |
| 2881 | { |
| 2882 | version: 1, |
| 2883 | contextId: file.id, |
| 2884 | kind: "file", |
| 2885 | label: file.name, |
| 2886 | attachmentId: file.id, |
| 2887 | name: file.name, |
| 2888 | mimeType: file.mimeType, |
| 2889 | sizeBytes: file.sizeBytes, |
| 2890 | }, |
| 2891 | ], |
| 2892 | }, |
| 2893 | }, |
| 2894 | }); |
| 2895 | expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled(); |
| 2896 | }); |
| 2897 | }); |