The best way to control Claude Code, Codex and more from any computer or phone
fix(mobile): preserve syntax and navigation in large diffs (#24276)
Julius Marminge committed
Oct 24, 2026 at 18:40 UTC
074d9e4d48832d9aee15f9ad85de483023f4cd6b
57 files changed
+5626
-574
apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt
+77
-9
@@ -185,7 +185,8 @@ internal class ReviewDiffCanvasDrawing(context: Context) {
185
fun prepareRows(
186
tokens: Map<String, List<DiffToken>>,
187
style: DiffStyle,
188
- width: Int
188
+ width: Int,
189
+ isCancelled: () -> Boolean = { false }
190
): (List<DiffRow>) -> CodeLayoutCache {
191
configureCodePaint(theme.text, 0, style)
192
val paint = TextPaint(textPaint)
@@ -196,7 +197,7 @@ internal class ReviewDiffCanvasDrawing(context: Context) {
197
style.codePaddingPx * 2f
198
).toInt()
199
return { rows ->
199
- cache.apply { layout(rows, tokens, paint, style, colors, availableWidth) }
200
+ cache.apply { layout(rows, tokens, paint, style, colors, availableWidth, isCancelled) }
201
}
202
}
203
@@ -218,6 +219,39 @@ internal class ReviewDiffCanvasDrawing(context: Context) {
219
private var widthTokens: Map<String, List<DiffToken>>? = null
220
private var widthStyle: DiffStyle? = null
221
private var measuredContentWidth = 0
222
+ private var asciiCharacterWidth = 0f
223
+ private var asciiFixedPitch = false
224
+
225
+ fun tokensChangeWidth(
226
+ previous: Map<String, List<DiffToken>>,
227
+ next: Map<String, List<DiffToken>>,
228
+ style: DiffStyle
229
+ ): Boolean {
230
+ if (widthStyle != style) return true
231
+ fun changed(id: String): Boolean {
232
+ val before = previous[id]
233
+ val after = next[id]
234
+ if (before == after) return false
235
+ return if (widthEntries.containsKey(id) ||
236
+ before.orEmpty().any { it.fontStyle and 3 != 0 } ||
237
+ after.orEmpty().any { it.fontStyle and 3 != 0 }
238
+ ) {
239
+ // Native run boundaries and fallback fonts can change advances, including ASCII italics.
240
+ before?.size != after?.size || before.orEmpty().indices.any { index ->
241
+ val old = before.orEmpty()[index]
242
+ val new = after.orEmpty()[index]
243
+ old.content != new.content || old.fontStyle and 3 != new.fontStyle and 3
244
+ }
245
+ } else {
246
+ before != null && after != null &&
247
+ before.sumOf { it.content.length } != after.sumOf { it.content.length }
248
+ }
249
+ }
250
+ val changed = next.keys.any(::changed) || previous.keys.any { it !in next && changed(it) }
251
+ // Paint-only patches must not make the next comment/viewport update remeasure rows.
252
+ if (!changed) widthTokens = next
253
+ return changed
254
+ }
255
256
fun contentWidth(
257
rows: List<DiffRow>,
@@ -233,20 +267,30 @@ internal class ReviewDiffCanvasDrawing(context: Context) {
267
}
268
// Comment heights and viewport resizing do not change unwrapped text widths.
269
if (widthRows !== rows || widthTokens !== tokens || widthStyle != style) {
236
- if (widthStyle != style) widthEntries = emptyMap()
270
+ if (widthStyle != style) {
271
+ widthEntries = emptyMap()
272
+ configureCodePaint(theme.text, 0, style)
273
+ asciiCharacterWidth = textPaint.measureText("M")
274
+ // Some system font weights resolve to proportional fallbacks even for "monospace".
275
+ val glyphs = CharArray(95) { (' '.code + it).toChar() }.concatToString()
276
+ val advances = FloatArray(glyphs.length)
277
+ textPaint.getTextWidths(glyphs, advances)
278
+ asciiFixedPitch = advances.all { it == asciiCharacterWidth }
279
+ }
280
val next = HashMap<String, WidthEntry>()
281
var widest = 0f
282
for (row in rows) {
283
if (row.kind != "line" && row.kind != "hunk") continue
284
val rowTokens = if (row.kind == "line") tokens[row.id] else null
242
- val cached = widthEntries[row.id]
243
- val entry = if (cached?.row == row && cached.tokens == rowTokens) {
244
- cached
285
+ val asciiWidth = asciiRowWidth(row, rowTokens)
286
+ val measured = if (asciiWidth >= 0f) {
287
+ asciiWidth
288
} else {
246
- WidthEntry(row, rowTokens, measureRowWidth(row, rowTokens, style))
289
+ val entry = widthEntry(row, rowTokens, style)
290
+ next[row.id] = entry
291
+ entry.width
292
}
248
- next[row.id] = entry
249
- widest = max(widest, entry.width)
293
+ widest = max(widest, measured)
294
}
295
widthEntries = next
296
widthRows = rows
@@ -259,6 +303,30 @@ internal class ReviewDiffCanvasDrawing(context: Context) {
303
return measuredContentWidth
304
}
305
306
+ private fun widthEntry(row: DiffRow, tokens: List<DiffToken>?, style: DiffStyle): WidthEntry {
307
+ val cached = widthEntries[row.id]
308
+ return if (cached?.row == row && cached.tokens == tokens) {
309
+ cached
310
+ } else {
311
+ WidthEntry(row, tokens, measureRowWidth(row, tokens, style))
312
+ }
313
+ }
314
+
315
+ private fun asciiRowWidth(row: DiffRow, tokens: List<DiffToken>?): Float {
316
+ val fixedPitch = asciiFixedPitch && row.kind == "line" && row.isPlainAscii
317
+ if (!fixedPitch || tokens.orEmpty().any { it.fontStyle and 3 != 0 }) {
318
+ return -1f
319
+ }
320
+ val length = if (tokens.isNullOrEmpty()) {
321
+ row.content.length
322
+ } else {
323
+ tokens.sumOf {
324
+ it.content.length
325
+ }
326
+ }
327
+ return length * asciiCharacterWidth
328
+ }
329
+
330
private fun measureRowWidth(row: DiffRow, tokens: List<DiffToken>?, style: DiffStyle): Float {
331
if (row.kind == "hunk") {
332
configureMonospacePaint(theme.hunkText, style.hunkFontSizePx, style.hunkFontWeight)
apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayout.kt
+31
-12
@@ -35,15 +35,31 @@ internal class CodeLines(
35
36
internal class CodeWrapLayout(
37
val enabled: Boolean,
38
- private val linesByRowId: Map<String, CodeLines>
38
+ private val linesByRowId: Map<String, CodeLines>,
39
+ private val asciiColumns: Int = Int.MAX_VALUE,
40
+ private val asciiLineHeight: Int = 0
41
) {
40
- fun lines(rowId: String): CodeLines = linesByRowId[rowId] ?: SINGLE_LINE
41
- fun extraHeight(rowId: String): Int = lines(rowId).extraHeight
42
- fun rowHeight(rowId: String, base: Int): Int = lines(rowId).let {
43
- it.firstHeight(base) +
44
- it.extraHeight
42
+ fun needsTokenLayout(
43
+ previous: Map<String, List<DiffToken>>,
44
+ next: Map<String, List<DiffToken>>
45
+ ): Boolean = linesByRowId.keys.any { previous[it] != next[it] }
46
+
47
+ // Only visible ASCII rows need line starts; offscreen heights use the same arithmetic.
48
+ fun lines(row: DiffRow): CodeLines = linesByRowId[row.id] ?: if (enabled) {
49
+ CodeLines(IntArray(asciiLineCount(row)) { it * asciiColumns }, asciiLineHeight)
50
+ } else {
51
+ SINGLE_LINE
52
}
53
54
+ private fun asciiLineCount(row: DiffRow): Int = max(
55
+ 1,
56
+ (row.content.length - 1) / asciiColumns + 1
57
+ )
58
+
59
+ fun rowHeight(row: DiffRow, base: Int): Int = linesByRowId[row.id]?.let {
60
+ it.firstHeight(base) + it.extraHeight
61
+ } ?: (base + if (enabled) (asciiLineCount(row) - 1) * asciiLineHeight else 0)
62
+
63
companion object {
64
private val SINGLE_LINE = CodeLines(intArrayOf(0), 0)
65
val NONE = CodeWrapLayout(false, emptyMap())
@@ -87,14 +103,15 @@ internal class CodeLayoutCache {
103
it.previousWidth = previousWidth
104
}
105
90
- @Suppress("LongParameterList")
106
+ @Suppress("LongParameterList", "ReturnCount")
107
fun layout(
108
rows: List<DiffRow>,
109
tokens: Map<String, List<DiffToken>>,
110
paint: Paint,
111
style: DiffStyle,
112
theme: DiffTheme,
97
- width: Int
113
+ width: Int,
114
+ isCancelled: () -> Boolean = { false }
115
): CodeWrapLayout {
116
if (!style.wordWrap || width < paint.measureText("M")) {
117
entries = emptyMap()
@@ -106,10 +123,14 @@ internal class CodeLayoutCache {
123
previousTheme = theme
124
previousWidth = width
125
}
126
+ val characterWidth = paint.measureText("M")
127
+ val columns = max(1, (width / characterWidth).toInt())
128
+ val lineHeight = ceil(paint.fontMetrics.run { descent - ascent }).toInt()
129
val next = HashMap<String, Entry>()
130
val layouts = HashMap<String, CodeLines>()
131
for (row in rows) {
112
- if (row.kind != "line") continue
132
+ if (isCancelled()) return CodeWrapLayout.NONE
133
+ if (row.kind != "line" || row.isPlainAscii) continue
134
val rowTokens = tokens[row.id]
135
val cached = entries[row.id]
136
val entry = if (cached?.row == row && cached.tokens == rowTokens) {
@@ -122,12 +143,10 @@ internal class CodeLayoutCache {
143
layouts[row.id] = entry.lines
144
}
145
entries = next
125
- return CodeWrapLayout(true, layouts)
146
+ return CodeWrapLayout(true, layouts, columns, lineHeight)
147
}
148
149
private fun styledCode(row: DiffRow, tokens: List<DiffToken>?, theme: DiffTheme): CharSequence {
129
- // The ASCII path uses the existing token drawing and rounded highlight rectangles.
130
- if (row.content.all { it in ' '..'~' }) return row.content
150
val text = SpannableString(row.content)
151
var offset = 0
152
for (token in tokens.orEmpty()) {
apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt
+10
-2
@@ -1,5 +1,6 @@
1
package expo.modules.t3reviewdiff
2
3
+import expo.modules.kotlin.Promise
4
import expo.modules.kotlin.modules.Module
5
import expo.modules.kotlin.modules.ModuleDefinition
6
@@ -49,6 +50,9 @@ class T3ReviewDiffModule : Module() {
50
Prop("initialRowIndex") { view: T3ReviewDiffView, initialRowIndex: Double ->
51
view.setInitialRowIndex(initialRowIndex)
52
}
53
+ Prop("initialFileId") { view: T3ReviewDiffView, fileId: String ->
54
+ view.setInitialFileId(fileId)
55
+ }
56
57
Events(
58
"onDebug",
@@ -71,8 +75,12 @@ class T3ReviewDiffModule : Module() {
75
AsyncFunction("setTokensJson") { view: T3ReviewDiffView, tokensJson: String ->
76
view.setTokensJson(tokensJson)
77
}
74
- AsyncFunction("setTokensPatchJson") { view: T3ReviewDiffView, tokensPatchJson: String ->
75
- view.setTokensPatchJson(tokensPatchJson)
78
+ AsyncFunction("setTokensPatchJson") {
79
+ view: T3ReviewDiffView,
80
+ tokensPatchJson: String,
81
+ promise: Promise
82
+ ->
83
+ view.setTokensPatchJson(tokensPatchJson) { accepted -> promise.resolve(accepted) }
84
}
85
86
OnViewDestroys { view: T3ReviewDiffView ->
apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt
+175
-84
@@ -39,10 +39,13 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
39
private var collapsedCommentIds: Set<String> = emptySet()
40
private var initialRowIndex = 0
41
private var pendingInitialScroll = false
42
+ private var initialFileId: String? = null
43
+ private var pendingScrollFileId: String? = null
44
private var lastVisibleFileId: String? = null
45
private var tokensResetKey = ""
46
private var contentResetKey = ""
45
- private var rowsDecodeGeneration = 0
47
+
48
+ @Volatile private var rowsDecodeGeneration = 0
49
private var tokensDecodeGeneration = 0
50
private val payloadDecodeExecutor = Executors.newSingleThreadExecutor()
51
private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop
@@ -65,13 +68,16 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
68
)
69
)
70
}
71
+ canvasView.onVerticalAnchorRestored = { verticalScroller.forceFinished(true) }
72
canvasView.onRowTap = { row, gesture, target -> handleRowTap(row, gesture, target) }
73
+ canvasView.onViewportSizeChanged = { applyPendingInitialScroll() }
74
canvasView.onVisibleRowsChanged = { first, last ->
75
onDebug(
76
mapOf(
77
"message" to "visible-range",
78
"firstRowIndex" to first,
79
"lastRowIndex" to last,
80
+ "totalRows" to rows.size,
81
),
82
)
83
emitVisibleFile(first)
@@ -92,10 +98,18 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
98
fun setContentResetKey(value: String) {
99
if (contentResetKey == value) return
100
contentResetKey = value
101
+ rowsDecodeGeneration += 1
102
tokensDecodeGeneration += 1
103
+ canvasView.setViewportEventsPaused(true)
104
+ verticalScroller.forceFinished(true)
105
+ horizontalScroller.forceFinished(true)
106
+ rows = emptyList()
107
+ visibleRows = emptyList()
108
+ canvasView.rows = emptyList()
109
canvasView.tokensByRowId = emptyMap()
110
lastVisibleFileId = null
111
pendingInitialScroll = true
112
+ pendingScrollFileId = initialFileId
113
canvasView.setVerticalOffset(0)
114
canvasView.resetHorizontalOffsets()
115
applyPendingInitialScroll()
@@ -146,18 +160,33 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
160
}
161
162
fun setInitialRowIndex(value: Double) {
149
- initialRowIndex = value.toInt().coerceAtLeast(0)
150
- pendingInitialScroll = true
163
+ initialRowIndex = value.toInt()
164
+ pendingInitialScroll = value.isFinite() && value >= 0
165
+ canvasView.setViewportEventsPaused(true)
166
+ applyPendingInitialScroll()
167
+ }
168
+
169
+ fun setInitialFileId(value: String) {
170
+ val nextFileId = value.takeIf { it.isNotEmpty() }
171
+ if (nextFileId == initialFileId) return
172
+ initialFileId = nextFileId
173
+ pendingScrollFileId = nextFileId
174
+ canvasView.setViewportEventsPaused(true)
175
applyPendingInitialScroll()
176
}
177
178
fun setRowsJson(value: String) {
179
rowsDecodeGeneration += 1
180
+ canvasView.setViewportEventsPaused(true)
181
val generation = rowsDecodeGeneration
157
- val prepareLayout = canvasView.prepareRows()
182
+ val isCancelled = { generation != rowsDecodeGeneration || Thread.currentThread().isInterrupted }
183
+ val prepareLayout = canvasView.prepareRows(isCancelled)
184
payloadDecodeExecutor.execute {
159
- val decodedRows = parseRows(value)
185
+ if (isCancelled()) return@execute
186
+ val decodedRows = parseRows(value, isCancelled)
187
+ if (isCancelled()) return@execute
188
val codeLayouts = prepareLayout(decodedRows)
189
+ if (isCancelled()) return@execute
190
post {
191
if (generation != rowsDecodeGeneration) return@post
192
canvasView.useCodeLayouts(codeLayouts)
@@ -180,7 +209,8 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
209
}
210
}
211
183
- fun setTokensPatchJson(value: String) {
212
+ fun setTokensPatchJson(value: String, completion: (Boolean) -> Unit) {
213
+ val contentKey = contentResetKey
214
payloadDecodeExecutor.execute {
215
try {
216
val payload = JSONObject(value)
@@ -189,12 +219,19 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
219
payload.optJSONObject("tokensByRowId") ?: JSONObject(),
220
)
221
post {
192
- if (resetKey.isNotEmpty() && resetKey != tokensResetKey) return@post
222
+ if (contentKey != contentResetKey ||
223
+ (resetKey.isNotEmpty() && resetKey != tokensResetKey)
224
+ ) {
225
+ completion(false)
226
+ return@post
227
+ }
228
if (decodedTokens.isNotEmpty()) {
229
canvasView.tokensByRowId = canvasView.tokensByRowId + decodedTokens
230
}
231
+ completion(true)
232
}
233
} catch (_: Exception) {
234
+ post { completion(false) }
235
}
236
}
237
}
@@ -354,6 +391,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
391
}
392
393
private fun rebuildVisibleRows() {
394
+ canvasView.setViewportEventsPaused(true)
395
val filtered = ArrayList<DiffRow>(rows.size)
396
var currentFileCollapsed = false
397
rows.forEach { row ->
@@ -411,10 +449,20 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
449
}
450
451
private fun applyPendingInitialScroll() {
414
- if (!pendingInitialScroll || visibleRows.isEmpty()) return
415
- pendingInitialScroll = false
416
- val index = initialRowIndex.coerceIn(0, visibleRows.lastIndex)
417
- post { canvasView.setVerticalOffset(canvasView.rowTop(index)) }
452
+ if (visibleRows.isEmpty() || canvasView.width <= 0 || canvasView.height <= 0) return
453
+ val fileId = pendingScrollFileId
454
+ if (fileId != null) {
455
+ val index = visibleRows.indexOfFirst { it.kind == "file" && it.resolvedFileId == fileId }
456
+ if (index < 0) return
457
+ pendingScrollFileId = null
458
+ pendingInitialScroll = false
459
+ canvasView.setVerticalOffset(canvasView.rowTop(index))
460
+ } else if (pendingInitialScroll) {
461
+ pendingInitialScroll = false
462
+ val index = initialRowIndex.coerceIn(0, visibleRows.lastIndex)
463
+ canvasView.setVerticalOffset(canvasView.rowTop(index))
464
+ }
465
+ canvasView.setViewportEventsPaused(false)
466
}
467
468
private fun scrollToY(y: Int, animated: Boolean) {
@@ -476,6 +524,7 @@ internal data class DiffRow(
524
val commentSectionTitle: String
525
) {
526
val resolvedFileId: String get() = fileId.ifEmpty { id }
527
+ val isPlainAscii: Boolean = content.all { it in ' '..'~' }
528
}
529
530
internal data class DiffWordDiffRange(
@@ -710,6 +759,7 @@ private class DiffCanvasView(context: Context) : View(context) {
759
},
760
)
761
private var rowOffsets = intArrayOf(0)
762
+ private var fileHeaderIndices = intArrayOf()
763
764
private var codeWrap = CodeWrapLayout.NONE
765
private var verticalOffset = 0
@@ -718,20 +768,26 @@ private class DiffCanvasView(context: Context) : View(context) {
768
private var contentWidthPx = 0
769
private val headerPathOffsetsByFileId = mutableMapOf<String, Int>()
770
private var lastVisibleRange: Pair<Int, Int>? = null
771
+ private var viewportEventsPaused = true
772
var rows: List<DiffRow> = emptyList()
773
set(value) {
774
field = value
775
+ fileHeaderIndices = indexFileHeaders(value)
776
headerPathOffsetsByFileId.keys.retainAll(
725
- value.asSequence().filter { it.kind == "file" }.map { it.resolvedFileId }.toSet(),
777
+ fileHeaderIndices.map { value[it].resolvedFileId }.toSet(),
778
)
727
- rebuildOffsets()
779
+ rebuildOffsets(preserveAnchor = false)
780
}
781
var tokensByRowId: Map<String, List<DiffToken>> = emptyMap()
782
set(value) {
783
+ val previous = field
784
field = value
785
if (style.wordWrap) {
733
- rebuildOffsets()
734
- } else {
786
+ // ASCII uses fixed-pitch geometry. Native layouts also carry their painted spans.
787
+ if (codeWrap.needsTokenLayout(previous, value)) {
788
+ rebuildOffsets()
789
+ }
790
+ } else if (drawing.tokensChangeWidth(previous, value, style)) {
791
contentWidthPx = drawing.contentWidth(rows, value, style)
792
setHorizontalOffset(horizontalOffset)
793
}
@@ -772,8 +828,11 @@ private class DiffCanvasView(context: Context) : View(context) {
828
var onRowTap: ((DiffRow, String, RowTapTarget) -> Unit)? = null
829
var onVisibleRowsChanged: ((Int, Int) -> Unit)? = null
830
var onContentHeightChanged: ((Int) -> Unit)? = null
831
+ var onVerticalAnchorRestored: (() -> Unit)? = null
832
+ var onViewportSizeChanged: (() -> Unit)? = null
833
776
- fun prepareRows() = drawing.prepareRows(tokensByRowId, style, width)
834
+ fun prepareRows(isCancelled: () -> Boolean = { false }) =
835
+ drawing.prepareRows(tokensByRowId, style, width, isCancelled)
836
fun useCodeLayouts(layouts: CodeLayoutCache) {
837
drawing.codeLayouts = layouts
838
}
@@ -789,6 +848,7 @@ private class DiffCanvasView(context: Context) : View(context) {
848
super.onSizeChanged(width, height, oldWidth, oldHeight)
849
// Wrapped rows take their height from the width, so a new width is a new layout.
850
if (style.wordWrap && width != oldWidth) layoutRows()
851
+ onViewportSizeChanged?.invoke()
852
setVerticalOffset(verticalOffset)
853
setHorizontalOffset(horizontalOffset)
854
clampHeaderPathOffsets()
@@ -883,20 +943,27 @@ private class DiffCanvasView(context: Context) : View(context) {
943
}
944
}
945
886
- private fun rebuildOffsets() {
887
- layoutRows()
946
+ private fun rebuildOffsets(preserveAnchor: Boolean = true) {
947
+ layoutRows(preserveAnchor)
948
requestLayout()
949
invalidate()
950
}
951
892
- private fun layoutRows() {
952
+ private fun layoutRows(preserveAnchor: Boolean = true) {
953
+ // Rows are unchanged here; their old offsets still identify the viewport's code row.
954
+ val anchorIndex = if (preserveAnchor && rows.isNotEmpty()) rowIndexAt(verticalOffset) else null
955
+ val intraRowOffset = anchorIndex?.let { verticalOffset - rowOffsets[it] } ?: 0
956
contentWidthPx = drawing.contentWidth(rows, tokensByRowId, style)
957
codeWrap = drawing.codeWrapLayout(rows, tokensByRowId, style, width)
958
rowOffsets = IntArray(rows.size + 1)
959
rows.forEachIndexed { index, row ->
960
rowOffsets[index + 1] = rowOffsets[index] + rowHeight(row)
961
}
899
- setVerticalOffset(verticalOffset)
962
+ val targetOffset = anchorIndex?.let {
963
+ rowOffsets[it] + intraRowOffset.coerceIn(0, max(0, rowOffsets[it + 1] - rowOffsets[it] - 1))
964
+ } ?: verticalOffset
965
+ if (targetOffset != verticalOffset) onVerticalAnchorRestored?.invoke()
966
+ setVerticalOffset(targetOffset)
967
setHorizontalOffset(horizontalOffset)
968
clampHeaderPathOffsets()
969
onContentHeightChanged?.invoke(rowOffsets.last())
@@ -910,25 +977,11 @@ private class DiffCanvasView(context: Context) : View(context) {
977
} else {
978
(124 * density).toInt()
979
}
913
- "line" -> codeWrap.rowHeight(row.id, style.rowHeightPx.toInt())
980
+ "line" -> codeWrap.rowHeight(row, style.rowHeightPx.toInt())
981
else -> style.rowHeightPx.toInt()
982
}.coerceAtLeast(1)
983
917
- @Suppress("ReturnCount")
918
- private fun rowIndexAt(y: Int): Int {
919
- if (rows.isEmpty()) return 0
920
- var low = 0
921
- var high = rows.lastIndex
922
- while (low <= high) {
923
- val middle = (low + high) ushr 1
924
- when {
925
- y < rowOffsets[middle] -> high = middle - 1
926
- y >= rowOffsets[middle + 1] -> low = middle + 1
927
- else -> return middle
928
- }
929
- }
930
- return low.coerceIn(0, rows.lastIndex)
931
- }
984
+ private fun rowIndexAt(y: Int): Int = rowIndexAtOffset(y, rowOffsets, rows.size)
985
986
private fun rowHitAt(y: Float): RowHit? {
987
stickyFileHeader(firstVisibleRow())?.let { sticky ->
@@ -949,14 +1002,21 @@ private class DiffCanvasView(context: Context) : View(context) {
1002
1003
private fun firstVisibleRow(): Int = rowIndexAt(verticalOffset)
1004
1005
+ fun setViewportEventsPaused(paused: Boolean) {
1006
+ viewportEventsPaused = paused
1007
+ if (paused) lastVisibleRange = null else emitVisibleRange()
1008
+ }
1009
+
1010
private fun emitVisibleRange() {
953
- if (rows.isEmpty()) return
1011
+ if (viewportEventsPaused || rows.isEmpty()) return
1012
+ if (width <= 0 || height <= 0) return
1013
val first = rowIndexAt(verticalOffset)
1014
val last = rowIndexAt(verticalOffset + max(1, height))
1015
val range = first to last
957
- if (range == lastVisibleRange) return
958
- lastVisibleRange = range
959
- onVisibleRowsChanged?.invoke(first, last)
1016
+ if (range != lastVisibleRange) {
1017
+ lastVisibleRange = range
1018
+ onVisibleRowsChanged?.invoke(first, last)
1019
+ }
1020
}
1021
1022
private fun drawRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
@@ -1235,7 +1295,7 @@ private class DiffCanvasView(context: Context) : View(context) {
1295
}
1296
1297
// Wrapped rows keep the line number and first code line in the first row-height band.
1238
- val lines = codeWrap.lines(row.id)
1298
+ val lines = codeWrap.lines(row)
1299
val firstLineBottom = top + lines.firstHeight(style.rowHeightPx.toInt())
1300
drawScrollableCode(canvas, top, bottom) { codeX ->
1301
drawing.configureCodePaint(theme.text, 0, style)
@@ -1287,11 +1347,13 @@ private class DiffCanvasView(context: Context) : View(context) {
1347
@Suppress("ReturnCount")
1348
private fun stickyFileHeader(firstVisibleIndex: Int): StickyFileHeader? {
1349
if (rows.isEmpty()) return null
1290
- val fileIndex = (firstVisibleIndex.coerceIn(0, rows.lastIndex) downTo 0)
1291
- .firstOrNull { rows[it].kind == "file" }
1292
- ?: return null
1350
+ val rowIndex = firstVisibleIndex.coerceIn(0, rows.lastIndex)
1351
+ val found = fileHeaderIndices.binarySearch(rowIndex)
1352
+ val slot = if (found >= 0) found else -found - 2
1353
+ if (slot < 0) return null
1354
+ val fileIndex = fileHeaderIndices[slot]
1355
val headerHeight = rowHeight(rows[fileIndex])
1294
- val nextFileIndex = ((fileIndex + 1)..rows.lastIndex).firstOrNull { rows[it].kind == "file" }
1356
+ val nextFileIndex = fileHeaderIndices.getOrNull(slot + 1)
1357
val top = nextFileIndex
1358
?.let { min(0, rowOffsets[it] - verticalOffset - headerHeight) }
1359
?: 0
@@ -1334,20 +1396,6 @@ private class DiffCanvasView(context: Context) : View(context) {
1396
canvas.drawLine(0f, bottom - density / 2f, width.toFloat(), bottom - density / 2f, borderPaint)
1397
}
1398
1337
- private fun centeredBaseline(top: Int, bottom: Int, paint: Paint): Float {
1338
- val metrics = paint.fontMetrics
1339
- return (top + bottom) / 2f - (metrics.ascent + metrics.descent) / 2f
1340
- }
1341
-
1342
- private fun ellipsize(value: String, paint: Paint, width: Float): String {
1343
- if (paint.measureText(value) <= width) return value
1344
- val suffix = "..."
1345
- val available = max(0f, width - paint.measureText(suffix))
1346
- var end = value.length
1347
- while (end > 0 && paint.measureText(value, 0, end) > available) end -= 1
1348
- return value.substring(0, end) + suffix
1349
- }
1350
-
1399
private data class StickyFileHeader(
1400
val index: Int,
1401
val top: Int,
@@ -1366,35 +1414,62 @@ private class DiffCanvasView(context: Context) : View(context) {
1414
)
1415
}
1416
1417
+private fun centeredBaseline(top: Int, bottom: Int, paint: Paint): Float {
1418
+ val metrics = paint.fontMetrics
1419
+ return (top + bottom) / 2f - (metrics.ascent + metrics.descent) / 2f
1420
+}
1421
+
1422
+private fun ellipsize(value: String, paint: Paint, width: Float): String {
1423
+ if (paint.measureText(value) <= width) return value
1424
+ val suffix = "..."
1425
+ val available = max(0f, width - paint.measureText(suffix))
1426
+ var end = value.length
1427
+ while (end > 0 && paint.measureText(value, 0, end) > available) end -= 1
1428
+ return value.substring(0, end) + suffix
1429
+}
1430
+
1431
+private fun indexFileHeaders(rows: List<DiffRow>): IntArray {
1432
+ val headers = ArrayList<Int>()
1433
+ rows.forEachIndexed { index, row ->
1434
+ if (row.kind == "file") headers.add(index)
1435
+ }
1436
+ return headers.toIntArray()
1437
+}
1438
+
1439
private fun withAlpha(color: Int, alpha: Int): Int =
1440
Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color))
1441
1372
-private fun parseRows(value: String): List<DiffRow> = try {
1373
- val array = JSONArray(value)
1374
- List(array.length()) { index ->
1375
- val row = array.getJSONObject(index)
1376
- DiffRow(
1377
- kind = row.optString("kind"),
1378
- id = row.optString("id"),
1379
- fileId = row.optString("fileId"),
1380
- filePath = row.optString("filePath"),
1381
- previousPath = row.optNullableString("previousPath"),
1382
- changeType = row.optString("changeType"),
1383
- additions = row.optInt("additions"),
1384
- deletions = row.optInt("deletions"),
1385
- text = row.optString("text"),
1386
- content = row.optString("content"),
1387
- change = row.optString("change", "context"),
1388
- oldLineNumber = row.optNullableInt("oldLineNumber"),
1389
- newLineNumber = row.optNullableInt("newLineNumber"),
1390
- wordDiffRanges = row.optJSONArray("wordDiffRanges")?.let(::parseWordDiffRanges).orEmpty(),
1391
- commentText = row.optString("commentText"),
1392
- commentRangeLabel = row.optString("commentRangeLabel"),
1393
- commentSectionTitle = row.optString("commentSectionTitle"),
1394
- )
1442
+private fun parseRows(value: String): List<DiffRow> = parseRows(value) { false }
1443
+
1444
+private fun parseRows(value: String, isCancelled: () -> Boolean): List<DiffRow> {
1445
+ return try {
1446
+ val array = JSONArray(value)
1447
+ List(array.length()) { index ->
1448
+ if (isCancelled()) return emptyList()
1449
+ val row = array.getJSONObject(index)
1450
+ DiffRow(
1451
+ kind = row.optString("kind"),
1452
+ id = row.optString("id"),
1453
+ fileId = row.optString("fileId"),
1454
+ filePath = row.optString("filePath"),
1455
+ previousPath = row.optNullableString("previousPath"),
1456
+ changeType = row.optString("changeType"),
1457
+ additions = row.optInt("additions"),
1458
+ deletions = row.optInt("deletions"),
1459
+ text = row.optString("text"),
1460
+ content = row.optString("content"),
1461
+ change = row.optString("change", "context"),
1462
+ oldLineNumber = row.optNullableInt("oldLineNumber"),
1463
+ newLineNumber = row.optNullableInt("newLineNumber"),
1464
+ wordDiffRanges = row.optJSONArray("wordDiffRanges")?.let(::parseWordDiffRanges).orEmpty(),
1465
+ commentText = row.optString("commentText"),
1466
+ commentRangeLabel = row.optString("commentRangeLabel"),
1467
+ commentSectionTitle = row.optString("commentSectionTitle"),
1468
+ )
1469
+ }
1470
+ } catch (_: Exception) {
1471
+ emptyList()
1472
}
1396
-} catch (_: Exception) {
1397
- emptyList()
1473
}
1474
1475
private fun parseWordDiffRanges(value: JSONArray): List<DiffWordDiffRange> = buildList {
@@ -1464,3 +1539,19 @@ private fun JSONObject.floatDp(key: String, fallbackPx: Float, density: Float):
1539
1540
private fun JSONObject.floatSp(key: String, fallbackPx: Float, density: Float): Float =
1541
if (has(key)) optDouble(key).toFloat() * density else fallbackPx
1542
+
1543
+@Suppress("ReturnCount")
1544
+private fun rowIndexAtOffset(y: Int, rowOffsets: IntArray, rowCount: Int): Int {
1545
+ if (rowCount == 0) return 0
1546
+ var low = 0
1547
+ var high = rowCount - 1
1548
+ while (low <= high) {
1549
+ val middle = (low + high) ushr 1
1550
+ when {
1551
+ y < rowOffsets[middle] -> high = middle - 1
1552
+ y >= rowOffsets[middle + 1] -> low = middle + 1
1553
+ else -> return middle
1554
+ }
1555
+ }
1556
+ return low.coerceIn(0, rowCount - 1)
1557
+}
apps/mobile/modules/t3-review-diff/android/src/test/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayoutTest.kt
+33
-7
@@ -91,7 +91,7 @@ class ReviewDiffCodeLayoutTest {
91
style,
92
theme,
93
280
94
- ).lines(row.id)
94
+ ).lines(row)
95
val second = cache.layout(
96
listOf(row, comment.copy(commentText = "After")),
97
emptyMap(),
@@ -99,9 +99,9 @@ class ReviewDiffCodeLayoutTest {
99
style,
100
theme,
101
280,
102
- ).lines(row.id)
102
+ ).lines(row)
103
assertSame(first, second)
104
- val narrow = cache.layout(listOf(row), emptyMap(), paint, style, theme, 180).lines(row.id)
104
+ val narrow = cache.layout(listOf(row), emptyMap(), paint, style, theme, 180).lines(row)
105
assertNotSame(first, narrow)
106
assertTrue(narrow.extraHeight > first.extraHeight)
107
val edited = cache.layout(
@@ -111,7 +111,7 @@ class ReviewDiffCodeLayoutTest {
111
style,
112
theme,
113
180
114
- ).lines(row.id)
114
+ ).lines(row)
115
assertTrue(edited.extraHeight < narrow.extraHeight)
116
assertEquals(
117
0,
@@ -122,7 +122,7 @@ class ReviewDiffCodeLayoutTest {
122
style.copy(wordWrap = false),
123
theme,
124
180
125
- ).extraHeight(row.id)
125
+ ).rowHeight(row, 0)
126
)
127
}
128
@@ -132,9 +132,9 @@ class ReviewDiffCodeLayoutTest {
132
val row = row("漢字".repeat(30)).copy(wordDiffRanges = listOf(DiffWordDiffRange(3, 21)))
133
val style = DiffStyle.defaults(1f).copy(wordWrap = true)
134
val theme = DiffTheme.fallback("light")
135
- val initial = cache.layout(listOf(row), emptyMap(), paint, style, theme, 180).lines(row.id)
135
+ val initial = cache.layout(listOf(row), emptyMap(), paint, style, theme, 180).lines(row)
136
val tokens = mapOf(row.id to listOf(DiffToken(row.content, 0xff008800.toInt(), 2)))
137
- val highlighted = cache.layout(listOf(row), tokens, paint, style, theme, 180).lines(row.id)
137
+ val highlighted = cache.layout(listOf(row), tokens, paint, style, theme, 180).lines(row)
138
assertNotSame(initial, highlighted)
139
val text = requireNotNull(highlighted.nativeLayout).text as Spanned
140
val span = text.getSpans(0, text.length, BackgroundColorSpan::class.java).single()
@@ -193,6 +193,32 @@ class ReviewDiffCodeLayoutTest {
193
assertFresh(rows)
194
}
195
196
+ @Test
197
+ fun obsoletePreparationStopsBeforeWalkingTheRemainingRows() {
198
+ val cache = CodeLayoutCache()
199
+ val row = row("漢字".repeat(100))
200
+ val style = DiffStyle.defaults(1f).copy(wordWrap = true)
201
+ val theme = DiffTheme.fallback("light")
202
+ val displayed = cache.layout(listOf(row), emptyMap(), paint, style, theme, 280).lines(row)
203
+ val preparation = cache.copyForPreparation()
204
+ var checked = 0
205
+ val cancelled = preparation.layout(
206
+ List(10000) { row.copy(id = "row:$it") },
207
+ emptyMap(),
208
+ paint,
209
+ style,
210
+ theme,
211
+ 280,
212
+ isCancelled = { ++checked == 2 },
213
+ )
214
+ assertEquals(2, checked)
215
+ assertEquals(false, cancelled.enabled)
216
+ assertSame(
217
+ displayed,
218
+ cache.layout(listOf(row), emptyMap(), paint, style, theme, 280).lines(row)
219
+ )
220
+ }
221
+
222
private fun row(content: String) = DiffRow(
223
kind = "line", id = "line", fileId = "file", filePath = "test.ts", previousPath = null,
224
changeType = "modified", additions = 1, deletions = 0, text = "", content = content,
apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift
+22
-4
@@ -1,5 +1,19 @@
1
import UIKit
2
3
+/// Fixed-pitch line boundaries need no storage proportional to the text length.
4
+struct ReviewDiffCodeLineStarts: RandomAccessCollection {
5
+ let startIndex = 0
6
+ let endIndex: Int
7
+ let columns: Int
8
+
9
+ init(length: Int, columns: Int?) {
10
+ self.columns = Swift.max(1, columns ?? length)
11
+ endIndex = (Swift.max(1, length) - 1) / self.columns + 1
12
+ }
13
+
14
+ subscript(index: Int) -> Int { index * columns }
15
+}
16
+
17
/// ASCII uses fixed-pitch columns. TextKit handles shaping, tabs, and Unicode highlights.
18
/// Pass `unboundedWidth` to lay a row out on one line for horizontal scrolling.
19
final class ReviewDiffCodeLayout: NSObject {
@@ -19,7 +33,7 @@ final class ReviewDiffCodeLayout: NSObject {
33
return cache
34
}()
35
let text: String
22
- let starts: [Int]
36
+ let starts: ReviewDiffCodeLineStarts
37
let lineHeight: CGFloat
38
let firstLineHeight: CGFloat
39
let extraHeight: CGFloat
@@ -36,10 +50,10 @@ final class ReviewDiffCodeLayout: NSObject {
50
self.width = width
51
self.characterWidth = characterWidth
52
lineHeight = ceil(font.lineHeight)
39
- if text.utf8.allSatisfy({ $0 >= 32 && $0 <= 126 }) {
53
+ if Self.isPrintableASCII(text) {
54
let length = max(1, text.utf8.count)
55
let columns = max(1, Int(min(width / characterWidth, CGFloat(length))))
42
- starts = Array(stride(from: 0, to: length, by: columns))
56
+ starts = ReviewDiffCodeLineStarts(length: length, columns: columns)
57
firstLineHeight = font.lineHeight
58
extraHeight = CGFloat(starts.count - 1) * lineHeight
59
usedWidth = CGFloat(min(text.utf8.count, columns)) * characterWidth
@@ -50,7 +64,7 @@ final class ReviewDiffCodeLayout: NSObject {
64
let manager = layout.manager
65
let container = layout.container
66
usesNativeLayout = true
53
- starts = [0]
67
+ starts = ReviewDiffCodeLineStarts(length: 0, columns: nil)
68
firstLineHeight = manager.numberOfGlyphs > 0
69
? manager.lineFragmentRect(forGlyphAt: 0, effectiveRange: nil).height : font.lineHeight
70
let used = manager.usedRect(for: container)
@@ -59,6 +73,10 @@ final class ReviewDiffCodeLayout: NSObject {
73
}
74
}
75
76
+ static func isPrintableASCII(_ text: String) -> Bool {
77
+ text.utf8.allSatisfy { $0 >= 32 && $0 <= 126 }
78
+ }
79
+
80
private func nativeLayout() -> ReviewDiffTextLayout {
81
if let cached = Self.drawnLayouts.object(forKey: self) { return cached }
82
let layout = ReviewDiffTextLayout()
apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift
+8
-2
@@ -61,6 +61,10 @@ public class T3ReviewDiffModule: Module {
61
view.setInitialRowIndex(initialRowIndex)
62
}
63
64
+ Prop("initialFileId") { (view: T3ReviewDiffView, fileId: String) in
65
+ view.setInitialFileId(fileId)
66
+ }
67
+
68
Prop("scrollEnabled") { (view: T3ReviewDiffView, enabled: Bool) in
69
view.setScrollEnabled(enabled)
70
}
@@ -106,8 +110,10 @@ public class T3ReviewDiffModule: Module {
110
view.setTokensJson(tokensJson)
111
}
112
109
- AsyncFunction("setTokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in
110
- view.setTokensPatchJson(tokensPatchJson)
113
+ AsyncFunction("setTokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String, promise: Promise) in
114
+ view.setTokensPatchJson(tokensPatchJson) { accepted in
115
+ promise.resolve(accepted)
116
+ }
117
}
118
}
119
}
apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift
+266
-102
@@ -170,7 +170,7 @@ private struct ReviewDiffNativeStylePayload: Decodable {
170
let emptyStateFontWeight: String?
171
}
172
173
-private struct ReviewDiffNativeStyle {
173
+private struct ReviewDiffNativeStyle: Equatable {
174
let wordWrap: Bool
175
let rowHeight: CGFloat
176
let contentWidth: CGFloat
@@ -333,6 +333,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
333
private var tokensResetKey = ""
334
private var contentResetKey = ""
335
private var initialRowIndex: Int?
336
+ private var initialFileId: String?
337
private var hasAppliedInitialRowIndex = false
338
private var lastVisibleFileId: String?
339
private var pendingScrollFileId: String?
@@ -388,8 +389,9 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
389
390
public override func layoutSubviews() {
391
super.layoutSubviews()
392
+ let anchor = contentView.viewportWidth != bounds.width ? contentView.viewportRowAnchor() : nil
393
scrollView.frame = bounds
392
- updateContentMetrics()
394
+ updateContentMetrics(rowAnchor: anchor)
395
}
396
397
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
@@ -423,6 +425,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
425
}
426
427
func setRowsJson(_ rowsJson: String) {
428
+ contentView.cancelRowPreparation()
429
rowsDecodeGeneration += 1
430
let generation = rowsDecodeGeneration
431
@@ -504,11 +507,12 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
507
}
508
}
509
507
- func setTokensPatchJson(_ tokensPatchJson: String) {
510
+ func setTokensPatchJson(_ tokensPatchJson: String, completion: @escaping (Bool) -> Void) {
511
let contentResetKey = self.contentResetKey
512
513
payloadDecodeQueue.async { [weak self] in
514
guard let data = tokensPatchJson.data(using: .utf8) else {
515
+ DispatchQueue.main.async { completion(false) }
516
return
517
}
518
@@ -516,27 +520,34 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
520
let patch = try JSONDecoder().decode(ReviewDiffNativeTokenPatch.self, from: data)
521
DispatchQueue.main.async { [weak self] in
522
guard let self else {
523
+ completion(false)
524
return
525
}
526
guard contentResetKey == self.contentResetKey else {
527
+ completion(false)
528
return
529
}
530
// A highlighter request from the previous file can finish after the view has
531
// already reset. Never let that stale patch roll the native token state back.
532
if let resetKey = patch.resetKey, resetKey != self.tokensResetKey {
533
+ completion(false)
534
return
535
}
536
537
let tokensByRowId = patch.tokensByRowId ?? [:]
538
if tokensByRowId.isEmpty {
539
+ completion(true)
540
return
541
}
542
543
self.contentView.mergeTokensByRowId(tokensByRowId)
536
- if let chunkIndex = patch.chunkIndex, chunkIndex < 5 || chunkIndex.isMultiple(of: 10) {
544
+ completion(true)
545
+ if let chunkIndex = patch.chunkIndex {
546
self.emitDebug("tokens-patch-decoded", [
547
+ "resetKey": patch.resetKey ?? "",
548
"chunkIndex": chunkIndex,
549
"rows": tokensByRowId.count,
550
+ "tokens": tokensByRowId.values.reduce(0) { $0 + $1.count },
551
"totalRows": self.contentView.tokensByRowId.count,
552
])
553
}
@@ -545,6 +556,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
556
let message = error.localizedDescription
557
DispatchQueue.main.async { [weak self] in
558
self?.emitDebug("tokens-patch-decode-failed", ["error": message])
559
+ completion(false)
560
}
561
}
562
}
@@ -587,13 +599,15 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
599
}
600
601
self.contentResetKey = contentResetKey
602
+ lastVisibleRangeDebugKey = ""
603
+ contentView.cancelRowPreparation()
604
rowsDecodeGeneration += 1
605
tokensDecodeGeneration += 1
606
contentView.tokensByRowId = [:]
607
rows = []
608
contentView.rows = []
609
hasAppliedInitialRowIndex = false
596
- pendingScrollFileId = nil
610
+ pendingScrollFileId = initialFileId
611
isProgrammaticScrollActive = false
612
scrollView.setContentOffset(CGPoint(x: 0, y: -scrollView.contentInset.top), animated: false)
613
updateContentMetrics()
@@ -681,12 +695,23 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
695
applyTheme()
696
}
697
684
- private func updateContentMetrics() {
698
+ private func updateContentMetrics(rowAnchor: ReviewDiffViewportRowAnchor? = nil) {
699
+ let anchor = rowAnchor ?? (contentView.viewportWidth != bounds.width
700
+ ? contentView.viewportRowAnchor() : nil)
701
let style = contentView.style
702
contentView.viewportWidth = bounds.width
703
let height = max(bounds.height, contentView.contentHeight)
704
let width = bounds.width
705
scrollView.contentSize = CGSize(width: bounds.width, height: height)
706
+ if let anchor, let offset = contentView.offset(for: anchor) {
707
+ let minOffset = -scrollView.contentInset.top
708
+ let maxOffset = max(height - scrollView.bounds.height + scrollView.contentInset.bottom, minOffset)
709
+ let target = min(max(offset - scrollView.contentInset.top, minOffset), maxOffset)
710
+ if abs(target - scrollView.contentOffset.y) > 0.01 {
711
+ scrollView.setContentOffset(CGPoint(x: 0, y: target), animated: false)
712
+ if isProgrammaticScrollActive { finishVerticalScroll() }
713
+ }
714
+ }
715
contentView.frame = CGRect(
716
x: 0,
717
y: scrollView.contentOffset.y,
@@ -699,6 +724,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
724
applyInitialRowIndexIfNeeded()
725
applyPendingScrollIfNeeded()
726
emitVisibleFileIfNeeded()
727
+ emitVisibleRange(reason: "layout")
728
729
let debugKey = "\(rows.count):\(Int(bounds.width)):\(Int(bounds.height)):\(Int(contentView.contentHeight))"
730
if debugKey != lastMetricsDebugKey {
@@ -759,7 +785,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
785
}
786
787
private func emitVisibleRange(reason: String) {
762
- guard let range = contentView.currentVisibleRowRange() else {
788
+ guard bounds.width > 0, bounds.height > 0,
789
+ let range = contentView.currentVisibleRowRange() else {
790
return
791
}
792
@@ -833,6 +860,16 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
860
applyPendingScrollIfNeeded()
861
}
862
863
+ func setInitialFileId(_ fileId: String) {
864
+ let nextFileId = fileId.isEmpty ? nil : fileId
865
+ guard nextFileId != initialFileId else { return }
866
+ initialFileId = nextFileId
867
+ pendingScrollFileId = nextFileId
868
+ pendingScrollAnimated = false
869
+ // Apply after the prop batch and content metrics, before the first range event.
870
+ setNeedsLayout()
871
+ }
872
+
873
func scrollToTop(animated: Bool) {
874
pendingScrollFileId = nil
875
pendingScrollAnimated = false
@@ -869,10 +906,11 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
906
}
907
908
private func applyStyle() {
909
+ let anchor = contentView.viewportRowAnchor()
910
contentView.style = ReviewDiffNativeStyle
911
.resolve(stylePayload)
912
.applyingOverrides(rowHeight: rowHeightOverride, contentWidth: contentWidthOverride)
875
- updateContentMetrics()
913
+ updateContentMetrics(rowAnchor: anchor)
914
}
915
916
private func updateViewportFrame() {
@@ -918,7 +956,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
956
contentView.isVerticalScrollActive = shouldAnimate
957
scrollView.setContentOffset(CGPoint(x: 0, y: clampedOffset), animated: shouldAnimate)
958
if !shouldAnimate {
921
- updateViewportFrame()
959
+ finishVerticalScroll()
960
}
961
}
962
@@ -964,11 +1002,77 @@ private struct ReviewDiffStickyFileHeaderTarget {
1002
let rect: CGRect
1003
}
1004
1005
+private struct ReviewDiffViewportRowAnchor {
1006
+ let rowIndex: Int
1007
+ let intraRowOffset: CGFloat
1008
+}
1009
+
1010
private struct ReviewDiffScrollAnchor {
1011
let fileId: String
1012
let screenY: CGFloat
1013
}
1014
1015
+private final class ReviewDiffRowPreparation {
1016
+ private let lock = NSLock()
1017
+ private var cancelled = false
1018
+
1019
+ func cancel() {
1020
+ lock.lock()
1021
+ cancelled = true
1022
+ lock.unlock()
1023
+ }
1024
+
1025
+ var isCancelled: Bool {
1026
+ lock.lock()
1027
+ defer { lock.unlock() }
1028
+ return cancelled
1029
+ }
1030
+}
1031
+
1032
+private struct ReviewDiffGeometryConfiguration: Equatable {
1033
+ let style: ReviewDiffNativeStyle
1034
+ let viewportWidth: CGFloat
1035
+ let collapsedFileIds: Set<String>
1036
+ let collapsedCommentIds: Set<String>
1037
+
1038
+ func height(for row: ReviewDiffNativeRow) -> CGFloat {
1039
+ if row.kind == "file" { return style.fileHeaderHeight }
1040
+ if collapsedFileIds.contains(row.resolvedFileId) { return 0 }
1041
+ if row.kind == "notice" { return max(style.rowHeight * 2, 44) }
1042
+ if row.kind == "comment" { return collapsedCommentIds.contains(row.id) ? 44 : 124 }
1043
+ return style.rowHeight
1044
+ }
1045
+}
1046
+
1047
+private struct ReviewDiffRowGeometryInput {
1048
+ let configuration: ReviewDiffGeometryConfiguration
1049
+ let font: UIFont
1050
+ let hunkFont: UIFont
1051
+ let characterWidth: CGFloat
1052
+ let layoutWidth: CGFloat?
1053
+ let cached: [String: ReviewDiffCodeLayout]
1054
+}
1055
+
1056
+private struct ReviewDiffRowGeometry {
1057
+ let offsets: [CGFloat]
1058
+ let fileHeaderIndices: [Int]
1059
+ let contentWidths: [String: CGFloat]
1060
+ let nativeLayouts: [String: ReviewDiffCodeLayout]
1061
+ let height: CGFloat
1062
+ let characterWidth: CGFloat
1063
+ let wrapColumns: Int?
1064
+}
1065
+
1066
+private extension ReviewDiffNativeRow {
1067
+ var resolvedFileId: String {
1068
+ if let fileId { return fileId }
1069
+ if let range = id.range(of: ":header") ?? id.range(of: ":hunk:") ?? id.range(of: ":line:") {
1070
+ return String(id[..<range.lowerBound])
1071
+ }
1072
+ return filePath ?? id
1073
+ }
1074
+}
1075
+
1076
private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
1077
var rows: [ReviewDiffNativeRow] = [] {
1078
didSet {
@@ -979,7 +1083,13 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
1083
activePanKind = nil
1084
codeDecorationVersion += 1
1085
tokenAttributedStringsByRowId.removeAll()
982
- rebuildRowLayout()
1086
+ if let geometry = preparedRowGeometry {
1087
+ preparedRowGeometry = nil
1088
+ applyRowGeometry(geometry)
1089
+ } else {
1090
+ cancelRowPreparation()
1091
+ rebuildRowLayout()
1092
+ }
1093
setNeedsDisplayForVisibleBounds()
1094
}
1095
}
@@ -993,12 +1103,8 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
1103
}
1104
1105
func mergeTokensByRowId(_ tokensPatch: [String: [ReviewDiffNativeToken]]) {
996
- tokensPatch.forEach { rowId, tokens in
997
- tokensByRowId[rowId] = tokens
998
- tokenAttributedStringsByRowId.removeValue(forKey: rowId)
999
- }
1000
- clampHorizontalOffsets()
1001
- setNeedsDisplayForVisibleBounds()
1106
+ // One mutation lets didSet invalidate decoration and display once per batch.
1107
+ tokensByRowId.merge(tokensPatch) { _, tokens in tokens }
1108
}
1109
1110
var collapsedFileIds: Set<String> = [] {
@@ -1065,9 +1171,18 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
1171
private var codeWrapColumns: Int?
1172
/// Text geometry survives comment height changes; width, font, and content invalidate it.
1173
private var codeLayoutsByRowId: [String: ReviewDiffCodeLayout] = [:]
1068
- private var codeLayoutWidth: CGFloat = 0
1174
+ private var codeLayoutWidth: CGFloat?
1175
private var codeLayoutFont: UIFont?
1176
private var codeDecorationVersion = 0
1177
+ private var rowPreparation: ReviewDiffRowPreparation?
1178
+ private var preparedRowGeometry: ReviewDiffRowGeometry?
1179
+
1180
+ private var geometryConfiguration: ReviewDiffGeometryConfiguration {
1181
+ ReviewDiffGeometryConfiguration(
1182
+ style: style, viewportWidth: viewportWidth,
1183
+ collapsedFileIds: collapsedFileIds, collapsedCommentIds: collapsedCommentIds
1184
+ )
1185
+ }
1186
private var panStartHorizontalOffset: CGFloat = 0
1187
private var activePanFileId: String?
1188
private var activePanKind: ReviewDiffHorizontalPanKind?
@@ -1095,19 +1210,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
1210
1211
/// Height before word wrap. Laid-out rows use height(at:), which includes wrapped lines.
1212
private func height(for row: ReviewDiffNativeRow) -> CGFloat {
1098
- if row.kind == "file" {
1099
- return style.fileHeaderHeight
1100
- }
1101
- if collapsedFileIds.contains(resolvedFileId(for: row)) {
1102
- return 0
1103
- }
1104
- if row.kind == "notice" {
1105
- return max(style.rowHeight * 2, 44)
1106
- }
1107
- if row.kind == "comment" {
1108
- return collapsedCommentIds.contains(row.id) ? 44 : 124
1109
- }
1110
- return style.rowHeight
1213
+ geometryConfiguration.height(for: row)
1214
}
1215
1216
/// Laid-out height, including wrapped lines. Requires a layout built from the current rows.
@@ -1141,111 +1244,174 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
1244
)
1245
}
1246
1144
- /// Shape new content on the existing decode worker before publishing rows to the UI.
1247
+ // Pixel offsets cannot identify the same code row after wrapping or font changes.
1248
+ func viewportRowAnchor() -> ReviewDiffViewportRowAnchor? {
1249
+ let top = max(0, verticalOffset + topContentInset)
1250
+ guard let index = rowIndex(at: top) else { return nil }
1251
+ return ReviewDiffViewportRowAnchor(rowIndex: index, intraRowOffset: top - rowOffsets[index])
1252
+ }
1253
+
1254
+ func offset(for anchor: ReviewDiffViewportRowAnchor) -> CGFloat? {
1255
+ guard let frame = frameForRow(at: anchor.rowIndex), frame.height > 0 else { return nil }
1256
+ let intraRowOffset = anchor.intraRowOffset < frame.height
1257
+ ? anchor.intraRowOffset : max(0, frame.height - 1)
1258
+ return frame.minY + intraRowOffset
1259
+ }
1260
+
1261
+ func cancelRowPreparation() {
1262
+ rowPreparation?.cancel()
1263
+ rowPreparation = nil
1264
+ preparedRowGeometry = nil
1265
+ }
1266
+
1267
+ /// Prepare immutable geometry on the decode worker; publication only swaps its buffers.
1268
func prepareRows(
1269
_ rows: [ReviewDiffNativeRow],
1270
on queue: DispatchQueue,
1271
isCurrent: @escaping () -> Bool,
1272
completion: @escaping () -> Void
1273
) {
1274
+ cancelRowPreparation()
1275
+ let preparation = ReviewDiffRowPreparation()
1276
+ rowPreparation = preparation
1277
+ let configuration = geometryConfiguration
1278
let font = codeFont
1279
let characterWidth = monospaceCharacterWidth(font: font)
1153
- guard let width = codeLayoutWidthLimit(font: font) else {
1154
- completion()
1155
- return
1156
- }
1280
+ let width = codeLayoutWidthLimit(font: font)
1281
+ let hunkFont = self.hunkFont
1282
let cached = codeLayoutWidth == width && codeLayoutFont == font ? codeLayoutsByRowId : [:]
1283
+ let input = ReviewDiffRowGeometryInput(
1284
+ configuration: configuration, font: font, hunkFont: hunkFont,
1285
+ characterWidth: characterWidth, layoutWidth: width, cached: cached
1286
+ )
1287
queue.async { [weak self] in
1159
- var layouts: [String: ReviewDiffCodeLayout] = [:]
1160
- for row in rows where row.kind == "line" {
1161
- guard let text = row.content else { continue }
1162
- if let previous = cached[row.id], previous.text == text {
1163
- layouts[row.id] = previous
1164
- } else {
1165
- layouts[row.id] = ReviewDiffCodeLayout(text: text, font: font, width: width, characterWidth: characterWidth)
1166
- }
1167
- }
1288
+ guard let geometry = Self.buildRowGeometry(
1289
+ rows, input: input, isCancelled: { preparation.isCancelled }
1290
+ ) else { return }
1291
DispatchQueue.main.async { [weak self] in
1169
- guard let self, isCurrent() else { return }
1170
- if self.codeFont != font || self.codeLayoutWidthLimit(font: font) != width {
1292
+ guard let self, !preparation.isCancelled, isCurrent() else { return }
1293
+ if self.geometryConfiguration != configuration {
1294
self.prepareRows(rows, on: queue, isCurrent: isCurrent, completion: completion)
1295
return
1296
}
1297
+ self.rowPreparation = nil
1298
self.codeLayoutWidth = width
1299
self.codeLayoutFont = font
1176
- self.codeLayoutsByRowId = layouts
1300
+ self.preparedRowGeometry = geometry
1301
completion()
1302
}
1303
}
1304
}
1305
1306
private func rebuildRowLayout() {
1307
+ let font = codeFont
1308
+ let characterWidth = monospaceCharacterWidth(font: font)
1309
+ let layoutWidth = codeLayoutWidthLimit(font: font)
1310
+ let cached = codeLayoutWidth == layoutWidth && codeLayoutFont == font ? codeLayoutsByRowId : [:]
1311
+ let input = ReviewDiffRowGeometryInput(
1312
+ configuration: geometryConfiguration, font: font, hunkFont: hunkFont,
1313
+ characterWidth: characterWidth, layoutWidth: layoutWidth, cached: cached
1314
+ )
1315
+ guard let geometry = Self.buildRowGeometry(rows, input: input) else { return }
1316
+ codeLayoutWidth = layoutWidth
1317
+ codeLayoutFont = font
1318
+ applyRowGeometry(geometry)
1319
+ }
1320
+
1321
+ private static func buildRowGeometry(
1322
+ _ rows: [ReviewDiffNativeRow],
1323
+ input: ReviewDiffRowGeometryInput,
1324
+ isCancelled: () -> Bool = { false }
1325
+ ) -> ReviewDiffRowGeometry? {
1326
var nextOffsets: [CGFloat] = []
1327
var nextFileHeaderRowIndices: [Int] = []
1328
nextOffsets.reserveCapacity(rows.count)
1329
var maxWidthsByFileId: [String: CGFloat] = [:]
1330
var nextCodeLayouts: [String: ReviewDiffCodeLayout] = [:]
1331
var offset: CGFloat = 0
1189
- let font = codeFont
1190
- let characterWidth = monospaceCharacterWidth(font: font)
1191
- let layoutWidth = codeLayoutWidthLimit(font: font)
1192
- let wrapColumns = style.wordWrap ? layoutWidth.map { Int($0 / characterWidth) } : nil
1193
- if let layoutWidth, codeLayoutWidth != layoutWidth || codeLayoutFont != font {
1194
- codeLayoutsByRowId.removeAll()
1195
- codeLayoutWidth = layoutWidth
1196
- codeLayoutFont = font
1197
- }
1332
+ let style = input.configuration.style
1333
+ let characterWidth = input.characterWidth
1334
+ let wrapColumns = style.wordWrap ? input.layoutWidth.map { Int($0 / characterWidth) } : nil
1335
1336
for (index, row) in rows.enumerated() {
1337
+ // Bound obsolete work without locking once per row; never read UIView state here.
1338
+ if index.isMultiple(of: 256), isCancelled() { return nil }
1339
nextOffsets.append(offset)
1340
if row.kind == "file" {
1341
nextFileHeaderRowIndices.append(index)
1342
}
1204
- var rowHeight = height(for: row)
1205
-
1206
- let fileId = resolvedFileId(for: row)
1343
+ var rowHeight = input.configuration.height(for: row)
1344
+ let fileId = row.resolvedFileId
1345
switch row.kind {
1346
case "line":
1209
- // UTF-16 columns match the word diff ranges and the segments drawCodeLines draws.
1210
- var width = CGFloat(row.content?.utf16.count ?? 0) * characterWidth
1211
- if let layoutWidth, let content = row.content {
1212
- let cached = codeLayoutsByRowId[row.id]
1213
- let layout: ReviewDiffCodeLayout
1214
- if let cached, cached.text == content {
1215
- layout = cached
1216
- } else {
1217
- layout = ReviewDiffCodeLayout(
1218
- text: content, font: font, width: layoutWidth, characterWidth: characterWidth
1219
- )
1220
- }
1221
- nextCodeLayouts[row.id] = layout
1222
- // Tabs and fallback glyphs are wider than one column.
1223
- width = layout.usedWidth
1224
- if rowHeight > 0 {
1225
- rowHeight = max(rowHeight, layout.firstLineHeight) + layout.extraHeight
1226
- }
1227
- }
1347
+ let width = lineWidth(
1348
+ for: row, input: input, wrapColumns: wrapColumns,
1349
+ height: &rowHeight, layouts: &nextCodeLayouts
1350
+ )
1351
maxWidthsByFileId[fileId] = max(maxWidthsByFileId[fileId] ?? 0, width)
1352
case "hunk":
1230
- // Hunk context can hold tabs and draws in its own font, so measure what drawHunkRow draws.
1231
- maxWidthsByFileId[fileId] = max(
1232
- maxWidthsByFileId[fileId] ?? 0,
1233
- textWidth(row.text ?? "", font: hunkFont)
1234
- )
1353
+ // Hunk context can hold tabs and draws in its own font.
1354
+ let width = ceil(((row.text ?? "") as NSString).size(withAttributes: [.font: input.hunkFont, .ligature: 0]).width)
1355
+ maxWidthsByFileId[fileId] = max(maxWidthsByFileId[fileId] ?? 0, width)
1356
default:
1357
break
1358
}
1359
offset += rowHeight
1360
}
1361
+ guard !isCancelled() else { return nil }
1362
+ return ReviewDiffRowGeometry(
1363
+ offsets: nextOffsets, fileHeaderIndices: nextFileHeaderRowIndices,
1364
+ contentWidths: maxWidthsByFileId.mapValues { ceil($0) + style.codePadding * 2 },
1365
+ nativeLayouts: nextCodeLayouts, height: offset,
1366
+ characterWidth: characterWidth, wrapColumns: wrapColumns
1367
+ )
1368
+ }
1369
1241
- codeCharacterWidth = characterWidth
1242
- codeWrapColumns = wrapColumns
1243
- codeLayoutsByRowId = nextCodeLayouts
1244
- // Measured widths are not capped, so the end of every line stays reachable by scrolling.
1245
- contentWidthsByFileId = maxWidthsByFileId.mapValues { ceil($0) + style.codePadding * 2 }
1246
- rowOffsets = nextOffsets
1247
- fileHeaderRowIndices = nextFileHeaderRowIndices
1248
- contentHeight = offset
1370
+ private static func lineWidth(
1371
+ for row: ReviewDiffNativeRow,
1372
+ input: ReviewDiffRowGeometryInput,
1373
+ wrapColumns: Int?,
1374
+ height: inout CGFloat,
1375
+ layouts: inout [String: ReviewDiffCodeLayout]
1376
+ ) -> CGFloat {
1377
+ let characterWidth = input.characterWidth
1378
+ let font = input.font
1379
+ var width = CGFloat(row.content?.utf16.count ?? 0) * characterWidth
1380
+ if let layoutWidth = input.layoutWidth, let content = row.content {
1381
+ if ReviewDiffCodeLayout.isPrintableASCII(content) {
1382
+ let length = content.utf8.count
1383
+ let starts = ReviewDiffCodeLineStarts(length: length, columns: wrapColumns)
1384
+ width = CGFloat(min(length, starts.columns)) * characterWidth
1385
+ if height > 0 {
1386
+ height = max(height, font.lineHeight) + CGFloat(starts.count - 1) * ceil(font.lineHeight)
1387
+ }
1388
+ } else {
1389
+ let layout: ReviewDiffCodeLayout
1390
+ if let previous = input.cached[row.id], previous.text == content {
1391
+ layout = previous
1392
+ } else {
1393
+ layout = ReviewDiffCodeLayout(
1394
+ text: content, font: font, width: layoutWidth, characterWidth: characterWidth
1395
+ )
1396
+ }
1397
+ layouts[row.id] = layout
1398
+ width = layout.usedWidth
1399
+ if height > 0 {
1400
+ height = max(height, layout.firstLineHeight) + layout.extraHeight
1401
+ }
1402
+ }
1403
+ }
1404
+ return width
1405
+ }
1406
+
1407
+ private func applyRowGeometry(_ geometry: ReviewDiffRowGeometry) {
1408
+ codeCharacterWidth = geometry.characterWidth
1409
+ codeWrapColumns = geometry.wrapColumns
1410
+ codeLayoutsByRowId = geometry.nativeLayouts
1411
+ contentWidthsByFileId = geometry.contentWidths
1412
+ rowOffsets = geometry.offsets
1413
+ fileHeaderRowIndices = geometry.fileHeaderIndices
1414
+ contentHeight = geometry.height
1415
}
1416
1417
private var codeFont: UIFont {
@@ -1704,13 +1870,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
1870
}
1871
1872
private func resolvedFileId(for row: ReviewDiffNativeRow) -> String {
1707
- if let fileId = row.fileId {
1708
- return fileId
1709
- }
1710
- if let range = row.id.range(of: ":header") ?? row.id.range(of: ":hunk:") ?? row.id.range(of: ":line:") {
1711
- return String(row.id[..<range.lowerBound])
1712
- }
1713
- return row.filePath ?? row.id
1873
+ row.resolvedFileId
1874
}
1875
1876
private func horizontalOffset(
@@ -2325,9 +2485,11 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
2485
let change = row.change ?? "context"
2486
// Wrapped rows keep the line number and first code line in the first row-height band.
2487
let layout = codeLayoutsByRowId[row.id]
2488
+ let firstLineHeight = layout?.firstLineHeight
2489
+ ?? (row.content != nil && codeLayoutWidth != nil ? codeFont.lineHeight : 0)
2490
let firstLineRect = CGRect(
2491
x: rect.minX, y: rect.minY, width: rect.width,
2330
- height: max(style.rowHeight, layout?.firstLineHeight ?? 0)
2492
+ height: max(style.rowHeight, firstLineHeight)
2493
)
2494
rowBackground(for: change).setFill()
2495
context.fill(rect)
@@ -2387,7 +2549,9 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
2549
context.restoreGState()
2550
return
2551
}
2390
- let lineStarts = layout?.starts ?? [0]
2552
+ let lineStarts = ReviewDiffCodeLineStarts(
2553
+ length: (row.content ?? "").utf16.count, columns: codeWrapColumns
2554
+ )
2555
drawWordDiffRanges(
2556
row,
2557
lineStarts: lineStarts,
@@ -2421,7 +2585,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
2585
/// Draws the segment starting at each of the row's line starts on its own visual line.
2586
private func drawCodeLines(
2587
length: Int,
2424
- lineStarts: [Int],
2588
+ lineStarts: ReviewDiffCodeLineStarts,
2589
firstLineRect: CGRect,
2590
draw: (NSRange, CGRect) -> Void
2591
) {
@@ -2455,7 +2619,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
2619
2620
private func drawWordDiffRanges(
2621
_ row: ReviewDiffNativeRow,
2458
- lineStarts: [Int],
2622
+ lineStarts: ReviewDiffCodeLineStarts,
2623
firstLineRect: CGRect,
2624
context: CGContext,
2625
horizontalOffset: CGFloat
apps/mobile/modules/t3-review-diff/tests/android/.gitignore
new
+2
@@ -0,0 +1,2 @@
1
+.gradle/
2
+build/
apps/mobile/modules/t3-review-diff/tests/android/README.md
new
+33
@@ -0,0 +1,33 @@
1
+# Android native regressions
2
+
3
+From the repository root:
4
+
5
+```sh
6
+apps/mobile/modules/t3-review-diff/tests/run-android.sh
7
+```
8
+
9
+Requires JDK 17+ (`JAVA_HOME`) and Gradle on `PATH`. Tested with JDK 17 and
10
+Gradle 9.4.1. To use another installed Gradle or a wrapper, set
11
+`GRADLE=/absolute/path/to/gradle` before the command. The runner resolves its own
12
+location, so it also works from other directories. Gradle test options are
13
+forwarded, for example `--tests '*ReviewDiffViewportTest' --rerun-tasks`.
14
+
15
+This standalone JVM build registers the viewport and geometry regressions and the
16
+module's existing `android/src/test` layout suite with Gradle's `test` task. It
17
+compiles the module's actual Android view, drawing, and layout sources. Pinned Maven dependencies supply Kotlin, Robolectric, Android API 35,
18
+and AndroidX test classes. The first run requires access to Maven Central and
19
+Google Maven, including Robolectric's runtime SDK download. No local Android
20
+SDK, Expo prebuild, device, temporary checkout, or pre-extracted jars are needed.
21
+Generated files stay in ignored `build/` and `.gradle/` directories; the HTML
22
+report is `build/reports/tests/test/index.html`.
23
+
24
+The three files under `stubs/expo/modules/kotlin/` replace only Expo's context, view base class, and event
25
+dispatcher. Events go to a per-test context instead of a React Native bridge.
26
+This checks reset/decode ordering, stale-row removal, and viewport publication
27
+in the real view, but does not validate Expo registration, JS event delivery,
28
+native libraries, or device rendering. These stubs are exclusive to this
29
+standalone build and must not be added to the production Android source set.
30
+Geometry regressions bound sticky-header row reads, check lazy ASCII layout
31
+retention and syntax invalidation, and compare ASCII widths against Android
32
+paint metrics. Native shaping tests cover tabs, Unicode clusters, and styled
33
+word-diff spans.
apps/mobile/modules/t3-review-diff/tests/android/build.gradle
new
+77
@@ -0,0 +1,77 @@
1
+plugins { id 'java' }
2
+
3
+repositories {
4
+ mavenCentral()
5
+ google()
6
+}
7
+
8
+configurations {
9
+ compiler
10
+ androidTestAars
11
+}
12
+
13
+dependencies {
14
+ compiler 'org.jetbrains.kotlin:kotlin-compiler-embeddable:2.2.21'
15
+ testImplementation 'org.jetbrains.kotlin:kotlin-stdlib:2.2.21'
16
+ testImplementation 'junit:junit:4.13.2'
17
+ testImplementation('org.robolectric:robolectric:4.16.1') {
18
+ exclude group: 'androidx.test', module: 'monitor'
19
+ exclude group: 'androidx.test.espresso', module: 'espresso-idling-resource'
20
+ }
21
+ // Compile against the same API used by @Config(sdk = [35]), without a local Android SDK.
22
+ testImplementation 'org.robolectric:android-all:15-robolectric-12650502'
23
+ androidTestAars 'androidx.test:monitor:1.8.0@aar'
24
+ androidTestAars 'androidx.test.espresso:espresso-idling-resource:3.7.0@aar'
25
+ testImplementation files(layout.buildDirectory.dir('android-test-jars').map {
26
+ fileTree(it) { include '**/*.jar' }
27
+ })
28
+}
29
+
30
+// The JVM plugin cannot load classes.jar inside AndroidX AAR dependencies.
31
+tasks.register('extractAndroidTestJars') {
32
+ inputs.files configurations.androidTestAars
33
+ outputs.dir layout.buildDirectory.dir('android-test-jars')
34
+ doLast {
35
+ configurations.androidTestAars.each { aar ->
36
+ copy {
37
+ from zipTree(aar)
38
+ include 'classes.jar'
39
+ filePermissions { unix('644') }
40
+ into layout.buildDirectory.dir("android-test-jars/${aar.name}")
41
+ }
42
+ }
43
+ }
44
+}
45
+
46
+def moduleRoot = file('../..')
47
+def sources = files(
48
+ fileTree('stubs') { include '**/*.kt' },
49
+ fileTree('src/test/kotlin') { include '**/*.kt' },
50
+ fileTree("${moduleRoot}/android/src/test/java") { include '**/*.kt' },
51
+ fileTree("${moduleRoot}/android/src/main/java/expo/modules/t3reviewdiff") {
52
+ include '**/*.kt'
53
+ exclude '**/T3ReviewDiffModule.kt'
54
+ },
55
+)
56
+
57
+tasks.register('compileRegression', JavaExec) {
58
+ dependsOn 'extractAndroidTestJars'
59
+ classpath = configurations.compiler
60
+ mainClass = 'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler'
61
+ inputs.files sources, configurations.testCompileClasspath
62
+ outputs.dir layout.buildDirectory.dir('regression')
63
+ doFirst {
64
+ args = [
65
+ '-no-stdlib', '-no-reflect', '-jvm-target', '17',
66
+ '-classpath', configurations.testCompileClasspath.asPath,
67
+ '-d', layout.buildDirectory.dir('regression').get().asFile.absolutePath,
68
+ ] + sources.files.collect { it.absolutePath }
69
+ }
70
+}
71
+
72
+test {
73
+ dependsOn 'compileRegression'
74
+ testClassesDirs = files(layout.buildDirectory.dir('regression'))
75
+ classpath = files(testClassesDirs, configurations.testRuntimeClasspath)
76
+ testLogging { events 'passed', 'failed'; exceptionFormat 'full' }
77
+}
apps/mobile/modules/t3-review-diff/tests/android/settings.gradle
new
+1
@@ -0,0 +1 @@
1
+rootProject.name = 't3-review-diff-viewport-tests'
apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt
new
+244
@@ -0,0 +1,244 @@
1
+package expo.modules.t3reviewdiff
2
+
3
+import android.graphics.Color
4
+import android.view.View
5
+import kotlin.math.ceil
6
+import expo.modules.kotlin.AppContext
7
+import org.junit.Assert.assertEquals
8
+import org.junit.Assert.assertSame
9
+import org.junit.Assert.assertTrue
10
+import org.junit.Test
11
+import org.junit.runner.RunWith
12
+import org.robolectric.RobolectricTestRunner
13
+import org.robolectric.RuntimeEnvironment
14
+import org.robolectric.annotation.Config
15
+import org.robolectric.annotation.GraphicsMode
16
+
17
+@RunWith(RobolectricTestRunner::class)
18
+@Config(sdk = [35], manifest = Config.NONE)
19
+@GraphicsMode(GraphicsMode.Mode.NATIVE)
20
+class ReviewDiffGeometryTest {
21
+ @Test
22
+ fun geometryChangesKeepTheVisibleRowAndClampWithinShortenedRows() {
23
+ val parent = T3ReviewDiffView(RuntimeEnvironment.getApplication(), AppContext())
24
+ val canvas = parent.getChildAt(0)
25
+ val spec = View.MeasureSpec.makeMeasureSpec(390, View.MeasureSpec.EXACTLY)
26
+ canvas.measure(spec, spec)
27
+ canvas.layout(0, 0, 390, 600)
28
+ try {
29
+ val rows = listOf("highlights.c", "simd128.h").flatMap { file ->
30
+ listOf(row("$file:header", "").copy(kind = "file", fileId = file)) +
31
+ List(100) { line ->
32
+ row("$file:line:$line", "long native code ".repeat(line % 9 + 1)).copy(fileId = file)
33
+ }
34
+ }
35
+ call(canvas, "setRows", rows)
36
+ val index = 130
37
+ fun position(intra: Int) {
38
+ call(canvas, "setVerticalOffset", (call(canvas, "rowTop", index) as Int) + intra)
39
+ }
40
+ fun assertPosition(intra: Int, reason: String) {
41
+ val top = call(canvas, "verticalOffset") as Int
42
+ assertEquals("$reason: visible row/file changed", index, call(canvas, "rowIndexAt", top))
43
+ assertEquals(
44
+ "$reason: intra-row position changed",
45
+ intra,
46
+ top - (call(canvas, "rowTop", index) as Int)
47
+ )
48
+ }
49
+ position(7)
50
+ call(parent, "scrollToY", 0, true)
51
+ val scroller = field(parent, "verticalScroller") as android.widget.OverScroller
52
+ assertTrue(!scroller.isFinished)
53
+ parent.setStyleJson("{\"wordWrap\":true}")
54
+ assertPosition(7, "wrap on")
55
+ assertTrue(
56
+ "Geometry correction must stop the old absolute scroll trajectory",
57
+ scroller.isFinished
58
+ )
59
+ parent.computeScroll()
60
+ assertPosition(7, "after interrupted animation")
61
+ parent.setStyleJson("{\"wordWrap\":true,\"codeFontSize\":22}")
62
+ assertPosition(7, "font change")
63
+ canvas.layout(0, 0, 280, 600)
64
+ assertPosition(7, "wrapped width change")
65
+ val height =
66
+ (call(canvas, "rowTop", index + 1) as Int) - (call(canvas, "rowTop", index) as Int)
67
+ position(height - 2)
68
+ parent.setStyleJson("{\"wordWrap\":false,\"rowHeight\":24}")
69
+ val shorterHeight =
70
+ (call(canvas, "rowTop", index + 1) as Int) - (call(canvas, "rowTop", index) as Int)
71
+ assertPosition(shorterHeight - 1, "unwrap clamps inside shortened row")
72
+ parent.setContentResetKey("new-content")
73
+ parent.setStyleJson("{\"wordWrap\":true}")
74
+ assertEquals(0, call(canvas, "verticalOffset"))
75
+ } finally {
76
+ parent.cleanup()
77
+ }
78
+ }
79
+
80
+ @Test
81
+ fun stickyHeadersUseTheHeaderIndexAndKeepPushOffAndHitTesting() {
82
+ val parent = T3ReviewDiffView(RuntimeEnvironment.getApplication(), AppContext())
83
+ val canvas = parent.getChildAt(0)
84
+ val spec = View.MeasureSpec.makeMeasureSpec(320, View.MeasureSpec.EXACTLY)
85
+ canvas.measure(spec, spec)
86
+ canvas.layout(0, 0, 320, 320)
87
+ try {
88
+ val rows = CountingRows(
89
+ List(10000) { index ->
90
+ row("row:$index", "const value = $index").copy(
91
+ kind = if (index == 100 || index == 9000) "file" else "line",
92
+ fileId = if (index < 9000) "first" else "second",
93
+ )
94
+ }
95
+ )
96
+ call(canvas, "setRows", rows)
97
+ assertEquals(null, call(canvas, "stickyFileHeader", 0))
98
+ val nextTop = call(canvas, "rowTop", 9000) as Int
99
+ call(canvas, "setVerticalOffset", nextTop - 10)
100
+ rows.reads = 0
101
+ val sticky = requireNotNull(call(canvas, "stickyFileHeader", 8999))
102
+ assertEquals(100, field(sticky, "index"))
103
+ assertEquals(10, field(sticky, "bottom"))
104
+ assertTrue("sticky lookup must not scan code rows: ${rows.reads}", rows.reads < 10)
105
+ val hit = requireNotNull(call(canvas, "rowHitAt", 5f))
106
+ assertEquals("row:100", (field(hit, "row") as DiffRow).id)
107
+ val second = requireNotNull(call(canvas, "stickyFileHeader", 9000))
108
+ assertEquals(9000, field(second, "index"))
109
+ call(canvas, "setRows", listOf(row("only", "value")))
110
+ assertEquals(null, call(canvas, "stickyFileHeader", 0))
111
+ } finally {
112
+ parent.cleanup()
113
+ }
114
+ }
115
+
116
+ @Test
117
+ fun asciiSyntaxArrivalDoesNotRebuildWrappedOffsetsOrRetainPerRowLayouts() {
118
+ val parent = T3ReviewDiffView(RuntimeEnvironment.getApplication(), AppContext())
119
+ val canvas = parent.getChildAt(0)
120
+ val spec = View.MeasureSpec.makeMeasureSpec(320, View.MeasureSpec.EXACTLY)
121
+ canvas.measure(spec, spec)
122
+ canvas.layout(0, 0, 320, 320)
123
+ try {
124
+ call(canvas, "setStyle", DiffStyle.defaults(1f).copy(wordWrap = true))
125
+ val rows = List(10000) { row("row:$it", "const value = 123; ".repeat(10)) }
126
+ call(canvas, "setRows", rows)
127
+ val offsets = field(canvas, "rowOffsets")
128
+ call(
129
+ canvas,
130
+ "setTokensByRowId",
131
+ mapOf(rows[0].id to listOf(DiffToken(rows[0].content, 0xff008800.toInt(), 2)))
132
+ )
133
+ assertSame("ASCII syntax must only repaint", offsets, field(canvas, "rowOffsets"))
134
+ val drawing = requireNotNull(field(canvas, "drawing"))
135
+ val cache = requireNotNull(field(drawing, "codeLayouts"))
136
+ assertEquals(
137
+ "offscreen ASCII must not retain layout objects",
138
+ 0,
139
+ (field(cache, "entries") as Map<*, *>).size
140
+ )
141
+ } finally {
142
+ parent.cleanup()
143
+ }
144
+ }
145
+
146
+ @Test
147
+ fun asciiWidthCacheDoesNotRetainPerRowMeasurementObjects() {
148
+ val drawing = ReviewDiffCanvasDrawing(RuntimeEnvironment.getApplication())
149
+ val rows = List(10000) { row("row:$it", "const value = $it") }
150
+ drawing.contentWidth(rows, emptyMap(), DiffStyle.defaults(1f))
151
+ assertEquals(0, (field(drawing, "widthEntries") as Map<*, *>).size)
152
+ }
153
+
154
+ @Test
155
+ fun asciiWidthMatchesPaintForEverySyntaxFontAndWeight() {
156
+ val drawing = ReviewDiffCanvasDrawing(RuntimeEnvironment.getApplication())
157
+ val content = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
158
+ "[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
159
+ val row = row("ascii", content)
160
+ for (weight in listOf("regular", "medium", "bold")) {
161
+ val style = DiffStyle.defaults(1f).copy(codeFontWeight = weight, codeFontSizePx = 17f)
162
+ for (fontStyle in 0..7) {
163
+ drawing.configureCodePaint(Color.RED, fontStyle, style)
164
+ val expected = ceil(
165
+ style.changeBarWidthPx + style.gutterWidthPx + style.codePaddingPx * 2f +
166
+ drawing.textPaint.measureText(content),
167
+ ).toInt()
168
+ val tokens = mapOf(row.id to listOf(DiffToken(content, Color.RED, fontStyle)))
169
+ assertEquals(
170
+ "weight=$weight style=$fontStyle",
171
+ expected,
172
+ drawing.contentWidth(listOf(row), tokens, style)
173
+ )
174
+ val recolored = mapOf(row.id to listOf(DiffToken(content, Color.BLUE, fontStyle xor 4)))
175
+ assertEquals(false, drawing.tokensChangeWidth(tokens, recolored, style))
176
+ }
177
+ }
178
+ }
179
+
180
+ @Test
181
+ fun lazyAsciiHeightAndLineStartsMatchTheExistingLayoutAtEveryBoundary() {
182
+ val drawing = ReviewDiffCanvasDrawing(RuntimeEnvironment.getApplication())
183
+ val style = DiffStyle.defaults(1f).copy(wordWrap = true, codeFontSizePx = 17f)
184
+ drawing.configureCodePaint(Color.BLACK, 0, style)
185
+ val paint = android.text.TextPaint(drawing.textPaint)
186
+ val cache = CodeLayoutCache()
187
+ for (width in listOf(120, 180, 280, 420)) {
188
+ for (length in listOf(0, 1, 13, 14, 15, 1000)) {
189
+ val row = row("ascii", "a".repeat(length))
190
+ val expected = createCodeLines(row.content, paint, width)
191
+ val wrapped = cache.layout(
192
+ listOf(row),
193
+ emptyMap(),
194
+ paint,
195
+ style,
196
+ DiffTheme.fallback("light"),
197
+ width
198
+ )
199
+ assertTrue(expected.starts.contentEquals(wrapped.lines(row).starts))
200
+ assertEquals(expected.firstHeight(24) + expected.extraHeight, wrapped.rowHeight(row, 24))
201
+ }
202
+ }
203
+ }
204
+
205
+ @Test
206
+ fun unwrappedColorAndUnderlinePatchesDoNotReadOffscreenRows() {
207
+ val parent = T3ReviewDiffView(RuntimeEnvironment.getApplication(), AppContext())
208
+ val canvas = parent.getChildAt(0)
209
+ try {
210
+ val rows = CountingRows(List(10000) { row("row:$it", "const value = $it") })
211
+ call(canvas, "setRows", rows)
212
+ val content = rows[0].content
213
+ rows.reads = 0
214
+ call(canvas, "setTokensByRowId", mapOf("row:0" to listOf(DiffToken(content, Color.RED, 0))))
215
+ call(canvas, "setTokensByRowId", mapOf("row:0" to listOf(DiffToken(content, Color.BLUE, 4))))
216
+ assertEquals(0, rows.reads)
217
+ } finally {
218
+ parent.cleanup()
219
+ }
220
+ }
221
+
222
+ private fun call(target: Any, name: String, vararg args: Any): Any? = target.javaClass
223
+ .declaredMethods.single { it.name == name && it.parameterCount == args.size }
224
+ .apply { isAccessible = true }.invoke(target, *args)
225
+
226
+ private fun field(target: Any, name: String): Any? = target.javaClass.getDeclaredField(name)
227
+ .apply { isAccessible = true }.get(target)
228
+
229
+ private fun row(id: String, content: String) = DiffRow(
230
+ kind = "line", id = id, fileId = "file", filePath = "test.ts", previousPath = null,
231
+ changeType = "modified", additions = 1, deletions = 0, text = "", content = content,
232
+ change = "add", oldLineNumber = null, newLineNumber = 1, wordDiffRanges = emptyList(),
233
+ commentText = "", commentRangeLabel = "", commentSectionTitle = "",
234
+ )
235
+
236
+ private class CountingRows(private val rows: List<DiffRow>) : AbstractList<DiffRow>() {
237
+ var reads = 0
238
+ override val size: Int get() = rows.size
239
+ override fun get(index: Int): DiffRow {
240
+ reads += 1
241
+ return rows[index]
242
+ }
243
+ }
244
+}
apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffViewportTest.kt
new
+156
@@ -0,0 +1,156 @@
1
+package expo.modules.t3reviewdiff
2
+
3
+import android.app.Activity
4
+import android.graphics.Bitmap
5
+import android.graphics.Canvas
6
+import android.os.Looper
7
+import android.view.View
8
+import expo.modules.kotlin.AppContext
9
+import java.util.concurrent.AbstractExecutorService
10
+import java.util.concurrent.TimeUnit
11
+import org.json.JSONArray
12
+import org.json.JSONObject
13
+import org.junit.Assert.assertEquals
14
+import org.junit.Assert.assertTrue
15
+import org.junit.Test
16
+import org.junit.runner.RunWith
17
+import org.robolectric.Robolectric
18
+import org.robolectric.RobolectricTestRunner
19
+import org.robolectric.Shadows.shadowOf
20
+import org.robolectric.annotation.Config
21
+
22
+@RunWith(RobolectricTestRunner::class)
23
+@Config(sdk = [35], manifest = Config.NONE)
24
+class ReviewDiffViewportTest {
25
+ @Test
26
+ fun resetDiscardsOldRowsAndPendingDecodeBeforePublishingTheNewDestination() {
27
+ val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
28
+ val appContext = AppContext()
29
+ val view = T3ReviewDiffView(activity, appContext)
30
+ val decoder = ManualDecoder()
31
+ view.javaClass.getDeclaredField("payloadDecodeExecutor").apply { isAccessible = true }
32
+ .set(view, decoder)
33
+ activity.setContentView(view)
34
+ val canvas = view.getChildAt(0)
35
+ val measure = View.MeasureSpec.makeMeasureSpec(320, View.MeasureSpec.EXACTLY)
36
+ canvas.measure(measure, measure)
37
+ canvas.layout(0, 0, 320, 320)
38
+ val bitmap = Bitmap.createBitmap(320, 320, Bitmap.Config.ARGB_8888)
39
+ try {
40
+ view.setInitialFileId("old-selected")
41
+ view.setRowsJson(rows("old-selected"))
42
+ decoder.completeNext()
43
+ canvas.draw(Canvas(bitmap))
44
+ assertEquals(900, ranges(appContext).first()["firstRowIndex"])
45
+ appContext.events.clear()
46
+
47
+ // This decode belongs to the old content, but completes after the reset.
48
+ view.setRowsJson(rows("old-selected"))
49
+ view.setContentResetKey("new-content")
50
+ view.setInitialFileId("new-selected")
51
+ canvas.draw(Canvas(bitmap))
52
+ assertTrue(
53
+ "reset must not publish the previous payload's top range",
54
+ ranges(appContext).isEmpty()
55
+ )
56
+ assertEquals(0, rowTop(canvas, 1))
57
+ decoder.completeNext()
58
+ canvas.draw(Canvas(bitmap))
59
+ assertTrue(
60
+ "a stale decode must not restore old rows or publish a range",
61
+ ranges(appContext).isEmpty()
62
+ )
63
+ assertEquals(0, rowTop(canvas, 1))
64
+
65
+ view.setRowsJson(rows("new-selected"))
66
+ decoder.completeNext()
67
+ canvas.draw(Canvas(bitmap))
68
+ assertEquals(1, ranges(appContext).size)
69
+ assertEquals(900, ranges(appContext).single()["firstRowIndex"])
70
+ assertEquals(1000, ranges(appContext).single()["totalRows"])
71
+ } finally {
72
+ view.cleanup()
73
+ bitmap.recycle()
74
+ activity.finish()
75
+ appContext.events.clear()
76
+ }
77
+ }
78
+
79
+ @Test
80
+ fun decodedRowsWaitForTheReplacementFilePropBeforePublishingAViewport() {
81
+ val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
82
+ val appContext = AppContext()
83
+ val view = T3ReviewDiffView(activity, appContext)
84
+ val decoder = ManualDecoder()
85
+ view.javaClass.getDeclaredField("payloadDecodeExecutor").apply { isAccessible = true }
86
+ .set(view, decoder)
87
+ activity.setContentView(view)
88
+ val canvas = view.getChildAt(0)
89
+ val measure = View.MeasureSpec.makeMeasureSpec(320, View.MeasureSpec.EXACTLY)
90
+ canvas.measure(measure, measure)
91
+ canvas.layout(0, 0, 320, 320)
92
+ try {
93
+ view.setInitialFileId("old-selected")
94
+ view.setRowsJson(rows("old-selected"))
95
+ decoder.completeNext()
96
+ appContext.events.clear()
97
+
98
+ view.setContentResetKey("new-content")
99
+ view.setRowsJson(rows("new-selected"))
100
+ decoder.completeNext()
101
+ // Other props can rebuild layout while the destination still names the old payload.
102
+ view.setCollapsedFileIdsJson("[]")
103
+ view.setStyleJson("{}")
104
+ view.setInitialRowIndex(-1.0)
105
+ assertTrue(
106
+ "decoded rows must wait for a resolvable destination",
107
+ ranges(appContext).isEmpty()
108
+ )
109
+
110
+ view.setInitialFileId("new-selected")
111
+ assertEquals(900, ranges(appContext).single()["firstRowIndex"])
112
+ assertEquals(1000, ranges(appContext).single()["totalRows"])
113
+ } finally {
114
+ view.cleanup()
115
+ activity.finish()
116
+ appContext.events.clear()
117
+ }
118
+ }
119
+
120
+ private fun rowTop(canvas: View, index: Int): Int = canvas.javaClass
121
+ .getDeclaredMethod("rowTop", Int::class.javaPrimitiveType).apply { isAccessible = true }
122
+ .invoke(canvas, index) as Int
123
+
124
+ private fun ranges(appContext: AppContext) = appContext.events
125
+ .filter { (name, payload) -> name == "onDebug" && payload["message"] == "visible-range" }
126
+ .map { it.second }
127
+
128
+ private fun rows(selectedFileId: String): String = JSONArray().apply {
129
+ for (index in 0 until 1000) {
130
+ put(
131
+ JSONObject().apply {
132
+ put("id", "$selectedFileId:$index")
133
+ put("kind", if (index == 0 || index == 900) "file" else "line")
134
+ put("fileId", if (index < 900) "first-file" else selectedFileId)
135
+ put("content", "const value = $index")
136
+ }
137
+ )
138
+ }
139
+ }.toString()
140
+
141
+ private class ManualDecoder : AbstractExecutorService() {
142
+ private val work = ArrayDeque<Runnable>()
143
+ override fun execute(command: Runnable) {
144
+ work.addLast(command)
145
+ }
146
+ fun completeNext() {
147
+ work.removeFirst().run()
148
+ shadowOf(Looper.getMainLooper()).idle()
149
+ }
150
+ override fun shutdown() = Unit
151
+ override fun shutdownNow(): MutableList<Runnable> = mutableListOf()
152
+ override fun isShutdown() = false
153
+ override fun isTerminated() = false
154
+ override fun awaitTermination(timeout: Long, unit: TimeUnit) = true
155
+ }
156
+}
apps/mobile/modules/t3-review-diff/tests/android/stubs/expo/modules/kotlin/AppContext.kt
new
+6
@@ -0,0 +1,6 @@
1
+package expo.modules.kotlin
2
+
3
+// Per-view event sink for the isolated JVM harness; no React Native bridge is loaded.
4
+class AppContext {
5
+ val events = mutableListOf<Pair<String, Map<String, Any>>>()
6
+}
apps/mobile/modules/t3-review-diff/tests/android/stubs/expo/modules/kotlin/viewevent/EventDispatcher.kt
new
+15
@@ -0,0 +1,15 @@
1
+package expo.modules.kotlin.viewevent
2
+
3
+import expo.modules.kotlin.views.ExpoView
4
+import kotlin.properties.ReadOnlyProperty
5
+import kotlin.reflect.KProperty
6
+
7
+@Suppress("FunctionName")
8
+fun ExpoView.EventDispatcher() = object : ReadOnlyProperty<ExpoView, (Map<String, Any>) -> Unit> {
9
+ override fun getValue(
10
+ thisRef: ExpoView,
11
+ property: KProperty<*>
12
+ ): (Map<String, Any>) -> Unit = { payload ->
13
+ thisRef.appContext.events.add(property.name to payload)
14
+ }
15
+}
apps/mobile/modules/t3-review-diff/tests/android/stubs/expo/modules/kotlin/views/ExpoView.kt
new
+7
@@ -0,0 +1,7 @@
1
+package expo.modules.kotlin.views
2
+
3
+import android.content.Context
4
+import android.widget.FrameLayout
5
+import expo.modules.kotlin.AppContext
6
+
7
+open class ExpoView(context: Context, val appContext: AppContext) : FrameLayout(context)
apps/mobile/modules/t3-review-diff/tests/ios/anchor.swift
new
+53
@@ -0,0 +1,53 @@
1
+// Exercise the real UIScrollView/geometry update path with a preceding large file.
2
+private extension T3ReviewDiffView {
3
+ func checkRowAnchoring() throws {
4
+ frame = CGRect(x: 0, y: 0, width: 390, height: 600)
5
+ layoutSubviews()
6
+ setContentInsetTop(80)
7
+ let fixture = ["highlights.c", "simd128.h"].flatMap { file in
8
+ [["kind": "file", "id": "\(file):header", "fileId": file]] + (0..<100).map { line in
9
+ ["kind": "line", "id": "\(file):line:\(line)", "fileId": file,
10
+ "content": String(repeating: "long native code ", count: line % 9 + 1)]
11
+ }
12
+ }
13
+ rows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: JSONSerialization.data(withJSONObject: fixture))
14
+ contentView.rows = rows
15
+ updateContentMetrics()
16
+ let index = 130
17
+ func position(_ intra: CGFloat) {
18
+ setVerticalContentOffset(contentView.frameForRow(at: index)!.minY + intra, animated: false)
19
+ }
20
+ func assertPosition(_ intra: CGFloat, _ reason: String) {
21
+ let frame = contentView.frameForRow(at: index)!
22
+ let top = scrollView.contentOffset.y + scrollView.contentInset.top
23
+ check(top >= frame.minY && top < frame.maxY, "\(reason): visible row/file changed across geometry update")
24
+ check(abs(top - frame.minY - intra) < 0.01, "\(reason): intra-row position changed")
25
+ check(contentView.verticalOffset == scrollView.contentOffset.y, "Viewport and UIScrollView must agree")
26
+ }
27
+ position(7)
28
+ isProgrammaticScrollActive = true
29
+ contentView.isVerticalScrollActive = true
30
+ setStyleJson("{\"wordWrap\":true}")
31
+ assertPosition(7, "wrap on")
32
+ check(!isProgrammaticScrollActive && !contentView.isVerticalScrollActive,
33
+ "Anchor restoration must finish an interrupted programmatic scroll")
34
+ setStyleJson("{\"wordWrap\":true,\"codeFontSize\":22}")
35
+ assertPosition(7, "font change")
36
+ frame.size.width = 280
37
+ layoutSubviews()
38
+ assertPosition(7, "wrapped width change")
39
+ position(contentView.frameForRow(at: index)!.height - 2)
40
+ setStyleJson("{\"wordWrap\":false,\"rowHeight\":24}")
41
+ let height = contentView.frameForRow(at: index)!.height
42
+ assertPosition(height - 1, "unwrap clamps inside shortened row")
43
+ setInitialFileId("simd128.h")
44
+ layoutSubviews()
45
+ check(abs(scrollView.contentOffset.y + scrollView.contentInset.top - contentView.fileHeaderOffset(forFileId: "simd128.h")!) < 0.01,
46
+ "Explicit initial-file navigation must win over geometry anchoring")
47
+ setContentResetKey("new-content")
48
+ setStyleJson("{\"wordWrap\":true}")
49
+ check(rows.isEmpty && scrollView.contentOffset.y == -80, "Reset must discard the old anchor")
50
+ print("Passed viewport row anchors for wrap, font, width, intra-row clamp, initial file, and reset")
51
+ }
52
+}
53
+try T3ReviewDiffView().checkRowAnchoring()
apps/mobile/modules/t3-review-diff/tests/ios/geometry.swift
new
+137
@@ -0,0 +1,137 @@
1
+// Geometry tests exercise the production content view without an Expo app or device.
2
+private extension ReviewDiffContentView {
3
+ func checkSparseGeometry(expectedNativeRows: Int) {
4
+ check(codeLayoutsByRowId.count == expectedNativeRows,
5
+ "Offscreen ASCII must not retain per-row layout objects or wrap-start arrays (retained \(codeLayoutsByRowId.count))")
6
+ }
7
+
8
+ func checkReferenceGeometry() {
9
+ let font = codeFont
10
+ let characterWidth = monospaceCharacterWidth(font: font)
11
+ let width = codeLayoutWidthLimit(font: font)
12
+ var offset: CGFloat = 0
13
+ var widths: [String: CGFloat] = [:]
14
+ for (index, row) in rows.enumerated() {
15
+ check(rowOffsets[index] == offset, "Wrapped offsets changed for \(row.id)")
16
+ var rowHeight = height(for: row)
17
+ if row.kind == "line", let width, let content = row.content {
18
+ let reference = ReviewDiffCodeLayout(text: content, font: font, width: width, characterWidth: characterWidth)
19
+ if rowHeight > 0 {
20
+ rowHeight = max(rowHeight, reference.firstLineHeight) + reference.extraHeight
21
+ }
22
+ widths[row.resolvedFileId] = max(widths[row.resolvedFileId] ?? 0, reference.usedWidth)
23
+ } else if row.kind == "hunk" {
24
+ widths[row.resolvedFileId] = max(widths[row.resolvedFileId] ?? 0, textWidth(row.text ?? "", font: hunkFont))
25
+ }
26
+ check(height(at: index) == rowHeight, "Row height changed for \(row.id)")
27
+ if rowHeight > 0 {
28
+ check(rowIndex(at: offset + rowHeight / 2) == index, "Hit testing must use the published wrapped offsets")
29
+ }
30
+ offset += rowHeight
31
+ }
32
+ check(contentHeight == offset, "Content height must include every row")
33
+ check(contentWidthsByFileId == widths.mapValues { ceil($0) + style.codePadding * 2 },
34
+ "The end of every unwrapped line must remain reachable")
35
+ }
36
+
37
+ func preparedOffsetAddress() -> UInt {
38
+ guard let geometry = preparedRowGeometry else { fatalError("Geometry was not prepared") }
39
+ return geometry.offsets.withUnsafeBufferPointer { UInt(bitPattern: $0.baseAddress) }
40
+ }
41
+
42
+ func checkPublishedOffsetAddress(_ address: UInt) {
43
+ check(rowOffsets.withUnsafeBufferPointer { UInt(bitPattern: $0.baseAddress) } == address,
44
+ "Publication must reuse the prepared offsets without rebuilding on the UI thread")
45
+ }
46
+
47
+ func checkCancellationInsideLoop() {
48
+ var checks = 0
49
+ let input = ReviewDiffRowGeometryInput(
50
+ configuration: geometryConfiguration, font: codeFont, hunkFont: hunkFont,
51
+ characterWidth: codeCharacterWidth, layoutWidth: codeLayoutWidthLimit(font: codeFont), cached: [:]
52
+ )
53
+ let geometry = Self.buildRowGeometry(
54
+ rows, input: input, isCancelled: {
55
+ checks += 1
56
+ return checks == 2
57
+ }
58
+ )
59
+ check(geometry == nil && checks == 2, "Obsolete work must abort at the next batch, before visiting every row")
60
+ }
61
+}
62
+
63
+private let geometryRows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: JSONSerialization.data(withJSONObject:
64
+ [["kind": "file", "id": "a:header", "fileId": "a"],
65
+ ["kind": "hunk", "id": "a:hunk:0", "fileId": "a", "text": "@@ context\twith tabs @@"]] + (0..<4096).map { index in
66
+ ["kind": "line", "id": "a:line:\(index)", "fileId": "a",
67
+ "content": String(repeating: "printable ASCII ", count: index % 30), "newLineNumber": index + 1]
68
+ } + [["kind": "line", "id": "a:unicode", "fileId": "a", "content": "漢字\t👨👩👧👦"],
69
+ ["kind": "comment", "id": "a:comment", "fileId": "a"],
70
+ ["kind": "file", "id": "b:header", "fileId": "b"],
71
+ ["kind": "line", "id": "b:line:0", "fileId": "b", "content": "e\u{301}\tمرحبا"]]
72
+))
73
+private let geometryView = ReviewDiffContentView(frame: CGRect(x: 0, y: 0, width: 390, height: 844))
74
+private func geometryStyle(wrap: Bool, fontSize: Int = 12, weight: String = "regular", rowHeight: Int = 24) throws -> ReviewDiffNativeStyle {
75
+ let payload = try JSONDecoder().decode(ReviewDiffNativeStylePayload.self, from: Data(
76
+ "{\"wordWrap\":\(wrap),\"codeFontSize\":\(fontSize),\"codeFontWeight\":\"\(weight)\",\"rowHeight\":\(rowHeight)}".utf8
77
+ ))
78
+ return ReviewDiffNativeStyle.resolve(payload)
79
+}
80
+geometryView.style = try geometryStyle(wrap: true)
81
+geometryView.viewportWidth = 390
82
+geometryView.rows = geometryRows
83
+geometryView.checkSparseGeometry(expectedNativeRows: 2)
84
+geometryView.checkReferenceGeometry()
85
+geometryView.checkCancellationInsideLoop()
86
+for width: CGFloat in [400, 280] {
87
+ geometryView.viewportWidth = width
88
+ geometryView.checkReferenceGeometry()
89
+}
90
+geometryView.collapsedFileIds = ["b"]
91
+geometryView.collapsedCommentIds = ["a:comment"]
92
+geometryView.checkReferenceGeometry()
93
+geometryView.style = try geometryStyle(wrap: true, fontSize: 28, weight: "bold", rowHeight: 8)
94
+geometryView.checkReferenceGeometry()
95
+geometryView.style = try geometryStyle(wrap: false)
96
+geometryView.checkReferenceGeometry()
97
+geometryView.collapsedFileIds = []
98
+geometryView.collapsedCommentIds = []
99
+geometryView.style = try geometryStyle(wrap: true)
100
+geometryView.checkReferenceGeometry()
101
+let originalHeight = geometryView.contentHeight
102
+geometryView.mergeTokensByRowId(["a:line:29": [ReviewDiffNativeToken(content: geometryRows[31].content ?? "", color: "#ff0000", fontStyle: 3)]])
103
+geometryView.selectedRowIds = ["a:line:29"]
104
+check(geometryView.contentHeight == originalHeight, "Tokens and selection must preserve geometry")
105
+
106
+// Configuration changes before publication must restart preparation from a fresh snapshot.
107
+private let geometryQueue = DispatchQueue(label: "review-diff.geometry-tests")
108
+geometryQueue.suspend()
109
+geometryView.prepareRows(geometryRows, on: geometryQueue, isCurrent: { true }, completion: {
110
+ let address = geometryView.preparedOffsetAddress()
111
+ geometryView.rows = geometryRows
112
+ geometryView.checkPublishedOffsetAddress(address)
113
+ geometryView.checkSparseGeometry(expectedNativeRows: 2)
114
+ geometryView.checkReferenceGeometry()
115
+ check(geometryView.style.codeFontSize == 28 && geometryView.viewportWidth == 400)
116
+
117
+ // A reset/new payload can cancel work before its worker is scheduled, without publishing it.
118
+ geometryQueue.suspend()
119
+ geometryView.prepareRows(geometryRows, on: geometryQueue, isCurrent: { true }, completion: {
120
+ check(false, "Cancelled geometry must never publish")
121
+ })
122
+ geometryView.rows = []
123
+ geometryQueue.resume()
124
+ geometryQueue.async {
125
+ DispatchQueue.main.async {
126
+ check(geometryView.rows.isEmpty && geometryView.contentHeight == 0, "Reset must remain empty after obsolete work drains")
127
+ print("Passed sparse geometry, reference heights/widths, font/wrap/collapse, hit testing, direct publication, and cancellation")
128
+ exit(0)
129
+ }
130
+ }
131
+})
132
+geometryView.style = try geometryStyle(wrap: true, fontSize: 28, weight: "bold", rowHeight: 8)
133
+geometryView.viewportWidth = 400
134
+geometryView.collapsedFileIds = ["b"]
135
+geometryView.collapsedCommentIds = ["a:comment"]
136
+geometryQueue.resume()
137
+dispatchMain()
apps/mobile/modules/t3-review-diff/tests/ios/main.swift
+1
-1
@@ -77,7 +77,7 @@ for text in ["\t\t\"extends\": \"@riptech/tsconfig/tsconfig.test.json\",", "漢
77
let unwrappedAscii = ReviewDiffCodeLayout(
78
text: "const value = 123;", font: font, width: ReviewDiffCodeLayout.unboundedWidth, characterWidth: characterWidth
79
)
80
-check(unwrappedAscii.starts == [0] && unwrappedAscii.usedWidth == 18 * characterWidth)
80
+check(Array(unwrappedAscii.starts) == [0] && unwrappedAscii.usedWidth == 18 * characterWidth)
81
82
let ascii = String(repeating: "const value = 123; ", count: 100)
83
let layout = ReviewDiffCodeLayout(text: ascii, font: font, width: 280, characterWidth: characterWidth)
apps/mobile/modules/t3-review-diff/tests/run-android.sh
new
+4
@@ -0,0 +1,4 @@
1
+#!/usr/bin/env bash
2
+set -euo pipefail
3
+tests_dir=$(cd "$(dirname "$0")" && pwd)
4
+"${GRADLE:-gradle}" --project-dir "$tests_dir/android" test "$@"
apps/mobile/modules/t3-review-diff/tests/run-ios.sh
+25
-1
@@ -5,8 +5,32 @@ sdk=$(xcrun --sdk macosx --show-sdk-path)
5
compiler=$(xcrun --find swiftc)
6
output=$(mktemp -d)
7
trap 'rm -rf "$output"' EXIT
8
+# Keep the real content view and helpers; the Expo bridge is not needed by this harness.
9
+python3 - "$module_dir" "$output/main.swift" <<'PYTHON'
10
+import sys
11
+from pathlib import Path
12
+module = Path(sys.argv[1])
13
+source = (module / "ios/T3ReviewDiffView.swift").read_text()
14
+source = source.replace("import ExpoModulesCore\n", "")
15
+stubs = """
16
+public final class AppContext {}
17
+open class ExpoView: UIView {
18
+ public required init(appContext: AppContext? = nil) { super.init(frame: .zero) }
19
+ @available(*, unavailable)
20
+ public required init?(coder: NSCoder) { fatalError("init(coder:) is unused") }
21
+}
22
+final class EventDispatcher {
23
+ func callAsFunction(_ payload: [String: Any]) {}
24
+}
25
+"""
26
+# Expo alone is stubbed; keep the real scroll container as well as the content view.
27
+Path(sys.argv[2]).write_text(source + "\n" + stubs + "\n"
28
+ + (module / "tests/ios/main.swift").read_text() + "\n"
29
+ + (module / "tests/ios/anchor.swift").read_text() + "\n"
30
+ + (module / "tests/ios/geometry.swift").read_text())
31
+PYTHON
32
"$compiler" -O -target "$(uname -m)-apple-ios16.1-macabi" -sdk "$sdk" \
33
-F "$sdk/System/iOSSupport/System/Library/Frameworks" \
10
- "$module_dir/ios/ReviewDiffCodeLayout.swift" "$module_dir/tests/ios/main.swift" \
34
+ "$module_dir/ios/ReviewDiffCodeLayout.swift" "$output/main.swift" \
35
-o "$output/layout-tests"
36
"$output/layout-tests"
apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.test.ts
+583
-17
@@ -1,13 +1,36 @@
1
-import { describe, expect, it, vi } from "vite-plus/test";
1
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2
+
3
+import { highlightCode } from "../../lib/highlights";
4
5
import type { NativeReviewDiffRow } from "./nativeReviewDiffSurface";
6
import type { NativeReviewDiffFile } from "./nativeReviewDiffTypes";
7
import { highlightNativeReviewDiffVisibleRows } from "./nativeReviewDiffHighlighter";
8
+import { buildNativeReviewDiffData } from "../review/nativeReviewDiffAdapter";
9
+import { buildReviewParsedDiff } from "../review/reviewModel";
10
+
11
+const tokenization = vi.hoisted(() => ({
12
+ calls: [] as string[],
13
+ afterCall: undefined as (() => void) | undefined,
14
+}));
15
16
vi.mock("expo", async () => {
17
const { createWasmHighlightsModule } = await import("../../lib/highlights.testing");
9
- const highlights = createWasmHighlightsModule();
10
- return { requireOptionalNativeModule: () => highlights };
18
+ const module = createWasmHighlightsModule();
19
+ return {
20
+ requireOptionalNativeModule: () => ({
21
+ tokenize(code: string, language: number) {
22
+ tokenization.calls.push(code);
23
+ const records = module.tokenize(code, language);
24
+ tokenization.afterCall?.();
25
+ return records;
26
+ },
27
+ }),
28
+ };
29
+});
30
+
31
+afterEach(() => {
32
+ tokenization.calls = [];
33
+ tokenization.afterCall = undefined;
34
});
35
36
const TYPESCRIPT_FILE: NativeReviewDiffFile = {
@@ -54,7 +77,128 @@ function highlight(
77
}
78
79
describe("highlightNativeReviewDiffVisibleRows", () => {
57
- it("does not carry grammar state across hunk boundaries", () => {
80
+ it("keeps overscan within the visible files, including a file header at the viewport edge", async () => {
81
+ const loadedFiles: string[] = [];
82
+ const files = Array.from({ length: 14 }, (_, index) => {
83
+ const id = `file-${index}`;
84
+ const source = Array.from({ length: 3 }, (_, line) => `const value${line} = ${line};`);
85
+ return {
86
+ ...TYPESCRIPT_FILE,
87
+ id,
88
+ loadContents: async () => {
89
+ loadedFiles.push(id);
90
+ return { oldContents: "", newContents: source.join("\n") };
91
+ },
92
+ rows: [
93
+ { kind: "file", id: `${id}-header`, fileId: id },
94
+ ...source.map((content, line) => ({
95
+ ...makeLine({
96
+ id: `${id}-line-${line + 1}`,
97
+ content,
98
+ change: "add",
99
+ oldLineNumber: null,
100
+ newLineNumber: line + 1,
101
+ }),
102
+ fileId: id,
103
+ })),
104
+ ] satisfies NativeReviewDiffRow[],
105
+ };
106
+ });
107
+ const input = {
108
+ rows: files.flatMap((file) => file.rows),
109
+ files,
110
+ scheme: "dark" as const,
111
+ firstRowIndex: 30,
112
+ lastRowIndex: 32,
113
+ };
114
+ const viewport = await highlightNativeReviewDiffVisibleRows({ ...input, overscanRows: 0 });
115
+ const visibleIds = ["file-7-line-2", "file-7-line-3"];
116
+ expect(Object.keys(viewport.tokensByRowId)).toEqual(visibleIds);
117
+ const overscan = await highlightNativeReviewDiffVisibleRows({
118
+ ...input,
119
+ overscanRows: 160,
120
+ alreadyHighlightedRowIds: new Set(visibleIds),
121
+ });
122
+ expect(Object.keys(overscan.tokensByRowId).sort()).toEqual([
123
+ "file-7-line-1",
124
+ "file-8-line-1",
125
+ "file-8-line-2",
126
+ "file-8-line-3",
127
+ ]);
128
+ for (const tokens of Object.values({ ...viewport.tokensByRowId, ...overscan.tokensByRowId })) {
129
+ expect(tokens.some((token) => token.color !== null)).toBe(true);
130
+ }
131
+ expect([...new Set(loadedFiles)].sort()).toEqual(["file-7", "file-8"]);
132
+ });
133
+
134
+ it("delivers the dominant viewport file before fetching a smaller blocked neighbor", async () => {
135
+ const neighborStarted = Promise.withResolvers<void>();
136
+ const neighborResponse = Promise.withResolvers<{ oldContents: string; newContents: string }>();
137
+ const source = Array.from({ length: 27 }, (_, index) => `const value${index} = true;`).join(
138
+ "\n",
139
+ );
140
+ const chunks = vi.fn();
141
+ const rows = [
142
+ ...Array.from({ length: 5 }, (_, index) => ({
143
+ ...makeLine({
144
+ id: `neighbor-${index}`,
145
+ content: `const value${index} = true;`,
146
+ change: "add",
147
+ oldLineNumber: null,
148
+ newLineNumber: index + 1,
149
+ }),
150
+ fileId: "neighbor",
151
+ })),
152
+ ...Array.from({ length: 27 }, (_, index) =>
153
+ makeLine({
154
+ id: `selected-${index}`,
155
+ content: `const value${index} = true;`,
156
+ change: "delete",
157
+ oldLineNumber: index + 1,
158
+ newLineNumber: null,
159
+ }),
160
+ ),
161
+ ];
162
+ const highlighting = highlightNativeReviewDiffVisibleRows({
163
+ rows,
164
+ files: [
165
+ {
166
+ ...TYPESCRIPT_FILE,
167
+ id: "neighbor",
168
+ loadContents: () => {
169
+ neighborStarted.resolve();
170
+ return neighborResponse.promise;
171
+ },
172
+ },
173
+ {
174
+ ...TYPESCRIPT_FILE,
175
+ loadContents: async () => ({ oldContents: source, newContents: "" }),
176
+ },
177
+ ],
178
+ scheme: "dark",
179
+ firstRowIndex: 0,
180
+ lastRowIndex: rows.length - 1,
181
+ overscanRows: 0,
182
+ onChunk: chunks,
183
+ });
184
+ try {
185
+ await neighborStarted.promise;
186
+ expect(chunks).toHaveBeenCalledTimes(1);
187
+ expect(Object.keys(chunks.mock.calls[0]![0].tokensByRowId)).toEqual(
188
+ Array.from({ length: 27 }, (_, index) => `selected-${index}`),
189
+ );
190
+ expect(
191
+ chunks.mock.calls[0]![0].tokensByRowId["selected-0"].some(
192
+ (token: { color: string | null }) => token.color !== null,
193
+ ),
194
+ ).toBe(true);
195
+ } finally {
196
+ neighborResponse.resolve({ oldContents: "", newContents: source });
197
+ await highlighting;
198
+ }
199
+ });
200
+
201
+ it("does not carry grammar state across hunk boundaries", async () => {
202
const exportRow = makeLine({
203
id: "export-row",
204
content: "export async function run() {}",
@@ -65,23 +209,32 @@ describe("highlightNativeReviewDiffVisibleRows", () => {
209
const rows = [
210
makeHunk("hunk-1"),
211
makeLine({
68
- id: "template-open",
69
- content: "const message = `open",
212
+ id: "import-open",
213
+ content: "import {",
214
change: "context",
215
oldLineNumber: 1,
216
newLineNumber: 1,
217
}),
218
+ makeLine({
219
+ id: "import-entry",
220
+ content: " Model,",
221
+ change: "context",
222
+ oldLineNumber: 2,
223
+ newLineNumber: 2,
224
+ }),
225
makeHunk("hunk-2"),
226
exportRow,
227
];
228
78
- const highlighted = highlight(rows);
79
- const standalone = highlight([makeHunk("standalone-hunk"), exportRow]);
229
+ const [highlighted, standalone] = await Promise.all([
230
+ highlight(rows),
231
+ highlight([makeHunk("standalone-hunk"), exportRow]),
232
+ ]);
233
234
expect(highlighted.tokensByRowId[exportRow.id]).toEqual(standalone.tokensByRowId[exportRow.id]);
235
});
236
84
- it("keeps grammar state across inline comment rows", () => {
237
+ it("keeps grammar state across inline comment rows", async () => {
238
const openingRow = makeLine({
239
id: "template-open",
240
content: "const message = `open",
@@ -110,16 +263,15 @@ describe("highlightNativeReviewDiffVisibleRows", () => {
263
commentText: "Review note",
264
};
265
113
- const withComment = highlight([openingRow, commentRow, closingRow, trailingRow]);
114
- const contiguous = highlight([openingRow, closingRow, trailingRow]);
266
+ const [withComment, contiguous] = await Promise.all([
267
+ highlight([openingRow, commentRow, closingRow, trailingRow]),
268
+ highlight([openingRow, closingRow, trailingRow]),
269
+ ]);
270
271
expect(withComment.tokensByRowId).toEqual(contiguous.tokensByRowId);
117
- expect(withComment.tokensByRowId[closingRow.id]?.[0]?.color).toBe(
118
- withComment.tokensByRowId[openingRow.id]?.at(-1)?.color,
119
- );
272
});
273
122
- it("does not join unhighlighted rows across cached gaps", () => {
274
+ it("does not join unhighlighted rows across cached gaps", async () => {
275
const trailingRow = makeLine({
276
id: "trailing-row",
277
content: "export const answer = 42;",
@@ -145,11 +297,425 @@ describe("highlightNativeReviewDiffVisibleRows", () => {
297
trailingRow,
298
];
299
148
- const highlighted = highlight(rows, new Set(["template-close"]));
149
- const standalone = highlight([trailingRow]);
300
+ const [highlighted, standalone] = await Promise.all([
301
+ highlight(rows, new Set(["template-close"])),
302
+ highlight([trailingRow]),
303
+ ]);
304
305
expect(highlighted.tokensByRowId[trailingRow.id]).toEqual(
306
standalone.tokensByRowId[trailingRow.id],
307
);
308
});
309
});
310
+
311
+// These complete sources are independent of the diff row selection below.
312
+const OLD_SOURCE = [
313
+ "export function render(name: string) {",
314
+ " const heading = `Hello ${name}",
315
+ "Welcome to the archive.",
316
+ "Your saved reports follow.",
317
+ " `;",
318
+ " /* Historical formatting rules:",
319
+ " * Keep the title and summary together.",
320
+ " * Preserve links in the footer.",
321
+ " */",
322
+ " return heading.trim();",
323
+ "}",
324
+];
325
+const NEW_SOURCE = [
326
+ "export function render(name: string) {",
327
+ " const heading = `Greetings ${name}",
328
+ "Welcome to the workspace.",
329
+ "Your saved reports follow.",
330
+ " `;",
331
+ " /* Current formatting rules:",
332
+ " * Keep the title and summary together.",
333
+ " * Highlight links in the footer.",
334
+ " */",
335
+ " return heading.trim();",
336
+ "}",
337
+];
338
+
339
+function authoritativeTokens(source: ReadonlyArray<string>) {
340
+ return highlightCode(source.join("\n"), "typescript", "dark");
341
+}
342
+
343
+function sourceRow(change: "context" | "add" | "delete", lineNumber: number) {
344
+ return makeLine({
345
+ id: `${change}-${lineNumber}`,
346
+ content: (change === "delete" ? OLD_SOURCE : NEW_SOURCE)[lineNumber - 1]!,
347
+ change,
348
+ oldLineNumber: change === "add" ? null : lineNumber,
349
+ newLineNumber: change === "delete" ? null : lineNumber,
350
+ });
351
+}
352
+
353
+function completeDiffRows() {
354
+ return [
355
+ sourceRow("context", 1),
356
+ sourceRow("delete", 2),
357
+ sourceRow("delete", 3),
358
+ sourceRow("add", 2),
359
+ sourceRow("add", 3),
360
+ sourceRow("context", 4),
361
+ sourceRow("context", 5),
362
+ sourceRow("delete", 6),
363
+ sourceRow("add", 6),
364
+ sourceRow("context", 7),
365
+ sourceRow("delete", 8),
366
+ sourceRow("add", 8),
367
+ sourceRow("context", 9),
368
+ sourceRow("context", 10),
369
+ sourceRow("context", 11),
370
+ ];
371
+}
372
+
373
+describe("source context", () => {
374
+ it("highlights parsed CRLF patch rows using omitted full-source templates and comments", async () => {
375
+ const newSource = [...OLD_SOURCE];
376
+ newSource[2] = NEW_SOURCE[2]!;
377
+ newSource[7] = NEW_SOURCE[7]!;
378
+ const parsed = buildReviewParsedDiff(
379
+ [
380
+ "diff --git a/example.ts b/example.ts",
381
+ "--- a/example.ts",
382
+ "+++ b/example.ts",
383
+ "@@ -3,2 +3,2 @@",
384
+ `-${OLD_SOURCE[2]}\r`,
385
+ `+${newSource[2]}\r`,
386
+ ` ${newSource[3]}\r`,
387
+ "@@ -7,3 +7,3 @@",
388
+ ` ${newSource[6]}\r`,
389
+ `-${OLD_SOURCE[7]}\r`,
390
+ `+${newSource[7]}\r`,
391
+ ` ${newSource[8]}\r`,
392
+ "",
393
+ ].join("\n"),
394
+ "crlf-context",
395
+ );
396
+ expect(parsed.kind).toBe("files");
397
+ const { rows, files } = buildNativeReviewDiffData(parsed);
398
+ const lineRows = rows.filter((row) => row.kind === "line");
399
+ expect(lineRows).toHaveLength(7);
400
+ const originalContents = lineRows.map((row) => row.content);
401
+ expect(originalContents.every((content) => content?.endsWith("\r"))).toBe(true);
402
+ const oldTokens = await authoritativeTokens(OLD_SOURCE);
403
+ const newTokens = await authoritativeTokens(newSource);
404
+ const result = await highlightNativeReviewDiffVisibleRows({
405
+ rows,
406
+ files: files.map((file) => ({
407
+ ...file,
408
+ loadContents: async () => ({
409
+ oldContents: `${OLD_SOURCE.join("\r\n")}\r\n`,
410
+ newContents: `${newSource.join("\r\n")}\r\n`,
411
+ }),
412
+ })),
413
+ scheme: "dark",
414
+ firstRowIndex: 0,
415
+ lastRowIndex: rows.length - 1,
416
+ overscanRows: 0,
417
+ });
418
+ for (const row of lineRows) {
419
+ const expected =
420
+ row.change === "delete"
421
+ ? oldTokens[row.oldLineNumber! - 1]
422
+ : newTokens[row.newLineNumber! - 1];
423
+ const tokens = result.tokensByRowId[row.id];
424
+ expect(tokens, row.id).toEqual(expected);
425
+ expect(
426
+ tokens?.every((token) => token.color !== null),
427
+ row.id,
428
+ ).toBe(true);
429
+ expect(tokens?.[0]?.color, row.id).toBe(
430
+ (row.newLineNumber ?? row.oldLineNumber)! <= 4 ? "#5ecc71" : "#737373",
431
+ );
432
+ }
433
+ expect(lineRows.map((row) => row.content)).toEqual(originalContents);
434
+ expect(result.retryableRowIds).toEqual([]);
435
+ });
436
+
437
+ it("matches full OLD/NEW source across replacement runs and shared multiline context", async () => {
438
+ const rows = completeDiffRows();
439
+ const oldTokens = await authoritativeTokens(OLD_SOURCE);
440
+ const newTokens = await authoritativeTokens(NEW_SOURCE);
441
+ const result = await highlightNativeReviewDiffVisibleRows({
442
+ rows,
443
+ files: [TYPESCRIPT_FILE],
444
+ scheme: "dark",
445
+ firstRowIndex: 0,
446
+ lastRowIndex: rows.length - 1,
447
+ overscanRows: 0,
448
+ });
449
+ for (const row of rows) {
450
+ const expected =
451
+ row.change === "delete"
452
+ ? oldTokens[row.oldLineNumber! - 1]
453
+ : newTokens[row.newLineNumber! - 1];
454
+ expect(result.tokensByRowId[row.id], row.id).toEqual(expected);
455
+ }
456
+ });
457
+
458
+ it("uses NEW grammar for shared rows when OLD remains inside a comment", async () => {
459
+ const oldSource = ["/* Retired renderer", "const value = 3;", "finish();"];
460
+ const newSource = ["// Active renderer", "const value = 3;", "finish();"];
461
+ const rows = [
462
+ makeLine({
463
+ id: "old-open",
464
+ content: oldSource[0],
465
+ change: "delete",
466
+ oldLineNumber: 1,
467
+ newLineNumber: null,
468
+ }),
469
+ makeLine({
470
+ id: "new-open",
471
+ content: newSource[0],
472
+ change: "add",
473
+ oldLineNumber: null,
474
+ newLineNumber: 1,
475
+ }),
476
+ makeLine({
477
+ id: "shared",
478
+ content: newSource[1],
479
+ change: "context",
480
+ oldLineNumber: 2,
481
+ newLineNumber: 2,
482
+ }),
483
+ makeLine({
484
+ id: "old-tail",
485
+ content: oldSource[2],
486
+ change: "delete",
487
+ oldLineNumber: 3,
488
+ newLineNumber: null,
489
+ }),
490
+ makeLine({
491
+ id: "new-tail",
492
+ content: newSource[2],
493
+ change: "add",
494
+ oldLineNumber: null,
495
+ newLineNumber: 3,
496
+ }),
497
+ ];
498
+ const oldTokens = await authoritativeTokens(oldSource);
499
+ const newTokens = await authoritativeTokens(newSource);
500
+ const result = await highlightNativeReviewDiffVisibleRows({
501
+ rows,
502
+ files: [TYPESCRIPT_FILE],
503
+ scheme: "dark",
504
+ firstRowIndex: 0,
505
+ lastRowIndex: rows.length - 1,
506
+ overscanRows: 0,
507
+ });
508
+ expect(oldTokens[1]).not.toEqual(newTokens[1]);
509
+ expect(result.tokensByRowId.shared).toEqual(newTokens[1]);
510
+ expect(result.tokensByRowId["old-tail"]).toEqual(oldTokens[2]);
511
+ expect(result.tokensByRowId["new-tail"]).toEqual(newTokens[2]);
512
+ });
513
+
514
+ it("leaves mismatched and unavailable source revisions plain", async () => {
515
+ const rows = [sourceRow("add", 3)];
516
+ for (const source of [null, { oldContents: "", newContents: "different revision" }]) {
517
+ const result = await highlightNativeReviewDiffVisibleRows({
518
+ rows,
519
+ files: [{ ...TYPESCRIPT_FILE, loadContents: async () => source }],
520
+ scheme: "dark",
521
+ firstRowIndex: 0,
522
+ lastRowIndex: 0,
523
+ overscanRows: 0,
524
+ });
525
+ expect(result.tokensByRowId[rows[0]!.id]).toEqual([
526
+ { content: NEW_SOURCE[2], color: null, fontStyle: null },
527
+ ]);
528
+ }
529
+ });
530
+});
531
+
532
+it("reuses full native records across viewport and theme changes and evicts old entries", async () => {
533
+ const sources = Array.from({ length: 9 }, (_, i) => ({
534
+ oldContents: "",
535
+ newContents: `/* ${i}\ninside\n*/\nconst tail = 2;`,
536
+ }));
537
+ const rows = [
538
+ makeLine({
539
+ id: "body",
540
+ content: "inside",
541
+ change: "add",
542
+ oldLineNumber: null,
543
+ newLineNumber: 2,
544
+ }),
545
+ makeLine({
546
+ id: "tail",
547
+ content: "const tail = 2;",
548
+ change: "add",
549
+ oldLineNumber: null,
550
+ newLineNumber: 4,
551
+ }),
552
+ ];
553
+ const input = {
554
+ rows,
555
+ scheme: "dark" as const,
556
+ firstRowIndex: 0,
557
+ lastRowIndex: 0,
558
+ overscanRows: 0,
559
+ };
560
+ const files = [{ ...TYPESCRIPT_FILE, loadContents: async () => sources[0]! }];
561
+ const initial = await highlightNativeReviewDiffVisibleRows({ ...input, files });
562
+ const moved = await highlightNativeReviewDiffVisibleRows({
563
+ ...input,
564
+ files,
565
+ firstRowIndex: 1,
566
+ lastRowIndex: 1,
567
+ });
568
+ await highlightNativeReviewDiffVisibleRows({ ...input, files, scheme: "light" });
569
+ expect(tokenization.calls).toEqual([sources[0]!.newContents]);
570
+ expect(initial.tokensByRowId.body).toEqual(
571
+ highlightCode(sources[0]!.newContents, "typescript", "dark")[1],
572
+ );
573
+ expect(moved.tokensByRowId.tail).toEqual(
574
+ highlightCode(sources[0]!.newContents, "typescript", "dark")[3],
575
+ );
576
+ tokenization.calls = [];
577
+ for (const source of sources.slice(1)) {
578
+ await highlightNativeReviewDiffVisibleRows({
579
+ ...input,
580
+ files: [{ ...TYPESCRIPT_FILE, loadContents: async () => source }],
581
+ });
582
+ }
583
+ await highlightNativeReviewDiffVisibleRows({ ...input, files });
584
+ expect(tokenization.calls).toHaveLength(9);
585
+ expect(tokenization.calls.at(-1)).toBe(sources[0]!.newContents);
586
+});
587
+
588
+it("reuses segment records across themes and replaces records when the language changes", async () => {
589
+ const rows = [
590
+ makeLine({
591
+ id: "line",
592
+ content: "const value = 1;",
593
+ change: "add",
594
+ oldLineNumber: null,
595
+ newLineNumber: 1,
596
+ }),
597
+ ];
598
+ const input = {
599
+ rows,
600
+ files: [TYPESCRIPT_FILE],
601
+ scheme: "dark" as const,
602
+ firstRowIndex: 0,
603
+ lastRowIndex: 0,
604
+ overscanRows: 0,
605
+ };
606
+ const first = await highlightNativeReviewDiffVisibleRows(input);
607
+ await highlightNativeReviewDiffVisibleRows({ ...input, scheme: "light" });
608
+ expect(tokenization.calls).toEqual([rows[0]!.content]);
609
+ await highlightNativeReviewDiffVisibleRows({
610
+ ...input,
611
+ files: [{ ...TYPESCRIPT_FILE, language: "c" }],
612
+ });
613
+ const restored = await highlightNativeReviewDiffVisibleRows(input);
614
+ expect(tokenization.calls).toHaveLength(3);
615
+ expect(restored.tokensByRowId).toEqual(first.tokensByRowId);
616
+});
617
+
618
+it("uses full grammar after an oversized line and expands only selected rows in a 100k-line C source", async () => {
619
+ const contents = [
620
+ " ".repeat(1_001) + "/*",
621
+ ...Array.from({ length: 99_997 }, (_, i) => `comment ${i}: int value = 1;`),
622
+ "*/",
623
+ "int done = 2;",
624
+ ].join("\n");
625
+ expect(contents.length).toBeGreaterThan(500_000);
626
+ const source = { oldContents: "", newContents: contents };
627
+ const rows = [
628
+ makeLine({
629
+ id: "body",
630
+ content: "comment 99996: int value = 1;",
631
+ change: "add",
632
+ oldLineNumber: null,
633
+ newLineNumber: 99_998,
634
+ }),
635
+ makeLine({
636
+ id: "end",
637
+ content: "int done = 2;",
638
+ change: "add",
639
+ oldLineNumber: null,
640
+ newLineNumber: 100_000,
641
+ }),
642
+ ];
643
+ const input = {
644
+ rows,
645
+ files: [{ ...TYPESCRIPT_FILE, language: "c", loadContents: async () => source }],
646
+ scheme: "dark" as const,
647
+ firstRowIndex: 0,
648
+ lastRowIndex: 0,
649
+ overscanRows: 0,
650
+ };
651
+ const result = await highlightNativeReviewDiffVisibleRows(input);
652
+ expect(Object.keys(result.tokensByRowId)).toEqual(["body"]);
653
+ expect(result.tokensByRowId.body).toEqual([
654
+ { content: rows[0]!.content, color: "#737373", fontStyle: 0 },
655
+ ]);
656
+ const moved = await highlightNativeReviewDiffVisibleRows({
657
+ ...input,
658
+ firstRowIndex: 1,
659
+ lastRowIndex: 1,
660
+ });
661
+ expect(moved.tokensByRowId.end?.some((token) => token.color !== "#737373")).toBe(true);
662
+ expect(tokenization.calls).toEqual([contents]);
663
+});
664
+
665
+it("publishes no cancelled file chunk and never tokenizes its next side", async () => {
666
+ const controller = new AbortController();
667
+ tokenization.afterCall = () => controller.abort();
668
+ const chunks = vi.fn();
669
+ const result = await highlightNativeReviewDiffVisibleRows({
670
+ rows: [sourceRow("delete", 3), sourceRow("add", 3)],
671
+ files: [
672
+ {
673
+ ...TYPESCRIPT_FILE,
674
+ loadContents: async () => ({
675
+ oldContents: OLD_SOURCE.join("\n"),
676
+ newContents: NEW_SOURCE.join("\n"),
677
+ }),
678
+ },
679
+ ],
680
+ scheme: "dark",
681
+ firstRowIndex: 0,
682
+ lastRowIndex: 1,
683
+ overscanRows: 0,
684
+ signal: controller.signal,
685
+ onChunk: chunks,
686
+ });
687
+ expect(tokenization.calls).toHaveLength(1);
688
+ expect(chunks).not.toHaveBeenCalled();
689
+ expect(result.tokensByRowId).toEqual({});
690
+ expect(result.rowCount).toBe(0);
691
+});
692
+
693
+it("does not tokenize or publish a source that arrives after cancellation", async () => {
694
+ const controller = new AbortController();
695
+ const started = Promise.withResolvers<void>();
696
+ const response = Promise.withResolvers<{ oldContents: string; newContents: string }>();
697
+ const chunks = vi.fn();
698
+ const work = highlightNativeReviewDiffVisibleRows({
699
+ rows: [sourceRow("add", 3)],
700
+ files: [
701
+ {
702
+ ...TYPESCRIPT_FILE,
703
+ loadContents: () => {
704
+ started.resolve();
705
+ return response.promise;
706
+ },
707
+ },
708
+ ],
709
+ scheme: "dark",
710
+ firstRowIndex: 0,
711
+ lastRowIndex: 0,
712
+ signal: controller.signal,
713
+ onChunk: chunks,
714
+ });
715
+ await started.promise;
716
+ controller.abort();
717
+ response.resolve({ oldContents: "", newContents: NEW_SOURCE.join("\n") });
718
+ expect((await work).rowCount).toBe(0);
719
+ expect(tokenization.calls).toEqual([]);
720
+ expect(chunks).not.toHaveBeenCalled();
721
+});
apps/mobile/src/features/diffs/nativeReviewDiffHighlighter.ts
+383
-68
@@ -1,6 +1,7 @@
1
-import { highlightCode, type HighlightScheme } from "../../lib/highlights";
2
-import type { NativeReviewDiffFile } from "./nativeReviewDiffTypes";
1
+import { tokenizeCode, type HighlightScheme, type TokenizedCode } from "../../lib/highlights";
2
+import type { NativeReviewDiffFile, NativeReviewDiffSource } from "./nativeReviewDiffTypes";
3
import type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewDiffSurface";
4
+import { diffHighlightTraceId, traceDiffHighlight } from "./nativeReviewDiffTrace";
5
6
interface NativeReviewDiffLineRow extends NativeReviewDiffRow {
7
readonly kind: "line";
@@ -8,11 +9,6 @@ interface NativeReviewDiffLineRow extends NativeReviewDiffRow {
9
readonly content: string;
10
}
11
11
-interface IndexedNativeReviewDiffLineRow {
12
- readonly row: NativeReviewDiffLineRow;
13
- readonly rowIndex: number;
14
-}
15
-
12
export interface HighlightNativeReviewDiffVisibleRowsInput {
13
readonly rows: ReadonlyArray<NativeReviewDiffRow>;
14
readonly files: ReadonlyArray<NativeReviewDiffFile>;
@@ -22,12 +18,19 @@ export interface HighlightNativeReviewDiffVisibleRowsInput {
18
readonly overscanRows?: number;
19
readonly maxRows?: number;
20
readonly alreadyHighlightedRowIds?: ReadonlySet<string>;
21
+ readonly signal?: AbortSignal;
22
+ readonly onChunk?: (chunk: NativeReviewDiffHighlightChunk) => void;
23
+}
24
+
25
+export interface NativeReviewDiffHighlightChunk {
26
+ readonly tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>>;
27
+ readonly retryableRowIds: ReadonlyArray<string>;
28
+ readonly rowCount: number;
29
+ readonly durationMs: number;
30
}
31
27
-// Bounds each token patch the native view parses, not the highlighting itself.
32
const NATIVE_REVIEW_DIFF_VISIBLE_OVERSCAN_ROWS = 160;
33
const NATIVE_REVIEW_DIFF_VISIBLE_MAX_ROWS = 360;
30
-
34
function isHighlightableLineRow(row: NativeReviewDiffRow): row is NativeReviewDiffLineRow {
35
return row.kind === "line" && typeof row.fileId === "string" && typeof row.content === "string";
36
}
@@ -39,49 +42,186 @@ function hasConsecutiveLineNumbers(
42
return typeof previous === "number" && typeof next === "number" && next === previous + 1;
43
}
44
42
-function hasOnlyCommentRowsBetween(
43
- rows: ReadonlyArray<NativeReviewDiffRow>,
44
- previousRowIndex: number,
45
- nextRowIndex: number,
46
-): boolean {
47
- for (let rowIndex = previousRowIndex + 1; rowIndex < nextRowIndex; rowIndex += 1) {
48
- if (rows[rowIndex]?.kind !== "comment") {
49
- return false;
45
+// Native lexing is non-incremental. Cache theme-independent raw records, never
46
+// expanded token objects for an entire large file. Bound both entry count and bytes.
47
+const MAX_TOKEN_CACHE_BYTES = 64 * 1024 * 1024;
48
+const MAX_TOKEN_CACHE_ENTRIES = 8;
49
+// LRU entries own only token data; source contexts and diff rows can collect independently.
50
+const tokenCacheKeys = new WeakMap<object, object>();
51
+const tokenCache = new Map<object, { language: string; tokens: TokenizedCode }>();
52
+let tokenCacheBytes = 0;
53
+
54
+function getTokenCacheKey(context: object): object {
55
+ let key = tokenCacheKeys.get(context);
56
+ if (!key) {
57
+ key = {};
58
+ tokenCacheKeys.set(context, key);
59
+ }
60
+ return key;
61
+}
62
+
63
+function getCachedTokens(
64
+ cacheKey: object,
65
+ contents: string | (() => string),
66
+ language: string,
67
+): TokenizedCode {
68
+ const cached = tokenCache.get(cacheKey);
69
+ if (cached) {
70
+ tokenCache.delete(cacheKey);
71
+ tokenCacheBytes -= cached.tokens.byteLength;
72
+ if (cached.language === language) {
73
+ tokenCache.set(cacheKey, cached);
74
+ tokenCacheBytes += cached.tokens.byteLength;
75
+ return cached.tokens;
76
}
77
}
52
- return true;
78
+ const tokens = tokenizeCode(typeof contents === "string" ? contents : contents(), language);
79
+ if (tokens.byteLength <= MAX_TOKEN_CACHE_BYTES) {
80
+ tokenCache.set(cacheKey, { language, tokens });
81
+ tokenCacheBytes += tokens.byteLength;
82
+ }
83
+ while (tokenCacheBytes > MAX_TOKEN_CACHE_BYTES || tokenCache.size > MAX_TOKEN_CACHE_ENTRIES) {
84
+ const oldest = tokenCache.keys().next().value!;
85
+ tokenCacheBytes -= tokenCache.get(oldest)!.tokens.byteLength;
86
+ tokenCache.delete(oldest);
87
+ }
88
+ return tokens;
89
}
90
55
-function canShareGrammarContext(
56
- previous: IndexedNativeReviewDiffLineRow,
57
- next: IndexedNativeReviewDiffLineRow,
58
- rows: ReadonlyArray<NativeReviewDiffRow>,
59
-): boolean {
60
- if (
61
- next.row.fileId !== previous.row.fileId ||
62
- !hasOnlyCommentRowsBetween(rows, previous.rowIndex, next.rowIndex)
63
- ) {
64
- return false;
91
+const fullSourceContexts = new WeakMap<
92
+ NativeReviewDiffSource,
93
+ { old: FullSourceContext; new: FullSourceContext }
94
+>();
95
+
96
+interface FullSourceContext {
97
+ readonly contents: string;
98
+ readonly comparisonLines: ReadonlyArray<string>;
99
+ readonly validation: WeakMap<ReadonlyArray<NativeReviewDiffLineRow>, boolean>;
100
+}
101
+
102
+const sourceRowsByFileCache = new WeakMap<
103
+ ReadonlyArray<NativeReviewDiffRow>,
104
+ Map<string, NativeReviewDiffLineRow[]>
105
+>();
106
+
107
+function getSourceRowsByFile(rows: ReadonlyArray<NativeReviewDiffRow>) {
108
+ let byFile = sourceRowsByFileCache.get(rows);
109
+ if (!byFile) {
110
+ byFile = new Map();
111
+ for (const row of rows) {
112
+ if (!isHighlightableLineRow(row)) continue;
113
+ const fileRows = byFile.get(row.fileId);
114
+ if (fileRows) fileRows.push(row);
115
+ else byFile.set(row.fileId, [row]);
116
+ }
117
+ sourceRowsByFileCache.set(rows, byFile);
118
}
119
+ return byFile;
120
+}
121
67
- if (previous.row.change === "delete" || next.row.change === "delete") {
122
+function matchesSourceSide(
123
+ context: FullSourceContext,
124
+ rows: ReadonlyArray<NativeReviewDiffLineRow>,
125
+ side: DiffSide,
126
+) {
127
+ const cached = context.validation.get(rows);
128
+ if (cached !== undefined) return cached;
129
+ // Context participates on both sides, even though it displays NEW tokens.
130
+ // A known mismatch anywhere invalidates grammar from the entire source side.
131
+ const matches = rows.every((row) => {
132
+ if (row.change === (side === "old" ? "add" : "delete")) return true;
133
+ const lineNumber = side === "old" ? row.oldLineNumber : row.newLineNumber;
134
return (
69
- previous.row.change !== "add" &&
70
- next.row.change !== "add" &&
71
- hasConsecutiveLineNumbers(previous.row.oldLineNumber, next.row.oldLineNumber)
135
+ typeof lineNumber === "number" && context.comparisonLines[lineNumber - 1] === row.content
136
);
137
+ });
138
+ context.validation.set(rows, matches);
139
+ return matches;
140
+}
141
+
142
+function createFullSourceContext(contents: string): FullSourceContext {
143
+ return {
144
+ contents,
145
+ // The diff parser retains CR on patch rows, unlike the token output.
146
+ comparisonLines: contents.split("\n"),
147
+ validation: new WeakMap(),
148
+ };
149
+}
150
+
151
+function getFullSourceContexts(source: NativeReviewDiffSource) {
152
+ let contexts = fullSourceContexts.get(source);
153
+ if (!contexts) {
154
+ contexts = {
155
+ old: createFullSourceContext(source.oldContents),
156
+ new: createFullSourceContext(source.newContents),
157
+ };
158
+ fullSourceContexts.set(source, contexts);
159
}
160
+ return contexts;
161
+}
162
+
163
+type DiffSide = "old" | "new";
164
75
- if (previous.row.change === "add" || next.row.change === "add") {
76
- return hasConsecutiveLineNumbers(previous.row.newLineNumber, next.row.newLineNumber);
165
+interface SourceSegment {
166
+ readonly fileId: string;
167
+ readonly side: DiffSide;
168
+ readonly rows: NativeReviewDiffLineRow[];
169
+}
170
+
171
+// Row arrays are immutable snapshots; comments and hidden hunks retain source context.
172
+const sourceSegmentsCache = new WeakMap<
173
+ ReadonlyArray<NativeReviewDiffRow>,
174
+ Map<string, { readonly segment: SourceSegment; readonly index: number }>
175
+>();
176
+
177
+function getSourceSegments(rows: ReadonlyArray<NativeReviewDiffRow>) {
178
+ const cached = sourceSegmentsCache.get(rows);
179
+ if (cached) return cached;
180
+
181
+ const segmentsByRowId = new Map<
182
+ string,
183
+ { readonly segment: SourceSegment; readonly index: number }
184
+ >();
185
+ for (const side of ["old", "new"] as const) {
186
+ let segment: SourceSegment | undefined;
187
+ for (const row of rows) {
188
+ if (row.kind === "comment" || row.kind === "hunk") continue;
189
+ if (!isHighlightableLineRow(row)) {
190
+ segment = undefined;
191
+ continue;
192
+ }
193
+ if (row.change === (side === "old" ? "add" : "delete")) continue;
194
+
195
+ const previous = segment?.rows.at(-1);
196
+ const lineNumber = side === "old" ? row.oldLineNumber : row.newLineNumber;
197
+ const previousLineNumber = side === "old" ? previous?.oldLineNumber : previous?.newLineNumber;
198
+ if (
199
+ !segment ||
200
+ segment.fileId !== row.fileId ||
201
+ !hasConsecutiveLineNumbers(previousLineNumber, lineNumber)
202
+ ) {
203
+ // A gap has no known incoming grammar state. Highlight the available
204
+ // fragment independently; never join it to an earlier, incomplete hunk.
205
+ segment = { fileId: row.fileId, side, rows: [] };
206
+ }
207
+ if (displaySide(row) === side) {
208
+ segmentsByRowId.set(row.id, { segment, index: segment.rows.length });
209
+ }
210
+ segment.rows.push(row);
211
+ }
212
}
213
+ sourceSegmentsCache.set(rows, segmentsByRowId);
214
+ return segmentsByRowId;
215
+}
216
79
- return (
80
- previous.row.change === "context" &&
81
- next.row.change === "context" &&
82
- hasConsecutiveLineNumbers(previous.row.oldLineNumber, next.row.oldLineNumber) &&
83
- hasConsecutiveLineNumbers(previous.row.newLineNumber, next.row.newLineNumber)
84
- );
217
+function displaySide(row: NativeReviewDiffLineRow): DiffSide {
218
+ // Unified context rows have one token array. Match the NEW side, while OLD
219
+ // context still advances deletion grammar independently.
220
+ return row.change === "delete" ? "old" : "new";
221
+}
222
+
223
+function createFileMap(files: ReadonlyArray<NativeReviewDiffFile>) {
224
+ return new Map(files.map((file) => [file.id, file]));
225
}
226
227
function clampRowIndex(index: number, rows: ReadonlyArray<NativeReviewDiffRow>) {
@@ -92,18 +232,53 @@ function clampRowIndex(index: number, rows: ReadonlyArray<NativeReviewDiffRow>)
232
return Math.min(rows.length - 1, Math.max(0, Math.floor(index)));
233
}
234
95
-export function highlightNativeReviewDiffVisibleRows(
235
+function makePlainTokenFallback(
236
+ row: NativeReviewDiffLineRow,
237
+): ReadonlyArray<NativeReviewDiffToken> {
238
+ return [{ content: row.content || " ", color: null, fontStyle: null }];
239
+}
240
+
241
+export async function highlightNativeReviewDiffVisibleRows(
242
input: HighlightNativeReviewDiffVisibleRowsInput,
97
-): {
243
+): Promise<{
244
readonly tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>>;
245
+ // Deliver plain tokens for these rows without marking them permanently highlighted.
246
+ readonly retryableRowIds: ReadonlyArray<string>;
247
readonly rowCount: number;
100
-} {
101
- const fileMap = new Map(input.files.map((file) => [file.id, file]));
248
+ readonly durationMs: number;
249
+}> {
250
+ const request = diffHighlightTraceId(input);
251
+ traceDiffHighlight("highlight-start", {
252
+ request,
253
+ first: input.firstRowIndex,
254
+ last: input.lastRowIndex,
255
+ overscan: input.overscanRows ?? NATIVE_REVIEW_DIFF_VISIBLE_OVERSCAN_ROWS,
256
+ });
257
+ if (input.signal?.aborted) {
258
+ return {
259
+ tokensByRowId: {},
260
+ retryableRowIds: [],
261
+ rowCount: 0,
262
+ durationMs: 0,
263
+ };
264
+ }
265
+
266
+ const startedAt = performance.now();
267
+ const fileMap = createFileMap(input.files);
268
const overscanRows = input.overscanRows ?? NATIVE_REVIEW_DIFF_VISIBLE_OVERSCAN_ROWS;
269
const maxRows = input.maxRows ?? NATIVE_REVIEW_DIFF_VISIBLE_MAX_ROWS;
270
const startIndex = clampRowIndex(input.firstRowIndex - overscanRows, input.rows);
271
const endIndex = clampRowIndex(input.lastRowIndex + overscanRows, input.rows);
106
- const selectedRows: IndexedNativeReviewDiffLineRow[] = [];
272
+ const visibleStartIndex = clampRowIndex(input.firstRowIndex, input.rows);
273
+ const visibleEndIndex = clampRowIndex(input.lastRowIndex, input.rows);
274
+ const visibleFileIds = new Set<string>();
275
+ // Overscan warms visible files without loading unrelated neighboring sources.
276
+ // Headers and already-highlighted rows still identify files in the viewport.
277
+ for (let rowIndex = visibleStartIndex; rowIndex <= visibleEndIndex; rowIndex += 1) {
278
+ const fileId = input.rows[rowIndex]?.fileId;
279
+ if (typeof fileId === "string") visibleFileIds.add(fileId);
280
+ }
281
+ const selectedRows: NativeReviewDiffLineRow[] = [];
282
283
for (
284
let rowIndex = startIndex;
@@ -114,40 +289,180 @@ export function highlightNativeReviewDiffVisibleRows(
289
if (
290
row &&
291
isHighlightableLineRow(row) &&
292
+ visibleFileIds.has(row.fileId) &&
293
!input.alreadyHighlightedRowIds?.has(row.id) &&
294
fileMap.has(row.fileId)
295
) {
120
- selectedRows.push({ row, rowIndex });
296
+ selectedRows.push(row);
297
}
298
}
299
124
- // Rows that continue each other's source are highlighted together so
125
- // multi-line constructs keep their colors.
300
const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
127
- let segment: IndexedNativeReviewDiffLineRow[] = [];
128
- const flushSegment = () => {
129
- const file = segment[0] ? fileMap.get(segment[0].row.fileId) : undefined;
130
- if (file) {
131
- const tokenLines = highlightCode(
132
- segment.map(({ row }) => row.content).join("\n"),
133
- file.language,
134
- input.scheme,
135
- );
136
- segment.forEach(({ row }, index) => {
137
- tokensByRowId[row.id] = tokenLines[index] ?? [];
301
+ const retryableRowIds: string[] = [];
302
+ const selectedRowIds = new Set(selectedRows.map((row) => row.id));
303
+ const tokenize = (context: object, contents: string | (() => string), language: string) => {
304
+ const cacheKey = getTokenCacheKey(context);
305
+ const cacheHit = tokenCache.get(cacheKey)?.language === language;
306
+ const cached = getCachedTokens(cacheKey, contents, language);
307
+ traceDiffHighlight("tokenized", {
308
+ request,
309
+ characters: typeof contents === "string" ? contents.length : undefined,
310
+ cacheHit,
311
+ retainedBytes: cached.byteLength,
312
+ lines: cached.lineCount,
313
+ aborted: input.signal?.aborted ?? false,
314
+ });
315
+ return cached;
316
+ };
317
+
318
+ const sourceFiles = new Map<string, NativeReviewDiffLineRow[]>();
319
+ for (const row of selectedRows) {
320
+ if (!fileMap.get(row.fileId)?.loadContents) continue;
321
+ const fileRows = sourceFiles.get(row.fileId);
322
+ if (fileRows) fileRows.push(row);
323
+ else sourceFiles.set(row.fileId, [row]);
324
+ }
325
+ const emitFileChunk = (fileRows: ReadonlyArray<NativeReviewDiffLineRow>) => {
326
+ if (!input.onChunk || input.signal?.aborted) return;
327
+ const rowIds = new Set(fileRows.map((row) => row.id));
328
+ input.onChunk({
329
+ tokensByRowId: Object.fromEntries(fileRows.map((row) => [row.id, tokensByRowId[row.id]!])),
330
+ retryableRowIds: retryableRowIds.filter((id) => rowIds.has(id)),
331
+ rowCount: fileRows.length,
332
+ durationMs: Math.round(performance.now() - startedAt),
333
+ });
334
+ };
335
+ // The file filling the viewport should not wait for a sliver of its neighbor.
336
+ for (const [fileId, fileRows] of [...sourceFiles].sort((a, b) => b[1].length - a[1].length)) {
337
+ if (input.signal?.aborted) break;
338
+ const file = fileMap.get(fileId)!;
339
+ const fileTraceId = diffHighlightTraceId(fileId);
340
+ traceDiffHighlight("highlight-source", { request, file: fileTraceId, rows: fileRows.length });
341
+ let source: NativeReviewDiffSource | null;
342
+ try {
343
+ source = await file.loadContents!(input.signal);
344
+ } catch {
345
+ traceDiffHighlight("highlight-source-error", { request, file: fileTraceId });
346
+ for (const row of fileRows) {
347
+ selectedRowIds.delete(row.id);
348
+ tokensByRowId[row.id] = makePlainTokenFallback(row);
349
+ retryableRowIds.push(row.id);
350
+ }
351
+ emitFileChunk(fileRows);
352
+ continue;
353
+ }
354
+ if (input.signal?.aborted) break;
355
+ const contexts = source ? getFullSourceContexts(source) : null;
356
+ for (const side of ["old", "new"] as const) {
357
+ if (input.signal?.aborted) break;
358
+ const candidate = contexts?.[side];
359
+ const context =
360
+ candidate &&
361
+ matchesSourceSide(candidate, getSourceRowsByFile(input.rows).get(fileId)!, side)
362
+ ? candidate
363
+ : null;
364
+ traceDiffHighlight("source-validation", {
365
+ request,
366
+ file: fileTraceId,
367
+ side,
368
+ present: !!candidate,
369
+ matches: !!context,
370
+ knownLines: context?.comparisonLines.length,
371
});
372
+ const matchingRows: { row: NativeReviewDiffLineRow; lineIndex: number }[] = [];
373
+ for (const row of fileRows) {
374
+ if (displaySide(row) !== side) continue;
375
+ selectedRowIds.delete(row.id);
376
+ const lineNumber = side === "old" ? row.oldLineNumber : row.newLineNumber;
377
+ const lineIndex = typeof lineNumber === "number" ? lineNumber - 1 : -1;
378
+ if (
379
+ context &&
380
+ lineIndex >= 0 &&
381
+ lineIndex < context.comparisonLines.length &&
382
+ context.comparisonLines[lineIndex] === row.content
383
+ ) {
384
+ matchingRows.push({ row, lineIndex });
385
+ } else {
386
+ // A changed revision or missing source cannot
387
+ // supply trustworthy grammar. Do not cache guessed syntax colors.
388
+ tokensByRowId[row.id] = makePlainTokenFallback(row);
389
+ }
390
+ }
391
+ if (!context || matchingRows.length === 0) continue;
392
+ const tokens = tokenize(context, context.contents, file.language);
393
+ for (const { row, lineIndex } of matchingRows) {
394
+ tokensByRowId[row.id] =
395
+ tokens.highlightLine(lineIndex, input.scheme) ?? makePlainTokenFallback(row);
396
+ }
397
}
140
- segment = [];
141
- };
398
+ emitFileChunk(fileRows);
399
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
400
+ }
401
+
402
+ const selectedSegments = new Map<
403
+ SourceSegment,
404
+ { firstSelected: number; lastSelected: number }
405
+ >();
406
+ if (selectedRowIds.size > 0 && !input.signal?.aborted) {
407
+ const sourceSegments = getSourceSegments(input.rows);
408
+ for (const row of selectedRows) {
409
+ if (!selectedRowIds.has(row.id)) continue;
410
+ const source = sourceSegments.get(row.id);
411
+ if (!source) continue;
412
+ const selection = selectedSegments.get(source.segment);
413
+ if (selection) {
414
+ selection.lastSelected = source.index;
415
+ } else {
416
+ selectedSegments.set(source.segment, {
417
+ firstSelected: source.index,
418
+ lastSelected: source.index,
419
+ });
420
+ }
421
+ }
422
+ }
423
143
- for (const selectedRow of selectedRows) {
144
- const previousRow = segment.at(-1);
145
- if (previousRow && !canShareGrammarContext(previousRow, selectedRow, input.rows)) {
146
- flushSegment();
424
+ for (const [segment, { firstSelected, lastSelected }] of selectedSegments) {
425
+ if (input.signal?.aborted) break;
426
+ const file = fileMap.get(segment.fileId);
427
+ if (!file) continue;
428
+
429
+ const tokens = tokenize(
430
+ segment,
431
+ () => segment.rows.map((row) => row.content).join("\n"),
432
+ file.language,
433
+ );
434
+ for (let index = firstSelected; index <= lastSelected; index += 1) {
435
+ const row = segment.rows[index]!;
436
+ if (selectedRowIds.has(row.id) && displaySide(row) === segment.side) {
437
+ tokensByRowId[row.id] =
438
+ tokens.highlightLine(index, input.scheme) ?? makePlainTokenFallback(row);
439
+ }
440
}
148
- segment.push(selectedRow);
441
}
150
- flushSegment();
442
152
- return { tokensByRowId, rowCount: selectedRows.length };
443
+ if (input.signal?.aborted) {
444
+ traceDiffHighlight("highlight-aborted", { request });
445
+ return {
446
+ tokensByRowId: {},
447
+ retryableRowIds: [],
448
+ rowCount: 0,
449
+ durationMs: 0,
450
+ };
451
+ }
452
+
453
+ traceDiffHighlight("highlight-result", {
454
+ request,
455
+ selected: selectedRows.length,
456
+ delivered: Object.keys(tokensByRowId).length,
457
+ retryable: retryableRowIds.length,
458
+ colored: Object.values(tokensByRowId).filter((tokens) =>
459
+ tokens.some((token) => token.color !== null),
460
+ ).length,
461
+ });
462
+ return {
463
+ tokensByRowId,
464
+ retryableRowIds,
465
+ rowCount: selectedRows.length,
466
+ durationMs: Math.round(performance.now() - startedAt),
467
+ };
468
}
apps/mobile/src/features/diffs/nativeReviewDiffSource.test.ts
new
+151
@@ -0,0 +1,151 @@
1
+import { expect, it, vi } from "vite-plus/test";
2
+
3
+import { createNativeReviewDiffSourceLoader } from "./nativeReviewDiffSource";
4
+import type { NativeReviewDiffSource } from "./nativeReviewDiffTypes";
5
+
6
+const SOURCE = { oldContents: "const before = true;", newContents: "const after = false;" };
7
+
8
+vi.mock("expo-file-system", () => ({
9
+ Paths: { document: "test-documents" },
10
+ File: class {
11
+ create() {}
12
+ async write() {}
13
+ },
14
+}));
15
+
16
+it("retains fetched stress sources above 500k characters within the aggregate budget", async () => {
17
+ const source = { oldContents: "", newContents: "x".repeat(3_270_000) };
18
+ const fetch = vi.fn(async () => source);
19
+ const load = createNativeReviewDiffSourceLoader(fetch);
20
+ expect(await load("generated.c")).toBe(source);
21
+ expect(await load("generated.c")).toBe(source);
22
+ expect(fetch).toHaveBeenCalledTimes(1);
23
+});
24
+
25
+it("evicts source text by aggregate size and returns an over-budget response uncached", async () => {
26
+ const source = { oldContents: "", newContents: "x".repeat(4_500_000) };
27
+ const huge = { oldContents: "", newContents: "x".repeat(9_000_000) };
28
+ const fetch = vi.fn(async (id: string) => (id === "huge" ? huge : source));
29
+ const load = createNativeReviewDiffSourceLoader(fetch);
30
+ expect(await load("first")).toBe(source);
31
+ expect(await load("second")).toBe(source);
32
+ expect(await load("first")).toBe(source);
33
+ expect(fetch).toHaveBeenCalledTimes(3);
34
+ expect(await load("huge")).toBe(huge);
35
+ expect(await load("huge")).toBe(huge);
36
+ expect(fetch).toHaveBeenCalledTimes(5);
37
+ expect(await load("first")).toBe(source);
38
+ expect(fetch).toHaveBeenCalledTimes(5);
39
+});
40
+
41
+it("lets later viewport requests retry a failed source fetch", async () => {
42
+ const fetch = vi.fn().mockRejectedValueOnce(new Error("Offline")).mockResolvedValueOnce(SOURCE);
43
+ const load = createNativeReviewDiffSourceLoader(fetch);
44
+ await expect(load("retry.ts")).rejects.toThrow("Offline");
45
+ expect(await load("retry.ts")).toBe(SOURCE);
46
+});
47
+
48
+const failureKeys = [
49
+ ["string", () => "retry.ts"],
50
+ ["number", () => 1],
51
+ ["boolean", () => false],
52
+ ["bigint", () => 1n],
53
+ ["symbol", () => Symbol("retry.ts")],
54
+ ["null", () => null],
55
+ ["undefined", () => undefined],
56
+ ["object", () => ({ id: "retry.ts" })],
57
+ ["function", () => () => SOURCE],
58
+] as const;
59
+
60
+it.each(failureKeys)("bounds transient retries for a %s key", async (_name, createKey) => {
61
+ const key = createKey();
62
+ const fetch = vi.fn(async () => {
63
+ throw new Error("Offline");
64
+ });
65
+ const load = createNativeReviewDiffSourceLoader(fetch);
66
+ await expect(load(key)).rejects.toThrow("Offline");
67
+ expect(await load(key)).toBeNull();
68
+ expect(await load(key)).toBeNull();
69
+ expect(fetch).toHaveBeenCalledTimes(2);
70
+});
71
+
72
+it.each(failureKeys)(
73
+ "remembers permanent unavailability for a %s key",
74
+ async (_name, createKey) => {
75
+ const key = createKey();
76
+ const fetch = vi.fn(async () => {
77
+ throw { reason: "unsupported" };
78
+ });
79
+ const load = createNativeReviewDiffSourceLoader(fetch);
80
+ expect(await load(key)).toBeNull();
81
+ expect(await load(key)).toBeNull();
82
+ expect(fetch).toHaveBeenCalledOnce();
83
+ },
84
+);
85
+
86
+it.each(failureKeys)(
87
+ "resets retries after success and eviction for a %s key",
88
+ async (_name, createKey) => {
89
+ const key = createKey();
90
+ const fetch = vi
91
+ .fn()
92
+ .mockRejectedValueOnce(new Error("Offline"))
93
+ .mockResolvedValueOnce(SOURCE)
94
+ .mockResolvedValueOnce({ oldContents: "", newContents: "x".repeat(8_000_000) })
95
+ .mockRejectedValueOnce(new Error("Offline again"))
96
+ .mockResolvedValueOnce(SOURCE);
97
+ const load = createNativeReviewDiffSourceLoader(fetch);
98
+ await expect(load(key)).rejects.toThrow("Offline");
99
+ expect(await load(key)).toBe(SOURCE);
100
+ await load({ id: "evict" });
101
+ await expect(load(key)).rejects.toThrow("Offline again");
102
+ expect(await load(key)).toBe(SOURCE);
103
+ expect(fetch).toHaveBeenCalledTimes(5);
104
+ },
105
+);
106
+
107
+it("shares an in-flight function request while one subscriber cancels", async () => {
108
+ const started = Promise.withResolvers<void>();
109
+ const response = Promise.withResolvers<NativeReviewDiffSource>();
110
+ let calls = 0;
111
+ const request = () => {
112
+ calls++;
113
+ started.resolve();
114
+ return response.promise;
115
+ };
116
+ const load = createNativeReviewDiffSourceLoader((sourceRequest: typeof request) =>
117
+ sourceRequest(),
118
+ );
119
+ const controller = new AbortController();
120
+ const first = load(request, controller.signal);
121
+ await started.promise;
122
+ const second = load(request);
123
+ controller.abort();
124
+ expect(await first).toBeNull();
125
+ response.resolve(SOURCE);
126
+ expect(await second).toBe(SOURCE);
127
+ expect(await load(request)).toBe(SOURCE);
128
+ expect(calls).toBe(1);
129
+});
130
+
131
+it("serializes RPCs and drops cancelled queued files", async () => {
132
+ const started = Promise.withResolvers<void>();
133
+ const response = Promise.withResolvers<NativeReviewDiffSource>();
134
+ const fetch = vi.fn((file: string) => {
135
+ if (file !== "active.ts") return Promise.resolve(SOURCE);
136
+ started.resolve();
137
+ return response.promise;
138
+ });
139
+ const load = createNativeReviewDiffSourceLoader(fetch);
140
+ const active = load("active.ts");
141
+ await started.promise;
142
+ const controller = new AbortController();
143
+ const queued = load("cancelled.ts", controller.signal);
144
+ controller.abort();
145
+ expect(await queued).toBeNull();
146
+ expect(fetch.mock.calls).toEqual([["active.ts"]]);
147
+ response.resolve(SOURCE);
148
+ await active;
149
+ await load("next.ts");
150
+ expect(fetch.mock.calls).toEqual([["active.ts"], ["next.ts"]]);
151
+});
apps/mobile/src/features/diffs/nativeReviewDiffSource.ts
new
+188
@@ -0,0 +1,188 @@
1
+import type { NativeReviewDiffSource } from "./nativeReviewDiffTypes";
2
+import { diffHighlightTraceId, traceDiffHighlight } from "./nativeReviewDiffTrace";
3
+
4
+const MAX_SOURCE_FILES = 4;
5
+// Bound retained UTF-16 text across files without discarding an already-fetched
6
+// authoritative source just because it is large. Provider response limits still apply.
7
+const MAX_CACHED_SOURCE_CHARACTERS = 8_000_000;
8
+const MAX_SOURCE_ATTEMPTS = 2;
9
+
10
+function isWeakKey(value: unknown): value is object {
11
+ return (typeof value === "object" && value !== null) || typeof value === "function";
12
+}
13
+
14
+function permanentSourceFailureReason(error: unknown): string | undefined {
15
+ for (let depth = 0; depth < 8 && typeof error === "object" && error !== null; depth++) {
16
+ const reason = "reason" in error ? error.reason : undefined;
17
+ const name = "name" in error ? error.name : undefined;
18
+ // Defect serialization preserves error names and causes, but drops custom fields.
19
+ if (name === "GitCafeDiffSourceUnavailableError") return "gitcafe-source-unavailable";
20
+ if (name === "GitHubDiffFileContentsUnavailableError") return "github-source-unavailable";
21
+ for (const permanent of [
22
+ "provider-unsupported",
23
+ "unsupported",
24
+ "oversized",
25
+ "binary",
26
+ "not-found",
27
+ ]) {
28
+ if (permanent === reason) return permanent;
29
+ }
30
+ if ("status" in error && error.status === 413) return "http-413";
31
+ if ("status" in error && error.status === 501) return "http-501";
32
+ // Older servers have no structured reason for an unsupported contents RPC.
33
+ if (
34
+ "detail" in error &&
35
+ error.detail === "This host cannot expand unchanged pull request lines."
36
+ )
37
+ return "legacy-host-unsupported";
38
+ error = "cause" in error ? error.cause : undefined;
39
+ }
40
+ return undefined;
41
+}
42
+
43
+function waitForSource(
44
+ promise: Promise<NativeReviewDiffSource | null>,
45
+ signal?: AbortSignal,
46
+): Promise<NativeReviewDiffSource | null> {
47
+ if (!signal) return promise;
48
+ if (signal.aborted) return Promise.resolve(null);
49
+ return new Promise((resolve, reject) => {
50
+ const abort = () => {
51
+ signal.removeEventListener("abort", abort);
52
+ resolve(null);
53
+ };
54
+ signal.addEventListener("abort", abort, { once: true });
55
+ void promise.then(
56
+ (source) => {
57
+ signal.removeEventListener("abort", abort);
58
+ resolve(source);
59
+ },
60
+ (error: unknown) => {
61
+ signal.removeEventListener("abort", abort);
62
+ reject(error);
63
+ },
64
+ );
65
+ });
66
+}
67
+
68
+export function createNativeReviewDiffSourceLoader<FileId>(
69
+ fetchSource: (fileId: FileId) => Promise<NativeReviewDiffSource>,
70
+) {
71
+ const cached = new Map<FileId, NativeReviewDiffSource>();
72
+ let cachedCharacters = 0;
73
+ type Failure = { attempts: number; unavailable: boolean };
74
+ // Request closures can own parsed rows; failed versions must not retain them.
75
+ const objectFailures = new WeakMap<object, Failure>();
76
+ const primitiveFailures = new Map<FileId, Failure>();
77
+ const pending = new Map<
78
+ FileId,
79
+ {
80
+ readonly promise: Promise<NativeReviewDiffSource | null>;
81
+ readonly subscribers: Set<AbortSignal | undefined>;
82
+ }
83
+ >();
84
+ // RPC commands cannot abort a request already sent. Serialize source fetches
85
+ // and drop queued requests whose viewports have all been cancelled.
86
+ let tail = Promise.resolve();
87
+ const loader = diffHighlightTraceId(cached);
88
+
89
+ return async (fileId: FileId, signal?: AbortSignal) => {
90
+ const file = diffHighlightTraceId(fileId);
91
+ const failure = (isWeakKey(fileId)
92
+ ? objectFailures.get(fileId)
93
+ : primitiveFailures.get(fileId)) ?? { attempts: 0, unavailable: false };
94
+ if (signal?.aborted || failure.unavailable) {
95
+ traceDiffHighlight("source-skip", {
96
+ loader,
97
+ file,
98
+ aborted: signal?.aborted ?? false,
99
+ unavailable: failure.unavailable,
100
+ });
101
+ return null;
102
+ }
103
+ if (cached.has(fileId)) {
104
+ traceDiffHighlight("source-cache", { loader, file });
105
+ const source = cached.get(fileId)!;
106
+ cached.delete(fileId);
107
+ cached.set(fileId, source);
108
+ return source;
109
+ }
110
+ let request = pending.get(fileId);
111
+ if (!request) {
112
+ traceDiffHighlight("source-queued", { loader, file, pending: pending.size });
113
+ const subscribers = new Set<AbortSignal | undefined>();
114
+ const promise = tail
115
+ .then(async () => {
116
+ if ([...subscribers].every((subscriber) => subscriber?.aborted)) {
117
+ traceDiffHighlight("source-dropped", { loader, file });
118
+ return null;
119
+ }
120
+ const attempt = ++failure.attempts;
121
+ if (isWeakKey(fileId)) objectFailures.set(fileId, failure);
122
+ else primitiveFailures.set(fileId, failure);
123
+ traceDiffHighlight("source-start", { loader, file, attempt });
124
+ try {
125
+ const contents = await fetchSource(fileId);
126
+ traceDiffHighlight("source-result", {
127
+ loader,
128
+ file,
129
+ oldCharacters: contents.oldContents.length,
130
+ newCharacters: contents.newContents.length,
131
+ });
132
+ const characters = contents.oldContents.length + contents.newContents.length;
133
+ if (isWeakKey(fileId)) objectFailures.delete(fileId);
134
+ else primitiveFailures.delete(fileId);
135
+ if (characters <= MAX_CACHED_SOURCE_CHARACTERS) {
136
+ cached.set(fileId, contents);
137
+ cachedCharacters += characters;
138
+ while (
139
+ cached.size > MAX_SOURCE_FILES ||
140
+ cachedCharacters > MAX_CACHED_SOURCE_CHARACTERS
141
+ ) {
142
+ const oldest = cached.keys().next().value!;
143
+ const source = cached.get(oldest)!;
144
+ cachedCharacters -= source.oldContents.length + source.newContents.length;
145
+ cached.delete(oldest);
146
+ }
147
+ }
148
+ return contents;
149
+ } catch (error) {
150
+ const reason = permanentSourceFailureReason(error);
151
+ const permanent = reason !== undefined;
152
+ traceDiffHighlight("source-error", {
153
+ loader,
154
+ file,
155
+ attempt,
156
+ permanent,
157
+ reason: reason ?? "transient",
158
+ });
159
+ if (permanent || attempt >= MAX_SOURCE_ATTEMPTS) {
160
+ failure.unavailable = true;
161
+ traceDiffHighlight("source-unavailable", {
162
+ loader,
163
+ file,
164
+ reason: permanent ? "permanent-error" : "attempts",
165
+ });
166
+ return null;
167
+ }
168
+ // Only a later viewport request retries; never loop inside this request.
169
+ throw error;
170
+ }
171
+ })
172
+ .finally(() => pending.delete(fileId));
173
+ tail = promise.then(
174
+ () => {},
175
+ () => {},
176
+ );
177
+ request = { promise, subscribers };
178
+ pending.set(fileId, request);
179
+ } else traceDiffHighlight("source-shared", { loader, file });
180
+ request.subscribers.add(signal);
181
+ try {
182
+ return await waitForSource(request.promise, signal);
183
+ } finally {
184
+ if (signal?.aborted) traceDiffHighlight("source-wait-aborted", { loader, file });
185
+ request.subscribers.delete(signal);
186
+ }
187
+ };
188
+}
apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.ts
deleted
-33
@@ -1,33 +0,0 @@
1
-import { describe, expect, it, vi } from "vite-plus/test";
2
-
3
-const expoMocks = vi.hoisted(() => ({
4
- requireNativeView: vi.fn(),
5
-}));
6
-
7
-vi.mock("expo", () => ({
8
- requireNativeView: expoMocks.requireNativeView,
9
-}));
10
-
11
-describe("isPendingNativeViewRegistration", () => {
12
- it("recognizes registration races for the installed native view name", async () => {
13
- const { isPendingNativeViewRegistration } = await import("./nativeReviewDiffSurface");
14
-
15
- expect(
16
- isPendingNativeViewRegistration(
17
- new Error("Unable to find the 'T3ReviewDiffSurface' view for this native tag"),
18
- ),
19
- ).toBe(true);
20
- expect(
21
- isPendingNativeViewRegistration(
22
- new Error("Unable to find the 'T3ReviewDiffView' view for this native tag"),
23
- ),
24
- ).toBe(false);
25
- expect(
26
- isPendingNativeViewRegistration(
27
- new Error(
28
- "Unable to find the class expo.modules.t3reviewdiff.T3ReviewDiffView view with tag 1150",
29
- ),
30
- ),
31
- ).toBe(true);
32
- });
33
-});
apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx
new
+405
@@ -0,0 +1,405 @@
1
+import {
2
+ act,
3
+ useLayoutEffect,
4
+ useImperativeHandle,
5
+ useRef,
6
+ useState,
7
+ type Ref,
8
+ type ReactNode,
9
+} from "react";
10
+import { createRoot } from "react-dom/client";
11
+import { expect, it, vi } from "vite-plus/test";
12
+import { AsyncResult } from "effect/reactivity";
13
+import * as Cause from "effect/Cause";
14
+import type { HighlightNativeReviewDiffVisibleRowsInput } from "./nativeReviewDiffHighlighter";
15
+import type { NativeReviewDiffViewProps } from "./nativeReviewDiffSurface";
16
+import type { NativeReviewDiffData } from "../review/nativeReviewDiffAdapter";
17
+
18
+const mocks = vi.hoisted(() => ({
19
+ registrationFailures: 0,
20
+ tokenAccepted: true as boolean | undefined,
21
+ tokenCompletion: null as Promise<boolean> | null,
22
+ onDebug: undefined as NativeReviewDiffViewProps["onDebug"],
23
+ autoViewport: false,
24
+ rows: vi.fn(),
25
+ tokens: vi.fn(),
26
+ highlight: vi.fn(),
27
+}));
28
+
29
+function RawView({
30
+ ref: nativeRef,
31
+ onDebug,
32
+ initialFileId,
33
+ contentResetKey,
34
+}: NativeReviewDiffViewProps & { ref: Ref<unknown> }) {
35
+ const [content, setContent] = useState({ resetKey: contentResetKey, rows: "" });
36
+ const rows = content.resetKey === contentResetKey ? content.rows : "";
37
+ const [tokenRowIds, setTokenRowIds] = useState<string[]>([]);
38
+ useLayoutEffect(() => {
39
+ mocks.onDebug = onDebug;
40
+ });
41
+ useImperativeHandle(nativeRef, () => ({
42
+ async setRowsJson(value: string) {
43
+ mocks.rows(value);
44
+ if (mocks.registrationFailures > 0) {
45
+ mocks.registrationFailures -= 1;
46
+ throw new Error("Unable to find the 'T3ReviewDiffSurface' view for this native tag");
47
+ }
48
+ setContent({ resetKey: contentResetKey, rows: value });
49
+ if (mocks.autoViewport) {
50
+ const decoded = JSON.parse(value) as NativeReviewDiffData["rows"];
51
+ onDebug?.({
52
+ nativeEvent: { message: "rows-decoded", rows: decoded.length },
53
+ } as unknown as Parameters<NonNullable<typeof onDebug>>[0]);
54
+ const index = decoded.findIndex(
55
+ (row) => row.kind === "file" && row.fileId === initialFileId,
56
+ );
57
+ onDebug?.({
58
+ nativeEvent: {
59
+ message: "visible-range",
60
+ firstRowIndex: Math.max(0, index),
61
+ lastRowIndex: Math.max(0, index) + 40,
62
+ totalRows: decoded.length,
63
+ },
64
+ } as unknown as Parameters<NonNullable<typeof onDebug>>[0]);
65
+ }
66
+ },
67
+ async scrollToFile() {},
68
+ async setTokensPatchJson(value: string) {
69
+ mocks.tokens(value);
70
+ const accepted = mocks.tokenCompletion ? await mocks.tokenCompletion : mocks.tokenAccepted;
71
+ if (accepted === true) {
72
+ const patch = JSON.parse(value);
73
+ setTokenRowIds((current) => [
74
+ ...new Set([...current, ...Object.keys(patch.tokensByRowId)]),
75
+ ]);
76
+ }
77
+ return accepted;
78
+ },
79
+ }));
80
+ return (
81
+ <div data-token-rows={tokenRowIds.join(",")}>
82
+ {rows ? "Rendered diff" : "Blank native surface"}
83
+ </div>
84
+ );
85
+}
86
+
87
+vi.mock("expo", () => ({ requireNativeView: () => RawView }));
88
+vi.mock("react-native", () => ({
89
+ View: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
90
+}));
91
+vi.mock("../../components/ui/EmptyState", () => ({
92
+ EmptyState: ({
93
+ title,
94
+ actionLabel,
95
+ onAction,
96
+ }: {
97
+ title: string;
98
+ actionLabel: string;
99
+ onAction: () => void;
100
+ }) => (
101
+ <div>
102
+ {title}
103
+ <button onClick={onAction}>{actionLabel}</button>
104
+ </div>
105
+ ),
106
+}));
107
+vi.mock("./nativeReviewDiffHighlighter", () => ({
108
+ highlightNativeReviewDiffVisibleRows: mocks.highlight,
109
+}));
110
+vi.mock("@t3tools/client-runtime/state/runtime", () => ({
111
+ settlePromise: async (execute: () => Promise<unknown>) => {
112
+ try {
113
+ return AsyncResult.success(await execute());
114
+ } catch (error) {
115
+ return AsyncResult.failure(Cause.die(error));
116
+ }
117
+ },
118
+ squashAtomCommandFailure: () => "tokenization failed",
119
+}));
120
+vi.mock("../review/nativeReviewDiffAdapter", () => ({ createNativeReviewDiffTheme: () => ({}) }));
121
+vi.mock("../settings/appearance/useAppearanceCodeSurface", () => ({
122
+ useAppearanceCodeSurface: () => ({ nativeReviewDiffStyle: {} }),
123
+}));
124
+vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({
125
+ useAppearancePreferences: () => ({ themeAppearance: "light", themeId: "test" }),
126
+}));
127
+vi.mock("../../lib/useUniwindTheme", () => ({ useUniwindTheme: () => ({}) }));
128
+
129
+import { resolveNativeReviewDiffView } from "./nativeReviewDiffSurface";
130
+import { useNativeReviewDiffBridge } from "../review/useNativeReviewDiffBridge";
131
+import {
132
+ handlePullRequestDiffDebugEvent,
133
+ pullRequestDiffInitialPosition,
134
+} from "../pull-requests/pullRequestDiffDebug";
135
+
136
+function setup(integrated = false) {
137
+ vi.useFakeTimers();
138
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
139
+ mocks.registrationFailures = 0;
140
+ mocks.tokenAccepted = true;
141
+ mocks.tokenCompletion = null;
142
+ mocks.onDebug = undefined;
143
+ mocks.autoViewport = false;
144
+ mocks.rows.mockClear();
145
+ mocks.tokens.mockClear();
146
+ mocks.highlight
147
+ .mockReset()
148
+ .mockImplementation(async (input: HighlightNativeReviewDiffVisibleRowsInput) => {
149
+ const rowId = `r${input.firstRowIndex}`;
150
+ const tokensByRowId = input.alreadyHighlightedRowIds?.has(rowId)
151
+ ? {}
152
+ : { [rowId]: [{ content: "const", color: "#ff0000", fontStyle: null }] };
153
+ return {
154
+ rowCount: Object.keys(tokensByRowId).length,
155
+ durationMs: 0,
156
+ retryableRowIds: [],
157
+ tokensByRowId,
158
+ };
159
+ });
160
+ const frames = new Map<number, FrameRequestCallback>();
161
+ let nextFrame = 0;
162
+ const requestFrame = vi
163
+ .spyOn(globalThis, "requestAnimationFrame")
164
+ .mockImplementation((callback) => {
165
+ frames.set(++nextFrame, callback);
166
+ return nextFrame;
167
+ });
168
+ const cancelFrame = vi.spyOn(globalThis, "cancelAnimationFrame").mockImplementation((id) => {
169
+ if (id != null) frames.delete(id);
170
+ });
171
+ const errors = vi.spyOn(console, "error").mockImplementation(() => {});
172
+ const expo = Object.getOwnPropertyDescriptor(globalThis, "expo");
173
+ Object.defineProperty(globalThis, "expo", {
174
+ configurable: true,
175
+ value: { getViewConfig: () => ({}) },
176
+ });
177
+ const NativeDiff = resolveNativeReviewDiffView()!;
178
+ const container = document.createElement("div");
179
+ const root = createRoot(container);
180
+ let data: NativeReviewDiffData = {
181
+ rows: Array.from({ length: 1000 }, (_, index) =>
182
+ index === 999
183
+ ? { kind: "comment", id: `r${index}`, commentText: "Original comment" }
184
+ : index === 900
185
+ ? { kind: "file", id: `r${index}`, fileId: "last-file" }
186
+ : { kind: "line", id: `r${index}` },
187
+ ),
188
+ files: [],
189
+ additions: 0,
190
+ deletions: 0,
191
+ commentTargetsByRowId: new Map(),
192
+ rowIdByCommentLineId: new Map(),
193
+ };
194
+ const ids: string[] = [];
195
+ function PullRequestDiff({ targetFileId }: { targetFileId?: string }) {
196
+ const bridge = useNativeReviewDiffBridge({
197
+ threadKey: null,
198
+ sectionId: "pull-request:test:1:all",
199
+ diff: "test diff",
200
+ data,
201
+ collapsedFileIds: ids,
202
+ viewedFileIds: ids,
203
+ selectedRowIds: ids,
204
+ canHighlight: true,
205
+ });
206
+ const nativeView = useRef(null);
207
+ const jumpStarted = useRef(true);
208
+ const onDebug: NonNullable<NativeReviewDiffViewProps["onDebug"]> = (event) =>
209
+ handlePullRequestDiffDebugEvent(event, {
210
+ rowCount: data.rows.length,
211
+ targetFileId,
212
+ focusIndex: -1,
213
+ isIos: true,
214
+ nativeView,
215
+ jumpStarted,
216
+ loadMore: () => {},
217
+ onDebug: bridge.onDebug,
218
+ });
219
+ return (
220
+ <NativeDiff
221
+ {...bridge}
222
+ {...pullRequestDiffInitialPosition(targetFileId, -1)}
223
+ nativeViewRef={nativeView}
224
+ appearanceScheme="light"
225
+ rowHeight={20}
226
+ contentWidth={300}
227
+ onDebug={onDebug}
228
+ />
229
+ );
230
+ }
231
+ if (!integrated) {
232
+ act(() =>
233
+ root.render(
234
+ <NativeDiff
235
+ rowsJson="[]"
236
+ tokensPatchJson='{"tokensByRowId":{}}'
237
+ appearanceScheme="light"
238
+ themeJson="{}"
239
+ rowHeight={20}
240
+ contentWidth={300}
241
+ />,
242
+ ),
243
+ );
244
+ }
245
+ return {
246
+ container,
247
+ async mountPullRequest(targetFileId?: string) {
248
+ await act(async () => root.render(<PullRequestDiff targetFileId={targetFileId} />));
249
+ },
250
+ async updateComment() {
251
+ data = {
252
+ ...data,
253
+ rows: data.rows.map((row) =>
254
+ row.kind === "comment" ? { ...row, commentText: "Updated comment" } : row,
255
+ ),
256
+ };
257
+ await act(async () => root.render(<PullRequestDiff />));
258
+ },
259
+ get tokenRows() {
260
+ return container.querySelector("[data-token-rows]")?.getAttribute("data-token-rows");
261
+ },
262
+ async jump(firstRowIndex: number, totalRows = 1000) {
263
+ await act(async () => {
264
+ mocks.onDebug?.({
265
+ nativeEvent: {
266
+ message: "visible-range",
267
+ firstRowIndex,
268
+ lastRowIndex: firstRowIndex + 40,
269
+ totalRows,
270
+ },
271
+ } as unknown as Parameters<NonNullable<NativeReviewDiffViewProps["onDebug"]>>[0]);
272
+ await vi.runOnlyPendingTimersAsync();
273
+ });
274
+ },
275
+ async deliverPayloads() {
276
+ const callbacks = [...frames.values()];
277
+ frames.clear();
278
+ await act(async () => {
279
+ for (const callback of callbacks) callback(0);
280
+ await vi.runOnlyPendingTimersAsync();
281
+ });
282
+ },
283
+ retry() {
284
+ const button = container.querySelector("button");
285
+ expect(button?.textContent).toBe("Retry diff");
286
+ act(() => button!.click());
287
+ },
288
+ decodeFailure() {
289
+ act(() =>
290
+ mocks.onDebug?.({
291
+ nativeEvent: { message: "rows-decode-failed", error: "Decode failed" },
292
+ } as unknown as Parameters<NonNullable<NativeReviewDiffViewProps["onDebug"]>>[0]),
293
+ );
294
+ },
295
+ [Symbol.dispose]() {
296
+ act(() => root.unmount());
297
+ requestFrame.mockRestore();
298
+ cancelFrame.mockRestore();
299
+ errors.mockRestore();
300
+ vi.useRealTimers();
301
+ if (expo) Object.defineProperty(globalThis, "expo", expo);
302
+ else Reflect.deleteProperty(globalThis, "expo");
303
+ },
304
+ };
305
+}
306
+
307
+it("retries transient native registration without replacing the diff with an error", async () => {
308
+ using screen = setup();
309
+ mocks.registrationFailures = 1;
310
+ await screen.deliverPayloads();
311
+ expect(screen.container.textContent).toBe("Blank native surface");
312
+ await screen.deliverPayloads();
313
+ expect(screen.container.textContent).toBe("Rendered diff");
314
+});
315
+
316
+it.each([false, undefined])(
317
+ "keeps colors queued until native accepts them and recovers rejected patches (%s)",
318
+ async (rejected) => {
319
+ using screen = setup(true);
320
+ await screen.mountPullRequest();
321
+ let accept!: (accepted: boolean) => void;
322
+ mocks.tokenCompletion = new Promise((resolve) => {
323
+ accept = resolve;
324
+ });
325
+ mocks.tokens.mockClear();
326
+ await screen.jump(0);
327
+ await screen.deliverPayloads();
328
+ await screen.jump(400);
329
+ await screen.deliverPayloads();
330
+ expect(
331
+ mocks.tokens.mock.calls.map(([json]) => Object.keys(JSON.parse(json).tokensByRowId)),
332
+ ).toEqual([["r0"]]);
333
+ await act(async () => accept(true));
334
+
335
+ mocks.tokenCompletion = null;
336
+ mocks.tokenAccepted = rejected;
337
+ await screen.deliverPayloads();
338
+ expect(screen.tokenRows).toBe("r0");
339
+
340
+ mocks.tokenAccepted = true;
341
+ await screen.jump(800);
342
+ await screen.deliverPayloads();
343
+ expect(screen.tokenRows).toBe("r0,r800");
344
+ await screen.jump(400);
345
+ await screen.deliverPayloads();
346
+ expect(screen.tokenRows).toBe("r0,r800,r400");
347
+ },
348
+);
349
+
350
+it.each(["retry", "comment update"])(
351
+ "re-highlights accepted rows after a native row failure, PR %s, and viewport revisit",
352
+ async (recovery) => {
353
+ using screen = setup(true);
354
+ await screen.mountPullRequest();
355
+ mocks.tokens.mockClear();
356
+ await screen.jump(0);
357
+ await screen.deliverPayloads();
358
+ await screen.jump(400);
359
+ await screen.deliverPayloads();
360
+ expect(screen.tokenRows).toBe("r0,r400");
361
+
362
+ screen.decodeFailure();
363
+ expect(screen.container.textContent).toContain("Could not display diff");
364
+ if (recovery === "retry") await act(async () => screen.retry());
365
+ else await screen.updateComment();
366
+ await screen.deliverPayloads();
367
+ expect(screen.container.textContent).toBe("Rendered diff");
368
+ await screen.jump(800);
369
+ await screen.deliverPayloads();
370
+ await screen.jump(400);
371
+ await screen.deliverPayloads();
372
+ expect(screen.tokenRows?.split(",")).toContain("r400");
373
+ },
374
+);
375
+
376
+it("delivers the selected file first with a warm highlighter and no startup command", async () => {
377
+ using screen = setup(true);
378
+ mocks.autoViewport = true;
379
+ await screen.mountPullRequest("last-file");
380
+ await screen.deliverPayloads();
381
+ await screen.deliverPayloads();
382
+ expect(screen.tokenRows).toBe("r900");
383
+});
384
+
385
+it("recognizes registration races for the installed native view name", async () => {
386
+ const { isPendingNativeViewRegistration } = await import("./nativeReviewDiffSurface");
387
+
388
+ expect(
389
+ isPendingNativeViewRegistration(
390
+ new Error("Unable to find the 'T3ReviewDiffSurface' view for this native tag"),
391
+ ),
392
+ ).toBe(true);
393
+ expect(
394
+ isPendingNativeViewRegistration(
395
+ new Error("Unable to find the 'T3ReviewDiffView' view for this native tag"),
396
+ ),
397
+ ).toBe(false);
398
+ expect(
399
+ isPendingNativeViewRegistration(
400
+ new Error(
401
+ "Unable to find the class expo.modules.t3reviewdiff.T3ReviewDiffView view with tag 1150",
402
+ ),
403
+ ),
404
+ ).toBe(true);
405
+});
apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts
+140
-19
@@ -1,14 +1,17 @@
1
import {
2
createElement,
3
+ useCallback,
4
useEffect,
5
useImperativeHandle,
6
useRef,
7
+ useState,
8
type ComponentType,
9
type Ref,
10
} from "react";
9
-import type { NativeSyntheticEvent, ViewProps } from "react-native";
11
+import { View, type NativeSyntheticEvent, type ViewProps } from "react-native";
12
import { requireNativeView } from "expo";
13
14
+import { EmptyState } from "../../components/ui/EmptyState";
15
import { NativeViewResolutionError } from "../../native/nativeViewResolutionError";
16
17
const NATIVE_REVIEW_DIFF_MODULE_NAME = "T3ReviewDiffSurface";
@@ -125,6 +128,7 @@ export interface NativeReviewDiffViewProps extends ViewProps {
128
/** Android ignores this and measures the widest row. */
129
readonly contentWidth: number;
130
readonly initialRowIndex?: number;
131
+ readonly initialFileId?: string;
132
readonly scrollEnabled?: boolean;
133
readonly bounces?: boolean;
134
readonly refreshing?: boolean;
@@ -161,7 +165,7 @@ export function isNativeReviewDiffDrawEvent(payload: Readonly<Record<string, unk
165
interface NativeReviewDiffViewRef {
166
readonly setRowsJson: (rowsJson: string) => Promise<void>;
167
readonly setTokensJson: (tokensJson: string) => Promise<void>;
164
- readonly setTokensPatchJson: (tokensPatchJson: string) => Promise<void>;
168
+ readonly setTokensPatchJson: (tokensPatchJson: string) => Promise<boolean>;
169
readonly scrollToFile: (fileId: string, animated: boolean) => Promise<void>;
170
readonly scrollToTop: (animated: boolean) => Promise<void>;
171
}
@@ -192,6 +196,9 @@ function useNativeReviewDiffPayload(
196
nativeRef: React.RefObject<NativeReviewDiffViewRef | null>,
197
method: NativeReviewDiffPayloadMethod,
198
payload: string | undefined,
199
+ resetKey?: string,
200
+ onFailure?: () => void,
201
+ onDelivered?: (payload: string) => void,
202
) {
203
useEffect(() => {
204
if (payload === undefined) {
@@ -208,27 +215,43 @@ function useNativeReviewDiffPayload(
215
}
216
217
const view = nativeRef.current;
211
- const command = view?.[method];
218
+ const command: ((payload: string) => Promise<void | boolean>) | undefined = view?.[method];
219
if (!view || !command) {
220
if (attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES) {
221
attempts += 1;
222
frame = requestAnimationFrame(dispatch);
223
+ } else {
224
+ console.error(`[native-review-diff] ${method} unavailable`);
225
+ onFailure?.();
226
}
227
return;
228
}
229
220
- void command.call(view, payload).catch((error: unknown) => {
221
- if (
222
- !cancelled &&
223
- attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES &&
224
- isPendingNativeViewRegistration(error)
225
- ) {
226
- attempts += 1;
227
- frame = requestAnimationFrame(dispatch);
228
- return;
229
- }
230
- console.error(`[native-review-diff] ${method} failed`, error);
231
- });
230
+ void Promise.resolve()
231
+ .then(() => {
232
+ if (!cancelled) return command.call(view, payload);
233
+ })
234
+ .then((accepted) => {
235
+ if (cancelled) return;
236
+ // This promise resolves after native decode, reset validation, and merge.
237
+ if (method === "setTokensPatchJson" && accepted !== true) {
238
+ throw new Error("Native token patch was not accepted");
239
+ }
240
+ onDelivered?.(payload);
241
+ })
242
+ .catch((error: unknown) => {
243
+ if (cancelled) return;
244
+ if (
245
+ attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES &&
246
+ isPendingNativeViewRegistration(error)
247
+ ) {
248
+ attempts += 1;
249
+ frame = requestAnimationFrame(dispatch);
250
+ return;
251
+ }
252
+ console.error(`[native-review-diff] ${method} failed`, error);
253
+ onFailure?.();
254
+ });
255
};
256
257
// Fabric attaches the React ref before Expo registers the native tag used by
@@ -241,7 +264,7 @@ function useNativeReviewDiffPayload(
264
cancelAnimationFrame(frame);
265
}
266
};
244
- }, [method, nativeRef, payload]);
267
+ }, [method, nativeRef, payload, resetKey, onFailure, onDelivered]);
268
}
269
270
function getExpoViewConfig(moduleName: string) {
@@ -251,11 +274,102 @@ function getExpoViewConfig(moduleName: string) {
274
}
275
276
function NativeReviewDiffView(props: NativeReviewDiffViewProps) {
254
- const { nativeViewRef, rowsJson, tokensJson, tokensPatchJson, ...nativeProps } = props;
277
+ const [failedRowsJson, setFailedRowsJson] = useState<string | null>(null);
278
+ const onRowsFailure = useCallback(() => setFailedRowsJson(props.rowsJson), [props.rowsJson]);
279
+ if (failedRowsJson !== null && failedRowsJson !== props.rowsJson) setFailedRowsJson(null);
280
+ if (failedRowsJson === props.rowsJson) {
281
+ return createElement(
282
+ View,
283
+ {
284
+ style: [
285
+ props.style,
286
+ {
287
+ flex: 1,
288
+ justifyContent: "center",
289
+ paddingTop: props.contentInsetTop,
290
+ paddingBottom: props.contentInsetBottom,
291
+ },
292
+ ],
293
+ },
294
+ createElement(EmptyState, {
295
+ title: "Could not display diff",
296
+ detail: "Try loading the diff view again.",
297
+ variant: "plain",
298
+ actionLabel: "Retry diff",
299
+ onAction: () => {
300
+ props.onDebug?.({
301
+ nativeEvent: { message: "surface-retry" },
302
+ } as unknown as NativeSyntheticEvent<Record<string, unknown>>);
303
+ setFailedRowsJson(null);
304
+ },
305
+ }),
306
+ );
307
+ }
308
+ return createElement(NativeReviewDiffContent, { ...props, onRowsFailure });
309
+}
310
+
311
+function NativeReviewDiffContent(
312
+ props: NativeReviewDiffViewProps & { readonly onRowsFailure: () => void },
313
+) {
314
+ const {
315
+ nativeViewRef,
316
+ rowsJson,
317
+ tokensJson,
318
+ tokensPatchJson,
319
+ onRowsFailure,
320
+ onDebug,
321
+ ...nativeProps
322
+ } = props;
323
const nativeRef = useRef<NativeReviewDiffViewRef>(null);
256
- useNativeReviewDiffPayload(nativeRef, "setRowsJson", rowsJson);
324
+ useNativeReviewDiffPayload(
325
+ nativeRef,
326
+ "setRowsJson",
327
+ rowsJson,
328
+ props.contentResetKey,
329
+ onRowsFailure,
330
+ );
331
useNativeReviewDiffPayload(nativeRef, "setTokensJson", tokensJson);
258
- useNativeReviewDiffPayload(nativeRef, "setTokensPatchJson", tokensPatchJson);
332
+ const onDebugRef = useRef(onDebug);
333
+ useEffect(() => {
334
+ onDebugRef.current = onDebug;
335
+ }, [onDebug]);
336
+ const reportedMountRef = useRef(false);
337
+ useEffect(() => {
338
+ // Effect replay keeps the same native content; only a new mount loses tokens.
339
+ if (reportedMountRef.current) return;
340
+ reportedMountRef.current = true;
341
+ onDebugRef.current?.({
342
+ nativeEvent: { message: "surface-content-mounted" },
343
+ } as unknown as NativeSyntheticEvent<Record<string, unknown>>);
344
+ }, []);
345
+ const reportTokenDelivery = useCallback((json: string, message: string) => {
346
+ const patch = JSON.parse(json) as { resetKey?: string; chunkIndex?: number };
347
+ if (patch.chunkIndex === undefined) return;
348
+ onDebugRef.current?.({
349
+ nativeEvent: {
350
+ message,
351
+ resetKey: patch.resetKey,
352
+ chunkIndex: patch.chunkIndex,
353
+ },
354
+ } as unknown as NativeSyntheticEvent<Record<string, unknown>>);
355
+ }, []);
356
+ const onTokensDelivered = useCallback(
357
+ (json: string) => {
358
+ reportTokenDelivery(json, "tokens-patch-delivered");
359
+ },
360
+ [reportTokenDelivery],
361
+ );
362
+ const onTokensFailure = useCallback(() => {
363
+ if (tokensPatchJson !== undefined) reportTokenDelivery(tokensPatchJson, "tokens-patch-failed");
364
+ }, [reportTokenDelivery, tokensPatchJson]);
365
+ useNativeReviewDiffPayload(
366
+ nativeRef,
367
+ "setTokensPatchJson",
368
+ tokensPatchJson,
369
+ undefined,
370
+ onTokensFailure,
371
+ onTokensDelivered,
372
+ );
373
useImperativeHandle(
374
nativeViewRef,
375
() => ({
@@ -277,6 +391,13 @@ function NativeReviewDiffView(props: NativeReviewDiffViewProps) {
391
return createElement(RawNativeView, {
392
...nativeProps,
393
refreshEnabled: props.onPullToRefresh !== undefined,
394
+ onDebug: (event) => {
395
+ if (event.nativeEvent.message === "rows-decode-failed") {
396
+ console.error("[native-review-diff] rows decode failed", event.nativeEvent.error);
397
+ onRowsFailure();
398
+ }
399
+ onDebug?.(event);
400
+ },
401
ref: nativeRef,
402
});
403
}
apps/mobile/src/features/diffs/nativeReviewDiffTrace.test.ts
new
+98
@@ -0,0 +1,98 @@
1
+import { expect, it, vi } from "vite-plus/test";
2
+
3
+const sink = vi.hoisted(() => ({
4
+ created: vi.fn(),
5
+ written: vi.fn<(line: string, options: unknown) => Promise<void>>(),
6
+ opened: vi.fn(),
7
+}));
8
+
9
+vi.mock("expo-file-system", () => ({
10
+ Paths: { document: "documents" },
11
+ File: class {
12
+ constructor(...args: unknown[]) {
13
+ sink.opened(...args);
14
+ }
15
+ create(options: unknown) {
16
+ sink.created(options);
17
+ }
18
+ write(line: string, options: unknown) {
19
+ return sink.written(line, options);
20
+ }
21
+ },
22
+}));
23
+
24
+it("leaves the filesystem untouched when Release tracing is disabled", async () => {
25
+ vi.resetModules();
26
+ sink.opened.mockClear();
27
+ vi.stubEnv("EXPO_PUBLIC_T3_DIFF_TRACE", "0");
28
+ try {
29
+ const { traceDiffHighlight } = await import("./nativeReviewDiffTrace");
30
+ traceDiffHighlight("viewport-start", { rows: 80 });
31
+ expect(sink.opened).not.toHaveBeenCalled();
32
+ } finally {
33
+ vi.unstubAllEnvs();
34
+ }
35
+});
36
+
37
+it("keeps object, function, and primitive identities stable without collisions", async () => {
38
+ vi.resetModules();
39
+ vi.stubEnv("EXPO_PUBLIC_T3_DIFF_TRACE", "1");
40
+ try {
41
+ const { diffHighlightTraceId } = await import("./nativeReviewDiffTrace");
42
+ const values = [{}, {}, () => {}, () => {}, null, undefined, "file", 1, "1", false];
43
+ const ids = values.map(diffHighlightTraceId);
44
+ expect(ids.every((id) => id > 0)).toBe(true);
45
+ expect(new Set(ids).size).toBe(values.length);
46
+ expect(values.map(diffHighlightTraceId)).toEqual(ids);
47
+ } finally {
48
+ vi.unstubAllEnvs();
49
+ }
50
+});
51
+
52
+it("serializes appends to a retrievable file and bounds a process to 1000 events", async () => {
53
+ vi.resetModules();
54
+ sink.opened.mockClear();
55
+ sink.created.mockClear();
56
+ sink.written.mockReset();
57
+ const firstWrite = Promise.withResolvers<void>();
58
+ const releaseFirst = Promise.withResolvers<void>();
59
+ const finished = Promise.withResolvers<void>();
60
+ sink.written.mockImplementation(async (line) => {
61
+ const { seq } = JSON.parse(line);
62
+ if (seq === 1) {
63
+ firstWrite.resolve();
64
+ await releaseFirst.promise;
65
+ }
66
+ if (seq === 1000) finished.resolve();
67
+ });
68
+ using warning = vi.spyOn(console, "warn").mockImplementation(() => {});
69
+ vi.stubEnv("EXPO_PUBLIC_T3_DIFF_TRACE", "1");
70
+ try {
71
+ const { diffHighlightTraceId, traceDiffHighlight } = await import("./nativeReviewDiffTrace");
72
+ const request = {};
73
+ expect(diffHighlightTraceId(request)).toBeGreaterThan(0);
74
+ for (let index = 0; index < 1001; index++)
75
+ traceDiffHighlight("viewport-start", { rows: index });
76
+ await firstWrite.promise;
77
+ expect(sink.written).toHaveBeenCalledTimes(1);
78
+ releaseFirst.resolve();
79
+ await finished.promise;
80
+ expect(sink.opened.mock.calls).toEqual([["documents", "t3-diff-highlight-trace.jsonl"]]);
81
+ expect(sink.created.mock.calls).toEqual([[{ overwrite: true, intermediates: true }]]);
82
+ expect(sink.written).toHaveBeenCalledTimes(1000);
83
+ expect(warning).toHaveBeenCalledTimes(1000);
84
+ expect(diffHighlightTraceId(request)).toBe(0);
85
+ expect(diffHighlightTraceId("file")).toBe(0);
86
+ expect(sink.written.mock.calls.map(([line]) => JSON.parse(line).seq)).toEqual(
87
+ Array.from({ length: 1000 }, (_, index) => index + 1),
88
+ );
89
+ expect(
90
+ sink.written.mock.calls.every(
91
+ ([line, options]) => line.endsWith("\n") && JSON.stringify(options) === '{"append":true}',
92
+ ),
93
+ ).toBe(true);
94
+ } finally {
95
+ releaseFirst.resolve();
96
+ vi.unstubAllEnvs();
97
+ }
98
+});
apps/mobile/src/features/diffs/nativeReviewDiffTrace.ts
new
+70
@@ -0,0 +1,70 @@
1
+// Opt in at bundle time for bounded Release diagnostics; never log source or RPC payloads.
2
+const MAX_TRACE_EVENTS = 1_000;
3
+let eventCount = 0;
4
+let nextId = 0;
5
+// Diagnostics must not keep requests, source loaders, or their row graphs alive.
6
+const objectIds = new WeakMap<object, number>();
7
+const primitiveIds = new Map<unknown, number>();
8
+let fileSink: Promise<import("expo-file-system").File | null> | undefined;
9
+
10
+export function diffHighlightTraceHash(value: string): number {
11
+ let hash = 2166136261;
12
+ for (let index = 0; index < value.length; index++)
13
+ hash = Math.imul(hash ^ value.charCodeAt(index), 16777619);
14
+ return hash >>> 0;
15
+}
16
+
17
+function appendTraceLine(line: string) {
18
+ fileSink ??= import("expo-file-system")
19
+ .then(({ File, Paths }) => {
20
+ const file = new File(Paths.document, "t3-diff-highlight-trace.jsonl");
21
+ file.create({ overwrite: true, intermediates: true });
22
+ return file;
23
+ })
24
+ .catch(() => null);
25
+ // File.write is async in Expo 58. Serialize appends to preserve sequence order.
26
+ fileSink = fileSink.then(async (file) => {
27
+ if (!file) return null;
28
+ try {
29
+ await file.write(line + "\n", { append: true });
30
+ return file;
31
+ } catch {
32
+ return null;
33
+ }
34
+ });
35
+}
36
+
37
+export function diffHighlightTraceId(value: unknown): number {
38
+ if (process.env.EXPO_PUBLIC_T3_DIFF_TRACE !== "1" || eventCount >= MAX_TRACE_EVENTS) return 0;
39
+ if ((typeof value === "object" && value !== null) || typeof value === "function") {
40
+ let id = objectIds.get(value);
41
+ if (id === undefined) {
42
+ id = ++nextId;
43
+ objectIds.set(value, id);
44
+ }
45
+ return id;
46
+ }
47
+ let id = primitiveIds.get(value);
48
+ if (id === undefined) {
49
+ id = ++nextId;
50
+ primitiveIds.set(value, id);
51
+ }
52
+ return id;
53
+}
54
+
55
+export function traceDiffHighlight(
56
+ event: string,
57
+ fields: Readonly<Record<string, number | boolean | string | undefined>> = {},
58
+) {
59
+ if (process.env.EXPO_PUBLIC_T3_DIFF_TRACE !== "1" || eventCount >= MAX_TRACE_EVENTS) return;
60
+ eventCount += 1;
61
+ const line = JSON.stringify({
62
+ event,
63
+ seq: eventCount,
64
+ at: Math.round(performance.now()),
65
+ ...fields,
66
+ });
67
+ appendTraceLine(line);
68
+ console.warn("[diff-highlight-trace] " + line);
69
+ if (eventCount === MAX_TRACE_EVENTS) primitiveIds.clear();
70
+}
apps/mobile/src/features/diffs/nativeReviewDiffTypes.ts
+6
@@ -1,3 +1,8 @@
1
+export interface NativeReviewDiffSource {
2
+ readonly oldContents: string;
3
+ readonly newContents: string;
4
+}
5
+
6
export interface NativeReviewDiffFile {
7
readonly id: string;
8
readonly path: string;
@@ -5,4 +10,5 @@ export interface NativeReviewDiffFile {
10
readonly language: string;
11
readonly additions: number;
12
readonly deletions: number;
13
+ readonly loadContents?: (signal?: AbortSignal) => Promise<NativeReviewDiffSource | null>;
14
}
apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
+40
-41
@@ -36,6 +36,11 @@ import { usePullRequestPermissions } from "./usePullRequestPermissions";
36
import { usePullRequestAction } from "./usePullRequestAction";
37
import { annotatePullRequestDiff, reviewPosition } from "./pullRequestDiffComments";
38
import { usePullRequestFileFilter } from "./usePullRequestFileFilter";
39
+import {
40
+ handlePullRequestDiffDebugEvent,
41
+ pullRequestDiffInitialPosition,
42
+} from "./pullRequestDiffDebug";
43
+import { usePullRequestDiffHighlightFiles } from "./usePullRequestDiffHighlightFiles";
44
import { isPullRequestTestFile } from "./pullRequestFileFilters";
45
import { useFocusEffect, useNavigation, type StaticScreenProps } from "@react-navigation/native";
46
import { RegistryContext, useAtomRefresh } from "@effect/atom-react";
@@ -44,7 +49,7 @@ import { type PullRequestDetail, type PullRequestListEntry } from "@t3tools/cont
49
import { PullRequestOverviewLoading } from "./PullRequestOverviewLoading";
50
import { copyPullRequestLink, sharePullRequestLink } from "./pullRequestLink";
51
import { pullRequestStatus } from "./pullRequestStatus";
47
-import { use, useEffect, useRef, useState } from "react";
52
+import { use, useEffect, useMemo, useRef, useState } from "react";
53
import {
54
Linking,
55
Platform,
@@ -75,7 +80,6 @@ import { composerPullRequests } from "../../state/pull-requests";
80
import { useEnvironmentQuery } from "../../state/query";
81
import { usePullToRefresh } from "../../state/use-pull-to-refresh";
82
import {
78
- isNativeReviewDiffDrawEvent,
83
resolveNativeReviewDiffView,
84
type NativeReviewDiffViewHandle,
85
type NativeReviewDiffViewProps,
@@ -804,12 +808,25 @@ export function PullRequestFileRouteScreen({
808
!result.isPending &&
809
!result.error;
810
const activity = useEnvironmentQuery(composerPullRequests.activity(requestTarget(route.params)));
807
- const baseData = buildNativeReviewDiffData(parsed);
808
- const data = annotatePullRequestDiff(
809
- baseData,
810
- staleDiff || commit ? [] : (activity.data?.reviewThreads ?? []),
811
- commit ? [] : reviewDraft.draft.comments,
812
- diffHead.sha ?? undefined,
811
+ const baseData = useMemo(() => buildNativeReviewDiffData(parsed), [parsed]);
812
+ const highlightFiles = usePullRequestDiffHighlightFiles(route.params, parsed, baseData.files);
813
+ const data = useMemo(
814
+ () =>
815
+ annotatePullRequestDiff(
816
+ { ...baseData, files: highlightFiles },
817
+ staleDiff || commit ? [] : (activity.data?.reviewThreads ?? []),
818
+ commit ? [] : reviewDraft.draft.comments,
819
+ diffHead.sha ?? undefined,
820
+ ),
821
+ [
822
+ baseData,
823
+ highlightFiles,
824
+ staleDiff,
825
+ commit,
826
+ activity.data?.reviewThreads,
827
+ reviewDraft.draft.comments,
828
+ diffHead.sha,
829
+ ],
830
);
831
const viewedIds = data.files
832
.filter((file) => (commit ? commitViewedPaths.has(file.path) : viewed.isViewed(file.path)))
@@ -854,7 +871,9 @@ export function PullRequestFileRouteScreen({
871
const [collapsedIds, setCollapsedIds] = useState<readonly string[]>(EMPTY_IDS);
872
const [visibleFileId, setVisibleFileId] = useState<string | null>(null);
873
const nativeView = useRef<NativeReviewDiffViewHandle>(null);
857
- const jumpStarted = useRef(false);
874
+ // Native applies the entry destination before its first viewport. Imperative
875
+ // jumps below are for subsequent selections and filter changes only.
876
+ const jumpStarted = useRef(true);
877
const lastSelection = useRef({ path: route.params.path, id: route.params.fileSelectionId });
878
useEffect(() => {
879
if (
@@ -902,37 +921,17 @@ export function PullRequestFileRouteScreen({
921
useEffect(() => {
922
if (!targetFile) loadMore();
923
}, [targetFile, loadMore]);
905
- const { onDebug: updateVisibleRange } = bridge;
906
- const onDebug: NonNullable<NativeReviewDiffViewProps["onDebug"]> = (event) => {
907
- const drawn = isNativeReviewDiffDrawEvent(event.nativeEvent);
908
- const decoded =
909
- event.nativeEvent.message === "rows-decoded" && event.nativeEvent.rows === data.rows.length;
910
- if (!drawn && !decoded) return;
911
- // Filtering replaces the native row payload asynchronously. Old draw events
912
- // must not consume the file jump or highlight the new payload's row indices.
913
- if (
914
- typeof event.nativeEvent.totalRows === "number" &&
915
- event.nativeEvent.totalRows !== data.rows.length
916
- )
917
- return;
918
- if (drawn) updateVisibleRange(event);
919
- if (
920
- targetFile &&
921
- !jumpStarted.current &&
922
- nativeView.current &&
923
- (Platform.OS !== "ios" || decoded)
924
- ) {
925
- jumpStarted.current = true;
926
- if (focusIndex >= 0) return;
927
- void nativeView.current.scrollToFile(targetFile.id, false).catch(() => {
928
- jumpStarted.current = false;
929
- });
930
- return;
931
- }
932
- if (!drawn) return;
933
- const lastRow = event.nativeEvent.lastRowIndex;
934
- if (typeof lastRow === "number" && lastRow >= data.rows.length - 40) loadMore();
935
- };
924
+ const onDebug: NonNullable<NativeReviewDiffViewProps["onDebug"]> = (event) =>
925
+ handlePullRequestDiffDebugEvent(event, {
926
+ rowCount: data.rows.length,
927
+ targetFileId: targetFile?.id,
928
+ focusIndex,
929
+ isIos: Platform.OS === "ios",
930
+ nativeView,
931
+ jumpStarted,
932
+ onDebug: bridge.onDebug,
933
+ loadMore,
934
+ });
935
const onToggleFile: NonNullable<NativeReviewDiffViewProps["onToggleFile"]> = (event) => {
936
const id = event.nativeEvent.fileId;
937
if (!id) return;
@@ -1114,7 +1113,7 @@ export function PullRequestFileRouteScreen({
1113
{NativeDiffView && data.rows.length && !seekingFile ? (
1114
<View className="flex-1" collapsable={false}>
1115
<NativeDiffView
1117
- initialRowIndex={focusIndex >= 0 ? Math.max(0, focusIndex - 3) : undefined}
1116
+ {...pullRequestDiffInitialPosition(targetFile?.id, focusIndex)}
1117
nativeViewRef={nativeView}
1118
refreshing={result.refreshing}
1119
onPullToRefresh={result.onPullRefresh}
apps/mobile/src/features/pull-requests/pullRequestDiffComments.test.ts
+11
@@ -24,6 +24,17 @@ const thread: PullRequestReviewThread = {
24
comments: [],
25
};
26
describe("PR comments in continuous native diffs", () => {
27
+ it("returns unannotated data unchanged without reading or indexing rows", () => {
28
+ const unannotated = {
29
+ ...data,
30
+ get rows(): NativeReviewDiffData["rows"] {
31
+ throw new Error("Empty annotation must not read rows");
32
+ },
33
+ };
34
+ expect(annotatePullRequestDiff(unannotated, [], [], undefined)).toBe(unannotated);
35
+ expect(annotatePullRequestDiff(data, [], [], undefined).rows).toBe(data.rows);
36
+ });
37
+
38
it("anchors old/new lines separately despite identical line numbers", () => {
39
const annotated = annotatePullRequestDiff(
40
data,
apps/mobile/src/features/pull-requests/pullRequestDiffComments.ts
+1
@@ -34,6 +34,7 @@ export function annotatePullRequestDiff(
34
drafts: readonly PendingReviewComment[],
35
headSha: string | undefined,
36
): NativeReviewDiffData {
37
+ if (threads.length === 0 && drafts.length === 0) return data;
38
const anchors = new Map<string, NativeReviewDiffRow[]>();
39
const firstByPath = new Map<string, NativeReviewDiffRow>();
40
const lines = new Map<string, NativeReviewDiffRow>();
apps/mobile/src/features/pull-requests/pullRequestDiffDebug.test.ts
new
+82
@@ -0,0 +1,82 @@
1
+import { expect, it, vi } from "vite-plus/test";
2
+
3
+vi.mock("react-native", () => ({ View: () => null }));
4
+vi.mock("expo", () => ({ requireNativeView: vi.fn() }));
5
+vi.mock("../../components/ui/EmptyState", () => ({ EmptyState: () => null }));
6
+
7
+import {
8
+ handlePullRequestDiffDebugEvent,
9
+ pullRequestDiffInitialPosition,
10
+} from "./pullRequestDiffDebug";
11
+import { createReviewDiffHighlightScheduler } from "../review/reviewDiffHighlightScheduler";
12
+import type { NativeReviewDiffViewProps } from "../diffs/nativeReviewDiffSurface";
13
+
14
+it("enters at a file header without changing guide focus positioning", () => {
15
+ expect(pullRequestDiffInitialPosition("last-file", -1)).toEqual({
16
+ initialFileId: "last-file",
17
+ initialRowIndex: -1,
18
+ });
19
+ expect(pullRequestDiffInitialPosition("last-file", 904)).toEqual({
20
+ initialFileId: "",
21
+ initialRowIndex: 901,
22
+ });
23
+ expect(pullRequestDiffInitialPosition(undefined, -1)).toEqual({
24
+ initialFileId: "",
25
+ initialRowIndex: -1,
26
+ });
27
+});
28
+
29
+it.each([true, false])(
30
+ "starts warm highlighting at the declared file without a JS jump (iOS: %s)",
31
+ async (isIos) => {
32
+ vi.useFakeTimers();
33
+ // A warm engine can issue its source RPC immediately when the scheduler flushes.
34
+ const sourceRequest = vi.fn();
35
+ const scheduler = createReviewDiffHighlightScheduler(sourceRequest);
36
+ const scrollToFile = vi.fn(async () => {});
37
+ const loadMore = vi.fn();
38
+ const jumpStarted = { current: true };
39
+ const onDebug: NonNullable<NativeReviewDiffViewProps["onDebug"]> = ({ nativeEvent }) => {
40
+ if (nativeEvent.message === "visible-range")
41
+ scheduler.update({
42
+ firstRowIndex: nativeEvent.firstRowIndex as number,
43
+ lastRowIndex: nativeEvent.lastRowIndex as number,
44
+ });
45
+ };
46
+ const emit = (nativeEvent: Record<string, unknown>) =>
47
+ handlePullRequestDiffDebugEvent({ nativeEvent } as Parameters<typeof onDebug>[0], {
48
+ rowCount: 1000,
49
+ targetFileId: "last-file",
50
+ focusIndex: -1,
51
+ isIos,
52
+ nativeView: { current: { scrollToFile, scrollToTop: vi.fn(async () => {}) } },
53
+ jumpStarted,
54
+ onDebug,
55
+ loadMore,
56
+ });
57
+ try {
58
+ const position = pullRequestDiffInitialPosition("last-file", -1);
59
+ emit({ message: "rows-decoded", rows: 1000 });
60
+ // Native applies the declared file before publishing its viewport. A later
61
+ // imperative bridge command cannot retract an RPC started from a top range.
62
+ const first = position.initialFileId === "last-file" ? 900 : 0;
63
+ emit({
64
+ message: "visible-range",
65
+ firstRowIndex: first,
66
+ lastRowIndex: first + 40,
67
+ totalRows: 1000,
68
+ });
69
+ await vi.runOnlyPendingTimersAsync();
70
+ expect(sourceRequest.mock.calls).toEqual([[{ firstRowIndex: 900, lastRowIndex: 940 }]]);
71
+ expect(scrollToFile).not.toHaveBeenCalled();
72
+ // Near-end pagination and stale-payload filtering still use native ranges.
73
+ emit({ message: "visible-range", firstRowIndex: 950, lastRowIndex: 990, totalRows: 999 });
74
+ expect(loadMore).not.toHaveBeenCalled();
75
+ emit({ message: "visible-range", firstRowIndex: 950, lastRowIndex: 990, totalRows: 1000 });
76
+ expect(loadMore).toHaveBeenCalledOnce();
77
+ } finally {
78
+ scheduler.cancel();
79
+ vi.useRealTimers();
80
+ }
81
+ },
82
+);
apps/mobile/src/features/pull-requests/pullRequestDiffDebug.ts
new
+63
@@ -0,0 +1,63 @@
1
+import type { RefObject } from "react";
2
+
3
+import {
4
+ isNativeReviewDiffDrawEvent,
5
+ type NativeReviewDiffViewHandle,
6
+ type NativeReviewDiffViewProps,
7
+} from "../diffs/nativeReviewDiffSurface";
8
+
9
+export function pullRequestDiffInitialPosition(
10
+ targetFileId: string | undefined,
11
+ focusIndex: number,
12
+): Pick<NativeReviewDiffViewProps, "initialRowIndex" | "initialFileId"> {
13
+ // Explicit empty values also clear a previous destination on a reused native view.
14
+ return {
15
+ initialRowIndex: focusIndex >= 0 ? Math.max(0, focusIndex - 3) : -1,
16
+ initialFileId: focusIndex >= 0 ? "" : (targetFileId ?? ""),
17
+ };
18
+}
19
+
20
+export function handlePullRequestDiffDebugEvent(
21
+ event: Parameters<NonNullable<NativeReviewDiffViewProps["onDebug"]>>[0],
22
+ input: {
23
+ readonly rowCount: number;
24
+ readonly targetFileId: string | undefined;
25
+ readonly focusIndex: number;
26
+ readonly isIos: boolean;
27
+ readonly nativeView: RefObject<NativeReviewDiffViewHandle | null>;
28
+ readonly jumpStarted: RefObject<boolean>;
29
+ readonly onDebug: NonNullable<NativeReviewDiffViewProps["onDebug"]>;
30
+ readonly loadMore: () => void;
31
+ },
32
+) {
33
+ const drawn = isNativeReviewDiffDrawEvent(event.nativeEvent);
34
+ // Delivery outcomes and content mounts must reach the bridge even before rows decode.
35
+ if (!drawn) input.onDebug(event);
36
+ const decoded =
37
+ event.nativeEvent.message === "rows-decoded" && event.nativeEvent.rows === input.rowCount;
38
+ if (!drawn && !decoded) return;
39
+ // Filtering replaces the native row payload asynchronously. Old draw events
40
+ // must not consume the file jump or highlight the new payload's row indices.
41
+ if (
42
+ typeof event.nativeEvent.totalRows === "number" &&
43
+ event.nativeEvent.totalRows !== input.rowCount
44
+ )
45
+ return;
46
+ if (drawn) input.onDebug(event);
47
+ if (
48
+ input.targetFileId &&
49
+ !input.jumpStarted.current &&
50
+ input.nativeView.current &&
51
+ (!input.isIos || decoded)
52
+ ) {
53
+ input.jumpStarted.current = true;
54
+ if (input.focusIndex >= 0) return;
55
+ void input.nativeView.current.scrollToFile(input.targetFileId, false).catch(() => {
56
+ input.jumpStarted.current = false;
57
+ });
58
+ return;
59
+ }
60
+ if (!drawn) return;
61
+ const lastRow = event.nativeEvent.lastRowIndex;
62
+ if (typeof lastRow === "number" && lastRow >= input.rowCount - 40) input.loadMore();
63
+}
apps/mobile/src/features/pull-requests/pullRequestDiffHighlightFiles.test.ts
new
+440
@@ -0,0 +1,440 @@
1
+import { highlightCode } from "../../lib/highlights";
2
+
3
+import { EnvironmentId, ProjectId } from "@t3tools/contracts";
4
+import { expect, it, vi } from "vite-plus/test";
5
+import { AsyncResult } from "effect/reactivity";
6
+
7
+import { highlightNativeReviewDiffVisibleRows } from "../diffs/nativeReviewDiffHighlighter";
8
+import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes";
9
+import type { ReviewParsedDiff, ReviewRenderableFile } from "../review/reviewModel";
10
+import { combinePullRequestDiffPages } from "./pullRequestDiffPages";
11
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
12
+import {
13
+ createPullRequestDiffHighlightCache,
14
+ createPullRequestDiffHighlightFiles,
15
+} from "./pullRequestDiffHighlightFiles";
16
+
17
+vi.mock("expo", async () => {
18
+ const { createWasmHighlightsModule } = await import("../../lib/highlights.testing");
19
+ return { requireOptionalNativeModule: () => createWasmHighlightsModule() };
20
+});
21
+
22
+const target = {
23
+ environmentId: EnvironmentId.make("remote-environment"),
24
+ input: {
25
+ projectId: ProjectId.make("project"),
26
+ repository: "org/repo",
27
+ number: 23,
28
+ host: "forge.example.com",
29
+ },
30
+};
31
+
32
+function file(id: string, path: string, previousPath: string | null): ReviewRenderableFile {
33
+ return {
34
+ id,
35
+ path,
36
+ previousPath,
37
+ cacheKey: id,
38
+ changeType: previousPath ? "rename-changed" : "change",
39
+ additions: 1,
40
+ deletions: 1,
41
+ languageHint: "typescript",
42
+ additionLines: [],
43
+ deletionLines: [],
44
+ rows: [],
45
+ };
46
+}
47
+
48
+function setup() {
49
+ const parsed = {
50
+ kind: "files",
51
+ fileCount: 2,
52
+ additions: 2,
53
+ deletions: 2,
54
+ notice: null,
55
+ files: [file("selected", "renderer.ts", "old-renderer.ts"), file("unseen", "unseen.ts", null)],
56
+ } satisfies ReviewParsedDiff;
57
+ const files: NativeReviewDiffFile[] = parsed.files.map((file) => ({
58
+ id: file.id,
59
+ path: file.path,
60
+ language: "typescript",
61
+ additions: 1,
62
+ deletions: 1,
63
+ }));
64
+ return { parsed, files };
65
+}
66
+
67
+it("loads only the selected PR file using its remote target, commit, and rename paths", async () => {
68
+ const { parsed, files } = setup();
69
+ const contents = {
70
+ oldContents: "/* Previous renderer\nconst removed = 1;\n*/",
71
+ newContents: "const heading = `Current renderer\nWelcome to the workspace.\n`;",
72
+ };
73
+ const fetch = vi.fn(async () => AsyncResult.success(contents));
74
+ const loaded = createPullRequestDiffHighlightFiles(
75
+ { target, commit: "abc123" },
76
+ parsed,
77
+ files,
78
+ fetch,
79
+ );
80
+ expect(fetch).not.toHaveBeenCalled();
81
+ const rows = [
82
+ {
83
+ kind: "line" as const,
84
+ id: "removed",
85
+ fileId: "selected",
86
+ change: "delete" as const,
87
+ oldLineNumber: 2,
88
+ newLineNumber: null,
89
+ content: "const removed = 1;",
90
+ },
91
+ {
92
+ kind: "line" as const,
93
+ id: "added",
94
+ fileId: "selected",
95
+ change: "add" as const,
96
+ oldLineNumber: null,
97
+ newLineNumber: 2,
98
+ content: "Welcome to the workspace.",
99
+ },
100
+ {
101
+ kind: "line" as const,
102
+ id: "unseen",
103
+ fileId: "unseen",
104
+ change: "add" as const,
105
+ oldLineNumber: null,
106
+ newLineNumber: 1,
107
+ content: "export const unseen = true;",
108
+ },
109
+ ];
110
+ const result = await highlightNativeReviewDiffVisibleRows({
111
+ rows,
112
+ files: loaded,
113
+ scheme: "dark",
114
+ firstRowIndex: 0,
115
+ lastRowIndex: 1,
116
+ overscanRows: 0,
117
+ });
118
+ expect(fetch.mock.calls).toEqual([
119
+ [
120
+ {
121
+ ...target,
122
+ input: {
123
+ ...target.input,
124
+ commit: "abc123",
125
+ changeType: "rename-changed",
126
+ oldPath: "old-renderer.ts",
127
+ newPath: "renderer.ts",
128
+ },
129
+ },
130
+ ],
131
+ ]);
132
+ expect(result.tokensByRowId.removed).toEqual(
133
+ highlightCode(contents.oldContents, "typescript", "dark")[1],
134
+ );
135
+ expect(result.tokensByRowId.added).toEqual(
136
+ highlightCode(contents.newContents, "typescript", "dark")[1],
137
+ );
138
+ expect(result.tokensByRowId.unseen).toBeUndefined();
139
+ expect(await loaded[0]!.loadContents!()).toBe(contents);
140
+ expect(fetch).toHaveBeenCalledTimes(1);
141
+});
142
+
143
+it.each([null, "Some file contents are unavailable"])(
144
+ "retains fetched and unavailable source when another diff page is appended (notice: %s)",
145
+ async (notice) => {
146
+ const { parsed, files } = setup();
147
+ const contents = { oldContents: "before", newContents: "after" };
148
+ const fetch = vi.fn(async ({ input }: { input: { newPath: string } }) => {
149
+ if (input.newPath === "unseen.ts") throw { reason: "unsupported" };
150
+ return AsyncResult.success(contents);
151
+ });
152
+ const cache = createPullRequestDiffHighlightCache();
153
+ const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);
154
+ expect(await first[0]!.loadContents!()).toBe(contents);
155
+ expect(await first[1]!.loadContents!()).toBeNull();
156
+ const appended = file("appended", "appended.ts", null);
157
+ const next = createPullRequestDiffHighlightFiles(
158
+ { target },
159
+ { ...parsed, files: [...parsed.files, appended], fileCount: 3, notice },
160
+ [...files, { ...files[1]!, id: appended.id, path: appended.path }],
161
+ fetch,
162
+ cache,
163
+ );
164
+ expect(await next[0]!.loadContents!()).toBe(contents);
165
+ expect(await next[1]!.loadContents!()).toBeNull();
166
+ expect(fetch).toHaveBeenCalledTimes(2);
167
+ },
168
+);
169
+
170
+it("does not reuse source from another diff snapshot", async () => {
171
+ const { parsed, files } = setup();
172
+ const fetch = vi.fn(async () =>
173
+ AsyncResult.success({ oldContents: "", newContents: "const current = true;" }),
174
+ );
175
+ const cache = createPullRequestDiffHighlightCache();
176
+ const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);
177
+ const second = createPullRequestDiffHighlightFiles(
178
+ { target },
179
+ { ...parsed, files: parsed.files.map((file) => ({ ...file })) },
180
+ files,
181
+ fetch,
182
+ cache,
183
+ );
184
+ await first[0]!.loadContents!();
185
+ await second[0]!.loadContents!();
186
+ expect(fetch).toHaveBeenCalledTimes(2);
187
+});
188
+
189
+it.each([
190
+ [
191
+ "environment",
192
+ { target: { ...target, environmentId: EnvironmentId.make("other") }, commit: "abc" },
193
+ ],
194
+ [
195
+ "project",
196
+ {
197
+ target: { ...target, input: { ...target.input, projectId: ProjectId.make("other") } },
198
+ commit: "abc",
199
+ },
200
+ ],
201
+ [
202
+ "repository",
203
+ { target: { ...target, input: { ...target.input, repository: "other/repo" } }, commit: "abc" },
204
+ ],
205
+ ["PR", { target: { ...target, input: { ...target.input, number: 24 } }, commit: "abc" }],
206
+ [
207
+ "host",
208
+ { target: { ...target, input: { ...target.input, host: "other.example.com" } }, commit: "abc" },
209
+ ],
210
+ ["commit", { target, commit: "def" }],
211
+ ["unpinned commit", { target }],
212
+])("isolates retained file objects after changing the %s", async (_name, source) => {
213
+ const { parsed, files } = setup();
214
+ const cache = createPullRequestDiffHighlightCache();
215
+ const previous = { oldContents: "", newContents: "previous" };
216
+ const current = { oldContents: "", newContents: "current" };
217
+ const fetch = vi
218
+ .fn()
219
+ .mockResolvedValueOnce(AsyncResult.success(previous))
220
+ .mockResolvedValueOnce(AsyncResult.success(current));
221
+ const first = createPullRequestDiffHighlightFiles(
222
+ { target, commit: "abc" },
223
+ parsed,
224
+ files,
225
+ fetch,
226
+ cache,
227
+ );
228
+ expect(await first[0]!.loadContents!()).toBe(previous);
229
+ const second = createPullRequestDiffHighlightFiles(source, parsed, files, fetch, cache);
230
+ expect(await second[0]!.loadContents!()).toBe(current);
231
+ expect(await first[0]!.loadContents!()).toBe(previous);
232
+ expect(fetch).toHaveBeenCalledTimes(2);
233
+});
234
+
235
+it("does not reuse a replaced later-page file with the same ID", async () => {
236
+ const { parsed, files } = setup();
237
+ const cache = createPullRequestDiffHighlightCache();
238
+ const previous = { oldContents: "", newContents: "previous" };
239
+ const current = { oldContents: "", newContents: "current" };
240
+ const fetch = vi
241
+ .fn()
242
+ .mockResolvedValueOnce(AsyncResult.success(previous))
243
+ .mockResolvedValueOnce(AsyncResult.success(current));
244
+ const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);
245
+ expect(await first[1]!.loadContents!()).toBe(previous);
246
+ const second = createPullRequestDiffHighlightFiles(
247
+ { target },
248
+ { ...parsed, files: [parsed.files[0]!, { ...parsed.files[1]! }] },
249
+ files,
250
+ fetch,
251
+ cache,
252
+ );
253
+ expect(await second[1]!.loadContents!()).toBe(current);
254
+ expect(fetch).toHaveBeenCalledTimes(2);
255
+});
256
+
257
+it.each(["permanent", "transient"])(
258
+ "does not reuse a replaced later-page file's %s failure with the same ID",
259
+ async (failure) => {
260
+ const { parsed, files } = setup();
261
+ const cache = createPullRequestDiffHighlightCache();
262
+ const contents = { oldContents: "", newContents: "current" };
263
+ const fetch = vi.fn(async () => AsyncResult.success(contents));
264
+ const error = failure === "permanent" ? { reason: "unsupported" } : new Error("Offline");
265
+ fetch.mockRejectedValueOnce(error);
266
+ if (failure === "transient") fetch.mockRejectedValueOnce(error);
267
+ const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);
268
+ if (failure === "transient") await expect(first[1]!.loadContents!()).rejects.toThrow("Offline");
269
+ expect(await first[1]!.loadContents!()).toBeNull();
270
+ const second = createPullRequestDiffHighlightFiles(
271
+ { target },
272
+ { ...parsed, files: [parsed.files[0]!, { ...parsed.files[1]! }] },
273
+ files,
274
+ fetch,
275
+ cache,
276
+ );
277
+ expect(await second[1]!.loadContents!()).toBe(contents);
278
+ expect(await first[1]!.loadContents!()).toBeNull();
279
+ expect(fetch).toHaveBeenCalledTimes(failure === "permanent" ? 2 : 3);
280
+ },
281
+);
282
+
283
+it("does not reuse reconstructed source after an appended page makes completeness uncertain", async () => {
284
+ const { parsed, files } = setup();
285
+ const cache = createPullRequestDiffHighlightCache();
286
+ const reconstructed = { oldContents: "", newContents: "reconstructed" };
287
+ const authoritative = { oldContents: "", newContents: "authoritative" };
288
+ parsed.files[0] = { ...parsed.files[0]!, completePatchSource: () => reconstructed };
289
+ const fetch = vi.fn(async () => AsyncResult.success(authoritative));
290
+ const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);
291
+ expect(await first[0]!.loadContents!()).toBe(reconstructed);
292
+ const next = createPullRequestDiffHighlightFiles(
293
+ { target },
294
+ { ...parsed, notice: "Some file contents are unavailable" },
295
+ files,
296
+ fetch,
297
+ cache,
298
+ );
299
+ expect(await next[0]!.loadContents!()).toBe(authoritative);
300
+ expect(fetch).toHaveBeenCalledOnce();
301
+});
302
+
303
+it.each([
304
+ ["characters", 2, 4_500_000],
305
+ ["file count", 5, 1],
306
+])(
307
+ "shares the source cache's aggregate %s budget across appended pages",
308
+ async (_name, count, size) => {
309
+ const { parsed, files } = setup();
310
+ const cache = createPullRequestDiffHighlightCache();
311
+ const contents = { oldContents: "", newContents: "x".repeat(size) };
312
+ const fetch = vi.fn(async () => AsyncResult.success(contents));
313
+ const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);
314
+ expect(await first[0]!.loadContents!()).toBe(contents);
315
+ let next = first;
316
+ for (let i = 1; i < count; i++) {
317
+ const appended = file(`page-${i}`, `page-${i}.ts`, null);
318
+ parsed.files.push(appended);
319
+ files.push({ ...files[0]!, id: appended.id, path: appended.path });
320
+ next = createPullRequestDiffHighlightFiles(
321
+ { target },
322
+ { ...parsed },
323
+ [...files],
324
+ fetch,
325
+ cache,
326
+ );
327
+ expect(await next.at(-1)!.loadContents!()).toBe(contents);
328
+ }
329
+ expect(fetch).toHaveBeenCalledTimes(count);
330
+ expect(await next[0]!.loadContents!()).toBe(contents);
331
+ expect(fetch).toHaveBeenCalledTimes(count + 1);
332
+ },
333
+);
334
+
335
+function addedPatch(body: string, header = "@@ -0,0 +1,2 @@") {
336
+ return `diff --git a/file.c b/file.c\nnew file mode 100644\n--- /dev/null\n+++ b/file.c\n${header}\n${body}`;
337
+}
338
+
339
+function loadPatch(patch: string, truncated = false) {
340
+ const parsed = combinePullRequestDiffPages(
341
+ [{ cursor: null, result: { patch, truncated, nextCursor: null } }],
342
+ new WeakMap(),
343
+ "complete-source",
344
+ sourceControlClients.get("github").changeRequest,
345
+ );
346
+ if (parsed.kind !== "files") throw new Error("Expected parsed files");
347
+ const files = parsed.files.map((file) => ({
348
+ id: file.id,
349
+ path: file.path,
350
+ language: "c" as const,
351
+ additions: file.additions,
352
+ deletions: file.deletions,
353
+ }));
354
+ const authoritative = { oldContents: "provider old", newContents: "provider new" };
355
+ const fetch = vi.fn(async () => AsyncResult.success(authoritative));
356
+ const loaded = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch);
357
+ return { loaded, fetch, authoritative };
358
+}
359
+
360
+it.each([0, 1])(
361
+ "loads a complete 100k-line addition with empty-side start %s beyond the RPC cap",
362
+ async (emptyStart) => {
363
+ const source = "/* generated C */ int value = 1;\n".repeat(100_000);
364
+ const body = source.replace(/^/gm, "+").slice(0, -1);
365
+ const { loaded, fetch } = loadPatch(addedPatch(body, `@@ -${emptyStart},0 +1,100000 @@`));
366
+ expect(source.length).toBeGreaterThan(1_048_576);
367
+ const contents = await loaded[0]!.loadContents!();
368
+ expect(contents?.oldContents).toBe("");
369
+ expect(contents?.newContents.length).toBe(source.length);
370
+ expect(contents?.newContents === source).toBe(true);
371
+ expect(fetch).not.toHaveBeenCalled();
372
+ },
373
+);
374
+
375
+it.each([
376
+ ["LF", "+first\n+last\n", "first\nlast\n"],
377
+ ["CRLF", "+first\r\n+last\r\n", "first\r\nlast\r\n"],
378
+ ["missing EOF newline", "+first\r\n+last\n\\ No newline at end of file\n", "first\r\nlast"],
379
+ ["final bare CR", "+first\r\n+last\r\n\\ No newline at end of file\n", "first\r\nlast\r"],
380
+])("preserves %s for complete additions and deletions", async (_name, body, source) => {
381
+ for (const emptyStart of [0, 1]) {
382
+ const added = addedPatch(body, `@@ -${emptyStart},0 +1,2 @@`);
383
+ const deleted = added
384
+ .replace("new file mode", "deleted file mode")
385
+ .replace("--- /dev/null\n+++ b/file.c", "--- a/file.c\n+++ /dev/null")
386
+ .replace(`@@ -${emptyStart},0 +1,2 @@`, `@@ -1,2 +${emptyStart},0 @@`);
387
+ const deletionPatch = deleted.replace(body, body.replace(/\+/g, "-"));
388
+ for (const [patch, expected] of [
389
+ [added, { oldContents: "", newContents: source }],
390
+ [deletionPatch, { oldContents: source, newContents: "" }],
391
+ ] as const) {
392
+ const { loaded, fetch } = loadPatch(patch);
393
+ expect(await loaded[0]!.loadContents!()).toEqual(expected);
394
+ expect(fetch).not.toHaveBeenCalled();
395
+ }
396
+ }
397
+});
398
+
399
+it.each([
400
+ ["too few lines", addedPatch("+first\n", "@@ -0,0 +1,2 @@")],
401
+ ["too many lines", addedPatch("+first\n+last\n", "@@ -0,0 +1 @@")],
402
+ ["zero repaired count", addedPatch("+first\n+last\n", "@@ -0,0 +1,0 @@")],
403
+ ["unterminated patch line", addedPatch("+first\n+last")],
404
+ ["missing count", addedPatch("+first\n+last\n", "@@ -0,0 +1, @@")],
405
+ ["gap", addedPatch("+first\n+last\n", "@@ -0,0 +2,2 @@")],
406
+ ["invalid empty-side start", addedPatch("+first\n+last\n", "@@ -2,0 +1,2 @@")],
407
+ ["converted underfull hunk", addedPatch("+first\n", "@@ -1,0 +1,2 @@")],
408
+ ["converted overfull hunk", addedPatch("+first\n+last\n", "@@ -1,0 +1 @@")],
409
+ ["converted nonempty old side", addedPatch("+first\n+last\n", "@@ -1,1 +1,2 @@")],
410
+ ["context", addedPatch(" first\n+last\n", "@@ -1 +1,2 @@")],
411
+ ["mixed sides", addedPatch("-first\n+last\n", "@@ -1 +1 @@")],
412
+ ["second hunk", addedPatch("+first\n@@ -0,0 +2 @@\n+last\n", "@@ -0,0 +1 @@")],
413
+ ["early EOF marker", addedPatch("+first\n\\ No newline at end of file\n+last\n")],
414
+ ["unknown marker", addedPatch("+first\n+last\n\\ unknown\n")],
415
+ ["trailing garbage", addedPatch("+first\n+last\nignored\n")],
416
+ ["submodule", addedPatch("+first\n+last\n").replace("100644", "160000")],
417
+ [
418
+ "binary",
419
+ addedPatch("+first\n+last\n").replace("--- /dev/null", "Binary files differ\n--- /dev/null"),
420
+ ],
421
+ ["changed", addedPatch("+first\n+last\n").replace("new file mode 100644\n", "")],
422
+ [
423
+ "rename",
424
+ addedPatch("+first\n+last\n").replace(
425
+ "new file mode 100644",
426
+ "similarity index 50%\nrename from old.c\nrename to file.c",
427
+ ),
428
+ ],
429
+ ["truncation marker", addedPatch("+first\n+last\n\n[truncated]\n")],
430
+])("uses authoritative RPC source when completeness is unproven: %s", async (_name, patch) => {
431
+ const { loaded, fetch, authoritative } = loadPatch(patch);
432
+ expect(await loaded[0]!.loadContents!()).toBe(authoritative);
433
+ expect(fetch).toHaveBeenCalledOnce();
434
+});
435
+
436
+it("rejects a complete-looking patch when the provider marks any page truncated", async () => {
437
+ const { loaded, fetch, authoritative } = loadPatch(addedPatch("+first\n+last\n"), true);
438
+ expect(await loaded[0]!.loadContents!()).toBe(authoritative);
439
+ expect(fetch).toHaveBeenCalledOnce();
440
+});
apps/mobile/src/features/pull-requests/pullRequestDiffHighlightFiles.ts
new
+113
@@ -0,0 +1,113 @@
1
+import {
2
+ squashAtomCommandFailure,
3
+ type AtomCommandResult,
4
+} from "@t3tools/client-runtime/state/runtime";
5
+import type {
6
+ PullRequestDiffFileContentsInput,
7
+ PullRequestDiffFileContentsResult,
8
+} from "@t3tools/contracts";
9
+
10
+import { createNativeReviewDiffSourceLoader } from "../diffs/nativeReviewDiffSource";
11
+import {
12
+ diffHighlightTraceHash,
13
+ diffHighlightTraceId,
14
+ traceDiffHighlight,
15
+} from "../diffs/nativeReviewDiffTrace";
16
+import type { NativeReviewDiffFile, NativeReviewDiffSource } from "../diffs/nativeReviewDiffTypes";
17
+import type { ReviewParsedDiff, ReviewRenderableFile } from "../review/reviewModel";
18
+import type { pullRequestTarget } from "./usePullRequestDiff";
19
+
20
+type FetchContents<E> = (request: {
21
+ readonly environmentId: ReturnType<typeof pullRequestTarget>["environmentId"];
22
+ readonly input: PullRequestDiffFileContentsInput;
23
+}) => Promise<AtomCommandResult<PullRequestDiffFileContentsResult, E>>;
24
+
25
+type SourceRequest = () => Promise<NativeReviewDiffSource>;
26
+
27
+interface SourceSnapshot {
28
+ readonly firstFile: ReviewRenderableFile;
29
+ readonly scope: string;
30
+ readonly load: ReturnType<typeof createNativeReviewDiffSourceLoader<SourceRequest>>;
31
+ readonly requests: WeakMap<
32
+ ReviewRenderableFile,
33
+ { readonly completePatch: boolean; readonly request: SourceRequest }
34
+ >;
35
+}
36
+
37
+export function createPullRequestDiffHighlightCache(): { snapshot?: SourceSnapshot } {
38
+ return {};
39
+}
40
+
41
+export function createPullRequestDiffHighlightFiles<E>(
42
+ source: {
43
+ readonly target: ReturnType<typeof pullRequestTarget>;
44
+ readonly commit?: string;
45
+ },
46
+ parsed: ReviewParsedDiff,
47
+ files: ReadonlyArray<NativeReviewDiffFile>,
48
+ fetchContents: FetchContents<E>,
49
+ cache = createPullRequestDiffHighlightCache(),
50
+): ReadonlyArray<NativeReviewDiffFile> {
51
+ if (parsed.kind !== "files" || !parsed.files[0]) return files;
52
+ const byId = new Map(parsed.files.map((file) => [file.id, file]));
53
+ const { target, commit } = source;
54
+ traceDiffHighlight("source-target", {
55
+ environment: diffHighlightTraceHash(target.environmentId),
56
+ project: diffHighlightTraceHash(target.input.projectId),
57
+ pr: target.input.number,
58
+ gitcafe: target.input.host === "git.cafe",
59
+ });
60
+ const scope = JSON.stringify([
61
+ target.environmentId,
62
+ target.input.projectId,
63
+ target.input.repository,
64
+ target.input.number,
65
+ target.input.host,
66
+ commit,
67
+ ]);
68
+ const firstFile = parsed.files[0];
69
+ // Appended pages share one loader budget; a new first file starts a new snapshot.
70
+ let snapshot = cache.snapshot;
71
+ if (!snapshot || snapshot.firstFile !== firstFile || snapshot.scope !== scope) {
72
+ snapshot = {
73
+ firstFile,
74
+ scope,
75
+ load: createNativeReviewDiffSourceLoader<SourceRequest>((request) => request()),
76
+ requests: new WeakMap(),
77
+ };
78
+ cache.snapshot = snapshot;
79
+ }
80
+ const { load, requests } = snapshot;
81
+ return files.map((nativeFile) => {
82
+ const file = byId.get(nativeFile.id);
83
+ if (!file) return nativeFile;
84
+ const completePatch = parsed.notice === null && !!file.completePatchSource;
85
+ const cached = requests.get(file);
86
+ if (cached?.completePatch === completePatch)
87
+ return { ...nativeFile, loadContents: (signal) => load(cached.request, signal) };
88
+ const request: SourceRequest = async () => {
89
+ if (completePatch && file.completePatchSource) return file.completePatchSource();
90
+ traceDiffHighlight("source-params", {
91
+ file: diffHighlightTraceId(file.id),
92
+ oldPath: diffHighlightTraceHash(file.previousPath ?? file.path),
93
+ newPath: diffHighlightTraceHash(file.path),
94
+ changeType: file.changeType,
95
+ hasCommit: !!commit,
96
+ });
97
+ const result = await fetchContents({
98
+ ...target,
99
+ input: {
100
+ ...target.input,
101
+ ...(commit ? { commit } : {}),
102
+ changeType: file.changeType,
103
+ oldPath: file.previousPath ?? file.path,
104
+ newPath: file.path,
105
+ },
106
+ });
107
+ if (result._tag !== "Success") throw squashAtomCommandFailure(result);
108
+ return result.value;
109
+ };
110
+ requests.set(file, { completePatch, request });
111
+ return { ...nativeFile, loadContents: (signal) => load(request, signal) };
112
+ });
113
+}
apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts
+2
-1
@@ -65,7 +65,8 @@ export function combinePullRequestDiffPages(
65
additions: files.reduce((total, file) => total + file.additions, 0),
66
deletions: files.reduce((total, file) => total + file.deletions, 0),
67
notice:
68
- pages.some((page) => page.result.truncated) || parsed.some((page) => page.kind === "raw")
68
+ pages.some((page) => page.result.truncated) ||
69
+ parsed.some((page) => page.kind === "raw" || (page.kind === "files" && page.notice !== null))
70
? `Some file contents are unavailable. Open the ${terminology.singular} on its provider to see the full changes.`
71
: null,
72
};
apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx
new
+118
@@ -0,0 +1,118 @@
1
+import { RegistryContext } from "@effect/atom-react";
2
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3
+import type { PullRequestDiffResult } from "@t3tools/contracts";
4
+import * as Effect from "effect/Effect";
5
+import { Atom, AtomRegistry } from "effect/reactivity";
6
+import { act, useLayoutEffect } from "react";
7
+import { createRoot } from "react-dom/client";
8
+import { expect, it, vi } from "vite-plus/test";
9
+
10
+const mocks = vi.hoisted(() => ({ diff: vi.fn() }));
11
+vi.mock("../../state/pull-requests", () => ({ composerPullRequests: { diff: mocks.diff } }));
12
+
13
+import { usePullRequestDiff } from "./usePullRequestDiff";
14
+
15
+function patch(path: string, nextCursor: string | null = null): PullRequestDiffResult {
16
+ return {
17
+ patch: `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-old\n+new\n`,
18
+ truncated: false,
19
+ nextCursor,
20
+ };
21
+}
22
+
23
+function setup() {
24
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
25
+ const registry = AtomRegistry.make();
26
+ const requests: {
27
+ cursor: string | null;
28
+ resolve: (value: PullRequestDiffResult) => void;
29
+ reject: (error: Error) => void;
30
+ }[] = [];
31
+ const queries = Atom.family((cursor: string | null) =>
32
+ Atom.make(
33
+ Effect.tryPromise(
34
+ () =>
35
+ new Promise<PullRequestDiffResult>((resolve, reject) => {
36
+ requests.push({ cursor, resolve, reject });
37
+ }),
38
+ ),
39
+ ).pipe(Atom.keepAlive),
40
+ );
41
+ mocks.diff.mockImplementation((target: { input: { cursor?: string } }) =>
42
+ queries(target.input.cursor ?? null),
43
+ );
44
+ const root = createRoot(document.createElement("div"));
45
+ let current: ReturnType<typeof usePullRequestDiff>;
46
+ function Probe() {
47
+ const result = usePullRequestDiff(
48
+ {
49
+ environmentId: "environment",
50
+ projectId: "project",
51
+ repository: "repo",
52
+ number: 1,
53
+ },
54
+ sourceControlClients.get("github").changeRequest,
55
+ );
56
+ useLayoutEffect(() => {
57
+ current = result;
58
+ });
59
+ return null;
60
+ }
61
+ act(() =>
62
+ root.render(
63
+ <RegistryContext.Provider value={registry}>
64
+ <Probe />
65
+ </RegistryContext.Provider>,
66
+ ),
67
+ );
68
+ return {
69
+ requests,
70
+ get current() {
71
+ return current;
72
+ },
73
+ async succeed(index: number, result: PullRequestDiffResult) {
74
+ await act(async () => {
75
+ requests[index]!.resolve(result);
76
+ });
77
+ },
78
+ async fail(index: number) {
79
+ await act(async () => {
80
+ requests[index]!.reject(new Error("Connection lost"));
81
+ });
82
+ },
83
+ [Symbol.dispose]() {
84
+ act(() => root.unmount());
85
+ registry.dispose();
86
+ },
87
+ };
88
+}
89
+
90
+it("retries a failed continuation without discarding loaded files or restarting page one", async () => {
91
+ using screen = setup();
92
+ await screen.succeed(0, patch("first.ts", "second"));
93
+ act(() => screen.current.loadMore());
94
+ await screen.fail(1);
95
+ expect(screen.current.error).not.toBeNull();
96
+ expect(screen.current.patch).toContain("first.ts");
97
+
98
+ act(() => screen.current.refresh());
99
+ expect(screen.requests.map((request) => request.cursor)).toEqual([null, "second", "second"]);
100
+ expect(screen.current.patch).toContain("first.ts");
101
+ await screen.succeed(2, patch("second.ts"));
102
+ expect(screen.current.error).toBeNull();
103
+ expect(screen.current.parsed.kind).toBe("files");
104
+ if (screen.current.parsed.kind !== "files") throw new Error("Expected files");
105
+ expect(screen.current.parsed.files.map((file) => file.path)).toEqual(["first.ts", "second.ts"]);
106
+ expect(screen.current.nextCursor).toBeNull();
107
+});
108
+
109
+it("still refreshes from page one after successfully loading a continuation", async () => {
110
+ using screen = setup();
111
+ await screen.succeed(0, patch("first.ts", "second"));
112
+ act(() => screen.current.loadMore());
113
+ await screen.succeed(1, patch("second.ts"));
114
+ act(() => screen.current.refresh());
115
+ await screen.succeed(2, patch("refreshed.ts"));
116
+ if (screen.current.parsed.kind !== "files") throw new Error("Expected files");
117
+ expect(screen.current.parsed.files.map((file) => file.path)).toEqual(["refreshed.ts"]);
118
+});
apps/mobile/src/features/pull-requests/usePullRequestDiff.ts
+6
-1
@@ -87,10 +87,15 @@ export function usePullRequestDiff(
87
if (!canLoadMore) return;
88
setState({ key, cursor: nextCursor, pages });
89
}, [canLoadMore, key, nextCursor, pages, setState]);
90
+ const { error, refresh: refreshPage } = query;
91
const refresh = useCallback(() => {
92
+ if (cursor !== null && error !== null) {
93
+ refreshPage();
94
+ return;
95
+ }
96
setState({ key, cursor: null, pages: NO_PAGES });
97
refreshFirstPage();
93
- }, [key, refreshFirstPage, setState]);
98
+ }, [cursor, error, refreshPage, key, refreshFirstPage, setState]);
99
const onPullRefresh = useCallback(() => {
100
setState({ key, cursor: null, pages: NO_PAGES });
101
onRefresh();
apps/mobile/src/features/pull-requests/usePullRequestDiffHighlightFiles.ts
new
+78
@@ -0,0 +1,78 @@
1
+import { useMemo } from "react";
2
+import { EnvironmentId } from "@t3tools/contracts";
3
+import * as Option from "effect/Option";
4
+
5
+import { environmentCatalog } from "../../connection/catalog";
6
+import { appAtomRegistry } from "../../state/atom-registry";
7
+import { composerPullRequests } from "../../state/pull-requests";
8
+import { useAtomCommand } from "../../state/use-atom-command";
9
+import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes";
10
+import { diffHighlightTraceHash, traceDiffHighlight } from "../diffs/nativeReviewDiffTrace";
11
+import type { ReviewParsedDiff } from "../review/reviewModel";
12
+import {
13
+ createPullRequestDiffHighlightCache,
14
+ createPullRequestDiffHighlightFiles,
15
+} from "./pullRequestDiffHighlightFiles";
16
+import { pullRequestTarget, type PullRequestDiffParams } from "./usePullRequestDiff";
17
+
18
+function traceSourceEndpoint(environmentId: string, url: string) {
19
+ try {
20
+ const endpoint = new URL(url);
21
+ traceDiffHighlight("source-endpoint", {
22
+ environment: diffHighlightTraceHash(environmentId),
23
+ origin: diffHighlightTraceHash(endpoint.origin),
24
+ port: endpoint.port || (endpoint.protocol === "https:" ? "443" : "80"),
25
+ });
26
+ } catch {
27
+ traceDiffHighlight("source-endpoint-invalid");
28
+ }
29
+}
30
+
31
+export function usePullRequestDiffHighlightFiles(
32
+ params: PullRequestDiffParams,
33
+ parsed: ReviewParsedDiff,
34
+ files: ReadonlyArray<NativeReviewDiffFile>,
35
+) {
36
+ const fetchContents = useAtomCommand(composerPullRequests.diffFileContents, {
37
+ reportFailure: false,
38
+ });
39
+ const { environmentId, projectId, repository, number, host, commit } = params;
40
+ const cache = useMemo(() => createPullRequestDiffHighlightCache(), []);
41
+ return useMemo(() => {
42
+ if (process.env.EXPO_PUBLIC_T3_DIFF_TRACE === "1") {
43
+ const catalog = appAtomRegistry.get(environmentCatalog.catalogValueAtom);
44
+ const entry = catalog.entries.get(EnvironmentId.make(environmentId));
45
+ const profile = entry && Option.getOrUndefined(entry.profile);
46
+ const url =
47
+ entry?.target._tag === "PrimaryConnectionTarget"
48
+ ? entry.target.httpBaseUrl
49
+ : profile?._tag === "BearerConnectionProfile"
50
+ ? profile.httpBaseUrl
51
+ : undefined;
52
+ if (url) {
53
+ traceSourceEndpoint(environmentId, url);
54
+ } else traceDiffHighlight("source-endpoint-unavailable");
55
+ }
56
+ return createPullRequestDiffHighlightFiles(
57
+ {
58
+ target: pullRequestTarget({ environmentId, projectId, repository, number, host }),
59
+ commit,
60
+ },
61
+ parsed,
62
+ files,
63
+ fetchContents,
64
+ cache,
65
+ );
66
+ }, [
67
+ environmentId,
68
+ projectId,
69
+ repository,
70
+ number,
71
+ host,
72
+ commit,
73
+ parsed,
74
+ files,
75
+ fetchContents,
76
+ cache,
77
+ ]);
78
+}
apps/mobile/src/features/review/nativeReviewDiffAdapter.test.ts
+269
-4
@@ -1,11 +1,19 @@
1
-import { describe, expect, it } from "vite-plus/test";
1
+import { describe, expect, it, vi } from "vite-plus/test";
2
+import { diffWordsWithSpace } from "diff";
3
+import { AsyncResult } from "effect/reactivity";
4
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
5
+import { EnvironmentId, ProjectId, type PullRequestDiffResult } from "@t3tools/contracts";
6
7
+import { combinePullRequestDiffPages } from "../pull-requests/pullRequestDiffPages";
8
+import { createPullRequestDiffHighlightFiles } from "../pull-requests/pullRequestDiffHighlightFiles";
9
import {
10
buildNativeReviewDiffData,
11
getCachedNativeReviewDiffData,
12
} from "./nativeReviewDiffAdapter";
13
import type { ReviewInlineComment } from "./reviewCommentSelection";
8
-import { buildReviewParsedDiff } from "./reviewModel";
14
+import { buildReviewParsedDiff, type ReviewParsedDiff } from "./reviewModel";
15
+
16
+vi.mock("diff", { spy: true });
17
18
function makeComment(text: string): ReviewInlineComment {
19
return {
@@ -38,7 +46,202 @@ function filesPatch(paths: ReadonlyArray<string>) {
46
.join("\n");
47
}
48
49
+describe("buildNativeReviewDiffData languages", () => {
50
+ it.each([
51
+ ["js", "javascript"],
52
+ ["cjs", "javascript"],
53
+ ["mjs", "javascript"],
54
+ ["jsx", "jsx"],
55
+ ["ts", "typescript"],
56
+ ["mts", "typescript"],
57
+ ["cts", "typescript"],
58
+ ["tsx", "tsx"],
59
+ ])("assigns %s files their syntax language when deleted", (extension, language) => {
60
+ const path = `scripts/dev-runner.${extension}`;
61
+ const data = buildNativeReviewDiffData(
62
+ buildReviewParsedDiff(
63
+ [
64
+ `diff --git a/${path} b/${path}`,
65
+ "deleted file mode 100644",
66
+ `--- a/${path}`,
67
+ "+++ /dev/null",
68
+ "@@ -1,2 +0,0 @@",
69
+ '-import process from "node:process";',
70
+ "-const port = process.env.PORT;",
71
+ "",
72
+ ].join("\n"),
73
+ "deleted-script-language",
74
+ ),
75
+ );
76
+
77
+ expect(data.files).toMatchObject([{ path, language }]);
78
+ expect(data.rows.filter((row) => row.kind === "line")).toMatchObject([
79
+ { content: 'import process from "node:process";', change: "delete" },
80
+ { content: "const port = process.env.PORT;", change: "delete" },
81
+ ]);
82
+ });
83
+});
84
+
85
describe("getCachedNativeReviewDiffData", () => {
86
+ it("keeps compact identities aligned through page append, filtering, comments, and source lookup", async () => {
87
+ const scope = JSON.stringify({ remote: 'long-target\\"'.repeat(100) });
88
+ const cache = new WeakMap<PullRequestDiffResult, ReviewParsedDiff>();
89
+ const firstPage = {
90
+ cursor: null,
91
+ result: {
92
+ patch: filesPatch(["example.ts", "hidden.test.ts"]),
93
+ truncated: false,
94
+ nextCursor: "next",
95
+ },
96
+ };
97
+ const terminology = sourceControlClients.get("github").changeRequest;
98
+ const first = combinePullRequestDiffPages([firstPage], cache, scope, terminology);
99
+ if (first.kind !== "files") throw new Error("Expected parsed first page");
100
+ const before = getCachedNativeReviewDiffData({ parsedDiff: first });
101
+ const selectedRowId = before.rows.find((row) => row.kind === "line")!.id;
102
+ const combined = combinePullRequestDiffPages(
103
+ [
104
+ firstPage,
105
+ {
106
+ cursor: "next",
107
+ result: { patch: filesPatch(["last.ts"]), truncated: false, nextCursor: null },
108
+ },
109
+ ],
110
+ cache,
111
+ scope,
112
+ terminology,
113
+ );
114
+ if (combined.kind !== "files") throw new Error("Expected parsed appended pages");
115
+ expect(combined.files[0]).toBe(first.files[0]);
116
+ const filtered = {
117
+ ...combined,
118
+ files: combined.files.filter((file) => !file.path.includes(".test.")),
119
+ };
120
+ const input = { parsedDiff: filtered, comments: [makeComment("Feedback")] };
121
+ const data = getCachedNativeReviewDiffData(input);
122
+ expect(getCachedNativeReviewDiffData(input)).toBe(data);
123
+ expect(new Set(data.rows.map((row) => row.id)).size).toBe(data.rows.length);
124
+ expect(data.rows.find((row) => row.id === selectedRowId)).toBe(
125
+ before.rows.find((row) => row.id === selectedRowId),
126
+ );
127
+ // IDs used by native initialFileId/collapse and parsed source lookup share one namespace.
128
+ expect(data.files.map((file) => file.id)).toEqual(filtered.files.map((file) => file.id));
129
+ for (const file of filtered.files) {
130
+ const header = data.rows.find((row) => row.kind === "file" && row.fileId === file.id)!;
131
+ expect(header.filePath).toBe(file.path);
132
+ const lines = file.rows.filter((row) => row.kind === "line");
133
+ for (const [lineIndex, line] of lines.entries()) {
134
+ const nativeId = data.rowIdByCommentLineId.get(line.id)!;
135
+ const row = data.rows.find((row) => row.id === nativeId)!;
136
+ expect(row.fileId).toBe(file.id);
137
+ expect(row.content).toBe(line.content);
138
+ expect(nativeId.length).toBeLessThan(64);
139
+ const target = data.commentTargetsByRowId.get(nativeId)!;
140
+ expect(target.filePath).toBe(file.path);
141
+ expect(target.lines[lineIndex]).toBe(line);
142
+ expect(target.lineIndex).toBe(lineIndex);
143
+ expect(row.wordDiffRanges?.length).toBeGreaterThan(0);
144
+ expect(
145
+ row.wordDiffRanges?.map((range) => row.content!.slice(range.start, range.end)),
146
+ ).toEqual([line.change === "delete" ? "before" : "after"]);
147
+ }
148
+ }
149
+ const commentIndex = data.rows.findIndex((row) => row.id === "comment-1");
150
+ expect(data.rows[commentIndex - 1]!.id).toBe(selectedRowId);
151
+ expect(data.rows[commentIndex]!.fileId).toBe(first.files[0]!.id);
152
+
153
+ const target = {
154
+ environmentId: EnvironmentId.make("remote"),
155
+ input: {
156
+ projectId: ProjectId.make("project"),
157
+ repository: "org/repo",
158
+ number: 23,
159
+ },
160
+ };
161
+ const contents = { oldContents: "old source", newContents: "new source" };
162
+ const fetch = vi.fn(async () => AsyncResult.success(contents));
163
+ const highlightFiles = createPullRequestDiffHighlightFiles(
164
+ { target },
165
+ filtered,
166
+ data.files,
167
+ fetch,
168
+ );
169
+ expect(await highlightFiles[1]!.loadContents!()).toBe(contents);
170
+ expect(fetch).toHaveBeenCalledExactlyOnceWith({
171
+ ...target,
172
+ input: { ...target.input, changeType: "change", oldPath: "last.ts", newPath: "last.ts" },
173
+ });
174
+ expect(JSON.stringify(data.rows).length).toBeLessThan(5000);
175
+ });
176
+
177
+ it("keeps Pierre's matching lines in the GitHub credential pinning excerpt", () => {
178
+ const parsed = buildReviewParsedDiff(
179
+ [
180
+ "diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts",
181
+ "--- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts",
182
+ "+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts",
183
+ "@@ -1221,11 +1240,4 @@",
184
+ "- operation: input.operation,",
185
+ "- path: input.path,",
186
+ "- ...(Option.isSome(previous) ? { ifNoneMatch: previous.value.etag } : {}),",
187
+ "- })",
188
+ "- .pipe(",
189
+ "- Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, {",
190
+ "- host,",
191
+ "- token,",
192
+ "- credentialFingerprint: fingerprint,",
193
+ "- }),",
194
+ "- );",
195
+ "+ token,",
196
+ "+ credentialFingerprint: fingerprint,",
197
+ "+ }),",
198
+ "+ );",
199
+ "",
200
+ ].join("\n"),
201
+ "credential-pinning",
202
+ );
203
+ expect(parsed.kind).toBe("files");
204
+ if (parsed.kind !== "files") return;
205
+ expect(
206
+ parsed.files[0]?.rows.find((row) => row.kind === "line" && row.newLineNumber === 1242),
207
+ ).toMatchObject({
208
+ comparison: { change: "delete", tokenIndex: 9 },
209
+ });
210
+ const data = buildNativeReviewDiffData(parsed);
211
+ expect(
212
+ data.rows.find((row) => row.kind === "line" && row.newLineNumber === 1242)?.wordDiffRanges,
213
+ ).toBeUndefined();
214
+ });
215
+
216
+ it.each([
217
+ [true, false, "Old file has no newline at end of file."],
218
+ [false, true, "New file has no newline at end of file."],
219
+ [true, true, "Old and new files have no newline at end of file."],
220
+ [false, false, null],
221
+ ])("shows missing-newline notices for old=%s new=%s", (oldMissing, newMissing, notice) => {
222
+ const data = buildNativeReviewDiffData(
223
+ buildReviewParsedDiff(
224
+ [
225
+ "diff --git a/example.ts b/example.ts",
226
+ "--- a/example.ts",
227
+ "+++ b/example.ts",
228
+ "@@ -1 +1 @@",
229
+ "-value",
230
+ ...(oldMissing ? ["\\ No newline at end of file"] : []),
231
+ "+value",
232
+ ...(newMissing ? ["\\ No newline at end of file"] : []),
233
+ "",
234
+ ].join("\n"),
235
+ "native-eof",
236
+ ),
237
+ );
238
+ expect(data.rows.filter((row) => row.kind === "notice").map((row) => row.text)).toEqual(
239
+ notice ? [notice] : [],
240
+ );
241
+ expect(data.rows.filter((row) => row.kind === "line")).toHaveLength(2);
242
+ expect(data.commentTargetsByRowId.size).toBe(2);
243
+ });
244
+
245
it("keeps cached IDs and targets local to each parsed section and file layout", () => {
246
const original = filesPatch(["example.ts", "second.ts"]);
247
const variants = [
@@ -89,9 +292,9 @@ describe("buildNativeReviewDiffData row bound", () => {
292
expect(data).toMatchObject({ additions: 201_000, deletions: 0 });
293
const hugeRows = data.rows.filter((row) => row.fileId === hugeHeader?.fileId);
294
expect(hugeRows.filter((row) => row.kind === "line" || row.kind === "hunk")).toHaveLength(
92
- 2_000,
295
+ 100_000,
296
);
94
- expect(hugeRows.at(-2)).toMatchObject({ kind: "line", newLineNumber: 1_999 });
297
+ expect(hugeRows.at(-2)).toMatchObject({ kind: "line", newLineNumber: 99_999 });
298
expect(hugeRows.at(-1)).toMatchObject({
299
kind: "notice",
300
text: "This diff is too large to show in full.",
@@ -106,3 +309,65 @@ describe("buildNativeReviewDiffData row bound", () => {
309
expect(ordinaryRows.some((row) => row.kind === "notice")).toBe(false);
310
});
311
});
312
+
313
+describe("buildNativeReviewDiffData word comparison bound", () => {
314
+ function modifiedFilePatch(pairCount: number, contextCount = 0) {
315
+ const lineCount = pairCount + contextCount;
316
+ return [
317
+ "diff --git a/example.ts b/example.ts",
318
+ "--- a/example.ts",
319
+ "+++ b/example.ts",
320
+ `@@ -1,${lineCount} +1,${lineCount} @@`,
321
+ ...Array.from({ length: contextCount }, (_, index) => ` const context${index} = true;`),
322
+ ...Array.from(
323
+ { length: pairCount },
324
+ (_, index) => `-const value${index} = renderPanel({ label: "before", enabled: true });`,
325
+ ),
326
+ ...Array.from(
327
+ { length: pairCount },
328
+ (_, index) => `+const value${index} = renderPanel({ label: "after", enabled: true });`,
329
+ ),
330
+ ].join("\n");
331
+ }
332
+
333
+ it("bounds eager word comparisons without truncating a large modified file", () => {
334
+ const parsedDiff = buildReviewParsedDiff(modifiedFilePatch(20_000), "native-word-bound");
335
+ const comparisons = vi.mocked(diffWordsWithSpace).mockClear();
336
+ const data = buildNativeReviewDiffData(parsedDiff);
337
+
338
+ expect(comparisons).toHaveBeenCalledTimes(1_000);
339
+ expect(data).toMatchObject({ additions: 20_000, deletions: 20_000 });
340
+ const lines = data.rows.filter((row) => row.kind === "line");
341
+ expect(lines).toHaveLength(40_000);
342
+ expect(data.rows.some((row) => row.kind === "notice")).toBe(false);
343
+ for (const offset of [0, 20_000]) {
344
+ expect(lines[offset]?.wordDiffRanges?.length).toBeGreaterThan(0);
345
+ expect(lines[offset + 999]?.wordDiffRanges?.length).toBeGreaterThan(0);
346
+ expect(lines[offset + 1_000]?.wordDiffRanges).toBeUndefined();
347
+ }
348
+ expect(lines.at(-1)).toMatchObject({
349
+ content: 'const value19999 = renderPanel({ label: "after", enabled: true });',
350
+ newLineNumber: 20_000,
351
+ });
352
+ expect(data.commentTargetsByRowId.size).toBe(40_000);
353
+ expect(data.commentTargetsByRowId.get(lines.at(-1)!.id)?.lineIndex).toBe(39_999);
354
+ });
355
+
356
+ it.each([0, 20_000])("preserves small word differences with %s context rows", (contextCount) => {
357
+ const parsedDiff = buildReviewParsedDiff(
358
+ modifiedFilePatch(2, contextCount),
359
+ "native-word-context",
360
+ );
361
+ const comparisons = vi.mocked(diffWordsWithSpace).mockClear();
362
+ const data = buildNativeReviewDiffData(parsedDiff);
363
+
364
+ expect(comparisons).toHaveBeenCalledTimes(2);
365
+ const changes = data.rows.filter((row) => row.kind === "line" && row.change !== "context");
366
+ expect(changes).toHaveLength(4);
367
+ for (const row of changes) {
368
+ expect(
369
+ row.wordDiffRanges?.map((range) => row.content!.slice(range.start, range.end)),
370
+ ).toEqual([row.change === "delete" ? "before" : "after"]);
371
+ }
372
+ });
373
+});
apps/mobile/src/features/review/nativeReviewDiffAdapter.ts
+46
-53
@@ -17,8 +17,10 @@ import type { ReviewInlineComment } from "./reviewCommentSelection";
17
18
const NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT = 4;
19
const NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE = 0.45;
20
+// Keep eager word matching within the old 2,000-row budget while retaining more rendered rows.
21
+const NATIVE_REVIEW_MAX_WORD_DIFF_COMPARISONS = 1_000;
22
// Bound the rows serialized to the native heap before mapping and word matching.
21
-const NATIVE_REVIEW_MAX_FILE_ROWS = 2_000;
23
+const NATIVE_REVIEW_MAX_FILE_ROWS = 100_000;
24
const TRUNCATED_FILE_NOTICE = "This diff is too large to show in full.";
25
const NATIVE_HEX_COLOR = /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})([\da-f]{2})?$/i;
26
const NATIVE_RGBA_COLOR =
@@ -311,63 +313,46 @@ function shouldUseWordDiffRanges(
313
314
function addNativeWordDiffRanges(
315
rows: ReadonlyArray<NativeReviewDiffRow>,
316
+ lineRows: ReadonlyArray<ReviewRenderableLineRow>,
317
): ReadonlyArray<NativeReviewDiffRow> {
318
const nextRows = [...rows];
316
- let index = 0;
317
-
318
- while (index < nextRows.length) {
319
- const deletedRowIndexes: number[] = [];
320
- const addedRowIndexes: number[] = [];
321
- const fileId = nextRows[index]?.fileId;
322
-
323
- while (
324
- nextRows[index]?.kind === "line" &&
325
- nextRows[index]?.change === "delete" &&
326
- nextRows[index]?.fileId === fileId
327
- ) {
328
- deletedRowIndexes.push(index);
329
- index += 1;
330
- }
319
+ const addedRowIndexes = new Map<number, number>();
320
+ const pairs: Array<{ deletionRowIndex: number; additionTokenIndex: number }> = [];
321
+ let lineIndex = 0;
322
332
- while (
333
- nextRows[index]?.kind === "line" &&
334
- nextRows[index]?.change === "add" &&
335
- nextRows[index]?.fileId === fileId
336
- ) {
337
- addedRowIndexes.push(index);
338
- index += 1;
323
+ // Pierre can split adjacent change blocks to align similar lines. Keep those pairings.
324
+ rows.forEach((row, rowIndex) => {
325
+ if (row.kind !== "line") return;
326
+ const source = lineRows[lineIndex++];
327
+ if (source?.change === "add" && source.additionTokenIndex !== null) {
328
+ addedRowIndexes.set(source.additionTokenIndex, rowIndex);
329
+ } else if (source?.change === "delete" && source.comparison?.change === "add") {
330
+ pairs.push({ deletionRowIndex: rowIndex, additionTokenIndex: source.comparison.tokenIndex });
331
}
332
+ });
333
341
- const pairedCount = Math.min(deletedRowIndexes.length, addedRowIndexes.length);
342
- for (let pairIndex = 0; pairIndex < pairedCount; pairIndex += 1) {
343
- const deletedRowIndex = deletedRowIndexes[pairIndex];
344
- const addedRowIndex = addedRowIndexes[pairIndex];
345
- if (deletedRowIndex === undefined || addedRowIndex === undefined) {
346
- continue;
347
- }
348
- const deletedRow = nextRows[deletedRowIndex];
349
- const addedRow = nextRows[addedRowIndex];
350
- if (!deletedRow?.content || !addedRow?.content) {
351
- continue;
352
- }
353
-
354
- const ranges = computeWordAltDiffRanges({
355
- deletionLine: deletedRow.content,
356
- additionLine: addedRow.content,
357
- });
358
- const deletionRanges = trimWordDiffRanges(deletedRow.content, ranges.deletion);
359
- const additionRanges = trimWordDiffRanges(addedRow.content, ranges.addition);
334
+ let comparisonCount = 0;
335
+ for (const { deletionRowIndex, additionTokenIndex } of pairs) {
336
+ if (comparisonCount >= NATIVE_REVIEW_MAX_WORD_DIFF_COMPARISONS) break;
337
+ const addedRowIndex = addedRowIndexes.get(additionTokenIndex);
338
+ if (addedRowIndex === undefined) continue;
339
+ const deletedRow = nextRows[deletionRowIndex];
340
+ const addedRow = nextRows[addedRowIndex];
341
+ if (!deletedRow?.content || !addedRow?.content) continue;
342
+
343
+ comparisonCount += 1;
344
+ const ranges = computeWordAltDiffRanges({
345
+ deletionLine: deletedRow.content,
346
+ additionLine: addedRow.content,
347
+ });
348
+ const deletionRanges = trimWordDiffRanges(deletedRow.content, ranges.deletion);
349
+ const additionRanges = trimWordDiffRanges(addedRow.content, ranges.addition);
350
361
- if (shouldUseWordDiffRanges(deletedRow.content, deletionRanges)) {
362
- nextRows[deletedRowIndex] = { ...deletedRow, wordDiffRanges: deletionRanges };
363
- }
364
- if (shouldUseWordDiffRanges(addedRow.content, additionRanges)) {
365
- nextRows[addedRowIndex] = { ...addedRow, wordDiffRanges: additionRanges };
366
- }
351
+ if (shouldUseWordDiffRanges(deletedRow.content, deletionRanges)) {
352
+ nextRows[deletionRowIndex] = { ...deletedRow, wordDiffRanges: deletionRanges };
353
}
368
-
369
- if (deletedRowIndexes.length === 0 && addedRowIndexes.length === 0) {
370
- index += 1;
354
+ if (shouldUseWordDiffRanges(addedRow.content, additionRanges)) {
355
+ nextRows[addedRowIndex] = { ...addedRow, wordDiffRanges: additionRanges };
356
}
357
}
358
@@ -440,13 +425,21 @@ function prepareFileRows(file: ReviewRenderableFile): PreparedNativeReviewFileRo
425
rows.push(createNoticeRow(file.id, "truncated", TRUNCATED_FILE_NOTICE));
426
}
427
rows.push(...noticeRowsForFile(file));
428
+ if (file.noEOFCRAdditions || file.noEOFCRDeletions) {
429
+ const side = file.noEOFCRAdditions
430
+ ? file.noEOFCRDeletions
431
+ ? "Old and new files have"
432
+ : "New file has"
433
+ : "Old file has";
434
+ rows.push(createNoticeRow(file.id, "eof", `${side} no newline at end of file.`));
435
+ }
436
const prepared: PreparedNativeReviewFileRows = {
437
fileId: file.id,
438
filePath: file.path,
439
lineCount: lineRows.length,
440
truncated: sourceRows !== file.rows,
448
- // Comments must not split the source deletion/addition runs used for word matching.
449
- rows: addNativeWordDiffRanges(rows),
441
+ // Pair source lines before inserting comments so comment rows cannot affect matching.
442
+ rows: addNativeWordDiffRanges(rows, lineRows),
443
commentTargetsByRowId,
444
rowIdByCommentLineId,
445
commentedRows: null,
apps/mobile/src/features/review/reviewDiffHighlightScheduler.ts
+12
-4
@@ -6,7 +6,7 @@ export interface NativeReviewVisibleRange {
6
export function createReviewDiffHighlightScheduler(
7
request: (range: NativeReviewVisibleRange) => void,
8
) {
9
- let requestedRange: NativeReviewVisibleRange = { firstRowIndex: 0, lastRowIndex: 80 };
9
+ let requestedRange: NativeReviewVisibleRange | undefined;
10
let visibleRange = requestedRange;
11
let timer: ReturnType<typeof setTimeout> | undefined;
12
@@ -17,19 +17,25 @@ export function createReviewDiffHighlightScheduler(
17
const flush = () => {
18
cancel();
19
requestedRange = visibleRange;
20
- request(visibleRange);
20
+ if (visibleRange) request(visibleRange);
21
};
22
23
return {
24
update(nextRange: NativeReviewVisibleRange) {
25
if (
26
- nextRange.firstRowIndex === visibleRange.firstRowIndex &&
26
+ nextRange.firstRowIndex === visibleRange?.firstRowIndex &&
27
nextRange.lastRowIndex === visibleRange.lastRowIndex
28
) {
29
return;
30
}
31
visibleRange = nextRange;
32
cancel();
33
+ if (!requestedRange) {
34
+ // Native publishes a pre-jump range and its initial destination together.
35
+ // Yield once so the destination wins before sending an unabortable source RPC.
36
+ timer = setTimeout(flush, 0);
37
+ return;
38
+ }
39
const movedRows =
40
Math.abs(nextRange.firstRowIndex - requestedRange.firstRowIndex) +
41
Math.abs(nextRange.lastRowIndex - requestedRange.lastRowIndex);
@@ -41,8 +47,10 @@ export function createReviewDiffHighlightScheduler(
47
},
48
reset() {
49
cancel();
44
- requestedRange = { firstRowIndex: 0, lastRowIndex: 80 };
50
+ const previousRange = visibleRange;
51
+ requestedRange = undefined;
52
visibleRange = requestedRange;
53
+ return previousRange;
54
},
55
cancel,
56
};
apps/mobile/src/features/review/reviewModel.test.ts
+117
@@ -3,6 +3,123 @@ import { describe, expect, it } from "vite-plus/test";
3
import { applyReviewDiffMetadata, buildReviewParsedDiff } from "./reviewModel";
4
5
describe("buildReviewParsedDiff", () => {
6
+ it("keeps UI identities compact, stable, and isolated from parser cache keys", () => {
7
+ const patch =
8
+ "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -1 +1 @@\n-before\n+after\n";
9
+ const scope = JSON.stringify({ target: 'remote\\"scope'.repeat(100) });
10
+ const parsed = buildReviewParsedDiff(patch + patch, scope);
11
+ const repeated = buildReviewParsedDiff(patch + patch, scope);
12
+ const otherSection = buildReviewParsedDiff(patch + patch, `${scope}:other`);
13
+ const changed = buildReviewParsedDiff((patch + patch).replaceAll("after", "changed"), scope);
14
+ if (
15
+ parsed.kind !== "files" ||
16
+ repeated.kind !== "files" ||
17
+ otherSection.kind !== "files" ||
18
+ changed.kind !== "files"
19
+ )
20
+ throw new Error("Expected structured diffs");
21
+
22
+ expect(parsed.files).toHaveLength(2);
23
+ expect(parsed.files.map((file) => file.id)).toEqual(repeated.files.map((file) => file.id));
24
+ expect(parsed.files.map((file) => file.cacheKey)).toEqual(
25
+ repeated.files.map((file) => file.cacheKey),
26
+ );
27
+ const ids = parsed.files.flatMap((file) => [file.id, ...file.rows.map((row) => row.id)]);
28
+ expect(new Set(ids).size).toBe(ids.length);
29
+ for (const id of ids) expect(id.length).toBeLessThan(48);
30
+ for (const variant of [otherSection, changed]) {
31
+ const otherIds = variant.files.flatMap((file) => [
32
+ file.id,
33
+ ...file.rows.map((row) => row.id),
34
+ ]);
35
+ expect(otherIds.some((id) => ids.includes(id))).toBe(false);
36
+ }
37
+ expect(parsed.files[0]!.cacheKey.length).toBeGreaterThan(scope.length);
38
+ expect(parsed.files[0]!.id).not.toBe(parsed.files[0]!.cacheKey);
39
+ expect(repeated.files[0]!.rows.map((row) => row.id)).toEqual(
40
+ parsed.files[0]!.rows.map((row) => row.id),
41
+ );
42
+ });
43
+
44
+ it.each(["", "\n\n[truncated]"])(
45
+ "preserves the final blank context in the resourceTelemetry excerpt with suffix %j",
46
+ (suffix) => {
47
+ const parsed = buildReviewParsedDiff(
48
+ [
49
+ "diff --git a/packages/contracts/src/resourceTelemetry.ts b/packages/contracts/src/resourceTelemetry.ts",
50
+ "--- a/packages/contracts/src/resourceTelemetry.ts",
51
+ "+++ b/packages/contracts/src/resourceTelemetry.ts",
52
+ "@@ -350,6 +371,7 @@",
53
+ " DesktopTelemetryRequestDesktopUpdate,",
54
+ " DesktopTelemetryCommitDesktopUpdate,",
55
+ " DesktopTelemetryCancelDesktopUpdate,",
56
+ "+ DesktopUpdateRestartPolicyResult,",
57
+ " ]);",
58
+ " export type DesktopTelemetryControlMessage = typeof DesktopTelemetryControlMessage.Type;",
59
+ " ",
60
+ "",
61
+ ].join("\n") + suffix,
62
+ "resource-telemetry",
63
+ );
64
+ expect(parsed.kind).toBe("files");
65
+ if (parsed.kind !== "files") return;
66
+ expect(parsed.files[0]?.rows.at(-1)).toMatchObject({
67
+ kind: "line",
68
+ change: "context",
69
+ oldLineNumber: 355,
70
+ newLineNumber: 377,
71
+ content: "",
72
+ });
73
+ expect(parsed.files[0]?.additionLines.at(-1)).toBe("\n");
74
+ expect(parsed.files[0]?.deletionLines.at(-1)).toBe("\n");
75
+ },
76
+ );
77
+
78
+ it("preserves final content whitespace and gives distinct patches distinct cache keys", () => {
79
+ 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";
80
+ const parsed = buildReviewParsedDiff(patch, "whitespace");
81
+ const withoutWhitespace = buildReviewParsedDiff(
82
+ patch.replace("value \t", "value"),
83
+ "whitespace",
84
+ );
85
+ expect(parsed.kind).toBe("files");
86
+ expect(withoutWhitespace.kind).toBe("files");
87
+ if (parsed.kind !== "files" || withoutWhitespace.kind !== "files") return;
88
+ expect(parsed.files[0]?.rows.at(-1)).toMatchObject({ content: "value \t" });
89
+ expect(parsed.files[0]?.additionLines).toEqual(["value \t\n"]);
90
+ expect(parsed.files[0]?.cacheKey).not.toBe(withoutWhitespace.files[0]?.cacheKey);
91
+ });
92
+
93
+ it.each([
94
+ [true, false],
95
+ [false, true],
96
+ [true, true],
97
+ [false, false],
98
+ ])("preserves missing-newline flags for old=%s and new=%s", (oldMissing, newMissing) => {
99
+ const parsed = buildReviewParsedDiff(
100
+ [
101
+ "diff --git a/a.ts b/a.ts",
102
+ "--- a/a.ts",
103
+ "+++ b/a.ts",
104
+ "@@ -1 +1 @@",
105
+ "-value",
106
+ ...(oldMissing ? ["\\ No newline at end of file"] : []),
107
+ "+value",
108
+ ...(newMissing ? ["\\ No newline at end of file"] : []),
109
+ "",
110
+ ].join("\n"),
111
+ "eof",
112
+ );
113
+ expect(parsed.kind).toBe("files");
114
+ if (parsed.kind !== "files") return;
115
+ expect(parsed.files[0]).toMatchObject({
116
+ noEOFCRDeletions: oldMissing,
117
+ noEOFCRAdditions: newMissing,
118
+ deletionLines: [oldMissing ? "value" : "value\n"],
119
+ additionLines: [newMissing ? "value" : "value\n"],
120
+ });
121
+ });
122
+
123
it.each([
124
["a/example.ts", "a/example.ts"],
125
["a/before.ts", "b/after.ts"],
apps/mobile/src/features/review/reviewModel.ts
+130
-27
@@ -2,6 +2,7 @@ import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
2
import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types";
3
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
4
import type { ReviewDiffPreviewSource } from "@t3tools/contracts";
5
+import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
6
import * as Arr from "effect/Array";
7
import { pipe } from "effect/Function";
8
import * as Order from "effect/Order";
@@ -60,6 +61,13 @@ export interface ReviewRenderableFile {
61
readonly languageHint: string | null;
62
readonly additionLines: ReadonlyArray<string>;
63
readonly deletionLines: ReadonlyArray<string>;
64
+ // Only populated after validating the entire raw file block against its original hunk count.
65
+ readonly completePatchSource?: () => {
66
+ readonly oldContents: string;
67
+ readonly newContents: string;
68
+ };
69
+ readonly noEOFCRAdditions?: boolean;
70
+ readonly noEOFCRDeletions?: boolean;
71
readonly rows: ReadonlyArray<ReviewRenderableRow>;
72
}
73
@@ -139,13 +147,13 @@ function splitTruncationMarker(diff: string): {
147
readonly text: string;
148
readonly truncated: boolean;
149
} {
142
- const trimmed = diff.trimEnd();
143
- if (!trimmed.endsWith("[truncated]")) {
144
- return { text: trimmed, truncated: false };
150
+ const marker = /(?:(?:\r?\n){1,2}|^)\[truncated\]\s*$/.exec(diff);
151
+ if (!marker) {
152
+ return { text: diff, truncated: false };
153
}
154
155
return {
148
- text: trimmed.replace(/\n*\[truncated\]\s*$/, "").trimEnd(),
156
+ text: diff.slice(0, marker.index),
157
truncated: true,
158
};
159
}
@@ -219,14 +227,22 @@ function fnv1a32(input: string, seed: number, multiplier: number): number {
227
}
228
229
function buildPatchCacheKey(patch: string, scope: string): string {
222
- const normalizedPatch = patch.trim();
223
- const primary = fnv1a32(normalizedPatch, FNV_OFFSET_BASIS_32, FNV_PRIME_32).toString(36);
224
- const secondary = fnv1a32(
225
- normalizedPatch,
226
- SECONDARY_HASH_SEED,
227
- SECONDARY_HASH_MULTIPLIER,
228
- ).toString(36);
229
- return `${scope}:${normalizedPatch.length}:${primary}:${secondary}`;
230
+ const primary = fnv1a32(patch, FNV_OFFSET_BASIS_32, FNV_PRIME_32).toString(36);
231
+ const secondary = fnv1a32(patch, SECONDARY_HASH_SEED, SECONDARY_HASH_MULTIPLIER).toString(36);
232
+ return `${scope}:${patch.length}:${primary}:${secondary}`;
233
+}
234
+
235
+// Re-parsing an unchanged page must preserve selection/collapse state. Intern only
236
+// its cache key (never patch contents), keeping scoped Pierre keys off every UI row.
237
+const reviewPatchIds = new Map<string, string>();
238
+
239
+function getReviewPatchId(cacheKey: string): string {
240
+ let id = reviewPatchIds.get(cacheKey);
241
+ if (id === undefined) {
242
+ id = `p${reviewPatchIds.size.toString(36)}`;
243
+ reviewPatchIds.set(cacheKey, id);
244
+ }
245
+ return id;
246
}
247
248
function getFileExtension(path: string): string | null {
@@ -276,14 +292,17 @@ function fallbackHunkHeader(hunk: FileDiffMetadata["hunks"][number]): string {
292
return `@@ -${hunk.deletionStart},${hunk.deletionCount} +${hunk.additionStart},${hunk.additionCount} @@`;
293
}
294
279
-function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRenderableRow> {
295
+function buildRenderableRows(
296
+ file: FileDiffMetadata,
297
+ fileId: string,
298
+): ReadonlyArray<ReviewRenderableRow> {
299
const rows: ReviewRenderableRow[] = [];
300
let rowIndex = 0;
301
302
file.hunks.forEach((hunk, hunkIndex) => {
303
rows.push({
304
kind: "hunk",
286
- id: `${file.cacheKey ?? file.name}:hunk:${hunkIndex}`,
305
+ id: `${fileId}:hunk:${hunkIndex}`,
306
header: fallbackHunkHeader(hunk),
307
context: hunk.hunkContext ? stripTrailingNewline(hunk.hunkContext) : null,
308
});
@@ -298,7 +317,7 @@ function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRender
317
for (let index = 0; index < segment.lines; index += 1) {
318
rows.push({
319
kind: "line",
301
- id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`,
320
+ id: `${fileId}:row:${rowIndex++}`,
321
change: "context",
322
oldLineNumber: deletionLineNumber,
323
newLineNumber: additionLineNumber,
@@ -326,7 +345,7 @@ function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRender
345
for (let index = 0; index < segment.deletions; index += 1) {
346
rows.push({
347
kind: "line",
329
- id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`,
348
+ id: `${fileId}:row:${rowIndex++}`,
349
change: "delete",
350
oldLineNumber: deletionLineNumber,
351
newLineNumber: null,
@@ -348,7 +367,7 @@ function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRender
367
for (let index = 0; index < segment.additions; index += 1) {
368
rows.push({
369
kind: "line",
351
- id: `${file.cacheKey ?? file.name}:row:${rowIndex++}`,
370
+ id: `${fileId}:row:${rowIndex++}`,
371
change: "add",
372
oldLineNumber: null,
373
newLineNumber: additionLineNumber,
@@ -372,7 +391,74 @@ function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRender
391
return rows;
392
}
393
375
-function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {
394
+function completePatchSource(file: FileDiffMetadata, rawPatch: string | null | undefined) {
395
+ if (!rawPatch || (file.type !== "new" && file.type !== "deleted") || file.hunks.length !== 1) {
396
+ return undefined;
397
+ }
398
+ const added = file.type === "new";
399
+ const a = quoteGitPatchPath(`a/${file.name}`);
400
+ const b = quoteGitPatchPath(`b/${file.name}`);
401
+ const lines = rawPatch.split("\n");
402
+ if (lines.pop() !== "" || rawPatch.includes("\0")) return undefined;
403
+ let index = 0;
404
+ if (lines[index++] !== `diff --git ${a} ${b}`) return undefined;
405
+ if (
406
+ !new RegExp(`^${added ? "new" : "deleted"} file mode 100(644|755)$`).test(lines[index++] ?? "")
407
+ ) {
408
+ return undefined;
409
+ }
410
+ if (lines[index]?.startsWith("index ")) {
411
+ if (!/^index [0-9a-f]+\.\.[0-9a-f]+(?: 100(?:644|755))?$/.test(lines[index++] ?? "")) {
412
+ return undefined;
413
+ }
414
+ }
415
+ if (lines[index++] !== `--- ${added ? "/dev/null" : a}`) return undefined;
416
+ if (lines[index++] !== `+++ ${added ? b : "/dev/null"}`) return undefined;
417
+ // Pierre repairs both underfull and overfull hunks. Its resulting counts cannot
418
+ // prove that patch lines cover the whole file; read the original header instead.
419
+ const header = lines[index++] ?? "";
420
+ // GitCafe's structured hunks can start the empty side at 1 instead of git's 0.
421
+ // Its explicit zero count still proves that side contributes no source lines.
422
+ const match = (added ? /^@@ -[01],0 \+1(?:,(\d+))? @@$/ : /^@@ -1(?:,(\d+))? \+[01],0 @@$/).exec(
423
+ header,
424
+ );
425
+ if (!match) return undefined;
426
+ const count = Number(match[1] ?? 1);
427
+ if (!Number.isSafeInteger(count) || count <= 0) return undefined;
428
+ const hunk = file.hunks[0]!;
429
+ if (
430
+ hunk.hunkSpecs !== `${header}\n` ||
431
+ (added ? hunk.additionCount : hunk.deletionCount) !== count ||
432
+ (added ? file.additionLines : file.deletionLines).length !== count ||
433
+ (added ? file.deletionLines : file.additionLines).length !== 0
434
+ )
435
+ return undefined;
436
+ const bodyStart = lines.slice(0, index).reduce((length, line) => length + line.length + 1, 0);
437
+ const prefix = added ? "+" : "-";
438
+ for (let line = 0; line < count; line++) {
439
+ if (!lines[index++]?.startsWith(prefix)) return undefined;
440
+ }
441
+ let bodyEnd = rawPatch.length;
442
+ if (lines[index] === "\\ No newline at end of file") {
443
+ // Only the patch's LF is synthetic, including when the source ends in a bare CR.
444
+ bodyEnd -= "\\ No newline at end of file\n".length + 1;
445
+ index++;
446
+ }
447
+ if (index !== lines.length) return undefined;
448
+ // Keep reconstruction lazy so only requested source enters the bounded source cache.
449
+ return () => {
450
+ const contents = rawPatch.slice(bodyStart + 1, bodyEnd).replace(/\n[+-]/g, "\n");
451
+ return added
452
+ ? { oldContents: "", newContents: contents }
453
+ : { oldContents: contents, newContents: "" };
454
+ };
455
+}
456
+
457
+function mapRenderableFile(
458
+ file: FileDiffMetadata,
459
+ id: string,
460
+ rawPatch?: string | null,
461
+): ReviewRenderableFile {
462
const path = file.name || file.prevName || "";
463
const previousPath = file.prevName || null;
464
const additions = file.hunks.reduce((total, hunk) => total + hunk.additionLines, 0);
@@ -380,7 +466,7 @@ function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {
466
const cacheKey = file.cacheKey ?? `${previousPath ?? "none"}:${path}:${file.type}`;
467
468
return {
383
- id: cacheKey,
469
+ id,
470
cacheKey,
471
path,
472
previousPath,
@@ -390,7 +476,10 @@ function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {
476
languageHint: file.lang ?? null,
477
additionLines: file.additionLines,
478
deletionLines: file.deletionLines,
393
- rows: buildRenderableRows(file),
479
+ completePatchSource: completePatchSource(file, rawPatch),
480
+ noEOFCRAdditions: file.hunks.some((hunk) => hunk.noEOFCRAdditions),
481
+ noEOFCRDeletions: file.hunks.some((hunk) => hunk.noEOFCRDeletions),
482
+ rows: buildRenderableRows(file, id),
483
};
484
}
485
@@ -471,12 +560,11 @@ export function buildReviewParsedDiff(
560
diff: string | null | undefined,
561
cacheScope: string,
562
): ReviewParsedDiff {
474
- const normalized = diff?.trim();
475
- if (!normalized) {
563
+ if (!diff?.trim()) {
564
return { kind: "empty" };
565
}
566
479
- const { text, truncated } = splitTruncationMarker(normalized);
567
+ const { text, truncated } = splitTruncationMarker(diff);
568
if (text.length === 0) {
569
return { kind: "empty" };
570
}
@@ -486,13 +574,28 @@ export function buildReviewParsedDiff(
574
: null;
575
576
try {
489
- const parsedPatches = runDiffParserSilently(() =>
490
- parsePatchFiles(text, buildPatchCacheKey(text, cacheScope)),
491
- );
577
+ const cacheKey = buildPatchCacheKey(text, cacheScope);
578
+ const patchId = getReviewPatchId(cacheKey);
579
+ const parsedPatches = runDiffParserSilently(() => parsePatchFiles(text, cacheKey));
580
+ const rawFiles = new Map<string, string | null>();
581
+ if (!truncated) {
582
+ for (const rawFile of text.split(/(?=^diff --git )/m)) {
583
+ const header = rawFile.slice(0, rawFile.indexOf("\n"));
584
+ rawFiles.set(header, rawFiles.has(header) ? null : rawFile);
585
+ }
586
+ }
587
const files = pipe(
588
parsedPatches,
589
Arr.flatMap((patch) => patch.files),
495
- Arr.map(mapRenderableFile),
590
+ Arr.map((file, index) =>
591
+ mapRenderableFile(
592
+ file,
593
+ `${patchId}:f${index.toString(36)}`,
594
+ rawFiles.get(
595
+ `diff --git ${quoteGitPatchPath(`a/${file.name}`)} ${quoteGitPatchPath(`b/${file.name}`)}`,
596
+ ),
597
+ ),
598
+ ),
599
);
600
601
if (files.length === 0) {
apps/mobile/src/features/review/useNativeReviewDiffBridge.ts
+22
-12
@@ -1,4 +1,4 @@
1
-import { useCallback, useMemo, useState } from "react";
1
+import { useCallback, useMemo, useRef, useState } from "react";
2
import type { NativeSyntheticEvent } from "react-native";
3
4
import { createNativeReviewDiffTheme, type NativeReviewDiffData } from "./nativeReviewDiffAdapter";
@@ -33,6 +33,8 @@ export function useNativeReviewDiffBridge(input: {
33
const { nativeReviewDiffStyle } = useAppearanceCodeSurface();
34
const { themeAppearance: scheme, themeId } = useAppearancePreferences();
35
const appTheme = useUniwindTheme();
36
+ const [surfaceGeneration, setSurfaceGeneration] = useState(0);
37
+ const hasMountedContentRef = useRef(false);
38
const [collapsedCommentIds, setCollapsedCommentIds] = useState<ReadonlySet<string>>(
39
() => new Set(),
40
);
@@ -53,28 +55,36 @@ export function useNativeReviewDiffBridge(input: {
55
const styleJson = useMemo(() => JSON.stringify(nativeReviewDiffStyle), [nativeReviewDiffStyle]);
56
const tokensResetKey = useMemo(
57
() =>
56
- buildNativeReviewTokensResetKey({
58
+ `${buildNativeReviewTokensResetKey({
59
threadKey,
60
sectionId,
61
scheme,
62
diff,
63
fileCount: data.files.length,
64
rowCount: data.rows.length,
63
- }),
64
- [data.files.length, data.rows.length, diff, scheme, sectionId, threadKey],
65
+ })}:${surfaceGeneration}`,
66
+ [data.files.length, data.rows.length, diff, scheme, sectionId, surfaceGeneration, threadKey],
67
);
66
- const { tokensPatchJson, updateVisibleRange } = useNativeReviewDiffHighlighting({
67
- files: data.files,
68
- rows: data.rows,
69
- scheme,
70
- resetKey: tokensResetKey,
71
- enabled: canHighlight,
72
- });
68
+ const { acknowledgeTokenPatch, rejectTokenPatch, tokensPatchJson, updateVisibleRange } =
69
+ useNativeReviewDiffHighlighting({
70
+ files: data.files,
71
+ rows: data.rows,
72
+ scheme,
73
+ resetKey: tokensResetKey,
74
+ enabled: canHighlight,
75
+ });
76
77
const onDebug = useCallback(
78
(event: NativeSyntheticEvent<Record<string, unknown>>) => {
79
const payload = event.nativeEvent;
80
const message = payload.message;
81
+ if (message === "surface-content-mounted") {
82
+ // The initial content already has a fresh hook; replacements lose accepted tokens.
83
+ if (hasMountedContentRef.current) setSurfaceGeneration((generation) => generation + 1);
84
+ hasMountedContentRef.current = true;
85
+ }
86
+ if (message === "tokens-patch-delivered") acknowledgeTokenPatch(payload);
87
+ if (message === "tokens-patch-failed") rejectTokenPatch(payload);
88
if (
89
(message === "draw-metrics" || message === "visible-range") &&
90
typeof payload.firstRowIndex === "number" &&
@@ -86,7 +96,7 @@ export function useNativeReviewDiffBridge(input: {
96
});
97
}
98
},
89
- [updateVisibleRange],
99
+ [acknowledgeTokenPatch, rejectTokenPatch, updateVisibleRange],
100
);
101
102
const onToggleComment = useCallback(
apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts
+173
-30
@@ -1,9 +1,16 @@
1
-import { useEffect, useRef, useState } from "react";
2
-
1
import type { HighlightScheme } from "../../lib/highlights";
4
-import { highlightNativeReviewDiffVisibleRows } from "../diffs/nativeReviewDiffHighlighter";
2
+
3
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4
+import { AsyncResult } from "effect/reactivity";
5
+import { useCallback, useEffect, useRef, useState } from "react";
6
+
7
+import {
8
+ highlightNativeReviewDiffVisibleRows,
9
+ type NativeReviewDiffHighlightChunk,
10
+} from "../diffs/nativeReviewDiffHighlighter";
11
import type { NativeReviewDiffRow } from "../diffs/nativeReviewDiffSurface";
12
import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes";
13
+import { diffHighlightTraceId, traceDiffHighlight } from "../diffs/nativeReviewDiffTrace";
14
15
import {
16
createReviewDiffHighlightScheduler,
@@ -23,50 +30,186 @@ export function useNativeReviewDiffHighlighting(input: {
30
}) {
31
const { enabled, files, resetKey, rows, scheme } = input;
32
const highlightedRowIdsRef = useRef<Set<string>>(new Set());
26
- const [visibleRange, setVisibleRange] = useState<NativeReviewVisibleRange>({
27
- firstRowIndex: 0,
28
- lastRowIndex: 80,
29
- });
33
+ const viewportScope = `${enabled}:${resetKey}:${rows.length}`;
34
+ const [viewport, setViewport] = useState<{
35
+ scope: string;
36
+ range: NativeReviewVisibleRange | null;
37
+ }>(() => ({ scope: viewportScope, range: null }));
38
const visibleChunkIndexRef = useRef(0);
39
+ // Keep undelivered chunks, rather than repeatedly serializing every highlighted row.
40
+ const pendingPatchesRef = useRef<
41
+ Array<{ resetKey: string; chunkIndex: number; json: string; rowIds: string[] }>
42
+ >([]);
43
const [tokensPatchJson, setTokensPatchJson] = useState(() => createEmptyTokenPatch(resetKey));
32
- const [scheduler] = useState(() => createReviewDiffHighlightScheduler(setVisibleRange));
44
+ const [scheduler] = useState(() =>
45
+ createReviewDiffHighlightScheduler((range) =>
46
+ setViewport((current) => ({ ...current, range })),
47
+ ),
48
+ );
49
50
useEffect(() => {
35
- scheduler.reset();
51
+ traceDiffHighlight("viewport-reset", {
52
+ reset: diffHighlightTraceId(resetKey),
53
+ enabled,
54
+ rows: rows.length,
55
+ });
56
+ const previousRange = scheduler.reset();
57
highlightedRowIdsRef.current = new Set();
37
- visibleChunkIndexRef.current = 0;
38
- setVisibleRange({ firstRowIndex: 0, lastRowIndex: 80 });
58
+ pendingPatchesRef.current = [];
59
+ setViewport({ scope: viewportScope, range: null });
60
setTokensPatchJson(createEmptyTokenPatch(resetKey));
61
+ // A token reset need not produce another native range event. Reuse only an
62
+ // observed viewport, with the same coalescing that lets a new jump replace it.
63
+ if (previousRange) scheduler.update(previousRange);
64
return () => scheduler.cancel();
41
- }, [enabled, resetKey, rows.length, scheduler]);
65
+ }, [enabled, resetKey, rows.length, scheduler, viewportScope]);
66
67
useEffect(() => {
44
- if (!enabled || rows.length === 0) {
68
+ if (!enabled || rows.length === 0 || !viewport.range || viewport.scope !== viewportScope) {
69
return;
70
}
71
48
- const result = highlightNativeReviewDiffVisibleRows({
49
- files,
50
- rows,
51
- scheme,
52
- firstRowIndex: visibleRange.firstRowIndex,
53
- lastRowIndex: visibleRange.lastRowIndex,
54
- alreadyHighlightedRowIds: highlightedRowIdsRef.current,
72
+ const abortController = new AbortController();
73
+ const requestRange = viewport.range;
74
+ const generation = diffHighlightTraceId(abortController);
75
+ const reset = diffHighlightTraceId(resetKey);
76
+ traceDiffHighlight("viewport-start", {
77
+ generation,
78
+ reset,
79
+ first: requestRange.firstRowIndex,
80
+ last: requestRange.lastRowIndex,
81
+ pending: pendingPatchesRef.current.length,
82
});
56
- if (result.rowCount === 0) return;
83
58
- for (const rowId of Object.keys(result.tokensByRowId)) {
59
- highlightedRowIdsRef.current.add(rowId);
60
- }
84
+ const enqueueChunk = (result: NativeReviewDiffHighlightChunk) => {
85
+ if (abortController.signal.aborted || result.rowCount === 0) return;
86
+ const retryableRowIds = new Set(result.retryableRowIds);
87
+ const rowIds = Object.keys(result.tokensByRowId);
88
+ for (const rowId of rowIds) {
89
+ if (!retryableRowIds.has(rowId)) highlightedRowIdsRef.current.add(rowId);
90
+ }
91
+ const chunkIndex = visibleChunkIndexRef.current++;
92
+ const json = JSON.stringify({
93
+ resetKey,
94
+ chunkIndex,
95
+ fileId: "visible",
96
+ filePath: "visible rows",
97
+ language: "diff",
98
+ lineCount: result.rowCount,
99
+ durationMs: result.durationMs,
100
+ tokensByRowId: result.tokensByRowId,
101
+ });
102
+ pendingPatchesRef.current.push({ resetKey, chunkIndex, json, rowIds });
103
+ traceDiffHighlight("patch-queued", {
104
+ generation,
105
+ reset,
106
+ chunk: chunkIndex,
107
+ rows: rowIds.length,
108
+ pending: pendingPatchesRef.current.length,
109
+ });
110
+ if (pendingPatchesRef.current.length === 1) setTokensPatchJson(json);
111
+ };
112
+
113
+ void (async () => {
114
+ // Deliver viewport tokens before offscreen source fetches can delay them.
115
+ let retryableViewportRowIds: ReadonlyArray<string> = [];
116
+ for (const overscanRows of [0, undefined]) {
117
+ const deliveredRowIds = new Set<string>();
118
+ const settled = await settlePromise(() =>
119
+ highlightNativeReviewDiffVisibleRows({
120
+ files,
121
+ rows,
122
+ scheme,
123
+ firstRowIndex: requestRange.firstRowIndex,
124
+ lastRowIndex: requestRange.lastRowIndex,
125
+ overscanRows,
126
+ alreadyHighlightedRowIds:
127
+ retryableViewportRowIds.length > 0
128
+ ? new Set([...highlightedRowIdsRef.current, ...retryableViewportRowIds])
129
+ : highlightedRowIdsRef.current,
130
+ signal: abortController.signal,
131
+ onChunk: (chunk) => {
132
+ for (const rowId of Object.keys(chunk.tokensByRowId)) deliveredRowIds.add(rowId);
133
+ enqueueChunk(chunk);
134
+ },
135
+ }),
136
+ );
137
+ if (abortController.signal.aborted) return;
138
+ if (AsyncResult.isFailure(settled)) {
139
+ console.warn("[review-sheet] native visible highlight failed", {
140
+ error: squashAtomCommandFailure(settled),
141
+ resetKey,
142
+ scheme,
143
+ firstRowIndex: requestRange.firstRowIndex,
144
+ lastRowIndex: requestRange.lastRowIndex,
145
+ });
146
+ return;
147
+ }
148
+ const result = settled.value;
149
+ traceDiffHighlight("viewport-result", {
150
+ generation,
151
+ reset,
152
+ overscan: overscanRows ?? 160,
153
+ rows: result.rowCount,
154
+ retryable: result.retryableRowIds.length,
155
+ });
156
+ if (result.rowCount === 0) continue;
157
+ retryableViewportRowIds = result.retryableRowIds;
158
+
159
+ const remaining = Object.fromEntries(
160
+ Object.entries(result.tokensByRowId).filter(([rowId]) => !deliveredRowIds.has(rowId)),
161
+ );
162
+ enqueueChunk({
163
+ ...result,
164
+ tokensByRowId: remaining,
165
+ rowCount: Object.keys(remaining).length,
166
+ });
167
+ }
168
+ })();
169
+
170
+ return () => {
171
+ traceDiffHighlight("viewport-abort", { generation, reset });
172
+ abortController.abort();
173
+ };
174
+ }, [enabled, files, resetKey, rows, scheme, viewport, viewportScope]);
175
+
176
+ const acknowledgeTokenPatch = useCallback((payload: Readonly<Record<string, unknown>>) => {
177
+ const pending = pendingPatchesRef.current;
178
+ const head = pending[0];
179
+ traceDiffHighlight("patch-ack", {
180
+ reset: diffHighlightTraceId(payload.resetKey),
181
+ chunk: typeof payload.chunkIndex === "number" ? payload.chunkIndex : -1,
182
+ matches:
183
+ !!head && payload.resetKey === head.resetKey && payload.chunkIndex === head.chunkIndex,
184
+ pending: pending.length,
185
+ });
186
+ if (!head || payload.resetKey !== head.resetKey || payload.chunkIndex !== head.chunkIndex)
187
+ return;
188
+ pending.shift();
189
+ setTokensPatchJson(pending[0]?.json ?? createEmptyTokenPatch(head.resetKey));
190
+ }, []);
191
62
- const chunkIndex = visibleChunkIndexRef.current;
63
- visibleChunkIndexRef.current += 1;
64
- setTokensPatchJson(
65
- JSON.stringify({ resetKey, chunkIndex, tokensByRowId: result.tokensByRowId }),
66
- );
67
- }, [enabled, files, resetKey, rows, scheme, visibleRange]);
192
+ const rejectTokenPatch = useCallback(
193
+ (payload: Readonly<Record<string, unknown>>) => {
194
+ const head = pendingPatchesRef.current[0];
195
+ traceDiffHighlight("patch-rejected", {
196
+ reset: diffHighlightTraceId(payload.resetKey),
197
+ chunk: typeof payload.chunkIndex === "number" ? payload.chunkIndex : -1,
198
+ matches:
199
+ !!head && payload.resetKey === head.resetKey && payload.chunkIndex === head.chunkIndex,
200
+ });
201
+ if (!head || payload.resetKey !== head.resetKey || payload.chunkIndex !== head.chunkIndex)
202
+ return;
203
+ for (const rowId of head.rowIds) highlightedRowIdsRef.current.delete(rowId);
204
+ // Retry these rows only on a later viewport request, not in a failure loop.
205
+ acknowledgeTokenPatch(payload);
206
+ },
207
+ [acknowledgeTokenPatch],
208
+ );
209
210
return {
211
+ rejectTokenPatch,
212
+ acknowledgeTokenPatch,
213
tokensPatchJson,
214
updateVisibleRange: scheduler.update,
215
};
apps/mobile/src/lib/highlights.test.ts
+14
-1
@@ -2,7 +2,7 @@ import { codeToTokens } from "@pierre/highlights";
2
import { pierreDark, pierreLight } from "@pierre/highlights/themes";
3
import { describe, expect, it, vi } from "vite-plus/test";
4
5
-import { highlightCode } from "./highlights";
5
+import { highlightCode, tokenizeCode } from "./highlights";
6
7
vi.mock("expo", async () => {
8
const { createWasmHighlightsModule } = await import("./highlights.testing");
@@ -44,3 +44,16 @@ describe("highlightCode", () => {
44
expect(second).toEqual([{ content: longLine, color: null, fontStyle: null }]);
45
});
46
});
47
+
48
+it("normalizes only requested lines from full-source records, including CRLF and a long comment opener", () => {
49
+ const code = `const first = 1;\r\n${" ".repeat(1_001)}/*\r\ninside\r\n*/\r\nconst last = 2;`;
50
+ const source = tokenizeCode(code, "typescript");
51
+ expect(source.byteLength).toBeGreaterThan(0);
52
+ for (let line = 0; line < 5; line++) {
53
+ expect(source.highlightLine(line, "dark")).toEqual(
54
+ highlightCode(code, "typescript", "dark")[line],
55
+ );
56
+ }
57
+ expect(source.highlightLine(2, "dark")?.[0]?.color).toBe("#737373");
58
+ expect(source.highlightLine(100, "dark")).toBeUndefined();
59
+});
apps/mobile/src/lib/highlights.ts
+56
-35
@@ -24,50 +24,71 @@ const nativeHighlights = requireOptionalNativeModule<{
24
tokenize(source: string, language: number): ArrayBuffer | null;
25
}>("T3Highlights");
26
27
-function plainLines(code: string): HighlightedLines {
28
- return code
29
- .split(/\r?\n/u)
30
- .map((line) => (line ? [{ content: line, color: null, fontStyle: null }] : []));
27
+export interface TokenizedCode {
28
+ /** Retained UTF-16 source, compact native records, and line indexes. */
29
+ readonly byteLength: number;
30
+ readonly lineCount: number;
31
+ readonly highlightLine: (
32
+ index: number,
33
+ scheme: HighlightScheme,
34
+ ) => ReadonlyArray<HighlightedToken> | undefined;
35
}
36
33
-/**
34
- * Tokenizes `code` synchronously, one token array per line. Lines split at LF
35
- * and CRLF, and a trailing line break yields a final empty line.
36
- */
37
-export function highlightCode(
38
- code: string,
39
- language: string,
40
- scheme: HighlightScheme,
41
-): HighlightedLines {
37
+/** Keep native records compact; expand only lines a client will display. */
38
+export function tokenizeCode(code: string, language: string): TokenizedCode {
39
const id = highlightLanguageId(language);
40
const buffer = id === 0 ? null : (nativeHighlights?.tokenize(code, id) ?? null);
44
- if (!buffer) return plainLines(code);
45
-
46
- // `(endUtf16, tokenId)` pairs. A LINE_END token ID ends a line, and its end
47
- // is where the next line starts. Mirrors @pierre/highlights' lineRecordsToTokens.
48
- const records = new Uint32Array(buffer);
49
- const styles = HIGHLIGHTS_THEME_STYLES[scheme];
50
- const lines: HighlightedToken[][] = [];
51
- let start = 0;
52
- for (let record = 0; ; record += 2) {
53
- const first = record;
54
- while (record < records.length && records[record + 1] !== LINE_END) record += 2;
55
- const end = record === first ? start : records[record - 2]!;
56
- if (end - start > MAX_HIGHLIGHTED_LINE_LENGTH) {
57
- lines.push([{ content: code.slice(start, end), color: null, fontStyle: null }]);
58
- } else {
41
+ const records = buffer ? new Uint32Array(buffer) : null;
42
+ const offsets = [0];
43
+ if (records) {
44
+ for (let record = 0; record < records.length; record += 2) {
45
+ if (records[record + 1] === LINE_END) offsets.push(record + 2);
46
+ }
47
+ } else {
48
+ for (let at = code.indexOf("\n"); at !== -1; at = code.indexOf("\n", at + 1))
49
+ offsets.push(at + 1);
50
+ }
51
+ const lineStarts = Uint32Array.from(offsets);
52
+ return {
53
+ byteLength: code.length * 2 + (records?.byteLength ?? 0) + lineStarts.byteLength,
54
+ lineCount: lineStarts.length,
55
+ highlightLine(index, scheme) {
56
+ if (index < 0 || index >= lineStarts.length) return undefined;
57
+ const first = lineStarts[index]!;
58
+ const next = lineStarts[index + 1];
59
+ if (!records) {
60
+ const end = next === undefined ? code.length : next - (code[next - 2] === "\r" ? 2 : 1);
61
+ const content = code.slice(first, end);
62
+ return content ? [{ content, color: null, fontStyle: null }] : [];
63
+ }
64
+ let start = first === 0 ? 0 : records[first - 2]!;
65
+ const last = next === undefined ? records.length : next - 2;
66
+ const end = last === first ? start : records[last - 2]!;
67
+ if (end - start > MAX_HIGHLIGHTED_LINE_LENGTH) {
68
+ return [{ content: code.slice(start, end), color: null, fontStyle: null }];
69
+ }
70
+ const styles = HIGHLIGHTS_THEME_STYLES[scheme];
71
const line: HighlightedToken[] = [];
60
- for (let at = first; at < record; at += 2) {
72
+ for (let at = first; at < last; at += 2) {
73
const tokenEnd = records[at]!;
74
if (tokenEnd <= start) continue;
75
const [color, fontStyle] = styles[records[at + 1]!] ?? styles[0]!;
76
line.push({ content: code.slice(start, tokenEnd), color, fontStyle });
77
start = tokenEnd;
78
}
67
- lines.push(line);
68
- }
69
- if (record >= records.length) break;
70
- start = records[record]!;
71
- }
72
- return lines;
79
+ return line;
80
+ },
81
+ };
82
+}
83
+
84
+/** LF and CRLF split lines; a trailing line break yields a final empty line. */
85
+export function highlightCode(
86
+ code: string,
87
+ language: string,
88
+ scheme: HighlightScheme,
89
+): HighlightedLines {
90
+ const source = tokenizeCode(code, language);
91
+ return Array.from({ length: source.lineCount }, (_, index) =>
92
+ source.highlightLine(index, scheme)!,
93
+ );
94
}
apps/mobile/vite.config.ts
+2
@@ -2,6 +2,8 @@ import { defineConfig } from "vite-plus";
2
import "vite-plus/test/config";
3
4
const reactTests = [
5
+ "src/features/diffs/nativeReviewDiffSurface.test.tsx",
6
+ "src/features/pull-requests/usePullRequestDiff.test.tsx",
7
"src/components/ui/Dialog.android.test.tsx",
8
"src/features/settings/SettingsServerControlsRouteScreen.test.tsx",
9
"src/features/settings/components/BranchNamingSettings.test.tsx",
packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts
+166
@@ -164,6 +164,172 @@ const assertRequestId = (body: unknown) =>
164
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,
165
);
166
167
+describe("GitCafePullRequestProvider source contents", () => {
168
+ const comparisonBase = "a".repeat(40);
169
+ const snapshot = { version: pull.version, headOid, comparisonBaseOid: comparisonBase };
170
+ const input = {
171
+ ...target,
172
+ changeType: "rename-changed" as const,
173
+ oldPath: "old name.ts",
174
+ newPath: "src/new #name.ts",
175
+ };
176
+ const blob = (request: SentRequest) => ({
177
+ commit: request.query.get("oid"),
178
+ oid: "b".repeat(40),
179
+ path: request.query.get("path"),
180
+ size: 16,
181
+ binary: false,
182
+ content: "const value = 1;",
183
+ });
184
+ const routes = {
185
+ "GET /repos/owner/repo/pulls/7": pull,
186
+ "GET /repos/owner/repo/pulls/7/changes": snapshot,
187
+ "GET /repos/owner/repo/blob": blob,
188
+ };
189
+
190
+ it.effect(
191
+ "pins rename source to the comparison base and fork head, without reading branches",
192
+ () => {
193
+ const server = fakeGitCafe({
194
+ ...routes,
195
+ "GET /repos/owner/repo/pulls/7": {
196
+ ...pull,
197
+ sourceRepo: { owner: "fork", name: "project" },
198
+ },
199
+ "GET /repos/fork/project/blob": blob,
200
+ });
201
+ return Effect.gen(function* () {
202
+ const provider = yield* GitCafePullRequestProvider.make;
203
+ const result = yield* provider.getDiffFileContents!(input);
204
+ assert.deepStrictEqual(result, {
205
+ oldContents: "const value = 1;",
206
+ newContents: "const value = 1;",
207
+ });
208
+ const changes = server.sent.find((request) => request.path.endsWith("/changes"))!;
209
+ assert.strictEqual(changes.query.get("expectedVersion"), "4");
210
+ assert.strictEqual(changes.query.get("limit"), "1");
211
+ assert.deepStrictEqual(
212
+ server.sent
213
+ .filter((request) => request.path.endsWith("/blob"))
214
+ .map((request) => ({
215
+ path: request.path,
216
+ oid: request.query.get("oid"),
217
+ file: request.query.get("path"),
218
+ ref: request.query.get("ref"),
219
+ })),
220
+ [
221
+ { path: "/repos/owner/repo/blob", oid: comparisonBase, file: input.oldPath, ref: null },
222
+ { path: "/repos/fork/project/blob", oid: headOid, file: input.newPath, ref: null },
223
+ ],
224
+ );
225
+ assert.deepStrictEqual(server.writes(), []);
226
+ }).pipe(Effect.provide(server.layer));
227
+ },
228
+ );
229
+
230
+ it.effect.each(["new", "deleted"] as const)(
231
+ "skips the absent side of a %s file",
232
+ (changeType) => {
233
+ const server = fakeGitCafe(routes);
234
+ return Effect.gen(function* () {
235
+ const provider = yield* GitCafePullRequestProvider.make;
236
+ const result = yield* provider.getDiffFileContents!({ ...input, changeType });
237
+ assert.strictEqual(result[changeType === "new" ? "oldContents" : "newContents"], "");
238
+ assert.lengthOf(
239
+ server.sent.filter((request) => request.path.endsWith("/blob")),
240
+ 1,
241
+ );
242
+ }).pipe(Effect.provide(server.layer));
243
+ },
244
+ );
245
+
246
+ it.effect.each([
247
+ { ...snapshot, version: 5 },
248
+ { ...snapshot, headOid: baseOid },
249
+ { ...snapshot, comparisonBaseOid: "main" },
250
+ ])("refuses a changed or nonimmutable comparison snapshot", (response) => {
251
+ const server = fakeGitCafe({ ...routes, "GET /repos/owner/repo/pulls/7/changes": response });
252
+ return Effect.gen(function* () {
253
+ const provider = yield* GitCafePullRequestProvider.make;
254
+ const result = yield* provider.getDiffFileContents!(input).pipe(Effect.result);
255
+ assert.strictEqual(result._tag, "Failure");
256
+ assert.isFalse(server.sent.some((request) => request.path.endsWith("/blob")));
257
+ }).pipe(Effect.provide(server.layer));
258
+ });
259
+
260
+ it.effect.each([
261
+ { binary: true, content: null },
262
+ { content: "binary\0data" },
263
+ { size: 1_048_577 },
264
+ { size: 1, content: "x".repeat(1_048_577) },
265
+ { size: 1, content: "é".repeat(524_289) },
266
+ { commit: baseOid },
267
+ { path: "another.ts" },
268
+ { content: null },
269
+ ])("refuses unavailable, oversized, binary, or mismatched blobs", (fields) => {
270
+ const server = fakeGitCafe({
271
+ ...routes,
272
+ "GET /repos/owner/repo/blob": (request: SentRequest) => ({ ...blob(request), ...fields }),
273
+ });
274
+ return Effect.gen(function* () {
275
+ const provider = yield* GitCafePullRequestProvider.make;
276
+ const result = yield* provider.getDiffFileContents!(input).pipe(Effect.result);
277
+ assert.strictEqual(result._tag, "Failure");
278
+ assert.deepStrictEqual(server.writes(), []);
279
+ }).pipe(Effect.provide(server.layer));
280
+ });
281
+
282
+ it.effect.each([
283
+ [413, "oversized"],
284
+ [501, "unavailable"],
285
+ ] as const)("marks HTTP %s blob refusals permanently unavailable", ([status, reason]) => {
286
+ const server = fakeGitCafe({
287
+ ...routes,
288
+ "GET /repos/owner/repo/blob": new Response("{}", { status }),
289
+ });
290
+ return Effect.gen(function* () {
291
+ const provider = yield* GitCafePullRequestProvider.make;
292
+ const error = yield* provider.getDiffFileContents!({ ...input, changeType: "new" }).pipe(
293
+ Effect.flip,
294
+ );
295
+ assert.deepInclude(error.cause as object, {
296
+ _tag: "GitCafeDiffSourceUnavailableError",
297
+ reason,
298
+ });
299
+ }).pipe(Effect.provide(server.layer));
300
+ });
301
+
302
+ it.effect("preserves authentication failures from blob access", () => {
303
+ const server = fakeGitCafe({
304
+ ...routes,
305
+ "GET /repos/owner/repo/blob": new Response("{}", { status: 401 }),
306
+ });
307
+ return Effect.gen(function* () {
308
+ const provider = yield* GitCafePullRequestProvider.make;
309
+ const error = yield* provider.getDiffFileContents!({ ...input, changeType: "new" }).pipe(
310
+ Effect.flip,
311
+ );
312
+ assert.strictEqual(error.reason, "unauthenticated");
313
+ assert.strictEqual(error.operation, "getDiffFileContents");
314
+ }).pipe(Effect.provide(server.layer));
315
+ });
316
+
317
+ it.effect(
318
+ "refuses commit-specific contents consistently with unsupported GitCafe commit diffs",
319
+ () => {
320
+ const server = fakeGitCafe({});
321
+ return Effect.gen(function* () {
322
+ const provider = yield* GitCafePullRequestProvider.make;
323
+ const result = yield* provider.getDiffFileContents!({ ...input, commit: headOid }).pipe(
324
+ Effect.result,
325
+ );
326
+ assert.strictEqual(result._tag, "Failure");
327
+ assert.deepStrictEqual(server.sent, []);
328
+ }).pipe(Effect.provide(server.layer));
329
+ },
330
+ );
331
+});
332
+
333
describe("GitCafePullRequestProvider", () => {
334
it.effect("keeps a staging repository's requests and links on staging", () => {
335
// CAFE_TOKEN follows CAFE_HOST, so staging reads the env token only when it is the target.
packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
+123
@@ -116,6 +116,30 @@ const Listed = Schema.Struct({
116
});
117
const encodeIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
118
const BranchCommit = Schema.Struct({ oid: TrimmedNonEmptyString });
119
+const CommitOid = Schema.String.check(Schema.isPattern(/^[0-9a-f]{40}$/u));
120
+const isCommitOid = Schema.is(CommitOid);
121
+const SourceSnapshot = Schema.Struct({
122
+ version: NonNegativeInt,
123
+ headOid: CommitOid,
124
+ comparisonBaseOid: CommitOid,
125
+});
126
+const SourceBlob = Schema.Struct({
127
+ commit: CommitOid,
128
+ path: Schema.String,
129
+ size: NonNegativeInt,
130
+ binary: Schema.Boolean,
131
+ content: Schema.NullOr(Schema.String),
132
+});
133
+const MAX_DIFF_FILE_BYTES = 1024 * 1024;
134
+
135
+class GitCafeDiffSourceUnavailableError extends Schema.TaggedError<GitCafeDiffSourceUnavailableError>()(
136
+ "GitCafeDiffSourceUnavailableError",
137
+ {
138
+ path: Schema.String,
139
+ reason: Schema.Literals(["oversized", "binary", "unavailable"]),
140
+ cause: Schema.optional(Schema.Defect()),
141
+ },
142
+) {}
143
const Snapshot = {
144
version: NonNegativeInt,
145
headOid: TrimmedNonEmptyString,
@@ -271,6 +295,58 @@ export const make = Effect.gen(function* () {
295
Effect.flatMap((path) => read(operation, input, { path }, Json.GitCafePullDetail)),
296
);
297
298
+ const readDiffSource = Effect.fn("GitCafePullRequestProvider.readDiffSource")(function* (
299
+ input: ProviderRepositoryRef,
300
+ revision: string,
301
+ filePath: string,
302
+ ) {
303
+ const operation = "getDiffFileContents";
304
+ const base = yield* repositoryPath(operation, input);
305
+ const query = new URLSearchParams({ oid: revision, path: filePath });
306
+ const blob = yield* read(operation, input, { path: `${base}/blob?${query}` }, SourceBlob).pipe(
307
+ Effect.catchIf(
308
+ (error) =>
309
+ isApiError(error.cause) && (error.cause.status === 413 || error.cause.status === 501),
310
+ (error) =>
311
+ Effect.fail(
312
+ failure(
313
+ operation,
314
+ "GitCafe cannot provide this source file as bounded text.",
315
+ new GitCafeDiffSourceUnavailableError({
316
+ path: filePath,
317
+ reason:
318
+ isApiError(error.cause) && error.cause.status === 413
319
+ ? "oversized"
320
+ : "unavailable",
321
+ cause: error,
322
+ }),
323
+ ),
324
+ ),
325
+ ),
326
+ );
327
+ if (blob.commit !== revision || blob.path !== filePath)
328
+ return yield* failure(
329
+ operation,
330
+ "GitCafe answered with a different source revision or path.",
331
+ );
332
+ const reason =
333
+ blob.size > MAX_DIFF_FILE_BYTES ||
334
+ (blob.content !== null && Buffer.byteLength(blob.content, "utf8") > MAX_DIFF_FILE_BYTES)
335
+ ? "oversized"
336
+ : blob.binary || blob.content?.includes("\0")
337
+ ? "binary"
338
+ : blob.content === null
339
+ ? "unavailable"
340
+ : null;
341
+ if (reason !== null)
342
+ return yield* failure(
343
+ operation,
344
+ "GitCafe cannot provide this source file as bounded text.",
345
+ new GitCafeDiffSourceUnavailableError({ path: filePath, reason }),
346
+ );
347
+ return blob.content!;
348
+ });
349
+
350
const readPages = Effect.fn("GitCafePullRequestProvider.readPages")(function* <
351
S extends Schema.Codec<Paged<unknown>, unknown, never, never>,
352
>(operation: string, input: Pick<ProviderRepositoryRef, "host">, path: string, schema: S) {
@@ -926,6 +1002,53 @@ export const make = Effect.gen(function* () {
1002
nextCursor: page.next === null ? null : encodeDiffCursor({ ...revision, after: page.next }),
1003
};
1004
}),
1005
+ getDiffFileContents: Effect.fn("GitCafePullRequestProvider.getDiffFileContents")(
1006
+ function* (input) {
1007
+ const operation = "getDiffFileContents";
1008
+ if (input.commit !== undefined)
1009
+ return yield* failure(operation, "GitCafe commit diff contents are not supported yet.");
1010
+ const pull = yield* readPull(operation, input);
1011
+ if (!isCommitOid(pull.headOid))
1012
+ return yield* failure(
1013
+ operation,
1014
+ "GitCafe has not reported an immutable pull request head.",
1015
+ );
1016
+ const path = yield* pullPath(operation, input);
1017
+ const query = new URLSearchParams({ expectedVersion: String(pull.version), limit: "1" });
1018
+ // observedBaseOid is the target tip, not necessarily the diff's merge base.
1019
+ const snapshot = yield* read(
1020
+ operation,
1021
+ input,
1022
+ { path: `${path}/changes?${query}` },
1023
+ SourceSnapshot,
1024
+ );
1025
+ if (snapshot.version !== pull.version || snapshot.headOid !== pull.headOid)
1026
+ return yield* failure(
1027
+ operation,
1028
+ "GitCafe changed the pull request revision. Refresh the diff.",
1029
+ );
1030
+ const sourceRepository =
1031
+ pull.sourceRepo === null
1032
+ ? input.repository
1033
+ : `${pull.sourceRepo.owner}/${pull.sourceRepo.name}`;
1034
+ const [oldContents, newContents] = yield* Effect.all(
1035
+ [
1036
+ input.changeType === "new"
1037
+ ? Effect.succeed("")
1038
+ : readDiffSource(input, snapshot.comparisonBaseOid, input.oldPath),
1039
+ input.changeType === "deleted"
1040
+ ? Effect.succeed("")
1041
+ : readDiffSource(
1042
+ { ...input, repository: sourceRepository },
1043
+ snapshot.headOid,
1044
+ input.newPath,
1045
+ ),
1046
+ ],
1047
+ { concurrency: 2 },
1048
+ );
1049
+ return { oldContents, newContents };
1050
+ },
1051
+ ),
1052
runAction: Effect.fn("GitCafePullRequestProvider.runAction")(function* (input) {
1053
if (input.stackNumber !== undefined)
1054
return yield* runStackAction({ ...input, stackNumber: input.stackNumber });
packages/source-control-gitcafe/src/server/gitCafePullRequestJson.test.ts
+109
@@ -336,6 +336,115 @@ describe("toStack", () => {
336
});
337
338
describe("toDiff", () => {
339
+ it("marks the unterminated 93-byte tunnel-release migration as missing its final newline", () => {
340
+ const content =
341
+ 'ALTER TABLE "relay_managed_endpoint_allocations" ADD COLUMN "tunnel_released_at" varchar(64);';
342
+ assert.strictEqual(Buffer.byteLength(content), 93);
343
+ const { patch } = GitCafePullRequestJson.toDiff(
344
+ decodeDiff({
345
+ items: [
346
+ {
347
+ path: "infra/relay/migrations/postgres/20261005232034_managed_endpoint_tunnel_released_at/migration.sql",
348
+ status: "added",
349
+ hunks: [
350
+ {
351
+ oldStart: 1,
352
+ oldLines: 0,
353
+ newStart: 1,
354
+ newLines: 1,
355
+ lines: [{ origin: "+", content }],
356
+ },
357
+ ],
358
+ },
359
+ ],
360
+ }),
361
+ );
362
+ assert.isTrue(patch.endsWith(`+${content}\n\\ No newline at end of file\n`));
363
+ });
364
+
365
+ it.each(["+", "-", " "])("marks unterminated ordinary %j lines", (origin) => {
366
+ const { patch } = GitCafePullRequestJson.toDiff(
367
+ decodeDiff({
368
+ items: [
369
+ {
370
+ path: "file.ts",
371
+ status: "modified",
372
+ hunks: [
373
+ {
374
+ oldStart: 1,
375
+ oldLines: origin === "+" ? 0 : 1,
376
+ newStart: 1,
377
+ newLines: origin === "-" ? 0 : 1,
378
+ lines: [{ origin, content: "value" }],
379
+ },
380
+ ],
381
+ },
382
+ ],
383
+ }),
384
+ );
385
+ assert.isTrue(patch.endsWith(`${origin}value\n\\ No newline at end of file\n`));
386
+ });
387
+
388
+ it.each([
389
+ ["+", ">"],
390
+ ["-", "<"],
391
+ [" ", "="],
392
+ ])("emits one marker for an explicit %s/%s EOF pair", (origin, marker) => {
393
+ const { patch } = GitCafePullRequestJson.toDiff(
394
+ decodeDiff({
395
+ items: [
396
+ {
397
+ path: "file.ts",
398
+ status: "modified",
399
+ hunks: [
400
+ {
401
+ oldStart: 1,
402
+ oldLines: origin === "+" ? 0 : 1,
403
+ newStart: 1,
404
+ newLines: origin === "-" ? 0 : 1,
405
+ lines: [
406
+ { origin, content: "value" },
407
+ { origin: marker, content: "\n" },
408
+ ],
409
+ },
410
+ ],
411
+ },
412
+ ],
413
+ }),
414
+ );
415
+ assert.strictEqual(patch.split("\\ No newline at end of file").length - 1, 1);
416
+ });
417
+
418
+ it.each([false, true])("preserves rename metadata for changed=%s", (changed) => {
419
+ const { patch } = GitCafePullRequestJson.toDiff(
420
+ decodeDiff({
421
+ items: [
422
+ {
423
+ path: "after.ts",
424
+ oldPath: "before.ts",
425
+ status: "renamed",
426
+ hunks: changed
427
+ ? [
428
+ {
429
+ oldStart: 1,
430
+ oldLines: 1,
431
+ newStart: 1,
432
+ newLines: 1,
433
+ lines: [
434
+ { origin: "-", content: "before\n" },
435
+ { origin: "+", content: "after\n" },
436
+ ],
437
+ },
438
+ ]
439
+ : [],
440
+ },
441
+ ],
442
+ }),
443
+ );
444
+ assert.include(patch, changed ? "similarity index 0%\n" : "similarity index 100%\n");
445
+ assert.include(patch, "rename from before.ts\nrename to after.ts\n");
446
+ });
447
+
448
it("converts numeric hunk coordinates into a unified patch", () => {
449
const diff = decodeDiff({
450
items: [
packages/source-control-gitcafe/src/server/gitCafePullRequestJson.ts
+26
-4
@@ -567,6 +567,10 @@ export function toStack(stack: GitCafeStack, target: RepositoryOnHost): Provider
567
};
568
}
569
570
+function isEOFMarker(origin: string | undefined) {
571
+ return origin === "=" || origin === ">" || origin === "<";
572
+}
573
+
574
export function toDiff(diff: typeof GitCafeDiff.Type): ProviderDiffSlice {
575
const chunks: Array<string> = [];
576
const omittedFileStats: Array<{ path: string; additions: number; deletions: number }> = [];
@@ -582,7 +586,16 @@ export function toDiff(diff: typeof GitCafeDiff.Type): ProviderDiffSlice {
586
if (file.status === "deleted") lines.push(`deleted file mode ${mode}`);
587
if (file.status === "renamed" || file.status === "copied") {
588
const action = file.status === "renamed" ? "rename" : "copy";
589
+ const hasChanges =
590
+ (file.hunks?.length ?? 0) > 0 ||
591
+ (file.additions ?? 0) > 0 ||
592
+ (file.deletions ?? 0) > 0 ||
593
+ file.binary ||
594
+ file.tooLarge ||
595
+ file.hunksOmitted;
596
+ // GitCafe has no similarity score; Pierre needs this header to retain rename metadata.
597
lines.push(
598
+ `similarity index ${hasChanges ? 0 : 100}%`,
599
`${action} from ${quoteGitPatchPath(oldPath)}`,
600
`${action} to ${quoteGitPatchPath(file.path)}`,
601
);
@@ -607,10 +620,19 @@ export function toDiff(diff: typeof GitCafeDiff.Type): ProviderDiffSlice {
620
if (hunks.length > 0) lines.push(`--- ${before}`, `+++ ${after}`);
621
for (const hunk of hunks) {
622
lines.push(`@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`);
610
- for (const line of hunk.lines) {
611
- // GitCafe marks a missing final newline with libgit2's own origins.
612
- if (["=", ">", "<"].includes(line.origin)) lines.push("\\ No newline at end of file");
613
- else lines.push(`${line.origin}${line.content.replace(/\n$/u, "")}`);
623
+ for (const [index, line] of hunk.lines.entries()) {
624
+ if (isEOFMarker(line.origin)) {
625
+ lines.push("\\ No newline at end of file");
626
+ } else {
627
+ lines.push(`${line.origin}${line.content.replace(/\n$/u, "")}`);
628
+ if (
629
+ ["+", "-", " "].includes(line.origin) &&
630
+ !line.content.endsWith("\n") &&
631
+ !isEOFMarker(hunk.lines[index + 1]?.origin)
632
+ ) {
633
+ lines.push("\\ No newline at end of file");
634
+ }
635
+ }
636
}
637
}
638
}