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

DiffPanel.browser.test.tsx

269 lines9.9 KB

1import { RegistryContext } from "@effect/atom-react";
2import { scopedThreadKey } from "@t3tools/client-runtime/environment";
3import {
4 DEFAULT_CLIENT_SETTINGS,
5 EnvironmentId,
6 ProjectId,
7 ThreadId,
8 type ClientSettings,
9 type ReviewBranchCommitsResult,
10 type ReviewDiffPreviewResult,
11 type ReviewDiffPreviewSource,
12 type ScopedThreadRef,
13 type VcsListRefsResult,
14 type VcsStatusResult,
15} from "@t3tools/contracts";
16import * as DateTime from "effect/DateTime";
17import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
18import { expect, it, vi } from "vite-plus/test";
19import { page, userEvent } from "vite-plus/test/browser";
20​
21import "~/index.css";
22import { act, render } from "../../test/render";
23import { makeThreadFixture } from "~/test-fixtures";
24​
25type ResultAtom<A> = Atom.Atom<AsyncResult.AsyncResult<A, Error>>;
26​
27const state = vi.hoisted(() => ({
28 thread: null as ReturnType<typeof makeThreadFixture> | null,
29 threadRef: null as ScopedThreadRef | null,
30 previews: new Map<string | null, ResultAtom<ReviewDiffPreviewResult>>(),
31 patch: null as unknown as ResultAtom<ReviewDiffPreviewSource>,
32 diffFilesCollapsed: false,
33 config: null as unknown as Atom.Atom<null>,
34 status: null as unknown as ResultAtom<VcsStatusResult>,
35 localRefs: null as unknown as ResultAtom<VcsListRefsResult>,
36 remoteRefs: null as unknown as ResultAtom<VcsListRefsResult>,
37 commits: null as unknown as ResultAtom<ReviewBranchCommitsResult>,
38}));
39​
40vi.mock("~/state/server", () => ({
41 serverEnvironment: { configValueAtom: () => state.config },
42}));
43vi.mock("~/state/review", () => ({
44 reviewEnvironment: {
45 diffPreview: ({ input }: { input: { baseRef?: string } }) =>
46 state.previews.get(input.baseRef ?? null)!,
47 branchCommits: () => state.commits,
48 diffFilePatch: () => state.patch,
49 diffFileContents: {},
50 },
51}));
52vi.mock("~/state/vcs", () => ({
53 vcsEnvironment: {
54 status: () => state.status,
55 listRefs: ({ input }: { input: { refKind: "local" | "remote" } }) =>
56 input.refKind === "local" ? state.localRefs : state.remoteRefs,
57 },
58}));
59vi.mock("~/state/entities", () => ({
60 useQuietThreadShell: () => state.thread,
61 useProject: () => ({ workspaceRoot: "/project", repositoryIdentity: null }),
62 useThreadCheckpointSummaries: () => [],
63 useQuietThreadVisibleTurnItems: () => [],
64}));
65vi.mock("~/state/filesystem", () => ({
66 useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }),
67}));
68vi.mock("~/hooks/useThreadRouteTarget", () => ({ useThreadRouteRef: () => state.threadRef }));
69vi.mock("~/hooks/useSettings", () => ({
70 useClientSettings: (select: (settings: ClientSettings) => unknown) =>
71 select({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: state.diffFilesCollapsed }),
72 updateClientSettings: async () => {},
73}));
74vi.mock("~/hooks/useTheme", () => ({
75 useRenderedAppearance: () => "dark",
76 getRenderedAppearance: () => "dark",
77 subscribeRenderedAppearance: () => () => {},
78}));
79vi.mock("~/state/queries", () => ({
80 useCheckpointDiff: () => ({ data: null, error: null, isPending: false }),
81 useTurnItemDetail: () => ({ data: null, error: null, isPending: false }),
82 useDebouncedValue: <A,>(value: A) => value,
83}));
84vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => async () => {} }));
85vi.mock("~/editorPreferences", () => ({ useOpenInPreferredEditor: () => async () => {} }));
86vi.mock("~/fileContextMenu", () => ({ useFileContextMenuHandler: () => () => {} }));
87vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => async () => {} }));
88vi.mock("./diffs/DiffCommentAnnotation", () => ({ DiffCommentAnnotation: () => null }));
89vi.mock("./diffs/DiffFileTree", () => ({ DiffFileTree: () => null }));
90vi.mock("./DiffFilePathCopyButton", () => ({ DiffFilePathCopyButton: () => null }));
91​
92import DiffPanel from "./DiffPanel";
93import { useDiffPanelSessionStore, useDiffPanelStore } from "~/diffPanelStore";
94​
95const cwd = "/project-worktree";
96const errorMessage = "Could not find a common commit between 'origin/orphan' and HEAD.";
97​
98function preview(): ReviewDiffPreviewResult {
99 return {
100 cwd,
101 generatedAt: DateTime.makeUnsafe("2026-10-30T00:00:00Z"),
102 sources: [
103 {
104 id: "branch",
105 kind: "branch-range",
106 title: "Changes",
107 baseRef: "main",
108 headRef: "dev",
109 diff: "",
110 diffHash: "empty",
111 truncated: false,
112 patchesDeferred: true,
113 files: [],
114 },
115 ],
116 };
118​
119function setup(failedBaseRef: string | null) {
120 const reset = () => {
121 useDiffPanelStore.setState({
122 byThreadKey: {},
123 branchBaseRefByThreadKey: {},
124 });
125 useDiffPanelSessionStore.setState({ collapsedFileKeysByScopeKey: {} });
126 };
127 reset();
128 state.diffFilesCollapsed = false;
129 const patch = Atom.make<AsyncResult.AsyncResult<ReviewDiffPreviewSource, Error>>(
130 AsyncResult.initial(),
131 );
132 state.patch = patch;
133 state.threadRef = {
134 environmentId: EnvironmentId.make("environment"),
135 threadId: ThreadId.make("thread"),
136 };
137 state.thread = makeThreadFixture({
138 ...state.threadRef,
139 id: state.threadRef.threadId,
140 projectId: ProjectId.make("project"),
141 branch: "dev",
142 worktreePath: cwd,
143 });
144 state.previews.clear();
145 state.previews.set(null, Atom.make(AsyncResult.success(preview())));
146 state.previews.set("main", Atom.make(AsyncResult.success(preview())));
147 state.previews.set(failedBaseRef, Atom.make(AsyncResult.fail(new Error(errorMessage))));
148 state.config = Atom.make(null);
149 state.status = Atom.make(
150 AsyncResult.success({
151 isRepo: true,
152 hasPrimaryRemote: true,
153 isDefaultRef: false,
154 refName: "dev",
155 hasWorkingTreeChanges: false,
156 workingTree: { rootPath: cwd, files: [], insertions: 0, deletions: 0 },
157 hasUpstream: true,
158 aheadCount: 0,
159 behindCount: 0,
160 pr: null,
161 }),
162 );
163 const refs = (names: string[], isRemote: boolean): VcsListRefsResult => ({
164 isRepo: true,
165 hasPrimaryRemote: true,
166 nextCursor: null,
167 totalCount: names.length,
168 refs: names.map((name) => ({
169 name,
170 isRemote,
171 ...(isRemote ? { remoteName: "origin" } : {}),
172 current: name === "dev",
173 isDefault: name === "main",
174 worktreePath: null,
175 })),
176 });
177 state.localRefs = Atom.make(AsyncResult.success(refs(["dev", "main"], false)));
178 state.remoteRefs = Atom.make(AsyncResult.success(refs(["origin/orphan"], true)));
179 state.commits = Atom.make(AsyncResult.success({ commits: [], truncated: false }));
180 useDiffPanelStore.getState().selectBranchBaseRef(state.threadRef, failedBaseRef);
181 const registry = AtomRegistry.make();
182 return {
183 registry,
184 patch,
185 threadRef: state.threadRef,
186 [Symbol.dispose]() {
187 registry.dispose();
188 reset();
189 },
190 };
192​
193it.each([
194 {
195 name: "a saved unrelated branch",
196 failedBaseRef: "origin/orphan",
197 recovery: "Automatic",
198 baseRef: null,
199 },
200 {
201 name: "an automatic base with unrelated history",
202 failedBaseRef: null,
203 recovery: "main",
204 baseRef: "main",
205 },
206])(
207 "recovers from $name without leaving the diff panel",
208 async ({ failedBaseRef, recovery, baseRef }) => {
209 using context = setup(failedBaseRef);
210 await using screen = await render(
211 <RegistryContext.Provider value={context.registry}>
212 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
213 </RegistryContext.Provider>,
214 );
215 await expect.element(screen.getByText(errorMessage, { exact: true })).toBeVisible();
216 const selector = screen.getByRole("combobox", { name: /Change comparison target/ });
217 await vi.waitFor(() => expect(selector.query()).not.toBeNull());
218 await userEvent.click(selector);
219 await expect.element(page.getByRole("option", { name: "main", exact: true })).toBeVisible();
220 await userEvent.click(page.getByRole("option", { name: recovery, exact: true }));
221 await expect.element(screen.getByText("No net changes in this selection.")).toBeVisible();
222 await expect.element(screen.getByText(errorMessage, { exact: true })).not.toBeInTheDocument();
223 const key = scopedThreadKey(context.threadRef);
224 await vi.waitFor(() => {
225 expect(useDiffPanelStore.getState().byThreadKey[key]).toEqual({ kind: "branch", baseRef });
226 expect(useDiffPanelStore.getState().branchBaseRefByThreadKey[key]).toBe(baseRef);
227 });
228 },
229);
230​
231it.each([false, true])(
232 "expands an unloaded file on the first click with default collapse %s",
233 async (collapsed) => {
234 using context = setup("origin/orphan");
235 state.diffFilesCollapsed = collapsed;
236 const path = `pending-${collapsed}.txt`;
237 const metadata = preview();
238 const source = {
239 ...metadata.sources[0]!,
240 files: [{ path, previousPath: null, additions: 1, deletions: 1 }],
241 };
242 state.previews.set("main", Atom.make(AsyncResult.success({ ...metadata, sources: [source] })));
243 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
244 await using screen = await render(
245 <RegistryContext.Provider value={context.registry}>
246 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
247 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
248 </div>
249 </RegistryContext.Provider>,
250 );
251 const toggle = screen.getByRole("button", { name: `Expand ${path}`, exact: true });
252 await expect.element(toggle).toHaveAttribute("aria-expanded", "false");
253 await userEvent.click(toggle);
254 await act(() =>
255 context.registry.set(
256 context.patch,
257 AsyncResult.success({
258 ...source,
259 diff: `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-before\n+after\n`,
260 }),
261 ),
262 );
263 const loadedToggle = screen.getByRole("button", { name: `Collapse ${path}`, exact: true });
264 await expect.element(loadedToggle).toHaveAttribute("aria-expanded", "true");
265 await expect.element(screen.getByText("after", { exact: true })).toBeVisible();
266 await userEvent.click(loadedToggle);
267 await expect.element(toggle).toHaveAttribute("aria-expanded", "false");
268 },
269);