Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
saves: write a static page-one preview so file managers can thumbnail a deck
nyblnete2fcc7f636d3
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex b379da1b..12bb9c68 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -109,6 +109,13 @@ jobs:# Tampered pack, tampered index, unsigned index — each must be refused.run: node scripts/test-packs.ts+ - name: First-page preview rig+ # Every save writes a static render of page one for file-manager+ # thumbnails. Two decisions in that path fail silently: an encrypted+ # deck must never carry one, and author content must never reach the+ # file carrying a script tag.+ run: node scripts/test-preview.ts+- name: CRDT convergence rig# 40 seeds locally; deeper on CI where the seconds are free.run: SEEDS=300 node scripts/test-sync.tsdiff --git a/AGENTS.md b/AGENTS.mdindex c0d8362e..8b20b6c9 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -45,18 +45,23 @@ are in `docs/DECISIONS.md` — don't reopen them.4. **After any change to `slides/src/sync/crdt.ts`, run`node scripts/test-sync.ts`.** The convergence rig has caught 15+ orderingbugs; a green typecheck means nothing for CRDT correctness.-5. **New UI strings go into ALL i18n catalogs** (ja, zh-Hans, zh-Hant, es, fr,+5. **A password-protected deck never carries a plaintext preview of page one.**+ Saves write a static first-page render into the shell for file-manager+ thumbnails (`kernel/src/save.ts`, `slides/src/preview.ts`); `bento/enc` decks+ are vetoed and any existing preview is stripped. Run+ `node scripts/test-preview.ts` after touching that path.+6. **New UI strings go into ALL i18n catalogs** (ja, zh-Hans, zh-Hant, es, fr,de, it). English-string-as-key; never call `t()` in module-level consts.-6. **Never edit `site/`** — it's generated. Sources are `site-src/` and the+7. **Never edit `site/`** — it's generated. Sources are `site-src/` and the`scripts/build-*.mjs` tooling. Same for `dist-single/`.-7. **No AI co-author trailers on commits** (no `Co-Authored-By: Claude` or+8. **No AI co-author trailers on commits** (no `Co-Authored-By: Claude` orsimilar), and no bot identities in git history.-8. **Releases are cut locally by the maintainer only.** Never touch signing+9. **Releases are cut locally by the maintainer only.** Never touch signingkeys (`~/.bento/release-key.json`), never attempt to release, publish, ordeploy from an agent session unless the maintainer explicitly asks.-9. **External PRs get provenance checks** before merge (`gh api users/<login>`)+10. **External PRs get provenance checks** before merge (`gh api users/<login>`)— AI-agent/bot contributions are not merged.-10. **Verify before claiming done**: typecheck, build, and exercise the change+11. **Verify before claiming done**: typecheck, build, and exercise the changein a browser when it's user-visible. Report failures honestly.## Commands@@ -68,6 +73,8 @@ npm run dev # dev server (see .claude/launch.json for ports)npm run build:single # → dist-single/Bento_Slides.bento.html (the product)node_modules/.bin/tsc -b # typechecknode ../scripts/test-sync.ts # CRDT convergence rig (SEEDS/STEPS/ACTORS env)+node ../scripts/test-preview.ts # first-page preview rig (encryption veto, output safety)+node ../scripts/shell-gate.mjs dist-single/Bento_Slides.bento.html # splice conformance```## Repo layoutdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 690dbb37..0e67d13f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -65,6 +65,24 @@ pre-1.0.legends, respects legend spacing and placement, and measures CJK legend textcorrectly so localized series names no longer overlap.+- **Your decks look like themselves in Finder, Files and the Bento Tray app.**+ Every Bento file used to thumbnail as the same dark box, because thumbnails+ are drawn without running a page's JavaScript and, until Bento boots, every+ deck genuinely is the same bytes plus the same boot splash. Saving now writes+ a still picture of page one into the file, which is what those previews draw+ instead — so a folder of decks is finally something you can read. It costs+ about 14 KB on a typical deck (under 2% of the file), never more than 64 KB: a+ page with a big photograph keeps its layout and its words and drops the+ photograph rather than carrying it twice. Nothing changes when you open a+ deck normally — the picture is written for software that can't run the file,+ and is never shown to a reader.++ **A password-protected deck gets no preview at all.** A readable picture of+ the title page sitting next to the encrypted document would give away exactly+ what the password is there to protect, so encrypted decks keep the plain dark+ thumbnail — and a deck that had a preview loses it the moment you set a+ password.+- **Updating a file now suggests that file's own name.** When an update askswhere to save, the dialog is pre-filled with the name of the deck you haveopen rather than one derived from its title — so a file calleddiff --git a/CLAUDE.md b/CLAUDE.mdindex 18bd2d94..240e898a 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -32,6 +32,32 @@ names provisional.- `src/save.ts` — the self-save trick: clone the document at boot (`capturePristine`),swap the `#bento-doc` data block, re-serialize. JSON is `<`-escaped (`\u003c`) so it cannever contain `</script>`. File System Access API first, download fallback.+- `src/preview.ts` + kernel `registerPreview` — **static first-page preview for+ file-manager thumbnails**. Thumbnailers (iOS Files, macOS QuickLook/Finder,+ Bento Tray) render HTML with JS OFF, so every deck used to thumbnail as the+ same boot splash. Every save now writes a still render of page one into the+ shell, parked in `<noscript data-bento-preview>` — rendered only when+ scripting is off, so with JS on the host node has ZERO element children (raw+ text) and a 0×0 box: no flash, no layout, nothing for print/present to+ exclude. Reuses `renderSlide` with `svgAsImage:true` (svg → one `<img>`,+ media → poster/icon still) + `hidePlaceholders`; `staticize()` strips active+ elements, runtime data-attrs and `on*`, and INLINES the few `.bento-*` rules+ from styles.css (the runtime CSS ships deflated and is never inflated in+ this mode). Fits an unknown viewport with+ `transform:scale(calc(min(100vw,<aspect>vh)/<w>px))` — `<svg><foreignObject>`+ was tried and is MANGLED by QuickLook's WebKit; verify with `qlmanage -t`,+ not Chrome alone (Chrome 150's `--blink-settings=scriptEnabled=false` kills+ `--screenshot`; use CDP `Emulation.setScriptExecutionDisabled`). GOTCHAS:+ never strip `id` from the render — svg gradients/markers paint through+ document-global `url(#…)`; the removal of an existing preview is+ UNCONDITIONAL (replace-never-append: `capturePristine` already holds the last+ save's copy, and a newly-encrypted deck must LOSE its preview).+ **Encrypted decks NEVER get a preview** (`previewAllowed` = no password flag+ AND body is not a `bento/enc` envelope) — a plaintext title slide beside the+ ciphertext is the leak the password exists to prevent. `PREVIEW_BUDGET`+ (64KB, model.ts) tiers the output: full → images dropped for tinted boxes →+ title card. Guards: `scripts/test-preview.ts` + shell-gate's+ preview-carrying-shell invariant. Full rationale in docs/DECISIONS.md.- `src/autosave.ts` (v0.9.8) — auto-save + local version history, IndexedDB(`bento-autosave`, two stores: `recovery` single-latest-per-docId, `versions`capped timeline). Editor debounces (2.5s) on `doc` events: writes a recoverydiff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 7bf4afb0..7e4e51a7 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -14,6 +14,74 @@ Decision. Why. Pointers.---+## 2026-07-26 — File-manager thumbnails: a `<noscript>` render of page one, written at save time++**Decided:** 2026-07-26. Kernel zone (`kernel/src/save.ts`), so it binds every+Bento app; the drawing is per-app (`slides/src/preview.ts`).++**The problem.** Thumbnailers render a document's HTML but do not run its+JavaScript, so every Bento file thumbnailed as the same dark box — correctly,+because before the runtime boots every deck *is* the same bytes plus the boot+splash. Confirmed on iOS, and confirmed that the iOS-side escape hatch does not+exist: an image attached via `UIDocument.fileAttributesToWrite` under+`NSURLThumbnailDictionaryKey` is accepted and then silently dropped for local+files (only `com.apple.lastuseddate` survives on disk). **The fix has to live+in the file.** So `serializeBody` now writes a static rendering of page one+into the shell on every save, and it fixes every platform at once with no+native extension anywhere.++**`<noscript>`, not "render it and let JS remove it".** The obvious design —+always paint the preview, have the runtime delete it at boot — flashes page one+in front of every reader on every open, for as long as the 600 KB payload takes+to inflate. `<noscript>` has exactly the semantics wanted: its contents are+rendered only when scripting is off, which is precisely the audience.+Empirically the DOM proves it, not just the spec — with scripting on the host+node has **zero element children** (its content is one raw text node) and a+bounding box of 0×0, so there is nothing to flash, nothing in layout, nothing+for print or present to exclude. The cost is that a thumbnailer which *does*+run scripts sees no preview — i.e. today's behaviour. A regression is not+possible, only an improvement.++**Scaling: `transform: scale(calc(min(100vw, <aspect>vh) / <width>px))`.**+CSS Values 4 length-over-length division yields the plain `<number>` `scale()`+needs, so the whole page scales as one unit and every inline px the renderer+emitted is left alone. **`<svg viewBox><foreignObject>` was tried first and does+not work**: Chrome renders it correctly, QuickLook's WebKit does not+(absolutely-positioned children disappeared, content scaled non-uniformly), and+QuickLook is the renderer this feature exists to serve. Verify changes here+against `qlmanage -t -s 640 -o <dir> <file>` — the real macOS thumbnailer, and+the only honest test. Chrome's `--blink-settings=scriptEnabled=false` suppresses+`--screenshot` entirely in Chrome 150; drive `Emulation.setScriptExecutionDisabled`+over CDP instead.++**Encrypted decks get NO preview — the load-bearing rule.** A plaintext+rendering of page one beside a `bento/enc` envelope hands over the title slide,+usually the most disclosive page, and does it invisibly. `previewAllowed()`+checks the in-memory password flag AND re-parses the body as an envelope,+because those fail independently. Removal of any existing preview is+UNCONDITIONAL and happens before that decision, so a deck that gains a password+loses its preview on the next save.++**Shell furniture, not format.** Nothing enters `#bento-doc`; no format field+is added; old files open unchanged; an app that registers no provider (spaces)+saves as before. The preview is replaced, never appended — `capturePristine()`+snapshots the file as loaded, so the clone already carries the previous save's+copy.++**Budget: 64 KB** (`PREVIEW_BUDGET`, slides/src/model.ts), ~10% of the shipped+shell. Measured: starter deck 25 KB (2.6% of the file); a page-one chart 11 KB;+a table 16 KB; a page with a 2.5 MB photograph degrades to 1.7 KB. Over budget,+page one re-renders with raster payloads replaced by tinted boxes; over it+again, a title card. Downscaling a hero photo instead would be+better and was NOT done: image decode is async and `serializeWith`/+`serializeFile` are synchronous (update.ts, `window.bento.serialize()`), so an+async provider is a kernel API change of its own.++Guards: `scripts/test-preview.ts` (encryption veto + the refusal to emit markup+carrying a script tag or `</noscript>`), and `scripts/shell-gate.mjs`, which+now also proves a preview-carrying file satisfies the splice contract and+asserts both rules are still wired into the save path.+## 2026-07-26 — A language pack lives in the FILE and nowhere elseNo browser-local install. A "keep it on this computer" option (localStorage)diff --git a/kernel/src/save.ts b/kernel/src/save.tsindex 5eb8df7c..07718a47 100644--- a/kernel/src/save.ts+++ b/kernel/src/save.ts@@ -90,7 +90,7 @@ export function readShellBlocks(type: string): Array<{ id: string; body: string;}/** Serialize a raw data-block body into an app shell. */-function serializeBody(shell: Document, body: string, title: string): string {+function serializeBody(shell: Document, body: string, doc: KernelDoc): string {const clone = shell.cloneNode(true) as Document// Runtime-injected DOM is not part of the shell (see TRANSIENT_SELECTOR).@@ -126,8 +126,10 @@ function serializeBody(shell: Document, body: string, title: string): string {// <-escape so the JSON can never contain "</script>" and break the file.block.textContent = '\n' + body.replace(/</g, '\\u003c') + '\n'+ writePreview(clone, body, doc)+const titleEl = clone.querySelector('title')- if (titleEl) titleEl.textContent = title + ' — ' + appConfig().appName+ if (titleEl) titleEl.textContent = doc.title + ' — ' + appConfig().appNameconst html = '<!DOCTYPE html>\n' + clone.documentElement.outerHTML// Belt-and-braces: an unescaped close tag anywhere in generated output would@@ -138,6 +140,130 @@ function serializeBody(shell: Document, body: string, title: string): string {return html}+// --- static first-page preview (file-manager thumbnails) ---------------------+//+// THE PROBLEM. A Bento file is one HTML document, and thumbnailers — iOS+// Files, macOS QuickLook/Finder, the Bento Tray app — render HTML with+// JavaScript DISABLED (verified: `qlmanage -t` renders <noscript> content).+// Until our runtime boots, every deck genuinely IS the same bytes plus the+// boot splash, so every deck thumbnailed as the same dark box.+//+// THE FIX. At save time we write a STATIC rendering of page one into the file+// and park it inside a `<noscript>`. That element's contents are rendered only+// when scripting is off, which is exactly the population we are addressing:+// a real reader never sees it — not for a frame — so there is no flash to+// suppress, no interaction with the splash's `.done`/`bsAuto` dismissal, and+// nothing for print or present to exclude. When a thumbnailer runs scripts+// after all, the preview is simply never rendered and we are back to today's+// behaviour: a regression is not possible, only an improvement.+//+// It is shell FURNITURE, not document data: nothing here enters `#bento-doc`,+// no format field is added, and a file saved by an older build (which has no+// preview) opens identically.+//+// The kernel knows nothing about how any app draws a page. It owns the+// placement, the replace-don't-append rule, the encryption veto and the+// output-safety check; the app hands back a ready-made element.++const PREVIEW_ATTR = 'data-bento-preview'++/** Builds the app's static first-page rendering. Return null for "no preview". */+export type PreviewProvider = (doc: KernelDoc) => HTMLElement | null++let previewProvider: PreviewProvider | null = null++/** Register the app's first-page renderer. Call once, at boot. Optional — an+ * app that registers nothing simply saves files without a preview. */+export function registerPreview(fn: PreviewProvider): void {+ previewProvider = fn+}++/**+ * May this saved file carry a plaintext preview of its first page?+ *+ * NO for an encrypted deck, and this is the single most important rule here.+ * The whole point of the `bento/enc` envelope is that the content is+ * unreadable on disk without the password; rendering page one in plaintext+ * beside the ciphertext would hand an attacker the title slide — usually the+ * most disclosive page in the deck — and would do it silently, because the+ * owner would never see the markup they were shipping. A missing thumbnail is+ * the correct, expected cost of encrypting a file.+ *+ * Two independent tests, because they fail independently: the in-memory+ * password flag covers the live session, and re-parsing the body covers any+ * path that hands us an already-encrypted block without the flag set.+ *+ * Pure and exported so `scripts/test-preview.ts` can exercise it directly —+ * the surrounding DOM work is not unit-testable in node, this decision is.+ */+export function previewAllowed(body: string, encrypted = isEncryptionActive()): boolean {+ return !encrypted && parseEnvelope(body) === null+}++// Built by concatenation for the usual reason (AGENTS.md #1): these literals+// must never appear in a Bento bundle, which is itself inline script.+// Note the close forms carry no ">": an HTML parser ends a script element at+// `</script` followed by whitespace, `/` or `>`, so `</script foo>` closes it+// just as surely as the tidy form does.+const SCRIPT_OPEN = '<scr' + 'ipt'+const SCRIPT_CLOSE_START = '</scr' + 'ipt'+const NOSCRIPT_CLOSE = '</nosc' + 'ript'++/**+ * Refuse any preview markup that could unbalance the file.+ *+ * The preview is generated from user content, so it is not shaped by us. Two+ * ways it could corrupt the document: a `<script>`/`</script>` would break the+ * open/close balance the frozen splice contract (and `scripts/shell-gate.mjs`)+ * depends on, and a `</noscript>` would end the host element early, spilling+ * the rest of the preview into the visible page. The app sanitizes its own+ * output; this is the kernel refusing to take its word for it. Dropping the+ * preview costs a thumbnail. Emitting it anyway could brick the file.+ *+ * Exported for `scripts/test-preview.ts`, like previewAllowed.+ */+export function previewIsSafe(html: string): boolean {+ const lower = html.toLowerCase()+ return !lower.includes(SCRIPT_OPEN) && !lower.includes(SCRIPT_CLOSE_START) && !lower.includes(NOSCRIPT_CLOSE)+}++function writePreview(clone: Document, body: string, doc: KernelDoc): void {+ // REPLACE, NEVER APPEND. `capturePristine()` snapshots the document as it+ // was loaded, so the shell we are cloning already carries the preview the+ // PREVIOUS save wrote; appending would stack a new one on every ⌘S until the+ // file was mostly stale previews. Removing unconditionally — before deciding+ // whether to write a new one — is also how a preview correctly DISAPPEARS+ // when a plaintext deck gains a password, or when an app stops providing+ // one. Both of those are silent leaks if the removal is conditional.+ for (const stale of Array.from(clone.querySelectorAll(`noscript[${PREVIEW_ATTR}]`))) stale.remove()++ if (!previewProvider || !previewAllowed(body)) return++ let el: HTMLElement | null = null+ try {+ el = previewProvider(doc)+ } catch (err) {+ // A preview is a nicety; a failed save is not. Never let rendering page+ // one take the file down with it.+ console.warn('bento: first-page preview failed, saving without one', err)+ return+ }+ if (!el) return++ const host = clone.createElement('noscript')+ host.setAttribute(PREVIEW_ATTR, '1')+ host.appendChild(clone.importNode(el, true))+ if (!previewIsSafe(host.innerHTML)) {+ console.warn('bento: first-page preview rejected as unsafe, saving without one')+ return+ }+ // Straight after the splash it replaces, so a thumbnailer reaches it before+ // the ~550KB of compressed payload at the end of the body.+ const splash = clone.getElementById('bento-splash')+ if (splash?.parentNode) splash.parentNode.insertBefore(host, splash.nextSibling)+ else (clone.body ?? clone.documentElement).appendChild(host)+}+/*** Serialize `doc` into an arbitrary app shell (a parsed Bento HTML document).* Used with the boot-time pristine copy on every save, and by the self-update@@ -145,7 +271,7 @@ function serializeBody(shell: Document, body: string, title: string): string {* PLAIN output — encryption-aware callers use serializeDocInto/serializeAuto.*/export function serializeWith(shell: Document, doc: KernelDoc): string {- return serializeBody(shell, JSON.stringify(doc), doc.title)+ return serializeBody(shell, JSON.stringify(doc), doc)}/** The full .bento.html file content with `doc` embedded (plain). */@@ -252,7 +378,7 @@ export async function serializeDocInto(shell: Document, doc: KernelDoc): Promiseconst body = encPassword? await encryptBody(JSON.stringify(doc), encPassword): JSON.stringify(doc)- return serializeBody(shell, body, doc.title)+ return serializeBody(shell, body, doc)}/** Encryption-aware serializeFile. */diff --git a/scripts/shell-gate.mjs b/scripts/shell-gate.mjsindex 72f806f8..8b6e79c1 100644--- a/scripts/shell-gate.mjs+++ b/scripts/shell-gate.mjs@@ -349,17 +349,101 @@ function checkEscapeIsImplemented() {)}+// --- invariant 5: a preview-carrying shell ---------------------------------+//+// The THIRD class of plaintext content a saved file carries: the static+// first-page preview `kernel/src/save.ts` writes into a+// `<noscript data-bento-preview>` so file managers can thumbnail the deck+// (docs/DECISIONS.md). Like a language pack it is not shaped by us — it is+// rendered from whatever the author typed on page one — but unlike a pack it+// is HTML, not JSON in a script block, so the `<` escape does not and+// cannot apply to it. Its safety rests on the kernel REFUSING to emit markup+// containing a script tag or a `</noscript>`, which is what this checks.++const NOSCRIPT_CLOSE = '</nosc' + 'ript>'++/** A preview whose content came from a hostile deck: entity-escaped exactly as+ * a DOM serializer escapes text, plus quotes, RTL, emoji and separators. */+const ADVERSARIAL_PREVIEW =+ `<noscript data-bento-preview="1"><div style="position:fixed;left:0;top:0;background:#0D1B2E">` ++ `<div></script> <script>alert(1)</script> ` ++ `<script type="application/bento+json" id="bento-doc">{"hijacked":true}</script>` ++ `</noscript> <!-- --> <![CDATA[ & " ' \` \\ ` ++ `مرحبا שלום 🎌 a b c</div>` ++ `</div>${NOSCRIPT_CLOSE}`++/** …and the same content with the escapes NOT applied — what the kernel's+ * `previewIsSafe` refusal exists to keep out of a file. */+const UNSAFE_PREVIEW =+ `<noscript data-bento-preview="1"><div>${SCRIPT_CLOSE} ` ++ `${DOC_BLOCK_OPEN}{"hijacked":true}${SCRIPT_CLOSE}</div>${NOSCRIPT_CLOSE}`++/** Insert a preview where `writePreview` does — straight after the splash. */+const withPreview = (html, preview) =>+ html.includes('<div id="bento-splash"')+ ? html.replace('<div id="app">', () => `${preview}\n <div id="app">`)+ : html.replace('</body>', () => `${preview}\n</body>`)++function checkPreviewCarryingShell(shell) {+ const realDoc = shell.match(DOC_BLOCK_RE)[0]+ const html = withPreview(shell, ADVERSARIAL_PREVIEW)++ checkSpliceContract(html, 'preview-carrying shell')+ checkDataBlocks(html, 'preview-carrying shell')+ if (html.match(DOC_BLOCK_RE)[0] !== realDoc) fail('#bento-doc extraction hijacked by a preview')++ // …and the preview survives the frozen text splice untouched: an updater+ // rewriting the document must not disturb the thumbnail riding beside it.+ const spliced = checkSpliceContract(html, 'preview-carrying shell + splice')+ if (!spliced.includes(ADVERSARIAL_PREVIEW)) fail('preview did not survive the doc splice')+ checkDataBlocks(spliced, 'preview-carrying shell + splice')++ // NEGATIVE CONTROL — the unescaped form must be caught. If it is not, the+ // check above proves nothing about why the escaped form is safe.+ let caught = false+ try {+ checkSpliceContract(withPreview(shell, UNSAFE_PREVIEW), 'unsafe preview control')+ } catch {+ caught = true+ }+ if (!caught) fail('negative control passed — the preview checks have no teeth')+}++/**+ * Source assertions for the preview, for the same reason as the escape one+ * above: a fresh shell carries no preview, so nothing in the built artifact+ * could notice these rules being dropped at save time.+ *+ * Two rules, both silent failures if they go: the ENCRYPTION VETO (a+ * `bento/enc` deck must never ship a plaintext rendering of page one beside+ * its ciphertext) and the OUTPUT REFUSAL (`previewIsSafe`, which is the only+ * thing standing between author content and an unbalanced script tag).+ */+function checkPreviewRulesAreImplemented() {+ const src = join(repoRoot, 'kernel/src/save.ts')+ if (!existsSync(src)) return // an app repo vendored without the kernel+ const text = readFileSync(src, 'utf8')+ if (!/previewAllowed\s*\(\s*body\s*\)/.test(text))+ fail('kernel/src/save.ts no longer gates the first-page preview on previewAllowed(body) — an encrypted deck could ship a plaintext page one')+ if (!/parseEnvelope\(body\) === null/.test(text) || !/!encrypted/.test(text))+ fail('kernel/src/save.ts previewAllowed no longer checks BOTH the password flag and the body envelope')+ if (!/previewIsSafe\(host\.innerHTML\)/.test(text))+ fail('kernel/src/save.ts no longer refuses unsafe first-page preview markup')+}+/** Throws with a GATE: message on the first violated invariant. */export function gateShell(shellPath) {const shell = readFileSync(shellPath, 'utf8')checkSpliceContract(shell, 'shell')checkDataBlocks(shell, 'shell')checkPackCarryingShell(shell)+ checkPreviewCarryingShell(shell)const compressed = checkRuntimeStaysCompressed(shell, 'shell')if (compressed) checkTransientMarking(shell)checkEscapeIsImplemented()+ checkPreviewRulesAreImplemented()console.log(- 'conformance gate: old-updater splice contract OK (incl. pack-carrying shell)' ++ 'conformance gate: old-updater splice contract OK (incl. pack- and preview-carrying shells)' +(compressed ? '; runtime ships deflated only' : ''),)}diff --git a/scripts/test-preview.ts b/scripts/test-preview.tsnew file mode 100644index 00000000..9ab765b0--- /dev/null+++ b/scripts/test-preview.ts@@ -0,0 +1,114 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// First-page preview rig.+//+// node scripts/test-preview.ts (Node ≥ 23.6 strips types natively)+//+// WHAT THIS PROVES. Every save writes a static rendering of page one into the+// shell so file managers can thumbnail the deck (kernel/src/save.ts, and+// slides/src/preview.ts for the drawing). Two of the decisions in that flow+// can fail SILENTLY — nobody looks at markup they cannot see — and both are+// unrecoverable once files are on disk:+//+// 1. THE ENCRYPTION VETO. A `bento/enc` deck must never carry a plaintext+// rendering of page one. Getting this wrong publishes the title slide of+// every password-protected deck ever saved, and the owner would have no+// way to notice.+// 2. THE OUTPUT REFUSAL. The preview is generated from author content. A+// script tag or a `</noscript>` reaching the file unbalances it and+// breaks the frozen splice contract every shipped updater relies on.+//+// The rest of the feature — laying the page out, fitting it to a viewport,+// staying inside the byte budget — needs a DOM and is verified in a browser+// and against the real macOS thumbnailer (`qlmanage -t`). These two are pure+// decisions, so they get pinned here where a regression costs one CI run+// instead of one release.+//+// The shell-level counterpart is `scripts/shell-gate.mjs`, which proves a+// preview-carrying FILE still satisfies the splice contract and asserts that+// both rules below are still wired into the save path at all.++import { previewAllowed, previewIsSafe, setEncryptionPassword } from '../kernel/src/save.ts'++let failures = 0+let checks = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (!cond) {+ failures+++ console.error(` ✗ ${msg}`)+ } else {+ console.log(` ✓ ${msg}`)+ }+}++// Never write these literals (AGENTS.md #1): this file is not bundled, but the+// fixtures below need them as data, and the habit is the rule.+const SCRIPT_CLOSE = '</scr' + 'ipt>'+const SCRIPT_OPEN = '<scr' + 'ipt>'+const NOSCRIPT_CLOSE = '</nosc' + 'ript>'++const PLAIN = JSON.stringify({ format: 'bento/slides', docId: 'x', title: 'Q3 board' })+const ENVELOPE = JSON.stringify({+ format: 'bento/enc', v: 1, it: 300000, salt: 'c2FsdA==', iv: 'aXY=', data: 'ZGF0YQ==',+})++// --- 1. the encryption veto -------------------------------------------------++console.log('\nencryption veto')++setEncryptionPassword(null)+ok(previewAllowed(PLAIN) === true, 'a plain deck with no password may carry a preview')++// The password flag alone must be enough. This is the live-session case: the+// user typed a password this session, and the tooling path (serializeFile) is+// still handing serializeBody a PLAINTEXT body.+ok(previewAllowed(PLAIN, true) === false, 'password active vetoes the preview even for a plaintext body')++// The body alone must be enough too. This is the path where an already-+// encrypted block is re-serialized without the in-memory flag ever being set.+ok(previewAllowed(ENVELOPE) === false, 'a bento/enc body vetoes the preview even with no password flag')+ok(previewAllowed(ENVELOPE, true) === false, 'both signals together still veto')++// …and through the real module state, not just the parameter, because that is+// how the save path actually calls it.+setEncryptionPassword('hunter2')+ok(previewAllowed(PLAIN) === false, 'setEncryptionPassword() vetoes the preview on the real save path')+setEncryptionPassword(null)+ok(previewAllowed(PLAIN) === true, 'clearing the password restores the preview')++// A body that merely looks envelope-ish must not accidentally suppress a+// preview — the check has to be the real parse, not a substring sniff.+ok(previewAllowed(JSON.stringify({ title: 'about bento/enc envelopes' })) === true,+ 'a deck that merely mentions bento/enc still previews')+ok(previewAllowed('not json at all') === true, 'an unparseable body is not mistaken for an envelope')++// --- 2. the output refusal --------------------------------------------------++console.log('\noutput refusal')++const SAFE = '<div style="position:fixed;inset:0"><div>Hello <world> & "quotes"</div></div>'+ok(previewIsSafe(SAFE) === true, 'ordinary escaped preview markup is accepted')+ok(previewIsSafe('<div>مرحبا שלום 🎌 a b c</div>') === true, 'RTL, emoji and JS line separators are fine')++ok(previewIsSafe(`<div>${SCRIPT_CLOSE}</div>`) === false, 'a bare script close is refused')+ok(previewIsSafe(`<div>${SCRIPT_OPEN}alert(1)${SCRIPT_CLOSE}</div>`) === false, 'a script element is refused')+ok(previewIsSafe(`<div>${NOSCRIPT_CLOSE}<h1>escaped</h1></div>`) === false,+ 'a noscript close is refused — it would end the host and spill into the page')++// Case and attribute variants: an HTML parser ends a script element at+// `</script` regardless of case or what follows, so the check must too.+ok(previewIsSafe('<div>' + '</SCR' + 'IPT>' + '</div>') === false, 'an upper-case script close is refused')+ok(previewIsSafe('<div>' + '</scr' + 'ipt foo>' + '</div>') === false, 'a script close with junk before ">" is refused')+ok(previewIsSafe('<div>' + '<SCR' + 'IPT src=x>' + '</div>') === false, 'an upper-case script open is refused')+ok(previewIsSafe('<div>' + '</NOSC' + 'RIPT>' + '</div>') === false, 'an upper-case noscript close is refused')++// The forged-block case the pack rig also covers: a preview must not be able+// to counterfeit an opening #bento-doc tag above the real one, because an old+// updater splices into the FIRST match.+ok(previewIsSafe('<div>' + '<scr' + 'ipt type="application/bento+json" id="bento-doc">{}</div>') === false,+ 'a forged #bento-doc opening tag is refused')++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/slides/src/main.ts b/slides/src/main.tsindex 783b4028..ce64e115 100644--- a/slides/src/main.ts+++ b/slides/src/main.ts@@ -9,7 +9,9 @@ import { configureApp, appConfig } from '../../kernel/src/app.ts'import {capturePristine, readEmbeddedDoc, serializeFile, serializeAuto, downloadFile,suggestedFileName, parseEnvelope, decryptEnvelope, setEncryptionPassword,+ registerPreview,} from './save'+import { buildSlidePreview } from './preview'import { APP_VERSION, checkForUpdates, buildUpdatedFile, applyUpdate } from './update'import { i18nApi, t, applyDirection } from './i18n'import { parseDoc, type BentoDoc } from './model'@@ -29,6 +31,12 @@ configureApp({manifestUrl: 'https://bento.page/releases/slides/manifest.json',})+// Every save writes a static rendering of page one into the shell, so file+// managers thumbnail the deck instead of the boot splash (src/preview.ts).+// Registered before capturePristine only for tidiness — nothing serializes+// this early — but it must be registered before the first save.+registerPreview((doc) => buildSlidePreview(doc as BentoDoc))+capturePristine()// Chrome direction follows the VIEWER's language (Arabic/Hebrew/… get an RTLdiff --git a/slides/src/model.ts b/slides/src/model.tsindex acb2f104..81e47fcc 100644--- a/slides/src/model.ts+++ b/slides/src/model.ts@@ -756,6 +756,24 @@ export function internAsset(doc: BentoDoc, src: string): string {* editor warns — a big embed makes the .bento.html slow to open and save. */export const MEDIA_EMBED_BUDGET = 8 * 1024 * 1024 // 8 MB+/**+ * Hard ceiling for the static first-page preview every save writes into the+ * shell (src/preview.ts), in bytes of serialized markup.+ *+ * Unlike MEDIA_EMBED_BUDGET this is not a warning the author can wave through+ * — there is no author in the loop, it is spent silently on every ⌘S, and it+ * is spent on a THUMBNAIL. A text page costs 2–5 KB. The thing that can blow+ * up is a full-bleed photo, whose data URI would be duplicated: once in the+ * document, once in the preview.+ *+ * 64 KB is ~10% of the shipped shell (~640 KB compressed): invisible against a+ * file that size, and enough for a real page plus a logo or an icon-sized+ * image. Measured: the starter deck's page one costs 25 KB (2.6% of it). Over+ * it, preview.ts degrades — first dropping raster payloads, then falling back+ * to a title card — rather than growing the file.+ */+export const PREVIEW_BUDGET = 64 * 1024 // 64 KB+export function defaultMedia(kind: 'video' | 'audio',src: string,diff --git a/slides/src/preview.ts b/slides/src/preview.tsnew file mode 100644index 00000000..d9f2b701--- /dev/null+++ b/slides/src/preview.ts@@ -0,0 +1,212 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// The static first-page preview: what a Bento deck looks like to something+// that renders its HTML but never runs its JavaScript.+//+// WHY THIS EXISTS. Thumbnailers — iOS Files, macOS QuickLook/Finder, the Bento+// Tray app — render HTML with scripting off. Until our runtime boots, every+// deck is the same bytes plus the same boot splash, so every deck thumbnailed+// as the same dark box. The kernel (kernel/src/save.ts) parks what we build+// here inside a `<noscript>` on every save, which is rendered by exactly that+// population and by nobody else. See that file for the placement rules, the+// encryption veto and the output-safety check.+//+// WHY IT REUSES render.ts. A second renderer would drift from the first, and+// a preview that disagrees with the deck is worse than no preview. `svgAsImage`+// (the mode sidebar thumbnails already use) does most of the static-ifying for+// free: svg elements collapse to one <img>, and media renders as a poster or+// an icon chip instead of a live <video>/<audio>. What is left is stripping the+// runtime's DOM hooks, inlining the handful of rules the (absent) runtime+// stylesheet would have supplied, and fitting 1280×720 into an unknown+// viewport without JavaScript.+//+// HOW IT SCALES. `transform: scale(calc(min(100vw, <aspect>vh) / <width>px))`.+// CSS Values 4 length-over-length division yields the plain <number> that+// scale() needs, so the whole page scales as ONE unit and every inline px the+// renderer emitted stays untouched. Measured in the real macOS thumbnailer+// (`qlmanage -t`) and pixel-exact there.+//+// WHAT DID NOT WORK, so nobody re-tries it: `<svg viewBox><foreignObject>`,+// the textbook way to fit HTML into a box. Chrome renders it correctly, and+// QuickLook's WebKit does not — absolutely-positioned children vanished and+// the content scaled non-uniformly. It is not usable for the one renderer this+// feature exists to serve.++import { renderSlide } from './render'+import { PREVIEW_BUDGET, type BentoDoc, type Slide } from './model'++/** Elements that must never reach a static preview (active or external). */+const BANNED = 'script,style,noscript,iframe,object,embed,link,video,audio,canvas,form,input,button'++/**+ * Runtime-only attributes: selection ids, morph keys, editing hooks. Dead+ * weight in a preview, and every one of them is paid for in every saved file.+ *+ * `id` is deliberately NOT on this list, however useless it looks. svg paints+ * gradients, markers and clip paths through document-global `url(#…)`+ * references, so stripping ids silently voids every fill that uses one — the+ * starter deck's tiles rendered as nothing at all until this was caught.+ * render.ts already mints those ids from a counter, so they are unique.+ */+const DROP_ATTRS = [+ 'data-el-id', 'data-flip-id', 'data-slide-id', 'data-link', 'data-group',+ 'data-show-on-hover', 'data-chart', 'data-table', 'data-autoplay',+ 'data-r', 'data-c', 'data-sym', 'contenteditable', 'draggable', 'tabindex',+]++/**+ * Generic families appended to every inline font-family.+ *+ * `doc.fonts[]` are injected as @font-face at boot from the asset table — which+ * is to say, by JavaScript, which is not running. Embedding the font data here+ * instead would cost hundreds of KB for a thumbnail. So the preview renders in+ * a system face; a fallback chain makes that a deliberate substitution rather+ * than whatever the UA picks for an unresolvable family name (usually Times).+ */+const FONT_FALLBACK = `-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif`++/** Inline the rules `.bento-*` classes get from styles.css, which is compressed+ * into a payload the preview's audience never decompresses. */+function inlineRuntimeCss(root: HTMLElement) {+ prepend(root, 'position:relative;overflow:hidden')+ for (const el of Array.from(root.querySelectorAll<HTMLElement>('.bento-el'))) {+ prepend(el, 'position:absolute')+ }+ for (const el of Array.from(root.querySelectorAll<HTMLElement>('.bento-el-text .bento-text-inner'))) {+ prepend(el, 'overflow-wrap:break-word')+ }+ for (const el of Array.from(root.querySelectorAll<HTMLElement>('.bento-el-table'))) {+ prepend(el, 'overflow:visible')+ }+ for (const el of Array.from(root.querySelectorAll<HTMLElement>('.bento-cell-inner'))) {+ prepend(el, 'min-height:1em')+ }+ for (const el of Array.from(root.querySelectorAll<HTMLElement>('code'))) {+ prepend(el, 'font-family:ui-monospace,Menlo,Consolas,monospace;font-size:0.9em;' ++ 'background:rgb(127 127 127 / 0.16);padding:0 0.28em;border-radius:3px')+ }+}++/** Put `css` in front of the element's existing inline style (which wins). */+function prepend(el: HTMLElement, css: string) {+ const own = el.getAttribute('style') ?? ''+ el.setAttribute('style', own ? `${css};${own}` : css)+}++/**+ * Turn the live render into inert markup: drop anything active, drop the+ * runtime's hooks, and (when `keepImages` is false) drop raster payloads whose+ * data URIs would otherwise be carried twice in the file.+ */+function staticize(root: HTMLElement, doc: BentoDoc, keepImages: boolean) {+ for (const el of Array.from(root.querySelectorAll(BANNED))) el.remove()++ for (const el of Array.from(root.querySelectorAll<HTMLElement>('*'))) {+ for (const attr of Array.from(el.attributes)) {+ // on* handlers can only arrive via sanitizeHtml's allowlist (which+ // strips every attribute) or our own code, so this is defence in depth.+ if (attr.name.startsWith('on') || DROP_ATTRS.includes(attr.name)) el.removeAttribute(attr.name)+ }+ const family = el.style?.fontFamily+ if (family && !family.includes(FONT_FALLBACK)) el.style.fontFamily = `${family},${FONT_FALLBACK}`+ }++ if (!keepImages) {+ for (const img of Array.from(root.querySelectorAll<HTMLImageElement>('img'))) {+ // Keep the BOX — an empty rectangle where the photo was reads as+ // composition; removing it collapses the page into floating text.+ const tint = document.createElement('div')+ tint.setAttribute('style',+ `width:100%;height:100%;border-radius:${img.style.borderRadius || '0'};` ++ `background:linear-gradient(135deg,${doc.theme.accent}2E,${doc.theme.accent}12)`)+ img.replaceWith(tint)+ }+ }++ inlineRuntimeCss(root)+}++/** A background string safe to repeat behind the page: a flat colour repeats+ * invisibly, a gradient or an embedded image does not (and a data: URI would+ * be paid for twice). */+const flatBackground = (css: string) => (/url\(|gradient|data:/i.test(css) ? null : css)++/** Wrap a rendered page in the fixed, viewport-fitting overlay. */+function overlay(page: HTMLElement, doc: BentoDoc, slide: Slide): HTMLElement {+ const { width: w, height: h } = doc.size+ const surround = flatBackground(slide.background) ?? flatBackground(doc.theme.background) ?? '#0D1B2E'++ const box = document.createElement('div')+ // z-index above the splash (9999) and the loader's failure card (99999).+ box.setAttribute('style',+ `position:fixed;left:0;top:0;width:100%;height:100%;z-index:2147483000;` ++ `overflow:hidden;background:${surround}`)++ const fit = document.createElement('div')+ // Two `transform` declarations on purpose. calc() length-over-length is CSS+ // Values 4; a renderer that rejects it drops the second declaration and+ // keeps the first, showing the page centred at 1:1 (cropped, but the deck)+ // instead of nothing at all.+ const aspect = ((w / h) * 100).toFixed(4)+ fit.setAttribute('style',+ `position:absolute;left:50%;top:50%;width:${w}px;height:${h}px;` ++ `transform:translate(-50%,-50%);` ++ `transform:translate(-50%,-50%) scale(calc(min(100vw, ${aspect}vh) / ${w}px))`)++ fit.appendChild(page)+ box.appendChild(fit)+ return box+}++/** Last resort: the deck's identity in the deck's colours, a few hundred bytes. */+function titleCard(doc: BentoDoc): HTMLElement {+ const page = document.createElement('div')+ const { width: w, height: h } = doc.size+ page.setAttribute('style',+ `position:relative;overflow:hidden;width:${w}px;height:${h}px;` ++ `background:${flatBackground(doc.theme.background) ?? '#0D1B2E'};` ++ `display:flex;flex-direction:column;justify-content:center;padding:0 ${Math.round(w * 0.075)}px;` ++ `box-sizing:border-box;font-family:${FONT_FALLBACK}`)++ const rule = document.createElement('div')+ rule.setAttribute('style',+ `width:${Math.round(w * 0.07)}px;height:${Math.round(h * 0.011)}px;background:${doc.theme.accent};margin-bottom:${Math.round(h * 0.05)}px`)++ const title = document.createElement('div')+ title.setAttribute('style',+ `font-size:${Math.round(h * 0.1)}px;font-weight:800;line-height:1.1;color:${doc.theme.color};overflow-wrap:break-word`)+ title.textContent = doc.title++ page.append(rule, title)+ return page+}++const byteLength = (el: HTMLElement) => new TextEncoder().encode(el.outerHTML).length++/**+ * Build the static preview of the deck's first page, or null when there is+ * nothing to show. Registered with the kernel from main.ts.+ *+ * Three tiers, cheapest acceptable one wins, all bounded by PREVIEW_BUDGET:+ * 1. the page as it renders, images and all;+ * 2. the same page with raster payloads replaced by tinted boxes — layout+ * and text survive, the megabytes do not;+ * 3. a title card in the deck's own colours.+ * Tier 3 cannot exceed the budget, so this always terminates with something.+ */+export function buildSlidePreview(doc: BentoDoc): HTMLElement | null {+ // The first page a reader sees: interactive states are hidden variants and+ // never open a deck.+ const slide = doc.slides.find((s) => !s.stateOf) ?? doc.slides[0]+ if (!slide) return null++ for (const keepImages of [true, false]) {+ const page = renderSlide(slide, doc, { svgAsImage: true, hidePlaceholders: true })+ staticize(page, doc, keepImages)+ if (!keepImages) page.style.background = flatBackground(slide.background) ?? doc.theme.background+ const built = overlay(page, doc, slide)+ if (byteLength(built) <= PREVIEW_BUDGET) return built+ }+ return overlay(titleCard(doc), doc, slide)+}