Open History to see the last commit
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 };
174}
175
176function setup(failedBaseRef: string | null) {
177 const reset = () => {
178 useDiffPanelStore.setState({
179 byThreadKey: {},
180 branchBaseRefByThreadKey: {},
181 gitRepositoryPathByThreadKey: {},
182 });
183 useDiffPanelSessionStore.setState({
184 collapsedFileKeysByScopeKey: {},
185 knownFileKeysByScopeKey: {},
186 });
187 useRightPanelStore.setState({ byThreadKey: {}, threadPanelVisibilityByThreadKey: {} });
188 useComposerDraftStore.setState({
189 draftsByThreadKey: {},
190 draftThreadsByThreadKey: {},
191 logicalProjectDraftThreadKeyByLogicalProjectKey: {},
192 });
193 };
194 reset();
195 state.diffFilesCollapsed = false;
196 state.project = { workspaceRoot: "/project", repositoryIdentity: null };
197 state.statusByCwd.clear();
198 state.taskFolder = null;
199 state.toolCallItem = null;
200 state.checkpoints = [];
201 state.checkpointDiff = null;
202 state.editorOpens = [];
203 const patch = Atom.make<AsyncResult.AsyncResult<ReviewDiffPreviewSource, Error>>(
204 AsyncResult.initial(),
205 );
206 state.patch = patch;
207 state.threadRef = {
208 environmentId: EnvironmentId.make("environment"),
209 threadId: ThreadId.make("thread"),
210 };
211 state.thread = makeThreadFixture({
212 ...state.threadRef,
213 id: state.threadRef.threadId,
214 projectId: ProjectId.make("project"),
215 branch: "dev",
216 worktreePath: cwd,
217 });
218 state.previews.clear();
219 state.previews.set(null, Atom.make(AsyncResult.success(preview())));
220 state.previews.set("main", Atom.make(AsyncResult.success(preview())));
221 state.previews.set(failedBaseRef, Atom.make(AsyncResult.fail(new Error(errorMessage))));
222 state.config = Atom.make(null);
223 state.status = Atom.make(
224 AsyncResult.success({
225 isRepo: true,
226 hasPrimaryRemote: true,
227 isDefaultRef: false,
228 refName: "dev",
229 hasWorkingTreeChanges: false,
230 workingTree: { rootPath: cwd, files: [], insertions: 0, deletions: 0 },
231 hasUpstream: true,
232 aheadCount: 0,
233 behindCount: 0,
234 pr: null,
235 }),
236 );
237 const refs = (names: string[], isRemote: boolean): VcsListRefsResult => ({
238 isRepo: true,
239 hasPrimaryRemote: true,
240 nextCursor: null,
241 totalCount: names.length,
242 refs: names.map((name) => ({
243 name,
244 isRemote,
245 ...(isRemote ? { remoteName: "origin" } : {}),
246 current: name === "dev",
247 isDefault: name === "main",
248 worktreePath: null,
249 })),
250 });
251 state.localRefs = Atom.make(AsyncResult.success(refs(["dev", "main"], false)));
252 state.remoteRefs = Atom.make(AsyncResult.success(refs(["origin/orphan"], true)));
253 state.commits = Atom.make(AsyncResult.success({ commits: [], truncated: false }));
254 useDiffPanelStore.getState().selectBranchBaseRef(state.threadRef, failedBaseRef);
255 const registry = AtomRegistry.make();
256 return {
257 registry,
258 patch,
259 threadRef: state.threadRef,
260 [Symbol.dispose]() {
261 registry.dispose();
262 reset();
263 },
264 };
265}
266
267it.each([
268 {
269 name: "a saved unrelated branch",
270 failedBaseRef: "origin/orphan",
271 recovery: "Automatic",
272 baseRef: null,
273 },
274 {
275 name: "an automatic base with unrelated history",
276 failedBaseRef: null,
277 recovery: "main",
278 baseRef: "main",
279 },
280])(
281 "recovers from $name without leaving the diff panel",
282 async ({ failedBaseRef, recovery, baseRef }) => {
283 using context = setup(failedBaseRef);
284 await using screen = await render(
285 <RegistryContext.Provider value={context.registry}>
286 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
287 </RegistryContext.Provider>,
288 );
289 await expect.element(screen.getByText(errorMessage, { exact: true })).toBeVisible();
290 const selector = screen.getByRole("combobox", { name: /Change comparison target/ });
291 await vi.waitFor(() => expect(selector.query()).not.toBeNull());
292 await userEvent.click(selector);
293 await expect.element(page.getByRole("option", { name: "main", exact: true })).toBeVisible();
294 await userEvent.click(page.getByRole("option", { name: recovery, exact: true }));
295 await expect.element(screen.getByText("No net changes in this selection.")).toBeVisible();
296 await expect.element(screen.getByText(errorMessage, { exact: true })).not.toBeInTheDocument();
297 const key = scopedThreadKey(context.threadRef);
298 await vi.waitFor(() => {
299 expect(useDiffPanelStore.getState().byThreadKey[key]).toEqual({ kind: "branch", baseRef });
300 expect(useDiffPanelStore.getState().branchBaseRefByThreadKey[key]).toBe(baseRef);
301 });
302 },
303);
304
305it("opens a repository-relative file from a nested project without a remote", async () => {
306 using context = setup("origin/orphan");
307 state.thread = { ...state.thread!, worktreePath: null };
308 const path = "project/back\\slash.txt";
309 const metadata = preview();
310 const source = {
311 ...metadata.sources[0]!,
312 files: [{ path, previousPath: null, additions: 1, deletions: 0 }],
313 };
314 state.previews.set("main", Atom.make(AsyncResult.success({ ...metadata, sources: [source] })));
315 state.status = Atom.make(
316 AsyncResult.success({
317 ...AsyncResult.getOrElse(context.registry.get(state.status), () => {
318 throw new Error("Missing status");
319 }),
320 workingTree: { rootPath: "/", files: [], insertions: 0, deletions: 0 },
321 }),
322 );
323 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
324 await using screen = await render(
325 <RegistryContext.Provider value={context.registry}>
326 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
327 </RegistryContext.Provider>,
328 );
329 await userEvent.click(screen.getByText(path, { exact: true }));
330 expect(
331 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, context.threadRef),
332 ).toMatchObject({ activeSurfaceId: "file:back\\slash.txt" });
333});
334
335// The file panel reads below the thread's folder; anything else goes to the editor.
336it.each([
337 { repository: `${cwd}/api`, surface: "file:api/notes.txt" },
338 { repository: `${cwd}/~`, surface: null },
339 { repository: `${cwd}/api\\..`, surface: null },
340 { repository: `${cwd}/a:repo`, surface: null },
341 { repository: "/elsewhere/api", surface: null },
342])("opens a selected repository's changed file at $repository", async ({ repository, surface }) => {
343 using context = setup(null);
344 const path = "notes.txt";
345 const metadata = preview();
346 const source = {
347 ...metadata.sources[0]!,
348 kind: "working-tree" as const,
349 files: [{ path, previousPath: null, additions: 1, deletions: 0 }],
350 };
351 state.previews.set(null, Atom.make(AsyncResult.success({ ...metadata, sources: [source] })));
352 const threadFolderStatus = AsyncResult.getOrThrow(context.registry.get(state.status));
353 state.status = Atom.make(AsyncResult.success({ ...threadFolderStatus, isRepo: false }));
354 state.project = { ...state.project, trackedFolders: [{}] };
355 state.taskFolder = Atom.make(
356 AsyncResult.success({
357 taskFolder: {
358 root: cwd,
359 repositories: [{ repositoryPath: repository, name: "api", worktreePath: repository }],
360 },
361 }),
362 );
363 useDiffPanelStore.getState().selectGitScope(context.threadRef, "unstaged");
364 await using screen = await render(
365 <RegistryContext.Provider value={context.registry}>
366 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
367 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
368 </div>
369 </RegistryContext.Provider>,
370 );
371 await userEvent.click(screen.getByText(path, { exact: true }));
372 const { activeSurfaceId } = selectThreadRightPanelState(
373 useRightPanelStore.getState().byThreadKey,
374 context.threadRef,
375 );
376 expect(activeSurfaceId?.startsWith("file:") ? activeSurfaceId : null).toBe(surface);
377 expect(state.editorOpens).toEqual(surface === null ? [`${repository}/${path}`] : []);
378});
379
380// A repository the picker selects in a plain task folder has a status of its own.
381it.each([
382 { checkout: "the thread folder", repository: null },
383 { checkout: "a selected repository", repository: `${cwd}/api` },
384])("rereads the Uncommitted list after the Git menu commits $checkout", async ({ repository }) => {
385 using context = setup(null);
386 const path = "committed.txt";
387 const metadata = preview();
388 const source = {
389 ...metadata.sources[0]!,
390 kind: "working-tree" as const,
391 files: [{ path, previousPath: null, additions: 1, deletions: 0 }],
392 };
393 let reads = 0;
394 state.previews.set(
395 null,
396 Atom.readable(() => {
397 reads += 1;
398 return AsyncResult.success({ ...metadata, sources: [source] });
399 }),
400 );
401 const dirty = (insertions: number) =>
402 AsyncResult.success({
403 isRepo: true,
404 hasPrimaryRemote: true,
405 isDefaultRef: false,
406 refName: "dev",
407 hasWorkingTreeChanges: insertions > 0,
408 workingTree: { rootPath: cwd, files: [], insertions, deletions: 0 },
409 hasUpstream: true,
410 aheadCount: 0,
411 behindCount: 0,
412 pr: null,
413 });
414 const status = Atom.make(dirty(1));
415 if (repository === null) {
416 state.status = status;
417 } else {
418 state.status = Atom.make(
419 AsyncResult.success({
420 ...AsyncResult.getOrThrow(dirty(0)),
421 isRepo: false,
422 refName: null,
423 workingTree: { files: [], insertions: 0, deletions: 0 },
424 }),
425 );
426 state.statusByCwd.set(repository, status);
427 state.project = { ...state.project, trackedFolders: [{}] };
428 state.taskFolder = Atom.make(
429 AsyncResult.success({
430 taskFolder: {
431 root: cwd,
432 repositories: [{ repositoryPath: repository, name: "api", worktreePath: repository }],
433 },
434 }),
435 );
436 }
437 useDiffPanelStore.getState().selectGitScope(context.threadRef, "unstaged");
438 await using screen = await render(
439 <RegistryContext.Provider value={context.registry}>
440 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
441 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
442 </div>
443 </RegistryContext.Provider>,
444 );
445 await expect.element(screen.getByText(path, { exact: true })).toBeVisible();
446 const readsBeforeCommit = reads;
447 // The commit leaves nothing uncommitted, and status says so.
448 context.registry.set(status, dirty(0));
449 await vi.waitFor(() => expect(reads).toBeGreaterThan(readsBeforeCommit));
450});
451
452it("explains a branch diff whose only changes are hidden test files", async () => {
453 using context = setup("origin/orphan");
454 using _hideTestFiles = {
455 [Symbol.dispose]() {
456 window.localStorage.removeItem("t3code.diffHideTestFiles");
457 },
458 };
459 const path = "math.test.ts";
460 const metadata = preview();
461 const source = {
462 ...metadata.sources[0]!,
463 files: [{ path, previousPath: null, additions: 1, deletions: 0 }],
464 };
465 state.previews.set("main", Atom.make(AsyncResult.success({ ...metadata, sources: [source] })));
466 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
467 await using screen = await render(
468 <RegistryContext.Provider value={context.registry}>
469 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
470 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
471 </div>
472 </RegistryContext.Provider>,
473 );
474 await expect.element(screen.getByText(path, { exact: true })).toBeVisible();
475 await userEvent.click(screen.getByRole("button", { name: "Hide test files", exact: true }));
476 await expect.element(screen.getByText(path, { exact: true })).not.toBeInTheDocument();
477 await expect.element(screen.getByText("1 test file hidden", { exact: true })).toBeVisible();
478 await userEvent.click(screen.getByRole("button", { name: "Show test files", exact: true }));
479 await expect.element(screen.getByText(path, { exact: true })).toBeVisible();
480});
481
482it.each([false, true])(
483 "expands an unloaded file on the first click with default collapse %s",
484 async (collapsed) => {
485 using context = setup("origin/orphan");
486 state.diffFilesCollapsed = collapsed;
487 const path = `pending-${collapsed}.txt`;
488 const metadata = preview();
489 const source = {
490 ...metadata.sources[0]!,
491 files: [{ path, previousPath: null, additions: 1, deletions: 1 }],
492 };
493 state.previews.set("main", Atom.make(AsyncResult.success({ ...metadata, sources: [source] })));
494 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
495 await using screen = await render(
496 <RegistryContext.Provider value={context.registry}>
497 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
498 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
499 </div>
500 </RegistryContext.Provider>,
501 );
502 const toggle = screen.getByRole("button", { name: `Expand ${path}`, exact: true });
503 await expect.element(toggle).toHaveAttribute("aria-expanded", "false");
504 await userEvent.click(toggle);
505 await act(() =>
506 context.registry.set(
507 context.patch,
508 AsyncResult.success({
509 ...source,
510 diff: `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-before\n+after\n`,
511 }),
512 ),
513 );
514 const loadedToggle = screen.getByRole("button", { name: `Collapse ${path}`, exact: true });
515 await expect.element(loadedToggle).toHaveAttribute("aria-expanded", "true");
516 await expect.element(screen.getByText("after", { exact: true })).toBeVisible();
517 await userEvent.click(loadedToggle);
518 await expect.element(toggle).toHaveAttribute("aria-expanded", "false");
519 },
520);
521
522it("keeps a file that appears later collapsed after another one was expanded", async () => {
523 using context = setup("origin/orphan");
524 state.diffFilesCollapsed = true;
525 const metadata = preview();
526 const stat = (path: string) => ({ path, previousPath: null, additions: 1, deletions: 1 });
527 const diff = (path: string) =>
528 `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-before\n+after\n`;
529 const source = { ...metadata.sources[0]!, files: [stat("first.txt")], diff: diff("first.txt") };
530 const previewAtom = Atom.make(
531 AsyncResult.success({ ...metadata, sources: [{ ...source, patchesDeferred: false }] }),
532 );
533 state.previews.set("main", previewAtom);
534 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
535 await using screen = await render(
536 <RegistryContext.Provider value={context.registry}>
537 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
538 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
539 </div>
540 </RegistryContext.Provider>,
541 );
542 await userEvent.click(screen.getByRole("button", { name: "Expand first.txt", exact: true }));
543 await act(() =>
544 context.registry.set(
545 previewAtom,
546 AsyncResult.success({
547 ...metadata,
548 sources: [
549 {
550 ...source,
551 patchesDeferred: false,
552 files: [stat("first.txt"), stat("second.txt")],
553 diff: diff("first.txt") + diff("second.txt"),
554 },
555 ],
556 }),
557 ),
558 );
559 await expect
560 .element(screen.getByRole("button", { name: "Expand second.txt", exact: true }))
561 .toHaveAttribute("aria-expanded", "false");
562});
563
564it.each([
565 { label: "an existing thread", draft: false, path: "changed.png" },
566 { label: "a new thread", draft: true, path: "draft-changed.png" },
567])("previews a changed image on $label when its file row is expanded", async ({ draft, path }) => {
568 using context = setup("origin/orphan");
569 let composerDraftTarget: ScopedThreadRef | DraftId = context.threadRef;
570 if (draft) {
571 state.threadRef = null;
572 state.thread = null;
573 const draftId = DraftId.make("draft-image-preview");
574 useComposerDraftStore
575 .getState()
576 .setProjectDraftThreadId(
577 scopeProjectRef(context.threadRef.environmentId, ProjectId.make("project")),
578 draftId,
579 { threadId: context.threadRef.threadId, worktreePath: cwd },
580 );
581 composerDraftTarget = draftId;
582 }
583 const metadata = preview();
584 const source = {
585 ...metadata.sources[0]!,
586 files: [{ path, previousPath: null, additions: 0, deletions: 0 }],
587 };
588 const previewAtom = Atom.make(
589 AsyncResult.success({ ...metadata, sources: [source] }, { timestamp: 1 }),
590 );
591 state.previews.set("main", previewAtom);
592 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
593 await using screen = await render(
594 <RegistryContext.Provider value={context.registry}>
595 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
596 <DiffPanel composerDraftTarget={composerDraftTarget} workspaceMutationId={null} visible />
597 </div>
598 </RegistryContext.Provider>,
599 );
600 await userEvent.click(screen.getByRole("button", { name: `Expand ${path}`, exact: true }));
601 await act(() =>
602 context.registry.set(
603 context.patch,
604 AsyncResult.success({
605 ...source,
606 diff: `diff --git a/${path} b/${path}\nindex 19fc4a5..fd0af9e 100644\nBinary files a/${path} and b/${path} differ\n`,
607 }),
608 ),
609 );
610 await expect
611 .element(screen.getByRole("button", { name: `Collapse ${path}`, exact: true }))
612 .toHaveAttribute("aria-expanded", "true");
613 const image = screen.getByRole("img", { name: path });
614 await expect.element(image).toBeVisible();
615 const firstSrc = image.element().getAttribute("src") ?? "";
616
617 // Replacing a binary file keeps the diff metadata identical; a refetch must still re-read it.
618 await act(() =>
619 context.registry.set(
620 previewAtom,
621 AsyncResult.success({ ...metadata, sources: [source] }, { timestamp: 2 }),
622 ),
623 );
624 await expect.element(image).not.toHaveAttribute("src", firstSrc);
625});
626
627it("says a turn diff cut off at the server's size limit is incomplete", async () => {
628 using context = setup("origin/orphan");
629 state.checkpoints = [
630 {
631 runId: "run",
632 checkpointTurnCount: 1,
633 checkpointRef: "ref",
634 status: "ready",
635 files: [],
636 assistantMessageId: null,
637 completedAt: "2026-01-01T00:00:00Z",
638 },
639 ];
640 state.checkpointDiff = {
641 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]",
642 };
643 useDiffPanelStore.getState().selectTurn(context.threadRef, RunId.make("run"));
644 await using screen = await render(
645 <RegistryContext.Provider value={context.registry}>
646 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
647 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
648 </div>
649 </RegistryContext.Provider>,
650 );
651 await expect.element(screen.getByText("first.txt", { exact: true }).first()).toBeVisible();
652 await expect
653 .element(screen.getByText("This preview exceeds the size limit. Changes shown are incomplete."))
654 .toBeVisible();
655});
656
657it("shows a turn's repositories in a folder that is not a Git repository", async () => {
658 using context = setup("origin/orphan");
659 state.status = Atom.make(
660 AsyncResult.success({
661 isRepo: false,
662 hasPrimaryRemote: false,
663 isDefaultRef: false,
664 refName: null,
665 hasWorkingTreeChanges: false,
666 workingTree: { files: [], insertions: 0, deletions: 0 },
667 hasUpstream: false,
668 aheadCount: 0,
669 behindCount: 0,
670 pr: null,
671 }),
672 );
673 const patch = (path: string) =>
674 `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-before\n+after\n`;
675 const repository = (name: string) => ({
676 scopeId: CheckpointScopeId.make(`scope-${name}`),
677 name,
678 repositoryPath: `${cwd}/${name}`,
679 cwd: `${cwd}/${name}`,
680 relativePath: name,
681 files: [{ path: "README.md", kind: "modified", additions: 1, deletions: 1 }],
682 baselineMissing: false,
683 });
684 state.checkpoints = [
685 {
686 runId: RunId.make("run-1"),
687 checkpointTurnCount: 1,
688 checkpointRef: CheckpointRef.make("refs/t3/root-1"),
689 status: "missing",
690 files: [],
691 repositories: [repository("api"), repository("web")],
692 assistantMessageId: null,
693 completedAt: "2026-11-10T00:00:00.000Z",
694 },
695 ];
696 state.checkpointDiff = {
697 threadId: context.threadRef.threadId,
698 fromTurnCount: 0,
699 toTurnCount: 1,
700 diff: "",
701 repositories: ["api", "web"].map((name) => ({
702 name,
703 repositoryPath: `${cwd}/${name}`,
704 relativePath: name,
705 diff: patch("README.md"),
706 })),
707 };
708 await using screen = await render(
709 <RegistryContext.Provider value={context.registry}>
710 <div style={{ height: 600, width: 390, display: "flex", flexDirection: "column" }}>
711 <DiffPanel
712 mode="embedded"
713 composerDraftTarget={context.threadRef}
714 workspaceMutationId={null}
715 visible
716 />
717 </div>
718 </RegistryContext.Provider>,
719 );
720 const api = screen.getByRole("button", { name: "Collapse api/README.md", exact: true });
721 const web = screen.getByRole("button", { name: "Collapse web/README.md", exact: true });
722 await expect.element(api).toBeVisible();
723 await expect.element(web).toBeVisible();
724 // Both pickers keep their labels in a phone-width panel.
725 await expect.element(screen.getByText("Latest turn", { exact: true })).toBeVisible();
726 const picker = screen.getByRole("button", { name: "Repository: All repositories" });
727 await expect.element(picker.getByText("All repositories")).toBeVisible();
728 await userEvent.click(picker);
729 await userEvent.click(page.getByRole("menuitemradio", { name: "web" }));
730 await expect.element(web).toBeVisible();
731 await expect.element(api).not.toBeInTheDocument();
732});
733
734// Paths as git's numstat reports them; the parsed patch keeps their edge whitespace.
735it.each([
736 { path: " leading.ts", name: " leading.ts" },
737 { path: "src/trailing.ts ", name: "src/trailing.ts " },
738])("reveals the turn file $path picked from the changed files", async ({ path, name }) => {
739 using context = setup("origin/orphan");
740 state.diffFilesCollapsed = true;
741 state.checkpoints = [
742 {
743 runId: "run",
744 checkpointTurnCount: 1,
745 checkpointRef: "ref",
746 status: "ready",
747 files: [],
748 assistantMessageId: null,
749 completedAt: "2026-01-01T00:00:00Z",
750 },
751 ];
752 state.checkpointDiff = {
753 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`,
754 };
755 useDiffPanelStore.getState().selectTurn(context.threadRef, RunId.make("run"), path);
756 await using screen = await render(
757 <RegistryContext.Provider value={context.registry}>
758 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
759 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
760 </div>
761 </RegistryContext.Provider>,
762 );
763 await expect
764 .element(screen.getByRole("button", { name: `Collapse ${name}`, exact: true }))
765 .toHaveAttribute("aria-expanded", "true");
766});
767
768it("opens a tool call diff expanded and uses the path its agent recorded", async () => {
769 using context = setup("origin/orphan");
770 state.diffFilesCollapsed = true;
771 // A local thread in a project that is the repository's apps/web folder.
772 state.thread = { ...state.thread!, worktreePath: null };
773 state.project = { workspaceRoot: "/repo/apps/web", repositoryIdentity: { rootPath: "/repo" } };
774 const status = AsyncResult.getOrThrow(context.registry.get(state.status));
775 state.status = Atom.make(
776 AsyncResult.success({ ...status, workingTree: { ...status.workingTree, rootPath: "/repo" } }),
777 );
778 // Claude's Edit can record a path relative to the workspace, unlike the repository's diffs.
779 state.toolCallItem = {
780 type: "file_change",
781 fileName: "src/a.ts",
782 diffStr: "--- src/a.ts\n+++ src/a.ts\n@@ -1 +1 @@\n-before\n+after\n",
783 };
784 useDiffPanelStore.getState().selectToolCall(context.threadRef, {
785 threadId: context.threadRef.threadId,
786 itemId: TurnItemId.make("edit"),
787 revision: "1",
788 });
789 await using screen = await render(
790 <RegistryContext.Provider value={context.registry}>
791 <div className="flex h-[600px] flex-col">
792 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
793 </div>
794 </RegistryContext.Provider>,
795 );
796 await expect
797 .element(screen.getByRole("button", { name: "Collapse src/a.ts", exact: true }))
798 .toHaveAttribute("aria-expanded", "true");
799 await userEvent.click(screen.getByText("src/a.ts", { exact: true }));
800 await vi.waitFor(() =>
801 expect(
802 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, context.threadRef),
803 ).toMatchObject({ activeSurfaceId: "file:src/a.ts" }),
804 );
805});
806
807it("filters base-ref dropdown rows against the search query", async () => {
808 using context = setup("origin/orphan");
809 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
810 await using screen = await render(
811 <RegistryContext.Provider value={context.registry}>
812 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
813 </RegistryContext.Provider>,
814 );
815 await userEvent.click(screen.getByRole("combobox", { name: /Change comparison target/ }));
816 const searchInput = page.getByPlaceholder("Search refs...");
817 const automaticOption = page.getByRole("option", { name: "Automatic", exact: true });
818 const mainOption = page.getByRole("option", { name: "main", exact: true });
819 const remoteOption = page.getByRole("option", { name: /origin\/orphan/ });
820
821 await expect.element(automaticOption).toBeVisible();
822 await expect.element(mainOption).toBeVisible();
823 await expect.element(remoteOption).toBeVisible();
824
825 await userEvent.fill(searchInput, "zzz-no-match");
826 await expect.element(page.getByText("No matching refs.", { exact: true })).toBeVisible();
827 await expect.element(automaticOption).not.toBeInTheDocument();
828 await expect.element(mainOption).not.toBeInTheDocument();
829 await expect.element(remoteOption).not.toBeInTheDocument();
830
831 await userEvent.fill(searchInput, "main");
832 await expect.element(mainOption).toBeVisible();
833 await expect.element(automaticOption).not.toBeInTheDocument();
834 await expect.element(remoteOption).not.toBeInTheDocument();
835
836 await userEvent.clear(searchInput);
837 await expect.element(automaticOption).toBeVisible();
838 await expect.element(mainOption).toBeVisible();
839 await expect.element(remoteOption).toBeVisible();
840});
841
842it("selects the first matching base ref on Enter after searching", async () => {
843 using context = setup("origin/orphan");
844 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
845 await using screen = await render(
846 <RegistryContext.Provider value={context.registry}>
847 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
848 </RegistryContext.Provider>,
849 );
850 await userEvent.click(screen.getByRole("combobox", { name: /Change comparison target/ }));
851 const searchInput = page.getByPlaceholder("Search refs...");
852 await userEvent.type(searchInput, "orphan");
853 await expect.element(page.getByRole("option", { name: /origin\/orphan/ })).toBeVisible();
854 await userEvent.keyboard("{Enter}");
855 await expect.element(searchInput).not.toBeInTheDocument();
856 const key = scopedThreadKey(context.threadRef);
857 await vi.waitFor(() => {
858 expect(useDiffPanelStore.getState().byThreadKey[key]).toEqual({
859 kind: "branch",
860 baseRef: "origin/orphan",
861 });
862 expect(useDiffPanelStore.getState().branchBaseRefByThreadKey[key]).toBe("origin/orphan");
863 });
864});
865
866it("hides the Turn submenu in the diff scope menu until a turn completes", async () => {
867 using context = setup("origin/orphan");
868 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
869 await using screen = await render(
870 <RegistryContext.Provider value={context.registry}>
871 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
872 </RegistryContext.Provider>,
873 );
874
875 const scopeButton = screen.getByRole("button", { name: "Diff scope: Changes" });
876 await userEvent.click(scopeButton);
877 await expect
878 .element(page.getByRole("menuitemradio", { name: "Changes", exact: true }))
879 .toBeVisible();
880 await expect
881 .element(page.getByRole("menuitemradio", { name: "Latest turn", exact: true }))
882 .toBeVisible();
883 await expect
884 .element(page.getByRole("menuitem", { name: "Turn", exact: true }))
885 .not.toBeInTheDocument();
886
887 await userEvent.keyboard("{Escape}");
888 state.checkpoints = [
889 {
890 runId: RunId.make("run-1"),
891 checkpointTurnCount: 1,
892 checkpointRef: CheckpointRef.make("refs/t3/root-1"),
893 status: "ready",
894 files: [],
895 assistantMessageId: null,
896 completedAt: "2026-01-01T00:00:00Z",
897 },
898 ];
899 await screen.rerender(
900 <RegistryContext.Provider value={context.registry}>
901 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
902 </RegistryContext.Provider>,
903 );
904
905 await userEvent.click(scopeButton);
906 await expect.element(page.getByRole("menuitem", { name: "Turn", exact: true })).toBeVisible();
907});