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