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 full token decodes (#25320)
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:00 UTC
391b56af7d98ae7655c03f1a4a4d850f5df6eedb
7 files changed
+570
-4
apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt
+7
-1
@@ -47,7 +47,8 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
47
private var contentResetKey = ""
48
49
@Volatile private var rowsDecodeGeneration = 0
50
- private var tokensDecodeGeneration = 0
50
+
51
+ @Volatile private var tokensDecodeGeneration = 0
52
private val payloadDecodeExecutor = Executors.newSingleThreadExecutor()
53
private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop
54
private val minimumFlingVelocity = ViewConfiguration.get(context).scaledMinimumFlingVelocity
@@ -203,6 +204,11 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
204
tokensDecodeGeneration += 1
205
val generation = tokensDecodeGeneration
206
payloadDecodeExecutor.execute {
207
+ if (generation != tokensDecodeGeneration ||
208
+ Thread.currentThread().isInterrupted
209
+ ) {
210
+ return@execute
211
+ }
212
val decodedTokens = parseTokensObject(value)
213
post {
214
if (generation != tokensDecodeGeneration) return@post
apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift
+8
@@ -342,6 +342,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
342
private var rowsDecodeGeneration = 0
343
private var rowsDecodeCancellation: ReviewDiffRowPreparation?
344
private var tokensDecodeGeneration = 0
345
+ private var tokensDecodeCancellation: ReviewDiffRowPreparation?
346
347
let onDebug = EventDispatcher()
348
let onVisibleFileChange = EventDispatcher()
@@ -390,6 +391,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
391
392
deinit {
393
rowsDecodeCancellation?.cancel()
394
+ tokensDecodeCancellation?.cancel()
395
}
396
397
public override func layoutSubviews() {
@@ -485,10 +487,15 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
487
}
488
489
func setTokensJson(_ tokensJson: String) {
490
+ tokensDecodeCancellation?.cancel()
491
+ let cancellation = ReviewDiffRowPreparation()
492
+ tokensDecodeCancellation = cancellation
493
tokensDecodeGeneration += 1
494
let generation = tokensDecodeGeneration
495
496
payloadDecodeQueue.async { [weak self] in
497
+ // Entered decoding may finish; only skip full payloads already obsolete in the queue.
498
+ guard !cancellation.isCancelled, self != nil else { return }
499
guard let data = tokensJson.data(using: .utf8) else {
500
return
501
}
@@ -615,6 +622,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
622
rowsDecodeCancellation = nil
623
rowsDecodeGeneration += 1
624
tokensDecodeGeneration += 1
625
+ tokensDecodeCancellation?.cancel()
626
contentView.tokensByRowId = [:]
627
rows = []
628
contentView.rows = []
apps/mobile/modules/t3-review-diff/tests/android/build.gradle
+23
-2
@@ -44,18 +44,39 @@ tasks.register('extractAndroidTestJars') {
44
}
45
46
def moduleRoot = file('../..')
47
+// Count decoder entry without replacing the production executor, parser, or lifecycle.
48
+def instrumentedView = layout.buildDirectory.file('token-fixture/T3ReviewDiffView.kt')
49
+tasks.register('instrumentTokenFixture') {
50
+ def original = file("${moduleRoot}/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt")
51
+ inputs.file original
52
+ outputs.file instrumentedView
53
+ doLast {
54
+ def source = original.text
55
+ def decode = ' val decodedTokens = parseTokensObject(value)'
56
+ def publish = ' canvasView.tokensByRowId = decodedTokens'
57
+ assert source.count(decode) == 1
58
+ assert source.count(publish) == 1
59
+ source = source.replace(decode, ' TokenDecodeProbe.enter()\n' + decode)
60
+ source = source.replace(publish, publish + '\n TokenDecodeProbe.publish()')
61
+ def destination = instrumentedView.get().asFile
62
+ destination.parentFile.mkdirs()
63
+ destination.text = source
64
+ }
65
+}
66
+
67
def sources = files(
68
+ instrumentedView,
69
fileTree('stubs') { include '**/*.kt' },
70
fileTree('src/test/kotlin') { include '**/*.kt' },
71
fileTree("${moduleRoot}/android/src/test/java") { include '**/*.kt' },
72
fileTree("${moduleRoot}/android/src/main/java/expo/modules/t3reviewdiff") {
73
include '**/*.kt'
53
- exclude '**/T3ReviewDiffModule.kt'
74
+ exclude '**/T3ReviewDiffModule.kt', '**/T3ReviewDiffView.kt'
75
},
76
)
77
78
tasks.register('compileRegression', JavaExec) {
58
- dependsOn 'extractAndroidTestJars'
79
+ dependsOn 'extractAndroidTestJars', 'instrumentTokenFixture'
80
classpath = configurations.compiler
81
mainClass = 'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler'
82
inputs.files sources, configurations.testCompileClasspath
apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffTokenDecodeTest.kt
new
+293
@@ -0,0 +1,293 @@
1
+package expo.modules.t3reviewdiff
2
+
3
+import android.app.Activity
4
+import android.graphics.Color
5
+import android.os.Looper
6
+import expo.modules.kotlin.AppContext
7
+import java.util.concurrent.CountDownLatch
8
+import java.util.concurrent.ExecutorService
9
+import java.util.concurrent.Semaphore
10
+import java.util.concurrent.atomic.AtomicInteger
11
+import java.util.concurrent.atomic.AtomicReference
12
+import org.junit.Assert.assertEquals
13
+import org.junit.Assert.assertTrue
14
+import org.junit.Test
15
+import org.junit.runner.RunWith
16
+import org.robolectric.Robolectric
17
+import org.robolectric.RobolectricTestRunner
18
+import org.robolectric.Shadows.shadowOf
19
+import org.robolectric.annotation.Config
20
+import org.robolectric.annotation.LooperMode
21
+
22
+internal object TokenDecodeProbe {
23
+ val entries = AtomicInteger()
24
+ val publications = AtomicInteger()
25
+
26
+ @Volatile var onEntry: ((Int) -> Unit)? = null
27
+
28
+ fun reset() {
29
+ entries.set(0)
30
+ publications.set(0)
31
+ onEntry = null
32
+ }
33
+
34
+ fun enter() {
35
+ val entry = entries.incrementAndGet()
36
+ onEntry?.invoke(entry)
37
+ }
38
+ fun publish() {
39
+ publications.incrementAndGet()
40
+ }
41
+}
42
+
43
+@RunWith(RobolectricTestRunner::class)
44
+@Config(sdk = [35], manifest = Config.NONE)
45
+@LooperMode(LooperMode.Mode.PAUSED)
46
+class ReviewDiffTokenDecodeTest {
47
+ @Test
48
+ fun queuedFullReplacementSkipsOnlyObsoleteWorkAndPreservesPatchOrdering() {
49
+ for (case in queuedCases()) {
50
+ fixture { view, executor ->
51
+ TokenDecodeProbe.reset()
52
+ view.setContentResetKey("content")
53
+ view.setTokensResetKey("tokens")
54
+ view.setTokensJson(payload("seed"))
55
+ drain(executor)
56
+ TokenDecodeProbe.reset()
57
+ val entered = CountDownLatch(1)
58
+ val release = Semaphore(0)
59
+ executor.execute {
60
+ entered.countDown()
61
+ release.acquire()
62
+ }
63
+ entered.await()
64
+ val acknowledgements = mutableListOf<Boolean>()
65
+ try {
66
+ case.enqueue(view) { id, chunk ->
67
+ view.setTokensPatchJson(patchPayload(id, chunk)) { acknowledgements.add(it) }
68
+ }
69
+ } finally {
70
+ release.release()
71
+ }
72
+ drain(executor)
73
+ assertEquals("${case.name} decoder entry", case.entries, TokenDecodeProbe.entries.get())
74
+ // Android's malformed full payload publishes its existing empty-map fallback.
75
+ assertEquals(
76
+ "${case.name} retained full publication",
77
+ case.entries,
78
+ TokenDecodeProbe.publications.get()
79
+ )
80
+ assertEquals("${case.name} token output", expected(case.ids), tokens(view))
81
+ assertEquals("${case.name} patch acknowledgements", case.acks, acknowledgements)
82
+ println(
83
+ "Passed tokens: ${case.name}, decoder entries=${case.entries}, " +
84
+ "retained full publications=${case.entries}"
85
+ )
86
+ }
87
+ }
88
+ }
89
+
90
+ private data class QueuedCase(
91
+ val name: String,
92
+ val ids: List<String> = listOf("b"),
93
+ val entries: Int = 1,
94
+ val acks: List<Boolean> = emptyList(),
95
+ val enqueue: (T3ReviewDiffView, (String, Int) -> Unit) -> Unit
96
+ )
97
+
98
+ private fun queuedCases() = listOf(
99
+ QueuedCase("A B C burst", ids = listOf("c")) { view, _ ->
100
+ listOf("a", "b", "c").forEach { view.setTokensJson(payload(it)) }
101
+ },
102
+ QueuedCase("content reset", ids = emptyList(), entries = 0) { view, _ ->
103
+ view.setTokensJson(payload("a"))
104
+ view.setContentResetKey("new")
105
+ },
106
+ QueuedCase("reset then B") { view, _ ->
107
+ view.setTokensJson(payload("a"))
108
+ view.setContentResetKey("new")
109
+ view.setTokensJson(payload("b"))
110
+ },
111
+ QueuedCase("same content key") { view, _ ->
112
+ view.setTokensJson(payload("b"))
113
+ view.setContentResetKey("content")
114
+ },
115
+ QueuedCase("token reset preserves full") { view, _ ->
116
+ view.setTokensJson(payload("b"))
117
+ view.setTokensResetKey("new")
118
+ },
119
+ QueuedCase("same token key") { view, _ ->
120
+ view.setTokensJson(payload("b"))
121
+ view.setTokensResetKey("tokens")
122
+ },
123
+ QueuedCase("current full") { view, _ -> view.setTokensJson(payload("b")) },
124
+ QueuedCase("current malformed", ids = emptyList()) { view, _ ->
125
+ view.setTokensJson("invalid JSON")
126
+ },
127
+ QueuedCase("obsolete malformed") { view, _ ->
128
+ view.setTokensJson("invalid JSON")
129
+ view.setTokensJson(payload("b"))
130
+ },
131
+ QueuedCase("full patch full", acks = listOf(true)) { view, patch ->
132
+ view.setTokensJson(payload("a"))
133
+ patch("patch", 0)
134
+ view.setTokensJson(payload("b"))
135
+ },
136
+ QueuedCase(
137
+ "full then patches",
138
+ ids = listOf("b", "one", "two"),
139
+ acks = listOf(true, true)
140
+ ) { view, patch ->
141
+ view.setTokensJson(payload("b"))
142
+ patch("one", 0)
143
+ patch("two", 1)
144
+ },
145
+ QueuedCase("patches then full", acks = listOf(true, true)) { view, patch ->
146
+ patch("one", 0)
147
+ patch("two", 1)
148
+ view.setTokensJson(payload("b"))
149
+ },
150
+ QueuedCase(
151
+ "additive patches",
152
+ ids = listOf("seed", "one", "two"),
153
+ entries = 0,
154
+ acks = listOf(true, true)
155
+ ) { _, patch ->
156
+ patch("one", 0)
157
+ patch("two", 1)
158
+ },
159
+ QueuedCase("reset rejects old patch", acks = listOf(false)) { view, patch ->
160
+ patch("old", 0)
161
+ view.setContentResetKey("new")
162
+ view.setTokensJson(payload("b"))
163
+ },
164
+ )
165
+
166
+ @Test
167
+ fun enteredFullSuccessAndErrorFinishButOnlyTheReplacementPublishes() {
168
+ for (invalid in listOf(false, true)) {
169
+ fixture { view, executor ->
170
+ TokenDecodeProbe.reset()
171
+ val entered = CountDownLatch(1)
172
+ val release = Semaphore(0)
173
+ TokenDecodeProbe.onEntry = { entry ->
174
+ if (entry == 1) {
175
+ entered.countDown()
176
+ release.acquire()
177
+ }
178
+ }
179
+ view.setTokensJson(if (invalid) "invalid JSON" else payload("a"))
180
+ entered.await()
181
+ try {
182
+ view.setContentResetKey("new")
183
+ view.setTokensJson(payload("b"))
184
+ } finally {
185
+ release.release()
186
+ }
187
+ drain(executor)
188
+ assertEquals(2, TokenDecodeProbe.entries.get())
189
+ assertEquals(1, TokenDecodeProbe.publications.get())
190
+ assertEquals(expected(listOf("b")), tokens(view))
191
+ println(
192
+ "Passed entered tokens invalid=$invalid, decoder entries=2, retained full publications=1"
193
+ )
194
+ }
195
+ }
196
+ }
197
+
198
+ @Test
199
+ fun cleanupDiscardsQueuedFullWorkOnTheProductionExecutor() {
200
+ fixture { view, executor ->
201
+ TokenDecodeProbe.reset()
202
+ val entered = CountDownLatch(1)
203
+ val worker = AtomicReference<Thread>()
204
+ val release = Semaphore(0)
205
+ executor.execute {
206
+ worker.set(Thread.currentThread())
207
+ entered.countDown()
208
+ try {
209
+ release.acquire()
210
+ } catch (
211
+ _: InterruptedException
212
+ ) {
213
+ Thread.currentThread().interrupt()
214
+ }
215
+ }
216
+ entered.await()
217
+ view.setTokensJson(payload("discarded"))
218
+ view.cleanup()
219
+ worker.get().join()
220
+ shadowOf(Looper.getMainLooper()).idle()
221
+ assertEquals(0, TokenDecodeProbe.entries.get())
222
+ assertEquals(0, TokenDecodeProbe.publications.get())
223
+ assertTrue(tokens(view).isEmpty())
224
+ println("Passed cleanup before entry, decoder entries=0, retained full publications=0")
225
+ }
226
+ }
227
+
228
+ @Test
229
+ fun cleanupAfterEntryKeepsTheExistingCurrentFullPublication() {
230
+ fixture { view, _ ->
231
+ TokenDecodeProbe.reset()
232
+ val entered = CountDownLatch(1)
233
+ val release = Semaphore(0)
234
+ val worker = AtomicReference<Thread>()
235
+ TokenDecodeProbe.onEntry = {
236
+ worker.set(Thread.currentThread())
237
+ entered.countDown()
238
+ // shutdownNow interrupts this worker; entered decoding must still finish.
239
+ release.acquireUninterruptibly()
240
+ }
241
+ view.setTokensJson(payload("entered"))
242
+ entered.await()
243
+ try {
244
+ view.cleanup()
245
+ } finally {
246
+ release.release()
247
+ }
248
+ worker.get().join()
249
+ shadowOf(Looper.getMainLooper()).idle()
250
+ assertEquals(1, TokenDecodeProbe.entries.get())
251
+ assertEquals(1, TokenDecodeProbe.publications.get())
252
+ assertEquals(expected(listOf("entered")), tokens(view))
253
+ println("Passed cleanup after entry, decoder entries=1, retained full publications=1")
254
+ }
255
+ }
256
+
257
+ private fun fixture(run: (T3ReviewDiffView, ExecutorService) -> Unit) {
258
+ val controller = Robolectric.buildActivity(Activity::class.java).setup()
259
+ val view = T3ReviewDiffView(controller.get(), AppContext())
260
+ controller.get().setContentView(view)
261
+ val executor = field(view, "payloadDecodeExecutor") as ExecutorService
262
+ try {
263
+ run(view, executor)
264
+ } finally {
265
+ view.cleanup()
266
+ TokenDecodeProbe.reset()
267
+ controller.pause().stop().destroy()
268
+ }
269
+ }
270
+
271
+ private fun drain(executor: ExecutorService) {
272
+ executor.submit {}.get()
273
+ shadowOf(Looper.getMainLooper()).idle()
274
+ }
275
+
276
+ private fun field(target: Any, name: String): Any = target.javaClass.getDeclaredField(name)
277
+ .apply { isAccessible = true }.get(target)
278
+
279
+ private fun tokens(view: T3ReviewDiffView) = field(
280
+ view.getChildAt(0),
281
+ "tokensByRowId"
282
+ ) as Map<*, *>
283
+
284
+ private fun expected(ids: List<String>) = ids.associateWith {
285
+ listOf(DiffToken("漢字 👨👩👧👦 é", Color.RED, 3), DiffToken("tail", null, 0))
286
+ }
287
+
288
+ private fun payload(id: String) =
289
+ """{"$id":[{"content":"漢字 👨👩👧👦 é","color":"#ff0000","fontStyle":3},{"content":"tail","fontStyle":0}]}"""
290
+
291
+ private fun patchPayload(id: String, chunk: Int) =
292
+ """{"resetKey":"tokens","chunkIndex":$chunk,"tokensByRowId":${payload(id)}}"""
293
+}
apps/mobile/modules/t3-review-diff/tests/ios/row-decode.swift
+1
-1
@@ -252,7 +252,7 @@ private extension T3ReviewDiffView {
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)
255
+ T3ReviewDiffView.runQueuedTokenDecodeCase(0)
256
}
257
}
258
}
apps/mobile/modules/t3-review-diff/tests/ios/token-decode.swift
new
+222
@@ -0,0 +1,222 @@
1
+// Instrument decoder entry and accepted publication in the real serial queue.
2
+private final class TokenDecodeProbe {
3
+ private let lock = NSLock()
4
+ private var entries = 0
5
+ private var publications = 0
6
+ private var onEntry: ((Int) -> Void)?
7
+
8
+ func reset(onEntry: ((Int) -> Void)? = nil) {
9
+ lock.lock()
10
+ entries = 0
11
+ publications = 0
12
+ self.onEntry = onEntry
13
+ lock.unlock()
14
+ }
15
+
16
+ func enter() {
17
+ lock.lock()
18
+ entries += 1
19
+ let entry = entries
20
+ let callback = onEntry
21
+ lock.unlock()
22
+ callback?(entry)
23
+ }
24
+
25
+ func publish() {
26
+ lock.lock()
27
+ publications += 1
28
+ lock.unlock()
29
+ }
30
+
31
+ func checkCounts(_ expectedEntries: Int, _ expectedPublications: Int, _ name: String) {
32
+ lock.lock()
33
+ defer { lock.unlock() }
34
+ check(entries == expectedEntries,
35
+ "\(name): expected \(expectedEntries) token decoder entries, got \(entries)")
36
+ check(publications == expectedPublications,
37
+ "\(name): expected \(expectedPublications) retained full publications, got \(publications)")
38
+ print("Passed tokens: \(name), decoder entries=\(entries), retained full publications=\(publications)")
39
+ }
40
+}
41
+
42
+private let tokenDecodeProbe = TokenDecodeProbe()
43
+
44
+private func decodeTokensForTest(
45
+ _ type: [String: [ReviewDiffNativeToken]].Type, from data: Data
46
+) throws -> [String: [ReviewDiffNativeToken]] {
47
+ tokenDecodeProbe.enter()
48
+ return try JSONDecoder().decode(type, from: data)
49
+}
50
+
51
+private func tokenPayload(_ id: String) -> String {
52
+ "{\"\(id)\":[{\"content\":\"漢字 👨👩👧👦 é\",\"color\":\"#ff0000\",\"fontStyle\":3},{\"content\":\"tail\",\"fontStyle\":0}]}"
53
+}
54
+
55
+private func tokenPatch(_ id: String, key: String = "tokens", chunk: Int = 0) -> String {
56
+ "{\"resetKey\":\"\(key)\",\"chunkIndex\":\(chunk),\"tokensByRowId\":\(tokenPayload(id))}"
57
+}
58
+
59
+private extension T3ReviewDiffView {
60
+ static func afterTokens(on queue: DispatchQueue, _ completion: @escaping () -> Void) {
61
+ queue.async { DispatchQueue.main.async(execute: completion) }
62
+ }
63
+
64
+ func checkTokens(_ payloads: [String]) {
65
+ var expected: [String: [ReviewDiffNativeToken]] = [:]
66
+ for payload in payloads {
67
+ let decoded = try! JSONDecoder().decode([String: [ReviewDiffNativeToken]].self, from: Data(payload.utf8))
68
+ expected.merge(decoded) { _, next in next }
69
+ }
70
+ let describe = { (value: [String: [ReviewDiffNativeToken]]) in
71
+ value.mapValues { $0.map { String(reflecting: $0) } }
72
+ }
73
+ check(describe(contentView.tokensByRowId) == describe(expected), "Token fields/output order changed")
74
+ }
75
+
76
+ static func runQueuedTokenDecodeCase(_ index: Int) {
77
+ let names = ["A B C burst", "content reset", "reset then B", "same content key",
78
+ "token reset preserves full", "same token key", "current full", "current malformed",
79
+ "obsolete malformed", "full patch full", "full then patches", "patches then full",
80
+ "additive patches", "reset rejects old patch"]
81
+ guard index < names.count else { runReleasedTokenDecodeCase(); return }
82
+ tokenDecodeProbe.reset()
83
+ let view = T3ReviewDiffView()
84
+ view.setContentResetKey("content")
85
+ view.setTokensResetKey("tokens")
86
+ var errors: [String] = []
87
+ view.onDebug.onEvent = { payload in
88
+ if payload["message"] as? String == "tokens-decode-failed" {
89
+ errors.append(payload["error"] as! String)
90
+ }
91
+ }
92
+ view.contentView.tokensByRowId = try! JSONDecoder().decode(
93
+ [String: [ReviewDiffNativeToken]].self, from: Data(tokenPayload("seed").utf8)
94
+ )
95
+ var acknowledgements: [Bool] = []
96
+ let patch = { (id: String, chunk: Int) in
97
+ view.setTokensPatchJson(tokenPatch(id, chunk: chunk)) { acknowledgements.append($0) }
98
+ }
99
+ view.payloadDecodeQueue.suspend()
100
+ switch index {
101
+ case 0:
102
+ for id in ["a", "b", "c"] { view.setTokensJson(tokenPayload(id)) }
103
+ case 1, 2:
104
+ view.setTokensJson(tokenPayload("a"))
105
+ view.setContentResetKey("new")
106
+ if index == 2 { view.setTokensJson(tokenPayload("b")) }
107
+ case 3:
108
+ view.setTokensJson(tokenPayload("b"))
109
+ view.setContentResetKey("content")
110
+ case 4, 5:
111
+ view.setTokensJson(tokenPayload("b"))
112
+ view.setTokensResetKey(index == 4 ? "new" : "tokens")
113
+ case 6: view.setTokensJson(tokenPayload("b"))
114
+ case 7: view.setTokensJson("invalid JSON")
115
+ case 8:
116
+ view.setTokensJson("invalid JSON")
117
+ view.setTokensJson(tokenPayload("b"))
118
+ case 9:
119
+ view.setTokensJson(tokenPayload("a"))
120
+ patch("patch", 0)
121
+ view.setTokensJson(tokenPayload("b"))
122
+ case 10:
123
+ view.setTokensJson(tokenPayload("b"))
124
+ patch("one", 0)
125
+ patch("two", 1)
126
+ case 11:
127
+ patch("one", 0)
128
+ patch("two", 1)
129
+ view.setTokensJson(tokenPayload("b"))
130
+ case 12:
131
+ patch("one", 0)
132
+ patch("two", 1)
133
+ default:
134
+ patch("old", 0)
135
+ view.setContentResetKey("new")
136
+ view.setTokensJson(tokenPayload("b"))
137
+ }
138
+ view.payloadDecodeQueue.resume()
139
+ afterTokens(on: view.payloadDecodeQueue) {
140
+ let entries = index == 1 || index == 12 ? 0 : 1
141
+ let publications = entries
142
+ tokenDecodeProbe.checkCounts(entries, publications, names[index])
143
+ if index == 1 || index == 7 {
144
+ view.checkTokens([])
145
+ } else if index == 0 {
146
+ view.checkTokens([tokenPayload("c")])
147
+ } else if index == 10 {
148
+ view.checkTokens([tokenPayload("b"), tokenPayload("one"), tokenPayload("two")])
149
+ } else if index == 12 {
150
+ view.checkTokens([tokenPayload("seed"), tokenPayload("one"), tokenPayload("two")])
151
+ } else {
152
+ view.checkTokens([tokenPayload("b")])
153
+ }
154
+ check(acknowledgements == (index == 9 ? [true] : index == 10 || index == 11 || index == 12 ? [true, true] : index == 13 ? [false] : []),
155
+ "All additive chunks must retain their acknowledgement semantics")
156
+ if index == 7 {
157
+ do {
158
+ _ = try JSONDecoder().decode([String: [ReviewDiffNativeToken]].self, from: Data("invalid JSON".utf8))
159
+ } catch { check(errors == [error.localizedDescription], "Current error/fallback changed") }
160
+ } else { check(errors.isEmpty, "Obsolete errors must not publish") }
161
+ runQueuedTokenDecodeCase(index + 1)
162
+ }
163
+ }
164
+
165
+ static func runReleasedTokenDecodeCase() {
166
+ tokenDecodeProbe.reset()
167
+ var view: T3ReviewDiffView? = T3ReviewDiffView()
168
+ let queue = view!.payloadDecodeQueue
169
+ let released = { [weak view] in view == nil }
170
+ queue.suspend()
171
+ view!.setTokensJson(tokenPayload("released"))
172
+ view = nil
173
+ check(released(), "Queued token closure must not retain the view")
174
+ queue.resume()
175
+ afterTokens(on: queue) {
176
+ tokenDecodeProbe.checkCounts(0, 0, "release before entry")
177
+ runEnteredTokenDecodeCase(invalid: false)
178
+ }
179
+ }
180
+
181
+ static func runEnteredTokenDecodeCase(invalid: Bool) {
182
+ let view = T3ReviewDiffView()
183
+ let release = DispatchSemaphore(value: 0)
184
+ tokenDecodeProbe.reset { entry in
185
+ guard entry == 1 else { return }
186
+ DispatchQueue.main.async {
187
+ view.setContentResetKey("new")
188
+ view.setTokensJson(tokenPayload("b"))
189
+ release.signal()
190
+ afterTokens(on: view.payloadDecodeQueue) {
191
+ tokenDecodeProbe.checkCounts(2, 1, "entered \(invalid ? "error" : "success") then replacement")
192
+ view.checkTokens([tokenPayload("b")])
193
+ tokenDecodeProbe.reset()
194
+ if invalid { runReleasedEnteredTokenDecodeCase() } else { runEnteredTokenDecodeCase(invalid: true) }
195
+ }
196
+ }
197
+ release.wait()
198
+ }
199
+ view.setTokensJson(invalid ? "invalid JSON" : tokenPayload("a"))
200
+ }
201
+
202
+ static func runReleasedEnteredTokenDecodeCase() {
203
+ var view: T3ReviewDiffView? = T3ReviewDiffView()
204
+ let released = { [weak view] in view == nil }
205
+ let queue = view!.payloadDecodeQueue
206
+ let release = DispatchSemaphore(value: 0)
207
+ tokenDecodeProbe.reset { _ in
208
+ DispatchQueue.main.async {
209
+ view = nil
210
+ check(released(), "Entered decoder must not keep the view alive")
211
+ release.signal()
212
+ afterTokens(on: queue) {
213
+ tokenDecodeProbe.checkCounts(1, 0, "release after entry")
214
+ tokenDecodeProbe.reset()
215
+ exit(0)
216
+ }
217
+ }
218
+ release.wait()
219
+ }
220
+ view!.setTokensJson(tokenPayload("a"))
221
+ }
222
+}
apps/mobile/modules/t3-review-diff/tests/run-ios.sh
+16
@@ -16,6 +16,21 @@ source = source.replace("import ExpoModulesCore\n", "")
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
+# Instrument the real full-token decoder and accepted publication only.
20
+start = source.index(" let decodedTokens = try JSONDecoder().decode(")
21
+end = source.index(" DispatchQueue.main.async", start)
22
+decode = source[start:end]
23
+source = source[:start] + decode.replace("try JSONDecoder().decode(", "try decodeTokensForTest(") + source[end:]
24
+publish = " self.contentView.tokensByRowId = decodedTokens"
25
+assert source.count(publish) == 1
26
+source = source.replace(publish, publish + "\n tokenDecodeProbe.publish()")
27
+# Include the accepted malformed-current fallback in publication counts.
28
+start = source.index(" func setTokensJson(")
29
+end = source.index(" func setTokensPatchJson(", start)
30
+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
stubs = """
35
public final class AppContext {}
36
open class ExpoView: UIView {
@@ -33,6 +48,7 @@ Path(sys.argv[2]).write_text(source + "\n" + stubs + "\n"
48
+ (module / "tests/ios/main.swift").read_text() + "\n"
49
+ (module / "tests/ios/anchor.swift").read_text() + "\n"
50
+ (module / "tests/ios/row-decode.swift").read_text() + "\n"
51
+ + (module / "tests/ios/token-decode.swift").read_text() + "\n"
52
+ (module / "tests/ios/geometry.swift").read_text())
53
PYTHON
54
"$compiler" -O -target "$(uname -m)-apple-ios16.1-macabi" -sdk "$sdk" \