oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/engines/saving.mjs — a document keeps saving while a link it
2// opened is still loading, in Chromium and in WebKit.
3//
4// WebKit refuses every ordinary fetch() and XMLHttpRequest a page starts
5// while its main frame has a navigation waiting for an answer: the promise
6// rejects at once with "TypeError: Load failed" and nothing leaves the
7// browser. A navigation that is never answered, or answered with a
8// download, leaves the page on screen and editable the whole time. Before
9// the fix, every save the editor tried in that state was refused that way,
10// so it said "Trouble saving. Retrying…" and retried four times a second
11// with requests the server never saw (Paul, Safari, 2026-10-26: the edge
12// logged no POSTs at all, and a reload cleared it).
13//
14// Run by internal/docs/saving_browser_test.go, which serves the link's
15// target and holds it unanswered, counts the saves that reach it while it
16// does, and reads the document back from the server afterwards. This
17// prints, per scenario, one "SAVING RESULT" line with the save states the
18// page showed and whether what the scenario waited for came, and one
19// "SAVING TRACE" line with the page's requests (the config's trace
20// script), which the test prints if the scenario fails.
21//
22// Nothing here waits a fixed time to decide anything. Each scenario
23// watches the page at least as long as it used to (WATCH_MS), then until
24// the server's view of the document (config.state) holds what it waits
25// for, for at most CEILING_MS. A fixed three seconds could not tell a slow
26// pass from a stall (Claude Fable on #94, round 3).
27
28const { chromium, webkit } = await import('playwright')
29
30const config = JSON.parse(process.env.DOCS_SAVING_CONFIG)
31const pause = (ms) => new Promise((r) => setTimeout(r, ms))
32
33// WATCH_MS is how long a scenario watches the save line at least: the
34// fixed pause it replaces, so no state it could see is missed now.
35// CEILING_MS is how long it waits for the server at most.
36const WATCH_MS = 3000
37const CEILING_MS = 20000
38
39// view is the test server's side of a document: its text, and every save
40// that reached it. Asked from here, not from the page, which is the one
41// whose requests are being refused.
42// A poll that fails is "not yet", as in the WKWebView harness: throwing
43// here would end every scenario left, with nothing explained, at the one
44// time the explanation is wanted (Claude Fable on Docs #98).
45const view = async (sqid) => {
46 try {
47 const r = await fetch(config.origin + config.state + sqid)
48 return r.ok ? await r.json() : null
49 } catch {
50 return null
51 }
52}
53
54const holds = (text, want) => want.split(/\s+/).every((w) => text.includes(w))
55
56// retried is whether the page tried a save again after one was refused:
57// the moment it decides whether to say "Trouble saving".
58const retried = (trace) => {
59 const refused = new Set(trace.filter((e) => e.ev === 'refused').map((e) => e.id))
60 const posts = trace.filter((e) => e.ev === 'start' && e.m === 'POST' && e.u.endsWith('/updates'))
61 return posts.some((p, i) => refused.has(p.id) && i < posts.length - 1)
62}
63
64// settle waits for done(view) from since, at least watchMs and at most
65// CEILING_MS, and says whether it came and when.
66async function settle (sqid, since, watchMs, done) {
67 for (;;) {
68 const ms = Date.now() - since
69 const v = ms >= watchMs ? await view(sqid) : null
70 if (v && done(v)) {
71 // The page's console lines from just before are still on their way.
72 await pause(250)
73 return { settled: true, ms }
74 }
75 if (ms >= CEILING_MS) return { settled: false, ms }
76 await pause(100)
77 }
78}
79
80// open is a document's page, ready to type in, with its save states and
81// requests read from its console from the start: Playwright's own
82// evaluate waits for a pending navigation to finish, and the held link
83// never does.
84async function open (context, sqid) {
85 const page = await context.newPage()
86 const seen = { states: [], trace: [], typed: false }
87 page.on('console', (m) => {
88 const t = m.text()
89 if (t.startsWith('SAVE-STATE ')) seen.states.push(t.slice('SAVE-STATE '.length))
90 else if (t.startsWith('SAVE-TRACE ')) seen.trace.push(JSON.parse(t.slice('SAVE-TRACE '.length)))
91 else if (t === 'SAVE-TYPED') seen.typed = true
92 })
93 // A real close asks first only while a resync holds the page; yes.
94 page.on('dialog', (d) => d.accept().catch(() => {}))
95 await page.goto(config.origin + '/d/' + sqid)
96 await page.waitForSelector('html[data-docs-fonts="shown"] [docs-text][contenteditable="true"]', { timeout: 30000 })
97 await pause(500)
98 return { page, seen }
99}
100
101const report = (engine, seen, got, waiting) => {
102 console.log('SAVING RESULT ' + JSON.stringify({ engine, states: seen.states, settled: got.settled, ms: got.ms, waiting }))
103 console.log('SAVING TRACE ' + JSON.stringify({ engine, trace: seen.trace }))
104}
105
106// heldScenario types into a document with the held link loading, and
107// waits for the server to hold want: saved while the link loads, given
108// link, or, given orRetried, a refused save tried again will do.
109async function heldScenario (context, engine, sqid, typing, { want, link, orRetried }) {
110 const { page, seen } = await open(context, sqid)
111 const since = Date.now()
112 await page.evaluate(`(${config.script})(${JSON.stringify(typing)})`)
113 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' : '')
114 const got = await settle(sqid, since, WATCH_MS, (v) => (holds(v.text, want) && (!link || v.held > 0)) || (orRetried && retried(seen.trace)))
115 report(engine, seen, got, waiting)
116 // Each page done with is closed, and its held link and stream with it:
117 // left open they take the host's connections (six, on HTTP/1.1), and a
118 // later page's unload beacon queues behind them. Playwright's close
119 // skips the unload handlers, so this is harsher than a tab closing:
120 // what the scenario waited for has to have been saved already.
121 await page.close()
122}
123
124for (const [engineName, engine] of Object.entries({ chromium, webkit }).filter(([n]) => !process.env.DOCS_ENGINES_ENGINE || n === process.env.DOCS_ENGINES_ENGINE)) {
125 const browser = await engine.launch({ headless: true })
126 try {
127 const context = await browser.newContext()
128 await context.addCookies(config.cookies.map((c) => ({ name: c.Name, value: c.Value, url: config.origin, httpOnly: c.HttpOnly, sameSite: 'Lax' })))
129 await context.addInitScript(config.trace)
130
131 // Three words typed while the link loads: saved while it does.
132 await heldScenario(context, engineName, config.docs[engineName], config.typing, { want: config.want, link: true })
133
134 // The same, closed the way a person closes a tab, as soon as the last
135 // word is in: the unload handlers run, and the beacon carries what the
136 // queue has not yet sent.
137 if (config.closed) {
138 const sqid = config.closed[engineName]
139 const { page, seen } = await open(context, sqid)
140 const since = Date.now()
141 await page.evaluate(`(${config.script})(${JSON.stringify(config.typing)})`)
142 const until = Date.now() + CEILING_MS
143 while (!seen.typed && Date.now() < until) await pause(25)
144 const gone = new Promise((resolve) => page.once('close', resolve))
145 await page.close({ runBeforeUnload: true })
146 await Promise.race([gone, pause(CEILING_MS)])
147 const got = await settle(sqid, since, 0, (v) => holds(v.text, config.want))
148 report(engineName + '-closed', seen, got, `the server to hold ${JSON.stringify(config.want)} after the tab closed`)
149 }
150
151 // The same with other edits (config.held: [{ name, docs, typing, want,
152 // link, retried }]): a large paste of prose, which goes keepalive once
153 // gzipped, and one too large for a keepalive save even compressed,
154 // which WebKit refuses until the link is answered. Nothing is lost, and
155 // the page must not say a save failed, because none did.
156 for (const held of config.held || []) {
157 await heldScenario(context, engineName + '-' + held.name, held.docs[engineName], held.typing, { want: held.want, link: !!held.link, orRetried: !!held.retried })
158 }
159
160 // Typed with no link loading (config.typed: [{ name, docs, text }]):
161 // the server's side is the case, such as a hop that strips a gzipped
162 // save's Content-Encoding. Each text is saved before the next is typed.
163 for (const typed of config.typed || []) {
164 const sqid = typed.docs[engineName]
165 const { page, seen } = await open(context, sqid)
166 await page.evaluate(`(() => { const line = document.querySelector('[estilo-save-status~="floating"]'); new MutationObserver(() => console.log('SAVE-STATE ' + line.getAttribute('data-state'))).observe(line, { attributes: true, attributeFilter: ['data-state'] }) })()`)
167 const got = { settled: true, ms: 0 }
168 let waiting = ''
169 for (const text of typed.text) {
170 const since = Date.now()
171 await page.evaluate(`(${config.type})(${JSON.stringify(text)})`)
172 const one = await settle(sqid, since, 1500, (v) => holds(v.text, text))
173 got.ms += one.ms
174 if (!one.settled) {
175 got.settled = false
176 waiting = `the server to hold ${JSON.stringify(text.slice(0, 40))}`
177 break
178 }
179 }
180 report(engineName + '-' + typed.name, seen, got, waiting || 'the server to hold each text')
181 await page.close()
182 }
183
184 // Closing with a large save on the wire: the server holds it, the page
185 // types more behind it and leaves before that is sent, and the unload
186 // beacon must carry what was typed. Keepalive requests and beacons
187 // share one 64KiB quota, so a beacon that repeats the save already on
188 // the wire is refused (Claude Fable on #94). Done once the large save
189 // has been answered and the server holds both.
190 if (config.closing) {
191 const sqid = config.closing[engineName]
192 const { page, seen } = await open(context, sqid)
193 const since = Date.now()
194 await page.evaluate(`(${config.closingScript})(${JSON.stringify(config.closingTyping)})`)
195 await page.waitForURL(config.origin + '/healthz', { timeout: 30000 })
196 const got = await settle(sqid, since, 0, (v) => !v.largeHeld && holds(v.text, 'Bigpaste Queuedbehind'))
197 report(engineName + '-closing', seen, got, 'the large save to be answered and the server to hold "Bigpaste Queuedbehind"')
198 }
199 } finally {
200 await browser.close()
201 }
202}
203