Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

kernel: recovery-banner 'looks older' signal + Save-a-copy keeps the original handle (#705)

nyblnetb14aa4244837
diff --git a/kernel/src/autosave.ts b/kernel/src/autosave.ts
index a8fe9d28..5ee83da6 100644
--- a/kernel/src/autosave.ts
+++ b/kernel/src/autosave.ts
@@ -250,6 +250,25 @@ export async function getRecovery(docId: string): Promise<Snapshot | null> {
return (await tx<Snapshot>(RECOVERY, 'readonly', (s) => s.get(docId))) ?? null
}
+/** Does the recovery snapshot look OLDER than the file now open? A SIGNAL for
+ * the app's banner, never a reason to HIDE the offer (maintainer ruling,
+ * 2026-10-15): the banner warns ("This recovered copy looks older than the
+ * file. Restore anyway?") and keeping the file is the default, but the snapshot
+ * is always offered. The two times come from different clocks — `snap.at` is
+ * this device's ms (`Date.now()`), `doc.modified` is whichever device last
+ * saved (an ISO string) — so a false "older" under skew must only soften copy,
+ * never suppress. Returns true ONLY when both times are known and the snapshot
+ * is the older; unknown either side → false (say nothing). */
+export function recoveryLooksOlder(snap: Snapshot, doc: { modified?: string | number }): boolean {
+ const ms = (t: string | number | undefined): number | undefined => {
+ if (typeof t === 'number') return Number.isFinite(t) ? t : undefined
+ if (typeof t === 'string') { const n = Date.parse(t); return Number.isNaN(n) ? undefined : n }
+ return undefined
+ }
+ const s = ms(snap.at), m = ms(doc.modified)
+ return s !== undefined && m !== undefined && s < m
+}
+
export async function clearRecovery(docId: string): Promise<void> {
const ds = docStore()
if (ds) {
diff --git a/kernel/src/save.ts b/kernel/src/save.ts
index 0d608329..b6014fab 100644
--- a/kernel/src/save.ts
+++ b/kernel/src/save.ts
@@ -525,7 +525,7 @@ export function suggestedFileName(doc: KernelDoc, suffix = ''): string {
// --- writing to disk --------------------------------------------------------
-type SaveResult = 'saved' | 'saved-as' | 'downloaded' | 'cancelled'
+type SaveResult = 'saved' | 'saved-as' | 'copied' | 'downloaded' | 'cancelled'
interface FsFileHandle {
createWritable(): Promise<{ write(data: Blob): Promise<void>; close(): Promise<void> }>
@@ -812,10 +812,17 @@ export async function saveFile(doc: KernelDoc, forcePicker = false): Promise<Sav
if (forcePicker || !fileHandle) {
// forcePicker is only ever "Save a copy…"; a first save of an unsaved
// document is in-place by intent even though it must also pick.
- const handle = await pickHandle(doc, '', undefined, forcePicker ? 'copy' : 'in-place')
+ const isCopy = forcePicker
+ const handle = await pickHandle(doc, '', undefined, isCopy ? 'copy' : 'in-place')
if (!handle) return 'cancelled'
- fileHandle = handle
await writeHandle(handle, html)
+ // "Save a copy…" keeps the open deck on the ORIGINAL (maintainer ruling,
+ // 2026-10-15): the copy is written, but the editor's handle stays with the
+ // original and the copy is NOT remembered as this doc's handle — so the
+ // next ⌘S still targets the original and reopening it still reconnects.
+ // Only a first in-place save retargets onto the file it just created.
+ if (isCopy) return 'copied'
+ fileHandle = handle
void persistHandle(doc, handle)
return 'saved-as'
}
diff --git a/scripts/test-autosave.ts b/scripts/test-autosave.ts
index 107e538f..0a33e7d7 100644
--- a/scripts/test-autosave.ts
+++ b/scripts/test-autosave.ts
@@ -31,7 +31,7 @@
import 'fake-indexeddb/auto'
import { configureApp } from '../kernel/src/app.ts'
-import { putRecovery, getRecovery, addVersion, listVersions } from '../kernel/src/autosave.ts'
+import { putRecovery, getRecovery, addVersion, listVersions, recoveryLooksOlder } from '../kernel/src/autosave.ts'
const APP = process.env.BENTO_TEST_APP || 'bento-slides'
const EXPECTED_DB = `${APP}-autosave`
@@ -154,5 +154,22 @@ ok(after.length === 4, `adding one version gives 4, not 7 — the legacy rows we
ok(!v.json.includes('OWNERPRIV') && v.json.includes('CONTENT-STAYS'), 'version keeps content, not secrets')
}
+// recoveryLooksOlder — the WARN signal (maintainer ruling): snap.at (ms) vs
+// doc.modified (ISO). A SIGNAL only; it never hides the offer.
+{
+ const snap = (at: number) => ({ docId: 'd', at, title: 't', json: '{}' })
+ const iso = (s: string) => ({ modified: s })
+ ok(recoveryLooksOlder(snap(Date.parse('2026-01-01T00:00:00Z')), iso('2026-02-01T00:00:00Z')) === true,
+ 'a snapshot older than the file is flagged (number ms vs ISO string, compared as ms)')
+ ok(recoveryLooksOlder(snap(Date.parse('2026-03-01T00:00:00Z')), iso('2026-02-01T00:00:00Z')) === false,
+ 'a newer snapshot is not flagged')
+ ok(recoveryLooksOlder(snap(Date.parse('2026-02-01T00:00:00Z')), iso('2026-02-01T00:00:00Z')) === false,
+ 'equal times are not "older"')
+ ok(recoveryLooksOlder(snap(123), {}) === false, 'no modified on the file (old doc) → say nothing (false)')
+ ok(recoveryLooksOlder(snap(123), iso('not a date')) === false, 'an unparseable modified → say nothing')
+ ok(recoveryLooksOlder(snap(200), { modified: 100 }) === false && recoveryLooksOlder(snap(100), { modified: 200 }) === true,
+ 'a numeric modified is compared directly (both-ms path)')
+}
+
console.log(`\n[${APP}] ${checks - failures}/${checks} checks passed`)
if (failures) process.exit(1)
diff --git a/scripts/test-file-handle.ts b/scripts/test-file-handle.ts
index 2cf863f6..4567e949 100644
--- a/scripts/test-file-handle.ts
+++ b/scripts/test-file-handle.ts
@@ -237,6 +237,18 @@ const settle = () => new Promise((r) => setTimeout(r, 10))
ok(/void persistHandle\(doc, handle\)/.test(body) && /void persistHandle\(doc, fileHandle\)/.test(body),
'saveFile persists the handle on both the picked and the reconnected/adopted save')
ok(/instanceof FileSystemFileHandle/.test(src), 'only a real FileSystemFileHandle is stored (host polyfill skipped)')
+ // "Save a copy…" keeps the open deck on the ORIGINAL (maintainer ruling
+ // 2026-10-15): the copy path writes the file but must NOT retarget fileHandle
+ // or persist the copy as the doc's handle — only a first in-place save does.
+ // Asserted at source like the ordering above (the write path needs a DOM).
+ {
+ const copyRet = body.indexOf("if (isCopy) return 'copied'")
+ const setHandle = body.indexOf('fileHandle = handle')
+ const persistPicked = body.indexOf('void persistHandle(doc, handle)')
+ ok(copyRet > 0, 'the copy path returns early with \'copied\'')
+ ok(setHandle > copyRet && persistPicked > copyRet,
+ 'fileHandle = handle and persistHandle(doc, handle) run ONLY after the isCopy early-return — never for a copy')
+ }
}
// --- embeddedDocBlock: the string-level #bento-doc extractor ------------------
diff --git a/scripts/test-slides-save-revisions.ts b/scripts/test-slides-save-revisions.ts
index db152754..e2c83dd4 100644
--- a/scripts/test-slides-save-revisions.ts
+++ b/scripts/test-slides-save-revisions.ts
@@ -192,5 +192,20 @@ console.log('\nthe editor writes through the queue')
'the CRDT stamp happens in the queue\'s prepare step, for auto-save and ⌘S')
}
+console.log('\nSave a copy… (a \'copied\' result) leaves the open deck dirty')
+{
+ // "Save a copy…" writes a DIFFERENT file (kernel returns 'copied' and keeps
+ // the editor on the original). The open deck still has unsaved edits, so the
+ // dot and the beforeunload prompt must STAY. Mutation: saving.ts clearing the
+ // dot for 'copied' (the old `if (current) setDirty(false)`) reds this.
+ const doc = newDoc(); doc.title = 'orig'
+ const store = new Store(doc)
+ const queue = createSaveQueue(store)
+ store.setDirty(true) // unsaved edits in the editor
+ const out = await saveRevision(store, queue, () => Promise.resolve('copied' as const))
+ check(out.kind === 'written' && (out as { result?: string }).result === 'copied', 'the copy write reports \'copied\'')
+ check(store.dirty, 'the open deck stays DIRTY after Save a copy — its edits are not on the original')
+}
+
console.log(`\n${checks - failures}/${checks} checks passed`)
process.exit(failures ? 1 : 0)
diff --git a/scripts/test-spaces-save-revisions.ts b/scripts/test-spaces-save-revisions.ts
index e3566957..d14aa117 100644
--- a/scripts/test-spaces-save-revisions.ts
+++ b/scripts/test-spaces-save-revisions.ts
@@ -292,5 +292,21 @@ console.log('\nmain.ts records the revision inside the queue for both writes of
check((src.match(/recordOnSave\(|recordRevision\(/g) ?? []).length === 2, 'and nowhere else in main.ts (no second, out-of-queue call)')
}
+// Save a copy… (a 'copied' result) is never a save of THIS document: it wrote a
+// different file, so it must not clear the dot or count as current. (Spaces'
+// copy does not route through saveRevision today, so this is the kernel #705
+// type-widen made safe at the saveRevision seam.) Mutation: saving.ts clearing
+// the dot / reporting current:true for 'copied' reds this.
+{
+ const p = parseSpace(JSON.stringify({ format: 'bento/spaces', version: 1, docId: 'cp', title: 'Copy', pages: [{ id: 'p', title: 'P', blocks: [{ id: 'b', type: 'p', html: 'x' }] }] }))
+ assert(p.ok)
+ const store = new SpacesStore(p.doc)
+ const queue = new SaveQueue({ getDocument: () => store.doc, getRevision: () => store.revision })
+ store.setDirty(true)
+ const out = await saveRevision(store, queue, () => Promise.resolve('copied' as const))
+ check(out?.kind === 'written' && out.current === false, 'a \'copied\' write is reported as NOT the current save of this document')
+ check(store.dirty, 'and the open space stays dirty — the copy went to another file')
+}
+
if (failures) { console.error(`\n${failures} save-race check(s) FAILED`); process.exit(1) }
console.log('\nspaces save race: an edit made during a write stays unsaved until a write that holds it lands')
diff --git a/scripts/test-type-autosave.ts b/scripts/test-type-autosave.ts
index 0902ff26..3b2a7670 100644
--- a/scripts/test-type-autosave.ts
+++ b/scripts/test-type-autosave.ts
@@ -23,6 +23,8 @@
// the document EXACTLY (byte-for-byte JSON) and lands as ONE undo step
// — never a silent, un-undoable swap of the document under the author.
+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'
@@ -165,6 +167,22 @@ H('THE CRASH CASE: sign, crash before the file is written, reload')
'a snapshot differing only in modified offers nothing — no banner on every reload')
}
+H('Save a copy… (a \'copied\' result) must not clear the dot (asserted at source)')
+{
+ // type's save() is module-level and DOM-bound, so this is pinned at source
+ // like the kernel's saveFile ordering. "Save a copy…" returns 'copied'; the
+ // open document is still unsaved, so dirty must stay set and paintTitle must
+ // not claim "Saved". Mutation: clearing dirty for any non-'cancelled' result
+ // (the old `dirty = false`) reds this.
+ const src = readFileSync(fileURLToPath(new URL('../type/src/main.ts', import.meta.url)), 'utf8')
+ const save = src.slice(src.indexOf('async function save('), src.indexOf('async function save(') + 1200)
+ ok(/if \(result === 'cancelled'\) return;/.test(save), 'save() returns early on cancelled')
+ ok(/if \(result === 'saved' \|\| result === 'saved-as' \|\| result === 'downloaded'\) dirty = false;/.test(save),
+ 'save() clears dirty ONLY for saved / saved-as / downloaded — never for a copy')
+ ok(!/if \(result === 'cancelled'\) return;\s*dirty = false;/.test(save),
+ 'and never clears dirty unconditionally after the cancelled guard')
+}
+
H('a recovery snapshot with NO signatures never pairs its revisions with the live signatures')
{
// Signatures cover content AND revisions, so a restore that took the
diff --git a/slides/src/saving.ts b/slides/src/saving.ts
index a6a6e5b6..519fc7dc 100644
--- a/slides/src/saving.ts
+++ b/slides/src/saving.ts
@@ -72,7 +72,11 @@ export async function saveRevision<R>(
if (result === 'cancelled') return { kind: 'cancelled' }
const current = saved.isCurrent()
// setDirty, not a bare assignment: it raises 'dirty', which repaints the
- // dot, and clearing never advances the revision.
- if (current) store.setDirty(false)
+ // dot, and clearing never advances the revision. Clear ONLY for a save of THIS
+ // file — not 'copied' ("Save a copy…" wrote a DIFFERENT file; the open deck is
+ // still unsaved, so the dot and the beforeunload prompt must stay). Allow-list,
+ // not deny, so a future result value never silently clears the dot.
+ const r = result as string
+ if (current && (r === 'saved' || r === 'saved-as' || r === 'downloaded')) store.setDirty(false)
return { kind: 'written', result: result as R, doc: saved.doc, current }
}
diff --git a/spaces/src/saving.ts b/spaces/src/saving.ts
index a39b8b7f..50937613 100644
--- a/spaces/src/saving.ts
+++ b/spaces/src/saving.ts
@@ -20,8 +20,12 @@ import type { SaveQueue } from '../../kernel/src/savequeue.ts'
import type { SpacesDoc } from './model'
import type { Store } from './store'
-/** What `saveFile` answers; 'cancelled' is the picker closed. */
-export type WriteResult = 'saved' | 'saved-as' | 'downloaded' | 'cancelled'
+/** What `saveFile` answers; 'cancelled' is the picker closed. 'copied' is a
+ * "Save a copy…" write that went to a DIFFERENT file (the kernel does not route
+ * spaces' copy through here today, so it does not occur at runtime yet — but
+ * the kernel type includes it, and a 'copied' save must never clear THIS
+ * document's dot). */
+export type WriteResult = 'saved' | 'saved-as' | 'copied' | 'downloaded' | 'cancelled'
export type SaveOutcome =
/** the space was swapped for another document while this save waited */
@@ -59,6 +63,10 @@ export async function saveRevision(
const result = saved.value
if (result === 'cancelled') return { kind: 'cancelled' }
const current = saved.isCurrent()
+ // A 'copied' write went to another file, so it is never a save of THIS
+ // document — do not clear the dot for it (keeps the fix robust if spaces ever
+ // routes "Save a copy…" through the queue).
+ if (result === 'copied') return { kind: 'written', result, doc: saved.doc, current: false }
// setDirty, not a bare assignment: it raises 'dirty', which is what repaints
// the dot, and it never advances the revision when clearing.
if (current) store.setDirty(false)
diff --git a/type/src/main.ts b/type/src/main.ts
index 725134d9..679e1cde 100644
--- a/type/src/main.ts
+++ b/type/src/main.ts
@@ -938,7 +938,10 @@ async function save(forcePicker = false) {
// document's OWN collab is kept — it is this file's.
const result = await saveFile(withoutEmbeddedCaps(store.doc), forcePicker);
if (result === 'cancelled') return;
- dirty = false;
+ // Clear the dot only for a save of THIS file. 'copied' ("Save a copy…") wrote a
+ // DIFFERENT file, so the open document is still unsaved — keep dirty set (and
+ // paintTitle then shows the unsaved state, not a false "Saved to …").
+ if (result === 'saved' || result === 'saved-as' || result === 'downloaded') dirty = false;
paintTitle();
}