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

ChatView.browser.test.tsx

1,047 lines42.2 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: issueRef.key,
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 { ...linked, issues: [issue] },
169 { ...grouped, issues: [completed, issue] },
170 ]);
171 const liveTitle = "Add keyboard shortcuts to the sidebar";
172 using _detail = answerRpc(WS_METHODS.issuesDetail, (input: IssueRef) => {
173 const isCompleted = input.key === completed.key;
174 expect(input).toEqual({ ...issueRef, key: isCompleted ? completed.key : issue.key });
175 return Effect.succeed({
176 ...(isCompleted ? completed : issue),
177 title: isCompleted ? completed.title : liveTitle,
178 author: { login: "sam", name: null, avatarUrl: null },
179 state: isCompleted
180 ? { category: "closed", closeReason: "completed", name: "Done" }
181 : { category: "open", name: "Open" },
182 createdAt: issue.linkedAt,
183 updatedAt: issue.linkedAt,
184 closedAt: null,
185 assignees: [],
186 labels: [],
187 commentCount: 3,
188 projectTitle: "render",
189 writable: false,
190 capabilities: {
191 create: false,
192 edit: false,
193 comment: false,
194 labels: false,
195 assignees: false,
196 reactions: false,
197 templates: false,
198 linkedPullRequests: false,
199 events: false,
200 search: false,
201 },
202 viewerPermissions: {
203 setState: false,
204 comment: false,
205 edit: false,
206 labels: false,
207 assignees: false,
208 },
209 states: [],
210 viewer: null,
211 body: "",
212 comments: [],
213 commentsCursor: null,
214 events: [],
215 linkedPullRequests: [],
216 } satisfies IssueDetail);
217 });
218 __setClientSettingsForTests({
219 ...DEFAULT_CLIENT_SETTINGS,
220 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
221 });
222 await page.viewport(1400, 900);
223 const router = getRouter(
224 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${first.id}`] }),
225 );
226 await router.load();
227 await using _app = await render(<AppRoot router={router} />, {
228 // AppRoot brings its own router.
229 router: false,
230 });
231 const badge = page.getByRole("button", {
232 name: `Issue ${issue.displayKey}: ${issue.title}, Open`,
233 });
234 await expect.element(badge).toBeVisible();
235 expect(badge.element().querySelector("svg")).toHaveClass(/text-emerald-600/);
236 const groupedBadge = page.getByRole("button", { name: "2 linked issues" });
237 await vi.waitFor(() =>
238 expect(groupedBadge.element().querySelector("svg")).toHaveClass(/text-emerald-600/),
239 );
240 await userEvent.hover(badge);
241 const issueName = `Issue ${issue.displayKey}: ${liveTitle}`;
242 const previewLink = page.getByRole("link", { name: issueName });
243 await userEvent.hover(previewLink.getByText("sam", { exact: true }));
244 await expect.element(previewLink).toBeVisible();
245 const contextMenu = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });
246 await act(() => previewLink.element().dispatchEvent(contextMenu));
247 expect(contextMenu.defaultPrevented).toBe(false);
248 await userEvent.click(badge);
249 const issueRow = page
250 .getByRole("region", { name: "Linked issues" })
251 .getByRole("link", { name: issueName });
252 await expect.element(issueRow.getByRole("img", { name: "Open" })).toBeVisible();
253 await expect.element(issueRow.getByRole("img", { name: "3 comments" })).toBeVisible();
254 await expect.element(issueRow.getByRole("img", { name: "Linear" })).toBeVisible();
255 await expect.element(issueRow.getByText(issue.scope, { exact: true })).toBeVisible();
256 await userEvent.click(issueRow);
257 expect(router.history.location.pathname).toBe(`/${ENVIRONMENT_ID}/${linked.id}`);
258 await expect.element(page.getByRole("heading", { name: liveTitle })).toBeVisible();
259 await act(() => useRightPanelStore.getState().close(scopeThreadRef(ENVIRONMENT_ID, linked.id)));
260 await expect
261 .element(
262 page.getByRole("region", { name: "Thread details" }).getByRole("link", {
263 name: issueName,
264 exact: true,
265 }),
266 )
267 .toBeVisible();
268});
269​
270it("a machine chip stashed in one thread restores with its machine in another", async () => {
271 const other = threadWithHistory("thread-stash-restore", 1);
272 const asking = threadWithQuestion("thread-stash-question", "Which file should change?");
273 using _environment = installFakeEnvironment([other, asking]);
274 __setClientSettingsForTests({
275 ...DEFAULT_CLIENT_SETTINGS,
276 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
277 });
278 const draftId = DraftId.make("draft-stash-machine");
279 const machine = environmentContextRecord(EnvironmentId.make("environment-build"), "Build box");
280 const drafts = useComposerDraftStore.getState();
281 drafts.setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
282 threadId: ThreadId.make("thread-stash-machine"),
283 });
284 drafts.setPrompt(draftId, "Deploy on ");
285 drafts.addEnvironmentContexts(draftId, [machine]);
286 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
287 await router.load();
288 await using _app = await render(<AppRoot router={router} />, {
289 // AppRoot brings its own router.
290 router: false,
291 });
292 const editor = page.getByTestId("composer-editor");
293 const pressStashShortcut = async () => {
294 await userEvent.click(editor);
295 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
296 };
297 await vi.waitFor(() => expect(editor.element().textContent).toContain("Deploy on"));
298 // A draft can't stash until the shell snapshot lists its project.
299 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
300 await pressStashShortcut();
301 await vi.waitFor(() => expect(usePromptStashStore.getState().entries).toHaveLength(1));
302​
303 // An answer carries no machines, so an open question refuses the restore and keeps the entry.
304 await router.navigate({ to: `/${ENVIRONMENT_ID}/${asking.id}` });
305 await expect.element(page.getByText("Which file should change?")).toBeVisible();
306 await userEvent.click(page.getByRole("button", { name: /^Stashed prompts/ }));
307 await userEvent.click(page.getByRole("button", { name: /^Restore stashed prompt/ }));
308 await vi.waitFor(() =>
309 expect(document.body.textContent).toContain("Stashed machines can't go in an answer"),
310 );
311 expect(usePromptStashStore.getState().entries).toHaveLength(1);
312​
313 await router.navigate({ to: `/${ENVIRONMENT_ID}/${other.id}` });
314 await expect.element(page.getByText("Answer 0 for thread-stash-restore.")).toBeVisible();
315 await pressStashShortcut();
316​
317 await vi.waitFor(() => expect(editor.element().textContent).toContain("Deploy on"));
318 expect(
319 useComposerDraftStore.getState().getComposerDraft(scopeThreadRef(ENVIRONMENT_ID, other.id))
320 ?.environmentContexts,
321 ).toEqual([machine]);
322 expect(
323 useComposerDraftStore.getState().getComposerDraft(draftId)?.environmentContexts ?? [],
324 ).toEqual([]);
325});
326​
327it("a question that opens while a stashed file is checked keeps a machine stash", async () => {
328 const thread = threadWithHistory("thread-stash-late-question", 1);
329 const asking = threadWithQuestion("thread-stash-late-question", "Which file should change?");
330 const [request] = asking.runtimeRequests ?? [];
331 const question = asking.items.at(-1);
332 if (!request || !question) throw new Error("threadWithQuestion has no question");
333 using _environment = installFakeEnvironment([thread]);
334 __setClientSettingsForTests({
335 ...DEFAULT_CLIENT_SETTINGS,
336 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
337 });
338 usePromptStashStore.getState().stashEntry({
339 id: "stash-late-question",
340 createdAt: "2026-01-01T00:00:00.000Z",
341 prompt: "Deploy on ",
342 attachments: [],
343 files: [
344 {
345 id: "file-notes",
346 name: "notes.txt",
347 mimeType: "text/plain",
348 sizeBytes: 5,
349 attachmentId: "attachment-notes",
350 environmentId: ENVIRONMENT_ID,
351 },
352 ],
353 droppedImageNames: [],
354 records: [environmentContextRecord(EnvironmentId.make("environment-build"), "Build box")],
355 });
356 const router = getRouter(
357 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
358 );
359 await router.load();
360 await using _app = await render(<AppRoot router={router} />, {
361 // AppRoot brings its own router.
362 router: false,
363 });
364 await expect.element(page.getByText("Answer 0 for thread-stash-late-question.")).toBeVisible();
365 await userEvent.click(page.getByRole("button", { name: /^Stashed prompts/ }));
366 await userEvent.click(page.getByRole("button", { name: /^Restore stashed prompt/ }));
367​
368 // The question opens while the restore still waits on the server's file check.
369 await vi.waitFor(() => expect(hasPendingAssetUrl()).toBe(true));
370 await emitThreadEvent(thread.id, { type: "turn-item.updated", payload: question });
371 await emitThreadEvent(thread.id, { type: "runtime-request.updated", payload: request });
372 await expect.element(page.getByText("Which file should change?")).toBeVisible();
373 await answerAssetUrls();
374​
375 await vi.waitFor(() =>
376 expect(document.body.textContent).toContain("Stashed machines can't go in an answer"),
377 );
378 expect(usePromptStashStore.getState().entries).toHaveLength(1);
379 usePromptStashStore.getState().takeEntry("stash-late-question");
380});
381​
382it("a new draft does not load its reserved thread before the server lists it", async () => {
383 using _environment = installFakeEnvironment([]);
384 using fetchSpy = vi.spyOn(globalThis, "fetch");
385 __setClientSettingsForTests({
386 ...DEFAULT_CLIENT_SETTINGS,
387 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
388 });
389 const draftId = DraftId.make("draft-27443");
390 const threadId = ThreadId.make("thread-27443");
391 useComposerDraftStore
392 .getState()
393 .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, { threadId });
394​
395 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
396 await router.load();
397 await using _app = await render(<AppRoot router={router} />, {
398 // AppRoot brings its own router.
399 router: false,
400 });
401 await expect.element(page.getByTestId("composer-editor")).toBeVisible();
402 // The shell snapshot has arrived once the sidebar lists the project, so the connection is up.
403 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
404​
405 const threadRequests = fetchSpy.mock.calls
406 .map(([input]) => String(input instanceof Request ? input.url : input))
407 .filter((url) => url.includes(`/api/orchestration/threads/${threadId}/`));
408 // A 404 here marks the thread deleted, and the view never loads it once the send creates it.
409 expect(threadRequests).toEqual([]);
410});
411​
412it("a failed image-only first send of a new thread keeps the new draft", async () => {
413 using _environment = installFakeEnvironment([]);
414 __setClientSettingsForTests({
415 ...DEFAULT_CLIENT_SETTINGS,
416 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
417 });
418 const draftId = DraftId.make("draft-image-only-interrupted");
419 useComposerDraftStore
420 .getState()
421 .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
422 threadId: ThreadId.make("thread-image-only-interrupted"),
423 });
424 // A refusal fails at once; an interrupted launch would wait for a reconnect and be resent.
425 using launch = holdRpc(
426 ORCHESTRATION_V2_WS_METHODS.launchThread,
427 Effect.fail(new LaunchRefused()),
428 );
429 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
430 await router.load();
431 await using _app = await render(<AppRoot router={router} />, {
432 // AppRoot brings its own router.
433 router: false,
434 });
435 using _uploads = acceptAttachmentUploads();
436 const editor = page.getByTestId("composer-editor");
437 await expect.element(editor).toBeVisible();
438 // The send needs the project, which arrives with the shell snapshot.
439 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
440​
441 await userEvent.click(editor);
442 const clipboardData = new DataTransfer();
443 clipboardData.items.add(new File([PNG], "shot.png", { type: "image/png" }));
444 editor
445 .element()
446 .dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
447 await expect.element(page.getByRole("img", { name: "shot.png" })).toBeVisible();
448 await userEvent.keyboard("{Enter}");
449 await vi.waitFor(() => expect(launch.calls).toHaveLength(1));
450 await userEvent.keyboard("next draft");
451 await expect.element(editor).toHaveTextContent("next draft");
452 launch.release();
453​
454 await expect.element(page.getByText("Message not sent")).toBeVisible();
455 await expect.element(editor).toHaveTextContent("next draft");
456 // With no text there is nothing to copy.
457 expect(page.getByText("Copy message", { exact: true }).query()).toBeNull();
458});
459​
460it.each(["new", "existing"] as const)(
461 "Enter while an image compresses shows a cancellable banner, cancels on edit or Esc, and still sends after leaving a %s thread",
462 async (kind) => {
463 const thread = threadWithHistory(`upload-wait-${kind}`, 1);
464 const other = threadWithHistory(`upload-wait-other-${kind}`, 1);
465 using _environment = installFakeEnvironment(kind === "existing" ? [thread, other] : [other], {
466 acceptCommands: true,
467 });
468 __setClientSettingsForTests({
469 ...DEFAULT_CLIENT_SETTINGS,
470 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
471 });
472 const draftId = DraftId.make(`draft-upload-wait-${kind}`);
473 if (kind === "new") {
474 useComposerDraftStore
475 .getState()
476 .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
477 threadId: thread.id,
478 });
479 }
480 using launch = holdRpc(ORCHESTRATION_V2_WS_METHODS.launchThread, Effect.interrupt);
481 const router = getRouter(
482 createMemoryHistory({
483 initialEntries: [kind === "new" ? `/draft/${draftId}` : `/${ENVIRONMENT_ID}/${thread.id}`],
484 }),
485 );
486 await router.load();
487 await using _app = await render(<AppRoot router={router} />, {
488 // AppRoot brings its own router.
489 router: false,
490 });
491 const compressed = Promise.withResolvers<void>();
492 compression.gate = compressed.promise;
493 using _compression = { [Symbol.dispose]: () => (compression.gate = null) };
494 using _uploads = acceptAttachmentUploads();
495 const editor = page.getByTestId("composer-editor");
496 await expect.element(editor).toBeVisible();
497 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
498​
499 await userEvent.click(editor);
500 const clipboardData = new DataTransfer();
501 clipboardData.items.add(new File([PNG], "shot.png", { type: "image/png" }));
502 editor
503 .element()
504 .dispatchEvent(
505 new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }),
506 );
507​
508 // Enter arms the send and shows the banner plus a disabled spinner button.
509 await userEvent.keyboard("check image{Enter}");
510 await expect.element(page.getByText("Sending once image is ready")).toBeVisible();
511 const waitingButton = page.getByRole("button", { name: "Sending when ready", exact: true });
512 await expect.element(waitingButton).toBeDisabled();
513 await expect.element(waitingButton).toHaveAttribute("aria-busy", "true");
514​
515 // Typing disarms the queued send and keeps the edit.
516 await userEvent.keyboard(" now");
517 await expect.element(page.getByText("Sending once image is ready")).not.toBeInTheDocument();
518 await expect.element(editor).toHaveTextContent("check image now");
519​
520 // Enter arms again; Esc cancels cleanly.
521 await userEvent.keyboard("{Enter}");
522 await expect.element(page.getByText("Sending once image is ready")).toBeVisible();
523 await userEvent.keyboard("{Escape}");
524 await expect.element(page.getByText("Sending once image is ready")).not.toBeInTheDocument();
525​
526 // Enter arms again; leaving the thread still sends once the image is ready.
527 await userEvent.keyboard("{Enter}");
528 await expect.element(page.getByText("Sending once image is ready")).toBeVisible();
529 await router.navigate({ to: `/${ENVIRONMENT_ID}/${other.id}` });
530 await expect.element(page.getByText(`Answer 0 for upload-wait-other-${kind}.`)).toBeVisible();
531​
532 compressed.resolve();
533 await vi.waitFor(() => {
534 if (kind === "new") {
535 expect(launch.calls).toHaveLength(1);
536 } else {
537 expect(dispatchedCommands()).toContainEqual(
538 expect.objectContaining({
539 type: "message.dispatch",
540 threadId: thread.id,
541 attachments: [expect.objectContaining({ type: "image", id: "upload-1" })],
542 }),
543 );
544 }
545 });
546 launch.release();
547 },
548);
549​
550it("opens the thread actions menu for an older settled thread the shell leaves out", async () => {
551 const thread = { ...threadWithHistory("older-settled", 1), olderSettled: true as const };
552 using _environment = installFakeEnvironment([thread]);
553 __setClientSettingsForTests({
554 ...DEFAULT_CLIENT_SETTINGS,
555 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
556 });
557​
558 const router = getRouter(
559 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
560 );
561 await router.load();
562 await using _app = await render(<AppRoot router={router} />, {
563 // AppRoot brings its own router.
564 router: false,
565 });
566 await expect.element(page.getByText("older-settled: question 0")).toBeVisible();
567​
568 await page.getByRole("button", { name: `Thread actions for ${thread.title}` }).click();
569 // Without a bound the poll runs to the test deadline and reports a bare timeout.
570 await expect
571 .element(page.getByRole("menuitem", { name: "Rename thread" }), { timeout: 5_000 })
572 .toBeVisible();
573});
574​
575it("retains each thread's diff selection when returning from another thread or Settings", async () => {
576 const a = threadWithHistory("diff-selection-a", 1);
577 const b = threadWithHistory("diff-selection-b", 1);
578 using _environment = installFakeEnvironment([a, b]);
579 __setClientSettingsForTests({
580 ...DEFAULT_CLIENT_SETTINGS,
581 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
582 });
583 const aRef = scopeThreadRef(ENVIRONMENT_ID, a.id);
584 const bRef = scopeThreadRef(ENVIRONMENT_ID, b.id);
585 useRightPanelStore.getState().open(aRef, "diff");
586 useRightPanelStore.getState().open(bRef, "diff");
587 useDiffPanelStore.getState().selectBranchBaseRef(bRef, "origin/release");
588 const router = getRouter(createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${a.id}`] }));
589 await router.load();
590 await using _app = await render(<AppRoot router={router} />, {
591 // AppRoot brings its own router.
592 router: false,
593 });
594 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
595 await act(() => useDiffPanelStore.getState().selectGitScope(aRef, "unstaged"));
596​
597 await act(() =>
598 router.navigate({
599 to: "/$environmentId/$threadId",
600 params: { environmentId: ENVIRONMENT_ID, threadId: b.id },
601 }),
602 );
603 await expect.element(page.getByText(`Answer 0 for ${b.id}.`)).toBeVisible();
604 expect(selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, bRef)).toEqual({
605 kind: "branch",
606 baseRef: "origin/release",
607 });
608 await act(() =>
609 router.navigate({
610 to: "/$environmentId/$threadId",
611 params: { environmentId: ENVIRONMENT_ID, threadId: a.id },
612 }),
613 );
614 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
615 expect(selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, aRef)).toEqual({
616 kind: "unstaged",
617 });
618​
619 await act(() => useDiffPanelStore.getState().selectTurn(aRef, a.runs[0]!.id));
620 await act(() => router.navigate({ to: "/settings/general" }));
621 await expect
622 .element(page.getByRole("heading", { name: "Time format", exact: true }))
623 .toBeVisible();
624 await act(() =>
625 router.navigate({
626 to: "/$environmentId/$threadId",
627 params: { environmentId: ENVIRONMENT_ID, threadId: a.id },
628 }),
629 );
630 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
631 expect(
632 selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, aRef),
633 ).toMatchObject({
634 kind: "turn",
635 turnId: a.runs[0]!.id,
636 });
637});
638​
639it("a stashed prompt ending in a file chip restores with the chip", async () => {
640 using _environment = installFakeEnvironment([]);
641 __setClientSettingsForTests({
642 ...DEFAULT_CLIENT_SETTINGS,
643 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
644 });
645 const draftId = DraftId.make("draft-28338");
646 const drafts = useComposerDraftStore.getState();
647 drafts.setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
648 threadId: ThreadId.make("thread-28338"),
649 });
650 drafts.setPrompt(draftId, "Check [package.json](package.json) ");
651 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
652 await router.load();
653 await using _app = await render(<AppRoot router={router} />, {
654 // AppRoot brings its own router.
655 router: false,
656 });
657 const chip = page.getByRole("button", { name: "Preview package.json" });
658 await expect.element(chip).toBeVisible();
659 // The stash shortcut is a no-op until the shell snapshot lists the project.
660 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
661​
662 const editor = page.getByTestId("composer-editor");
663 await userEvent.click(editor);
664 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
665 await expect.element(chip).not.toBeInTheDocument();
666 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
667​
668 await vi.waitFor(() => expect(editor.element().textContent).toContain("Check"));
669 expect(editor.element().textContent).not.toContain("[package.json](package.json)");
670 await expect.element(chip).toBeVisible();
671});
672​
673it("a rejected send leaves the timeline when a new draft was typed meanwhile", async () => {
674 const thread = threadWithHistory("rejected-send", 1);
675 using _environment = installFakeEnvironment([thread], {
676 acceptCommands: true,
677 holdCommand: (command) => command.type === "message.dispatch",
678 });
679 __setClientSettingsForTests({
680 ...DEFAULT_CLIENT_SETTINGS,
681 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
682 });
683 const router = getRouter(
684 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
685 );
686 await router.load();
687 await using _app = await render(<AppRoot router={router} />, {
688 // AppRoot brings its own router.
689 router: false,
690 });
691 await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible();
692​
693 const editor = page.getByTestId("composer-editor");
694 await userEvent.click(editor);
695 await userEvent.keyboard("Failed prompt{Enter}");
696 await vi.waitFor(() =>
697 expect(dispatchedCommands().map((command) => command.type)).toContain("message.dispatch"),
698 );
699 await expect.element(page.getByText("Failed prompt")).toBeVisible();
700 await userEvent.keyboard("Next draft");
701​
702 await rejectPendingCommand("Attachment 'sample.png' cannot be sent.");
703​
704 await expect.element(page.getByText("Attachment 'sample.png' cannot be sent.")).toBeVisible();
705 await expect.element(page.getByText("Failed prompt")).not.toBeInTheDocument();
706 expect(editor.element().textContent).toContain("Next draft");
707});
708​
709it("Enter on an empty prompt resumes an interrupted thread", async () => {
710 const history = threadWithHistory("interrupted", 1);
711 const interruptedRun = { ...history.runs[0]!, status: "interrupted" as const };
712 const thread = { ...history, runs: [interruptedRun] };
713 using _environment = installFakeEnvironment([thread], { acceptCommands: true });
714 __setClientSettingsForTests({
715 ...DEFAULT_CLIENT_SETTINGS,
716 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
717 });
718 const router = getRouter(
719 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
720 );
721 await router.load();
722 await using _app = await render(<AppRoot router={router} />, {
723 // AppRoot brings its own router.
724 router: false,
725 });
726 await expect.element(page.getByRole("button", { name: "Resume thread" })).toBeVisible();
727​
728 await userEvent.click(page.getByTestId("composer-editor"));
729 await userEvent.keyboard("{Enter}");
730​
731 await vi.waitFor(() =>
732 expect(dispatchedCommands()).toContainEqual(
733 expect.objectContaining({ manualContinuationOfRunId: interruptedRun.id }),
734 ),
735 );
736});
737​
738it("opening a thread or returning to the window on a touch tablet does not focus the composer", async () => {
739 const realMatchMedia = window.matchMedia.bind(window);
740 using _touch = vi
741 .spyOn(window, "matchMedia")
742 .mockImplementation((query) => realMatchMedia(query === "(pointer: coarse)" ? "all" : query));
743 const first = threadWithHistory("thread-29469-a", 1);
744 const second = threadWithHistory("thread-29469-b", 1);
745 using _environment = installFakeEnvironment([first, second]);
746 // iPad Pro 11 in landscape: the desktop layout, above max-sm.
747 await page.viewport(1194, 834);
748 __setClientSettingsForTests({
749 ...DEFAULT_CLIENT_SETTINGS,
750 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
751 });
752 const router = getRouter(
753 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${first.id}`] }),
754 );
755 await router.load();
756 await using _app = await render(<AppRoot router={router} />, {
757 // AppRoot brings its own router.
758 router: false,
759 });
760 const composer = page.getByTestId("composer-editor");
761 await expect.element(page.getByText(`Answer 0 for ${first.id}.`)).toBeVisible();
762​
763 // Fake frames hold the next thread entry's focus frame until the test advances it.
764 using _timers = fakeTimers();
765 await act(() =>
766 router.navigate({
767 to: "/$environmentId/$threadId",
768 params: { environmentId: ENVIRONMENT_ID, threadId: second.id },
769 }),
770 );
771 await expect.element(page.getByText(`Answer 0 for ${second.id}.`)).toBeVisible();
772 vi.advanceTimersToNextFrame();
773 // Focusing the editor raises the on-screen keyboard, which shrinks the page on iPadOS.
774 expect(document.activeElement).not.toBe(composer.element());
775​
776 // ChatView waits two frames after window focus before refocusing the composer.
777 window.dispatchEvent(new FocusEvent("focus"));
778 vi.advanceTimersToNextFrame();
779 vi.advanceTimersToNextFrame();
780 expect(document.activeElement).not.toBe(composer.element());
781});
782​
783it("a mounted thread view lets go of the thread structures it has replaced", async () => {
784 // Items are shared with the fixture, so a reopen's snapshot also carries the earlier updates.
785 const history = threadWithHistory("updated", 3);
786 const items = [...history.items];
787 const updated = { ...history, items };
788 const other = threadWithHistory("other", 3);
789 using _environment = installFakeEnvironment([updated, other]);
790 __setClientSettingsForTests({
791 ...DEFAULT_CLIENT_SETTINGS,
792 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
793 });
794 const router = getRouter(createMemoryHistory({ initialEntries: ["/"] }));
795 await router.load();
796 await using _app = await render(<AppRoot router={router} />, { router: false });
797 const open = async (threadId: ThreadId, text: string) => {
798 await act(() =>
799 router.navigate({
800 to: "/$environmentId/$threadId",
801 params: { environmentId: ENVIRONMENT_ID, threadId },
802 }),
803 );
804 await expect.element(page.getByText(text).first()).toBeVisible();
805 };
806 const structureAtom = environmentThreadDetails.quietThreadAtom(
807 scopeThreadRef(ENVIRONMENT_ID, updated.id),
808 );
809​
810 // Each round, a new answer arrives while the thread is shown, then the user switches away.
811 const shown: Array<WeakRef<object>> = [];
812 await open(other.id, "Answer 2 for other.");
813 for (let round = 0; round < 6; round++) {
814 await open(updated.id, round === 0 ? "Answer 2 for updated." : `Update ${round - 1}.`);
815 const update = assistantItem(
816 updated.id,
817 RunId.make("updated-run-2"),
818 `updated-update-${round}`,
819 6 + round,
820 `Update ${round}.`,
821 );
822 items.push(update);
823 await act(() => emitThreadEvent(updated.id, { type: "turn-item.updated", payload: update }));
824 await expect.element(page.getByText(`Update ${round}.`)).toBeVisible();
825 shown.push(new WeakRef(appAtomRegistry.get(structureAtom)!.projection));
826 await open(other.id, "Answer 2 for other.");
827 }
828 await cdp().send("HeapProfiler.collectGarbage");
829​
830 // The thread keeps its latest structure, and the timeline may remember the one before it.
831 const kept = shown.slice(0, -2).flatMap((structure, round) => (structure.deref() ? [round] : []));
832 expect(kept).toEqual([]);
833});
834​
835it("a shortcut conditioned on rightPanelOpen sees the thread's open right panel", async () => {
836 await page.viewport(1280, 800);
837 const thread = threadWithHistory("thread-panel-shortcut", 1);
838 using _environment = installFakeEnvironment([thread], {
839 keybindings: mergeWithDefaultKeybindings(
840 compileResolvedKeybindingsConfig([
841 { key: "ctrl+t", command: "rightPanel.new", when: "rightPanelOpen && !terminalFocus" },
842 { key: "ctrl+t", command: "rightPanel.toggle", when: "!rightPanelOpen" },
843 ]),
844 ),
845 });
846 __setClientSettingsForTests({
847 ...DEFAULT_CLIENT_SETTINGS,
848 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
849 });
850 const router = getRouter(
851 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
852 );
853 await router.load();
854 await using _app = await render(<AppRoot router={router} />, {
855 // AppRoot brings its own router.
856 router: false,
857 });
858 const composer = page.getByTestId("composer-editor");
859 const toggle = page.getByRole("button", { name: "Toggle right panel", exact: true });
860 await expect.element(toggle).toHaveAttribute("aria-pressed", "false");
861 await toggle.click();
862 await page.getByRole("button", { name: /^Files/ }).click();
863 await composer.click();
864 await userEvent.keyboard("{Control>}t{/Control}");
865 await expect.element(page.getByRole("menuitem", { name: /Files/ })).toBeVisible();
866 await expect.element(toggle).toHaveAttribute("aria-pressed", "true");
867});
868​
869it("selecting a side-chat tab focuses that side chat's composer", async () => {
870 const parent = threadWithHistory("focus-parent", 1);
871 // The shell loaded by the file's first test stays; a family read serves side chats added later.
872 const sideChat = (name: string) => ({
873 ...threadWithHistory(name, 1),
874 sideChatOf: parent.id,
875 olderSettled: true as const,
876 });
877 const side = sideChat("focus-side");
878 const otherSide = sideChat("focus-other-side");
879 await page.viewport(1400, 900);
880 using _environment = installFakeEnvironment([parent, side, otherSide]);
881 __setClientSettingsForTests({
882 ...DEFAULT_CLIENT_SETTINGS,
883 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
884 });
885 const parentRef = scopeThreadRef(ENVIRONMENT_ID, parent.id);
886 useRightPanelStore.getState().openThread(parentRef, otherSide.id);
887 useRightPanelStore.getState().openThread(parentRef, side.id);
888 const router = getRouter(
889 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${parent.id}`] }),
890 );
891 await router.load();
892 await using screen = await render(<AppRoot router={router} />, {
893 // AppRoot brings its own router.
894 router: false,
895 });
896 using _focus = { [Symbol.dispose]: startWorkspaceFocus(router) };
897 const mainEditor = screen.getByRole("textbox", { name: `Message ${parent.title}`, exact: true });
898 const sideEditor = screen.getByRole("textbox", { name: `Message ${side.title}`, exact: true });
899 await expect.element(sideEditor).toBeVisible();
900 await userEvent.click(mainEditor);
901 await userEvent.keyboard("main draft");
902​
903 await userEvent.click(screen.getByRole("button", { name: otherSide.title, exact: true }));
904 const otherEditor = screen.getByRole("textbox", {
905 name: `Message ${otherSide.title}`,
906 exact: true,
907 });
908 await expect.element(otherEditor).toHaveFocus();
909 await userEvent.keyboard("other draft");
910 await expect.element(otherEditor).toHaveTextContent("other draft");
911​
912 await userEvent.click(screen.getByRole("button", { name: side.title, exact: true }));
913 await expect.element(sideEditor).toHaveFocus();
914 await expect.element(mainEditor).toHaveTextContent("main draft");
915});
916​
917it("a subagent tab shows its read-only bar under no header of its own", async () => {
918 const parent = threadWithHistory("subagent-parent", 1);
919 const subagent = {
920 ...threadWithHistory("subagent-child", 1),
921 providerSubagentOf: parent.id,
922 olderSettled: true as const,
923 };
924 await page.viewport(1400, 900);
925 using _environment = installFakeEnvironment([parent, subagent]);
926 __setClientSettingsForTests({
927 ...DEFAULT_CLIENT_SETTINGS,
928 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
929 });
930 const parentRef = scopeThreadRef(ENVIRONMENT_ID, parent.id);
931 useRightPanelStore.getState().openThread(parentRef, subagent.id);
932 const router = getRouter(
933 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${parent.id}`] }),
934 );
935 await router.load();
936 await using screen = await render(<AppRoot router={router} />, {
937 // AppRoot brings its own router.
938 router: false,
939 });
940 const pane = screen.getByTestId("side-thread-pane");
941 // No header of its own: the tab names it, and only a side chat has actions to put in one.
942 await expect.element(pane.getByRole("heading", { name: subagent.title })).not.toBeInTheDocument();
943 await expect.element(pane.getByText("Runs on its own")).toBeVisible();
944 await expect.element(pane.getByRole("button", { name: "Add to chat" })).not.toBeInTheDocument();
945 await expect
946 .element(screen.getByRole("textbox", { name: `Message ${subagent.title}`, exact: true }))
947 .not.toBeInTheDocument();
948 await expect
949 .element(screen.getByRole("textbox", { name: `Message ${parent.title}`, exact: true }))
950 .toBeVisible();
951});
952​
953it("/side sends the draft's attachments and context, and keeps them when it does not start", async () => {
954 await page.viewport(1400, 900);
955 const thread = threadWithHistory("side-attachments", 1);
956 let holdFork = false;
957 using _environment = installFakeEnvironment([thread], {
958 acceptCommands: true,
959 holdCommand: (command) => holdFork && command.type === "thread.fork",
960 });
961 __setClientSettingsForTests({
962 ...DEFAULT_CLIENT_SETTINGS,
963 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
964 });
965 const router = getRouter(
966 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
967 );
968 await router.load();
969 await using _app = await render(<AppRoot router={router} />, {
970 // AppRoot brings its own router.
971 router: false,
972 });
973 using _uploads = acceptAttachmentUploads();
974 await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible();
975​
976 const editor = page.getByRole("textbox", { name: `Message ${thread.title}`, exact: true });
977 const image = page.getByRole("img", { name: "shot.png" });
978 const sendImageToSideChat = async () => {
979 await userEvent.click(editor);
980 const clipboardData = new DataTransfer();
981 clipboardData.items.add(new File([PNG], "shot.png", { type: "image/png" }));
982 editor
983 .element()
984 .dispatchEvent(
985 new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }),
986 );
987 await expect.element(image).toBeVisible();
988 await insertText("/side what is this?");
989 await userEvent.keyboard("{Enter}");
990 await expect.element(image).not.toBeInTheDocument();
991 };
992 // The tab opens once the start finished; until then `/side` refuses another side chat.
993 const sideChatTabs = page.getByRole("button", { name: "Side chat", exact: true });
994 const sentMessage = async (fields: Record<string, unknown>, openTabs: number) => {
995 await vi.waitFor(() =>
996 expect(dispatchedCommands()).toContainEqual(
997 expect.objectContaining({ type: "message.dispatch", ...fields }),
998 ),
999 );
1000 await expect.element(sideChatTabs).toHaveLength(openTabs);
1001 };
1002​
1003 await sendImageToSideChat();
1004 await sentMessage(
1006 text: "what is this?",
1007 attachments: [expect.objectContaining({ type: "image", id: "upload-1" })],
1008 context: {
1009 version: 1,
1010 records: [expect.objectContaining({ kind: "image", attachmentId: "upload-1" })],
1011 },
1012 },
1013 1,
1014 );
1015​
1016 // A reply alone is enough to send.
1017 await page.getByRole("button", { name: "Reply to this response" }).first().click();
1018 await userEvent.click(editor);
1019 await insertText("/side ");
1020 await userEvent.keyboard("{Enter}");
1021 await sentMessage(
1023 context: expect.objectContaining({
1024 records: [expect.objectContaining({ kind: "response" })],
1025 }),
1026 },
1027 2,
1028 );
1029​
1030 // A failed start puts the message back after the draft typed meanwhile.
1031 holdFork = true;
1032 await sendImageToSideChat();
1033 await insertText("next draft");
1034 await vi.waitFor(() =>
1035 expect(dispatchedCommands().filter((command) => command.type === "thread.fork")).toHaveLength(
1036 3,
1037 ),
1038 );
1039 await rejectPendingCommand("Side chats are paused.");
1040 await expect.element(image).toBeVisible();
1041 await vi.waitFor(() =>
1042 expect((editor.element() as HTMLElement).innerText.split("\n").filter(Boolean)).toEqual([
1043 "next draft",
1044 "/side what is this?",
1045 ]),
1046 );
1047});