oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2import RastrilloApple
3import RastrilloTestSupport
4import SwiftUI
5import XCTest
6@testable import DocsKit
7#if os(macOS)
8import AppKit
9#else
10import UIKit
11#endif
12
13/// Render isolation and §7's hard counters (spec 2026-11-22 §7 Design 9,
14/// "Measurement and targets"; §11 "Render isolation"). The production
15/// `DocsWorkspace` for one document in a real window, on an in-memory
16/// server: type 40 keys, flip the sync status 10 times, move the selection
17/// 20 times and take 5 peer changes. After open, the text view's host is
18/// never evaluated again, nothing renders the whole document, iOS never
19/// assigns `attributedText`, and each key or peer change renders at most
20/// its block and two neighbours.
21#if DOCS_PROBES
22@MainActor final class RenderIsolationTests: XCTestCase {
23 private var window: AnyObject?
24
25 func testTheHostObservesNothingThatMovesPerKey() async throws {
26 DocsFonts.register()
27 let server = LoopServer()
28 try await server.seed(LoopFixture.everything)
29 let path = ScriptedPathSource(.satisfied)
30 let connectivity = NativeConnectivity(source: path)
31 let workspace = DocsWorkspace(client: NativeHTTP(origin: server.origin), transport: { server }, signOut: {}, documentID: "doc", connectivity: connectivity)
32 #if os(macOS)
33 let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 800), styleMask: [.titled, .resizable], backing: .buffered, defer: false)
34 window.isReleasedWhenClosed = false
35 window.contentView = NSHostingView(rootView: workspace)
36 window.orderFront(nil)
37 #else
38 let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
39 if let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene { window.windowScene = scene }
40 window.rootViewController = UIHostingController(rootView: workspace)
41 window.makeKeyAndVisible()
42 #endif
43 self.window = window
44 defer {
45 #if os(macOS)
46 window.contentView = nil; window.close()
47 #else
48 window.rootViewController = nil; window.isHidden = true
49 #endif
50 }
51 func find() -> DocsTextView? {
52 #if os(macOS)
53 func search(_ view: NSView) -> DocsTextView? { (view as? DocsTextView) ?? view.subviews.lazy.compactMap(search).first }
54 return window.contentView.flatMap(search)
55 #else
56 func search(_ view: UIView) -> DocsTextView? { (view as? DocsTextView) ?? view.subviews.lazy.compactMap(search).first }
57 return search(window)
58 #endif
59 }
60 try await until("the document is shown") { find().map { Keyboard.storage(of: $0).string.contains(LoopFixture.middle) } ?? false }
61 let text = try XCTUnwrap(find())
62 let surface = try XCTUnwrap(text.delegate as? DocumentSurface)
63 // Drawn: nothing waiting, and no character without its block (typed
64 // text carries its block's id only once a publication drew it on
65 // iOS, whose typing attributes may leave it out).
66 func settled() -> Bool {
67 (surface.newest.map { $0.revision == surface.appliedRevision } ?? false) && surface.pendingDirty.isEmpty
68 && !surface.index.runs.contains { $0.id == nil }
69 }
70 try await until("open settled") { settled() }
71 try await Task.sleep(for: .milliseconds(300))
72 var storageEdits = 0
73 let observer = NotificationCenter.default.addObserver(forName: NSTextStorage.didProcessEditingNotification, object: Keyboard.storage(of: text), queue: nil) { _ in
74 MainActor.assumeIsolated { storageEdits += 1 }
75 }
76 defer { NotificationCenter.default.removeObserver(observer) }
77 DocsProbes.reset()
78
79 // 40 keys, each drawn before the next.
80 let line = (surface.content.string as NSString).range(of: LoopFixture.middle)
81 Keyboard.select(NSRange(location: NSMaxRange(line), length: 0), in: text)
82 var typed = LoopFixture.middle
83 var perKey: [(blocks: Int, edits: Int)] = []
84 var chrome: [Int] = []
85 for index in 0..<40 {
86 let blocks = DocsProbes.blockRenders, edits = storageEdits
87 let bodies = DocsProbes.workspaceBodies + DocsProbes.inspectorBodies
88 let character = index % 10 == 9 ? " " : String(UnicodeScalar(UInt8(97 + index % 26)))
89 Keyboard.type(character, in: text)
90 typed += character
91 try await until("key \(index) drawn") { settled() && surface.content.string.contains(typed) && surface.appliedRevision > 0 }
92 try await Task.sleep(for: .milliseconds(20))
93 perKey.append((DocsProbes.blockRenders - blocks, storageEdits - edits))
94 chrome.append(DocsProbes.workspaceBodies + DocsProbes.inspectorBodies - bodies)
95 }
96 XCTAssertEqual(DocsProbes.wholeRenders, 0, "whole-document renders while typing")
97 XCTAssertEqual(DocsProbes.hostBodies, 0, "host body evaluations while typing")
98 // S1b step 0: the workspace and the inspector were evaluated again
99 // on every key (the offline banner's summary, the commands' pending
100 // input), 2–4 ms of each key's display pass. Only the first key may
101 // move them: it makes Undo possible.
102 XCTAssertEqual(chrome.dropFirst().reduce(0, +), 0, "workspace and inspector body evaluations per key after the first: \(chrome)")
103 XCTAssertEqual(DocsProbes.attributedTextAssignments, 0, "attributedText assignments while typing")
104 XCTAssertLessThanOrEqual(perKey.map(\.blocks).max() ?? 0, 3, "block renders per key: \(perKey.map(\.blocks))")
105 XCTAssertLessThanOrEqual(perKey.map(\.edits).max() ?? 0, 3, "text-storage edits per key: \(perKey.map(\.edits))")
106 print("RENDER ISOLATION per key: block renders \(perKey.map(\.blocks)), storage edits \(perKey.map(\.edits)); \(DocsProbes.summary)")
107
108 // The sync status, ten times.
109 DocsProbes.reset(); storageEdits = 0
110 for index in 0..<10 {
111 path.send(index % 2 == 0 ? .unsatisfied : .satisfied)
112 try await Task.sleep(for: .milliseconds(40))
113 }
114 path.send(.satisfied)
115 try await Task.sleep(for: .milliseconds(200))
116 XCTAssertEqual(DocsProbes.hostBodies, 0, "host body evaluations per sync-status change")
117 XCTAssertEqual(DocsProbes.wholeRenders, 0, "whole renders per sync-status change")
118 XCTAssertEqual(DocsProbes.blockRenders, 0, "block renders per sync-status change")
119 XCTAssertEqual(storageEdits, 0, "storage edits per sync-status change")
120
121 // The selection, twenty times.
122 DocsProbes.reset(); storageEdits = 0
123 let length = surface.content.length
124 for index in 0..<20 {
125 Keyboard.select(NSRange(location: (index * 37) % max(1, length - 1), length: index % 3), in: text)
126 try await Task.sleep(for: .milliseconds(10))
127 }
128 try await Task.sleep(for: .milliseconds(200))
129 XCTAssertEqual(DocsProbes.hostBodies, 0, "host body evaluations per selection change")
130 XCTAssertEqual(DocsProbes.wholeRenders, 0, "whole renders per selection change")
131 XCTAssertEqual(DocsProbes.blockRenders, 0, "block renders per selection change")
132 XCTAssertEqual(storageEdits, 0, "storage edits per selection change")
133
134 // Five peer changes, in one block.
135 DocsProbes.reset()
136 for index in 0..<5 {
137 let note = "Peer\(index) "
138 let at = (surface.content.string as NSString).range(of: LoopFixture.afterRule).location
139 let blocks = DocsProbes.blockRenders
140 try await server.peerInsert(note, at: at)
141 try await until("peer change \(index) shown") { surface.content.string.contains(note) && settled() }
142 try await Task.sleep(for: .milliseconds(20))
143 XCTAssertLessThanOrEqual(DocsProbes.blockRenders - blocks, 3, "block renders for peer change \(index)")
144 }
145 XCTAssertEqual(DocsProbes.wholeRenders, 0, "whole renders per peer change")
146 XCTAssertEqual(DocsProbes.hostBodies, 0, "host body evaluations per peer change")
147 XCTAssertEqual(DocsProbes.attributedTextAssignments, 0, "attributedText assignments per peer change")
148 print("RENDER ISOLATION peers: \(DocsProbes.summary)")
149 }
150
151 private func until(_ what: String, _ condition: () -> Bool) async throws {
152 let deadline = ContinuousClock.now + .seconds(10)
153 while !condition() {
154 guard ContinuousClock.now < deadline else { throw LoopFailure("timed out waiting for \(what)") }
155 try await Task.sleep(for: .milliseconds(5))
156 }
157 }
158}
159#endif
160