@devries-cameron20 / t3code Mirror · read-only / commits / bc9080f4d6
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 03:15 UTC

perf(mobile): skip obsolete queued iOS diff row decodes (#25287)

Co-authored-by: SAPHID <saphid@users.noreply.github.com>

Alex Southwell committed Nov 6, 2026 at 00:49 UTC bc9080f4d687e07440cba9d0b08bcdab3a722c56
4 files changed +283 -2
apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift
+12
@@ -340,6 +340,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
340 private var pendingScrollAnimated = false
341 private var isProgrammaticScrollActive = false
342 private var rowsDecodeGeneration = 0
343 + private var rowsDecodeCancellation: ReviewDiffRowPreparation?
344 private var tokensDecodeGeneration = 0
345
346 let onDebug = EventDispatcher()
@@ -387,6 +388,10 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
388 scrollView.addSubview(contentView)
389 }
390
391 + deinit {
392 + rowsDecodeCancellation?.cancel()
393 + }
394 +
395 public override func layoutSubviews() {
396 super.layoutSubviews()
397 let anchor = contentView.viewportWidth != bounds.width ? contentView.viewportRowAnchor() : nil
@@ -426,10 +431,15 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
431
432 func setRowsJson(_ rowsJson: String) {
433 contentView.cancelRowPreparation()
434 + rowsDecodeCancellation?.cancel()
435 + let cancellation = ReviewDiffRowPreparation()
436 + rowsDecodeCancellation = cancellation
437 rowsDecodeGeneration += 1
438 let generation = rowsDecodeGeneration
439
440 payloadDecodeQueue.async { [weak self] in
441 + // Check weak liveness without retaining the view or reading its UIKit state.
442 + guard !cancellation.isCancelled, self != nil else { return }
443 guard let data = rowsJson.data(using: .utf8) else {
444 return
445 }
@@ -601,6 +611,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
611 self.contentResetKey = contentResetKey
612 lastVisibleRangeDebugKey = ""
613 contentView.cancelRowPreparation()
614 + rowsDecodeCancellation?.cancel()
615 + rowsDecodeCancellation = nil
616 rowsDecodeGeneration += 1
617 tokensDecodeGeneration += 1
618 contentView.tokensByRowId = [:]
apps/mobile/modules/t3-review-diff/tests/ios/geometry.swift
+1 -1
@@ -125,7 +125,7 @@ geometryView.prepareRows(geometryRows, on: geometryQueue, isCurrent: { true }, c
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)
128 + runRowDecodeTests()
129 }
130 }
131 })
apps/mobile/modules/t3-review-diff/tests/ios/row-decode.swift new
+262
@@ -0,0 +1,262 @@
1 +// The harness instruments only decoder entry; scheduling and publication use the real view.
2 +private final class RowDecodeProbe {
3 + private let lock = NSLock()
4 + private var entries = 0
5 + private var onEntry: ((Int) -> Void)?
6 +
7 + func reset(onEntry: ((Int) -> Void)? = nil) {
8 + lock.lock()
9 + entries = 0
10 + self.onEntry = onEntry
11 + lock.unlock()
12 + }
13 +
14 + func enter() {
15 + lock.lock()
16 + entries += 1
17 + let entry = entries
18 + let callback = onEntry
19 + lock.unlock()
20 + callback?(entry)
21 + }
22 +
23 + var count: Int {
24 + lock.lock()
25 + defer { lock.unlock() }
26 + return entries
27 + }
28 +}
29 +
30 +private let rowDecodeProbe = RowDecodeProbe()
31 +
32 +private func decodeRowsForTest(_ data: Data) throws -> [ReviewDiffNativeRow] {
33 + rowDecodeProbe.enter()
34 + return try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)
35 +}
36 +
37 +private extension ReviewDiffContentView {
38 + func checkSameGeometry(as reference: ReviewDiffContentView) {
39 + check(rowOffsets == reference.rowOffsets && contentHeight == reference.contentHeight,
40 + "Queued decoding must preserve reference row offsets and height")
41 + check(contentWidthsByFileId == reference.contentWidthsByFileId,
42 + "Queued decoding must preserve reference widths")
43 + }
44 +}
45 +
46 +private extension T3ReviewDiffView {
47 + // One worker/main round decodes, the next prepares and publishes geometry.
48 + func afterRowPipeline(_ completion: @escaping () -> Void) {
49 + Self.afterRowPipeline(on: payloadDecodeQueue, completion)
50 + }
51 +
52 + static func afterRowPipeline(on queue: DispatchQueue, _ completion: @escaping () -> Void) {
53 + queue.async {
54 + DispatchQueue.main.async {
55 + queue.async {
56 + DispatchQueue.main.async(execute: completion)
57 + }
58 + }
59 + }
60 + }
61 +
62 + func checkRowsMatch(_ json: String) {
63 + let expected = try! JSONDecoder().decode([ReviewDiffNativeRow].self, from: Data(json.utf8))
64 + check(rows.map { String(reflecting: $0) } == expected.map { String(reflecting: $0) },
65 + "Every decoded row field must match the unchanged decoder")
66 + check(contentView.rows.map { String(reflecting: $0) } == rows.map { String(reflecting: $0) })
67 + contentView.checkReferenceGeometry()
68 + let reference = ReviewDiffContentView(frame: contentView.frame)
69 + reference.style = contentView.style
70 + reference.viewportWidth = contentView.viewportWidth
71 + reference.collapsedFileIds = contentView.collapsedFileIds
72 + reference.collapsedCommentIds = contentView.collapsedCommentIds
73 + reference.rows = expected
74 + contentView.checkSameGeometry(as: reference)
75 + }
76 +
77 + func checkEmptyRows() {
78 + check(rows.isEmpty && contentView.rows.isEmpty && contentView.contentHeight == 0,
79 + "Reset/error must remain empty after the queue drains")
80 + }
81 +}
82 +
83 +private func rowDecodePayload(_ file: String) -> String {
84 + let objects: [[String: Any]] = [
85 + ["kind": "file", "id": "\(file):header", "fileId": file, "filePath": "\(file).swift"],
86 + ["kind": "hunk", "id": "\(file):hunk", "fileId": file, "text": "@@ context\t@@"],
87 + ["kind": "line", "id": "\(file):ascii", "fileId": file, "content": String(repeating: "let value = 123; ", count: 60),
88 + "change": "add", "newLineNumber": 1, "wordDiffRanges": [["start": 0, "end": 3]]],
89 + ["kind": "line", "id": "\(file):unicode", "fileId": file, "content": "漢字\t👨‍👩‍👧‍👦 e\u{301} مرحبا", "oldLineNumber": 2],
90 + ["kind": "comment", "id": "\(file):comment", "fileId": file, "commentText": "Keep every field"],
91 + ]
92 + return String(data: try! JSONSerialization.data(withJSONObject: objects), encoding: .utf8)!
93 +}
94 +
95 +private extension T3ReviewDiffView {
96 + static func runQueuedRowDecodeCase(_ index: Int) {
97 + let names = ["A to B", "reset", "reset then B", "unchanged reset key", "current success", "current error", "obsolete error"]
98 + guard index < names.count else {
99 + runReleasedRowDecodeCase()
100 + return
101 + }
102 + rowDecodeProbe.reset()
103 + let view = T3ReviewDiffView()
104 + view.bounds = CGRect(x: 0, y: 0, width: 390, height: 844)
105 + view.layoutSubviews()
106 + view.setContentResetKey("section-a")
107 + view.setStyleJson("{\"wordWrap\":true}")
108 + view.pendingScrollFileId = "pending"
109 + var events: [[String: Any]] = []
110 + view.onDebug.onEvent = { payload in
111 + if (payload["message"] as? String)?.hasPrefix("rows-decode") == true { events.append(payload) }
112 + }
113 + let a = rowDecodePayload("a")
114 + let b = rowDecodePayload("b")
115 + view.payloadDecodeQueue.suspend()
116 + switch index {
117 + case 0:
118 + view.setRowsJson(a)
119 + view.setRowsJson(b)
120 + case 1, 2:
121 + view.setRowsJson(a)
122 + view.setContentResetKey("section-b")
123 + if index == 2 { view.setRowsJson(b) }
124 + case 3:
125 + view.setRowsJson(b)
126 + view.setContentResetKey("section-a")
127 + case 4:
128 + view.setRowsJson(b)
129 + case 5:
130 + view.rows = try! JSONDecoder().decode([ReviewDiffNativeRow].self, from: Data(a.utf8))
131 + view.contentView.rows = view.rows
132 + view.setRowsJson("invalid JSON")
133 + default:
134 + view.setRowsJson("invalid JSON")
135 + view.setRowsJson(b)
136 + }
137 + view.payloadDecodeQueue.resume()
138 + view.afterRowPipeline {
139 + let expected = index == 1 ? 0 : 1
140 + check(rowDecodeProbe.count == expected,
141 + "\(names[index]): expected \(expected) decoder entries, got \(rowDecodeProbe.count)")
142 + if index == 1 {
143 + view.checkEmptyRows()
144 + check(events.isEmpty, "Reset work must not publish success or error")
145 + } else if index == 5 {
146 + view.checkEmptyRows()
147 + check(view.pendingScrollFileId == nil, "Current error must clear pending scroll")
148 + check(events.count == 1 && events[0]["message"] as? String == "rows-decode-failed")
149 + do {
150 + _ = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: Data("invalid JSON".utf8))
151 + check(false)
152 + } catch {
153 + check(events[0]["error"] as? String == error.localizedDescription, "Preserve the current error")
154 + }
155 + } else {
156 + view.checkRowsMatch(b)
157 + check(events.count == 1 && events[0]["message"] as? String == "rows-decoded",
158 + "Only the current payload may publish success")
159 + }
160 + print("Passed queued row decode: \(names[index]), decoder entries=\(rowDecodeProbe.count)")
161 + runQueuedRowDecodeCase(index + 1)
162 + }
163 + }
164 +
165 + static func runReleasedRowDecodeCase() {
166 + rowDecodeProbe.reset()
167 + var view: T3ReviewDiffView? = T3ReviewDiffView()
168 + let isReleased = { [weak view] in view == nil }
169 + let queue = view!.payloadDecodeQueue
170 + queue.suspend()
171 + view!.setRowsJson(rowDecodePayload("released"))
172 + view = nil
173 + check(isReleased(), "Queued row work must not retain the view")
174 + queue.resume()
175 + T3ReviewDiffView.afterRowPipeline(on: queue) {
176 + check(rowDecodeProbe.count == 0, "Release before worker resume must skip decoding")
177 + print("Passed release before worker resume, decoder entries=0")
178 + runRunningRowDecodeCase(invalid: false)
179 + }
180 + }
181 +
182 + static func runRunningRowDecodeCase(invalid: Bool) {
183 + let view = T3ReviewDiffView()
184 + let release = DispatchSemaphore(value: 0)
185 + let b = rowDecodePayload("current")
186 + var publications = 0
187 + view.onDebug.onEvent = { payload in
188 + if (payload["message"] as? String)?.hasPrefix("rows-decode") == true {
189 + check(payload["message"] as? String == "rows-decoded", "Running stale errors must not publish")
190 + publications += 1
191 + }
192 + }
193 + rowDecodeProbe.reset { entry in
194 + guard entry == 1 else { return }
195 + DispatchQueue.main.async {
196 + view.setContentResetKey("new-section")
197 + view.setRowsJson(b)
198 + release.signal()
199 + view.afterRowPipeline {
200 + check(rowDecodeProbe.count == 2, "An entered decoder must finish; the current payload must also decode")
201 + check(publications == 1, "Running obsolete success/error must not publish")
202 + view.checkRowsMatch(b)
203 + rowDecodeProbe.reset()
204 + print("Passed running \(invalid ? "error" : "success") replaced by current rows, decoder entries=2")
205 + if invalid { runReleasedRunningRowDecodeCase() } else { runRunningRowDecodeCase(invalid: true) }
206 + }
207 + }
208 + release.wait()
209 + }
210 + view.setRowsJson(invalid ? "invalid JSON" : rowDecodePayload("running"))
211 + }
212 +
213 + static func runReleasedRunningRowDecodeCase() {
214 + var view: T3ReviewDiffView? = T3ReviewDiffView()
215 + let isReleased = { [weak view] in view == nil }
216 + let queue = view!.payloadDecodeQueue
217 + let release = DispatchSemaphore(value: 0)
218 + var publications = 0
219 + view!.onDebug.onEvent = { payload in
220 + if (payload["message"] as? String)?.hasPrefix("rows-decode") == true { publications += 1 }
221 + }
222 + rowDecodeProbe.reset { _ in
223 + DispatchQueue.main.async {
224 + view = nil
225 + check(isReleased(), "An entered decoder must not retain the view")
226 + release.signal()
227 + afterRowPipeline(on: queue) {
228 + check(rowDecodeProbe.count == 1 && publications == 0,
229 + "An entered decode may finish after release but must not publish")
230 + rowDecodeProbe.reset()
231 + print("Passed release after decoder entry without retaining the view, decoder entries=1")
232 + runAdditiveTokenPatchCase()
233 + }
234 + }
235 + release.wait()
236 + }
237 + view!.setRowsJson(rowDecodePayload("released-running"))
238 + }
239 +
240 + static func runAdditiveTokenPatchCase() {
241 + let view = T3ReviewDiffView()
242 + view.setTokensResetKey("tokens")
243 + view.payloadDecodeQueue.suspend()
244 + var acknowledgements: [Bool] = []
245 + for id in ["one", "two"] {
246 + view.setTokensPatchJson("{\"resetKey\":\"tokens\",\"tokensByRowId\":{\"\(id)\":[{\"content\":\"\(id)\"}]}}") {
247 + acknowledgements.append($0)
248 + }
249 + }
250 + view.payloadDecodeQueue.resume()
251 + view.afterRowPipeline {
252 + check(acknowledgements == [true, true], "Every additive token patch must be acknowledged")
253 + check(Set(view.contentView.tokensByRowId.keys) == Set(["one", "two"]), "Token patches must never coalesce")
254 + print("Passed additive token patches and acknowledgements; all 12 row/payload lifecycle cases passed")
255 + exit(0)
256 + }
257 + }
258 +}
259 +
260 +private func runRowDecodeTests() {
261 + T3ReviewDiffView.runQueuedRowDecodeCase(0)
262 +}
apps/mobile/modules/t3-review-diff/tests/run-ios.sh
+8 -1
@@ -12,6 +12,10 @@ 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 +# Count entry into the real decoder without replacing the production queue or lifecycle.
16 +row_decode = "try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)"
17 +assert source.count(row_decode) == 1
18 +source = source.replace(row_decode, "try decodeRowsForTest(data)")
19 stubs = """
20 public final class AppContext {}
21 open class ExpoView: UIView {
@@ -20,16 +24,19 @@ open class ExpoView: UIView {
24 public required init?(coder: NSCoder) { fatalError("init(coder:) is unused") }
25 }
26 final class EventDispatcher {
23 - func callAsFunction(_ payload: [String: Any]) {}
27 + var onEvent: (([String: Any]) -> Void)?
28 + func callAsFunction(_ payload: [String: Any]) { onEvent?(payload) }
29 }
30 """
31 # Expo alone is stubbed; keep the real scroll container as well as the content view.
32 Path(sys.argv[2]).write_text(source + "\n" + stubs + "\n"
33 + (module / "tests/ios/main.swift").read_text() + "\n"
34 + (module / "tests/ios/anchor.swift").read_text() + "\n"
35 + + (module / "tests/ios/row-decode.swift").read_text() + "\n"
36 + (module / "tests/ios/geometry.swift").read_text())
37 PYTHON
38 "$compiler" -O -target "$(uname -m)-apple-ios16.1-macabi" -sdk "$sdk" \
39 + -module-cache-path "$output/module-cache" \
40 -F "$sdk/System/iOSSupport/System/Library/Frameworks" \
41 "$module_dir/ios/ReviewDiffCodeLayout.swift" "$output/main.swift" \
42 -o "$output/layout-tests"