Open History to see the last commit
1import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
2import { scopedThreadKey } from "@t3tools/client-runtime/environment";
3import {
4 EnvironmentId,
5 ChatAttachmentId,
6 ComposerContextId,
7 MessageId,
8 ProviderInstanceId,
9 RunId,
10 ThreadId,
11 TurnItemId,
12 type ScopedThreadRef,
13} from "@t3tools/contracts";
14import { useImperativeHandle, useLayoutEffect, useRef, type RefObject } from "react";
15import { describe, expect, it, vi } from "vite-plus/test";
16import {
17 ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
18 threadContextRecord,
19} from "@t3tools/shared/composerContextReferences";
20import { toastManager } from "../ui/toast";
21
22import { act, render } from "../../../test/render";
23import { useComposerDraftStore, useComposerThreadDraft } from "../../composerDraftStore";
24import { formatInlineContextReference } from "../../lib/composerContextReferences";
25import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "../../lib/terminalContext";
26import {
27 environmentContextRecord,
28 environmentContextReference,
29 responseContextRecord,
30 responseContextReference,
31 terminalContextRecord,
32 threadContextReference,
33} from "../../lib/composerContextRecords";
34import { deriveComposerSendState } from "../ChatView.logic";
35import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
36import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry";
37import { useQueuedRunEdit } from "./useQueuedRunEdit";
38import type { ChatComposerHandle } from "./ChatComposer";
39import { readAttachmentUpload, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue";
40
41interface RunStatus {
42 readonly id: RunId;
43 readonly status: string;
44 readonly modelSelection?: { readonly instanceId: ProviderInstanceId; readonly model: string };
45 readonly activeAttemptId?: string;
46}
47
48const mocks = await vi.hoisted(async () => {
49 const { Atom } = await import("effect/reactivity");
50 return {
51 editQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" | "Failure" }>>(),
52 promoteQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" }>>(),
53 promoteCommand: {},
54 cancelQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" | "Failure" }>>(),
55 cancelCommand: {},
56 // The projection's runs per thread, written by each test to stand in for the server.
57 threadRuns: Atom.family((_key: string) =>
58 Atom.make<ReadonlyArray<RunStatus> | null>(null).pipe(Atom.keepAlive),
59 ),
60 };
61});
62
63vi.mock("../../state/use-atom-command", () => ({
64 useAtomCommand: (command: unknown) =>
65 command === mocks.promoteCommand
66 ? mocks.promoteQueuedRun
67 : command === mocks.cancelCommand
68 ? mocks.cancelQueuedRun
69 : mocks.editQueuedRun,
70}));
71
72vi.mock("../../hooks/useSettings", () => ({
73 useEnvironmentIdentificationMode: () => "none",
74}));
75
76const runsKey = (ref: ScopedThreadRef) => `${ref.environmentId}:${ref.threadId}`;
77
78vi.mock("../../state/threads", async () => {
79 const { Atom } = await import("effect/reactivity");
80 const key = (ref: ScopedThreadRef) => `${ref.environmentId}:${ref.threadId}`;
81 return {
82 threadEnvironment: {
83 snapshotAtom: () => Atom.make(null),
84 editQueuedRun: {},
85 promoteQueuedRun: mocks.promoteCommand,
86 cancelQueuedRun: mocks.cancelCommand,
87 },
88 environmentThreadDetails: {
89 statusAtom: () => Atom.make("ready"),
90 quietThreadAtom: (ref: ScopedThreadRef) =>
91 Atom.make((get) => {
92 const runs = get(mocks.threadRuns(key(ref)));
93 if (runs === null) return null;
94 // A Claude-like session whose running turn takes steering.
95 return {
96 projection: {
97 thread: { id: ref.threadId, activeProviderThreadId: null },
98 runs,
99 messages: [],
100 turnItems: [],
101 providerThreads: [],
102 providerSessions: [
103 {
104 id: "session",
105 status: "running",
106 capabilities: { turns: { supportsActiveSteering: true } },
107 },
108 ],
109 providerTurns: runs.flatMap((run) =>
110 run.activeAttemptId
111 ? [{ runAttemptId: run.activeAttemptId, status: "running" }]
112 : [],
113 ),
114 },
115 };
116 }),
117 },
118 environmentThreadShells: {
119 threadShellAtom: () => Atom.make(null),
120 },
121 };
122});
123
124const ENV = EnvironmentId.make("env-1");
125const THREAD_A: ScopedThreadRef = { environmentId: ENV, threadId: ThreadId.make("thread-a") };
126const THREAD_B: ScopedThreadRef = { environmentId: ENV, threadId: ThreadId.make("thread-b") };
127const RUN = RunId.make("run-1");
128
129type HookResult = ReturnType<typeof useQueuedRunEdit>;
130
131function projection(runs: ReadonlyArray<RunStatus>, messages: ReadonlyArray<unknown>) {
132 return {
133 runs,
134 messages,
135 thread: {
136 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "current-model" },
137 },
138 } as unknown as ThreadStructure;
139}
140
141function setRuns(ref: ScopedThreadRef, status: string) {
142 appAtomRegistry.set(mocks.threadRuns(runsKey(ref)), [{ id: RUN, status }]);
143}
144
145interface ComposerRefs {
146 readonly promptRef: RefObject<string>;
147 readonly composerRef: Parameters<typeof useQueuedRunEdit>[0]["composerRef"];
148}
149
150function Harness(props: {
151 readonly threadRef: ScopedThreadRef;
152 readonly runStatus: string;
153 readonly hookRef: RefObject<HookResult | null>;
154 readonly messages: ReadonlyArray<unknown>;
155 readonly composer?: ComposerRefs | undefined;
156}) {
157 const threadKey = scopedThreadKey(props.threadRef);
158 const currentRouteThreadKeyRef = useRef<string | null>(threadKey);
159 useLayoutEffect(() => {
160 currentRouteThreadKeyRef.current = threadKey;
161 return () => {
162 currentRouteThreadKeyRef.current = null;
163 };
164 }, [threadKey]);
165 const result = useQueuedRunEdit({
166 environmentId: ENV,
167 routeThreadRef: props.threadRef,
168 currentRouteThreadKeyRef,
169 threadDraftTarget: props.threadRef,
170 activeThreadId: props.threadRef.threadId,
171 serverProjection: projection(
172 [{ id: RUN, status: props.runStatus, modelSelection: savedContent("").modelSelection }],
173 props.messages,
174 ),
175 promptRef: props.composer?.promptRef ?? { current: "" },
176 composerRef: props.composer?.composerRef ?? { current: null },
177 });
178 useImperativeHandle(props.hookRef, () => result);
179 const draft = useComposerThreadDraft(result.draftTarget);
180 const sendState = deriveComposerSendState({
181 prompt: draft.prompt,
182 imageCount: draft.images.length + draft.files.length,
183 existingAttachmentCount: result.editingAttachments?.length ?? 0,
184 terminalContexts: draft.terminalContexts,
185 });
186 return result.isEditing ? (
187 <ComposerPrimaryActions
188 compact={false}
189 canOperateThread
190 pendingAction={null}
191 isRunning={false}
192 canInterrupt={false}
193 isSendBusy={result.isSaving}
194 sendDisabledReason={null}
195 isEnvironmentUnavailable={false}
196 isPreparingWorktree={false}
197 hasSendableContent={sendState.hasSendableContent}
198 isEditingQueuedMessage
199 onSubmitMessage={() => void result.saveEdit(savedContent(draft.prompt), () => {})}
200 onPreviousPendingQuestion={() => {}}
201 onInterrupt={() => {}}
202 />
203 ) : null;
204}
205
206function view(
207 threadRef: ScopedThreadRef,
208 runStatus: string,
209 hook: { current: HookResult | null },
210 messages: ReadonlyArray<unknown> = [],
211 composer?: ComposerRefs,
212) {
213 return (
214 <AppAtomRegistryProvider>
215 <Harness
216 threadRef={threadRef}
217 runStatus={runStatus}
218 hookRef={hook}
219 messages={messages}
220 composer={composer}
221 />
222 </AppAtomRegistryProvider>
223 );
224}
225
226function setup() {
227 mocks.editQueuedRun.mockReset();
228 mocks.promoteQueuedRun.mockReset();
229 mocks.cancelQueuedRun.mockReset();
230 useAttachmentUploadStore.setState({ uploadsByImageId: {} });
231 useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} });
232 setRuns(THREAD_A, "queued");
233 setRuns(THREAD_B, "queued");
234 return { hook: { current: null as HookResult | null } };
235}
236
237function requireHook(hook: { current: HookResult | null }): HookResult {
238 if (hook.current === null) throw new Error("hook did not render");
239 return hook.current;
240}
241
242async function beginChangedEdit(hook: { current: HookResult | null }) {
243 await act(() =>
244 requireHook(hook).beginEdit({
245 runId: RUN,
246 messageId: MessageId.make("message-1"),
247 text: "original",
248 attachments: [],
249 }),
250 );
251 await act(() =>
252 useComposerDraftStore.getState().setPrompt(requireHook(hook).draftTarget, "changed"),
253 );
254}
255
256const savedContent = (prompt: string) => ({
257 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
258 prompt,
259 images: [],
260 files: [],
261 terminalContexts: [],
262 reviewComments: [],
263 previewAnnotations: [],
264 threadContexts: [],
265 environmentContexts: [],
266});
267
268const REPLY = responseContextRecord({
269 citation: {
270 version: 1,
271 environmentId: ENV,
272 threadId: THREAD_A.threadId,
273 messageId: MessageId.make("message-answer"),
274 text: "Done.",
275 start: 0,
276 end: 5,
277 prefix: "",
278 suffix: "",
279 },
280 itemId: TurnItemId.make("item-answer"),
281 subagents: [],
282});
283const REPLY_REFERENCE = formatInlineContextReference(responseContextReference(REPLY));
284
285const promptOf = (ref: ScopedThreadRef) =>
286 useComposerDraftStore.getState().getComposerDraft(ref)?.prompt ?? "";
287
288describe("useQueuedRunEdit", () => {
289 it.each([
290 { navigation: "switches before the reply", resets: false, focuses: false },
291 { navigation: "switches before the frame", resets: true, focuses: false },
292 { navigation: "stays on thread", resets: true, focuses: true },
293 ])("finishes a successful queued edit when the user $navigation", async (scenario) => {
294 const { hook } = setup();
295 const requested = Promise.withResolvers<void>();
296 const reply = Promise.withResolvers<{ readonly _tag: "Success" }>();
297 mocks.editQueuedRun.mockImplementation(() => {
298 requested.resolve();
299 return reply.promise;
300 });
301 const focusAtEnd = vi.fn();
302 const resetCursorState = vi.fn();
303 const composer: ComposerRefs = {
304 promptRef: { current: "changed" },
305 composerRef: { current: null },
306 };
307 await using screen = await render(view(THREAD_A, "queued", hook, [], composer));
308 const frames: FrameRequestCallback[] = [];
309 using _frame = vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
310 frames.push(callback);
311 return 0;
312 });
313 await beginChangedEdit(hook);
314 await act(() => {
315 for (const frame of frames.splice(0)) frame(0);
316 });
317 composer.composerRef.current = {
318 focusAtEnd,
319 resetCursorState,
320 } as unknown as ChatComposerHandle;
321
322 const setThreadError = vi.fn();
323 const saved = requireHook(hook).saveEdit(savedContent("changed"), setThreadError);
324 await requested.promise;
325 const openOtherThread = async () => {
326 await screen.rerender(view(THREAD_B, "queued", hook, [], composer));
327 composer.promptRef.current = "other thread draft";
328 };
329 if (scenario.navigation === "switches before the reply") await openOtherThread();
330 reply.resolve({ _tag: "Success" });
331 await act(() => saved);
332 expect(setThreadError).toHaveBeenCalledExactlyOnceWith(THREAD_A.threadId, null);
333 expect(resetCursorState).toHaveBeenCalledTimes(Number(scenario.resets));
334
335 if (scenario.navigation === "switches before the frame") await openOtherThread();
336 await act(() => {
337 for (const frame of frames.splice(0)) frame(0);
338 });
339 expect(focusAtEnd).toHaveBeenCalledTimes(Number(scenario.focuses));
340 expect(composer.promptRef.current).toBe(
341 scenario.navigation === "stays on thread" ? "" : "other thread draft",
342 );
343 });
344
345 it("reopens a message ending in a skill with the space that keeps it a chip", async () => {
346 const { hook } = setup();
347 await using _screen = await render(view(THREAD_A, "queued", hook));
348 using toast = vi.spyOn(toastManager, "add");
349 await act(() =>
350 requireHook(hook).beginEdit({
351 runId: RUN,
352 messageId: MessageId.make("message-1"),
353 text: "polish it $ui-taste",
354 attachments: [],
355 }),
356 );
357 expect(
358 useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt,
359 ).toBe("polish it $ui-taste ");
360 await act(() => setRuns(THREAD_A, "running"));
361 expect(toast).not.toHaveBeenCalled();
362 });
363
364 it.each(["", "Ultrathink:\n"])(
365 "opens attachment-only edits without the placeholder and preserves effort on save (%j)",
366 async (prefix) => {
367 const { hook } = setup();
368 mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" });
369 await using screen = await render(view(THREAD_A, "queued", hook));
370 using toast = vi.spyOn(toastManager, "add");
371 const attachments = [
372 {
373 type: "image" as const,
374 id: ChatAttachmentId.make("kept"),
375 name: "kept.png",
376 mimeType: "image/png",
377 sizeBytes: 10,
378 },
379 ];
380 const request = {
381 runId: RUN,
382 messageId: MessageId.make("message-1"),
383 text: prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
384 attachments,
385 };
386 await act(() => requireHook(hook).beginEdit(request));
387 expect(
388 useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt ??
389 "",
390 ).toBe(prefix.trimEnd());
391 expect(requireHook(hook).editingAttachments?.map(({ attachment }) => attachment)).toEqual(
392 attachments,
393 );
394 await act(() =>
395 useComposerDraftStore
396 .getState()
397 .setRuntimeMode(requireHook(hook).draftTarget, "full-access"),
398 );
399 await act(() => setRuns(THREAD_A, "running"));
400 expect(toast).not.toHaveBeenCalled();
401 expect(requireHook(hook).isEditing).toBe(false);
402 await act(() => setRuns(THREAD_A, "queued"));
403 await act(() => requireHook(hook).beginEdit(request));
404 const update = screen.getByRole("button", { name: "Update queued message" });
405 await expect.element(update).toBeEnabled();
406 await update.click();
407 await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
408 expect(mocks.editQueuedRun).toHaveBeenCalledWith(
409 expect.objectContaining({
410 input: expect.objectContaining({
411 text: prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
412 edit: expect.objectContaining({ attachments }),
413 }),
414 }),
415 );
416 },
417 );
418
419 it.each([
420 // Cmd+Enter or Cmd-click with Queue as the default: save, then steer.
421 { dispatchMode: "steer", submissionIntent: "alternate", steers: true },
422 // Enter or the Update button with Steer as the default: save in place only.
423 { dispatchMode: "steer", submissionIntent: "foreground", steers: false },
424 // Cmd+Enter with Steer as the default queues, so the message stays queued.
425 { dispatchMode: "queue", submissionIntent: "alternate", steers: false },
426 ] as const)(
427 "a saved edit sent as $submissionIntent/$dispatchMode steers: $steers",
428 async (submission) => {
429 const { hook } = setup();
430 mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" });
431 mocks.promoteQueuedRun.mockResolvedValue({ _tag: "Success" });
432 const activeRun = RunId.make("run-active");
433 appAtomRegistry.set(mocks.threadRuns(runsKey(THREAD_A)), [
434 { id: activeRun, status: "running", activeAttemptId: "attempt-1" },
435 { id: RUN, status: "queued" },
436 ]);
437 await using _screen = await render(view(THREAD_A, "queued", hook));
438 await beginChangedEdit(hook);
439 await act(() => requireHook(hook).saveEdit(savedContent("changed"), () => {}, submission));
440 expect(mocks.editQueuedRun).toHaveBeenCalledOnce();
441 if (!submission.steers) {
442 expect(mocks.promoteQueuedRun).not.toHaveBeenCalled();
443 return;
444 }
445 expect(mocks.promoteQueuedRun).toHaveBeenCalledExactlyOnceWith({
446 environmentId: ENV,
447 input: { threadId: THREAD_A.threadId, queuedRunId: RUN, targetRunId: activeRun },
448 });
449 expect(mocks.editQueuedRun.mock.invocationCallOrder[0]).toBeLessThan(
450 mocks.promoteQueuedRun.mock.invocationCallOrder[0]!,
451 );
452 },
453 );
454
455 it.each([
456 {
457 result: "Success",
458 replaced: false,
459 typed: false,
460 moved: true,
461 cleared: 1,
462 prompt: undefined,
463 },
464 {
465 result: "Failure",
466 replaced: false,
467 typed: false,
468 moved: false,
469 cleared: 0,
470 prompt: "changed",
471 },
472 // The edit was cancelled and begun again while the cancel was in flight.
473 { result: "Success", replaced: true, typed: false, moved: true, cleared: 0, prompt: "changed" },
474 // Text typed while the cancel was in flight is not in the stash entry.
475 { result: "Success", replaced: false, typed: true, moved: true, cleared: 0, prompt: "newer" },
476 ] as const)(
477 "moving an edit to the stash after a $result cancel (replaced: $replaced, typed: $typed)",
478 async ({ result, replaced, typed, moved, cleared, prompt }) => {
479 const { hook } = setup();
480 let settleCancel = (_value: { readonly _tag: "Success" | "Failure" }) => {};
481 mocks.cancelQueuedRun.mockImplementation(
482 () => new Promise((resolve) => (settleCancel = resolve)),
483 );
484 const composer: ComposerRefs = {
485 promptRef: { current: "changed" },
486 composerRef: { current: null },
487 };
488 await using _screen = await render(view(THREAD_A, "queued", hook, [], composer));
489 await beginChangedEdit(hook);
490 const editTarget = requireHook(hook).draftTarget;
491 const move = { unstash: vi.fn(), clearComposer: vi.fn() };
492 const stashedFile = new File(["report"], "report.pdf", { type: "application/pdf" });
493 if (typed) {
494 useComposerDraftStore.getState().addFiles(editTarget, [
495 {
496 type: "file",
497 id: "stashed-file",
498 name: stashedFile.name,
499 mimeType: stashedFile.type,
500 sizeBytes: stashedFile.size,
501 file: stashedFile,
502 },
503 ]);
504 }
505
506 let removal: Promise<boolean> | undefined;
507 await act(() => {
508 removal = requireHook(hook).removeEditedRun(move);
509 });
510 if (replaced) {
511 await act(() => requireHook(hook).cancelEdit());
512 await beginChangedEdit(hook);
513 }
514 if (typed) {
515 await act(() => useComposerDraftStore.getState().setPrompt(editTarget, "newer"));
516 }
517 await act(() => settleCancel({ _tag: result }));
518
519 expect(await removal).toBe(moved);
520 expect(move.unstash).toHaveBeenCalledTimes(moved ? 0 : 1);
521 expect(move.clearComposer).toHaveBeenCalledTimes(cleared);
522 expect(requireHook(hook).isEditing).toBe(prompt !== undefined);
523 expect(useComposerDraftStore.getState().getComposerDraft(editTarget)?.prompt).toBe(prompt);
524 // The stash entry owns the file, so the run-left-queue recovery must not release it.
525 if (typed) {
526 expect(useComposerDraftStore.getState().getComposerDraft(editTarget)?.files).toEqual([]);
527 }
528 expect(mocks.cancelQueuedRun).toHaveBeenCalledExactlyOnceWith({
529 environmentId: THREAD_A.environmentId,
530 input: { threadId: THREAD_A.threadId, runId: RUN },
531 });
532 },
533 );
534
535 it("lets an edit move to the stash only when the stash can hold all of the message", async () => {
536 const { hook } = setup();
537 const thread = threadContextRecord(THREAD_B, "Kept in the draft");
538 const terminalDraft = {
539 id: "terminal-1",
540 threadId: THREAD_A.threadId,
541 createdAt: "2026-01-01T00:00:00.000Z",
542 terminalId: "term-1",
543 terminalLabel: "Terminal 1",
544 lineStart: 1,
545 lineEnd: 2,
546 text: "npm test",
547 };
548 const terminal = terminalContextRecord(terminalDraft);
549 const threadOnly = MessageId.make("message-thread");
550 const withReply = MessageId.make("message-reply");
551 const withStaleReply = MessageId.make("message-stale-reply");
552 const withTerminal = MessageId.make("message-terminal");
553 const threadText = `see ${formatInlineContextReference(threadContextReference(thread))}`;
554 const replyText = `${REPLY_REFERENCE} check the tests`;
555 // A save keeps a terminal or unreferenced reply record even after its chip left the text; the stash cannot.
556 const terminalText = "see the output";
557 const messages = [
558 { id: threadOnly, text: threadText, context: { version: 1, records: [thread] } },
559 { id: withReply, text: replyText, context: { version: 1, records: [REPLY] } },
560 { id: withStaleReply, text: "check the tests", context: { version: 1, records: [REPLY] } },
561 { id: withTerminal, text: terminalText, context: { version: 1, records: [terminal] } },
562 ];
563 await using _screen = await render(view(THREAD_A, "queued", hook, messages));
564
565 await act(() =>
566 requireHook(hook).beginEdit({
567 runId: RUN,
568 messageId: threadOnly,
569 text: threadText,
570 attachments: [],
571 }),
572 );
573 expect(requireHook(hook).canMoveEditToStash).toBe(true);
574
575 await act(() =>
576 requireHook(hook).beginEdit({
577 runId: RUN,
578 messageId: withReply,
579 text: replyText,
580 attachments: [],
581 }),
582 );
583 expect(requireHook(hook).canMoveEditToStash).toBe(true);
584
585 await act(() =>
586 requireHook(hook).beginEdit({
587 runId: RUN,
588 messageId: withStaleReply,
589 text: "check the tests",
590 attachments: [],
591 }),
592 );
593 expect(requireHook(hook).canMoveEditToStash).toBe(false);
594
595 await act(() =>
596 requireHook(hook).beginEdit({
597 runId: RUN,
598 messageId: withTerminal,
599 text: terminalText,
600 attachments: [],
601 }),
602 );
603 expect(requireHook(hook).canMoveEditToStash).toBe(false);
604 });
605
606 it("saves an effort-only prompt without claiming removed attachments remain", async () => {
607 const { hook } = setup();
608 mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" });
609 await using screen = await render(view(THREAD_A, "queued", hook));
610 await act(() =>
611 requireHook(hook).beginEdit({
612 runId: RUN,
613 messageId: MessageId.make("message-1"),
614 text: `Ultrathink:\n${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`,
615 attachments: [
616 {
617 type: "image",
618 id: ChatAttachmentId.make("removed"),
619 name: "removed.png",
620 mimeType: "image/png",
621 sizeBytes: 10,
622 },
623 ],
624 }),
625 );
626 await act(() => requireHook(hook).removeEditingAttachment("removed"));
627 await screen.getByRole("button", { name: "Update queued message" }).click();
628 await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
629 expect(mocks.editQueuedRun).toHaveBeenCalledWith(
630 expect.objectContaining({
631 input: expect.objectContaining({
632 text: "Ultrathink:",
633 edit: expect.objectContaining({ attachments: [] }),
634 }),
635 }),
636 );
637 });
638
639 it("saves nothing when the edit leaves only its reply, as the disabled button says", async () => {
640 const { hook } = setup();
641 const messageId = MessageId.make("message-1");
642 const text = `${REPLY_REFERENCE} Fix the login form`;
643 const messages = [{ id: messageId, text, context: { version: 1, records: [REPLY] } }];
644 await using screen = await render(view(THREAD_A, "queued", hook, messages));
645 await act(() => requireHook(hook).beginEdit({ runId: RUN, messageId, text, attachments: [] }));
646 const target = requireHook(hook).draftTarget;
647 await act(() => useComposerDraftStore.getState().setPrompt(target, " "));
648 await expect
649 .element(screen.getByRole("button", { name: "Update queued message" }))
650 .toBeDisabled();
651
652 // Enter hands `saveEdit` the prompt with the reply's reference in front, as `onSend` builds it.
653 await requireHook(hook).saveEdit(
654 { ...savedContent(`${REPLY_REFERENCE} `), replyTo: REPLY },
655 () => {},
656 { dispatchMode: "steer", submissionIntent: "foreground" },
657 );
658
659 expect(mocks.editQueuedRun).not.toHaveBeenCalled();
660 expect(requireHook(hook).isEditing).toBe(true);
661 expect(useComposerDraftStore.getState().getComposerDraft(target)?.replyTo).toEqual(REPLY);
662 });
663
664 it("saves the reply and image of an edit whose text is deleted", async () => {
665 const { hook } = setup();
666 mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" });
667 const image = {
668 type: "image" as const,
669 id: ChatAttachmentId.make("image-1"),
670 name: "a.png",
671 mimeType: "image/png",
672 sizeBytes: 10,
673 };
674 const messageId = MessageId.make("message-1");
675 const text = `${REPLY_REFERENCE} Look at this`;
676 const messages = [{ id: messageId, text, context: { version: 1, records: [REPLY] } }];
677 await using _screen = await render(view(THREAD_A, "queued", hook, messages));
678 await act(() =>
679 requireHook(hook).beginEdit({ runId: RUN, messageId, text, attachments: [image] }),
680 );
681 await act(() => useComposerDraftStore.getState().setPrompt(requireHook(hook).draftTarget, ""));
682 await requireHook(hook).saveEdit(
683 { ...savedContent(`${REPLY_REFERENCE} `), replyTo: REPLY },
684 () => {},
685 );
686
687 const edit = { attachments: [image], context: { version: 1, records: [REPLY] } };
688 expect(mocks.editQueuedRun.mock.calls).toMatchObject([
689 [{ input: { text: REPLY_REFERENCE, edit } }],
690 ]);
691 });
692
693 it("opens an edit with only the thread and machine records its text still mentions", async () => {
694 const { hook } = setup();
695 const thread = threadContextRecord(THREAD_B, "Support Any File Uploads");
696 const machine = environmentContextRecord(ENV, "Build box");
697 const unreferenced = threadContextRecord(THREAD_A, "Removed earlier");
698 const messageId = MessageId.make("message-1");
699 const text = `wait for ${formatInlineContextReference(threadContextReference(thread))} on ${formatInlineContextReference(environmentContextReference(machine))}`;
700 const messages = [
701 { id: messageId, text, context: { version: 1, records: [thread, machine, unreferenced] } },
702 ];
703 await using _screen = await render(view(THREAD_A, "queued", hook, messages));
704
705 await act(() => requireHook(hook).beginEdit({ runId: RUN, messageId, text, attachments: [] }));
706
707 const draft = useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget);
708 expect(draft?.prompt).toBe(text);
709 expect(draft?.threadContexts).toEqual([thread]);
710 expect(draft?.environmentContexts).toEqual([machine]);
711 });
712
713 it("saves only the thread mentions and attachments still in the edited message", async () => {
714 const { hook } = setup();
715 mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" });
716 const kept = threadContextRecord(THREAD_B, "Kept");
717 const removed = threadContextRecord(THREAD_A, "Removed");
718 const removedImageId = ChatAttachmentId.make("server-image-removed");
719 const keptFileId = ChatAttachmentId.make("server-file-kept");
720 const removedImageContextId = ComposerContextId.make("image_local-removed");
721 const keptFileContextId = ComposerContextId.make("file_local-kept");
722 const removedImage = {
723 type: "image" as const,
724 id: removedImageId,
725 name: "image.png",
726 mimeType: "image/png",
727 sizeBytes: 67,
728 };
729 const keptFile = {
730 type: "file" as const,
731 id: keptFileId,
732 name: "legacy.pdf",
733 mimeType: "application/pdf",
734 sizeBytes: 40,
735 };
736 const removedImageRecord = {
737 version: 1 as const,
738 kind: "image" as const,
739 contextId: removedImageContextId,
740 label: "image.png",
741 attachmentId: removedImageId,
742 name: "image.png",
743 mimeType: "image/png",
744 sizeBytes: 67,
745 };
746 const keptFileRecord = {
747 version: 1 as const,
748 kind: "file" as const,
749 contextId: keptFileContextId,
750 label: "legacy.pdf",
751 attachmentId: keptFileId,
752 name: "legacy.pdf",
753 mimeType: "application/pdf",
754 sizeBytes: 40,
755 };
756 const messageId = MessageId.make("message-1");
757 const text = [
758 formatInlineContextReference(threadContextReference(kept)),
759 formatInlineContextReference(threadContextReference(removed)),
760 formatInlineContextReference({
761 kind: "image",
762 contextId: removedImageContextId,
763 label: "image.png",
764 }),
765 ].join(" and ");
766 const messages = [
767 {
768 id: messageId,
769 text,
770 context: { version: 1, records: [kept, removed, removedImageRecord, keptFileRecord] },
771 },
772 ];
773 await using _screen = await render(view(THREAD_A, "queued", hook, messages));
774 await act(() =>
775 requireHook(hook).beginEdit({
776 runId: RUN,
777 messageId,
778 text,
779 attachments: [removedImage, keptFile],
780 }),
781 );
782 const target = requireHook(hook).draftTarget;
783 await act(() => {
784 useComposerDraftStore.getState().setThreadContexts(target, [kept]);
785 requireHook(hook).removeEditingAttachment(removedImageId);
786 });
787
788 const draft = useComposerDraftStore.getState().getComposerDraft(target);
789 expect(draft?.prompt).not.toContain(removedImageContextId);
790 await requireHook(hook).saveEdit(
791 { ...savedContent(draft?.prompt ?? ""), threadContexts: draft?.threadContexts ?? [] },
792 () => {},
793 );
794
795 expect(mocks.editQueuedRun).toHaveBeenCalledWith(
796 expect.objectContaining({
797 input: expect.objectContaining({
798 text: draft?.prompt,
799 edit: expect.objectContaining({
800 attachments: [keptFile],
801 context: { version: 1, records: [keptFileRecord, kept] },
802 }),
803 }),
804 }),
805 );
806 });
807
808 it("adds terminal context to the queued message being edited", async () => {
809 const { hook } = setup();
810 await using _screen = await render(view(THREAD_A, "queued", hook));
811 await beginChangedEdit(hook);
812 const target = requireHook(hook).draftTarget;
813 const inserted = useComposerDraftStore.getState().insertTerminalContext(
814 target,
815 `changed${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}`,
816 {
817 id: "terminal-context-1",
818 threadId: THREAD_A.threadId,
819 createdAt: "2026-01-01T00:00:00.000Z",
820 terminalId: "default",
821 terminalLabel: "Terminal 1",
822 lineStart: 3,
823 lineEnd: 3,
824 text: "hello",
825 },
826 0,
827 );
828 expect(inserted).toBe(true);
829 expect(
830 useComposerDraftStore.getState().getComposerDraft(target)?.terminalContexts,
831 ).toHaveLength(1);
832 });
833
834 it("keeps an open edit when the user leaves the thread and comes back", async () => {
835 const { hook } = setup();
836 await using screen = await render(view(THREAD_A, "queued", hook));
837 await beginChangedEdit(hook);
838
839 await screen.rerender(view(THREAD_B, "queued", hook));
840 expect(requireHook(hook).isEditing).toBe(false);
841 await screen.rerender(view(THREAD_A, "queued", hook));
842
843 expect(requireHook(hook).editingRunId).toBe(RUN);
844 expect(
845 useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt,
846 ).toBe("changed");
847 });
848
849 it("moves a changed edit into the thread draft when its run starts while the user is away", async () => {
850 const { hook } = setup();
851 await using screen = await render(view(THREAD_A, "queued", hook));
852 await beginChangedEdit(hook);
853
854 await screen.rerender(view(THREAD_B, "queued", hook));
855 expect(promptOf(THREAD_A)).toBe("");
856 await act(() => setRuns(THREAD_A, "running"));
857
858 expect(promptOf(THREAD_A)).toBe("changed");
859 });
860
861 it("does not copy a saved edit into the thread draft when the run starts mid-save", async () => {
862 const { hook } = setup();
863 let finishSave: (result: { readonly _tag: "Success" }) => void = () => {};
864 mocks.editQueuedRun.mockReturnValue(
865 new Promise((resolve) => {
866 finishSave = resolve;
867 }),
868 );
869 await using screen = await render(view(THREAD_A, "queued", hook));
870 await beginChangedEdit(hook);
871
872 // Not inside act(): act would hold the projection update until the save settles.
873 const saved = requireHook(hook).saveEdit(savedContent("changed"), () => {});
874 await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
875 // The server applied the edit and then started the run; the projection
876 // reports the start before the edit's acknowledgement arrives.
877 await act(() => setRuns(THREAD_A, "running"));
878 await screen.rerender(view(THREAD_A, "running", hook));
879 finishSave({ _tag: "Success" });
880 await act(() => saved);
881
882 expect(requireHook(hook).isEditing).toBe(false);
883 expect(promptOf(THREAD_A)).toBe("");
884 });
885
886 it.each([
887 { transition: "cancel", result: "Success" },
888 { transition: "recover", result: "Failure" },
889 { transition: "replace", result: "Success" },
890 ] as const)(
891 "settles saved attachments after $transition and $result",
892 async ({ transition, result }) => {
893 const { hook } = setup();
894 let finishSave!: (result: { readonly _tag: "Success" | "Failure" }) => void;
895 let started!: () => void;
896 const saving = new Promise<{ readonly _tag: "Success" | "Failure" }>((resolve) => {
897 finishSave = resolve;
898 });
899 const requested = new Promise<void>((resolve) => {
900 started = resolve;
901 });
902 mocks.editQueuedRun.mockImplementation(() => {
903 started();
904 return saving;
905 });
906 await using _screen = await render(view(THREAD_A, "queued", hook));
907 await beginChangedEdit(hook);
908 const image = {
909 type: "image" as const,
910 id: "saved-image",
911 name: "image.png",
912 mimeType: "image/png",
913 sizeBytes: 5,
914 file: new File(["image"], "image.png", { type: "image/png" }),
915 previewUrl: "blob:saved-image",
916 };
917 using revoke = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
918 await act(() =>
919 useComposerDraftStore.getState().addImage(requireHook(hook).draftTarget, image),
920 );
921 useAttachmentUploadStore.setState({
922 uploadsByImageId: {
923 [image.id]: { status: "ready", environmentId: ENV, attachmentId: "saved-upload" },
924 },
925 });
926 const target = requireHook(hook).draftTarget;
927 const saved = requireHook(hook).saveEdit(
928 { ...savedContent("changed"), images: [image] },
929 () => {},
930 );
931 await act(() => requested);
932 expect(requireHook(hook).isSaving).toBe(true);
933 if (transition === "cancel") await act(() => requireHook(hook).cancelEdit());
934 if (transition === "recover") await act(() => setRuns(THREAD_A, "running"));
935 if (transition === "replace") {
936 await beginChangedEdit(hook);
937 await act(() =>
938 useComposerDraftStore.getState().addImage(requireHook(hook).draftTarget, image),
939 );
940 }
941 expect(readAttachmentUpload(image.id)).toBeDefined();
942 expect(revoke).not.toHaveBeenCalled();
943 finishSave({ _tag: result });
944 await act(() => saved);
945 if (transition === "cancel") {
946 expect(readAttachmentUpload(image.id)).toBeUndefined();
947 expect(revoke).toHaveBeenCalledWith(image.previewUrl);
948 expect(useComposerDraftStore.getState().getComposerDraft(target)).toBeNull();
949 } else {
950 expect(readAttachmentUpload(image.id)).toBeDefined();
951 expect(revoke).not.toHaveBeenCalled();
952 const owner = transition === "recover" ? THREAD_A : target;
953 expect(useComposerDraftStore.getState().getComposerDraft(owner)?.images).toEqual([image]);
954 }
955 },
956 );
957
958 it("leaves a newer edit alone when a save from before navigation finishes", async () => {
959 const { hook } = setup();
960 let finishSave: (result: { readonly _tag: "Success" }) => void = () => {};
961 mocks.editQueuedRun.mockReturnValue(
962 new Promise((resolve) => {
963 finishSave = resolve;
964 }),
965 );
966 await using screen = await render(view(THREAD_A, "queued", hook));
967 await beginChangedEdit(hook);
968 // Not inside act(): act would hold the rerenders until the save settles.
969 const saved = requireHook(hook).saveEdit(savedContent("changed"), () => {});
970 await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
971
972 // Leaving the thread unmounts the chat view; coming back mounts a new one.
973 await screen.rerender(<AppAtomRegistryProvider>{null}</AppAtomRegistryProvider>);
974 await screen.rerender(view(THREAD_A, "queued", hook));
975 expect(requireHook(hook).isSaving).toBe(true);
976 await beginChangedEdit(hook);
977 await act(() =>
978 useComposerDraftStore.getState().setPrompt(requireHook(hook).draftTarget, "newer"),
979 );
980
981 finishSave({ _tag: "Success" });
982 await act(() => saved);
983
984 expect(requireHook(hook).editingRunId).toBe(RUN);
985 expect(requireHook(hook).isSaving).toBe(false);
986 expect(
987 useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt,
988 ).toBe("newer");
989 });
990});
991
992it.each([false, true])(
993 "pins a following queued message only after a model pick: %s",
994 async (pick) => {
995 const { hook } = setup();
996 mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" });
997 await using _screen = await render(
998 view(THREAD_A, "queued", hook, [
999 { id: MessageId.make("message-1"), followsThreadSelection: true },
1000 ]),
1001 );
1002 await beginChangedEdit(hook);
1003 const selection = { instanceId: ProviderInstanceId.make("codex"), model: "chosen-model" };
1004 const target = requireHook(hook).draftTarget;
1005 expect(useComposerDraftStore.getState().getComposerDraft(target)?.activeProvider).toBeNull();
1006 if (pick)
1007 await act(() =>
1008 useComposerDraftStore.getState().setModelSelection(target, selection, { explicit: true }),
1009 );
1010 await requireHook(hook).saveEdit(
1011 { ...savedContent("changed"), modelSelection: selection },
1012 () => {},
1013 );
1014 expect(mocks.editQueuedRun).toHaveBeenCalledWith(
1015 expect.objectContaining({
1016 input: expect.objectContaining(
1017 pick ? { modelSelection: selection } : { threadId: THREAD_A.threadId },
1018 ),
1019 }),
1020 );
1021 if (!pick)
1022 expect(mocks.editQueuedRun.mock.calls[0]?.[0]).toEqual(
1023 expect.objectContaining({
1024 input: expect.not.objectContaining({ modelSelection: expect.anything() }),
1025 }),
1026 );
1027 },
1028);