| 1 | import AppKit |
| 2 | import DocsKit |
| 3 | import ObjectiveC |
| 4 | |
| 5 | /// Characters whose attributes the text system fixes (lazy attribute |
| 6 | /// fixing), counted per key with DOCS_RT_AUDIT_COUNT_FIXES=1. |
| 7 | nonisolated(unsafe) var fixedCharacters = 0 |
| 8 | extension NSMutableAttributedString { |
| 9 | @objc func probeCountingFixAttributes(in range: NSRange) { |
| 10 | fixedCharacters += range.length |
| 11 | probeCountingFixAttributes(in: range) |
| 12 | } |
| 13 | } |
| 14 | func countAttributeFixing() { |
| 15 | method_exchangeImplementations(class_getInstanceMethod(NSMutableAttributedString.self, #selector(NSMutableAttributedString.fixAttributes(in:)))!, |
| 16 | class_getInstanceMethod(NSMutableAttributedString.self, #selector(NSMutableAttributedString.probeCountingFixAttributes(in:)))!) |
| 17 | } |
| 18 | import RastrilloApple |
| 19 | import SwiftUI |
| 20 | |
| 21 | // Realtime UI probe (spec 2026-11-22 §7, "Measurement and targets"). Opens the real DocsWorkspace |
| 22 | // (memory store: accountID nil, nothing on disk) against the audit fixture |
| 23 | // server described by $DOCS_RT_AUDIT_DIR/connection.json, then: |
| 24 | // A. types $DOCS_RT_AUDIT_KEYS characters into the real NSTextView with |
| 25 | // keyDown at $DOCS_RT_AUDIT_CADENCE_MS, counting whole-document and block |
| 26 | // renders, reconciliations, view updates and host body evaluations |
| 27 | // (DocsProbes; build with -Xswiftc -DDOCS_PROBES) and main-queue stalls; |
| 28 | // B. writes typing-done, then watches the text view for the peer's "Z"s that |
| 29 | // run-ui.py posts, recording when each became visible. |
| 30 | |
| 31 | struct Connection: Decodable { let origin: String; let sqid: String; let name: String; let value: String; let base_unix_ms: Double } |
| 32 | let dir = URL(fileURLWithPath: ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_DIR"]!) |
| 33 | let connection = try! JSONDecoder().decode(Connection.self, from: Data(contentsOf: dir.appendingPathComponent("connection.json"))) |
| 34 | func serverNow() -> Double { Date().timeIntervalSince1970 * 1000 - connection.base_unix_ms } |
| 35 | |
| 36 | @MainActor final class Stalls { |
| 37 | var timer: DispatchSourceTimer? |
| 38 | var last = DispatchTime.now() |
| 39 | var gaps: [Double] = [] |
| 40 | func start() { |
| 41 | gaps = [] |
| 42 | let t = DispatchSource.makeTimerSource(queue: .main) |
| 43 | t.schedule(deadline: .now(), repeating: .milliseconds(5), leeway: .microseconds(100)) |
| 44 | last = .now() |
| 45 | t.setEventHandler { [weak self] in |
| 46 | MainActor.assumeIsolated { |
| 47 | guard let self else { return } |
| 48 | let now = DispatchTime.now(); self.gaps.append(Double(now.uptimeNanoseconds - self.last.uptimeNanoseconds) / 1e6); self.last = now |
| 49 | } |
| 50 | } |
| 51 | t.resume(); timer = t |
| 52 | } |
| 53 | func stop() -> String { |
| 54 | timer?.cancel(); timer = nil |
| 55 | let s = gaps.sorted(), over = gaps.filter { $0 > 16.7 } |
| 56 | return String(format: "max %.1f ms, p99 %.1f ms, %d gaps > 16.7 ms totalling %.0f ms; busy %.1f ms", s.last ?? 0, s.isEmpty ? 0 : s[Int(Double(s.count - 1) * 0.99)], over.count, over.reduce(0, +), busy) |
| 57 | } |
| 58 | /// Main-thread time the 5 ms tick waited for: every gap beyond its period. |
| 59 | var busy: Double { gaps.reduce(0) { $0 + max(0, $1 - 5) } } |
| 60 | } |
| 61 | |
| 62 | func counters(_ label: String, per count: Int) { |
| 63 | print("RTUI \(label) \(DocsProbes.summary)") |
| 64 | let n = Double(max(1, count)) |
| 65 | print(String(format: "RTUI %@ per event (n=%d): wholeRenders %.2f blockRenders %.2f reconciles %.2f viewUpdates %.2f hostBodies %.2f", label, count, |
| 66 | Double(DocsProbes.wholeRenders) / n, Double(DocsProbes.blockRenders) / n, Double(DocsProbes.reconciles) / n, |
| 67 | Double(DocsProbes.viewUpdates) / n, Double(DocsProbes.hostBodies) / n)) |
| 68 | } |
| 69 | |
| 70 | @MainActor private enum Run { |
| 71 | static var started = false |
| 72 | static var opened = ContinuousClock.now |
| 73 | } |
| 74 | |
| 75 | @main struct RealtimeUIProbe: App { |
| 76 | var body: some Scene { |
| 77 | Window("Probe Home", id: "home") { Launcher() } |
| 78 | WindowGroup("Probe Document", id: "document", for: String.self) { _ in |
| 79 | DocsWorkspace(client: NativeHTTP(origin: URL(string: connection.origin)!, credential: NativeSession(name: connection.name, value: connection.value)), |
| 80 | signOut: {}, documentID: connection.sqid) |
| 81 | }.defaultSize(width: 1120, height: 820).restorationBehavior(.disabled) |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | private struct Launcher: View { |
| 86 | @Environment(\.openWindow) private var openWindow |
| 87 | var body: some View { |
| 88 | Text("Realtime audit probe").frame(width: 300, height: 100).task { |
| 89 | guard !Run.started else { return } |
| 90 | Run.started = true |
| 91 | NSApp.setActivationPolicy(.regular) |
| 92 | openWindow(id: "document", value: connection.sqid) |
| 93 | Run.opened = .now |
| 94 | for _ in 0..<6000 { |
| 95 | if let window = NSApp.windows.first(where: { $0.title == "Realtime audit" }), let editor = window.contentView.flatMap(findEditor), !editor.string.isEmpty { |
| 96 | await exercise(window, editor) |
| 97 | return |
| 98 | } |
| 99 | try? await Task.sleep(for: .milliseconds(10)) |
| 100 | } |
| 101 | print("RTUI FAILED: document did not load") |
| 102 | exit(2) |
| 103 | } |
| 104 | } |
| 105 | func findEditor(_ view: NSView) -> NSTextView? { |
| 106 | if let text = view as? NSTextView, text.accessibilityIdentifier() == "docs.editor" { return text } |
| 107 | return view.subviews.lazy.compactMap(findEditor).first |
| 108 | } |
| 109 | func exercise(_ window: NSWindow, _ editor: NSTextView) async { |
| 110 | let env = ProcessInfo.processInfo.environment |
| 111 | let keys = Int(env["DOCS_RT_AUDIT_KEYS"] ?? "40") ?? 40 |
| 112 | let cadence = Double(env["DOCS_RT_AUDIT_CADENCE_MS"] ?? "125") ?? 125 |
| 113 | // DOCS_RT_AUDIT_AT_OPEN=1: type at the start of the document as soon |
| 114 | // as it shows, while the rest is still being measured (S1b). |
| 115 | let atOpen = env["DOCS_RT_AUDIT_AT_OPEN"] == "1" |
| 116 | let shown = Run.opened.duration(to: .now) |
| 117 | NSApp.activate(ignoringOtherApps: true) |
| 118 | window.makeKeyAndOrderFront(nil); window.makeFirstResponder(editor) |
| 119 | if atOpen { |
| 120 | print("RTUI open: document shown \(shown) after the window was asked for; measuring \(DocsProbes.measuring ? "still going" : "done")") |
| 121 | Task { @MainActor in |
| 122 | while DocsProbes.measuring { try? await Task.sleep(for: .milliseconds(2)) } |
| 123 | print("RTUI open: measuring done \(Run.opened.duration(to: .now)) after the window was asked for") |
| 124 | } |
| 125 | } else { try? await Task.sleep(for: .seconds(2)) } |
| 126 | let ns = editor.string as NSString |
| 127 | var at = atOpen || env["DOCS_RT_AUDIT_AT"] == "top" ? ns.range(of: "\n").location : ns.length / 3 |
| 128 | while at < ns.length, ns.character(at: at) == 10 { at += 1 } |
| 129 | editor.setSelectedRange(NSRange(location: at, length: 0)) |
| 130 | editor.scrollRangeToVisible(editor.selectedRange()) |
| 131 | if !atOpen { try? await Task.sleep(for: .seconds(1)) } |
| 132 | |
| 133 | // A. Typing. |
| 134 | DocsProbes.reset() |
| 135 | let stalls = Stalls(); stalls.start() |
| 136 | var keyDown: [Double] = [] |
| 137 | // keyDown → drawn: the key, then the window's layout and display |
| 138 | // pass that would follow it at the end of the turn, run at once |
| 139 | // (event → text storage → layout → display on the main thread). |
| 140 | var drawn: [Double] = [] |
| 141 | // Per key, through its draw: line-fragment requests to the live and |
| 142 | // the measurement containers, and pagination time (S1b's gates). |
| 143 | var lines: [Int] = [], measureLines: [Int] = [], paginationMs: [Double] = [] |
| 144 | // The display pass after the key: all of it, and what is not the |
| 145 | // text view's own layout and drawing (SwiftUI's hosting views, AppKit). |
| 146 | var display: [Double] = [], displayOther: [Double] = [] |
| 147 | var fixes: [Int] = [] |
| 148 | if env["DOCS_RT_AUDIT_COUNT_FIXES"] == "1" { countAttributeFixing() } |
| 149 | let clock = ContinuousClock.now |
| 150 | for i in 0..<keys { |
| 151 | let due = clock.advanced(by: .milliseconds(Int(Double(i) * cadence))) |
| 152 | if due > .now { try? await Task.sleep(until: due) } |
| 153 | window.makeFirstResponder(editor) |
| 154 | let event = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil, characters: "x", charactersIgnoringModifiers: "x", isARepeat: false, keyCode: 7)! |
| 155 | let t = DispatchTime.now().uptimeNanoseconds |
| 156 | let lines0 = DocsProbes.lineRequests, measure0 = DocsProbes.measureLineRequests, pagination0 = DocsProbes.paginationMs |
| 157 | let fixed0 = fixedCharacters |
| 158 | editor.keyDown(with: event) |
| 159 | keyDown.append(Double(DispatchTime.now().uptimeNanoseconds - t) / 1e6) |
| 160 | let ours0 = DocsProbes.textLayoutMs + DocsProbes.drawMs, d0 = DispatchTime.now().uptimeNanoseconds |
| 161 | window.displayIfNeeded() |
| 162 | let displayed = Double(DispatchTime.now().uptimeNanoseconds - d0) / 1e6 |
| 163 | display.append(displayed); displayOther.append(displayed - (DocsProbes.textLayoutMs + DocsProbes.drawMs - ours0)) |
| 164 | drawn.append(Double(DispatchTime.now().uptimeNanoseconds - t) / 1e6) |
| 165 | lines.append(DocsProbes.lineRequests - lines0); measureLines.append(DocsProbes.measureLineRequests - measure0) |
| 166 | paginationMs.append(DocsProbes.paginationMs - pagination0) |
| 167 | fixes.append(fixedCharacters - fixed0) |
| 168 | } |
| 169 | let typedAt = ContinuousClock.now |
| 170 | try? await Task.sleep(for: .seconds(Double(env["DOCS_RT_AUDIT_SETTLE_S"] ?? "6") ?? 6)) |
| 171 | let typedStall = stalls.stop() |
| 172 | let sorted = keyDown.sorted() |
| 173 | print(String(format: "RTUI typing: %d keys at %.0f ms; keyDown sync median %.2f ms p95 %.2f ms max %.2f ms; main queue %@", keys, cadence, sorted[sorted.count / 2], sorted[min(sorted.count - 1, Int(Double(sorted.count) * 0.95))], sorted.last ?? 0, typedStall)) |
| 174 | let drawnSorted = drawn.sorted() |
| 175 | print(String(format: "RTUI typing: keyDown to drawn median %.2f ms p95 %.2f ms max %.2f ms", drawnSorted[drawnSorted.count / 2], drawnSorted[min(drawnSorted.count - 1, Int(Double(drawnSorted.count) * 0.95))], drawnSorted.last ?? 0)) |
| 176 | let paginationSorted = paginationMs.sorted() |
| 177 | print(String(format: "RTUI typing per key to drawn: line requests max %d median %d; measurement line requests max %d median %d; pagination median %.2f ms max %.2f ms", |
| 178 | lines.max() ?? 0, lines.sorted()[lines.count / 2], measureLines.max() ?? 0, measureLines.sorted()[measureLines.count / 2], |
| 179 | paginationSorted[paginationSorted.count / 2], paginationSorted.last ?? 0)) |
| 180 | print("RTUI typing per key line requests: \(lines.map(String.init).joined(separator: " "))") |
| 181 | if env["DOCS_RT_AUDIT_COUNT_FIXES"] == "1" { print("RTUI typing per key characters fixed: \(fixes.map(String.init).joined(separator: " "))") } |
| 182 | print("RTUI typing per key keyDown ms: \(keyDown.map { String(format: "%.1f", $0) }.joined(separator: " "))") |
| 183 | let displaySorted = display.sorted(), otherSorted = displayOther.sorted() |
| 184 | print(String(format: "RTUI typing display pass after the key: median %.2f ms p95 %.2f ms; not the text view's own layout and drawing: median %.2f ms p95 %.2f ms", |
| 185 | displaySorted[displaySorted.count / 2], displaySorted[min(displaySorted.count - 1, Int(Double(displaySorted.count) * 0.95))], |
| 186 | otherSorted[otherSorted.count / 2], otherSorted[min(otherSorted.count - 1, Int(Double(otherSorted.count) * 0.95))])) |
| 187 | counters("typing (\(keys) keys + settle)", per: keys) |
| 188 | print("RTUI typing path \(DocsProbes.pathSummary)") |
| 189 | let x = (editor.string as NSString).components(separatedBy: "x").count - 1 |
| 190 | print("RTUI typing: settle after last key \(typedAt.duration(to: .now)); x in editor \(x)") |
| 191 | |
| 192 | // B. Remote: run-ui.py posts the peer's updates once this file exists. |
| 193 | DocsProbes.reset() |
| 194 | stalls.start() |
| 195 | try? Data().write(to: dir.appendingPathComponent("typing-done")) |
| 196 | var seen: [Double] = [] |
| 197 | var lastLength = -1 |
| 198 | let deadline = ContinuousClock.now.advanced(by: .seconds(240)) |
| 199 | while ContinuousClock.now < deadline { |
| 200 | let text = editor.string as NSString |
| 201 | if text.length != lastLength { |
| 202 | lastLength = text.length |
| 203 | var count = 0, range = NSRange(location: 0, length: text.length) |
| 204 | while true { |
| 205 | let found = text.range(of: "Z", options: .literal, range: range) |
| 206 | if found.location == NSNotFound { break } |
| 207 | count += 1; range = NSRange(location: found.location + 1, length: text.length - found.location - 1) |
| 208 | } |
| 209 | while seen.count < count { seen.append(serverNow()) } |
| 210 | } |
| 211 | if FileManager.default.fileExists(atPath: dir.appendingPathComponent("remote-done").path), |
| 212 | let expected = Int((try? String(contentsOf: dir.appendingPathComponent("remote-done"), encoding: .utf8)) ?? ""), seen.count >= expected { break } |
| 213 | try? await Task.sleep(for: .milliseconds(3)) |
| 214 | } |
| 215 | try? await Task.sleep(for: .seconds(2)) |
| 216 | let remoteStall = stalls.stop() |
| 217 | print("RTUI remote: main queue \(remoteStall)") |
| 218 | print(String(format: "RTUI remote: main-thread busy per peer change %.2f ms (n=%d)", stalls.busy / Double(max(1, seen.count)), seen.count)) |
| 219 | counters("remote", per: seen.count) |
| 220 | print("RTUI remote path \(DocsProbes.pathSummary)") |
| 221 | try? JSONEncoder().encode(seen).write(to: dir.appendingPathComponent("seen.json")) |
| 222 | print("RTUI remote: seen \(seen.count)") |
| 223 | exit(0) |
| 224 | } |
| 225 | } |
| 226 | |