The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { ThreadStructure } from "@t3tools/client-runtime/state/shell"; |
| 2 | import { |
| 3 | EnvironmentId, |
| 4 | ChatAttachmentId, |
| 5 | MessageId, |
| 6 | RunId, |
| 7 | ThreadId, |
| 8 | type ScopedThreadRef, |
| 9 | } from "@t3tools/contracts"; |
| 10 | import { useImperativeHandle, type RefObject } from "react"; |
| 11 | import { describe, expect, it, vi } from "vite-plus/test"; |
| 12 | import { |
| 13 | ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, |
| 14 | threadContextRecord, |
| 15 | } from "@t3tools/shared/composerContextReferences"; |
| 16 | import { toastManager } from "../ui/toast"; |
| 17 | |
| 18 | import { act, render } from "../../../test/render"; |
| 19 | import { useComposerDraftStore, useComposerThreadDraft } from "../../composerDraftStore"; |
| 20 | import { formatInlineContextReference } from "../../lib/composerContextReferences"; |
| 21 | import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "../../lib/terminalContext"; |
| 22 | import { |
| 23 | environmentContextRecord, |
| 24 | environmentContextReference, |
| 25 | threadContextReference, |
| 26 | } from "../../lib/composerContextRecords"; |
| 27 | import { deriveComposerSendState } from "../ChatView.logic"; |
| 28 | import { ComposerPrimaryActions } from "./ComposerPrimaryActions"; |
| 29 | import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry"; |
| 30 | import { useQueuedRunEdit } from "./useQueuedRunEdit"; |
| 31 | import { readAttachmentUpload, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue"; |
| 32 | |
| 33 | interface RunStatus { |
| 34 | readonly id: RunId; |
| 35 | readonly status: string; |
| 36 | readonly activeAttemptId?: string; |
| 37 | } |
| 38 | |
| 39 | const mocks = await vi.hoisted(async () => { |
| 40 | const { Atom } = await import("effect/reactivity"); |
| 41 | return { |
| 42 | editQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" | "Failure" }>>(), |
| 43 | promoteQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" }>>(), |
| 44 | promoteCommand: {}, |
| 45 | // The projection's runs per thread, written by each test to stand in for the server. |
| 46 | threadRuns: Atom.family((_key: string) => |
| 47 | Atom.make<ReadonlyArray<RunStatus> | null>(null).pipe(Atom.keepAlive), |
| 48 | ), |
| 49 | }; |
| 50 | }); |
| 51 | |
| 52 | vi.mock("../../state/use-atom-command", () => ({ |
| 53 | useAtomCommand: (command: unknown) => |
| 54 | command === mocks.promoteCommand ? mocks.promoteQueuedRun : mocks.editQueuedRun, |
| 55 | })); |
| 56 | |
| 57 | vi.mock("../../hooks/useSettings", () => ({ |
| 58 | useEnvironmentIdentificationMode: () => "none", |
| 59 | })); |
| 60 | |
| 61 | const runsKey = (ref: ScopedThreadRef) => `${ref.environmentId}:${ref.threadId}`; |
| 62 | |
| 63 | vi.mock("../../state/threads", async () => { |
| 64 | const { Atom } = await import("effect/reactivity"); |
| 65 | const key = (ref: ScopedThreadRef) => `${ref.environmentId}:${ref.threadId}`; |
| 66 | return { |
| 67 | threadEnvironment: { |
| 68 | snapshotAtom: () => Atom.make(null), |
| 69 | editQueuedRun: {}, |
| 70 | promoteQueuedRun: mocks.promoteCommand, |
| 71 | }, |
| 72 | environmentThreadDetails: { |
| 73 | statusAtom: () => Atom.make("ready"), |
| 74 | quietThreadAtom: (ref: ScopedThreadRef) => |
| 75 | Atom.make((get) => { |
| 76 | const runs = get(mocks.threadRuns(key(ref))); |
| 77 | if (runs === null) return null; |
| 78 | // A Claude-like session whose running turn takes steering. |
| 79 | return { |
| 80 | projection: { |
| 81 | thread: { id: ref.threadId, activeProviderThreadId: null }, |
| 82 | runs, |
| 83 | messages: [], |
| 84 | providerThreads: [], |
| 85 | providerSessions: [ |
| 86 | { |
| 87 | id: "session", |
| 88 | status: "running", |
| 89 | capabilities: { turns: { supportsActiveSteering: true } }, |
| 90 | }, |
| 91 | ], |
| 92 | providerTurns: runs.flatMap((run) => |
| 93 | run.activeAttemptId |
| 94 | ? [{ runAttemptId: run.activeAttemptId, status: "running" }] |
| 95 | : [], |
| 96 | ), |
| 97 | }, |
| 98 | }; |
| 99 | }), |
| 100 | }, |
| 101 | environmentThreadShells: { |
| 102 | threadShellAtom: () => Atom.make(null), |
| 103 | }, |
| 104 | }; |
| 105 | }); |
| 106 | |
| 107 | const ENV = EnvironmentId.make("env-1"); |
| 108 | const THREAD_A: ScopedThreadRef = { environmentId: ENV, threadId: ThreadId.make("thread-a") }; |
| 109 | const THREAD_B: ScopedThreadRef = { environmentId: ENV, threadId: ThreadId.make("thread-b") }; |
| 110 | const RUN = RunId.make("run-1"); |
| 111 | |
| 112 | type HookResult = ReturnType<typeof useQueuedRunEdit>; |
| 113 | |
| 114 | function projection(runs: ReadonlyArray<RunStatus>, messages: ReadonlyArray<unknown>) { |
| 115 | return { runs, messages } as unknown as ThreadStructure; |
| 116 | } |
| 117 | |
| 118 | function setRuns(ref: ScopedThreadRef, status: string) { |
| 119 | appAtomRegistry.set(mocks.threadRuns(runsKey(ref)), [{ id: RUN, status }]); |
| 120 | } |
| 121 | |
| 122 | function Harness(props: { |
| 123 | readonly threadRef: ScopedThreadRef; |
| 124 | readonly runStatus: string; |
| 125 | readonly hookRef: RefObject<HookResult | null>; |
| 126 | readonly messages: ReadonlyArray<unknown>; |
| 127 | }) { |
| 128 | const result = useQueuedRunEdit({ |
| 129 | environmentId: ENV, |
| 130 | routeThreadRef: props.threadRef, |
| 131 | threadDraftTarget: props.threadRef, |
| 132 | activeThreadId: props.threadRef.threadId, |
| 133 | serverProjection: projection([{ id: RUN, status: props.runStatus }], props.messages), |
| 134 | promptRef: { current: "" }, |
| 135 | composerRef: { current: null }, |
| 136 | }); |
| 137 | useImperativeHandle(props.hookRef, () => result); |
| 138 | const draft = useComposerThreadDraft(result.draftTarget); |
| 139 | const sendState = deriveComposerSendState({ |
| 140 | prompt: draft.prompt, |
| 141 | imageCount: draft.images.length + draft.files.length, |
| 142 | existingAttachmentCount: result.editingAttachments?.length ?? 0, |
| 143 | terminalContexts: draft.terminalContexts, |
| 144 | }); |
| 145 | return result.isEditing ? ( |
| 146 | <ComposerPrimaryActions |
| 147 | compact={false} |
| 148 | canOperateThread |
| 149 | pendingAction={null} |
| 150 | isRunning={false} |
| 151 | canInterrupt={false} |
| 152 | isSendBusy={result.isSaving} |
| 153 | sendDisabledReason={null} |
| 154 | isEnvironmentUnavailable={false} |
| 155 | isPreparingWorktree={false} |
| 156 | hasSendableContent={sendState.hasSendableContent} |
| 157 | isEditingQueuedMessage |
| 158 | onSubmitMessage={() => void result.saveEdit(savedContent(draft.prompt), () => {})} |
| 159 | onPreviousPendingQuestion={() => {}} |
| 160 | onInterrupt={() => {}} |
| 161 | /> |
| 162 | ) : null; |
| 163 | } |
| 164 | |
| 165 | function view( |
| 166 | threadRef: ScopedThreadRef, |
| 167 | runStatus: string, |
| 168 | hook: { current: HookResult | null }, |
| 169 | messages: ReadonlyArray<unknown> = [], |
| 170 | ) { |
| 171 | return ( |
| 172 | <AppAtomRegistryProvider> |
| 173 | <Harness threadRef={threadRef} runStatus={runStatus} hookRef={hook} messages={messages} /> |
| 174 | </AppAtomRegistryProvider> |
| 175 | ); |
| 176 | } |
| 177 | |
| 178 | function setup() { |
| 179 | mocks.editQueuedRun.mockReset(); |
| 180 | mocks.promoteQueuedRun.mockReset(); |
| 181 | useAttachmentUploadStore.setState({ uploadsByImageId: {} }); |
| 182 | useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} }); |
| 183 | setRuns(THREAD_A, "queued"); |
| 184 | setRuns(THREAD_B, "queued"); |
| 185 | return { hook: { current: null as HookResult | null } }; |
| 186 | } |
| 187 | |
| 188 | function requireHook(hook: { current: HookResult | null }): HookResult { |
| 189 | if (hook.current === null) throw new Error("hook did not render"); |
| 190 | return hook.current; |
| 191 | } |
| 192 | |
| 193 | async function beginChangedEdit(hook: { current: HookResult | null }) { |
| 194 | await act(() => |
| 195 | requireHook(hook).beginEdit({ |
| 196 | runId: RUN, |
| 197 | messageId: MessageId.make("message-1"), |
| 198 | text: "original", |
| 199 | attachments: [], |
| 200 | }), |
| 201 | ); |
| 202 | await act(() => |
| 203 | useComposerDraftStore.getState().setPrompt(requireHook(hook).draftTarget, "changed"), |
| 204 | ); |
| 205 | } |
| 206 | |
| 207 | const savedContent = (prompt: string) => ({ |
| 208 | prompt, |
| 209 | images: [], |
| 210 | files: [], |
| 211 | terminalContexts: [], |
| 212 | reviewComments: [], |
| 213 | previewAnnotations: [], |
| 214 | threadContexts: [], |
| 215 | environmentContexts: [], |
| 216 | }); |
| 217 | |
| 218 | const promptOf = (ref: ScopedThreadRef) => |
| 219 | useComposerDraftStore.getState().getComposerDraft(ref)?.prompt ?? ""; |
| 220 | |
| 221 | describe("useQueuedRunEdit", () => { |
| 222 | it.each(["", "Ultrathink:\n"])( |
| 223 | "opens attachment-only edits without the placeholder and preserves effort on save (%j)", |
| 224 | async (prefix) => { |
| 225 | const { hook } = setup(); |
| 226 | mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" }); |
| 227 | await using screen = await render(view(THREAD_A, "queued", hook)); |
| 228 | using toast = vi.spyOn(toastManager, "add"); |
| 229 | const attachments = [ |
| 230 | { |
| 231 | type: "image" as const, |
| 232 | id: ChatAttachmentId.make("kept"), |
| 233 | name: "kept.png", |
| 234 | mimeType: "image/png", |
| 235 | sizeBytes: 10, |
| 236 | }, |
| 237 | ]; |
| 238 | const request = { |
| 239 | runId: RUN, |
| 240 | messageId: MessageId.make("message-1"), |
| 241 | text: prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, |
| 242 | attachments, |
| 243 | }; |
| 244 | await act(() => requireHook(hook).beginEdit(request)); |
| 245 | expect( |
| 246 | useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt ?? |
| 247 | "", |
| 248 | ).toBe(prefix.trimEnd()); |
| 249 | expect(requireHook(hook).editingAttachments?.map(({ attachment }) => attachment)).toEqual( |
| 250 | attachments, |
| 251 | ); |
| 252 | await act(() => |
| 253 | useComposerDraftStore |
| 254 | .getState() |
| 255 | .setRuntimeMode(requireHook(hook).draftTarget, "full-access"), |
| 256 | ); |
| 257 | await act(() => setRuns(THREAD_A, "running")); |
| 258 | expect(toast).not.toHaveBeenCalled(); |
| 259 | expect(requireHook(hook).isEditing).toBe(false); |
| 260 | await act(() => setRuns(THREAD_A, "queued")); |
| 261 | await act(() => requireHook(hook).beginEdit(request)); |
| 262 | const update = screen.getByRole("button", { name: "Update queued message" }); |
| 263 | await expect.element(update).toBeEnabled(); |
| 264 | await update.click(); |
| 265 | await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce()); |
| 266 | expect(mocks.editQueuedRun).toHaveBeenCalledWith( |
| 267 | expect.objectContaining({ |
| 268 | input: expect.objectContaining({ |
| 269 | text: prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, |
| 270 | edit: expect.objectContaining({ attachments }), |
| 271 | }), |
| 272 | }), |
| 273 | ); |
| 274 | }, |
| 275 | ); |
| 276 | |
| 277 | it.each([ |
| 278 | // Cmd+Enter or Cmd-click with Queue as the default: save, then steer. |
| 279 | { dispatchMode: "steer", submissionIntent: "alternate", steers: true }, |
| 280 | // Enter or the Update button with Steer as the default: save in place only. |
| 281 | { dispatchMode: "steer", submissionIntent: "foreground", steers: false }, |
| 282 | // Cmd+Enter with Steer as the default queues, so the message stays queued. |
| 283 | { dispatchMode: "queue", submissionIntent: "alternate", steers: false }, |
| 284 | ] as const)( |
| 285 | "a saved edit sent as $submissionIntent/$dispatchMode steers: $steers", |
| 286 | async (submission) => { |
| 287 | const { hook } = setup(); |
| 288 | mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" }); |
| 289 | mocks.promoteQueuedRun.mockResolvedValue({ _tag: "Success" }); |
| 290 | const activeRun = RunId.make("run-active"); |
| 291 | appAtomRegistry.set(mocks.threadRuns(runsKey(THREAD_A)), [ |
| 292 | { id: activeRun, status: "running", activeAttemptId: "attempt-1" }, |
| 293 | { id: RUN, status: "queued" }, |
| 294 | ]); |
| 295 | await using _screen = await render(view(THREAD_A, "queued", hook)); |
| 296 | await beginChangedEdit(hook); |
| 297 | await act(() => requireHook(hook).saveEdit(savedContent("changed"), () => {}, submission)); |
| 298 | expect(mocks.editQueuedRun).toHaveBeenCalledOnce(); |
| 299 | if (!submission.steers) { |
| 300 | expect(mocks.promoteQueuedRun).not.toHaveBeenCalled(); |
| 301 | return; |
| 302 | } |
| 303 | expect(mocks.promoteQueuedRun).toHaveBeenCalledExactlyOnceWith({ |
| 304 | environmentId: ENV, |
| 305 | input: { threadId: THREAD_A.threadId, queuedRunId: RUN, targetRunId: activeRun }, |
| 306 | }); |
| 307 | expect(mocks.editQueuedRun.mock.invocationCallOrder[0]).toBeLessThan( |
| 308 | mocks.promoteQueuedRun.mock.invocationCallOrder[0]!, |
| 309 | ); |
| 310 | }, |
| 311 | ); |
| 312 | |
| 313 | it("saves an effort-only prompt without claiming removed attachments remain", async () => { |
| 314 | const { hook } = setup(); |
| 315 | mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" }); |
| 316 | await using screen = await render(view(THREAD_A, "queued", hook)); |
| 317 | await act(() => |
| 318 | requireHook(hook).beginEdit({ |
| 319 | runId: RUN, |
| 320 | messageId: MessageId.make("message-1"), |
| 321 | text: `Ultrathink:\n${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`, |
| 322 | attachments: [ |
| 323 | { |
| 324 | type: "image", |
| 325 | id: ChatAttachmentId.make("removed"), |
| 326 | name: "removed.png", |
| 327 | mimeType: "image/png", |
| 328 | sizeBytes: 10, |
| 329 | }, |
| 330 | ], |
| 331 | }), |
| 332 | ); |
| 333 | await act(() => requireHook(hook).removeEditingAttachment("removed")); |
| 334 | await screen.getByRole("button", { name: "Update queued message" }).click(); |
| 335 | await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce()); |
| 336 | expect(mocks.editQueuedRun).toHaveBeenCalledWith( |
| 337 | expect.objectContaining({ |
| 338 | input: expect.objectContaining({ |
| 339 | text: "Ultrathink:", |
| 340 | edit: expect.objectContaining({ attachments: [] }), |
| 341 | }), |
| 342 | }), |
| 343 | ); |
| 344 | }); |
| 345 | |
| 346 | it("opens an edit with only the thread and machine records its text still mentions", async () => { |
| 347 | const { hook } = setup(); |
| 348 | const thread = threadContextRecord(THREAD_B, "Support Any File Uploads"); |
| 349 | const machine = environmentContextRecord(ENV, "Build box"); |
| 350 | const unreferenced = threadContextRecord(THREAD_A, "Removed earlier"); |
| 351 | const messageId = MessageId.make("message-1"); |
| 352 | const text = `wait for ${formatInlineContextReference(threadContextReference(thread))} on ${formatInlineContextReference(environmentContextReference(machine))}`; |
| 353 | const messages = [ |
| 354 | { id: messageId, text, context: { version: 1, records: [thread, machine, unreferenced] } }, |
| 355 | ]; |
| 356 | await using _screen = await render(view(THREAD_A, "queued", hook, messages)); |
| 357 | |
| 358 | await act(() => requireHook(hook).beginEdit({ runId: RUN, messageId, text, attachments: [] })); |
| 359 | |
| 360 | const draft = useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget); |
| 361 | expect(draft?.prompt).toBe(text); |
| 362 | expect(draft?.threadContexts).toEqual([thread]); |
| 363 | expect(draft?.environmentContexts).toEqual([machine]); |
| 364 | }); |
| 365 | |
| 366 | it("saves only the thread mentions still in the edited message", async () => { |
| 367 | const { hook } = setup(); |
| 368 | mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" }); |
| 369 | const kept = threadContextRecord(THREAD_B, "Kept"); |
| 370 | const removed = threadContextRecord(THREAD_A, "Removed"); |
| 371 | const messageId = MessageId.make("message-1"); |
| 372 | const text = [kept, removed] |
| 373 | .map((record) => formatInlineContextReference(threadContextReference(record))) |
| 374 | .join(" and "); |
| 375 | const messages = [{ id: messageId, text, context: { version: 1, records: [kept, removed] } }]; |
| 376 | await using _screen = await render(view(THREAD_A, "queued", hook, messages)); |
| 377 | await act(() => requireHook(hook).beginEdit({ runId: RUN, messageId, text, attachments: [] })); |
| 378 | const target = requireHook(hook).draftTarget; |
| 379 | await act(() => useComposerDraftStore.getState().setThreadContexts(target, [kept])); |
| 380 | |
| 381 | const draft = useComposerDraftStore.getState().getComposerDraft(target); |
| 382 | await requireHook(hook).saveEdit( |
| 383 | { ...savedContent(draft?.prompt ?? ""), threadContexts: draft?.threadContexts ?? [] }, |
| 384 | () => {}, |
| 385 | ); |
| 386 | |
| 387 | expect(mocks.editQueuedRun).toHaveBeenCalledWith( |
| 388 | expect.objectContaining({ |
| 389 | input: expect.objectContaining({ |
| 390 | edit: expect.objectContaining({ context: { version: 1, records: [kept] } }), |
| 391 | }), |
| 392 | }), |
| 393 | ); |
| 394 | }); |
| 395 | |
| 396 | it("adds terminal context to the queued message being edited", async () => { |
| 397 | const { hook } = setup(); |
| 398 | await using _screen = await render(view(THREAD_A, "queued", hook)); |
| 399 | await beginChangedEdit(hook); |
| 400 | const target = requireHook(hook).draftTarget; |
| 401 | const inserted = useComposerDraftStore.getState().insertTerminalContext( |
| 402 | target, |
| 403 | `changed${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}`, |
| 404 | { |
| 405 | id: "terminal-context-1", |
| 406 | threadId: THREAD_A.threadId, |
| 407 | createdAt: "2026-01-01T00:00:00.000Z", |
| 408 | terminalId: "default", |
| 409 | terminalLabel: "Terminal 1", |
| 410 | lineStart: 3, |
| 411 | lineEnd: 3, |
| 412 | text: "hello", |
| 413 | }, |
| 414 | 0, |
| 415 | ); |
| 416 | expect(inserted).toBe(true); |
| 417 | expect( |
| 418 | useComposerDraftStore.getState().getComposerDraft(target)?.terminalContexts, |
| 419 | ).toHaveLength(1); |
| 420 | }); |
| 421 | |
| 422 | it("keeps an open edit when the user leaves the thread and comes back", async () => { |
| 423 | const { hook } = setup(); |
| 424 | await using screen = await render(view(THREAD_A, "queued", hook)); |
| 425 | await beginChangedEdit(hook); |
| 426 | |
| 427 | await screen.rerender(view(THREAD_B, "queued", hook)); |
| 428 | expect(requireHook(hook).isEditing).toBe(false); |
| 429 | await screen.rerender(view(THREAD_A, "queued", hook)); |
| 430 | |
| 431 | expect(requireHook(hook).editingRunId).toBe(RUN); |
| 432 | expect( |
| 433 | useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt, |
| 434 | ).toBe("changed"); |
| 435 | }); |
| 436 | |
| 437 | it("moves a changed edit into the thread draft when its run starts while the user is away", async () => { |
| 438 | const { hook } = setup(); |
| 439 | await using screen = await render(view(THREAD_A, "queued", hook)); |
| 440 | await beginChangedEdit(hook); |
| 441 | |
| 442 | await screen.rerender(view(THREAD_B, "queued", hook)); |
| 443 | expect(promptOf(THREAD_A)).toBe(""); |
| 444 | await act(() => setRuns(THREAD_A, "running")); |
| 445 | |
| 446 | expect(promptOf(THREAD_A)).toBe("changed"); |
| 447 | }); |
| 448 | |
| 449 | it("does not copy a saved edit into the thread draft when the run starts mid-save", async () => { |
| 450 | const { hook } = setup(); |
| 451 | let finishSave: (result: { readonly _tag: "Success" }) => void = () => {}; |
| 452 | mocks.editQueuedRun.mockReturnValue( |
| 453 | new Promise((resolve) => { |
| 454 | finishSave = resolve; |
| 455 | }), |
| 456 | ); |
| 457 | await using screen = await render(view(THREAD_A, "queued", hook)); |
| 458 | await beginChangedEdit(hook); |
| 459 | |
| 460 | // Not inside act(): act would hold the projection update until the save settles. |
| 461 | const saved = requireHook(hook).saveEdit(savedContent("changed"), () => {}); |
| 462 | await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce()); |
| 463 | // The server applied the edit and then started the run; the projection |
| 464 | // reports the start before the edit's acknowledgement arrives. |
| 465 | await act(() => setRuns(THREAD_A, "running")); |
| 466 | await screen.rerender(view(THREAD_A, "running", hook)); |
| 467 | finishSave({ _tag: "Success" }); |
| 468 | await act(() => saved); |
| 469 | |
| 470 | expect(requireHook(hook).isEditing).toBe(false); |
| 471 | expect(promptOf(THREAD_A)).toBe(""); |
| 472 | }); |
| 473 | |
| 474 | it.each([ |
| 475 | { transition: "cancel", result: "Success" }, |
| 476 | { transition: "recover", result: "Failure" }, |
| 477 | { transition: "replace", result: "Success" }, |
| 478 | ] as const)( |
| 479 | "settles saved attachments after $transition and $result", |
| 480 | async ({ transition, result }) => { |
| 481 | const { hook } = setup(); |
| 482 | let finishSave!: (result: { readonly _tag: "Success" | "Failure" }) => void; |
| 483 | let started!: () => void; |
| 484 | const saving = new Promise<{ readonly _tag: "Success" | "Failure" }>((resolve) => { |
| 485 | finishSave = resolve; |
| 486 | }); |
| 487 | const requested = new Promise<void>((resolve) => { |
| 488 | started = resolve; |
| 489 | }); |
| 490 | mocks.editQueuedRun.mockImplementation(() => { |
| 491 | started(); |
| 492 | return saving; |
| 493 | }); |
| 494 | await using _screen = await render(view(THREAD_A, "queued", hook)); |
| 495 | await beginChangedEdit(hook); |
| 496 | const image = { |
| 497 | type: "image" as const, |
| 498 | id: "saved-image", |
| 499 | name: "image.png", |
| 500 | mimeType: "image/png", |
| 501 | sizeBytes: 5, |
| 502 | file: new File(["image"], "image.png", { type: "image/png" }), |
| 503 | previewUrl: "blob:saved-image", |
| 504 | }; |
| 505 | using revoke = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {}); |
| 506 | await act(() => |
| 507 | useComposerDraftStore.getState().addImage(requireHook(hook).draftTarget, image), |
| 508 | ); |
| 509 | useAttachmentUploadStore.setState({ |
| 510 | uploadsByImageId: { |
| 511 | [image.id]: { status: "ready", environmentId: ENV, attachmentId: "saved-upload" }, |
| 512 | }, |
| 513 | }); |
| 514 | const target = requireHook(hook).draftTarget; |
| 515 | const saved = requireHook(hook).saveEdit( |
| 516 | { ...savedContent("changed"), images: [image] }, |
| 517 | () => {}, |
| 518 | ); |
| 519 | await act(() => requested); |
| 520 | expect(requireHook(hook).isSaving).toBe(true); |
| 521 | if (transition === "cancel") await act(() => requireHook(hook).cancelEdit()); |
| 522 | if (transition === "recover") await act(() => setRuns(THREAD_A, "running")); |
| 523 | if (transition === "replace") { |
| 524 | await beginChangedEdit(hook); |
| 525 | await act(() => |
| 526 | useComposerDraftStore.getState().addImage(requireHook(hook).draftTarget, image), |
| 527 | ); |
| 528 | } |
| 529 | expect(readAttachmentUpload(image.id)).toBeDefined(); |
| 530 | expect(revoke).not.toHaveBeenCalled(); |
| 531 | finishSave({ _tag: result }); |
| 532 | await act(() => saved); |
| 533 | if (transition === "cancel") { |
| 534 | expect(readAttachmentUpload(image.id)).toBeUndefined(); |
| 535 | expect(revoke).toHaveBeenCalledWith(image.previewUrl); |
| 536 | expect(useComposerDraftStore.getState().getComposerDraft(target)).toBeNull(); |
| 537 | } else { |
| 538 | expect(readAttachmentUpload(image.id)).toBeDefined(); |
| 539 | expect(revoke).not.toHaveBeenCalled(); |
| 540 | const owner = transition === "recover" ? THREAD_A : target; |
| 541 | expect(useComposerDraftStore.getState().getComposerDraft(owner)?.images).toEqual([image]); |
| 542 | } |
| 543 | }, |
| 544 | ); |
| 545 | |
| 546 | it("leaves a newer edit alone when a save from before navigation finishes", async () => { |
| 547 | const { hook } = setup(); |
| 548 | let finishSave: (result: { readonly _tag: "Success" }) => void = () => {}; |
| 549 | mocks.editQueuedRun.mockReturnValue( |
| 550 | new Promise((resolve) => { |
| 551 | finishSave = resolve; |
| 552 | }), |
| 553 | ); |
| 554 | await using screen = await render(view(THREAD_A, "queued", hook)); |
| 555 | await beginChangedEdit(hook); |
| 556 | // Not inside act(): act would hold the rerenders until the save settles. |
| 557 | const saved = requireHook(hook).saveEdit(savedContent("changed"), () => {}); |
| 558 | await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce()); |
| 559 | |
| 560 | // Leaving the thread unmounts the chat view; coming back mounts a new one. |
| 561 | await screen.rerender(<AppAtomRegistryProvider>{null}</AppAtomRegistryProvider>); |
| 562 | await screen.rerender(view(THREAD_A, "queued", hook)); |
| 563 | expect(requireHook(hook).isSaving).toBe(true); |
| 564 | await beginChangedEdit(hook); |
| 565 | await act(() => |
| 566 | useComposerDraftStore.getState().setPrompt(requireHook(hook).draftTarget, "newer"), |
| 567 | ); |
| 568 | |
| 569 | finishSave({ _tag: "Success" }); |
| 570 | await act(() => saved); |
| 571 | |
| 572 | expect(requireHook(hook).editingRunId).toBe(RUN); |
| 573 | expect(requireHook(hook).isSaving).toBe(false); |
| 574 | expect( |
| 575 | useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt, |
| 576 | ).toBe("newer"); |
| 577 | }); |
| 578 | }); |