import AppKit import DocsKit import ObjectiveC /// Characters whose attributes the text system fixes (lazy attribute /// fixing), counted per key with DOCS_RT_AUDIT_COUNT_FIXES=1. nonisolated(unsafe) var fixedCharacters = 0 extension NSMutableAttributedString { @objc func probeCountingFixAttributes(in range: NSRange) { fixedCharacters += range.length probeCountingFixAttributes(in: range) } } func countAttributeFixing() { method_exchangeImplementations(class_getInstanceMethod(NSMutableAttributedString.self, #selector(NSMutableAttributedString.fixAttributes(in:)))!, class_getInstanceMethod(NSMutableAttributedString.self, #selector(NSMutableAttributedString.probeCountingFixAttributes(in:)))!) } import RastrilloApple import SwiftUI // Realtime UI probe (spec 2026-11-22 §7, "Measurement and targets"). Opens the real DocsWorkspace // (memory store: accountID nil, nothing on disk) against the audit fixture // server described by $DOCS_RT_AUDIT_DIR/connection.json, then: // A. types $DOCS_RT_AUDIT_KEYS characters into the real NSTextView with // keyDown at $DOCS_RT_AUDIT_CADENCE_MS, counting whole-document and block // renders, reconciliations, view updates and host body evaluations // (DocsProbes; build with -Xswiftc -DDOCS_PROBES) and main-queue stalls; // B. writes typing-done, then watches the text view for the peer's "Z"s that // run-ui.py posts, recording when each became visible. struct Connection: Decodable { let origin: String; let sqid: String; let name: String; let value: String; let base_unix_ms: Double } let dir = URL(fileURLWithPath: ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_DIR"]!) let connection = try! JSONDecoder().decode(Connection.self, from: Data(contentsOf: dir.appendingPathComponent("connection.json"))) func serverNow() -> Double { Date().timeIntervalSince1970 * 1000 - connection.base_unix_ms } @MainActor final class Stalls { var timer: DispatchSourceTimer? var last = DispatchTime.now() var gaps: [Double] = [] func start() { gaps = [] let t = DispatchSource.makeTimerSource(queue: .main) t.schedule(deadline: .now(), repeating: .milliseconds(5), leeway: .microseconds(100)) last = .now() t.setEventHandler { [weak self] in MainActor.assumeIsolated { guard let self else { return } let now = DispatchTime.now(); self.gaps.append(Double(now.uptimeNanoseconds - self.last.uptimeNanoseconds) / 1e6); self.last = now } } t.resume(); timer = t } func stop() -> String { timer?.cancel(); timer = nil let s = gaps.sorted(), over = gaps.filter { $0 > 16.7 } 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) } /// Main-thread time the 5 ms tick waited for: every gap beyond its period. var busy: Double { gaps.reduce(0) { $0 + max(0, $1 - 5) } } } func counters(_ label: String, per count: Int) { print("RTUI \(label) \(DocsProbes.summary)") let n = Double(max(1, count)) print(String(format: "RTUI %@ per event (n=%d): wholeRenders %.2f blockRenders %.2f reconciles %.2f viewUpdates %.2f hostBodies %.2f", label, count, Double(DocsProbes.wholeRenders) / n, Double(DocsProbes.blockRenders) / n, Double(DocsProbes.reconciles) / n, Double(DocsProbes.viewUpdates) / n, Double(DocsProbes.hostBodies) / n)) } @MainActor private enum Run { static var started = false static var opened = ContinuousClock.now } @main struct RealtimeUIProbe: App { var body: some Scene { Window("Probe Home", id: "home") { Launcher() } WindowGroup("Probe Document", id: "document", for: String.self) { _ in DocsWorkspace(client: NativeHTTP(origin: URL(string: connection.origin)!, credential: NativeSession(name: connection.name, value: connection.value)), signOut: {}, documentID: connection.sqid) }.defaultSize(width: 1120, height: 820).restorationBehavior(.disabled) } } private struct Launcher: View { @Environment(\.openWindow) private var openWindow var body: some View { Text("Realtime audit probe").frame(width: 300, height: 100).task { guard !Run.started else { return } Run.started = true NSApp.setActivationPolicy(.regular) openWindow(id: "document", value: connection.sqid) Run.opened = .now for _ in 0..<6000 { if let window = NSApp.windows.first(where: { $0.title == "Realtime audit" }), let editor = window.contentView.flatMap(findEditor), !editor.string.isEmpty { await exercise(window, editor) return } try? await Task.sleep(for: .milliseconds(10)) } print("RTUI FAILED: document did not load") exit(2) } } func findEditor(_ view: NSView) -> NSTextView? { if let text = view as? NSTextView, text.accessibilityIdentifier() == "docs.editor" { return text } return view.subviews.lazy.compactMap(findEditor).first } func exercise(_ window: NSWindow, _ editor: NSTextView) async { let env = ProcessInfo.processInfo.environment let keys = Int(env["DOCS_RT_AUDIT_KEYS"] ?? "40") ?? 40 let cadence = Double(env["DOCS_RT_AUDIT_CADENCE_MS"] ?? "125") ?? 125 // DOCS_RT_AUDIT_AT_OPEN=1: type at the start of the document as soon // as it shows, while the rest is still being measured (S1b). let atOpen = env["DOCS_RT_AUDIT_AT_OPEN"] == "1" let shown = Run.opened.duration(to: .now) NSApp.activate(ignoringOtherApps: true) window.makeKeyAndOrderFront(nil); window.makeFirstResponder(editor) if atOpen { print("RTUI open: document shown \(shown) after the window was asked for; measuring \(DocsProbes.measuring ? "still going" : "done")") Task { @MainActor in while DocsProbes.measuring { try? await Task.sleep(for: .milliseconds(2)) } print("RTUI open: measuring done \(Run.opened.duration(to: .now)) after the window was asked for") } } else { try? await Task.sleep(for: .seconds(2)) } let ns = editor.string as NSString var at = atOpen || env["DOCS_RT_AUDIT_AT"] == "top" ? ns.range(of: "\n").location : ns.length / 3 while at < ns.length, ns.character(at: at) == 10 { at += 1 } editor.setSelectedRange(NSRange(location: at, length: 0)) editor.scrollRangeToVisible(editor.selectedRange()) if !atOpen { try? await Task.sleep(for: .seconds(1)) } // A. Typing. DocsProbes.reset() let stalls = Stalls(); stalls.start() var keyDown: [Double] = [] // keyDown → drawn: the key, then the window's layout and display // pass that would follow it at the end of the turn, run at once // (event → text storage → layout → display on the main thread). var drawn: [Double] = [] // Per key, through its draw: line-fragment requests to the live and // the measurement containers, and pagination time (S1b's gates). var lines: [Int] = [], measureLines: [Int] = [], paginationMs: [Double] = [] // The display pass after the key: all of it, and what is not the // text view's own layout and drawing (SwiftUI's hosting views, AppKit). var display: [Double] = [], displayOther: [Double] = [] var fixes: [Int] = [] if env["DOCS_RT_AUDIT_COUNT_FIXES"] == "1" { countAttributeFixing() } let clock = ContinuousClock.now for i in 0.. .now { try? await Task.sleep(until: due) } window.makeFirstResponder(editor) 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)! let t = DispatchTime.now().uptimeNanoseconds let lines0 = DocsProbes.lineRequests, measure0 = DocsProbes.measureLineRequests, pagination0 = DocsProbes.paginationMs let fixed0 = fixedCharacters editor.keyDown(with: event) keyDown.append(Double(DispatchTime.now().uptimeNanoseconds - t) / 1e6) let ours0 = DocsProbes.textLayoutMs + DocsProbes.drawMs, d0 = DispatchTime.now().uptimeNanoseconds window.displayIfNeeded() let displayed = Double(DispatchTime.now().uptimeNanoseconds - d0) / 1e6 display.append(displayed); displayOther.append(displayed - (DocsProbes.textLayoutMs + DocsProbes.drawMs - ours0)) drawn.append(Double(DispatchTime.now().uptimeNanoseconds - t) / 1e6) lines.append(DocsProbes.lineRequests - lines0); measureLines.append(DocsProbes.measureLineRequests - measure0) paginationMs.append(DocsProbes.paginationMs - pagination0) fixes.append(fixedCharacters - fixed0) } let typedAt = ContinuousClock.now try? await Task.sleep(for: .seconds(Double(env["DOCS_RT_AUDIT_SETTLE_S"] ?? "6") ?? 6)) let typedStall = stalls.stop() let sorted = keyDown.sorted() 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)) let drawnSorted = drawn.sorted() 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)) let paginationSorted = paginationMs.sorted() 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", lines.max() ?? 0, lines.sorted()[lines.count / 2], measureLines.max() ?? 0, measureLines.sorted()[measureLines.count / 2], paginationSorted[paginationSorted.count / 2], paginationSorted.last ?? 0)) print("RTUI typing per key line requests: \(lines.map(String.init).joined(separator: " "))") if env["DOCS_RT_AUDIT_COUNT_FIXES"] == "1" { print("RTUI typing per key characters fixed: \(fixes.map(String.init).joined(separator: " "))") } print("RTUI typing per key keyDown ms: \(keyDown.map { String(format: "%.1f", $0) }.joined(separator: " "))") let displaySorted = display.sorted(), otherSorted = displayOther.sorted() 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", displaySorted[displaySorted.count / 2], displaySorted[min(displaySorted.count - 1, Int(Double(displaySorted.count) * 0.95))], otherSorted[otherSorted.count / 2], otherSorted[min(otherSorted.count - 1, Int(Double(otherSorted.count) * 0.95))])) counters("typing (\(keys) keys + settle)", per: keys) print("RTUI typing path \(DocsProbes.pathSummary)") let x = (editor.string as NSString).components(separatedBy: "x").count - 1 print("RTUI typing: settle after last key \(typedAt.duration(to: .now)); x in editor \(x)") // B. Remote: run-ui.py posts the peer's updates once this file exists. DocsProbes.reset() stalls.start() try? Data().write(to: dir.appendingPathComponent("typing-done")) var seen: [Double] = [] var lastLength = -1 let deadline = ContinuousClock.now.advanced(by: .seconds(240)) while ContinuousClock.now < deadline { let text = editor.string as NSString if text.length != lastLength { lastLength = text.length var count = 0, range = NSRange(location: 0, length: text.length) while true { let found = text.range(of: "Z", options: .literal, range: range) if found.location == NSNotFound { break } count += 1; range = NSRange(location: found.location + 1, length: text.length - found.location - 1) } while seen.count < count { seen.append(serverNow()) } } if FileManager.default.fileExists(atPath: dir.appendingPathComponent("remote-done").path), let expected = Int((try? String(contentsOf: dir.appendingPathComponent("remote-done"), encoding: .utf8)) ?? ""), seen.count >= expected { break } try? await Task.sleep(for: .milliseconds(3)) } try? await Task.sleep(for: .seconds(2)) let remoteStall = stalls.stop() print("RTUI remote: main queue \(remoteStall)") print(String(format: "RTUI remote: main-thread busy per peer change %.2f ms (n=%d)", stalls.busy / Double(max(1, seen.count)), seen.count)) counters("remote", per: seen.count) print("RTUI remote path \(DocsProbes.pathSummary)") try? JSONEncoder().encode(seen).write(to: dir.appendingPathComponent("seen.json")) print("RTUI remote: seen \(seen.count)") exit(0) } }