@devries-cameron20 / t3code-1 / commits / 8b2c4d1ed9
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

perf(mobile): avoid code row scans while dragging file paths (#25484)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: SAPHID <saphid@users.noreply.github.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Alex Southwell committed Nov 6, 2026 at 01:08 UTC 8b2c4d1ed97fbce748c93a42cf276a87b8c5537e
5 files changed +262 -3
apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt
+2 -1
@@ -1129,7 +1129,8 @@ private class DiffCanvasView(context: Context) : View(context) {
1129 }
1130
1131 private fun maxHeaderPathOffset(fileId: String): Int {
1132 - val row = rows.firstOrNull { it.kind == "file" && it.resolvedFileId == fileId } ?: return 0
1132 + val rowIndex = fileHeaderIndices.firstOrNull { rows[it].resolvedFileId == fileId } ?: return 0
1133 + val row = rows[rowIndex]
1134 val top = 0
1135 val bottom = rowHeight(row)
1136 val iconRect = drawing.fileHeaderIconRect(top, bottom, style)
apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift
+2 -2
@@ -1929,8 +1929,8 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
1929
1930 private func maxHorizontalOffset(for target: (fileId: String, kind: ReviewDiffHorizontalPanKind)) -> CGFloat {
1931 if target.kind == .fileHeaderPath,
1932 - let row = rows.first(where: { resolvedFileId(for: $0) == target.fileId && $0.kind == "file" }) {
1933 - return maxHeaderPathOffset(for: row)
1932 + let rowIndex = fileHeaderRowIndex(forFileId: target.fileId) {
1933 + return maxHeaderPathOffset(for: rows[rowIndex])
1934 }
1935 if codeWrapColumns != nil {
1936 return 0
apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt
+153
@@ -219,6 +219,157 @@ class ReviewDiffGeometryTest {
219 }
220 }
221
222 + @Test
223 + fun headerPathLimitsKeepFirstMatchAndNeverReadCodeRows() {
224 + val parent = T3ReviewDiffView(RuntimeEnvironment.getApplication(), AppContext())
225 + val reference = T3ReviewDiffView(RuntimeEnvironment.getApplication(), AppContext())
226 + val canvas = parent.getChildAt(0)
227 + val oracle = reference.getChildAt(0)
228 + val spec = View.MeasureSpec.makeMeasureSpec(390, View.MeasureSpec.EXACTLY)
229 + for (view in listOf(canvas, oracle)) {
230 + view.measure(spec, spec)
231 + view.layout(0, 0, 390, 600)
232 + }
233 + val longPath = "long/directory/".repeat(12)
234 + val ordinary = headerRows(longPath)
235 + val input = listOf(row("impostor", "value").copy(fileId = "f9")) + ordinary + listOf(
236 + row("duplicate:header", "").copy(kind = "file", fileId = "f9", filePath = "short.kt"),
237 + row("id-fallback", "").copy(kind = "file", fileId = "", filePath = longPath + "fallback.kt"),
238 + row("", "").copy(kind = "file", fileId = "", filePath = longPath + "empty.kt"),
239 + row("orphan:line:0", "code ".repeat(100)).copy(fileId = "orphan"),
240 + )
241 + try {
242 + // Drive the production collapse path from its full decoded payload boundary.
243 + parent.javaClass.getDeclaredField("rows").apply { isAccessible = true }.set(parent, input)
244 + call(parent, "rebuildVisibleRows")
245 + for (wrap in listOf(false, true)) {
246 + parent.setStyleJson("{\"wordWrap\":$wrap}")
247 + reference.setStyleJson("{\"wordWrap\":$wrap}")
248 + for (collapsed in listOf("[]", "[\"f0\",\"f5\"]", "[]")) {
249 + parent.setCollapsedFileIdsJson(collapsed)
250 + checkHeaderLimits(canvas, oracle, input, wrap, collapsed)
251 + }
252 + }
253 + parent.setStyleJson("{\"wordWrap\":false}")
254 + val counted = CountingRows(ordinary)
255 + call(canvas, "setRows", counted)
256 + val target = panTarget(canvas, "f9", "FILE_HEADER_PATH")
257 + call(canvas, "resetHorizontalOffsets")
258 + counted.reads = 0
259 + counted.codeReads = 0
260 + repeat(120) { call(canvas, "scrollByHorizontal", 1, target) }
261 + val panReads = counted.reads
262 + val panCodeReads = counted.codeReads
263 + counted.reads = 0
264 + counted.codeReads = 0
265 + repeat(120) { call(canvas, "clampHeaderPathOffsets") }
266 + val clampReads = counted.reads
267 + val clampCodeReads = counted.codeReads
268 + println(
269 + "HEADER_LOOKUP Android updates=120 panReads=$panReads panCodeReads=$panCodeReads " +
270 + "clampReads=$clampReads clampCodeReads=$clampCodeReads"
271 + )
272 + call(
273 + canvas,
274 + "setRows",
275 + listOf(row("replacement", "").copy(kind = "file", fileId = "f9", filePath = "short.kt"))
276 + )
277 + assertEquals(0, headerLimit(canvas, "f9"))
278 + assertEquals(0, headerOffset(canvas, "f9"))
279 + parent.setContentResetKey("new-content")
280 + assertEquals(0, headerLimit(canvas, "f9"))
281 + assertTrue((field(canvas, "fileHeaderIndices") as IntArray).isEmpty())
282 + assertTrue((field(canvas, "headerPathOffsetsByFileId") as Map<*, *>).isEmpty())
283 + println(
284 + "Passed Android header limits: first/middle/last, duplicate, empty/missing IDs, rename, " +
285 + "collapse/reexpand, replacement/reset, wrap and code bounds"
286 + )
287 + assertEquals("Header pans must not inspect code rows", 0, panCodeReads)
288 + assertEquals("Header clamps must not inspect code rows", 0, clampCodeReads)
289 + assertTrue("Header pans must read only preceding headers", panReads <= 1320)
290 + assertTrue("Header clamps must read only preceding headers", clampReads <= 1320)
291 + } finally {
292 + parent.cleanup()
293 + reference.cleanup()
294 + }
295 + }
296 +
297 + private fun headerRows(longPath: String): List<DiffRow> = (0 until 10).flatMap { file ->
298 + listOf(
299 + row("f$file:header", "").copy(
300 + kind = "file",
301 + fileId = "f$file",
302 + filePath = "${longPath}new-$file.kt",
303 + previousPath = "old-$file.kt",
304 + additions = file + 1,
305 + deletions = file * 2,
306 + )
307 + ) +
308 + List(100) { line -> row("f$file:line:$line", "code ".repeat(100)).copy(fileId = "f$file") }
309 + }
310 +
311 + private fun checkHeaderLimits(
312 + canvas: View,
313 + oracle: View,
314 + input: List<DiffRow>,
315 + wrap: Boolean,
316 + collapsed: String
317 + ) {
318 + for ((caseIndex, id) in listOf(
319 + "f0",
320 + "f5",
321 + "f9",
322 + "id-fallback",
323 + "",
324 + "orphan",
325 + "missing"
326 + ).withIndex()) {
327 + val header = input.firstOrNull { it.kind == "file" && it.resolvedFileId == id }
328 + call(oracle, "setRows", listOfNotNull(header))
329 + val expected = headerLimit(oracle, id)
330 + val actual = headerLimit(canvas, id)
331 + println("HEADER_LIMIT Android wrap=$wrap collapsed=$collapsed case=$caseIndex limit=$actual")
332 + assertEquals("wrap=$wrap collapsed=$collapsed id=$id", expected, actual)
333 + if (header != null) assertTrue("Long rename/header path must overflow", expected > 0)
334 + val target = panTarget(canvas, id, "FILE_HEADER_PATH")
335 + assertEquals(expected, call(canvas, "maxHorizontalOffset", target))
336 + call(canvas, "scrollByHorizontal", 1_000_000, target)
337 + assertEquals(expected, headerOffset(canvas, id))
338 + call(canvas, "scrollByHorizontal", -1_000_000, target)
339 + assertEquals(0, headerOffset(canvas, id))
340 + call(canvas, "scrollByHorizontal", 1, target)
341 + call(canvas, "clampHeaderPathOffsets")
342 + assertEquals(minOf(1, expected), headerOffset(canvas, id))
343 + }
344 + val codeTarget = panTarget(canvas, "f9", "CODE")
345 + val codeLimit = call(canvas, "maxHorizontalOffset") as Int
346 + assertEquals(codeLimit, call(canvas, "maxHorizontalOffset", codeTarget))
347 + if (wrap) assertEquals(0, codeLimit) else assertTrue(codeLimit > 0)
348 + call(canvas, "scrollByHorizontal", 1_000_000, codeTarget)
349 + assertEquals(codeLimit, call(canvas, "horizontalOffset"))
350 + call(canvas, "scrollByHorizontal", -1_000_000, codeTarget)
351 + assertEquals(0, call(canvas, "horizontalOffset"))
352 + }
353 +
354 + private fun headerLimit(canvas: View, id: String): Int = canvas.javaClass
355 + .getDeclaredMethod("maxHeaderPathOffset", String::class.java).apply { isAccessible = true }
356 + .invoke(canvas, id) as Int
357 +
358 + private fun headerOffset(canvas: View, id: String): Int =
359 + (field(canvas, "headerPathOffsetsByFileId") as Map<*, *>)[id] as Int? ?: 0
360 +
361 + private fun panTarget(canvas: View, id: String, kind: String): Any {
362 + val targetClass = canvas.javaClass.declaredMethods.single {
363 + it.name == "scrollByHorizontal"
364 + }.parameterTypes[1]
365 + val constructor = targetClass.declaredConstructors.single().apply { isAccessible = true }
366 + val enumValue = constructor.parameterTypes[1].enumConstants.single {
367 + (it as Enum<*>).name ==
368 + kind
369 + }
370 + return constructor.newInstance(id, enumValue)
371 + }
372 +
373 private fun call(target: Any, name: String, vararg args: Any): Any? = target.javaClass
374 .declaredMethods.single { it.name == name && it.parameterCount == args.size }
375 .apply { isAccessible = true }.invoke(target, *args)
@@ -235,9 +386,11 @@ class ReviewDiffGeometryTest {
386
387 private class CountingRows(private val rows: List<DiffRow>) : AbstractList<DiffRow>() {
388 var reads = 0
389 + var codeReads = 0
390 override val size: Int get() = rows.size
391 override fun get(index: Int): DiffRow {
392 reads += 1
393 + if (rows[index].kind != "file") codeReads += 1
394 return rows[index]
395 }
396 }
apps/mobile/modules/t3-review-diff/tests/ios/geometry.swift
+95
@@ -103,6 +103,101 @@ geometryView.mergeTokensByRowId(["a:line:29": [ReviewDiffNativeToken(content: ge
103 geometryView.selectedRowIds = ["a:line:29"]
104 check(geometryView.contentHeight == originalHeight, "Tokens and selection must preserve geometry")
105
106 +// The runner instruments the production resolver in its temporary compile input only.
107 +private enum HeaderLookupReads {
108 + static var enabled = false
109 + static var headers = 0
110 + static var code = 0
111 + static func record(_ row: ReviewDiffNativeRow) {
112 + guard enabled else { return }
113 + if row.kind == "file" { headers += 1 } else { code += 1 }
114 + }
115 +}
116 +
117 +private extension ReviewDiffContentView {
118 + func checkHeaderPathLimits() throws {
119 + viewportWidth = 390
120 + let longPath = String(repeating: "long/directory/", count: 12)
121 + func decode(_ input: [[String: Any]]) throws -> [ReviewDiffNativeRow] {
122 + try JSONDecoder().decode([ReviewDiffNativeRow].self, from: JSONSerialization.data(withJSONObject: input))
123 + }
124 + var fixture: [[String: Any]] = []
125 + for file in 0..<10 {
126 + fixture.append(["kind": "file", "id": "f\(file):header", "fileId": "f\(file)",
127 + "filePath": longPath + "new-\(file).swift", "previousPath": "old-\(file).swift",
128 + "additions": file + 1, "deletions": file * 2])
129 + for line in 0..<100 {
130 + fixture.append(["kind": "line", "id": "f\(file):line:\(line)", "fileId": "f\(file)",
131 + "content": String(repeating: "code ", count: 100)])
132 + }
133 + }
134 + // A code row sharing the target ID must not hide the first header.
135 + fixture.insert(["kind": "line", "id": "impostor", "fileId": "f9", "content": "value"], at: 0)
136 + fixture += [
137 + ["kind": "file", "id": "duplicate:header", "fileId": "f9", "filePath": "short.swift"],
138 + ["kind": "file", "id": "empty:header", "fileId": "", "filePath": longPath + "empty.swift"],
139 + ["kind": "file", "id": "derived:header", "filePath": longPath + "derived.swift"],
140 + ["kind": "file", "id": "path-fallback", "filePath": longPath + "fallback.swift"],
141 + ["kind": "file", "id": "id-only"],
142 + ["kind": "line", "id": "orphan:line:0", "fileId": "orphan", "content": String(repeating: "code ", count: 100)]
143 + ]
144 + let input = try decode(fixture)
145 + rows = input
146 + for wrap in [false, true] {
147 + style = try geometryStyle(wrap: wrap)
148 + func verify(_ label: String) {
149 + for (caseIndex, id) in ["f0", "f5", "f9", "", "derived", longPath + "fallback.swift", "id-only", "orphan", "missing"].enumerated() {
150 + let header = rows.first { $0.kind == "file" && $0.resolvedFileId == id }
151 + let expected = header.map { maxHeaderPathOffset(for: $0) }
152 + ?? maxHorizontalOffset(for: (fileId: id, kind: .code))
153 + let actual = maxHorizontalOffset(for: (fileId: id, kind: .fileHeaderPath))
154 + print("HEADER_LIMIT iOS wrap=\(wrap) state=\(label) case=\(caseIndex) limit=\(actual)")
155 + check(actual == expected, "\(label) wrap=\(wrap) id=\(id): header path limit changed")
156 + if ["f0", "f5", "f9", "", "derived"].contains(id) {
157 + check(actual > 0, "Long rename/header path must overflow in either wrap mode")
158 + }
159 + // This is the same clamp called after token, style, and viewport changes.
160 + setHorizontalOffset(.greatestFiniteMagnitude, for: id, kind: .fileHeaderPath)
161 + clampHorizontalOffsets()
162 + check(horizontalOffset(for: id, kind: .fileHeaderPath) == expected, "Header clamp changed")
163 + setHorizontalOffset(13, for: id, kind: .code)
164 + clampHorizontalOffsets()
165 + check(horizontalOffset(for: id, kind: .code) == min(13, maxHorizontalOffset(for: (id, .code))),
166 + "Code bounds changed")
167 + }
168 + }
169 + verify("expanded")
170 + collapsedFileIds = ["f0", "f5"]
171 + verify("collapsed")
172 + collapsedFileIds = []
173 + verify("reexpanded")
174 + }
175 + // Known fixture: ten headers separated by 100 code rows; repeatedly clamp the last.
176 + rows = try decode(Array(fixture[1..<1011]))
177 + style = try geometryStyle(wrap: false)
178 + headerPathOffsetsByFileId = ["f9": 1]
179 + horizontalOffsetsByFileId = [:]
180 + HeaderLookupReads.headers = 0
181 + HeaderLookupReads.code = 0
182 + HeaderLookupReads.enabled = true
183 + for _ in 0..<120 { clampHorizontalOffsets() }
184 + HeaderLookupReads.enabled = false
185 + print("HEADER_LOOKUP iOS updates=120 headerVisits=\(HeaderLookupReads.headers) codeVisits=\(HeaderLookupReads.code)")
186 + // Finish semantic checks before rejecting baseline scan work.
187 + rows = try decode([["kind": "file", "id": "replacement:header", "fileId": "f9", "filePath": "short.swift"]])
188 + check(headerPathOffsetsByFileId.isEmpty && horizontalOffsetsByFileId.isEmpty, "Replacement clears offsets")
189 + check(maxHorizontalOffset(for: ("f9", .fileHeaderPath)) == 0, "Replacement must use current header")
190 + rows = []
191 + check(fileHeaderRowIndices.isEmpty && headerPathOffsetsByFileId.isEmpty, "Reset must clear old index/offsets")
192 + check(maxHorizontalOffset(for: ("f9", .fileHeaderPath)) == maxHorizontalOffset(for: ("f9", .code)),
193 + "Missing-header fallback after reset changed")
194 + print("Passed iOS header limits: first/middle/last, duplicate, empty/absent IDs, rename, collapse/reexpand, replacement/reset, wrap and code bounds")
195 + check(HeaderLookupReads.code == 0, "Header clamps must not inspect code rows")
196 + check(HeaderLookupReads.headers == 1200, "Header clamps must visit only preceding headers")
197 + }
198 +}
199 +try ReviewDiffContentView(frame: CGRect(x: 0, y: 0, width: 390, height: 600)).checkHeaderPathLimits()
200 +
201 // Configuration changes before publication must restart preparation from a fresh snapshot.
202 private let geometryQueue = DispatchQueue(label: "review-diff.geometry-tests")
203 geometryQueue.suspend()
apps/mobile/modules/t3-review-diff/tests/run-ios.sh
+10
@@ -31,6 +31,16 @@ method = source[start:end]
31 fallback = " self.contentView.tokensByRowId = [:]"
32 assert method.count(fallback) == 1
33 source = source[:start] + method.replace(fallback, fallback + "\n tokenDecodeProbe.publish()") + source[end:]
34 +# Count the actual lookup's row visits only in the compiled test copy.
35 +needle = """ private func resolvedFileId(for row: ReviewDiffNativeRow) -> String {
36 + row.resolvedFileId
37 + }"""
38 +if source.count(needle) != 1:
39 + raise RuntimeError("Header lookup instrumentation seam changed")
40 +source = source.replace(needle, """ private func resolvedFileId(for row: ReviewDiffNativeRow) -> String {
41 + HeaderLookupReads.record(row)
42 + return row.resolvedFileId
43 + }""")
44 stubs = """
45 public final class AppContext {}
46 open class ExpoView: UIView {