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

DiffPanel.browser.test.tsx

499 lines18.6 KB

1import { RegistryContext } from "@effect/atom-react";
2import { 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 ClientSettings,
13 type OrchestrationGetTurnDiffResult,
14 type ReviewBranchCommitsResult,
15 type ReviewDiffPreviewResult,
16 type ReviewDiffPreviewSource,
17 type ScopedThreadRef,
18 type VcsListRefsResult,
19 type VcsStatusResult,
20} from "@t3tools/contracts";
21import * as DateTime from "effect/DateTime";
22import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
23import { expect, it, vi } from "vite-plus/test";
24import { page, userEvent } from "vite-plus/test/browser";
25​
26import "~/index.css";
27import { act, render } from "../../test/render";
28import { makeThreadFixture } from "~/test-fixtures";
29​
30type ResultAtom<A> = Atom.Atom<AsyncResult.AsyncResult<A, Error>>;
31​
32const state = vi.hoisted(() => ({
33 thread: null as ReturnType<typeof makeThreadFixture> | null,
34 threadRef: null as ScopedThreadRef | null,
35 previews: new Map<string | null, ResultAtom<ReviewDiffPreviewResult>>(),
36 patch: null as unknown as ResultAtom<ReviewDiffPreviewSource>,
37 diffFilesCollapsed: false,
38 project: {
39 workspaceRoot: "/project",
40 repositoryIdentity: null as { rootPath: string } | null,
41 },
42 toolCallItem: null as unknown,
43 config: null as unknown as Atom.Atom<null>,
44 status: null as unknown as ResultAtom<VcsStatusResult>,
45 localRefs: null as unknown as ResultAtom<VcsListRefsResult>,
46 remoteRefs: null as unknown as ResultAtom<VcsListRefsResult>,
47 commits: null as unknown as ResultAtom<ReviewBranchCommitsResult>,
48 checkpoints: [] as unknown[],
49 checkpointDiff: null as Partial<OrchestrationGetTurnDiffResult> | null,
50}));
51​
52vi.mock("~/state/server", () => ({
53 serverEnvironment: { configValueAtom: () => state.config },
54}));
55vi.mock("~/state/review", () => ({
56 reviewEnvironment: {
57 diffPreview: ({ input }: { input: { baseRef?: string } }) =>
58 state.previews.get(input.baseRef ?? null)!,
59 branchCommits: () => state.commits,
60 diffFilePatch: () => state.patch,
61 diffFileContents: {},
62 },
63}));
64vi.mock("~/state/vcs", () => ({
65 vcsEnvironment: {
66 status: () => state.status,
67 listRefs: ({ input }: { input: { refKind: "local" | "remote" } }) =>
68 input.refKind === "local" ? state.localRefs : state.remoteRefs,
69 },
70}));
71vi.mock("~/state/entities", () => ({
72 useQuietThreadShell: () => state.thread,
73 useProject: () => state.project,
74 useThreadCheckpointSummaries: () => state.checkpoints,
75 useQuietThreadVisibleTurnItems: () => [],
76 useQuietThreadProjection: () => null,
77}));
78vi.mock("~/state/filesystem", () => ({
79 useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }),
80 filesystemEnvironment: {},
81}));
82vi.mock("~/hooks/useThreadRouteTarget", () => ({ useThreadRouteRef: () => state.threadRef }));
83vi.mock("~/hooks/useSettings", () => ({
84 useClientSettings: (select: (settings: ClientSettings) => unknown) =>
85 select({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: state.diffFilesCollapsed }),
86 updateClientSettings: async () => {},
87}));
88vi.mock("~/hooks/useTheme", () => ({
89 useRenderedAppearance: () => "dark",
90 getRenderedAppearance: () => "dark",
91 subscribeRenderedAppearance: () => () => {},
92}));
93vi.mock("~/state/queries", () => ({
94 useCheckpointDiff: () => ({ data: state.checkpointDiff, error: null, isPending: false }),
95 useTurnItemDetail: () => ({
96 data: state.toolCallItem ? { item: state.toolCallItem } : null,
97 error: null,
98 isPending: false,
99 }),
100 useDebouncedValue: <A,>(value: A) => value,
101}));
102vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => async () => {} }));
103vi.mock("~/editorPreferences", () => ({ useOpenInPreferredEditor: () => async () => {} }));
104vi.mock("~/fileContextMenu", () => ({ useFileContextMenuHandler: () => () => {} }));
105vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => async () => {} }));
106vi.mock("./diffs/DiffCommentAnnotation", () => ({ DiffCommentAnnotation: () => null }));
107vi.mock("./diffs/DiffFileTree", () => ({ DiffFileTree: () => null }));
108vi.mock("./DiffFilePathCopyButton", () => ({ DiffFilePathCopyButton: () => null }));
109​
110import DiffPanel from "./DiffPanel";
111import { useDiffPanelSessionStore, useDiffPanelStore } from "~/diffPanelStore";
112import { selectThreadRightPanelState, useRightPanelStore } from "~/rightPanelStore";
113​
114const cwd = "/project-worktree";
115const errorMessage = "Could not find a common commit between 'origin/orphan' and HEAD.";
116​
117function preview(): ReviewDiffPreviewResult {
118 return {
119 cwd,
120 generatedAt: DateTime.makeUnsafe("2026-10-30T00:00:00Z"),
121 sources: [
122 {
123 id: "branch",
124 kind: "branch-range",
125 title: "Changes",
126 baseRef: "main",
127 headRef: "dev",
128 diff: "",
129 diffHash: "empty",
130 truncated: false,
131 patchesDeferred: true,
132 files: [],
133 },
134 ],
135 };
137​
138function setup(failedBaseRef: string | null) {
139 const reset = () => {
140 useDiffPanelStore.setState({
141 byThreadKey: {},
142 branchBaseRefByThreadKey: {},
143 });
144 useDiffPanelSessionStore.setState({ collapsedFileKeysByScopeKey: {} });
145 useRightPanelStore.setState({ byThreadKey: {}, threadPanelVisibilityByThreadKey: {} });
146 };
147 reset();
148 state.diffFilesCollapsed = false;
149 state.project = { workspaceRoot: "/project", repositoryIdentity: null };
150 state.toolCallItem = null;
151 state.checkpoints = [];
152 state.checkpointDiff = null;
153 const patch = Atom.make<AsyncResult.AsyncResult<ReviewDiffPreviewSource, Error>>(
154 AsyncResult.initial(),
155 );
156 state.patch = patch;
157 state.threadRef = {
158 environmentId: EnvironmentId.make("environment"),
159 threadId: ThreadId.make("thread"),
160 };
161 state.thread = makeThreadFixture({
162 ...state.threadRef,
163 id: state.threadRef.threadId,
164 projectId: ProjectId.make("project"),
165 branch: "dev",
166 worktreePath: cwd,
167 });
168 state.previews.clear();
169 state.previews.set(null, Atom.make(AsyncResult.success(preview())));
170 state.previews.set("main", Atom.make(AsyncResult.success(preview())));
171 state.previews.set(failedBaseRef, Atom.make(AsyncResult.fail(new Error(errorMessage))));
172 state.config = Atom.make(null);
173 state.status = Atom.make(
174 AsyncResult.success({
175 isRepo: true,
176 hasPrimaryRemote: true,
177 isDefaultRef: false,
178 refName: "dev",
179 hasWorkingTreeChanges: false,
180 workingTree: { rootPath: cwd, files: [], insertions: 0, deletions: 0 },
181 hasUpstream: true,
182 aheadCount: 0,
183 behindCount: 0,
184 pr: null,
185 }),
186 );
187 const refs = (names: string[], isRemote: boolean): VcsListRefsResult => ({
188 isRepo: true,
189 hasPrimaryRemote: true,
190 nextCursor: null,
191 totalCount: names.length,
192 refs: names.map((name) => ({
193 name,
194 isRemote,
195 ...(isRemote ? { remoteName: "origin" } : {}),
196 current: name === "dev",
197 isDefault: name === "main",
198 worktreePath: null,
199 })),
200 });
201 state.localRefs = Atom.make(AsyncResult.success(refs(["dev", "main"], false)));
202 state.remoteRefs = Atom.make(AsyncResult.success(refs(["origin/orphan"], true)));
203 state.commits = Atom.make(AsyncResult.success({ commits: [], truncated: false }));
204 useDiffPanelStore.getState().selectBranchBaseRef(state.threadRef, failedBaseRef);
205 const registry = AtomRegistry.make();
206 return {
207 registry,
208 patch,
209 threadRef: state.threadRef,
210 [Symbol.dispose]() {
211 registry.dispose();
212 reset();
213 },
214 };
216​
217it.each([
218 {
219 name: "a saved unrelated branch",
220 failedBaseRef: "origin/orphan",
221 recovery: "Automatic",
222 baseRef: null,
223 },
224 {
225 name: "an automatic base with unrelated history",
226 failedBaseRef: null,
227 recovery: "main",
228 baseRef: "main",
229 },
230])(
231 "recovers from $name without leaving the diff panel",
232 async ({ failedBaseRef, recovery, baseRef }) => {
233 using context = setup(failedBaseRef);
234 await using screen = await render(
235 <RegistryContext.Provider value={context.registry}>
236 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
237 </RegistryContext.Provider>,
238 );
239 await expect.element(screen.getByText(errorMessage, { exact: true })).toBeVisible();
240 const selector = screen.getByRole("combobox", { name: /Change comparison target/ });
241 await vi.waitFor(() => expect(selector.query()).not.toBeNull());
242 await userEvent.click(selector);
243 await expect.element(page.getByRole("option", { name: "main", exact: true })).toBeVisible();
244 await userEvent.click(page.getByRole("option", { name: recovery, exact: true }));
245 await expect.element(screen.getByText("No net changes in this selection.")).toBeVisible();
246 await expect.element(screen.getByText(errorMessage, { exact: true })).not.toBeInTheDocument();
247 const key = scopedThreadKey(context.threadRef);
248 await vi.waitFor(() => {
249 expect(useDiffPanelStore.getState().byThreadKey[key]).toEqual({ kind: "branch", baseRef });
250 expect(useDiffPanelStore.getState().branchBaseRefByThreadKey[key]).toBe(baseRef);
251 });
252 },
253);
254​
255it("opens a repository-relative file from a nested project without a remote", async () => {
256 using context = setup("origin/orphan");
257 state.thread = { ...state.thread!, worktreePath: null };
258 const path = "project/back\\slash.txt";
259 const metadata = preview();
260 const source = {
261 ...metadata.sources[0]!,
262 files: [{ path, previousPath: null, additions: 1, deletions: 0 }],
263 };
264 state.previews.set("main", Atom.make(AsyncResult.success({ ...metadata, sources: [source] })));
265 state.status = Atom.make(
266 AsyncResult.success({
267 ...AsyncResult.getOrElse(context.registry.get(state.status), () => {
268 throw new Error("Missing status");
269 }),
270 workingTree: { rootPath: "/", files: [], insertions: 0, deletions: 0 },
271 }),
272 );
273 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
274 await using screen = await render(
275 <RegistryContext.Provider value={context.registry}>
276 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
277 </RegistryContext.Provider>,
278 );
279 await userEvent.click(screen.getByText(path, { exact: true }));
280 expect(
281 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, context.threadRef),
282 ).toMatchObject({ activeSurfaceId: "file:back\\slash.txt" });
283});
284​
285it.each([false, true])(
286 "expands an unloaded file on the first click with default collapse %s",
287 async (collapsed) => {
288 using context = setup("origin/orphan");
289 state.diffFilesCollapsed = collapsed;
290 const path = `pending-${collapsed}.txt`;
291 const metadata = preview();
292 const source = {
293 ...metadata.sources[0]!,
294 files: [{ path, previousPath: null, additions: 1, deletions: 1 }],
295 };
296 state.previews.set("main", Atom.make(AsyncResult.success({ ...metadata, sources: [source] })));
297 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
298 await using screen = await render(
299 <RegistryContext.Provider value={context.registry}>
300 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
301 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
302 </div>
303 </RegistryContext.Provider>,
304 );
305 const toggle = screen.getByRole("button", { name: `Expand ${path}`, exact: true });
306 await expect.element(toggle).toHaveAttribute("aria-expanded", "false");
307 await userEvent.click(toggle);
308 await act(() =>
309 context.registry.set(
310 context.patch,
311 AsyncResult.success({
312 ...source,
313 diff: `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-before\n+after\n`,
314 }),
315 ),
316 );
317 const loadedToggle = screen.getByRole("button", { name: `Collapse ${path}`, exact: true });
318 await expect.element(loadedToggle).toHaveAttribute("aria-expanded", "true");
319 await expect.element(screen.getByText("after", { exact: true })).toBeVisible();
320 await userEvent.click(loadedToggle);
321 await expect.element(toggle).toHaveAttribute("aria-expanded", "false");
322 },
323);
324​
325it("says a turn diff cut off at the server's size limit is incomplete", async () => {
326 using context = setup("origin/orphan");
327 state.checkpoints = [
328 {
329 runId: "run",
330 checkpointTurnCount: 1,
331 checkpointRef: "ref",
332 status: "ready",
333 files: [],
334 assistantMessageId: null,
335 completedAt: "2026-01-01T00:00:00Z",
336 },
337 ];
338 state.checkpointDiff = {
339 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]",
340 };
341 useDiffPanelStore.getState().selectTurn(context.threadRef, RunId.make("run"));
342 await using screen = await render(
343 <RegistryContext.Provider value={context.registry}>
344 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
345 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
346 </div>
347 </RegistryContext.Provider>,
348 );
349 await expect.element(screen.getByText("first.txt", { exact: true }).first()).toBeVisible();
350 await expect
351 .element(screen.getByText("This preview exceeds the size limit. Changes shown are incomplete."))
352 .toBeVisible();
353});
354​
355it("shows a turn's repositories in a folder that is not a Git repository", async () => {
356 using context = setup("origin/orphan");
357 state.status = Atom.make(
358 AsyncResult.success({
359 isRepo: false,
360 hasPrimaryRemote: false,
361 isDefaultRef: false,
362 refName: null,
363 hasWorkingTreeChanges: false,
364 workingTree: { files: [], insertions: 0, deletions: 0 },
365 hasUpstream: false,
366 aheadCount: 0,
367 behindCount: 0,
368 pr: null,
369 }),
370 );
371 const patch = (path: string) =>
372 `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-before\n+after\n`;
373 const repository = (name: string) => ({
374 scopeId: CheckpointScopeId.make(`scope-${name}`),
375 name,
376 repositoryPath: `${cwd}/${name}`,
377 cwd: `${cwd}/${name}`,
378 relativePath: name,
379 files: [{ path: "README.md", kind: "modified", additions: 1, deletions: 1 }],
380 baselineMissing: false,
381 });
382 state.checkpoints = [
383 {
384 runId: RunId.make("run-1"),
385 checkpointTurnCount: 1,
386 checkpointRef: CheckpointRef.make("refs/t3/root-1"),
387 status: "missing",
388 files: [],
389 repositories: [repository("api"), repository("web")],
390 assistantMessageId: null,
391 completedAt: "2026-11-10T00:00:00.000Z",
392 },
393 ];
394 state.checkpointDiff = {
395 threadId: context.threadRef.threadId,
396 fromTurnCount: 0,
397 toTurnCount: 1,
398 diff: "",
399 repositories: ["api", "web"].map((name) => ({
400 name,
401 repositoryPath: `${cwd}/${name}`,
402 relativePath: name,
403 diff: patch("README.md"),
404 })),
405 };
406 await using screen = await render(
407 <RegistryContext.Provider value={context.registry}>
408 <div style={{ height: 600, width: 390, display: "flex", flexDirection: "column" }}>
409 <DiffPanel
410 mode="embedded"
411 composerDraftTarget={context.threadRef}
412 workspaceMutationId={null}
413 visible
414 />
415 </div>
416 </RegistryContext.Provider>,
417 );
418 const api = screen.getByRole("button", { name: "Collapse api/README.md", exact: true });
419 const web = screen.getByRole("button", { name: "Collapse web/README.md", exact: true });
420 await expect.element(api).toBeVisible();
421 await expect.element(web).toBeVisible();
422 // Both pickers keep their labels in a phone-width panel.
423 await expect.element(screen.getByText("Latest turn", { exact: true })).toBeVisible();
424 const picker = screen.getByRole("button", { name: "Repository: All repositories" });
425 await expect.element(picker.getByText("All repositories")).toBeVisible();
426 await userEvent.click(picker);
427 await userEvent.click(page.getByRole("menuitemradio", { name: "web" }));
428 await expect.element(web).toBeVisible();
429 await expect.element(api).not.toBeInTheDocument();
430});
431​
432// Paths as git's numstat reports them; the parsed patch keeps their edge whitespace.
433it.each([
434 { path: " leading.ts", name: " leading.ts" },
435 { path: "src/trailing.ts ", name: "src/trailing.ts " },
436])("reveals the turn file $path picked from the changed files", async ({ path, name }) => {
437 using context = setup("origin/orphan");
438 state.diffFilesCollapsed = true;
439 state.checkpoints = [
440 {
441 runId: "run",
442 checkpointTurnCount: 1,
443 checkpointRef: "ref",
444 status: "ready",
445 files: [],
446 assistantMessageId: null,
447 completedAt: "2026-01-01T00:00:00Z",
448 },
449 ];
450 state.checkpointDiff = {
451 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`,
452 };
453 useDiffPanelStore.getState().selectTurn(context.threadRef, RunId.make("run"), path);
454 await using screen = await render(
455 <RegistryContext.Provider value={context.registry}>
456 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
457 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
458 </div>
459 </RegistryContext.Provider>,
460 );
461 await expect
462 .element(screen.getByRole("button", { name: `Collapse ${name}`, exact: true }))
463 .toHaveAttribute("aria-expanded", "true");
464});
465​
466it("opens a file from a tool call's diff by the path its agent recorded", async () => {
467 using context = setup("origin/orphan");
468 // A local thread in a project that is the repository's apps/web folder.
469 state.thread = { ...state.thread!, worktreePath: null };
470 state.project = { workspaceRoot: "/repo/apps/web", repositoryIdentity: { rootPath: "/repo" } };
471 const status = AsyncResult.getOrThrow(context.registry.get(state.status));
472 state.status = Atom.make(
473 AsyncResult.success({ ...status, workingTree: { ...status.workingTree, rootPath: "/repo" } }),
474 );
475 // Claude's Edit can record a path relative to the workspace, unlike the repository's diffs.
476 state.toolCallItem = {
477 type: "file_change",
478 fileName: "src/a.ts",
479 diffStr: "--- src/a.ts\n+++ src/a.ts\n@@ -1 +1 @@\n-before\n+after\n",
480 };
481 useDiffPanelStore.getState().selectToolCall(context.threadRef, {
482 threadId: context.threadRef.threadId,
483 itemId: TurnItemId.make("edit"),
484 revision: "1",
485 });
486 await using screen = await render(
487 <RegistryContext.Provider value={context.registry}>
488 <div className="flex h-[600px] flex-col">
489 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
490 </div>
491 </RegistryContext.Provider>,
492 );
493 await userEvent.click(screen.getByText("src/a.ts", { exact: true }));
494 await vi.waitFor(() =>
495 expect(
496 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, context.threadRef),
497 ).toMatchObject({ activeSurfaceId: "file:src/a.ts" }),
498 );
499});