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

useQueuedRunEdit.browser.test.tsx

349 lines12.3 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 { 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;
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;
80​
81function setRuns(ref: ScopedThreadRef, status: string) {
82 appAtomRegistry.set(mocks.threadRuns(runsKey(ref)), [{ id: RUN, status }]);
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 isSendBusy={result.isSaving}
115 sendDisabledReason={null}
116 isEnvironmentUnavailable={false}
117 isPreparingWorktree={false}
118 hasSendableContent={sendState.hasSendableContent}
119 isEditingQueuedMessage
120 onSubmitMessage={() => void result.saveEdit(savedContent(draft.prompt), () => {})}
121 onPreviousPendingQuestion={() => {}}
122 onInterrupt={() => {}}
123 />
124 ) : null;
126​
127function view(threadRef: ScopedThreadRef, runStatus: string, hook: { current: HookResult | null }) {
128 return (
129 <AppAtomRegistryProvider>
130 <Harness threadRef={threadRef} runStatus={runStatus} hookRef={hook} />
131 </AppAtomRegistryProvider>
132 );
134​
135function setup() {
136 mocks.editQueuedRun.mockReset();
137 useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} });
138 setRuns(THREAD_A, "queued");
139 setRuns(THREAD_B, "queued");
140 return { hook: { current: null as HookResult | null } };
142​
143function requireHook(hook: { current: HookResult | null }): HookResult {
144 if (hook.current === null) throw new Error("hook did not render");
145 return hook.current;
147​
148async function beginChangedEdit(hook: { current: HookResult | null }) {
149 await act(() =>
150 requireHook(hook).beginEdit({
151 runId: RUN,
152 messageId: MessageId.make("message-1"),
153 text: "original",
154 attachments: [],
155 }),
156 );
157 await act(() =>
158 useComposerDraftStore.getState().setPrompt(requireHook(hook).draftTarget, "changed"),
159 );
161​
162const savedContent = (prompt: string) => ({
163 prompt,
164 images: [],
165 files: [],
166 terminalContexts: [],
167 reviewComments: [],
168 previewAnnotations: [],
169 threadContexts: [],
170 environmentContexts: [],
171});
172​
173const promptOf = (ref: ScopedThreadRef) =>
174 useComposerDraftStore.getState().getComposerDraft(ref)?.prompt ?? "";
175​
176describe("useQueuedRunEdit", () => {
177 it.each(["", "Ultrathink:\n"])(
178 "opens attachment-only edits without the placeholder and preserves effort on save (%j)",
179 async (prefix) => {
180 const { hook } = setup();
181 mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" });
182 await using screen = await render(view(THREAD_A, "queued", hook));
183 using toast = vi.spyOn(toastManager, "add");
184 const attachments = [
185 {
186 type: "image" as const,
187 id: ChatAttachmentId.make("kept"),
188 name: "kept.png",
189 mimeType: "image/png",
190 sizeBytes: 10,
191 },
192 ];
193 const request = {
194 runId: RUN,
195 messageId: MessageId.make("message-1"),
196 text: prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
197 attachments,
198 };
199 await act(() => requireHook(hook).beginEdit(request));
200 expect(
201 useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt ??
202 "",
203 ).toBe(prefix.trimEnd());
204 expect(requireHook(hook).editingAttachments?.map(({ attachment }) => attachment)).toEqual(
205 attachments,
206 );
207 await act(() =>
208 useComposerDraftStore
209 .getState()
210 .setRuntimeMode(requireHook(hook).draftTarget, "full-access"),
211 );
212 await act(() => setRuns(THREAD_A, "running"));
213 expect(toast).not.toHaveBeenCalled();
214 expect(requireHook(hook).isEditing).toBe(false);
215 await act(() => setRuns(THREAD_A, "queued"));
216 await act(() => requireHook(hook).beginEdit(request));
217 const update = screen.getByRole("button", { name: "Update queued message" });
218 await expect.element(update).toBeEnabled();
219 await update.click();
220 await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
221 expect(mocks.editQueuedRun).toHaveBeenCalledWith(
222 expect.objectContaining({
223 input: expect.objectContaining({
224 text: prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
225 edit: expect.objectContaining({ attachments }),
226 }),
227 }),
228 );
229 },
230 );
231​
232 it("saves an effort-only prompt without claiming removed attachments remain", async () => {
233 const { hook } = setup();
234 mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" });
235 await using screen = await render(view(THREAD_A, "queued", hook));
236 await act(() =>
237 requireHook(hook).beginEdit({
238 runId: RUN,
239 messageId: MessageId.make("message-1"),
240 text: `Ultrathink:\n${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`,
241 attachments: [
242 {
243 type: "image",
244 id: ChatAttachmentId.make("removed"),
245 name: "removed.png",
246 mimeType: "image/png",
247 sizeBytes: 10,
248 },
249 ],
250 }),
251 );
252 await act(() => requireHook(hook).removeEditingAttachment("removed"));
253 await screen.getByRole("button", { name: "Update queued message" }).click();
254 await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
255 expect(mocks.editQueuedRun).toHaveBeenCalledWith(
256 expect.objectContaining({
257 input: expect.objectContaining({
258 text: "Ultrathink:",
259 edit: expect.objectContaining({ attachments: [] }),
260 }),
261 }),
262 );
263 });
264​
265 it("keeps an open edit when the user leaves the thread and comes back", async () => {
266 const { hook } = setup();
267 await using screen = await render(view(THREAD_A, "queued", hook));
268 await beginChangedEdit(hook);
269​
270 await screen.rerender(view(THREAD_B, "queued", hook));
271 expect(requireHook(hook).isEditing).toBe(false);
272 await screen.rerender(view(THREAD_A, "queued", hook));
273​
274 expect(requireHook(hook).editingRunId).toBe(RUN);
275 expect(
276 useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt,
277 ).toBe("changed");
278 });
279​
280 it("moves a changed edit into the thread draft when its run starts while the user is away", async () => {
281 const { hook } = setup();
282 await using screen = await render(view(THREAD_A, "queued", hook));
283 await beginChangedEdit(hook);
284​
285 await screen.rerender(view(THREAD_B, "queued", hook));
286 expect(promptOf(THREAD_A)).toBe("");
287 await act(() => setRuns(THREAD_A, "running"));
288​
289 expect(promptOf(THREAD_A)).toBe("changed");
290 });
291​
292 it("does not copy a saved edit into the thread draft when the run starts mid-save", async () => {
293 const { hook } = setup();
294 let finishSave: (result: { readonly _tag: "Success" }) => void = () => {};
295 mocks.editQueuedRun.mockReturnValue(
296 new Promise((resolve) => {
297 finishSave = resolve;
298 }),
299 );
300 await using screen = await render(view(THREAD_A, "queued", hook));
301 await beginChangedEdit(hook);
302​
303 // Not inside act(): act would hold the projection update until the save settles.
304 const saved = requireHook(hook).saveEdit(savedContent("changed"), () => {});
305 await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
306 // The server applied the edit and then started the run; the projection
307 // reports the start before the edit's acknowledgement arrives.
308 await act(() => setRuns(THREAD_A, "running"));
309 await screen.rerender(view(THREAD_A, "running", hook));
310 finishSave({ _tag: "Success" });
311 await act(() => saved);
312​
313 expect(requireHook(hook).isEditing).toBe(false);
314 expect(promptOf(THREAD_A)).toBe("");
315 });
316​
317 it("leaves a newer edit alone when a save from before navigation finishes", async () => {
318 const { hook } = setup();
319 let finishSave: (result: { readonly _tag: "Success" }) => void = () => {};
320 mocks.editQueuedRun.mockReturnValue(
321 new Promise((resolve) => {
322 finishSave = resolve;
323 }),
324 );
325 await using screen = await render(view(THREAD_A, "queued", hook));
326 await beginChangedEdit(hook);
327 // Not inside act(): act would hold the rerenders until the save settles.
328 const saved = requireHook(hook).saveEdit(savedContent("changed"), () => {});
329 await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
330​
331 // Leaving the thread unmounts the chat view; coming back mounts a new one.
332 await screen.rerender(<AppAtomRegistryProvider>{null}</AppAtomRegistryProvider>);
333 await screen.rerender(view(THREAD_A, "queued", hook));
334 expect(requireHook(hook).isSaving).toBe(true);
335 await beginChangedEdit(hook);
336 await act(() =>
337 useComposerDraftStore.getState().setPrompt(requireHook(hook).draftTarget, "newer"),
338 );
339​
340 finishSave({ _tag: "Success" });
341 await act(() => saved);
342​
343 expect(requireHook(hook).editingRunId).toBe(RUN);
344 expect(requireHook(hook).isSaving).toBe(false);
345 expect(
346 useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt,
347 ).toBe("newer");
348 });
349});