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

ChatView.browser.test.tsx

1,151 lines46.5 KB

1import { createMemoryHistory } from "@tanstack/react-router";
2import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
3import {
4 EnvironmentId,
5 IssueTrackerKind,
6 ORCHESTRATION_V2_WS_METHODS,
7 RunId,
8 ThreadId,
9 WS_METHODS,
10 type IssueDetail,
11 type IssueRef,
12 type ThreadIssueLink,
13} from "@t3tools/contracts";
14import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
15import {
16 compileResolvedKeybindingsConfig,
17 mergeWithDefaultKeybindings,
18} from "@t3tools/shared/keybindings";
19import type * as Context from "effect/Context";
20import * as Schema from "effect/Schema";
21import * as Effect from "effect/Effect";
22import { expect, it, vi } from "vite-plus/test";
23import { cdp, page, userEvent } from "vite-plus/test/browser";
24​
25import { AppRoot } from "~/AppRoot";
26// The route loads ChatView lazily, and its first transform (React Compiler over ~4k lines)
27// takes 6-11s; importing it here keeps that out of the test's timeout.
28import "~/components/ChatView";
29import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
30import { selectThreadDiffPanelSelection, useDiffPanelStore } from "~/diffPanelStore";
31import { __setClientSettingsForTests } from "~/hooks/useSettings";
32import stylesheet from "~/index.css?inline";
33import { environmentContextRecord } from "~/lib/composerContextRecords";
34import { startWorkspaceFocus } from "~/lib/workspaceFocus";
35import { usePromptStashStore } from "~/promptStashStore";
36import { useRightPanelStore } from "~/rightPanelStore";
37import { getRouter } from "~/router";
38import { appAtomRegistry } from "~/rpc/atomRegistry";
39import { environmentThreadDetails } from "~/state/threads";
40import {
41 ENVIRONMENT_ID,
42 PROJECT_ID,
43 answerAssetUrls,
44 answerRpc,
45 assistantItem,
46 dispatchedCommands,
47 emitThreadEvent,
48 hasPendingAssetUrl,
49 installFakeEnvironment,
50 rejectPendingCommand,
51 threadWithHistory,
52 threadWithQuestion,
53 type FakeDriver,
54} from "../../test/fakeEnvironment";
55import { act, fakeTimers, render } from "../../test/render";
56​
57const PNG = Uint8Array.from(
58 atob(
59 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=",
60 ),
61 (char) => char.charCodeAt(0),
62);
63​
64/** Accepts every attachment upload without sending its bytes, until disposed. */
65function acceptAttachmentUploads(): Disposable {
66 const mint = answerRpc(WS_METHODS.attachmentsCreateUploadUrl, () =>
67 Effect.succeed({ attachmentId: "upload-1", relativeUrl: "/upload", expiresAt: 0 }),
68 );
69 // Sending verifies each ready upload still exists on the server.
70 const verify = answerRpc(WS_METHODS.assetsCreateUrl, () =>
71 Effect.succeed({ relativeUrl: "/upload-1", expiresAt: 0 }),
72 );
73 const status = vi.spyOn(XMLHttpRequest.prototype, "status", "get").mockReturnValue(200);
74 const send = vi.spyOn(XMLHttpRequest.prototype, "send").mockImplementation(function (
75 this: XMLHttpRequest,
76 ) {
77 queueMicrotask(() => this.dispatchEvent(new ProgressEvent("load")));
78 });
79 return {
80 [Symbol.dispose]: () => {
81 send.mockRestore();
82 status.mockRestore();
83 mint[Symbol.dispose]();
84 verify[Symbol.dispose]();
85 },
86 };
88​
89// One input event, where typing a key at a time takes seconds on a loaded CI runner.
90const insertText = (text: string) => cdp().send("Input.insertText", { text });
91​
92/** Holds every call to `method` until `release`, then ends it with `end`, until disposed. */
93class LaunchRefused extends Schema.TaggedError<LaunchRefused>()("LaunchRefused", {}) {}
94​
95function holdRpc<Input>(method: string, end: Effect.Effect<never, Error>) {
96 let release = () => {};
97 const held = new Promise<void>((resolve) => {
98 release = resolve;
99 });
100 const calls: Input[] = [];
101 const answer = answerRpc(method, (input: Input) => {
102 calls.push(input);
103 return Effect.promise(() => held).pipe(Effect.andThen(end));
104 });
105 return { calls, release, [Symbol.dispose]: () => answer[Symbol.dispose]() };
107​
108// The socket is the only fake layer; see test/appScenarios.renders.tsx.
109vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => {
110 const [actual, { fakeDriver }, Layer] = await Promise.all([
111 importOriginal<{ readonly ConnectionDriver: Context.Key<unknown, FakeDriver> }>(),
112 import("../../test/fakeEnvironment"),
113 import("effect/Layer"),
114 ]);
115 return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) };
116});
117​
118// Null runs the real compression; a test sets it to hold an image in preparation.
119const compression = vi.hoisted(() => ({ gate: null as Promise<void> | null }));
120vi.mock(import("~/lib/imageCompression"), async (original) => {
121 const actual = await original();
122 return {
123 ...actual,
124 prepareImageForAttachment: async (...args) => {
125 await compression.gate;
126 return actual.prepareImageForAttachment(...args);
127 },
128 };
129});
130​
131vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({
132 ...(await original()),
133 trackRpcRequestSent: () => {},
134}));
135​
136it("opens a linked Linear issue from an inactive thread's sidebar badge", async () => {
137 const style = document.createElement("style");
138 style.textContent = stylesheet;
139 document.head.append(style);
140 using _style = { [Symbol.dispose]: () => style.remove() };
141 const first = threadWithHistory("issue-first", 1);
142 const linked = threadWithHistory("issue-linked", 1);
143 const issueRef = {
144 projectId: PROJECT_ID,
145 tracker: IssueTrackerKind.make("linear"),
146 host: "linear.app",
147 scope: "WEB",
148 key: "WEB-123",
149 } satisfies IssueRef;
150 const issue: ThreadIssueLink = {
151 ...issueRef,
152 url: "https://linear.app/example/issue/WEB-123/add-keyboard-support",
153 source: "manual",
154 linkedAt: "2026-01-01T00:00:00.000Z",
155 displayKey: "#123",
156 title: "Add keyboard support",
157 };
158 const completed = {
159 ...issue,
160 key: "WEB-124",
161 displayKey: "WEB-124",
162 url: "https://linear.app/example/issue/WEB-124/keep-tabs-visible",
163 title: "Keep tabs visible",
164 };
165 const grouped = threadWithHistory("issue-grouped", 1);
166 using _environment = installFakeEnvironment([
167 first,
168 {
169 ...linked,
170 issues: [issue],
171 pullRequests: [
172 {
173 host: "github.com",
174 repository: "pingdotgg/t3code",
175 number: 124,
176 url: "https://github.com/pingdotgg/t3code/pull/124",
177 source: "manual",
178 linkedAt: "2026-01-01T00:00:00.000Z",
179 snapshot: null,
180 stack: null,
181 },
182 ],
183 },
184 { ...grouped, issues: [completed, issue] },
185 ]);
186 const liveTitle = "Add keyboard shortcuts to the sidebar";
187 using _detail = answerRpc(WS_METHODS.issuesDetail, (input: IssueRef) => {
188 const isCompleted = input.key === completed.key;
189 expect(input).toEqual({ ...issueRef, key: isCompleted ? completed.key : issue.key });
190 return Effect.succeed({
191 ...(isCompleted ? completed : issue),
192 title: isCompleted ? completed.title : liveTitle,
193 author: { login: "sam", name: null, avatarUrl: null },
194 state: isCompleted
195 ? { category: "closed", closeReason: "completed", name: "Done" }
196 : { category: "open", name: "Open" },
197 createdAt: issue.linkedAt,
198 updatedAt: issue.linkedAt,
199 closedAt: null,
200 assignees: [],
201 labels: [],
202 commentCount: 3,
203 projectTitle: "render",
204 writable: false,
205 capabilities: {
206 create: false,
207 edit: false,
208 comment: false,
209 labels: false,
210 assignees: false,
211 reactions: false,
212 templates: false,
213 linkedPullRequests: false,
214 events: false,
215 search: false,
216 },
217 viewerPermissions: {
218 setState: false,
219 comment: false,
220 edit: false,
221 labels: false,
222 assignees: false,
223 },
224 states: [],
225 viewer: null,
226 body: "",
227 comments: [],
228 commentsCursor: null,
229 events: [],
230 linkedPullRequests: [],
231 } satisfies IssueDetail);
232 });
233 __setClientSettingsForTests({
234 ...DEFAULT_CLIENT_SETTINGS,
235 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
236 });
237 await page.viewport(1400, 900);
238 const router = getRouter(
239 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${first.id}`] }),
240 );
241 await router.load();
242 await using _app = await render(<AppRoot router={router} />, {
243 // AppRoot brings its own router.
244 router: false,
245 });
246 const badge = page.getByRole("button", {
247 name: `Issue ${issue.displayKey}: ${issue.title}, Open`,
248 });
249 await expect.element(badge).toBeVisible();
250 expect(badge.element().querySelector("span")).toHaveClass(/text-emerald-600/);
251 expect(badge.element()).toHaveTextContent("123");
252 expect(badge.element()).not.toHaveTextContent("#");
253 const prBadge = page.getByRole("link", { name: "PR #124, status pending" });
254 await expect.element(prBadge).toHaveTextContent("124");
255 for (const control of [badge, prBadge]) {
256 expect(control.element().querySelector("span")).toHaveClass(
257 "contents",
258 "text-xs",
259 "tabular-nums",
260 );
261 }
262 const groupedBadge = page.getByRole("button", { name: "2 linked issues" });
263 await vi.waitFor(() =>
264 expect(groupedBadge.element().querySelector("span")).toHaveClass(/text-emerald-600/),
265 );
266 await userEvent.hover(badge);
267 const issueName = `Issue ${issue.displayKey}: ${liveTitle}`;
268 const previewLink = page.getByRole("link", { name: issueName });
269 await userEvent.hover(previewLink.getByText("sam", { exact: true }));
270 await expect.element(previewLink).toBeVisible();
271 const contextMenu = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });
272 await act(() => previewLink.element().dispatchEvent(contextMenu));
273 expect(contextMenu.defaultPrevented).toBe(false);
274 await userEvent.click(badge);
275 const issueRow = page
276 .getByRole("region", { name: "Linked issues" })
277 .getByRole("link", { name: issueName });
278 await expect.element(issueRow.getByRole("img", { name: "Open" })).toBeVisible();
279 await expect.element(issueRow.getByRole("img", { name: "3 comments" })).toBeVisible();
280 await expect.element(issueRow.getByRole("img", { name: "Linear" })).toBeVisible();
281 await expect.element(issueRow.getByText(issue.scope, { exact: true })).toBeVisible();
282 await userEvent.click(issueRow);
283 expect(router.history.location.pathname).toBe(`/${ENVIRONMENT_ID}/${linked.id}`);
284 await expect.element(page.getByRole("heading", { name: liveTitle })).toBeVisible();
285 await act(() => useRightPanelStore.getState().close(scopeThreadRef(ENVIRONMENT_ID, linked.id)));
286 await expect
287 .element(
288 page.getByRole("region", { name: "Thread details" }).getByRole("link", {
289 name: issueName,
290 exact: true,
291 }),
292 )
293 .toBeVisible();
294});
295​
296it("a machine chip stashed in one thread restores with its machine in another", async () => {
297 const other = threadWithHistory("thread-stash-restore", 1);
298 const asking = threadWithQuestion("thread-stash-question", "Which file should change?");
299 using _environment = installFakeEnvironment([other, asking]);
300 __setClientSettingsForTests({
301 ...DEFAULT_CLIENT_SETTINGS,
302 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
303 });
304 const draftId = DraftId.make("draft-stash-machine");
305 const machine = environmentContextRecord(EnvironmentId.make("environment-build"), "Build box");
306 const drafts = useComposerDraftStore.getState();
307 drafts.setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
308 threadId: ThreadId.make("thread-stash-machine"),
309 });
310 drafts.setPrompt(draftId, "Deploy on ");
311 drafts.addEnvironmentContexts(draftId, [machine]);
312 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
313 await router.load();
314 await using _app = await render(<AppRoot router={router} />, {
315 // AppRoot brings its own router.
316 router: false,
317 });
318 const editor = page.getByTestId("composer-editor");
319 const pressStashShortcut = async () => {
320 await userEvent.click(editor);
321 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
322 };
323 await vi.waitFor(() => expect(editor.element().textContent).toContain("Deploy on"));
324 // A draft can't stash until the shell snapshot lists its project.
325 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
326 await pressStashShortcut();
327 await vi.waitFor(() => expect(usePromptStashStore.getState().entries).toHaveLength(1));
328​
329 // An answer carries no machines, so an open question refuses the restore and keeps the entry.
330 await router.navigate({ to: `/${ENVIRONMENT_ID}/${asking.id}` });
331 await expect.element(page.getByText("Which file should change?")).toBeVisible();
332 await userEvent.click(page.getByRole("button", { name: /^Stashed prompts/ }));
333 await userEvent.click(page.getByRole("button", { name: /^Restore stashed prompt/ }));
334 await vi.waitFor(() =>
335 expect(document.body.textContent).toContain("Stashed machines can't go in an answer"),
336 );
337 expect(usePromptStashStore.getState().entries).toHaveLength(1);
338​
339 await router.navigate({ to: `/${ENVIRONMENT_ID}/${other.id}` });
340 await expect.element(page.getByText("Answer 0 for thread-stash-restore.")).toBeVisible();
341 await pressStashShortcut();
342​
343 await vi.waitFor(() => expect(editor.element().textContent).toContain("Deploy on"));
344 expect(
345 useComposerDraftStore.getState().getComposerDraft(scopeThreadRef(ENVIRONMENT_ID, other.id))
346 ?.environmentContexts,
347 ).toEqual([machine]);
348 expect(
349 useComposerDraftStore.getState().getComposerDraft(draftId)?.environmentContexts ?? [],
350 ).toEqual([]);
351});
352​
353it("a question that opens while a stashed file is checked keeps a machine stash", async () => {
354 const thread = threadWithHistory("thread-stash-late-question", 1);
355 const asking = threadWithQuestion("thread-stash-late-question", "Which file should change?");
356 const [request] = asking.runtimeRequests ?? [];
357 const question = asking.items.at(-1);
358 if (!request || !question) throw new Error("threadWithQuestion has no question");
359 using _environment = installFakeEnvironment([thread]);
360 __setClientSettingsForTests({
361 ...DEFAULT_CLIENT_SETTINGS,
362 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
363 });
364 usePromptStashStore.getState().stashEntry({
365 id: "stash-late-question",
366 createdAt: "2026-01-01T00:00:00.000Z",
367 prompt: "Deploy on ",
368 attachments: [],
369 files: [
370 {
371 id: "file-notes",
372 name: "notes.txt",
373 mimeType: "text/plain",
374 sizeBytes: 5,
375 attachmentId: "attachment-notes",
376 environmentId: ENVIRONMENT_ID,
377 },
378 ],
379 droppedImageNames: [],
380 records: [environmentContextRecord(EnvironmentId.make("environment-build"), "Build box")],
381 });
382 const router = getRouter(
383 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
384 );
385 await router.load();
386 await using _app = await render(<AppRoot router={router} />, {
387 // AppRoot brings its own router.
388 router: false,
389 });
390 await expect.element(page.getByText("Answer 0 for thread-stash-late-question.")).toBeVisible();
391 await userEvent.click(page.getByRole("button", { name: /^Stashed prompts/ }));
392 await userEvent.click(page.getByRole("button", { name: /^Restore stashed prompt/ }));
393​
394 // The question opens while the restore still waits on the server's file check.
395 await vi.waitFor(() => expect(hasPendingAssetUrl()).toBe(true));
396 await emitThreadEvent(thread.id, { type: "turn-item.updated", payload: question });
397 await emitThreadEvent(thread.id, { type: "runtime-request.updated", payload: request });
398 await expect.element(page.getByText("Which file should change?")).toBeVisible();
399 await answerAssetUrls();
400​
401 await vi.waitFor(() =>
402 expect(document.body.textContent).toContain("Stashed machines can't go in an answer"),
403 );
404 expect(usePromptStashStore.getState().entries).toHaveLength(1);
405 usePromptStashStore.getState().takeEntry("stash-late-question");
406});
407​
408it("a new draft does not load its reserved thread before the server lists it", async () => {
409 using _environment = installFakeEnvironment([]);
410 using fetchSpy = vi.spyOn(globalThis, "fetch");
411 __setClientSettingsForTests({
412 ...DEFAULT_CLIENT_SETTINGS,
413 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
414 });
415 const draftId = DraftId.make("draft-27443");
416 const threadId = ThreadId.make("thread-27443");
417 useComposerDraftStore
418 .getState()
419 .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, { threadId });
420​
421 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
422 await router.load();
423 await using _app = await render(<AppRoot router={router} />, {
424 // AppRoot brings its own router.
425 router: false,
426 });
427 await expect.element(page.getByTestId("composer-editor")).toBeVisible();
428 // The shell snapshot has arrived once the sidebar lists the project, so the connection is up.
429 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
430​
431 const threadRequests = fetchSpy.mock.calls
432 .map(([input]) => String(input instanceof Request ? input.url : input))
433 .filter((url) => url.includes(`/api/orchestration/threads/${threadId}/`));
434 // A 404 here marks the thread deleted, and the view never loads it once the send creates it.
435 expect(threadRequests).toEqual([]);
436});
437​
438it("a failed image-only first send of a new thread keeps the new draft", async () => {
439 using _environment = installFakeEnvironment([]);
440 __setClientSettingsForTests({
441 ...DEFAULT_CLIENT_SETTINGS,
442 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
443 });
444 const draftId = DraftId.make("draft-image-only-interrupted");
445 useComposerDraftStore
446 .getState()
447 .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
448 threadId: ThreadId.make("thread-image-only-interrupted"),
449 });
450 // A refusal fails at once; an interrupted launch would wait for a reconnect and be resent.
451 using launch = holdRpc(
452 ORCHESTRATION_V2_WS_METHODS.launchThread,
453 Effect.fail(new LaunchRefused()),
454 );
455 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
456 await router.load();
457 await using _app = await render(<AppRoot router={router} />, {
458 // AppRoot brings its own router.
459 router: false,
460 });
461 using _uploads = acceptAttachmentUploads();
462 const editor = page.getByTestId("composer-editor");
463 await expect.element(editor).toBeVisible();
464 // The send needs the project, which arrives with the shell snapshot.
465 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
466​
467 await userEvent.click(editor);
468 const clipboardData = new DataTransfer();
469 clipboardData.items.add(new File([PNG], "shot.png", { type: "image/png" }));
470 editor
471 .element()
472 .dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
473 await expect.element(page.getByRole("img", { name: "shot.png" })).toBeVisible();
474 await userEvent.keyboard("{Enter}");
475 await vi.waitFor(() => expect(launch.calls).toHaveLength(1));
476 await userEvent.keyboard("next draft");
477 await expect.element(editor).toHaveTextContent("next draft");
478 launch.release();
479​
480 await expect.element(page.getByText("Message not sent")).toBeVisible();
481 await expect.element(editor).toHaveTextContent("next draft");
482 // With no text there is nothing to copy.
483 expect(page.getByText("Copy message", { exact: true }).query()).toBeNull();
484});
485​
486it.each(["new", "existing"] as const)(
487 "Enter while an image compresses shows a cancellable banner, cancels on edit or Esc, and still sends after leaving a %s thread",
488 async (kind) => {
489 const thread = threadWithHistory(`upload-wait-${kind}`, 1);
490 const other = threadWithHistory(`upload-wait-other-${kind}`, 1);
491 using _environment = installFakeEnvironment(kind === "existing" ? [thread, other] : [other], {
492 acceptCommands: true,
493 });
494 __setClientSettingsForTests({
495 ...DEFAULT_CLIENT_SETTINGS,
496 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
497 });
498 const draftId = DraftId.make(`draft-upload-wait-${kind}`);
499 if (kind === "new") {
500 useComposerDraftStore
501 .getState()
502 .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
503 threadId: thread.id,
504 });
505 }
506 using launch = holdRpc(ORCHESTRATION_V2_WS_METHODS.launchThread, Effect.interrupt);
507 const router = getRouter(
508 createMemoryHistory({
509 initialEntries: [kind === "new" ? `/draft/${draftId}` : `/${ENVIRONMENT_ID}/${thread.id}`],
510 }),
511 );
512 await router.load();
513 await using _app = await render(<AppRoot router={router} />, {
514 // AppRoot brings its own router.
515 router: false,
516 });
517 const compressed = Promise.withResolvers<void>();
518 compression.gate = compressed.promise;
519 using _compression = { [Symbol.dispose]: () => (compression.gate = null) };
520 using _uploads = acceptAttachmentUploads();
521 const editor = page.getByTestId("composer-editor");
522 await expect.element(editor).toBeVisible();
523 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
524​
525 await userEvent.click(editor);
526 const clipboardData = new DataTransfer();
527 clipboardData.items.add(new File([PNG], "shot.png", { type: "image/png" }));
528 editor
529 .element()
530 .dispatchEvent(
531 new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }),
532 );
533​
534 // Enter arms the send and shows the banner plus a disabled spinner button.
535 await userEvent.keyboard("check image{Enter}");
536 await expect.element(page.getByText("Sending once image is ready")).toBeVisible();
537 const waitingButton = page.getByRole("button", { name: "Sending when ready", exact: true });
538 await expect.element(waitingButton).toBeDisabled();
539 await expect.element(waitingButton).toHaveAttribute("aria-busy", "true");
540​
541 // Typing disarms the queued send and keeps the edit.
542 await userEvent.keyboard(" now");
543 await expect.element(page.getByText("Sending once image is ready")).not.toBeInTheDocument();
544 await expect.element(editor).toHaveTextContent("check image now");
545​
546 // Enter arms again; Esc cancels cleanly.
547 await userEvent.keyboard("{Enter}");
548 await expect.element(page.getByText("Sending once image is ready")).toBeVisible();
549 await userEvent.keyboard("{Escape}");
550 await expect.element(page.getByText("Sending once image is ready")).not.toBeInTheDocument();
551​
552 // Enter arms again; leaving the thread still sends once the image is ready.
553 await userEvent.keyboard("{Enter}");
554 await expect.element(page.getByText("Sending once image is ready")).toBeVisible();
555 await router.navigate({ to: `/${ENVIRONMENT_ID}/${other.id}` });
556 await expect.element(page.getByText(`Answer 0 for upload-wait-other-${kind}.`)).toBeVisible();
557​
558 compressed.resolve();
559 await vi.waitFor(() => {
560 if (kind === "new") {
561 expect(launch.calls).toHaveLength(1);
562 } else {
563 expect(dispatchedCommands()).toContainEqual(
564 expect.objectContaining({
565 type: "message.dispatch",
566 threadId: thread.id,
567 attachments: [expect.objectContaining({ type: "image", id: "upload-1" })],
568 }),
569 );
570 }
571 });
572 launch.release();
573 },
574);
575​
576it("a file picked after the phone composer collapses still attaches", async () => {
577 const thread = threadWithHistory("thread-40993", 1);
578 using _environment = installFakeEnvironment([thread]);
579 await page.viewport(390, 844);
580 __setClientSettingsForTests({
581 ...DEFAULT_CLIENT_SETTINGS,
582 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
583 });
584 const router = getRouter(
585 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
586 );
587 await router.load();
588 await using _app = await render(<AppRoot router={router} />, {
589 // AppRoot brings its own router.
590 router: false,
591 });
592 using _uploads = acceptAttachmentUploads();
593 const editor = page.getByTestId("composer-editor");
594 await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible();
595 await userEvent.click(editor);
596 await expect.element(page.getByRole("button", { name: "Attach files" })).toBeVisible();
597 const input = document.querySelector<HTMLInputElement>(
598 'form[data-chat-composer-form] input[type="file"]',
599 );
600 expect(input).not.toBeNull();
601​
602 // Opening the native picker blurs the editor, which collapses the phone composer.
603 (editor.element() as HTMLElement).blur();
604 await expect.element(page.getByRole("button", { name: "Attach files" })).not.toBeInTheDocument();
605 const files = new DataTransfer();
606 files.items.add(new File([PNG], "picked.png", { type: "image/png" }));
607 input!.files = files.files;
608 input!.dispatchEvent(new Event("change", { bubbles: true }));
609​
610 await expect.element(page.getByRole("img", { name: "picked.png" })).toBeVisible();
611});
612​
613it("opens the thread actions menu for an older settled thread the shell leaves out", async () => {
614 const thread = { ...threadWithHistory("older-settled", 1), olderSettled: true as const };
615 using _environment = installFakeEnvironment([thread]);
616 __setClientSettingsForTests({
617 ...DEFAULT_CLIENT_SETTINGS,
618 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
619 });
620​
621 const router = getRouter(
622 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
623 );
624 await router.load();
625 await using _app = await render(<AppRoot router={router} />, {
626 // AppRoot brings its own router.
627 router: false,
628 });
629 await expect.element(page.getByText("older-settled: question 0")).toBeVisible();
630​
631 await page.getByRole("button", { name: `Thread actions for ${thread.title}` }).click();
632 // Without a bound the poll runs to the test deadline and reports a bare timeout.
633 await expect
634 .element(page.getByRole("menuitem", { name: "Rename thread" }), { timeout: 5_000 })
635 .toBeVisible();
636});
637​
638it("retains each thread's diff selection when returning from another thread or Settings", async () => {
639 const a = threadWithHistory("diff-selection-a", 1);
640 const b = threadWithHistory("diff-selection-b", 1);
641 using _environment = installFakeEnvironment([a, b]);
642 __setClientSettingsForTests({
643 ...DEFAULT_CLIENT_SETTINGS,
644 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
645 });
646 const aRef = scopeThreadRef(ENVIRONMENT_ID, a.id);
647 const bRef = scopeThreadRef(ENVIRONMENT_ID, b.id);
648 useRightPanelStore.getState().open(aRef, "diff");
649 useRightPanelStore.getState().open(bRef, "diff");
650 useDiffPanelStore.getState().selectBranchBaseRef(bRef, "origin/release");
651 const router = getRouter(createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${a.id}`] }));
652 await router.load();
653 await using _app = await render(<AppRoot router={router} />, {
654 // AppRoot brings its own router.
655 router: false,
656 });
657 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
658 await act(() => useDiffPanelStore.getState().selectGitScope(aRef, "unstaged"));
659​
660 await act(() =>
661 router.navigate({
662 to: "/$environmentId/$threadId",
663 params: { environmentId: ENVIRONMENT_ID, threadId: b.id },
664 }),
665 );
666 await expect.element(page.getByText(`Answer 0 for ${b.id}.`)).toBeVisible();
667 expect(selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, bRef)).toEqual({
668 kind: "branch",
669 baseRef: "origin/release",
670 });
671 await act(() =>
672 router.navigate({
673 to: "/$environmentId/$threadId",
674 params: { environmentId: ENVIRONMENT_ID, threadId: a.id },
675 }),
676 );
677 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
678 expect(selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, aRef)).toEqual({
679 kind: "unstaged",
680 });
681​
682 await act(() => useDiffPanelStore.getState().selectTurn(aRef, a.runs[0]!.id));
683 await act(() => router.navigate({ to: "/settings/general" }));
684 await expect
685 .element(page.getByRole("heading", { name: "Time format", exact: true }))
686 .toBeVisible();
687 await act(() =>
688 router.navigate({
689 to: "/$environmentId/$threadId",
690 params: { environmentId: ENVIRONMENT_ID, threadId: a.id },
691 }),
692 );
693 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
694 expect(
695 selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, aRef),
696 ).toMatchObject({
697 kind: "turn",
698 turnId: a.runs[0]!.id,
699 });
700});
701​
702it("a stashed prompt ending in a file chip restores with the chip", async () => {
703 using _environment = installFakeEnvironment([]);
704 __setClientSettingsForTests({
705 ...DEFAULT_CLIENT_SETTINGS,
706 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
707 });
708 const draftId = DraftId.make("draft-28338");
709 const drafts = useComposerDraftStore.getState();
710 drafts.setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
711 threadId: ThreadId.make("thread-28338"),
712 });
713 drafts.setPrompt(draftId, "Check [package.json](package.json) ");
714 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
715 await router.load();
716 await using _app = await render(<AppRoot router={router} />, {
717 // AppRoot brings its own router.
718 router: false,
719 });
720 const chip = page.getByRole("button", { name: "Preview package.json" });
721 await expect.element(chip).toBeVisible();
722 // The stash shortcut is a no-op until the shell snapshot lists the project.
723 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
724​
725 const editor = page.getByTestId("composer-editor");
726 await userEvent.click(editor);
727 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
728 await expect.element(chip).not.toBeInTheDocument();
729 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
730​
731 await vi.waitFor(() => expect(editor.element().textContent).toContain("Check"));
732 expect(editor.element().textContent).not.toContain("[package.json](package.json)");
733 await expect.element(chip).toBeVisible();
734});
735​
736it("a rejected send leaves the timeline when a new draft was typed meanwhile", async () => {
737 const thread = threadWithHistory("rejected-send", 1);
738 using _environment = installFakeEnvironment([thread], {
739 acceptCommands: true,
740 holdCommand: (command) => command.type === "message.dispatch",
741 });
742 __setClientSettingsForTests({
743 ...DEFAULT_CLIENT_SETTINGS,
744 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
745 });
746 const router = getRouter(
747 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
748 );
749 await router.load();
750 await using _app = await render(<AppRoot router={router} />, {
751 // AppRoot brings its own router.
752 router: false,
753 });
754 await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible();
755​
756 const editor = page.getByTestId("composer-editor");
757 await userEvent.click(editor);
758 await userEvent.keyboard("Failed prompt{Enter}");
759 await vi.waitFor(() =>
760 expect(dispatchedCommands().map((command) => command.type)).toContain("message.dispatch"),
761 );
762 await expect.element(page.getByText("Failed prompt")).toBeVisible();
763 await userEvent.keyboard("Next draft");
764​
765 await rejectPendingCommand("Attachment 'sample.png' cannot be sent.");
766​
767 await expect.element(page.getByText("Attachment 'sample.png' cannot be sent.")).toBeVisible();
768 await expect.element(page.getByText("Failed prompt")).not.toBeInTheDocument();
769 expect(editor.element().textContent).toContain("Next draft");
770});
771​
772it("Enter on an empty prompt resumes an interrupted thread", async () => {
773 const history = threadWithHistory("interrupted", 1);
774 const interruptedRun = { ...history.runs[0]!, status: "interrupted" as const };
775 const thread = { ...history, runs: [interruptedRun] };
776 using _environment = installFakeEnvironment([thread], { acceptCommands: true });
777 __setClientSettingsForTests({
778 ...DEFAULT_CLIENT_SETTINGS,
779 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
780 });
781 const router = getRouter(
782 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
783 );
784 await router.load();
785 await using _app = await render(<AppRoot router={router} />, {
786 // AppRoot brings its own router.
787 router: false,
788 });
789 await expect.element(page.getByRole("button", { name: "Resume thread" })).toBeVisible();
790​
791 await userEvent.click(page.getByTestId("composer-editor"));
792 await userEvent.keyboard("{Enter}");
793​
794 await vi.waitFor(() =>
795 expect(dispatchedCommands()).toContainEqual(
796 expect.objectContaining({ manualContinuationOfRunId: interruptedRun.id }),
797 ),
798 );
799});
800​
801it("opening a thread or returning to the window on a touch tablet does not focus the composer", async () => {
802 const realMatchMedia = window.matchMedia.bind(window);
803 using _touch = vi
804 .spyOn(window, "matchMedia")
805 .mockImplementation((query) => realMatchMedia(query === "(pointer: coarse)" ? "all" : query));
806 const first = threadWithHistory("thread-29469-a", 1);
807 const second = threadWithHistory("thread-29469-b", 1);
808 using _environment = installFakeEnvironment([first, second]);
809 // iPad Pro 11 in landscape: the desktop layout, above max-sm.
810 await page.viewport(1194, 834);
811 __setClientSettingsForTests({
812 ...DEFAULT_CLIENT_SETTINGS,
813 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
814 });
815 const router = getRouter(
816 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${first.id}`] }),
817 );
818 await router.load();
819 await using _app = await render(<AppRoot router={router} />, {
820 // AppRoot brings its own router.
821 router: false,
822 });
823 const composer = page.getByTestId("composer-editor");
824 await expect.element(page.getByText(`Answer 0 for ${first.id}.`)).toBeVisible();
825​
826 // Fake frames hold the next thread entry's focus frame until the test advances it.
827 using _timers = fakeTimers();
828 await act(() =>
829 router.navigate({
830 to: "/$environmentId/$threadId",
831 params: { environmentId: ENVIRONMENT_ID, threadId: second.id },
832 }),
833 );
834 await expect.element(page.getByText(`Answer 0 for ${second.id}.`)).toBeVisible();
835 vi.advanceTimersToNextFrame();
836 // Focusing the editor raises the on-screen keyboard, which shrinks the page on iPadOS.
837 expect(document.activeElement).not.toBe(composer.element());
838​
839 // ChatView waits two frames after window focus before refocusing the composer.
840 window.dispatchEvent(new FocusEvent("focus"));
841 vi.advanceTimersToNextFrame();
842 vi.advanceTimersToNextFrame();
843 expect(document.activeElement).not.toBe(composer.element());
844});
845​
846it("a mounted thread view lets go of the thread structures it has replaced", async () => {
847 // Items are shared with the fixture, so a reopen's snapshot also carries the earlier updates.
848 const history = threadWithHistory("updated", 3);
849 const items = [...history.items];
850 const updated = { ...history, items };
851 const other = threadWithHistory("other", 3);
852 using _environment = installFakeEnvironment([updated, other]);
853 __setClientSettingsForTests({
854 ...DEFAULT_CLIENT_SETTINGS,
855 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
856 });
857 const router = getRouter(createMemoryHistory({ initialEntries: ["/"] }));
858 await router.load();
859 await using _app = await render(<AppRoot router={router} />, { router: false });
860 const open = async (threadId: ThreadId, text: string) => {
861 await act(() =>
862 router.navigate({
863 to: "/$environmentId/$threadId",
864 params: { environmentId: ENVIRONMENT_ID, threadId },
865 }),
866 );
867 await expect.element(page.getByText(text).first()).toBeVisible();
868 };
869 const structureAtom = environmentThreadDetails.quietThreadAtom(
870 scopeThreadRef(ENVIRONMENT_ID, updated.id),
871 );
872​
873 // Each round, a new answer arrives while the thread is shown, then the user switches away.
874 const shown: Array<WeakRef<object>> = [];
875 await open(other.id, "Answer 2 for other.");
876 for (let round = 0; round < 6; round++) {
877 await open(updated.id, round === 0 ? "Answer 2 for updated." : `Update ${round - 1}.`);
878 const update = assistantItem(
879 updated.id,
880 RunId.make("updated-run-2"),
881 `updated-update-${round}`,
882 6 + round,
883 `Update ${round}.`,
884 );
885 items.push(update);
886 await act(() => emitThreadEvent(updated.id, { type: "turn-item.updated", payload: update }));
887 await expect.element(page.getByText(`Update ${round}.`)).toBeVisible();
888 shown.push(new WeakRef(appAtomRegistry.get(structureAtom)!.projection));
889 await open(other.id, "Answer 2 for other.");
890 }
891 await cdp().send("HeapProfiler.collectGarbage");
892​
893 // The thread keeps its latest structure, and the timeline may remember the one before it.
894 const kept = shown.slice(0, -2).flatMap((structure, round) => (structure.deref() ? [round] : []));
895 expect(kept).toEqual([]);
896});
897​
898it("a shortcut conditioned on rightPanelOpen sees the thread's open right panel", async () => {
899 await page.viewport(1280, 800);
900 const thread = threadWithHistory("thread-panel-shortcut", 1);
901 using _environment = installFakeEnvironment([thread], {
902 keybindings: mergeWithDefaultKeybindings(
903 compileResolvedKeybindingsConfig([
904 { key: "ctrl+t", command: "rightPanel.new", when: "rightPanelOpen && !terminalFocus" },
905 { key: "ctrl+t", command: "rightPanel.toggle", when: "!rightPanelOpen" },
906 ]),
907 ),
908 });
909 __setClientSettingsForTests({
910 ...DEFAULT_CLIENT_SETTINGS,
911 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
912 });
913 const router = getRouter(
914 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
915 );
916 await router.load();
917 await using _app = await render(<AppRoot router={router} />, {
918 // AppRoot brings its own router.
919 router: false,
920 });
921 const composer = page.getByTestId("composer-editor");
922 const toggle = page.getByRole("button", { name: "Toggle right panel", exact: true });
923 await expect.element(toggle).toHaveAttribute("aria-pressed", "false");
924 await toggle.click();
925 await page.getByRole("button", { name: /^Files/ }).click();
926 await composer.click();
927 await userEvent.keyboard("{Control>}t{/Control}");
928 await expect.element(page.getByRole("menuitem", { name: /Files/ })).toBeVisible();
929 await expect.element(toggle).toHaveAttribute("aria-pressed", "true");
930});
931​
932it("selecting a side-chat tab focuses that side chat's composer", async () => {
933 const parent = threadWithHistory("focus-parent", 1);
934 // The shell loaded by the file's first test stays; a family read serves side chats added later.
935 const sideChat = (name: string) => ({
936 ...threadWithHistory(name, 1),
937 sideChatOf: parent.id,
938 olderSettled: true as const,
939 });
940 const side = sideChat("focus-side");
941 const otherSide = sideChat("focus-other-side");
942 await page.viewport(1400, 900);
943 using _environment = installFakeEnvironment([parent, side, otherSide]);
944 __setClientSettingsForTests({
945 ...DEFAULT_CLIENT_SETTINGS,
946 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
947 });
948 const parentRef = scopeThreadRef(ENVIRONMENT_ID, parent.id);
949 useRightPanelStore.getState().openThread(parentRef, otherSide.id);
950 useRightPanelStore.getState().openThread(parentRef, side.id);
951 const router = getRouter(
952 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${parent.id}`] }),
953 );
954 await router.load();
955 await using screen = await render(<AppRoot router={router} />, {
956 // AppRoot brings its own router.
957 router: false,
958 });
959 using _focus = { [Symbol.dispose]: startWorkspaceFocus(router) };
960 const mainEditor = screen.getByRole("textbox", { name: `Message ${parent.title}`, exact: true });
961 const sideEditor = screen.getByRole("textbox", { name: `Message ${side.title}`, exact: true });
962 await expect.element(sideEditor).toBeVisible();
963 await userEvent.click(mainEditor);
964 await userEvent.keyboard("main draft");
965​
966 await userEvent.click(screen.getByRole("button", { name: otherSide.title, exact: true }));
967 const otherEditor = screen.getByRole("textbox", {
968 name: `Message ${otherSide.title}`,
969 exact: true,
970 });
971 await expect.element(otherEditor).toHaveFocus();
972 await userEvent.keyboard("other draft");
973 await expect.element(otherEditor).toHaveTextContent("other draft");
974​
975 await userEvent.click(screen.getByRole("button", { name: side.title, exact: true }));
976 await expect.element(sideEditor).toHaveFocus();
977 await expect.element(mainEditor).toHaveTextContent("main draft");
978});
979​
980it("a subagent tab shows its read-only bar under no header of its own", async () => {
981 const parent = threadWithHistory("subagent-parent", 1);
982 const subagent = {
983 ...threadWithHistory("subagent-child", 1),
984 providerSubagentOf: parent.id,
985 olderSettled: true as const,
986 };
987 await page.viewport(1400, 900);
988 using _environment = installFakeEnvironment([parent, subagent]);
989 __setClientSettingsForTests({
990 ...DEFAULT_CLIENT_SETTINGS,
991 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
992 });
993 const parentRef = scopeThreadRef(ENVIRONMENT_ID, parent.id);
994 useRightPanelStore.getState().openThread(parentRef, subagent.id);
995 const router = getRouter(
996 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${parent.id}`] }),
997 );
998 await router.load();
999 await using screen = await render(<AppRoot router={router} />, {
1000 // AppRoot brings its own router.
1001 router: false,
1002 });
1003 const pane = screen.getByTestId("side-thread-pane");
1004 // No header of its own: the tab names it, and only a side chat has actions to put in one.
1005 await expect.element(pane.getByRole("heading", { name: subagent.title })).not.toBeInTheDocument();
1006 await expect.element(pane.getByText("Runs on its own")).toBeVisible();
1007 await expect.element(pane.getByRole("button", { name: "Add to chat" })).not.toBeInTheDocument();
1008 await expect
1009 .element(screen.getByRole("textbox", { name: `Message ${subagent.title}`, exact: true }))
1010 .not.toBeInTheDocument();
1011 await expect
1012 .element(screen.getByRole("textbox", { name: `Message ${parent.title}`, exact: true }))
1013 .toBeVisible();
1014});
1015​
1016it("/side sends the draft's attachments and context, and keeps them when it does not start", async () => {
1017 await page.viewport(1400, 900);
1018 const thread = threadWithHistory("side-attachments", 1);
1019 let holdFork = false;
1020 using _environment = installFakeEnvironment([thread], {
1021 acceptCommands: true,
1022 holdCommand: (command) => holdFork && command.type === "thread.fork",
1023 });
1024 __setClientSettingsForTests({
1025 ...DEFAULT_CLIENT_SETTINGS,
1026 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
1027 });
1028 const router = getRouter(
1029 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
1030 );
1031 await router.load();
1032 await using _app = await render(<AppRoot router={router} />, {
1033 // AppRoot brings its own router.
1034 router: false,
1035 });
1036 using _uploads = acceptAttachmentUploads();
1037 await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible();
1038​
1039 const editor = page.getByRole("textbox", { name: `Message ${thread.title}`, exact: true });
1040 const image = page.getByRole("img", { name: "shot.png" });
1041 const sendImageToSideChat = async () => {
1042 await userEvent.click(editor);
1043 const clipboardData = new DataTransfer();
1044 clipboardData.items.add(new File([PNG], "shot.png", { type: "image/png" }));
1045 editor
1046 .element()
1047 .dispatchEvent(
1048 new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }),
1049 );
1050 await expect.element(image).toBeVisible();
1051 await insertText("/side what is this?");
1052 await userEvent.keyboard("{Enter}");
1053 await expect.element(image).not.toBeInTheDocument();
1054 };
1055 // The tab opens once the start finished; until then `/side` refuses another side chat.
1056 const sideChatTabs = page.getByRole("button", { name: "Side chat", exact: true });
1057 const sentMessage = async (fields: Record<string, unknown>, openTabs: number) => {
1058 await vi.waitFor(() =>
1059 expect(dispatchedCommands()).toContainEqual(
1060 expect.objectContaining({ type: "message.dispatch", ...fields }),
1061 ),
1062 );
1063 await expect.element(sideChatTabs).toHaveLength(openTabs);
1064 };
1065​
1066 await sendImageToSideChat();
1067 await sentMessage(
1069 text: "what is this?",
1070 attachments: [expect.objectContaining({ type: "image", id: "upload-1" })],
1071 context: {
1072 version: 1,
1073 records: [expect.objectContaining({ kind: "image", attachmentId: "upload-1" })],
1074 },
1075 },
1076 1,
1077 );
1078​
1079 // A reply alone is enough to send.
1080 await page.getByRole("button", { name: "Reply to this response" }).first().click();
1081 await userEvent.click(editor);
1082 await insertText("/side ");
1083 await userEvent.keyboard("{Enter}");
1084 await sentMessage(
1086 context: expect.objectContaining({
1087 records: [expect.objectContaining({ kind: "response" })],
1088 }),
1089 },
1090 2,
1091 );
1092​
1093 // A failed start puts the message back after the draft typed meanwhile.
1094 holdFork = true;
1095 await sendImageToSideChat();
1096 await insertText("next draft");
1097 await vi.waitFor(() =>
1098 expect(dispatchedCommands().filter((command) => command.type === "thread.fork")).toHaveLength(
1099 3,
1100 ),
1101 );
1102 await rejectPendingCommand("Side chats are paused.");
1103 await expect.element(image).toBeVisible();
1104 await vi.waitFor(() =>
1105 expect((editor.element() as HTMLElement).innerText.split("\n").filter(Boolean)).toEqual([
1106 "next draft",
1107 "/side what is this?",
1108 ]),
1109 );
1110});
1111​
1112it("opening Settings without a page event closes the composer model picker and permissions menu", async () => {
1113 using _environment = installFakeEnvironment([]);
1114 __setClientSettingsForTests({
1115 ...DEFAULT_CLIENT_SETTINGS,
1116 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
1117 });
1118 const draftId = DraftId.make("draft-29219");
1119 useComposerDraftStore
1120 .getState()
1121 .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
1122 threadId: ThreadId.make("thread-29219"),
1123 });
1124​
1125 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
1126 await router.load();
1127 await using _app = await render(<AppRoot router={router} />, {
1128 // AppRoot brings its own router.
1129 router: false,
1130 });
1131 await expect.element(page.getByTestId("composer-editor")).toBeVisible();
1132 const trigger = document.querySelector<HTMLElement>("[data-chat-provider-model-picker]");
1133 if (!trigger) throw new Error("composer model picker trigger missing");
1134 await userEvent.click(trigger);
1135 const search = page.getByPlaceholder("Search models...");
1136 await expect.element(search).toBeVisible();
1137​
1138 // The desktop menu's open-settings accelerator navigates with no key or pointer event in the page.
1139 await act(() => router.navigate({ to: "/settings" }));
1140 await expect.element(page.getByRole("dialog", { name: "Settings" })).toBeVisible();
1141 await expect.element(search).not.toBeInTheDocument();
1142​
1143 await act(() => router.navigate({ to: "/draft/$draftId", params: { draftId } }));
1144 await page.getByRole("button", { name: /^Permissions: / }).click();
1145 // The modal Settings dialog aria-hides everything outside it, so match text, not role.
1146 const permissions = page.getByText("Allow commands and edits without prompts.").last();
1147 await expect.element(permissions).toBeVisible();
1148 await act(() => router.navigate({ to: "/settings" }));
1149 await expect.element(page.getByRole("dialog", { name: "Settings" })).toBeVisible();
1150 await expect.element(permissions).not.toBeInTheDocument();
1151});