Skip to content
TypeScript

fix(mobile): keep visible diff files highlighted (#24682)

Julius Marmingee666c01aeaee
diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt
index a15c3ada293..8426ddb565a 100644
--- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt
+++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt
@@ -33,6 +33,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
private val onToggleComment by EventDispatcher()
private var rows: List<DiffRow> = emptyList()
private var visibleRows: List<DiffRow> = emptyList()
+ private var visibleRowIndices = IntArray(0)
private var collapsedFileIds: Set<String> = emptySet()
private var viewedFileIds: Set<String> = emptySet()
private var selectedRowIds: Set<String> = emptySet()
@@ -75,8 +76,8 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
onDebug(
mapOf(
"message" to "visible-range",
- "firstRowIndex" to first,
- "lastRowIndex" to last,
+ "firstRowIndex" to visibleRowIndices[first],
+ "lastRowIndex" to visibleRowIndices[last],
"totalRows" to rows.size,
),
)
@@ -105,6 +106,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
horizontalScroller.forceFinished(true)
rows = emptyList()
visibleRows = emptyList()
+ visibleRowIndices = IntArray(0)
canvasView.rows = emptyList()
canvasView.tokensByRowId = emptyMap()
lastVisibleFileId = null
@@ -393,16 +395,20 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
private fun rebuildVisibleRows() {
canvasView.setViewportEventsPaused(true)
val filtered = ArrayList<DiffRow>(rows.size)
+ val indices = IntArray(rows.size)
var currentFileCollapsed = false
- rows.forEach { row ->
+ rows.forEachIndexed { index, row ->
if (row.kind == "file") {
currentFileCollapsed = collapsedFileIds.contains(row.resolvedFileId)
- filtered.add(row)
- } else if (!currentFileCollapsed) {
+ }
+ if (row.kind == "file" || !currentFileCollapsed) {
+ indices[filtered.size] = index
filtered.add(row)
}
}
visibleRows = filtered
+ // JS selects highlights from the full payload, including collapsed rows.
+ visibleRowIndices = indices.copyOf(filtered.size)
canvasView.rows = filtered
canvasView.viewedFileIds = viewedFileIds
canvasView.selectedRowIds = selectedRowIds
diff --git a/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffViewportTest.kt b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffViewportTest.kt
index 28935a11db8..10d9a45107c 100644
--- a/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffViewportTest.kt
+++ b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffViewportTest.kt
@@ -117,6 +117,55 @@ class ReviewDiffViewportTest {
}
}
+ @Test
+ fun collapsedFilesKeepViewportIndicesInTheFullPayload() {
+ val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
+ val appContext = AppContext()
+ val view = T3ReviewDiffView(activity, appContext)
+ val decoder = ManualDecoder()
+ view.javaClass.getDeclaredField("payloadDecodeExecutor").apply { isAccessible = true }
+ .set(view, decoder)
+ activity.setContentView(view)
+ val canvas = view.getChildAt(0)
+ val measure = View.MeasureSpec.makeMeasureSpec(320, View.MeasureSpec.EXACTLY)
+ canvas.measure(measure, measure)
+ canvas.layout(0, 0, 320, 320)
+ try {
+ view.setRowsJson(rows("expanded-file", 100001, 100226))
+ decoder.completeNext()
+ assertEquals(0, ranges(appContext).last()["firstRowIndex"])
+ assertTrue((ranges(appContext).last()["lastRowIndex"] as Int) < 100001)
+ appContext.events.clear()
+
+ view.setCollapsedFileIdsJson("[\"first-file\"]")
+ val collapsedRange = ranges(appContext).single()
+ assertEquals("the collapsed file header stays visible", 0, collapsedRange["firstRowIndex"])
+ assertTrue(
+ "the following expanded file must be addressed in the full payload",
+ (collapsedRange["lastRowIndex"] as Int) > 100001
+ )
+ assertEquals(100226, collapsedRange["totalRows"])
+ appContext.events.clear()
+
+ view.setInitialFileId("expanded-file")
+ assertEquals(100001, ranges(appContext).last()["firstRowIndex"])
+ assertEquals(
+ "expanded-file",
+ appContext.events.last { it.first == "onVisibleFileChange" }.second["fileId"]
+ )
+ appContext.events.clear()
+
+ view.setCollapsedFileIdsJson("[]")
+ view.setInitialFileId("first-file")
+ assertEquals(0, ranges(appContext).last()["firstRowIndex"])
+ assertTrue((ranges(appContext).last()["lastRowIndex"] as Int) < 100001)
+ } finally {
+ view.cleanup()
+ activity.finish()
+ appContext.events.clear()
+ }
+ }
+
private fun rowTop(canvas: View, index: Int): Int = canvas.javaClass
.getDeclaredMethod("rowTop", Int::class.javaPrimitiveType).apply { isAccessible = true }
.invoke(canvas, index) as Int
@@ -125,13 +174,17 @@ class ReviewDiffViewportTest {
.filter { (name, payload) -> name == "onDebug" && payload["message"] == "visible-range" }
.map { it.second }
- private fun rows(selectedFileId: String): String = JSONArray().apply {
- for (index in 0 until 1000) {
+ private fun rows(
+ selectedFileId: String,
+ selectedStart: Int = 900,
+ count: Int = 1000
+ ): String = JSONArray().apply {
+ for (index in 0 until count) {
put(
JSONObject().apply {
put("id", "$selectedFileId:$index")
- put("kind", if (index == 0 || index == 900) "file" else "line")
- put("fileId", if (index < 900) "first-file" else selectedFileId)
+ put("kind", if (index == 0 || index == selectedStart) "file" else "line")
+ put("fileId", if (index < selectedStart) "first-file" else selectedFileId)
put("content", "const value = $index")
}
)
diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts b/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts
index c418d528129..36773f8bdc4 100644
--- a/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts
+++ b/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts
@@ -131,6 +131,98 @@ describe("highlightNativeReviewDiffVisibleRows", () => {
expect([...new Set(loadedFiles)].sort()).toEqual(["file-7", "file-8"]);
});
+ it("skips collapsed code before the row cap and restores it on expansion", async () => {
+ const collapsedSource = Array.from(
+ { length: 100_000 },
+ (_, index) => `int hidden${index} = 1;`,
+ );
+ const expandedSource = [
+ "/* open",
+ ...Array.from({ length: 222 }, () => "still a comment"),
+ "*/ int visible = 1;",
+ ];
+ const collapsedLoad = vi.fn(async () => ({
+ oldContents: "",
+ newContents: collapsedSource.join("\n"),
+ }));
+ const expandedLoad = vi.fn(async () => ({
+ oldContents: "",
+ newContents: expandedSource.join("\n"),
+ }));
+ const files = [
+ {
+ ...TYPESCRIPT_FILE,
+ id: "collapsed",
+ language: "c",
+ path: "highlights.c",
+ loadContents: collapsedLoad,
+ },
+ {
+ ...TYPESCRIPT_FILE,
+ id: "expanded",
+ language: "c",
+ path: "highlights.h",
+ loadContents: expandedLoad,
+ },
+ ];
+ const rows = [collapsedSource, expandedSource].flatMap((source, fileIndex) => {
+ const fileId = files[fileIndex]!.id;
+ return [
+ { kind: "file", id: `${fileId}-header`, fileId },
+ ...source.map((content, index) => ({
+ ...makeLine({
+ id: `${fileId}-${index}`,
+ content,
+ change: "add",
+ newLineNumber: index + 1,
+ }),
+ fileId,
+ })),
+ ] satisfies NativeReviewDiffRow[];
+ });
+ const input = {
+ rows,
+ files,
+ scheme: "dark" as const,
+ firstRowIndex: 0,
+ lastRowIndex: rows.length - 1,
+ };
+ // A collapsed header and the next expanded header can share an iOS viewport,
+ // with 100,000 zero-height code rows between their canonical indices.
+ const viewport = await highlightNativeReviewDiffVisibleRows({
+ ...input,
+ collapsedFileIds: new Set(["collapsed"]),
+ overscanRows: 0,
+ });
+ expect(Object.keys(viewport.tokensByRowId)).toEqual(
+ expandedSource.map((_, index) => `expanded-${index}`),
+ );
+ const overscan = await highlightNativeReviewDiffVisibleRows({
+ ...input,
+ collapsedFileIds: new Set(["collapsed"]),
+ lastRowIndex: 100_002,
+ alreadyHighlightedRowIds: new Set(["expanded-0"]),
+ });
+ expect(Object.keys(overscan.tokensByRowId)).toEqual(
+ Array.from({ length: 160 }, (_, index) => `expanded-${index + 1}`),
+ );
+ expect(overscan.tokensByRowId["expanded-1"]).toEqual(
+ highlightCode(expandedSource.join("\n"), "c", "dark")[1],
+ );
+ expect(collapsedLoad).not.toHaveBeenCalled();
+ expect(expandedLoad).toHaveBeenCalled();
+
+ const expanded = await highlightNativeReviewDiffVisibleRows({
+ ...input,
+ lastRowIndex: 400,
+ collapsedFileIds: new Set(),
+ overscanRows: 0,
+ });
+ expect(expanded.rowCount).toBe(360);
+ expect(expanded.tokensByRowId["collapsed-0"]).toBeDefined();
+ expect(collapsedLoad).toHaveBeenCalledTimes(1);
+ });
+
it("delivers the dominant viewport file before fetching a smaller blocked neighbor", async () => {
const neighborStarted = Promise.withResolvers<void>();
const neighborResponse = Promise.withResolvers<{ oldContents: string; newContents: string }>();
diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts b/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts
index a4084d2ccaa..f25d058995a 100644
--- a/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts
+++ b/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts
@@ -18,6 +18,7 @@ export interface HighlightNativeReviewDiffVisibleRowsInput {
readonly overscanRows?: number;
readonly maxRows?: number;
readonly alreadyHighlightedRowIds?: ReadonlySet<string>;
+ readonly collapsedFileIds?: ReadonlySet<string>;
readonly signal?: AbortSignal;
readonly onChunk?: (chunk: NativeReviewDiffHighlightChunk) => void;
}
@@ -290,6 +291,7 @@ export async function highlightNativeReviewDiffVisibleRows(
row &&
isHighlightableLineRow(row) &&
visibleFileIds.has(row.fileId) &&
+ !input.collapsedFileIds?.has(row.fileId) &&
!input.alreadyHighlightedRowIds?.has(row.id) &&
fileMap.has(row.fileId)
) {
diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSource.test.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSource.test.ts
index 3dcc3c7597f..ef2743a34d5 100644
--- a/apps/mobile/src/features/diffs/nativeReviewDiffSource.test.ts
+++ b/apps/mobile/src/features/diffs/nativeReviewDiffSource.test.ts
@@ -1,6 +1,7 @@
import { expect, it, vi } from "vite-plus/test";
import { createNativeReviewDiffSourceLoader } from "./nativeReviewDiffSource";
+import * as DiffHighlightTrace from "./nativeReviewDiffTrace";
import type { NativeReviewDiffSource } from "./nativeReviewDiffTypes";
const SOURCE = { oldContents: "const before = true;", newContents: "const after = false;" };
@@ -149,3 +150,40 @@ it("serializes RPCs and drops cancelled queued files", async () => {
await load("next.ts");
expect(fetch.mock.calls).toEqual([["active.ts"], ["next.ts"]]);
});
+
+it("starts a shared fresh request for a file whose cancelled request was dropped", async () => {
+ const started = Promise.withResolvers<void>();
+ const response = Promise.withResolvers<NativeReviewDiffSource>();
+ const dropped = Promise.withResolvers<void>();
+ const replacementStarted = Promise.withResolvers<void>();
+ const replacementResponse = Promise.withResolvers<NativeReviewDiffSource>();
+ using _trace = vi.spyOn(DiffHighlightTrace, "traceDiffHighlight").mockImplementation((event) => {
+ if (event === "source-dropped") dropped.resolve();
+ });
+ const fetch = vi.fn((file: string) => {
+ if (file === "active.ts") {
+ started.resolve();
+ return response.promise;
+ }
+ replacementStarted.resolve();
+ return replacementResponse.promise;
+ });
+ const load = createNativeReviewDiffSourceLoader(fetch);
+ const active = load("active.ts");
+ await started.promise;
+ const controller = new AbortController();
+ const queued = load("cancelled.ts", controller.signal);
+ controller.abort();
+ expect(await queued).toBeNull();
+ response.resolve(SOURCE);
+ await dropped.promise;
+ const fresh = load("cancelled.ts");
+ // Settling first means the fresh caller joined the dropped request instead of fetching.
+ await Promise.race([replacementStarted.promise, fresh]);
+ const shared = load("cancelled.ts");
+ replacementResponse.resolve(SOURCE);
+ expect(await fresh).toBe(SOURCE);
+ expect(await shared).toBe(SOURCE);
+ expect(await active).toBe(SOURCE);
+ expect(fetch.mock.calls).toEqual([["active.ts"], ["cancelled.ts"]]);
+});
diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts
index 52fae25d35b..8dc30c71825 100644
--- a/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts
+++ b/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts
@@ -114,6 +114,8 @@ export function createNativeReviewDiffSourceLoader<FileId>(
const promise = tail
.then(async () => {
if ([...subscribers].every((subscriber) => subscriber?.aborted)) {
+ // A cancelled request must stop being shareable before its promise settles.
+ pending.delete(fileId);
traceDiffHighlight("source-dropped", { loader, file });
return null;
}
@@ -169,7 +171,9 @@ export function createNativeReviewDiffSourceLoader<FileId>(
throw error;
}
})
- .finally(() => pending.delete(fileId));
+ .finally(() => {
+ if (pending.get(fileId) === request) pending.delete(fileId);
+ });
tail = promise.then(
() => {},
() => {},
diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx
index 52cc1805342..81d43353d4c 100644
--- a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx
+++ b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx
@@ -192,13 +192,14 @@ function setup(integrated = false) {
rowIdByCommentLineId: new Map(),
};
const ids: string[] = [];
+ let collapsedFileIds: ReadonlyArray<string> = ids;
function PullRequestDiff({ targetFileId }: { targetFileId?: string }) {
const bridge = useNativeReviewDiffBridge({
threadKey: null,
sectionId: "pull-request:test:1:all",
diff: "test diff",
data,
- collapsedFileIds: ids,
+ collapsedFileIds,
viewedFileIds: ids,
selectedRowIds: ids,
canHighlight: true,
@@ -247,6 +248,10 @@ function setup(integrated = false) {
async mountPullRequest(targetFileId?: string) {
await act(async () => root.render(<PullRequestDiff targetFileId={targetFileId} />));
},
+ async collapseFiles(fileIds: ReadonlyArray<string>) {
+ collapsedFileIds = fileIds;
+ await act(async () => root.render(<PullRequestDiff />));
+ },
async updateComment() {
data = {
...data,
@@ -403,3 +408,35 @@ it("recognizes registration races for the installed native view name", async ()
),
).toBe(true);
});
+
+it("cancels stale collapse work and highlights expansion without resetting accepted tokens", async () => {
+ using screen = setup(true);
+ await screen.mountPullRequest();
+ await screen.jump(0);
+ await screen.deliverPayloads();
+ expect(screen.tokenRows).toBe("r0");
+
+ const response = Promise.withResolvers<void>();
+ const highlight = mocks.highlight.getMockImplementation()!;
+ mocks.highlight.mockImplementation(async (input: HighlightNativeReviewDiffVisibleRowsInput) => {
+ if (input.firstRowIndex === 400) {
+ await response.promise;
+ if (input.collapsedFileIds?.has("last-file")) {
+ return { tokensByRowId: {}, rowCount: 0, retryableRowIds: [], durationMs: 0 };
+ }
+ }
+ return highlight(input);
+ });
+ await screen.jump(400);
+ await screen.collapseFiles(["last-file"]);
+ await act(async () => response.resolve());
+ await screen.deliverPayloads();
+ expect(screen.tokenRows).toBe("r0");
+
+ await screen.collapseFiles([]);
+ await screen.deliverPayloads();
+ expect(screen.tokenRows).toBe("r0,r400");
+ await screen.jump(0);
+ await screen.deliverPayloads();
+ expect(screen.tokenRows).toBe("r0,r400");
+});
diff --git a/apps/mobile/src/features/review/useNativeReviewDiffBridge.ts b/apps/mobile/src/features/review/useNativeReviewDiffBridge.ts
index d51000bb1f7..2ae7c77e14d 100644
--- a/apps/mobile/src/features/review/useNativeReviewDiffBridge.ts
+++ b/apps/mobile/src/features/review/useNativeReviewDiffBridge.ts
@@ -43,6 +43,7 @@ export function useNativeReviewDiffBridge(input: {
() => createNativeReviewDiffTheme(scheme, themeId, appTheme),
[appTheme, scheme, themeId],
);
+ const collapsedFileIdsSet = useMemo(() => new Set(collapsedFileIds), [collapsedFileIds]);
const rowsJson = useMemo(() => JSON.stringify(data.rows), [data.rows]);
const collapsedFileIdsJson = useMemo(() => JSON.stringify(collapsedFileIds), [collapsedFileIds]);
const viewedFileIdsJson = useMemo(() => JSON.stringify(viewedFileIds), [viewedFileIds]);
@@ -69,6 +70,7 @@ export function useNativeReviewDiffBridge(input: {
useNativeReviewDiffHighlighting({
files: data.files,
rows: data.rows,
+ collapsedFileIds: collapsedFileIdsSet,
scheme,
resetKey: tokensResetKey,
enabled: canHighlight,
diff --git a/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts b/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts
index 1658f8e7695..6c454d94a6b 100644
--- a/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts
+++ b/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts
@@ -25,10 +25,11 @@ export function useNativeReviewDiffHighlighting(input: {
readonly files: ReadonlyArray<NativeReviewDiffFile>;
readonly rows: ReadonlyArray<NativeReviewDiffRow>;
readonly scheme: HighlightScheme;
+ readonly collapsedFileIds: ReadonlySet<string>;
readonly resetKey: string;
readonly enabled: boolean;
}) {
- const { enabled, files, resetKey, rows, scheme } = input;
+ const { collapsedFileIds, enabled, files, resetKey, rows, scheme } = input;
const highlightedRowIdsRef = useRef<Set<string>>(new Set());
const viewportScope = `${enabled}:${resetKey}:${rows.length}`;
const [viewport, setViewport] = useState<{
@@ -120,6 +121,7 @@ export function useNativeReviewDiffHighlighting(input: {
files,
rows,
scheme,
+ collapsedFileIds,
firstRowIndex: requestRange.firstRowIndex,
lastRowIndex: requestRange.lastRowIndex,
overscanRows,
@@ -140,6 +142,7 @@ export function useNativeReviewDiffHighlighting(input: {
error: squashAtomCommandFailure(settled),
resetKey,
scheme,
+ collapsedFileIds,
firstRowIndex: requestRange.firstRowIndex,
lastRowIndex: requestRange.lastRowIndex,
});
@@ -171,7 +174,7 @@ export function useNativeReviewDiffHighlighting(input: {
traceDiffHighlight("viewport-abort", { generation, reset });
abortController.abort();
};
- }, [enabled, files, resetKey, rows, scheme, viewport, viewportScope]);
+ }, [collapsedFileIds, enabled, files, resetKey, rows, scheme, viewport, viewportScope]);
const acknowledgeTokenPatch = useCallback((payload: Readonly<Record<string, unknown>>) => {
const pending = pendingPatchesRef.current;
diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts
index b569e7e531d..a17347d8347 100644
--- a/apps/server/src/pullRequest/PullRequestService.test.ts
+++ b/apps/server/src/pullRequest/PullRequestService.test.ts
@@ -3981,78 +3981,204 @@ it.effect("pauses uncached activity on a host after one activity read is rate li
}),
);
-it.effect("expands only files the change request changes, across every slice of its diff", () =>
- Effect.gen(function* () {
- const read: Array<string> = [];
- const service = yield* makeService({
- projects: [
- project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),
- ],
- providers: [
- fakePullRequestProvider(SourceControlProviderKind.make("github"), {
- getDiff: (input) =>
- Effect.succeed(
- input.cursor === undefined
- ? {
- patch: [
- "diff --git a/src/old.ts b/src/new.ts",
- "rename from src/old.ts",
- "rename to src/new.ts",
- "--- a/src/old.ts",
- "+++ b/src/new.ts",
- "",
- ].join("\n"),
- truncated: false,
- nextCursor: "2",
- }
- : {
- patch: [
- "diff --git a/gone.md b/gone.md",
- "deleted file mode 100644",
- "--- a/gone.md",
- "+++ /dev/null",
- "",
- ].join("\n"),
- truncated: false,
- nextCursor: null,
- },
- ),
- getDiffFileContents: (input) =>
- Effect.sync(() => {
- read.push(`${input.oldPath}->${input.newPath}`);
- return { oldContents: "old", newContents: "new" };
- }),
- }),
- ],
- });
- const ref = { projectId: "p1" as ProjectId, repository: "pingdotgg/t3code", number: 1 };
+it.effect(
+ "reuses loaded oversized diff slices to expand only files the change request changes",
+ () =>
+ Effect.gen(function* () {
+ const read: Array<string> = [];
+ const diffReads: Array<string | undefined> = [];
+ const service = yield* makeService({
+ projects: [
+ project({
+ id: "p1",
+ title: "t3code",
+ workspaceRoot: "/a",
+ repository: "pingdotgg/t3code",
+ }),
+ ],
+ providers: [
+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {
+ getDiff: (input) =>
+ Effect.sync(() => {
+ diffReads.push(input.cursor);
+ return input.cursor === undefined
+ ? {
+ patch: [
+ "diff --git a/src/old.ts b/src/new.ts",
+ "rename from src/old.ts",
+ "rename to src/new.ts",
+ "--- a/src/old.ts",
+ "+++ b/src/new.ts",
+ `+${"x".repeat(300_000)}`,
+ "",
+ ].join("\n"),
+ truncated: false,
+ nextCursor: "2",
+ }
+ : {
+ patch: [
+ "diff --git a/gone.md b/gone.md",
+ "deleted file mode 100644",
+ "--- a/gone.md",
+ "+++ /dev/null",
+ `-${"x".repeat(300_000)}`,
+ "",
+ ].join("\n"),
+ truncated: false,
+ nextCursor: null,
+ };
+ }),
+ getDiffFileContents: (input) =>
+ Effect.sync(() => {
+ read.push(`${input.oldPath}->${input.newPath}`);
+ return { oldContents: "old", newContents: "new" };
+ }),
+ }),
+ ],
+ });
+ const ref = { projectId: "p1" as ProjectId, repository: "pingdotgg/t3code", number: 1 };
- yield* service.diffFileContents({
- ...ref,
- changeType: "rename-changed",
- oldPath: "src/old.ts",
- newPath: "src/new.ts",
- });
- yield* service.diffFileContents({
- ...ref,
- changeType: "deleted",
- oldPath: "gone.md",
- newPath: "gone.md",
- });
- const outside = yield* service
- .diffFileContents({ ...ref, changeType: "deleted", oldPath: ".env", newPath: ".env" })
- .pipe(Effect.flip);
- const halfRename = yield* service
- .diffFileContents({
+ yield* service.diff(ref);
+ yield* service.diff({ ...ref, cursor: "2" });
+
+ yield* service.diffFileContents({
...ref,
- changeType: "change",
- oldPath: "src/secret.ts",
+ changeType: "rename-changed",
+ oldPath: "src/old.ts",
newPath: "src/new.ts",
- })
- .pipe(Effect.flip);
+ });
+ yield* service.diffFileContents({
+ ...ref,
+ changeType: "deleted",
+ oldPath: "gone.md",
+ newPath: "gone.md",
+ });
+ const outside = yield* service
+ .diffFileContents({ ...ref, changeType: "deleted", oldPath: ".env", newPath: ".env" })
+ .pipe(Effect.flip);
+ const halfRename = yield* service
+ .diffFileContents({
+ ...ref,
+ changeType: "change",
+ oldPath: "src/secret.ts",
+ newPath: "src/new.ts",
+ })
+ .pipe(Effect.flip);
+
+ assert.strictEqual(outside._tag, "PullRequestOperationError");
+ assert.strictEqual(halfRename._tag, "PullRequestOperationError");
+ assert.deepStrictEqual(read, ["src/old.ts->src/new.ts", "gone.md->gone.md"]);
+ assert.deepStrictEqual(diffReads, [undefined, "2"]);
+ }),
+);
- assert.strictEqual(outside._tag, "PullRequestOperationError");
- assert.strictEqual(halfRename._tag, "PullRequestOperationError");
- assert.deepStrictEqual(read, ["src/old.ts->src/new.ts", "gone.md->gone.md"]);
- }),
+// Refresh and expiry are covered by the in-flight test below; repository and number share the ref key.
+it.effect.each(["commit", "credential"] as const)(
+ "does not reuse loaded diff membership after changing %s",
+ (boundary) =>
+ Effect.gen(function* () {
+ let credential = "broad";
+ let diffReads = 0;
+ let contentReads = 0;
+ const service = yield* makeService({
+ projects: [
+ project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
+ ],
+ providers: [
+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {
+ withVerifiedCredential: (_, use) =>
+ Effect.suspend(() =>
+ use({ accountId: "101", viewer: "octocat", credentialFingerprint: credential }),
+ ),
+ getDiff: () =>
+ Effect.sync(() => ({
+ patch:
+ ++diffReads === 1
+ ? `diff --git a/private.ts b/private.ts\n--- a/private.ts\n+++ b/private.ts\n+${"x".repeat(300_000)}\n`
+ : "",
+ truncated: false,
+ nextCursor: null,
+ })),
+ getDiffFileContents: () =>
+ Effect.sync(() => {
+ contentReads += 1;
+ return { oldContents: "old", newContents: "new" };
+ }),
+ }),
+ ],
+ });
+ const ref = {
+ projectId: "p1" as ProjectId,
+ repository: "acme/web",
+ number: 1,
+ host: "github.com",
+ expectedAccountId: "101",
+ };
+ // Load at a commit and expand without one so the commit must be part of the membership key.
+ const loaded = boundary === "commit" ? { ...ref, commit: "a".repeat(40) } : ref;
+ yield* service.withRoutingCredential(loaded, service.diff(loaded));
+ if (boundary === "credential") credential = "restricted";
+ const input = {
+ ...ref,
+ changeType: "change" as const,
+ oldPath: "private.ts",
+ newPath: "private.ts",
+ };
+ const error = yield* service
+ .withRoutingCredential(input, service.diffFileContents(input))
+ .pipe(Effect.flip);
+ assert.strictEqual(error._tag, "PullRequestOperationError");
+ assert.strictEqual(error.reason, "not-found");
+ assert.strictEqual(diffReads, 2);
+ assert.strictEqual(contentReads, 0);
+ }),
+);
+
+it.effect.each(["expiry", "refresh"] as const)(
+ "keeps a loaded diff's original membership scope through an in-flight %s",
+ (boundary) =>
+ Effect.gen(function* () {
+ const started = yield* Deferred.make<void>();
+ const release = yield* Deferred.make<void>();
+ let diffReads = 0;
+ const service = yield* makeService({
+ projects: [
+ project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
+ ],
+ providers: [
+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {
+ getDiff: () =>
+ Effect.gen(function* () {
+ if (++diffReads !== 1) return { patch: "", truncated: false, nextCursor: null };
+ yield* Deferred.succeed(started, undefined);
+ yield* Deferred.await(release);
+ return {
+ patch: `diff --git a/private.ts b/private.ts\n--- a/private.ts\n+++ b/private.ts\n+${"x".repeat(300_000)}\n`,
+ truncated: false,
+ nextCursor: null,
+ };
+ }),
+ getDiffFileContents: () => Effect.die("an expired file must not be read"),
+ }),
+ ],
+ });
+ const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
+ const loading = yield* Effect.forkChild(service.diff(ref));
+ yield* Deferred.await(started);
+ if (boundary === "expiry") yield* TestClock.adjust("61 seconds");
+ else yield* service.invalidate({ reference: ref });
+ yield* Deferred.succeed(release, undefined);
+ yield* Fiber.join(loading);
+ const error = yield* service
+ .diffFileContents({
+ ...ref,
+ changeType: "change",
+ oldPath: "private.ts",
+ newPath: "private.ts",
+ })
+ .pipe(Effect.flip);
+ assert.strictEqual(error._tag, "PullRequestOperationError");
+ assert.strictEqual(error.reason, "not-found");
+ assert.strictEqual(diffReads, 2);
+ }),
);
diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts
index 5a31ced2137..437f8ab4e52 100644
--- a/apps/server/src/pullRequest/PullRequestService.ts
+++ b/apps/server/src/pullRequest/PullRequestService.ts
@@ -3202,7 +3202,14 @@ export const make = Effect.gen(function* () {
...refOfCacheKey(reference),
...(cursor === null ? {} : { cursor }),
...(commit === null ? {} : { commit }),
- } as PullRequestDiffInput);
+ } as PullRequestDiffInput).pipe(
+ observeRead,
+ Effect.map(({ value, observedAt }) => {
+ // Keep the loader's epoch and read time if a refresh occurs during the provider read.
+ diffFiles.record(JSON.stringify([reference, cursor, commit]), value, observedAt);
+ return value;
+ }),
+ );
},
{
capacity: DIFF_CACHE_CAPACITY,
@@ -3468,14 +3475,9 @@ export const make = Effect.gen(function* () {
const fileKey = (oldPath: string, newPath: string) => JSON.stringify([oldPath, newPath]);
const sliceKey = (input: PullRequestDiffInput) =>
JSON.stringify([refCacheKey(input), input.cursor ?? null, input.commit ?? null]);
- const read = Effect.fn("PullRequestService.read")(function* (input: PullRequestDiffInput) {
- const key = sliceKey(input);
- const now = yield* Clock.currentTimeMillis;
- const cached = held.get(key);
- if (cached !== undefined && now - cached.at <= ttlMs) return cached;
- const slice = yield* diff(input);
+ const record = (key: string, slice: PullRequestDiffResult, at: number) => {
const entry = {
- at: now,
+ at,
files: new Set(
parseDiffFilePaths(slice.patch).map((file) =>
fileKey(file.oldPath ?? file.newPath ?? "", file.newPath ?? file.oldPath ?? ""),
@@ -3490,8 +3492,16 @@ export const make = Effect.gen(function* () {
}
held.set(key, entry);
return entry;
+ };
+ const read = Effect.fn("PullRequestService.read")(function* (input: PullRequestDiffInput) {
+ const key = sliceKey(input);
+ const now = yield* Clock.currentTimeMillis;
+ const cached = held.get(key);
+ if (cached !== undefined && now - cached.at <= ttlMs) return cached;
+ const slice = yield* diff(input);
+ return record(key, slice, now);
});
- return { read: credentialCached(read), fileKey };
+ return { read: credentialCached(read), record, fileKey };
})();
const changesFile = (input: PullRequestDiffFileContentsInput) => {
const wanted = diffFiles.fileKey(input.oldPath, input.newPath);