// fixtures/engines/saving-webkit.swift — saving.mjs in WebKit itself: a // WKWebView, the engine Safari is, rather than Playwright's build of it. // Two scenarios, chosen by the config's "scenario", each reporting the // save states the page showed; internal/docs/saving_browser_test.go // checks the server's side. // // - "held-link", saving.mjs's own, with the same in-page script (passed // in the config): open a document, click a link the server never // answers, type. // - "back": type, and leave while that save is on the wire (the server // answers it late, once the page is in the back/forward cache, which // Playwright's WebKit does not keep); come back and type again. WebKit // never settles the promise of a keepalive save answered while its page // was away, so the editor waited on it forever and nothing typed after // coming back was ever sent. With "before" a large paste and a short // "awayMs", the page is back while that save and the unload beacon may // still hold keepalive's 64KiB, and the resend is refused: that must not // read as a failed save. // // The window is never shown, so the page would be hidden and its timers // throttled, as an occluded Safari tab's are; occlusion detection is // turned off so the page is visible, as a document someone is typing in // is. Built by the test with swiftc; macOS only. // // As in saving.mjs, nothing waits a fixed time to decide anything: each // scenario watches the page at least as long as it used to, then until the // server's view of the document (config.state) holds config.want, for at // most twenty seconds, and reports whether it did. The page's requests are // recorded by the config's trace script and printed on a "SAVING TRACE" // line, which the test shows if the scenario fails. import Cocoa import WebKit struct Config: Decodable { struct Cookie: Decodable { let Name: String let Value: String } let origin: String let doc: String let scenario: String let script: String let typing: [String: String] let type: String let cookies: [Cookie] // trace records the page's requests; state, followed by the sqid, is // the server's view of the document; want is what the server must // hold for the scenario to be done. let trace: String let state: String let want: String // back: what is typed before leaving, and how long the page is away. let before: String? let awayMs: Int? } @MainActor final class Harness: NSObject, NSApplicationDelegate { var window: NSWindow! var web: WKWebView! let config: Config init(config: Config) { self.config = config } func applicationDidFinishLaunching(_ notification: Notification) { Task { do { try await run() exit(0) } catch { print("SAVING FAILED \(error)") exit(1) } } } func js(_ script: String) async throws -> Any? { try await web.evaluateJavaScript(script) } func until(_ script: String, seconds: Double) async -> Bool { let end = Date().addingTimeInterval(seconds) while Date() < end { if (try? await js(script)) as? Bool == true { return true } try? await Task.sleep(for: .milliseconds(100)) } return false } // The fixed pause each scenario's watch replaces, and how long it // waits for the server at most. let watch = 3.0 let ceiling = 20.0 // View is the test server's side of the document: its text, how many // saves it answered while the held link loaded, and every save that // reached it. Asked from here, not from the page. struct View: Decodable { struct Post: Decodable { let status: Int } let text: String let held: Int let posts: [Post] } func view() async -> View? { guard let (data, _) = try? await URLSession.shared.data(from: URL(string: config.origin + config.state + config.doc)!) else { return nil } return try? JSONDecoder().decode(View.self, from: data) } func holds(_ text: String, _ want: String) -> Bool { want.split(separator: " ").allSatisfy { text.contains($0) } } // settle waits for done(view) from since, at least watchFor seconds // and at most the ceiling; it says whether it came, and after how // many milliseconds. func settle(since: Date, watchFor: Double, _ done: (View) -> Bool) async -> (Bool, Int) { while true { let s = Date().timeIntervalSince(since) if s >= watchFor, let v = await view(), done(v) { try? await Task.sleep(for: .milliseconds(250)) return (true, Int(s * 1000)) } if s >= ceiling { return (false, Int(s * 1000)) } try? await Task.sleep(for: .milliseconds(100)) } } // report prints the scenario's "SAVING RESULT" and "SAVING TRACE" // lines: the save states the page showed, whether what it waited for // came, and the page's requests. func report(_ engine: String, persisted: Bool? = nil, settled: Bool, ms: Int, waiting: String) async { func read(_ script: String) async -> Any { let s = (try? await js(script)) as? String ?? "[]" return (try? JSONSerialization.jsonObject(with: Data(s.utf8))) ?? [] } var result: [String: Any] = ["engine": engine, "states": await read("JSON.stringify(window.__saveStates || [])"), "settled": settled, "ms": ms, "waiting": waiting] if let persisted { result["persisted"] = persisted } let trace: [String: Any] = ["engine": engine, "trace": await read("JSON.stringify(window.__saveTrace || [])")] for (prefix, line) in [("SAVING RESULT ", result), ("SAVING TRACE ", trace)] { let data = try! JSONSerialization.data(withJSONObject: line, options: [.sortedKeys]) print(prefix + String(decoding: data, as: UTF8.self)) } } func run() async throws { setbuf(stdout, nil) let cfg = WKWebViewConfiguration() cfg.websiteDataStore = .nonPersistent() cfg.userContentController.addUserScript(WKUserScript(source: config.trace, injectionTime: .atDocumentStart, forMainFrameOnly: true)) let host = URL(string: config.origin)!.host! for c in config.cookies { let cookie = HTTPCookie(properties: [.name: c.Name, .value: c.Value, .domain: host, .path: "/"])! await cfg.websiteDataStore.httpCookieStore.setCookie(cookie) } web = WKWebView(frame: NSRect(x: 0, y: 0, width: 1100, height: 800), configuration: cfg) // A visible page, as one being typed in is (see the header). let occlusion = Selector(("_setWindowOcclusionDetectionEnabled:")) if web.responds(to: occlusion) { typealias Set = @convention(c) (AnyObject, Selector, Bool) -> Void unsafeBitCast(web.method(for: occlusion), to: Set.self)(web, occlusion, false) } window = NSWindow(contentRect: web.frame, styleMask: [.titled], backing: .buffered, defer: false) window.contentView = web let editor = "!!document.querySelector('html[data-docs-fonts=\"shown\"] [docs-text][contenteditable=\"true\"]')" if config.scenario == "back" { try await back(editor) return } web.load(URLRequest(url: URL(string: config.origin + "/d/" + config.doc)!)) guard await until(editor, seconds: 30) else { throw NSError(domain: "the editor never opened", code: 1) } try await Task.sleep(for: .milliseconds(500)) let typing = String(data: try JSONEncoder().encode(config.typing), encoding: .utf8)! let since = Date() _ = try await js("(\(config.script))(\(typing)); true") let (settled, ms) = await settle(since: since, watchFor: watch) { holds($0.text, config.want) && $0.held > 0 } await report("wkwebview", settled: settled, ms: ms, waiting: "the server to hold \"\(config.want)\", saved while the link loaded") } // back is the "back" scenario (see the header). func back(_ editor: String) async throws { // Away to a page that costs nothing to draw (the documents list lays // out a thumbnail of every document, the large ones included). let list = "location.pathname === '/healthz' && document.readyState === 'complete'" web.load(URLRequest(url: URL(string: config.origin + "/healthz")!)) guard await until(list, seconds: 30) else { throw NSError(domain: "the first page never loaded", code: 1) } // From there, so there is a page to come back to (WebKit turns a // navigation before the load event into a replacement). web.load(URLRequest(url: URL(string: config.origin + "/d/" + config.doc)!)) guard await until(editor, seconds: 30) else { throw NSError(domain: "the editor never opened", code: 1) } try await Task.sleep(for: .milliseconds(500)) _ = try await js("window.__saveStates = []; new MutationObserver(() => window.__saveStates.push(document.querySelector('[estilo-save-status~=\"floating\"]').getAttribute('data-state'))).observe(document.querySelector('[estilo-save-status~=\"floating\"]'), { attributes: true, attributeFilter: ['data-state'] }); addEventListener('pageshow', (e) => { window.__persisted = e.persisted }); true") let beforeText = config.before ?? "Before leaving" let before = String(data: try JSONEncoder().encode([beforeText]), encoding: .utf8)! var since = Date() _ = try await js("(\(config.type))(\(before)[0]); true") // Past the debounce: the save is on the wire, and the server holds it. var (settled, ms) = await settle(since: since, watchFor: 0) { !$0.posts.isEmpty } guard settled else { await report("wkwebview-back", settled: false, ms: ms, waiting: "the save typed before leaving to reach the server") return } web.load(URLRequest(url: URL(string: config.origin + "/healthz")!)) guard await until(list, seconds: 30) else { throw NSError(domain: "the document was never left", code: 1) } // The held save is answered while the page is away, or, back // sooner (awayMs), it is still on the wire. if let away = config.awayMs { try await Task.sleep(for: .milliseconds(away)) } else { since = Date() (settled, ms) = await settle(since: since, watchFor: 0) { v in holds(v.text, beforeText) && v.posts.allSatisfy { $0.status != 0 } } guard settled else { await report("wkwebview-back", settled: false, ms: ms, waiting: "the save typed before leaving to be answered while the page was away") return } } web.goBack() guard await until("window.__persisted === true && " + editor, seconds: 15) else { await report("wkwebview-back", persisted: false, settled: false, ms: 0, waiting: "the page to come back from the back/forward cache") return } try await Task.sleep(for: .milliseconds(300)) since = Date() _ = try await js("(\(config.type))('After coming back'); true") (settled, ms) = await settle(since: since, watchFor: watch) { holds($0.text, config.want) } await report("wkwebview-back", persisted: true, settled: settled, ms: ms, waiting: "the server to hold \"\(config.want)\"") } } let config = try! JSONDecoder().decode(Config.self, from: ProcessInfo.processInfo.environment["DOCS_SAVING_CONFIG"]!.data(using: .utf8)!) MainActor.assumeIsolated { let app = NSApplication.shared let delegate = Harness(config: config) app.delegate = delegate app.setActivationPolicy(.accessory) app.run() }