Open History to see the last commit
1import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
2import {
3 EnvironmentId,
4 ChatAttachmentId,
5 MessageId,
6 RunId,
7 ThreadId,
8 type ScopedThreadRef,
9} from "@t3tools/contracts";
10import { useImperativeHandle, type RefObject } from "react";
11import { describe, expect, it, vi } from "vite-plus/test";
12import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
13import { toastManager } from "../ui/toast";
14
15import { act, render } from "../../../test/render";
16import { useComposerDraftStore, useComposerThreadDraft } from "../../composerDraftStore";
17import { deriveComposerSendState } from "../ChatView.logic";
18import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
19import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry";
20import { useQueuedRunEdit } from "./useQueuedRunEdit";
21
22interface RunStatus {
23 readonly id: RunId;
24 readonly status: string;
25}
26
27const mocks = await vi.hoisted(async () => {
28 const { Atom } = await import("effect/reactivity");
29 return {
30 editQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" | "Failure" }>>(),
31 // The projection's runs per thread, written by each test to stand in for the server.
32 threadRuns: Atom.family((_key: string) =>
33 Atom.make<ReadonlyArray<RunStatus> | null>(null).pipe(Atom.keepAlive),
34 ),
35 };
36});
37
38vi.mock("../../state/use-atom-command", () => ({
39 useAtomCommand: () => mocks.editQueuedRun,
40}));
41
42vi.mock("../../hooks/useSettings", () => ({
43 useEnvironmentIdentificationMode: () => "none",
44}));
45
46const runsKey = (ref: ScopedThreadRef) => `${ref.environmentId}:${ref.threadId}`;
47
48vi.mock("../../state/threads", async () => {
49 const { Atom } = await import("effect/reactivity");
50 const key = (ref: ScopedThreadRef) => `${ref.environmentId}:${ref.threadId}`;
51 return {
52 threadEnvironment: {
53 snapshotAtom: () => Atom.make(null),
54 editQueuedRun: {},
55 },
56 environmentThreadDetails: {
57 statusAtom: () => Atom.make("ready"),
58 quietThreadAtom: (ref: ScopedThreadRef) =>
59 Atom.make((get) => {
60 const runs = get(mocks.threadRuns(key(ref)));
61 return runs === null ? null : { projection: { runs } };
62 }),
63 },
64 environmentThreadShells: {
65 threadShellAtom: () => Atom.make(null),
66 },
67 };
68});
69
70const ENV = EnvironmentId.make("env-1");
71const THREAD_A: ScopedThreadRef = { environmentId: ENV, threadId: ThreadId.make("thread-a") };
72const THREAD_B: ScopedThreadRef = { environmentId: ENV, threadId: ThreadId.make("thread-b") };
73const RUN = RunId.make("run-1");
74
75type HookResult = ReturnType<typeof useQueuedRunEdit>;
76
77function projection(runs: ReadonlyArray<RunStatus>) {
78 return { runs, messages: [] } as unknown as ThreadStructure;
79}
80
81function setRuns(ref: ScopedThreadRef, status: string) {
82 appAtomRegistry.set(mocks.threadRuns(runsKey(ref)), [{ id: RUN, status }]);
83}
84
85function Harness(props: {
86 readonly threadRef: ScopedThreadRef;
87 readonly runStatus: string;
88 readonly hookRef: RefObject<HookResult | null>;
89}) {
90 const result = useQueuedRunEdit({
91 environmentId: ENV,
92 routeThreadRef: props.threadRef,
93 threadDraftTarget: props.threadRef,
94 activeThreadId: props.threadRef.threadId,
95 serverProjection: projection([{ id: RUN, status: props.runStatus }]),
96 promptRef: { current: "" },
97 composerRef: { current: null },
98 });
99 useImperativeHandle(props.hookRef, () => result);
100 const draft = useComposerThreadDraft(result.draftTarget);
101 const sendState = deriveComposerSendState({
102 prompt: draft.prompt,
103 imageCount: draft.images.length + draft.files.length,
104 existingAttachmentCount: result.editingAttachments?.length ?? 0,
105 terminalContexts: draft.terminalContexts,
106 });
107 return result.isEditing ? (
108 <ComposerPrimaryActions
109 compact={false}
110 canOperateThread
111 pendingAction={null}
112 isRunning={false}
113 canInterrupt={false}
114 showPlanFollowUpPrompt={false}
115 promptHasText={draft.prompt.trim().length > 0}
116 isSendBusy={result.isSaving}
117 sendDisabledReason={null}
118 isEnvironmentUnavailable={false}
119 isPreparingWorktree={false}
120 hasSendableContent={sendState.hasSendableContent}
121 isEditingQueuedMessage
122 onSubmitMessage={() => void result.saveEdit(savedContent(draft.prompt), () => {})}
123 onPreviousPendingQuestion={() => {}}
124 onInterrupt={() => {}}
125 onImplementPlanInNewThread={() => {}}
126 />
127 ) : null;
128}
129
130function view(threadRef: ScopedThreadRef, runStatus: string, hook: { current: HookResult | null }) {
131 return (
132 <AppAtomRegistryProvider>
133 <Harness threadRef={threadRef} runStatus={runStatus} hookRef={hook} />
134 </AppAtomRegistryProvider>
135 );
136}
137
138function setup() {
139 mocks.editQueuedRun.mockReset();
140 useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} });
141 setRuns(THREAD_A, "queued");
142 setRuns(THREAD_B, "queued");
143 return { hook: { current: null as HookResult | null } };
144}
145
146function requireHook(hook: { current: HookResult | null }): HookResult {
147 if (hook.current === null) throw new Error("hook did not render");
148 return hook.current;
149}
150
151async function beginChangedEdit(hook: { current: HookResult | null }) {
152 await act(() =>
153 requireHook(hook).beginEdit({
154 runId: RUN,
155 messageId: MessageId.make("message-1"),
156 text: "original",
157 attachments: [],
158 }),
159 );
160 await act(() =>
161 useComposerDraftStore.getState().setPrompt(requireHook(hook).draftTarget, "changed"),
162 );
163}
164
165const savedContent = (prompt: string) => ({
166 prompt,
167 images: [],
168 files: [],
169 terminalContexts: [],
170 reviewComments: [],
171 previewAnnotations: [],
172 threadContexts: [],
173 environmentContexts: [],
174});
175
176const promptOf = (ref: ScopedThreadRef) =>
177 useComposerDraftStore.getState().getComposerDraft(ref)?.prompt ?? "";
178
179describe("useQueuedRunEdit", () => {
180 it.each(["", "Ultrathink:\n"])(
181 "opens attachment-only edits without the placeholder and preserves effort on save (%j)",
182 async (prefix) => {
183 const { hook } = setup();
184 mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" });
185 await using screen = await render(view(THREAD_A, "queued", hook));
186 using toast = vi.spyOn(toastManager, "add");
187 const attachments = [
188 {
189 type: "image" as const,
190 id: ChatAttachmentId.make("kept"),
191 name: "kept.png",
192 mimeType: "image/png",
193 sizeBytes: 10,
194 },
195 ];
196 const request = {
197 runId: RUN,
198 messageId: MessageId.make("message-1"),
199 text: prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
200 attachments,
201 };
202 await act(() => requireHook(hook).beginEdit(request));
203 expect(
204 useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt ??
205 "",
206 ).toBe(prefix.trimEnd());
207 expect(requireHook(hook).editingAttachments?.map(({ attachment }) => attachment)).toEqual(
208 attachments,
209 );
210 await act(() =>
211 useComposerDraftStore
212 .getState()
213 .setRuntimeMode(requireHook(hook).draftTarget, "full-access"),
214 );
215 await act(() => setRuns(THREAD_A, "running"));
216 expect(toast).not.toHaveBeenCalled();
217 expect(requireHook(hook).isEditing).toBe(false);
218 await act(() => setRuns(THREAD_A, "queued"));
219 await act(() => requireHook(hook).beginEdit(request));
220 const update = screen.getByRole("button", { name: "Update queued message" });
221 await expect.element(update).toBeEnabled();
222 await update.click();
223 await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
224 expect(mocks.editQueuedRun).toHaveBeenCalledWith(
225 expect.objectContaining({
226 input: expect.objectContaining({
227 text: prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
228 edit: expect.objectContaining({ attachments }),
229 }),
230 }),
231 );
232 },
233 );
234
235 it("saves an effort-only prompt without claiming removed attachments remain", async () => {
236 const { hook } = setup();
237 mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" });
238 await using screen = await render(view(THREAD_A, "queued", hook));
239 await act(() =>
240 requireHook(hook).beginEdit({
241 runId: RUN,
242 messageId: MessageId.make("message-1"),
243 text: `Ultrathink:\n${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`,
244 attachments: [
245 {
246 type: "image",
247 id: ChatAttachmentId.make("removed"),
248 name: "removed.png",
249 mimeType: "image/png",
250 sizeBytes: 10,
251 },
252 ],
253 }),
254 );
255 await act(() => requireHook(hook).removeEditingAttachment("removed"));
256 await screen.getByRole("button", { name: "Update queued message" }).click();
257 await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
258 expect(mocks.editQueuedRun).toHaveBeenCalledWith(
259 expect.objectContaining({
260 input: expect.objectContaining({
261 text: "Ultrathink:",
262 edit: expect.objectContaining({ attachments: [] }),
263 }),
264 }),
265 );
266 });
267
268 it("keeps an open edit when the user leaves the thread and comes back", async () => {
269 const { hook } = setup();
270 await using screen = await render(view(THREAD_A, "queued", hook));
271 await beginChangedEdit(hook);
272
273 await screen.rerender(view(THREAD_B, "queued", hook));
274 expect(requireHook(hook).isEditing).toBe(false);
275 await screen.rerender(view(THREAD_A, "queued", hook));
276
277 expect(requireHook(hook).editingRunId).toBe(RUN);
278 expect(
279 useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt,
280 ).toBe("changed");
281 });
282
283 it("moves a changed edit into the thread draft when its run starts while the user is away", async () => {
284 const { hook } = setup();
285 await using screen = await render(view(THREAD_A, "queued", hook));
286 await beginChangedEdit(hook);
287
288 await screen.rerender(view(THREAD_B, "queued", hook));
289 expect(promptOf(THREAD_A)).toBe("");
290 await act(() => setRuns(THREAD_A, "running"));
291
292 expect(promptOf(THREAD_A)).toBe("changed");
293 });
294
295 it("does not copy a saved edit into the thread draft when the run starts mid-save", async () => {
296 const { hook } = setup();
297 let finishSave: (result: { readonly _tag: "Success" }) => void = () => {};
298 mocks.editQueuedRun.mockReturnValue(
299 new Promise((resolve) => {
300 finishSave = resolve;
301 }),
302 );
303 await using screen = await render(view(THREAD_A, "queued", hook));
304 await beginChangedEdit(hook);
305
306 // Not inside act(): act would hold the projection update until the save settles.
307 const saved = requireHook(hook).saveEdit(savedContent("changed"), () => {});
308 await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
309 // The server applied the edit and then started the run; the projection
310 // reports the start before the edit's acknowledgement arrives.
311 await act(() => setRuns(THREAD_A, "running"));
312 await screen.rerender(view(THREAD_A, "running", hook));
313 finishSave({ _tag: "Success" });
314 await act(() => saved);
315
316 expect(requireHook(hook).isEditing).toBe(false);
317 expect(promptOf(THREAD_A)).toBe("");
318 });
319
320 it("leaves a newer edit alone when a save from before navigation finishes", async () => {
321 const { hook } = setup();
322 let finishSave: (result: { readonly _tag: "Success" }) => void = () => {};
323 mocks.editQueuedRun.mockReturnValue(
324 new Promise((resolve) => {
325 finishSave = resolve;
326 }),
327 );
328 await using screen = await render(view(THREAD_A, "queued", hook));
329 await beginChangedEdit(hook);
330 // Not inside act(): act would hold the rerenders until the save settles.
331 const saved = requireHook(hook).saveEdit(savedContent("changed"), () => {});
332 await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
333
334 // Leaving the thread unmounts the chat view; coming back mounts a new one.
335 await screen.rerender(<AppAtomRegistryProvider>{null}</AppAtomRegistryProvider>);
336 await screen.rerender(view(THREAD_A, "queued", hook));
337 expect(requireHook(hook).isSaving).toBe(true);
338 await beginChangedEdit(hook);
339 await act(() =>
340 useComposerDraftStore.getState().setPrompt(requireHook(hook).draftTarget, "newer"),
341 );
342
343 finishSave({ _tag: "Success" });
344 await act(() => saved);
345
346 expect(requireHook(hook).editingRunId).toBe(RUN);
347 expect(requireHook(hook).isSaving).toBe(false);
348 expect(
349 useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt,
350 ).toBe("newer");
351 });
352});