Open History to see the last commit
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 };
117}
118
119function setup(failedBaseRef: string | null) {
120 const reset = () => {
121 useDiffPanelStore.setState({
122 byThreadKey: {},
123 branchBaseRefByThreadKey: {},
124 keepSelectionOnOpenThreadKey: null,
125 });
126 useDiffPanelSessionStore.setState({ collapsedFileKeysByScopeKey: {} });
127 };
128 reset();
129 state.diffFilesCollapsed = false;
130 const patch = Atom.make<AsyncResult.AsyncResult<ReviewDiffPreviewSource, Error>>(
131 AsyncResult.initial(),
132 );
133 state.patch = patch;
134 state.threadRef = {
135 environmentId: EnvironmentId.make("environment"),
136 threadId: ThreadId.make("thread"),
137 };
138 state.thread = makeThreadFixture({
139 ...state.threadRef,
140 id: state.threadRef.threadId,
141 projectId: ProjectId.make("project"),
142 branch: "dev",
143 worktreePath: cwd,
144 });
145 state.previews.clear();
146 state.previews.set(null, Atom.make(AsyncResult.success(preview())));
147 state.previews.set("main", Atom.make(AsyncResult.success(preview())));
148 state.previews.set(failedBaseRef, Atom.make(AsyncResult.fail(new Error(errorMessage))));
149 state.config = Atom.make(null);
150 state.status = Atom.make(
151 AsyncResult.success({
152 isRepo: true,
153 hasPrimaryRemote: true,
154 isDefaultRef: false,
155 refName: "dev",
156 hasWorkingTreeChanges: false,
157 workingTree: { rootPath: cwd, files: [], insertions: 0, deletions: 0 },
158 hasUpstream: true,
159 aheadCount: 0,
160 behindCount: 0,
161 pr: null,
162 }),
163 );
164 const refs = (names: string[], isRemote: boolean): VcsListRefsResult => ({
165 isRepo: true,
166 hasPrimaryRemote: true,
167 nextCursor: null,
168 totalCount: names.length,
169 refs: names.map((name) => ({
170 name,
171 isRemote,
172 ...(isRemote ? { remoteName: "origin" } : {}),
173 current: name === "dev",
174 isDefault: name === "main",
175 worktreePath: null,
176 })),
177 });
178 state.localRefs = Atom.make(AsyncResult.success(refs(["dev", "main"], false)));
179 state.remoteRefs = Atom.make(AsyncResult.success(refs(["origin/orphan"], true)));
180 state.commits = Atom.make(AsyncResult.success({ commits: [], truncated: false }));
181 useDiffPanelStore.getState().selectBranchBaseRef(state.threadRef, failedBaseRef);
182 const registry = AtomRegistry.make();
183 return {
184 registry,
185 patch,
186 threadRef: state.threadRef,
187 [Symbol.dispose]() {
188 registry.dispose();
189 reset();
190 },
191 };
192}
193
194it.each([
195 {
196 name: "a saved unrelated branch",
197 failedBaseRef: "origin/orphan",
198 recovery: "Automatic",
199 baseRef: null,
200 },
201 {
202 name: "an automatic base with unrelated history",
203 failedBaseRef: null,
204 recovery: "main",
205 baseRef: "main",
206 },
207])(
208 "recovers from $name without leaving the diff panel",
209 async ({ failedBaseRef, recovery, baseRef }) => {
210 using context = setup(failedBaseRef);
211 await using screen = await render(
212 <RegistryContext.Provider value={context.registry}>
213 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
214 </RegistryContext.Provider>,
215 );
216 await expect.element(screen.getByText(errorMessage, { exact: true })).toBeVisible();
217 const selector = screen.getByRole("combobox", { name: /Change comparison target/ });
218 await vi.waitFor(() => expect(selector.query()).not.toBeNull());
219 await userEvent.click(selector);
220 await expect.element(page.getByRole("option", { name: "main", exact: true })).toBeVisible();
221 await userEvent.click(page.getByRole("option", { name: recovery, exact: true }));
222 await expect.element(screen.getByText("No net changes in this selection.")).toBeVisible();
223 await expect.element(screen.getByText(errorMessage, { exact: true })).not.toBeInTheDocument();
224 const key = scopedThreadKey(context.threadRef);
225 await vi.waitFor(() => {
226 expect(useDiffPanelStore.getState().byThreadKey[key]).toEqual({ kind: "branch", baseRef });
227 expect(useDiffPanelStore.getState().branchBaseRefByThreadKey[key]).toBe(baseRef);
228 });
229 },
230);
231
232it.each([false, true])(
233 "expands an unloaded file on the first click with default collapse %s",
234 async (collapsed) => {
235 using context = setup("origin/orphan");
236 state.diffFilesCollapsed = collapsed;
237 const path = `pending-${collapsed}.txt`;
238 const metadata = preview();
239 const source = {
240 ...metadata.sources[0]!,
241 files: [{ path, previousPath: null, additions: 1, deletions: 1 }],
242 };
243 state.previews.set("main", Atom.make(AsyncResult.success({ ...metadata, sources: [source] })));
244 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
245 await using screen = await render(
246 <RegistryContext.Provider value={context.registry}>
247 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
248 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
249 </div>
250 </RegistryContext.Provider>,
251 );
252 const toggle = screen.getByRole("button", { name: `Expand ${path}`, exact: true });
253 await expect.element(toggle).toHaveAttribute("aria-expanded", "false");
254 await userEvent.click(toggle);
255 await act(() =>
256 context.registry.set(
257 context.patch,
258 AsyncResult.success({
259 ...source,
260 diff: `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-before\n+after\n`,
261 }),
262 ),
263 );
264 const loadedToggle = screen.getByRole("button", { name: `Collapse ${path}`, exact: true });
265 await expect.element(loadedToggle).toHaveAttribute("aria-expanded", "true");
266 await expect.element(screen.getByText("after", { exact: true })).toBeVisible();
267 await userEvent.click(loadedToggle);
268 await expect.element(toggle).toHaveAttribute("aria-expanded", "false");
269 },
270);