Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
spaces: a reading copy you can hand to someone who will not edit it (#668)
nyblnetaaf542a2de34
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 818e946b..f9a91475 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -178,6 +178,21 @@ jobs:--outfile="$RUNNER_TEMP/test-spaces-copytiers.mjs"node "$RUNNER_TEMP/test-spaces-copytiers.mjs"+ - name: Spaces reading-copy rig+ # "Save a reading copy…" is the file you hand to somebody who will not+ # edit it, and its whole value is in what the bytes do NOT contain. So+ # this asserts on the serialized document, not on "the strip function+ # ran": no room, no read key, no owner/writer/invite private key+ # anywhere in the text, no comment thread (page-level, block-level or+ # reply), no history, and the readonly flag set. Prev/Next follows the+ # tree's order. (The field-by-field key set and the mutation controls+ # are the copy-tier rig's.) (Bundled: share.ts imports the kernel+ # transport.)+ run: |+ slides/node_modules/.bin/esbuild scripts/test-spaces-reading.ts --bundle --platform=node --format=esm \+ --outfile="$RUNNER_TEMP/test-spaces-reading.mjs"+ node "$RUNNER_TEMP/test-spaces-reading.mjs"+- name: Spaces undo rig# Every checkpoint used to stringify the WHOLE document: measured on a# 200-page, 2.5 MB handbook, fifty edits left an undo depth of NINE,diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex a655dc8a..67bc798a 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -9879,3 +9879,53 @@ field that does not count as an edit. The kernel key is a superset of the oldone: theme, assets, fonts and undeclared keys now count as unsaved work. Thatis safe because the only comparison is snapshot against live after`keepLiveIdentity`, and no key is ever stored.++## 2026-10-10 — bento/spaces reading copies: the kernel's package tier, and a guarantee is removal not a flag++**Decision.** A space has TWO published shapes and no third. `doc.readonly` is a+SEALED reading copy (no session, opens in the reader); `collab.role:'reader'` is+a LIVE view-only copy (follows the room, cryptographically cannot write). Both+already existed in the format; "Save a reading copy…" (Share) is the button that+writes the first, and `spaces/src/reading.ts` is what it writes. A new+"published" field would be a second spelling of `readonly` that old files answer+only one of, so there is no fourth.++**It is built by the kernel's copy table, tier `package`** — slides'+presentation package, the same shape one app over. That row SETS `readonly`,+DROPS the capability block (no projection), drops the in-file history, drops+`template` and drops every top-level key this build does not declare. Not+`reader`: that tier keeps `collabForReader`'s room + read key, which is a live+viewer, the one thing a sealed copy must not be able to become. So there is no+`delete collab` and no hand strip list anywhere in spaces — the copy is built+without it. Comment threads (`Page.comments`, `Block.comments`) live inside+pages, which every tier keeps as content, so `reading.ts` removes them itself:+comments are workspace, not publication.++**`readonly: true` comes from the kernel.** The package tier's `{set}` mode rule+fires whether or not the source has the key (#666 — before it, a space with no+`readonly` key, which is almost every space, would have come out of the package+tier editable). `readingCopy` sets nothing by hand; `scripts/test-spaces-copytiers.ts`+asserts the flag on a source with NO readonly key.++**Which banner.** A live view-only copy can carry `readonly: true` too, so+`main.ts` asks about the reader role FIRST (the ordering from the field-classes+change) and only a `readonly` file with no reader role enters the sealed+reading view.++**The rule this exists to state.** `readonly` is INTENT and protects nothing —+the document block is plaintext by design, so a recipient can clear it. What a+reading copy guarantees is what is ABSENT from its bytes, and that holds+whatever opens the file, including a build that predates the flag (which opens+the space editable — the correct degradation). Any future work here must keep+saying which of its guarantees are cryptographic (no collab at all), which+format-level (no history, no comments, no undeclared key) and which cosmetic+(`readonly` and the hidden chrome), and must never present the third as the+first.++**Encrypted spaces inherit, deliberately.** A reading copy is written through+`serializeAuto`, so it stays encrypted with the same password and — via+`previewAllowed` — carries no file-manager still.++Assertions are on the SERIALIZED document: `scripts/test-spaces-reading.ts`+(bytes) and `scripts/test-spaces-copytiers.ts` (the exact key set, against the+hostile source, with three planted builders that must fail).diff --git a/docs/spaces-agents.md b/docs/spaces-agents.mdindex 54c27524..96a6880f 100644--- a/docs/spaces-agents.md+++ b/docs/spaces-agents.md@@ -930,8 +930,19 @@ rather than vanishing quietly at save time.- **Never write a page with an empty `blocks` array.** Nothing in it can take acaret, so it is a page nobody can type in. Give it `[{ "type": "p", "html":"" }]` — `bento.newPage()` does exactly that.-- `readonly: true` and a `policy` this build does not know both open **frozen**- — the file round-trips byte-exact and edits are refused.+- `readonly: true` marks a READING COPY: the file opens in the reader (no+ editing tools, no comment markers, a Previous/Next pair under each page) and+ `bento.readonly` is true, so every write returns `err: 'readonly'`. (A+ view-only copy that follows a live session — `collab.role: 'reader'` — may+ carry the flag too; it opens locked but stays the live viewer.) A `policy`+ this build does not know opens **frozen** for a different reason — we do not+ understand the file — and is likewise refused. In both cases the document+ round-trips byte-exact.+ `readonly` is INTENT, not a lock: the document block is plaintext, so anyone+ can clear the flag. What a reading copy actually guarantees is what it does+ not contain — no `collab` block (every room credential), no comment thread,+ no in-file version history and no top-level field the writing build did not+ declare.- A remote image `src` shows a placeholder until the reader asks for it. Embedthe bytes as an `asset:` instead — see **Images** above.- A shared space (its `collab` names a room) syncs between open copies, and adiff --git a/scripts/test-spaces-chrome.ts b/scripts/test-spaces-chrome.tsindex ec0e7e46..ecb57fb4 100644--- a/scripts/test-spaces-chrome.ts+++ b/scripts/test-spaces-chrome.ts@@ -907,6 +907,9 @@ async function browser(chrome: string, html: string): Promise<void> {for (const r of tr.parentElement.querySelector(':scope > .bkm-menu').querySelectorAll('.bkm-item')) add('menu', r.querySelector('.bkm-text')?.textContent || '')esc(); await sleep(60)}+ // the Share popover's actions (a popover of rows, not a kernel menu)+ const live = bar.querySelector('.sp-live')+ if (live && vis(live)) { live.click(); await sleep(120); for (const r of document.querySelectorAll('.sp-pop .sp-paction-name')) add('share', r.textContent); esc(); await sleep(80) }const more = document.querySelector('.sp-treelink.sp-here .sp-rowmore')if (more) { more.click(); await sleep(80); const m = [...document.querySelectorAll('.sp-mn-anchored .bkm-menu')].pop(); if (m) for (const r of m.querySelectorAll('.bkm-item')) add('page menu', r.querySelector('.bkm-text')?.textContent || ''); esc(); await sleep(60) }// the page list's + ▾ (a drawer on a phone: open it from the bar first)@@ -930,6 +933,8 @@ async function browser(chrome: string, html: string): Promise<void> {// per-page designs: the page's Design row, and its note under Save ▾if (!('Design' in now)) lost.push('Design (new member unreachable)')if (!('Export page as Markdown…' in now)) lost.push('Export page as Markdown… (new member unreachable)')+ // the sealed reading copy, from the Share popover+ if (now['Save a reading copy…'] !== 'share') lost.push(`Save a reading copy… (not in Share: ${now['Save a reading copy…']})`)ok(lost.length === 0, `at ${w}px every command reachable before is reachable now (${BEFORE[w].length} checked${lost.length ? '; LOST: ' + lost.join(', ') : ''})`)}diff --git a/scripts/test-spaces-copytiers.ts b/scripts/test-spaces-copytiers.tsindex c5cdd3e8..ee394685 100644--- a/scripts/test-spaces-copytiers.ts+++ b/scripts/test-spaces-copytiers.ts@@ -11,7 +11,8 @@// WHAT THIS PROVES. Every copy of a space that leaves the open document is built// by the kernel's copy table (kernel/src/docfields.ts projectForCopy) over this// app's exhaustive field map (spaces/src/docclass.ts). This rig runs each REAL-// builder — share.ts readerCopy / inviteCopy / duplicateAsNew, portable.ts+// builder — share.ts readerCopy / inviteCopy / duplicateAsNew, reading.ts+// readingCopy (the SEALED reading copy, tier 'package'), portable.ts// extractSpace, model.ts docForExport (Copy document JSON) and the 'file' tier// main.ts writes "Save a copy…" through — against ONE source carrying every// class of field: content, identity, both modes, a full collab with every@@ -24,6 +25,10 @@// · reader / Copy JSON (and audience / link / template, which spaces has no// builder for yet): no history, no undeclared key, no capability secret;// readonly SET on a reader copy, template dropped from it+// · sealed reading copy (package): NO collab at all — not even the room and+// read key a live viewer keeps; readonly SET even on a source with no+// readonly key (the kernel's package tier sets it, #666); no history, no+// undeclared key, no template, no comment thread// · invite: no undeclared key; history KEPT; the modes dropped// · duplicate / file: the undeclared key and the history KEPT//@@ -48,6 +53,7 @@ g.window = g.window ?? { localStorage: shim, addEventListener() {}, setTimeout,const { inviteCopy, readerCopy, duplicateAsNew } = await import('../spaces/src/share.ts')const { extractSpace } = await import('../spaces/src/portable.ts')+const { readingCopy, stripComments } = await import('../spaces/src/reading.ts')const { docForExport, FORMAT } = await import('../spaces/src/model.ts')const { SPACES_FIELDS } = await import('../spaces/src/docclass.ts')const { projectForCopy, collabForReader, COLLAB_READER_KEEP, COLLAB_INVITE_KEEP } = await import('../kernel/src/docfields.ts')@@ -197,6 +203,70 @@ function checkReader(out: SpacesDoc | null, label: string): boolean {ok(!passed && plantedFailed >= 3, `a reader builder that skips projectForCopy FAILS these checks (${plantedFailed} rows red)`)}+// ---------------------------------------------------------------------------+console.log('\nsealed reading copy — "Share → Save a reading copy…" (reading.ts readingCopy, tier package)')+{+ const EXPECT_SEALED = sorted([...CONTENT, 'docId', 'readonly'])+ const ROOM = (collab as Obj).room as string+ const KEY = (collab as Obj).key as string+ // the hostile source, with comment threads planted at both anchors+ const withComments = (d: SpacesDoc): SpacesDoc => {+ const o = clone(d)+ ;(o.pages[0] as Obj).comments = [{ id: 'c1', author: 'A', at: 'x', text: 'PAGE-COMMENT-CANARY' }]+ ;(o.pages[0].blocks[0] as Obj).comments = [{ id: 'c2', author: 'B', at: 'x', text: 'BLOCK-COMMENT-CANARY' }]+ return o+ }+ function checkSealed(out: SpacesDoc, label: string): boolean {+ const before = failures+ const o = out as Obj+ const text = JSON.stringify(o)+ ok(!('collab' in o), `${label}: NO collab key at all — not even the reader subset`)+ ok(!text.includes(ROOM) && !text.includes(KEY), `${label}: neither the room id nor the read key appears anywhere`)+ ok(o.readonly === true, `${label}: readonly:true (opens in the reading view)`)+ ok(!('revisions' in o) && !('trail' in o) && !text.includes('THE-WHOLE-SPACE'), `${label}: no history`)+ ok(!('futureField' in o), `${label}: the undeclared key is dropped`)+ ok(!('template' in o), `${label}: no template`)+ ok(same(keys(o), EXPECT_SEALED), `${label}: EXACT top-level keys (${show(o)})`)+ ok(!text.includes('COMMENT-CANARY'), `${label}: no comment thread, page- or block-level`)+ noSecrets(o, label)+ return failures === before+ }+ // the fixture carries NO readonly key: the package tier must set it anyway+ const bare = source() as Obj+ ok(!('readonly' in bare), 'premise: the hostile source has NO readonly key')+ checkSealed(readingCopy(withComments(source())), 'sealed (source with no readonly key)')+ checkSealed(readingCopy(withComments(source({ template: true }))), 'sealed of a template source')+ checkSealed(readingCopy(withComments(source({ readonly: false }))), 'sealed of a source with readonly:false')+ const src = withComments(source())+ const snap = JSON.stringify(src)+ readingCopy(src)+ ok(JSON.stringify(src) === snap, 'sealed: the open document is untouched')++ // NOT VACUOUS: three planted builders, each one of the ways this could+ // regress, must each FAIL the same checks.+ const planted: Array<[string, (d: SpacesDoc) => SpacesDoc]> = [+ // the app-side step forgotten: comment threads live inside pages, which+ // every tier keeps, so only stripComments takes them out+ ['forgets the comment threads', (d) => projectForCopy(clone(d), SPACES_FIELDS, 'package')],+ // the live viewer's tier: collab survives as collabForReader's room + key+ ['keeps collab (tier reader)', (d) => {+ const o = projectForCopy(clone(d), SPACES_FIELDS, 'reader'); stripComments(o); return o+ }],+ // no table at all: the shape #435 had, minus its collab strip+ ['skips projectForCopy', (d) => {+ const o = clone(d); o.readonly = true; stripComments(o); return o+ }],+ ]+ for (const [name, build] of planted) {+ const f0 = failures, c0 = checks+ console.log(` (planted builder that ${name} — these rows MUST fail:)`)+ const passed = checkSealed(build(withComments(source())), 'planted')+ const red = failures - f0+ failures = f0; checks = c0+ ok(!passed && red >= 1, `a sealed builder that ${name} FAILS these checks (${red} rows red)`)+ }+}+// ---------------------------------------------------------------------------console.log('\ninvite — "Share → invite to edit" (share.ts inviteCopy)'){@@ -314,6 +384,15 @@ console.log('\nevery builder routes through projectForCopy (source)')ok(/projectForCopy\(clone\(doc\), SPACES_FIELDS, 'reader'\)/.test(body(share, 'readerCopy')), 'readerCopy → tier reader')ok(/projectForCopy\(clone\(doc\), SPACES_FIELDS, 'invite', \{ invite \}\)/.test(body(share, 'inviteCopy')), 'inviteCopy → tier invite, with the freshly minted invite')ok(/projectForCopy\(clone\(doc\), SPACES_FIELDS, 'duplicate'\)/.test(body(share, 'duplicateAsNew')), 'duplicateAsNew → tier duplicate')+ ok(/projectForCopy\(clone\(doc\), SPACES_FIELDS, 'package'\)/.test(body(rd('reading.ts'), 'readingCopy')), 'readingCopy → tier package')+ {+ // a METHOD, so located by its own signature rather than body()'s `function`+ const ed = rd('editor.ts')+ const i = ed.indexOf('private async saveReadingCopy(')+ const m = i < 0 ? '' : ed.slice(i, ed.indexOf('\n }\n', i))+ ok(/const out = readingCopy\(this\.store\.doc\)/.test(m) && /onShareCopy\?\.\(out, 'reading'\)/.test(m),+ '"Save a reading copy…" writes readingCopy\'s output, and nothing else')+ }ok(/projectForCopy\(clone\(doc\), SPACES_FIELDS, 'duplicate'\)/.test(body(portable, 'extractSpace')), 'extractSpace → tier duplicate')ok(/return projectForCopy\(doc, SPACES_FIELDS, 'copyJSON'\)/.test(body(model, 'docForExport')), 'docForExport → tier copyJSON')ok(/docForExport\(h\.store\.doc\)/.test(body(cmds, 'copyJson')), 'Copy document JSON writes docForExport\'s output')diff --git a/scripts/test-spaces-model.ts b/scripts/test-spaces-model.tsindex 38fefb08..34c5b6a6 100644--- a/scripts/test-spaces-model.ts+++ b/scripts/test-spaces-model.ts@@ -951,7 +951,8 @@ for (const [label, input, err] of [ok(/const barActions: BarAction\[\]/.test(ed), 'the bar actions are declared as one typed list')ok(!/const menuActions: BarAction\[\]/.test(ed), '…and there is no second, ⋯-only list any more (its rows moved to Insert, Save, the bar and the page menu)')ok(/barActions\.map\(/.test(ed), '…the inline row is built from the bar list')- ok(/for \(const a of barActions\) row\(m,/.test(ed), '…and folded ⋯ is built from the same list')+ // (a sealed reading copy skips the eye inside that loop — still the one list)+ ok(/for \(const a of barActions\) \{?\s*(if \(this\.sealed && a\.icon === 'eye'\) continue\s*)?row\(m,/.test(ed), '…and folded ⋯ is built from the same list')ok(/saveList\(m\)/.test(ed) && /fill: saveList/.test(ed), '…and ends on the Save list, the same function the caret fills from')// WHICH TIER a rule lives in is the thing worth pinning — but the tiers arediff --git a/scripts/test-spaces-reading.ts b/scripts/test-spaces-reading.tsnew file mode 100644index 00000000..3daf45fc--- /dev/null+++ b/scripts/test-spaces-reading.ts@@ -0,0 +1,252 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/spaces reading-copy rig — what a published file carries, and what it must not.+//+// node scripts/test-spaces.mjs reading # or just: node scripts/test-spaces.mjs+//+// (Bundled, not run directly, for the same reason the invite rig is: the kernel+// transport reached through share.ts uses TypeScript parameter properties, which+// node's strip-only loader refuses. The runner above bundles it the way CI does.)+//+// WHAT THIS PROVES. "Save a reading copy…" is the button you press to hand a+// space to somebody who is not going to edit it — a colleague, a customer, the+// internet. The whole value of that button is in what the file does NOT contain,+// and every part of that is invisible in the product: the copy opens, reads and+// prints identically whether or not it still carries the owner key to the live+// room and every comment anyone left on the draft.+//+// So the assertions here are over the BYTES, never over "the strip function was+// called". `JSON.stringify(copy)` is not a proxy for the file: it is literally+// what `serializeAuto` writes into the `#bento-doc` block, so a full-text scan+// of it is a scan of the document a recipient opens in a text editor.+//+// THREE CATEGORIES, and the rig keeps them apart on purpose (reading.ts says+// why at length):+//+// CRYPTOGRAPHIC — `doc.collab` is gone, so the room, the symmetric read key+// and every private signing key are gone. The recipient cannot read the+// room's history, cannot write to it and cannot join it, because the+// material a socket must present is not in the file. (The kernel's copy+// table, tier `package`, builds the copy without it — the field-by-field+// key set and the mutation controls live in test-spaces-copytiers.ts.)+// FORMAT-LEVEL — comment threads are gone from the bytes, and so is the+// in-file version history.+// COSMETIC — `doc.readonly` itself. It is checked here as a FLAG that is+// set, and nothing in this file pretends it is a lock. Anyone can flip it.+//+// The last one is why the first two are asserted the way they are: a guarantee+// that survives someone editing the JSON is a guarantee about absent bytes, and+// only that.++// --- a browser, reduced to what the module graph touches at import time -----+// share.ts reaches the kernel's online transport, which reads localStorage for+// the relay-host override and the device key. Nothing here connects.+const store = new Map<string, string>()+const shim = {+ getItem: (k: string) => (store.has(k) ? store.get(k)! : null),+ setItem: (k: string, v: string) => { store.set(k, String(v)) },+ removeItem: (k: string) => { store.delete(k) },+ clear: () => store.clear(),+ key: (i: number) => [...store.keys()][i] ?? null,+ get length() { return store.size },+}+const g = globalThis as unknown as Record<string, unknown>+g.localStorage = shim+g.window = g.window ?? { localStorage: shim, addEventListener() {}, setTimeout, clearTimeout }+// node HAS a navigator (getter-only, no setter), so nothing is installed here:+// i18n reads `navigator.language` at import time and node's answers it. The+// reading copy's contents do not depend on a locale — English-as-key is the+// right answer in a rig — but the read must not throw.++const { readingCopy, isReadingCopy, readingNeighbours, stripComments } =+ await import('../spaces/src/reading.ts')+const { readerCopy, inviteCopy } = await import('../spaces/src/share.ts')+const { mintCollab } = await import('../kernel/src/sync/online.ts')+import type { SpacesDoc } from '../spaces/src/model.ts'++let failures = 0+let checks = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (cond) console.log(` ✓ ${msg}`)+ else { failures++; console.error(` ✗ ${msg}`) }+}++/** Text that could only have come from a comment thread. */+const PAGE_NOTE = 'PAGE-COMMENT-CANARY-do-not-publish'+const BLOCK_NOTE = 'BLOCK-COMMENT-CANARY-do-not-publish'+const REPLY_NOTE = 'REPLY-COMMENT-CANARY-do-not-publish'++/** A space with real credentials, real comments, and a bit of everything else. */+async function freshDoc(): Promise<SpacesDoc> {+ const collab = await mintCollab()+ return {+ format: 'bento/spaces',+ version: 1,+ docId: 'doc-under-test',+ title: 'Handbook',+ home: 'p1',+ theme: { background: '#fff', color: '#111', accent: '#F7A600', fontFamily: 'serif', measure: 720 },+ assets: { 'a1': 'data:image/png;base64,AAAA' },+ pages: [+ {+ id: 'p1',+ title: 'Home',+ blocks: [+ { id: 'b1', type: 'p', html: 'The onboarding process starts here.' },+ {+ id: 'b2', type: 'p', html: 'Second paragraph.',+ comments: [{+ id: 'c2', author: 'Dana', at: '2026-01-02T00:00:00Z', text: BLOCK_NOTE,+ replies: [{ id: 'c3', author: 'Sam', at: '2026-01-03T00:00:00Z', text: REPLY_NOTE }],+ }],+ },+ ],+ comments: [{ id: 'c1', author: 'Ali', at: '2026-01-01T00:00:00Z', text: PAGE_NOTE }],+ },+ { id: 'p2', title: 'Policies', parent: 'p1', blocks: [{ id: 'b3', type: 'p', html: 'Expenses.' }] },+ { id: 'p3', title: 'Travel', blocks: [{ id: 'b4', type: 'p', html: 'Book early.' }] },+ ],+ collab,+ // A field this build has never heard of. The FILE keeps it (format+ // additivity); a copy handed to someone else does not — the kernel's copy+ // table drops an undeclared key from every outward tier, so a future+ // secret cannot ride a reading copy before anyone has classified it.+ somethingFromTheFuture: { keep: 'me' },+ revisions: [{ id: 'r1', at: '2026-01-01T00:00:00Z', body: { draft: 'HISTORY-CANARY-old-draft' } }],+ trail: { '2026-01-01': { done: 1 } },+ } as unknown as SpacesDoc+}++// ---------------------------------------------------------------------------+console.log('\nthe premise: the OPEN document really does hold all of it')++const doc = await freshDoc()+const c = doc.collab!+const openText = JSON.stringify(doc)+ok(!!c.ownerPriv && !!c.key && !!c.room, 'a fresh space is minted with an owner key, a read key and a room')+ok(openText.includes(c.ownerPriv!) && openText.includes(c.key!) && openText.includes(c.room!),+ 'serializing the open document carries the owner key, the read key and the room id')+ok(openText.includes(PAGE_NOTE) && openText.includes(BLOCK_NOTE) && openText.includes(REPLY_NOTE),+ 'and it carries every comment, page-level, block-level and reply')++// ---------------------------------------------------------------------------+console.log('\na reading copy — CRYPTOGRAPHIC: none of the room material survives')++const copy = readingCopy(doc)+const text = JSON.stringify(copy)++// THE ASSERTIONS THIS RIG EXISTS FOR. Not "collab is undefined" — the whole+// serialized copy is scanned, so key material smuggled anywhere in the document+// (a stray backup under another name, a stamped sync blob that embeds it) fails+// too. That is the indirection hole this repo has shipped twice.+ok(!text.includes(c.ownerPriv!), 'the OWNER PRIVATE key appears NOWHERE in the bytes')+ok(!text.includes(c.owner!), 'nor the owner public key — the room id commits to it')+ok(!text.includes(c.key!), 'nor the symmetric READ key, which decrypts every frame the relay holds')+ok(!text.includes(c.room!), 'nor the room id, so there is nothing to connect to')+ok(copy.collab === undefined, 'doc.collab is absent outright, not emptied')++const withWriter = await freshDoc()+;(withWriter.collab as Record<string, unknown>).writerPriv = 'LEGACY-WRITER-PRIV-CANARY'+ok(!JSON.stringify(readingCopy(withWriter)).includes('LEGACY-WRITER-PRIV-CANARY'),+ 'a pre-v2 room-wide writerPriv goes too — deleting collab covers fields nobody remembered')++const invited = await inviteCopy(doc)+ok(!!invited?.collab?.invite?.priv, 'premise: an invite copy really does carry a delegation private key')+ok(!JSON.stringify(readingCopy(invited!)).includes(invited!.collab!.invite!.priv!),+ 'a reading copy taken FROM an invite copy carries no invite key either')++const viewer = readerCopy(doc)+ok(!!viewer?.collab?.key, 'premise: a view-only copy still holds the read key (it follows the room)')+const fromViewer = JSON.stringify(readingCopy(viewer!))+ok(!fromViewer.includes(viewer!.collab!.key!) && !fromViewer.includes(viewer!.collab!.room!),+ 'a reading copy taken FROM a view-only copy strips the room and the read key')++// ---------------------------------------------------------------------------+console.log('\na reading copy — FORMAT-LEVEL: the comments are not in the file')++ok(!text.includes(PAGE_NOTE), 'a page-level comment is absent from the bytes')+ok(!text.includes(BLOCK_NOTE), 'a block-level comment is absent from the bytes')+ok(!text.includes(REPLY_NOTE), 'a REPLY inside a thread is absent too — the whole thread goes')+ok(copy.pages[0].comments === undefined, 'Page.comments is deleted, not set to an empty array')+ok(copy.pages[0].blocks[1].comments === undefined, 'Block.comments is deleted, not emptied')+ok(!text.includes('HISTORY-CANARY') && !('revisions' in copy) && !('trail' in copy),+ 'the in-file version history (revisions, trail) is not in the file')++// ---------------------------------------------------------------------------+console.log('\na reading copy — COSMETIC: the flag, which protects nothing')++ok(copy.readonly === true, 'doc.readonly is set, so the app opens it as a document')+ok(isReadingCopy(copy) && !isReadingCopy(doc), 'isReadingCopy answers for the copy and not the original')+// Said out loud so nobody later reads this rig as proving a lock exists.+const unsealed = JSON.parse(text) as SpacesDoc+delete unsealed.readonly+ok(unsealed.readonly === undefined && JSON.stringify(unsealed).length < text.length,+ 'and a recipient can delete that flag from the JSON — it is intent, never enforcement')++// ---------------------------------------------------------------------------+console.log('\nthe document itself is all still there')++ok(copy.pages.length === 3, 'every page survives')+ok(text.includes('The onboarding process starts here.'), 'block content survives')+ok(text.includes('Second paragraph.'), 'a block that HAD a comment keeps its content')+ok(copy.title === 'Handbook' && copy.docId === doc.docId, 'title and docId are untouched (PLATFORM §3)')+ok(JSON.stringify(copy.theme) === JSON.stringify(doc.theme), 'the theme, measure included, is untouched')+ok(JSON.stringify(copy.assets) === JSON.stringify(doc.assets), 'assets ride along — a reading copy is self-contained')+ok(!('somethingFromTheFuture' in copy),+ 'an unknown top-level field does NOT leave in a copy for someone else (the kernel\'s fail-closed rule)')+ok(JSON.stringify((doc as Record<string, unknown>).somethingFromTheFuture) === '{"keep":"me"}',+ 'while the open document — and so the file — keeps it byte-identical (format additivity)')++const before = new Set(Object.keys(doc))+const after = new Set(Object.keys(copy))+const added = [...after].filter((k) => !before.has(k))+const removed = [...before].filter((k) => !after.has(k)).sort()+ok(added.length === 1 && added[0] === 'readonly',+ `exactly one top-level key is ADDED, and it is the flag (added: ${JSON.stringify(added)})`)+ok(JSON.stringify(removed) === JSON.stringify(['collab', 'revisions', 'somethingFromTheFuture', 'trail']),+ `the keys removed are collab, the history and the undeclared one (removed: ${JSON.stringify(removed)})`)++// ---------------------------------------------------------------------------+console.log('\nit is a copy, and it is idempotent')++ok(doc.collab !== undefined, 'the OPEN document still has its credentials afterwards')+ok(JSON.stringify(doc).includes(PAGE_NOTE), 'and still has its comments — nothing was mutated in place')+ok(JSON.stringify(readingCopy(copy)) === text, 'a reading copy of a reading copy is byte-identical')++// ---------------------------------------------------------------------------+console.log('\nreader navigation follows the tree, because doc.pages IS pre-order')++const n1 = readingNeighbours(copy, 'p1')+ok(n1.prev === undefined && n1.next?.id === 'p2', 'the first page has no previous, and p2 next')+const n2 = readingNeighbours(copy, 'p2')+ok(n2.prev?.id === 'p1' && n2.next?.id === 'p3', 'a child sits between its parent and the next root')+const n3 = readingNeighbours(copy, 'p3')+ok(n3.prev?.id === 'p2' && n3.next === undefined, 'the last page has no next')+ok(Object.keys(readingNeighbours(copy, 'nope')).length === 0, 'an unknown page id yields neither end')+{+ const arch = JSON.parse(text) as SpacesDoc+ arch.pages[1].archived = true+ const a = readingNeighbours(arch, 'p1')+ ok(a.next?.id === 'p3', 'an ARCHIVED page is skipped, as the sidebar leaves it out')+}+ok(Object.keys(readingNeighbours({ ...copy, pages: [copy.pages[0]] }, 'p1')).every((k) =>+ (readingNeighbours({ ...copy, pages: [copy.pages[0]] }, 'p1') as Record<string, unknown>)[k] === undefined),+ 'a one-page space has no navigation at all')++// ---------------------------------------------------------------------------+console.log('\nhand-written and half-built documents do not throw')++ok(JSON.stringify(readingCopy({ title: 'x' } as unknown as SpacesDoc)) === '{"title":"x","readonly":true}',+ 'a document with no pages array is sealed rather than crashed')+const noBlocks = { pages: [{ id: 'p', title: 'p' }] } as unknown as SpacesDoc+stripComments(noBlocks)+ok(true, 'a page with no blocks array survives stripComments')++// ---------------------------------------------------------------------------+console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) {+ console.error(`${failures} FAILED`)+ process.exit(1)+}diff --git a/scripts/test-spaces.mjs b/scripts/test-spaces.mjsindex da527fec..4bfed4f2 100755--- a/scripts/test-spaces.mjs+++ b/scripts/test-spaces.mjs@@ -66,6 +66,7 @@ const RIGS = [{ name: 'invite', file: 'scripts/test-spaces-invite.ts', bundle: true },{ name: 'copytiers', file: 'scripts/test-spaces-copytiers.ts', bundle: true },{ name: 'roundtrip', file: 'scripts/test-spaces-roundtrip.ts', bundle: true },+ { name: 'reading', file: 'scripts/test-spaces-reading.ts', bundle: true },{ name: 'md-strict', file: 'scripts/test-spaces-md-strict.ts', bundle: true },{ name: 'restore-gate', file: 'scripts/test-spaces-restore-gate.ts', bundle: true },{ name: 'mentions', file: 'scripts/test-spaces-mentions.ts' },diff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.mdindex 2933e475..8b26679a 100644--- a/spaces/CHANGELOG.md+++ b/spaces/CHANGELOG.md@@ -1270,6 +1270,34 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.the file, a duplicate and an invite, and never with a view-only copy, Copydocument JSON or a page export.+- **A space you can hand to a reader.** "Save a reading copy…" (in Share)+ writes a second file that opens as a **document** rather than as an editor:+ the pages, the tree, ⌘K search and print, and none of the machinery for+ changing them. The eye toggle is the same view for the file you are writing+ in — it now takes the tools away rather than merely switching them off, and+ every page carries a Previous / Next pair so a reader can go through a space+ without hunting the sidebar.++ What the copy leaves behind is the point, and it comes in three grades:++ - **Cryptographic.** No `collab` block at all, so the copy holds no room, no+ read key and no private signing key of any kind. Whoever you send it to+ cannot read the room, write to it or join it, because the material a+ connection must present is not in the file. Making the copy starts no live+ session either.+ - **Format-level.** Comment threads are gone from the bytes (page-level and+ block-level, replies included), and so is the version history kept in the+ file, and any field this build does not know.+ - **Cosmetic.** The reading-copy setting itself. It states what the file is+ and the app honours it; anyone can open the HTML and change it back. It is+ intent, never a lock.++ Old builds ignore the setting and open the space editable, which is the+ correct degradation: the guarantees that matter are bytes that are not in the+ file. A reading copy of a password-protected space is written encrypted with+ the same password, and carries no file-manager preview. A view-only copy that+ follows the live session still says so when it opens.+## [0.1.0] — 2026-08-03First release.diff --git a/spaces/src/collabui.ts b/spaces/src/collabui.tsindex 10876565..4b545b7a 100644--- a/spaces/src/collabui.ts+++ b/spaces/src/collabui.ts@@ -361,9 +361,20 @@ export class CollabUi {// "connecting" that reads as "off" sends people to fix a session that is// already dialling; a view-only copy that reads as "off" sends them to// press Start, which is the one thing that cannot help.+ // THE ONE EXPORT EVERY COPY CAN MAKE, so it is built once and offered+ // in every branch below — offline included. A reading copy carries no+ // room and no read key (reading.ts, the kernel's `package` tier), so it+ // needs no capability this copy might not hold, and it starts no session.+ const readingAct = () => this.action(ICONS.book, t('Save a reading copy…'),+ t('A sealed file for someone who will only read it: the pages with no editing tools, no comment threads, and none of this space’s keys — it never joins the live session.'),+ () => { close(); this.host.shareCopy('reading') })+if (st === 'offline') {pop.append(el('div', 'sp-pnote', t('Offline mode is on — nothing leaves this computer.')))pop.append(el('div', 'sp-pnote', t('Windows on this computer still sync; turn offline mode off in About to work with someone elsewhere.')))+ const only = el('div', 'sp-pacts')+ only.append(readingAct())+ pop.append(only)return}const status = el('div', 'sp-pstatus')@@ -380,11 +391,14 @@ export class CollabUi {}pop.append(status)- // A view-only copy holds no signing key, so there is nothing here it- // could do. Saying why is the point: the relay refuses its writes, and a- // person who does not know that will keep trying.+ // A view-only copy holds no signing key, so there is nothing else here+ // it could do. Saying why is the point: the relay refuses its writes, and+ // a person who does not know that will keep trying.if (!canWrite(doc)) {pop.append(el('div', 'sp-pnote', t('This is a view-only copy — it follows the live session but can’t change this space.')))+ const only = el('div', 'sp-pacts')+ only.append(readingAct())+ pop.append(only)return}@@ -394,10 +408,13 @@ export class CollabUi {: t('Nothing leaves this file until you start a session.')))}- // SHARING IS FILES. Each of these saves a copy to send, and turns the- // live session on — there is no separate start-a-session step.+ // SHARING IS FILES. Each of these saves a copy to send; the two that make+ // a LIVE copy turn the session on as they go, so there is no separate+ // start-a-session step. The reading copy is first because it is the one+ // that hands over nothing — and it is the only one that starts nothing.pop.append(el('div', 'sp-share-label', t('Share a copy')))const acts = el('div', 'sp-pacts')+ acts.append(readingAct())acts.append(this.action(ICONS.people, t('Invite to edit…'),t('Saves a copy to send. Whoever opens it edits this space live with you (end-to-end encrypted); you stay the owner and can remove them from the People list.'),() => { close(); this.host.shareCopy('invite') }))diff --git a/spaces/src/editor.ts b/spaces/src/editor.tsindex 1b779d2c..4c7fe224 100644--- a/spaces/src/editor.ts+++ b/spaces/src/editor.ts@@ -67,6 +67,7 @@ import { offlineEnabled } from '../../kernel/src/net.ts'import { withoutCaps } from '../../kernel/src/docfields.ts'import { startSharing } from '../../kernel/src/sync/online.ts'import * as shareModule from './share.ts'+import { readerNav, readingCopy } from './reading.ts'import { ICONS, type IconName } from './icons'import { barMenu, anchoredMenu, row, caption, extra, keys, type Menu } from './menus.ts'import { createTopbarFit, type TopbarFit } from './topbar.ts'@@ -184,6 +185,15 @@ export class Editor {private painting = false/** reading view: the document without the machinery for changing it */private reading = false+ /**+ * This FILE is a reading copy (`doc.readonly`), not a view someone toggled.+ *+ * The difference is whether there is anything to go back to. A reading view+ * is a mode you leave; a reading copy has no editing to return to, so the eye+ * and the ways to write this file go away entirely rather than sitting there+ * doing nothing. See reading.ts for what such a copy carries.+ */+ private sealed = false/*** The column ↑/↓ are aiming for, in viewport px, or null.*@@ -324,6 +334,11 @@ export class Editor {private build(): void {this.root.innerHTML = ''this.root.className = 'sp-app'+ // build() rewrites className outright, so the mode has to be re-applied or+ // anything that repaints the shell (About's onRepaint, a language change)+ // silently drops the reader back into the editor.+ if (this.reading) this.root.classList.add('sp-reading')+ if (this.sealed) this.root.classList.add('sp-sealed')const bar = el('header', 'sp-bar')// THE SUITE'S MARK, and the way into About — the same control slides has.@@ -424,7 +439,9 @@ export class Editor {const barActions: BarAction[] = [{ icon: 'eye', label: t('Reading view'),run: () => this.toggleReading(),- keep: (b) => { this.readB = b } },+ // named so a sealed copy can take it away: there is no editing to go+ // back to, so the eye is absent rather than inert (styles.css)+ keep: (b) => { this.readB = b; b.classList.add('sp-readtoggle') } },{ icon: 'graph', label: t('Graph'), run: () => this.openGraph() },{ icon: 'print', label: t('Export PDF (print)'), kbd: keys('mod', 'P'), run: () => this.openPrint() },]@@ -458,10 +475,14 @@ export class Editor {// order, then the Save list. The list SCROLLS (`scroll`): folded it is// taller than a phone, and its last rows are the ONLY way to save a// copy or export there.- row(m, { icon: ICONS.undo, label: t('Undo'), kbd: keys('mod', 'Z'), off: !this.store.canUndo,- run: () => { this.store.undo(); this.repaint() } })- row(m, { icon: ICONS.redo, label: t('Redo'), kbd: keys('shift', 'mod', 'Z'), off: !this.store.canRedo,- run: () => { this.store.redo(); this.repaint() } })+ // A SEALED reading copy has nothing to undo, set or go back to, so+ // those rows are absent here as their buttons are in the bar.+ if (!this.sealed) {+ row(m, { icon: ICONS.undo, label: t('Undo'), kbd: keys('mod', 'Z'), off: !this.store.canUndo,+ run: () => { this.store.undo(); this.repaint() } })+ row(m, { icon: ICONS.redo, label: t('Redo'), kbd: keys('shift', 'mod', 'Z'), off: !this.store.canRedo,+ run: () => { this.store.redo(); this.repaint() } })+ }// …then the insert group, folded: each family with variants under its// caption, the one-member kinds set apart by a rule (inserts.ts), and// Comment last, as the group ends in the bar@@ -474,8 +495,11 @@ export class Editor {row(m, { icon: ICONS.comment, label: t('Comment'), run: () => this.commentHere() })m.separator()}- row(m, { icon: ICONS.panelRight, label: t('Properties'), kbd: ']', run: () => this.toggleInsp() })- for (const a of barActions) row(m, { icon: ICONS[a.icon], label: a.label, kbd: a.kbd, run: a.run })+ if (!this.sealed) row(m, { icon: ICONS.panelRight, label: t('Properties'), kbd: ']', run: () => this.toggleInsp() })+ for (const a of barActions) {+ if (this.sealed && a.icon === 'eye') continue+ row(m, { icon: ICONS[a.icon], label: a.label, kbd: a.kbd, run: a.run })+ }// The globe's list, one tap further: a menu cannot hold a menu, so// the row opens the same list as its own popup (a sheet on a phone).const moreB = m.trigger@@ -661,7 +685,8 @@ export class Editor {* they saved.*/private toggleReading(force?: boolean): void {- this.reading = force ?? !this.reading+ // A sealed copy has one state, and it is this one.+ this.reading = this.sealed ? true : (force ?? !this.reading)this.root.classList.toggle('sp-reading', this.reading)this.readB?.classList.toggle('sp-on', this.reading)this.readB?.setAttribute('aria-pressed', String(this.reading))@@ -671,6 +696,20 @@ export class Editor {this.status(this.reading ? t('Reading view — press Esc or the eye to edit') : t('Editing'))}+ /**+ * This file was saved for reading — so open it as a document.+ *+ * Called once, from boot, for a `doc.readonly` file that is NOT a live+ * view-only copy (main.ts asks about the reader role first). The lock on the+ * store is separate and already applied (main.ts); this is the surface half.+ */+ enterReadingCopy(): void {+ this.sealed = true+ this.root.classList.add('sp-sealed')+ this.toggleReading(true)+ this.status('')+ }+/** Undo/redo must LOOK unavailable when they are, or they read as broken. *//** The dot on Save, and the only place the file's state is visible. */syncDirty(): void {@@ -1332,6 +1371,13 @@ export class Editor {// here" is a fact about the space, "what could have" is a suggestion, and// a suggestion above a fact reads as one.view.querySelector('.sp-page-inner')?.append(this.unlinked(page.id))+ // The reader's way through the space. Only in reading mode: an editor has+ // the sidebar, the gutters and ⌘K, and a pair of chapter links under every+ // page would be furniture in the way of the writing.+ if (this.reading) {+ const rnav = readerNav(s.doc, page.id, (id) => s.goToPage(id))+ if (rnav) view.querySelector('.sp-page-inner')?.append(rnav)+ }// Comments are EDITOR-ONLY. The gate is here rather than in comments.ts// because this is the object that knows which view it is in — and the// renderer, which print and the reading view share, has never heard of@@ -3621,7 +3667,7 @@ export class Editor {this.paintPage(); this.paintTree()return}- if (e.key === 'Escape' && this.reading && !this.overlay && !document.querySelector('.bkm-open')) { e.preventDefault(); this.toggleReading(false); return }+ if (e.key === 'Escape' && this.reading && !this.sealed && !this.overlay && !document.querySelector('.bkm-open')) { e.preventDefault(); this.toggleReading(false); return }if (this.overlay) return // the overlay owns the keyboard while it is open// A TABLE CELL IS NOT A BLOCK HOST, so the block keymap below does not@@ -6218,6 +6264,11 @@ export class Editor {* the room, which writes AND revokes, the inviter included.*/private async shareCopy(kind: import('./share.ts').ShareKind): Promise<void> {+ // A READING COPY IS SEALED, so it must not go live first — that is the one+ // thing the other two branches do that would be wrong here. Going live on+ // the way out would arm this space's session for a file that carries none+ // of its keys, which is a session nobody asked for.+ if (kind === 'reading') { await this.saveReadingCopy(); return }await this.goLive()// Committed first for the same reason slides commits its text edit: a// half-typed block that only exists in the DOM is not in the copy.@@ -6243,6 +6294,25 @@ export class Editor {}}+ /**+ * Save a copy for somebody who is only going to read it.+ *+ * A DERIVED document (reading.ts, the kernel's `package` tier), never+ * `store.doc`: the whole point is what the copy does not contain — no+ * collaboration credentials at all, no history and no comment threads. What+ * it DOES keep is the space itself, so the recipient gets the pages, the+ * search and the tree, and no editing tools. No sync stamp either: the copy+ * carries no collab block to stamp into.+ */+ private async saveReadingCopy(): Promise<void> {+ // Committed first for the same reason the share copies commit: a half-typed+ // block that only exists in the DOM is not in the copy.+ this.store.endRun()+ const out = readingCopy(this.store.doc)+ const ok = await this.onShareCopy?.(out, 'reading')+ if (ok) this.notice(t('Reading copy saved — it opens as a document, with no keys and no comments'))+ }+/** Turn the live session on (idempotent). Sharing a copy calls this first. */async goLive(): Promise<void> {if (!this.session || offlineEnabled()) returndiff --git a/spaces/src/i18n/de.ts b/spaces/src/i18n/de.tsindex a04c8a2b..073e007c 100644--- a/spaces/src/i18n/de.ts+++ b/spaces/src/i18n/de.ts@@ -942,4 +942,9 @@ export const de: Catalog = {"This page no longer uses a design of its own.": "Diese Seite verwendet keine eigene Gestaltung mehr.","{n} page(s) arrived with a design of their own.": "{n} Seite(n) kamen mit einer eigenen Gestaltung.","A page can wear a design of its own, and a section’s passes to the pages inside it: choose it from the page’s ⋯ menu.": "Eine Seite kann eine eigene Gestaltung tragen, und die eines Abschnitts gilt für die Seiten darin: Wähle sie im ⋯-Menü der Seite.",+ "A sealed file for someone who will only read it: the pages with no editing tools, no comment threads, and none of this space’s keys — it never joins the live session.": "Eine versiegelte Datei für alle, die sie nur lesen: die Seiten ohne Bearbeitungswerkzeuge, ohne Kommentar-Threads und ohne jeden Schlüssel dieses Space – sie tritt der Live-Sitzung nie bei.",+ "Next": "Weiter",+ "Previous": "Zurück",+ "Reading copy saved — it opens as a document, with no keys and no comments": "Lesekopie gespeichert – sie öffnet als Dokument, ohne Schlüssel und ohne Kommentare",+ "Save a reading copy…": "Lesekopie speichern…",}diff --git a/spaces/src/i18n/es.ts b/spaces/src/i18n/es.tsindex 0bd1dfeb..9f883e3f 100644--- a/spaces/src/i18n/es.ts+++ b/spaces/src/i18n/es.ts@@ -942,4 +942,9 @@ export const es: Catalog = {"This page no longer uses a design of its own.": "Esta página ya no usa un diseño propio.","{n} page(s) arrived with a design of their own.": "{n} página(s) llegaron con un diseño propio.","A page can wear a design of its own, and a section’s passes to the pages inside it: choose it from the page’s ⋯ menu.": "Una página puede tener un diseño propio, y el de una sección pasa a las páginas que contiene: elígelo en el menú ⋯ de la página.",+ "A sealed file for someone who will only read it: the pages with no editing tools, no comment threads, and none of this space’s keys — it never joins the live session.": "Un archivo sellado para quien solo va a leerlo: las páginas sin herramientas de edición, sin hilos de comentarios y sin ninguna de las claves de este espacio: nunca se une a la sesión en vivo.",+ "Next": "Siguiente",+ "Previous": "Anterior",+ "Reading copy saved — it opens as a document, with no keys and no comments": "Copia de lectura guardada: se abre como un documento, sin claves ni comentarios",+ "Save a reading copy…": "Guardar una copia de lectura…",}diff --git a/spaces/src/i18n/fr.ts b/spaces/src/i18n/fr.tsindex 02dddb5b..4e5af7c5 100644--- a/spaces/src/i18n/fr.ts+++ b/spaces/src/i18n/fr.ts@@ -942,4 +942,9 @@ export const fr: Catalog = {"This page no longer uses a design of its own.": "Cette page n’utilise plus de design qui lui soit propre.","{n} page(s) arrived with a design of their own.": "{n} page(s) sont arrivées avec un design qui leur est propre.","A page can wear a design of its own, and a section’s passes to the pages inside it: choose it from the page’s ⋯ menu.": "Une page peut avoir son propre design, et celui d’une section passe aux pages qu’elle contient : choisissez-le dans le menu ⋯ de la page.",+ "A sealed file for someone who will only read it: the pages with no editing tools, no comment threads, and none of this space’s keys — it never joins the live session.": "Un fichier scellé pour qui ne fera que le lire : les pages sans les outils d’édition, sans fils de commentaires et sans aucune des clés de cet espace — il ne rejoint jamais la session en direct.",+ "Next": "Suivant",+ "Previous": "Précédent",+ "Reading copy saved — it opens as a document, with no keys and no comments": "Copie de lecture enregistrée — elle s’ouvre comme un document, sans clés ni commentaires",+ "Save a reading copy…": "Enregistrer une copie de lecture…",}diff --git a/spaces/src/i18n/it.ts b/spaces/src/i18n/it.tsindex 0585096a..3bd036a4 100644--- a/spaces/src/i18n/it.ts+++ b/spaces/src/i18n/it.ts@@ -942,4 +942,9 @@ export const it: Catalog = {"This page no longer uses a design of its own.": "Questa pagina non usa più un design proprio.","{n} page(s) arrived with a design of their own.": "{n} pagina/e sono arrivate con un design proprio.","A page can wear a design of its own, and a section’s passes to the pages inside it: choose it from the page’s ⋯ menu.": "Una pagina può avere un design proprio, e quello di una sezione passa alle pagine che contiene: sceglilo dal menu ⋯ della pagina.",+ "A sealed file for someone who will only read it: the pages with no editing tools, no comment threads, and none of this space’s keys — it never joins the live session.": "Un file sigillato per chi lo leggerà soltanto: le pagine senza strumenti di modifica, senza thread di commenti e senza nessuna delle chiavi di questo spazio — non si unisce mai alla sessione dal vivo.",+ "Next": "Successivo",+ "Previous": "Precedente",+ "Reading copy saved — it opens as a document, with no keys and no comments": "Copia di lettura salvata — si apre come un documento, senza chiavi né commenti",+ "Save a reading copy…": "Salva una copia di lettura…",}diff --git a/spaces/src/i18n/ja.ts b/spaces/src/i18n/ja.tsindex 122228ee..1bfb76f8 100644--- a/spaces/src/i18n/ja.ts+++ b/spaces/src/i18n/ja.ts@@ -942,4 +942,9 @@ export const ja: Catalog = {"This page no longer uses a design of its own.": "このページは独自のデザインを使わなくなりました。","{n} page(s) arrived with a design of their own.": "{n} 件のページが独自のデザイン付きで取り込まれました。","A page can wear a design of its own, and a section’s passes to the pages inside it: choose it from the page’s ⋯ menu.": "ページは独自のデザインを持てます。セクションのデザインはその中のページに引き継がれます。ページの ⋯ メニューから選んでください。",+ "A sealed file for someone who will only read it: the pages with no editing tools, no comment threads, and none of this space’s keys — it never joins the live session.": "読むだけの人に渡す封をしたファイル:編集ツールもコメントスレッドもなく、このスペースの鍵も一切含みません — ライブセッションに参加することはありません。",+ "Next": "次へ",+ "Previous": "前へ",+ "Reading copy saved — it opens as a document, with no keys and no comments": "読むためのコピーを保存しました — 鍵もコメントもない、読むためのドキュメントとして開きます",+ "Save a reading copy…": "読むためのコピーを保存…",}diff --git a/spaces/src/i18n/packed.ts b/spaces/src/i18n/packed.tsindex 0f309385..4ef81a6b 100644--- a/spaces/src/i18n/packed.ts+++ b/spaces/src/i18n/packed.ts@@ -42,6 +42,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"A picture that lives on the web was left out — a deck never fetches.": ["ウェブ上にある画像は除きました — デッキは決して取得しません。","一张存放在网上的图片被略去了——演示文稿从不联网获取。","一張放在網路上的圖片被略過了——簡報從不連網取得。","Se dejó fuera una imagen alojada en la web: una presentación nunca descarga nada.","Une image hébergée sur le web a été laissée de côté — une présentation ne télécharge jamais rien.","Ein Bild aus dem Web wurde weggelassen – eine Präsentation lädt nie etwas nach.","Un’immagine che vive sul web è stata esclusa: una presentazione non scarica mai nulla.","Uma imagem que vive na web ficou de fora — uma apresentação nunca vai buscar nada."],"A precise grid, figures in a monospace, cobalt rules.": ["精密なグリッド、等幅の数字、コバルトの罫線。","精确的网格,等宽数字,钴蓝色分隔线。","精確的網格,等寬數字,鈷藍色分隔線。","Una retícula precisa, cifras en monoespaciada y filetes cobalto.","Une grille précise, des chiffres en chasse fixe, des filets cobalt.","Ein präzises Raster, Zahlen in Festbreitenschrift, kobaltblaue Linien.","Una griglia precisa, cifre a spaziatura fissa, filetti cobalto.","Uma grelha precisa, algarismos em monoespaçada, fios cobalto."],"A risograph zine: two spot inks, heavy capitals, offset shadows.": ["リソグラフのZINE:2色の特色インク、太い大文字、ずれた影。","孔版印刷小志:两种专色油墨、粗重大写、错位阴影。","孔版印刷小誌:兩種專色油墨、粗重大寫、錯位陰影。","Un fanzine en risografía: dos tintas planas, mayúsculas gruesas y sombras desplazadas.","Un fanzine en risographie : deux encres d’accompagnement, des capitales grasses, des ombres décalées.","Ein Risograph-Zine: zwei Schmuckfarben, fette Versalien, versetzte Schatten.","Una fanzine in risografia: due inchiostri spot, maiuscole pesanti, ombre sfalsate.","Um fanzine em risografia: duas tintas especiais, maiúsculas pesadas, sombras desfasadas."],+ "A sealed file for someone who will only read it: the pages with no editing tools, no comment threads, and none of this space’s keys — it never joins the live session.": ["読むだけの人に渡す封をしたファイル:編集ツールもコメントスレッドもなく、このスペースの鍵も一切含みません — ライブセッションに参加することはありません。","交给只阅读的人的封存文件:只有页面,没有编辑工具,没有评论线程,也不含本空间的任何密钥 — 它永远不会加入实时会话。","交給只閱讀的人的封存檔案:只有頁面,沒有編輯工具,沒有評論討論串,也不含本空間的任何金鑰 — 它永遠不會加入即時工作階段。","Un archivo sellado para quien solo va a leerlo: las páginas sin herramientas de edición, sin hilos de comentarios y sin ninguna de las claves de este espacio: nunca se une a la sesión en vivo.","Un fichier scellé pour qui ne fera que le lire : les pages sans les outils d’édition, sans fils de commentaires et sans aucune des clés de cet espace — il ne rejoint jamais la session en direct.","Eine versiegelte Datei für alle, die sie nur lesen: die Seiten ohne Bearbeitungswerkzeuge, ohne Kommentar-Threads und ohne jeden Schlüssel dieses Space – sie tritt der Live-Sitzung nie bei.","Un file sigillato per chi lo leggerà soltanto: le pagine senza strumenti di modifica, senza thread di commenti e senza nessuna delle chiavi di questo spazio — non si unisce mai alla sessione dal vivo.","Um ficheiro selado para quem só o vai ler: as páginas sem ferramentas de edição, sem tópicos de comentários e sem nenhuma das chaves deste espaço — nunca se junta à sessão ao vivo."],"A second file — the original is left alone": ["2 つ目のファイル — 元のファイルはそのまま","另存一个新文件 — 原文件不动","第二個檔案 — 原檔案不受影響","Un segundo archivo — el original queda intacto","Un second fichier — l’original reste intact","Eine zweite Datei — das Original bleibt unberührt","Un secondo file — l’originale resta intatto","Um segundo ficheiro — o original fica intacto"],"A sort here is newer than this build and was not applied.": ["このビューには、このバージョンより新しい並び順があり、適用されていません。","此视图中有比当前版本更新的排序方式,未被应用。","此檢視中有比目前版本更新的排序方式,未被套用。","Un orden de esta vista es más reciente que esta versión y no se ha aplicado.","Un tri de cette vue est plus récent que cette version et n’a pas été appliqué.","Eine Sortierung dieser Ansicht ist neuer als diese Version und wurde nicht angewendet.","Un ordinamento di questa vista è più recente di questa versione e non è stato applicato.","Uma ordenação desta vista é mais recente do que esta versão e não foi aplicada."],"A space needs at least one page": ["スペースには少なくとも 1 ページが必要です","空间至少要有一个页面","空間至少要有一個頁面","Un espacio necesita al menos una página","Un espace doit contenir au moins une page","Ein Space braucht mindestens eine Seite","Uno spazio deve avere almeno una pagina","Um espaço precisa de pelo menos uma página"],@@ -416,6 +417,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"New to Bento? Find templates, the gallery and the AI editing guide at {home} — or ⭐ it on {gh}.": ["Bento は初めてですか?テンプレート、ギャラリー、AI編集ガイドは {home} でどうぞ — {gh} で ⭐ もぜひ。","第一次用 Bento?在 {home} 查看模板、图库和 AI 编辑指南 — 也欢迎到 {gh} 点 ⭐。","第一次用 Bento?在 {home} 查看範本、圖庫和 AI 編輯指南 — 也歡迎到 {gh} 按 ⭐。","¿Nuevo en Bento? Encuentra plantillas, la galería y la guía de edición con IA en {home} — o dale ⭐ en {gh}.","Nouveau sur Bento ? Trouvez des modèles, la galerie et le guide d’édition par IA sur {home} — ou mettez une ⭐ sur {gh}.","Neu bei Bento? Vorlagen, die Galerie und den KI-Bearbeitungsleitfaden findest du auf {home} — oder gib ⭐ auf {gh}.","Nuovo su Bento? Trovi modelli, la galleria e la guida all’editing con IA su {home} — o metti una ⭐ su {gh}.","Novo no Bento? Encontre modelos, a galeria e o guia de edição com IA em {home} — ou dê uma ⭐ no {gh}."],"News serif": ["ニュース用セリフ","新闻衬线体","新聞襯線體","Serifa de periódico","Caractère de journal","Zeitungs-Serifenschrift","Graziato da quotidiano","Serifa de jornal"],"New… — page, journal, issue": ["新規… — ページ・ジャーナル・イシュー","新建… — 页面、日志、事项","新增… — 頁面、日誌、項目","Nuevo… — página, diario, incidencia","Nouveau… — page, journal, ticket","Neu… — Seite, Journal, Issue","Nuovo… — pagina, diario, issue","Novo… — página, diário, tarefa"],+ "Next": ["次へ","下一页","下一頁","Siguiente","Suivant","Weiter","Successivo","Seguinte"],"Next (⏎)": ["次へ (⏎)","下一个 (⏎)","下一個 (⏎)","Siguiente (⏎)","Suivant (⏎)","Weiter (⏎)","Successivo (⏎)","Seguinte (⏎)"],"Next month": ["次の月","下一月","下一月","Mes siguiente","Mois suivant","Nächster Monat","Mese successivo","Próximo mês"],"No Markdown files in that selection": ["選択に Markdown ファイルがありません","所选内容里没有 Markdown 文件","所選項目中沒有 Markdown 檔案","No hay archivos Markdown en esa selección","Aucun fichier Markdown dans cette sélection","Keine Markdown-Dateien in dieser Auswahl","Nessun file Markdown in questa selezione","Não há ficheiros Markdown nessa seleção"],@@ -497,6 +499,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Plays in the page": ["ページ内で再生します","在页面中播放","在頁面中播放","Se reproduce en la página","Se lit dans la page","Wird auf der Seite abgespielt","Si riproduce nella pagina","Reproduz na página"],"Poster": ["ポスター","封面图","封面圖","Póster","Affiche","Poster","Poster","Miniatura"],"Poster…": ["ポスター…","封面图…","封面圖…","Póster…","Affiche…","Poster…","Poster…","Miniatura…"],+ "Previous": ["前へ","上一页","上一頁","Anterior","Précédent","Zurück","Precedente","Anterior"],"Previous (⇧⏎)": ["前へ (⇧⏎)","上一个 (⇧⏎)","上一個 (⇧⏎)","Anterior (⇧⏎)","Précédent (⇧⏎)","Zurück (⇧⏎)","Precedente (⇧⏎)","Anterior (⇧⏎)"],"Previous month": ["前の月","上一月","上一月","Mes anterior","Mois précédent","Vorheriger Monat","Mese precedente","Mês anterior"],"Print or save as PDF": ["印刷または PDF として保存","打印或存为 PDF","列印或另存為 PDF","Imprimir o guardar como PDF","Imprimer ou enregistrer en PDF","Drucken oder als PDF speichern","Stampa o salva come PDF","Imprimir ou guardar como PDF"],@@ -510,6 +513,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Quotes": ["引用","引用","引用","Citas","Citations","Zitate","Citazioni","Citações"],"Read the release notes for v{v} (opens in a new tab)": ["v{v} のリリースノートを読む(新しいタブで開きます)","查看 v{v} 的发行说明(在新标签页中打开)","查看 v{v} 的發行說明(在新分頁中開啟)","Leer las notas de la versión v{v} (se abre en una pestaña nueva)","Lire les notes de version de la v{v} (s’ouvre dans un nouvel onglet)","Versionshinweise für v{v} lesen (öffnet einen neuen Tab)","Leggi le note di rilascio della v{v} (si apre in una nuova scheda)","Ler as notas de versão da v{v} (abre em uma nova aba)"],"Read-only copy saved — it follows the live session, view only": ["読み取り専用コピーを保存しました — ライブセッションに追従し、閲覧のみです","只读副本已保存——它跟随实时会话,仅供查看","唯讀副本已儲存——它跟隨即時工作階段,僅供檢視","Copia de solo lectura guardada — sigue la sesión en vivo, solo para ver","Copie en lecture seule enregistrée — elle suit la session en direct, en lecture seule","Nur-Lese-Kopie gespeichert — sie folgt der Live-Sitzung, nur zum Ansehen","Copia in sola lettura salvata — segue la sessione live, solo visualizzazione","Cópia somente leitura salva — ela acompanha a sessão ao vivo, apenas para visualizar"],+ "Reading copy saved — it opens as a document, with no keys and no comments": ["読むためのコピーを保存しました — 鍵もコメントもない、読むためのドキュメントとして開きます","阅读副本已保存 — 它作为文档打开,不含密钥和评论","閱讀副本已儲存 — 它會以文件形式開啟,不含金鑰與評論","Copia de lectura guardada: se abre como un documento, sin claves ni comentarios","Copie de lecture enregistrée — elle s’ouvre comme un document, sans clés ni commentaires","Lesekopie gespeichert – sie öffnet als Dokument, ohne Schlüssel und ohne Kommentare","Copia di lettura salvata — si apre come un documento, senza chiavi né commenti","Cópia de leitura guardada — abre como um documento, sem chaves e sem comentários"],"Reading file…": ["ファイルを読み込み中…","正在读取文件…","正在讀取檔案…","Leyendo el archivo…","Lecture du fichier…","Lese Datei…","Lettura del file…","A ler o ficheiro…"],"Reading image…": ["画像を読み込み中…","正在读取图片…","正在讀取圖片…","Leyendo la imagen…","Lecture de l’image…","Lese Bild…","Lettura dell’immagine…","A ler a imagem…"],"Reading view": ["閲覧ビュー","阅读视图","閱讀檢視","Vista de lectura","Mode lecture","Leseansicht","Vista di lettura","Modo de leitura"],@@ -569,6 +573,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Save": ["保存","保存","儲存","Guardar","Enregistrer","Speichern","Salva","Guardar"],"Save (⌘S)": ["保存 (⌘S)","保存 (⌘S)","儲存 (⌘S)","Guardar (⌘S)","Enregistrer (⌘S)","Speichern (⌘S)","Salva (⌘S)","Guardar (⌘S)"],"Save a copy…": ["コピーを保存…","保存副本…","儲存副本…","Guardar una copia…","Enregistrer une copie…","Kopie speichern…","Salva una copia…","Guardar uma cópia…"],+ "Save a reading copy…": ["読むためのコピーを保存…","保存阅读副本…","儲存閱讀副本…","Guardar una copia de lectura…","Enregistrer une copie de lecture…","Lesekopie speichern…","Salva una copia di lettura…","Guardar uma cópia de leitura…"],"Save an untouched copy…": ["元のままのコピーを保存…","另存副本,原文件不动…","儲存原封不動的副本…","Guardar una copia intacta…","Enregistrer une copie sans toucher à l’original…","Unveränderte Kopie speichern…","Salva una copia senza toccare l’originale…","Guardar uma cópia intacta…"],"Save as template": ["テンプレートとして保存","保存为模板","儲存為範本","Guardar como plantilla","Enregistrer comme modèle","Als Vorlage sichern","Salva come modello","Guardar como modelo"],"Save as… — copy, new space, password": ["別名で保存… — コピー・新しいスペース・パスワード","另存为… — 副本、新空间、密码","另存為… — 副本、新空間、密碼","Guardar como… — copia, espacio nuevo, contraseña","Enregistrer sous… — copie, nouvel espace, mot de passe","Speichern unter… — Kopie, neuer Space, Passwort","Salva come… — copia, nuovo spazio, password","Guardar como… — cópia, novo espaço, palavra-passe"],diff --git a/spaces/src/i18n/pt.ts b/spaces/src/i18n/pt.tsindex a247cd11..098a4a5f 100644--- a/spaces/src/i18n/pt.ts+++ b/spaces/src/i18n/pt.ts@@ -942,4 +942,9 @@ export const pt: Catalog = {"This page no longer uses a design of its own.": "Esta página já não usa um design próprio.","{n} page(s) arrived with a design of their own.": "{n} página(s) chegaram com um design próprio.","A page can wear a design of its own, and a section’s passes to the pages inside it: choose it from the page’s ⋯ menu.": "Uma página pode ter um design próprio, e o de uma secção passa às páginas dentro dela: escolha-o no menu ⋯ da página.",+ "A sealed file for someone who will only read it: the pages with no editing tools, no comment threads, and none of this space’s keys — it never joins the live session.": "Um ficheiro selado para quem só o vai ler: as páginas sem ferramentas de edição, sem tópicos de comentários e sem nenhuma das chaves deste espaço — nunca se junta à sessão ao vivo.",+ "Next": "Seguinte",+ "Previous": "Anterior",+ "Reading copy saved — it opens as a document, with no keys and no comments": "Cópia de leitura guardada — abre como um documento, sem chaves e sem comentários",+ "Save a reading copy…": "Guardar uma cópia de leitura…",}diff --git a/spaces/src/i18n/zh-Hans.ts b/spaces/src/i18n/zh-Hans.tsindex 8257ecb8..b20bc83a 100644--- a/spaces/src/i18n/zh-Hans.ts+++ b/spaces/src/i18n/zh-Hans.ts@@ -942,4 +942,9 @@ export const zh_Hans: Catalog = {"This page no longer uses a design of its own.": "此页面不再使用自己的设计。","{n} page(s) arrived with a design of their own.": "{n} 个页面带着自己的设计导入。","A page can wear a design of its own, and a section’s passes to the pages inside it: choose it from the page’s ⋯ menu.": "页面可以使用自己的设计,分区的设计会传给其中的页面:在页面的 ⋯ 菜单中选择。",+ "A sealed file for someone who will only read it: the pages with no editing tools, no comment threads, and none of this space’s keys — it never joins the live session.": "交给只阅读的人的封存文件:只有页面,没有编辑工具,没有评论线程,也不含本空间的任何密钥 — 它永远不会加入实时会话。",+ "Next": "下一页",+ "Previous": "上一页",+ "Reading copy saved — it opens as a document, with no keys and no comments": "阅读副本已保存 — 它作为文档打开,不含密钥和评论",+ "Save a reading copy…": "保存阅读副本…",}diff --git a/spaces/src/i18n/zh-Hant.ts b/spaces/src/i18n/zh-Hant.tsindex 61d7a97d..dc76495e 100644--- a/spaces/src/i18n/zh-Hant.ts+++ b/spaces/src/i18n/zh-Hant.ts@@ -942,4 +942,9 @@ export const zh_Hant: Catalog = {"This page no longer uses a design of its own.": "此頁面不再使用自己的設計。","{n} page(s) arrived with a design of their own.": "{n} 個頁面帶著自己的設計匯入。","A page can wear a design of its own, and a section’s passes to the pages inside it: choose it from the page’s ⋯ menu.": "頁面可以使用自己的設計,分區的設計會傳給其中的頁面:在頁面的 ⋯ 選單中選擇。",+ "A sealed file for someone who will only read it: the pages with no editing tools, no comment threads, and none of this space’s keys — it never joins the live session.": "交給只閱讀的人的封存檔案:只有頁面,沒有編輯工具,沒有評論討論串,也不含本空間的任何金鑰 — 它永遠不會加入即時工作階段。",+ "Next": "下一頁",+ "Previous": "上一頁",+ "Reading copy saved — it opens as a document, with no keys and no comments": "閱讀副本已儲存 — 它會以文件形式開啟,不含金鑰與評論",+ "Save a reading copy…": "儲存閱讀副本…",}diff --git a/spaces/src/main.ts b/spaces/src/main.tsindex 9faace1c..0f05efc3 100644--- a/spaces/src/main.ts+++ b/spaces/src/main.ts@@ -246,6 +246,13 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')if (!frozen && isReaderCopy(doc)) {banner(t('This is a view-only copy — it follows the live session but can’t change this space.'))} else if (!frozen && doc.readonly) {+ // A FILE SAVED FOR READING OPENS AS ONE. `doc.readonly` alone only locked+ // the store, so a reading copy arrived as the full editor with every+ // control inert — which reads as a broken editor rather than as a+ // document. reading.ts says what such a copy carries and what it does not.+ // (A live view-only copy may carry `readonly` too, which is why the role is+ // asked first: it follows the session, and it keeps the follows-live view.)+ editor.enterReadingCopy()banner(t('This is a reading copy. It opens for reading; nothing you do here changes the file.'))}if (frozen) {diff --git a/spaces/src/reading.ts b/spaces/src/reading.tsnew file mode 100644index 00000000..8c94d825--- /dev/null+++ b/spaces/src/reading.ts@@ -0,0 +1,202 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// The reading copy: a space handed to somebody who is only going to read it.+//+// THE PRODUCT DECISION. A space is already the whole artifact — the pages, the+// reader and the editor in one file — so "publishing" one has never needed a+// server. What it needed was a file you can hand over without also handing over+// the workspace: the editing tools, the half-finished conversations in the+// margins, and the keys to the live room.+//+// HOW MANY TIERS. bento/slides has three (docs/DECISIONS.md, "Signed writes /+// read-only tiers"): a presentation package, a live read-only viewer, and a+// writer. Spaces already carries all three shapes, and they were settled before+// this file existed:+//+// `doc.readonly` a SEALED file — no session, opens locked+// `collab.role: 'reader'` a LIVE viewer — follows the room, can never write+// (neither) a writer+//+// So this module adds NO tier. It builds the sealed one, which was declared in+// the format, honoured by `main.ts`, and reachable from no button in the app —+// the one property a sender could choose was the one they had to hand-edit the+// JSON to set. Adding a fourth ("published", say) would mean two fields meaning+// the same thing, and old files would answer only one of them.+//+// WHICH ROW OF THE KERNEL'S COPY TABLE. Every copy of a space is built by+// `projectForCopy` (kernel/src/docfields.ts) over this app's field map+// (docclass.ts), from an EMPTY object. The kernel's tier for a sealed,+// sessionless copy is `package` — slides' presentation package, the same shape+// one app over: `readonly` SET, the capability block DROPPED (not projected),+// the in-file history dropped, `template` dropped, and every top-level key this+// build does not declare dropped. Not `reader`: that tier keeps+// collabForReader's room + read key, which is a LIVE viewer (share.ts+// readerCopy) — the one thing a sealed copy must not be able to become.+//+// WHAT IS ACTUALLY GUARANTEED, in three honest categories. This app's history+// says the failure worth naming is presenting a cosmetic guarantee as+// protection, so:+//+// CRYPTOGRAPHIC. `doc.collab` is not carried at all — the package tier's+// capability rule is `drop`, so the copy is built without it rather than+// having it stripped — and so the copy carries no+// `key` (the read capability for every frame and blob the relay holds for+// the room), no `ownerPriv`, no `writerPriv` and no `invite.priv`. The+// recipient cannot read the room, cannot write to it, and cannot join it —+// not because the UI declines, but because the material a socket must+// present to the relay is not in the file. This is the same boundary+// `share.ts` draws for an invite, drawn further: an invite keeps `room` ++// `key` because it is MEANT to follow; a reading copy is sealed, so it+// keeps nothing.+//+// FORMAT-LEVEL. The version history (`revisions`, `trail` — class+// 'history') is not carried: the kernel drops it from every copy for+// someone else, and here it would hand over every draft the space went+// through. Comments are gone from the bytes too. A reading copy that merely+// hid them would still be a file whose JSON block contains every remark+// anyone made about the draft, and the app invites people to read that+// block. Deleting them is not enforcement of anything — it is the copy+// genuinely not containing them, which is the only version of "comments are+// workspace, not publication" that survives someone opening the file in a+// text editor.+//+// COSMETIC. `doc.readonly` itself, and every piece of chrome the reading view+// hides. Anyone can open the HTML, change `"readonly":true` to `false`, and+// have the editor back — the document block is deliberately plaintext and+// that is the point of the whole format. `readonly` states the sender's+// intent and makes the app honour it; it is NOT a lock, it protects+// nothing, and it must never be described as though it did. What stops a+// recipient reaching the live space is the previous paragraph, not this one.+//+// AN OLDER BUILD OPENING A READING COPY does not fail: `readonly` is an+// optional boolean it either ignores (builds before main.ts read it) or+// honours. It opens the space, editable in the oldest builds. That is the+// correct degradation, and it is exactly why the guarantee that matters is+// removal rather than a flag — bytes that are not in the file are not in the+// file whatever opens it.+//+// ENCRYPTED SPACES. Nothing here touches encryption, deliberately. A reading+// copy is written through `serializeAuto` like every other export, so a copy+// taken out of a password-protected space is written encrypted with the same+// password and its reader meets the password gate before the reading view —+// and, because `previewAllowed` (kernel/src/save.ts) refuses a preview for an+// encrypted body, it carries no still render either. A plaintext home page+// sitting beside the ciphertext is the leak the password exists to prevent, and+// a reading copy — the one file most likely to be sent to a stranger — is the+// last place to make that exception.++import type { SpacesDoc, Page } from './model.ts'+import { projectForCopy } from '../../kernel/src/docfields.ts'+import { SPACES_FIELDS } from './docclass.ts'+import { t } from './i18n.ts'++/** Is this file one that was saved for reading? */+export function isReadingCopy(doc: SpacesDoc): boolean {+ return doc.readonly === true+}++/** A deep clone, so nothing done to a copy can reach the open document. */+const clone = (doc: SpacesDoc): SpacesDoc => JSON.parse(JSON.stringify(doc)) as SpacesDoc++/**+ * Seal a copy of this space for reading.+ *+ * Built FROM EMPTY by the kernel's copy table, tier `package` (see the header):+ * no `collab` at all — room and read key included, since together they ARE+ * the capability to follow the room, and a sealed copy follows nothing — no+ * history, no template flag, and no top-level key this build does not declare.+ * A private field added to `CollabCreds` later is covered without anyone+ * remembering to act, because the whole block is never copied.+ */+export function readingCopy(doc: SpacesDoc): SpacesDoc {+ const out = projectForCopy(clone(doc), SPACES_FIELDS, 'package')+ // readonly:true comes from the package tier's {set} rule, which the kernel+ // applies whether or not the source has the key (#666) — almost no space+ // does. scripts/test-spaces-copytiers.ts asserts it on a source without one.+ // Comments live INSIDE pages (content, which every tier keeps), so they are+ // not a field the kernel's table can see; taking them out is this app's.+ stripComments(out)+ return out+}++/**+ * Every comment thread, gone from the document.+ *+ * There are exactly two anchors in the format (model.ts): `Page.comments` is a+ * thread about the page, `Block.comments` a thread about that block. Both go.+ * The starter space says out loud that a comment is saved in the file and that+ * anyone you send it to can read it — this is the export where that stops being+ * the reader's problem.+ */+export function stripComments(doc: SpacesDoc): void {+ for (const page of doc.pages ?? []) {+ delete page.comments+ for (const b of page.blocks ?? []) delete b.comments+ }+}++/**+ * The page before this one and the page after it, in the tree's reading order.+ *+ * `doc.pages` is flat and PRE-ORDER (model.ts), so the reading order is simply+ * the array: a child always follows its parent, and a sibling follows the whole+ * of the previous sibling's subtree. Walking it as a tree here would rebuild+ * that ordering and could only ever disagree with the sidebar. Archived pages+ * are skipped for the same reason: the sidebar's tree leaves them out.+ */+export function readingNeighbours(+ doc: SpacesDoc, pageId: string,+): { prev?: Page; next?: Page } {+ const pages = (doc.pages ?? []).filter((p) => !p.archived)+ const i = pages.findIndex((p) => p.id === pageId)+ if (i < 0) return {}+ return { prev: pages[i - 1], next: pages[i + 1] }+}++/**+ * The reader's footer: what came before, what comes next.+ *+ * A reading copy has no sidebar affordances to add a page and no gutters to+ * hover, so without this the only way through a space of forty pages is the+ * tree — which is a table of contents, not a way of reading. Slides gives a+ * presented deck arrow keys for the same reason.+ *+ * Returns null for a one-page space, where a nav with both ends empty is just+ * a rule across the bottom of the page.+ */+export function readerNav(+ doc: SpacesDoc, pageId: string, go: (id: string) => void,+): HTMLElement | null {+ const { prev, next } = readingNeighbours(doc, pageId)+ if (!prev && !next) return null++ const nav = document.createElement('nav')+ nav.className = 'sp-rnav'+ nav.setAttribute('aria-label', t('Pages'))++ const end = (page: Page | undefined, dir: 'prev' | 'next') => {+ if (!page) {+ // A spacer, so "next" stays on the end edge when there is no "previous".+ nav.append(Object.assign(document.createElement('span'), { className: 'sp-rnav-gap' }))+ return+ }+ const a = document.createElement('a')+ a.className = `sp-rnav-link sp-rnav-${dir}`+ a.href = `#p/${page.id}`+ const kicker = document.createElement('span')+ kicker.className = 'sp-rnav-kicker'+ // LITERALS, both of them: `t(MAP[dir])` would reach no catalog while the+ // packer happily reported a full sweep.+ kicker.textContent = dir === 'prev' ? t('Previous') : t('Next')+ const label = document.createElement('span')+ label.className = 'sp-rnav-title'+ label.textContent = page.title || t('Untitled')+ a.append(kicker, label)+ a.addEventListener('click', (e) => { e.preventDefault(); go(page.id) })+ nav.append(a)+ }++ end(prev, 'prev')+ end(next, 'next')+ return nav+}diff --git a/spaces/src/share.ts b/spaces/src/share.tsindex 7f83eedc..e04a37ed 100644--- a/spaces/src/share.ts+++ b/spaces/src/share.ts@@ -37,8 +37,16 @@ import { projectForCopy } from '../../kernel/src/docfields.ts'import type { SpacesDoc } from './model.ts'import { SPACES_FIELDS } from './docclass.ts'-/** A share export's filename suffix — also what the UI calls the copy. */-export type ShareKind = 'invite' | 'viewonly'+/**+ * A share export's filename suffix — also what the UI calls the copy.+ *+ * `reading` is the SEALED one and is built in reading.ts, not here: it keeps no+ * room (the kernel's `package` tier), so it is not a question about which+ * collaboration fields survive. It is named in this union because the three of+ * them are one menu and one write path, and a fourth kind added elsewhere would+ * type-check against neither.+ */+export type ShareKind = 'invite' | 'viewonly' | 'reading'/** A deep clone, so nothing done to a copy can reach the open document. */const clone = (doc: SpacesDoc): SpacesDoc => JSON.parse(JSON.stringify(doc)) as SpacesDocdiff --git a/spaces/src/styles.css b/spaces/src/styles.cssindex 1a2c38de..35bebe47 100644--- a/spaces/src/styles.css+++ b/spaces/src/styles.css@@ -1591,6 +1591,64 @@ a.sp-embed-src:hover { color: var(--ink); text-decoration: underline; }.sp-app.sp-reading .sp-page-inner { font-size: 17px; }.sp-app.sp-reading .sp-title { margin-bottom: 18px; }+/* THE TOOLS GO, NOT THE DOCUMENT. Reading view was a font-size bump and some+ padding: every editing control was still on screen, merely inert, which+ reads as a broken editor rather than as a document. What leaves is anything+ whose only purpose is CHANGING the space; what stays is everything a reader+ uses — the page tree, ⌘K search, Graph, print, and the eye to come back.+ `!important` throughout because these are one-line overrides of the layout+ rules that build each control, not a competition of specificity. (The insert+ group already leaves, with the insert group's own rules below.) */+.sp-app.sp-reading .sp-group-history,+.sp-app.sp-reading .sp-insp-toggle,+.sp-app.sp-reading .bkp-end,+.sp-app.sp-reading .sp-fmt,+.sp-app.sp-reading .sp-newsplit,+.sp-app.sp-reading .sp-rowmore,+.sp-app.sp-reading .sp-gutter,+.sp-app.sp-reading .sp-pageicon { display: none !important; }++/* A SEALED READING COPY (`doc.readonly`) has no editing to go back to, so the+ eye, the way to write this file and the live control are not hidden-because-+ inert, they are absent. Nothing here is protection — see reading.ts on which+ guarantees are cryptographic and which are only this. connectSync REPLACES+ the live slot with the real control, which carries `.sp-live` and not the+ slot class, so both are named. */+.sp-app.sp-sealed .sp-readtoggle,+.sp-app.sp-sealed .sp-split,+.sp-app.sp-sealed .sp-live-slot,+.sp-app.sp-sealed .sp-live { display: none !important; }++/* The reader's footer: what came before, what comes next.+ `.sp-page a` underlines every link in the reading column and out-specifies a+ bare class, so these say so with `.sp-page` in front of them. */+.sp-rnav {+ display: flex; align-items: stretch; gap: 12px;+ margin: 54px 0 0; padding-top: 20px; border-top: 1px solid var(--line);+}+.sp-rnav-gap { flex: 1 1 0; }+.sp-page a.sp-rnav-link, .sp-rnav-link {+ flex: 1 1 0; min-width: 0;+ display: flex; flex-direction: column; gap: 3px;+ padding: 11px 14px; border: 1px solid var(--line); border-radius: var(--radius);+ background: var(--surface); color: var(--ink); text-decoration: none;+}+.sp-rnav-link:hover { border-color: var(--edge); background: var(--chrome-2); }+.sp-rnav-next { text-align: end; }+.sp-rnav-kicker {+ font-size: 11px; font-weight: 600; text-transform: uppercase;+ letter-spacing: .07em; color: var(--muted);+}+.sp-rnav-title {+ font-size: 14.5px; font-weight: 600; line-height: 1.35;+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+}+/* PAPER WANTS WHAT READING MODE WANTS — no tools — and it already hides the+ bar, the panels and the gutters. The footer is the one thing reading mode+ ADDS, so it is the one thing this has to take away again: a "Next ›" card is+ a control, and a control on paper is a card that does nothing. */+@media print { .sp-rnav { display: none !important; } }+/* A remote image that has not been loaded. Deliberately quiet and boxy — itholds the place without pretending to be the picture. */.sp-remote {