Add native mobile review diff rendering and static checks

- Add iOS review diff module, parser, and highlighter support
- Wire mobile native lint tooling into CI and local docs
- Include fixtures and tests for the new diff pipeline
This commit is contained in:
Julius Marminge committed 2026-05-20 10:52:49 +02:00
1 parent da56bd50d9
commit 37908166ed
26 files changed
+4836 -192

No files matched your search

+27
View File
@@ -74,6 +74,33 @@ jobs:
test -f apps/desktop/dist-electron/preload.cjs
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
mobile_native_static_analysis:
name: Mobile Native Static Analysis
runs-on: blacksmith-12vcpu-macos-26
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Install mobile native static analysis tools
run: brew bundle install --file apps/mobile/Brewfile
- name: Lint mobile native sources
run: node scripts/mobile-native-static-check.ts
release_smoke:
name: Release Smoke
runs-on: blacksmith-8vcpu-ubuntu-2404
+1
View File
@@ -3,6 +3,7 @@
## Task Completion Requirements
- All of `bun fmt`, `bun lint`, and `bun typecheck` must pass before considering tasks completed.
- If changing native mobile code, `bun lint:mobile` must also pass.
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
## Project Snapshot
+12
View File
@@ -0,0 +1,12 @@
root = false
[*.{kt,kts}]
indent_size = 2
ktlint_code_style = android_studio
ktlint_standard_blank-line-between-when-conditions = disabled
ktlint_standard_class-signature = disabled
ktlint_standard_function-signature = disabled
ktlint_standard_import-ordering = disabled
ktlint_standard_multiline-expression-wrapping = disabled
ktlint_standard_trailing-comma-on-call-site = disabled
ktlint_standard_when-entry-bracing = disabled
+58
View File
@@ -0,0 +1,58 @@
included:
- ios/T3Code
- modules/t3-terminal/ios
- modules/t3-review-diff/ios
excluded:
- ios/Pods
- ios/build
- modules/t3-terminal/Vendor
reporter: xcode
disabled_rules:
- file_length
- function_body_length
- identifier_name
- line_length
- lower_acl_than_parent
- modifier_order
- trailing_comma
- type_body_length
opt_in_rules:
- array_init
- closure_end_indentation
- closure_spacing
- collection_alignment
- contains_over_filter_count
- contains_over_filter_is_empty
- contains_over_first_not_nil
- contains_over_range_nil_comparison
- empty_collection_literal
- empty_count
- empty_string
- enum_case_associated_values_count
- fallthrough
- fatal_error_message
- first_where
- flatmap_over_map_reduce
- force_unwrapping
- implicitly_unwrapped_optional
- last_where
- legacy_multiple
- legacy_random
- operator_usage_whitespace
- overridden_super_call
- prefer_self_type_over_type_of_self
- private_action
- private_outlet
- prohibited_super_call
- reduce_into
- redundant_nil_coalescing
- sorted_first_last
- static_operator
- toggle_bool
- unneeded_parentheses_in_closure_argument
- vertical_parameter_alignment_on_call
- yoda_condition
+3
View File
@@ -0,0 +1,3 @@
brew "swiftlint"
brew "ktlint"
brew "detekt"
+8
View File
@@ -51,6 +51,14 @@ bun run config:dev
bun run config:preview
```
Run static checks for mobile native code:
```bash
node ../../scripts/mobile-native-static-check.ts
```
The native lint task runs SwiftLint for Swift plus ktlint and detekt for Kotlin. Missing native tools are reported as warnings and skipped locally. CI installs the default toolset from `apps/mobile/Brewfile` before running the native checks.
## EAS Builds
Create a cloud dev-client build:
+19
View File
@@ -0,0 +1,19 @@
config:
validation: true
build:
maxIssues: 0
complexity:
LongMethod:
active: true
threshold: 80
TooManyFunctions:
active: false
style:
MagicNumber:
active: false
MaxLineLength:
active: true
maxLineLength: 120
@@ -0,0 +1,19 @@
require 'json'
package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
Pod::Spec.new do |s|
s.name = 'T3ReviewDiffNative'
s.version = package['version']
s.summary = 'Native review diff debug surface for T3 Code mobile.'
s.description = 'Native iOS review diff renderer used to prototype fast mobile review scrolling.'
s.homepage = 'https://t3tools.com'
s.license = { :type => 'UNLICENSED' }
s.author = { 'T3 Tools' => '[email protected]' }
s.platforms = { :ios => '16.1' }
s.source = { :path => '.' }
s.source_files = 'ios/**/*.{h,m,mm,swift}'
s.frameworks = 'CoreGraphics', 'UIKit'
s.swift_version = '5.9'
s.dependency 'ExpoModulesCore'
end
@@ -0,0 +1,7 @@
{
"platforms": ["apple"],
"apple": {
"modules": ["T3ReviewDiffModule"],
"podspecPath": "T3ReviewDiffNative.podspec"
}
}
@@ -0,0 +1,55 @@
import ExpoModulesCore
public class T3ReviewDiffModule: Module {
public func definition() -> ModuleDefinition {
Name("T3ReviewDiffSurface")
View(T3ReviewDiffView.self) {
Prop("rowsJson") { (view: T3ReviewDiffView, rowsJson: String) in
view.setRowsJson(rowsJson)
}
Prop("tokensJson") { (view: T3ReviewDiffView, tokensJson: String) in
view.setTokensJson(tokensJson)
}
Prop("tokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in
view.setTokensPatchJson(tokensPatchJson)
}
Prop("tokensResetKey") { (view: T3ReviewDiffView, tokensResetKey: String) in
view.setTokensResetKey(tokensResetKey)
}
Prop("collapsedFileIdsJson") { (view: T3ReviewDiffView, collapsedFileIdsJson: String) in
view.setCollapsedFileIdsJson(collapsedFileIdsJson)
}
Prop("viewedFileIdsJson") { (view: T3ReviewDiffView, viewedFileIdsJson: String) in
view.setViewedFileIdsJson(viewedFileIdsJson)
}
Prop("appearanceScheme") { (view: T3ReviewDiffView, appearanceScheme: String) in
view.setAppearanceScheme(appearanceScheme)
}
Prop("themeJson") { (view: T3ReviewDiffView, themeJson: String) in
view.setThemeJson(themeJson)
}
Prop("styleJson") { (view: T3ReviewDiffView, styleJson: String) in
view.setStyleJson(styleJson)
}
Prop("rowHeight") { (view: T3ReviewDiffView, rowHeight: Double) in
view.setRowHeight(CGFloat(rowHeight))
}
Prop("contentWidth") { (view: T3ReviewDiffView, contentWidth: Double) in
view.setContentWidth(CGFloat(contentWidth))
}
Events("onDebug", "onToggleFile", "onToggleViewedFile")
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,12 @@
{
"name": "@t3tools/mobile-review-diff-native",
"version": "0.0.0",
"private": true,
"expo-module": {
"ios": {
"modules": [
"T3ReviewDiffModule"
]
}
}
}
+1
View File
@@ -47,6 +47,7 @@
"@shikijs/themes": "3.23.0",
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
"@t3tools/mobile-review-diff-native": "file:./modules/t3-review-diff",
"@t3tools/mobile-terminal-native": "file:./modules/t3-terminal",
"@t3tools/shared": "workspace:*",
"clsx": "^2.1.1",
@@ -0,0 +1,528 @@
import Stack from "expo-router/stack";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
type LayoutChangeEvent,
StyleSheet,
Text as NativeText,
type NativeSyntheticEvent,
useColorScheme,
View,
} from "react-native";
import {
debugReviewDiffFixtures,
type DebugReviewDiffFixtureId,
} from "../../features/debug/fixtures/reviewDiffFixtures";
import {
getResolvedNativeReviewDiffModuleName,
type NativeReviewDiffStyle,
type NativeReviewDiffTheme,
resolveNativeReviewDiffView,
} from "../../features/debug/native-review-diff/nativeReviewDiffModule";
import {
highlightNativeReviewDiffVisibleRows,
streamNativeReviewDiffTokens,
type NativeReviewDiffHighlightEngine,
} from "../../features/debug/native-review-diff/nativeReviewDiffHighlighter";
import {
getNativeReviewDiffFixture,
parseNativeReviewDiffFixture,
} from "../../features/debug/native-review-diff/nativeReviewDiffParser";
import {
getPierreTerminalTheme,
type TerminalAppearanceScheme,
} from "../../features/terminal/terminalTheme";
const NATIVE_DEBUG_ROW_HEIGHT = 20;
const NATIVE_DEBUG_CONTENT_WIDTH = 2800;
const NATIVE_DEBUG_STYLE = {
rowHeight: NATIVE_DEBUG_ROW_HEIGHT,
contentWidth: NATIVE_DEBUG_CONTENT_WIDTH,
changeBarWidth: 4,
gutterWidth: 46,
codePadding: 7,
textVerticalInset: 2,
fileHeaderHeight: 56,
fileHeaderHorizontalMargin: 8,
fileHeaderVerticalMargin: 6,
fileHeaderCornerRadius: 10,
fileHeaderHorizontalPadding: 10,
fileHeaderPathRightPadding: 118,
fileHeaderCountColumnWidth: 38,
fileHeaderCountGap: 5,
codeFontSize: 11,
codeFontWeight: "regular",
lineNumberFontSize: 10,
lineNumberFontWeight: "regular",
hunkFontSize: 11,
hunkFontWeight: "medium",
fileHeaderFontSize: 11,
fileHeaderFontWeight: "semibold",
fileHeaderMetaFontSize: 10,
fileHeaderMetaFontWeight: "semibold",
fileHeaderSubtextFontSize: 11,
fileHeaderSubtextFontWeight: "medium",
fileHeaderStatusFontSize: 9,
fileHeaderStatusFontWeight: "bold",
emptyStateFontSize: 12,
emptyStateFontWeight: "medium",
} satisfies NativeReviewDiffStyle;
function createNativeReviewDiffTheme(scheme: TerminalAppearanceScheme): NativeReviewDiffTheme {
const terminalTheme = getPierreTerminalTheme(scheme);
const [, terminalRed, , , terminalBlue] = terminalTheme.palette;
if (scheme === "dark") {
return {
background: terminalTheme.background,
text: terminalTheme.foreground,
mutedText: terminalTheme.mutedForeground,
headerBackground: terminalTheme.background,
border: terminalTheme.border,
hunkBackground: "#071f28",
hunkText: terminalBlue ?? "#009fff",
addBackground: "#0d2f28",
deleteBackground: "#391415",
addBar: "#00cab1",
deleteBar: terminalRed ?? "#ff2e3f",
addText: "#5ECC71",
deleteText: "#FF6762",
};
}
return {
background: "#ffffff",
text: "#070707",
mutedText: terminalTheme.mutedForeground,
headerBackground: "#ffffff",
border: terminalTheme.border,
hunkBackground: "#e0f2ff",
hunkText: terminalBlue ?? "#009fff",
addBackground: "#e5f8f5",
deleteBackground: "#ffe6e7",
addBar: "#00cab1",
deleteBar: terminalRed ?? "#ff2e3f",
addText: "#199F43",
deleteText: "#D52C36",
};
}
export default function NativeReviewDiffDebugRoute() {
const colorScheme = useColorScheme() === "dark" ? "dark" : "light";
const [fixtureId, setFixtureId] = useState<DebugReviewDiffFixtureId>("large");
const [highlightEngine, setHighlightEngine] = useState<NativeReviewDiffHighlightEngine>("native");
const [collapsedFileIds, setCollapsedFileIds] = useState<ReadonlyArray<string>>([]);
const [viewedFileIds, setViewedFileIds] = useState<ReadonlyArray<string>>([]);
const fixture = getNativeReviewDiffFixture(fixtureId);
const parsed = useMemo(() => parseNativeReviewDiffFixture(fixture), [fixture]);
const effectiveHighlightEngine: NativeReviewDiffHighlightEngine =
fixtureId === "xl" && highlightEngine === "native" ? "javascript" : highlightEngine;
const useVisibleOnlyHighlighting = fixtureId === "xl";
const debugTheme = useMemo(() => createNativeReviewDiffTheme(colorScheme), [colorScheme]);
const rowsJson = useMemo(() => JSON.stringify(parsed.rows), [parsed.rows]);
const collapsedFileIdsJson = useMemo(() => JSON.stringify(collapsedFileIds), [collapsedFileIds]);
const viewedFileIdsJson = useMemo(() => JSON.stringify(viewedFileIds), [viewedFileIds]);
const themeJson = useMemo(() => JSON.stringify(debugTheme), [debugTheme]);
const styleJson = useMemo(() => JSON.stringify(NATIVE_DEBUG_STYLE), []);
const tokensResetKey = `${fixtureId}:${colorScheme}:${effectiveHighlightEngine}`;
const [tokensPatchJson, setTokensPatchJson] = useState(
JSON.stringify({ resetKey: "", tokensByRowId: {} }),
);
const highlightedRowIdsRef = useRef<Set<string>>(new Set());
const visibleRangeRef = useRef({ firstRowIndex: 0, lastRowIndex: 80 });
const visibleChunkIndexRef = useRef(0);
const useVisibleOnlyHighlightingRef = useRef(useVisibleOnlyHighlighting);
const [visibleHighlightRequest, setVisibleHighlightRequest] = useState(0);
const NativeReviewDiffView = resolveNativeReviewDiffView();
const handleSelectFixture = useCallback((nextFixtureId: DebugReviewDiffFixtureId) => {
setFixtureId(nextFixtureId);
}, []);
useEffect(() => {
useVisibleOnlyHighlightingRef.current = useVisibleOnlyHighlighting;
}, [useVisibleOnlyHighlighting]);
useEffect(() => {
setCollapsedFileIds([]);
setViewedFileIds([]);
}, [fixtureId]);
useEffect(() => {
const abortController = new AbortController();
highlightedRowIdsRef.current = new Set();
visibleChunkIndexRef.current = 0;
setTokensPatchJson(JSON.stringify({ resetKey: tokensResetKey, tokensByRowId: {} }));
if (useVisibleOnlyHighlighting) {
setVisibleHighlightRequest((request) => request + 1);
console.log("[debug-native-diff] visible-only highlight start", {
fixture: fixtureId,
files: parsed.files.length,
rows: parsed.rows.length,
scheme: colorScheme,
effectiveEngine: effectiveHighlightEngine,
requestedEngine: highlightEngine,
});
return () => abortController.abort();
}
void (async () => {
const startedAt = performance.now();
console.log("[debug-native-diff] highlight start", {
fixture: fixtureId,
files: parsed.files.length,
rows: parsed.rows.length,
scheme: colorScheme,
effectiveEngine: effectiveHighlightEngine,
requestedEngine: highlightEngine,
});
try {
const engine = await streamNativeReviewDiffTokens({
files: parsed.files,
rows: parsed.rows,
scheme: colorScheme,
engine: effectiveHighlightEngine,
signal: abortController.signal,
onChunk: (chunk) => {
if (abortController.signal.aborted) {
return;
}
setTokensPatchJson(JSON.stringify({ resetKey: tokensResetKey, ...chunk }));
if (chunk.chunkIndex < 5 || chunk.chunkIndex % 10 === 0) {
console.log("[debug-native-diff] highlight chunk", {
chunkIndex: chunk.chunkIndex,
durationMs: chunk.durationMs,
filePath: chunk.filePath,
lineCount: chunk.lineCount,
});
}
},
});
if (!abortController.signal.aborted) {
console.log("[debug-native-diff] highlight complete", {
durationMs: Math.round(performance.now() - startedAt),
engine,
fixture: fixtureId,
effectiveEngine: effectiveHighlightEngine,
requestedEngine: highlightEngine,
});
}
} catch (error) {
if (!abortController.signal.aborted) {
console.warn("[debug-native-diff] highlight failed", {
error: error instanceof Error ? error.message : String(error),
});
}
}
})();
return () => abortController.abort();
}, [
colorScheme,
effectiveHighlightEngine,
fixtureId,
highlightEngine,
parsed.files,
parsed.rows,
tokensResetKey,
useVisibleOnlyHighlighting,
]);
useEffect(() => {
if (!useVisibleOnlyHighlighting) {
return;
}
const abortController = new AbortController();
const requestRange = visibleRangeRef.current;
void (async () => {
try {
const result = await highlightNativeReviewDiffVisibleRows({
files: parsed.files,
rows: parsed.rows,
scheme: colorScheme,
engine: effectiveHighlightEngine,
firstRowIndex: requestRange.firstRowIndex,
lastRowIndex: requestRange.lastRowIndex,
alreadyHighlightedRowIds: highlightedRowIdsRef.current,
signal: abortController.signal,
});
if (abortController.signal.aborted || result.rowCount === 0) {
return;
}
for (const rowId of Object.keys(result.tokensByRowId)) {
highlightedRowIdsRef.current.add(rowId);
}
const chunkIndex = visibleChunkIndexRef.current;
visibleChunkIndexRef.current += 1;
setTokensPatchJson(
JSON.stringify({
resetKey: tokensResetKey,
chunkIndex,
fileId: "visible",
filePath: "visible rows",
language: "diff",
lineCount: result.rowCount,
durationMs: result.durationMs,
tokensByRowId: result.tokensByRowId,
}),
);
if (chunkIndex < 2 || chunkIndex % 10 === 0) {
console.log("[debug-native-diff] visible highlight chunk", {
chunkIndex,
durationMs: result.durationMs,
highlightedRows: result.rowCount,
firstRowIndex: requestRange.firstRowIndex,
lastRowIndex: requestRange.lastRowIndex,
});
}
} catch (error) {
if (!abortController.signal.aborted) {
console.warn("[debug-native-diff] visible highlight failed", {
error: error instanceof Error ? error.message : String(error),
});
}
}
})();
return () => abortController.abort();
}, [
colorScheme,
effectiveHighlightEngine,
parsed.files,
parsed.rows,
tokensResetKey,
useVisibleOnlyHighlighting,
visibleHighlightRequest,
]);
useEffect(() => {
console.log("[debug-native-diff] native view availability", {
available: NativeReviewDiffView != null,
moduleName: getResolvedNativeReviewDiffModuleName(),
rowsJsonLength: rowsJson.length,
});
}, [NativeReviewDiffView, rowsJson.length]);
const handleNativeContainerLayout = useCallback((event: LayoutChangeEvent) => {
const { height, width } = event.nativeEvent.layout;
console.log("[debug-native-diff] native container layout", {
height: Math.round(height),
width: Math.round(width),
});
}, []);
const handleNativeLayout = useCallback((event: LayoutChangeEvent) => {
const { height, width } = event.nativeEvent.layout;
console.log("[debug-native-diff] native view layout", {
height: Math.round(height),
width: Math.round(width),
});
}, []);
const handleNativeDebug = useCallback((event: NativeSyntheticEvent<Record<string, unknown>>) => {
const payload = event.nativeEvent;
const message = payload.message;
if (
useVisibleOnlyHighlightingRef.current &&
(message === "draw-metrics" || message === "visible-range") &&
typeof payload.firstRowIndex === "number" &&
typeof payload.lastRowIndex === "number"
) {
const previousRange = visibleRangeRef.current;
const nextRange = {
firstRowIndex: payload.firstRowIndex,
lastRowIndex: payload.lastRowIndex,
};
const movedRows =
Math.abs(nextRange.firstRowIndex - previousRange.firstRowIndex) +
Math.abs(nextRange.lastRowIndex - previousRange.lastRowIndex);
visibleRangeRef.current = nextRange;
if (movedRows >= 20) {
setVisibleHighlightRequest((request) => request + 1);
}
}
}, []);
const handleToggleFile = useCallback(
(event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
const { fileId } = event.nativeEvent;
if (!fileId) {
return;
}
setCollapsedFileIds((current) =>
current.includes(fileId) ? current.filter((id) => id !== fileId) : [...current, fileId],
);
},
[],
);
const handleToggleViewedFile = useCallback(
(event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
const { fileId } = event.nativeEvent;
if (!fileId) {
return;
}
setViewedFileIds((current) => {
if (current.includes(fileId)) {
return current.filter((id) => id !== fileId);
}
setCollapsedFileIds((collapsed) =>
collapsed.includes(fileId) ? collapsed : [...collapsed, fileId],
);
return [...current, fileId];
});
},
[],
);
return (
<>
<Stack.Screen
options={{
headerShown: true,
headerShadowVisible: false,
headerStyle: { backgroundColor: debugTheme.background },
headerTintColor: debugTheme.text,
headerTitleAlign: "center",
title: "",
headerTitle: () => (
<View style={{ alignItems: "center", maxWidth: 240 }}>
<NativeText
numberOfLines={1}
style={{
color: debugTheme.text,
fontFamily: "DMSans_700Bold",
fontSize: 13,
lineHeight: 16,
}}
>
Native review diff
</NativeText>
<NativeText
numberOfLines={1}
style={{
color: debugTheme.mutedText,
fontFamily: "DMSans_700Bold",
fontSize: 11,
lineHeight: 14,
}}
>
{parsed.files.length} files · {parsed.rows.length} rows · +{parsed.additions} -
{parsed.deletions} · {effectiveHighlightEngine === "native" ? "native" : "JS"}
{fixtureId === "xl" && highlightEngine === "native" ? " fallback" : ""}
</NativeText>
</View>
),
}}
/>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Menu
icon="line.3.horizontal.decrease.circle"
title="Diff debug options"
separateBackground
>
<Stack.Toolbar.Menu icon="sparkles" inline title="Highlighter engine">
<Stack.Toolbar.Label>Highlighter engine</Stack.Toolbar.Label>
{(["native", "javascript"] as const).map((engine) => {
const isSelected = engine === highlightEngine;
return (
<Stack.Toolbar.MenuAction
key={engine}
icon="circle"
isOn={isSelected}
onPress={() => setHighlightEngine(engine)}
subtitle={
engine === "native" && fixtureId === "xl"
? "XL currently falls back after native engine crash"
: engine === "native"
? "react-native-shiki-engine"
: "JavaScript regex engine"
}
>
<Stack.Toolbar.Label>
{engine === "native" ? "Native" : "JavaScript"}
</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
);
})}
</Stack.Toolbar.Menu>
<Stack.Toolbar.Menu icon="doc.text" inline title="Fixture">
<Stack.Toolbar.Label>Fixture</Stack.Toolbar.Label>
{debugReviewDiffFixtures.map((candidate) => {
const isSelected = candidate.id === fixtureId;
return (
<Stack.Toolbar.MenuAction
key={candidate.id}
icon="doc.text"
isOn={isSelected}
onPress={() => handleSelectFixture(candidate.id)}
subtitle={`${candidate.lineCount} patch lines`}
>
<Stack.Toolbar.Label>{candidate.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
);
})}
</Stack.Toolbar.Menu>
</Stack.Toolbar.Menu>
</Stack.Toolbar>
<View
className="relative flex-1"
style={{ backgroundColor: debugTheme.background }}
collapsable={false}
onLayout={handleNativeContainerLayout}
>
{NativeReviewDiffView ? (
<NativeReviewDiffView
key={fixtureId}
collapsable={false}
testID="native-review-diff-view"
style={StyleSheet.absoluteFillObject}
appearanceScheme={colorScheme}
contentWidth={NATIVE_DEBUG_CONTENT_WIDTH}
collapsedFileIdsJson={collapsedFileIdsJson}
rowHeight={NATIVE_DEBUG_ROW_HEIGHT}
rowsJson={rowsJson}
styleJson={styleJson}
themeJson={themeJson}
tokensResetKey={tokensResetKey}
tokensPatchJson={tokensPatchJson}
viewedFileIdsJson={viewedFileIdsJson}
onDebug={handleNativeDebug}
onLayout={handleNativeLayout}
onToggleFile={handleToggleFile}
onToggleViewedFile={handleToggleViewedFile}
/>
) : (
<View className="flex-1 items-center justify-center px-8">
<NativeText
style={{
color: debugTheme.text,
fontFamily: "DMSans_700Bold",
fontSize: 14,
textAlign: "center",
}}
>
Native review diff view is not available in this build.
</NativeText>
<NativeText
style={{
color: debugTheme.mutedText,
fontFamily: "DMSans_400Regular",
fontSize: 12,
marginTop: 8,
textAlign: "center",
}}
>
Expected native view manager: T3ReviewDiffSurface. Rebuild the current iOS development
client with `bun ios` after native module changes.
</NativeText>
</View>
)}
</View>
</>
);
}
+225 -130
View File
@@ -13,6 +13,7 @@ import githubLightDefault from "@shikijs/themes/github-light-default";
import Stack from "expo-router/stack";
import {
memo,
type ReactElement,
useCallback,
useEffect,
useMemo,
@@ -21,7 +22,9 @@ import {
useSyncExternalStore,
} from "react";
import {
Animated,
FlatList,
PanResponder,
Pressable,
ScrollView,
Text as NativeText,
@@ -98,11 +101,6 @@ type DebugDiffCodeRow = {
type DebugDiffRow = DebugDiffFileHeaderRow | DebugDiffHunkRow | DebugDiffCodeRow;
type DebugDiffFileBlock = {
readonly file: DebugDiffFileHeaderRow;
readonly rows: ReadonlyArray<DebugDiffHunkRow | DebugDiffCodeRow>;
};
type DebugHighlightChunk = {
readonly id: string;
readonly fileId: string;
@@ -112,7 +110,6 @@ type DebugHighlightChunk = {
type DebugParsedDiff = {
readonly files: ReadonlyArray<DebugDiffFile>;
readonly fileBlocks: ReadonlyArray<DebugDiffFileBlock>;
readonly rows: ReadonlyArray<DebugDiffRow>;
readonly highlightChunks: ReadonlyArray<DebugHighlightChunk>;
readonly additions: number;
@@ -135,6 +132,15 @@ 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_CODE_TEXT_STYLE = {
fontFamily: DEBUG_MONO_FONT_FAMILY,
fontStyle: "normal" as const,
fontWeight: "700" as const,
};
const DEBUG_DELETE_STRIPE_INDICES = Array.from(
{ length: DEBUG_DELETE_STRIPE_COUNT },
(_, index) => index,
);
const DEBUG_THEME_NAME_BY_SCHEME = {
dark: "github-dark-default",
light: "github-light-default",
@@ -200,6 +206,35 @@ class DebugTokenStore {
}
}
class DebugHorizontalOffsetStore {
private readonly offsetsByFileId = new Map<string, number>();
private readonly valuesByFileId = new Map<string, Animated.Value>();
getOffset(fileId: string): number {
return this.offsetsByFileId.get(fileId) ?? 0;
}
getValue(fileId: string): Animated.Value {
let value = this.valuesByFileId.get(fileId);
if (!value) {
value = new Animated.Value(-this.getOffset(fileId));
this.valuesByFileId.set(fileId, value);
}
return value;
}
reset(): void {
this.valuesByFileId.forEach((value) => value.stopAnimation());
this.valuesByFileId.clear();
this.offsetsByFileId.clear();
}
setOffset(fileId: string, offset: number): void {
this.offsetsByFileId.set(fileId, offset);
this.getValue(fileId).setValue(-offset);
}
}
function waitForNextFrame(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, 0));
}
@@ -424,20 +459,6 @@ function parseDebugDiffFixture(fixture: DebugReviewDiffFixture): DebugParsedDiff
deletions: file?.deletions ?? row.deletions,
};
});
const fileBlocksById = new Map<
string,
{ file: DebugDiffFileHeaderRow; rows: Array<DebugDiffHunkRow | DebugDiffCodeRow> }
>();
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);
@@ -461,7 +482,6 @@ function parseDebugDiffFixture(fixture: DebugReviewDiffFixture): DebugParsedDiff
const parsed = {
files: fileSummaries,
fileBlocks,
rows: rowsWithFileStats,
highlightChunks,
additions: fileSummaries.reduce((total, file) => total + file.additions, 0),
@@ -487,8 +507,8 @@ const TokenText = memo(function TokenText(props: {
return (
<NativeText
numberOfLines={1}
className="text-[13px] font-medium leading-[18px] text-foreground"
style={{ fontFamily: DEBUG_MONO_FONT_FAMILY }}
className="text-[13px] leading-[18px] text-foreground"
style={DEBUG_CODE_TEXT_STYLE}
>
{props.content || " "}
</NativeText>
@@ -500,29 +520,19 @@ const TokenText = memo(function TokenText(props: {
return (
<NativeText
numberOfLines={1}
className="text-[13px] font-medium leading-[18px] text-foreground"
style={{ fontFamily: DEBUG_MONO_FONT_FAMILY }}
className="text-[13px] leading-[18px] text-foreground"
style={DEBUG_CODE_TEXT_STYLE}
>
{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 (
<NativeText
key={tokenKey}
style={{
...DEBUG_CODE_TEXT_STYLE,
color: token.color ?? undefined,
fontFamily: DEBUG_MONO_FONT_FAMILY,
fontStyle,
fontWeight,
}}
>
{token.content}
@@ -539,11 +549,11 @@ function changeRowClassName(change: DebugDiffChange): string {
return "bg-card";
}
function DebugChangeBar(props: { readonly change: DebugDiffChange }) {
const DebugChangeBar = memo(function DebugChangeBar(props: { readonly change: DebugDiffChange }) {
if (props.change === "delete") {
return (
<View className="overflow-hidden" style={{ width: DEBUG_CHANGE_BAR_WIDTH }}>
{Array.from({ length: DEBUG_DELETE_STRIPE_COUNT }, (_, index) => (
{DEBUG_DELETE_STRIPE_INDICES.map((index) => (
<View key={index}>
<View className="bg-rose-400" style={{ height: 1, width: DEBUG_CHANGE_BAR_WIDTH }} />
<View style={{ height: 1, width: DEBUG_CHANGE_BAR_WIDTH }} />
@@ -558,9 +568,9 @@ function DebugChangeBar(props: { readonly change: DebugDiffChange }) {
}
return <View style={{ width: DEBUG_CHANGE_BAR_WIDTH }} />;
}
});
function DebugDiffFileHeader(props: {
const DebugDiffFileHeader = memo(function DebugDiffFileHeader(props: {
readonly header: DebugDiffFileHeaderRow;
readonly width: number;
}) {
@@ -578,9 +588,11 @@ function DebugDiffFileHeader(props: {
</Text>
</View>
);
}
});
function DebugDiffStickyCell(props: { readonly item: DebugDiffHunkRow | DebugDiffCodeRow }) {
const DebugDiffStickyCell = memo(function DebugDiffStickyCell(props: {
readonly item: DebugDiffHunkRow | DebugDiffCodeRow;
}) {
if (props.item.kind === "hunk") {
return (
<View
@@ -599,13 +611,19 @@ function DebugDiffStickyCell(props: { readonly item: DebugDiffHunkRow | DebugDif
>
<DebugChangeBar change={props.item.change} />
<View className="items-end justify-center pr-2" style={{ width: DEBUG_GUTTER_WIDTH }}>
<Text className="font-mono text-[11px] text-foreground-muted">{displayLineNumber}</Text>
<NativeText
className="text-[11px] text-foreground-muted"
numberOfLines={1}
style={DEBUG_CODE_TEXT_STYLE}
>
{displayLineNumber}
</NativeText>
</View>
</View>
);
}
});
function DebugDiffCodeCell(props: {
const DebugDiffCodeCell = memo(function DebugDiffCodeCell(props: {
readonly item: DebugDiffHunkRow | DebugDiffCodeRow;
readonly tokens: ReadonlyArray<DebugToken> | null;
}) {
@@ -619,8 +637,8 @@ function DebugDiffCodeCell(props: {
>
<NativeText
numberOfLines={1}
className="text-[13px] font-medium leading-[18px] text-sky-700 dark:text-sky-300"
style={{ fontFamily: DEBUG_MONO_FONT_FAMILY }}
className="text-[13px] leading-[18px] text-sky-700 dark:text-sky-300"
style={DEBUG_CODE_TEXT_STYLE}
>
{item.text}
</NativeText>
@@ -636,76 +654,112 @@ function DebugDiffCodeCell(props: {
<TokenText content={item.content} tokens={props.tokens} />
</View>
);
}
});
const DebugDiffFileBlockView = memo(function DebugDiffFileBlockView(props: {
readonly block: DebugDiffFileBlock;
readonly tokenStore: DebugTokenStore;
readonly width: number;
const DebugHorizontalCodeViewport = memo(function DebugHorizontalCodeViewport(props: {
readonly children: ReactElement;
readonly fileId: string;
readonly horizontalOffset: Animated.Value;
readonly onActivateFile: (fileId: string) => void;
readonly viewportWidth: number;
}) {
return (
<View
onTouchStart={() => props.onActivateFile(props.fileId)}
style={{ overflow: "hidden", width: props.viewportWidth }}
>
<Animated.View style={{ transform: [{ translateX: props.horizontalOffset }] }}>
{props.children}
</Animated.View>
</View>
);
});
const DebugDiffLineRowView = memo(function DebugDiffLineRowView(props: {
readonly horizontalOffset: Animated.Value;
readonly onActivateFile: (fileId: string) => void;
readonly row: DebugDiffCodeRow;
readonly tokenStore: DebugTokenStore;
readonly viewportWidth: 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],
(listener) => props.tokenStore.subscribeFile(props.row.fileId, listener),
[props.row.fileId, props.tokenStore],
),
useCallback(
() => props.tokenStore.getFileVersion(props.block.file.fileId),
[props.block.file.fileId, props.tokenStore],
() => props.tokenStore.getFileVersion(props.row.fileId),
[props.row.fileId, props.tokenStore],
),
useCallback(
() => props.tokenStore.getFileVersion(props.block.file.fileId),
[props.block.file.fileId, props.tokenStore],
() => props.tokenStore.getFileVersion(props.row.fileId),
[props.row.fileId, props.tokenStore],
),
);
return (
<View style={{ width: props.width }}>
<DebugDiffFileHeader header={props.block.file} width={props.width} />
<View
className="flex-row"
style={{
height: props.block.rows.length * DEBUG_DIFF_ROW_HEIGHT,
width: props.width,
}}
<View className="flex-row" style={{ height: DEBUG_DIFF_ROW_HEIGHT }}>
<DebugDiffStickyCell item={props.row} />
<DebugHorizontalCodeViewport
fileId={props.row.fileId}
horizontalOffset={props.horizontalOffset}
onActivateFile={props.onActivateFile}
viewportWidth={props.viewportWidth}
>
<View style={{ width: DEBUG_STICKY_WIDTH }}>
{props.block.rows.map((row) => (
<DebugDiffStickyCell key={row.id} item={row} />
))}
</View>
<ScrollView
horizontal
bounces={false}
directionalLockEnabled
keyboardShouldPersistTaps="handled"
showsHorizontalScrollIndicator
style={{
height: props.block.rows.length * DEBUG_DIFF_ROW_HEIGHT,
width: viewportWidth,
}}
>
<View style={{ width: DEBUG_CONTENT_WIDTH }}>
{props.block.rows.map((row) => (
<DebugDiffCodeCell
key={row.id}
item={row}
tokens={
row.kind === "line"
? (props.tokenStore.getTokens(row.highlightChunkId)?.[
row.indexInHighlightChunk
] ?? null)
: null
}
/>
))}
</View>
</ScrollView>
</View>
<DebugDiffCodeCell
item={props.row}
tokens={
props.tokenStore.getTokens(props.row.highlightChunkId)?.[
props.row.indexInHighlightChunk
] ?? null
}
/>
</DebugHorizontalCodeViewport>
</View>
);
});
const DebugDiffFlatRowView = memo(function DebugDiffFlatRowView(props: {
readonly horizontalOffsetStore: DebugHorizontalOffsetStore;
readonly onActivateFile: (fileId: string) => void;
readonly row: DebugDiffRow;
readonly tokenStore: DebugTokenStore;
readonly width: number;
}) {
if (props.row.kind === "file") {
return <DebugDiffFileHeader header={props.row} width={props.width} />;
}
const viewportWidth = Math.max(0, props.width - DEBUG_STICKY_WIDTH);
if (props.row.kind === "hunk") {
const horizontalOffset = props.horizontalOffsetStore.getValue(props.row.fileId);
return (
<View className="flex-row" style={{ height: DEBUG_DIFF_ROW_HEIGHT, width: props.width }}>
<DebugDiffStickyCell item={props.row} />
<View
onTouchStart={() => props.onActivateFile(props.row.fileId)}
style={{ overflow: "hidden", width: viewportWidth }}
>
<Animated.View style={{ transform: [{ translateX: horizontalOffset }] }}>
<DebugDiffCodeCell item={props.row} tokens={null} />
</Animated.View>
</View>
</View>
);
}
return (
<DebugDiffLineRowView
horizontalOffset={props.horizontalOffsetStore.getValue(props.row.fileId)}
onActivateFile={props.onActivateFile}
row={props.row}
tokenStore={props.tokenStore}
viewportWidth={viewportWidth}
/>
);
});
function EngineToggle(props: {
readonly engine: DebugHighlightEngine;
readonly onChangeEngine: (engine: DebugHighlightEngine) => void;
@@ -781,6 +835,9 @@ export default function SyntaxHighlightDebugRoute() {
const renderStartRef = useRef<number | null>(null);
const generationRef = useRef(0);
const tokenStore = useMemo(() => new DebugTokenStore(), []);
const horizontalOffsetStore = useMemo(() => new DebugHorizontalOffsetStore(), []);
const activeHorizontalFileIdRef = useRef<string | null>(null);
const horizontalDragStartRef = useRef(0);
const fixture = useMemo(
() =>
@@ -789,21 +846,12 @@ export default function SyntaxHighlightDebugRoute() {
[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();
horizontalOffsetStore.reset();
setStatus("Initializing highlighter");
void (async () => {
@@ -887,6 +935,7 @@ export default function SyntaxHighlightDebugRoute() {
parsedDiff.highlightChunks,
parsedDiff.rows.length,
themeName,
horizontalOffsetStore,
tokenStore,
]);
@@ -906,11 +955,53 @@ export default function SyntaxHighlightDebugRoute() {
});
});
const onActivateHorizontalFile = useCallback((fileId: string) => {
activeHorizontalFileIdRef.current = fileId;
}, []);
const maxHorizontalOffset = Math.max(
0,
DEBUG_CONTENT_WIDTH - Math.max(0, width - DEBUG_STICKY_WIDTH),
);
const horizontalPanResponder = useMemo(
() =>
PanResponder.create({
onMoveShouldSetPanResponder: (_event, gestureState) => {
const horizontalDistance = Math.abs(gestureState.dx);
const verticalDistance = Math.abs(gestureState.dy);
return horizontalDistance > 8 && horizontalDistance > verticalDistance * 1.25;
},
onPanResponderGrant: () => {
const fileId = activeHorizontalFileIdRef.current;
horizontalDragStartRef.current = fileId ? horizontalOffsetStore.getOffset(fileId) : 0;
},
onPanResponderMove: (_event, gestureState) => {
const fileId = activeHorizontalFileIdRef.current;
if (!fileId) {
return;
}
const nextOffset = Math.min(
Math.max(horizontalDragStartRef.current - gestureState.dx, 0),
maxHorizontalOffset,
);
horizontalOffsetStore.setOffset(fileId, nextOffset);
},
onPanResponderTerminationRequest: () => true,
}),
[horizontalOffsetStore, maxHorizontalOffset],
);
const renderItem = useCallback(
({ item }: ListRenderItemInfo<DebugDiffFileBlock>) => (
<DebugDiffFileBlockView block={item} tokenStore={tokenStore} width={width} />
({ item }: ListRenderItemInfo<DebugDiffRow>) => (
<DebugDiffFlatRowView
horizontalOffsetStore={horizontalOffsetStore}
onActivateFile={onActivateHorizontalFile}
row={item}
tokenStore={tokenStore}
width={width}
/>
),
[tokenStore, width],
[horizontalOffsetStore, onActivateHorizontalFile, tokenStore, width],
);
return (
@@ -922,6 +1013,7 @@ export default function SyntaxHighlightDebugRoute() {
headerTintColor: headerIcon,
headerTransparent: true,
headerShadowVisible: false,
gestureEnabled: false,
}}
/>
@@ -942,23 +1034,26 @@ export default function SyntaxHighlightDebugRoute() {
<FixtureToggle fixtureId={fixtureId} onChangeFixture={setFixtureId} />
</View>
<FlatList
style={{ flex: 1, width }}
data={parsedDiff.fileBlocks}
renderItem={renderItem}
keyExtractor={(item) => 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 }}
/>
<View className="flex-1" {...horizontalPanResponder.panHandlers}>
<FlatList
style={{ flex: 1, width }}
data={parsedDiff.rows}
renderItem={renderItem}
keyExtractor={(item) => item.id}
getItemLayout={(_, index) => ({
length: DEBUG_DIFF_ROW_HEIGHT,
offset: DEBUG_DIFF_ROW_HEIGHT * index,
index,
})}
initialNumToRender={28}
maxToRenderPerBatch={32}
updateCellsBatchingPeriod={24}
windowSize={7}
removeClippedSubviews
keyboardShouldPersistTaps="handled"
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
/>
</View>
</View>
);
}
+15 -61
View File
@@ -1,36 +1,23 @@
import { Stack, useRouter } from "expo-router";
import { useState } from "react";
import { Pressable, Text as RNText, View, useColorScheme } from "react-native";
import { Text as RNText, View, useColorScheme } from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
import { buildThreadRoutePath } from "../lib/routes";
import { ConnectionStatusDot } from "../features/connection/ConnectionStatusDot";
import { useRemoteCatalog } from "../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../state/use-remote-environment-registry";
import { HomeScreen } from "../features/home/HomeScreen";
import { EnvironmentConnectionState } from "@t3tools/client-runtime";
/* ─── Connection pill label ──────────────────────────────────────────── */
const CONNECTION_LABEL: Record<EnvironmentConnectionState, string> = {
ready: "Connected",
connecting: "Connecting",
reconnecting: "Reconnecting",
disconnected: "Offline",
idle: "No backends",
};
/* ─── Route screen ───────────────────────────────────────────────────── */
export default function HomeRouteScreen() {
const { connectionState, hasRemoteActivity, projects, threads } = useRemoteCatalog();
const { projects, threads } = useRemoteCatalog();
const { savedConnectionsById } = useRemoteEnvironmentState();
const router = useRouter();
const [searchQuery, setSearchQuery] = useState("");
const isDark = useColorScheme() === "dark";
const iconColor = String(useThemeColor("--color-icon"));
const secondaryFg = isDark ? "#a3a3a3" : "#525252";
return (
<>
@@ -42,52 +29,6 @@ export default function HomeRouteScreen() {
headerShadowVisible: false,
headerTintColor: iconColor,
headerTitle: "",
headerRight: () => (
<View style={{ flexDirection: "row", alignItems: "center", gap: 12 }}>
<Pressable
onPress={() => router.push("/debug/syntax-highlight")}
hitSlop={8}
style={{
borderRadius: 999,
backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)",
paddingHorizontal: 10,
paddingVertical: 5,
}}
>
<RNText
style={{
fontFamily: "DMSans_700Bold",
fontSize: 12,
color: secondaryFg,
}}
>
Debug
</RNText>
</Pressable>
<Pressable
onPress={() => router.push("/connections")}
hitSlop={8}
style={{
flexDirection: "row",
alignItems: "center",
gap: 8,
paddingHorizontal: 4,
paddingVertical: 4,
}}
>
<ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />
<RNText
style={{
fontFamily: "DMSans_700Bold",
fontSize: 12,
color: secondaryFg,
}}
>
{CONNECTION_LABEL[connectionState]}
</RNText>
</Pressable>
</View>
),
headerSearchBarOptions: {
placeholder: "Search threads",
onChangeText: (event) => {
@@ -136,6 +77,19 @@ export default function HomeRouteScreen() {
</Stack.Toolbar.View>
</Stack.Toolbar>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
icon="ladybug"
onPress={() => router.push("/debug/native-review-diff")}
separateBackground
/>
<Stack.Toolbar.Button
icon="network"
onPress={() => router.push("/connections")}
separateBackground
/>
</Stack.Toolbar>
{/* Bottom toolbar: search + compose, visually split like iMessage */}
<Stack.Toolbar placement="bottom">
<Stack.Toolbar.SearchBarSlot />
@@ -1,4 +1,6 @@
export type DebugReviewDiffFixtureId = "small" | "medium" | "large" | "current";
import { DEBUG_REVIEW_XL_DIFF } from "./reviewDiffXlFixture";
export type DebugReviewDiffFixtureId = "small" | "medium" | "large" | "xl" | "current" | "states";
export interface DebugReviewDiffFixture {
readonly id: DebugReviewDiffFixtureId;
@@ -8,7 +10,203 @@ export interface DebugReviewDiffFixture {
readonly diff: string;
}
const DEBUG_REVIEW_STATES_DIFF = `diff --git a/apps/demo/src/main.ts b/apps/demo/src/main.ts
index 78f5eaa12..c2874ad31 100644
--- a/apps/demo/src/main.ts
+++ b/apps/demo/src/main.ts
@@ -1,18 +1,24 @@
import { createServer } from "./server";
import { createLogger } from "./logger";
-const retryLimit = 2;
-const greeting = "Hi You, {name}! Welcome to our application.";
+const retryLimit = 4;
+const greeting = "Hello There, {name}! Welcome to the updated application.";
const logger = createLogger("demo");
export async function boot() {
const server = createServer({
- port: 3000,
- timeoutMs: 1200,
+ port: 3030,
+ timeoutMs: 2500,
retryLimit,
});
- logger.info("starting server");
+ logger.info("starting review fixture server");
+ logger.debug({ retryLimit }, "configured retry policy");
await server.start();
- logger.info(greeting.replace("{name}", "reviewer"));
+ logger.info(greeting.replace("{name}", "native reviewer"));
+
+ if (process.env.DEMO_FIXTURE_VERBOSE === "1") {
+ logger.debug("verbose review fixture mode enabled");
+ }
}
void boot();
diff --git a/apps/demo/src/utils/format.ts b/apps/demo/src/utils/stringFormat.ts
similarity index 100%
rename from apps/demo/src/utils/format.ts
rename to apps/demo/src/utils/stringFormat.ts
diff --git a/apps/demo/src/oldClient.ts b/apps/demo/src/apiClient.ts
similarity index 62%
rename from apps/demo/src/oldClient.ts
rename to apps/demo/src/apiClient.ts
index 18518fca1..87e0e2bea 100644
--- a/apps/demo/src/oldClient.ts
+++ b/apps/demo/src/apiClient.ts
@@ -1,15 +1,22 @@
-export interface ClientOptions {
- readonly baseUrl: string;
- readonly timeoutMs: number;
-}
-
-export function request(path: string, options: ClientOptions) {
- return fetch(options.baseUrl + path, {
- signal: AbortSignal.timeout(options.timeoutMs),
- });
+export interface ApiClientOptions {
+ readonly baseUrl: string;
+ readonly token: string;
+ readonly timeoutMs: number;
+}
+
+export async function request(path: string, options: ApiClientOptions) {
+ const response = await fetch(options.baseUrl + "/v2" + path, {
+ headers: {
+ Authorization: "Bearer " + options.token,
+ "X-Client": "native-review-debug",
+ },
+ signal: AbortSignal.timeout(options.timeoutMs),
+ });
+
+ if (!response.ok) {
+ throw new Error("Request failed: " + response.status);
+ }
+
+ return response.json();
}
-
-export function requestJson(path: string, options: ClientOptions) {
- return request(path, options).then((response) => response.json());
-}
diff --git a/apps/demo/src/features/flags.ts b/apps/demo/src/features/flags.ts
new file mode 100644
index 000000000..755df9762
--- /dev/null
+++ b/apps/demo/src/features/flags.ts
@@ -0,0 +1,29 @@
+export type FeatureState = "enabled" | "disabled" | "preview";
+
+export interface FeatureFlag {
+ readonly key: string;
+ readonly label: string;
+ readonly state: FeatureState;
+}
+
+export const reviewFixtureFlags: ReadonlyArray<FeatureFlag> = [
+ {
+ key: "native-file-headers",
+ label: "Native file headers",
+ state: "preview",
+ },
+ {
+ key: "word-diff-highlights",
+ label: "Word diff highlights",
+ state: "enabled",
+ },
+ {
+ key: "deleted-file-markers",
+ label: "Deleted file markers",
+ state: "enabled",
+ },
+];
+
+export function isEnabled(flag: FeatureFlag): boolean {
+ return flag.state !== "disabled";
+}
diff --git a/apps/demo/src/legacyReview.ts b/apps/demo/src/legacyReview.ts
deleted file mode 100644
index 9cf2f63dc..000000000
--- a/apps/demo/src/legacyReview.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-export const legacyReviewMode = true;
-
-export function createLegacyRows(lines: ReadonlyArray<string>) {
- return lines.map((line, index) => ({
- id: "legacy-" + index,
- lineNumber: index + 1,
- text: line,
- }));
-}
-
-export function renderLegacyHeader(path: string) {
- return {
- title: path,
- subtitle: "legacy renderer",
- icon: "blue-dot",
- };
-}
-
-export function shouldUseLegacyReview() {
- return legacyReviewMode;
-}
diff --git a/apps/demo/src/wordChanges.zig b/apps/demo/src/wordChanges.zig
index 6bfcc7e37..af359829c 100644
--- a/apps/demo/src/wordChanges.zig
+++ b/apps/demo/src/wordChanges.zig
@@ -1,18 +1,23 @@
const std = @import("std");
-const Allocator = std.heap.page_allocator;
+const GeneralPurposeAllocator = std.heap.GeneralPurposeAllocator;
const ArrayList = std.ArrayList;
pub fn main() !void {
+ var gpa = GeneralPurposeAllocator(.{}){};
+ defer _ = gpa.deinit();
+ const allocator = gpa.allocator();
+
const stdout_writer_instance = std.io.getStdOut().writer();
- try stdout_writer_instance.print("Hi You, {s}! Welcome to our application.", .{"Reviewer"});
+ try stdout_writer_instance.print("Hello There, {s}! Welcome to the updated application.", .{"Reviewer"});
- var list = ArrayList(i32).init(Allocator);
+ var list = ArrayList(i32).init(allocator);
defer list.deinit();
+ try list.append(42);
- const configuration_options = .{ .enable_logging = true, .max_buffer_size = 1024 };
+ const configuration_options = .{ .enable_logging = true, .max_buffer_size = 2048 };
_ = configuration_options;
}
diff --git a/apps/demo/assets/review-logo.png b/apps/demo/assets/review-logo.png
new file mode 100644
index 000000000..4628f44da
--- /dev/null
+++ b/apps/demo/assets/review-logo.png
Binary files /dev/null and b/apps/demo/assets/review-logo.png differ
diff --git a/apps/demo/scripts/review-fixture.sh b/apps/demo/scripts/review-fixture.sh
old mode 100644
new mode 100755`;
export const debugReviewDiffFixtures: ReadonlyArray<DebugReviewDiffFixture> = [
{
id: "states",
label: "States",
filename: "review-states.diff",
lineCount: DEBUG_REVIEW_STATES_DIFF.split("\n").length,
diff: DEBUG_REVIEW_STATES_DIFF,
},
{
id: "xl",
label: "XL",
filename: "08e6d4cfbfe55af83fe5fb6b9e75364f42f1f22f.patch",
lineCount: DEBUG_REVIEW_XL_DIFF.split("\n").length,
diff: DEBUG_REVIEW_XL_DIFF,
},
{
id: "small",
label: "Small",
@@ -0,0 +1,4 @@
// Generated from https://github.com/pingdotgg/t3code/commit/08e6d4cfbfe55af83fe5fb6b9e75364f42f1f22f.patch
// Keep this split from reviewDiffFixtures.ts so the fixture registry stays readable.
export const DEBUG_REVIEW_XL_DIFF =
'From 08e6d4cfbfe55af83fe5fb6b9e75364f42f1f22f Mon Sep 17 00:00:00 2001\nFrom: Julius Marminge <julius0216@outlook.com>\nDate: Wed, 29 Apr 2026 16:13:55 -0700\nSubject: [PATCH] feat: Multi-Provider support (#2277)\n\nCo-authored-by: Claude Opus 4.7 <noreply@anthropic.com>\nCo-authored-by: codex <codex@users.noreply.github.com>\n---\n apps/desktop/src/clientPersistence.test.ts | 1 +\n .../OrchestrationEngineHarness.integration.ts | 44 +-\n .../TestProviderAdapter.integration.ts | 17 +-\n .../integration/fixtures/providerRuntime.ts | 4 +-\n .../orchestrationEngine.integration.test.ts | 178 +-\n .../providerService.integration.test.ts | 37 +-\n .../git/Layers/ClaudeTextGeneration.test.ts | 311 +--\n .../src/git/Layers/ClaudeTextGeneration.ts | 55 +-\n .../git/Layers/CodexTextGeneration.test.ts | 528 +++--\n .../src/git/Layers/CodexTextGeneration.ts | 97 +-\n .../git/Layers/CursorTextGeneration.test.ts | 311 ++-\n .../src/git/Layers/CursorTextGeneration.ts | 56 +-\n .../git/Layers/OpenCodeTextGeneration.test.ts | 354 ++--\n .../src/git/Layers/OpenCodeTextGeneration.ts | 77 +-\n .../src/git/Layers/RoutingTextGeneration.ts | 104 -\n .../src/git/Layers/TextGenerationLive.test.ts | 117 ++\n .../src/git/Layers/TextGenerationLive.ts | 101 +\n apps/server/src/observability/Metrics.test.ts | 10 +-\n .../Layers/CheckpointReactor.test.ts | 60 +-\n .../Layers/OrchestrationEngine.test.ts | 51 +-\n .../Layers/ProjectionPipeline.test.ts | 33 +-\n .../Layers/ProjectionPipeline.ts | 1 +\n .../Layers/ProjectionSnapshotQuery.test.ts | 18 +-\n .../Layers/ProjectionSnapshotQuery.ts | 6 +\n .../Layers/ProviderCommandReactor.test.ts | 438 +++-\n .../Layers/ProviderCommandReactor.ts | 183 +-\n .../Layers/ProviderRuntimeIngestion.test.ts | 229 ++-\n .../Layers/ProviderRuntimeIngestion.ts | 6 +\n .../orchestration/commandInvariants.test.ts | 13 +-\n .../src/orchestration/decider.delete.test.ts | 5 +-\n .../decider.projectScripts.test.ts | 11 +-\n .../src/orchestration/projector.test.ts | 21 +-\n .../Layers/ProjectionRepositories.test.ts | 14 +-\n .../Layers/ProjectionThreadSessions.ts | 4 +\n .../Layers/ProviderSessionRuntime.ts | 5 +\n apps/server/src/persistence/Migrations.ts | 4 +\n .../027_028_ProviderInstanceIdColumns.test.ts | 74 +\n .../027_ProviderSessionRuntimeInstanceId.ts | 38 +\n .../028_ProjectionThreadSessionInstanceId.ts | 21 +\n .../Services/ProjectionThreadSessions.ts | 2 +\n .../Services/ProviderSessionRuntime.ts | 9 +\n .../src/provider/Drivers/ClaudeDriver.ts | 157 ++\n .../src/provider/Drivers/ClaudeHome.test.ts | 52 +\n .../server/src/provider/Drivers/ClaudeHome.ts | 43 +\n .../src/provider/Drivers/CodexDriver.ts | 171 ++\n .../provider/Drivers/CodexHomeLayout.test.ts | 209 ++\n .../src/provider/Drivers/CodexHomeLayout.ts | 263 +++\n .../src/provider/Drivers/CursorDriver.ts | 148 ++\n .../src/provider/Drivers/OpenCodeDriver.ts | 135 ++\n apps/server/src/provider/Errors.ts | 41 +\n .../src/provider/Layers/ClaudeAdapter.test.ts | 339 ++--\n .../src/provider/Layers/ClaudeAdapter.ts | 63 +-\n .../src/provider/Layers/ClaudeProvider.ts | 484 ++---\n .../src/provider/Layers/CodexAdapter.test.ts | 186 +-\n .../src/provider/Layers/CodexAdapter.ts | 65 +-\n .../src/provider/Layers/CodexProvider.ts | 99 +-\n .../provider/Layers/CodexSessionRuntime.ts | 61 +-\n .../src/provider/Layers/CursorAdapter.test.ts | 213 +-\n .../src/provider/Layers/CursorAdapter.ts | 73 +-\n .../provider/Layers/CursorProvider.test.ts | 159 +-\n .../src/provider/Layers/CursorProvider.ts | 665 ++++---\n .../provider/Layers/OpenCodeAdapter.test.ts | 286 ++-\n .../src/provider/Layers/OpenCodeAdapter.ts | 1770 +++++++++--------\n .../provider/Layers/OpenCodeProvider.test.ts | 119 +-\n .../src/provider/Layers/OpenCodeProvider.ts | 378 ++--\n .../Layers/ProviderAdapterRegistry.test.ts | 148 +-\n .../Layers/ProviderAdapterRegistry.ts | 133 +-\n .../provider/Layers/ProviderEventLoggers.ts | 83 +\n .../ProviderInstanceRegistryHydration.ts | 176 ++\n .../ProviderInstanceRegistryLive.test.ts | 357 ++++\n .../Layers/ProviderInstanceRegistryLive.ts | 434 ++++\n .../provider/Layers/ProviderRegistry.test.ts | 850 ++++++--\n .../src/provider/Layers/ProviderRegistry.ts | 546 +++--\n .../provider/Layers/ProviderService.test.ts | 583 ++++--\n .../src/provider/Layers/ProviderService.ts | 418 +++-\n .../Layers/ProviderSessionDirectory.test.ts | 25 +-\n .../Layers/ProviderSessionDirectory.ts | 24 +-\n .../Layers/ProviderSessionReaper.test.ts | 31 +-\n .../Layers/scopedSafeTeardown.test.ts | 94 +\n .../src/provider/Layers/scopedSafeTeardoLine truncated
@@ -0,0 +1,405 @@
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 type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewDiffModule";
import type { NativeReviewDiffFile, NativeReviewDiffLanguage } from "./nativeReviewDiffParser";
export type NativeReviewDiffHighlightScheme = "light" | "dark";
export type NativeReviewDiffHighlightEngine = "native" | "javascript";
export interface NativeReviewDiffHighlighterHandle {
readonly engine: NativeReviewDiffHighlightEngine;
readonly tokenize: (
code: string,
options: { readonly lang: NativeReviewDiffLanguage; readonly theme: string },
) => ReadonlyArray<ReadonlyArray<NativeReviewDiffToken>>;
}
interface NativeReviewDiffLineRow extends NativeReviewDiffRow {
readonly kind: "line";
readonly fileId: string;
readonly content: string;
}
export interface NativeReviewDiffTokenChunk {
readonly chunkIndex: number;
readonly fileId: string;
readonly filePath: string;
readonly language: NativeReviewDiffLanguage;
readonly lineCount: number;
readonly durationMs: number;
readonly tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>>;
}
export interface StreamNativeReviewDiffTokenInput {
readonly rows: ReadonlyArray<NativeReviewDiffRow>;
readonly files: ReadonlyArray<NativeReviewDiffFile>;
readonly scheme: NativeReviewDiffHighlightScheme;
readonly engine?: NativeReviewDiffHighlightEngine;
readonly chunkSize?: number;
readonly signal?: AbortSignal;
readonly onChunk: (chunk: NativeReviewDiffTokenChunk) => void;
}
export interface HighlightNativeReviewDiffVisibleRowsInput {
readonly rows: ReadonlyArray<NativeReviewDiffRow>;
readonly files: ReadonlyArray<NativeReviewDiffFile>;
readonly scheme: NativeReviewDiffHighlightScheme;
readonly engine?: NativeReviewDiffHighlightEngine;
readonly firstRowIndex: number;
readonly lastRowIndex: number;
readonly overscanRows?: number;
readonly maxRows?: number;
readonly alreadyHighlightedRowIds?: ReadonlySet<string>;
readonly signal?: AbortSignal;
}
const NATIVE_REVIEW_DIFF_HIGHLIGHT_CHUNK_SIZE = 500;
const NATIVE_REVIEW_DIFF_VISIBLE_OVERSCAN_ROWS = 160;
const NATIVE_REVIEW_DIFF_VISIBLE_MAX_ROWS = 360;
const NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME = {
dark: "t3-pierre-dark",
light: "t3-pierre-light",
} as const;
const PIERRE_LIGHT_SHIKI_THEME = {
name: NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME.light,
type: "light" as const,
fg: "#070707",
bg: "#ffffff",
settings: [
{ settings: { foreground: "#070707", background: "#ffffff" } },
{ scope: "comment, punctuation.definition.comment", settings: { foreground: "#84848A" } },
{
scope: "keyword, storage, storage.type, keyword.operator.expression",
settings: { foreground: "#FC2B73" },
},
{
scope: "entity.name.function, support.function, meta.function-call",
settings: { foreground: "#7B43F8" },
},
{
scope: "entity.name.type, support.type, support.class",
settings: { foreground: "#C635E4" },
},
{
scope: "string, constant.character, punctuation.definition.string",
settings: { foreground: "#199F43" },
},
{
scope: "constant.numeric, constant.language, constant.other",
settings: { foreground: "#1CA1C7" },
},
{
scope: "variable.parameter, variable.other.readwrite, meta.object-literal.key",
settings: { foreground: "#D47628" },
},
{
scope: "entity.name.tag, support.class.component",
settings: { foreground: "#199F43" },
},
{
scope: "punctuation, meta.brace, meta.delimiter",
settings: { foreground: "#79797F" },
},
{ scope: "invalid", settings: { foreground: "#D52C36" } },
],
};
const PIERRE_DARK_SHIKI_THEME = {
name: NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME.dark,
type: "dark" as const,
fg: "#adadb1",
bg: "#0a0a0a",
settings: [
{ settings: { foreground: "#adadb1", background: "#0a0a0a" } },
{ scope: "comment, punctuation.definition.comment", settings: { foreground: "#84848A" } },
{
scope: "keyword, storage, storage.type, keyword.operator.expression",
settings: { foreground: "#FF678D" },
},
{
scope: "entity.name.function, support.function, meta.function-call",
settings: { foreground: "#9D6AFB" },
},
{
scope: "entity.name.type, support.type, support.class",
settings: { foreground: "#D568EA" },
},
{
scope: "string, constant.character, punctuation.definition.string",
settings: { foreground: "#5ECC71" },
},
{
scope: "constant.numeric, constant.language, constant.other",
settings: { foreground: "#68CDF2" },
},
{
scope: "variable.parameter, variable.other.readwrite, meta.object-literal.key",
settings: { foreground: "#FFA359" },
},
{
scope: "entity.name.tag, support.class.component",
settings: { foreground: "#5ECC71" },
},
{
scope: "punctuation, meta.brace, meta.delimiter",
settings: { foreground: "#79797F" },
},
{ scope: "invalid", settings: { foreground: "#FF6762" } },
],
};
const NATIVE_REVIEW_DIFF_SHIKI_THEMES = [
PIERRE_LIGHT_SHIKI_THEME,
PIERRE_DARK_SHIKI_THEME,
] satisfies Parameters<typeof createHighlighterCore>[0]["themes"];
const NATIVE_REVIEW_DIFF_LANGUAGES = [
bashLanguage,
diffLanguage,
javascriptLanguage,
jsonLanguage,
jsxLanguage,
tsxLanguage,
typescriptLanguage,
yamlLanguage,
] satisfies Parameters<typeof createHighlighterCore>[0]["langs"];
let nativeHighlighterPromise: Promise<NativeReviewDiffHighlighterHandle> | null = null;
let javascriptHighlighterPromise: Promise<NativeReviewDiffHighlighterHandle> | null = null;
function waitForNextFrame(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, 0));
}
function normalizeTokens(
tokenLines: ReadonlyArray<ReadonlyArray<{ content: string; color?: string; fontStyle?: number }>>,
): ReadonlyArray<ReadonlyArray<NativeReviewDiffToken>> {
return tokenLines.map((line) =>
line.map((token) => ({
content: token.content,
color: token.color ?? null,
fontStyle: token.fontStyle ?? null,
})),
);
}
async function createNativeReviewDiffHighlighter(): Promise<NativeReviewDiffHighlighterHandle> {
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: NATIVE_REVIEW_DIFF_LANGUAGES,
themes: NATIVE_REVIEW_DIFF_SHIKI_THEMES,
engine: nativeEngineModule.createNativeEngine(),
});
return {
engine: "native",
tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),
};
}
async function createJavascriptReviewDiffHighlighter(): Promise<NativeReviewDiffHighlighterHandle> {
const highlighter: HighlighterCore = await createHighlighterCore({
langs: NATIVE_REVIEW_DIFF_LANGUAGES,
themes: NATIVE_REVIEW_DIFF_SHIKI_THEMES,
engine: createJavaScriptRegexEngine(),
});
return {
engine: "javascript",
tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),
};
}
export async function getNativeReviewDiffHighlighter(
engine: NativeReviewDiffHighlightEngine = "native",
): Promise<NativeReviewDiffHighlighterHandle> {
if (engine === "javascript") {
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
return javascriptHighlighterPromise;
}
nativeHighlighterPromise ??= createNativeReviewDiffHighlighter().catch((error: unknown) => {
console.warn("[debug-native-diff] native highlighter unavailable", {
error: error instanceof Error ? error.message : String(error),
});
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
return javascriptHighlighterPromise;
});
return nativeHighlighterPromise;
}
function isHighlightableLineRow(row: NativeReviewDiffRow): row is NativeReviewDiffLineRow {
return row.kind === "line" && typeof row.fileId === "string" && typeof row.content === "string";
}
function groupLineRowsByFileId(rows: ReadonlyArray<NativeReviewDiffRow>) {
const rowsByFileId = new Map<string, NativeReviewDiffLineRow[]>();
for (const row of rows) {
if (!isHighlightableLineRow(row)) {
continue;
}
const fileRows = rowsByFileId.get(row.fileId) ?? [];
fileRows.push(row);
rowsByFileId.set(row.fileId, fileRows);
}
return rowsByFileId;
}
function createFileMap(files: ReadonlyArray<NativeReviewDiffFile>) {
return new Map(files.map((file) => [file.id, file]));
}
function clampRowIndex(index: number, rows: ReadonlyArray<NativeReviewDiffRow>) {
if (rows.length === 0) {
return 0;
}
return Math.min(rows.length - 1, Math.max(0, Math.floor(index)));
}
function makePlainTokenFallback(
row: NativeReviewDiffLineRow,
): ReadonlyArray<NativeReviewDiffToken> {
return [{ content: row.content || " ", color: null, fontStyle: null }];
}
export async function highlightNativeReviewDiffVisibleRows(
input: HighlightNativeReviewDiffVisibleRowsInput,
): Promise<{
readonly engine: NativeReviewDiffHighlightEngine;
readonly tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>>;
readonly rowCount: number;
readonly durationMs: number;
}> {
const highlighter = await getNativeReviewDiffHighlighter(input.engine ?? "native");
if (input.signal?.aborted) {
return { engine: highlighter.engine, tokensByRowId: {}, rowCount: 0, durationMs: 0 };
}
const startedAt = performance.now();
const theme = NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME[input.scheme];
const fileMap = createFileMap(input.files);
const overscanRows = input.overscanRows ?? NATIVE_REVIEW_DIFF_VISIBLE_OVERSCAN_ROWS;
const maxRows = input.maxRows ?? NATIVE_REVIEW_DIFF_VISIBLE_MAX_ROWS;
const startIndex = clampRowIndex(input.firstRowIndex - overscanRows, input.rows);
const endIndex = clampRowIndex(input.lastRowIndex + overscanRows, input.rows);
const selectedRows: NativeReviewDiffLineRow[] = [];
for (
let rowIndex = startIndex;
rowIndex <= endIndex && selectedRows.length < maxRows;
rowIndex += 1
) {
const row = input.rows[rowIndex];
if (
row &&
isHighlightableLineRow(row) &&
!input.alreadyHighlightedRowIds?.has(row.id) &&
fileMap.has(row.fileId)
) {
selectedRows.push(row);
}
}
const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
let segmentRows: NativeReviewDiffLineRow[] = [];
let segmentFile: NativeReviewDiffFile | undefined;
const flushSegment = () => {
if (!segmentFile || segmentRows.length === 0 || input.signal?.aborted) {
segmentRows = [];
segmentFile = undefined;
return;
}
const code = segmentRows.map((row) => row.content).join("\n");
const tokenLines = highlighter.tokenize(code, { lang: segmentFile.language, theme });
segmentRows.forEach((row, rowIndex) => {
tokensByRowId[row.id] = tokenLines[rowIndex] ?? makePlainTokenFallback(row);
});
segmentRows = [];
segmentFile = undefined;
};
for (const row of selectedRows) {
const file = fileMap.get(row.fileId);
if (!file) {
continue;
}
if (segmentFile && segmentFile.id !== file.id) {
flushSegment();
}
segmentFile = file;
segmentRows.push(row);
}
flushSegment();
return {
engine: highlighter.engine,
tokensByRowId,
rowCount: selectedRows.length,
durationMs: Math.round(performance.now() - startedAt),
};
}
export async function streamNativeReviewDiffTokens(
input: StreamNativeReviewDiffTokenInput,
): Promise<NativeReviewDiffHighlightEngine> {
const highlighter = await getNativeReviewDiffHighlighter(input.engine ?? "native");
const rowsByFileId = groupLineRowsByFileId(input.rows);
const theme = NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME[input.scheme];
const chunkSize = input.chunkSize ?? NATIVE_REVIEW_DIFF_HIGHLIGHT_CHUNK_SIZE;
let chunkIndex = 0;
for (const file of input.files) {
const fileRows = rowsByFileId.get(file.id) ?? [];
for (let startIndex = 0; startIndex < fileRows.length; startIndex += chunkSize) {
if (input.signal?.aborted) {
return highlighter.engine;
}
const startedAt = performance.now();
const chunkRows = fileRows.slice(startIndex, startIndex + chunkSize);
const code = chunkRows.map((row) => row.content).join("\n");
const tokenLines = highlighter.tokenize(code, { lang: file.language, theme });
const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
chunkRows.forEach((row, rowIndex) => {
tokensByRowId[row.id] = tokenLines[rowIndex] ?? makePlainTokenFallback(row);
});
input.onChunk({
chunkIndex,
fileId: file.id,
filePath: file.path,
language: file.language,
lineCount: chunkRows.length,
durationMs: Math.round(performance.now() - startedAt),
tokensByRowId,
});
chunkIndex += 1;
await waitForNextFrame();
}
}
return highlighter.engine;
}
@@ -0,0 +1,69 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const expoModulesCoreMocks = vi.hoisted(() => ({
requireNativeViewManager: vi.fn(),
}));
const nativeView = () => null;
const originalExpo = globalThis.expo;
function setExpoViewConfigAvailable() {
globalThis.expo = {
getViewConfig: vi.fn().mockReturnValue({ validAttributes: {}, directEventTypes: {} }),
} as unknown as typeof globalThis.expo;
}
vi.mock("expo-modules-core", () => ({
requireNativeViewManager: expoModulesCoreMocks.requireNativeViewManager,
}));
describe("resolveNativeReviewDiffView", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.resetModules();
globalThis.expo = undefined as unknown as typeof globalThis.expo;
});
afterEach(() => {
globalThis.expo = originalExpo;
});
it("returns null when the native review diff view config is unavailable", async () => {
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffModule");
expect(resolveNativeReviewDiffView()).toBeNull();
expect(expoModulesCoreMocks.requireNativeViewManager).not.toHaveBeenCalled();
});
it("returns the native review diff view when the view config is installed", async () => {
setExpoViewConfigAvailable();
expoModulesCoreMocks.requireNativeViewManager.mockReturnValue(nativeView);
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffModule");
expect(resolveNativeReviewDiffView()).toBe(nativeView);
expect(expoModulesCoreMocks.requireNativeViewManager).toHaveBeenCalledWith(
"T3ReviewDiffSurface",
);
});
it("does not fall back to stale legacy native review diff view names", async () => {
globalThis.expo = {
getViewConfig: vi.fn().mockImplementation((moduleName: string) => {
if (moduleName === "T3ReviewDiffView") {
return { validAttributes: {}, directEventTypes: {} };
}
return null;
}),
} as unknown as typeof globalThis.expo;
expoModulesCoreMocks.requireNativeViewManager.mockReturnValue(nativeView);
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffModule");
expect(resolveNativeReviewDiffView()).toBeNull();
expect(expoModulesCoreMocks.requireNativeViewManager).not.toHaveBeenCalled();
});
it("returns null when the view manager cannot be required", async () => {
setExpoViewConfigAvailable();
expoModulesCoreMocks.requireNativeViewManager.mockImplementation(() => {
throw new Error("boom");
});
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffModule");
expect(resolveNativeReviewDiffView()).toBeNull();
});
});
@@ -0,0 +1,145 @@
import type { ComponentType } from "react";
import type { NativeSyntheticEvent, ViewProps } from "react-native";
import { requireNativeViewManager } from "expo-modules-core";
const NATIVE_REVIEW_DIFF_MODULE_NAME = "T3ReviewDiffSurface";
interface ExpoGlobalWithViewConfig {
readonly expo?: {
getViewConfig?: (moduleName: string, viewName?: string) => unknown;
};
}
export interface NativeReviewDiffRow {
readonly kind: "file" | "hunk" | "line" | "notice";
readonly id: string;
readonly fileId?: string;
readonly filePath?: string;
readonly previousPath?: string | null;
readonly changeType?:
| "modified"
| "new"
| "deleted"
| "renamed"
| "rename-pure"
| "rename-changed";
readonly additions?: number;
readonly deletions?: number;
readonly text?: string;
readonly content?: string;
readonly change?: "context" | "add" | "delete";
readonly oldLineNumber?: number | null;
readonly newLineNumber?: number | null;
readonly wordDiffRanges?: ReadonlyArray<NativeReviewDiffWordDiffRange>;
}
export interface NativeReviewDiffWordDiffRange {
readonly start: number;
readonly end: number;
}
export interface NativeReviewDiffToken {
readonly content: string;
readonly color: string | null;
readonly fontStyle: number | null;
}
export interface NativeReviewDiffTheme {
readonly background: string;
readonly text: string;
readonly mutedText: string;
readonly headerBackground: string;
readonly border: string;
readonly hunkBackground: string;
readonly hunkText: string;
readonly addBackground: string;
readonly deleteBackground: string;
readonly addBar: string;
readonly deleteBar: string;
readonly addText: string;
readonly deleteText: string;
}
export interface NativeReviewDiffStyle {
readonly rowHeight?: number;
readonly contentWidth?: number;
readonly changeBarWidth?: number;
readonly gutterWidth?: number;
readonly codePadding?: number;
readonly textVerticalInset?: number;
readonly fileHeaderHeight?: number;
readonly fileHeaderHorizontalMargin?: number;
readonly fileHeaderVerticalMargin?: number;
readonly fileHeaderCornerRadius?: number;
readonly fileHeaderHorizontalPadding?: number;
readonly fileHeaderPathRightPadding?: number;
readonly fileHeaderCountColumnWidth?: number;
readonly fileHeaderCountGap?: number;
readonly codeFontSize?: number;
readonly codeFontWeight?: string;
readonly lineNumberFontSize?: number;
readonly lineNumberFontWeight?: string;
readonly hunkFontSize?: number;
readonly hunkFontWeight?: string;
readonly fileHeaderFontSize?: number;
readonly fileHeaderFontWeight?: string;
readonly fileHeaderMetaFontSize?: number;
readonly fileHeaderMetaFontWeight?: string;
readonly fileHeaderSubtextFontSize?: number;
readonly fileHeaderSubtextFontWeight?: string;
readonly fileHeaderStatusFontSize?: number;
readonly fileHeaderStatusFontWeight?: string;
readonly emptyStateFontSize?: number;
readonly emptyStateFontWeight?: string;
}
export interface NativeReviewDiffViewProps extends ViewProps {
readonly rowsJson: string;
readonly tokensJson?: string;
readonly tokensPatchJson?: string;
readonly tokensResetKey?: string;
readonly collapsedFileIdsJson?: string;
readonly viewedFileIdsJson?: string;
readonly appearanceScheme: "light" | "dark";
readonly themeJson: string;
readonly styleJson?: string;
readonly rowHeight: number;
readonly contentWidth: number;
readonly onDebug?: (event: NativeSyntheticEvent<Record<string, unknown>>) => void;
readonly onToggleFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
readonly onToggleViewedFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
}
let cachedNativeReviewDiffView: ComponentType<NativeReviewDiffViewProps> | undefined;
let cachedNativeReviewDiffModuleName: typeof NATIVE_REVIEW_DIFF_MODULE_NAME | undefined;
function getExpoViewConfig(moduleName: string) {
return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
moduleName,
);
}
export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffViewProps> | null {
if (cachedNativeReviewDiffView) {
return cachedNativeReviewDiffView;
}
if (getExpoViewConfig(NATIVE_REVIEW_DIFF_MODULE_NAME) == null) {
return null;
}
try {
cachedNativeReviewDiffView = requireNativeViewManager<NativeReviewDiffViewProps>(
NATIVE_REVIEW_DIFF_MODULE_NAME,
);
} catch {
return null;
}
cachedNativeReviewDiffModuleName = NATIVE_REVIEW_DIFF_MODULE_NAME;
return cachedNativeReviewDiffView ?? null;
}
export function getResolvedNativeReviewDiffModuleName() {
return cachedNativeReviewDiffModuleName ?? null;
}
@@ -0,0 +1,156 @@
import { describe, expect, it } from "vitest";
import { parseNativeReviewDiffFixture } from "./nativeReviewDiffParser";
describe("parseNativeReviewDiffFixture", () => {
it("adds word diff ranges to paired changed lines", () => {
const parsed = parseNativeReviewDiffFixture({
id: "states",
label: "States",
filename: "states.diff",
lineCount: 9,
diff: [
"diff --git a/main.ts b/main.ts",
"index 1111111..2222222 100644",
"--- a/main.ts",
"+++ b/main.ts",
"@@ -1,3 +1,3 @@",
" const stable = true;",
'-const label = "Before value";',
'+const label = "After value";',
" const done = true;",
].join("\n"),
});
const deletion = parsed.rows.find((row) => row.change === "delete");
const addition = parsed.rows.find((row) => row.change === "add");
expect(deletion?.wordDiffRanges).toEqual([{ start: 15, end: 21 }]);
expect(addition?.wordDiffRanges).toEqual([{ start: 15, end: 20 }]);
});
it("does not add word diff ranges to unpaired created lines", () => {
const parsed = parseNativeReviewDiffFixture({
id: "states",
label: "States",
filename: "states.diff",
lineCount: 9,
diff: [
"diff --git a/new.ts b/new.ts",
"new file mode 100644",
"index 0000000..2222222",
"--- /dev/null",
"+++ b/new.ts",
"@@ -0,0 +1,2 @@",
'+const label = "After value";',
"+export default label;",
].join("\n"),
});
expect(parsed.rows.filter((row) => row.kind === "line")).toHaveLength(2);
expect(parsed.rows.every((row) => row.wordDiffRanges === undefined)).toBe(true);
});
it("trims whitespace from word diff range edges", () => {
const parsed = parseNativeReviewDiffFixture({
id: "states",
label: "States",
filename: "states.diff",
lineCount: 8,
diff: [
"diff --git a/main.tsx b/main.tsx",
"index 1111111..2222222 100644",
"--- a/main.tsx",
"+++ b/main.tsx",
"@@ -1,2 +1,2 @@",
"- const status = disabled;",
"+ const status = enabled;",
].join("\n"),
});
const deletion = parsed.rows.find((row) => row.change === "delete");
const addition = parsed.rows.find((row) => row.change === "add");
expect(deletion?.wordDiffRanges?.[0]?.start).toBeGreaterThanOrEqual(4);
expect(addition?.wordDiffRanges?.[0]?.start).toBeGreaterThanOrEqual(4);
});
it("keeps word diff ranges aligned to exact replacement columns", () => {
const parsed = parseNativeReviewDiffFixture({
id: "states",
label: "States",
filename: "states.diff",
lineCount: 12,
diff: [
"diff --git a/main.ts b/main.ts",
"index 1111111..2222222 100644",
"--- a/main.ts",
"+++ b/main.ts",
"@@ -1,5 +1,5 @@",
"-const retryLimit = 2;",
"+const retryLimit = 4;",
'-const greeting = greeting.replace("{name}", "reviewer");',
'+const greeting = greeting.replace("{name}", "native reviewer");',
].join("\n"),
});
const changedRows = parsed.rows.filter((row) => row.kind === "line");
expect(changedRows[0]?.wordDiffRanges).toEqual([{ start: 19, end: 20 }]);
expect(changedRows[1]?.wordDiffRanges).toEqual([{ start: 19, end: 20 }]);
expect(changedRows[2]?.wordDiffRanges).toBeUndefined();
expect(changedRows[3]?.wordDiffRanges).toEqual([{ start: 45, end: 51 }]);
});
it("suppresses noisy word diff ranges for unrelated replacement lines", () => {
const parsed = parseNativeReviewDiffFixture({
id: "states",
label: "States",
filename: "states.diff",
lineCount: 8,
diff: [
"diff --git a/main.tsx b/main.tsx",
"index 1111111..2222222 100644",
"--- a/main.tsx",
"+++ b/main.tsx",
"@@ -1,2 +1,2 @@",
'- case "file-header":',
"+ const status = enabled;",
].join("\n"),
});
expect(parsed.rows.every((row) => row.wordDiffRanges === undefined)).toBe(true);
});
it("adds notice rows for pure renames and metadata-only changes", () => {
const parsed = parseNativeReviewDiffFixture({
id: "states",
label: "States",
filename: "states.diff",
lineCount: 16,
diff: [
"diff --git a/src/oldName.ts b/src/newName.ts",
"similarity index 100%",
"rename from src/oldName.ts",
"rename to src/newName.ts",
"diff --git a/scripts/run.sh b/scripts/run.sh",
"old mode 100644",
"new mode 100755",
"diff --git a/assets/logo.png b/assets/logo.png",
"new file mode 100644",
"index 000000000..4628f44da",
"--- /dev/null",
"+++ b/assets/logo.png",
"Binary files /dev/null and b/assets/logo.png differ",
].join("\n"),
});
const noticeTexts = parsed.rows.filter((row) => row.kind === "notice").map((row) => row.text);
expect(noticeTexts).toEqual([
"This file was renamed without modifications.",
"File mode changed from 100644 to 100755.",
"Unsupported binary format. Diff contents are not available.",
]);
});
});
@@ -0,0 +1,549 @@
import {
debugReviewDiffFixtures,
type DebugReviewDiffFixture,
type DebugReviewDiffFixtureId,
} from "../fixtures/reviewDiffFixtures";
import { computeWordAltDiffRanges } from "../../review/reviewWordDiffs";
import type { NativeReviewDiffRow } from "./nativeReviewDiffModule";
const NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT = 4;
const NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE = 0.45;
export type NativeReviewDiffLanguage =
| "bash"
| "diff"
| "javascript"
| "json"
| "jsx"
| "tsx"
| "typescript"
| "yaml";
export interface NativeReviewDiffFile {
readonly id: string;
readonly path: string;
readonly language: NativeReviewDiffLanguage;
readonly additions: number;
readonly deletions: number;
}
export interface NativeReviewDiffParsedFixture {
readonly fixtureId: DebugReviewDiffFixtureId;
readonly rows: ReadonlyArray<NativeReviewDiffRow>;
readonly files: ReadonlyArray<NativeReviewDiffFile>;
readonly additions: number;
readonly deletions: number;
}
interface NativeReviewDiffFileParseState {
readonly path: string;
readonly language: NativeReviewDiffLanguage;
readonly additions: number;
readonly deletions: number;
readonly hasRenderableRows: boolean;
readonly isBinary: boolean;
readonly oldMode: string | null;
readonly newMode: string | null;
}
function getDiffPathFromHeader(line: string): string {
const match = line.match(/^diff --git a\/(.+) b\/(.+)$/);
return match?.[2] ?? line.replace(/^diff --git /, "");
}
function getDiffPreviousPathFromHeader(line: string): string | null {
const match = line.match(/^diff --git a\/(.+) b\/(.+)$/);
return match?.[1] ?? null;
}
function parseDiffPath(line: string, prefix: "--- " | "+++ "): string | null {
if (!line.startsWith(prefix)) {
return null;
}
const rawPath = line.slice(prefix.length).trim();
if (rawPath === "/dev/null") {
return null;
}
return rawPath.replace(/^[ab]\//, "");
}
function resolveChangeType(input: {
readonly previousPath: string | null;
readonly nextPath: string | null;
}): NativeReviewDiffRow["changeType"] {
if (!input.previousPath && input.nextPath) {
return "new";
}
if (input.previousPath && !input.nextPath) {
return "deleted";
}
if (input.previousPath && input.nextPath && input.previousPath !== input.nextPath) {
return "renamed";
}
return "modified";
}
function resolveFileHeaderChangeType(input: {
readonly previousPath: string | null | undefined;
readonly nextPath: string | null | undefined;
readonly currentChangeType: NativeReviewDiffRow["changeType"];
readonly additions: number;
readonly deletions: number;
}): NativeReviewDiffRow["changeType"] {
if (input.currentChangeType === "new" || input.currentChangeType === "deleted") {
return input.currentChangeType;
}
if (input.previousPath && input.nextPath && input.previousPath !== input.nextPath) {
return input.additions + input.deletions === 0 ? "rename-pure" : "rename-changed";
}
return resolveChangeType({
nextPath: input.nextPath ?? null,
previousPath: input.previousPath ?? null,
});
}
function getLanguageForPath(filePath: string): NativeReviewDiffLanguage {
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 parseFileModeLine(line: string, prefix: "old mode " | "new mode "): string | null {
if (!line.startsWith(prefix)) {
return null;
}
return line.slice(prefix.length).trim() || null;
}
function createNoticeRow(input: {
readonly fileId: string;
readonly message: string;
readonly suffix: string;
}): NativeReviewDiffRow {
return {
kind: "notice",
id: `${input.fileId}:notice:${input.suffix}`,
fileId: input.fileId,
text: input.message,
};
}
function getNoticeRowForFile(input: {
readonly row: NativeReviewDiffRow;
readonly file: NativeReviewDiffFileParseState | undefined;
}): NativeReviewDiffRow | null {
const { file, row } = input;
if (!file || row.kind !== "file" || !row.fileId) {
return null;
}
if (file.isBinary) {
return createNoticeRow({
fileId: row.fileId,
message: "Unsupported binary format. Diff contents are not available.",
suffix: "binary",
});
}
if (file.oldMode && file.newMode && file.oldMode !== file.newMode && !file.hasRenderableRows) {
return createNoticeRow({
fileId: row.fileId,
message: `File mode changed from ${file.oldMode} to ${file.newMode}.`,
suffix: "mode",
});
}
if (row.changeType === "rename-pure" && !file.hasRenderableRows) {
return createNoticeRow({
fileId: row.fileId,
message: "This file was renamed without modifications.",
suffix: "rename",
});
}
return null;
}
function isChangedLine(row: NativeReviewDiffRow | undefined, change: "add" | "delete") {
return row?.kind === "line" && row.change === change && typeof row.content === "string";
}
function trimWordDiffRanges(
content: string,
ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
): NonNullable<NativeReviewDiffRow["wordDiffRanges"]> {
return ranges.flatMap((range) => {
let start = Math.max(0, range.start);
let end = Math.min(content.length, range.end);
while (start < end && /\s/.test(content[start] ?? "")) {
start += 1;
}
while (end > start && /\s/.test(content[end - 1] ?? "")) {
end -= 1;
}
return end > start ? [{ start, end }] : [];
});
}
function nonWhitespaceLength(value: string) {
return value.replace(/\s/g, "").length;
}
function getRangeCoverage(
content: string,
ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
) {
const meaningfulLength = nonWhitespaceLength(content);
if (meaningfulLength === 0) {
return 1;
}
const highlightedLength = ranges.reduce(
(total, range) => total + nonWhitespaceLength(content.slice(range.start, range.end)),
0,
);
return highlightedLength / meaningfulLength;
}
function shouldUseWordDiffRanges(
content: string,
ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
) {
if (ranges.length === 0 || ranges.length > NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT) {
return false;
}
return getRangeCoverage(content, ranges) <= NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE;
}
function addNativeWordDiffRanges(rows: ReadonlyArray<NativeReviewDiffRow>) {
const nextRows = [...rows];
let index = 0;
while (index < nextRows.length) {
const deletedRowIndexes: number[] = [];
const addedRowIndexes: number[] = [];
const fileId = nextRows[index]?.fileId;
while (isChangedLine(nextRows[index], "delete") && nextRows[index]?.fileId === fileId) {
deletedRowIndexes.push(index);
index += 1;
}
if (deletedRowIndexes.length === 0) {
index += 1;
continue;
}
while (isChangedLine(nextRows[index], "add") && nextRows[index]?.fileId === fileId) {
addedRowIndexes.push(index);
index += 1;
}
if (addedRowIndexes.length === 0) {
continue;
}
const pairCount = Math.min(deletedRowIndexes.length, addedRowIndexes.length);
for (let pairIndex = 0; pairIndex < pairCount; pairIndex += 1) {
const deletedRowIndex = deletedRowIndexes[pairIndex];
const addedRowIndex = addedRowIndexes[pairIndex];
const deletedRow = nextRows[deletedRowIndex];
const addedRow = nextRows[addedRowIndex];
if (!deletedRow?.content || !addedRow?.content) {
continue;
}
const ranges = computeWordAltDiffRanges({
deletionLine: deletedRow.content,
additionLine: addedRow.content,
});
const deletionRanges = trimWordDiffRanges(deletedRow.content, ranges.deletion);
const additionRanges = trimWordDiffRanges(addedRow.content, ranges.addition);
if (shouldUseWordDiffRanges(deletedRow.content, deletionRanges)) {
nextRows[deletedRowIndex] = { ...deletedRow, wordDiffRanges: deletionRanges };
}
if (shouldUseWordDiffRanges(addedRow.content, additionRanges)) {
nextRows[addedRowIndex] = { ...addedRow, wordDiffRanges: additionRanges };
}
}
}
return nextRows;
}
export function parseNativeReviewDiffFixture(
fixture: DebugReviewDiffFixture,
): NativeReviewDiffParsedFixture {
const startedAt = performance.now();
let rows: NativeReviewDiffRow[] = [];
const files = new Map<string, NativeReviewDiffFileParseState>();
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, previousPath: string | null): string {
const fileId = `file:${files.size}:${filePath}`;
const language = getLanguageForPath(filePath);
files.set(fileId, {
path: filePath,
language,
additions: 0,
deletions: 0,
hasRenderableRows: false,
isBinary: false,
oldMode: null,
newMode: null,
});
rows.push({
kind: "file",
id: `${fileId}:header`,
fileId,
filePath,
previousPath,
changeType: resolveChangeType({ nextPath: filePath, previousPath }),
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),
getDiffPreviousPathFromHeader(rawLine),
);
currentOldLine = null;
currentNewLine = null;
continue;
}
if (!currentFileId) {
continue;
}
const previousPath = parseDiffPath(rawLine, "--- ");
if (previousPath !== null || rawLine === "--- /dev/null") {
rows = rows.map((row) =>
row.id === `${currentFileId}:header`
? {
...row,
previousPath,
changeType: resolveChangeType({
nextPath: row.filePath ?? null,
previousPath,
}),
}
: row,
);
continue;
}
const nextPath = parseDiffPath(rawLine, "+++ ");
if (nextPath !== null || rawLine === "+++ /dev/null") {
rows = rows.map((row) =>
row.id === `${currentFileId}:header`
? {
...row,
filePath: nextPath ?? row.filePath,
changeType: resolveChangeType({
nextPath,
previousPath: row.previousPath ?? null,
}),
}
: row,
);
continue;
}
const oldMode = parseFileModeLine(rawLine, "old mode ");
if (oldMode !== null) {
const file = files.get(currentFileId);
if (file) {
files.set(currentFileId, { ...file, oldMode });
}
continue;
}
const newMode = parseFileModeLine(rawLine, "new mode ");
if (newMode !== null) {
const file = files.get(currentFileId);
if (file) {
files.set(currentFileId, { ...file, newMode });
}
continue;
}
if (rawLine.startsWith("Binary files ")) {
const file = files.get(currentFileId);
if (file) {
files.set(currentFileId, { ...file, isBinary: true });
}
continue;
}
if (rawLine.startsWith("@@ ")) {
const file = files.get(currentFileId);
if (file) {
files.set(currentFileId, { ...file, hasRenderableRows: true });
}
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;
}
const marker = rawLine[0];
if (marker !== " " && marker !== "+" && marker !== "-") {
continue;
}
const file = files.get(currentFileId);
if (!file) {
continue;
}
const change = marker === "+" ? "add" : marker === "-" ? "delete" : "context";
rows.push({
kind: "line",
id: `${currentFileId}:line:${index}`,
fileId: currentFileId,
change,
oldLineNumber: change === "add" ? null : currentOldLine,
newLineNumber: change === "delete" ? null : currentNewLine,
content: rawLine.slice(1),
});
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;
}
rows = addNativeWordDiffRanges(rows);
const fileSummaries = Array.from(files, ([id, file]) => ({
id,
path: file.path,
language: file.language,
additions: file.additions,
deletions: file.deletions,
}));
const fileSummaryByPath = new Map(fileSummaries.map((file) => [file.path, file]));
const rowsWithFileStats = rows.map((row): NativeReviewDiffRow => {
if (row.kind !== "file" || !row.filePath) {
return row;
}
const file = fileSummaryByPath.get(row.filePath);
const additions = file?.additions ?? row.additions ?? 0;
const deletions = file?.deletions ?? row.deletions ?? 0;
return {
kind: row.kind,
id: row.id,
fileId: row.fileId,
filePath: row.filePath,
previousPath: row.previousPath,
changeType: resolveFileHeaderChangeType({
previousPath: row.previousPath,
nextPath: row.filePath,
currentChangeType: row.changeType ?? "modified",
additions,
deletions,
}),
additions,
deletions,
text: row.text,
content: row.content,
change: row.change,
oldLineNumber: row.oldLineNumber,
newLineNumber: row.newLineNumber,
wordDiffRanges: row.wordDiffRanges,
};
});
const rowsWithFileNotices = rowsWithFileStats.flatMap((row): NativeReviewDiffRow[] => {
const noticeRow = getNoticeRowForFile({
row,
file: row.fileId ? files.get(row.fileId) : undefined,
});
return noticeRow ? [row, noticeRow] : [row];
});
const parsed = {
fixtureId: fixture.id,
rows: rowsWithFileNotices,
files: fileSummaries,
additions: fileSummaries.reduce((total, file) => total + file.additions, 0),
deletions: fileSummaries.reduce((total, file) => total + file.deletions, 0),
};
console.log("[debug-native-diff] parse", {
durationMs: Math.round(performance.now() - startedAt),
files: parsed.files.length,
fixture: fixture.id,
rows: parsed.rows.length,
});
return parsed;
}
export function getNativeReviewDiffFixture(fixtureId: DebugReviewDiffFixtureId) {
return (
debugReviewDiffFixtures.find((fixture) => fixture.id === fixtureId) ??
debugReviewDiffFixtures[0]
);
}
+3
View File
@@ -64,6 +64,7 @@
"@shikijs/themes": "3.23.0",
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
"@t3tools/mobile-review-diff-native": "file:./modules/t3-review-diff",
"@t3tools/mobile-terminal-native": "file:./modules/t3-terminal",
"@t3tools/shared": "workspace:*",
"clsx": "^2.1.1",
@@ -3131,6 +3132,8 @@
"@shikijs/primitive/@shikijs/types": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-qzbeRooUTPnLE+sHD/Z8DStmaDgnbbc/pMrU203950aRqjX/6AFHeDYT+j00y2lPdz0ywJKx7o/7qnqTivtlXg=="],
"@t3tools/mobile/@t3tools/mobile-review-diff-native": ["@t3tools/mobile-review-diff-native@file:apps/mobile/modules/t3-review-diff", {}],
"@t3tools/mobile/@t3tools/mobile-terminal-native": ["@t3tools/mobile-terminal-native@file:apps/mobile/modules/t3-terminal", {}],
"@t3tools/web/react": ["[email protected]", "", {}, "sha512-sfWGGfavi0xr8Pg0sVsyHMAOziVYKgPLNrS7ig+ivMNb3wbCBw3KxtflsGBAwD3gYQlE/AEZsTLgToRrSCjb0Q=="],
+1
View File
@@ -43,6 +43,7 @@
"build:desktop": "turbo run build --filter=@t3tools/desktop --filter=t3",
"typecheck": "turbo run typecheck",
"lint": "oxlint --report-unused-disable-directives",
"lint:mobile": "node scripts/mobile-native-static-check.ts",
"test": "turbo run test",
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
"fmt": "oxfmt",
+208
View File
@@ -0,0 +1,208 @@
#!/usr/bin/env node
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Console, Data, Effect, FileSystem, Logger, Path } from "effect";
import { Command } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
interface NativeStaticTool {
readonly command: string;
readonly installHint: string;
}
class NativeStaticCheckError extends Data.TaggedError("NativeStaticCheckError")<{
readonly message: string;
}> {}
const tools = [
{
command: "swiftlint",
installHint: "brew install swiftlint",
},
{
command: "ktlint",
installHint: "brew install ktlint",
},
{
command: "detekt",
installHint: "brew install detekt",
},
] as const satisfies ReadonlyArray<NativeStaticTool>;
const sourceExtensions = new Set([".swift", ".kt", ".kts"]);
const excludedDirectories = new Set([
".expo",
".git",
"build",
"DerivedData",
"node_modules",
"Pods",
"Vendor",
]);
const appRoot = Effect.service(Path.Path).pipe(
Effect.flatMap((path) => path.fromFileUrl(new URL("../apps/mobile", import.meta.url))),
);
const commandOutputOptions = {
stdout: "inherit",
stderr: "inherit",
} as const;
const commandExists = Effect.fn("commandExists")(function* (command: string) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const lookupCommand =
process.platform === "win32"
? ChildProcess.make("where", [command], {
stdout: "ignore",
stderr: "ignore",
})
: ChildProcess.make("/bin/sh", ["-c", `command -v ${command}`], {
stdout: "ignore",
stderr: "ignore",
});
return yield* spawner.spawn(lookupCommand).pipe(
Effect.flatMap((child) => child.exitCode),
Effect.map((exitCode) => exitCode === 0),
Effect.catch(() => Effect.succeed(false)),
);
});
const warnMissingTool = (tool: NativeStaticTool, checkName: string) =>
Effect.logWarning(
`${tool.command} is not installed; skipping ${checkName}. Install it with '${tool.installHint}' or run 'brew bundle install --file apps/mobile/Brewfile'.`,
);
const runCommand = Effect.fn("runCommand")(function* (
command: string,
args: ReadonlyArray<string>,
cwd: string,
) {
yield* Console.log(`$ ${[command, ...args].join(" ")}`);
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* spawner.spawn(
ChildProcess.make(command, [...args], {
cwd,
...commandOutputOptions,
shell: process.platform === "win32",
}),
);
const exitCode = Number(yield* child.exitCode);
if (exitCode !== 0) {
return yield* new NativeStaticCheckError({
message: `Command exited with non-zero exit code (${exitCode})`,
});
}
});
function collectSources(
directory: string,
): Effect.Effect<ReadonlyArray<string>, unknown, FileSystem.FileSystem | Path.Path> {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const entries = yield* fs.readDirectory(directory);
const sources: Array<string> = [];
for (const entry of entries) {
if (excludedDirectories.has(entry)) {
continue;
}
const entryPath = path.join(directory, entry);
const stat = yield* fs.stat(entryPath);
if (stat.type === "Directory") {
sources.push(...(yield* collectSources(entryPath)));
continue;
}
if (stat.type === "File" && sourceExtensions.has(path.extname(entry))) {
sources.push(entryPath);
}
}
return sources;
});
}
const runNativeStaticChecks = Effect.fn("runNativeStaticChecks")(function* () {
const path = yield* Path.Path;
const root = yield* appRoot;
const sources = yield* collectSources(root);
const swiftSources = sources.filter((source) => path.extname(source) === ".swift");
const kotlinSources = sources.filter((source) => {
const extension = path.extname(source);
return extension === ".kt" || extension === ".kts";
});
const availableTools = new Map<string, boolean>();
for (const tool of tools) {
availableTools.set(tool.command, yield* commandExists(tool.command));
}
if (swiftSources.length > 0) {
if (availableTools.get("swiftlint")) {
yield* runCommand("swiftlint", ["lint", "--config", ".swiftlint.yml", "--strict"], root);
} else {
yield* warnMissingTool(tools[0], "SwiftLint");
}
}
if (kotlinSources.length > 0) {
const relativeKotlinSources = kotlinSources.map((source) => path.relative(root, source));
if (availableTools.get("ktlint")) {
yield* runCommand("ktlint", relativeKotlinSources, root);
} else {
yield* warnMissingTool(tools[1], "ktlint");
}
if (availableTools.get("detekt")) {
yield* runCommand(
"detekt",
[
"--config",
"detekt.yml",
"--input",
relativeKotlinSources.join(","),
"--build-upon-default-config",
],
root,
);
} else {
yield* warnMissingTool(tools[2], "detekt");
}
}
const androidProject = path.join(root, "android");
const gradlew = path.join(
androidProject,
process.platform === "win32" ? "gradlew.bat" : "gradlew",
);
const fs = yield* FileSystem.FileSystem;
if (yield* fs.exists(gradlew)) {
const stat = yield* fs.stat(gradlew);
if (stat.type === "File") {
yield* runCommand(gradlew, ["lint"], androidProject);
}
}
});
export const mobileNativeStaticCheckCommand = Command.make("mobile-native-static-check", {}, () =>
runNativeStaticChecks(),
).pipe(
Command.withDescription("Run mobile native static analysis when native tools are available."),
);
if (import.meta.main) {
Command.run(mobileNativeStaticCheckCommand, { version: "0.0.0" }).pipe(
Effect.scoped,
Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
NodeRuntime.runMain,
);
}