The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 23:15 UTC
fix(web): expand clicked file in sidebar diff (#20101)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Nick Aristizabal committed
Oct 20, 2026 at 01:05 UTC
0c9717b0cc93fe1d7d3a41b1066e08f60ba25b0d
2 files changed
+243
-21
apps/web/src/components/DiffPanel.browser.test.tsx
new
+231
@@ -0,0 +1,231 @@
1
+import "~/index.css";
2
+
3
+import { RegistryContext, useAtomValue } from "@effect/atom-react";
4
+import { scopeThreadRef } from "@t3tools/client-runtime/environment";
5
+import {
6
+ EnvironmentId,
7
+ RunId,
8
+ ThreadId,
9
+ type ReviewDiffPreviewResult,
10
+ type ReviewDiffPreviewSource,
11
+} from "@t3tools/contracts";
12
+import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
13
+import * as DateTime from "effect/DateTime";
14
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
15
+import { act } from "react";
16
+import { createRoot, type Root } from "react-dom/client";
17
+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
18
+import { page } from "vite-plus/test/browser";
19
+
20
+vi.mock("../hooks/useThreadRouteTarget", () => ({
21
+ useThreadRouteRef: () => threadRef,
22
+ useThreadRouteTarget: () => ({ ...threadRef, kind: "thread" }),
23
+}));
24
+vi.mock("../state/entities", () => ({
25
+ useQuietThreadShell: () => thread,
26
+ useThreadCheckpointSummaries: () => turns,
27
+ useProject: () => null,
28
+}));
29
+vi.mock("../state/filesystem", () => ({ useFilesystemReadAccess: () => ({ canReadFiles: true }) }));
30
+vi.mock("../state/server", () => ({ serverEnvironment: { configValueAtom: () => configAtom } }));
31
+vi.mock("../state/vcs", () => ({ vcsEnvironment: { status: () => null, listRefs: () => null } }));
32
+vi.mock("../state/review", () => ({
33
+ reviewEnvironment: {
34
+ diffPreview: () => previewAtom,
35
+ diffFilePatch: ({ input }: { input: { request: { file: { path: string } } } }) =>
36
+ patchAtoms(input.request.file.path),
37
+ },
38
+}));
39
+vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
40
+vi.mock("../hooks/useSettings", () => ({
41
+ useClientSettings: () => ({
42
+ ...DEFAULT_CLIENT_SETTINGS,
43
+ diffFilesCollapsed: useAtomValue(collapsedAtom),
44
+ }),
45
+ updateClientSettings: vi.fn(),
46
+}));
47
+vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
48
+vi.mock("../editorPreferences", () => ({ useOpenInPreferredEditor: () => vi.fn() }));
49
+vi.mock("../fileContextMenu", () => ({ useFileContextMenuHandler: () => vi.fn() }));
50
+vi.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
+
57
+import DiffPanel from "./DiffPanel";
58
+import { useDiffPanelStore } from "../diffPanelStore";
59
+
60
+const threadRef = scopeThreadRef(EnvironmentId.make("environment"), ThreadId.make("thread"));
61
+const thread = { ...threadRef, worktreePath: "/repo" };
62
+const turns = [1, 2].map((ordinal) => ({
63
+ runId: RunId.make(`turn-${ordinal}`),
64
+ checkpointTurnCount: ordinal,
65
+ completedAt: "2026-10-16T00:00:00Z",
66
+}));
67
+const paths = ["a.txt", "b.txt", "c.txt", "d.txt", "e.txt"];
68
+function 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
+}
73
+const 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
+};
89
+const configAtom = Atom.make(null);
90
+const collapsedAtom = Atom.make(true);
91
+const checkpointAtom = Atom.make<string | null>(null);
92
+const 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
+);
99
+function 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
+}
107
+const patchAtoms = Atom.family((path: string) =>
108
+ Atom.make<AsyncResult.AsyncResult<ReviewDiffPreviewSource>>(
109
+ path === "e.txt" ? AsyncResult.initial() : AsyncResult.success(loadedPatch(path)),
110
+ ),
111
+);
112
+let registry: AtomRegistry.AtomRegistry;
113
+let container: HTMLDivElement;
114
+let root: Root;
115
+
116
+beforeEach(() => {
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
+});
126
+afterEach(async () => {
127
+ await act(async () => root.unmount());
128
+ container.remove();
129
+ registry.dispose();
130
+ localStorage.clear();
131
+ vi.unstubAllGlobals();
132
+});
133
+async 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
+}
147
+const toggle = (path: string, expanded: boolean) =>
148
+ page.getByRole("button", { name: `${expanded ? "Collapse" : "Expand"} ${path}`, exact: true });
149
+const viewport = () => container.querySelector<HTMLElement>(".diff-render-surface")!;
150
+async function selectTurn(path?: string, turn = turns[0]!) {
151
+ await act(async () => useDiffPanelStore.getState().selectTurn(threadRef, turn.runId, path));
152
+}
153
+async 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
+}
163
+async function scrollToStart() {
164
+ await act(async () => {
165
+ viewport().scrollTop = 0;
166
+ viewport().dispatchEvent(new Event("scroll"));
167
+ await new Promise(requestAnimationFrame);
168
+ });
169
+}
170
+async 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
+
180
+it("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
+
211
+it("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
+});
apps/web/src/components/DiffPanel.tsx
+12
-21
@@ -542,16 +542,6 @@ export default function DiffPanel({
542
const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
543
const diffLineStat = sourceLineStat ?? getDiffLineStat(renderableFiles);
544
const fileTreeEntries = diffFileTreeEntries(renderableFiles);
545
- const selectedDiffFileKey = selectedFilePath
546
- ? (codeViewFiles.find((candidate) => candidate.filePath === selectedFilePath)?.fileKey ?? null)
547
- : null;
548
-
549
- useEffect(() => {
550
- if (!selectedDiffFileKey || !codeView?.getInstance()) return;
551
- codeView.scrollTo({ type: "item", id: selectedDiffFileKey, align: "start" });
552
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A remounted viewer or a repeated reveal request scrolls to the same file again.
553
- }, [codeView, codeViewMountKey, selectedDiffFileKey, selectedFileRevealRequestId]);
554
-
545
const treeRevealScope = { collapseScopeKey, diffSelection };
546
const requestTreeReveal = useCodeViewFileReveal(codeView, treeRevealScope, codeViewFileKeys);
547
const revealDiffFile = (filePath: string) => {
@@ -559,7 +549,7 @@ export default function DiffPanel({
549
(candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath,
550
);
551
const file = renderableFileEntries[index];
562
- if (!file) return;
552
+ if (!file) return false;
553
setCollapsedDiffFiles((current) => {
554
const next = new Set(
555
current.scopeKey === collapseScopeKey ? current.fileKeys : defaultCollapsedDiffFileKeys,
@@ -571,20 +561,21 @@ export default function DiffPanel({
561
requestFile(index);
562
}
563
requestTreeReveal(file.fileKey);
564
+ return true;
565
};
566
576
- const externalRevealRef = useRef<{ cache: string; key: string } | null>(null);
567
+ const externalRevealRef = useRef<string | null>(null);
568
useEffect(() => {
578
- if (!lazySource || !selectedFilePath) return;
579
- const key = `${selectedFilePath}:${selectedFileRevealRequestId}`;
580
- if (
581
- externalRevealRef.current?.cache === filePatchScope &&
582
- externalRevealRef.current.key === key
583
- )
569
+ if (!selectedFilePath) {
570
+ externalRevealRef.current = null;
571
return;
585
- externalRevealRef.current = { cache: filePatchScope, key };
586
- revealDiffFile(selectedFilePath);
587
- }, [lazySource, selectedFilePath, selectedFileRevealRequestId, filePatchScope, revealDiffFile]);
572
+ }
573
+ const key = JSON.stringify([collapseScopeKey, selectedFilePath, selectedFileRevealRequestId]);
574
+ if (externalRevealRef.current === key) return;
575
+ if (revealDiffFile(selectedFilePath)) {
576
+ externalRevealRef.current = key;
577
+ }
578
+ }, [collapseScopeKey, selectedFilePath, selectedFileRevealRequestId, revealDiffFile]);
579
580
const openDiffFile = (filePath: string) => {
581
openDiffFilePrimaryAction({