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

DiffPanel.browser.test.tsx

862 lines33.2 KB

1import { RegistryContext } from "@effect/atom-react";
2import { scopeProjectRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
3import {
4 DEFAULT_CLIENT_SETTINGS,
5 EnvironmentId,
6 CheckpointRef,
7 CheckpointScopeId,
8 ProjectId,
9 RunId,
10 ThreadId,
11 TurnItemId,
12 type AssetResource,
13 type ClientSettings,
14 type OrchestrationGetTurnDiffResult,
15 type ReviewBranchCommitsResult,
16 type ReviewDiffPreviewResult,
17 type ReviewDiffPreviewSource,
18 type ScopedThreadRef,
19 type VcsListRefsResult,
20 type VcsStatusResult,
21} from "@t3tools/contracts";
22import * as DateTime from "effect/DateTime";
23import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
24import { expect, it, vi } from "vite-plus/test";
25import { page, userEvent } from "vite-plus/test/browser";
26​
27import "~/index.css";
28import { act, render } from "../../test/render";
29import { makeThreadFixture } from "~/test-fixtures";
30​
31type ResultAtom<A> = Atom.Atom<AsyncResult.AsyncResult<A, Error>>;
32​
33const state = vi.hoisted(() => ({
34 thread: null as ReturnType<typeof makeThreadFixture> | null,
35 threadRef: null as ScopedThreadRef | null,
36 previews: new Map<string | null, ResultAtom<ReviewDiffPreviewResult>>(),
37 patch: null as unknown as ResultAtom<ReviewDiffPreviewSource>,
38 diffFilesCollapsed: false,
39 project: { workspaceRoot: "/project", repositoryIdentity: null } as {
40 workspaceRoot: string;
41 repositoryIdentity: { rootPath: string } | null;
42 trackedFolders?: ReadonlyArray<unknown>;
43 },
44 toolCallItem: null as unknown,
45 config: null as unknown as Atom.Atom<null>,
46 status: null as unknown as ResultAtom<VcsStatusResult>,
47 statusByCwd: new Map<string, ResultAtom<VcsStatusResult>>(),
48 taskFolder: null as ResultAtom<unknown> | null,
49 localRefs: null as unknown as ResultAtom<VcsListRefsResult>,
50 remoteRefs: null as unknown as ResultAtom<VcsListRefsResult>,
51 commits: null as unknown as ResultAtom<ReviewBranchCommitsResult>,
52 checkpoints: [] as unknown[],
53 checkpointDiff: null as Partial<OrchestrationGetTurnDiffResult> | null,
54 editorOpens: [] as string[],
55}));
56​
57vi.mock("~/state/server", () => ({
58 serverEnvironment: { configValueAtom: () => state.config },
59}));
60vi.mock("~/state/review", () => ({
61 reviewEnvironment: {
62 diffPreview: ({ input }: { input: { baseRef?: string } }) =>
63 state.previews.get(input.baseRef ?? null)!,
64 branchCommits: () => state.commits,
65 diffFilePatch: () => state.patch,
66 diffFileContents: {},
67 },
68}));
69vi.mock("~/state/vcs", () => ({
70 vcsEnvironment: {
71 status: ({ input }: { input: { cwd: string } }) =>
72 state.statusByCwd.get(input.cwd) ?? state.status,
73 listRefs: ({ input }: { input: { refKind: "local" | "remote" } }) =>
74 input.refKind === "local" ? state.localRefs : state.remoteRefs,
75 },
76}));
77vi.mock("~/state/entities", () => ({
78 useQuietThreadShell: () => state.thread,
79 useProject: () => state.project,
80 useThreadCheckpointSummaries: () => state.checkpoints,
81 useQuietThreadVisibleTurnItems: () => [],
82 useQuietThreadProjection: () => null,
83}));
84vi.mock("~/state/filesystem", () => ({
85 useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }),
86 filesystemEnvironment: { taskFolder: () => state.taskFolder },
87}));
88vi.mock("~/hooks/useThreadRouteTarget", () => ({ useThreadRouteRef: () => state.threadRef }));
89vi.mock("~/hooks/useSettings", () => ({
90 useClientSettings: (select: (settings: ClientSettings) => unknown) =>
91 select({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: state.diffFilesCollapsed }),
92 updateClientSettings: async () => {},
93}));
94vi.mock("~/hooks/useTheme", () => ({
95 useRenderedAppearance: () => "dark",
96 getRenderedAppearance: () => "dark",
97 subscribeRenderedAppearance: () => () => {},
98}));
99vi.mock("~/state/queries", () => ({
100 useCheckpointDiff: () => ({ data: state.checkpointDiff, error: null, isPending: false }),
101 useTurnItemDetail: () => ({
102 data: state.toolCallItem ? { item: state.toolCallItem } : null,
103 error: null,
104 isPending: false,
105 }),
106 useDebouncedValue: <A,>(value: A) => value,
107}));
108vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => async () => {} }));
109vi.mock("~/editorPreferences", () => ({
110 useOpenInPreferredEditor: () => async (target: string) => {
111 state.editorOpens.push(target);
112 return { _tag: "Success" };
113 },
114}));
115vi.mock("~/fileContextMenu", () => ({ useFileContextMenuHandler: () => () => {} }));
116vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => async () => {} }));
117vi.mock("./diffs/DiffCommentAnnotation", () => ({ DiffCommentAnnotation: () => null }));
118vi.mock(import("~/assets/assetUrls"), async (original) => ({
119 ...(await original()),
120 useAssetUrlState: (
121 environmentId: EnvironmentId | null,
122 resource: AssetResource | null,
123 revision?: string | null,
124 ) => {
125 const valid =
126 environmentId === EnvironmentId.make("environment") &&
127 resource !== null &&
128 (resource._tag === "draft-workspace-file"
129 ? resource.cwd === cwd && resource.path.startsWith(`${cwd}/`)
130 : (resource._tag === "workspace-file" || resource._tag === "media-file") &&
131 state.thread !== null &&
132 resource.threadId === state.thread.id &&
133 resource.path.startsWith(`${cwd}/`));
134 if (!valid) {
135 return { _tag: "Failure" as const };
136 }
137 return {
138 _tag: "Success" as const,
139 url: `data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==#${revision ?? ""}`,
140 expiresAt: Number.MAX_SAFE_INTEGER,
141 };
142 },
143}));
144vi.mock("./diffs/DiffFileTree", () => ({ DiffFileTree: () => null }));
145vi.mock("./DiffFilePathCopyButton", () => ({ DiffFilePathCopyButton: () => null }));
146​
147import DiffPanel from "./DiffPanel";
148import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
149import { useDiffPanelSessionStore, useDiffPanelStore } from "~/diffPanelStore";
150import { selectThreadRightPanelState, useRightPanelStore } from "~/rightPanelStore";
151​
152const cwd = "/project-worktree";
153const errorMessage = "Could not find a common commit between 'origin/orphan' and HEAD.";
154​
155function preview(): ReviewDiffPreviewResult {
156 return {
157 cwd,
158 generatedAt: DateTime.makeUnsafe("2026-10-30T00:00:00Z"),
159 sources: [
160 {
161 id: "branch",
162 kind: "branch-range",
163 title: "Changes",
164 baseRef: "main",
165 headRef: "dev",
166 diff: "",
167 diffHash: "empty",
168 truncated: false,
169 patchesDeferred: true,
170 files: [],
171 },
172 ],
173 };
175​
176function setup(failedBaseRef: string | null) {
177 const reset = () => {
178 useDiffPanelStore.setState({
179 byThreadKey: {},
180 branchBaseRefByThreadKey: {},
181 gitRepositoryPathByThreadKey: {},
182 });
183 useDiffPanelSessionStore.setState({ collapsedFileKeysByScopeKey: {} });
184 useRightPanelStore.setState({ byThreadKey: {}, threadPanelVisibilityByThreadKey: {} });
185 useComposerDraftStore.setState({
186 draftsByThreadKey: {},
187 draftThreadsByThreadKey: {},
188 logicalProjectDraftThreadKeyByLogicalProjectKey: {},
189 });
190 };
191 reset();
192 state.diffFilesCollapsed = false;
193 state.project = { workspaceRoot: "/project", repositoryIdentity: null };
194 state.statusByCwd.clear();
195 state.taskFolder = null;
196 state.toolCallItem = null;
197 state.checkpoints = [];
198 state.checkpointDiff = null;
199 state.editorOpens = [];
200 const patch = Atom.make<AsyncResult.AsyncResult<ReviewDiffPreviewSource, Error>>(
201 AsyncResult.initial(),
202 );
203 state.patch = patch;
204 state.threadRef = {
205 environmentId: EnvironmentId.make("environment"),
206 threadId: ThreadId.make("thread"),
207 };
208 state.thread = makeThreadFixture({
209 ...state.threadRef,
210 id: state.threadRef.threadId,
211 projectId: ProjectId.make("project"),
212 branch: "dev",
213 worktreePath: cwd,
214 });
215 state.previews.clear();
216 state.previews.set(null, Atom.make(AsyncResult.success(preview())));
217 state.previews.set("main", Atom.make(AsyncResult.success(preview())));
218 state.previews.set(failedBaseRef, Atom.make(AsyncResult.fail(new Error(errorMessage))));
219 state.config = Atom.make(null);
220 state.status = Atom.make(
221 AsyncResult.success({
222 isRepo: true,
223 hasPrimaryRemote: true,
224 isDefaultRef: false,
225 refName: "dev",
226 hasWorkingTreeChanges: false,
227 workingTree: { rootPath: cwd, files: [], insertions: 0, deletions: 0 },
228 hasUpstream: true,
229 aheadCount: 0,
230 behindCount: 0,
231 pr: null,
232 }),
233 );
234 const refs = (names: string[], isRemote: boolean): VcsListRefsResult => ({
235 isRepo: true,
236 hasPrimaryRemote: true,
237 nextCursor: null,
238 totalCount: names.length,
239 refs: names.map((name) => ({
240 name,
241 isRemote,
242 ...(isRemote ? { remoteName: "origin" } : {}),
243 current: name === "dev",
244 isDefault: name === "main",
245 worktreePath: null,
246 })),
247 });
248 state.localRefs = Atom.make(AsyncResult.success(refs(["dev", "main"], false)));
249 state.remoteRefs = Atom.make(AsyncResult.success(refs(["origin/orphan"], true)));
250 state.commits = Atom.make(AsyncResult.success({ commits: [], truncated: false }));
251 useDiffPanelStore.getState().selectBranchBaseRef(state.threadRef, failedBaseRef);
252 const registry = AtomRegistry.make();
253 return {
254 registry,
255 patch,
256 threadRef: state.threadRef,
257 [Symbol.dispose]() {
258 registry.dispose();
259 reset();
260 },
261 };
263​
264it.each([
265 {
266 name: "a saved unrelated branch",
267 failedBaseRef: "origin/orphan",
268 recovery: "Automatic",
269 baseRef: null,
270 },
271 {
272 name: "an automatic base with unrelated history",
273 failedBaseRef: null,
274 recovery: "main",
275 baseRef: "main",
276 },
277])(
278 "recovers from $name without leaving the diff panel",
279 async ({ failedBaseRef, recovery, baseRef }) => {
280 using context = setup(failedBaseRef);
281 await using screen = await render(
282 <RegistryContext.Provider value={context.registry}>
283 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
284 </RegistryContext.Provider>,
285 );
286 await expect.element(screen.getByText(errorMessage, { exact: true })).toBeVisible();
287 const selector = screen.getByRole("combobox", { name: /Change comparison target/ });
288 await vi.waitFor(() => expect(selector.query()).not.toBeNull());
289 await userEvent.click(selector);
290 await expect.element(page.getByRole("option", { name: "main", exact: true })).toBeVisible();
291 await userEvent.click(page.getByRole("option", { name: recovery, exact: true }));
292 await expect.element(screen.getByText("No net changes in this selection.")).toBeVisible();
293 await expect.element(screen.getByText(errorMessage, { exact: true })).not.toBeInTheDocument();
294 const key = scopedThreadKey(context.threadRef);
295 await vi.waitFor(() => {
296 expect(useDiffPanelStore.getState().byThreadKey[key]).toEqual({ kind: "branch", baseRef });
297 expect(useDiffPanelStore.getState().branchBaseRefByThreadKey[key]).toBe(baseRef);
298 });
299 },
300);
301​
302it("opens a repository-relative file from a nested project without a remote", async () => {
303 using context = setup("origin/orphan");
304 state.thread = { ...state.thread!, worktreePath: null };
305 const path = "project/back\\slash.txt";
306 const metadata = preview();
307 const source = {
308 ...metadata.sources[0]!,
309 files: [{ path, previousPath: null, additions: 1, deletions: 0 }],
310 };
311 state.previews.set("main", Atom.make(AsyncResult.success({ ...metadata, sources: [source] })));
312 state.status = Atom.make(
313 AsyncResult.success({
314 ...AsyncResult.getOrElse(context.registry.get(state.status), () => {
315 throw new Error("Missing status");
316 }),
317 workingTree: { rootPath: "/", files: [], insertions: 0, deletions: 0 },
318 }),
319 );
320 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
321 await using screen = await render(
322 <RegistryContext.Provider value={context.registry}>
323 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
324 </RegistryContext.Provider>,
325 );
326 await userEvent.click(screen.getByText(path, { exact: true }));
327 expect(
328 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, context.threadRef),
329 ).toMatchObject({ activeSurfaceId: "file:back\\slash.txt" });
330});
331​
332// The file panel reads below the thread's folder; anything else goes to the editor.
333it.each([
334 { repository: `${cwd}/api`, surface: "file:api/notes.txt" },
335 { repository: `${cwd}/~`, surface: null },
336 { repository: `${cwd}/api\\..`, surface: null },
337 { repository: `${cwd}/a:repo`, surface: null },
338 { repository: "/elsewhere/api", surface: null },
339])("opens a selected repository's changed file at $repository", async ({ repository, surface }) => {
340 using context = setup(null);
341 const path = "notes.txt";
342 const metadata = preview();
343 const source = {
344 ...metadata.sources[0]!,
345 kind: "working-tree" as const,
346 files: [{ path, previousPath: null, additions: 1, deletions: 0 }],
347 };
348 state.previews.set(null, Atom.make(AsyncResult.success({ ...metadata, sources: [source] })));
349 const threadFolderStatus = AsyncResult.getOrThrow(context.registry.get(state.status));
350 state.status = Atom.make(AsyncResult.success({ ...threadFolderStatus, isRepo: false }));
351 state.project = { ...state.project, trackedFolders: [{}] };
352 state.taskFolder = Atom.make(
353 AsyncResult.success({
354 taskFolder: {
355 root: cwd,
356 repositories: [{ repositoryPath: repository, name: "api", worktreePath: repository }],
357 },
358 }),
359 );
360 useDiffPanelStore.getState().selectGitScope(context.threadRef, "unstaged");
361 await using screen = await render(
362 <RegistryContext.Provider value={context.registry}>
363 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
364 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
365 </div>
366 </RegistryContext.Provider>,
367 );
368 await userEvent.click(screen.getByText(path, { exact: true }));
369 const { activeSurfaceId } = selectThreadRightPanelState(
370 useRightPanelStore.getState().byThreadKey,
371 context.threadRef,
372 );
373 expect(activeSurfaceId?.startsWith("file:") ? activeSurfaceId : null).toBe(surface);
374 expect(state.editorOpens).toEqual(surface === null ? [`${repository}/${path}`] : []);
375});
376​
377// A repository the picker selects in a plain task folder has a status of its own.
378it.each([
379 { checkout: "the thread folder", repository: null },
380 { checkout: "a selected repository", repository: `${cwd}/api` },
381])("rereads the Uncommitted list after the Git menu commits $checkout", async ({ repository }) => {
382 using context = setup(null);
383 const path = "committed.txt";
384 const metadata = preview();
385 const source = {
386 ...metadata.sources[0]!,
387 kind: "working-tree" as const,
388 files: [{ path, previousPath: null, additions: 1, deletions: 0 }],
389 };
390 let reads = 0;
391 state.previews.set(
392 null,
393 Atom.readable(() => {
394 reads += 1;
395 return AsyncResult.success({ ...metadata, sources: [source] });
396 }),
397 );
398 const dirty = (insertions: number) =>
399 AsyncResult.success({
400 isRepo: true,
401 hasPrimaryRemote: true,
402 isDefaultRef: false,
403 refName: "dev",
404 hasWorkingTreeChanges: insertions > 0,
405 workingTree: { rootPath: cwd, files: [], insertions, deletions: 0 },
406 hasUpstream: true,
407 aheadCount: 0,
408 behindCount: 0,
409 pr: null,
410 });
411 const status = Atom.make(dirty(1));
412 if (repository === null) {
413 state.status = status;
414 } else {
415 state.status = Atom.make(
416 AsyncResult.success({
417 ...AsyncResult.getOrThrow(dirty(0)),
418 isRepo: false,
419 refName: null,
420 workingTree: { files: [], insertions: 0, deletions: 0 },
421 }),
422 );
423 state.statusByCwd.set(repository, status);
424 state.project = { ...state.project, trackedFolders: [{}] };
425 state.taskFolder = Atom.make(
426 AsyncResult.success({
427 taskFolder: {
428 root: cwd,
429 repositories: [{ repositoryPath: repository, name: "api", worktreePath: repository }],
430 },
431 }),
432 );
433 }
434 useDiffPanelStore.getState().selectGitScope(context.threadRef, "unstaged");
435 await using screen = await render(
436 <RegistryContext.Provider value={context.registry}>
437 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
438 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
439 </div>
440 </RegistryContext.Provider>,
441 );
442 await expect.element(screen.getByText(path, { exact: true })).toBeVisible();
443 const readsBeforeCommit = reads;
444 // The commit leaves nothing uncommitted, and status says so.
445 context.registry.set(status, dirty(0));
446 await vi.waitFor(() => expect(reads).toBeGreaterThan(readsBeforeCommit));
447});
448​
449it("explains a branch diff whose only changes are hidden test files", async () => {
450 using context = setup("origin/orphan");
451 using _hideTestFiles = {
452 [Symbol.dispose]() {
453 window.localStorage.removeItem("t3code.diffHideTestFiles");
454 },
455 };
456 const path = "math.test.ts";
457 const metadata = preview();
458 const source = {
459 ...metadata.sources[0]!,
460 files: [{ path, previousPath: null, additions: 1, deletions: 0 }],
461 };
462 state.previews.set("main", Atom.make(AsyncResult.success({ ...metadata, sources: [source] })));
463 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
464 await using screen = await render(
465 <RegistryContext.Provider value={context.registry}>
466 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
467 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
468 </div>
469 </RegistryContext.Provider>,
470 );
471 await expect.element(screen.getByText(path, { exact: true })).toBeVisible();
472 await userEvent.click(screen.getByRole("button", { name: "Hide test files", exact: true }));
473 await expect.element(screen.getByText(path, { exact: true })).not.toBeInTheDocument();
474 await expect.element(screen.getByText("1 test file hidden", { exact: true })).toBeVisible();
475 await userEvent.click(screen.getByRole("button", { name: "Show test files", exact: true }));
476 await expect.element(screen.getByText(path, { exact: true })).toBeVisible();
477});
478​
479it.each([false, true])(
480 "expands an unloaded file on the first click with default collapse %s",
481 async (collapsed) => {
482 using context = setup("origin/orphan");
483 state.diffFilesCollapsed = collapsed;
484 const path = `pending-${collapsed}.txt`;
485 const metadata = preview();
486 const source = {
487 ...metadata.sources[0]!,
488 files: [{ path, previousPath: null, additions: 1, deletions: 1 }],
489 };
490 state.previews.set("main", Atom.make(AsyncResult.success({ ...metadata, sources: [source] })));
491 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
492 await using screen = await render(
493 <RegistryContext.Provider value={context.registry}>
494 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
495 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
496 </div>
497 </RegistryContext.Provider>,
498 );
499 const toggle = screen.getByRole("button", { name: `Expand ${path}`, exact: true });
500 await expect.element(toggle).toHaveAttribute("aria-expanded", "false");
501 await userEvent.click(toggle);
502 await act(() =>
503 context.registry.set(
504 context.patch,
505 AsyncResult.success({
506 ...source,
507 diff: `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-before\n+after\n`,
508 }),
509 ),
510 );
511 const loadedToggle = screen.getByRole("button", { name: `Collapse ${path}`, exact: true });
512 await expect.element(loadedToggle).toHaveAttribute("aria-expanded", "true");
513 await expect.element(screen.getByText("after", { exact: true })).toBeVisible();
514 await userEvent.click(loadedToggle);
515 await expect.element(toggle).toHaveAttribute("aria-expanded", "false");
516 },
517);
518​
519it.each([
520 { label: "an existing thread", draft: false, path: "changed.png" },
521 { label: "a new thread", draft: true, path: "draft-changed.png" },
522])("previews a changed image on $label when its file row is expanded", async ({ draft, path }) => {
523 using context = setup("origin/orphan");
524 let composerDraftTarget: ScopedThreadRef | DraftId = context.threadRef;
525 if (draft) {
526 state.threadRef = null;
527 state.thread = null;
528 const draftId = DraftId.make("draft-image-preview");
529 useComposerDraftStore
530 .getState()
531 .setProjectDraftThreadId(
532 scopeProjectRef(context.threadRef.environmentId, ProjectId.make("project")),
533 draftId,
534 { threadId: context.threadRef.threadId, worktreePath: cwd },
535 );
536 composerDraftTarget = draftId;
537 }
538 const metadata = preview();
539 const source = {
540 ...metadata.sources[0]!,
541 files: [{ path, previousPath: null, additions: 0, deletions: 0 }],
542 };
543 const previewAtom = Atom.make(
544 AsyncResult.success({ ...metadata, sources: [source] }, { timestamp: 1 }),
545 );
546 state.previews.set("main", previewAtom);
547 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
548 await using screen = await render(
549 <RegistryContext.Provider value={context.registry}>
550 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
551 <DiffPanel composerDraftTarget={composerDraftTarget} workspaceMutationId={null} visible />
552 </div>
553 </RegistryContext.Provider>,
554 );
555 await userEvent.click(screen.getByRole("button", { name: `Expand ${path}`, exact: true }));
556 await act(() =>
557 context.registry.set(
558 context.patch,
559 AsyncResult.success({
560 ...source,
561 diff: `diff --git a/${path} b/${path}\nindex 19fc4a5..fd0af9e 100644\nBinary files a/${path} and b/${path} differ\n`,
562 }),
563 ),
564 );
565 await expect
566 .element(screen.getByRole("button", { name: `Collapse ${path}`, exact: true }))
567 .toHaveAttribute("aria-expanded", "true");
568 const image = screen.getByRole("img", { name: path });
569 await expect.element(image).toBeVisible();
570 const firstSrc = image.element().getAttribute("src") ?? "";
571​
572 // Replacing a binary file keeps the diff metadata identical; a refetch must still re-read it.
573 await act(() =>
574 context.registry.set(
575 previewAtom,
576 AsyncResult.success({ ...metadata, sources: [source] }, { timestamp: 2 }),
577 ),
578 );
579 await expect.element(image).not.toHaveAttribute("src", firstSrc);
580});
581​
582it("says a turn diff cut off at the server's size limit is incomplete", async () => {
583 using context = setup("origin/orphan");
584 state.checkpoints = [
585 {
586 runId: "run",
587 checkpointTurnCount: 1,
588 checkpointRef: "ref",
589 status: "ready",
590 files: [],
591 assistantMessageId: null,
592 completedAt: "2026-01-01T00:00:00Z",
593 },
594 ];
595 state.checkpointDiff = {
596 diff: "diff --git a/first.txt b/first.txt\n--- a/first.txt\n+++ b/first.txt\n@@ -0,0 +1 @@\n+visible\n\n[truncated]",
597 };
598 useDiffPanelStore.getState().selectTurn(context.threadRef, RunId.make("run"));
599 await using screen = await render(
600 <RegistryContext.Provider value={context.registry}>
601 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
602 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
603 </div>
604 </RegistryContext.Provider>,
605 );
606 await expect.element(screen.getByText("first.txt", { exact: true }).first()).toBeVisible();
607 await expect
608 .element(screen.getByText("This preview exceeds the size limit. Changes shown are incomplete."))
609 .toBeVisible();
610});
611​
612it("shows a turn's repositories in a folder that is not a Git repository", async () => {
613 using context = setup("origin/orphan");
614 state.status = Atom.make(
615 AsyncResult.success({
616 isRepo: false,
617 hasPrimaryRemote: false,
618 isDefaultRef: false,
619 refName: null,
620 hasWorkingTreeChanges: false,
621 workingTree: { files: [], insertions: 0, deletions: 0 },
622 hasUpstream: false,
623 aheadCount: 0,
624 behindCount: 0,
625 pr: null,
626 }),
627 );
628 const patch = (path: string) =>
629 `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-before\n+after\n`;
630 const repository = (name: string) => ({
631 scopeId: CheckpointScopeId.make(`scope-${name}`),
632 name,
633 repositoryPath: `${cwd}/${name}`,
634 cwd: `${cwd}/${name}`,
635 relativePath: name,
636 files: [{ path: "README.md", kind: "modified", additions: 1, deletions: 1 }],
637 baselineMissing: false,
638 });
639 state.checkpoints = [
640 {
641 runId: RunId.make("run-1"),
642 checkpointTurnCount: 1,
643 checkpointRef: CheckpointRef.make("refs/t3/root-1"),
644 status: "missing",
645 files: [],
646 repositories: [repository("api"), repository("web")],
647 assistantMessageId: null,
648 completedAt: "2026-11-10T00:00:00.000Z",
649 },
650 ];
651 state.checkpointDiff = {
652 threadId: context.threadRef.threadId,
653 fromTurnCount: 0,
654 toTurnCount: 1,
655 diff: "",
656 repositories: ["api", "web"].map((name) => ({
657 name,
658 repositoryPath: `${cwd}/${name}`,
659 relativePath: name,
660 diff: patch("README.md"),
661 })),
662 };
663 await using screen = await render(
664 <RegistryContext.Provider value={context.registry}>
665 <div style={{ height: 600, width: 390, display: "flex", flexDirection: "column" }}>
666 <DiffPanel
667 mode="embedded"
668 composerDraftTarget={context.threadRef}
669 workspaceMutationId={null}
670 visible
671 />
672 </div>
673 </RegistryContext.Provider>,
674 );
675 const api = screen.getByRole("button", { name: "Collapse api/README.md", exact: true });
676 const web = screen.getByRole("button", { name: "Collapse web/README.md", exact: true });
677 await expect.element(api).toBeVisible();
678 await expect.element(web).toBeVisible();
679 // Both pickers keep their labels in a phone-width panel.
680 await expect.element(screen.getByText("Latest turn", { exact: true })).toBeVisible();
681 const picker = screen.getByRole("button", { name: "Repository: All repositories" });
682 await expect.element(picker.getByText("All repositories")).toBeVisible();
683 await userEvent.click(picker);
684 await userEvent.click(page.getByRole("menuitemradio", { name: "web" }));
685 await expect.element(web).toBeVisible();
686 await expect.element(api).not.toBeInTheDocument();
687});
688​
689// Paths as git's numstat reports them; the parsed patch keeps their edge whitespace.
690it.each([
691 { path: " leading.ts", name: " leading.ts" },
692 { path: "src/trailing.ts ", name: "src/trailing.ts " },
693])("reveals the turn file $path picked from the changed files", async ({ path, name }) => {
694 using context = setup("origin/orphan");
695 state.diffFilesCollapsed = true;
696 state.checkpoints = [
697 {
698 runId: "run",
699 checkpointTurnCount: 1,
700 checkpointRef: "ref",
701 status: "ready",
702 files: [],
703 assistantMessageId: null,
704 completedAt: "2026-01-01T00:00:00Z",
705 },
706 ];
707 state.checkpointDiff = {
708 diff: `diff --git a/${path} b/${path}\nnew file mode 100644\n--- /dev/null\n+++ b/${path}\t\n@@ -0,0 +1 @@\n+revealed\n`,
709 };
710 useDiffPanelStore.getState().selectTurn(context.threadRef, RunId.make("run"), path);
711 await using screen = await render(
712 <RegistryContext.Provider value={context.registry}>
713 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
714 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
715 </div>
716 </RegistryContext.Provider>,
717 );
718 await expect
719 .element(screen.getByRole("button", { name: `Collapse ${name}`, exact: true }))
720 .toHaveAttribute("aria-expanded", "true");
721});
722​
723it("opens a tool call diff expanded and uses the path its agent recorded", async () => {
724 using context = setup("origin/orphan");
725 state.diffFilesCollapsed = true;
726 // A local thread in a project that is the repository's apps/web folder.
727 state.thread = { ...state.thread!, worktreePath: null };
728 state.project = { workspaceRoot: "/repo/apps/web", repositoryIdentity: { rootPath: "/repo" } };
729 const status = AsyncResult.getOrThrow(context.registry.get(state.status));
730 state.status = Atom.make(
731 AsyncResult.success({ ...status, workingTree: { ...status.workingTree, rootPath: "/repo" } }),
732 );
733 // Claude's Edit can record a path relative to the workspace, unlike the repository's diffs.
734 state.toolCallItem = {
735 type: "file_change",
736 fileName: "src/a.ts",
737 diffStr: "--- src/a.ts\n+++ src/a.ts\n@@ -1 +1 @@\n-before\n+after\n",
738 };
739 useDiffPanelStore.getState().selectToolCall(context.threadRef, {
740 threadId: context.threadRef.threadId,
741 itemId: TurnItemId.make("edit"),
742 revision: "1",
743 });
744 await using screen = await render(
745 <RegistryContext.Provider value={context.registry}>
746 <div className="flex h-[600px] flex-col">
747 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
748 </div>
749 </RegistryContext.Provider>,
750 );
751 await expect
752 .element(screen.getByRole("button", { name: "Collapse src/a.ts", exact: true }))
753 .toHaveAttribute("aria-expanded", "true");
754 await userEvent.click(screen.getByText("src/a.ts", { exact: true }));
755 await vi.waitFor(() =>
756 expect(
757 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, context.threadRef),
758 ).toMatchObject({ activeSurfaceId: "file:src/a.ts" }),
759 );
760});
761​
762it("filters base-ref dropdown rows against the search query", async () => {
763 using context = setup("origin/orphan");
764 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
765 await using screen = await render(
766 <RegistryContext.Provider value={context.registry}>
767 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
768 </RegistryContext.Provider>,
769 );
770 await userEvent.click(screen.getByRole("combobox", { name: /Change comparison target/ }));
771 const searchInput = page.getByPlaceholder("Search refs...");
772 const automaticOption = page.getByRole("option", { name: "Automatic", exact: true });
773 const mainOption = page.getByRole("option", { name: "main", exact: true });
774 const remoteOption = page.getByRole("option", { name: /origin\/orphan/ });
775​
776 await expect.element(automaticOption).toBeVisible();
777 await expect.element(mainOption).toBeVisible();
778 await expect.element(remoteOption).toBeVisible();
779​
780 await userEvent.fill(searchInput, "zzz-no-match");
781 await expect.element(page.getByText("No matching refs.", { exact: true })).toBeVisible();
782 await expect.element(automaticOption).not.toBeInTheDocument();
783 await expect.element(mainOption).not.toBeInTheDocument();
784 await expect.element(remoteOption).not.toBeInTheDocument();
785​
786 await userEvent.fill(searchInput, "main");
787 await expect.element(mainOption).toBeVisible();
788 await expect.element(automaticOption).not.toBeInTheDocument();
789 await expect.element(remoteOption).not.toBeInTheDocument();
790​
791 await userEvent.clear(searchInput);
792 await expect.element(automaticOption).toBeVisible();
793 await expect.element(mainOption).toBeVisible();
794 await expect.element(remoteOption).toBeVisible();
795});
796​
797it("selects the first matching base ref on Enter after searching", async () => {
798 using context = setup("origin/orphan");
799 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
800 await using screen = await render(
801 <RegistryContext.Provider value={context.registry}>
802 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
803 </RegistryContext.Provider>,
804 );
805 await userEvent.click(screen.getByRole("combobox", { name: /Change comparison target/ }));
806 const searchInput = page.getByPlaceholder("Search refs...");
807 await userEvent.type(searchInput, "orphan");
808 await expect.element(page.getByRole("option", { name: /origin\/orphan/ })).toBeVisible();
809 await userEvent.keyboard("{Enter}");
810 await expect.element(searchInput).not.toBeInTheDocument();
811 const key = scopedThreadKey(context.threadRef);
812 await vi.waitFor(() => {
813 expect(useDiffPanelStore.getState().byThreadKey[key]).toEqual({
814 kind: "branch",
815 baseRef: "origin/orphan",
816 });
817 expect(useDiffPanelStore.getState().branchBaseRefByThreadKey[key]).toBe("origin/orphan");
818 });
819});
820​
821it("hides the Turn submenu in the diff scope menu until a turn completes", async () => {
822 using context = setup("origin/orphan");
823 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
824 await using screen = await render(
825 <RegistryContext.Provider value={context.registry}>
826 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
827 </RegistryContext.Provider>,
828 );
829​
830 const scopeButton = screen.getByRole("button", { name: "Diff scope: Changes" });
831 await userEvent.click(scopeButton);
832 await expect
833 .element(page.getByRole("menuitemradio", { name: "Changes", exact: true }))
834 .toBeVisible();
835 await expect
836 .element(page.getByRole("menuitemradio", { name: "Latest turn", exact: true }))
837 .toBeVisible();
838 await expect
839 .element(page.getByRole("menuitem", { name: "Turn", exact: true }))
840 .not.toBeInTheDocument();
841​
842 await userEvent.keyboard("{Escape}");
843 state.checkpoints = [
844 {
845 runId: RunId.make("run-1"),
846 checkpointTurnCount: 1,
847 checkpointRef: CheckpointRef.make("refs/t3/root-1"),
848 status: "ready",
849 files: [],
850 assistantMessageId: null,
851 completedAt: "2026-01-01T00:00:00Z",
852 },
853 ];
854 await screen.rerender(
855 <RegistryContext.Provider value={context.registry}>
856 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
857 </RegistryContext.Provider>,
858 );
859​
860 await userEvent.click(scopeButton);
861 await expect.element(page.getByRole("menuitem", { name: "Turn", exact: true })).toBeVisible();
862});