Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

slides: Save perf improvements (phase 3) (#794)

Rahul Ravikumarff0714a46758
diff --git a/.github/workflows/ci-slides.yml b/.github/workflows/ci-slides.yml
index f49956cd..d07aa830 100644
--- a/.github/workflows/ci-slides.yml
+++ b/.github/workflows/ci-slides.yml
@@ -132,6 +132,11 @@ jobs:
# keeps tier 1, and a page whose assets exceed the budget takes the fast
# path straight to tinted boxes.
run: node scripts/test-slides-preview-tiers-browser.mjs
+ - name: Saving never costs an edit its recovery copy in Chromium
+ # A dismissed save leaves the edit's pending auto-save running (so its
+ # recovery copy is written); a save that succeeds records a recovery
+ # baseline and a version from the idle-time checkpoint.
+ run: node scripts/test-slides-save-recovery-browser.mjs
- name: The loader reads what the app published in Chromium
# Toy shells from the real postbuild: an app that is running, locked at
# a gate, or refused (and threw) runs ONCE and gets no loader card; only
diff --git a/kernel/src/save.ts b/kernel/src/save.ts
index 78a2b09c..f2accda6 100644
--- a/kernel/src/save.ts
+++ b/kernel/src/save.ts
@@ -833,6 +833,10 @@ async function pickHandle(
}
async function writeHandle(handle: FsFileHandle, html: string) {
+ // Yield to the event loop before disk I/O.
+ // On Linux + Wayland it is important to give the compositor a chance to
+ // commit pending frames, before Disk I/O.
+ await new Promise((r) => setTimeout(r, 0))
const writable = await handle.createWritable()
await writable.write(new Blob([html], { type: 'text/html' }))
await writable.close()
diff --git a/scripts/test-slides-save-recovery-browser.mjs b/scripts/test-slides-save-recovery-browser.mjs
new file mode 100644
index 00000000..dc6a417e
--- /dev/null
+++ b/scripts/test-slides-save-recovery-browser.mjs
@@ -0,0 +1,106 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// ⌘S never costs an edit its crash-recovery copy, and a save still records one.
+//
+// npm run build:single --prefix slides && node scripts/test-slides-save-recovery-browser.mjs
+//
+// WHAT THIS PROVES, in the packaged document. An edit schedules an auto-save
+// (2.5 s), which writes the deck's recovery copy to IndexedDB: the backstop if
+// the tab dies. A save makes that pending write redundant, so it is cancelled —
+// but only after a save that SUCCEEDED and left nothing unsaved. Cancelled at
+// the start of every save, a save the user then dismissed (the picker closed)
+// took the edit's only recovery copy with it. And the save's own recovery
+// baseline and version checkpoint now run when the page is idle rather than in
+// the save's path; they must still run.
+// 1. edit, ⌘S, dismiss the save picker, wait past the debounce: the edit IS in
+// the recovery store (and in the version history);
+// 2. edit, ⌘S that succeeds (a download here): the recovery copy and a
+// version hold the saved deck, written by the deferred checkpoint.
+// Mutation: cancel the timer at the start of save() again and 1 goes red.
+import { readFileSync, writeFileSync, mkdtempSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')
+
+let checks = 0
+let failures = 0
+function ok(cond, msg) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) } else console.log(` ok ${msg}`)
+}
+const shell = readFileSync(new URL('../slides/dist-single/Bento_Slides.bento.html', import.meta.url), 'utf8')
+const dir = mkdtempSync(join(tmpdir(), 'bento-save-recovery-'))
+const SAVE = process.platform === 'darwin' ? 'Meta+s' : 'Control+s'
+
+// which IndexedDB stores hold `marker` (recovery and version history live in IndexedDB)
+const stores = (p, marker) => p.evaluate(async (m) => {
+ const hits = []
+ for (const { name } of await indexedDB.databases()) {
+ const db = await new Promise((res, rej) => { const r = indexedDB.open(name); r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error) })
+ for (const store of Array.from(db.objectStoreNames)) {
+ const all = await new Promise((res) => { const r = db.transaction(store).objectStore(store).getAll(); r.onsuccess = () => res(r.result); r.onerror = () => res([]) })
+ if (JSON.stringify(all).includes(m)) hits.push(store)
+ }
+ db.close()
+ }
+ return hits
+}, marker)
+async function open(withPicker) {
+ const ctx = await browser.newContext({ viewport: { width: 1280, height: 860 }, acceptDownloads: true })
+ await ctx.route(/^https?:/, (r) => r.abort())
+ await ctx.addInitScript((keep) => { if (!keep) delete window.showSaveFilePicker; try { localStorage.setItem('bento-slideshow-started', '1') } catch {} }, withPicker)
+ const p = await ctx.newPage()
+ const errors = []
+ p.on('pageerror', (e) => errors.push(e.message))
+ p.on('dialog', (d) => d.dismiss())
+ const file = join(dir, `deck-${Math.random().toString(36).slice(2)}.bento.html`)
+ writeFileSync(file, shell)
+ await p.goto('file://' + file)
+ await p.waitForFunction(() => window.bento?.doc && document.querySelector('.ed-topbar .ed-title'))
+ await p.waitForTimeout(400)
+ return { ctx, p, errors }
+}
+const retitle = async (p, title) => {
+ await p.locator('.ed-topbar .ed-title').fill(title)
+ await p.locator('.ed-topbar .ed-title').press('Enter')
+ await p.waitForFunction((t) => window.bento.doc.title === t, title)
+}
+
+const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH, headless: true })
+try {
+ console.log('a save the user dismisses\n')
+ {
+ const { ctx, p, errors } = await open(true)
+ ok(await p.evaluate(() => typeof window.showSaveFilePicker === 'function'), 'this browser has a save picker (left unanswered, the save is cancelled)')
+ const MARK = 'Cancelled save ' + Date.now()
+ await retitle(p, MARK)
+ await p.waitForTimeout(300) // well inside the 2.5 s debounce
+ await p.keyboard.press(SAVE)
+ await p.waitForTimeout(500)
+ await p.keyboard.press('Escape') // nobody picks a file
+ await p.waitForTimeout(4000) // past the debounce
+ const hits = await stores(p, MARK)
+ ok(hits.includes('recovery'), `the edit is in the recovery store after the dismissed save (${hits.join(', ') || 'nowhere'})`)
+ ok(errors.length === 0, `no page error${errors.length ? ' — ' + errors[0] : ''}`)
+ await ctx.close()
+ }
+
+ console.log('\na save that succeeds\n')
+ {
+ const { ctx, p, errors } = await open(false)
+ const MARK = 'Saved deck ' + Date.now()
+ await retitle(p, MARK)
+ const dl = p.waitForEvent('download', { timeout: 15000 }).catch(() => null)
+ await p.keyboard.press(SAVE)
+ ok(!!(await dl), 'the save went through (a download: this browser cannot write in place)')
+ await p.waitForTimeout(1200) // the deferred checkpoint runs when idle, at most 200 ms later
+ const hits = await stores(p, MARK)
+ ok(hits.includes('recovery') && hits.includes('versions'), `the save recorded a recovery baseline and a version (${hits.join(', ') || 'nowhere'})`)
+ ok(errors.length === 0, `no page error${errors.length ? ' — ' + errors[0] : ''}`)
+ await ctx.close()
+ }
+} finally {
+ await browser.close()
+}
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.ts
index 4ec959f9..a62addb1 100644
--- a/slides/src/editor/editor.ts
+++ b/slides/src/editor/editor.ts
@@ -3182,8 +3182,18 @@ export class Editor {
this.syncWindowTitle()
// staged language packs are in the bytes now — stop calling them pending
markFileSaved()
- // record a recovery baseline + a version checkpoint at each manual save
- if (!isBodySealed()) { void putRecovery(this.store.doc); void addVersion(this.store.doc); this.lastVersionAt = Date.now() }
+ // The save wrote everything there was, so a pending auto-save would only
+ // write it again. Cancelled ONLY here, after a save that left nothing
+ // unsaved: a cancelled or failed save returns above with the timer still
+ // running (it is the edit's crash-recovery copy), and an edit made while
+ // the bytes were on their way keeps the deck dirty and keeps its timer.
+ if (!this.store.dirty) {
+ clearTimeout(this.autosaveTimer)
+ this.autosaveTimer = 0
+ }
+ this.toast(result === 'downloaded'
+ ? t('This browser can’t rewrite files in place — a fresh copy went to Downloads')
+ : t('Saved'))
// Saving is the opt-in: a named, saved deck is "live by default" from
// now on (the recipient of a copy already joins on open). Connect this
// session too so author and recipient meet without another click.
@@ -3191,22 +3201,35 @@ export class Editor {
this.session?.enableSharing()
this.tryJoin()
}
- // A save from the WEB changes what this page is: the deck now lives in a
- // file, and this URL will hand out a fresh starter next time. Said here,
- // persistently, so the next visit is not a surprise — and deliberately
- // NOT as a block, because this tab keeps working and keeps writing.
- noteSavedFromWeb(currentFileName() ?? suggestedFileName(this.store.doc), {
- fsAccess: canWriteInPlace(), canWrite: hostCan('write'),
- })
- this.toast(result === 'downloaded'
- ? t('This browser can’t rewrite files in place — a fresh copy went to Downloads')
- : t('Saved'))
+ // The recovery baseline, the version checkpoint and the web note run when
+ // the page is idle, so the toast and the next paint are not held behind
+ // two IndexedDB writes (a large deck stalled the compositor on Wayland).
+ // The seal is asked when they run, not now: a deck sealed meanwhile
+ // writes nothing.
+ const doc = this.store.doc
+ Editor.whenIdle(() => {
+ // record a recovery baseline + a version checkpoint at each manual save
+ if (!isBodySealed()) { void putRecovery(doc); void addVersion(doc); this.lastVersionAt = Date.now() }
+ // A save from the WEB changes what this page is: the deck now lives in a
+ // file, and this URL will hand out a fresh starter next time. Said here,
+ // persistently, so the next visit is not a surprise — and deliberately
+ // NOT as a block, because this tab keeps working and keeps writing.
+ noteSavedFromWeb(currentFileName() ?? suggestedFileName(doc), {
+ fsAccess: canWriteInPlace(), canWrite: hostCan('write'),
+ })
+ }, 200)
} catch (err) {
console.error(err)
this.toast(t('Save failed — see console'))
}
}
+ /** Run `task` when the page is idle, and at most `timeout` ms later. */
+ private static whenIdle(task: () => void, timeout: number) {
+ if (typeof requestIdleCallback === 'function') requestIdleCallback(() => task(), { timeout })
+ else setTimeout(task, 0)
+ }
+
// --- keyboard ------------------------------------------------------------------
private wireKeyboard() {