| 1 | // fixtures/engines/replay.mjs — a paste that waited for its font is kept |
| 2 | // across a resync, in Chromium and in WebKit, through the real editor |
| 3 | // (Claude Fable's eleven replay cases on #27/#88, pm-replay-probe.mjs, made |
| 4 | // into the editor's own keys and clipboard). |
| 5 | // |
| 6 | // Run by internal/docs/replay_engines_browser_test.go with the same |
| 7 | // DOCS_ENGINES_CONFIG as first-reveal.mjs; docs.replay holds a fresh |
| 8 | // document per engine and case (fixtures/vectors/fragment/simple.bin: |
| 9 | // "First paragraph." / "Second paragraph."). Slides has the same script |
| 10 | // (oficina/slides fixtures/engines/replay.mjs). |
| 11 | // |
| 12 | // Each case: the editor's first save is answered 413 (the refused change, |
| 13 | // made with real keys); at once a paste with code in it is made, which |
| 14 | // waits for the code face (held 1.5 s); a colleague's words reach the |
| 15 | // server meanwhile in (j) and (k), through a second editor, while the |
| 16 | // rebuild's fetch is held. Afterwards the page must hold the paste once, in |
| 17 | // the shape the case wants, and the pasted words must never have left the |
| 18 | // page once there — no DOM change and no frame without them. A line |
| 19 | // RESULT {...} per case carries what the Go test checks on the server. |
| 20 | |
| 21 | const { chromium, webkit } = await import('playwright') |
| 22 | |
| 23 | const config = JSON.parse(process.env.DOCS_ENGINES_CONFIG) |
| 24 | const pause = (ms) => new Promise((r) => setTimeout(r, ms)) |
| 25 | const PASTE = '<p>REVIEW_RESYNC_PASTE <code>codeword</code></p>' |
| 26 | const TWO = '<p>ONE <code>c1</code></p><p>TWO</p>' |
| 27 | const KEPT = ['First paragraph.', 'Second paragraph.REVIEW_RESYNC_PASTE codeword'] |
| 28 | |
| 29 | // Each step is [what, ...args] run in the page (see act below). |
| 30 | const cases = [ |
| 31 | { name: '(a) the paste right after the refused x (Fable\'s probe)', refuse: [['type', 1, 'end', 'x']], paste: [['caret', 1, 'end']], want: KEPT }, |
| 32 | { name: '(b) the refused x elsewhere, before the paste', refuse: [['type', 0, 'end', 'x']], paste: [['caret', 1, 'end']], want: KEPT }, |
| 33 | { name: '(g) the refused x after the paste point', refuse: [['type', 1, 'end', 'x']], paste: [['caret', 0, 'end']], want: ['First paragraph.REVIEW_RESYNC_PASTE codeword', 'Second paragraph.'] }, |
| 34 | { name: '(c) two refused x, the paste after the second', refuse: [['type', 0, 'end', 'x'], ['type', 1, 'end', 'x']], paste: [['caret', 1, 'end']], want: KEPT }, |
| 35 | { name: '(i) the refused x mid-paragraph, the paste at its end', refuse: [['type', 1, 7, 'x']], paste: [['caret', 1, 'end']], want: KEPT }, |
| 36 | { name: '(d) the paste inside a paragraph the refused Enter made', refuse: [['press', 1, 'end', 'Enter']], paste: [['caret', 2, 0]], want: ['First paragraph.', 'Second paragraph.'], lost: true }, |
| 37 | { name: '(e) the paste over "paragraph.x"', refuse: [['type', 1, 'end', 'x']], paste: [['select', 1, 7, 'end']], want: ['First paragraph.', 'Second REVIEW_RESYNC_PASTE codeword'] }, |
| 38 | { name: '(f) a refused deletion elsewhere', refuse: [['select', 0, 6, 15], ['key', 'Backspace']], paste: [['caret', 1, 'end']], want: KEPT }, |
| 39 | { name: '(h) two paragraphs pasted after the refused x', refuse: [['type', 1, 'end', 'x']], paste: [['caret', 1, 'end']], html: TWO, words: 'ONE', want: ['First paragraph.', 'Second paragraph.ONE c1', 'TWO'] }, |
| 40 | { name: '(j) a colleague\'s words before, the refused x after', refuse: [['type', 1, 'end', 'x']], paste: [['caret', 1, 'end']], colleague: [0, ' More from a colleague.'], want: ['First paragraph. More from a colleague.', 'Second paragraph.REVIEW_RESYNC_PASTE codeword'] }, |
| 41 | { name: '(k) a colleague appended where the x was refused', refuse: [['type', 1, 'end', 'x']], paste: [['caret', 1, 'end']], colleague: [1, ' Colleague.'], want: ['First paragraph.', 'Second paragraph. Colleague.REVIEW_RESYNC_PASTE codeword'] }, |
| 42 | ] |
| 43 | |
| 44 | // In the page: the first save refused, the rebuild's fetch held while |
| 45 | // window.__hold is set, and a log of whether the pasted words are on the |
| 46 | // stage at every DOM change and every frame. |
| 47 | const instrument = (words) => { |
| 48 | const f = window.fetch |
| 49 | window.__posts = [] |
| 50 | window.__errors = [] |
| 51 | addEventListener('error', (e) => window.__errors.push(String(e.message))) |
| 52 | addEventListener('unhandledrejection', (e) => window.__errors.push(String(e.reason))) |
| 53 | window.__inflight = 0 |
| 54 | window.__lastPost = performance.now() |
| 55 | window.__release = () => { window.__hold = false; window.__lastPost = performance.now(); if (window.__go) window.__go() } |
| 56 | window.fetch = async function (u, o) { |
| 57 | const post = String(u).endsWith('/updates') && o && o.method === 'POST' |
| 58 | if (post && !window.refused) { |
| 59 | await new Promise((r) => setTimeout(r, 150)) |
| 60 | window.refused = true |
| 61 | window.__posts.push(413) |
| 62 | return new Response('', { status: 413 }) |
| 63 | } |
| 64 | // The rebuild's fetch of the whole log (the live cursor's carries since=). |
| 65 | if (window.refused && !post && String(u).includes('/updates') && !String(u).includes('since=') && window.__hold) await new Promise((r) => { window.__go = r }) |
| 66 | if (post) { window.__inflight++; window.__lastPost = performance.now() } |
| 67 | try { |
| 68 | const r = await f.call(this, u, o) |
| 69 | if (post) window.__posts.push(r.status) |
| 70 | return r |
| 71 | } finally { |
| 72 | if (post) { window.__inflight--; window.__lastPost = performance.now() } |
| 73 | } |
| 74 | } |
| 75 | window.__log = [] |
| 76 | const stage = document.querySelector('[docs-text]') |
| 77 | const rec = (how) => { |
| 78 | const has = stage.textContent.includes(words) |
| 79 | const last = window.__log[window.__log.length - 1] |
| 80 | if (!last || last.has !== has) window.__log.push({ ms: Math.round(performance.now()), has, how }) |
| 81 | } |
| 82 | new MutationObserver(() => rec('dom')).observe(stage, { subtree: true, childList: true, characterData: true }) |
| 83 | const frame = () => { rec('frame'); requestAnimationFrame(frame) } |
| 84 | requestAnimationFrame(frame) |
| 85 | } |
| 86 | |
| 87 | // place puts the DOM selection in paragraph i of the text block: a caret at |
| 88 | // offset (a number or 'end'), or a range from a to b. |
| 89 | const place = ([i, a, b]) => { |
| 90 | const ps = document.querySelectorAll('[docs-text] p') |
| 91 | const p = ps[i] |
| 92 | const el = document.querySelector('[docs-text]') |
| 93 | el.focus() |
| 94 | const at = (off) => { |
| 95 | const w = document.createTreeWalker(p, NodeFilter.SHOW_TEXT) |
| 96 | let n |
| 97 | let last = null |
| 98 | let left = off === 'end' ? Infinity : off |
| 99 | while ((n = w.nextNode())) { |
| 100 | last = n |
| 101 | if (left <= n.data.length) return [n, left] |
| 102 | left -= n.data.length |
| 103 | } |
| 104 | return last ? [last, last.data.length] : [p, 0] |
| 105 | } |
| 106 | const r = document.createRange() |
| 107 | const [sn, so] = at(a) |
| 108 | r.setStart(sn, so) |
| 109 | if (b !== undefined) { |
| 110 | const [en, eo] = at(b) |
| 111 | r.setEnd(en, eo) |
| 112 | } else r.collapse(true) |
| 113 | getSelection().removeAllRanges() |
| 114 | getSelection().addRange(r) |
| 115 | } |
| 116 | |
| 117 | const paste = (html) => { |
| 118 | const el = document.activeElement |
| 119 | const d = new DataTransfer() |
| 120 | d.setData('text/html', html) |
| 121 | d.setData('text/plain', 'x') |
| 122 | el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })) |
| 123 | } |
| 124 | |
| 125 | // act runs one step. ProseMirror reads a moved caret on the next |
| 126 | // selectionchange, so every move is followed by a moment before the key. |
| 127 | async function act (page, [what, ...args]) { |
| 128 | if (what === 'caret') await page.evaluate(place, [args[0], args[1]]) |
| 129 | else if (what === 'select') await page.evaluate(place, [args[0], args[1], args[2]]) |
| 130 | else if (what === 'type' || what === 'press') { |
| 131 | await page.evaluate(place, [args[0], args[1]]) |
| 132 | await pause(40) |
| 133 | if (what === 'type') await page.keyboard.type(args[2]) |
| 134 | else await page.keyboard.press(args[2]) |
| 135 | return |
| 136 | } else if (what === 'key') { |
| 137 | await page.keyboard.press(args[0]) |
| 138 | return |
| 139 | } |
| 140 | await pause(40) |
| 141 | } |
| 142 | |
| 143 | const paragraphs = () => [...document.querySelectorAll('[docs-text] p')].map((p) => p.textContent) |
| 144 | |
| 145 | async function editor (context, deck) { |
| 146 | const page = await context.newPage() |
| 147 | await page.goto(config.origin + '/d/' + deck) |
| 148 | await page.waitForSelector('html[data-docs-fonts="shown"] [docs-text][contenteditable="true"]', { timeout: 15000 }) |
| 149 | await pause(300) |
| 150 | return page |
| 151 | } |
| 152 | |
| 153 | const failures = [] |
| 154 | for (const [engineName, engine] of Object.entries({ chromium, webkit }).filter(([n]) => !process.env.DOCS_ENGINES_ENGINE || n === process.env.DOCS_ENGINES_ENGINE)) { |
| 155 | const browser = await engine.launch(engineName === 'chromium' ? { headless: true, channel: 'chromium' } : { headless: true }) |
| 156 | for (const c of cases) { |
| 157 | if (process.env.DOCS_REPLAY_CASE && !c.name.startsWith(process.env.DOCS_REPLAY_CASE)) continue |
| 158 | const label = `${engineName}, ${c.name}` |
| 159 | const deck = config.docs.replay.shift() |
| 160 | const context = await browser.newContext({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 1 }) |
| 161 | await context.addCookies([ |
| 162 | ...config.cookies.map((k) => ({ name: k.Name, value: k.Value, url: config.origin, httpOnly: k.HttpOnly, sameSite: 'Lax' })), |
| 163 | { name: 'docs-view', value: 'paged', url: config.origin }, |
| 164 | ]) |
| 165 | // The code face is held until this case's refusal has landed, then |
| 166 | // let go: the paste is still waiting for it when the 413 arrives, and |
| 167 | // runs right after. A fixed hold raced the refusal under load — a |
| 168 | // face that came first put the paste into the refused batch, one that |
| 169 | // came late ran past the paste's own deadline (Claude Fable, #90). |
| 170 | let watched = null |
| 171 | await context.route('**/*', async (route) => { |
| 172 | if (/LiberationMono-/.test(route.request().url())) { |
| 173 | const response = await route.fetch() |
| 174 | const until = Date.now() + 20000 |
| 175 | while (Date.now() < until) { |
| 176 | if (watched && (await watched.evaluate(() => window.refused === true).catch(() => false))) break |
| 177 | await pause(25) |
| 178 | } |
| 179 | await pause(50) |
| 180 | try { await route.fulfill({ response }) } catch {} |
| 181 | return |
| 182 | } |
| 183 | return route.continue() |
| 184 | }) |
| 185 | try { |
| 186 | const page = await editor(context, deck) |
| 187 | watched = page |
| 188 | const words = c.words || 'REVIEW_RESYNC_PASTE' |
| 189 | await page.evaluate(instrument, words) |
| 190 | if (c.colleague) await page.evaluate(() => { window.__hold = true }) |
| 191 | // The refused change, and at once the paste: it is waiting for its |
| 192 | // font when the refusal arrives (the save goes 250 ms after the |
| 193 | // first key and is answered 150 ms later), and runs after it. |
| 194 | for (const step of c.refuse) await act(page, step) |
| 195 | for (const step of c.paste) await act(page, step) |
| 196 | const early = await page.evaluate(() => !!window.refused) |
| 197 | await page.evaluate(paste, c.html || PASTE) |
| 198 | const waited = await page.evaluate(() => document.querySelector('[docs-fonts-status]').getAttribute('data-state') === 'loading') |
| 199 | if (early || !waited) failures.push(`${label}: the paste did not wait for its font across the refusal (${early ? 'refused first' : 'no wait'}), so this proves nothing`) |
| 200 | await page.waitForFunction(() => window.refused === true, null, { timeout: 5000 }) |
| 201 | if (c.colleague) { |
| 202 | const other = await editor(context, deck) |
| 203 | await other.evaluate(() => { |
| 204 | const f = window.fetch |
| 205 | window.__inflight = 0 |
| 206 | window.__saved = 0 |
| 207 | window.__lastPost = performance.now() |
| 208 | window.fetch = async function (u, o) { |
| 209 | const post = String(u).endsWith('/updates') && o && o.method === 'POST' |
| 210 | if (post) window.__inflight++ |
| 211 | try { |
| 212 | const r = await f.call(this, u, o) |
| 213 | if (post && r.ok) window.__saved++ |
| 214 | return r |
| 215 | } finally { |
| 216 | if (post) { window.__inflight--; window.__lastPost = performance.now() } |
| 217 | } |
| 218 | } |
| 219 | }) |
| 220 | await act(other, ['caret', c.colleague[0], 'end']) |
| 221 | await other.keyboard.type(c.colleague[1]) |
| 222 | // Until the colleague's words are saved: a save answered, none on |
| 223 | // the wire, and quiet past the queue's debounce. |
| 224 | await other.waitForFunction(() => window.__saved > 0 && window.__inflight === 0 && performance.now() - window.__lastPost > 600, null, { timeout: 15000 }) |
| 225 | await other.close() |
| 226 | await page.evaluate(() => window.__release()) |
| 227 | } |
| 228 | // Until the page holds what the case wants and its saves are done: |
| 229 | // none on the wire, and quiet for 1.5 s after the release or the |
| 230 | // last save. |
| 231 | await page.waitForFunction((want) => JSON.stringify([...document.querySelectorAll('[docs-text] p')].map((p) => p.textContent)) === JSON.stringify(want), c.want, { timeout: 15000 }).catch(() => {}) |
| 232 | await page.waitForFunction(() => window.__inflight === 0 && performance.now() - window.__lastPost > 1500, null, { timeout: 15000 }).catch(() => {}) |
| 233 | const got = await page.evaluate(paragraphs) |
| 234 | const state = await page.evaluate(() => ({ log: window.__log, posts: window.__posts, errors: window.__errors, status: document.querySelector('[estilo-save-status~="floating"]') && document.querySelector('[estilo-save-status~="floating"]').getAttribute('data-state') })) |
| 235 | if (JSON.stringify(got) !== JSON.stringify(c.want)) failures.push(`${label}: the page holds ${JSON.stringify(got)}, want ${JSON.stringify(c.want)}`) |
| 236 | if (state.errors.length) failures.push(`${label}: errors ${JSON.stringify(state.errors)}`) |
| 237 | if (!c.lost) { |
| 238 | const appeared = state.log.filter((e) => e.has).length |
| 239 | const stayed = state.log.length && state.log[state.log.length - 1].has |
| 240 | if (appeared !== 1 || !stayed) failures.push(`${label}: the pasted words appeared ${appeared} times and ${stayed ? 'stayed' : 'went'}, want once and to stay: ${JSON.stringify(state.log)}`) |
| 241 | } else { |
| 242 | if (state.posts.length !== 1) failures.push(`${label}: a paste that could not be kept was posted: ${JSON.stringify(state.posts)}`) |
| 243 | if (state.status !== 'failed') failures.push(`${label}: the save line says ${state.status}, want failed`) |
| 244 | } |
| 245 | console.log('RESULT ' + JSON.stringify({ label, deck, want: c.want })) |
| 246 | } catch (err) { |
| 247 | failures.push(`${label}: ${err.message}`) |
| 248 | } |
| 249 | await context.close() |
| 250 | } |
| 251 | await browser.close() |
| 252 | } |
| 253 | |
| 254 | if (failures.length) { |
| 255 | console.error(failures.join('\n')) |
| 256 | process.exit(1) |
| 257 | } |
| 258 | console.log('every case kept its paste, or refused it cleanly, in both engines') |
| 259 | |