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

useQueuedRunEdit.browser.test.tsx

441 lines16.1 KB

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 {
13 ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
14 threadContextRecord,
15} from "@t3tools/shared/composerContextReferences";
16import { toastManager } from "../ui/toast";
17​
18import { act, render } from "../../../test/render";
19import { useComposerDraftStore, useComposerThreadDraft } from "../../composerDraftStore";
20import { formatInlineContextReference } from "../../lib/composerContextReferences";
21import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "../../lib/terminalContext";
22import {
23 environmentContextRecord,
24 environmentContextReference,
25 threadContextReference,
26} from "../../lib/composerContextRecords";
27import { deriveComposerSendState } from "../ChatView.logic";
28import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
29import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry";
30import { useQueuedRunEdit } from "./useQueuedRunEdit";
31​
32interface RunStatus {
33 readonly id: RunId;
34 readonly status: string;
36​
37const mocks = await vi.hoisted(async () => {
38 const { Atom } = await import("effect/reactivity");
39 return {
40 editQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" | "Failure" }>>(),
41 // The projection's runs per thread, written by each test to stand in for the server.
42 threadRuns: Atom.family((_key: string) =>
43 Atom.make<ReadonlyArray<RunStatus> | null>(null).pipe(Atom.keepAlive),
44 ),
45 };
46});
47​
48vi.mock("../../state/use-atom-command", () => ({
49 useAtomCommand: () => mocks.editQueuedRun,
50}));
51​
52vi.mock("../../hooks/useSettings", () => ({
53 useEnvironmentIdentificationMode: () => "none",
54}));
55​
56const runsKey = (ref: ScopedThreadRef) => `${ref.environmentId}:${ref.threadId}`;
57​
58vi.mock("../../state/threads", async () => {
59 const { Atom } = await import("effect/reactivity");
60 const key = (ref: ScopedThreadRef) => `${ref.environmentId}:${ref.threadId}`;
61 return {
62 threadEnvironment: {
63 snapshotAtom: () => Atom.make(null),
64 editQueuedRun: {},
65 },
66 environmentThreadDetails: {
67 statusAtom: () => Atom.make("ready"),
68 quietThreadAtom: (ref: ScopedThreadRef) =>
69 Atom.make((get) => {
70 const runs = get(mocks.threadRuns(key(ref)));
71 return runs === null ? null : { projection: { runs } };
72 }),
73 },
74 environmentThreadShells: {
75 threadShellAtom: () => Atom.make(null),
76 },
77 };
78});
79​
80const ENV = EnvironmentId.make("env-1");
81const THREAD_A: ScopedThreadRef = { environmentId: ENV, threadId: ThreadId.make("thread-a") };
82const THREAD_B: ScopedThreadRef = { environmentId: ENV, threadId: ThreadId.make("thread-b") };
83const RUN = RunId.make("run-1");
84​
85type HookResult = ReturnType<typeof useQueuedRunEdit>;
86​
87function projection(runs: ReadonlyArray<RunStatus>, messages: ReadonlyArray<unknown>) {
88 return { runs, messages } as unknown as ThreadStructure;
90​
91function setRuns(ref: ScopedThreadRef, status: string) {
92 appAtomRegistry.set(mocks.threadRuns(runsKey(ref)), [{ id: RUN, status }]);
94​
95function Harness(props: {
96 readonly threadRef: ScopedThreadRef;
97 readonly runStatus: string;
98 readonly hookRef: RefObject<HookResult | null>;
99 readonly messages: ReadonlyArray<unknown>;
100}) {
101 const result = useQueuedRunEdit({
102 environmentId: ENV,
103 routeThreadRef: props.threadRef,
104 threadDraftTarget: props.threadRef,
105 activeThreadId: props.threadRef.threadId,
106 serverProjection: projection([{ id: RUN, status: props.runStatus }], props.messages),
107 promptRef: { current: "" },
108 composerRef: { current: null },
109 });
110 useImperativeHandle(props.hookRef, () => result);
111 const draft = useComposerThreadDraft(result.draftTarget);
112 const sendState = deriveComposerSendState({
113 prompt: draft.prompt,
114 imageCount: draft.images.length + draft.files.length,
115 existingAttachmentCount: result.editingAttachments?.length ?? 0,
116 terminalContexts: draft.terminalContexts,
117 });
118 return result.isEditing ? (
119 <ComposerPrimaryActions
120 compact={false}
121 canOperateThread
122 pendingAction={null}
123 isRunning={false}
124 canInterrupt={false}
125 isSendBusy={result.isSaving}
126 sendDisabledReason={null}
127 isEnvironmentUnavailable={false}
128 isPreparingWorktree={false}
129 hasSendableContent={sendState.hasSendableContent}
130 isEditingQueuedMessage
131 onSubmitMessage={() => void result.saveEdit(savedContent(draft.prompt), () => {})}
132 onPreviousPendingQuestion={() => {}}
133 onInterrupt={() => {}}
134 />
135 ) : null;
137​
138function view(
139 threadRef: ScopedThreadRef,
140 runStatus: string,
141 hook: { current: HookResult | null },
142 messages: ReadonlyArray<unknown> = [],
143) {
144 return (
145 <AppAtomRegistryProvider>
146 <Harness threadRef={threadRef} runStatus={runStatus} hookRef={hook} messages={messages} />
147 </AppAtomRegistryProvider>
148 );
150​
151function setup() {
152 mocks.editQueuedRun.mockReset();
153 useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} });
154 setRuns(THREAD_A, "queued");
155 setRuns(THREAD_B, "queued");
156 return { hook: { current: null as HookResult | null } };
158​
159function requireHook(hook: { current: HookResult | null }): HookResult {
160 if (hook.current === null) throw new Error("hook did not render");
161 return hook.current;
163​
164async function beginChangedEdit(hook: { current: HookResult | null }) {
165 await act(() =>
166 requireHook(hook).beginEdit({
167 runId: RUN,
168 messageId: MessageId.make("message-1"),
169 text: "original",
170 attachments: [],
171 }),
172 );
173 await act(() =>
174 useComposerDraftStore.getState().setPrompt(requireHook(hook).draftTarget, "changed"),
175 );
177​
178const savedContent = (prompt: string) => ({
179 prompt,
180 images: [],
181 files: [],
182 terminalContexts: [],
183 reviewComments: [],
184 previewAnnotations: [],
185 threadContexts: [],
186 environmentContexts: [],
187});
188​
189const promptOf = (ref: ScopedThreadRef) =>
190 useComposerDraftStore.getState().getComposerDraft(ref)?.prompt ?? "";
191​
192describe("useQueuedRunEdit", () => {
193 it.each(["", "Ultrathink:\n"])(
194 "opens attachment-only edits without the placeholder and preserves effort on save (%j)",
195 async (prefix) => {
196 const { hook } = setup();
197 mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" });
198 await using screen = await render(view(THREAD_A, "queued", hook));
199 using toast = vi.spyOn(toastManager, "add");
200 const attachments = [
201 {
202 type: "image" as const,
203 id: ChatAttachmentId.make("kept"),
204 name: "kept.png",
205 mimeType: "image/png",
206 sizeBytes: 10,
207 },
208 ];
209 const request = {
210 runId: RUN,
211 messageId: MessageId.make("message-1"),
212 text: prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
213 attachments,
214 };
215 await act(() => requireHook(hook).beginEdit(request));
216 expect(
217 useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt ??
218 "",
219 ).toBe(prefix.trimEnd());
220 expect(requireHook(hook).editingAttachments?.map(({ attachment }) => attachment)).toEqual(
221 attachments,
222 );
223 await act(() =>
224 useComposerDraftStore
225 .getState()
226 .setRuntimeMode(requireHook(hook).draftTarget, "full-access"),
227 );
228 await act(() => setRuns(THREAD_A, "running"));
229 expect(toast).not.toHaveBeenCalled();
230 expect(requireHook(hook).isEditing).toBe(false);
231 await act(() => setRuns(THREAD_A, "queued"));
232 await act(() => requireHook(hook).beginEdit(request));
233 const update = screen.getByRole("button", { name: "Update queued message" });
234 await expect.element(update).toBeEnabled();
235 await update.click();
236 await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
237 expect(mocks.editQueuedRun).toHaveBeenCalledWith(
238 expect.objectContaining({
239 input: expect.objectContaining({
240 text: prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
241 edit: expect.objectContaining({ attachments }),
242 }),
243 }),
244 );
245 },
246 );
247​
248 it("saves an effort-only prompt without claiming removed attachments remain", async () => {
249 const { hook } = setup();
250 mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" });
251 await using screen = await render(view(THREAD_A, "queued", hook));
252 await act(() =>
253 requireHook(hook).beginEdit({
254 runId: RUN,
255 messageId: MessageId.make("message-1"),
256 text: `Ultrathink:\n${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`,
257 attachments: [
258 {
259 type: "image",
260 id: ChatAttachmentId.make("removed"),
261 name: "removed.png",
262 mimeType: "image/png",
263 sizeBytes: 10,
264 },
265 ],
266 }),
267 );
268 await act(() => requireHook(hook).removeEditingAttachment("removed"));
269 await screen.getByRole("button", { name: "Update queued message" }).click();
270 await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
271 expect(mocks.editQueuedRun).toHaveBeenCalledWith(
272 expect.objectContaining({
273 input: expect.objectContaining({
274 text: "Ultrathink:",
275 edit: expect.objectContaining({ attachments: [] }),
276 }),
277 }),
278 );
279 });
280​
281 it("opens an edit with only the thread and machine records its text still mentions", async () => {
282 const { hook } = setup();
283 const thread = threadContextRecord(THREAD_B, "Support Any File Uploads");
284 const machine = environmentContextRecord(ENV, "Build box");
285 const unreferenced = threadContextRecord(THREAD_A, "Removed earlier");
286 const messageId = MessageId.make("message-1");
287 const text = `wait for ${formatInlineContextReference(threadContextReference(thread))} on ${formatInlineContextReference(environmentContextReference(machine))}`;
288 const messages = [
289 { id: messageId, text, context: { version: 1, records: [thread, machine, unreferenced] } },
290 ];
291 await using _screen = await render(view(THREAD_A, "queued", hook, messages));
292​
293 await act(() => requireHook(hook).beginEdit({ runId: RUN, messageId, text, attachments: [] }));
294​
295 const draft = useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget);
296 expect(draft?.prompt).toBe(text);
297 expect(draft?.threadContexts).toEqual([thread]);
298 expect(draft?.environmentContexts).toEqual([machine]);
299 });
300​
301 it("saves only the thread mentions still in the edited message", async () => {
302 const { hook } = setup();
303 mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" });
304 const kept = threadContextRecord(THREAD_B, "Kept");
305 const removed = threadContextRecord(THREAD_A, "Removed");
306 const messageId = MessageId.make("message-1");
307 const text = [kept, removed]
308 .map((record) => formatInlineContextReference(threadContextReference(record)))
309 .join(" and ");
310 const messages = [{ id: messageId, text, context: { version: 1, records: [kept, removed] } }];
311 await using _screen = await render(view(THREAD_A, "queued", hook, messages));
312 await act(() => requireHook(hook).beginEdit({ runId: RUN, messageId, text, attachments: [] }));
313 const target = requireHook(hook).draftTarget;
314 await act(() => useComposerDraftStore.getState().setThreadContexts(target, [kept]));
315​
316 const draft = useComposerDraftStore.getState().getComposerDraft(target);
317 await requireHook(hook).saveEdit(
318 { ...savedContent(draft?.prompt ?? ""), threadContexts: draft?.threadContexts ?? [] },
319 () => {},
320 );
321​
322 expect(mocks.editQueuedRun).toHaveBeenCalledWith(
323 expect.objectContaining({
324 input: expect.objectContaining({
325 edit: expect.objectContaining({ context: { version: 1, records: [kept] } }),
326 }),
327 }),
328 );
329 });
330​
331 it("adds terminal context to the queued message being edited", async () => {
332 const { hook } = setup();
333 await using _screen = await render(view(THREAD_A, "queued", hook));
334 await beginChangedEdit(hook);
335 const target = requireHook(hook).draftTarget;
336 const inserted = useComposerDraftStore.getState().insertTerminalContext(
337 target,
338 `changed${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}`,
339 {
340 id: "terminal-context-1",
341 threadId: THREAD_A.threadId,
342 createdAt: "2026-01-01T00:00:00.000Z",
343 terminalId: "default",
344 terminalLabel: "Terminal 1",
345 lineStart: 3,
346 lineEnd: 3,
347 text: "hello",
348 },
349 0,
350 );
351 expect(inserted).toBe(true);
352 expect(
353 useComposerDraftStore.getState().getComposerDraft(target)?.terminalContexts,
354 ).toHaveLength(1);
355 });
356​
357 it("keeps an open edit when the user leaves the thread and comes back", async () => {
358 const { hook } = setup();
359 await using screen = await render(view(THREAD_A, "queued", hook));
360 await beginChangedEdit(hook);
361​
362 await screen.rerender(view(THREAD_B, "queued", hook));
363 expect(requireHook(hook).isEditing).toBe(false);
364 await screen.rerender(view(THREAD_A, "queued", hook));
365​
366 expect(requireHook(hook).editingRunId).toBe(RUN);
367 expect(
368 useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt,
369 ).toBe("changed");
370 });
371​
372 it("moves a changed edit into the thread draft when its run starts while the user is away", async () => {
373 const { hook } = setup();
374 await using screen = await render(view(THREAD_A, "queued", hook));
375 await beginChangedEdit(hook);
376​
377 await screen.rerender(view(THREAD_B, "queued", hook));
378 expect(promptOf(THREAD_A)).toBe("");
379 await act(() => setRuns(THREAD_A, "running"));
380​
381 expect(promptOf(THREAD_A)).toBe("changed");
382 });
383​
384 it("does not copy a saved edit into the thread draft when the run starts mid-save", async () => {
385 const { hook } = setup();
386 let finishSave: (result: { readonly _tag: "Success" }) => void = () => {};
387 mocks.editQueuedRun.mockReturnValue(
388 new Promise((resolve) => {
389 finishSave = resolve;
390 }),
391 );
392 await using screen = await render(view(THREAD_A, "queued", hook));
393 await beginChangedEdit(hook);
394​
395 // Not inside act(): act would hold the projection update until the save settles.
396 const saved = requireHook(hook).saveEdit(savedContent("changed"), () => {});
397 await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
398 // The server applied the edit and then started the run; the projection
399 // reports the start before the edit's acknowledgement arrives.
400 await act(() => setRuns(THREAD_A, "running"));
401 await screen.rerender(view(THREAD_A, "running", hook));
402 finishSave({ _tag: "Success" });
403 await act(() => saved);
404​
405 expect(requireHook(hook).isEditing).toBe(false);
406 expect(promptOf(THREAD_A)).toBe("");
407 });
408​
409 it("leaves a newer edit alone when a save from before navigation finishes", async () => {
410 const { hook } = setup();
411 let finishSave: (result: { readonly _tag: "Success" }) => void = () => {};
412 mocks.editQueuedRun.mockReturnValue(
413 new Promise((resolve) => {
414 finishSave = resolve;
415 }),
416 );
417 await using screen = await render(view(THREAD_A, "queued", hook));
418 await beginChangedEdit(hook);
419 // Not inside act(): act would hold the rerenders until the save settles.
420 const saved = requireHook(hook).saveEdit(savedContent("changed"), () => {});
421 await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
422​
423 // Leaving the thread unmounts the chat view; coming back mounts a new one.
424 await screen.rerender(<AppAtomRegistryProvider>{null}</AppAtomRegistryProvider>);
425 await screen.rerender(view(THREAD_A, "queued", hook));
426 expect(requireHook(hook).isSaving).toBe(true);
427 await beginChangedEdit(hook);
428 await act(() =>
429 useComposerDraftStore.getState().setPrompt(requireHook(hook).draftTarget, "newer"),
430 );
431​
432 finishSave({ _tag: "Success" });
433 await act(() => saved);
434​
435 expect(requireHook(hook).editingRunId).toBe(RUN);
436 expect(requireHook(hook).isSaving).toBe(false);
437 expect(
438 useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt,
439 ).toBe("newer");
440 });
441});