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

ChatView.browser.test.tsx

664 lines27.8 KB

1import { createMemoryHistory } from "@tanstack/react-router";
2import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
3import {
4 EnvironmentId,
5 ORCHESTRATION_V2_WS_METHODS,
6 RunId,
7 ThreadId,
8 WS_METHODS,
9} from "@t3tools/contracts";
10import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
11import {
12 compileResolvedKeybindingsConfig,
13 mergeWithDefaultKeybindings,
14} from "@t3tools/shared/keybindings";
15import type * as Context from "effect/Context";
16import * as Effect from "effect/Effect";
17import { expect, it, vi } from "vite-plus/test";
18import { cdp, page, userEvent } from "vite-plus/test/browser";
19​
20import { AppRoot } from "~/AppRoot";
21// The route loads ChatView lazily, and its first transform (React Compiler over ~4k lines)
22// takes 6-11s; importing it here keeps that out of the test's timeout.
23import "~/components/ChatView";
24import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
25import { selectThreadDiffPanelSelection, useDiffPanelStore } from "~/diffPanelStore";
26import { __setClientSettingsForTests } from "~/hooks/useSettings";
27import { environmentContextRecord } from "~/lib/composerContextRecords";
28import { startWorkspaceFocus } from "~/lib/workspaceFocus";
29import { usePromptStashStore } from "~/promptStashStore";
30import { useRightPanelStore } from "~/rightPanelStore";
31import { getRouter } from "~/router";
32import { appAtomRegistry } from "~/rpc/atomRegistry";
33import { environmentThreadDetails } from "~/state/threads";
34import {
35 ENVIRONMENT_ID,
36 PROJECT_ID,
37 answerAssetUrls,
38 answerRpc,
39 assistantItem,
40 dispatchedCommands,
41 emitThreadEvent,
42 hasPendingAssetUrl,
43 installFakeEnvironment,
44 rejectPendingCommand,
45 threadWithHistory,
46 threadWithQuestion,
47 type FakeDriver,
48} from "../../test/fakeEnvironment";
49import { act, fakeTimers, render } from "../../test/render";
50​
51const PNG = Uint8Array.from(
52 atob(
53 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=",
54 ),
55 (char) => char.charCodeAt(0),
56);
57​
58/** Accepts every attachment upload without sending its bytes, until disposed. */
59function acceptAttachmentUploads(): Disposable {
60 const mint = answerRpc(WS_METHODS.attachmentsCreateUploadUrl, () =>
61 Effect.succeed({ attachmentId: "upload-1", relativeUrl: "/upload", expiresAt: 0 }),
62 );
63 // Sending verifies each ready upload still exists on the server.
64 const verify = answerRpc(WS_METHODS.assetsCreateUrl, () =>
65 Effect.succeed({ relativeUrl: "/upload-1", expiresAt: 0 }),
66 );
67 const status = vi.spyOn(XMLHttpRequest.prototype, "status", "get").mockReturnValue(200);
68 const send = vi.spyOn(XMLHttpRequest.prototype, "send").mockImplementation(function (
69 this: XMLHttpRequest,
70 ) {
71 queueMicrotask(() => this.dispatchEvent(new ProgressEvent("load")));
72 });
73 return {
74 [Symbol.dispose]: () => {
75 send.mockRestore();
76 status.mockRestore();
77 mint[Symbol.dispose]();
78 verify[Symbol.dispose]();
79 },
80 };
82​
83/** Holds every call to `method` until `release`, then ends it with `end`, until disposed. */
84function holdRpc<Input>(method: string, end: Effect.Effect<never, Error>) {
85 let release = () => {};
86 const held = new Promise<void>((resolve) => {
87 release = resolve;
88 });
89 const calls: Input[] = [];
90 const answer = answerRpc(method, (input: Input) => {
91 calls.push(input);
92 return Effect.promise(() => held).pipe(Effect.andThen(end));
93 });
94 return { calls, release, [Symbol.dispose]: () => answer[Symbol.dispose]() };
96​
97// The socket is the only fake layer; see test/appScenarios.renders.tsx.
98vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => {
99 const [actual, { fakeDriver }, Layer] = await Promise.all([
100 importOriginal<{ readonly ConnectionDriver: Context.Key<unknown, FakeDriver> }>(),
101 import("../../test/fakeEnvironment"),
102 import("effect/Layer"),
103 ]);
104 return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) };
105});
106​
107vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({
108 ...(await original()),
109 trackRpcRequestSent: () => {},
110}));
111​
112it("a machine chip stashed in one thread restores with its machine in another", async () => {
113 const other = threadWithHistory("thread-stash-restore", 1);
114 const asking = threadWithQuestion("thread-stash-question", "Which file should change?");
115 using _environment = installFakeEnvironment([other, asking]);
116 __setClientSettingsForTests({
117 ...DEFAULT_CLIENT_SETTINGS,
118 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
119 });
120 const draftId = DraftId.make("draft-stash-machine");
121 const machine = environmentContextRecord(EnvironmentId.make("environment-build"), "Build box");
122 const drafts = useComposerDraftStore.getState();
123 drafts.setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
124 threadId: ThreadId.make("thread-stash-machine"),
125 });
126 drafts.setPrompt(draftId, "Deploy on ");
127 drafts.addEnvironmentContexts(draftId, [machine]);
128 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
129 await router.load();
130 await using _app = await render(<AppRoot router={router} />, {
131 // AppRoot brings its own router.
132 router: false,
133 });
134 const editor = page.getByTestId("composer-editor");
135 const pressStashShortcut = async () => {
136 await userEvent.click(editor);
137 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
138 };
139 await vi.waitFor(() => expect(editor.element().textContent).toContain("Deploy on"));
140 // A draft can't stash until the shell snapshot lists its project.
141 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
142 await pressStashShortcut();
143 await vi.waitFor(() => expect(usePromptStashStore.getState().entries).toHaveLength(1));
144​
145 // An answer carries no machines, so an open question refuses the restore and keeps the entry.
146 await router.navigate({ to: `/${ENVIRONMENT_ID}/${asking.id}` });
147 await expect.element(page.getByText("Which file should change?")).toBeVisible();
148 await userEvent.click(page.getByRole("button", { name: /^Stashed prompts/ }));
149 await userEvent.click(page.getByRole("button", { name: /^Restore stashed prompt/ }));
150 await vi.waitFor(() =>
151 expect(document.body.textContent).toContain("Stashed machines can't go in an answer"),
152 );
153 expect(usePromptStashStore.getState().entries).toHaveLength(1);
154​
155 await router.navigate({ to: `/${ENVIRONMENT_ID}/${other.id}` });
156 await expect.element(page.getByText("Answer 0 for thread-stash-restore.")).toBeVisible();
157 await pressStashShortcut();
158​
159 await vi.waitFor(() => expect(editor.element().textContent).toContain("Deploy on"));
160 expect(
161 useComposerDraftStore.getState().getComposerDraft(scopeThreadRef(ENVIRONMENT_ID, other.id))
162 ?.environmentContexts,
163 ).toEqual([machine]);
164 expect(
165 useComposerDraftStore.getState().getComposerDraft(draftId)?.environmentContexts ?? [],
166 ).toEqual([]);
167});
168​
169it("a question that opens while a stashed file is checked keeps a machine stash", async () => {
170 const thread = threadWithHistory("thread-stash-late-question", 1);
171 const asking = threadWithQuestion("thread-stash-late-question", "Which file should change?");
172 const [request] = asking.runtimeRequests ?? [];
173 const question = asking.items.at(-1);
174 if (!request || !question) throw new Error("threadWithQuestion has no question");
175 using _environment = installFakeEnvironment([thread]);
176 __setClientSettingsForTests({
177 ...DEFAULT_CLIENT_SETTINGS,
178 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
179 });
180 usePromptStashStore.getState().stashEntry({
181 id: "stash-late-question",
182 createdAt: "2026-01-01T00:00:00.000Z",
183 prompt: "Deploy on ",
184 attachments: [],
185 files: [
186 {
187 id: "file-notes",
188 name: "notes.txt",
189 mimeType: "text/plain",
190 sizeBytes: 5,
191 attachmentId: "attachment-notes",
192 environmentId: ENVIRONMENT_ID,
193 },
194 ],
195 droppedImageNames: [],
196 records: [environmentContextRecord(EnvironmentId.make("environment-build"), "Build box")],
197 });
198 const router = getRouter(
199 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
200 );
201 await router.load();
202 await using _app = await render(<AppRoot router={router} />, {
203 // AppRoot brings its own router.
204 router: false,
205 });
206 await expect.element(page.getByText("Answer 0 for thread-stash-late-question.")).toBeVisible();
207 await userEvent.click(page.getByRole("button", { name: /^Stashed prompts/ }));
208 await userEvent.click(page.getByRole("button", { name: /^Restore stashed prompt/ }));
209​
210 // The question opens while the restore still waits on the server's file check.
211 await vi.waitFor(() => expect(hasPendingAssetUrl()).toBe(true));
212 await emitThreadEvent(thread.id, { type: "turn-item.updated", payload: question });
213 await emitThreadEvent(thread.id, { type: "runtime-request.updated", payload: request });
214 await expect.element(page.getByText("Which file should change?")).toBeVisible();
215 await answerAssetUrls();
216​
217 await vi.waitFor(() =>
218 expect(document.body.textContent).toContain("Stashed machines can't go in an answer"),
219 );
220 expect(usePromptStashStore.getState().entries).toHaveLength(1);
221 usePromptStashStore.getState().takeEntry("stash-late-question");
222});
223​
224it("a new draft does not load its reserved thread before the server lists it", async () => {
225 using _environment = installFakeEnvironment([]);
226 using fetchSpy = vi.spyOn(globalThis, "fetch");
227 __setClientSettingsForTests({
228 ...DEFAULT_CLIENT_SETTINGS,
229 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
230 });
231 const draftId = DraftId.make("draft-27443");
232 const threadId = ThreadId.make("thread-27443");
233 useComposerDraftStore
234 .getState()
235 .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, { threadId });
236​
237 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
238 await router.load();
239 await using _app = await render(<AppRoot router={router} />, {
240 // AppRoot brings its own router.
241 router: false,
242 });
243 await expect.element(page.getByTestId("composer-editor")).toBeVisible();
244 // The shell snapshot has arrived once the sidebar lists the project, so the connection is up.
245 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
246​
247 const threadRequests = fetchSpy.mock.calls
248 .map(([input]) => String(input instanceof Request ? input.url : input))
249 .filter((url) => url.includes(`/api/orchestration/threads/${threadId}/`));
250 // A 404 here marks the thread deleted, and the view never loads it once the send creates it.
251 expect(threadRequests).toEqual([]);
252});
253​
254it("an interrupted image-only first send of a new thread says it may not have been sent", async () => {
255 using _environment = installFakeEnvironment([]);
256 __setClientSettingsForTests({
257 ...DEFAULT_CLIENT_SETTINGS,
258 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
259 });
260 const draftId = DraftId.make("draft-image-only-interrupted");
261 useComposerDraftStore
262 .getState()
263 .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
264 threadId: ThreadId.make("thread-image-only-interrupted"),
265 });
266 // A dropped connection interrupts a new thread's launch, which is not resent.
267 using launch = holdRpc(ORCHESTRATION_V2_WS_METHODS.launchThread, Effect.interrupt);
268 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
269 await router.load();
270 await using _app = await render(<AppRoot router={router} />, {
271 // AppRoot brings its own router.
272 router: false,
273 });
274 using _uploads = acceptAttachmentUploads();
275 const editor = page.getByTestId("composer-editor");
276 await expect.element(editor).toBeVisible();
277 // The send needs the project, which arrives with the shell snapshot.
278 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
279​
280 await userEvent.click(editor);
281 const clipboardData = new DataTransfer();
282 clipboardData.items.add(new File([PNG], "shot.png", { type: "image/png" }));
283 editor
284 .element()
285 .dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
286 await expect.element(page.getByRole("img", { name: "shot.png" })).toBeVisible();
287 await userEvent.keyboard("{Enter}");
288 await vi.waitFor(() => expect(launch.calls).toHaveLength(1));
289 await userEvent.keyboard("next draft");
290 await expect.element(editor).toHaveTextContent("next draft");
291 launch.release();
292​
293 await expect.element(page.getByText("Message may not have been sent")).toBeVisible();
294 await expect.element(editor).toHaveTextContent("next draft");
295 // With no text there is nothing to copy.
296 expect(page.getByText("Copy message", { exact: true }).query()).toBeNull();
297});
298​
299it("opens the thread actions menu for an older settled thread the shell leaves out", async () => {
300 const thread = { ...threadWithHistory("older-settled", 1), olderSettled: true as const };
301 using _environment = installFakeEnvironment([thread]);
302 __setClientSettingsForTests({
303 ...DEFAULT_CLIENT_SETTINGS,
304 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
305 });
306​
307 const router = getRouter(
308 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
309 );
310 await router.load();
311 await using _app = await render(<AppRoot router={router} />, {
312 // AppRoot brings its own router.
313 router: false,
314 });
315 await expect.element(page.getByText("older-settled: question 0")).toBeVisible();
316​
317 await page.getByRole("button", { name: `Thread actions for ${thread.title}` }).click();
318 // Without a bound the poll runs to the test deadline and reports a bare timeout.
319 await expect
320 .element(page.getByRole("menuitem", { name: "Rename thread" }), { timeout: 5_000 })
321 .toBeVisible();
322});
323​
324it("retains each thread's diff selection when returning from another thread or Settings", async () => {
325 const a = threadWithHistory("diff-selection-a", 1);
326 const b = threadWithHistory("diff-selection-b", 1);
327 using _environment = installFakeEnvironment([a, b]);
328 __setClientSettingsForTests({
329 ...DEFAULT_CLIENT_SETTINGS,
330 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
331 });
332 const aRef = scopeThreadRef(ENVIRONMENT_ID, a.id);
333 const bRef = scopeThreadRef(ENVIRONMENT_ID, b.id);
334 useRightPanelStore.getState().open(aRef, "diff");
335 useRightPanelStore.getState().open(bRef, "diff");
336 useDiffPanelStore.getState().selectBranchBaseRef(bRef, "origin/release");
337 const router = getRouter(createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${a.id}`] }));
338 await router.load();
339 await using _app = await render(<AppRoot router={router} />, {
340 // AppRoot brings its own router.
341 router: false,
342 });
343 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
344 await act(() => useDiffPanelStore.getState().selectGitScope(aRef, "unstaged"));
345​
346 await act(() =>
347 router.navigate({
348 to: "/$environmentId/$threadId",
349 params: { environmentId: ENVIRONMENT_ID, threadId: b.id },
350 }),
351 );
352 await expect.element(page.getByText(`Answer 0 for ${b.id}.`)).toBeVisible();
353 expect(selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, bRef)).toEqual({
354 kind: "branch",
355 baseRef: "origin/release",
356 });
357 await act(() =>
358 router.navigate({
359 to: "/$environmentId/$threadId",
360 params: { environmentId: ENVIRONMENT_ID, threadId: a.id },
361 }),
362 );
363 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
364 expect(selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, aRef)).toEqual({
365 kind: "unstaged",
366 });
367​
368 await act(() => useDiffPanelStore.getState().selectTurn(aRef, a.runs[0]!.id));
369 await act(() => router.navigate({ to: "/settings/general" }));
370 await expect
371 .element(page.getByRole("heading", { name: "Time format", exact: true }))
372 .toBeVisible();
373 await act(() =>
374 router.navigate({
375 to: "/$environmentId/$threadId",
376 params: { environmentId: ENVIRONMENT_ID, threadId: a.id },
377 }),
378 );
379 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
380 expect(
381 selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, aRef),
382 ).toMatchObject({
383 kind: "turn",
384 turnId: a.runs[0]!.id,
385 });
386});
387​
388it("a stashed prompt ending in a file chip restores with the chip", async () => {
389 using _environment = installFakeEnvironment([]);
390 __setClientSettingsForTests({
391 ...DEFAULT_CLIENT_SETTINGS,
392 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
393 });
394 const draftId = DraftId.make("draft-28338");
395 const drafts = useComposerDraftStore.getState();
396 drafts.setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
397 threadId: ThreadId.make("thread-28338"),
398 });
399 drafts.setPrompt(draftId, "Check [package.json](package.json) ");
400 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
401 await router.load();
402 await using _app = await render(<AppRoot router={router} />, {
403 // AppRoot brings its own router.
404 router: false,
405 });
406 const chip = page.getByRole("button", { name: "Preview package.json" });
407 await expect.element(chip).toBeVisible();
408 // The stash shortcut is a no-op until the shell snapshot lists the project.
409 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
410​
411 const editor = page.getByTestId("composer-editor");
412 await userEvent.click(editor);
413 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
414 await expect.element(chip).not.toBeInTheDocument();
415 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
416​
417 await vi.waitFor(() => expect(editor.element().textContent).toContain("Check"));
418 expect(editor.element().textContent).not.toContain("[package.json](package.json)");
419 await expect.element(chip).toBeVisible();
420});
421​
422it("a rejected send leaves the timeline when a new draft was typed meanwhile", async () => {
423 const thread = threadWithHistory("rejected-send", 1);
424 using _environment = installFakeEnvironment([thread], {
425 acceptCommands: true,
426 holdCommand: (command) => command.type === "message.dispatch",
427 });
428 __setClientSettingsForTests({
429 ...DEFAULT_CLIENT_SETTINGS,
430 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
431 });
432 const router = getRouter(
433 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
434 );
435 await router.load();
436 await using _app = await render(<AppRoot router={router} />, {
437 // AppRoot brings its own router.
438 router: false,
439 });
440 await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible();
441​
442 const editor = page.getByTestId("composer-editor");
443 await userEvent.click(editor);
444 await userEvent.keyboard("Failed prompt{Enter}");
445 await vi.waitFor(() =>
446 expect(dispatchedCommands().map((command) => command.type)).toContain("message.dispatch"),
447 );
448 await expect.element(page.getByText("Failed prompt")).toBeVisible();
449 await userEvent.keyboard("Next draft");
450​
451 await rejectPendingCommand("Attachment 'sample.png' cannot be sent.");
452​
453 await expect.element(page.getByText("Attachment 'sample.png' cannot be sent.")).toBeVisible();
454 await expect.element(page.getByText("Failed prompt")).not.toBeInTheDocument();
455 expect(editor.element().textContent).toContain("Next draft");
456});
457​
458it("Enter on an empty prompt resumes an interrupted thread", async () => {
459 const history = threadWithHistory("interrupted", 1);
460 const interruptedRun = { ...history.runs[0]!, status: "interrupted" as const };
461 const thread = { ...history, runs: [interruptedRun] };
462 using _environment = installFakeEnvironment([thread], { acceptCommands: true });
463 __setClientSettingsForTests({
464 ...DEFAULT_CLIENT_SETTINGS,
465 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
466 });
467 const router = getRouter(
468 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
469 );
470 await router.load();
471 await using _app = await render(<AppRoot router={router} />, {
472 // AppRoot brings its own router.
473 router: false,
474 });
475 await expect.element(page.getByRole("button", { name: "Resume thread" })).toBeVisible();
476​
477 await userEvent.click(page.getByTestId("composer-editor"));
478 await userEvent.keyboard("{Enter}");
479​
480 await vi.waitFor(() =>
481 expect(dispatchedCommands()).toContainEqual(
482 expect.objectContaining({ manualContinuationOfRunId: interruptedRun.id }),
483 ),
484 );
485});
486​
487it("opening a thread or returning to the window on a touch tablet does not focus the composer", async () => {
488 const realMatchMedia = window.matchMedia.bind(window);
489 using _touch = vi
490 .spyOn(window, "matchMedia")
491 .mockImplementation((query) => realMatchMedia(query === "(pointer: coarse)" ? "all" : query));
492 const first = threadWithHistory("thread-29469-a", 1);
493 const second = threadWithHistory("thread-29469-b", 1);
494 using _environment = installFakeEnvironment([first, second]);
495 // iPad Pro 11 in landscape: the desktop layout, above max-sm.
496 await page.viewport(1194, 834);
497 __setClientSettingsForTests({
498 ...DEFAULT_CLIENT_SETTINGS,
499 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
500 });
501 const router = getRouter(
502 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${first.id}`] }),
503 );
504 await router.load();
505 await using _app = await render(<AppRoot router={router} />, {
506 // AppRoot brings its own router.
507 router: false,
508 });
509 const composer = page.getByTestId("composer-editor");
510 await expect.element(page.getByText(`Answer 0 for ${first.id}.`)).toBeVisible();
511​
512 // Fake frames hold the next thread entry's focus frame until the test advances it.
513 using _timers = fakeTimers();
514 await act(() =>
515 router.navigate({
516 to: "/$environmentId/$threadId",
517 params: { environmentId: ENVIRONMENT_ID, threadId: second.id },
518 }),
519 );
520 await expect.element(page.getByText(`Answer 0 for ${second.id}.`)).toBeVisible();
521 vi.advanceTimersToNextFrame();
522 // Focusing the editor raises the on-screen keyboard, which shrinks the page on iPadOS.
523 expect(document.activeElement).not.toBe(composer.element());
524​
525 // ChatView waits two frames after window focus before refocusing the composer.
526 window.dispatchEvent(new FocusEvent("focus"));
527 vi.advanceTimersToNextFrame();
528 vi.advanceTimersToNextFrame();
529 expect(document.activeElement).not.toBe(composer.element());
530});
531​
532it("a mounted thread view lets go of the thread structures it has replaced", async () => {
533 // Items are shared with the fixture, so a reopen's snapshot also carries the earlier updates.
534 const history = threadWithHistory("updated", 3);
535 const items = [...history.items];
536 const updated = { ...history, items };
537 const other = threadWithHistory("other", 3);
538 using _environment = installFakeEnvironment([updated, other]);
539 __setClientSettingsForTests({
540 ...DEFAULT_CLIENT_SETTINGS,
541 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
542 });
543 const router = getRouter(createMemoryHistory({ initialEntries: ["/"] }));
544 await router.load();
545 await using _app = await render(<AppRoot router={router} />, { router: false });
546 const open = async (threadId: ThreadId, text: string) => {
547 await act(() =>
548 router.navigate({
549 to: "/$environmentId/$threadId",
550 params: { environmentId: ENVIRONMENT_ID, threadId },
551 }),
552 );
553 await expect.element(page.getByText(text).first()).toBeVisible();
554 };
555 const structureAtom = environmentThreadDetails.quietThreadAtom(
556 scopeThreadRef(ENVIRONMENT_ID, updated.id),
557 );
558​
559 // Each round, a new answer arrives while the thread is shown, then the user switches away.
560 const shown: Array<WeakRef<object>> = [];
561 await open(other.id, "Answer 2 for other.");
562 for (let round = 0; round < 6; round++) {
563 await open(updated.id, round === 0 ? "Answer 2 for updated." : `Update ${round - 1}.`);
564 const update = assistantItem(
565 updated.id,
566 RunId.make("updated-run-2"),
567 `updated-update-${round}`,
568 6 + round,
569 `Update ${round}.`,
570 );
571 items.push(update);
572 await act(() => emitThreadEvent(updated.id, { type: "turn-item.updated", payload: update }));
573 await expect.element(page.getByText(`Update ${round}.`)).toBeVisible();
574 shown.push(new WeakRef(appAtomRegistry.get(structureAtom)!.projection));
575 await open(other.id, "Answer 2 for other.");
576 }
577 await cdp().send("HeapProfiler.collectGarbage");
578​
579 // The thread keeps its latest structure, and the timeline may remember the one before it.
580 const kept = shown.slice(0, -2).flatMap((structure, round) => (structure.deref() ? [round] : []));
581 expect(kept).toEqual([]);
582});
583​
584it("a shortcut conditioned on rightPanelOpen sees the thread's open right panel", async () => {
585 await page.viewport(1280, 800);
586 const thread = threadWithHistory("thread-panel-shortcut", 1);
587 using _environment = installFakeEnvironment([thread], {
588 keybindings: mergeWithDefaultKeybindings(
589 compileResolvedKeybindingsConfig([
590 { key: "ctrl+t", command: "rightPanel.new", when: "rightPanelOpen && !terminalFocus" },
591 { key: "ctrl+t", command: "rightPanel.toggle", when: "!rightPanelOpen" },
592 ]),
593 ),
594 });
595 __setClientSettingsForTests({
596 ...DEFAULT_CLIENT_SETTINGS,
597 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
598 });
599 const router = getRouter(
600 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
601 );
602 await router.load();
603 await using _app = await render(<AppRoot router={router} />, {
604 // AppRoot brings its own router.
605 router: false,
606 });
607 const composer = page.getByTestId("composer-editor");
608 const toggle = page.getByRole("button", { name: "Toggle right panel", exact: true });
609 await expect.element(toggle).toHaveAttribute("aria-pressed", "false");
610 await toggle.click();
611 await page.getByRole("button", { name: /^Files/ }).click();
612 await composer.click();
613 await userEvent.keyboard("{Control>}t{/Control}");
614 await expect.element(page.getByRole("menuitem", { name: /Files/ })).toBeVisible();
615 await expect.element(toggle).toHaveAttribute("aria-pressed", "true");
616});
617​
618it("selecting a side-chat tab focuses that side chat's composer", async () => {
619 const parent = threadWithHistory("focus-parent", 1);
620 // The shell loaded by the file's first test stays; a family read serves side chats added later.
621 const sideChat = (name: string) => ({
622 ...threadWithHistory(name, 1),
623 sideChatOf: parent.id,
624 olderSettled: true as const,
625 });
626 const side = sideChat("focus-side");
627 const otherSide = sideChat("focus-other-side");
628 await page.viewport(1400, 900);
629 using _environment = installFakeEnvironment([parent, side, otherSide]);
630 __setClientSettingsForTests({
631 ...DEFAULT_CLIENT_SETTINGS,
632 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
633 });
634 const parentRef = scopeThreadRef(ENVIRONMENT_ID, parent.id);
635 useRightPanelStore.getState().openSideChat(parentRef, otherSide.id);
636 useRightPanelStore.getState().openSideChat(parentRef, side.id);
637 const router = getRouter(
638 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${parent.id}`] }),
639 );
640 await router.load();
641 await using screen = await render(<AppRoot router={router} />, {
642 // AppRoot brings its own router.
643 router: false,
644 });
645 using _focus = { [Symbol.dispose]: startWorkspaceFocus(router) };
646 const mainEditor = screen.getByRole("textbox", { name: `Message ${parent.title}`, exact: true });
647 const sideEditor = screen.getByRole("textbox", { name: `Message ${side.title}`, exact: true });
648 await expect.element(sideEditor).toBeVisible();
649 await userEvent.click(mainEditor);
650 await userEvent.keyboard("main draft");
651​
652 await userEvent.click(screen.getByRole("button", { name: otherSide.title, exact: true }));
653 const otherEditor = screen.getByRole("textbox", {
654 name: `Message ${otherSide.title}`,
655 exact: true,
656 });
657 await expect.element(otherEditor).toHaveFocus();
658 await userEvent.keyboard("other draft");
659 await expect.element(otherEditor).toHaveTextContent("other draft");
660​
661 await userEvent.click(screen.getByRole("button", { name: side.title, exact: true }));
662 await expect.element(sideEditor).toHaveFocus();
663 await expect.element(mainEditor).toHaveTextContent("main draft");
664});