oficina / docs Public

Merge remote-tracking branch 'origin/main' into fix/phone-pickers

claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 2b04c1b83c2fe7d16fb60daecd71a431f52dbeee parent c861852parent 3ef4ef3
3 files changed, +615 −121
  • fixtures/engines/saving-webkit.swift +96 −11
  • fixtures/engines/saving.mjs +152 −62
  • internal/docs/saving_browser_test.go +367 −48
diff --git a/fixtures/engines/saving-webkit.swift b/fixtures/engines/saving-webkit.swift
index fe7a090..3d70089 100644
--- a/fixtures/engines/saving-webkit.swift
+++ b/fixtures/engines/saving-webkit.swift
@@ -21,6 +21,13 @@
// 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
@@ -37,6 +44,12 @@ struct Config: Decodable {
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?
@@ -72,10 +85,67 @@ struct Config: Decodable {
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: "/"])!
@@ -101,10 +171,10 @@ struct Config: Decodable {
}
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")
- try await Task.sleep(for: .seconds(3))
- let states = (try? await js("JSON.stringify(window.__saveStates || [])")) as? String ?? "[]"
- print("SAVING RESULT {\"engine\":\"wkwebview\",\"states\":\(states)}")
+ 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).
@@ -120,25 +190,40 @@ struct Config: Decodable {
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]').getAttribute('data-state'))).observe(document.querySelector('[estilo-save-status]'), { attributes: true, attributeFilter: ['data-state'] }); addEventListener('pageshow', (e) => { window.__persisted = e.persisted }); true")
- let before = String(data: try JSONEncoder().encode([config.before ?? "Before leaving"]), encoding: .utf8)!
+ 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.
- try await Task.sleep(for: .milliseconds(600))
+ 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, it is still on the wire.
- try await Task.sleep(for: .milliseconds(config.awayMs ?? 2000))
+ // 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 {
- print("SAVING RESULT {\"engine\":\"wkwebview-back\",\"persisted\":false,\"states\":[]}")
+ 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")
- try await Task.sleep(for: .seconds(3))
- let states = (try? await js("JSON.stringify(window.__saveStates || [])")) as? String ?? "[]"
- print("SAVING RESULT {\"engine\":\"wkwebview-back\",\"persisted\":true,\"states\":\(states)}")
+ (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)\"")
}
}
diff --git a/fixtures/engines/saving.mjs b/fixtures/engines/saving.mjs
index cca0778..cb66684 100644
--- a/fixtures/engines/saving.mjs
+++ b/fixtures/engines/saving.mjs
@@ -14,79 +14,170 @@
// Run by internal/docs/saving_browser_test.go, which serves the link's
// target and holds it unanswered, counts the saves that reach it while it
// does, and reads the document back from the server afterwards. This
-// prints one "SAVING RESULT" line per engine with the save states the page
-// showed, and, given config.closing, one "SAVING CLOSED" line once a page
-// that closed with a large save on the wire has had time to beacon.
+// prints, per scenario, one "SAVING RESULT" line with the save states the
+// page showed and whether what the scenario waited for came, and one
+// "SAVING TRACE" line with the page's requests (the config's trace
+// script), which the test prints if the scenario fails.
+//
+// Nothing here waits a fixed time to decide anything. Each scenario
+// watches the page at least as long as it used to (WATCH_MS), then until
+// the server's view of the document (config.state) holds what it waits
+// for, for at most CEILING_MS. A fixed three seconds could not tell a slow
+// pass from a stall (Claude Fable on #94, round 3).
const { chromium, webkit } = await import('playwright')
const config = JSON.parse(process.env.DOCS_SAVING_CONFIG)
const pause = (ms) => new Promise((r) => setTimeout(r, ms))
+// WATCH_MS is how long a scenario watches the save line at least: the
+// fixed pause it replaces, so no state it could see is missed now.
+// CEILING_MS is how long it waits for the server at most.
+const WATCH_MS = 3000
+const CEILING_MS = 20000
+
+// view is the test server's side of a document: its text, and every save
+// that reached it. Asked from here, not from the page, which is the one
+// whose requests are being refused.
+// A poll that fails is "not yet", as in the WKWebView harness: throwing
+// here would end every scenario left, with nothing explained, at the one
+// time the explanation is wanted (Claude Fable on Docs #98).
+const view = async (sqid) => {
+ try {
+ const r = await fetch(config.origin + config.state + sqid)
+ return r.ok ? await r.json() : null
+ } catch {
+ return null
+ }
+}
+
+const holds = (text, want) => want.split(/\s+/).every((w) => text.includes(w))
+
+// retried is whether the page tried a save again after one was refused:
+// the moment it decides whether to say "Trouble saving".
+const retried = (trace) => {
+ const refused = new Set(trace.filter((e) => e.ev === 'refused').map((e) => e.id))
+ const posts = trace.filter((e) => e.ev === 'start' && e.m === 'POST' && e.u.endsWith('/updates'))
+ return posts.some((p, i) => refused.has(p.id) && i < posts.length - 1)
+}
+
+// settle waits for done(view) from since, at least watchMs and at most
+// CEILING_MS, and says whether it came and when.
+async function settle (sqid, since, watchMs, done) {
+ for (;;) {
+ const ms = Date.now() - since
+ const v = ms >= watchMs ? await view(sqid) : null
+ if (v && done(v)) {
+ // The page's console lines from just before are still on their way.
+ await pause(250)
+ return { settled: true, ms }
+ }
+ if (ms >= CEILING_MS) return { settled: false, ms }
+ await pause(100)
+ }
+}
+
+// open is a document's page, ready to type in, with its save states and
+// requests read from its console from the start: Playwright's own
+// evaluate waits for a pending navigation to finish, and the held link
+// never does.
+async function open (context, sqid) {
+ const page = await context.newPage()
+ const seen = { states: [], trace: [], typed: false }
+ page.on('console', (m) => {
+ const t = m.text()
+ if (t.startsWith('SAVE-STATE ')) seen.states.push(t.slice('SAVE-STATE '.length))
+ else if (t.startsWith('SAVE-TRACE ')) seen.trace.push(JSON.parse(t.slice('SAVE-TRACE '.length)))
+ else if (t === 'SAVE-TYPED') seen.typed = true
+ })
+ // A real close asks first only while a resync holds the page; yes.
+ page.on('dialog', (d) => d.accept().catch(() => {}))
+ await page.goto(config.origin + '/d/' + sqid)
+ await page.waitForSelector('html[data-docs-fonts="shown"] [docs-text][contenteditable="true"]', { timeout: 30000 })
+ await pause(500)
+ return { page, seen }
+}
+
+const report = (engine, seen, got, waiting) => {
+ console.log('SAVING RESULT ' + JSON.stringify({ engine, states: seen.states, settled: got.settled, ms: got.ms, waiting }))
+ console.log('SAVING TRACE ' + JSON.stringify({ engine, trace: seen.trace }))
+}
+
+// heldScenario types into a document with the held link loading, and
+// waits for the server to hold want: saved while the link loads, given
+// link, or, given orRetried, a refused save tried again will do.
+async function heldScenario (context, engine, sqid, typing, { want, link, orRetried }) {
+ const { page, seen } = await open(context, sqid)
+ const since = Date.now()
+ await page.evaluate(`(${config.script})(${JSON.stringify(typing)})`)
+ const waiting = `the server to hold ${JSON.stringify(want.slice(0, 40))}` + (link ? ', saved while the link loaded' : '') + (orRetried ? ', or a refused save tried again' : '')
+ const got = await settle(sqid, since, WATCH_MS, (v) => (holds(v.text, want) && (!link || v.held > 0)) || (orRetried && retried(seen.trace)))
+ report(engine, seen, got, waiting)
+ // Each page done with is closed, and its held link and stream with it:
+ // left open they take the host's connections (six, on HTTP/1.1), and a
+ // later page's unload beacon queues behind them. Playwright's close
+ // skips the unload handlers, so this is harsher than a tab closing:
+ // what the scenario waited for has to have been saved already.
+ await page.close()
+}
+
for (const [engineName, engine] of Object.entries({ chromium, webkit }).filter(([n]) => !process.env.DOCS_ENGINES_ENGINE || n === process.env.DOCS_ENGINES_ENGINE)) {
const browser = await engine.launch({ headless: true })
try {
const context = await browser.newContext()
await context.addCookies(config.cookies.map((c) => ({ name: c.Name, value: c.Value, url: config.origin, httpOnly: c.HttpOnly, sameSite: 'Lax' })))
- const page = await context.newPage()
- const states = []
- // The page is read through its console from here on: Playwright's own
- // evaluate waits for a pending navigation to finish, and this one never
- // does.
- page.on('console', (m) => {
- if (m.text().startsWith('SAVE-STATE ')) states.push(m.text().slice('SAVE-STATE '.length))
- })
- await page.goto(config.origin + '/d/' + config.docs[engineName])
- await page.waitForSelector('html[data-docs-fonts="shown"] [docs-text][contenteditable="true"]', { timeout: 30000 })
- await pause(500)
- await page.evaluate(`(${config.script})(${JSON.stringify(config.typing)})`)
- // Well past the debounce and a local round trip, and the link is still
- // loading: the test's server holds it until the browser goes away.
- await pause(3000)
- console.log('SAVING RESULT ' + JSON.stringify({ engine: engineName, states }))
- // Each page done with is closed, and its held link and stream with it:
- // left open they take the host's connections (six, on HTTP/1.1), and a
- // later page's unload beacon queues behind them.
- await page.close()
-
- // The same with other edits (config.held: [{ name, docs, typing }]):
- // a large paste of prose, which goes keepalive once gzipped, and one
- // too large for a keepalive save even compressed, which WebKit refuses
- // until the link is answered. Nothing is lost, and the page must not
- // say a save failed, because none did.
+ await context.addInitScript(config.trace)
+
+ // Three words typed while the link loads: saved while it does.
+ await heldScenario(context, engineName, config.docs[engineName], config.typing, { want: config.want, link: true })
+
+ // The same, closed the way a person closes a tab, as soon as the last
+ // word is in: the unload handlers run, and the beacon carries what the
+ // queue has not yet sent.
+ if (config.closed) {
+ const sqid = config.closed[engineName]
+ const { page, seen } = await open(context, sqid)
+ const since = Date.now()
+ await page.evaluate(`(${config.script})(${JSON.stringify(config.typing)})`)
+ const until = Date.now() + CEILING_MS
+ while (!seen.typed && Date.now() < until) await pause(25)
+ const gone = new Promise((resolve) => page.once('close', resolve))
+ await page.close({ runBeforeUnload: true })
+ await Promise.race([gone, pause(CEILING_MS)])
+ const got = await settle(sqid, since, 0, (v) => holds(v.text, config.want))
+ report(engineName + '-closed', seen, got, `the server to hold ${JSON.stringify(config.want)} after the tab closed`)
+ }
+
+ // The same with other edits (config.held: [{ name, docs, typing, want,
+ // link, retried }]): a large paste of prose, which goes keepalive once
+ // gzipped, and one too large for a keepalive save even compressed,
+ // which WebKit refuses until the link is answered. Nothing is lost, and
+ // the page must not say a save failed, because none did.
for (const held of config.held || []) {
- const page = await context.newPage()
- const heldStates = []
- page.on('console', (m) => {
- if (m.text().startsWith('SAVE-STATE ')) heldStates.push(m.text().slice('SAVE-STATE '.length))
- })
- await page.goto(config.origin + '/d/' + held.docs[engineName])
- await page.waitForSelector('html[data-docs-fonts="shown"] [docs-text][contenteditable="true"]', { timeout: 30000 })
- await pause(500)
- await page.evaluate(`(${config.script})(${JSON.stringify(held.typing)})`)
- await pause(3000)
- console.log('SAVING RESULT ' + JSON.stringify({ engine: engineName + '-' + held.name, states: heldStates }))
- await page.close()
+ await heldScenario(context, engineName + '-' + held.name, held.docs[engineName], held.typing, { want: held.want, link: !!held.link, orRetried: !!held.retried })
}
// Typed with no link loading (config.typed: [{ name, docs, text }]):
// the server's side is the case, such as a hop that strips a gzipped
- // save's Content-Encoding.
+ // save's Content-Encoding. Each text is saved before the next is typed.
for (const typed of config.typed || []) {
- const page = await context.newPage()
- const typedStates = []
- page.on('console', (m) => {
- if (m.text().startsWith('SAVE-STATE ')) typedStates.push(m.text().slice('SAVE-STATE '.length))
- })
- await page.goto(config.origin + '/d/' + typed.docs[engineName])
- await page.waitForSelector('html[data-docs-fonts="shown"] [docs-text][contenteditable="true"]', { timeout: 30000 })
- await pause(500)
+ const sqid = typed.docs[engineName]
+ const { page, seen } = await open(context, sqid)
await page.evaluate(`(() => { const line = document.querySelector('[estilo-save-status]'); new MutationObserver(() => console.log('SAVE-STATE ' + line.getAttribute('data-state'))).observe(line, { attributes: true, attributeFilter: ['data-state'] }) })()`)
+ const got = { settled: true, ms: 0 }
+ let waiting = ''
for (const text of typed.text) {
+ const since = Date.now()
await page.evaluate(`(${config.type})(${JSON.stringify(text)})`)
- await pause(1500)
+ const one = await settle(sqid, since, 1500, (v) => holds(v.text, text))
+ got.ms += one.ms
+ if (!one.settled) {
+ got.settled = false
+ waiting = `the server to hold ${JSON.stringify(text.slice(0, 40))}`
+ break
+ }
}
- console.log('SAVING RESULT ' + JSON.stringify({ engine: engineName + '-' + typed.name, states: typedStates }))
+ report(engineName + '-' + typed.name, seen, got, waiting || 'the server to hold each text')
await page.close()
}
@@ -94,17 +185,16 @@ for (const [engineName, engine] of Object.entries({ chromium, webkit }).filter((
// types more behind it and leaves before that is sent, and the unload
// beacon must carry what was typed. Keepalive requests and beacons
// share one 64KiB quota, so a beacon that repeats the save already on
- // the wire is refused (Claude Fable on #94).
+ // the wire is refused (Claude Fable on #94). Done once the large save
+ // has been answered and the server holds both.
if (config.closing) {
- const closing = await context.newPage()
- await closing.goto(config.origin + '/d/' + config.closing[engineName])
- await closing.waitForSelector('html[data-docs-fonts="shown"] [docs-text][contenteditable="true"]', { timeout: 30000 })
- await pause(500)
- await closing.evaluate(`(${config.closingScript})(${JSON.stringify(config.closingTyping)})`)
- await closing.waitForURL(config.origin + '/healthz', { timeout: 30000 })
- // The held save is answered, and the beacon has long arrived.
- await pause(4500)
- console.log('SAVING CLOSED ' + JSON.stringify({ engine: engineName }))
+ const sqid = config.closing[engineName]
+ const { page, seen } = await open(context, sqid)
+ const since = Date.now()
+ await page.evaluate(`(${config.closingScript})(${JSON.stringify(config.closingTyping)})`)
+ await page.waitForURL(config.origin + '/healthz', { timeout: 30000 })
+ const got = await settle(sqid, since, 0, (v) => !v.largeHeld && holds(v.text, 'Bigpaste Queuedbehind'))
+ report(engineName + '-closing', seen, got, 'the large save to be answered and the server to hold "Bigpaste Queuedbehind"')
}
} finally {
await browser.close()
diff --git a/internal/docs/saving_browser_test.go b/internal/docs/saving_browser_test.go
index ecc8994..9290a7a 100644
--- a/internal/docs/saving_browser_test.go
+++ b/internal/docs/saving_browser_test.go
@@ -5,6 +5,7 @@ package docs_test
import (
"context"
"encoding/json"
+ "fmt"
"math/rand/v2"
"net/http"
"net/http/httptest"
@@ -54,10 +55,52 @@ const savingScript = `({ text, held }) => {
getSelection().collapseToEnd()
document.execCommand('insertText', false, ' ' + words[i])
if (++i < words.length) setTimeout(type, 300)
+ else {
+ window.__typed = true
+ console.log('SAVE-TYPED')
+ }
}
setTimeout(type, 300)
}`
+// traceScript runs in every page before its own scripts: it records the
+// requests a save can make (POSTs, the probe's HEADs, beacons, the log's
+// GETs; not the static files) with their timing and how each was answered
+// or refused, in window.__saveTrace and as "SAVE-TRACE" console lines. The
+// test prints them when a scenario fails, beside the server's side of the
+// same saves, so a failure says which requests left the page and what
+// became of them (Claude Fable on #94, round 3). It hands each call to the
+// browser's own fetch and sendBeacon unchanged and returns their results.
+const traceScript = `(() => {
+ const trace = window.__saveTrace = []
+ const log = (e) => {
+ e.at = Math.round(performance.timeOrigin + performance.now())
+ trace.push(e)
+ console.log('SAVE-TRACE ' + JSON.stringify(e))
+ }
+ const path = (u) => { try { const x = new URL(u, location.href); return x.pathname + x.search } catch { return String(u) } }
+ const size = (b) => b == null ? 0 : (b.byteLength ?? b.size ?? String(b).length)
+ let n = 0
+ const fetch = window.fetch
+ window.fetch = function (input, init) {
+ const u = path(typeof input === 'string' || input instanceof URL ? input : input.url)
+ const m = ((init && init.method) || (input && input.method) || 'GET').toUpperCase()
+ if (m === 'GET' && u.startsWith('/static/')) return fetch.apply(window, arguments)
+ const h = new Headers((init && init.headers) || undefined)
+ const id = ++n
+ log({ id, ev: 'start', m, u, ka: !!(init && init.keepalive), enc: h.get('Content-Encoding') || '', size: size(init && init.body) })
+ const p = fetch.apply(window, arguments)
+ p.then((r) => log({ id, ev: 'answer', status: r.status }), (err) => log({ id, ev: 'refused', err: String(err) }))
+ return p
+ }
+ const beacon = navigator.sendBeacon
+ navigator.sendBeacon = function (u, data) {
+ const ok = beacon.apply(navigator, arguments)
+ log({ id: ++n, ev: 'beacon', m: 'POST', u: path(u), size: size(data), ok })
+ return ok
+ }
+})()`
+
// typeScript types text at the end of the document's first paragraph.
const typeScript = `(text) => {
const el = document.querySelector('[docs-text]')
@@ -146,6 +189,15 @@ func proseText() string {
//
// The scenario is blind unless the link really was loading while the
// saves were made, so that is checked too.
+//
+// The harnesses wait on conditions, not fixed pauses. Each scenario
+// watches the page at least as long as the fixed pause used to, then until
+// the server's view of the document (savingStatePath) holds what the
+// scenario waits for, for at most twenty seconds; a scenario that never
+// gets there fails. Any failure prints the page's requests beside the
+// server's side of them (explain). A fixed three seconds, and a page
+// closed without its unload handlers, made a one-off WebKit failure
+// impossible to read (Claude Fable on #94, round 3).
func TestSavingContinuesWhileALinkIsLoading(t *testing.T) {
if _, err := os.Stat("../../fixtures/engines/node_modules/playwright"); err != nil {
if os.Getenv("RASTRILLO_BROWSER_OPTIONAL") != "" {
@@ -156,11 +208,12 @@ func TestSavingContinuesWhileALinkIsLoading(t *testing.T) {
s := newSavingServer(t)
t.Run("playwright", func(t *testing.T) {
engines := []string{"chromium", "webkit"}
- docs, closing, large, prose, stripped := map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{}
+ docs, closed, closing, large, prose, stripped := map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{}
for _, e := range engines {
stripped[e] = s.document(t, e+" stripped")
s.strip(stripped[e])
docs[e] = s.document(t, e)
+ closed[e] = s.document(t, e+" closed")
large[e] = s.document(t, e+" large")
prose[e] = s.document(t, e+" prose")
closing[e] = s.document(t, e+" closing")
@@ -170,47 +223,58 @@ func TestSavingContinuesWhileALinkIsLoading(t *testing.T) {
cmd.Dir = "../../fixtures/engines"
cmd.Env = append(os.Environ(), "DOCS_SAVING_CONFIG="+s.config(t, map[string]any{
"docs": docs,
+ "closed": closed,
"closing": closing,
"closingScript": closingScript,
"closingTyping": closingTyping(),
"typed": []map[string]any{
{"name": "stripped", "docs": stripped, "text": []string{"Strippedpaste" + strings.Repeat("-gzipped-and-then-stripped", 120), "Smallafter"}},
},
+ // want is what the scenario waits for the server to hold; with
+ // link, saved while the link loads; with retried, a refused
+ // save tried again will do instead.
"held": []map[string]any{
- {"name": "large", "docs": large, "typing": map[string]string{"text": largeText(), "held": heldNavigation}},
- {"name": "prose", "docs": prose, "typing": map[string]string{"text": proseText(), "held": heldNavigation}},
+ {"name": "large", "docs": large, "typing": map[string]string{"text": largeText(), "held": heldNavigation}, "want": largeText()[:64], "retried": true},
+ {"name": "prose", "docs": prose, "typing": map[string]string{"text": proseText(), "held": heldNavigation}, "want": "Prosepaste", "link": true},
},
}))
out, err := cmd.CombinedOutput()
- t.Logf("%s", out)
+ logHarness(t, string(out))
if err != nil {
t.Fatalf("saving.mjs: %v", err)
}
results := savingResults(t, string(out))
for _, e := range engines {
t.Run(e, func(t *testing.T) { s.check(t, docs[e], results[e]) })
- // Closed with a large save on the wire and more typed behind
- // it: the more must arrive by the unload beacon. Keepalive
- // saves and beacons share the browser's 64KiB, so a beacon
- // repeating the save on the wire was refused, and so was its
- // keepalive fallback (Claude Fable on #94).
+ // The same, closed as a person closes a tab, at once after the
+ // last word: the unload handlers run, so the beacon carries
+ // what the queue has not sent yet. Playwright's page.close()
+ // skips them, which the held-link case above keeps as the
+ // harsher close (Claude Fable on #94, round 3).
+ t.Run(e+"/closed", func(t *testing.T) {
+ r := s.result(t, closed[e], results[e+"-closed"])
+ s.contains(t, closed[e], savingText)
+ s.calm(t, r)
+ })
// An edit too large for a keepalive save, even compressed, is
// refused by WebKit until the link is answered: the page waits
// quietly and retries, because no request has failed. "Trouble
// saving" said otherwise (Claude Fable on #94).
- t.Run(e+"/large", func(t *testing.T) { s.calm(t, results[e+"-large"]) })
+ t.Run(e+"/large", func(t *testing.T) { s.calm(t, s.result(t, large[e], results[e+"-large"])) })
// A gzipped save meets a server that does not gunzip it: here a
// hop strips Content-Encoding, and updatesPost reads the
// compressed bytes as the update and refuses them, as main
// does, and as a rollback would. The save is sent again as it
// is, and nothing is dropped (Claude Fable on #94, round 2).
t.Run(e+"/stripped", func(t *testing.T) {
+ r := s.result(t, stripped[e], results[e+"-stripped"])
s.contains(t, stripped[e], "Strippedpaste Smallafter")
- s.calm(t, results[e+"-stripped"])
+ s.calm(t, r)
})
// A paste of 64KB of prose, twice what a keepalive save may
// carry, goes gzipped and fits: saved while the link loads.
t.Run(e+"/prose", func(t *testing.T) {
+ r := s.result(t, prose[e], results[e+"-prose"])
s.mu.Lock()
held := s.held[prose[e]]
s.mu.Unlock()
@@ -218,12 +282,19 @@ func TestSavingContinuesWhileALinkIsLoading(t *testing.T) {
t.Error("the paste did not reach the server while the link was loading")
}
s.contains(t, prose[e], "Prosepaste")
- s.calm(t, results[e+"-prose"])
+ s.calm(t, r)
})
+ // Closed with a large save on the wire and more typed behind
+ // it: the more must arrive by the unload beacon. Keepalive
+ // saves and beacons share the browser's 64KiB, so a beacon
+ // repeating the save on the wire was refused, and so was its
+ // keepalive fallback (Claude Fable on #94).
t.Run(e+"/closing", func(t *testing.T) {
- if !strings.Contains(string(out), `SAVING CLOSED {"engine":"`+e+`"}`) {
+ if results[e+"-closing"] == nil {
+ s.explain(t, closing[e], nil)
t.Fatal("the harness never closed the page")
}
+ s.result(t, closing[e], results[e+"-closing"])
// The beacon, while the large save is still held: the
// queued text arrives by itself. Without it the old page,
// which outlives the hold, sends the text once the large
@@ -253,7 +324,7 @@ func TestSavingContinuesWhileALinkIsLoading(t *testing.T) {
}
t.Run("held-link", func(t *testing.T) {
doc := s.document(t, "wkwebview")
- out := runSavingHarness(t, bin, s.config(t, map[string]any{"doc": doc, "scenario": "held-link"}))
+ out := runSavingHarness(t, bin, s.config(t, map[string]any{"doc": doc, "scenario": "held-link", "want": savingText}))
s.check(t, doc, savingResults(t, out)["wkwebview"])
})
// The page leaves with a save on the wire, the server answers it
@@ -265,12 +336,13 @@ func TestSavingContinuesWhileALinkIsLoading(t *testing.T) {
t.Run("back", func(t *testing.T) {
doc := s.document(t, "wkwebview back")
s.slow(doc)
- out := runSavingHarness(t, bin, s.config(t, map[string]any{"doc": doc, "scenario": "back"}))
+ out := runSavingHarness(t, bin, s.config(t, map[string]any{"doc": doc, "scenario": "back", "want": "Before leaving After coming back"}))
+ r := s.result(t, doc, savingResults(t, out)["wkwebview-back"])
if !strings.Contains(out, `"persisted":true`) {
t.Fatal("the page was not shown again from the back/forward cache, so this check saw nothing")
}
s.contains(t, doc, "After coming back")
- s.calm(t, savingResults(t, out)["wkwebview-back"])
+ s.calm(t, r)
})
// Back at once, with a large paste still on the wire: the resend
// may be refused while that save and the unload beacon hold
@@ -280,12 +352,13 @@ func TestSavingContinuesWhileALinkIsLoading(t *testing.T) {
doc := s.document(t, "wkwebview back quick")
s.holdLarge(doc)
big := closingTyping()["big"]
- out := runSavingHarness(t, bin, s.config(t, map[string]any{"doc": doc, "scenario": "back", "before": big, "awayMs": 300}))
+ out := runSavingHarness(t, bin, s.config(t, map[string]any{"doc": doc, "scenario": "back", "before": big, "awayMs": 300, "want": "Bigpaste After coming back"}))
+ r := s.result(t, doc, savingResults(t, out)["wkwebview-back"])
if !strings.Contains(out, `"persisted":true`) {
t.Fatal("the page was not shown again from the back/forward cache, so this check saw nothing")
}
s.contains(t, doc, "Bigpaste After coming back")
- s.calm(t, savingResults(t, out)["wkwebview-back"])
+ s.calm(t, r)
})
})
}
@@ -295,7 +368,7 @@ func runSavingHarness(t *testing.T, bin, config string) string {
cmd := exec.Command(bin)
cmd.Env = append(os.Environ(), "DOCS_SAVING_CONFIG="+config)
out, err := cmd.CombinedOutput()
- t.Logf("%s", out)
+ logHarness(t, string(out))
if err != nil {
t.Fatalf("saving-webkit: %v", err)
}
@@ -304,6 +377,10 @@ func runSavingHarness(t *testing.T, bin, config string) string {
const savingText = "Typed while loading"
+// savingStatePath, followed by a document's sqid, is the server's view of
+// it as JSON (savingView): what the harnesses wait on.
+const savingStatePath = "/test/saving-state/"
+
type savingServer struct {
app *docs.App
served http.Handler
@@ -327,6 +404,31 @@ type savingServer struct {
// duringLarge counts the saves answered 2xx meanwhile.
holdingLarge map[string]bool
duringLarge map[string]int
+ // posts are, per document, the saves that reached the server, in the
+ // order they did.
+ posts map[string][]*savingPost
+}
+
+// savingPost is one save as the server saw it.
+type savingPost struct {
+ At int64 `json:"at"` // arrived, Unix ms
+ Bytes int64 `json:"bytes"`
+ Encoding string `json:"encoding,omitempty"` // as sent, before any stripping
+ Type string `json:"type,omitempty"`
+ Status int `json:"status"` // 0 until answered
+ Took int64 `json:"took"` // ms from arrival to answer
+ Link bool `json:"link,omitempty"` // answered while the held link was loading
+ Large bool `json:"large,omitempty"` // the large save the server held
+}
+
+// savingView is what the server holds for a document, and how its saves
+// went.
+type savingView struct {
+ Text string `json:"text"`
+ Held int `json:"held"`
+ DuringLarge int `json:"duringLarge"`
+ LargeHeld bool `json:"largeHeld"` // a large save awaited, or held now
+ Posts []savingPost `json:"posts"`
}
// strip makes sqid's saves lose their Content-Encoding on the way in, as
@@ -355,7 +457,7 @@ func (s *savingServer) slow(sqid string) {
func newSavingServer(t *testing.T) *savingServer {
t.Helper()
server := httptest.NewUnstartedServer(nil)
- s := &savingServer{origin: "http://" + server.Listener.Addr().String(), held: map[string]int{}, slowed: map[string]bool{}, heldLarge: map[string]bool{}, holdingLarge: map[string]bool{}, duringLarge: map[string]int{}, stripped: map[string]bool{}}
+ s := &savingServer{origin: "http://" + server.Listener.Addr().String(), held: map[string]int{}, slowed: map[string]bool{}, heldLarge: map[string]bool{}, holdingLarge: map[string]bool{}, duringLarge: map[string]int{}, stripped: map[string]bool{}, posts: map[string][]*savingPost{}}
app, err := docs.NewForTestWith(t, docs.Config{Origin: s.origin})
if err != nil {
t.Fatal(err)
@@ -375,9 +477,16 @@ func newSavingServer(t *testing.T) *savingServer {
<-r.Context().Done()
return
}
+ if sqid, ok := strings.CutPrefix(r.URL.Path, savingStatePath); ok && r.Method == http.MethodGet {
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(s.view(sqid))
+ return
+ }
if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/updates") {
s.mu.Lock()
sqid := strings.Split(r.URL.Path, "/")[2]
+ post := &savingPost{At: time.Now().UnixMilli(), Bytes: r.ContentLength, Encoding: r.Header.Get("Content-Encoding"), Type: r.Header.Get("Content-Type")}
+ s.posts[sqid] = append(s.posts[sqid], post)
slow, large := s.slowed[sqid], s.heldLarge[sqid] && r.ContentLength > 16*1024
if s.stripped[sqid] {
r.Header.Del("Content-Encoding")
@@ -406,6 +515,7 @@ func newSavingServer(t *testing.T) *savingServer {
if rec.code/100 == 2 && !large && s.holdingLarge[sqid] {
s.duringLarge[sqid]++
}
+ post.Status, post.Took, post.Link, post.Large = rec.code, time.Now().UnixMilli()-post.At, during, large
s.mu.Unlock()
return
}
@@ -437,7 +547,10 @@ func (s *savingServer) config(t *testing.T, extra map[string]any) string {
"cookies": s.cookies,
"script": savingScript,
"typing": map[string]string{"text": savingText, "held": heldNavigation},
+ "want": savingText,
"type": typeScript,
+ "trace": traceScript,
+ "state": savingStatePath,
}
for k, v := range extra {
config[k] = v
@@ -449,14 +562,56 @@ func (s *savingServer) config(t *testing.T, extra map[string]any) string {
return string(b)
}
+// text is the server's document, as Markdown.
+func (s *savingServer) text(sqid string) (string, error) {
+ req := httptest.NewRequest(http.MethodGet, "/d/"+sqid+"/export.md", nil)
+ for _, c := range s.cookies {
+ req.AddCookie(c)
+ }
+ rec := httptest.NewRecorder()
+ s.served.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ return "", fmt.Errorf("export.md: %d %s", rec.Code, rec.Body.String())
+ }
+ return rec.Body.String(), nil
+}
+
+// view is the server's side of sqid: its text, and every save that
+// reached it.
+func (s *savingServer) view(sqid string) savingView {
+ text, err := s.text(sqid)
+ if err != nil {
+ text = err.Error()
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ v := savingView{Text: text, Held: s.held[sqid], DuringLarge: s.duringLarge[sqid], LargeHeld: s.heldLarge[sqid] || s.holdingLarge[sqid], Posts: []savingPost{}}
+ for _, p := range s.posts[sqid] {
+ v.Posts = append(v.Posts, *p)
+ }
+ return v
+}
+
+// result is a scenario's harness report, which must exist and must have
+// got what it waited for; should the scenario fail, its story is printed.
+func (s *savingServer) result(t *testing.T, sqid string, r *savingResult) *savingResult {
+ t.Helper()
+ s.explain(t, sqid, r)
+ if r == nil {
+ t.Fatal("the harness reported nothing for this scenario")
+ }
+ if !r.Settled {
+ t.Errorf("the harness gave up after %d ms waiting for %s", r.Ms, r.Waiting)
+ }
+ return r
+}
+
// check is the held-link scenario's verdict: saves reached the server
// while the link was loading, the words are in the server's document, and
// the page never said a save had failed.
-func (s *savingServer) check(t *testing.T, sqid string, states []string) {
+func (s *savingServer) check(t *testing.T, sqid string, r *savingResult) {
t.Helper()
- if states == nil {
- t.Fatal("the harness reported nothing for this engine")
- }
+ s.result(t, sqid, r)
s.mu.Lock()
held := s.held[sqid]
s.mu.Unlock()
@@ -464,68 +619,232 @@ func (s *savingServer) check(t *testing.T, sqid string, states []string) {
t.Error("no save reached the server while the link was loading: the editor stopped saving")
}
s.contains(t, sqid, savingText)
- s.calm(t, states)
+ s.calm(t, r)
}
// contains reads the document back from the server and checks every
// word of text is in it.
func (s *savingServer) contains(t *testing.T, sqid, text string) {
t.Helper()
- req := httptest.NewRequest(http.MethodGet, "/d/"+sqid+"/export.md", nil)
- for _, c := range s.cookies {
- req.AddCookie(c)
- }
- rec := httptest.NewRecorder()
- s.served.ServeHTTP(rec, req)
- if rec.Code != http.StatusOK {
- t.Fatalf("export.md: %d %s", rec.Code, rec.Body.String())
+ body, err := s.text(sqid)
+ if err != nil {
+ t.Fatal(err)
}
for _, word := range strings.Fields(text) {
- if !strings.Contains(rec.Body.String(), word) {
- t.Errorf("the server's document is missing %q:\n%s", word, rec.Body.String())
+ if !strings.Contains(body, word) {
+ t.Errorf("the server's document is missing %q:\n%s", word, body)
}
}
}
// calm fails if the page ever said a save failed: in these scenarios no
// request does.
-func (s *savingServer) calm(t *testing.T, states []string) {
+func (s *savingServer) calm(t *testing.T, r *savingResult) {
t.Helper()
- if states == nil {
+ if r == nil {
t.Fatal("the harness reported no save states")
}
- for _, st := range states {
+ for _, st := range r.States {
if st == "retrying" || st == "failed" {
- t.Errorf("the page said %q while no request had failed (states %v)", st, states)
+ t.Errorf("the page said %q while no request had failed (states %v)", st, r.States)
break
}
}
}
-// savingResults reads each "SAVING RESULT {engine, states}" line.
-func savingResults(t *testing.T, out string) map[string][]string {
+// explain prints, should t fail, what the page sent and what the server
+// made of it, on one clock: the page's requests (traceScript) and every
+// save that reached the server, how each was answered, and the text the
+// server holds. So a failure says whether the saves never left the page,
+// left and were refused, or are still waiting for an answer.
+func (s *savingServer) explain(t *testing.T, sqid string, r *savingResult) {
+ t.Cleanup(func() {
+ if !t.Failed() {
+ return
+ }
+ v := s.view(sqid)
+ var base int64
+ for _, at := range []int64{firstAt(r), firstPost(v)} {
+ if at != 0 && (base == 0 || at < base) {
+ base = at
+ }
+ }
+ var b strings.Builder
+ if r != nil {
+ fmt.Fprintf(&b, "The harness waited %d ms for %s (got it: %v); the save line showed %v.\n", r.Ms, r.Waiting, r.Settled, r.States)
+ }
+ b.WriteString("What the page sent (ms from the first request either side saw):\n")
+ if r == nil || len(r.Trace) == 0 {
+ b.WriteString(" nothing recorded\n")
+ } else {
+ // A page refused four times a second makes hundreds: the start
+ // and the end say what happened.
+ for i, e := range r.Trace {
+ if n := len(r.Trace); n > 60 && i >= 40 && i < n-20 {
+ if i == 40 {
+ fmt.Fprintf(&b, " … %d more\n", n-60)
+ }
+ continue
+ }
+ fmt.Fprintf(&b, " %s\n", e.line(base))
+ }
+ }
+ b.WriteString("What reached the server:\n")
+ if len(v.Posts) == 0 {
+ b.WriteString(" no save\n")
+ }
+ for _, p := range v.Posts {
+ fmt.Fprintf(&b, " %s\n", p.line(base))
+ }
+ fmt.Fprintf(&b, "Saves answered 2xx while the link loaded: %d; while the large save was held: %d.\n", v.Held, v.DuringLarge)
+ text := v.Text
+ if len(text) > 800 {
+ text = text[:800] + fmt.Sprintf("… (%d bytes in all)", len(v.Text))
+ }
+ fmt.Fprintf(&b, "What the server holds:\n%s", text)
+ t.Logf("%s", b.String())
+ })
+}
+
+func firstAt(r *savingResult) int64 {
+ if r == nil || len(r.Trace) == 0 {
+ return 0
+ }
+ return r.Trace[0].At
+}
+
+func firstPost(v savingView) int64 {
+ if len(v.Posts) == 0 {
+ return 0
+ }
+ return v.Posts[0].At
+}
+
+func (p savingPost) line(base int64) string {
+ enc := p.Encoding
+ if enc == "" {
+ enc = "identity"
+ }
+ what := fmt.Sprintf("+%d ms POST %d B %s %s", p.At-base, p.Bytes, enc, p.Type)
+ if p.Large {
+ what += ", the large save, held 3 s"
+ }
+ if p.Status == 0 {
+ return what + ": not answered yet"
+ }
+ what += fmt.Sprintf(": answered %d after %d ms", p.Status, p.Took)
+ if p.Link {
+ what += ", with the link loading"
+ }
+ return what
+}
+
+// savingTrace is one entry of traceScript's record.
+type savingTrace struct {
+ ID int `json:"id"`
+ At int64 `json:"at"`
+ Event string `json:"ev"`
+ Method string `json:"m"`
+ URL string `json:"u"`
+ Keep bool `json:"ka"`
+ Encoding string `json:"enc"`
+ Size int `json:"size"`
+ Status int `json:"status"`
+ Err string `json:"err"`
+ OK bool `json:"ok"`
+}
+
+func (e savingTrace) line(base int64) string {
+ at := fmt.Sprintf("+%d ms #%d", e.At-base, e.ID)
+ switch e.Event {
+ case "start":
+ how := "fetch"
+ if e.Keep {
+ how = "keepalive fetch"
+ }
+ if e.Encoding != "" {
+ how += " " + e.Encoding
+ }
+ return fmt.Sprintf("%s %s %s %s, %d B", at, how, e.Method, e.URL, e.Size)
+ case "answer":
+ return fmt.Sprintf("%s answered %d", at, e.Status)
+ case "refused":
+ return fmt.Sprintf("%s refused: %s", at, e.Err)
+ case "beacon":
+ ok := "queued"
+ if !e.OK {
+ ok = "refused"
+ }
+ return fmt.Sprintf("%s beacon %s %s, %d B: %s", at, e.Method, e.URL, e.Size, ok)
+ }
+ return fmt.Sprintf("%s %s", at, e.Event)
+}
+
+// savingResult is one "SAVING RESULT" line: the save states the page
+// showed, and whether what the scenario waited for came, and when; with
+// the page's requests from its "SAVING TRACE" line.
+type savingResult struct {
+ Engine string `json:"engine"`
+ States []string `json:"states"`
+ Settled bool `json:"settled"`
+ Ms int `json:"ms"`
+ Waiting string `json:"waiting"`
+ Trace []savingTrace
+}
+
+// savingResults reads each "SAVING RESULT {engine, states, ...}" line, and
+// the "SAVING TRACE {engine, trace}" line beside it.
+func savingResults(t *testing.T, out string) map[string]*savingResult {
t.Helper()
- results := map[string][]string{}
+ results := map[string]*savingResult{}
+ traces := map[string][]savingTrace{}
for _, line := range strings.Split(out, "\n") {
- rest, ok := strings.CutPrefix(strings.TrimSpace(line), "SAVING RESULT ")
- if !ok {
+ line = strings.TrimSpace(line)
+ if rest, ok := strings.CutPrefix(line, "SAVING TRACE "); ok {
+ var tr struct {
+ Engine string `json:"engine"`
+ Trace []savingTrace `json:"trace"`
+ }
+ if err := json.Unmarshal([]byte(rest), &tr); err != nil {
+ t.Fatalf("%q: %v", line, err)
+ }
+ traces[tr.Engine] = tr.Trace
continue
}
- var r struct {
- Engine string `json:"engine"`
- States []string `json:"states"`
+ rest, ok := strings.CutPrefix(line, "SAVING RESULT ")
+ if !ok {
+ continue
}
+ var r savingResult
if err := json.Unmarshal([]byte(rest), &r); err != nil {
t.Fatalf("%q: %v", line, err)
}
if r.States == nil {
r.States = []string{}
}
- results[r.Engine] = r.States
+ results[r.Engine] = &r
+ }
+ for engine, tr := range traces {
+ if r := results[engine]; r != nil {
+ r.Trace = tr
+ }
}
return results
}
+// logHarness logs a harness's output, less the request traces: those are
+// printed only for a scenario that fails (explain).
+func logHarness(t *testing.T, out string) {
+ t.Helper()
+ var keep []string
+ for _, line := range strings.Split(out, "\n") {
+ if !strings.HasPrefix(strings.TrimSpace(line), "SAVING TRACE ") {
+ keep = append(keep, line)
+ }
+ }
+ t.Logf("%s", strings.Join(keep, "\n"))
+}
+
type statusRecorder struct {
http.ResponseWriter
code int