diff --git a/apps/mobile/docs/review-profiling.md b/apps/mobile/docs/review-profiling.md new file mode 100644 index 0000000000..6977eaf6ef --- /dev/null +++ b/apps/mobile/docs/review-profiling.md @@ -0,0 +1,80 @@ +# Review Screen Profiling + +Use this when the mobile review screen is slow or crashes while opening large diffs. + +## Preferred Capture: React Native DevTools Performance + +This app is on Expo SDK 55 / React Native 0.83 with Hermes, so the best first trace is the React Native DevTools Performance recording. The review screen also emits `t3.review.*` user timing marks in development builds so the trace can show parse, list-building, row indexing, and syntax-highlighting work. + +1. Start the development client: + + ```sh + cd apps/mobile + bun dev:client + ``` + +2. Open the app in the iOS Simulator or on the device using the development client. + +3. In the terminal running Expo, press `j` to open React Native DevTools. + +4. In DevTools, open the `Performance` panel. + +5. Start recording. + +6. In the app, reproduce the slow path: + - Navigate to the thread. + - Open `Files Changed`. + - Select the largest review source. + - Expand a few large files or tap `Load diff`. + - Scroll until the app is clearly slow or until just before it crashes. + +7. Stop recording. + +8. Export or save the Performance recording as a JSON trace. + +Send that exported trace file here. Also include the device/simulator model and whether it was iOS or Android. + +## Android Fallback: Hermes Sampling Profile + +Use this if the app crashes before DevTools can export a trace, or if we need deeper JavaScript stack samples. + +1. Run Android dev client: + + ```sh + cd apps/mobile + bun android:dev + bun dev:client + ``` + +2. Open the developer menu from the Expo terminal with `d`. + +3. Select `Enable Sampling Profiler`. + +4. Reproduce the review-screen slowdown. + +5. Open the developer menu again with `d`. + +6. Select `Disable Sampling Profiler`. + +7. Pull and convert the Hermes profile: + + ```sh + cd apps/mobile + mkdir -p profiles/review + bunx react-native profile-hermes profiles/review + ``` + +8. Send the generated Chrome trace/profile file from `apps/mobile/profiles/review`. + +For the development app variant, the Android package is `com.t3tools.t3code.dev`. + +## What To Capture + +For the first trace, do not optimize the repro. We want the slowest realistic case: + +- A diff with many files and large line counts. +- At least one `Load diff` action for a suppressed large diff. +- One vertical scroll pass after the content appears. +- One horizontal scroll of a long file, if that is part of the slowdown. + +If the app crashes, note the last visible action before the crash and attach device logs if available. diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 08329e1d41..36ac93a0f7 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -30,6 +30,7 @@ "config:dev": "APP_VARIANT=development expo config", "config:preview": "APP_VARIANT=preview expo config", "config:prod": "APP_VARIANT=production expo config", + "profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review", "test": "vitest run", "typecheck": "tsc --noEmit" }, diff --git a/apps/mobile/src/app/debug/syntax-highlight.tsx b/apps/mobile/src/app/debug/syntax-highlight.tsx new file mode 100644 index 0000000000..5c9634cf22 --- /dev/null +++ b/apps/mobile/src/app/debug/syntax-highlight.tsx @@ -0,0 +1,964 @@ +import { createHighlighterCore, type HighlighterCore } from "@shikijs/core"; +import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript"; +import bashLanguage from "@shikijs/langs/bash"; +import diffLanguage from "@shikijs/langs/diff"; +import javascriptLanguage from "@shikijs/langs/javascript"; +import jsonLanguage from "@shikijs/langs/json"; +import jsxLanguage from "@shikijs/langs/jsx"; +import tsxLanguage from "@shikijs/langs/tsx"; +import typescriptLanguage from "@shikijs/langs/typescript"; +import yamlLanguage from "@shikijs/langs/yaml"; +import githubDarkDefault from "@shikijs/themes/github-dark-default"; +import githubLightDefault from "@shikijs/themes/github-light-default"; +import Stack from "expo-router/stack"; +import { + memo, + useCallback, + useEffect, + useMemo, + useRef, + useState, + useSyncExternalStore, +} from "react"; +import { + FlatList, + Pressable, + ScrollView, + Text as NativeText, + type ListRenderItemInfo, + useColorScheme, + useWindowDimensions, + View, +} from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { AppText as Text } from "../../components/AppText"; +import { + debugReviewDiffFixtures, + type DebugReviewDiffFixture, + type DebugReviewDiffFixtureId, +} from "../../features/debug/fixtures/reviewDiffFixtures"; +import { cn } from "../../lib/cn"; +import { useThemeColor } from "../../lib/useThemeColor"; + +type DebugHighlightEngine = "native" | "javascript"; +type DebugDiffChange = "context" | "add" | "delete"; +type DebugDiffLanguage = + | "bash" + | "diff" + | "javascript" + | "json" + | "jsx" + | "tsx" + | "typescript" + | "yaml"; + +type DebugToken = { + readonly content: string; + readonly color: string | null; + readonly fontStyle: number | null; +}; + +type DebugDiffFile = { + readonly id: string; + readonly path: string; + readonly language: DebugDiffLanguage; + readonly additions: number; + readonly deletions: number; +}; + +type DebugDiffFileHeaderRow = { + readonly kind: "file"; + readonly id: string; + readonly fileId: string; + readonly filePath: string; + readonly language: DebugDiffLanguage; + readonly additions: number; + readonly deletions: number; +}; + +type DebugDiffHunkRow = { + readonly kind: "hunk"; + readonly id: string; + readonly fileId: string; + readonly text: string; +}; + +type DebugDiffCodeRow = { + readonly kind: "line"; + readonly id: string; + readonly fileId: string; + readonly change: DebugDiffChange; + readonly oldLineNumber: number | null; + readonly newLineNumber: number | null; + readonly content: string; + readonly highlightChunkId: string; + readonly indexInHighlightChunk: number; +}; + +type DebugDiffRow = DebugDiffFileHeaderRow | DebugDiffHunkRow | DebugDiffCodeRow; + +type DebugDiffFileBlock = { + readonly file: DebugDiffFileHeaderRow; + readonly rows: ReadonlyArray; +}; + +type DebugHighlightChunk = { + readonly id: string; + readonly fileId: string; + readonly language: DebugDiffLanguage; + readonly rows: ReadonlyArray; +}; + +type DebugParsedDiff = { + readonly files: ReadonlyArray; + readonly fileBlocks: ReadonlyArray; + readonly rows: ReadonlyArray; + readonly highlightChunks: ReadonlyArray; + readonly additions: number; + readonly deletions: number; +}; + +type DebugHighlighterHandle = { + readonly engine: DebugHighlightEngine; + readonly tokenize: ( + code: string, + options: { readonly lang: DebugDiffLanguage; readonly theme: string }, + ) => ReadonlyArray>; +}; + +const DEBUG_HIGHLIGHT_CHUNK_SIZE = 500; +const DEBUG_DIFF_ROW_HEIGHT = 28; +const DEBUG_CHANGE_BAR_WIDTH = 4; +const DEBUG_GUTTER_WIDTH = 58; +const DEBUG_STICKY_WIDTH = DEBUG_CHANGE_BAR_WIDTH + DEBUG_GUTTER_WIDTH; +const DEBUG_CONTENT_WIDTH = 3_000; +const DEBUG_DELETE_STRIPE_COUNT = DEBUG_DIFF_ROW_HEIGHT / 2; +const DEBUG_MONO_FONT_FAMILY = "BerkeleyMono-Regular"; +const DEBUG_THEME_NAME_BY_SCHEME = { + dark: "github-dark-default", + light: "github-light-default", +} as const; + +const DEBUG_LANGUAGES = [ + bashLanguage, + diffLanguage, + javascriptLanguage, + jsonLanguage, + jsxLanguage, + tsxLanguage, + typescriptLanguage, + yamlLanguage, +] satisfies Parameters[0]["langs"]; + +let nativeHighlighterPromise: Promise | null = null; +let javascriptHighlighterPromise: Promise | null = null; + +class DebugTokenStore { + private readonly fileVersions = new Map(); + private readonly listenersByFileId = new Map void>>(); + private resetVersion = 0; + private readonly tokensByChunkId = new Map>>(); + + getFileVersion(fileId: string): string { + return `${this.resetVersion}:${this.fileVersions.get(fileId) ?? 0}`; + } + + getTokens(chunkId: string): ReadonlyArray> | null { + return this.tokensByChunkId.get(chunkId) ?? null; + } + + reset(): void { + this.tokensByChunkId.clear(); + this.fileVersions.clear(); + this.resetVersion += 1; + this.listenersByFileId.forEach((listeners) => { + listeners.forEach((listener) => listener()); + }); + } + + setChunk(chunk: DebugHighlightChunk, tokens: ReadonlyArray>): void { + this.tokensByChunkId.set(chunk.id, tokens); + this.fileVersions.set(chunk.fileId, (this.fileVersions.get(chunk.fileId) ?? 0) + 1); + this.listenersByFileId.get(chunk.fileId)?.forEach((listener) => listener()); + } + + subscribeFile(fileId: string, listener: () => void): () => void { + let listeners = this.listenersByFileId.get(fileId); + if (!listeners) { + listeners = new Set(); + this.listenersByFileId.set(fileId, listeners); + } + + listeners.add(listener); + return () => { + listeners?.delete(listener); + if (listeners?.size === 0) { + this.listenersByFileId.delete(fileId); + } + }; + } +} + +function waitForNextFrame(): Promise { + return new Promise((resolve) => setTimeout(resolve, 0)); +} + +function normalizeTokens( + tokenLines: ReadonlyArray>, +): ReadonlyArray> { + return tokenLines.map((line) => + line.map((token) => ({ + content: token.content, + color: token.color ?? null, + fontStyle: token.fontStyle ?? null, + })), + ); +} + +async function createNativeDebugHighlighter(): Promise { + const nativeEngineModule = await import("react-native-shiki-engine"); + if (!nativeEngineModule.isNativeEngineAvailable()) { + throw new Error("Native Shiki engine is not available in this build."); + } + + const highlighter = await createHighlighterCore({ + langs: DEBUG_LANGUAGES, + themes: [githubLightDefault, githubDarkDefault], + engine: nativeEngineModule.createNativeEngine(), + }); + + return { + engine: "native", + tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)), + }; +} + +async function createJavascriptDebugHighlighter(): Promise { + const highlighter: HighlighterCore = await createHighlighterCore({ + langs: DEBUG_LANGUAGES, + themes: [githubLightDefault, githubDarkDefault], + engine: createJavaScriptRegexEngine(), + }); + + return { + engine: "javascript", + tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)), + }; +} + +async function getDebugHighlighter(engine: DebugHighlightEngine): Promise { + if (engine === "native") { + nativeHighlighterPromise ??= createNativeDebugHighlighter(); + return nativeHighlighterPromise; + } + + javascriptHighlighterPromise ??= createJavascriptDebugHighlighter(); + return javascriptHighlighterPromise; +} + +function getDiffPathFromHeader(line: string): string { + const match = line.match(/^diff --git a\/(.+) b\/(.+)$/); + return match?.[2] ?? line.replace(/^diff --git /, ""); +} + +function getLanguageForPath(filePath: string): DebugDiffLanguage { + const normalizedPath = filePath.toLowerCase(); + if (normalizedPath.endsWith(".tsx")) return "tsx"; + if (normalizedPath.endsWith(".ts")) return "typescript"; + if (normalizedPath.endsWith(".jsx")) return "jsx"; + if (normalizedPath.endsWith(".js") || normalizedPath.endsWith(".cjs")) return "javascript"; + if (normalizedPath.endsWith(".json") || normalizedPath.endsWith(".jsonc")) return "json"; + if (normalizedPath.endsWith(".yml") || normalizedPath.endsWith(".yaml")) return "yaml"; + if ( + normalizedPath.endsWith(".sh") || + normalizedPath.includes("/bin/") || + normalizedPath.includes("shell") + ) { + return "bash"; + } + return "diff"; +} + +function parseHunkLineNumbers(line: string): { oldLine: number; newLine: number } | null { + const match = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/); + if (!match) { + return null; + } + return { + oldLine: Number(match[1]), + newLine: Number(match[2]), + }; +} + +function makeChunkId(fileId: string, chunkIndex: number): string { + return `${fileId}:chunk:${chunkIndex}`; +} + +function parseDebugDiffFixture(fixture: DebugReviewDiffFixture): DebugParsedDiff { + const startedAt = performance.now(); + const rows: DebugDiffRow[] = []; + const files = new Map< + string, + { path: string; language: DebugDiffLanguage; additions: number; deletions: number } + >(); + const fileLineRows = new Map(); + const rawLines = fixture.diff.split(/\r?\n/); + + let currentFileId: string | null = null; + let currentOldLine: number | null = null; + let currentNewLine: number | null = null; + + function ensureCurrentFile(filePath: string): string { + const fileId = `file:${files.size}:${filePath}`; + files.set(fileId, { + path: filePath, + language: getLanguageForPath(filePath), + additions: 0, + deletions: 0, + }); + fileLineRows.set(fileId, []); + rows.push({ + kind: "file", + id: `${fileId}:header`, + fileId, + filePath, + language: getLanguageForPath(filePath), + additions: 0, + deletions: 0, + }); + return fileId; + } + + for (let index = 0; index < rawLines.length; index += 1) { + const rawLine = rawLines[index] ?? ""; + if (rawLine.startsWith("diff --git ")) { + currentFileId = ensureCurrentFile(getDiffPathFromHeader(rawLine)); + currentOldLine = null; + currentNewLine = null; + continue; + } + + if (!currentFileId) { + continue; + } + + if (rawLine.startsWith("@@ ")) { + const parsedLineNumbers = parseHunkLineNumbers(rawLine); + currentOldLine = parsedLineNumbers?.oldLine ?? null; + currentNewLine = parsedLineNumbers?.newLine ?? null; + rows.push({ + kind: "hunk", + id: `${currentFileId}:hunk:${index}`, + fileId: currentFileId, + text: rawLine, + }); + continue; + } + + if (rawLine.startsWith("+++") || rawLine.startsWith("---")) { + continue; + } + + const marker = rawLine[0]; + if (marker !== " " && marker !== "+" && marker !== "-") { + continue; + } + + const file = files.get(currentFileId); + if (!file) { + continue; + } + + const change: DebugDiffChange = marker === "+" ? "add" : marker === "-" ? "delete" : "context"; + const oldLineNumber = change === "add" ? null : currentOldLine; + const newLineNumber = change === "delete" ? null : currentNewLine; + const lineRows = fileLineRows.get(currentFileId) ?? []; + const chunkIndex = Math.floor(lineRows.length / DEBUG_HIGHLIGHT_CHUNK_SIZE); + const codeRow: DebugDiffCodeRow = { + kind: "line", + id: `${currentFileId}:line:${index}`, + fileId: currentFileId, + change, + oldLineNumber, + newLineNumber, + content: rawLine.slice(1), + highlightChunkId: makeChunkId(currentFileId, chunkIndex), + indexInHighlightChunk: lineRows.length % DEBUG_HIGHLIGHT_CHUNK_SIZE, + }; + + rows.push(codeRow); + lineRows.push(codeRow); + fileLineRows.set(currentFileId, lineRows); + + if (change === "add") { + files.set(currentFileId, { ...file, additions: file.additions + 1 }); + currentNewLine = currentNewLine === null ? null : currentNewLine + 1; + continue; + } + + if (change === "delete") { + files.set(currentFileId, { ...file, deletions: file.deletions + 1 }); + currentOldLine = currentOldLine === null ? null : currentOldLine + 1; + continue; + } + + currentOldLine = currentOldLine === null ? null : currentOldLine + 1; + currentNewLine = currentNewLine === null ? null : currentNewLine + 1; + } + + const fileSummaries = Array.from(files, ([id, file]) => ({ id, ...file })); + const fileSummaryById = new Map(fileSummaries.map((file) => [file.id, file])); + const rowsWithFileStats = rows.map((row): DebugDiffRow => { + if (row.kind !== "file") { + return row; + } + const file = fileSummaryById.get(row.fileId); + return { + kind: row.kind, + id: row.id, + fileId: row.fileId, + filePath: row.filePath, + language: row.language, + additions: file?.additions ?? row.additions, + deletions: file?.deletions ?? row.deletions, + }; + }); + const fileBlocksById = new Map< + string, + { file: DebugDiffFileHeaderRow; rows: Array } + >(); + for (const row of rowsWithFileStats) { + if (row.kind === "file") { + fileBlocksById.set(row.fileId, { file: row, rows: [] }); + continue; + } + + fileBlocksById.get(row.fileId)?.rows.push(row); + } + const fileBlocks: DebugDiffFileBlock[] = Array.from(fileBlocksById.values()); + + const highlightChunks: DebugHighlightChunk[] = []; + fileLineRows.forEach((lineRows, fileId) => { + const file = fileSummaryById.get(fileId); + if (!file) { + return; + } + for ( + let startIndex = 0; + startIndex < lineRows.length; + startIndex += DEBUG_HIGHLIGHT_CHUNK_SIZE + ) { + const chunkIndex = startIndex / DEBUG_HIGHLIGHT_CHUNK_SIZE; + highlightChunks.push({ + id: makeChunkId(fileId, chunkIndex), + fileId, + language: file.language, + rows: lineRows.slice(startIndex, startIndex + DEBUG_HIGHLIGHT_CHUNK_SIZE), + }); + } + }); + + const parsed = { + files: fileSummaries, + fileBlocks, + rows: rowsWithFileStats, + highlightChunks, + additions: fileSummaries.reduce((total, file) => total + file.additions, 0), + deletions: fileSummaries.reduce((total, file) => total + file.deletions, 0), + }; + + console.log("[debug-diff-scratch] parse", { + durationMs: Math.round(performance.now() - startedAt), + fixture: fixture.id, + files: parsed.files.length, + highlightChunks: parsed.highlightChunks.length, + rows: parsed.rows.length, + }); + + return parsed; +} + +const TokenText = memo(function TokenText(props: { + readonly content: string; + readonly tokens: ReadonlyArray | null; +}) { + if (!props.tokens) { + return ( + + {props.content || " "} + + ); + } + + let tokenOffset = 0; + + return ( + + {props.tokens.map((token) => { + const tokenKey = `${tokenOffset}:${token.content.length}:${token.color ?? ""}:${token.fontStyle ?? ""}`; + tokenOffset += token.content.length; + const fontWeight = + token.fontStyle !== null && (token.fontStyle & 2) === 2 + ? ("700" as const) + : ("500" as const); + const fontStyle = + token.fontStyle !== null && (token.fontStyle & 1) === 1 + ? ("italic" as const) + : ("normal" as const); + + return ( + + {token.content} + + ); + })} + + ); +}); + +function changeRowClassName(change: DebugDiffChange): string { + if (change === "add") return "bg-emerald-500/10"; + if (change === "delete") return "bg-rose-500/10"; + return "bg-card"; +} + +function DebugChangeBar(props: { readonly change: DebugDiffChange }) { + if (props.change === "delete") { + return ( + + {Array.from({ length: DEBUG_DELETE_STRIPE_COUNT }, (_, index) => ( + + + + + ))} + + ); + } + + if (props.change === "add") { + return ; + } + + return ; +} + +function DebugDiffFileHeader(props: { + readonly header: DebugDiffFileHeaderRow; + readonly width: number; +}) { + return ( + + + {props.header.filePath} + + -{props.header.deletions} + + +{props.header.additions} + + + ); +} + +function DebugDiffStickyCell(props: { readonly item: DebugDiffHunkRow | DebugDiffCodeRow }) { + if (props.item.kind === "hunk") { + return ( + + ); + } + + const displayLineNumber = props.item.newLineNumber ?? props.item.oldLineNumber ?? ""; + + return ( + + + + {displayLineNumber} + + + ); +} + +function DebugDiffCodeCell(props: { + readonly item: DebugDiffHunkRow | DebugDiffCodeRow; + readonly tokens: ReadonlyArray | null; +}) { + const { item } = props; + + if (item.kind === "hunk") { + return ( + + + {item.text} + + + ); + } + + return ( + + + + ); +} + +const DebugDiffFileBlockView = memo(function DebugDiffFileBlockView(props: { + readonly block: DebugDiffFileBlock; + readonly tokenStore: DebugTokenStore; + readonly width: number; +}) { + const viewportWidth = Math.max(0, props.width - DEBUG_STICKY_WIDTH); + useSyncExternalStore( + useCallback( + (listener) => props.tokenStore.subscribeFile(props.block.file.fileId, listener), + [props.block.file.fileId, props.tokenStore], + ), + useCallback( + () => props.tokenStore.getFileVersion(props.block.file.fileId), + [props.block.file.fileId, props.tokenStore], + ), + useCallback( + () => props.tokenStore.getFileVersion(props.block.file.fileId), + [props.block.file.fileId, props.tokenStore], + ), + ); + + return ( + + + + + {props.block.rows.map((row) => ( + + ))} + + + + {props.block.rows.map((row) => ( + + ))} + + + + + ); +}); + +function EngineToggle(props: { + readonly engine: DebugHighlightEngine; + readonly onChangeEngine: (engine: DebugHighlightEngine) => void; +}) { + return ( + + {(["native", "javascript"] as const).map((engine) => { + const selected = props.engine === engine; + return ( + props.onChangeEngine(engine)} + > + + {engine === "javascript" ? "JS" : "Native"} + + + ); + })} + + ); +} + +function FixtureToggle(props: { + readonly fixtureId: DebugReviewDiffFixtureId; + readonly onChangeFixture: (fixtureId: DebugReviewDiffFixtureId) => void; +}) { + return ( + + + {debugReviewDiffFixtures.map((fixture) => { + const selected = props.fixtureId === fixture.id; + return ( + props.onChangeFixture(fixture.id)} + > + + {fixture.label} + + + ); + })} + + + ); +} + +export default function SyntaxHighlightDebugRoute() { + const insets = useSafeAreaInsets(); + const { width } = useWindowDimensions(); + const colorScheme = useColorScheme(); + const headerIcon = String(useThemeColor("--color-icon")); + const themeName = DEBUG_THEME_NAME_BY_SCHEME[colorScheme === "dark" ? "dark" : "light"]; + const [engine, setEngine] = useState("native"); + const [fixtureId, setFixtureId] = useState("small"); + const [status, setStatus] = useState("Idle"); + const renderStartRef = useRef(null); + const generationRef = useRef(0); + const tokenStore = useMemo(() => new DebugTokenStore(), []); + + const fixture = useMemo( + () => + debugReviewDiffFixtures.find((candidate) => candidate.id === fixtureId) ?? + debugReviewDiffFixtures[0], + [fixtureId], + ); + const parsedDiff = useMemo(() => parseDebugDiffFixture(fixture), [fixture]); + const fileBlockOffsets = useMemo(() => { + let offset = 0; + return parsedDiff.fileBlocks.map((block, index) => { + const length = DEBUG_DIFF_ROW_HEIGHT * (block.rows.length + 1); + const itemLayout = { index, length, offset }; + offset += length; + return itemLayout; + }); + }, [parsedDiff.fileBlocks]); + + useEffect(() => { + const generation = generationRef.current + 1; + generationRef.current = generation; + renderStartRef.current = performance.now(); + tokenStore.reset(); + setStatus("Initializing highlighter"); + + void (async () => { + try { + const highlighterStartedAt = performance.now(); + const highlighter = await getDebugHighlighter(engine); + if (generation !== generationRef.current) { + return; + } + + console.log("[debug-diff-scratch] initialize", { + durationMs: Math.round(performance.now() - highlighterStartedAt), + engine: highlighter.engine, + }); + + let firstChunkMs: number | null = null; + const totalStartedAt = performance.now(); + setStatus(`Streaming ${parsedDiff.highlightChunks.length.toLocaleString()} chunks`); + + for (let chunkIndex = 0; chunkIndex < parsedDiff.highlightChunks.length; chunkIndex += 1) { + if (generation !== generationRef.current) { + return; + } + + const chunk = parsedDiff.highlightChunks[chunkIndex]; + if (!chunk) { + continue; + } + + const chunkCode = chunk.rows.map((line) => line.content).join("\n"); + const chunkStartedAt = performance.now(); + const chunkTokens = highlighter.tokenize(chunkCode, { + lang: chunk.language, + theme: themeName, + }); + const chunkMs = performance.now() - chunkStartedAt; + + if (firstChunkMs === null) { + firstChunkMs = performance.now() - totalStartedAt; + console.log("[debug-diff-scratch] first chunk", { + durationMs: Math.round(firstChunkMs), + engine, + fixture: fixture.id, + language: chunk.language, + lineCount: chunkTokens.length, + }); + } + + tokenStore.setChunk(chunk, chunkTokens); + + console.log("[debug-diff-scratch] chunk", { + chunkIndex, + chunkMs: Math.round(chunkMs), + engine, + fixture: fixture.id, + language: chunk.language, + lineCount: chunkTokens.length, + }); + + await waitForNextFrame(); + } + + console.log("[debug-diff-scratch] complete", { + durationMs: Math.round(performance.now() - totalStartedAt), + engine, + fixture: fixture.id, + rows: parsedDiff.rows.length, + }); + setStatus(`Complete with ${engine}`); + } catch (error) { + console.error("[debug-diff-scratch] failed", { + engine, + message: error instanceof Error ? error.message : String(error), + }); + setStatus(error instanceof Error ? error.message : "Highlight failed"); + } + })(); + }, [ + engine, + fixture.id, + parsedDiff.highlightChunks, + parsedDiff.rows.length, + themeName, + tokenStore, + ]); + + useEffect(() => { + if (renderStartRef.current === null) { + return; + } + + const startedAt = renderStartRef.current; + renderStartRef.current = null; + const commitMs = performance.now() - startedAt; + requestAnimationFrame(() => { + console.log("[debug-diff-scratch] render", { + commitMs: Math.round(commitMs), + paintMs: Math.round(performance.now() - startedAt), + }); + }); + }); + + const renderItem = useCallback( + ({ item }: ListRenderItemInfo) => ( + + ), + [tokenStore, width], + ); + + return ( + + + + + + + Diff streaming scratch + + {fixture.label} · {parsedDiff.files.length} files · {parsedDiff.rows.length} rows ·{" "} + {status} + + + + + + + + item.file.id} + getItemLayout={(_, index) => ({ + length: fileBlockOffsets[index]?.length ?? DEBUG_DIFF_ROW_HEIGHT, + offset: fileBlockOffsets[index]?.offset ?? 0, + index, + })} + initialNumToRender={2} + maxToRenderPerBatch={3} + updateCellsBatchingPeriod={32} + windowSize={5} + keyboardShouldPersistTaps="handled" + contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }} + /> + + ); +} diff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx index f153db7013..f6095c051a 100644 --- a/apps/mobile/src/app/index.tsx +++ b/apps/mobile/src/app/index.tsx @@ -43,28 +43,50 @@ export default function HomeRouteScreen() { headerTintColor: iconColor, headerTitle: "", headerRight: () => ( - router.push("/connections")} - hitSlop={8} - style={{ - flexDirection: "row", - alignItems: "center", - gap: 8, - paddingHorizontal: 4, - paddingVertical: 4, - }} - > - - + router.push("/debug/syntax-highlight")} + hitSlop={8} style={{ - fontFamily: "DMSans_700Bold", - fontSize: 12, - color: secondaryFg, + borderRadius: 999, + backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)", + paddingHorizontal: 10, + paddingVertical: 5, }} > - {CONNECTION_LABEL[connectionState]} - - + + Debug + + + router.push("/connections")} + hitSlop={8} + style={{ + flexDirection: "row", + alignItems: "center", + gap: 8, + paddingHorizontal: 4, + paddingVertical: 4, + }} + > + + + {CONNECTION_LABEL[connectionState]} + + + ), headerSearchBarOptions: { placeholder: "Search threads", diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx index 84c48c6edc..ee993ee7c8 100644 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx +++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx @@ -1,5 +1,10 @@ +import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider"; import { ReviewSheet } from "../../../../features/review/ReviewSheet"; export default function ReviewRoute() { - return ; + return ( + + + + ); } diff --git a/apps/mobile/src/features/debug/fixtures/README.md b/apps/mobile/src/features/debug/fixtures/README.md new file mode 100644 index 0000000000..f504644cca --- /dev/null +++ b/apps/mobile/src/features/debug/fixtures/README.md @@ -0,0 +1,13 @@ +# Debug Fixtures + +These patch fixtures snapshot review-rendering worktree diffs used to develop +the scratch review renderer. Keep them deterministic so the debug route can test +parsing, chunked syntax highlighting, and virtualization without depending on +the current repo state. + +- `review-small.diff`: 155 lines, narrow model/rendering changes. +- `review-medium.diff`: 1,955 lines, review screen and highlighter changes. +- `review-large.diff`: 3,208 lines, broad current worktree snapshot excluding + this fixture directory. +- `current-working-review.diff`: alias of `review-large.diff` for quick loading + while iterating. diff --git a/apps/mobile/src/features/debug/fixtures/current-working-review.diff b/apps/mobile/src/features/debug/fixtures/current-working-review.diff new file mode 100644 index 0000000000..ca2da03aff --- /dev/null +++ b/apps/mobile/src/features/debug/fixtures/current-working-review.diff @@ -0,0 +1,3208 @@ +diff --git a/apps/mobile/package.json b/apps/mobile/package.json +index 08329e1d4..36ac93a0f 100644 +--- a/apps/mobile/package.json ++++ b/apps/mobile/package.json +@@ -30,6 +30,7 @@ + "config:dev": "APP_VARIANT=development expo config", + "config:preview": "APP_VARIANT=preview expo config", + "config:prod": "APP_VARIANT=production expo config", ++ "profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review", + "test": "vitest run", + "typecheck": "tsc --noEmit" + }, +diff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx +index f153db701..f6095c051 100644 +--- a/apps/mobile/src/app/index.tsx ++++ b/apps/mobile/src/app/index.tsx +@@ -43,28 +43,50 @@ export default function HomeRouteScreen() { + headerTintColor: iconColor, + headerTitle: "", + headerRight: () => ( +- router.push("/connections")} +- hitSlop={8} +- style={{ +- flexDirection: "row", +- alignItems: "center", +- gap: 8, +- paddingHorizontal: 4, +- paddingVertical: 4, +- }} +- > +- +- ++ router.push("/debug/syntax-highlight")} ++ hitSlop={8} + style={{ +- fontFamily: "DMSans_700Bold", +- fontSize: 12, +- color: secondaryFg, ++ borderRadius: 999, ++ backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)", ++ paddingHorizontal: 10, ++ paddingVertical: 5, + }} + > +- {CONNECTION_LABEL[connectionState]} +- +- ++ ++ Debug ++ ++ ++ router.push("/connections")} ++ hitSlop={8} ++ style={{ ++ flexDirection: "row", ++ alignItems: "center", ++ gap: 8, ++ paddingHorizontal: 4, ++ paddingVertical: 4, ++ }} ++ > ++ ++ ++ {CONNECTION_LABEL[connectionState]} ++ ++ ++ + ), + headerSearchBarOptions: { + placeholder: "Search threads", +diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx +index 84c48c6ed..ee993ee7c 100644 +--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx ++++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx +@@ -1,5 +1,10 @@ ++import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider"; + import { ReviewSheet } from "../../../../features/review/ReviewSheet"; + + export default function ReviewRoute() { +- return ; ++ return ( ++ ++ ++ ++ ); + } +diff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx +index 076a2286d..9a173224a 100644 +--- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx ++++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx +@@ -2,15 +2,8 @@ import { useLocalSearchParams, useRouter } from "expo-router"; + import { SymbolView } from "expo-symbols"; + import { TextInputWrapper } from "expo-paste-input"; + import { useEffect, useMemo, useState } from "react"; +-import { +- KeyboardAvoidingView, +- Platform, +- Pressable, +- ScrollView, +- View, +- useColorScheme, +- useWindowDimensions, +-} from "react-native"; ++import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native"; ++import { KeyboardStickyView } from "react-native-keyboard-controller"; + import { useSafeAreaInsets } from "react-native-safe-area-context"; + import ImageViewing from "react-native-image-viewing"; + +@@ -34,6 +27,7 @@ import { + import { + changeTone, + DiffTokenText, ++ REVIEW_DIFF_LINE_HEIGHT, + REVIEW_MONO_FONT_FAMILY, + ReviewChangeBar, + } from "./reviewDiffRendering"; +@@ -44,7 +38,6 @@ import { + } from "./shikiReviewHighlighter"; + + const REVIEW_COMMENT_PREVIEW_MAX_LINES = 5; +-const REVIEW_COMMENT_LINE_HEIGHT = 26; + + export function ReviewCommentComposerSheet() { + const router = useRouter(); +@@ -84,8 +77,8 @@ export function ReviewCommentComposerSheet() { + ? `Lines ${firstNumber}-${lastNumber}` + : `${selectedLines.length} lines selected`; + const previewHeight = Math.max( +- Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_COMMENT_LINE_HEIGHT, +- REVIEW_COMMENT_LINE_HEIGHT, ++ Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_DIFF_LINE_HEIGHT, ++ REVIEW_DIFF_LINE_HEIGHT, + ); + const previewViewportWidth = Math.max(width - 40, 280); + const handleNativePaste = useNativePaste((uris) => { +@@ -143,17 +136,13 @@ export function ReviewCommentComposerSheet() { + } + + return ( +- ++ + + +@@ -219,7 +208,7 @@ export function ReviewCommentComposerSheet() { + + + + +- +- +- void handlePickImages()} /> +- +- { +- if (!target || !environmentId || !threadId || commentText.trim().length === 0) { +- return; +- } +- +- appendReviewCommentToDraft({ +- environmentId, +- threadId, +- text: formatReviewCommentContext(target, commentText), +- attachments, +- }); +- setAttachments([]); +- clearReviewCommentTarget(); +- router.dismiss(); +- }} +- /> +- + + )} + ++ {target ? ( ++ ++ ++ void handlePickImages()} /> ++ ++ { ++ if (!target || !environmentId || !threadId || commentText.trim().length === 0) { ++ return; ++ } ++ ++ appendReviewCommentToDraft({ ++ environmentId, ++ threadId, ++ text: formatReviewCommentContext(target, commentText), ++ attachments, ++ }); ++ setAttachments([]); ++ clearReviewCommentTarget(); ++ router.dismiss(); ++ }} ++ /> ++ ++ ++ ) : null} + +- ++ + ); + } +diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx +index 82c28e81e..e148a8da2 100644 +--- a/apps/mobile/src/features/review/ReviewSheet.tsx ++++ b/apps/mobile/src/features/review/ReviewSheet.tsx +@@ -1,17 +1,31 @@ + import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts"; ++import { Gesture, GestureDetector } from "react-native-gesture-handler"; ++import Animated, { ++ makeMutable, ++ type SharedValue, ++ useAnimatedStyle, ++ useSharedValue, ++} from "react-native-reanimated"; + import { useLocalSearchParams, useRouter } from "expo-router"; + import Stack from "expo-router/stack"; + import { SymbolView } from "expo-symbols"; +-import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react"; ++import { ++ memo, ++ type ReactElement, ++ useCallback, ++ useDeferredValue, ++ useEffect, ++ useMemo, ++ useRef, ++ useState, ++} from "react"; + import { + ActivityIndicator, + FlatList, +- InteractionManager, + type ListRenderItemInfo, + Pressable, + ScrollView, + Text as NativeText, +- type ViewToken, + useColorScheme, + useWindowDimensions, + View, +@@ -32,6 +46,7 @@ import { + setReviewTurnDiff, + updateReviewExpandedFileIds, + updateReviewRevealedLargeFileIds, ++ updateReviewViewedFileIds, + useReviewCacheForThread, + } from "./reviewState"; + import { +@@ -45,11 +60,12 @@ import { + type ReviewParsedDiff, + type ReviewRenderableFile, + type ReviewRenderableLineRow, ++ type ReviewRenderableRow, + } from "./reviewModel"; + import { + clearReviewHighlightFileCache, + getCachedHighlightedReviewFile, +- highlightReviewFile, ++ streamHighlightReviewFile, + type ReviewDiffTheme, + type ReviewHighlightedFile, + type ReviewHighlightedToken, +@@ -67,9 +83,12 @@ import { + import { + changeTone, + DiffTokenText, ++ REVIEW_DIFF_LINE_HEIGHT, + REVIEW_MONO_FONT_FAMILY, + ReviewChangeBar, + } from "./reviewDiffRendering"; ++import { markReviewEvent, measureReviewWork } from "./reviewPerf"; ++import { useReviewHighlighterStatus } from "./ReviewHighlighterProvider"; + + interface PendingCommentSelection { + readonly sectionTitle: string; +@@ -87,14 +106,21 @@ interface ReviewLineActionInput { + + const IOS_NAV_BAR_HEIGHT = 44; + const REVIEW_HEADER_SPACING = 0; +-const REVIEW_LINE_GUTTER_WIDTH = 62; ++const REVIEW_CHANGE_BAR_WIDTH = 5; ++const REVIEW_MIN_LINE_NUMBER_WIDTH = 27; ++const REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE = 8; ++const REVIEW_LINE_NUMBER_HORIZONTAL_PADDING = 6; + const REVIEW_CHARACTER_WIDTH_ESTIMATE = 8.4; + const REVIEW_MAX_CONTENT_WIDTH = 4_800; +-const REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT = 2; +-const REVIEW_HIGHLIGHT_BACKTRACK_COUNT = 0; +-const REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT = 1; ++const REVIEW_HUNK_ROW_HEIGHT = 35; ++const REVIEW_FILE_HEADER_HEIGHT = 43; ++const REVIEW_SUPPRESSED_ROW_HEIGHT = 92; + const loggedMissingReviewTokenKeys = new Set(); + ++function waitForReviewDelay(durationMs: number): Promise { ++ return new Promise((resolve) => setTimeout(resolve, durationMs)); ++} ++ + function isReviewDiffDebugLoggingEnabled(): boolean { + return typeof __DEV__ !== "undefined" ? __DEV__ : false; + } +@@ -113,33 +139,27 @@ function logReviewDiffDiagnostic(message: string, details?: Record, ++function computeReviewFileContentWidth( ++ rows: ReadonlyArray, + viewportWidth: number, ++ gutterWidth: number, + ): number { + let maxTextLength = 0; + +- items.forEach((item) => { +- switch (item.kind) { +- case "file-header": +- maxTextLength = Math.max( +- maxTextLength, +- item.file.path.length, +- item.file.previousPath?.length ?? 0, +- ); +- break; +- case "file-suppressed": +- maxTextLength = Math.max(maxTextLength, item.message.length, item.actionLabel?.length ?? 0); +- break; +- case "hunk": +- maxTextLength = Math.max( +- maxTextLength, +- item.row.header.length + (item.row.context ? item.row.context.length + 1 : 0), +- ); +- break; +- case "line": +- maxTextLength = Math.max(maxTextLength, item.row.content.length); +- break; ++ rows.forEach((row) => { ++ if (row.kind === "hunk") { ++ maxTextLength = Math.max( ++ maxTextLength, ++ row.header.length + (row.context ? row.context.length + 1 : 0), ++ ); ++ return; + } ++ ++ maxTextLength = Math.max(maxTextLength, row.content.length); + }); + + return Math.max( +- viewportWidth, ++ Math.max(0, viewportWidth - gutterWidth), + Math.min( + REVIEW_MAX_CONTENT_WIDTH, +- Math.ceil(REVIEW_LINE_GUTTER_WIDTH + 48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE), ++ Math.ceil(48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE), + ), + ); + } + ++function computeReviewFileGutterWidth(rows: ReadonlyArray): number { ++ let maxLineNumber = 0; ++ ++ rows.forEach((row) => { ++ if (row.kind !== "line") { ++ return; ++ } ++ ++ maxLineNumber = Math.max(maxLineNumber, row.oldLineNumber ?? 0, row.newLineNumber ?? 0); ++ }); ++ ++ const digitCount = Math.max(1, String(maxLineNumber).length); ++ const lineNumberWidth = Math.max( ++ REVIEW_MIN_LINE_NUMBER_WIDTH, ++ digitCount * REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE + REVIEW_LINE_NUMBER_HORIZONTAL_PADDING, ++ ); ++ ++ return REVIEW_CHANGE_BAR_WIDTH + lineNumberWidth; ++} ++ + function getDefaultExpandedFileIds( + files: ReadonlyArray, + ): ReadonlyArray { + return files.map((file) => file.id); + } + ++function getValidReviewExpandedFileIds( ++ files: ReadonlyArray, ++ cachedExpandedFileIds: ReadonlyArray | undefined, ++): ReadonlyArray { ++ if (cachedExpandedFileIds === undefined) { ++ return getDefaultExpandedFileIds(files); ++ } ++ ++ const fileIdSet = new Set(files.map((file) => file.id)); ++ return cachedExpandedFileIds.filter((id) => fileIdSet.has(id)); ++} ++ + function getHighlightedTokensForLine( + line: ReviewRenderableLineRow, + highlightedFile: ReviewHighlightedFile | null, +@@ -252,16 +293,13 @@ const ReviewLineRow = memo(function ReviewLineRow(props: { + delayLongPress={220} + onLongPress={props.onStartRangeSelection} + onPress={props.onComment} +- style={{ minWidth: props.viewportWidth }} ++ style={{ ++ height: REVIEW_DIFF_LINE_HEIGHT, ++ width: props.viewportWidth, ++ overflow: "hidden", ++ }} + > +- +- +- {lineNumber ?? ""} +- +- ++ + ++ ++ ++ {props.lineNumber ?? ""} ++ ++ ++ ); ++}); ++ ++const ReviewHunkGutter = memo(function ReviewHunkGutter(props: { readonly gutterWidth: number }) { ++ return ( ++ ++ ); ++}); ++ + const ReviewFileCard = memo(function ReviewFileCard(props: { + readonly file: ReviewRenderableFile; + readonly fileId: string; + readonly expanded: boolean; ++ readonly viewed: boolean; + readonly viewportWidth: number; + readonly onToggleFile: (fileId: string) => void; ++ readonly onToggleViewed: (fileId: string) => void; + }) { +- const chrome = getFileHeaderChrome(props.file.changeType); ++ const { expanded, file, fileId, onToggleFile, onToggleViewed, viewed, viewportWidth } = props; ++ const chrome = getFileHeaderChrome(file.changeType); ++ const iconColor = String(useThemeColor("--color-icon-muted")); ++ const handleToggleFile = useCallback(() => { ++ onToggleFile(fileId); ++ }, [fileId, onToggleFile]); ++ const handleToggleViewed = useCallback(() => { ++ onToggleViewed(fileId); ++ }, [fileId, onToggleViewed]); + + return ( + +- props.onToggleFile(props.fileId)}> +- +- +- +- +- +- +- +- +- +- {props.file.path} ++ ++ ++ ++ ++ ++ ++ ++ ++ {file.path} ++ ++ {file.previousPath && file.previousPath !== file.path ? ( ++ ++ {file.previousPath} + +- {props.file.previousPath && props.file.previousPath !== props.file.path ? ( +- +- {props.file.previousPath} +- ++ ) : null} ++ ++ ++ ++ ++ -{file.deletions} ++ ++ ++ +{file.additions} ++ ++ ++ ++ {viewed ? ( ++ + ) : null} + +- +- +- +- +{props.file.additions} +- +- +- -{props.file.deletions} ++ ++ Viewed + +- ++ + +- ++ + + ); + }); +@@ -342,7 +453,11 @@ const ReviewFileSuppressedBody = memo(function ReviewFileSuppressedBody(props: { + return ( + + {props.message} + {props.actionLabel && props.onLoadDiffFile ? ( +@@ -364,10 +479,13 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: { + }) { + return ( + +- ++ + {props.header} + {props.context ? ` ${props.context}` : ""} + +@@ -375,6 +493,61 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: { + ); + }); + ++const ReviewCodePanRow = memo(function ReviewCodePanRow(props: { ++ readonly contentWidth: number; ++ readonly horizontalOffset: SharedValue; ++ readonly gutterWidth?: number; ++ readonly viewportWidth: number; ++ readonly leftGutter?: ReactElement; ++ readonly children: ReactElement; ++}) { ++ const { ++ children, ++ contentWidth, ++ gutterWidth = 0, ++ horizontalOffset, ++ leftGutter, ++ viewportWidth, ++ } = props; ++ const dragStartOffset = useSharedValue(0); ++ const visibleContentWidth = leftGutter ? viewportWidth - gutterWidth : viewportWidth; ++ const maxOffset = Math.max(0, contentWidth - visibleContentWidth); ++ ++ const panGesture = useMemo( ++ () => ++ Gesture.Pan() ++ .activeOffsetX([-8, 8]) ++ .failOffsetY([-10, 10]) ++ .onBegin(() => { ++ dragStartOffset.value = horizontalOffset.value; ++ }) ++ .onUpdate((event) => { ++ "worklet"; ++ const nextOffset = dragStartOffset.value - event.translationX; ++ horizontalOffset.value = Math.min(maxOffset, Math.max(0, nextOffset)); ++ }), ++ [dragStartOffset, horizontalOffset, maxOffset], ++ ); ++ ++ const contentStyle = useAnimatedStyle( ++ () => ({ ++ transform: [{ translateX: -horizontalOffset.value }], ++ }), ++ [horizontalOffset], ++ ); ++ ++ return ( ++ ++ ++ {leftGutter ?? null} ++ ++ {children} ++ ++ ++ ++ ); ++}); ++ + const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) { + return ( + +@@ -454,15 +627,19 @@ export function ReviewSheet() { + const [highlightedFilesById, setHighlightedFilesById] = useState< + Record + >({}); +- const [visibleFileIds, setVisibleFileIds] = useState>([]); ++ const deferredHighlightedFilesById = useDeferredValue(highlightedFilesById); ++ const [localExpandedFileIdsBySection, setLocalExpandedFileIdsBySection] = useState< ++ Record> ++ >({}); ++ const [localViewedFileIdsBySection, setLocalViewedFileIdsBySection] = useState< ++ Record> ++ >({}); + const activeCommentTarget = useReviewCommentTarget(); + const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme; +- const highlightQueueRef = useRef([]); +- const highlightRequestedFileIdsRef = useRef>(new Set()); +- const highlightQueueGenerationRef = useRef(0); +- const highlightQueueActiveRef = useRef(false); +- const highlightableFilesByIdRef = useRef>(new Map()); +- const selectedThemeRef = useRef(selectedTheme); ++ const reviewHighlighter = useReviewHighlighterStatus(); ++ const highlightRunIdRef = useRef(0); ++ const highlightableFilesRef = useRef>([]); ++ const horizontalOffsetByFileIdRef = useRef>>(new Map()); + const { selectedThreadCwd } = useSelectedThreadWorktree(); + + const cwd = selectedThreadCwd; +@@ -498,11 +675,13 @@ export function ReviewSheet() { + const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT; + const parsedDiff = useMemo( + () => +- getCachedReviewParsedDiff({ +- threadKey: reviewCache.threadKey, +- sectionId: selectedSection?.id ?? null, +- diff: selectedSection?.diff, +- }), ++ measureReviewWork("parse-diff", () => ++ getCachedReviewParsedDiff({ ++ threadKey: reviewCache.threadKey, ++ sectionId: selectedSection?.id ?? null, ++ diff: selectedSection?.diff, ++ }), ++ ), + [reviewCache.threadKey, selectedSection?.diff, selectedSection?.id], + ); + const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]); +@@ -510,14 +689,53 @@ export function ReviewSheet() { + () => countReviewCommentContexts(draftMessage), + [draftMessage], + ); ++ const viewportWidth = Math.max(width, 280); ++ ++ useEffect(() => { ++ if (!selectedSection?.id || parsedDiff.kind !== "files") { ++ return; ++ } ++ ++ setLocalExpandedFileIdsBySection((current) => { ++ if (current[selectedSection.id] !== undefined) { ++ return current; ++ } ++ ++ return { ++ ...current, ++ [selectedSection.id]: getValidReviewExpandedFileIds( ++ parsedDiff.files, ++ reviewCache.expandedFileIdsBySection[selectedSection.id], ++ ), ++ }; ++ }); ++ ++ setLocalViewedFileIdsBySection((current) => { ++ if (current[selectedSection.id] !== undefined) { ++ return current; ++ } ++ ++ return { ++ ...current, ++ [selectedSection.id]: reviewCache.viewedFileIdsBySection[selectedSection.id] ?? [], ++ }; ++ }); ++ }, [ ++ parsedDiff, ++ reviewCache.expandedFileIdsBySection, ++ reviewCache.viewedFileIdsBySection, ++ selectedSection?.id, ++ ]); + + const expandedFileIds = useMemo( + () => + selectedSection?.id && parsedDiff.kind === "files" +- ? (reviewCache.expandedFileIdsBySection[selectedSection.id] ?? +- getDefaultExpandedFileIds(parsedDiff.files)) ++ ? getValidReviewExpandedFileIds( ++ parsedDiff.files, ++ localExpandedFileIdsBySection[selectedSection.id], ++ ) + : [], +- [parsedDiff, reviewCache.expandedFileIdsBySection, selectedSection?.id], ++ [localExpandedFileIdsBySection, parsedDiff, selectedSection?.id], + ); + const revealedLargeFileIds = useMemo( + () => +@@ -526,47 +744,96 @@ export function ReviewSheet() { + : [], + [reviewCache.revealedLargeFileIdsBySection, selectedSection?.id], + ); ++ const viewedFileIds = useMemo( ++ () => (selectedSection?.id ? (localViewedFileIdsBySection[selectedSection.id] ?? []) : []), ++ [localViewedFileIdsBySection, selectedSection?.id], ++ ); ++ const viewedFileIdSet = useMemo(() => new Set(viewedFileIds), [viewedFileIds]); + const reviewListItems = useMemo( + () => + selectedSection && parsedDiff.kind === "files" +- ? buildReviewListItems({ +- files: parsedDiff.files, +- expandedFileIds, +- revealedLargeFileIds, +- }) ++ ? measureReviewWork("build-list-items", () => ++ buildReviewListItems({ ++ files: parsedDiff.files, ++ expandedFileIds, ++ revealedLargeFileIds, ++ }), ++ ) + : [], + [expandedFileIds, parsedDiff, revealedLargeFileIds, selectedSection], + ); +- const reviewFileById = useMemo(() => { ++ const reviewLineRowsByFileId = useMemo(() => { + if (parsedDiff.kind !== "files") { +- return new Map(); ++ return new Map>(); + } + +- return new Map(parsedDiff.files.map((file) => [file.id, file] as const)); ++ return measureReviewWork( ++ "index-line-rows", ++ () => ++ new Map( ++ parsedDiff.files.map((file) => [ ++ file.id, ++ file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"), ++ ]), ++ ), ++ ); + }, [parsedDiff]); +- const reviewLineRowsByFileId = useMemo(() => { ++ const reviewContentWidthByFileId = useMemo(() => { + if (parsedDiff.kind !== "files") { +- return new Map>(); ++ return new Map(); ++ } ++ ++ return measureReviewWork( ++ "measure-file-widths", ++ () => ++ new Map( ++ parsedDiff.files.map((file) => [ ++ file.id, ++ computeReviewFileContentWidth( ++ file.rows, ++ viewportWidth, ++ computeReviewFileGutterWidth(file.rows), ++ ), ++ ]), ++ ), ++ ); ++ }, [parsedDiff, viewportWidth]); ++ const reviewGutterWidthByFileId = useMemo(() => { ++ if (parsedDiff.kind !== "files") { ++ return new Map(); + } + + return new Map( +- parsedDiff.files.map((file) => [ +- file.id, +- file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"), +- ]), ++ parsedDiff.files.map((file) => [file.id, computeReviewFileGutterWidth(file.rows)]), + ); + }, [parsedDiff]); +- const reviewLineIndexByRowId = useMemo(() => { +- const map = new Map(); ++ const getReviewFileHorizontalOffset = useCallback((fileId: string) => { ++ let offset = horizontalOffsetByFileIdRef.current.get(fileId); ++ if (!offset) { ++ offset = makeMutable(0); ++ horizontalOffsetByFileIdRef.current.set(fileId, offset); ++ } + +- reviewLineRowsByFileId.forEach((rows) => { +- rows.forEach((row, index) => { +- map.set(row.id, index); +- }); +- }); ++ return offset; ++ }, []); ++ useEffect(() => { ++ const knownFileIds = ++ parsedDiff.kind === "files" ? new Set(parsedDiff.files.map((file) => file.id)) : new Set(); + +- return map; +- }, [reviewLineRowsByFileId]); ++ horizontalOffsetByFileIdRef.current.forEach((offset, fileId) => { ++ if (!knownFileIds.has(fileId)) { ++ horizontalOffsetByFileIdRef.current.delete(fileId); ++ return; ++ } ++ ++ const contentWidth = reviewContentWidthByFileId.get(fileId) ?? viewportWidth; ++ const gutterWidth = reviewGutterWidthByFileId.get(fileId) ?? 0; ++ offset.value = Math.min( ++ offset.value, ++ Math.max(0, contentWidth - (viewportWidth - gutterWidth)), ++ ); ++ }); ++ }, [parsedDiff, reviewContentWidthByFileId, reviewGutterWidthByFileId, viewportWidth]); + const highlightableFiles = useMemo(() => { + if (parsedDiff.kind !== "files") { + return [] as ReadonlyArray; +@@ -587,59 +854,13 @@ export function ReviewSheet() { + ); + }); + }, [expandedFileIds, parsedDiff, revealedLargeFileIds]); +- const highlightableFileIds = useMemo( +- () => new Set(highlightableFiles.map((file) => file.id)), ++ const highlightableFilesKey = useMemo( ++ () => highlightableFiles.map((file) => `${file.id}:${file.cacheKey}`).join("\n"), + [highlightableFiles], + ); +- const priorityHighlightFileIds = useMemo(() => { +- if (parsedDiff.kind !== "files" || highlightableFiles.length === 0) { +- return [] as ReadonlyArray; +- } +- +- const fileIdsInPriorityOrder = +- visibleFileIds.length > 0 +- ? visibleFileIds.filter((fileId) => highlightableFileIds.has(fileId)) +- : parsedDiff.files +- .slice(0, REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT) +- .map((file) => file.id) +- .filter((fileId) => highlightableFileIds.has(fileId)); +- +- if (fileIdsInPriorityOrder.length === 0) { +- return [] as ReadonlyArray; +- } +- +- const firstVisibleIndex = parsedDiff.files.findIndex( +- (file) => file.id === fileIdsInPriorityOrder[0], +- ); +- const lastVisibleIndex = parsedDiff.files.findIndex( +- (file) => file.id === fileIdsInPriorityOrder[fileIdsInPriorityOrder.length - 1], +- ); +- +- if (firstVisibleIndex < 0 || lastVisibleIndex < 0) { +- return fileIdsInPriorityOrder; +- } +- +- const startIndex = Math.max(0, firstVisibleIndex - REVIEW_HIGHLIGHT_BACKTRACK_COUNT); +- const endIndex = Math.min( +- parsedDiff.files.length - 1, +- lastVisibleIndex + REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT, +- ); +- +- const queuedIds: string[] = []; +- for (let index = startIndex; index <= endIndex; index += 1) { +- const fileId = parsedDiff.files[index]?.id; +- if (fileId && highlightableFileIds.has(fileId)) { +- queuedIds.push(fileId); +- } +- } +- +- return queuedIds; +- }, [highlightableFileIds, highlightableFiles.length, parsedDiff, visibleFileIds]); +- const viewportWidth = Math.max(width, 280); +- const reviewListContentWidth = useMemo( +- () => computeReviewListContentWidth(reviewListItems, viewportWidth), +- [reviewListItems, viewportWidth], +- ); ++ useEffect(() => { ++ highlightableFilesRef.current = highlightableFiles; ++ }, [highlightableFiles]); + const loadGitDiffs = useCallback(async () => { + if (!cwd) { + return; +@@ -714,100 +935,6 @@ export function ReviewSheet() { + void loadGitDiffs(); + }, [loadGitDiffs]); + +- useEffect(() => { +- selectedThemeRef.current = selectedTheme; +- }, [selectedTheme]); +- +- useEffect(() => { +- highlightableFilesByIdRef.current = new Map(highlightableFiles.map((file) => [file.id, file])); +- }, [highlightableFiles]); +- +- const startHighlightQueueRunner = useCallback(function startHighlightQueueRunner() { +- if (highlightQueueActiveRef.current) { +- return; +- } +- +- const generation = highlightQueueGenerationRef.current; +- highlightQueueActiveRef.current = true; +- +- void (async () => { +- try { +- while (generation === highlightQueueGenerationRef.current) { +- const nextFileId = highlightQueueRef.current.shift(); +- if (!nextFileId) { +- break; +- } +- +- const file = highlightableFilesByIdRef.current.get(nextFileId); +- if (!file) { +- continue; +- } +- +- const theme = selectedThemeRef.current; +- const cached = getCachedHighlightedReviewFile(file, theme); +- if (cached) { +- logReviewDiffDiagnostic("using cached highlighted file", { +- fileId: file.id, +- filePath: file.path, +- theme, +- }); +- setHighlightedFilesById((current) => +- current[file.id] === cached ? current : { ...current, [file.id]: cached }, +- ); +- continue; +- } +- +- logReviewDiffDiagnostic("requesting highlighted file", { +- fileId: file.id, +- filePath: file.path, +- theme, +- }); +- +- try { +- await new Promise((resolve) => { +- InteractionManager.runAfterInteractions(() => resolve()); +- }); +- const result = await highlightReviewFile(file, theme); +- if (generation !== highlightQueueGenerationRef.current) { +- logReviewDiffDiagnostic("discarding highlighted file after cancellation", { +- fileId: file.id, +- filePath: file.path, +- }); +- return; +- } +- +- logReviewDiffDiagnostic("received highlighted file", { +- fileId: file.id, +- filePath: file.path, +- additionLines: result.additionLines.length, +- deletionLines: result.deletionLines.length, +- }); +- setHighlightedFilesById((current) => { +- if (current[file.id] === result) { +- return current; +- } +- return { ...current, [file.id]: result }; +- }); +- } catch (error) { +- logReviewDiffDiagnostic("highlight request failed", { +- fileId: file.id, +- filePath: file.path, +- error: error instanceof Error ? error.message : String(error), +- }); +- } +- } +- } finally { +- highlightQueueActiveRef.current = false; +- if ( +- generation === highlightQueueGenerationRef.current && +- highlightQueueRef.current.length > 0 +- ) { +- startHighlightQueueRunner(); +- } +- } +- })(); +- }, []); +- + useEffect(() => { + if (reviewSections.length === 0) { + return; +@@ -854,15 +981,15 @@ export function ReviewSheet() { + } + + updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => { +- if (existing !== undefined) { +- const validIds = existing.filter((id) => parsedDiff.files.some((file) => file.id === id)); +- if (validIds.length === existing.length) { +- return existing; +- } +- return validIds; ++ const validIds = getValidReviewExpandedFileIds(parsedDiff.files, existing); ++ if ( ++ existing !== undefined && ++ validIds.length === existing.length && ++ validIds.every((id, index) => id === existing[index]) ++ ) { ++ return existing; + } +- +- return getDefaultExpandedFileIds(parsedDiff.files); ++ return validIds; + }); + }, [parsedDiff, reviewCache.threadKey, selectedSection?.id]); + +@@ -887,11 +1014,7 @@ export function ReviewSheet() { + + useEffect(() => { + setHighlightedFilesById({}); +- setVisibleFileIds([]); +- highlightQueueGenerationRef.current += 1; +- highlightQueueRef.current = []; +- highlightRequestedFileIdsRef.current = new Set(); +- highlightQueueActiveRef.current = false; ++ highlightRunIdRef.current += 1; + clearReviewHighlightFileCache(); + loggedMissingReviewTokenKeys.clear(); + logReviewDiffDiagnostic("reset highlighted files", { +@@ -905,15 +1028,23 @@ export function ReviewSheet() { + return; + } + ++ markReviewEvent("parsed-diff-ready", { ++ sectionId: selectedSection?.id ?? null, ++ fileCount: parsedDiff.fileCount, ++ additions: parsedDiff.additions, ++ deletions: parsedDiff.deletions, ++ renderedItems: reviewListItems.length, ++ }); + logReviewDiffDiagnostic("parsed diff files", { + selectedSectionId: selectedSection?.id ?? null, + fileCount: parsedDiff.fileCount, + renderableFileCount: parsedDiff.files.length, + }); +- }, [parsedDiff, selectedSection?.id]); ++ }, [parsedDiff, reviewListItems.length, selectedSection?.id]); + + useEffect(() => { +- if (priorityHighlightFileIds.length === 0) { ++ const files = highlightableFilesRef.current; ++ if (files.length === 0) { + logReviewDiffDiagnostic("no highlightable files", { + selectedSectionId: selectedSection?.id ?? null, + parsedDiffKind: parsedDiff.kind, +@@ -922,33 +1053,98 @@ export function ReviewSheet() { + return; + } + +- const queuedFileIds: string[] = []; +- priorityHighlightFileIds.forEach((fileId) => { +- if (highlightRequestedFileIdsRef.current.has(fileId)) { +- return; +- } +- +- const file = highlightableFilesByIdRef.current.get(fileId); +- if (!file) { +- return; +- } +- +- highlightRequestedFileIdsRef.current.add(fileId); +- highlightQueueRef.current.push(fileId); +- queuedFileIds.push(fileId); +- }); +- +- if (queuedFileIds.length === 0) { ++ if (reviewHighlighter.status !== "ready") { ++ logReviewDiffDiagnostic("waiting for highlighter provider", { ++ selectedSectionId: selectedSection?.id ?? null, ++ status: reviewHighlighter.status, ++ error: reviewHighlighter.error, ++ }); + return; + } + +- logReviewDiffDiagnostic("scheduling file highlights", { ++ const runId = highlightRunIdRef.current; ++ let cancelled = false; ++ ++ logReviewDiffDiagnostic("streaming file highlights", { + selectedSectionId: selectedSection?.id ?? null, +- fileCount: queuedFileIds.length, +- fileIds: queuedFileIds, ++ fileCount: files.length, + }); +- startHighlightQueueRunner(); +- }, [parsedDiff.kind, priorityHighlightFileIds, selectedSection?.id, startHighlightQueueRunner]); ++ ++ void (async () => { ++ for (const file of files) { ++ if (cancelled || runId !== highlightRunIdRef.current) { ++ return; ++ } ++ ++ const cached = getCachedHighlightedReviewFile(file, selectedTheme); ++ if (cached) { ++ setHighlightedFilesById((current) => ++ current[file.id] === cached ? current : { ...current, [file.id]: cached }, ++ ); ++ continue; ++ } ++ ++ logReviewDiffDiagnostic("requesting highlighted file", { ++ fileId: file.id, ++ filePath: file.path, ++ theme: selectedTheme, ++ }); ++ ++ try { ++ const highlightStartedAt = performance.now(); ++ const result = await streamHighlightReviewFile(file, selectedTheme, (progress) => { ++ if (cancelled || runId !== highlightRunIdRef.current) { ++ return; ++ } ++ ++ if (!progress.complete) { ++ return; ++ } ++ ++ logReviewDiffDiagnostic("received streamed highlighted file", { ++ fileId: file.id, ++ filePath: file.path, ++ highlightedLineCount: progress.highlightedLineCount, ++ durationMs: Math.round(performance.now() - highlightStartedAt), ++ }); ++ }); ++ ++ if (cancelled || runId !== highlightRunIdRef.current) { ++ return; ++ } ++ ++ logReviewDiffDiagnostic("received highlighted file", { ++ fileId: file.id, ++ filePath: file.path, ++ additionLines: result.additionLines.length, ++ deletionLines: result.deletionLines.length, ++ }); ++ setHighlightedFilesById((current) => ++ current[file.id] === result ? current : { ...current, [file.id]: result }, ++ ); ++ } catch (error) { ++ logReviewDiffDiagnostic("highlight request failed", { ++ fileId: file.id, ++ filePath: file.path, ++ error: error instanceof Error ? error.message : String(error), ++ }); ++ } ++ ++ await waitForReviewDelay(0); ++ } ++ })(); ++ ++ return () => { ++ cancelled = true; ++ }; ++ }, [ ++ highlightableFilesKey, ++ parsedDiff.kind, ++ reviewHighlighter.error, ++ reviewHighlighter.status, ++ selectedSection?.id, ++ selectedTheme, ++ ]); + + const refreshSelectedSection = useCallback(async () => { + if (!selectedSection) { +@@ -968,20 +1164,68 @@ export function ReviewSheet() { + + const handleToggleExpandedFile = useCallback( + (fileId: string) => { +- if (!reviewCache.threadKey || !selectedSection?.id || parsedDiff.kind !== "files") { ++ if (!selectedSection?.id || parsedDiff.kind !== "files") { + return; + } + +- updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => { +- const currentIds = existing ?? getDefaultExpandedFileIds(parsedDiff.files); +- return currentIds.includes(fileId) ++ const sectionId = selectedSection.id; ++ ++ setLocalExpandedFileIdsBySection((current) => { ++ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, current[sectionId]); ++ const nextIds = currentIds.includes(fileId) + ? currentIds.filter((id) => id !== fileId) + : [...currentIds, fileId]; ++ ++ return { ++ ...current, ++ [sectionId]: nextIds, ++ }; + }); ++ ++ if (reviewCache.threadKey) { ++ updateReviewExpandedFileIds(reviewCache.threadKey, sectionId, (existing) => { ++ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, existing); ++ return currentIds.includes(fileId) ++ ? currentIds.filter((id) => id !== fileId) ++ : [...currentIds, fileId]; ++ }); ++ } + }, + [parsedDiff, reviewCache.threadKey, selectedSection?.id], + ); + ++ const handleToggleViewedFile = useCallback( ++ (fileId: string) => { ++ if (!selectedSection?.id) { ++ return; ++ } ++ ++ const sectionId = selectedSection.id; ++ ++ setLocalViewedFileIdsBySection((current) => { ++ const currentIds = current[sectionId] ?? []; ++ const nextIds = currentIds.includes(fileId) ++ ? currentIds.filter((id) => id !== fileId) ++ : [...currentIds, fileId]; ++ ++ return { ++ ...current, ++ [sectionId]: nextIds, ++ }; ++ }); ++ ++ if (reviewCache.threadKey) { ++ updateReviewViewedFileIds(reviewCache.threadKey, sectionId, (existing) => { ++ const currentIds = existing ?? []; ++ return currentIds.includes(fileId) ++ ? currentIds.filter((id) => id !== fileId) ++ : [...currentIds, fileId]; ++ }); ++ } ++ }, ++ [reviewCache.threadKey, selectedSection?.id], ++ ); ++ + const handleRevealLargeDiff = useCallback( + (fileId: string) => { + if (!reviewCache.threadKey || !selectedSection?.id) { +@@ -1080,35 +1324,6 @@ export function ReviewSheet() { + + return <>{children}; + }, [error, parsedDiffNotice]); +- const stickyHeaderIndices = useMemo(() => { +- const itemOffset = listHeader ? 1 : 0; +- +- return reviewListItems.flatMap((item, index) => +- item.kind === "file-header" ? [index + itemOffset] : [], +- ); +- }, [listHeader, reviewListItems]); +- +- const viewabilityConfigRef = useRef({ +- itemVisiblePercentThreshold: 10, +- }); +- const onViewableItemsChangedRef = useRef( +- ({ +- viewableItems, +- }: { +- readonly viewableItems: Array>; +- readonly changed: Array>; +- }) => { +- const nextVisibleFileIds = Array.from( +- new Set( +- viewableItems +- .filter((token) => token.isViewable && token.item !== undefined) +- .map((token) => token.item.fileId), +- ), +- ); +- +- setVisibleFileIds(nextVisibleFileIds); +- }, +- ); + + const renderReviewListItem = useCallback( + ({ item }: ListRenderItemInfo) => { +@@ -1116,112 +1331,142 @@ export function ReviewSheet() { + return null; + } + ++ let renderedItem: ReactElement | null = null; + switch (item.kind) { + case "file-header": +- return ( ++ renderedItem = ( + + ); ++ break; + case "file-suppressed": +- return ( ++ renderedItem = ( + + ); +- case "hunk": +- return ( +- ++ break; ++ case "hunk": { ++ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth; ++ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0; ++ ++ renderedItem = ( ++ } ++ viewportWidth={viewportWidth} ++ > ++ ++ + ); ++ break; ++ } + case "line": { +- const file = reviewFileById.get(item.fileId); +- if (!file) { +- return null; +- } +- +- const fileLineRows = reviewLineRowsByFileId.get(file.id) ?? []; +- const lineIndex = reviewLineIndexByRowId.get(item.row.id); +- if (lineIndex === undefined) { +- return null; +- } +- ++ const fileLineRows = reviewLineRowsByFileId.get(item.file.id) ?? []; + const pendingSelectionForFile = + pendingCommentSelection && + pendingCommentSelection.sectionTitle === selectedSection.title && +- pendingCommentSelection.filePath === file.path ++ pendingCommentSelection.filePath === item.file.path + ? pendingCommentSelection + : null; + const selectedTargetForFile = + activeCommentTarget && + activeCommentTarget.sectionTitle === selectedSection.title && +- activeCommentTarget.filePath === file.path ++ activeCommentTarget.filePath === item.file.path + ? activeCommentTarget + : null; + const highlightedFile = +- highlightedFilesById[file.id] ?? +- getCachedHighlightedReviewFile(file, selectedTheme) ?? ++ deferredHighlightedFilesById[item.file.id] ?? ++ getCachedHighlightedReviewFile(item.file, selectedTheme) ?? + null; ++ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth; ++ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0; + + if (highlightedFile === null) { +- const missingTokenKey = `${selectedSection.id}:${file.id}`; ++ const missingTokenKey = `${selectedSection.id}:${item.file.id}`; + if (!loggedMissingReviewTokenKeys.has(missingTokenKey)) { + loggedMissingReviewTokenKeys.add(missingTokenKey); + logReviewDiffDiagnostic("rendering file without tokens", { + sectionId: selectedSection.id, +- fileId: file.id, +- filePath: file.path, +- highlightedFileKnownInState: highlightedFilesById[file.id] !== undefined, ++ fileId: item.file.id, ++ filePath: item.file.path, ++ highlightedFileKnownInState: ++ deferredHighlightedFilesById[item.file.id] !== undefined, + }); + } + } + + const selectionState = +- pendingSelectionForFile?.anchorIndex === lineIndex ++ pendingSelectionForFile?.anchorIndex === item.lineIndex + ? ("anchor" as const) + : selectedTargetForFile && +- lineIndex >= selectedTargetForFile.startIndex && +- lineIndex <= selectedTargetForFile.endIndex ++ item.lineIndex >= selectedTargetForFile.startIndex && ++ item.lineIndex <= selectedTargetForFile.endIndex + ? ("selected" as const) + : null; + +- return ( +- +- handlePressLine({ +- sectionTitle: selectedSection.title, +- filePath: file.path, +- lines: fileLineRows, +- lineIndex, +- }) +- } +- onStartRangeSelection={() => +- handleStartRangeSelection({ +- sectionTitle: selectedSection.title, +- filePath: file.path, +- lines: fileLineRows, +- lineIndex, +- }) ++ renderedItem = ( ++ + } +- /> ++ viewportWidth={viewportWidth} ++ > ++ ++ handlePressLine({ ++ sectionTitle: selectedSection.title, ++ filePath: item.file.path, ++ lines: fileLineRows, ++ lineIndex: item.lineIndex, ++ }) ++ } ++ onStartRangeSelection={() => ++ handleStartRangeSelection({ ++ sectionTitle: selectedSection.title, ++ filePath: item.file.path, ++ lines: fileLineRows, ++ lineIndex: item.lineIndex, ++ }) ++ } ++ /> ++ + ); ++ break; + } + } ++ ++ return renderedItem; + }, + [ + activeCommentTarget, +@@ -1229,14 +1474,17 @@ export function ReviewSheet() { + handleRevealLargeDiff, + handleStartRangeSelection, + handleToggleExpandedFile, +- highlightedFilesById, ++ handleToggleViewedFile, ++ getReviewFileHorizontalOffset, ++ deferredHighlightedFilesById, + pendingCommentSelection, +- reviewFileById, +- reviewLineIndexByRowId, ++ reviewContentWidthByFileId, ++ reviewGutterWidthByFileId, + reviewLineRowsByFileId, +- reviewListContentWidth, + selectedSection, + selectedTheme, ++ viewedFileIdSet, ++ viewportWidth, + ], + ); + +@@ -1374,27 +1622,20 @@ export function ReviewSheet() { + + {selectedSection && parsedDiff.kind === "files" ? ( + item.id} ++ initialNumToRender={20} ++ maxToRenderPerBatch={20} ++ updateCellsBatchingPeriod={16} ++ windowSize={5} ++ removeClippedSubviews={false} + keyboardShouldPersistTaps="handled" + ListHeaderComponent={listHeader} +- stickyHeaderIndices={stickyHeaderIndices} +- removeClippedSubviews={false} +- initialNumToRender={24} +- maxToRenderPerBatch={16} +- updateCellsBatchingPeriod={16} +- windowSize={10} +- scrollEventThrottle={16} +- onViewableItemsChanged={onViewableItemsChangedRef.current} +- viewabilityConfig={viewabilityConfigRef.current} + contentContainerStyle={{ +- paddingTop: REVIEW_HEADER_SPACING, ++ paddingTop: topContentInset + REVIEW_HEADER_SPACING, + paddingBottom: Math.max(insets.bottom, 18) + 18, + }} + /> +diff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx +index d61924a62..3f2ae0160 100644 +--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx ++++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx +@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({ + default: "monospace", + }); + ++export const REVIEW_DIFF_LINE_HEIGHT = 26; ++const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2; ++ + export function renderVisibleWhitespace(value: string): string { + const expandedTabs = value.replace(/\t/g, " "); + return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\u00A0")); +@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string | + export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) { + if (props.change === "delete") { + return ( +- +- +- {Array.from({ length: 6 }, (_, index) => ( +- ++ ++ ++ {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => ( ++ ++ ++ ++ + ))} + + +@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo + } + + return ( +- ++ + + + ); +@@ -63,6 +69,7 @@ export function DiffTokenText(props: { + if (!props.tokens || props.tokens.length === 0) { + return ( + { +- it("defaults invalid values to javascript", () => { +- expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("javascript"); +- expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("javascript"); ++ it("defaults invalid values to native", () => { ++ expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("native"); ++ expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("native"); + }); + + it("accepts supported values", () => { +diff --git a/apps/mobile/src/features/review/reviewHighlighterEngine.ts b/apps/mobile/src/features/review/reviewHighlighterEngine.ts +index 5ef9f055a..428768537 100644 +--- a/apps/mobile/src/features/review/reviewHighlighterEngine.ts ++++ b/apps/mobile/src/features/review/reviewHighlighterEngine.ts +@@ -11,7 +11,7 @@ export function resolveReviewHighlighterEnginePreference( + case "native": + return "native"; + default: +- return "javascript"; ++ return "native"; + } + } + +diff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts +index a24a99ceb..69a6e7261 100644 +--- a/apps/mobile/src/features/review/reviewModel.test.ts ++++ b/apps/mobile/src/features/review/reviewModel.test.ts +@@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => { + }); + }); + +- it("flattens expanded files into virtualizable review items", () => { ++ it("flattens expanded file rows into virtualized review items", () => { + const file = makeRenderableFile({ + path: "apps/mobile/src/a.ts", + rows: [ +@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => { + + expect(items).toEqual([ + expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }), +- expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }), +- expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }), ++ expect.objectContaining({ ++ kind: "hunk", ++ fileId: file.id, ++ file, ++ row: file.rows[0], ++ }), ++ expect.objectContaining({ ++ kind: "line", ++ fileId: file.id, ++ file, ++ row: file.rows[1], ++ lineIndex: 0, ++ }), + ]); + }); + +diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts +index 27e6d7ae4..1cfbf358c 100644 +--- a/apps/mobile/src/features/review/reviewModel.ts ++++ b/apps/mobile/src/features/review/reviewModel.ts +@@ -72,6 +72,7 @@ export interface ReviewHunkListItem { + readonly kind: "hunk"; + readonly id: string; + readonly fileId: string; ++ readonly file: ReviewRenderableFile; + readonly row: ReviewRenderableHunkRow; + } + +@@ -79,7 +80,9 @@ export interface ReviewLineListItem { + readonly kind: "line"; + readonly id: string; + readonly fileId: string; ++ readonly file: ReviewRenderableFile; + readonly row: ReviewRenderableLineRow; ++ readonly lineIndex: number; + } + + export type ReviewListItem = +@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil + } + + // The flattened review list item model is inspired by pierre/diffs' iterator-first +-// virtualization architecture, adapted here for React Native and LegendList. ++// virtualization architecture, adapted here for React Native virtualization. + // Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs + // Reference files: + // - src/utils/iterateOverDiff.ts +@@ -350,12 +353,14 @@ export function buildReviewListItems(input: { + } + } + +- file.rows.forEach((row) => { ++ let lineIndex = 0; ++ file.rows.forEach((row, rowIndex) => { + if (row.kind === "hunk") { + items.push({ + kind: "hunk", +- id: row.id, ++ id: `${file.id}:row:${rowIndex}:${row.id}`, + fileId: file.id, ++ file, + row, + }); + return; +@@ -363,10 +368,13 @@ export function buildReviewListItems(input: { + + items.push({ + kind: "line", +- id: row.id, ++ id: `${file.id}:row:${rowIndex}:${row.id}`, + fileId: file.id, ++ file, + row, ++ lineIndex, + }); ++ lineIndex += 1; + }); + }); + +diff --git a/apps/mobile/src/features/review/reviewState.ts b/apps/mobile/src/features/review/reviewState.ts +index 06134db7d..c116f93fe 100644 +--- a/apps/mobile/src/features/review/reviewState.ts ++++ b/apps/mobile/src/features/review/reviewState.ts +@@ -64,6 +64,13 @@ const reviewRevealedLargeFileIdsByThreadKeyAtom = Atom.family((threadKey: string + ), + ); + ++const reviewViewedFileIdsByThreadKeyAtom = Atom.family((threadKey: string) => ++ Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe( ++ Atom.keepAlive, ++ Atom.withLabel(`mobile:review:viewed-file-ids:${threadKey}`), ++ ), ++); ++ + const reviewParsedDiffBySectionCacheKeyAtom = Atom.family((cacheKey: string) => + Atom.make<{ readonly diff: string | null; readonly parsed: ReviewParsedDiff } | null>(null).pipe( + Atom.keepAlive, +@@ -110,6 +117,9 @@ export function useReviewCacheForThread(input: { + ? reviewRevealedLargeFileIdsByThreadKeyAtom(threadKey) + : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM, + ); ++ const viewedFileIdsBySection = useAtomValue( ++ threadKey ? reviewViewedFileIdsByThreadKeyAtom(threadKey) : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM, ++ ); + + return { + threadKey, +@@ -118,6 +128,7 @@ export function useReviewCacheForThread(input: { + selectedSectionId, + expandedFileIdsBySection, + revealedLargeFileIdsBySection, ++ viewedFileIdsBySection, + }; + } + +@@ -169,6 +180,20 @@ export function updateReviewRevealedLargeFileIds( + }); + } + ++export function updateReviewViewedFileIds( ++ threadKey: string, ++ sectionId: string, ++ update: (current: ReadonlyArray | undefined) => ReadonlyArray | undefined, ++): void { ++ const atom = reviewViewedFileIdsByThreadKeyAtom(threadKey); ++ const current = appAtomRegistry.get(atom); ++ const nextValue = update(current[sectionId]); ++ appAtomRegistry.set(atom, { ++ ...current, ++ [sectionId]: nextValue, ++ }); ++} ++ + export function getCachedReviewParsedDiff(input: { + readonly threadKey: string | null; + readonly sectionId: string | null; +diff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts +index 05b5c9213..402d00668 100644 +--- a/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts ++++ b/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts +@@ -24,7 +24,7 @@ function makeRenderableFile( + describe("highlightReviewFile", () => { + it("preserves one highlighted token row per diff line even without trailing newlines", async () => { + const file = makeRenderableFile({ +- path: "apps/mobile/src/example.test.ts", ++ path: "apps/mobile/src/example.txt", + additionLines: [ + 'const items = ["a"];', + 'expect(items).toEqual(["a"]);', +@@ -36,15 +36,23 @@ describe("highlightReviewFile", () => { + const highlighted = await highlightReviewFile(file, "light"); + + expect(highlighted.additionLines).toHaveLength(file.additionLines.length); +- expect(highlighted.additionLines[0]?.some((token) => token.content === "const")).toBe(true); +- expect(highlighted.additionLines[1]?.some((token) => token.content === "expect")).toBe(true); +- expect(highlighted.additionLines[2]?.some((token) => token.content === "const")).toBe(true); +- expect(highlighted.additionLines[3]?.some((token) => token.content === "expect")).toBe(true); ++ expect(highlighted.additionLines[0]?.map((token) => token.content).join("")).toBe( ++ file.additionLines[0], ++ ); ++ expect(highlighted.additionLines[1]?.map((token) => token.content).join("")).toBe( ++ file.additionLines[1], ++ ); ++ expect(highlighted.additionLines[2]?.map((token) => token.content).join("")).toBe( ++ file.additionLines[2], ++ ); ++ expect(highlighted.additionLines[3]?.map((token) => token.content).join("")).toBe( ++ file.additionLines[3], ++ ); + }); + + it("adds word-alt diff emphasis for paired deletion and addition lines", async () => { + const file = makeRenderableFile({ +- path: "apps/mobile/src/example-inline-diff.test.ts", ++ path: "apps/mobile/src/example-inline-diff.txt", + additionLines: ["const after = 2;"], + deletionLines: ["const before = 1;"], + rows: [ +@@ -82,7 +90,7 @@ describe("highlightReviewFile", () => { + it("falls back to plain tokens for very long lines", async () => { + const longLine = `const value = "${"a".repeat(1_100)}";`; + const file = makeRenderableFile({ +- path: "apps/mobile/src/example-long-line.ts", ++ path: "apps/mobile/src/example-long-line.txt", + additionLines: [longLine], + rows: [ + { +diff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.ts +index f7a5c4125..eb6bf6973 100644 +--- a/apps/mobile/src/features/review/shikiReviewHighlighter.ts ++++ b/apps/mobile/src/features/review/shikiReviewHighlighter.ts +@@ -1,5 +1,14 @@ + import { createHighlighterCore, type HighlighterCore } from "@shikijs/core"; + import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript"; ++import bashLanguage from "@shikijs/langs/bash"; ++import javascriptLanguage from "@shikijs/langs/javascript"; ++import jsonLanguage from "@shikijs/langs/json"; ++import jsxLanguage from "@shikijs/langs/jsx"; ++import tsxLanguage from "@shikijs/langs/tsx"; ++import typescriptLanguage from "@shikijs/langs/typescript"; ++import yamlLanguage from "@shikijs/langs/yaml"; ++import githubDarkDefault from "@shikijs/themes/github-dark-default"; ++import githubLightDefault from "@shikijs/themes/github-light-default"; + import { getFiletypeFromFileName } from "@pierre/diffs/utils"; + + import { +@@ -11,6 +20,7 @@ import type { ReviewRenderableFile, ReviewRenderableLineRow } from "./reviewMode + import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs"; + + export type ReviewDiffTheme = "light" | "dark"; ++export type { ReviewHighlighterEngine }; + + export interface ReviewHighlightedToken { + content: string; +@@ -24,12 +34,19 @@ export interface ReviewHighlightedFile { + readonly deletionLines: ReadonlyArray>; + } + ++export interface ReviewHighlightFileProgress { ++ readonly highlightedFile: ReviewHighlightedFile; ++ readonly complete: boolean; ++ readonly highlightedLineCount: number; ++} ++ + const SHIKI_THEME_NAME_BY_SCHEME = { + light: "github-light-default", + dark: "github-dark-default", + } as const; + const REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE = +- process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? "javascript"; ++ process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? ++ (process.env.NODE_ENV === "test" ? "javascript" : "native"); + const REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE = resolveReviewHighlighterEnginePreference( + REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE, + ); +@@ -38,12 +55,30 @@ const REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE = resolveReviewHighlighterBooleanF + false, + ); + const REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT = 8; +-const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 40; +-const REVIEW_HIGHLIGHT_CHUNK_SIZE = 20; ++const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 8; ++const REVIEW_HIGHLIGHT_CHUNK_SIZE = 200; + const REVIEW_TOKENIZE_MAX_LINE_LENGTH = 1_000; + const highlightCache = new Map>(); + const resolvedHighlightCache = new Map(); +-const loadedLanguages = new Set(["text"]); ++const REVIEW_INITIAL_LANGUAGE_MODULES = [ ++ bashLanguage, ++ javascriptLanguage, ++ jsonLanguage, ++ jsxLanguage, ++ tsxLanguage, ++ typescriptLanguage, ++ yamlLanguage, ++] satisfies Parameters[0]["langs"]; ++const loadedLanguages = new Set([ ++ "text", ++ "bash", ++ "javascript", ++ "json", ++ "jsx", ++ "tsx", ++ "typescript", ++ "yaml", ++]); + const languageLoadingPromises = new Map>(); + const languageImports: Partial Promise>> = { + javascript: () => import("@shikijs/langs/javascript"), +@@ -215,21 +250,13 @@ function joinPatchLines(lines: ReadonlyArray): string { + + function waitForNextFrame(): Promise { + return new Promise((resolve) => { +- if (typeof requestAnimationFrame === "function") { +- requestAnimationFrame(() => resolve()); +- return; +- } +- + setTimeout(resolve, 0); + }); + } + + async function getHighlighter(): Promise { + if (!highlighterPromise) { +- const configuredHighlighterPromise = Promise.all([ +- import("@shikijs/themes/github-light-default"), +- import("@shikijs/themes/github-dark-default"), +- ]).then(async ([lightThemeModule, darkThemeModule]) => { ++ const configuredHighlighterPromise = (async () => { + let nativeEngineAvailable = false; + + logReviewHighlighterDiagnostic("initializing", { +@@ -238,12 +265,11 @@ async function getHighlighter(): Promise { + resultCacheDisabled: REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE, + }); + +- const themes = [lightThemeModule.default, darkThemeModule.default]; ++ const themes = [githubLightDefault, githubDarkDefault]; + + if (REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE !== "javascript") { + try { + const nativeEngineModule = await import("react-native-shiki-engine"); +- logReviewHighlighterDiagnostic("imported react-native-shiki-engine"); + nativeEngineAvailable = nativeEngineModule.isNativeEngineAvailable(); + logReviewHighlighterDiagnostic("checked native engine availability", { + nativeEngineAvailable, +@@ -253,7 +279,7 @@ async function getHighlighter(): Promise { + logReviewHighlighterDiagnostic("creating native regex engine"); + const highlighter = await createHighlighterCore({ + themes, +- langs: [], ++ langs: REVIEW_INITIAL_LANGUAGE_MODULES, + engine: nativeEngineModule.createNativeEngine(), + }); + logReviewHighlighterDiagnostic("using native engine"); +@@ -281,7 +307,7 @@ async function getHighlighter(): Promise { + ); + const highlighter = await createHighlighterCore({ + themes, +- langs: [], ++ langs: REVIEW_INITIAL_LANGUAGE_MODULES, + engine: createJavaScriptRegexEngine(), + }); + logReviewHighlighterDiagnostic("using javascript engine", { +@@ -291,7 +317,7 @@ async function getHighlighter(): Promise { + highlighter, + engine, + }; +- }); ++ })(); + + highlighterPromise = configuredHighlighterPromise + .then((result) => result.highlighter) +@@ -316,11 +342,52 @@ export async function getActiveReviewHighlighterEngine(): Promise { ++ await getHighlighter(); ++} ++ ++export async function prepareReviewHighlighterLanguages( ++ languages: ReadonlyArray, ++): Promise { ++ const highlighter = await getHighlighter(); ++ await Promise.all( ++ languages.map(async (language) => { ++ const candidate = resolveLanguageAlias(language); ++ if (candidate === "text" || !(candidate in languageImports)) { ++ return; ++ } ++ ++ await loadSingleLanguage(highlighter, candidate); ++ }), ++ ); ++} ++ + function resolveLanguageAlias(language: string): string { + const normalized = language.toLowerCase(); + return languageAliases[normalized] ?? normalized; + } + ++function resolveLoadedLanguageFromPath( ++ path: string, ++ languageHint: string | null = null, ++): string | null { ++ const detectedLanguage = languageHint ?? getFiletypeFromFileName(path); ++ if (!detectedLanguage) { ++ return "text"; ++ } ++ ++ const candidate = resolveLanguageAlias(detectedLanguage); ++ if (candidate === "text" || candidate === "ansi") { ++ return "text"; ++ } ++ ++ if (!(candidate in languageImports)) { ++ return "text"; ++ } ++ ++ return loadedLanguages.has(candidate) ? candidate : null; ++} ++ + async function loadSingleLanguage( + highlighter: HighlighterCore, + language: string, +@@ -360,6 +427,11 @@ async function resolveLanguageFromPath( + path: string, + languageHint: string | null = null, + ): Promise { ++ const loadedLanguage = resolveLoadedLanguageFromPath(path, languageHint); ++ if (loadedLanguage) { ++ return loadedLanguage; ++ } ++ + const detectedLanguage = languageHint ?? getFiletypeFromFileName(path); + if (!detectedLanguage) { + return "text"; +@@ -374,8 +446,12 @@ async function resolveLanguageFromPath( + return "text"; + } + ++ if (loadedLanguages.has(candidate)) { ++ return candidate; ++ } ++ + const highlighter = await getHighlighter(); +- const loaded = await loadSingleLanguage(highlighter, resolveLanguageAlias(candidate)); ++ const loaded = await loadSingleLanguage(highlighter, candidate); + if (!loaded) { + return "text"; + } +@@ -384,7 +460,10 @@ async function resolveLanguageFromPath( + } + + async function resolveLanguage(file: ReviewRenderableFile): Promise { +- return resolveLanguageFromPath(file.path, file.languageHint); ++ return ( ++ resolveLoadedLanguageFromPath(file.path, file.languageHint) ?? ++ (await resolveLanguageFromPath(file.path, file.languageHint)) ++ ); + } + + function normalizeHighlightedLines( +@@ -399,6 +478,18 @@ function normalizeHighlightedLines( + ); + } + ++function makePlainHighlightedLines( ++ lines: ReadonlyArray, ++): ReadonlyArray> { ++ return lines.map((line) => [ ++ { ++ content: stripTrailingNewline(line), ++ color: null, ++ fontStyle: null, ++ }, ++ ]); ++} ++ + function applyWordAltDiffHighlightsToFile( + file: ReviewRenderableFile, + highlighted: ReviewHighlightedFile, +@@ -594,6 +685,67 @@ async function highlightLines( + return highlightedLines; + } + ++async function highlightPatchLinesInChunks(input: { ++ readonly lines: ReadonlyArray; ++ readonly language: string; ++ readonly theme: string; ++ readonly onChunk: ( ++ startIndex: number, ++ tokens: ReadonlyArray>, ++ ) => void; ++}): Promise>> { ++ if (input.lines.length === 0) { ++ return []; ++ } ++ ++ const highlighter = await getHighlighter(); ++ const highlightedLines: Array> = []; ++ ++ for ( ++ let startIndex = 0; ++ startIndex < input.lines.length; ++ startIndex += REVIEW_HIGHLIGHT_CHUNK_SIZE ++ ) { ++ const lineChunk = input.lines.slice(startIndex, startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE); ++ const chunkTokens: Array> = []; ++ const tokenizableLines: string[] = []; ++ const tokenizableIndexes: number[] = []; ++ ++ lineChunk.forEach((line, index) => { ++ const strippedLine = stripTrailingNewline(line); ++ if (strippedLine.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH) { ++ chunkTokens[index] = [{ content: strippedLine, color: null, fontStyle: null }]; ++ return; ++ } ++ ++ tokenizableIndexes.push(index); ++ tokenizableLines.push(strippedLine); ++ }); ++ ++ if (tokenizableLines.length > 0) { ++ const tokenLines = highlighter.codeToTokensBase(tokenizableLines.join("\n"), { ++ lang: input.language, ++ theme: input.theme, ++ }); ++ const normalizedTokenLines = normalizeHighlightedLines(tokenLines); ++ ++ tokenizableIndexes.forEach((chunkIndex, tokenIndex) => { ++ chunkTokens[chunkIndex] = normalizedTokenLines[tokenIndex] ?? []; ++ }); ++ } ++ ++ const completedChunk = lineChunk.map((_, index) => chunkTokens[index] ?? []); ++ highlightedLines.push(...completedChunk); ++ input.onChunk(startIndex, completedChunk); ++ ++ if (startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE < input.lines.length) { ++ await waitForNextFrame(); ++ } ++ } ++ ++ return highlightedLines; ++} ++ + function getHighlightCacheKey(file: ReviewRenderableFile, theme: ReviewDiffTheme): string { + return `${SHIKI_THEME_NAME_BY_SCHEME[theme]}:${file.cacheKey}`; + } +@@ -667,7 +819,28 @@ export async function highlightReviewFile( + deletionLineCount: file.deletionLines.length, + rowCount: file.rows.length, + }); +- const language = await resolveLanguage(file); ++ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint); ++ const language = loadedLanguage ?? (await resolveLanguage(file)); ++ if (language === "text") { ++ const highlighted = applyWordAltDiffHighlightsToFile(file, { ++ additionLines: makePlainHighlightedLines(file.additionLines), ++ deletionLines: makePlainHighlightedLines(file.deletionLines), ++ }); ++ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { ++ storeResolvedHighlightedFile(cacheKey, highlighted); ++ } ++ logReviewHighlighterDiagnostic("file highlight complete", { ++ fileId: file.id, ++ filePath: file.path, ++ theme, ++ language, ++ highlightedAdditionLineCount: highlighted.additionLines.length, ++ highlightedDeletionLineCount: highlighted.deletionLines.length, ++ durationMs: Date.now() - startedAt, ++ }); ++ return highlighted; ++ } ++ + const additionLines = await highlightLines( + joinPatchLines(file.additionLines), + language, +@@ -707,6 +880,113 @@ export async function highlightReviewFile( + }); + } + ++export async function streamHighlightReviewFile( ++ file: ReviewRenderableFile, ++ theme: ReviewDiffTheme, ++ onProgress: (progress: ReviewHighlightFileProgress) => void, ++): Promise { ++ const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[theme]; ++ const cacheKey = getHighlightCacheKey(file, theme); ++ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { ++ const resolved = resolvedHighlightCache.get(cacheKey); ++ if (resolved) { ++ onProgress({ ++ highlightedFile: resolved, ++ complete: true, ++ highlightedLineCount: resolved.additionLines.length + resolved.deletionLines.length, ++ }); ++ return resolved; ++ } ++ } ++ ++ const startedAt = Date.now(); ++ logReviewHighlighterDiagnostic("file stream highlight start", { ++ fileId: file.id, ++ filePath: file.path, ++ theme, ++ additionLineCount: file.additionLines.length, ++ deletionLineCount: file.deletionLines.length, ++ rowCount: file.rows.length, ++ }); ++ ++ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint); ++ const language = loadedLanguage ?? (await resolveLanguage(file)); ++ if (language === "text") { ++ const highlighted = applyWordAltDiffHighlightsToFile(file, { ++ additionLines: makePlainHighlightedLines(file.additionLines), ++ deletionLines: makePlainHighlightedLines(file.deletionLines), ++ }); ++ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { ++ storeResolvedHighlightedFile(cacheKey, highlighted); ++ } ++ onProgress({ ++ highlightedFile: highlighted, ++ complete: true, ++ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length, ++ }); ++ logReviewHighlighterDiagnostic("file stream highlight complete", { ++ fileId: file.id, ++ filePath: file.path, ++ theme, ++ language, ++ highlightedAdditionLineCount: highlighted.additionLines.length, ++ highlightedDeletionLineCount: highlighted.deletionLines.length, ++ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length, ++ durationMs: Date.now() - startedAt, ++ }); ++ return highlighted; ++ } ++ ++ const additionLines: Array> = []; ++ const deletionLines: Array> = []; ++ let highlightedLineCount = 0; ++ ++ await highlightPatchLinesInChunks({ ++ lines: file.additionLines, ++ language, ++ theme: shikiTheme, ++ onChunk: (startIndex, tokens) => { ++ tokens.forEach((lineTokens, index) => { ++ additionLines[startIndex + index] = lineTokens; ++ }); ++ highlightedLineCount += tokens.length; ++ }, ++ }); ++ await waitForNextFrame(); ++ await highlightPatchLinesInChunks({ ++ lines: file.deletionLines, ++ language, ++ theme: shikiTheme, ++ onChunk: (startIndex, tokens) => { ++ tokens.forEach((lineTokens, index) => { ++ deletionLines[startIndex + index] = lineTokens; ++ }); ++ highlightedLineCount += tokens.length; ++ }, ++ }); ++ ++ const highlighted = applyWordAltDiffHighlightsToFile(file, { additionLines, deletionLines }); ++ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { ++ storeResolvedHighlightedFile(cacheKey, highlighted); ++ } ++ onProgress({ ++ highlightedFile: highlighted, ++ complete: true, ++ highlightedLineCount, ++ }); ++ logReviewHighlighterDiagnostic("file stream highlight complete", { ++ fileId: file.id, ++ filePath: file.path, ++ theme, ++ language, ++ highlightedAdditionLineCount: highlighted.additionLines.length, ++ highlightedDeletionLineCount: highlighted.deletionLines.length, ++ highlightedLineCount, ++ durationMs: Date.now() - startedAt, ++ }); ++ return highlighted; ++} ++ + export async function highlightReviewSelectedLines(input: { + readonly filePath: string; + readonly lines: ReadonlyArray; +@@ -717,7 +997,9 @@ export async function highlightReviewSelectedLines(input: { + return {}; + } + +- const language = await resolveLanguageFromPath(input.filePath, input.languageHint ?? null); ++ const loadedLanguage = resolveLoadedLanguageFromPath(input.filePath, input.languageHint ?? null); ++ const language = ++ loadedLanguage ?? (await resolveLanguageFromPath(input.filePath, input.languageHint ?? null)); + const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[input.theme]; + const additionLikeLines = input.lines + .filter((line) => line.change !== "delete") +diff --git a/apps/mobile/docs/review-profiling.md b/apps/mobile/docs/review-profiling.md +new file mode 100644 +index 000000000..6977eaf6e +--- /dev/null ++++ b/apps/mobile/docs/review-profiling.md +@@ -0,0 +1,80 @@ ++# Review Screen Profiling ++ ++Use this when the mobile review screen is slow or crashes while opening large diffs. ++ ++## Preferred Capture: React Native DevTools Performance ++ ++This app is on Expo SDK 55 / React Native 0.83 with Hermes, so the best first trace is the React Native DevTools Performance recording. The review screen also emits `t3.review.*` user timing marks in development builds so the trace can show parse, list-building, row indexing, and syntax-highlighting work. ++ ++1. Start the development client: ++ ++ ```sh ++ cd apps/mobile ++ bun dev:client ++ ``` ++ ++2. Open the app in the iOS Simulator or on the device using the development client. ++ ++3. In the terminal running Expo, press `j` to open React Native DevTools. ++ ++4. In DevTools, open the `Performance` panel. ++ ++5. Start recording. ++ ++6. In the app, reproduce the slow path: ++ - Navigate to the thread. ++ - Open `Files Changed`. ++ - Select the largest review source. ++ - Expand a few large files or tap `Load diff`. ++ - Scroll until the app is clearly slow or until just before it crashes. ++ ++7. Stop recording. ++ ++8. Export or save the Performance recording as a JSON trace. ++ ++Send that exported trace file here. Also include the device/simulator model and whether it was iOS or Android. ++ ++## Android Fallback: Hermes Sampling Profile ++ ++Use this if the app crashes before DevTools can export a trace, or if we need deeper JavaScript stack samples. ++ ++1. Run Android dev client: ++ ++ ```sh ++ cd apps/mobile ++ bun android:dev ++ bun dev:client ++ ``` ++ ++2. Open the developer menu from the Expo terminal with `d`. ++ ++3. Select `Enable Sampling Profiler`. ++ ++4. Reproduce the review-screen slowdown. ++ ++5. Open the developer menu again with `d`. ++ ++6. Select `Disable Sampling Profiler`. ++ ++7. Pull and convert the Hermes profile: ++ ++ ```sh ++ cd apps/mobile ++ mkdir -p profiles/review ++ bunx react-native profile-hermes profiles/review ++ ``` ++ ++8. Send the generated Chrome trace/profile file from `apps/mobile/profiles/review`. ++ ++For the development app variant, the Android package is `com.t3tools.t3code.dev`. ++ ++## What To Capture ++ ++For the first trace, do not optimize the repro. We want the slowest realistic case: ++ ++- A diff with many files and large line counts. ++- At least one `Load diff` action for a suppressed large diff. ++- One vertical scroll pass after the content appears. ++- One horizontal scroll of a long file, if that is part of the slowdown. ++ ++If the app crashes, note the last visible action before the crash and attach device logs if available. +diff --git a/apps/mobile/src/app/debug/syntax-highlight.tsx b/apps/mobile/src/app/debug/syntax-highlight.tsx +new file mode 100644 +index 000000000..c2a36d126 +--- /dev/null ++++ b/apps/mobile/src/app/debug/syntax-highlight.tsx +@@ -0,0 +1,423 @@ ++import { createHighlighterCore, type HighlighterCore } from "@shikijs/core"; ++import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript"; ++import typescriptLanguage from "@shikijs/langs/typescript"; ++import githubDarkDefault from "@shikijs/themes/github-dark-default"; ++import githubLightDefault from "@shikijs/themes/github-light-default"; ++import Stack from "expo-router/stack"; ++import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"; ++import { ++ FlatList, ++ Pressable, ++ Text as NativeText, ++ type ListRenderItemInfo, ++ useColorScheme, ++ useWindowDimensions, ++ View, ++} from "react-native"; ++import { useSafeAreaInsets } from "react-native-safe-area-context"; ++ ++import { AppText as Text } from "../../components/AppText"; ++import { cn } from "../../lib/cn"; ++import { useThemeColor } from "../../lib/useThemeColor"; ++ ++type DebugHighlightEngine = "native" | "javascript"; ++ ++type DebugToken = { ++ readonly content: string; ++ readonly color: string | null; ++ readonly fontStyle: number | null; ++}; ++ ++type DebugLine = { ++ readonly id: string; ++ readonly chunkIndex: number; ++ readonly indexInChunk: number; ++ readonly lineNumber: number; ++ readonly content: string; ++}; ++ ++type DebugHighlighterHandle = { ++ readonly engine: DebugHighlightEngine; ++ readonly tokenize: ( ++ code: string, ++ options: { readonly lang: string; readonly theme: string }, ++ ) => ReadonlyArray>; ++}; ++ ++const DEBUG_LINE_COUNT = 10_000; ++const DEBUG_CHUNK_SIZE = 500; ++const DEBUG_LINE_HEIGHT = 24; ++const DEBUG_GUTTER_WIDTH = 58; ++const DEBUG_CONTENT_WIDTH = 3_200; ++const DEBUG_MONO_FONT_FAMILY = "BerkeleyMono-Regular"; ++const DEBUG_THEME_NAME_BY_SCHEME = { ++ dark: "github-dark-default", ++ light: "github-light-default", ++} as const; ++ ++let nativeHighlighterPromise: Promise | null = null; ++let javascriptHighlighterPromise: Promise | null = null; ++ ++function waitForNextFrame(): Promise { ++ return new Promise((resolve) => setTimeout(resolve, 0)); ++} ++ ++function normalizeTokens( ++ tokenLines: ReadonlyArray>, ++): ReadonlyArray> { ++ return tokenLines.map((line) => ++ line.map((token) => ({ ++ content: token.content, ++ color: token.color ?? null, ++ fontStyle: token.fontStyle ?? null, ++ })), ++ ); ++} ++ ++function makeDebugCodeLine(index: number): string { ++ const label = `generatedLine${String(index).padStart(5, "0")}`; ++ switch (index % 8) { ++ case 0: ++ return `export async function ${label}(input: { value: number; name: string }) {`; ++ case 1: ++ return ` const normalized = input.name.trim().toLowerCase();`; ++ case 2: ++ return ` const result = await Promise.resolve({ id: "${label}", score: input.value * ${index + 1} });`; ++ case 3: ++ return ` if (result.score > ${index * 17}) return normalized + ":" + result.id;`; ++ case 4: ++ return ` return [normalized, String(result.score), "${"x".repeat((index % 24) + 8)}"].join("/");`; ++ case 5: ++ return `}`; ++ case 6: ++ return `type ${label}Record = Readonly<{ id: string; createdAt: Date; tags: string[] }>;`; ++ default: ++ return `const ${label}: ${label}Record = { id: "${label}", createdAt: new Date(), tags: ["debug", "highlight"] };`; ++ } ++} ++ ++function makeDebugLines(): ReadonlyArray { ++ return Array.from({ length: DEBUG_LINE_COUNT }, (_, index) => ({ ++ id: `line:${index + 1}`, ++ chunkIndex: Math.floor(index / DEBUG_CHUNK_SIZE), ++ indexInChunk: index % DEBUG_CHUNK_SIZE, ++ lineNumber: index + 1, ++ content: makeDebugCodeLine(index + 1), ++ })); ++} ++ ++async function createNativeDebugHighlighter(): Promise { ++ const nativeEngineModule = await import("react-native-shiki-engine"); ++ if (!nativeEngineModule.isNativeEngineAvailable()) { ++ throw new Error("Native Shiki engine is not available in this build."); ++ } ++ ++ const highlighter = await createHighlighterCore({ ++ langs: [typescriptLanguage], ++ themes: [githubLightDefault, githubDarkDefault], ++ engine: nativeEngineModule.createNativeEngine(), ++ }); ++ ++ return { ++ engine: "native", ++ tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)), ++ }; ++} ++ ++async function createJavascriptDebugHighlighter(): Promise { ++ const highlighter: HighlighterCore = await createHighlighterCore({ ++ langs: [typescriptLanguage], ++ themes: [githubLightDefault, githubDarkDefault], ++ engine: createJavaScriptRegexEngine(), ++ }); ++ ++ return { ++ engine: "javascript", ++ tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)), ++ }; ++} ++ ++async function getDebugHighlighter(engine: DebugHighlightEngine): Promise { ++ if (engine === "native") { ++ nativeHighlighterPromise ??= createNativeDebugHighlighter(); ++ return nativeHighlighterPromise; ++ } ++ ++ javascriptHighlighterPromise ??= createJavascriptDebugHighlighter(); ++ return javascriptHighlighterPromise; ++} ++ ++const TokenText = memo(function TokenText(props: { ++ readonly content: string; ++ readonly tokens: ReadonlyArray | null; ++}) { ++ if (!props.tokens) { ++ return ( ++ ++ {props.content} ++ ++ ); ++ } ++ ++ let tokenOffset = 0; ++ ++ return ( ++ ++ {props.tokens.map((token) => { ++ const tokenKey = `${tokenOffset}:${token.content.length}:${token.color ?? ""}:${token.fontStyle ?? ""}`; ++ tokenOffset += token.content.length; ++ const fontWeight = ++ token.fontStyle !== null && (token.fontStyle & 2) === 2 ++ ? ("700" as const) ++ : ("500" as const); ++ const fontStyle = ++ token.fontStyle !== null && (token.fontStyle & 1) === 1 ++ ? ("italic" as const) ++ : ("normal" as const); ++ ++ return ( ++ ++ {token.content} ++ ++ ); ++ })} ++ ++ ); ++}); ++ ++const DebugCodeLineRow = memo(function DebugCodeLineRow(props: { ++ readonly item: DebugLine; ++ readonly tokens: ReadonlyArray | null; ++ readonly width: number; ++}) { ++ return ( ++ ++ ++ {props.item.lineNumber} ++ ++ ++ ++ ++ ++ ); ++}); ++ ++function EngineToggle(props: { ++ readonly engine: DebugHighlightEngine; ++ readonly onChangeEngine: (engine: DebugHighlightEngine) => void; ++}) { ++ return ( ++ ++ {(["native", "javascript"] as const).map((engine) => { ++ const selected = props.engine === engine; ++ return ( ++ props.onChangeEngine(engine)} ++ > ++ ++ {engine === "javascript" ? "JS" : "Native"} ++ ++ ++ ); ++ })} ++ ++ ); ++} ++ ++export default function SyntaxHighlightDebugRoute() { ++ const insets = useSafeAreaInsets(); ++ const { width } = useWindowDimensions(); ++ const colorScheme = useColorScheme(); ++ const headerIcon = String(useThemeColor("--color-icon")); ++ const themeName = DEBUG_THEME_NAME_BY_SCHEME[colorScheme === "dark" ? "dark" : "light"]; ++ const [engine, setEngine] = useState("native"); ++ const [tokensByChunkIndex, setTokensByChunkIndex] = useState< ++ Record>> ++ >({}); ++ const [status, setStatus] = useState("Idle"); ++ const renderStartRef = useRef(null); ++ const generationRef = useRef(0); ++ const lines = useMemo(() => makeDebugLines(), []); ++ ++ useEffect(() => { ++ const generation = generationRef.current + 1; ++ generationRef.current = generation; ++ renderStartRef.current = performance.now(); ++ setTokensByChunkIndex({}); ++ setStatus("Initializing highlighter"); ++ ++ void (async () => { ++ try { ++ const highlighterStartedAt = performance.now(); ++ const highlighter = await getDebugHighlighter(engine); ++ if (generation !== generationRef.current) { ++ return; ++ } ++ ++ console.log("[debug-syntax-scratch] initialize", { ++ durationMs: Math.round(performance.now() - highlighterStartedAt), ++ engine: highlighter.engine, ++ }); ++ ++ let firstChunkMs: number | null = null; ++ const totalStartedAt = performance.now(); ++ setStatus(`Streaming ${DEBUG_LINE_COUNT.toLocaleString()} lines`); ++ ++ for (let startIndex = 0; startIndex < lines.length; startIndex += DEBUG_CHUNK_SIZE) { ++ if (generation !== generationRef.current) { ++ return; ++ } ++ ++ const chunkLines = lines.slice(startIndex, startIndex + DEBUG_CHUNK_SIZE); ++ const chunkCode = chunkLines.map((line) => line.content).join("\n"); ++ const chunkStartedAt = performance.now(); ++ const chunkTokens = highlighter.tokenize(chunkCode, { ++ lang: "typescript", ++ theme: themeName, ++ }); ++ const chunkMs = performance.now() - chunkStartedAt; ++ ++ if (firstChunkMs === null) { ++ firstChunkMs = performance.now() - totalStartedAt; ++ console.log("[debug-syntax-scratch] first chunk", { ++ chunkSize: DEBUG_CHUNK_SIZE, ++ durationMs: Math.round(firstChunkMs), ++ engine, ++ lineCount: chunkTokens.length, ++ }); ++ } ++ ++ setTokensByChunkIndex((current) => ({ ++ ...current, ++ [startIndex / DEBUG_CHUNK_SIZE]: chunkTokens, ++ })); ++ setStatus( ++ `Streamed ${Math.min(startIndex + DEBUG_CHUNK_SIZE, lines.length).toLocaleString()} / ${lines.length.toLocaleString()} lines`, ++ ); ++ ++ console.log("[debug-syntax-scratch] chunk", { ++ chunkIndex: startIndex / DEBUG_CHUNK_SIZE, ++ chunkMs: Math.round(chunkMs), ++ engine, ++ lineCount: chunkTokens.length, ++ }); ++ ++ await waitForNextFrame(); ++ } ++ ++ console.log("[debug-syntax-scratch] complete", { ++ durationMs: Math.round(performance.now() - totalStartedAt), ++ engine, ++ lineCount: lines.length, ++ }); ++ setStatus(`Complete with ${engine}`); ++ } catch (error) { ++ console.error("[debug-syntax-scratch] failed", { ++ engine, ++ message: error instanceof Error ? error.message : String(error), ++ }); ++ setStatus(error instanceof Error ? error.message : "Highlight failed"); ++ } ++ })(); ++ }, [engine, lines, themeName]); ++ ++ useEffect(() => { ++ if (renderStartRef.current === null) { ++ return; ++ } ++ ++ const startedAt = renderStartRef.current; ++ renderStartRef.current = null; ++ const commitMs = performance.now() - startedAt; ++ requestAnimationFrame(() => { ++ console.log("[debug-syntax-scratch] render", { ++ commitMs: Math.round(commitMs), ++ paintMs: Math.round(performance.now() - startedAt), ++ }); ++ }); ++ }); ++ ++ const renderItem = useCallback( ++ ({ item }: ListRenderItemInfo) => ( ++ ++ ), ++ [tokensByChunkIndex, width], ++ ); ++ ++ return ( ++ ++ ++ ++ ++ ++ ++ ++ Shiki streaming baseline ++ ++ ++ {status} ++ ++ ++ ++ ++ ++ ++ item.id} ++ getItemLayout={(_, index) => ({ ++ length: DEBUG_LINE_HEIGHT, ++ offset: DEBUG_LINE_HEIGHT * index, ++ index, ++ })} ++ initialNumToRender={40} ++ maxToRenderPerBatch={80} ++ updateCellsBatchingPeriod={16} ++ windowSize={9} ++ removeClippedSubviews ++ keyboardShouldPersistTaps="handled" ++ contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }} ++ /> ++ ++ ); ++} +diff --git a/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx +new file mode 100644 +index 000000000..095201929 +--- /dev/null ++++ b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx +@@ -0,0 +1,110 @@ ++import { createContext, type ReactNode, useContext, useEffect, useMemo, useState } from "react"; ++ ++import { ++ getActiveReviewHighlighterEngine, ++ prepareReviewHighlighter, ++ prepareReviewHighlighterLanguages, ++ type ReviewHighlighterEngine, ++} from "./shikiReviewHighlighter"; ++ ++type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error"; ++ ++interface ReviewHighlighterContextValue { ++ readonly engine: ReviewHighlighterEngine | null; ++ readonly error: string | null; ++ readonly status: ReviewHighlighterStatus; ++} ++ ++const ReviewHighlighterContext = createContext({ ++ engine: null, ++ error: null, ++ status: "idle", ++}); ++ ++const REVIEW_INITIAL_LANGUAGES = [ ++ "typescript", ++ "tsx", ++ "javascript", ++ "jsx", ++ "json", ++ "yaml", ++ "bash", ++] as const; ++ ++function isReviewHighlighterProviderDebugLoggingEnabled(): boolean { ++ return typeof __DEV__ !== "undefined" ? __DEV__ : false; ++} ++ ++function logReviewHighlighterProviderDiagnostic( ++ message: string, ++ details?: Record, ++): void { ++ if (!isReviewHighlighterProviderDebugLoggingEnabled()) { ++ return; ++ } ++ ++ if (details) { ++ console.log(`[review-highlighter-provider] ${message}`, details); ++ return; ++ } ++ ++ console.log(`[review-highlighter-provider] ${message}`); ++} ++ ++export function ReviewHighlighterProvider(props: { readonly children: ReactNode }) { ++ const [value, setValue] = useState({ ++ engine: null, ++ error: null, ++ status: "idle", ++ }); ++ ++ useEffect(() => { ++ let cancelled = false; ++ ++ setValue({ engine: null, error: null, status: "initializing" }); ++ ++ void (async () => { ++ const startedAt = performance.now(); ++ try { ++ await prepareReviewHighlighter(); ++ await prepareReviewHighlighterLanguages(REVIEW_INITIAL_LANGUAGES); ++ const engine = await getActiveReviewHighlighterEngine(); ++ ++ if (cancelled) { ++ return; ++ } ++ ++ const durationMs = Math.round(performance.now() - startedAt); ++ logReviewHighlighterProviderDiagnostic("initialized", { ++ durationMs, ++ engine, ++ }); ++ setValue({ engine, error: null, status: "ready" }); ++ } catch (error) { ++ if (cancelled) { ++ return; ++ } ++ ++ const message = error instanceof Error ? error.message : String(error); ++ logReviewHighlighterProviderDiagnostic("initialization failed", { error: message }); ++ setValue({ engine: null, error: message, status: "error" }); ++ } ++ })(); ++ ++ return () => { ++ cancelled = true; ++ }; ++ }, []); ++ ++ const contextValue = useMemo(() => value, [value]); ++ ++ return ( ++ ++ {props.children} ++ ++ ); ++} ++ ++export function useReviewHighlighterStatus(): ReviewHighlighterContextValue { ++ return useContext(ReviewHighlighterContext); ++} +diff --git a/apps/mobile/src/features/review/reviewPerf.ts b/apps/mobile/src/features/review/reviewPerf.ts +new file mode 100644 +index 000000000..2ae1095b1 +--- /dev/null ++++ b/apps/mobile/src/features/review/reviewPerf.ts +@@ -0,0 +1,83 @@ ++interface ReviewPerformanceLike { ++ readonly now?: () => number; ++ readonly mark?: (name: string) => void; ++ readonly measure?: (name: string, startMark: string, endMark: string) => void; ++ readonly clearMarks?: (name?: string) => void; ++ readonly clearMeasures?: (name?: string) => void; ++} ++ ++const REVIEW_PERF_PREFIX = "t3.review"; ++let reviewPerfSequence = 0; ++ ++function getPerformance(): ReviewPerformanceLike | null { ++ const candidate = (globalThis as { readonly performance?: ReviewPerformanceLike }).performance; ++ return candidate ?? null; ++} ++ ++export function isReviewPerfEnabled(): boolean { ++ return typeof __DEV__ !== "undefined" ? __DEV__ : false; ++} ++ ++export function measureReviewWork(name: string, callback: () => T): T { ++ if (!isReviewPerfEnabled()) { ++ return callback(); ++ } ++ ++ const perf = getPerformance(); ++ const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`; ++ const startMark = `${marker}.start`; ++ const endMark = `${marker}.end`; ++ const startedAt = perf?.now?.() ?? Date.now(); ++ ++ perf?.mark?.(startMark); ++ try { ++ return callback(); ++ } finally { ++ const durationMs = (perf?.now?.() ?? Date.now()) - startedAt; ++ perf?.mark?.(endMark); ++ perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark); ++ perf?.clearMarks?.(startMark); ++ perf?.clearMarks?.(endMark); ++ console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) }); ++ } ++} ++ ++export async function measureReviewAsyncWork( ++ name: string, ++ callback: () => Promise, ++): Promise { ++ if (!isReviewPerfEnabled()) { ++ return callback(); ++ } ++ ++ const perf = getPerformance(); ++ const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`; ++ const startMark = `${marker}.start`; ++ const endMark = `${marker}.end`; ++ const startedAt = perf?.now?.() ?? Date.now(); ++ ++ perf?.mark?.(startMark); ++ try { ++ return await callback(); ++ } finally { ++ const durationMs = (perf?.now?.() ?? Date.now()) - startedAt; ++ perf?.mark?.(endMark); ++ perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark); ++ perf?.clearMarks?.(startMark); ++ perf?.clearMarks?.(endMark); ++ console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) }); ++ } ++} ++ ++export function markReviewEvent(name: string, details?: Record): void { ++ if (!isReviewPerfEnabled()) { ++ return; ++ } ++ ++ getPerformance()?.mark?.(`${REVIEW_PERF_PREFIX}.${name}`); ++ if (details) { ++ console.log(`[review-perf] ${name}`, details); ++ return; ++ } ++ console.log(`[review-perf] ${name}`); ++} diff --git a/apps/mobile/src/features/debug/fixtures/review-large.diff b/apps/mobile/src/features/debug/fixtures/review-large.diff new file mode 100644 index 0000000000..ca2da03aff --- /dev/null +++ b/apps/mobile/src/features/debug/fixtures/review-large.diff @@ -0,0 +1,3208 @@ +diff --git a/apps/mobile/package.json b/apps/mobile/package.json +index 08329e1d4..36ac93a0f 100644 +--- a/apps/mobile/package.json ++++ b/apps/mobile/package.json +@@ -30,6 +30,7 @@ + "config:dev": "APP_VARIANT=development expo config", + "config:preview": "APP_VARIANT=preview expo config", + "config:prod": "APP_VARIANT=production expo config", ++ "profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review", + "test": "vitest run", + "typecheck": "tsc --noEmit" + }, +diff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx +index f153db701..f6095c051 100644 +--- a/apps/mobile/src/app/index.tsx ++++ b/apps/mobile/src/app/index.tsx +@@ -43,28 +43,50 @@ export default function HomeRouteScreen() { + headerTintColor: iconColor, + headerTitle: "", + headerRight: () => ( +- router.push("/connections")} +- hitSlop={8} +- style={{ +- flexDirection: "row", +- alignItems: "center", +- gap: 8, +- paddingHorizontal: 4, +- paddingVertical: 4, +- }} +- > +- +- ++ router.push("/debug/syntax-highlight")} ++ hitSlop={8} + style={{ +- fontFamily: "DMSans_700Bold", +- fontSize: 12, +- color: secondaryFg, ++ borderRadius: 999, ++ backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)", ++ paddingHorizontal: 10, ++ paddingVertical: 5, + }} + > +- {CONNECTION_LABEL[connectionState]} +- +- ++ ++ Debug ++ ++ ++ router.push("/connections")} ++ hitSlop={8} ++ style={{ ++ flexDirection: "row", ++ alignItems: "center", ++ gap: 8, ++ paddingHorizontal: 4, ++ paddingVertical: 4, ++ }} ++ > ++ ++ ++ {CONNECTION_LABEL[connectionState]} ++ ++ ++ + ), + headerSearchBarOptions: { + placeholder: "Search threads", +diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx +index 84c48c6ed..ee993ee7c 100644 +--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx ++++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx +@@ -1,5 +1,10 @@ ++import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider"; + import { ReviewSheet } from "../../../../features/review/ReviewSheet"; + + export default function ReviewRoute() { +- return ; ++ return ( ++ ++ ++ ++ ); + } +diff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx +index 076a2286d..9a173224a 100644 +--- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx ++++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx +@@ -2,15 +2,8 @@ import { useLocalSearchParams, useRouter } from "expo-router"; + import { SymbolView } from "expo-symbols"; + import { TextInputWrapper } from "expo-paste-input"; + import { useEffect, useMemo, useState } from "react"; +-import { +- KeyboardAvoidingView, +- Platform, +- Pressable, +- ScrollView, +- View, +- useColorScheme, +- useWindowDimensions, +-} from "react-native"; ++import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native"; ++import { KeyboardStickyView } from "react-native-keyboard-controller"; + import { useSafeAreaInsets } from "react-native-safe-area-context"; + import ImageViewing from "react-native-image-viewing"; + +@@ -34,6 +27,7 @@ import { + import { + changeTone, + DiffTokenText, ++ REVIEW_DIFF_LINE_HEIGHT, + REVIEW_MONO_FONT_FAMILY, + ReviewChangeBar, + } from "./reviewDiffRendering"; +@@ -44,7 +38,6 @@ import { + } from "./shikiReviewHighlighter"; + + const REVIEW_COMMENT_PREVIEW_MAX_LINES = 5; +-const REVIEW_COMMENT_LINE_HEIGHT = 26; + + export function ReviewCommentComposerSheet() { + const router = useRouter(); +@@ -84,8 +77,8 @@ export function ReviewCommentComposerSheet() { + ? `Lines ${firstNumber}-${lastNumber}` + : `${selectedLines.length} lines selected`; + const previewHeight = Math.max( +- Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_COMMENT_LINE_HEIGHT, +- REVIEW_COMMENT_LINE_HEIGHT, ++ Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_DIFF_LINE_HEIGHT, ++ REVIEW_DIFF_LINE_HEIGHT, + ); + const previewViewportWidth = Math.max(width - 40, 280); + const handleNativePaste = useNativePaste((uris) => { +@@ -143,17 +136,13 @@ export function ReviewCommentComposerSheet() { + } + + return ( +- ++ + + +@@ -219,7 +208,7 @@ export function ReviewCommentComposerSheet() { + + + + +- +- +- void handlePickImages()} /> +- +- { +- if (!target || !environmentId || !threadId || commentText.trim().length === 0) { +- return; +- } +- +- appendReviewCommentToDraft({ +- environmentId, +- threadId, +- text: formatReviewCommentContext(target, commentText), +- attachments, +- }); +- setAttachments([]); +- clearReviewCommentTarget(); +- router.dismiss(); +- }} +- /> +- + + )} + ++ {target ? ( ++ ++ ++ void handlePickImages()} /> ++ ++ { ++ if (!target || !environmentId || !threadId || commentText.trim().length === 0) { ++ return; ++ } ++ ++ appendReviewCommentToDraft({ ++ environmentId, ++ threadId, ++ text: formatReviewCommentContext(target, commentText), ++ attachments, ++ }); ++ setAttachments([]); ++ clearReviewCommentTarget(); ++ router.dismiss(); ++ }} ++ /> ++ ++ ++ ) : null} + +- ++ + ); + } +diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx +index 82c28e81e..e148a8da2 100644 +--- a/apps/mobile/src/features/review/ReviewSheet.tsx ++++ b/apps/mobile/src/features/review/ReviewSheet.tsx +@@ -1,17 +1,31 @@ + import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts"; ++import { Gesture, GestureDetector } from "react-native-gesture-handler"; ++import Animated, { ++ makeMutable, ++ type SharedValue, ++ useAnimatedStyle, ++ useSharedValue, ++} from "react-native-reanimated"; + import { useLocalSearchParams, useRouter } from "expo-router"; + import Stack from "expo-router/stack"; + import { SymbolView } from "expo-symbols"; +-import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react"; ++import { ++ memo, ++ type ReactElement, ++ useCallback, ++ useDeferredValue, ++ useEffect, ++ useMemo, ++ useRef, ++ useState, ++} from "react"; + import { + ActivityIndicator, + FlatList, +- InteractionManager, + type ListRenderItemInfo, + Pressable, + ScrollView, + Text as NativeText, +- type ViewToken, + useColorScheme, + useWindowDimensions, + View, +@@ -32,6 +46,7 @@ import { + setReviewTurnDiff, + updateReviewExpandedFileIds, + updateReviewRevealedLargeFileIds, ++ updateReviewViewedFileIds, + useReviewCacheForThread, + } from "./reviewState"; + import { +@@ -45,11 +60,12 @@ import { + type ReviewParsedDiff, + type ReviewRenderableFile, + type ReviewRenderableLineRow, ++ type ReviewRenderableRow, + } from "./reviewModel"; + import { + clearReviewHighlightFileCache, + getCachedHighlightedReviewFile, +- highlightReviewFile, ++ streamHighlightReviewFile, + type ReviewDiffTheme, + type ReviewHighlightedFile, + type ReviewHighlightedToken, +@@ -67,9 +83,12 @@ import { + import { + changeTone, + DiffTokenText, ++ REVIEW_DIFF_LINE_HEIGHT, + REVIEW_MONO_FONT_FAMILY, + ReviewChangeBar, + } from "./reviewDiffRendering"; ++import { markReviewEvent, measureReviewWork } from "./reviewPerf"; ++import { useReviewHighlighterStatus } from "./ReviewHighlighterProvider"; + + interface PendingCommentSelection { + readonly sectionTitle: string; +@@ -87,14 +106,21 @@ interface ReviewLineActionInput { + + const IOS_NAV_BAR_HEIGHT = 44; + const REVIEW_HEADER_SPACING = 0; +-const REVIEW_LINE_GUTTER_WIDTH = 62; ++const REVIEW_CHANGE_BAR_WIDTH = 5; ++const REVIEW_MIN_LINE_NUMBER_WIDTH = 27; ++const REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE = 8; ++const REVIEW_LINE_NUMBER_HORIZONTAL_PADDING = 6; + const REVIEW_CHARACTER_WIDTH_ESTIMATE = 8.4; + const REVIEW_MAX_CONTENT_WIDTH = 4_800; +-const REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT = 2; +-const REVIEW_HIGHLIGHT_BACKTRACK_COUNT = 0; +-const REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT = 1; ++const REVIEW_HUNK_ROW_HEIGHT = 35; ++const REVIEW_FILE_HEADER_HEIGHT = 43; ++const REVIEW_SUPPRESSED_ROW_HEIGHT = 92; + const loggedMissingReviewTokenKeys = new Set(); + ++function waitForReviewDelay(durationMs: number): Promise { ++ return new Promise((resolve) => setTimeout(resolve, durationMs)); ++} ++ + function isReviewDiffDebugLoggingEnabled(): boolean { + return typeof __DEV__ !== "undefined" ? __DEV__ : false; + } +@@ -113,33 +139,27 @@ function logReviewDiffDiagnostic(message: string, details?: Record, ++function computeReviewFileContentWidth( ++ rows: ReadonlyArray, + viewportWidth: number, ++ gutterWidth: number, + ): number { + let maxTextLength = 0; + +- items.forEach((item) => { +- switch (item.kind) { +- case "file-header": +- maxTextLength = Math.max( +- maxTextLength, +- item.file.path.length, +- item.file.previousPath?.length ?? 0, +- ); +- break; +- case "file-suppressed": +- maxTextLength = Math.max(maxTextLength, item.message.length, item.actionLabel?.length ?? 0); +- break; +- case "hunk": +- maxTextLength = Math.max( +- maxTextLength, +- item.row.header.length + (item.row.context ? item.row.context.length + 1 : 0), +- ); +- break; +- case "line": +- maxTextLength = Math.max(maxTextLength, item.row.content.length); +- break; ++ rows.forEach((row) => { ++ if (row.kind === "hunk") { ++ maxTextLength = Math.max( ++ maxTextLength, ++ row.header.length + (row.context ? row.context.length + 1 : 0), ++ ); ++ return; + } ++ ++ maxTextLength = Math.max(maxTextLength, row.content.length); + }); + + return Math.max( +- viewportWidth, ++ Math.max(0, viewportWidth - gutterWidth), + Math.min( + REVIEW_MAX_CONTENT_WIDTH, +- Math.ceil(REVIEW_LINE_GUTTER_WIDTH + 48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE), ++ Math.ceil(48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE), + ), + ); + } + ++function computeReviewFileGutterWidth(rows: ReadonlyArray): number { ++ let maxLineNumber = 0; ++ ++ rows.forEach((row) => { ++ if (row.kind !== "line") { ++ return; ++ } ++ ++ maxLineNumber = Math.max(maxLineNumber, row.oldLineNumber ?? 0, row.newLineNumber ?? 0); ++ }); ++ ++ const digitCount = Math.max(1, String(maxLineNumber).length); ++ const lineNumberWidth = Math.max( ++ REVIEW_MIN_LINE_NUMBER_WIDTH, ++ digitCount * REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE + REVIEW_LINE_NUMBER_HORIZONTAL_PADDING, ++ ); ++ ++ return REVIEW_CHANGE_BAR_WIDTH + lineNumberWidth; ++} ++ + function getDefaultExpandedFileIds( + files: ReadonlyArray, + ): ReadonlyArray { + return files.map((file) => file.id); + } + ++function getValidReviewExpandedFileIds( ++ files: ReadonlyArray, ++ cachedExpandedFileIds: ReadonlyArray | undefined, ++): ReadonlyArray { ++ if (cachedExpandedFileIds === undefined) { ++ return getDefaultExpandedFileIds(files); ++ } ++ ++ const fileIdSet = new Set(files.map((file) => file.id)); ++ return cachedExpandedFileIds.filter((id) => fileIdSet.has(id)); ++} ++ + function getHighlightedTokensForLine( + line: ReviewRenderableLineRow, + highlightedFile: ReviewHighlightedFile | null, +@@ -252,16 +293,13 @@ const ReviewLineRow = memo(function ReviewLineRow(props: { + delayLongPress={220} + onLongPress={props.onStartRangeSelection} + onPress={props.onComment} +- style={{ minWidth: props.viewportWidth }} ++ style={{ ++ height: REVIEW_DIFF_LINE_HEIGHT, ++ width: props.viewportWidth, ++ overflow: "hidden", ++ }} + > +- +- +- {lineNumber ?? ""} +- +- ++ + ++ ++ ++ {props.lineNumber ?? ""} ++ ++ ++ ); ++}); ++ ++const ReviewHunkGutter = memo(function ReviewHunkGutter(props: { readonly gutterWidth: number }) { ++ return ( ++ ++ ); ++}); ++ + const ReviewFileCard = memo(function ReviewFileCard(props: { + readonly file: ReviewRenderableFile; + readonly fileId: string; + readonly expanded: boolean; ++ readonly viewed: boolean; + readonly viewportWidth: number; + readonly onToggleFile: (fileId: string) => void; ++ readonly onToggleViewed: (fileId: string) => void; + }) { +- const chrome = getFileHeaderChrome(props.file.changeType); ++ const { expanded, file, fileId, onToggleFile, onToggleViewed, viewed, viewportWidth } = props; ++ const chrome = getFileHeaderChrome(file.changeType); ++ const iconColor = String(useThemeColor("--color-icon-muted")); ++ const handleToggleFile = useCallback(() => { ++ onToggleFile(fileId); ++ }, [fileId, onToggleFile]); ++ const handleToggleViewed = useCallback(() => { ++ onToggleViewed(fileId); ++ }, [fileId, onToggleViewed]); + + return ( + +- props.onToggleFile(props.fileId)}> +- +- +- +- +- +- +- +- +- +- {props.file.path} ++ ++ ++ ++ ++ ++ ++ ++ ++ {file.path} ++ ++ {file.previousPath && file.previousPath !== file.path ? ( ++ ++ {file.previousPath} + +- {props.file.previousPath && props.file.previousPath !== props.file.path ? ( +- +- {props.file.previousPath} +- ++ ) : null} ++ ++ ++ ++ ++ -{file.deletions} ++ ++ ++ +{file.additions} ++ ++ ++ ++ {viewed ? ( ++ + ) : null} + +- +- +- +- +{props.file.additions} +- +- +- -{props.file.deletions} ++ ++ Viewed + +- ++ + +- ++ + + ); + }); +@@ -342,7 +453,11 @@ const ReviewFileSuppressedBody = memo(function ReviewFileSuppressedBody(props: { + return ( + + {props.message} + {props.actionLabel && props.onLoadDiffFile ? ( +@@ -364,10 +479,13 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: { + }) { + return ( + +- ++ + {props.header} + {props.context ? ` ${props.context}` : ""} + +@@ -375,6 +493,61 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: { + ); + }); + ++const ReviewCodePanRow = memo(function ReviewCodePanRow(props: { ++ readonly contentWidth: number; ++ readonly horizontalOffset: SharedValue; ++ readonly gutterWidth?: number; ++ readonly viewportWidth: number; ++ readonly leftGutter?: ReactElement; ++ readonly children: ReactElement; ++}) { ++ const { ++ children, ++ contentWidth, ++ gutterWidth = 0, ++ horizontalOffset, ++ leftGutter, ++ viewportWidth, ++ } = props; ++ const dragStartOffset = useSharedValue(0); ++ const visibleContentWidth = leftGutter ? viewportWidth - gutterWidth : viewportWidth; ++ const maxOffset = Math.max(0, contentWidth - visibleContentWidth); ++ ++ const panGesture = useMemo( ++ () => ++ Gesture.Pan() ++ .activeOffsetX([-8, 8]) ++ .failOffsetY([-10, 10]) ++ .onBegin(() => { ++ dragStartOffset.value = horizontalOffset.value; ++ }) ++ .onUpdate((event) => { ++ "worklet"; ++ const nextOffset = dragStartOffset.value - event.translationX; ++ horizontalOffset.value = Math.min(maxOffset, Math.max(0, nextOffset)); ++ }), ++ [dragStartOffset, horizontalOffset, maxOffset], ++ ); ++ ++ const contentStyle = useAnimatedStyle( ++ () => ({ ++ transform: [{ translateX: -horizontalOffset.value }], ++ }), ++ [horizontalOffset], ++ ); ++ ++ return ( ++ ++ ++ {leftGutter ?? null} ++ ++ {children} ++ ++ ++ ++ ); ++}); ++ + const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) { + return ( + +@@ -454,15 +627,19 @@ export function ReviewSheet() { + const [highlightedFilesById, setHighlightedFilesById] = useState< + Record + >({}); +- const [visibleFileIds, setVisibleFileIds] = useState>([]); ++ const deferredHighlightedFilesById = useDeferredValue(highlightedFilesById); ++ const [localExpandedFileIdsBySection, setLocalExpandedFileIdsBySection] = useState< ++ Record> ++ >({}); ++ const [localViewedFileIdsBySection, setLocalViewedFileIdsBySection] = useState< ++ Record> ++ >({}); + const activeCommentTarget = useReviewCommentTarget(); + const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme; +- const highlightQueueRef = useRef([]); +- const highlightRequestedFileIdsRef = useRef>(new Set()); +- const highlightQueueGenerationRef = useRef(0); +- const highlightQueueActiveRef = useRef(false); +- const highlightableFilesByIdRef = useRef>(new Map()); +- const selectedThemeRef = useRef(selectedTheme); ++ const reviewHighlighter = useReviewHighlighterStatus(); ++ const highlightRunIdRef = useRef(0); ++ const highlightableFilesRef = useRef>([]); ++ const horizontalOffsetByFileIdRef = useRef>>(new Map()); + const { selectedThreadCwd } = useSelectedThreadWorktree(); + + const cwd = selectedThreadCwd; +@@ -498,11 +675,13 @@ export function ReviewSheet() { + const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT; + const parsedDiff = useMemo( + () => +- getCachedReviewParsedDiff({ +- threadKey: reviewCache.threadKey, +- sectionId: selectedSection?.id ?? null, +- diff: selectedSection?.diff, +- }), ++ measureReviewWork("parse-diff", () => ++ getCachedReviewParsedDiff({ ++ threadKey: reviewCache.threadKey, ++ sectionId: selectedSection?.id ?? null, ++ diff: selectedSection?.diff, ++ }), ++ ), + [reviewCache.threadKey, selectedSection?.diff, selectedSection?.id], + ); + const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]); +@@ -510,14 +689,53 @@ export function ReviewSheet() { + () => countReviewCommentContexts(draftMessage), + [draftMessage], + ); ++ const viewportWidth = Math.max(width, 280); ++ ++ useEffect(() => { ++ if (!selectedSection?.id || parsedDiff.kind !== "files") { ++ return; ++ } ++ ++ setLocalExpandedFileIdsBySection((current) => { ++ if (current[selectedSection.id] !== undefined) { ++ return current; ++ } ++ ++ return { ++ ...current, ++ [selectedSection.id]: getValidReviewExpandedFileIds( ++ parsedDiff.files, ++ reviewCache.expandedFileIdsBySection[selectedSection.id], ++ ), ++ }; ++ }); ++ ++ setLocalViewedFileIdsBySection((current) => { ++ if (current[selectedSection.id] !== undefined) { ++ return current; ++ } ++ ++ return { ++ ...current, ++ [selectedSection.id]: reviewCache.viewedFileIdsBySection[selectedSection.id] ?? [], ++ }; ++ }); ++ }, [ ++ parsedDiff, ++ reviewCache.expandedFileIdsBySection, ++ reviewCache.viewedFileIdsBySection, ++ selectedSection?.id, ++ ]); + + const expandedFileIds = useMemo( + () => + selectedSection?.id && parsedDiff.kind === "files" +- ? (reviewCache.expandedFileIdsBySection[selectedSection.id] ?? +- getDefaultExpandedFileIds(parsedDiff.files)) ++ ? getValidReviewExpandedFileIds( ++ parsedDiff.files, ++ localExpandedFileIdsBySection[selectedSection.id], ++ ) + : [], +- [parsedDiff, reviewCache.expandedFileIdsBySection, selectedSection?.id], ++ [localExpandedFileIdsBySection, parsedDiff, selectedSection?.id], + ); + const revealedLargeFileIds = useMemo( + () => +@@ -526,47 +744,96 @@ export function ReviewSheet() { + : [], + [reviewCache.revealedLargeFileIdsBySection, selectedSection?.id], + ); ++ const viewedFileIds = useMemo( ++ () => (selectedSection?.id ? (localViewedFileIdsBySection[selectedSection.id] ?? []) : []), ++ [localViewedFileIdsBySection, selectedSection?.id], ++ ); ++ const viewedFileIdSet = useMemo(() => new Set(viewedFileIds), [viewedFileIds]); + const reviewListItems = useMemo( + () => + selectedSection && parsedDiff.kind === "files" +- ? buildReviewListItems({ +- files: parsedDiff.files, +- expandedFileIds, +- revealedLargeFileIds, +- }) ++ ? measureReviewWork("build-list-items", () => ++ buildReviewListItems({ ++ files: parsedDiff.files, ++ expandedFileIds, ++ revealedLargeFileIds, ++ }), ++ ) + : [], + [expandedFileIds, parsedDiff, revealedLargeFileIds, selectedSection], + ); +- const reviewFileById = useMemo(() => { ++ const reviewLineRowsByFileId = useMemo(() => { + if (parsedDiff.kind !== "files") { +- return new Map(); ++ return new Map>(); + } + +- return new Map(parsedDiff.files.map((file) => [file.id, file] as const)); ++ return measureReviewWork( ++ "index-line-rows", ++ () => ++ new Map( ++ parsedDiff.files.map((file) => [ ++ file.id, ++ file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"), ++ ]), ++ ), ++ ); + }, [parsedDiff]); +- const reviewLineRowsByFileId = useMemo(() => { ++ const reviewContentWidthByFileId = useMemo(() => { + if (parsedDiff.kind !== "files") { +- return new Map>(); ++ return new Map(); ++ } ++ ++ return measureReviewWork( ++ "measure-file-widths", ++ () => ++ new Map( ++ parsedDiff.files.map((file) => [ ++ file.id, ++ computeReviewFileContentWidth( ++ file.rows, ++ viewportWidth, ++ computeReviewFileGutterWidth(file.rows), ++ ), ++ ]), ++ ), ++ ); ++ }, [parsedDiff, viewportWidth]); ++ const reviewGutterWidthByFileId = useMemo(() => { ++ if (parsedDiff.kind !== "files") { ++ return new Map(); + } + + return new Map( +- parsedDiff.files.map((file) => [ +- file.id, +- file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"), +- ]), ++ parsedDiff.files.map((file) => [file.id, computeReviewFileGutterWidth(file.rows)]), + ); + }, [parsedDiff]); +- const reviewLineIndexByRowId = useMemo(() => { +- const map = new Map(); ++ const getReviewFileHorizontalOffset = useCallback((fileId: string) => { ++ let offset = horizontalOffsetByFileIdRef.current.get(fileId); ++ if (!offset) { ++ offset = makeMutable(0); ++ horizontalOffsetByFileIdRef.current.set(fileId, offset); ++ } + +- reviewLineRowsByFileId.forEach((rows) => { +- rows.forEach((row, index) => { +- map.set(row.id, index); +- }); +- }); ++ return offset; ++ }, []); ++ useEffect(() => { ++ const knownFileIds = ++ parsedDiff.kind === "files" ? new Set(parsedDiff.files.map((file) => file.id)) : new Set(); + +- return map; +- }, [reviewLineRowsByFileId]); ++ horizontalOffsetByFileIdRef.current.forEach((offset, fileId) => { ++ if (!knownFileIds.has(fileId)) { ++ horizontalOffsetByFileIdRef.current.delete(fileId); ++ return; ++ } ++ ++ const contentWidth = reviewContentWidthByFileId.get(fileId) ?? viewportWidth; ++ const gutterWidth = reviewGutterWidthByFileId.get(fileId) ?? 0; ++ offset.value = Math.min( ++ offset.value, ++ Math.max(0, contentWidth - (viewportWidth - gutterWidth)), ++ ); ++ }); ++ }, [parsedDiff, reviewContentWidthByFileId, reviewGutterWidthByFileId, viewportWidth]); + const highlightableFiles = useMemo(() => { + if (parsedDiff.kind !== "files") { + return [] as ReadonlyArray; +@@ -587,59 +854,13 @@ export function ReviewSheet() { + ); + }); + }, [expandedFileIds, parsedDiff, revealedLargeFileIds]); +- const highlightableFileIds = useMemo( +- () => new Set(highlightableFiles.map((file) => file.id)), ++ const highlightableFilesKey = useMemo( ++ () => highlightableFiles.map((file) => `${file.id}:${file.cacheKey}`).join("\n"), + [highlightableFiles], + ); +- const priorityHighlightFileIds = useMemo(() => { +- if (parsedDiff.kind !== "files" || highlightableFiles.length === 0) { +- return [] as ReadonlyArray; +- } +- +- const fileIdsInPriorityOrder = +- visibleFileIds.length > 0 +- ? visibleFileIds.filter((fileId) => highlightableFileIds.has(fileId)) +- : parsedDiff.files +- .slice(0, REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT) +- .map((file) => file.id) +- .filter((fileId) => highlightableFileIds.has(fileId)); +- +- if (fileIdsInPriorityOrder.length === 0) { +- return [] as ReadonlyArray; +- } +- +- const firstVisibleIndex = parsedDiff.files.findIndex( +- (file) => file.id === fileIdsInPriorityOrder[0], +- ); +- const lastVisibleIndex = parsedDiff.files.findIndex( +- (file) => file.id === fileIdsInPriorityOrder[fileIdsInPriorityOrder.length - 1], +- ); +- +- if (firstVisibleIndex < 0 || lastVisibleIndex < 0) { +- return fileIdsInPriorityOrder; +- } +- +- const startIndex = Math.max(0, firstVisibleIndex - REVIEW_HIGHLIGHT_BACKTRACK_COUNT); +- const endIndex = Math.min( +- parsedDiff.files.length - 1, +- lastVisibleIndex + REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT, +- ); +- +- const queuedIds: string[] = []; +- for (let index = startIndex; index <= endIndex; index += 1) { +- const fileId = parsedDiff.files[index]?.id; +- if (fileId && highlightableFileIds.has(fileId)) { +- queuedIds.push(fileId); +- } +- } +- +- return queuedIds; +- }, [highlightableFileIds, highlightableFiles.length, parsedDiff, visibleFileIds]); +- const viewportWidth = Math.max(width, 280); +- const reviewListContentWidth = useMemo( +- () => computeReviewListContentWidth(reviewListItems, viewportWidth), +- [reviewListItems, viewportWidth], +- ); ++ useEffect(() => { ++ highlightableFilesRef.current = highlightableFiles; ++ }, [highlightableFiles]); + const loadGitDiffs = useCallback(async () => { + if (!cwd) { + return; +@@ -714,100 +935,6 @@ export function ReviewSheet() { + void loadGitDiffs(); + }, [loadGitDiffs]); + +- useEffect(() => { +- selectedThemeRef.current = selectedTheme; +- }, [selectedTheme]); +- +- useEffect(() => { +- highlightableFilesByIdRef.current = new Map(highlightableFiles.map((file) => [file.id, file])); +- }, [highlightableFiles]); +- +- const startHighlightQueueRunner = useCallback(function startHighlightQueueRunner() { +- if (highlightQueueActiveRef.current) { +- return; +- } +- +- const generation = highlightQueueGenerationRef.current; +- highlightQueueActiveRef.current = true; +- +- void (async () => { +- try { +- while (generation === highlightQueueGenerationRef.current) { +- const nextFileId = highlightQueueRef.current.shift(); +- if (!nextFileId) { +- break; +- } +- +- const file = highlightableFilesByIdRef.current.get(nextFileId); +- if (!file) { +- continue; +- } +- +- const theme = selectedThemeRef.current; +- const cached = getCachedHighlightedReviewFile(file, theme); +- if (cached) { +- logReviewDiffDiagnostic("using cached highlighted file", { +- fileId: file.id, +- filePath: file.path, +- theme, +- }); +- setHighlightedFilesById((current) => +- current[file.id] === cached ? current : { ...current, [file.id]: cached }, +- ); +- continue; +- } +- +- logReviewDiffDiagnostic("requesting highlighted file", { +- fileId: file.id, +- filePath: file.path, +- theme, +- }); +- +- try { +- await new Promise((resolve) => { +- InteractionManager.runAfterInteractions(() => resolve()); +- }); +- const result = await highlightReviewFile(file, theme); +- if (generation !== highlightQueueGenerationRef.current) { +- logReviewDiffDiagnostic("discarding highlighted file after cancellation", { +- fileId: file.id, +- filePath: file.path, +- }); +- return; +- } +- +- logReviewDiffDiagnostic("received highlighted file", { +- fileId: file.id, +- filePath: file.path, +- additionLines: result.additionLines.length, +- deletionLines: result.deletionLines.length, +- }); +- setHighlightedFilesById((current) => { +- if (current[file.id] === result) { +- return current; +- } +- return { ...current, [file.id]: result }; +- }); +- } catch (error) { +- logReviewDiffDiagnostic("highlight request failed", { +- fileId: file.id, +- filePath: file.path, +- error: error instanceof Error ? error.message : String(error), +- }); +- } +- } +- } finally { +- highlightQueueActiveRef.current = false; +- if ( +- generation === highlightQueueGenerationRef.current && +- highlightQueueRef.current.length > 0 +- ) { +- startHighlightQueueRunner(); +- } +- } +- })(); +- }, []); +- + useEffect(() => { + if (reviewSections.length === 0) { + return; +@@ -854,15 +981,15 @@ export function ReviewSheet() { + } + + updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => { +- if (existing !== undefined) { +- const validIds = existing.filter((id) => parsedDiff.files.some((file) => file.id === id)); +- if (validIds.length === existing.length) { +- return existing; +- } +- return validIds; ++ const validIds = getValidReviewExpandedFileIds(parsedDiff.files, existing); ++ if ( ++ existing !== undefined && ++ validIds.length === existing.length && ++ validIds.every((id, index) => id === existing[index]) ++ ) { ++ return existing; + } +- +- return getDefaultExpandedFileIds(parsedDiff.files); ++ return validIds; + }); + }, [parsedDiff, reviewCache.threadKey, selectedSection?.id]); + +@@ -887,11 +1014,7 @@ export function ReviewSheet() { + + useEffect(() => { + setHighlightedFilesById({}); +- setVisibleFileIds([]); +- highlightQueueGenerationRef.current += 1; +- highlightQueueRef.current = []; +- highlightRequestedFileIdsRef.current = new Set(); +- highlightQueueActiveRef.current = false; ++ highlightRunIdRef.current += 1; + clearReviewHighlightFileCache(); + loggedMissingReviewTokenKeys.clear(); + logReviewDiffDiagnostic("reset highlighted files", { +@@ -905,15 +1028,23 @@ export function ReviewSheet() { + return; + } + ++ markReviewEvent("parsed-diff-ready", { ++ sectionId: selectedSection?.id ?? null, ++ fileCount: parsedDiff.fileCount, ++ additions: parsedDiff.additions, ++ deletions: parsedDiff.deletions, ++ renderedItems: reviewListItems.length, ++ }); + logReviewDiffDiagnostic("parsed diff files", { + selectedSectionId: selectedSection?.id ?? null, + fileCount: parsedDiff.fileCount, + renderableFileCount: parsedDiff.files.length, + }); +- }, [parsedDiff, selectedSection?.id]); ++ }, [parsedDiff, reviewListItems.length, selectedSection?.id]); + + useEffect(() => { +- if (priorityHighlightFileIds.length === 0) { ++ const files = highlightableFilesRef.current; ++ if (files.length === 0) { + logReviewDiffDiagnostic("no highlightable files", { + selectedSectionId: selectedSection?.id ?? null, + parsedDiffKind: parsedDiff.kind, +@@ -922,33 +1053,98 @@ export function ReviewSheet() { + return; + } + +- const queuedFileIds: string[] = []; +- priorityHighlightFileIds.forEach((fileId) => { +- if (highlightRequestedFileIdsRef.current.has(fileId)) { +- return; +- } +- +- const file = highlightableFilesByIdRef.current.get(fileId); +- if (!file) { +- return; +- } +- +- highlightRequestedFileIdsRef.current.add(fileId); +- highlightQueueRef.current.push(fileId); +- queuedFileIds.push(fileId); +- }); +- +- if (queuedFileIds.length === 0) { ++ if (reviewHighlighter.status !== "ready") { ++ logReviewDiffDiagnostic("waiting for highlighter provider", { ++ selectedSectionId: selectedSection?.id ?? null, ++ status: reviewHighlighter.status, ++ error: reviewHighlighter.error, ++ }); + return; + } + +- logReviewDiffDiagnostic("scheduling file highlights", { ++ const runId = highlightRunIdRef.current; ++ let cancelled = false; ++ ++ logReviewDiffDiagnostic("streaming file highlights", { + selectedSectionId: selectedSection?.id ?? null, +- fileCount: queuedFileIds.length, +- fileIds: queuedFileIds, ++ fileCount: files.length, + }); +- startHighlightQueueRunner(); +- }, [parsedDiff.kind, priorityHighlightFileIds, selectedSection?.id, startHighlightQueueRunner]); ++ ++ void (async () => { ++ for (const file of files) { ++ if (cancelled || runId !== highlightRunIdRef.current) { ++ return; ++ } ++ ++ const cached = getCachedHighlightedReviewFile(file, selectedTheme); ++ if (cached) { ++ setHighlightedFilesById((current) => ++ current[file.id] === cached ? current : { ...current, [file.id]: cached }, ++ ); ++ continue; ++ } ++ ++ logReviewDiffDiagnostic("requesting highlighted file", { ++ fileId: file.id, ++ filePath: file.path, ++ theme: selectedTheme, ++ }); ++ ++ try { ++ const highlightStartedAt = performance.now(); ++ const result = await streamHighlightReviewFile(file, selectedTheme, (progress) => { ++ if (cancelled || runId !== highlightRunIdRef.current) { ++ return; ++ } ++ ++ if (!progress.complete) { ++ return; ++ } ++ ++ logReviewDiffDiagnostic("received streamed highlighted file", { ++ fileId: file.id, ++ filePath: file.path, ++ highlightedLineCount: progress.highlightedLineCount, ++ durationMs: Math.round(performance.now() - highlightStartedAt), ++ }); ++ }); ++ ++ if (cancelled || runId !== highlightRunIdRef.current) { ++ return; ++ } ++ ++ logReviewDiffDiagnostic("received highlighted file", { ++ fileId: file.id, ++ filePath: file.path, ++ additionLines: result.additionLines.length, ++ deletionLines: result.deletionLines.length, ++ }); ++ setHighlightedFilesById((current) => ++ current[file.id] === result ? current : { ...current, [file.id]: result }, ++ ); ++ } catch (error) { ++ logReviewDiffDiagnostic("highlight request failed", { ++ fileId: file.id, ++ filePath: file.path, ++ error: error instanceof Error ? error.message : String(error), ++ }); ++ } ++ ++ await waitForReviewDelay(0); ++ } ++ })(); ++ ++ return () => { ++ cancelled = true; ++ }; ++ }, [ ++ highlightableFilesKey, ++ parsedDiff.kind, ++ reviewHighlighter.error, ++ reviewHighlighter.status, ++ selectedSection?.id, ++ selectedTheme, ++ ]); + + const refreshSelectedSection = useCallback(async () => { + if (!selectedSection) { +@@ -968,20 +1164,68 @@ export function ReviewSheet() { + + const handleToggleExpandedFile = useCallback( + (fileId: string) => { +- if (!reviewCache.threadKey || !selectedSection?.id || parsedDiff.kind !== "files") { ++ if (!selectedSection?.id || parsedDiff.kind !== "files") { + return; + } + +- updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => { +- const currentIds = existing ?? getDefaultExpandedFileIds(parsedDiff.files); +- return currentIds.includes(fileId) ++ const sectionId = selectedSection.id; ++ ++ setLocalExpandedFileIdsBySection((current) => { ++ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, current[sectionId]); ++ const nextIds = currentIds.includes(fileId) + ? currentIds.filter((id) => id !== fileId) + : [...currentIds, fileId]; ++ ++ return { ++ ...current, ++ [sectionId]: nextIds, ++ }; + }); ++ ++ if (reviewCache.threadKey) { ++ updateReviewExpandedFileIds(reviewCache.threadKey, sectionId, (existing) => { ++ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, existing); ++ return currentIds.includes(fileId) ++ ? currentIds.filter((id) => id !== fileId) ++ : [...currentIds, fileId]; ++ }); ++ } + }, + [parsedDiff, reviewCache.threadKey, selectedSection?.id], + ); + ++ const handleToggleViewedFile = useCallback( ++ (fileId: string) => { ++ if (!selectedSection?.id) { ++ return; ++ } ++ ++ const sectionId = selectedSection.id; ++ ++ setLocalViewedFileIdsBySection((current) => { ++ const currentIds = current[sectionId] ?? []; ++ const nextIds = currentIds.includes(fileId) ++ ? currentIds.filter((id) => id !== fileId) ++ : [...currentIds, fileId]; ++ ++ return { ++ ...current, ++ [sectionId]: nextIds, ++ }; ++ }); ++ ++ if (reviewCache.threadKey) { ++ updateReviewViewedFileIds(reviewCache.threadKey, sectionId, (existing) => { ++ const currentIds = existing ?? []; ++ return currentIds.includes(fileId) ++ ? currentIds.filter((id) => id !== fileId) ++ : [...currentIds, fileId]; ++ }); ++ } ++ }, ++ [reviewCache.threadKey, selectedSection?.id], ++ ); ++ + const handleRevealLargeDiff = useCallback( + (fileId: string) => { + if (!reviewCache.threadKey || !selectedSection?.id) { +@@ -1080,35 +1324,6 @@ export function ReviewSheet() { + + return <>{children}; + }, [error, parsedDiffNotice]); +- const stickyHeaderIndices = useMemo(() => { +- const itemOffset = listHeader ? 1 : 0; +- +- return reviewListItems.flatMap((item, index) => +- item.kind === "file-header" ? [index + itemOffset] : [], +- ); +- }, [listHeader, reviewListItems]); +- +- const viewabilityConfigRef = useRef({ +- itemVisiblePercentThreshold: 10, +- }); +- const onViewableItemsChangedRef = useRef( +- ({ +- viewableItems, +- }: { +- readonly viewableItems: Array>; +- readonly changed: Array>; +- }) => { +- const nextVisibleFileIds = Array.from( +- new Set( +- viewableItems +- .filter((token) => token.isViewable && token.item !== undefined) +- .map((token) => token.item.fileId), +- ), +- ); +- +- setVisibleFileIds(nextVisibleFileIds); +- }, +- ); + + const renderReviewListItem = useCallback( + ({ item }: ListRenderItemInfo) => { +@@ -1116,112 +1331,142 @@ export function ReviewSheet() { + return null; + } + ++ let renderedItem: ReactElement | null = null; + switch (item.kind) { + case "file-header": +- return ( ++ renderedItem = ( + + ); ++ break; + case "file-suppressed": +- return ( ++ renderedItem = ( + + ); +- case "hunk": +- return ( +- ++ break; ++ case "hunk": { ++ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth; ++ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0; ++ ++ renderedItem = ( ++ } ++ viewportWidth={viewportWidth} ++ > ++ ++ + ); ++ break; ++ } + case "line": { +- const file = reviewFileById.get(item.fileId); +- if (!file) { +- return null; +- } +- +- const fileLineRows = reviewLineRowsByFileId.get(file.id) ?? []; +- const lineIndex = reviewLineIndexByRowId.get(item.row.id); +- if (lineIndex === undefined) { +- return null; +- } +- ++ const fileLineRows = reviewLineRowsByFileId.get(item.file.id) ?? []; + const pendingSelectionForFile = + pendingCommentSelection && + pendingCommentSelection.sectionTitle === selectedSection.title && +- pendingCommentSelection.filePath === file.path ++ pendingCommentSelection.filePath === item.file.path + ? pendingCommentSelection + : null; + const selectedTargetForFile = + activeCommentTarget && + activeCommentTarget.sectionTitle === selectedSection.title && +- activeCommentTarget.filePath === file.path ++ activeCommentTarget.filePath === item.file.path + ? activeCommentTarget + : null; + const highlightedFile = +- highlightedFilesById[file.id] ?? +- getCachedHighlightedReviewFile(file, selectedTheme) ?? ++ deferredHighlightedFilesById[item.file.id] ?? ++ getCachedHighlightedReviewFile(item.file, selectedTheme) ?? + null; ++ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth; ++ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0; + + if (highlightedFile === null) { +- const missingTokenKey = `${selectedSection.id}:${file.id}`; ++ const missingTokenKey = `${selectedSection.id}:${item.file.id}`; + if (!loggedMissingReviewTokenKeys.has(missingTokenKey)) { + loggedMissingReviewTokenKeys.add(missingTokenKey); + logReviewDiffDiagnostic("rendering file without tokens", { + sectionId: selectedSection.id, +- fileId: file.id, +- filePath: file.path, +- highlightedFileKnownInState: highlightedFilesById[file.id] !== undefined, ++ fileId: item.file.id, ++ filePath: item.file.path, ++ highlightedFileKnownInState: ++ deferredHighlightedFilesById[item.file.id] !== undefined, + }); + } + } + + const selectionState = +- pendingSelectionForFile?.anchorIndex === lineIndex ++ pendingSelectionForFile?.anchorIndex === item.lineIndex + ? ("anchor" as const) + : selectedTargetForFile && +- lineIndex >= selectedTargetForFile.startIndex && +- lineIndex <= selectedTargetForFile.endIndex ++ item.lineIndex >= selectedTargetForFile.startIndex && ++ item.lineIndex <= selectedTargetForFile.endIndex + ? ("selected" as const) + : null; + +- return ( +- +- handlePressLine({ +- sectionTitle: selectedSection.title, +- filePath: file.path, +- lines: fileLineRows, +- lineIndex, +- }) +- } +- onStartRangeSelection={() => +- handleStartRangeSelection({ +- sectionTitle: selectedSection.title, +- filePath: file.path, +- lines: fileLineRows, +- lineIndex, +- }) ++ renderedItem = ( ++ + } +- /> ++ viewportWidth={viewportWidth} ++ > ++ ++ handlePressLine({ ++ sectionTitle: selectedSection.title, ++ filePath: item.file.path, ++ lines: fileLineRows, ++ lineIndex: item.lineIndex, ++ }) ++ } ++ onStartRangeSelection={() => ++ handleStartRangeSelection({ ++ sectionTitle: selectedSection.title, ++ filePath: item.file.path, ++ lines: fileLineRows, ++ lineIndex: item.lineIndex, ++ }) ++ } ++ /> ++ + ); ++ break; + } + } ++ ++ return renderedItem; + }, + [ + activeCommentTarget, +@@ -1229,14 +1474,17 @@ export function ReviewSheet() { + handleRevealLargeDiff, + handleStartRangeSelection, + handleToggleExpandedFile, +- highlightedFilesById, ++ handleToggleViewedFile, ++ getReviewFileHorizontalOffset, ++ deferredHighlightedFilesById, + pendingCommentSelection, +- reviewFileById, +- reviewLineIndexByRowId, ++ reviewContentWidthByFileId, ++ reviewGutterWidthByFileId, + reviewLineRowsByFileId, +- reviewListContentWidth, + selectedSection, + selectedTheme, ++ viewedFileIdSet, ++ viewportWidth, + ], + ); + +@@ -1374,27 +1622,20 @@ export function ReviewSheet() { + + {selectedSection && parsedDiff.kind === "files" ? ( + item.id} ++ initialNumToRender={20} ++ maxToRenderPerBatch={20} ++ updateCellsBatchingPeriod={16} ++ windowSize={5} ++ removeClippedSubviews={false} + keyboardShouldPersistTaps="handled" + ListHeaderComponent={listHeader} +- stickyHeaderIndices={stickyHeaderIndices} +- removeClippedSubviews={false} +- initialNumToRender={24} +- maxToRenderPerBatch={16} +- updateCellsBatchingPeriod={16} +- windowSize={10} +- scrollEventThrottle={16} +- onViewableItemsChanged={onViewableItemsChangedRef.current} +- viewabilityConfig={viewabilityConfigRef.current} + contentContainerStyle={{ +- paddingTop: REVIEW_HEADER_SPACING, ++ paddingTop: topContentInset + REVIEW_HEADER_SPACING, + paddingBottom: Math.max(insets.bottom, 18) + 18, + }} + /> +diff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx +index d61924a62..3f2ae0160 100644 +--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx ++++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx +@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({ + default: "monospace", + }); + ++export const REVIEW_DIFF_LINE_HEIGHT = 26; ++const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2; ++ + export function renderVisibleWhitespace(value: string): string { + const expandedTabs = value.replace(/\t/g, " "); + return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\u00A0")); +@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string | + export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) { + if (props.change === "delete") { + return ( +- +- +- {Array.from({ length: 6 }, (_, index) => ( +- ++ ++ ++ {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => ( ++ ++ ++ ++ + ))} + + +@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo + } + + return ( +- ++ + + + ); +@@ -63,6 +69,7 @@ export function DiffTokenText(props: { + if (!props.tokens || props.tokens.length === 0) { + return ( + { +- it("defaults invalid values to javascript", () => { +- expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("javascript"); +- expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("javascript"); ++ it("defaults invalid values to native", () => { ++ expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("native"); ++ expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("native"); + }); + + it("accepts supported values", () => { +diff --git a/apps/mobile/src/features/review/reviewHighlighterEngine.ts b/apps/mobile/src/features/review/reviewHighlighterEngine.ts +index 5ef9f055a..428768537 100644 +--- a/apps/mobile/src/features/review/reviewHighlighterEngine.ts ++++ b/apps/mobile/src/features/review/reviewHighlighterEngine.ts +@@ -11,7 +11,7 @@ export function resolveReviewHighlighterEnginePreference( + case "native": + return "native"; + default: +- return "javascript"; ++ return "native"; + } + } + +diff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts +index a24a99ceb..69a6e7261 100644 +--- a/apps/mobile/src/features/review/reviewModel.test.ts ++++ b/apps/mobile/src/features/review/reviewModel.test.ts +@@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => { + }); + }); + +- it("flattens expanded files into virtualizable review items", () => { ++ it("flattens expanded file rows into virtualized review items", () => { + const file = makeRenderableFile({ + path: "apps/mobile/src/a.ts", + rows: [ +@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => { + + expect(items).toEqual([ + expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }), +- expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }), +- expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }), ++ expect.objectContaining({ ++ kind: "hunk", ++ fileId: file.id, ++ file, ++ row: file.rows[0], ++ }), ++ expect.objectContaining({ ++ kind: "line", ++ fileId: file.id, ++ file, ++ row: file.rows[1], ++ lineIndex: 0, ++ }), + ]); + }); + +diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts +index 27e6d7ae4..1cfbf358c 100644 +--- a/apps/mobile/src/features/review/reviewModel.ts ++++ b/apps/mobile/src/features/review/reviewModel.ts +@@ -72,6 +72,7 @@ export interface ReviewHunkListItem { + readonly kind: "hunk"; + readonly id: string; + readonly fileId: string; ++ readonly file: ReviewRenderableFile; + readonly row: ReviewRenderableHunkRow; + } + +@@ -79,7 +80,9 @@ export interface ReviewLineListItem { + readonly kind: "line"; + readonly id: string; + readonly fileId: string; ++ readonly file: ReviewRenderableFile; + readonly row: ReviewRenderableLineRow; ++ readonly lineIndex: number; + } + + export type ReviewListItem = +@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil + } + + // The flattened review list item model is inspired by pierre/diffs' iterator-first +-// virtualization architecture, adapted here for React Native and LegendList. ++// virtualization architecture, adapted here for React Native virtualization. + // Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs + // Reference files: + // - src/utils/iterateOverDiff.ts +@@ -350,12 +353,14 @@ export function buildReviewListItems(input: { + } + } + +- file.rows.forEach((row) => { ++ let lineIndex = 0; ++ file.rows.forEach((row, rowIndex) => { + if (row.kind === "hunk") { + items.push({ + kind: "hunk", +- id: row.id, ++ id: `${file.id}:row:${rowIndex}:${row.id}`, + fileId: file.id, ++ file, + row, + }); + return; +@@ -363,10 +368,13 @@ export function buildReviewListItems(input: { + + items.push({ + kind: "line", +- id: row.id, ++ id: `${file.id}:row:${rowIndex}:${row.id}`, + fileId: file.id, ++ file, + row, ++ lineIndex, + }); ++ lineIndex += 1; + }); + }); + +diff --git a/apps/mobile/src/features/review/reviewState.ts b/apps/mobile/src/features/review/reviewState.ts +index 06134db7d..c116f93fe 100644 +--- a/apps/mobile/src/features/review/reviewState.ts ++++ b/apps/mobile/src/features/review/reviewState.ts +@@ -64,6 +64,13 @@ const reviewRevealedLargeFileIdsByThreadKeyAtom = Atom.family((threadKey: string + ), + ); + ++const reviewViewedFileIdsByThreadKeyAtom = Atom.family((threadKey: string) => ++ Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe( ++ Atom.keepAlive, ++ Atom.withLabel(`mobile:review:viewed-file-ids:${threadKey}`), ++ ), ++); ++ + const reviewParsedDiffBySectionCacheKeyAtom = Atom.family((cacheKey: string) => + Atom.make<{ readonly diff: string | null; readonly parsed: ReviewParsedDiff } | null>(null).pipe( + Atom.keepAlive, +@@ -110,6 +117,9 @@ export function useReviewCacheForThread(input: { + ? reviewRevealedLargeFileIdsByThreadKeyAtom(threadKey) + : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM, + ); ++ const viewedFileIdsBySection = useAtomValue( ++ threadKey ? reviewViewedFileIdsByThreadKeyAtom(threadKey) : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM, ++ ); + + return { + threadKey, +@@ -118,6 +128,7 @@ export function useReviewCacheForThread(input: { + selectedSectionId, + expandedFileIdsBySection, + revealedLargeFileIdsBySection, ++ viewedFileIdsBySection, + }; + } + +@@ -169,6 +180,20 @@ export function updateReviewRevealedLargeFileIds( + }); + } + ++export function updateReviewViewedFileIds( ++ threadKey: string, ++ sectionId: string, ++ update: (current: ReadonlyArray | undefined) => ReadonlyArray | undefined, ++): void { ++ const atom = reviewViewedFileIdsByThreadKeyAtom(threadKey); ++ const current = appAtomRegistry.get(atom); ++ const nextValue = update(current[sectionId]); ++ appAtomRegistry.set(atom, { ++ ...current, ++ [sectionId]: nextValue, ++ }); ++} ++ + export function getCachedReviewParsedDiff(input: { + readonly threadKey: string | null; + readonly sectionId: string | null; +diff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts +index 05b5c9213..402d00668 100644 +--- a/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts ++++ b/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts +@@ -24,7 +24,7 @@ function makeRenderableFile( + describe("highlightReviewFile", () => { + it("preserves one highlighted token row per diff line even without trailing newlines", async () => { + const file = makeRenderableFile({ +- path: "apps/mobile/src/example.test.ts", ++ path: "apps/mobile/src/example.txt", + additionLines: [ + 'const items = ["a"];', + 'expect(items).toEqual(["a"]);', +@@ -36,15 +36,23 @@ describe("highlightReviewFile", () => { + const highlighted = await highlightReviewFile(file, "light"); + + expect(highlighted.additionLines).toHaveLength(file.additionLines.length); +- expect(highlighted.additionLines[0]?.some((token) => token.content === "const")).toBe(true); +- expect(highlighted.additionLines[1]?.some((token) => token.content === "expect")).toBe(true); +- expect(highlighted.additionLines[2]?.some((token) => token.content === "const")).toBe(true); +- expect(highlighted.additionLines[3]?.some((token) => token.content === "expect")).toBe(true); ++ expect(highlighted.additionLines[0]?.map((token) => token.content).join("")).toBe( ++ file.additionLines[0], ++ ); ++ expect(highlighted.additionLines[1]?.map((token) => token.content).join("")).toBe( ++ file.additionLines[1], ++ ); ++ expect(highlighted.additionLines[2]?.map((token) => token.content).join("")).toBe( ++ file.additionLines[2], ++ ); ++ expect(highlighted.additionLines[3]?.map((token) => token.content).join("")).toBe( ++ file.additionLines[3], ++ ); + }); + + it("adds word-alt diff emphasis for paired deletion and addition lines", async () => { + const file = makeRenderableFile({ +- path: "apps/mobile/src/example-inline-diff.test.ts", ++ path: "apps/mobile/src/example-inline-diff.txt", + additionLines: ["const after = 2;"], + deletionLines: ["const before = 1;"], + rows: [ +@@ -82,7 +90,7 @@ describe("highlightReviewFile", () => { + it("falls back to plain tokens for very long lines", async () => { + const longLine = `const value = "${"a".repeat(1_100)}";`; + const file = makeRenderableFile({ +- path: "apps/mobile/src/example-long-line.ts", ++ path: "apps/mobile/src/example-long-line.txt", + additionLines: [longLine], + rows: [ + { +diff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.ts +index f7a5c4125..eb6bf6973 100644 +--- a/apps/mobile/src/features/review/shikiReviewHighlighter.ts ++++ b/apps/mobile/src/features/review/shikiReviewHighlighter.ts +@@ -1,5 +1,14 @@ + import { createHighlighterCore, type HighlighterCore } from "@shikijs/core"; + import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript"; ++import bashLanguage from "@shikijs/langs/bash"; ++import javascriptLanguage from "@shikijs/langs/javascript"; ++import jsonLanguage from "@shikijs/langs/json"; ++import jsxLanguage from "@shikijs/langs/jsx"; ++import tsxLanguage from "@shikijs/langs/tsx"; ++import typescriptLanguage from "@shikijs/langs/typescript"; ++import yamlLanguage from "@shikijs/langs/yaml"; ++import githubDarkDefault from "@shikijs/themes/github-dark-default"; ++import githubLightDefault from "@shikijs/themes/github-light-default"; + import { getFiletypeFromFileName } from "@pierre/diffs/utils"; + + import { +@@ -11,6 +20,7 @@ import type { ReviewRenderableFile, ReviewRenderableLineRow } from "./reviewMode + import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs"; + + export type ReviewDiffTheme = "light" | "dark"; ++export type { ReviewHighlighterEngine }; + + export interface ReviewHighlightedToken { + content: string; +@@ -24,12 +34,19 @@ export interface ReviewHighlightedFile { + readonly deletionLines: ReadonlyArray>; + } + ++export interface ReviewHighlightFileProgress { ++ readonly highlightedFile: ReviewHighlightedFile; ++ readonly complete: boolean; ++ readonly highlightedLineCount: number; ++} ++ + const SHIKI_THEME_NAME_BY_SCHEME = { + light: "github-light-default", + dark: "github-dark-default", + } as const; + const REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE = +- process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? "javascript"; ++ process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? ++ (process.env.NODE_ENV === "test" ? "javascript" : "native"); + const REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE = resolveReviewHighlighterEnginePreference( + REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE, + ); +@@ -38,12 +55,30 @@ const REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE = resolveReviewHighlighterBooleanF + false, + ); + const REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT = 8; +-const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 40; +-const REVIEW_HIGHLIGHT_CHUNK_SIZE = 20; ++const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 8; ++const REVIEW_HIGHLIGHT_CHUNK_SIZE = 200; + const REVIEW_TOKENIZE_MAX_LINE_LENGTH = 1_000; + const highlightCache = new Map>(); + const resolvedHighlightCache = new Map(); +-const loadedLanguages = new Set(["text"]); ++const REVIEW_INITIAL_LANGUAGE_MODULES = [ ++ bashLanguage, ++ javascriptLanguage, ++ jsonLanguage, ++ jsxLanguage, ++ tsxLanguage, ++ typescriptLanguage, ++ yamlLanguage, ++] satisfies Parameters[0]["langs"]; ++const loadedLanguages = new Set([ ++ "text", ++ "bash", ++ "javascript", ++ "json", ++ "jsx", ++ "tsx", ++ "typescript", ++ "yaml", ++]); + const languageLoadingPromises = new Map>(); + const languageImports: Partial Promise>> = { + javascript: () => import("@shikijs/langs/javascript"), +@@ -215,21 +250,13 @@ function joinPatchLines(lines: ReadonlyArray): string { + + function waitForNextFrame(): Promise { + return new Promise((resolve) => { +- if (typeof requestAnimationFrame === "function") { +- requestAnimationFrame(() => resolve()); +- return; +- } +- + setTimeout(resolve, 0); + }); + } + + async function getHighlighter(): Promise { + if (!highlighterPromise) { +- const configuredHighlighterPromise = Promise.all([ +- import("@shikijs/themes/github-light-default"), +- import("@shikijs/themes/github-dark-default"), +- ]).then(async ([lightThemeModule, darkThemeModule]) => { ++ const configuredHighlighterPromise = (async () => { + let nativeEngineAvailable = false; + + logReviewHighlighterDiagnostic("initializing", { +@@ -238,12 +265,11 @@ async function getHighlighter(): Promise { + resultCacheDisabled: REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE, + }); + +- const themes = [lightThemeModule.default, darkThemeModule.default]; ++ const themes = [githubLightDefault, githubDarkDefault]; + + if (REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE !== "javascript") { + try { + const nativeEngineModule = await import("react-native-shiki-engine"); +- logReviewHighlighterDiagnostic("imported react-native-shiki-engine"); + nativeEngineAvailable = nativeEngineModule.isNativeEngineAvailable(); + logReviewHighlighterDiagnostic("checked native engine availability", { + nativeEngineAvailable, +@@ -253,7 +279,7 @@ async function getHighlighter(): Promise { + logReviewHighlighterDiagnostic("creating native regex engine"); + const highlighter = await createHighlighterCore({ + themes, +- langs: [], ++ langs: REVIEW_INITIAL_LANGUAGE_MODULES, + engine: nativeEngineModule.createNativeEngine(), + }); + logReviewHighlighterDiagnostic("using native engine"); +@@ -281,7 +307,7 @@ async function getHighlighter(): Promise { + ); + const highlighter = await createHighlighterCore({ + themes, +- langs: [], ++ langs: REVIEW_INITIAL_LANGUAGE_MODULES, + engine: createJavaScriptRegexEngine(), + }); + logReviewHighlighterDiagnostic("using javascript engine", { +@@ -291,7 +317,7 @@ async function getHighlighter(): Promise { + highlighter, + engine, + }; +- }); ++ })(); + + highlighterPromise = configuredHighlighterPromise + .then((result) => result.highlighter) +@@ -316,11 +342,52 @@ export async function getActiveReviewHighlighterEngine(): Promise { ++ await getHighlighter(); ++} ++ ++export async function prepareReviewHighlighterLanguages( ++ languages: ReadonlyArray, ++): Promise { ++ const highlighter = await getHighlighter(); ++ await Promise.all( ++ languages.map(async (language) => { ++ const candidate = resolveLanguageAlias(language); ++ if (candidate === "text" || !(candidate in languageImports)) { ++ return; ++ } ++ ++ await loadSingleLanguage(highlighter, candidate); ++ }), ++ ); ++} ++ + function resolveLanguageAlias(language: string): string { + const normalized = language.toLowerCase(); + return languageAliases[normalized] ?? normalized; + } + ++function resolveLoadedLanguageFromPath( ++ path: string, ++ languageHint: string | null = null, ++): string | null { ++ const detectedLanguage = languageHint ?? getFiletypeFromFileName(path); ++ if (!detectedLanguage) { ++ return "text"; ++ } ++ ++ const candidate = resolveLanguageAlias(detectedLanguage); ++ if (candidate === "text" || candidate === "ansi") { ++ return "text"; ++ } ++ ++ if (!(candidate in languageImports)) { ++ return "text"; ++ } ++ ++ return loadedLanguages.has(candidate) ? candidate : null; ++} ++ + async function loadSingleLanguage( + highlighter: HighlighterCore, + language: string, +@@ -360,6 +427,11 @@ async function resolveLanguageFromPath( + path: string, + languageHint: string | null = null, + ): Promise { ++ const loadedLanguage = resolveLoadedLanguageFromPath(path, languageHint); ++ if (loadedLanguage) { ++ return loadedLanguage; ++ } ++ + const detectedLanguage = languageHint ?? getFiletypeFromFileName(path); + if (!detectedLanguage) { + return "text"; +@@ -374,8 +446,12 @@ async function resolveLanguageFromPath( + return "text"; + } + ++ if (loadedLanguages.has(candidate)) { ++ return candidate; ++ } ++ + const highlighter = await getHighlighter(); +- const loaded = await loadSingleLanguage(highlighter, resolveLanguageAlias(candidate)); ++ const loaded = await loadSingleLanguage(highlighter, candidate); + if (!loaded) { + return "text"; + } +@@ -384,7 +460,10 @@ async function resolveLanguageFromPath( + } + + async function resolveLanguage(file: ReviewRenderableFile): Promise { +- return resolveLanguageFromPath(file.path, file.languageHint); ++ return ( ++ resolveLoadedLanguageFromPath(file.path, file.languageHint) ?? ++ (await resolveLanguageFromPath(file.path, file.languageHint)) ++ ); + } + + function normalizeHighlightedLines( +@@ -399,6 +478,18 @@ function normalizeHighlightedLines( + ); + } + ++function makePlainHighlightedLines( ++ lines: ReadonlyArray, ++): ReadonlyArray> { ++ return lines.map((line) => [ ++ { ++ content: stripTrailingNewline(line), ++ color: null, ++ fontStyle: null, ++ }, ++ ]); ++} ++ + function applyWordAltDiffHighlightsToFile( + file: ReviewRenderableFile, + highlighted: ReviewHighlightedFile, +@@ -594,6 +685,67 @@ async function highlightLines( + return highlightedLines; + } + ++async function highlightPatchLinesInChunks(input: { ++ readonly lines: ReadonlyArray; ++ readonly language: string; ++ readonly theme: string; ++ readonly onChunk: ( ++ startIndex: number, ++ tokens: ReadonlyArray>, ++ ) => void; ++}): Promise>> { ++ if (input.lines.length === 0) { ++ return []; ++ } ++ ++ const highlighter = await getHighlighter(); ++ const highlightedLines: Array> = []; ++ ++ for ( ++ let startIndex = 0; ++ startIndex < input.lines.length; ++ startIndex += REVIEW_HIGHLIGHT_CHUNK_SIZE ++ ) { ++ const lineChunk = input.lines.slice(startIndex, startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE); ++ const chunkTokens: Array> = []; ++ const tokenizableLines: string[] = []; ++ const tokenizableIndexes: number[] = []; ++ ++ lineChunk.forEach((line, index) => { ++ const strippedLine = stripTrailingNewline(line); ++ if (strippedLine.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH) { ++ chunkTokens[index] = [{ content: strippedLine, color: null, fontStyle: null }]; ++ return; ++ } ++ ++ tokenizableIndexes.push(index); ++ tokenizableLines.push(strippedLine); ++ }); ++ ++ if (tokenizableLines.length > 0) { ++ const tokenLines = highlighter.codeToTokensBase(tokenizableLines.join("\n"), { ++ lang: input.language, ++ theme: input.theme, ++ }); ++ const normalizedTokenLines = normalizeHighlightedLines(tokenLines); ++ ++ tokenizableIndexes.forEach((chunkIndex, tokenIndex) => { ++ chunkTokens[chunkIndex] = normalizedTokenLines[tokenIndex] ?? []; ++ }); ++ } ++ ++ const completedChunk = lineChunk.map((_, index) => chunkTokens[index] ?? []); ++ highlightedLines.push(...completedChunk); ++ input.onChunk(startIndex, completedChunk); ++ ++ if (startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE < input.lines.length) { ++ await waitForNextFrame(); ++ } ++ } ++ ++ return highlightedLines; ++} ++ + function getHighlightCacheKey(file: ReviewRenderableFile, theme: ReviewDiffTheme): string { + return `${SHIKI_THEME_NAME_BY_SCHEME[theme]}:${file.cacheKey}`; + } +@@ -667,7 +819,28 @@ export async function highlightReviewFile( + deletionLineCount: file.deletionLines.length, + rowCount: file.rows.length, + }); +- const language = await resolveLanguage(file); ++ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint); ++ const language = loadedLanguage ?? (await resolveLanguage(file)); ++ if (language === "text") { ++ const highlighted = applyWordAltDiffHighlightsToFile(file, { ++ additionLines: makePlainHighlightedLines(file.additionLines), ++ deletionLines: makePlainHighlightedLines(file.deletionLines), ++ }); ++ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { ++ storeResolvedHighlightedFile(cacheKey, highlighted); ++ } ++ logReviewHighlighterDiagnostic("file highlight complete", { ++ fileId: file.id, ++ filePath: file.path, ++ theme, ++ language, ++ highlightedAdditionLineCount: highlighted.additionLines.length, ++ highlightedDeletionLineCount: highlighted.deletionLines.length, ++ durationMs: Date.now() - startedAt, ++ }); ++ return highlighted; ++ } ++ + const additionLines = await highlightLines( + joinPatchLines(file.additionLines), + language, +@@ -707,6 +880,113 @@ export async function highlightReviewFile( + }); + } + ++export async function streamHighlightReviewFile( ++ file: ReviewRenderableFile, ++ theme: ReviewDiffTheme, ++ onProgress: (progress: ReviewHighlightFileProgress) => void, ++): Promise { ++ const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[theme]; ++ const cacheKey = getHighlightCacheKey(file, theme); ++ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { ++ const resolved = resolvedHighlightCache.get(cacheKey); ++ if (resolved) { ++ onProgress({ ++ highlightedFile: resolved, ++ complete: true, ++ highlightedLineCount: resolved.additionLines.length + resolved.deletionLines.length, ++ }); ++ return resolved; ++ } ++ } ++ ++ const startedAt = Date.now(); ++ logReviewHighlighterDiagnostic("file stream highlight start", { ++ fileId: file.id, ++ filePath: file.path, ++ theme, ++ additionLineCount: file.additionLines.length, ++ deletionLineCount: file.deletionLines.length, ++ rowCount: file.rows.length, ++ }); ++ ++ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint); ++ const language = loadedLanguage ?? (await resolveLanguage(file)); ++ if (language === "text") { ++ const highlighted = applyWordAltDiffHighlightsToFile(file, { ++ additionLines: makePlainHighlightedLines(file.additionLines), ++ deletionLines: makePlainHighlightedLines(file.deletionLines), ++ }); ++ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { ++ storeResolvedHighlightedFile(cacheKey, highlighted); ++ } ++ onProgress({ ++ highlightedFile: highlighted, ++ complete: true, ++ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length, ++ }); ++ logReviewHighlighterDiagnostic("file stream highlight complete", { ++ fileId: file.id, ++ filePath: file.path, ++ theme, ++ language, ++ highlightedAdditionLineCount: highlighted.additionLines.length, ++ highlightedDeletionLineCount: highlighted.deletionLines.length, ++ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length, ++ durationMs: Date.now() - startedAt, ++ }); ++ return highlighted; ++ } ++ ++ const additionLines: Array> = []; ++ const deletionLines: Array> = []; ++ let highlightedLineCount = 0; ++ ++ await highlightPatchLinesInChunks({ ++ lines: file.additionLines, ++ language, ++ theme: shikiTheme, ++ onChunk: (startIndex, tokens) => { ++ tokens.forEach((lineTokens, index) => { ++ additionLines[startIndex + index] = lineTokens; ++ }); ++ highlightedLineCount += tokens.length; ++ }, ++ }); ++ await waitForNextFrame(); ++ await highlightPatchLinesInChunks({ ++ lines: file.deletionLines, ++ language, ++ theme: shikiTheme, ++ onChunk: (startIndex, tokens) => { ++ tokens.forEach((lineTokens, index) => { ++ deletionLines[startIndex + index] = lineTokens; ++ }); ++ highlightedLineCount += tokens.length; ++ }, ++ }); ++ ++ const highlighted = applyWordAltDiffHighlightsToFile(file, { additionLines, deletionLines }); ++ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { ++ storeResolvedHighlightedFile(cacheKey, highlighted); ++ } ++ onProgress({ ++ highlightedFile: highlighted, ++ complete: true, ++ highlightedLineCount, ++ }); ++ logReviewHighlighterDiagnostic("file stream highlight complete", { ++ fileId: file.id, ++ filePath: file.path, ++ theme, ++ language, ++ highlightedAdditionLineCount: highlighted.additionLines.length, ++ highlightedDeletionLineCount: highlighted.deletionLines.length, ++ highlightedLineCount, ++ durationMs: Date.now() - startedAt, ++ }); ++ return highlighted; ++} ++ + export async function highlightReviewSelectedLines(input: { + readonly filePath: string; + readonly lines: ReadonlyArray; +@@ -717,7 +997,9 @@ export async function highlightReviewSelectedLines(input: { + return {}; + } + +- const language = await resolveLanguageFromPath(input.filePath, input.languageHint ?? null); ++ const loadedLanguage = resolveLoadedLanguageFromPath(input.filePath, input.languageHint ?? null); ++ const language = ++ loadedLanguage ?? (await resolveLanguageFromPath(input.filePath, input.languageHint ?? null)); + const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[input.theme]; + const additionLikeLines = input.lines + .filter((line) => line.change !== "delete") +diff --git a/apps/mobile/docs/review-profiling.md b/apps/mobile/docs/review-profiling.md +new file mode 100644 +index 000000000..6977eaf6e +--- /dev/null ++++ b/apps/mobile/docs/review-profiling.md +@@ -0,0 +1,80 @@ ++# Review Screen Profiling ++ ++Use this when the mobile review screen is slow or crashes while opening large diffs. ++ ++## Preferred Capture: React Native DevTools Performance ++ ++This app is on Expo SDK 55 / React Native 0.83 with Hermes, so the best first trace is the React Native DevTools Performance recording. The review screen also emits `t3.review.*` user timing marks in development builds so the trace can show parse, list-building, row indexing, and syntax-highlighting work. ++ ++1. Start the development client: ++ ++ ```sh ++ cd apps/mobile ++ bun dev:client ++ ``` ++ ++2. Open the app in the iOS Simulator or on the device using the development client. ++ ++3. In the terminal running Expo, press `j` to open React Native DevTools. ++ ++4. In DevTools, open the `Performance` panel. ++ ++5. Start recording. ++ ++6. In the app, reproduce the slow path: ++ - Navigate to the thread. ++ - Open `Files Changed`. ++ - Select the largest review source. ++ - Expand a few large files or tap `Load diff`. ++ - Scroll until the app is clearly slow or until just before it crashes. ++ ++7. Stop recording. ++ ++8. Export or save the Performance recording as a JSON trace. ++ ++Send that exported trace file here. Also include the device/simulator model and whether it was iOS or Android. ++ ++## Android Fallback: Hermes Sampling Profile ++ ++Use this if the app crashes before DevTools can export a trace, or if we need deeper JavaScript stack samples. ++ ++1. Run Android dev client: ++ ++ ```sh ++ cd apps/mobile ++ bun android:dev ++ bun dev:client ++ ``` ++ ++2. Open the developer menu from the Expo terminal with `d`. ++ ++3. Select `Enable Sampling Profiler`. ++ ++4. Reproduce the review-screen slowdown. ++ ++5. Open the developer menu again with `d`. ++ ++6. Select `Disable Sampling Profiler`. ++ ++7. Pull and convert the Hermes profile: ++ ++ ```sh ++ cd apps/mobile ++ mkdir -p profiles/review ++ bunx react-native profile-hermes profiles/review ++ ``` ++ ++8. Send the generated Chrome trace/profile file from `apps/mobile/profiles/review`. ++ ++For the development app variant, the Android package is `com.t3tools.t3code.dev`. ++ ++## What To Capture ++ ++For the first trace, do not optimize the repro. We want the slowest realistic case: ++ ++- A diff with many files and large line counts. ++- At least one `Load diff` action for a suppressed large diff. ++- One vertical scroll pass after the content appears. ++- One horizontal scroll of a long file, if that is part of the slowdown. ++ ++If the app crashes, note the last visible action before the crash and attach device logs if available. +diff --git a/apps/mobile/src/app/debug/syntax-highlight.tsx b/apps/mobile/src/app/debug/syntax-highlight.tsx +new file mode 100644 +index 000000000..c2a36d126 +--- /dev/null ++++ b/apps/mobile/src/app/debug/syntax-highlight.tsx +@@ -0,0 +1,423 @@ ++import { createHighlighterCore, type HighlighterCore } from "@shikijs/core"; ++import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript"; ++import typescriptLanguage from "@shikijs/langs/typescript"; ++import githubDarkDefault from "@shikijs/themes/github-dark-default"; ++import githubLightDefault from "@shikijs/themes/github-light-default"; ++import Stack from "expo-router/stack"; ++import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"; ++import { ++ FlatList, ++ Pressable, ++ Text as NativeText, ++ type ListRenderItemInfo, ++ useColorScheme, ++ useWindowDimensions, ++ View, ++} from "react-native"; ++import { useSafeAreaInsets } from "react-native-safe-area-context"; ++ ++import { AppText as Text } from "../../components/AppText"; ++import { cn } from "../../lib/cn"; ++import { useThemeColor } from "../../lib/useThemeColor"; ++ ++type DebugHighlightEngine = "native" | "javascript"; ++ ++type DebugToken = { ++ readonly content: string; ++ readonly color: string | null; ++ readonly fontStyle: number | null; ++}; ++ ++type DebugLine = { ++ readonly id: string; ++ readonly chunkIndex: number; ++ readonly indexInChunk: number; ++ readonly lineNumber: number; ++ readonly content: string; ++}; ++ ++type DebugHighlighterHandle = { ++ readonly engine: DebugHighlightEngine; ++ readonly tokenize: ( ++ code: string, ++ options: { readonly lang: string; readonly theme: string }, ++ ) => ReadonlyArray>; ++}; ++ ++const DEBUG_LINE_COUNT = 10_000; ++const DEBUG_CHUNK_SIZE = 500; ++const DEBUG_LINE_HEIGHT = 24; ++const DEBUG_GUTTER_WIDTH = 58; ++const DEBUG_CONTENT_WIDTH = 3_200; ++const DEBUG_MONO_FONT_FAMILY = "BerkeleyMono-Regular"; ++const DEBUG_THEME_NAME_BY_SCHEME = { ++ dark: "github-dark-default", ++ light: "github-light-default", ++} as const; ++ ++let nativeHighlighterPromise: Promise | null = null; ++let javascriptHighlighterPromise: Promise | null = null; ++ ++function waitForNextFrame(): Promise { ++ return new Promise((resolve) => setTimeout(resolve, 0)); ++} ++ ++function normalizeTokens( ++ tokenLines: ReadonlyArray>, ++): ReadonlyArray> { ++ return tokenLines.map((line) => ++ line.map((token) => ({ ++ content: token.content, ++ color: token.color ?? null, ++ fontStyle: token.fontStyle ?? null, ++ })), ++ ); ++} ++ ++function makeDebugCodeLine(index: number): string { ++ const label = `generatedLine${String(index).padStart(5, "0")}`; ++ switch (index % 8) { ++ case 0: ++ return `export async function ${label}(input: { value: number; name: string }) {`; ++ case 1: ++ return ` const normalized = input.name.trim().toLowerCase();`; ++ case 2: ++ return ` const result = await Promise.resolve({ id: "${label}", score: input.value * ${index + 1} });`; ++ case 3: ++ return ` if (result.score > ${index * 17}) return normalized + ":" + result.id;`; ++ case 4: ++ return ` return [normalized, String(result.score), "${"x".repeat((index % 24) + 8)}"].join("/");`; ++ case 5: ++ return `}`; ++ case 6: ++ return `type ${label}Record = Readonly<{ id: string; createdAt: Date; tags: string[] }>;`; ++ default: ++ return `const ${label}: ${label}Record = { id: "${label}", createdAt: new Date(), tags: ["debug", "highlight"] };`; ++ } ++} ++ ++function makeDebugLines(): ReadonlyArray { ++ return Array.from({ length: DEBUG_LINE_COUNT }, (_, index) => ({ ++ id: `line:${index + 1}`, ++ chunkIndex: Math.floor(index / DEBUG_CHUNK_SIZE), ++ indexInChunk: index % DEBUG_CHUNK_SIZE, ++ lineNumber: index + 1, ++ content: makeDebugCodeLine(index + 1), ++ })); ++} ++ ++async function createNativeDebugHighlighter(): Promise { ++ const nativeEngineModule = await import("react-native-shiki-engine"); ++ if (!nativeEngineModule.isNativeEngineAvailable()) { ++ throw new Error("Native Shiki engine is not available in this build."); ++ } ++ ++ const highlighter = await createHighlighterCore({ ++ langs: [typescriptLanguage], ++ themes: [githubLightDefault, githubDarkDefault], ++ engine: nativeEngineModule.createNativeEngine(), ++ }); ++ ++ return { ++ engine: "native", ++ tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)), ++ }; ++} ++ ++async function createJavascriptDebugHighlighter(): Promise { ++ const highlighter: HighlighterCore = await createHighlighterCore({ ++ langs: [typescriptLanguage], ++ themes: [githubLightDefault, githubDarkDefault], ++ engine: createJavaScriptRegexEngine(), ++ }); ++ ++ return { ++ engine: "javascript", ++ tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)), ++ }; ++} ++ ++async function getDebugHighlighter(engine: DebugHighlightEngine): Promise { ++ if (engine === "native") { ++ nativeHighlighterPromise ??= createNativeDebugHighlighter(); ++ return nativeHighlighterPromise; ++ } ++ ++ javascriptHighlighterPromise ??= createJavascriptDebugHighlighter(); ++ return javascriptHighlighterPromise; ++} ++ ++const TokenText = memo(function TokenText(props: { ++ readonly content: string; ++ readonly tokens: ReadonlyArray | null; ++}) { ++ if (!props.tokens) { ++ return ( ++ ++ {props.content} ++ ++ ); ++ } ++ ++ let tokenOffset = 0; ++ ++ return ( ++ ++ {props.tokens.map((token) => { ++ const tokenKey = `${tokenOffset}:${token.content.length}:${token.color ?? ""}:${token.fontStyle ?? ""}`; ++ tokenOffset += token.content.length; ++ const fontWeight = ++ token.fontStyle !== null && (token.fontStyle & 2) === 2 ++ ? ("700" as const) ++ : ("500" as const); ++ const fontStyle = ++ token.fontStyle !== null && (token.fontStyle & 1) === 1 ++ ? ("italic" as const) ++ : ("normal" as const); ++ ++ return ( ++ ++ {token.content} ++ ++ ); ++ })} ++ ++ ); ++}); ++ ++const DebugCodeLineRow = memo(function DebugCodeLineRow(props: { ++ readonly item: DebugLine; ++ readonly tokens: ReadonlyArray | null; ++ readonly width: number; ++}) { ++ return ( ++ ++ ++ {props.item.lineNumber} ++ ++ ++ ++ ++ ++ ); ++}); ++ ++function EngineToggle(props: { ++ readonly engine: DebugHighlightEngine; ++ readonly onChangeEngine: (engine: DebugHighlightEngine) => void; ++}) { ++ return ( ++ ++ {(["native", "javascript"] as const).map((engine) => { ++ const selected = props.engine === engine; ++ return ( ++ props.onChangeEngine(engine)} ++ > ++ ++ {engine === "javascript" ? "JS" : "Native"} ++ ++ ++ ); ++ })} ++ ++ ); ++} ++ ++export default function SyntaxHighlightDebugRoute() { ++ const insets = useSafeAreaInsets(); ++ const { width } = useWindowDimensions(); ++ const colorScheme = useColorScheme(); ++ const headerIcon = String(useThemeColor("--color-icon")); ++ const themeName = DEBUG_THEME_NAME_BY_SCHEME[colorScheme === "dark" ? "dark" : "light"]; ++ const [engine, setEngine] = useState("native"); ++ const [tokensByChunkIndex, setTokensByChunkIndex] = useState< ++ Record>> ++ >({}); ++ const [status, setStatus] = useState("Idle"); ++ const renderStartRef = useRef(null); ++ const generationRef = useRef(0); ++ const lines = useMemo(() => makeDebugLines(), []); ++ ++ useEffect(() => { ++ const generation = generationRef.current + 1; ++ generationRef.current = generation; ++ renderStartRef.current = performance.now(); ++ setTokensByChunkIndex({}); ++ setStatus("Initializing highlighter"); ++ ++ void (async () => { ++ try { ++ const highlighterStartedAt = performance.now(); ++ const highlighter = await getDebugHighlighter(engine); ++ if (generation !== generationRef.current) { ++ return; ++ } ++ ++ console.log("[debug-syntax-scratch] initialize", { ++ durationMs: Math.round(performance.now() - highlighterStartedAt), ++ engine: highlighter.engine, ++ }); ++ ++ let firstChunkMs: number | null = null; ++ const totalStartedAt = performance.now(); ++ setStatus(`Streaming ${DEBUG_LINE_COUNT.toLocaleString()} lines`); ++ ++ for (let startIndex = 0; startIndex < lines.length; startIndex += DEBUG_CHUNK_SIZE) { ++ if (generation !== generationRef.current) { ++ return; ++ } ++ ++ const chunkLines = lines.slice(startIndex, startIndex + DEBUG_CHUNK_SIZE); ++ const chunkCode = chunkLines.map((line) => line.content).join("\n"); ++ const chunkStartedAt = performance.now(); ++ const chunkTokens = highlighter.tokenize(chunkCode, { ++ lang: "typescript", ++ theme: themeName, ++ }); ++ const chunkMs = performance.now() - chunkStartedAt; ++ ++ if (firstChunkMs === null) { ++ firstChunkMs = performance.now() - totalStartedAt; ++ console.log("[debug-syntax-scratch] first chunk", { ++ chunkSize: DEBUG_CHUNK_SIZE, ++ durationMs: Math.round(firstChunkMs), ++ engine, ++ lineCount: chunkTokens.length, ++ }); ++ } ++ ++ setTokensByChunkIndex((current) => ({ ++ ...current, ++ [startIndex / DEBUG_CHUNK_SIZE]: chunkTokens, ++ })); ++ setStatus( ++ `Streamed ${Math.min(startIndex + DEBUG_CHUNK_SIZE, lines.length).toLocaleString()} / ${lines.length.toLocaleString()} lines`, ++ ); ++ ++ console.log("[debug-syntax-scratch] chunk", { ++ chunkIndex: startIndex / DEBUG_CHUNK_SIZE, ++ chunkMs: Math.round(chunkMs), ++ engine, ++ lineCount: chunkTokens.length, ++ }); ++ ++ await waitForNextFrame(); ++ } ++ ++ console.log("[debug-syntax-scratch] complete", { ++ durationMs: Math.round(performance.now() - totalStartedAt), ++ engine, ++ lineCount: lines.length, ++ }); ++ setStatus(`Complete with ${engine}`); ++ } catch (error) { ++ console.error("[debug-syntax-scratch] failed", { ++ engine, ++ message: error instanceof Error ? error.message : String(error), ++ }); ++ setStatus(error instanceof Error ? error.message : "Highlight failed"); ++ } ++ })(); ++ }, [engine, lines, themeName]); ++ ++ useEffect(() => { ++ if (renderStartRef.current === null) { ++ return; ++ } ++ ++ const startedAt = renderStartRef.current; ++ renderStartRef.current = null; ++ const commitMs = performance.now() - startedAt; ++ requestAnimationFrame(() => { ++ console.log("[debug-syntax-scratch] render", { ++ commitMs: Math.round(commitMs), ++ paintMs: Math.round(performance.now() - startedAt), ++ }); ++ }); ++ }); ++ ++ const renderItem = useCallback( ++ ({ item }: ListRenderItemInfo) => ( ++ ++ ), ++ [tokensByChunkIndex, width], ++ ); ++ ++ return ( ++ ++ ++ ++ ++ ++ ++ ++ Shiki streaming baseline ++ ++ ++ {status} ++ ++ ++ ++ ++ ++ ++ item.id} ++ getItemLayout={(_, index) => ({ ++ length: DEBUG_LINE_HEIGHT, ++ offset: DEBUG_LINE_HEIGHT * index, ++ index, ++ })} ++ initialNumToRender={40} ++ maxToRenderPerBatch={80} ++ updateCellsBatchingPeriod={16} ++ windowSize={9} ++ removeClippedSubviews ++ keyboardShouldPersistTaps="handled" ++ contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }} ++ /> ++ ++ ); ++} +diff --git a/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx +new file mode 100644 +index 000000000..095201929 +--- /dev/null ++++ b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx +@@ -0,0 +1,110 @@ ++import { createContext, type ReactNode, useContext, useEffect, useMemo, useState } from "react"; ++ ++import { ++ getActiveReviewHighlighterEngine, ++ prepareReviewHighlighter, ++ prepareReviewHighlighterLanguages, ++ type ReviewHighlighterEngine, ++} from "./shikiReviewHighlighter"; ++ ++type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error"; ++ ++interface ReviewHighlighterContextValue { ++ readonly engine: ReviewHighlighterEngine | null; ++ readonly error: string | null; ++ readonly status: ReviewHighlighterStatus; ++} ++ ++const ReviewHighlighterContext = createContext({ ++ engine: null, ++ error: null, ++ status: "idle", ++}); ++ ++const REVIEW_INITIAL_LANGUAGES = [ ++ "typescript", ++ "tsx", ++ "javascript", ++ "jsx", ++ "json", ++ "yaml", ++ "bash", ++] as const; ++ ++function isReviewHighlighterProviderDebugLoggingEnabled(): boolean { ++ return typeof __DEV__ !== "undefined" ? __DEV__ : false; ++} ++ ++function logReviewHighlighterProviderDiagnostic( ++ message: string, ++ details?: Record, ++): void { ++ if (!isReviewHighlighterProviderDebugLoggingEnabled()) { ++ return; ++ } ++ ++ if (details) { ++ console.log(`[review-highlighter-provider] ${message}`, details); ++ return; ++ } ++ ++ console.log(`[review-highlighter-provider] ${message}`); ++} ++ ++export function ReviewHighlighterProvider(props: { readonly children: ReactNode }) { ++ const [value, setValue] = useState({ ++ engine: null, ++ error: null, ++ status: "idle", ++ }); ++ ++ useEffect(() => { ++ let cancelled = false; ++ ++ setValue({ engine: null, error: null, status: "initializing" }); ++ ++ void (async () => { ++ const startedAt = performance.now(); ++ try { ++ await prepareReviewHighlighter(); ++ await prepareReviewHighlighterLanguages(REVIEW_INITIAL_LANGUAGES); ++ const engine = await getActiveReviewHighlighterEngine(); ++ ++ if (cancelled) { ++ return; ++ } ++ ++ const durationMs = Math.round(performance.now() - startedAt); ++ logReviewHighlighterProviderDiagnostic("initialized", { ++ durationMs, ++ engine, ++ }); ++ setValue({ engine, error: null, status: "ready" }); ++ } catch (error) { ++ if (cancelled) { ++ return; ++ } ++ ++ const message = error instanceof Error ? error.message : String(error); ++ logReviewHighlighterProviderDiagnostic("initialization failed", { error: message }); ++ setValue({ engine: null, error: message, status: "error" }); ++ } ++ })(); ++ ++ return () => { ++ cancelled = true; ++ }; ++ }, []); ++ ++ const contextValue = useMemo(() => value, [value]); ++ ++ return ( ++ ++ {props.children} ++ ++ ); ++} ++ ++export function useReviewHighlighterStatus(): ReviewHighlighterContextValue { ++ return useContext(ReviewHighlighterContext); ++} +diff --git a/apps/mobile/src/features/review/reviewPerf.ts b/apps/mobile/src/features/review/reviewPerf.ts +new file mode 100644 +index 000000000..2ae1095b1 +--- /dev/null ++++ b/apps/mobile/src/features/review/reviewPerf.ts +@@ -0,0 +1,83 @@ ++interface ReviewPerformanceLike { ++ readonly now?: () => number; ++ readonly mark?: (name: string) => void; ++ readonly measure?: (name: string, startMark: string, endMark: string) => void; ++ readonly clearMarks?: (name?: string) => void; ++ readonly clearMeasures?: (name?: string) => void; ++} ++ ++const REVIEW_PERF_PREFIX = "t3.review"; ++let reviewPerfSequence = 0; ++ ++function getPerformance(): ReviewPerformanceLike | null { ++ const candidate = (globalThis as { readonly performance?: ReviewPerformanceLike }).performance; ++ return candidate ?? null; ++} ++ ++export function isReviewPerfEnabled(): boolean { ++ return typeof __DEV__ !== "undefined" ? __DEV__ : false; ++} ++ ++export function measureReviewWork(name: string, callback: () => T): T { ++ if (!isReviewPerfEnabled()) { ++ return callback(); ++ } ++ ++ const perf = getPerformance(); ++ const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`; ++ const startMark = `${marker}.start`; ++ const endMark = `${marker}.end`; ++ const startedAt = perf?.now?.() ?? Date.now(); ++ ++ perf?.mark?.(startMark); ++ try { ++ return callback(); ++ } finally { ++ const durationMs = (perf?.now?.() ?? Date.now()) - startedAt; ++ perf?.mark?.(endMark); ++ perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark); ++ perf?.clearMarks?.(startMark); ++ perf?.clearMarks?.(endMark); ++ console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) }); ++ } ++} ++ ++export async function measureReviewAsyncWork( ++ name: string, ++ callback: () => Promise, ++): Promise { ++ if (!isReviewPerfEnabled()) { ++ return callback(); ++ } ++ ++ const perf = getPerformance(); ++ const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`; ++ const startMark = `${marker}.start`; ++ const endMark = `${marker}.end`; ++ const startedAt = perf?.now?.() ?? Date.now(); ++ ++ perf?.mark?.(startMark); ++ try { ++ return await callback(); ++ } finally { ++ const durationMs = (perf?.now?.() ?? Date.now()) - startedAt; ++ perf?.mark?.(endMark); ++ perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark); ++ perf?.clearMarks?.(startMark); ++ perf?.clearMarks?.(endMark); ++ console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) }); ++ } ++} ++ ++export function markReviewEvent(name: string, details?: Record): void { ++ if (!isReviewPerfEnabled()) { ++ return; ++ } ++ ++ getPerformance()?.mark?.(`${REVIEW_PERF_PREFIX}.${name}`); ++ if (details) { ++ console.log(`[review-perf] ${name}`, details); ++ return; ++ } ++ console.log(`[review-perf] ${name}`); ++} diff --git a/apps/mobile/src/features/debug/fixtures/review-medium.diff b/apps/mobile/src/features/debug/fixtures/review-medium.diff new file mode 100644 index 0000000000..9618d97f2c --- /dev/null +++ b/apps/mobile/src/features/debug/fixtures/review-medium.diff @@ -0,0 +1,1955 @@ +diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx +index 84c48c6ed..ee993ee7c 100644 +--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx ++++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx +@@ -1,5 +1,10 @@ ++import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider"; + import { ReviewSheet } from "../../../../features/review/ReviewSheet"; + + export default function ReviewRoute() { +- return ; ++ return ( ++ ++ ++ ++ ); + } +diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx +index 82c28e81e..e148a8da2 100644 +--- a/apps/mobile/src/features/review/ReviewSheet.tsx ++++ b/apps/mobile/src/features/review/ReviewSheet.tsx +@@ -1,17 +1,31 @@ + import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts"; ++import { Gesture, GestureDetector } from "react-native-gesture-handler"; ++import Animated, { ++ makeMutable, ++ type SharedValue, ++ useAnimatedStyle, ++ useSharedValue, ++} from "react-native-reanimated"; + import { useLocalSearchParams, useRouter } from "expo-router"; + import Stack from "expo-router/stack"; + import { SymbolView } from "expo-symbols"; +-import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react"; ++import { ++ memo, ++ type ReactElement, ++ useCallback, ++ useDeferredValue, ++ useEffect, ++ useMemo, ++ useRef, ++ useState, ++} from "react"; + import { + ActivityIndicator, + FlatList, +- InteractionManager, + type ListRenderItemInfo, + Pressable, + ScrollView, + Text as NativeText, +- type ViewToken, + useColorScheme, + useWindowDimensions, + View, +@@ -32,6 +46,7 @@ import { + setReviewTurnDiff, + updateReviewExpandedFileIds, + updateReviewRevealedLargeFileIds, ++ updateReviewViewedFileIds, + useReviewCacheForThread, + } from "./reviewState"; + import { +@@ -45,11 +60,12 @@ import { + type ReviewParsedDiff, + type ReviewRenderableFile, + type ReviewRenderableLineRow, ++ type ReviewRenderableRow, + } from "./reviewModel"; + import { + clearReviewHighlightFileCache, + getCachedHighlightedReviewFile, +- highlightReviewFile, ++ streamHighlightReviewFile, + type ReviewDiffTheme, + type ReviewHighlightedFile, + type ReviewHighlightedToken, +@@ -67,9 +83,12 @@ import { + import { + changeTone, + DiffTokenText, ++ REVIEW_DIFF_LINE_HEIGHT, + REVIEW_MONO_FONT_FAMILY, + ReviewChangeBar, + } from "./reviewDiffRendering"; ++import { markReviewEvent, measureReviewWork } from "./reviewPerf"; ++import { useReviewHighlighterStatus } from "./ReviewHighlighterProvider"; + + interface PendingCommentSelection { + readonly sectionTitle: string; +@@ -87,14 +106,21 @@ interface ReviewLineActionInput { + + const IOS_NAV_BAR_HEIGHT = 44; + const REVIEW_HEADER_SPACING = 0; +-const REVIEW_LINE_GUTTER_WIDTH = 62; ++const REVIEW_CHANGE_BAR_WIDTH = 5; ++const REVIEW_MIN_LINE_NUMBER_WIDTH = 27; ++const REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE = 8; ++const REVIEW_LINE_NUMBER_HORIZONTAL_PADDING = 6; + const REVIEW_CHARACTER_WIDTH_ESTIMATE = 8.4; + const REVIEW_MAX_CONTENT_WIDTH = 4_800; +-const REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT = 2; +-const REVIEW_HIGHLIGHT_BACKTRACK_COUNT = 0; +-const REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT = 1; ++const REVIEW_HUNK_ROW_HEIGHT = 35; ++const REVIEW_FILE_HEADER_HEIGHT = 43; ++const REVIEW_SUPPRESSED_ROW_HEIGHT = 92; + const loggedMissingReviewTokenKeys = new Set(); + ++function waitForReviewDelay(durationMs: number): Promise { ++ return new Promise((resolve) => setTimeout(resolve, durationMs)); ++} ++ + function isReviewDiffDebugLoggingEnabled(): boolean { + return typeof __DEV__ !== "undefined" ? __DEV__ : false; + } +@@ -113,33 +139,27 @@ function logReviewDiffDiagnostic(message: string, details?: Record, ++function computeReviewFileContentWidth( ++ rows: ReadonlyArray, + viewportWidth: number, ++ gutterWidth: number, + ): number { + let maxTextLength = 0; + +- items.forEach((item) => { +- switch (item.kind) { +- case "file-header": +- maxTextLength = Math.max( +- maxTextLength, +- item.file.path.length, +- item.file.previousPath?.length ?? 0, +- ); +- break; +- case "file-suppressed": +- maxTextLength = Math.max(maxTextLength, item.message.length, item.actionLabel?.length ?? 0); +- break; +- case "hunk": +- maxTextLength = Math.max( +- maxTextLength, +- item.row.header.length + (item.row.context ? item.row.context.length + 1 : 0), +- ); +- break; +- case "line": +- maxTextLength = Math.max(maxTextLength, item.row.content.length); +- break; ++ rows.forEach((row) => { ++ if (row.kind === "hunk") { ++ maxTextLength = Math.max( ++ maxTextLength, ++ row.header.length + (row.context ? row.context.length + 1 : 0), ++ ); ++ return; + } ++ ++ maxTextLength = Math.max(maxTextLength, row.content.length); + }); + + return Math.max( +- viewportWidth, ++ Math.max(0, viewportWidth - gutterWidth), + Math.min( + REVIEW_MAX_CONTENT_WIDTH, +- Math.ceil(REVIEW_LINE_GUTTER_WIDTH + 48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE), ++ Math.ceil(48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE), + ), + ); + } + ++function computeReviewFileGutterWidth(rows: ReadonlyArray): number { ++ let maxLineNumber = 0; ++ ++ rows.forEach((row) => { ++ if (row.kind !== "line") { ++ return; ++ } ++ ++ maxLineNumber = Math.max(maxLineNumber, row.oldLineNumber ?? 0, row.newLineNumber ?? 0); ++ }); ++ ++ const digitCount = Math.max(1, String(maxLineNumber).length); ++ const lineNumberWidth = Math.max( ++ REVIEW_MIN_LINE_NUMBER_WIDTH, ++ digitCount * REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE + REVIEW_LINE_NUMBER_HORIZONTAL_PADDING, ++ ); ++ ++ return REVIEW_CHANGE_BAR_WIDTH + lineNumberWidth; ++} ++ + function getDefaultExpandedFileIds( + files: ReadonlyArray, + ): ReadonlyArray { + return files.map((file) => file.id); + } + ++function getValidReviewExpandedFileIds( ++ files: ReadonlyArray, ++ cachedExpandedFileIds: ReadonlyArray | undefined, ++): ReadonlyArray { ++ if (cachedExpandedFileIds === undefined) { ++ return getDefaultExpandedFileIds(files); ++ } ++ ++ const fileIdSet = new Set(files.map((file) => file.id)); ++ return cachedExpandedFileIds.filter((id) => fileIdSet.has(id)); ++} ++ + function getHighlightedTokensForLine( + line: ReviewRenderableLineRow, + highlightedFile: ReviewHighlightedFile | null, +@@ -252,16 +293,13 @@ const ReviewLineRow = memo(function ReviewLineRow(props: { + delayLongPress={220} + onLongPress={props.onStartRangeSelection} + onPress={props.onComment} +- style={{ minWidth: props.viewportWidth }} ++ style={{ ++ height: REVIEW_DIFF_LINE_HEIGHT, ++ width: props.viewportWidth, ++ overflow: "hidden", ++ }} + > +- +- +- {lineNumber ?? ""} +- +- ++ + ++ ++ ++ {props.lineNumber ?? ""} ++ ++ ++ ); ++}); ++ ++const ReviewHunkGutter = memo(function ReviewHunkGutter(props: { readonly gutterWidth: number }) { ++ return ( ++ ++ ); ++}); ++ + const ReviewFileCard = memo(function ReviewFileCard(props: { + readonly file: ReviewRenderableFile; + readonly fileId: string; + readonly expanded: boolean; ++ readonly viewed: boolean; + readonly viewportWidth: number; + readonly onToggleFile: (fileId: string) => void; ++ readonly onToggleViewed: (fileId: string) => void; + }) { +- const chrome = getFileHeaderChrome(props.file.changeType); ++ const { expanded, file, fileId, onToggleFile, onToggleViewed, viewed, viewportWidth } = props; ++ const chrome = getFileHeaderChrome(file.changeType); ++ const iconColor = String(useThemeColor("--color-icon-muted")); ++ const handleToggleFile = useCallback(() => { ++ onToggleFile(fileId); ++ }, [fileId, onToggleFile]); ++ const handleToggleViewed = useCallback(() => { ++ onToggleViewed(fileId); ++ }, [fileId, onToggleViewed]); + + return ( + +- props.onToggleFile(props.fileId)}> +- +- +- +- +- +- +- +- +- +- {props.file.path} ++ ++ ++ ++ ++ ++ ++ ++ ++ {file.path} ++ ++ {file.previousPath && file.previousPath !== file.path ? ( ++ ++ {file.previousPath} + +- {props.file.previousPath && props.file.previousPath !== props.file.path ? ( +- +- {props.file.previousPath} +- ++ ) : null} ++ ++ ++ ++ ++ -{file.deletions} ++ ++ ++ +{file.additions} ++ ++ ++ ++ {viewed ? ( ++ + ) : null} + +- +- +- +- +{props.file.additions} +- +- +- -{props.file.deletions} ++ ++ Viewed + +- ++ + +- ++ + + ); + }); +@@ -342,7 +453,11 @@ const ReviewFileSuppressedBody = memo(function ReviewFileSuppressedBody(props: { + return ( + + {props.message} + {props.actionLabel && props.onLoadDiffFile ? ( +@@ -364,10 +479,13 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: { + }) { + return ( + +- ++ + {props.header} + {props.context ? ` ${props.context}` : ""} + +@@ -375,6 +493,61 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: { + ); + }); + ++const ReviewCodePanRow = memo(function ReviewCodePanRow(props: { ++ readonly contentWidth: number; ++ readonly horizontalOffset: SharedValue; ++ readonly gutterWidth?: number; ++ readonly viewportWidth: number; ++ readonly leftGutter?: ReactElement; ++ readonly children: ReactElement; ++}) { ++ const { ++ children, ++ contentWidth, ++ gutterWidth = 0, ++ horizontalOffset, ++ leftGutter, ++ viewportWidth, ++ } = props; ++ const dragStartOffset = useSharedValue(0); ++ const visibleContentWidth = leftGutter ? viewportWidth - gutterWidth : viewportWidth; ++ const maxOffset = Math.max(0, contentWidth - visibleContentWidth); ++ ++ const panGesture = useMemo( ++ () => ++ Gesture.Pan() ++ .activeOffsetX([-8, 8]) ++ .failOffsetY([-10, 10]) ++ .onBegin(() => { ++ dragStartOffset.value = horizontalOffset.value; ++ }) ++ .onUpdate((event) => { ++ "worklet"; ++ const nextOffset = dragStartOffset.value - event.translationX; ++ horizontalOffset.value = Math.min(maxOffset, Math.max(0, nextOffset)); ++ }), ++ [dragStartOffset, horizontalOffset, maxOffset], ++ ); ++ ++ const contentStyle = useAnimatedStyle( ++ () => ({ ++ transform: [{ translateX: -horizontalOffset.value }], ++ }), ++ [horizontalOffset], ++ ); ++ ++ return ( ++ ++ ++ {leftGutter ?? null} ++ ++ {children} ++ ++ ++ ++ ); ++}); ++ + const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) { + return ( + +@@ -454,15 +627,19 @@ export function ReviewSheet() { + const [highlightedFilesById, setHighlightedFilesById] = useState< + Record + >({}); +- const [visibleFileIds, setVisibleFileIds] = useState>([]); ++ const deferredHighlightedFilesById = useDeferredValue(highlightedFilesById); ++ const [localExpandedFileIdsBySection, setLocalExpandedFileIdsBySection] = useState< ++ Record> ++ >({}); ++ const [localViewedFileIdsBySection, setLocalViewedFileIdsBySection] = useState< ++ Record> ++ >({}); + const activeCommentTarget = useReviewCommentTarget(); + const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme; +- const highlightQueueRef = useRef([]); +- const highlightRequestedFileIdsRef = useRef>(new Set()); +- const highlightQueueGenerationRef = useRef(0); +- const highlightQueueActiveRef = useRef(false); +- const highlightableFilesByIdRef = useRef>(new Map()); +- const selectedThemeRef = useRef(selectedTheme); ++ const reviewHighlighter = useReviewHighlighterStatus(); ++ const highlightRunIdRef = useRef(0); ++ const highlightableFilesRef = useRef>([]); ++ const horizontalOffsetByFileIdRef = useRef>>(new Map()); + const { selectedThreadCwd } = useSelectedThreadWorktree(); + + const cwd = selectedThreadCwd; +@@ -498,11 +675,13 @@ export function ReviewSheet() { + const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT; + const parsedDiff = useMemo( + () => +- getCachedReviewParsedDiff({ +- threadKey: reviewCache.threadKey, +- sectionId: selectedSection?.id ?? null, +- diff: selectedSection?.diff, +- }), ++ measureReviewWork("parse-diff", () => ++ getCachedReviewParsedDiff({ ++ threadKey: reviewCache.threadKey, ++ sectionId: selectedSection?.id ?? null, ++ diff: selectedSection?.diff, ++ }), ++ ), + [reviewCache.threadKey, selectedSection?.diff, selectedSection?.id], + ); + const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]); +@@ -510,14 +689,53 @@ export function ReviewSheet() { + () => countReviewCommentContexts(draftMessage), + [draftMessage], + ); ++ const viewportWidth = Math.max(width, 280); ++ ++ useEffect(() => { ++ if (!selectedSection?.id || parsedDiff.kind !== "files") { ++ return; ++ } ++ ++ setLocalExpandedFileIdsBySection((current) => { ++ if (current[selectedSection.id] !== undefined) { ++ return current; ++ } ++ ++ return { ++ ...current, ++ [selectedSection.id]: getValidReviewExpandedFileIds( ++ parsedDiff.files, ++ reviewCache.expandedFileIdsBySection[selectedSection.id], ++ ), ++ }; ++ }); ++ ++ setLocalViewedFileIdsBySection((current) => { ++ if (current[selectedSection.id] !== undefined) { ++ return current; ++ } ++ ++ return { ++ ...current, ++ [selectedSection.id]: reviewCache.viewedFileIdsBySection[selectedSection.id] ?? [], ++ }; ++ }); ++ }, [ ++ parsedDiff, ++ reviewCache.expandedFileIdsBySection, ++ reviewCache.viewedFileIdsBySection, ++ selectedSection?.id, ++ ]); + + const expandedFileIds = useMemo( + () => + selectedSection?.id && parsedDiff.kind === "files" +- ? (reviewCache.expandedFileIdsBySection[selectedSection.id] ?? +- getDefaultExpandedFileIds(parsedDiff.files)) ++ ? getValidReviewExpandedFileIds( ++ parsedDiff.files, ++ localExpandedFileIdsBySection[selectedSection.id], ++ ) + : [], +- [parsedDiff, reviewCache.expandedFileIdsBySection, selectedSection?.id], ++ [localExpandedFileIdsBySection, parsedDiff, selectedSection?.id], + ); + const revealedLargeFileIds = useMemo( + () => +@@ -526,47 +744,96 @@ export function ReviewSheet() { + : [], + [reviewCache.revealedLargeFileIdsBySection, selectedSection?.id], + ); ++ const viewedFileIds = useMemo( ++ () => (selectedSection?.id ? (localViewedFileIdsBySection[selectedSection.id] ?? []) : []), ++ [localViewedFileIdsBySection, selectedSection?.id], ++ ); ++ const viewedFileIdSet = useMemo(() => new Set(viewedFileIds), [viewedFileIds]); + const reviewListItems = useMemo( + () => + selectedSection && parsedDiff.kind === "files" +- ? buildReviewListItems({ +- files: parsedDiff.files, +- expandedFileIds, +- revealedLargeFileIds, +- }) ++ ? measureReviewWork("build-list-items", () => ++ buildReviewListItems({ ++ files: parsedDiff.files, ++ expandedFileIds, ++ revealedLargeFileIds, ++ }), ++ ) + : [], + [expandedFileIds, parsedDiff, revealedLargeFileIds, selectedSection], + ); +- const reviewFileById = useMemo(() => { ++ const reviewLineRowsByFileId = useMemo(() => { + if (parsedDiff.kind !== "files") { +- return new Map(); ++ return new Map>(); + } + +- return new Map(parsedDiff.files.map((file) => [file.id, file] as const)); ++ return measureReviewWork( ++ "index-line-rows", ++ () => ++ new Map( ++ parsedDiff.files.map((file) => [ ++ file.id, ++ file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"), ++ ]), ++ ), ++ ); + }, [parsedDiff]); +- const reviewLineRowsByFileId = useMemo(() => { ++ const reviewContentWidthByFileId = useMemo(() => { + if (parsedDiff.kind !== "files") { +- return new Map>(); ++ return new Map(); ++ } ++ ++ return measureReviewWork( ++ "measure-file-widths", ++ () => ++ new Map( ++ parsedDiff.files.map((file) => [ ++ file.id, ++ computeReviewFileContentWidth( ++ file.rows, ++ viewportWidth, ++ computeReviewFileGutterWidth(file.rows), ++ ), ++ ]), ++ ), ++ ); ++ }, [parsedDiff, viewportWidth]); ++ const reviewGutterWidthByFileId = useMemo(() => { ++ if (parsedDiff.kind !== "files") { ++ return new Map(); + } + + return new Map( +- parsedDiff.files.map((file) => [ +- file.id, +- file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"), +- ]), ++ parsedDiff.files.map((file) => [file.id, computeReviewFileGutterWidth(file.rows)]), + ); + }, [parsedDiff]); +- const reviewLineIndexByRowId = useMemo(() => { +- const map = new Map(); ++ const getReviewFileHorizontalOffset = useCallback((fileId: string) => { ++ let offset = horizontalOffsetByFileIdRef.current.get(fileId); ++ if (!offset) { ++ offset = makeMutable(0); ++ horizontalOffsetByFileIdRef.current.set(fileId, offset); ++ } + +- reviewLineRowsByFileId.forEach((rows) => { +- rows.forEach((row, index) => { +- map.set(row.id, index); +- }); +- }); ++ return offset; ++ }, []); ++ useEffect(() => { ++ const knownFileIds = ++ parsedDiff.kind === "files" ? new Set(parsedDiff.files.map((file) => file.id)) : new Set(); + +- return map; +- }, [reviewLineRowsByFileId]); ++ horizontalOffsetByFileIdRef.current.forEach((offset, fileId) => { ++ if (!knownFileIds.has(fileId)) { ++ horizontalOffsetByFileIdRef.current.delete(fileId); ++ return; ++ } ++ ++ const contentWidth = reviewContentWidthByFileId.get(fileId) ?? viewportWidth; ++ const gutterWidth = reviewGutterWidthByFileId.get(fileId) ?? 0; ++ offset.value = Math.min( ++ offset.value, ++ Math.max(0, contentWidth - (viewportWidth - gutterWidth)), ++ ); ++ }); ++ }, [parsedDiff, reviewContentWidthByFileId, reviewGutterWidthByFileId, viewportWidth]); + const highlightableFiles = useMemo(() => { + if (parsedDiff.kind !== "files") { + return [] as ReadonlyArray; +@@ -587,59 +854,13 @@ export function ReviewSheet() { + ); + }); + }, [expandedFileIds, parsedDiff, revealedLargeFileIds]); +- const highlightableFileIds = useMemo( +- () => new Set(highlightableFiles.map((file) => file.id)), ++ const highlightableFilesKey = useMemo( ++ () => highlightableFiles.map((file) => `${file.id}:${file.cacheKey}`).join("\n"), + [highlightableFiles], + ); +- const priorityHighlightFileIds = useMemo(() => { +- if (parsedDiff.kind !== "files" || highlightableFiles.length === 0) { +- return [] as ReadonlyArray; +- } +- +- const fileIdsInPriorityOrder = +- visibleFileIds.length > 0 +- ? visibleFileIds.filter((fileId) => highlightableFileIds.has(fileId)) +- : parsedDiff.files +- .slice(0, REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT) +- .map((file) => file.id) +- .filter((fileId) => highlightableFileIds.has(fileId)); +- +- if (fileIdsInPriorityOrder.length === 0) { +- return [] as ReadonlyArray; +- } +- +- const firstVisibleIndex = parsedDiff.files.findIndex( +- (file) => file.id === fileIdsInPriorityOrder[0], +- ); +- const lastVisibleIndex = parsedDiff.files.findIndex( +- (file) => file.id === fileIdsInPriorityOrder[fileIdsInPriorityOrder.length - 1], +- ); +- +- if (firstVisibleIndex < 0 || lastVisibleIndex < 0) { +- return fileIdsInPriorityOrder; +- } +- +- const startIndex = Math.max(0, firstVisibleIndex - REVIEW_HIGHLIGHT_BACKTRACK_COUNT); +- const endIndex = Math.min( +- parsedDiff.files.length - 1, +- lastVisibleIndex + REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT, +- ); +- +- const queuedIds: string[] = []; +- for (let index = startIndex; index <= endIndex; index += 1) { +- const fileId = parsedDiff.files[index]?.id; +- if (fileId && highlightableFileIds.has(fileId)) { +- queuedIds.push(fileId); +- } +- } +- +- return queuedIds; +- }, [highlightableFileIds, highlightableFiles.length, parsedDiff, visibleFileIds]); +- const viewportWidth = Math.max(width, 280); +- const reviewListContentWidth = useMemo( +- () => computeReviewListContentWidth(reviewListItems, viewportWidth), +- [reviewListItems, viewportWidth], +- ); ++ useEffect(() => { ++ highlightableFilesRef.current = highlightableFiles; ++ }, [highlightableFiles]); + const loadGitDiffs = useCallback(async () => { + if (!cwd) { + return; +@@ -714,100 +935,6 @@ export function ReviewSheet() { + void loadGitDiffs(); + }, [loadGitDiffs]); + +- useEffect(() => { +- selectedThemeRef.current = selectedTheme; +- }, [selectedTheme]); +- +- useEffect(() => { +- highlightableFilesByIdRef.current = new Map(highlightableFiles.map((file) => [file.id, file])); +- }, [highlightableFiles]); +- +- const startHighlightQueueRunner = useCallback(function startHighlightQueueRunner() { +- if (highlightQueueActiveRef.current) { +- return; +- } +- +- const generation = highlightQueueGenerationRef.current; +- highlightQueueActiveRef.current = true; +- +- void (async () => { +- try { +- while (generation === highlightQueueGenerationRef.current) { +- const nextFileId = highlightQueueRef.current.shift(); +- if (!nextFileId) { +- break; +- } +- +- const file = highlightableFilesByIdRef.current.get(nextFileId); +- if (!file) { +- continue; +- } +- +- const theme = selectedThemeRef.current; +- const cached = getCachedHighlightedReviewFile(file, theme); +- if (cached) { +- logReviewDiffDiagnostic("using cached highlighted file", { +- fileId: file.id, +- filePath: file.path, +- theme, +- }); +- setHighlightedFilesById((current) => +- current[file.id] === cached ? current : { ...current, [file.id]: cached }, +- ); +- continue; +- } +- +- logReviewDiffDiagnostic("requesting highlighted file", { +- fileId: file.id, +- filePath: file.path, +- theme, +- }); +- +- try { +- await new Promise((resolve) => { +- InteractionManager.runAfterInteractions(() => resolve()); +- }); +- const result = await highlightReviewFile(file, theme); +- if (generation !== highlightQueueGenerationRef.current) { +- logReviewDiffDiagnostic("discarding highlighted file after cancellation", { +- fileId: file.id, +- filePath: file.path, +- }); +- return; +- } +- +- logReviewDiffDiagnostic("received highlighted file", { +- fileId: file.id, +- filePath: file.path, +- additionLines: result.additionLines.length, +- deletionLines: result.deletionLines.length, +- }); +- setHighlightedFilesById((current) => { +- if (current[file.id] === result) { +- return current; +- } +- return { ...current, [file.id]: result }; +- }); +- } catch (error) { +- logReviewDiffDiagnostic("highlight request failed", { +- fileId: file.id, +- filePath: file.path, +- error: error instanceof Error ? error.message : String(error), +- }); +- } +- } +- } finally { +- highlightQueueActiveRef.current = false; +- if ( +- generation === highlightQueueGenerationRef.current && +- highlightQueueRef.current.length > 0 +- ) { +- startHighlightQueueRunner(); +- } +- } +- })(); +- }, []); +- + useEffect(() => { + if (reviewSections.length === 0) { + return; +@@ -854,15 +981,15 @@ export function ReviewSheet() { + } + + updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => { +- if (existing !== undefined) { +- const validIds = existing.filter((id) => parsedDiff.files.some((file) => file.id === id)); +- if (validIds.length === existing.length) { +- return existing; +- } +- return validIds; ++ const validIds = getValidReviewExpandedFileIds(parsedDiff.files, existing); ++ if ( ++ existing !== undefined && ++ validIds.length === existing.length && ++ validIds.every((id, index) => id === existing[index]) ++ ) { ++ return existing; + } +- +- return getDefaultExpandedFileIds(parsedDiff.files); ++ return validIds; + }); + }, [parsedDiff, reviewCache.threadKey, selectedSection?.id]); + +@@ -887,11 +1014,7 @@ export function ReviewSheet() { + + useEffect(() => { + setHighlightedFilesById({}); +- setVisibleFileIds([]); +- highlightQueueGenerationRef.current += 1; +- highlightQueueRef.current = []; +- highlightRequestedFileIdsRef.current = new Set(); +- highlightQueueActiveRef.current = false; ++ highlightRunIdRef.current += 1; + clearReviewHighlightFileCache(); + loggedMissingReviewTokenKeys.clear(); + logReviewDiffDiagnostic("reset highlighted files", { +@@ -905,15 +1028,23 @@ export function ReviewSheet() { + return; + } + ++ markReviewEvent("parsed-diff-ready", { ++ sectionId: selectedSection?.id ?? null, ++ fileCount: parsedDiff.fileCount, ++ additions: parsedDiff.additions, ++ deletions: parsedDiff.deletions, ++ renderedItems: reviewListItems.length, ++ }); + logReviewDiffDiagnostic("parsed diff files", { + selectedSectionId: selectedSection?.id ?? null, + fileCount: parsedDiff.fileCount, + renderableFileCount: parsedDiff.files.length, + }); +- }, [parsedDiff, selectedSection?.id]); ++ }, [parsedDiff, reviewListItems.length, selectedSection?.id]); + + useEffect(() => { +- if (priorityHighlightFileIds.length === 0) { ++ const files = highlightableFilesRef.current; ++ if (files.length === 0) { + logReviewDiffDiagnostic("no highlightable files", { + selectedSectionId: selectedSection?.id ?? null, + parsedDiffKind: parsedDiff.kind, +@@ -922,33 +1053,98 @@ export function ReviewSheet() { + return; + } + +- const queuedFileIds: string[] = []; +- priorityHighlightFileIds.forEach((fileId) => { +- if (highlightRequestedFileIdsRef.current.has(fileId)) { +- return; +- } +- +- const file = highlightableFilesByIdRef.current.get(fileId); +- if (!file) { +- return; +- } +- +- highlightRequestedFileIdsRef.current.add(fileId); +- highlightQueueRef.current.push(fileId); +- queuedFileIds.push(fileId); +- }); +- +- if (queuedFileIds.length === 0) { ++ if (reviewHighlighter.status !== "ready") { ++ logReviewDiffDiagnostic("waiting for highlighter provider", { ++ selectedSectionId: selectedSection?.id ?? null, ++ status: reviewHighlighter.status, ++ error: reviewHighlighter.error, ++ }); + return; + } + +- logReviewDiffDiagnostic("scheduling file highlights", { ++ const runId = highlightRunIdRef.current; ++ let cancelled = false; ++ ++ logReviewDiffDiagnostic("streaming file highlights", { + selectedSectionId: selectedSection?.id ?? null, +- fileCount: queuedFileIds.length, +- fileIds: queuedFileIds, ++ fileCount: files.length, + }); +- startHighlightQueueRunner(); +- }, [parsedDiff.kind, priorityHighlightFileIds, selectedSection?.id, startHighlightQueueRunner]); ++ ++ void (async () => { ++ for (const file of files) { ++ if (cancelled || runId !== highlightRunIdRef.current) { ++ return; ++ } ++ ++ const cached = getCachedHighlightedReviewFile(file, selectedTheme); ++ if (cached) { ++ setHighlightedFilesById((current) => ++ current[file.id] === cached ? current : { ...current, [file.id]: cached }, ++ ); ++ continue; ++ } ++ ++ logReviewDiffDiagnostic("requesting highlighted file", { ++ fileId: file.id, ++ filePath: file.path, ++ theme: selectedTheme, ++ }); ++ ++ try { ++ const highlightStartedAt = performance.now(); ++ const result = await streamHighlightReviewFile(file, selectedTheme, (progress) => { ++ if (cancelled || runId !== highlightRunIdRef.current) { ++ return; ++ } ++ ++ if (!progress.complete) { ++ return; ++ } ++ ++ logReviewDiffDiagnostic("received streamed highlighted file", { ++ fileId: file.id, ++ filePath: file.path, ++ highlightedLineCount: progress.highlightedLineCount, ++ durationMs: Math.round(performance.now() - highlightStartedAt), ++ }); ++ }); ++ ++ if (cancelled || runId !== highlightRunIdRef.current) { ++ return; ++ } ++ ++ logReviewDiffDiagnostic("received highlighted file", { ++ fileId: file.id, ++ filePath: file.path, ++ additionLines: result.additionLines.length, ++ deletionLines: result.deletionLines.length, ++ }); ++ setHighlightedFilesById((current) => ++ current[file.id] === result ? current : { ...current, [file.id]: result }, ++ ); ++ } catch (error) { ++ logReviewDiffDiagnostic("highlight request failed", { ++ fileId: file.id, ++ filePath: file.path, ++ error: error instanceof Error ? error.message : String(error), ++ }); ++ } ++ ++ await waitForReviewDelay(0); ++ } ++ })(); ++ ++ return () => { ++ cancelled = true; ++ }; ++ }, [ ++ highlightableFilesKey, ++ parsedDiff.kind, ++ reviewHighlighter.error, ++ reviewHighlighter.status, ++ selectedSection?.id, ++ selectedTheme, ++ ]); + + const refreshSelectedSection = useCallback(async () => { + if (!selectedSection) { +@@ -968,20 +1164,68 @@ export function ReviewSheet() { + + const handleToggleExpandedFile = useCallback( + (fileId: string) => { +- if (!reviewCache.threadKey || !selectedSection?.id || parsedDiff.kind !== "files") { ++ if (!selectedSection?.id || parsedDiff.kind !== "files") { + return; + } + +- updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => { +- const currentIds = existing ?? getDefaultExpandedFileIds(parsedDiff.files); +- return currentIds.includes(fileId) ++ const sectionId = selectedSection.id; ++ ++ setLocalExpandedFileIdsBySection((current) => { ++ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, current[sectionId]); ++ const nextIds = currentIds.includes(fileId) + ? currentIds.filter((id) => id !== fileId) + : [...currentIds, fileId]; ++ ++ return { ++ ...current, ++ [sectionId]: nextIds, ++ }; + }); ++ ++ if (reviewCache.threadKey) { ++ updateReviewExpandedFileIds(reviewCache.threadKey, sectionId, (existing) => { ++ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, existing); ++ return currentIds.includes(fileId) ++ ? currentIds.filter((id) => id !== fileId) ++ : [...currentIds, fileId]; ++ }); ++ } + }, + [parsedDiff, reviewCache.threadKey, selectedSection?.id], + ); + ++ const handleToggleViewedFile = useCallback( ++ (fileId: string) => { ++ if (!selectedSection?.id) { ++ return; ++ } ++ ++ const sectionId = selectedSection.id; ++ ++ setLocalViewedFileIdsBySection((current) => { ++ const currentIds = current[sectionId] ?? []; ++ const nextIds = currentIds.includes(fileId) ++ ? currentIds.filter((id) => id !== fileId) ++ : [...currentIds, fileId]; ++ ++ return { ++ ...current, ++ [sectionId]: nextIds, ++ }; ++ }); ++ ++ if (reviewCache.threadKey) { ++ updateReviewViewedFileIds(reviewCache.threadKey, sectionId, (existing) => { ++ const currentIds = existing ?? []; ++ return currentIds.includes(fileId) ++ ? currentIds.filter((id) => id !== fileId) ++ : [...currentIds, fileId]; ++ }); ++ } ++ }, ++ [reviewCache.threadKey, selectedSection?.id], ++ ); ++ + const handleRevealLargeDiff = useCallback( + (fileId: string) => { + if (!reviewCache.threadKey || !selectedSection?.id) { +@@ -1080,35 +1324,6 @@ export function ReviewSheet() { + + return <>{children}; + }, [error, parsedDiffNotice]); +- const stickyHeaderIndices = useMemo(() => { +- const itemOffset = listHeader ? 1 : 0; +- +- return reviewListItems.flatMap((item, index) => +- item.kind === "file-header" ? [index + itemOffset] : [], +- ); +- }, [listHeader, reviewListItems]); +- +- const viewabilityConfigRef = useRef({ +- itemVisiblePercentThreshold: 10, +- }); +- const onViewableItemsChangedRef = useRef( +- ({ +- viewableItems, +- }: { +- readonly viewableItems: Array>; +- readonly changed: Array>; +- }) => { +- const nextVisibleFileIds = Array.from( +- new Set( +- viewableItems +- .filter((token) => token.isViewable && token.item !== undefined) +- .map((token) => token.item.fileId), +- ), +- ); +- +- setVisibleFileIds(nextVisibleFileIds); +- }, +- ); + + const renderReviewListItem = useCallback( + ({ item }: ListRenderItemInfo) => { +@@ -1116,112 +1331,142 @@ export function ReviewSheet() { + return null; + } + ++ let renderedItem: ReactElement | null = null; + switch (item.kind) { + case "file-header": +- return ( ++ renderedItem = ( + + ); ++ break; + case "file-suppressed": +- return ( ++ renderedItem = ( + + ); +- case "hunk": +- return ( +- ++ break; ++ case "hunk": { ++ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth; ++ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0; ++ ++ renderedItem = ( ++ } ++ viewportWidth={viewportWidth} ++ > ++ ++ + ); ++ break; ++ } + case "line": { +- const file = reviewFileById.get(item.fileId); +- if (!file) { +- return null; +- } +- +- const fileLineRows = reviewLineRowsByFileId.get(file.id) ?? []; +- const lineIndex = reviewLineIndexByRowId.get(item.row.id); +- if (lineIndex === undefined) { +- return null; +- } +- ++ const fileLineRows = reviewLineRowsByFileId.get(item.file.id) ?? []; + const pendingSelectionForFile = + pendingCommentSelection && + pendingCommentSelection.sectionTitle === selectedSection.title && +- pendingCommentSelection.filePath === file.path ++ pendingCommentSelection.filePath === item.file.path + ? pendingCommentSelection + : null; + const selectedTargetForFile = + activeCommentTarget && + activeCommentTarget.sectionTitle === selectedSection.title && +- activeCommentTarget.filePath === file.path ++ activeCommentTarget.filePath === item.file.path + ? activeCommentTarget + : null; + const highlightedFile = +- highlightedFilesById[file.id] ?? +- getCachedHighlightedReviewFile(file, selectedTheme) ?? ++ deferredHighlightedFilesById[item.file.id] ?? ++ getCachedHighlightedReviewFile(item.file, selectedTheme) ?? + null; ++ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth; ++ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0; + + if (highlightedFile === null) { +- const missingTokenKey = `${selectedSection.id}:${file.id}`; ++ const missingTokenKey = `${selectedSection.id}:${item.file.id}`; + if (!loggedMissingReviewTokenKeys.has(missingTokenKey)) { + loggedMissingReviewTokenKeys.add(missingTokenKey); + logReviewDiffDiagnostic("rendering file without tokens", { + sectionId: selectedSection.id, +- fileId: file.id, +- filePath: file.path, +- highlightedFileKnownInState: highlightedFilesById[file.id] !== undefined, ++ fileId: item.file.id, ++ filePath: item.file.path, ++ highlightedFileKnownInState: ++ deferredHighlightedFilesById[item.file.id] !== undefined, + }); + } + } + + const selectionState = +- pendingSelectionForFile?.anchorIndex === lineIndex ++ pendingSelectionForFile?.anchorIndex === item.lineIndex + ? ("anchor" as const) + : selectedTargetForFile && +- lineIndex >= selectedTargetForFile.startIndex && +- lineIndex <= selectedTargetForFile.endIndex ++ item.lineIndex >= selectedTargetForFile.startIndex && ++ item.lineIndex <= selectedTargetForFile.endIndex + ? ("selected" as const) + : null; + +- return ( +- +- handlePressLine({ +- sectionTitle: selectedSection.title, +- filePath: file.path, +- lines: fileLineRows, +- lineIndex, +- }) +- } +- onStartRangeSelection={() => +- handleStartRangeSelection({ +- sectionTitle: selectedSection.title, +- filePath: file.path, +- lines: fileLineRows, +- lineIndex, +- }) ++ renderedItem = ( ++ + } +- /> ++ viewportWidth={viewportWidth} ++ > ++ ++ handlePressLine({ ++ sectionTitle: selectedSection.title, ++ filePath: item.file.path, ++ lines: fileLineRows, ++ lineIndex: item.lineIndex, ++ }) ++ } ++ onStartRangeSelection={() => ++ handleStartRangeSelection({ ++ sectionTitle: selectedSection.title, ++ filePath: item.file.path, ++ lines: fileLineRows, ++ lineIndex: item.lineIndex, ++ }) ++ } ++ /> ++ + ); ++ break; + } + } ++ ++ return renderedItem; + }, + [ + activeCommentTarget, +@@ -1229,14 +1474,17 @@ export function ReviewSheet() { + handleRevealLargeDiff, + handleStartRangeSelection, + handleToggleExpandedFile, +- highlightedFilesById, ++ handleToggleViewedFile, ++ getReviewFileHorizontalOffset, ++ deferredHighlightedFilesById, + pendingCommentSelection, +- reviewFileById, +- reviewLineIndexByRowId, ++ reviewContentWidthByFileId, ++ reviewGutterWidthByFileId, + reviewLineRowsByFileId, +- reviewListContentWidth, + selectedSection, + selectedTheme, ++ viewedFileIdSet, ++ viewportWidth, + ], + ); + +@@ -1374,27 +1622,20 @@ export function ReviewSheet() { + + {selectedSection && parsedDiff.kind === "files" ? ( + item.id} ++ initialNumToRender={20} ++ maxToRenderPerBatch={20} ++ updateCellsBatchingPeriod={16} ++ windowSize={5} ++ removeClippedSubviews={false} + keyboardShouldPersistTaps="handled" + ListHeaderComponent={listHeader} +- stickyHeaderIndices={stickyHeaderIndices} +- removeClippedSubviews={false} +- initialNumToRender={24} +- maxToRenderPerBatch={16} +- updateCellsBatchingPeriod={16} +- windowSize={10} +- scrollEventThrottle={16} +- onViewableItemsChanged={onViewableItemsChangedRef.current} +- viewabilityConfig={viewabilityConfigRef.current} + contentContainerStyle={{ +- paddingTop: REVIEW_HEADER_SPACING, ++ paddingTop: topContentInset + REVIEW_HEADER_SPACING, + paddingBottom: Math.max(insets.bottom, 18) + 18, + }} + /> +diff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.ts +index f7a5c4125..eb6bf6973 100644 +--- a/apps/mobile/src/features/review/shikiReviewHighlighter.ts ++++ b/apps/mobile/src/features/review/shikiReviewHighlighter.ts +@@ -1,5 +1,14 @@ + import { createHighlighterCore, type HighlighterCore } from "@shikijs/core"; + import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript"; ++import bashLanguage from "@shikijs/langs/bash"; ++import javascriptLanguage from "@shikijs/langs/javascript"; ++import jsonLanguage from "@shikijs/langs/json"; ++import jsxLanguage from "@shikijs/langs/jsx"; ++import tsxLanguage from "@shikijs/langs/tsx"; ++import typescriptLanguage from "@shikijs/langs/typescript"; ++import yamlLanguage from "@shikijs/langs/yaml"; ++import githubDarkDefault from "@shikijs/themes/github-dark-default"; ++import githubLightDefault from "@shikijs/themes/github-light-default"; + import { getFiletypeFromFileName } from "@pierre/diffs/utils"; + + import { +@@ -11,6 +20,7 @@ import type { ReviewRenderableFile, ReviewRenderableLineRow } from "./reviewMode + import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs"; + + export type ReviewDiffTheme = "light" | "dark"; ++export type { ReviewHighlighterEngine }; + + export interface ReviewHighlightedToken { + content: string; +@@ -24,12 +34,19 @@ export interface ReviewHighlightedFile { + readonly deletionLines: ReadonlyArray>; + } + ++export interface ReviewHighlightFileProgress { ++ readonly highlightedFile: ReviewHighlightedFile; ++ readonly complete: boolean; ++ readonly highlightedLineCount: number; ++} ++ + const SHIKI_THEME_NAME_BY_SCHEME = { + light: "github-light-default", + dark: "github-dark-default", + } as const; + const REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE = +- process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? "javascript"; ++ process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? ++ (process.env.NODE_ENV === "test" ? "javascript" : "native"); + const REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE = resolveReviewHighlighterEnginePreference( + REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE, + ); +@@ -38,12 +55,30 @@ const REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE = resolveReviewHighlighterBooleanF + false, + ); + const REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT = 8; +-const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 40; +-const REVIEW_HIGHLIGHT_CHUNK_SIZE = 20; ++const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 8; ++const REVIEW_HIGHLIGHT_CHUNK_SIZE = 200; + const REVIEW_TOKENIZE_MAX_LINE_LENGTH = 1_000; + const highlightCache = new Map>(); + const resolvedHighlightCache = new Map(); +-const loadedLanguages = new Set(["text"]); ++const REVIEW_INITIAL_LANGUAGE_MODULES = [ ++ bashLanguage, ++ javascriptLanguage, ++ jsonLanguage, ++ jsxLanguage, ++ tsxLanguage, ++ typescriptLanguage, ++ yamlLanguage, ++] satisfies Parameters[0]["langs"]; ++const loadedLanguages = new Set([ ++ "text", ++ "bash", ++ "javascript", ++ "json", ++ "jsx", ++ "tsx", ++ "typescript", ++ "yaml", ++]); + const languageLoadingPromises = new Map>(); + const languageImports: Partial Promise>> = { + javascript: () => import("@shikijs/langs/javascript"), +@@ -215,21 +250,13 @@ function joinPatchLines(lines: ReadonlyArray): string { + + function waitForNextFrame(): Promise { + return new Promise((resolve) => { +- if (typeof requestAnimationFrame === "function") { +- requestAnimationFrame(() => resolve()); +- return; +- } +- + setTimeout(resolve, 0); + }); + } + + async function getHighlighter(): Promise { + if (!highlighterPromise) { +- const configuredHighlighterPromise = Promise.all([ +- import("@shikijs/themes/github-light-default"), +- import("@shikijs/themes/github-dark-default"), +- ]).then(async ([lightThemeModule, darkThemeModule]) => { ++ const configuredHighlighterPromise = (async () => { + let nativeEngineAvailable = false; + + logReviewHighlighterDiagnostic("initializing", { +@@ -238,12 +265,11 @@ async function getHighlighter(): Promise { + resultCacheDisabled: REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE, + }); + +- const themes = [lightThemeModule.default, darkThemeModule.default]; ++ const themes = [githubLightDefault, githubDarkDefault]; + + if (REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE !== "javascript") { + try { + const nativeEngineModule = await import("react-native-shiki-engine"); +- logReviewHighlighterDiagnostic("imported react-native-shiki-engine"); + nativeEngineAvailable = nativeEngineModule.isNativeEngineAvailable(); + logReviewHighlighterDiagnostic("checked native engine availability", { + nativeEngineAvailable, +@@ -253,7 +279,7 @@ async function getHighlighter(): Promise { + logReviewHighlighterDiagnostic("creating native regex engine"); + const highlighter = await createHighlighterCore({ + themes, +- langs: [], ++ langs: REVIEW_INITIAL_LANGUAGE_MODULES, + engine: nativeEngineModule.createNativeEngine(), + }); + logReviewHighlighterDiagnostic("using native engine"); +@@ -281,7 +307,7 @@ async function getHighlighter(): Promise { + ); + const highlighter = await createHighlighterCore({ + themes, +- langs: [], ++ langs: REVIEW_INITIAL_LANGUAGE_MODULES, + engine: createJavaScriptRegexEngine(), + }); + logReviewHighlighterDiagnostic("using javascript engine", { +@@ -291,7 +317,7 @@ async function getHighlighter(): Promise { + highlighter, + engine, + }; +- }); ++ })(); + + highlighterPromise = configuredHighlighterPromise + .then((result) => result.highlighter) +@@ -316,11 +342,52 @@ export async function getActiveReviewHighlighterEngine(): Promise { ++ await getHighlighter(); ++} ++ ++export async function prepareReviewHighlighterLanguages( ++ languages: ReadonlyArray, ++): Promise { ++ const highlighter = await getHighlighter(); ++ await Promise.all( ++ languages.map(async (language) => { ++ const candidate = resolveLanguageAlias(language); ++ if (candidate === "text" || !(candidate in languageImports)) { ++ return; ++ } ++ ++ await loadSingleLanguage(highlighter, candidate); ++ }), ++ ); ++} ++ + function resolveLanguageAlias(language: string): string { + const normalized = language.toLowerCase(); + return languageAliases[normalized] ?? normalized; + } + ++function resolveLoadedLanguageFromPath( ++ path: string, ++ languageHint: string | null = null, ++): string | null { ++ const detectedLanguage = languageHint ?? getFiletypeFromFileName(path); ++ if (!detectedLanguage) { ++ return "text"; ++ } ++ ++ const candidate = resolveLanguageAlias(detectedLanguage); ++ if (candidate === "text" || candidate === "ansi") { ++ return "text"; ++ } ++ ++ if (!(candidate in languageImports)) { ++ return "text"; ++ } ++ ++ return loadedLanguages.has(candidate) ? candidate : null; ++} ++ + async function loadSingleLanguage( + highlighter: HighlighterCore, + language: string, +@@ -360,6 +427,11 @@ async function resolveLanguageFromPath( + path: string, + languageHint: string | null = null, + ): Promise { ++ const loadedLanguage = resolveLoadedLanguageFromPath(path, languageHint); ++ if (loadedLanguage) { ++ return loadedLanguage; ++ } ++ + const detectedLanguage = languageHint ?? getFiletypeFromFileName(path); + if (!detectedLanguage) { + return "text"; +@@ -374,8 +446,12 @@ async function resolveLanguageFromPath( + return "text"; + } + ++ if (loadedLanguages.has(candidate)) { ++ return candidate; ++ } ++ + const highlighter = await getHighlighter(); +- const loaded = await loadSingleLanguage(highlighter, resolveLanguageAlias(candidate)); ++ const loaded = await loadSingleLanguage(highlighter, candidate); + if (!loaded) { + return "text"; + } +@@ -384,7 +460,10 @@ async function resolveLanguageFromPath( + } + + async function resolveLanguage(file: ReviewRenderableFile): Promise { +- return resolveLanguageFromPath(file.path, file.languageHint); ++ return ( ++ resolveLoadedLanguageFromPath(file.path, file.languageHint) ?? ++ (await resolveLanguageFromPath(file.path, file.languageHint)) ++ ); + } + + function normalizeHighlightedLines( +@@ -399,6 +478,18 @@ function normalizeHighlightedLines( + ); + } + ++function makePlainHighlightedLines( ++ lines: ReadonlyArray, ++): ReadonlyArray> { ++ return lines.map((line) => [ ++ { ++ content: stripTrailingNewline(line), ++ color: null, ++ fontStyle: null, ++ }, ++ ]); ++} ++ + function applyWordAltDiffHighlightsToFile( + file: ReviewRenderableFile, + highlighted: ReviewHighlightedFile, +@@ -594,6 +685,67 @@ async function highlightLines( + return highlightedLines; + } + ++async function highlightPatchLinesInChunks(input: { ++ readonly lines: ReadonlyArray; ++ readonly language: string; ++ readonly theme: string; ++ readonly onChunk: ( ++ startIndex: number, ++ tokens: ReadonlyArray>, ++ ) => void; ++}): Promise>> { ++ if (input.lines.length === 0) { ++ return []; ++ } ++ ++ const highlighter = await getHighlighter(); ++ const highlightedLines: Array> = []; ++ ++ for ( ++ let startIndex = 0; ++ startIndex < input.lines.length; ++ startIndex += REVIEW_HIGHLIGHT_CHUNK_SIZE ++ ) { ++ const lineChunk = input.lines.slice(startIndex, startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE); ++ const chunkTokens: Array> = []; ++ const tokenizableLines: string[] = []; ++ const tokenizableIndexes: number[] = []; ++ ++ lineChunk.forEach((line, index) => { ++ const strippedLine = stripTrailingNewline(line); ++ if (strippedLine.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH) { ++ chunkTokens[index] = [{ content: strippedLine, color: null, fontStyle: null }]; ++ return; ++ } ++ ++ tokenizableIndexes.push(index); ++ tokenizableLines.push(strippedLine); ++ }); ++ ++ if (tokenizableLines.length > 0) { ++ const tokenLines = highlighter.codeToTokensBase(tokenizableLines.join("\n"), { ++ lang: input.language, ++ theme: input.theme, ++ }); ++ const normalizedTokenLines = normalizeHighlightedLines(tokenLines); ++ ++ tokenizableIndexes.forEach((chunkIndex, tokenIndex) => { ++ chunkTokens[chunkIndex] = normalizedTokenLines[tokenIndex] ?? []; ++ }); ++ } ++ ++ const completedChunk = lineChunk.map((_, index) => chunkTokens[index] ?? []); ++ highlightedLines.push(...completedChunk); ++ input.onChunk(startIndex, completedChunk); ++ ++ if (startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE < input.lines.length) { ++ await waitForNextFrame(); ++ } ++ } ++ ++ return highlightedLines; ++} ++ + function getHighlightCacheKey(file: ReviewRenderableFile, theme: ReviewDiffTheme): string { + return `${SHIKI_THEME_NAME_BY_SCHEME[theme]}:${file.cacheKey}`; + } +@@ -667,7 +819,28 @@ export async function highlightReviewFile( + deletionLineCount: file.deletionLines.length, + rowCount: file.rows.length, + }); +- const language = await resolveLanguage(file); ++ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint); ++ const language = loadedLanguage ?? (await resolveLanguage(file)); ++ if (language === "text") { ++ const highlighted = applyWordAltDiffHighlightsToFile(file, { ++ additionLines: makePlainHighlightedLines(file.additionLines), ++ deletionLines: makePlainHighlightedLines(file.deletionLines), ++ }); ++ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { ++ storeResolvedHighlightedFile(cacheKey, highlighted); ++ } ++ logReviewHighlighterDiagnostic("file highlight complete", { ++ fileId: file.id, ++ filePath: file.path, ++ theme, ++ language, ++ highlightedAdditionLineCount: highlighted.additionLines.length, ++ highlightedDeletionLineCount: highlighted.deletionLines.length, ++ durationMs: Date.now() - startedAt, ++ }); ++ return highlighted; ++ } ++ + const additionLines = await highlightLines( + joinPatchLines(file.additionLines), + language, +@@ -707,6 +880,113 @@ export async function highlightReviewFile( + }); + } + ++export async function streamHighlightReviewFile( ++ file: ReviewRenderableFile, ++ theme: ReviewDiffTheme, ++ onProgress: (progress: ReviewHighlightFileProgress) => void, ++): Promise { ++ const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[theme]; ++ const cacheKey = getHighlightCacheKey(file, theme); ++ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { ++ const resolved = resolvedHighlightCache.get(cacheKey); ++ if (resolved) { ++ onProgress({ ++ highlightedFile: resolved, ++ complete: true, ++ highlightedLineCount: resolved.additionLines.length + resolved.deletionLines.length, ++ }); ++ return resolved; ++ } ++ } ++ ++ const startedAt = Date.now(); ++ logReviewHighlighterDiagnostic("file stream highlight start", { ++ fileId: file.id, ++ filePath: file.path, ++ theme, ++ additionLineCount: file.additionLines.length, ++ deletionLineCount: file.deletionLines.length, ++ rowCount: file.rows.length, ++ }); ++ ++ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint); ++ const language = loadedLanguage ?? (await resolveLanguage(file)); ++ if (language === "text") { ++ const highlighted = applyWordAltDiffHighlightsToFile(file, { ++ additionLines: makePlainHighlightedLines(file.additionLines), ++ deletionLines: makePlainHighlightedLines(file.deletionLines), ++ }); ++ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { ++ storeResolvedHighlightedFile(cacheKey, highlighted); ++ } ++ onProgress({ ++ highlightedFile: highlighted, ++ complete: true, ++ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length, ++ }); ++ logReviewHighlighterDiagnostic("file stream highlight complete", { ++ fileId: file.id, ++ filePath: file.path, ++ theme, ++ language, ++ highlightedAdditionLineCount: highlighted.additionLines.length, ++ highlightedDeletionLineCount: highlighted.deletionLines.length, ++ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length, ++ durationMs: Date.now() - startedAt, ++ }); ++ return highlighted; ++ } ++ ++ const additionLines: Array> = []; ++ const deletionLines: Array> = []; ++ let highlightedLineCount = 0; ++ ++ await highlightPatchLinesInChunks({ ++ lines: file.additionLines, ++ language, ++ theme: shikiTheme, ++ onChunk: (startIndex, tokens) => { ++ tokens.forEach((lineTokens, index) => { ++ additionLines[startIndex + index] = lineTokens; ++ }); ++ highlightedLineCount += tokens.length; ++ }, ++ }); ++ await waitForNextFrame(); ++ await highlightPatchLinesInChunks({ ++ lines: file.deletionLines, ++ language, ++ theme: shikiTheme, ++ onChunk: (startIndex, tokens) => { ++ tokens.forEach((lineTokens, index) => { ++ deletionLines[startIndex + index] = lineTokens; ++ }); ++ highlightedLineCount += tokens.length; ++ }, ++ }); ++ ++ const highlighted = applyWordAltDiffHighlightsToFile(file, { additionLines, deletionLines }); ++ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { ++ storeResolvedHighlightedFile(cacheKey, highlighted); ++ } ++ onProgress({ ++ highlightedFile: highlighted, ++ complete: true, ++ highlightedLineCount, ++ }); ++ logReviewHighlighterDiagnostic("file stream highlight complete", { ++ fileId: file.id, ++ filePath: file.path, ++ theme, ++ language, ++ highlightedAdditionLineCount: highlighted.additionLines.length, ++ highlightedDeletionLineCount: highlighted.deletionLines.length, ++ highlightedLineCount, ++ durationMs: Date.now() - startedAt, ++ }); ++ return highlighted; ++} ++ + export async function highlightReviewSelectedLines(input: { + readonly filePath: string; + readonly lines: ReadonlyArray; +@@ -717,7 +997,9 @@ export async function highlightReviewSelectedLines(input: { + return {}; + } + +- const language = await resolveLanguageFromPath(input.filePath, input.languageHint ?? null); ++ const loadedLanguage = resolveLoadedLanguageFromPath(input.filePath, input.languageHint ?? null); ++ const language = ++ loadedLanguage ?? (await resolveLanguageFromPath(input.filePath, input.languageHint ?? null)); + const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[input.theme]; + const additionLikeLines = input.lines + .filter((line) => line.change !== "delete") diff --git a/apps/mobile/src/features/debug/fixtures/review-small.diff b/apps/mobile/src/features/debug/fixtures/review-small.diff new file mode 100644 index 0000000000..14ac0d9c73 --- /dev/null +++ b/apps/mobile/src/features/debug/fixtures/review-small.diff @@ -0,0 +1,155 @@ +diff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx +index d61924a62..3f2ae0160 100644 +--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx ++++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx +@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({ + default: "monospace", + }); + ++export const REVIEW_DIFF_LINE_HEIGHT = 26; ++const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2; ++ + export function renderVisibleWhitespace(value: string): string { + const expandedTabs = value.replace(/\t/g, " "); + return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\u00A0")); +@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string | + export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) { + if (props.change === "delete") { + return ( +- +- +- {Array.from({ length: 6 }, (_, index) => ( +- ++ ++ ++ {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => ( ++ ++ ++ ++ + ))} + + +@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo + } + + return ( +- ++ + + + ); +@@ -63,6 +69,7 @@ export function DiffTokenText(props: { + if (!props.tokens || props.tokens.length === 0) { + return ( + { + }); + }); + +- it("flattens expanded files into virtualizable review items", () => { ++ it("flattens expanded file rows into virtualized review items", () => { + const file = makeRenderableFile({ + path: "apps/mobile/src/a.ts", + rows: [ +@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => { + + expect(items).toEqual([ + expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }), +- expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }), +- expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }), ++ expect.objectContaining({ ++ kind: "hunk", ++ fileId: file.id, ++ file, ++ row: file.rows[0], ++ }), ++ expect.objectContaining({ ++ kind: "line", ++ fileId: file.id, ++ file, ++ row: file.rows[1], ++ lineIndex: 0, ++ }), + ]); + }); + +diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts +index 27e6d7ae4..1cfbf358c 100644 +--- a/apps/mobile/src/features/review/reviewModel.ts ++++ b/apps/mobile/src/features/review/reviewModel.ts +@@ -72,6 +72,7 @@ export interface ReviewHunkListItem { + readonly kind: "hunk"; + readonly id: string; + readonly fileId: string; ++ readonly file: ReviewRenderableFile; + readonly row: ReviewRenderableHunkRow; + } + +@@ -79,7 +80,9 @@ export interface ReviewLineListItem { + readonly kind: "line"; + readonly id: string; + readonly fileId: string; ++ readonly file: ReviewRenderableFile; + readonly row: ReviewRenderableLineRow; ++ readonly lineIndex: number; + } + + export type ReviewListItem = +@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil + } + + // The flattened review list item model is inspired by pierre/diffs' iterator-first +-// virtualization architecture, adapted here for React Native and LegendList. ++// virtualization architecture, adapted here for React Native virtualization. + // Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs + // Reference files: + // - src/utils/iterateOverDiff.ts +@@ -350,12 +353,14 @@ export function buildReviewListItems(input: { + } + } + +- file.rows.forEach((row) => { ++ let lineIndex = 0; ++ file.rows.forEach((row, rowIndex) => { + if (row.kind === "hunk") { + items.push({ + kind: "hunk", +- id: row.id, ++ id: `${file.id}:row:${rowIndex}:${row.id}`, + fileId: file.id, ++ file, + row, + }); + return; +@@ -363,10 +368,13 @@ export function buildReviewListItems(input: { + + items.push({ + kind: "line", +- id: row.id, ++ id: `${file.id}:row:${rowIndex}:${row.id}`, + fileId: file.id, ++ file, + row, ++ lineIndex, + }); ++ lineIndex += 1; + }); + }); + diff --git a/apps/mobile/src/features/debug/fixtures/reviewDiffFixtures.ts b/apps/mobile/src/features/debug/fixtures/reviewDiffFixtures.ts new file mode 100644 index 0000000000..475e82292a --- /dev/null +++ b/apps/mobile/src/features/debug/fixtures/reviewDiffFixtures.ts @@ -0,0 +1,40 @@ +export type DebugReviewDiffFixtureId = "small" | "medium" | "large" | "current"; + +export interface DebugReviewDiffFixture { + readonly id: DebugReviewDiffFixtureId; + readonly label: string; + readonly filename: string; + readonly lineCount: number; + readonly diff: string; +} + +export const debugReviewDiffFixtures: ReadonlyArray = [ + { + id: "small", + label: "Small", + filename: "review-small.diff", + lineCount: 155, + diff: 'diff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx\nindex d61924a62..3f2ae0160 100644\n--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx\n+++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx\n@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({\n default: "monospace",\n });\n \n+export const REVIEW_DIFF_LINE_HEIGHT = 26;\n+const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2;\n+\n export function renderVisibleWhitespace(value: string): string {\n const expandedTabs = value.replace(/\\t/g, " ");\n return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\\u00A0"));\n@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string |\n export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) {\n if (props.change === "delete") {\n return (\n- \n- \n- {Array.from({ length: 6 }, (_, index) => (\n- \n+ \n+ \n+ {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => (\n+ \n+ \n+ \n+ \n ))}\n \n \n@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo\n }\n \n return (\n- \n+ \n \n \n );\n@@ -63,6 +69,7 @@ export function DiffTokenText(props: {\n if (!props.tokens || props.tokens.length === 0) {\n return (\n {\n });\n });\n \n- it("flattens expanded files into virtualizable review items", () => {\n+ it("flattens expanded file rows into virtualized review items", () => {\n const file = makeRenderableFile({\n path: "apps/mobile/src/a.ts",\n rows: [\n@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => {\n \n expect(items).toEqual([\n expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }),\n- expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }),\n- expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }),\n+ expect.objectContaining({\n+ kind: "hunk",\n+ fileId: file.id,\n+ file,\n+ row: file.rows[0],\n+ }),\n+ expect.objectContaining({\n+ kind: "line",\n+ fileId: file.id,\n+ file,\n+ row: file.rows[1],\n+ lineIndex: 0,\n+ }),\n ]);\n });\n \ndiff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts\nindex 27e6d7ae4..1cfbf358c 100644\n--- a/apps/mobile/src/features/review/reviewModel.ts\n+++ b/apps/mobile/src/features/review/reviewModel.ts\n@@ -72,6 +72,7 @@ export interface ReviewHunkListItem {\n readonly kind: "hunk";\n readonly id: string;\n readonly fileId: string;\n+ readonly file: ReviewRenderableFile;\n readonly row: ReviewRenderableHunkRow;\n }\n \n@@ -79,7 +80,9 @@ export interface ReviewLineListItem {\n readonly kind: "line";\n readonly id: string;\n readonly fileId: string;\n+ readonly file: ReviewRenderableFile;\n readonly row: ReviewRenderableLineRow;\n+ readonly lineIndex: number;\n }\n \n export type ReviewListItem =\n@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil\n }\n \n // The flattened review list item model is inspired by pierre/diffs\' iterator-first\n-// virtualization architecture, adapted here for React Native and LegendList.\n+// virtualization architecture, adapted here for React Native virtualization.\n // Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs\n // Reference files:\n // - src/utils/iterateOverDiff.ts\n@@ -350,12 +353,14 @@ export function buildReviewListItems(input: {\n }\n }\n \n- file.rows.forEach((row) => {\n+ let lineIndex = 0;\n+ file.rows.forEach((row, rowIndex) => {\n if (row.kind === "hunk") {\n items.push({\n kind: "hunk",\n- id: row.id,\n+ id: `${file.id}:row:${rowIndex}:${row.id}`,\n fileId: file.id,\n+ file,\n row,\n });\n return;\n@@ -363,10 +368,13 @@ export function buildReviewListItems(input: {\n \n items.push({\n kind: "line",\n- id: row.id,\n+ id: `${file.id}:row:${rowIndex}:${row.id}`,\n fileId: file.id,\n+ file,\n row,\n+ lineIndex,\n });\n+ lineIndex += 1;\n });\n });\n \n', + }, + { + id: "medium", + label: "Medium", + filename: "review-medium.diff", + lineCount: 1955, + diff: 'diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\nindex 84c48c6ed..ee993ee7c 100644\n--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n@@ -1,5 +1,10 @@\n+import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";\n import { ReviewSheet } from "../../../../features/review/ReviewSheet";\n \n export default function ReviewRoute() {\n- return ;\n+ return (\n+ \n+ \n+ \n+ );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx\nindex 82c28e81e..e148a8da2 100644\n--- a/apps/mobile/src/features/review/ReviewSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewSheet.tsx\n@@ -1,17 +1,31 @@\n import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts";\n+import { Gesture, GestureDetector } from "react-native-gesture-handler";\n+import Animated, {\n+ makeMutable,\n+ type SharedValue,\n+ useAnimatedStyle,\n+ useSharedValue,\n+} from "react-native-reanimated";\n import { useLocalSearchParams, useRouter } from "expo-router";\n import Stack from "expo-router/stack";\n import { SymbolView } from "expo-symbols";\n-import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react";\n+import {\n+ memo,\n+ type ReactElement,\n+ useCallback,\n+ useDeferredValue,\n+ useEffect,\n+ useMemo,\n+ useRef,\n+ useState,\n+} from "react";\n import {\n ActivityIndicator,\n FlatList,\n- InteractionManager,\n type ListRenderItemInfo,\n Pressable,\n ScrollView,\n Text as NativeText,\n- type ViewToken,\n useColorScheme,\n useWindowDimensions,\n View,\n@@ -32,6 +46,7 @@ import {\n setReviewTurnDiff,\n updateReviewExpandedFileIds,\n updateReviewRevealedLargeFileIds,\n+ updateReviewViewedFileIds,\n useReviewCacheForThread,\n } from "./reviewState";\n import {\n@@ -45,11 +60,12 @@ import {\n type ReviewParsedDiff,\n type ReviewRenderableFile,\n type ReviewRenderableLineRow,\n+ type ReviewRenderableRow,\n } from "./reviewModel";\n import {\n clearReviewHighlightFileCache,\n getCachedHighlightedReviewFile,\n- highlightReviewFile,\n+ streamHighlightReviewFile,\n type ReviewDiffTheme,\n type ReviewHighlightedFile,\n type ReviewHighlightedToken,\n@@ -67,9 +83,12 @@ import {\n import {\n changeTone,\n DiffTokenText,\n+ REVIEW_DIFF_LINE_HEIGHT,\n REVIEW_MONO_FONT_FAMILY,\n ReviewChangeBar,\n } from "./reviewDiffRendering";\n+import { markReviewEvent, measureReviewWork } from "./reviewPerf";\n+import { useReviewHighlighterStatus } from "./ReviewHighlighterProvider";\n \n interface PendingCommentSelection {\n readonly sectionTitle: string;\n@@ -87,14 +106,21 @@ interface ReviewLineActionInput {\n \n const IOS_NAV_BAR_HEIGHT = 44;\n const REVIEW_HEADER_SPACING = 0;\n-const REVIEW_LINE_GUTTER_WIDTH = 62;\n+const REVIEW_CHANGE_BAR_WIDTH = 5;\n+const REVIEW_MIN_LINE_NUMBER_WIDTH = 27;\n+const REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE = 8;\n+const REVIEW_LINE_NUMBER_HORIZONTAL_PADDING = 6;\n const REVIEW_CHARACTER_WIDTH_ESTIMATE = 8.4;\n const REVIEW_MAX_CONTENT_WIDTH = 4_800;\n-const REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT = 2;\n-const REVIEW_HIGHLIGHT_BACKTRACK_COUNT = 0;\n-const REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT = 1;\n+const REVIEW_HUNK_ROW_HEIGHT = 35;\n+const REVIEW_FILE_HEADER_HEIGHT = 43;\n+const REVIEW_SUPPRESSED_ROW_HEIGHT = 92;\n const loggedMissingReviewTokenKeys = new Set();\n \n+function waitForReviewDelay(durationMs: number): Promise {\n+ return new Promise((resolve) => setTimeout(resolve, durationMs));\n+}\n+\n function isReviewDiffDebugLoggingEnabled(): boolean {\n return typeof __DEV__ !== "undefined" ? __DEV__ : false;\n }\n@@ -113,33 +139,27 @@ function logReviewDiffDiagnostic(message: string, details?: Record,\n+function computeReviewFileContentWidth(\n+ rows: ReadonlyArray,\n viewportWidth: number,\n+ gutterWidth: number,\n ): number {\n let maxTextLength = 0;\n \n- items.forEach((item) => {\n- switch (item.kind) {\n- case "file-header":\n- maxTextLength = Math.max(\n- maxTextLength,\n- item.file.path.length,\n- item.file.previousPath?.length ?? 0,\n- );\n- break;\n- case "file-suppressed":\n- maxTextLength = Math.max(maxTextLength, item.message.length, item.actionLabel?.length ?? 0);\n- break;\n- case "hunk":\n- maxTextLength = Math.max(\n- maxTextLength,\n- item.row.header.length + (item.row.context ? item.row.context.length + 1 : 0),\n- );\n- break;\n- case "line":\n- maxTextLength = Math.max(maxTextLength, item.row.content.length);\n- break;\n+ rows.forEach((row) => {\n+ if (row.kind === "hunk") {\n+ maxTextLength = Math.max(\n+ maxTextLength,\n+ row.header.length + (row.context ? row.context.length + 1 : 0),\n+ );\n+ return;\n }\n+\n+ maxTextLength = Math.max(maxTextLength, row.content.length);\n });\n \n return Math.max(\n- viewportWidth,\n+ Math.max(0, viewportWidth - gutterWidth),\n Math.min(\n REVIEW_MAX_CONTENT_WIDTH,\n- Math.ceil(REVIEW_LINE_GUTTER_WIDTH + 48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE),\n+ Math.ceil(48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE),\n ),\n );\n }\n \n+function computeReviewFileGutterWidth(rows: ReadonlyArray): number {\n+ let maxLineNumber = 0;\n+\n+ rows.forEach((row) => {\n+ if (row.kind !== "line") {\n+ return;\n+ }\n+\n+ maxLineNumber = Math.max(maxLineNumber, row.oldLineNumber ?? 0, row.newLineNumber ?? 0);\n+ });\n+\n+ const digitCount = Math.max(1, String(maxLineNumber).length);\n+ const lineNumberWidth = Math.max(\n+ REVIEW_MIN_LINE_NUMBER_WIDTH,\n+ digitCount * REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE + REVIEW_LINE_NUMBER_HORIZONTAL_PADDING,\n+ );\n+\n+ return REVIEW_CHANGE_BAR_WIDTH + lineNumberWidth;\n+}\n+\n function getDefaultExpandedFileIds(\n files: ReadonlyArray,\n ): ReadonlyArray {\n return files.map((file) => file.id);\n }\n \n+function getValidReviewExpandedFileIds(\n+ files: ReadonlyArray,\n+ cachedExpandedFileIds: ReadonlyArray | undefined,\n+): ReadonlyArray {\n+ if (cachedExpandedFileIds === undefined) {\n+ return getDefaultExpandedFileIds(files);\n+ }\n+\n+ const fileIdSet = new Set(files.map((file) => file.id));\n+ return cachedExpandedFileIds.filter((id) => fileIdSet.has(id));\n+}\n+\n function getHighlightedTokensForLine(\n line: ReviewRenderableLineRow,\n highlightedFile: ReviewHighlightedFile | null,\n@@ -252,16 +293,13 @@ const ReviewLineRow = memo(function ReviewLineRow(props: {\n delayLongPress={220}\n onLongPress={props.onStartRangeSelection}\n onPress={props.onComment}\n- style={{ minWidth: props.viewportWidth }}\n+ style={{\n+ height: REVIEW_DIFF_LINE_HEIGHT,\n+ width: props.viewportWidth,\n+ overflow: "hidden",\n+ }}\n >\n- \n- \n- {lineNumber ?? ""}\n- \n- \n+ \n \n+ \n+ \n+ {props.lineNumber ?? ""}\n+ \n+ \n+ );\n+});\n+\n+const ReviewHunkGutter = memo(function ReviewHunkGutter(props: { readonly gutterWidth: number }) {\n+ return (\n+ \n+ );\n+});\n+\n const ReviewFileCard = memo(function ReviewFileCard(props: {\n readonly file: ReviewRenderableFile;\n readonly fileId: string;\n readonly expanded: boolean;\n+ readonly viewed: boolean;\n readonly viewportWidth: number;\n readonly onToggleFile: (fileId: string) => void;\n+ readonly onToggleViewed: (fileId: string) => void;\n }) {\n- const chrome = getFileHeaderChrome(props.file.changeType);\n+ const { expanded, file, fileId, onToggleFile, onToggleViewed, viewed, viewportWidth } = props;\n+ const chrome = getFileHeaderChrome(file.changeType);\n+ const iconColor = String(useThemeColor("--color-icon-muted"));\n+ const handleToggleFile = useCallback(() => {\n+ onToggleFile(fileId);\n+ }, [fileId, onToggleFile]);\n+ const handleToggleViewed = useCallback(() => {\n+ onToggleViewed(fileId);\n+ }, [fileId, onToggleViewed]);\n \n return (\n \n- props.onToggleFile(props.fileId)}>\n- \n- \n- \n- \n- \n- \n- \n- \n- \n- {props.file.path}\n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ {file.path}\n+ \n+ {file.previousPath && file.previousPath !== file.path ? (\n+ \n+ {file.previousPath}\n \n- {props.file.previousPath && props.file.previousPath !== props.file.path ? (\n- \n- {props.file.previousPath}\n- \n+ ) : null}\n+ \n+ \n+ \n+ \n+ -{file.deletions}\n+ \n+ \n+ +{file.additions}\n+ \n+ \n+ \n+ {viewed ? (\n+ \n ) : null}\n \n- \n- \n- \n- +{props.file.additions}\n- \n- \n- -{props.file.deletions}\n+ \n+ Viewed\n \n- \n+ \n \n- \n+ \n \n );\n });\n@@ -342,7 +453,11 @@ const ReviewFileSuppressedBody = memo(function ReviewFileSuppressedBody(props: {\n return (\n \n {props.message}\n {props.actionLabel && props.onLoadDiffFile ? (\n@@ -364,10 +479,13 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: {\n }) {\n return (\n \n- \n+ \n {props.header}\n {props.context ? ` ${props.context}` : ""}\n \n@@ -375,6 +493,61 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: {\n );\n });\n \n+const ReviewCodePanRow = memo(function ReviewCodePanRow(props: {\n+ readonly contentWidth: number;\n+ readonly horizontalOffset: SharedValue;\n+ readonly gutterWidth?: number;\n+ readonly viewportWidth: number;\n+ readonly leftGutter?: ReactElement;\n+ readonly children: ReactElement;\n+}) {\n+ const {\n+ children,\n+ contentWidth,\n+ gutterWidth = 0,\n+ horizontalOffset,\n+ leftGutter,\n+ viewportWidth,\n+ } = props;\n+ const dragStartOffset = useSharedValue(0);\n+ const visibleContentWidth = leftGutter ? viewportWidth - gutterWidth : viewportWidth;\n+ const maxOffset = Math.max(0, contentWidth - visibleContentWidth);\n+\n+ const panGesture = useMemo(\n+ () =>\n+ Gesture.Pan()\n+ .activeOffsetX([-8, 8])\n+ .failOffsetY([-10, 10])\n+ .onBegin(() => {\n+ dragStartOffset.value = horizontalOffset.value;\n+ })\n+ .onUpdate((event) => {\n+ "worklet";\n+ const nextOffset = dragStartOffset.value - event.translationX;\n+ horizontalOffset.value = Math.min(maxOffset, Math.max(0, nextOffset));\n+ }),\n+ [dragStartOffset, horizontalOffset, maxOffset],\n+ );\n+\n+ const contentStyle = useAnimatedStyle(\n+ () => ({\n+ transform: [{ translateX: -horizontalOffset.value }],\n+ }),\n+ [horizontalOffset],\n+ );\n+\n+ return (\n+ \n+ \n+ {leftGutter ?? null}\n+ \n+ {children}\n+ \n+ \n+ \n+ );\n+});\n+\n const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) {\n return (\n \n@@ -454,15 +627,19 @@ export function ReviewSheet() {\n const [highlightedFilesById, setHighlightedFilesById] = useState<\n Record\n >({});\n- const [visibleFileIds, setVisibleFileIds] = useState>([]);\n+ const deferredHighlightedFilesById = useDeferredValue(highlightedFilesById);\n+ const [localExpandedFileIdsBySection, setLocalExpandedFileIdsBySection] = useState<\n+ Record>\n+ >({});\n+ const [localViewedFileIdsBySection, setLocalViewedFileIdsBySection] = useState<\n+ Record>\n+ >({});\n const activeCommentTarget = useReviewCommentTarget();\n const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme;\n- const highlightQueueRef = useRef([]);\n- const highlightRequestedFileIdsRef = useRef>(new Set());\n- const highlightQueueGenerationRef = useRef(0);\n- const highlightQueueActiveRef = useRef(false);\n- const highlightableFilesByIdRef = useRef>(new Map());\n- const selectedThemeRef = useRef(selectedTheme);\n+ const reviewHighlighter = useReviewHighlighterStatus();\n+ const highlightRunIdRef = useRef(0);\n+ const highlightableFilesRef = useRef>([]);\n+ const horizontalOffsetByFileIdRef = useRef>>(new Map());\n const { selectedThreadCwd } = useSelectedThreadWorktree();\n \n const cwd = selectedThreadCwd;\n@@ -498,11 +675,13 @@ export function ReviewSheet() {\n const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;\n const parsedDiff = useMemo(\n () =>\n- getCachedReviewParsedDiff({\n- threadKey: reviewCache.threadKey,\n- sectionId: selectedSection?.id ?? null,\n- diff: selectedSection?.diff,\n- }),\n+ measureReviewWork("parse-diff", () =>\n+ getCachedReviewParsedDiff({\n+ threadKey: reviewCache.threadKey,\n+ sectionId: selectedSection?.id ?? null,\n+ diff: selectedSection?.diff,\n+ }),\n+ ),\n [reviewCache.threadKey, selectedSection?.diff, selectedSection?.id],\n );\n const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]);\n@@ -510,14 +689,53 @@ export function ReviewSheet() {\n () => countReviewCommentContexts(draftMessage),\n [draftMessage],\n );\n+ const viewportWidth = Math.max(width, 280);\n+\n+ useEffect(() => {\n+ if (!selectedSection?.id || parsedDiff.kind !== "files") {\n+ return;\n+ }\n+\n+ setLocalExpandedFileIdsBySection((current) => {\n+ if (current[selectedSection.id] !== undefined) {\n+ return current;\n+ }\n+\n+ return {\n+ ...current,\n+ [selectedSection.id]: getValidReviewExpandedFileIds(\n+ parsedDiff.files,\n+ reviewCache.expandedFileIdsBySection[selectedSection.id],\n+ ),\n+ };\n+ });\n+\n+ setLocalViewedFileIdsBySection((current) => {\n+ if (current[selectedSection.id] !== undefined) {\n+ return current;\n+ }\n+\n+ return {\n+ ...current,\n+ [selectedSection.id]: reviewCache.viewedFileIdsBySection[selectedSection.id] ?? [],\n+ };\n+ });\n+ }, [\n+ parsedDiff,\n+ reviewCache.expandedFileIdsBySection,\n+ reviewCache.viewedFileIdsBySection,\n+ selectedSection?.id,\n+ ]);\n \n const expandedFileIds = useMemo(\n () =>\n selectedSection?.id && parsedDiff.kind === "files"\n- ? (reviewCache.expandedFileIdsBySection[selectedSection.id] ??\n- getDefaultExpandedFileIds(parsedDiff.files))\n+ ? getValidReviewExpandedFileIds(\n+ parsedDiff.files,\n+ localExpandedFileIdsBySection[selectedSection.id],\n+ )\n : [],\n- [parsedDiff, reviewCache.expandedFileIdsBySection, selectedSection?.id],\n+ [localExpandedFileIdsBySection, parsedDiff, selectedSection?.id],\n );\n const revealedLargeFileIds = useMemo(\n () =>\n@@ -526,47 +744,96 @@ export function ReviewSheet() {\n : [],\n [reviewCache.revealedLargeFileIdsBySection, selectedSection?.id],\n );\n+ const viewedFileIds = useMemo(\n+ () => (selectedSection?.id ? (localViewedFileIdsBySection[selectedSection.id] ?? []) : []),\n+ [localViewedFileIdsBySection, selectedSection?.id],\n+ );\n+ const viewedFileIdSet = useMemo(() => new Set(viewedFileIds), [viewedFileIds]);\n const reviewListItems = useMemo(\n () =>\n selectedSection && parsedDiff.kind === "files"\n- ? buildReviewListItems({\n- files: parsedDiff.files,\n- expandedFileIds,\n- revealedLargeFileIds,\n- })\n+ ? measureReviewWork("build-list-items", () =>\n+ buildReviewListItems({\n+ files: parsedDiff.files,\n+ expandedFileIds,\n+ revealedLargeFileIds,\n+ }),\n+ )\n : [],\n [expandedFileIds, parsedDiff, revealedLargeFileIds, selectedSection],\n );\n- const reviewFileById = useMemo(() => {\n+ const reviewLineRowsByFileId = useMemo(() => {\n if (parsedDiff.kind !== "files") {\n- return new Map();\n+ return new Map>();\n }\n \n- return new Map(parsedDiff.files.map((file) => [file.id, file] as const));\n+ return measureReviewWork(\n+ "index-line-rows",\n+ () =>\n+ new Map(\n+ parsedDiff.files.map((file) => [\n+ file.id,\n+ file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"),\n+ ]),\n+ ),\n+ );\n }, [parsedDiff]);\n- const reviewLineRowsByFileId = useMemo(() => {\n+ const reviewContentWidthByFileId = useMemo(() => {\n if (parsedDiff.kind !== "files") {\n- return new Map>();\n+ return new Map();\n+ }\n+\n+ return measureReviewWork(\n+ "measure-file-widths",\n+ () =>\n+ new Map(\n+ parsedDiff.files.map((file) => [\n+ file.id,\n+ computeReviewFileContentWidth(\n+ file.rows,\n+ viewportWidth,\n+ computeReviewFileGutterWidth(file.rows),\n+ ),\n+ ]),\n+ ),\n+ );\n+ }, [parsedDiff, viewportWidth]);\n+ const reviewGutterWidthByFileId = useMemo(() => {\n+ if (parsedDiff.kind !== "files") {\n+ return new Map();\n }\n \n return new Map(\n- parsedDiff.files.map((file) => [\n- file.id,\n- file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"),\n- ]),\n+ parsedDiff.files.map((file) => [file.id, computeReviewFileGutterWidth(file.rows)]),\n );\n }, [parsedDiff]);\n- const reviewLineIndexByRowId = useMemo(() => {\n- const map = new Map();\n+ const getReviewFileHorizontalOffset = useCallback((fileId: string) => {\n+ let offset = horizontalOffsetByFileIdRef.current.get(fileId);\n+ if (!offset) {\n+ offset = makeMutable(0);\n+ horizontalOffsetByFileIdRef.current.set(fileId, offset);\n+ }\n \n- reviewLineRowsByFileId.forEach((rows) => {\n- rows.forEach((row, index) => {\n- map.set(row.id, index);\n- });\n- });\n+ return offset;\n+ }, []);\n+ useEffect(() => {\n+ const knownFileIds =\n+ parsedDiff.kind === "files" ? new Set(parsedDiff.files.map((file) => file.id)) : new Set();\n \n- return map;\n- }, [reviewLineRowsByFileId]);\n+ horizontalOffsetByFileIdRef.current.forEach((offset, fileId) => {\n+ if (!knownFileIds.has(fileId)) {\n+ horizontalOffsetByFileIdRef.current.delete(fileId);\n+ return;\n+ }\n+\n+ const contentWidth = reviewContentWidthByFileId.get(fileId) ?? viewportWidth;\n+ const gutterWidth = reviewGutterWidthByFileId.get(fileId) ?? 0;\n+ offset.value = Math.min(\n+ offset.value,\n+ Math.max(0, contentWidth - (viewportWidth - gutterWidth)),\n+ );\n+ });\n+ }, [parsedDiff, reviewContentWidthByFileId, reviewGutterWidthByFileId, viewportWidth]);\n const highlightableFiles = useMemo(() => {\n if (parsedDiff.kind !== "files") {\n return [] as ReadonlyArray;\n@@ -587,59 +854,13 @@ export function ReviewSheet() {\n );\n });\n }, [expandedFileIds, parsedDiff, revealedLargeFileIds]);\n- const highlightableFileIds = useMemo(\n- () => new Set(highlightableFiles.map((file) => file.id)),\n+ const highlightableFilesKey = useMemo(\n+ () => highlightableFiles.map((file) => `${file.id}:${file.cacheKey}`).join("\\n"),\n [highlightableFiles],\n );\n- const priorityHighlightFileIds = useMemo(() => {\n- if (parsedDiff.kind !== "files" || highlightableFiles.length === 0) {\n- return [] as ReadonlyArray;\n- }\n-\n- const fileIdsInPriorityOrder =\n- visibleFileIds.length > 0\n- ? visibleFileIds.filter((fileId) => highlightableFileIds.has(fileId))\n- : parsedDiff.files\n- .slice(0, REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT)\n- .map((file) => file.id)\n- .filter((fileId) => highlightableFileIds.has(fileId));\n-\n- if (fileIdsInPriorityOrder.length === 0) {\n- return [] as ReadonlyArray;\n- }\n-\n- const firstVisibleIndex = parsedDiff.files.findIndex(\n- (file) => file.id === fileIdsInPriorityOrder[0],\n- );\n- const lastVisibleIndex = parsedDiff.files.findIndex(\n- (file) => file.id === fileIdsInPriorityOrder[fileIdsInPriorityOrder.length - 1],\n- );\n-\n- if (firstVisibleIndex < 0 || lastVisibleIndex < 0) {\n- return fileIdsInPriorityOrder;\n- }\n-\n- const startIndex = Math.max(0, firstVisibleIndex - REVIEW_HIGHLIGHT_BACKTRACK_COUNT);\n- const endIndex = Math.min(\n- parsedDiff.files.length - 1,\n- lastVisibleIndex + REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT,\n- );\n-\n- const queuedIds: string[] = [];\n- for (let index = startIndex; index <= endIndex; index += 1) {\n- const fileId = parsedDiff.files[index]?.id;\n- if (fileId && highlightableFileIds.has(fileId)) {\n- queuedIds.push(fileId);\n- }\n- }\n-\n- return queuedIds;\n- }, [highlightableFileIds, highlightableFiles.length, parsedDiff, visibleFileIds]);\n- const viewportWidth = Math.max(width, 280);\n- const reviewListContentWidth = useMemo(\n- () => computeReviewListContentWidth(reviewListItems, viewportWidth),\n- [reviewListItems, viewportWidth],\n- );\n+ useEffect(() => {\n+ highlightableFilesRef.current = highlightableFiles;\n+ }, [highlightableFiles]);\n const loadGitDiffs = useCallback(async () => {\n if (!cwd) {\n return;\n@@ -714,100 +935,6 @@ export function ReviewSheet() {\n void loadGitDiffs();\n }, [loadGitDiffs]);\n \n- useEffect(() => {\n- selectedThemeRef.current = selectedTheme;\n- }, [selectedTheme]);\n-\n- useEffect(() => {\n- highlightableFilesByIdRef.current = new Map(highlightableFiles.map((file) => [file.id, file]));\n- }, [highlightableFiles]);\n-\n- const startHighlightQueueRunner = useCallback(function startHighlightQueueRunner() {\n- if (highlightQueueActiveRef.current) {\n- return;\n- }\n-\n- const generation = highlightQueueGenerationRef.current;\n- highlightQueueActiveRef.current = true;\n-\n- void (async () => {\n- try {\n- while (generation === highlightQueueGenerationRef.current) {\n- const nextFileId = highlightQueueRef.current.shift();\n- if (!nextFileId) {\n- break;\n- }\n-\n- const file = highlightableFilesByIdRef.current.get(nextFileId);\n- if (!file) {\n- continue;\n- }\n-\n- const theme = selectedThemeRef.current;\n- const cached = getCachedHighlightedReviewFile(file, theme);\n- if (cached) {\n- logReviewDiffDiagnostic("using cached highlighted file", {\n- fileId: file.id,\n- filePath: file.path,\n- theme,\n- });\n- setHighlightedFilesById((current) =>\n- current[file.id] === cached ? current : { ...current, [file.id]: cached },\n- );\n- continue;\n- }\n-\n- logReviewDiffDiagnostic("requesting highlighted file", {\n- fileId: file.id,\n- filePath: file.path,\n- theme,\n- });\n-\n- try {\n- await new Promise((resolve) => {\n- InteractionManager.runAfterInteractions(() => resolve());\n- });\n- const result = await highlightReviewFile(file, theme);\n- if (generation !== highlightQueueGenerationRef.current) {\n- logReviewDiffDiagnostic("discarding highlighted file after cancellation", {\n- fileId: file.id,\n- filePath: file.path,\n- });\n- return;\n- }\n-\n- logReviewDiffDiagnostic("received highlighted file", {\n- fileId: file.id,\n- filePath: file.path,\n- additionLines: result.additionLines.length,\n- deletionLines: result.deletionLines.length,\n- });\n- setHighlightedFilesById((current) => {\n- if (current[file.id] === result) {\n- return current;\n- }\n- return { ...current, [file.id]: result };\n- });\n- } catch (error) {\n- logReviewDiffDiagnostic("highlight request failed", {\n- fileId: file.id,\n- filePath: file.path,\n- error: error instanceof Error ? error.message : String(error),\n- });\n- }\n- }\n- } finally {\n- highlightQueueActiveRef.current = false;\n- if (\n- generation === highlightQueueGenerationRef.current &&\n- highlightQueueRef.current.length > 0\n- ) {\n- startHighlightQueueRunner();\n- }\n- }\n- })();\n- }, []);\n-\n useEffect(() => {\n if (reviewSections.length === 0) {\n return;\n@@ -854,15 +981,15 @@ export function ReviewSheet() {\n }\n \n updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {\n- if (existing !== undefined) {\n- const validIds = existing.filter((id) => parsedDiff.files.some((file) => file.id === id));\n- if (validIds.length === existing.length) {\n- return existing;\n- }\n- return validIds;\n+ const validIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);\n+ if (\n+ existing !== undefined &&\n+ validIds.length === existing.length &&\n+ validIds.every((id, index) => id === existing[index])\n+ ) {\n+ return existing;\n }\n-\n- return getDefaultExpandedFileIds(parsedDiff.files);\n+ return validIds;\n });\n }, [parsedDiff, reviewCache.threadKey, selectedSection?.id]);\n \n@@ -887,11 +1014,7 @@ export function ReviewSheet() {\n \n useEffect(() => {\n setHighlightedFilesById({});\n- setVisibleFileIds([]);\n- highlightQueueGenerationRef.current += 1;\n- highlightQueueRef.current = [];\n- highlightRequestedFileIdsRef.current = new Set();\n- highlightQueueActiveRef.current = false;\n+ highlightRunIdRef.current += 1;\n clearReviewHighlightFileCache();\n loggedMissingReviewTokenKeys.clear();\n logReviewDiffDiagnostic("reset highlighted files", {\n@@ -905,15 +1028,23 @@ export function ReviewSheet() {\n return;\n }\n \n+ markReviewEvent("parsed-diff-ready", {\n+ sectionId: selectedSection?.id ?? null,\n+ fileCount: parsedDiff.fileCount,\n+ additions: parsedDiff.additions,\n+ deletions: parsedDiff.deletions,\n+ renderedItems: reviewListItems.length,\n+ });\n logReviewDiffDiagnostic("parsed diff files", {\n selectedSectionId: selectedSection?.id ?? null,\n fileCount: parsedDiff.fileCount,\n renderableFileCount: parsedDiff.files.length,\n });\n- }, [parsedDiff, selectedSection?.id]);\n+ }, [parsedDiff, reviewListItems.length, selectedSection?.id]);\n \n useEffect(() => {\n- if (priorityHighlightFileIds.length === 0) {\n+ const files = highlightableFilesRef.current;\n+ if (files.length === 0) {\n logReviewDiffDiagnostic("no highlightable files", {\n selectedSectionId: selectedSection?.id ?? null,\n parsedDiffKind: parsedDiff.kind,\n@@ -922,33 +1053,98 @@ export function ReviewSheet() {\n return;\n }\n \n- const queuedFileIds: string[] = [];\n- priorityHighlightFileIds.forEach((fileId) => {\n- if (highlightRequestedFileIdsRef.current.has(fileId)) {\n- return;\n- }\n-\n- const file = highlightableFilesByIdRef.current.get(fileId);\n- if (!file) {\n- return;\n- }\n-\n- highlightRequestedFileIdsRef.current.add(fileId);\n- highlightQueueRef.current.push(fileId);\n- queuedFileIds.push(fileId);\n- });\n-\n- if (queuedFileIds.length === 0) {\n+ if (reviewHighlighter.status !== "ready") {\n+ logReviewDiffDiagnostic("waiting for highlighter provider", {\n+ selectedSectionId: selectedSection?.id ?? null,\n+ status: reviewHighlighter.status,\n+ error: reviewHighlighter.error,\n+ });\n return;\n }\n \n- logReviewDiffDiagnostic("scheduling file highlights", {\n+ const runId = highlightRunIdRef.current;\n+ let cancelled = false;\n+\n+ logReviewDiffDiagnostic("streaming file highlights", {\n selectedSectionId: selectedSection?.id ?? null,\n- fileCount: queuedFileIds.length,\n- fileIds: queuedFileIds,\n+ fileCount: files.length,\n });\n- startHighlightQueueRunner();\n- }, [parsedDiff.kind, priorityHighlightFileIds, selectedSection?.id, startHighlightQueueRunner]);\n+\n+ void (async () => {\n+ for (const file of files) {\n+ if (cancelled || runId !== highlightRunIdRef.current) {\n+ return;\n+ }\n+\n+ const cached = getCachedHighlightedReviewFile(file, selectedTheme);\n+ if (cached) {\n+ setHighlightedFilesById((current) =>\n+ current[file.id] === cached ? current : { ...current, [file.id]: cached },\n+ );\n+ continue;\n+ }\n+\n+ logReviewDiffDiagnostic("requesting highlighted file", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme: selectedTheme,\n+ });\n+\n+ try {\n+ const highlightStartedAt = performance.now();\n+ const result = await streamHighlightReviewFile(file, selectedTheme, (progress) => {\n+ if (cancelled || runId !== highlightRunIdRef.current) {\n+ return;\n+ }\n+\n+ if (!progress.complete) {\n+ return;\n+ }\n+\n+ logReviewDiffDiagnostic("received streamed highlighted file", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ highlightedLineCount: progress.highlightedLineCount,\n+ durationMs: Math.round(performance.now() - highlightStartedAt),\n+ });\n+ });\n+\n+ if (cancelled || runId !== highlightRunIdRef.current) {\n+ return;\n+ }\n+\n+ logReviewDiffDiagnostic("received highlighted file", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ additionLines: result.additionLines.length,\n+ deletionLines: result.deletionLines.length,\n+ });\n+ setHighlightedFilesById((current) =>\n+ current[file.id] === result ? current : { ...current, [file.id]: result },\n+ );\n+ } catch (error) {\n+ logReviewDiffDiagnostic("highlight request failed", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ error: error instanceof Error ? error.message : String(error),\n+ });\n+ }\n+\n+ await waitForReviewDelay(0);\n+ }\n+ })();\n+\n+ return () => {\n+ cancelled = true;\n+ };\n+ }, [\n+ highlightableFilesKey,\n+ parsedDiff.kind,\n+ reviewHighlighter.error,\n+ reviewHighlighter.status,\n+ selectedSection?.id,\n+ selectedTheme,\n+ ]);\n \n const refreshSelectedSection = useCallback(async () => {\n if (!selectedSection) {\n@@ -968,20 +1164,68 @@ export function ReviewSheet() {\n \n const handleToggleExpandedFile = useCallback(\n (fileId: string) => {\n- if (!reviewCache.threadKey || !selectedSection?.id || parsedDiff.kind !== "files") {\n+ if (!selectedSection?.id || parsedDiff.kind !== "files") {\n return;\n }\n \n- updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {\n- const currentIds = existing ?? getDefaultExpandedFileIds(parsedDiff.files);\n- return currentIds.includes(fileId)\n+ const sectionId = selectedSection.id;\n+\n+ setLocalExpandedFileIdsBySection((current) => {\n+ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, current[sectionId]);\n+ const nextIds = currentIds.includes(fileId)\n ? currentIds.filter((id) => id !== fileId)\n : [...currentIds, fileId];\n+\n+ return {\n+ ...current,\n+ [sectionId]: nextIds,\n+ };\n });\n+\n+ if (reviewCache.threadKey) {\n+ updateReviewExpandedFileIds(reviewCache.threadKey, sectionId, (existing) => {\n+ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);\n+ return currentIds.includes(fileId)\n+ ? currentIds.filter((id) => id !== fileId)\n+ : [...currentIds, fileId];\n+ });\n+ }\n },\n [parsedDiff, reviewCache.threadKey, selectedSection?.id],\n );\n \n+ const handleToggleViewedFile = useCallback(\n+ (fileId: string) => {\n+ if (!selectedSection?.id) {\n+ return;\n+ }\n+\n+ const sectionId = selectedSection.id;\n+\n+ setLocalViewedFileIdsBySection((current) => {\n+ const currentIds = current[sectionId] ?? [];\n+ const nextIds = currentIds.includes(fileId)\n+ ? currentIds.filter((id) => id !== fileId)\n+ : [...currentIds, fileId];\n+\n+ return {\n+ ...current,\n+ [sectionId]: nextIds,\n+ };\n+ });\n+\n+ if (reviewCache.threadKey) {\n+ updateReviewViewedFileIds(reviewCache.threadKey, sectionId, (existing) => {\n+ const currentIds = existing ?? [];\n+ return currentIds.includes(fileId)\n+ ? currentIds.filter((id) => id !== fileId)\n+ : [...currentIds, fileId];\n+ });\n+ }\n+ },\n+ [reviewCache.threadKey, selectedSection?.id],\n+ );\n+\n const handleRevealLargeDiff = useCallback(\n (fileId: string) => {\n if (!reviewCache.threadKey || !selectedSection?.id) {\n@@ -1080,35 +1324,6 @@ export function ReviewSheet() {\n \n return <>{children};\n }, [error, parsedDiffNotice]);\n- const stickyHeaderIndices = useMemo(() => {\n- const itemOffset = listHeader ? 1 : 0;\n-\n- return reviewListItems.flatMap((item, index) =>\n- item.kind === "file-header" ? [index + itemOffset] : [],\n- );\n- }, [listHeader, reviewListItems]);\n-\n- const viewabilityConfigRef = useRef({\n- itemVisiblePercentThreshold: 10,\n- });\n- const onViewableItemsChangedRef = useRef(\n- ({\n- viewableItems,\n- }: {\n- readonly viewableItems: Array>;\n- readonly changed: Array>;\n- }) => {\n- const nextVisibleFileIds = Array.from(\n- new Set(\n- viewableItems\n- .filter((token) => token.isViewable && token.item !== undefined)\n- .map((token) => token.item.fileId),\n- ),\n- );\n-\n- setVisibleFileIds(nextVisibleFileIds);\n- },\n- );\n \n const renderReviewListItem = useCallback(\n ({ item }: ListRenderItemInfo) => {\n@@ -1116,112 +1331,142 @@ export function ReviewSheet() {\n return null;\n }\n \n+ let renderedItem: ReactElement | null = null;\n switch (item.kind) {\n case "file-header":\n- return (\n+ renderedItem = (\n \n );\n+ break;\n case "file-suppressed":\n- return (\n+ renderedItem = (\n \n );\n- case "hunk":\n- return (\n- \n+ break;\n+ case "hunk": {\n+ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth;\n+ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0;\n+\n+ renderedItem = (\n+ }\n+ viewportWidth={viewportWidth}\n+ >\n+ \n+ \n );\n+ break;\n+ }\n case "line": {\n- const file = reviewFileById.get(item.fileId);\n- if (!file) {\n- return null;\n- }\n-\n- const fileLineRows = reviewLineRowsByFileId.get(file.id) ?? [];\n- const lineIndex = reviewLineIndexByRowId.get(item.row.id);\n- if (lineIndex === undefined) {\n- return null;\n- }\n-\n+ const fileLineRows = reviewLineRowsByFileId.get(item.file.id) ?? [];\n const pendingSelectionForFile =\n pendingCommentSelection &&\n pendingCommentSelection.sectionTitle === selectedSection.title &&\n- pendingCommentSelection.filePath === file.path\n+ pendingCommentSelection.filePath === item.file.path\n ? pendingCommentSelection\n : null;\n const selectedTargetForFile =\n activeCommentTarget &&\n activeCommentTarget.sectionTitle === selectedSection.title &&\n- activeCommentTarget.filePath === file.path\n+ activeCommentTarget.filePath === item.file.path\n ? activeCommentTarget\n : null;\n const highlightedFile =\n- highlightedFilesById[file.id] ??\n- getCachedHighlightedReviewFile(file, selectedTheme) ??\n+ deferredHighlightedFilesById[item.file.id] ??\n+ getCachedHighlightedReviewFile(item.file, selectedTheme) ??\n null;\n+ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth;\n+ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0;\n \n if (highlightedFile === null) {\n- const missingTokenKey = `${selectedSection.id}:${file.id}`;\n+ const missingTokenKey = `${selectedSection.id}:${item.file.id}`;\n if (!loggedMissingReviewTokenKeys.has(missingTokenKey)) {\n loggedMissingReviewTokenKeys.add(missingTokenKey);\n logReviewDiffDiagnostic("rendering file without tokens", {\n sectionId: selectedSection.id,\n- fileId: file.id,\n- filePath: file.path,\n- highlightedFileKnownInState: highlightedFilesById[file.id] !== undefined,\n+ fileId: item.file.id,\n+ filePath: item.file.path,\n+ highlightedFileKnownInState:\n+ deferredHighlightedFilesById[item.file.id] !== undefined,\n });\n }\n }\n \n const selectionState =\n- pendingSelectionForFile?.anchorIndex === lineIndex\n+ pendingSelectionForFile?.anchorIndex === item.lineIndex\n ? ("anchor" as const)\n : selectedTargetForFile &&\n- lineIndex >= selectedTargetForFile.startIndex &&\n- lineIndex <= selectedTargetForFile.endIndex\n+ item.lineIndex >= selectedTargetForFile.startIndex &&\n+ item.lineIndex <= selectedTargetForFile.endIndex\n ? ("selected" as const)\n : null;\n \n- return (\n- \n- handlePressLine({\n- sectionTitle: selectedSection.title,\n- filePath: file.path,\n- lines: fileLineRows,\n- lineIndex,\n- })\n- }\n- onStartRangeSelection={() =>\n- handleStartRangeSelection({\n- sectionTitle: selectedSection.title,\n- filePath: file.path,\n- lines: fileLineRows,\n- lineIndex,\n- })\n+ renderedItem = (\n+ \n }\n- />\n+ viewportWidth={viewportWidth}\n+ >\n+ \n+ handlePressLine({\n+ sectionTitle: selectedSection.title,\n+ filePath: item.file.path,\n+ lines: fileLineRows,\n+ lineIndex: item.lineIndex,\n+ })\n+ }\n+ onStartRangeSelection={() =>\n+ handleStartRangeSelection({\n+ sectionTitle: selectedSection.title,\n+ filePath: item.file.path,\n+ lines: fileLineRows,\n+ lineIndex: item.lineIndex,\n+ })\n+ }\n+ />\n+ \n );\n+ break;\n }\n }\n+\n+ return renderedItem;\n },\n [\n activeCommentTarget,\n@@ -1229,14 +1474,17 @@ export function ReviewSheet() {\n handleRevealLargeDiff,\n handleStartRangeSelection,\n handleToggleExpandedFile,\n- highlightedFilesById,\n+ handleToggleViewedFile,\n+ getReviewFileHorizontalOffset,\n+ deferredHighlightedFilesById,\n pendingCommentSelection,\n- reviewFileById,\n- reviewLineIndexByRowId,\n+ reviewContentWidthByFileId,\n+ reviewGutterWidthByFileId,\n reviewLineRowsByFileId,\n- reviewListContentWidth,\n selectedSection,\n selectedTheme,\n+ viewedFileIdSet,\n+ viewportWidth,\n ],\n );\n \n@@ -1374,27 +1622,20 @@ export function ReviewSheet() {\n \n {selectedSection && parsedDiff.kind === "files" ? (\n item.id}\n+ initialNumToRender={20}\n+ maxToRenderPerBatch={20}\n+ updateCellsBatchingPeriod={16}\n+ windowSize={5}\n+ removeClippedSubviews={false}\n keyboardShouldPersistTaps="handled"\n ListHeaderComponent={listHeader}\n- stickyHeaderIndices={stickyHeaderIndices}\n- removeClippedSubviews={false}\n- initialNumToRender={24}\n- maxToRenderPerBatch={16}\n- updateCellsBatchingPeriod={16}\n- windowSize={10}\n- scrollEventThrottle={16}\n- onViewableItemsChanged={onViewableItemsChangedRef.current}\n- viewabilityConfig={viewabilityConfigRef.current}\n contentContainerStyle={{\n- paddingTop: REVIEW_HEADER_SPACING,\n+ paddingTop: topContentInset + REVIEW_HEADER_SPACING,\n paddingBottom: Math.max(insets.bottom, 18) + 18,\n }}\n />\ndiff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.ts\nindex f7a5c4125..eb6bf6973 100644\n--- a/apps/mobile/src/features/review/shikiReviewHighlighter.ts\n+++ b/apps/mobile/src/features/review/shikiReviewHighlighter.ts\n@@ -1,5 +1,14 @@\n import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";\n import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";\n+import bashLanguage from "@shikijs/langs/bash";\n+import javascriptLanguage from "@shikijs/langs/javascript";\n+import jsonLanguage from "@shikijs/langs/json";\n+import jsxLanguage from "@shikijs/langs/jsx";\n+import tsxLanguage from "@shikijs/langs/tsx";\n+import typescriptLanguage from "@shikijs/langs/typescript";\n+import yamlLanguage from "@shikijs/langs/yaml";\n+import githubDarkDefault from "@shikijs/themes/github-dark-default";\n+import githubLightDefault from "@shikijs/themes/github-light-default";\n import { getFiletypeFromFileName } from "@pierre/diffs/utils";\n \n import {\n@@ -11,6 +20,7 @@ import type { ReviewRenderableFile, ReviewRenderableLineRow } from "./reviewMode\n import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs";\n \n export type ReviewDiffTheme = "light" | "dark";\n+export type { ReviewHighlighterEngine };\n \n export interface ReviewHighlightedToken {\n content: string;\n@@ -24,12 +34,19 @@ export interface ReviewHighlightedFile {\n readonly deletionLines: ReadonlyArray>;\n }\n \n+export interface ReviewHighlightFileProgress {\n+ readonly highlightedFile: ReviewHighlightedFile;\n+ readonly complete: boolean;\n+ readonly highlightedLineCount: number;\n+}\n+\n const SHIKI_THEME_NAME_BY_SCHEME = {\n light: "github-light-default",\n dark: "github-dark-default",\n } as const;\n const REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE =\n- process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? "javascript";\n+ process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ??\n+ (process.env.NODE_ENV === "test" ? "javascript" : "native");\n const REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE = resolveReviewHighlighterEnginePreference(\n REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE,\n );\n@@ -38,12 +55,30 @@ const REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE = resolveReviewHighlighterBooleanF\n false,\n );\n const REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT = 8;\n-const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 40;\n-const REVIEW_HIGHLIGHT_CHUNK_SIZE = 20;\n+const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 8;\n+const REVIEW_HIGHLIGHT_CHUNK_SIZE = 200;\n const REVIEW_TOKENIZE_MAX_LINE_LENGTH = 1_000;\n const highlightCache = new Map>();\n const resolvedHighlightCache = new Map();\n-const loadedLanguages = new Set(["text"]);\n+const REVIEW_INITIAL_LANGUAGE_MODULES = [\n+ bashLanguage,\n+ javascriptLanguage,\n+ jsonLanguage,\n+ jsxLanguage,\n+ tsxLanguage,\n+ typescriptLanguage,\n+ yamlLanguage,\n+] satisfies Parameters[0]["langs"];\n+const loadedLanguages = new Set([\n+ "text",\n+ "bash",\n+ "javascript",\n+ "json",\n+ "jsx",\n+ "tsx",\n+ "typescript",\n+ "yaml",\n+]);\n const languageLoadingPromises = new Map>();\n const languageImports: Partial Promise>> = {\n javascript: () => import("@shikijs/langs/javascript"),\n@@ -215,21 +250,13 @@ function joinPatchLines(lines: ReadonlyArray): string {\n \n function waitForNextFrame(): Promise {\n return new Promise((resolve) => {\n- if (typeof requestAnimationFrame === "function") {\n- requestAnimationFrame(() => resolve());\n- return;\n- }\n-\n setTimeout(resolve, 0);\n });\n }\n \n async function getHighlighter(): Promise {\n if (!highlighterPromise) {\n- const configuredHighlighterPromise = Promise.all([\n- import("@shikijs/themes/github-light-default"),\n- import("@shikijs/themes/github-dark-default"),\n- ]).then(async ([lightThemeModule, darkThemeModule]) => {\n+ const configuredHighlighterPromise = (async () => {\n let nativeEngineAvailable = false;\n \n logReviewHighlighterDiagnostic("initializing", {\n@@ -238,12 +265,11 @@ async function getHighlighter(): Promise {\n resultCacheDisabled: REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE,\n });\n \n- const themes = [lightThemeModule.default, darkThemeModule.default];\n+ const themes = [githubLightDefault, githubDarkDefault];\n \n if (REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE !== "javascript") {\n try {\n const nativeEngineModule = await import("react-native-shiki-engine");\n- logReviewHighlighterDiagnostic("imported react-native-shiki-engine");\n nativeEngineAvailable = nativeEngineModule.isNativeEngineAvailable();\n logReviewHighlighterDiagnostic("checked native engine availability", {\n nativeEngineAvailable,\n@@ -253,7 +279,7 @@ async function getHighlighter(): Promise {\n logReviewHighlighterDiagnostic("creating native regex engine");\n const highlighter = await createHighlighterCore({\n themes,\n- langs: [],\n+ langs: REVIEW_INITIAL_LANGUAGE_MODULES,\n engine: nativeEngineModule.createNativeEngine(),\n });\n logReviewHighlighterDiagnostic("using native engine");\n@@ -281,7 +307,7 @@ async function getHighlighter(): Promise {\n );\n const highlighter = await createHighlighterCore({\n themes,\n- langs: [],\n+ langs: REVIEW_INITIAL_LANGUAGE_MODULES,\n engine: createJavaScriptRegexEngine(),\n });\n logReviewHighlighterDiagnostic("using javascript engine", {\n@@ -291,7 +317,7 @@ async function getHighlighter(): Promise {\n highlighter,\n engine,\n };\n- });\n+ })();\n \n highlighterPromise = configuredHighlighterPromise\n .then((result) => result.highlighter)\n@@ -316,11 +342,52 @@ export async function getActiveReviewHighlighterEngine(): Promise {\n+ await getHighlighter();\n+}\n+\n+export async function prepareReviewHighlighterLanguages(\n+ languages: ReadonlyArray,\n+): Promise {\n+ const highlighter = await getHighlighter();\n+ await Promise.all(\n+ languages.map(async (language) => {\n+ const candidate = resolveLanguageAlias(language);\n+ if (candidate === "text" || !(candidate in languageImports)) {\n+ return;\n+ }\n+\n+ await loadSingleLanguage(highlighter, candidate);\n+ }),\n+ );\n+}\n+\n function resolveLanguageAlias(language: string): string {\n const normalized = language.toLowerCase();\n return languageAliases[normalized] ?? normalized;\n }\n \n+function resolveLoadedLanguageFromPath(\n+ path: string,\n+ languageHint: string | null = null,\n+): string | null {\n+ const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);\n+ if (!detectedLanguage) {\n+ return "text";\n+ }\n+\n+ const candidate = resolveLanguageAlias(detectedLanguage);\n+ if (candidate === "text" || candidate === "ansi") {\n+ return "text";\n+ }\n+\n+ if (!(candidate in languageImports)) {\n+ return "text";\n+ }\n+\n+ return loadedLanguages.has(candidate) ? candidate : null;\n+}\n+\n async function loadSingleLanguage(\n highlighter: HighlighterCore,\n language: string,\n@@ -360,6 +427,11 @@ async function resolveLanguageFromPath(\n path: string,\n languageHint: string | null = null,\n ): Promise {\n+ const loadedLanguage = resolveLoadedLanguageFromPath(path, languageHint);\n+ if (loadedLanguage) {\n+ return loadedLanguage;\n+ }\n+\n const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);\n if (!detectedLanguage) {\n return "text";\n@@ -374,8 +446,12 @@ async function resolveLanguageFromPath(\n return "text";\n }\n \n+ if (loadedLanguages.has(candidate)) {\n+ return candidate;\n+ }\n+\n const highlighter = await getHighlighter();\n- const loaded = await loadSingleLanguage(highlighter, resolveLanguageAlias(candidate));\n+ const loaded = await loadSingleLanguage(highlighter, candidate);\n if (!loaded) {\n return "text";\n }\n@@ -384,7 +460,10 @@ async function resolveLanguageFromPath(\n }\n \n async function resolveLanguage(file: ReviewRenderableFile): Promise {\n- return resolveLanguageFromPath(file.path, file.languageHint);\n+ return (\n+ resolveLoadedLanguageFromPath(file.path, file.languageHint) ??\n+ (await resolveLanguageFromPath(file.path, file.languageHint))\n+ );\n }\n \n function normalizeHighlightedLines(\n@@ -399,6 +478,18 @@ function normalizeHighlightedLines(\n );\n }\n \n+function makePlainHighlightedLines(\n+ lines: ReadonlyArray,\n+): ReadonlyArray> {\n+ return lines.map((line) => [\n+ {\n+ content: stripTrailingNewline(line),\n+ color: null,\n+ fontStyle: null,\n+ },\n+ ]);\n+}\n+\n function applyWordAltDiffHighlightsToFile(\n file: ReviewRenderableFile,\n highlighted: ReviewHighlightedFile,\n@@ -594,6 +685,67 @@ async function highlightLines(\n return highlightedLines;\n }\n \n+async function highlightPatchLinesInChunks(input: {\n+ readonly lines: ReadonlyArray;\n+ readonly language: string;\n+ readonly theme: string;\n+ readonly onChunk: (\n+ startIndex: number,\n+ tokens: ReadonlyArray>,\n+ ) => void;\n+}): Promise>> {\n+ if (input.lines.length === 0) {\n+ return [];\n+ }\n+\n+ const highlighter = await getHighlighter();\n+ const highlightedLines: Array> = [];\n+\n+ for (\n+ let startIndex = 0;\n+ startIndex < input.lines.length;\n+ startIndex += REVIEW_HIGHLIGHT_CHUNK_SIZE\n+ ) {\n+ const lineChunk = input.lines.slice(startIndex, startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE);\n+ const chunkTokens: Array> = [];\n+ const tokenizableLines: string[] = [];\n+ const tokenizableIndexes: number[] = [];\n+\n+ lineChunk.forEach((line, index) => {\n+ const strippedLine = stripTrailingNewline(line);\n+ if (strippedLine.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH) {\n+ chunkTokens[index] = [{ content: strippedLine, color: null, fontStyle: null }];\n+ return;\n+ }\n+\n+ tokenizableIndexes.push(index);\n+ tokenizableLines.push(strippedLine);\n+ });\n+\n+ if (tokenizableLines.length > 0) {\n+ const tokenLines = highlighter.codeToTokensBase(tokenizableLines.join("\\n"), {\n+ lang: input.language,\n+ theme: input.theme,\n+ });\n+ const normalizedTokenLines = normalizeHighlightedLines(tokenLines);\n+\n+ tokenizableIndexes.forEach((chunkIndex, tokenIndex) => {\n+ chunkTokens[chunkIndex] = normalizedTokenLines[tokenIndex] ?? [];\n+ });\n+ }\n+\n+ const completedChunk = lineChunk.map((_, index) => chunkTokens[index] ?? []);\n+ highlightedLines.push(...completedChunk);\n+ input.onChunk(startIndex, completedChunk);\n+\n+ if (startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE < input.lines.length) {\n+ await waitForNextFrame();\n+ }\n+ }\n+\n+ return highlightedLines;\n+}\n+\n function getHighlightCacheKey(file: ReviewRenderableFile, theme: ReviewDiffTheme): string {\n return `${SHIKI_THEME_NAME_BY_SCHEME[theme]}:${file.cacheKey}`;\n }\n@@ -667,7 +819,28 @@ export async function highlightReviewFile(\n deletionLineCount: file.deletionLines.length,\n rowCount: file.rows.length,\n });\n- const language = await resolveLanguage(file);\n+ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);\n+ const language = loadedLanguage ?? (await resolveLanguage(file));\n+ if (language === "text") {\n+ const highlighted = applyWordAltDiffHighlightsToFile(file, {\n+ additionLines: makePlainHighlightedLines(file.additionLines),\n+ deletionLines: makePlainHighlightedLines(file.deletionLines),\n+ });\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ storeResolvedHighlightedFile(cacheKey, highlighted);\n+ }\n+ logReviewHighlighterDiagnostic("file highlight complete", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ language,\n+ highlightedAdditionLineCount: highlighted.additionLines.length,\n+ highlightedDeletionLineCount: highlighted.deletionLines.length,\n+ durationMs: Date.now() - startedAt,\n+ });\n+ return highlighted;\n+ }\n+\n const additionLines = await highlightLines(\n joinPatchLines(file.additionLines),\n language,\n@@ -707,6 +880,113 @@ export async function highlightReviewFile(\n });\n }\n \n+export async function streamHighlightReviewFile(\n+ file: ReviewRenderableFile,\n+ theme: ReviewDiffTheme,\n+ onProgress: (progress: ReviewHighlightFileProgress) => void,\n+): Promise {\n+ const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[theme];\n+ const cacheKey = getHighlightCacheKey(file, theme);\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ const resolved = resolvedHighlightCache.get(cacheKey);\n+ if (resolved) {\n+ onProgress({\n+ highlightedFile: resolved,\n+ complete: true,\n+ highlightedLineCount: resolved.additionLines.length + resolved.deletionLines.length,\n+ });\n+ return resolved;\n+ }\n+ }\n+\n+ const startedAt = Date.now();\n+ logReviewHighlighterDiagnostic("file stream highlight start", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ additionLineCount: file.additionLines.length,\n+ deletionLineCount: file.deletionLines.length,\n+ rowCount: file.rows.length,\n+ });\n+\n+ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);\n+ const language = loadedLanguage ?? (await resolveLanguage(file));\n+ if (language === "text") {\n+ const highlighted = applyWordAltDiffHighlightsToFile(file, {\n+ additionLines: makePlainHighlightedLines(file.additionLines),\n+ deletionLines: makePlainHighlightedLines(file.deletionLines),\n+ });\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ storeResolvedHighlightedFile(cacheKey, highlighted);\n+ }\n+ onProgress({\n+ highlightedFile: highlighted,\n+ complete: true,\n+ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,\n+ });\n+ logReviewHighlighterDiagnostic("file stream highlight complete", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ language,\n+ highlightedAdditionLineCount: highlighted.additionLines.length,\n+ highlightedDeletionLineCount: highlighted.deletionLines.length,\n+ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,\n+ durationMs: Date.now() - startedAt,\n+ });\n+ return highlighted;\n+ }\n+\n+ const additionLines: Array> = [];\n+ const deletionLines: Array> = [];\n+ let highlightedLineCount = 0;\n+\n+ await highlightPatchLinesInChunks({\n+ lines: file.additionLines,\n+ language,\n+ theme: shikiTheme,\n+ onChunk: (startIndex, tokens) => {\n+ tokens.forEach((lineTokens, index) => {\n+ additionLines[startIndex + index] = lineTokens;\n+ });\n+ highlightedLineCount += tokens.length;\n+ },\n+ });\n+ await waitForNextFrame();\n+ await highlightPatchLinesInChunks({\n+ lines: file.deletionLines,\n+ language,\n+ theme: shikiTheme,\n+ onChunk: (startIndex, tokens) => {\n+ tokens.forEach((lineTokens, index) => {\n+ deletionLines[startIndex + index] = lineTokens;\n+ });\n+ highlightedLineCount += tokens.length;\n+ },\n+ });\n+\n+ const highlighted = applyWordAltDiffHighlightsToFile(file, { additionLines, deletionLines });\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ storeResolvedHighlightedFile(cacheKey, highlighted);\n+ }\n+ onProgress({\n+ highlightedFile: highlighted,\n+ complete: true,\n+ highlightedLineCount,\n+ });\n+ logReviewHighlighterDiagnostic("file stream highlight complete", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ language,\n+ highlightedAdditionLineCount: highlighted.additionLines.length,\n+ highlightedDeletionLineCount: highlighted.deletionLines.length,\n+ highlightedLineCount,\n+ durationMs: Date.now() - startedAt,\n+ });\n+ return highlighted;\n+}\n+\n export async function highlightReviewSelectedLines(input: {\n readonly filePath: string;\n readonly lines: ReadonlyArray;\n@@ -717,7 +997,9 @@ export async function highlightReviewSelectedLines(input: {\n return {};\n }\n \n- const language = await resolveLanguageFromPath(input.filePath, input.languageHint ?? null);\n+ const loadedLanguage = resolveLoadedLanguageFromPath(input.filePath, input.languageHint ?? null);\n+ const language =\n+ loadedLanguage ?? (await resolveLanguageFromPath(input.filePath, input.languageHint ?? null));\n const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[input.theme];\n const additionLikeLines = input.lines\n .filter((line) => line.change !== "delete")\n', + }, + { + id: "large", + label: "Large", + filename: "review-large.diff", + lineCount: 3208, + diff: 'diff --git a/apps/mobile/package.json b/apps/mobile/package.json\nindex 08329e1d4..36ac93a0f 100644\n--- a/apps/mobile/package.json\n+++ b/apps/mobile/package.json\n@@ -30,6 +30,7 @@\n "config:dev": "APP_VARIANT=development expo config",\n "config:preview": "APP_VARIANT=preview expo config",\n "config:prod": "APP_VARIANT=production expo config",\n+ "profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",\n "test": "vitest run",\n "typecheck": "tsc --noEmit"\n },\ndiff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx\nindex f153db701..f6095c051 100644\n--- a/apps/mobile/src/app/index.tsx\n+++ b/apps/mobile/src/app/index.tsx\n@@ -43,28 +43,50 @@ export default function HomeRouteScreen() {\n headerTintColor: iconColor,\n headerTitle: "",\n headerRight: () => (\n- router.push("/connections")}\n- hitSlop={8}\n- style={{\n- flexDirection: "row",\n- alignItems: "center",\n- gap: 8,\n- paddingHorizontal: 4,\n- paddingVertical: 4,\n- }}\n- >\n- \n- \n+ router.push("/debug/syntax-highlight")}\n+ hitSlop={8}\n style={{\n- fontFamily: "DMSans_700Bold",\n- fontSize: 12,\n- color: secondaryFg,\n+ borderRadius: 999,\n+ backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)",\n+ paddingHorizontal: 10,\n+ paddingVertical: 5,\n }}\n >\n- {CONNECTION_LABEL[connectionState]}\n- \n- \n+ \n+ Debug\n+ \n+ \n+ router.push("/connections")}\n+ hitSlop={8}\n+ style={{\n+ flexDirection: "row",\n+ alignItems: "center",\n+ gap: 8,\n+ paddingHorizontal: 4,\n+ paddingVertical: 4,\n+ }}\n+ >\n+ \n+ \n+ {CONNECTION_LABEL[connectionState]}\n+ \n+ \n+ \n ),\n headerSearchBarOptions: {\n placeholder: "Search threads",\ndiff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\nindex 84c48c6ed..ee993ee7c 100644\n--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n@@ -1,5 +1,10 @@\n+import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";\n import { ReviewSheet } from "../../../../features/review/ReviewSheet";\n \n export default function ReviewRoute() {\n- return ;\n+ return (\n+ \n+ \n+ \n+ );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\nindex 076a2286d..9a173224a 100644\n--- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n@@ -2,15 +2,8 @@ import { useLocalSearchParams, useRouter } from "expo-router";\n import { SymbolView } from "expo-symbols";\n import { TextInputWrapper } from "expo-paste-input";\n import { useEffect, useMemo, useState } from "react";\n-import {\n- KeyboardAvoidingView,\n- Platform,\n- Pressable,\n- ScrollView,\n- View,\n- useColorScheme,\n- useWindowDimensions,\n-} from "react-native";\n+import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native";\n+import { KeyboardStickyView } from "react-native-keyboard-controller";\n import { useSafeAreaInsets } from "react-native-safe-area-context";\n import ImageViewing from "react-native-image-viewing";\n \n@@ -34,6 +27,7 @@ import {\n import {\n changeTone,\n DiffTokenText,\n+ REVIEW_DIFF_LINE_HEIGHT,\n REVIEW_MONO_FONT_FAMILY,\n ReviewChangeBar,\n } from "./reviewDiffRendering";\n@@ -44,7 +38,6 @@ import {\n } from "./shikiReviewHighlighter";\n \n const REVIEW_COMMENT_PREVIEW_MAX_LINES = 5;\n-const REVIEW_COMMENT_LINE_HEIGHT = 26;\n \n export function ReviewCommentComposerSheet() {\n const router = useRouter();\n@@ -84,8 +77,8 @@ export function ReviewCommentComposerSheet() {\n ? `Lines ${firstNumber}-${lastNumber}`\n : `${selectedLines.length} lines selected`;\n const previewHeight = Math.max(\n- Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_COMMENT_LINE_HEIGHT,\n- REVIEW_COMMENT_LINE_HEIGHT,\n+ Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_DIFF_LINE_HEIGHT,\n+ REVIEW_DIFF_LINE_HEIGHT,\n );\n const previewViewportWidth = Math.max(width - 40, 280);\n const handleNativePaste = useNativePaste((uris) => {\n@@ -143,17 +136,13 @@ export function ReviewCommentComposerSheet() {\n }\n \n return (\n- \n+ \n \n \n@@ -219,7 +208,7 @@ export function ReviewCommentComposerSheet() {\n \n \n \n \n-\n- \n- void handlePickImages()} />\n- \n- {\n- if (!target || !environmentId || !threadId || commentText.trim().length === 0) {\n- return;\n- }\n-\n- appendReviewCommentToDraft({\n- environmentId,\n- threadId,\n- text: formatReviewCommentContext(target, commentText),\n- attachments,\n- });\n- setAttachments([]);\n- clearReviewCommentTarget();\n- router.dismiss();\n- }}\n- />\n- \n \n )}\n \n+ {target ? (\n+ \n+ \n+ void handlePickImages()} />\n+ \n+ {\n+ if (!target || !environmentId || !threadId || commentText.trim().length === 0) {\n+ return;\n+ }\n+\n+ appendReviewCommentToDraft({\n+ environmentId,\n+ threadId,\n+ text: formatReviewCommentContext(target, commentText),\n+ attachments,\n+ });\n+ setAttachments([]);\n+ clearReviewCommentTarget();\n+ router.dismiss();\n+ }}\n+ />\n+ \n+ \n+ ) : null}\n \n- \n+ \n );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx\nindex 82c28e81e..e148a8da2 100644\n--- a/apps/mobile/src/features/review/ReviewSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewSheet.tsx\n@@ -1,17 +1,31 @@\n import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts";\n+import { Gesture, GestureDetector } from "react-native-gesture-handler";\n+import Animated, {\n+ makeMutable,\n+ type SharedValue,\n+ useAnimatedStyle,\n+ useSharedValue,\n+} from "react-native-reanimated";\n import { useLocalSearchParams, useRouter } from "expo-router";\n import Stack from "expo-router/stack";\n import { SymbolView } from "expo-symbols";\n-import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react";\n+import {\n+ memo,\n+ type ReactElement,\n+ useCallback,\n+ useDeferredValue,\n+ useEffect,\n+ useMemo,\n+ useRef,\n+ useState,\n+} from "react";\n import {\n ActivityIndicator,\n FlatList,\n- InteractionManager,\n type ListRenderItemInfo,\n Pressable,\n ScrollView,\n Text as NativeText,\n- type ViewToken,\n useColorScheme,\n useWindowDimensions,\n View,\n@@ -32,6 +46,7 @@ import {\n setReviewTurnDiff,\n updateReviewExpandedFileIds,\n updateReviewRevealedLargeFileIds,\n+ updateReviewViewedFileIds,\n useReviewCacheForThread,\n } from "./reviewState";\n import {\n@@ -45,11 +60,12 @@ import {\n type ReviewParsedDiff,\n type ReviewRenderableFile,\n type ReviewRenderableLineRow,\n+ type ReviewRenderableRow,\n } from "./reviewModel";\n import {\n clearReviewHighlightFileCache,\n getCachedHighlightedReviewFile,\n- highlightReviewFile,\n+ streamHighlightReviewFile,\n type ReviewDiffTheme,\n type ReviewHighlightedFile,\n type ReviewHighlightedToken,\n@@ -67,9 +83,12 @@ import {\n import {\n changeTone,\n DiffTokenText,\n+ REVIEW_DIFF_LINE_HEIGHT,\n REVIEW_MONO_FONT_FAMILY,\n ReviewChangeBar,\n } from "./reviewDiffRendering";\n+import { markReviewEvent, measureReviewWork } from "./reviewPerf";\n+import { useReviewHighlighterStatus } from "./ReviewHighlighterProvider";\n \n interface PendingCommentSelection {\n readonly sectionTitle: string;\n@@ -87,14 +106,21 @@ interface ReviewLineActionInput {\n \n const IOS_NAV_BAR_HEIGHT = 44;\n const REVIEW_HEADER_SPACING = 0;\n-const REVIEW_LINE_GUTTER_WIDTH = 62;\n+const REVIEW_CHANGE_BAR_WIDTH = 5;\n+const REVIEW_MIN_LINE_NUMBER_WIDTH = 27;\n+const REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE = 8;\n+const REVIEW_LINE_NUMBER_HORIZONTAL_PADDING = 6;\n const REVIEW_CHARACTER_WIDTH_ESTIMATE = 8.4;\n const REVIEW_MAX_CONTENT_WIDTH = 4_800;\n-const REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT = 2;\n-const REVIEW_HIGHLIGHT_BACKTRACK_COUNT = 0;\n-const REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT = 1;\n+const REVIEW_HUNK_ROW_HEIGHT = 35;\n+const REVIEW_FILE_HEADER_HEIGHT = 43;\n+const REVIEW_SUPPRESSED_ROW_HEIGHT = 92;\n const loggedMissingReviewTokenKeys = new Set();\n \n+function waitForReviewDelay(durationMs: number): Promise {\n+ return new Promise((resolve) => setTimeout(resolve, durationMs));\n+}\n+\n function isReviewDiffDebugLoggingEnabled(): boolean {\n return typeof __DEV__ !== "undefined" ? __DEV__ : false;\n }\n@@ -113,33 +139,27 @@ function logReviewDiffDiagnostic(message: string, details?: Record,\n+function computeReviewFileContentWidth(\n+ rows: ReadonlyArray,\n viewportWidth: number,\n+ gutterWidth: number,\n ): number {\n let maxTextLength = 0;\n \n- items.forEach((item) => {\n- switch (item.kind) {\n- case "file-header":\n- maxTextLength = Math.max(\n- maxTextLength,\n- item.file.path.length,\n- item.file.previousPath?.length ?? 0,\n- );\n- break;\n- case "file-suppressed":\n- maxTextLength = Math.max(maxTextLength, item.message.length, item.actionLabel?.length ?? 0);\n- break;\n- case "hunk":\n- maxTextLength = Math.max(\n- maxTextLength,\n- item.row.header.length + (item.row.context ? item.row.context.length + 1 : 0),\n- );\n- break;\n- case "line":\n- maxTextLength = Math.max(maxTextLength, item.row.content.length);\n- break;\n+ rows.forEach((row) => {\n+ if (row.kind === "hunk") {\n+ maxTextLength = Math.max(\n+ maxTextLength,\n+ row.header.length + (row.context ? row.context.length + 1 : 0),\n+ );\n+ return;\n }\n+\n+ maxTextLength = Math.max(maxTextLength, row.content.length);\n });\n \n return Math.max(\n- viewportWidth,\n+ Math.max(0, viewportWidth - gutterWidth),\n Math.min(\n REVIEW_MAX_CONTENT_WIDTH,\n- Math.ceil(REVIEW_LINE_GUTTER_WIDTH + 48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE),\n+ Math.ceil(48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE),\n ),\n );\n }\n \n+function computeReviewFileGutterWidth(rows: ReadonlyArray): number {\n+ let maxLineNumber = 0;\n+\n+ rows.forEach((row) => {\n+ if (row.kind !== "line") {\n+ return;\n+ }\n+\n+ maxLineNumber = Math.max(maxLineNumber, row.oldLineNumber ?? 0, row.newLineNumber ?? 0);\n+ });\n+\n+ const digitCount = Math.max(1, String(maxLineNumber).length);\n+ const lineNumberWidth = Math.max(\n+ REVIEW_MIN_LINE_NUMBER_WIDTH,\n+ digitCount * REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE + REVIEW_LINE_NUMBER_HORIZONTAL_PADDING,\n+ );\n+\n+ return REVIEW_CHANGE_BAR_WIDTH + lineNumberWidth;\n+}\n+\n function getDefaultExpandedFileIds(\n files: ReadonlyArray,\n ): ReadonlyArray {\n return files.map((file) => file.id);\n }\n \n+function getValidReviewExpandedFileIds(\n+ files: ReadonlyArray,\n+ cachedExpandedFileIds: ReadonlyArray | undefined,\n+): ReadonlyArray {\n+ if (cachedExpandedFileIds === undefined) {\n+ return getDefaultExpandedFileIds(files);\n+ }\n+\n+ const fileIdSet = new Set(files.map((file) => file.id));\n+ return cachedExpandedFileIds.filter((id) => fileIdSet.has(id));\n+}\n+\n function getHighlightedTokensForLine(\n line: ReviewRenderableLineRow,\n highlightedFile: ReviewHighlightedFile | null,\n@@ -252,16 +293,13 @@ const ReviewLineRow = memo(function ReviewLineRow(props: {\n delayLongPress={220}\n onLongPress={props.onStartRangeSelection}\n onPress={props.onComment}\n- style={{ minWidth: props.viewportWidth }}\n+ style={{\n+ height: REVIEW_DIFF_LINE_HEIGHT,\n+ width: props.viewportWidth,\n+ overflow: "hidden",\n+ }}\n >\n- \n- \n- {lineNumber ?? ""}\n- \n- \n+ \n \n+ \n+ \n+ {props.lineNumber ?? ""}\n+ \n+ \n+ );\n+});\n+\n+const ReviewHunkGutter = memo(function ReviewHunkGutter(props: { readonly gutterWidth: number }) {\n+ return (\n+ \n+ );\n+});\n+\n const ReviewFileCard = memo(function ReviewFileCard(props: {\n readonly file: ReviewRenderableFile;\n readonly fileId: string;\n readonly expanded: boolean;\n+ readonly viewed: boolean;\n readonly viewportWidth: number;\n readonly onToggleFile: (fileId: string) => void;\n+ readonly onToggleViewed: (fileId: string) => void;\n }) {\n- const chrome = getFileHeaderChrome(props.file.changeType);\n+ const { expanded, file, fileId, onToggleFile, onToggleViewed, viewed, viewportWidth } = props;\n+ const chrome = getFileHeaderChrome(file.changeType);\n+ const iconColor = String(useThemeColor("--color-icon-muted"));\n+ const handleToggleFile = useCallback(() => {\n+ onToggleFile(fileId);\n+ }, [fileId, onToggleFile]);\n+ const handleToggleViewed = useCallback(() => {\n+ onToggleViewed(fileId);\n+ }, [fileId, onToggleViewed]);\n \n return (\n \n- props.onToggleFile(props.fileId)}>\n- \n- \n- \n- \n- \n- \n- \n- \n- \n- {props.file.path}\n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ {file.path}\n+ \n+ {file.previousPath && file.previousPath !== file.path ? (\n+ \n+ {file.previousPath}\n \n- {props.file.previousPath && props.file.previousPath !== props.file.path ? (\n- \n- {props.file.previousPath}\n- \n+ ) : null}\n+ \n+ \n+ \n+ \n+ -{file.deletions}\n+ \n+ \n+ +{file.additions}\n+ \n+ \n+ \n+ {viewed ? (\n+ \n ) : null}\n \n- \n- \n- \n- +{props.file.additions}\n- \n- \n- -{props.file.deletions}\n+ \n+ Viewed\n \n- \n+ \n \n- \n+ \n \n );\n });\n@@ -342,7 +453,11 @@ const ReviewFileSuppressedBody = memo(function ReviewFileSuppressedBody(props: {\n return (\n \n {props.message}\n {props.actionLabel && props.onLoadDiffFile ? (\n@@ -364,10 +479,13 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: {\n }) {\n return (\n \n- \n+ \n {props.header}\n {props.context ? ` ${props.context}` : ""}\n \n@@ -375,6 +493,61 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: {\n );\n });\n \n+const ReviewCodePanRow = memo(function ReviewCodePanRow(props: {\n+ readonly contentWidth: number;\n+ readonly horizontalOffset: SharedValue;\n+ readonly gutterWidth?: number;\n+ readonly viewportWidth: number;\n+ readonly leftGutter?: ReactElement;\n+ readonly children: ReactElement;\n+}) {\n+ const {\n+ children,\n+ contentWidth,\n+ gutterWidth = 0,\n+ horizontalOffset,\n+ leftGutter,\n+ viewportWidth,\n+ } = props;\n+ const dragStartOffset = useSharedValue(0);\n+ const visibleContentWidth = leftGutter ? viewportWidth - gutterWidth : viewportWidth;\n+ const maxOffset = Math.max(0, contentWidth - visibleContentWidth);\n+\n+ const panGesture = useMemo(\n+ () =>\n+ Gesture.Pan()\n+ .activeOffsetX([-8, 8])\n+ .failOffsetY([-10, 10])\n+ .onBegin(() => {\n+ dragStartOffset.value = horizontalOffset.value;\n+ })\n+ .onUpdate((event) => {\n+ "worklet";\n+ const nextOffset = dragStartOffset.value - event.translationX;\n+ horizontalOffset.value = Math.min(maxOffset, Math.max(0, nextOffset));\n+ }),\n+ [dragStartOffset, horizontalOffset, maxOffset],\n+ );\n+\n+ const contentStyle = useAnimatedStyle(\n+ () => ({\n+ transform: [{ translateX: -horizontalOffset.value }],\n+ }),\n+ [horizontalOffset],\n+ );\n+\n+ return (\n+ \n+ \n+ {leftGutter ?? null}\n+ \n+ {children}\n+ \n+ \n+ \n+ );\n+});\n+\n const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) {\n return (\n \n@@ -454,15 +627,19 @@ export function ReviewSheet() {\n const [highlightedFilesById, setHighlightedFilesById] = useState<\n Record\n >({});\n- const [visibleFileIds, setVisibleFileIds] = useState>([]);\n+ const deferredHighlightedFilesById = useDeferredValue(highlightedFilesById);\n+ const [localExpandedFileIdsBySection, setLocalExpandedFileIdsBySection] = useState<\n+ Record>\n+ >({});\n+ const [localViewedFileIdsBySection, setLocalViewedFileIdsBySection] = useState<\n+ Record>\n+ >({});\n const activeCommentTarget = useReviewCommentTarget();\n const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme;\n- const highlightQueueRef = useRef([]);\n- const highlightRequestedFileIdsRef = useRef>(new Set());\n- const highlightQueueGenerationRef = useRef(0);\n- const highlightQueueActiveRef = useRef(false);\n- const highlightableFilesByIdRef = useRef>(new Map());\n- const selectedThemeRef = useRef(selectedTheme);\n+ const reviewHighlighter = useReviewHighlighterStatus();\n+ const highlightRunIdRef = useRef(0);\n+ const highlightableFilesRef = useRef>([]);\n+ const horizontalOffsetByFileIdRef = useRef>>(new Map());\n const { selectedThreadCwd } = useSelectedThreadWorktree();\n \n const cwd = selectedThreadCwd;\n@@ -498,11 +675,13 @@ export function ReviewSheet() {\n const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;\n const parsedDiff = useMemo(\n () =>\n- getCachedReviewParsedDiff({\n- threadKey: reviewCache.threadKey,\n- sectionId: selectedSection?.id ?? null,\n- diff: selectedSection?.diff,\n- }),\n+ measureReviewWork("parse-diff", () =>\n+ getCachedReviewParsedDiff({\n+ threadKey: reviewCache.threadKey,\n+ sectionId: selectedSection?.id ?? null,\n+ diff: selectedSection?.diff,\n+ }),\n+ ),\n [reviewCache.threadKey, selectedSection?.diff, selectedSection?.id],\n );\n const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]);\n@@ -510,14 +689,53 @@ export function ReviewSheet() {\n () => countReviewCommentContexts(draftMessage),\n [draftMessage],\n );\n+ const viewportWidth = Math.max(width, 280);\n+\n+ useEffect(() => {\n+ if (!selectedSection?.id || parsedDiff.kind !== "files") {\n+ return;\n+ }\n+\n+ setLocalExpandedFileIdsBySection((current) => {\n+ if (current[selectedSection.id] !== undefined) {\n+ return current;\n+ }\n+\n+ return {\n+ ...current,\n+ [selectedSection.id]: getValidReviewExpandedFileIds(\n+ parsedDiff.files,\n+ reviewCache.expandedFileIdsBySection[selectedSection.id],\n+ ),\n+ };\n+ });\n+\n+ setLocalViewedFileIdsBySection((current) => {\n+ if (current[selectedSection.id] !== undefined) {\n+ return current;\n+ }\n+\n+ return {\n+ ...current,\n+ [selectedSection.id]: reviewCache.viewedFileIdsBySection[selectedSection.id] ?? [],\n+ };\n+ });\n+ }, [\n+ parsedDiff,\n+ reviewCache.expandedFileIdsBySection,\n+ reviewCache.viewedFileIdsBySection,\n+ selectedSection?.id,\n+ ]);\n \n const expandedFileIds = useMemo(\n () =>\n selectedSection?.id && parsedDiff.kind === "files"\n- ? (reviewCache.expandedFileIdsBySection[selectedSection.id] ??\n- getDefaultExpandedFileIds(parsedDiff.files))\n+ ? getValidReviewExpandedFileIds(\n+ parsedDiff.files,\n+ localExpandedFileIdsBySection[selectedSection.id],\n+ )\n : [],\n- [parsedDiff, reviewCache.expandedFileIdsBySection, selectedSection?.id],\n+ [localExpandedFileIdsBySection, parsedDiff, selectedSection?.id],\n );\n const revealedLargeFileIds = useMemo(\n () =>\n@@ -526,47 +744,96 @@ export function ReviewSheet() {\n : [],\n [reviewCache.revealedLargeFileIdsBySection, selectedSection?.id],\n );\n+ const viewedFileIds = useMemo(\n+ () => (selectedSection?.id ? (localViewedFileIdsBySection[selectedSection.id] ?? []) : []),\n+ [localViewedFileIdsBySection, selectedSection?.id],\n+ );\n+ const viewedFileIdSet = useMemo(() => new Set(viewedFileIds), [viewedFileIds]);\n const reviewListItems = useMemo(\n () =>\n selectedSection && parsedDiff.kind === "files"\n- ? buildReviewListItems({\n- files: parsedDiff.files,\n- expandedFileIds,\n- revealedLargeFileIds,\n- })\n+ ? measureReviewWork("build-list-items", () =>\n+ buildReviewListItems({\n+ files: parsedDiff.files,\n+ expandedFileIds,\n+ revealedLargeFileIds,\n+ }),\n+ )\n : [],\n [expandedFileIds, parsedDiff, revealedLargeFileIds, selectedSection],\n );\n- const reviewFileById = useMemo(() => {\n+ const reviewLineRowsByFileId = useMemo(() => {\n if (parsedDiff.kind !== "files") {\n- return new Map();\n+ return new Map>();\n }\n \n- return new Map(parsedDiff.files.map((file) => [file.id, file] as const));\n+ return measureReviewWork(\n+ "index-line-rows",\n+ () =>\n+ new Map(\n+ parsedDiff.files.map((file) => [\n+ file.id,\n+ file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"),\n+ ]),\n+ ),\n+ );\n }, [parsedDiff]);\n- const reviewLineRowsByFileId = useMemo(() => {\n+ const reviewContentWidthByFileId = useMemo(() => {\n if (parsedDiff.kind !== "files") {\n- return new Map>();\n+ return new Map();\n+ }\n+\n+ return measureReviewWork(\n+ "measure-file-widths",\n+ () =>\n+ new Map(\n+ parsedDiff.files.map((file) => [\n+ file.id,\n+ computeReviewFileContentWidth(\n+ file.rows,\n+ viewportWidth,\n+ computeReviewFileGutterWidth(file.rows),\n+ ),\n+ ]),\n+ ),\n+ );\n+ }, [parsedDiff, viewportWidth]);\n+ const reviewGutterWidthByFileId = useMemo(() => {\n+ if (parsedDiff.kind !== "files") {\n+ return new Map();\n }\n \n return new Map(\n- parsedDiff.files.map((file) => [\n- file.id,\n- file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"),\n- ]),\n+ parsedDiff.files.map((file) => [file.id, computeReviewFileGutterWidth(file.rows)]),\n );\n }, [parsedDiff]);\n- const reviewLineIndexByRowId = useMemo(() => {\n- const map = new Map();\n+ const getReviewFileHorizontalOffset = useCallback((fileId: string) => {\n+ let offset = horizontalOffsetByFileIdRef.current.get(fileId);\n+ if (!offset) {\n+ offset = makeMutable(0);\n+ horizontalOffsetByFileIdRef.current.set(fileId, offset);\n+ }\n \n- reviewLineRowsByFileId.forEach((rows) => {\n- rows.forEach((row, index) => {\n- map.set(row.id, index);\n- });\n- });\n+ return offset;\n+ }, []);\n+ useEffect(() => {\n+ const knownFileIds =\n+ parsedDiff.kind === "files" ? new Set(parsedDiff.files.map((file) => file.id)) : new Set();\n \n- return map;\n- }, [reviewLineRowsByFileId]);\n+ horizontalOffsetByFileIdRef.current.forEach((offset, fileId) => {\n+ if (!knownFileIds.has(fileId)) {\n+ horizontalOffsetByFileIdRef.current.delete(fileId);\n+ return;\n+ }\n+\n+ const contentWidth = reviewContentWidthByFileId.get(fileId) ?? viewportWidth;\n+ const gutterWidth = reviewGutterWidthByFileId.get(fileId) ?? 0;\n+ offset.value = Math.min(\n+ offset.value,\n+ Math.max(0, contentWidth - (viewportWidth - gutterWidth)),\n+ );\n+ });\n+ }, [parsedDiff, reviewContentWidthByFileId, reviewGutterWidthByFileId, viewportWidth]);\n const highlightableFiles = useMemo(() => {\n if (parsedDiff.kind !== "files") {\n return [] as ReadonlyArray;\n@@ -587,59 +854,13 @@ export function ReviewSheet() {\n );\n });\n }, [expandedFileIds, parsedDiff, revealedLargeFileIds]);\n- const highlightableFileIds = useMemo(\n- () => new Set(highlightableFiles.map((file) => file.id)),\n+ const highlightableFilesKey = useMemo(\n+ () => highlightableFiles.map((file) => `${file.id}:${file.cacheKey}`).join("\\n"),\n [highlightableFiles],\n );\n- const priorityHighlightFileIds = useMemo(() => {\n- if (parsedDiff.kind !== "files" || highlightableFiles.length === 0) {\n- return [] as ReadonlyArray;\n- }\n-\n- const fileIdsInPriorityOrder =\n- visibleFileIds.length > 0\n- ? visibleFileIds.filter((fileId) => highlightableFileIds.has(fileId))\n- : parsedDiff.files\n- .slice(0, REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT)\n- .map((file) => file.id)\n- .filter((fileId) => highlightableFileIds.has(fileId));\n-\n- if (fileIdsInPriorityOrder.length === 0) {\n- return [] as ReadonlyArray;\n- }\n-\n- const firstVisibleIndex = parsedDiff.files.findIndex(\n- (file) => file.id === fileIdsInPriorityOrder[0],\n- );\n- const lastVisibleIndex = parsedDiff.files.findIndex(\n- (file) => file.id === fileIdsInPriorityOrder[fileIdsInPriorityOrder.length - 1],\n- );\n-\n- if (firstVisibleIndex < 0 || lastVisibleIndex < 0) {\n- return fileIdsInPriorityOrder;\n- }\n-\n- const startIndex = Math.max(0, firstVisibleIndex - REVIEW_HIGHLIGHT_BACKTRACK_COUNT);\n- const endIndex = Math.min(\n- parsedDiff.files.length - 1,\n- lastVisibleIndex + REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT,\n- );\n-\n- const queuedIds: string[] = [];\n- for (let index = startIndex; index <= endIndex; index += 1) {\n- const fileId = parsedDiff.files[index]?.id;\n- if (fileId && highlightableFileIds.has(fileId)) {\n- queuedIds.push(fileId);\n- }\n- }\n-\n- return queuedIds;\n- }, [highlightableFileIds, highlightableFiles.length, parsedDiff, visibleFileIds]);\n- const viewportWidth = Math.max(width, 280);\n- const reviewListContentWidth = useMemo(\n- () => computeReviewListContentWidth(reviewListItems, viewportWidth),\n- [reviewListItems, viewportWidth],\n- );\n+ useEffect(() => {\n+ highlightableFilesRef.current = highlightableFiles;\n+ }, [highlightableFiles]);\n const loadGitDiffs = useCallback(async () => {\n if (!cwd) {\n return;\n@@ -714,100 +935,6 @@ export function ReviewSheet() {\n void loadGitDiffs();\n }, [loadGitDiffs]);\n \n- useEffect(() => {\n- selectedThemeRef.current = selectedTheme;\n- }, [selectedTheme]);\n-\n- useEffect(() => {\n- highlightableFilesByIdRef.current = new Map(highlightableFiles.map((file) => [file.id, file]));\n- }, [highlightableFiles]);\n-\n- const startHighlightQueueRunner = useCallback(function startHighlightQueueRunner() {\n- if (highlightQueueActiveRef.current) {\n- return;\n- }\n-\n- const generation = highlightQueueGenerationRef.current;\n- highlightQueueActiveRef.current = true;\n-\n- void (async () => {\n- try {\n- while (generation === highlightQueueGenerationRef.current) {\n- const nextFileId = highlightQueueRef.current.shift();\n- if (!nextFileId) {\n- break;\n- }\n-\n- const file = highlightableFilesByIdRef.current.get(nextFileId);\n- if (!file) {\n- continue;\n- }\n-\n- const theme = selectedThemeRef.current;\n- const cached = getCachedHighlightedReviewFile(file, theme);\n- if (cached) {\n- logReviewDiffDiagnostic("using cached highlighted file", {\n- fileId: file.id,\n- filePath: file.path,\n- theme,\n- });\n- setHighlightedFilesById((current) =>\n- current[file.id] === cached ? current : { ...current, [file.id]: cached },\n- );\n- continue;\n- }\n-\n- logReviewDiffDiagnostic("requesting highlighted file", {\n- fileId: file.id,\n- filePath: file.path,\n- theme,\n- });\n-\n- try {\n- await new Promise((resolve) => {\n- InteractionManager.runAfterInteractions(() => resolve());\n- });\n- const result = await highlightReviewFile(file, theme);\n- if (generation !== highlightQueueGenerationRef.current) {\n- logReviewDiffDiagnostic("discarding highlighted file after cancellation", {\n- fileId: file.id,\n- filePath: file.path,\n- });\n- return;\n- }\n-\n- logReviewDiffDiagnostic("received highlighted file", {\n- fileId: file.id,\n- filePath: file.path,\n- additionLines: result.additionLines.length,\n- deletionLines: result.deletionLines.length,\n- });\n- setHighlightedFilesById((current) => {\n- if (current[file.id] === result) {\n- return current;\n- }\n- return { ...current, [file.id]: result };\n- });\n- } catch (error) {\n- logReviewDiffDiagnostic("highlight request failed", {\n- fileId: file.id,\n- filePath: file.path,\n- error: error instanceof Error ? error.message : String(error),\n- });\n- }\n- }\n- } finally {\n- highlightQueueActiveRef.current = false;\n- if (\n- generation === highlightQueueGenerationRef.current &&\n- highlightQueueRef.current.length > 0\n- ) {\n- startHighlightQueueRunner();\n- }\n- }\n- })();\n- }, []);\n-\n useEffect(() => {\n if (reviewSections.length === 0) {\n return;\n@@ -854,15 +981,15 @@ export function ReviewSheet() {\n }\n \n updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {\n- if (existing !== undefined) {\n- const validIds = existing.filter((id) => parsedDiff.files.some((file) => file.id === id));\n- if (validIds.length === existing.length) {\n- return existing;\n- }\n- return validIds;\n+ const validIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);\n+ if (\n+ existing !== undefined &&\n+ validIds.length === existing.length &&\n+ validIds.every((id, index) => id === existing[index])\n+ ) {\n+ return existing;\n }\n-\n- return getDefaultExpandedFileIds(parsedDiff.files);\n+ return validIds;\n });\n }, [parsedDiff, reviewCache.threadKey, selectedSection?.id]);\n \n@@ -887,11 +1014,7 @@ export function ReviewSheet() {\n \n useEffect(() => {\n setHighlightedFilesById({});\n- setVisibleFileIds([]);\n- highlightQueueGenerationRef.current += 1;\n- highlightQueueRef.current = [];\n- highlightRequestedFileIdsRef.current = new Set();\n- highlightQueueActiveRef.current = false;\n+ highlightRunIdRef.current += 1;\n clearReviewHighlightFileCache();\n loggedMissingReviewTokenKeys.clear();\n logReviewDiffDiagnostic("reset highlighted files", {\n@@ -905,15 +1028,23 @@ export function ReviewSheet() {\n return;\n }\n \n+ markReviewEvent("parsed-diff-ready", {\n+ sectionId: selectedSection?.id ?? null,\n+ fileCount: parsedDiff.fileCount,\n+ additions: parsedDiff.additions,\n+ deletions: parsedDiff.deletions,\n+ renderedItems: reviewListItems.length,\n+ });\n logReviewDiffDiagnostic("parsed diff files", {\n selectedSectionId: selectedSection?.id ?? null,\n fileCount: parsedDiff.fileCount,\n renderableFileCount: parsedDiff.files.length,\n });\n- }, [parsedDiff, selectedSection?.id]);\n+ }, [parsedDiff, reviewListItems.length, selectedSection?.id]);\n \n useEffect(() => {\n- if (priorityHighlightFileIds.length === 0) {\n+ const files = highlightableFilesRef.current;\n+ if (files.length === 0) {\n logReviewDiffDiagnostic("no highlightable files", {\n selectedSectionId: selectedSection?.id ?? null,\n parsedDiffKind: parsedDiff.kind,\n@@ -922,33 +1053,98 @@ export function ReviewSheet() {\n return;\n }\n \n- const queuedFileIds: string[] = [];\n- priorityHighlightFileIds.forEach((fileId) => {\n- if (highlightRequestedFileIdsRef.current.has(fileId)) {\n- return;\n- }\n-\n- const file = highlightableFilesByIdRef.current.get(fileId);\n- if (!file) {\n- return;\n- }\n-\n- highlightRequestedFileIdsRef.current.add(fileId);\n- highlightQueueRef.current.push(fileId);\n- queuedFileIds.push(fileId);\n- });\n-\n- if (queuedFileIds.length === 0) {\n+ if (reviewHighlighter.status !== "ready") {\n+ logReviewDiffDiagnostic("waiting for highlighter provider", {\n+ selectedSectionId: selectedSection?.id ?? null,\n+ status: reviewHighlighter.status,\n+ error: reviewHighlighter.error,\n+ });\n return;\n }\n \n- logReviewDiffDiagnostic("scheduling file highlights", {\n+ const runId = highlightRunIdRef.current;\n+ let cancelled = false;\n+\n+ logReviewDiffDiagnostic("streaming file highlights", {\n selectedSectionId: selectedSection?.id ?? null,\n- fileCount: queuedFileIds.length,\n- fileIds: queuedFileIds,\n+ fileCount: files.length,\n });\n- startHighlightQueueRunner();\n- }, [parsedDiff.kind, priorityHighlightFileIds, selectedSection?.id, startHighlightQueueRunner]);\n+\n+ void (async () => {\n+ for (const file of files) {\n+ if (cancelled || runId !== highlightRunIdRef.current) {\n+ return;\n+ }\n+\n+ const cached = getCachedHighlightedReviewFile(file, selectedTheme);\n+ if (cached) {\n+ setHighlightedFilesById((current) =>\n+ current[file.id] === cached ? current : { ...current, [file.id]: cached },\n+ );\n+ continue;\n+ }\n+\n+ logReviewDiffDiagnostic("requesting highlighted file", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme: selectedTheme,\n+ });\n+\n+ try {\n+ const highlightStartedAt = performance.now();\n+ const result = await streamHighlightReviewFile(file, selectedTheme, (progress) => {\n+ if (cancelled || runId !== highlightRunIdRef.current) {\n+ return;\n+ }\n+\n+ if (!progress.complete) {\n+ return;\n+ }\n+\n+ logReviewDiffDiagnostic("received streamed highlighted file", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ highlightedLineCount: progress.highlightedLineCount,\n+ durationMs: Math.round(performance.now() - highlightStartedAt),\n+ });\n+ });\n+\n+ if (cancelled || runId !== highlightRunIdRef.current) {\n+ return;\n+ }\n+\n+ logReviewDiffDiagnostic("received highlighted file", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ additionLines: result.additionLines.length,\n+ deletionLines: result.deletionLines.length,\n+ });\n+ setHighlightedFilesById((current) =>\n+ current[file.id] === result ? current : { ...current, [file.id]: result },\n+ );\n+ } catch (error) {\n+ logReviewDiffDiagnostic("highlight request failed", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ error: error instanceof Error ? error.message : String(error),\n+ });\n+ }\n+\n+ await waitForReviewDelay(0);\n+ }\n+ })();\n+\n+ return () => {\n+ cancelled = true;\n+ };\n+ }, [\n+ highlightableFilesKey,\n+ parsedDiff.kind,\n+ reviewHighlighter.error,\n+ reviewHighlighter.status,\n+ selectedSection?.id,\n+ selectedTheme,\n+ ]);\n \n const refreshSelectedSection = useCallback(async () => {\n if (!selectedSection) {\n@@ -968,20 +1164,68 @@ export function ReviewSheet() {\n \n const handleToggleExpandedFile = useCallback(\n (fileId: string) => {\n- if (!reviewCache.threadKey || !selectedSection?.id || parsedDiff.kind !== "files") {\n+ if (!selectedSection?.id || parsedDiff.kind !== "files") {\n return;\n }\n \n- updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {\n- const currentIds = existing ?? getDefaultExpandedFileIds(parsedDiff.files);\n- return currentIds.includes(fileId)\n+ const sectionId = selectedSection.id;\n+\n+ setLocalExpandedFileIdsBySection((current) => {\n+ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, current[sectionId]);\n+ const nextIds = currentIds.includes(fileId)\n ? currentIds.filter((id) => id !== fileId)\n : [...currentIds, fileId];\n+\n+ return {\n+ ...current,\n+ [sectionId]: nextIds,\n+ };\n });\n+\n+ if (reviewCache.threadKey) {\n+ updateReviewExpandedFileIds(reviewCache.threadKey, sectionId, (existing) => {\n+ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);\n+ return currentIds.includes(fileId)\n+ ? currentIds.filter((id) => id !== fileId)\n+ : [...currentIds, fileId];\n+ });\n+ }\n },\n [parsedDiff, reviewCache.threadKey, selectedSection?.id],\n );\n \n+ const handleToggleViewedFile = useCallback(\n+ (fileId: string) => {\n+ if (!selectedSection?.id) {\n+ return;\n+ }\n+\n+ const sectionId = selectedSection.id;\n+\n+ setLocalViewedFileIdsBySection((current) => {\n+ const currentIds = current[sectionId] ?? [];\n+ const nextIds = currentIds.includes(fileId)\n+ ? currentIds.filter((id) => id !== fileId)\n+ : [...currentIds, fileId];\n+\n+ return {\n+ ...current,\n+ [sectionId]: nextIds,\n+ };\n+ });\n+\n+ if (reviewCache.threadKey) {\n+ updateReviewViewedFileIds(reviewCache.threadKey, sectionId, (existing) => {\n+ const currentIds = existing ?? [];\n+ return currentIds.includes(fileId)\n+ ? currentIds.filter((id) => id !== fileId)\n+ : [...currentIds, fileId];\n+ });\n+ }\n+ },\n+ [reviewCache.threadKey, selectedSection?.id],\n+ );\n+\n const handleRevealLargeDiff = useCallback(\n (fileId: string) => {\n if (!reviewCache.threadKey || !selectedSection?.id) {\n@@ -1080,35 +1324,6 @@ export function ReviewSheet() {\n \n return <>{children};\n }, [error, parsedDiffNotice]);\n- const stickyHeaderIndices = useMemo(() => {\n- const itemOffset = listHeader ? 1 : 0;\n-\n- return reviewListItems.flatMap((item, index) =>\n- item.kind === "file-header" ? [index + itemOffset] : [],\n- );\n- }, [listHeader, reviewListItems]);\n-\n- const viewabilityConfigRef = useRef({\n- itemVisiblePercentThreshold: 10,\n- });\n- const onViewableItemsChangedRef = useRef(\n- ({\n- viewableItems,\n- }: {\n- readonly viewableItems: Array>;\n- readonly changed: Array>;\n- }) => {\n- const nextVisibleFileIds = Array.from(\n- new Set(\n- viewableItems\n- .filter((token) => token.isViewable && token.item !== undefined)\n- .map((token) => token.item.fileId),\n- ),\n- );\n-\n- setVisibleFileIds(nextVisibleFileIds);\n- },\n- );\n \n const renderReviewListItem = useCallback(\n ({ item }: ListRenderItemInfo) => {\n@@ -1116,112 +1331,142 @@ export function ReviewSheet() {\n return null;\n }\n \n+ let renderedItem: ReactElement | null = null;\n switch (item.kind) {\n case "file-header":\n- return (\n+ renderedItem = (\n \n );\n+ break;\n case "file-suppressed":\n- return (\n+ renderedItem = (\n \n );\n- case "hunk":\n- return (\n- \n+ break;\n+ case "hunk": {\n+ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth;\n+ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0;\n+\n+ renderedItem = (\n+ }\n+ viewportWidth={viewportWidth}\n+ >\n+ \n+ \n );\n+ break;\n+ }\n case "line": {\n- const file = reviewFileById.get(item.fileId);\n- if (!file) {\n- return null;\n- }\n-\n- const fileLineRows = reviewLineRowsByFileId.get(file.id) ?? [];\n- const lineIndex = reviewLineIndexByRowId.get(item.row.id);\n- if (lineIndex === undefined) {\n- return null;\n- }\n-\n+ const fileLineRows = reviewLineRowsByFileId.get(item.file.id) ?? [];\n const pendingSelectionForFile =\n pendingCommentSelection &&\n pendingCommentSelection.sectionTitle === selectedSection.title &&\n- pendingCommentSelection.filePath === file.path\n+ pendingCommentSelection.filePath === item.file.path\n ? pendingCommentSelection\n : null;\n const selectedTargetForFile =\n activeCommentTarget &&\n activeCommentTarget.sectionTitle === selectedSection.title &&\n- activeCommentTarget.filePath === file.path\n+ activeCommentTarget.filePath === item.file.path\n ? activeCommentTarget\n : null;\n const highlightedFile =\n- highlightedFilesById[file.id] ??\n- getCachedHighlightedReviewFile(file, selectedTheme) ??\n+ deferredHighlightedFilesById[item.file.id] ??\n+ getCachedHighlightedReviewFile(item.file, selectedTheme) ??\n null;\n+ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth;\n+ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0;\n \n if (highlightedFile === null) {\n- const missingTokenKey = `${selectedSection.id}:${file.id}`;\n+ const missingTokenKey = `${selectedSection.id}:${item.file.id}`;\n if (!loggedMissingReviewTokenKeys.has(missingTokenKey)) {\n loggedMissingReviewTokenKeys.add(missingTokenKey);\n logReviewDiffDiagnostic("rendering file without tokens", {\n sectionId: selectedSection.id,\n- fileId: file.id,\n- filePath: file.path,\n- highlightedFileKnownInState: highlightedFilesById[file.id] !== undefined,\n+ fileId: item.file.id,\n+ filePath: item.file.path,\n+ highlightedFileKnownInState:\n+ deferredHighlightedFilesById[item.file.id] !== undefined,\n });\n }\n }\n \n const selectionState =\n- pendingSelectionForFile?.anchorIndex === lineIndex\n+ pendingSelectionForFile?.anchorIndex === item.lineIndex\n ? ("anchor" as const)\n : selectedTargetForFile &&\n- lineIndex >= selectedTargetForFile.startIndex &&\n- lineIndex <= selectedTargetForFile.endIndex\n+ item.lineIndex >= selectedTargetForFile.startIndex &&\n+ item.lineIndex <= selectedTargetForFile.endIndex\n ? ("selected" as const)\n : null;\n \n- return (\n- \n- handlePressLine({\n- sectionTitle: selectedSection.title,\n- filePath: file.path,\n- lines: fileLineRows,\n- lineIndex,\n- })\n- }\n- onStartRangeSelection={() =>\n- handleStartRangeSelection({\n- sectionTitle: selectedSection.title,\n- filePath: file.path,\n- lines: fileLineRows,\n- lineIndex,\n- })\n+ renderedItem = (\n+ \n }\n- />\n+ viewportWidth={viewportWidth}\n+ >\n+ \n+ handlePressLine({\n+ sectionTitle: selectedSection.title,\n+ filePath: item.file.path,\n+ lines: fileLineRows,\n+ lineIndex: item.lineIndex,\n+ })\n+ }\n+ onStartRangeSelection={() =>\n+ handleStartRangeSelection({\n+ sectionTitle: selectedSection.title,\n+ filePath: item.file.path,\n+ lines: fileLineRows,\n+ lineIndex: item.lineIndex,\n+ })\n+ }\n+ />\n+ \n );\n+ break;\n }\n }\n+\n+ return renderedItem;\n },\n [\n activeCommentTarget,\n@@ -1229,14 +1474,17 @@ export function ReviewSheet() {\n handleRevealLargeDiff,\n handleStartRangeSelection,\n handleToggleExpandedFile,\n- highlightedFilesById,\n+ handleToggleViewedFile,\n+ getReviewFileHorizontalOffset,\n+ deferredHighlightedFilesById,\n pendingCommentSelection,\n- reviewFileById,\n- reviewLineIndexByRowId,\n+ reviewContentWidthByFileId,\n+ reviewGutterWidthByFileId,\n reviewLineRowsByFileId,\n- reviewListContentWidth,\n selectedSection,\n selectedTheme,\n+ viewedFileIdSet,\n+ viewportWidth,\n ],\n );\n \n@@ -1374,27 +1622,20 @@ export function ReviewSheet() {\n \n {selectedSection && parsedDiff.kind === "files" ? (\n item.id}\n+ initialNumToRender={20}\n+ maxToRenderPerBatch={20}\n+ updateCellsBatchingPeriod={16}\n+ windowSize={5}\n+ removeClippedSubviews={false}\n keyboardShouldPersistTaps="handled"\n ListHeaderComponent={listHeader}\n- stickyHeaderIndices={stickyHeaderIndices}\n- removeClippedSubviews={false}\n- initialNumToRender={24}\n- maxToRenderPerBatch={16}\n- updateCellsBatchingPeriod={16}\n- windowSize={10}\n- scrollEventThrottle={16}\n- onViewableItemsChanged={onViewableItemsChangedRef.current}\n- viewabilityConfig={viewabilityConfigRef.current}\n contentContainerStyle={{\n- paddingTop: REVIEW_HEADER_SPACING,\n+ paddingTop: topContentInset + REVIEW_HEADER_SPACING,\n paddingBottom: Math.max(insets.bottom, 18) + 18,\n }}\n />\ndiff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx\nindex d61924a62..3f2ae0160 100644\n--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx\n+++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx\n@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({\n default: "monospace",\n });\n \n+export const REVIEW_DIFF_LINE_HEIGHT = 26;\n+const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2;\n+\n export function renderVisibleWhitespace(value: string): string {\n const expandedTabs = value.replace(/\\t/g, " ");\n return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\\u00A0"));\n@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string |\n export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) {\n if (props.change === "delete") {\n return (\n- \n- \n- {Array.from({ length: 6 }, (_, index) => (\n- \n+ \n+ \n+ {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => (\n+ \n+ \n+ \n+ \n ))}\n \n \n@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo\n }\n \n return (\n- \n+ \n \n \n );\n@@ -63,6 +69,7 @@ export function DiffTokenText(props: {\n if (!props.tokens || props.tokens.length === 0) {\n return (\n {\n- it("defaults invalid values to javascript", () => {\n- expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("javascript");\n- expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("javascript");\n+ it("defaults invalid values to native", () => {\n+ expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("native");\n+ expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("native");\n });\n \n it("accepts supported values", () => {\ndiff --git a/apps/mobile/src/features/review/reviewHighlighterEngine.ts b/apps/mobile/src/features/review/reviewHighlighterEngine.ts\nindex 5ef9f055a..428768537 100644\n--- a/apps/mobile/src/features/review/reviewHighlighterEngine.ts\n+++ b/apps/mobile/src/features/review/reviewHighlighterEngine.ts\n@@ -11,7 +11,7 @@ export function resolveReviewHighlighterEnginePreference(\n case "native":\n return "native";\n default:\n- return "javascript";\n+ return "native";\n }\n }\n \ndiff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts\nindex a24a99ceb..69a6e7261 100644\n--- a/apps/mobile/src/features/review/reviewModel.test.ts\n+++ b/apps/mobile/src/features/review/reviewModel.test.ts\n@@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => {\n });\n });\n \n- it("flattens expanded files into virtualizable review items", () => {\n+ it("flattens expanded file rows into virtualized review items", () => {\n const file = makeRenderableFile({\n path: "apps/mobile/src/a.ts",\n rows: [\n@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => {\n \n expect(items).toEqual([\n expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }),\n- expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }),\n- expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }),\n+ expect.objectContaining({\n+ kind: "hunk",\n+ fileId: file.id,\n+ file,\n+ row: file.rows[0],\n+ }),\n+ expect.objectContaining({\n+ kind: "line",\n+ fileId: file.id,\n+ file,\n+ row: file.rows[1],\n+ lineIndex: 0,\n+ }),\n ]);\n });\n \ndiff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts\nindex 27e6d7ae4..1cfbf358c 100644\n--- a/apps/mobile/src/features/review/reviewModel.ts\n+++ b/apps/mobile/src/features/review/reviewModel.ts\n@@ -72,6 +72,7 @@ export interface ReviewHunkListItem {\n readonly kind: "hunk";\n readonly id: string;\n readonly fileId: string;\n+ readonly file: ReviewRenderableFile;\n readonly row: ReviewRenderableHunkRow;\n }\n \n@@ -79,7 +80,9 @@ export interface ReviewLineListItem {\n readonly kind: "line";\n readonly id: string;\n readonly fileId: string;\n+ readonly file: ReviewRenderableFile;\n readonly row: ReviewRenderableLineRow;\n+ readonly lineIndex: number;\n }\n \n export type ReviewListItem =\n@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil\n }\n \n // The flattened review list item model is inspired by pierre/diffs\' iterator-first\n-// virtualization architecture, adapted here for React Native and LegendList.\n+// virtualization architecture, adapted here for React Native virtualization.\n // Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs\n // Reference files:\n // - src/utils/iterateOverDiff.ts\n@@ -350,12 +353,14 @@ export function buildReviewListItems(input: {\n }\n }\n \n- file.rows.forEach((row) => {\n+ let lineIndex = 0;\n+ file.rows.forEach((row, rowIndex) => {\n if (row.kind === "hunk") {\n items.push({\n kind: "hunk",\n- id: row.id,\n+ id: `${file.id}:row:${rowIndex}:${row.id}`,\n fileId: file.id,\n+ file,\n row,\n });\n return;\n@@ -363,10 +368,13 @@ export function buildReviewListItems(input: {\n \n items.push({\n kind: "line",\n- id: row.id,\n+ id: `${file.id}:row:${rowIndex}:${row.id}`,\n fileId: file.id,\n+ file,\n row,\n+ lineIndex,\n });\n+ lineIndex += 1;\n });\n });\n \ndiff --git a/apps/mobile/src/features/review/reviewState.ts b/apps/mobile/src/features/review/reviewState.ts\nindex 06134db7d..c116f93fe 100644\n--- a/apps/mobile/src/features/review/reviewState.ts\n+++ b/apps/mobile/src/features/review/reviewState.ts\n@@ -64,6 +64,13 @@ const reviewRevealedLargeFileIdsByThreadKeyAtom = Atom.family((threadKey: string\n ),\n );\n \n+const reviewViewedFileIdsByThreadKeyAtom = Atom.family((threadKey: string) =>\n+ Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe(\n+ Atom.keepAlive,\n+ Atom.withLabel(`mobile:review:viewed-file-ids:${threadKey}`),\n+ ),\n+);\n+\n const reviewParsedDiffBySectionCacheKeyAtom = Atom.family((cacheKey: string) =>\n Atom.make<{ readonly diff: string | null; readonly parsed: ReviewParsedDiff } | null>(null).pipe(\n Atom.keepAlive,\n@@ -110,6 +117,9 @@ export function useReviewCacheForThread(input: {\n ? reviewRevealedLargeFileIdsByThreadKeyAtom(threadKey)\n : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,\n );\n+ const viewedFileIdsBySection = useAtomValue(\n+ threadKey ? reviewViewedFileIdsByThreadKeyAtom(threadKey) : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,\n+ );\n \n return {\n threadKey,\n@@ -118,6 +128,7 @@ export function useReviewCacheForThread(input: {\n selectedSectionId,\n expandedFileIdsBySection,\n revealedLargeFileIdsBySection,\n+ viewedFileIdsBySection,\n };\n }\n \n@@ -169,6 +180,20 @@ export function updateReviewRevealedLargeFileIds(\n });\n }\n \n+export function updateReviewViewedFileIds(\n+ threadKey: string,\n+ sectionId: string,\n+ update: (current: ReadonlyArray | undefined) => ReadonlyArray | undefined,\n+): void {\n+ const atom = reviewViewedFileIdsByThreadKeyAtom(threadKey);\n+ const current = appAtomRegistry.get(atom);\n+ const nextValue = update(current[sectionId]);\n+ appAtomRegistry.set(atom, {\n+ ...current,\n+ [sectionId]: nextValue,\n+ });\n+}\n+\n export function getCachedReviewParsedDiff(input: {\n readonly threadKey: string | null;\n readonly sectionId: string | null;\ndiff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts\nindex 05b5c9213..402d00668 100644\n--- a/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts\n+++ b/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts\n@@ -24,7 +24,7 @@ function makeRenderableFile(\n describe("highlightReviewFile", () => {\n it("preserves one highlighted token row per diff line even without trailing newlines", async () => {\n const file = makeRenderableFile({\n- path: "apps/mobile/src/example.test.ts",\n+ path: "apps/mobile/src/example.txt",\n additionLines: [\n \'const items = ["a"];\',\n \'expect(items).toEqual(["a"]);\',\n@@ -36,15 +36,23 @@ describe("highlightReviewFile", () => {\n const highlighted = await highlightReviewFile(file, "light");\n \n expect(highlighted.additionLines).toHaveLength(file.additionLines.length);\n- expect(highlighted.additionLines[0]?.some((token) => token.content === "const")).toBe(true);\n- expect(highlighted.additionLines[1]?.some((token) => token.content === "expect")).toBe(true);\n- expect(highlighted.additionLines[2]?.some((token) => token.content === "const")).toBe(true);\n- expect(highlighted.additionLines[3]?.some((token) => token.content === "expect")).toBe(true);\n+ expect(highlighted.additionLines[0]?.map((token) => token.content).join("")).toBe(\n+ file.additionLines[0],\n+ );\n+ expect(highlighted.additionLines[1]?.map((token) => token.content).join("")).toBe(\n+ file.additionLines[1],\n+ );\n+ expect(highlighted.additionLines[2]?.map((token) => token.content).join("")).toBe(\n+ file.additionLines[2],\n+ );\n+ expect(highlighted.additionLines[3]?.map((token) => token.content).join("")).toBe(\n+ file.additionLines[3],\n+ );\n });\n \n it("adds word-alt diff emphasis for paired deletion and addition lines", async () => {\n const file = makeRenderableFile({\n- path: "apps/mobile/src/example-inline-diff.test.ts",\n+ path: "apps/mobile/src/example-inline-diff.txt",\n additionLines: ["const after = 2;"],\n deletionLines: ["const before = 1;"],\n rows: [\n@@ -82,7 +90,7 @@ describe("highlightReviewFile", () => {\n it("falls back to plain tokens for very long lines", async () => {\n const longLine = `const value = "${"a".repeat(1_100)}";`;\n const file = makeRenderableFile({\n- path: "apps/mobile/src/example-long-line.ts",\n+ path: "apps/mobile/src/example-long-line.txt",\n additionLines: [longLine],\n rows: [\n {\ndiff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.ts\nindex f7a5c4125..eb6bf6973 100644\n--- a/apps/mobile/src/features/review/shikiReviewHighlighter.ts\n+++ b/apps/mobile/src/features/review/shikiReviewHighlighter.ts\n@@ -1,5 +1,14 @@\n import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";\n import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";\n+import bashLanguage from "@shikijs/langs/bash";\n+import javascriptLanguage from "@shikijs/langs/javascript";\n+import jsonLanguage from "@shikijs/langs/json";\n+import jsxLanguage from "@shikijs/langs/jsx";\n+import tsxLanguage from "@shikijs/langs/tsx";\n+import typescriptLanguage from "@shikijs/langs/typescript";\n+import yamlLanguage from "@shikijs/langs/yaml";\n+import githubDarkDefault from "@shikijs/themes/github-dark-default";\n+import githubLightDefault from "@shikijs/themes/github-light-default";\n import { getFiletypeFromFileName } from "@pierre/diffs/utils";\n \n import {\n@@ -11,6 +20,7 @@ import type { ReviewRenderableFile, ReviewRenderableLineRow } from "./reviewMode\n import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs";\n \n export type ReviewDiffTheme = "light" | "dark";\n+export type { ReviewHighlighterEngine };\n \n export interface ReviewHighlightedToken {\n content: string;\n@@ -24,12 +34,19 @@ export interface ReviewHighlightedFile {\n readonly deletionLines: ReadonlyArray>;\n }\n \n+export interface ReviewHighlightFileProgress {\n+ readonly highlightedFile: ReviewHighlightedFile;\n+ readonly complete: boolean;\n+ readonly highlightedLineCount: number;\n+}\n+\n const SHIKI_THEME_NAME_BY_SCHEME = {\n light: "github-light-default",\n dark: "github-dark-default",\n } as const;\n const REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE =\n- process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? "javascript";\n+ process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ??\n+ (process.env.NODE_ENV === "test" ? "javascript" : "native");\n const REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE = resolveReviewHighlighterEnginePreference(\n REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE,\n );\n@@ -38,12 +55,30 @@ const REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE = resolveReviewHighlighterBooleanF\n false,\n );\n const REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT = 8;\n-const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 40;\n-const REVIEW_HIGHLIGHT_CHUNK_SIZE = 20;\n+const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 8;\n+const REVIEW_HIGHLIGHT_CHUNK_SIZE = 200;\n const REVIEW_TOKENIZE_MAX_LINE_LENGTH = 1_000;\n const highlightCache = new Map>();\n const resolvedHighlightCache = new Map();\n-const loadedLanguages = new Set(["text"]);\n+const REVIEW_INITIAL_LANGUAGE_MODULES = [\n+ bashLanguage,\n+ javascriptLanguage,\n+ jsonLanguage,\n+ jsxLanguage,\n+ tsxLanguage,\n+ typescriptLanguage,\n+ yamlLanguage,\n+] satisfies Parameters[0]["langs"];\n+const loadedLanguages = new Set([\n+ "text",\n+ "bash",\n+ "javascript",\n+ "json",\n+ "jsx",\n+ "tsx",\n+ "typescript",\n+ "yaml",\n+]);\n const languageLoadingPromises = new Map>();\n const languageImports: Partial Promise>> = {\n javascript: () => import("@shikijs/langs/javascript"),\n@@ -215,21 +250,13 @@ function joinPatchLines(lines: ReadonlyArray): string {\n \n function waitForNextFrame(): Promise {\n return new Promise((resolve) => {\n- if (typeof requestAnimationFrame === "function") {\n- requestAnimationFrame(() => resolve());\n- return;\n- }\n-\n setTimeout(resolve, 0);\n });\n }\n \n async function getHighlighter(): Promise {\n if (!highlighterPromise) {\n- const configuredHighlighterPromise = Promise.all([\n- import("@shikijs/themes/github-light-default"),\n- import("@shikijs/themes/github-dark-default"),\n- ]).then(async ([lightThemeModule, darkThemeModule]) => {\n+ const configuredHighlighterPromise = (async () => {\n let nativeEngineAvailable = false;\n \n logReviewHighlighterDiagnostic("initializing", {\n@@ -238,12 +265,11 @@ async function getHighlighter(): Promise {\n resultCacheDisabled: REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE,\n });\n \n- const themes = [lightThemeModule.default, darkThemeModule.default];\n+ const themes = [githubLightDefault, githubDarkDefault];\n \n if (REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE !== "javascript") {\n try {\n const nativeEngineModule = await import("react-native-shiki-engine");\n- logReviewHighlighterDiagnostic("imported react-native-shiki-engine");\n nativeEngineAvailable = nativeEngineModule.isNativeEngineAvailable();\n logReviewHighlighterDiagnostic("checked native engine availability", {\n nativeEngineAvailable,\n@@ -253,7 +279,7 @@ async function getHighlighter(): Promise {\n logReviewHighlighterDiagnostic("creating native regex engine");\n const highlighter = await createHighlighterCore({\n themes,\n- langs: [],\n+ langs: REVIEW_INITIAL_LANGUAGE_MODULES,\n engine: nativeEngineModule.createNativeEngine(),\n });\n logReviewHighlighterDiagnostic("using native engine");\n@@ -281,7 +307,7 @@ async function getHighlighter(): Promise {\n );\n const highlighter = await createHighlighterCore({\n themes,\n- langs: [],\n+ langs: REVIEW_INITIAL_LANGUAGE_MODULES,\n engine: createJavaScriptRegexEngine(),\n });\n logReviewHighlighterDiagnostic("using javascript engine", {\n@@ -291,7 +317,7 @@ async function getHighlighter(): Promise {\n highlighter,\n engine,\n };\n- });\n+ })();\n \n highlighterPromise = configuredHighlighterPromise\n .then((result) => result.highlighter)\n@@ -316,11 +342,52 @@ export async function getActiveReviewHighlighterEngine(): Promise {\n+ await getHighlighter();\n+}\n+\n+export async function prepareReviewHighlighterLanguages(\n+ languages: ReadonlyArray,\n+): Promise {\n+ const highlighter = await getHighlighter();\n+ await Promise.all(\n+ languages.map(async (language) => {\n+ const candidate = resolveLanguageAlias(language);\n+ if (candidate === "text" || !(candidate in languageImports)) {\n+ return;\n+ }\n+\n+ await loadSingleLanguage(highlighter, candidate);\n+ }),\n+ );\n+}\n+\n function resolveLanguageAlias(language: string): string {\n const normalized = language.toLowerCase();\n return languageAliases[normalized] ?? normalized;\n }\n \n+function resolveLoadedLanguageFromPath(\n+ path: string,\n+ languageHint: string | null = null,\n+): string | null {\n+ const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);\n+ if (!detectedLanguage) {\n+ return "text";\n+ }\n+\n+ const candidate = resolveLanguageAlias(detectedLanguage);\n+ if (candidate === "text" || candidate === "ansi") {\n+ return "text";\n+ }\n+\n+ if (!(candidate in languageImports)) {\n+ return "text";\n+ }\n+\n+ return loadedLanguages.has(candidate) ? candidate : null;\n+}\n+\n async function loadSingleLanguage(\n highlighter: HighlighterCore,\n language: string,\n@@ -360,6 +427,11 @@ async function resolveLanguageFromPath(\n path: string,\n languageHint: string | null = null,\n ): Promise {\n+ const loadedLanguage = resolveLoadedLanguageFromPath(path, languageHint);\n+ if (loadedLanguage) {\n+ return loadedLanguage;\n+ }\n+\n const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);\n if (!detectedLanguage) {\n return "text";\n@@ -374,8 +446,12 @@ async function resolveLanguageFromPath(\n return "text";\n }\n \n+ if (loadedLanguages.has(candidate)) {\n+ return candidate;\n+ }\n+\n const highlighter = await getHighlighter();\n- const loaded = await loadSingleLanguage(highlighter, resolveLanguageAlias(candidate));\n+ const loaded = await loadSingleLanguage(highlighter, candidate);\n if (!loaded) {\n return "text";\n }\n@@ -384,7 +460,10 @@ async function resolveLanguageFromPath(\n }\n \n async function resolveLanguage(file: ReviewRenderableFile): Promise {\n- return resolveLanguageFromPath(file.path, file.languageHint);\n+ return (\n+ resolveLoadedLanguageFromPath(file.path, file.languageHint) ??\n+ (await resolveLanguageFromPath(file.path, file.languageHint))\n+ );\n }\n \n function normalizeHighlightedLines(\n@@ -399,6 +478,18 @@ function normalizeHighlightedLines(\n );\n }\n \n+function makePlainHighlightedLines(\n+ lines: ReadonlyArray,\n+): ReadonlyArray> {\n+ return lines.map((line) => [\n+ {\n+ content: stripTrailingNewline(line),\n+ color: null,\n+ fontStyle: null,\n+ },\n+ ]);\n+}\n+\n function applyWordAltDiffHighlightsToFile(\n file: ReviewRenderableFile,\n highlighted: ReviewHighlightedFile,\n@@ -594,6 +685,67 @@ async function highlightLines(\n return highlightedLines;\n }\n \n+async function highlightPatchLinesInChunks(input: {\n+ readonly lines: ReadonlyArray;\n+ readonly language: string;\n+ readonly theme: string;\n+ readonly onChunk: (\n+ startIndex: number,\n+ tokens: ReadonlyArray>,\n+ ) => void;\n+}): Promise>> {\n+ if (input.lines.length === 0) {\n+ return [];\n+ }\n+\n+ const highlighter = await getHighlighter();\n+ const highlightedLines: Array> = [];\n+\n+ for (\n+ let startIndex = 0;\n+ startIndex < input.lines.length;\n+ startIndex += REVIEW_HIGHLIGHT_CHUNK_SIZE\n+ ) {\n+ const lineChunk = input.lines.slice(startIndex, startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE);\n+ const chunkTokens: Array> = [];\n+ const tokenizableLines: string[] = [];\n+ const tokenizableIndexes: number[] = [];\n+\n+ lineChunk.forEach((line, index) => {\n+ const strippedLine = stripTrailingNewline(line);\n+ if (strippedLine.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH) {\n+ chunkTokens[index] = [{ content: strippedLine, color: null, fontStyle: null }];\n+ return;\n+ }\n+\n+ tokenizableIndexes.push(index);\n+ tokenizableLines.push(strippedLine);\n+ });\n+\n+ if (tokenizableLines.length > 0) {\n+ const tokenLines = highlighter.codeToTokensBase(tokenizableLines.join("\\n"), {\n+ lang: input.language,\n+ theme: input.theme,\n+ });\n+ const normalizedTokenLines = normalizeHighlightedLines(tokenLines);\n+\n+ tokenizableIndexes.forEach((chunkIndex, tokenIndex) => {\n+ chunkTokens[chunkIndex] = normalizedTokenLines[tokenIndex] ?? [];\n+ });\n+ }\n+\n+ const completedChunk = lineChunk.map((_, index) => chunkTokens[index] ?? []);\n+ highlightedLines.push(...completedChunk);\n+ input.onChunk(startIndex, completedChunk);\n+\n+ if (startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE < input.lines.length) {\n+ await waitForNextFrame();\n+ }\n+ }\n+\n+ return highlightedLines;\n+}\n+\n function getHighlightCacheKey(file: ReviewRenderableFile, theme: ReviewDiffTheme): string {\n return `${SHIKI_THEME_NAME_BY_SCHEME[theme]}:${file.cacheKey}`;\n }\n@@ -667,7 +819,28 @@ export async function highlightReviewFile(\n deletionLineCount: file.deletionLines.length,\n rowCount: file.rows.length,\n });\n- const language = await resolveLanguage(file);\n+ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);\n+ const language = loadedLanguage ?? (await resolveLanguage(file));\n+ if (language === "text") {\n+ const highlighted = applyWordAltDiffHighlightsToFile(file, {\n+ additionLines: makePlainHighlightedLines(file.additionLines),\n+ deletionLines: makePlainHighlightedLines(file.deletionLines),\n+ });\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ storeResolvedHighlightedFile(cacheKey, highlighted);\n+ }\n+ logReviewHighlighterDiagnostic("file highlight complete", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ language,\n+ highlightedAdditionLineCount: highlighted.additionLines.length,\n+ highlightedDeletionLineCount: highlighted.deletionLines.length,\n+ durationMs: Date.now() - startedAt,\n+ });\n+ return highlighted;\n+ }\n+\n const additionLines = await highlightLines(\n joinPatchLines(file.additionLines),\n language,\n@@ -707,6 +880,113 @@ export async function highlightReviewFile(\n });\n }\n \n+export async function streamHighlightReviewFile(\n+ file: ReviewRenderableFile,\n+ theme: ReviewDiffTheme,\n+ onProgress: (progress: ReviewHighlightFileProgress) => void,\n+): Promise {\n+ const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[theme];\n+ const cacheKey = getHighlightCacheKey(file, theme);\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ const resolved = resolvedHighlightCache.get(cacheKey);\n+ if (resolved) {\n+ onProgress({\n+ highlightedFile: resolved,\n+ complete: true,\n+ highlightedLineCount: resolved.additionLines.length + resolved.deletionLines.length,\n+ });\n+ return resolved;\n+ }\n+ }\n+\n+ const startedAt = Date.now();\n+ logReviewHighlighterDiagnostic("file stream highlight start", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ additionLineCount: file.additionLines.length,\n+ deletionLineCount: file.deletionLines.length,\n+ rowCount: file.rows.length,\n+ });\n+\n+ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);\n+ const language = loadedLanguage ?? (await resolveLanguage(file));\n+ if (language === "text") {\n+ const highlighted = applyWordAltDiffHighlightsToFile(file, {\n+ additionLines: makePlainHighlightedLines(file.additionLines),\n+ deletionLines: makePlainHighlightedLines(file.deletionLines),\n+ });\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ storeResolvedHighlightedFile(cacheKey, highlighted);\n+ }\n+ onProgress({\n+ highlightedFile: highlighted,\n+ complete: true,\n+ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,\n+ });\n+ logReviewHighlighterDiagnostic("file stream highlight complete", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ language,\n+ highlightedAdditionLineCount: highlighted.additionLines.length,\n+ highlightedDeletionLineCount: highlighted.deletionLines.length,\n+ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,\n+ durationMs: Date.now() - startedAt,\n+ });\n+ return highlighted;\n+ }\n+\n+ const additionLines: Array> = [];\n+ const deletionLines: Array> = [];\n+ let highlightedLineCount = 0;\n+\n+ await highlightPatchLinesInChunks({\n+ lines: file.additionLines,\n+ language,\n+ theme: shikiTheme,\n+ onChunk: (startIndex, tokens) => {\n+ tokens.forEach((lineTokens, index) => {\n+ additionLines[startIndex + index] = lineTokens;\n+ });\n+ highlightedLineCount += tokens.length;\n+ },\n+ });\n+ await waitForNextFrame();\n+ await highlightPatchLinesInChunks({\n+ lines: file.deletionLines,\n+ language,\n+ theme: shikiTheme,\n+ onChunk: (startIndex, tokens) => {\n+ tokens.forEach((lineTokens, index) => {\n+ deletionLines[startIndex + index] = lineTokens;\n+ });\n+ highlightedLineCount += tokens.length;\n+ },\n+ });\n+\n+ const highlighted = applyWordAltDiffHighlightsToFile(file, { additionLines, deletionLines });\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ storeResolvedHighlightedFile(cacheKey, highlighted);\n+ }\n+ onProgress({\n+ highlightedFile: highlighted,\n+ complete: true,\n+ highlightedLineCount,\n+ });\n+ logReviewHighlighterDiagnostic("file stream highlight complete", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ language,\n+ highlightedAdditionLineCount: highlighted.additionLines.length,\n+ highlightedDeletionLineCount: highlighted.deletionLines.length,\n+ highlightedLineCount,\n+ durationMs: Date.now() - startedAt,\n+ });\n+ return highlighted;\n+}\n+\n export async function highlightReviewSelectedLines(input: {\n readonly filePath: string;\n readonly lines: ReadonlyArray;\n@@ -717,7 +997,9 @@ export async function highlightReviewSelectedLines(input: {\n return {};\n }\n \n- const language = await resolveLanguageFromPath(input.filePath, input.languageHint ?? null);\n+ const loadedLanguage = resolveLoadedLanguageFromPath(input.filePath, input.languageHint ?? null);\n+ const language =\n+ loadedLanguage ?? (await resolveLanguageFromPath(input.filePath, input.languageHint ?? null));\n const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[input.theme];\n const additionLikeLines = input.lines\n .filter((line) => line.change !== "delete")\ndiff --git a/apps/mobile/docs/review-profiling.md b/apps/mobile/docs/review-profiling.md\nnew file mode 100644\nindex 000000000..6977eaf6e\n--- /dev/null\n+++ b/apps/mobile/docs/review-profiling.md\n@@ -0,0 +1,80 @@\n+# Review Screen Profiling\n+\n+Use this when the mobile review screen is slow or crashes while opening large diffs.\n+\n+## Preferred Capture: React Native DevTools Performance\n+\n+This app is on Expo SDK 55 / React Native 0.83 with Hermes, so the best first trace is the React Native DevTools Performance recording. The review screen also emits `t3.review.*` user timing marks in development builds so the trace can show parse, list-building, row indexing, and syntax-highlighting work.\n+\n+1. Start the development client:\n+\n+ ```sh\n+ cd apps/mobile\n+ bun dev:client\n+ ```\n+\n+2. Open the app in the iOS Simulator or on the device using the development client.\n+\n+3. In the terminal running Expo, press `j` to open React Native DevTools.\n+\n+4. In DevTools, open the `Performance` panel.\n+\n+5. Start recording.\n+\n+6. In the app, reproduce the slow path:\n+ - Navigate to the thread.\n+ - Open `Files Changed`.\n+ - Select the largest review source.\n+ - Expand a few large files or tap `Load diff`.\n+ - Scroll until the app is clearly slow or until just before it crashes.\n+\n+7. Stop recording.\n+\n+8. Export or save the Performance recording as a JSON trace.\n+\n+Send that exported trace file here. Also include the device/simulator model and whether it was iOS or Android.\n+\n+## Android Fallback: Hermes Sampling Profile\n+\n+Use this if the app crashes before DevTools can export a trace, or if we need deeper JavaScript stack samples.\n+\n+1. Run Android dev client:\n+\n+ ```sh\n+ cd apps/mobile\n+ bun android:dev\n+ bun dev:client\n+ ```\n+\n+2. Open the developer menu from the Expo terminal with `d`.\n+\n+3. Select `Enable Sampling Profiler`.\n+\n+4. Reproduce the review-screen slowdown.\n+\n+5. Open the developer menu again with `d`.\n+\n+6. Select `Disable Sampling Profiler`.\n+\n+7. Pull and convert the Hermes profile:\n+\n+ ```sh\n+ cd apps/mobile\n+ mkdir -p profiles/review\n+ bunx react-native profile-hermes profiles/review\n+ ```\n+\n+8. Send the generated Chrome trace/profile file from `apps/mobile/profiles/review`.\n+\n+For the development app variant, the Android package is `com.t3tools.t3code.dev`.\n+\n+## What To Capture\n+\n+For the first trace, do not optimize the repro. We want the slowest realistic case:\n+\n+- A diff with many files and large line counts.\n+- At least one `Load diff` action for a suppressed large diff.\n+- One vertical scroll pass after the content appears.\n+- One horizontal scroll of a long file, if that is part of the slowdown.\n+\n+If the app crashes, note the last visible action before the crash and attach device logs if available.\ndiff --git a/apps/mobile/src/app/debug/syntax-highlight.tsx b/apps/mobile/src/app/debug/syntax-highlight.tsx\nnew file mode 100644\nindex 000000000..c2a36d126\n--- /dev/null\n+++ b/apps/mobile/src/app/debug/syntax-highlight.tsx\n@@ -0,0 +1,423 @@\n+import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";\n+import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";\n+import typescriptLanguage from "@shikijs/langs/typescript";\n+import githubDarkDefault from "@shikijs/themes/github-dark-default";\n+import githubLightDefault from "@shikijs/themes/github-light-default";\n+import Stack from "expo-router/stack";\n+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";\n+import {\n+ FlatList,\n+ Pressable,\n+ Text as NativeText,\n+ type ListRenderItemInfo,\n+ useColorScheme,\n+ useWindowDimensions,\n+ View,\n+} from "react-native";\n+import { useSafeAreaInsets } from "react-native-safe-area-context";\n+\n+import { AppText as Text } from "../../components/AppText";\n+import { cn } from "../../lib/cn";\n+import { useThemeColor } from "../../lib/useThemeColor";\n+\n+type DebugHighlightEngine = "native" | "javascript";\n+\n+type DebugToken = {\n+ readonly content: string;\n+ readonly color: string | null;\n+ readonly fontStyle: number | null;\n+};\n+\n+type DebugLine = {\n+ readonly id: string;\n+ readonly chunkIndex: number;\n+ readonly indexInChunk: number;\n+ readonly lineNumber: number;\n+ readonly content: string;\n+};\n+\n+type DebugHighlighterHandle = {\n+ readonly engine: DebugHighlightEngine;\n+ readonly tokenize: (\n+ code: string,\n+ options: { readonly lang: string; readonly theme: string },\n+ ) => ReadonlyArray>;\n+};\n+\n+const DEBUG_LINE_COUNT = 10_000;\n+const DEBUG_CHUNK_SIZE = 500;\n+const DEBUG_LINE_HEIGHT = 24;\n+const DEBUG_GUTTER_WIDTH = 58;\n+const DEBUG_CONTENT_WIDTH = 3_200;\n+const DEBUG_MONO_FONT_FAMILY = "BerkeleyMono-Regular";\n+const DEBUG_THEME_NAME_BY_SCHEME = {\n+ dark: "github-dark-default",\n+ light: "github-light-default",\n+} as const;\n+\n+let nativeHighlighterPromise: Promise | null = null;\n+let javascriptHighlighterPromise: Promise | null = null;\n+\n+function waitForNextFrame(): Promise {\n+ return new Promise((resolve) => setTimeout(resolve, 0));\n+}\n+\n+function normalizeTokens(\n+ tokenLines: ReadonlyArray>,\n+): ReadonlyArray> {\n+ return tokenLines.map((line) =>\n+ line.map((token) => ({\n+ content: token.content,\n+ color: token.color ?? null,\n+ fontStyle: token.fontStyle ?? null,\n+ })),\n+ );\n+}\n+\n+function makeDebugCodeLine(index: number): string {\n+ const label = `generatedLine${String(index).padStart(5, "0")}`;\n+ switch (index % 8) {\n+ case 0:\n+ return `export async function ${label}(input: { value: number; name: string }) {`;\n+ case 1:\n+ return ` const normalized = input.name.trim().toLowerCase();`;\n+ case 2:\n+ return ` const result = await Promise.resolve({ id: "${label}", score: input.value * ${index + 1} });`;\n+ case 3:\n+ return ` if (result.score > ${index * 17}) return normalized + ":" + result.id;`;\n+ case 4:\n+ return ` return [normalized, String(result.score), "${"x".repeat((index % 24) + 8)}"].join("/");`;\n+ case 5:\n+ return `}`;\n+ case 6:\n+ return `type ${label}Record = Readonly<{ id: string; createdAt: Date; tags: string[] }>;`;\n+ default:\n+ return `const ${label}: ${label}Record = { id: "${label}", createdAt: new Date(), tags: ["debug", "highlight"] };`;\n+ }\n+}\n+\n+function makeDebugLines(): ReadonlyArray {\n+ return Array.from({ length: DEBUG_LINE_COUNT }, (_, index) => ({\n+ id: `line:${index + 1}`,\n+ chunkIndex: Math.floor(index / DEBUG_CHUNK_SIZE),\n+ indexInChunk: index % DEBUG_CHUNK_SIZE,\n+ lineNumber: index + 1,\n+ content: makeDebugCodeLine(index + 1),\n+ }));\n+}\n+\n+async function createNativeDebugHighlighter(): Promise {\n+ const nativeEngineModule = await import("react-native-shiki-engine");\n+ if (!nativeEngineModule.isNativeEngineAvailable()) {\n+ throw new Error("Native Shiki engine is not available in this build.");\n+ }\n+\n+ const highlighter = await createHighlighterCore({\n+ langs: [typescriptLanguage],\n+ themes: [githubLightDefault, githubDarkDefault],\n+ engine: nativeEngineModule.createNativeEngine(),\n+ });\n+\n+ return {\n+ engine: "native",\n+ tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),\n+ };\n+}\n+\n+async function createJavascriptDebugHighlighter(): Promise {\n+ const highlighter: HighlighterCore = await createHighlighterCore({\n+ langs: [typescriptLanguage],\n+ themes: [githubLightDefault, githubDarkDefault],\n+ engine: createJavaScriptRegexEngine(),\n+ });\n+\n+ return {\n+ engine: "javascript",\n+ tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),\n+ };\n+}\n+\n+async function getDebugHighlighter(engine: DebugHighlightEngine): Promise {\n+ if (engine === "native") {\n+ nativeHighlighterPromise ??= createNativeDebugHighlighter();\n+ return nativeHighlighterPromise;\n+ }\n+\n+ javascriptHighlighterPromise ??= createJavascriptDebugHighlighter();\n+ return javascriptHighlighterPromise;\n+}\n+\n+const TokenText = memo(function TokenText(props: {\n+ readonly content: string;\n+ readonly tokens: ReadonlyArray | null;\n+}) {\n+ if (!props.tokens) {\n+ return (\n+ \n+ {props.content}\n+ \n+ );\n+ }\n+\n+ let tokenOffset = 0;\n+\n+ return (\n+ \n+ {props.tokens.map((token) => {\n+ const tokenKey = `${tokenOffset}:${token.content.length}:${token.color ?? ""}:${token.fontStyle ?? ""}`;\n+ tokenOffset += token.content.length;\n+ const fontWeight =\n+ token.fontStyle !== null && (token.fontStyle & 2) === 2\n+ ? ("700" as const)\n+ : ("500" as const);\n+ const fontStyle =\n+ token.fontStyle !== null && (token.fontStyle & 1) === 1\n+ ? ("italic" as const)\n+ : ("normal" as const);\n+\n+ return (\n+ \n+ {token.content}\n+ \n+ );\n+ })}\n+ \n+ );\n+});\n+\n+const DebugCodeLineRow = memo(function DebugCodeLineRow(props: {\n+ readonly item: DebugLine;\n+ readonly tokens: ReadonlyArray | null;\n+ readonly width: number;\n+}) {\n+ return (\n+ \n+ \n+ {props.item.lineNumber}\n+ \n+ \n+ \n+ \n+ \n+ );\n+});\n+\n+function EngineToggle(props: {\n+ readonly engine: DebugHighlightEngine;\n+ readonly onChangeEngine: (engine: DebugHighlightEngine) => void;\n+}) {\n+ return (\n+ \n+ {(["native", "javascript"] as const).map((engine) => {\n+ const selected = props.engine === engine;\n+ return (\n+ props.onChangeEngine(engine)}\n+ >\n+ \n+ {engine === "javascript" ? "JS" : "Native"}\n+ \n+ \n+ );\n+ })}\n+ \n+ );\n+}\n+\n+export default function SyntaxHighlightDebugRoute() {\n+ const insets = useSafeAreaInsets();\n+ const { width } = useWindowDimensions();\n+ const colorScheme = useColorScheme();\n+ const headerIcon = String(useThemeColor("--color-icon"));\n+ const themeName = DEBUG_THEME_NAME_BY_SCHEME[colorScheme === "dark" ? "dark" : "light"];\n+ const [engine, setEngine] = useState("native");\n+ const [tokensByChunkIndex, setTokensByChunkIndex] = useState<\n+ Record>>\n+ >({});\n+ const [status, setStatus] = useState("Idle");\n+ const renderStartRef = useRef(null);\n+ const generationRef = useRef(0);\n+ const lines = useMemo(() => makeDebugLines(), []);\n+\n+ useEffect(() => {\n+ const generation = generationRef.current + 1;\n+ generationRef.current = generation;\n+ renderStartRef.current = performance.now();\n+ setTokensByChunkIndex({});\n+ setStatus("Initializing highlighter");\n+\n+ void (async () => {\n+ try {\n+ const highlighterStartedAt = performance.now();\n+ const highlighter = await getDebugHighlighter(engine);\n+ if (generation !== generationRef.current) {\n+ return;\n+ }\n+\n+ console.log("[debug-syntax-scratch] initialize", {\n+ durationMs: Math.round(performance.now() - highlighterStartedAt),\n+ engine: highlighter.engine,\n+ });\n+\n+ let firstChunkMs: number | null = null;\n+ const totalStartedAt = performance.now();\n+ setStatus(`Streaming ${DEBUG_LINE_COUNT.toLocaleString()} lines`);\n+\n+ for (let startIndex = 0; startIndex < lines.length; startIndex += DEBUG_CHUNK_SIZE) {\n+ if (generation !== generationRef.current) {\n+ return;\n+ }\n+\n+ const chunkLines = lines.slice(startIndex, startIndex + DEBUG_CHUNK_SIZE);\n+ const chunkCode = chunkLines.map((line) => line.content).join("\\n");\n+ const chunkStartedAt = performance.now();\n+ const chunkTokens = highlighter.tokenize(chunkCode, {\n+ lang: "typescript",\n+ theme: themeName,\n+ });\n+ const chunkMs = performance.now() - chunkStartedAt;\n+\n+ if (firstChunkMs === null) {\n+ firstChunkMs = performance.now() - totalStartedAt;\n+ console.log("[debug-syntax-scratch] first chunk", {\n+ chunkSize: DEBUG_CHUNK_SIZE,\n+ durationMs: Math.round(firstChunkMs),\n+ engine,\n+ lineCount: chunkTokens.length,\n+ });\n+ }\n+\n+ setTokensByChunkIndex((current) => ({\n+ ...current,\n+ [startIndex / DEBUG_CHUNK_SIZE]: chunkTokens,\n+ }));\n+ setStatus(\n+ `Streamed ${Math.min(startIndex + DEBUG_CHUNK_SIZE, lines.length).toLocaleString()} / ${lines.length.toLocaleString()} lines`,\n+ );\n+\n+ console.log("[debug-syntax-scratch] chunk", {\n+ chunkIndex: startIndex / DEBUG_CHUNK_SIZE,\n+ chunkMs: Math.round(chunkMs),\n+ engine,\n+ lineCount: chunkTokens.length,\n+ });\n+\n+ await waitForNextFrame();\n+ }\n+\n+ console.log("[debug-syntax-scratch] complete", {\n+ durationMs: Math.round(performance.now() - totalStartedAt),\n+ engine,\n+ lineCount: lines.length,\n+ });\n+ setStatus(`Complete with ${engine}`);\n+ } catch (error) {\n+ console.error("[debug-syntax-scratch] failed", {\n+ engine,\n+ message: error instanceof Error ? error.message : String(error),\n+ });\n+ setStatus(error instanceof Error ? error.message : "Highlight failed");\n+ }\n+ })();\n+ }, [engine, lines, themeName]);\n+\n+ useEffect(() => {\n+ if (renderStartRef.current === null) {\n+ return;\n+ }\n+\n+ const startedAt = renderStartRef.current;\n+ renderStartRef.current = null;\n+ const commitMs = performance.now() - startedAt;\n+ requestAnimationFrame(() => {\n+ console.log("[debug-syntax-scratch] render", {\n+ commitMs: Math.round(commitMs),\n+ paintMs: Math.round(performance.now() - startedAt),\n+ });\n+ });\n+ });\n+\n+ const renderItem = useCallback(\n+ ({ item }: ListRenderItemInfo) => (\n+ \n+ ),\n+ [tokensByChunkIndex, width],\n+ );\n+\n+ return (\n+ \n+ \n+\n+ \n+ \n+ \n+ \n+ Shiki streaming baseline\n+ \n+ \n+ {status}\n+ \n+ \n+ \n+ \n+ \n+\n+ item.id}\n+ getItemLayout={(_, index) => ({\n+ length: DEBUG_LINE_HEIGHT,\n+ offset: DEBUG_LINE_HEIGHT * index,\n+ index,\n+ })}\n+ initialNumToRender={40}\n+ maxToRenderPerBatch={80}\n+ updateCellsBatchingPeriod={16}\n+ windowSize={9}\n+ removeClippedSubviews\n+ keyboardShouldPersistTaps="handled"\n+ contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}\n+ />\n+ \n+ );\n+}\ndiff --git a/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx\nnew file mode 100644\nindex 000000000..095201929\n--- /dev/null\n+++ b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx\n@@ -0,0 +1,110 @@\n+import { createContext, type ReactNode, useContext, useEffect, useMemo, useState } from "react";\n+\n+import {\n+ getActiveReviewHighlighterEngine,\n+ prepareReviewHighlighter,\n+ prepareReviewHighlighterLanguages,\n+ type ReviewHighlighterEngine,\n+} from "./shikiReviewHighlighter";\n+\n+type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error";\n+\n+interface ReviewHighlighterContextValue {\n+ readonly engine: ReviewHighlighterEngine | null;\n+ readonly error: string | null;\n+ readonly status: ReviewHighlighterStatus;\n+}\n+\n+const ReviewHighlighterContext = createContext({\n+ engine: null,\n+ error: null,\n+ status: "idle",\n+});\n+\n+const REVIEW_INITIAL_LANGUAGES = [\n+ "typescript",\n+ "tsx",\n+ "javascript",\n+ "jsx",\n+ "json",\n+ "yaml",\n+ "bash",\n+] as const;\n+\n+function isReviewHighlighterProviderDebugLoggingEnabled(): boolean {\n+ return typeof __DEV__ !== "undefined" ? __DEV__ : false;\n+}\n+\n+function logReviewHighlighterProviderDiagnostic(\n+ message: string,\n+ details?: Record,\n+): void {\n+ if (!isReviewHighlighterProviderDebugLoggingEnabled()) {\n+ return;\n+ }\n+\n+ if (details) {\n+ console.log(`[review-highlighter-provider] ${message}`, details);\n+ return;\n+ }\n+\n+ console.log(`[review-highlighter-provider] ${message}`);\n+}\n+\n+export function ReviewHighlighterProvider(props: { readonly children: ReactNode }) {\n+ const [value, setValue] = useState({\n+ engine: null,\n+ error: null,\n+ status: "idle",\n+ });\n+\n+ useEffect(() => {\n+ let cancelled = false;\n+\n+ setValue({ engine: null, error: null, status: "initializing" });\n+\n+ void (async () => {\n+ const startedAt = performance.now();\n+ try {\n+ await prepareReviewHighlighter();\n+ await prepareReviewHighlighterLanguages(REVIEW_INITIAL_LANGUAGES);\n+ const engine = await getActiveReviewHighlighterEngine();\n+\n+ if (cancelled) {\n+ return;\n+ }\n+\n+ const durationMs = Math.round(performance.now() - startedAt);\n+ logReviewHighlighterProviderDiagnostic("initialized", {\n+ durationMs,\n+ engine,\n+ });\n+ setValue({ engine, error: null, status: "ready" });\n+ } catch (error) {\n+ if (cancelled) {\n+ return;\n+ }\n+\n+ const message = error instanceof Error ? error.message : String(error);\n+ logReviewHighlighterProviderDiagnostic("initialization failed", { error: message });\n+ setValue({ engine: null, error: message, status: "error" });\n+ }\n+ })();\n+\n+ return () => {\n+ cancelled = true;\n+ };\n+ }, []);\n+\n+ const contextValue = useMemo(() => value, [value]);\n+\n+ return (\n+ \n+ {props.children}\n+ \n+ );\n+}\n+\n+export function useReviewHighlighterStatus(): ReviewHighlighterContextValue {\n+ return useContext(ReviewHighlighterContext);\n+}\ndiff --git a/apps/mobile/src/features/review/reviewPerf.ts b/apps/mobile/src/features/review/reviewPerf.ts\nnew file mode 100644\nindex 000000000..2ae1095b1\n--- /dev/null\n+++ b/apps/mobile/src/features/review/reviewPerf.ts\n@@ -0,0 +1,83 @@\n+interface ReviewPerformanceLike {\n+ readonly now?: () => number;\n+ readonly mark?: (name: string) => void;\n+ readonly measure?: (name: string, startMark: string, endMark: string) => void;\n+ readonly clearMarks?: (name?: string) => void;\n+ readonly clearMeasures?: (name?: string) => void;\n+}\n+\n+const REVIEW_PERF_PREFIX = "t3.review";\n+let reviewPerfSequence = 0;\n+\n+function getPerformance(): ReviewPerformanceLike | null {\n+ const candidate = (globalThis as { readonly performance?: ReviewPerformanceLike }).performance;\n+ return candidate ?? null;\n+}\n+\n+export function isReviewPerfEnabled(): boolean {\n+ return typeof __DEV__ !== "undefined" ? __DEV__ : false;\n+}\n+\n+export function measureReviewWork(name: string, callback: () => T): T {\n+ if (!isReviewPerfEnabled()) {\n+ return callback();\n+ }\n+\n+ const perf = getPerformance();\n+ const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`;\n+ const startMark = `${marker}.start`;\n+ const endMark = `${marker}.end`;\n+ const startedAt = perf?.now?.() ?? Date.now();\n+\n+ perf?.mark?.(startMark);\n+ try {\n+ return callback();\n+ } finally {\n+ const durationMs = (perf?.now?.() ?? Date.now()) - startedAt;\n+ perf?.mark?.(endMark);\n+ perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark);\n+ perf?.clearMarks?.(startMark);\n+ perf?.clearMarks?.(endMark);\n+ console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) });\n+ }\n+}\n+\n+export async function measureReviewAsyncWork(\n+ name: string,\n+ callback: () => Promise,\n+): Promise {\n+ if (!isReviewPerfEnabled()) {\n+ return callback();\n+ }\n+\n+ const perf = getPerformance();\n+ const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`;\n+ const startMark = `${marker}.start`;\n+ const endMark = `${marker}.end`;\n+ const startedAt = perf?.now?.() ?? Date.now();\n+\n+ perf?.mark?.(startMark);\n+ try {\n+ return await callback();\n+ } finally {\n+ const durationMs = (perf?.now?.() ?? Date.now()) - startedAt;\n+ perf?.mark?.(endMark);\n+ perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark);\n+ perf?.clearMarks?.(startMark);\n+ perf?.clearMarks?.(endMark);\n+ console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) });\n+ }\n+}\n+\n+export function markReviewEvent(name: string, details?: Record): void {\n+ if (!isReviewPerfEnabled()) {\n+ return;\n+ }\n+\n+ getPerformance()?.mark?.(`${REVIEW_PERF_PREFIX}.${name}`);\n+ if (details) {\n+ console.log(`[review-perf] ${name}`, details);\n+ return;\n+ }\n+ console.log(`[review-perf] ${name}`);\n+}\n', + }, + { + id: "current", + label: "Current Working", + filename: "current-working-review.diff", + lineCount: 3208, + diff: 'diff --git a/apps/mobile/package.json b/apps/mobile/package.json\nindex 08329e1d4..36ac93a0f 100644\n--- a/apps/mobile/package.json\n+++ b/apps/mobile/package.json\n@@ -30,6 +30,7 @@\n "config:dev": "APP_VARIANT=development expo config",\n "config:preview": "APP_VARIANT=preview expo config",\n "config:prod": "APP_VARIANT=production expo config",\n+ "profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",\n "test": "vitest run",\n "typecheck": "tsc --noEmit"\n },\ndiff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx\nindex f153db701..f6095c051 100644\n--- a/apps/mobile/src/app/index.tsx\n+++ b/apps/mobile/src/app/index.tsx\n@@ -43,28 +43,50 @@ export default function HomeRouteScreen() {\n headerTintColor: iconColor,\n headerTitle: "",\n headerRight: () => (\n- router.push("/connections")}\n- hitSlop={8}\n- style={{\n- flexDirection: "row",\n- alignItems: "center",\n- gap: 8,\n- paddingHorizontal: 4,\n- paddingVertical: 4,\n- }}\n- >\n- \n- \n+ router.push("/debug/syntax-highlight")}\n+ hitSlop={8}\n style={{\n- fontFamily: "DMSans_700Bold",\n- fontSize: 12,\n- color: secondaryFg,\n+ borderRadius: 999,\n+ backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)",\n+ paddingHorizontal: 10,\n+ paddingVertical: 5,\n }}\n >\n- {CONNECTION_LABEL[connectionState]}\n- \n- \n+ \n+ Debug\n+ \n+ \n+ router.push("/connections")}\n+ hitSlop={8}\n+ style={{\n+ flexDirection: "row",\n+ alignItems: "center",\n+ gap: 8,\n+ paddingHorizontal: 4,\n+ paddingVertical: 4,\n+ }}\n+ >\n+ \n+ \n+ {CONNECTION_LABEL[connectionState]}\n+ \n+ \n+ \n ),\n headerSearchBarOptions: {\n placeholder: "Search threads",\ndiff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\nindex 84c48c6ed..ee993ee7c 100644\n--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n@@ -1,5 +1,10 @@\n+import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";\n import { ReviewSheet } from "../../../../features/review/ReviewSheet";\n \n export default function ReviewRoute() {\n- return ;\n+ return (\n+ \n+ \n+ \n+ );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\nindex 076a2286d..9a173224a 100644\n--- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n@@ -2,15 +2,8 @@ import { useLocalSearchParams, useRouter } from "expo-router";\n import { SymbolView } from "expo-symbols";\n import { TextInputWrapper } from "expo-paste-input";\n import { useEffect, useMemo, useState } from "react";\n-import {\n- KeyboardAvoidingView,\n- Platform,\n- Pressable,\n- ScrollView,\n- View,\n- useColorScheme,\n- useWindowDimensions,\n-} from "react-native";\n+import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native";\n+import { KeyboardStickyView } from "react-native-keyboard-controller";\n import { useSafeAreaInsets } from "react-native-safe-area-context";\n import ImageViewing from "react-native-image-viewing";\n \n@@ -34,6 +27,7 @@ import {\n import {\n changeTone,\n DiffTokenText,\n+ REVIEW_DIFF_LINE_HEIGHT,\n REVIEW_MONO_FONT_FAMILY,\n ReviewChangeBar,\n } from "./reviewDiffRendering";\n@@ -44,7 +38,6 @@ import {\n } from "./shikiReviewHighlighter";\n \n const REVIEW_COMMENT_PREVIEW_MAX_LINES = 5;\n-const REVIEW_COMMENT_LINE_HEIGHT = 26;\n \n export function ReviewCommentComposerSheet() {\n const router = useRouter();\n@@ -84,8 +77,8 @@ export function ReviewCommentComposerSheet() {\n ? `Lines ${firstNumber}-${lastNumber}`\n : `${selectedLines.length} lines selected`;\n const previewHeight = Math.max(\n- Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_COMMENT_LINE_HEIGHT,\n- REVIEW_COMMENT_LINE_HEIGHT,\n+ Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_DIFF_LINE_HEIGHT,\n+ REVIEW_DIFF_LINE_HEIGHT,\n );\n const previewViewportWidth = Math.max(width - 40, 280);\n const handleNativePaste = useNativePaste((uris) => {\n@@ -143,17 +136,13 @@ export function ReviewCommentComposerSheet() {\n }\n \n return (\n- \n+ \n \n \n@@ -219,7 +208,7 @@ export function ReviewCommentComposerSheet() {\n \n \n \n \n-\n- \n- void handlePickImages()} />\n- \n- {\n- if (!target || !environmentId || !threadId || commentText.trim().length === 0) {\n- return;\n- }\n-\n- appendReviewCommentToDraft({\n- environmentId,\n- threadId,\n- text: formatReviewCommentContext(target, commentText),\n- attachments,\n- });\n- setAttachments([]);\n- clearReviewCommentTarget();\n- router.dismiss();\n- }}\n- />\n- \n \n )}\n \n+ {target ? (\n+ \n+ \n+ void handlePickImages()} />\n+ \n+ {\n+ if (!target || !environmentId || !threadId || commentText.trim().length === 0) {\n+ return;\n+ }\n+\n+ appendReviewCommentToDraft({\n+ environmentId,\n+ threadId,\n+ text: formatReviewCommentContext(target, commentText),\n+ attachments,\n+ });\n+ setAttachments([]);\n+ clearReviewCommentTarget();\n+ router.dismiss();\n+ }}\n+ />\n+ \n+ \n+ ) : null}\n \n- \n+ \n );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx\nindex 82c28e81e..e148a8da2 100644\n--- a/apps/mobile/src/features/review/ReviewSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewSheet.tsx\n@@ -1,17 +1,31 @@\n import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts";\n+import { Gesture, GestureDetector } from "react-native-gesture-handler";\n+import Animated, {\n+ makeMutable,\n+ type SharedValue,\n+ useAnimatedStyle,\n+ useSharedValue,\n+} from "react-native-reanimated";\n import { useLocalSearchParams, useRouter } from "expo-router";\n import Stack from "expo-router/stack";\n import { SymbolView } from "expo-symbols";\n-import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react";\n+import {\n+ memo,\n+ type ReactElement,\n+ useCallback,\n+ useDeferredValue,\n+ useEffect,\n+ useMemo,\n+ useRef,\n+ useState,\n+} from "react";\n import {\n ActivityIndicator,\n FlatList,\n- InteractionManager,\n type ListRenderItemInfo,\n Pressable,\n ScrollView,\n Text as NativeText,\n- type ViewToken,\n useColorScheme,\n useWindowDimensions,\n View,\n@@ -32,6 +46,7 @@ import {\n setReviewTurnDiff,\n updateReviewExpandedFileIds,\n updateReviewRevealedLargeFileIds,\n+ updateReviewViewedFileIds,\n useReviewCacheForThread,\n } from "./reviewState";\n import {\n@@ -45,11 +60,12 @@ import {\n type ReviewParsedDiff,\n type ReviewRenderableFile,\n type ReviewRenderableLineRow,\n+ type ReviewRenderableRow,\n } from "./reviewModel";\n import {\n clearReviewHighlightFileCache,\n getCachedHighlightedReviewFile,\n- highlightReviewFile,\n+ streamHighlightReviewFile,\n type ReviewDiffTheme,\n type ReviewHighlightedFile,\n type ReviewHighlightedToken,\n@@ -67,9 +83,12 @@ import {\n import {\n changeTone,\n DiffTokenText,\n+ REVIEW_DIFF_LINE_HEIGHT,\n REVIEW_MONO_FONT_FAMILY,\n ReviewChangeBar,\n } from "./reviewDiffRendering";\n+import { markReviewEvent, measureReviewWork } from "./reviewPerf";\n+import { useReviewHighlighterStatus } from "./ReviewHighlighterProvider";\n \n interface PendingCommentSelection {\n readonly sectionTitle: string;\n@@ -87,14 +106,21 @@ interface ReviewLineActionInput {\n \n const IOS_NAV_BAR_HEIGHT = 44;\n const REVIEW_HEADER_SPACING = 0;\n-const REVIEW_LINE_GUTTER_WIDTH = 62;\n+const REVIEW_CHANGE_BAR_WIDTH = 5;\n+const REVIEW_MIN_LINE_NUMBER_WIDTH = 27;\n+const REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE = 8;\n+const REVIEW_LINE_NUMBER_HORIZONTAL_PADDING = 6;\n const REVIEW_CHARACTER_WIDTH_ESTIMATE = 8.4;\n const REVIEW_MAX_CONTENT_WIDTH = 4_800;\n-const REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT = 2;\n-const REVIEW_HIGHLIGHT_BACKTRACK_COUNT = 0;\n-const REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT = 1;\n+const REVIEW_HUNK_ROW_HEIGHT = 35;\n+const REVIEW_FILE_HEADER_HEIGHT = 43;\n+const REVIEW_SUPPRESSED_ROW_HEIGHT = 92;\n const loggedMissingReviewTokenKeys = new Set();\n \n+function waitForReviewDelay(durationMs: number): Promise {\n+ return new Promise((resolve) => setTimeout(resolve, durationMs));\n+}\n+\n function isReviewDiffDebugLoggingEnabled(): boolean {\n return typeof __DEV__ !== "undefined" ? __DEV__ : false;\n }\n@@ -113,33 +139,27 @@ function logReviewDiffDiagnostic(message: string, details?: Record,\n+function computeReviewFileContentWidth(\n+ rows: ReadonlyArray,\n viewportWidth: number,\n+ gutterWidth: number,\n ): number {\n let maxTextLength = 0;\n \n- items.forEach((item) => {\n- switch (item.kind) {\n- case "file-header":\n- maxTextLength = Math.max(\n- maxTextLength,\n- item.file.path.length,\n- item.file.previousPath?.length ?? 0,\n- );\n- break;\n- case "file-suppressed":\n- maxTextLength = Math.max(maxTextLength, item.message.length, item.actionLabel?.length ?? 0);\n- break;\n- case "hunk":\n- maxTextLength = Math.max(\n- maxTextLength,\n- item.row.header.length + (item.row.context ? item.row.context.length + 1 : 0),\n- );\n- break;\n- case "line":\n- maxTextLength = Math.max(maxTextLength, item.row.content.length);\n- break;\n+ rows.forEach((row) => {\n+ if (row.kind === "hunk") {\n+ maxTextLength = Math.max(\n+ maxTextLength,\n+ row.header.length + (row.context ? row.context.length + 1 : 0),\n+ );\n+ return;\n }\n+\n+ maxTextLength = Math.max(maxTextLength, row.content.length);\n });\n \n return Math.max(\n- viewportWidth,\n+ Math.max(0, viewportWidth - gutterWidth),\n Math.min(\n REVIEW_MAX_CONTENT_WIDTH,\n- Math.ceil(REVIEW_LINE_GUTTER_WIDTH + 48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE),\n+ Math.ceil(48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE),\n ),\n );\n }\n \n+function computeReviewFileGutterWidth(rows: ReadonlyArray): number {\n+ let maxLineNumber = 0;\n+\n+ rows.forEach((row) => {\n+ if (row.kind !== "line") {\n+ return;\n+ }\n+\n+ maxLineNumber = Math.max(maxLineNumber, row.oldLineNumber ?? 0, row.newLineNumber ?? 0);\n+ });\n+\n+ const digitCount = Math.max(1, String(maxLineNumber).length);\n+ const lineNumberWidth = Math.max(\n+ REVIEW_MIN_LINE_NUMBER_WIDTH,\n+ digitCount * REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE + REVIEW_LINE_NUMBER_HORIZONTAL_PADDING,\n+ );\n+\n+ return REVIEW_CHANGE_BAR_WIDTH + lineNumberWidth;\n+}\n+\n function getDefaultExpandedFileIds(\n files: ReadonlyArray,\n ): ReadonlyArray {\n return files.map((file) => file.id);\n }\n \n+function getValidReviewExpandedFileIds(\n+ files: ReadonlyArray,\n+ cachedExpandedFileIds: ReadonlyArray | undefined,\n+): ReadonlyArray {\n+ if (cachedExpandedFileIds === undefined) {\n+ return getDefaultExpandedFileIds(files);\n+ }\n+\n+ const fileIdSet = new Set(files.map((file) => file.id));\n+ return cachedExpandedFileIds.filter((id) => fileIdSet.has(id));\n+}\n+\n function getHighlightedTokensForLine(\n line: ReviewRenderableLineRow,\n highlightedFile: ReviewHighlightedFile | null,\n@@ -252,16 +293,13 @@ const ReviewLineRow = memo(function ReviewLineRow(props: {\n delayLongPress={220}\n onLongPress={props.onStartRangeSelection}\n onPress={props.onComment}\n- style={{ minWidth: props.viewportWidth }}\n+ style={{\n+ height: REVIEW_DIFF_LINE_HEIGHT,\n+ width: props.viewportWidth,\n+ overflow: "hidden",\n+ }}\n >\n- \n- \n- {lineNumber ?? ""}\n- \n- \n+ \n \n+ \n+ \n+ {props.lineNumber ?? ""}\n+ \n+ \n+ );\n+});\n+\n+const ReviewHunkGutter = memo(function ReviewHunkGutter(props: { readonly gutterWidth: number }) {\n+ return (\n+ \n+ );\n+});\n+\n const ReviewFileCard = memo(function ReviewFileCard(props: {\n readonly file: ReviewRenderableFile;\n readonly fileId: string;\n readonly expanded: boolean;\n+ readonly viewed: boolean;\n readonly viewportWidth: number;\n readonly onToggleFile: (fileId: string) => void;\n+ readonly onToggleViewed: (fileId: string) => void;\n }) {\n- const chrome = getFileHeaderChrome(props.file.changeType);\n+ const { expanded, file, fileId, onToggleFile, onToggleViewed, viewed, viewportWidth } = props;\n+ const chrome = getFileHeaderChrome(file.changeType);\n+ const iconColor = String(useThemeColor("--color-icon-muted"));\n+ const handleToggleFile = useCallback(() => {\n+ onToggleFile(fileId);\n+ }, [fileId, onToggleFile]);\n+ const handleToggleViewed = useCallback(() => {\n+ onToggleViewed(fileId);\n+ }, [fileId, onToggleViewed]);\n \n return (\n \n- props.onToggleFile(props.fileId)}>\n- \n- \n- \n- \n- \n- \n- \n- \n- \n- {props.file.path}\n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ {file.path}\n+ \n+ {file.previousPath && file.previousPath !== file.path ? (\n+ \n+ {file.previousPath}\n \n- {props.file.previousPath && props.file.previousPath !== props.file.path ? (\n- \n- {props.file.previousPath}\n- \n+ ) : null}\n+ \n+ \n+ \n+ \n+ -{file.deletions}\n+ \n+ \n+ +{file.additions}\n+ \n+ \n+ \n+ {viewed ? (\n+ \n ) : null}\n \n- \n- \n- \n- +{props.file.additions}\n- \n- \n- -{props.file.deletions}\n+ \n+ Viewed\n \n- \n+ \n \n- \n+ \n \n );\n });\n@@ -342,7 +453,11 @@ const ReviewFileSuppressedBody = memo(function ReviewFileSuppressedBody(props: {\n return (\n \n {props.message}\n {props.actionLabel && props.onLoadDiffFile ? (\n@@ -364,10 +479,13 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: {\n }) {\n return (\n \n- \n+ \n {props.header}\n {props.context ? ` ${props.context}` : ""}\n \n@@ -375,6 +493,61 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: {\n );\n });\n \n+const ReviewCodePanRow = memo(function ReviewCodePanRow(props: {\n+ readonly contentWidth: number;\n+ readonly horizontalOffset: SharedValue;\n+ readonly gutterWidth?: number;\n+ readonly viewportWidth: number;\n+ readonly leftGutter?: ReactElement;\n+ readonly children: ReactElement;\n+}) {\n+ const {\n+ children,\n+ contentWidth,\n+ gutterWidth = 0,\n+ horizontalOffset,\n+ leftGutter,\n+ viewportWidth,\n+ } = props;\n+ const dragStartOffset = useSharedValue(0);\n+ const visibleContentWidth = leftGutter ? viewportWidth - gutterWidth : viewportWidth;\n+ const maxOffset = Math.max(0, contentWidth - visibleContentWidth);\n+\n+ const panGesture = useMemo(\n+ () =>\n+ Gesture.Pan()\n+ .activeOffsetX([-8, 8])\n+ .failOffsetY([-10, 10])\n+ .onBegin(() => {\n+ dragStartOffset.value = horizontalOffset.value;\n+ })\n+ .onUpdate((event) => {\n+ "worklet";\n+ const nextOffset = dragStartOffset.value - event.translationX;\n+ horizontalOffset.value = Math.min(maxOffset, Math.max(0, nextOffset));\n+ }),\n+ [dragStartOffset, horizontalOffset, maxOffset],\n+ );\n+\n+ const contentStyle = useAnimatedStyle(\n+ () => ({\n+ transform: [{ translateX: -horizontalOffset.value }],\n+ }),\n+ [horizontalOffset],\n+ );\n+\n+ return (\n+ \n+ \n+ {leftGutter ?? null}\n+ \n+ {children}\n+ \n+ \n+ \n+ );\n+});\n+\n const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) {\n return (\n \n@@ -454,15 +627,19 @@ export function ReviewSheet() {\n const [highlightedFilesById, setHighlightedFilesById] = useState<\n Record\n >({});\n- const [visibleFileIds, setVisibleFileIds] = useState>([]);\n+ const deferredHighlightedFilesById = useDeferredValue(highlightedFilesById);\n+ const [localExpandedFileIdsBySection, setLocalExpandedFileIdsBySection] = useState<\n+ Record>\n+ >({});\n+ const [localViewedFileIdsBySection, setLocalViewedFileIdsBySection] = useState<\n+ Record>\n+ >({});\n const activeCommentTarget = useReviewCommentTarget();\n const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme;\n- const highlightQueueRef = useRef([]);\n- const highlightRequestedFileIdsRef = useRef>(new Set());\n- const highlightQueueGenerationRef = useRef(0);\n- const highlightQueueActiveRef = useRef(false);\n- const highlightableFilesByIdRef = useRef>(new Map());\n- const selectedThemeRef = useRef(selectedTheme);\n+ const reviewHighlighter = useReviewHighlighterStatus();\n+ const highlightRunIdRef = useRef(0);\n+ const highlightableFilesRef = useRef>([]);\n+ const horizontalOffsetByFileIdRef = useRef>>(new Map());\n const { selectedThreadCwd } = useSelectedThreadWorktree();\n \n const cwd = selectedThreadCwd;\n@@ -498,11 +675,13 @@ export function ReviewSheet() {\n const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;\n const parsedDiff = useMemo(\n () =>\n- getCachedReviewParsedDiff({\n- threadKey: reviewCache.threadKey,\n- sectionId: selectedSection?.id ?? null,\n- diff: selectedSection?.diff,\n- }),\n+ measureReviewWork("parse-diff", () =>\n+ getCachedReviewParsedDiff({\n+ threadKey: reviewCache.threadKey,\n+ sectionId: selectedSection?.id ?? null,\n+ diff: selectedSection?.diff,\n+ }),\n+ ),\n [reviewCache.threadKey, selectedSection?.diff, selectedSection?.id],\n );\n const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]);\n@@ -510,14 +689,53 @@ export function ReviewSheet() {\n () => countReviewCommentContexts(draftMessage),\n [draftMessage],\n );\n+ const viewportWidth = Math.max(width, 280);\n+\n+ useEffect(() => {\n+ if (!selectedSection?.id || parsedDiff.kind !== "files") {\n+ return;\n+ }\n+\n+ setLocalExpandedFileIdsBySection((current) => {\n+ if (current[selectedSection.id] !== undefined) {\n+ return current;\n+ }\n+\n+ return {\n+ ...current,\n+ [selectedSection.id]: getValidReviewExpandedFileIds(\n+ parsedDiff.files,\n+ reviewCache.expandedFileIdsBySection[selectedSection.id],\n+ ),\n+ };\n+ });\n+\n+ setLocalViewedFileIdsBySection((current) => {\n+ if (current[selectedSection.id] !== undefined) {\n+ return current;\n+ }\n+\n+ return {\n+ ...current,\n+ [selectedSection.id]: reviewCache.viewedFileIdsBySection[selectedSection.id] ?? [],\n+ };\n+ });\n+ }, [\n+ parsedDiff,\n+ reviewCache.expandedFileIdsBySection,\n+ reviewCache.viewedFileIdsBySection,\n+ selectedSection?.id,\n+ ]);\n \n const expandedFileIds = useMemo(\n () =>\n selectedSection?.id && parsedDiff.kind === "files"\n- ? (reviewCache.expandedFileIdsBySection[selectedSection.id] ??\n- getDefaultExpandedFileIds(parsedDiff.files))\n+ ? getValidReviewExpandedFileIds(\n+ parsedDiff.files,\n+ localExpandedFileIdsBySection[selectedSection.id],\n+ )\n : [],\n- [parsedDiff, reviewCache.expandedFileIdsBySection, selectedSection?.id],\n+ [localExpandedFileIdsBySection, parsedDiff, selectedSection?.id],\n );\n const revealedLargeFileIds = useMemo(\n () =>\n@@ -526,47 +744,96 @@ export function ReviewSheet() {\n : [],\n [reviewCache.revealedLargeFileIdsBySection, selectedSection?.id],\n );\n+ const viewedFileIds = useMemo(\n+ () => (selectedSection?.id ? (localViewedFileIdsBySection[selectedSection.id] ?? []) : []),\n+ [localViewedFileIdsBySection, selectedSection?.id],\n+ );\n+ const viewedFileIdSet = useMemo(() => new Set(viewedFileIds), [viewedFileIds]);\n const reviewListItems = useMemo(\n () =>\n selectedSection && parsedDiff.kind === "files"\n- ? buildReviewListItems({\n- files: parsedDiff.files,\n- expandedFileIds,\n- revealedLargeFileIds,\n- })\n+ ? measureReviewWork("build-list-items", () =>\n+ buildReviewListItems({\n+ files: parsedDiff.files,\n+ expandedFileIds,\n+ revealedLargeFileIds,\n+ }),\n+ )\n : [],\n [expandedFileIds, parsedDiff, revealedLargeFileIds, selectedSection],\n );\n- const reviewFileById = useMemo(() => {\n+ const reviewLineRowsByFileId = useMemo(() => {\n if (parsedDiff.kind !== "files") {\n- return new Map();\n+ return new Map>();\n }\n \n- return new Map(parsedDiff.files.map((file) => [file.id, file] as const));\n+ return measureReviewWork(\n+ "index-line-rows",\n+ () =>\n+ new Map(\n+ parsedDiff.files.map((file) => [\n+ file.id,\n+ file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"),\n+ ]),\n+ ),\n+ );\n }, [parsedDiff]);\n- const reviewLineRowsByFileId = useMemo(() => {\n+ const reviewContentWidthByFileId = useMemo(() => {\n if (parsedDiff.kind !== "files") {\n- return new Map>();\n+ return new Map();\n+ }\n+\n+ return measureReviewWork(\n+ "measure-file-widths",\n+ () =>\n+ new Map(\n+ parsedDiff.files.map((file) => [\n+ file.id,\n+ computeReviewFileContentWidth(\n+ file.rows,\n+ viewportWidth,\n+ computeReviewFileGutterWidth(file.rows),\n+ ),\n+ ]),\n+ ),\n+ );\n+ }, [parsedDiff, viewportWidth]);\n+ const reviewGutterWidthByFileId = useMemo(() => {\n+ if (parsedDiff.kind !== "files") {\n+ return new Map();\n }\n \n return new Map(\n- parsedDiff.files.map((file) => [\n- file.id,\n- file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"),\n- ]),\n+ parsedDiff.files.map((file) => [file.id, computeReviewFileGutterWidth(file.rows)]),\n );\n }, [parsedDiff]);\n- const reviewLineIndexByRowId = useMemo(() => {\n- const map = new Map();\n+ const getReviewFileHorizontalOffset = useCallback((fileId: string) => {\n+ let offset = horizontalOffsetByFileIdRef.current.get(fileId);\n+ if (!offset) {\n+ offset = makeMutable(0);\n+ horizontalOffsetByFileIdRef.current.set(fileId, offset);\n+ }\n \n- reviewLineRowsByFileId.forEach((rows) => {\n- rows.forEach((row, index) => {\n- map.set(row.id, index);\n- });\n- });\n+ return offset;\n+ }, []);\n+ useEffect(() => {\n+ const knownFileIds =\n+ parsedDiff.kind === "files" ? new Set(parsedDiff.files.map((file) => file.id)) : new Set();\n \n- return map;\n- }, [reviewLineRowsByFileId]);\n+ horizontalOffsetByFileIdRef.current.forEach((offset, fileId) => {\n+ if (!knownFileIds.has(fileId)) {\n+ horizontalOffsetByFileIdRef.current.delete(fileId);\n+ return;\n+ }\n+\n+ const contentWidth = reviewContentWidthByFileId.get(fileId) ?? viewportWidth;\n+ const gutterWidth = reviewGutterWidthByFileId.get(fileId) ?? 0;\n+ offset.value = Math.min(\n+ offset.value,\n+ Math.max(0, contentWidth - (viewportWidth - gutterWidth)),\n+ );\n+ });\n+ }, [parsedDiff, reviewContentWidthByFileId, reviewGutterWidthByFileId, viewportWidth]);\n const highlightableFiles = useMemo(() => {\n if (parsedDiff.kind !== "files") {\n return [] as ReadonlyArray;\n@@ -587,59 +854,13 @@ export function ReviewSheet() {\n );\n });\n }, [expandedFileIds, parsedDiff, revealedLargeFileIds]);\n- const highlightableFileIds = useMemo(\n- () => new Set(highlightableFiles.map((file) => file.id)),\n+ const highlightableFilesKey = useMemo(\n+ () => highlightableFiles.map((file) => `${file.id}:${file.cacheKey}`).join("\\n"),\n [highlightableFiles],\n );\n- const priorityHighlightFileIds = useMemo(() => {\n- if (parsedDiff.kind !== "files" || highlightableFiles.length === 0) {\n- return [] as ReadonlyArray;\n- }\n-\n- const fileIdsInPriorityOrder =\n- visibleFileIds.length > 0\n- ? visibleFileIds.filter((fileId) => highlightableFileIds.has(fileId))\n- : parsedDiff.files\n- .slice(0, REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT)\n- .map((file) => file.id)\n- .filter((fileId) => highlightableFileIds.has(fileId));\n-\n- if (fileIdsInPriorityOrder.length === 0) {\n- return [] as ReadonlyArray;\n- }\n-\n- const firstVisibleIndex = parsedDiff.files.findIndex(\n- (file) => file.id === fileIdsInPriorityOrder[0],\n- );\n- const lastVisibleIndex = parsedDiff.files.findIndex(\n- (file) => file.id === fileIdsInPriorityOrder[fileIdsInPriorityOrder.length - 1],\n- );\n-\n- if (firstVisibleIndex < 0 || lastVisibleIndex < 0) {\n- return fileIdsInPriorityOrder;\n- }\n-\n- const startIndex = Math.max(0, firstVisibleIndex - REVIEW_HIGHLIGHT_BACKTRACK_COUNT);\n- const endIndex = Math.min(\n- parsedDiff.files.length - 1,\n- lastVisibleIndex + REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT,\n- );\n-\n- const queuedIds: string[] = [];\n- for (let index = startIndex; index <= endIndex; index += 1) {\n- const fileId = parsedDiff.files[index]?.id;\n- if (fileId && highlightableFileIds.has(fileId)) {\n- queuedIds.push(fileId);\n- }\n- }\n-\n- return queuedIds;\n- }, [highlightableFileIds, highlightableFiles.length, parsedDiff, visibleFileIds]);\n- const viewportWidth = Math.max(width, 280);\n- const reviewListContentWidth = useMemo(\n- () => computeReviewListContentWidth(reviewListItems, viewportWidth),\n- [reviewListItems, viewportWidth],\n- );\n+ useEffect(() => {\n+ highlightableFilesRef.current = highlightableFiles;\n+ }, [highlightableFiles]);\n const loadGitDiffs = useCallback(async () => {\n if (!cwd) {\n return;\n@@ -714,100 +935,6 @@ export function ReviewSheet() {\n void loadGitDiffs();\n }, [loadGitDiffs]);\n \n- useEffect(() => {\n- selectedThemeRef.current = selectedTheme;\n- }, [selectedTheme]);\n-\n- useEffect(() => {\n- highlightableFilesByIdRef.current = new Map(highlightableFiles.map((file) => [file.id, file]));\n- }, [highlightableFiles]);\n-\n- const startHighlightQueueRunner = useCallback(function startHighlightQueueRunner() {\n- if (highlightQueueActiveRef.current) {\n- return;\n- }\n-\n- const generation = highlightQueueGenerationRef.current;\n- highlightQueueActiveRef.current = true;\n-\n- void (async () => {\n- try {\n- while (generation === highlightQueueGenerationRef.current) {\n- const nextFileId = highlightQueueRef.current.shift();\n- if (!nextFileId) {\n- break;\n- }\n-\n- const file = highlightableFilesByIdRef.current.get(nextFileId);\n- if (!file) {\n- continue;\n- }\n-\n- const theme = selectedThemeRef.current;\n- const cached = getCachedHighlightedReviewFile(file, theme);\n- if (cached) {\n- logReviewDiffDiagnostic("using cached highlighted file", {\n- fileId: file.id,\n- filePath: file.path,\n- theme,\n- });\n- setHighlightedFilesById((current) =>\n- current[file.id] === cached ? current : { ...current, [file.id]: cached },\n- );\n- continue;\n- }\n-\n- logReviewDiffDiagnostic("requesting highlighted file", {\n- fileId: file.id,\n- filePath: file.path,\n- theme,\n- });\n-\n- try {\n- await new Promise((resolve) => {\n- InteractionManager.runAfterInteractions(() => resolve());\n- });\n- const result = await highlightReviewFile(file, theme);\n- if (generation !== highlightQueueGenerationRef.current) {\n- logReviewDiffDiagnostic("discarding highlighted file after cancellation", {\n- fileId: file.id,\n- filePath: file.path,\n- });\n- return;\n- }\n-\n- logReviewDiffDiagnostic("received highlighted file", {\n- fileId: file.id,\n- filePath: file.path,\n- additionLines: result.additionLines.length,\n- deletionLines: result.deletionLines.length,\n- });\n- setHighlightedFilesById((current) => {\n- if (current[file.id] === result) {\n- return current;\n- }\n- return { ...current, [file.id]: result };\n- });\n- } catch (error) {\n- logReviewDiffDiagnostic("highlight request failed", {\n- fileId: file.id,\n- filePath: file.path,\n- error: error instanceof Error ? error.message : String(error),\n- });\n- }\n- }\n- } finally {\n- highlightQueueActiveRef.current = false;\n- if (\n- generation === highlightQueueGenerationRef.current &&\n- highlightQueueRef.current.length > 0\n- ) {\n- startHighlightQueueRunner();\n- }\n- }\n- })();\n- }, []);\n-\n useEffect(() => {\n if (reviewSections.length === 0) {\n return;\n@@ -854,15 +981,15 @@ export function ReviewSheet() {\n }\n \n updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {\n- if (existing !== undefined) {\n- const validIds = existing.filter((id) => parsedDiff.files.some((file) => file.id === id));\n- if (validIds.length === existing.length) {\n- return existing;\n- }\n- return validIds;\n+ const validIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);\n+ if (\n+ existing !== undefined &&\n+ validIds.length === existing.length &&\n+ validIds.every((id, index) => id === existing[index])\n+ ) {\n+ return existing;\n }\n-\n- return getDefaultExpandedFileIds(parsedDiff.files);\n+ return validIds;\n });\n }, [parsedDiff, reviewCache.threadKey, selectedSection?.id]);\n \n@@ -887,11 +1014,7 @@ export function ReviewSheet() {\n \n useEffect(() => {\n setHighlightedFilesById({});\n- setVisibleFileIds([]);\n- highlightQueueGenerationRef.current += 1;\n- highlightQueueRef.current = [];\n- highlightRequestedFileIdsRef.current = new Set();\n- highlightQueueActiveRef.current = false;\n+ highlightRunIdRef.current += 1;\n clearReviewHighlightFileCache();\n loggedMissingReviewTokenKeys.clear();\n logReviewDiffDiagnostic("reset highlighted files", {\n@@ -905,15 +1028,23 @@ export function ReviewSheet() {\n return;\n }\n \n+ markReviewEvent("parsed-diff-ready", {\n+ sectionId: selectedSection?.id ?? null,\n+ fileCount: parsedDiff.fileCount,\n+ additions: parsedDiff.additions,\n+ deletions: parsedDiff.deletions,\n+ renderedItems: reviewListItems.length,\n+ });\n logReviewDiffDiagnostic("parsed diff files", {\n selectedSectionId: selectedSection?.id ?? null,\n fileCount: parsedDiff.fileCount,\n renderableFileCount: parsedDiff.files.length,\n });\n- }, [parsedDiff, selectedSection?.id]);\n+ }, [parsedDiff, reviewListItems.length, selectedSection?.id]);\n \n useEffect(() => {\n- if (priorityHighlightFileIds.length === 0) {\n+ const files = highlightableFilesRef.current;\n+ if (files.length === 0) {\n logReviewDiffDiagnostic("no highlightable files", {\n selectedSectionId: selectedSection?.id ?? null,\n parsedDiffKind: parsedDiff.kind,\n@@ -922,33 +1053,98 @@ export function ReviewSheet() {\n return;\n }\n \n- const queuedFileIds: string[] = [];\n- priorityHighlightFileIds.forEach((fileId) => {\n- if (highlightRequestedFileIdsRef.current.has(fileId)) {\n- return;\n- }\n-\n- const file = highlightableFilesByIdRef.current.get(fileId);\n- if (!file) {\n- return;\n- }\n-\n- highlightRequestedFileIdsRef.current.add(fileId);\n- highlightQueueRef.current.push(fileId);\n- queuedFileIds.push(fileId);\n- });\n-\n- if (queuedFileIds.length === 0) {\n+ if (reviewHighlighter.status !== "ready") {\n+ logReviewDiffDiagnostic("waiting for highlighter provider", {\n+ selectedSectionId: selectedSection?.id ?? null,\n+ status: reviewHighlighter.status,\n+ error: reviewHighlighter.error,\n+ });\n return;\n }\n \n- logReviewDiffDiagnostic("scheduling file highlights", {\n+ const runId = highlightRunIdRef.current;\n+ let cancelled = false;\n+\n+ logReviewDiffDiagnostic("streaming file highlights", {\n selectedSectionId: selectedSection?.id ?? null,\n- fileCount: queuedFileIds.length,\n- fileIds: queuedFileIds,\n+ fileCount: files.length,\n });\n- startHighlightQueueRunner();\n- }, [parsedDiff.kind, priorityHighlightFileIds, selectedSection?.id, startHighlightQueueRunner]);\n+\n+ void (async () => {\n+ for (const file of files) {\n+ if (cancelled || runId !== highlightRunIdRef.current) {\n+ return;\n+ }\n+\n+ const cached = getCachedHighlightedReviewFile(file, selectedTheme);\n+ if (cached) {\n+ setHighlightedFilesById((current) =>\n+ current[file.id] === cached ? current : { ...current, [file.id]: cached },\n+ );\n+ continue;\n+ }\n+\n+ logReviewDiffDiagnostic("requesting highlighted file", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme: selectedTheme,\n+ });\n+\n+ try {\n+ const highlightStartedAt = performance.now();\n+ const result = await streamHighlightReviewFile(file, selectedTheme, (progress) => {\n+ if (cancelled || runId !== highlightRunIdRef.current) {\n+ return;\n+ }\n+\n+ if (!progress.complete) {\n+ return;\n+ }\n+\n+ logReviewDiffDiagnostic("received streamed highlighted file", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ highlightedLineCount: progress.highlightedLineCount,\n+ durationMs: Math.round(performance.now() - highlightStartedAt),\n+ });\n+ });\n+\n+ if (cancelled || runId !== highlightRunIdRef.current) {\n+ return;\n+ }\n+\n+ logReviewDiffDiagnostic("received highlighted file", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ additionLines: result.additionLines.length,\n+ deletionLines: result.deletionLines.length,\n+ });\n+ setHighlightedFilesById((current) =>\n+ current[file.id] === result ? current : { ...current, [file.id]: result },\n+ );\n+ } catch (error) {\n+ logReviewDiffDiagnostic("highlight request failed", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ error: error instanceof Error ? error.message : String(error),\n+ });\n+ }\n+\n+ await waitForReviewDelay(0);\n+ }\n+ })();\n+\n+ return () => {\n+ cancelled = true;\n+ };\n+ }, [\n+ highlightableFilesKey,\n+ parsedDiff.kind,\n+ reviewHighlighter.error,\n+ reviewHighlighter.status,\n+ selectedSection?.id,\n+ selectedTheme,\n+ ]);\n \n const refreshSelectedSection = useCallback(async () => {\n if (!selectedSection) {\n@@ -968,20 +1164,68 @@ export function ReviewSheet() {\n \n const handleToggleExpandedFile = useCallback(\n (fileId: string) => {\n- if (!reviewCache.threadKey || !selectedSection?.id || parsedDiff.kind !== "files") {\n+ if (!selectedSection?.id || parsedDiff.kind !== "files") {\n return;\n }\n \n- updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {\n- const currentIds = existing ?? getDefaultExpandedFileIds(parsedDiff.files);\n- return currentIds.includes(fileId)\n+ const sectionId = selectedSection.id;\n+\n+ setLocalExpandedFileIdsBySection((current) => {\n+ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, current[sectionId]);\n+ const nextIds = currentIds.includes(fileId)\n ? currentIds.filter((id) => id !== fileId)\n : [...currentIds, fileId];\n+\n+ return {\n+ ...current,\n+ [sectionId]: nextIds,\n+ };\n });\n+\n+ if (reviewCache.threadKey) {\n+ updateReviewExpandedFileIds(reviewCache.threadKey, sectionId, (existing) => {\n+ const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);\n+ return currentIds.includes(fileId)\n+ ? currentIds.filter((id) => id !== fileId)\n+ : [...currentIds, fileId];\n+ });\n+ }\n },\n [parsedDiff, reviewCache.threadKey, selectedSection?.id],\n );\n \n+ const handleToggleViewedFile = useCallback(\n+ (fileId: string) => {\n+ if (!selectedSection?.id) {\n+ return;\n+ }\n+\n+ const sectionId = selectedSection.id;\n+\n+ setLocalViewedFileIdsBySection((current) => {\n+ const currentIds = current[sectionId] ?? [];\n+ const nextIds = currentIds.includes(fileId)\n+ ? currentIds.filter((id) => id !== fileId)\n+ : [...currentIds, fileId];\n+\n+ return {\n+ ...current,\n+ [sectionId]: nextIds,\n+ };\n+ });\n+\n+ if (reviewCache.threadKey) {\n+ updateReviewViewedFileIds(reviewCache.threadKey, sectionId, (existing) => {\n+ const currentIds = existing ?? [];\n+ return currentIds.includes(fileId)\n+ ? currentIds.filter((id) => id !== fileId)\n+ : [...currentIds, fileId];\n+ });\n+ }\n+ },\n+ [reviewCache.threadKey, selectedSection?.id],\n+ );\n+\n const handleRevealLargeDiff = useCallback(\n (fileId: string) => {\n if (!reviewCache.threadKey || !selectedSection?.id) {\n@@ -1080,35 +1324,6 @@ export function ReviewSheet() {\n \n return <>{children};\n }, [error, parsedDiffNotice]);\n- const stickyHeaderIndices = useMemo(() => {\n- const itemOffset = listHeader ? 1 : 0;\n-\n- return reviewListItems.flatMap((item, index) =>\n- item.kind === "file-header" ? [index + itemOffset] : [],\n- );\n- }, [listHeader, reviewListItems]);\n-\n- const viewabilityConfigRef = useRef({\n- itemVisiblePercentThreshold: 10,\n- });\n- const onViewableItemsChangedRef = useRef(\n- ({\n- viewableItems,\n- }: {\n- readonly viewableItems: Array>;\n- readonly changed: Array>;\n- }) => {\n- const nextVisibleFileIds = Array.from(\n- new Set(\n- viewableItems\n- .filter((token) => token.isViewable && token.item !== undefined)\n- .map((token) => token.item.fileId),\n- ),\n- );\n-\n- setVisibleFileIds(nextVisibleFileIds);\n- },\n- );\n \n const renderReviewListItem = useCallback(\n ({ item }: ListRenderItemInfo) => {\n@@ -1116,112 +1331,142 @@ export function ReviewSheet() {\n return null;\n }\n \n+ let renderedItem: ReactElement | null = null;\n switch (item.kind) {\n case "file-header":\n- return (\n+ renderedItem = (\n \n );\n+ break;\n case "file-suppressed":\n- return (\n+ renderedItem = (\n \n );\n- case "hunk":\n- return (\n- \n+ break;\n+ case "hunk": {\n+ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth;\n+ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0;\n+\n+ renderedItem = (\n+ }\n+ viewportWidth={viewportWidth}\n+ >\n+ \n+ \n );\n+ break;\n+ }\n case "line": {\n- const file = reviewFileById.get(item.fileId);\n- if (!file) {\n- return null;\n- }\n-\n- const fileLineRows = reviewLineRowsByFileId.get(file.id) ?? [];\n- const lineIndex = reviewLineIndexByRowId.get(item.row.id);\n- if (lineIndex === undefined) {\n- return null;\n- }\n-\n+ const fileLineRows = reviewLineRowsByFileId.get(item.file.id) ?? [];\n const pendingSelectionForFile =\n pendingCommentSelection &&\n pendingCommentSelection.sectionTitle === selectedSection.title &&\n- pendingCommentSelection.filePath === file.path\n+ pendingCommentSelection.filePath === item.file.path\n ? pendingCommentSelection\n : null;\n const selectedTargetForFile =\n activeCommentTarget &&\n activeCommentTarget.sectionTitle === selectedSection.title &&\n- activeCommentTarget.filePath === file.path\n+ activeCommentTarget.filePath === item.file.path\n ? activeCommentTarget\n : null;\n const highlightedFile =\n- highlightedFilesById[file.id] ??\n- getCachedHighlightedReviewFile(file, selectedTheme) ??\n+ deferredHighlightedFilesById[item.file.id] ??\n+ getCachedHighlightedReviewFile(item.file, selectedTheme) ??\n null;\n+ const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth;\n+ const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0;\n \n if (highlightedFile === null) {\n- const missingTokenKey = `${selectedSection.id}:${file.id}`;\n+ const missingTokenKey = `${selectedSection.id}:${item.file.id}`;\n if (!loggedMissingReviewTokenKeys.has(missingTokenKey)) {\n loggedMissingReviewTokenKeys.add(missingTokenKey);\n logReviewDiffDiagnostic("rendering file without tokens", {\n sectionId: selectedSection.id,\n- fileId: file.id,\n- filePath: file.path,\n- highlightedFileKnownInState: highlightedFilesById[file.id] !== undefined,\n+ fileId: item.file.id,\n+ filePath: item.file.path,\n+ highlightedFileKnownInState:\n+ deferredHighlightedFilesById[item.file.id] !== undefined,\n });\n }\n }\n \n const selectionState =\n- pendingSelectionForFile?.anchorIndex === lineIndex\n+ pendingSelectionForFile?.anchorIndex === item.lineIndex\n ? ("anchor" as const)\n : selectedTargetForFile &&\n- lineIndex >= selectedTargetForFile.startIndex &&\n- lineIndex <= selectedTargetForFile.endIndex\n+ item.lineIndex >= selectedTargetForFile.startIndex &&\n+ item.lineIndex <= selectedTargetForFile.endIndex\n ? ("selected" as const)\n : null;\n \n- return (\n- \n- handlePressLine({\n- sectionTitle: selectedSection.title,\n- filePath: file.path,\n- lines: fileLineRows,\n- lineIndex,\n- })\n- }\n- onStartRangeSelection={() =>\n- handleStartRangeSelection({\n- sectionTitle: selectedSection.title,\n- filePath: file.path,\n- lines: fileLineRows,\n- lineIndex,\n- })\n+ renderedItem = (\n+ \n }\n- />\n+ viewportWidth={viewportWidth}\n+ >\n+ \n+ handlePressLine({\n+ sectionTitle: selectedSection.title,\n+ filePath: item.file.path,\n+ lines: fileLineRows,\n+ lineIndex: item.lineIndex,\n+ })\n+ }\n+ onStartRangeSelection={() =>\n+ handleStartRangeSelection({\n+ sectionTitle: selectedSection.title,\n+ filePath: item.file.path,\n+ lines: fileLineRows,\n+ lineIndex: item.lineIndex,\n+ })\n+ }\n+ />\n+ \n );\n+ break;\n }\n }\n+\n+ return renderedItem;\n },\n [\n activeCommentTarget,\n@@ -1229,14 +1474,17 @@ export function ReviewSheet() {\n handleRevealLargeDiff,\n handleStartRangeSelection,\n handleToggleExpandedFile,\n- highlightedFilesById,\n+ handleToggleViewedFile,\n+ getReviewFileHorizontalOffset,\n+ deferredHighlightedFilesById,\n pendingCommentSelection,\n- reviewFileById,\n- reviewLineIndexByRowId,\n+ reviewContentWidthByFileId,\n+ reviewGutterWidthByFileId,\n reviewLineRowsByFileId,\n- reviewListContentWidth,\n selectedSection,\n selectedTheme,\n+ viewedFileIdSet,\n+ viewportWidth,\n ],\n );\n \n@@ -1374,27 +1622,20 @@ export function ReviewSheet() {\n \n {selectedSection && parsedDiff.kind === "files" ? (\n item.id}\n+ initialNumToRender={20}\n+ maxToRenderPerBatch={20}\n+ updateCellsBatchingPeriod={16}\n+ windowSize={5}\n+ removeClippedSubviews={false}\n keyboardShouldPersistTaps="handled"\n ListHeaderComponent={listHeader}\n- stickyHeaderIndices={stickyHeaderIndices}\n- removeClippedSubviews={false}\n- initialNumToRender={24}\n- maxToRenderPerBatch={16}\n- updateCellsBatchingPeriod={16}\n- windowSize={10}\n- scrollEventThrottle={16}\n- onViewableItemsChanged={onViewableItemsChangedRef.current}\n- viewabilityConfig={viewabilityConfigRef.current}\n contentContainerStyle={{\n- paddingTop: REVIEW_HEADER_SPACING,\n+ paddingTop: topContentInset + REVIEW_HEADER_SPACING,\n paddingBottom: Math.max(insets.bottom, 18) + 18,\n }}\n />\ndiff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx\nindex d61924a62..3f2ae0160 100644\n--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx\n+++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx\n@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({\n default: "monospace",\n });\n \n+export const REVIEW_DIFF_LINE_HEIGHT = 26;\n+const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2;\n+\n export function renderVisibleWhitespace(value: string): string {\n const expandedTabs = value.replace(/\\t/g, " ");\n return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\\u00A0"));\n@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string |\n export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) {\n if (props.change === "delete") {\n return (\n- \n- \n- {Array.from({ length: 6 }, (_, index) => (\n- \n+ \n+ \n+ {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => (\n+ \n+ \n+ \n+ \n ))}\n \n \n@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo\n }\n \n return (\n- \n+ \n \n \n );\n@@ -63,6 +69,7 @@ export function DiffTokenText(props: {\n if (!props.tokens || props.tokens.length === 0) {\n return (\n {\n- it("defaults invalid values to javascript", () => {\n- expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("javascript");\n- expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("javascript");\n+ it("defaults invalid values to native", () => {\n+ expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("native");\n+ expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("native");\n });\n \n it("accepts supported values", () => {\ndiff --git a/apps/mobile/src/features/review/reviewHighlighterEngine.ts b/apps/mobile/src/features/review/reviewHighlighterEngine.ts\nindex 5ef9f055a..428768537 100644\n--- a/apps/mobile/src/features/review/reviewHighlighterEngine.ts\n+++ b/apps/mobile/src/features/review/reviewHighlighterEngine.ts\n@@ -11,7 +11,7 @@ export function resolveReviewHighlighterEnginePreference(\n case "native":\n return "native";\n default:\n- return "javascript";\n+ return "native";\n }\n }\n \ndiff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts\nindex a24a99ceb..69a6e7261 100644\n--- a/apps/mobile/src/features/review/reviewModel.test.ts\n+++ b/apps/mobile/src/features/review/reviewModel.test.ts\n@@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => {\n });\n });\n \n- it("flattens expanded files into virtualizable review items", () => {\n+ it("flattens expanded file rows into virtualized review items", () => {\n const file = makeRenderableFile({\n path: "apps/mobile/src/a.ts",\n rows: [\n@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => {\n \n expect(items).toEqual([\n expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }),\n- expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }),\n- expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }),\n+ expect.objectContaining({\n+ kind: "hunk",\n+ fileId: file.id,\n+ file,\n+ row: file.rows[0],\n+ }),\n+ expect.objectContaining({\n+ kind: "line",\n+ fileId: file.id,\n+ file,\n+ row: file.rows[1],\n+ lineIndex: 0,\n+ }),\n ]);\n });\n \ndiff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts\nindex 27e6d7ae4..1cfbf358c 100644\n--- a/apps/mobile/src/features/review/reviewModel.ts\n+++ b/apps/mobile/src/features/review/reviewModel.ts\n@@ -72,6 +72,7 @@ export interface ReviewHunkListItem {\n readonly kind: "hunk";\n readonly id: string;\n readonly fileId: string;\n+ readonly file: ReviewRenderableFile;\n readonly row: ReviewRenderableHunkRow;\n }\n \n@@ -79,7 +80,9 @@ export interface ReviewLineListItem {\n readonly kind: "line";\n readonly id: string;\n readonly fileId: string;\n+ readonly file: ReviewRenderableFile;\n readonly row: ReviewRenderableLineRow;\n+ readonly lineIndex: number;\n }\n \n export type ReviewListItem =\n@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil\n }\n \n // The flattened review list item model is inspired by pierre/diffs\' iterator-first\n-// virtualization architecture, adapted here for React Native and LegendList.\n+// virtualization architecture, adapted here for React Native virtualization.\n // Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs\n // Reference files:\n // - src/utils/iterateOverDiff.ts\n@@ -350,12 +353,14 @@ export function buildReviewListItems(input: {\n }\n }\n \n- file.rows.forEach((row) => {\n+ let lineIndex = 0;\n+ file.rows.forEach((row, rowIndex) => {\n if (row.kind === "hunk") {\n items.push({\n kind: "hunk",\n- id: row.id,\n+ id: `${file.id}:row:${rowIndex}:${row.id}`,\n fileId: file.id,\n+ file,\n row,\n });\n return;\n@@ -363,10 +368,13 @@ export function buildReviewListItems(input: {\n \n items.push({\n kind: "line",\n- id: row.id,\n+ id: `${file.id}:row:${rowIndex}:${row.id}`,\n fileId: file.id,\n+ file,\n row,\n+ lineIndex,\n });\n+ lineIndex += 1;\n });\n });\n \ndiff --git a/apps/mobile/src/features/review/reviewState.ts b/apps/mobile/src/features/review/reviewState.ts\nindex 06134db7d..c116f93fe 100644\n--- a/apps/mobile/src/features/review/reviewState.ts\n+++ b/apps/mobile/src/features/review/reviewState.ts\n@@ -64,6 +64,13 @@ const reviewRevealedLargeFileIdsByThreadKeyAtom = Atom.family((threadKey: string\n ),\n );\n \n+const reviewViewedFileIdsByThreadKeyAtom = Atom.family((threadKey: string) =>\n+ Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe(\n+ Atom.keepAlive,\n+ Atom.withLabel(`mobile:review:viewed-file-ids:${threadKey}`),\n+ ),\n+);\n+\n const reviewParsedDiffBySectionCacheKeyAtom = Atom.family((cacheKey: string) =>\n Atom.make<{ readonly diff: string | null; readonly parsed: ReviewParsedDiff } | null>(null).pipe(\n Atom.keepAlive,\n@@ -110,6 +117,9 @@ export function useReviewCacheForThread(input: {\n ? reviewRevealedLargeFileIdsByThreadKeyAtom(threadKey)\n : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,\n );\n+ const viewedFileIdsBySection = useAtomValue(\n+ threadKey ? reviewViewedFileIdsByThreadKeyAtom(threadKey) : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,\n+ );\n \n return {\n threadKey,\n@@ -118,6 +128,7 @@ export function useReviewCacheForThread(input: {\n selectedSectionId,\n expandedFileIdsBySection,\n revealedLargeFileIdsBySection,\n+ viewedFileIdsBySection,\n };\n }\n \n@@ -169,6 +180,20 @@ export function updateReviewRevealedLargeFileIds(\n });\n }\n \n+export function updateReviewViewedFileIds(\n+ threadKey: string,\n+ sectionId: string,\n+ update: (current: ReadonlyArray | undefined) => ReadonlyArray | undefined,\n+): void {\n+ const atom = reviewViewedFileIdsByThreadKeyAtom(threadKey);\n+ const current = appAtomRegistry.get(atom);\n+ const nextValue = update(current[sectionId]);\n+ appAtomRegistry.set(atom, {\n+ ...current,\n+ [sectionId]: nextValue,\n+ });\n+}\n+\n export function getCachedReviewParsedDiff(input: {\n readonly threadKey: string | null;\n readonly sectionId: string | null;\ndiff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts\nindex 05b5c9213..402d00668 100644\n--- a/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts\n+++ b/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts\n@@ -24,7 +24,7 @@ function makeRenderableFile(\n describe("highlightReviewFile", () => {\n it("preserves one highlighted token row per diff line even without trailing newlines", async () => {\n const file = makeRenderableFile({\n- path: "apps/mobile/src/example.test.ts",\n+ path: "apps/mobile/src/example.txt",\n additionLines: [\n \'const items = ["a"];\',\n \'expect(items).toEqual(["a"]);\',\n@@ -36,15 +36,23 @@ describe("highlightReviewFile", () => {\n const highlighted = await highlightReviewFile(file, "light");\n \n expect(highlighted.additionLines).toHaveLength(file.additionLines.length);\n- expect(highlighted.additionLines[0]?.some((token) => token.content === "const")).toBe(true);\n- expect(highlighted.additionLines[1]?.some((token) => token.content === "expect")).toBe(true);\n- expect(highlighted.additionLines[2]?.some((token) => token.content === "const")).toBe(true);\n- expect(highlighted.additionLines[3]?.some((token) => token.content === "expect")).toBe(true);\n+ expect(highlighted.additionLines[0]?.map((token) => token.content).join("")).toBe(\n+ file.additionLines[0],\n+ );\n+ expect(highlighted.additionLines[1]?.map((token) => token.content).join("")).toBe(\n+ file.additionLines[1],\n+ );\n+ expect(highlighted.additionLines[2]?.map((token) => token.content).join("")).toBe(\n+ file.additionLines[2],\n+ );\n+ expect(highlighted.additionLines[3]?.map((token) => token.content).join("")).toBe(\n+ file.additionLines[3],\n+ );\n });\n \n it("adds word-alt diff emphasis for paired deletion and addition lines", async () => {\n const file = makeRenderableFile({\n- path: "apps/mobile/src/example-inline-diff.test.ts",\n+ path: "apps/mobile/src/example-inline-diff.txt",\n additionLines: ["const after = 2;"],\n deletionLines: ["const before = 1;"],\n rows: [\n@@ -82,7 +90,7 @@ describe("highlightReviewFile", () => {\n it("falls back to plain tokens for very long lines", async () => {\n const longLine = `const value = "${"a".repeat(1_100)}";`;\n const file = makeRenderableFile({\n- path: "apps/mobile/src/example-long-line.ts",\n+ path: "apps/mobile/src/example-long-line.txt",\n additionLines: [longLine],\n rows: [\n {\ndiff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.ts\nindex f7a5c4125..eb6bf6973 100644\n--- a/apps/mobile/src/features/review/shikiReviewHighlighter.ts\n+++ b/apps/mobile/src/features/review/shikiReviewHighlighter.ts\n@@ -1,5 +1,14 @@\n import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";\n import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";\n+import bashLanguage from "@shikijs/langs/bash";\n+import javascriptLanguage from "@shikijs/langs/javascript";\n+import jsonLanguage from "@shikijs/langs/json";\n+import jsxLanguage from "@shikijs/langs/jsx";\n+import tsxLanguage from "@shikijs/langs/tsx";\n+import typescriptLanguage from "@shikijs/langs/typescript";\n+import yamlLanguage from "@shikijs/langs/yaml";\n+import githubDarkDefault from "@shikijs/themes/github-dark-default";\n+import githubLightDefault from "@shikijs/themes/github-light-default";\n import { getFiletypeFromFileName } from "@pierre/diffs/utils";\n \n import {\n@@ -11,6 +20,7 @@ import type { ReviewRenderableFile, ReviewRenderableLineRow } from "./reviewMode\n import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs";\n \n export type ReviewDiffTheme = "light" | "dark";\n+export type { ReviewHighlighterEngine };\n \n export interface ReviewHighlightedToken {\n content: string;\n@@ -24,12 +34,19 @@ export interface ReviewHighlightedFile {\n readonly deletionLines: ReadonlyArray>;\n }\n \n+export interface ReviewHighlightFileProgress {\n+ readonly highlightedFile: ReviewHighlightedFile;\n+ readonly complete: boolean;\n+ readonly highlightedLineCount: number;\n+}\n+\n const SHIKI_THEME_NAME_BY_SCHEME = {\n light: "github-light-default",\n dark: "github-dark-default",\n } as const;\n const REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE =\n- process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? "javascript";\n+ process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ??\n+ (process.env.NODE_ENV === "test" ? "javascript" : "native");\n const REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE = resolveReviewHighlighterEnginePreference(\n REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE,\n );\n@@ -38,12 +55,30 @@ const REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE = resolveReviewHighlighterBooleanF\n false,\n );\n const REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT = 8;\n-const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 40;\n-const REVIEW_HIGHLIGHT_CHUNK_SIZE = 20;\n+const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 8;\n+const REVIEW_HIGHLIGHT_CHUNK_SIZE = 200;\n const REVIEW_TOKENIZE_MAX_LINE_LENGTH = 1_000;\n const highlightCache = new Map>();\n const resolvedHighlightCache = new Map();\n-const loadedLanguages = new Set(["text"]);\n+const REVIEW_INITIAL_LANGUAGE_MODULES = [\n+ bashLanguage,\n+ javascriptLanguage,\n+ jsonLanguage,\n+ jsxLanguage,\n+ tsxLanguage,\n+ typescriptLanguage,\n+ yamlLanguage,\n+] satisfies Parameters[0]["langs"];\n+const loadedLanguages = new Set([\n+ "text",\n+ "bash",\n+ "javascript",\n+ "json",\n+ "jsx",\n+ "tsx",\n+ "typescript",\n+ "yaml",\n+]);\n const languageLoadingPromises = new Map>();\n const languageImports: Partial Promise>> = {\n javascript: () => import("@shikijs/langs/javascript"),\n@@ -215,21 +250,13 @@ function joinPatchLines(lines: ReadonlyArray): string {\n \n function waitForNextFrame(): Promise {\n return new Promise((resolve) => {\n- if (typeof requestAnimationFrame === "function") {\n- requestAnimationFrame(() => resolve());\n- return;\n- }\n-\n setTimeout(resolve, 0);\n });\n }\n \n async function getHighlighter(): Promise {\n if (!highlighterPromise) {\n- const configuredHighlighterPromise = Promise.all([\n- import("@shikijs/themes/github-light-default"),\n- import("@shikijs/themes/github-dark-default"),\n- ]).then(async ([lightThemeModule, darkThemeModule]) => {\n+ const configuredHighlighterPromise = (async () => {\n let nativeEngineAvailable = false;\n \n logReviewHighlighterDiagnostic("initializing", {\n@@ -238,12 +265,11 @@ async function getHighlighter(): Promise {\n resultCacheDisabled: REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE,\n });\n \n- const themes = [lightThemeModule.default, darkThemeModule.default];\n+ const themes = [githubLightDefault, githubDarkDefault];\n \n if (REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE !== "javascript") {\n try {\n const nativeEngineModule = await import("react-native-shiki-engine");\n- logReviewHighlighterDiagnostic("imported react-native-shiki-engine");\n nativeEngineAvailable = nativeEngineModule.isNativeEngineAvailable();\n logReviewHighlighterDiagnostic("checked native engine availability", {\n nativeEngineAvailable,\n@@ -253,7 +279,7 @@ async function getHighlighter(): Promise {\n logReviewHighlighterDiagnostic("creating native regex engine");\n const highlighter = await createHighlighterCore({\n themes,\n- langs: [],\n+ langs: REVIEW_INITIAL_LANGUAGE_MODULES,\n engine: nativeEngineModule.createNativeEngine(),\n });\n logReviewHighlighterDiagnostic("using native engine");\n@@ -281,7 +307,7 @@ async function getHighlighter(): Promise {\n );\n const highlighter = await createHighlighterCore({\n themes,\n- langs: [],\n+ langs: REVIEW_INITIAL_LANGUAGE_MODULES,\n engine: createJavaScriptRegexEngine(),\n });\n logReviewHighlighterDiagnostic("using javascript engine", {\n@@ -291,7 +317,7 @@ async function getHighlighter(): Promise {\n highlighter,\n engine,\n };\n- });\n+ })();\n \n highlighterPromise = configuredHighlighterPromise\n .then((result) => result.highlighter)\n@@ -316,11 +342,52 @@ export async function getActiveReviewHighlighterEngine(): Promise {\n+ await getHighlighter();\n+}\n+\n+export async function prepareReviewHighlighterLanguages(\n+ languages: ReadonlyArray,\n+): Promise {\n+ const highlighter = await getHighlighter();\n+ await Promise.all(\n+ languages.map(async (language) => {\n+ const candidate = resolveLanguageAlias(language);\n+ if (candidate === "text" || !(candidate in languageImports)) {\n+ return;\n+ }\n+\n+ await loadSingleLanguage(highlighter, candidate);\n+ }),\n+ );\n+}\n+\n function resolveLanguageAlias(language: string): string {\n const normalized = language.toLowerCase();\n return languageAliases[normalized] ?? normalized;\n }\n \n+function resolveLoadedLanguageFromPath(\n+ path: string,\n+ languageHint: string | null = null,\n+): string | null {\n+ const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);\n+ if (!detectedLanguage) {\n+ return "text";\n+ }\n+\n+ const candidate = resolveLanguageAlias(detectedLanguage);\n+ if (candidate === "text" || candidate === "ansi") {\n+ return "text";\n+ }\n+\n+ if (!(candidate in languageImports)) {\n+ return "text";\n+ }\n+\n+ return loadedLanguages.has(candidate) ? candidate : null;\n+}\n+\n async function loadSingleLanguage(\n highlighter: HighlighterCore,\n language: string,\n@@ -360,6 +427,11 @@ async function resolveLanguageFromPath(\n path: string,\n languageHint: string | null = null,\n ): Promise {\n+ const loadedLanguage = resolveLoadedLanguageFromPath(path, languageHint);\n+ if (loadedLanguage) {\n+ return loadedLanguage;\n+ }\n+\n const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);\n if (!detectedLanguage) {\n return "text";\n@@ -374,8 +446,12 @@ async function resolveLanguageFromPath(\n return "text";\n }\n \n+ if (loadedLanguages.has(candidate)) {\n+ return candidate;\n+ }\n+\n const highlighter = await getHighlighter();\n- const loaded = await loadSingleLanguage(highlighter, resolveLanguageAlias(candidate));\n+ const loaded = await loadSingleLanguage(highlighter, candidate);\n if (!loaded) {\n return "text";\n }\n@@ -384,7 +460,10 @@ async function resolveLanguageFromPath(\n }\n \n async function resolveLanguage(file: ReviewRenderableFile): Promise {\n- return resolveLanguageFromPath(file.path, file.languageHint);\n+ return (\n+ resolveLoadedLanguageFromPath(file.path, file.languageHint) ??\n+ (await resolveLanguageFromPath(file.path, file.languageHint))\n+ );\n }\n \n function normalizeHighlightedLines(\n@@ -399,6 +478,18 @@ function normalizeHighlightedLines(\n );\n }\n \n+function makePlainHighlightedLines(\n+ lines: ReadonlyArray,\n+): ReadonlyArray> {\n+ return lines.map((line) => [\n+ {\n+ content: stripTrailingNewline(line),\n+ color: null,\n+ fontStyle: null,\n+ },\n+ ]);\n+}\n+\n function applyWordAltDiffHighlightsToFile(\n file: ReviewRenderableFile,\n highlighted: ReviewHighlightedFile,\n@@ -594,6 +685,67 @@ async function highlightLines(\n return highlightedLines;\n }\n \n+async function highlightPatchLinesInChunks(input: {\n+ readonly lines: ReadonlyArray;\n+ readonly language: string;\n+ readonly theme: string;\n+ readonly onChunk: (\n+ startIndex: number,\n+ tokens: ReadonlyArray>,\n+ ) => void;\n+}): Promise>> {\n+ if (input.lines.length === 0) {\n+ return [];\n+ }\n+\n+ const highlighter = await getHighlighter();\n+ const highlightedLines: Array> = [];\n+\n+ for (\n+ let startIndex = 0;\n+ startIndex < input.lines.length;\n+ startIndex += REVIEW_HIGHLIGHT_CHUNK_SIZE\n+ ) {\n+ const lineChunk = input.lines.slice(startIndex, startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE);\n+ const chunkTokens: Array> = [];\n+ const tokenizableLines: string[] = [];\n+ const tokenizableIndexes: number[] = [];\n+\n+ lineChunk.forEach((line, index) => {\n+ const strippedLine = stripTrailingNewline(line);\n+ if (strippedLine.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH) {\n+ chunkTokens[index] = [{ content: strippedLine, color: null, fontStyle: null }];\n+ return;\n+ }\n+\n+ tokenizableIndexes.push(index);\n+ tokenizableLines.push(strippedLine);\n+ });\n+\n+ if (tokenizableLines.length > 0) {\n+ const tokenLines = highlighter.codeToTokensBase(tokenizableLines.join("\\n"), {\n+ lang: input.language,\n+ theme: input.theme,\n+ });\n+ const normalizedTokenLines = normalizeHighlightedLines(tokenLines);\n+\n+ tokenizableIndexes.forEach((chunkIndex, tokenIndex) => {\n+ chunkTokens[chunkIndex] = normalizedTokenLines[tokenIndex] ?? [];\n+ });\n+ }\n+\n+ const completedChunk = lineChunk.map((_, index) => chunkTokens[index] ?? []);\n+ highlightedLines.push(...completedChunk);\n+ input.onChunk(startIndex, completedChunk);\n+\n+ if (startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE < input.lines.length) {\n+ await waitForNextFrame();\n+ }\n+ }\n+\n+ return highlightedLines;\n+}\n+\n function getHighlightCacheKey(file: ReviewRenderableFile, theme: ReviewDiffTheme): string {\n return `${SHIKI_THEME_NAME_BY_SCHEME[theme]}:${file.cacheKey}`;\n }\n@@ -667,7 +819,28 @@ export async function highlightReviewFile(\n deletionLineCount: file.deletionLines.length,\n rowCount: file.rows.length,\n });\n- const language = await resolveLanguage(file);\n+ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);\n+ const language = loadedLanguage ?? (await resolveLanguage(file));\n+ if (language === "text") {\n+ const highlighted = applyWordAltDiffHighlightsToFile(file, {\n+ additionLines: makePlainHighlightedLines(file.additionLines),\n+ deletionLines: makePlainHighlightedLines(file.deletionLines),\n+ });\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ storeResolvedHighlightedFile(cacheKey, highlighted);\n+ }\n+ logReviewHighlighterDiagnostic("file highlight complete", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ language,\n+ highlightedAdditionLineCount: highlighted.additionLines.length,\n+ highlightedDeletionLineCount: highlighted.deletionLines.length,\n+ durationMs: Date.now() - startedAt,\n+ });\n+ return highlighted;\n+ }\n+\n const additionLines = await highlightLines(\n joinPatchLines(file.additionLines),\n language,\n@@ -707,6 +880,113 @@ export async function highlightReviewFile(\n });\n }\n \n+export async function streamHighlightReviewFile(\n+ file: ReviewRenderableFile,\n+ theme: ReviewDiffTheme,\n+ onProgress: (progress: ReviewHighlightFileProgress) => void,\n+): Promise {\n+ const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[theme];\n+ const cacheKey = getHighlightCacheKey(file, theme);\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ const resolved = resolvedHighlightCache.get(cacheKey);\n+ if (resolved) {\n+ onProgress({\n+ highlightedFile: resolved,\n+ complete: true,\n+ highlightedLineCount: resolved.additionLines.length + resolved.deletionLines.length,\n+ });\n+ return resolved;\n+ }\n+ }\n+\n+ const startedAt = Date.now();\n+ logReviewHighlighterDiagnostic("file stream highlight start", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ additionLineCount: file.additionLines.length,\n+ deletionLineCount: file.deletionLines.length,\n+ rowCount: file.rows.length,\n+ });\n+\n+ const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);\n+ const language = loadedLanguage ?? (await resolveLanguage(file));\n+ if (language === "text") {\n+ const highlighted = applyWordAltDiffHighlightsToFile(file, {\n+ additionLines: makePlainHighlightedLines(file.additionLines),\n+ deletionLines: makePlainHighlightedLines(file.deletionLines),\n+ });\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ storeResolvedHighlightedFile(cacheKey, highlighted);\n+ }\n+ onProgress({\n+ highlightedFile: highlighted,\n+ complete: true,\n+ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,\n+ });\n+ logReviewHighlighterDiagnostic("file stream highlight complete", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ language,\n+ highlightedAdditionLineCount: highlighted.additionLines.length,\n+ highlightedDeletionLineCount: highlighted.deletionLines.length,\n+ highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,\n+ durationMs: Date.now() - startedAt,\n+ });\n+ return highlighted;\n+ }\n+\n+ const additionLines: Array> = [];\n+ const deletionLines: Array> = [];\n+ let highlightedLineCount = 0;\n+\n+ await highlightPatchLinesInChunks({\n+ lines: file.additionLines,\n+ language,\n+ theme: shikiTheme,\n+ onChunk: (startIndex, tokens) => {\n+ tokens.forEach((lineTokens, index) => {\n+ additionLines[startIndex + index] = lineTokens;\n+ });\n+ highlightedLineCount += tokens.length;\n+ },\n+ });\n+ await waitForNextFrame();\n+ await highlightPatchLinesInChunks({\n+ lines: file.deletionLines,\n+ language,\n+ theme: shikiTheme,\n+ onChunk: (startIndex, tokens) => {\n+ tokens.forEach((lineTokens, index) => {\n+ deletionLines[startIndex + index] = lineTokens;\n+ });\n+ highlightedLineCount += tokens.length;\n+ },\n+ });\n+\n+ const highlighted = applyWordAltDiffHighlightsToFile(file, { additionLines, deletionLines });\n+ if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {\n+ storeResolvedHighlightedFile(cacheKey, highlighted);\n+ }\n+ onProgress({\n+ highlightedFile: highlighted,\n+ complete: true,\n+ highlightedLineCount,\n+ });\n+ logReviewHighlighterDiagnostic("file stream highlight complete", {\n+ fileId: file.id,\n+ filePath: file.path,\n+ theme,\n+ language,\n+ highlightedAdditionLineCount: highlighted.additionLines.length,\n+ highlightedDeletionLineCount: highlighted.deletionLines.length,\n+ highlightedLineCount,\n+ durationMs: Date.now() - startedAt,\n+ });\n+ return highlighted;\n+}\n+\n export async function highlightReviewSelectedLines(input: {\n readonly filePath: string;\n readonly lines: ReadonlyArray;\n@@ -717,7 +997,9 @@ export async function highlightReviewSelectedLines(input: {\n return {};\n }\n \n- const language = await resolveLanguageFromPath(input.filePath, input.languageHint ?? null);\n+ const loadedLanguage = resolveLoadedLanguageFromPath(input.filePath, input.languageHint ?? null);\n+ const language =\n+ loadedLanguage ?? (await resolveLanguageFromPath(input.filePath, input.languageHint ?? null));\n const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[input.theme];\n const additionLikeLines = input.lines\n .filter((line) => line.change !== "delete")\ndiff --git a/apps/mobile/docs/review-profiling.md b/apps/mobile/docs/review-profiling.md\nnew file mode 100644\nindex 000000000..6977eaf6e\n--- /dev/null\n+++ b/apps/mobile/docs/review-profiling.md\n@@ -0,0 +1,80 @@\n+# Review Screen Profiling\n+\n+Use this when the mobile review screen is slow or crashes while opening large diffs.\n+\n+## Preferred Capture: React Native DevTools Performance\n+\n+This app is on Expo SDK 55 / React Native 0.83 with Hermes, so the best first trace is the React Native DevTools Performance recording. The review screen also emits `t3.review.*` user timing marks in development builds so the trace can show parse, list-building, row indexing, and syntax-highlighting work.\n+\n+1. Start the development client:\n+\n+ ```sh\n+ cd apps/mobile\n+ bun dev:client\n+ ```\n+\n+2. Open the app in the iOS Simulator or on the device using the development client.\n+\n+3. In the terminal running Expo, press `j` to open React Native DevTools.\n+\n+4. In DevTools, open the `Performance` panel.\n+\n+5. Start recording.\n+\n+6. In the app, reproduce the slow path:\n+ - Navigate to the thread.\n+ - Open `Files Changed`.\n+ - Select the largest review source.\n+ - Expand a few large files or tap `Load diff`.\n+ - Scroll until the app is clearly slow or until just before it crashes.\n+\n+7. Stop recording.\n+\n+8. Export or save the Performance recording as a JSON trace.\n+\n+Send that exported trace file here. Also include the device/simulator model and whether it was iOS or Android.\n+\n+## Android Fallback: Hermes Sampling Profile\n+\n+Use this if the app crashes before DevTools can export a trace, or if we need deeper JavaScript stack samples.\n+\n+1. Run Android dev client:\n+\n+ ```sh\n+ cd apps/mobile\n+ bun android:dev\n+ bun dev:client\n+ ```\n+\n+2. Open the developer menu from the Expo terminal with `d`.\n+\n+3. Select `Enable Sampling Profiler`.\n+\n+4. Reproduce the review-screen slowdown.\n+\n+5. Open the developer menu again with `d`.\n+\n+6. Select `Disable Sampling Profiler`.\n+\n+7. Pull and convert the Hermes profile:\n+\n+ ```sh\n+ cd apps/mobile\n+ mkdir -p profiles/review\n+ bunx react-native profile-hermes profiles/review\n+ ```\n+\n+8. Send the generated Chrome trace/profile file from `apps/mobile/profiles/review`.\n+\n+For the development app variant, the Android package is `com.t3tools.t3code.dev`.\n+\n+## What To Capture\n+\n+For the first trace, do not optimize the repro. We want the slowest realistic case:\n+\n+- A diff with many files and large line counts.\n+- At least one `Load diff` action for a suppressed large diff.\n+- One vertical scroll pass after the content appears.\n+- One horizontal scroll of a long file, if that is part of the slowdown.\n+\n+If the app crashes, note the last visible action before the crash and attach device logs if available.\ndiff --git a/apps/mobile/src/app/debug/syntax-highlight.tsx b/apps/mobile/src/app/debug/syntax-highlight.tsx\nnew file mode 100644\nindex 000000000..c2a36d126\n--- /dev/null\n+++ b/apps/mobile/src/app/debug/syntax-highlight.tsx\n@@ -0,0 +1,423 @@\n+import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";\n+import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";\n+import typescriptLanguage from "@shikijs/langs/typescript";\n+import githubDarkDefault from "@shikijs/themes/github-dark-default";\n+import githubLightDefault from "@shikijs/themes/github-light-default";\n+import Stack from "expo-router/stack";\n+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";\n+import {\n+ FlatList,\n+ Pressable,\n+ Text as NativeText,\n+ type ListRenderItemInfo,\n+ useColorScheme,\n+ useWindowDimensions,\n+ View,\n+} from "react-native";\n+import { useSafeAreaInsets } from "react-native-safe-area-context";\n+\n+import { AppText as Text } from "../../components/AppText";\n+import { cn } from "../../lib/cn";\n+import { useThemeColor } from "../../lib/useThemeColor";\n+\n+type DebugHighlightEngine = "native" | "javascript";\n+\n+type DebugToken = {\n+ readonly content: string;\n+ readonly color: string | null;\n+ readonly fontStyle: number | null;\n+};\n+\n+type DebugLine = {\n+ readonly id: string;\n+ readonly chunkIndex: number;\n+ readonly indexInChunk: number;\n+ readonly lineNumber: number;\n+ readonly content: string;\n+};\n+\n+type DebugHighlighterHandle = {\n+ readonly engine: DebugHighlightEngine;\n+ readonly tokenize: (\n+ code: string,\n+ options: { readonly lang: string; readonly theme: string },\n+ ) => ReadonlyArray>;\n+};\n+\n+const DEBUG_LINE_COUNT = 10_000;\n+const DEBUG_CHUNK_SIZE = 500;\n+const DEBUG_LINE_HEIGHT = 24;\n+const DEBUG_GUTTER_WIDTH = 58;\n+const DEBUG_CONTENT_WIDTH = 3_200;\n+const DEBUG_MONO_FONT_FAMILY = "BerkeleyMono-Regular";\n+const DEBUG_THEME_NAME_BY_SCHEME = {\n+ dark: "github-dark-default",\n+ light: "github-light-default",\n+} as const;\n+\n+let nativeHighlighterPromise: Promise | null = null;\n+let javascriptHighlighterPromise: Promise | null = null;\n+\n+function waitForNextFrame(): Promise {\n+ return new Promise((resolve) => setTimeout(resolve, 0));\n+}\n+\n+function normalizeTokens(\n+ tokenLines: ReadonlyArray>,\n+): ReadonlyArray> {\n+ return tokenLines.map((line) =>\n+ line.map((token) => ({\n+ content: token.content,\n+ color: token.color ?? null,\n+ fontStyle: token.fontStyle ?? null,\n+ })),\n+ );\n+}\n+\n+function makeDebugCodeLine(index: number): string {\n+ const label = `generatedLine${String(index).padStart(5, "0")}`;\n+ switch (index % 8) {\n+ case 0:\n+ return `export async function ${label}(input: { value: number; name: string }) {`;\n+ case 1:\n+ return ` const normalized = input.name.trim().toLowerCase();`;\n+ case 2:\n+ return ` const result = await Promise.resolve({ id: "${label}", score: input.value * ${index + 1} });`;\n+ case 3:\n+ return ` if (result.score > ${index * 17}) return normalized + ":" + result.id;`;\n+ case 4:\n+ return ` return [normalized, String(result.score), "${"x".repeat((index % 24) + 8)}"].join("/");`;\n+ case 5:\n+ return `}`;\n+ case 6:\n+ return `type ${label}Record = Readonly<{ id: string; createdAt: Date; tags: string[] }>;`;\n+ default:\n+ return `const ${label}: ${label}Record = { id: "${label}", createdAt: new Date(), tags: ["debug", "highlight"] };`;\n+ }\n+}\n+\n+function makeDebugLines(): ReadonlyArray {\n+ return Array.from({ length: DEBUG_LINE_COUNT }, (_, index) => ({\n+ id: `line:${index + 1}`,\n+ chunkIndex: Math.floor(index / DEBUG_CHUNK_SIZE),\n+ indexInChunk: index % DEBUG_CHUNK_SIZE,\n+ lineNumber: index + 1,\n+ content: makeDebugCodeLine(index + 1),\n+ }));\n+}\n+\n+async function createNativeDebugHighlighter(): Promise {\n+ const nativeEngineModule = await import("react-native-shiki-engine");\n+ if (!nativeEngineModule.isNativeEngineAvailable()) {\n+ throw new Error("Native Shiki engine is not available in this build.");\n+ }\n+\n+ const highlighter = await createHighlighterCore({\n+ langs: [typescriptLanguage],\n+ themes: [githubLightDefault, githubDarkDefault],\n+ engine: nativeEngineModule.createNativeEngine(),\n+ });\n+\n+ return {\n+ engine: "native",\n+ tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),\n+ };\n+}\n+\n+async function createJavascriptDebugHighlighter(): Promise {\n+ const highlighter: HighlighterCore = await createHighlighterCore({\n+ langs: [typescriptLanguage],\n+ themes: [githubLightDefault, githubDarkDefault],\n+ engine: createJavaScriptRegexEngine(),\n+ });\n+\n+ return {\n+ engine: "javascript",\n+ tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),\n+ };\n+}\n+\n+async function getDebugHighlighter(engine: DebugHighlightEngine): Promise {\n+ if (engine === "native") {\n+ nativeHighlighterPromise ??= createNativeDebugHighlighter();\n+ return nativeHighlighterPromise;\n+ }\n+\n+ javascriptHighlighterPromise ??= createJavascriptDebugHighlighter();\n+ return javascriptHighlighterPromise;\n+}\n+\n+const TokenText = memo(function TokenText(props: {\n+ readonly content: string;\n+ readonly tokens: ReadonlyArray | null;\n+}) {\n+ if (!props.tokens) {\n+ return (\n+ \n+ {props.content}\n+ \n+ );\n+ }\n+\n+ let tokenOffset = 0;\n+\n+ return (\n+ \n+ {props.tokens.map((token) => {\n+ const tokenKey = `${tokenOffset}:${token.content.length}:${token.color ?? ""}:${token.fontStyle ?? ""}`;\n+ tokenOffset += token.content.length;\n+ const fontWeight =\n+ token.fontStyle !== null && (token.fontStyle & 2) === 2\n+ ? ("700" as const)\n+ : ("500" as const);\n+ const fontStyle =\n+ token.fontStyle !== null && (token.fontStyle & 1) === 1\n+ ? ("italic" as const)\n+ : ("normal" as const);\n+\n+ return (\n+ \n+ {token.content}\n+ \n+ );\n+ })}\n+ \n+ );\n+});\n+\n+const DebugCodeLineRow = memo(function DebugCodeLineRow(props: {\n+ readonly item: DebugLine;\n+ readonly tokens: ReadonlyArray | null;\n+ readonly width: number;\n+}) {\n+ return (\n+ \n+ \n+ {props.item.lineNumber}\n+ \n+ \n+ \n+ \n+ \n+ );\n+});\n+\n+function EngineToggle(props: {\n+ readonly engine: DebugHighlightEngine;\n+ readonly onChangeEngine: (engine: DebugHighlightEngine) => void;\n+}) {\n+ return (\n+ \n+ {(["native", "javascript"] as const).map((engine) => {\n+ const selected = props.engine === engine;\n+ return (\n+ props.onChangeEngine(engine)}\n+ >\n+ \n+ {engine === "javascript" ? "JS" : "Native"}\n+ \n+ \n+ );\n+ })}\n+ \n+ );\n+}\n+\n+export default function SyntaxHighlightDebugRoute() {\n+ const insets = useSafeAreaInsets();\n+ const { width } = useWindowDimensions();\n+ const colorScheme = useColorScheme();\n+ const headerIcon = String(useThemeColor("--color-icon"));\n+ const themeName = DEBUG_THEME_NAME_BY_SCHEME[colorScheme === "dark" ? "dark" : "light"];\n+ const [engine, setEngine] = useState("native");\n+ const [tokensByChunkIndex, setTokensByChunkIndex] = useState<\n+ Record>>\n+ >({});\n+ const [status, setStatus] = useState("Idle");\n+ const renderStartRef = useRef(null);\n+ const generationRef = useRef(0);\n+ const lines = useMemo(() => makeDebugLines(), []);\n+\n+ useEffect(() => {\n+ const generation = generationRef.current + 1;\n+ generationRef.current = generation;\n+ renderStartRef.current = performance.now();\n+ setTokensByChunkIndex({});\n+ setStatus("Initializing highlighter");\n+\n+ void (async () => {\n+ try {\n+ const highlighterStartedAt = performance.now();\n+ const highlighter = await getDebugHighlighter(engine);\n+ if (generation !== generationRef.current) {\n+ return;\n+ }\n+\n+ console.log("[debug-syntax-scratch] initialize", {\n+ durationMs: Math.round(performance.now() - highlighterStartedAt),\n+ engine: highlighter.engine,\n+ });\n+\n+ let firstChunkMs: number | null = null;\n+ const totalStartedAt = performance.now();\n+ setStatus(`Streaming ${DEBUG_LINE_COUNT.toLocaleString()} lines`);\n+\n+ for (let startIndex = 0; startIndex < lines.length; startIndex += DEBUG_CHUNK_SIZE) {\n+ if (generation !== generationRef.current) {\n+ return;\n+ }\n+\n+ const chunkLines = lines.slice(startIndex, startIndex + DEBUG_CHUNK_SIZE);\n+ const chunkCode = chunkLines.map((line) => line.content).join("\\n");\n+ const chunkStartedAt = performance.now();\n+ const chunkTokens = highlighter.tokenize(chunkCode, {\n+ lang: "typescript",\n+ theme: themeName,\n+ });\n+ const chunkMs = performance.now() - chunkStartedAt;\n+\n+ if (firstChunkMs === null) {\n+ firstChunkMs = performance.now() - totalStartedAt;\n+ console.log("[debug-syntax-scratch] first chunk", {\n+ chunkSize: DEBUG_CHUNK_SIZE,\n+ durationMs: Math.round(firstChunkMs),\n+ engine,\n+ lineCount: chunkTokens.length,\n+ });\n+ }\n+\n+ setTokensByChunkIndex((current) => ({\n+ ...current,\n+ [startIndex / DEBUG_CHUNK_SIZE]: chunkTokens,\n+ }));\n+ setStatus(\n+ `Streamed ${Math.min(startIndex + DEBUG_CHUNK_SIZE, lines.length).toLocaleString()} / ${lines.length.toLocaleString()} lines`,\n+ );\n+\n+ console.log("[debug-syntax-scratch] chunk", {\n+ chunkIndex: startIndex / DEBUG_CHUNK_SIZE,\n+ chunkMs: Math.round(chunkMs),\n+ engine,\n+ lineCount: chunkTokens.length,\n+ });\n+\n+ await waitForNextFrame();\n+ }\n+\n+ console.log("[debug-syntax-scratch] complete", {\n+ durationMs: Math.round(performance.now() - totalStartedAt),\n+ engine,\n+ lineCount: lines.length,\n+ });\n+ setStatus(`Complete with ${engine}`);\n+ } catch (error) {\n+ console.error("[debug-syntax-scratch] failed", {\n+ engine,\n+ message: error instanceof Error ? error.message : String(error),\n+ });\n+ setStatus(error instanceof Error ? error.message : "Highlight failed");\n+ }\n+ })();\n+ }, [engine, lines, themeName]);\n+\n+ useEffect(() => {\n+ if (renderStartRef.current === null) {\n+ return;\n+ }\n+\n+ const startedAt = renderStartRef.current;\n+ renderStartRef.current = null;\n+ const commitMs = performance.now() - startedAt;\n+ requestAnimationFrame(() => {\n+ console.log("[debug-syntax-scratch] render", {\n+ commitMs: Math.round(commitMs),\n+ paintMs: Math.round(performance.now() - startedAt),\n+ });\n+ });\n+ });\n+\n+ const renderItem = useCallback(\n+ ({ item }: ListRenderItemInfo) => (\n+ \n+ ),\n+ [tokensByChunkIndex, width],\n+ );\n+\n+ return (\n+ \n+ \n+\n+ \n+ \n+ \n+ \n+ Shiki streaming baseline\n+ \n+ \n+ {status}\n+ \n+ \n+ \n+ \n+ \n+\n+ item.id}\n+ getItemLayout={(_, index) => ({\n+ length: DEBUG_LINE_HEIGHT,\n+ offset: DEBUG_LINE_HEIGHT * index,\n+ index,\n+ })}\n+ initialNumToRender={40}\n+ maxToRenderPerBatch={80}\n+ updateCellsBatchingPeriod={16}\n+ windowSize={9}\n+ removeClippedSubviews\n+ keyboardShouldPersistTaps="handled"\n+ contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}\n+ />\n+ \n+ );\n+}\ndiff --git a/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx\nnew file mode 100644\nindex 000000000..095201929\n--- /dev/null\n+++ b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx\n@@ -0,0 +1,110 @@\n+import { createContext, type ReactNode, useContext, useEffect, useMemo, useState } from "react";\n+\n+import {\n+ getActiveReviewHighlighterEngine,\n+ prepareReviewHighlighter,\n+ prepareReviewHighlighterLanguages,\n+ type ReviewHighlighterEngine,\n+} from "./shikiReviewHighlighter";\n+\n+type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error";\n+\n+interface ReviewHighlighterContextValue {\n+ readonly engine: ReviewHighlighterEngine | null;\n+ readonly error: string | null;\n+ readonly status: ReviewHighlighterStatus;\n+}\n+\n+const ReviewHighlighterContext = createContext({\n+ engine: null,\n+ error: null,\n+ status: "idle",\n+});\n+\n+const REVIEW_INITIAL_LANGUAGES = [\n+ "typescript",\n+ "tsx",\n+ "javascript",\n+ "jsx",\n+ "json",\n+ "yaml",\n+ "bash",\n+] as const;\n+\n+function isReviewHighlighterProviderDebugLoggingEnabled(): boolean {\n+ return typeof __DEV__ !== "undefined" ? __DEV__ : false;\n+}\n+\n+function logReviewHighlighterProviderDiagnostic(\n+ message: string,\n+ details?: Record,\n+): void {\n+ if (!isReviewHighlighterProviderDebugLoggingEnabled()) {\n+ return;\n+ }\n+\n+ if (details) {\n+ console.log(`[review-highlighter-provider] ${message}`, details);\n+ return;\n+ }\n+\n+ console.log(`[review-highlighter-provider] ${message}`);\n+}\n+\n+export function ReviewHighlighterProvider(props: { readonly children: ReactNode }) {\n+ const [value, setValue] = useState({\n+ engine: null,\n+ error: null,\n+ status: "idle",\n+ });\n+\n+ useEffect(() => {\n+ let cancelled = false;\n+\n+ setValue({ engine: null, error: null, status: "initializing" });\n+\n+ void (async () => {\n+ const startedAt = performance.now();\n+ try {\n+ await prepareReviewHighlighter();\n+ await prepareReviewHighlighterLanguages(REVIEW_INITIAL_LANGUAGES);\n+ const engine = await getActiveReviewHighlighterEngine();\n+\n+ if (cancelled) {\n+ return;\n+ }\n+\n+ const durationMs = Math.round(performance.now() - startedAt);\n+ logReviewHighlighterProviderDiagnostic("initialized", {\n+ durationMs,\n+ engine,\n+ });\n+ setValue({ engine, error: null, status: "ready" });\n+ } catch (error) {\n+ if (cancelled) {\n+ return;\n+ }\n+\n+ const message = error instanceof Error ? error.message : String(error);\n+ logReviewHighlighterProviderDiagnostic("initialization failed", { error: message });\n+ setValue({ engine: null, error: message, status: "error" });\n+ }\n+ })();\n+\n+ return () => {\n+ cancelled = true;\n+ };\n+ }, []);\n+\n+ const contextValue = useMemo(() => value, [value]);\n+\n+ return (\n+ \n+ {props.children}\n+ \n+ );\n+}\n+\n+export function useReviewHighlighterStatus(): ReviewHighlighterContextValue {\n+ return useContext(ReviewHighlighterContext);\n+}\ndiff --git a/apps/mobile/src/features/review/reviewPerf.ts b/apps/mobile/src/features/review/reviewPerf.ts\nnew file mode 100644\nindex 000000000..2ae1095b1\n--- /dev/null\n+++ b/apps/mobile/src/features/review/reviewPerf.ts\n@@ -0,0 +1,83 @@\n+interface ReviewPerformanceLike {\n+ readonly now?: () => number;\n+ readonly mark?: (name: string) => void;\n+ readonly measure?: (name: string, startMark: string, endMark: string) => void;\n+ readonly clearMarks?: (name?: string) => void;\n+ readonly clearMeasures?: (name?: string) => void;\n+}\n+\n+const REVIEW_PERF_PREFIX = "t3.review";\n+let reviewPerfSequence = 0;\n+\n+function getPerformance(): ReviewPerformanceLike | null {\n+ const candidate = (globalThis as { readonly performance?: ReviewPerformanceLike }).performance;\n+ return candidate ?? null;\n+}\n+\n+export function isReviewPerfEnabled(): boolean {\n+ return typeof __DEV__ !== "undefined" ? __DEV__ : false;\n+}\n+\n+export function measureReviewWork(name: string, callback: () => T): T {\n+ if (!isReviewPerfEnabled()) {\n+ return callback();\n+ }\n+\n+ const perf = getPerformance();\n+ const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`;\n+ const startMark = `${marker}.start`;\n+ const endMark = `${marker}.end`;\n+ const startedAt = perf?.now?.() ?? Date.now();\n+\n+ perf?.mark?.(startMark);\n+ try {\n+ return callback();\n+ } finally {\n+ const durationMs = (perf?.now?.() ?? Date.now()) - startedAt;\n+ perf?.mark?.(endMark);\n+ perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark);\n+ perf?.clearMarks?.(startMark);\n+ perf?.clearMarks?.(endMark);\n+ console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) });\n+ }\n+}\n+\n+export async function measureReviewAsyncWork(\n+ name: string,\n+ callback: () => Promise,\n+): Promise {\n+ if (!isReviewPerfEnabled()) {\n+ return callback();\n+ }\n+\n+ const perf = getPerformance();\n+ const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`;\n+ const startMark = `${marker}.start`;\n+ const endMark = `${marker}.end`;\n+ const startedAt = perf?.now?.() ?? Date.now();\n+\n+ perf?.mark?.(startMark);\n+ try {\n+ return await callback();\n+ } finally {\n+ const durationMs = (perf?.now?.() ?? Date.now()) - startedAt;\n+ perf?.mark?.(endMark);\n+ perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark);\n+ perf?.clearMarks?.(startMark);\n+ perf?.clearMarks?.(endMark);\n+ console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) });\n+ }\n+}\n+\n+export function markReviewEvent(name: string, details?: Record): void {\n+ if (!isReviewPerfEnabled()) {\n+ return;\n+ }\n+\n+ getPerformance()?.mark?.(`${REVIEW_PERF_PREFIX}.${name}`);\n+ if (details) {\n+ console.log(`[review-perf] ${name}`, details);\n+ return;\n+ }\n+ console.log(`[review-perf] ${name}`);\n+}\n', + }, +]; diff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx index 076a2286dc..9a173224a6 100644 --- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx +++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx @@ -2,15 +2,8 @@ import { useLocalSearchParams, useRouter } from "expo-router"; import { SymbolView } from "expo-symbols"; import { TextInputWrapper } from "expo-paste-input"; import { useEffect, useMemo, useState } from "react"; -import { - KeyboardAvoidingView, - Platform, - Pressable, - ScrollView, - View, - useColorScheme, - useWindowDimensions, -} from "react-native"; +import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native"; +import { KeyboardStickyView } from "react-native-keyboard-controller"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import ImageViewing from "react-native-image-viewing"; @@ -34,6 +27,7 @@ import { import { changeTone, DiffTokenText, + REVIEW_DIFF_LINE_HEIGHT, REVIEW_MONO_FONT_FAMILY, ReviewChangeBar, } from "./reviewDiffRendering"; @@ -44,7 +38,6 @@ import { } from "./shikiReviewHighlighter"; const REVIEW_COMMENT_PREVIEW_MAX_LINES = 5; -const REVIEW_COMMENT_LINE_HEIGHT = 26; export function ReviewCommentComposerSheet() { const router = useRouter(); @@ -84,8 +77,8 @@ export function ReviewCommentComposerSheet() { ? `Lines ${firstNumber}-${lastNumber}` : `${selectedLines.length} lines selected`; const previewHeight = Math.max( - Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_COMMENT_LINE_HEIGHT, - REVIEW_COMMENT_LINE_HEIGHT, + Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_DIFF_LINE_HEIGHT, + REVIEW_DIFF_LINE_HEIGHT, ); const previewViewportWidth = Math.max(width - 40, 280); const handleNativePaste = useNativePaste((uris) => { @@ -143,17 +136,13 @@ export function ReviewCommentComposerSheet() { } return ( - + @@ -219,7 +208,7 @@ export function ReviewCommentComposerSheet() { - - - void handlePickImages()} /> - - { - if (!target || !environmentId || !threadId || commentText.trim().length === 0) { - return; - } - - appendReviewCommentToDraft({ - environmentId, - threadId, - text: formatReviewCommentContext(target, commentText), - attachments, - }); - setAttachments([]); - clearReviewCommentTarget(); - router.dismiss(); - }} - /> - )} + {target ? ( + + + void handlePickImages()} /> + + { + if (!target || !environmentId || !threadId || commentText.trim().length === 0) { + return; + } + + appendReviewCommentToDraft({ + environmentId, + threadId, + text: formatReviewCommentContext(target, commentText), + attachments, + }); + setAttachments([]); + clearReviewCommentTarget(); + router.dismiss(); + }} + /> + + + ) : null} - + ); } diff --git a/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx new file mode 100644 index 0000000000..0952019291 --- /dev/null +++ b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx @@ -0,0 +1,110 @@ +import { createContext, type ReactNode, useContext, useEffect, useMemo, useState } from "react"; + +import { + getActiveReviewHighlighterEngine, + prepareReviewHighlighter, + prepareReviewHighlighterLanguages, + type ReviewHighlighterEngine, +} from "./shikiReviewHighlighter"; + +type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error"; + +interface ReviewHighlighterContextValue { + readonly engine: ReviewHighlighterEngine | null; + readonly error: string | null; + readonly status: ReviewHighlighterStatus; +} + +const ReviewHighlighterContext = createContext({ + engine: null, + error: null, + status: "idle", +}); + +const REVIEW_INITIAL_LANGUAGES = [ + "typescript", + "tsx", + "javascript", + "jsx", + "json", + "yaml", + "bash", +] as const; + +function isReviewHighlighterProviderDebugLoggingEnabled(): boolean { + return typeof __DEV__ !== "undefined" ? __DEV__ : false; +} + +function logReviewHighlighterProviderDiagnostic( + message: string, + details?: Record, +): void { + if (!isReviewHighlighterProviderDebugLoggingEnabled()) { + return; + } + + if (details) { + console.log(`[review-highlighter-provider] ${message}`, details); + return; + } + + console.log(`[review-highlighter-provider] ${message}`); +} + +export function ReviewHighlighterProvider(props: { readonly children: ReactNode }) { + const [value, setValue] = useState({ + engine: null, + error: null, + status: "idle", + }); + + useEffect(() => { + let cancelled = false; + + setValue({ engine: null, error: null, status: "initializing" }); + + void (async () => { + const startedAt = performance.now(); + try { + await prepareReviewHighlighter(); + await prepareReviewHighlighterLanguages(REVIEW_INITIAL_LANGUAGES); + const engine = await getActiveReviewHighlighterEngine(); + + if (cancelled) { + return; + } + + const durationMs = Math.round(performance.now() - startedAt); + logReviewHighlighterProviderDiagnostic("initialized", { + durationMs, + engine, + }); + setValue({ engine, error: null, status: "ready" }); + } catch (error) { + if (cancelled) { + return; + } + + const message = error instanceof Error ? error.message : String(error); + logReviewHighlighterProviderDiagnostic("initialization failed", { error: message }); + setValue({ engine: null, error: message, status: "error" }); + } + })(); + + return () => { + cancelled = true; + }; + }, []); + + const contextValue = useMemo(() => value, [value]); + + return ( + + {props.children} + + ); +} + +export function useReviewHighlighterStatus(): ReviewHighlighterContextValue { + return useContext(ReviewHighlighterContext); +} diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx index 82c28e81e4..e148a8da23 100644 --- a/apps/mobile/src/features/review/ReviewSheet.tsx +++ b/apps/mobile/src/features/review/ReviewSheet.tsx @@ -1,17 +1,31 @@ import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts"; +import { Gesture, GestureDetector } from "react-native-gesture-handler"; +import Animated, { + makeMutable, + type SharedValue, + useAnimatedStyle, + useSharedValue, +} from "react-native-reanimated"; import { useLocalSearchParams, useRouter } from "expo-router"; import Stack from "expo-router/stack"; import { SymbolView } from "expo-symbols"; -import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { + memo, + type ReactElement, + useCallback, + useDeferredValue, + useEffect, + useMemo, + useRef, + useState, +} from "react"; import { ActivityIndicator, FlatList, - InteractionManager, type ListRenderItemInfo, Pressable, ScrollView, Text as NativeText, - type ViewToken, useColorScheme, useWindowDimensions, View, @@ -32,6 +46,7 @@ import { setReviewTurnDiff, updateReviewExpandedFileIds, updateReviewRevealedLargeFileIds, + updateReviewViewedFileIds, useReviewCacheForThread, } from "./reviewState"; import { @@ -45,11 +60,12 @@ import { type ReviewParsedDiff, type ReviewRenderableFile, type ReviewRenderableLineRow, + type ReviewRenderableRow, } from "./reviewModel"; import { clearReviewHighlightFileCache, getCachedHighlightedReviewFile, - highlightReviewFile, + streamHighlightReviewFile, type ReviewDiffTheme, type ReviewHighlightedFile, type ReviewHighlightedToken, @@ -67,9 +83,12 @@ import { import { changeTone, DiffTokenText, + REVIEW_DIFF_LINE_HEIGHT, REVIEW_MONO_FONT_FAMILY, ReviewChangeBar, } from "./reviewDiffRendering"; +import { markReviewEvent, measureReviewWork } from "./reviewPerf"; +import { useReviewHighlighterStatus } from "./ReviewHighlighterProvider"; interface PendingCommentSelection { readonly sectionTitle: string; @@ -87,14 +106,21 @@ interface ReviewLineActionInput { const IOS_NAV_BAR_HEIGHT = 44; const REVIEW_HEADER_SPACING = 0; -const REVIEW_LINE_GUTTER_WIDTH = 62; +const REVIEW_CHANGE_BAR_WIDTH = 5; +const REVIEW_MIN_LINE_NUMBER_WIDTH = 27; +const REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE = 8; +const REVIEW_LINE_NUMBER_HORIZONTAL_PADDING = 6; const REVIEW_CHARACTER_WIDTH_ESTIMATE = 8.4; const REVIEW_MAX_CONTENT_WIDTH = 4_800; -const REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT = 2; -const REVIEW_HIGHLIGHT_BACKTRACK_COUNT = 0; -const REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT = 1; +const REVIEW_HUNK_ROW_HEIGHT = 35; +const REVIEW_FILE_HEADER_HEIGHT = 43; +const REVIEW_SUPPRESSED_ROW_HEIGHT = 92; const loggedMissingReviewTokenKeys = new Set(); +function waitForReviewDelay(durationMs: number): Promise { + return new Promise((resolve) => setTimeout(resolve, durationMs)); +} + function isReviewDiffDebugLoggingEnabled(): boolean { return typeof __DEV__ !== "undefined" ? __DEV__ : false; } @@ -113,33 +139,27 @@ function logReviewDiffDiagnostic(message: string, details?: Record, +function computeReviewFileContentWidth( + rows: ReadonlyArray, viewportWidth: number, + gutterWidth: number, ): number { let maxTextLength = 0; - items.forEach((item) => { - switch (item.kind) { - case "file-header": - maxTextLength = Math.max( - maxTextLength, - item.file.path.length, - item.file.previousPath?.length ?? 0, - ); - break; - case "file-suppressed": - maxTextLength = Math.max(maxTextLength, item.message.length, item.actionLabel?.length ?? 0); - break; - case "hunk": - maxTextLength = Math.max( - maxTextLength, - item.row.header.length + (item.row.context ? item.row.context.length + 1 : 0), - ); - break; - case "line": - maxTextLength = Math.max(maxTextLength, item.row.content.length); - break; + rows.forEach((row) => { + if (row.kind === "hunk") { + maxTextLength = Math.max( + maxTextLength, + row.header.length + (row.context ? row.context.length + 1 : 0), + ); + return; } + + maxTextLength = Math.max(maxTextLength, row.content.length); }); return Math.max( - viewportWidth, + Math.max(0, viewportWidth - gutterWidth), Math.min( REVIEW_MAX_CONTENT_WIDTH, - Math.ceil(REVIEW_LINE_GUTTER_WIDTH + 48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE), + Math.ceil(48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE), ), ); } +function computeReviewFileGutterWidth(rows: ReadonlyArray): number { + let maxLineNumber = 0; + + rows.forEach((row) => { + if (row.kind !== "line") { + return; + } + + maxLineNumber = Math.max(maxLineNumber, row.oldLineNumber ?? 0, row.newLineNumber ?? 0); + }); + + const digitCount = Math.max(1, String(maxLineNumber).length); + const lineNumberWidth = Math.max( + REVIEW_MIN_LINE_NUMBER_WIDTH, + digitCount * REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE + REVIEW_LINE_NUMBER_HORIZONTAL_PADDING, + ); + + return REVIEW_CHANGE_BAR_WIDTH + lineNumberWidth; +} + function getDefaultExpandedFileIds( files: ReadonlyArray, ): ReadonlyArray { return files.map((file) => file.id); } +function getValidReviewExpandedFileIds( + files: ReadonlyArray, + cachedExpandedFileIds: ReadonlyArray | undefined, +): ReadonlyArray { + if (cachedExpandedFileIds === undefined) { + return getDefaultExpandedFileIds(files); + } + + const fileIdSet = new Set(files.map((file) => file.id)); + return cachedExpandedFileIds.filter((id) => fileIdSet.has(id)); +} + function getHighlightedTokensForLine( line: ReviewRenderableLineRow, highlightedFile: ReviewHighlightedFile | null, @@ -252,16 +293,13 @@ const ReviewLineRow = memo(function ReviewLineRow(props: { delayLongPress={220} onLongPress={props.onStartRangeSelection} onPress={props.onComment} - style={{ minWidth: props.viewportWidth }} + style={{ + height: REVIEW_DIFF_LINE_HEIGHT, + width: props.viewportWidth, + overflow: "hidden", + }} > - - - {lineNumber ?? ""} - - + + + + {props.lineNumber ?? ""} + + + ); +}); + +const ReviewHunkGutter = memo(function ReviewHunkGutter(props: { readonly gutterWidth: number }) { + return ( + + ); +}); + const ReviewFileCard = memo(function ReviewFileCard(props: { readonly file: ReviewRenderableFile; readonly fileId: string; readonly expanded: boolean; + readonly viewed: boolean; readonly viewportWidth: number; readonly onToggleFile: (fileId: string) => void; + readonly onToggleViewed: (fileId: string) => void; }) { - const chrome = getFileHeaderChrome(props.file.changeType); + const { expanded, file, fileId, onToggleFile, onToggleViewed, viewed, viewportWidth } = props; + const chrome = getFileHeaderChrome(file.changeType); + const iconColor = String(useThemeColor("--color-icon-muted")); + const handleToggleFile = useCallback(() => { + onToggleFile(fileId); + }, [fileId, onToggleFile]); + const handleToggleViewed = useCallback(() => { + onToggleViewed(fileId); + }, [fileId, onToggleViewed]); return ( - props.onToggleFile(props.fileId)}> - - - - - - - - - - {props.file.path} + + + + + + + + + {file.path} + + {file.previousPath && file.previousPath !== file.path ? ( + + {file.previousPath} - {props.file.previousPath && props.file.previousPath !== props.file.path ? ( - - {props.file.previousPath} - + ) : null} + + + + + -{file.deletions} + + + +{file.additions} + + + + {viewed ? ( + ) : null} - - - - +{props.file.additions} + + Viewed - - -{props.file.deletions} - - + - + ); }); @@ -342,7 +453,11 @@ const ReviewFileSuppressedBody = memo(function ReviewFileSuppressedBody(props: { return ( {props.message} {props.actionLabel && props.onLoadDiffFile ? ( @@ -364,10 +479,13 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: { }) { return ( - + {props.header} {props.context ? ` ${props.context}` : ""} @@ -375,6 +493,61 @@ const ReviewHunkRow = memo(function ReviewHunkRow(props: { ); }); +const ReviewCodePanRow = memo(function ReviewCodePanRow(props: { + readonly contentWidth: number; + readonly horizontalOffset: SharedValue; + readonly gutterWidth?: number; + readonly viewportWidth: number; + readonly leftGutter?: ReactElement; + readonly children: ReactElement; +}) { + const { + children, + contentWidth, + gutterWidth = 0, + horizontalOffset, + leftGutter, + viewportWidth, + } = props; + const dragStartOffset = useSharedValue(0); + const visibleContentWidth = leftGutter ? viewportWidth - gutterWidth : viewportWidth; + const maxOffset = Math.max(0, contentWidth - visibleContentWidth); + + const panGesture = useMemo( + () => + Gesture.Pan() + .activeOffsetX([-8, 8]) + .failOffsetY([-10, 10]) + .onBegin(() => { + dragStartOffset.value = horizontalOffset.value; + }) + .onUpdate((event) => { + "worklet"; + const nextOffset = dragStartOffset.value - event.translationX; + horizontalOffset.value = Math.min(maxOffset, Math.max(0, nextOffset)); + }), + [dragStartOffset, horizontalOffset, maxOffset], + ); + + const contentStyle = useAnimatedStyle( + () => ({ + transform: [{ translateX: -horizontalOffset.value }], + }), + [horizontalOffset], + ); + + return ( + + + {leftGutter ?? null} + + {children} + + + + ); +}); + const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) { return ( @@ -454,15 +627,19 @@ export function ReviewSheet() { const [highlightedFilesById, setHighlightedFilesById] = useState< Record >({}); - const [visibleFileIds, setVisibleFileIds] = useState>([]); + const deferredHighlightedFilesById = useDeferredValue(highlightedFilesById); + const [localExpandedFileIdsBySection, setLocalExpandedFileIdsBySection] = useState< + Record> + >({}); + const [localViewedFileIdsBySection, setLocalViewedFileIdsBySection] = useState< + Record> + >({}); const activeCommentTarget = useReviewCommentTarget(); const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme; - const highlightQueueRef = useRef([]); - const highlightRequestedFileIdsRef = useRef>(new Set()); - const highlightQueueGenerationRef = useRef(0); - const highlightQueueActiveRef = useRef(false); - const highlightableFilesByIdRef = useRef>(new Map()); - const selectedThemeRef = useRef(selectedTheme); + const reviewHighlighter = useReviewHighlighterStatus(); + const highlightRunIdRef = useRef(0); + const highlightableFilesRef = useRef>([]); + const horizontalOffsetByFileIdRef = useRef>>(new Map()); const { selectedThreadCwd } = useSelectedThreadWorktree(); const cwd = selectedThreadCwd; @@ -498,11 +675,13 @@ export function ReviewSheet() { const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT; const parsedDiff = useMemo( () => - getCachedReviewParsedDiff({ - threadKey: reviewCache.threadKey, - sectionId: selectedSection?.id ?? null, - diff: selectedSection?.diff, - }), + measureReviewWork("parse-diff", () => + getCachedReviewParsedDiff({ + threadKey: reviewCache.threadKey, + sectionId: selectedSection?.id ?? null, + diff: selectedSection?.diff, + }), + ), [reviewCache.threadKey, selectedSection?.diff, selectedSection?.id], ); const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]); @@ -510,14 +689,53 @@ export function ReviewSheet() { () => countReviewCommentContexts(draftMessage), [draftMessage], ); + const viewportWidth = Math.max(width, 280); + + useEffect(() => { + if (!selectedSection?.id || parsedDiff.kind !== "files") { + return; + } + + setLocalExpandedFileIdsBySection((current) => { + if (current[selectedSection.id] !== undefined) { + return current; + } + + return { + ...current, + [selectedSection.id]: getValidReviewExpandedFileIds( + parsedDiff.files, + reviewCache.expandedFileIdsBySection[selectedSection.id], + ), + }; + }); + + setLocalViewedFileIdsBySection((current) => { + if (current[selectedSection.id] !== undefined) { + return current; + } + + return { + ...current, + [selectedSection.id]: reviewCache.viewedFileIdsBySection[selectedSection.id] ?? [], + }; + }); + }, [ + parsedDiff, + reviewCache.expandedFileIdsBySection, + reviewCache.viewedFileIdsBySection, + selectedSection?.id, + ]); const expandedFileIds = useMemo( () => selectedSection?.id && parsedDiff.kind === "files" - ? (reviewCache.expandedFileIdsBySection[selectedSection.id] ?? - getDefaultExpandedFileIds(parsedDiff.files)) + ? getValidReviewExpandedFileIds( + parsedDiff.files, + localExpandedFileIdsBySection[selectedSection.id], + ) : [], - [parsedDiff, reviewCache.expandedFileIdsBySection, selectedSection?.id], + [localExpandedFileIdsBySection, parsedDiff, selectedSection?.id], ); const revealedLargeFileIds = useMemo( () => @@ -526,47 +744,96 @@ export function ReviewSheet() { : [], [reviewCache.revealedLargeFileIdsBySection, selectedSection?.id], ); + const viewedFileIds = useMemo( + () => (selectedSection?.id ? (localViewedFileIdsBySection[selectedSection.id] ?? []) : []), + [localViewedFileIdsBySection, selectedSection?.id], + ); + const viewedFileIdSet = useMemo(() => new Set(viewedFileIds), [viewedFileIds]); const reviewListItems = useMemo( () => selectedSection && parsedDiff.kind === "files" - ? buildReviewListItems({ - files: parsedDiff.files, - expandedFileIds, - revealedLargeFileIds, - }) + ? measureReviewWork("build-list-items", () => + buildReviewListItems({ + files: parsedDiff.files, + expandedFileIds, + revealedLargeFileIds, + }), + ) : [], [expandedFileIds, parsedDiff, revealedLargeFileIds, selectedSection], ); - const reviewFileById = useMemo(() => { - if (parsedDiff.kind !== "files") { - return new Map(); - } - - return new Map(parsedDiff.files.map((file) => [file.id, file] as const)); - }, [parsedDiff]); const reviewLineRowsByFileId = useMemo(() => { if (parsedDiff.kind !== "files") { return new Map>(); } - return new Map( - parsedDiff.files.map((file) => [ - file.id, - file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"), - ]), + return measureReviewWork( + "index-line-rows", + () => + new Map( + parsedDiff.files.map((file) => [ + file.id, + file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"), + ]), + ), ); }, [parsedDiff]); - const reviewLineIndexByRowId = useMemo(() => { - const map = new Map(); + const reviewContentWidthByFileId = useMemo(() => { + if (parsedDiff.kind !== "files") { + return new Map(); + } - reviewLineRowsByFileId.forEach((rows) => { - rows.forEach((row, index) => { - map.set(row.id, index); - }); + return measureReviewWork( + "measure-file-widths", + () => + new Map( + parsedDiff.files.map((file) => [ + file.id, + computeReviewFileContentWidth( + file.rows, + viewportWidth, + computeReviewFileGutterWidth(file.rows), + ), + ]), + ), + ); + }, [parsedDiff, viewportWidth]); + const reviewGutterWidthByFileId = useMemo(() => { + if (parsedDiff.kind !== "files") { + return new Map(); + } + + return new Map( + parsedDiff.files.map((file) => [file.id, computeReviewFileGutterWidth(file.rows)]), + ); + }, [parsedDiff]); + const getReviewFileHorizontalOffset = useCallback((fileId: string) => { + let offset = horizontalOffsetByFileIdRef.current.get(fileId); + if (!offset) { + offset = makeMutable(0); + horizontalOffsetByFileIdRef.current.set(fileId, offset); + } + + return offset; + }, []); + useEffect(() => { + const knownFileIds = + parsedDiff.kind === "files" ? new Set(parsedDiff.files.map((file) => file.id)) : new Set(); + + horizontalOffsetByFileIdRef.current.forEach((offset, fileId) => { + if (!knownFileIds.has(fileId)) { + horizontalOffsetByFileIdRef.current.delete(fileId); + return; + } + + const contentWidth = reviewContentWidthByFileId.get(fileId) ?? viewportWidth; + const gutterWidth = reviewGutterWidthByFileId.get(fileId) ?? 0; + offset.value = Math.min( + offset.value, + Math.max(0, contentWidth - (viewportWidth - gutterWidth)), + ); }); - - return map; - }, [reviewLineRowsByFileId]); + }, [parsedDiff, reviewContentWidthByFileId, reviewGutterWidthByFileId, viewportWidth]); const highlightableFiles = useMemo(() => { if (parsedDiff.kind !== "files") { return [] as ReadonlyArray; @@ -587,59 +854,13 @@ export function ReviewSheet() { ); }); }, [expandedFileIds, parsedDiff, revealedLargeFileIds]); - const highlightableFileIds = useMemo( - () => new Set(highlightableFiles.map((file) => file.id)), + const highlightableFilesKey = useMemo( + () => highlightableFiles.map((file) => `${file.id}:${file.cacheKey}`).join("\n"), [highlightableFiles], ); - const priorityHighlightFileIds = useMemo(() => { - if (parsedDiff.kind !== "files" || highlightableFiles.length === 0) { - return [] as ReadonlyArray; - } - - const fileIdsInPriorityOrder = - visibleFileIds.length > 0 - ? visibleFileIds.filter((fileId) => highlightableFileIds.has(fileId)) - : parsedDiff.files - .slice(0, REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT) - .map((file) => file.id) - .filter((fileId) => highlightableFileIds.has(fileId)); - - if (fileIdsInPriorityOrder.length === 0) { - return [] as ReadonlyArray; - } - - const firstVisibleIndex = parsedDiff.files.findIndex( - (file) => file.id === fileIdsInPriorityOrder[0], - ); - const lastVisibleIndex = parsedDiff.files.findIndex( - (file) => file.id === fileIdsInPriorityOrder[fileIdsInPriorityOrder.length - 1], - ); - - if (firstVisibleIndex < 0 || lastVisibleIndex < 0) { - return fileIdsInPriorityOrder; - } - - const startIndex = Math.max(0, firstVisibleIndex - REVIEW_HIGHLIGHT_BACKTRACK_COUNT); - const endIndex = Math.min( - parsedDiff.files.length - 1, - lastVisibleIndex + REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT, - ); - - const queuedIds: string[] = []; - for (let index = startIndex; index <= endIndex; index += 1) { - const fileId = parsedDiff.files[index]?.id; - if (fileId && highlightableFileIds.has(fileId)) { - queuedIds.push(fileId); - } - } - - return queuedIds; - }, [highlightableFileIds, highlightableFiles.length, parsedDiff, visibleFileIds]); - const viewportWidth = Math.max(width, 280); - const reviewListContentWidth = useMemo( - () => computeReviewListContentWidth(reviewListItems, viewportWidth), - [reviewListItems, viewportWidth], - ); + useEffect(() => { + highlightableFilesRef.current = highlightableFiles; + }, [highlightableFiles]); const loadGitDiffs = useCallback(async () => { if (!cwd) { return; @@ -714,100 +935,6 @@ export function ReviewSheet() { void loadGitDiffs(); }, [loadGitDiffs]); - useEffect(() => { - selectedThemeRef.current = selectedTheme; - }, [selectedTheme]); - - useEffect(() => { - highlightableFilesByIdRef.current = new Map(highlightableFiles.map((file) => [file.id, file])); - }, [highlightableFiles]); - - const startHighlightQueueRunner = useCallback(function startHighlightQueueRunner() { - if (highlightQueueActiveRef.current) { - return; - } - - const generation = highlightQueueGenerationRef.current; - highlightQueueActiveRef.current = true; - - void (async () => { - try { - while (generation === highlightQueueGenerationRef.current) { - const nextFileId = highlightQueueRef.current.shift(); - if (!nextFileId) { - break; - } - - const file = highlightableFilesByIdRef.current.get(nextFileId); - if (!file) { - continue; - } - - const theme = selectedThemeRef.current; - const cached = getCachedHighlightedReviewFile(file, theme); - if (cached) { - logReviewDiffDiagnostic("using cached highlighted file", { - fileId: file.id, - filePath: file.path, - theme, - }); - setHighlightedFilesById((current) => - current[file.id] === cached ? current : { ...current, [file.id]: cached }, - ); - continue; - } - - logReviewDiffDiagnostic("requesting highlighted file", { - fileId: file.id, - filePath: file.path, - theme, - }); - - try { - await new Promise((resolve) => { - InteractionManager.runAfterInteractions(() => resolve()); - }); - const result = await highlightReviewFile(file, theme); - if (generation !== highlightQueueGenerationRef.current) { - logReviewDiffDiagnostic("discarding highlighted file after cancellation", { - fileId: file.id, - filePath: file.path, - }); - return; - } - - logReviewDiffDiagnostic("received highlighted file", { - fileId: file.id, - filePath: file.path, - additionLines: result.additionLines.length, - deletionLines: result.deletionLines.length, - }); - setHighlightedFilesById((current) => { - if (current[file.id] === result) { - return current; - } - return { ...current, [file.id]: result }; - }); - } catch (error) { - logReviewDiffDiagnostic("highlight request failed", { - fileId: file.id, - filePath: file.path, - error: error instanceof Error ? error.message : String(error), - }); - } - } - } finally { - highlightQueueActiveRef.current = false; - if ( - generation === highlightQueueGenerationRef.current && - highlightQueueRef.current.length > 0 - ) { - startHighlightQueueRunner(); - } - } - })(); - }, []); - useEffect(() => { if (reviewSections.length === 0) { return; @@ -854,15 +981,15 @@ export function ReviewSheet() { } updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => { - if (existing !== undefined) { - const validIds = existing.filter((id) => parsedDiff.files.some((file) => file.id === id)); - if (validIds.length === existing.length) { - return existing; - } - return validIds; + const validIds = getValidReviewExpandedFileIds(parsedDiff.files, existing); + if ( + existing !== undefined && + validIds.length === existing.length && + validIds.every((id, index) => id === existing[index]) + ) { + return existing; } - - return getDefaultExpandedFileIds(parsedDiff.files); + return validIds; }); }, [parsedDiff, reviewCache.threadKey, selectedSection?.id]); @@ -887,11 +1014,7 @@ export function ReviewSheet() { useEffect(() => { setHighlightedFilesById({}); - setVisibleFileIds([]); - highlightQueueGenerationRef.current += 1; - highlightQueueRef.current = []; - highlightRequestedFileIdsRef.current = new Set(); - highlightQueueActiveRef.current = false; + highlightRunIdRef.current += 1; clearReviewHighlightFileCache(); loggedMissingReviewTokenKeys.clear(); logReviewDiffDiagnostic("reset highlighted files", { @@ -905,15 +1028,23 @@ export function ReviewSheet() { return; } + markReviewEvent("parsed-diff-ready", { + sectionId: selectedSection?.id ?? null, + fileCount: parsedDiff.fileCount, + additions: parsedDiff.additions, + deletions: parsedDiff.deletions, + renderedItems: reviewListItems.length, + }); logReviewDiffDiagnostic("parsed diff files", { selectedSectionId: selectedSection?.id ?? null, fileCount: parsedDiff.fileCount, renderableFileCount: parsedDiff.files.length, }); - }, [parsedDiff, selectedSection?.id]); + }, [parsedDiff, reviewListItems.length, selectedSection?.id]); useEffect(() => { - if (priorityHighlightFileIds.length === 0) { + const files = highlightableFilesRef.current; + if (files.length === 0) { logReviewDiffDiagnostic("no highlightable files", { selectedSectionId: selectedSection?.id ?? null, parsedDiffKind: parsedDiff.kind, @@ -922,33 +1053,98 @@ export function ReviewSheet() { return; } - const queuedFileIds: string[] = []; - priorityHighlightFileIds.forEach((fileId) => { - if (highlightRequestedFileIdsRef.current.has(fileId)) { - return; - } - - const file = highlightableFilesByIdRef.current.get(fileId); - if (!file) { - return; - } - - highlightRequestedFileIdsRef.current.add(fileId); - highlightQueueRef.current.push(fileId); - queuedFileIds.push(fileId); - }); - - if (queuedFileIds.length === 0) { + if (reviewHighlighter.status !== "ready") { + logReviewDiffDiagnostic("waiting for highlighter provider", { + selectedSectionId: selectedSection?.id ?? null, + status: reviewHighlighter.status, + error: reviewHighlighter.error, + }); return; } - logReviewDiffDiagnostic("scheduling file highlights", { + const runId = highlightRunIdRef.current; + let cancelled = false; + + logReviewDiffDiagnostic("streaming file highlights", { selectedSectionId: selectedSection?.id ?? null, - fileCount: queuedFileIds.length, - fileIds: queuedFileIds, + fileCount: files.length, }); - startHighlightQueueRunner(); - }, [parsedDiff.kind, priorityHighlightFileIds, selectedSection?.id, startHighlightQueueRunner]); + + void (async () => { + for (const file of files) { + if (cancelled || runId !== highlightRunIdRef.current) { + return; + } + + const cached = getCachedHighlightedReviewFile(file, selectedTheme); + if (cached) { + setHighlightedFilesById((current) => + current[file.id] === cached ? current : { ...current, [file.id]: cached }, + ); + continue; + } + + logReviewDiffDiagnostic("requesting highlighted file", { + fileId: file.id, + filePath: file.path, + theme: selectedTheme, + }); + + try { + const highlightStartedAt = performance.now(); + const result = await streamHighlightReviewFile(file, selectedTheme, (progress) => { + if (cancelled || runId !== highlightRunIdRef.current) { + return; + } + + if (!progress.complete) { + return; + } + + logReviewDiffDiagnostic("received streamed highlighted file", { + fileId: file.id, + filePath: file.path, + highlightedLineCount: progress.highlightedLineCount, + durationMs: Math.round(performance.now() - highlightStartedAt), + }); + }); + + if (cancelled || runId !== highlightRunIdRef.current) { + return; + } + + logReviewDiffDiagnostic("received highlighted file", { + fileId: file.id, + filePath: file.path, + additionLines: result.additionLines.length, + deletionLines: result.deletionLines.length, + }); + setHighlightedFilesById((current) => + current[file.id] === result ? current : { ...current, [file.id]: result }, + ); + } catch (error) { + logReviewDiffDiagnostic("highlight request failed", { + fileId: file.id, + filePath: file.path, + error: error instanceof Error ? error.message : String(error), + }); + } + + await waitForReviewDelay(0); + } + })(); + + return () => { + cancelled = true; + }; + }, [ + highlightableFilesKey, + parsedDiff.kind, + reviewHighlighter.error, + reviewHighlighter.status, + selectedSection?.id, + selectedTheme, + ]); const refreshSelectedSection = useCallback(async () => { if (!selectedSection) { @@ -968,20 +1164,68 @@ export function ReviewSheet() { const handleToggleExpandedFile = useCallback( (fileId: string) => { - if (!reviewCache.threadKey || !selectedSection?.id || parsedDiff.kind !== "files") { + if (!selectedSection?.id || parsedDiff.kind !== "files") { return; } - updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => { - const currentIds = existing ?? getDefaultExpandedFileIds(parsedDiff.files); - return currentIds.includes(fileId) + const sectionId = selectedSection.id; + + setLocalExpandedFileIdsBySection((current) => { + const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, current[sectionId]); + const nextIds = currentIds.includes(fileId) ? currentIds.filter((id) => id !== fileId) : [...currentIds, fileId]; + + return { + ...current, + [sectionId]: nextIds, + }; }); + + if (reviewCache.threadKey) { + updateReviewExpandedFileIds(reviewCache.threadKey, sectionId, (existing) => { + const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, existing); + return currentIds.includes(fileId) + ? currentIds.filter((id) => id !== fileId) + : [...currentIds, fileId]; + }); + } }, [parsedDiff, reviewCache.threadKey, selectedSection?.id], ); + const handleToggleViewedFile = useCallback( + (fileId: string) => { + if (!selectedSection?.id) { + return; + } + + const sectionId = selectedSection.id; + + setLocalViewedFileIdsBySection((current) => { + const currentIds = current[sectionId] ?? []; + const nextIds = currentIds.includes(fileId) + ? currentIds.filter((id) => id !== fileId) + : [...currentIds, fileId]; + + return { + ...current, + [sectionId]: nextIds, + }; + }); + + if (reviewCache.threadKey) { + updateReviewViewedFileIds(reviewCache.threadKey, sectionId, (existing) => { + const currentIds = existing ?? []; + return currentIds.includes(fileId) + ? currentIds.filter((id) => id !== fileId) + : [...currentIds, fileId]; + }); + } + }, + [reviewCache.threadKey, selectedSection?.id], + ); + const handleRevealLargeDiff = useCallback( (fileId: string) => { if (!reviewCache.threadKey || !selectedSection?.id) { @@ -1080,35 +1324,6 @@ export function ReviewSheet() { return <>{children}; }, [error, parsedDiffNotice]); - const stickyHeaderIndices = useMemo(() => { - const itemOffset = listHeader ? 1 : 0; - - return reviewListItems.flatMap((item, index) => - item.kind === "file-header" ? [index + itemOffset] : [], - ); - }, [listHeader, reviewListItems]); - - const viewabilityConfigRef = useRef({ - itemVisiblePercentThreshold: 10, - }); - const onViewableItemsChangedRef = useRef( - ({ - viewableItems, - }: { - readonly viewableItems: Array>; - readonly changed: Array>; - }) => { - const nextVisibleFileIds = Array.from( - new Set( - viewableItems - .filter((token) => token.isViewable && token.item !== undefined) - .map((token) => token.item.fileId), - ), - ); - - setVisibleFileIds(nextVisibleFileIds); - }, - ); const renderReviewListItem = useCallback( ({ item }: ListRenderItemInfo) => { @@ -1116,112 +1331,142 @@ export function ReviewSheet() { return null; } + let renderedItem: ReactElement | null = null; switch (item.kind) { case "file-header": - return ( + renderedItem = ( ); + break; case "file-suppressed": - return ( + renderedItem = ( ); - case "hunk": - return ( - + break; + case "hunk": { + const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth; + const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0; + + renderedItem = ( + } + viewportWidth={viewportWidth} + > + + ); + break; + } case "line": { - const file = reviewFileById.get(item.fileId); - if (!file) { - return null; - } - - const fileLineRows = reviewLineRowsByFileId.get(file.id) ?? []; - const lineIndex = reviewLineIndexByRowId.get(item.row.id); - if (lineIndex === undefined) { - return null; - } - + const fileLineRows = reviewLineRowsByFileId.get(item.file.id) ?? []; const pendingSelectionForFile = pendingCommentSelection && pendingCommentSelection.sectionTitle === selectedSection.title && - pendingCommentSelection.filePath === file.path + pendingCommentSelection.filePath === item.file.path ? pendingCommentSelection : null; const selectedTargetForFile = activeCommentTarget && activeCommentTarget.sectionTitle === selectedSection.title && - activeCommentTarget.filePath === file.path + activeCommentTarget.filePath === item.file.path ? activeCommentTarget : null; const highlightedFile = - highlightedFilesById[file.id] ?? - getCachedHighlightedReviewFile(file, selectedTheme) ?? + deferredHighlightedFilesById[item.file.id] ?? + getCachedHighlightedReviewFile(item.file, selectedTheme) ?? null; + const contentWidth = reviewContentWidthByFileId.get(item.fileId) ?? viewportWidth; + const gutterWidth = reviewGutterWidthByFileId.get(item.fileId) ?? 0; if (highlightedFile === null) { - const missingTokenKey = `${selectedSection.id}:${file.id}`; + const missingTokenKey = `${selectedSection.id}:${item.file.id}`; if (!loggedMissingReviewTokenKeys.has(missingTokenKey)) { loggedMissingReviewTokenKeys.add(missingTokenKey); logReviewDiffDiagnostic("rendering file without tokens", { sectionId: selectedSection.id, - fileId: file.id, - filePath: file.path, - highlightedFileKnownInState: highlightedFilesById[file.id] !== undefined, + fileId: item.file.id, + filePath: item.file.path, + highlightedFileKnownInState: + deferredHighlightedFilesById[item.file.id] !== undefined, }); } } const selectionState = - pendingSelectionForFile?.anchorIndex === lineIndex + pendingSelectionForFile?.anchorIndex === item.lineIndex ? ("anchor" as const) : selectedTargetForFile && - lineIndex >= selectedTargetForFile.startIndex && - lineIndex <= selectedTargetForFile.endIndex + item.lineIndex >= selectedTargetForFile.startIndex && + item.lineIndex <= selectedTargetForFile.endIndex ? ("selected" as const) : null; - return ( - - handlePressLine({ - sectionTitle: selectedSection.title, - filePath: file.path, - lines: fileLineRows, - lineIndex, - }) + renderedItem = ( + } - onStartRangeSelection={() => - handleStartRangeSelection({ - sectionTitle: selectedSection.title, - filePath: file.path, - lines: fileLineRows, - lineIndex, - }) - } - /> + viewportWidth={viewportWidth} + > + + handlePressLine({ + sectionTitle: selectedSection.title, + filePath: item.file.path, + lines: fileLineRows, + lineIndex: item.lineIndex, + }) + } + onStartRangeSelection={() => + handleStartRangeSelection({ + sectionTitle: selectedSection.title, + filePath: item.file.path, + lines: fileLineRows, + lineIndex: item.lineIndex, + }) + } + /> + ); + break; } } + + return renderedItem; }, [ activeCommentTarget, @@ -1229,14 +1474,17 @@ export function ReviewSheet() { handleRevealLargeDiff, handleStartRangeSelection, handleToggleExpandedFile, - highlightedFilesById, + handleToggleViewedFile, + getReviewFileHorizontalOffset, + deferredHighlightedFilesById, pendingCommentSelection, - reviewFileById, - reviewLineIndexByRowId, + reviewContentWidthByFileId, + reviewGutterWidthByFileId, reviewLineRowsByFileId, - reviewListContentWidth, selectedSection, selectedTheme, + viewedFileIdSet, + viewportWidth, ], ); @@ -1374,27 +1622,20 @@ export function ReviewSheet() { {selectedSection && parsedDiff.kind === "files" ? ( item.id} + initialNumToRender={20} + maxToRenderPerBatch={20} + updateCellsBatchingPeriod={16} + windowSize={5} + removeClippedSubviews={false} keyboardShouldPersistTaps="handled" ListHeaderComponent={listHeader} - stickyHeaderIndices={stickyHeaderIndices} - removeClippedSubviews={false} - initialNumToRender={24} - maxToRenderPerBatch={16} - updateCellsBatchingPeriod={16} - windowSize={10} - scrollEventThrottle={16} - onViewableItemsChanged={onViewableItemsChangedRef.current} - viewabilityConfig={viewabilityConfigRef.current} contentContainerStyle={{ - paddingTop: REVIEW_HEADER_SPACING, + paddingTop: topContentInset + REVIEW_HEADER_SPACING, paddingBottom: Math.max(insets.bottom, 18) + 18, }} /> diff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx index d61924a621..3f2ae01609 100644 --- a/apps/mobile/src/features/review/reviewDiffRendering.tsx +++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx @@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({ default: "monospace", }); +export const REVIEW_DIFF_LINE_HEIGHT = 26; +const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2; + export function renderVisibleWhitespace(value: string): string { const expandedTabs = value.replace(/\t/g, " "); return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\u00A0")); @@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string | export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) { if (props.change === "delete") { return ( - - - {Array.from({ length: 6 }, (_, index) => ( - + + + {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => ( + + + + ))} @@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo } return ( - + ); @@ -63,6 +69,7 @@ export function DiffTokenText(props: { if (!props.tokens || props.tokens.length === 0) { return ( { - it("defaults invalid values to javascript", () => { - expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("javascript"); - expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("javascript"); + it("defaults invalid values to native", () => { + expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("native"); + expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("native"); }); it("accepts supported values", () => { diff --git a/apps/mobile/src/features/review/reviewHighlighterEngine.ts b/apps/mobile/src/features/review/reviewHighlighterEngine.ts index 5ef9f055a6..4287685376 100644 --- a/apps/mobile/src/features/review/reviewHighlighterEngine.ts +++ b/apps/mobile/src/features/review/reviewHighlighterEngine.ts @@ -11,7 +11,7 @@ export function resolveReviewHighlighterEnginePreference( case "native": return "native"; default: - return "javascript"; + return "native"; } } diff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts index a24a99ceb4..69a6e72618 100644 --- a/apps/mobile/src/features/review/reviewModel.test.ts +++ b/apps/mobile/src/features/review/reviewModel.test.ts @@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => { }); }); - it("flattens expanded files into virtualizable review items", () => { + it("flattens expanded file rows into virtualized review items", () => { const file = makeRenderableFile({ path: "apps/mobile/src/a.ts", rows: [ @@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => { expect(items).toEqual([ expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }), - expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }), - expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }), + expect.objectContaining({ + kind: "hunk", + fileId: file.id, + file, + row: file.rows[0], + }), + expect.objectContaining({ + kind: "line", + fileId: file.id, + file, + row: file.rows[1], + lineIndex: 0, + }), ]); }); diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts index 27e6d7ae40..1cfbf358cc 100644 --- a/apps/mobile/src/features/review/reviewModel.ts +++ b/apps/mobile/src/features/review/reviewModel.ts @@ -72,6 +72,7 @@ export interface ReviewHunkListItem { readonly kind: "hunk"; readonly id: string; readonly fileId: string; + readonly file: ReviewRenderableFile; readonly row: ReviewRenderableHunkRow; } @@ -79,7 +80,9 @@ export interface ReviewLineListItem { readonly kind: "line"; readonly id: string; readonly fileId: string; + readonly file: ReviewRenderableFile; readonly row: ReviewRenderableLineRow; + readonly lineIndex: number; } export type ReviewListItem = @@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil } // The flattened review list item model is inspired by pierre/diffs' iterator-first -// virtualization architecture, adapted here for React Native and LegendList. +// virtualization architecture, adapted here for React Native virtualization. // Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs // Reference files: // - src/utils/iterateOverDiff.ts @@ -350,12 +353,14 @@ export function buildReviewListItems(input: { } } - file.rows.forEach((row) => { + let lineIndex = 0; + file.rows.forEach((row, rowIndex) => { if (row.kind === "hunk") { items.push({ kind: "hunk", - id: row.id, + id: `${file.id}:row:${rowIndex}:${row.id}`, fileId: file.id, + file, row, }); return; @@ -363,10 +368,13 @@ export function buildReviewListItems(input: { items.push({ kind: "line", - id: row.id, + id: `${file.id}:row:${rowIndex}:${row.id}`, fileId: file.id, + file, row, + lineIndex, }); + lineIndex += 1; }); }); diff --git a/apps/mobile/src/features/review/reviewPerf.ts b/apps/mobile/src/features/review/reviewPerf.ts new file mode 100644 index 0000000000..2ae1095b1c --- /dev/null +++ b/apps/mobile/src/features/review/reviewPerf.ts @@ -0,0 +1,83 @@ +interface ReviewPerformanceLike { + readonly now?: () => number; + readonly mark?: (name: string) => void; + readonly measure?: (name: string, startMark: string, endMark: string) => void; + readonly clearMarks?: (name?: string) => void; + readonly clearMeasures?: (name?: string) => void; +} + +const REVIEW_PERF_PREFIX = "t3.review"; +let reviewPerfSequence = 0; + +function getPerformance(): ReviewPerformanceLike | null { + const candidate = (globalThis as { readonly performance?: ReviewPerformanceLike }).performance; + return candidate ?? null; +} + +export function isReviewPerfEnabled(): boolean { + return typeof __DEV__ !== "undefined" ? __DEV__ : false; +} + +export function measureReviewWork(name: string, callback: () => T): T { + if (!isReviewPerfEnabled()) { + return callback(); + } + + const perf = getPerformance(); + const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`; + const startMark = `${marker}.start`; + const endMark = `${marker}.end`; + const startedAt = perf?.now?.() ?? Date.now(); + + perf?.mark?.(startMark); + try { + return callback(); + } finally { + const durationMs = (perf?.now?.() ?? Date.now()) - startedAt; + perf?.mark?.(endMark); + perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark); + perf?.clearMarks?.(startMark); + perf?.clearMarks?.(endMark); + console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) }); + } +} + +export async function measureReviewAsyncWork( + name: string, + callback: () => Promise, +): Promise { + if (!isReviewPerfEnabled()) { + return callback(); + } + + const perf = getPerformance(); + const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`; + const startMark = `${marker}.start`; + const endMark = `${marker}.end`; + const startedAt = perf?.now?.() ?? Date.now(); + + perf?.mark?.(startMark); + try { + return await callback(); + } finally { + const durationMs = (perf?.now?.() ?? Date.now()) - startedAt; + perf?.mark?.(endMark); + perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark); + perf?.clearMarks?.(startMark); + perf?.clearMarks?.(endMark); + console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) }); + } +} + +export function markReviewEvent(name: string, details?: Record): void { + if (!isReviewPerfEnabled()) { + return; + } + + getPerformance()?.mark?.(`${REVIEW_PERF_PREFIX}.${name}`); + if (details) { + console.log(`[review-perf] ${name}`, details); + return; + } + console.log(`[review-perf] ${name}`); +} diff --git a/apps/mobile/src/features/review/reviewState.ts b/apps/mobile/src/features/review/reviewState.ts index 06134db7d5..c116f93fed 100644 --- a/apps/mobile/src/features/review/reviewState.ts +++ b/apps/mobile/src/features/review/reviewState.ts @@ -64,6 +64,13 @@ const reviewRevealedLargeFileIdsByThreadKeyAtom = Atom.family((threadKey: string ), ); +const reviewViewedFileIdsByThreadKeyAtom = Atom.family((threadKey: string) => + Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe( + Atom.keepAlive, + Atom.withLabel(`mobile:review:viewed-file-ids:${threadKey}`), + ), +); + const reviewParsedDiffBySectionCacheKeyAtom = Atom.family((cacheKey: string) => Atom.make<{ readonly diff: string | null; readonly parsed: ReviewParsedDiff } | null>(null).pipe( Atom.keepAlive, @@ -110,6 +117,9 @@ export function useReviewCacheForThread(input: { ? reviewRevealedLargeFileIdsByThreadKeyAtom(threadKey) : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM, ); + const viewedFileIdsBySection = useAtomValue( + threadKey ? reviewViewedFileIdsByThreadKeyAtom(threadKey) : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM, + ); return { threadKey, @@ -118,6 +128,7 @@ export function useReviewCacheForThread(input: { selectedSectionId, expandedFileIdsBySection, revealedLargeFileIdsBySection, + viewedFileIdsBySection, }; } @@ -169,6 +180,20 @@ export function updateReviewRevealedLargeFileIds( }); } +export function updateReviewViewedFileIds( + threadKey: string, + sectionId: string, + update: (current: ReadonlyArray | undefined) => ReadonlyArray | undefined, +): void { + const atom = reviewViewedFileIdsByThreadKeyAtom(threadKey); + const current = appAtomRegistry.get(atom); + const nextValue = update(current[sectionId]); + appAtomRegistry.set(atom, { + ...current, + [sectionId]: nextValue, + }); +} + export function getCachedReviewParsedDiff(input: { readonly threadKey: string | null; readonly sectionId: string | null; diff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts index 05b5c9213c..402d00668d 100644 --- a/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts +++ b/apps/mobile/src/features/review/shikiReviewHighlighter.test.ts @@ -24,7 +24,7 @@ function makeRenderableFile( describe("highlightReviewFile", () => { it("preserves one highlighted token row per diff line even without trailing newlines", async () => { const file = makeRenderableFile({ - path: "apps/mobile/src/example.test.ts", + path: "apps/mobile/src/example.txt", additionLines: [ 'const items = ["a"];', 'expect(items).toEqual(["a"]);', @@ -36,15 +36,23 @@ describe("highlightReviewFile", () => { const highlighted = await highlightReviewFile(file, "light"); expect(highlighted.additionLines).toHaveLength(file.additionLines.length); - expect(highlighted.additionLines[0]?.some((token) => token.content === "const")).toBe(true); - expect(highlighted.additionLines[1]?.some((token) => token.content === "expect")).toBe(true); - expect(highlighted.additionLines[2]?.some((token) => token.content === "const")).toBe(true); - expect(highlighted.additionLines[3]?.some((token) => token.content === "expect")).toBe(true); + expect(highlighted.additionLines[0]?.map((token) => token.content).join("")).toBe( + file.additionLines[0], + ); + expect(highlighted.additionLines[1]?.map((token) => token.content).join("")).toBe( + file.additionLines[1], + ); + expect(highlighted.additionLines[2]?.map((token) => token.content).join("")).toBe( + file.additionLines[2], + ); + expect(highlighted.additionLines[3]?.map((token) => token.content).join("")).toBe( + file.additionLines[3], + ); }); it("adds word-alt diff emphasis for paired deletion and addition lines", async () => { const file = makeRenderableFile({ - path: "apps/mobile/src/example-inline-diff.test.ts", + path: "apps/mobile/src/example-inline-diff.txt", additionLines: ["const after = 2;"], deletionLines: ["const before = 1;"], rows: [ @@ -82,7 +90,7 @@ describe("highlightReviewFile", () => { it("falls back to plain tokens for very long lines", async () => { const longLine = `const value = "${"a".repeat(1_100)}";`; const file = makeRenderableFile({ - path: "apps/mobile/src/example-long-line.ts", + path: "apps/mobile/src/example-long-line.txt", additionLines: [longLine], rows: [ { diff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.ts index f7a5c4125f..eb6bf6973c 100644 --- a/apps/mobile/src/features/review/shikiReviewHighlighter.ts +++ b/apps/mobile/src/features/review/shikiReviewHighlighter.ts @@ -1,5 +1,14 @@ import { createHighlighterCore, type HighlighterCore } from "@shikijs/core"; import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript"; +import bashLanguage from "@shikijs/langs/bash"; +import javascriptLanguage from "@shikijs/langs/javascript"; +import jsonLanguage from "@shikijs/langs/json"; +import jsxLanguage from "@shikijs/langs/jsx"; +import tsxLanguage from "@shikijs/langs/tsx"; +import typescriptLanguage from "@shikijs/langs/typescript"; +import yamlLanguage from "@shikijs/langs/yaml"; +import githubDarkDefault from "@shikijs/themes/github-dark-default"; +import githubLightDefault from "@shikijs/themes/github-light-default"; import { getFiletypeFromFileName } from "@pierre/diffs/utils"; import { @@ -11,6 +20,7 @@ import type { ReviewRenderableFile, ReviewRenderableLineRow } from "./reviewMode import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs"; export type ReviewDiffTheme = "light" | "dark"; +export type { ReviewHighlighterEngine }; export interface ReviewHighlightedToken { content: string; @@ -24,12 +34,19 @@ export interface ReviewHighlightedFile { readonly deletionLines: ReadonlyArray>; } +export interface ReviewHighlightFileProgress { + readonly highlightedFile: ReviewHighlightedFile; + readonly complete: boolean; + readonly highlightedLineCount: number; +} + const SHIKI_THEME_NAME_BY_SCHEME = { light: "github-light-default", dark: "github-dark-default", } as const; const REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE = - process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? "javascript"; + process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? + (process.env.NODE_ENV === "test" ? "javascript" : "native"); const REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE = resolveReviewHighlighterEnginePreference( REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE, ); @@ -38,12 +55,30 @@ const REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE = resolveReviewHighlighterBooleanF false, ); const REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT = 8; -const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 40; -const REVIEW_HIGHLIGHT_CHUNK_SIZE = 20; +const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 8; +const REVIEW_HIGHLIGHT_CHUNK_SIZE = 200; const REVIEW_TOKENIZE_MAX_LINE_LENGTH = 1_000; const highlightCache = new Map>(); const resolvedHighlightCache = new Map(); -const loadedLanguages = new Set(["text"]); +const REVIEW_INITIAL_LANGUAGE_MODULES = [ + bashLanguage, + javascriptLanguage, + jsonLanguage, + jsxLanguage, + tsxLanguage, + typescriptLanguage, + yamlLanguage, +] satisfies Parameters[0]["langs"]; +const loadedLanguages = new Set([ + "text", + "bash", + "javascript", + "json", + "jsx", + "tsx", + "typescript", + "yaml", +]); const languageLoadingPromises = new Map>(); const languageImports: Partial Promise>> = { javascript: () => import("@shikijs/langs/javascript"), @@ -215,21 +250,13 @@ function joinPatchLines(lines: ReadonlyArray): string { function waitForNextFrame(): Promise { return new Promise((resolve) => { - if (typeof requestAnimationFrame === "function") { - requestAnimationFrame(() => resolve()); - return; - } - setTimeout(resolve, 0); }); } async function getHighlighter(): Promise { if (!highlighterPromise) { - const configuredHighlighterPromise = Promise.all([ - import("@shikijs/themes/github-light-default"), - import("@shikijs/themes/github-dark-default"), - ]).then(async ([lightThemeModule, darkThemeModule]) => { + const configuredHighlighterPromise = (async () => { let nativeEngineAvailable = false; logReviewHighlighterDiagnostic("initializing", { @@ -238,12 +265,11 @@ async function getHighlighter(): Promise { resultCacheDisabled: REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE, }); - const themes = [lightThemeModule.default, darkThemeModule.default]; + const themes = [githubLightDefault, githubDarkDefault]; if (REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE !== "javascript") { try { const nativeEngineModule = await import("react-native-shiki-engine"); - logReviewHighlighterDiagnostic("imported react-native-shiki-engine"); nativeEngineAvailable = nativeEngineModule.isNativeEngineAvailable(); logReviewHighlighterDiagnostic("checked native engine availability", { nativeEngineAvailable, @@ -253,7 +279,7 @@ async function getHighlighter(): Promise { logReviewHighlighterDiagnostic("creating native regex engine"); const highlighter = await createHighlighterCore({ themes, - langs: [], + langs: REVIEW_INITIAL_LANGUAGE_MODULES, engine: nativeEngineModule.createNativeEngine(), }); logReviewHighlighterDiagnostic("using native engine"); @@ -281,7 +307,7 @@ async function getHighlighter(): Promise { ); const highlighter = await createHighlighterCore({ themes, - langs: [], + langs: REVIEW_INITIAL_LANGUAGE_MODULES, engine: createJavaScriptRegexEngine(), }); logReviewHighlighterDiagnostic("using javascript engine", { @@ -291,7 +317,7 @@ async function getHighlighter(): Promise { highlighter, engine, }; - }); + })(); highlighterPromise = configuredHighlighterPromise .then((result) => result.highlighter) @@ -316,11 +342,52 @@ export async function getActiveReviewHighlighterEngine(): Promise { + await getHighlighter(); +} + +export async function prepareReviewHighlighterLanguages( + languages: ReadonlyArray, +): Promise { + const highlighter = await getHighlighter(); + await Promise.all( + languages.map(async (language) => { + const candidate = resolveLanguageAlias(language); + if (candidate === "text" || !(candidate in languageImports)) { + return; + } + + await loadSingleLanguage(highlighter, candidate); + }), + ); +} + function resolveLanguageAlias(language: string): string { const normalized = language.toLowerCase(); return languageAliases[normalized] ?? normalized; } +function resolveLoadedLanguageFromPath( + path: string, + languageHint: string | null = null, +): string | null { + const detectedLanguage = languageHint ?? getFiletypeFromFileName(path); + if (!detectedLanguage) { + return "text"; + } + + const candidate = resolveLanguageAlias(detectedLanguage); + if (candidate === "text" || candidate === "ansi") { + return "text"; + } + + if (!(candidate in languageImports)) { + return "text"; + } + + return loadedLanguages.has(candidate) ? candidate : null; +} + async function loadSingleLanguage( highlighter: HighlighterCore, language: string, @@ -360,6 +427,11 @@ async function resolveLanguageFromPath( path: string, languageHint: string | null = null, ): Promise { + const loadedLanguage = resolveLoadedLanguageFromPath(path, languageHint); + if (loadedLanguage) { + return loadedLanguage; + } + const detectedLanguage = languageHint ?? getFiletypeFromFileName(path); if (!detectedLanguage) { return "text"; @@ -374,8 +446,12 @@ async function resolveLanguageFromPath( return "text"; } + if (loadedLanguages.has(candidate)) { + return candidate; + } + const highlighter = await getHighlighter(); - const loaded = await loadSingleLanguage(highlighter, resolveLanguageAlias(candidate)); + const loaded = await loadSingleLanguage(highlighter, candidate); if (!loaded) { return "text"; } @@ -384,7 +460,10 @@ async function resolveLanguageFromPath( } async function resolveLanguage(file: ReviewRenderableFile): Promise { - return resolveLanguageFromPath(file.path, file.languageHint); + return ( + resolveLoadedLanguageFromPath(file.path, file.languageHint) ?? + (await resolveLanguageFromPath(file.path, file.languageHint)) + ); } function normalizeHighlightedLines( @@ -399,6 +478,18 @@ function normalizeHighlightedLines( ); } +function makePlainHighlightedLines( + lines: ReadonlyArray, +): ReadonlyArray> { + return lines.map((line) => [ + { + content: stripTrailingNewline(line), + color: null, + fontStyle: null, + }, + ]); +} + function applyWordAltDiffHighlightsToFile( file: ReviewRenderableFile, highlighted: ReviewHighlightedFile, @@ -594,6 +685,67 @@ async function highlightLines( return highlightedLines; } +async function highlightPatchLinesInChunks(input: { + readonly lines: ReadonlyArray; + readonly language: string; + readonly theme: string; + readonly onChunk: ( + startIndex: number, + tokens: ReadonlyArray>, + ) => void; +}): Promise>> { + if (input.lines.length === 0) { + return []; + } + + const highlighter = await getHighlighter(); + const highlightedLines: Array> = []; + + for ( + let startIndex = 0; + startIndex < input.lines.length; + startIndex += REVIEW_HIGHLIGHT_CHUNK_SIZE + ) { + const lineChunk = input.lines.slice(startIndex, startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE); + const chunkTokens: Array> = []; + const tokenizableLines: string[] = []; + const tokenizableIndexes: number[] = []; + + lineChunk.forEach((line, index) => { + const strippedLine = stripTrailingNewline(line); + if (strippedLine.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH) { + chunkTokens[index] = [{ content: strippedLine, color: null, fontStyle: null }]; + return; + } + + tokenizableIndexes.push(index); + tokenizableLines.push(strippedLine); + }); + + if (tokenizableLines.length > 0) { + const tokenLines = highlighter.codeToTokensBase(tokenizableLines.join("\n"), { + lang: input.language, + theme: input.theme, + }); + const normalizedTokenLines = normalizeHighlightedLines(tokenLines); + + tokenizableIndexes.forEach((chunkIndex, tokenIndex) => { + chunkTokens[chunkIndex] = normalizedTokenLines[tokenIndex] ?? []; + }); + } + + const completedChunk = lineChunk.map((_, index) => chunkTokens[index] ?? []); + highlightedLines.push(...completedChunk); + input.onChunk(startIndex, completedChunk); + + if (startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE < input.lines.length) { + await waitForNextFrame(); + } + } + + return highlightedLines; +} + function getHighlightCacheKey(file: ReviewRenderableFile, theme: ReviewDiffTheme): string { return `${SHIKI_THEME_NAME_BY_SCHEME[theme]}:${file.cacheKey}`; } @@ -667,7 +819,28 @@ export async function highlightReviewFile( deletionLineCount: file.deletionLines.length, rowCount: file.rows.length, }); - const language = await resolveLanguage(file); + const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint); + const language = loadedLanguage ?? (await resolveLanguage(file)); + if (language === "text") { + const highlighted = applyWordAltDiffHighlightsToFile(file, { + additionLines: makePlainHighlightedLines(file.additionLines), + deletionLines: makePlainHighlightedLines(file.deletionLines), + }); + if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { + storeResolvedHighlightedFile(cacheKey, highlighted); + } + logReviewHighlighterDiagnostic("file highlight complete", { + fileId: file.id, + filePath: file.path, + theme, + language, + highlightedAdditionLineCount: highlighted.additionLines.length, + highlightedDeletionLineCount: highlighted.deletionLines.length, + durationMs: Date.now() - startedAt, + }); + return highlighted; + } + const additionLines = await highlightLines( joinPatchLines(file.additionLines), language, @@ -707,6 +880,113 @@ export async function highlightReviewFile( }); } +export async function streamHighlightReviewFile( + file: ReviewRenderableFile, + theme: ReviewDiffTheme, + onProgress: (progress: ReviewHighlightFileProgress) => void, +): Promise { + const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[theme]; + const cacheKey = getHighlightCacheKey(file, theme); + if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { + const resolved = resolvedHighlightCache.get(cacheKey); + if (resolved) { + onProgress({ + highlightedFile: resolved, + complete: true, + highlightedLineCount: resolved.additionLines.length + resolved.deletionLines.length, + }); + return resolved; + } + } + + const startedAt = Date.now(); + logReviewHighlighterDiagnostic("file stream highlight start", { + fileId: file.id, + filePath: file.path, + theme, + additionLineCount: file.additionLines.length, + deletionLineCount: file.deletionLines.length, + rowCount: file.rows.length, + }); + + const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint); + const language = loadedLanguage ?? (await resolveLanguage(file)); + if (language === "text") { + const highlighted = applyWordAltDiffHighlightsToFile(file, { + additionLines: makePlainHighlightedLines(file.additionLines), + deletionLines: makePlainHighlightedLines(file.deletionLines), + }); + if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { + storeResolvedHighlightedFile(cacheKey, highlighted); + } + onProgress({ + highlightedFile: highlighted, + complete: true, + highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length, + }); + logReviewHighlighterDiagnostic("file stream highlight complete", { + fileId: file.id, + filePath: file.path, + theme, + language, + highlightedAdditionLineCount: highlighted.additionLines.length, + highlightedDeletionLineCount: highlighted.deletionLines.length, + highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length, + durationMs: Date.now() - startedAt, + }); + return highlighted; + } + + const additionLines: Array> = []; + const deletionLines: Array> = []; + let highlightedLineCount = 0; + + await highlightPatchLinesInChunks({ + lines: file.additionLines, + language, + theme: shikiTheme, + onChunk: (startIndex, tokens) => { + tokens.forEach((lineTokens, index) => { + additionLines[startIndex + index] = lineTokens; + }); + highlightedLineCount += tokens.length; + }, + }); + await waitForNextFrame(); + await highlightPatchLinesInChunks({ + lines: file.deletionLines, + language, + theme: shikiTheme, + onChunk: (startIndex, tokens) => { + tokens.forEach((lineTokens, index) => { + deletionLines[startIndex + index] = lineTokens; + }); + highlightedLineCount += tokens.length; + }, + }); + + const highlighted = applyWordAltDiffHighlightsToFile(file, { additionLines, deletionLines }); + if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { + storeResolvedHighlightedFile(cacheKey, highlighted); + } + onProgress({ + highlightedFile: highlighted, + complete: true, + highlightedLineCount, + }); + logReviewHighlighterDiagnostic("file stream highlight complete", { + fileId: file.id, + filePath: file.path, + theme, + language, + highlightedAdditionLineCount: highlighted.additionLines.length, + highlightedDeletionLineCount: highlighted.deletionLines.length, + highlightedLineCount, + durationMs: Date.now() - startedAt, + }); + return highlighted; +} + export async function highlightReviewSelectedLines(input: { readonly filePath: string; readonly lines: ReadonlyArray; @@ -717,7 +997,9 @@ export async function highlightReviewSelectedLines(input: { return {}; } - const language = await resolveLanguageFromPath(input.filePath, input.languageHint ?? null); + const loadedLanguage = resolveLoadedLanguageFromPath(input.filePath, input.languageHint ?? null); + const language = + loadedLanguage ?? (await resolveLanguageFromPath(input.filePath, input.languageHint ?? null)); const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[input.theme]; const additionLikeLines = input.lines .filter((line) => line.change !== "delete")