Open History to see the last commit
1import { createMemoryHistory } from "@tanstack/react-router";
2import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
3import { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";
4import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
5import type * as Context from "effect/Context";
6import { expect, it, vi } from "vite-plus/test";
7import { cdp, page, userEvent } from "vite-plus/test/browser";
8
9import { AppRoot } from "~/AppRoot";
10// The route loads ChatView lazily, and its first transform (React Compiler over ~4k lines)
11// takes 6-11s; importing it here keeps that out of the test's timeout.
12import "~/components/ChatView";
13import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
14import { selectThreadDiffPanelSelection, useDiffPanelStore } from "~/diffPanelStore";
15import { __setClientSettingsForTests } from "~/hooks/useSettings";
16import { environmentContextRecord } from "~/lib/composerContextRecords";
17import { usePromptStashStore } from "~/promptStashStore";
18import { useRightPanelStore } from "~/rightPanelStore";
19import { getRouter } from "~/router";
20import { appAtomRegistry } from "~/rpc/atomRegistry";
21import { environmentThreadDetails } from "~/state/threads";
22import {
23 ENVIRONMENT_ID,
24 PROJECT_ID,
25 answerAssetUrls,
26 assistantItem,
27 dispatchedCommands,
28 emitThreadEvent,
29 hasPendingAssetUrl,
30 installFakeEnvironment,
31 rejectPendingCommand,
32 threadWithHistory,
33 threadWithQuestion,
34 type FakeDriver,
35} from "../../test/fakeEnvironment";
36import { act, fakeTimers, render } from "../../test/render";
37
38// The socket is the only fake layer; see test/appScenarios.renders.tsx.
39vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => {
40 const [actual, { fakeDriver }, Layer] = await Promise.all([
41 importOriginal<{ readonly ConnectionDriver: Context.Key<unknown, FakeDriver> }>(),
42 import("../../test/fakeEnvironment"),
43 import("effect/Layer"),
44 ]);
45 return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) };
46});
47
48vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({
49 ...(await original()),
50 trackRpcRequestSent: () => {},
51}));
52
53it("a machine chip stashed in one thread restores with its machine in another", async () => {
54 const other = threadWithHistory("thread-stash-restore", 1);
55 const asking = threadWithQuestion("thread-stash-question", "Which file should change?");
56 using _environment = installFakeEnvironment([other, asking]);
57 __setClientSettingsForTests({
58 ...DEFAULT_CLIENT_SETTINGS,
59 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
60 });
61 const draftId = DraftId.make("draft-stash-machine");
62 const machine = environmentContextRecord(EnvironmentId.make("environment-build"), "Build box");
63 const drafts = useComposerDraftStore.getState();
64 drafts.setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
65 threadId: ThreadId.make("thread-stash-machine"),
66 });
67 drafts.setPrompt(draftId, "Deploy on ");
68 drafts.addEnvironmentContexts(draftId, [machine]);
69 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
70 await router.load();
71 await using _app = await render(<AppRoot router={router} />, {
72 // AppRoot brings its own router.
73 router: false,
74 });
75 const editor = page.getByTestId("composer-editor");
76 const pressStashShortcut = async () => {
77 await userEvent.click(editor);
78 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
79 };
80 await vi.waitFor(() => expect(editor.element().textContent).toContain("Deploy on"));
81 // A draft can't stash until the shell snapshot lists its project.
82 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
83 await pressStashShortcut();
84 await vi.waitFor(() => expect(usePromptStashStore.getState().entries).toHaveLength(1));
85
86 // An answer carries no machines, so an open question refuses the restore and keeps the entry.
87 await router.navigate({ to: `/${ENVIRONMENT_ID}/${asking.id}` });
88 await expect.element(page.getByText("Which file should change?")).toBeVisible();
89 await userEvent.click(page.getByRole("button", { name: /^Stashed prompts/ }));
90 await userEvent.click(page.getByRole("button", { name: /^Restore stashed prompt/ }));
91 await vi.waitFor(() =>
92 expect(document.body.textContent).toContain("Stashed machines can't go in an answer"),
93 );
94 expect(usePromptStashStore.getState().entries).toHaveLength(1);
95
96 await router.navigate({ to: `/${ENVIRONMENT_ID}/${other.id}` });
97 await expect.element(page.getByText("Answer 0 for thread-stash-restore.")).toBeVisible();
98 await pressStashShortcut();
99
100 await vi.waitFor(() => expect(editor.element().textContent).toContain("Deploy on"));
101 expect(
102 useComposerDraftStore.getState().getComposerDraft(scopeThreadRef(ENVIRONMENT_ID, other.id))
103 ?.environmentContexts,
104 ).toEqual([machine]);
105 expect(
106 useComposerDraftStore.getState().getComposerDraft(draftId)?.environmentContexts ?? [],
107 ).toEqual([]);
108});
109
110it("a question that opens while a stashed file is checked keeps a machine stash", async () => {
111 const thread = threadWithHistory("thread-stash-late-question", 1);
112 const asking = threadWithQuestion("thread-stash-late-question", "Which file should change?");
113 const [request] = asking.runtimeRequests ?? [];
114 const question = asking.items.at(-1);
115 if (!request || !question) throw new Error("threadWithQuestion has no question");
116 using _environment = installFakeEnvironment([thread]);
117 __setClientSettingsForTests({
118 ...DEFAULT_CLIENT_SETTINGS,
119 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
120 });
121 usePromptStashStore.getState().stashEntry({
122 id: "stash-late-question",
123 createdAt: "2026-01-01T00:00:00.000Z",
124 prompt: "Deploy on ",
125 attachments: [],
126 files: [
127 {
128 id: "file-notes",
129 name: "notes.txt",
130 mimeType: "text/plain",
131 sizeBytes: 5,
132 attachmentId: "attachment-notes",
133 environmentId: ENVIRONMENT_ID,
134 },
135 ],
136 droppedImageNames: [],
137 records: [environmentContextRecord(EnvironmentId.make("environment-build"), "Build box")],
138 });
139 const router = getRouter(
140 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
141 );
142 await router.load();
143 await using _app = await render(<AppRoot router={router} />, {
144 // AppRoot brings its own router.
145 router: false,
146 });
147 await expect.element(page.getByText("Answer 0 for thread-stash-late-question.")).toBeVisible();
148 await userEvent.click(page.getByRole("button", { name: /^Stashed prompts/ }));
149 await userEvent.click(page.getByRole("button", { name: /^Restore stashed prompt/ }));
150
151 // The question opens while the restore still waits on the server's file check.
152 await vi.waitFor(() => expect(hasPendingAssetUrl()).toBe(true));
153 await emitThreadEvent(thread.id, { type: "turn-item.updated", payload: question });
154 await emitThreadEvent(thread.id, { type: "runtime-request.updated", payload: request });
155 await expect.element(page.getByText("Which file should change?")).toBeVisible();
156 await answerAssetUrls();
157
158 await vi.waitFor(() =>
159 expect(document.body.textContent).toContain("Stashed machines can't go in an answer"),
160 );
161 expect(usePromptStashStore.getState().entries).toHaveLength(1);
162 usePromptStashStore.getState().takeEntry("stash-late-question");
163});
164
165it("a new draft does not load its reserved thread before the server lists it", async () => {
166 using _environment = installFakeEnvironment([]);
167 using fetchSpy = vi.spyOn(globalThis, "fetch");
168 __setClientSettingsForTests({
169 ...DEFAULT_CLIENT_SETTINGS,
170 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
171 });
172 const draftId = DraftId.make("draft-27443");
173 const threadId = ThreadId.make("thread-27443");
174 useComposerDraftStore
175 .getState()
176 .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, { threadId });
177
178 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
179 await router.load();
180 await using _app = await render(<AppRoot router={router} />, {
181 // AppRoot brings its own router.
182 router: false,
183 });
184 await expect.element(page.getByTestId("composer-editor")).toBeVisible();
185 // The shell snapshot has arrived once the sidebar lists the project, so the connection is up.
186 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
187
188 const threadRequests = fetchSpy.mock.calls
189 .map(([input]) => String(input instanceof Request ? input.url : input))
190 .filter((url) => url.includes(`/api/orchestration/threads/${threadId}/`));
191 // A 404 here marks the thread deleted, and the view never loads it once the send creates it.
192 expect(threadRequests).toEqual([]);
193});
194
195it("opens the thread actions menu for an older settled thread the shell leaves out", async () => {
196 const thread = { ...threadWithHistory("older-settled", 1), olderSettled: true as const };
197 using _environment = installFakeEnvironment([thread]);
198 __setClientSettingsForTests({
199 ...DEFAULT_CLIENT_SETTINGS,
200 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
201 });
202
203 const router = getRouter(
204 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
205 );
206 await router.load();
207 await using _app = await render(<AppRoot router={router} />, {
208 // AppRoot brings its own router.
209 router: false,
210 });
211 await expect.element(page.getByText("older-settled: question 0")).toBeVisible();
212
213 await page.getByRole("button", { name: `Thread actions for ${thread.title}` }).click();
214 // Without a bound the poll runs to the test deadline and reports a bare timeout.
215 await expect
216 .element(page.getByRole("menuitem", { name: "Rename thread" }), { timeout: 5_000 })
217 .toBeVisible();
218});
219
220it("retains each thread's diff selection when returning from another thread or Settings", async () => {
221 const a = threadWithHistory("diff-selection-a", 1);
222 const b = threadWithHistory("diff-selection-b", 1);
223 using _environment = installFakeEnvironment([a, b]);
224 __setClientSettingsForTests({
225 ...DEFAULT_CLIENT_SETTINGS,
226 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
227 });
228 const aRef = scopeThreadRef(ENVIRONMENT_ID, a.id);
229 const bRef = scopeThreadRef(ENVIRONMENT_ID, b.id);
230 useRightPanelStore.getState().open(aRef, "diff");
231 useRightPanelStore.getState().open(bRef, "diff");
232 useDiffPanelStore.getState().selectBranchBaseRef(bRef, "origin/release");
233 const router = getRouter(createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${a.id}`] }));
234 await router.load();
235 await using _app = await render(<AppRoot router={router} />, {
236 // AppRoot brings its own router.
237 router: false,
238 });
239 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
240 await act(() => useDiffPanelStore.getState().selectGitScope(aRef, "unstaged"));
241
242 await act(() =>
243 router.navigate({
244 to: "/$environmentId/$threadId",
245 params: { environmentId: ENVIRONMENT_ID, threadId: b.id },
246 }),
247 );
248 await expect.element(page.getByText(`Answer 0 for ${b.id}.`)).toBeVisible();
249 expect(selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, bRef)).toEqual({
250 kind: "branch",
251 baseRef: "origin/release",
252 });
253 await act(() =>
254 router.navigate({
255 to: "/$environmentId/$threadId",
256 params: { environmentId: ENVIRONMENT_ID, threadId: a.id },
257 }),
258 );
259 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
260 expect(selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, aRef)).toEqual({
261 kind: "unstaged",
262 });
263
264 await act(() => useDiffPanelStore.getState().selectTurn(aRef, a.runs[0]!.id));
265 await act(() => router.navigate({ to: "/settings/general" }));
266 await expect
267 .element(page.getByRole("heading", { name: "Time format", exact: true }))
268 .toBeVisible();
269 await act(() =>
270 router.navigate({
271 to: "/$environmentId/$threadId",
272 params: { environmentId: ENVIRONMENT_ID, threadId: a.id },
273 }),
274 );
275 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
276 expect(
277 selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, aRef),
278 ).toMatchObject({
279 kind: "turn",
280 turnId: a.runs[0]!.id,
281 });
282});
283
284it("a stashed prompt ending in a file chip restores with the chip", async () => {
285 using _environment = installFakeEnvironment([]);
286 __setClientSettingsForTests({
287 ...DEFAULT_CLIENT_SETTINGS,
288 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
289 });
290 const draftId = DraftId.make("draft-28338");
291 const drafts = useComposerDraftStore.getState();
292 drafts.setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
293 threadId: ThreadId.make("thread-28338"),
294 });
295 drafts.setPrompt(draftId, "Check [package.json](package.json) ");
296 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
297 await router.load();
298 await using _app = await render(<AppRoot router={router} />, {
299 // AppRoot brings its own router.
300 router: false,
301 });
302 const chip = page.getByRole("button", { name: "Preview package.json" });
303 await expect.element(chip).toBeVisible();
304 // The stash shortcut is a no-op until the shell snapshot lists the project.
305 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
306
307 const editor = page.getByTestId("composer-editor");
308 await userEvent.click(editor);
309 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
310 await expect.element(chip).not.toBeInTheDocument();
311 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
312
313 await vi.waitFor(() => expect(editor.element().textContent).toContain("Check"));
314 expect(editor.element().textContent).not.toContain("[package.json](package.json)");
315 await expect.element(chip).toBeVisible();
316});
317
318it("a rejected send leaves the timeline when a new draft was typed meanwhile", async () => {
319 const thread = threadWithHistory("rejected-send", 1);
320 using _environment = installFakeEnvironment([thread], {
321 acceptCommands: true,
322 holdCommand: (command) => command.type === "message.dispatch",
323 });
324 __setClientSettingsForTests({
325 ...DEFAULT_CLIENT_SETTINGS,
326 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
327 });
328 const router = getRouter(
329 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
330 );
331 await router.load();
332 await using _app = await render(<AppRoot router={router} />, {
333 // AppRoot brings its own router.
334 router: false,
335 });
336 await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible();
337
338 const editor = page.getByTestId("composer-editor");
339 await userEvent.click(editor);
340 await userEvent.keyboard("Failed prompt{Enter}");
341 await vi.waitFor(() =>
342 expect(dispatchedCommands().map((command) => command.type)).toContain("message.dispatch"),
343 );
344 await expect.element(page.getByText("Failed prompt")).toBeVisible();
345 await userEvent.keyboard("Next draft");
346
347 await rejectPendingCommand("Attachment 'sample.png' cannot be sent.");
348
349 await expect.element(page.getByText("Attachment 'sample.png' cannot be sent.")).toBeVisible();
350 await expect.element(page.getByText("Failed prompt")).not.toBeInTheDocument();
351 expect(editor.element().textContent).toContain("Next draft");
352});
353
354it("Enter on an empty prompt resumes an interrupted thread", async () => {
355 const history = threadWithHistory("interrupted", 1);
356 const interruptedRun = { ...history.runs[0]!, status: "interrupted" as const };
357 const thread = { ...history, runs: [interruptedRun] };
358 using _environment = installFakeEnvironment([thread], { acceptCommands: true });
359 __setClientSettingsForTests({
360 ...DEFAULT_CLIENT_SETTINGS,
361 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
362 });
363 const router = getRouter(
364 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
365 );
366 await router.load();
367 await using _app = await render(<AppRoot router={router} />, {
368 // AppRoot brings its own router.
369 router: false,
370 });
371 await expect.element(page.getByRole("button", { name: "Resume thread" })).toBeVisible();
372
373 await userEvent.click(page.getByTestId("composer-editor"));
374 await userEvent.keyboard("{Enter}");
375
376 await vi.waitFor(() =>
377 expect(dispatchedCommands()).toContainEqual(
378 expect.objectContaining({ manualContinuationOfRunId: interruptedRun.id }),
379 ),
380 );
381});
382
383it("opening a thread or returning to the window on a touch tablet does not focus the composer", async () => {
384 const realMatchMedia = window.matchMedia.bind(window);
385 using _touch = vi
386 .spyOn(window, "matchMedia")
387 .mockImplementation((query) => realMatchMedia(query === "(pointer: coarse)" ? "all" : query));
388 const first = threadWithHistory("thread-29469-a", 1);
389 const second = threadWithHistory("thread-29469-b", 1);
390 using _environment = installFakeEnvironment([first, second]);
391 // iPad Pro 11 in landscape: the desktop layout, above max-sm.
392 await page.viewport(1194, 834);
393 __setClientSettingsForTests({
394 ...DEFAULT_CLIENT_SETTINGS,
395 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
396 });
397 const router = getRouter(
398 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${first.id}`] }),
399 );
400 await router.load();
401 await using _app = await render(<AppRoot router={router} />, {
402 // AppRoot brings its own router.
403 router: false,
404 });
405 const composer = page.getByTestId("composer-editor");
406 await expect.element(page.getByText(`Answer 0 for ${first.id}.`)).toBeVisible();
407
408 // Fake frames hold the next thread entry's focus frame until the test advances it.
409 using _timers = fakeTimers();
410 await act(() =>
411 router.navigate({
412 to: "/$environmentId/$threadId",
413 params: { environmentId: ENVIRONMENT_ID, threadId: second.id },
414 }),
415 );
416 await expect.element(page.getByText(`Answer 0 for ${second.id}.`)).toBeVisible();
417 vi.advanceTimersToNextFrame();
418 // Focusing the editor raises the on-screen keyboard, which shrinks the page on iPadOS.
419 expect(document.activeElement).not.toBe(composer.element());
420
421 // ChatView waits two frames after window focus before refocusing the composer.
422 window.dispatchEvent(new FocusEvent("focus"));
423 vi.advanceTimersToNextFrame();
424 vi.advanceTimersToNextFrame();
425 expect(document.activeElement).not.toBe(composer.element());
426});
427
428it("a mounted thread view lets go of the thread structures it has replaced", async () => {
429 // Items are shared with the fixture, so a reopen's snapshot also carries the earlier updates.
430 const history = threadWithHistory("updated", 3);
431 const items = [...history.items];
432 const updated = { ...history, items };
433 const other = threadWithHistory("other", 3);
434 using _environment = installFakeEnvironment([updated, other]);
435 __setClientSettingsForTests({
436 ...DEFAULT_CLIENT_SETTINGS,
437 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
438 });
439 const router = getRouter(createMemoryHistory({ initialEntries: ["/"] }));
440 await router.load();
441 await using _app = await render(<AppRoot router={router} />, { router: false });
442 const open = async (threadId: ThreadId, text: string) => {
443 await act(() =>
444 router.navigate({
445 to: "/$environmentId/$threadId",
446 params: { environmentId: ENVIRONMENT_ID, threadId },
447 }),
448 );
449 await expect.element(page.getByText(text).first()).toBeVisible();
450 };
451 const structureAtom = environmentThreadDetails.quietThreadAtom(
452 scopeThreadRef(ENVIRONMENT_ID, updated.id),
453 );
454
455 // Each round, a new answer arrives while the thread is shown, then the user switches away.
456 const shown: Array<WeakRef<object>> = [];
457 await open(other.id, "Answer 2 for other.");
458 for (let round = 0; round < 6; round++) {
459 await open(updated.id, round === 0 ? "Answer 2 for updated." : `Update ${round - 1}.`);
460 const update = assistantItem(
461 updated.id,
462 RunId.make("updated-run-2"),
463 `updated-update-${round}`,
464 6 + round,
465 `Update ${round}.`,
466 );
467 items.push(update);
468 await act(() => emitThreadEvent(updated.id, { type: "turn-item.updated", payload: update }));
469 await expect.element(page.getByText(`Update ${round}.`)).toBeVisible();
470 shown.push(new WeakRef(appAtomRegistry.get(structureAtom)!.projection));
471 await open(other.id, "Answer 2 for other.");
472 }
473 await cdp().send("HeapProfiler.collectGarbage");
474
475 // The thread keeps its latest structure, and the timeline may remember the one before it.
476 const kept = shown.slice(0, -2).flatMap((structure, round) => (structure.deref() ? [round] : []));
477 expect(kept).toEqual([]);
478});