Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

kernel: one autosave database per app, with the data carried over (#211)

nyblnet54c926f8146f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 961d32d2..224a77d3 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -131,6 +131,19 @@ jobs:
# throw when storage does.
run: node scripts/test-storage.ts
+ - name: Autosave per-app database rig
+ # Every app shared one IndexedDB database AND one DB_VERSION, so spaces
+ # has been writing into slides' store, and a version bump by any new app
+ # would make every SHIPPED shell of every other app throw VersionError
+ # and lose autosave. Renaming without carrying the data over would empty
+ # a visible feature, so the migration is tested in both directions.
+ run: |
+ slides/node_modules/.bin/esbuild scripts/test-autosave.ts --bundle --platform=node --format=esm \
+ --alias:fake-indexeddb/auto=./slides/node_modules/fake-indexeddb/auto/index.js \
+ --outfile="$RUNNER_TEMP/test-autosave.mjs"
+ BENTO_TEST_APP=bento-slides node "$RUNNER_TEMP/test-autosave.mjs"
+ BENTO_TEST_APP=bento-spaces node "$RUNNER_TEMP/test-autosave.mjs"
+
- name: Publish deletion-gate rig
# A publish assembles site/ for ONE app and mirrors it authoritatively.
# Measured: a spaces-shaped site/ deleted 47 live files — the signed
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index cf709696..a46b4ef0 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -1113,3 +1113,45 @@ contract.
`home/src/deckmeta.ts`, which reads a deck's title without executing it — the
extension needs exactly that to label what it is about to save. The launcher UI
and the recents store are superseded by the directory grant.
+## 2026-08-02 — One autosave database per app, migrated once
+
+`kernel/src/autosave.ts` used a single `DB_NAME = 'bento-autosave'` and a single
+`DB_VERSION` for every app. Two problems, and the second is the dangerous one.
+
+Snapshots from different apps piled into one store wherever they share an
+origin — `bento.page`, or any local server. bento/spaces has been writing into
+bento/slides' database since its scaffold landed (`spaces/src/main.ts` calls
+`putRecovery` on a 2.5s debounce).
+
+`DB_VERSION` was shared too, and that breaks in one direction only: a new app
+bumping it to 2 makes every ALREADY-SHIPPED shell of every other app throw
+`VersionError` on open and lose autosave entirely. Shipped shells are frozen
+code — 1.0.11 files are in the world and will go on opening version 1 forever.
+There is no way to reach them.
+
+**The name is `${appId}-autosave`.** `appId` is already `bento-slides` /
+`bento-spaces`, so this reads `bento-slides-autosave` with no doubled prefix
+and — deliberately — **no special case for the app that happened to be
+first**. An earlier draft grandfathered `bento-autosave` for slides to avoid
+orphaning data; carrying the data over is a better answer than a permanent
+exception, and each app now owns its own version line.
+
+**Migration copies, once, and never moves.** Renaming alone would silently drop
+every user's recovery snapshot and their whole version timeline — a visible
+feature emptying itself, which is a bug report, not a migration. It runs only
+into an empty target, so a second pass cannot duplicate the timeline or
+resurrect a snapshot the user deleted. The legacy database is left intact
+because shells already shipped keep writing to it, and the copy of the app the
+user opens next must still work; `pruneOld` ages its contents out on its own.
+
+Everything is copied, not just the running app's rows. Nothing in a snapshot
+records which app wrote it, and it does not need to: `docId` is a uuid, so
+another app's rows can never match a lookup. Filtering would mean guessing.
+
+`appConfig()` is read LAZILY inside `openDb()`. It throws before
+`configureApp()` runs, and a kernel module that explodes at import time
+depending on evaluation order is the trap `app.ts` exists to avoid — its header
+comment named autosave as config-free and is corrected in the same change.
+
+Rig: `scripts/test-autosave.ts`, run for both apps in CI. It fails against the
+old shared-name code (7/8), which is the property that makes it a gate.
diff --git a/kernel/src/app.ts b/kernel/src/app.ts
index 5fd62633..197eaf5b 100644
--- a/kernel/src/app.ts
+++ b/kernel/src/app.ts
@@ -9,8 +9,11 @@
// else in the kernel is genuinely app-agnostic.
//
// Deliberately NOT a general "kernel init" — modules that need no config
-// (anim, autosave, charts) take none, so there is no import-order trap and
-// no false coupling for apps that skip a module.
+// (anim, charts) take none, so there is no import-order trap and no false
+// coupling for apps that skip a module. `autosave` is the one exception and
+// reads appConfig() LAZILY, inside openDb(), for exactly that reason: its
+// IndexedDB database is named per app, and resolving that at module scope
+// would make importing it before configureApp() throw.
export interface AppConfig {
/** Manifest `app` field this shell will accept — e.g. 'bento-slides'.
diff --git a/kernel/src/autosave.ts b/kernel/src/autosave.ts
index 7b8fea83..ed9b188f 100644
--- a/kernel/src/autosave.ts
+++ b/kernel/src/autosave.ts
@@ -16,8 +16,32 @@
// write-back stays encrypted.
import type { KernelDoc } from './doc.ts'
+import { appConfig } from './app.ts'
-const DB_NAME = 'bento-autosave'
+/**
+ * One database PER APP.
+ *
+ * Every app used to share `bento-autosave`, which is two problems, not one.
+ * The visible one is that two apps' snapshots pile into one store wherever
+ * they share an origin — `bento.page`, or any local server. The dangerous one
+ * is `DB_VERSION`: it was shared too, so a new app bumping it to 2 would make
+ * every ALREADY-SHIPPED shell of every other app throw `VersionError` on open
+ * and lose autosave entirely. Files in the world are frozen code; they would
+ * go on opening version 1 forever and there is no way to reach them.
+ *
+ * `appId` is already `bento-slides` / `bento-spaces`, so this reads
+ * `bento-slides-autosave` — no doubled prefix, and no special case for the
+ * app that happened to be first. Each app now owns its own version line.
+ *
+ * Called lazily rather than at module scope: `appConfig()` throws before
+ * `configureApp()` runs, and a kernel module that explodes at import time
+ * depending on evaluation order is the import-order trap app.ts exists to
+ * avoid.
+ */
+const dbName = () => `${appConfig().appId}-autosave`
+
+/** The shared name every app wrote to before scoping. Read once, then left alone. */
+const LEGACY_DB_NAME = 'bento-autosave'
const DB_VERSION = 1
const RECOVERY = 'recovery'
const VERSIONS = 'versions'
@@ -34,12 +58,12 @@ export interface Snapshot {
let dbPromise: Promise<IDBDatabase | null> | null = null
-function openDb(): Promise<IDBDatabase | null> {
- if (dbPromise) return dbPromise
- dbPromise = new Promise((resolve) => {
+/** Open a database by name, creating this build's stores. */
+function open(name: string): Promise<IDBDatabase | null> {
+ return new Promise((resolve) => {
if (typeof indexedDB === 'undefined') { resolve(null); return }
let req: IDBOpenDBRequest
- try { req = indexedDB.open(DB_NAME, DB_VERSION) } catch { resolve(null); return }
+ try { req = indexedDB.open(name, DB_VERSION) } catch { resolve(null); return }
req.onupgradeneeded = () => {
const db = req.result
if (!db.objectStoreNames.contains(RECOVERY)) db.createObjectStore(RECOVERY, { keyPath: 'docId' })
@@ -50,7 +74,78 @@ function openDb(): Promise<IDBDatabase | null> {
}
req.onsuccess = () => resolve(req.result)
req.onerror = () => resolve(null)
+ req.onblocked = () => resolve(null)
+ })
+}
+
+/** Everything in one store of a database, or [] on any failure. */
+function readAll(db: IDBDatabase, store: string): Promise<Snapshot[]> {
+ return new Promise((resolve) => {
+ let t: IDBTransaction
+ try { t = db.transaction(store, 'readonly') } catch { resolve([]); return }
+ const req = t.objectStore(store).getAll()
+ req.onsuccess = () => resolve((req.result as Snapshot[]) ?? [])
+ req.onerror = () => resolve([])
})
+}
+
+/**
+ * Carry snapshots over from the shared database, ONCE, on first open.
+ *
+ * Renaming without this would silently drop every user's recovery snapshot and
+ * their whole version timeline — a visible feature quietly emptying itself,
+ * which is a bug report, not a migration.
+ *
+ * It COPIES rather than moves: shells already shipped go on writing to the old
+ * name forever, and deleting the source would break the copy of the app the
+ * user might open next. The cost is that the old database lingers; `pruneOld`
+ * ages its contents out on its own schedule.
+ *
+ * Everything is copied, not just this app's rows. Nothing in a snapshot records
+ * which app wrote it — and it does not need to: `docId` is a uuid, so another
+ * app's rows can never match a lookup here. Filtering would mean guessing.
+ */
+async function migrateLegacy(target: IDBDatabase, targetName: string): Promise<void> {
+ if (targetName === LEGACY_DB_NAME) return
+ // Only ever migrate INTO an empty database — a second pass would duplicate
+ // the version timeline, and a user who deleted a snapshot would see it return.
+ const existing = await readAll(target, RECOVERY)
+ if (existing.length) return
+ const legacy = await open(LEGACY_DB_NAME)
+ if (!legacy) return
+ try {
+ const [recovery, versions] = await Promise.all([
+ readAll(legacy, RECOVERY),
+ readAll(legacy, VERSIONS),
+ ])
+ if (!recovery.length && !versions.length) return
+ await new Promise<void>((resolve) => {
+ let t: IDBTransaction
+ try { t = target.transaction([RECOVERY, VERSIONS], 'readwrite') } catch { resolve(); return }
+ const rs = t.objectStore(RECOVERY)
+ const vs = t.objectStore(VERSIONS)
+ for (const r of recovery) rs.put(r)
+ // drop the old autoIncrement key so the target mints its own
+ for (const v of versions) { const { id: _id, ...rest } = v; vs.add(rest as Snapshot) }
+ t.oncomplete = () => resolve()
+ t.onerror = () => resolve()
+ t.onabort = () => resolve()
+ })
+ } finally {
+ legacy.close()
+ }
+}
+
+function openDb(): Promise<IDBDatabase | null> {
+ if (dbPromise) return dbPromise
+ dbPromise = (async () => {
+ let name: string
+ try { name = dbName() } catch { return null } // configureApp() never ran
+ const db = await open(name)
+ if (!db) return null
+ try { await migrateLegacy(db, name) } catch { /* best effort, never fatal */ }
+ return db
+ })()
return dbPromise
}
diff --git a/scripts/test-autosave.ts b/scripts/test-autosave.ts
new file mode 100644
index 00000000..66f67e12
--- /dev/null
+++ b/scripts/test-autosave.ts
@@ -0,0 +1,128 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Autosave per-app database rig.
+//
+// esbuild scripts/test-autosave.ts --bundle --platform=node --format=esm ...
+// BENTO_TEST_APP=bento-slides node <bundle>
+// BENTO_TEST_APP=bento-spaces node <bundle>
+//
+// (bundled so `fake-indexeddb` resolves from slides/node_modules, matching
+// test-clipboard and test-validate)
+//
+// WHAT THIS PROVES. Every app used to share one IndexedDB database,
+// `bento-autosave`, and one `DB_VERSION`. Two failures, one shared:
+//
+// 1. Snapshots from different apps piled into one store wherever they share
+// an origin — bento.page, or any local server. bento/spaces has been
+// writing into bento/slides' database since its scaffold landed.
+// 2. Worse, and asymmetric: DB_VERSION was shared too. A new app bumping it
+// to 2 makes every ALREADY-SHIPPED shell of every other app throw
+// VersionError on open and lose autosave outright. Shipped shells are
+// frozen code — they go on opening version 1 forever, and 1.0.11 files
+// are in the world today.
+//
+// The rename alone would silently drop every user's recovery snapshot and
+// their whole version timeline — a visible feature emptying itself, which is
+// a bug report rather than a migration. So the properties tested here are:
+// the database is named per app, the legacy contents are carried over ONCE,
+// the legacy database is left intact for shells that still write to it, and a
+// second run neither duplicates the timeline nor resurrects deleted rows.
+
+import 'fake-indexeddb/auto'
+import { configureApp } from '../kernel/src/app.ts'
+import { putRecovery, getRecovery, addVersion, listVersions } from '../kernel/src/autosave.ts'
+
+const APP = process.env.BENTO_TEST_APP || 'bento-slides'
+const EXPECTED_DB = `${APP}-autosave`
+const LEGACY = 'bento-autosave'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+const open = (name: string, version?: number): Promise<IDBDatabase> =>
+ new Promise((res, rej) => {
+ const q = version ? indexedDB.open(name, version) : indexedDB.open(name)
+ q.onupgradeneeded = () => {
+ const d = q.result
+ if (!d.objectStoreNames.contains('recovery')) d.createObjectStore('recovery', { keyPath: 'docId' })
+ if (!d.objectStoreNames.contains('versions')) {
+ const s = d.createObjectStore('versions', { keyPath: 'id', autoIncrement: true })
+ s.createIndex('docId', 'docId', { unique: false })
+ }
+ }
+ q.onsuccess = () => res(q.result)
+ q.onerror = () => rej(q.error)
+ })
+
+const readAll = (db: IDBDatabase, store: string): Promise<any[]> =>
+ new Promise((res) => {
+ if (!db.objectStoreNames.contains(store)) return res([])
+ const r = db.transaction(store, 'readonly').objectStore(store).getAll()
+ r.onsuccess = () => res(r.result ?? [])
+ r.onerror = () => res([])
+ })
+
+const dbNames = async () => (await indexedDB.databases()).map((d: any) => d.name).sort()
+
+// ---- seed the shared legacy database, as a pre-upgrade user would have it ---
+// Both apps' rows, because both wrote here.
+const now = Date.now()
+{
+ const legacy = await open(LEGACY, 1)
+ await new Promise<void>((res) => {
+ const t = legacy.transaction(['recovery', 'versions'], 'readwrite')
+ t.objectStore('recovery').put({ docId: 'deck-uuid-1', at: now, title: 'A deck', json: '{"a":1}' })
+ t.objectStore('recovery').put({ docId: 'space-uuid-1', at: now, title: 'A space', json: '{"b":2}' })
+ for (let i = 0; i < 3; i++) {
+ t.objectStore('versions').add({ docId: 'deck-uuid-1', at: now - i * 1000, title: `v${i}`, json: '{}' })
+ }
+ t.oncomplete = () => res()
+ })
+ legacy.close()
+}
+
+configureApp({ appId: APP, appName: APP, manifestUrl: 'https://example.invalid/m.json' })
+
+// ---- first use triggers open + migration -----------------------------------
+const carried = await getRecovery('deck-uuid-1')
+ok((await dbNames()).includes(EXPECTED_DB), `the database is named ${EXPECTED_DB}, not the shared ${LEGACY}`)
+ok(carried !== null && carried.title === 'A deck',
+ `a recovery snapshot written before the rename is still found (got ${carried ? carried.title : 'null'})`)
+ok((await getRecovery('space-uuid-1')) !== null,
+ 'rows the OTHER app wrote are carried too — nothing records which app wrote a snapshot, and a uuid docId can never collide')
+ok((await listVersions('deck-uuid-1')).length === 3,
+ `the version timeline survives the rename (got ${(await listVersions('deck-uuid-1')).length}/3)`)
+
+// ---- the legacy database is COPIED, never moved -----------------------------
+// Shells already shipped keep writing to the old name; emptying it would break
+// the copy of the app the user opens next.
+{
+ const legacy = await open(LEGACY)
+ const rec = await readAll(legacy, 'recovery')
+ const ver = await readAll(legacy, 'versions')
+ legacy.close()
+ ok(rec.length === 2 && ver.length === 3,
+ `the legacy database is left intact for shipped shells (${rec.length} recovery, ${ver.length} versions)`)
+}
+
+// ---- the new database is live ----------------------------------------------
+ok(await putRecovery({ docId: 'deck-uuid-1', title: 'A deck, edited', json: '' } as any),
+ 'putRecovery reports success against the per-app database')
+ok((await getRecovery('deck-uuid-1'))!.title === 'A deck, edited', 'the newer snapshot wins')
+
+// ---- migration runs ONCE ---------------------------------------------------
+// A second pass would duplicate the timeline, and would resurrect any snapshot
+// the user had deleted. Re-running the migration against a populated target
+// must be a no-op.
+await addVersion({ docId: 'deck-uuid-1', title: 'v3', json: '{}' } as any)
+const after = await listVersions('deck-uuid-1')
+ok(after.length === 4, `adding one version gives 4, not 7 — the legacy rows were not copied twice (got ${after.length})`)
+
+console.log(`\n[${APP}] ${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/slides/package-lock.json b/slides/package-lock.json
index d70d8cc1..fa9e7558 100644
--- a/slides/package-lock.json
+++ b/slides/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "bento-slides",
- "version": "1.0.10",
+ "version": "1.0.14",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "bento-slides",
- "version": "1.0.10",
+ "version": "1.0.14",
"license": "MIT",
"dependencies": {
"moveable": "^0.53.0",
@@ -17,6 +17,7 @@
"devDependencies": {
"@types/node": "^24.13.2",
"@types/reveal.js": "^5.2.1",
+ "fake-indexeddb": "^6.2.5",
"qrcode": "^1.5.4",
"typescript": "~5.8.3",
"vite": "^7.1.1",
@@ -1160,6 +1161,16 @@
"@esbuild/win32-x64": "0.28.1"
}
},
+ "node_modules/fake-indexeddb": {
+ "version": "6.2.5",
+ "resolved": "https://registry.npmjs.org/fake-indexeddb/-/fake-indexeddb-6.2.5.tgz",
+ "integrity": "sha512-CGnyrvbhPlWYMngksqrSSUT1BAVP49dZocrHuK0SvtR0D5TMs5wP0o3j7jexDJW01KSadjBp1M/71o/KR3nD1w==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
diff --git a/slides/package.json b/slides/package.json
index 54e9cd2d..e7c4e164 100644
--- a/slides/package.json
+++ b/slides/package.json
@@ -19,6 +19,7 @@
"devDependencies": {
"@types/node": "^24.13.2",
"@types/reveal.js": "^5.2.1",
+ "fake-indexeddb": "^6.2.5",
"qrcode": "^1.5.4",
"typescript": "~5.8.3",
"vite": "^7.1.1",