The best way to control Claude Code, Codex and more from any computer or phone
fix(web): load selected diff metadata before file patches (#30567)
Yash Singh committed
Nov 4, 2026 at 01:01 UTC
8b44f42b14c8e273156474a924ccf29680dd7857
10 files changed
+583
-104
apps/server/src/vcs/GitVcsDriverCore.test.ts
+115
-1
@@ -2170,6 +2170,14 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
2170
.sources[0]!;
2171
assert.equal(rootSource.baseRef, emptyTree);
2172
assert.include(rootSource.diff, "+# test");
2173
+ const rootMetadata = (yield* driver.getReviewDiffPreview({
2174
+ cwd: upstream,
2175
+ commitSha: root,
2176
+ metadataOnly: true,
2177
+ })).sources[0]!;
2178
+ assert.deepStrictEqual(rootMetadata.files, rootSource.files);
2179
+ assert.isTrue(rootMetadata.patchesDeferred);
2180
+ assert.isEmpty(rootMetadata.diff);
2181
2182
yield* writeTextFile(upstream, "README.md", "# boundary\n");
2183
yield* git(upstream, ["commit", "-am", "boundary"]);
@@ -2396,6 +2404,78 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
2404
}),
2405
);
2406
2407
+ it.effect(
2408
+ "returns an incomplete selected tracked preview while untracked discovery is held",
2409
+ () =>
2410
+ Effect.gen(function* () {
2411
+ const cwd = yield* makeTmpDir();
2412
+ yield* initRepoWithCommit(cwd);
2413
+ yield* writeTextFile(cwd, "README.md", "changed\n");
2414
+ yield* writeTextFile(cwd, "new.txt", "untracked\n");
2415
+ const started = yield* Deferred.make<void>();
2416
+ const release = yield* Deferred.make<void>();
2417
+ let untrackedReads = 0;
2418
+ const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
2419
+ const spawner = ChildProcessSpawner.make((command) =>
2420
+ Effect.gen(function* () {
2421
+ if (ChildProcess.isStandardCommand(command) && command.args.includes("--others")) {
2422
+ assert.equal(
2423
+ ++untrackedReads,
2424
+ 1,
2425
+ "tracked preview must not enumerate untracked files",
2426
+ );
2427
+ yield* Deferred.succeed(started, undefined);
2428
+ yield* Deferred.await(release);
2429
+ }
2430
+ return yield* delegate.spawn(command);
2431
+ }),
2432
+ );
2433
+ const driver = yield* makeGitVcsDriverCore().pipe(
2434
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
2435
+ Effect.provide(layerServerConfig),
2436
+ );
2437
+ const full = yield* driver
2438
+ .getReviewDiffPreview({ cwd, sourceKind: "working-tree" })
2439
+ .pipe(Effect.forkChild);
2440
+ yield* Deferred.await(started);
2441
+ yield* Effect.gen(function* () {
2442
+ const preview = yield* driver.getReviewDiffPreview({
2443
+ cwd,
2444
+ sourceKind: "working-tree",
2445
+ trackedOnly: true,
2446
+ });
2447
+ assert.isTrue(preview.incomplete);
2448
+ assert.deepStrictEqual(
2449
+ preview.sources.map((source) => source.kind),
2450
+ ["working-tree"],
2451
+ );
2452
+ assert.include(preview.sources[0]!.diff, "+changed");
2453
+ assert.notInclude(preview.sources[0]!.diff, "untracked");
2454
+ const metadata = yield* driver.getReviewDiffPreview({
2455
+ cwd,
2456
+ sourceKind: "working-tree",
2457
+ trackedOnly: true,
2458
+ metadataOnly: true,
2459
+ });
2460
+ assert.isTrue(metadata.incomplete);
2461
+ assert.deepStrictEqual(metadata.sources[0]!.files, preview.sources[0]!.files);
2462
+ assert.isTrue(metadata.sources[0]!.patchesDeferred);
2463
+ assert.isEmpty(metadata.sources[0]!.diff);
2464
+ }).pipe(Effect.ensuring(Deferred.succeed(release, undefined)));
2465
+ const complete = yield* Fiber.join(full);
2466
+ assert.isUndefined(complete.incomplete);
2467
+ assert.include(complete.sources[0]!.diff, "+untracked");
2468
+ yield* writeTextFile(cwd, "README.md", "edited again\n");
2469
+ const refreshed = yield* driver.getReviewDiffPreview({
2470
+ cwd,
2471
+ baseRef: "missing-base",
2472
+ sourceKind: "working-tree",
2473
+ trackedOnly: true,
2474
+ });
2475
+ assert.include(refreshed.sources[0]!.diff, "+edited again");
2476
+ }),
2477
+ );
2478
+
2479
it.effect("propagates patch failures instead of reporting an empty complete diff", () =>
2480
Effect.gen(function* () {
2481
const cwd = yield* makeTmpDir();
@@ -2416,6 +2496,16 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
2496
if (Result.isFailure(result)) {
2497
assert.equal(result.failure.operation, "GitVcsDriver.getReviewDiffPreview.patch");
2498
}
2499
+ const metadata = yield* driver.getReviewDiffPreview({
2500
+ cwd,
2501
+ sourceKind: "working-tree",
2502
+ metadataOnly: true,
2503
+ });
2504
+ assert.isTrue(metadata.sources[0]!.patchesDeferred);
2505
+ assert.isEmpty(metadata.sources[0]!.diff);
2506
+ assert.deepStrictEqual(metadata.sources[0]!.files, [
2507
+ { path: "README.md", previousPath: null, additions: 1, deletions: 1 },
2508
+ ]);
2509
}),
2510
);
2511
@@ -2597,9 +2687,17 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
2687
);
2688
yield* writeTextFile(cwd, "README.md", "# tracked change\n");
2689
2600
- const preview = yield* driver.getReviewDiffPreview({ cwd, ignoreWhitespace: false });
2690
+ const preview = yield* driver.getReviewDiffPreview({
2691
+ cwd,
2692
+ ignoreWhitespace: false,
2693
+ metadataOnly: true,
2694
+ });
2695
const diff = preview.sources.find((source) => source.kind === "working-tree")?.diff ?? "";
2696
2697
+ const source = preview.sources.find((source) => source.kind === "working-tree")!;
2698
+ assert.isUndefined(source.patchesDeferred);
2699
+ assert.isUndefined(source.files);
2700
+ assert.isTrue(source.truncated);
2701
assert.include(diff, "-# test");
2702
assert.include(diff, "+# tracked change");
2703
}),
@@ -2734,6 +2832,22 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
2832
assert.isTrue(dirty.truncated);
2833
assert.notInclude(branch.diff, "z-last.txt");
2834
for (const source of [branch, dirty]) {
2835
+ const selected = yield* driver.getReviewDiffPreview({
2836
+ cwd,
2837
+ baseRef: initialBranch,
2838
+ sourceKind: source.kind === "working-tree" ? "working-tree" : "branch-range",
2839
+ });
2840
+ assert.deepStrictEqual(selected.sources, [source]);
2841
+ const metadata = (yield* driver.getReviewDiffPreview({
2842
+ cwd,
2843
+ baseRef: initialBranch,
2844
+ sourceKind: source.kind === "working-tree" ? "working-tree" : "branch-range",
2845
+ metadataOnly: true,
2846
+ })).sources[0]!;
2847
+ assert.deepStrictEqual(metadata.files, source.files);
2848
+ assert.isTrue(metadata.patchesDeferred);
2849
+ assert.isFalse(metadata.truncated);
2850
+ assert.isEmpty(metadata.diff);
2851
for (const file of source.files ?? []) {
2852
const individual = yield* driver.getReviewDiffPreview({
2853
cwd,
apps/server/src/vcs/GitVcsDriverCore.ts
+35
-15
@@ -3409,10 +3409,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3409
const patchLimit = input.file
3410
? REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES
3411
: REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES;
3412
+ const sourceKind = input.file?.sourceKind ?? input.sourceKind;
3413
const needsCurrentBranch =
3414
input.commitSha === undefined &&
3415
input.file?.sourceKind !== "commit" &&
3415
- input.file?.sourceKind !== "working-tree";
3416
+ sourceKind !== "working-tree";
3417
const repository = yield* (
3418
needsCurrentBranch
3419
? resolveRepositoryPathsUncached(input.cwd)
@@ -3463,12 +3464,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3464
{ maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES },
3465
);
3466
const files = parseReviewNumstat(stat.stdout);
3466
- const patch = yield* executeGit(
3467
- "GitVcsDriver.getReviewDiffPreview.commitPatch",
3468
- cwd,
3469
- [...diffArgs, "--patch", commit.parent, commit.sha, "--", ...pathArgs],
3470
- { maxOutputBytes: patchLimit, appendTruncationMarker: true },
3471
- );
3467
+ const patch =
3468
+ input.metadataOnly && !input.file
3469
+ ? { stdout: "", stdoutTruncated: false }
3470
+ : yield* executeGit(
3471
+ "GitVcsDriver.getReviewDiffPreview.commitPatch",
3472
+ cwd,
3473
+ [...diffArgs, "--patch", commit.parent, commit.sha, "--", ...pathArgs],
3474
+ { maxOutputBytes: patchLimit, appendTruncationMarker: true },
3475
+ );
3476
const diffHash = yield* hashDiff(patch.stdout, files);
3477
return {
3478
cwd: input.cwd,
@@ -3485,14 +3489,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3489
files,
3490
diffHash,
3491
truncated: patch.stdoutTruncated,
3492
+ ...(input.metadataOnly && !input.file ? { patchesDeferred: true } : {}),
3493
},
3494
],
3495
};
3496
}
3497
3493
- const dirtyRef = input.file?.sourceKind === "branch-range" ? null : "HEAD";
3498
+ const dirtyRef = sourceKind === "branch-range" ? null : "HEAD";
3499
const review =
3495
- input.file?.sourceKind === "working-tree"
3500
+ sourceKind === "working-tree"
3501
? { baseRef: input.baseRef ?? null, mergeBase: null }
3502
: yield* resolveReviewMergeBase(cwd, repository.currentBranch, input.baseRef);
3503
@@ -3534,10 +3539,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3539
const readTrackedDiff = Effect.fn("GitVcsDriver.getReviewDiffPreview.tracked")(function* (
3540
ref: string | null,
3541
env?: NodeJS.ProcessEnv,
3542
+ metadataOnly = false,
3543
) {
3544
if (ref === null) return { stdout: "", stdoutTruncated: false, files: [] };
3545
const stat = yield* readStats(ref, env);
3540
- if (stat.files.length === 0) return { stdout: "", stdoutTruncated: false, files: [] };
3546
+ if (metadataOnly || stat.files.length === 0) {
3547
+ return { stdout: "", stdoutTruncated: false, files: stat.files };
3548
+ }
3549
const patch = yield* executeGit(
3550
"GitVcsDriver.getReviewDiffPreview.patch",
3551
cwd,
@@ -3547,16 +3555,19 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3555
return { ...patch, files: stat.files };
3556
});
3557
const [dirtyTrackedResult, baseResult] = yield* Effect.gen(function* () {
3550
- const untracked = yield* prepareUntrackedReviewIndex(cwd, pathArgs, input.file?.path);
3558
+ const untracked = input.trackedOnly
3559
+ ? { env: undefined }
3560
+ : yield* prepareUntrackedReviewIndex(cwd, pathArgs, input.file?.path);
3561
+ const metadataOnly = input.metadataOnly === true && !input.file && untracked !== null;
3562
const [dirty, base] =
3563
review.mergeBase === dirtyRef
3553
- ? yield* readTrackedDiff(dirtyRef, untracked?.env).pipe(
3564
+ ? yield* readTrackedDiff(dirtyRef, untracked?.env, metadataOnly).pipe(
3565
Effect.map((result) => [result, result] as const),
3566
)
3567
: yield* Effect.all(
3568
[
3558
- readTrackedDiff(dirtyRef, untracked?.env),
3559
- readTrackedDiff(review.mergeBase, untracked?.env),
3569
+ readTrackedDiff(dirtyRef, untracked?.env, metadataOnly),
3570
+ readTrackedDiff(review.mergeBase, untracked?.env, metadataOnly),
3571
],
3572
{ concurrency: 2 },
3573
);
@@ -3585,6 +3596,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3596
...(dirtyFiles === undefined ? {} : { files: dirtyFiles }),
3597
diffHash: dirtyDiffHash,
3598
truncated: dirtyTrackedResult.stdoutTruncated,
3599
+ ...(input.metadataOnly && !input.file && dirtyFiles !== undefined
3600
+ ? { patchesDeferred: true }
3601
+ : {}),
3602
},
3603
{
3604
id: "branch-range",
@@ -3596,13 +3610,19 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3610
...(baseFiles === undefined ? {} : { files: baseFiles }),
3611
diffHash: baseDiffHash,
3612
truncated: baseResult.stdoutTruncated,
3613
+ ...(input.metadataOnly && !input.file && baseFiles !== undefined
3614
+ ? { patchesDeferred: true }
3615
+ : {}),
3616
},
3617
];
3618
3619
return {
3620
cwd: input.cwd,
3621
generatedAt: yield* DateTime.now,
3605
- sources,
3622
+ sources: input.sourceKind
3623
+ ? sources.filter((source) => source.kind === input.sourceKind)
3624
+ : sources,
3625
+ ...(input.trackedOnly ? { incomplete: true } : {}),
3626
};
3627
});
3628
apps/web/src/components/DiffPanel.browser.test.tsx
+59
-5
@@ -8,6 +8,7 @@ import {
8
type ClientSettings,
9
type ReviewBranchCommitsResult,
10
type ReviewDiffPreviewResult,
11
+ type ReviewDiffPreviewSource,
12
type ScopedThreadRef,
13
type VcsListRefsResult,
14
type VcsStatusResult,
@@ -18,7 +19,7 @@ import { expect, it, vi } from "vite-plus/test";
19
import { page, userEvent } from "vite-plus/test/browser";
20
21
import "~/index.css";
21
-import { render } from "../../test/render";
22
+import { act, render } from "../../test/render";
23
import { makeThreadFixture } from "~/test-fixtures";
24
25
type ResultAtom<A> = Atom.Atom<AsyncResult.AsyncResult<A, Error>>;
@@ -27,6 +28,8 @@ const 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>,
@@ -42,6 +45,7 @@ vi.mock("~/state/review", () => ({
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
}));
@@ -64,10 +68,14 @@ vi.mock("~/state/filesystem", () => ({
68
vi.mock("~/hooks/useThreadRouteTarget", () => ({ useThreadRouteRef: () => state.threadRef }));
69
vi.mock("~/hooks/useSettings", () => ({
70
useClientSettings: (select: (settings: ClientSettings) => unknown) =>
67
- select(DEFAULT_CLIENT_SETTINGS),
71
+ select({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: state.diffFilesCollapsed }),
72
updateClientSettings: async () => {},
73
}));
70
-vi.mock("~/hooks/useTheme", () => ({ useRenderedAppearance: () => "dark" }));
74
+vi.mock("~/hooks/useTheme", () => ({
75
+ useRenderedAppearance: () => "dark",
76
+ getRenderedAppearance: () => "dark",
77
+ subscribeRenderedAppearance: () => () => {},
78
+}));
79
vi.mock("~/state/queries", () => ({
80
useCheckpointDiff: () => ({ data: null, error: null, isPending: false }),
81
useTurnItemDetail: () => ({ data: null, error: null, isPending: false }),
@@ -76,8 +84,6 @@ vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => async () => {
84
vi.mock("~/editorPreferences", () => ({ useOpenInPreferredEditor: () => async () => {} }));
85
vi.mock("~/fileContextMenu", () => ({ useFileContextMenuHandler: () => () => {} }));
86
vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => async () => {} }));
79
-// The test drives comparison controls, without mounting virtualized diff viewers or their workers.
80
-vi.mock("./diffs/AnnotatableCodeView", () => ({ AnnotatableCodeView: () => null }));
87
vi.mock("./diffs/DiffFileTree", () => ({ DiffFileTree: () => null }));
88
vi.mock("./DiffFilePathCopyButton", () => ({ DiffFilePathCopyButton: () => null }));
89
@@ -101,6 +107,8 @@ function preview(): ReviewDiffPreviewResult {
107
diff: "",
108
diffHash: "empty",
109
truncated: false,
110
+ patchesDeferred: true,
111
+ files: [],
112
},
113
],
114
};
@@ -116,6 +124,11 @@ function setup(failedBaseRef: string | null) {
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"),
@@ -167,6 +180,7 @@ function setup(failedBaseRef: string | null) {
180
const registry = AtomRegistry.make();
181
return {
182
registry,
183
+ patch,
184
threadRef: state.threadRef,
185
[Symbol.dispose]() {
186
registry.dispose();
@@ -212,3 +226,43 @@ it.each([
226
});
227
},
228
);
229
+
230
+it.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
+);
apps/web/src/components/DiffPanel.tsx
+79
-38
@@ -102,6 +102,7 @@ import { vcsEnvironment } from "../state/vcs";
102
import { buildBaseRefChoices, filterBaseRefChoices } from "../lib/baseRefChoices";
103
import { createGitDiffFileContentsLoader } from "../lib/diffFileContents";
104
105
+import { observeIntersection } from "~/lib/observeIntersection";
106
import { useReviewFilePatches } from "./diffs/useReviewFilePatches";
107
import { DiffFileLoadingBoundary } from "./diffs/DiffFileLoadingBoundary";
108
import { DiffFileStatus } from "./diffs/DiffFileStatus";
@@ -135,13 +136,13 @@ function DiffFileCollapseToggle({
136
filePath,
137
fileKey,
138
collapsed,
138
- unavailable,
139
onToggle,
140
+ load,
141
}: {
142
filePath: string;
143
fileKey: string;
144
collapsed: boolean;
144
- unavailable: boolean;
145
+ load?: () => void;
146
onToggle: (fileKey: string) => void;
147
}) {
148
return (
@@ -154,7 +155,16 @@ function DiffFileCollapseToggle({
155
className="-ms-0.5"
156
aria-label={collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`}
157
aria-expanded={!collapsed}
157
- disabled={unavailable}
158
+ ref={(node) => {
159
+ if (!node || !load) return;
160
+ return observeIntersection(
161
+ node,
162
+ (entry) => {
163
+ if (entry.isIntersecting) load();
164
+ },
165
+ { rootMargin: "600px" },
166
+ );
167
+ }}
168
onClick={(event) => {
169
event.stopPropagation();
170
onToggle(fileKey);
@@ -362,6 +372,15 @@ export default function DiffPanel({
372
...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),
373
...(selectedCommitSha !== null ? { commitSha: selectedCommitSha } : {}),
374
ignoreWhitespace: diffIgnoreWhitespace,
375
+ metadataOnly: true,
376
+ ...(selectedCommitSha === null
377
+ ? {
378
+ sourceKind:
379
+ selectedGitScope === "unstaged"
380
+ ? ("working-tree" as const)
381
+ : ("branch-range" as const),
382
+ }
383
+ : {}),
384
}
385
: undefined;
386
const canRefreshGitDiff =
@@ -465,16 +484,25 @@ export default function DiffPanel({
484
: selectedTurn
485
? activeCheckpointDiff
486
: branchDiffPreview;
468
- const isLoadingSelectedPatch = selectedPatchQuery.isPending && selectedPatchQuery.data === null;
487
+ const isLoadingSelectedPatch =
488
+ selectedPatchQuery.isPending &&
489
+ (selectedPatchQuery.data === null ||
490
+ (isGitSelection && preview?.incomplete === true && selectedGitSource?.files?.length === 0));
491
const selectedPatchError = toolCallSelection
492
? toolCallDetail.error
493
: selectedTurn
494
? activeCheckpointDiff.error
495
: branchDiffPreview.error;
496
const hasResolvedPatch = typeof selectedPatch === "string";
475
- const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0;
497
+ const hasNoNetChanges =
498
+ hasResolvedPatch &&
499
+ selectedPatch.trim().length === 0 &&
500
+ !preview?.incomplete &&
501
+ (!selectedGitSource?.patchesDeferred || selectedGitSource.files?.length === 0);
502
const lazySource =
477
- isGitSelection && selectedGitSource?.truncated && selectedGitSource.files
503
+ isGitSelection &&
504
+ (selectedGitSource?.truncated || selectedGitSource?.patchesDeferred) &&
505
+ selectedGitSource.files?.length
506
? selectedGitSource
507
: null;
508
const renderablePatch = getRenderablePatch(
@@ -566,14 +594,12 @@ export default function DiffPanel({
594
...matchingBaseRefChoices.map(valueForBaseRefChoice),
595
];
596
const {
569
- scope: filePatchScope,
597
isPending: areFilePatchesPending,
598
fileStates,
599
retry,
600
requestFile,
574
- readyFilePaths,
601
renderableFiles,
576
- settledFileCount,
602
+ remainingFileCount,
603
loadNextFiles,
604
} = useReviewFilePatches({
605
environmentId: activeThread?.environmentId,
@@ -609,7 +635,16 @@ export default function DiffPanel({
635
);
636
637
const isRefreshingDiff = branchDiffPreview.isPending || areFilePatchesPending;
612
- const renderableFileEntries = renderableFiles.map(getCachedFileEntry);
638
+ const pathOccurrences = new Map<string, number>();
639
+ const renderableFileEntries = renderableFiles.map((fileDiff) => {
640
+ const entry = getCachedFileEntry(fileDiff);
641
+ if (!isGitSelection) return entry;
642
+ // Metadata has no change type; keep each path's identity when its patch arrives.
643
+ const pathKey = JSON.stringify([fileDiff.prevName ?? fileDiff.name, fileDiff.name]);
644
+ const occurrence = pathOccurrences.get(pathKey) ?? 0;
645
+ pathOccurrences.set(pathKey, occurrence + 1);
646
+ return { ...entry, fileKey: `${pathKey}:${occurrence}` };
647
+ });
648
const diffFileKeys = renderableFileEntries.map((file) => file.fileKey);
649
const testFileCount = renderableFiles.filter((file) =>
650
isTestChangedFile(resolveFileDiffPath(file)),
@@ -637,25 +672,17 @@ export default function DiffPanel({
672
.updateCollapsedFileKeys(collapseScopeKey, defaultCollapsedDiffFileKeys, update);
673
};
674
const renderLoadingBoundary = () =>
640
- settledFileCount < renderableFiles.length ? (
641
- <DiffFileLoadingBoundary
642
- load={loadNextFiles}
643
- count={renderableFiles.length - settledFileCount}
644
- />
675
+ remainingFileCount > 0 ? (
676
+ <DiffFileLoadingBoundary load={loadNextFiles} count={remainingFileCount} />
677
) : null;
646
- const codeViewFiles = shownFileEntries
647
- .filter(
648
- ({ fileDiff }) =>
649
- !lazySource || !readyFilePaths || readyFilePaths.has(resolveFileDiffPath(fileDiff)),
650
- )
651
- .map(({ fileDiff, fileKey, fileVersion }) => ({
652
- fileDiff,
653
- filePath: resolveFileDiffPath(fileDiff),
654
- fileKey,
655
- fileVersion,
656
- collapsed:
657
- collapsedDiffFileKeys.has(fileKey) || fileDiff.cacheKey?.endsWith(":pending") === true,
658
- }));
678
+ const codeViewFiles = shownFileEntries.map(({ fileDiff, fileKey, fileVersion }) => ({
679
+ fileDiff,
680
+ filePath: resolveFileDiffPath(fileDiff),
681
+ fileKey,
682
+ fileVersion,
683
+ collapsed:
684
+ collapsedDiffFileKeys.has(fileKey) || fileDiff.cacheKey?.endsWith(":pending") === true,
685
+ }));
686
const pendingFiles = renderableFiles.filter(
687
(file) => file.cacheKey?.endsWith(":pending") && isFileShown(file),
688
);
@@ -674,9 +701,7 @@ export default function DiffPanel({
701
next.delete(file.fileKey);
702
return next;
703
});
677
- if (lazySource && index >= settledFileCount) {
678
- requestFile(index);
679
- }
704
+ if (lazySource) requestFile(filePath);
705
codeViewReveal.request(file.fileKey);
706
return true;
707
};
@@ -723,9 +748,12 @@ export default function DiffPanel({
748
});
749
};
750
const toggleDiffFileCollapsed = useStableCallback((fileKey: string) => {
751
+ const file = renderableFileEntries.find((file) => file.fileKey === fileKey);
752
+ if (lazySource && file) requestFile(resolveFileDiffPath(file.fileDiff));
753
+ const pending = file?.fileDiff.cacheKey?.endsWith(":pending") === true;
754
updateCollapsedDiffFiles((current) => {
755
const next = new Set(current);
728
- if (next.has(fileKey)) {
756
+ if (pending || next.has(fileKey)) {
757
next.delete(fileKey);
758
} else {
759
next.add(fileKey);
@@ -1273,10 +1301,19 @@ export default function DiffPanel({
1301
) : (
1302
<>
1303
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background">
1304
+ {preview?.incomplete && (
1305
+ <p className="shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-2xs text-muted-foreground">
1306
+ {selectedPatchError
1307
+ ? "Showing tracked changes. Untracked changes could not be loaded. Refresh to retry."
1308
+ : "Showing tracked changes. Checking untracked files..."}
1309
+ </p>
1310
+ )}
1311
{isSelectedPatchTruncated && !lazySource && (
1312
<p className="shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-2xs text-muted-foreground">
1313
This preview exceeds the size limit. Changes shown are incomplete.
1279
- {isGitSelection && selectedGitSource?.files ? " Totals include all changes." : ""}
1314
+ {isGitSelection && selectedGitSource?.files && !preview?.incomplete
1315
+ ? " Totals include all changes."
1316
+ : ""}
1317
</p>
1318
)}
1319
{omittedToolCallFiles > 0 && (
@@ -1389,7 +1426,7 @@ export default function DiffPanel({
1426
<AnnotatableCodeView
1427
key={collapseScopeKey ?? reviewSectionId}
1428
viewerRef={codeViewReveal.attach}
1392
- codeViewKey={`${codeViewMountKey}:${lazySource ? filePatchScope : "preview"}`}
1429
+ codeViewKey={codeViewMountKey}
1430
className="h-full min-h-0 overflow-auto"
1431
files={codeViewFiles}
1432
pendingFiles={pendingFiles}
@@ -1426,15 +1463,19 @@ export default function DiffPanel({
1463
}
1464
: {})}
1465
onRevealSearchMatch={unfoldDiffFile}
1429
- renderHeaderPrefix={(fileDiff, fileKey) => {
1430
- const unavailable = fileDiff.cacheKey?.endsWith(":pending") === true;
1466
+ renderHeaderPrefix={(fileDiff, fileKey, collapsed) => {
1467
return (
1468
<DiffFileCollapseToggle
1469
filePath={resolveFileDiffPath(fileDiff)}
1470
fileKey={fileKey}
1435
- collapsed={unavailable || collapsedDiffFileKeys.has(fileKey)}
1436
- unavailable={unavailable}
1471
+ collapsed={collapsed}
1472
onToggle={toggleDiffFileCollapsed}
1473
+ {...(fileDiff.cacheKey?.endsWith(":pending") &&
1474
+ !collapsedDiffFileKeys.has(fileKey)
1475
+ ? {
1476
+ load: () => requestFile(resolveFileDiffPath(fileDiff)),
1477
+ }
1478
+ : {})}
1479
/>
1480
);
1481
}}
apps/web/src/components/diffs/useReviewFilePatches.browser.test.tsx
new
+145
@@ -0,0 +1,145 @@
1
+import { RegistryContext } from "@effect/atom-react";
2
+import type { ReviewDiffPreviewSource } from "@t3tools/contracts";
3
+import { EnvironmentId } from "@t3tools/contracts";
4
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
5
+import * as Option from "effect/Option";
6
+import { expect, it, vi } from "vite-plus/test";
7
+import { userEvent } from "vite-plus/test/browser";
8
+import { act, render } from "../../../test/render";
9
+
10
+type PatchAtom = Atom.Writable<AsyncResult.AsyncResult<ReviewDiffPreviewSource, Error>>;
11
+const state = vi.hoisted(() => ({ patches: new Map<string, PatchAtom>() }));
12
+vi.mock("~/state/review", () => ({
13
+ reviewEnvironment: {
14
+ diffFilePatch: (target: {
15
+ input: { cacheKey: string; request: { file: { path: string } } };
16
+ }) => {
17
+ const key = JSON.stringify([target.input.cacheKey, target.input.request.file.path]);
18
+ let atom = state.patches.get(key);
19
+ if (!atom) {
20
+ atom = Atom.make<AsyncResult.AsyncResult<ReviewDiffPreviewSource, Error>>(
21
+ AsyncResult.initial(),
22
+ );
23
+ state.patches.set(key, atom);
24
+ }
25
+ return atom;
26
+ },
27
+ },
28
+}));
29
+
30
+import { useReviewFilePatches } from "./useReviewFilePatches";
31
+
32
+function source(paths: string[], hash: string): ReviewDiffPreviewSource {
33
+ return {
34
+ id: "working-tree",
35
+ kind: "working-tree",
36
+ title: "Uncommitted",
37
+ baseRef: "HEAD",
38
+ headRef: null,
39
+ diff: "",
40
+ diffHash: hash,
41
+ truncated: false,
42
+ patchesDeferred: true,
43
+ files: paths.map((path) => ({ path, previousPath: null, additions: 1, deletions: 1 })),
44
+ };
45
+}
46
+
47
+function Probe({ source }: { source: ReviewDiffPreviewSource }) {
48
+ const files = useReviewFilePatches({
49
+ environmentId: EnvironmentId.make("environment"),
50
+ cwd: "/project",
51
+ source,
52
+ baseRef: "HEAD",
53
+ ignoreWhitespace: false,
54
+ theme: "dark",
55
+ previewInput: { cwd: "/project", metadataOnly: true },
56
+ preview: null,
57
+ });
58
+ return (
59
+ <>
60
+ <button onClick={() => files.requestFile("f.txt")}>Open f</button>
61
+ <output>Pending files: {files.remainingFileCount}</output>
62
+ {files.renderableFiles.map((file) => (
63
+ <div key={`${file.name}:${file.type}`}>
64
+ <span>
65
+ {file.name}:{file.hunks.length ? "loaded" : "pending"}
66
+ </span>
67
+ <span>{file.type}</span>
68
+ </div>
69
+ ))}
70
+ </>
71
+ );
72
+}
73
+
74
+it("retains automatic and explicitly opened files through metadata insertion, refresh failure and retry", async () => {
75
+ state.patches.clear();
76
+ const registry = AtomRegistry.make();
77
+ using _registry = { [Symbol.dispose]: () => registry.dispose() };
78
+ const tracked = source(["b.txt", "c.txt", "d.txt", "e.txt", "f.txt"], "tracked");
79
+ const view = (source: ReviewDiffPreviewSource) => (
80
+ <RegistryContext.Provider value={registry}>
81
+ <Probe source={source} />
82
+ </RegistryContext.Provider>
83
+ );
84
+ await using screen = await render(view(tracked));
85
+ await userEvent.click(screen.getByRole("button", { name: "Open f" }));
86
+ const atom = [...state.patches].find(([key]) => JSON.parse(key)[1] === "f.txt")![1];
87
+ const loaded = AsyncResult.success({
88
+ ...tracked,
89
+ diff: "diff --git a/f.txt b/f.txt\n--- a/f.txt\n+++ b/f.txt\n@@ -1 +1 @@\n-old\n+new\n",
90
+ files: tracked.files!.filter((f) => f.path === "f.txt"),
91
+ });
92
+ act(() => registry.set(atom, loaded));
93
+ await expect.element(screen.getByText("f.txt:loaded")).toBeVisible();
94
+ const automatic = [...state.patches].find(([key]) => JSON.parse(key)[1] === "e.txt")![1];
95
+ act(() =>
96
+ registry.set(
97
+ automatic,
98
+ AsyncResult.success({
99
+ ...loaded.value,
100
+ diff: loaded.value.diff.replaceAll("f.txt", "e.txt"),
101
+ files: tracked.files!.filter((file) => file.path === "e.txt"),
102
+ }),
103
+ ),
104
+ );
105
+ await expect.element(screen.getByText("e.txt:loaded")).toBeVisible();
106
+ await screen.rerender(
107
+ view(source(["a-new.txt", ...tracked.files!.map((f) => f.path)], "complete")),
108
+ );
109
+ await expect.element(screen.getByText("e.txt:loaded")).toBeVisible();
110
+ await expect.element(screen.getByText("f.txt:loaded")).toBeVisible();
111
+ act(() =>
112
+ registry.set(
113
+ atom,
114
+ AsyncResult.fail(new Error("refresh failed"), { previousSuccess: Option.some(loaded) }),
115
+ ),
116
+ );
117
+ await expect.element(screen.getByText("f.txt:loaded")).toBeVisible();
118
+ act(() => registry.set(atom, loaded));
119
+ await expect.element(screen.getByText("f.txt:loaded")).toBeVisible();
120
+});
121
+
122
+it("preserves deletion and addition patches for a file replaced by a symlink", async () => {
123
+ state.patches.clear();
124
+ const registry = AtomRegistry.make();
125
+ using _registry = { [Symbol.dispose]: () => registry.dispose() };
126
+ const metadata = source(["entry"], "type-change");
127
+ await using screen = await render(
128
+ <RegistryContext.Provider value={registry}>
129
+ <Probe source={metadata} />
130
+ </RegistryContext.Provider>,
131
+ );
132
+ const atom = [...state.patches.values()][0]!;
133
+ act(() =>
134
+ registry.set(
135
+ atom,
136
+ AsyncResult.success({
137
+ ...metadata,
138
+ diff: "diff --git a/entry b/entry\ndeleted file mode 100644\n--- a/entry\n+++ /dev/null\n@@ -1 +0,0 @@\n-before\ndiff --git a/entry b/entry\nnew file mode 120000\n--- /dev/null\n+++ b/entry\n@@ -0,0 +1 @@\n+target\n\\ No newline at end of file\n",
139
+ }),
140
+ ),
141
+ );
142
+ await expect.element(screen.getByText("deleted", { exact: true })).toBeVisible();
143
+ await expect.element(screen.getByText("new", { exact: true })).toBeVisible();
144
+ await expect.element(screen.getByText("Pending files: 0")).toBeVisible();
145
+});
apps/web/src/components/diffs/useReviewFilePatches.ts
+50
-43
@@ -5,6 +5,7 @@ import type {
5
ReviewDiffPreviewInput,
6
ReviewDiffPreviewSource,
7
} from "@t3tools/contracts";
8
+import * as Option from "effect/Option";
9
import * as AsyncResult from "effect/reactivity/AsyncResult";
10
import * as Atom from "effect/reactivity/Atom";
11
import { useContext, useState } from "react";
@@ -16,7 +17,7 @@ const filePathCollator = new Intl.Collator(undefined, {
17
numeric: true,
18
sensitivity: "base",
19
});
19
-const DEFAULT_INDICES = [0, 1, 2, 3];
20
+const INITIAL_FILE_COUNT = 4;
21
22
export function useReviewFilePatches({
23
environmentId,
@@ -43,11 +44,19 @@ export function useReviewFilePatches({
44
environmentId,
45
cwd,
46
source?.kind,
46
- source?.diffHash,
47
+ source?.baseRef,
48
+ source?.headRef,
49
baseRef,
50
ignoreWhitespace,
51
]);
50
- const [requested, setRequested] = useState(() => ({ scope, indices: DEFAULT_INDICES }));
52
+ const files = sortedReviewFiles(source);
53
+ const automaticPaths = files.slice(0, INITIAL_FILE_COUNT).map((file) => file.path);
54
+ const [requested, setRequested] = useState(() => ({ scope, paths: automaticPaths }));
55
+ const previousPaths = requested.scope === scope ? requested.paths : [];
56
+ const paths = [...new Set([...previousPaths, ...automaticPaths])];
57
+ if (requested.scope !== scope || paths.length !== previousPaths.length) {
58
+ setRequested({ scope, paths });
59
+ }
60
const queries = reviewFileQueries({
61
environmentId,
62
cwd,
@@ -67,7 +76,6 @@ export function useReviewFilePatches({
76
const query = queries.find(({ index }) => files[index]?.path === path)?.query;
77
if (query) registry.refresh(query);
78
});
70
- const files = sortedReviewFiles(source);
79
const pendingIndex = files.findIndex((_, index) => {
80
const patch = patches.get(index);
81
return !patch || patch._tag === "Initial";
@@ -81,39 +89,46 @@ export function useReviewFilePatches({
89
: 0;
90
const requestFiles = (indices: number[]) =>
91
setRequested((current) => {
84
- const previous = current.scope === scope ? current.indices : [0, 1, 2, 3];
85
- const added = indices.filter((index) => !previous.includes(index));
86
- return added.length === 0 ? current : { scope, indices: [...previous, ...added] };
92
+ const previous = current.scope === scope ? current.paths : [];
93
+ const added = indices.flatMap((index) => {
94
+ const path = files[index]?.path;
95
+ return path !== undefined && !previous.includes(path) ? [path] : [];
96
+ });
97
+ return added.length === 0 ? current : { scope, paths: [...previous, ...added] };
98
});
99
// The first unsettled file already requested means a batch is in flight; wait for it.
100
const loadNextFiles = () => {
101
if (queries.some(({ index }) => index === settledFileCount)) return;
102
requestFiles(Array.from({ length: 4 }, (_, index) => settledFileCount + index));
103
};
93
- const requestFile = (index: number) => requestFiles([index]);
104
+ const requestFile = (path: string) =>
105
+ requestFiles([files.findIndex((file) => file.path === path)]);
106
const renderableFiles = source
95
- ? files.map((file, index): FileDiffMetadata => {
107
+ ? files.flatMap((file, index): FileDiffMetadata[] => {
108
const result = patches.get(index);
97
- if (result?._tag === "Success" && result.value.patch?.kind === "files") {
98
- const loaded = result.value.patch.files.find(
109
+ const value = result && Option.getOrUndefined(AsyncResult.value(result));
110
+ if (value?.patch?.kind === "files") {
111
+ const loaded = value.patch.files.filter(
112
(candidate) => resolveFileDiffPath(candidate) === file.path,
113
);
101
- if (loaded) return loaded;
114
+ if (loaded.length > 0) return loaded;
115
}
103
- return {
104
- name: file.path,
105
- ...(file.previousPath ? { prevName: file.previousPath } : {}),
106
- type: file.previousPath ? "rename-changed" : "change",
107
- hunks: [],
108
- additionLines: [],
109
- deletionLines: [],
110
- additionCharacterCount: 0,
111
- deletionCharacterCount: 0,
112
- splitLineCount: 0,
113
- unifiedLineCount: 0,
114
- isPartial: true,
115
- cacheKey: `${scope}:${file.path}:pending`,
116
- };
116
+ return [
117
+ {
118
+ name: file.path,
119
+ ...(file.previousPath ? { prevName: file.previousPath } : {}),
120
+ type: file.previousPath ? "rename-changed" : "change",
121
+ hunks: [],
122
+ additionLines: [],
123
+ deletionLines: [],
124
+ additionCharacterCount: 0,
125
+ deletionCharacterCount: 0,
126
+ splitLineCount: 0,
127
+ unifiedLineCount: 0,
128
+ isPartial: true,
129
+ cacheKey: `${scope}:${file.path}:pending`,
130
+ },
131
+ ];
132
})
133
: (preview?.kind === "files" ? preview.files : []).toSorted((a, b) =>
134
filePathCollator.compare(resolveFileDiffPath(a), resolveFileDiffPath(b)),
@@ -136,23 +151,13 @@ export function useReviewFilePatches({
151
] as const;
152
}),
153
);
139
- const readyFilePaths = new Set(
140
- files
141
- .filter((_, index) => {
142
- const patch = patches.get(index);
143
- return patch && patch._tag !== "Initial";
144
- })
145
- .map((file) => file.path),
146
- );
154
return {
148
- scope,
155
fileStates,
156
isPending: [...patches.values()].some((patch) => patch._tag === "Initial" || patch.waiting),
157
retry,
158
requestFile,
153
- readyFilePaths,
159
renderableFiles,
155
- settledFileCount,
160
+ remainingFileCount: source ? files.length - settledFileCount : 0,
161
loadNextFiles,
162
};
163
}
@@ -174,17 +179,19 @@ function reviewFileQueries({
179
ignoreWhitespace: boolean;
180
previewInput: ReviewDiffPreviewInput | undefined;
181
scope: string;
177
- requested: { scope: string; indices: number[] };
182
+ requested: { scope: string; paths: string[] };
183
}) {
179
- const indices = requested.scope === scope ? requested.indices : DEFAULT_INDICES;
184
const files = sortedReviewFiles(source);
185
+ const paths = new Set([
186
+ ...files.slice(0, INITIAL_FILE_COUNT).map((file) => file.path),
187
+ ...(requested.scope === scope ? requested.paths : []),
188
+ ]);
189
const queries =
190
!environmentId || !cwd || !source
191
? []
184
- : indices
185
- .filter((index) => index < files.length)
186
- .map((index) => {
187
- const file = files[index]!;
192
+ : files
193
+ .flatMap((file, index) => (paths.has(file.path) ? [{ file, index }] : []))
194
+ .map(({ file, index }) => {
195
const target: ReviewPatchTarget = {
196
environmentId,
197
input: {
packages/client-runtime/src/state/review.ts
+23
@@ -35,6 +35,29 @@ export function createReviewEnvironmentAtoms<R, E>(
35
label: "environment-data:review:diff-preview",
36
tag: WS_METHODS.reviewGetDiffPreview,
37
staleTimeMs: 5_000,
38
+ execute: Effect.fn("review.diffPreview")(function* (
39
+ input: ReviewDiffPreviewInput,
40
+ emit: (value: ReviewDiffPreviewResult) => Effect.Effect<void>,
41
+ previous: Option.Option<ReviewDiffPreviewResult>,
42
+ ) {
43
+ const hasCompletePreview = Option.exists(previous, (preview) => !preview.incomplete);
44
+ if (
45
+ !hasCompletePreview &&
46
+ input.sourceKind &&
47
+ !input.file &&
48
+ !input.commitSha &&
49
+ !input.trackedOnly
50
+ ) {
51
+ const tracked = yield* request(WS_METHODS.reviewGetDiffPreview, {
52
+ ...input,
53
+ trackedOnly: true,
54
+ });
55
+ // Older servers ignore trackedOnly and already return the complete preview.
56
+ if (!tracked.incomplete) return tracked;
57
+ yield* emit(tracked);
58
+ }
59
+ return yield* request(WS_METHODS.reviewGetDiffPreview, input);
60
+ }),
61
...(options.onDiffPreviewAnswer === undefined ? {} : { onAnswer: options.onDiffPreviewAnswer }),
62
});
63
// A file patch is a slice of the comparison its preview generated, so a newer preview
packages/client-runtime/src/state/runtime.test.ts
+60
@@ -1,6 +1,7 @@
1
import { describe, expect, it } from "@effect/vitest";
2
import {
3
EnvironmentId,
4
+ type ReviewDiffPreviewInput,
5
type PreviewEvent,
6
type TerminalAttachInput,
7
type TerminalAttachStreamEvent,
@@ -9,6 +10,7 @@ import {
10
WS_METHODS,
11
} from "@t3tools/contracts";
12
import * as Cause from "effect/Cause";
13
+import * as DateTime from "effect/DateTime";
14
import * as Deferred from "effect/Deferred";
15
import * as Effect from "effect/Effect";
16
import * as Exit from "effect/Exit";
@@ -33,6 +35,7 @@ import * as EnvironmentRegistry from "../connection/registry.ts";
35
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
36
import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
37
import type * as RpcSession from "../rpc/session.ts";
38
+import { createReviewEnvironmentAtoms } from "./review.ts";
39
import { createPreviewEnvironmentAtoms } from "./preview.ts";
40
import type { QueryPersistence } from "./queryPersistence.ts";
41
import { createTerminalEnvironmentAtoms } from "./terminal.ts";
@@ -184,6 +187,63 @@ const mountEnvironmentQuery = Effect.fn("TestEnvironmentQuery.mount")(function*
187
return registry;
188
});
189
190
+it.effect("keeps complete review metadata visible while a refresh is held", () =>
191
+ Effect.scoped(
192
+ Effect.gen(function* () {
193
+ const started = yield* Deferred.make<void>();
194
+ const release = yield* Deferred.make<void>();
195
+ let fullReads = 0;
196
+ const rpcSession = {
197
+ client: {
198
+ [WS_METHODS.reviewGetDiffPreview]: (input: ReviewDiffPreviewInput) =>
199
+ Effect.gen(function* () {
200
+ if (!input.trackedOnly && ++fullReads > 1) {
201
+ yield* Deferred.succeed(started, undefined);
202
+ yield* Deferred.await(release);
203
+ }
204
+ return {
205
+ cwd: input.cwd,
206
+ generatedAt: DateTime.makeUnsafe(0),
207
+ ...(input.trackedOnly ? { incomplete: true } : {}),
208
+ sources: [
209
+ {
210
+ id: "working-tree",
211
+ kind: "working-tree" as const,
212
+ title: "Uncommitted",
213
+ baseRef: "HEAD",
214
+ headRef: null,
215
+ diff: "",
216
+ diffHash: String(fullReads),
217
+ truncated: false,
218
+ patchesDeferred: true,
219
+ files: (input.trackedOnly ? ["tracked"] : ["tracked", "untracked"]).map(
220
+ (path) => ({ path, previousPath: null, additions: 1, deletions: 0 }),
221
+ ),
222
+ },
223
+ ],
224
+ };
225
+ }),
226
+ },
227
+ } as unknown as RpcSession.RpcSession;
228
+ const harness = yield* makeEnvironmentQueryHarness(Effect.void, { rpcSession });
229
+ const atom = createReviewEnvironmentAtoms(harness.runtime).diffPreview({
230
+ environmentId: QUERY_ENVIRONMENT.environmentId,
231
+ input: { cwd: "/project", sourceKind: "working-tree", metadataOnly: true },
232
+ });
233
+ const registry = yield* mountEnvironmentQuery(atom);
234
+ expect((yield* readEnvironmentQuery(registry, atom)).sources[0]!.files).toHaveLength(2);
235
+ registry.refresh(atom);
236
+ yield* Deferred.await(started);
237
+ yield* Effect.sync(() => {
238
+ const value = AsyncResult.getOrElse(registry.get(atom), () => null);
239
+ expect(value?.incomplete).not.toBe(true);
240
+ expect(value?.sources[0]!.files).toHaveLength(2);
241
+ }).pipe(Effect.ensuring(Deferred.succeed(release, undefined)));
242
+ expect((yield* readEnvironmentQuery(registry, atom)).sources[0]!.diffHash).toBe("2");
243
+ }),
244
+ ),
245
+);
246
+
247
describe("preview event subscriptions", () => {
248
it.effect("delivers every open and close when RPC events arrive in batches", () =>
249
Effect.scoped(
packages/client-runtime/src/state/runtime.ts
+12
-2
@@ -91,6 +91,7 @@ interface EnvironmentQueryAtomOptions<Input, A, E, R> extends Omit<
91
readonly execute: (
92
input: Input,
93
emit: (value: A) => Effect.Effect<void>,
94
+ previous: Option.Option<A>,
95
) => Effect.Effect<A, E, R>;
96
readonly persistence?: QueryPersistence<A>;
97
readonly staleTimeMs?: number;
@@ -713,7 +714,14 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
714
? runInEnvironment(
715
target.environmentId,
716
options
716
- .execute(target.input, emit)
717
+ .execute(
718
+ target.input,
719
+ emit,
720
+ Option.flatMap(
721
+ get.self<AsyncResult.AsyncResult<A, unknown>>(),
722
+ AsyncResult.value,
723
+ ),
724
+ )
725
.pipe(pendingOnceSessionReplaced(session.value)),
726
)
727
: Effect.never;
@@ -864,6 +872,7 @@ export function createEnvironmentRpcQueryAtomFamily<
872
readonly execute?: (
873
input: EnvironmentRpcInput<TTag>,
874
emit: (value: EnvironmentRpcSuccess<TTag>) => Effect.Effect<void>,
875
+ previous: Option.Option<EnvironmentRpcSuccess<TTag>>,
876
) => Effect.Effect<
877
EnvironmentRpcSuccess<TTag>,
878
EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,
@@ -895,7 +904,8 @@ export function createEnvironmentRpcQueryAtomFamily<
904
execute: (
905
input: EnvironmentRpcInput<TTag>,
906
emit: (value: EnvironmentRpcSuccess<TTag>) => Effect.Effect<void>,
898
- ) => options.execute?.(input, emit) ?? request(options.tag, input),
907
+ previous: Option.Option<EnvironmentRpcSuccess<TTag>>,
908
+ ) => options.execute?.(input, emit, previous) ?? request(options.tag, input),
909
});
910
}
911
packages/contracts/src/review.ts
+5
@@ -8,6 +8,9 @@ export const ReviewDiffPreviewInput = Schema.Struct({
8
baseRef: Schema.optional(TrimmedNonEmptyString),
9
commitSha: Schema.optional(TrimmedNonEmptyString),
10
ignoreWhitespace: Schema.optionalKey(Schema.Boolean),
11
+ sourceKind: Schema.optionalKey(Schema.Literals(["working-tree", "branch-range"])),
12
+ trackedOnly: Schema.optionalKey(Schema.Boolean),
13
+ metadataOnly: Schema.optionalKey(Schema.Boolean),
14
file: Schema.optionalKey(
15
Schema.Struct({
16
path: Schema.NonEmptyString,
@@ -61,6 +64,7 @@ export const ReviewDiffPreviewSource = Schema.Struct({
64
diff: Schema.String,
65
diffHash: TrimmedNonEmptyString,
66
truncated: Schema.Boolean,
67
+ patchesDeferred: Schema.optionalKey(Schema.Boolean),
68
files: Schema.optionalKey(Schema.Array(ReviewDiffFileStat)),
69
});
70
export type ReviewDiffPreviewSource = typeof ReviewDiffPreviewSource.Type;
@@ -86,6 +90,7 @@ export const ReviewDiffPreviewResult = Schema.Struct({
90
cwd: TrimmedNonEmptyString,
91
generatedAt: Schema.DateTimeUtc,
92
sources: Schema.Array(ReviewDiffPreviewSource),
93
+ incomplete: Schema.optionalKey(Schema.Boolean),
94
});
95
export type ReviewDiffPreviewResult = typeof ReviewDiffPreviewResult.Type;
96