import Foundation import RastrilloApple import RastrilloTestSupport import SwiftUI import XCTest @testable import DocsKit #if os(macOS) import AppKit #else import UIKit #endif /// Render isolation and §7's hard counters (spec 2026-11-22 §7 Design 9, /// "Measurement and targets"; §11 "Render isolation"). The production /// `DocsWorkspace` for one document in a real window, on an in-memory /// server: type 40 keys, flip the sync status 10 times, move the selection /// 20 times and take 5 peer changes. After open, the text view's host is /// never evaluated again, nothing renders the whole document, iOS never /// assigns `attributedText`, and each key or peer change renders at most /// its block and two neighbours. #if DOCS_PROBES @MainActor final class RenderIsolationTests: XCTestCase { private var window: AnyObject? func testTheHostObservesNothingThatMovesPerKey() async throws { DocsFonts.register() let server = LoopServer() try await server.seed(LoopFixture.everything) let path = ScriptedPathSource(.satisfied) let connectivity = NativeConnectivity(source: path) let workspace = DocsWorkspace(client: NativeHTTP(origin: server.origin), transport: { server }, signOut: {}, documentID: "doc", connectivity: connectivity) #if os(macOS) let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 800), styleMask: [.titled, .resizable], backing: .buffered, defer: false) window.isReleasedWhenClosed = false window.contentView = NSHostingView(rootView: workspace) window.orderFront(nil) #else let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) if let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene { window.windowScene = scene } window.rootViewController = UIHostingController(rootView: workspace) window.makeKeyAndVisible() #endif self.window = window defer { #if os(macOS) window.contentView = nil; window.close() #else window.rootViewController = nil; window.isHidden = true #endif } func find() -> DocsTextView? { #if os(macOS) func search(_ view: NSView) -> DocsTextView? { (view as? DocsTextView) ?? view.subviews.lazy.compactMap(search).first } return window.contentView.flatMap(search) #else func search(_ view: UIView) -> DocsTextView? { (view as? DocsTextView) ?? view.subviews.lazy.compactMap(search).first } return search(window) #endif } try await until("the document is shown") { find().map { Keyboard.storage(of: $0).string.contains(LoopFixture.middle) } ?? false } let text = try XCTUnwrap(find()) let surface = try XCTUnwrap(text.delegate as? DocumentSurface) // Drawn: nothing waiting, and no character without its block (typed // text carries its block's id only once a publication drew it on // iOS, whose typing attributes may leave it out). func settled() -> Bool { (surface.newest.map { $0.revision == surface.appliedRevision } ?? false) && surface.pendingDirty.isEmpty && !surface.index.runs.contains { $0.id == nil } } try await until("open settled") { settled() } try await Task.sleep(for: .milliseconds(300)) var storageEdits = 0 let observer = NotificationCenter.default.addObserver(forName: NSTextStorage.didProcessEditingNotification, object: Keyboard.storage(of: text), queue: nil) { _ in MainActor.assumeIsolated { storageEdits += 1 } } defer { NotificationCenter.default.removeObserver(observer) } DocsProbes.reset() // 40 keys, each drawn before the next. let line = (surface.content.string as NSString).range(of: LoopFixture.middle) Keyboard.select(NSRange(location: NSMaxRange(line), length: 0), in: text) var typed = LoopFixture.middle var perKey: [(blocks: Int, edits: Int)] = [] var chrome: [Int] = [] for index in 0..<40 { let blocks = DocsProbes.blockRenders, edits = storageEdits let bodies = DocsProbes.workspaceBodies + DocsProbes.inspectorBodies let character = index % 10 == 9 ? " " : String(UnicodeScalar(UInt8(97 + index % 26))) Keyboard.type(character, in: text) typed += character try await until("key \(index) drawn") { settled() && surface.content.string.contains(typed) && surface.appliedRevision > 0 } try await Task.sleep(for: .milliseconds(20)) perKey.append((DocsProbes.blockRenders - blocks, storageEdits - edits)) chrome.append(DocsProbes.workspaceBodies + DocsProbes.inspectorBodies - bodies) } XCTAssertEqual(DocsProbes.wholeRenders, 0, "whole-document renders while typing") XCTAssertEqual(DocsProbes.hostBodies, 0, "host body evaluations while typing") // S1b step 0: the workspace and the inspector were evaluated again // on every key (the offline banner's summary, the commands' pending // input), 2–4 ms of each key's display pass. Only the first key may // move them: it makes Undo possible. XCTAssertEqual(chrome.dropFirst().reduce(0, +), 0, "workspace and inspector body evaluations per key after the first: \(chrome)") XCTAssertEqual(DocsProbes.attributedTextAssignments, 0, "attributedText assignments while typing") XCTAssertLessThanOrEqual(perKey.map(\.blocks).max() ?? 0, 3, "block renders per key: \(perKey.map(\.blocks))") XCTAssertLessThanOrEqual(perKey.map(\.edits).max() ?? 0, 3, "text-storage edits per key: \(perKey.map(\.edits))") print("RENDER ISOLATION per key: block renders \(perKey.map(\.blocks)), storage edits \(perKey.map(\.edits)); \(DocsProbes.summary)") // The sync status, ten times. DocsProbes.reset(); storageEdits = 0 for index in 0..<10 { path.send(index % 2 == 0 ? .unsatisfied : .satisfied) try await Task.sleep(for: .milliseconds(40)) } path.send(.satisfied) try await Task.sleep(for: .milliseconds(200)) XCTAssertEqual(DocsProbes.hostBodies, 0, "host body evaluations per sync-status change") XCTAssertEqual(DocsProbes.wholeRenders, 0, "whole renders per sync-status change") XCTAssertEqual(DocsProbes.blockRenders, 0, "block renders per sync-status change") XCTAssertEqual(storageEdits, 0, "storage edits per sync-status change") // The selection, twenty times. DocsProbes.reset(); storageEdits = 0 let length = surface.content.length for index in 0..<20 { Keyboard.select(NSRange(location: (index * 37) % max(1, length - 1), length: index % 3), in: text) try await Task.sleep(for: .milliseconds(10)) } try await Task.sleep(for: .milliseconds(200)) XCTAssertEqual(DocsProbes.hostBodies, 0, "host body evaluations per selection change") XCTAssertEqual(DocsProbes.wholeRenders, 0, "whole renders per selection change") XCTAssertEqual(DocsProbes.blockRenders, 0, "block renders per selection change") XCTAssertEqual(storageEdits, 0, "storage edits per selection change") // Five peer changes, in one block. DocsProbes.reset() for index in 0..<5 { let note = "Peer\(index) " let at = (surface.content.string as NSString).range(of: LoopFixture.afterRule).location let blocks = DocsProbes.blockRenders try await server.peerInsert(note, at: at) try await until("peer change \(index) shown") { surface.content.string.contains(note) && settled() } try await Task.sleep(for: .milliseconds(20)) XCTAssertLessThanOrEqual(DocsProbes.blockRenders - blocks, 3, "block renders for peer change \(index)") } XCTAssertEqual(DocsProbes.wholeRenders, 0, "whole renders per peer change") XCTAssertEqual(DocsProbes.hostBodies, 0, "host body evaluations per peer change") XCTAssertEqual(DocsProbes.attributedTextAssignments, 0, "attributedText assignments per peer change") print("RENDER ISOLATION peers: \(DocsProbes.summary)") } private func until(_ what: String, _ condition: () -> Bool) async throws { let deadline = ContinuousClock.now + .seconds(10) while !condition() { guard ContinuousClock.now < deadline else { throw LoopFailure("timed out waiting for \(what)") } try await Task.sleep(for: .milliseconds(5)) } } } #endif