The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | acknowledgedThreadMessagesAtom, |
| 3 | pruneCaughtUpAcknowledgedThreadMessages, |
| 4 | } from "./acknowledged-thread-messages"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Fiber from "effect/Fiber"; |
| 7 | import { |
| 8 | CommandId, |
| 9 | ComposerContextId, |
| 10 | EnvironmentId, |
| 11 | MessageId, |
| 12 | ProjectId, |
| 13 | ProviderInstanceId, |
| 14 | ThreadId, |
| 15 | } from "@t3tools/contracts"; |
| 16 | import { describe, expect, it } from "@effect/vitest"; |
| 17 | import { afterEach, beforeEach, vi } from "vite-plus/test"; |
| 18 | |
| 19 | import type { PreparedTurnAttachments } from "../lib/attachmentUpload"; |
| 20 | |
| 21 | const harness = vi.hoisted(() => ({ |
| 22 | canOperate: true, |
| 23 | threadState: null as unknown as import("effect/reactivity").Atom.Writable<{ |
| 24 | readonly data: import("effect/Option").Option<{ |
| 25 | readonly messages: ReadonlyArray<{ readonly id: string }>; |
| 26 | }>; |
| 27 | readonly sequence: number; |
| 28 | }>, |
| 29 | manager: null as unknown as ReturnType< |
| 30 | typeof import("./thread-outbox-manager").createThreadOutboxManager |
| 31 | >, |
| 32 | removePersistedFile: vi.fn(async () => undefined), |
| 33 | removeOutboxMessage: vi.fn(async (_message: QueuedThreadMessage) => undefined), |
| 34 | prepareTurnAttachments: vi.fn<typeof import("../lib/attachmentUpload").prepareTurnAttachments>(), |
| 35 | draftFile: (() => { |
| 36 | let document = ""; |
| 37 | let writeError: Error | null = null; |
| 38 | return { |
| 39 | setDocument(value: unknown) { |
| 40 | document = JSON.stringify(value); |
| 41 | }, |
| 42 | setWriteError(error: Error | null) { |
| 43 | writeError = error; |
| 44 | }, |
| 45 | Directory: class { |
| 46 | create() {} |
| 47 | }, |
| 48 | File: class { |
| 49 | exists = true; |
| 50 | parentDirectory = null; |
| 51 | |
| 52 | create() {} |
| 53 | |
| 54 | moveSync() {} |
| 55 | |
| 56 | async text() { |
| 57 | return document; |
| 58 | } |
| 59 | |
| 60 | write(value: string) { |
| 61 | if (writeError) { |
| 62 | throw writeError; |
| 63 | } |
| 64 | document = value; |
| 65 | } |
| 66 | }, |
| 67 | }; |
| 68 | })(), |
| 69 | })); |
| 70 | |
| 71 | vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } })); |
| 72 | |
| 73 | vi.mock("expo-file-system", () => ({ |
| 74 | Directory: harness.draftFile.Directory, |
| 75 | File: harness.draftFile.File, |
| 76 | Paths: { document: "/documents" }, |
| 77 | })); |
| 78 | |
| 79 | vi.mock("../lib/composerImages", () => ({ |
| 80 | removePersistedComposerAttachmentFile: harness.removePersistedFile, |
| 81 | })); |
| 82 | |
| 83 | vi.mock("../lib/uuid", () => ({ |
| 84 | uuidv4: () => "00000000-0000-4000-8000-000000000000", |
| 85 | randomHex: () => "abcd", |
| 86 | })); |
| 87 | |
| 88 | vi.mock("../lib/attachmentUpload", () => ({ |
| 89 | prepareTurnAttachments: harness.prepareTurnAttachments, |
| 90 | })); |
| 91 | vi.mock("./composer-attachment-uploads", () => ({ uploadComposerAttachmentShared: vi.fn() })); |
| 92 | |
| 93 | vi.mock("./projects", () => ({ environmentProjects: {} })); |
| 94 | |
| 95 | vi.mock("./workspace", () => ({ workspaceConnections: {} })); |
| 96 | |
| 97 | vi.mock("./server", async () => { |
| 98 | const { Atom } = await import("effect/reactivity"); |
| 99 | return { serverEnvironment: { configValueAtom: Atom.family(() => Atom.make(null)) } }; |
| 100 | }); |
| 101 | |
| 102 | vi.mock("./git", () => ({ gitEnvironment: {} })); |
| 103 | |
| 104 | vi.mock("./threads", async () => { |
| 105 | const { Atom } = await import("effect/reactivity"); |
| 106 | const Option = await import("effect/Option"); |
| 107 | harness.threadState = Atom.make({ |
| 108 | data: Option.none<{ readonly messages: ReadonlyArray<{ readonly id: string }> }>(), |
| 109 | sequence: 0, |
| 110 | }).pipe(Atom.keepAlive); |
| 111 | return { |
| 112 | threadEnvironment: {}, |
| 113 | environmentThreadDetails: { stateAtom: () => harness.threadState }, |
| 114 | }; |
| 115 | }); |
| 116 | |
| 117 | vi.mock("./session", () => ({ |
| 118 | environmentSession: {}, |
| 119 | readEnvironmentScope: () => harness.canOperate, |
| 120 | sessionHasScope: () => harness.canOperate, |
| 121 | })); |
| 122 | |
| 123 | vi.mock("./use-thread-outbox", async () => { |
| 124 | const { Atom } = await import("effect/reactivity"); |
| 125 | return { |
| 126 | editingQueuedMessageIdsAtom: Atom.make<Record<string, boolean>>({}).pipe(Atom.keepAlive), |
| 127 | dispatchingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive), |
| 128 | retryingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive), |
| 129 | threadOutboxShellStatusesAtom: Atom.make(new Map()), |
| 130 | }; |
| 131 | }); |
| 132 | |
| 133 | vi.mock("./thread-outbox", async () => { |
| 134 | const { createThreadOutboxManager } = await import("./thread-outbox-manager"); |
| 135 | const { appAtomRegistry } = await import("./atom-registry"); |
| 136 | harness.manager = createThreadOutboxManager({ |
| 137 | registry: appAtomRegistry, |
| 138 | storage: { |
| 139 | load: async () => ({ messages: [], errors: [] }), |
| 140 | write: async () => undefined, |
| 141 | remove: (message) => harness.removeOutboxMessage(message), |
| 142 | }, |
| 143 | }); |
| 144 | const manager = harness.manager; |
| 145 | return { |
| 146 | threadOutboxManager: manager, |
| 147 | flushThreadOutbox: async () => undefined, |
| 148 | confirmThreadOutboxMessageQueued: (message: never) => manager.confirmQueued(message), |
| 149 | updateThreadOutboxMessage: (message: never, expectedRevision?: number) => |
| 150 | manager.update(message, expectedRevision), |
| 151 | threadOutboxRevision: (messageId: never) => manager.revisionOf(messageId), |
| 152 | }; |
| 153 | }); |
| 154 | |
| 155 | import * as Option from "effect/Option"; |
| 156 | import { scopedThreadKey } from "../lib/scopedEntities"; |
| 157 | import { appAtomRegistry } from "./atom-registry"; |
| 158 | import { pendingThreadCreationOutcomesAtom } from "./pending-thread-creation"; |
| 159 | import { clearThreadComposerError, threadComposerErrorsAtom } from "./thread-composer-error"; |
| 160 | import type { QueuedThreadMessage } from "./thread-outbox-model"; |
| 161 | import * as composerDrafts from "./use-composer-drafts"; |
| 162 | import { startComposerDraftOperation } from "./composerDraftOperations"; |
| 163 | import { recoverFailedThreadDraft } from "./recover-failed-thread-draft"; |
| 164 | import { editingQueuedMessageIdsAtom } from "./use-thread-outbox"; |
| 165 | import { |
| 166 | completeQueuedMessageDelivery, |
| 167 | type DeliveryRetry, |
| 168 | prepareQueuedMessageAttachments, |
| 169 | recoverEditedCreationAfterDelivery, |
| 170 | removeAcknowledgedExistingThreadMessage, |
| 171 | restoreRejectedQueuedMessage, |
| 172 | } from "./threadOutboxDelivery"; |
| 173 | |
| 174 | function queuedMessage(input: { |
| 175 | readonly messageId: string; |
| 176 | readonly text: string; |
| 177 | readonly fileUri?: string; |
| 178 | }): QueuedThreadMessage { |
| 179 | return { |
| 180 | environmentId: EnvironmentId.make("environment-1"), |
| 181 | threadId: ThreadId.make("thread-1"), |
| 182 | messageId: MessageId.make(input.messageId), |
| 183 | commandId: CommandId.make(`command-${input.messageId}`), |
| 184 | text: input.text, |
| 185 | attachments: input.fileUri |
| 186 | ? [ |
| 187 | { |
| 188 | id: `file-${input.messageId}`, |
| 189 | type: "file", |
| 190 | name: "report.pdf", |
| 191 | mimeType: "application/pdf", |
| 192 | sizeBytes: 42, |
| 193 | fileUri: input.fileUri, |
| 194 | }, |
| 195 | ] |
| 196 | : [], |
| 197 | createdAt: "2026-08-24T12:00:00.000Z", |
| 198 | }; |
| 199 | } |
| 200 | |
| 201 | function withReusedFileUpload( |
| 202 | message: QueuedThreadMessage, |
| 203 | attachmentId: string, |
| 204 | ): QueuedThreadMessage { |
| 205 | return { |
| 206 | ...message, |
| 207 | attachments: message.attachments.map((attachment) => |
| 208 | attachment.type === "file" |
| 209 | ? { |
| 210 | ...attachment, |
| 211 | uploadedAttachmentId: attachmentId, |
| 212 | uploadEnvironmentId: message.environmentId, |
| 213 | } |
| 214 | : attachment, |
| 215 | ), |
| 216 | }; |
| 217 | } |
| 218 | |
| 219 | function remainingMessages(): ReadonlyArray<QueuedThreadMessage> { |
| 220 | return Object.values(appAtomRegistry.get(harness.manager.queuedMessagesByThreadKeyAtom)).flat(); |
| 221 | } |
| 222 | |
| 223 | beforeEach(() => { |
| 224 | appAtomRegistry.set(acknowledgedThreadMessagesAtom, []); |
| 225 | appAtomRegistry.set(harness.threadState, { data: Option.none(), sequence: 0 }); |
| 226 | harness.canOperate = true; |
| 227 | harness.draftFile.setDocument({ schemaVersion: 1, drafts: {} }); |
| 228 | }); |
| 229 | |
| 230 | afterEach(() => { |
| 231 | appAtomRegistry.set(harness.manager.queuedMessagesByThreadKeyAtom, {}); |
| 232 | appAtomRegistry.set(composerDrafts.composerDraftsAtom, {}); |
| 233 | appAtomRegistry.set(composerDrafts.composerCloudDraftsAtom, { accountId: null, signedOut: {} }); |
| 234 | appAtomRegistry.set(editingQueuedMessageIdsAtom, {}); |
| 235 | appAtomRegistry.set(pendingThreadCreationOutcomesAtom, {}); |
| 236 | appAtomRegistry.set(threadComposerErrorsAtom, {}); |
| 237 | harness.draftFile.setWriteError(null); |
| 238 | harness.removePersistedFile.mockClear(); |
| 239 | harness.removeOutboxMessage.mockClear(); |
| 240 | harness.prepareTurnAttachments.mockReset(); |
| 241 | }); |
| 242 | |
| 243 | /** True once a delivery step handled its message, false when it asks to retry. */ |
| 244 | const handled = (step: Effect.Effect<void, DeliveryRetry>) => |
| 245 | step.pipe(Effect.as(true), Effect.catchTags({ DeliveryRetry: () => Effect.succeed(false) })); |
| 246 | |
| 247 | describe("thread outbox attachment preparation", () => { |
| 248 | it.effect("keeps a denied message queued without starting its attachment upload", () => |
| 249 | Effect.gen(function* () { |
| 250 | const message = queuedMessage({ |
| 251 | messageId: "denied-queued-message", |
| 252 | text: "Keep this queued", |
| 253 | fileUri: "file:///documents/keep.pdf", |
| 254 | }); |
| 255 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 256 | harness.prepareTurnAttachments.mockReturnValueOnce( |
| 257 | Effect.succeed({ |
| 258 | status: "ready", |
| 259 | attachments: [], |
| 260 | draftAttachments: message.attachments, |
| 261 | pendingAttachmentIds: [], |
| 262 | }), |
| 263 | ); |
| 264 | harness.canOperate = false; |
| 265 | expect(yield* prepareQueuedMessageAttachments(message)).toEqual({ |
| 266 | status: "abandoned", |
| 267 | }); |
| 268 | expect(harness.prepareTurnAttachments).not.toHaveBeenCalled(); |
| 269 | expect(remainingMessages()).toEqual([message]); |
| 270 | }), |
| 271 | ); |
| 272 | |
| 273 | it.effect("abandons reused uploads when an editor saves changed text during verification", () => |
| 274 | Effect.gen(function* () { |
| 275 | const message = withReusedFileUpload( |
| 276 | queuedMessage({ |
| 277 | messageId: "message-reused-upload-race", |
| 278 | text: "original text", |
| 279 | fileUri: "file:///documents/t3-composer-attachments/reused.pdf", |
| 280 | }), |
| 281 | "pending-reused-upload", |
| 282 | ); |
| 283 | const preparationStarted = Promise.withResolvers<void>(); |
| 284 | const preparationBarrier = Promise.withResolvers<PreparedTurnAttachments>(); |
| 285 | harness.prepareTurnAttachments.mockImplementationOnce(() => |
| 286 | Effect.promise(() => { |
| 287 | preparationStarted.resolve(); |
| 288 | return preparationBarrier.promise; |
| 289 | }), |
| 290 | ); |
| 291 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 292 | appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true }); |
| 293 | |
| 294 | const preparation = yield* Effect.forkChild(prepareQueuedMessageAttachments(message), { |
| 295 | startImmediately: true, |
| 296 | }); |
| 297 | yield* Effect.promise(() => preparationStarted.promise); |
| 298 | const edited = { ...message, text: "saved editor text" }; |
| 299 | yield* Effect.promise(() => harness.manager.update(edited)); |
| 300 | appAtomRegistry.set(editingQueuedMessageIdsAtom, {}); |
| 301 | preparationBarrier.resolve({ |
| 302 | status: "ready", |
| 303 | attachments: [], |
| 304 | draftAttachments: message.attachments, |
| 305 | pendingAttachmentIds: ["pending-reused-upload"], |
| 306 | }); |
| 307 | |
| 308 | expect(yield* Fiber.join(preparation)).toEqual({ status: "abandoned" }); |
| 309 | expect(remainingMessages()).toEqual([edited]); |
| 310 | }), |
| 311 | ); |
| 312 | |
| 313 | it.effect("uses the known next revision after persisting uploaded references", () => |
| 314 | Effect.gen(function* () { |
| 315 | const message = queuedMessage({ |
| 316 | messageId: "message-new-upload-revision", |
| 317 | text: "upload this file", |
| 318 | fileUri: "file:///documents/t3-composer-attachments/new.pdf", |
| 319 | }); |
| 320 | const uploadedAttachments = message.attachments.map((attachment) => |
| 321 | attachment.type === "file" |
| 322 | ? { |
| 323 | ...attachment, |
| 324 | uploadedAttachmentId: "pending-new-upload", |
| 325 | uploadEnvironmentId: message.environmentId, |
| 326 | } |
| 327 | : attachment, |
| 328 | ); |
| 329 | harness.prepareTurnAttachments.mockImplementationOnce((input) => |
| 330 | Effect.gen(function* () { |
| 331 | expect(yield* input.persistUploadedReferences!(uploadedAttachments)).toBe("persisted"); |
| 332 | return { |
| 333 | status: "ready", |
| 334 | attachments: [], |
| 335 | draftAttachments: uploadedAttachments, |
| 336 | pendingAttachmentIds: ["pending-new-upload"], |
| 337 | } as const; |
| 338 | }), |
| 339 | ); |
| 340 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 341 | const revision = harness.manager.revisionOf(message.messageId); |
| 342 | |
| 343 | const result = yield* prepareQueuedMessageAttachments(message); |
| 344 | |
| 345 | expect(result).toMatchObject({ |
| 346 | status: "ready", |
| 347 | persistedMessage: { attachments: uploadedAttachments }, |
| 348 | deliveryRevision: revision + 1, |
| 349 | }); |
| 350 | expect(harness.manager.revisionOf(message.messageId)).toBe(revision + 1); |
| 351 | }), |
| 352 | ); |
| 353 | |
| 354 | it.effect("does not prepare a payload that was already replaced", () => |
| 355 | Effect.gen(function* () { |
| 356 | const message = queuedMessage({ messageId: "message-stale-before-upload", text: "old" }); |
| 357 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 358 | const edited = { ...message, text: "new" }; |
| 359 | yield* Effect.promise(() => harness.manager.update(edited)); |
| 360 | |
| 361 | expect(yield* prepareQueuedMessageAttachments(message)).toEqual({ |
| 362 | status: "abandoned", |
| 363 | }); |
| 364 | expect(harness.prepareTurnAttachments).not.toHaveBeenCalled(); |
| 365 | expect(remainingMessages()).toEqual([edited]); |
| 366 | }), |
| 367 | ); |
| 368 | }); |
| 369 | |
| 370 | describe("thread outbox drain delivery cleanup", () => { |
| 371 | it.effect( |
| 372 | "drops caught-up acknowledged rows at the next delivery without subscribing to the thread", |
| 373 | () => |
| 374 | Effect.gen(function* () { |
| 375 | const first = queuedMessage({ messageId: "awaiting-echo", text: "Delivered" }); |
| 376 | const second = queuedMessage({ messageId: "next-delivery", text: "Also delivered" }); |
| 377 | yield* Effect.promise(() => harness.manager.enqueue(first)); |
| 378 | yield* Effect.promise(() => harness.manager.enqueue(second)); |
| 379 | |
| 380 | expect( |
| 381 | yield* completeQueuedMessageDelivery( |
| 382 | first, |
| 383 | harness.manager.revisionOf(first.messageId), |
| 384 | 7, |
| 385 | ), |
| 386 | ).toBe("removed"); |
| 387 | expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([ |
| 388 | { ...first, sequence: 7 }, |
| 389 | ]); |
| 390 | |
| 391 | // The thread applied the message, but its bounded window does not hold it. |
| 392 | appAtomRegistry.set(harness.threadState, { |
| 393 | data: Option.some({ messages: [{ id: "unrelated" }] }), |
| 394 | sequence: 7, |
| 395 | }); |
| 396 | expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toHaveLength(1); |
| 397 | |
| 398 | expect( |
| 399 | yield* completeQueuedMessageDelivery( |
| 400 | second, |
| 401 | harness.manager.revisionOf(second.messageId), |
| 402 | 9, |
| 403 | ), |
| 404 | ).toBe("removed"); |
| 405 | expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([ |
| 406 | { ...second, sequence: 9 }, |
| 407 | ]); |
| 408 | }), |
| 409 | ); |
| 410 | |
| 411 | it.effect( |
| 412 | "drops an acknowledged row once the open thread catches up, so a reload cannot resurrect it", |
| 413 | () => |
| 414 | Effect.gen(function* () { |
| 415 | const message = queuedMessage({ messageId: "paged-out-later", text: "Delivered" }); |
| 416 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 417 | yield* completeQueuedMessageDelivery( |
| 418 | message, |
| 419 | harness.manager.revisionOf(message.messageId), |
| 420 | 7, |
| 421 | ); |
| 422 | |
| 423 | pruneCaughtUpAcknowledgedThreadMessages( |
| 424 | scopedThreadKey(message.environmentId, message.threadId), |
| 425 | { |
| 426 | sequence: 6, |
| 427 | messages: [], |
| 428 | }, |
| 429 | ); |
| 430 | expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([ |
| 431 | { ...message, sequence: 7 }, |
| 432 | ]); |
| 433 | |
| 434 | pruneCaughtUpAcknowledgedThreadMessages( |
| 435 | scopedThreadKey(message.environmentId, message.threadId), |
| 436 | { |
| 437 | sequence: 7, |
| 438 | messages: [], |
| 439 | }, |
| 440 | ); |
| 441 | expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([]); |
| 442 | }), |
| 443 | ); |
| 444 | |
| 445 | it.effect("removes an acknowledged outbox item even when the sign-out archive write fails", () => |
| 446 | Effect.gen(function* () { |
| 447 | const message = queuedMessage({ messageId: "archive-write-failure", text: "Delivered" }); |
| 448 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 449 | yield* Effect.promise(() => |
| 450 | composerDrafts.archiveCloudComposerDrafts("account-a", new Set([message.environmentId]), [ |
| 451 | message.environmentId, |
| 452 | ]), |
| 453 | ); |
| 454 | harness.draftFile.setWriteError(new Error("Draft storage unavailable")); |
| 455 | |
| 456 | expect( |
| 457 | yield* completeQueuedMessageDelivery( |
| 458 | message, |
| 459 | harness.manager.revisionOf(message.messageId), |
| 460 | undefined, |
| 461 | ), |
| 462 | ).toBe("removed"); |
| 463 | expect(remainingMessages()).toEqual([]); |
| 464 | |
| 465 | harness.draftFile.setWriteError(null); |
| 466 | yield* Effect.promise(() => composerDrafts.flushComposerDrafts()); |
| 467 | appAtomRegistry.set(composerDrafts.composerCloudDraftsAtom, { |
| 468 | accountId: null, |
| 469 | signedOut: {}, |
| 470 | }); |
| 471 | composerDrafts.resetComposerDraftsLoadState(); |
| 472 | yield* Effect.promise(() => composerDrafts.restoreCloudComposerDrafts("account-a")); |
| 473 | expect(remainingMessages()).toEqual([]); |
| 474 | }), |
| 475 | ); |
| 476 | |
| 477 | it.effect.each([false, true])( |
| 478 | "does not restore a message delivered after the sign-out snapshot (outbox already cleared: %s)", |
| 479 | (cleared) => |
| 480 | Effect.gen(function* () { |
| 481 | const message = queuedMessage({ |
| 482 | messageId: "delivered-during-sign-out", |
| 483 | text: "Already delivered", |
| 484 | }); |
| 485 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 486 | const deliveryRevision = harness.manager.revisionOf(message.messageId); |
| 487 | yield* Effect.promise(() => |
| 488 | composerDrafts.archiveCloudComposerDrafts("account-a", new Set([message.environmentId]), [ |
| 489 | message.environmentId, |
| 490 | ]), |
| 491 | ); |
| 492 | expect( |
| 493 | appAtomRegistry.get(composerDrafts.composerCloudDraftsAtom).signedOut["account-a"] |
| 494 | ?.queuedMessages, |
| 495 | ).toEqual([message]); |
| 496 | |
| 497 | if (cleared) { |
| 498 | yield* Effect.promise(() => harness.manager.clearEnvironment(message.environmentId)); |
| 499 | } |
| 500 | expect(yield* completeQueuedMessageDelivery(message, deliveryRevision, undefined)).toBe( |
| 501 | cleared ? "edited" : "removed", |
| 502 | ); |
| 503 | |
| 504 | appAtomRegistry.set(composerDrafts.composerCloudDraftsAtom, { |
| 505 | accountId: null, |
| 506 | signedOut: {}, |
| 507 | }); |
| 508 | composerDrafts.resetComposerDraftsLoadState(); |
| 509 | yield* Effect.promise(() => composerDrafts.restoreCloudComposerDrafts("account-a")); |
| 510 | expect(remainingMessages()).toEqual([]); |
| 511 | }), |
| 512 | ); |
| 513 | |
| 514 | it.effect("preserves an archived edit when an older payload finishes delivery", () => |
| 515 | Effect.gen(function* () { |
| 516 | const message = queuedMessage({ messageId: "edited-during-sign-out", text: "Original" }); |
| 517 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 518 | const deliveryRevision = harness.manager.revisionOf(message.messageId); |
| 519 | const edited = { ...message, text: "Keep this edit" }; |
| 520 | yield* Effect.promise(() => harness.manager.update(edited)); |
| 521 | yield* Effect.promise(() => |
| 522 | composerDrafts.archiveCloudComposerDrafts("account-a", new Set([message.environmentId]), [ |
| 523 | message.environmentId, |
| 524 | ]), |
| 525 | ); |
| 526 | yield* Effect.promise(() => harness.manager.clearEnvironment(message.environmentId)); |
| 527 | expect(yield* completeQueuedMessageDelivery(message, deliveryRevision, undefined)).toBe( |
| 528 | "edited", |
| 529 | ); |
| 530 | yield* Effect.promise(() => composerDrafts.restoreCloudComposerDrafts("account-a")); |
| 531 | expect(remainingMessages()).toEqual([edited]); |
| 532 | }), |
| 533 | ); |
| 534 | |
| 535 | it.effect("retries only cleanup after an acknowledged send removal fails", () => |
| 536 | Effect.gen(function* () { |
| 537 | const message = queuedMessage({ messageId: "message-acknowledged", text: "delivered" }); |
| 538 | const acknowledged = new Set([message.messageId]); |
| 539 | harness.removeOutboxMessage.mockRejectedValueOnce(new Error("storage unavailable")); |
| 540 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 541 | |
| 542 | expect(yield* handled(removeAcknowledgedExistingThreadMessage(message, acknowledged))).toBe( |
| 543 | false, |
| 544 | ); |
| 545 | expect(remainingMessages()).toEqual([message]); |
| 546 | expect(acknowledged).toEqual(new Set([message.messageId])); |
| 547 | |
| 548 | expect(yield* handled(removeAcknowledgedExistingThreadMessage(message, acknowledged))).toBe( |
| 549 | true, |
| 550 | ); |
| 551 | expect(remainingMessages()).toEqual([]); |
| 552 | expect(acknowledged).toEqual(new Set()); |
| 553 | }), |
| 554 | ); |
| 555 | |
| 556 | it.effect( |
| 557 | "keeps an edited message and its files when delivery cleanup loses the revision race", |
| 558 | () => |
| 559 | Effect.gen(function* () { |
| 560 | const message = queuedMessage({ |
| 561 | messageId: "message-edited", |
| 562 | text: "original", |
| 563 | fileUri: "file:///documents/t3-composer-attachments/report.pdf", |
| 564 | }); |
| 565 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 566 | const deliveryRevision = harness.manager.revisionOf(message.messageId); |
| 567 | const edited = { ...message, text: "edited while the turn delivered" }; |
| 568 | yield* Effect.promise(() => harness.manager.update(edited)); |
| 569 | |
| 570 | expect(yield* completeQueuedMessageDelivery(message, deliveryRevision, undefined)).toBe( |
| 571 | "edited", |
| 572 | ); |
| 573 | |
| 574 | expect(remainingMessages()).toEqual([edited]); |
| 575 | expect(harness.removePersistedFile).not.toHaveBeenCalled(); |
| 576 | }), |
| 577 | ); |
| 578 | |
| 579 | it.effect("removes the delivered message when no edit was accepted", () => |
| 580 | Effect.gen(function* () { |
| 581 | const message = queuedMessage({ messageId: "message-clean", text: "hello" }); |
| 582 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 583 | const deliveryRevision = harness.manager.revisionOf(message.messageId); |
| 584 | |
| 585 | expect(yield* completeQueuedMessageDelivery(message, deliveryRevision, undefined)).toBe( |
| 586 | "removed", |
| 587 | ); |
| 588 | |
| 589 | expect(remainingMessages()).toEqual([]); |
| 590 | expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([message]); |
| 591 | }), |
| 592 | ); |
| 593 | |
| 594 | it.effect("keeps a delivered message when its editor opens during storage removal", () => |
| 595 | Effect.gen(function* () { |
| 596 | const message = queuedMessage({ |
| 597 | messageId: "message-editor-removal-race", |
| 598 | text: "keep editor changes", |
| 599 | fileUri: "file:///documents/t3-composer-attachments/editor-race.pdf", |
| 600 | }); |
| 601 | const removeStarted = Promise.withResolvers<void>(); |
| 602 | const removeBarrier = Promise.withResolvers<void>(); |
| 603 | harness.removeOutboxMessage.mockImplementationOnce(async () => { |
| 604 | removeStarted.resolve(); |
| 605 | await removeBarrier.promise; |
| 606 | }); |
| 607 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 608 | const deliveryRevision = harness.manager.revisionOf(message.messageId); |
| 609 | |
| 610 | const cleanup = yield* Effect.forkChild( |
| 611 | completeQueuedMessageDelivery(message, deliveryRevision, undefined), |
| 612 | { startImmediately: true }, |
| 613 | ); |
| 614 | yield* Effect.promise(() => removeStarted.promise); |
| 615 | appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true }); |
| 616 | removeBarrier.resolve(); |
| 617 | |
| 618 | expect(yield* Fiber.join(cleanup)).toBe("edited"); |
| 619 | expect(remainingMessages()).toEqual([message]); |
| 620 | expect(harness.removePersistedFile).not.toHaveBeenCalled(); |
| 621 | }), |
| 622 | ); |
| 623 | }); |
| 624 | |
| 625 | describe("thread outbox delivered creation recovery", () => { |
| 626 | it.effect("keeps an edit accepted while the older payload is persisted to the draft", () => |
| 627 | Effect.gen(function* () { |
| 628 | const message = queuedMessage({ |
| 629 | messageId: "message-recovery-race", |
| 630 | text: "original queued text", |
| 631 | fileUri: "file:///documents/t3-composer-attachments/report.pdf", |
| 632 | }); |
| 633 | const originalMergeComposerDraftContent = composerDrafts.mergeComposerDraftContent; |
| 634 | const mergeCompleted = Promise.withResolvers<void>(); |
| 635 | const releaseRecovery = Promise.withResolvers<void>(); |
| 636 | const mergeSpy = vi |
| 637 | .spyOn(composerDrafts, "mergeComposerDraftContent") |
| 638 | .mockImplementation(async (draftKey, content) => { |
| 639 | const result = await originalMergeComposerDraftContent(draftKey, content); |
| 640 | mergeCompleted.resolve(); |
| 641 | await releaseRecovery.promise; |
| 642 | return result; |
| 643 | }); |
| 644 | |
| 645 | try { |
| 646 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 647 | const recovery = yield* Effect.forkChild( |
| 648 | handled(recoverEditedCreationAfterDelivery(message)), |
| 649 | { startImmediately: true }, |
| 650 | ); |
| 651 | yield* Effect.promise(() => mergeCompleted.promise); |
| 652 | |
| 653 | const newer = { ...message, text: "edited while recovery persisted the draft" }; |
| 654 | yield* Effect.promise(() => harness.manager.update(newer)); |
| 655 | |
| 656 | releaseRecovery.resolve(); |
| 657 | expect(yield* Fiber.join(recovery)).toBe(false); |
| 658 | |
| 659 | expect(remainingMessages()).toEqual([newer]); |
| 660 | expect( |
| 661 | composerDrafts.getComposerDraftSnapshot(`${message.environmentId}:${message.threadId}`), |
| 662 | ).toMatchObject({ text: message.text, attachments: [] }); |
| 663 | expect(harness.removePersistedFile).not.toHaveBeenCalled(); |
| 664 | } finally { |
| 665 | releaseRecovery.resolve(); |
| 666 | mergeSpy.mockRestore(); |
| 667 | } |
| 668 | }), |
| 669 | ); |
| 670 | |
| 671 | it.effect("leaves recovery to an editor that opens while the draft persists", () => |
| 672 | Effect.gen(function* () { |
| 673 | const message = queuedMessage({ |
| 674 | messageId: "message-recovery-editor", |
| 675 | text: "recover this text", |
| 676 | fileUri: "file:///documents/t3-composer-attachments/editor.pdf", |
| 677 | }); |
| 678 | const originalMergeComposerDraftContent = composerDrafts.mergeComposerDraftContent; |
| 679 | const mergeCompleted = Promise.withResolvers<void>(); |
| 680 | const releaseRecovery = Promise.withResolvers<void>(); |
| 681 | const mergeSpy = vi |
| 682 | .spyOn(composerDrafts, "mergeComposerDraftContent") |
| 683 | .mockImplementation(async (draftKey, content) => { |
| 684 | const result = await originalMergeComposerDraftContent(draftKey, content); |
| 685 | mergeCompleted.resolve(); |
| 686 | await releaseRecovery.promise; |
| 687 | return result; |
| 688 | }); |
| 689 | |
| 690 | try { |
| 691 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 692 | const recovery = yield* Effect.forkChild( |
| 693 | handled(recoverEditedCreationAfterDelivery(message)), |
| 694 | { startImmediately: true }, |
| 695 | ); |
| 696 | yield* Effect.promise(() => mergeCompleted.promise); |
| 697 | appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true }); |
| 698 | |
| 699 | releaseRecovery.resolve(); |
| 700 | expect(yield* Fiber.join(recovery)).toBe(true); |
| 701 | |
| 702 | expect(remainingMessages()).toEqual([message]); |
| 703 | expect( |
| 704 | composerDrafts.getComposerDraftSnapshot(`${message.environmentId}:${message.threadId}`), |
| 705 | ).toMatchObject({ text: message.text, attachments: [] }); |
| 706 | expect(harness.removePersistedFile).not.toHaveBeenCalled(); |
| 707 | } finally { |
| 708 | releaseRecovery.resolve(); |
| 709 | mergeSpy.mockRestore(); |
| 710 | } |
| 711 | }), |
| 712 | ); |
| 713 | |
| 714 | it.effect("retries a failed removal without duplicating recovered draft content", () => |
| 715 | Effect.gen(function* () { |
| 716 | const message = queuedMessage({ |
| 717 | messageId: "message-recovery-removal", |
| 718 | text: "recover once", |
| 719 | fileUri: "file:///documents/t3-composer-attachments/retry.pdf", |
| 720 | }); |
| 721 | const draftKey = `${message.environmentId}:${message.threadId}`; |
| 722 | const removeSpy = vi |
| 723 | .spyOn(harness.manager, "remove") |
| 724 | .mockRejectedValueOnce(new Error("storage unavailable")); |
| 725 | |
| 726 | try { |
| 727 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 728 | |
| 729 | expect(yield* handled(recoverEditedCreationAfterDelivery(message))).toBe(false); |
| 730 | expect(remainingMessages()).toEqual([message]); |
| 731 | |
| 732 | expect(yield* handled(recoverEditedCreationAfterDelivery(message))).toBe(true); |
| 733 | |
| 734 | const draft = composerDrafts.getComposerDraftSnapshot(draftKey); |
| 735 | expect(draft.text).toBe(message.text); |
| 736 | expect(draft.attachments).toEqual(message.attachments); |
| 737 | expect(remainingMessages()).toEqual([]); |
| 738 | expect(harness.removePersistedFile).not.toHaveBeenCalled(); |
| 739 | } finally { |
| 740 | removeSpy.mockRestore(); |
| 741 | } |
| 742 | }), |
| 743 | ); |
| 744 | |
| 745 | it.effect("keeps the queue entry when the recovered draft cannot persist", () => |
| 746 | Effect.gen(function* () { |
| 747 | const message = queuedMessage({ |
| 748 | messageId: "message-recovery-persistence", |
| 749 | text: "recover after persistence returns", |
| 750 | }); |
| 751 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 752 | harness.draftFile.setWriteError(new Error("disk full")); |
| 753 | |
| 754 | expect(yield* handled(recoverEditedCreationAfterDelivery(message))).toBe(false); |
| 755 | |
| 756 | expect(remainingMessages()).toEqual([message]); |
| 757 | }), |
| 758 | ); |
| 759 | }); |
| 760 | |
| 761 | describe("thread outbox recovery rollback", () => { |
| 762 | it("reopens a rejected task with setup edits and every attachment, even above the send cap", async () => { |
| 763 | const message = queuedMessage({ messageId: "failed-setup", text: "Original prompt" }); |
| 764 | const sourceKey = `${message.environmentId}:${message.threadId}`; |
| 765 | const targetKey = "new-task:restored-failed-setup"; |
| 766 | const files = Array.from( |
| 767 | { length: 10 }, |
| 768 | (_, index) => |
| 769 | queuedMessage({ |
| 770 | messageId: `attachment-${index}`, |
| 771 | text: "", |
| 772 | fileUri: `file:///file-${index}`, |
| 773 | }).attachments[0]!, |
| 774 | ); |
| 775 | appAtomRegistry.set(composerDrafts.composerDraftsAtom, { |
| 776 | [targetKey]: { text: message.text, attachments: files.slice(0, 8) }, |
| 777 | [sourceKey]: { text: "Please include tests", attachments: files.slice(8) }, |
| 778 | }); |
| 779 | await recoverFailedThreadDraft(message); |
| 780 | expect(composerDrafts.getComposerDraftSnapshot(targetKey)).toMatchObject({ |
| 781 | text: "Original prompt\n\nPlease include tests", |
| 782 | attachments: files, |
| 783 | }); |
| 784 | expect(composerDrafts.getComposerDraftSnapshot(sourceKey)).toMatchObject({ |
| 785 | text: "", |
| 786 | attachments: [], |
| 787 | }); |
| 788 | await recoverFailedThreadDraft(message); |
| 789 | expect(composerDrafts.getComposerDraftSnapshot(targetKey).text).toBe( |
| 790 | "Original prompt\n\nPlease include tests", |
| 791 | ); |
| 792 | }); |
| 793 | |
| 794 | it("keeps a late attachment and its reference when recovery fills the context limit", async () => { |
| 795 | const message: QueuedThreadMessage = { |
| 796 | ...queuedMessage({ messageId: "failed-full-context", text: "Original prompt" }), |
| 797 | modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" }, |
| 798 | creation: { |
| 799 | projectId: ProjectId.make("project-1"), |
| 800 | workspaceMode: "local", |
| 801 | branch: null, |
| 802 | worktreePath: null, |
| 803 | }, |
| 804 | }; |
| 805 | const sourceKey = `${message.environmentId}:${message.threadId}`; |
| 806 | const targetKey = "new-task:restored-failed-full-context"; |
| 807 | await composerDrafts.waitForComposerDraftsLoaded(); |
| 808 | const contextDraft = (start: number) => { |
| 809 | const records = Array.from({ length: 100 }, (_, index) => ({ |
| 810 | version: 1 as const, |
| 811 | contextId: ComposerContextId.make(`skill-${start + index}`), |
| 812 | kind: "skill" as const, |
| 813 | label: "Skill", |
| 814 | name: "skill", |
| 815 | })); |
| 816 | return { |
| 817 | text: records |
| 818 | .map((record) => `[Skill](t3-context://v1/skill/${record.contextId})`) |
| 819 | .join(" "), |
| 820 | context: { version: 1 as const, records }, |
| 821 | attachments: [], |
| 822 | }; |
| 823 | }; |
| 824 | appAtomRegistry.set(composerDrafts.composerDraftsAtom, { |
| 825 | [targetKey]: contextDraft(0), |
| 826 | [sourceKey]: contextDraft(100), |
| 827 | }); |
| 828 | const saving = Promise.withResolvers<void>(); |
| 829 | const resume = Promise.withResolvers<void>(); |
| 830 | const write = harness.draftFile.File.prototype.write; |
| 831 | const writeSpy = vi |
| 832 | .spyOn(harness.draftFile.File.prototype, "write") |
| 833 | .mockImplementationOnce(async function (value) { |
| 834 | write(value); |
| 835 | saving.resolve(); |
| 836 | await resume.promise; |
| 837 | }); |
| 838 | const attachment = { |
| 839 | id: "late-paste", |
| 840 | type: "image" as const, |
| 841 | name: "pasted.png", |
| 842 | mimeType: "image/png", |
| 843 | sizeBytes: 1, |
| 844 | dataUrl: "data:image/png;base64,AA==", |
| 845 | previewUri: "data:image/png;base64,AA==", |
| 846 | }; |
| 847 | try { |
| 848 | const recovering = recoverFailedThreadDraft(message); |
| 849 | await saving.promise; |
| 850 | composerDrafts.appendComposerDraftAttachments(sourceKey, [attachment], { |
| 851 | appendReference: true, |
| 852 | }); |
| 853 | resume.resolve(); |
| 854 | await recovering; |
| 855 | const restored = composerDrafts.getComposerDraftSnapshot(targetKey); |
| 856 | expect(restored.attachments).toContainEqual(attachment); |
| 857 | expect(restored.context?.records).toHaveLength(201); |
| 858 | const imageRecord = restored.context?.records.find( |
| 859 | (record) => "attachmentId" in record && record.attachmentId === attachment.id, |
| 860 | ); |
| 861 | expect(imageRecord).toBeDefined(); |
| 862 | expect(restored.text).toContain(`/${imageRecord!.contextId})`); |
| 863 | expect(composerDrafts.getComposerDraftSnapshot(sourceKey).attachments).toEqual([]); |
| 864 | } finally { |
| 865 | resume.resolve(); |
| 866 | writeSpy.mockRestore(); |
| 867 | await composerDrafts.flushComposerDrafts(); |
| 868 | } |
| 869 | }); |
| 870 | |
| 871 | it("cancels a paste that finishes preparing after recovery returns", async () => { |
| 872 | const message = queuedMessage({ messageId: "failed-unfinished-paste", text: "Original" }); |
| 873 | const sourceKey = `${message.environmentId}:${message.threadId}`; |
| 874 | appAtomRegistry.set(composerDrafts.composerDraftsAtom, { |
| 875 | [sourceKey]: { text: "Follow-up", attachments: [] }, |
| 876 | }); |
| 877 | const paste = startComposerDraftOperation(sourceKey); |
| 878 | try { |
| 879 | await recoverFailedThreadDraft(message); |
| 880 | expect(paste.signal.aborted).toBe(true); |
| 881 | } finally { |
| 882 | paste.finish(); |
| 883 | await composerDrafts.flushComposerDrafts(); |
| 884 | } |
| 885 | }); |
| 886 | |
| 887 | it("keeps setup edits recoverable when saving their recovery draft fails", async () => { |
| 888 | const message = queuedMessage({ messageId: "failed-save", text: "Original prompt" }); |
| 889 | const sourceKey = `${message.environmentId}:${message.threadId}`; |
| 890 | appAtomRegistry.set(composerDrafts.composerDraftsAtom, { |
| 891 | "new-task:restored-failed-save": { text: message.text, attachments: [] }, |
| 892 | [sourceKey]: { text: "Follow-up", attachments: [] }, |
| 893 | }); |
| 894 | harness.draftFile.setWriteError(new Error("disk full")); |
| 895 | await expect(recoverFailedThreadDraft(message)).rejects.toThrow("Composer draft persistence"); |
| 896 | expect(composerDrafts.getComposerDraftSnapshot(sourceKey).text).toBe("Follow-up"); |
| 897 | harness.draftFile.setWriteError(null); |
| 898 | await recoverFailedThreadDraft(message); |
| 899 | expect(composerDrafts.getComposerDraftSnapshot("new-task:restored-failed-save").text).toBe( |
| 900 | "Original prompt\n\nFollow-up", |
| 901 | ); |
| 902 | }); |
| 903 | |
| 904 | it.effect("restores a rejected new task as its own draft for the project", () => |
| 905 | Effect.gen(function* () { |
| 906 | const message: QueuedThreadMessage = { |
| 907 | ...queuedMessage({ messageId: "message-creation-restore", text: "new task text" }), |
| 908 | modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" }, |
| 909 | creation: { |
| 910 | projectId: ProjectId.make("project-1"), |
| 911 | workspaceMode: "local", |
| 912 | branch: null, |
| 913 | worktreePath: null, |
| 914 | }, |
| 915 | }; |
| 916 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 917 | |
| 918 | expect(yield* restoreRejectedQueuedMessage(message, "rejected by server")).toBe("restored"); |
| 919 | |
| 920 | expect( |
| 921 | composerDrafts.getComposerDraftSnapshot(`new-task:restored-${message.messageId}`), |
| 922 | ).toMatchObject({ |
| 923 | text: message.text, |
| 924 | attachments: message.attachments, |
| 925 | modelSelection: message.modelSelection, |
| 926 | project: { |
| 927 | environmentId: message.environmentId, |
| 928 | projectId: message.creation!.projectId, |
| 929 | createdAt: message.createdAt, |
| 930 | }, |
| 931 | }); |
| 932 | expect(remainingMessages()).toEqual([]); |
| 933 | expect(appAtomRegistry.get(threadComposerErrorsAtom)).toEqual({}); |
| 934 | expect( |
| 935 | appAtomRegistry.get(pendingThreadCreationOutcomesAtom)[ |
| 936 | `${message.environmentId}:${message.threadId}` |
| 937 | ], |
| 938 | ).toEqual({ kind: "failed", message, reason: "rejected by server" }); |
| 939 | }), |
| 940 | ); |
| 941 | |
| 942 | it.effect("keeps the draft unchanged when a standalone goal command is rejected", () => |
| 943 | Effect.gen(function* () { |
| 944 | const message: QueuedThreadMessage = { |
| 945 | ...queuedMessage({ messageId: "goal-rejected", text: "/goal clear" }), |
| 946 | restoreToDraft: false, |
| 947 | modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" }, |
| 948 | runtimeMode: "full-access", |
| 949 | }; |
| 950 | const threadKey = `${message.environmentId}:${message.threadId}`; |
| 951 | appAtomRegistry.set(composerDrafts.composerDraftsAtom, { |
| 952 | [threadKey]: { text: "Keep my draft", attachments: [], runtimeMode: "approval-required" }, |
| 953 | }); |
| 954 | const draft = composerDrafts.getComposerDraftSnapshot(threadKey); |
| 955 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 956 | expect(yield* restoreRejectedQueuedMessage(message, "rejected")).toBe("restored"); |
| 957 | expect(composerDrafts.getComposerDraftSnapshot(threadKey)).toEqual(draft); |
| 958 | expect(remainingMessages()).toEqual([]); |
| 959 | expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]).toEqual({ |
| 960 | message: "rejected", |
| 961 | messageId: message.messageId, |
| 962 | }); |
| 963 | }), |
| 964 | ); |
| 965 | |
| 966 | it.effect("does not record a creation outcome for a rejected follow-up message", () => |
| 967 | Effect.gen(function* () { |
| 968 | const message = queuedMessage({ messageId: "message-followup-restore", text: "follow up" }); |
| 969 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 970 | |
| 971 | expect(yield* restoreRejectedQueuedMessage(message, "rejected")).toBe("restored"); |
| 972 | |
| 973 | expect(appAtomRegistry.get(pendingThreadCreationOutcomesAtom)).toEqual({}); |
| 974 | expect( |
| 975 | appAtomRegistry.get(threadComposerErrorsAtom)[ |
| 976 | `${message.environmentId}:${message.threadId}` |
| 977 | ], |
| 978 | ).toEqual({ message: "rejected", messageId: message.messageId }); |
| 979 | }), |
| 980 | ); |
| 981 | |
| 982 | it.effect("leaves no error when the restored text is resent before recovery finishes", () => |
| 983 | Effect.gen(function* () { |
| 984 | const message = queuedMessage({ messageId: "message-resent", text: "resend me" }); |
| 985 | const threadKey = `${message.environmentId}:${message.threadId}`; |
| 986 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 987 | const unsubscribe = appAtomRegistry.subscribe(composerDrafts.composerDraftsAtom, (drafts) => { |
| 988 | if (drafts[threadKey]?.text === "resend me") { |
| 989 | unsubscribe(); |
| 990 | clearThreadComposerError(threadKey); |
| 991 | void composerDrafts.clearComposerDraftContent(threadKey); |
| 992 | } |
| 993 | }); |
| 994 | |
| 995 | expect(yield* restoreRejectedQueuedMessage(message, "rejected")).toBe("restored"); |
| 996 | |
| 997 | expect(appAtomRegistry.get(threadComposerErrorsAtom)).toEqual({}); |
| 998 | }), |
| 999 | ); |
| 1000 | |
| 1001 | it.effect("withdraws the error when an edit makes the recovery back out", () => |
| 1002 | Effect.gen(function* () { |
| 1003 | const message = queuedMessage({ messageId: "message-edited-mid-recovery", text: "edit me" }); |
| 1004 | const threadKey = `${message.environmentId}:${message.threadId}`; |
| 1005 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 1006 | const unsubscribe = appAtomRegistry.subscribe(composerDrafts.composerDraftsAtom, (drafts) => { |
| 1007 | if (drafts[threadKey]?.text === "edit me") { |
| 1008 | unsubscribe(); |
| 1009 | appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true }); |
| 1010 | } |
| 1011 | }); |
| 1012 | |
| 1013 | expect(yield* restoreRejectedQueuedMessage(message, "rejected")).toBe("deferred"); |
| 1014 | |
| 1015 | expect(appAtomRegistry.get(threadComposerErrorsAtom)).toEqual({}); |
| 1016 | expect(remainingMessages()).toEqual([message]); |
| 1017 | }), |
| 1018 | ); |
| 1019 | |
| 1020 | it.effect("rolls a failed recovery merge back so the retry cannot duplicate the text", () => |
| 1021 | Effect.gen(function* () { |
| 1022 | const message = queuedMessage({ messageId: "message-restore", text: "queued text" }); |
| 1023 | const draftKey = `${message.environmentId}:${message.threadId}`; |
| 1024 | appAtomRegistry.set(composerDrafts.composerDraftsAtom, { |
| 1025 | [draftKey]: { text: "typed offline", attachments: [] }, |
| 1026 | }); |
| 1027 | yield* Effect.promise(() => harness.manager.enqueue(message)); |
| 1028 | |
| 1029 | harness.draftFile.setWriteError(new Error("disk full")); |
| 1030 | expect(yield* restoreRejectedQueuedMessage(message, "too large")).toBe("retry"); |
| 1031 | |
| 1032 | expect(composerDrafts.getComposerDraftSnapshot(draftKey).text).toBe("typed offline"); |
| 1033 | expect(remainingMessages()).toEqual([message]); |
| 1034 | |
| 1035 | harness.draftFile.setWriteError(null); |
| 1036 | expect(yield* restoreRejectedQueuedMessage(message, "too large")).toBe("restored"); |
| 1037 | |
| 1038 | expect(composerDrafts.getComposerDraftSnapshot(draftKey).text).toBe( |
| 1039 | "typed offline\n\nqueued text", |
| 1040 | ); |
| 1041 | expect(remainingMessages()).toEqual([]); |
| 1042 | expect(appAtomRegistry.get(threadComposerErrorsAtom)[draftKey]?.message).toBe("too large"); |
| 1043 | }), |
| 1044 | ); |
| 1045 | }); |