Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useQueuedRunEdit.browser.test.tsx

694 lines25.3 KB

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