oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

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