Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

kernel: make the intent of a save visible to a host (#213)

nyblnet651a15d97ca1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 224a77d3..6034ab31 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -122,6 +122,14 @@ jobs:
# file carrying a script tag.
run: node scripts/test-preview.ts
+ - name: Save-intent rig
+ # A host polyfilling showSaveFilePicker sees only the options bag, and
+ # must tell "overwrite the open document" from "make a second file" from
+ # that alone. It could not, and a browser extension overwrote a deck.
+ # `id` is the signal; if the three purposes ever collapse to one value
+ # every host silently loses the distinction.
+ run: node scripts/test-savepurpose.ts
+
- name: Guarded storage rig
# localStorage's absence is hostile: reading the PROPERTY throws, so
# `if (localStorage)` is itself the crash and one bare read at module
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2575a797..5fc428cc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,16 @@ pre-1.0.
## [Unreleased]
+- **"Save a copy…" and share exports remember their own folder.** The save
+ picker used one identity for every kind of save, so it opened wherever you
+ last put a view-only copy even when you were saving your working file.
+ In-place saves, copies and share exports now each remember their own last
+ location.
+
+ Underneath, this makes the *intent* of a save visible to anything hosting
+ Bento — `tray/ios`, and browser hosts — which previously could not tell ⌘S
+ from "Save a copy…" at all, because both arrived with identical arguments.
+
- **Fix: the topbar came back in the wrong order after the window narrowed and
widened again.** Below 700px the bar folds its buttons into two menus, and
unfolding put them back by a rule rather than by memory — everything except
diff --git a/kernel/src/save.ts b/kernel/src/save.ts
index c7a9c658..ec409193 100644
--- a/kernel/src/save.ts
+++ b/kernel/src/save.ts
@@ -469,8 +469,40 @@ const hasFsAccess = () => typeof (window as any).showSaveFilePicker === 'functio
*/
export const canWriteInPlace = () => hasFsAccess()
+/**
+ * What a save is FOR. The three cases want different files in different places,
+ * and until now the picker could not tell them apart.
+ *
+ * · `in-place` — ⌘S. Overwrite the document being edited.
+ * · `copy` — "Save a copy…". A second file, chosen by the author.
+ * · `share` — a suffixed export: view-only, presentation package, invite,
+ * template. Deliberately a new file, and never the ⌘S target.
+ */
+export type SavePurpose = 'in-place' | 'copy' | 'share'
+
+/**
+ * The picker `id` for a purpose — and, incidentally, the only signal a HOST has
+ * about what it is being asked to do.
+ *
+ * Browsers remember the last directory used per `id`, so distinct ids are worth
+ * having on their own: exports and working files usually live in different
+ * places, and one shared id made the picker open wherever you last put a
+ * view-only copy.
+ *
+ * The other reason is not incidental. A host that polyfills
+ * `showSaveFilePicker` (tray/ios over UIDocument, tray/webext over a directory
+ * grant) sees ONLY the options bag. `saveFile(doc, forcePicker)` used to reach
+ * this function with byte-identical arguments for ⌘S and for "Save a copy…",
+ * so a host could not distinguish them — and one that guessed wrong overwrote
+ * the open document instead of copying it. Measured, in a browser extension,
+ * 2026-08-02. Intent has to be explicit in the call, because it cannot be
+ * recovered from anything else in it.
+ */
+export const pickerIdFor = (purpose: SavePurpose): string =>
+ purpose === 'in-place' ? 'bento-doc' : purpose === 'copy' ? 'bento-copy' : 'bento-share'
+
async function pickHandle(
- doc: KernelDoc, suffix = '', suggestedName?: string,
+ doc: KernelDoc, suffix = '', suggestedName?: string, purpose: SavePurpose = 'in-place',
): Promise<FsFileHandle | null> {
try {
// The name to offer is the file the user is ALREADY looking at, when we know
@@ -489,7 +521,7 @@ async function pickHandle(
// browser remembers the last directory used under this id, so the second
// update onwards opens where the first one saved.
...(fileHandle ? { startIn: fileHandle } : {}),
- id: 'bento-doc',
+ id: pickerIdFor(purpose),
types: [{ description: appConfig().appName, accept: { 'text/html': ['.html'] } }],
})
} catch (err: any) {
@@ -521,7 +553,9 @@ export async function saveFile(doc: KernelDoc, forcePicker = false): Promise<Sav
const html = await serializeAuto(doc)
if (hasFsAccess()) {
if (forcePicker || !fileHandle) {
- const handle = await pickHandle(doc)
+ // 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')
if (!handle) return 'cancelled'
fileHandle = handle
await writeHandle(handle, html)
@@ -604,7 +638,7 @@ export async function writeUpdatedFileAs(
downloadFile(html, opts.suggestedName ?? suggestedFileName(doc, opts.suffix))
return true
}
- const handle = await pickHandle(doc, opts.suffix, opts.suggestedName)
+ const handle = await pickHandle(doc, opts.suffix, opts.suggestedName, 'share')
if (!handle) return false
// Share/export artifacts must NOT become the ⌘S target — otherwise the next
// save would overwrite e.g. a view-only copy with the FULL document (owner
diff --git a/scripts/test-savepurpose.ts b/scripts/test-savepurpose.ts
new file mode 100644
index 00000000..9a2eff16
--- /dev/null
+++ b/scripts/test-savepurpose.ts
@@ -0,0 +1,46 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Save-intent rig.
+//
+// node scripts/test-savepurpose.ts
+//
+// WHAT THIS PROVES. A HOST that polyfills `showSaveFilePicker` — tray/ios over
+// UIDocument, tray/webext over a directory grant — sees only the options bag.
+// It has to answer "am I being asked to overwrite the open document, or to make
+// a second file?" from that alone, and the two failure directions are not
+// symmetric: guessing "copy" costs a prompt, guessing "in-place" overwrites
+// somebody's work with no dialog and no warning.
+//
+// Measured, in a browser extension, 2026-08-02: it overwrote the open deck,
+// because ⌘S and "Save a copy…" reached the picker with byte-identical
+// arguments. `id` is now the signal. If these three ever collapse back to one
+// value, every host silently loses the ability to tell them apart — and finds
+// out the way we did.
+
+import { pickerIdFor, type SavePurpose } from '../kernel/src/save.ts'
+
+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 purposes: SavePurpose[] = ['in-place', 'copy', 'share']
+const ids = purposes.map(pickerIdFor)
+
+ok(new Set(ids).size === purposes.length,
+ `every purpose has its own picker id (${ids.join(', ')})`)
+ok(pickerIdFor('in-place') === 'bento-doc',
+ 'in-place keeps the original id, so no existing deck changes where its picker opens')
+ok(pickerIdFor('copy') !== pickerIdFor('in-place'),
+ 'a copy is distinguishable from an in-place save — the case that overwrote a file')
+ok(pickerIdFor('share') !== pickerIdFor('in-place'),
+ 'a share export is distinguishable from an in-place save')
+ok(ids.every((id) => /^[a-z0-9-]+$/.test(id) && id.length <= 32),
+ 'ids are plain and short enough for the picker to accept')
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/tray/README.md b/tray/README.md
index 9d7964a4..e5e129ca 100644
--- a/tray/README.md
+++ b/tray/README.md
@@ -41,10 +41,28 @@ as any page a browser renders.
window.showSaveFilePicker === 'function'`, and needs only
```
-showSaveFilePicker({suggestedName}) -> { name, createWritable() }
+showSaveFilePicker({suggestedName, id}) -> { name, createWritable() }
createWritable() -> { write(Blob|string), close() }
```
+`id` tells a host WHAT IT IS BEING ASKED TO DO, and a host that ignores it can
+destroy a file:
+
+| `id` | meaning | a host may |
+|---|---|---|
+| `bento-doc` | ⌘S — overwrite the document being edited | write in place, silently |
+| `bento-copy` | "Save a copy…" — a second file the author chooses | **must** let the author choose |
+| `bento-share` | a suffixed export: view-only, presentation package, invite, template | **must** let the author choose |
+
+Before this existed, ⌘S and "Save a copy…" reached the picker with
+byte-identical arguments, so a host could not distinguish them. One that guessed
+"in-place" overwrote the open deck with no dialog and no warning — measured in a
+browser extension, 2026-08-02. The two failure directions are not symmetric:
+guessing `copy` costs a prompt, guessing `in-place` costs the file. **When in
+doubt, prompt.**
+
+Pinned by `scripts/test-savepurpose.ts`.
+
So `Resources/bridge.js` polyfills that over a `UIDocument` bridge — three
methods. Two consequences: