Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
slides: the unsaved dot goes out only for the revision written (adopts the kernel save queue) (#677)
nyblneta32ff9a6d4c4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 51414cb4..a9757d4a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -99,6 +99,12 @@ jobs:# Typing runs and remote changes invalidate in-flight saves even while dirty.run: node scripts/test-spaces-save-revisions.ts+ - name: Slides save revisions+ # An edit, panel keystroke, remote op or undo during a write keeps the+ # deck dirty; writes queue; the CRDT stamp is taken as each one starts;+ # ⌘S, auto-save and Update this file all write through the queue.+ run: node scripts/test-slides-save-revisions.ts+- name: Typecheck kernel (standalone)# Apps also typecheck kernel transitively through their imports; this# catches kernel-only errors under the kernel's own flags. It ALSO@@ -2305,6 +2311,11 @@ jobs:# range across a parent copies parents only, never its states; plural# and singular toasts.run: node scripts/test-slides-copy-slides-browser.mjs+ - name: Save queue in Chromium+ # Real ⌘S and auto-save with the file write held open: an edit made+ # during a write stays dirty, writes never overlap, the dot goes out+ # only when the deck on screen is the one on disk.+ run: node scripts/test-slides-save-browser.mjsspaces-save-browser:runs-on: ubuntu-latestdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 10235598..2933d59f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,13 @@ pre-1.0.## [Unreleased]+- **An edit made while the deck is saving is no longer marked saved.** Saving+ takes a moment, and an edit made in that moment — by you, or by someone in a+ live session — used to be shown as saved while the file on disk was still+ missing it. The unsaved-changes dot now goes out only when the file holds+ exactly what is on screen; otherwise it stays on and the next save (or+ auto-save) writes the edit. ⌘S, auto-save and "Update this file" also wait+ for each other instead of writing the file at the same time.- **One page for PowerPoint, in and out: bento.page/convert.** Drop a`.pptx` to open it as a bento/slides deck, or drop a bento/slides deck (orits document JSON) to save it as PowerPoint. The page detects what youdiff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 2d1d81e1..e3a89bbf 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -10230,3 +10230,31 @@ bento's page. Elsewhere, after a hidden slide or a state, it is fixed text,reported as `text-field-frozen`. This was already wrong after any hiddenslide before states existed.++## 2026-10-10 — Slides: the unsaved dot answers for one revision, and every write of the open file queues++Slides adopts the kernel's `SaveQueue` on the same terms as spaces (2026-09-28+entry above) and dash. Auto-save's write-back, ⌘S, Save a copy and About's+"Update this file" all wrote the open file and then cleared the dirty flag+unconditionally, so an edit made while a write was in flight was shown as+saved and never reached disk; auto-save and ⌘S could also write at once.+The rule, owned by `slides/src/saving.ts`:++- **One queue per editor** for every write that uses or adopts the open+ file's handle. Share exports (invite, view-only, present-only, audience,+ template) write OTHER files and never retain the handle, so they stay outside it.+- **The dot clears only if `isCurrent()` holds when the write resolves.**+ `Store.revision` advances on every `'doc'` event and every+ `setDirty(true)` (a remote op marks dirty while already dirty), and undo,+ redo and `replaceDoc` swap the document object, which also fails the check.+- **The CRDT stamp is taken in the queue's prepare step**, so a write+ queued behind another carries the live session's state as of its own start.+- **Unchanged:** an encrypted deck is still never snapshotted to IndexedDB+ and its write-back stays encrypted (`serializeAuto` on the snapshot);+ "Backed up in this browser" is still said only when the IndexedDB snapshot+ really stored and no file write-back happened. Auto-save says "Saved" only+ when the dot actually went out.++Guards: `scripts/test-slides-save-revisions.ts` (the rule, through+`saveRevision`, plus the editor wiring) and `scripts/test-slides-save-browser.mjs`+(the packaged editor through the shared `scripts/lib/savequeue-browser.mjs`).diff --git a/scripts/test-slides-save-browser.mjs b/scripts/test-slides-save-browser.mjsnew file mode 100644index 00000000..f14e3466--- /dev/null+++ b/scripts/test-slides-save-browser.mjs@@ -0,0 +1,8 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// The packaged slides editor, real ⌘S and auto-save, file writes held open:+// an edit made during a write stays dirty, writes never overlap, and the dot+// goes out only once the deck on screen is the one on disk. Same helper as+// spaces and dash (scripts/lib/savequeue-browser.mjs).+import { runSaveQueueBrowser } from './lib/savequeue-browser.mjs'+await runSaveQueueBrowser({ app: 'slides', title: '.ed-title', dirty: '.ed-dirty.on' })diff --git a/scripts/test-slides-save-revisions.ts b/scripts/test-slides-save-revisions.tsnew file mode 100644index 00000000..db152754--- /dev/null+++ b/scripts/test-slides-save-revisions.ts@@ -0,0 +1,196 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// The unsaved dot goes out only for the revision that was actually written.+//+// node scripts/test-slides-save-revisions.ts+//+// WHAT THIS PROVES. Slides cleared its dirty flag after every awaited write —+// auto-save's write-back, ⌘S and Update this file — so an edit made WHILE the+// bytes were on their way was marked saved and never reached disk. Slides now+// writes through the kernel's SaveQueue (slides/src/saving.ts), as spaces and+// dash do. Every case below drives saveRevision — the function the editor+// calls — against a gated fake write, so it can hold a write open, change the+// deck under it, then let it land. The write records the bytes it was handed,+// which is what the file on disk would hold.+//+// The last section checks the wiring: all three of the editor's writes to the+// open file go through the queue, and no path clears the dot unconditionally.++import { readFileSync } from 'node:fs'+import { register } from 'node:module'+register('./lib/ts-resolve-hooks.mjs', import.meta.url)+const { Store } = await import('../slides/src/store.ts')+const { newDoc } = await import('../slides/src/model.ts')+const { createSaveQueue, saveRevision } = await import('../slides/src/saving.ts')++let failures = 0+let checks = 0+function check(cond: boolean, what: string): void {+ checks+++ if (cond) console.log(` ok ${what}`)+ else { failures++; console.log(` FAIL ${what}`) }+}++type Gate = { title: string; stamp: unknown; release: () => void; fail: (e: Error) => void }+function harness() {+ const doc = newDoc()+ doc.title = 'one'+ const store = new Store(doc)+ const queue = createSaveQueue(store)+ const gates: Gate[] = []+ let open = 0, maxOpen = 0+ const write = (snapshot: any) => new Promise<'saved'>((resolve, reject) => {+ open++; maxOpen = Math.max(maxOpen, open)+ // the bytes are taken when the write starts, as the serializer does+ gates.push({+ title: snapshot.title, stamp: snapshot.collab?.sync,+ release: () => { open--; resolve('saved') },+ fail: (e) => { open--; reject(e) },+ })+ })+ let stamps = 0+ const save = (stamp = false) => saveRevision(store, queue, write,+ stamp ? () => { (store.doc as any).collab = { ...(store.doc as any).collab, sync: `stamp-${++stamps}` } } : undefined)+ const edit = (v: string) => store.commit(() => { store.doc.title = v })+ const tick = async () => { for (let i = 0; i < 8; i++) await Promise.resolve() }+ return { store, gates, save, edit, tick, maxOpen: () => maxOpen }+}++console.log('\nan edit committed while the write is in flight')+{+ const h = harness()+ h.edit('two')+ const first = h.save()+ await h.tick()+ check(h.gates.length === 1 && h.gates[0].title === 'two', 'the write took the deck as it was when it started')+ h.edit('three') // lands after the bytes were taken+ h.gates[0].release()+ const out = await first+ check(out.kind === 'written' && out.current === false, 'the write reports it is no longer the deck on screen')+ check(h.store.dirty, 'the deck stays dirty — "three" is not on disk')+ const second = h.save()+ await h.tick()+ check(h.gates[1]?.title === 'three', 'the next save writes the edit')+ h.gates[1].release()+ const out2 = await second+ check(out2.kind === 'written' && out2.current && !h.store.dirty, 'and only then does the dot go out')+}++console.log('\nan edit with no new undo entry (a panel keystroke while already dirty)')+{+ const h = harness()+ h.edit('two')+ const p = h.save()+ await h.tick()+ h.store.doc.title = 'typed'+ h.store.touch() // what PropsPanel.edit does mid-burst+ h.gates[0].release()+ await p+ check(h.store.dirty, 'still dirty — touch() advances the revision even when already dirty')+}++console.log('\na remote edit while the write is in flight')+{+ const h = harness()+ h.edit('two')+ const p = h.save()+ await h.tick()+ h.store.doc.title = 'from a collaborator'+ h.store.setDirty(true) // what the sync session does, already dirty+ h.gates[0].release()+ await p+ check(h.store.dirty, 'still dirty — a remote op counts as a change')+}++console.log('\nundo while the write is in flight')+{+ const h = harness()+ h.edit('two')+ const p = h.save()+ await h.tick()+ h.store.undo() // replaces the document object+ h.gates[0].release()+ const out = await p+ check(out.kind === 'written' && !out.current && h.store.dirty, 'still dirty — the deck on screen is not the one written')+}++console.log('\na write that fails')+{+ const h = harness()+ h.edit('two')+ const p = h.save()+ await h.tick()+ h.gates[0].fail(new Error('disk full'))+ const out = await p+ check(out.kind === 'failed' && h.store.dirty, 'reported as failed, and the deck stays dirty')+ const next = h.save()+ await h.tick()+ check(h.gates.length === 2, 'the queue is not poisoned — the next save still runs')+ h.gates[1].release()+ await next+ check(!h.store.dirty, 'and it clears the dot')+}++console.log('\nback-to-back saves (⌘S while auto-save writes)')+{+ const h = harness()+ h.edit('two')+ const a = h.save()+ h.edit('three')+ const b = h.save()+ await h.tick()+ check(h.gates.length === 1, 'the second write waits for the first')+ h.gates[0].release()+ await a+ await h.tick()+ check(h.gates[1]?.title === 'three', 'and takes its own snapshot when it starts')+ h.gates[1].release()+ await b+ check(h.maxOpen() === 1 && !h.store.dirty, 'never two writes at once; clean at the end')+}++console.log('\nthe live-session stamp is taken when each write starts')+{+ const h = harness()+ h.edit('two')+ const a = h.save(true)+ const b = h.save(true)+ await h.tick()+ check(h.gates[0].stamp === 'stamp-1', 'the first write carries its own stamp')+ h.gates[0].release()+ await a+ await h.tick()+ check(h.gates[1]?.stamp === 'stamp-2', 'a write queued behind it stamps at its own start, not at the click')+ h.gates[1].release()+ await b+}++console.log('\na save with nothing changed under it')+{+ const h = harness()+ h.edit('two')+ const p = h.save()+ await h.tick()+ h.gates[0].release()+ const out = await p+ check(out.kind === 'written' && out.current && !h.store.dirty, 'clears the dot')+}++console.log('\nthe editor writes through the queue')+{+ const src = readFileSync(new URL('../slides/src/editor/editor.ts', import.meta.url), 'utf8')+ const body = (sig: string, len = 2400) => { const i = src.indexOf(sig); return i < 0 ? '' : src.slice(i, i + len) }+ const auto = body('private async runAutosave()')+ const manual = body('async save(forcePicker: boolean)')+ const update = body("inPlaceB.addEventListener('click', async () => {", 1200)+ check(/saveRevision\(this\.store, this\.saveQueue,[\s\S]*writeUpdatedFile\(await serializeAuto\(snapshot\)\)/.test(auto), 'auto-save writes the queue\'s snapshot')+ check(/saveRevision\(this\.store, this\.saveQueue,[\s\S]*saveFile\(snapshot, forcePicker\)/.test(manual), '⌘S and Save a copy write the queue\'s snapshot')+ check(/saveRevision\(this\.store, this\.saveQueue,[\s\S]*applyUpdateInPlace\(release, snapshot\)/.test(update), 'Update this file writes the queue\'s snapshot')+ const clears = [...src.matchAll(/^.*setDirty\(false\).*$/gm)].map((m) => m[0].trim()).filter((l) => !l.startsWith('//'))+ check(clears.length === 1 && /if \(outcome\.current\)/.test(clears[0]), `no unconditional clear left (${clears.join(' | ') || 'none'})`)+ check(/\(\) => this\.session\?\.stampInto\(this\.store\.doc\)\)/.test(auto) && /\(\) => this\.session\?\.stampInto\(this\.store\.doc\)\)/.test(manual),+ 'the CRDT stamp happens in the queue\'s prepare step, for auto-save and ⌘S')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+process.exit(failures ? 1 : 0)diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.tsindex 176ad18f..346a1219 100644--- a/slides/src/editor/editor.ts+++ b/slides/src/editor/editor.ts@@ -26,6 +26,8 @@ import { startPresentation } from '../present'// in this file writes a real file for a person, so all of them must inherit an// active password. serializeAuto is the only encryption-aware serializer.import { adoptFileHandle, canWriteInPlace, currentFileName, fileBase, hasFileHandle, hostCan, isEncryptionActive, openedFileName, saveFile, serializeAuto, setEncryptionPassword, suggestedFileName, writeUpdatedFile, writeUpdatedFileAs } from '../save'+import { createSaveQueue, saveRevision } from '../saving'+import type { SaveQueue } from '../../../kernel/src/savequeue.ts'import { noteSavedFromWeb } from './returngate'import { addVersion, clearRecovery, clearVersions, docContentKey, getRecovery, listVersions, pruneOld, putRecovery, type Snapshot } from '../autosave'import { insertElements, insertSlides, parseClip, serializeElements, serializeSlides } from './clipboard'@@ -2616,6 +2618,13 @@ export class Editor {private autosaveTimer = 0private lastVersionAt = 0private lastBackupAt = 0+ /** Every write to the open file's handle — ⌘S, Save a copy, auto-save and+ * Update this file — goes through this one queue (saving.ts). Lazy: the+ * store arrives as a constructor parameter, after field initialisers run. */+ private saveQueueInst: SaveQueue<import('../model').BentoDoc> | null = null+ private get saveQueue(): SaveQueue<import('../model').BentoDoc> {+ return this.saveQueueInst ??= createSaveQueue(this.store)+ }private wireAutosave() {if (this.store.doc.readonly) return // player file — nothing to autosave@@ -2645,15 +2654,23 @@ export class Editor {if (Date.now() - this.lastVersionAt > 120_000) { this.lastVersionAt = Date.now(); await addVersion(doc) }}// Silent file write-back once we hold a writable handle (Chrome/Edge).+ // Through the save queue: it waits behind a ⌘S already writing, writes a+ // snapshot taken as it starts, and the dot goes out only if no edit landed+ // while the bytes were on their way — the old unconditional+ // setDirty(false) here marked such an edit saved, and it never reached disk.if (hasFileHandle()) {- try {- this.session?.stampInto(doc)- await writeUpdatedFile(await serializeAuto(doc))- this.store.setDirty(false)+ const out = await saveRevision(this.store, this.saveQueue,+ async (snapshot) => { await writeUpdatedFile(await serializeAuto(snapshot)); return 'saved' as const },+ () => this.session?.stampInto(this.store.doc))+ if (out.kind === 'discarded') return // another deck was opened meanwhile+ if (out.kind === 'written') {markFileSaved() // the packs went out with those bytes too- this.flashSaved()+ // "Saved" only when the dot actually went out; an edit made during the+ // write stays dirty and its own 'doc' event has already re-armed us+ if (out.current) this.flashSaved()return- } catch { /* keep dirty; the IndexedDB snapshot is the backstop */ }+ }+ // failed: keep dirty; the IndexedDB snapshot is the backstop}// No handle (Safari/Firefox/iOS) or the write failed: the file on disk is// STALE and the deck stays dirty — saying "Saved" here would be a lie. But@@ -3073,13 +3090,23 @@ export class Editor {async save(forcePicker: boolean) {this.canvas.commitTextEdit()- // shared docs persist their CRDT state so the saved copy can rejoin- // as a true fork later (offline edits merge both ways)- this.session?.stampInto(this.store.doc)+ // Through the save queue (saving.ts): serialised with auto-save and+ // Update this file, written from a snapshot taken as the write starts, and+ // the dot goes out only if nothing changed while the bytes were on their+ // way. Shared decks stamp their CRDT state in the queue's prepare step, so+ // the saved copy can rejoin as a true fork later (offline edits merge both+ // ways) and a save queued behind another carries the state of its own start.+ const out = await saveRevision(this.store, this.saveQueue,+ (snapshot) => saveFile(snapshot, forcePicker),+ () => this.session?.stampInto(this.store.doc))+ if (out.kind === 'discarded' || out.kind === 'cancelled') return+ if (out.kind === 'failed') {+ console.error(out.error)+ this.toast(t('Save failed — see console'))+ return+ }+ const result = out.resulttry {- const result = await saveFile(this.store.doc, forcePicker)- if (result === 'cancelled') return- this.store.setDirty(false)// the file name is knowable from here on — put it in the tab and the chipthis.syncWindowTitle()// staged language packs are in the bytes now — stop calling them pending@@ -3589,7 +3616,7 @@ export class Editor {}const actions = div('ed-about-actions')const fail = (err: any) => { status.textContent = t('Update failed: {m}', { m: String(err?.message ?? err) }) }- const done = (outcome: InPlaceOutcome) => {+ const done = (outcome: InPlaceOutcome & { current: boolean }) => {status.textContent = ''const after = div('ed-about-update')status.appendChild(after)@@ -3610,7 +3637,10 @@ export class Editor {reloadB.className = 'ed-btn ed-btn-primary'reloadB.textContent = t('Reload into new version')reloadB.addEventListener('click', () => {- this.store.setDirty(false) // disk already holds this exact document+ // The disk holds the deck as it was when the update was WRITTEN.+ // Only then is the dot honest to clear; an edit made since stays+ // dirty, so the page's unload guard still asks before it is lost.+ if (outcome.current) this.store.setDirty(false)// Hand a note to the version we are about to become. sessionStorage// because the lifetime is exactly right: it survives this reload and// dies with the tab. See noticeIfJustUpdated.@@ -3645,12 +3675,14 @@ export class Editor {inPlaceB.addEventListener('click', async () => {inPlaceB.disabled = trueinPlaceB.textContent = t('Verifying…')- try {- this.session?.stampInto(this.store.doc)- const written = await applyUpdateInPlace(release, this.store.doc)- if (written) done(written)- else { inPlaceB.disabled = false; inPlaceB.textContent = t('Update this file…') }- } catch (err: any) { fail(err) }+ // the same handle ⌘S and auto-save write, so the same queue: it never+ // overlaps them, and it writes the snapshot taken as it starts+ const out = await saveRevision(this.store, this.saveQueue,+ async (snapshot) => (await applyUpdateInPlace(release, snapshot)) ?? 'cancelled',+ () => this.session?.stampInto(this.store.doc))+ if (out.kind === 'written') done({ ...out.result, current: out.current })+ else if (out.kind === 'failed') fail(out.error)+ else { inPlaceB.disabled = false; inPlaceB.textContent = t('Update this file…') }})actions.appendChild(inPlaceB)diff --git a/slides/src/saving.ts b/slides/src/saving.tsnew file mode 100644index 00000000..a6a6e5b6--- /dev/null+++ b/slides/src/saving.ts@@ -0,0 +1,78 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// ⌘S, auto-save write-back and "Update this file", and the one rule that makes+// the unsaved dot honest: the dot goes out only when the write that captured+// THIS revision is acknowledged.+//+// It used to go out when ANY write resolved. Every write awaits (a handle+// reconnect, the serializer, an encrypting serializer, the disk), and an edit+// made in that window landed in the live deck after the bytes were taken —+// then setDirty(false) ran anyway, so the file on disk was missing the edit and+// nothing on screen said so. The kernel's SaveQueue (kernel/src/savequeue.ts)+// serialises the writes against the one file handle, captures a detached+// snapshot immediately before each write, and answers `isCurrent()` at+// acknowledgement time; this module is slides' side of that contract, kept out+// of editor.ts so the rig drives the same code the button does+// (scripts/test-slides-save-revisions.ts). Spaces and dash adopted the same+// queue the same way (spaces/src/saving.ts, dash/src/saving.ts).+//+// Policy that stays here and NOT in the kernel: which store event clears the+// dot, what each caller does before its write starts (close a text edit, stamp+// the CRDT state into the deck), and what counts as failure.++import { SaveQueue } from '../../kernel/src/savequeue.ts'+import type { BentoDoc } from './model'+import type { Store } from './store'++/** What a write answers. saveFile's results, plus 'cancelled' = picker closed. */+export type WriteResult = 'saved' | 'saved-as' | 'downloaded' | 'cancelled'++export type SaveOutcome<R> =+ /** the deck was swapped for another document while this save waited */+ | { kind: 'discarded' }+ | { kind: 'cancelled' }+ /** the write threw — nothing is acknowledged, the dot stays on */+ | { kind: 'failed'; error: unknown }+ /**+ * A file now holds `doc`. `current` says whether that is still the deck on+ * screen — false means an edit landed while the write was in flight, and the+ * dot stays on for it (auto-save picks it up on its next pass).+ */+ | { kind: 'written'; result: R; doc: BentoDoc; current: boolean }++/** One queue per editor: every write that uses or adopts the open file's+ * handle goes through it — ⌘S, Save a copy, auto-save, Update this file. */+export function createSaveQueue(store: Store): SaveQueue<BentoDoc> {+ return new SaveQueue<BentoDoc>({ getDocument: () => store.doc, getRevision: () => store.revision })+}++/**+ * Write the deck through the queue and acknowledge only its own revision.+ *+ * `prepare` runs when THIS write actually begins (after any write ahead of+ * it), before the snapshot is taken: it is where a caller stamps the live+ * session's CRDT state into the deck, so a save queued behind another carries+ * the state as of its own start, not the click.+ */+export async function saveRevision<R>(+ store: Store,+ queue: SaveQueue<BentoDoc>,+ write: (snapshot: BentoDoc) => Promise<R | 'cancelled'>,+ prepare?: () => void,+): Promise<SaveOutcome<R>> {+ let saved+ try {+ saved = await queue.run(() => prepare?.(), write)+ } catch (error) {+ return { kind: 'failed', error }+ }+ if (!saved) return { kind: 'discarded' }+ const result = saved.value+ if (result === 'cancelled') return { kind: 'cancelled' }+ const current = saved.isCurrent()+ // setDirty, not a bare assignment: it raises 'dirty', which repaints the+ // dot, and clearing never advances the revision.+ if (current) store.setDirty(false)+ return { kind: 'written', result: result as R, doc: saved.doc, current }+}diff --git a/slides/src/store.ts b/slides/src/store.tsindex a09d04c2..09c724aa 100644--- a/slides/src/store.ts+++ b/slides/src/store.ts@@ -32,6 +32,11 @@ export class Store {currentIndex = 0selection: string[] = []dirty = false+ /** Advances on EVERY mutation — a local edit, a panel keystroke inside one+ * undo group, a remote op — even while already dirty. The save queue+ * (saving.ts) clears the dirty flag only if this has not moved since the+ * bytes it wrote were taken. Never decreases; never saved. */+ revision = 0/** editor-only: which showOnHover set the canvas previews (never saved) */hoverPreview: string | null = null@@ -55,6 +60,7 @@ export class Store {}emit(event: StoreEvent) {+ if (event === 'doc') this.revision++this.listeners.get(event)?.forEach((fn) => fn())}@@ -192,6 +198,8 @@ export class Store {}setDirty(dirty: boolean) {+ // Remote apply marks dirty even when already dirty — that is a mutation too.+ if (dirty) this.revision++if (this.dirty === dirty) returnthis.dirty = dirtythis.emit('dirty')