Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
spaces: acknowledge only the revision actually saved (adopts the kernel save queue; replaces #580) (#617)
nyblnet77753fea0b62
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex cd6d05be..4727924c 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -95,6 +95,10 @@ jobs:working-directory: slidesrun: node_modules/.bin/tsc -b+ - name: Spaces save revisions+ # Typing runs and remote changes invalidate in-flight saves even while dirty.+ run: node scripts/test-spaces-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.@@ -1984,3 +1988,26 @@ jobs:# unknown-role copy arriving in a running editor (dropped, loadDoc) gets# no write actions and is locked; owner and writer copies keep theirs.run: node scripts/test-slides-audience-gate-browser.mjs++ spaces-save-browser:+ runs-on: ubuntu-latest+ timeout-minutes: 15+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 24+ - name: Install browser test runtime+ # Pinned outside app packages: browser automation is not shipped in documents.+ run: |+ npm install --prefix "$RUNNER_TEMP/bento-browser" --no-package-lock --ignore-scripts [email protected]+ "$RUNNER_TEMP/bento-browser/node_modules/.bin/playwright" install --with-deps chromium+ echo "PLAYWRIGHT_MODULE=$RUNNER_TEMP/bento-browser/node_modules/playwright/index.mjs" >> "$GITHUB_ENV"+ - name: Build the tested standalone documents+ run: |+ npm ci --prefix spaces+ npm run build:single --prefix spaces+ - name: Exercise the packaged documents in Chromium+ # Real UI and serialization, offline; delayed mock writes expose save races.+ run: |+ node scripts/test-spaces-save-browser.mjsdiff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex c571ad10..20e1768f 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -7790,6 +7790,50 @@ needs those more than anyone. Remote edits arrive through `touch()`, not`commit`, so a locked copy still follows the room. `copyIsReceiveOnly` is thelock's question (a document with no `collab` is local and editable — unlike`copyCanWrite`, which says no only because there is no room to write to).+## 2026-09-28 — Spaces: the unsaved dot answers for one revision, and every write of the open file queues++Spaces adopts the kernel's `SaveQueue` (kernel/src/savequeue.ts). The race it+closes was real in every app: ⌘S awaited `saveFile` and then cleared the+dirty flag, so an edit made while the write was in flight was never written+and was shown as saved. The rule now, owned by `spaces/src/saving.ts`:++- **The dot clears only when the write that captured THAT revision is+ acknowledged** — `isCurrent()` read after the write resolves, never the+ resolve itself. A stale write still counts as written: it gets its version+ entry (the snapshot that reached disk, not what is on screen now), but it+ does not clear recovery, because the recovery snapshot is then the only copy+ of the newer edit.+- **`store.revision` advances on every mutation**, including each keystroke+ inside a typing run (which deliberately raises no 'doc' event) and every+ remote apply, even while the space is already dirty. An undo that swaps the+ document object is stale by identity.+- **Every write to the OPEN file goes through one queue**: ⌘S and About's+ in-place self-update (`applyUpdateInPlace` adopts the same handle; overlapping+ it with a save let whichever closed last decide the file's shell). The+ update's old "Reload into new version" line set the dot false+ unconditionally; that was the same race, and it is gone.+- **Copies and exports stay OUT of the queue** — Save a copy, the page+ extract, Duplicate as new space, the invite and view-only copies. They write+ a different file, never keep its handle (`keepHandle` false, the lesson+ slides paid for), and never touch the dot. Queuing them would only put a+ file picker in front of ⌘S.+- **Encryption is unchanged** — `saveFile` serializes the snapshot through+ `serializeAuto`, the encryption-aware path.+- **A failed write says so** and leaves the space dirty; the queue is not+ poisoned, so the next ⌘S writes. It used to leave "Saving…" on screen and+ surface as an unhandled rejection.+- **⌘S in a read-only space behaves as before.** The adopting branch (#537)+ also made doSave return early when `store.readOnly`; that is not part of+ this fix and would have left a view-only follower's dot — lit by every+ remote op — impossible to clear. Whether a frozen (newer-version) file+ should refuse ⌘S is its own decision.++Proof: `scripts/test-spaces-save-revisions.ts` holds a write open, edits under+it, releases it, and requires the space still dirty with the edit in the next+write; plus a failed write, back-to-back saves, a remote edit and an undo+mid-write. Reverting to mark-saved-on-resolve fails five checks. Spaces does+not stamp `collab.sync` on ⌘S the way slides does; the queue's `prepare` is+where that would go, and it is filed rather than folded in here.## 2026-10-04 — Undo moves content, never identity (type)diff --git a/scripts/lib/savequeue-browser.mjs b/scripts/lib/savequeue-browser.mjsnew file mode 100644index 00000000..aedf71d0--- /dev/null+++ b/scripts/lib/savequeue-browser.mjs@@ -0,0 +1,54 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// App wrappers provide controls. Delay only file transport; exercise the real+// packaged UI, serialization and acknowledgement. Never skip when Chrome is absent.+import assert from 'node:assert/strict'+export async function runSaveQueueBrowser({ app, title, dirty, afterSave }) {+ const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')+ const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH, headless: true })+ try {+ const context = await browser.newContext({ viewport: { width: 1280, height: 900 } })+ await context.route(/^https?:/, route => route.abort())+ await context.addInitScript(() => {+ window.testWrites = []; window.testActive = 0; window.testMaxActive = 0;+ window.testReleases = []; window.testBlock = true;+ const handle = { name: 'queue-test.bento.html', async createWritable() {+ window.testActive++; window.testMaxActive = Math.max(window.testMaxActive, window.testActive);+ return { async write(blob) {+ const html = await blob.text();+ const match = html.match(/<script\b[^>]*id="bento-doc"[^>]*>([\s\S]*?)<\/script>/i);+ window.testWrites.push(JSON.parse(match[1]));+ if (window.testBlock) await new Promise(resolve => window.testReleases.push(resolve));+ }, async close() { window.testActive-- } };+ } };+ window.showSaveFilePicker = async () => handle;+ })+ const page = await context.newPage(), errors = []+ page.on('pageerror', e => errors.push(e.message)); page.on('dialog', d => d.accept())+ const name = app[0].toUpperCase() + app.slice(1)+ await page.goto(new URL(`../../${app}/dist-single/Bento_${name}.bento.html`, import.meta.url).href)+ await page.waitForFunction(() => window.bento?.doc)+ await page.locator(title).fill('First saved revision')+ await page.locator(title).press('Tab')+ await page.keyboard.press('ControlOrMeta+s')+ await page.waitForFunction(() => window.testWrites.length === 1)+ await page.locator(title).fill('Second saved revision')+ await page.locator(title).press('Tab')+ await page.keyboard.press('ControlOrMeta+s')+ // Allow automatic write-back to queue behind the blocked manual save too.+ await page.waitForTimeout(2800)+ assert.equal(await page.evaluate(() => window.testWrites.length), 1, app + ' writes do not overlap')+ await page.evaluate(() => window.testReleases.shift()())+ await page.waitForFunction(() => window.testWrites.length === 2)+ assert(await page.locator(dirty).count() > 0, app + ' older save leaves new edits dirty')+ assert.deepEqual(await page.evaluate(() => window.testWrites.slice(0,2).map(d => d.title)), ['First saved revision', 'Second saved revision'])+ await page.evaluate(() => { window.testBlock = false; window.testReleases.splice(0).forEach(release => release()) })+ await page.waitForFunction(() => window.testActive === 0)+ await page.waitForFunction(selector => document.querySelector(selector) === null, dirty)+ if (afterSave) await afterSave(page, { title })+ assert.equal(await page.evaluate(() => window.testMaxActive), 1, app + ' serializes manual and automatic writes')+ assert.deepEqual(errors, [], app + ' has no runtime errors')+ console.log(app + ': packaged UI preserves in-flight snapshot, serializes writes and acknowledges only current revision')+ await context.close()+ } finally { await browser.close() }+}diff --git a/scripts/test-spaces-save-browser.mjs b/scripts/test-spaces-save-browser.mjsnew file mode 100644index 00000000..3d2a8841--- /dev/null+++ b/scripts/test-spaces-save-browser.mjs@@ -0,0 +1,4 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+import { runSaveQueueBrowser } from './lib/savequeue-browser.mjs'+await runSaveQueueBrowser({ app: 'spaces', title: '.sp-doctitle', dirty: '.sp-dirty.sp-on' })diff --git a/scripts/test-spaces-save-revisions.ts b/scripts/test-spaces-save-revisions.tsnew file mode 100644index 00000000..83aebde1--- /dev/null+++ b/scripts/test-spaces-save-revisions.ts@@ -0,0 +1,221 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+import assert from 'node:assert/strict'+import { register } from 'node:module'+register('./lib/ts-resolve-hooks.mjs', import.meta.url)+const { Store: SpacesStore } = await import('../spaces/src/store.ts')+const { parseDoc: parseSpace } = await import('../spaces/src/model.ts')+import { SaveQueue } from '../kernel/src/savequeue.ts'+const space = parseSpace(JSON.stringify({ format: 'bento/spaces', version: 1, docId: 's', title: 'Space', pages: [{ id: 'p', title: 'Page', blocks: [{ id: 'b', type: 'p', html: 'before' }] }] }))+assert(space.ok)+const s = new SpacesStore(space.doc)+const q = new SaveQueue({ getDocument: () => s.doc, getRevision: () => s.revision })+s.runEdit('b', () => { s.doc.pages[0].blocks[0].html = 'first' })+let release!: () => void+const first = q.run(() => s.endRun(), async doc => { await new Promise<void>(r => { release = r }); return doc.pages[0].blocks[0].html })+await Promise.resolve()+// Two inputs while already dirty; the second does not emit a doc notification.+s.runEdit('b', () => { s.doc.pages[0].blocks[0].html = 'second' })+const revision = s.revision+s.runEdit('b', () => { s.doc.pages[0].blocks[0].html = 'third' })+assert(s.revision > revision)+release()+const saved = await first+assert.equal(saved!.value, 'first')+assert.equal(saved!.isCurrent(), false)+s.endRun()+const remote = await q.run(() => {}, async () => true)+s.doc.pages[0].blocks[0].html = 'remote'+s.setDirty(true)+assert.equal(remote!.isCurrent(), false, 'remote change invalidates a save even while already dirty')++console.log('spaces save revisions: grouped typing and already-dirty remote changes passed')++// ---- the race, through the code ⌘S runs (spaces/src/saving.ts) --------------+//+// Every case below drives saveRevision — the function main.ts's doSave calls —+// against a gated fake write, so each one can hold a write open, edit under it,+// then let it land. The write records the bytes it was handed, which is what a+// file on disk would hold.+const { saveRevision } = await import('../spaces/src/saving.ts')++let failures = 0+function check(cond: boolean, what: string): void {+ if (cond) console.log(` ok ${what}`)+ else { failures++; console.error(` FAIL ${what}`) }+}++type Gate = { bytes: string; release: () => void; fail: (e: Error) => void }+function harness() {+ const p = parseSpace(JSON.stringify({ format: 'bento/spaces', version: 1, docId: 'race', title: 'Race', pages: [{ id: 'p', title: 'Page', blocks: [{ id: 'b', type: 'p', html: 'one' }] }] }))+ assert(p.ok)+ const store = new SpacesStore(p.doc)+ const queue = new SaveQueue({ getDocument: () => store.doc, getRevision: () => store.revision })+ 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 saveFile's serializer does+ gates.push({+ bytes: snapshot.pages[0].blocks[0].html,+ release: () => { open--; resolve('saved') },+ fail: (e) => { open--; reject(e) },+ })+ })+ const save = () => saveRevision(store, queue, write)+ const html = () => store.doc.pages[0].blocks[0].html+ const edit = (v: string) => store.commit(() => { store.doc.pages[0].blocks[0].html = v })+ const type = (v: string) => store.runEdit('b', () => { store.doc.pages[0].blocks[0].html = v })+ const tick = async () => { for (let i = 0; i < 5; i++) await Promise.resolve() }+ return { store, gates, save, html, edit, type, 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, 'the write started')+ h.edit('three') // lands after the bytes were taken+ h.gates[0].release()+ const out = await first+ check(out.kind === 'written' && !out.current, 'the write is acknowledged as STALE')+ check(h.gates[0].bytes === 'two', 'it wrote the revision it captured ("two")')+ check(h.store.dirty === true, 'the document is STILL DIRTY after the older write resolved')+ const second = h.save()+ await h.tick()+ check(h.gates[1]?.bytes === 'three', 'the edit reaches the next write')+ h.gates[1]?.release()+ const out2 = await second+ check(out2.kind === 'written' && out2.current, 'the next write is current')+ check(h.store.dirty === false, 'and only then does the dot go out')+}++console.log('\na keystroke inside a typing run while the write is in flight')+{+ const h = harness()+ h.type('ty')+ const first = h.save() // closes the run, then snapshots+ await h.tick()+ h.type('typ') // a NEW run, mid-write+ h.gates[0].release()+ await first+ check(h.gates[0].bytes === 'ty', 'the write holds the text as it was at ⌘S')+ check(h.store.dirty === true, 'the keystroke typed during the write keeps the dot on')+}++console.log('\na failed write')+{+ const h = harness()+ h.edit('two')+ const first = h.save()+ await h.tick()+ h.gates[0].fail(new Error('disk full'))+ const out = await first+ check(out.kind === 'failed' && (out as any).error?.message === 'disk full', 'the failure is reported, not swallowed or thrown')+ check(h.store.dirty === true, 'a failed write leaves the document dirty')+ const again = h.save()+ await h.tick()+ check(h.gates.length === 2 && h.gates[1].bytes === 'two', 'the queue is not poisoned: the next save writes')+ h.gates[1]?.release()+ const out2 = await again+ check(out2.kind === 'written' && out2.current && h.store.dirty === false, 'and that one clears the dot')+}++console.log('\nback-to-back saves')+{+ const h = harness()+ h.edit('two')+ const a = h.save()+ const b = h.save() // pressed again before the first landed+ await h.tick()+ check(h.gates.length === 1, 'the second write waits for the first (no overlap on one handle)')+ h.edit('three')+ h.gates[0].release()+ const outA = await a+ await h.tick()+ check(outA.kind === 'written' && !outA.current && h.store.dirty === true, 'the first is stale and the dot stays on')+ check(h.gates.length === 2 && h.gates[1].bytes === 'three', 'the second captured its revision only when it STARTED')+ h.gates[1]?.release()+ const outB = await b+ check(outB.kind === 'written' && outB.current && h.store.dirty === false, 'the second is current and clears the dot')+ check(h.maxOpen() === 1, 'never more than one write open at once')+}++console.log('\na remote change while the write is in flight')+{+ const h = harness()+ h.edit('two')+ const first = h.save()+ await h.tick()+ // what the kernel session does: mutate doc directly, then setDirty(true)+ h.store.doc.pages[0].blocks[0].html = 'remote'+ h.store.setDirty(true)+ h.gates[0].release()+ const out = await first+ check(out.kind === 'written' && !out.current && h.store.dirty === true, 'a colleague’s edit mid-write keeps the dot on')+}++console.log('\nan undo while the write is in flight')+{+ const h = harness()+ h.edit('two')+ const first = h.save()+ await h.tick()+ h.store.undo()+ h.gates[0].release()+ const out = await first+ check(out.kind === 'written' && !out.current && h.store.dirty === true, 'an undo mid-write keeps the dot on')+ check(h.html() === 'one', 'and the undo held')+}++// ---- collab.sync is stamped in the queue's prepare (#594 × the save queue) ---+// The stamp must describe exactly the bytes written: taken after any write+// ahead of this one, immediately before the snapshot is copied. `started` is+// that prepare step, so a stamp made there must be IN the snapshot the write+// receives, and a save queued behind another stamps at its own start.+console.log('\ncollab.sync is stamped in prepare, inside the snapshot')+{+ const p = parseSpace(JSON.stringify({ format: 'bento/spaces', version: 1, docId: 'stamp', title: 'Stamp', pages: [{ id: 'p', title: 'Page', blocks: [{ id: 'b', type: 'p', html: 'one' }] }] }))+ assert(p.ok)+ const store = new SpacesStore(p.doc)+ const queue = new SaveQueue({ getDocument: () => store.doc, getRevision: () => store.revision })+ let n = 0+ const stamp = () => { (store.doc as any).collab = { sync: { mark: ++n } } }+ const written: number[] = []+ const gates: Array<() => void> = []+ const write = (snapshot: any) => new Promise<'saved'>((resolve) => {+ written.push(snapshot.collab?.sync?.mark ?? 0)+ gates.push(() => resolve('saved'))+ })+ const tick = async () => { for (let i = 0; i < 5; i++) await Promise.resolve() }+ store.commit(() => { store.doc.pages[0].blocks[0].html = 'two' })+ const a = saveRevision(store, queue, write, stamp)+ const b = saveRevision(store, queue, write, stamp)+ await tick()+ check(written.length === 1 && written[0] === 1, 'the first write carries the stamp made in its own prepare')+ gates[0]()+ await a+ await tick()+ check(written.length === 2 && written[1] === 2, 'a save queued behind it stamps again at its own start, not when it was asked for')+ gates[1]()+ const out = await b+ check(out.kind === 'written' && out.current, 'stamping in prepare does not make the write stale')+}++// The wiring: the code ⌘S and "Update this file" run passes the stamp into+// the queue's prepare. Removing it fails no behavioural rig on its own (#594's+// proof of this path was a browser probe), so the call sites are pinned here.+console.log('\nmain.ts stamps inside the queue for both writes of this file')+{+ const { readFileSync } = await import('node:fs')+ const src = readFileSync(new URL('../spaces/src/main.ts', import.meta.url), 'utf8')+ const doSave = src.match(/saveRevision\(store, saves,[\s\S]*?\)\)/)?.[0] ?? ''+ check(/stampSync\(store, session\)/.test(doSave), '⌘S passes stampSync as the prepare step of saveRevision')+ const inPlace = src.match(/editor\.onUpdateInPlace = async[\s\S]*?saves\.run\(([\s\S]*?)applyUpdateInPlace/)?.[1] ?? ''+ check(/stampSync\(store, session\)/.test(inPlace), '"Update this file" stamps in the queue\'s prepare too')+}++if (failures) { console.error(`\n${failures} save-race check(s) FAILED`); process.exit(1) }+console.log('\nspaces save race: an edit made during a write stays unsaved until a write that holds it lands')diff --git a/scripts/test-spaces.mjs b/scripts/test-spaces.mjsindex ae197b89..1f24b4bf 100755--- a/scripts/test-spaces.mjs+++ b/scripts/test-spaces.mjs@@ -51,6 +51,10 @@ const RIGS = [{ name: 'invite', file: 'scripts/test-spaces-invite.ts', bundle: true },{ name: 'roundtrip', file: 'scripts/test-spaces-roundtrip.ts', bundle: true },{ name: 'size', file: 'scripts/test-spaces-size.mjs' },+ // Revision tracking has no timezone dependency; the browser rig needs the+ // built spaces shell and Playwright/Chrome (the CI browser job provides both).+ { name: 'save-revisions', file: 'scripts/test-spaces-save-revisions.ts' },+ { name: 'save-browser', file: 'scripts/test-spaces-save-browser.mjs' },]// A rig that exists but is not listed here would never run locally, and thediff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.mdindex fe81769a..ee61842b 100644--- a/spaces/CHANGELOG.md+++ b/spaces/CHANGELOG.md@@ -508,6 +508,18 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.writes, anything else opens view-only. Every gate — the boot lock, the Sharepopover, the People label — asks that one function. Plain files and legacyrooms open exactly as before.+- **Fixed: an edit made while the file was being written could be marked saved.**+ Saving takes a moment — the file is reconnected, the space is written out,+ the disk answers — and a word typed in that moment went into the space after+ the file's copy had already been taken. When the write finished, the unsaved+ dot went out anyway, so the file was missing the edit and nothing said so.+ Now each save writes the space exactly as it was when that save began, and+ the dot goes out only if nothing has changed since. Anything newer — your own+ typing, a colleague's edit arriving live, an undo — keeps the dot on and goes+ into the next save. Two saves in quick succession wait for each other instead+ of writing the file at the same time, and so does "Update this file" in+ About. A save that fails now says so ("Save failed — see console") instead of+ leaving "Saving…" on screen, and the space stays unsaved.## [0.1.0] — 2026-08-03diff --git a/spaces/src/about.ts b/spaces/src/about.tsindex 5d2fc007..c91c1501 100644--- a/spaces/src/about.ts+++ b/spaces/src/about.ts@@ -27,9 +27,9 @@// and nothing added later can be made to by raising its own z-index.import {- checkForUpdates, applyUpdate, applyUpdateInPlace, canUpdateInPlace,+ checkForUpdates, applyUpdate, canUpdateInPlace,autoCheckEnabled, setAutoCheck, compareVersions,- APP_VERSION, type ReleaseInfo, type UpdateCheck,+ APP_VERSION, type ReleaseInfo, type UpdateCheck, type InPlaceOutcome,} from '../../kernel/src/update.ts'import {setEncryptionPassword, isEncryptionActive,@@ -77,9 +77,18 @@ export interface AboutHooks {/** the editor's status line, for the confirmations that outlive the dialog */onStatus?: (message: string) => void/**- * Called immediately before a self-update writes THIS document into a new- * shell — stamps the live session's CRDT state (share.ts stampSync), so the- * updated file rejoins as a fork exactly as a ⌘S-saved one does.+ * "Update this file" — the kernel's applyUpdateInPlace, run through main.ts's+ * save queue. NOT called directly from here: it rewrites the same file ⌘S+ * does, so the two must never be open on one handle at once, and only the+ * queue's acknowledgement may say the disk holds what is on screen.+ * null = nothing was written (cancelled, or the space was swapped).+ */+ onUpdateInPlace: (release: ReleaseInfo) => Promise<InPlaceOutcome | null>+ /**+ * Called immediately before "Download updated copy" writes THIS document+ * into a new shell — stamps the live session's CRDT state (share.ts+ * stampSync), so the updated file rejoins as a fork exactly as a ⌘S-saved+ * one does. "Update this file" is stamped inside the save queue instead.*/onBeforeWrite?: () => void}@@ -106,7 +115,7 @@ export async function launchUpdateCheck(): Promise<void> {}export function openAbout(hooks: AboutHooks): void {- const { store, onRepaint, onSaveCopy, onImport, onExportSpace, onWriteCopy, onStatus, onBeforeWrite } = hooks+ const { store, onRepaint, onSaveCopy, onImport, onExportSpace, onWriteCopy, onStatus, onUpdateInPlace, onBeforeWrite } = hooksconst doc = store.docconst returnFocus = document.activeElement as HTMLElement | null@@ -384,8 +393,7 @@ export function openAbout(hooks: AboutHooks): void {inPlace.disabled = trueinPlace.textContent = t('Verifying…')try {- onBeforeWrite?.()- const written = await applyUpdateInPlace(rel, store.doc)+ const written = await onUpdateInPlace(rel)if (written) {box.replaceChildren(updatedCard(rel, written.backup))} else {@@ -441,8 +449,11 @@ export function openAbout(hooks: AboutHooks): void {? t('This window is still running v{v} — reload to finish. A v{v} backup was downloaded.', { v: APP_VERSION }): t("This window is still running v{v}. If you overwrote the file that's open here, reload; otherwise open the file you saved.", { v: APP_VERSION }),))+ // No `store.dirty = false` here any more: whether the disk holds this exact+ // document is the save queue's to say, and it already said so when the+ // update was written (main.ts onUpdateInPlace). An edit typed since then is+ // NOT on disk, and clearing the dot for it would be the race all over again.done.append(actions(button(t('Reload into new version'), () => {- store.dirty = false // disk already holds this exact documentlocation.reload()}, true)))return donediff --git a/spaces/src/editor.ts b/spaces/src/editor.tsindex 5bc1558d..150ec76d 100644--- a/spaces/src/editor.ts+++ b/spaces/src/editor.ts@@ -175,6 +175,9 @@ export class Editor {*/onShareCopy: ((doc: SpacesDoc, suffix: string) => Promise<boolean>) | null = nullonPrint: (() => void) | null = null+ /** About's "Update this file" — supplied by main.ts, which owns the save queue */+ onUpdateInPlace: ((release: import('../../kernel/src/update.ts').ReleaseInfo) =>+ Promise<import('../../kernel/src/update.ts').InPlaceOutcome | null>) | null = nullconstructor(root: HTMLElement, store: Store) {this.root = root@@ -5211,6 +5214,7 @@ export class Editor {// handle, which is what leaves you editing this space afterwards.onWriteCopy: (out) => this.onExportSpace?.(out) ?? Promise.resolve(false),onStatus: (msg) => this.status(msg),+ onUpdateInPlace: (rel) => this.onUpdateInPlace?.(rel) ?? Promise.resolve(null),// both self-update writes carry this space's CRDT state, as ⌘S doesonBeforeWrite: () => shareModule.stampSync(this.store, this.session),})diff --git a/spaces/src/i18n/de.ts b/spaces/src/i18n/de.tsindex 29921266..19fbd301 100644--- a/spaces/src/i18n/de.ts+++ b/spaces/src/i18n/de.ts@@ -390,6 +390,7 @@ export const de: Catalog = {"Save an untouched copy…": "Unveränderte Kopie speichern…","Saved": "Gespeichert","Saved a new copy": "Neue Kopie gespeichert",+ "Save failed — see console": "Speichern fehlgeschlagen — siehe Konsole","Saves a copy that joins this session": "Speichert eine Kopie, die dieser Sitzung beitritt","Saves a copy to send. Whoever opens it edits this space live with you (end-to-end encrypted); you stay the owner and can remove them from the People list.": "Speichert eine Kopie zum Versenden. Wer sie öffnet, bearbeitet diesen Space live mit dir (Ende-zu-Ende-verschlüsselt); du bleibst Eigentümer und kannst sie aus der Personenliste entfernen.","Saving…": "Speichere…",diff --git a/spaces/src/i18n/es.ts b/spaces/src/i18n/es.tsindex 772b824f..88abbb1d 100644--- a/spaces/src/i18n/es.ts+++ b/spaces/src/i18n/es.ts@@ -390,6 +390,7 @@ export const es: Catalog = {"Save an untouched copy…": "Guardar una copia intacta…","Saved": "Guardado","Saved a new copy": "Se guardó una copia nueva",+ "Save failed — see console": "Error al guardar — mira la consola","Saves a copy that joins this session": "Guarda una copia que se une a esta sesión","Saves a copy to send. Whoever opens it edits this space live with you (end-to-end encrypted); you stay the owner and can remove them from the People list.": "Guarda una copia para enviar. Quien la abra editará este Space en vivo contigo (cifrado de extremo a extremo); tú sigues siendo el propietario y puedes quitarlos de la lista de Personas.","Saving…": "Guardando…",diff --git a/spaces/src/i18n/fr.ts b/spaces/src/i18n/fr.tsindex a7042f28..4712f8c1 100644--- a/spaces/src/i18n/fr.ts+++ b/spaces/src/i18n/fr.ts@@ -390,6 +390,7 @@ export const fr: Catalog = {"Save an untouched copy…": "Enregistrer une copie sans toucher à l’original…","Saved": "Enregistré","Saved a new copy": "Nouvelle copie enregistrée",+ "Save failed — see console": "Échec de l’enregistrement — voir la console","Saves a copy that joins this session": "Enregistre une copie qui rejoint cette session","Saves a copy to send. Whoever opens it edits this space live with you (end-to-end encrypted); you stay the owner and can remove them from the People list.": "Enregistre une copie à envoyer. Qui l’ouvre édite cet espace en direct avec vous (chiffré de bout en bout) ; vous restez propriétaire et pouvez les retirer de la liste Personnes.","Saving…": "Enregistrement…",diff --git a/spaces/src/i18n/it.ts b/spaces/src/i18n/it.tsindex a4f1c6af..360fa076 100644--- a/spaces/src/i18n/it.ts+++ b/spaces/src/i18n/it.ts@@ -390,6 +390,7 @@ export const it: Catalog = {"Save an untouched copy…": "Salva una copia senza toccare l’originale…","Saved": "Salvato","Saved a new copy": "Salvata una nuova copia",+ "Save failed — see console": "Salvataggio non riuscito — vedi console","Saves a copy that joins this session": "Salva una copia che entra in questa sessione","Saves a copy to send. Whoever opens it edits this space live with you (end-to-end encrypted); you stay the owner and can remove them from the People list.": "Salva una copia da inviare. Chi la apre modifica questo Space live con te (crittografia end-to-end); resti il proprietario e puoi rimuoverli dall’elenco Persone.","Saving…": "Salvataggio…",diff --git a/spaces/src/i18n/ja.ts b/spaces/src/i18n/ja.tsindex 89841877..d2955f0c 100644--- a/spaces/src/i18n/ja.ts+++ b/spaces/src/i18n/ja.ts@@ -390,6 +390,7 @@ export const ja: Catalog = {"Save an untouched copy…": "元のままのコピーを保存…","Saved": "保存しました","Saved a new copy": "新しいコピーを保存しました",+ "Save failed — see console": "保存に失敗 — コンソールを確認","Saves a copy that joins this session": "このセッションに参加するコピーを保存します","Saves a copy to send. Whoever opens it edits this space live with you (end-to-end encrypted); you stay the owner and can remove them from the People list.": "送るためのコピーを保存します。開いた人はこの Space をあなたと一緒にライブ編集できます(エンドツーエンド暗号化)。あなたはオーナーのままで、メンバーリストからいつでも削除できます。","Saving…": "保存中…",diff --git a/spaces/src/i18n/packed.ts b/spaces/src/i18n/packed.tsindex 2ed45fd6..94c48b26 100644--- a/spaces/src/i18n/packed.ts+++ b/spaces/src/i18n/packed.ts@@ -403,6 +403,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Save (⌘S)": ["保存 (⌘S)","保存 (⌘S)","儲存 (⌘S)","Guardar (⌘S)","Enregistrer (⌘S)","Speichern (⌘S)","Salva (⌘S)","Guardar (⌘S)"],"Save a copy…": ["コピーを保存…","保存副本…","儲存副本…","Guardar una copia…","Enregistrer une copie…","Kopie speichern…","Salva una copia…","Guardar uma cópia…"],"Save an untouched copy…": ["元のままのコピーを保存…","另存副本,原文件不动…","儲存原封不動的副本…","Guardar una copia intacta…","Enregistrer une copie sans toucher à l’original…","Unveränderte Kopie speichern…","Salva una copia senza toccare l’originale…","Guardar uma cópia intacta…"],+ "Save failed — see console": ["保存に失敗 — コンソールを確認","保存失败 — 请查看控制台","儲存失敗 — 請查看主控台","Error al guardar — mira la consola","Échec de l’enregistrement — voir la console","Speichern fehlgeschlagen — siehe Konsole","Salvataggio non riuscito — vedi console","Falha ao guardar — vê a consola"],"Saved": ["保存しました","已保存","已儲存","Guardado","Enregistré","Gespeichert","Salvato","Guardado"],"Saved a new copy": ["新しいコピーを保存しました","已保存新副本","已儲存新副本","Se guardó una copia nueva","Nouvelle copie enregistrée","Neue Kopie gespeichert","Salvata una nuova copia","Nova cópia guardada"],"Saves a copy to send. Whoever opens it edits this space live with you (end-to-end encrypted); you stay the owner and can remove them from the People list.": ["送るためのコピーを保存します。開いた人はこの Space をあなたと一緒にライブ編集できます(エンドツーエンド暗号化)。あなたはオーナーのままで、メンバーリストからいつでも削除できます。","保存一份用于发送的副本。打开的人可与你实时共同编辑此 Space(端到端加密);你仍是所有者,可随时从成员列表中移除他们。","儲存一份用於傳送的副本。開啟的人可與你即時共同編輯此 Space(端對端加密);你仍是擁有者,可隨時從成員列表中移除他們。","Guarda una copia para enviar. Quien la abra editará este Space en vivo contigo (cifrado de extremo a extremo); tú sigues siendo el propietario y puedes quitarlos de la lista de Personas.","Enregistre une copie à envoyer. Qui l’ouvre édite cet espace en direct avec vous (chiffré de bout en bout) ; vous restez propriétaire et pouvez les retirer de la liste Personnes.","Speichert eine Kopie zum Versenden. Wer sie öffnet, bearbeitet diesen Space live mit dir (Ende-zu-Ende-verschlüsselt); du bleibst Eigentümer und kannst sie aus der Personenliste entfernen.","Salva una copia da inviare. Chi la apre modifica questo Space live con te (crittografia end-to-end); resti il proprietario e puoi rimuoverli dall’elenco Persone.","Salva uma cópia para enviar. Quem a abrir edita este Space ao vivo com você (com criptografia de ponta a ponta); você continua sendo o dono e pode removê-la na lista de Pessoas."],diff --git a/spaces/src/i18n/pt.ts b/spaces/src/i18n/pt.tsindex 0e26b5a6..13845acf 100644--- a/spaces/src/i18n/pt.ts+++ b/spaces/src/i18n/pt.ts@@ -390,6 +390,7 @@ export const pt: Catalog = {"Save an untouched copy…": "Guardar uma cópia intacta…","Saved": "Guardado","Saved a new copy": "Nova cópia guardada",+ "Save failed — see console": "Falha ao guardar — vê a consola","Saves a copy that joins this session": "Guarda uma cópia que entra nesta sessão","Saves a copy to send. Whoever opens it edits this space live with you (end-to-end encrypted); you stay the owner and can remove them from the People list.": "Salva uma cópia para enviar. Quem a abrir edita este Space ao vivo com você (com criptografia de ponta a ponta); você continua sendo o dono e pode removê-la na lista de Pessoas.","Saving…": "A guardar…",diff --git a/spaces/src/i18n/zh-Hans.ts b/spaces/src/i18n/zh-Hans.tsindex f97f50a2..58a05195 100644--- a/spaces/src/i18n/zh-Hans.ts+++ b/spaces/src/i18n/zh-Hans.ts@@ -390,6 +390,7 @@ export const zh_Hans: Catalog = {"Save an untouched copy…": "另存副本,原文件不动…","Saved": "已保存","Saved a new copy": "已保存新副本",+ "Save failed — see console": "保存失败 — 请查看控制台","Saves a copy that joins this session": "保存一个会加入此会话的副本","Saves a copy to send. Whoever opens it edits this space live with you (end-to-end encrypted); you stay the owner and can remove them from the People list.": "保存一份用于发送的副本。打开的人可与你实时共同编辑此 Space(端到端加密);你仍是所有者,可随时从成员列表中移除他们。","Saving…": "保存中…",diff --git a/spaces/src/i18n/zh-Hant.ts b/spaces/src/i18n/zh-Hant.tsindex 85526d58..8aa746d0 100644--- a/spaces/src/i18n/zh-Hant.ts+++ b/spaces/src/i18n/zh-Hant.ts@@ -390,6 +390,7 @@ export const zh_Hant: Catalog = {"Save an untouched copy…": "儲存原封不動的副本…","Saved": "已儲存","Saved a new copy": "已儲存新副本",+ "Save failed — see console": "儲存失敗 — 請查看主控台","Saves a copy that joins this session": "儲存一份會加入此工作階段的副本","Saves a copy to send. Whoever opens it edits this space live with you (end-to-end encrypted); you stay the owner and can remove them from the People list.": "儲存一份用於傳送的副本。開啟的人可與你即時共同編輯此 Space(端對端加密);你仍是擁有者,可隨時從成員列表中移除他們。","Saving…": "儲存中…",diff --git a/spaces/src/main.ts b/spaces/src/main.tsindex 7b5f64d2..4b3650b0 100644--- a/spaces/src/main.ts+++ b/spaces/src/main.ts@@ -4,6 +4,8 @@// capture the pristine document BEFORE any DOM mutation — the captured copy is// what gets re-serialized on save.+import { SaveQueue } from '../../kernel/src/savequeue.ts'+import { saveRevision } from './saving'import './styles.css'import { configureApp, appConfig } from '../../kernel/src/app.ts'import { startTheme } from '../../kernel/src/theme.ts'@@ -14,7 +16,7 @@ import {isEncryptionActive,} from '../../kernel/src/save.ts'import { putRecovery, getRecovery, clearRecovery, pruneOld, addVersion } from '../../kernel/src/autosave.ts'-import { APP_VERSION } from '../../kernel/src/update.ts'+import { APP_VERSION, applyUpdateInPlace } from '../../kernel/src/update.ts'import { t, locale, applyDirection } from './i18n'import { i18nApi } from '../../kernel/src/i18n.ts'import { parseDoc, docContentKey, uid, newPage, type SpacesDoc, type ParseResult } from './model'@@ -198,6 +200,7 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')document.getElementById('bento-splash')?.remove()const store = new Store(doc)+ const saves = new SaveQueue({ getDocument: () => store.doc, getRevision: () => store.revision })// `doc.readonly` was declared in the format and read by NOTHING: a space// saved as a reading copy opened fully editable, so the one property the// sender chose was the one the file did not keep. It is not a security@@ -316,28 +319,32 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')let lastVersionAt = 0async function doSave(): Promise<void> {- store.endRun()- editor.status(t('Saving…'))- // Stamped at the moment the document is taken for the write, and nowhere- // earlier: the state must describe exactly the bytes that reach the file,- // or the registers restored on reopen defend the wrong values. When the- // save queue lands this moves into its prepare step, beside the snapshot.- stampSync(store, session)- const res = await saveFile(store.doc)- if (res === 'saved' || res === 'saved-as' || res === 'downloaded') {- // the document is on disk now — the dot goes out- store.dirty = false- editor.syncDirty()+ // Every write of THIS file goes through `saves` (the in-place self-update+ // too, below): the queue keeps two writes from overlapping on one handle,+ // and saving.ts clears the dot only if nothing changed while the bytes were+ // being written. The copies and share exports stay outside it on purpose —+ // they write a DIFFERENT file and never keep its handle.+ // collab.sync is stamped in the queue's prepare step: after any write+ // ahead of this one, immediately before the snapshot is copied, so the+ // state describes exactly the bytes that reach the file (#594).+ const out = await saveRevision(store, saves, (snapshot) => saveFile(snapshot),+ () => { stampSync(store, session); editor.status(t('Saving…')) })+ if (out.kind === 'failed') {+ console.error('bento/spaces: save failed', out.error)+ editor.status(t('Save failed — see console'))+ return}- if (res === 'saved' || res === 'saved-as' || res === 'downloaded') {- // A SAVE IS THE MOMENT WORTH KEEPING. The throttle below catches long- // editing runs, but the point somebody chose to write the file is the- // point they would most want back, so it is never throttled away.- // Encrypted spaces keep nothing here, for the reason putRecovery does not.- if (!isEncryptionActive()) { void addVersion(store.doc); lastVersionAt = Date.now() }- }- if (res === 'saved') {- void clearRecovery(store.doc.docId)+ if (out.kind !== 'written') { editor.status(''); return }+ // A SAVE IS THE MOMENT WORTH KEEPING. The throttle below catches long+ // editing runs, but the point somebody chose to write the file is the+ // point they would most want back, so it is never throttled away. The+ // version is the snapshot that was WRITTEN, not whatever is on screen now.+ // Encrypted spaces keep nothing here, for the reason putRecovery does not.+ if (!isEncryptionActive()) { void addVersion(out.doc); lastVersionAt = Date.now() }+ if (out.result === 'saved' && out.current) {+ // Only when the disk holds what is on screen: after a stale write the+ // recovery snapshot is the one copy of the newer edit.+ void clearRecovery(out.doc.docId)// "Saved" is doing real work here: on a browser without file-system// access this was a NEW download, and saying so is the difference// between understanding that and losing track of which copy is current@@ -347,6 +354,22 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')}}+ /**+ * The in-place self-update rewrites the SAME file ⌘S does, so it takes the+ * same queue: without it an update and a save could be open on one handle at+ * once, and whichever closed last would decide which shell the file ends up+ * as. It writes the queue's snapshot, and — like a save — clears the dot only+ * when that snapshot is still the document on screen.+ */+ editor.onUpdateInPlace = async (rel) => {+ // stamped in prepare, beside the snapshot, exactly as ⌘S is+ const saved = await saves.run(() => { store.endRun(); stampSync(store, session) },+ (snapshot) => applyUpdateInPlace(rel, snapshot))+ if (!saved?.value) return null+ if (saved.isCurrent()) store.setDirty(false)+ return saved.value+ }+// A recovery snapshot is the ONLY backstop on browsers with no file-system// access — which is every browser on iOS.//diff --git a/spaces/src/saving.ts b/spaces/src/saving.tsnew file mode 100644index 00000000..a39b8b7f--- /dev/null+++ b/spaces/src/saving.ts@@ -0,0 +1,66 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// ⌘S, 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. `saveFile` awaits (a handle+// reconnect, the serializer, the disk), and an edit made in that window landed+// in the live document after the bytes were taken — then the resolve cleared+// the dot, so the file on disk was missing the edit and nothing on screen said+// so. The kernel's SaveQueue (kernel/src/savequeue.ts) captures a detached+// snapshot before each write and answers `isCurrent()` at acknowledgement time;+// this module is the app's side of that contract, kept out of main.ts so the+// rig drives the same code the button does (scripts/test-spaces-save-revisions.ts).+//+// Policy that stays here and NOT in the kernel: which store event clears the+// dot, that a typing run closes before the snapshot, and what counts as failure.++import type { SaveQueue } from '../../kernel/src/savequeue.ts'+import type { SpacesDoc } from './model'+import type { Store } from './store'++/** What `saveFile` answers; 'cancelled' is the picker closed. */+export type WriteResult = 'saved' | 'saved-as' | 'downloaded' | 'cancelled'++export type SaveOutcome =+ /** the space 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 document+ * on screen — false means an edit landed while the write was in flight, and+ * the dot stays on for it.+ */+ | { kind: 'written'; result: Exclude<WriteResult, 'cancelled'>; doc: SpacesDoc; current: boolean }++/**+ * Write the space through the queue and acknowledge only its own revision.+ *+ * `started` runs when THIS write actually begins (after any write ahead of it),+ * after the typing run has closed — closing the run raises 'doc', which paints+ * "Edited", so a status set before it would be overwritten at once.+ */+export async function saveRevision(+ store: Store,+ queue: SaveQueue<SpacesDoc>,+ write: (snapshot: SpacesDoc) => Promise<WriteResult>,+ started?: () => void,+): Promise<SaveOutcome> {+ let saved+ try {+ saved = await queue.run(() => { store.endRun(); started?.() }, 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 is what repaints+ // the dot, and it never advances the revision when clearing.+ if (current) store.setDirty(false)+ return { kind: 'written', result, doc: saved.doc, current }+}diff --git a/spaces/src/store.ts b/spaces/src/store.tsindex 230e433a..5064ae2e 100644--- a/spaces/src/store.ts+++ b/spaces/src/store.ts@@ -101,6 +101,8 @@ export class Store {* is "the file IS the document" is the one thing it should say.*/dirty = false+ /** Every mutation, even within a typing run or while already dirty. */+ revision = 0private undoStack: Entry[] = []private redoStack: Entry[] = []@@ -123,6 +125,7 @@ export class Store {}emit(ev: Event): void {+ if (ev === 'doc') this.revision++for (const fn of this.listeners.get(ev) ?? []) fn()}@@ -216,6 +219,7 @@ export class Store {/** Model changed without a new undo entry (mid-run). */touch(): void {+ this.revision++// A typing run deliberately does NOT emit 'doc' per keystroke — that is the// whole point of the run. But the FIRST keystroke changes something the// reader can see: the file now differs from the disk. Announce that once,@@ -238,6 +242,8 @@ export class Store {* a colleague's keystroke must move the dot without claiming to be yours.*/setDirty(v: boolean): void {+ // Remote apply calls this even when the dirty flag is already set.+ if (v) this.revision++if (this.dirty === v) returnthis.dirty = v// NOT 'doc'. The editor reads 'doc' as "you edited something" and paints