The best way to control Claude Code, Codex and more from any computer or phone

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