The best way to control Claude Code, Codex and more from any computer or phone
fix(mobile): keep visible diff files highlighted (#24682)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 24, 2026 at 20:28 UTC
e666c01aeaee14d486b32e00d938af598d59bd51
11 files changed
+465
-92
apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt
+11
-5
@@ -33,6 +33,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
33
private val onToggleComment by EventDispatcher()
34
private var rows: List<DiffRow> = emptyList()
35
private var visibleRows: List<DiffRow> = emptyList()
36
+ private var visibleRowIndices = IntArray(0)
37
private var collapsedFileIds: Set<String> = emptySet()
38
private var viewedFileIds: Set<String> = emptySet()
39
private var selectedRowIds: Set<String> = emptySet()
@@ -75,8 +76,8 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
76
onDebug(
77
mapOf(
78
"message" to "visible-range",
78
- "firstRowIndex" to first,
79
- "lastRowIndex" to last,
79
+ "firstRowIndex" to visibleRowIndices[first],
80
+ "lastRowIndex" to visibleRowIndices[last],
81
"totalRows" to rows.size,
82
),
83
)
@@ -105,6 +106,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
106
horizontalScroller.forceFinished(true)
107
rows = emptyList()
108
visibleRows = emptyList()
109
+ visibleRowIndices = IntArray(0)
110
canvasView.rows = emptyList()
111
canvasView.tokensByRowId = emptyMap()
112
lastVisibleFileId = null
@@ -393,16 +395,20 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
395
private fun rebuildVisibleRows() {
396
canvasView.setViewportEventsPaused(true)
397
val filtered = ArrayList<DiffRow>(rows.size)
398
+ val indices = IntArray(rows.size)
399
var currentFileCollapsed = false
397
- rows.forEach { row ->
400
+ rows.forEachIndexed { index, row ->
401
if (row.kind == "file") {
402
currentFileCollapsed = collapsedFileIds.contains(row.resolvedFileId)
400
- filtered.add(row)
401
- } else if (!currentFileCollapsed) {
403
+ }
404
+ if (row.kind == "file" || !currentFileCollapsed) {
405
+ indices[filtered.size] = index
406
filtered.add(row)
407
}
408
}
409
visibleRows = filtered
410
+ // JS selects highlights from the full payload, including collapsed rows.
411
+ visibleRowIndices = indices.copyOf(filtered.size)
412
canvasView.rows = filtered
413
canvasView.viewedFileIds = viewedFileIds
414
canvasView.selectedRowIds = selectedRowIds
apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffViewportTest.kt
+57
-4
@@ -117,6 +117,55 @@ class ReviewDiffViewportTest {
117
}
118
}
119
120
+ @Test
121
+ fun collapsedFilesKeepViewportIndicesInTheFullPayload() {
122
+ val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
123
+ val appContext = AppContext()
124
+ val view = T3ReviewDiffView(activity, appContext)
125
+ val decoder = ManualDecoder()
126
+ view.javaClass.getDeclaredField("payloadDecodeExecutor").apply { isAccessible = true }
127
+ .set(view, decoder)
128
+ activity.setContentView(view)
129
+ val canvas = view.getChildAt(0)
130
+ val measure = View.MeasureSpec.makeMeasureSpec(320, View.MeasureSpec.EXACTLY)
131
+ canvas.measure(measure, measure)
132
+ canvas.layout(0, 0, 320, 320)
133
+ try {
134
+ view.setRowsJson(rows("expanded-file", 100001, 100226))
135
+ decoder.completeNext()
136
+ assertEquals(0, ranges(appContext).last()["firstRowIndex"])
137
+ assertTrue((ranges(appContext).last()["lastRowIndex"] as Int) < 100001)
138
+ appContext.events.clear()
139
+
140
+ view.setCollapsedFileIdsJson("[\"first-file\"]")
141
+ val collapsedRange = ranges(appContext).single()
142
+ assertEquals("the collapsed file header stays visible", 0, collapsedRange["firstRowIndex"])
143
+ assertTrue(
144
+ "the following expanded file must be addressed in the full payload",
145
+ (collapsedRange["lastRowIndex"] as Int) > 100001
146
+ )
147
+ assertEquals(100226, collapsedRange["totalRows"])
148
+ appContext.events.clear()
149
+
150
+ view.setInitialFileId("expanded-file")
151
+ assertEquals(100001, ranges(appContext).last()["firstRowIndex"])
152
+ assertEquals(
153
+ "expanded-file",
154
+ appContext.events.last { it.first == "onVisibleFileChange" }.second["fileId"]
155
+ )
156
+ appContext.events.clear()
157
+
158
+ view.setCollapsedFileIdsJson("[]")
159
+ view.setInitialFileId("first-file")
160
+ assertEquals(0, ranges(appContext).last()["firstRowIndex"])
161
+ assertTrue((ranges(appContext).last()["lastRowIndex"] as Int) < 100001)
162
+ } finally {
163
+ view.cleanup()
164
+ activity.finish()
165
+ appContext.events.clear()
166
+ }
167
+ }
168
+
169
private fun rowTop(canvas: View, index: Int): Int = canvas.javaClass
170
.getDeclaredMethod("rowTop", Int::class.javaPrimitiveType).apply { isAccessible = true }
171
.invoke(canvas, index) as Int
@@ -125,13 +174,17 @@ class ReviewDiffViewportTest {
174
.filter { (name, payload) -> name == "onDebug" && payload["message"] == "visible-range" }
175
.map { it.second }
176
128
- private fun rows(selectedFileId: String): String = JSONArray().apply {
129
- for (index in 0 until 1000) {
177
+ private fun rows(
178
+ selectedFileId: String,
179
+ selectedStart: Int = 900,
180
+ count: Int = 1000
181
+ ): String = JSONArray().apply {
182
+ for (index in 0 until count) {
183
put(
184
JSONObject().apply {
185
put("id", "$selectedFileId:$index")
133
- put("kind", if (index == 0 || index == 900) "file" else "line")
134
- put("fileId", if (index < 900) "first-file" else selectedFileId)
186
+ put("kind", if (index == 0 || index == selectedStart) "file" else "line")
187
+ put("fileId", if (index < selectedStart) "first-file" else selectedFileId)
188
put("content", "const value = $index")
189
}
190
)
apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts
+92
@@ -131,6 +131,98 @@ describe("highlightNativeReviewDiffVisibleRows", () => {
131
expect([...new Set(loadedFiles)].sort()).toEqual(["file-7", "file-8"]);
132
});
133
134
+ it("skips collapsed code before the row cap and restores it on expansion", async () => {
135
+ const collapsedSource = Array.from(
136
+ { length: 100_000 },
137
+ (_, index) => `int hidden${index} = 1;`,
138
+ );
139
+ const expandedSource = [
140
+ "/* open",
141
+ ...Array.from({ length: 222 }, () => "still a comment"),
142
+ "*/ int visible = 1;",
143
+ ];
144
+ const collapsedLoad = vi.fn(async () => ({
145
+ oldContents: "",
146
+ newContents: collapsedSource.join("\n"),
147
+ }));
148
+ const expandedLoad = vi.fn(async () => ({
149
+ oldContents: "",
150
+ newContents: expandedSource.join("\n"),
151
+ }));
152
+ const files = [
153
+ {
154
+ ...TYPESCRIPT_FILE,
155
+ id: "collapsed",
156
+ language: "c",
157
+ path: "highlights.c",
158
+ loadContents: collapsedLoad,
159
+ },
160
+ {
161
+ ...TYPESCRIPT_FILE,
162
+ id: "expanded",
163
+ language: "c",
164
+ path: "highlights.h",
165
+ loadContents: expandedLoad,
166
+ },
167
+ ];
168
+ const rows = [collapsedSource, expandedSource].flatMap((source, fileIndex) => {
169
+ const fileId = files[fileIndex]!.id;
170
+ return [
171
+ { kind: "file", id: `${fileId}-header`, fileId },
172
+ ...source.map((content, index) => ({
173
+ ...makeLine({
174
+ id: `${fileId}-${index}`,
175
+ content,
176
+ change: "add",
177
+ newLineNumber: index + 1,
178
+ }),
179
+ fileId,
180
+ })),
181
+ ] satisfies NativeReviewDiffRow[];
182
+ });
183
+ const input = {
184
+ rows,
185
+ files,
186
+ scheme: "dark" as const,
187
+ firstRowIndex: 0,
188
+ lastRowIndex: rows.length - 1,
189
+ };
190
+ // A collapsed header and the next expanded header can share an iOS viewport,
191
+ // with 100,000 zero-height code rows between their canonical indices.
192
+ const viewport = await highlightNativeReviewDiffVisibleRows({
193
+ ...input,
194
+ collapsedFileIds: new Set(["collapsed"]),
195
+ overscanRows: 0,
196
+ });
197
+ expect(Object.keys(viewport.tokensByRowId)).toEqual(
198
+ expandedSource.map((_, index) => `expanded-${index}`),
199
+ );
200
+ const overscan = await highlightNativeReviewDiffVisibleRows({
201
+ ...input,
202
+ collapsedFileIds: new Set(["collapsed"]),
203
+ lastRowIndex: 100_002,
204
+ alreadyHighlightedRowIds: new Set(["expanded-0"]),
205
+ });
206
+ expect(Object.keys(overscan.tokensByRowId)).toEqual(
207
+ Array.from({ length: 160 }, (_, index) => `expanded-${index + 1}`),
208
+ );
209
+ expect(overscan.tokensByRowId["expanded-1"]).toEqual(
210
+ highlightCode(expandedSource.join("\n"), "c", "dark")[1],
211
+ );
212
+ expect(collapsedLoad).not.toHaveBeenCalled();
213
+ expect(expandedLoad).toHaveBeenCalled();
214
+
215
+ const expanded = await highlightNativeReviewDiffVisibleRows({
216
+ ...input,
217
+ lastRowIndex: 400,
218
+ collapsedFileIds: new Set(),
219
+ overscanRows: 0,
220
+ });
221
+ expect(expanded.rowCount).toBe(360);
222
+ expect(expanded.tokensByRowId["collapsed-0"]).toBeDefined();
223
+ expect(collapsedLoad).toHaveBeenCalledTimes(1);
224
+ });
225
+
226
it("delivers the dominant viewport file before fetching a smaller blocked neighbor", async () => {
227
const neighborStarted = Promise.withResolvers<void>();
228
const neighborResponse = Promise.withResolvers<{ oldContents: string; newContents: string }>();
apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts
+2
@@ -18,6 +18,7 @@ export interface HighlightNativeReviewDiffVisibleRowsInput {
18
readonly overscanRows?: number;
19
readonly maxRows?: number;
20
readonly alreadyHighlightedRowIds?: ReadonlySet<string>;
21
+ readonly collapsedFileIds?: ReadonlySet<string>;
22
readonly signal?: AbortSignal;
23
readonly onChunk?: (chunk: NativeReviewDiffHighlightChunk) => void;
24
}
@@ -290,6 +291,7 @@ export async function highlightNativeReviewDiffVisibleRows(
291
row &&
292
isHighlightableLineRow(row) &&
293
visibleFileIds.has(row.fileId) &&
294
+ !input.collapsedFileIds?.has(row.fileId) &&
295
!input.alreadyHighlightedRowIds?.has(row.id) &&
296
fileMap.has(row.fileId)
297
) {
apps/mobile/src/features/diffs/nativeReviewDiffSource.test.ts
+38
@@ -1,6 +1,7 @@
1
import { expect, it, vi } from "vite-plus/test";
2
3
import { createNativeReviewDiffSourceLoader } from "./nativeReviewDiffSource";
4
+import * as DiffHighlightTrace from "./nativeReviewDiffTrace";
5
import type { NativeReviewDiffSource } from "./nativeReviewDiffTypes";
6
7
const SOURCE = { oldContents: "const before = true;", newContents: "const after = false;" };
@@ -149,3 +150,40 @@ it("serializes RPCs and drops cancelled queued files", async () => {
150
await load("next.ts");
151
expect(fetch.mock.calls).toEqual([["active.ts"], ["next.ts"]]);
152
});
153
+
154
+it("starts a shared fresh request for a file whose cancelled request was dropped", async () => {
155
+ const started = Promise.withResolvers<void>();
156
+ const response = Promise.withResolvers<NativeReviewDiffSource>();
157
+ const dropped = Promise.withResolvers<void>();
158
+ const replacementStarted = Promise.withResolvers<void>();
159
+ const replacementResponse = Promise.withResolvers<NativeReviewDiffSource>();
160
+ using _trace = vi.spyOn(DiffHighlightTrace, "traceDiffHighlight").mockImplementation((event) => {
161
+ if (event === "source-dropped") dropped.resolve();
162
+ });
163
+ const fetch = vi.fn((file: string) => {
164
+ if (file === "active.ts") {
165
+ started.resolve();
166
+ return response.promise;
167
+ }
168
+ replacementStarted.resolve();
169
+ return replacementResponse.promise;
170
+ });
171
+ const load = createNativeReviewDiffSourceLoader(fetch);
172
+ const active = load("active.ts");
173
+ await started.promise;
174
+ const controller = new AbortController();
175
+ const queued = load("cancelled.ts", controller.signal);
176
+ controller.abort();
177
+ expect(await queued).toBeNull();
178
+ response.resolve(SOURCE);
179
+ await dropped.promise;
180
+ const fresh = load("cancelled.ts");
181
+ // Settling first means the fresh caller joined the dropped request instead of fetching.
182
+ await Promise.race([replacementStarted.promise, fresh]);
183
+ const shared = load("cancelled.ts");
184
+ replacementResponse.resolve(SOURCE);
185
+ expect(await fresh).toBe(SOURCE);
186
+ expect(await shared).toBe(SOURCE);
187
+ expect(await active).toBe(SOURCE);
188
+ expect(fetch.mock.calls).toEqual([["active.ts"], ["cancelled.ts"]]);
189
+});
apps/mobile/src/features/diffs/nativeReviewDiffSource.ts
+5
-1
@@ -114,6 +114,8 @@ export function createNativeReviewDiffSourceLoader<FileId>(
114
const promise = tail
115
.then(async () => {
116
if ([...subscribers].every((subscriber) => subscriber?.aborted)) {
117
+ // A cancelled request must stop being shareable before its promise settles.
118
+ pending.delete(fileId);
119
traceDiffHighlight("source-dropped", { loader, file });
120
return null;
121
}
@@ -169,7 +171,9 @@ export function createNativeReviewDiffSourceLoader<FileId>(
171
throw error;
172
}
173
})
172
- .finally(() => pending.delete(fileId));
174
+ .finally(() => {
175
+ if (pending.get(fileId) === request) pending.delete(fileId);
176
+ });
177
tail = promise.then(
178
() => {},
179
() => {},
apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx
+38
-1
@@ -192,13 +192,14 @@ function setup(integrated = false) {
192
rowIdByCommentLineId: new Map(),
193
};
194
const ids: string[] = [];
195
+ let collapsedFileIds: ReadonlyArray<string> = ids;
196
function PullRequestDiff({ targetFileId }: { targetFileId?: string }) {
197
const bridge = useNativeReviewDiffBridge({
198
threadKey: null,
199
sectionId: "pull-request:test:1:all",
200
diff: "test diff",
201
data,
201
- collapsedFileIds: ids,
202
+ collapsedFileIds,
203
viewedFileIds: ids,
204
selectedRowIds: ids,
205
canHighlight: true,
@@ -247,6 +248,10 @@ function setup(integrated = false) {
248
async mountPullRequest(targetFileId?: string) {
249
await act(async () => root.render(<PullRequestDiff targetFileId={targetFileId} />));
250
},
251
+ async collapseFiles(fileIds: ReadonlyArray<string>) {
252
+ collapsedFileIds = fileIds;
253
+ await act(async () => root.render(<PullRequestDiff />));
254
+ },
255
async updateComment() {
256
data = {
257
...data,
@@ -403,3 +408,35 @@ it("recognizes registration races for the installed native view name", async ()
408
),
409
).toBe(true);
410
});
411
+
412
+it("cancels stale collapse work and highlights expansion without resetting accepted tokens", async () => {
413
+ using screen = setup(true);
414
+ await screen.mountPullRequest();
415
+ await screen.jump(0);
416
+ await screen.deliverPayloads();
417
+ expect(screen.tokenRows).toBe("r0");
418
+
419
+ const response = Promise.withResolvers<void>();
420
+ const highlight = mocks.highlight.getMockImplementation()!;
421
+ mocks.highlight.mockImplementation(async (input: HighlightNativeReviewDiffVisibleRowsInput) => {
422
+ if (input.firstRowIndex === 400) {
423
+ await response.promise;
424
+ if (input.collapsedFileIds?.has("last-file")) {
425
+ return { tokensByRowId: {}, rowCount: 0, retryableRowIds: [], durationMs: 0 };
426
+ }
427
+ }
428
+ return highlight(input);
429
+ });
430
+ await screen.jump(400);
431
+ await screen.collapseFiles(["last-file"]);
432
+ await act(async () => response.resolve());
433
+ await screen.deliverPayloads();
434
+ expect(screen.tokenRows).toBe("r0");
435
+
436
+ await screen.collapseFiles([]);
437
+ await screen.deliverPayloads();
438
+ expect(screen.tokenRows).toBe("r0,r400");
439
+ await screen.jump(0);
440
+ await screen.deliverPayloads();
441
+ expect(screen.tokenRows).toBe("r0,r400");
442
+});
apps/mobile/src/features/review/useNativeReviewDiffBridge.ts
+2
@@ -43,6 +43,7 @@ export function useNativeReviewDiffBridge(input: {
43
() => createNativeReviewDiffTheme(scheme, themeId, appTheme),
44
[appTheme, scheme, themeId],
45
);
46
+ const collapsedFileIdsSet = useMemo(() => new Set(collapsedFileIds), [collapsedFileIds]);
47
const rowsJson = useMemo(() => JSON.stringify(data.rows), [data.rows]);
48
const collapsedFileIdsJson = useMemo(() => JSON.stringify(collapsedFileIds), [collapsedFileIds]);
49
const viewedFileIdsJson = useMemo(() => JSON.stringify(viewedFileIds), [viewedFileIds]);
@@ -69,6 +70,7 @@ export function useNativeReviewDiffBridge(input: {
70
useNativeReviewDiffHighlighting({
71
files: data.files,
72
rows: data.rows,
73
+ collapsedFileIds: collapsedFileIdsSet,
74
scheme,
75
resetKey: tokensResetKey,
76
enabled: canHighlight,
apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts
+5
-2
@@ -25,10 +25,11 @@ export function useNativeReviewDiffHighlighting(input: {
25
readonly files: ReadonlyArray<NativeReviewDiffFile>;
26
readonly rows: ReadonlyArray<NativeReviewDiffRow>;
27
readonly scheme: HighlightScheme;
28
+ readonly collapsedFileIds: ReadonlySet<string>;
29
readonly resetKey: string;
30
readonly enabled: boolean;
31
}) {
31
- const { enabled, files, resetKey, rows, scheme } = input;
32
+ const { collapsedFileIds, enabled, files, resetKey, rows, scheme } = input;
33
const highlightedRowIdsRef = useRef<Set<string>>(new Set());
34
const viewportScope = `${enabled}:${resetKey}:${rows.length}`;
35
const [viewport, setViewport] = useState<{
@@ -120,6 +121,7 @@ export function useNativeReviewDiffHighlighting(input: {
121
files,
122
rows,
123
scheme,
124
+ collapsedFileIds,
125
firstRowIndex: requestRange.firstRowIndex,
126
lastRowIndex: requestRange.lastRowIndex,
127
overscanRows,
@@ -140,6 +142,7 @@ export function useNativeReviewDiffHighlighting(input: {
142
error: squashAtomCommandFailure(settled),
143
resetKey,
144
scheme,
145
+ collapsedFileIds,
146
firstRowIndex: requestRange.firstRowIndex,
147
lastRowIndex: requestRange.lastRowIndex,
148
});
@@ -171,7 +174,7 @@ export function useNativeReviewDiffHighlighting(input: {
174
traceDiffHighlight("viewport-abort", { generation, reset });
175
abortController.abort();
176
};
174
- }, [enabled, files, resetKey, rows, scheme, viewport, viewportScope]);
177
+ }, [collapsedFileIds, enabled, files, resetKey, rows, scheme, viewport, viewportScope]);
178
179
const acknowledgeTokenPatch = useCallback((payload: Readonly<Record<string, unknown>>) => {
180
const pending = pendingPatchesRef.current;
apps/server/src/pullRequest/PullRequestService.test.ts
+196
-70
@@ -3981,78 +3981,204 @@ it.effect("pauses uncached activity on a host after one activity read is rate li
3981
}),
3982
);
3983
3984
-it.effect("expands only files the change request changes, across every slice of its diff", () =>
3985
- Effect.gen(function* () {
3986
- const read: Array<string> = [];
3987
- const service = yield* makeService({
3988
- projects: [
3989
- project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),
3990
- ],
3991
- providers: [
3992
- fakePullRequestProvider(SourceControlProviderKind.make("github"), {
3993
- getDiff: (input) =>
3994
- Effect.succeed(
3995
- input.cursor === undefined
3996
- ? {
3997
- patch: [
3998
- "diff --git a/src/old.ts b/src/new.ts",
3999
- "rename from src/old.ts",
4000
- "rename to src/new.ts",
4001
- "--- a/src/old.ts",
4002
- "+++ b/src/new.ts",
4003
- "",
4004
- ].join("\n"),
4005
- truncated: false,
4006
- nextCursor: "2",
4007
- }
4008
- : {
4009
- patch: [
4010
- "diff --git a/gone.md b/gone.md",
4011
- "deleted file mode 100644",
4012
- "--- a/gone.md",
4013
- "+++ /dev/null",
4014
- "",
4015
- ].join("\n"),
4016
- truncated: false,
4017
- nextCursor: null,
4018
- },
4019
- ),
4020
- getDiffFileContents: (input) =>
4021
- Effect.sync(() => {
4022
- read.push(`${input.oldPath}->${input.newPath}`);
4023
- return { oldContents: "old", newContents: "new" };
4024
- }),
4025
- }),
4026
- ],
4027
- });
4028
- const ref = { projectId: "p1" as ProjectId, repository: "pingdotgg/t3code", number: 1 };
3984
+it.effect(
3985
+ "reuses loaded oversized diff slices to expand only files the change request changes",
3986
+ () =>
3987
+ Effect.gen(function* () {
3988
+ const read: Array<string> = [];
3989
+ const diffReads: Array<string | undefined> = [];
3990
+ const service = yield* makeService({
3991
+ projects: [
3992
+ project({
3993
+ id: "p1",
3994
+ title: "t3code",
3995
+ workspaceRoot: "/a",
3996
+ repository: "pingdotgg/t3code",
3997
+ }),
3998
+ ],
3999
+ providers: [
4000
+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {
4001
+ getDiff: (input) =>
4002
+ Effect.sync(() => {
4003
+ diffReads.push(input.cursor);
4004
+ return input.cursor === undefined
4005
+ ? {
4006
+ patch: [
4007
+ "diff --git a/src/old.ts b/src/new.ts",
4008
+ "rename from src/old.ts",
4009
+ "rename to src/new.ts",
4010
+ "--- a/src/old.ts",
4011
+ "+++ b/src/new.ts",
4012
+ `+${"x".repeat(300_000)}`,
4013
+ "",
4014
+ ].join("\n"),
4015
+ truncated: false,
4016
+ nextCursor: "2",
4017
+ }
4018
+ : {
4019
+ patch: [
4020
+ "diff --git a/gone.md b/gone.md",
4021
+ "deleted file mode 100644",
4022
+ "--- a/gone.md",
4023
+ "+++ /dev/null",
4024
+ `-${"x".repeat(300_000)}`,
4025
+ "",
4026
+ ].join("\n"),
4027
+ truncated: false,
4028
+ nextCursor: null,
4029
+ };
4030
+ }),
4031
+ getDiffFileContents: (input) =>
4032
+ Effect.sync(() => {
4033
+ read.push(`${input.oldPath}->${input.newPath}`);
4034
+ return { oldContents: "old", newContents: "new" };
4035
+ }),
4036
+ }),
4037
+ ],
4038
+ });
4039
+ const ref = { projectId: "p1" as ProjectId, repository: "pingdotgg/t3code", number: 1 };
4040
4030
- yield* service.diffFileContents({
4031
- ...ref,
4032
- changeType: "rename-changed",
4033
- oldPath: "src/old.ts",
4034
- newPath: "src/new.ts",
4035
- });
4036
- yield* service.diffFileContents({
4037
- ...ref,
4038
- changeType: "deleted",
4039
- oldPath: "gone.md",
4040
- newPath: "gone.md",
4041
- });
4042
- const outside = yield* service
4043
- .diffFileContents({ ...ref, changeType: "deleted", oldPath: ".env", newPath: ".env" })
4044
- .pipe(Effect.flip);
4045
- const halfRename = yield* service
4046
- .diffFileContents({
4041
+ yield* service.diff(ref);
4042
+ yield* service.diff({ ...ref, cursor: "2" });
4043
+
4044
+ yield* service.diffFileContents({
4045
...ref,
4048
- changeType: "change",
4049
- oldPath: "src/secret.ts",
4046
+ changeType: "rename-changed",
4047
+ oldPath: "src/old.ts",
4048
newPath: "src/new.ts",
4051
- })
4052
- .pipe(Effect.flip);
4049
+ });
4050
+ yield* service.diffFileContents({
4051
+ ...ref,
4052
+ changeType: "deleted",
4053
+ oldPath: "gone.md",
4054
+ newPath: "gone.md",
4055
+ });
4056
+ const outside = yield* service
4057
+ .diffFileContents({ ...ref, changeType: "deleted", oldPath: ".env", newPath: ".env" })
4058
+ .pipe(Effect.flip);
4059
+ const halfRename = yield* service
4060
+ .diffFileContents({
4061
+ ...ref,
4062
+ changeType: "change",
4063
+ oldPath: "src/secret.ts",
4064
+ newPath: "src/new.ts",
4065
+ })
4066
+ .pipe(Effect.flip);
4067
+
4068
+ assert.strictEqual(outside._tag, "PullRequestOperationError");
4069
+ assert.strictEqual(halfRename._tag, "PullRequestOperationError");
4070
+ assert.deepStrictEqual(read, ["src/old.ts->src/new.ts", "gone.md->gone.md"]);
4071
+ assert.deepStrictEqual(diffReads, [undefined, "2"]);
4072
+ }),
4073
+);
4074
4054
- assert.strictEqual(outside._tag, "PullRequestOperationError");
4055
- assert.strictEqual(halfRename._tag, "PullRequestOperationError");
4056
- assert.deepStrictEqual(read, ["src/old.ts->src/new.ts", "gone.md->gone.md"]);
4057
- }),
4075
+// Refresh and expiry are covered by the in-flight test below; repository and number share the ref key.
4076
+it.effect.each(["commit", "credential"] as const)(
4077
+ "does not reuse loaded diff membership after changing %s",
4078
+ (boundary) =>
4079
+ Effect.gen(function* () {
4080
+ let credential = "broad";
4081
+ let diffReads = 0;
4082
+ let contentReads = 0;
4083
+ const service = yield* makeService({
4084
+ projects: [
4085
+ project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
4086
+ ],
4087
+ providers: [
4088
+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {
4089
+ withVerifiedCredential: (_, use) =>
4090
+ Effect.suspend(() =>
4091
+ use({ accountId: "101", viewer: "octocat", credentialFingerprint: credential }),
4092
+ ),
4093
+ getDiff: () =>
4094
+ Effect.sync(() => ({
4095
+ patch:
4096
+ ++diffReads === 1
4097
+ ? `diff --git a/private.ts b/private.ts\n--- a/private.ts\n+++ b/private.ts\n+${"x".repeat(300_000)}\n`
4098
+ : "",
4099
+ truncated: false,
4100
+ nextCursor: null,
4101
+ })),
4102
+ getDiffFileContents: () =>
4103
+ Effect.sync(() => {
4104
+ contentReads += 1;
4105
+ return { oldContents: "old", newContents: "new" };
4106
+ }),
4107
+ }),
4108
+ ],
4109
+ });
4110
+ const ref = {
4111
+ projectId: "p1" as ProjectId,
4112
+ repository: "acme/web",
4113
+ number: 1,
4114
+ host: "github.com",
4115
+ expectedAccountId: "101",
4116
+ };
4117
+ // Load at a commit and expand without one so the commit must be part of the membership key.
4118
+ const loaded = boundary === "commit" ? { ...ref, commit: "a".repeat(40) } : ref;
4119
+ yield* service.withRoutingCredential(loaded, service.diff(loaded));
4120
+ if (boundary === "credential") credential = "restricted";
4121
+ const input = {
4122
+ ...ref,
4123
+ changeType: "change" as const,
4124
+ oldPath: "private.ts",
4125
+ newPath: "private.ts",
4126
+ };
4127
+ const error = yield* service
4128
+ .withRoutingCredential(input, service.diffFileContents(input))
4129
+ .pipe(Effect.flip);
4130
+ assert.strictEqual(error._tag, "PullRequestOperationError");
4131
+ assert.strictEqual(error.reason, "not-found");
4132
+ assert.strictEqual(diffReads, 2);
4133
+ assert.strictEqual(contentReads, 0);
4134
+ }),
4135
+);
4136
+
4137
+it.effect.each(["expiry", "refresh"] as const)(
4138
+ "keeps a loaded diff's original membership scope through an in-flight %s",
4139
+ (boundary) =>
4140
+ Effect.gen(function* () {
4141
+ const started = yield* Deferred.make<void>();
4142
+ const release = yield* Deferred.make<void>();
4143
+ let diffReads = 0;
4144
+ const service = yield* makeService({
4145
+ projects: [
4146
+ project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
4147
+ ],
4148
+ providers: [
4149
+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {
4150
+ getDiff: () =>
4151
+ Effect.gen(function* () {
4152
+ if (++diffReads !== 1) return { patch: "", truncated: false, nextCursor: null };
4153
+ yield* Deferred.succeed(started, undefined);
4154
+ yield* Deferred.await(release);
4155
+ return {
4156
+ patch: `diff --git a/private.ts b/private.ts\n--- a/private.ts\n+++ b/private.ts\n+${"x".repeat(300_000)}\n`,
4157
+ truncated: false,
4158
+ nextCursor: null,
4159
+ };
4160
+ }),
4161
+ getDiffFileContents: () => Effect.die("an expired file must not be read"),
4162
+ }),
4163
+ ],
4164
+ });
4165
+ const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
4166
+ const loading = yield* Effect.forkChild(service.diff(ref));
4167
+ yield* Deferred.await(started);
4168
+ if (boundary === "expiry") yield* TestClock.adjust("61 seconds");
4169
+ else yield* service.invalidate({ reference: ref });
4170
+ yield* Deferred.succeed(release, undefined);
4171
+ yield* Fiber.join(loading);
4172
+ const error = yield* service
4173
+ .diffFileContents({
4174
+ ...ref,
4175
+ changeType: "change",
4176
+ oldPath: "private.ts",
4177
+ newPath: "private.ts",
4178
+ })
4179
+ .pipe(Effect.flip);
4180
+ assert.strictEqual(error._tag, "PullRequestOperationError");
4181
+ assert.strictEqual(error.reason, "not-found");
4182
+ assert.strictEqual(diffReads, 2);
4183
+ }),
4184
);
apps/server/src/pullRequest/PullRequestService.ts
+19
-9
@@ -3202,7 +3202,14 @@ export const make = Effect.gen(function* () {
3202
...refOfCacheKey(reference),
3203
...(cursor === null ? {} : { cursor }),
3204
...(commit === null ? {} : { commit }),
3205
- } as PullRequestDiffInput);
3205
+ } as PullRequestDiffInput).pipe(
3206
+ observeRead,
3207
+ Effect.map(({ value, observedAt }) => {
3208
+ // Keep the loader's epoch and read time if a refresh occurs during the provider read.
3209
+ diffFiles.record(JSON.stringify([reference, cursor, commit]), value, observedAt);
3210
+ return value;
3211
+ }),
3212
+ );
3213
},
3214
{
3215
capacity: DIFF_CACHE_CAPACITY,
@@ -3468,14 +3475,9 @@ export const make = Effect.gen(function* () {
3475
const fileKey = (oldPath: string, newPath: string) => JSON.stringify([oldPath, newPath]);
3476
const sliceKey = (input: PullRequestDiffInput) =>
3477
JSON.stringify([refCacheKey(input), input.cursor ?? null, input.commit ?? null]);
3471
- const read = Effect.fn("PullRequestService.read")(function* (input: PullRequestDiffInput) {
3472
- const key = sliceKey(input);
3473
- const now = yield* Clock.currentTimeMillis;
3474
- const cached = held.get(key);
3475
- if (cached !== undefined && now - cached.at <= ttlMs) return cached;
3476
- const slice = yield* diff(input);
3478
+ const record = (key: string, slice: PullRequestDiffResult, at: number) => {
3479
const entry = {
3478
- at: now,
3480
+ at,
3481
files: new Set(
3482
parseDiffFilePaths(slice.patch).map((file) =>
3483
fileKey(file.oldPath ?? file.newPath ?? "", file.newPath ?? file.oldPath ?? ""),
@@ -3490,8 +3492,16 @@ export const make = Effect.gen(function* () {
3492
}
3493
held.set(key, entry);
3494
return entry;
3495
+ };
3496
+ const read = Effect.fn("PullRequestService.read")(function* (input: PullRequestDiffInput) {
3497
+ const key = sliceKey(input);
3498
+ const now = yield* Clock.currentTimeMillis;
3499
+ const cached = held.get(key);
3500
+ if (cached !== undefined && now - cached.at <= ttlMs) return cached;
3501
+ const slice = yield* diff(input);
3502
+ return record(key, slice, now);
3503
});
3494
- return { read: credentialCached(read), fileKey };
3504
+ return { read: credentialCached(read), record, fileKey };
3505
})();
3506
const changesFile = (input: PullRequestDiffFileContentsInput) => {
3507
const wanted = diffFiles.fileKey(input.oldPath, input.newPath);