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