Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions apps/mobile/src/features/diffs/nativeReviewDiffHighlightFiles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import type { ReviewParsedDiff, ReviewRenderableFile } from "../review/reviewModel";
import { createNativeReviewDiffSourceLoader } from "./nativeReviewDiffSource";
import type { NativeReviewDiffFile, NativeReviewDiffSource } from "./nativeReviewDiffTypes";

type SourceRequest = () => Promise<NativeReviewDiffSource>;

interface SourceSnapshot {
readonly firstFile: ReviewRenderableFile;
readonly scope: string;
readonly load: ReturnType<typeof createNativeReviewDiffSourceLoader<SourceRequest>>;
readonly requests: WeakMap<
ReviewRenderableFile,
{ readonly completePatch: boolean; readonly request: SourceRequest }
>;
}

export function createDiffHighlightCache(): { snapshot?: SourceSnapshot } {
return {};
}

/**
* Gives each file a loader for its whole old and new contents, so a hunk that starts inside a
* docstring or an embedded script block is tokenized with the lines above it. `scope` names
* everything `fetchFile` reads; a new scope or a new first file starts a new snapshot.
*/
export function withDiffSourceLoaders(
scope: string,
parsed: ReviewParsedDiff,
files: ReadonlyArray<NativeReviewDiffFile>,
fetchFile: (file: ReviewRenderableFile) => Promise<NativeReviewDiffSource>,
cache = createDiffHighlightCache(),
): ReadonlyArray<NativeReviewDiffFile> {
if (parsed.kind !== "files" || !parsed.files[0]) return files;
const byId = new Map(parsed.files.map((file) => [file.id, file]));
const firstFile = parsed.files[0];
// Appended pages share one loader budget; a new first file starts a new snapshot.
let snapshot = cache.snapshot;
if (!snapshot || snapshot.firstFile !== firstFile || snapshot.scope !== scope) {
snapshot = {
firstFile,
scope,
load: createNativeReviewDiffSourceLoader<SourceRequest>((request) => request()),
requests: new WeakMap(),
};
cache.snapshot = snapshot;
}
const { load, requests } = snapshot;
return files.map((nativeFile) => {
const file = byId.get(nativeFile.id);
if (!file) return nativeFile;
const completePatch = parsed.notice === null && !!file.completePatchSource;
const cached = requests.get(file);
if (cached?.completePatch === completePatch)
return { ...nativeFile, loadContents: (signal) => load(cached.request, signal) };
const request: SourceRequest = async () =>
completePatch && file.completePatchSource ? file.completePatchSource() : fetchFile(file);
requests.set(file, { completePatch, request });
return { ...nativeFile, loadContents: (signal) => load(request, signal) };
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,36 +7,25 @@ import type {
PullRequestDiffFileContentsResult,
} from "@t3tools/contracts";

import { createNativeReviewDiffSourceLoader } from "../diffs/nativeReviewDiffSource";
import {
createDiffHighlightCache,
withDiffSourceLoaders,
} from "../diffs/nativeReviewDiffHighlightFiles";
import {
diffHighlightTraceHash,
diffHighlightTraceId,
traceDiffHighlight,
} from "../diffs/nativeReviewDiffTrace";
import type { NativeReviewDiffFile, NativeReviewDiffSource } from "../diffs/nativeReviewDiffTypes";
import type { ReviewParsedDiff, ReviewRenderableFile } from "../review/reviewModel";
import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes";
import type { ReviewParsedDiff } from "../review/reviewModel";
import type { pullRequestTarget } from "./usePullRequestDiff";

type FetchContents<E> = (request: {
readonly environmentId: ReturnType<typeof pullRequestTarget>["environmentId"];
readonly input: PullRequestDiffFileContentsInput;
}) => Promise<AtomCommandResult<PullRequestDiffFileContentsResult, E>>;

type SourceRequest = () => Promise<NativeReviewDiffSource>;

interface SourceSnapshot {
readonly firstFile: ReviewRenderableFile;
readonly scope: string;
readonly load: ReturnType<typeof createNativeReviewDiffSourceLoader<SourceRequest>>;
readonly requests: WeakMap<
ReviewRenderableFile,
{ readonly completePatch: boolean; readonly request: SourceRequest }
>;
}

export function createPullRequestDiffHighlightCache(): { snapshot?: SourceSnapshot } {
return {};
}
export const createPullRequestDiffHighlightCache = createDiffHighlightCache;

export function createPullRequestDiffHighlightFiles<E>(
source: {
Expand All @@ -49,7 +38,6 @@ export function createPullRequestDiffHighlightFiles<E>(
cache = createPullRequestDiffHighlightCache(),
): ReadonlyArray<NativeReviewDiffFile> {
if (parsed.kind !== "files" || !parsed.files[0]) return files;
const byId = new Map(parsed.files.map((file) => [file.id, file]));
const { target, commit } = source;
traceDiffHighlight("source-target", {
environment: diffHighlightTraceHash(target.environmentId),
Expand All @@ -65,28 +53,11 @@ export function createPullRequestDiffHighlightFiles<E>(
target.input.host,
commit,
]);
const firstFile = parsed.files[0];
// Appended pages share one loader budget; a new first file starts a new snapshot.
let snapshot = cache.snapshot;
if (!snapshot || snapshot.firstFile !== firstFile || snapshot.scope !== scope) {
snapshot = {
firstFile,
scope,
load: createNativeReviewDiffSourceLoader<SourceRequest>((request) => request()),
requests: new WeakMap(),
};
cache.snapshot = snapshot;
}
const { load, requests } = snapshot;
return files.map((nativeFile) => {
const file = byId.get(nativeFile.id);
if (!file) return nativeFile;
const completePatch = parsed.notice === null && !!file.completePatchSource;
const cached = requests.get(file);
if (cached?.completePatch === completePatch)
return { ...nativeFile, loadContents: (signal) => load(cached.request, signal) };
const request: SourceRequest = async () => {
if (completePatch && file.completePatchSource) return file.completePatchSource();
return withDiffSourceLoaders(
scope,
parsed,
files,
async (file) => {
traceDiffHighlight("source-params", {
file: diffHighlightTraceId(file.id),
oldPath: diffHighlightTraceHash(file.previousPath ?? file.path),
Expand All @@ -106,8 +77,7 @@ export function createPullRequestDiffHighlightFiles<E>(
});
if (result._tag !== "Success") throw squashAtomCommandFailure(result);
return result.value;
};
requests.set(file, { completePatch, request });
return { ...nativeFile, loadContents: (signal) => load(request, signal) };
});
},
cache,
);
}
125 changes: 125 additions & 0 deletions apps/mobile/src/features/review/reviewDiffHighlightFiles.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { highlightCode } from "../../lib/highlights";

import {
EnvironmentId,
GitCommandError,
type ReviewDiffFileContentsResult,
} from "@t3tools/contracts";
import { Cause } from "effect";
import { AsyncResult } from "effect/reactivity";
import { expect, it, vi } from "vite-plus/test";

import { highlightNativeReviewDiffVisibleRows } from "../diffs/nativeReviewDiffHighlighter";
import { buildNativeReviewDiffData } from "./nativeReviewDiffAdapter";
import { createReviewDiffHighlightFiles } from "./reviewDiffHighlightFiles";
import { buildReviewParsedDiff } from "./reviewModel";

vi.mock("react-native-nitro-modules", async () => {
const { createWasmHighlightsModule } = await import("../../lib/highlights.testing");
const highlights = createWasmHighlightsModule();
return { NitroModules: { hasHybridObject: () => true, createHybridObject: () => highlights } };
});

const source = {
environmentId: EnvironmentId.make("environment"),
cwd: "/repo",
sourceKind: "revision-range" as const,
baseRef: "turn-start",
headRef: "refs/t3/turn/2",
diffKey: "turn:2",
};
const docstring = (line: string) =>
["def load():", ' """', " Reads settings.", "", " Notes:", line, ' """', ""].join(
"\n",
);
const oldContents = docstring(" the result is not a dict of dicts");
const newContents = docstring(" the result is and is not a dict");
const patch = [
"diff --git a/settings.py b/settings.py",
"--- a/settings.py",
"+++ b/settings.py",
"@@ -5,3 +5,3 @@ def load():",
" Notes:",
"- the result is not a dict of dicts",
"+ the result is and is not a dict",
' """',
"diff --git a/top.py b/top.py",
"--- a/top.py",
"+++ b/top.py",
"@@ -1,2 +1,2 @@",
"-x = 1",
"+x = 2",
" y = 3",
"",
].join("\n");

function setup() {
const parsed = buildReviewParsedDiff(patch, "scope");
const data = buildNativeReviewDiffData(parsed);
return { parsed, data };
}

it("colours a hunk inside a docstring from the whole file, and leaves files that start at the top", async () => {
const { parsed, data } = setup();
const fetch = vi.fn(async () => AsyncResult.success({ oldContents, newContents }));
const files = createReviewDiffHighlightFiles(source, parsed, data.files, fetch);

expect(files[1]!.loadContents).toBeUndefined();
const rowIndex = data.rows.findIndex(
(row) => row.kind === "line" && row.content === " the result is and is not a dict",
);
const result = await highlightNativeReviewDiffVisibleRows({
rows: data.rows,
files,
scheme: "dark",
firstRowIndex: rowIndex,
lastRowIndex: rowIndex,
overscanRows: 0,
});

expect(fetch).toHaveBeenCalledExactlyOnceWith({
environmentId: source.environmentId,
input: {
cwd: "/repo",
sourceKind: "revision-range",
changeType: "change",
baseRef: "turn-start",
headRef: "refs/t3/turn/2",
oldPath: "settings.py",
newPath: "settings.py",
},
});
expect(result.tokensByRowId[data.rows[rowIndex]!.id]).toEqual(
highlightCode(newContents, "python", "dark")[5],
);
});

it("keeps patch colours and stops asking for a file the server cannot read", async () => {
const { parsed, data } = setup();
const error = new GitCommandError({
operation: "read",
command: "git",
cwd: "/repo",
detail: "Git output exceeded the size limit.",
});
const fetch = vi.fn(async () =>
AsyncResult.failure<ReviewDiffFileContentsResult, GitCommandError>(Cause.fail(error)),
);
const files = createReviewDiffHighlightFiles(source, parsed, data.files, fetch);

const highlight = (withFiles: typeof files) =>
highlightNativeReviewDiffVisibleRows({
rows: data.rows,
files: withFiles,
scheme: "dark",
firstRowIndex: 0,
lastRowIndex: data.rows.length - 1,
overscanRows: 0,
});

expect((await highlight(files)).tokensByRowId).toEqual(
(await highlight(data.files)).tokensByRowId,
);
expect(await files[0]!.loadContents!()).toBeNull();
expect(fetch).toHaveBeenCalledTimes(1);
});
90 changes: 90 additions & 0 deletions apps/mobile/src/features/review/reviewDiffHighlightFiles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import {
squashAtomCommandFailure,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import {
EnvironmentAuthorizationError,
ReviewDiffPreviewError,
type EnvironmentId,
type ReviewDiffFileContentsInput,
type ReviewDiffFileContentsResult,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";

import {
createDiffHighlightCache,
withDiffSourceLoaders,
} from "../diffs/nativeReviewDiffHighlightFiles";
import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes";
import type { ReviewParsedDiff, ReviewRenderableFile } from "./reviewModel";

export interface ReviewDiffContentsSource {
readonly environmentId: EnvironmentId;
readonly cwd: string;
readonly sourceKind: ReviewDiffFileContentsInput["sourceKind"];
readonly baseRef: string | null;
readonly headRef: string | null;
/** Changes whenever the diff does, so contents read for an older diff are not reused. */
readonly diffKey: string;
}

type FetchContents<E> = (request: {
readonly environmentId: EnvironmentId;
readonly input: ReviewDiffFileContentsInput;
}) => Promise<AtomCommandResult<ReviewDiffFileContentsResult, E>>;

const isServerAnswer = Schema.is(
Schema.Union([ReviewDiffPreviewError, EnvironmentAuthorizationError]),
);

// Only a hunk with lines hidden above it can open inside a docstring or script block.
function hidesLinesAboveAHunk(file: ReviewRenderableFile): boolean {
let hunkStart = true;
for (const row of file.rows) {
if (row.kind === "hunk") hunkStart = true;
else if (row.kind === "line") {
if (hunkStart && Math.max(row.oldLineNumber ?? 0, row.newLineNumber ?? 0) > 1) return true;
hunkStart = false;
}
}
return false;
}

export function createReviewDiffHighlightFiles<E>(
source: ReviewDiffContentsSource,
parsed: ReviewParsedDiff,
files: ReadonlyArray<NativeReviewDiffFile>,
fetchContents: FetchContents<E>,
cache = createDiffHighlightCache(),
): ReadonlyArray<NativeReviewDiffFile> {
const { environmentId, cwd, sourceKind, baseRef, headRef, diffKey } = source;
const scope = JSON.stringify([environmentId, cwd, sourceKind, baseRef, headRef, diffKey]);
if (parsed.kind !== "files") return files;
const needsContents = new Set(parsed.files.filter(hidesLinesAboveAHunk).map((file) => file.id));
const loaded = withDiffSourceLoaders(
scope,
parsed,
files,
async (file) => {
const result = await fetchContents({
environmentId,
input: {
cwd,
sourceKind,
changeType: file.changeType,
baseRef,
headRef,
oldPath: file.previousPath ?? file.path,
newPath: file.path,
},
});
if (result._tag === "Success") return result.value;
const error = squashAtomCommandFailure(result);
// The server gives the same answer (too large, binary, no access) until the diff changes,
// so the loader stops asking for this file instead of retrying on every scroll.
throw isServerAnswer(error) ? { reason: "unsupported", cause: error } : error;
},
cache,
);
return loaded.map((file, index) => (needsContents.has(file.id) ? file : files[index]!));
}
4 changes: 3 additions & 1 deletion apps/mobile/src/features/review/reviewModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types";
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
import { turnChanges, turnHasChanges } from "@t3tools/client-runtime/state/thread-repositories";
import type { ReviewDiffPreviewSource } from "@t3tools/contracts";
import type { OrchestrationGetTurnDiffResult, ReviewDiffPreviewSource } from "@t3tools/contracts";
import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
Expand Down Expand Up @@ -40,6 +40,8 @@ export interface ReviewSectionItem {
readonly files?: ReviewDiffPreviewSource["files"];
readonly truncated?: boolean;
readonly source?: ReviewGitSource;
/** The revisions a turn diff compares; absent from older servers. */
readonly turnSource?: OrchestrationGetTurnDiffResult["source"];
/** Set when a turn's patch spans more than one folder. */
readonly repositoryGroups?: ReadonlyArray<ReviewRepositoryGroup>;
/** Repositories the turn changed that have nothing recorded before it to compare with. */
Expand Down
Loading
Loading