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

main
swift 262 lines 9.98 KB
Raw
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 T3ReviewDiffView.runQueuedTokenDecodeCase(0)
256 }
257 }
258 }
259
260 private func runRowDecodeTests() {
261 T3ReviewDiffView.runQueuedRowDecodeCase(0)
262 }