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 Effect from "effect/Effect";
21import { expect, it, vi } from "vite-plus/test";
22import { cdp, page, userEvent } from "vite-plus/test/browser";
23
24import { AppRoot } from "~/AppRoot";
25// The route loads ChatView lazily, and its first transform (React Compiler over ~4k lines)
26// takes 6-11s; importing it here keeps that out of the test's timeout.
27import "~/components/ChatView";
28import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
29import { selectThreadDiffPanelSelection, useDiffPanelStore } from "~/diffPanelStore";
30import { __setClientSettingsForTests } from "~/hooks/useSettings";
31import stylesheet from "~/index.css?inline";
32import { environmentContextRecord } from "~/lib/composerContextRecords";
33import { startWorkspaceFocus } from "~/lib/workspaceFocus";
34import { usePromptStashStore } from "~/promptStashStore";
35import { useRightPanelStore } from "~/rightPanelStore";
36import { getRouter } from "~/router";
37import { appAtomRegistry } from "~/rpc/atomRegistry";
38import { environmentThreadDetails } from "~/state/threads";
39import {
40 ENVIRONMENT_ID,
41 PROJECT_ID,
42 answerAssetUrls,
43 answerRpc,
44 assistantItem,
45 dispatchedCommands,
46 emitThreadEvent,
47 hasPendingAssetUrl,
48 installFakeEnvironment,
49 rejectPendingCommand,
50 threadWithHistory,
51 threadWithQuestion,
52 type FakeDriver,
53} from "../../test/fakeEnvironment";
54import { act, fakeTimers, render } from "../../test/render";
55
56const PNG = Uint8Array.from(
57 atob(
58 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=",
59 ),
60 (char) => char.charCodeAt(0),
61);
62
63/** Accepts every attachment upload without sending its bytes, until disposed. */
64function acceptAttachmentUploads(): Disposable {
65 const mint = answerRpc(WS_METHODS.attachmentsCreateUploadUrl, () =>
66 Effect.succeed({ attachmentId: "upload-1", relativeUrl: "/upload", expiresAt: 0 }),
67 );
68 // Sending verifies each ready upload still exists on the server.
69 const verify = answerRpc(WS_METHODS.assetsCreateUrl, () =>
70 Effect.succeed({ relativeUrl: "/upload-1", expiresAt: 0 }),
71 );
72 const status = vi.spyOn(XMLHttpRequest.prototype, "status", "get").mockReturnValue(200);
73 const send = vi.spyOn(XMLHttpRequest.prototype, "send").mockImplementation(function (
74 this: XMLHttpRequest,
75 ) {
76 queueMicrotask(() => this.dispatchEvent(new ProgressEvent("load")));
77 });
78 return {
79 [Symbol.dispose]: () => {
80 send.mockRestore();
81 status.mockRestore();
82 mint[Symbol.dispose]();
83 verify[Symbol.dispose]();
84 },
85 };
86}
87
88// One input event, where typing a key at a time takes seconds on a loaded CI runner.
89const insertText = (text: string) => cdp().send("Input.insertText", { text });
90
91/** Holds every call to `method` until `release`, then ends it with `end`, until disposed. */
92function holdRpc<Input>(method: string, end: Effect.Effect<never, Error>) {
93 let release = () => {};
94 const held = new Promise<void>((resolve) => {
95 release = resolve;
96 });
97 const calls: Input[] = [];
98 const answer = answerRpc(method, (input: Input) => {
99 calls.push(input);
100 return Effect.promise(() => held).pipe(Effect.andThen(end));
101 });
102 return { calls, release, [Symbol.dispose]: () => answer[Symbol.dispose]() };
103}
104
105// The socket is the only fake layer; see test/appScenarios.renders.tsx.
106vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => {
107 const [actual, { fakeDriver }, Layer] = await Promise.all([
108 importOriginal<{ readonly ConnectionDriver: Context.Key<unknown, FakeDriver> }>(),
109 import("../../test/fakeEnvironment"),
110 import("effect/Layer"),
111 ]);
112 return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) };
113});
114
115vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({
116 ...(await original()),
117 trackRpcRequestSent: () => {},
118}));
119
120it("opens a linked Linear issue from an inactive thread's sidebar badge", async () => {
121 const style = document.createElement("style");
122 style.textContent = stylesheet;
123 document.head.append(style);
124 using _style = { [Symbol.dispose]: () => style.remove() };
125 const first = threadWithHistory("issue-first", 1);
126 const linked = threadWithHistory("issue-linked", 1);
127 const issueRef = {
128 projectId: PROJECT_ID,
129 tracker: IssueTrackerKind.make("linear"),
130 host: "linear.app",
131 scope: "WEB",
132 key: "WEB-123",
133 } satisfies IssueRef;
134 const issue: ThreadIssueLink = {
135 ...issueRef,
136 url: "https://linear.app/example/issue/WEB-123/add-keyboard-support",
137 source: "manual",
138 linkedAt: "2026-01-01T00:00:00.000Z",
139 displayKey: issueRef.key,
140 title: "Add keyboard support",
141 };
142 using _environment = installFakeEnvironment([first, { ...linked, issues: [issue] }]);
143 const liveTitle = "Add keyboard shortcuts to the sidebar";
144 using _detail = answerRpc(WS_METHODS.issuesDetail, (input: IssueRef) => {
145 expect(input).toEqual(issueRef);
146 return Effect.succeed({
147 ...issue,
148 title: liveTitle,
149 author: { login: "sam", name: null, avatarUrl: null },
150 state: { category: "open", name: "Open" },
151 createdAt: issue.linkedAt,
152 updatedAt: issue.linkedAt,
153 closedAt: null,
154 assignees: [],
155 labels: [],
156 commentCount: 3,
157 projectTitle: "render",
158 writable: false,
159 capabilities: {
160 create: false,
161 edit: false,
162 comment: false,
163 labels: false,
164 assignees: false,
165 reactions: false,
166 templates: false,
167 linkedPullRequests: false,
168 events: false,
169 search: false,
170 },
171 viewerPermissions: {
172 setState: false,
173 comment: false,
174 edit: false,
175 labels: false,
176 assignees: false,
177 },
178 states: [],
179 viewer: null,
180 body: "",
181 comments: [],
182 commentsCursor: null,
183 events: [],
184 linkedPullRequests: [],
185 } satisfies IssueDetail);
186 });
187 __setClientSettingsForTests({
188 ...DEFAULT_CLIENT_SETTINGS,
189 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
190 });
191 await page.viewport(1400, 900);
192 const router = getRouter(
193 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${first.id}`] }),
194 );
195 await router.load();
196 await using _app = await render(<AppRoot router={router} />, {
197 // AppRoot brings its own router.
198 router: false,
199 });
200 const badge = page.getByRole("button", {
201 name: `Issue ${issue.displayKey}: ${issue.title}, Open`,
202 });
203 await expect.element(badge).toBeVisible();
204 expect(badge.element().querySelector("svg")).toHaveClass(/text-emerald-600/);
205 await userEvent.hover(badge);
206 const issueName = `Issue ${issue.displayKey}: ${liveTitle}`;
207 const previewLink = page.getByRole("link", { name: issueName });
208 await userEvent.hover(previewLink.getByText("sam", { exact: true }));
209 await expect.element(previewLink).toBeVisible();
210 const contextMenu = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });
211 await act(() => previewLink.element().dispatchEvent(contextMenu));
212 expect(contextMenu.defaultPrevented).toBe(false);
213 await userEvent.click(badge);
214 const issueRow = page
215 .getByRole("region", { name: "Linked issues" })
216 .getByRole("link", { name: issueName });
217 await expect.element(issueRow.getByRole("img", { name: "Open" })).toBeVisible();
218 await expect.element(issueRow.getByRole("img", { name: "3 comments" })).toBeVisible();
219 await expect.element(issueRow.getByRole("img", { name: "Linear" })).toBeVisible();
220 await expect.element(issueRow.getByText(issue.scope, { exact: true })).toBeVisible();
221 await userEvent.click(issueRow);
222 expect(router.history.location.pathname).toBe(`/${ENVIRONMENT_ID}/${linked.id}`);
223 await expect.element(page.getByRole("heading", { name: liveTitle })).toBeVisible();
224 await act(() => useRightPanelStore.getState().close(scopeThreadRef(ENVIRONMENT_ID, linked.id)));
225 await expect
226 .element(
227 page.getByRole("region", { name: "Thread details" }).getByRole("link", {
228 name: issueName,
229 exact: true,
230 }),
231 )
232 .toBeVisible();
233});
234
235it("a machine chip stashed in one thread restores with its machine in another", async () => {
236 const other = threadWithHistory("thread-stash-restore", 1);
237 const asking = threadWithQuestion("thread-stash-question", "Which file should change?");
238 using _environment = installFakeEnvironment([other, asking]);
239 __setClientSettingsForTests({
240 ...DEFAULT_CLIENT_SETTINGS,
241 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
242 });
243 const draftId = DraftId.make("draft-stash-machine");
244 const machine = environmentContextRecord(EnvironmentId.make("environment-build"), "Build box");
245 const drafts = useComposerDraftStore.getState();
246 drafts.setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
247 threadId: ThreadId.make("thread-stash-machine"),
248 });
249 drafts.setPrompt(draftId, "Deploy on ");
250 drafts.addEnvironmentContexts(draftId, [machine]);
251 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
252 await router.load();
253 await using _app = await render(<AppRoot router={router} />, {
254 // AppRoot brings its own router.
255 router: false,
256 });
257 const editor = page.getByTestId("composer-editor");
258 const pressStashShortcut = async () => {
259 await userEvent.click(editor);
260 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
261 };
262 await vi.waitFor(() => expect(editor.element().textContent).toContain("Deploy on"));
263 // A draft can't stash until the shell snapshot lists its project.
264 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
265 await pressStashShortcut();
266 await vi.waitFor(() => expect(usePromptStashStore.getState().entries).toHaveLength(1));
267
268 // An answer carries no machines, so an open question refuses the restore and keeps the entry.
269 await router.navigate({ to: `/${ENVIRONMENT_ID}/${asking.id}` });
270 await expect.element(page.getByText("Which file should change?")).toBeVisible();
271 await userEvent.click(page.getByRole("button", { name: /^Stashed prompts/ }));
272 await userEvent.click(page.getByRole("button", { name: /^Restore stashed prompt/ }));
273 await vi.waitFor(() =>
274 expect(document.body.textContent).toContain("Stashed machines can't go in an answer"),
275 );
276 expect(usePromptStashStore.getState().entries).toHaveLength(1);
277
278 await router.navigate({ to: `/${ENVIRONMENT_ID}/${other.id}` });
279 await expect.element(page.getByText("Answer 0 for thread-stash-restore.")).toBeVisible();
280 await pressStashShortcut();
281
282 await vi.waitFor(() => expect(editor.element().textContent).toContain("Deploy on"));
283 expect(
284 useComposerDraftStore.getState().getComposerDraft(scopeThreadRef(ENVIRONMENT_ID, other.id))
285 ?.environmentContexts,
286 ).toEqual([machine]);
287 expect(
288 useComposerDraftStore.getState().getComposerDraft(draftId)?.environmentContexts ?? [],
289 ).toEqual([]);
290});
291
292it("a question that opens while a stashed file is checked keeps a machine stash", async () => {
293 const thread = threadWithHistory("thread-stash-late-question", 1);
294 const asking = threadWithQuestion("thread-stash-late-question", "Which file should change?");
295 const [request] = asking.runtimeRequests ?? [];
296 const question = asking.items.at(-1);
297 if (!request || !question) throw new Error("threadWithQuestion has no question");
298 using _environment = installFakeEnvironment([thread]);
299 __setClientSettingsForTests({
300 ...DEFAULT_CLIENT_SETTINGS,
301 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
302 });
303 usePromptStashStore.getState().stashEntry({
304 id: "stash-late-question",
305 createdAt: "2026-01-01T00:00:00.000Z",
306 prompt: "Deploy on ",
307 attachments: [],
308 files: [
309 {
310 id: "file-notes",
311 name: "notes.txt",
312 mimeType: "text/plain",
313 sizeBytes: 5,
314 attachmentId: "attachment-notes",
315 environmentId: ENVIRONMENT_ID,
316 },
317 ],
318 droppedImageNames: [],
319 records: [environmentContextRecord(EnvironmentId.make("environment-build"), "Build box")],
320 });
321 const router = getRouter(
322 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
323 );
324 await router.load();
325 await using _app = await render(<AppRoot router={router} />, {
326 // AppRoot brings its own router.
327 router: false,
328 });
329 await expect.element(page.getByText("Answer 0 for thread-stash-late-question.")).toBeVisible();
330 await userEvent.click(page.getByRole("button", { name: /^Stashed prompts/ }));
331 await userEvent.click(page.getByRole("button", { name: /^Restore stashed prompt/ }));
332
333 // The question opens while the restore still waits on the server's file check.
334 await vi.waitFor(() => expect(hasPendingAssetUrl()).toBe(true));
335 await emitThreadEvent(thread.id, { type: "turn-item.updated", payload: question });
336 await emitThreadEvent(thread.id, { type: "runtime-request.updated", payload: request });
337 await expect.element(page.getByText("Which file should change?")).toBeVisible();
338 await answerAssetUrls();
339
340 await vi.waitFor(() =>
341 expect(document.body.textContent).toContain("Stashed machines can't go in an answer"),
342 );
343 expect(usePromptStashStore.getState().entries).toHaveLength(1);
344 usePromptStashStore.getState().takeEntry("stash-late-question");
345});
346
347it("a new draft does not load its reserved thread before the server lists it", async () => {
348 using _environment = installFakeEnvironment([]);
349 using fetchSpy = vi.spyOn(globalThis, "fetch");
350 __setClientSettingsForTests({
351 ...DEFAULT_CLIENT_SETTINGS,
352 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
353 });
354 const draftId = DraftId.make("draft-27443");
355 const threadId = ThreadId.make("thread-27443");
356 useComposerDraftStore
357 .getState()
358 .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, { threadId });
359
360 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
361 await router.load();
362 await using _app = await render(<AppRoot router={router} />, {
363 // AppRoot brings its own router.
364 router: false,
365 });
366 await expect.element(page.getByTestId("composer-editor")).toBeVisible();
367 // The shell snapshot has arrived once the sidebar lists the project, so the connection is up.
368 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
369
370 const threadRequests = fetchSpy.mock.calls
371 .map(([input]) => String(input instanceof Request ? input.url : input))
372 .filter((url) => url.includes(`/api/orchestration/threads/${threadId}/`));
373 // A 404 here marks the thread deleted, and the view never loads it once the send creates it.
374 expect(threadRequests).toEqual([]);
375});
376
377it("an interrupted image-only first send of a new thread says it may not have been sent", async () => {
378 using _environment = installFakeEnvironment([]);
379 __setClientSettingsForTests({
380 ...DEFAULT_CLIENT_SETTINGS,
381 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
382 });
383 const draftId = DraftId.make("draft-image-only-interrupted");
384 useComposerDraftStore
385 .getState()
386 .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
387 threadId: ThreadId.make("thread-image-only-interrupted"),
388 });
389 // A dropped connection interrupts a new thread's launch, which is not resent.
390 using launch = holdRpc(ORCHESTRATION_V2_WS_METHODS.launchThread, Effect.interrupt);
391 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
392 await router.load();
393 await using _app = await render(<AppRoot router={router} />, {
394 // AppRoot brings its own router.
395 router: false,
396 });
397 using _uploads = acceptAttachmentUploads();
398 const editor = page.getByTestId("composer-editor");
399 await expect.element(editor).toBeVisible();
400 // The send needs the project, which arrives with the shell snapshot.
401 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
402
403 await userEvent.click(editor);
404 const clipboardData = new DataTransfer();
405 clipboardData.items.add(new File([PNG], "shot.png", { type: "image/png" }));
406 editor
407 .element()
408 .dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
409 await expect.element(page.getByRole("img", { name: "shot.png" })).toBeVisible();
410 await userEvent.keyboard("{Enter}");
411 await vi.waitFor(() => expect(launch.calls).toHaveLength(1));
412 await userEvent.keyboard("next draft");
413 await expect.element(editor).toHaveTextContent("next draft");
414 launch.release();
415
416 await expect.element(page.getByText("Message may not have been sent")).toBeVisible();
417 await expect.element(editor).toHaveTextContent("next draft");
418 // With no text there is nothing to copy.
419 expect(page.getByText("Copy message", { exact: true }).query()).toBeNull();
420});
421
422it("opens the thread actions menu for an older settled thread the shell leaves out", async () => {
423 const thread = { ...threadWithHistory("older-settled", 1), olderSettled: true as const };
424 using _environment = installFakeEnvironment([thread]);
425 __setClientSettingsForTests({
426 ...DEFAULT_CLIENT_SETTINGS,
427 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
428 });
429
430 const router = getRouter(
431 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
432 );
433 await router.load();
434 await using _app = await render(<AppRoot router={router} />, {
435 // AppRoot brings its own router.
436 router: false,
437 });
438 await expect.element(page.getByText("older-settled: question 0")).toBeVisible();
439
440 await page.getByRole("button", { name: `Thread actions for ${thread.title}` }).click();
441 // Without a bound the poll runs to the test deadline and reports a bare timeout.
442 await expect
443 .element(page.getByRole("menuitem", { name: "Rename thread" }), { timeout: 5_000 })
444 .toBeVisible();
445});
446
447it("retains each thread's diff selection when returning from another thread or Settings", async () => {
448 const a = threadWithHistory("diff-selection-a", 1);
449 const b = threadWithHistory("diff-selection-b", 1);
450 using _environment = installFakeEnvironment([a, b]);
451 __setClientSettingsForTests({
452 ...DEFAULT_CLIENT_SETTINGS,
453 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
454 });
455 const aRef = scopeThreadRef(ENVIRONMENT_ID, a.id);
456 const bRef = scopeThreadRef(ENVIRONMENT_ID, b.id);
457 useRightPanelStore.getState().open(aRef, "diff");
458 useRightPanelStore.getState().open(bRef, "diff");
459 useDiffPanelStore.getState().selectBranchBaseRef(bRef, "origin/release");
460 const router = getRouter(createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${a.id}`] }));
461 await router.load();
462 await using _app = await render(<AppRoot router={router} />, {
463 // AppRoot brings its own router.
464 router: false,
465 });
466 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
467 await act(() => useDiffPanelStore.getState().selectGitScope(aRef, "unstaged"));
468
469 await act(() =>
470 router.navigate({
471 to: "/$environmentId/$threadId",
472 params: { environmentId: ENVIRONMENT_ID, threadId: b.id },
473 }),
474 );
475 await expect.element(page.getByText(`Answer 0 for ${b.id}.`)).toBeVisible();
476 expect(selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, bRef)).toEqual({
477 kind: "branch",
478 baseRef: "origin/release",
479 });
480 await act(() =>
481 router.navigate({
482 to: "/$environmentId/$threadId",
483 params: { environmentId: ENVIRONMENT_ID, threadId: a.id },
484 }),
485 );
486 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
487 expect(selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, aRef)).toEqual({
488 kind: "unstaged",
489 });
490
491 await act(() => useDiffPanelStore.getState().selectTurn(aRef, a.runs[0]!.id));
492 await act(() => router.navigate({ to: "/settings/general" }));
493 await expect
494 .element(page.getByRole("heading", { name: "Time format", exact: true }))
495 .toBeVisible();
496 await act(() =>
497 router.navigate({
498 to: "/$environmentId/$threadId",
499 params: { environmentId: ENVIRONMENT_ID, threadId: a.id },
500 }),
501 );
502 await expect.element(page.getByText(`Answer 0 for ${a.id}.`)).toBeVisible();
503 expect(
504 selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, aRef),
505 ).toMatchObject({
506 kind: "turn",
507 turnId: a.runs[0]!.id,
508 });
509});
510
511it("a stashed prompt ending in a file chip restores with the chip", async () => {
512 using _environment = installFakeEnvironment([]);
513 __setClientSettingsForTests({
514 ...DEFAULT_CLIENT_SETTINGS,
515 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
516 });
517 const draftId = DraftId.make("draft-28338");
518 const drafts = useComposerDraftStore.getState();
519 drafts.setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, {
520 threadId: ThreadId.make("thread-28338"),
521 });
522 drafts.setPrompt(draftId, "Check [package.json](package.json) ");
523 const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] }));
524 await router.load();
525 await using _app = await render(<AppRoot router={router} />, {
526 // AppRoot brings its own router.
527 router: false,
528 });
529 const chip = page.getByRole("button", { name: "Preview package.json" });
530 await expect.element(chip).toBeVisible();
531 // The stash shortcut is a no-op until the shell snapshot lists the project.
532 await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible();
533
534 const editor = page.getByTestId("composer-editor");
535 await userEvent.click(editor);
536 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
537 await expect.element(chip).not.toBeInTheDocument();
538 await userEvent.keyboard("{ControlOrMeta>}s{/ControlOrMeta}");
539
540 await vi.waitFor(() => expect(editor.element().textContent).toContain("Check"));
541 expect(editor.element().textContent).not.toContain("[package.json](package.json)");
542 await expect.element(chip).toBeVisible();
543});
544
545it("a rejected send leaves the timeline when a new draft was typed meanwhile", async () => {
546 const thread = threadWithHistory("rejected-send", 1);
547 using _environment = installFakeEnvironment([thread], {
548 acceptCommands: true,
549 holdCommand: (command) => command.type === "message.dispatch",
550 });
551 __setClientSettingsForTests({
552 ...DEFAULT_CLIENT_SETTINGS,
553 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
554 });
555 const router = getRouter(
556 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
557 );
558 await router.load();
559 await using _app = await render(<AppRoot router={router} />, {
560 // AppRoot brings its own router.
561 router: false,
562 });
563 await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible();
564
565 const editor = page.getByTestId("composer-editor");
566 await userEvent.click(editor);
567 await userEvent.keyboard("Failed prompt{Enter}");
568 await vi.waitFor(() =>
569 expect(dispatchedCommands().map((command) => command.type)).toContain("message.dispatch"),
570 );
571 await expect.element(page.getByText("Failed prompt")).toBeVisible();
572 await userEvent.keyboard("Next draft");
573
574 await rejectPendingCommand("Attachment 'sample.png' cannot be sent.");
575
576 await expect.element(page.getByText("Attachment 'sample.png' cannot be sent.")).toBeVisible();
577 await expect.element(page.getByText("Failed prompt")).not.toBeInTheDocument();
578 expect(editor.element().textContent).toContain("Next draft");
579});
580
581it("Enter on an empty prompt resumes an interrupted thread", async () => {
582 const history = threadWithHistory("interrupted", 1);
583 const interruptedRun = { ...history.runs[0]!, status: "interrupted" as const };
584 const thread = { ...history, runs: [interruptedRun] };
585 using _environment = installFakeEnvironment([thread], { acceptCommands: true });
586 __setClientSettingsForTests({
587 ...DEFAULT_CLIENT_SETTINGS,
588 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
589 });
590 const router = getRouter(
591 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
592 );
593 await router.load();
594 await using _app = await render(<AppRoot router={router} />, {
595 // AppRoot brings its own router.
596 router: false,
597 });
598 await expect.element(page.getByRole("button", { name: "Resume thread" })).toBeVisible();
599
600 await userEvent.click(page.getByTestId("composer-editor"));
601 await userEvent.keyboard("{Enter}");
602
603 await vi.waitFor(() =>
604 expect(dispatchedCommands()).toContainEqual(
605 expect.objectContaining({ manualContinuationOfRunId: interruptedRun.id }),
606 ),
607 );
608});
609
610it("opening a thread or returning to the window on a touch tablet does not focus the composer", async () => {
611 const realMatchMedia = window.matchMedia.bind(window);
612 using _touch = vi
613 .spyOn(window, "matchMedia")
614 .mockImplementation((query) => realMatchMedia(query === "(pointer: coarse)" ? "all" : query));
615 const first = threadWithHistory("thread-29469-a", 1);
616 const second = threadWithHistory("thread-29469-b", 1);
617 using _environment = installFakeEnvironment([first, second]);
618 // iPad Pro 11 in landscape: the desktop layout, above max-sm.
619 await page.viewport(1194, 834);
620 __setClientSettingsForTests({
621 ...DEFAULT_CLIENT_SETTINGS,
622 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
623 });
624 const router = getRouter(
625 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${first.id}`] }),
626 );
627 await router.load();
628 await using _app = await render(<AppRoot router={router} />, {
629 // AppRoot brings its own router.
630 router: false,
631 });
632 const composer = page.getByTestId("composer-editor");
633 await expect.element(page.getByText(`Answer 0 for ${first.id}.`)).toBeVisible();
634
635 // Fake frames hold the next thread entry's focus frame until the test advances it.
636 using _timers = fakeTimers();
637 await act(() =>
638 router.navigate({
639 to: "/$environmentId/$threadId",
640 params: { environmentId: ENVIRONMENT_ID, threadId: second.id },
641 }),
642 );
643 await expect.element(page.getByText(`Answer 0 for ${second.id}.`)).toBeVisible();
644 vi.advanceTimersToNextFrame();
645 // Focusing the editor raises the on-screen keyboard, which shrinks the page on iPadOS.
646 expect(document.activeElement).not.toBe(composer.element());
647
648 // ChatView waits two frames after window focus before refocusing the composer.
649 window.dispatchEvent(new FocusEvent("focus"));
650 vi.advanceTimersToNextFrame();
651 vi.advanceTimersToNextFrame();
652 expect(document.activeElement).not.toBe(composer.element());
653});
654
655it("a mounted thread view lets go of the thread structures it has replaced", async () => {
656 // Items are shared with the fixture, so a reopen's snapshot also carries the earlier updates.
657 const history = threadWithHistory("updated", 3);
658 const items = [...history.items];
659 const updated = { ...history, items };
660 const other = threadWithHistory("other", 3);
661 using _environment = installFakeEnvironment([updated, other]);
662 __setClientSettingsForTests({
663 ...DEFAULT_CLIENT_SETTINGS,
664 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
665 });
666 const router = getRouter(createMemoryHistory({ initialEntries: ["/"] }));
667 await router.load();
668 await using _app = await render(<AppRoot router={router} />, { router: false });
669 const open = async (threadId: ThreadId, text: string) => {
670 await act(() =>
671 router.navigate({
672 to: "/$environmentId/$threadId",
673 params: { environmentId: ENVIRONMENT_ID, threadId },
674 }),
675 );
676 await expect.element(page.getByText(text).first()).toBeVisible();
677 };
678 const structureAtom = environmentThreadDetails.quietThreadAtom(
679 scopeThreadRef(ENVIRONMENT_ID, updated.id),
680 );
681
682 // Each round, a new answer arrives while the thread is shown, then the user switches away.
683 const shown: Array<WeakRef<object>> = [];
684 await open(other.id, "Answer 2 for other.");
685 for (let round = 0; round < 6; round++) {
686 await open(updated.id, round === 0 ? "Answer 2 for updated." : `Update ${round - 1}.`);
687 const update = assistantItem(
688 updated.id,
689 RunId.make("updated-run-2"),
690 `updated-update-${round}`,
691 6 + round,
692 `Update ${round}.`,
693 );
694 items.push(update);
695 await act(() => emitThreadEvent(updated.id, { type: "turn-item.updated", payload: update }));
696 await expect.element(page.getByText(`Update ${round}.`)).toBeVisible();
697 shown.push(new WeakRef(appAtomRegistry.get(structureAtom)!.projection));
698 await open(other.id, "Answer 2 for other.");
699 }
700 await cdp().send("HeapProfiler.collectGarbage");
701
702 // The thread keeps its latest structure, and the timeline may remember the one before it.
703 const kept = shown.slice(0, -2).flatMap((structure, round) => (structure.deref() ? [round] : []));
704 expect(kept).toEqual([]);
705});
706
707it("a shortcut conditioned on rightPanelOpen sees the thread's open right panel", async () => {
708 await page.viewport(1280, 800);
709 const thread = threadWithHistory("thread-panel-shortcut", 1);
710 using _environment = installFakeEnvironment([thread], {
711 keybindings: mergeWithDefaultKeybindings(
712 compileResolvedKeybindingsConfig([
713 { key: "ctrl+t", command: "rightPanel.new", when: "rightPanelOpen && !terminalFocus" },
714 { key: "ctrl+t", command: "rightPanel.toggle", when: "!rightPanelOpen" },
715 ]),
716 ),
717 });
718 __setClientSettingsForTests({
719 ...DEFAULT_CLIENT_SETTINGS,
720 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
721 });
722 const router = getRouter(
723 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
724 );
725 await router.load();
726 await using _app = await render(<AppRoot router={router} />, {
727 // AppRoot brings its own router.
728 router: false,
729 });
730 const composer = page.getByTestId("composer-editor");
731 const toggle = page.getByRole("button", { name: "Toggle right panel", exact: true });
732 await expect.element(toggle).toHaveAttribute("aria-pressed", "false");
733 await toggle.click();
734 await page.getByRole("button", { name: /^Files/ }).click();
735 await composer.click();
736 await userEvent.keyboard("{Control>}t{/Control}");
737 await expect.element(page.getByRole("menuitem", { name: /Files/ })).toBeVisible();
738 await expect.element(toggle).toHaveAttribute("aria-pressed", "true");
739});
740
741it("selecting a side-chat tab focuses that side chat's composer", async () => {
742 const parent = threadWithHistory("focus-parent", 1);
743 // The shell loaded by the file's first test stays; a family read serves side chats added later.
744 const sideChat = (name: string) => ({
745 ...threadWithHistory(name, 1),
746 sideChatOf: parent.id,
747 olderSettled: true as const,
748 });
749 const side = sideChat("focus-side");
750 const otherSide = sideChat("focus-other-side");
751 await page.viewport(1400, 900);
752 using _environment = installFakeEnvironment([parent, side, otherSide]);
753 __setClientSettingsForTests({
754 ...DEFAULT_CLIENT_SETTINGS,
755 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
756 });
757 const parentRef = scopeThreadRef(ENVIRONMENT_ID, parent.id);
758 useRightPanelStore.getState().openSideChat(parentRef, otherSide.id);
759 useRightPanelStore.getState().openSideChat(parentRef, side.id);
760 const router = getRouter(
761 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${parent.id}`] }),
762 );
763 await router.load();
764 await using screen = await render(<AppRoot router={router} />, {
765 // AppRoot brings its own router.
766 router: false,
767 });
768 using _focus = { [Symbol.dispose]: startWorkspaceFocus(router) };
769 const mainEditor = screen.getByRole("textbox", { name: `Message ${parent.title}`, exact: true });
770 const sideEditor = screen.getByRole("textbox", { name: `Message ${side.title}`, exact: true });
771 await expect.element(sideEditor).toBeVisible();
772 await userEvent.click(mainEditor);
773 await userEvent.keyboard("main draft");
774
775 await userEvent.click(screen.getByRole("button", { name: otherSide.title, exact: true }));
776 const otherEditor = screen.getByRole("textbox", {
777 name: `Message ${otherSide.title}`,
778 exact: true,
779 });
780 await expect.element(otherEditor).toHaveFocus();
781 await userEvent.keyboard("other draft");
782 await expect.element(otherEditor).toHaveTextContent("other draft");
783
784 await userEvent.click(screen.getByRole("button", { name: side.title, exact: true }));
785 await expect.element(sideEditor).toHaveFocus();
786 await expect.element(mainEditor).toHaveTextContent("main draft");
787});
788
789it("/side sends the draft's attachments and context, and keeps them when it does not start", async () => {
790 await page.viewport(1400, 900);
791 const thread = threadWithHistory("side-attachments", 1);
792 let holdFork = false;
793 using _environment = installFakeEnvironment([thread], {
794 acceptCommands: true,
795 holdCommand: (command) => holdFork && command.type === "thread.fork",
796 });
797 __setClientSettingsForTests({
798 ...DEFAULT_CLIENT_SETTINGS,
799 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
800 });
801 const router = getRouter(
802 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
803 );
804 await router.load();
805 await using _app = await render(<AppRoot router={router} />, {
806 // AppRoot brings its own router.
807 router: false,
808 });
809 using _uploads = acceptAttachmentUploads();
810 await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible();
811
812 const editor = page.getByRole("textbox", { name: `Message ${thread.title}`, exact: true });
813 const image = page.getByRole("img", { name: "shot.png" });
814 const sendImageToSideChat = async () => {
815 await userEvent.click(editor);
816 const clipboardData = new DataTransfer();
817 clipboardData.items.add(new File([PNG], "shot.png", { type: "image/png" }));
818 editor
819 .element()
820 .dispatchEvent(
821 new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }),
822 );
823 await expect.element(image).toBeVisible();
824 await insertText("/side what is this?");
825 await userEvent.keyboard("{Enter}");
826 await expect.element(image).not.toBeInTheDocument();
827 };
828 // The tab opens once the start finished; until then `/side` refuses another side chat.
829 const sideChatTabs = page.getByRole("button", { name: "Side chat", exact: true });
830 const sentMessage = async (fields: Record<string, unknown>, openTabs: number) => {
831 await vi.waitFor(() =>
832 expect(dispatchedCommands()).toContainEqual(
833 expect.objectContaining({ type: "message.dispatch", ...fields }),
834 ),
835 );
836 await expect.element(sideChatTabs).toHaveLength(openTabs);
837 };
838
839 await sendImageToSideChat();
840 await sentMessage(
841 {
842 text: "what is this?",
843 attachments: [expect.objectContaining({ type: "image", id: "upload-1" })],
844 context: {
845 version: 1,
846 records: [expect.objectContaining({ kind: "image", attachmentId: "upload-1" })],
847 },
848 },
849 1,
850 );
851
852 // A reply alone is enough to send.
853 await page.getByRole("button", { name: "Reply to this response" }).first().click();
854 await userEvent.click(editor);
855 await insertText("/side ");
856 await userEvent.keyboard("{Enter}");
857 await sentMessage(
858 {
859 context: expect.objectContaining({
860 records: [expect.objectContaining({ kind: "response" })],
861 }),
862 },
863 2,
864 );
865
866 // A failed start puts the message back after the draft typed meanwhile.
867 holdFork = true;
868 await sendImageToSideChat();
869 await insertText("next draft");
870 await vi.waitFor(() =>
871 expect(dispatchedCommands().filter((command) => command.type === "thread.fork")).toHaveLength(
872 3,
873 ),
874 );
875 await rejectPendingCommand("Side chats are paused.");
876 await expect.element(image).toBeVisible();
877 await vi.waitFor(() =>
878 expect((editor.element() as HTMLElement).innerText.split("\n").filter(Boolean)).toEqual([
879 "next draft",
880 "/side what is this?",
881 ]),
882 );
883});