Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
home: hand the page the file it opened, through launchQueue (bridge half of B6) (#635)
nyblnet808d8947d6f7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a2067c33..7a27be1b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -547,6 +547,14 @@ jobs:# Source-shape checks; the Swift half self-skips without a toolchain.run: node scripts/test-home-bridge.ts+ - name: home launch handle rig+ # A page in a native host held no file handle until its first save, so+ # autosave never wrote the file. home/bridge.js now hands it over through+ # launchQueue — lazily, so documents from older runtimes keep their first+ # silent save — and a launch request the host cannot meet is refused,+ # never turned into an export. Runs the real bridge against a fake host.+ run: node scripts/test-home-launch.mjs+- name: tray mark is one source# tray-icon.svg is the only drawing of the mark. Everything else is# generated from it: the Android launcher vectors (which have no <rect>,diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex b67751c6..fa50419e 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -14,6 +14,59 @@ Decision. Why. Pointers.---+## 2026-10-05 — A native host hands the page the file it opened, through `launchQueue`++**Decision.** `home/bridge.js` (iOS and Android) defines `window.launchQueue`. When+a page calls `setConsumer`, the bridge asks the host for the open document (the+existing `begin`) and delivers its handle as `{ files: [handle] }` — the File+Handling API's shape, and the same handle `showSaveFilePicker` returns. The kernel+consumes it at boot and adopts the handle, so autosave writes the file from the+first edit.++**Why.** A page in a host held no handle until its first ⌘S, and every app's+autosave writes the file only with one. So an edit made and left never reached+disk — the 2026-08-16 observation the iOS submission pack carried as B6, found by+reading on 2026-10-05.++**Lazy, and why that is load-bearing.** Hosts treat the FIRST `begin` as the open+document and every later one as an export. The bridge asks nothing until a page+calls `setConsumer`, so a document saved by an older runtime — frozen code that+never will — keeps today's behaviour exactly: its first ⌘S gets the open document+silently. Asking eagerly at load would have turned that first save into a Save-As+prompt for every existing document. If a ⌘S already claimed the open document, the+consumer gets that same name; it never spends a second `begin`.++**A launch request is marked, and refused rather than exported.** The bridge sends+it as `begin` with `launch: true`. A host that cannot hand over the open document —+already handed out, or a grant it cannot write in place (Android's read-only+`ACTION_VIEW`) — answers **no**. Falling through to the export branch, as an+unmarked `begin` would, hands the page an EXPORT handle as if it were its own+file: nothing appears at open (`begin` only vends a name, on both hosts), but the+first autosave after any edit opens a save dialog nobody asked for. Measured on+Android by home-android on a control build; the same by reading on iOS, where the+picker comes with the first write.+The page then keeps today's path: its ⌘S behaves exactly as before.++**With it:** when the main frame commits a new page, a host forgets the hand-over —+so a reload's first claim is again the open document rather than an export — and+forgets the old page's remembered Save-As copies (2026-10-04 entries, #595/#600),+which are keyed by vended name: a new page's first export under the same name would+otherwise write into the previous page's copy without asking.++**Per host:** iOS does both in this change. **Android must refuse a `launch`+request it cannot meet before its bridge.js ships with this** — today its `begin`+exports when `!canWriteInPlace`, which on a read-only grant would now prompt at+open. Android's reload reset is the same one-line change as iOS's. Both are+home-android's; the parity table in home/README.md says "not yet" until they land.++**Guarded by** `scripts/test-home-launch.mjs`, which runs the real bridge against a+host applying the hosts' rule. It fails against an eager bridge, one that forgets+the first begin, one that drops the launch flag, one that assigns `launchQueue`+instead of defining it, and the pre-change bridge. `scripts/test-home-bridge.ts`+pins the iOS refusal and its order before the export branch, and the reset.++---+## 2026-10-04 — "+" offers only apps that can be made now, on every host**Decision.** A host's "New document" offers an app only when that app's@@ -46,10 +99,13 @@ It is still only the release channel, and still only when creating adocument. Probes run concurrently, so "+" waits for the slowest channel ratherthan the sum of them, capped at 8 s.-**Status.** iOS implements it first (`home/ios/Releases.swift`-`available()`). Android and the extension still show the aspirational list and-follow once this is accepted — until then the hosts differ on this one point,-recorded here rather than left to be found.+**Status.** **Accepted** by the maintainer, merged with #596 on 2026-10-04.+iOS implements it (`home/ios/Releases.swift` `available()`). Android and the+extension still show the aspirational list and are to follow — until they do,+the hosts differ on this one point, recorded here rather than left to be found.++---+## 2026-10-04 — iOS: "Save a copy…" reports what the picker actually did**Decision.** iOS follows the same rules as Android's 2026-10-04 entry ondiff --git a/home/README.md b/home/README.mdindex 3f1c60b9..6ed281e3 100644--- a/home/README.md+++ b/home/README.md@@ -462,6 +462,9 @@ here rather than discovered later.| bridge injected at document start | `WKUserScript(.atDocumentStart)` | `addDocumentStartJavaScript` | same || bridge reachable only from the document | every message checked: main frame + own origin (`BridgeSender`) | `allowedOriginRules` + `isMainFrame` | same || first `begin` = open document, later = export | ✓ | ✓ | same |+| the open document offered at boot via `launchQueue`, only to a page that asks | ✓ (`home/bridge.js`) | ✓ (`home/bridge.js`) | same |+| a launch request it cannot meet is refused, never exported | ✓ | **not yet** — a read-only grant would prompt at the first autosave | differs |+| a reload may claim the open document again | resets on main-frame commit | **not yet** | differs || an export can never address the open file | `exportName` + `targetsOpenDocument` | identical logic | same || page-supplied filenames sanitised | `safeFileName` | `safeFileName` | same || in-place write | `UIDocument.save(.forOverwriting)` | `openOutputStream(uri, "wt")` | same |diff --git a/home/bridge.js b/home/bridge.jsindex 1ebc37ff..d38bdc6d 100644--- a/home/bridge.js+++ b/home/bridge.js@@ -9,6 +9,8 @@// Bento needs exactly this much of the API (kernel/src/save.ts):// showSaveFilePicker({suggestedName}) -> { name, createWritable() }// createWritable() -> { write(Blob|string), close() }+// ...plus, from runtimes that know to ask, the file it was opened with:+// launchQueue.setConsumer(fn) -> fn({ files: [handle] })// ...and hasFsAccess() is just `typeof window.showSaveFilePicker === 'function'`.//// That is why the app needs NO changes to Bento and works with decks saved by@@ -89,10 +91,58 @@// Do NOT try to infer this by comparing suggestedName to the open file:// Bento derives that name from the DECK TITLE, so it rarely matches and// every save would wrongly prompt.- const name = await call('begin', { suggestedName: want })- return makeHandle(name)+ return makeHandle(await begin(want))}+ // The FIRST begin is the open document, by the host's rule above. Kept, so a+ // launch consumer that arrives after a ⌘S gets that same name rather than+ // asking again — a second begin would be an export, and would prompt.+ let opened = null+ const begin = (want, launch) => {+ const p = call('begin', launch ? { suggestedName: want, launch: true } : { suggestedName: want })+ if (!opened) {+ opened = p+ // A refused first begin vended nothing, so the next one may still claim it.+ p.catch(() => { if (opened === p) opened = null })+ }+ return p+ }++ // ----------------------------------------------------- the open document+ //+ // `launchQueue` is the File Handling API's way of handing a page the file it+ // was opened with. Without it, a page in this host holds NO handle until its+ // first ⌘S, and Bento's autosave writes the file only when it holds one — so+ // an edit made and left never reached disk. The kernel consumes this at boot+ // and adopts the handle, after which autosave writes in place from the first+ // edit.+ //+ // The request is marked `launch: true`. A host that cannot hand over the open+ // document — already handed out, or (Android) a read-only grant — must answer+ // no, never fall through to an export: the page would adopt an export handle as+ // its own file, and the first autosave after any edit would open a save dialog+ // nobody asked for (measured on Android; the same on iOS, where begin only+ // vends a name and the picker comes with the first write). bridge.js ships inside each host app,+ // so the flag and the host that honours it always arrive together.+ //+ // LAZY, deliberately: nothing is asked of the host until a page calls+ // setConsumer. A document saved by a runtime that predates this never calls+ // it, so its first ⌘S still gets the open document silently, exactly as+ // before. Asking eagerly at load would have spent that first begin and turned+ // every old document's first save into a Save-As prompt.+ //+ // Defined, not assigned: a Chromium WebView may already carry a native+ // launchQueue that will never deliver anything here, and an accessor+ // property silently ignores a plain assignment.+ Object.defineProperty(window, 'launchQueue', { configurable: true, enumerable: true, value: {+ setConsumer(consumer) {+ if (typeof consumer !== 'function') return+ ;(opened || begin('', true)).then(+ (name) => consumer({ files: [makeHandle(name)] }),+ () => { /* the host declined; the page keeps today's ⌘S path */ })+ },+ } })+// A FileSystemFileHandle faithful enough for apps that are not Bento.// Bento itself only ever touches createWritable/write/close, but this host// opens ANY self-contained HTML document, and a real app may well calldiff --git a/home/ios/EditorViewController.swift b/home/ios/EditorViewController.swiftindex 4551b1c0..92ab3b76 100644--- a/home/ios/EditorViewController.swift+++ b/home/ios/EditorViewController.swift@@ -363,6 +363,23 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR}}+ /// A new page holds no handles, so the open document is the next page's to+ /// claim again. Without this, a reload spent the first begin on the old+ /// page, and the+ /// new page's first save (or its launch handle) was taken for an export and+ /// prompted for a destination. Fires for main-frame commits only; a fragment+ /// change is not a commit.+ ///+ /// The remembered Save-As copies go with it. They are keyed by the name a+ /// handle was vended under, and a new page's export can be vended under the+ /// same name — it would then write into the previous page's copy without+ /// asking. A picker still open from the old page answers nobody; its+ /// delegate finds nothing pending and does nothing.+ func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {+ openDocumentVended = false+ exports = ExportSessions()+ }+func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse,decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {decisionHandler(navigationResponse.canShowMIMEType ? .allow : .download)@@ -483,6 +500,14 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKURif !openDocumentVended {openDocumentVended = truereply(id, ok: true, value: document.fileURL.lastPathComponent)+ } else if m["launch"] as? Bool == true {+ // The page asked for the file it was opened with (bridge.js+ // launchQueue), and it has already been handed out. That is a+ // no, never an export: the page would adopt the export handle+ // as its own file, and its first autosave after an edit would+ // open the export picker (exportCopy runs on the first write)+ // with nobody having asked to save anything.+ reply(id, ok: false, value: "the open document was already handed out")} else {// A copy/template/read-only export. Ask where it goes; it must// never land on the open document.diff --git a/scripts/test-home-bridge.ts b/scripts/test-home-bridge.tsindex 8ca207cd..1b478fff 100644--- a/scripts/test-home-bridge.ts+++ b/scripts/test-home-bridge.ts@@ -111,6 +111,27 @@ ok(exportCopy.includes('hasPrefix(') && exportCopy.includes('safeFileName(name)'&& exportCopy.indexOf('write(to: tmp)') > exportCopy.indexOf('hasPrefix('),'both guards come before the write — the ordering is the property, not their presence')+// The launch handle (bridge.js launchQueue). A launch request the host cannot+// meet must be REFUSED — falling through to the export branch hands the page an+// export handle as its own file, so the first autosave after an edit opens a save+// dialog nobody asked for. And a new page may claim the open document again, or a+// reload's first save is taken for an export; and it forgets the old page's+// Save-As copies, or its first export under a reused name lands in one unasked.+{+ const begin = swift.slice(swift.indexOf('case "begin":'), swift.indexOf('case "read":'))+ const refuse = begin.indexOf('m["launch"] as? Bool == true')+ const exportAt = begin.indexOf('exportName(')+ ok(refuse > 0 && /reply\(id, ok: false/.test(begin.slice(refuse, refuse + 600)),+ 'a launch request for an already-vended document is refused')+ ok(refuse > 0 && exportAt > refuse,+ 'the launch refusal comes before the export branch, so it can never reach a picker')+ const commit = slice(swift, 'didCommit navigation: WKNavigation!)')+ ok(/openDocumentVended = false/.test(commit),+ 'a main-frame commit lets the new page claim the open document again')+ ok(/exports = ExportSessions\(\)/.test(commit),+ "a main-frame commit forgets the old page's Save-As copies")+}+if (spawnSync('swiftc', ['--version']).status !== 0) {console.log(' skip no Swift toolchain on this machine — behaviour checks not run')console.log(`\n${checks - failures}/${checks} checks passed`)diff --git a/scripts/test-home-launch.mjs b/scripts/test-home-launch.mjsnew file mode 100644index 00000000..e265a7e0--- /dev/null+++ b/scripts/test-home-launch.mjs@@ -0,0 +1,130 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/home launch handle — home/bridge.js hands the page the file it was+// opened with, through `launchQueue`, without breaking documents that never ask.+//+// node scripts/test-home-launch.mjs (or BRIDGE=<path> to test a variant)+//+// WHY. A page in a native host held no handle until its first ⌘S, and autosave+// writes the file only with one, so an edit made and left never reached disk+// (iOS submission pack, B6). The kernel now consumes launchQueue at boot; this+// checks the bridge half.+//+// The bridge runs for real, in a vm, against a fake host that applies the+// hosts' actual rule — the FIRST begin is the open document, every later one is+// an export — because that rule is what makes laziness load-bearing: a bridge+// that asked eagerly at load would spend the first begin, and every old+// document's first ⌘S would become a Save-As prompt. Case 1 fails against+// exactly that variant.++import { readFileSync } from 'node:fs'+import vm from 'node:vm'+import { dirname, join, resolve } from 'node:path'+import { fileURLToPath } from 'node:url'++const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')+const SRC = readFileSync(process.env.BRIDGE || join(root, 'home/bridge.js'), 'utf8')+const OPEN = 'Q3 board.bento.html'++let failures = 0, checks = 0+const ok = (c, m) => { checks++; if (!c) failures++; console.log(` ${c ? 'ok ' : 'FAIL'} ${m}`) }+const tick = () => new Promise((r) => setTimeout(r, 0))++// One page in one host. `refuseFirst` makes the host decline the first begin.+function page({ transport = true, refuseFirst = false, nativeLaunchQueue = false, readOnly = false } = {}) {+ const sent = [], begins = []+ let vended = false, refused = !refuseFirst, n = 0+ const writes = []+ const win = { File, Blob, TextDecoder, ArrayBuffer, Promise, setTimeout }+ if (transport) {+ win.webkit = { messageHandlers: { bentoFile: { postMessage(m) {+ sent.push(m.op)+ if (m.op === 'begin') begins.push(m)+ setTimeout(() => {+ // The hosts' rule: the first begin that CAN be the open document is;+ // a launch request that cannot be is refused, never exported.+ if (m.op === 'begin') {+ if (!refused) { refused = true; return win.__bentoNativeReply(m.id, false, 'no') }+ if (!vended && !readOnly) { vended = true; return win.__bentoNativeReply(m.id, true, OPEN) }+ if (m.launch) return win.__bentoNativeReply(m.id, false, 'already handed out')+ return win.__bentoNativeReply(m.id, true, `export-${++n}.bento.html`)+ }+ if (m.op === 'write') { writes.push(m.name); return win.__bentoNativeReply(m.id, true, null) }+ win.__bentoNativeReply(m.id, true, '')+ }, 0)+ } } } }+ }+ // A WebView's own launchQueue, as an accessor that ignores assignment.+ if (nativeLaunchQueue) Object.defineProperty(win, 'launchQueue',+ { configurable: true, get: () => ({ setConsumer() {} }), set() {} })+ win.window = win+ vm.runInNewContext(SRC, win)+ return { win, sent, writes, begins }+}+const launch = (win) => new Promise((r) => win.launchQueue.setConsumer((p) => r(p)))++{ // 1. an old runtime never asks — nothing changes for it+ const { win, sent } = page()+ await tick(); await tick()+ ok(sent.length === 0, 'a page that never calls setConsumer sends nothing at load')+ const h = await win.showSaveFilePicker({ suggestedName: 'Deck' })+ ok(h.name === OPEN, "an old runtime's first ⌘S still gets the open document, no prompt")+}+{ // 2. a new runtime gets the open document at boot, and saves go there+ const { win, sent, writes } = page()+ const p = await launch(win)+ ok(p.files.length === 1 && p.files[0].kind === 'file' && p.files[0].name === OPEN,+ 'setConsumer delivers one file handle: the open document')+ const w = await p.files[0].createWritable(); await w.write('<html>edited'); await w.close()+ ok(writes[0] === OPEN, 'writing through the launch handle writes the open document')+ const e = await win.showSaveFilePicker({ suggestedName: 'copy' })+ ok(e.name !== OPEN, 'a later picker call is an export, never the open document')+ ok(sent.filter((o) => o === 'begin').length === 2, 'one begin for the launch, one for the export')+}+{ // 3. a ⌘S that came first is not asked for twice+ const { win, sent } = page()+ const h = await win.showSaveFilePicker({ suggestedName: 'Deck' })+ const p = await launch(win)+ ok(h.name === OPEN && p.files[0].name === OPEN, 'launch after a ⌘S delivers the same open document')+ ok(sent.filter((o) => o === 'begin').length === 1, 'and does not spend a second begin on it')+}+{ // 4. a refused first begin does not poison the next+ const { win } = page({ refuseFirst: true })+ let got = null+ win.launchQueue.setConsumer((p) => { got = p })+ await tick(); await tick()+ ok(got === null, 'a refused launch delivers nothing (the page keeps the ⌘S path)')+ const h = await win.showSaveFilePicker({ suggestedName: 'Deck' })+ ok(h.name === OPEN, 'the next begin may still claim the open document')+}+{ // 5. outside a host the bridge stays out of the way+ const { win } = page({ transport: false })+ ok(win.launchQueue === undefined && win.showSaveFilePicker === undefined,+ 'in a plain browser no launchQueue or picker is defined')+}+{ // 6. a WebView's own launchQueue does not shadow the bridge's+ const { win } = page({ nativeLaunchQueue: true })+ const p = await Promise.race([launch(win), new Promise((r) => setTimeout(() => r(null), 50))])+ ok(p && p.files[0].name === OPEN, "the bridge's launchQueue replaces a native one that would never deliver")+}+{ // 7. a document the host cannot write in place (Android read-only grant)+ const { win, begins } = page({ readOnly: true })+ let got = null+ win.launchQueue.setConsumer((p) => { got = p })+ await tick(); await tick()+ ok(begins[0] && begins[0].launch === true, 'the launch request is marked launch:true')+ ok(got === null, 'a read-only document gets no launch handle, so no export handle posing as its file')+ const h = await win.showSaveFilePicker({ suggestedName: 'Deck' })+ ok(h.name !== OPEN, 'its ⌘S still goes the export route, as before')+}+{ // 8. junk consumers are ignored rather than thrown on+ const { win, sent } = page()+ let threw = false+ try { win.launchQueue.setConsumer(null) } catch { threw = true }+ await tick()+ ok(!threw && sent.length === 0, 'setConsumer(non-function) is a no-op and asks nothing')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+process.exit(failures ? 1 : 0)