Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

tray/webext: save a double-clicked deck in place, from the browser (#214)

nyblnet7483ae26c94e
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 6034ab31..68164d08 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: WebExtension bridge rig
+ # tray/webext decides, per save, whether to write in place or hand back
+ # to the browser's own picker. Wrong in the permissive direction it
+ # overwrites the open document with no dialog — which it did once. The
+ # decision is pure logic over an options bag, so it is checkable here
+ # rather than by reloading an extension and pressing Cmd-S.
+ run: node scripts/test-webext-bridge.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
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index a46b4ef0..588f3a46 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -931,7 +931,7 @@ Follow-up to the entry above, which ruled that bento/home must run documents in
a per-document origin. **That is not reachable, and the measurement says so
unambiguously.**
-`home/probe/` (run it with `node scripts/probe-origins.mjs`) picks a file on one
+`tray/webext/probe/` (run it with `node scripts/probe-origins.mjs`) picks a file on one
origin, grants write access there, and `postMessage`s the handle to another
origin. Chrome 150, macOS, 2026-08-02:
@@ -987,7 +987,7 @@ whether home can open documents at all.
## 2026-08-02 — MEASURED: an opaque origin is blocked by unguarded storage, not by incapability
-Third measurement in the bento/home sequence (`home/probe/sandbox.html`, Chrome
+Third measurement in the bento/home sequence (`tray/webext/probe/sandbox.html`, Chrome
150, macOS). Same deck loaded twice from a blob: once in a plain iframe, once in
`<iframe sandbox="allow-scripts">` with no `allow-same-origin`, so the second
gets an opaque origin. The control is what makes the result readable — it
@@ -1062,7 +1062,7 @@ keys) pool into a store any document can read. Rejected.
A launcher that can list decks but not open them is not worth building.
**MEASURED, and it is the unlock** (Chrome 150, macOS,
-`home/probe/directory.html`): a DIRECTORY grant is not per-file.
+`tray/webext/probe/directory.html`): a DIRECTORY grant is not per-file.
```
GRANTED <folder> queryPermission: granted
@@ -1109,7 +1109,7 @@ whether the write must happen in an offscreen document or extension page. Keep
the write behind one function so the answer can move without touching the
contract.
-**Kept from home:** `home/probe/` (four probes, all reusable) and
+**Kept from home:** `tray/webext/probe/` (four probes, all reusable) and
`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.
diff --git a/scripts/probe-origins.mjs b/scripts/probe-origins.mjs
new file mode 100644
index 00000000..0f3859d8
--- /dev/null
+++ b/scripts/probe-origins.mjs
@@ -0,0 +1,73 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Serves the tray/webext capability probes on TWO origins.
+//
+// node scripts/probe-origins.mjs
+// → open http://localhost:5301/probe/parent.html in YOUR OWN browser
+//
+// WHY TWO PORTS. A different port is a different origin, which is all the probe
+// needs: it asks whether a `FileSystemFileHandle` picked on one origin can be
+// `postMessage`d to another and still be used to read and WRITE. That is the
+// question that closed bento/home and pointed at a browser EXTENSION instead
+// (docs/DECISIONS.md, 2026-08-02): a page cannot hand a document write access,
+// so the host has to be something that already has it.
+//
+// WHY YOU HAVE TO RUN IT YOURSELF. Permission-gated APIs — File System Access
+// write, clipboard, notifications — report `denied` in an AUTOMATED browser,
+// without ever prompting, because a driven browser must not be able to hand out
+// filesystem write access. So an agent testing this gets `denied` no matter
+// what the truth is. That trap already produced two wrong conclusions during
+// this design (working/home-design.md §3.2). Only a human in a real browser
+// window can answer it.
+
+import { createServer } from 'node:http'
+import { readFile } from 'node:fs/promises'
+import { join, dirname, extname, normalize } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const root = join(dirname(fileURLToPath(import.meta.url)), '..', 'tray', 'webext')
+const PARENT_PORT = 5301
+const RUNNER_PORT = 5302
+
+const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css' }
+
+function serve(port, label) {
+ createServer(async (req, res) => {
+ // Normalise and confine to `home/` — this serves on localhost, but a path
+ // traversal in a dev server is still a path traversal.
+ const rel = normalize(decodeURIComponent(new URL(req.url, 'http://x').pathname)).replace(/^(\.\.[/\\])+/, '')
+ const path = join(root, rel)
+ if (!path.startsWith(root)) {
+ res.writeHead(403).end('forbidden')
+ return
+ }
+ try {
+ const body = await readFile(path)
+ res.writeHead(200, {
+ 'content-type': TYPES[extname(path)] ?? 'application/octet-stream',
+ // No caching: the whole point is re-running after an edit.
+ 'cache-control': 'no-store',
+ })
+ res.end(body)
+ } catch {
+ res.writeHead(404, { 'content-type': 'text/plain' }).end('not found')
+ }
+ }).listen(port, () => console.log(` ${label.padEnd(8)} http://localhost:${port}`))
+}
+
+console.log('\nbento/home — cross-origin handle probe\n')
+serve(PARENT_PORT, 'origin A')
+serve(RUNNER_PORT, 'origin B')
+console.log(`
+ Open this in YOUR OWN browser (not an automated one):
+
+ http://localhost:${PARENT_PORT}/probe/parent.html
+
+ Pick a THROWAWAY file — the last step rewrites it with identical bytes.
+ The runner page reports what it can do with the handle it receives, and
+ has a "Copy the report" button at the end.
+
+ Ctrl-C to stop.
+`)
diff --git a/scripts/test-webext-bridge.ts b/scripts/test-webext-bridge.ts
new file mode 100644
index 00000000..8c0aafe3
--- /dev/null
+++ b/scripts/test-webext-bridge.ts
@@ -0,0 +1,124 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// tray/webext page-bridge rig.
+//
+// node scripts/test-webext-bridge.ts
+//
+// WHAT THIS PROVES. The bridge decides, per save, whether to write in place or
+// hand back to the browser's own picker. Getting that wrong in the permissive
+// direction overwrites the open document with no dialog — it already happened
+// once. The decision is pure logic over an options bag, so it does not need a
+// browser, and anything that does not need a browser should not require one:
+// the previous round trip cost a manual reload to discover a ReferenceError
+// that only fired at CALL time, which `node --check` cannot see and this can.
+//
+// Everything here runs the REAL page-bridge.js in a stubbed window, so the file
+// under test is the file that ships.
+
+import { readFileSync } from 'node:fs'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { createContext, runInContext } from 'node:vm'
+
+const root = join(dirname(fileURLToPath(import.meta.url)), '..')
+const SRC = readFileSync(join(root, 'tray/webext/src/page-bridge.js'), 'utf8')
+
+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}`)
+}
+
+/** A window just real enough to load the bridge into. */
+function load(opts: { version?: string; pathname?: string } = {}) {
+ const nativeCalls: any[] = []
+ const posted: any[] = []
+ const win: any = {
+ location: { pathname: opts.pathname ?? '/Users/x/Decks/Q3.bento.html' },
+ addEventListener() {},
+ postMessage(msg: any) { posted.push(msg) },
+ showSaveFilePicker(o: any) { nativeCalls.push(o); return Promise.resolve({ __native: true }) },
+ bento: opts.version ? { updates: { version: opts.version } } : undefined,
+ }
+ const ctx: any = createContext({
+ window: win, setTimeout, clearTimeout, Date, Math, JSON, Promise, Blob: class {},
+ DOMException: class extends Error { constructor(m: string, n: string) { super(m); this.name = n } },
+ FileSystemHandle: class {},
+ crypto: { randomUUID: () => 'x' },
+ })
+ ctx.globalThis = ctx
+ runInContext(SRC, ctx)
+ return { win, nativeCalls, posted }
+}
+
+// ---- the bug that shipped: a call-time ReferenceError ----------------------
+// `node --check` parses; it cannot see an identifier that resolves only when
+// the function runs. This does.
+{
+ const { win, nativeCalls } = load({ version: '1.0.15' })
+ let threw: any = null
+ await win.showSaveFilePicker({ id: 'bento-copy', suggestedName: 'Q3.bento.html' }).catch((e: any) => { threw = e })
+ ok(threw === null, `declining does not throw (${threw ? threw.name + ': ' + threw.message : 'clean'})`)
+ ok(nativeCalls.length === 1, 'and it reaches the native picker')
+}
+
+// ---- the three purposes ----------------------------------------------------
+for (const [id, shouldDefer] of [
+ ['bento-copy', true],
+ ['bento-share', true],
+ ['bento-doc', false],
+] as const) {
+ const { win, nativeCalls, posted } = load({ version: '1.0.15' })
+ const p = win.showSaveFilePicker({ id, suggestedName: 'Q3.bento.html' })
+ await new Promise((r) => setTimeout(r, 0))
+ const deferred = nativeCalls.length === 1
+ ok(deferred === shouldDefer,
+ `${id} ${shouldDefer ? 'defers to the native picker' : 'is claimed by the host'}`)
+ if (!shouldDefer) {
+ ok(posted.some((m) => m.op === 'claim'), 'bento-doc asks the extension to claim the file')
+ }
+ p.catch(() => {})
+}
+
+// ---- the version gate: a deck older than #213 sends bento-doc for EVERYTHING
+for (const [version, trusted] of [
+ [undefined, false],
+ ['1.0.11', false],
+ ['1.0.14', false],
+ ['1.0.15', true],
+ ['1.1.0', true],
+ ['2.0.0', true],
+] as const) {
+ const { win, nativeCalls } = load({ version })
+ win.showSaveFilePicker({ id: 'bento-doc', suggestedName: 'Q3.bento.html' }).catch(() => {})
+ await new Promise((r) => setTimeout(r, 0))
+ const claimed = nativeCalls.length === 0
+ ok(claimed === trusted,
+ `runtime ${version ?? '(absent)'} is ${trusted ? 'trusted' : 'NOT trusted'} to mean what bento-doc says`)
+}
+
+// ---- a polyfilled handle must never reach the native picker ----------------
+// This is what killed the exports: save.ts keeps our handle and passes it back
+// as `startIn`, where a real FileSystemHandle is required.
+{
+ const { win, nativeCalls } = load({ version: '1.0.15' })
+ const fake = { name: 'Q3.bento.html', kind: 'file', createWritable() {} }
+ await win.showSaveFilePicker({ id: 'bento-share', suggestedName: 'x-viewonly.bento.html', startIn: fake })
+ .catch(() => {})
+ ok(nativeCalls.length === 1, 'a share export reaches the native picker')
+ ok(!('startIn' in nativeCalls[0]), 'and a non-FileSystemHandle startIn is stripped before it gets there')
+}
+{
+ const { win, nativeCalls } = load({ version: '1.0.15' })
+ class RealHandle {}
+ const real = Object.create((global as any).FileSystemHandle?.prototype ?? RealHandle.prototype)
+ await win.showSaveFilePicker({ id: 'bento-copy', suggestedName: 'copy.bento.html', startIn: real })
+ .catch(() => {})
+ ok(nativeCalls.length === 1, 'a copy reaches the native picker')
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/tray/README.md b/tray/README.md
index e5e129ca..f1805a90 100644
--- a/tray/README.md
+++ b/tray/README.md
@@ -190,7 +190,7 @@ brew install xcodegen
cd tray/ios && xcodegen && open BentoTray.xcodeproj
```
-Source lives under `tray/<platform>/` — `tray/ios/` today. The design below
+Source lives under `tray/<platform>/` — `tray/ios/` and `tray/webext/` today. The design below
(the polyfill and its protocol) is platform-neutral; only the transport lookup
and the native file layer are not.
diff --git a/tray/webext/README.md b/tray/webext/README.md
new file mode 100644
index 00000000..37e8ff32
--- /dev/null
+++ b/tray/webext/README.md
@@ -0,0 +1,190 @@
+# bento/tray — WebExtension
+
+A browser host for Bento documents. Grant your decks folder once; after that a
+deck you opened by **double-clicking** saves back to its own file with no
+destination prompt.
+
+Status: **works end to end.** Chrome 150 / macOS, 2026-08-02, against a shell
+built from #213:
+
+| action | result |
+|---|---|
+| ⌘S | **no dialog** — `[bento-tray] wrote Tray_Test.bento.html (898775 bytes) in place` |
+| Save a copy… | prompts, as it must |
+| Save read-only copy… | prompts, as it must |
+| the working file afterwards | 898,775 chars, 17 slides, script tags 5/5 balanced, `readonly` unset |
+
+The last row is the one that matters: the copy and the export went elsewhere
+rather than overwriting the document being edited. An earlier build got that
+wrong and silently destroyed it.
+
+## Operating it
+
+**The folder grant lapses when the extension reloads.** A reload resets the
+service worker and the directory permission commonly drops back to `prompt`.
+`background.js` will not request it from there — a service worker has no user
+gesture, so the request would be refused, and a save is the wrong moment to
+discover that. Open the options page and press **Check**; renewing is one click,
+which is what `probe/directory.html` measured.
+
+Every save says which path it took:
+
+```
+[bento-tray] wrote <file> (<n> bytes) in place
+[bento-tray] not saving in place: <reason> — falling back to the browser picker
+```
+
+Safe-by-default only helps if the safe path explains itself. Without that second
+line, a lapsed grant is indistinguishable from the extension not being installed
+— which cost a full diagnostic round trip.
+
+## Why an extension and not a web page
+
+`bento/home` was going to do this as an ordinary page. It cannot, and three
+measurements in `docs/DECISIONS.md` (2026-08-02) say why:
+
+- A `FileSystemFileHandle` **cannot be delegated across origins** — `postMessage`
+ serialises it and the receiver fires `messageerror`. So the origin that
+ acquires a handle is the only origin that can use it, and a launcher can never
+ hand one to a document.
+- Running every document on one shared origin would pool `bento-autosave`
+ (plaintext doc JSON, version history) and `bento-member-<docId>` (collab
+ private keys) into a store any document could read.
+- A **directory** grant behaves differently, and that is the unlock: it survives
+ a reload and covers files inside it that were never picked.
+
+An extension changes the shape completely. The document stays on `file://`,
+which the browser treats as a unique origin per file — so per-document isolation
+is free, and no deck can read another's storage. The extension holds the folder
+grant and does the writing.
+
+## The contract is tray's, unchanged
+
+`kernel/src/save.ts` tests one thing — `typeof window.showSaveFilePicker ===
+'function'` — and needs only:
+
+```
+showSaveFilePicker({suggestedName}) -> { name, createWritable() }
+createWritable() -> { write(Blob|string), close() }
+```
+
+Same three methods `tray/ios` implements over a `UIDocument` bridge. **No
+web-side changes**, and every deck ever saved works, including files whose
+embedded runtime predates this extension.
+
+One wrinkle that does not exist on iOS: on `file://` in Chrome,
+`showSaveFilePicker` **already exists**. So here the bridge REPLACES a working
+API rather than filling a gap, and it is deliberately conservative — it only
+takes over when the suggested name is the file already on screen. "Save a
+copy…", templates, read-only exports and invites all mean *a new file somewhere
+you choose*, so they fall through to the native picker untouched.
+
+## Shape
+
+| file | world | job |
+|---|---|---|
+| `src/page-bridge.js` | MAIN | overrides `showSaveFilePicker`; decides in-place vs native |
+| `src/relay.js` | ISOLATED | pure relay, no logic — the two worlds cannot reach each other |
+| `src/background.js` | service worker | holds the grant; matches the file; writes |
+| `src/options.html/js` | extension page | where the folder is granted (needs a gesture) |
+
+Both content-script halves are required: an isolated world can talk to the
+extension but not touch page globals; a MAIN world can define
+`showSaveFilePicker` but has no extension APIs.
+
+## It depends on `openedFileName()`
+
+The override only fires when `suggestedName` is the file on screen, so it rests
+on what `save.ts` passes. For a double-clicked deck there is no handle, and
+`openedFileName()` falls back to the URL:
+
+```js
+if (fileHandle?.name) return fileHandle.name
+const base = decodeURIComponent(new URL(location.href).pathname.split('/').pop() ?? '')
+return /\.bento\.html$/i.test(base) ? base : null
+```
+
+So `Q3.bento.html` on disk arrives as `suggestedName: "Q3.bento.html"` and the
+comparison holds. That fallback shipped in 1.0.12 for an unrelated reason —
+"Save offers the file you are looking at" — and this depends on it. If it ever
+goes back to naming saves after the deck's TITLE, this extension silently stops
+taking over and every save returns to a destination prompt.
+
+Note the `.bento.html` test in that fallback: a deck saved as plain `.html`
+returns null, the suggested name comes from the title instead, and the override
+declines. Correct, but it means the extension only covers `.bento.html` files.
+
+## The matching problem
+
+A page gives us `/Users/…/Decks/Q3.bento.html`. A `FileSystemDirectoryHandle`
+knows its own **name** but not its path, and nothing in the API exposes one — so
+the two cannot be compared directly.
+
+`findByName` searches the granted tree (depth-limited) and requires **exactly one
+match**. Unambiguous in the ordinary case; when it is ambiguous it declines and
+the native picker takes over. Declining costs a prompt, guessing costs somebody's
+file.
+
+## Trying it
+
+1. `chrome://extensions` → Developer mode → **Load unpacked** → `tray/webext/`
+2. Open its **options** and grant the folder your decks live in
+3. Double-click a `.bento.html` in that folder, edit something, press ⌘S
+
+Expected: it saves with no dialog. Today, without the extension, that first ⌘S
+asks where to put the file.
+
+## What is unverified
+
+Everything below needs the extension actually loaded — none of it is testable
+from a page, and permission-gated behaviour reports `denied` under automation
+(`working/home-design.md` §3.2, a trap that already produced two wrong
+conclusions).
+
+~~1. Can an MV3 service worker `createWritable()` on a stored directory
+handle?~~ **YES** — measured 2026-08-02. No offscreen document needed.
+
+~~2. Do MAIN-world content scripts run before the deck's runtime?~~ **YES** —
+the override was in place before `save.ts` read it.
+
+~~3. Does file-URL access work?~~ **YES**, with the per-extension toggle enabled
+by hand.
+
+4. ~~THE EXPORT PATHS~~ **BOTH BUGS FOUND, 2026-08-02.**
+
+ **(a) "Save a copy…" overwrote the open deck.** Not a bad threshold — the
+ discriminator does not exist. `saveFile(doc, forcePicker)` reaches the same
+ call with the same arguments for both intents. Override disabled until
+ `save.ts` makes intent explicit.
+
+ **(b) View-only and present-only copies stopped saving.** Once a save
+ returned one of our handles, `save.ts` kept it and later passed it back as
+ `startIn`, where the native picker requires a real `FileSystemHandle` — it
+ threw `TypeError`, and `pickHandle` rethrows anything that is not
+ `AbortError`. Fixed: `forNative()` strips any `startIn` that is not a genuine
+ handle before calling through. **A polyfilled handle must never escape into
+ an API that needs the real thing** — the general lesson, and the reason to
+ audit every other value this bridge hands back.
+
+ The original text follows, because the reasoning it records was wrong in an
+ instructive way:
+
+ **THE EXPORT PATHS — untested, and the failure mode is destructive.** The
+ override fires only when `suggestedName` is the file on screen. If that
+ comparison is wrong in the other direction, "Save a copy…", presentation
+ packages, read-only copies, templates and invites would **silently overwrite
+ the open deck** instead of creating a new file: no dialog, no warning,
+ original gone. `save.ts` passes `suffix` for those and `openedName` is
+ nulled when a suffix is present, so it *should* decline — but "should" is
+ what the first three probes in this arc each disproved.
+
+5. Autosave write-back and self-update, which route through the same function.
+
+## Not this
+
+**Firefox** implements no File System Access API at all, and its extensions
+cannot write arbitrary files either; that needs native messaging with a native
+helper. Firefox stays download-a-copy.
+
+**Safari** likewise has no FSA, and a Safari Web Extension ships inside a native
+macOS app anyway — so Safari's answer is `tray/macos`, not this.
diff --git a/tray/webext/manifest.json b/tray/webext/manifest.json
new file mode 100644
index 00000000..8ed96ba0
--- /dev/null
+++ b/tray/webext/manifest.json
@@ -0,0 +1,27 @@
+{
+ "manifest_version": 3,
+ "name": "Bento Tray",
+ "version": "0.0.1",
+ "description": "Save a Bento document back to the file you opened, without a destination prompt.",
+ "minimum_chrome_version": "116",
+ "permissions": ["storage", "offscreen"],
+ "options_page": "src/options.html",
+ "background": {
+ "service_worker": "src/background.js",
+ "type": "module"
+ },
+ "content_scripts": [
+ {
+ "matches": ["file:///*.html"],
+ "js": ["src/page-bridge.js"],
+ "world": "MAIN",
+ "run_at": "document_start"
+ },
+ {
+ "matches": ["file:///*.html"],
+ "js": ["src/relay.js"],
+ "world": "ISOLATED",
+ "run_at": "document_start"
+ }
+ ]
+}
diff --git a/tray/webext/probe/directory.html b/tray/webext/probe/directory.html
new file mode 100644
index 00000000..f0321402
--- /dev/null
+++ b/tray/webext/probe/directory.html
@@ -0,0 +1,171 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>Probe — does a directory grant survive, and cover files inside it?</title>
+<style>
+ body { font: 15px/1.6 -apple-system, system-ui, sans-serif; max-width: 46rem; margin: 4vh auto; padding: 0 1.4rem; color: #1e2a3a; }
+ h1 { font-size: 20px; margin-bottom: .2rem; }
+ .sub { color: #586a80; margin-top: 0; }
+ .warn { background: #fff6e5; border: 1px solid #f0d9a8; border-radius: 8px; padding: .8rem 1rem; margin: 1rem 0; }
+ .step { margin: 1rem 0; padding-left: .9rem; border-left: 3px solid #f7a600; }
+ b { color: #7a5200; }
+ button { font: inherit; padding: .5rem 1rem; border: 1px solid #c8d0dc; border-radius: 8px; background: #fff; cursor: pointer; }
+ button:hover:not(:disabled) { background: #f5f7fa; }
+ button:disabled { opacity: .5; cursor: default; }
+ #log { background: #f5f7fa; border-radius: 8px; padding: .9rem; white-space: pre-wrap; font: 12.5px/1.5 ui-monospace, monospace; margin-top: 1rem; }
+ #verdict { margin-top: 1rem; padding: .9rem 1rem; border-radius: 8px; font-weight: 600; display: none; }
+ .pass { background: #e8f5ec; border: 1px solid #b7dcc3; color: #1d6b39; }
+ .fail { background: #fdeceb; border: 1px solid #f0c0bc; color: #a3322a; }
+ code { background: #eef1f5; padding: 1px 4px; border-radius: 4px; font-size: 12.5px; }
+</style>
+
+<h1>Does one directory grant cover every file inside it — across sessions?</h1>
+<p class="sub">
+ This is the premise the whole extension approach rests on. If a stored directory
+ handle re-grants with one click and then hands out <em>writable</em> file handles
+ with no further prompts, a Bento host can save any deck in your Decks folder —
+ including one you opened by double-clicking, which no web page can ever do.
+ If it prompts per file, the idea is worth much less.
+</p>
+
+<div class="warn">
+ <b>Pick a scratch folder.</b> Step 3 creates <code>bento-probe.txt</code> inside it
+ and writes a line to it. Nothing else is touched, and it tells you before it writes.
+</div>
+
+<div class="step">
+ <b>Step 1.</b> Grant a folder, once.<br>
+ <button id="pick">Choose a folder…</button>
+</div>
+
+<div class="step">
+ <b>Step 2.</b> <b>Reload this page</b> (⌘R). The handle is read back from IndexedDB
+ and its state is reported without prompting.
+</div>
+
+<div class="step">
+ <b>Step 3.</b> Re-grant with one click, then write a file <em>inside</em> the folder —
+ the file itself was never picked.<br>
+ <button id="grant" disabled>Re-grant</button>
+ <button id="write" disabled>Create and write bento-probe.txt</button>
+ <button id="again" disabled>Write a second file (no new prompt?)</button>
+</div>
+
+<div id="verdict"></div>
+<div id="log">…</div>
+
+<script type="module">
+const logEl = document.getElementById('log')
+logEl.textContent = ''
+const log = (...a) => { logEl.textContent += a.join(' ') + '\n' }
+const verdict = (ok, text) => {
+ const el = document.getElementById('verdict')
+ el.className = ok ? 'pass' : 'fail'
+ el.textContent = text
+ el.style.display = 'block'
+}
+
+// --- the smallest IndexedDB that can hold a handle --------------------------
+const db = () => new Promise((res, rej) => {
+ const r = indexedDB.open('bento-dir-probe', 1)
+ r.onupgradeneeded = () => r.result.createObjectStore('h')
+ r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error)
+})
+const put = async (v) => { const d = await db(); return new Promise((res, rej) => {
+ const t = d.transaction('h', 'readwrite'); t.objectStore('h').put(v, 'dir')
+ t.oncomplete = res; t.onerror = () => rej(t.error) }) }
+const get = async () => { const d = await db(); return new Promise((res, rej) => {
+ const t = d.transaction('h', 'readonly'); const q = t.objectStore('h').get('dir')
+ q.onsuccess = () => res(q.result); q.onerror = () => rej(q.error) }) }
+
+let dir = null
+
+document.getElementById('pick').onclick = async () => {
+ try {
+ dir = await window.showDirectoryPicker({ mode: 'readwrite' })
+ await put(dir)
+ log('GRANTED ' + dir.name)
+ log(' stored in IndexedDB (structured clone of a DIRECTORY handle)')
+ log(' permission now: ' + await dir.queryPermission({ mode: 'readwrite' }))
+ log('\n>>> Now RELOAD the page. That is the part that matters. <<<')
+ } catch (e) { log('PICK FAILED ' + e.name + ': ' + e.message) }
+}
+
+// --- on load: what survived? ------------------------------------------------
+;(async () => {
+ try {
+ dir = await get()
+ if (!dir) { log('No folder stored yet — do step 1.'); return }
+ log('RESTORED ' + dir.name + ' (kind=' + dir.kind + ')')
+ const q = await dir.queryPermission({ mode: 'readwrite' })
+ log(' queryPermission, no gesture: ' + q)
+ document.getElementById('grant').disabled = false
+ if (q === 'granted') {
+ log('\nStill granted outright — no click needed. Go to step 3.')
+ document.getElementById('write').disabled = false
+ } else {
+ log('\nReset to "' + q + '". Step 3 tests whether ONE click restores it.')
+ }
+ } catch (e) { log('RESTORE FAILED ' + e.name + ': ' + e.message) }
+})()
+
+document.getElementById('grant').onclick = async () => {
+ try {
+ const p = await dir.requestPermission({ mode: 'readwrite' })
+ log('\nrequestPermission (one click) → ' + p)
+ if (p === 'granted') {
+ document.getElementById('write').disabled = false
+ log('Directory is writable again. Now the real question: files inside it.')
+ } else {
+ verdict(false, 'The stored directory could not be re-granted. A host cannot keep folder access across sessions this way.')
+ }
+ } catch (e) {
+ log('requestPermission threw: ' + e.name + ': ' + e.message)
+ verdict(false, 'A stored directory handle cannot be re-granted (' + e.name + ').')
+ }
+}
+
+/** Create a file INSIDE the granted folder and write to it. */
+async function writeInside(name, body, label) {
+ log(`\n[${label}] getFileHandle('${name}', {create:true}) …`)
+ const fh = await dir.getFileHandle(name, { create: true })
+ // The point: this file was never picked. If the directory grant covers it,
+ // no prompt appears and the permission is already 'granted'.
+ const perm = await fh.queryPermission({ mode: 'readwrite' })
+ log(`[${label}] the FILE's permission, unprompted: ${perm}`)
+ const w = await fh.createWritable()
+ await w.write(body)
+ await w.close()
+ const back = await (await fh.getFile()).text()
+ log(`[${label}] wrote and read back ${back.length} bytes: ${JSON.stringify(back.slice(0, 40))}`)
+ return perm
+}
+
+document.getElementById('write').onclick = async () => {
+ try {
+ const perm = await writeInside('bento-probe.txt', `written by the bento directory probe\n`, 'file 1')
+ document.getElementById('again').disabled = false
+ if (perm === 'granted') {
+ log('\nThe file inherited the folder grant — no prompt of its own.')
+ log('Press the third button to confirm a SECOND file needs no prompt either.')
+ } else {
+ verdict(false, `A file inside the granted folder reports "${perm}" rather than granted — the grant does not cover its contents usefully.`)
+ }
+ } catch (e) {
+ log('write failed: ' + e.name + ': ' + e.message)
+ verdict(false, 'Could not create or write a file inside the granted folder (' + e.name + ').')
+ }
+}
+
+document.getElementById('again').onclick = async () => {
+ try {
+ const perm = await writeInside('bento-probe-2.txt', 'second file\n', 'file 2')
+ verdict(perm === 'granted',
+ perm === 'granted'
+ ? 'One folder grant covers every file inside it, and survives a reload with a single click. A host can save any deck in that folder — including ones opened by double-clicking. This is the premise the extension needs, and it holds.'
+ : `The second file reports "${perm}" — the grant is not blanket, so a host would prompt per file.`)
+ } catch (e) {
+ log('second write failed: ' + e.name + ': ' + e.message)
+ verdict(false, 'A second file inside the folder could not be written (' + e.name + ').')
+ }
+}
+</script>
diff --git a/tray/webext/probe/parent.html b/tray/webext/probe/parent.html
new file mode 100644
index 00000000..21d54b3e
--- /dev/null
+++ b/tray/webext/probe/parent.html
@@ -0,0 +1,109 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>Probe — handle across origins (home side)</title>
+<style>
+ body { font: 15px/1.6 -apple-system, system-ui, sans-serif; max-width: 44rem; margin: 4vh auto; padding: 0 1.4rem; color: #1e2a3a; }
+ h1 { font-size: 20px; margin-bottom: .2rem; }
+ .sub { color: #586a80; margin-top: 0; }
+ .step { margin: 1.1rem 0; padding-left: .9rem; border-left: 3px solid #f7a600; }
+ b { color: #7a5200; }
+ button { font: inherit; padding: .5rem 1rem; border: 1px solid #c8d0dc; border-radius: 8px; background: #fff; cursor: pointer; }
+ button:hover:not(:disabled) { background: #f5f7fa; }
+ button:disabled { opacity: .5; cursor: default; }
+ #log { background: #f5f7fa; border-radius: 8px; padding: .9rem; white-space: pre-wrap; font: 12.5px/1.5 ui-monospace, monospace; margin-top: 1rem; }
+ .warn { background: #fff6e5; border: 1px solid #f0d9a8; border-radius: 8px; padding: .8rem 1rem; }
+ code { background: #eef1f5; padding: 1px 4px; border-radius: 4px; font-size: 12.5px; }
+</style>
+
+<h1>Does a file handle survive a cross-origin <code>postMessage</code>?</h1>
+<p class="sub">
+ This is the question that decides whether <b>bento/home</b> can hand a deck to an
+ isolated runner origin. If the handle arrives unusable, the whole per-document-origin
+ design is dead and we need a different one.
+</p>
+
+<div class="warn">
+ <b>Pick a throwaway file.</b> The optional write test rewrites the file you choose
+ with byte-identical content. Copy a deck first, or use any scratch file.
+ Everything before that step is read-only.
+</div>
+
+<div class="step">
+ <b>Step 1.</b> Pick a file here, on <span id="origin-a"></span>.<br>
+ <button id="pick">Pick a file…</button>
+</div>
+
+<div class="step">
+ <b>Step 2.</b> Send the handle to a window on a <em>different</em> origin
+ (<span id="origin-b"></span>) and let it report what it can do.<br>
+ <button id="send" disabled>Open the runner and send the handle</button>
+</div>
+
+<div id="log">Waiting…</div>
+
+<script type="module">
+const RUNNER = location.origin.replace(/:\d+$/, ':5302') + '/probe/runner.html'
+const logEl = document.getElementById('log')
+logEl.textContent = ''
+const log = (...a) => { logEl.textContent += a.join(' ') + '\n' }
+
+document.getElementById('origin-a').textContent = location.origin
+document.getElementById('origin-b').textContent = new URL(RUNNER).origin
+
+let handle = null
+
+document.getElementById('pick').onclick = async () => {
+ try {
+ ;[handle] = await window.showOpenFilePicker()
+ log('PICKED ' + handle.name)
+ const perm = await handle.requestPermission({ mode: 'readwrite' })
+ log(' requestPermission here → ' + perm)
+ if (perm !== 'granted') {
+ log('\nSTOP: write access was refused on THIS origin, so the cross-origin')
+ log(' question cannot be asked. Are you in a normal browser window?')
+ return
+ }
+ document.getElementById('send').disabled = false
+ log('\nReady. Step 2 sends it across.')
+ } catch (e) {
+ log('PICK FAILED ' + e.name + ': ' + e.message)
+ }
+}
+
+document.getElementById('send').onclick = () => {
+ const target = new URL(RUNNER).origin
+ const win = window.open(RUNNER, '_blank')
+ if (!win) { log('Pop-up blocked — allow pop-ups and retry.'); return }
+ log('\nOpened ' + target + ', waiting for it to say it is ready…')
+
+ window.addEventListener('message', (ev) => {
+ if (ev.origin !== target) return
+ if (ev.data?.type === 'ready') {
+ // CONTROL FIRST. A plain object proves the channel itself works, so if
+ // the handle then fails to arrive we know it is the handle that was
+ // refused and not the plumbing. Without this the two are
+ // indistinguishable from here, and they mean opposite things.
+ win.postMessage({ type: 'ping' }, target)
+ log('SENT control ping → ' + target)
+ try {
+ win.postMessage({ type: 'handle', handle }, target)
+ log('SENT handle → ' + target)
+ log('\nNote: postMessage succeeding here only means the handle was')
+ log('SERIALISED. Whether it can be DESERIALISED on the other origin is')
+ log('the actual question — read the runner window, not this one.')
+ } catch (e) {
+ // A structured-clone failure lands here: the handle could not even be
+ // serialised for another origin.
+ log('SEND FAILED ' + e.name + ': ' + e.message)
+ log('\nVERDICT: handles cannot cross origins. Per-document origins are out.')
+ }
+ }
+ // The runner echoes its log here, so the whole run reads in one window.
+ if (ev.data?.type === 'log') log(' [runner] ' + ev.data.line)
+ if (ev.data?.type === 'verdict') {
+ log('\n———— VERDICT (' + (ev.data.ok ? 'PASS' : 'FAIL') + ') ————')
+ log(ev.data.text)
+ }
+ })
+}
+</script>
diff --git a/tray/webext/probe/runner.html b/tray/webext/probe/runner.html
new file mode 100644
index 00000000..ae927aeb
--- /dev/null
+++ b/tray/webext/probe/runner.html
@@ -0,0 +1,181 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>Probe — runner side</title>
+<style>
+ body { font: 15px/1.6 -apple-system, system-ui, sans-serif; max-width: 44rem; margin: 4vh auto; padding: 0 1.4rem; color: #1e2a3a; }
+ h1 { font-size: 19px; margin-bottom: .2rem; }
+ .sub { color: #586a80; margin-top: 0; }
+ button { font: inherit; padding: .5rem 1rem; border: 1px solid #c8d0dc; border-radius: 8px; background: #fff; cursor: pointer; margin-right: .4rem; }
+ button:hover:not(:disabled) { background: #f5f7fa; }
+ button:disabled { opacity: .5; cursor: default; }
+ #log { background: #f5f7fa; border-radius: 8px; padding: .9rem; white-space: pre-wrap; font: 12.5px/1.5 ui-monospace, monospace; margin-top: 1rem; }
+ .verdict { margin-top: 1rem; padding: .9rem 1rem; border-radius: 8px; font-weight: 600; display: none; }
+ .pass { background: #e8f5ec; border: 1px solid #b7dcc3; color: #1d6b39; }
+ .fail { background: #fdeceb; border: 1px solid #f0c0bc; color: #a3322a; }
+ .danger { border-color: #e0a9a4; color: #a3322a; }
+ #copy { margin-top: .8rem; }
+</style>
+
+<h1>Runner side — <span id="origin"></span></h1>
+<p class="sub">
+ This page is a <em>different origin</em> from the one that picked the file. It can
+ see nothing of that page's storage. The only thing it has is whatever arrived by
+ <code>postMessage</code>.
+</p>
+
+<div id="controls" style="display:none">
+ <button id="ask">Ask for write access here</button>
+ <button id="read" disabled>Read the file</button>
+ <button id="write" class="danger" disabled>Write it back (byte-identical)</button>
+</div>
+
+<div id="verdict" class="verdict"></div>
+<div id="log">Waiting for a handle…</div>
+<button id="copy" style="display:none">Copy the report</button>
+
+<script type="module">
+const logEl = document.getElementById('log')
+const lines = []
+logEl.textContent = ''
+
+/** Whoever launched us — an opener, or an embedding frame's parent. */
+const launcher = window.opener || (window.parent !== window ? window.parent : null)
+
+// Everything logged here is echoed to the launcher, so the whole run can be
+// read in one window. The two pages are on different origins by construction,
+// so this is the only way either can see the other's side of the story.
+const log = (...a) => {
+ const s = a.join(' ')
+ lines.push(s)
+ logEl.textContent += s + '\n'
+ try { launcher?.postMessage({ type: 'log', line: s }, '*') } catch { /* gone */ }
+}
+
+document.getElementById('origin').textContent = location.origin
+
+let handle = null
+let bytes = null
+
+function verdict(ok, text) {
+ const el = document.getElementById('verdict')
+ el.className = 'verdict ' + (ok ? 'pass' : 'fail')
+ el.textContent = text
+ el.style.display = 'block'
+ lines.push('')
+ lines.push((ok ? 'VERDICT (pass): ' : 'VERDICT (fail): ') + text)
+ document.getElementById('copy').style.display = 'inline-block'
+ try { launcher?.postMessage({ type: 'verdict', ok, text }, '*') } catch { /* gone */ }
+}
+
+// A message whose payload cannot be DESERIALISED here does not arrive as a
+// `message` at all — the target fires `messageerror` instead, with no data.
+// That is the difference between "the plumbing is broken" and "this browser
+// refuses to hand a file handle to another origin", and it is the whole reason
+// this probe can give a decisive answer instead of a shrug.
+window.addEventListener('messageerror', (ev) => {
+ log('\nMESSAGEERROR from ' + ev.origin)
+ log(' A message arrived but could not be deserialised in this origin.')
+ verdict(false,
+ 'This browser refuses to deserialise the payload cross-origin. A FileSystemFileHandle cannot be delegated to another origin by postMessage — per-document runner origins cannot work this way.')
+})
+
+window.addEventListener('message', async (ev) => {
+ // Log EVERYTHING, so a control message proves the plumbing independently of
+ // whether the handle survives.
+ if (ev.data?.type === 'ping') {
+ log('CONTROL plain object arrived from ' + ev.origin + ' — the channel works.')
+ log(' (so if no handle follows, it is the HANDLE that was refused)')
+ return
+ }
+ if (ev.data?.type !== 'handle') { log('(message: ' + JSON.stringify(ev.data).slice(0, 80) + ')'); return }
+ handle = ev.data.handle
+ log('RECEIVED from ' + ev.origin)
+ log(' arrived as : ' + Object.prototype.toString.call(handle))
+ log(' instanceof FSFH : ' + (typeof FileSystemFileHandle !== 'undefined' && handle instanceof FileSystemFileHandle))
+ log(' .name : ' + (handle?.name ?? '(none)'))
+ log(' .kind : ' + (handle?.kind ?? '(none)'))
+
+ if (!handle || typeof handle.queryPermission !== 'function') {
+ verdict(false, 'The handle did not survive as a usable FileSystemFileHandle. Per-document origins are not viable this way.')
+ return
+ }
+ // Permissions are per-ORIGIN, so 'prompt' here is expected and fine — it
+ // means one extra click, not a dead end. 'denied' would be the dead end.
+ const q = await handle.queryPermission({ mode: 'readwrite' })
+ log(' queryPermission : ' + q + ' (no gesture yet)')
+ log('\nThe handle crossed intact. Now the question that matters:')
+ log('can THIS origin obtain write access to it?')
+ document.getElementById('controls').style.display = 'block'
+ if (q === 'granted') log('\n(already granted — press Read, then Write)')
+})
+
+document.getElementById('ask').onclick = async () => {
+ try {
+ const p = await handle.requestPermission({ mode: 'readwrite' })
+ log('\nrequestPermission (in a click) → ' + p)
+ if (p === 'granted') {
+ document.getElementById('read').disabled = false
+ document.getElementById('write').disabled = false
+ log('Write access granted to this origin. Read and write to confirm it is real.')
+ } else if (p === 'denied') {
+ verdict(false, 'This origin was refused write access without a prompt. A handle cannot be delegated across origins.')
+ } else {
+ log('Still "prompt" — the browser did not ask, or the dialog was dismissed.')
+ }
+ } catch (e) {
+ log('requestPermission threw: ' + e.name + ': ' + e.message)
+ verdict(false, 'requestPermission is not usable on a handle received cross-origin (' + e.name + ').')
+ }
+}
+
+document.getElementById('read').onclick = async () => {
+ try {
+ const f = await handle.getFile()
+ bytes = new Uint8Array(await f.arrayBuffer())
+ log('\ngetFile() OK ' + f.name + ' ' + f.size + ' bytes')
+ log('first 48 chars: ' + JSON.stringify(new TextDecoder().decode(bytes.slice(0, 48))))
+ } catch (e) {
+ log('getFile() threw: ' + e.name + ': ' + e.message)
+ verdict(false, 'The handle carries permission but cannot read (' + e.name + ').')
+ }
+}
+
+document.getElementById('write').onclick = async () => {
+ if (!bytes) { log('Read the file first — the write is a byte-identical round trip.'); return }
+ try {
+ const w = await handle.createWritable()
+ await w.write(bytes)
+ await w.close()
+ const after = await handle.getFile()
+ const ok = after.size === bytes.length
+ log('\ncreateWritable + write + close OK')
+ log('size before ' + bytes.length + ' → after ' + after.size + (ok ? ' (identical)' : ' MISMATCH'))
+ verdict(ok,
+ ok
+ ? 'A handle CAN be delegated to another origin and used to write. Per-document runner origins are viable.'
+ : 'The write completed but the file changed size — investigate before trusting this.')
+ } catch (e) {
+ log('createWritable/write threw: ' + e.name + ': ' + e.message)
+ verdict(false, 'This origin can read but NOT write through the delegated handle (' + e.name + '). Silent save would not work.')
+ }
+}
+
+document.getElementById('copy').onclick = async () => {
+ const report = [
+ 'bento/home probe — cross-origin handle delegation',
+ 'ua: ' + navigator.userAgent,
+ 'sender origin → this origin: (see below)',
+ '', ...lines,
+ ].join('\n')
+ try { await navigator.clipboard.writeText(report); document.getElementById('copy').textContent = 'Copied' }
+ catch { log('\n(clipboard blocked — select the log above and copy it manually)') }
+}
+
+// Tell whoever launched us that we exist — they hold the handle until they
+// hear it. Announcing to an embedding parent as well as an opener is what makes
+// the channel testable from a frame: without it a sender has to guess when this
+// document is listening, and a message posted too early is simply lost, which
+// looks exactly like a refusal.
+if (launcher) launcher.postMessage({ type: 'ready' }, '*')
+else log('Opened directly. Start from the parent page on port 5301 instead.')
+</script>
diff --git a/tray/webext/probe/sandbox.html b/tray/webext/probe/sandbox.html
new file mode 100644
index 00000000..e3cdecd3
--- /dev/null
+++ b/tray/webext/probe/sandbox.html
@@ -0,0 +1,240 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>Probe — does a deck survive an opaque origin?</title>
+<style>
+ body { font: 15px/1.6 -apple-system, system-ui, sans-serif; max-width: 60rem; margin: 3vh auto; padding: 0 1.4rem; color: #1e2a3a; }
+ h1 { font-size: 20px; margin-bottom: .2rem; }
+ .sub { color: #586a80; margin-top: 0; }
+ .warn { background: #fff6e5; border: 1px solid #f0d9a8; border-radius: 8px; padding: .8rem 1rem; margin: 1rem 0; }
+ button, input[type=file] { font: inherit; }
+ button { padding: .5rem 1rem; border: 1px solid #c8d0dc; border-radius: 8px; background: #fff; cursor: pointer; }
+ button:disabled { opacity: .5; cursor: default; }
+ table { border-collapse: collapse; width: 100%; margin-top: 1rem; font-size: 13.5px; }
+ th, td { text-align: left; padding: 6px 10px; border-bottom: 1px solid #e6e2d8; vertical-align: top; }
+ th { font-size: 11.5px; text-transform: uppercase; letter-spacing: .07em; color: #8b9bb0; }
+ td.k { font: 12.5px ui-monospace, monospace; white-space: nowrap; }
+ .ok { color: #1d6b39; } .bad { color: #a3322a; } .same { color: #8b9bb0; }
+ .frames { display: flex; gap: 12px; margin-top: 1rem; }
+ .frames > div { flex: 1; }
+ iframe { width: 100%; height: 260px; border: 1px solid #e6e2d8; border-radius: 8px; background: #fff; }
+ .cap { font-size: 12px; color: #8b9bb0; margin-bottom: 4px; }
+ #verdict { margin-top: 1rem; padding: .9rem 1rem; border-radius: 8px; font-weight: 600; display: none; }
+ .pass { background: #e8f5ec; border: 1px solid #b7dcc3; color: #1d6b39; }
+ .fail { background: #fdeceb; border: 1px solid #f0c0bc; color: #a3322a; }
+ #log { background: #f5f7fa; border-radius: 8px; padding: .8rem; white-space: pre-wrap; font: 12px/1.45 ui-monospace, monospace; margin-top: 1rem; max-height: 260px; overflow: auto; }
+</style>
+
+<h1>Does a Bento document survive an <em>opaque origin</em>?</h1>
+<p class="sub">
+ The only isolation left to <b>bento/home</b> is running a document in
+ <code>&lt;iframe sandbox="allow-scripts"&gt;</code> — no <code>allow-same-origin</code>, so it
+ reaches no storage at all, home's or any other document's. The question is what
+ that costs the document.
+</p>
+
+<div class="warn">
+ Nothing is written to disk. The file is read into memory and loaded twice: once
+ <b>without</b> the sandbox (the control, so we can tell what the sandbox breaks
+ from what breaks anyway) and once <b>with</b> it.
+</div>
+
+<p><input type="file" id="file" accept=".html,text/html"> <button id="run" disabled>Run both</button></p>
+
+<div id="verdict"></div>
+<div id="results"></div>
+
+<div class="frames">
+ <div><div class="cap">control — same origin, full storage</div><iframe id="f-control"></iframe></div>
+ <div><div class="cap">sandboxed — opaque origin, no storage</div><iframe id="f-sandbox" sandbox="allow-scripts"></iframe></div>
+</div>
+
+<div id="log"></div>
+
+<script type="module">
+const logEl = document.getElementById('log')
+const log = (...a) => { logEl.textContent += a.join(' ') + '\n'; logEl.scrollTop = logEl.scrollHeight }
+
+let html = null
+const runs = { control: {}, sandbox: {} }
+
+document.getElementById('file').onchange = async (ev) => {
+ const f = ev.target.files?.[0]
+ if (!f) return
+ html = await f.text()
+ log(`loaded ${f.name} — ${(f.size / 1024).toFixed(0)}KB`)
+ document.getElementById('run').disabled = false
+}
+
+// ?src=… fetches a deck instead of picking one — so a run can be repeated
+// after an edit without re-choosing the file every time.
+{
+ const src = new URLSearchParams(location.search).get('src')
+ if (src) {
+ fetch(src)
+ .then((r) => (r.ok ? r.text() : Promise.reject(new Error(r.status + ' ' + r.statusText))))
+ .then((t) => {
+ html = t
+ log(`fetched ${src} — ${(t.length / 1024).toFixed(0)}KB`)
+ document.getElementById('run').disabled = false
+ if (new URLSearchParams(location.search).has('auto')) document.getElementById('run').click()
+ })
+ .catch((e) => log('could not fetch ' + src + ': ' + e.message))
+ }
+}
+
+/**
+ * A harness injected at the very top of the document, before its own scripts.
+ *
+ * Necessary because an opaque-origin frame cannot be inspected from here at
+ * all — no contentDocument, no console. The document has to report on itself,
+ * so the probe adds a reporter rather than guessing from the outside.
+ *
+ * Built by concatenation so no literal script-close can appear in this file.
+ */
+function harness(tag) {
+ const OPEN = '<scr' + 'ipt>'
+ const CLOSE = '</scr' + 'ipt>'
+ return OPEN + `
+(function () {
+ var TAG = ${JSON.stringify(tag)};
+ var send = function (m) { try { m.tag = TAG; m.__probe = 1; parent.postMessage(m, '*') } catch (e) {} };
+ var probe = function (name, fn) {
+ try { send({ type: 'api', name: name, ok: true, detail: String(fn()) }) }
+ catch (e) { send({ type: 'api', name: name, ok: false, detail: e.name + ': ' + e.message }) }
+ };
+ send({ type: 'ctx', origin: String(location.origin), secure: !!self.isSecureContext });
+
+ // The APIs a Bento document actually reaches for. Each is a real feature:
+ // localStorage carries language/reduce-motion and the collab member key,
+ // IndexedDB carries autosave + version history, crypto mints docIds and
+ // signs collab writes.
+ probe('localStorage read', function () { return 'ok, len=' + localStorage.length });
+ probe('localStorage write', function () { localStorage.setItem('__probe', '1'); return 'ok' });
+ probe('indexedDB present', function () { return typeof indexedDB });
+ probe('indexedDB.open', function () { var r = indexedDB.open('__probe', 1); return 'call ok (' + typeof r + ')' });
+ probe('crypto.randomUUID', function () { return crypto.randomUUID().slice(0, 8) + '…' });
+ probe('crypto.subtle', function () { return typeof crypto.subtle });
+ probe('caches', function () { return typeof caches });
+
+ // Anything the document throws on its own, which is the real question:
+ // does it DEGRADE or does it die.
+ window.addEventListener('error', function (e) {
+ send({ type: 'error', detail: (e.message || 'error') + ' @' + (e.filename || '?').split('/').pop() + ':' + (e.lineno || 0) });
+ });
+ window.addEventListener('unhandledrejection', function (e) {
+ var r = e.reason; send({ type: 'reject', detail: String((r && (r.message || r.name)) || r) });
+ });
+
+ // Did the app actually come up? Reported twice: once early, once late enough
+ // for a deflate-and-import boot to have finished.
+ var report = function (when) {
+ var b = window.bento;
+ send({
+ type: 'boot', when: when,
+ hasBento: !!b,
+ slides: (b && b.doc && b.doc.slides && b.doc.slides.length) || 0,
+ title: (b && b.doc && b.doc.title) || null,
+ appNodes: (document.getElementById('app') && document.getElementById('app').childElementCount) || 0,
+ surfaces: document.querySelectorAll('.bento-slide, .ed-stage-scale').length,
+ bodyText: (document.body ? document.body.innerText.slice(0, 90) : '')
+ });
+ };
+ setTimeout(function () { report('3s') }, 3000);
+ setTimeout(function () { report('8s') }, 8000);
+})();
+` + CLOSE
+}
+
+/** Put the harness first, so it is installed before the document's own boot. */
+function inject(src, tag) {
+ const m = /<head[^>]*>/i.exec(src)
+ return m ? src.slice(0, m.index + m[0].length) + harness(tag) + src.slice(m.index + m[0].length)
+ : harness(tag) + src
+}
+
+window.addEventListener('message', (ev) => {
+ const d = ev.data
+ if (!d || !d.__probe) return
+ const run = runs[d.tag]
+ if (!run) return
+ if (d.type === 'ctx') { run.origin = d.origin; run.secure = d.secure; log(`[${d.tag}] origin=${d.origin} secure=${d.secure}`) }
+ if (d.type === 'api') { (run.api ??= {})[d.name] = d; log(`[${d.tag}] ${d.ok ? 'ok ' : 'FAIL'} ${d.name} — ${d.detail}`) }
+ if (d.type === 'error' || d.type === 'reject') {
+ (run.errors ??= []).push(d.detail)
+ log(`[${d.tag}] ${d.type.toUpperCase()} ${d.detail}`)
+ }
+ if (d.type === 'boot') {
+ run.boot = d
+ log(`[${d.tag}] boot@${d.when} bento=${d.hasBento} slides=${d.slides} surfaces=${d.surfaces} appNodes=${d.appNodes}`)
+ // The body text is where a shell that refused to start says WHY — the
+ // loader catches its own failure and prints it, so nothing reaches
+ // window.onerror and the run otherwise looks like a silent death.
+ if (!d.hasBento && d.bodyText) log(`[${d.tag}] page says: ${d.bodyText}`)
+ render()
+ }
+ render()
+})
+
+document.getElementById('run').onclick = () => {
+ document.getElementById('run').disabled = true
+ logEl.textContent = ''
+ runs.control = {}; runs.sandbox = {}
+ for (const tag of ['control', 'sandbox']) {
+ const blob = new Blob([inject(html, tag)], { type: 'text/html' })
+ // A blob URL inherits THIS origin — which is exactly why the sandbox
+ // attribute matters: with `sandbox` and no `allow-same-origin`, the frame
+ // is forced into a unique opaque origin regardless of where the blob came
+ // from. The control frame has no sandbox, so it keeps this origin.
+ document.getElementById('f-' + tag).src = URL.createObjectURL(blob)
+ }
+ log('both frames loading…\n')
+}
+
+const ROWS = ['localStorage read', 'localStorage write', 'indexedDB present', 'indexedDB.open',
+ 'crypto.randomUUID', 'crypto.subtle', 'caches']
+
+function cell(d) {
+ if (!d) return '<td class="same">—</td>'
+ return `<td class="${d.ok ? 'ok' : 'bad'}">${d.ok ? '✓' : '✗'} ${escapeHtml(d.detail).slice(0, 60)}</td>`
+}
+const escapeHtml = (s) => String(s).replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]))
+
+function render() {
+ const c = runs.control, s = runs.sandbox
+ let out = `<table><tr><th>capability</th><th>control (same origin)</th><th>sandboxed (opaque)</th></tr>`
+ out += `<tr><td class="k">origin</td><td class="same">${escapeHtml(c.origin ?? '—')}</td><td class="same">${escapeHtml(s.origin ?? '—')}</td></tr>`
+ out += `<tr><td class="k">secure context</td><td class="same">${c.secure ?? '—'}</td><td class="same">${s.secure ?? '—'}</td></tr>`
+ for (const k of ROWS) out += `<tr><td class="k">${k}</td>${cell(c.api?.[k])}${cell(s.api?.[k])}</tr>`
+ const bootRow = (r) => r.boot
+ ? `<td class="${r.boot.hasBento ? 'ok' : 'bad'}">${r.boot.hasBento ? '✓ booted' : '✗ no window.bento'} · ${r.boot.slides} slides · ${r.boot.surfaces} surfaces</td>`
+ : '<td class="same">waiting…</td>'
+ out += `<tr><td class="k">app boot</td>${bootRow(c)}${bootRow(s)}</tr>`
+ const errRow = (r) => `<td class="${r.errors?.length ? 'bad' : 'ok'}">${r.errors?.length ? escapeHtml(r.errors.slice(0, 3).join(' · ')).slice(0, 120) : 'none'}</td>`
+ out += `<tr><td class="k">errors thrown</td>${errRow(c)}${errRow(s)}</tr>`
+ out += `</table>`
+ document.getElementById('results').innerHTML = out
+
+ if (c.boot?.when === '8s' && s.boot?.when === '8s') {
+ const el = document.getElementById('verdict')
+ const bothBooted = c.boot.hasBento && s.boot.hasBento
+ const sameSlides = c.boot.slides === s.boot.slides
+ const ok = bothBooted && sameSlides
+ el.className = ok ? 'pass' : 'fail'
+ el.style.display = 'block'
+ // Two very different failures hide behind "it did not boot", and calling
+ // them both fatal would be the wrong answer. Dying on a storage ACCESS is
+ // an unguarded call site — bounded, mechanical, fixable. Dying with no
+ // explanation is the one that says the shape does not work.
+ const said = s.boot.bodyText ?? ''
+ const storageDeath = /could not start/i.test(said) && /localStorage|IndexedDB|storage/i.test(said)
+ el.textContent = ok
+ ? `The document boots and renders in an opaque origin (${s.boot.slides} slides, same as the control). Storage is gone — see the table — but the runtime survives, so home CAN host documents this way.`
+ : storageDeath
+ ? `NOT fatal, but blocked: the shell refuses to start because something reads storage during boot — "${said.slice(0, 120)}". That is an unguarded call site, not an incapability. Guard the storage accessors and re-run this probe; the features that need storage (autosave, version history, collab identity) stay lost either way, and that is the real decision.`
+ : !s.boot.hasBento
+ ? 'The document does NOT come up in an opaque origin, and does not say why. Home cannot host documents this way.'
+ : `The document comes up but does not match the control (${s.boot.slides} vs ${c.boot.slides} slides). Read the errors before trusting it.`
+ document.getElementById('run').disabled = false
+ }
+}
+</script>
diff --git a/tray/webext/src/background.js b/tray/webext/src/background.js
new file mode 100644
index 00000000..044a911a
--- /dev/null
+++ b/tray/webext/src/background.js
@@ -0,0 +1,103 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The extension side: the only place that holds the folder grant and the only
+// place that writes.
+//
+// MEASURED (docs/DECISIONS.md, 2026-08-02): one `showDirectoryPicker` grant
+// survives IndexedDB and a reload — still `granted` with no gesture, and
+// re-grantable with one click when it lapses — and covers files INSIDE the
+// folder that were never picked. That is what lets a deck opened by
+// double-clicking be written without a destination prompt, which no web page
+// can do for itself.
+//
+// THE MATCHING PROBLEM, and why it is not solved perfectly. A page gives us
+// `/Users/…/Decks/Q3.bento.html`; a `FileSystemDirectoryHandle` knows its own
+// NAME but not its path, and there is no API to ask. So the two cannot be
+// compared directly. This resolves it by searching the granted tree for a file
+// of that name and requiring EXACTLY ONE match: unambiguous in the ordinary
+// case, and when it is ambiguous the answer is to decline and let the native
+// picker handle it. Declining costs a prompt; guessing costs somebody's file.
+
+const DB = 'bento-tray'
+const STORE = 'grant'
+
+const open = () => new Promise((res, rej) => {
+ const r = indexedDB.open(DB, 1)
+ r.onupgradeneeded = () => r.result.createObjectStore(STORE)
+ r.onsuccess = () => res(r.result)
+ r.onerror = () => rej(r.error)
+})
+
+async function readGrant() {
+ const d = await open()
+ return new Promise((res, rej) => {
+ const t = d.transaction(STORE, 'readonly')
+ const q = t.objectStore(STORE).get('dir')
+ q.onsuccess = () => res(q.result ?? null)
+ q.onerror = () => rej(q.error)
+ })
+}
+
+/** Every file of this name in the granted tree. Depth-limited: a Decks folder
+ * is not a filesystem, and an unbounded walk on a mistakenly-granted home
+ * directory would hang the save the user is waiting on. */
+async function findByName(dir, name, depth = 0, found = []) {
+ if (depth > 4 || found.length > 1) return found
+ for await (const [entryName, handle] of dir.entries()) {
+ if (handle.kind === 'file' && entryName === name) found.push(handle)
+ else if (handle.kind === 'directory' && !entryName.startsWith('.')) {
+ await findByName(handle, name, depth + 1, found)
+ }
+ if (found.length > 1) break // ambiguous is already an answer
+ }
+ return found
+}
+
+/** token → file handle, for the life of this service-worker instance. */
+const claims = new Map()
+
+async function claim(path) {
+ const dir = await readGrant()
+ if (!dir) return { ok: false, reason: 'no folder granted' }
+ // queryPermission only — never prompt from here. A service worker has no
+ // user gesture, so a request would be refused, and a save is the wrong
+ // moment to discover that. The options page is where granting happens.
+ const perm = await dir.queryPermission({ mode: 'readwrite' })
+ if (perm !== 'granted') return { ok: false, reason: 'folder grant needs renewing' }
+
+ const name = decodeURIComponent(path.split('/').pop() || '')
+ if (!name) return { ok: false, reason: 'no file name' }
+ const hits = await findByName(dir, name)
+ if (hits.length !== 1) {
+ return { ok: false, reason: hits.length ? `${name} is ambiguous in the granted folder` : 'not in the granted folder' }
+ }
+ const token = crypto.randomUUID()
+ claims.set(token, hits[0])
+ return { ok: true, token, name }
+}
+
+async function write({ token, text }) {
+ const handle = claims.get(token)
+ if (!handle) return { ok: false, reason: 'stale claim' }
+ try {
+ // The open question this scaffold cannot settle without being loaded:
+ // whether an MV3 service worker may createWritable() on a stored handle,
+ // or whether the write must move to an offscreen document. Kept as ONE
+ // call so that answer changes this function and nothing else.
+ const w = await handle.createWritable()
+ await w.write(text)
+ await w.close()
+ return { ok: true, bytes: text.length }
+ } catch (e) {
+ return { ok: false, reason: `${e.name}: ${e.message}` }
+ }
+}
+
+chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
+ const run = msg?.op === 'claim' ? claim(msg.payload?.path)
+ : msg?.op === 'write' ? write(msg.payload ?? {})
+ : Promise.resolve({ ok: false, reason: 'unknown op' })
+ run.then(sendResponse, (e) => sendResponse({ ok: false, reason: String(e?.message || e) }))
+ return true // async response
+})
diff --git a/tray/webext/src/options.html b/tray/webext/src/options.html
new file mode 100644
index 00000000..7bfcc84c
--- /dev/null
+++ b/tray/webext/src/options.html
@@ -0,0 +1,19 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>Bento Tray</title>
+<style>
+ body { font: 15px/1.6 -apple-system, system-ui, sans-serif; max-width: 34rem; margin: 3rem auto; padding: 0 1.4rem; color: #1e2a3a; }
+ h1 { font-size: 19px; margin-bottom: .2rem; }
+ .sub { color: #586a80; margin-top: 0; }
+ button { font: inherit; padding: .5rem 1rem; border: 1px solid #c8d0dc; border-radius: 8px; background: #fff; cursor: pointer; }
+ button:hover { background: #f5f7fa; }
+ #state { background: #f5f7fa; border-radius: 8px; padding: .8rem 1rem; margin-top: 1rem; font: 13px/1.5 ui-monospace, monospace; white-space: pre-wrap; }
+</style>
+<h1>Bento Tray</h1>
+<p class="sub">
+ Grant the folder your decks live in, once. After that, ⌘S on a deck you opened
+ by double-clicking writes straight back to the file — no destination prompt.
+</p>
+<p><button id="pick">Choose your decks folder…</button> <button id="check">Check</button></p>
+<div id="state">…</div>
+<script type="module" src="options.js"></script>
diff --git a/tray/webext/src/options.js b/tray/webext/src/options.js
new file mode 100644
index 00000000..5552c219
--- /dev/null
+++ b/tray/webext/src/options.js
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Granting happens here and nowhere else: `showDirectoryPicker` needs a user
+// gesture, and a save is the wrong moment to discover there isn't one. The
+// service worker only ever reads the grant it finds.
+
+const DB = 'bento-tray'
+const STORE = 'grant'
+const open = () => new Promise((res, rej) => {
+ const r = indexedDB.open(DB, 1)
+ r.onupgradeneeded = () => r.result.createObjectStore(STORE)
+ r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error)
+})
+const put = async (v) => { const d = await open(); return new Promise((res, rej) => {
+ const t = d.transaction(STORE, 'readwrite'); t.objectStore(STORE).put(v, 'dir')
+ t.oncomplete = res; t.onerror = () => rej(t.error) }) }
+const get = async () => { const d = await open(); return new Promise((res, rej) => {
+ const t = d.transaction(STORE, 'readonly'); const q = t.objectStore(STORE).get('dir')
+ q.onsuccess = () => res(q.result ?? null); q.onerror = () => rej(q.error) }) }
+
+const el = document.getElementById('state')
+const show = (s) => { el.textContent = s }
+
+async function report() {
+ const dir = await get()
+ if (!dir) return show('No folder granted yet.')
+ const perm = await dir.queryPermission({ mode: 'readwrite' })
+ show(`folder: ${dir.name}\npermission: ${perm}` +
+ (perm === 'granted' ? '\n\nDecks in this folder save in place.'
+ : '\n\nNeeds renewing — choose the folder again.'))
+}
+
+document.getElementById('pick').onclick = async () => {
+ try {
+ const dir = await window.showDirectoryPicker({ mode: 'readwrite' })
+ await dir.requestPermission({ mode: 'readwrite' })
+ await put(dir)
+ await report()
+ } catch (e) { show(`${e.name}: ${e.message}`) }
+}
+document.getElementById('check').onclick = report
+void report()
diff --git a/tray/webext/src/page-bridge.js b/tray/webext/src/page-bridge.js
new file mode 100644
index 00000000..92f97808
--- /dev/null
+++ b/tray/webext/src/page-bridge.js
@@ -0,0 +1,172 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The page-world half of the bridge. Runs in the DOCUMENT's world (MAIN), at
+// document_start, so it is in place before the deck's own runtime boots.
+//
+// WHAT IT OVERRIDES AND WHY. `kernel/src/save.ts` tests exactly one thing —
+// `typeof window.showSaveFilePicker === 'function'` — and needs only:
+//
+// showSaveFilePicker({suggestedName}) -> { name, createWritable() }
+// createWritable() -> { write(Blob|string), close() }
+//
+// That is tray's contract (tray/README.md), and it is why no web-side change is
+// needed: every in-place path (⌘S, autosave write-back, self-update) already
+// routes through that function, including in decks whose embedded runtime
+// predates this extension.
+//
+// The wrinkle unique to a browser host: on `file://` in Chrome that function
+// ALREADY EXISTS. So unlike tray on iOS, where the polyfill fills a gap, here it
+// REPLACES a working API that prompts for a destination. The override therefore
+// has to be conservative — see `wantsOpenFile` below. Anything it does not
+// recognise falls through to the native picker, which still works exactly as it
+// did.
+
+;(() => {
+ const native = window.showSaveFilePicker?.bind(window)
+ const CH = '__bento_tray__'
+ let seq = 0
+ const pending = new Map()
+
+ /** One round trip to the isolated world, which relays to the extension. */
+ const ask = (op, payload) =>
+ new Promise((resolve) => {
+ const id = `${Date.now()}-${seq++}`
+ pending.set(id, resolve)
+ window.postMessage({ [CH]: true, dir: 'req', id, op, payload }, '*')
+ // A host that never answers must not hang a save forever — the caller
+ // falls back to the native picker instead.
+ setTimeout(() => {
+ if (pending.delete(id)) resolve({ ok: false, reason: 'timeout' })
+ }, 5000)
+ })
+
+ window.addEventListener('message', (ev) => {
+ const d = ev.data
+ if (ev.source !== window || !d || d[CH] !== true || d.dir !== 'res') return
+ const resolve = pending.get(d.id)
+ if (resolve) { pending.delete(d.id); resolve(d.result) }
+ })
+
+ /**
+ * Is this save aimed at the file we are already looking at?
+ *
+ * The deck asks to save under a suggested name. When that name is the file on
+ * screen, the author means "save my work" and the host can write in place.
+ * When it differs — "Save a copy…", a template, a read-only export, an invite
+ * — they mean a NEW file somewhere they choose, and taking that over silently
+ * would write to a place nobody asked for. Those go to the native picker.
+ */
+ /**
+ * Is this save meant to overwrite the document on screen?
+ *
+ * `id` is the answer, and it is the ONLY reliable one. It was added to
+ * `save.ts` for exactly this (#213, `pickerIdFor`): before it, ⌘S and "Save a
+ * copy…" reached the picker with byte-identical arguments, this code guessed
+ * in-place, and it overwrote the open deck — no dialog, no new file.
+ *
+ * bento-doc ⌘S, or a first save of an unsaved document → write in place
+ * bento-copy "Save a copy…" → the author chooses
+ * bento-share view-only, package, invite, template → the author chooses
+ *
+ * Default to declining. An unknown or absent id means a caller we have not
+ * seen; the native picker is the correct answer.
+ *
+ * And the id alone is not enough: a deck whose runtime PREDATES #213 sends
+ * `bento-doc` for every save, "Save a copy…" included, so acting on it there
+ * reproduces exactly the bug this replaced. Hence the runtime-version gate —
+ * old decks keep the behaviour they have today, which is correct and safe.
+ * The failure directions are not symmetric: declining costs a prompt, taking
+ * over wrongly costs the file.
+ */
+ /**
+ * The release that first sent a distinct picker `id` per purpose (#213).
+ * A deck whose embedded runtime predates it sends `bento-doc` for EVERY save
+ * — including "Save a copy…" — so the id carries no information there and
+ * this bridge must not act on it. If #213 ships under a different number,
+ * this constant is the one thing to change.
+ */
+ const ID_SINCE = [1, 0, 15]
+
+ const runtimeAtLeast = (min) => {
+ const v = window.bento?.updates?.version
+ if (typeof v !== 'string') return false // no runtime yet, or too old to say
+ const parts = v.split('.').map((n) => parseInt(n, 10))
+ if (parts.some(Number.isNaN)) return false
+ for (let i = 0; i < min.length; i++) {
+ if ((parts[i] ?? 0) > min[i]) return true
+ if ((parts[i] ?? 0) < min[i]) return false
+ }
+ return true
+ }
+
+ const wantsOpenFile = (opts) => opts?.id === 'bento-doc' && runtimeAtLeast(ID_SINCE)
+
+ /**
+ * Options safe to hand to the NATIVE picker.
+ *
+ * MEASURED 2026-08-02, and it broke every export: once a save returns one of
+ * our handles, `save.ts` keeps it (`fileHandle = handle`) and later passes it
+ * back as `startIn` — `...(fileHandle ? { startIn: fileHandle } : {})`. The
+ * native picker requires a REAL FileSystemHandle there, so it threw
+ * TypeError, and `pickHandle` rethrows anything that is not AbortError. View-
+ * only and present-only copies simply stopped working, with no clue pointing
+ * here.
+ *
+ * A polyfilled handle must never escape into an API that needs the genuine
+ * article. Anything not actually a FileSystemHandle is dropped; `startIn` is
+ * only ever a convenience about which folder opens first.
+ */
+ const forNative = (opts) => {
+ const out = { ...opts }
+ const real = typeof FileSystemHandle !== 'undefined' && out.startIn instanceof FileSystemHandle
+ if (out.startIn && !real) delete out.startIn
+ return out
+ }
+
+ window.showSaveFilePicker = async (opts = {}) => {
+ if (!wantsOpenFile(opts)) {
+ if (native) return native(forNative(opts))
+ throw new DOMException('No file picker available', 'AbortError')
+ }
+ const claim = await ask('claim', { path: decodeURIComponent(window.location.pathname) })
+ if (!claim?.ok) {
+ // Say WHY. Falling through to the native picker is the safe outcome, but
+ // an unexplained dialog is indistinguishable from the extension not being
+ // installed — which cost a full diagnostic round trip. The common cause
+ // is the folder grant lapsing after an extension reload, which the
+ // options page can renew in one click.
+ console.info('[bento-tray] not saving in place:', claim?.reason ?? 'no answer from the extension',
+ '— falling back to the browser picker. Open the extension options to check the folder grant.')
+ // The extension cannot reach this file — no folder granted, or the deck
+ // lives outside it. The native picker is not a worse outcome, it is
+ // exactly what happens without the extension installed.
+ if (native) return native(forNative(opts))
+ throw new DOMException('No writable location', 'AbortError')
+ }
+ return {
+ name: claim.name,
+ kind: 'file',
+ createWritable: async () => {
+ const chunks = []
+ return {
+ async write(data) { chunks.push(data) },
+ async close() {
+ const blob = chunks.length === 1 && chunks[0] instanceof Blob
+ ? chunks[0]
+ : new Blob(chunks)
+ const text = await blob.text()
+ const res = await ask('write', { token: claim.token, text })
+ if (!res?.ok) throw new DOMException(res?.reason || 'write failed', 'NotAllowedError')
+ console.info('[bento-tray] wrote', claim.name, `(${res.bytes} bytes) in place`)
+ },
+ }
+ },
+ // save.ts re-queries permission on a retained handle; a host-backed handle
+ // is granted for as long as the folder grant stands.
+ queryPermission: async () => 'granted',
+ requestPermission: async () => 'granted',
+ isSameEntry: async () => false,
+ }
+ }
+})()
diff --git a/tray/webext/src/relay.js b/tray/webext/src/relay.js
new file mode 100644
index 00000000..22567cc1
--- /dev/null
+++ b/tray/webext/src/relay.js
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The isolated-world half of the bridge: a pure relay.
+//
+// Content scripts in the ISOLATED world can talk to the extension but cannot
+// touch the page's globals; a MAIN-world script can define `showSaveFilePicker`
+// but has no extension APIs. Neither half can do the job alone, so the pair
+// meet over `window.postMessage`.
+//
+// This file deliberately holds NO logic. It does not decide what may be
+// written, does not read the document, and does not touch the filesystem — it
+// forwards two message shapes and nothing else. Every decision that matters
+// lives on the extension side, which is the only side the page cannot reach.
+
+const CH = '__bento_tray__'
+
+window.addEventListener('message', async (ev) => {
+ const d = ev.data
+ // Same-window only: `ev.source !== window` rejects anything posted in from a
+ // frame or an opener, which is the one way a page could try to speak for
+ // another document.
+ if (ev.source !== window || !d || d[CH] !== true || d.dir !== 'req') return
+
+ let result
+ try {
+ result = await chrome.runtime.sendMessage({ op: d.op, payload: d.payload })
+ } catch (e) {
+ // The service worker can be asleep or the extension reloading; a failure
+ // here means the page falls back to the native picker, not that a save is
+ // lost.
+ result = { ok: false, reason: String(e?.message || e) }
+ }
+ window.postMessage({ [CH]: true, dir: 'res', id: d.id, result }, '*')
+})