Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

spaces: the older-copy recovery warning and the recovery-off notice (#746)

nyblnet63910f711f76
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index cd31d078..f07a1ca2 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -2601,3 +2601,10 @@ jobs:
run: node scripts/test-spaces-fields-browser.mjs
- name: An encrypted space opens (one password gate, no loader failure)
run: node scripts/test-spaces-encrypted-browser.mjs
+ - name: Spaces recovery banner and recovery-off notice in Chromium
+ # An older recovery snapshot gets the warning with "Keep the file" the
+ # focused default (keeping deletes nothing; "Restore anyway" restores);
+ # a newer or equal one the plain banner that claims nothing; a host
+ # that refuses the recovery copy gets the notice once, held to read;
+ # pt and de show slides' words. Planted in bento-spaces-autosave.
+ run: node scripts/test-spaces-recovery-browser.mjs
diff --git a/scripts/test-spaces-recovery-browser.mjs b/scripts/test-spaces-recovery-browser.mjs
new file mode 100644
index 00000000..b72e9a1e
--- /dev/null
+++ b/scripts/test-spaces-recovery-browser.mjs
@@ -0,0 +1,265 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The crash-recovery banner's older-copy warning, and the recovery-off notice,
+// in the packaged bento/spaces.
+//
+// npm run build:single --prefix spaces && node scripts/test-spaces-recovery-browser.mjs
+//
+// WHAT THIS PROVES (maintainer rulings 2026-10-15, shared with slides and type;
+// slides' test-slides-save-copy-browser.mjs and
+// test-slides-recovery-off-browser.mjs are the reference):
+// 1. a recovery snapshot OLDER than the open file gets the warning — "This
+// recovered copy looks older than the file you opened. Keep the file
+// unless you know it’s newer." — with "Keep the file" first, primary and
+// FOCUSED, and "Restore anyway" still on offer;
+// 2. "Keep the file" keeps the file and deletes nothing; "Restore anyway"
+// restores the snapshot;
+// 3. a snapshot that is NOT older gets spaces' plain banner, which claims
+// nothing about "newer" or "safe";
+// 4. under a host whose per-document store refuses the recovery copy, the
+// save status says crash recovery is off, ONCE, held long enough to read;
+// a host that keeps it gets no message;
+// 5. Portuguese and German show slides' exact words.
+//
+// THE DATABASE IS PINNED: `bento-spaces-autosave` (kernel autosave.ts:
+// `${appId}-autosave`). A legacy shared `bento-autosave` can sit beside it;
+// planting there would test nothing.
+//
+// Served from 127.0.0.1 (the origin a file:// copy does not share), offline.
+import { readFileSync } from 'node:fs'
+import { createServer } from 'node:http'
+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 DB = 'bento-spaces-autosave'
+const OLDER = 'This recovered copy looks older than the file you opened. Keep the file unless you know it’s newer.'
+const PLAIN = 'Unsaved changes from a previous session were found.'
+const NOTICE = 'Crash recovery is off for this space — it’s too large to keep a backup copy. Save often.'
+const shellPath = new URL('../spaces/dist-single/Bento_Spaces.bento.html', import.meta.url)
+const shell = readFileSync(shellPath, 'utf8')
+
+// a catalog value, read from the catalog file (slides' for the shared strings)
+const catalog = (app, loc, key) => {
+ const src = readFileSync(new URL(`../${app}/src/i18n/${loc}.ts`, import.meta.url), 'utf8')
+ const line = src.split('\n').find((l) => l.startsWith(` ${JSON.stringify(key)}: `))
+ return line ? JSON.parse(line.slice(line.indexOf(': ') + 2).replace(/,$/, '')) : undefined
+}
+
+const routes = new Map([['/blank.html', shell]])
+const server = createServer((q, r) => {
+ const body = routes.get(new URL(q.url, 'http://x').pathname)
+ if (body === undefined) { r.writeHead(404); r.end(); return }
+ r.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' }); r.end(body)
+})
+await new Promise((res) => server.listen(0, '127.0.0.1', res))
+const base = `http://127.0.0.1:${server.address().port}`
+
+const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH, headless: true })
+const newCtx = async () => {
+ const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } })
+ await ctx.route((u) => !u.href.startsWith(base), (r) => r.abort())
+ return ctx
+}
+try {
+ // A saved space with a fixed docId and modified time, spliced into the shell.
+ const MODIFIED = '2026-10-10T12:00:00.000Z'
+ const MS = Date.parse(MODIFIED)
+ let doc
+ {
+ const ctx = await newCtx()
+ const p = await ctx.newPage()
+ await p.goto(base + '/blank.html')
+ await p.waitForFunction(() => window.bento?.doc)
+ doc = await p.evaluate((m) => { const d = JSON.parse(JSON.stringify(window.bento.doc)); d.docId = 'rig-recovery-space'; d.modified = m; delete d.collab; return d }, MODIFIED)
+ await ctx.close()
+ }
+ const open = '<script type="application/bento+json" id="bento-doc">'
+ const i = shell.indexOf(open) + open.length, j = shell.indexOf('</' + 'script>', i)
+ routes.set('/space.html', shell.slice(0, i) + JSON.stringify(doc).replace(/</g, '\\u003c') + shell.slice(j))
+
+ /** Open the space with a recovery snapshot taken at `at` planted in SPACES' own database. */
+ async function withSnapshot(at, lang) {
+ const ctx = await newCtx()
+ if (lang) await ctx.addInitScript((l) => { try { localStorage.setItem('bento-lang', l) } catch {} }, lang)
+ const p = await ctx.newPage()
+ const errors = []
+ p.on('pageerror', (e) => errors.push(e.message))
+ await p.goto(base + '/space.html')
+ await p.waitForFunction(() => window.bento?.doc)
+ await p.evaluate(async ([d, when, name]) => {
+ const db = await new Promise((res, rej) => {
+ const r = indexedDB.open(name, 1)
+ // the kernel's own stores, should the app not have opened it yet
+ r.onupgradeneeded = () => {
+ if (!r.result.objectStoreNames.contains('recovery')) r.result.createObjectStore('recovery', { keyPath: 'docId' })
+ if (!r.result.objectStoreNames.contains('versions')) r.result.createObjectStore('versions', { keyPath: 'id', autoIncrement: true }).createIndex('docId', 'docId', { unique: false })
+ }
+ r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error)
+ })
+ const snap = JSON.parse(JSON.stringify(d)); snap.title = 'Recovered edits'
+ await new Promise((res, rej) => { const tx = db.transaction('recovery', 'readwrite'); tx.objectStore('recovery').put({ docId: d.docId, at: when, title: snap.title, json: JSON.stringify(snap) }); tx.oncomplete = res; tx.onerror = () => rej(tx.error) })
+ db.close()
+ }, [doc, at, DB])
+ await p.reload()
+ await p.waitForFunction(() => window.bento?.doc)
+ await p.waitForSelector('.sp-banner', { timeout: 8000 }).catch(() => {})
+ await p.waitForTimeout(300)
+ return { ctx, p, errors }
+ }
+ const bannerOf = (p) => p.evaluate(() => {
+ const b = [...document.querySelectorAll('.sp-banner')].find((x) => [...x.querySelectorAll('button')].some((y) => y.textContent !== '✕'))
+ if (!b) return null
+ return {
+ text: b.querySelector('span')?.textContent ?? '',
+ buttons: [...b.querySelectorAll('button')].map((x) => x.textContent).filter((x) => x !== '✕'),
+ primary: [...b.querySelectorAll('button.sp-primary')].map((x) => x.textContent),
+ focused: b.contains(document.activeElement) ? document.activeElement.textContent : null,
+ }
+ })
+ const held = (p, name) => p.evaluate(async ([id, db]) => {
+ const d = await new Promise((res, rej) => { const r = indexedDB.open(db); r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error) })
+ const row = await new Promise((res) => { const tx = d.transaction('recovery', 'readonly'); const g = tx.objectStore('recovery').get(id); g.onsuccess = () => res(g.result ?? null); g.onerror = () => res(null) })
+ d.close()
+ return row ? { at: row.at, title: row.title } : null
+ }, [name, DB])
+ const clickBtn = (p, label) => p.evaluate((l) => [...document.querySelectorAll('.sp-banner button')].find((x) => x.textContent === l).click(), label)
+
+ console.log('\nan older snapshot: the warning banner\n')
+ {
+ const { ctx, p, errors } = await withSnapshot(MS - 3600_000)
+ const b = await bannerOf(p)
+ ok(!!b && b.text === OLDER, `the banner warns the copy looks older ("${b?.text}")`)
+ ok(!!b && b.buttons.join(' · ') === 'Keep the file · Restore anyway', `"Keep the file" first, then "Restore anyway" (${b?.buttons.join(' · ')})`)
+ ok(!!b && b.primary.join() === 'Keep the file', `"Keep the file" is the one primary button (${b?.primary.join(', ')})`)
+ ok(!!b && b.focused === 'Keep the file', `keeping the file is the default: it has focus (${b?.focused})`)
+ await clickBtn(p, 'Keep the file')
+ await p.waitForTimeout(300)
+ const kept = await p.evaluate(() => ({ gone: !document.querySelector('.sp-banner'), title: window.bento.doc.title }))
+ const snap = await held(p, doc.docId)
+ ok(kept.gone && kept.title === doc.title, `Keep the file closes the banner and keeps the file ("${kept.title}")`)
+ ok(!!snap && snap.title === 'Recovered edits', `…without deleting the planted snapshot (a clock-skewed "older" must never cost work) (${JSON.stringify(snap)})`)
+ ok(errors.length === 0, `no page errors${errors.length ? ': ' + errors.join('; ') : ''}`)
+ await ctx.close()
+ }
+ {
+ const { ctx, p } = await withSnapshot(MS - 3600_000)
+ await clickBtn(p, 'Restore anyway')
+ await p.waitForTimeout(400)
+ const t = await p.evaluate(() => window.bento.doc.title)
+ ok(t === 'Recovered edits', `"Restore anyway" restores the older snapshot ("${t}")`)
+ await ctx.close()
+ }
+
+ console.log('\na snapshot that is not older: the plain banner\n')
+ for (const [at, what] of [[MS + 3600_000, 'newer'], [MS, 'equal-time']]) {
+ const { ctx, p } = await withSnapshot(at)
+ const b = await bannerOf(p)
+ ok(!!b && b.text === PLAIN, `${what}: spaces' plain banner ("${b?.text}")`)
+ ok(!!b && !/newer|older|safe/i.test(b.text + ' ' + b.buttons.join(' ')), `${what}: it claims nothing about newer, older or safe`)
+ ok(!!b && b.buttons.join(' · ') === 'Restore · Discard', `${what}: Restore then Discard (${b?.buttons.join(' · ')})`)
+ // slides' default (lead ruling 2026-10-16): Restore primary, Discard not
+ ok(!!b && b.primary.join() === 'Restore', `${what}: Restore is the one primary button (${b?.primary.join(', ') || 'none'})`)
+ // …and, as in slides, not focused: no banner button holds focus
+ ok(!!b && b.focused === null, `${what}: no banner button takes focus, as in slides (focus: ${b?.focused})`)
+ await ctx.close()
+ }
+
+ console.log('\nslides\' words, in Portuguese and German\n')
+ for (const loc of ['pt', 'de']) {
+ const { ctx, p } = await withSnapshot(MS - 3600_000, loc)
+ const b = await bannerOf(p)
+ const want = {
+ text: catalog('slides', loc, OLDER),
+ keep: catalog('slides', loc, 'Keep the file'),
+ anyway: catalog('slides', loc, 'Restore anyway'),
+ }
+ ok(!!want.text && !!b && b.text === want.text, `${loc}: the warning is slides' ("${b?.text}")`)
+ ok(!!b && b.buttons.join(' · ') === `${want.keep} · ${want.anyway}` && b.focused === want.keep,
+ `${loc}: the buttons are slides', the first focused (${b?.buttons.join(' · ')})`)
+ await ctx.close()
+ }
+
+ // A host with a per-document store, played by the page: it announces `store`
+ // and answers the kernel's postMessage requests, refusing or keeping the
+ // recovery copy per run.
+ async function hosted(refuse, lang) {
+ const ctx = await newCtx()
+ await ctx.addInitScript(([refuseRecovery, l]) => {
+ if (l) try { localStorage.setItem('bento-lang', l) } catch {}
+ window.__bentoHost = { ops: ['store'] }
+ window.__sets = 0
+ window.__notices = []
+ const CH = '__bento_tray__'
+ window.addEventListener('message', (ev) => {
+ const d = ev.data
+ if (!d || d[CH] !== true || d.dir !== 'req') return
+ let result = { ok: true }
+ if (d.op === 'store.set' && d.payload?.name === 'recovery') { window.__sets++; result = refuseRecovery ? { ok: false, reason: 'too-large' } : { ok: true } }
+ if (d.op === 'store.get') result = { ok: true, bytes: null }
+ if (d.op === 'store.list') result = { ok: true, names: [] }
+ window.postMessage({ [CH]: true, dir: 'res', id: d.id, result }, '*')
+ })
+ // every time the save status is SET to a sentence (the status rewrites
+ // its text on each call, so a repeat shows as a second record)
+ new MutationObserver((ms) => {
+ for (const m of ms) {
+ const s = m.target.nodeType === 1 ? m.target.closest?.('.sp-status') : m.target.parentElement?.closest('.sp-status')
+ if (s && m.type === 'childList' && s.textContent) window.__notices.push(s.textContent)
+ }
+ }).observe(document, { subtree: true, childList: true })
+ }, [refuse, lang])
+ const p = await ctx.newPage()
+ const errors = []
+ p.on('pageerror', (e) => errors.push(e.message))
+ await p.goto(base + '/space.html')
+ await p.waitForFunction(() => window.bento?.doc && document.querySelector('.sp-doctitle'))
+ const edit = async (v) => {
+ await p.locator('.sp-doctitle').fill(v)
+ await p.locator('.sp-doctitle').press('Tab')
+ await p.waitForTimeout(3300) // the 2.5s autosave debounce, then the host's answer
+ }
+ await edit('First edit')
+ const first = await p.evaluate(() => {
+ const s = document.querySelector('.sp-status')
+ return { text: s?.textContent ?? '', shown: !!s?.classList.contains('sp-on'), sets: window.__sets }
+ })
+ await p.waitForTimeout(2500) // past the 1.8s an ordinary status lasts
+ const stillUp = await p.evaluate(() => !!document.querySelector('.sp-status')?.classList.contains('sp-on'))
+ await edit('Second edit')
+ await p.waitForTimeout(500)
+ const second = await p.evaluate((n) => ({ sets: window.__sets, notices: window.__notices.filter((x) => x.startsWith(n)).length }), NOTICE.slice(0, 12))
+ await ctx.close()
+ return { first, stillUp, second, errors }
+ }
+
+ console.log('\na host that refuses the recovery copy\n')
+ {
+ const r = await hosted(true)
+ ok(r.first.sets >= 1, `the app asked the host to keep a recovery copy (${r.first.sets})`)
+ ok(r.first.shown && r.first.text === NOTICE, `the save status says recovery is off ("${r.first.text}")`)
+ ok(r.stillUp, 'and holds it long enough to read')
+ ok(r.second.sets >= 1 && r.second.notices === 1, `said ONCE: a later autosave stays quiet (${r.second.notices} notice)`)
+ ok(r.errors.length === 0, `no page errors${r.errors.length ? ': ' + r.errors.join('; ') : ''}`)
+ }
+ console.log('\na host that keeps it (the control)\n')
+ {
+ const r = await hosted(false)
+ ok(r.first.sets >= 1 && r.second.notices === 0 && r.first.text !== NOTICE, `no recovery-off message (${r.second.notices})`)
+ }
+ for (const loc of ['pt', 'de']) {
+ const r = await hosted(true, loc)
+ const want = catalog('spaces', loc, NOTICE)
+ ok(!!want && r.first.text === want, `${loc}: the notice is the catalog's ("${r.first.text}")`)
+ }
+} finally {
+ await browser.close()
+ server.close()
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)
diff --git a/scripts/test-spaces-restore.ts b/scripts/test-spaces-restore.ts
index 2bb45003..bbc2bbe5 100644
--- a/scripts/test-spaces-restore.ts
+++ b/scripts/test-spaces-restore.ts
@@ -34,6 +34,9 @@ import { parseDoc, FORMAT, type SpacesDoc } from '../spaces/src/model.ts'
import { recoverInto, restoreVersion, replaceFromJson, recoveryOffered, gateRestored, asWholeRecovery } from '../spaces/src/restoregate.ts'
import { trailRecover, pruneTrail, TRAIL_BUDGET, TRAIL_MAX, spanOf, dayIndex, parseTrailKey, type Trail, type TrailRow } from '../spaces/src/trail.ts'
import { recordRevision, restoredDoc, revisionsOf, revisionsRecover, clearHistory } from '../spaces/src/history.ts'
+import { recoveryBanner, wireRecoveryOff, type RecoveryBanner } from '../spaces/src/recoverynotice.ts'
+import { putRecovery, recoveryOff } from '../kernel/src/autosave.ts'
+import { resetDocStoreForTest, type DocStore } from '../kernel/src/docstore.ts'
let checks = 0
let failures = 0
@@ -529,5 +532,108 @@ console.log('\n8. every entry point names its direction\n')
ok(/recover: \{ trail: trailRecover, revisions: revisionsRecover \}/.test(store), 'both recover hooks are bound in source')
}
+// ---------------------------------------------------------------------------
+// The maintainer's two recovery notices (2026-10-15, shared with slides and
+// type): an older-looking snapshot WARNS but is still offered, with "Keep the
+// file" the default; a refused recovery copy is said ONCE per space, never for
+// an encrypted one. recoverynotice.ts decides both; the kernel supplies the
+// signals (recoveryLooksOlder, onRecoveryOff). The browser half — focus, the
+// planted snapshot, a refusing host — is test-spaces-recovery-browser.mjs.
+console.log('\n9. the recovery banner\'s words, and the recovery-off notice\n')
+{
+ const OLDER = 'This recovered copy looks older than the file you opened. Keep the file unless you know it’s newer.'
+ const PLAIN = 'Unsaved changes from a previous session were found.'
+ const snapAt = (at: number) => ({ docId: 'space-R', at, title: 'R', json: J(snapOf(mk())) })
+ const live = mk()
+ const labels = (b: RecoveryBanner) => b.buttons.map((x) => x.label).join(' · ')
+
+ const o = recoveryBanner(snapAt(LIVE_MS - HOUR), live)
+ ok(o.older && o.text === OLDER, `an older snapshot: the banner warns ("${o.text}")`)
+ ok(labels(o) === 'Keep the file · Restore anyway', `…offering "Keep the file" then "Restore anyway" (${labels(o)})`)
+ const prim = o.buttons.filter((b) => b.primary)
+ ok(prim.length === 1 && prim[0].action === 'keep', `…with "Keep the file" the ONE default (${prim.map((b) => b.label).join(', ') || 'none'})`)
+ const foc = o.buttons.filter((b) => b.focus)
+ ok(foc.length === 1 && foc[0].action === 'keep', `…and "Keep the file" the ONE button that takes focus, as in slides (${foc.map((b) => b.label).join(', ') || 'none'})`)
+ ok(o.buttons.find((b) => b.label === 'Restore anyway')?.action === 'restore', '…and "Restore anyway" still restores: the older snapshot is never hidden')
+ ok(!o.buttons.some((b) => b.action === 'discard'), '…and nothing on it deletes the snapshot (a skewed clock must never cost work)')
+ {
+ // through the real restore: "Restore anyway" installs the snapshot's text
+ const s = new Store(mk())
+ const old = snapOf(mk()); old.pages[0].blocks[0].html = 'from the crash'
+ ok(recoverInto(s, { json: J(old), at: LIVE_MS - HOUR }) && text(s.doc) === 'from the crash', '"Restore anyway" → recoverInto installs the older snapshot')
+ }
+
+ for (const [at, what] of [[LIVE_MS + HOUR, 'a newer'], [LIVE_MS, 'an equal-time']] as const) {
+ const b = recoveryBanner(snapAt(at), live)
+ ok(!b.older && b.text === PLAIN, `${what} snapshot: the plain banner ("${b.text}")`)
+ ok(!/newer|older|safe/i.test(b.text + ' ' + labels(b)), `…claiming nothing about newer, older or safe (${labels(b)})`)
+ ok(labels(b) === 'Restore · Discard', `…with spaces' own buttons, Restore then Discard (${labels(b)})`)
+ // slides' default (lead ruling 2026-10-16): Restore is the one primary
+ const bp = b.buttons.filter((x) => x.primary)
+ ok(bp.length === 1 && bp[0].action === 'restore' && !b.buttons.find((x) => x.action === 'discard')?.primary,
+ `…Restore is the ONE default, Discard is not (${bp.map((x) => x.label).join(', ') || 'none'})`)
+ // …but, as in slides, nothing on the plain banner takes focus
+ ok(!b.buttons.some((x) => x.focus), `…and no button takes focus, as in slides (${b.buttons.filter((x) => x.focus).map((x) => x.label).join(', ') || 'none'})`)
+ }
+ // #705's rule: unknown either side says nothing
+ const noMod = mk(); delete (noMod as Obj).modified
+ const nm = recoveryBanner(snapAt(LIVE_MS - 1000 * HOUR), noMod)
+ ok(!nm.older && nm.text === PLAIN, 'a file with no `modified`: no warning, the plain banner (kernel: unknown → false)')
+ const badMod = recoveryBanner(snapAt(LIVE_MS - HOUR), mk({ modified: 'not a date' }))
+ ok(!badMod.older && badMod.text === PLAIN, 'an unreadable `modified`: no warning either')
+}
+{
+ // the notice, fired by the REAL kernel: a host whose per-document store
+ // refuses the recovery copy (docstore.ts), as bento/home does when too large
+ const said: string[] = []
+ let docId = 'space-off', encrypted = false
+ const refusing: DocStore = {
+ async get() { return null },
+ async set() { return 'refused' as const },
+ async list() { return [] },
+ async delete() { return true },
+ }
+ resetDocStoreForTest(refusing)
+ const off = wireRecoveryOff({ docId: () => docId, encrypted: () => encrypted, say: (m) => said.push(m) })
+ const NOTICE = 'Crash recovery is off for this space — it’s too large to keep a backup copy. Save often.'
+ const kdoc = (id: string) => ({ ...snapOf(mk()), docId: id }) as unknown as Parameters<typeof putRecovery>[0]
+ await putRecovery(kdoc('space-off'))
+ ok(said.length === 1 && said[0] === NOTICE, `a refused recovery copy: the notice, in the save status ("${said[0] ?? ''}")`)
+ ok(recoveryOff('space-off'), '…and the kernel agrees recovery is off for the space')
+ await putRecovery(kdoc('space-off'))
+ ok(said.length === 1, `…said ONCE: the next autosave stays quiet (${said.length})`)
+ await putRecovery(kdoc('space-other'))
+ ok(said.length === 1, `another space's refusal says nothing here (${said.length})`)
+ off()
+ resetDocStoreForTest(null)
+
+ // the app's own guard, fired twice for the same space (the kernel fires once,
+ // so this is what holds if it ever fires again)
+ type Fn = (id: string, reason: string) => void
+ const fns: Fn[] = []
+ const sub = (fn: Fn) => { fns.push(fn); return () => {} }
+ const twice: string[] = []
+ docId = 'space-twice'
+ wireRecoveryOff({ docId: () => docId, encrypted: () => encrypted, say: (m) => twice.push(m), subscribe: sub })
+ ok(fns.length === 1, 'the notice registers a listener')
+ fns.forEach((f) => f('space-twice', 'r')); fns.forEach((f) => f('space-twice', 'r'))
+ ok(twice.length === 1, `fired twice for one space: said once (${twice.length})`)
+ fns.forEach((f) => f('space-elsewhere', 'r'))
+ ok(twice.length === 1, 'fired for another docId: nothing')
+ const enc: string[] = []
+ const fns2: Fn[] = []
+ encrypted = true; docId = 'space-enc'
+ wireRecoveryOff({ docId: () => docId, encrypted: () => encrypted, say: (m) => enc.push(m), subscribe: (fn: Fn) => { fns2.push(fn); return () => {} } })
+ fns2.forEach((f) => f('space-enc', 'r'))
+ ok(enc.length === 0, 'an encrypted space: nothing (it was never snapshotted)')
+
+ const main = readFileSync(join(process.cwd(), 'spaces/src/main.ts'), 'utf8')
+ ok(/wireRecoveryOff\(\{\s*docId: \(\) => store\.doc\.docId,\s*encrypted: isEncryptionActive,\s*say: \(msg\) => editor\.status\(msg, 8000\),?\s*\}\)/.test(main),
+ 'main.ts registers the notice for the open space, encryption-aware, in the save status for 8s')
+ ok(/const spec = recoveryBanner\(snap, store\.doc\)[\s\S]{0,1200}?banner\(spec\.text, spec\.buttons\.map\(\(b\) => \[b\.label, run\[b\.action\], b\.primary, b\.focus\]\)\)/.test(main),
+ 'the recovery banner shows what recoveryBanner says, primary and focus and all')
+ ok(/keep: \(\) => \{\}/.test(main), '"Keep the file" deletes nothing')
+}
+
console.log(`\n${checks - failures}/${checks} checks passed`)
process.exit(failures ? 1 : 0)
diff --git a/scripts/test-spaces.mjs b/scripts/test-spaces.mjs
index 7618a027..3993b4d5 100755
--- a/scripts/test-spaces.mjs
+++ b/scripts/test-spaces.mjs
@@ -85,6 +85,8 @@ const RIGS = [
// every chrome field styled, light and dark — the built shell in Chromium
{ name: 'fields-browser', file: 'scripts/test-spaces-fields-browser.mjs' },
{ name: 'encrypted-browser', file: 'scripts/test-spaces-encrypted-browser.mjs' },
+ // the older-copy warning and the recovery-off notice, in the built shell
+ { name: 'recovery-browser', file: 'scripts/test-spaces-recovery-browser.mjs' },
// drives the BUILT shell in Chrome; self-skips outside CI without one
{ name: 'chrome', file: 'scripts/test-spaces-chrome.ts' },
]
diff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.md
index d78fed67..ece3f10d 100644
--- a/spaces/CHANGELOG.md
+++ b/spaces/CHANGELOG.md
@@ -1362,6 +1362,19 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.
history comes back with the recovered copy. If you cleared the version
history before the crash, it stays cleared. Undo, restoring a version and
pasting document JSON still leave both records exactly as they are.
+- **The recovery banner warns when the recovered copy looks older than the
+ file.** It now says "This recovered copy looks older than the file you
+ opened. Keep the file unless you know it’s newer." **Keep the file** is the
+ default and has focus. It closes the banner and deletes nothing, because two
+ devices' clocks can disagree. **Restore anyway** still brings the copy back.
+ When the copy is not older, the banner keeps its usual wording, and
+ **Restore** is now its default button. The words and behaviour match
+ bento/slides.
+- **Spaces says when crash recovery is off.** When bento/home declines to keep
+ a recovery copy because the space is too large, the save status says "Crash
+ recovery is off for this space — it’s too large to keep a backup copy. Save
+ often." It says so once per space, and never for an encrypted space, which
+ never keeps a recovery copy.
## [0.1.0] — 2026-08-03
diff --git a/spaces/src/editor.ts b/spaces/src/editor.ts
index d2aa20d4..867bdcd9 100644
--- a/spaces/src/editor.ts
+++ b/spaces/src/editor.ts
@@ -912,7 +912,9 @@ export class Editor {
;(n as any)._t = setTimeout(() => n?.classList.remove('sp-on'), 3600)
}
- status(msg: string): void {
+ /** The transient save status. `ms` is how long it stays up: a sentence the
+ * author must read (crash recovery is off) needs longer than "Saved". */
+ status(msg: string, ms = 1800): void {
this.statusEl.textContent = msg
this.statusEl.classList.add('sp-on')
clearTimeout((this.statusEl as any)._t)
@@ -925,7 +927,7 @@ export class Editor {
setTimeout(() => {
if (!this.statusEl.classList.contains('sp-on')) this.statusEl.textContent = ''
}, 260)
- }, 1800)
+ }, ms)
}
// ---- the page tree ------------------------------------------------------
diff --git a/spaces/src/i18n/de.ts b/spaces/src/i18n/de.ts
index 884e8a3f..c1016c54 100644
--- a/spaces/src/i18n/de.ts
+++ b/spaces/src/i18n/de.ts
@@ -996,4 +996,8 @@ export const de: Catalog = {
"Leave version history out": "Versionsverlauf weglassen",
"Versions include text that was deleted. This file keeps them either way.": "Versionen enthalten auch gelöschten Text. Diese Datei behält sie in jedem Fall.",
"Save invite…": "Einladung speichern…",
+ "This recovered copy looks older than the file you opened. Keep the file unless you know it’s newer.": "Diese wiederhergestellte Kopie scheint älter zu sein als die geöffnete Datei. Behalten Sie die Datei, es sei denn, Sie wissen, dass die Kopie neuer ist.",
+ "Keep the file": "Datei behalten",
+ "Restore anyway": "Trotzdem wiederherstellen",
+ "Crash recovery is off for this space — it’s too large to keep a backup copy. Save often.": "Die Absturzwiederherstellung ist für diesen Space deaktiviert – er ist zu groß für eine Sicherungskopie. Speichern Sie häufig.",
}
diff --git a/spaces/src/i18n/es.ts b/spaces/src/i18n/es.ts
index 4b001078..22353e14 100644
--- a/spaces/src/i18n/es.ts
+++ b/spaces/src/i18n/es.ts
@@ -996,4 +996,8 @@ export const es: Catalog = {
"Leave version history out": "Dejar fuera el historial de versiones",
"Versions include text that was deleted. This file keeps them either way.": "Las versiones incluyen texto que se borró. Este archivo las conserva en cualquier caso.",
"Save invite…": "Guardar invitación…",
+ "This recovered copy looks older than the file you opened. Keep the file unless you know it’s newer.": "Esta copia recuperada parece más antigua que el archivo que abriste. Conserva el archivo, salvo que sepas que la copia es más reciente.",
+ "Keep the file": "Conservar el archivo",
+ "Restore anyway": "Restaurar de todos modos",
+ "Crash recovery is off for this space — it’s too large to keep a backup copy. Save often.": "La recuperación tras fallos está desactivada para este espacio: es demasiado grande para guardar una copia de seguridad. Guarda a menudo.",
}
diff --git a/spaces/src/i18n/fr.ts b/spaces/src/i18n/fr.ts
index 9d27aebd..b3149e4e 100644
--- a/spaces/src/i18n/fr.ts
+++ b/spaces/src/i18n/fr.ts
@@ -996,4 +996,8 @@ export const fr: Catalog = {
"Leave version history out": "Ne pas inclure l’historique des versions",
"Versions include text that was deleted. This file keeps them either way.": "Les versions contiennent du texte supprimé. Ce fichier les conserve dans tous les cas.",
"Save invite…": "Enregistrer l’invitation…",
+ "This recovered copy looks older than the file you opened. Keep the file unless you know it’s newer.": "Cette copie récupérée semble plus ancienne que le fichier ouvert. Gardez le fichier, sauf si vous savez qu’elle est plus récente.",
+ "Keep the file": "Garder le fichier",
+ "Restore anyway": "Restaurer quand même",
+ "Crash recovery is off for this space — it’s too large to keep a backup copy. Save often.": "La récupération après plantage est désactivée pour cet espace : il est trop volumineux pour en garder une copie de secours. Enregistrez souvent.",
}
diff --git a/spaces/src/i18n/it.ts b/spaces/src/i18n/it.ts
index 6f505bc9..1541e39c 100644
--- a/spaces/src/i18n/it.ts
+++ b/spaces/src/i18n/it.ts
@@ -996,4 +996,8 @@ export const it: Catalog = {
"Leave version history out": "Escludi la cronologia delle versioni",
"Versions include text that was deleted. This file keeps them either way.": "Le versioni includono testo eliminato. Questo file le conserva in ogni caso.",
"Save invite…": "Salva l’invito…",
+ "This recovered copy looks older than the file you opened. Keep the file unless you know it’s newer.": "Questa copia recuperata sembra più vecchia del file che hai aperto. Tieni il file, a meno che tu non sappia che la copia è più recente.",
+ "Keep the file": "Tieni il file",
+ "Restore anyway": "Ripristina comunque",
+ "Crash recovery is off for this space — it’s too large to keep a backup copy. Save often.": "Il ripristino dopo un arresto anomalo è disattivato per questo spazio: è troppo grande per conservarne una copia di backup. Salva spesso.",
}
diff --git a/spaces/src/i18n/ja.ts b/spaces/src/i18n/ja.ts
index 4bf90dcd..b2e7d37f 100644
--- a/spaces/src/i18n/ja.ts
+++ b/spaces/src/i18n/ja.ts
@@ -996,4 +996,8 @@ export const ja: Catalog = {
"Leave version history out": "バージョン履歴を含めない",
"Versions include text that was deleted. This file keeps them either way.": "バージョンには削除された本文も含まれます。このファイルにはどちらの場合も残ります。",
"Save invite…": "招待を保存…",
+ "This recovered copy looks older than the file you opened. Keep the file unless you know it’s newer.": "この復元コピーは、開いたファイルより古いようです。新しいと分かっている場合を除き、ファイルをそのまま使ってください。",
+ "Keep the file": "ファイルを使う",
+ "Restore anyway": "それでも復元",
+ "Crash recovery is off for this space — it’s too large to keep a backup copy. Save often.": "このスペースのクラッシュ復旧はオフです — 大きすぎてバックアップを保存できません。こまめに保存してください。",
}
diff --git a/spaces/src/i18n/packed.ts b/spaces/src/i18n/packed.ts
index 48019844..896ae172 100644
--- a/spaces/src/i18n/packed.ts
+++ b/spaces/src/i18n/packed.ts
@@ -212,6 +212,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Couldn’t access the clipboard": ["クリップボードにアクセスできませんでした","无法访问剪贴板","無法存取剪貼簿","No se pudo acceder al portapapeles","Impossible d'accéder au presse-papiers","Zugriff auf die Zwischenablage nicht möglich","Impossibile accedere agli appunti","Não foi possível acessar a área de transferência"],
"Couldn’t reach the live session": ["ライブセッションに接続できませんでした","无法连接实时会话","無法連線即時會話","No se pudo contactar la sesión en vivo","Impossible de joindre la session live","Live-Sitzung nicht erreichbar","Impossibile raggiungere la sessione live","Não foi possível alcançar a sessão ao vivo"],
"Cover": ["カバー","封面","封面","Portada","Couverture","Titelbild","Copertina","Capa"],
+ "Crash recovery is off for this space — it’s too large to keep a backup copy. Save often.": ["このスペースのクラッシュ復旧はオフです — 大きすぎてバックアップを保存できません。こまめに保存してください。","此空间的崩溃恢复已关闭 — 文件太大,无法保留备份。请经常保存。","此空間的當機復原已關閉 — 檔案太大,無法保留備份。請經常儲存。","La recuperación tras fallos está desactivada para este espacio: es demasiado grande para guardar una copia de seguridad. Guarda a menudo.","La récupération après plantage est désactivée pour cet espace : il est trop volumineux pour en garder une copie de secours. Enregistrez souvent.","Die Absturzwiederherstellung ist für diesen Space deaktiviert – er ist zu groß für eine Sicherungskopie. Speichern Sie häufig.","Il ripristino dopo un arresto anomalo è disattivato per questo spazio: è troppo grande per conservarne una copia di backup. Salva spesso.","A recuperação de falhas está desativada para este espaço: ele é grande demais para manter uma cópia de segurança. Salve com frequência."],
"Create “{name}”": ["「{name}」を作成","创建“{name}”","建立「{name}」","Crear «{name}»","Créer « {name} »","„{name}“ erstellen","Crea «{name}»","Criar “{name}”"],
"Cumulative flow": ["累積フロー図","累积流图","累積流圖","Flujo acumulado","Flux cumulé","Kumulierter Fluss","Flusso cumulativo","Fluxo acumulado"],
"Custom": ["カスタム","自定义","自訂","Personalizado","Personnalisé","Eigene","Personalizzato","Personalizado"],
@@ -372,6 +373,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Italic — ⌘I": ["イタリック — ⌘I","斜体 — ⌘I","斜體 — ⌘I","Cursiva — ⌘I","Italique — ⌘I","Kursiv — ⌘I","Corsivo — ⌘I","Itálico — ⌘I"],
"Journal date": ["ジャーナルの日付","日志日期","日誌日期","Fecha del diario","Date du journal","Journaldatum","Data del diario","Data do diário"],
"Justified text": ["両端揃え","两端对齐","左右對齊","Texto justificado","Texte justifié","Blocksatz","Testo giustificato","Texto justificado"],
+ "Keep the file": ["ファイルを使う","保留文件","保留檔案","Conservar el archivo","Garder le fichier","Datei behalten","Tieni il file","Manter o arquivo"],
"Kept inside the file, one per save, so they travel with it. Restoring is undoable.": ["保存するたびに 1 つ、ファイルの中に記録され、ファイルと一緒に移動します。復元は取り消せます。","保存在文件内部,每次保存一个,随文件一起流转。恢复可以撤销。","保存在檔案內部,每次儲存一個,隨檔案一起流轉。還原可以復原。","Se guardan dentro del archivo, una por cada guardado, y viajan con él. Restaurar se puede deshacer.","Conservées dans le fichier, une par enregistrement, elles voyagent avec lui. La restauration peut être annulée.","In der Datei aufbewahrt, eine pro Speichern, und reisen mit ihr. Wiederherstellen lässt sich rückgängig machen.","Conservate nel file, una per salvataggio, viaggiano con esso. Il ripristino si può annullare.","Guardadas dentro do arquivo, uma por salvamento, e por isso viajam com ele. Restaurar pode ser desfeito."],
"Key-verified identity": ["鍵で検証済みのアイデンティティ","密钥验证的身份","金鑰驗證的身份","Identidad verificada por clave","Identité vérifiée par clé","Schlüssel-verifizierte Identität","Identità verificata da chiave","Identidade verificada por chave"],
"Label colour": ["ラベルの色","标签颜色","標籤顏色","Color de las etiquetas","Couleur des étiquettes","Farbe der Labels","Colore delle etichette","Cor dos rótulos"],
@@ -585,6 +587,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Resized": ["縮小済み","已缩放","已縮小","Redimensionada","Redimensionnée","Verkleinert","Ridimensionata","Redimensionada"],
"Resolve": ["解決","解决","解決","Resolver","Résoudre","Erledigen","Risolvi","Resolver"],
"Restore": ["復元","恢复","還原","Restaurar","Restaurer","Wiederherstellen","Ripristina","Restaurar"],
+ "Restore anyway": ["それでも復元","仍然恢复","仍然還原","Restaurar de todos modos","Restaurer quand même","Trotzdem wiederherstellen","Ripristina comunque","Restaurar mesmo assim"],
"Restore to the page list": ["ページ一覧に戻す","恢复到页面列表","還原到頁面清單","Restaurar a la lista de páginas","Restaurer dans la liste des pages","Zurück in die Seitenliste","Ripristina nell’elenco delle pagine","Restaurar para a lista de páginas"],
"Restored the version from {when} — ⌘Z undoes it": ["{when} のバージョンを復元しました。⌘Z で取り消せます。","已恢复 {when} 的版本,按 ⌘Z 可撤销。","已還原 {when} 的版本,按 ⌘Z 可復原。","Se restauró la versión del {when}: ⌘Z lo deshace.","Version du {when} restaurée — ⌘Z annule.","Version vom {when} wiederhergestellt — ⌘Z macht das rückgängig.","Ripristinata la versione del {when} — ⌘Z annulla.","Versão de {when} restaurada — ⌘Z desfaz"],
"Review comments stayed behind, on purpose.": ["レビューのコメントは、意図的に持ち出していません。","审阅评论有意留在了原处。","審閱註解刻意留在了原處。","Los comentarios de revisión se quedaron atrás, a propósito.","Les commentaires de relecture sont restés en arrière, volontairement.","Review-Kommentare sind absichtlich zurückgeblieben.","I commenti di revisione sono rimasti indietro, di proposito.","Os comentários de revisão ficaram para trás, de propósito."],
@@ -753,6 +756,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"This page as one .md note": ["このページを 1 つの .md ノートに","此页面导出为一个 .md 笔记","此頁面匯出為一個 .md 筆記","Esta página, como una nota .md","Cette page, en une note .md","Diese Seite als eine .md-Notiz","Questa pagina, come una nota .md","Esta página, como uma nota .md"],
"This page no longer uses a design of its own.": ["このページは独自のデザインを使わなくなりました。","此页面不再使用自己的设计。","此頁面不再使用自己的設計。","Esta página ya no usa un diseño propio.","Cette page n’utilise plus de design qui lui soit propre.","Diese Seite verwendet keine eigene Gestaltung mehr.","Questa pagina non usa più un design proprio.","Esta página não usa mais um design próprio."],
"This page only": ["このページだけ","仅此页面","僅此頁面","Solo esta página","Cette page seulement","Nur diese Seite","Solo questa pagina","Apenas esta página"],
+ "This recovered copy looks older than the file you opened. Keep the file unless you know it’s newer.": ["この復元コピーは、開いたファイルより古いようです。新しいと分かっている場合を除き、ファイルをそのまま使ってください。","此恢复副本似乎比你打开的文件更旧。除非你确定它更新,否则请保留该文件。","此復原副本似乎比你開啟的檔案更舊。除非你確定它較新,否則請保留該檔案。","Esta copia recuperada parece más antigua que el archivo que abriste. Conserva el archivo, salvo que sepas que la copia es más reciente.","Cette copie récupérée semble plus ancienne que le fichier ouvert. Gardez le fichier, sauf si vous savez qu’elle est plus récente.","Diese wiederhergestellte Kopie scheint älter zu sein als die geöffnete Datei. Behalten Sie die Datei, es sei denn, Sie wissen, dass die Kopie neuer ist.","Questa copia recuperata sembra più vecchia del file che hai aperto. Tieni il file, a meno che tu non sappia che la copia è più recente.","Esta cópia recuperada parece mais antiga do que o arquivo que você abriu. Mantenha o arquivo, a menos que saiba que a cópia é mais recente."],
"This space has no live session to follow": ["この Space には追従できるライブセッションがありません","此 Space 没有可跟随的实时会话","此 Space 沒有可跟隨的即時會話","Este Space no tiene sesión en vivo que seguir","Cet espace n’a pas de session live à suivre","Dieser Space hat keine Live-Sitzung zum Folgen","Questo Space non ha una sessione live da seguire","Este espaço não tem sessão ao vivo para acompanhar"],
"This space has no pages.": ["このスペースにはページがありません。","此空间没有页面。","此空間沒有任何頁面。","Este espacio no tiene páginas.","Cet espace n’a aucune page.","Dieser Space hat keine Seiten.","Questo spazio non ha pagine.","Este espaço não tem páginas."],
"This space is encrypted, so no versions are kept.": ["このスペースは暗号化されているため、バージョンは保存されません。","此空间已加密,因此不保存任何版本。","此空間已加密,因此不保存任何版本。","Este espacio está cifrado, así que no se guarda ninguna versión.","Cet espace est chiffré : aucune version n’est conservée.","Dieser Space ist verschlüsselt, deshalb werden keine Versionen aufbewahrt.","Questo spazio è cifrato, quindi non viene conservata alcuna versione.","Este espaço está criptografado, então nenhuma versão é guardada."],
diff --git a/spaces/src/i18n/pt.ts b/spaces/src/i18n/pt.ts
index 6da5ff2b..af2fc517 100644
--- a/spaces/src/i18n/pt.ts
+++ b/spaces/src/i18n/pt.ts
@@ -1003,4 +1003,8 @@ export const pt: Catalog = {
"Leave version history out": "Deixar de fora o histórico de versões",
"Versions include text that was deleted. This file keeps them either way.": "As versões incluem texto que foi apagado. Este arquivo as mantém de qualquer forma.",
"Save invite…": "Salvar convite…",
+ "This recovered copy looks older than the file you opened. Keep the file unless you know it’s newer.": "Esta cópia recuperada parece mais antiga do que o arquivo que você abriu. Mantenha o arquivo, a menos que saiba que a cópia é mais recente.",
+ "Keep the file": "Manter o arquivo",
+ "Restore anyway": "Restaurar mesmo assim",
+ "Crash recovery is off for this space — it’s too large to keep a backup copy. Save often.": "A recuperação de falhas está desativada para este espaço: ele é grande demais para manter uma cópia de segurança. Salve com frequência.",
}
diff --git a/spaces/src/i18n/zh-Hans.ts b/spaces/src/i18n/zh-Hans.ts
index f50715e7..e2a3bd4b 100644
--- a/spaces/src/i18n/zh-Hans.ts
+++ b/spaces/src/i18n/zh-Hans.ts
@@ -996,4 +996,8 @@ export const zh_Hans: Catalog = {
"Leave version history out": "不包含版本历史",
"Versions include text that was deleted. This file keeps them either way.": "版本中包含已删除的文字。无论如何,此文件都会保留它们。",
"Save invite…": "保存邀请…",
+ "This recovered copy looks older than the file you opened. Keep the file unless you know it’s newer.": "此恢复副本似乎比你打开的文件更旧。除非你确定它更新,否则请保留该文件。",
+ "Keep the file": "保留文件",
+ "Restore anyway": "仍然恢复",
+ "Crash recovery is off for this space — it’s too large to keep a backup copy. Save often.": "此空间的崩溃恢复已关闭 — 文件太大,无法保留备份。请经常保存。",
}
diff --git a/spaces/src/i18n/zh-Hant.ts b/spaces/src/i18n/zh-Hant.ts
index 97b94585..734801bd 100644
--- a/spaces/src/i18n/zh-Hant.ts
+++ b/spaces/src/i18n/zh-Hant.ts
@@ -996,4 +996,8 @@ export const zh_Hant: Catalog = {
"Leave version history out": "不包含版本歷程",
"Versions include text that was deleted. This file keeps them either way.": "版本中包含已刪除的文字。無論如何,此檔案都會保留它們。",
"Save invite…": "儲存邀請…",
+ "This recovered copy looks older than the file you opened. Keep the file unless you know it’s newer.": "此復原副本似乎比你開啟的檔案更舊。除非你確定它較新,否則請保留該檔案。",
+ "Keep the file": "保留檔案",
+ "Restore anyway": "仍然還原",
+ "Crash recovery is off for this space — it’s too large to keep a backup copy. Save often.": "此空間的當機復原已關閉 — 檔案太大,無法保留備份。請經常儲存。",
}
diff --git a/spaces/src/main.ts b/spaces/src/main.ts
index 875eea36..a7cea7f7 100644
--- a/spaces/src/main.ts
+++ b/spaces/src/main.ts
@@ -24,6 +24,7 @@ import { t, locale, applyDirection } from './i18n'
import { i18nApi } from '../../kernel/src/i18n.ts'
import { parseDoc, uid, newPage, type SpacesDoc, type ParseResult } from './model'
import { recoveryOffered, recoverInto, replaceFromJson } from './restoregate'
+import { recoveryBanner, wireRecoveryOff, type RecoveryAction } from './recoverynotice'
import { recordTrail } from './observe.ts'
import { protectedDays } from './periods.ts'
import {
@@ -479,6 +480,14 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')
})
void pruneOld()
void offerRecovery(doc, store, editor)
+ // A host that refuses the recovery copy (too large) turns crash recovery off
+ // for this space; say so once, where the save status shows, held long enough
+ // to read (slides holds it 8s). Never for an encrypted space.
+ wireRecoveryOff({
+ docId: () => store.doc.docId,
+ encrypted: isEncryptionActive,
+ say: (msg) => editor.status(msg, 8000),
+ })
// ---- the AI round-trip (PLATFORM §7) -----------------------------------
//
@@ -700,18 +709,23 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')
.catch(() => { /* an unreachable server is not an error here */ })
}
-function banner(text: string, actions: Array<[string, () => void]> = []): void {
+/** A strip across the top. An action marked primary is styled as the default;
+ * one marked focus takes focus when the banner appears. The two are separate
+ * because slides' recovery banner separates them. */
+function banner(text: string, actions: Array<[string, () => void, boolean?, boolean?]> = []): void {
const bar = document.createElement('div')
bar.className = 'sp-banner'
const span = document.createElement('span')
span.textContent = text
bar.append(span)
- for (const [label, fn] of actions) {
+ let focused: HTMLButtonElement | undefined
+ for (const [label, fn, isPrimary, takesFocus] of actions) {
const b = document.createElement('button')
- b.className = 'sp-btn'
+ b.className = isPrimary ? 'sp-btn sp-primary' : 'sp-btn'
b.textContent = label
b.addEventListener('click', () => { fn(); bar.remove() })
bar.append(b)
+ if (takesFocus) focused ??= b
}
const close = document.createElement('button')
close.className = 'sp-btn'
@@ -720,6 +734,7 @@ function banner(text: string, actions: Array<[string, () => void]> = []): void {
close.addEventListener('click', () => bar.remove())
bar.append(close)
document.body.prepend(bar)
+ focused?.focus()
}
/**
@@ -735,15 +750,22 @@ async function offerRecovery(doc: SpacesDoc, store: Store, editor: Editor): Prom
if (store.readOnly) return // a reading copy, a view-only follower or a frozen file is never rewritten
const snap = await getRecovery(doc.docId)
if (!snap || !recoveryOffered(snap.json, doc, snap.at)) return
- banner(t('Unsaved changes from a previous session were found.'), [
- [t('Restore'), () => {
+ // What the banner SAYS is recoverynotice.ts: when the snapshot looks older
+ // than the file it warns, and "Keep the file" is the default — but the
+ // snapshot is still offered, and keeping the file deletes nothing.
+ const spec = recoveryBanner(snap, store.doc)
+ const run: Record<RecoveryAction, () => void> = {
+ restore: () => {
// re-gated against the space as it is NOW (recoverInto). A refusal
// applies nothing and keeps the entry; only Discard deletes it.
// 'recover': the snapshot is a newer copy of this space, so its history
// is reconciled (trail unioned by day) rather than kept from the file.
if (!recoverInto(store, snap)) { editor.status(t('That version could not be read')); return }
editor.repaint()
- }],
- [t('Discard'), () => { void clearRecovery(doc.docId) }],
- ])
+ },
+ discard: () => { void clearRecovery(doc.docId) },
+ // a clock-skewed "older" must never cost work: the entry stays
+ keep: () => {},
+ }
+ banner(spec.text, spec.buttons.map((b) => [b.label, run[b.action], b.primary, b.focus]))
}
diff --git a/spaces/src/recoverynotice.ts b/spaces/src/recoverynotice.ts
new file mode 100644
index 00000000..bfb4d114
--- /dev/null
+++ b/spaces/src/recoverynotice.ts
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// What the crash-recovery banner says, and the one-time "recovery is off"
+// notice. Both are maintainer rulings shared with slides and type
+// (2026-10-15); slides' editor.ts (showRecoveryBanner, noticeRecoveryOff) is
+// the reference, and the strings are its strings with "deck" read as "space".
+//
+// THE OLDER-COPY WARNING. The kernel says whether a recovery snapshot looks
+// OLDER than the file now open (autosave.ts recoveryLooksOlder: both times
+// known and the snapshot's the earlier; unknown either side is false). It is a
+// SIGNAL, never a reason to hide the offer: the two times come from different
+// clocks, so a false "older" must only change the words and the default. So
+// the banner still offers the snapshot ("Restore anyway"), "Keep the file" is
+// the primary button and takes focus, and keeping the file deletes NOTHING —
+// a clock-skewed "older" must never cost work. With no signal the banner is the
+// plain one, with Restore its default (styled, not focused), and claims nothing about "newer" or
+// "safe".
+//
+// THE RECOVERY-OFF NOTICE. Under a host with a per-document store (bento/home),
+// the kernel fires onRecoveryOff once per document when the host refuses the
+// recovery copy (too large). From then on there is no crash backstop, and the
+// author is told so once per space per page load, where the save status shows.
+// Never for an encrypted space: those are never snapshotted, so there was no
+// backstop to lose.
+
+import { onRecoveryOff, recoveryLooksOlder, type Snapshot } from '../../kernel/src/autosave.ts'
+import { t } from './i18n'
+
+export type RecoveryAction = 'restore' | 'discard' | 'keep'
+
+export interface RecoveryButton {
+ label: string
+ action: RecoveryAction
+ /** the default: styled primary */
+ primary?: boolean
+ /** takes focus when the banner appears — only where slides focuses */
+ focus?: boolean
+}
+
+export interface RecoveryBanner {
+ older: boolean
+ text: string
+ buttons: RecoveryButton[]
+}
+
+/** The banner for a snapshot that has already passed the gate
+ * (restoregate.ts recoveryOffered). */
+export function recoveryBanner(snap: Snapshot, doc: { modified?: string | number }): RecoveryBanner {
+ const older = recoveryLooksOlder(snap, doc)
+ if (older) {
+ return {
+ older,
+ text: t('This recovered copy looks older than the file you opened. Keep the file unless you know it’s newer.'),
+ buttons: [
+ { label: t('Keep the file'), action: 'keep', primary: true, focus: true },
+ { label: t('Restore anyway'), action: 'restore' },
+ ],
+ }
+ }
+ // The plain banner's default is Restore, as slides' is (lead ruling,
+ // 2026-10-16): a primary button is the expected recovery action, not a claim
+ // that the copy is newer or safe — the text still claims neither. Like
+ // slides, it is styled as the default but NOT focused.
+ return {
+ older,
+ text: t('Unsaved changes from a previous session were found.'),
+ buttons: [
+ { label: t('Restore'), action: 'restore', primary: true },
+ { label: t('Discard'), action: 'discard' },
+ ],
+ }
+}
+
+export interface RecoveryOffWiring {
+ /** the space open in this page, read when the kernel fires */
+ docId: () => string
+ /** is this space encrypted now? */
+ encrypted: () => boolean
+ /** show the message where the save status shows */
+ say: (msg: string) => void
+ /** the kernel's subscription; a rig may pass its own to fire twice */
+ subscribe?: typeof onRecoveryOff
+}
+
+/** Listen for the kernel's recovery-off signal and say so once per space.
+ * Returns the unsubscribe. */
+export function wireRecoveryOff(w: RecoveryOffWiring): () => void {
+ const said = new Set<string>()
+ return (w.subscribe ?? onRecoveryOff)((docId) => {
+ if (docId !== w.docId() || w.encrypted() || said.has(docId)) return
+ said.add(docId)
+ w.say(t('Crash recovery is off for this space — it’s too large to keep a backup copy. Save often.'))
+ })
+}
diff --git a/spaces/src/styles.css b/spaces/src/styles.css
index f1c65aad..50b2beac 100644
--- a/spaces/src/styles.css
+++ b/spaces/src/styles.css
@@ -1074,6 +1074,10 @@ a.sp-embed-src:hover { color: var(--ink); text-decoration: underline; }
border-bottom: 1px solid color-mix(in srgb, var(--accent) 35%, transparent); font-size: 13.5px;
}
.sp-banner .sp-btn { color: var(--accent-ink); border-color: color-mix(in srgb, var(--accent-ink) 30%, transparent); }
+/* the default action (the recovery banner's "Keep the file") is slides' primary
+ on its banner: ink ground, page text, not the wash-coloured outline */
+.sp-banner .sp-primary { background: var(--ink); color: var(--bg); border-color: var(--ink); }
+.sp-banner .sp-primary:hover { background: var(--ink-2); border-color: var(--ink-2); }
.sp-gate { position: fixed; inset: 0; display: grid; place-items: center; padding: 24px; background: var(--chrome); }
.sp-gate-card {
max-width: 620px; background: var(--surface); padding: 26px;