Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
tray/ios: document search, verified releases, and the bento/home identity (#315)
nyblnetb843d0cbfcc1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex ea51a860..cea98a76 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -322,6 +322,40 @@ jobs:# Source-shape checks; the Swift half self-skips without a toolchain.run: node scripts/test-tray-bridge.ts+ - 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>,+ # so each rounded corner becomes opaque path data nobody would diff), and+ # the iOS asset catalog — the mark plus the four brand colours the app's+ # chrome reads by name. A hex value retyped into Swift is a value that can+ # disagree with the logo while looking almost right, which is the kind of+ # wrong nothing notices. This fails if any of it drifts.+ run: node tray/assets/make-icons.mjs --check++ - name: tray/ios index rig+ # The iOS text extractor is a PORT of tray/webext's, and the two are held+ # together by nothing but agreement — so this diffs them, driving the+ # real library.js against the compiled Swift over generated edge cases+ # and every document in the tree. A divergence means a deck is findable+ # by a phrase on one host and not the other, which nothing else notices.+ # This one really runs HERE: BentoIndex.swift is Foundation-only, and the+ # runner has Swift, so the diff happens on every push rather than only on+ # a Mac. That is the payoff for keeping UIKit out of that file.+ run: node scripts/test-tray-index.mjs++ - name: tray/ios release verifier rig+ # Starter decks are not bundled; a new document is FETCHED from the+ # signed release channel and written to disk as an executable page. The+ # signature and hash checks are what make that acceptable, so this proves+ # the verifier REFUSES — tampered payload, tampered signature, a real+ # signature over different bytes, no signature at all. Watching it accept+ # the live manifest proves nothing: `return true` passes that test.+ # Unlike the index rig above this CANNOT run here — CryptoKit is+ # Apple-only — so it probes for that module (not for swiftc, which the+ # runner has) and skips loudly. A Mac must run it before Releases.swift+ # changes.+ run: node scripts/test-tray-releases.mjs+- name: WebExtension package rig# Validates the store package without writing it: every file the# manifest names exists, every icon is the size it claims, no unexpecteddiff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 909b97f5..faafc820 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -8,50 +8,71 @@ Reversing a decision = a new entry that supersedes the old one, not an edit.Format:```-## 2026-08-19 — Page width has TWO settings, because it answers two questions--The per-page control shipped in #325 answered "this page needs the room". It-did not answer "I have a wide screen", and it made somebody say so on every-page in a space one page at a time. Reported as still-narrow after it shipped,-and MEASURED at a 2560px viewport: a 720px column using 31% of the area with-1,591px empty beside it.--Two settings now, and the split is the whole point:-- · `Page.width` — DOCUMENT data. What this page needs; travels with the file.- · `bento-sp-width` — VIEWER data, in localStorage. What this reader's SCREEN- is; never written to the file.--Precedence: the page, then the reader, then the board default, then the-measure. A reader who sets it once gets it on every page that has not asked for-something specific, and the document is byte-unchanged — verified: four pages-at 1500px with no `width` key stored on any of them and no `"width"` anywhere-in the serialized doc.--That split is the rule locale and reduced motion already follow (PLATFORM §8):-two people opening one space on a laptop and a 27-inch monitor should each get-their own answer, and neither should write theirs into the file the other-opens.--THE BUILT-IN DEFAULT ALSO GROWS, `min(max(measure, 42vw), measure × 1.25)` —-720px on a laptop, 900px at 2560px. Capped deliberately: 720px is already ~88-characters at 16px, and past ~95 a line gets harder to read rather than easier,-so the cap is a typographic limit and not a shortage of nerve. Filling a 2560px-screen with one column of prose is not the goal; not showing a ribbon in the-middle of it is.--PRINT DOES NOT INHERIT THE READER WIDTH. Paper has a fixed width, and the size-of the monitor somebody happens to be sitting at is not a fact about the page-they are printing. Pinned in the rig.------## YYYY-MM-DD — TitleDecision. Why. Pointers.```---+## 2026-08-25 — The tray hosts are called `bento/home`++**Decision.** All three hosts are named **`bento/home`** — lowercase, with the+slash, set like `bento/slides`. **Never "Bento Home"**, in any casing, in any+surface a user reads. This supersedes the naming half of the 2026-07-26 entry+below, which called the iOS app `bento/tray`.++**Why `home`.** It is not a component that needs distinguishing from the brand —+it is where documents live and where new ones start, on every host. The suite+convention is `bento/<what you get>`, and what you get is your documents.++**Why the qualifier route was abandoned, so it is not tried again.** The+alternative was a distinguishing second word, and every candidate died to a live+collision: **box** → BentoBox (and "bento box" is the literal object), **desk** →+Addit's furniture line, **works** → Apple's iWork, **keep** → Google Keep. That+is four independent attempts failing the same way, which is the signal that the+premise was wrong rather than the words: the front door does not need a+qualifier, because it is not one thing among several.++**Scope: the PRODUCT is renamed, not the tree.** Directories stay `tray/ios`,+`tray/android`, `tray/webext`, and `tray/bridge.js` keeps its name. Renaming+paths would churn every import, every doc link and every open branch for no+reader's benefit — the name people see is not the name the repo files it under.++**What must NOT change, on any host:**++- **The bundle identifier.** `page.bento.tray` on iOS, and its Android+ counterpart. To the OS and the store it IS the app: changing it does not rename+ the app, it creates a different one that cannot update the installed copy.+- **`PRODUCT_NAME` / `CFBundleName`** (iOS). They name the executable and the+ bundle, not the label. `CFBundleDisplayName` is the label, and it is the only+ key the rename touches.+- **The App Store listing name.** Per 2026-07-24, `/` is a mark and never a+ stored name, and store names are stored. The listing keeps a slashless form;+ the on-device label does not. Those are separate fields — see the note on the+ 2026-07-26 entry for why that pair is not a contradiction.++`bento/home` is 10 characters, which fits the iOS home-screen label without+truncation. (`bento/tray` was 10 too, so this was not at risk, but it is the+constraint any future rename has to clear.)++**Where it landed.** `tray/webext` first, in PR #360 / `50d1c40` — read that as+the precedent for which strings change. `tray/ios` in PR #315: the display name,+the search screen's lockup, and the mark's `aria-label`. `tray/android` follows.++Screen readers get the spoken form, not the mark: `aria-label` and+`accessibilityLabel` say "bento home", because a slash is read out as+punctuation. Visible text keeps the slash, and only the search screen can colour+it — the home-screen label, the browser title and the Browse folder are system+chrome drawn as plain text.++**One practical note for the listing, since it is cheap to record and expensive+to rediscover:** App Store screenshots need documents that have been **saved at+least once**. A preview is only written on save, so an unsaved document+photographs as a "Not saved yet" placeholder — a whole screenshot set can be shot+and only later found to be showing empty cards.++---+## 2026-08-23 — The web demo gates on RETURN, not on saveSomeone works at `https://bento.page/slides/`, saves, comes back later and gets@@ -453,6 +474,44 @@ being zero-`<` by construction against hostile payloads.---+## 2026-08-19 — Page width has TWO settings, because it answers two questions++The per-page control shipped in #325 answered "this page needs the room". It+did not answer "I have a wide screen", and it made somebody say so on every+page in a space one page at a time. Reported as still-narrow after it shipped,+and MEASURED at a 2560px viewport: a 720px column using 31% of the area with+1,591px empty beside it.++Two settings now, and the split is the whole point:++ · `Page.width` — DOCUMENT data. What this page needs; travels with the file.+ · `bento-sp-width` — VIEWER data, in localStorage. What this reader's SCREEN+ is; never written to the file.++Precedence: the page, then the reader, then the board default, then the+measure. A reader who sets it once gets it on every page that has not asked for+something specific, and the document is byte-unchanged — verified: four pages+at 1500px with no `width` key stored on any of them and no `"width"` anywhere+in the serialized doc.++That split is the rule locale and reduced motion already follow (PLATFORM §8):+two people opening one space on a laptop and a 27-inch monitor should each get+their own answer, and neither should write theirs into the file the other+opens.++THE BUILT-IN DEFAULT ALSO GROWS, `min(max(measure, 42vw), measure × 1.25)` —+720px on a laptop, 900px at 2560px. Capped deliberately: 720px is already ~88+characters at 16px, and past ~95 a line gets harder to read rather than easier,+so the cap is a typographic limit and not a shortage of nerve. Filling a 2560px+screen with one column of prose is not the goal; not showing a ribbon in the+middle of it is.++PRINT DOES NOT INHERIT THE READER WIDTH. Paper has a fixed width, and the size+of the monitor somebody happens to be sitting at is not a fact about the page+they are printing. Pinned in the rig.++---+## 2026-08-19 — How wide a page is belongs to the PAGE, not the theme`theme.measure` is one number for the whole document — "text column width in px@@ -750,6 +809,27 @@ consistent.today; the app list is aspirational on every host. All three say"<App> has not been released yet" rather than surfacing an HTTP status.+**Proving the verifier REFUSES is a separate obligation from writing it.** A+verifier only ever watched saying yes is indistinguishable from `return true`,+so each host's rig runs the real captured manifest plus deliberately bad ones.+Three cases are worth naming because each catches something the others cannot:++- **A valid signature under the WRONG key** is not the same test as a bent one.+ Bending bytes proves a non-validating signature is rejected, which almost any+ bug-free crypto call manages; a signature that validates PERFECTLY under an+ untrusted key is what catches a verifier that imported the wrong key, or that+ would trust a key travelling inside the manifest. No test seam is needed —+ sign the real payload with a throwaway key and hand it to the shipped+ verifier. (The NEGATIVE cases must never go through an injected key, or a+ verifier that trusts one passes its own tampering tests.)+- **An unsigned manifest is refused as a CATEGORY**, not as a parse error. A+ flat `{url: …}` is exactly the shape the old broken reader wanted, so+ "malformed" invites someone to add a lenient fallback for it later as a+ compatibility gap. It is not a gap.+- **An absent `app` field must not read as a match** — `undefined !== 'bento-x'`+ passes by construction, and a plausible tidy-up to `info.app && info.app !== x`+ silently turns a missing field into a pass.+**Status.** `tray/webext` done (`src/release.js`, used by `library.jsnewDocument`); `tray/ios` done (`Releases.swift`, PR #315); `tray/android` inprogress.@@ -772,6 +852,64 @@ rather than the shape the SERVER sends. A fixture that is not the real shapeproves only that the code agrees with itself — hence the captured manifest, andhence the same warning for android and ios.+## 2026-08-16 — iOS document search: CoreSpotlight is the surface, and the port is pinned to the LIVE reference++**Decision.** `tray/ios` implements the search settled below. Three things that+the Android port and any future host should follow or knowingly diverge from:++**1. On iOS the "native list" is a screen BESIDE the document browser, and the+system index is a first-class output.** `UIDocumentBrowserViewController` stays+the root; search is one toolbar button away from it. The extracted prose is also+donated to **CoreSpotlight**, which is what the original gap statement ("the app+contributes nothing to search — no CoreSpotlight, no `NSUserActivity`") actually+asked for, and Spotlight results are resolved back through the index rather than+by re-deriving a path. Android has no equivalent obligation; its recents list IS+its root, so it has one surface where iOS has two.++**2. TWO checks, because they catch different things.**+`scripts/test-tray-index.mjs` runs both:++- **against the shared corpus** (`tray/fixtures/`, with `tray/doc-index.mjs` as+ the reference and `expected.json` as the answer key). This proves all three+ hosts give the same frozen answers — including Kotlin, which nothing on a Mac+ running the Swift rig can execute. Budgets are checked too: a port that agreed+ on every case while carrying a different `TEXT_BUDGET` agrees by luck.+- **against the RUNNING `library.js`**, imported live — `describe()` is exported+ and takes injectable deps, so a fake file handle runs the real code path.++The second is not redundant. A frozen answer key pins each port to a SNAPSHOT:+when `library.js` moves, static expectations go stale silently and every host+stays green while drifting from the thing they are copies of. Importing the+reference means it cannot move without a rig failing. Verified 2026-08-16: the+Swift port agrees with both, on all 11 corpus cases and on 59 documents against+the live reference.++**The corpus contract is the one to conform to where they differ.** It folds+`isDocument` into the same call and returns nulls throughout for a file that is+not ours; `library.js`'s `describe()` always returns a title, falling back to the+file name, because its caller sniffs first and it never faces a non-document.+`BentoIndex.describe` follows the corpus and the LISTING supplies the file-name+fallback — which is the better seam anyway: inventing a title during extraction+reports one for a file that is not a Bento document at all.++**3. Ports must count UTF-16 code units.** The reference is JavaScript, where+every index, length and budget is UTF-16; the natural Swift/Kotlin spelling uses+graphemes or code points and disagrees on any document containing an emoji or a+CJK character — that is real documents, not pathological ones. One deviation is+allowed and is written down in `BentoIndex.swift`: the final `slice(0, 40KB)` can+land inside a surrogate pair, and where JavaScript keeps the lone half a Swift+`String` cannot hold one, so it is dropped. The rig accepts exactly that shape+and nothing looser.++**Also:** enumeration needs a folder grant the app did not previously take+(folder-mode `UIDocumentPickerViewController`, persisted as a security-scoped+bookmark). Each indexed document gets its OWN bookmark, minted inside the+folder's open scope, because a file in a granted folder is readable only while+the FOLDER is scoped and an editing session outlives the walk. Encrypted+documents are never read for text or preview, and revoking a folder deletes its+documents from CoreSpotlight — both enforced in `LibraryIndex`, not just+described. Parity table: `tray/README.md`.+## 2026-08-16 — Document search: the list stays native, the indexer is shared by FIXTURE**Decision.** When the native hosts grow a document library, each keeps its own@@ -2065,6 +2203,18 @@ Naming notes, so this is not relitigated:it, so confirm there before submitting.- The App Store name carries no slash. Per the 2026-07-24 naming entry, `/` isa mark, never a stored name.+- **But the ON-DEVICE name does carry it: `CFBundleDisplayName` is `bento/tray`**+ (2026-08-18). These are different fields and only one of them is a stored name.+ The App Store listing name lives in App Store Connect and stays "Bento Tray";+ the bundle display name is a LABEL — it drives the home-screen caption, the+ document browser's title ("bento/tray Recents") and the app's folder in Browse,+ and iOS never turns it into a path, because the container on disk is addressed+ by uuid. Verified on iOS 26: all three render it verbatim, nothing escaped or+ substituted. The 2026-07-24 rule scopes the ban to "filenames, URLs, package+ names and social handles… anywhere a name must be stored or typed", and a+ display label is none of those — it is exactly where the mark belongs. Recorded+ because "the App Store name carries no slash" reads at a glance as "the app is+ never called bento/tray", and someone will otherwise "fix" the plist.**One app, not two.** A separate "generic HTML runner" listing would riskguideline 4.3 (duplicate apps from one developer) and doubles the listingdiff --git a/scripts/lib/tray-release-manifest.json b/scripts/lib/tray-release-manifest.jsonnew file mode 100644index 00000000..d8343bfe--- /dev/null+++ b/scripts/lib/tray-release-manifest.json@@ -0,0 +1,4 @@+{+ "payload": "{\"app\":\"bento-slides\",\"version\":\"1.0.18\",\"sha256\":\"9fef088beb763e86a7c13b6b5e2226816a9e8e1c61331f0c5270fdd5cf538424\",\"url\":\"https://bento.page/releases/slides/Bento_Slides.bento.html\",\"notes\":\"• Security: offline mode did not block everything it promised.\\n• Updating a file no longer interrupts you.\\n• Fix: Share opened cut in half on a narrow window.\\n• The update card drops its peach stripe.\\n• Security: update this file. A deck could run code hidden in its own content. (1.0.17)\\n• A dark interface, if you want one. (1.0.17)\\n…and 8 more\",\"notesFrom\":{\"1.0.18\":[\"Security: offline mode did not block everything it promised.\",\"Updating a file no longer interrupts you.\",\"Fix: Share opened cut in half on a narrow window.\",\"The update card drops its peach stripe.\"],\"1.0.17\":[\"Security: update this file. A deck could run code hidden in its own content.\",\"A dark interface, if you want one.\",\"Hide a slide from the show.\",\"A deck that is being shared now says so before an agent reads it.\",\"Fix: a live session could crash when two people created the same element at the same moment.\",\"Fix: the end of the toolbar could be cut off the right edge.\",\"Fix: on a narrow window, the ⋯ menu could not be clicked.\",\"Fix: choosing a custom slide size now reveals its width and height.\"],\"1.0.16\":[\"Fix: the slide could open off-centre, pushed to one side and clipped.\"],\"1.0.15\":[\"Fix: removing a formatting option no longer disconnects the people you are working with.\",\"\\\"Save a copy…\\\" and share exports remember their own folder.\",\"Fix: the topbar came back in the wrong order after the window narrowed and widened again.\",\"Fix: a deck opens where the browser refuses it storage.\"],\"1.0.14\":[\"Pan the canvas by dragging, and past the slide's edges.\",\"Fit a text box to its text, in one click.\",\"Entrances and count-ups now run on morph slides.\",\"Fix: the built-in layouts fit the slide.\",\"Check a deck for what the runtime silently swallows.\",\"Fix: two gallery templates asked for a typeface they did not carry.\",\"The agent authoring guide describes what the runtime actually does.\"],\"1.0.13\":[\"Fix: fade, slide and zoom transitions animate again.\",\"Copy and paste keeps embedded typefaces intact.\",\"Update notes now cover every version you skipped.\"]},\"at\":\"2026-08-15T19:48:04.509Z\"}",+ "sig": "iqII5phREEUo9st7o3HkNoQifZobKbAY/h9Oeq6ibXjGOJf+uaWjIV7PMtCGW75CT4Wek1rJ6iPFF7OGvjtYIg=="+}diff --git a/scripts/test-tray-index.mjs b/scripts/test-tray-index.mjsnew file mode 100644index 00000000..c2f36073--- /dev/null+++ b/scripts/test-tray-index.mjs@@ -0,0 +1,490 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors++/**+ * Does the iOS text extractor agree with the one the extension ships?+ *+ * `docs/DECISIONS.md` (2026-08-16) settles that the three hosts each carry their+ * own copy of the indexer and are held together by a shared fixture corpus+ * rather than by shared code. The guarantee that buys is not "cannot diverge"+ * but "cannot diverge SILENTLY" — which is only true if something actually+ * looks. This is the thing that looks, for `tray/ios`.+ *+ * It drives the REAL `library.js`: `describe()` is exported and takes its cache+ * through injectable deps, so a fake file handle is enough to run the shipping+ * code path — the title regex, the format regex, the encrypted test, the+ * preview slice and `extractText`, exactly as the extension runs them. That+ * matters more than it might look. A rig that re-implemented the reference+ * would only ever prove the re-implementation agrees with the port; when+ * `library.js` changed, both would be wrong together and the rig would stay+ * green. Importing it means the reference cannot move without this failing.+ *+ * The Swift side is compiled straight from `tray/ios/BentoIndex.swift` with+ * `swiftc`, which is why that file is Foundation-only and has no UIKit in it.+ *+ * Corpus: real documents found in the repo, plus generated edge cases covering+ * the places the two languages are most likely to part company — UTF-16 versus+ * grapheme counting, JavaScript's `\s` versus ICU's, ASCII `\d` versus Unicode+ * Nd, and every budget boundary at N-1/N/N+1. When the shared corpus lands,+ * point this at it: `node scripts/test-tray-index.mjs --corpus <dir>`. It is+ * additive, not a replacement — the generated cases are cheap and the real+ * documents are the ones that catch what nobody thought to generate.+ *+ * Usage:+ * node scripts/test-tray-index.mjs [--corpus <dir>] [--verbose]+ */++import { execFileSync } from 'node:child_process'+import { createHash } from 'node:crypto'+import { mkdtempSync, readFileSync, writeFileSync, readdirSync, statSync, mkdirSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve, dirname, basename } from 'node:path'+import { fileURLToPath, pathToFileURL } from 'node:url'++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')+const args = process.argv.slice(2)+const VERBOSE = args.includes('--verbose')+const corpusIdx = args.indexOf('--corpus')+const EXTRA_CORPUS = corpusIdx !== -1 ? resolve(args[corpusIdx + 1]) : null++const decoder = new TextDecoder('utf-8')++/* ── the generated edge cases ─────────────────────────────────────────────── */++const MARKER = 'id="bento-doc"'+const doc = (body) => `<!doctype html><html><head><title>x</title></head><body>` ++ `<script type="application/json" ${MARKER}>${body}</script></body></html>`++function cases() {+ const out = []+ const add = (name, html) => out.push({ name, html })++ // Nothing to find.+ add('empty', '')+ add('no-marker', '<!doctype html><html><body>hello there friend</body></html>')+ // The marker with no closing script tag — the reference returns null rather+ // than running to the end of the file.+ add('marker-unterminated', `<!doctype html><body><script ${MARKER}>{"title":"Orphan text here"}`)++ // Values are taken from `:"…"`, never from keys.+ add('keys-are-not-values', doc('{"heading":"alpha bravo","charlie":"delta echo"}'))+ // Fewer than three consecutive ASCII letters = an id, a colour, a number.+ add('short-values-skipped', doc('{"a":"#ff0088","b":"12345","c":"ab","d":"real words here"}'))++ // Data URIs: 199 chars stays, 200 goes. The boundary is the whole point.+ add('data-uri-199', doc(`{"src":"data:${'A'.repeat(199)}","t":"keep this prose"}`))+ add('data-uri-200', doc(`{"src":"data:${'A'.repeat(200)}","t":"keep this prose"}`))+ // A `data:` inside a run that was too short to strip — the reference resumes+ // one character later, so the inner one is still found.+ add('data-uri-nested', doc(`{"src":"data:xx data:${'B'.repeat(400)}","t":"prose here"}`))++ // Value length: 400 units matches, 401 is skipped entirely.+ add('value-400', doc(`{"v":"${'word '.repeat(80).slice(0, 400)}"}`))+ add('value-401', doc(`{"v":"${('word '.repeat(81)).slice(0, 401)}","after":"tail words"}`))++ // Escaped quotes keep a value together.+ add('escaped-quote', doc('{"v":"she said \\"hello there\\" loudly"}'))+ add('escaped-backslash', doc('{"v":"path\\\\to\\\\somewhere useful"}'))+ // A trailing backslash cannot start a repetition, so the value never closes.+ add('trailing-backslash', doc('{"v":"dangling\\\\"}'))++ // Tags: 200 non-`>` chars strips, 201 does not.+ add('tag-200', doc(`{"v":"alpha <${'x'.repeat(198)}> bravo"}`))+ add('tag-201', doc(`{"v":"alpha <${'x'.repeat(199)}> bravo"}`))+ add('tag-nested-lt', doc('{"v":"alpha <<b> bravo charlie"}'))+ add('tag-empty', doc('{"v":"alpha <> bravo charlie"}'))++ // Entities. The Arabic-Indic digits are the ICU trap: JavaScript's `\\d` is+ // ASCII, so `&#١٢٣;` is NOT an entity and must survive.+ add('entities-named', doc('{"v":"alpha & bravo &NBSP; charlie"}'))+ add('entities-numeric', doc('{"v":"alpha & bravo Ӓ charlie"}'))+ add('entities-arabic-indic', doc('{"v":"alpha &#١٢٣; bravo charlie"}'))+ add('entities-malformed', doc('{"v":"alpha ¬anentity bravo & charlie"}'))++ // Whitespace. NBSP and U+FEFF collapse (JavaScript `\\s`); U+200B does not.+ add('ws-nbsp', doc('{"v":"alpha bravo charlie"}'))+ add('ws-feff', doc('{"v":"alphabravo charlie"}'))+ add('ws-zwsp-kept', doc('{"v":"alphabravo charlie"}'))+ add('ws-exotic', doc('{"v":"alpha bravo charlie"}'))+ add('ws-vertical-tab', doc('{"v":"alphabravo charlie"}'))++ // UTF-16 counting. Emoji are surrogate pairs: a grapheme-counting port+ // disagrees with the reference on every one of these.+ add('astral-emoji', doc('{"v":"alpha \u{1F600}\u{1F601}\u{1F602} bravo charlie"}'))+ add('cjk', doc('{"v":"alpha 你好世界 bravo charlie"}'))+ add('combining', doc('{"v":"alpha ééé bravo charlie"}'))+ // A 400-unit value made of astral characters — 200 characters, 400 units.+ add('astral-value-400', doc(`{"v":"${'\u{1F600}'.repeat(200)}","after":"tail words here"}`))++ // Title.+ add('title-plain', doc('{"title":"Quarterly Review","v":"body words here"}'))+ add('title-escaped', doc('{"title":"She said \\"go\\"","v":"body words here"}'))+ add('title-empty', doc('{"title":"","v":"body words here"}'))+ add('title-spaced-colon', doc('{"title" : "Spaced Out","v":"body words here"}'))+ add('title-too-long', doc(`{"title":"${'t'.repeat(201)}","v":"body words here"}`))+ add('title-201-boundary', doc(`{"title":"${'t'.repeat(200)}","v":"body words here"}`))++ // Format, and the reason it must scan past a non-matching key.+ add('format-slides', doc('{"format":"bento/slides","v":"body words here"}'))+ add('format-unrelated-first', doc('{"format":"text/html","format":"bento/spaces","v":"body words"}'))+ add('format-uppercase', doc('{"format":"bento/Slides","v":"body words here"}'))++ // Encrypted: no text, no preview. Both spellings.+ add('encrypted-format', doc('{"format":"bento/enc","ct":"opaque ciphertext here"}'))+ add('encrypted-attr', `<!doctype html><body data-bento-enc="1">` ++ `<script ${MARKER}>{"title":"Secret","v":"should not be extracted"}</script>` ++ `<div data-bento-preview="1">leak</div><script data-bento-preview="1"></script></body>`)++ // Preview slice, present and absent.+ add('preview-present', doc('{"v":"body words here"}') ++ `<div data-bento-preview="1"><p>page one</p></div><script data-bento-preview="1">x</script>`)+ add('preview-no-remover', doc('{"v":"body words here"}') ++ `<div data-bento-preview="1"><p>page one</p></div>`)++ // The budget, and the deliberate overshoot: the value is kept, THEN the size+ // is checked, so the last value crosses 40KB before the final slice cuts back.+ const filler = Array.from({ length: 200 }, (_, i) => `"k${i}":"${`lorem ipsum dolor sit amet ${i} `.repeat(8)}"`).join(',')+ add('budget-overshoot', doc(`{${filler}}`))+ // Astral characters straddling the 40KB cut — the one documented deviation.+ const bigAstral = Array.from({ length: 300 }, (_, i) => `"k${i}":"word ${'\u{1F600}'.repeat(80)} ${i}"`).join(',')+ add('budget-astral-cut', doc(`{${bigAstral}}`))++ return out+}++/* ── corpus ───────────────────────────────────────────────────────────────── */++function realDocuments() {+ const found = []+ const skip = new Set(['node_modules', '.git', '.worktrees', 'dist', 'dist-single'])+ const walk = (dir, depth) => {+ if (depth > 3) return+ let entries+ try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return }+ for (const e of entries) {+ if (e.name.startsWith('.') || skip.has(e.name)) continue+ const p = join(dir, e.name)+ if (e.isDirectory()) walk(p, depth + 1)+ else if (/\.html?$/i.test(e.name)) {+ try { if (statSync(p).size > 0) found.push(p) } catch { /* raced */ }+ }+ }+ }+ walk(ROOT, 0)+ // Deterministic order, and a cap so the rig stays quick on a big working tree.+ return found.sort().slice(0, 60)+}++function buildCorpus() {+ const dir = mkdtempSync(join(tmpdir(), 'bento-index-'))+ const files = []+ for (const c of cases()) {+ const p = join(dir, `${c.name}.bento.html`)+ writeFileSync(p, c.html, 'utf8')+ files.push(p)+ }+ const generated = files.length+ for (const p of realDocuments()) files.push(p)+ if (EXTRA_CORPUS) {+ let entries = []+ try { entries = readdirSync(EXTRA_CORPUS, { withFileTypes: true }) } catch {+ console.error(`corpus directory not readable: ${EXTRA_CORPUS}`)+ process.exit(2)+ }+ for (const e of entries) if (e.isFile() && /\.html?$/i.test(e.name)) files.push(join(EXTRA_CORPUS, e.name))+ }+ return { dir, files, generated }+}++/* ── the reference, run as the extension runs it ──────────────────────────── */++async function referenceFor(files) {+ const lib = await import(pathToFileURL(join(ROOT, 'tray/webext/src/library.js')).href)+ const deps = { get: async () => null, put: async () => {} }+ const out = new Map()+ for (const path of files) {+ const bytes = readFileSync(path)+ // What `listDocuments` computes and hands to describe() as the title+ // fallback — extensions stripped, both of them.+ const base = basename(path).replace(/\.bento\.html$/i, '').replace(/\.html?$/i, '')+ const file = {+ size: bytes.length,+ lastModified: 0,+ slice: (a, b) => ({ text: async () => decoder.decode(bytes.subarray(a, b)) }),+ text: async () => decoder.decode(bytes),+ }+ const d = { handle: { getFile: async () => file, name: base }, base, folder: 'corpus', rel: [] }+ const meta = await lib.describe(d, deps)+ // `sniff` is not exported; it is one `includes` on the first 64KB and the+ // rig checks the same thing rather than reaching into the module.+ const isDoc = decoder.decode(bytes.subarray(0, 64 * 1024)).includes(MARKER)+ out.set(path, {+ isDoc,+ title: meta.title,+ app: meta.app ?? null,+ encrypted: meta.encrypted,+ text: meta.text ?? null,+ preview: meta.preview ?? null,+ })+ }+ return out+}++/* ── the port, compiled ───────────────────────────────────────────────────── */++const MAIN_SWIFT = `+import Foundation++struct Row: Codable {+ let path: String+ let isDoc: Bool+ let title: String?+ let app: String?+ let encrypted: Bool+ let text: String?+ let preview: String?+}++let encoder = JSONEncoder()+for path in CommandLine.arguments.dropFirst() {+ guard let data = FileManager.default.contents(atPath: path) else { continue }+ let head = String(decoding: data.prefix(BentoIndex.headBytes), as: UTF8.self)+ let sniff = String(decoding: data.prefix(BentoIndex.sniffBytes), as: UTF8.self)+ let whole = String(decoding: data, as: UTF8.self)+ let meta = BentoIndex.describe(head: head, sniffHead: sniff, whole: whole)+ let row = Row(path: path,+ isDoc: meta.isDocument,+ title: meta.title,+ app: meta.app,+ encrypted: meta.encrypted,+ text: meta.text,+ preview: meta.preview)+ if let out = try? encoder.encode(row), let s = String(data: out, encoding: .utf8) {+ print(s)+ }+}+`++/**+ * `BentoIndex.swift` is Foundation-only, which is what lets this rig REALLY RUN+ * on the Linux CI runner — Swift is installed there and the file compiles+ * unchanged, so the whole diff happens on every push rather than only on a Mac.+ * That is the payoff for keeping UIKit out of it.+ *+ * The skip below is for a machine with no Swift at all. Deliberately LOUD: a+ * skip that reads like a pass is how a rig stops being run.+ */+function haveSwift() {+ try {+ execFileSync('swiftc', ['--version'], { stdio: 'pipe' })+ return true+ } catch {+ return false+ }+}++function buildSwift(dir) {+ const mainPath = join(dir, 'main.swift')+ writeFileSync(mainPath, MAIN_SWIFT, 'utf8')+ const bin = join(dir, 'indexer')+ const src = join(ROOT, 'tray/ios/BentoIndex.swift')+ try {+ execFileSync('swiftc', ['-O', '-o', bin, src, mainPath], { stdio: 'pipe' })+ } catch (e) {+ console.error('swiftc failed:\n' + (e.stderr?.toString() ?? e.message))+ process.exit(2)+ }+ return bin+}++function runSwift(bin, files) {+ const out = new Map()+ // Chunked so the argument list cannot overflow on a large corpus.+ for (let i = 0; i < files.length; i += 40) {+ const chunk = files.slice(i, i + 40)+ const stdout = execFileSync(bin, chunk, { maxBuffer: 512 * 1024 * 1024 }).toString()+ for (const line of stdout.split('\n')) {+ if (!line.trim()) continue+ const row = JSON.parse(line)+ out.set(row.path, {+ isDoc: row.isDoc,+ // `library.js`'s describe() ALWAYS returns a title, falling back to the+ // file's base name, because its caller has already sniffed and it never+ // faces a non-document. The Swift port answers all the questions in one+ // call (the shared contract in tray/fixtures) so it returns nil, and the+ // listing supplies the file name. Same behaviour, different seam — the+ // fallback is applied here so the two are compared like for like.+ title: row.title ?? basename(row.path)+ .replace(/\.bento\.html$/i, '').replace(/\.html?$/i, ''),+ rawTitle: row.title ?? null,+ app: row.app ?? null,+ encrypted: row.encrypted,+ text: row.text ?? null,+ preview: row.preview ?? null,+ })+ }+ }+ return out+}++/* ── compare ──────────────────────────────────────────────────────────────── */++const show = (v) => v === null ? 'null' : JSON.stringify(v.length > 90 ? v.slice(0, 90) + '…' : v)++function firstDifference(a, b) {+ if (a === null || b === null) return null+ const n = Math.min(a.length, b.length)+ for (let i = 0; i < n; i++) if (a[i] !== b[i]) return i+ return a.length === b.length ? null : n+}++/**+ * The one difference that is allowed, stated narrowly enough to be a check.+ *+ * `extractText` ends with `.slice(0, 40KB)` on UTF-16 units, which can land+ * between a surrogate pair. JavaScript keeps the lone half; a Swift `String`+ * cannot hold one at all, so the port drops it — the deviation is forced by the+ * language rather than chosen, and dropping beats decoding to U+FFFD in a+ * search index either way. Recognised here as EXACTLY "js has one more unit,+ * that unit is an unpaired high surrogate, and everything before it is+ * identical", so any other disagreement about text still fails.+ */+function isSurrogateCut(a, b) {+ if (typeof a !== 'string' || typeof b !== 'string') return false+ if (a.length !== b.length + 1) return false+ const last = a.charCodeAt(a.length - 1)+ if (last < 0xd800 || last > 0xdbff) return false+ return a.slice(0, -1) === b+}++function compare(path, js, sw, failures, known) {+ const bad = []+ for (const field of ['isDoc', 'title', 'app', 'encrypted', 'text', 'preview']) {+ if (js[field] === sw[field]) continue+ if (field === 'text' && isSurrogateCut(js[field], sw[field])) { known.push(basename(path)); continue }+ let detail = ` js: ${show(js[field])}\n sw: ${show(sw[field])}`+ if (typeof js[field] === 'string' && typeof sw[field] === 'string') {+ const at = firstDifference(js[field], sw[field])+ const ctx = (s) => JSON.stringify(s.slice(Math.max(0, at - 25), at + 25))+ detail = ` lengths js=${js[field].length} sw=${sw[field].length}, first differs at ${at}\n` ++ ` js …${ctx(js[field])}…\n sw …${ctx(sw[field])}…`+ }+ bad.push(` ${field}:\n${detail}`)+ }+ if (bad.length) failures.push(` ${basename(path)}\n${bad.join('\n')}`)+ return bad.length === 0+}++/* ── main ─────────────────────────────────────────────────────────────────── */++if (!haveSwift()) {+ console.log('tray index: SKIPPED — no swiftc on this machine.')+ console.log(' This rig is the only thing holding tray/ios/BentoIndex.swift to')+ console.log(' tray/webext/src/library.js. Run it on a Mac before changing either.')+ process.exit(0)+}++const { dir, files, generated } = buildCorpus()+const bin = buildSwift(dir)+const js = await referenceFor(files)+const sw = runSwift(bin, files)++const failures = []+const known = []+let checked = 0+let withText = 0+for (const path of files) {+ const a = js.get(path), b = sw.get(path)+ if (!a || !b) { failures.push(` ${basename(path)}\n missing result (js=${!!a} swift=${!!b})`); continue }+ checked+++ if (a.text) withText+++ const ok = compare(path, a, b, failures, known)+ if (VERBOSE) console.log(`${ok ? 'ok ' : 'FAIL'} ${basename(path)}`)+}++const real = files.length - generated - (EXTRA_CORPUS ? 0 : 0)+/* ── the shared corpus ────────────────────────────────────────────────────── */++/**+ * `tray/fixtures/` is the corpus all three hosts answer, with `expected.json`+ * as the answer key and `tray/doc-index.mjs` as the reference. It is a DIFFERENT+ * guarantee from the diff above and worth having both: that one proves this port+ * tracks the extension as it moves, this one proves all three hosts agree on one+ * frozen set of answers — including Kotlin, which nothing on this machine can run.+ *+ * Skipped, not failed, when the directory is absent: it arrives with the Android+ * work, and a rig that fails until an unrelated branch lands is a rig people+ * learn to ignore.+ */+function sharedCorpus() {+ const dir = join(ROOT, 'tray/fixtures')+ let expected+ try { expected = JSON.parse(readFileSync(join(dir, 'expected.json'), 'utf8')) } catch { return null }++ const names = Object.keys(expected.cases).sort()+ const paths = names.map((n) => join(dir, 'cases', n))+ const rows = runSwift(bin, paths)+ const sha = (s) => createHash('sha256').update(s, 'utf8').digest('hex').slice(0, 16)+ const bad = []++ for (const name of names) {+ const want = expected.cases[name]+ const r = rows.get(join(dir, 'cases', name))+ if (!r) { bad.push(` ${name}: the port produced no answer`); continue }+ const mine = {+ isDocument: r.isDoc,+ title: r.rawTitle,+ app: r.app,+ encrypted: r.encrypted,+ hasPreview: r.preview !== null,+ textLength: r.text === null ? null : r.text.length,+ textSha256_16: r.text === null ? null : sha(r.text),+ text: r.text,+ }+ for (const key of Object.keys(want)) {+ if (JSON.stringify(want[key]) === JSON.stringify(mine[key])) continue+ bad.push(` ${name} · ${key}: corpus says ${show(want[key])}, port says ${show(mine[key])}`)+ }+ }++ // The budgets are part of the contract too — a port that agreed on every case+ // while carrying a different TEXT_BUDGET agrees only by luck.+ const budgets = [['textBudget', 40960], ['sniffBytes', 65536], ['headBytes', 307200]]+ for (const [key, mineValue] of budgets) {+ if (expected[key] !== undefined && expected[key] !== mineValue) {+ bad.push(` ${key}: corpus says ${expected[key]}, port uses ${mineValue}`)+ }+ }+ return { count: names.length, bad }+}++const shared = sharedCorpus()++console.log(`\ntray index: ${checked} documents compared ` ++ `(${generated} generated edge cases, ${real} from the tree${EXTRA_CORPUS ? `, corpus ${EXTRA_CORPUS}` : ''})`)+console.log(` ${withText} yielded searchable text`)+if (known.length) {+ console.log(` ${known.length} matched only after the documented surrogate-cut deviation ` ++ `(${known.join(', ')})`)+}++if (shared) {+ console.log(` shared corpus (tray/fixtures): ${shared.count} cases` ++ (shared.bad.length ? ` — ${shared.bad.length} DISAGREE` : ' — all agree'))+} else {+ console.log(' shared corpus (tray/fixtures): absent, skipped — arrives with tray/android')+}++if (failures.length || shared?.bad.length) {+ if (failures.length) {+ console.error(`\n${failures.length} disagreement(s) between library.js and BentoIndex.swift:\n`)+ console.error(failures.join('\n\n'))+ }+ if (shared?.bad.length) {+ console.error('\nDisagreements with the shared corpus (tray/fixtures/expected.json):\n')+ console.error(shared.bad.join('\n'))+ }+ process.exit(1)+}+console.log(' swift port agrees with library.js on every field')diff --git a/scripts/test-tray-releases.mjs b/scripts/test-tray-releases.mjsnew file mode 100644index 00000000..79562c52--- /dev/null+++ b/scripts/test-tray-releases.mjs@@ -0,0 +1,274 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors++/**+ * Does the iOS release verifier REFUSE what it should?+ *+ * `tray/ios/Releases.swift` fetches the shell for a new document from the signed+ * release channel, because starter decks are not bundled. Those bytes become an+ * executable HTML document on the reader's own disk that they will afterwards+ * trust — so an unverified download lets a network attacker choose what they+ * create, and the verification is the whole reason the fetch is acceptable at+ * all (`docs/DECISIONS.md`, 2026-08-16).+ *+ * Watching it succeed against the live server proves nothing: `return true`+ * passes that test. What has to be shown is that it says NO — to a tampered+ * payload, to a tampered signature, to a signature that is valid for a+ * DIFFERENT payload, and to a malformed envelope. Every case below is a way the+ * check could be wrong while looking right in the app.+ *+ * The fixture is a real manifest captured from bento.page. It does not go stale:+ * a signature stays valid for the bytes it covers forever, so this keeps testing+ * the same thing after the live release has moved on.+ *+ * Needs an APPLE Swift toolchain, and the reason is worth stating precisely+ * because the obvious guess is wrong: the Linux CI runner DOES have `swiftc`,+ * and `scripts/test-tray-index.mjs` really does compile and run there. What is+ * missing on Linux is CryptoKit, which is Apple-only — so this rig probes for+ * the MODULE rather than for the compiler. Probing for `swiftc` skipped nothing+ * and failed the build.+ */++import { execFileSync } from 'node:child_process'+import { mkdtempSync, readFileSync, writeFileSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve, dirname } from 'node:path'+import { fileURLToPath } from 'node:url'++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')++/** Can this machine build the thing under test at all? */+function haveCryptoKit() {+ let probe+ try {+ probe = mkdtempSync(join(tmpdir(), 'bento-cryptokit-'))+ // Foundation too — `Data` comes from there, and a probe that fails for its+ // OWN missing import would skip this rig on a perfectly capable Mac.+ writeFileSync(join(probe, 'main.swift'),+ 'import CryptoKit\nimport Foundation\nprint(SHA256.hash(data: Data()).description)\n')+ execFileSync('swiftc', ['-o', join(probe, 'p'), join(probe, 'main.swift')], { stdio: 'pipe' })+ return true+ } catch {+ return false+ } finally {+ if (probe) try { rmSync(probe, { recursive: true, force: true }) } catch { /* best effort */ }+ }+}++if (!haveCryptoKit()) {+ console.log('tray releases: SKIPPED — no CryptoKit on this machine (Apple platforms only).')+ console.log(' This rig is the only proof that the release verifier REFUSES a')+ console.log(' tampered manifest, and a new document is fetched over the network')+ console.log(' and written to disk as an executable page. Run it on a Mac before')+ console.log(' touching Releases.swift.')+ process.exit(0)+}++const MAIN = `+import Foundation++// Each argument is "<app-id>:<path>" — the app the caller ASKED for, and the+// envelope the channel served. Going through \`release(from:for:)\` rather than+// \`verify\` alone is deliberate: the app-identity check lives there, and it is+// the one that catches a swap between two genuinely signed releases.+for arg in CommandLine.arguments.dropFirst() {+ let parts = arg.split(separator: ":", maxSplits: 1).map(String.init)+ guard parts.count == 2, let app = Releases.apps.first(where: { $0.id == parts[0] }) else {+ print("REFUSE bad test argument"); continue+ }+ // "<app>:<floor-or-none>:<path>" — the floor exercises rollback refusal+ // without touching UserDefaults, which the app owns.+ let bits = parts[1].split(separator: ":", maxSplits: 1).map(String.init)+ let floor = bits[0] == "none" ? nil : bits[0]+ let raw = (try? String(contentsOfFile: bits[1], encoding: .utf8)) ?? ""+ do {+ let release = try Releases.release(from: raw, for: app, notBefore: floor)+ print("ACCEPT \\(release.version)")+ } catch {+ print("REFUSE \\(error.localizedDescription)")+ }+}+`++const dir = mkdtempSync(join(tmpdir(), 'bento-releases-'))+writeFileSync(join(dir, 'main.swift'), MAIN)+const bin = join(dir, 'verifier')+try {+ execFileSync('swiftc', ['-O', '-o', bin, join(ROOT, 'tray/ios/Releases.swift'), join(dir, 'main.swift')],+ { stdio: 'pipe' })+} catch (e) {+ console.error('swiftc failed:\n' + (e.stderr?.toString() ?? e.message))+ process.exit(2)+}++const real = JSON.parse(readFileSync(join(ROOT, 'scripts/lib/tray-release-manifest.json'), 'utf8'))++/** Flip one character of a base64 signature, keeping it decodable. */+const bendSig = (sig) => {+ const at = 10+ const c = sig[at]+ return sig.slice(0, at) + (c === 'A' ? 'B' : 'A') + sig.slice(at + 1)+}++const cases = [+ {+ name: 'the real manifest',+ expect: 'ACCEPT',+ why: 'a genuine signed release must be accepted, or nothing can be created at all',+ envelope: JSON.stringify(real),+ },+ {+ name: 'payload tampered (url swapped)',+ expect: 'REFUSE',+ why: 'THE attack: point the download at a shell an attacker controls',+ envelope: JSON.stringify({+ ...real,+ payload: real.payload.replace(/"url":"[^"]*"/, '"url":"https://evil.example/shell.html"'),+ }),+ },+ {+ name: 'payload tampered (sha256 swapped)',+ expect: 'REFUSE',+ why: 'defeats the hash check downstream by re-pinning it to attacker bytes',+ envelope: JSON.stringify({+ ...real,+ payload: real.payload.replace(/"sha256":"[0-9a-f]*"/, `"sha256":"${'0'.repeat(64)}"`),+ }),+ },+ {+ name: 'signature tampered',+ expect: 'REFUSE',+ why: 'a bent signature must not verify — catches a verifier that ignores its input',+ envelope: JSON.stringify({ ...real, sig: bendSig(real.sig) }),+ },+ {+ name: 'signature valid for a DIFFERENT payload',+ expect: 'REFUSE',+ why: 'catches verifying the wrong bytes — a real signature, the wrong message',+ envelope: JSON.stringify({ payload: JSON.stringify({ app: 'bento-slides', version: '9.9.9' }), sig: real.sig }),+ },+ {+ name: 'signature removed',+ expect: 'REFUSE',+ why: 'an unsigned manifest must never be treated as signed',+ envelope: JSON.stringify({ payload: real.payload }),+ },+ {+ name: 'empty signature',+ expect: 'REFUSE',+ why: 'the empty string is the value an absent field decodes to',+ envelope: JSON.stringify({ ...real, sig: '' }),+ },+ {+ name: 'not JSON at all',+ expect: 'REFUSE',+ why: 'a captive-portal HTML page is what a fetch returns on hotel wifi',+ envelope: '<html><body>Sign in to continue</body></html>',+ },+ {+ // Found by reading tray/webext's own verification tests (PR #318), which+ // had this case when neither native host did. Both manifests are GENUINELY+ // signed by the maintainer, so the signature passes and the hash passes —+ // every byte is authentic, just not the thing that was asked for. Only+ // identity catches a swap between two real releases.+ name: 'a real slides manifest served on the DASH channel',+ expect: 'REFUSE',+ app: 'dash',+ why: 'signature and hash both pass; only the app check catches this',+ envelope: JSON.stringify(real),+ },+ {+ name: 'the same manifest on its OWN channel',+ expect: 'ACCEPT',+ app: 'slides',+ why: 'the identity check must not reject the legitimate case',+ envelope: JSON.stringify(real),+ },+ {+ name: 'payload naming no app at all',+ expect: 'REFUSE',+ why: 'an absent field must not read as a match',+ envelope: JSON.stringify({ ...real, payload: real.payload.replace(/"app":"[^"]*",/, '') }),+ },+ {+ // The webext session's point, and it is a good one: bending bytes only+ // proves the verifier rejects a signature that does not validate. This+ // rejects one that validates PERFECTLY — under the wrong key. That is what+ // catches a verifier which imported the wrong key, or which would trust a+ // key travelling in the manifest. No seam is needed to test it: sign with a+ // throwaway key and hand it to the shipped verifier, which must refuse.+ name: 'signed perfectly, by somebody else',+ expect: 'REFUSE',+ why: 'a valid signature under an untrusted key is the wrong-key failure mode',+ envelope: null, // built below — needs async WebCrypto+ },+ {+ name: 'a flat unsigned manifest',+ expect: 'REFUSE',+ why: 'exactly what the old broken reader wanted; refused as a CATEGORY, not as a parse error',+ envelope: JSON.stringify({ app: 'bento-slides', version: '1.0.18', url: 'https://bento.page/x.html', sha256: 'ab' }),+ },+ {+ name: 'a genuine but OLDER release, against a newer floor',+ expect: 'REFUSE',+ floor: '1.0.99',+ why: 'rollback replay: every other check passes because every byte is authentic',+ envelope: JSON.stringify(real),+ },+ {+ name: 'the same release, against an older floor',+ expect: 'ACCEPT',+ floor: '1.0.17',+ why: 'moving forward must still work, or the floor bricks the + button',+ envelope: JSON.stringify(real),+ },+ {+ name: 'the same release, against an equal floor',+ expect: 'ACCEPT',+ floor: '1.0.18',+ why: 're-fetching the version you already have is normal, not an attack',+ envelope: JSON.stringify(real),+ },+]++/* The wrong-key envelope: a real ECDSA P-256 signature over the real payload,+ * made with a key the app has never heard of. */+{+ const { webcrypto } = await import('node:crypto')+ const pair = await webcrypto.subtle.generateKey(+ { name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify'])+ const sig = await webcrypto.subtle.sign(+ { name: 'ECDSA', hash: 'SHA-256' }, pair.privateKey, Buffer.from(real.payload, 'utf8'))+ const c = cases.find((k) => k.envelope === null)+ c.envelope = JSON.stringify({ payload: real.payload, sig: Buffer.from(sig).toString('base64') })+}++const paths = cases.map((c, i) => {+ const p = join(dir, `case-${i}.json`)+ writeFileSync(p, c.envelope)+ return `${c.app ?? 'slides'}:${c.floor ?? 'none'}:${p}`+})++const out = execFileSync(bin, paths).toString().trim().split('\n')++let failed = 0+for (const [i, c] of cases.entries()) {+ const got = (out[i] ?? '').startsWith('ACCEPT') ? 'ACCEPT' : 'REFUSE'+ const ok = got === c.expect+ if (!ok) failed+++ console.log(`${ok ? 'ok ' : 'FAIL'} ${c.expect.padEnd(6)} ${c.name}`)+ if (!ok) {+ console.log(` expected ${c.expect}, got: ${out[i]}`)+ console.log(` why it matters: ${c.why}`)+ }+}++console.log(`\ntray releases: ${cases.length - failed}/${cases.length} verifier cases behaved correctly`)+if (failed) {+ console.error('\nThe release verifier does not refuse what it must. A new document is')+ console.error('fetched over the network and written to disk as an executable page —')+ console.error('this check is what makes that acceptable.')+ process.exit(1)+}+console.log(' a tampered manifest cannot produce a document')diff --git a/tray/README.md b/tray/README.mdindex 884cd987..aac34a3d 100644--- a/tray/README.md+++ b/tray/README.md@@ -1,4 +1,4 @@-# bento/tray+# bento/homeThin native hosts that run **any self-contained HTML document** and let it**save itself in place**, on platforms where a browser will not.@@ -108,7 +108,7 @@ mean more than "any document that saves the way Bento does":"export this page" tools. WKWebView DROPS these silently without a downloaddelegate, so the button appears to do nothing, which is the worst possiblefailure for a save. Downloads land in the app's Documents folder (visible in- Files under Bento Tray) with a collision-safe name and a confirmation. A+ Files under bento/home) with a collision-safe name and a confirmation. Apicker per save would punish an app that saves often, and a download cannotoverwrite the user's original anyway — that is what the FSA path is for.@@ -276,7 +276,7 @@ back to downloading the rollback copy, which is where it used to go.Four routes, all landing on the same in-place editing:-1. **Files** — the app's folder appears under *On My iPhone → Bento Tray*, and+1. **Files** — the app's folder appears under *On My iPhone → bento/home*, andthe Browse tab navigates the whole Files hierarchy: iCloud Drive, Dropbox,Google Drive, anything with a File Provider. Tap a document to open it whereit lives; edits go back to that file.@@ -470,13 +470,21 @@ here rather than discovered later.| `<input type="file">` | native | `onShowFileChooser` | same || element fullscreen | declined | declined | same || safe-area insets, natively + `--tray-safe-*` | ✓ | ✓ | same |-| new document from the bundled seed | ✓ | ✓ | same |+| new document | fetched from the signed release channel | fetched from the signed release channel | same |+| starter deck bundled in the app | **no** | **no** | same |+| release manifest signature verified | `CryptoKit` P-256 | `SHA256withECDSA` + DER | same check |+| downloaded shell hash-checked | ✓ | ✓ | same |+| release is for the app we ASKED for | ✓ | — | **gap on Android** |+| rollback refused (per-app version floor) | ✓ | — | **gap on Android** |+| seed cached for offline "New" | Application Support | `filesDir` | same || way back out | floating exit, fades when idle | system back gesture | platform-forced || root screen | `UIDocumentBrowserViewController` | own recents list over SAF | platform-forced || `<a download>` lands | app's Documents folder, silently | wherever the author picks | platform-forced || write access to an opened document | always | **may be read-only** | platform-forced || status bar while editing | hidden on iPad | always shown | **known gap** |-| finding a document by its contents | — | — | **gap on both**, see below |+| whole-folder grant | folder-mode `UIDocumentPickerViewController` | `ACTION_OPEN_DOCUMENT_TREE` | same capability |+| text extracted from a document | `BentoIndex.swift` | (in progress) | ported per platform |+| finding a document by its contents | ✓ search screen + Spotlight | — | **gap on Android**, see below |Two gaps, both named rather than quietly left out.@@ -486,18 +494,57 @@ the whole screen there; the Android equivalent would be to hide it on tabletstablet target, and shipping an untested behaviour is worse than naming anuntested one.-**Search — and note this table compares the two NATIVE hosts to each other,-which flatters both.** Against `tray/webext` there is a third axis neither has:-the extension scans every granted folder and searches **the document's own-prose**, so a deck is findable by a phrase on a slide. iOS gets only the system-document browser's search field, and the app contributes nothing to it (no-CoreSpotlight, no `NSUserActivity`); Android has no search at all. Both platforms-*could* support it — `ACTION_OPEN_DOCUMENT_TREE` on Android, the folder-mode-document picker on iOS — so this is "not built", not "can't". The direction is-settled in `docs/DECISIONS.md` (2026-08-16): native list UI on each host, the-extraction ported per platform and pinned against one shared fixture, rather than-a shared HTML library screen in a WebView — which was measured at ~0.5s of extra-cold start and would cost iOS its system document browser.+**Search.** `tray/webext` scans every granted folder and searches **the document's+own prose**, so a deck is findable by a phrase on a slide rather than by what+somebody named the file. iOS has that now; Android does not yet.++On iOS it is three pieces, following `docs/DECISIONS.md` (2026-08-16):++- a **whole-folder grant** through the folder-mode document picker, persisted as+ a security-scoped bookmark — the app could previously open one file at a time+ and could not enumerate anything;+- **`BentoIndex.swift`**, a port of the extension's `extractText`: up to 40KB of+ prose per document pulled out of the `#bento-doc` block as string values, data+ URIs stripped first, encrypted documents never read at all;+- a **search screen** beside the document browser, and the same prose donated to+ **CoreSpotlight** so results turn up in system search too.++The browser stays the root. It is not a list but a surface — iCloud Drive, every+File Provider on the device, drag-and-drop, rename in place, favourites and tags+— so search is one button away from it rather than in place of it.++The port is held in place by `scripts/test-tray-index.mjs`, which runs two checks+because they fail for different reasons:++- the **shared corpus** in `tray/fixtures/` — the same cases and answer key every+ host answers, budgets included. Skipped, not failed, when that directory is+ absent, since it arrives with the Android work.+- a diff against the **live `library.js`**, imported and run rather than copied,+ over generated edge cases and every document in the tree. A frozen answer key+ pins a port to a snapshot; when the reference moves, static expectations go+ stale silently and every host stays green while drifting.++That is what makes "each host carries its own copy" safe: a divergence is a+failing rig rather than a document that is findable on one platform and not+another. The one deviation currently accepted is written down in+`BentoIndex.swift` — JavaScript can hold half a surrogate pair at the 40KB cut+and Swift cannot, so the port drops it.++Indexing prose into CoreSpotlight is a deliberate reach beyond the app, so two+rules are enforced in code rather than described: an encrypted document yields no+text and no preview, and revoking a folder deletes everything indexed from it.++**Not built yet, on iOS.** The `data-bento-preview` slice is extracted and stored+— it is free, the same read produces it — but the results list shows no+thumbnail, because turning that HTML into an image means snapshotting a WebView+per row. The document browser already thumbnails these documents; the search+list does not.++**One thing the extraction inherits from the reference**, visible in snippets: it+pulls string VALUES, so style values (`sans-serif`, `#EAF4FF`, `rgba(…)`) sit in+the prose alongside real words. That is what makes it format-agnostic, and it is+the extension's behaviour too — narrowing it is a change to all three ports and+belongs in `docs/DECISIONS.md`, not in one host.### What is genuinely differentdiff --git a/tray/assets/make-icons.mjs b/tray/assets/make-icons.mjsindex 7d1f85de..16bb5f4c 100644--- a/tray/assets/make-icons.mjs+++ b/tray/assets/make-icons.mjs@@ -3,15 +3,22 @@// Copyright (c) 2026 The Bento authors//// One mark, two platforms. `tray-icon.svg` is the SOURCE; this generates the-// Android launcher vectors from it so the geometry cannot drift.+// Android launcher vectors and the iOS asset catalog from it so the geometry and+// the palette cannot drift.//-// node tray/assets/make-icons.mjs # write the Android drawables+// node tray/assets/make-icons.mjs # write the generated assets// node tray/assets/make-icons.mjs --check # fail if they are out of date (CI)//-// iOS consumes the same SVG directly, as a 1024x1024 PNG export — see the-// comment at the top of tray-icon.svg for the export command. It is not-// generated here because it needs a browser to rasterise, and this script has no-// dependencies on purpose.+// The iOS APP ICON is still a hand-exported 1024x1024 PNG — see the comment at+// the top of tray-icon.svg for the command — because rasterising needs a browser+// and this script has no dependencies on purpose. Everything else iOS needs is+// vector or colour, so it is generated: the mark used by the launch screen and+// the in-app chrome, and the four brand colours as named colour sets.+//+// The colours are read OUT OF THE MARK rather than typed in again. Four hex+// values restated in a Swift file are four values that can disagree with the+// logo, and nothing would notice — the app would simply be slightly the wrong+// navy forever.//// WHY GENERATE AT ALL: Android vector drawables have no <rect>, so every rounded// rectangle in the mark has to be re-expressed as path data. Written by hand@@ -24,6 +31,7 @@ import { fileURLToPath } from 'node:url'const here = dirname(fileURLToPath(import.meta.url))const ANDROID_RES = join(here, '../android/app/src/main/res/drawable')+const IOS_ASSETS = join(here, '../ios/Assets.xcassets')// The adaptive-icon canvas is 108 units with a 72-unit safe zone. The cream tray// is drawn at 56, NOT 72: at 72 it exactly filled the visible area, so every@@ -121,7 +129,80 @@ ${extra}-->return {[join(ANDROID_RES, 'ic_launcher_foreground.xml')]: foreground,[join(ANDROID_RES, 'ic_launcher_monochrome.xml')]: monochrome,+ ...ios({ ground, tray, cells }),+ }+}++/**+ * The iOS asset catalog: the mark as a vector image set, and the brand palette+ * as named colour sets.+ *+ * The mark keeps its navy GROUND, deliberately, so one asset serves both places+ * it is used. On the navy launch screen the frame melts into the background and+ * the cream tray reads as floating; on the search screen's system background it+ * reads as the app icon. A frameless variant would vanish on white and need a+ * second asset to maintain.+ *+ * Named colour sets rather than UIColor literals in Swift: the launch screen is+ * configured from Info.plist and can only name a colour from the catalog, so the+ * catalog has to hold them anyway. Having code read the same names means the+ * launch screen and the chrome cannot end up different shades of navy.+ */+function ios({ ground, tray, cells }) {+ const asset = (obj) => JSON.stringify(obj, null, 2) + '\n'+ const info = { author: 'xcode', version: 1 }++ const note = 'GENERATED from tray/assets/tray-icon.svg by tray/assets/make-icons.mjs.'+ const mark =+ `<!-- ${note} Do not edit. -->\n` ++ `<svg xmlns="http://www.w3.org/2000/svg" width="${ground.w * 4}" height="${ground.h * 4}"\n` ++ ` viewBox="0 0 ${ground.w} ${ground.h}" role="img" aria-label="bento home">\n` ++ [ground, tray, ...cells].map((r) =>+ ` <rect${r.x ? ` x="${f(r.x)}"` : ''}${r.y ? ` y="${f(r.y)}"` : ''}` ++ ` width="${f(r.w)}" height="${f(r.h)}"${r.r ? ` rx="${f(r.r)}"` : ''} fill="${r.fill}"/>`+ ).join('\n') ++ '\n</svg>\n'++ // Ground is the navy, tray the cream, and the three compartments give steel,+ // peach and (again) navy. Named for what they are in the mark, so a reader can+ // point at the shape a colour came from.+ const palette = {+ BentoNavy: ground.fill,+ BentoCream: tray.fill,+ BentoSteel: cells[0].fill,+ BentoPeach: cells[1].fill,+ }++ const colorset = (hex) => asset({+ colors: [{+ color: {+ 'color-space': 'srgb',+ components: {+ alpha: '1.000',+ red: `0x${hex.slice(1, 3).toUpperCase()}`,+ green: `0x${hex.slice(3, 5).toUpperCase()}`,+ blue: `0x${hex.slice(5, 7).toUpperCase()}`,+ },+ },+ idiom: 'universal',+ }],+ info,+ })++ const out = {+ [join(IOS_ASSETS, 'BentoMark.imageset', 'bento-mark.svg')]: mark,+ [join(IOS_ASSETS, 'BentoMark.imageset', 'Contents.json')]: asset({+ images: [{ filename: 'bento-mark.svg', idiom: 'universal' }],+ info,+ // Vector preserved so the launch screen and any chrome can scale it without+ // shipping a rasterised ladder of @1x/@2x/@3x.+ properties: { 'preserves-vector-representation': true },+ }),+ }+ for (const [name, hex] of Object.entries(palette)) {+ out[join(IOS_ASSETS, `${name}.colorset`, 'Contents.json')] = colorset(hex)}+ return out}const files = build()@@ -141,8 +222,9 @@ for (const [path, content] of Object.entries(files)) {}if (check && stale) {- console.error('\nAndroid launcher drawables are out of date with tray-icon.svg.')+ console.error(`\n${stale} generated file(s) are out of date with tray-icon.svg —`)+ console.error('the Android launcher vectors and/or the iOS asset catalog.')console.error('Run: node tray/assets/make-icons.mjs')process.exit(1)}-if (!stale) console.log('icons up to date')+if (!stale) console.log('mark, launcher vectors and iOS assets all match tray-icon.svg')diff --git a/tray/assets/tray-icon.svg b/tray/assets/tray-icon.svgindex 7f030141..5dba484b 100644--- a/tray/assets/tray-icon.svg+++ b/tray/assets/tray-icon.svg@@ -1,5 +1,5 @@<!--- bento/tray iOS app icon — the mark from tray-logo.svg, full bleed.+ bento/home iOS app icon — the mark from tray-logo.svg, full bleed.No corner radius: iOS applies its own squircle mask, and a rounded rect drawninside one shows as a seam along every edge.@@ -18,7 +18,7 @@--default-background-color=00000000 tray-icon.svg--><svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 32 32"- role="img" aria-label="Bento Tray">+ role="img" aria-label="bento home"><rect width="32" height="32" fill="#16273E"/><rect x="4.2" y="4.2" width="23.6" height="23.6" rx="4.8" fill="#F0EBE0"/><rect x="6.800" y="6.800" width="5.855" height="18.400" rx="2.091" fill="#5E7699"/>diff --git a/tray/assets/tray-logo.svg b/tray/assets/tray-logo.svgindex c5be9c92..a19ffa06 100644--- a/tray/assets/tray-logo.svg+++ b/tray/assets/tray-logo.svg@@ -1,5 +1,5 @@<!--- bento/tray mark.+ bento/home mark.The mark inverts the parent rather than adding anything to it: the TRAY is thesurface, filling the frame, and the Bento compartments sit on it. That changes@@ -17,7 +17,7 @@with one shape instead of two.--><svg xmlns="http://www.w3.org/2000/svg" width="112" height="112" viewBox="0 0 32 32"- role="img" aria-label="Bento Tray">+ role="img" aria-label="bento home"><rect width="32" height="32" rx="7" fill="#16273E"/><rect x="3.6" y="3.6" width="24.8" height="24.8" rx="5" fill="#F0EBE0"/><rect x="6.400" y="6.400" width="6.109" height="19.200" rx="2.182" fill="#5E7699"/>diff --git a/tray/ios/Assets.xcassets/BentoCream.colorset/Contents.json b/tray/ios/Assets.xcassets/BentoCream.colorset/Contents.jsonnew file mode 100644index 00000000..fb003112--- /dev/null+++ b/tray/ios/Assets.xcassets/BentoCream.colorset/Contents.json@@ -0,0 +1,20 @@+{+ "colors": [+ {+ "color": {+ "color-space": "srgb",+ "components": {+ "alpha": "1.000",+ "red": "0xF0",+ "green": "0xEB",+ "blue": "0xE0"+ }+ },+ "idiom": "universal"+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}diff --git a/tray/ios/Assets.xcassets/BentoMark.imageset/Contents.json b/tray/ios/Assets.xcassets/BentoMark.imageset/Contents.jsonnew file mode 100644index 00000000..992faffb--- /dev/null+++ b/tray/ios/Assets.xcassets/BentoMark.imageset/Contents.json@@ -0,0 +1,15 @@+{+ "images": [+ {+ "filename": "bento-mark.svg",+ "idiom": "universal"+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ },+ "properties": {+ "preserves-vector-representation": true+ }+}diff --git a/tray/ios/Assets.xcassets/BentoMark.imageset/bento-mark.svg b/tray/ios/Assets.xcassets/BentoMark.imageset/bento-mark.svgnew file mode 100644index 00000000..716dcefc--- /dev/null+++ b/tray/ios/Assets.xcassets/BentoMark.imageset/bento-mark.svg@@ -0,0 +1,9 @@+<!-- GENERATED from tray/assets/tray-icon.svg by tray/assets/make-icons.mjs. Do not edit. -->+<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128"+ viewBox="0 0 32 32" role="img" aria-label="bento home">+ <rect width="32" height="32" fill="#16273E"/>+ <rect x="4.2" y="4.2" width="23.6" height="23.6" rx="4.8" fill="#F0EBE0"/>+ <rect x="6.8" y="6.8" width="5.86" height="18.4" rx="2.09" fill="#5E7699"/>+ <rect x="14.33" y="6.8" width="10.87" height="8.36" rx="2.09" fill="#FF9E8A"/>+ <rect x="14.33" y="16.84" width="10.87" height="8.36" rx="2.09" fill="#16273E"/>+</svg>diff --git a/tray/ios/Assets.xcassets/BentoNavy.colorset/Contents.json b/tray/ios/Assets.xcassets/BentoNavy.colorset/Contents.jsonnew file mode 100644index 00000000..4273efe3--- /dev/null+++ b/tray/ios/Assets.xcassets/BentoNavy.colorset/Contents.json@@ -0,0 +1,20 @@+{+ "colors": [+ {+ "color": {+ "color-space": "srgb",+ "components": {+ "alpha": "1.000",+ "red": "0x16",+ "green": "0x27",+ "blue": "0x3E"+ }+ },+ "idiom": "universal"+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}diff --git a/tray/ios/Assets.xcassets/BentoPeach.colorset/Contents.json b/tray/ios/Assets.xcassets/BentoPeach.colorset/Contents.jsonnew file mode 100644index 00000000..a0f58e32--- /dev/null+++ b/tray/ios/Assets.xcassets/BentoPeach.colorset/Contents.json@@ -0,0 +1,20 @@+{+ "colors": [+ {+ "color": {+ "color-space": "srgb",+ "components": {+ "alpha": "1.000",+ "red": "0xFF",+ "green": "0x9E",+ "blue": "0x8A"+ }+ },+ "idiom": "universal"+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}diff --git a/tray/ios/Assets.xcassets/BentoSteel.colorset/Contents.json b/tray/ios/Assets.xcassets/BentoSteel.colorset/Contents.jsonnew file mode 100644index 00000000..4c74bd22--- /dev/null+++ b/tray/ios/Assets.xcassets/BentoSteel.colorset/Contents.json@@ -0,0 +1,20 @@+{+ "colors": [+ {+ "color": {+ "color-space": "srgb",+ "components": {+ "alpha": "1.000",+ "red": "0x5E",+ "green": "0x76",+ "blue": "0x99"+ }+ },+ "idiom": "universal"+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}diff --git a/tray/ios/BentoIndex.swift b/tray/ios/BentoIndex.swiftnew file mode 100644index 00000000..90bc8e63--- /dev/null+++ b/tray/ios/BentoIndex.swift@@ -0,0 +1,511 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors++import Foundation++/// What a Bento document says about itself, read without parsing it.+///+/// This is a port of `tray/webext/src/library.js` — `sniff`, the metadata half+/// of `describe`, and `extractText`. The three hosts (extension, iOS, Android)+/// each carry their own copy, pinned to each other by a shared fixture corpus+/// rather than by shared code; the reasoning is in `docs/DECISIONS.md`+/// (2026-08-16, "Document search: the list stays native, the indexer is shared+/// by FIXTURE"). Read that before changing anything here — a change that is not+/// also made in the other two is a silent divergence, and the fixture is what+/// turns it into a loud one.+///+/// **Everything here works in UTF-16 code units, deliberately.** The reference+/// is JavaScript, where `indexOf`, `slice`, `String.length` and every regex+/// offset are UTF-16. Swift's `String` is grapheme-clustered, so the natural+/// Swift spelling of this code would silently disagree with the reference the+/// moment a document contains an emoji or a CJK character — which is to say, on+/// real documents rather than only on pathological ones. Counting the same+/// units the reference counts is the cheapest way to be able to prove agreement.+///+/// **No UIKit.** Kept Foundation-only so it compiles standalone with `swiftc`,+/// which is what `scripts/test-tray-index.mjs` does to diff this against the+/// live JavaScript. An indexer that can only be exercised inside a simulator is+/// an indexer whose agreement with the reference is an assertion rather than a+/// measurement.+enum BentoIndex {++ // MARK: - Budgets+ //+ // These four numbers are the reference's, and they are the ones the fixture+ // pins. Changing one here without changing it in `library.js` and in the+ // Android port makes the same document searchable by different words on+ // different platforms.++ /// The splice-contract marker every Bento app honours (`docs/PLATFORM.md`+ /// §2), frozen because old updaters depend on it. It is what makes a file a+ /// Bento document — the `.bento.html` name is a convention, and conventions+ /// get broken by people renaming things to email them.+ static let marker = "id=\"bento-doc\""++ /// How much of a file to read before deciding whether it is one of ours.+ /// Measured on a real shell the marker sits 5.8KB in, so this is generous —+ /// and deliberately much smaller than `headBytes`, because this runs against+ /// every stray `.html` in a granted folder and most of them are not ours.+ static let sniffBytes = 64 * 1024++ /// Enough to reach the title inside the document block. NOT enough to reach+ /// the end of that block, which runs to megabytes when a document carries+ /// images — an earlier metadata reader looked for the closing tag and so+ /// found nothing in any document with a picture in it.+ static let headBytes = 300 * 1024++ /// How much extracted prose to keep. Enough for any phrase somebody would+ /// search for; far short of storing the document twice.+ static let textBudget = 40 * 1024++ // MARK: - Result++ struct Meta {+ /// Is this one of ours at all? Everything below is nil or false when it+ /// is not — the shared corpus pins that, and it is why `title` is+ /// optional rather than falling back to the file name here. A file name+ /// is what the LISTING shows when a document has no title of its own;+ /// inventing one during extraction would report a title for a file that+ /// is not even a Bento document.+ var isDocument: Bool+ /// The document's own title, if it has one.+ var title: String?+ /// Which Bento this is — `slides`, `spaces`, `dash`. A pristine shell+ /// has no document in it yet and so no format: that is not a failure,+ /// it is a document nobody has saved.+ var app: String?+ var encrypted: Bool+ /// What the document SAYS, so search can find a deck by a phrase on a+ /// slide rather than only by what somebody happened to call the file.+ var text: String?+ /// The still first-page render the thumbnailers use, as raw HTML.+ var preview: String?++ static let notADocument = Meta(isDocument: false, title: nil, app: nil,+ encrypted: false, text: nil, preview: nil)+ }++ // MARK: - Sniff++ /// Is this actually a Bento document, whatever it is called?+ static func isDocument(head: String) -> Bool {+ Array(head.utf16).firstIndex(ofSequence: Array(marker.utf16)) != nil+ }++ // MARK: - Describe++ /// Everything a listing needs, from bytes already in hand.+ ///+ /// The three windows are the caller's to cut, because they are byte slices+ /// of the file and this function only sees decoded text: `sniffHead` is the+ /// first `sniffBytes`, `head` the first `headBytes`, `whole` all of it (or+ /// nil when the caller has decided not to pay for the full read). The split+ /// mirrors the reference — the title is cheap and near the front, the+ /// preview sits a quarter of the way into a 900KB file and cannot be had+ /// from the head at all.+ ///+ /// An ENCRYPTED document deliberately yields no text and no preview. That is+ /// a privacy rule, not an optimisation: a plaintext title page beside the+ /// ciphertext is the leak the password exists to prevent, and prose lifted+ /// into a system-wide search index is that same leak with a longer reach.+ ///+ /// The shape — `isDocument` folded in, everything else nil when it is false+ /// — is the SHARED contract in `tray/fixtures/README.md`, not this host's+ /// choice. `tray/webext`'s `describe()` never faces a non-document because+ /// its caller sniffs first; a port that answers all the questions in one+ /// call does, and has to say so.+ static func describe(head: String, sniffHead: String, whole: String?) -> Meta {+ guard isDocument(head: sniffHead) else { return .notADocument }+ let headU = Array(head.utf16)+ let encrypted = isEncrypted(headU)+ var meta = Meta(isDocument: true,+ title: title(headU).flatMap { $0.isEmpty ? nil : $0 },+ app: app(headU),+ encrypted: encrypted,+ text: nil,+ preview: nil)+ guard !encrypted, let whole else { return meta }+ let wholeU = Array(whole.utf16)+ meta.preview = previewSlice(wholeU)+ meta.text = extractText(wholeU)+ return meta+ }++ // MARK: - The words a document actually contains++ /// Search used to cover the title, the file name and the folder — which+ /// finds a deck you can already name. What you usually remember is a phrase+ /// ON a slide, and the bytes to answer that were already read for the+ /// thumbnail and then thrown away.+ ///+ /// Deliberately NOT a JSON parse. The document block runs to megabytes with+ /// images inline, every app shapes it differently (slides put prose in+ /// `element.html`, spaces in blocks, dash in cells), and a parser that has+ /// to know the format is a parser that breaks when the format moves. Pulling+ /// string VALUES out — `:"…"`, never keys — is format-agnostic and degrades+ /// to "finds less" rather than "throws".+ ///+ /// Data URIs go first: one embedded image is bigger than every word in the+ /// document, and they would dominate both the work and the budget.+ static func extractText(_ html: [UInt16]) -> String? {+ guard let start = html.firstIndex(ofSequence: Array(marker.utf16)) else { return nil }+ guard let end = html.firstIndex(ofSequence: Array("</script>".utf16), from: start) else { return nil }++ let block = stripDataURIs(Array(html[start..<end]))++ var out: [UInt16] = []+ var size = 0+ var i = 0+ let n = block.count+ while i + 1 < n {+ guard block[i] == .colon, block[i + 1] == .quote else { i += 1; continue }+ guard let close = matchJSONValue(block, from: i + 2, maxReps: 400, minReps: 1) else {+ i += 1+ continue+ }+ let value = block[(i + 2)..<close]+ if hasRunOfLetters(value, 3) {+ if !out.isEmpty { out.append(.space) } // the reference's join(' ')+ out.append(contentsOf: value)+ size += value.count+ // The value is kept BEFORE the budget is checked, exactly as the+ // reference does — so the budget overshoots by up to one value+ // and then the final slice trims it back. Reproduced rather than+ // tidied: tidying it would change what the last few words are.+ if size > textBudget { break }+ }+ i = close + 1+ }++ let cleaned = collapseWhitespace(stripEntities(stripTags(out)))+ let trimmed = trimWhitespace(cleaned)+ if trimmed.isEmpty { return nil }+ return String(decoding: clampToBudget(trimmed), as: UTF16.self)+ }++ // MARK: - Head fields++ static func title(_ head: [UInt16]) -> String? {+ guard let raw = quotedValue(after: "\"title\"", in: head, maxReps: 200) else { return nil }+ return String(decoding: unescape(raw), as: UTF16.self)+ }++ static func app(_ head: [UInt16]) -> String? {+ // Every `"format"` is tried, not just the first. A regex looks for the+ // first position where the WHOLE pattern matches, so a `"format"` whose+ // value is not `bento/…` makes the reference keep scanning rather than+ // give up — stopping at the first key would disagree with it on any+ // document that carries an unrelated `format` field ahead of its own.+ firstQuotedValue(after: "\"format\"", in: head, maxReps: 400) { raw in+ let prefix = Array("bento/".utf16)+ guard raw.count > prefix.count, Array(raw[0..<prefix.count]) == prefix else { return nil }+ let rest = Array(raw[prefix.count...])+ // `[a-z]+` — lowercase only, and the whole remainder must be letters.+ guard !rest.isEmpty, rest.allSatisfy({ $0 >= .lowerA && $0 <= .lowerZ }) else { return nil }+ return String(decoding: rest, as: UTF16.self)+ }+ }++ static func isEncrypted(_ head: [UInt16]) -> Bool {+ let enc = Array("bento/enc".utf16)+ let found: Bool? = firstQuotedValue(after: "\"format\"", in: head, maxReps: 400) { raw in+ raw == enc ? true : nil+ }+ if found == true { return true }+ return head.firstIndex(ofSequence: Array("data-bento-enc".utf16)) != nil+ }++ /// The preview sits AFTER the document block and is bounded by the script+ /// that removes it, which is the same pair the thumbnailers rely on.+ static func previewSlice(_ whole: [UInt16]) -> String? {+ guard let start = whole.firstIndex(ofSequence: Array("<div data-bento-preview".utf16)) else { return nil }+ guard let end = whole.firstIndex(ofSequence: Array("<script data-bento-preview".utf16), from: start),+ end > start else { return nil }+ return String(decoding: whole[start..<end], as: UTF16.self)+ }++ // MARK: - Scanners+ //+ // Hand-written rather than NSRegularExpression, for two reasons that both+ // showed up as real divergences from the reference:+ //+ // * ICU's `\d` is Unicode Nd, so `&#\d+;` would swallow Arabic-Indic+ // digits that the reference leaves alone; ICU's `\s` is `\p{Z}`-based and+ // excludes U+FEFF, which JavaScript's `\s` includes.+ // * The value pattern `(?:[^"\\]|\\.){1,400}` is a backtracking shape over+ // a block that can be megabytes long.+ //+ // A single forward pass is both exactly specifiable and cheaper. Where the+ // reference relies on regex backtracking, the note above each scanner says+ // why the straight-line version is equivalent.++ /// `(?:[^"\\]|\\.){minReps,maxReps}"` starting at `p`, returning the index+ /// of the closing quote.+ ///+ /// Backtracking cannot change the answer here, which is why one pass is+ /// enough. `[^"\\]` cannot match a quote, so the greedy run only ever+ /// advances past positions that are NOT a quote; a quote can therefore only+ /// sit at the position where the run stops, never at an interior repetition+ /// boundary the engine could give back to. So if the run hits `maxReps`+ /// without a quote following it, every shorter alternative fails too, and+ /// the whole match fails — the reference then advances its start position by+ /// one, which is what the callers do.+ private static func matchJSONValue(_ s: [UInt16], from p: Int, maxReps: Int, minReps: Int) -> Int? {+ var j = p+ var reps = 0+ let n = s.count+ while reps < maxReps && j < n {+ let c = s[j]+ if c == .quote { break }+ if c == .backslash {+ // `\\.` — and `.` does not match a line terminator in either+ // language, so a backslash before one ends the run instead.+ guard j + 1 < n, !isLineTerminator(s[j + 1]) else { break }+ j += 2; reps += 1; continue+ }+ j += 1; reps += 1+ }+ guard reps >= minReps, j < n, s[j] == .quote else { return nil }+ return j+ }++ /// `"key"\s*:\s*"(value)"`, scanning every occurrence of the key.+ private static func quotedValue(after key: String, in s: [UInt16], maxReps: Int) -> [UInt16]? {+ firstQuotedValue(after: key, in: s, maxReps: maxReps) { $0 }+ }++ /// The same scan, but the caller decides whether a given value counts —+ /// which is what lets `app` and `isEncrypted` keep looking past a `"format"`+ /// that does not have the shape they want, exactly as a regex would.+ private static func firstQuotedValue<T>(after key: String, in s: [UInt16], maxReps: Int,+ accept: ([UInt16]) -> T?) -> T? {+ let k = Array(key.utf16)+ var from = 0+ while let at = s.firstIndex(ofSequence: k, from: from) {+ var j = skipWhitespace(s, at + k.count)+ if j < s.count, s[j] == .colon {+ j = skipWhitespace(s, j + 1)+ if j < s.count, s[j] == .quote,+ let close = matchJSONValue(s, from: j + 1, maxReps: maxReps, minReps: 0),+ let got = accept(Array(s[(j + 1)..<close])) {+ return got+ }+ }+ from = at + 1+ }+ return nil+ }++ /// `/data:[^"\\]{200,}/g` → a single space.+ ///+ /// Greedy with nothing following it, so it simply takes the maximal run and+ /// never backtracks. A run shorter than 200 is not a match, and the+ /// reference then resumes one character later — which can find a `data:`+ /// INSIDE the run it just rejected, so that is what happens here too.+ private static func stripDataURIs(_ s: [UInt16]) -> [UInt16] {+ let needle = Array("data:".utf16)+ var out: [UInt16] = []+ out.reserveCapacity(s.count)+ var i = 0+ var copied = 0+ while let at = s.firstIndex(ofSequence: needle, from: i) {+ var j = at + needle.count+ while j < s.count, s[j] != .quote, s[j] != .backslash { j += 1 }+ if j - (at + needle.count) >= 200 {+ out.append(contentsOf: s[copied..<at])+ out.append(.space)+ i = j+ copied = j+ } else {+ i = at + 1+ }+ }+ out.append(contentsOf: s[copied...])+ return out+ }++ /// `/<[^>]{1,200}>/g` → a single space. Same no-backtracking argument as the+ /// value scanner: `[^>]` cannot match `>`.+ private static func stripTags(_ s: [UInt16]) -> [UInt16] {+ var out: [UInt16] = []+ out.reserveCapacity(s.count)+ var i = 0+ while i < s.count {+ guard s[i] == .lt else { out.append(s[i]); i += 1; continue }+ var j = i + 1+ var reps = 0+ while reps < 200, j < s.count, s[j] != .gt { j += 1; reps += 1 }+ if reps >= 1, j < s.count, s[j] == .gt {+ out.append(.space)+ i = j + 1+ } else {+ out.append(s[i]); i += 1+ }+ }+ return out+ }++ /// `/&[a-z]+;|&#\d+;/gi` → a single space. `\d` is ASCII in JavaScript, so+ /// it is ASCII here — ICU's Unicode-Nd reading would eat digits the+ /// reference keeps.+ private static func stripEntities(_ s: [UInt16]) -> [UInt16] {+ var out: [UInt16] = []+ out.reserveCapacity(s.count)+ var i = 0+ while i < s.count {+ guard s[i] == .amp else { out.append(s[i]); i += 1; continue }+ var j = i + 1+ var reps = 0+ while j < s.count, isAsciiLetter(s[j]) { j += 1; reps += 1 }+ if reps >= 1, j < s.count, s[j] == .semi {+ out.append(.space); i = j + 1; continue+ }+ // The alternation is ordered, so the numeric form is only tried+ // once the named form has failed.+ if i + 1 < s.count, s[i + 1] == .hash {+ j = i + 2; reps = 0+ while j < s.count, isAsciiDigit(s[j]) { j += 1; reps += 1 }+ if reps >= 1, j < s.count, s[j] == .semi {+ out.append(.space); i = j + 1; continue+ }+ }+ out.append(s[i]); i += 1+ }+ return out+ }++ private static func collapseWhitespace(_ s: [UInt16]) -> [UInt16] {+ var out: [UInt16] = []+ out.reserveCapacity(s.count)+ var i = 0+ while i < s.count {+ if isJSWhitespace(s[i]) {+ out.append(.space)+ while i < s.count, isJSWhitespace(s[i]) { i += 1 }+ } else {+ out.append(s[i]); i += 1+ }+ }+ return out+ }++ private static func trimWhitespace(_ s: [UInt16]) -> [UInt16] {+ var a = 0, b = s.count+ while a < b, isJSWhitespace(s[a]) { a += 1 }+ while b > a, isJSWhitespace(s[b - 1]) { b -= 1 }+ return Array(s[a..<b])+ }++ /// `.slice(0, textBudget)` on UTF-16 units.+ ///+ /// ONE deliberate deviation from the reference, and the only one in this+ /// file. JavaScript will happily cut between a surrogate pair and hand back+ /// a lone surrogate; Swift cannot hold one, and decoding it yields U+FFFD.+ /// A trailing high surrogate is dropped instead. It costs the last half of+ /// one astral character in a document that happens to be exactly 40KB of+ /// prose long, and it avoids putting a replacement character into a search+ /// index. Written down because the fixture will show it as a one-unit+ /// length difference on such a document and it should read as a decision,+ /// not a bug.+ private static func clampToBudget(_ s: [UInt16]) -> [UInt16] {+ guard s.count > textBudget else { return s }+ var out = Array(s[0..<textBudget])+ if let last = out.last, last >= 0xD800, last <= 0xDBFF { out.removeLast() }+ return out+ }++ private static func unescape(_ s: [UInt16]) -> [UInt16] {+ var out: [UInt16] = []+ out.reserveCapacity(s.count)+ var i = 0+ while i < s.count {+ if s[i] == .backslash, i + 1 < s.count { out.append(s[i + 1]); i += 2 }+ else { out.append(s[i]); i += 1 }+ }+ return out+ }++ private static func skipWhitespace(_ s: [UInt16], _ from: Int) -> Int {+ var i = from+ while i < s.count, isJSWhitespace(s[i]) { i += 1 }+ return i+ }++ private static func hasRunOfLetters(_ s: ArraySlice<UInt16>, _ count: Int) -> Bool {+ var run = 0+ for c in s {+ if isAsciiLetter(c) {+ run += 1+ if run >= count { return true }+ } else {+ run = 0+ }+ }+ return false+ }++ // MARK: - Character classes++ private static func isAsciiLetter(_ c: UInt16) -> Bool {+ (c >= .upperA && c <= .upperZ) || (c >= .lowerA && c <= .lowerZ)+ }++ private static func isAsciiDigit(_ c: UInt16) -> Bool { c >= .zero && c <= .nine }++ private static func isLineTerminator(_ c: UInt16) -> Bool {+ c == 0x0A || c == 0x0D || c == 0x2028 || c == 0x2029+ }++ /// JavaScript's `\s`, written out. Notably it includes U+FEFF and U+00A0,+ /// which a `\p{Z}`-based class does not, and excludes U+200B, which people+ /// assume it contains. `markdown.ts` puts real NBSPs into documents, so this+ /// set is load-bearing rather than theoretical.+ private static func isJSWhitespace(_ c: UInt16) -> Bool {+ switch c {+ case 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x20, 0xA0, 0x1680,+ 0x2028, 0x2029, 0x202F, 0x205F, 0x3000, 0xFEFF:+ return true+ case 0x2000...0x200A:+ return true+ default:+ return false+ }+ }+}++// MARK: - UTF-16 helpers++private extension UInt16 {+ static let colon: UInt16 = 0x3A+ static let quote: UInt16 = 0x22+ static let backslash: UInt16 = 0x5C+ static let space: UInt16 = 0x20+ static let lt: UInt16 = 0x3C+ static let gt: UInt16 = 0x3E+ static let amp: UInt16 = 0x26+ static let semi: UInt16 = 0x3B+ static let hash: UInt16 = 0x23+ static let zero: UInt16 = 0x30+ static let nine: UInt16 = 0x39+ static let upperA: UInt16 = 0x41+ static let upperZ: UInt16 = 0x5A+ static let lowerA: UInt16 = 0x61+ static let lowerZ: UInt16 = 0x7A+}++extension Array where Element == UInt16 {+ /// `String.prototype.indexOf`, in the units the reference counts.+ func firstIndex(ofSequence needle: [UInt16], from: Int = 0) -> Int? {+ guard !needle.isEmpty, count >= needle.count else { return nil }+ let last = count - needle.count+ guard from <= last else { return nil }+ var i = Swift.max(0, from)+ while i <= last {+ var k = 0+ while k < needle.count, self[i + k] == needle[k] { k += 1 }+ if k == needle.count { return i }+ i += 1+ }+ return nil+ }+}diff --git a/tray/ios/Brand.swift b/tray/ios/Brand.swiftnew file mode 100644index 00000000..4fca9dc5--- /dev/null+++ b/tray/ios/Brand.swift@@ -0,0 +1,104 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors++import UIKit++/// The mark, the wordmark, and the four colours — in one place.+///+/// Everything here reads from `Assets.xcassets`, which is GENERATED from+/// `tray/assets/tray-icon.svg` by `tray/assets/make-icons.mjs`. Nothing in this+/// file contains a hex value, deliberately: a colour typed into Swift is a colour+/// that can quietly disagree with the logo, and the app would simply be the wrong+/// navy forever with nothing to notice it. `make-icons.mjs --check` fails if the+/// catalog drifts from the mark.+enum Brand {++ // MARK: - Palette++ /// Falling back to a system colour rather than a literal keeps the no-hex rule+ /// honest: if an asset is ever missing, the app looks plain rather than+ /// looking *nearly* right, which is the failure that hides.+ private static func named(_ name: String, fallback: UIColor) -> UIColor {+ UIColor(named: name) ?? fallback+ }++ static var navy: UIColor { named("BentoNavy", fallback: .label) }+ static var cream: UIColor { named("BentoCream", fallback: .systemBackground) }+ static var steel: UIColor { named("BentoSteel", fallback: .systemBlue) }+ static var peach: UIColor { named("BentoPeach", fallback: .systemOrange) }++ /// The accent for interactive chrome.+ ///+ /// Steel, not peach. Peach is the wordmark's slash and the icon's brightest+ /// block — it earns its attention by being rare, and spending it on every bar+ /// button makes it ordinary. Steel is the same family and reads as a control.+ static var accent: UIColor { steel }++ /// Navy is a brand colour, not a text colour: on a dark interface it is nearly+ /// the background. Chrome that must stay legible asks for this instead, which+ /// keeps navy in light mode and hands dark mode back to the system.+ static var ink: UIColor {+ UIColor { traits in+ traits.userInterfaceStyle == .dark ? .label : navy+ }+ }++ // MARK: - The mark++ /// The app's mark as a rounded tile.+ ///+ /// The asset is the ICON artwork, whose navy ground is a full-bleed square —+ /// correct there, because iOS applies its own squircle mask to app icons.+ /// Nothing masks it inside the app, so the rounding is applied here rather+ /// than by shipping a second, nearly-identical asset to maintain.+ static func markView(side: CGFloat) -> UIView {+ let view = UIImageView(image: UIImage(named: "BentoMark"))+ view.contentMode = .scaleAspectFit+ view.clipsToBounds = true+ view.layer.cornerRadius = side * 0.22 // matches the icon's 7/32+ view.layer.cornerCurve = .continuous+ view.translatesAutoresizingMaskIntoConstraints = false+ view.widthAnchor.constraint(equalToConstant: side).isActive = true+ view.heightAnchor.constraint(equalToConstant: side).isActive = true+ view.isAccessibilityElement = false // the wordmark beside it says the name+ return view+ }++ // MARK: - The wordmark++ /// `bento` + a peach slash + the app name, set to match the web editor's+ /// lockup: one weight throughout, the slash carrying the only colour.+ ///+ /// Rounded design, because the mark is all rounded rectangles and the system+ /// text face beside it looks like a different family. Scales with Dynamic Type+ /// rather than being pinned — a wordmark that ignores the reader's text size+ /// is a wordmark that looks broken at the sizes people actually use.+ static func wordmark(_ app: String = "home", style: UIFont.TextStyle = .title3) -> UILabel {+ let label = UILabel()+ let base = UIFont.preferredFont(forTextStyle: style)+ let size = base.pointSize+ let font = UIFont.systemFont(ofSize: size, weight: .bold)+ let rounded = font.fontDescriptor.withDesign(.rounded).map { UIFont(descriptor: $0, size: size) } ?? font++ let text = NSMutableAttributedString()+ text.append(NSAttributedString(string: "bento", attributes: [.font: rounded, .foregroundColor: ink]))+ text.append(NSAttributedString(string: "/", attributes: [.font: rounded, .foregroundColor: peach]))+ text.append(NSAttributedString(string: app, attributes: [.font: rounded, .foregroundColor: ink]))++ label.attributedText = text+ label.adjustsFontForContentSizeCategory = true+ // Read as one word, not as three fragments with a slash in the middle.+ label.accessibilityLabel = "bento \(app)"+ return label+ }++ /// Mark and wordmark together, for a screen that needs to say whose it is.+ static func lockup(_ app: String = "home", side: CGFloat = 28,+ style: UIFont.TextStyle = .title3) -> UIStackView {+ let stack = UIStackView(arrangedSubviews: [markView(side: side), wordmark(app, style: style)])+ stack.axis = .horizontal+ stack.alignment = .center+ stack.spacing = side * 0.32+ return stack+ }+}diff --git a/tray/ios/DocumentBrowserViewController.swift b/tray/ios/DocumentBrowserViewController.swiftindex 6db1f3eb..0090ff81 100644--- a/tray/ios/DocumentBrowserViewController.swift+++ b/tray/ios/DocumentBrowserViewController.swift@@ -13,9 +13,37 @@ final class DocumentBrowserViewController: UIDocumentBrowserViewController,delegate = selfallowsDocumentCreation = trueallowsPickingMultipleItems = false+ // The ONLY styling this screen gets. It is `UIDocumentBrowserViewController`+ // — Files, iCloud Drive, every File Provider on the device, drag-and-drop,+ // rename in place, favourites, tags — and keeping it as iOS designed it is+ // the decision (docs/DECISIONS.md, 2026-08-16), so it is not dressed up.+ // A tint on our own buttons is enough to say the app is ours; a branded+ // bar would fight the system chrome it sits in and win nothing.+ view.tintColor = Brand.accent+ // Search sits BESIDE the browser, never in place of it. The browser's+ // own field searches file names in whatever provider is being browsed;+ // this one searches what the documents say. See SearchViewController.+ additionalTrailingNavigationBarButtonItems = [+ UIBarButtonItem(image: UIImage(systemName: "text.magnifyingglass"),+ style: .plain, target: self, action: #selector(openSearch))+ ]}- /// A new document is seeded from the bundled starter shell.+ @objc private func openSearch() {+ let search = SearchViewController()+ search.onOpen = { [weak self] url in self?.openEditor(url) }+ let nav = UINavigationController(rootViewController: search)+ present(nav, animated: true)+ }++ /// Open a document the index found. The URL carries its own security scope+ /// (`FolderGrants.detach`), so it outlives the walk that discovered it.+ func openIndexed(_ url: URL) { openEditor(url) }++ /// A new document is fetched from the signed release channel — never bundled.+ ///+ /// The reasoning, the verification and the cache all live in `Releases`.+ /// What belongs here is the browser's own contract:////// The document is placed OURSELVES and handed back with `.none` ("already/// in its final location") rather than handing the browser a temp file to@@ -31,28 +59,99 @@ final class DocumentBrowserViewController: UIDocumentBrowserViewController,/// the name "Untitled.bento" plus extension "html" and inserts the/// counter before the last extension only. Ours reads "Untitled 2".///- /// The bundled seed is the only Bento version this app ships and it ages- /// harmlessly: a new document self-updates through the normal signed- /// channel the first time it checks.+ /// Unlike Android's `ACTION_CREATE_DOCUMENT`, nothing exists on disk until+ /// we put it there, so a failed fetch needs no clean-up — it just answers+ /// `nil` and no empty document is left behind.func documentBrowser(_ c: UIDocumentBrowserViewController,didRequestDocumentCreationWithHandler handler:@escaping (URL?, UIDocumentBrowserViewController.ImportMode) -> Void) {- guard let seed = Bundle.main.url(forResource: "starter", withExtension: "bento.html"),- let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first- else { handler(nil, .none); return }-- var dest = docs.appendingPathComponent("Untitled.bento.html")- var n = 2- while FileManager.default.fileExists(atPath: dest.path) {- dest = docs.appendingPathComponent("Untitled \(n).bento.html")- n += 1+ chooseApp { [weak self] app in+ guard let self, let app else { handler(nil, .none); return }+ self.create(app, handler)+ }+ }++ /// Which Bento. The list is aspirational on purpose — only slides has a+ /// published channel today, and an unreleased one says so plainly rather+ /// than being hidden, because adding an app to `Releases.apps` is meant to+ /// be the whole integration.+ private func chooseApp(_ done: @escaping (Releases.App?) -> Void) {+ let sheet = UIAlertController(title: "New document", message: nil, preferredStyle: .actionSheet)+ for app in Releases.apps {+ sheet.addAction(UIAlertAction(title: "\(app.label) — \(app.blurb)", style: .default) { _ in+ done(app)+ })}- do { try FileManager.default.copyItem(at: seed, to: dest) } catch { handler(nil, .none); return }+ sheet.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in done(nil) })+ sheet.popoverPresentationController?.sourceView = view+ sheet.popoverPresentationController?.sourceRect =+ CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)+ present(sheet, animated: true)+ }++ private func create(_ app: Releases.App,+ _ handler: @escaping (URL?, UIDocumentBrowserViewController.ImportMode) -> Void) {+ let waiting = UIAlertController(title: nil, message: "Fetching \(app.label)…", preferredStyle: .alert)+ present(waiting, animated: true)++ Task { @MainActor in+ var failure: String?+ var bytes: Data?+ do {+ bytes = try await Releases.seed(for: app)+ } catch {+ failure = error.localizedDescription+ // Offline, or the server is down. A shell cached by an earlier+ // "New" is still a signed release — it was verified when it was+ // cached — so it is a sound fallback rather than a guess.+ bytes = Releases.anyCached(app)+ }++ // WAIT for the spinner to be fully gone before anything else is+ // presented. `dismiss` returns immediately and the alert is still+ // on screen through its animation; presenting the editor into that+ // window silently does nothing, which looked exactly like a failed+ // fetch — the document was created correctly and the app just sat+ // there. Same class of bug as the runloop hop below.+ await withCheckedContinuation { done in+ waiting.dismiss(animated: true) { done.resume() }+ }++ guard let bytes,+ let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first+ else {+ handler(nil, .none)+ self.report(failure ?? "Could not reach the release server, and nothing is cached yet.")+ return+ }++ var dest = docs.appendingPathComponent("Untitled.bento.html")+ var n = 2+ while FileManager.default.fileExists(atPath: dest.path) {+ dest = docs.appendingPathComponent("Untitled \(n).bento.html")+ n += 1+ }+ do { try bytes.write(to: dest, options: .atomic) } catch {+ handler(nil, .none)+ self.report("Could not write the new document.")+ return+ }++ handler(dest, .none)+ // Next runloop: the browser is mid-transition when the handler+ // returns, and presenting into that animation is how a present()+ // silently fails.+ DispatchQueue.main.async { [weak self] in self?.openEditor(dest) }+ }+ }- handler(dest, .none)- // Next runloop: the browser is mid-transition when the handler returns,- // and presenting into that animation is how a present() silently fails.- DispatchQueue.main.async { [weak self] in self?.openEditor(dest) }+ /// A refusal is worth saying out loud. A failed signature or hash check is+ /// the app protecting the reader, and silently doing nothing reads as a bug.+ private func report(_ message: String) {+ let alert = UIAlertController(title: "Could not create a document",+ message: message, preferredStyle: .alert)+ alert.addAction(UIAlertAction(title: "OK", style: .default))+ present(alert, animated: true)}/// Still implemented for documents imported from ELSEWHERE (dragged in,diff --git a/tray/ios/EditorViewController.swift b/tray/ios/EditorViewController.swiftindex e8ee0ed0..46fde0b2 100644--- a/tray/ios/EditorViewController.swift+++ b/tray/ios/EditorViewController.swift@@ -322,7 +322,7 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR// nothing at all, which is the worst possible failure for a save.//// Downloads land in the app's Documents folder, which is visible in Files- // under Bento Tray. A picker per save would be punishing for an app that+ // under bento/home. A picker per save would be punishing for an app that// saves often, and a download cannot overwrite the user's original anyway —// that is what the FSA path is for.diff --git a/tray/ios/FolderGrants.swift b/tray/ios/FolderGrants.swiftnew file mode 100644index 00000000..a3b497ab--- /dev/null+++ b/tray/ios/FolderGrants.swift@@ -0,0 +1,92 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors++import Foundation++/// Folders the reader has handed the app, kept across launches.+///+/// The document browser can open any single file the reader points at, but it+/// cannot ENUMERATE — and enumeration is what searching a library means. iOS+/// grants that through the document picker in folder mode, which returns a+/// security-scoped directory URL; a bookmark makes it survive a relaunch. It is+/// the same capability as `showDirectoryPicker` in `tray/webext` and+/// `ACTION_OPEN_DOCUMENT_TREE` on Android, and it is the only new permission+/// this feature needs.+///+/// Nothing here reads a document. Access is granted here and spent in+/// `LibraryIndex`, so the rules about WHAT gets read — encrypted documents are+/// never opened for text — live in one place next to the extractor rather than+/// being restated wherever a file is touched.+final class FolderGrants {+ static let shared = FolderGrants()++ private let key = "bento.tray.folder-grants"+ private var bookmarks: [Data] = []++ private init() {+ bookmarks = (UserDefaults.standard.array(forKey: key) as? [Data]) ?? []+ }++ /// Folder URLs, freshly resolved. A grant whose bookmark no longer resolves+ /// — the folder was deleted, or the provider that served it is gone — is+ /// dropped rather than reported: there is nothing the reader can do about it+ /// and an error about a folder they may have removed on purpose is noise.+ var folders: [URL] {+ var kept: [Data] = []+ var urls: [URL] = []+ for data in bookmarks {+ var stale = false+ guard let url = try? URL(resolvingBookmarkData: data,+ bookmarkDataIsStale: &stale) else { continue }+ // A stale bookmark still resolves; re-minting it needs the scope+ // open, which the indexer does on its next pass.+ kept.append(data)+ urls.append(url)+ }+ if kept.count != bookmarks.count {+ bookmarks = kept+ UserDefaults.standard.set(bookmarks, forKey: key)+ }+ return urls+ }++ var isEmpty: Bool { bookmarks.isEmpty }++ func add(_ url: URL) {+ // The picker hands back a scoped URL; the bookmark has to be minted+ // while that scope is open or it resolves to something unreadable.+ let scoped = url.startAccessingSecurityScopedResource()+ defer { if scoped { url.stopAccessingSecurityScopedResource() } }+ guard let data = try? url.bookmarkData() else { return }+ guard !folders.contains(where: { $0.standardizedFileURL == url.standardizedFileURL }) else { return }+ bookmarks.append(data)+ UserDefaults.standard.set(bookmarks, forKey: key)+ }++ /// Revoking a folder also drops what was indexed from it — see+ /// `LibraryIndex.forget(folder:)`. Leaving prose in the system index for a+ /// folder the reader has just withdrawn would be the opposite of what they+ /// asked for.+ func remove(_ url: URL) {+ var kept: [Data] = []+ for data in bookmarks {+ var stale = false+ if let resolved = try? URL(resolvingBookmarkData: data, bookmarkDataIsStale: &stale),+ resolved.standardizedFileURL == url.standardizedFileURL { continue }+ kept.append(data)+ }+ bookmarks = kept+ UserDefaults.standard.set(bookmarks, forKey: key)+ }++ /// Run `body` with every granted folder's security scope open, and close+ /// them all again afterwards however it exits.+ func withAccess<T>(_ body: ([URL]) throws -> T) rethrows -> T {+ let urls = folders+ var opened: [URL] = []+ for url in urls where url.startAccessingSecurityScopedResource() { opened.append(url) }+ defer { for url in opened { url.stopAccessingSecurityScopedResource() } }+ return try body(urls)+ }++}diff --git a/tray/ios/Info.plist b/tray/ios/Info.plistindex 67f21e00..9e0a3ad2 100644--- a/tray/ios/Info.plist+++ b/tray/ios/Info.plist@@ -2,7 +2,24 @@<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>- <key>CFBundleDisplayName</key><string>Bento Tray</string>+ <!--+ The wordmark IS the name: `bento/home`, matching the web editor's lockup and+ the search screen's. This drives the home-screen label, the document+ browser's title ("bento/home Recents") and the app's folder in Browse.++ The slash is deliberate and it is SAFE. A display name never becomes a path:+ the container on disk is addressed by uuid, and iOS renders this string in+ presentation contexts only. Checked on iOS 26 — home screen, browser title+ and the Browse hierarchy all show it verbatim, with nothing escaped or+ substituted. Do not "fix" it to "Bento Home" on the assumption that a slash+ in a name breaks something; it does not, and a title-case form is the one+ that is off-brand — the name is lowercase, always.++ In these places it is plain text, so the slash cannot be peach. Only the+ search screen draws the styled lockup (Brand.swift), which is the one screen+ that is ours rather than the system's.+ -->+ <key>CFBundleDisplayName</key><string>bento/home</string><!-- Must be present and must reference the build setting: without it the apphas no bundle id and `simctl install` refuses it ("Missing bundle ID"). --><key>CFBundleIdentifier</key><string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>@@ -14,7 +31,38 @@<key>LSSupportsOpeningDocumentsInPlace</key><true/><key>UISupportsDocumentBrowser</key><true/><key>UIFileSharingEnabled</key><true/>- <key>UILaunchScreen</key><dict/>+ <!--+ The launch screen. An empty dict here meant a plain system-white screen, so+ the app flashed white and then the document appeared — the one moment the app+ is guaranteed to be seen, spent saying nothing.++ Navy ground plus the mark, both named from Assets.xcassets so they are the+ same values the icon is drawn from (generated by tray/assets/make-icons.mjs).+ The mark carries its own navy ground, which melts into the background here and+ leaves the cream tray floating — the same silhouette as the app icon the user+ just tapped, which is the whole point of a launch screen.++ Note it is NOT a loading indicator: iOS renders this static, before any code+ runs, so nothing here can show progress. It exists to make the launch feel+ like the app rather than like a blank page.+ -->+ <key>UILaunchScreen</key>+ <dict>+ <key>UIColorName</key><string>BentoNavy</string>+ <key>UIImageName</key><string>BentoMark</string>+ <key>UIImageRespectsSafeAreaInsets</key><false/>+ </dict>+ <!--+ Light status bar over the navy launch ground. Without this the clock and+ battery render as dark content on a dark background and are nearly invisible+ for the length of the launch — measured on the first build of this screen.++ This key styles the LAUNCH only. `UIViewControllerBasedStatusBarAppearance`+ stays at its default of true, so once the app is up each view controller+ answers for itself again — which matters, because the editor hides the bar+ entirely on iPad and must keep that say.+ -->+ <key>UIStatusBarStyle</key><string>UIStatusBarStyleLightContent</string><key>CFBundleDocumentTypes</key><array><dict>diff --git a/tray/ios/LibraryIndex.swift b/tray/ios/LibraryIndex.swiftnew file mode 100644index 00000000..61914291--- /dev/null+++ b/tray/ios/LibraryIndex.swift@@ -0,0 +1,307 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors++import CoreSpotlight+import Foundation+import UniformTypeIdentifiers++/// One document, as the index knows it.+struct IndexedDocument: Codable {+ var bookmark: Data?+ var path: String+ var name: String+ var base: String+ var folder: String+ var title: String+ var app: String?+ var encrypted: Bool+ var text: String?+ var size: Int+ var modified: Date+}++/// Where a query matched, so a result can show the reader why it is a result.+struct SearchHit {+ var document: IndexedDocument+ /// A window of the document's own prose around the match, or nil when the+ /// match was on the title or the file name.+ var snippet: String?+}++/// The library: what is in the granted folders, and what those documents say.+///+/// The walk, the budgets and the caching all mirror `tray/webext`'s+/// `listDocuments`/`describe`, because the point of this feature is that a deck+/// is findable by a phrase on a slide on every host. `BentoIndex` is the shared+/// half — the part that reads bytes and decides what the words are — and it is+/// diffed against the extension's own copy by `scripts/test-tray-index.mjs`.+/// This file is the iOS half: where the files come from, when the work happens,+/// and where the answers go.+///+/// **The prose goes into CoreSpotlight**, which is what "the app contributes+/// nothing to search" was about. That is a deliberate reach beyond the app: the+/// reader's own device index gains the text of documents in folders they+/// granted. Two rules keep it honest — an encrypted document is never read for+/// text at all (`BentoIndex.describe` refuses), and revoking a folder deletes+/// everything indexed from it. Both are enforced here rather than described.+final class LibraryIndex {+ static let shared = LibraryIndex()++ /// The reference's budgets, so the two hosts list the same things.+ /// `maxDepth` is inclusive of the root, matching `depth > MAX_DEPTH`.+ private let maxDepth = 4+ private let maxDocs = 300+ private let maxSniffs = 400++ private let domain = "page.bento.tray.documents"+ private let queue = DispatchQueue(label: "page.bento.tray.index", qos: .utility)++ private(set) var documents: [IndexedDocument] = []+ private var cache: [String: IndexedDocument] = [:]+ private var indexing = false++ /// Fires on the main queue whenever `documents` changes.+ var onChange: (() -> Void)?++ private init() { load() }++ // MARK: - Query++ /// Title, file name, folder, and the document's own words.+ ///+ /// Deliberately the same four fields the extension searches. Ranking is by+ /// where the match landed rather than by score: a title match is what the+ /// reader meant if it exists, and prose matches are the long tail that make+ /// the feature worth having.+ func search(_ raw: String) -> [SearchHit] {+ let q = raw.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()+ guard !q.isEmpty else { return documents.map { SearchHit(document: $0, snippet: nil) } }++ var titled: [SearchHit] = []+ var named: [SearchHit] = []+ var prose: [SearchHit] = []+ for doc in documents {+ if doc.title.lowercased().contains(q) {+ titled.append(SearchHit(document: doc, snippet: nil))+ } else if doc.name.lowercased().contains(q) || doc.folder.lowercased().contains(q) {+ named.append(SearchHit(document: doc, snippet: nil))+ } else if let text = doc.text, let range = text.range(of: q, options: .caseInsensitive) {+ prose.append(SearchHit(document: doc, snippet: snippet(text, around: range)))+ }+ }+ return titled + named + prose+ }++ private func snippet(_ text: String, around range: Range<String.Index>) -> String {+ let pad = 60+ let start = text.index(range.lowerBound, offsetBy: -pad, limitedBy: text.startIndex) ?? text.startIndex+ let end = text.index(range.upperBound, offsetBy: pad, limitedBy: text.endIndex) ?? text.endIndex+ var out = String(text[start..<end])+ if start > text.startIndex { out = "…" + out }+ if end < text.endIndex { out += "…" }+ return out+ }++ // MARK: - Indexing++ /// Walk the granted folders and republish.+ ///+ /// `cache` and `documents` belong to the MAIN queue and the walk runs on a+ /// utility one, so the walk gets a SNAPSHOT of the cache and hands back a+ /// whole result to be installed. Reading the live dictionary from the+ /// background would race `forget(folder:)` — a revoke landing mid-walk is+ /// exactly when that happens, and a dictionary mutated during a read is a+ /// crash rather than a wrong answer.+ func reindex() {+ guard !indexing else { return }+ indexing = true+ let snapshot = cache+ queue.async { [weak self] in+ guard let self else { return }+ let (found, fresh) = FolderGrants.shared.withAccess { folders in+ self.walk(folders, cache: snapshot)+ }+ DispatchQueue.main.async {+ self.cache = fresh+ self.documents = found.sorted { $0.modified > $1.modified }+ self.save()+ self.donate(found)+ self.indexing = false+ self.onChange?()+ }+ }+ }++ private func walk(_ folders: [URL], cache: [String: IndexedDocument]) -> ([IndexedDocument], [String: IndexedDocument]) {+ var cache = cache+ var out: [IndexedDocument] = []+ // Reading is only free the first time. A granted home directory can hold+ // thousands of unrelated .html files, so the sniff budget is per pass+ // and documents named like ours never spend from it.+ var sniffs = maxSniffs+ let fm = FileManager.default++ for root in folders {+ guard out.count < maxDocs else { break }+ let keys: [URLResourceKey] = [.isDirectoryKey, .fileSizeKey, .contentModificationDateKey, .isRegularFileKey]+ guard let walker = fm.enumerator(at: root, includingPropertiesForKeys: keys,+ options: [.skipsHiddenFiles, .skipsPackageDescendants]) else { continue }+ let rootName = root.lastPathComponent+ while let url = walker.nextObject() as? URL {+ if out.count >= maxDocs { break }+ // `level` counts the root's own contents as 1, so this is the+ // reference's `depth > MAX_DEPTH` on a 0-based root.+ if walker.level > maxDepth + 1 { walker.skipDescendants(); continue }+ let values = try? url.resourceValues(forKeys: Set(keys))+ guard values?.isRegularFile == true else { continue }++ let name = url.lastPathComponent+ let named = name.range(of: #"\.bento\.html$"#, options: [.regularExpression, .caseInsensitive]) != nil+ let maybe = !named && name.range(of: #"\.html?$"#, options: [.regularExpression, .caseInsensitive]) != nil+ guard named || maybe else { continue }++ let size = values?.fileSize ?? 0+ let modified = values?.contentModificationDate ?? .distantPast+ let cacheKey = "\(url.path):\(size):\(modified.timeIntervalSince1970)"+ if let hit = cache[cacheKey] { out.append(hit); continue }++ if maybe {+ guard sniffs > 0 else { continue }+ sniffs -= 1+ guard let head = read(url, limit: BentoIndex.sniffBytes),+ BentoIndex.isDocument(head: head) else { continue }+ }++ guard let doc = describe(url, name: name, folder: rootName, size: size, modified: modified) else { continue }+ cache[cacheKey] = doc+ out.append(doc)+ }+ }+ return (out, cache)+ }++ private func describe(_ url: URL, name: String, folder: String, size: Int, modified: Date) -> IndexedDocument? {+ guard let data = try? Data(contentsOf: url, options: .mappedIfSafe) else { return nil }+ let head = String(decoding: data.prefix(BentoIndex.headBytes), as: UTF8.self)+ let sniffHead = String(decoding: data.prefix(BentoIndex.sniffBytes), as: UTF8.self)+ // The whole file is only decoded when the head says it is worth it. A+ // sniffed file has already proven it carries the marker; a named one has+ // not, and a 40MB video someone called `.html` should not be decoded to+ // find that out.+ guard BentoIndex.isDocument(head: sniffHead) else { return nil }+ let whole = String(decoding: data, as: UTF8.self)+ let base = name+ .replacingOccurrences(of: #"\.bento\.html$"#, with: "", options: [.regularExpression, .caseInsensitive])+ .replacingOccurrences(of: #"\.html?$"#, with: "", options: [.regularExpression, .caseInsensitive])+ let meta = BentoIndex.describe(head: head, sniffHead: sniffHead, whole: whole)+ // Minted HERE, inside the folder's open scope, because that is the only+ // moment it can be: a document inside a granted folder is readable only+ // while the FOLDER is scoped, and an editing session outlives this walk+ // by minutes. The bookmark is what lets the editor hold the file on its+ // own afterwards.+ return IndexedDocument(bookmark: try? url.bookmarkData(),+ path: url.path,+ name: name,+ base: base,+ folder: folder,+ // The file name is what a listing shows for a+ // document that never got a title of its own.+ // That is a listing decision, so it is made here+ // rather than inside the extractor.+ title: meta.title ?? base,+ app: meta.app,+ encrypted: meta.encrypted,+ text: meta.text,+ size: size,+ modified: modified)+ }++ private func read(_ url: URL, limit: Int) -> String? {+ guard let handle = try? FileHandle(forReadingFrom: url) else { return nil }+ defer { try? handle.close() }+ guard let data = try? handle.read(upToCount: limit) else { return nil }+ return String(decoding: data, as: UTF8.self)+ }++ // MARK: - CoreSpotlight++ private func donate(_ docs: [IndexedDocument]) {+ let items: [CSSearchableItem] = docs.map { doc in+ let attrs = CSSearchableItemAttributeSet(contentType: UTType.html)+ attrs.title = doc.title+ attrs.displayName = doc.title+ attrs.contentURL = URL(fileURLWithPath: doc.path)+ // The whole point: the document's own prose, searchable from the+ // system. Encrypted documents carry nil here because nothing was+ // ever extracted from them.+ attrs.textContent = doc.text+ attrs.contentDescription = doc.encrypted+ ? "Encrypted Bento document"+ : (doc.text.map { String($0.prefix(200)) } ?? doc.folder)+ attrs.keywords = [doc.app, "bento"].compactMap { $0 }+ return CSSearchableItem(uniqueIdentifier: doc.path,+ domainIdentifier: domain,+ attributeSet: attrs)+ }+ guard !items.isEmpty else { return }+ CSSearchableIndex.default().indexSearchableItems(items) { error in+ if let error { NSLog("spotlight index failed: %@", String(describing: error)) }+ }+ }++ /// Drop a folder's documents from both the local list and the system index.+ func forget(folder: URL) {+ let name = folder.lastPathComponent+ let prefix = folder.standardizedFileURL.path+ let gone = documents.filter { $0.path.hasPrefix(prefix) || $0.folder == name }+ documents.removeAll { $0.path.hasPrefix(prefix) || $0.folder == name }+ cache = cache.filter { !$0.key.hasPrefix(prefix) }+ save()+ guard !gone.isEmpty else { return }+ CSSearchableIndex.default().deleteSearchableItems(withIdentifiers: gone.map(\.path)) { error in+ if let error { NSLog("spotlight delete failed: %@", String(describing: error)) }+ }+ onChange?()+ }++ /// Resolve a Spotlight result back to a document this app can open.+ func document(withIdentifier id: String) -> IndexedDocument? {+ documents.first { $0.path == id }+ }++ /// A URL carrying its own security scope, for opening outside the walk.+ func openableURL(for doc: IndexedDocument) -> URL? {+ if let data = doc.bookmark {+ var stale = false+ if let url = try? URL(resolvingBookmarkData: data, bookmarkDataIsStale: &stale) { return url }+ }+ // The bookmark can fail to resolve after the folder moved; the walk will+ // re-mint it, and in the meantime the raw path is still worth trying.+ return URL(fileURLWithPath: doc.path)+ }++ // MARK: - Persistence++ private var storeURL: URL? {+ guard let dir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first+ else { return nil }+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ return dir.appendingPathComponent("library-index.json")+ }++ private func load() {+ guard let url = storeURL, let data = try? Data(contentsOf: url),+ let saved = try? JSONDecoder().decode([IndexedDocument].self, from: data) else { return }+ documents = saved+ for doc in saved {+ cache["\(doc.path):\(doc.size):\(doc.modified.timeIntervalSince1970)"] = doc+ }+ }++ private func save() {+ guard let url = storeURL, let data = try? JSONEncoder().encode(documents) else { return }+ // The extracted prose is the reader's own document text; it stays inside+ // the app container with the same protection the documents themselves get.+ try? data.write(to: url, options: [.atomic, .completeFileProtectionUnlessOpen])+ }+}diff --git a/tray/ios/Releases.swift b/tray/ios/Releases.swiftnew file mode 100644index 00000000..459af821--- /dev/null+++ b/tray/ios/Releases.swift@@ -0,0 +1,343 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors++import CryptoKit+import Foundation++/// Where a NEW document comes from.+///+/// **Starter decks are never bundled.** They change often, and there are already+/// three apps with more coming — so a bundled seed means either picking one+/// arbitrarily or shipping several copies of Bento inside the app, each stale+/// from the moment it was built. Measured on the Android host before this+/// changed: the single bundled slides seed was 517,161 bytes, **81% of a+/// 630,851-byte release APK**. The `.ipa` was never measured, but it staged the+/// same 686KB shell.+///+/// So the shell is fetched from the same signed release channel a document uses+/// to update itself, which also means a document created here is the version+/// everyone else has, the same day.+///+/// THIS IS THE ONE THING THE HOST FETCHES. The app makes no other network+/// request — no update check of its own, no telemetry. `docs/PLATFORM.md` §1+/// requires no network to OPEN, EDIT, PRESENT or SAVE, and none of those touch+/// this; creating a document from a template is a different act, and+/// `tray/webext` draws the line in the same place. The result is cached, so only+/// the first "New" of a given release needs a connection.+///+/// VERIFICATION IS NOT OPTIONAL HERE. The bytes become an executable HTML+/// document on the user's own disk that they will afterwards trust, so an+/// unverified download lets a network attacker choose what they create. Both+/// halves are checked, exactly as `kernel/src/update.ts` does it: the manifest's+/// ECDSA signature, and then the shell's sha256 as pinned by the signed payload.+///+/// Deliberately a mirror of `tray/android`'s `Releases.kt` — same apps, same+/// key, same order of checks, same refusal messages — so the two hosts cannot+/// answer differently. Two details there were learned the hard way and are+/// inherited rather than rediscovered: the Accept header (see `fetch`), and the+/// signature being raw `r || s` rather than DER (see `verify`).+enum Releases {++ /// The apps a new document can be. Mirrors `APPS` in+ /// `tray/webext/src/library.js` and `Releases.kt`; adding one here is the+ /// whole integration, because nothing else in this app asks which Bento a+ /// document is.+ struct App: Equatable {+ let id: String+ let label: String+ let blurb: String+ var manifest: String { "https://bento.page/releases/\(id)/manifest.json" }+ }++ static let apps = [+ App(id: "slides", label: "Slides", blurb: "Presentations"),+ App(id: "spaces", label: "Spaces", blurb: "Notes and pages"),+ App(id: "dash", label: "Dash", blurb: "Data and sheets"),+ ]++ /// Release signing PUBLIC key, copied from `kernel/src/update.ts`. The+ /// private half lives offline with the maintainer. Rotating it orphans every+ /// previously shipped file, so the key is guarded rather than rotated.+ private static let keyX = "GMHSKwWcAoJVq-Dz1ZxWZM6TXATWIKbaQBpjoTystH8"+ private static let keyY = "flFNzbdXCmJN8RQYCeG71rBZnnbN-MCEnp1EbCLFrj0"++ private static let timeout: TimeInterval = 20++ struct Failed: LocalizedError {+ let message: String+ var errorDescription: String? { message }+ }++ // MARK: - The release++ struct Release {+ let version: String+ let url: String+ let sha256: String+ }++ /// Verify an envelope and pull out what a download needs — including that it+ /// is a release of the app we ASKED for.+ ///+ /// That last check is not redundant with the signature, and it was missing+ /// here until `tray/webext`'s own verification (PR #318) tested for it. Both+ /// a `bento-slides` manifest and a `bento-dash` one are genuinely signed by+ /// the same maintainer key, so serving the former on the latter's channel+ /// passes the signature AND the hash: every byte is authentic, just not the+ /// thing that was requested. Only identity catches a swap between two real+ /// releases. `tray/android` does not check this either — reported.+ static func release(from raw: String, for app: App, notBefore floor: String? = nil) throws -> Release {+ let payload = try verify(raw)++ // The payload names the app as `bento-<id>`.+ let want = "bento-\(app.id)"+ guard let named = payload["app"] as? String, named == want else {+ let got = (payload["app"] as? String) ?? "nothing"+ throw Failed(message: "the \(app.label) channel served a release for \(got) — refusing it")+ }+ guard let version = payload["version"] as? String, !version.isEmpty else {+ throw Failed(message: "the release server did not name a version")+ }+ guard let url = payload["url"] as? String, !url.isEmpty else {+ throw Failed(message: "the release server did not offer a build")+ }+ guard let sha = (payload["sha256"] as? String)?.lowercased(), !sha.isEmpty else {+ throw Failed(message: "the release is not pinned to a hash")+ }+ // ROLLBACK REPLAY. A stale but GENUINE manifest passes every check above+ // — signature, app identity, and the digest of the shell it points at,+ // because all of it really was signed and really does match. It just+ // hands over an older release, which is how someone who can re-serve but+ // not forge pins new documents to a version with a known hole in it.+ //+ // `kernel/src/update.ts` already refuses to go backwards; a host that+ // CREATES documents had no such floor, because it has no version of its+ // own to compare against. The floor is therefore the highest version+ // this device has already accepted for this app.+ //+ // The cost is honest and worth stating: a deliberate rollback by the+ // maintainer — pulling a bad release — is refused too, until the version+ // number moves past it. That is the same trade update.ts makes, so at+ // least the two agree.+ if let floor, isOlder(version, than: floor) {+ throw Failed(message: "the \(app.label) channel offered \(version), older than the \(floor) "+ + "this device already accepted — refusing it")+ }+ return Release(version: version, url: url, sha256: sha)+ }++ /// Dotted-numeric compare, enough for the versions this project mints. An+ /// unparsable component sorts as 0 rather than throwing: a strange version+ /// string should not be able to BLOCK an update, only fail to raise the floor.+ static func isOlder(_ a: String, than b: String) -> Bool {+ let x = a.split(separator: ".").map { Int($0.prefix(while: \.isNumber)) ?? 0 }+ let y = b.split(separator: ".").map { Int($0.prefix(while: \.isNumber)) ?? 0 }+ for i in 0..<max(x.count, y.count) {+ let l = i < x.count ? x[i] : 0+ let r = i < y.count ? y[i] : 0+ if l != r { return l < r }+ }+ return false+ }++ /// The highest version this device has accepted for `app`, if any.+ static func floor(for app: App) -> String? {+ UserDefaults.standard.string(forKey: "bento.tray.release-floor.\(app.id)")+ }++ private static func raiseFloor(_ app: App, to version: String) {+ if let current = floor(for: app), !isOlder(current, than: version) { return }+ UserDefaults.standard.set(version, forKey: "bento.tray.release-floor.\(app.id)")+ }++ // MARK: - The seed++ /// The current signed shell for `app`, from cache when we already have it.+ static func seed(for app: App) async throws -> Data {+ // Only slides has a published channel today; spaces and dash 404. Say so+ // rather than surfacing an HTTP code — the app list is aspirational on+ // purpose (adding an app here is the whole integration), so an unreleased+ // one is an expected answer, not a fault.+ let envelope: Data+ do {+ envelope = try await fetch(app.manifest)+ } catch let e as Failed where e.message.contains("404") {+ throw Failed(message: "\(app.label) has not been released yet")+ }++ let release = try release(from: String(decoding: envelope, as: UTF8.self),+ for: app, notBefore: floor(for: app))++ if let hit = cached(app, release.version) {+ raiseFloor(app, to: release.version)+ return hit+ }++ let shell = try await fetch(release.url)+ let got = SHA256.hash(data: shell).map { String(format: "%02x", $0) }.joined()+ // The signed payload pins this. A mismatch means the bytes are not the+ // release the maintainer signed, whatever the server said.+ guard got == release.sha256 else {+ throw Failed(message: "the downloaded app did not match its signed hash — refusing it")+ }++ // Only after the bytes have proven themselves. Raising the floor on a+ // manifest whose download then failed its hash would let a forged+ // manifest lock the device out of every real release below it.+ store(app, release.version, shell)+ raiseFloor(app, to: release.version)+ return shell+ }++ // MARK: - Crypto++ /// Verify the `{payload, sig}` envelope and return the parsed payload.+ ///+ /// The signature covers the EXACT payload string bytes — no canonicalisation,+ /// no re-serialisation. Parse it for reading only, never to re-encode and+ /// verify, or a byte-identical-looking round trip breaks the signature.+ ///+ /// `scripts/sign-release.mjs` signs through WebCrypto, which emits ECDSA+ /// signatures as RAW `r || s` — 64 bytes, two fixed-width integers.+ /// CryptoKit's `ECDSASignature(rawRepresentation:)` takes exactly that, so+ /// iOS needs no conversion. Noted because the Android host DOES: Java's+ /// `SHA256withECDSA` wants DER, and handing it the raw 64 bytes is simply a+ /// bad signature — silent, and indistinguishable from tampering. Anyone+ /// porting this a third time should check which their platform expects+ /// before concluding the manifest is broken.+ /// Internal rather than private so `scripts/test-tray-releases.mjs` can prove+ /// it REFUSES things. A verifier that has only ever been watched saying yes+ /// is indistinguishable from `return true`.+ static func verify(_ raw: String) throws -> [String: Any] {+ guard let data = raw.data(using: .utf8),+ let env = try? JSONSerialization.jsonObject(with: data) as? [String: Any]+ else { throw Failed(message: "the release manifest is not valid JSON") }++ let payloadField = env["payload"] as? String+ let sigField = env["sig"] as? String+ // An UNSIGNED manifest is refused as its own category, not as a parse+ // error. `{"url": …}` flat is exactly the shape the old broken reader+ // was reaching for, so saying "malformed" invites someone later to add a+ // lenient fallback for it as a compatibility gap. It is not a gap.+ if (payloadField ?? "").isEmpty && (sigField ?? "").isEmpty {+ throw Failed(message: "the release manifest is not signed — refusing it")+ }+ guard let payload = payloadField, !payload.isEmpty,+ let sig = sigField, !sig.isEmpty+ else { throw Failed(message: "the release manifest is malformed") }++ guard let x = b64url(keyX), let y = b64url(keyY),+ let key = try? P256.Signing.PublicKey(rawRepresentation: x + y)+ else { throw Failed(message: "the embedded release key is unusable") }++ guard let sigBytes = Data(base64Encoded: sig) ?? b64url(sig),+ let signature = try? P256.Signing.ECDSASignature(rawRepresentation: sigBytes),+ key.isValidSignature(signature, for: Data(payload.utf8))+ else { throw Failed(message: "the release manifest signature is INVALID — refusing it") }++ guard let parsed = try? JSONSerialization.jsonObject(with: Data(payload.utf8)) as? [String: Any]+ else { throw Failed(message: "the release payload is not valid JSON") }+ return parsed+ }++ private static func b64url(_ s: String) -> Data? {+ var t = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")+ while t.count % 4 != 0 { t += "=" }+ return Data(base64Encoded: t)+ }++ // MARK: - Net++ private static func fetch(_ url: String) async throws -> Data {+ guard url.hasPrefix("https://"), let u = URL(string: url) else {+ throw Failed(message: "the release server offered a non-HTTPS build")+ }+ var req = URLRequest(url: u, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,+ timeoutInterval: timeout)+ // ASK FOR BYTES, NOT A PAGE — and this header is LOAD-BEARING, not+ // belt-and-braces. Measured against the live server 2026-08-17:+ //+ // Accept: */* 689,316 bytes — matches the pin+ // Accept: text/html,…,*/*;q=0.8 689,675 bytes — does NOT+ //+ // Same URL, same `.bento.html` path, 359 bytes apart. The CDN injects a+ // Cloudflare analytics beacon before `</body>` when it believes the+ // response is a page being browsed, and the trigger is the ACCEPT+ // HEADER, not the extension — which is worth knowing precisely, because+ // if it were the path then no header would fix it for anyone.+ //+ // The injected file still carries an intact `id="bento-doc"`, so it+ // looks like a perfectly good document; only the hash tells them apart.+ // (An earlier note here said this had been fixed at the origin. It has+ // not — that was inherited second-hand and is wrong.)+ //+ // The hash check remains the actual defence: this header avoids a known+ // rewrite, it does not make the bytes trustworthy.+ req.setValue("*/*", forHTTPHeaderField: "Accept")+ req.setValue("no-store", forHTTPHeaderField: "Cache-Control")++ let (data, response) = try await URLSession.shared.data(for: req)+ guard let http = response as? HTTPURLResponse else {+ throw Failed(message: "the release server gave no answer")+ }+ guard (200...299).contains(http.statusCode) else {+ throw Failed(message: "the release server answered \(http.statusCode)")+ }+ return data+ }++ // MARK: - Cache++ /// Kept in Application Support, not Caches: this is what makes "New" work+ /// offline after the first time, so it should not evaporate under storage+ /// pressure the way a thumbnail happily can.+ private static func seedsDir() -> URL? {+ guard let dir = FileManager.default.urls(for: .applicationSupportDirectory,+ in: .userDomainMask).first?+ .appendingPathComponent("seeds") else { return nil }+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ return dir+ }++ private static func cacheFile(_ app: App, _ version: String) -> URL? {+ seedsDir()?.appendingPathComponent("\(app.id)-\(version).html")+ }++ private static func cached(_ app: App, _ version: String) -> Data? {+ guard let f = cacheFile(app, version), let d = try? Data(contentsOf: f), !d.isEmpty+ else { return nil }+ return d+ }++ private static func store(_ app: App, _ version: String, _ bytes: Data) {+ guard let f = cacheFile(app, version), let dir = seedsDir() else { return }+ do { try bytes.write(to: f, options: .atomic) } catch { return }+ // One release per app is enough to work offline; older ones are dead+ // weight the moment a newer one is cached.+ let others = (try? FileManager.default.contentsOfDirectory(at: dir,+ includingPropertiesForKeys: nil)) ?? []+ for other in others where other.lastPathComponent.hasPrefix("\(app.id)-")+ && other.lastPathComponent != f.lastPathComponent {+ try? FileManager.default.removeItem(at: other)+ }+ }++ /// The newest cached shell for `app`, whatever its version — the offline+ /// fallback when the release server cannot be reached at all. Sound rather+ /// than a guess: it was verified when it was cached.+ static func anyCached(_ app: App) -> Data? {+ guard let dir = seedsDir(),+ let files = try? FileManager.default.contentsOfDirectory(+ at: dir, includingPropertiesForKeys: [.contentModificationDateKey])+ else { return nil }+ let mine = files.filter { $0.lastPathComponent.hasPrefix("\(app.id)-") }+ let newest = mine.max { a, b in+ let da = (try? a.resourceValues(forKeys: [.contentModificationDateKey]))?+ .contentModificationDate ?? .distantPast+ let db = (try? b.resourceValues(forKeys: [.contentModificationDateKey]))?+ .contentModificationDate ?? .distantPast+ return da < db+ }+ return newest.flatMap { try? Data(contentsOf: $0) }+ }+}diff --git a/tray/ios/SceneDelegate.swift b/tray/ios/SceneDelegate.swiftindex c6c5d3f5..aa71526f 100644--- a/tray/ios/SceneDelegate.swift+++ b/tray/ios/SceneDelegate.swift@@ -1,6 +1,7 @@// SPDX-License-Identifier: MIT// Copyright (c) 2026 The Bento authors+import CoreSpotlightimport UIKitfinal class SceneDelegate: UIResponder, UIWindowSceneDelegate {@@ -18,6 +19,30 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {if let url = options.urlContexts.first?.url {DispatchQueue.main.async { [weak self] in self?.open(url) }}+ // …or a Spotlight result, which arrives as a user activity instead.+ for activity in options.userActivities where activity.activityType == CSSearchableItemActionType {+ DispatchQueue.main.async { [weak self] in self?.openSpotlight(activity) }+ }+ // The index is only as good as its last pass, and documents change+ // outside this app — that is the point of opening them in place.+ LibraryIndex.shared.reindex()+ }++ /// A result tapped in system Spotlight. The identifier is the one donated in+ /// `LibraryIndex.donate`, so it resolves through the index rather than being+ /// re-derived from a path that may since have moved.+ func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {+ openSpotlight(userActivity)+ }++ private func openSpotlight(_ activity: NSUserActivity) {+ guard activity.activityType == CSSearchableItemActionType,+ let id = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String,+ let browser = window?.rootViewController as? DocumentBrowserViewController+ else { return }+ guard let doc = LibraryIndex.shared.document(withIdentifier: id),+ let url = LibraryIndex.shared.openableURL(for: doc) else { return }+ browser.openIndexed(url)}/// WARM: the app is already running and the system hands it another file.diff --git a/tray/ios/SearchViewController.swift b/tray/ios/SearchViewController.swiftnew file mode 100644index 00000000..086f6c28--- /dev/null+++ b/tray/ios/SearchViewController.swift@@ -0,0 +1,230 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors++import UIKit+import UniformTypeIdentifiers++/// Find a document by something inside it.+///+/// This screen SITS BESIDE `UIDocumentBrowserViewController` rather than+/// replacing it, which is the whole shape of the decision in `docs/DECISIONS.md`+/// (2026-08-16). The browser is not a list — it is Files, iCloud Drive, every+/// File Provider on the device, drag-and-drop, rename in place, favourites and+/// tags — and none of that is worth trading for a search field. So the browser+/// stays the root and this is one button away from it, answering the one+/// question the browser cannot: which document was the one that said this?+final class SearchViewController: UIViewController {++ /// Handing the opening back rather than doing it here: the browser already+ /// knows how to open a document in place, and two code paths that open+ /// documents is how one of them ends up subtly different.+ var onOpen: ((URL) -> Void)?++ private let table = UITableView(frame: .zero, style: .insetGrouped)+ private let search = UISearchController(searchResultsController: nil)+ private let empty = UILabel()+ /// The mark and wordmark sit above the empty state's text. This is the one+ /// screen in the app that is OURS rather than the system's — the document+ /// browser is deliberately left as iOS designed it — so it is the right and+ /// only place to say whose app this is.+ private let brand = Brand.lockup("home", side: 34, style: .title2)+ private var hits: [SearchHit] = []++ override func viewDidLoad() {+ super.viewDidLoad()+ title = "Search"+ view.backgroundColor = .systemGroupedBackground+ view.tintColor = Brand.accent++ navigationItem.leftBarButtonItem = UIBarButtonItem(+ barButtonSystemItem: .close, target: self, action: #selector(close))+ navigationItem.rightBarButtonItem = UIBarButtonItem(+ image: UIImage(systemName: "folder.badge.plus"), style: .plain,+ target: self, action: #selector(folders))++ search.searchResultsUpdater = self+ search.obscuresBackgroundDuringPresentation = false+ search.searchBar.placeholder = "Title, file name, or a phrase inside"+ // A phrase from inside a document is not a sentence, and the keyboard+ // capitalising it is a small lie about what is being matched — the+ // search itself is case-insensitive either way.+ search.searchBar.autocapitalizationType = .none+ search.searchBar.autocorrectionType = .no+ navigationItem.searchController = search+ navigationItem.hidesSearchBarWhenScrolling = false+ definesPresentationContext = true++ table.dataSource = self+ table.delegate = self+ table.register(HitCell.self, forCellReuseIdentifier: "hit")+ table.translatesAutoresizingMaskIntoConstraints = false+ view.addSubview(table)++ empty.numberOfLines = 0+ empty.textAlignment = .center+ empty.textColor = .secondaryLabel+ empty.font = .preferredFont(forTextStyle: .callout)+ empty.adjustsFontForContentSizeCategory = true+ empty.translatesAutoresizingMaskIntoConstraints = false+ view.addSubview(empty)++ brand.translatesAutoresizingMaskIntoConstraints = false+ view.addSubview(brand)++ NSLayoutConstraint.activate([+ table.topAnchor.constraint(equalTo: view.topAnchor),+ table.leadingAnchor.constraint(equalTo: view.leadingAnchor),+ table.trailingAnchor.constraint(equalTo: view.trailingAnchor),+ table.bottomAnchor.constraint(equalTo: view.bottomAnchor),+ // The lockup and the text are one block, centred together: pinning the+ // text to the centre and hanging the mark above it drifts as Dynamic+ // Type changes the text's height.+ brand.centerXAnchor.constraint(equalTo: view.centerXAnchor),+ brand.bottomAnchor.constraint(equalTo: empty.topAnchor, constant: -20),+ empty.centerYAnchor.constraint(equalTo: view.centerYAnchor),+ empty.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40),+ empty.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40),+ ])++ LibraryIndex.shared.onChange = { [weak self] in self?.refresh() }+ refresh()+ LibraryIndex.shared.reindex()+ }++ private func refresh() {+ hits = LibraryIndex.shared.search(search.searchBar.text ?? "")+ table.reloadData()+ let granted = !FolderGrants.shared.isEmpty+ empty.isHidden = !hits.isEmpty+ brand.isHidden = !hits.isEmpty+ table.isHidden = hits.isEmpty+ empty.text = granted+ ? (search.isActive && !(search.searchBar.text ?? "").isEmpty+ ? "Nothing matches that."+ : "No Bento documents in the folders you have added yet.")+ // The permission is explained where it is asked for, not in a+ // settings screen nobody opens.+ : "Add a folder to search inside your documents.\n\nThe browser opens one file at a time; searching what a document SAYS means reading the folder it lives in."+ }++ @objc private func close() { dismiss(animated: true) }++ @objc private func folders() {+ let sheet = UIAlertController(title: "Folders", message: nil, preferredStyle: .actionSheet)+ sheet.addAction(UIAlertAction(title: "Add a folder…", style: .default) { [weak self] _ in+ self?.pickFolder()+ })+ for url in FolderGrants.shared.folders {+ sheet.addAction(UIAlertAction(title: "Remove “\(url.lastPathComponent)”", style: .destructive) { [weak self] _ in+ FolderGrants.shared.remove(url)+ LibraryIndex.shared.forget(folder: url)+ self?.refresh()+ })+ }+ sheet.addAction(UIAlertAction(title: "Cancel", style: .cancel))+ sheet.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem+ present(sheet, animated: true)+ }++ private func pickFolder() {+ let picker = UIDocumentPickerViewController(forOpeningContentTypes: [.folder], asCopy: false)+ picker.delegate = self+ picker.allowsMultipleSelection = false+ present(picker, animated: true)+ }+}++extension SearchViewController: UISearchResultsUpdating {+ func updateSearchResults(for searchController: UISearchController) { refresh() }+}++extension SearchViewController: UIDocumentPickerDelegate {+ func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {+ guard let url = urls.first else { return }+ FolderGrants.shared.add(url)+ refresh()+ LibraryIndex.shared.reindex()+ }+}++extension SearchViewController: UITableViewDataSource, UITableViewDelegate {+ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { hits.count }++ func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {+ let cell = tableView.dequeueReusableCell(withIdentifier: "hit", for: indexPath) as! HitCell+ cell.show(hits[indexPath.row], query: search.searchBar.text ?? "")+ return cell+ }++ func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {+ tableView.deselectRow(at: indexPath, animated: true)+ let doc = hits[indexPath.row].document+ guard let url = LibraryIndex.shared.openableURL(for: doc) else { return }+ dismiss(animated: true) { [weak self] in self?.onOpen?(url) }+ }+}++/// Title, where it lives, and — when the match was on the prose — the words+/// that matched, with the query itself picked out. A prose result that does not+/// show the phrase is indistinguishable from a wrong result.+private final class HitCell: UITableViewCell {+ private let titleLabel = UILabel()+ private let whereLabel = UILabel()+ private let snippetLabel = UILabel()++ override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {+ super.init(style: style, reuseIdentifier: reuseIdentifier)+ titleLabel.font = .preferredFont(forTextStyle: .body)+ whereLabel.font = .preferredFont(forTextStyle: .caption1)+ whereLabel.textColor = .secondaryLabel+ snippetLabel.font = .preferredFont(forTextStyle: .caption1)+ snippetLabel.textColor = .secondaryLabel+ snippetLabel.numberOfLines = 2+ for label in [titleLabel, whereLabel, snippetLabel] {+ label.adjustsFontForContentSizeCategory = true+ }+ let stack = UIStackView(arrangedSubviews: [titleLabel, whereLabel, snippetLabel])+ stack.axis = .vertical+ stack.spacing = 2+ stack.translatesAutoresizingMaskIntoConstraints = false+ contentView.addSubview(stack)+ NSLayoutConstraint.activate([+ stack.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8),+ stack.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8),+ stack.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor),+ stack.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor),+ ])+ accessoryType = .disclosureIndicator+ }++ required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }++ func show(_ hit: SearchHit, query: String) {+ let doc = hit.document+ titleLabel.text = doc.title+ var where_ = doc.folder+ if let app = doc.app { where_ += " · bento/\(app)" }+ if doc.encrypted { where_ += " · encrypted" }+ whereLabel.text = where_+ snippetLabel.isHidden = hit.snippet == nil+ snippetLabel.attributedText = hit.snippet.map { highlight($0, query: query) }+ // VoiceOver reads one sentence rather than three fragments.+ accessibilityLabel = [doc.title, where_, hit.snippet].compactMap { $0 }.joined(separator: ", ")+ }++ private func highlight(_ text: String, query: String) -> NSAttributedString {+ let out = NSMutableAttributedString(string: text)+ guard !query.isEmpty, let range = text.range(of: query, options: .caseInsensitive) else { return out }+ out.addAttributes([.foregroundColor: UIColor.label,+ .font: UIFont.preferredFont(forTextStyle: .caption1).bold()],+ range: NSRange(range, in: text))+ return out+ }+}++private extension UIFont {+ func bold() -> UIFont {+ guard let d = fontDescriptor.withSymbolicTraits(.traitBold) else { return self }+ return UIFont(descriptor: d, size: 0)+ }+}diff --git a/tray/ios/project.yml b/tray/ios/project.ymlindex e1ffa627..26d9ba11 100644--- a/tray/ios/project.yml+++ b/tray/ios/project.yml@@ -19,20 +19,13 @@ targets:# withExtension: "js")` finds it exactly as it did under Resources/.- path: ../bridge.jsbuildPhase: resources- preBuildScripts:- # The seed shell for "new document". Copied from the current build rather- # than committed: a 587KB binary in git would churn on every release, and- # the seed ages harmlessly anyway — a new deck self-updates through the- # normal signed channel the first time it checks.- - name: Stage starter shell- script: |- SRC="$SRCROOT/../../slides/dist-single/Bento_Slides.bento.html"- DST="$SRCROOT/Resources/starter.bento.html"- if [ -f "$SRC" ]; then- mkdir -p "$(dirname "$DST")" && cp "$SRC" "$DST"- elif [ ! -f "$DST" ]; then- echo "warning: no starter shell — run 'npm run build:single' in slides/; new-document creation will fail"- fi+ # NO starter shell is staged into the bundle. It used to be, and it was the+ # single largest thing in the app — the same seed measured 81% of the Android+ # release APK. New documents come from the signed release channel instead+ # (tray/ios/Releases.swift), which also means one created here is the version+ # everyone else has rather than whatever was current on build day. There are+ # three apps now and more coming; bundling meant picking one or shipping+ # several copies of Bento inside the app.settings:base:INFOPLIST_FILE: Info.plist