TypeScript
fix(mobile): preserve syntax and navigation in large diffs (#24276)
Julius Marminge074d9e4d4883
diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.ktindex 67579a1cad8..8339b79592b 100644--- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt+++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt@@ -185,7 +185,8 @@ internal class ReviewDiffCanvasDrawing(context: Context) {fun prepareRows(tokens: Map<String, List<DiffToken>>,style: DiffStyle,- width: Int+ width: Int,+ isCancelled: () -> Boolean = { false }): (List<DiffRow>) -> CodeLayoutCache {configureCodePaint(theme.text, 0, style)val paint = TextPaint(textPaint)@@ -196,7 +197,7 @@ internal class ReviewDiffCanvasDrawing(context: Context) {style.codePaddingPx * 2f).toInt()return { rows ->- cache.apply { layout(rows, tokens, paint, style, colors, availableWidth) }+ cache.apply { layout(rows, tokens, paint, style, colors, availableWidth, isCancelled) }}}@@ -218,6 +219,39 @@ internal class ReviewDiffCanvasDrawing(context: Context) {private var widthTokens: Map<String, List<DiffToken>>? = nullprivate var widthStyle: DiffStyle? = nullprivate var measuredContentWidth = 0+ private var asciiCharacterWidth = 0f+ private var asciiFixedPitch = false++ fun tokensChangeWidth(+ previous: Map<String, List<DiffToken>>,+ next: Map<String, List<DiffToken>>,+ style: DiffStyle+ ): Boolean {+ if (widthStyle != style) return true+ fun changed(id: String): Boolean {+ val before = previous[id]+ val after = next[id]+ if (before == after) return false+ return if (widthEntries.containsKey(id) ||+ before.orEmpty().any { it.fontStyle and 3 != 0 } ||+ after.orEmpty().any { it.fontStyle and 3 != 0 }+ ) {+ // Native run boundaries and fallback fonts can change advances, including ASCII italics.+ before?.size != after?.size || before.orEmpty().indices.any { index ->+ val old = before.orEmpty()[index]+ val new = after.orEmpty()[index]+ old.content != new.content || old.fontStyle and 3 != new.fontStyle and 3+ }+ } else {+ before != null && after != null &&+ before.sumOf { it.content.length } != after.sumOf { it.content.length }+ }+ }+ val changed = next.keys.any(::changed) || previous.keys.any { it !in next && changed(it) }+ // Paint-only patches must not make the next comment/viewport update remeasure rows.+ if (!changed) widthTokens = next+ return changed+ }fun contentWidth(rows: List<DiffRow>,@@ -233,20 +267,30 @@ internal class ReviewDiffCanvasDrawing(context: Context) {}// Comment heights and viewport resizing do not change unwrapped text widths.if (widthRows !== rows || widthTokens !== tokens || widthStyle != style) {- if (widthStyle != style) widthEntries = emptyMap()+ if (widthStyle != style) {+ widthEntries = emptyMap()+ configureCodePaint(theme.text, 0, style)+ asciiCharacterWidth = textPaint.measureText("M")+ // Some system font weights resolve to proportional fallbacks even for "monospace".+ val glyphs = CharArray(95) { (' '.code + it).toChar() }.concatToString()+ val advances = FloatArray(glyphs.length)+ textPaint.getTextWidths(glyphs, advances)+ asciiFixedPitch = advances.all { it == asciiCharacterWidth }+ }val next = HashMap<String, WidthEntry>()var widest = 0ffor (row in rows) {if (row.kind != "line" && row.kind != "hunk") continueval rowTokens = if (row.kind == "line") tokens[row.id] else null- val cached = widthEntries[row.id]- val entry = if (cached?.row == row && cached.tokens == rowTokens) {- cached+ val asciiWidth = asciiRowWidth(row, rowTokens)+ val measured = if (asciiWidth >= 0f) {+ asciiWidth} else {- WidthEntry(row, rowTokens, measureRowWidth(row, rowTokens, style))+ val entry = widthEntry(row, rowTokens, style)+ next[row.id] = entry+ entry.width}- next[row.id] = entry- widest = max(widest, entry.width)+ widest = max(widest, measured)}widthEntries = nextwidthRows = rows@@ -259,6 +303,30 @@ internal class ReviewDiffCanvasDrawing(context: Context) {return measuredContentWidth}+ private fun widthEntry(row: DiffRow, tokens: List<DiffToken>?, style: DiffStyle): WidthEntry {+ val cached = widthEntries[row.id]+ return if (cached?.row == row && cached.tokens == tokens) {+ cached+ } else {+ WidthEntry(row, tokens, measureRowWidth(row, tokens, style))+ }+ }++ private fun asciiRowWidth(row: DiffRow, tokens: List<DiffToken>?): Float {+ val fixedPitch = asciiFixedPitch && row.kind == "line" && row.isPlainAscii+ if (!fixedPitch || tokens.orEmpty().any { it.fontStyle and 3 != 0 }) {+ return -1f+ }+ val length = if (tokens.isNullOrEmpty()) {+ row.content.length+ } else {+ tokens.sumOf {+ it.content.length+ }+ }+ return length * asciiCharacterWidth+ }+private fun measureRowWidth(row: DiffRow, tokens: List<DiffToken>?, style: DiffStyle): Float {if (row.kind == "hunk") {configureMonospacePaint(theme.hunkText, style.hunkFontSizePx, style.hunkFontWeight)diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayout.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayout.ktindex dc77a846703..b63baa569be 100644--- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayout.kt+++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayout.kt@@ -35,15 +35,31 @@ internal class CodeLines(internal class CodeWrapLayout(val enabled: Boolean,- private val linesByRowId: Map<String, CodeLines>+ private val linesByRowId: Map<String, CodeLines>,+ private val asciiColumns: Int = Int.MAX_VALUE,+ private val asciiLineHeight: Int = 0) {- fun lines(rowId: String): CodeLines = linesByRowId[rowId] ?: SINGLE_LINE- fun extraHeight(rowId: String): Int = lines(rowId).extraHeight- fun rowHeight(rowId: String, base: Int): Int = lines(rowId).let {- it.firstHeight(base) +- it.extraHeight+ fun needsTokenLayout(+ previous: Map<String, List<DiffToken>>,+ next: Map<String, List<DiffToken>>+ ): Boolean = linesByRowId.keys.any { previous[it] != next[it] }++ // Only visible ASCII rows need line starts; offscreen heights use the same arithmetic.+ fun lines(row: DiffRow): CodeLines = linesByRowId[row.id] ?: if (enabled) {+ CodeLines(IntArray(asciiLineCount(row)) { it * asciiColumns }, asciiLineHeight)+ } else {+ SINGLE_LINE}+ private fun asciiLineCount(row: DiffRow): Int = max(+ 1,+ (row.content.length - 1) / asciiColumns + 1+ )++ fun rowHeight(row: DiffRow, base: Int): Int = linesByRowId[row.id]?.let {+ it.firstHeight(base) + it.extraHeight+ } ?: (base + if (enabled) (asciiLineCount(row) - 1) * asciiLineHeight else 0)+companion object {private val SINGLE_LINE = CodeLines(intArrayOf(0), 0)val NONE = CodeWrapLayout(false, emptyMap())@@ -87,14 +103,15 @@ internal class CodeLayoutCache {it.previousWidth = previousWidth}- @Suppress("LongParameterList")+ @Suppress("LongParameterList", "ReturnCount")fun layout(rows: List<DiffRow>,tokens: Map<String, List<DiffToken>>,paint: Paint,style: DiffStyle,theme: DiffTheme,- width: Int+ width: Int,+ isCancelled: () -> Boolean = { false }): CodeWrapLayout {if (!style.wordWrap || width < paint.measureText("M")) {entries = emptyMap()@@ -106,10 +123,14 @@ internal class CodeLayoutCache {previousTheme = themepreviousWidth = width}+ val characterWidth = paint.measureText("M")+ val columns = max(1, (width / characterWidth).toInt())+ val lineHeight = ceil(paint.fontMetrics.run { descent - ascent }).toInt()val next = HashMap<String, Entry>()val layouts = HashMap<String, CodeLines>()for (row in rows) {- if (row.kind != "line") continue+ if (isCancelled()) return CodeWrapLayout.NONE+ if (row.kind != "line" || row.isPlainAscii) continueval rowTokens = tokens[row.id]val cached = entries[row.id]val entry = if (cached?.row == row && cached.tokens == rowTokens) {@@ -122,12 +143,10 @@ internal class CodeLayoutCache {layouts[row.id] = entry.lines}entries = next- return CodeWrapLayout(true, layouts)+ return CodeWrapLayout(true, layouts, columns, lineHeight)}private fun styledCode(row: DiffRow, tokens: List<DiffToken>?, theme: DiffTheme): CharSequence {- // The ASCII path uses the existing token drawing and rounded highlight rectangles.- if (row.content.all { it in ' '..'~' }) return row.contentval text = SpannableString(row.content)var offset = 0for (token in tokens.orEmpty()) {diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.ktindex ee6740cf34c..1291826f1c1 100644--- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt+++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt@@ -1,5 +1,6 @@package expo.modules.t3reviewdiff+import expo.modules.kotlin.Promiseimport expo.modules.kotlin.modules.Moduleimport expo.modules.kotlin.modules.ModuleDefinition@@ -49,6 +50,9 @@ class T3ReviewDiffModule : Module() {Prop("initialRowIndex") { view: T3ReviewDiffView, initialRowIndex: Double ->view.setInitialRowIndex(initialRowIndex)}+ Prop("initialFileId") { view: T3ReviewDiffView, fileId: String ->+ view.setInitialFileId(fileId)+ }Events("onDebug",@@ -71,8 +75,12 @@ class T3ReviewDiffModule : Module() {AsyncFunction("setTokensJson") { view: T3ReviewDiffView, tokensJson: String ->view.setTokensJson(tokensJson)}- AsyncFunction("setTokensPatchJson") { view: T3ReviewDiffView, tokensPatchJson: String ->- view.setTokensPatchJson(tokensPatchJson)+ AsyncFunction("setTokensPatchJson") {+ view: T3ReviewDiffView,+ tokensPatchJson: String,+ promise: Promise+ ->+ view.setTokensPatchJson(tokensPatchJson) { accepted -> promise.resolve(accepted) }}OnViewDestroys { view: T3ReviewDiffView ->diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.ktindex e39fdeb9634..5accfa4b963 100644--- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt+++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt@@ -39,10 +39,13 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(contprivate var collapsedCommentIds: Set<String> = emptySet()private var initialRowIndex = 0private var pendingInitialScroll = false+ private var initialFileId: String? = null+ private var pendingScrollFileId: String? = nullprivate var lastVisibleFileId: String? = nullprivate var tokensResetKey = ""private var contentResetKey = ""- private var rowsDecodeGeneration = 0++ @Volatile private var rowsDecodeGeneration = 0private var tokensDecodeGeneration = 0private val payloadDecodeExecutor = Executors.newSingleThreadExecutor()private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop@@ -65,13 +68,16 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont))}+ canvasView.onVerticalAnchorRestored = { verticalScroller.forceFinished(true) }canvasView.onRowTap = { row, gesture, target -> handleRowTap(row, gesture, target) }+ canvasView.onViewportSizeChanged = { applyPendingInitialScroll() }canvasView.onVisibleRowsChanged = { first, last ->onDebug(mapOf("message" to "visible-range","firstRowIndex" to first,"lastRowIndex" to last,+ "totalRows" to rows.size,),)emitVisibleFile(first)@@ -92,10 +98,18 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(contfun setContentResetKey(value: String) {if (contentResetKey == value) returncontentResetKey = value+ rowsDecodeGeneration += 1tokensDecodeGeneration += 1+ canvasView.setViewportEventsPaused(true)+ verticalScroller.forceFinished(true)+ horizontalScroller.forceFinished(true)+ rows = emptyList()+ visibleRows = emptyList()+ canvasView.rows = emptyList()canvasView.tokensByRowId = emptyMap()lastVisibleFileId = nullpendingInitialScroll = true+ pendingScrollFileId = initialFileIdcanvasView.setVerticalOffset(0)canvasView.resetHorizontalOffsets()applyPendingInitialScroll()@@ -146,18 +160,33 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont}fun setInitialRowIndex(value: Double) {- initialRowIndex = value.toInt().coerceAtLeast(0)- pendingInitialScroll = true+ initialRowIndex = value.toInt()+ pendingInitialScroll = value.isFinite() && value >= 0+ canvasView.setViewportEventsPaused(true)+ applyPendingInitialScroll()+ }++ fun setInitialFileId(value: String) {+ val nextFileId = value.takeIf { it.isNotEmpty() }+ if (nextFileId == initialFileId) return+ initialFileId = nextFileId+ pendingScrollFileId = nextFileId+ canvasView.setViewportEventsPaused(true)applyPendingInitialScroll()}fun setRowsJson(value: String) {rowsDecodeGeneration += 1+ canvasView.setViewportEventsPaused(true)val generation = rowsDecodeGeneration- val prepareLayout = canvasView.prepareRows()+ val isCancelled = { generation != rowsDecodeGeneration || Thread.currentThread().isInterrupted }+ val prepareLayout = canvasView.prepareRows(isCancelled)payloadDecodeExecutor.execute {- val decodedRows = parseRows(value)+ if (isCancelled()) return@execute+ val decodedRows = parseRows(value, isCancelled)+ if (isCancelled()) return@executeval codeLayouts = prepareLayout(decodedRows)+ if (isCancelled()) return@executepost {if (generation != rowsDecodeGeneration) return@postcanvasView.useCodeLayouts(codeLayouts)@@ -180,7 +209,8 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont}}- fun setTokensPatchJson(value: String) {+ fun setTokensPatchJson(value: String, completion: (Boolean) -> Unit) {+ val contentKey = contentResetKeypayloadDecodeExecutor.execute {try {val payload = JSONObject(value)@@ -189,12 +219,19 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(contpayload.optJSONObject("tokensByRowId") ?: JSONObject(),)post {- if (resetKey.isNotEmpty() && resetKey != tokensResetKey) return@post+ if (contentKey != contentResetKey ||+ (resetKey.isNotEmpty() && resetKey != tokensResetKey)+ ) {+ completion(false)+ return@post+ }if (decodedTokens.isNotEmpty()) {canvasView.tokensByRowId = canvasView.tokensByRowId + decodedTokens}+ completion(true)}} catch (_: Exception) {+ post { completion(false) }}}}@@ -354,6 +391,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont}private fun rebuildVisibleRows() {+ canvasView.setViewportEventsPaused(true)val filtered = ArrayList<DiffRow>(rows.size)var currentFileCollapsed = falserows.forEach { row ->@@ -411,10 +449,20 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont}private fun applyPendingInitialScroll() {- if (!pendingInitialScroll || visibleRows.isEmpty()) return- pendingInitialScroll = false- val index = initialRowIndex.coerceIn(0, visibleRows.lastIndex)- post { canvasView.setVerticalOffset(canvasView.rowTop(index)) }+ if (visibleRows.isEmpty() || canvasView.width <= 0 || canvasView.height <= 0) return+ val fileId = pendingScrollFileId+ if (fileId != null) {+ val index = visibleRows.indexOfFirst { it.kind == "file" && it.resolvedFileId == fileId }+ if (index < 0) return+ pendingScrollFileId = null+ pendingInitialScroll = false+ canvasView.setVerticalOffset(canvasView.rowTop(index))+ } else if (pendingInitialScroll) {+ pendingInitialScroll = false+ val index = initialRowIndex.coerceIn(0, visibleRows.lastIndex)+ canvasView.setVerticalOffset(canvasView.rowTop(index))+ }+ canvasView.setViewportEventsPaused(false)}private fun scrollToY(y: Int, animated: Boolean) {@@ -476,6 +524,7 @@ internal data class DiffRow(val commentSectionTitle: String) {val resolvedFileId: String get() = fileId.ifEmpty { id }+ val isPlainAscii: Boolean = content.all { it in ' '..'~' }}internal data class DiffWordDiffRange(@@ -710,6 +759,7 @@ private class DiffCanvasView(context: Context) : View(context) {},)private var rowOffsets = intArrayOf(0)+ private var fileHeaderIndices = intArrayOf()private var codeWrap = CodeWrapLayout.NONEprivate var verticalOffset = 0@@ -718,20 +768,26 @@ private class DiffCanvasView(context: Context) : View(context) {private var contentWidthPx = 0private val headerPathOffsetsByFileId = mutableMapOf<String, Int>()private var lastVisibleRange: Pair<Int, Int>? = null+ private var viewportEventsPaused = truevar rows: List<DiffRow> = emptyList()set(value) {field = value+ fileHeaderIndices = indexFileHeaders(value)headerPathOffsetsByFileId.keys.retainAll(- value.asSequence().filter { it.kind == "file" }.map { it.resolvedFileId }.toSet(),+ fileHeaderIndices.map { value[it].resolvedFileId }.toSet(),)- rebuildOffsets()+ rebuildOffsets(preserveAnchor = false)}var tokensByRowId: Map<String, List<DiffToken>> = emptyMap()set(value) {+ val previous = fieldfield = valueif (style.wordWrap) {- rebuildOffsets()- } else {+ // ASCII uses fixed-pitch geometry. Native layouts also carry their painted spans.+ if (codeWrap.needsTokenLayout(previous, value)) {+ rebuildOffsets()+ }+ } else if (drawing.tokensChangeWidth(previous, value, style)) {contentWidthPx = drawing.contentWidth(rows, value, style)setHorizontalOffset(horizontalOffset)}@@ -772,8 +828,11 @@ private class DiffCanvasView(context: Context) : View(context) {var onRowTap: ((DiffRow, String, RowTapTarget) -> Unit)? = nullvar onVisibleRowsChanged: ((Int, Int) -> Unit)? = nullvar onContentHeightChanged: ((Int) -> Unit)? = null+ var onVerticalAnchorRestored: (() -> Unit)? = null+ var onViewportSizeChanged: (() -> Unit)? = null- fun prepareRows() = drawing.prepareRows(tokensByRowId, style, width)+ fun prepareRows(isCancelled: () -> Boolean = { false }) =+ drawing.prepareRows(tokensByRowId, style, width, isCancelled)fun useCodeLayouts(layouts: CodeLayoutCache) {drawing.codeLayouts = layouts}@@ -789,6 +848,7 @@ private class DiffCanvasView(context: Context) : View(context) {super.onSizeChanged(width, height, oldWidth, oldHeight)// Wrapped rows take their height from the width, so a new width is a new layout.if (style.wordWrap && width != oldWidth) layoutRows()+ onViewportSizeChanged?.invoke()setVerticalOffset(verticalOffset)setHorizontalOffset(horizontalOffset)clampHeaderPathOffsets()@@ -883,20 +943,27 @@ private class DiffCanvasView(context: Context) : View(context) {}}- private fun rebuildOffsets() {- layoutRows()+ private fun rebuildOffsets(preserveAnchor: Boolean = true) {+ layoutRows(preserveAnchor)requestLayout()invalidate()}- private fun layoutRows() {+ private fun layoutRows(preserveAnchor: Boolean = true) {+ // Rows are unchanged here; their old offsets still identify the viewport's code row.+ val anchorIndex = if (preserveAnchor && rows.isNotEmpty()) rowIndexAt(verticalOffset) else null+ val intraRowOffset = anchorIndex?.let { verticalOffset - rowOffsets[it] } ?: 0contentWidthPx = drawing.contentWidth(rows, tokensByRowId, style)codeWrap = drawing.codeWrapLayout(rows, tokensByRowId, style, width)rowOffsets = IntArray(rows.size + 1)rows.forEachIndexed { index, row ->rowOffsets[index + 1] = rowOffsets[index] + rowHeight(row)}- setVerticalOffset(verticalOffset)+ val targetOffset = anchorIndex?.let {+ rowOffsets[it] + intraRowOffset.coerceIn(0, max(0, rowOffsets[it + 1] - rowOffsets[it] - 1))+ } ?: verticalOffset+ if (targetOffset != verticalOffset) onVerticalAnchorRestored?.invoke()+ setVerticalOffset(targetOffset)setHorizontalOffset(horizontalOffset)clampHeaderPathOffsets()onContentHeightChanged?.invoke(rowOffsets.last())@@ -910,25 +977,11 @@ private class DiffCanvasView(context: Context) : View(context) {} else {(124 * density).toInt()}- "line" -> codeWrap.rowHeight(row.id, style.rowHeightPx.toInt())+ "line" -> codeWrap.rowHeight(row, style.rowHeightPx.toInt())else -> style.rowHeightPx.toInt()}.coerceAtLeast(1)- @Suppress("ReturnCount")- private fun rowIndexAt(y: Int): Int {- if (rows.isEmpty()) return 0- var low = 0- var high = rows.lastIndex- while (low <= high) {- val middle = (low + high) ushr 1- when {- y < rowOffsets[middle] -> high = middle - 1- y >= rowOffsets[middle + 1] -> low = middle + 1- else -> return middle- }- }- return low.coerceIn(0, rows.lastIndex)- }+ private fun rowIndexAt(y: Int): Int = rowIndexAtOffset(y, rowOffsets, rows.size)private fun rowHitAt(y: Float): RowHit? {stickyFileHeader(firstVisibleRow())?.let { sticky ->@@ -949,14 +1002,21 @@ private class DiffCanvasView(context: Context) : View(context) {private fun firstVisibleRow(): Int = rowIndexAt(verticalOffset)+ fun setViewportEventsPaused(paused: Boolean) {+ viewportEventsPaused = paused+ if (paused) lastVisibleRange = null else emitVisibleRange()+ }+private fun emitVisibleRange() {- if (rows.isEmpty()) return+ if (viewportEventsPaused || rows.isEmpty()) return+ if (width <= 0 || height <= 0) returnval first = rowIndexAt(verticalOffset)val last = rowIndexAt(verticalOffset + max(1, height))val range = first to last- if (range == lastVisibleRange) return- lastVisibleRange = range- onVisibleRowsChanged?.invoke(first, last)+ if (range != lastVisibleRange) {+ lastVisibleRange = range+ onVisibleRowsChanged?.invoke(first, last)+ }}private fun drawRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {@@ -1235,7 +1295,7 @@ private class DiffCanvasView(context: Context) : View(context) {}// Wrapped rows keep the line number and first code line in the first row-height band.- val lines = codeWrap.lines(row.id)+ val lines = codeWrap.lines(row)val firstLineBottom = top + lines.firstHeight(style.rowHeightPx.toInt())drawScrollableCode(canvas, top, bottom) { codeX ->drawing.configureCodePaint(theme.text, 0, style)@@ -1287,11 +1347,13 @@ private class DiffCanvasView(context: Context) : View(context) {@Suppress("ReturnCount")private fun stickyFileHeader(firstVisibleIndex: Int): StickyFileHeader? {if (rows.isEmpty()) return null- val fileIndex = (firstVisibleIndex.coerceIn(0, rows.lastIndex) downTo 0)- .firstOrNull { rows[it].kind == "file" }- ?: return null+ val rowIndex = firstVisibleIndex.coerceIn(0, rows.lastIndex)+ val found = fileHeaderIndices.binarySearch(rowIndex)+ val slot = if (found >= 0) found else -found - 2+ if (slot < 0) return null+ val fileIndex = fileHeaderIndices[slot]val headerHeight = rowHeight(rows[fileIndex])- val nextFileIndex = ((fileIndex + 1)..rows.lastIndex).firstOrNull { rows[it].kind == "file" }+ val nextFileIndex = fileHeaderIndices.getOrNull(slot + 1)val top = nextFileIndex?.let { min(0, rowOffsets[it] - verticalOffset - headerHeight) }?: 0@@ -1334,20 +1396,6 @@ private class DiffCanvasView(context: Context) : View(context) {canvas.drawLine(0f, bottom - density / 2f, width.toFloat(), bottom - density / 2f, borderPaint)}- private fun centeredBaseline(top: Int, bottom: Int, paint: Paint): Float {- val metrics = paint.fontMetrics- return (top + bottom) / 2f - (metrics.ascent + metrics.descent) / 2f- }-- private fun ellipsize(value: String, paint: Paint, width: Float): String {- if (paint.measureText(value) <= width) return value- val suffix = "..."- val available = max(0f, width - paint.measureText(suffix))- var end = value.length- while (end > 0 && paint.measureText(value, 0, end) > available) end -= 1- return value.substring(0, end) + suffix- }-private data class StickyFileHeader(val index: Int,val top: Int,@@ -1366,35 +1414,62 @@ private class DiffCanvasView(context: Context) : View(context) {)}+private fun centeredBaseline(top: Int, bottom: Int, paint: Paint): Float {+ val metrics = paint.fontMetrics+ return (top + bottom) / 2f - (metrics.ascent + metrics.descent) / 2f+}++private fun ellipsize(value: String, paint: Paint, width: Float): String {+ if (paint.measureText(value) <= width) return value+ val suffix = "..."+ val available = max(0f, width - paint.measureText(suffix))+ var end = value.length+ while (end > 0 && paint.measureText(value, 0, end) > available) end -= 1+ return value.substring(0, end) + suffix+}++private fun indexFileHeaders(rows: List<DiffRow>): IntArray {+ val headers = ArrayList<Int>()+ rows.forEachIndexed { index, row ->+ if (row.kind == "file") headers.add(index)+ }+ return headers.toIntArray()+}+private fun withAlpha(color: Int, alpha: Int): Int =Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color))-private fun parseRows(value: String): List<DiffRow> = try {- val array = JSONArray(value)- List(array.length()) { index ->- val row = array.getJSONObject(index)- DiffRow(- kind = row.optString("kind"),- id = row.optString("id"),- fileId = row.optString("fileId"),- filePath = row.optString("filePath"),- previousPath = row.optNullableString("previousPath"),- changeType = row.optString("changeType"),- additions = row.optInt("additions"),- deletions = row.optInt("deletions"),- text = row.optString("text"),- content = row.optString("content"),- change = row.optString("change", "context"),- oldLineNumber = row.optNullableInt("oldLineNumber"),- newLineNumber = row.optNullableInt("newLineNumber"),- wordDiffRanges = row.optJSONArray("wordDiffRanges")?.let(::parseWordDiffRanges).orEmpty(),- commentText = row.optString("commentText"),- commentRangeLabel = row.optString("commentRangeLabel"),- commentSectionTitle = row.optString("commentSectionTitle"),- )+private fun parseRows(value: String): List<DiffRow> = parseRows(value) { false }++private fun parseRows(value: String, isCancelled: () -> Boolean): List<DiffRow> {+ return try {+ val array = JSONArray(value)+ List(array.length()) { index ->+ if (isCancelled()) return emptyList()+ val row = array.getJSONObject(index)+ DiffRow(+ kind = row.optString("kind"),+ id = row.optString("id"),+ fileId = row.optString("fileId"),+ filePath = row.optString("filePath"),+ previousPath = row.optNullableString("previousPath"),+ changeType = row.optString("changeType"),+ additions = row.optInt("additions"),+ deletions = row.optInt("deletions"),+ text = row.optString("text"),+ content = row.optString("content"),+ change = row.optString("change", "context"),+ oldLineNumber = row.optNullableInt("oldLineNumber"),+ newLineNumber = row.optNullableInt("newLineNumber"),+ wordDiffRanges = row.optJSONArray("wordDiffRanges")?.let(::parseWordDiffRanges).orEmpty(),+ commentText = row.optString("commentText"),+ commentRangeLabel = row.optString("commentRangeLabel"),+ commentSectionTitle = row.optString("commentSectionTitle"),+ )+ }+ } catch (_: Exception) {+ emptyList()}-} catch (_: Exception) {- emptyList()}private fun parseWordDiffRanges(value: JSONArray): List<DiffWordDiffRange> = buildList {@@ -1464,3 +1539,19 @@ private fun JSONObject.floatDp(key: String, fallbackPx: Float, density: Float):private fun JSONObject.floatSp(key: String, fallbackPx: Float, density: Float): Float =if (has(key)) optDouble(key).toFloat() * density else fallbackPx++@Suppress("ReturnCount")+private fun rowIndexAtOffset(y: Int, rowOffsets: IntArray, rowCount: Int): Int {+ if (rowCount == 0) return 0+ var low = 0+ var high = rowCount - 1+ while (low <= high) {+ val middle = (low + high) ushr 1+ when {+ y < rowOffsets[middle] -> high = middle - 1+ y >= rowOffsets[middle + 1] -> low = middle + 1+ else -> return middle+ }+ }+ return low.coerceIn(0, rowCount - 1)+}diff --git a/apps/mobile/modules/t3-review-diff/android/src/test/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayoutTest.kt b/apps/mobile/modules/t3-review-diff/android/src/test/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayoutTest.ktindex 7c4f531fbec..04469974231 100644--- a/apps/mobile/modules/t3-review-diff/android/src/test/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayoutTest.kt+++ b/apps/mobile/modules/t3-review-diff/android/src/test/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayoutTest.kt@@ -91,7 +91,7 @@ class ReviewDiffCodeLayoutTest {style,theme,280- ).lines(row.id)+ ).lines(row)val second = cache.layout(listOf(row, comment.copy(commentText = "After")),emptyMap(),@@ -99,9 +99,9 @@ class ReviewDiffCodeLayoutTest {style,theme,280,- ).lines(row.id)+ ).lines(row)assertSame(first, second)- val narrow = cache.layout(listOf(row), emptyMap(), paint, style, theme, 180).lines(row.id)+ val narrow = cache.layout(listOf(row), emptyMap(), paint, style, theme, 180).lines(row)assertNotSame(first, narrow)assertTrue(narrow.extraHeight > first.extraHeight)val edited = cache.layout(@@ -111,7 +111,7 @@ class ReviewDiffCodeLayoutTest {style,theme,180- ).lines(row.id)+ ).lines(row)assertTrue(edited.extraHeight < narrow.extraHeight)assertEquals(0,@@ -122,7 +122,7 @@ class ReviewDiffCodeLayoutTest {style.copy(wordWrap = false),theme,180- ).extraHeight(row.id)+ ).rowHeight(row, 0))}@@ -132,9 +132,9 @@ class ReviewDiffCodeLayoutTest {val row = row("漢字".repeat(30)).copy(wordDiffRanges = listOf(DiffWordDiffRange(3, 21)))val style = DiffStyle.defaults(1f).copy(wordWrap = true)val theme = DiffTheme.fallback("light")- val initial = cache.layout(listOf(row), emptyMap(), paint, style, theme, 180).lines(row.id)+ val initial = cache.layout(listOf(row), emptyMap(), paint, style, theme, 180).lines(row)val tokens = mapOf(row.id to listOf(DiffToken(row.content, 0xff008800.toInt(), 2)))- val highlighted = cache.layout(listOf(row), tokens, paint, style, theme, 180).lines(row.id)+ val highlighted = cache.layout(listOf(row), tokens, paint, style, theme, 180).lines(row)assertNotSame(initial, highlighted)val text = requireNotNull(highlighted.nativeLayout).text as Spannedval span = text.getSpans(0, text.length, BackgroundColorSpan::class.java).single()@@ -193,6 +193,32 @@ class ReviewDiffCodeLayoutTest {assertFresh(rows)}+ @Test+ fun obsoletePreparationStopsBeforeWalkingTheRemainingRows() {+ val cache = CodeLayoutCache()+ val row = row("漢字".repeat(100))+ val style = DiffStyle.defaults(1f).copy(wordWrap = true)+ val theme = DiffTheme.fallback("light")+ val displayed = cache.layout(listOf(row), emptyMap(), paint, style, theme, 280).lines(row)+ val preparation = cache.copyForPreparation()+ var checked = 0+ val cancelled = preparation.layout(+ List(10000) { row.copy(id = "row:$it") },+ emptyMap(),+ paint,+ style,+ theme,+ 280,+ isCancelled = { ++checked == 2 },+ )+ assertEquals(2, checked)+ assertEquals(false, cancelled.enabled)+ assertSame(+ displayed,+ cache.layout(listOf(row), emptyMap(), paint, style, theme, 280).lines(row)+ )+ }+private fun row(content: String) = DiffRow(kind = "line", id = "line", fileId = "file", filePath = "test.ts", previousPath = null,changeType = "modified", additions = 1, deletions = 0, text = "", content = content,diff --git a/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift b/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swiftindex 20aa20c2c73..604e90658b7 100644--- a/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift+++ b/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift@@ -1,5 +1,19 @@import UIKit+/// Fixed-pitch line boundaries need no storage proportional to the text length.+struct ReviewDiffCodeLineStarts: RandomAccessCollection {+ let startIndex = 0+ let endIndex: Int+ let columns: Int++ init(length: Int, columns: Int?) {+ self.columns = Swift.max(1, columns ?? length)+ endIndex = (Swift.max(1, length) - 1) / self.columns + 1+ }++ subscript(index: Int) -> Int { index * columns }+}+/// ASCII uses fixed-pitch columns. TextKit handles shaping, tabs, and Unicode highlights./// Pass `unboundedWidth` to lay a row out on one line for horizontal scrolling.final class ReviewDiffCodeLayout: NSObject {@@ -19,7 +33,7 @@ final class ReviewDiffCodeLayout: NSObject {return cache}()let text: String- let starts: [Int]+ let starts: ReviewDiffCodeLineStartslet lineHeight: CGFloatlet firstLineHeight: CGFloatlet extraHeight: CGFloat@@ -36,10 +50,10 @@ final class ReviewDiffCodeLayout: NSObject {self.width = widthself.characterWidth = characterWidthlineHeight = ceil(font.lineHeight)- if text.utf8.allSatisfy({ $0 >= 32 && $0 <= 126 }) {+ if Self.isPrintableASCII(text) {let length = max(1, text.utf8.count)let columns = max(1, Int(min(width / characterWidth, CGFloat(length))))- starts = Array(stride(from: 0, to: length, by: columns))+ starts = ReviewDiffCodeLineStarts(length: length, columns: columns)firstLineHeight = font.lineHeightextraHeight = CGFloat(starts.count - 1) * lineHeightusedWidth = CGFloat(min(text.utf8.count, columns)) * characterWidth@@ -50,7 +64,7 @@ final class ReviewDiffCodeLayout: NSObject {let manager = layout.managerlet container = layout.containerusesNativeLayout = true- starts = [0]+ starts = ReviewDiffCodeLineStarts(length: 0, columns: nil)firstLineHeight = manager.numberOfGlyphs > 0? manager.lineFragmentRect(forGlyphAt: 0, effectiveRange: nil).height : font.lineHeightlet used = manager.usedRect(for: container)@@ -59,6 +73,10 @@ final class ReviewDiffCodeLayout: NSObject {}}+ static func isPrintableASCII(_ text: String) -> Bool {+ text.utf8.allSatisfy { $0 >= 32 && $0 <= 126 }+ }+private func nativeLayout() -> ReviewDiffTextLayout {if let cached = Self.drawnLayouts.object(forKey: self) { return cached }let layout = ReviewDiffTextLayout()diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swiftindex 0b8bd70633b..caab10799c0 100644--- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift+++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift@@ -61,6 +61,10 @@ public class T3ReviewDiffModule: Module {view.setInitialRowIndex(initialRowIndex)}+ Prop("initialFileId") { (view: T3ReviewDiffView, fileId: String) in+ view.setInitialFileId(fileId)+ }+Prop("scrollEnabled") { (view: T3ReviewDiffView, enabled: Bool) inview.setScrollEnabled(enabled)}@@ -106,8 +110,10 @@ public class T3ReviewDiffModule: Module {view.setTokensJson(tokensJson)}- AsyncFunction("setTokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in- view.setTokensPatchJson(tokensPatchJson)+ AsyncFunction("setTokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String, promise: Promise) in+ view.setTokensPatchJson(tokensPatchJson) { accepted in+ promise.resolve(accepted)+ }}}}diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swiftindex 4e41fa64383..41edbe3e095 100644--- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift+++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift@@ -170,7 +170,7 @@ private struct ReviewDiffNativeStylePayload: Decodable {let emptyStateFontWeight: String?}-private struct ReviewDiffNativeStyle {+private struct ReviewDiffNativeStyle: Equatable {let wordWrap: Boollet rowHeight: CGFloatlet contentWidth: CGFloat@@ -333,6 +333,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {private var tokensResetKey = ""private var contentResetKey = ""private var initialRowIndex: Int?+ private var initialFileId: String?private var hasAppliedInitialRowIndex = falseprivate var lastVisibleFileId: String?private var pendingScrollFileId: String?@@ -388,8 +389,9 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {public override func layoutSubviews() {super.layoutSubviews()+ let anchor = contentView.viewportWidth != bounds.width ? contentView.viewportRowAnchor() : nilscrollView.frame = bounds- updateContentMetrics()+ updateContentMetrics(rowAnchor: anchor)}public func scrollViewDidScroll(_ scrollView: UIScrollView) {@@ -423,6 +425,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {}func setRowsJson(_ rowsJson: String) {+ contentView.cancelRowPreparation()rowsDecodeGeneration += 1let generation = rowsDecodeGeneration@@ -504,11 +507,12 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {}}- func setTokensPatchJson(_ tokensPatchJson: String) {+ func setTokensPatchJson(_ tokensPatchJson: String, completion: @escaping (Bool) -> Void) {let contentResetKey = self.contentResetKeypayloadDecodeQueue.async { [weak self] inguard let data = tokensPatchJson.data(using: .utf8) else {+ DispatchQueue.main.async { completion(false) }return}@@ -516,27 +520,34 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {let patch = try JSONDecoder().decode(ReviewDiffNativeTokenPatch.self, from: data)DispatchQueue.main.async { [weak self] inguard let self else {+ completion(false)return}guard contentResetKey == self.contentResetKey else {+ completion(false)return}// A highlighter request from the previous file can finish after the view has// already reset. Never let that stale patch roll the native token state back.if let resetKey = patch.resetKey, resetKey != self.tokensResetKey {+ completion(false)return}let tokensByRowId = patch.tokensByRowId ?? [:]if tokensByRowId.isEmpty {+ completion(true)return}self.contentView.mergeTokensByRowId(tokensByRowId)- if let chunkIndex = patch.chunkIndex, chunkIndex < 5 || chunkIndex.isMultiple(of: 10) {+ completion(true)+ if let chunkIndex = patch.chunkIndex {self.emitDebug("tokens-patch-decoded", [+ "resetKey": patch.resetKey ?? "","chunkIndex": chunkIndex,"rows": tokensByRowId.count,+ "tokens": tokensByRowId.values.reduce(0) { $0 + $1.count },"totalRows": self.contentView.tokensByRowId.count,])}@@ -545,6 +556,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {let message = error.localizedDescriptionDispatchQueue.main.async { [weak self] inself?.emitDebug("tokens-patch-decode-failed", ["error": message])+ completion(false)}}}@@ -587,13 +599,15 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {}self.contentResetKey = contentResetKey+ lastVisibleRangeDebugKey = ""+ contentView.cancelRowPreparation()rowsDecodeGeneration += 1tokensDecodeGeneration += 1contentView.tokensByRowId = [:]rows = []contentView.rows = []hasAppliedInitialRowIndex = false- pendingScrollFileId = nil+ pendingScrollFileId = initialFileIdisProgrammaticScrollActive = falsescrollView.setContentOffset(CGPoint(x: 0, y: -scrollView.contentInset.top), animated: false)updateContentMetrics()@@ -681,12 +695,23 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {applyTheme()}- private func updateContentMetrics() {+ private func updateContentMetrics(rowAnchor: ReviewDiffViewportRowAnchor? = nil) {+ let anchor = rowAnchor ?? (contentView.viewportWidth != bounds.width+ ? contentView.viewportRowAnchor() : nil)let style = contentView.stylecontentView.viewportWidth = bounds.widthlet height = max(bounds.height, contentView.contentHeight)let width = bounds.widthscrollView.contentSize = CGSize(width: bounds.width, height: height)+ if let anchor, let offset = contentView.offset(for: anchor) {+ let minOffset = -scrollView.contentInset.top+ let maxOffset = max(height - scrollView.bounds.height + scrollView.contentInset.bottom, minOffset)+ let target = min(max(offset - scrollView.contentInset.top, minOffset), maxOffset)+ if abs(target - scrollView.contentOffset.y) > 0.01 {+ scrollView.setContentOffset(CGPoint(x: 0, y: target), animated: false)+ if isProgrammaticScrollActive { finishVerticalScroll() }+ }+ }contentView.frame = CGRect(x: 0,y: scrollView.contentOffset.y,@@ -699,6 +724,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {applyInitialRowIndexIfNeeded()applyPendingScrollIfNeeded()emitVisibleFileIfNeeded()+ emitVisibleRange(reason: "layout")let debugKey = "\(rows.count):\(Int(bounds.width)):\(Int(bounds.height)):\(Int(contentView.contentHeight))"if debugKey != lastMetricsDebugKey {@@ -759,7 +785,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {}private func emitVisibleRange(reason: String) {- guard let range = contentView.currentVisibleRowRange() else {+ guard bounds.width > 0, bounds.height > 0,+ let range = contentView.currentVisibleRowRange() else {return}@@ -833,6 +860,16 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {applyPendingScrollIfNeeded()}+ func setInitialFileId(_ fileId: String) {+ let nextFileId = fileId.isEmpty ? nil : fileId+ guard nextFileId != initialFileId else { return }+ initialFileId = nextFileId+ pendingScrollFileId = nextFileId+ pendingScrollAnimated = false+ // Apply after the prop batch and content metrics, before the first range event.+ setNeedsLayout()+ }+func scrollToTop(animated: Bool) {pendingScrollFileId = nilpendingScrollAnimated = false@@ -869,10 +906,11 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {}private func applyStyle() {+ let anchor = contentView.viewportRowAnchor()contentView.style = ReviewDiffNativeStyle.resolve(stylePayload).applyingOverrides(rowHeight: rowHeightOverride, contentWidth: contentWidthOverride)- updateContentMetrics()+ updateContentMetrics(rowAnchor: anchor)}private func updateViewportFrame() {@@ -918,7 +956,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {contentView.isVerticalScrollActive = shouldAnimatescrollView.setContentOffset(CGPoint(x: 0, y: clampedOffset), animated: shouldAnimate)if !shouldAnimate {- updateViewportFrame()+ finishVerticalScroll()}}@@ -964,11 +1002,77 @@ private struct ReviewDiffStickyFileHeaderTarget {let rect: CGRect}+private struct ReviewDiffViewportRowAnchor {+ let rowIndex: Int+ let intraRowOffset: CGFloat+}+private struct ReviewDiffScrollAnchor {let fileId: Stringlet screenY: CGFloat}+private final class ReviewDiffRowPreparation {+ private let lock = NSLock()+ private var cancelled = false++ func cancel() {+ lock.lock()+ cancelled = true+ lock.unlock()+ }++ var isCancelled: Bool {+ lock.lock()+ defer { lock.unlock() }+ return cancelled+ }+}++private struct ReviewDiffGeometryConfiguration: Equatable {+ let style: ReviewDiffNativeStyle+ let viewportWidth: CGFloat+ let collapsedFileIds: Set<String>+ let collapsedCommentIds: Set<String>++ func height(for row: ReviewDiffNativeRow) -> CGFloat {+ if row.kind == "file" { return style.fileHeaderHeight }+ if collapsedFileIds.contains(row.resolvedFileId) { return 0 }+ if row.kind == "notice" { return max(style.rowHeight * 2, 44) }+ if row.kind == "comment" { return collapsedCommentIds.contains(row.id) ? 44 : 124 }+ return style.rowHeight+ }+}++private struct ReviewDiffRowGeometryInput {+ let configuration: ReviewDiffGeometryConfiguration+ let font: UIFont+ let hunkFont: UIFont+ let characterWidth: CGFloat+ let layoutWidth: CGFloat?+ let cached: [String: ReviewDiffCodeLayout]+}++private struct ReviewDiffRowGeometry {+ let offsets: [CGFloat]+ let fileHeaderIndices: [Int]+ let contentWidths: [String: CGFloat]+ let nativeLayouts: [String: ReviewDiffCodeLayout]+ let height: CGFloat+ let characterWidth: CGFloat+ let wrapColumns: Int?+}++private extension ReviewDiffNativeRow {+ var resolvedFileId: String {+ if let fileId { return fileId }+ if let range = id.range(of: ":header") ?? id.range(of: ":hunk:") ?? id.range(of: ":line:") {+ return String(id[..<range.lowerBound])+ }+ return filePath ?? id+ }+}+private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {var rows: [ReviewDiffNativeRow] = [] {didSet {@@ -979,7 +1083,13 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {activePanKind = nilcodeDecorationVersion += 1tokenAttributedStringsByRowId.removeAll()- rebuildRowLayout()+ if let geometry = preparedRowGeometry {+ preparedRowGeometry = nil+ applyRowGeometry(geometry)+ } else {+ cancelRowPreparation()+ rebuildRowLayout()+ }setNeedsDisplayForVisibleBounds()}}@@ -993,12 +1103,8 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {}func mergeTokensByRowId(_ tokensPatch: [String: [ReviewDiffNativeToken]]) {- tokensPatch.forEach { rowId, tokens in- tokensByRowId[rowId] = tokens- tokenAttributedStringsByRowId.removeValue(forKey: rowId)- }- clampHorizontalOffsets()- setNeedsDisplayForVisibleBounds()+ // One mutation lets didSet invalidate decoration and display once per batch.+ tokensByRowId.merge(tokensPatch) { _, tokens in tokens }}var collapsedFileIds: Set<String> = [] {@@ -1065,9 +1171,18 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {private var codeWrapColumns: Int?/// Text geometry survives comment height changes; width, font, and content invalidate it.private var codeLayoutsByRowId: [String: ReviewDiffCodeLayout] = [:]- private var codeLayoutWidth: CGFloat = 0+ private var codeLayoutWidth: CGFloat?private var codeLayoutFont: UIFont?private var codeDecorationVersion = 0+ private var rowPreparation: ReviewDiffRowPreparation?+ private var preparedRowGeometry: ReviewDiffRowGeometry?++ private var geometryConfiguration: ReviewDiffGeometryConfiguration {+ ReviewDiffGeometryConfiguration(+ style: style, viewportWidth: viewportWidth,+ collapsedFileIds: collapsedFileIds, collapsedCommentIds: collapsedCommentIds+ )+ }private var panStartHorizontalOffset: CGFloat = 0private var activePanFileId: String?private var activePanKind: ReviewDiffHorizontalPanKind?@@ -1095,19 +1210,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {/// Height before word wrap. Laid-out rows use height(at:), which includes wrapped lines.private func height(for row: ReviewDiffNativeRow) -> CGFloat {- if row.kind == "file" {- return style.fileHeaderHeight- }- if collapsedFileIds.contains(resolvedFileId(for: row)) {- return 0- }- if row.kind == "notice" {- return max(style.rowHeight * 2, 44)- }- if row.kind == "comment" {- return collapsedCommentIds.contains(row.id) ? 44 : 124- }- return style.rowHeight+ geometryConfiguration.height(for: row)}/// Laid-out height, including wrapped lines. Requires a layout built from the current rows.@@ -1141,111 +1244,174 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {)}- /// Shape new content on the existing decode worker before publishing rows to the UI.+ // Pixel offsets cannot identify the same code row after wrapping or font changes.+ func viewportRowAnchor() -> ReviewDiffViewportRowAnchor? {+ let top = max(0, verticalOffset + topContentInset)+ guard let index = rowIndex(at: top) else { return nil }+ return ReviewDiffViewportRowAnchor(rowIndex: index, intraRowOffset: top - rowOffsets[index])+ }++ func offset(for anchor: ReviewDiffViewportRowAnchor) -> CGFloat? {+ guard let frame = frameForRow(at: anchor.rowIndex), frame.height > 0 else { return nil }+ let intraRowOffset = anchor.intraRowOffset < frame.height+ ? anchor.intraRowOffset : max(0, frame.height - 1)+ return frame.minY + intraRowOffset+ }++ func cancelRowPreparation() {+ rowPreparation?.cancel()+ rowPreparation = nil+ preparedRowGeometry = nil+ }++ /// Prepare immutable geometry on the decode worker; publication only swaps its buffers.func prepareRows(_ rows: [ReviewDiffNativeRow],on queue: DispatchQueue,isCurrent: @escaping () -> Bool,completion: @escaping () -> Void) {+ cancelRowPreparation()+ let preparation = ReviewDiffRowPreparation()+ rowPreparation = preparation+ let configuration = geometryConfigurationlet font = codeFontlet characterWidth = monospaceCharacterWidth(font: font)- guard let width = codeLayoutWidthLimit(font: font) else {- completion()- return- }+ let width = codeLayoutWidthLimit(font: font)+ let hunkFont = self.hunkFontlet cached = codeLayoutWidth == width && codeLayoutFont == font ? codeLayoutsByRowId : [:]+ let input = ReviewDiffRowGeometryInput(+ configuration: configuration, font: font, hunkFont: hunkFont,+ characterWidth: characterWidth, layoutWidth: width, cached: cached+ )queue.async { [weak self] in- var layouts: [String: ReviewDiffCodeLayout] = [:]- for row in rows where row.kind == "line" {- guard let text = row.content else { continue }- if let previous = cached[row.id], previous.text == text {- layouts[row.id] = previous- } else {- layouts[row.id] = ReviewDiffCodeLayout(text: text, font: font, width: width, characterWidth: characterWidth)- }- }+ guard let geometry = Self.buildRowGeometry(+ rows, input: input, isCancelled: { preparation.isCancelled }+ ) else { return }DispatchQueue.main.async { [weak self] in- guard let self, isCurrent() else { return }- if self.codeFont != font || self.codeLayoutWidthLimit(font: font) != width {+ guard let self, !preparation.isCancelled, isCurrent() else { return }+ if self.geometryConfiguration != configuration {self.prepareRows(rows, on: queue, isCurrent: isCurrent, completion: completion)return}+ self.rowPreparation = nilself.codeLayoutWidth = widthself.codeLayoutFont = font- self.codeLayoutsByRowId = layouts+ self.preparedRowGeometry = geometrycompletion()}}}private func rebuildRowLayout() {+ let font = codeFont+ let characterWidth = monospaceCharacterWidth(font: font)+ let layoutWidth = codeLayoutWidthLimit(font: font)+ let cached = codeLayoutWidth == layoutWidth && codeLayoutFont == font ? codeLayoutsByRowId : [:]+ let input = ReviewDiffRowGeometryInput(+ configuration: geometryConfiguration, font: font, hunkFont: hunkFont,+ characterWidth: characterWidth, layoutWidth: layoutWidth, cached: cached+ )+ guard let geometry = Self.buildRowGeometry(rows, input: input) else { return }+ codeLayoutWidth = layoutWidth+ codeLayoutFont = font+ applyRowGeometry(geometry)+ }++ private static func buildRowGeometry(+ _ rows: [ReviewDiffNativeRow],+ input: ReviewDiffRowGeometryInput,+ isCancelled: () -> Bool = { false }+ ) -> ReviewDiffRowGeometry? {var nextOffsets: [CGFloat] = []var nextFileHeaderRowIndices: [Int] = []nextOffsets.reserveCapacity(rows.count)var maxWidthsByFileId: [String: CGFloat] = [:]var nextCodeLayouts: [String: ReviewDiffCodeLayout] = [:]var offset: CGFloat = 0- let font = codeFont- let characterWidth = monospaceCharacterWidth(font: font)- let layoutWidth = codeLayoutWidthLimit(font: font)- let wrapColumns = style.wordWrap ? layoutWidth.map { Int($0 / characterWidth) } : nil- if let layoutWidth, codeLayoutWidth != layoutWidth || codeLayoutFont != font {- codeLayoutsByRowId.removeAll()- codeLayoutWidth = layoutWidth- codeLayoutFont = font- }+ let style = input.configuration.style+ let characterWidth = input.characterWidth+ let wrapColumns = style.wordWrap ? input.layoutWidth.map { Int($0 / characterWidth) } : nilfor (index, row) in rows.enumerated() {+ // Bound obsolete work without locking once per row; never read UIView state here.+ if index.isMultiple(of: 256), isCancelled() { return nil }nextOffsets.append(offset)if row.kind == "file" {nextFileHeaderRowIndices.append(index)}- var rowHeight = height(for: row)-- let fileId = resolvedFileId(for: row)+ var rowHeight = input.configuration.height(for: row)+ let fileId = row.resolvedFileIdswitch row.kind {case "line":- // UTF-16 columns match the word diff ranges and the segments drawCodeLines draws.- var width = CGFloat(row.content?.utf16.count ?? 0) * characterWidth- if let layoutWidth, let content = row.content {- let cached = codeLayoutsByRowId[row.id]- let layout: ReviewDiffCodeLayout- if let cached, cached.text == content {- layout = cached- } else {- layout = ReviewDiffCodeLayout(- text: content, font: font, width: layoutWidth, characterWidth: characterWidth- )- }- nextCodeLayouts[row.id] = layout- // Tabs and fallback glyphs are wider than one column.- width = layout.usedWidth- if rowHeight > 0 {- rowHeight = max(rowHeight, layout.firstLineHeight) + layout.extraHeight- }- }+ let width = lineWidth(+ for: row, input: input, wrapColumns: wrapColumns,+ height: &rowHeight, layouts: &nextCodeLayouts+ )maxWidthsByFileId[fileId] = max(maxWidthsByFileId[fileId] ?? 0, width)case "hunk":- // Hunk context can hold tabs and draws in its own font, so measure what drawHunkRow draws.- maxWidthsByFileId[fileId] = max(- maxWidthsByFileId[fileId] ?? 0,- textWidth(row.text ?? "", font: hunkFont)- )+ // Hunk context can hold tabs and draws in its own font.+ let width = ceil(((row.text ?? "") as NSString).size(withAttributes: [.font: input.hunkFont, .ligature: 0]).width)+ maxWidthsByFileId[fileId] = max(maxWidthsByFileId[fileId] ?? 0, width)default:break}offset += rowHeight}+ guard !isCancelled() else { return nil }+ return ReviewDiffRowGeometry(+ offsets: nextOffsets, fileHeaderIndices: nextFileHeaderRowIndices,+ contentWidths: maxWidthsByFileId.mapValues { ceil($0) + style.codePadding * 2 },+ nativeLayouts: nextCodeLayouts, height: offset,+ characterWidth: characterWidth, wrapColumns: wrapColumns+ )+ }- codeCharacterWidth = characterWidth- codeWrapColumns = wrapColumns- codeLayoutsByRowId = nextCodeLayouts- // Measured widths are not capped, so the end of every line stays reachable by scrolling.- contentWidthsByFileId = maxWidthsByFileId.mapValues { ceil($0) + style.codePadding * 2 }- rowOffsets = nextOffsets- fileHeaderRowIndices = nextFileHeaderRowIndices- contentHeight = offset+ private static func lineWidth(+ for row: ReviewDiffNativeRow,+ input: ReviewDiffRowGeometryInput,+ wrapColumns: Int?,+ height: inout CGFloat,+ layouts: inout [String: ReviewDiffCodeLayout]+ ) -> CGFloat {+ let characterWidth = input.characterWidth+ let font = input.font+ var width = CGFloat(row.content?.utf16.count ?? 0) * characterWidth+ if let layoutWidth = input.layoutWidth, let content = row.content {+ if ReviewDiffCodeLayout.isPrintableASCII(content) {+ let length = content.utf8.count+ let starts = ReviewDiffCodeLineStarts(length: length, columns: wrapColumns)+ width = CGFloat(min(length, starts.columns)) * characterWidth+ if height > 0 {+ height = max(height, font.lineHeight) + CGFloat(starts.count - 1) * ceil(font.lineHeight)+ }+ } else {+ let layout: ReviewDiffCodeLayout+ if let previous = input.cached[row.id], previous.text == content {+ layout = previous+ } else {+ layout = ReviewDiffCodeLayout(+ text: content, font: font, width: layoutWidth, characterWidth: characterWidth+ )+ }+ layouts[row.id] = layout+ width = layout.usedWidth+ if height > 0 {+ height = max(height, layout.firstLineHeight) + layout.extraHeight+ }+ }+ }+ return width+ }++ private func applyRowGeometry(_ geometry: ReviewDiffRowGeometry) {+ codeCharacterWidth = geometry.characterWidth+ codeWrapColumns = geometry.wrapColumns+ codeLayoutsByRowId = geometry.nativeLayouts+ contentWidthsByFileId = geometry.contentWidths+ rowOffsets = geometry.offsets+ fileHeaderRowIndices = geometry.fileHeaderIndices+ contentHeight = geometry.height}private var codeFont: UIFont {@@ -1704,13 +1870,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {}private func resolvedFileId(for row: ReviewDiffNativeRow) -> String {- if let fileId = row.fileId {- return fileId- }- if let range = row.id.range(of: ":header") ?? row.id.range(of: ":hunk:") ?? row.id.range(of: ":line:") {- return String(row.id[..<range.lowerBound])- }- return row.filePath ?? row.id+ row.resolvedFileId}private func horizontalOffset(@@ -2325,9 +2485,11 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {let change = row.change ?? "context"// Wrapped rows keep the line number and first code line in the first row-height band.let layout = codeLayoutsByRowId[row.id]+ let firstLineHeight = layout?.firstLineHeight+ ?? (row.content != nil && codeLayoutWidth != nil ? codeFont.lineHeight : 0)let firstLineRect = CGRect(x: rect.minX, y: rect.minY, width: rect.width,- height: max(style.rowHeight, layout?.firstLineHeight ?? 0)+ height: max(style.rowHeight, firstLineHeight))rowBackground(for: change).setFill()context.fill(rect)@@ -2387,7 +2549,9 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {context.restoreGState()return}- let lineStarts = layout?.starts ?? [0]+ let lineStarts = ReviewDiffCodeLineStarts(+ length: (row.content ?? "").utf16.count, columns: codeWrapColumns+ )drawWordDiffRanges(row,lineStarts: lineStarts,@@ -2421,7 +2585,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {/// Draws the segment starting at each of the row's line starts on its own visual line.private func drawCodeLines(length: Int,- lineStarts: [Int],+ lineStarts: ReviewDiffCodeLineStarts,firstLineRect: CGRect,draw: (NSRange, CGRect) -> Void) {@@ -2455,7 +2619,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {private func drawWordDiffRanges(_ row: ReviewDiffNativeRow,- lineStarts: [Int],+ lineStarts: ReviewDiffCodeLineStarts,firstLineRect: CGRect,context: CGContext,horizontalOffset: CGFloatdiff --git a/apps/mobile/modules/t3-review-diff/tests/android/.gitignore b/apps/mobile/modules/t3-review-diff/tests/android/.gitignorenew file mode 100644index 00000000000..67bcc2f7272--- /dev/null+++ b/apps/mobile/modules/t3-review-diff/tests/android/.gitignore@@ -0,0 +1,2 @@+.gradle/+build/diff --git a/apps/mobile/modules/t3-review-diff/tests/android/README.md b/apps/mobile/modules/t3-review-diff/tests/android/README.mdnew file mode 100644index 00000000000..4211691134d--- /dev/null+++ b/apps/mobile/modules/t3-review-diff/tests/android/README.md@@ -0,0 +1,33 @@+# Android native regressions++From the repository root:++```sh+apps/mobile/modules/t3-review-diff/tests/run-android.sh+```++Requires JDK 17+ (`JAVA_HOME`) and Gradle on `PATH`. Tested with JDK 17 and+Gradle 9.4.1. To use another installed Gradle or a wrapper, set+`GRADLE=/absolute/path/to/gradle` before the command. The runner resolves its own+location, so it also works from other directories. Gradle test options are+forwarded, for example `--tests '*ReviewDiffViewportTest' --rerun-tasks`.++This standalone JVM build registers the viewport and geometry regressions and the+module's existing `android/src/test` layout suite with Gradle's `test` task. It+compiles the module's actual Android view, drawing, and layout sources. Pinned Maven dependencies supply Kotlin, Robolectric, Android API 35,+and AndroidX test classes. The first run requires access to Maven Central and+Google Maven, including Robolectric's runtime SDK download. No local Android+SDK, Expo prebuild, device, temporary checkout, or pre-extracted jars are needed.+Generated files stay in ignored `build/` and `.gradle/` directories; the HTML+report is `build/reports/tests/test/index.html`.++The three files under `stubs/expo/modules/kotlin/` replace only Expo's context, view base class, and event+dispatcher. Events go to a per-test context instead of a React Native bridge.+This checks reset/decode ordering, stale-row removal, and viewport publication+in the real view, but does not validate Expo registration, JS event delivery,+native libraries, or device rendering. These stubs are exclusive to this+standalone build and must not be added to the production Android source set.+Geometry regressions bound sticky-header row reads, check lazy ASCII layout+retention and syntax invalidation, and compare ASCII widths against Android+paint metrics. Native shaping tests cover tabs, Unicode clusters, and styled+word-diff spans.diff --git a/apps/mobile/modules/t3-review-diff/tests/android/build.gradle b/apps/mobile/modules/t3-review-diff/tests/android/build.gradlenew file mode 100644index 00000000000..fa067950ed0--- /dev/null+++ b/apps/mobile/modules/t3-review-diff/tests/android/build.gradle@@ -0,0 +1,77 @@+plugins { id 'java' }++repositories {+ mavenCentral()+ google()+}++configurations {+ compiler+ androidTestAars+}++dependencies {+ compiler 'org.jetbrains.kotlin:kotlin-compiler-embeddable:2.2.21'+ testImplementation 'org.jetbrains.kotlin:kotlin-stdlib:2.2.21'+ testImplementation 'junit:junit:4.13.2'+ testImplementation('org.robolectric:robolectric:4.16.1') {+ exclude group: 'androidx.test', module: 'monitor'+ exclude group: 'androidx.test.espresso', module: 'espresso-idling-resource'+ }+ // Compile against the same API used by @Config(sdk = [35]), without a local Android SDK.+ testImplementation 'org.robolectric:android-all:15-robolectric-12650502'+ androidTestAars 'androidx.test:monitor:1.8.0@aar'+ androidTestAars 'androidx.test.espresso:espresso-idling-resource:3.7.0@aar'+ testImplementation files(layout.buildDirectory.dir('android-test-jars').map {+ fileTree(it) { include '**/*.jar' }+ })+}++// The JVM plugin cannot load classes.jar inside AndroidX AAR dependencies.+tasks.register('extractAndroidTestJars') {+ inputs.files configurations.androidTestAars+ outputs.dir layout.buildDirectory.dir('android-test-jars')+ doLast {+ configurations.androidTestAars.each { aar ->+ copy {+ from zipTree(aar)+ include 'classes.jar'+ filePermissions { unix('644') }+ into layout.buildDirectory.dir("android-test-jars/${aar.name}")+ }+ }+ }+}++def moduleRoot = file('../..')+def sources = files(+ fileTree('stubs') { include '**/*.kt' },+ fileTree('src/test/kotlin') { include '**/*.kt' },+ fileTree("${moduleRoot}/android/src/test/java") { include '**/*.kt' },+ fileTree("${moduleRoot}/android/src/main/java/expo/modules/t3reviewdiff") {+ include '**/*.kt'+ exclude '**/T3ReviewDiffModule.kt'+ },+)++tasks.register('compileRegression', JavaExec) {+ dependsOn 'extractAndroidTestJars'+ classpath = configurations.compiler+ mainClass = 'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler'+ inputs.files sources, configurations.testCompileClasspath+ outputs.dir layout.buildDirectory.dir('regression')+ doFirst {+ args = [+ '-no-stdlib', '-no-reflect', '-jvm-target', '17',+ '-classpath', configurations.testCompileClasspath.asPath,+ '-d', layout.buildDirectory.dir('regression').get().asFile.absolutePath,+ ] + sources.files.collect { it.absolutePath }+ }+}++test {+ dependsOn 'compileRegression'+ testClassesDirs = files(layout.buildDirectory.dir('regression'))+ classpath = files(testClassesDirs, configurations.testRuntimeClasspath)+ testLogging { events 'passed', 'failed'; exceptionFormat 'full' }+}diff --git a/apps/mobile/modules/t3-review-diff/tests/android/settings.gradle b/apps/mobile/modules/t3-review-diff/tests/android/settings.gradlenew file mode 100644index 00000000000..8fc37a9c434--- /dev/null+++ b/apps/mobile/modules/t3-review-diff/tests/android/settings.gradle@@ -0,0 +1 @@+rootProject.name = 't3-review-diff-viewport-tests'diff --git a/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.ktnew file mode 100644index 00000000000..d6b4c745639--- /dev/null+++ b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt@@ -0,0 +1,244 @@+package expo.modules.t3reviewdiff++import android.graphics.Color+import android.view.View+import kotlin.math.ceil+import expo.modules.kotlin.AppContext+import org.junit.Assert.assertEquals+import org.junit.Assert.assertSame+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35], manifest = Config.NONE)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class ReviewDiffGeometryTest {+ @Test+ fun geometryChangesKeepTheVisibleRowAndClampWithinShortenedRows() {+ val parent = T3ReviewDiffView(RuntimeEnvironment.getApplication(), AppContext())+ val canvas = parent.getChildAt(0)+ val spec = View.MeasureSpec.makeMeasureSpec(390, View.MeasureSpec.EXACTLY)+ canvas.measure(spec, spec)+ canvas.layout(0, 0, 390, 600)+ try {+ val rows = listOf("highlights.c", "simd128.h").flatMap { file ->+ listOf(row("$file:header", "").copy(kind = "file", fileId = file)) ++ List(100) { line ->+ row("$file:line:$line", "long native code ".repeat(line % 9 + 1)).copy(fileId = file)+ }+ }+ call(canvas, "setRows", rows)+ val index = 130+ fun position(intra: Int) {+ call(canvas, "setVerticalOffset", (call(canvas, "rowTop", index) as Int) + intra)+ }+ fun assertPosition(intra: Int, reason: String) {+ val top = call(canvas, "verticalOffset") as Int+ assertEquals("$reason: visible row/file changed", index, call(canvas, "rowIndexAt", top))+ assertEquals(+ "$reason: intra-row position changed",+ intra,+ top - (call(canvas, "rowTop", index) as Int)+ )+ }+ position(7)+ call(parent, "scrollToY", 0, true)+ val scroller = field(parent, "verticalScroller") as android.widget.OverScroller+ assertTrue(!scroller.isFinished)+ parent.setStyleJson("{\"wordWrap\":true}")+ assertPosition(7, "wrap on")+ assertTrue(+ "Geometry correction must stop the old absolute scroll trajectory",+ scroller.isFinished+ )+ parent.computeScroll()+ assertPosition(7, "after interrupted animation")+ parent.setStyleJson("{\"wordWrap\":true,\"codeFontSize\":22}")+ assertPosition(7, "font change")+ canvas.layout(0, 0, 280, 600)+ assertPosition(7, "wrapped width change")+ val height =+ (call(canvas, "rowTop", index + 1) as Int) - (call(canvas, "rowTop", index) as Int)+ position(height - 2)+ parent.setStyleJson("{\"wordWrap\":false,\"rowHeight\":24}")+ val shorterHeight =+ (call(canvas, "rowTop", index + 1) as Int) - (call(canvas, "rowTop", index) as Int)+ assertPosition(shorterHeight - 1, "unwrap clamps inside shortened row")+ parent.setContentResetKey("new-content")+ parent.setStyleJson("{\"wordWrap\":true}")+ assertEquals(0, call(canvas, "verticalOffset"))+ } finally {+ parent.cleanup()+ }+ }++ @Test+ fun stickyHeadersUseTheHeaderIndexAndKeepPushOffAndHitTesting() {+ val parent = T3ReviewDiffView(RuntimeEnvironment.getApplication(), AppContext())+ val canvas = parent.getChildAt(0)+ val spec = View.MeasureSpec.makeMeasureSpec(320, View.MeasureSpec.EXACTLY)+ canvas.measure(spec, spec)+ canvas.layout(0, 0, 320, 320)+ try {+ val rows = CountingRows(+ List(10000) { index ->+ row("row:$index", "const value = $index").copy(+ kind = if (index == 100 || index == 9000) "file" else "line",+ fileId = if (index < 9000) "first" else "second",+ )+ }+ )+ call(canvas, "setRows", rows)+ assertEquals(null, call(canvas, "stickyFileHeader", 0))+ val nextTop = call(canvas, "rowTop", 9000) as Int+ call(canvas, "setVerticalOffset", nextTop - 10)+ rows.reads = 0+ val sticky = requireNotNull(call(canvas, "stickyFileHeader", 8999))+ assertEquals(100, field(sticky, "index"))+ assertEquals(10, field(sticky, "bottom"))+ assertTrue("sticky lookup must not scan code rows: ${rows.reads}", rows.reads < 10)+ val hit = requireNotNull(call(canvas, "rowHitAt", 5f))+ assertEquals("row:100", (field(hit, "row") as DiffRow).id)+ val second = requireNotNull(call(canvas, "stickyFileHeader", 9000))+ assertEquals(9000, field(second, "index"))+ call(canvas, "setRows", listOf(row("only", "value")))+ assertEquals(null, call(canvas, "stickyFileHeader", 0))+ } finally {+ parent.cleanup()+ }+ }++ @Test+ fun asciiSyntaxArrivalDoesNotRebuildWrappedOffsetsOrRetainPerRowLayouts() {+ val parent = T3ReviewDiffView(RuntimeEnvironment.getApplication(), AppContext())+ val canvas = parent.getChildAt(0)+ val spec = View.MeasureSpec.makeMeasureSpec(320, View.MeasureSpec.EXACTLY)+ canvas.measure(spec, spec)+ canvas.layout(0, 0, 320, 320)+ try {+ call(canvas, "setStyle", DiffStyle.defaults(1f).copy(wordWrap = true))+ val rows = List(10000) { row("row:$it", "const value = 123; ".repeat(10)) }+ call(canvas, "setRows", rows)+ val offsets = field(canvas, "rowOffsets")+ call(+ canvas,+ "setTokensByRowId",+ mapOf(rows[0].id to listOf(DiffToken(rows[0].content, 0xff008800.toInt(), 2)))+ )+ assertSame("ASCII syntax must only repaint", offsets, field(canvas, "rowOffsets"))+ val drawing = requireNotNull(field(canvas, "drawing"))+ val cache = requireNotNull(field(drawing, "codeLayouts"))+ assertEquals(+ "offscreen ASCII must not retain layout objects",+ 0,+ (field(cache, "entries") as Map<*, *>).size+ )+ } finally {+ parent.cleanup()+ }+ }++ @Test+ fun asciiWidthCacheDoesNotRetainPerRowMeasurementObjects() {+ val drawing = ReviewDiffCanvasDrawing(RuntimeEnvironment.getApplication())+ val rows = List(10000) { row("row:$it", "const value = $it") }+ drawing.contentWidth(rows, emptyMap(), DiffStyle.defaults(1f))+ assertEquals(0, (field(drawing, "widthEntries") as Map<*, *>).size)+ }++ @Test+ fun asciiWidthMatchesPaintForEverySyntaxFontAndWeight() {+ val drawing = ReviewDiffCanvasDrawing(RuntimeEnvironment.getApplication())+ val content = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ" ++ "[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"+ val row = row("ascii", content)+ for (weight in listOf("regular", "medium", "bold")) {+ val style = DiffStyle.defaults(1f).copy(codeFontWeight = weight, codeFontSizePx = 17f)+ for (fontStyle in 0..7) {+ drawing.configureCodePaint(Color.RED, fontStyle, style)+ val expected = ceil(+ style.changeBarWidthPx + style.gutterWidthPx + style.codePaddingPx * 2f ++ drawing.textPaint.measureText(content),+ ).toInt()+ val tokens = mapOf(row.id to listOf(DiffToken(content, Color.RED, fontStyle)))+ assertEquals(+ "weight=$weight style=$fontStyle",+ expected,+ drawing.contentWidth(listOf(row), tokens, style)+ )+ val recolored = mapOf(row.id to listOf(DiffToken(content, Color.BLUE, fontStyle xor 4)))+ assertEquals(false, drawing.tokensChangeWidth(tokens, recolored, style))+ }+ }+ }++ @Test+ fun lazyAsciiHeightAndLineStartsMatchTheExistingLayoutAtEveryBoundary() {+ val drawing = ReviewDiffCanvasDrawing(RuntimeEnvironment.getApplication())+ val style = DiffStyle.defaults(1f).copy(wordWrap = true, codeFontSizePx = 17f)+ drawing.configureCodePaint(Color.BLACK, 0, style)+ val paint = android.text.TextPaint(drawing.textPaint)+ val cache = CodeLayoutCache()+ for (width in listOf(120, 180, 280, 420)) {+ for (length in listOf(0, 1, 13, 14, 15, 1000)) {+ val row = row("ascii", "a".repeat(length))+ val expected = createCodeLines(row.content, paint, width)+ val wrapped = cache.layout(+ listOf(row),+ emptyMap(),+ paint,+ style,+ DiffTheme.fallback("light"),+ width+ )+ assertTrue(expected.starts.contentEquals(wrapped.lines(row).starts))+ assertEquals(expected.firstHeight(24) + expected.extraHeight, wrapped.rowHeight(row, 24))+ }+ }+ }++ @Test+ fun unwrappedColorAndUnderlinePatchesDoNotReadOffscreenRows() {+ val parent = T3ReviewDiffView(RuntimeEnvironment.getApplication(), AppContext())+ val canvas = parent.getChildAt(0)+ try {+ val rows = CountingRows(List(10000) { row("row:$it", "const value = $it") })+ call(canvas, "setRows", rows)+ val content = rows[0].content+ rows.reads = 0+ call(canvas, "setTokensByRowId", mapOf("row:0" to listOf(DiffToken(content, Color.RED, 0))))+ call(canvas, "setTokensByRowId", mapOf("row:0" to listOf(DiffToken(content, Color.BLUE, 4))))+ assertEquals(0, rows.reads)+ } finally {+ parent.cleanup()+ }+ }++ private fun call(target: Any, name: String, vararg args: Any): Any? = target.javaClass+ .declaredMethods.single { it.name == name && it.parameterCount == args.size }+ .apply { isAccessible = true }.invoke(target, *args)++ private fun field(target: Any, name: String): Any? = target.javaClass.getDeclaredField(name)+ .apply { isAccessible = true }.get(target)++ private fun row(id: String, content: String) = DiffRow(+ kind = "line", id = id, fileId = "file", filePath = "test.ts", previousPath = null,+ changeType = "modified", additions = 1, deletions = 0, text = "", content = content,+ change = "add", oldLineNumber = null, newLineNumber = 1, wordDiffRanges = emptyList(),+ commentText = "", commentRangeLabel = "", commentSectionTitle = "",+ )++ private class CountingRows(private val rows: List<DiffRow>) : AbstractList<DiffRow>() {+ var reads = 0+ override val size: Int get() = rows.size+ override fun get(index: Int): DiffRow {+ reads += 1+ return rows[index]+ }+ }+}diff --git a/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffViewportTest.kt b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffViewportTest.ktnew file mode 100644index 00000000000..28935a11db8--- /dev/null+++ b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffViewportTest.kt@@ -0,0 +1,156 @@+package expo.modules.t3reviewdiff++import android.app.Activity+import android.graphics.Bitmap+import android.graphics.Canvas+import android.os.Looper+import android.view.View+import expo.modules.kotlin.AppContext+import java.util.concurrent.AbstractExecutorService+import java.util.concurrent.TimeUnit+import org.json.JSONArray+import org.json.JSONObject+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35], manifest = Config.NONE)+class ReviewDiffViewportTest {+ @Test+ fun resetDiscardsOldRowsAndPendingDecodeBeforePublishingTheNewDestination() {+ val activity = Robolectric.buildActivity(Activity::class.java).setup().get()+ val appContext = AppContext()+ val view = T3ReviewDiffView(activity, appContext)+ val decoder = ManualDecoder()+ view.javaClass.getDeclaredField("payloadDecodeExecutor").apply { isAccessible = true }+ .set(view, decoder)+ activity.setContentView(view)+ val canvas = view.getChildAt(0)+ val measure = View.MeasureSpec.makeMeasureSpec(320, View.MeasureSpec.EXACTLY)+ canvas.measure(measure, measure)+ canvas.layout(0, 0, 320, 320)+ val bitmap = Bitmap.createBitmap(320, 320, Bitmap.Config.ARGB_8888)+ try {+ view.setInitialFileId("old-selected")+ view.setRowsJson(rows("old-selected"))+ decoder.completeNext()+ canvas.draw(Canvas(bitmap))+ assertEquals(900, ranges(appContext).first()["firstRowIndex"])+ appContext.events.clear()++ // This decode belongs to the old content, but completes after the reset.+ view.setRowsJson(rows("old-selected"))+ view.setContentResetKey("new-content")+ view.setInitialFileId("new-selected")+ canvas.draw(Canvas(bitmap))+ assertTrue(+ "reset must not publish the previous payload's top range",+ ranges(appContext).isEmpty()+ )+ assertEquals(0, rowTop(canvas, 1))+ decoder.completeNext()+ canvas.draw(Canvas(bitmap))+ assertTrue(+ "a stale decode must not restore old rows or publish a range",+ ranges(appContext).isEmpty()+ )+ assertEquals(0, rowTop(canvas, 1))++ view.setRowsJson(rows("new-selected"))+ decoder.completeNext()+ canvas.draw(Canvas(bitmap))+ assertEquals(1, ranges(appContext).size)+ assertEquals(900, ranges(appContext).single()["firstRowIndex"])+ assertEquals(1000, ranges(appContext).single()["totalRows"])+ } finally {+ view.cleanup()+ bitmap.recycle()+ activity.finish()+ appContext.events.clear()+ }+ }++ @Test+ fun decodedRowsWaitForTheReplacementFilePropBeforePublishingAViewport() {+ val activity = Robolectric.buildActivity(Activity::class.java).setup().get()+ val appContext = AppContext()+ val view = T3ReviewDiffView(activity, appContext)+ val decoder = ManualDecoder()+ view.javaClass.getDeclaredField("payloadDecodeExecutor").apply { isAccessible = true }+ .set(view, decoder)+ activity.setContentView(view)+ val canvas = view.getChildAt(0)+ val measure = View.MeasureSpec.makeMeasureSpec(320, View.MeasureSpec.EXACTLY)+ canvas.measure(measure, measure)+ canvas.layout(0, 0, 320, 320)+ try {+ view.setInitialFileId("old-selected")+ view.setRowsJson(rows("old-selected"))+ decoder.completeNext()+ appContext.events.clear()++ view.setContentResetKey("new-content")+ view.setRowsJson(rows("new-selected"))+ decoder.completeNext()+ // Other props can rebuild layout while the destination still names the old payload.+ view.setCollapsedFileIdsJson("[]")+ view.setStyleJson("{}")+ view.setInitialRowIndex(-1.0)+ assertTrue(+ "decoded rows must wait for a resolvable destination",+ ranges(appContext).isEmpty()+ )++ view.setInitialFileId("new-selected")+ assertEquals(900, ranges(appContext).single()["firstRowIndex"])+ assertEquals(1000, ranges(appContext).single()["totalRows"])+ } finally {+ view.cleanup()+ activity.finish()+ appContext.events.clear()+ }+ }++ private fun rowTop(canvas: View, index: Int): Int = canvas.javaClass+ .getDeclaredMethod("rowTop", Int::class.javaPrimitiveType).apply { isAccessible = true }+ .invoke(canvas, index) as Int++ private fun ranges(appContext: AppContext) = appContext.events+ .filter { (name, payload) -> name == "onDebug" && payload["message"] == "visible-range" }+ .map { it.second }++ private fun rows(selectedFileId: String): String = JSONArray().apply {+ for (index in 0 until 1000) {+ put(+ JSONObject().apply {+ put("id", "$selectedFileId:$index")+ put("kind", if (index == 0 || index == 900) "file" else "line")+ put("fileId", if (index < 900) "first-file" else selectedFileId)+ put("content", "const value = $index")+ }+ )+ }+ }.toString()++ private class ManualDecoder : AbstractExecutorService() {+ private val work = ArrayDeque<Runnable>()+ override fun execute(command: Runnable) {+ work.addLast(command)+ }+ fun completeNext() {+ work.removeFirst().run()+ shadowOf(Looper.getMainLooper()).idle()+ }+ override fun shutdown() = Unit+ override fun shutdownNow(): MutableList<Runnable> = mutableListOf()+ override fun isShutdown() = false+ override fun isTerminated() = false+ override fun awaitTermination(timeout: Long, unit: TimeUnit) = true+ }+}diff --git a/apps/mobile/modules/t3-review-diff/tests/android/stubs/expo/modules/kotlin/AppContext.kt b/apps/mobile/modules/t3-review-diff/tests/android/stubs/expo/modules/kotlin/AppContext.ktnew file mode 100644index 00000000000..88a47d2d2ed--- /dev/null+++ b/apps/mobile/modules/t3-review-diff/tests/android/stubs/expo/modules/kotlin/AppContext.kt@@ -0,0 +1,6 @@+package expo.modules.kotlin++// Per-view event sink for the isolated JVM harness; no React Native bridge is loaded.+class AppContext {+ val events = mutableListOf<Pair<String, Map<String, Any>>>()+}diff --git a/apps/mobile/modules/t3-review-diff/tests/android/stubs/expo/modules/kotlin/viewevent/EventDispatcher.kt b/apps/mobile/modules/t3-review-diff/tests/android/stubs/expo/modules/kotlin/viewevent/EventDispatcher.ktnew file mode 100644index 00000000000..fff408e4c5e--- /dev/null+++ b/apps/mobile/modules/t3-review-diff/tests/android/stubs/expo/modules/kotlin/viewevent/EventDispatcher.kt@@ -0,0 +1,15 @@+package expo.modules.kotlin.viewevent++import expo.modules.kotlin.views.ExpoView+import kotlin.properties.ReadOnlyProperty+import kotlin.reflect.KProperty++@Suppress("FunctionName")+fun ExpoView.EventDispatcher() = object : ReadOnlyProperty<ExpoView, (Map<String, Any>) -> Unit> {+ override fun getValue(+ thisRef: ExpoView,+ property: KProperty<*>+ ): (Map<String, Any>) -> Unit = { payload ->+ thisRef.appContext.events.add(property.name to payload)+ }+}diff --git a/apps/mobile/modules/t3-review-diff/tests/android/stubs/expo/modules/kotlin/views/ExpoView.kt b/apps/mobile/modules/t3-review-diff/tests/android/stubs/expo/modules/kotlin/views/ExpoView.ktnew file mode 100644index 00000000000..d65b9f412ab--- /dev/null+++ b/apps/mobile/modules/t3-review-diff/tests/android/stubs/expo/modules/kotlin/views/ExpoView.kt@@ -0,0 +1,7 @@+package expo.modules.kotlin.views++import android.content.Context+import android.widget.FrameLayout+import expo.modules.kotlin.AppContext++open class ExpoView(context: Context, val appContext: AppContext) : FrameLayout(context)diff --git a/apps/mobile/modules/t3-review-diff/tests/ios/anchor.swift b/apps/mobile/modules/t3-review-diff/tests/ios/anchor.swiftnew file mode 100644index 00000000000..40bde07fc5b--- /dev/null+++ b/apps/mobile/modules/t3-review-diff/tests/ios/anchor.swift@@ -0,0 +1,53 @@+// Exercise the real UIScrollView/geometry update path with a preceding large file.+private extension T3ReviewDiffView {+ func checkRowAnchoring() throws {+ frame = CGRect(x: 0, y: 0, width: 390, height: 600)+ layoutSubviews()+ setContentInsetTop(80)+ let fixture = ["highlights.c", "simd128.h"].flatMap { file in+ [["kind": "file", "id": "\(file):header", "fileId": file]] + (0..<100).map { line in+ ["kind": "line", "id": "\(file):line:\(line)", "fileId": file,+ "content": String(repeating: "long native code ", count: line % 9 + 1)]+ }+ }+ rows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: JSONSerialization.data(withJSONObject: fixture))+ contentView.rows = rows+ updateContentMetrics()+ let index = 130+ func position(_ intra: CGFloat) {+ setVerticalContentOffset(contentView.frameForRow(at: index)!.minY + intra, animated: false)+ }+ func assertPosition(_ intra: CGFloat, _ reason: String) {+ let frame = contentView.frameForRow(at: index)!+ let top = scrollView.contentOffset.y + scrollView.contentInset.top+ check(top >= frame.minY && top < frame.maxY, "\(reason): visible row/file changed across geometry update")+ check(abs(top - frame.minY - intra) < 0.01, "\(reason): intra-row position changed")+ check(contentView.verticalOffset == scrollView.contentOffset.y, "Viewport and UIScrollView must agree")+ }+ position(7)+ isProgrammaticScrollActive = true+ contentView.isVerticalScrollActive = true+ setStyleJson("{\"wordWrap\":true}")+ assertPosition(7, "wrap on")+ check(!isProgrammaticScrollActive && !contentView.isVerticalScrollActive,+ "Anchor restoration must finish an interrupted programmatic scroll")+ setStyleJson("{\"wordWrap\":true,\"codeFontSize\":22}")+ assertPosition(7, "font change")+ frame.size.width = 280+ layoutSubviews()+ assertPosition(7, "wrapped width change")+ position(contentView.frameForRow(at: index)!.height - 2)+ setStyleJson("{\"wordWrap\":false,\"rowHeight\":24}")+ let height = contentView.frameForRow(at: index)!.height+ assertPosition(height - 1, "unwrap clamps inside shortened row")+ setInitialFileId("simd128.h")+ layoutSubviews()+ check(abs(scrollView.contentOffset.y + scrollView.contentInset.top - contentView.fileHeaderOffset(forFileId: "simd128.h")!) < 0.01,+ "Explicit initial-file navigation must win over geometry anchoring")+ setContentResetKey("new-content")+ setStyleJson("{\"wordWrap\":true}")+ check(rows.isEmpty && scrollView.contentOffset.y == -80, "Reset must discard the old anchor")+ print("Passed viewport row anchors for wrap, font, width, intra-row clamp, initial file, and reset")+ }+}+try T3ReviewDiffView().checkRowAnchoring()diff --git a/apps/mobile/modules/t3-review-diff/tests/ios/geometry.swift b/apps/mobile/modules/t3-review-diff/tests/ios/geometry.swiftnew file mode 100644index 00000000000..bd213f694f0--- /dev/null+++ b/apps/mobile/modules/t3-review-diff/tests/ios/geometry.swift@@ -0,0 +1,137 @@+// Geometry tests exercise the production content view without an Expo app or device.+private extension ReviewDiffContentView {+ func checkSparseGeometry(expectedNativeRows: Int) {+ check(codeLayoutsByRowId.count == expectedNativeRows,+ "Offscreen ASCII must not retain per-row layout objects or wrap-start arrays (retained \(codeLayoutsByRowId.count))")+ }++ func checkReferenceGeometry() {+ let font = codeFont+ let characterWidth = monospaceCharacterWidth(font: font)+ let width = codeLayoutWidthLimit(font: font)+ var offset: CGFloat = 0+ var widths: [String: CGFloat] = [:]+ for (index, row) in rows.enumerated() {+ check(rowOffsets[index] == offset, "Wrapped offsets changed for \(row.id)")+ var rowHeight = height(for: row)+ if row.kind == "line", let width, let content = row.content {+ let reference = ReviewDiffCodeLayout(text: content, font: font, width: width, characterWidth: characterWidth)+ if rowHeight > 0 {+ rowHeight = max(rowHeight, reference.firstLineHeight) + reference.extraHeight+ }+ widths[row.resolvedFileId] = max(widths[row.resolvedFileId] ?? 0, reference.usedWidth)+ } else if row.kind == "hunk" {+ widths[row.resolvedFileId] = max(widths[row.resolvedFileId] ?? 0, textWidth(row.text ?? "", font: hunkFont))+ }+ check(height(at: index) == rowHeight, "Row height changed for \(row.id)")+ if rowHeight > 0 {+ check(rowIndex(at: offset + rowHeight / 2) == index, "Hit testing must use the published wrapped offsets")+ }+ offset += rowHeight+ }+ check(contentHeight == offset, "Content height must include every row")+ check(contentWidthsByFileId == widths.mapValues { ceil($0) + style.codePadding * 2 },+ "The end of every unwrapped line must remain reachable")+ }++ func preparedOffsetAddress() -> UInt {+ guard let geometry = preparedRowGeometry else { fatalError("Geometry was not prepared") }+ return geometry.offsets.withUnsafeBufferPointer { UInt(bitPattern: $0.baseAddress) }+ }++ func checkPublishedOffsetAddress(_ address: UInt) {+ check(rowOffsets.withUnsafeBufferPointer { UInt(bitPattern: $0.baseAddress) } == address,+ "Publication must reuse the prepared offsets without rebuilding on the UI thread")+ }++ func checkCancellationInsideLoop() {+ var checks = 0+ let input = ReviewDiffRowGeometryInput(+ configuration: geometryConfiguration, font: codeFont, hunkFont: hunkFont,+ characterWidth: codeCharacterWidth, layoutWidth: codeLayoutWidthLimit(font: codeFont), cached: [:]+ )+ let geometry = Self.buildRowGeometry(+ rows, input: input, isCancelled: {+ checks += 1+ return checks == 2+ }+ )+ check(geometry == nil && checks == 2, "Obsolete work must abort at the next batch, before visiting every row")+ }+}++private let geometryRows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: JSONSerialization.data(withJSONObject:+ [["kind": "file", "id": "a:header", "fileId": "a"],+ ["kind": "hunk", "id": "a:hunk:0", "fileId": "a", "text": "@@ context\twith tabs @@"]] + (0..<4096).map { index in+ ["kind": "line", "id": "a:line:\(index)", "fileId": "a",+ "content": String(repeating: "printable ASCII ", count: index % 30), "newLineNumber": index + 1]+ } + [["kind": "line", "id": "a:unicode", "fileId": "a", "content": "漢字\t👨👩👧👦"],+ ["kind": "comment", "id": "a:comment", "fileId": "a"],+ ["kind": "file", "id": "b:header", "fileId": "b"],+ ["kind": "line", "id": "b:line:0", "fileId": "b", "content": "e\u{301}\tمرحبا"]]+))+private let geometryView = ReviewDiffContentView(frame: CGRect(x: 0, y: 0, width: 390, height: 844))+private func geometryStyle(wrap: Bool, fontSize: Int = 12, weight: String = "regular", rowHeight: Int = 24) throws -> ReviewDiffNativeStyle {+ let payload = try JSONDecoder().decode(ReviewDiffNativeStylePayload.self, from: Data(+ "{\"wordWrap\":\(wrap),\"codeFontSize\":\(fontSize),\"codeFontWeight\":\"\(weight)\",\"rowHeight\":\(rowHeight)}".utf8+ ))+ return ReviewDiffNativeStyle.resolve(payload)+}+geometryView.style = try geometryStyle(wrap: true)+geometryView.viewportWidth = 390+geometryView.rows = geometryRows+geometryView.checkSparseGeometry(expectedNativeRows: 2)+geometryView.checkReferenceGeometry()+geometryView.checkCancellationInsideLoop()+for width: CGFloat in [400, 280] {+ geometryView.viewportWidth = width+ geometryView.checkReferenceGeometry()+}+geometryView.collapsedFileIds = ["b"]+geometryView.collapsedCommentIds = ["a:comment"]+geometryView.checkReferenceGeometry()+geometryView.style = try geometryStyle(wrap: true, fontSize: 28, weight: "bold", rowHeight: 8)+geometryView.checkReferenceGeometry()+geometryView.style = try geometryStyle(wrap: false)+geometryView.checkReferenceGeometry()+geometryView.collapsedFileIds = []+geometryView.collapsedCommentIds = []+geometryView.style = try geometryStyle(wrap: true)+geometryView.checkReferenceGeometry()+let originalHeight = geometryView.contentHeight+geometryView.mergeTokensByRowId(["a:line:29": [ReviewDiffNativeToken(content: geometryRows[31].content ?? "", color: "#ff0000", fontStyle: 3)]])+geometryView.selectedRowIds = ["a:line:29"]+check(geometryView.contentHeight == originalHeight, "Tokens and selection must preserve geometry")++// Configuration changes before publication must restart preparation from a fresh snapshot.+private let geometryQueue = DispatchQueue(label: "review-diff.geometry-tests")+geometryQueue.suspend()+geometryView.prepareRows(geometryRows, on: geometryQueue, isCurrent: { true }, completion: {+ let address = geometryView.preparedOffsetAddress()+ geometryView.rows = geometryRows+ geometryView.checkPublishedOffsetAddress(address)+ geometryView.checkSparseGeometry(expectedNativeRows: 2)+ geometryView.checkReferenceGeometry()+ check(geometryView.style.codeFontSize == 28 && geometryView.viewportWidth == 400)++ // A reset/new payload can cancel work before its worker is scheduled, without publishing it.+ geometryQueue.suspend()+ geometryView.prepareRows(geometryRows, on: geometryQueue, isCurrent: { true }, completion: {+ check(false, "Cancelled geometry must never publish")+ })+ geometryView.rows = []+ geometryQueue.resume()+ geometryQueue.async {+ DispatchQueue.main.async {+ check(geometryView.rows.isEmpty && geometryView.contentHeight == 0, "Reset must remain empty after obsolete work drains")+ print("Passed sparse geometry, reference heights/widths, font/wrap/collapse, hit testing, direct publication, and cancellation")+ exit(0)+ }+ }+})+geometryView.style = try geometryStyle(wrap: true, fontSize: 28, weight: "bold", rowHeight: 8)+geometryView.viewportWidth = 400+geometryView.collapsedFileIds = ["b"]+geometryView.collapsedCommentIds = ["a:comment"]+geometryQueue.resume()+dispatchMain()diff --git a/apps/mobile/modules/t3-review-diff/tests/ios/main.swift b/apps/mobile/modules/t3-review-diff/tests/ios/main.swiftindex d8ce5420e09..974c3d72665 100644--- a/apps/mobile/modules/t3-review-diff/tests/ios/main.swift+++ b/apps/mobile/modules/t3-review-diff/tests/ios/main.swift@@ -77,7 +77,7 @@ for text in ["\t\t\"extends\": \"@riptech/tsconfig/tsconfig.test.json\",", "漢let unwrappedAscii = ReviewDiffCodeLayout(text: "const value = 123;", font: font, width: ReviewDiffCodeLayout.unboundedWidth, characterWidth: characterWidth)-check(unwrappedAscii.starts == [0] && unwrappedAscii.usedWidth == 18 * characterWidth)+check(Array(unwrappedAscii.starts) == [0] && unwrappedAscii.usedWidth == 18 * characterWidth)let ascii = String(repeating: "const value = 123; ", count: 100)let layout = ReviewDiffCodeLayout(text: ascii, font: font, width: 280, characterWidth: characterWidth)diff --git a/apps/mobile/modules/t3-review-diff/tests/run-android.sh b/apps/mobile/modules/t3-review-diff/tests/run-android.shnew file mode 100755index 00000000000..f62b0a02d01--- /dev/null+++ b/apps/mobile/modules/t3-review-diff/tests/run-android.sh@@ -0,0 +1,4 @@+#!/usr/bin/env bash+set -euo pipefail+tests_dir=$(cd "$(dirname "$0")" && pwd)+"${GRADLE:-gradle}" --project-dir "$tests_dir/android" test "$@"diff --git a/apps/mobile/modules/t3-review-diff/tests/run-ios.sh b/apps/mobile/modules/t3-review-diff/tests/run-ios.shindex 464ef0cf457..a8ecdd88947 100644--- a/apps/mobile/modules/t3-review-diff/tests/run-ios.sh+++ b/apps/mobile/modules/t3-review-diff/tests/run-ios.sh@@ -5,8 +5,32 @@ sdk=$(xcrun --sdk macosx --show-sdk-path)compiler=$(xcrun --find swiftc)output=$(mktemp -d)trap 'rm -rf "$output"' EXIT+# Keep the real content view and helpers; the Expo bridge is not needed by this harness.+python3 - "$module_dir" "$output/main.swift" <<'PYTHON'+import sys+from pathlib import Path+module = Path(sys.argv[1])+source = (module / "ios/T3ReviewDiffView.swift").read_text()+source = source.replace("import ExpoModulesCore\n", "")+stubs = """+public final class AppContext {}+open class ExpoView: UIView {+ public required init(appContext: AppContext? = nil) { super.init(frame: .zero) }+ @available(*, unavailable)+ public required init?(coder: NSCoder) { fatalError("init(coder:) is unused") }+}+final class EventDispatcher {+ func callAsFunction(_ payload: [String: Any]) {}+}+"""+# Expo alone is stubbed; keep the real scroll container as well as the content view.+Path(sys.argv[2]).write_text(source + "\n" + stubs + "\n"+ + (module / "tests/ios/main.swift").read_text() + "\n"+ + (module / "tests/ios/anchor.swift").read_text() + "\n"+ + (module / "tests/ios/geometry.swift").read_text())+PYTHON"$compiler" -O -target "$(uname -m)-apple-ios16.1-macabi" -sdk "$sdk" \-F "$sdk/System/iOSSupport/System/Library/Frameworks" \- "$module_dir/ios/ReviewDiffCodeLayout.swift" "$module_dir/tests/ios/main.swift" \+ "$module_dir/ios/ReviewDiffCodeLayout.swift" "$output/main.swift" \-o "$output/layout-tests""$output/layout-tests"diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts b/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.tsindex aa9275745ce..c418d528129 100644--- a/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts+++ b/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts@@ -1,13 +1,36 @@-import { describe, expect, it, vi } from "vite-plus/test";+import { afterEach, describe, expect, it, vi } from "vite-plus/test";++import { highlightCode } from "../../lib/highlights";import type { NativeReviewDiffRow } from "./nativeReviewDiffSurface";import type { NativeReviewDiffFile } from "./nativeReviewDiffTypes";import { highlightNativeReviewDiffVisibleRows } from "./nativeReviewDiffHighlighter";+import { buildNativeReviewDiffData } from "../review/nativeReviewDiffAdapter";+import { buildReviewParsedDiff } from "../review/reviewModel";++const tokenization = vi.hoisted(() => ({+ calls: [] as string[],+ afterCall: undefined as (() => void) | undefined,+}));vi.mock("expo", async () => {const { createWasmHighlightsModule } = await import("../../lib/highlights.testing");- const highlights = createWasmHighlightsModule();- return { requireOptionalNativeModule: () => highlights };+ const module = createWasmHighlightsModule();+ return {+ requireOptionalNativeModule: () => ({+ tokenize(code: string, language: number) {+ tokenization.calls.push(code);+ const records = module.tokenize(code, language);+ tokenization.afterCall?.();+ return records;+ },+ }),+ };+});++afterEach(() => {+ tokenization.calls = [];+ tokenization.afterCall = undefined;});const TYPESCRIPT_FILE: NativeReviewDiffFile = {@@ -54,7 +77,128 @@ function highlight(}describe("highlightNativeReviewDiffVisibleRows", () => {- it("does not carry grammar state across hunk boundaries", () => {+ it("keeps overscan within the visible files, including a file header at the viewport edge", async () => {+ const loadedFiles: string[] = [];+ const files = Array.from({ length: 14 }, (_, index) => {+ const id = `file-${index}`;+ const source = Array.from({ length: 3 }, (_, line) => `const value${line} = ${line};`);+ return {+ ...TYPESCRIPT_FILE,+ id,+ loadContents: async () => {+ loadedFiles.push(id);+ return { oldContents: "", newContents: source.join("\n") };+ },+ rows: [+ { kind: "file", id: `${id}-header`, fileId: id },+ ...source.map((content, line) => ({+ ...makeLine({+ id: `${id}-line-${line + 1}`,+ content,+ change: "add",+ oldLineNumber: null,+ newLineNumber: line + 1,+ }),+ fileId: id,+ })),+ ] satisfies NativeReviewDiffRow[],+ };+ });+ const input = {+ rows: files.flatMap((file) => file.rows),+ files,+ scheme: "dark" as const,+ firstRowIndex: 30,+ lastRowIndex: 32,+ };+ const viewport = await highlightNativeReviewDiffVisibleRows({ ...input, overscanRows: 0 });+ const visibleIds = ["file-7-line-2", "file-7-line-3"];+ expect(Object.keys(viewport.tokensByRowId)).toEqual(visibleIds);+ const overscan = await highlightNativeReviewDiffVisibleRows({+ ...input,+ overscanRows: 160,+ alreadyHighlightedRowIds: new Set(visibleIds),+ });+ expect(Object.keys(overscan.tokensByRowId).sort()).toEqual([+ "file-7-line-1",+ "file-8-line-1",+ "file-8-line-2",+ "file-8-line-3",+ ]);+ for (const tokens of Object.values({ ...viewport.tokensByRowId, ...overscan.tokensByRowId })) {+ expect(tokens.some((token) => token.color !== null)).toBe(true);+ }+ expect([...new Set(loadedFiles)].sort()).toEqual(["file-7", "file-8"]);+ });++ it("delivers the dominant viewport file before fetching a smaller blocked neighbor", async () => {+ const neighborStarted = Promise.withResolvers<void>();+ const neighborResponse = Promise.withResolvers<{ oldContents: string; newContents: string }>();+ const source = Array.from({ length: 27 }, (_, index) => `const value${index} = true;`).join(+ "\n",+ );+ const chunks = vi.fn();+ const rows = [+ ...Array.from({ length: 5 }, (_, index) => ({+ ...makeLine({+ id: `neighbor-${index}`,+ content: `const value${index} = true;`,+ change: "add",+ oldLineNumber: null,+ newLineNumber: index + 1,+ }),+ fileId: "neighbor",+ })),+ ...Array.from({ length: 27 }, (_, index) =>+ makeLine({+ id: `selected-${index}`,+ content: `const value${index} = true;`,+ change: "delete",+ oldLineNumber: index + 1,+ newLineNumber: null,+ }),+ ),+ ];+ const highlighting = highlightNativeReviewDiffVisibleRows({+ rows,+ files: [+ {+ ...TYPESCRIPT_FILE,+ id: "neighbor",+ loadContents: () => {+ neighborStarted.resolve();+ return neighborResponse.promise;+ },+ },+ {+ ...TYPESCRIPT_FILE,+ loadContents: async () => ({ oldContents: source, newContents: "" }),+ },+ ],+ scheme: "dark",+ firstRowIndex: 0,+ lastRowIndex: rows.length - 1,+ overscanRows: 0,+ onChunk: chunks,+ });+ try {+ await neighborStarted.promise;+ expect(chunks).toHaveBeenCalledTimes(1);+ expect(Object.keys(chunks.mock.calls[0]![0].tokensByRowId)).toEqual(+ Array.from({ length: 27 }, (_, index) => `selected-${index}`),+ );+ expect(+ chunks.mock.calls[0]![0].tokensByRowId["selected-0"].some(+ (token: { color: string | null }) => token.color !== null,+ ),+ ).toBe(true);+ } finally {+ neighborResponse.resolve({ oldContents: "", newContents: source });+ await highlighting;+ }+ });++ it("does not carry grammar state across hunk boundaries", async () => {const exportRow = makeLine({id: "export-row",content: "export async function run() {}",@@ -65,23 +209,32 @@ describe("highlightNativeReviewDiffVisibleRows", () => {const rows = [makeHunk("hunk-1"),makeLine({- id: "template-open",- content: "const message = `open",+ id: "import-open",+ content: "import {",change: "context",oldLineNumber: 1,newLineNumber: 1,}),+ makeLine({+ id: "import-entry",+ content: " Model,",+ change: "context",+ oldLineNumber: 2,+ newLineNumber: 2,+ }),makeHunk("hunk-2"),exportRow,];- const highlighted = highlight(rows);- const standalone = highlight([makeHunk("standalone-hunk"), exportRow]);+ const [highlighted, standalone] = await Promise.all([+ highlight(rows),+ highlight([makeHunk("standalone-hunk"), exportRow]),+ ]);expect(highlighted.tokensByRowId[exportRow.id]).toEqual(standalone.tokensByRowId[exportRow.id]);});- it("keeps grammar state across inline comment rows", () => {+ it("keeps grammar state across inline comment rows", async () => {const openingRow = makeLine({id: "template-open",content: "const message = `open",@@ -110,16 +263,15 @@ describe("highlightNativeReviewDiffVisibleRows", () => {commentText: "Review note",};- const withComment = highlight([openingRow, commentRow, closingRow, trailingRow]);- const contiguous = highlight([openingRow, closingRow, trailingRow]);+ const [withComment, contiguous] = await Promise.all([+ highlight([openingRow, commentRow, closingRow, trailingRow]),+ highlight([openingRow, closingRow, trailingRow]),+ ]);expect(withComment.tokensByRowId).toEqual(contiguous.tokensByRowId);- expect(withComment.tokensByRowId[closingRow.id]?.[0]?.color).toBe(- withComment.tokensByRowId[openingRow.id]?.at(-1)?.color,- );});- it("does not join unhighlighted rows across cached gaps", () => {+ it("does not join unhighlighted rows across cached gaps", async () => {const trailingRow = makeLine({id: "trailing-row",content: "export const answer = 42;",@@ -145,11 +297,425 @@ describe("highlightNativeReviewDiffVisibleRows", () => {trailingRow,];- const highlighted = highlight(rows, new Set(["template-close"]));- const standalone = highlight([trailingRow]);+ const [highlighted, standalone] = await Promise.all([+ highlight(rows, new Set(["template-close"])),+ highlight([trailingRow]),+ ]);expect(highlighted.tokensByRowId[trailingRow.id]).toEqual(standalone.tokensByRowId[trailingRow.id],);});});++// These complete sources are independent of the diff row selection below.+const OLD_SOURCE = [+ "export function render(name: string) {",+ " const heading = `Hello ${name}",+ "Welcome to the archive.",+ "Your saved reports follow.",+ " `;",+ " /* Historical formatting rules:",+ " * Keep the title and summary together.",+ " * Preserve links in the footer.",+ " */",+ " return heading.trim();",+ "}",+];+const NEW_SOURCE = [+ "export function render(name: string) {",+ " const heading = `Greetings ${name}",+ "Welcome to the workspace.",+ "Your saved reports follow.",+ " `;",+ " /* Current formatting rules:",+ " * Keep the title and summary together.",+ " * Highlight links in the footer.",+ " */",+ " return heading.trim();",+ "}",+];++function authoritativeTokens(source: ReadonlyArray<string>) {+ return highlightCode(source.join("\n"), "typescript", "dark");+}++function sourceRow(change: "context" | "add" | "delete", lineNumber: number) {+ return makeLine({+ id: `${change}-${lineNumber}`,+ content: (change === "delete" ? OLD_SOURCE : NEW_SOURCE)[lineNumber - 1]!,+ change,+ oldLineNumber: change === "add" ? null : lineNumber,+ newLineNumber: change === "delete" ? null : lineNumber,+ });+}++function completeDiffRows() {+ return [+ sourceRow("context", 1),+ sourceRow("delete", 2),+ sourceRow("delete", 3),+ sourceRow("add", 2),+ sourceRow("add", 3),+ sourceRow("context", 4),+ sourceRow("context", 5),+ sourceRow("delete", 6),+ sourceRow("add", 6),+ sourceRow("context", 7),+ sourceRow("delete", 8),+ sourceRow("add", 8),+ sourceRow("context", 9),+ sourceRow("context", 10),+ sourceRow("context", 11),+ ];+}++describe("source context", () => {+ it("highlights parsed CRLF patch rows using omitted full-source templates and comments", async () => {+ const newSource = [...OLD_SOURCE];+ newSource[2] = NEW_SOURCE[2]!;+ newSource[7] = NEW_SOURCE[7]!;+ const parsed = buildReviewParsedDiff(+ [+ "diff --git a/example.ts b/example.ts",+ "--- a/example.ts",+ "+++ b/example.ts",+ "@@ -3,2 +3,2 @@",+ `-${OLD_SOURCE[2]}\r`,+ `+${newSource[2]}\r`,+ ` ${newSource[3]}\r`,+ "@@ -7,3 +7,3 @@",+ ` ${newSource[6]}\r`,+ `-${OLD_SOURCE[7]}\r`,+ `+${newSource[7]}\r`,+ ` ${newSource[8]}\r`,+ "",+ ].join("\n"),+ "crlf-context",+ );+ expect(parsed.kind).toBe("files");+ const { rows, files } = buildNativeReviewDiffData(parsed);+ const lineRows = rows.filter((row) => row.kind === "line");+ expect(lineRows).toHaveLength(7);+ const originalContents = lineRows.map((row) => row.content);+ expect(originalContents.every((content) => content?.endsWith("\r"))).toBe(true);+ const oldTokens = await authoritativeTokens(OLD_SOURCE);+ const newTokens = await authoritativeTokens(newSource);+ const result = await highlightNativeReviewDiffVisibleRows({+ rows,+ files: files.map((file) => ({+ ...file,+ loadContents: async () => ({+ oldContents: `${OLD_SOURCE.join("\r\n")}\r\n`,+ newContents: `${newSource.join("\r\n")}\r\n`,+ }),+ })),+ scheme: "dark",+ firstRowIndex: 0,+ lastRowIndex: rows.length - 1,+ overscanRows: 0,+ });+ for (const row of lineRows) {+ const expected =+ row.change === "delete"+ ? oldTokens[row.oldLineNumber! - 1]+ : newTokens[row.newLineNumber! - 1];+ const tokens = result.tokensByRowId[row.id];+ expect(tokens, row.id).toEqual(expected);+ expect(+ tokens?.every((token) => token.color !== null),+ row.id,+ ).toBe(true);+ expect(tokens?.[0]?.color, row.id).toBe(+ (row.newLineNumber ?? row.oldLineNumber)! <= 4 ? "#5ecc71" : "#737373",+ );+ }+ expect(lineRows.map((row) => row.content)).toEqual(originalContents);+ expect(result.retryableRowIds).toEqual([]);+ });++ it("matches full OLD/NEW source across replacement runs and shared multiline context", async () => {+ const rows = completeDiffRows();+ const oldTokens = await authoritativeTokens(OLD_SOURCE);+ const newTokens = await authoritativeTokens(NEW_SOURCE);+ const result = await highlightNativeReviewDiffVisibleRows({+ rows,+ files: [TYPESCRIPT_FILE],+ scheme: "dark",+ firstRowIndex: 0,+ lastRowIndex: rows.length - 1,+ overscanRows: 0,+ });+ for (const row of rows) {+ const expected =+ row.change === "delete"+ ? oldTokens[row.oldLineNumber! - 1]+ : newTokens[row.newLineNumber! - 1];+ expect(result.tokensByRowId[row.id], row.id).toEqual(expected);+ }+ });++ it("uses NEW grammar for shared rows when OLD remains inside a comment", async () => {+ const oldSource = ["/* Retired renderer", "const value = 3;", "finish();"];+ const newSource = ["// Active renderer", "const value = 3;", "finish();"];+ const rows = [+ makeLine({+ id: "old-open",+ content: oldSource[0],+ change: "delete",+ oldLineNumber: 1,+ newLineNumber: null,+ }),+ makeLine({+ id: "new-open",+ content: newSource[0],+ change: "add",+ oldLineNumber: null,+ newLineNumber: 1,+ }),+ makeLine({+ id: "shared",+ content: newSource[1],+ change: "context",+ oldLineNumber: 2,+ newLineNumber: 2,+ }),+ makeLine({+ id: "old-tail",+ content: oldSource[2],+ change: "delete",+ oldLineNumber: 3,+ newLineNumber: null,+ }),+ makeLine({+ id: "new-tail",+ content: newSource[2],+ change: "add",+ oldLineNumber: null,+ newLineNumber: 3,+ }),+ ];+ const oldTokens = await authoritativeTokens(oldSource);+ const newTokens = await authoritativeTokens(newSource);+ const result = await highlightNativeReviewDiffVisibleRows({+ rows,+ files: [TYPESCRIPT_FILE],+ scheme: "dark",+ firstRowIndex: 0,+ lastRowIndex: rows.length - 1,+ overscanRows: 0,+ });+ expect(oldTokens[1]).not.toEqual(newTokens[1]);+ expect(result.tokensByRowId.shared).toEqual(newTokens[1]);+ expect(result.tokensByRowId["old-tail"]).toEqual(oldTokens[2]);+ expect(result.tokensByRowId["new-tail"]).toEqual(newTokens[2]);+ });++ it("leaves mismatched and unavailable source revisions plain", async () => {+ const rows = [sourceRow("add", 3)];+ for (const source of [null, { oldContents: "", newContents: "different revision" }]) {+ const result = await highlightNativeReviewDiffVisibleRows({+ rows,+ files: [{ ...TYPESCRIPT_FILE, loadContents: async () => source }],+ scheme: "dark",+ firstRowIndex: 0,+ lastRowIndex: 0,+ overscanRows: 0,+ });+ expect(result.tokensByRowId[rows[0]!.id]).toEqual([+ { content: NEW_SOURCE[2], color: null, fontStyle: null },+ ]);+ }+ });+});++it("reuses full native records across viewport and theme changes and evicts old entries", async () => {+ const sources = Array.from({ length: 9 }, (_, i) => ({+ oldContents: "",+ newContents: `/* ${i}\ninside\n*/\nconst tail = 2;`,+ }));+ const rows = [+ makeLine({+ id: "body",+ content: "inside",+ change: "add",+ oldLineNumber: null,+ newLineNumber: 2,+ }),+ makeLine({+ id: "tail",+ content: "const tail = 2;",+ change: "add",+ oldLineNumber: null,+ newLineNumber: 4,+ }),+ ];+ const input = {+ rows,+ scheme: "dark" as const,+ firstRowIndex: 0,+ lastRowIndex: 0,+ overscanRows: 0,+ };+ const files = [{ ...TYPESCRIPT_FILE, loadContents: async () => sources[0]! }];+ const initial = await highlightNativeReviewDiffVisibleRows({ ...input, files });+ const moved = await highlightNativeReviewDiffVisibleRows({+ ...input,+ files,+ firstRowIndex: 1,+ lastRowIndex: 1,+ });+ await highlightNativeReviewDiffVisibleRows({ ...input, files, scheme: "light" });+ expect(tokenization.calls).toEqual([sources[0]!.newContents]);+ expect(initial.tokensByRowId.body).toEqual(+ highlightCode(sources[0]!.newContents, "typescript", "dark")[1],+ );+ expect(moved.tokensByRowId.tail).toEqual(+ highlightCode(sources[0]!.newContents, "typescript", "dark")[3],+ );+ tokenization.calls = [];+ for (const source of sources.slice(1)) {+ await highlightNativeReviewDiffVisibleRows({+ ...input,+ files: [{ ...TYPESCRIPT_FILE, loadContents: async () => source }],+ });+ }+ await highlightNativeReviewDiffVisibleRows({ ...input, files });+ expect(tokenization.calls).toHaveLength(9);+ expect(tokenization.calls.at(-1)).toBe(sources[0]!.newContents);+});++it("reuses segment records across themes and replaces records when the language changes", async () => {+ const rows = [+ makeLine({+ id: "line",+ content: "const value = 1;",+ change: "add",+ oldLineNumber: null,+ newLineNumber: 1,+ }),+ ];+ const input = {+ rows,+ files: [TYPESCRIPT_FILE],+ scheme: "dark" as const,+ firstRowIndex: 0,+ lastRowIndex: 0,+ overscanRows: 0,+ };+ const first = await highlightNativeReviewDiffVisibleRows(input);+ await highlightNativeReviewDiffVisibleRows({ ...input, scheme: "light" });+ expect(tokenization.calls).toEqual([rows[0]!.content]);+ await highlightNativeReviewDiffVisibleRows({+ ...input,+ files: [{ ...TYPESCRIPT_FILE, language: "c" }],+ });+ const restored = await highlightNativeReviewDiffVisibleRows(input);+ expect(tokenization.calls).toHaveLength(3);+ expect(restored.tokensByRowId).toEqual(first.tokensByRowId);+});++it("uses full grammar after an oversized line and expands only selected rows in a 100k-line C source", async () => {+ const contents = [+ " ".repeat(1_001) + "/*",+ ...Array.from({ length: 99_997 }, (_, i) => `comment ${i}: int value = 1;`),+ "*/",+ "int done = 2;",+ ].join("\n");+ expect(contents.length).toBeGreaterThan(500_000);+ const source = { oldContents: "", newContents: contents };+ const rows = [+ makeLine({+ id: "body",+ content: "comment 99996: int value = 1;",+ change: "add",+ oldLineNumber: null,+ newLineNumber: 99_998,+ }),+ makeLine({+ id: "end",+ content: "int done = 2;",+ change: "add",+ oldLineNumber: null,+ newLineNumber: 100_000,+ }),+ ];+ const input = {+ rows,+ files: [{ ...TYPESCRIPT_FILE, language: "c", loadContents: async () => source }],+ scheme: "dark" as const,+ firstRowIndex: 0,+ lastRowIndex: 0,+ overscanRows: 0,+ };+ const result = await highlightNativeReviewDiffVisibleRows(input);+ expect(Object.keys(result.tokensByRowId)).toEqual(["body"]);+ expect(result.tokensByRowId.body).toEqual([+ { content: rows[0]!.content, color: "#737373", fontStyle: 0 },+ ]);+ const moved = await highlightNativeReviewDiffVisibleRows({+ ...input,+ firstRowIndex: 1,+ lastRowIndex: 1,+ });+ expect(moved.tokensByRowId.end?.some((token) => token.color !== "#737373")).toBe(true);+ expect(tokenization.calls).toEqual([contents]);+});++it("publishes no cancelled file chunk and never tokenizes its next side", async () => {+ const controller = new AbortController();+ tokenization.afterCall = () => controller.abort();+ const chunks = vi.fn();+ const result = await highlightNativeReviewDiffVisibleRows({+ rows: [sourceRow("delete", 3), sourceRow("add", 3)],+ files: [+ {+ ...TYPESCRIPT_FILE,+ loadContents: async () => ({+ oldContents: OLD_SOURCE.join("\n"),+ newContents: NEW_SOURCE.join("\n"),+ }),+ },+ ],+ scheme: "dark",+ firstRowIndex: 0,+ lastRowIndex: 1,+ overscanRows: 0,+ signal: controller.signal,+ onChunk: chunks,+ });+ expect(tokenization.calls).toHaveLength(1);+ expect(chunks).not.toHaveBeenCalled();+ expect(result.tokensByRowId).toEqual({});+ expect(result.rowCount).toBe(0);+});++it("does not tokenize or publish a source that arrives after cancellation", async () => {+ const controller = new AbortController();+ const started = Promise.withResolvers<void>();+ const response = Promise.withResolvers<{ oldContents: string; newContents: string }>();+ const chunks = vi.fn();+ const work = highlightNativeReviewDiffVisibleRows({+ rows: [sourceRow("add", 3)],+ files: [+ {+ ...TYPESCRIPT_FILE,+ loadContents: () => {+ started.resolve();+ return response.promise;+ },+ },+ ],+ scheme: "dark",+ firstRowIndex: 0,+ lastRowIndex: 0,+ signal: controller.signal,+ onChunk: chunks,+ });+ await started.promise;+ controller.abort();+ response.resolve({ oldContents: "", newContents: NEW_SOURCE.join("\n") });+ expect((await work).rowCount).toBe(0);+ expect(tokenization.calls).toEqual([]);+ expect(chunks).not.toHaveBeenCalled();+});diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts b/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.tsindex dd94f6fb608..a4084d2ccaa 100644--- a/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts+++ b/apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts@@ -1,6 +1,7 @@-import { highlightCode, type HighlightScheme } from "../../lib/highlights";-import type { NativeReviewDiffFile } from "./nativeReviewDiffTypes";+import { tokenizeCode, type HighlightScheme, type TokenizedCode } from "../../lib/highlights";+import type { NativeReviewDiffFile, NativeReviewDiffSource } from "./nativeReviewDiffTypes";import type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewDiffSurface";+import { diffHighlightTraceId, traceDiffHighlight } from "./nativeReviewDiffTrace";interface NativeReviewDiffLineRow extends NativeReviewDiffRow {readonly kind: "line";@@ -8,11 +9,6 @@ interface NativeReviewDiffLineRow extends NativeReviewDiffRow {readonly content: string;}-interface IndexedNativeReviewDiffLineRow {- readonly row: NativeReviewDiffLineRow;- readonly rowIndex: number;-}-export interface HighlightNativeReviewDiffVisibleRowsInput {readonly rows: ReadonlyArray<NativeReviewDiffRow>;readonly files: ReadonlyArray<NativeReviewDiffFile>;@@ -22,12 +18,19 @@ export interface HighlightNativeReviewDiffVisibleRowsInput {readonly overscanRows?: number;readonly maxRows?: number;readonly alreadyHighlightedRowIds?: ReadonlySet<string>;+ readonly signal?: AbortSignal;+ readonly onChunk?: (chunk: NativeReviewDiffHighlightChunk) => void;+}++export interface NativeReviewDiffHighlightChunk {+ readonly tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>>;+ readonly retryableRowIds: ReadonlyArray<string>;+ readonly rowCount: number;+ readonly durationMs: number;}-// Bounds each token patch the native view parses, not the highlighting itself.const NATIVE_REVIEW_DIFF_VISIBLE_OVERSCAN_ROWS = 160;const NATIVE_REVIEW_DIFF_VISIBLE_MAX_ROWS = 360;-function isHighlightableLineRow(row: NativeReviewDiffRow): row is NativeReviewDiffLineRow {return row.kind === "line" && typeof row.fileId === "string" && typeof row.content === "string";}@@ -39,49 +42,186 @@ function hasConsecutiveLineNumbers(return typeof previous === "number" && typeof next === "number" && next === previous + 1;}-function hasOnlyCommentRowsBetween(- rows: ReadonlyArray<NativeReviewDiffRow>,- previousRowIndex: number,- nextRowIndex: number,-): boolean {- for (let rowIndex = previousRowIndex + 1; rowIndex < nextRowIndex; rowIndex += 1) {- if (rows[rowIndex]?.kind !== "comment") {- return false;+// Native lexing is non-incremental. Cache theme-independent raw records, never+// expanded token objects for an entire large file. Bound both entry count and bytes.+const MAX_TOKEN_CACHE_BYTES = 64 * 1024 * 1024;+const MAX_TOKEN_CACHE_ENTRIES = 8;+// LRU entries own only token data; source contexts and diff rows can collect independently.+const tokenCacheKeys = new WeakMap<object, object>();+const tokenCache = new Map<object, { language: string; tokens: TokenizedCode }>();+let tokenCacheBytes = 0;++function getTokenCacheKey(context: object): object {+ let key = tokenCacheKeys.get(context);+ if (!key) {+ key = {};+ tokenCacheKeys.set(context, key);+ }+ return key;+}++function getCachedTokens(+ cacheKey: object,+ contents: string | (() => string),+ language: string,+): TokenizedCode {+ const cached = tokenCache.get(cacheKey);+ if (cached) {+ tokenCache.delete(cacheKey);+ tokenCacheBytes -= cached.tokens.byteLength;+ if (cached.language === language) {+ tokenCache.set(cacheKey, cached);+ tokenCacheBytes += cached.tokens.byteLength;+ return cached.tokens;}}- return true;+ const tokens = tokenizeCode(typeof contents === "string" ? contents : contents(), language);+ if (tokens.byteLength <= MAX_TOKEN_CACHE_BYTES) {+ tokenCache.set(cacheKey, { language, tokens });+ tokenCacheBytes += tokens.byteLength;+ }+ while (tokenCacheBytes > MAX_TOKEN_CACHE_BYTES || tokenCache.size > MAX_TOKEN_CACHE_ENTRIES) {+ const oldest = tokenCache.keys().next().value!;+ tokenCacheBytes -= tokenCache.get(oldest)!.tokens.byteLength;+ tokenCache.delete(oldest);+ }+ return tokens;}-function canShareGrammarContext(- previous: IndexedNativeReviewDiffLineRow,- next: IndexedNativeReviewDiffLineRow,- rows: ReadonlyArray<NativeReviewDiffRow>,-): boolean {- if (- next.row.fileId !== previous.row.fileId ||- !hasOnlyCommentRowsBetween(rows, previous.rowIndex, next.rowIndex)- ) {- return false;+const fullSourceContexts = new WeakMap<+ NativeReviewDiffSource,+ { old: FullSourceContext; new: FullSourceContext }+>();++interface FullSourceContext {+ readonly contents: string;+ readonly comparisonLines: ReadonlyArray<string>;+ readonly validation: WeakMap<ReadonlyArray<NativeReviewDiffLineRow>, boolean>;+}++const sourceRowsByFileCache = new WeakMap<+ ReadonlyArray<NativeReviewDiffRow>,+ Map<string, NativeReviewDiffLineRow[]>+>();++function getSourceRowsByFile(rows: ReadonlyArray<NativeReviewDiffRow>) {+ let byFile = sourceRowsByFileCache.get(rows);+ if (!byFile) {+ byFile = new Map();+ for (const row of rows) {+ if (!isHighlightableLineRow(row)) continue;+ const fileRows = byFile.get(row.fileId);+ if (fileRows) fileRows.push(row);+ else byFile.set(row.fileId, [row]);+ }+ sourceRowsByFileCache.set(rows, byFile);}+ return byFile;+}- if (previous.row.change === "delete" || next.row.change === "delete") {+function matchesSourceSide(+ context: FullSourceContext,+ rows: ReadonlyArray<NativeReviewDiffLineRow>,+ side: DiffSide,+) {+ const cached = context.validation.get(rows);+ if (cached !== undefined) return cached;+ // Context participates on both sides, even though it displays NEW tokens.+ // A known mismatch anywhere invalidates grammar from the entire source side.+ const matches = rows.every((row) => {+ if (row.change === (side === "old" ? "add" : "delete")) return true;+ const lineNumber = side === "old" ? row.oldLineNumber : row.newLineNumber;return (- previous.row.change !== "add" &&- next.row.change !== "add" &&- hasConsecutiveLineNumbers(previous.row.oldLineNumber, next.row.oldLineNumber)+ typeof lineNumber === "number" && context.comparisonLines[lineNumber - 1] === row.content);+ });+ context.validation.set(rows, matches);+ return matches;+}++function createFullSourceContext(contents: string): FullSourceContext {+ return {+ contents,+ // The diff parser retains CR on patch rows, unlike the token output.+ comparisonLines: contents.split("\n"),+ validation: new WeakMap(),+ };+}++function getFullSourceContexts(source: NativeReviewDiffSource) {+ let contexts = fullSourceContexts.get(source);+ if (!contexts) {+ contexts = {+ old: createFullSourceContext(source.oldContents),+ new: createFullSourceContext(source.newContents),+ };+ fullSourceContexts.set(source, contexts);}+ return contexts;+}++type DiffSide = "old" | "new";- if (previous.row.change === "add" || next.row.change === "add") {- return hasConsecutiveLineNumbers(previous.row.newLineNumber, next.row.newLineNumber);+interface SourceSegment {+ readonly fileId: string;+ readonly side: DiffSide;+ readonly rows: NativeReviewDiffLineRow[];+}++// Row arrays are immutable snapshots; comments and hidden hunks retain source context.+const sourceSegmentsCache = new WeakMap<+ ReadonlyArray<NativeReviewDiffRow>,+ Map<string, { readonly segment: SourceSegment; readonly index: number }>+>();++function getSourceSegments(rows: ReadonlyArray<NativeReviewDiffRow>) {+ const cached = sourceSegmentsCache.get(rows);+ if (cached) return cached;++ const segmentsByRowId = new Map<+ string,+ { readonly segment: SourceSegment; readonly index: number }+ >();+ for (const side of ["old", "new"] as const) {+ let segment: SourceSegment | undefined;+ for (const row of rows) {+ if (row.kind === "comment" || row.kind === "hunk") continue;+ if (!isHighlightableLineRow(row)) {+ segment = undefined;+ continue;+ }+ if (row.change === (side === "old" ? "add" : "delete")) continue;++ const previous = segment?.rows.at(-1);+ const lineNumber = side === "old" ? row.oldLineNumber : row.newLineNumber;+ const previousLineNumber = side === "old" ? previous?.oldLineNumber : previous?.newLineNumber;+ if (+ !segment ||+ segment.fileId !== row.fileId ||+ !hasConsecutiveLineNumbers(previousLineNumber, lineNumber)+ ) {+ // A gap has no known incoming grammar state. Highlight the available+ // fragment independently; never join it to an earlier, incomplete hunk.+ segment = { fileId: row.fileId, side, rows: [] };+ }+ if (displaySide(row) === side) {+ segmentsByRowId.set(row.id, { segment, index: segment.rows.length });+ }+ segment.rows.push(row);+ }}+ sourceSegmentsCache.set(rows, segmentsByRowId);+ return segmentsByRowId;+}- return (- previous.row.change === "context" &&- next.row.change === "context" &&- hasConsecutiveLineNumbers(previous.row.oldLineNumber, next.row.oldLineNumber) &&- hasConsecutiveLineNumbers(previous.row.newLineNumber, next.row.newLineNumber)- );+function displaySide(row: NativeReviewDiffLineRow): DiffSide {+ // Unified context rows have one token array. Match the NEW side, while OLD+ // context still advances deletion grammar independently.+ return row.change === "delete" ? "old" : "new";+}++function createFileMap(files: ReadonlyArray<NativeReviewDiffFile>) {+ return new Map(files.map((file) => [file.id, file]));}function clampRowIndex(index: number, rows: ReadonlyArray<NativeReviewDiffRow>) {@@ -92,18 +232,53 @@ function clampRowIndex(index: number, rows: ReadonlyArray<NativeReviewDiffRow>)return Math.min(rows.length - 1, Math.max(0, Math.floor(index)));}-export function highlightNativeReviewDiffVisibleRows(+function makePlainTokenFallback(+ row: NativeReviewDiffLineRow,+): ReadonlyArray<NativeReviewDiffToken> {+ return [{ content: row.content || " ", color: null, fontStyle: null }];+}++export async function highlightNativeReviewDiffVisibleRows(input: HighlightNativeReviewDiffVisibleRowsInput,-): {+): Promise<{readonly tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>>;+ // Deliver plain tokens for these rows without marking them permanently highlighted.+ readonly retryableRowIds: ReadonlyArray<string>;readonly rowCount: number;-} {- const fileMap = new Map(input.files.map((file) => [file.id, file]));+ readonly durationMs: number;+}> {+ const request = diffHighlightTraceId(input);+ traceDiffHighlight("highlight-start", {+ request,+ first: input.firstRowIndex,+ last: input.lastRowIndex,+ overscan: input.overscanRows ?? NATIVE_REVIEW_DIFF_VISIBLE_OVERSCAN_ROWS,+ });+ if (input.signal?.aborted) {+ return {+ tokensByRowId: {},+ retryableRowIds: [],+ rowCount: 0,+ durationMs: 0,+ };+ }++ const startedAt = performance.now();+ 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: IndexedNativeReviewDiffLineRow[] = [];+ const visibleStartIndex = clampRowIndex(input.firstRowIndex, input.rows);+ const visibleEndIndex = clampRowIndex(input.lastRowIndex, input.rows);+ const visibleFileIds = new Set<string>();+ // Overscan warms visible files without loading unrelated neighboring sources.+ // Headers and already-highlighted rows still identify files in the viewport.+ for (let rowIndex = visibleStartIndex; rowIndex <= visibleEndIndex; rowIndex += 1) {+ const fileId = input.rows[rowIndex]?.fileId;+ if (typeof fileId === "string") visibleFileIds.add(fileId);+ }+ const selectedRows: NativeReviewDiffLineRow[] = [];for (let rowIndex = startIndex;@@ -114,40 +289,180 @@ export function highlightNativeReviewDiffVisibleRows(if (row &&isHighlightableLineRow(row) &&+ visibleFileIds.has(row.fileId) &&!input.alreadyHighlightedRowIds?.has(row.id) &&fileMap.has(row.fileId)) {- selectedRows.push({ row, rowIndex });+ selectedRows.push(row);}}- // Rows that continue each other's source are highlighted together so- // multi-line constructs keep their colors.const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};- let segment: IndexedNativeReviewDiffLineRow[] = [];- const flushSegment = () => {- const file = segment[0] ? fileMap.get(segment[0].row.fileId) : undefined;- if (file) {- const tokenLines = highlightCode(- segment.map(({ row }) => row.content).join("\n"),- file.language,- input.scheme,- );- segment.forEach(({ row }, index) => {- tokensByRowId[row.id] = tokenLines[index] ?? [];+ const retryableRowIds: string[] = [];+ const selectedRowIds = new Set(selectedRows.map((row) => row.id));+ const tokenize = (context: object, contents: string | (() => string), language: string) => {+ const cacheKey = getTokenCacheKey(context);+ const cacheHit = tokenCache.get(cacheKey)?.language === language;+ const cached = getCachedTokens(cacheKey, contents, language);+ traceDiffHighlight("tokenized", {+ request,+ characters: typeof contents === "string" ? contents.length : undefined,+ cacheHit,+ retainedBytes: cached.byteLength,+ lines: cached.lineCount,+ aborted: input.signal?.aborted ?? false,+ });+ return cached;+ };++ const sourceFiles = new Map<string, NativeReviewDiffLineRow[]>();+ for (const row of selectedRows) {+ if (!fileMap.get(row.fileId)?.loadContents) continue;+ const fileRows = sourceFiles.get(row.fileId);+ if (fileRows) fileRows.push(row);+ else sourceFiles.set(row.fileId, [row]);+ }+ const emitFileChunk = (fileRows: ReadonlyArray<NativeReviewDiffLineRow>) => {+ if (!input.onChunk || input.signal?.aborted) return;+ const rowIds = new Set(fileRows.map((row) => row.id));+ input.onChunk({+ tokensByRowId: Object.fromEntries(fileRows.map((row) => [row.id, tokensByRowId[row.id]!])),+ retryableRowIds: retryableRowIds.filter((id) => rowIds.has(id)),+ rowCount: fileRows.length,+ durationMs: Math.round(performance.now() - startedAt),+ });+ };+ // The file filling the viewport should not wait for a sliver of its neighbor.+ for (const [fileId, fileRows] of [...sourceFiles].sort((a, b) => b[1].length - a[1].length)) {+ if (input.signal?.aborted) break;+ const file = fileMap.get(fileId)!;+ const fileTraceId = diffHighlightTraceId(fileId);+ traceDiffHighlight("highlight-source", { request, file: fileTraceId, rows: fileRows.length });+ let source: NativeReviewDiffSource | null;+ try {+ source = await file.loadContents!(input.signal);+ } catch {+ traceDiffHighlight("highlight-source-error", { request, file: fileTraceId });+ for (const row of fileRows) {+ selectedRowIds.delete(row.id);+ tokensByRowId[row.id] = makePlainTokenFallback(row);+ retryableRowIds.push(row.id);+ }+ emitFileChunk(fileRows);+ continue;+ }+ if (input.signal?.aborted) break;+ const contexts = source ? getFullSourceContexts(source) : null;+ for (const side of ["old", "new"] as const) {+ if (input.signal?.aborted) break;+ const candidate = contexts?.[side];+ const context =+ candidate &&+ matchesSourceSide(candidate, getSourceRowsByFile(input.rows).get(fileId)!, side)+ ? candidate+ : null;+ traceDiffHighlight("source-validation", {+ request,+ file: fileTraceId,+ side,+ present: !!candidate,+ matches: !!context,+ knownLines: context?.comparisonLines.length,});+ const matchingRows: { row: NativeReviewDiffLineRow; lineIndex: number }[] = [];+ for (const row of fileRows) {+ if (displaySide(row) !== side) continue;+ selectedRowIds.delete(row.id);+ const lineNumber = side === "old" ? row.oldLineNumber : row.newLineNumber;+ const lineIndex = typeof lineNumber === "number" ? lineNumber - 1 : -1;+ if (+ context &&+ lineIndex >= 0 &&+ lineIndex < context.comparisonLines.length &&+ context.comparisonLines[lineIndex] === row.content+ ) {+ matchingRows.push({ row, lineIndex });+ } else {+ // A changed revision or missing source cannot+ // supply trustworthy grammar. Do not cache guessed syntax colors.+ tokensByRowId[row.id] = makePlainTokenFallback(row);+ }+ }+ if (!context || matchingRows.length === 0) continue;+ const tokens = tokenize(context, context.contents, file.language);+ for (const { row, lineIndex } of matchingRows) {+ tokensByRowId[row.id] =+ tokens.highlightLine(lineIndex, input.scheme) ?? makePlainTokenFallback(row);+ }}- segment = [];- };+ emitFileChunk(fileRows);+ await new Promise<void>((resolve) => setTimeout(resolve, 0));+ }++ const selectedSegments = new Map<+ SourceSegment,+ { firstSelected: number; lastSelected: number }+ >();+ if (selectedRowIds.size > 0 && !input.signal?.aborted) {+ const sourceSegments = getSourceSegments(input.rows);+ for (const row of selectedRows) {+ if (!selectedRowIds.has(row.id)) continue;+ const source = sourceSegments.get(row.id);+ if (!source) continue;+ const selection = selectedSegments.get(source.segment);+ if (selection) {+ selection.lastSelected = source.index;+ } else {+ selectedSegments.set(source.segment, {+ firstSelected: source.index,+ lastSelected: source.index,+ });+ }+ }+ }- for (const selectedRow of selectedRows) {- const previousRow = segment.at(-1);- if (previousRow && !canShareGrammarContext(previousRow, selectedRow, input.rows)) {- flushSegment();+ for (const [segment, { firstSelected, lastSelected }] of selectedSegments) {+ if (input.signal?.aborted) break;+ const file = fileMap.get(segment.fileId);+ if (!file) continue;++ const tokens = tokenize(+ segment,+ () => segment.rows.map((row) => row.content).join("\n"),+ file.language,+ );+ for (let index = firstSelected; index <= lastSelected; index += 1) {+ const row = segment.rows[index]!;+ if (selectedRowIds.has(row.id) && displaySide(row) === segment.side) {+ tokensByRowId[row.id] =+ tokens.highlightLine(index, input.scheme) ?? makePlainTokenFallback(row);+ }}- segment.push(selectedRow);}- flushSegment();- return { tokensByRowId, rowCount: selectedRows.length };+ if (input.signal?.aborted) {+ traceDiffHighlight("highlight-aborted", { request });+ return {+ tokensByRowId: {},+ retryableRowIds: [],+ rowCount: 0,+ durationMs: 0,+ };+ }++ traceDiffHighlight("highlight-result", {+ request,+ selected: selectedRows.length,+ delivered: Object.keys(tokensByRowId).length,+ retryable: retryableRowIds.length,+ colored: Object.values(tokensByRowId).filter((tokens) =>+ tokens.some((token) => token.color !== null),+ ).length,+ });+ return {+ tokensByRowId,+ retryableRowIds,+ rowCount: selectedRows.length,+ durationMs: Math.round(performance.now() - startedAt),+ };}diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSource.test.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSource.test.tsnew file mode 100644index 00000000000..3dcc3c7597f--- /dev/null+++ b/apps/mobile/src/features/diffs/nativeReviewDiffSource.test.ts@@ -0,0 +1,151 @@+import { expect, it, vi } from "vite-plus/test";++import { createNativeReviewDiffSourceLoader } from "./nativeReviewDiffSource";+import type { NativeReviewDiffSource } from "./nativeReviewDiffTypes";++const SOURCE = { oldContents: "const before = true;", newContents: "const after = false;" };++vi.mock("expo-file-system", () => ({+ Paths: { document: "test-documents" },+ File: class {+ create() {}+ async write() {}+ },+}));++it("retains fetched stress sources above 500k characters within the aggregate budget", async () => {+ const source = { oldContents: "", newContents: "x".repeat(3_270_000) };+ const fetch = vi.fn(async () => source);+ const load = createNativeReviewDiffSourceLoader(fetch);+ expect(await load("generated.c")).toBe(source);+ expect(await load("generated.c")).toBe(source);+ expect(fetch).toHaveBeenCalledTimes(1);+});++it("evicts source text by aggregate size and returns an over-budget response uncached", async () => {+ const source = { oldContents: "", newContents: "x".repeat(4_500_000) };+ const huge = { oldContents: "", newContents: "x".repeat(9_000_000) };+ const fetch = vi.fn(async (id: string) => (id === "huge" ? huge : source));+ const load = createNativeReviewDiffSourceLoader(fetch);+ expect(await load("first")).toBe(source);+ expect(await load("second")).toBe(source);+ expect(await load("first")).toBe(source);+ expect(fetch).toHaveBeenCalledTimes(3);+ expect(await load("huge")).toBe(huge);+ expect(await load("huge")).toBe(huge);+ expect(fetch).toHaveBeenCalledTimes(5);+ expect(await load("first")).toBe(source);+ expect(fetch).toHaveBeenCalledTimes(5);+});++it("lets later viewport requests retry a failed source fetch", async () => {+ const fetch = vi.fn().mockRejectedValueOnce(new Error("Offline")).mockResolvedValueOnce(SOURCE);+ const load = createNativeReviewDiffSourceLoader(fetch);+ await expect(load("retry.ts")).rejects.toThrow("Offline");+ expect(await load("retry.ts")).toBe(SOURCE);+});++const failureKeys = [+ ["string", () => "retry.ts"],+ ["number", () => 1],+ ["boolean", () => false],+ ["bigint", () => 1n],+ ["symbol", () => Symbol("retry.ts")],+ ["null", () => null],+ ["undefined", () => undefined],+ ["object", () => ({ id: "retry.ts" })],+ ["function", () => () => SOURCE],+] as const;++it.each(failureKeys)("bounds transient retries for a %s key", async (_name, createKey) => {+ const key = createKey();+ const fetch = vi.fn(async () => {+ throw new Error("Offline");+ });+ const load = createNativeReviewDiffSourceLoader(fetch);+ await expect(load(key)).rejects.toThrow("Offline");+ expect(await load(key)).toBeNull();+ expect(await load(key)).toBeNull();+ expect(fetch).toHaveBeenCalledTimes(2);+});++it.each(failureKeys)(+ "remembers permanent unavailability for a %s key",+ async (_name, createKey) => {+ const key = createKey();+ const fetch = vi.fn(async () => {+ throw { reason: "unsupported" };+ });+ const load = createNativeReviewDiffSourceLoader(fetch);+ expect(await load(key)).toBeNull();+ expect(await load(key)).toBeNull();+ expect(fetch).toHaveBeenCalledOnce();+ },+);++it.each(failureKeys)(+ "resets retries after success and eviction for a %s key",+ async (_name, createKey) => {+ const key = createKey();+ const fetch = vi+ .fn()+ .mockRejectedValueOnce(new Error("Offline"))+ .mockResolvedValueOnce(SOURCE)+ .mockResolvedValueOnce({ oldContents: "", newContents: "x".repeat(8_000_000) })+ .mockRejectedValueOnce(new Error("Offline again"))+ .mockResolvedValueOnce(SOURCE);+ const load = createNativeReviewDiffSourceLoader(fetch);+ await expect(load(key)).rejects.toThrow("Offline");+ expect(await load(key)).toBe(SOURCE);+ await load({ id: "evict" });+ await expect(load(key)).rejects.toThrow("Offline again");+ expect(await load(key)).toBe(SOURCE);+ expect(fetch).toHaveBeenCalledTimes(5);+ },+);++it("shares an in-flight function request while one subscriber cancels", async () => {+ const started = Promise.withResolvers<void>();+ const response = Promise.withResolvers<NativeReviewDiffSource>();+ let calls = 0;+ const request = () => {+ calls++;+ started.resolve();+ return response.promise;+ };+ const load = createNativeReviewDiffSourceLoader((sourceRequest: typeof request) =>+ sourceRequest(),+ );+ const controller = new AbortController();+ const first = load(request, controller.signal);+ await started.promise;+ const second = load(request);+ controller.abort();+ expect(await first).toBeNull();+ response.resolve(SOURCE);+ expect(await second).toBe(SOURCE);+ expect(await load(request)).toBe(SOURCE);+ expect(calls).toBe(1);+});++it("serializes RPCs and drops cancelled queued files", async () => {+ const started = Promise.withResolvers<void>();+ const response = Promise.withResolvers<NativeReviewDiffSource>();+ const fetch = vi.fn((file: string) => {+ if (file !== "active.ts") return Promise.resolve(SOURCE);+ started.resolve();+ return response.promise;+ });+ const load = createNativeReviewDiffSourceLoader(fetch);+ const active = load("active.ts");+ await started.promise;+ const controller = new AbortController();+ const queued = load("cancelled.ts", controller.signal);+ controller.abort();+ expect(await queued).toBeNull();+ expect(fetch.mock.calls).toEqual([["active.ts"]]);+ response.resolve(SOURCE);+ await active;+ await load("next.ts");+ expect(fetch.mock.calls).toEqual([["active.ts"], ["next.ts"]]);+});diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSource.tsnew file mode 100644index 00000000000..52fae25d35b--- /dev/null+++ b/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts@@ -0,0 +1,188 @@+import type { NativeReviewDiffSource } from "./nativeReviewDiffTypes";+import { diffHighlightTraceId, traceDiffHighlight } from "./nativeReviewDiffTrace";++const MAX_SOURCE_FILES = 4;+// Bound retained UTF-16 text across files without discarding an already-fetched+// authoritative source just because it is large. Provider response limits still apply.+const MAX_CACHED_SOURCE_CHARACTERS = 8_000_000;+const MAX_SOURCE_ATTEMPTS = 2;++function isWeakKey(value: unknown): value is object {+ return (typeof value === "object" && value !== null) || typeof value === "function";+}++function permanentSourceFailureReason(error: unknown): string | undefined {+ for (let depth = 0; depth < 8 && typeof error === "object" && error !== null; depth++) {+ const reason = "reason" in error ? error.reason : undefined;+ const name = "name" in error ? error.name : undefined;+ // Defect serialization preserves error names and causes, but drops custom fields.+ if (name === "GitCafeDiffSourceUnavailableError") return "gitcafe-source-unavailable";+ if (name === "GitHubDiffFileContentsUnavailableError") return "github-source-unavailable";+ for (const permanent of [+ "provider-unsupported",+ "unsupported",+ "oversized",+ "binary",+ "not-found",+ ]) {+ if (permanent === reason) return permanent;+ }+ if ("status" in error && error.status === 413) return "http-413";+ if ("status" in error && error.status === 501) return "http-501";+ // Older servers have no structured reason for an unsupported contents RPC.+ if (+ "detail" in error &&+ error.detail === "This host cannot expand unchanged pull request lines."+ )+ return "legacy-host-unsupported";+ error = "cause" in error ? error.cause : undefined;+ }+ return undefined;+}++function waitForSource(+ promise: Promise<NativeReviewDiffSource | null>,+ signal?: AbortSignal,+): Promise<NativeReviewDiffSource | null> {+ if (!signal) return promise;+ if (signal.aborted) return Promise.resolve(null);+ return new Promise((resolve, reject) => {+ const abort = () => {+ signal.removeEventListener("abort", abort);+ resolve(null);+ };+ signal.addEventListener("abort", abort, { once: true });+ void promise.then(+ (source) => {+ signal.removeEventListener("abort", abort);+ resolve(source);+ },+ (error: unknown) => {+ signal.removeEventListener("abort", abort);+ reject(error);+ },+ );+ });+}++export function createNativeReviewDiffSourceLoader<FileId>(+ fetchSource: (fileId: FileId) => Promise<NativeReviewDiffSource>,+) {+ const cached = new Map<FileId, NativeReviewDiffSource>();+ let cachedCharacters = 0;+ type Failure = { attempts: number; unavailable: boolean };+ // Request closures can own parsed rows; failed versions must not retain them.+ const objectFailures = new WeakMap<object, Failure>();+ const primitiveFailures = new Map<FileId, Failure>();+ const pending = new Map<+ FileId,+ {+ readonly promise: Promise<NativeReviewDiffSource | null>;+ readonly subscribers: Set<AbortSignal | undefined>;+ }+ >();+ // RPC commands cannot abort a request already sent. Serialize source fetches+ // and drop queued requests whose viewports have all been cancelled.+ let tail = Promise.resolve();+ const loader = diffHighlightTraceId(cached);++ return async (fileId: FileId, signal?: AbortSignal) => {+ const file = diffHighlightTraceId(fileId);+ const failure = (isWeakKey(fileId)+ ? objectFailures.get(fileId)+ : primitiveFailures.get(fileId)) ?? { attempts: 0, unavailable: false };+ if (signal?.aborted || failure.unavailable) {+ traceDiffHighlight("source-skip", {+ loader,+ file,+ aborted: signal?.aborted ?? false,+ unavailable: failure.unavailable,+ });+ return null;+ }+ if (cached.has(fileId)) {+ traceDiffHighlight("source-cache", { loader, file });+ const source = cached.get(fileId)!;+ cached.delete(fileId);+ cached.set(fileId, source);+ return source;+ }+ let request = pending.get(fileId);+ if (!request) {+ traceDiffHighlight("source-queued", { loader, file, pending: pending.size });+ const subscribers = new Set<AbortSignal | undefined>();+ const promise = tail+ .then(async () => {+ if ([...subscribers].every((subscriber) => subscriber?.aborted)) {+ traceDiffHighlight("source-dropped", { loader, file });+ return null;+ }+ const attempt = ++failure.attempts;+ if (isWeakKey(fileId)) objectFailures.set(fileId, failure);+ else primitiveFailures.set(fileId, failure);+ traceDiffHighlight("source-start", { loader, file, attempt });+ try {+ const contents = await fetchSource(fileId);+ traceDiffHighlight("source-result", {+ loader,+ file,+ oldCharacters: contents.oldContents.length,+ newCharacters: contents.newContents.length,+ });+ const characters = contents.oldContents.length + contents.newContents.length;+ if (isWeakKey(fileId)) objectFailures.delete(fileId);+ else primitiveFailures.delete(fileId);+ if (characters <= MAX_CACHED_SOURCE_CHARACTERS) {+ cached.set(fileId, contents);+ cachedCharacters += characters;+ while (+ cached.size > MAX_SOURCE_FILES ||+ cachedCharacters > MAX_CACHED_SOURCE_CHARACTERS+ ) {+ const oldest = cached.keys().next().value!;+ const source = cached.get(oldest)!;+ cachedCharacters -= source.oldContents.length + source.newContents.length;+ cached.delete(oldest);+ }+ }+ return contents;+ } catch (error) {+ const reason = permanentSourceFailureReason(error);+ const permanent = reason !== undefined;+ traceDiffHighlight("source-error", {+ loader,+ file,+ attempt,+ permanent,+ reason: reason ?? "transient",+ });+ if (permanent || attempt >= MAX_SOURCE_ATTEMPTS) {+ failure.unavailable = true;+ traceDiffHighlight("source-unavailable", {+ loader,+ file,+ reason: permanent ? "permanent-error" : "attempts",+ });+ return null;+ }+ // Only a later viewport request retries; never loop inside this request.+ throw error;+ }+ })+ .finally(() => pending.delete(fileId));+ tail = promise.then(+ () => {},+ () => {},+ );+ request = { promise, subscribers };+ pending.set(fileId, request);+ } else traceDiffHighlight("source-shared", { loader, file });+ request.subscribers.add(signal);+ try {+ return await waitForSource(request.promise, signal);+ } finally {+ if (signal?.aborted) traceDiffHighlight("source-wait-aborted", { loader, file });+ request.subscribers.delete(signal);+ }+ };+}diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsdeleted file mode 100644index 805cc77ae36..00000000000--- a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.ts+++ /dev/null@@ -1,33 +0,0 @@-import { describe, expect, it, vi } from "vite-plus/test";--const expoMocks = vi.hoisted(() => ({- requireNativeView: vi.fn(),-}));--vi.mock("expo", () => ({- requireNativeView: expoMocks.requireNativeView,-}));--describe("isPendingNativeViewRegistration", () => {- it("recognizes registration races for the installed native view name", async () => {- const { isPendingNativeViewRegistration } = await import("./nativeReviewDiffSurface");-- expect(- isPendingNativeViewRegistration(- new Error("Unable to find the 'T3ReviewDiffSurface' view for this native tag"),- ),- ).toBe(true);- expect(- isPendingNativeViewRegistration(- new Error("Unable to find the 'T3ReviewDiffView' view for this native tag"),- ),- ).toBe(false);- expect(- isPendingNativeViewRegistration(- new Error(- "Unable to find the class expo.modules.t3reviewdiff.T3ReviewDiffView view with tag 1150",- ),- ),- ).toBe(true);- });-});diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsxnew file mode 100644index 00000000000..52cc1805342--- /dev/null+++ b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx@@ -0,0 +1,405 @@+import {+ act,+ useLayoutEffect,+ useImperativeHandle,+ useRef,+ useState,+ type Ref,+ type ReactNode,+} from "react";+import { createRoot } from "react-dom/client";+import { expect, it, vi } from "vite-plus/test";+import { AsyncResult } from "effect/reactivity";+import * as Cause from "effect/Cause";+import type { HighlightNativeReviewDiffVisibleRowsInput } from "./nativeReviewDiffHighlighter";+import type { NativeReviewDiffViewProps } from "./nativeReviewDiffSurface";+import type { NativeReviewDiffData } from "../review/nativeReviewDiffAdapter";++const mocks = vi.hoisted(() => ({+ registrationFailures: 0,+ tokenAccepted: true as boolean | undefined,+ tokenCompletion: null as Promise<boolean> | null,+ onDebug: undefined as NativeReviewDiffViewProps["onDebug"],+ autoViewport: false,+ rows: vi.fn(),+ tokens: vi.fn(),+ highlight: vi.fn(),+}));++function RawView({+ ref: nativeRef,+ onDebug,+ initialFileId,+ contentResetKey,+}: NativeReviewDiffViewProps & { ref: Ref<unknown> }) {+ const [content, setContent] = useState({ resetKey: contentResetKey, rows: "" });+ const rows = content.resetKey === contentResetKey ? content.rows : "";+ const [tokenRowIds, setTokenRowIds] = useState<string[]>([]);+ useLayoutEffect(() => {+ mocks.onDebug = onDebug;+ });+ useImperativeHandle(nativeRef, () => ({+ async setRowsJson(value: string) {+ mocks.rows(value);+ if (mocks.registrationFailures > 0) {+ mocks.registrationFailures -= 1;+ throw new Error("Unable to find the 'T3ReviewDiffSurface' view for this native tag");+ }+ setContent({ resetKey: contentResetKey, rows: value });+ if (mocks.autoViewport) {+ const decoded = JSON.parse(value) as NativeReviewDiffData["rows"];+ onDebug?.({+ nativeEvent: { message: "rows-decoded", rows: decoded.length },+ } as unknown as Parameters<NonNullable<typeof onDebug>>[0]);+ const index = decoded.findIndex(+ (row) => row.kind === "file" && row.fileId === initialFileId,+ );+ onDebug?.({+ nativeEvent: {+ message: "visible-range",+ firstRowIndex: Math.max(0, index),+ lastRowIndex: Math.max(0, index) + 40,+ totalRows: decoded.length,+ },+ } as unknown as Parameters<NonNullable<typeof onDebug>>[0]);+ }+ },+ async scrollToFile() {},+ async setTokensPatchJson(value: string) {+ mocks.tokens(value);+ const accepted = mocks.tokenCompletion ? await mocks.tokenCompletion : mocks.tokenAccepted;+ if (accepted === true) {+ const patch = JSON.parse(value);+ setTokenRowIds((current) => [+ ...new Set([...current, ...Object.keys(patch.tokensByRowId)]),+ ]);+ }+ return accepted;+ },+ }));+ return (+ <div data-token-rows={tokenRowIds.join(",")}>+ {rows ? "Rendered diff" : "Blank native surface"}+ </div>+ );+}++vi.mock("expo", () => ({ requireNativeView: () => RawView }));+vi.mock("react-native", () => ({+ View: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+}));+vi.mock("../../components/ui/EmptyState", () => ({+ EmptyState: ({+ title,+ actionLabel,+ onAction,+ }: {+ title: string;+ actionLabel: string;+ onAction: () => void;+ }) => (+ <div>+ {title}+ <button onClick={onAction}>{actionLabel}</button>+ </div>+ ),+}));+vi.mock("./nativeReviewDiffHighlighter", () => ({+ highlightNativeReviewDiffVisibleRows: mocks.highlight,+}));+vi.mock("@t3tools/client-runtime/state/runtime", () => ({+ settlePromise: async (execute: () => Promise<unknown>) => {+ try {+ return AsyncResult.success(await execute());+ } catch (error) {+ return AsyncResult.failure(Cause.die(error));+ }+ },+ squashAtomCommandFailure: () => "tokenization failed",+}));+vi.mock("../review/nativeReviewDiffAdapter", () => ({ createNativeReviewDiffTheme: () => ({}) }));+vi.mock("../settings/appearance/useAppearanceCodeSurface", () => ({+ useAppearanceCodeSurface: () => ({ nativeReviewDiffStyle: {} }),+}));+vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({+ useAppearancePreferences: () => ({ themeAppearance: "light", themeId: "test" }),+}));+vi.mock("../../lib/useUniwindTheme", () => ({ useUniwindTheme: () => ({}) }));++import { resolveNativeReviewDiffView } from "./nativeReviewDiffSurface";+import { useNativeReviewDiffBridge } from "../review/useNativeReviewDiffBridge";+import {+ handlePullRequestDiffDebugEvent,+ pullRequestDiffInitialPosition,+} from "../pull-requests/pullRequestDiffDebug";++function setup(integrated = false) {+ vi.useFakeTimers();+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+ mocks.registrationFailures = 0;+ mocks.tokenAccepted = true;+ mocks.tokenCompletion = null;+ mocks.onDebug = undefined;+ mocks.autoViewport = false;+ mocks.rows.mockClear();+ mocks.tokens.mockClear();+ mocks.highlight+ .mockReset()+ .mockImplementation(async (input: HighlightNativeReviewDiffVisibleRowsInput) => {+ const rowId = `r${input.firstRowIndex}`;+ const tokensByRowId = input.alreadyHighlightedRowIds?.has(rowId)+ ? {}+ : { [rowId]: [{ content: "const", color: "#ff0000", fontStyle: null }] };+ return {+ rowCount: Object.keys(tokensByRowId).length,+ durationMs: 0,+ retryableRowIds: [],+ tokensByRowId,+ };+ });+ const frames = new Map<number, FrameRequestCallback>();+ let nextFrame = 0;+ const requestFrame = vi+ .spyOn(globalThis, "requestAnimationFrame")+ .mockImplementation((callback) => {+ frames.set(++nextFrame, callback);+ return nextFrame;+ });+ const cancelFrame = vi.spyOn(globalThis, "cancelAnimationFrame").mockImplementation((id) => {+ if (id != null) frames.delete(id);+ });+ const errors = vi.spyOn(console, "error").mockImplementation(() => {});+ const expo = Object.getOwnPropertyDescriptor(globalThis, "expo");+ Object.defineProperty(globalThis, "expo", {+ configurable: true,+ value: { getViewConfig: () => ({}) },+ });+ const NativeDiff = resolveNativeReviewDiffView()!;+ const container = document.createElement("div");+ const root = createRoot(container);+ let data: NativeReviewDiffData = {+ rows: Array.from({ length: 1000 }, (_, index) =>+ index === 999+ ? { kind: "comment", id: `r${index}`, commentText: "Original comment" }+ : index === 900+ ? { kind: "file", id: `r${index}`, fileId: "last-file" }+ : { kind: "line", id: `r${index}` },+ ),+ files: [],+ additions: 0,+ deletions: 0,+ commentTargetsByRowId: new Map(),+ rowIdByCommentLineId: new Map(),+ };+ const ids: string[] = [];+ function PullRequestDiff({ targetFileId }: { targetFileId?: string }) {+ const bridge = useNativeReviewDiffBridge({+ threadKey: null,+ sectionId: "pull-request:test:1:all",+ diff: "test diff",+ data,+ collapsedFileIds: ids,+ viewedFileIds: ids,+ selectedRowIds: ids,+ canHighlight: true,+ });+ const nativeView = useRef(null);+ const jumpStarted = useRef(true);+ const onDebug: NonNullable<NativeReviewDiffViewProps["onDebug"]> = (event) =>+ handlePullRequestDiffDebugEvent(event, {+ rowCount: data.rows.length,+ targetFileId,+ focusIndex: -1,+ isIos: true,+ nativeView,+ jumpStarted,+ loadMore: () => {},+ onDebug: bridge.onDebug,+ });+ return (+ <NativeDiff+ {...bridge}+ {...pullRequestDiffInitialPosition(targetFileId, -1)}+ nativeViewRef={nativeView}+ appearanceScheme="light"+ rowHeight={20}+ contentWidth={300}+ onDebug={onDebug}+ />+ );+ }+ if (!integrated) {+ act(() =>+ root.render(+ <NativeDiff+ rowsJson="[]"+ tokensPatchJson='{"tokensByRowId":{}}'+ appearanceScheme="light"+ themeJson="{}"+ rowHeight={20}+ contentWidth={300}+ />,+ ),+ );+ }+ return {+ container,+ async mountPullRequest(targetFileId?: string) {+ await act(async () => root.render(<PullRequestDiff targetFileId={targetFileId} />));+ },+ async updateComment() {+ data = {+ ...data,+ rows: data.rows.map((row) =>+ row.kind === "comment" ? { ...row, commentText: "Updated comment" } : row,+ ),+ };+ await act(async () => root.render(<PullRequestDiff />));+ },+ get tokenRows() {+ return container.querySelector("[data-token-rows]")?.getAttribute("data-token-rows");+ },+ async jump(firstRowIndex: number, totalRows = 1000) {+ await act(async () => {+ mocks.onDebug?.({+ nativeEvent: {+ message: "visible-range",+ firstRowIndex,+ lastRowIndex: firstRowIndex + 40,+ totalRows,+ },+ } as unknown as Parameters<NonNullable<NativeReviewDiffViewProps["onDebug"]>>[0]);+ await vi.runOnlyPendingTimersAsync();+ });+ },+ async deliverPayloads() {+ const callbacks = [...frames.values()];+ frames.clear();+ await act(async () => {+ for (const callback of callbacks) callback(0);+ await vi.runOnlyPendingTimersAsync();+ });+ },+ retry() {+ const button = container.querySelector("button");+ expect(button?.textContent).toBe("Retry diff");+ act(() => button!.click());+ },+ decodeFailure() {+ act(() =>+ mocks.onDebug?.({+ nativeEvent: { message: "rows-decode-failed", error: "Decode failed" },+ } as unknown as Parameters<NonNullable<NativeReviewDiffViewProps["onDebug"]>>[0]),+ );+ },+ [Symbol.dispose]() {+ act(() => root.unmount());+ requestFrame.mockRestore();+ cancelFrame.mockRestore();+ errors.mockRestore();+ vi.useRealTimers();+ if (expo) Object.defineProperty(globalThis, "expo", expo);+ else Reflect.deleteProperty(globalThis, "expo");+ },+ };+}++it("retries transient native registration without replacing the diff with an error", async () => {+ using screen = setup();+ mocks.registrationFailures = 1;+ await screen.deliverPayloads();+ expect(screen.container.textContent).toBe("Blank native surface");+ await screen.deliverPayloads();+ expect(screen.container.textContent).toBe("Rendered diff");+});++it.each([false, undefined])(+ "keeps colors queued until native accepts them and recovers rejected patches (%s)",+ async (rejected) => {+ using screen = setup(true);+ await screen.mountPullRequest();+ let accept!: (accepted: boolean) => void;+ mocks.tokenCompletion = new Promise((resolve) => {+ accept = resolve;+ });+ mocks.tokens.mockClear();+ await screen.jump(0);+ await screen.deliverPayloads();+ await screen.jump(400);+ await screen.deliverPayloads();+ expect(+ mocks.tokens.mock.calls.map(([json]) => Object.keys(JSON.parse(json).tokensByRowId)),+ ).toEqual([["r0"]]);+ await act(async () => accept(true));++ mocks.tokenCompletion = null;+ mocks.tokenAccepted = rejected;+ await screen.deliverPayloads();+ expect(screen.tokenRows).toBe("r0");++ mocks.tokenAccepted = true;+ await screen.jump(800);+ await screen.deliverPayloads();+ expect(screen.tokenRows).toBe("r0,r800");+ await screen.jump(400);+ await screen.deliverPayloads();+ expect(screen.tokenRows).toBe("r0,r800,r400");+ },+);++it.each(["retry", "comment update"])(+ "re-highlights accepted rows after a native row failure, PR %s, and viewport revisit",+ async (recovery) => {+ using screen = setup(true);+ await screen.mountPullRequest();+ mocks.tokens.mockClear();+ await screen.jump(0);+ await screen.deliverPayloads();+ await screen.jump(400);+ await screen.deliverPayloads();+ expect(screen.tokenRows).toBe("r0,r400");++ screen.decodeFailure();+ expect(screen.container.textContent).toContain("Could not display diff");+ if (recovery === "retry") await act(async () => screen.retry());+ else await screen.updateComment();+ await screen.deliverPayloads();+ expect(screen.container.textContent).toBe("Rendered diff");+ await screen.jump(800);+ await screen.deliverPayloads();+ await screen.jump(400);+ await screen.deliverPayloads();+ expect(screen.tokenRows?.split(",")).toContain("r400");+ },+);++it("delivers the selected file first with a warm highlighter and no startup command", async () => {+ using screen = setup(true);+ mocks.autoViewport = true;+ await screen.mountPullRequest("last-file");+ await screen.deliverPayloads();+ await screen.deliverPayloads();+ expect(screen.tokenRows).toBe("r900");+});++it("recognizes registration races for the installed native view name", async () => {+ const { isPendingNativeViewRegistration } = await import("./nativeReviewDiffSurface");++ expect(+ isPendingNativeViewRegistration(+ new Error("Unable to find the 'T3ReviewDiffSurface' view for this native tag"),+ ),+ ).toBe(true);+ expect(+ isPendingNativeViewRegistration(+ new Error("Unable to find the 'T3ReviewDiffView' view for this native tag"),+ ),+ ).toBe(false);+ expect(+ isPendingNativeViewRegistration(+ new Error(+ "Unable to find the class expo.modules.t3reviewdiff.T3ReviewDiffView view with tag 1150",+ ),+ ),+ ).toBe(true);+});diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.tsindex 9d51c72272b..bb0d0d170b4 100644--- a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts+++ b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts@@ -1,14 +1,17 @@import {createElement,+ useCallback,useEffect,useImperativeHandle,useRef,+ useState,type ComponentType,type Ref,} from "react";-import type { NativeSyntheticEvent, ViewProps } from "react-native";+import { View, type NativeSyntheticEvent, type ViewProps } from "react-native";import { requireNativeView } from "expo";+import { EmptyState } from "../../components/ui/EmptyState";import { NativeViewResolutionError } from "../../native/nativeViewResolutionError";const NATIVE_REVIEW_DIFF_MODULE_NAME = "T3ReviewDiffSurface";@@ -125,6 +128,7 @@ export interface NativeReviewDiffViewProps extends ViewProps {/** Android ignores this and measures the widest row. */readonly contentWidth: number;readonly initialRowIndex?: number;+ readonly initialFileId?: string;readonly scrollEnabled?: boolean;readonly bounces?: boolean;readonly refreshing?: boolean;@@ -161,7 +165,7 @@ export function isNativeReviewDiffDrawEvent(payload: Readonly<Record<string, unkinterface NativeReviewDiffViewRef {readonly setRowsJson: (rowsJson: string) => Promise<void>;readonly setTokensJson: (tokensJson: string) => Promise<void>;- readonly setTokensPatchJson: (tokensPatchJson: string) => Promise<void>;+ readonly setTokensPatchJson: (tokensPatchJson: string) => Promise<boolean>;readonly scrollToFile: (fileId: string, animated: boolean) => Promise<void>;readonly scrollToTop: (animated: boolean) => Promise<void>;}@@ -192,6 +196,9 @@ function useNativeReviewDiffPayload(nativeRef: React.RefObject<NativeReviewDiffViewRef | null>,method: NativeReviewDiffPayloadMethod,payload: string | undefined,+ resetKey?: string,+ onFailure?: () => void,+ onDelivered?: (payload: string) => void,) {useEffect(() => {if (payload === undefined) {@@ -208,27 +215,43 @@ function useNativeReviewDiffPayload(}const view = nativeRef.current;- const command = view?.[method];+ const command: ((payload: string) => Promise<void | boolean>) | undefined = view?.[method];if (!view || !command) {if (attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES) {attempts += 1;frame = requestAnimationFrame(dispatch);+ } else {+ console.error(`[native-review-diff] ${method} unavailable`);+ onFailure?.();}return;}- void command.call(view, payload).catch((error: unknown) => {- if (- !cancelled &&- attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES &&- isPendingNativeViewRegistration(error)- ) {- attempts += 1;- frame = requestAnimationFrame(dispatch);- return;- }- console.error(`[native-review-diff] ${method} failed`, error);- });+ void Promise.resolve()+ .then(() => {+ if (!cancelled) return command.call(view, payload);+ })+ .then((accepted) => {+ if (cancelled) return;+ // This promise resolves after native decode, reset validation, and merge.+ if (method === "setTokensPatchJson" && accepted !== true) {+ throw new Error("Native token patch was not accepted");+ }+ onDelivered?.(payload);+ })+ .catch((error: unknown) => {+ if (cancelled) return;+ if (+ attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES &&+ isPendingNativeViewRegistration(error)+ ) {+ attempts += 1;+ frame = requestAnimationFrame(dispatch);+ return;+ }+ console.error(`[native-review-diff] ${method} failed`, error);+ onFailure?.();+ });};// Fabric attaches the React ref before Expo registers the native tag used by@@ -241,7 +264,7 @@ function useNativeReviewDiffPayload(cancelAnimationFrame(frame);}};- }, [method, nativeRef, payload]);+ }, [method, nativeRef, payload, resetKey, onFailure, onDelivered]);}function getExpoViewConfig(moduleName: string) {@@ -251,11 +274,102 @@ function getExpoViewConfig(moduleName: string) {}function NativeReviewDiffView(props: NativeReviewDiffViewProps) {- const { nativeViewRef, rowsJson, tokensJson, tokensPatchJson, ...nativeProps } = props;+ const [failedRowsJson, setFailedRowsJson] = useState<string | null>(null);+ const onRowsFailure = useCallback(() => setFailedRowsJson(props.rowsJson), [props.rowsJson]);+ if (failedRowsJson !== null && failedRowsJson !== props.rowsJson) setFailedRowsJson(null);+ if (failedRowsJson === props.rowsJson) {+ return createElement(+ View,+ {+ style: [+ props.style,+ {+ flex: 1,+ justifyContent: "center",+ paddingTop: props.contentInsetTop,+ paddingBottom: props.contentInsetBottom,+ },+ ],+ },+ createElement(EmptyState, {+ title: "Could not display diff",+ detail: "Try loading the diff view again.",+ variant: "plain",+ actionLabel: "Retry diff",+ onAction: () => {+ props.onDebug?.({+ nativeEvent: { message: "surface-retry" },+ } as unknown as NativeSyntheticEvent<Record<string, unknown>>);+ setFailedRowsJson(null);+ },+ }),+ );+ }+ return createElement(NativeReviewDiffContent, { ...props, onRowsFailure });+}++function NativeReviewDiffContent(+ props: NativeReviewDiffViewProps & { readonly onRowsFailure: () => void },+) {+ const {+ nativeViewRef,+ rowsJson,+ tokensJson,+ tokensPatchJson,+ onRowsFailure,+ onDebug,+ ...nativeProps+ } = props;const nativeRef = useRef<NativeReviewDiffViewRef>(null);- useNativeReviewDiffPayload(nativeRef, "setRowsJson", rowsJson);+ useNativeReviewDiffPayload(+ nativeRef,+ "setRowsJson",+ rowsJson,+ props.contentResetKey,+ onRowsFailure,+ );useNativeReviewDiffPayload(nativeRef, "setTokensJson", tokensJson);- useNativeReviewDiffPayload(nativeRef, "setTokensPatchJson", tokensPatchJson);+ const onDebugRef = useRef(onDebug);+ useEffect(() => {+ onDebugRef.current = onDebug;+ }, [onDebug]);+ const reportedMountRef = useRef(false);+ useEffect(() => {+ // Effect replay keeps the same native content; only a new mount loses tokens.+ if (reportedMountRef.current) return;+ reportedMountRef.current = true;+ onDebugRef.current?.({+ nativeEvent: { message: "surface-content-mounted" },+ } as unknown as NativeSyntheticEvent<Record<string, unknown>>);+ }, []);+ const reportTokenDelivery = useCallback((json: string, message: string) => {+ const patch = JSON.parse(json) as { resetKey?: string; chunkIndex?: number };+ if (patch.chunkIndex === undefined) return;+ onDebugRef.current?.({+ nativeEvent: {+ message,+ resetKey: patch.resetKey,+ chunkIndex: patch.chunkIndex,+ },+ } as unknown as NativeSyntheticEvent<Record<string, unknown>>);+ }, []);+ const onTokensDelivered = useCallback(+ (json: string) => {+ reportTokenDelivery(json, "tokens-patch-delivered");+ },+ [reportTokenDelivery],+ );+ const onTokensFailure = useCallback(() => {+ if (tokensPatchJson !== undefined) reportTokenDelivery(tokensPatchJson, "tokens-patch-failed");+ }, [reportTokenDelivery, tokensPatchJson]);+ useNativeReviewDiffPayload(+ nativeRef,+ "setTokensPatchJson",+ tokensPatchJson,+ undefined,+ onTokensFailure,+ onTokensDelivered,+ );useImperativeHandle(nativeViewRef,() => ({@@ -277,6 +391,13 @@ function NativeReviewDiffView(props: NativeReviewDiffViewProps) {return createElement(RawNativeView, {...nativeProps,refreshEnabled: props.onPullToRefresh !== undefined,+ onDebug: (event) => {+ if (event.nativeEvent.message === "rows-decode-failed") {+ console.error("[native-review-diff] rows decode failed", event.nativeEvent.error);+ onRowsFailure();+ }+ onDebug?.(event);+ },ref: nativeRef,});}diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffTrace.test.ts b/apps/mobile/src/features/diffs/nativeReviewDiffTrace.test.tsnew file mode 100644index 00000000000..e43a2d7ec9a--- /dev/null+++ b/apps/mobile/src/features/diffs/nativeReviewDiffTrace.test.ts@@ -0,0 +1,98 @@+import { expect, it, vi } from "vite-plus/test";++const sink = vi.hoisted(() => ({+ created: vi.fn(),+ written: vi.fn<(line: string, options: unknown) => Promise<void>>(),+ opened: vi.fn(),+}));++vi.mock("expo-file-system", () => ({+ Paths: { document: "documents" },+ File: class {+ constructor(...args: unknown[]) {+ sink.opened(...args);+ }+ create(options: unknown) {+ sink.created(options);+ }+ write(line: string, options: unknown) {+ return sink.written(line, options);+ }+ },+}));++it("leaves the filesystem untouched when Release tracing is disabled", async () => {+ vi.resetModules();+ sink.opened.mockClear();+ vi.stubEnv("EXPO_PUBLIC_T3_DIFF_TRACE", "0");+ try {+ const { traceDiffHighlight } = await import("./nativeReviewDiffTrace");+ traceDiffHighlight("viewport-start", { rows: 80 });+ expect(sink.opened).not.toHaveBeenCalled();+ } finally {+ vi.unstubAllEnvs();+ }+});++it("keeps object, function, and primitive identities stable without collisions", async () => {+ vi.resetModules();+ vi.stubEnv("EXPO_PUBLIC_T3_DIFF_TRACE", "1");+ try {+ const { diffHighlightTraceId } = await import("./nativeReviewDiffTrace");+ const values = [{}, {}, () => {}, () => {}, null, undefined, "file", 1, "1", false];+ const ids = values.map(diffHighlightTraceId);+ expect(ids.every((id) => id > 0)).toBe(true);+ expect(new Set(ids).size).toBe(values.length);+ expect(values.map(diffHighlightTraceId)).toEqual(ids);+ } finally {+ vi.unstubAllEnvs();+ }+});++it("serializes appends to a retrievable file and bounds a process to 1000 events", async () => {+ vi.resetModules();+ sink.opened.mockClear();+ sink.created.mockClear();+ sink.written.mockReset();+ const firstWrite = Promise.withResolvers<void>();+ const releaseFirst = Promise.withResolvers<void>();+ const finished = Promise.withResolvers<void>();+ sink.written.mockImplementation(async (line) => {+ const { seq } = JSON.parse(line);+ if (seq === 1) {+ firstWrite.resolve();+ await releaseFirst.promise;+ }+ if (seq === 1000) finished.resolve();+ });+ using warning = vi.spyOn(console, "warn").mockImplementation(() => {});+ vi.stubEnv("EXPO_PUBLIC_T3_DIFF_TRACE", "1");+ try {+ const { diffHighlightTraceId, traceDiffHighlight } = await import("./nativeReviewDiffTrace");+ const request = {};+ expect(diffHighlightTraceId(request)).toBeGreaterThan(0);+ for (let index = 0; index < 1001; index++)+ traceDiffHighlight("viewport-start", { rows: index });+ await firstWrite.promise;+ expect(sink.written).toHaveBeenCalledTimes(1);+ releaseFirst.resolve();+ await finished.promise;+ expect(sink.opened.mock.calls).toEqual([["documents", "t3-diff-highlight-trace.jsonl"]]);+ expect(sink.created.mock.calls).toEqual([[{ overwrite: true, intermediates: true }]]);+ expect(sink.written).toHaveBeenCalledTimes(1000);+ expect(warning).toHaveBeenCalledTimes(1000);+ expect(diffHighlightTraceId(request)).toBe(0);+ expect(diffHighlightTraceId("file")).toBe(0);+ expect(sink.written.mock.calls.map(([line]) => JSON.parse(line).seq)).toEqual(+ Array.from({ length: 1000 }, (_, index) => index + 1),+ );+ expect(+ sink.written.mock.calls.every(+ ([line, options]) => line.endsWith("\n") && JSON.stringify(options) === '{"append":true}',+ ),+ ).toBe(true);+ } finally {+ releaseFirst.resolve();+ vi.unstubAllEnvs();+ }+});diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffTrace.ts b/apps/mobile/src/features/diffs/nativeReviewDiffTrace.tsnew file mode 100644index 00000000000..c7f39b051d2--- /dev/null+++ b/apps/mobile/src/features/diffs/nativeReviewDiffTrace.ts@@ -0,0 +1,70 @@+// Opt in at bundle time for bounded Release diagnostics; never log source or RPC payloads.+const MAX_TRACE_EVENTS = 1_000;+let eventCount = 0;+let nextId = 0;+// Diagnostics must not keep requests, source loaders, or their row graphs alive.+const objectIds = new WeakMap<object, number>();+const primitiveIds = new Map<unknown, number>();+let fileSink: Promise<import("expo-file-system").File | null> | undefined;++export function diffHighlightTraceHash(value: string): number {+ let hash = 2166136261;+ for (let index = 0; index < value.length; index++)+ hash = Math.imul(hash ^ value.charCodeAt(index), 16777619);+ return hash >>> 0;+}++function appendTraceLine(line: string) {+ fileSink ??= import("expo-file-system")+ .then(({ File, Paths }) => {+ const file = new File(Paths.document, "t3-diff-highlight-trace.jsonl");+ file.create({ overwrite: true, intermediates: true });+ return file;+ })+ .catch(() => null);+ // File.write is async in Expo 58. Serialize appends to preserve sequence order.+ fileSink = fileSink.then(async (file) => {+ if (!file) return null;+ try {+ await file.write(line + "\n", { append: true });+ return file;+ } catch {+ return null;+ }+ });+}++export function diffHighlightTraceId(value: unknown): number {+ if (process.env.EXPO_PUBLIC_T3_DIFF_TRACE !== "1" || eventCount >= MAX_TRACE_EVENTS) return 0;+ if ((typeof value === "object" && value !== null) || typeof value === "function") {+ let id = objectIds.get(value);+ if (id === undefined) {+ id = ++nextId;+ objectIds.set(value, id);+ }+ return id;+ }+ let id = primitiveIds.get(value);+ if (id === undefined) {+ id = ++nextId;+ primitiveIds.set(value, id);+ }+ return id;+}++export function traceDiffHighlight(+ event: string,+ fields: Readonly<Record<string, number | boolean | string | undefined>> = {},+) {+ if (process.env.EXPO_PUBLIC_T3_DIFF_TRACE !== "1" || eventCount >= MAX_TRACE_EVENTS) return;+ eventCount += 1;+ const line = JSON.stringify({+ event,+ seq: eventCount,+ at: Math.round(performance.now()),+ ...fields,+ });+ appendTraceLine(line);+ console.warn("[diff-highlight-trace] " + line);+ if (eventCount === MAX_TRACE_EVENTS) primitiveIds.clear();+}diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffTypes.ts b/apps/mobile/src/features/diffs/nativeReviewDiffTypes.tsindex 24ce1667aee..6d0427c2622 100644--- a/apps/mobile/src/features/diffs/nativeReviewDiffTypes.ts+++ b/apps/mobile/src/features/diffs/nativeReviewDiffTypes.ts@@ -1,3 +1,8 @@+export interface NativeReviewDiffSource {+ readonly oldContents: string;+ readonly newContents: string;+}+export interface NativeReviewDiffFile {readonly id: string;readonly path: string;@@ -5,4 +10,5 @@ export interface NativeReviewDiffFile {readonly language: string;readonly additions: number;readonly deletions: number;+ readonly loadContents?: (signal?: AbortSignal) => Promise<NativeReviewDiffSource | null>;}diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsxindex 0f48b2ad9c0..b013029db79 100644--- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx@@ -36,6 +36,11 @@ import { usePullRequestPermissions } from "./usePullRequestPermissions";import { usePullRequestAction } from "./usePullRequestAction";import { annotatePullRequestDiff, reviewPosition } from "./pullRequestDiffComments";import { usePullRequestFileFilter } from "./usePullRequestFileFilter";+import {+ handlePullRequestDiffDebugEvent,+ pullRequestDiffInitialPosition,+} from "./pullRequestDiffDebug";+import { usePullRequestDiffHighlightFiles } from "./usePullRequestDiffHighlightFiles";import { isPullRequestTestFile } from "./pullRequestFileFilters";import { useFocusEffect, useNavigation, type StaticScreenProps } from "@react-navigation/native";import { RegistryContext, useAtomRefresh } from "@effect/atom-react";@@ -44,7 +49,7 @@ import { type PullRequestDetail, type PullRequestListEntry } from "@t3tools/contimport { PullRequestOverviewLoading } from "./PullRequestOverviewLoading";import { copyPullRequestLink, sharePullRequestLink } from "./pullRequestLink";import { pullRequestStatus } from "./pullRequestStatus";-import { use, useEffect, useRef, useState } from "react";+import { use, useEffect, useMemo, useRef, useState } from "react";import {Linking,Platform,@@ -75,7 +80,6 @@ import { composerPullRequests } from "../../state/pull-requests";import { useEnvironmentQuery } from "../../state/query";import { usePullToRefresh } from "../../state/use-pull-to-refresh";import {- isNativeReviewDiffDrawEvent,resolveNativeReviewDiffView,type NativeReviewDiffViewHandle,type NativeReviewDiffViewProps,@@ -804,12 +808,25 @@ export function PullRequestFileRouteScreen({!result.isPending &&!result.error;const activity = useEnvironmentQuery(composerPullRequests.activity(requestTarget(route.params)));- const baseData = buildNativeReviewDiffData(parsed);- const data = annotatePullRequestDiff(- baseData,- staleDiff || commit ? [] : (activity.data?.reviewThreads ?? []),- commit ? [] : reviewDraft.draft.comments,- diffHead.sha ?? undefined,+ const baseData = useMemo(() => buildNativeReviewDiffData(parsed), [parsed]);+ const highlightFiles = usePullRequestDiffHighlightFiles(route.params, parsed, baseData.files);+ const data = useMemo(+ () =>+ annotatePullRequestDiff(+ { ...baseData, files: highlightFiles },+ staleDiff || commit ? [] : (activity.data?.reviewThreads ?? []),+ commit ? [] : reviewDraft.draft.comments,+ diffHead.sha ?? undefined,+ ),+ [+ baseData,+ highlightFiles,+ staleDiff,+ commit,+ activity.data?.reviewThreads,+ reviewDraft.draft.comments,+ diffHead.sha,+ ],);const viewedIds = data.files.filter((file) => (commit ? commitViewedPaths.has(file.path) : viewed.isViewed(file.path)))@@ -854,7 +871,9 @@ export function PullRequestFileRouteScreen({const [collapsedIds, setCollapsedIds] = useState<readonly string[]>(EMPTY_IDS);const [visibleFileId, setVisibleFileId] = useState<string | null>(null);const nativeView = useRef<NativeReviewDiffViewHandle>(null);- const jumpStarted = useRef(false);+ // Native applies the entry destination before its first viewport. Imperative+ // jumps below are for subsequent selections and filter changes only.+ const jumpStarted = useRef(true);const lastSelection = useRef({ path: route.params.path, id: route.params.fileSelectionId });useEffect(() => {if (@@ -902,37 +921,17 @@ export function PullRequestFileRouteScreen({useEffect(() => {if (!targetFile) loadMore();}, [targetFile, loadMore]);- const { onDebug: updateVisibleRange } = bridge;- const onDebug: NonNullable<NativeReviewDiffViewProps["onDebug"]> = (event) => {- const drawn = isNativeReviewDiffDrawEvent(event.nativeEvent);- const decoded =- event.nativeEvent.message === "rows-decoded" && event.nativeEvent.rows === data.rows.length;- if (!drawn && !decoded) return;- // Filtering replaces the native row payload asynchronously. Old draw events- // must not consume the file jump or highlight the new payload's row indices.- if (- typeof event.nativeEvent.totalRows === "number" &&- event.nativeEvent.totalRows !== data.rows.length- )- return;- if (drawn) updateVisibleRange(event);- if (- targetFile &&- !jumpStarted.current &&- nativeView.current &&- (Platform.OS !== "ios" || decoded)- ) {- jumpStarted.current = true;- if (focusIndex >= 0) return;- void nativeView.current.scrollToFile(targetFile.id, false).catch(() => {- jumpStarted.current = false;- });- return;- }- if (!drawn) return;- const lastRow = event.nativeEvent.lastRowIndex;- if (typeof lastRow === "number" && lastRow >= data.rows.length - 40) loadMore();- };+ const onDebug: NonNullable<NativeReviewDiffViewProps["onDebug"]> = (event) =>+ handlePullRequestDiffDebugEvent(event, {+ rowCount: data.rows.length,+ targetFileId: targetFile?.id,+ focusIndex,+ isIos: Platform.OS === "ios",+ nativeView,+ jumpStarted,+ onDebug: bridge.onDebug,+ loadMore,+ });const onToggleFile: NonNullable<NativeReviewDiffViewProps["onToggleFile"]> = (event) => {const id = event.nativeEvent.fileId;if (!id) return;@@ -1114,7 +1113,7 @@ export function PullRequestFileRouteScreen({{NativeDiffView && data.rows.length && !seekingFile ? (<View className="flex-1" collapsable={false}><NativeDiffView- initialRowIndex={focusIndex >= 0 ? Math.max(0, focusIndex - 3) : undefined}+ {...pullRequestDiffInitialPosition(targetFile?.id, focusIndex)}nativeViewRef={nativeView}refreshing={result.refreshing}onPullToRefresh={result.onPullRefresh}diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffComments.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffComments.test.tsindex df769c2b2af..2573436f3ac 100644--- a/apps/mobile/src/features/pull-requests/pullRequestDiffComments.test.ts+++ b/apps/mobile/src/features/pull-requests/pullRequestDiffComments.test.ts@@ -24,6 +24,17 @@ const thread: PullRequestReviewThread = {comments: [],};describe("PR comments in continuous native diffs", () => {+ it("returns unannotated data unchanged without reading or indexing rows", () => {+ const unannotated = {+ ...data,+ get rows(): NativeReviewDiffData["rows"] {+ throw new Error("Empty annotation must not read rows");+ },+ };+ expect(annotatePullRequestDiff(unannotated, [], [], undefined)).toBe(unannotated);+ expect(annotatePullRequestDiff(data, [], [], undefined).rows).toBe(data.rows);+ });+it("anchors old/new lines separately despite identical line numbers", () => {const annotated = annotatePullRequestDiff(data,diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffComments.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffComments.tsindex 73a24c3b903..097ede3867e 100644--- a/apps/mobile/src/features/pull-requests/pullRequestDiffComments.ts+++ b/apps/mobile/src/features/pull-requests/pullRequestDiffComments.ts@@ -34,6 +34,7 @@ export function annotatePullRequestDiff(drafts: readonly PendingReviewComment[],headSha: string | undefined,): NativeReviewDiffData {+ if (threads.length === 0 && drafts.length === 0) return data;const anchors = new Map<string, NativeReviewDiffRow[]>();const firstByPath = new Map<string, NativeReviewDiffRow>();const lines = new Map<string, NativeReviewDiffRow>();diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.test.tsnew file mode 100644index 00000000000..030e3ef4395--- /dev/null+++ b/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.test.ts@@ -0,0 +1,82 @@+import { expect, it, vi } from "vite-plus/test";++vi.mock("react-native", () => ({ View: () => null }));+vi.mock("expo", () => ({ requireNativeView: vi.fn() }));+vi.mock("../../components/ui/EmptyState", () => ({ EmptyState: () => null }));++import {+ handlePullRequestDiffDebugEvent,+ pullRequestDiffInitialPosition,+} from "./pullRequestDiffDebug";+import { createReviewDiffHighlightScheduler } from "../review/reviewDiffHighlightScheduler";+import type { NativeReviewDiffViewProps } from "../diffs/nativeReviewDiffSurface";++it("enters at a file header without changing guide focus positioning", () => {+ expect(pullRequestDiffInitialPosition("last-file", -1)).toEqual({+ initialFileId: "last-file",+ initialRowIndex: -1,+ });+ expect(pullRequestDiffInitialPosition("last-file", 904)).toEqual({+ initialFileId: "",+ initialRowIndex: 901,+ });+ expect(pullRequestDiffInitialPosition(undefined, -1)).toEqual({+ initialFileId: "",+ initialRowIndex: -1,+ });+});++it.each([true, false])(+ "starts warm highlighting at the declared file without a JS jump (iOS: %s)",+ async (isIos) => {+ vi.useFakeTimers();+ // A warm engine can issue its source RPC immediately when the scheduler flushes.+ const sourceRequest = vi.fn();+ const scheduler = createReviewDiffHighlightScheduler(sourceRequest);+ const scrollToFile = vi.fn(async () => {});+ const loadMore = vi.fn();+ const jumpStarted = { current: true };+ const onDebug: NonNullable<NativeReviewDiffViewProps["onDebug"]> = ({ nativeEvent }) => {+ if (nativeEvent.message === "visible-range")+ scheduler.update({+ firstRowIndex: nativeEvent.firstRowIndex as number,+ lastRowIndex: nativeEvent.lastRowIndex as number,+ });+ };+ const emit = (nativeEvent: Record<string, unknown>) =>+ handlePullRequestDiffDebugEvent({ nativeEvent } as Parameters<typeof onDebug>[0], {+ rowCount: 1000,+ targetFileId: "last-file",+ focusIndex: -1,+ isIos,+ nativeView: { current: { scrollToFile, scrollToTop: vi.fn(async () => {}) } },+ jumpStarted,+ onDebug,+ loadMore,+ });+ try {+ const position = pullRequestDiffInitialPosition("last-file", -1);+ emit({ message: "rows-decoded", rows: 1000 });+ // Native applies the declared file before publishing its viewport. A later+ // imperative bridge command cannot retract an RPC started from a top range.+ const first = position.initialFileId === "last-file" ? 900 : 0;+ emit({+ message: "visible-range",+ firstRowIndex: first,+ lastRowIndex: first + 40,+ totalRows: 1000,+ });+ await vi.runOnlyPendingTimersAsync();+ expect(sourceRequest.mock.calls).toEqual([[{ firstRowIndex: 900, lastRowIndex: 940 }]]);+ expect(scrollToFile).not.toHaveBeenCalled();+ // Near-end pagination and stale-payload filtering still use native ranges.+ emit({ message: "visible-range", firstRowIndex: 950, lastRowIndex: 990, totalRows: 999 });+ expect(loadMore).not.toHaveBeenCalled();+ emit({ message: "visible-range", firstRowIndex: 950, lastRowIndex: 990, totalRows: 1000 });+ expect(loadMore).toHaveBeenCalledOnce();+ } finally {+ scheduler.cancel();+ vi.useRealTimers();+ }+ },+);diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.tsnew file mode 100644index 00000000000..c82aa9deeb6--- /dev/null+++ b/apps/mobile/src/features/pull-requests/pullRequestDiffDebug.ts@@ -0,0 +1,63 @@+import type { RefObject } from "react";++import {+ isNativeReviewDiffDrawEvent,+ type NativeReviewDiffViewHandle,+ type NativeReviewDiffViewProps,+} from "../diffs/nativeReviewDiffSurface";++export function pullRequestDiffInitialPosition(+ targetFileId: string | undefined,+ focusIndex: number,+): Pick<NativeReviewDiffViewProps, "initialRowIndex" | "initialFileId"> {+ // Explicit empty values also clear a previous destination on a reused native view.+ return {+ initialRowIndex: focusIndex >= 0 ? Math.max(0, focusIndex - 3) : -1,+ initialFileId: focusIndex >= 0 ? "" : (targetFileId ?? ""),+ };+}++export function handlePullRequestDiffDebugEvent(+ event: Parameters<NonNullable<NativeReviewDiffViewProps["onDebug"]>>[0],+ input: {+ readonly rowCount: number;+ readonly targetFileId: string | undefined;+ readonly focusIndex: number;+ readonly isIos: boolean;+ readonly nativeView: RefObject<NativeReviewDiffViewHandle | null>;+ readonly jumpStarted: RefObject<boolean>;+ readonly onDebug: NonNullable<NativeReviewDiffViewProps["onDebug"]>;+ readonly loadMore: () => void;+ },+) {+ const drawn = isNativeReviewDiffDrawEvent(event.nativeEvent);+ // Delivery outcomes and content mounts must reach the bridge even before rows decode.+ if (!drawn) input.onDebug(event);+ const decoded =+ event.nativeEvent.message === "rows-decoded" && event.nativeEvent.rows === input.rowCount;+ if (!drawn && !decoded) return;+ // Filtering replaces the native row payload asynchronously. Old draw events+ // must not consume the file jump or highlight the new payload's row indices.+ if (+ typeof event.nativeEvent.totalRows === "number" &&+ event.nativeEvent.totalRows !== input.rowCount+ )+ return;+ if (drawn) input.onDebug(event);+ if (+ input.targetFileId &&+ !input.jumpStarted.current &&+ input.nativeView.current &&+ (!input.isIos || decoded)+ ) {+ input.jumpStarted.current = true;+ if (input.focusIndex >= 0) return;+ void input.nativeView.current.scrollToFile(input.targetFileId, false).catch(() => {+ input.jumpStarted.current = false;+ });+ return;+ }+ if (!drawn) return;+ const lastRow = event.nativeEvent.lastRowIndex;+ if (typeof lastRow === "number" && lastRow >= input.rowCount - 40) input.loadMore();+}diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffHighlightFiles.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffHighlightFiles.test.tsnew file mode 100644index 00000000000..3d419f262da--- /dev/null+++ b/apps/mobile/src/features/pull-requests/pullRequestDiffHighlightFiles.test.ts@@ -0,0 +1,440 @@+import { highlightCode } from "../../lib/highlights";++import { EnvironmentId, ProjectId } from "@t3tools/contracts";+import { expect, it, vi } from "vite-plus/test";+import { AsyncResult } from "effect/reactivity";++import { highlightNativeReviewDiffVisibleRows } from "../diffs/nativeReviewDiffHighlighter";+import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes";+import type { ReviewParsedDiff, ReviewRenderableFile } from "../review/reviewModel";+import { combinePullRequestDiffPages } from "./pullRequestDiffPages";+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";+import {+ createPullRequestDiffHighlightCache,+ createPullRequestDiffHighlightFiles,+} from "./pullRequestDiffHighlightFiles";++vi.mock("expo", async () => {+ const { createWasmHighlightsModule } = await import("../../lib/highlights.testing");+ return { requireOptionalNativeModule: () => createWasmHighlightsModule() };+});++const target = {+ environmentId: EnvironmentId.make("remote-environment"),+ input: {+ projectId: ProjectId.make("project"),+ repository: "org/repo",+ number: 23,+ host: "forge.example.com",+ },+};++function file(id: string, path: string, previousPath: string | null): ReviewRenderableFile {+ return {+ id,+ path,+ previousPath,+ cacheKey: id,+ changeType: previousPath ? "rename-changed" : "change",+ additions: 1,+ deletions: 1,+ languageHint: "typescript",+ additionLines: [],+ deletionLines: [],+ rows: [],+ };+}++function setup() {+ const parsed = {+ kind: "files",+ fileCount: 2,+ additions: 2,+ deletions: 2,+ notice: null,+ files: [file("selected", "renderer.ts", "old-renderer.ts"), file("unseen", "unseen.ts", null)],+ } satisfies ReviewParsedDiff;+ const files: NativeReviewDiffFile[] = parsed.files.map((file) => ({+ id: file.id,+ path: file.path,+ language: "typescript",+ additions: 1,+ deletions: 1,+ }));+ return { parsed, files };+}++it("loads only the selected PR file using its remote target, commit, and rename paths", async () => {+ const { parsed, files } = setup();+ const contents = {+ oldContents: "/* Previous renderer\nconst removed = 1;\n*/",+ newContents: "const heading = `Current renderer\nWelcome to the workspace.\n`;",+ };+ const fetch = vi.fn(async () => AsyncResult.success(contents));+ const loaded = createPullRequestDiffHighlightFiles(+ { target, commit: "abc123" },+ parsed,+ files,+ fetch,+ );+ expect(fetch).not.toHaveBeenCalled();+ const rows = [+ {+ kind: "line" as const,+ id: "removed",+ fileId: "selected",+ change: "delete" as const,+ oldLineNumber: 2,+ newLineNumber: null,+ content: "const removed = 1;",+ },+ {+ kind: "line" as const,+ id: "added",+ fileId: "selected",+ change: "add" as const,+ oldLineNumber: null,+ newLineNumber: 2,+ content: "Welcome to the workspace.",+ },+ {+ kind: "line" as const,+ id: "unseen",+ fileId: "unseen",+ change: "add" as const,+ oldLineNumber: null,+ newLineNumber: 1,+ content: "export const unseen = true;",+ },+ ];+ const result = await highlightNativeReviewDiffVisibleRows({+ rows,+ files: loaded,+ scheme: "dark",+ firstRowIndex: 0,+ lastRowIndex: 1,+ overscanRows: 0,+ });+ expect(fetch.mock.calls).toEqual([+ [+ {+ ...target,+ input: {+ ...target.input,+ commit: "abc123",+ changeType: "rename-changed",+ oldPath: "old-renderer.ts",+ newPath: "renderer.ts",+ },+ },+ ],+ ]);+ expect(result.tokensByRowId.removed).toEqual(+ highlightCode(contents.oldContents, "typescript", "dark")[1],+ );+ expect(result.tokensByRowId.added).toEqual(+ highlightCode(contents.newContents, "typescript", "dark")[1],+ );+ expect(result.tokensByRowId.unseen).toBeUndefined();+ expect(await loaded[0]!.loadContents!()).toBe(contents);+ expect(fetch).toHaveBeenCalledTimes(1);+});++it.each([null, "Some file contents are unavailable"])(+ "retains fetched and unavailable source when another diff page is appended (notice: %s)",+ async (notice) => {+ const { parsed, files } = setup();+ const contents = { oldContents: "before", newContents: "after" };+ const fetch = vi.fn(async ({ input }: { input: { newPath: string } }) => {+ if (input.newPath === "unseen.ts") throw { reason: "unsupported" };+ return AsyncResult.success(contents);+ });+ const cache = createPullRequestDiffHighlightCache();+ const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);+ expect(await first[0]!.loadContents!()).toBe(contents);+ expect(await first[1]!.loadContents!()).toBeNull();+ const appended = file("appended", "appended.ts", null);+ const next = createPullRequestDiffHighlightFiles(+ { target },+ { ...parsed, files: [...parsed.files, appended], fileCount: 3, notice },+ [...files, { ...files[1]!, id: appended.id, path: appended.path }],+ fetch,+ cache,+ );+ expect(await next[0]!.loadContents!()).toBe(contents);+ expect(await next[1]!.loadContents!()).toBeNull();+ expect(fetch).toHaveBeenCalledTimes(2);+ },+);++it("does not reuse source from another diff snapshot", async () => {+ const { parsed, files } = setup();+ const fetch = vi.fn(async () =>+ AsyncResult.success({ oldContents: "", newContents: "const current = true;" }),+ );+ const cache = createPullRequestDiffHighlightCache();+ const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);+ const second = createPullRequestDiffHighlightFiles(+ { target },+ { ...parsed, files: parsed.files.map((file) => ({ ...file })) },+ files,+ fetch,+ cache,+ );+ await first[0]!.loadContents!();+ await second[0]!.loadContents!();+ expect(fetch).toHaveBeenCalledTimes(2);+});++it.each([+ [+ "environment",+ { target: { ...target, environmentId: EnvironmentId.make("other") }, commit: "abc" },+ ],+ [+ "project",+ {+ target: { ...target, input: { ...target.input, projectId: ProjectId.make("other") } },+ commit: "abc",+ },+ ],+ [+ "repository",+ { target: { ...target, input: { ...target.input, repository: "other/repo" } }, commit: "abc" },+ ],+ ["PR", { target: { ...target, input: { ...target.input, number: 24 } }, commit: "abc" }],+ [+ "host",+ { target: { ...target, input: { ...target.input, host: "other.example.com" } }, commit: "abc" },+ ],+ ["commit", { target, commit: "def" }],+ ["unpinned commit", { target }],+])("isolates retained file objects after changing the %s", async (_name, source) => {+ const { parsed, files } = setup();+ const cache = createPullRequestDiffHighlightCache();+ const previous = { oldContents: "", newContents: "previous" };+ const current = { oldContents: "", newContents: "current" };+ const fetch = vi+ .fn()+ .mockResolvedValueOnce(AsyncResult.success(previous))+ .mockResolvedValueOnce(AsyncResult.success(current));+ const first = createPullRequestDiffHighlightFiles(+ { target, commit: "abc" },+ parsed,+ files,+ fetch,+ cache,+ );+ expect(await first[0]!.loadContents!()).toBe(previous);+ const second = createPullRequestDiffHighlightFiles(source, parsed, files, fetch, cache);+ expect(await second[0]!.loadContents!()).toBe(current);+ expect(await first[0]!.loadContents!()).toBe(previous);+ expect(fetch).toHaveBeenCalledTimes(2);+});++it("does not reuse a replaced later-page file with the same ID", async () => {+ const { parsed, files } = setup();+ const cache = createPullRequestDiffHighlightCache();+ const previous = { oldContents: "", newContents: "previous" };+ const current = { oldContents: "", newContents: "current" };+ const fetch = vi+ .fn()+ .mockResolvedValueOnce(AsyncResult.success(previous))+ .mockResolvedValueOnce(AsyncResult.success(current));+ const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);+ expect(await first[1]!.loadContents!()).toBe(previous);+ const second = createPullRequestDiffHighlightFiles(+ { target },+ { ...parsed, files: [parsed.files[0]!, { ...parsed.files[1]! }] },+ files,+ fetch,+ cache,+ );+ expect(await second[1]!.loadContents!()).toBe(current);+ expect(fetch).toHaveBeenCalledTimes(2);+});++it.each(["permanent", "transient"])(+ "does not reuse a replaced later-page file's %s failure with the same ID",+ async (failure) => {+ const { parsed, files } = setup();+ const cache = createPullRequestDiffHighlightCache();+ const contents = { oldContents: "", newContents: "current" };+ const fetch = vi.fn(async () => AsyncResult.success(contents));+ const error = failure === "permanent" ? { reason: "unsupported" } : new Error("Offline");+ fetch.mockRejectedValueOnce(error);+ if (failure === "transient") fetch.mockRejectedValueOnce(error);+ const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);+ if (failure === "transient") await expect(first[1]!.loadContents!()).rejects.toThrow("Offline");+ expect(await first[1]!.loadContents!()).toBeNull();+ const second = createPullRequestDiffHighlightFiles(+ { target },+ { ...parsed, files: [parsed.files[0]!, { ...parsed.files[1]! }] },+ files,+ fetch,+ cache,+ );+ expect(await second[1]!.loadContents!()).toBe(contents);+ expect(await first[1]!.loadContents!()).toBeNull();+ expect(fetch).toHaveBeenCalledTimes(failure === "permanent" ? 2 : 3);+ },+);++it("does not reuse reconstructed source after an appended page makes completeness uncertain", async () => {+ const { parsed, files } = setup();+ const cache = createPullRequestDiffHighlightCache();+ const reconstructed = { oldContents: "", newContents: "reconstructed" };+ const authoritative = { oldContents: "", newContents: "authoritative" };+ parsed.files[0] = { ...parsed.files[0]!, completePatchSource: () => reconstructed };+ const fetch = vi.fn(async () => AsyncResult.success(authoritative));+ const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);+ expect(await first[0]!.loadContents!()).toBe(reconstructed);+ const next = createPullRequestDiffHighlightFiles(+ { target },+ { ...parsed, notice: "Some file contents are unavailable" },+ files,+ fetch,+ cache,+ );+ expect(await next[0]!.loadContents!()).toBe(authoritative);+ expect(fetch).toHaveBeenCalledOnce();+});++it.each([+ ["characters", 2, 4_500_000],+ ["file count", 5, 1],+])(+ "shares the source cache's aggregate %s budget across appended pages",+ async (_name, count, size) => {+ const { parsed, files } = setup();+ const cache = createPullRequestDiffHighlightCache();+ const contents = { oldContents: "", newContents: "x".repeat(size) };+ const fetch = vi.fn(async () => AsyncResult.success(contents));+ const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);+ expect(await first[0]!.loadContents!()).toBe(contents);+ let next = first;+ for (let i = 1; i < count; i++) {+ const appended = file(`page-${i}`, `page-${i}.ts`, null);+ parsed.files.push(appended);+ files.push({ ...files[0]!, id: appended.id, path: appended.path });+ next = createPullRequestDiffHighlightFiles(+ { target },+ { ...parsed },+ [...files],+ fetch,+ cache,+ );+ expect(await next.at(-1)!.loadContents!()).toBe(contents);+ }+ expect(fetch).toHaveBeenCalledTimes(count);+ expect(await next[0]!.loadContents!()).toBe(contents);+ expect(fetch).toHaveBeenCalledTimes(count + 1);+ },+);++function addedPatch(body: string, header = "@@ -0,0 +1,2 @@") {+ return `diff --git a/file.c b/file.c\nnew file mode 100644\n--- /dev/null\n+++ b/file.c\n${header}\n${body}`;+}++function loadPatch(patch: string, truncated = false) {+ const parsed = combinePullRequestDiffPages(+ [{ cursor: null, result: { patch, truncated, nextCursor: null } }],+ new WeakMap(),+ "complete-source",+ sourceControlClients.get("github").changeRequest,+ );+ if (parsed.kind !== "files") throw new Error("Expected parsed files");+ const files = parsed.files.map((file) => ({+ id: file.id,+ path: file.path,+ language: "c" as const,+ additions: file.additions,+ deletions: file.deletions,+ }));+ const authoritative = { oldContents: "provider old", newContents: "provider new" };+ const fetch = vi.fn(async () => AsyncResult.success(authoritative));+ const loaded = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch);+ return { loaded, fetch, authoritative };+}++it.each([0, 1])(+ "loads a complete 100k-line addition with empty-side start %s beyond the RPC cap",+ async (emptyStart) => {+ const source = "/* generated C */ int value = 1;\n".repeat(100_000);+ const body = source.replace(/^/gm, "+").slice(0, -1);+ const { loaded, fetch } = loadPatch(addedPatch(body, `@@ -${emptyStart},0 +1,100000 @@`));+ expect(source.length).toBeGreaterThan(1_048_576);+ const contents = await loaded[0]!.loadContents!();+ expect(contents?.oldContents).toBe("");+ expect(contents?.newContents.length).toBe(source.length);+ expect(contents?.newContents === source).toBe(true);+ expect(fetch).not.toHaveBeenCalled();+ },+);++it.each([+ ["LF", "+first\n+last\n", "first\nlast\n"],+ ["CRLF", "+first\r\n+last\r\n", "first\r\nlast\r\n"],+ ["missing EOF newline", "+first\r\n+last\n\\ No newline at end of file\n", "first\r\nlast"],+ ["final bare CR", "+first\r\n+last\r\n\\ No newline at end of file\n", "first\r\nlast\r"],+])("preserves %s for complete additions and deletions", async (_name, body, source) => {+ for (const emptyStart of [0, 1]) {+ const added = addedPatch(body, `@@ -${emptyStart},0 +1,2 @@`);+ const deleted = added+ .replace("new file mode", "deleted file mode")+ .replace("--- /dev/null\n+++ b/file.c", "--- a/file.c\n+++ /dev/null")+ .replace(`@@ -${emptyStart},0 +1,2 @@`, `@@ -1,2 +${emptyStart},0 @@`);+ const deletionPatch = deleted.replace(body, body.replace(/\+/g, "-"));+ for (const [patch, expected] of [+ [added, { oldContents: "", newContents: source }],+ [deletionPatch, { oldContents: source, newContents: "" }],+ ] as const) {+ const { loaded, fetch } = loadPatch(patch);+ expect(await loaded[0]!.loadContents!()).toEqual(expected);+ expect(fetch).not.toHaveBeenCalled();+ }+ }+});++it.each([+ ["too few lines", addedPatch("+first\n", "@@ -0,0 +1,2 @@")],+ ["too many lines", addedPatch("+first\n+last\n", "@@ -0,0 +1 @@")],+ ["zero repaired count", addedPatch("+first\n+last\n", "@@ -0,0 +1,0 @@")],+ ["unterminated patch line", addedPatch("+first\n+last")],+ ["missing count", addedPatch("+first\n+last\n", "@@ -0,0 +1, @@")],+ ["gap", addedPatch("+first\n+last\n", "@@ -0,0 +2,2 @@")],+ ["invalid empty-side start", addedPatch("+first\n+last\n", "@@ -2,0 +1,2 @@")],+ ["converted underfull hunk", addedPatch("+first\n", "@@ -1,0 +1,2 @@")],+ ["converted overfull hunk", addedPatch("+first\n+last\n", "@@ -1,0 +1 @@")],+ ["converted nonempty old side", addedPatch("+first\n+last\n", "@@ -1,1 +1,2 @@")],+ ["context", addedPatch(" first\n+last\n", "@@ -1 +1,2 @@")],+ ["mixed sides", addedPatch("-first\n+last\n", "@@ -1 +1 @@")],+ ["second hunk", addedPatch("+first\n@@ -0,0 +2 @@\n+last\n", "@@ -0,0 +1 @@")],+ ["early EOF marker", addedPatch("+first\n\\ No newline at end of file\n+last\n")],+ ["unknown marker", addedPatch("+first\n+last\n\\ unknown\n")],+ ["trailing garbage", addedPatch("+first\n+last\nignored\n")],+ ["submodule", addedPatch("+first\n+last\n").replace("100644", "160000")],+ [+ "binary",+ addedPatch("+first\n+last\n").replace("--- /dev/null", "Binary files differ\n--- /dev/null"),+ ],+ ["changed", addedPatch("+first\n+last\n").replace("new file mode 100644\n", "")],+ [+ "rename",+ addedPatch("+first\n+last\n").replace(+ "new file mode 100644",+ "similarity index 50%\nrename from old.c\nrename to file.c",+ ),+ ],+ ["truncation marker", addedPatch("+first\n+last\n\n[truncated]\n")],+])("uses authoritative RPC source when completeness is unproven: %s", async (_name, patch) => {+ const { loaded, fetch, authoritative } = loadPatch(patch);+ expect(await loaded[0]!.loadContents!()).toBe(authoritative);+ expect(fetch).toHaveBeenCalledOnce();+});++it("rejects a complete-looking patch when the provider marks any page truncated", async () => {+ const { loaded, fetch, authoritative } = loadPatch(addedPatch("+first\n+last\n"), true);+ expect(await loaded[0]!.loadContents!()).toBe(authoritative);+ expect(fetch).toHaveBeenCalledOnce();+});diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffHighlightFiles.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffHighlightFiles.tsnew file mode 100644index 00000000000..8d9432368f7--- /dev/null+++ b/apps/mobile/src/features/pull-requests/pullRequestDiffHighlightFiles.ts@@ -0,0 +1,113 @@+import {+ squashAtomCommandFailure,+ type AtomCommandResult,+} from "@t3tools/client-runtime/state/runtime";+import type {+ PullRequestDiffFileContentsInput,+ PullRequestDiffFileContentsResult,+} from "@t3tools/contracts";++import { createNativeReviewDiffSourceLoader } from "../diffs/nativeReviewDiffSource";+import {+ diffHighlightTraceHash,+ diffHighlightTraceId,+ traceDiffHighlight,+} from "../diffs/nativeReviewDiffTrace";+import type { NativeReviewDiffFile, NativeReviewDiffSource } from "../diffs/nativeReviewDiffTypes";+import type { ReviewParsedDiff, ReviewRenderableFile } from "../review/reviewModel";+import type { pullRequestTarget } from "./usePullRequestDiff";++type FetchContents<E> = (request: {+ readonly environmentId: ReturnType<typeof pullRequestTarget>["environmentId"];+ readonly input: PullRequestDiffFileContentsInput;+}) => Promise<AtomCommandResult<PullRequestDiffFileContentsResult, E>>;++type SourceRequest = () => Promise<NativeReviewDiffSource>;++interface SourceSnapshot {+ readonly firstFile: ReviewRenderableFile;+ readonly scope: string;+ readonly load: ReturnType<typeof createNativeReviewDiffSourceLoader<SourceRequest>>;+ readonly requests: WeakMap<+ ReviewRenderableFile,+ { readonly completePatch: boolean; readonly request: SourceRequest }+ >;+}++export function createPullRequestDiffHighlightCache(): { snapshot?: SourceSnapshot } {+ return {};+}++export function createPullRequestDiffHighlightFiles<E>(+ source: {+ readonly target: ReturnType<typeof pullRequestTarget>;+ readonly commit?: string;+ },+ parsed: ReviewParsedDiff,+ files: ReadonlyArray<NativeReviewDiffFile>,+ fetchContents: FetchContents<E>,+ cache = createPullRequestDiffHighlightCache(),+): ReadonlyArray<NativeReviewDiffFile> {+ if (parsed.kind !== "files" || !parsed.files[0]) return files;+ const byId = new Map(parsed.files.map((file) => [file.id, file]));+ const { target, commit } = source;+ traceDiffHighlight("source-target", {+ environment: diffHighlightTraceHash(target.environmentId),+ project: diffHighlightTraceHash(target.input.projectId),+ pr: target.input.number,+ gitcafe: target.input.host === "git.cafe",+ });+ const scope = JSON.stringify([+ target.environmentId,+ target.input.projectId,+ target.input.repository,+ target.input.number,+ target.input.host,+ commit,+ ]);+ const firstFile = parsed.files[0];+ // Appended pages share one loader budget; a new first file starts a new snapshot.+ let snapshot = cache.snapshot;+ if (!snapshot || snapshot.firstFile !== firstFile || snapshot.scope !== scope) {+ snapshot = {+ firstFile,+ scope,+ load: createNativeReviewDiffSourceLoader<SourceRequest>((request) => request()),+ requests: new WeakMap(),+ };+ cache.snapshot = snapshot;+ }+ const { load, requests } = snapshot;+ return files.map((nativeFile) => {+ const file = byId.get(nativeFile.id);+ if (!file) return nativeFile;+ const completePatch = parsed.notice === null && !!file.completePatchSource;+ const cached = requests.get(file);+ if (cached?.completePatch === completePatch)+ return { ...nativeFile, loadContents: (signal) => load(cached.request, signal) };+ const request: SourceRequest = async () => {+ if (completePatch && file.completePatchSource) return file.completePatchSource();+ traceDiffHighlight("source-params", {+ file: diffHighlightTraceId(file.id),+ oldPath: diffHighlightTraceHash(file.previousPath ?? file.path),+ newPath: diffHighlightTraceHash(file.path),+ changeType: file.changeType,+ hasCommit: !!commit,+ });+ const result = await fetchContents({+ ...target,+ input: {+ ...target.input,+ ...(commit ? { commit } : {}),+ changeType: file.changeType,+ oldPath: file.previousPath ?? file.path,+ newPath: file.path,+ },+ });+ if (result._tag !== "Success") throw squashAtomCommandFailure(result);+ return result.value;+ };+ requests.set(file, { completePatch, request });+ return { ...nativeFile, loadContents: (signal) => load(request, signal) };+ });+}diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.tsindex 8c3258e44b5..c30f3a3198a 100644--- a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts+++ b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts@@ -65,7 +65,8 @@ export function combinePullRequestDiffPages(additions: files.reduce((total, file) => total + file.additions, 0),deletions: files.reduce((total, file) => total + file.deletions, 0),notice:- pages.some((page) => page.result.truncated) || parsed.some((page) => page.kind === "raw")+ pages.some((page) => page.result.truncated) ||+ parsed.some((page) => page.kind === "raw" || (page.kind === "files" && page.notice !== null))? `Some file contents are unavailable. Open the ${terminology.singular} on its provider to see the full changes.`: null,};diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx b/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsxnew file mode 100644index 00000000000..0548cbb2419--- /dev/null+++ b/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx@@ -0,0 +1,118 @@+import { RegistryContext } from "@effect/atom-react";+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";+import type { PullRequestDiffResult } from "@t3tools/contracts";+import * as Effect from "effect/Effect";+import { Atom, AtomRegistry } from "effect/reactivity";+import { act, useLayoutEffect } from "react";+import { createRoot } from "react-dom/client";+import { expect, it, vi } from "vite-plus/test";++const mocks = vi.hoisted(() => ({ diff: vi.fn() }));+vi.mock("../../state/pull-requests", () => ({ composerPullRequests: { diff: mocks.diff } }));++import { usePullRequestDiff } from "./usePullRequestDiff";++function patch(path: string, nextCursor: string | null = null): PullRequestDiffResult {+ return {+ patch: `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-old\n+new\n`,+ truncated: false,+ nextCursor,+ };+}++function setup() {+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+ const registry = AtomRegistry.make();+ const requests: {+ cursor: string | null;+ resolve: (value: PullRequestDiffResult) => void;+ reject: (error: Error) => void;+ }[] = [];+ const queries = Atom.family((cursor: string | null) =>+ Atom.make(+ Effect.tryPromise(+ () =>+ new Promise<PullRequestDiffResult>((resolve, reject) => {+ requests.push({ cursor, resolve, reject });+ }),+ ),+ ).pipe(Atom.keepAlive),+ );+ mocks.diff.mockImplementation((target: { input: { cursor?: string } }) =>+ queries(target.input.cursor ?? null),+ );+ const root = createRoot(document.createElement("div"));+ let current: ReturnType<typeof usePullRequestDiff>;+ function Probe() {+ const result = usePullRequestDiff(+ {+ environmentId: "environment",+ projectId: "project",+ repository: "repo",+ number: 1,+ },+ sourceControlClients.get("github").changeRequest,+ );+ useLayoutEffect(() => {+ current = result;+ });+ return null;+ }+ act(() =>+ root.render(+ <RegistryContext.Provider value={registry}>+ <Probe />+ </RegistryContext.Provider>,+ ),+ );+ return {+ requests,+ get current() {+ return current;+ },+ async succeed(index: number, result: PullRequestDiffResult) {+ await act(async () => {+ requests[index]!.resolve(result);+ });+ },+ async fail(index: number) {+ await act(async () => {+ requests[index]!.reject(new Error("Connection lost"));+ });+ },+ [Symbol.dispose]() {+ act(() => root.unmount());+ registry.dispose();+ },+ };+}++it("retries a failed continuation without discarding loaded files or restarting page one", async () => {+ using screen = setup();+ await screen.succeed(0, patch("first.ts", "second"));+ act(() => screen.current.loadMore());+ await screen.fail(1);+ expect(screen.current.error).not.toBeNull();+ expect(screen.current.patch).toContain("first.ts");++ act(() => screen.current.refresh());+ expect(screen.requests.map((request) => request.cursor)).toEqual([null, "second", "second"]);+ expect(screen.current.patch).toContain("first.ts");+ await screen.succeed(2, patch("second.ts"));+ expect(screen.current.error).toBeNull();+ expect(screen.current.parsed.kind).toBe("files");+ if (screen.current.parsed.kind !== "files") throw new Error("Expected files");+ expect(screen.current.parsed.files.map((file) => file.path)).toEqual(["first.ts", "second.ts"]);+ expect(screen.current.nextCursor).toBeNull();+});++it("still refreshes from page one after successfully loading a continuation", async () => {+ using screen = setup();+ await screen.succeed(0, patch("first.ts", "second"));+ act(() => screen.current.loadMore());+ await screen.succeed(1, patch("second.ts"));+ act(() => screen.current.refresh());+ await screen.succeed(2, patch("refreshed.ts"));+ if (screen.current.parsed.kind !== "files") throw new Error("Expected files");+ expect(screen.current.parsed.files.map((file) => file.path)).toEqual(["refreshed.ts"]);+});diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts b/apps/mobile/src/features/pull-requests/usePullRequestDiff.tsindex cef9be5db17..2b33c86871a 100644--- a/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts+++ b/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts@@ -87,10 +87,15 @@ export function usePullRequestDiff(if (!canLoadMore) return;setState({ key, cursor: nextCursor, pages });}, [canLoadMore, key, nextCursor, pages, setState]);+ const { error, refresh: refreshPage } = query;const refresh = useCallback(() => {+ if (cursor !== null && error !== null) {+ refreshPage();+ return;+ }setState({ key, cursor: null, pages: NO_PAGES });refreshFirstPage();- }, [key, refreshFirstPage, setState]);+ }, [cursor, error, refreshPage, key, refreshFirstPage, setState]);const onPullRefresh = useCallback(() => {setState({ key, cursor: null, pages: NO_PAGES });onRefresh();diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDiffHighlightFiles.ts b/apps/mobile/src/features/pull-requests/usePullRequestDiffHighlightFiles.tsnew file mode 100644index 00000000000..ddbc8520dcd--- /dev/null+++ b/apps/mobile/src/features/pull-requests/usePullRequestDiffHighlightFiles.ts@@ -0,0 +1,78 @@+import { useMemo } from "react";+import { EnvironmentId } from "@t3tools/contracts";+import * as Option from "effect/Option";++import { environmentCatalog } from "../../connection/catalog";+import { appAtomRegistry } from "../../state/atom-registry";+import { composerPullRequests } from "../../state/pull-requests";+import { useAtomCommand } from "../../state/use-atom-command";+import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes";+import { diffHighlightTraceHash, traceDiffHighlight } from "../diffs/nativeReviewDiffTrace";+import type { ReviewParsedDiff } from "../review/reviewModel";+import {+ createPullRequestDiffHighlightCache,+ createPullRequestDiffHighlightFiles,+} from "./pullRequestDiffHighlightFiles";+import { pullRequestTarget, type PullRequestDiffParams } from "./usePullRequestDiff";++function traceSourceEndpoint(environmentId: string, url: string) {+ try {+ const endpoint = new URL(url);+ traceDiffHighlight("source-endpoint", {+ environment: diffHighlightTraceHash(environmentId),+ origin: diffHighlightTraceHash(endpoint.origin),+ port: endpoint.port || (endpoint.protocol === "https:" ? "443" : "80"),+ });+ } catch {+ traceDiffHighlight("source-endpoint-invalid");+ }+}++export function usePullRequestDiffHighlightFiles(+ params: PullRequestDiffParams,+ parsed: ReviewParsedDiff,+ files: ReadonlyArray<NativeReviewDiffFile>,+) {+ const fetchContents = useAtomCommand(composerPullRequests.diffFileContents, {+ reportFailure: false,+ });+ const { environmentId, projectId, repository, number, host, commit } = params;+ const cache = useMemo(() => createPullRequestDiffHighlightCache(), []);+ return useMemo(() => {+ if (process.env.EXPO_PUBLIC_T3_DIFF_TRACE === "1") {+ const catalog = appAtomRegistry.get(environmentCatalog.catalogValueAtom);+ const entry = catalog.entries.get(EnvironmentId.make(environmentId));+ const profile = entry && Option.getOrUndefined(entry.profile);+ const url =+ entry?.target._tag === "PrimaryConnectionTarget"+ ? entry.target.httpBaseUrl+ : profile?._tag === "BearerConnectionProfile"+ ? profile.httpBaseUrl+ : undefined;+ if (url) {+ traceSourceEndpoint(environmentId, url);+ } else traceDiffHighlight("source-endpoint-unavailable");+ }+ return createPullRequestDiffHighlightFiles(+ {+ target: pullRequestTarget({ environmentId, projectId, repository, number, host }),+ commit,+ },+ parsed,+ files,+ fetchContents,+ cache,+ );+ }, [+ environmentId,+ projectId,+ repository,+ number,+ host,+ commit,+ parsed,+ files,+ fetchContents,+ cache,+ ]);+}diff --git a/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts b/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.tsindex 12317f1bfa7..7e620836bac 100644--- a/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts+++ b/apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts@@ -1,11 +1,19 @@-import { describe, expect, it } from "vite-plus/test";+import { describe, expect, it, vi } from "vite-plus/test";+import { diffWordsWithSpace } from "diff";+import { AsyncResult } from "effect/reactivity";+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";+import { EnvironmentId, ProjectId, type PullRequestDiffResult } from "@t3tools/contracts";+import { combinePullRequestDiffPages } from "../pull-requests/pullRequestDiffPages";+import { createPullRequestDiffHighlightFiles } from "../pull-requests/pullRequestDiffHighlightFiles";import {buildNativeReviewDiffData,getCachedNativeReviewDiffData,} from "./nativeReviewDiffAdapter";import type { ReviewInlineComment } from "./reviewCommentSelection";-import { buildReviewParsedDiff } from "./reviewModel";+import { buildReviewParsedDiff, type ReviewParsedDiff } from "./reviewModel";++vi.mock("diff", { spy: true });function makeComment(text: string): ReviewInlineComment {return {@@ -38,7 +46,202 @@ function filesPatch(paths: ReadonlyArray<string>) {.join("\n");}+describe("buildNativeReviewDiffData languages", () => {+ it.each([+ ["js", "javascript"],+ ["cjs", "javascript"],+ ["mjs", "javascript"],+ ["jsx", "jsx"],+ ["ts", "typescript"],+ ["mts", "typescript"],+ ["cts", "typescript"],+ ["tsx", "tsx"],+ ])("assigns %s files their syntax language when deleted", (extension, language) => {+ const path = `scripts/dev-runner.${extension}`;+ const data = buildNativeReviewDiffData(+ buildReviewParsedDiff(+ [+ `diff --git a/${path} b/${path}`,+ "deleted file mode 100644",+ `--- a/${path}`,+ "+++ /dev/null",+ "@@ -1,2 +0,0 @@",+ '-import process from "node:process";',+ "-const port = process.env.PORT;",+ "",+ ].join("\n"),+ "deleted-script-language",+ ),+ );++ expect(data.files).toMatchObject([{ path, language }]);+ expect(data.rows.filter((row) => row.kind === "line")).toMatchObject([+ { content: 'import process from "node:process";', change: "delete" },+ { content: "const port = process.env.PORT;", change: "delete" },+ ]);+ });+});+describe("getCachedNativeReviewDiffData", () => {+ it("keeps compact identities aligned through page append, filtering, comments, and source lookup", async () => {+ const scope = JSON.stringify({ remote: 'long-target\\"'.repeat(100) });+ const cache = new WeakMap<PullRequestDiffResult, ReviewParsedDiff>();+ const firstPage = {+ cursor: null,+ result: {+ patch: filesPatch(["example.ts", "hidden.test.ts"]),+ truncated: false,+ nextCursor: "next",+ },+ };+ const terminology = sourceControlClients.get("github").changeRequest;+ const first = combinePullRequestDiffPages([firstPage], cache, scope, terminology);+ if (first.kind !== "files") throw new Error("Expected parsed first page");+ const before = getCachedNativeReviewDiffData({ parsedDiff: first });+ const selectedRowId = before.rows.find((row) => row.kind === "line")!.id;+ const combined = combinePullRequestDiffPages(+ [+ firstPage,+ {+ cursor: "next",+ result: { patch: filesPatch(["last.ts"]), truncated: false, nextCursor: null },+ },+ ],+ cache,+ scope,+ terminology,+ );+ if (combined.kind !== "files") throw new Error("Expected parsed appended pages");+ expect(combined.files[0]).toBe(first.files[0]);+ const filtered = {+ ...combined,+ files: combined.files.filter((file) => !file.path.includes(".test.")),+ };+ const input = { parsedDiff: filtered, comments: [makeComment("Feedback")] };+ const data = getCachedNativeReviewDiffData(input);+ expect(getCachedNativeReviewDiffData(input)).toBe(data);+ expect(new Set(data.rows.map((row) => row.id)).size).toBe(data.rows.length);+ expect(data.rows.find((row) => row.id === selectedRowId)).toBe(+ before.rows.find((row) => row.id === selectedRowId),+ );+ // IDs used by native initialFileId/collapse and parsed source lookup share one namespace.+ expect(data.files.map((file) => file.id)).toEqual(filtered.files.map((file) => file.id));+ for (const file of filtered.files) {+ const header = data.rows.find((row) => row.kind === "file" && row.fileId === file.id)!;+ expect(header.filePath).toBe(file.path);+ const lines = file.rows.filter((row) => row.kind === "line");+ for (const [lineIndex, line] of lines.entries()) {+ const nativeId = data.rowIdByCommentLineId.get(line.id)!;+ const row = data.rows.find((row) => row.id === nativeId)!;+ expect(row.fileId).toBe(file.id);+ expect(row.content).toBe(line.content);+ expect(nativeId.length).toBeLessThan(64);+ const target = data.commentTargetsByRowId.get(nativeId)!;+ expect(target.filePath).toBe(file.path);+ expect(target.lines[lineIndex]).toBe(line);+ expect(target.lineIndex).toBe(lineIndex);+ expect(row.wordDiffRanges?.length).toBeGreaterThan(0);+ expect(+ row.wordDiffRanges?.map((range) => row.content!.slice(range.start, range.end)),+ ).toEqual([line.change === "delete" ? "before" : "after"]);+ }+ }+ const commentIndex = data.rows.findIndex((row) => row.id === "comment-1");+ expect(data.rows[commentIndex - 1]!.id).toBe(selectedRowId);+ expect(data.rows[commentIndex]!.fileId).toBe(first.files[0]!.id);++ const target = {+ environmentId: EnvironmentId.make("remote"),+ input: {+ projectId: ProjectId.make("project"),+ repository: "org/repo",+ number: 23,+ },+ };+ const contents = { oldContents: "old source", newContents: "new source" };+ const fetch = vi.fn(async () => AsyncResult.success(contents));+ const highlightFiles = createPullRequestDiffHighlightFiles(+ { target },+ filtered,+ data.files,+ fetch,+ );+ expect(await highlightFiles[1]!.loadContents!()).toBe(contents);+ expect(fetch).toHaveBeenCalledExactlyOnceWith({+ ...target,+ input: { ...target.input, changeType: "change", oldPath: "last.ts", newPath: "last.ts" },+ });+ expect(JSON.stringify(data.rows).length).toBeLessThan(5000);+ });++ it("keeps Pierre's matching lines in the GitHub credential pinning excerpt", () => {+ const parsed = buildReviewParsedDiff(+ [+ "diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts",+ "--- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts",+ "+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts",+ "@@ -1221,11 +1240,4 @@",+ "- operation: input.operation,",+ "- path: input.path,",+ "- ...(Option.isSome(previous) ? { ifNoneMatch: previous.value.etag } : {}),",+ "- })",+ "- .pipe(",+ "- Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, {",+ "- host,",+ "- token,",+ "- credentialFingerprint: fingerprint,",+ "- }),",+ "- );",+ "+ token,",+ "+ credentialFingerprint: fingerprint,",+ "+ }),",+ "+ );",+ "",+ ].join("\n"),+ "credential-pinning",+ );+ expect(parsed.kind).toBe("files");+ if (parsed.kind !== "files") return;+ expect(+ parsed.files[0]?.rows.find((row) => row.kind === "line" && row.newLineNumber === 1242),+ ).toMatchObject({+ comparison: { change: "delete", tokenIndex: 9 },+ });+ const data = buildNativeReviewDiffData(parsed);+ expect(+ data.rows.find((row) => row.kind === "line" && row.newLineNumber === 1242)?.wordDiffRanges,+ ).toBeUndefined();+ });++ it.each([+ [true, false, "Old file has no newline at end of file."],+ [false, true, "New file has no newline at end of file."],+ [true, true, "Old and new files have no newline at end of file."],+ [false, false, null],+ ])("shows missing-newline notices for old=%s new=%s", (oldMissing, newMissing, notice) => {+ const data = buildNativeReviewDiffData(+ buildReviewParsedDiff(+ [+ "diff --git a/example.ts b/example.ts",+ "--- a/example.ts",+ "+++ b/example.ts",+ "@@ -1 +1 @@",+ "-value",+ ...(oldMissing ? ["\\ No newline at end of file"] : []),+ "+value",+ ...(newMissing ? ["\\ No newline at end of file"] : []),+ "",+ ].join("\n"),+ "native-eof",+ ),+ );+ expect(data.rows.filter((row) => row.kind === "notice").map((row) => row.text)).toEqual(+ notice ? [notice] : [],+ );+ expect(data.rows.filter((row) => row.kind === "line")).toHaveLength(2);+ expect(data.commentTargetsByRowId.size).toBe(2);+ });+it("keeps cached IDs and targets local to each parsed section and file layout", () => {const original = filesPatch(["example.ts", "second.ts"]);const variants = [@@ -89,9 +292,9 @@ describe("buildNativeReviewDiffData row bound", () => {expect(data).toMatchObject({ additions: 201_000, deletions: 0 });const hugeRows = data.rows.filter((row) => row.fileId === hugeHeader?.fileId);expect(hugeRows.filter((row) => row.kind === "line" || row.kind === "hunk")).toHaveLength(- 2_000,+ 100_000,);- expect(hugeRows.at(-2)).toMatchObject({ kind: "line", newLineNumber: 1_999 });+ expect(hugeRows.at(-2)).toMatchObject({ kind: "line", newLineNumber: 99_999 });expect(hugeRows.at(-1)).toMatchObject({kind: "notice",text: "This diff is too large to show in full.",@@ -106,3 +309,65 @@ describe("buildNativeReviewDiffData row bound", () => {expect(ordinaryRows.some((row) => row.kind === "notice")).toBe(false);});});++describe("buildNativeReviewDiffData word comparison bound", () => {+ function modifiedFilePatch(pairCount: number, contextCount = 0) {+ const lineCount = pairCount + contextCount;+ return [+ "diff --git a/example.ts b/example.ts",+ "--- a/example.ts",+ "+++ b/example.ts",+ `@@ -1,${lineCount} +1,${lineCount} @@`,+ ...Array.from({ length: contextCount }, (_, index) => ` const context${index} = true;`),+ ...Array.from(+ { length: pairCount },+ (_, index) => `-const value${index} = renderPanel({ label: "before", enabled: true });`,+ ),+ ...Array.from(+ { length: pairCount },+ (_, index) => `+const value${index} = renderPanel({ label: "after", enabled: true });`,+ ),+ ].join("\n");+ }++ it("bounds eager word comparisons without truncating a large modified file", () => {+ const parsedDiff = buildReviewParsedDiff(modifiedFilePatch(20_000), "native-word-bound");+ const comparisons = vi.mocked(diffWordsWithSpace).mockClear();+ const data = buildNativeReviewDiffData(parsedDiff);++ expect(comparisons).toHaveBeenCalledTimes(1_000);+ expect(data).toMatchObject({ additions: 20_000, deletions: 20_000 });+ const lines = data.rows.filter((row) => row.kind === "line");+ expect(lines).toHaveLength(40_000);+ expect(data.rows.some((row) => row.kind === "notice")).toBe(false);+ for (const offset of [0, 20_000]) {+ expect(lines[offset]?.wordDiffRanges?.length).toBeGreaterThan(0);+ expect(lines[offset + 999]?.wordDiffRanges?.length).toBeGreaterThan(0);+ expect(lines[offset + 1_000]?.wordDiffRanges).toBeUndefined();+ }+ expect(lines.at(-1)).toMatchObject({+ content: 'const value19999 = renderPanel({ label: "after", enabled: true });',+ newLineNumber: 20_000,+ });+ expect(data.commentTargetsByRowId.size).toBe(40_000);+ expect(data.commentTargetsByRowId.get(lines.at(-1)!.id)?.lineIndex).toBe(39_999);+ });++ it.each([0, 20_000])("preserves small word differences with %s context rows", (contextCount) => {+ const parsedDiff = buildReviewParsedDiff(+ modifiedFilePatch(2, contextCount),+ "native-word-context",+ );+ const comparisons = vi.mocked(diffWordsWithSpace).mockClear();+ const data = buildNativeReviewDiffData(parsedDiff);++ expect(comparisons).toHaveBeenCalledTimes(2);+ const changes = data.rows.filter((row) => row.kind === "line" && row.change !== "context");+ expect(changes).toHaveLength(4);+ for (const row of changes) {+ expect(+ row.wordDiffRanges?.map((range) => row.content!.slice(range.start, range.end)),+ ).toEqual([row.change === "delete" ? "before" : "after"]);+ }+ });+});diff --git a/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts b/apps/mobile/src/features/review/nativeReviewDiffAdapter.tsindex d49302764b1..02c699fe097 100644--- a/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts+++ b/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts@@ -17,8 +17,10 @@ import type { ReviewInlineComment } from "./reviewCommentSelection";const NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT = 4;const NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE = 0.45;+// Keep eager word matching within the old 2,000-row budget while retaining more rendered rows.+const NATIVE_REVIEW_MAX_WORD_DIFF_COMPARISONS = 1_000;// Bound the rows serialized to the native heap before mapping and word matching.-const NATIVE_REVIEW_MAX_FILE_ROWS = 2_000;+const NATIVE_REVIEW_MAX_FILE_ROWS = 100_000;const TRUNCATED_FILE_NOTICE = "This diff is too large to show in full.";const NATIVE_HEX_COLOR = /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})([\da-f]{2})?$/i;const NATIVE_RGBA_COLOR =@@ -311,63 +313,46 @@ function shouldUseWordDiffRanges(function addNativeWordDiffRanges(rows: ReadonlyArray<NativeReviewDiffRow>,+ lineRows: ReadonlyArray<ReviewRenderableLineRow>,): ReadonlyArray<NativeReviewDiffRow> {const nextRows = [...rows];- let index = 0;-- while (index < nextRows.length) {- const deletedRowIndexes: number[] = [];- const addedRowIndexes: number[] = [];- const fileId = nextRows[index]?.fileId;-- while (- nextRows[index]?.kind === "line" &&- nextRows[index]?.change === "delete" &&- nextRows[index]?.fileId === fileId- ) {- deletedRowIndexes.push(index);- index += 1;- }+ const addedRowIndexes = new Map<number, number>();+ const pairs: Array<{ deletionRowIndex: number; additionTokenIndex: number }> = [];+ let lineIndex = 0;- while (- nextRows[index]?.kind === "line" &&- nextRows[index]?.change === "add" &&- nextRows[index]?.fileId === fileId- ) {- addedRowIndexes.push(index);- index += 1;+ // Pierre can split adjacent change blocks to align similar lines. Keep those pairings.+ rows.forEach((row, rowIndex) => {+ if (row.kind !== "line") return;+ const source = lineRows[lineIndex++];+ if (source?.change === "add" && source.additionTokenIndex !== null) {+ addedRowIndexes.set(source.additionTokenIndex, rowIndex);+ } else if (source?.change === "delete" && source.comparison?.change === "add") {+ pairs.push({ deletionRowIndex: rowIndex, additionTokenIndex: source.comparison.tokenIndex });}+ });- const pairedCount = Math.min(deletedRowIndexes.length, addedRowIndexes.length);- for (let pairIndex = 0; pairIndex < pairedCount; pairIndex += 1) {- const deletedRowIndex = deletedRowIndexes[pairIndex];- const addedRowIndex = addedRowIndexes[pairIndex];- if (deletedRowIndex === undefined || addedRowIndex === undefined) {- continue;- }- 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);+ let comparisonCount = 0;+ for (const { deletionRowIndex, additionTokenIndex } of pairs) {+ if (comparisonCount >= NATIVE_REVIEW_MAX_WORD_DIFF_COMPARISONS) break;+ const addedRowIndex = addedRowIndexes.get(additionTokenIndex);+ if (addedRowIndex === undefined) continue;+ const deletedRow = nextRows[deletionRowIndex];+ const addedRow = nextRows[addedRowIndex];+ if (!deletedRow?.content || !addedRow?.content) continue;++ comparisonCount += 1;+ 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 };- }+ if (shouldUseWordDiffRanges(deletedRow.content, deletionRanges)) {+ nextRows[deletionRowIndex] = { ...deletedRow, wordDiffRanges: deletionRanges };}-- if (deletedRowIndexes.length === 0 && addedRowIndexes.length === 0) {- index += 1;+ if (shouldUseWordDiffRanges(addedRow.content, additionRanges)) {+ nextRows[addedRowIndex] = { ...addedRow, wordDiffRanges: additionRanges };}}@@ -440,13 +425,21 @@ function prepareFileRows(file: ReviewRenderableFile): PreparedNativeReviewFileRorows.push(createNoticeRow(file.id, "truncated", TRUNCATED_FILE_NOTICE));}rows.push(...noticeRowsForFile(file));+ if (file.noEOFCRAdditions || file.noEOFCRDeletions) {+ const side = file.noEOFCRAdditions+ ? file.noEOFCRDeletions+ ? "Old and new files have"+ : "New file has"+ : "Old file has";+ rows.push(createNoticeRow(file.id, "eof", `${side} no newline at end of file.`));+ }const prepared: PreparedNativeReviewFileRows = {fileId: file.id,filePath: file.path,lineCount: lineRows.length,truncated: sourceRows !== file.rows,- // Comments must not split the source deletion/addition runs used for word matching.- rows: addNativeWordDiffRanges(rows),+ // Pair source lines before inserting comments so comment rows cannot affect matching.+ rows: addNativeWordDiffRanges(rows, lineRows),commentTargetsByRowId,rowIdByCommentLineId,commentedRows: null,diff --git a/apps/mobile/src/features/review/reviewDiffHighlightScheduler.ts b/apps/mobile/src/features/review/reviewDiffHighlightScheduler.tsindex d2e986e925b..8da759a0223 100644--- a/apps/mobile/src/features/review/reviewDiffHighlightScheduler.ts+++ b/apps/mobile/src/features/review/reviewDiffHighlightScheduler.ts@@ -6,7 +6,7 @@ export interface NativeReviewVisibleRange {export function createReviewDiffHighlightScheduler(request: (range: NativeReviewVisibleRange) => void,) {- let requestedRange: NativeReviewVisibleRange = { firstRowIndex: 0, lastRowIndex: 80 };+ let requestedRange: NativeReviewVisibleRange | undefined;let visibleRange = requestedRange;let timer: ReturnType<typeof setTimeout> | undefined;@@ -17,19 +17,25 @@ export function createReviewDiffHighlightScheduler(const flush = () => {cancel();requestedRange = visibleRange;- request(visibleRange);+ if (visibleRange) request(visibleRange);};return {update(nextRange: NativeReviewVisibleRange) {if (- nextRange.firstRowIndex === visibleRange.firstRowIndex &&+ nextRange.firstRowIndex === visibleRange?.firstRowIndex &&nextRange.lastRowIndex === visibleRange.lastRowIndex) {return;}visibleRange = nextRange;cancel();+ if (!requestedRange) {+ // Native publishes a pre-jump range and its initial destination together.+ // Yield once so the destination wins before sending an unabortable source RPC.+ timer = setTimeout(flush, 0);+ return;+ }const movedRows =Math.abs(nextRange.firstRowIndex - requestedRange.firstRowIndex) +Math.abs(nextRange.lastRowIndex - requestedRange.lastRowIndex);@@ -41,8 +47,10 @@ export function createReviewDiffHighlightScheduler(},reset() {cancel();- requestedRange = { firstRowIndex: 0, lastRowIndex: 80 };+ const previousRange = visibleRange;+ requestedRange = undefined;visibleRange = requestedRange;+ return previousRange;},cancel,};diff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.tsindex c4f64329779..39d27de3d6d 100644--- a/apps/mobile/src/features/review/reviewModel.test.ts+++ b/apps/mobile/src/features/review/reviewModel.test.ts@@ -3,6 +3,123 @@ import { describe, expect, it } from "vite-plus/test";import { applyReviewDiffMetadata, buildReviewParsedDiff } from "./reviewModel";describe("buildReviewParsedDiff", () => {+ it("keeps UI identities compact, stable, and isolated from parser cache keys", () => {+ const patch =+ "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -1 +1 @@\n-before\n+after\n";+ const scope = JSON.stringify({ target: 'remote\\"scope'.repeat(100) });+ const parsed = buildReviewParsedDiff(patch + patch, scope);+ const repeated = buildReviewParsedDiff(patch + patch, scope);+ const otherSection = buildReviewParsedDiff(patch + patch, `${scope}:other`);+ const changed = buildReviewParsedDiff((patch + patch).replaceAll("after", "changed"), scope);+ if (+ parsed.kind !== "files" ||+ repeated.kind !== "files" ||+ otherSection.kind !== "files" ||+ changed.kind !== "files"+ )+ throw new Error("Expected structured diffs");++ expect(parsed.files).toHaveLength(2);+ expect(parsed.files.map((file) => file.id)).toEqual(repeated.files.map((file) => file.id));+ expect(parsed.files.map((file) => file.cacheKey)).toEqual(+ repeated.files.map((file) => file.cacheKey),+ );+ const ids = parsed.files.flatMap((file) => [file.id, ...file.rows.map((row) => row.id)]);+ expect(new Set(ids).size).toBe(ids.length);+ for (const id of ids) expect(id.length).toBeLessThan(48);+ for (const variant of [otherSection, changed]) {+ const otherIds = variant.files.flatMap((file) => [+ file.id,+ ...file.rows.map((row) => row.id),+ ]);+ expect(otherIds.some((id) => ids.includes(id))).toBe(false);+ }+ expect(parsed.files[0]!.cacheKey.length).toBeGreaterThan(scope.length);+ expect(parsed.files[0]!.id).not.toBe(parsed.files[0]!.cacheKey);+ expect(repeated.files[0]!.rows.map((row) => row.id)).toEqual(+ parsed.files[0]!.rows.map((row) => row.id),+ );+ });++ it.each(["", "\n\n[truncated]"])(+ "preserves the final blank context in the resourceTelemetry excerpt with suffix %j",+ (suffix) => {+ const parsed = buildReviewParsedDiff(+ [+ "diff --git a/packages/contracts/src/resourceTelemetry.ts b/packages/contracts/src/resourceTelemetry.ts",+ "--- a/packages/contracts/src/resourceTelemetry.ts",+ "+++ b/packages/contracts/src/resourceTelemetry.ts",+ "@@ -350,6 +371,7 @@",+ " DesktopTelemetryRequestDesktopUpdate,",+ " DesktopTelemetryCommitDesktopUpdate,",+ " DesktopTelemetryCancelDesktopUpdate,",+ "+ DesktopUpdateRestartPolicyResult,",+ " ]);",+ " export type DesktopTelemetryControlMessage = typeof DesktopTelemetryControlMessage.Type;",+ " ",+ "",+ ].join("\n") + suffix,+ "resource-telemetry",+ );+ expect(parsed.kind).toBe("files");+ if (parsed.kind !== "files") return;+ expect(parsed.files[0]?.rows.at(-1)).toMatchObject({+ kind: "line",+ change: "context",+ oldLineNumber: 355,+ newLineNumber: 377,+ content: "",+ });+ expect(parsed.files[0]?.additionLines.at(-1)).toBe("\n");+ expect(parsed.files[0]?.deletionLines.at(-1)).toBe("\n");+ },+ );++ it("preserves final content whitespace and gives distinct patches distinct cache keys", () => {+ const patch = "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -0,0 +1 @@\n+value \t\n";+ const parsed = buildReviewParsedDiff(patch, "whitespace");+ const withoutWhitespace = buildReviewParsedDiff(+ patch.replace("value \t", "value"),+ "whitespace",+ );+ expect(parsed.kind).toBe("files");+ expect(withoutWhitespace.kind).toBe("files");+ if (parsed.kind !== "files" || withoutWhitespace.kind !== "files") return;+ expect(parsed.files[0]?.rows.at(-1)).toMatchObject({ content: "value \t" });+ expect(parsed.files[0]?.additionLines).toEqual(["value \t\n"]);+ expect(parsed.files[0]?.cacheKey).not.toBe(withoutWhitespace.files[0]?.cacheKey);+ });++ it.each([+ [true, false],+ [false, true],+ [true, true],+ [false, false],+ ])("preserves missing-newline flags for old=%s and new=%s", (oldMissing, newMissing) => {+ const parsed = buildReviewParsedDiff(+ [+ "diff --git a/a.ts b/a.ts",+ "--- a/a.ts",+ "+++ b/a.ts",+ "@@ -1 +1 @@",+ "-value",+ ...(oldMissing ? ["\\ No newline at end of file"] : []),+ "+value",+ ...(newMissing ? ["\\ No newline at end of file"] : []),+ "",+ ].join("\n"),+ "eof",+ );+ expect(parsed.kind).toBe("files");+ if (parsed.kind !== "files") return;+ expect(parsed.files[0]).toMatchObject({+ noEOFCRDeletions: oldMissing,+ noEOFCRAdditions: newMissing,+ deletionLines: [oldMissing ? "value" : "value\n"],+ additionLines: [newMissing ? "value" : "value\n"],+ });+ });+it.each([["a/example.ts", "a/example.ts"],["a/before.ts", "b/after.ts"],diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.tsindex 7b82f02d006..a5b077e139a 100644--- a/apps/mobile/src/features/review/reviewModel.ts+++ b/apps/mobile/src/features/review/reviewModel.ts@@ -2,6 +2,7 @@ import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types";import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";import type { ReviewDiffPreviewSource } from "@t3tools/contracts";+import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath";import * as Arr from "effect/Array";import { pipe } from "effect/Function";import * as Order from "effect/Order";@@ -60,6 +61,13 @@ export interface ReviewRenderableFile {readonly languageHint: string | null;readonly additionLines: ReadonlyArray<string>;readonly deletionLines: ReadonlyArray<string>;+ // Only populated after validating the entire raw file block against its original hunk count.+ readonly completePatchSource?: () => {+ readonly oldContents: string;+ readonly newContents: string;+ };+ readonly noEOFCRAdditions?: boolean;+ readonly noEOFCRDeletions?: boolean;readonly rows: ReadonlyArray<ReviewRenderableRow>;}@@ -139,13 +147,13 @@ function splitTruncationMarker(diff: string): {readonly text: string;readonly truncated: boolean;} {- const trimmed = diff.trimEnd();- if (!trimmed.endsWith("[truncated]")) {- return { text: trimmed, truncated: false };+ const marker = /(?:(?:\r?\n){1,2}|^)\[truncated\]\s*$/.exec(diff);+ if (!marker) {+ return { text: diff, truncated: false };}return {- text: trimmed.replace(/\n*\[truncated\]\s*$/, "").trimEnd(),+ text: diff.slice(0, marker.index),truncated: true,};}@@ -219,14 +227,22 @@ function fnv1a32(input: string, seed: number, multiplier: number): number {}function buildPatchCacheKey(patch: string, scope: string): string {- const normalizedPatch = patch.trim();- const primary = fnv1a32(normalizedPatch, FNV_OFFSET_BASIS_32, FNV_PRIME_32).toString(36);- const secondary = fnv1a32(- normalizedPatch,- SECONDARY_HASH_SEED,- SECONDARY_HASH_MULTIPLIER,- ).toString(36);- return `${scope}:${normalizedPatch.length}:${primary}:${secondary}`;+ const primary = fnv1a32(patch, FNV_OFFSET_BASIS_32, FNV_PRIME_32).toString(36);+ const secondary = fnv1a32(patch, SECONDARY_HASH_SEED, SECONDARY_HASH_MULTIPLIER).toString(36);+ return `${scope}:${patch.length}:${primary}:${secondary}`;+}++// Re-parsing an unchanged page must preserve selection/collapse state. Intern only+// its cache key (never patch contents), keeping scoped Pierre keys off every UI row.+const reviewPatchIds = new Map<string, string>();++function getReviewPatchId(cacheKey: string): string {+ let id = reviewPatchIds.get(cacheKey);+ if (id === undefined) {+ id = `p${reviewPatchIds.size.toString(36)}`;+ reviewPatchIds.set(cacheKey, id);+ }+ return id;}function getFileExtension(path: string): string | null {@@ -276,14 +292,17 @@ function fallbackHunkHeader(hunk: FileDiffMetadata["hunks"][number]): string {return `@@ -${hunk.deletionStart},${hunk.deletionCount} +${hunk.additionStart},${hunk.additionCount} @@`;}-function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRenderableRow> {+function buildRenderableRows(+ file: FileDiffMetadata,+ fileId: string,+): ReadonlyArray<ReviewRenderableRow> {const rows: ReviewRenderableRow[] = [];let rowIndex = 0;file.hunks.forEach((hunk, hunkIndex) => {rows.push({kind: "hunk",- id: `${file.cacheKey ?? file.name}:hunk:${hunkIndex}`,+ id: `${fileId}:hunk:${hunkIndex}`,header: fallbackHunkHeader(hunk),context: hunk.hunkContext ? stripTrailingNewline(hunk.hunkContext) : null,});@@ -298,7 +317,7 @@ function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRenderfor (let index = 0; index < segment.lines; index += 1) {rows.push({kind: "line",- id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`,+ id: `${fileId}:row:${rowIndex++}`,change: "context",oldLineNumber: deletionLineNumber,newLineNumber: additionLineNumber,@@ -326,7 +345,7 @@ function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRenderfor (let index = 0; index < segment.deletions; index += 1) {rows.push({kind: "line",- id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`,+ id: `${fileId}:row:${rowIndex++}`,change: "delete",oldLineNumber: deletionLineNumber,newLineNumber: null,@@ -348,7 +367,7 @@ function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRenderfor (let index = 0; index < segment.additions; index += 1) {rows.push({kind: "line",- id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`,+ id: `${fileId}:row:${rowIndex++}`,change: "add",oldLineNumber: null,newLineNumber: additionLineNumber,@@ -372,7 +391,74 @@ function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRenderreturn rows;}-function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {+function completePatchSource(file: FileDiffMetadata, rawPatch: string | null | undefined) {+ if (!rawPatch || (file.type !== "new" && file.type !== "deleted") || file.hunks.length !== 1) {+ return undefined;+ }+ const added = file.type === "new";+ const a = quoteGitPatchPath(`a/${file.name}`);+ const b = quoteGitPatchPath(`b/${file.name}`);+ const lines = rawPatch.split("\n");+ if (lines.pop() !== "" || rawPatch.includes("\0")) return undefined;+ let index = 0;+ if (lines[index++] !== `diff --git ${a} ${b}`) return undefined;+ if (+ !new RegExp(`^${added ? "new" : "deleted"} file mode 100(644|755)$`).test(lines[index++] ?? "")+ ) {+ return undefined;+ }+ if (lines[index]?.startsWith("index ")) {+ if (!/^index [0-9a-f]+\.\.[0-9a-f]+(?: 100(?:644|755))?$/.test(lines[index++] ?? "")) {+ return undefined;+ }+ }+ if (lines[index++] !== `--- ${added ? "/dev/null" : a}`) return undefined;+ if (lines[index++] !== `+++ ${added ? b : "/dev/null"}`) return undefined;+ // Pierre repairs both underfull and overfull hunks. Its resulting counts cannot+ // prove that patch lines cover the whole file; read the original header instead.+ const header = lines[index++] ?? "";+ // GitCafe's structured hunks can start the empty side at 1 instead of git's 0.+ // Its explicit zero count still proves that side contributes no source lines.+ const match = (added ? /^@@ -[01],0 \+1(?:,(\d+))? @@$/ : /^@@ -1(?:,(\d+))? \+[01],0 @@$/).exec(+ header,+ );+ if (!match) return undefined;+ const count = Number(match[1] ?? 1);+ if (!Number.isSafeInteger(count) || count <= 0) return undefined;+ const hunk = file.hunks[0]!;+ if (+ hunk.hunkSpecs !== `${header}\n` ||+ (added ? hunk.additionCount : hunk.deletionCount) !== count ||+ (added ? file.additionLines : file.deletionLines).length !== count ||+ (added ? file.deletionLines : file.additionLines).length !== 0+ )+ return undefined;+ const bodyStart = lines.slice(0, index).reduce((length, line) => length + line.length + 1, 0);+ const prefix = added ? "+" : "-";+ for (let line = 0; line < count; line++) {+ if (!lines[index++]?.startsWith(prefix)) return undefined;+ }+ let bodyEnd = rawPatch.length;+ if (lines[index] === "\\ No newline at end of file") {+ // Only the patch's LF is synthetic, including when the source ends in a bare CR.+ bodyEnd -= "\\ No newline at end of file\n".length + 1;+ index++;+ }+ if (index !== lines.length) return undefined;+ // Keep reconstruction lazy so only requested source enters the bounded source cache.+ return () => {+ const contents = rawPatch.slice(bodyStart + 1, bodyEnd).replace(/\n[+-]/g, "\n");+ return added+ ? { oldContents: "", newContents: contents }+ : { oldContents: contents, newContents: "" };+ };+}++function mapRenderableFile(+ file: FileDiffMetadata,+ id: string,+ rawPatch?: string | null,+): ReviewRenderableFile {const path = file.name || file.prevName || "";const previousPath = file.prevName || null;const additions = file.hunks.reduce((total, hunk) => total + hunk.additionLines, 0);@@ -380,7 +466,7 @@ function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {const cacheKey = file.cacheKey ?? `${previousPath ?? "none"}:${path}:${file.type}`;return {- id: cacheKey,+ id,cacheKey,path,previousPath,@@ -390,7 +476,10 @@ function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {languageHint: file.lang ?? null,additionLines: file.additionLines,deletionLines: file.deletionLines,- rows: buildRenderableRows(file),+ completePatchSource: completePatchSource(file, rawPatch),+ noEOFCRAdditions: file.hunks.some((hunk) => hunk.noEOFCRAdditions),+ noEOFCRDeletions: file.hunks.some((hunk) => hunk.noEOFCRDeletions),+ rows: buildRenderableRows(file, id),};}@@ -471,12 +560,11 @@ export function buildReviewParsedDiff(diff: string | null | undefined,cacheScope: string,): ReviewParsedDiff {- const normalized = diff?.trim();- if (!normalized) {+ if (!diff?.trim()) {return { kind: "empty" };}- const { text, truncated } = splitTruncationMarker(normalized);+ const { text, truncated } = splitTruncationMarker(diff);if (text.length === 0) {return { kind: "empty" };}@@ -486,13 +574,28 @@ export function buildReviewParsedDiff(: null;try {- const parsedPatches = runDiffParserSilently(() =>- parsePatchFiles(text, buildPatchCacheKey(text, cacheScope)),- );+ const cacheKey = buildPatchCacheKey(text, cacheScope);+ const patchId = getReviewPatchId(cacheKey);+ const parsedPatches = runDiffParserSilently(() => parsePatchFiles(text, cacheKey));+ const rawFiles = new Map<string, string | null>();+ if (!truncated) {+ for (const rawFile of text.split(/(?=^diff --git )/m)) {+ const header = rawFile.slice(0, rawFile.indexOf("\n"));+ rawFiles.set(header, rawFiles.has(header) ? null : rawFile);+ }+ }const files = pipe(parsedPatches,Arr.flatMap((patch) => patch.files),- Arr.map(mapRenderableFile),+ Arr.map((file, index) =>+ mapRenderableFile(+ file,+ `${patchId}:f${index.toString(36)}`,+ rawFiles.get(+ `diff --git ${quoteGitPatchPath(`a/${file.name}`)} ${quoteGitPatchPath(`b/${file.name}`)}`,+ ),+ ),+ ),);if (files.length === 0) {diff --git a/apps/mobile/src/features/review/useNativeReviewDiffBridge.ts b/apps/mobile/src/features/review/useNativeReviewDiffBridge.tsindex 1728da66268..d51000bb1f7 100644--- a/apps/mobile/src/features/review/useNativeReviewDiffBridge.ts+++ b/apps/mobile/src/features/review/useNativeReviewDiffBridge.ts@@ -1,4 +1,4 @@-import { useCallback, useMemo, useState } from "react";+import { useCallback, useMemo, useRef, useState } from "react";import type { NativeSyntheticEvent } from "react-native";import { createNativeReviewDiffTheme, type NativeReviewDiffData } from "./nativeReviewDiffAdapter";@@ -33,6 +33,8 @@ export function useNativeReviewDiffBridge(input: {const { nativeReviewDiffStyle } = useAppearanceCodeSurface();const { themeAppearance: scheme, themeId } = useAppearancePreferences();const appTheme = useUniwindTheme();+ const [surfaceGeneration, setSurfaceGeneration] = useState(0);+ const hasMountedContentRef = useRef(false);const [collapsedCommentIds, setCollapsedCommentIds] = useState<ReadonlySet<string>>(() => new Set(),);@@ -53,28 +55,36 @@ export function useNativeReviewDiffBridge(input: {const styleJson = useMemo(() => JSON.stringify(nativeReviewDiffStyle), [nativeReviewDiffStyle]);const tokensResetKey = useMemo(() =>- buildNativeReviewTokensResetKey({+ `${buildNativeReviewTokensResetKey({threadKey,sectionId,scheme,diff,fileCount: data.files.length,rowCount: data.rows.length,- }),- [data.files.length, data.rows.length, diff, scheme, sectionId, threadKey],+ })}:${surfaceGeneration}`,+ [data.files.length, data.rows.length, diff, scheme, sectionId, surfaceGeneration, threadKey],);- const { tokensPatchJson, updateVisibleRange } = useNativeReviewDiffHighlighting({- files: data.files,- rows: data.rows,- scheme,- resetKey: tokensResetKey,- enabled: canHighlight,- });+ const { acknowledgeTokenPatch, rejectTokenPatch, tokensPatchJson, updateVisibleRange } =+ useNativeReviewDiffHighlighting({+ files: data.files,+ rows: data.rows,+ scheme,+ resetKey: tokensResetKey,+ enabled: canHighlight,+ });const onDebug = useCallback((event: NativeSyntheticEvent<Record<string, unknown>>) => {const payload = event.nativeEvent;const message = payload.message;+ if (message === "surface-content-mounted") {+ // The initial content already has a fresh hook; replacements lose accepted tokens.+ if (hasMountedContentRef.current) setSurfaceGeneration((generation) => generation + 1);+ hasMountedContentRef.current = true;+ }+ if (message === "tokens-patch-delivered") acknowledgeTokenPatch(payload);+ if (message === "tokens-patch-failed") rejectTokenPatch(payload);if ((message === "draw-metrics" || message === "visible-range") &&typeof payload.firstRowIndex === "number" &&@@ -86,7 +96,7 @@ export function useNativeReviewDiffBridge(input: {});}},- [updateVisibleRange],+ [acknowledgeTokenPatch, rejectTokenPatch, updateVisibleRange],);const onToggleComment = useCallback(diff --git a/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts b/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.tsindex 6a9b5ee121c..1658f8e7695 100644--- a/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts+++ b/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts@@ -1,9 +1,16 @@-import { useEffect, useRef, useState } from "react";-import type { HighlightScheme } from "../../lib/highlights";-import { highlightNativeReviewDiffVisibleRows } from "../diffs/nativeReviewDiffHighlighter";++import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";+import { AsyncResult } from "effect/reactivity";+import { useCallback, useEffect, useRef, useState } from "react";++import {+ highlightNativeReviewDiffVisibleRows,+ type NativeReviewDiffHighlightChunk,+} from "../diffs/nativeReviewDiffHighlighter";import type { NativeReviewDiffRow } from "../diffs/nativeReviewDiffSurface";import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes";+import { diffHighlightTraceId, traceDiffHighlight } from "../diffs/nativeReviewDiffTrace";import {createReviewDiffHighlightScheduler,@@ -23,50 +30,186 @@ export function useNativeReviewDiffHighlighting(input: {}) {const { enabled, files, resetKey, rows, scheme } = input;const highlightedRowIdsRef = useRef<Set<string>>(new Set());- const [visibleRange, setVisibleRange] = useState<NativeReviewVisibleRange>({- firstRowIndex: 0,- lastRowIndex: 80,- });+ const viewportScope = `${enabled}:${resetKey}:${rows.length}`;+ const [viewport, setViewport] = useState<{+ scope: string;+ range: NativeReviewVisibleRange | null;+ }>(() => ({ scope: viewportScope, range: null }));const visibleChunkIndexRef = useRef(0);+ // Keep undelivered chunks, rather than repeatedly serializing every highlighted row.+ const pendingPatchesRef = useRef<+ Array<{ resetKey: string; chunkIndex: number; json: string; rowIds: string[] }>+ >([]);const [tokensPatchJson, setTokensPatchJson] = useState(() => createEmptyTokenPatch(resetKey));- const [scheduler] = useState(() => createReviewDiffHighlightScheduler(setVisibleRange));+ const [scheduler] = useState(() =>+ createReviewDiffHighlightScheduler((range) =>+ setViewport((current) => ({ ...current, range })),+ ),+ );useEffect(() => {- scheduler.reset();+ traceDiffHighlight("viewport-reset", {+ reset: diffHighlightTraceId(resetKey),+ enabled,+ rows: rows.length,+ });+ const previousRange = scheduler.reset();highlightedRowIdsRef.current = new Set();- visibleChunkIndexRef.current = 0;- setVisibleRange({ firstRowIndex: 0, lastRowIndex: 80 });+ pendingPatchesRef.current = [];+ setViewport({ scope: viewportScope, range: null });setTokensPatchJson(createEmptyTokenPatch(resetKey));+ // A token reset need not produce another native range event. Reuse only an+ // observed viewport, with the same coalescing that lets a new jump replace it.+ if (previousRange) scheduler.update(previousRange);return () => scheduler.cancel();- }, [enabled, resetKey, rows.length, scheduler]);+ }, [enabled, resetKey, rows.length, scheduler, viewportScope]);useEffect(() => {- if (!enabled || rows.length === 0) {+ if (!enabled || rows.length === 0 || !viewport.range || viewport.scope !== viewportScope) {return;}- const result = highlightNativeReviewDiffVisibleRows({- files,- rows,- scheme,- firstRowIndex: visibleRange.firstRowIndex,- lastRowIndex: visibleRange.lastRowIndex,- alreadyHighlightedRowIds: highlightedRowIdsRef.current,+ const abortController = new AbortController();+ const requestRange = viewport.range;+ const generation = diffHighlightTraceId(abortController);+ const reset = diffHighlightTraceId(resetKey);+ traceDiffHighlight("viewport-start", {+ generation,+ reset,+ first: requestRange.firstRowIndex,+ last: requestRange.lastRowIndex,+ pending: pendingPatchesRef.current.length,});- if (result.rowCount === 0) return;- for (const rowId of Object.keys(result.tokensByRowId)) {- highlightedRowIdsRef.current.add(rowId);- }+ const enqueueChunk = (result: NativeReviewDiffHighlightChunk) => {+ if (abortController.signal.aborted || result.rowCount === 0) return;+ const retryableRowIds = new Set(result.retryableRowIds);+ const rowIds = Object.keys(result.tokensByRowId);+ for (const rowId of rowIds) {+ if (!retryableRowIds.has(rowId)) highlightedRowIdsRef.current.add(rowId);+ }+ const chunkIndex = visibleChunkIndexRef.current++;+ const json = JSON.stringify({+ resetKey,+ chunkIndex,+ fileId: "visible",+ filePath: "visible rows",+ language: "diff",+ lineCount: result.rowCount,+ durationMs: result.durationMs,+ tokensByRowId: result.tokensByRowId,+ });+ pendingPatchesRef.current.push({ resetKey, chunkIndex, json, rowIds });+ traceDiffHighlight("patch-queued", {+ generation,+ reset,+ chunk: chunkIndex,+ rows: rowIds.length,+ pending: pendingPatchesRef.current.length,+ });+ if (pendingPatchesRef.current.length === 1) setTokensPatchJson(json);+ };++ void (async () => {+ // Deliver viewport tokens before offscreen source fetches can delay them.+ let retryableViewportRowIds: ReadonlyArray<string> = [];+ for (const overscanRows of [0, undefined]) {+ const deliveredRowIds = new Set<string>();+ const settled = await settlePromise(() =>+ highlightNativeReviewDiffVisibleRows({+ files,+ rows,+ scheme,+ firstRowIndex: requestRange.firstRowIndex,+ lastRowIndex: requestRange.lastRowIndex,+ overscanRows,+ alreadyHighlightedRowIds:+ retryableViewportRowIds.length > 0+ ? new Set([...highlightedRowIdsRef.current, ...retryableViewportRowIds])+ : highlightedRowIdsRef.current,+ signal: abortController.signal,+ onChunk: (chunk) => {+ for (const rowId of Object.keys(chunk.tokensByRowId)) deliveredRowIds.add(rowId);+ enqueueChunk(chunk);+ },+ }),+ );+ if (abortController.signal.aborted) return;+ if (AsyncResult.isFailure(settled)) {+ console.warn("[review-sheet] native visible highlight failed", {+ error: squashAtomCommandFailure(settled),+ resetKey,+ scheme,+ firstRowIndex: requestRange.firstRowIndex,+ lastRowIndex: requestRange.lastRowIndex,+ });+ return;+ }+ const result = settled.value;+ traceDiffHighlight("viewport-result", {+ generation,+ reset,+ overscan: overscanRows ?? 160,+ rows: result.rowCount,+ retryable: result.retryableRowIds.length,+ });+ if (result.rowCount === 0) continue;+ retryableViewportRowIds = result.retryableRowIds;++ const remaining = Object.fromEntries(+ Object.entries(result.tokensByRowId).filter(([rowId]) => !deliveredRowIds.has(rowId)),+ );+ enqueueChunk({+ ...result,+ tokensByRowId: remaining,+ rowCount: Object.keys(remaining).length,+ });+ }+ })();++ return () => {+ traceDiffHighlight("viewport-abort", { generation, reset });+ abortController.abort();+ };+ }, [enabled, files, resetKey, rows, scheme, viewport, viewportScope]);++ const acknowledgeTokenPatch = useCallback((payload: Readonly<Record<string, unknown>>) => {+ const pending = pendingPatchesRef.current;+ const head = pending[0];+ traceDiffHighlight("patch-ack", {+ reset: diffHighlightTraceId(payload.resetKey),+ chunk: typeof payload.chunkIndex === "number" ? payload.chunkIndex : -1,+ matches:+ !!head && payload.resetKey === head.resetKey && payload.chunkIndex === head.chunkIndex,+ pending: pending.length,+ });+ if (!head || payload.resetKey !== head.resetKey || payload.chunkIndex !== head.chunkIndex)+ return;+ pending.shift();+ setTokensPatchJson(pending[0]?.json ?? createEmptyTokenPatch(head.resetKey));+ }, []);- const chunkIndex = visibleChunkIndexRef.current;- visibleChunkIndexRef.current += 1;- setTokensPatchJson(- JSON.stringify({ resetKey, chunkIndex, tokensByRowId: result.tokensByRowId }),- );- }, [enabled, files, resetKey, rows, scheme, visibleRange]);+ const rejectTokenPatch = useCallback(+ (payload: Readonly<Record<string, unknown>>) => {+ const head = pendingPatchesRef.current[0];+ traceDiffHighlight("patch-rejected", {+ reset: diffHighlightTraceId(payload.resetKey),+ chunk: typeof payload.chunkIndex === "number" ? payload.chunkIndex : -1,+ matches:+ !!head && payload.resetKey === head.resetKey && payload.chunkIndex === head.chunkIndex,+ });+ if (!head || payload.resetKey !== head.resetKey || payload.chunkIndex !== head.chunkIndex)+ return;+ for (const rowId of head.rowIds) highlightedRowIdsRef.current.delete(rowId);+ // Retry these rows only on a later viewport request, not in a failure loop.+ acknowledgeTokenPatch(payload);+ },+ [acknowledgeTokenPatch],+ );return {+ rejectTokenPatch,+ acknowledgeTokenPatch,tokensPatchJson,updateVisibleRange: scheduler.update,};diff --git a/apps/mobile/src/lib/highlights.test.ts b/apps/mobile/src/lib/highlights.test.tsindex 6d082b53f02..83469ef745e 100644--- a/apps/mobile/src/lib/highlights.test.ts+++ b/apps/mobile/src/lib/highlights.test.ts@@ -2,7 +2,7 @@ import { codeToTokens } from "@pierre/highlights";import { pierreDark, pierreLight } from "@pierre/highlights/themes";import { describe, expect, it, vi } from "vite-plus/test";-import { highlightCode } from "./highlights";+import { highlightCode, tokenizeCode } from "./highlights";vi.mock("expo", async () => {const { createWasmHighlightsModule } = await import("./highlights.testing");@@ -44,3 +44,16 @@ describe("highlightCode", () => {expect(second).toEqual([{ content: longLine, color: null, fontStyle: null }]);});});++it("normalizes only requested lines from full-source records, including CRLF and a long comment opener", () => {+ const code = `const first = 1;\r\n${" ".repeat(1_001)}/*\r\ninside\r\n*/\r\nconst last = 2;`;+ const source = tokenizeCode(code, "typescript");+ expect(source.byteLength).toBeGreaterThan(0);+ for (let line = 0; line < 5; line++) {+ expect(source.highlightLine(line, "dark")).toEqual(+ highlightCode(code, "typescript", "dark")[line],+ );+ }+ expect(source.highlightLine(2, "dark")?.[0]?.color).toBe("#737373");+ expect(source.highlightLine(100, "dark")).toBeUndefined();+});diff --git a/apps/mobile/src/lib/highlights.ts b/apps/mobile/src/lib/highlights.tsindex f936db10836..184f203ca87 100644--- a/apps/mobile/src/lib/highlights.ts+++ b/apps/mobile/src/lib/highlights.ts@@ -24,50 +24,71 @@ const nativeHighlights = requireOptionalNativeModule<{tokenize(source: string, language: number): ArrayBuffer | null;}>("T3Highlights");-function plainLines(code: string): HighlightedLines {- return code- .split(/\r?\n/u)- .map((line) => (line ? [{ content: line, color: null, fontStyle: null }] : []));+export interface TokenizedCode {+ /** Retained UTF-16 source, compact native records, and line indexes. */+ readonly byteLength: number;+ readonly lineCount: number;+ readonly highlightLine: (+ index: number,+ scheme: HighlightScheme,+ ) => ReadonlyArray<HighlightedToken> | undefined;}-/**- * Tokenizes `code` synchronously, one token array per line. Lines split at LF- * and CRLF, and a trailing line break yields a final empty line.- */-export function highlightCode(- code: string,- language: string,- scheme: HighlightScheme,-): HighlightedLines {+/** Keep native records compact; expand only lines a client will display. */+export function tokenizeCode(code: string, language: string): TokenizedCode {const id = highlightLanguageId(language);const buffer = id === 0 ? null : (nativeHighlights?.tokenize(code, id) ?? null);- if (!buffer) return plainLines(code);-- // `(endUtf16, tokenId)` pairs. A LINE_END token ID ends a line, and its end- // is where the next line starts. Mirrors @pierre/highlights' lineRecordsToTokens.- const records = new Uint32Array(buffer);- const styles = HIGHLIGHTS_THEME_STYLES[scheme];- const lines: HighlightedToken[][] = [];- let start = 0;- for (let record = 0; ; record += 2) {- const first = record;- while (record < records.length && records[record + 1] !== LINE_END) record += 2;- const end = record === first ? start : records[record - 2]!;- if (end - start > MAX_HIGHLIGHTED_LINE_LENGTH) {- lines.push([{ content: code.slice(start, end), color: null, fontStyle: null }]);- } else {+ const records = buffer ? new Uint32Array(buffer) : null;+ const offsets = [0];+ if (records) {+ for (let record = 0; record < records.length; record += 2) {+ if (records[record + 1] === LINE_END) offsets.push(record + 2);+ }+ } else {+ for (let at = code.indexOf("\n"); at !== -1; at = code.indexOf("\n", at + 1))+ offsets.push(at + 1);+ }+ const lineStarts = Uint32Array.from(offsets);+ return {+ byteLength: code.length * 2 + (records?.byteLength ?? 0) + lineStarts.byteLength,+ lineCount: lineStarts.length,+ highlightLine(index, scheme) {+ if (index < 0 || index >= lineStarts.length) return undefined;+ const first = lineStarts[index]!;+ const next = lineStarts[index + 1];+ if (!records) {+ const end = next === undefined ? code.length : next - (code[next - 2] === "\r" ? 2 : 1);+ const content = code.slice(first, end);+ return content ? [{ content, color: null, fontStyle: null }] : [];+ }+ let start = first === 0 ? 0 : records[first - 2]!;+ const last = next === undefined ? records.length : next - 2;+ const end = last === first ? start : records[last - 2]!;+ if (end - start > MAX_HIGHLIGHTED_LINE_LENGTH) {+ return [{ content: code.slice(start, end), color: null, fontStyle: null }];+ }+ const styles = HIGHLIGHTS_THEME_STYLES[scheme];const line: HighlightedToken[] = [];- for (let at = first; at < record; at += 2) {+ for (let at = first; at < last; at += 2) {const tokenEnd = records[at]!;if (tokenEnd <= start) continue;const [color, fontStyle] = styles[records[at + 1]!] ?? styles[0]!;line.push({ content: code.slice(start, tokenEnd), color, fontStyle });start = tokenEnd;}- lines.push(line);- }- if (record >= records.length) break;- start = records[record]!;- }- return lines;+ return line;+ },+ };+}++/** LF and CRLF split lines; a trailing line break yields a final empty line. */+export function highlightCode(+ code: string,+ language: string,+ scheme: HighlightScheme,+): HighlightedLines {+ const source = tokenizeCode(code, language);+ return Array.from({ length: source.lineCount }, (_, index) =>+ source.highlightLine(index, scheme)!,+ );}diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.tsindex 9cf6092d0ba..4c371d2dbc4 100644--- a/apps/mobile/vite.config.ts+++ b/apps/mobile/vite.config.ts@@ -2,6 +2,8 @@ import { defineConfig } from "vite-plus";import "vite-plus/test/config";const reactTests = [+ "src/features/diffs/nativeReviewDiffSurface.test.tsx",+ "src/features/pull-requests/usePullRequestDiff.test.tsx","src/components/ui/Dialog.android.test.tsx","src/features/settings/SettingsServerControlsRouteScreen.test.tsx","src/features/settings/components/BranchNamingSettings.test.tsx",diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.tsindex 7ac94bfd963..92e233f6523 100644--- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts+++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts@@ -164,6 +164,172 @@ const assertRequestId = (body: unknown) =>/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,);+describe("GitCafePullRequestProvider source contents", () => {+ const comparisonBase = "a".repeat(40);+ const snapshot = { version: pull.version, headOid, comparisonBaseOid: comparisonBase };+ const input = {+ ...target,+ changeType: "rename-changed" as const,+ oldPath: "old name.ts",+ newPath: "src/new #name.ts",+ };+ const blob = (request: SentRequest) => ({+ commit: request.query.get("oid"),+ oid: "b".repeat(40),+ path: request.query.get("path"),+ size: 16,+ binary: false,+ content: "const value = 1;",+ });+ const routes = {+ "GET /repos/owner/repo/pulls/7": pull,+ "GET /repos/owner/repo/pulls/7/changes": snapshot,+ "GET /repos/owner/repo/blob": blob,+ };++ it.effect(+ "pins rename source to the comparison base and fork head, without reading branches",+ () => {+ const server = fakeGitCafe({+ ...routes,+ "GET /repos/owner/repo/pulls/7": {+ ...pull,+ sourceRepo: { owner: "fork", name: "project" },+ },+ "GET /repos/fork/project/blob": blob,+ });+ return Effect.gen(function* () {+ const provider = yield* GitCafePullRequestProvider.make;+ const result = yield* provider.getDiffFileContents!(input);+ assert.deepStrictEqual(result, {+ oldContents: "const value = 1;",+ newContents: "const value = 1;",+ });+ const changes = server.sent.find((request) => request.path.endsWith("/changes"))!;+ assert.strictEqual(changes.query.get("expectedVersion"), "4");+ assert.strictEqual(changes.query.get("limit"), "1");+ assert.deepStrictEqual(+ server.sent+ .filter((request) => request.path.endsWith("/blob"))+ .map((request) => ({+ path: request.path,+ oid: request.query.get("oid"),+ file: request.query.get("path"),+ ref: request.query.get("ref"),+ })),+ [+ { path: "/repos/owner/repo/blob", oid: comparisonBase, file: input.oldPath, ref: null },+ { path: "/repos/fork/project/blob", oid: headOid, file: input.newPath, ref: null },+ ],+ );+ assert.deepStrictEqual(server.writes(), []);+ }).pipe(Effect.provide(server.layer));+ },+ );++ it.effect.each(["new", "deleted"] as const)(+ "skips the absent side of a %s file",+ (changeType) => {+ const server = fakeGitCafe(routes);+ return Effect.gen(function* () {+ const provider = yield* GitCafePullRequestProvider.make;+ const result = yield* provider.getDiffFileContents!({ ...input, changeType });+ assert.strictEqual(result[changeType === "new" ? "oldContents" : "newContents"], "");+ assert.lengthOf(+ server.sent.filter((request) => request.path.endsWith("/blob")),+ 1,+ );+ }).pipe(Effect.provide(server.layer));+ },+ );++ it.effect.each([+ { ...snapshot, version: 5 },+ { ...snapshot, headOid: baseOid },+ { ...snapshot, comparisonBaseOid: "main" },+ ])("refuses a changed or nonimmutable comparison snapshot", (response) => {+ const server = fakeGitCafe({ ...routes, "GET /repos/owner/repo/pulls/7/changes": response });+ return Effect.gen(function* () {+ const provider = yield* GitCafePullRequestProvider.make;+ const result = yield* provider.getDiffFileContents!(input).pipe(Effect.result);+ assert.strictEqual(result._tag, "Failure");+ assert.isFalse(server.sent.some((request) => request.path.endsWith("/blob")));+ }).pipe(Effect.provide(server.layer));+ });++ it.effect.each([+ { binary: true, content: null },+ { content: "binary\0data" },+ { size: 1_048_577 },+ { size: 1, content: "x".repeat(1_048_577) },+ { size: 1, content: "é".repeat(524_289) },+ { commit: baseOid },+ { path: "another.ts" },+ { content: null },+ ])("refuses unavailable, oversized, binary, or mismatched blobs", (fields) => {+ const server = fakeGitCafe({+ ...routes,+ "GET /repos/owner/repo/blob": (request: SentRequest) => ({ ...blob(request), ...fields }),+ });+ return Effect.gen(function* () {+ const provider = yield* GitCafePullRequestProvider.make;+ const result = yield* provider.getDiffFileContents!(input).pipe(Effect.result);+ assert.strictEqual(result._tag, "Failure");+ assert.deepStrictEqual(server.writes(), []);+ }).pipe(Effect.provide(server.layer));+ });++ it.effect.each([+ [413, "oversized"],+ [501, "unavailable"],+ ] as const)("marks HTTP %s blob refusals permanently unavailable", ([status, reason]) => {+ const server = fakeGitCafe({+ ...routes,+ "GET /repos/owner/repo/blob": new Response("{}", { status }),+ });+ return Effect.gen(function* () {+ const provider = yield* GitCafePullRequestProvider.make;+ const error = yield* provider.getDiffFileContents!({ ...input, changeType: "new" }).pipe(+ Effect.flip,+ );+ assert.deepInclude(error.cause as object, {+ _tag: "GitCafeDiffSourceUnavailableError",+ reason,+ });+ }).pipe(Effect.provide(server.layer));+ });++ it.effect("preserves authentication failures from blob access", () => {+ const server = fakeGitCafe({+ ...routes,+ "GET /repos/owner/repo/blob": new Response("{}", { status: 401 }),+ });+ return Effect.gen(function* () {+ const provider = yield* GitCafePullRequestProvider.make;+ const error = yield* provider.getDiffFileContents!({ ...input, changeType: "new" }).pipe(+ Effect.flip,+ );+ assert.strictEqual(error.reason, "unauthenticated");+ assert.strictEqual(error.operation, "getDiffFileContents");+ }).pipe(Effect.provide(server.layer));+ });++ it.effect(+ "refuses commit-specific contents consistently with unsupported GitCafe commit diffs",+ () => {+ const server = fakeGitCafe({});+ return Effect.gen(function* () {+ const provider = yield* GitCafePullRequestProvider.make;+ const result = yield* provider.getDiffFileContents!({ ...input, commit: headOid }).pipe(+ Effect.result,+ );+ assert.strictEqual(result._tag, "Failure");+ assert.deepStrictEqual(server.sent, []);+ }).pipe(Effect.provide(server.layer));+ },+ );+});+describe("GitCafePullRequestProvider", () => {it.effect("keeps a staging repository's requests and links on staging", () => {// CAFE_TOKEN follows CAFE_HOST, so staging reads the env token only when it is the target.diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.tsindex 6d62801ad4b..e69961bcba4 100644--- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts+++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts@@ -116,6 +116,30 @@ const Listed = Schema.Struct({});const encodeIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));const BranchCommit = Schema.Struct({ oid: TrimmedNonEmptyString });+const CommitOid = Schema.String.check(Schema.isPattern(/^[0-9a-f]{40}$/u));+const isCommitOid = Schema.is(CommitOid);+const SourceSnapshot = Schema.Struct({+ version: NonNegativeInt,+ headOid: CommitOid,+ comparisonBaseOid: CommitOid,+});+const SourceBlob = Schema.Struct({+ commit: CommitOid,+ path: Schema.String,+ size: NonNegativeInt,+ binary: Schema.Boolean,+ content: Schema.NullOr(Schema.String),+});+const MAX_DIFF_FILE_BYTES = 1024 * 1024;++class GitCafeDiffSourceUnavailableError extends Schema.TaggedError<GitCafeDiffSourceUnavailableError>()(+ "GitCafeDiffSourceUnavailableError",+ {+ path: Schema.String,+ reason: Schema.Literals(["oversized", "binary", "unavailable"]),+ cause: Schema.optional(Schema.Defect()),+ },+) {}const Snapshot = {version: NonNegativeInt,headOid: TrimmedNonEmptyString,@@ -271,6 +295,58 @@ export const make = Effect.gen(function* () {Effect.flatMap((path) => read(operation, input, { path }, Json.GitCafePullDetail)),);+ const readDiffSource = Effect.fn("GitCafePullRequestProvider.readDiffSource")(function* (+ input: ProviderRepositoryRef,+ revision: string,+ filePath: string,+ ) {+ const operation = "getDiffFileContents";+ const base = yield* repositoryPath(operation, input);+ const query = new URLSearchParams({ oid: revision, path: filePath });+ const blob = yield* read(operation, input, { path: `${base}/blob?${query}` }, SourceBlob).pipe(+ Effect.catchIf(+ (error) =>+ isApiError(error.cause) && (error.cause.status === 413 || error.cause.status === 501),+ (error) =>+ Effect.fail(+ failure(+ operation,+ "GitCafe cannot provide this source file as bounded text.",+ new GitCafeDiffSourceUnavailableError({+ path: filePath,+ reason:+ isApiError(error.cause) && error.cause.status === 413+ ? "oversized"+ : "unavailable",+ cause: error,+ }),+ ),+ ),+ ),+ );+ if (blob.commit !== revision || blob.path !== filePath)+ return yield* failure(+ operation,+ "GitCafe answered with a different source revision or path.",+ );+ const reason =+ blob.size > MAX_DIFF_FILE_BYTES ||+ (blob.content !== null && Buffer.byteLength(blob.content, "utf8") > MAX_DIFF_FILE_BYTES)+ ? "oversized"+ : blob.binary || blob.content?.includes("\0")+ ? "binary"+ : blob.content === null+ ? "unavailable"+ : null;+ if (reason !== null)+ return yield* failure(+ operation,+ "GitCafe cannot provide this source file as bounded text.",+ new GitCafeDiffSourceUnavailableError({ path: filePath, reason }),+ );+ return blob.content!;+ });+const readPages = Effect.fn("GitCafePullRequestProvider.readPages")(function* <S extends Schema.Codec<Paged<unknown>, unknown, never, never>,>(operation: string, input: Pick<ProviderRepositoryRef, "host">, path: string, schema: S) {@@ -926,6 +1002,53 @@ export const make = Effect.gen(function* () {nextCursor: page.next === null ? null : encodeDiffCursor({ ...revision, after: page.next }),};}),+ getDiffFileContents: Effect.fn("GitCafePullRequestProvider.getDiffFileContents")(+ function* (input) {+ const operation = "getDiffFileContents";+ if (input.commit !== undefined)+ return yield* failure(operation, "GitCafe commit diff contents are not supported yet.");+ const pull = yield* readPull(operation, input);+ if (!isCommitOid(pull.headOid))+ return yield* failure(+ operation,+ "GitCafe has not reported an immutable pull request head.",+ );+ const path = yield* pullPath(operation, input);+ const query = new URLSearchParams({ expectedVersion: String(pull.version), limit: "1" });+ // observedBaseOid is the target tip, not necessarily the diff's merge base.+ const snapshot = yield* read(+ operation,+ input,+ { path: `${path}/changes?${query}` },+ SourceSnapshot,+ );+ if (snapshot.version !== pull.version || snapshot.headOid !== pull.headOid)+ return yield* failure(+ operation,+ "GitCafe changed the pull request revision. Refresh the diff.",+ );+ const sourceRepository =+ pull.sourceRepo === null+ ? input.repository+ : `${pull.sourceRepo.owner}/${pull.sourceRepo.name}`;+ const [oldContents, newContents] = yield* Effect.all(+ [+ input.changeType === "new"+ ? Effect.succeed("")+ : readDiffSource(input, snapshot.comparisonBaseOid, input.oldPath),+ input.changeType === "deleted"+ ? Effect.succeed("")+ : readDiffSource(+ { ...input, repository: sourceRepository },+ snapshot.headOid,+ input.newPath,+ ),+ ],+ { concurrency: 2 },+ );+ return { oldContents, newContents };+ },+ ),runAction: Effect.fn("GitCafePullRequestProvider.runAction")(function* (input) {if (input.stackNumber !== undefined)return yield* runStackAction({ ...input, stackNumber: input.stackNumber });diff --git a/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.test.ts b/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.test.tsindex b3a070b8417..83279771cb4 100644--- a/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.test.ts+++ b/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.test.ts@@ -336,6 +336,115 @@ describe("toStack", () => {});describe("toDiff", () => {+ it("marks the unterminated 93-byte tunnel-release migration as missing its final newline", () => {+ const content =+ 'ALTER TABLE "relay_managed_endpoint_allocations" ADD COLUMN "tunnel_released_at" varchar(64);';+ assert.strictEqual(Buffer.byteLength(content), 93);+ const { patch } = GitCafePullRequestJson.toDiff(+ decodeDiff({+ items: [+ {+ path: "infra/relay/migrations/postgres/20261005232034_managed_endpoint_tunnel_released_at/migration.sql",+ status: "added",+ hunks: [+ {+ oldStart: 1,+ oldLines: 0,+ newStart: 1,+ newLines: 1,+ lines: [{ origin: "+", content }],+ },+ ],+ },+ ],+ }),+ );+ assert.isTrue(patch.endsWith(`+${content}\n\\ No newline at end of file\n`));+ });++ it.each(["+", "-", " "])("marks unterminated ordinary %j lines", (origin) => {+ const { patch } = GitCafePullRequestJson.toDiff(+ decodeDiff({+ items: [+ {+ path: "file.ts",+ status: "modified",+ hunks: [+ {+ oldStart: 1,+ oldLines: origin === "+" ? 0 : 1,+ newStart: 1,+ newLines: origin === "-" ? 0 : 1,+ lines: [{ origin, content: "value" }],+ },+ ],+ },+ ],+ }),+ );+ assert.isTrue(patch.endsWith(`${origin}value\n\\ No newline at end of file\n`));+ });++ it.each([+ ["+", ">"],+ ["-", "<"],+ [" ", "="],+ ])("emits one marker for an explicit %s/%s EOF pair", (origin, marker) => {+ const { patch } = GitCafePullRequestJson.toDiff(+ decodeDiff({+ items: [+ {+ path: "file.ts",+ status: "modified",+ hunks: [+ {+ oldStart: 1,+ oldLines: origin === "+" ? 0 : 1,+ newStart: 1,+ newLines: origin === "-" ? 0 : 1,+ lines: [+ { origin, content: "value" },+ { origin: marker, content: "\n" },+ ],+ },+ ],+ },+ ],+ }),+ );+ assert.strictEqual(patch.split("\\ No newline at end of file").length - 1, 1);+ });++ it.each([false, true])("preserves rename metadata for changed=%s", (changed) => {+ const { patch } = GitCafePullRequestJson.toDiff(+ decodeDiff({+ items: [+ {+ path: "after.ts",+ oldPath: "before.ts",+ status: "renamed",+ hunks: changed+ ? [+ {+ oldStart: 1,+ oldLines: 1,+ newStart: 1,+ newLines: 1,+ lines: [+ { origin: "-", content: "before\n" },+ { origin: "+", content: "after\n" },+ ],+ },+ ]+ : [],+ },+ ],+ }),+ );+ assert.include(patch, changed ? "similarity index 0%\n" : "similarity index 100%\n");+ assert.include(patch, "rename from before.ts\nrename to after.ts\n");+ });+it("converts numeric hunk coordinates into a unified patch", () => {const diff = decodeDiff({items: [diff --git a/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.ts b/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.tsindex c932b243b23..87704efd08b 100644--- a/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.ts+++ b/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.ts@@ -567,6 +567,10 @@ export function toStack(stack: GitCafeStack, target: RepositoryOnHost): Provider};}+function isEOFMarker(origin: string | undefined) {+ return origin === "=" || origin === ">" || origin === "<";+}+export function toDiff(diff: typeof GitCafeDiff.Type): ProviderDiffSlice {const chunks: Array<string> = [];const omittedFileStats: Array<{ path: string; additions: number; deletions: number }> = [];@@ -582,7 +586,16 @@ export function toDiff(diff: typeof GitCafeDiff.Type): ProviderDiffSlice {if (file.status === "deleted") lines.push(`deleted file mode ${mode}`);if (file.status === "renamed" || file.status === "copied") {const action = file.status === "renamed" ? "rename" : "copy";+ const hasChanges =+ (file.hunks?.length ?? 0) > 0 ||+ (file.additions ?? 0) > 0 ||+ (file.deletions ?? 0) > 0 ||+ file.binary ||+ file.tooLarge ||+ file.hunksOmitted;+ // GitCafe has no similarity score; Pierre needs this header to retain rename metadata.lines.push(+ `similarity index ${hasChanges ? 0 : 100}%`,`${action} from ${quoteGitPatchPath(oldPath)}`,`${action} to ${quoteGitPatchPath(file.path)}`,);@@ -607,10 +620,19 @@ export function toDiff(diff: typeof GitCafeDiff.Type): ProviderDiffSlice {if (hunks.length > 0) lines.push(`--- ${before}`, `+++ ${after}`);for (const hunk of hunks) {lines.push(`@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`);- for (const line of hunk.lines) {- // GitCafe marks a missing final newline with libgit2's own origins.- if (["=", ">", "<"].includes(line.origin)) lines.push("\\ No newline at end of file");- else lines.push(`${line.origin}${line.content.replace(/\n$/u, "")}`);+ for (const [index, line] of hunk.lines.entries()) {+ if (isEOFMarker(line.origin)) {+ lines.push("\\ No newline at end of file");+ } else {+ lines.push(`${line.origin}${line.content.replace(/\n$/u, "")}`);+ if (+ ["+", "-", " "].includes(line.origin) &&+ !line.content.endsWith("\n") &&+ !isEOFMarker(hunk.lines[index + 1]?.origin)+ ) {+ lines.push("\\ No newline at end of file");+ }+ }}}}