Open History to see the last commit
1import "~/index.css";
2
3import { RegistryContext, useAtomValue } from "@effect/atom-react";
4import { scopeThreadRef } from "@t3tools/client-runtime/environment";
5import {
6 EnvironmentId,
7 RunId,
8 ThreadId,
9 type ReviewDiffPreviewResult,
10 type ReviewDiffPreviewSource,
11} from "@t3tools/contracts";
12import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
13import * as DateTime from "effect/DateTime";
14import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
15import { act } from "react";
16import { createRoot, type Root } from "react-dom/client";
17import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
18import { page } from "vite-plus/test/browser";
19
20vi.mock("../hooks/useThreadRouteTarget", () => ({
21 useThreadRouteRef: () => threadRef,
22 useThreadRouteTarget: () => ({ ...threadRef, kind: "thread" }),
23}));
24vi.mock("../state/entities", () => ({
25 useQuietThreadShell: () => thread,
26 useThreadCheckpointSummaries: () => turns,
27 useProject: () => null,
28}));
29vi.mock("../state/filesystem", () => ({ useFilesystemReadAccess: () => ({ canReadFiles: true }) }));
30vi.mock("../state/server", () => ({ serverEnvironment: { configValueAtom: () => configAtom } }));
31vi.mock("../state/vcs", () => ({ vcsEnvironment: { status: () => null, listRefs: () => null } }));
32vi.mock("../state/review", () => ({
33 reviewEnvironment: {
34 diffPreview: () => previewAtom,
35 diffFilePatch: ({ input }: { input: { request: { file: { path: string } } } }) =>
36 patchAtoms(input.request.file.path),
37 },
38}));
39vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
40vi.mock("../hooks/useSettings", () => ({
41 useClientSettings: () => ({
42 ...DEFAULT_CLIENT_SETTINGS,
43 diffFilesCollapsed: useAtomValue(collapsedAtom),
44 }),
45 updateClientSettings: vi.fn(),
46}));
47vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
48vi.mock("../editorPreferences", () => ({ useOpenInPreferredEditor: () => vi.fn() }));
49vi.mock("../fileContextMenu", () => ({ useFileContextMenuHandler: () => vi.fn() }));
50vi.mock("../lib/checkpointDiffState", () => ({
51 useCheckpointDiff: () => {
52 const diff = useAtomValue(checkpointAtom);
53 return { data: diff === null ? null : { diff }, isPending: diff === null, error: null };
54 },
55}));
56
57import DiffPanel from "./DiffPanel";
58import { useDiffPanelStore } from "../diffPanelStore";
59
60const threadRef = scopeThreadRef(EnvironmentId.make("environment"), ThreadId.make("thread"));
61const thread = { ...threadRef, worktreePath: "/repo" };
62const turns = [1, 2].map((ordinal) => ({
63 runId: RunId.make(`turn-${ordinal}`),
64 checkpointTurnCount: ordinal,
65 completedAt: "2026-10-16T00:00:00Z",
66}));
67const paths = ["a.txt", "b.txt", "c.txt", "d.txt", "e.txt"];
68function filePatch(path: string) {
69 const count = path === "e.txt" ? 30 : 4;
70 const lines = Array.from({ length: count }, (_, index) => `+after ${index}`).join("\n");
71 return `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1,${count} @@\n-before\n${lines}\n`;
72}
73const source: ReviewDiffPreviewSource = {
74 id: "branch",
75 kind: "branch-range",
76 title: "Changes",
77 baseRef: "main",
78 headRef: "HEAD",
79 diff: "",
80 diffHash: "branch-diff",
81 truncated: true,
82 files: paths.map((path) => ({
83 path,
84 previousPath: null,
85 additions: path === "e.txt" ? 30 : 4,
86 deletions: 1,
87 })),
88};
89const configAtom = Atom.make(null);
90const collapsedAtom = Atom.make(true);
91const checkpointAtom = Atom.make<string | null>(null);
92const previewAtom = Atom.make(
93 AsyncResult.success<ReviewDiffPreviewResult>({
94 cwd: "/repo",
95 generatedAt: DateTime.makeUnsafe("2026-10-16T00:00:00Z"),
96 sources: [source, { ...source, id: "working", kind: "working-tree" }],
97 }),
98);
99function loadedPatch(path: string): ReviewDiffPreviewSource {
100 return {
101 ...source,
102 diff: filePatch(path),
103 files: source.files?.filter((file) => file.path === path) ?? [],
104 truncated: false,
105 };
106}
107const patchAtoms = Atom.family((path: string) =>
108 Atom.make<AsyncResult.AsyncResult<ReviewDiffPreviewSource>>(
109 path === "e.txt" ? AsyncResult.initial() : AsyncResult.success(loadedPatch(path)),
110 ),
111);
112let registry: AtomRegistry.AtomRegistry;
113let container: HTMLDivElement;
114let root: Root;
115
116beforeEach(() => {
117 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
118 localStorage.setItem("t3code.diffFileTreeOpen", "true");
119 useDiffPanelStore.setState({ byThreadKey: {}, branchBaseRefByThreadKey: {} });
120 registry = AtomRegistry.make();
121 container = document.createElement("div");
122 container.style.cssText = "width: 1000px; height: 300px";
123 document.body.append(container);
124 root = createRoot(container);
125});
126afterEach(async () => {
127 await act(async () => root.unmount());
128 container.remove();
129 registry.dispose();
130 localStorage.clear();
131 vi.unstubAllGlobals();
132});
133async function render() {
134 await act(async () =>
135 root.render(
136 <RegistryContext.Provider value={registry}>
137 <DiffPanel
138 visible
139 mode="embedded"
140 composerDraftTarget={threadRef}
141 workspaceMutationId={null}
142 />
143 </RegistryContext.Provider>,
144 ),
145 );
146}
147const toggle = (path: string, expanded: boolean) =>
148 page.getByRole("button", { name: `${expanded ? "Collapse" : "Expand"} ${path}`, exact: true });
149const viewport = () => container.querySelector<HTMLElement>(".diff-render-surface")!;
150async function selectTurn(path?: string, turn = turns[0]!) {
151 await act(async () => useDiffPanelStore.getState().selectTurn(threadRef, turn.runId, path));
152}
153async function expectRevealed(path: string) {
154 await expect.element(toggle(path, true)).toBeInTheDocument();
155 await expect
156 .poll(() => {
157 const bounds = viewport().getBoundingClientRect();
158 const header = toggle(path, true).element().getBoundingClientRect();
159 return viewport().scrollTop > 0 && header.top >= bounds.top && header.bottom <= bounds.bottom;
160 })
161 .toBe(true);
162}
163async function scrollToStart() {
164 await act(async () => {
165 viewport().scrollTop = 0;
166 viewport().dispatchEvent(new Event("scroll"));
167 await new Promise(requestAnimationFrame);
168 });
169}
170async function selectTreeFile(path: string) {
171 const tree = container.querySelector("file-tree-container")!;
172 const row = tree.shadowRoot!.querySelector<HTMLElement>(`[data-item-path="${path}"]`)!;
173 await act(async () =>
174 row.dispatchEvent(
175 new MouseEvent("click", { bubbles: true, composed: true, button: 0, detail: 1 }),
176 ),
177 );
178}
179
180it("reveals a delayed turn selection, preserves siblings, and repeats after scope changes", async () => {
181 await selectTurn("e.txt");
182 await render();
183 await expect
184 .element(page.getByRole("status", { name: "Loading checkpoint diff..." }))
185 .toBeInTheDocument();
186 await act(async () => registry.set(checkpointAtom, paths.map(filePatch).join("")));
187 await expectRevealed("e.txt");
188 await act(async () => useDiffPanelStore.getState().selectGitScope(threadRef, "branch"));
189 await expect.element(toggle("a.txt", false)).toBeInTheDocument();
190 await selectTurn("e.txt");
191 await expectRevealed("e.txt");
192 await scrollToStart();
193 await toggle("a.txt", false).click();
194 await selectTurn("b.txt");
195 await expect.element(toggle("b.txt", true)).toBeInTheDocument();
196 await toggle("b.txt", true).click();
197 await selectTurn("e.txt");
198 await expectRevealed("e.txt");
199 await scrollToStart();
200 await expect.element(toggle("a.txt", true)).toBeInTheDocument();
201 await expect.element(toggle("b.txt", false)).toBeInTheDocument();
202 await expect.element(toggle("c.txt", false)).toBeInTheDocument();
203 await selectTurn("e.txt");
204 await expectRevealed("e.txt");
205
206 await selectTurn(undefined, turns[1]!);
207 await expect.element(toggle("a.txt", false)).toBeInTheDocument();
208 await expect.element(toggle("e.txt", false)).toBeInTheDocument();
209});
210
211it("waits for a lazy Git patch while preserving sibling choices and expanded defaults", async () => {
212 registry.set(collapsedAtom, false);
213 await render();
214 await toggle("b.txt", true).click();
215 await selectTreeFile("b.txt");
216 await expect.element(toggle("b.txt", true)).toBeInTheDocument();
217 await toggle("b.txt", true).click();
218 await scrollToStart();
219 await selectTreeFile("e.txt");
220 expect(viewport().scrollTop).toBe(0);
221 await expect.element(toggle("e.txt", true)).not.toBeInTheDocument();
222 await act(async () =>
223 registry.set(patchAtoms("e.txt"), AsyncResult.success(loadedPatch("e.txt"))),
224 );
225 await expectRevealed("e.txt");
226 await scrollToStart();
227 await expect.element(toggle("a.txt", true)).toBeInTheDocument();
228 await expect.element(toggle("b.txt", false)).toBeInTheDocument();
229 await act(async () => useDiffPanelStore.getState().selectGitScope(threadRef, "unstaged"));
230 await expect.element(toggle("b.txt", true)).toBeInTheDocument();
231});