Open History to see the last commit
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 };
87}
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]() };
106}
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("a file picked after the phone composer collapses still attaches", async () => {
551 const thread = threadWithHistory("thread-40993", 1);
552 using _environment = installFakeEnvironment([thread]);
553 await page.viewport(390, 844);
554 __setClientSettingsForTests({
555 ...DEFAULT_CLIENT_SETTINGS,
556 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
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 using _uploads = acceptAttachmentUploads();
567 const editor = page.getByTestId("composer-editor");
568 await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible();
569 await userEvent.click(editor);
570 await expect.element(page.getByRole("button", { name: "Attach files" })).toBeVisible();
571 const input = document.querySelector<HTMLInputElement>(
572 'form[data-chat-composer-form] input[type="file"]',
573 );
574 expect(input).not.toBeNull();
575
576 // Opening the native picker blurs the editor, which collapses the phone composer.
577 (editor.element() as HTMLElement).blur();
578 await expect.element(page.getByRole("button", { name: "Attach files" })).not.toBeInTheDocument();
579 const files = new DataTransfer();
580 files.items.add(new File([PNG], "picked.png", { type: "image/png" }));
581 input!.files = files.files;
582 input!.dispatchEvent(new Event("change", { bubbles: true }));
583
584 await expect.element(page.getByRole("img", { name: "picked.png" })).toBeVisible();
585});
586
587it("opens the thread actions menu for an older settled thread the shell leaves out", async () => {
588 const thread = { ...threadWithHistory("older-settled", 1), olderSettled: true as const };
589 using _environment = installFakeEnvironment([thread]);
590 __setClientSettingsForTests({
591 ...DEFAULT_CLIENT_SETTINGS,
592 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
593 });
594
595 const router = getRouter(
596 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
597 );
598 await router.load();
599 await using _app = await render(<AppRoot router={router} />, {
600 // AppRoot brings its own router.
601 router: false,
602 });
603 await expect.element(page.getByText("older-settled: question 0")).toBeVisible();
604
605 await page.getByRole("button", { name: `Thread actions for ${thread.title}` }).click();
606 // Without a bound the poll runs to the test deadline and reports a bare timeout.
607 await expect
608 .element(page.getByRole("menuitem", { name: "Rename thread" }), { timeout: 5_000 })
609 .toBeVisible();
610});
611
612it("retains each thread's diff selection when returning from another thread or Settings", async () => {
613 const a = threadWithHistory("diff-selection-a", 1);
614 const b = threadWithHistory("diff-selection-b", 1);
615 using _environment = installFakeEnvironment([a, b]);
616 __setClientSettingsForTests({
617 ...DEFAULT_CLIENT_SETTINGS,
618 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
619 });
620 const aRef = scopeThreadRef(ENVIRONMENT_ID, a.id);
621 const bRef = scopeThreadRef(ENVIRONMENT_ID, b.id);
622 useRightPanelStore.getState().open(aRef, "diff");
623 useRightPanelStore.getState().open(bRef, "diff");
624 useDiffPanelStore.getState().selectBranchBaseRef(bRef, "origin/release");
625 const router = getRouter(createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${a.id}`] }));
626 await router.load();
627 await using _app = await render(<AppRoot router={router} />, {
628 // AppRoot brings its own router.
629 router: false,
630 });
631 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
632 await act(() => useDiffPanelStore.getState().selectGitScope(aRef, "unstaged"));
633
634 await act(() =>
635 router.navigate({
636 to: "/$environmentId/$threadId",
637 params: { environmentId: ENVIRONMENT_ID, threadId: b.id },
638 }),
639 );
640 await expect.element(page.getByText(`Answer 0 for ${b.id}.`)).toBeVisible();
641 expect(selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, bRef)).toEqual({
642 kind: "branch",
643 baseRef: "origin/release",
644 });
645 await act(() =>
646 router.navigate({
647 to: "/$environmentId/$threadId",
648 params: { environmentId: ENVIRONMENT_ID, threadId: a.id },
649 }),
650 );
651 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
652 expect(selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, aRef)).toEqual({
653 kind: "unstaged",
654 });
655
656 await act(() => useDiffPanelStore.getState().selectTurn(aRef, a.runs[0]!.id));
657 await act(() => router.navigate({ to: "/settings/general" }));
658 await expect
659 .element(page.getByRole("heading", { name: "Time format", exact: true }))
660 .toBeVisible();
661 await act(() =>
662 router.navigate({
663 to: "/$environmentId/$threadId",
664 params: { environmentId: ENVIRONMENT_ID, threadId: a.id },
665 }),
666 );
667 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
668 expect(
669 selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, aRef),
670 ).toMatchObject({
671 kind: "turn",
672 turnId: a.runs[0]!.id,
673 });
674});
675
676it("a stashed prompt ending in a file chip restores with the chip", async () => {
677 using _environment = installFakeEnvironment([]);
678 __setClientSettingsForTests({
679 ...DEFAULT_CLIENT_SETTINGS,
680 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
681 });
682 const draftId = DraftId.make("draft-28338");
683 const drafts = useComposerDraftStore.getState();
684 drafts.setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
685 threadId: ThreadId.make("thread-28338"),
686 });
687 drafts.setPrompt(draftId, "Check [package.json](package.json) ");
688 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
689 await router.load();
690 await using _app = await render(<AppRoot router={router} />, {
691 // AppRoot brings its own router.
692 router: false,
693 });
694 const chip = page.getByRole("button", { name: "Preview package.json" });
695 await expect.element(chip).toBeVisible();
696 // The stash shortcut is a no-op until the shell snapshot lists the project.
697 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
698
699 const editor = page.getByTestId("composer-editor");
700 await userEvent.click(editor);
701 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
702 await expect.element(chip).not.toBeInTheDocument();
703 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
704
705 await vi.waitFor(() => expect(editor.element().textContent).toContain("Check"));
706 expect(editor.element().textContent).not.toContain("[package.json](package.json)");
707 await expect.element(chip).toBeVisible();
708});
709
710it("a rejected send leaves the timeline when a new draft was typed meanwhile", async () => {
711 const thread = threadWithHistory("rejected-send", 1);
712 using _environment = installFakeEnvironment([thread], {
713 acceptCommands: true,
714 holdCommand: (command) => command.type === "message.dispatch",
715 });
716 __setClientSettingsForTests({
717 ...DEFAULT_CLIENT_SETTINGS,
718 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
719 });
720 const router = getRouter(
721 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
722 );
723 await router.load();
724 await using _app = await render(<AppRoot router={router} />, {
725 // AppRoot brings its own router.
726 router: false,
727 });
728 await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible();
729
730 const editor = page.getByTestId("composer-editor");
731 await userEvent.click(editor);
732 await userEvent.keyboard("Failed prompt{Enter}");
733 await vi.waitFor(() =>
734 expect(dispatchedCommands().map((command) => command.type)).toContain("message.dispatch"),
735 );
736 await expect.element(page.getByText("Failed prompt")).toBeVisible();
737 await userEvent.keyboard("Next draft");
738
739 await rejectPendingCommand("Attachment 'sample.png' cannot be sent.");
740
741 await expect.element(page.getByText("Attachment 'sample.png' cannot be sent.")).toBeVisible();
742 await expect.element(page.getByText("Failed prompt")).not.toBeInTheDocument();
743 expect(editor.element().textContent).toContain("Next draft");
744});
745
746it("Enter on an empty prompt resumes an interrupted thread", async () => {
747 const history = threadWithHistory("interrupted", 1);
748 const interruptedRun = { ...history.runs[0]!, status: "interrupted" as const };
749 const thread = { ...history, runs: [interruptedRun] };
750 using _environment = installFakeEnvironment([thread], { acceptCommands: true });
751 __setClientSettingsForTests({
752 ...DEFAULT_CLIENT_SETTINGS,
753 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
754 });
755 const router = getRouter(
756 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
757 );
758 await router.load();
759 await using _app = await render(<AppRoot router={router} />, {
760 // AppRoot brings its own router.
761 router: false,
762 });
763 await expect.element(page.getByRole("button", { name: "Resume thread" })).toBeVisible();
764
765 await userEvent.click(page.getByTestId("composer-editor"));
766 await userEvent.keyboard("{Enter}");
767
768 await vi.waitFor(() =>
769 expect(dispatchedCommands()).toContainEqual(
770 expect.objectContaining({ manualContinuationOfRunId: interruptedRun.id }),
771 ),
772 );
773});
774
775it("opening a thread or returning to the window on a touch tablet does not focus the composer", async () => {
776 const realMatchMedia = window.matchMedia.bind(window);
777 using _touch = vi
778 .spyOn(window, "matchMedia")
779 .mockImplementation((query) => realMatchMedia(query === "(pointer: coarse)" ? "all" : query));
780 const first = threadWithHistory("thread-29469-a", 1);
781 const second = threadWithHistory("thread-29469-b", 1);
782 using _environment = installFakeEnvironment([first, second]);
783 // iPad Pro 11 in landscape: the desktop layout, above max-sm.
784 await page.viewport(1194, 834);
785 __setClientSettingsForTests({
786 ...DEFAULT_CLIENT_SETTINGS,
787 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
788 });
789 const router = getRouter(
790 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${first.id}`] }),
791 );
792 await router.load();
793 await using _app = await render(<AppRoot router={router} />, {
794 // AppRoot brings its own router.
795 router: false,
796 });
797 const composer = page.getByTestId("composer-editor");
798 await expect.element(page.getByText(`Answer 0 for ${first.id}.`)).toBeVisible();
799
800 // Fake frames hold the next thread entry's focus frame until the test advances it.
801 using _timers = fakeTimers();
802 await act(() =>
803 router.navigate({
804 to: "/$environmentId/$threadId",
805 params: { environmentId: ENVIRONMENT_ID, threadId: second.id },
806 }),
807 );
808 await expect.element(page.getByText(`Answer 0 for ${second.id}.`)).toBeVisible();
809 vi.advanceTimersToNextFrame();
810 // Focusing the editor raises the on-screen keyboard, which shrinks the page on iPadOS.
811 expect(document.activeElement).not.toBe(composer.element());
812
813 // ChatView waits two frames after window focus before refocusing the composer.
814 window.dispatchEvent(new FocusEvent("focus"));
815 vi.advanceTimersToNextFrame();
816 vi.advanceTimersToNextFrame();
817 expect(document.activeElement).not.toBe(composer.element());
818});
819
820it("a mounted thread view lets go of the thread structures it has replaced", async () => {
821 // Items are shared with the fixture, so a reopen's snapshot also carries the earlier updates.
822 const history = threadWithHistory("updated", 3);
823 const items = [...history.items];
824 const updated = { ...history, items };
825 const other = threadWithHistory("other", 3);
826 using _environment = installFakeEnvironment([updated, other]);
827 __setClientSettingsForTests({
828 ...DEFAULT_CLIENT_SETTINGS,
829 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
830 });
831 const router = getRouter(createMemoryHistory({ initialEntries: ["/"] }));
832 await router.load();
833 await using _app = await render(<AppRoot router={router} />, { router: false });
834 const open = async (threadId: ThreadId, text: string) => {
835 await act(() =>
836 router.navigate({
837 to: "/$environmentId/$threadId",
838 params: { environmentId: ENVIRONMENT_ID, threadId },
839 }),
840 );
841 await expect.element(page.getByText(text).first()).toBeVisible();
842 };
843 const structureAtom = environmentThreadDetails.quietThreadAtom(
844 scopeThreadRef(ENVIRONMENT_ID, updated.id),
845 );
846
847 // Each round, a new answer arrives while the thread is shown, then the user switches away.
848 const shown: Array<WeakRef<object>> = [];
849 await open(other.id, "Answer 2 for other.");
850 for (let round = 0; round < 6; round++) {
851 await open(updated.id, round === 0 ? "Answer 2 for updated." : `Update ${round - 1}.`);
852 const update = assistantItem(
853 updated.id,
854 RunId.make("updated-run-2"),
855 `updated-update-${round}`,
856 6 + round,
857 `Update ${round}.`,
858 );
859 items.push(update);
860 await act(() => emitThreadEvent(updated.id, { type: "turn-item.updated", payload: update }));
861 await expect.element(page.getByText(`Update ${round}.`)).toBeVisible();
862 shown.push(new WeakRef(appAtomRegistry.get(structureAtom)!.projection));
863 await open(other.id, "Answer 2 for other.");
864 }
865 await cdp().send("HeapProfiler.collectGarbage");
866
867 // The thread keeps its latest structure, and the timeline may remember the one before it.
868 const kept = shown.slice(0, -2).flatMap((structure, round) => (structure.deref() ? [round] : []));
869 expect(kept).toEqual([]);
870});
871
872it("a shortcut conditioned on rightPanelOpen sees the thread's open right panel", async () => {
873 await page.viewport(1280, 800);
874 const thread = threadWithHistory("thread-panel-shortcut", 1);
875 using _environment = installFakeEnvironment([thread], {
876 keybindings: mergeWithDefaultKeybindings(
877 compileResolvedKeybindingsConfig([
878 { key: "ctrl+t", command: "rightPanel.new", when: "rightPanelOpen && !terminalFocus" },
879 { key: "ctrl+t", command: "rightPanel.toggle", when: "!rightPanelOpen" },
880 ]),
881 ),
882 });
883 __setClientSettingsForTests({
884 ...DEFAULT_CLIENT_SETTINGS,
885 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
886 });
887 const router = getRouter(
888 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
889 );
890 await router.load();
891 await using _app = await render(<AppRoot router={router} />, {
892 // AppRoot brings its own router.
893 router: false,
894 });
895 const composer = page.getByTestId("composer-editor");
896 const toggle = page.getByRole("button", { name: "Toggle right panel", exact: true });
897 await expect.element(toggle).toHaveAttribute("aria-pressed", "false");
898 await toggle.click();
899 await page.getByRole("button", { name: /^Files/ }).click();
900 await composer.click();
901 await userEvent.keyboard("{Control>}t{/Control}");
902 await expect.element(page.getByRole("menuitem", { name: /Files/ })).toBeVisible();
903 await expect.element(toggle).toHaveAttribute("aria-pressed", "true");
904});
905
906it("selecting a side-chat tab focuses that side chat's composer", async () => {
907 const parent = threadWithHistory("focus-parent", 1);
908 // The shell loaded by the file's first test stays; a family read serves side chats added later.
909 const sideChat = (name: string) => ({
910 ...threadWithHistory(name, 1),
911 sideChatOf: parent.id,
912 olderSettled: true as const,
913 });
914 const side = sideChat("focus-side");
915 const otherSide = sideChat("focus-other-side");
916 await page.viewport(1400, 900);
917 using _environment = installFakeEnvironment([parent, side, otherSide]);
918 __setClientSettingsForTests({
919 ...DEFAULT_CLIENT_SETTINGS,
920 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
921 });
922 const parentRef = scopeThreadRef(ENVIRONMENT_ID, parent.id);
923 useRightPanelStore.getState().openThread(parentRef, otherSide.id);
924 useRightPanelStore.getState().openThread(parentRef, side.id);
925 const router = getRouter(
926 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${parent.id}`] }),
927 );
928 await router.load();
929 await using screen = await render(<AppRoot router={router} />, {
930 // AppRoot brings its own router.
931 router: false,
932 });
933 using _focus = { [Symbol.dispose]: startWorkspaceFocus(router) };
934 const mainEditor = screen.getByRole("textbox", { name: `Message ${parent.title}`, exact: true });
935 const sideEditor = screen.getByRole("textbox", { name: `Message ${side.title}`, exact: true });
936 await expect.element(sideEditor).toBeVisible();
937 await userEvent.click(mainEditor);
938 await userEvent.keyboard("main draft");
939
940 await userEvent.click(screen.getByRole("button", { name: otherSide.title, exact: true }));
941 const otherEditor = screen.getByRole("textbox", {
942 name: `Message ${otherSide.title}`,
943 exact: true,
944 });
945 await expect.element(otherEditor).toHaveFocus();
946 await userEvent.keyboard("other draft");
947 await expect.element(otherEditor).toHaveTextContent("other draft");
948
949 await userEvent.click(screen.getByRole("button", { name: side.title, exact: true }));
950 await expect.element(sideEditor).toHaveFocus();
951 await expect.element(mainEditor).toHaveTextContent("main draft");
952});
953
954it("a subagent tab shows its read-only bar under no header of its own", async () => {
955 const parent = threadWithHistory("subagent-parent", 1);
956 const subagent = {
957 ...threadWithHistory("subagent-child", 1),
958 providerSubagentOf: parent.id,
959 olderSettled: true as const,
960 };
961 await page.viewport(1400, 900);
962 using _environment = installFakeEnvironment([parent, subagent]);
963 __setClientSettingsForTests({
964 ...DEFAULT_CLIENT_SETTINGS,
965 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
966 });
967 const parentRef = scopeThreadRef(ENVIRONMENT_ID, parent.id);
968 useRightPanelStore.getState().openThread(parentRef, subagent.id);
969 const router = getRouter(
970 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${parent.id}`] }),
971 );
972 await router.load();
973 await using screen = await render(<AppRoot router={router} />, {
974 // AppRoot brings its own router.
975 router: false,
976 });
977 const pane = screen.getByTestId("side-thread-pane");
978 // No header of its own: the tab names it, and only a side chat has actions to put in one.
979 await expect.element(pane.getByRole("heading", { name: subagent.title })).not.toBeInTheDocument();
980 await expect.element(pane.getByText("Runs on its own")).toBeVisible();
981 await expect.element(pane.getByRole("button", { name: "Add to chat" })).not.toBeInTheDocument();
982 await expect
983 .element(screen.getByRole("textbox", { name: `Message ${subagent.title}`, exact: true }))
984 .not.toBeInTheDocument();
985 await expect
986 .element(screen.getByRole("textbox", { name: `Message ${parent.title}`, exact: true }))
987 .toBeVisible();
988});
989
990it("/side sends the draft's attachments and context, and keeps them when it does not start", async () => {
991 await page.viewport(1400, 900);
992 const thread = threadWithHistory("side-attachments", 1);
993 let holdFork = false;
994 using _environment = installFakeEnvironment([thread], {
995 acceptCommands: true,
996 holdCommand: (command) => holdFork && command.type === "thread.fork",
997 });
998 __setClientSettingsForTests({
999 ...DEFAULT_CLIENT_SETTINGS,
1000 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
1001 });
1002 const router = getRouter(
1003 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
1004 );
1005 await router.load();
1006 await using _app = await render(<AppRoot router={router} />, {
1007 // AppRoot brings its own router.
1008 router: false,
1009 });
1010 using _uploads = acceptAttachmentUploads();
1011 await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible();
1012
1013 const editor = page.getByRole("textbox", { name: `Message ${thread.title}`, exact: true });
1014 const image = page.getByRole("img", { name: "shot.png" });
1015 const sendImageToSideChat = async () => {
1016 await userEvent.click(editor);
1017 const clipboardData = new DataTransfer();
1018 clipboardData.items.add(new File([PNG], "shot.png", { type: "image/png" }));
1019 editor
1020 .element()
1021 .dispatchEvent(
1022 new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }),
1023 );
1024 await expect.element(image).toBeVisible();
1025 await insertText("/side what is this?");
1026 await userEvent.keyboard("{Enter}");
1027 await expect.element(image).not.toBeInTheDocument();
1028 };
1029 // The tab opens once the start finished; until then `/side` refuses another side chat.
1030 const sideChatTabs = page.getByRole("button", { name: "Side chat", exact: true });
1031 const sentMessage = async (fields: Record<string, unknown>, openTabs: number) => {
1032 await vi.waitFor(() =>
1033 expect(dispatchedCommands()).toContainEqual(
1034 expect.objectContaining({ type: "message.dispatch", ...fields }),
1035 ),
1036 );
1037 await expect.element(sideChatTabs).toHaveLength(openTabs);
1038 };
1039
1040 await sendImageToSideChat();
1041 await sentMessage(
1042 {
1043 text: "what is this?",
1044 attachments: [expect.objectContaining({ type: "image", id: "upload-1" })],
1045 context: {
1046 version: 1,
1047 records: [expect.objectContaining({ kind: "image", attachmentId: "upload-1" })],
1048 },
1049 },
1050 1,
1051 );
1052
1053 // A reply alone is enough to send.
1054 await page.getByRole("button", { name: "Reply to this response" }).first().click();
1055 await userEvent.click(editor);
1056 await insertText("/side ");
1057 await userEvent.keyboard("{Enter}");
1058 await sentMessage(
1059 {
1060 context: expect.objectContaining({
1061 records: [expect.objectContaining({ kind: "response" })],
1062 }),
1063 },
1064 2,
1065 );
1066
1067 // A failed start puts the message back after the draft typed meanwhile.
1068 holdFork = true;
1069 await sendImageToSideChat();
1070 await insertText("next draft");
1071 await vi.waitFor(() =>
1072 expect(dispatchedCommands().filter((command) => command.type === "thread.fork")).toHaveLength(
1073 3,
1074 ),
1075 );
1076 await rejectPendingCommand("Side chats are paused.");
1077 await expect.element(image).toBeVisible();
1078 await vi.waitFor(() =>
1079 expect((editor.element() as HTMLElement).innerText.split("\n").filter(Boolean)).toEqual([
1080 "next draft",
1081 "/side what is this?",
1082 ]),
1083 );
1084});