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

DiffPanel.browser.test.tsx

370 lines14.0 KB

1import { RegistryContext } from "@effect/atom-react";
2import { scopedThreadKey } from "@t3tools/client-runtime/environment";
3import {
4 DEFAULT_CLIENT_SETTINGS,
5 EnvironmentId,
6 ProjectId,
7 RunId,
8 ThreadId,
9 type ClientSettings,
10 type ReviewBranchCommitsResult,
11 type ReviewDiffPreviewResult,
12 type ReviewDiffPreviewSource,
13 type ScopedThreadRef,
14 type VcsListRefsResult,
15 type VcsStatusResult,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
19import { expect, it, vi } from "vite-plus/test";
20import { page, userEvent } from "vite-plus/test/browser";
21​
22import "~/index.css";
23import { act, render } from "../../test/render";
24import { makeThreadFixture } from "~/test-fixtures";
25​
26type ResultAtom<A> = Atom.Atom<AsyncResult.AsyncResult<A, Error>>;
27​
28const state = vi.hoisted(() => ({
29 thread: null as ReturnType<typeof makeThreadFixture> | null,
30 threadRef: null as ScopedThreadRef | null,
31 previews: new Map<string | null, ResultAtom<ReviewDiffPreviewResult>>(),
32 patch: null as unknown as ResultAtom<ReviewDiffPreviewSource>,
33 diffFilesCollapsed: false,
34 config: null as unknown as Atom.Atom<null>,
35 status: null as unknown as ResultAtom<VcsStatusResult>,
36 localRefs: null as unknown as ResultAtom<VcsListRefsResult>,
37 remoteRefs: null as unknown as ResultAtom<VcsListRefsResult>,
38 commits: null as unknown as ResultAtom<ReviewBranchCommitsResult>,
39 checkpoints: [] as unknown[],
40 checkpointDiff: null as { diff: string } | null,
41}));
42​
43vi.mock("~/state/server", () => ({
44 serverEnvironment: { configValueAtom: () => state.config },
45}));
46vi.mock("~/state/review", () => ({
47 reviewEnvironment: {
48 diffPreview: ({ input }: { input: { baseRef?: string } }) =>
49 state.previews.get(input.baseRef ?? null)!,
50 branchCommits: () => state.commits,
51 diffFilePatch: () => state.patch,
52 diffFileContents: {},
53 },
54}));
55vi.mock("~/state/vcs", () => ({
56 vcsEnvironment: {
57 status: () => state.status,
58 listRefs: ({ input }: { input: { refKind: "local" | "remote" } }) =>
59 input.refKind === "local" ? state.localRefs : state.remoteRefs,
60 },
61}));
62vi.mock("~/state/entities", () => ({
63 useQuietThreadShell: () => state.thread,
64 useProject: () => ({ workspaceRoot: "/project", repositoryIdentity: null }),
65 useThreadCheckpointSummaries: () => state.checkpoints,
66 useQuietThreadVisibleTurnItems: () => [],
67}));
68vi.mock("~/state/filesystem", () => ({
69 useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }),
70}));
71vi.mock("~/hooks/useThreadRouteTarget", () => ({ useThreadRouteRef: () => state.threadRef }));
72vi.mock("~/hooks/useSettings", () => ({
73 useClientSettings: (select: (settings: ClientSettings) => unknown) =>
74 select({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: state.diffFilesCollapsed }),
75 updateClientSettings: async () => {},
76}));
77vi.mock("~/hooks/useTheme", () => ({
78 useRenderedAppearance: () => "dark",
79 getRenderedAppearance: () => "dark",
80 subscribeRenderedAppearance: () => () => {},
81}));
82vi.mock("~/state/queries", () => ({
83 useCheckpointDiff: () => ({ data: state.checkpointDiff, error: null, isPending: false }),
84 useTurnItemDetail: () => ({ data: null, error: null, isPending: false }),
85 useDebouncedValue: <A,>(value: A) => value,
86}));
87vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => async () => {} }));
88vi.mock("~/editorPreferences", () => ({ useOpenInPreferredEditor: () => async () => {} }));
89vi.mock("~/fileContextMenu", () => ({ useFileContextMenuHandler: () => () => {} }));
90vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => async () => {} }));
91vi.mock("./diffs/DiffCommentAnnotation", () => ({ DiffCommentAnnotation: () => null }));
92vi.mock("./diffs/DiffFileTree", () => ({ DiffFileTree: () => null }));
93vi.mock("./DiffFilePathCopyButton", () => ({ DiffFilePathCopyButton: () => null }));
94​
95import DiffPanel from "./DiffPanel";
96import { useDiffPanelSessionStore, useDiffPanelStore } from "~/diffPanelStore";
97import { selectThreadRightPanelState, useRightPanelStore } from "~/rightPanelStore";
98​
99const cwd = "/project-worktree";
100const errorMessage = "Could not find a common commit between 'origin/orphan' and HEAD.";
101​
102function preview(): ReviewDiffPreviewResult {
103 return {
104 cwd,
105 generatedAt: DateTime.makeUnsafe("2026-10-30T00:00:00Z"),
106 sources: [
107 {
108 id: "branch",
109 kind: "branch-range",
110 title: "Changes",
111 baseRef: "main",
112 headRef: "dev",
113 diff: "",
114 diffHash: "empty",
115 truncated: false,
116 patchesDeferred: true,
117 files: [],
118 },
119 ],
120 };
122​
123function setup(failedBaseRef: string | null) {
124 const reset = () => {
125 useDiffPanelStore.setState({
126 byThreadKey: {},
127 branchBaseRefByThreadKey: {},
128 });
129 useDiffPanelSessionStore.setState({ collapsedFileKeysByScopeKey: {} });
130 useRightPanelStore.setState({ byThreadKey: {}, threadPanelVisibilityByThreadKey: {} });
131 };
132 reset();
133 state.diffFilesCollapsed = false;
134 state.checkpoints = [];
135 state.checkpointDiff = null;
136 const patch = Atom.make<AsyncResult.AsyncResult<ReviewDiffPreviewSource, Error>>(
137 AsyncResult.initial(),
138 );
139 state.patch = patch;
140 state.threadRef = {
141 environmentId: EnvironmentId.make("environment"),
142 threadId: ThreadId.make("thread"),
143 };
144 state.thread = makeThreadFixture({
145 ...state.threadRef,
146 id: state.threadRef.threadId,
147 projectId: ProjectId.make("project"),
148 branch: "dev",
149 worktreePath: cwd,
150 });
151 state.previews.clear();
152 state.previews.set(null, Atom.make(AsyncResult.success(preview())));
153 state.previews.set("main", Atom.make(AsyncResult.success(preview())));
154 state.previews.set(failedBaseRef, Atom.make(AsyncResult.fail(new Error(errorMessage))));
155 state.config = Atom.make(null);
156 state.status = Atom.make(
157 AsyncResult.success({
158 isRepo: true,
159 hasPrimaryRemote: true,
160 isDefaultRef: false,
161 refName: "dev",
162 hasWorkingTreeChanges: false,
163 workingTree: { rootPath: cwd, files: [], insertions: 0, deletions: 0 },
164 hasUpstream: true,
165 aheadCount: 0,
166 behindCount: 0,
167 pr: null,
168 }),
169 );
170 const refs = (names: string[], isRemote: boolean): VcsListRefsResult => ({
171 isRepo: true,
172 hasPrimaryRemote: true,
173 nextCursor: null,
174 totalCount: names.length,
175 refs: names.map((name) => ({
176 name,
177 isRemote,
178 ...(isRemote ? { remoteName: "origin" } : {}),
179 current: name === "dev",
180 isDefault: name === "main",
181 worktreePath: null,
182 })),
183 });
184 state.localRefs = Atom.make(AsyncResult.success(refs(["dev", "main"], false)));
185 state.remoteRefs = Atom.make(AsyncResult.success(refs(["origin/orphan"], true)));
186 state.commits = Atom.make(AsyncResult.success({ commits: [], truncated: false }));
187 useDiffPanelStore.getState().selectBranchBaseRef(state.threadRef, failedBaseRef);
188 const registry = AtomRegistry.make();
189 return {
190 registry,
191 patch,
192 threadRef: state.threadRef,
193 [Symbol.dispose]() {
194 registry.dispose();
195 reset();
196 },
197 };
199​
200it.each([
201 {
202 name: "a saved unrelated branch",
203 failedBaseRef: "origin/orphan",
204 recovery: "Automatic",
205 baseRef: null,
206 },
207 {
208 name: "an automatic base with unrelated history",
209 failedBaseRef: null,
210 recovery: "main",
211 baseRef: "main",
212 },
213])(
214 "recovers from $name without leaving the diff panel",
215 async ({ failedBaseRef, recovery, baseRef }) => {
216 using context = setup(failedBaseRef);
217 await using screen = await render(
218 <RegistryContext.Provider value={context.registry}>
219 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
220 </RegistryContext.Provider>,
221 );
222 await expect.element(screen.getByText(errorMessage, { exact: true })).toBeVisible();
223 const selector = screen.getByRole("combobox", { name: /Change comparison target/ });
224 await vi.waitFor(() => expect(selector.query()).not.toBeNull());
225 await userEvent.click(selector);
226 await expect.element(page.getByRole("option", { name: "main", exact: true })).toBeVisible();
227 await userEvent.click(page.getByRole("option", { name: recovery, exact: true }));
228 await expect.element(screen.getByText("No net changes in this selection.")).toBeVisible();
229 await expect.element(screen.getByText(errorMessage, { exact: true })).not.toBeInTheDocument();
230 const key = scopedThreadKey(context.threadRef);
231 await vi.waitFor(() => {
232 expect(useDiffPanelStore.getState().byThreadKey[key]).toEqual({ kind: "branch", baseRef });
233 expect(useDiffPanelStore.getState().branchBaseRefByThreadKey[key]).toBe(baseRef);
234 });
235 },
236);
237​
238it("opens a repository-relative file from a nested project without a remote", async () => {
239 using context = setup("origin/orphan");
240 state.thread = { ...state.thread!, worktreePath: null };
241 const path = "project/back\\slash.txt";
242 const metadata = preview();
243 const source = {
244 ...metadata.sources[0]!,
245 files: [{ path, previousPath: null, additions: 1, deletions: 0 }],
246 };
247 state.previews.set("main", Atom.make(AsyncResult.success({ ...metadata, sources: [source] })));
248 state.status = Atom.make(
249 AsyncResult.success({
250 ...AsyncResult.getOrElse(context.registry.get(state.status), () => {
251 throw new Error("Missing status");
252 }),
253 workingTree: { rootPath: "/", files: [], insertions: 0, deletions: 0 },
254 }),
255 );
256 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
257 await using screen = await render(
258 <RegistryContext.Provider value={context.registry}>
259 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
260 </RegistryContext.Provider>,
261 );
262 await userEvent.click(screen.getByText(path, { exact: true }));
263 expect(
264 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, context.threadRef),
265 ).toMatchObject({ activeSurfaceId: "file:back\\slash.txt" });
266});
267​
268it.each([false, true])(
269 "expands an unloaded file on the first click with default collapse %s",
270 async (collapsed) => {
271 using context = setup("origin/orphan");
272 state.diffFilesCollapsed = collapsed;
273 const path = `pending-${collapsed}.txt`;
274 const metadata = preview();
275 const source = {
276 ...metadata.sources[0]!,
277 files: [{ path, previousPath: null, additions: 1, deletions: 1 }],
278 };
279 state.previews.set("main", Atom.make(AsyncResult.success({ ...metadata, sources: [source] })));
280 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
281 await using screen = await render(
282 <RegistryContext.Provider value={context.registry}>
283 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
284 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
285 </div>
286 </RegistryContext.Provider>,
287 );
288 const toggle = screen.getByRole("button", { name: `Expand ${path}`, exact: true });
289 await expect.element(toggle).toHaveAttribute("aria-expanded", "false");
290 await userEvent.click(toggle);
291 await act(() =>
292 context.registry.set(
293 context.patch,
294 AsyncResult.success({
295 ...source,
296 diff: `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-before\n+after\n`,
297 }),
298 ),
299 );
300 const loadedToggle = screen.getByRole("button", { name: `Collapse ${path}`, exact: true });
301 await expect.element(loadedToggle).toHaveAttribute("aria-expanded", "true");
302 await expect.element(screen.getByText("after", { exact: true })).toBeVisible();
303 await userEvent.click(loadedToggle);
304 await expect.element(toggle).toHaveAttribute("aria-expanded", "false");
305 },
306);
307​
308it("says a turn diff cut off at the server's size limit is incomplete", async () => {
309 using context = setup("origin/orphan");
310 state.checkpoints = [
311 {
312 runId: "run",
313 checkpointTurnCount: 1,
314 checkpointRef: "ref",
315 status: "ready",
316 files: [],
317 assistantMessageId: null,
318 completedAt: "2026-01-01T00:00:00Z",
319 },
320 ];
321 state.checkpointDiff = {
322 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]",
323 };
324 useDiffPanelStore.getState().selectTurn(context.threadRef, RunId.make("run"));
325 await using screen = await render(
326 <RegistryContext.Provider value={context.registry}>
327 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
328 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
329 </div>
330 </RegistryContext.Provider>,
331 );
332 await expect.element(screen.getByText("first.txt", { exact: true }).first()).toBeVisible();
333 await expect
334 .element(screen.getByText("This preview exceeds the size limit. Changes shown are incomplete."))
335 .toBeVisible();
336});
337​
338// Paths as git's numstat reports them; the parsed patch trims the trailing space from its name.
339it.each([
340 { path: " leading.ts", name: " leading.ts" },
341 { path: "src/trailing.ts ", name: "src/trailing.ts" },
342])("reveals the turn file $path picked from the changed files", async ({ path, name }) => {
343 using context = setup("origin/orphan");
344 state.diffFilesCollapsed = true;
345 state.checkpoints = [
346 {
347 runId: "run",
348 checkpointTurnCount: 1,
349 checkpointRef: "ref",
350 status: "ready",
351 files: [],
352 assistantMessageId: null,
353 completedAt: "2026-01-01T00:00:00Z",
354 },
355 ];
356 state.checkpointDiff = {
357 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`,
358 };
359 useDiffPanelStore.getState().selectTurn(context.threadRef, RunId.make("run"), path);
360 await using screen = await render(
361 <RegistryContext.Provider value={context.registry}>
362 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
363 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
364 </div>
365 </RegistryContext.Provider>,
366 );
367 await expect
368 .element(screen.getByRole("button", { name: `Collapse ${name}`, exact: true }))
369 .toHaveAttribute("aria-expanded", "true");
370});