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

ChatView.browser.test.tsx

361 lines15.0 KB

1import { createMemoryHistory } from "@tanstack/react-router";
2import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
3import { 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 { useRightPanelStore } from "~/rightPanelStore";
17import { getRouter } from "~/router";
18import { appAtomRegistry } from "~/rpc/atomRegistry";
19import { environmentThreadDetails } from "~/state/threads";
20import {
21 ENVIRONMENT_ID,
22 PROJECT_ID,
23 assistantItem,
24 dispatchedCommands,
25 emitThreadEvent,
26 installFakeEnvironment,
27 rejectPendingCommand,
28 threadWithHistory,
29 type FakeDriver,
30} from "../../test/fakeEnvironment";
31import { act, fakeTimers, render } from "../../test/render";
32​
33// The socket is the only fake layer; see test/appScenarios.renders.tsx.
34vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => {
35 const [actual, { fakeDriver }, Layer] = await Promise.all([
36 importOriginal<{ readonly ConnectionDriver: Context.Key<unknown, FakeDriver> }>(),
37 import("../../test/fakeEnvironment"),
38 import("effect/Layer"),
39 ]);
40 return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) };
41});
42​
43vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({
44 ...(await original()),
45 trackRpcRequestSent: () => {},
46}));
47​
48it("a new draft does not load its reserved thread before the server lists it", async () => {
49 using _environment = installFakeEnvironment([]);
50 using fetchSpy = vi.spyOn(globalThis, "fetch");
51 __setClientSettingsForTests({
52 ...DEFAULT_CLIENT_SETTINGS,
53 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
54 });
55 const draftId = DraftId.make("draft-27443");
56 const threadId = ThreadId.make("thread-27443");
57 useComposerDraftStore
58 .getState()
59 .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, { threadId });
60​
61 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
62 await router.load();
63 await using _app = await render(<AppRoot router={router} />, {
64 // AppRoot brings its own router.
65 router: false,
66 });
67 await expect.element(page.getByTestId("composer-editor")).toBeVisible();
68 // The shell snapshot has arrived once the sidebar lists the project, so the connection is up.
69 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
70​
71 const threadRequests = fetchSpy.mock.calls
72 .map(([input]) => String(input instanceof Request ? input.url : input))
73 .filter((url) => url.includes(`/api/orchestration/threads/${threadId}/`));
74 // A 404 here marks the thread deleted, and the view never loads it once the send creates it.
75 expect(threadRequests).toEqual([]);
76});
77​
78it("opens the thread actions menu for an older settled thread the shell leaves out", async () => {
79 const thread = { ...threadWithHistory("older-settled", 1), olderSettled: true as const };
80 using _environment = installFakeEnvironment([thread]);
81 __setClientSettingsForTests({
82 ...DEFAULT_CLIENT_SETTINGS,
83 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
84 });
85​
86 const router = getRouter(
87 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
88 );
89 await router.load();
90 await using _app = await render(<AppRoot router={router} />, {
91 // AppRoot brings its own router.
92 router: false,
93 });
94 await expect.element(page.getByText("older-settled: question 0")).toBeVisible();
95​
96 await page.getByRole("button", { name: `Thread actions for ${thread.title}` }).click();
97 // Without a bound the poll runs to the test deadline and reports a bare timeout.
98 await expect
99 .element(page.getByRole("menuitem", { name: "Rename thread" }), { timeout: 5_000 })
100 .toBeVisible();
101});
102​
103it("retains each thread's diff selection when returning from another thread or Settings", async () => {
104 const a = threadWithHistory("diff-selection-a", 1);
105 const b = threadWithHistory("diff-selection-b", 1);
106 using _environment = installFakeEnvironment([a, b]);
107 __setClientSettingsForTests({
108 ...DEFAULT_CLIENT_SETTINGS,
109 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
110 });
111 const aRef = scopeThreadRef(ENVIRONMENT_ID, a.id);
112 const bRef = scopeThreadRef(ENVIRONMENT_ID, b.id);
113 useRightPanelStore.getState().open(aRef, "diff");
114 useRightPanelStore.getState().open(bRef, "diff");
115 useDiffPanelStore.getState().selectBranchBaseRef(bRef, "origin/release");
116 const router = getRouter(createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${a.id}`] }));
117 await router.load();
118 await using _app = await render(<AppRoot router={router} />, {
119 // AppRoot brings its own router.
120 router: false,
121 });
122 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
123 await act(() => useDiffPanelStore.getState().selectGitScope(aRef, "unstaged"));
124​
125 await act(() =>
126 router.navigate({
127 to: "/$environmentId/$threadId",
128 params: { environmentId: ENVIRONMENT_ID, threadId: b.id },
129 }),
130 );
131 await expect.element(page.getByText(`Answer 0 for ${b.id}.`)).toBeVisible();
132 expect(selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, bRef)).toEqual({
133 kind: "branch",
134 baseRef: "origin/release",
135 });
136 await act(() =>
137 router.navigate({
138 to: "/$environmentId/$threadId",
139 params: { environmentId: ENVIRONMENT_ID, threadId: a.id },
140 }),
141 );
142 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
143 expect(selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, aRef)).toEqual({
144 kind: "unstaged",
145 });
146​
147 await act(() => useDiffPanelStore.getState().selectTurn(aRef, a.runs[0]!.id));
148 await act(() => router.navigate({ to: "/settings/general" }));
149 await expect
150 .element(page.getByRole("heading", { name: "Time format", exact: true }))
151 .toBeVisible();
152 await act(() =>
153 router.navigate({
154 to: "/$environmentId/$threadId",
155 params: { environmentId: ENVIRONMENT_ID, threadId: a.id },
156 }),
157 );
158 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
159 expect(
160 selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, aRef),
161 ).toMatchObject({
162 kind: "turn",
163 turnId: a.runs[0]!.id,
164 });
165});
166​
167it("a stashed prompt ending in a file chip restores with the chip", async () => {
168 using _environment = installFakeEnvironment([]);
169 __setClientSettingsForTests({
170 ...DEFAULT_CLIENT_SETTINGS,
171 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
172 });
173 const draftId = DraftId.make("draft-28338");
174 const drafts = useComposerDraftStore.getState();
175 drafts.setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
176 threadId: ThreadId.make("thread-28338"),
177 });
178 drafts.setPrompt(draftId, "Check [package.json](package.json) ");
179 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
180 await router.load();
181 await using _app = await render(<AppRoot router={router} />, {
182 // AppRoot brings its own router.
183 router: false,
184 });
185 const chip = page.getByRole("button", { name: "Preview package.json" });
186 await expect.element(chip).toBeVisible();
187 // The stash shortcut is a no-op until the shell snapshot lists the project.
188 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
189​
190 const editor = page.getByTestId("composer-editor");
191 await userEvent.click(editor);
192 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
193 await expect.element(chip).not.toBeInTheDocument();
194 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
195​
196 await vi.waitFor(() => expect(editor.element().textContent).toContain("Check"));
197 expect(editor.element().textContent).not.toContain("[package.json](package.json)");
198 await expect.element(chip).toBeVisible();
199});
200​
201it("a rejected send leaves the timeline when a new draft was typed meanwhile", async () => {
202 const thread = threadWithHistory("rejected-send", 1);
203 using _environment = installFakeEnvironment([thread], {
204 acceptCommands: true,
205 holdCommand: (command) => command.type === "message.dispatch",
206 });
207 __setClientSettingsForTests({
208 ...DEFAULT_CLIENT_SETTINGS,
209 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
210 });
211 const router = getRouter(
212 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
213 );
214 await router.load();
215 await using _app = await render(<AppRoot router={router} />, {
216 // AppRoot brings its own router.
217 router: false,
218 });
219 await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible();
220​
221 const editor = page.getByTestId("composer-editor");
222 await userEvent.click(editor);
223 await userEvent.keyboard("Failed prompt{Enter}");
224 await vi.waitFor(() =>
225 expect(dispatchedCommands().map((command) => command.type)).toContain("message.dispatch"),
226 );
227 await expect.element(page.getByText("Failed prompt")).toBeVisible();
228 await userEvent.keyboard("Next draft");
229​
230 await rejectPendingCommand("Attachment 'sample.png' cannot be sent.");
231​
232 await expect.element(page.getByText("Attachment 'sample.png' cannot be sent.")).toBeVisible();
233 await expect.element(page.getByText("Failed prompt")).not.toBeInTheDocument();
234 expect(editor.element().textContent).toContain("Next draft");
235});
236​
237it("Enter on an empty prompt resumes an interrupted thread", async () => {
238 const history = threadWithHistory("interrupted", 1);
239 const interruptedRun = { ...history.runs[0]!, status: "interrupted" as const };
240 const thread = { ...history, runs: [interruptedRun] };
241 using _environment = installFakeEnvironment([thread], { acceptCommands: true });
242 __setClientSettingsForTests({
243 ...DEFAULT_CLIENT_SETTINGS,
244 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
245 });
246 const router = getRouter(
247 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
248 );
249 await router.load();
250 await using _app = await render(<AppRoot router={router} />, {
251 // AppRoot brings its own router.
252 router: false,
253 });
254 await expect.element(page.getByRole("button", { name: "Resume thread" })).toBeVisible();
255​
256 await userEvent.click(page.getByTestId("composer-editor"));
257 await userEvent.keyboard("{Enter}");
258​
259 await vi.waitFor(() =>
260 expect(dispatchedCommands()).toContainEqual(
261 expect.objectContaining({ manualContinuationOfRunId: interruptedRun.id }),
262 ),
263 );
264});
265​
266it("opening a thread or returning to the window on a touch tablet does not focus the composer", async () => {
267 const realMatchMedia = window.matchMedia.bind(window);
268 using _touch = vi
269 .spyOn(window, "matchMedia")
270 .mockImplementation((query) => realMatchMedia(query === "(pointer: coarse)" ? "all" : query));
271 const first = threadWithHistory("thread-29469-a", 1);
272 const second = threadWithHistory("thread-29469-b", 1);
273 using _environment = installFakeEnvironment([first, second]);
274 // iPad Pro 11 in landscape: the desktop layout, above max-sm.
275 await page.viewport(1194, 834);
276 __setClientSettingsForTests({
277 ...DEFAULT_CLIENT_SETTINGS,
278 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
279 });
280 const router = getRouter(
281 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${first.id}`] }),
282 );
283 await router.load();
284 await using _app = await render(<AppRoot router={router} />, {
285 // AppRoot brings its own router.
286 router: false,
287 });
288 const composer = page.getByTestId("composer-editor");
289 await expect.element(page.getByText(`Answer 0 for ${first.id}.`)).toBeVisible();
290​
291 // Fake frames hold the next thread entry's focus frame until the test advances it.
292 using _timers = fakeTimers();
293 await act(() =>
294 router.navigate({
295 to: "/$environmentId/$threadId",
296 params: { environmentId: ENVIRONMENT_ID, threadId: second.id },
297 }),
298 );
299 await expect.element(page.getByText(`Answer 0 for ${second.id}.`)).toBeVisible();
300 vi.advanceTimersToNextFrame();
301 // Focusing the editor raises the on-screen keyboard, which shrinks the page on iPadOS.
302 expect(document.activeElement).not.toBe(composer.element());
303​
304 // ChatView waits two frames after window focus before refocusing the composer.
305 window.dispatchEvent(new FocusEvent("focus"));
306 vi.advanceTimersToNextFrame();
307 vi.advanceTimersToNextFrame();
308 expect(document.activeElement).not.toBe(composer.element());
309});
310​
311it("a mounted thread view lets go of the thread structures it has replaced", async () => {
312 // Items are shared with the fixture, so a reopen's snapshot also carries the earlier updates.
313 const history = threadWithHistory("updated", 3);
314 const items = [...history.items];
315 const updated = { ...history, items };
316 const other = threadWithHistory("other", 3);
317 using _environment = installFakeEnvironment([updated, other]);
318 __setClientSettingsForTests({
319 ...DEFAULT_CLIENT_SETTINGS,
320 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
321 });
322 const router = getRouter(createMemoryHistory({ initialEntries: ["/"] }));
323 await router.load();
324 await using _app = await render(<AppRoot router={router} />, { router: false });
325 const open = async (threadId: ThreadId, text: string) => {
326 await act(() =>
327 router.navigate({
328 to: "/$environmentId/$threadId",
329 params: { environmentId: ENVIRONMENT_ID, threadId },
330 }),
331 );
332 await expect.element(page.getByText(text).first()).toBeVisible();
333 };
334 const structureAtom = environmentThreadDetails.quietThreadAtom(
335 scopeThreadRef(ENVIRONMENT_ID, updated.id),
336 );
337​
338 // Each round, a new answer arrives while the thread is shown, then the user switches away.
339 const shown: Array<WeakRef<object>> = [];
340 await open(other.id, "Answer 2 for other.");
341 for (let round = 0; round < 6; round++) {
342 await open(updated.id, round === 0 ? "Answer 2 for updated." : `Update ${round - 1}.`);
343 const update = assistantItem(
344 updated.id,
345 RunId.make("updated-run-2"),
346 `updated-update-${round}`,
347 6 + round,
348 `Update ${round}.`,
349 );
350 items.push(update);
351 await act(() => emitThreadEvent(updated.id, { type: "turn-item.updated", payload: update }));
352 await expect.element(page.getByText(`Update ${round}.`)).toBeVisible();
353 shown.push(new WeakRef(appAtomRegistry.get(structureAtom)!.projection));
354 await open(other.id, "Answer 2 for other.");
355 }
356 await cdp().send("HeapProfiler.collectGarbage");
357​
358 // The thread keeps its latest structure, and the timeline may remember the one before it.
359 const kept = shown.slice(0, -2).flatMap((structure, round) => (structure.deref() ? [round] : []));
360 expect(kept).toEqual([]);
361});