Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

type: undo and both restores go through the kernel's restore directions; the ruled recovery banner (#715)

nyblneta159fa865c8d
diff --git a/scripts/test-type-autosave.ts b/scripts/test-type-autosave.ts
index 3b2a7670..7c0502f9 100644
--- a/scripts/test-type-autosave.ts
+++ b/scripts/test-type-autosave.ts
@@ -27,7 +27,10 @@ import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { configureApp } from '../kernel/src/app.ts'
import { setEncryptionPassword } from '../kernel/src/save.ts'
-import { docContentKey, canSnapshot } from '../type/src/autosave.ts'
+import { docContentKey, canSnapshot, recoveryBanner } from '../type/src/autosave.ts'
+import { sign, newKey, verifyChain, newHistorySalt } from '../type/src/canon.ts'
+import { RESTORE_RULES } from '../type/src/restorerules.ts'
+import { validateRestoreRules } from '../kernel/src/docfields.ts'
import { emptyDoc, uid, type TypeDoc } from '../type/src/model.ts'
import { Store } from '../type/src/store.ts'
import { gateRestored } from '../type/src/restoregate.ts'
@@ -42,6 +45,7 @@ const doc = (): TypeDoc => {
const d = emptyDoc()
d.title = 'Master Services Agreement'
d.body = [{ id: uid(), kind: 'para', text: 'Payment is due within 30 days.' }]
+ d.historySalt = newHistorySalt() // v2 signing commits to the history under it (canon.ts)
return d
}
@@ -224,5 +228,248 @@ H('a recovery snapshot with NO signatures never pairs its revisions with the liv
'the file\'s signatures are never paired with the snapshot\'s revisions')
}
+// ════════════════════════════════════════════════════════════════════════════
+// RESTORE DIRECTIONS (restorerules.ts, kernel applyRestore): undo/redo and a
+// version restore go BACK — content follows, history stays live; the recovery
+// banner RECOVERS — content and history follow the newer copy together.
+const rev = (id: string, text: string) => ({ id, at: '2026-01-01T00:00:00.000Z', label: id, body: [{ id: 'p0', kind: 'para', text }] })
+
+H('a Snapshot is a record, not an edit — and undo can never take one back')
+{
+ const store = new Store(doc())
+ store.commit(d => { d.body[0].text = 'Payment is due within 45 days.' }) // an ordinary edit
+ store.commit(d => { d.revisions.push(rev('r1', 'draft')) }, { undoable: false }) // what ⋯ → Snapshot does
+ ok(store.doc.revisions.length === 1, 'the Snapshot is recorded')
+ ok(store.undo(), 'undo takes back the EDIT')
+ ok(store.doc.body[0].text === 'Payment is due within 30 days.', 'the text reverts')
+ ok(store.doc.revisions.length === 1 && store.doc.revisions[0].id === 'r1',
+ 'but the revision SURVIVES — a document-level undo keeps history live')
+ ok(!store.undo(), 'and the Snapshot itself is not on the undo stack at all')
+ const red = readFileSync(fileURLToPath(new URL('../type/src/redlineview.ts', import.meta.url)), 'utf8')
+ const snapFn = red.slice(red.indexOf('export function takeSnapshot'), red.indexOf('export function startReview'))
+ ok(/\}, \{ undoable: false \}\);/.test(snapFn), '⋯ → Snapshot really commits with undoable: false')
+}
+
+H('comments undo like any edit (comments FOLLOW a restore)')
+{
+ const store = new Store(doc())
+ store.commit(d => { (d as any).comments = { c1: { id: 'c1', text: 'check this', author: 'Bob', at: 'x', replies: [],
+ anchor: { block: d.body[0].id, from: 0, to: 4 } } } })
+ ok(!!(store.doc as any).comments?.c1, 'a comment is added')
+ ok(store.undo() && !(store.doc as any).comments?.c1, 'and undo removes it — history-class for copying, follows for undo')
+ ok(store.redo() && !!(store.doc as any).comments?.c1, 'redo brings it back')
+}
+
+H('restoring an older VERSION keeps every newer revision (back)')
+{
+ const store = new Store(doc())
+ const older = JSON.parse(JSON.stringify(store.doc)) as TypeDoc // the version kept earlier
+ store.commit(d => { d.body[0].text = 'Payment is due within 60 days.' })
+ store.commit(d => { d.revisions.push(rev('r1', 'a')); d.revisions.push(rev('r2', 'b')) }, { undoable: false })
+ store.restore(older, 'back')
+ ok(store.doc.body[0].text === 'Payment is due within 30 days.', 'the older version\'s content comes back')
+ ok(store.doc.revisions.map(r => r.id).join() === 'r1,r2', 'and the revisions made since are KEPT, never discarded')
+ ok(store.doc.docId === older.docId, 'identity stays live')
+}
+
+H('crash recovery brings content AND history back TOGETHER (recover)')
+{
+ // The case that motivated the direction split: trim history, re-sign, crash
+ // before the file is written. The file still holds the long list; the
+ // snapshot holds the trimmed list and the NEW signature over it.
+ const k = await newKey()
+ const file = doc()
+ file.revisions = [rev('r1', 'a'), rev('r2', 'b'), rev('r3', 'c')]
+ file.signatures = [await sign(file, k, { name: 'Alice' })]
+ const snap = JSON.parse(JSON.stringify(file)) as TypeDoc
+ snap.revisions = [rev('r3', 'c')] // trimmed…
+ snap.signatures = [await sign({ ...snap, signatures: [] }, k, { name: 'Alice' })] // …and re-signed
+
+ const store = new Store(JSON.parse(JSON.stringify(file)))
+ const gated = gateRestored(JSON.stringify(snap), store.doc)!
+ store.restore(gated, 'recover')
+ ok(store.doc.revisions.map(r => r.id).join() === 'r3', 'the TRIMMED list comes back from the snapshot')
+ ok(store.doc.signatures.length === 1 && store.doc.signatures[0].sig === snap.signatures[0].sig,
+ 'with the signature made over it — revisions and signatures are never split')
+ const v = await verifyChain(store.doc, store.doc.signatures)
+ ok(v.ok && v.entries[0].ok, 'so the re-signed signature VERIFIES after recovery')
+ ok(store.doc.docId === file.docId, 'identity still comes from the live file')
+ ok(store.undo() && store.doc.revisions.map(r => r.id).join() === 'r3',
+ 'undo of the restore reverts content but keeps history live — going back never discards')
+}
+
+H('what was DELETED before the crash stays deleted on Restore (recover, whole snapshot)')
+{
+ // The recovery snapshot is the WHOLE document as the crashed session held it,
+ // so a key it lacks was removed — Restore must not bring it back from the file.
+ // Each row asserts the FILE carries the thing first, so "absent after" means
+ // the restore removed it, not that it was never there. Through the banner's
+ // own path: gateRestored, then store.restore(…, 'recover').
+ const recover = (file: TypeDoc, snap: TypeDoc) => {
+ const store = new Store(JSON.parse(JSON.stringify(file)))
+ const gated = gateRestored(JSON.stringify(snap), store.doc)
+ ok(gated !== null, ' (the snapshot passes the restore gate)')
+ store.restore(gated!, 'recover')
+ return store
+ }
+ const thread = (block: string) => ({ c1: { id: 'c1', text: 'redact this clause', author: 'Bob', at: '2026-01-01T00:00:00.000Z',
+ replies: [], anchor: { block, from: 0, to: 7 } } })
+
+ // 1. a deleted comment — history-class, but FOLLOWS a restore (the #722 case)
+ {
+ const file = doc(); (file as any).comments = thread(file.body[0].id)
+ const snap = JSON.parse(JSON.stringify(file)) as TypeDoc; delete (snap as any).comments
+ const live = new Store(JSON.parse(JSON.stringify(file)))
+ ok(!!(live.doc as any).comments?.c1, 'the file carries the comment')
+ const s = recover(file, snap)
+ ok(!(s.doc as any).comments?.c1 && !JSON.stringify(s.doc).includes('redact this clause'),
+ 'a comment deleted before the crash stays deleted')
+ }
+ // 2. a deleted paragraph
+ {
+ const file = doc(); file.body.push({ id: uid(), kind: 'para', text: 'Late fees accrue at 5%.' })
+ const snap = JSON.parse(JSON.stringify(file)) as TypeDoc; snap.body = [snap.body[0]]
+ ok(file.body.length === 2, 'the file carries the second paragraph')
+ const s = recover(file, snap)
+ ok(s.doc.body.length === 1 && !JSON.stringify(s.doc.body).includes('Late fees'), 'a paragraph deleted before the crash stays deleted')
+ }
+ // 3. a cleared field
+ {
+ const file = doc(); file.subtitle = 'DRAFT — privileged'
+ const snap = JSON.parse(JSON.stringify(file)) as TypeDoc; delete snap.subtitle
+ ok(!('subtitle' in snap), 'the snapshot genuinely lacks the subtitle key')
+ const s = recover(file, snap)
+ ok(!s.doc.subtitle, 'a field cleared before the crash stays cleared')
+ }
+ // 4. an emptied list — footnotes present-but-empty, and styles (parseDoc DROPS an empty map)
+ {
+ const file = doc(); file.footnotes = { f1: 'Per the side letter.' }
+ ;(file as any).styles = { quote: { label: 'Quote', italic: true } }
+ const snap = JSON.parse(JSON.stringify(file)) as TypeDoc; snap.footnotes = {} as any; delete (snap as any).styles
+ const gatedFile = gateRestored(JSON.stringify(file), file)!
+ ok(Object.keys(gatedFile.footnotes).length === 1 && !!(gatedFile as any).styles?.quote,
+ 'the file carries the footnote and the style through parseDoc')
+ const s = recover(file, snap)
+ ok(Object.keys(s.doc.footnotes).length === 0, 'footnotes emptied before the crash stay empty')
+ ok(!(s.doc as any).styles?.quote, 'a style list emptied before the crash stays empty')
+ }
+ // 5. cleared HISTORY — no path in type empties revisions today; when one does
+ // (re-sign-to-trim), a whole snapshot's [] OR missing key must mean cleared.
+ // The missing case holds twice over: the kernel removes an absent history
+ // field from a whole snapshot (#726), and parseDoc defaults absent revisions
+ // to [] (model.ts) before the restore sees them.
+ for (const how of ['[]', 'missing'] as const) {
+ const file = doc(); file.revisions = [rev('r1', 'negotiated away'), rev('r2', 'b')]
+ const snap = JSON.parse(JSON.stringify(file)) as TypeDoc
+ if (how === '[]') snap.revisions = []; else delete (snap as any).revisions
+ ok(how === '[]' || !('revisions' in snap), ` (the ${how} snapshot genuinely lacks revisions)`)
+ const s = recover(file, snap)
+ ok(s.doc.revisions.length === 0 && !JSON.stringify(s.doc).includes('negotiated away'),
+ `history cleared before the crash stays cleared — snapshot revisions ${how}`)
+ }
+ // 6. …but the history SALT is the one exception. A snapshot without it was
+ // autosaved BEFORE the first Sign (which mints it); a live document never
+ // loses its salt. Removing it would orphan every signature made over it.
+ {
+ const file = doc() // fixture carries a salt
+ const stale = JSON.parse(JSON.stringify(file)) as TypeDoc
+ delete (stale as any).historySalt // …autosaved before the first Sign
+ ok(!!file.historySalt && !('historySalt' in stale), ' (the file has a salt, the stale snapshot genuinely lacks one)')
+ const s = recover(file, stale)
+ ok(s.doc.historySalt === file.historySalt,
+ 'a snapshot from before the first signature keeps the live history salt — signatures made over it still match')
+ }
+}
+
+H('restoring an older version of a SIGNED document reports changed, and does not crash')
+{
+ const k = await newKey()
+ const store = new Store(doc())
+ const older = JSON.parse(JSON.stringify(store.doc)) as TypeDoc
+ store.commit(d => { d.body[0].text = 'Payment is due within 60 days.' })
+ const signed = await sign(store.doc, k, { name: 'Alice' })
+ store.commit(d => { d.signatures.push(signed) })
+ store.restore(older, 'back')
+ const v = await verifyChain(store.doc, store.doc.signatures)
+ ok(v.entries.length === 1 && !v.entries[0].ok,
+ 'the live signature is kept and honestly reads changed — the content it signed is not what is open')
+}
+
+H('the recovery banner: warn and default to keeping the file, never hide (ruling 9)')
+{
+ const file = doc(); file.modified = '2026-06-01T12:00:00.000Z'
+ const older = { docId: file.docId, at: Date.parse('2026-06-01T09:00:00.000Z'), title: '', json: '{}' }
+ const newer = { ...older, at: Date.parse('2026-06-01T15:00:00.000Z') }
+ ok(recoveryBanner(older, file).older && recoveryBanner(older, file).defaultAction === 'keep',
+ 'a copy that looks OLDER than the file warns, and keeping the file is the default')
+ ok(!recoveryBanner(newer, file).older && recoveryBanner(newer, file).defaultAction === 'restore',
+ 'a newer-looking copy offers restore as before')
+ const unknown = doc(); delete (unknown as any).modified
+ ok(!recoveryBanner(older, unknown).older, 'an unknown age raises no warning — and nothing claims it is newer either')
+ const src = readFileSync(fileURLToPath(new URL('../type/src/autosave.ts', import.meta.url)), 'utf8')
+ ok(src.includes(`t('This recovered copy looks older than the file you opened. Keep the file unless you know it’s newer.')`),
+ 'the banner uses the ruled wording verbatim')
+ ok(src.includes(`t('Keep the file')`) && src.includes(`t('Restore anyway')`), 'with the ruled button labels')
+ ok(/ctx\.store\.restore\(gated, 'recover'\)/.test(src), 'and its Restore goes through the RECOVER direction')
+ ok(/onRecoveryOff\(docId => \{ if \(docId === ctx\.store\.doc\.docId\) showRecoveryOff\(\); \}\)/.test(src),
+ 'the recovery-off notice is wired to the kernel\'s signal, for THIS document only')
+ ok(src.includes(`t('Crash recovery is off for this document — it’s too large to keep a backup copy. Save often.')`),
+ 'with the ruled wording verbatim')
+ const main = readFileSync(fileURLToPath(new URL('../type/src/main.ts', import.meta.url)), 'utf8')
+ ok(/store\.restore\(doc, 'back'\)/.test(main), 'About\'s version restore goes through the BACK direction')
+}
+
+H('the restore rules themselves')
+{
+ for (const dir of ['back', 'recover'] as const) {
+ let threw = false; try { validateRestoreRules(RESTORE_RULES[dir]) } catch { threw = true }
+ ok(!threw, `the ${dir} rules pass the kernel's floor check at load`)
+ ok((RESTORE_RULES[dir].keepLive as Record<string, string>).comments === 'follows', `comments follow a ${dir} restore`)
+ }
+ ok(Object.keys(RESTORE_RULES.back.keepLive ?? {}).sort().join() === 'comments,signatures', 'back overrides comments and signatures, nothing else')
+ ok((RESTORE_RULES.back.keepLive as Record<string, string>).signatures === 'live', 'signatures stay LIVE going back')
+ ok(Object.keys(RESTORE_RULES.recover.keepLive ?? {}).join() === 'comments', 'recover overrides comments only — signatures follow the snapshot')
+ ok(RESTORE_RULES.recover.wholeSnapshot === true, 'and recover states its snapshot is WHOLE')
+ ok(JSON.stringify(RESTORE_RULES.recover.keepLiveWhenAbsent) === '["historySalt"]',
+ 'the only field whose absence keeps live is historySalt — never revisions, comments or signatures')
+}
+
+H('Sign is not undoable (ruling 7)')
+{
+ const k = await newKey()
+ const store = new Store(doc())
+ store.commit(d => { d.body[0].text = 'Payment is due within 60 days.' })
+ const signed = await sign(store.doc, k, { name: 'Alice' })
+ store.commit(d => { d.signatures.push(signed) }, { undoable: false })
+ ok(store.undo(), 'undo takes back the edit made BEFORE signing')
+ ok(store.doc.signatures.length === 1 && store.doc.signatures[0].sig === signed.sig,
+ 'and the signature stays — ⌘Z never removes one')
+ const main = readFileSync(fileURLToPath(new URL('../type/src/main.ts', import.meta.url)), 'utf8')
+ ok(/store\.commit\(d => \{ d\.signatures\.push\(entry\); \}, \{ undoable: false \}\)/.test(main),
+ 'the Sign button really commits with undoable: false')
+ ok(/store\.commit\(d => \{ d\.historySalt = salt; \}, \{ undoable: false \}\)/.test(main),
+ 'and so does minting the history salt')
+}
+
+H('type\'s recovery store is its OWN, never the legacy shared one')
+{
+ // The kernel names the store `${appId}-autosave`, and copies the legacy
+ // shared `bento-autosave` into an EMPTY app store once. An app — or a rig —
+ // configured with appId 'bento' would BE the legacy store, and a test that
+ // deletes a snapshot could then pass against the wrong database.
+ const kernel = readFileSync(fileURLToPath(new URL('../kernel/src/autosave.ts', import.meta.url)), 'utf8')
+ ok(/const dbName = \(\) => `\$\{appConfig\(\)\.appId\}-autosave`/.test(kernel), 'the kernel derives the store name from the appId')
+ const legacy = /const LEGACY_DB_NAME = '([^']+)'/.exec(kernel)?.[1]
+ ok(legacy === 'bento-autosave', 'and the legacy shared store is bento-autosave')
+ const main = readFileSync(fileURLToPath(new URL('../type/src/main.ts', import.meta.url)), 'utf8')
+ const appId = /configureApp\(\{\s*appId: '([^']+)'/.exec(main)?.[1]
+ ok(appId === 'bento-type' && `${appId}-autosave` === 'bento-type-autosave',
+ 'bento/type writes its recovery copies to bento-type-autosave')
+ ok(`${appId}-autosave` !== legacy, 'which is NOT the legacy shared store')
+ const self = readFileSync(fileURLToPath(import.meta.url), 'utf8')
+ const rigId = /configureApp\(\{ appId: '([^']+)'/.exec(self)?.[1]
+ ok(!!rigId && `${rigId}-autosave` !== legacy, 'and neither does this rig')
+}
+
console.log(`\n${checks - failures}/${checks} checks passed`)
if (failures) process.exit(1)
diff --git a/type/src/autosave.ts b/type/src/autosave.ts
index 377f3322..66628ad5 100644
--- a/type/src/autosave.ts
+++ b/type/src/autosave.ts
@@ -36,7 +36,7 @@
import { isEncryptionActive } from '../../kernel/src/save.ts';
import {
putRecovery, getRecovery, clearRecovery, addVersion, listVersions, pruneOld,
- clearVersions, type Snapshot,
+ clearVersions, recoveryLooksOlder, onRecoveryOff, type Snapshot,
} from '../../kernel/src/autosave.ts';
import { canonicalize } from './canon.ts';
import { registerReady, type FeatureContext } from './features.ts';
@@ -156,19 +156,38 @@ function ensureStyle(): void {
document.head.appendChild(style);
}
+/**
+ * What the recovery banner offers — maintainer ruling (9), 2026-10-15.
+ *
+ * When the recovered copy LOOKS OLDER than the file just opened (kernel
+ * recoveryLooksOlder: the snapshot's time is before the file's `modified`), it
+ * WARNS and makes keeping the file the default. It never hides the copy: the
+ * two clocks come from different devices, and hiding a copy that was really
+ * newer would lose work, which is the worse failure. When the age is unknown
+ * (either time missing or unparseable) there is no warning — and the ordinary
+ * banner makes no claim that the copy is newer or safe either.
+ */
+export function recoveryBanner(snap: Snapshot, doc: TypeDoc): { older: boolean; defaultAction: 'keep' | 'restore' } {
+ const older = recoveryLooksOlder(snap, doc);
+ return { older, defaultAction: older ? 'keep' : 'restore' };
+}
+
function showRecoveryBanner(ctx: FeatureContext, snap: Snapshot): void {
ensureStyle();
document.querySelector('.t-recover')?.remove();
const bar = document.createElement('div');
bar.className = 't-recover';
bar.setAttribute('role', 'alert');
+ const plan = recoveryBanner(snap, ctx.store.doc);
const when = new Date(snap.at).toLocaleString([], { hour: '2-digit', minute: '2-digit', month: 'short', day: 'numeric' });
const msg = document.createElement('span');
- msg.textContent = t('Unsaved changes from {when} were found.', { when });
+ msg.textContent = plan.older
+ ? t('This recovered copy looks older than the file you opened. Keep the file unless you know it’s newer.')
+ : t('Unsaved changes from {when} were found.', { when });
const restore = document.createElement('button');
- restore.className = 't-btn t-primary';
+ restore.className = plan.older ? 't-btn' : 't-btn t-primary';
restore.type = 'button';
- restore.textContent = t('Restore');
+ restore.textContent = plan.older ? t('Restore anyway') : t('Restore');
restore.addEventListener('click', () => {
// Gated AGAIN, against the document open at the click: identity comes from
// the live document, and that can change while this banner is up (Stop
@@ -178,17 +197,51 @@ function showRecoveryBanner(ctx: FeatureContext, snap: Snapshot): void {
// Never fall back to the copy gated when the banner appeared: its identity
// was the document's THEN, which is the staleness this re-gate exists for.
if (!gated) { bar.remove(); return; }
- ctx.store.replace(gated);
+ // RECOVER: the person chose this copy over the file, so its content AND its
+ // history come back together — revisions and the signatures over them are
+ // one unit and are never split (restorerules.ts).
+ ctx.store.restore(gated, 'recover');
ctx.refresh();
bar.remove();
ctx.toast(t('Restored your unsaved changes'));
});
const dismiss = document.createElement('button');
- dismiss.className = 't-btn';
+ dismiss.className = plan.older ? 't-btn t-primary' : 't-btn';
dismiss.type = 'button';
- dismiss.textContent = t('Discard');
+ // Keeping the file and discarding the recovered copy are the same act; when
+ // the copy looks older, it is named for what the person is choosing.
+ dismiss.textContent = plan.older ? t('Keep the file') : t('Discard');
dismiss.addEventListener('click', () => { void clearRecovery(ctx.store.doc.docId); bar.remove(); });
- bar.append(msg, restore, dismiss);
+ // The DEFAULT is first in the bar and takes focus: keep the file when the copy
+ // looks older, restore otherwise.
+ if (plan.defaultAction === 'keep') bar.append(msg, dismiss, restore);
+ else bar.append(msg, restore, dismiss);
+ document.body.appendChild(bar);
+ (plan.defaultAction === 'keep' ? dismiss : restore).focus();
+}
+
+/**
+ * Crash recovery switched off for this document — ruling (9). The kernel's
+ * per-document store refuses a recovery copy it cannot keep (too large), and
+ * says so once through onRecoveryOff. Shown once, dismissible, never a modal:
+ * the advice is to save often, and the person should be able to keep working.
+ */
+let recoveryOffShown = false;
+function showRecoveryOff(): void {
+ if (recoveryOffShown) return;
+ recoveryOffShown = true;
+ ensureStyle();
+ const bar = document.createElement('div');
+ bar.className = 't-recover t-recover-off';
+ bar.setAttribute('role', 'status');
+ const msg = document.createElement('span');
+ msg.textContent = t('Crash recovery is off for this document — it’s too large to keep a backup copy. Save often.');
+ const close = document.createElement('button');
+ close.className = 't-btn';
+ close.type = 'button';
+ close.textContent = t('Close');
+ close.addEventListener('click', () => bar.remove());
+ bar.append(msg, close);
document.body.appendChild(bar);
}
@@ -196,6 +249,7 @@ function wireAutosave(ctx: FeatureContext): void {
if (ctx.store.doc.readonly) return; // a player file has nothing to protect
void pruneOld();
void checkRecovery(ctx);
+ onRecoveryOff(docId => { if (docId === ctx.store.doc.docId) showRecoveryOff(); });
ctx.store.on(() => scheduleAutosave(ctx));
}
diff --git a/type/src/i18n/de.ts b/type/src/i18n/de.ts
index 7534effc..7d00b6dc 100644
--- a/type/src/i18n/de.ts
+++ b/type/src/i18n/de.ts
@@ -465,6 +465,10 @@ 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 document — it’s too large to keep a backup copy. Save often.": "Die Absturzwiederherstellung ist für dieses Dokument deaktiviert – es ist zu groß für eine Sicherungskopie. Speichern Sie häufig.",
"✓ valid": "✓ gültig",
"✕ the content has changed since this was signed": "✕ der Inhalt wurde seit der Signatur geändert",
"⚠ not linked to the previous signature": "⚠ nicht mit der vorherigen Signatur verknüpft",
diff --git a/type/src/i18n/es.ts b/type/src/i18n/es.ts
index 9d95b3fa..edbf337f 100644
--- a/type/src/i18n/es.ts
+++ b/type/src/i18n/es.ts
@@ -465,6 +465,10 @@ 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 document — it’s too large to keep a backup copy. Save often.": "La recuperación tras fallos está desactivada para este documento: es demasiado grande para guardar una copia de seguridad. Guarda a menudo.",
"✓ valid": "✓ válida",
"✕ the content has changed since this was signed": "✕ el contenido ha cambiado desde que se firmó",
"⚠ not linked to the previous signature": "⚠ no está enlazada con la firma anterior",
diff --git a/type/src/i18n/fr.ts b/type/src/i18n/fr.ts
index 53f73916..83b0a06d 100644
--- a/type/src/i18n/fr.ts
+++ b/type/src/i18n/fr.ts
@@ -465,6 +465,10 @@ 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 document — it’s too large to keep a backup copy. Save often.": "La récupération après plantage est désactivée pour ce document : il est trop volumineux pour en garder une copie de secours. Enregistrez souvent.",
"✓ valid": "✓ valide",
"✕ the content has changed since this was signed": "✕ le contenu a changé depuis la signature",
"⚠ not linked to the previous signature": "⚠ non liée à la signature précédente",
diff --git a/type/src/i18n/it.ts b/type/src/i18n/it.ts
index 4a67a7c9..99f7b5f2 100644
--- a/type/src/i18n/it.ts
+++ b/type/src/i18n/it.ts
@@ -465,6 +465,10 @@ 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 document — it’s too large to keep a backup copy. Save often.": "Il ripristino dopo un arresto anomalo è disattivato per questo documento: è troppo grande per conservarne una copia di backup. Salva spesso.",
"✓ valid": "✓ valida",
"✕ the content has changed since this was signed": "✕ il contenuto è cambiato dopo la firma",
"⚠ not linked to the previous signature": "⚠ non collegata alla firma precedente",
diff --git a/type/src/i18n/ja.ts b/type/src/i18n/ja.ts
index dfea0d45..7d918f34 100644
--- a/type/src/i18n/ja.ts
+++ b/type/src/i18n/ja.ts
@@ -465,6 +465,10 @@ 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 document — it’s too large to keep a backup copy. Save often.": "この文書のクラッシュ復旧はオフです — 大きすぎてバックアップを保存できません。こまめに保存してください。",
"✓ valid": "✓ 有効",
"✕ the content has changed since this was signed": "✕ 署名後に内容が変更されています",
"⚠ not linked to the previous signature": "⚠ 前の署名とつながっていません",
diff --git a/type/src/i18n/packed.ts b/type/src/i18n/packed.ts
index 2d0d865d..cb91fa9b 100644
--- a/type/src/i18n/packed.ts
+++ b/type/src/i18n/packed.ts
@@ -82,6 +82,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Copy document JSON": ["文書の JSON をコピー","复制文档 JSON","複製文件 JSON","Copiar el JSON del documento","Copier le JSON du document","Dokument-JSON kopieren","Copia il JSON del documento","Copiar JSON do documento"],
"Could not check right now.": ["現在確認できませんでした。","目前无法检查。","目前無法檢查。","No se pudo comprobar en este momento.","Impossible de vérifier pour le moment.","Konnte gerade nicht geprüft werden.","Impossibile controllare in questo momento.","Não foi possível verificar agora."],
"Could not read: {cols}": ["読み取れませんでした: {cols}","无法读取:{cols}","無法讀取:{cols}","No se pudo leer: {cols}","Lecture impossible : {cols}","Nicht lesbar: {cols}","Impossibile leggere: {cols}","Não foi possível ler: {cols}"],
+ "Crash recovery is off for this document — it’s too large to keep a backup copy. Save often.": ["この文書のクラッシュ復旧はオフです — 大きすぎてバックアップを保存できません。こまめに保存してください。","此文档的崩溃恢复已关闭 — 文件太大,无法保留备份。请经常保存。","此文件的當機復原已關閉 — 檔案太大,無法保留備份。請經常儲存。","La recuperación tras fallos está desactivada para este documento: es demasiado grande para guardar una copia de seguridad. Guarda a menudo.","La récupération après plantage est désactivée pour ce document : il est trop volumineux pour en garder une copie de secours. Enregistrez souvent.","Die Absturzwiederherstellung ist für dieses Dokument deaktiviert – es ist zu groß für eine Sicherungskopie. Speichern Sie häufig.","Il ripristino dopo un arresto anomalo è disattivato per questo documento: è troppo grande per conservarne una copia di backup. Salva spesso.","A recuperação de falhas está desativada para este documento: ele é grande demais para manter uma cópia de segurança. Salve com frequência."],
"Credits": ["クレジット","致谢","致謝","Créditos","Crédits","Danksagung","Crediti","Créditos"],
"Cross-reference": ["相互参照","交叉引用","交叉參照","Referencia cruzada","Renvoi","Querverweis","Riferimento incrociato","Referência cruzada"],
"Custom": ["カスタム","自定义","自訂","Personalizado","Personnalisé","Benutzerdefiniert","Personalizzato","Personalizado"],
@@ -165,6 +166,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Italic": ["斜体","斜体","斜體","Cursiva","Italique","Kursiv","Corsivo","Itálico"],
"Italic (⌘I)": ["斜体 (⌘I)","斜体 (⌘I)","斜體 (⌘I)","Cursiva (⌘I)","Italique (⌘I)","Kursiv (⌘I)","Corsivo (⌘I)","Itálico (⌘I)"],
"Justified": ["両端揃え","两端对齐","左右對齊","Justificado","Justifié","Blocksatz","Giustificato","Justificado"],
+ "Keep the file": ["ファイルを使う","保留文件","保留檔案","Conservar el archivo","Garder le fichier","Datei behalten","Tieni il file","Manter o arquivo"],
"Keep together": ["段落を分割しない","段落不跨页","段落不跨頁","Mantener unido","Ne pas scinder","Zusammenhalten","Non dividere","Manter junto"],
"Keep with next": ["次の段落と分離しない","与下段同页","與下段同頁","Mantener con el siguiente","Solidaire du suivant","Mit nächstem zusammenhalten","Solidale con il successivo","Manter com o próximo"],
"Keywords": ["キーワード","关键词","關鍵字","Palabras clave","Mots-clés","Schlagwörter","Parole chiave","Palavras-chave"],
@@ -287,6 +289,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Reset access…": ["アクセスをリセット…","重置访问权限…","重設存取權…","Restablecer acceso…","Réinitialiser l'accès…","Zugriff zurücksetzen …","Reimposta accesso…","Redefinir acesso…"],
"Resolve": ["解決","解决","解決","Resolver","Résoudre","Lösen","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"],
"Restored your unsaved changes": ["保存されていない変更を復元しました","已恢复未保存的更改","已還原未儲存的變更","Se han restaurado los cambios sin guardar","Vos modifications non enregistrées ont été restaurées","Nicht gespeicherte Änderungen wurden wiederhergestellt","Le modifiche non salvate sono state ripristinate","Suas alterações não salvas foram restauradas"],
"Results": ["結果","结果","結果","Resultados","Résultats","Ergebnisse","Risultati","Resultados"],
"Review": ["レビュー","审阅","校閱","Revisar","Révision","Überprüfung","Revisione","Revisão"],
@@ -393,6 +396,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"This paragraph has direct formatting of its own, on top of its style.": ["この段落にはスタイルとは別に直接指定された書式があります。","此段落在其样式之上还带有直接格式。","此段落在其樣式之上還帶有直接格式。","Este párrafo tiene formato directo propio, además de su estilo.","Ce paragraphe possède sa propre mise en forme directe, en plus de son style.","Dieser Absatz hat zusätzlich zu seiner Formatvorlage eine eigene direkte Formatierung.","Questo paragrafo ha una propria formattazione diretta, oltre al suo stile.","Este parágrafo tem formatação direta própria, além do seu estilo."],
"This paragraph is never split across a page break.": ["この段落は改ページで分割されません。","此段落绝不会被分页符拆分。","此段落絕不會被分頁符號拆分。","Este párrafo nunca se divide por un salto de página.","Ce paragraphe n'est jamais scindé par un saut de page.","Dieser Absatz wird nie durch einen Seitenumbruch getrennt.","Questo paragrafo non viene mai diviso da un'interruzione di pagina.","Este parágrafo nunca é dividido por uma quebra de página."],
"This picture is {size}, and embedding it makes the document that much bigger. Insert it anyway?": ["この画像は {size} あり、埋め込むと文書がその分大きくなります。それでも挿入しますか?","这张图片大小为 {size},嵌入后文档会相应增大。仍要插入吗?","這張圖片大小為 {size},嵌入後文件會相應增大。仍要插入嗎?","Esta imagen pesa {size}, e insertarla aumentará el documento en esa cantidad. ¿Insertarla de todos modos?","Cette image pèse {size}, et l'intégrer augmentera d'autant la taille du document. L'insérer quand même ?","Dieses Bild ist {size} groß, und das Einbetten macht das Dokument entsprechend größer. Trotzdem einfügen?","Questa immagine è di {size}, e incorporarla renderà il documento più grande di altrettanto. Inserirla comunque?","Esta imagem tem {size}, e incorporá-la aumenta o documento nessa mesma medida. Inserir mesmo assim?"],
+ "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 reference points at something that is no longer in the document": ["この参照は文書内に存在しないものを指しています","此引用指向的内容已不在文档中","此參照指向的內容已不在文件中","Esta referencia apunta a algo que ya no está en el documento","Cette référence pointe vers un élément qui n'est plus dans le document","Dieser Verweis zeigt auf etwas, das nicht mehr im Dokument ist","Questo riferimento punta a qualcosa che non è più nel documento","Esta referência aponta para algo que não está mais no documento"],
"Those side margins leave no room for text.": ["左右の余白が広すぎて本文のスペースがありません。","左右页边距过大,没有留出文本空间。","左右邊界過大,沒有留出文字空間。","Esos márgenes laterales no dejan espacio para el texto.","Ces marges latérales ne laissent aucune place au texte.","Diese seitlichen Ränder lassen keinen Platz für Text.","Questi margini laterali non lasciano spazio al testo.","Essas margens laterais não deixam espaço para o texto."],
"Those top and bottom margins leave no room for text.": ["上下の余白が広すぎて本文のスペースがありません。","上下页边距过大,没有留出文本空间。","上下邊界過大,沒有留出文字空間。","Esos márgenes superior e inferior no dejan espacio para el texto.","Ces marges du haut et du bas ne laissent aucune place au texte.","Diese oberen und unteren Ränder lassen keinen Platz für Text.","Questi margini superiore e inferiore non lasciano spazio al testo.","Essas margens superior e inferior não deixam espaço para o texto."],
diff --git a/type/src/i18n/pt.ts b/type/src/i18n/pt.ts
index d4b8a461..2901e3d7 100644
--- a/type/src/i18n/pt.ts
+++ b/type/src/i18n/pt.ts
@@ -476,6 +476,10 @@ 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 document — it’s too large to keep a backup copy. Save often.": "A recuperação de falhas está desativada para este documento: ele é grande demais para manter uma cópia de segurança. Salve com frequência.",
"✓ valid": "✓ válida",
"✕ the content has changed since this was signed": "✕ o conteúdo mudou desde que foi assinado",
"⚠ not linked to the previous signature": "⚠ não vinculada à assinatura anterior",
diff --git a/type/src/i18n/zh-Hans.ts b/type/src/i18n/zh-Hans.ts
index 1104e235..f77507ac 100644
--- a/type/src/i18n/zh-Hans.ts
+++ b/type/src/i18n/zh-Hans.ts
@@ -465,6 +465,10 @@ export const zhHans: 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 document — it’s too large to keep a backup copy. Save often.": "此文档的崩溃恢复已关闭 — 文件太大,无法保留备份。请经常保存。",
"✓ valid": "✓ 有效",
"✕ the content has changed since this was signed": "✕ 签名后内容已被更改",
"⚠ not linked to the previous signature": "⚠ 未与上一个签名关联",
diff --git a/type/src/i18n/zh-Hant.ts b/type/src/i18n/zh-Hant.ts
index f6a06b40..e78d8173 100644
--- a/type/src/i18n/zh-Hant.ts
+++ b/type/src/i18n/zh-Hant.ts
@@ -465,6 +465,10 @@ export const zhHant: 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 document — it’s too large to keep a backup copy. Save often.": "此文件的當機復原已關閉 — 檔案太大,無法保留備份。請經常儲存。",
"✓ valid": "✓ 有效",
"✕ the content has changed since this was signed": "✕ 簽署後內容已被變更",
"⚠ not linked to the previous signature": "⚠ 未與上一個簽署連結",
diff --git a/type/src/main.ts b/type/src/main.ts
index 3858a1e2..9b088748 100644
--- a/type/src/main.ts
+++ b/type/src/main.ts
@@ -261,7 +261,9 @@ const showAbout = () => openAbout({
onRestoreDoc: json => {
const doc = gateRestored(json, store.doc);
if (!doc) { alert(t('That saved version could not be restored.')); return; }
- store.replace(doc);
+ // Going BACK to an older version: its content returns, but history stays
+ // live, so restoring never discards revisions made since (restorerules.ts).
+ store.restore(doc, 'back');
editor.render();
schedule();
},
@@ -854,12 +856,15 @@ document.getElementById('sign')!.addEventListener('click', async () => {
// later signature commits to history under the same salt (canon.ts).
if (!store.doc.historySalt) {
const salt = newHistorySalt();
- store.commit(d => { d.historySalt = salt; });
+ store.commit(d => { d.historySalt = salt; }, { undoable: false });
}
const prev = store.doc.signatures[store.doc.signatures.length - 1] ?? null;
const entry = await signDoc(store.doc, key, { name, prev });
entry.at = new Date().toISOString();
- store.commit(d => { d.signatures.push(entry); });
+ // NOT undoable (ruling 7): a signature leaves only by its signer's or the
+ // owner's removal, never by ⌘Z — and a 'back' restore keeps signatures live
+ // (restorerules.ts), so an undo step here would only be a step that does nothing.
+ store.commit(d => { d.signatures.push(entry); }, { undoable: false });
markDirty(); showTab('sigs'); await paintSigs();
toast('Signed');
});
diff --git a/type/src/redlineview.ts b/type/src/redlineview.ts
index 065a91c1..998e4679 100644
--- a/type/src/redlineview.ts
+++ b/type/src/redlineview.ts
@@ -79,10 +79,15 @@ let repaint: (() => void) | null = null;
/** ⋯ → Snapshot: record the document as it stands now, the base a later Review compares against. */
export function takeSnapshot(ctx: FeatureContext): void {
const label = `Revision ${ctx.store.doc.revisions.length + 1}`;
+ // A Snapshot is a RECORD, not an edit: it is signed history, so ⌘Z must not
+ // take it back (an undo that removed one would silently change what every
+ // signature covers). Off the undo stack — safe because a document-level undo
+ // keeps history live (store.ts #apply), so undoing an earlier edit never
+ // removes a revision either.
ctx.store.commit(d => {
d.revisions.push({ id: uid('rev'), at: new Date().toISOString(), label,
body: JSON.parse(JSON.stringify(d.body)) });
- });
+ }, { undoable: false });
ctx.toast(`${label} recorded — edit, then Review`);
}
diff --git a/type/src/restorerules.ts b/type/src/restorerules.ts
new file mode 100644
index 00000000..887050e2
--- /dev/null
+++ b/type/src/restorerules.ts
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// How a whole-document restore treats each field — bento/type's row in the
+// kernel's restore table (kernel/src/docfields.ts applyRestore).
+//
+// Every whole-document restore goes through this, in one of two directions:
+//
+// 'back' undo / redo of a document-level step, and restoring a version
+// from About's version history — going BACK in time. Content
+// follows the older copy; history stays LIVE, so going back can
+// never discard revisions made since.
+// 'recover' the crash-recovery banner — the snapshot is a NEWER copy of this
+// same document, and the person chose it over the file. Content
+// AND history follow it, so revisions and the signatures over them
+// come back as one self-consistent unit, never split.
+//
+// Identity, mode and capability always stay live, in both directions — the
+// kernel's floor, which no override here can move.
+//
+// Overrides, per direction:
+//
+// `comments` is history-class (for COPYING — a view-only copy drops it) but
+// FOLLOWS a restore in both directions, so adding, resolving or deleting a
+// comment stays undoable like any edit. The class answers "how is it
+// copied"; this answers "does a restore move it" — two questions, kept apart.
+//
+// `signatures` is content-class (a view-only copy carries them, canon.ts v2)
+// but stays LIVE going 'back': ⌘Z past the moment of signing, or restoring a
+// version from before it, must not delete a signature. A signature leaves
+// only by its signer's or the owner's removal (ruling 7), and going back
+// leaves it honestly reading "changed". On 'recover' it FOLLOWS the snapshot,
+// so a signature made just before a crash comes back, together with the
+// revisions it commits to — never split.
+//
+// A paste (Replace from JSON, bento.loadDoc) is not a restore and does not come
+// through here: it never installs history at all (docclass.ts keepLiveHistory).
+
+import { restoreOverrides, validateRestoreRules, type RestoreDirection, type RestoreRules } from '../../kernel/src/docfields.ts';
+import { TYPE_FIELDS } from './docclass.ts';
+
+export const RESTORE_RULES: Readonly<Record<RestoreDirection, RestoreRules>> = {
+ back: {
+ classes: TYPE_FIELDS,
+ // restoreOverrides makes naming an identity, mode or capability field a
+ // COMPILE error; validateRestoreRules below is the runtime backstop.
+ keepLive: restoreOverrides(TYPE_FIELDS, { comments: 'follows', signatures: 'live' }),
+ },
+ recover: {
+ classes: TYPE_FIELDS,
+ keepLive: restoreOverrides(TYPE_FIELDS, { comments: 'follows' }),
+ // A recovery snapshot is the WHOLE document (autosave writes the entire doc),
+ // so on 'recover' a field it does not carry was DELETED before the crash and
+ // stays deleted — a removed comment, paragraph, footnote or style does not
+ // come back. Keyed on each field's EFFECTIVE keepLive (kernel #722), which is
+ // what makes it cover `comments`: history-class, but overridden to follow.
+ // The kernel's default; stated here because the guarantee is load-bearing
+ // (a resurrected redaction rides the next copy shared).
+ //
+ // Since kernel #726 this covers history fields left 'live' too: a whole
+ // snapshot without `revisions` means the history was cleared, and it stays
+ // cleared (parseDoc's [] default now only makes that doubly true).
+ wholeSnapshot: true,
+ // …with ONE exception. `historySalt` is minted by the first Sign and never
+ // removed or replaced in a live document (only a projection drops it, and
+ // a projection is not a recovery snapshot). So a snapshot WITHOUT it was
+ // taken BEFORE the first signature, never after a clearing. Removing the
+ // salt then would orphan every signature already made over it — each
+ // would read its history "missing", and the next Sign would mint a new
+ // salt that the earlier commitments can never match. A kept random salt
+ // reveals nothing even if the revisions are gone.
+ keepLiveWhenAbsent: ['historySalt'],
+ },
+};
+
+validateRestoreRules(RESTORE_RULES.back);
+validateRestoreRules(RESTORE_RULES.recover);
diff --git a/type/src/store.ts b/type/src/store.ts
index bfa13a9a..b30032e9 100644
--- a/type/src/store.ts
+++ b/type/src/store.ts
@@ -20,7 +20,8 @@
import type { Block, TypeDoc } from './model.ts';
import { copyIsReceiveOnly } from './model.ts';
-import { FROM_LIVE } from '../../kernel/src/docfields.ts';
+import { FROM_LIVE, applyRestore, type RestoreDirection } from '../../kernel/src/docfields.ts';
+import { RESTORE_RULES } from './restorerules.ts';
type Snap =
| { kind: 'doc'; doc: TypeDoc }
@@ -123,7 +124,8 @@ export class Store {
* one undo step, which is how a typed word is one press of ⌘Z rather than
* five. Any commit without a run, or with a different one, closes the group.
*/
- commit(fn: (doc: TypeDoc) => void, opts: { scope?: Scope; run?: string; system?: boolean } = {}): void {
+ commit(fn: (doc: TypeDoc) => void,
+ opts: { scope?: Scope; run?: string; system?: boolean; undoable?: boolean } = {}): void {
// A receive-only copy takes no USER edits — the relay would drop them, so
// they would live only here and quietly diverge this file from the room it
// claims to follow. `system` is for the sync session's own bookkeeping
@@ -133,8 +135,12 @@ export class Store {
if (this.#locked && !opts.system) return;
const scope = opts.scope ?? 'doc';
const run = opts.run ?? null;
- if (run === null || run !== this.#run) this.#push(this.#snap(scope));
- this.#run = run;
+ // `undoable: false` is for HISTORY writes (⋯ → Snapshot): they are a record,
+ // not an edit, so ⌘Z must not take them back. Safe only because a
+ // document-level undo keeps history LIVE (#apply below): undoing an
+ // earlier edit restores the content of before it, never the history.
+ if (opts.undoable !== false && (run === null || run !== this.#run)) this.#push(this.#snap(scope));
+ this.#run = opts.undoable === false ? this.#run : run;
fn(this.#doc);
this.#emit();
}
@@ -154,6 +160,19 @@ export class Store {
touch(): void { this.#emit(); }
/** Replace the whole document — loading a file, or restoring a revision. */
+ /**
+ * Restore a whole document, as ONE undoable step, in a direction:
+ * 'back' a version from About's version history
+ * 'recover' the crash-recovery banner's snapshot (a newer copy of this doc)
+ * See restorerules.ts. A paste is not a restore — it uses replace().
+ */
+ restore(doc: TypeDoc, direction: RestoreDirection): void {
+ this.#push({ kind: 'doc', doc: clone(this.#doc) });
+ this.#run = null;
+ this.#doc = applyRestore(this.#doc, doc, direction, RESTORE_RULES[direction]);
+ this.#emit();
+ }
+
replace(doc: TypeDoc): void {
this.#push({ kind: 'doc', doc: clone(this.#doc) });
this.#run = null;
@@ -164,9 +183,10 @@ export class Store {
#apply(s: Snap): Snap {
if (s.kind === 'doc') {
const inverse: Snap = { kind: 'doc', doc: clone(this.#doc) };
- const live = this.#doc;
- this.#doc = s.doc;
- keepLiveIdentity(this.#doc, live);
+ // Going BACK (undo or redo): content follows the snapshot, history stays
+ // live, identity/mode/capability stay live (restorerules.ts). So undo
+ // can never discard a revision, and comments undo like any edit.
+ this.#doc = applyRestore(this.#doc, s.doc, 'back', RESTORE_RULES.back);
return inverse;
}
// A block snapshot restores that block in place. If the block is gone (a