@devries-cameron20 / t3code Mirror · read-only
Fork 0

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 21, 04:45 UTC

main
tsx 417 lines 15.8 KB
Raw
1 import { RegistryContext } from "@effect/atom-react";
2 import { scopedThreadKey } from "@t3tools/client-runtime/environment";
3 import {
4 DEFAULT_CLIENT_SETTINGS,
5 EnvironmentId,
6 ProjectId,
7 RunId,
8 ThreadId,
9 TurnItemId,
10 type ClientSettings,
11 type ReviewBranchCommitsResult,
12 type ReviewDiffPreviewResult,
13 type ReviewDiffPreviewSource,
14 type ScopedThreadRef,
15 type VcsListRefsResult,
16 type VcsStatusResult,
17 } from "@t3tools/contracts";
18 import * as DateTime from "effect/DateTime";
19 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
20 import { expect, it, vi } from "vite-plus/test";
21 import { page, userEvent } from "vite-plus/test/browser";
22
23 import "~/index.css";
24 import { act, render } from "../../test/render";
25 import { makeThreadFixture } from "~/test-fixtures";
26
27 type ResultAtom<A> = Atom.Atom<AsyncResult.AsyncResult<A, Error>>;
28
29 const state = vi.hoisted(() => ({
30 thread: null as ReturnType<typeof makeThreadFixture> | null,
31 threadRef: null as ScopedThreadRef | null,
32 previews: new Map<string | null, ResultAtom<ReviewDiffPreviewResult>>(),
33 patch: null as unknown as ResultAtom<ReviewDiffPreviewSource>,
34 diffFilesCollapsed: false,
35 project: {
36 workspaceRoot: "/project",
37 repositoryIdentity: null as { rootPath: string } | null,
38 },
39 toolCallItem: null as unknown,
40 config: null as unknown as Atom.Atom<null>,
41 status: null as unknown as ResultAtom<VcsStatusResult>,
42 localRefs: null as unknown as ResultAtom<VcsListRefsResult>,
43 remoteRefs: null as unknown as ResultAtom<VcsListRefsResult>,
44 commits: null as unknown as ResultAtom<ReviewBranchCommitsResult>,
45 checkpoints: [] as unknown[],
46 checkpointDiff: null as { diff: string } | null,
47 }));
48
49 vi.mock("~/state/server", () => ({
50 serverEnvironment: { configValueAtom: () => state.config },
51 }));
52 vi.mock("~/state/review", () => ({
53 reviewEnvironment: {
54 diffPreview: ({ input }: { input: { baseRef?: string } }) =>
55 state.previews.get(input.baseRef ?? null)!,
56 branchCommits: () => state.commits,
57 diffFilePatch: () => state.patch,
58 diffFileContents: {},
59 },
60 }));
61 vi.mock("~/state/vcs", () => ({
62 vcsEnvironment: {
63 status: () => state.status,
64 listRefs: ({ input }: { input: { refKind: "local" | "remote" } }) =>
65 input.refKind === "local" ? state.localRefs : state.remoteRefs,
66 },
67 }));
68 vi.mock("~/state/entities", () => ({
69 useQuietThreadShell: () => state.thread,
70 useProject: () => state.project,
71 useThreadCheckpointSummaries: () => state.checkpoints,
72 useQuietThreadVisibleTurnItems: () => [],
73 }));
74 vi.mock("~/state/filesystem", () => ({
75 useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }),
76 }));
77 vi.mock("~/hooks/useThreadRouteTarget", () => ({ useThreadRouteRef: () => state.threadRef }));
78 vi.mock("~/hooks/useSettings", () => ({
79 useClientSettings: (select: (settings: ClientSettings) => unknown) =>
80 select({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: state.diffFilesCollapsed }),
81 updateClientSettings: async () => {},
82 }));
83 vi.mock("~/hooks/useTheme", () => ({
84 useRenderedAppearance: () => "dark",
85 getRenderedAppearance: () => "dark",
86 subscribeRenderedAppearance: () => () => {},
87 }));
88 vi.mock("~/state/queries", () => ({
89 useCheckpointDiff: () => ({ data: state.checkpointDiff, error: null, isPending: false }),
90 useTurnItemDetail: () => ({
91 data: state.toolCallItem ? { item: state.toolCallItem } : null,
92 error: null,
93 isPending: false,
94 }),
95 useDebouncedValue: <A,>(value: A) => value,
96 }));
97 vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => async () => {} }));
98 vi.mock("~/editorPreferences", () => ({ useOpenInPreferredEditor: () => async () => {} }));
99 vi.mock("~/fileContextMenu", () => ({ useFileContextMenuHandler: () => () => {} }));
100 vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => async () => {} }));
101 vi.mock("./diffs/DiffCommentAnnotation", () => ({ DiffCommentAnnotation: () => null }));
102 vi.mock("./diffs/DiffFileTree", () => ({ DiffFileTree: () => null }));
103 vi.mock("./DiffFilePathCopyButton", () => ({ DiffFilePathCopyButton: () => null }));
104
105 import DiffPanel from "./DiffPanel";
106 import { useDiffPanelSessionStore, useDiffPanelStore } from "~/diffPanelStore";
107 import { selectThreadRightPanelState, useRightPanelStore } from "~/rightPanelStore";
108
109 const cwd = "/project-worktree";
110 const errorMessage = "Could not find a common commit between 'origin/orphan' and HEAD.";
111
112 function preview(): ReviewDiffPreviewResult {
113 return {
114 cwd,
115 generatedAt: DateTime.makeUnsafe("2026-10-30T00:00:00Z"),
116 sources: [
117 {
118 id: "branch",
119 kind: "branch-range",
120 title: "Changes",
121 baseRef: "main",
122 headRef: "dev",
123 diff: "",
124 diffHash: "empty",
125 truncated: false,
126 patchesDeferred: true,
127 files: [],
128 },
129 ],
130 };
131 }
132
133 function setup(failedBaseRef: string | null) {
134 const reset = () => {
135 useDiffPanelStore.setState({
136 byThreadKey: {},
137 branchBaseRefByThreadKey: {},
138 });
139 useDiffPanelSessionStore.setState({ collapsedFileKeysByScopeKey: {} });
140 useRightPanelStore.setState({ byThreadKey: {}, threadPanelVisibilityByThreadKey: {} });
141 };
142 reset();
143 state.diffFilesCollapsed = false;
144 state.project = { workspaceRoot: "/project", repositoryIdentity: null };
145 state.toolCallItem = null;
146 state.checkpoints = [];
147 state.checkpointDiff = null;
148 const patch = Atom.make<AsyncResult.AsyncResult<ReviewDiffPreviewSource, Error>>(
149 AsyncResult.initial(),
150 );
151 state.patch = patch;
152 state.threadRef = {
153 environmentId: EnvironmentId.make("environment"),
154 threadId: ThreadId.make("thread"),
155 };
156 state.thread = makeThreadFixture({
157 ...state.threadRef,
158 id: state.threadRef.threadId,
159 projectId: ProjectId.make("project"),
160 branch: "dev",
161 worktreePath: cwd,
162 });
163 state.previews.clear();
164 state.previews.set(null, Atom.make(AsyncResult.success(preview())));
165 state.previews.set("main", Atom.make(AsyncResult.success(preview())));
166 state.previews.set(failedBaseRef, Atom.make(AsyncResult.fail(new Error(errorMessage))));
167 state.config = Atom.make(null);
168 state.status = Atom.make(
169 AsyncResult.success({
170 isRepo: true,
171 hasPrimaryRemote: true,
172 isDefaultRef: false,
173 refName: "dev",
174 hasWorkingTreeChanges: false,
175 workingTree: { rootPath: cwd, files: [], insertions: 0, deletions: 0 },
176 hasUpstream: true,
177 aheadCount: 0,
178 behindCount: 0,
179 pr: null,
180 }),
181 );
182 const refs = (names: string[], isRemote: boolean): VcsListRefsResult => ({
183 isRepo: true,
184 hasPrimaryRemote: true,
185 nextCursor: null,
186 totalCount: names.length,
187 refs: names.map((name) => ({
188 name,
189 isRemote,
190 ...(isRemote ? { remoteName: "origin" } : {}),
191 current: name === "dev",
192 isDefault: name === "main",
193 worktreePath: null,
194 })),
195 });
196 state.localRefs = Atom.make(AsyncResult.success(refs(["dev", "main"], false)));
197 state.remoteRefs = Atom.make(AsyncResult.success(refs(["origin/orphan"], true)));
198 state.commits = Atom.make(AsyncResult.success({ commits: [], truncated: false }));
199 useDiffPanelStore.getState().selectBranchBaseRef(state.threadRef, failedBaseRef);
200 const registry = AtomRegistry.make();
201 return {
202 registry,
203 patch,
204 threadRef: state.threadRef,
205 [Symbol.dispose]() {
206 registry.dispose();
207 reset();
208 },
209 };
210 }
211
212 it.each([
213 {
214 name: "a saved unrelated branch",
215 failedBaseRef: "origin/orphan",
216 recovery: "Automatic",
217 baseRef: null,
218 },
219 {
220 name: "an automatic base with unrelated history",
221 failedBaseRef: null,
222 recovery: "main",
223 baseRef: "main",
224 },
225 ])(
226 "recovers from $name without leaving the diff panel",
227 async ({ failedBaseRef, recovery, baseRef }) => {
228 using context = setup(failedBaseRef);
229 await using screen = await render(
230 <RegistryContext.Provider value={context.registry}>
231 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
232 </RegistryContext.Provider>,
233 );
234 await expect.element(screen.getByText(errorMessage, { exact: true })).toBeVisible();
235 const selector = screen.getByRole("combobox", { name: /Change comparison target/ });
236 await vi.waitFor(() => expect(selector.query()).not.toBeNull());
237 await userEvent.click(selector);
238 await expect.element(page.getByRole("option", { name: "main", exact: true })).toBeVisible();
239 await userEvent.click(page.getByRole("option", { name: recovery, exact: true }));
240 await expect.element(screen.getByText("No net changes in this selection.")).toBeVisible();
241 await expect.element(screen.getByText(errorMessage, { exact: true })).not.toBeInTheDocument();
242 const key = scopedThreadKey(context.threadRef);
243 await vi.waitFor(() => {
244 expect(useDiffPanelStore.getState().byThreadKey[key]).toEqual({ kind: "branch", baseRef });
245 expect(useDiffPanelStore.getState().branchBaseRefByThreadKey[key]).toBe(baseRef);
246 });
247 },
248 );
249
250 it("opens a repository-relative file from a nested project without a remote", async () => {
251 using context = setup("origin/orphan");
252 state.thread = { ...state.thread!, worktreePath: null };
253 const path = "project/back\\slash.txt";
254 const metadata = preview();
255 const source = {
256 ...metadata.sources[0]!,
257 files: [{ path, previousPath: null, additions: 1, deletions: 0 }],
258 };
259 state.previews.set("main", Atom.make(AsyncResult.success({ ...metadata, sources: [source] })));
260 state.status = Atom.make(
261 AsyncResult.success({
262 ...AsyncResult.getOrElse(context.registry.get(state.status), () => {
263 throw new Error("Missing status");
264 }),
265 workingTree: { rootPath: "/", files: [], insertions: 0, deletions: 0 },
266 }),
267 );
268 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
269 await using screen = await render(
270 <RegistryContext.Provider value={context.registry}>
271 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
272 </RegistryContext.Provider>,
273 );
274 await userEvent.click(screen.getByText(path, { exact: true }));
275 expect(
276 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, context.threadRef),
277 ).toMatchObject({ activeSurfaceId: "file:back\\slash.txt" });
278 });
279
280 it.each([false, true])(
281 "expands an unloaded file on the first click with default collapse %s",
282 async (collapsed) => {
283 using context = setup("origin/orphan");
284 state.diffFilesCollapsed = collapsed;
285 const path = `pending-${collapsed}.txt`;
286 const metadata = preview();
287 const source = {
288 ...metadata.sources[0]!,
289 files: [{ path, previousPath: null, additions: 1, deletions: 1 }],
290 };
291 state.previews.set("main", Atom.make(AsyncResult.success({ ...metadata, sources: [source] })));
292 useDiffPanelStore.getState().selectBranchBaseRef(context.threadRef, "main");
293 await using screen = await render(
294 <RegistryContext.Provider value={context.registry}>
295 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
296 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
297 </div>
298 </RegistryContext.Provider>,
299 );
300 const toggle = screen.getByRole("button", { name: `Expand ${path}`, exact: true });
301 await expect.element(toggle).toHaveAttribute("aria-expanded", "false");
302 await userEvent.click(toggle);
303 await act(() =>
304 context.registry.set(
305 context.patch,
306 AsyncResult.success({
307 ...source,
308 diff: `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-before\n+after\n`,
309 }),
310 ),
311 );
312 const loadedToggle = screen.getByRole("button", { name: `Collapse ${path}`, exact: true });
313 await expect.element(loadedToggle).toHaveAttribute("aria-expanded", "true");
314 await expect.element(screen.getByText("after", { exact: true })).toBeVisible();
315 await userEvent.click(loadedToggle);
316 await expect.element(toggle).toHaveAttribute("aria-expanded", "false");
317 },
318 );
319
320 it("says a turn diff cut off at the server's size limit is incomplete", async () => {
321 using context = setup("origin/orphan");
322 state.checkpoints = [
323 {
324 runId: "run",
325 checkpointTurnCount: 1,
326 checkpointRef: "ref",
327 status: "ready",
328 files: [],
329 assistantMessageId: null,
330 completedAt: "2026-01-01T00:00:00Z",
331 },
332 ];
333 state.checkpointDiff = {
334 diff: "diff --git a/first.txt b/first.txt\n--- a/first.txt\n+++ b/first.txt\n@@ -0,0 +1 @@\n+visible\n\n[truncated]",
335 };
336 useDiffPanelStore.getState().selectTurn(context.threadRef, RunId.make("run"));
337 await using screen = await render(
338 <RegistryContext.Provider value={context.registry}>
339 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
340 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
341 </div>
342 </RegistryContext.Provider>,
343 );
344 await expect.element(screen.getByText("first.txt", { exact: true }).first()).toBeVisible();
345 await expect
346 .element(screen.getByText("This preview exceeds the size limit. Changes shown are incomplete."))
347 .toBeVisible();
348 });
349
350 // Paths as git's numstat reports them; the parsed patch keeps their edge whitespace.
351 it.each([
352 { path: " leading.ts", name: " leading.ts" },
353 { path: "src/trailing.ts ", name: "src/trailing.ts " },
354 ])("reveals the turn file $path picked from the changed files", async ({ path, name }) => {
355 using context = setup("origin/orphan");
356 state.diffFilesCollapsed = true;
357 state.checkpoints = [
358 {
359 runId: "run",
360 checkpointTurnCount: 1,
361 checkpointRef: "ref",
362 status: "ready",
363 files: [],
364 assistantMessageId: null,
365 completedAt: "2026-01-01T00:00:00Z",
366 },
367 ];
368 state.checkpointDiff = {
369 diff: `diff --git a/${path} b/${path}\nnew file mode 100644\n--- /dev/null\n+++ b/${path}\t\n@@ -0,0 +1 @@\n+revealed\n`,
370 };
371 useDiffPanelStore.getState().selectTurn(context.threadRef, RunId.make("run"), path);
372 await using screen = await render(
373 <RegistryContext.Provider value={context.registry}>
374 <div style={{ height: 600, display: "flex", flexDirection: "column" }}>
375 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
376 </div>
377 </RegistryContext.Provider>,
378 );
379 await expect
380 .element(screen.getByRole("button", { name: `Collapse ${name}`, exact: true }))
381 .toHaveAttribute("aria-expanded", "true");
382 });
383
384 it("opens a file from a tool call's diff by the path its agent recorded", async () => {
385 using context = setup("origin/orphan");
386 // A local thread in a project that is the repository's apps/web folder.
387 state.thread = { ...state.thread!, worktreePath: null };
388 state.project = { workspaceRoot: "/repo/apps/web", repositoryIdentity: { rootPath: "/repo" } };
389 const status = AsyncResult.getOrThrow(context.registry.get(state.status));
390 state.status = Atom.make(
391 AsyncResult.success({ ...status, workingTree: { ...status.workingTree, rootPath: "/repo" } }),
392 );
393 // Claude's Edit can record a path relative to the workspace, unlike the repository's diffs.
394 state.toolCallItem = {
395 type: "file_change",
396 fileName: "src/a.ts",
397 diffStr: "--- src/a.ts\n+++ src/a.ts\n@@ -1 +1 @@\n-before\n+after\n",
398 };
399 useDiffPanelStore.getState().selectToolCall(context.threadRef, {
400 threadId: context.threadRef.threadId,
401 itemId: TurnItemId.make("edit"),
402 revision: "1",
403 });
404 await using screen = await render(
405 <RegistryContext.Provider value={context.registry}>
406 <div className="flex h-[600px] flex-col">
407 <DiffPanel composerDraftTarget={context.threadRef} workspaceMutationId={null} visible />
408 </div>
409 </RegistryContext.Provider>,
410 );
411 await userEvent.click(screen.getByText("src/a.ts", { exact: true }));
412 await vi.waitFor(() =>
413 expect(
414 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, context.threadRef),
415 ).toMatchObject({ activeSurfaceId: "file:src/a.ts" }),
416 );
417 });