Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
spaces: version history inside the file, on the kernel's Revision envelope (#671)
nyblnetc4b282ee5cc7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 38ee6d30..6cba0f72 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -219,6 +219,18 @@ jobs:--outfile="$RUNNER_TEMP/test-spaces-restore-gate.mjs"node "$RUNNER_TEMP/test-spaces-restore-gate.mjs"+ - name: Spaces in-file history rig+ # doc.revisions (spaces/src/history.ts): every entry is the kernel's+ # Revision envelope with the patch under body; what it covers is the+ # field map's content class minus assets (footnotes, design, templates+ # included); restore(N) is byte-identical to what was saved at N and+ # goes through the restore gate; history is a log undo never un-records.+ # (Bundled: store.ts imports './model' extensionless.)+ run: |+ slides/node_modules/.bin/esbuild scripts/test-spaces-history.ts --bundle --platform=node --format=esm \+ --outfile="$RUNNER_TEMP/test-spaces-history.mjs"+ node "$RUNNER_TEMP/test-spaces-history.mjs"+- name: Spaces agent-surface rig# agent.ts is ~900 lines and shipped with no coverage at all: two of the# five defects an adversarial review found in round 2 lived here,diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 67bc798a..40c866e7 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -9929,3 +9929,74 @@ first.Assertions are on the SERIALIZED document: `scripts/test-spaces-reading.ts`(bytes) and `scripts/test-spaces-copytiers.ts` (the exact key set, against thehostile source, with three planted builders that must fail).++## 2026-10-10 — bento/spaces keeps version history inside the file, on the kernel's Revision envelope++**Decision.** `doc.revisions` (spaces/src/history.ts) is the space's own+timeline, carried in the file. It was first built against bento/type's local+`Revision` shape (#440, never merged) and is rebuilt here on the kernel's+shared envelope and field classes. Six things are settled, any of which a later+session could otherwise contradict.++**1. The entry is the kernel's `Revision<Body>`** (kernel/src/docfields.ts):+`{ id, at, label?, body }`. Spaces' body is a per-page, id-keyed PATCH against+the entry before it (`doc` / `unset` for top-level fields, `order`, and per page+`meta` / `put` / `order` / `gone`). `label` is absent unless a person typed one.+The summary on screen is derived from the patch when the dialog opens, so the+file stores no sentence in its author's UI language. Every entry read from a+file passes `validateRevision` plus the app's body check. If any entry fails,+the whole list counts as foreign: it is kept, and never recorded onto, pruned or+cleared.++**2. What a revision covers comes from the field map, not a hand list.** It is+every field `SPACES_FIELDS` classes `content`, minus the asset pool (bytes are+never duplicated: a revision keeps `asset:<key>`), the not-edit fields+(`modified`) and the encoding tags (`format`, `version`). Today that is title,+home, theme, footnotes, fonts, templates, journalTemplate, design, designs,+policy and pages. A content field added to the map later joins history with no+change to history.ts. Identity, mode, capability and history fields can never+be rolled back by a restore.++**3. The budget is the kernel fold module's defaults, implemented here for+now.** `HISTORY_MAX` = 60, `HISTORY_BUDGET` = 128 KB. Over either, the oldest+two entries fold into one, re-derived from the state they produce, so every+surviving entry still restores exactly. A space whose content alone is over+budget keeps none (tier 3), and the dialog says so. `pruneRevisions` is the seam:+when the kernel's fold module lands after DocStore, the swap replaces that one+function.++**4. A revision is recorded inside the save queue's prepare step,** beside+`stampSync`, after any write ahead of it and immediately before the snapshot is+copied. It therefore describes exactly the bytes written, and those bytes+contain it. ⌘S and "Update this file" both do this. Recording writes the field+directly, never through `commit`, so the store revision does not move and the+write is not stale. `revisions` is also in `SPACES_NOT_EDIT`, which keeps it+out of the recovery key. The kernel's default counts history as unsaved work.+That default is right for history made between saves (type's typed revisions,+a signature), but spaces only ever writes a revision into the bytes a save is+writing. Counting it would raise the recovery banner on every file reopened+after a download-save. `trail` is not exempted; its own feature decides.++**5. History is a log, so the store keeps the live list.** Undo snapshots omit+every `history`-class field, and every whole-document restore (undo/redo,+`replaceDoc`: version restore, recovery, Replace from JSON, `bento.loadDoc`)+puts back the live value. Without this, ⌘Z after a save un-recorded that save's+revision, and pasting Copy document JSON's output (which drops history by the+copy table) deleted it. A restore from the in-file timeline goes through the+restore gate (`restoreInto`): parsed, block html sanitized, identity kept live,+undoable. A revision's `body.doc` only ever applies covered fields, so a crafted+entry cannot carry a docId, room or mode.++**6. Copies follow the kernel table; there are no hand strips.** The file, a+duplicate and an invite keep history. A view-only copy, the sealed reading copy+(tier package), link, audience, template and Copy document JSON drop it. The page extract drops the history+class as before. An encrypted space keeps history inside the `bento/enc`+envelope, and nothing goes to IndexedDB.++**Not in this change:** migrating the legacy IndexedDB timeline into+`doc.revisions` (the kernel's fold-in helper, later), and a "leave history out"+option on invites.++Pointers: spaces/src/history.ts, scripts/test-spaces-history.ts,+scripts/test-spaces-save-revisions.ts (the prepare rows and the main.ts pins),+scripts/test-spaces-copytiers.ts (real revisions per tier).diff --git a/docs/spaces-agents.md b/docs/spaces-agents.mdindex 96a6880f..7803658c 100644--- a/docs/spaces-agents.md+++ b/docs/spaces-agents.md@@ -617,7 +617,7 @@ bento.removeBlocks([ids]) // → {ok:true, removed, missing, adbento.moveBlock(id, {pageId?, afterId?, beforeId?, parent?})bento.updatePage(id, patch) // → {ok:true, id} | {ok:false, err}bento.removePage(id, {descendants?}) // → {ok:true, removed, rehomed, links}-bento.loadDoc(json) // replace the content (one undo step); docId, collab, readonly, template stay+bento.loadDoc(json) // replace the content (one undo step); docId, collab, readonly, template and revisions staybento.serialize() // the whole .bento.html filebento.undo() / bento.redo()@@ -930,6 +930,14 @@ 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.+- `doc.revisions` is the space's **version history, kept inside the file**:+ oldest first, each entry `{ id, at, label?, body }` where `body` is the change+ from the entry before it. Leave it alone. Saving appends to it; only **Save ▾+ → Versions in this file… → Clear history** removes it. `bento.loadDoc` keeps+ the open space's history whatever the JSON you pass carries, so a whole-+ document rewrite cannot delete it, and cannot plant one either. If you write+ `#bento-doc` from outside the app, copy the field across unchanged; an entry+ this build cannot read makes the whole list read-only (kept, never extended).- `readonly: true` marks a READING COPY: the file opens in the reader (noediting tools, no comment markers, a Previous/Next pair under each page) and`bento.readonly` is true, so every write returns `err: 'readonly'`. (Adiff --git a/scripts/test-spaces-copytiers.ts b/scripts/test-spaces-copytiers.tsindex ee394685..a6f37fcb 100644--- a/scripts/test-spaces-copytiers.ts+++ b/scripts/test-spaces-copytiers.ts@@ -58,6 +58,8 @@ 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')const { mintCollab } = await import('../kernel/src/sync/online.ts')+const { recordRevision, revisionsOf, applyRevisions } = await import('../spaces/src/history.ts')+const { validateRevision } = await import('../kernel/src/docfields.ts')import type { SpacesDoc } from '../spaces/src/model.ts'import type { Tier } from '../kernel/src/docfields.ts'@@ -114,13 +116,43 @@ function source(extra: Obj = {}): SpacesDoc {design: 'almanac',journalTemplate: 't1',collab: clone(collab),- revisions: [{ id: 'r1', at: '2026-10-09T00:00:00Z', body: { pages: 'THE-WHOLE-SPACE' } }],+ revisions: realRevisions(),trail: { '2026-10-09': { done: 3 } },futureField: 'FROM-A-NEWER-BUILD',...extra,} as unknown as SpacesDoc}+/**+ * REAL in-file history, recorded by history.ts exactly as a save records it:+ * three saves of a space that had a third page, then deleted it. Each entry is+ * the kernel's Revision envelope; the deleted page's text survives only inside+ * the history, which is what makes "does this copy carry it" a real question.+ */+// recorded ONCE (ids and times are minted) and cloned per source, so every+// source() carries the same bytes. `var`: source() runs before this line.+// eslint-disable-next-line no-var+var REAL_REVISIONS: unknown[] | undefined+function realRevisions(): unknown[] {+ if (REAL_REVISIONS) return clone(REAL_REVISIONS)+ const d = {+ format: FORMAT, version: 1, docId: 'doc-source', title: 'Handbook', home: 'p1',+ pages: [+ { id: 'p1', title: 'Home', blocks: [{ id: 'b1', type: 'p', html: 'first draft' }] },+ { id: 'p3', title: 'Gone', blocks: [{ id: 'b3', type: 'p', html: 'THE-WHOLE-SPACE deleted page text' }] },+ ],+ theme: { background: '#FFFFFF', color: '#1E2A3A', accent: '#F7A600', fontFamily: 'sans-serif', measure: 720 },+ footnotes: { 1: 'an older note' },+ } as unknown as SpacesDoc+ recordRevision(d)+ d.pages[0].blocks[0].html = 'second draft'+ recordRevision(d)+ d.pages.splice(1, 1)+ recordRevision(d)+ REAL_REVISIONS = clone(d.revisions as unknown[])+ return clone(REAL_REVISIONS)+}+/** No capability secret anywhere in the serialized copy — a full-text scan. */function noSecrets(o: object, label: string, allowFreshInvite = false) {const text = JSON.stringify(o)@@ -150,6 +182,45 @@ console.log('\nthe source: one field of every class, and every secret')ok(SPACES_FIELDS.readonly === 'mode' && SPACES_FIELDS.template === 'mode', 'readonly and template are the modes')}+// ---------------------------------------------------------------------------+// REAL REVISIONS, per tier. The fixture's history is three genuine entries+// recorded by history.ts (one of them holding a deleted page's text), so this+// is the copy table applied to what a saved space actually carries — not a+// placeholder. Copies handed to a reader drop it whole; the owner's own copies+// and an invite keep it BYTE-FOR-BYTE, still readable and still restorable.+console.log('\nreal in-file history (history.ts), tier by tier')+{+ const src = source()+ const want = JSON.stringify(src.revisions)+ const revs = src.revisions as unknown[]+ ok(revs.length === 3 && revs.every((r) => validateRevision(r) && !Object.hasOwn(r as Obj, 'label')),+ `the fixture's history is 3 kernel Revision envelopes with no label (${revs.length})`)+ ok(revisionsOf(src).length === 3 && JSON.stringify(applyRevisions(revisionsOf(src), 0)).includes('THE-WHOLE-SPACE'),+ 'and it is readable: the oldest entry restores the page that was later deleted')+ const kept: Array<[string, SpacesDoc]> = [+ ['invite', (await inviteCopy(source()))!],+ ['duplicate', duplicateAsNew(source(), 'doc-fresh')],+ ['file', projectForCopy(source(), SPACES_FIELDS, 'file')],+ ]+ for (const [label, o] of kept) {+ ok(JSON.stringify((o as Obj).revisions) === want, `${label}: KEEPS the revisions byte-for-byte`)+ ok(revisionsOf(o).length === 3, `${label}: and they still read as history`)+ }+ const dropped: Array<[string, SpacesDoc]> = [+ ['reader (view-only copy)', readerCopy(source())!],+ ['Copy document JSON', docForExport(source())],+ ['sealed reading copy (reading.ts, tier package)', readingCopy(source())],+ ['link', projectForCopy(source(), SPACES_FIELDS, 'link')],+ ['audience', projectForCopy(source(), SPACES_FIELDS, 'audience', { projectAudience: (c) => ({ ...collabForReader(c), role: 'audience' }) })],+ ['template', projectForCopy(source(), SPACES_FIELDS, 'template')],+ ['extract', extractSpace(source(), 'p1', { subtree: true, docId: 'doc-x' }).doc],+ ]+ for (const [label, o] of dropped) {+ ok(!('revisions' in (o as Obj)), `${label}: DROPS the revisions`)+ ok(!JSON.stringify(o).includes('THE-WHOLE-SPACE'), `${label}: the deleted page's text appears nowhere in it`)+ }+}+// ---------------------------------------------------------------------------console.log('\nreader — "Share → view-only copy" (share.ts readerCopy)')const EXPECT_READER = sorted([...CONTENT, 'docId', 'collab', 'readonly'])diff --git a/scripts/test-spaces-history.ts b/scripts/test-spaces-history.tsnew file mode 100644index 00000000..8f4ff0d7--- /dev/null+++ b/scripts/test-spaces-history.ts@@ -0,0 +1,425 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/spaces in-file version history (spaces/src/history.ts).+//+// node scripts/test-spaces.mjs history # bundled, like restore-gate+//+// (Bundled: store.ts imports './model' extensionless. Run from the repo root;+// the source rows read spaces/src.)+//+// WHAT THIS PROVES.+// 1. Every entry is the KERNEL's Revision envelope ({id, at, label?, body}),+// the patch under `body`, no app-minted label; entries read from a file+// are validated, and a foreign or invalid list is never written over.+// 2. What a revision covers is READ FROM THE FIELD MAP: every field+// SPACES_FIELDS classes 'content', minus the asset pool, `modified` and+// the encoding tags. Footnotes, templates, journalTemplate, design,+// designs, policy and fonts are covered; a restore brings last week's+// footnotes and design back WITH last week's pages, through the real+// restore gate and Store, and ⌘Z undoes it.+// 3. restore(N) is byte-identical to the content recorded at N — for a+// scripted sequence and 200 randomised ones — and survives every fold.+// 4. The budget is the kernel fold module's defaults and tiers, not fails.+// 5. History is a LOG: recording does not move the recovery key, undo does+// not un-record a save, and a whole-document replace keeps the live list.+// 6. A crafted revision cannot smuggle identity, capability or script.+//+// Mutation controls (by hand, listed in the PR): hand-list contentOf's fields+// without `footnotes` → rows in 2 red; class `revisions` as content → rows in+// 2 red (and copytiers); move recordOnSave out of the queue's prepare → the+// save-revisions rig's pins red.++import { readFileSync } from 'node:fs'+import { join } from 'node:path'+import { Store } from '../spaces/src/store.ts'+import { parseDoc, docContentKey, FORMAT, type SpacesDoc } from '../spaces/src/model.ts'+import { SPACES_FIELDS, SPACES_NOT_EDIT } from '../spaces/src/docclass.ts'+import { restoreInto } from '../spaces/src/restoregate.ts'+import { extractSpace } from '../spaces/src/portable.ts'+import { starterDoc } from '../spaces/src/starter.ts'+import { validateRevision } from '../kernel/src/docfields.ts'+import {+ HISTORY_FIELDS, HISTORY_BUDGET, HISTORY_MAX, HISTORY_FOLD,+ contentOf, recordRevision, recordOnSave, revisionsOf, historyIsForeign, readable,+ applyRevisions, restoredDoc, pruneRevisions, clearHistory, diffWords, changesAt,+ tooLargeForHistory, historyBytes,+} from '../spaces/src/history.ts'++let checks = 0+let failures = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (!cond) { failures++; console.log(` FAIL ${msg}`) }+ else console.log(` ok ${msg}`)+}+const J = (v: unknown) => JSON.stringify(v)+const B = (v: unknown) => new TextEncoder().encode(J(v)).length+const clone = <T>(v: T): T => JSON.parse(J(v)) as T+type Obj = Record<string, unknown>++const PHOTO = 'data:image/png;base64,' + 'A'.repeat(20_000)++/** A space carrying every covered field, an asset, identity and a live room. */+function mkDoc(): SpacesDoc {+ const r = parseDoc(J({+ format: FORMAT, version: 1, docId: 'd-hist', title: 'Space', home: 'p1',+ theme: { background: '#FFFFFF', color: '#1E2A3A', accent: '#F7A600', fontFamily: 'x', measure: 720 },+ pages: [+ { id: 'p1', title: 'One', icon: 'star', blocks: [+ { id: 'b1', type: 'p', html: 'the quick brown fox [^1]' },+ { id: 'b2', type: 'p', html: 'second line' },+ { id: 'b4', type: 'image', src: 'asset:photo', alt: 'a photo' },+ ] },+ { id: 'p2', title: 'Two', parent: 'p1', blocks: [{ id: 'b3', type: 'p', html: 'other page' }] },+ ],+ assets: { photo: PHOTO },+ footnotes: { 1: 'last week’s note' },+ design: 'almanac',+ designs: { mine: { base: 'riso', label: 'Mine' } },+ templates: [{ id: 't1', title: 'Meeting', blocks: [{ id: 'tb', type: 'p', html: 'Agenda' }] }],+ journalTemplate: 't1',+ collab: { v: 2, room: 'wROOM', key: 'k', on: true },+ }))+ if (!r.ok) throw new Error('fixture does not parse')+ return r.doc+}++// ---------------------------------------------------------------------------+console.log('\n1. the envelope is the kernel\'s\n')+{+ const d = mkDoc()+ recordRevision(d)+ d.pages[0].blocks[0].html = 'edited'+ recordRevision(d)+ const revs = d.revisions as unknown as Obj[]+ ok(revs.length === 2 && revs.every((r) => validateRevision(r)), 'every recorded entry passes the kernel\'s validateRevision')+ ok(revs.every((r) => Object.keys(r).sort().join() === 'at,body,id'),+ `the patch lives UNDER body — the entry carries only id, at, body (${Object.keys(revs[0]).join(',')})`)+ ok(revs.every((r) => !Object.hasOwn(r, 'label')), 'no app-minted label: absent unless a person typed one')+ ok(recordRevision(mkDoc(), 'before the reorg')?.label === 'before the reorg', 'a typed label is kept as typed')+ const body = revs[1].body as Obj+ ok(Object.keys(body).every((k) => ['doc', 'unset', 'order', 'pages'].includes(k)), `the body is the patch: ${Object.keys(body).join(',')}`)++ // a foreign or invalid list is never written over+ const cases: Array<[string, unknown]> = [+ ['not an array', { v: 9, entries: [] }],+ ['an entry with no body (#440\'s flat shape)', [{ id: 'r1', at: 't', doc: { title: 'x' }, pages: [] }]],+ ['an entry whose body.pages is junk', [{ id: 'r1', at: 't', body: { pages: [{ nope: 1 }] } }]],+ ['an entry with a non-string label', [{ id: 'r1', at: 't', label: 7, body: {} }]],+ ['one bad entry after a good one', [...clone(revs), { id: 'r9', at: 't' }]],+ ]+ for (const [label, rv] of cases) {+ const x = mkDoc() as SpacesDoc & Obj+ x.revisions = clone(rv) as never+ const before = J(x.revisions)+ ok(historyIsForeign(x) && revisionsOf(x).length === 0, `${label}: read as foreign, never misread`)+ x.pages[0].blocks[0].html = 'an edit'+ ok(recordRevision(x) === null && J(x.revisions) === before, `${label}: a save never writes over it`)+ ok(!clearHistory(x) && J(x.revisions) === before, `${label}: and Clear history leaves it alone`)+ }+ ok(readable(revs[0]) && !readable({ id: 'a', at: 'b', body: null }), 'readable = the envelope check plus a body check')++ // additivity: unknown fields on an entry and in its body survive a later save+ const a = mkDoc()+ recordRevision(a)+ ;(a.revisions![0] as unknown as Obj).futureField = { note: 'from 2036' }+ ;((a.revisions![0] as unknown as Obj).body as Obj).futureBody = 1+ a.pages[0].blocks[1].html = 'later'+ recordRevision(a)+ ok(J((a.revisions![0] as unknown as Obj).futureField) === J({ note: 'from 2036' }) &&+ ((a.revisions![0] as unknown as Obj).body as Obj).futureBody === 1,+ 'unknown fields on an entry and in its body survive a later save untouched')+}++// ---------------------------------------------------------------------------+console.log('\n2. what is covered comes from the field map\n')+{+ const derived = Object.keys(SPACES_FIELDS).filter((k) =>+ (SPACES_FIELDS as Record<string, string>)[k] === 'content' &&+ !['assets', 'format', 'version'].includes(k) && !SPACES_NOT_EDIT.has(k))+ ok(J(HISTORY_FIELDS) === J(derived),+ `HISTORY_FIELDS is the map's content class minus assets, encoding tags and not-edit fields (${HISTORY_FIELDS.join(', ')})`)+ for (const k of ['title', 'home', 'theme', 'pages', 'footnotes', 'templates', 'journalTemplate', 'design', 'designs', 'policy', 'fonts']) {+ ok((HISTORY_FIELDS as readonly string[]).includes(k), `covers \`${k}\``)+ }+ for (const k of ['assets', 'modified', 'format', 'version', 'docId', 'collab', 'readonly', 'template', 'revisions', 'trail']) {+ ok(!(HISTORY_FIELDS as readonly string[]).includes(k), `does not cover \`${k}\``)+ }+ const hsrc = readFileSync(join(process.cwd(), 'spaces/src/history.ts'), 'utf8')+ ok(!/'footnotes'|'journalTemplate'|'designs'/.test(hsrc), 'history.ts names no content field by hand — the list is the map\'s')++ // the content projection never carries asset BYTES+ const d = mkDoc()+ recordRevision(d)+ ok(!J(d.revisions).includes(PHOTO.slice(22, 200)), 'no revision holds the asset pool\'s bytes — only the `asset:` reference')+ ok(historyBytes(d) < B(contentOf(d)) + 2048, `the base revision costs about the content, not the content plus a 20 KB photo (${historyBytes(d)} B)`)++ // LAST WEEK'S footnotes and design come back WITH last week's pages —+ // through the real restore gate and Store, and ⌘Z undoes it.+ const store = new Store(mkDoc())+ recordOnSave(store) // "last week"+ const lastWeek = J(contentOf(store.doc))+ store.commit(() => {+ store.doc.pages[0].blocks[0].html = 'rewritten this week'+ store.doc.pages.push({ id: 'p9', title: 'New', blocks: [{ id: 'b9', type: 'p', html: 'new' }] })+ store.doc.footnotes = { 1: 'this week’s note', 2: 'another' }+ store.doc.design = 'ledger'+ delete store.doc.designs+ store.doc.templates = []+ store.doc.journalTemplate = undefined+ delete store.doc.journalTemplate+ })+ recordOnSave(store) // "this week"+ const thisWeek = J(contentOf(store.doc))+ const next = restoredDoc(store.doc, 0)!+ ok(restoreInto(store, J(next)), 'restoring last week goes through the gate and is accepted')+ const back = store.doc+ ok(J(back.footnotes) === J({ 1: 'last week’s note' }), 'last week\'s FOOTNOTES are back')+ ok(back.design === 'almanac' && J(back.designs) === J({ mine: { base: 'riso', label: 'Mine' } }), 'last week\'s DESIGN and design registry are back')+ ok(J(back.templates) === J(mkDoc().templates) && back.journalTemplate === 't1', 'last week\'s templates and journal template are back')+ ok(back.pages.length === 2 && back.pages[0].blocks[0].html === 'the quick brown fox [^1]', '…WITH last week\'s pages')+ ok(J(contentOf(back)) === lastWeek, 'the whole covered content is byte-identical to what was saved last week')+ ok(back.docId === 'd-hist' && J(back.collab) === J(mkDoc().collab) && back.assets?.photo === PHOTO,+ 'identity, the live room and the asset pool are the live document\'s')+ ok(revisionsOf(back).length === 2, 'and the history itself is untouched: restoring is an edit, not a rewind of the file')+ store.undo()+ ok(J(contentOf(store.doc)) === thisWeek && revisionsOf(store.doc).length === 2, '⌘Z undoes the restore, and keeps the history')+}++// ---------------------------------------------------------------------------+console.log('\n3. restore(N) is the content saved at N, on the bytes\n')+{+ const d = mkDoc()+ const stamps: string[] = []+ const save = () => { recordRevision(d); stamps.push(J(contentOf(d))) }+ save()+ d.pages[0].blocks[0].html = 'the quick red fox'+ save()+ d.pages[0].title = 'One (renamed)'+ d.pages.push({ id: 'p3', title: 'Three', blocks: [{ id: 'b9', type: 'p', html: 'new' }] })+ d.footnotes = { 1: 'edited note' }+ save()+ d.pages.splice(1, 1)+ d.theme.accent = '#00AA00'+ delete d.design+ save()+ const revs = revisionsOf(d)+ ok(revs.length === 4, `four saves record four revisions (${revs.length})`)+ let exact = 0+ for (let i = 0; i < revs.length; i++) if (J(contentOf(restoredDoc(d, i)!)) === stamps[i]) exact+++ ok(exact === revs.length, `restore(N) is BYTE-IDENTICAL to the content saved at N, for all ${revs.length}`)+ ok(!('design' in restoredDoc(d, 3)!) && restoredDoc(d, 2)!.design === 'almanac', 'a covered field that became absent is absent again, and comes back with an older version')++ // a save that changed nothing writes nothing; no history = no key+ const one = J(d.revisions)+ ok(recordRevision(d) === null && J(d.revisions) === one, 'a save that changed nothing records nothing')+ ok(!Object.hasOwn(mkDoc(), 'revisions'), 'a never-saved space has no revisions key at all')+ const f = mkDoc()+ recordRevision(f)+ clearHistory(f)+ ok(!Object.hasOwn(f, 'revisions'), 'Clear history removes the key — never `revisions: []`')+}++// ---------------------------------------------------------------------------+console.log('\n4. the budget tiers, with the kernel fold module\'s defaults\n')+{+ ok(HISTORY_BUDGET === 128 * 1024 && HISTORY_MAX === 60 && HISTORY_FOLD === 2,+ `HISTORY_BUDGET ${HISTORY_BUDGET} B, HISTORY_MAX ${HISTORY_MAX}, folding the oldest ${HISTORY_FOLD}`)+ const d = mkDoc()+ for (let i = 0; i < 40; i++) { d.pages[0].blocks[0].html = `revision ${i} of the first paragraph`; recordRevision(d) }+ const full = revisionsOf(d)+ ok(full.length === 40, `40 edits, 40 revisions under the real budget (${full.length})`)+ const wantById = new Map<string, string>()+ for (let i = 0; i < full.length; i++) wantById.set(full[i].id, J(applyRevisions(full, i)))+ const squeezed = pruneRevisions(full, 4 * 1024, 60)+ ok(squeezed.length > 1 && squeezed.length < full.length, `a 4 KB budget folds the oldest: ${full.length} → ${squeezed.length}`)+ let still = 0+ for (let i = 0; i < squeezed.length; i++) if (J(applyRevisions(squeezed, i)) === wantById.get(squeezed[i].id)) still+++ ok(still === squeezed.length, `every surviving revision restores EXACTLY what it did before the fold (${still}/${squeezed.length})`)+ ok(B(squeezed) <= 4 * 1024 && squeezed.every((r) => validateRevision(r)), 'the folded list fits, and its folded entry is still a kernel envelope')+ const capped = pruneRevisions(full, HISTORY_BUDGET, 5)+ ok(capped.length === 5 && J(applyRevisions(capped)) === J(applyRevisions(full)), 'the count ceiling bites on its own; the newest state is untouched')+ ok(pruneRevisions(full, 10, 60).length === 0, 'tier 3: a budget below one whole snapshot keeps none')+ const huge = mkDoc()+ huge.pages[0].blocks[0].html = 'x'.repeat(HISTORY_BUDGET + 10)+ ok(tooLargeForHistory(huge) && recordRevision(huge) === null && !Object.hasOwn(huge, 'revisions'),+ 'a space too large for the budget records nothing, carries no key, and the dialog can say why')+}++// ---------------------------------------------------------------------------+console.log('\n5. history is a log: the dot, the recovery key, undo, replace\n')+{+ const store = new Store(mkDoc())+ store.commit(() => { store.doc.pages[0].blocks[0].html = 'edited' })+ store.setDirty(false)+ const key = docContentKey(store.doc)+ const rev = store.revision+ recordOnSave(store)+ ok(revisionsOf(store.doc).length === 1, 'recorded')+ ok(docContentKey(store.doc) === key, 'recording does not change the recovery key — no phantom "unsaved changes" banner')+ ok(store.dirty === false && store.revision === rev, 'recording does not raise the unsaved dot or advance the revision')+ ok(SPACES_NOT_EDIT.has('revisions') && !SPACES_NOT_EDIT.has('trail'), 'revisions is a not-edit field; trail is left to its own feature')++ // undo after a save must not un-record the revision that save wrote+ store.commit(() => { store.doc.pages[0].blocks[0].html = 'edited again' })+ recordOnSave(store)+ const two = J(store.doc.revisions)+ store.undo()+ ok(store.doc.pages[0].blocks[0].html === 'edited' && J(store.doc.revisions) === two, '⌘Z undoes the edit and keeps both revisions')+ store.redo()+ ok(J(store.doc.revisions) === two, '⌘⇧Z too')++ // Replace from JSON with Copy document JSON's output (which drops history)+ const pasted = clone(store.doc) as SpacesDoc & Obj+ delete pasted.revisions+ pasted.title = 'Pasted'+ store.replaceDoc(pasted)+ ok(store.doc.title === 'Pasted' && J(store.doc.revisions) === two, 'a whole-document replace keeps the LIVE history (a paste never deletes it)')+ const forged = clone(store.doc) as SpacesDoc & Obj+ forged.revisions = [{ id: 'forged', at: 't', body: { doc: { title: 'x' } } }] as never+ store.replaceDoc(forged)+ ok(J(store.doc.revisions) === two, '…and never installs the pasted document\'s history either')+}++// ---------------------------------------------------------------------------+console.log('\n6. a crafted revision cannot smuggle identity, capability or script\n')+{+ const store = new Store(mkDoc())+ recordOnSave(store)+ const crafted = clone(store.doc.revisions!) as unknown as Obj[]+ crafted.push({+ id: 'evil', at: '2026-10-10T00:00:00Z',+ body: {+ doc: { docId: 'someone-else', collab: { room: 'attacker', key: 'x', on: true }, readonly: false, template: true, title: 'Owned' },+ pages: [{ id: 'p1', put: [{ id: 'b1', type: 'p', html: 'hi <img src=x onerror="alert(1)"><script>alert(2)</script>' }] }],+ },+ })+ ;(store.doc as SpacesDoc & Obj).revisions = crafted as never+ ok(revisionsOf(store.doc).length === 2, 'the crafted entry is a readable patch (the gate, not the parser, is what stops it)')+ const next = restoredDoc(store.doc, 1)!+ ok(next.docId === 'd-hist' && (next.collab as Obj).room === 'wROOM' && !('template' in next),+ 'body.doc only ever applies COVERED fields — docId, collab and the modes are ignored')+ ok(next.title === 'Owned', '…while a covered field in it does apply')+ ok(restoreInto(store, J(next)), 'restored through the gate')+ const html = store.doc.pages[0].blocks[0].html ?? ''+ ok(!/onerror|<script/i.test(html) && /hi/.test(html), `block html is sanitized on the way in (${J(html)})`)+ ok(store.doc.docId === 'd-hist' && (store.doc.collab as Obj).room === 'wROOM', 'identity and the room are the live space\'s')+}++// ---------------------------------------------------------------------------+console.log('\n7. randomised edit sequences\n')+{+ let seed = 12345+ const rnd = () => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed / 0x7fffffff }+ const pick = (n: number) => Math.floor(rnd() * n)+ let good = 0+ const total = 200+ for (let s = 0; s < total; s++) {+ const d = mkDoc()+ const stamps: string[] = []+ for (let step = 0; step < 8; step++) {+ const pages = d.pages+ switch (pick(8)) {+ case 0: if (pages.length) pages[pick(pages.length)].title = `T${step}`; break+ case 1: { const p = pages[pick(pages.length)]; if (p && p.blocks.length) p.blocks[pick(p.blocks.length)].html = `edit ${s}.${step}`; break }+ case 2: pages.push({ id: `np${pick(4)}`, title: `N${step}`, blocks: [{ id: `nb${step}`, type: 'p', html: 'x' }] }); break+ case 3: if (pages.length > 1) pages.splice(pick(pages.length), 1); break+ case 4: if (pages.length > 1) { const [m] = pages.splice(pick(pages.length), 1); pages.splice(pick(pages.length + 1), 0, m) } break+ case 5: if (rnd() < 0.5) d.footnotes = { [step]: `note ${s}.${step}` }; else delete d.footnotes; break+ case 6: if (rnd() < 0.5) d.design = `d${step}`; else delete d.design; break+ default: {+ const p = pages[pick(pages.length)]+ if (!p) break+ if (p.blocks.length > 1) { const [b] = p.blocks.splice(pick(p.blocks.length), 1); p.blocks.unshift(b) }+ else p.blocks.push({ id: `xb${step}`, type: 'p', html: 'added' })+ }+ }+ const seen = new Set<string>()+ d.pages = d.pages.filter((p) => (seen.has(p.id) ? false : (seen.add(p.id), true)))+ if (recordRevision(d)) stamps.push(J(contentOf(d)))+ }+ const revs = revisionsOf(d)+ let seqOk = revs.length === stamps.length+ for (let i = 0; i < revs.length && seqOk; i++) if (J(contentOf(restoredDoc(d, i)!)) !== stamps[i]) seqOk = false+ if (seqOk) good+++ }+ ok(good === total, `${total} randomised sequences (pages, blocks, footnotes, design; create/delete/reorder/resurrect): every revision restores byte-exactly (${good}/${total})`)+}++// ---------------------------------------------------------------------------+console.log('\n8. the word diff and the derived summary\n')+{+ const parts = diffWords('the quick brown fox', 'the quick red fox')+ ok(parts.filter((p) => p.op === 'del').map((p) => p.text).join('') === 'brown' &&+ parts.filter((p) => p.op === 'ins').map((p) => p.text).join('') === 'red', 'WORD granularity: brown → red')+ const n = diffWords('we grew 30 percent', 'we grew 60 percent')+ ok(n.filter((p) => p.op === 'del').map((p) => p.text).join('') === '30', '"30" → "60" is a whole word, not one glyph')+ const pairs: Array<[string, string]> = [+ ['the quick brown fox', 'the quick red fox'], ['', 'all new'], ['all gone', ''], ['a b c d', 'd c b a'],+ ['one\ntwo\nthree', 'one\ntwo and a half\nthree'], ['same', 'same'], [' lead ', ' lead '], ['naïve café', 'naive cafe'],+ ]+ let both = 0+ for (const [a, b] of pairs) {+ const p = diffWords(a, b)+ if (p.filter((x) => x.op !== 'ins').map((x) => x.text).join('') === a && p.filter((x) => x.op !== 'del').map((x) => x.text).join('') === b) both+++ }+ ok(both === pairs.length, `reject-all == old and accept-all == new, for all ${pairs.length} pairs`)++ const d = mkDoc()+ recordRevision(d)+ d.pages[0].blocks[0].html = 'the quick red fox'+ d.pages.splice(1, 1)+ recordRevision(d)+ d.footnotes = { 1: 'only the note changed' }+ recordRevision(d)+ const revs = revisionsOf(d)+ ok(changesAt(revs, 0).first, 'the first revision is reported as the first — there is nothing before it')+ const rep = changesAt(revs, 1)+ ok(rep.pagesChanged === 2 && rep.blocksChanged === 2 && rep.pages.some((p) => p.kind === 'removed' && p.title === 'Two'),+ `the counts behind the summary are derived from the patch (${rep.pagesChanged} pages, ${rep.blocksChanged} blocks)`)+ const r2 = changesAt(revs, 2)+ ok(r2.pagesChanged === 0 && J(r2.fieldsChanged) === J(['footnotes']), `a change outside the pages is reported by field (${r2.fieldsChanged.join(',')})`)+ ok(revs.every((r) => !Object.hasOwn(r, 'label')), 'and nothing language-bearing is stored: the sentence is made at render time')+}++// ---------------------------------------------------------------------------+console.log('\n9. cost on a real space, and what leaves it\n')+{+ const d = starterDoc()+ const contentBytes = B(contentOf(d))+ recordRevision(d)+ const base = B(d.revisions)+ let before = base+ const deltas: number[] = []+ for (let i = 0; i < 20; i++) {+ const p = d.pages[i % d.pages.length]+ if (p.blocks.length) p.blocks[0].html = `${p.blocks[0].html ?? ''} — edited pass ${i}`+ recordRevision(d)+ const now = B(d.revisions)+ deltas.push(now - before)+ before = now+ }+ const avg = Math.round(deltas.reduce((a, b) => a + b, 0) / deltas.length)+ console.log(` starter space: content ${contentBytes} B · base revision ${base} B · 20 saves +${before - base} B (avg ${avg}, worst ${Math.max(...deltas)}) · total ${before} B of ${HISTORY_BUDGET}`)+ ok(avg * 10 < contentBytes, `an ordinary save costs an order of magnitude less than a whole snapshot (${avg} B vs ${contentBytes} B)`)+ ok(before < HISTORY_BUDGET && revisionsOf(d).length === 21, '21 saves of the starter space fit without folding')+ const ex = extractSpace(d, d.pages[0].id, { docId: 'ex-1', subtree: false })+ ok(!Object.hasOwn(ex.doc, 'revisions'), 'a page extract carries no history (the copy table\'s history class, portable.ts)')+}++// ---------------------------------------------------------------------------+console.log('\n10. encrypted spaces: in the envelope, never in IndexedDB (source)\n')+{+ const root = process.cwd()+ const hsrc = readFileSync(join(root, 'spaces/src/history.ts'), 'utf8')+ const main = readFileSync(join(root, 'spaces/src/main.ts'), 'utf8')+ ok(!/autosave|indexedDB|putRecovery|addVersion|localStorage/.test(hsrc.replace(/\/\/.*$/gm, '')),+ 'history.ts touches no browser storage — revisions live only in the document')+ const doSave = main.slice(main.indexOf('async function doSave('), main.indexOf('editor.onUpdateInPlace'))+ ok(/recordOnSave\(store\)/.test(doSave) && !/isEncryptionActive\(\)[^\n]*recordOnSave/.test(doSave),+ 'the save records unconditionally — an encrypted space keeps history, inside #bento-doc\'s envelope')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/scripts/test-spaces-restore-gate.ts b/scripts/test-spaces-restore-gate.tsindex 6160f559..e631162c 100644--- a/scripts/test-spaces-restore-gate.ts+++ b/scripts/test-spaces-restore-gate.ts@@ -229,6 +229,11 @@ console.log('\nevery restore path uses the gate\n')ok(/restoreInto\(store, snap\.json\)/.test(offer), 'the banner\'s Restore goes through restoreInto')ok(/restoreInto\((h\.)?store, v\.json\)/.test(about), 'History\'s Restore goes through restoreInto')ok(!/JSON\.parse\((snap|v)\.json\)/.test(main + about), 'no raw JSON.parse of a stored entry remains')+ // the in-file timeline (history.ts) is the document's own, but what it+ // applies is still parsed, sanitized and given the live identity+ const fileHist = about.slice(about.indexOf('function openFileHistory('), about.indexOf('function summary('))+ ok(/restoreInto\(h\.store, JSON\.stringify\(next\)\)/.test(fileHist) && !/replaceDoc\(/.test(fileHist),+ 'Versions in this file restores through restoreInto, never a bare replaceDoc')}console.log('\na design is content, not identity\n')diff --git a/scripts/test-spaces-save-revisions.ts b/scripts/test-spaces-save-revisions.tsindex 83aebde1..e3566957 100644--- a/scripts/test-spaces-save-revisions.ts+++ b/scripts/test-spaces-save-revisions.ts@@ -217,5 +217,80 @@ console.log('\nmain.ts stamps inside the queue for both writes of this file')check(/stampSync\(store, session\)/.test(inPlace), '"Update this file" stamps in the queue\'s prepare too')}+// ---- the in-file revision is recorded in prepare, inside the snapshot ------+// history.ts recordOnSave runs in the same prepare step as the stamp, so the+// revision describes exactly the bytes written and those bytes contain it.+// Recording writes doc.revisions directly — never through commit — so it must+// not advance the store's revision (the write is not stale), not raise the+// unsaved dot, and not change the recovery key (docclass.ts SPACES_NOT_EDIT).+console.log('\nthe in-file revision is recorded in prepare, inside the snapshot')+{+ const { recordOnSave, revisionsOf, applyRevisions, contentOf } = await import('../spaces/src/history.ts')+ const { docContentKey } = await import('../spaces/src/model.ts')+ const p = parseSpace(JSON.stringify({ format: 'bento/spaces', version: 1, docId: 'hist', title: 'Hist', pages: [{ id: 'p', title: 'Page', blocks: [{ id: 'b', type: 'p', html: 'one' }] }] }))+ assert(p.ok)+ const store = new SpacesStore(p.doc)+ const queue = new SaveQueue({ getDocument: () => store.doc, getRevision: () => store.revision })+ const written: any[] = []+ const gates: Array<() => void> = []+ const write = (snapshot: any) => new Promise<'saved'>((resolve) => {+ written.push(JSON.parse(JSON.stringify(snapshot)))+ gates.push(() => resolve('saved'))+ })+ const prepare = () => { recordOnSave(store) }+ const tick = async () => { for (let i = 0; i < 5; i++) await Promise.resolve() }++ store.commit(() => { store.doc.pages[0].blocks[0].html = 'two' })+ const keyBefore = docContentKey(store.doc)+ const revBefore = store.revision+ const a = saveRevision(store, queue, write, prepare)+ // queued behind `a`, asked for NOW — and an edit lands before it starts+ const b = saveRevision(store, queue, write, prepare)+ await tick()+ check(written.length === 1 && revisionsOf(written[0]).length === 1,+ 'the snapshot the write receives contains the revision recorded in its prepare')+ check(JSON.stringify(applyRevisions(revisionsOf(written[0]))) === JSON.stringify(contentOf(written[0])),+ 'and that revision restores exactly the content of the bytes written')+ check(store.revision === revBefore && docContentKey(store.doc) === keyBefore,+ 'recording advanced no store revision and left the recovery key unchanged')+ store.commit(() => { store.doc.pages[0].blocks[0].html = 'three' }) // lands while `a` is in flight+ gates[0]()+ const outA = await a+ await tick()+ check(outA.kind === 'written' && !outA.current, 'the first write is stale (an edit landed after its snapshot)')+ check(written.length === 2 && revisionsOf(written[1]).length === 2,+ 'the save queued behind it recorded at its OWN start: its snapshot carries a second revision')+ check(written[1] && JSON.stringify(applyRevisions(revisionsOf(written[1]))) === JSON.stringify(contentOf(written[1]))+ && written[1].pages[0].blocks[0].html === 'three',+ 'and that revision describes the content as it was when the second write began ("three"), not when it was asked for')+ gates[1]()+ const outB = await b+ check(outB.kind === 'written' && outB.current, 'recording in prepare does not make the write stale')+ check(store.dirty === false, 'the dot goes out: recording a revision did not raise it')++ // a save that changed nothing records nothing, and a read-only store never records+ const c = saveRevision(store, queue, write, prepare)+ await tick(); gates[2]?.()+ await c+ check(revisionsOf(store.doc).length === 2, 'a save with no change since the last revision records none')+ store.readOnly = true+ store.doc.pages[0].blocks[0].html = 'frozen edit'+ check(recordOnSave(store) === null && revisionsOf(store.doc).length === 2, 'a read-only store never records (a frozen file round-trips byte-exact)')+}++// The wiring: ⌘S and "Update this file" record in the queue's prepare, beside+// the stamp. Pinned like #594's rows — moving the call outside the queue (back+// to before saveRevision, where #440 had it) fails here.+console.log('\nmain.ts records the revision inside the queue for both writes of this file')+{+ const { readFileSync } = await import('node:fs')+ const src = readFileSync(new URL('../spaces/src/main.ts', import.meta.url), 'utf8')+ const doSave = src.match(/saveRevision\(store, saves,[\s\S]*?\)\)/)?.[0] ?? ''+ check(/stampSync\(store, session\); recordOnSave\(store\)/.test(doSave), '⌘S records in the prepare step of saveRevision, beside stampSync')+ const inPlace = src.match(/editor\.onUpdateInPlace = async[\s\S]*?saves\.run\(([\s\S]*?)applyUpdateInPlace/)?.[1] ?? ''+ check(/stampSync\(store, session\); recordOnSave\(store\)/.test(inPlace), '"Update this file" records in the queue\'s prepare too')+ check((src.match(/recordOnSave\(|recordRevision\(/g) ?? []).length === 2, 'and nowhere else in main.ts (no second, out-of-queue call)')+}+if (failures) { console.error(`\n${failures} save-race check(s) FAILED`); process.exit(1) }console.log('\nspaces save race: an edit made during a write stays unsaved until a write that holds it lands')diff --git a/scripts/test-spaces.mjs b/scripts/test-spaces.mjsindex 4bfed4f2..14b618d5 100755--- a/scripts/test-spaces.mjs+++ b/scripts/test-spaces.mjs@@ -69,6 +69,7 @@ const RIGS = [{ 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: 'history', file: 'scripts/test-spaces-history.ts', bundle: true },{ name: 'mentions', file: 'scripts/test-spaces-mentions.ts' },{ name: 'size', file: 'scripts/test-spaces-size.mjs' },// Revision tracking has no timezone dependency; the browser rig needs thediff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.mdindex 8b26679a..b575e1c3 100644--- a/spaces/CHANGELOG.md+++ b/spaces/CHANGELOG.md@@ -1298,6 +1298,24 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.the same password, and carries no file-manager preview. A view-only copy thatfollows the live session still says so when it opens.+- **Version history inside the file.** Every save records what changed in the+ document itself, so the history travels with the file to another machine and+ to anyone you send it to. The browser-local timeline is unchanged; **Save ▾ →+ Versions in this file…** sits beside it. Each version shows a one-line+ summary, made in your language when the list opens, and a **Changes** view of+ the words that went and the words that arrived. **Restore** brings back+ everything the space had then: its pages, title, home page, theme, design,+ footnotes and page templates. It is an ordinary edit, so `⌘Z` takes it back,+ and it never changes which document this is, who it is shared with, or the+ history itself. A save costs a few hundred bytes, not a copy of the space;+ history is capped at 128 KB and sixty versions, and past that the oldest+ versions fold together. A password-protected space keeps history too, inside+ the encryption. History remembers text you deleted, and the dialog says so:+ invites and the file carry it, while reading copies, view-only copies, Copy+ document JSON and a page exported as its own space leave it out. **Clear history** removes it.+ Pasting document JSON over the space no longer touches the history, and+ neither does undo.+## [0.1.0] — 2026-08-03First release.diff --git a/spaces/src/docclass.ts b/spaces/src/docclass.tsindex 559d2c9a..ee5d8226 100644--- a/spaces/src/docclass.ts+++ b/spaces/src/docclass.ts@@ -68,6 +68,15 @@ export const SPACES_FIELDS = {const _modeOk: ModeFieldsOk<typeof SPACES_FIELDS> = truevoid _modeOk-/** Content that changes without anyone editing — excluded from the recovery- * key so an autosave of an untouched space is not a phantom edit. */-export const SPACES_NOT_EDIT: ReadonlySet<string> = new Set(['modified'])+/** Fields that change without anyone editing — excluded from the recovery+ * key so an autosave of an untouched space is not a phantom edit.+ *+ * `revisions` is here although the kernel's default counts history as+ * unsaved work. That default exists for history a person makes BETWEEN saves+ * (type's typed revisions, a signature), which only a recovery snapshot can+ * keep. Spaces records a revision only inside a save's prepare step, into+ * the bytes that save writes (history.ts) — so it is never unsaved work, and+ * counting it would raise the recovery banner on every file reopened after a+ * download-save, whose recovery snapshot predates the revision. `trail` is+ * NOT listed: when it is written is its feature's call. */+export const SPACES_NOT_EDIT: ReadonlySet<string> = new Set(['modified', 'revisions'])diff --git a/spaces/src/doccmds.ts b/spaces/src/doccmds.tsindex 2a3b64e3..dedbb2f0 100644--- a/spaces/src/doccmds.ts+++ b/spaces/src/doccmds.ts@@ -28,6 +28,11 @@ import { ICONS } from './icons'import { row, type Menu } from './menus.ts'import { docForExport, parseDoc, uid, type SpacesDoc } from './model'import { restoreInto } from './restoregate'+import {+ revisionsOf, historyIsForeign, changesAt, restoredDoc, clearHistory, historyBytes,+ tooLargeForHistory, type ChangeReport,+} from './history.ts'+import { humanBytes } from './assets'import { duplicateAsNew } from './share.ts'import type { Store } from './store'@@ -72,6 +77,7 @@ export function saveRows(m: Menu, h: DocHost): void {// the document AS DATA — the timeline and the round tripsm.separator()row(m, { icon: ICONS.history, label: t('Version history…'), desc: t('Versions are kept in this browser only — never in the file, never online. Restoring is undoable.'), run: () => openHistory(h) })+ row(m, { icon: ICONS.history, label: t('Versions in this file…'), desc: t('Kept inside the file, one per save, so they travel with it. Restoring is undoable.'), run: () => openFileHistory(h) })row(m, { icon: ICONS.code, label: t('Copy document JSON'), desc: t('Plain JSON of every page — no live-session keys'),run: () => copyJson(h) })row(m, { icon: ICONS.code, label: t('Replace from JSON…'), desc: t('Replaces every page — ⌘Z undoes'),@@ -82,7 +88,7 @@ export function saveRows(m: Menu, h: DocHost): void {/** The labels, in order — what the chrome rig holds the menu to. */export const SAVE_ORDER = ['Save a copy…', 'Duplicate as new space…', 'Export as Markdown…', 'Export page as a space…', 'Export page as Markdown…',- 'Encrypt with password…', 'Version history…', 'Copy document JSON', 'Replace from JSON…', 'Import Markdown…',+ 'Encrypt with password…', 'Version history…', 'Versions in this file…', 'Copy document JSON', 'Replace from JSON…', 'Import Markdown…',]// ---- the commands ---------------------------------------------------------@@ -222,6 +228,126 @@ function openHistory(h: DocHost): void {}))}+/**+ * The timeline INSIDE THE FILE (history.ts) — the one that travels. Read+ * synchronously: it is a field of the document already in memory.+ *+ * A row's summary is DERIVED here, in the reader's language, from the patch;+ * the file stores no sentence. Restore goes through the same gate as the+ * browser-local timeline (restoregate.ts restoreInto): the version is the+ * document's own, but what is applied is still parsed, sanitized and given the+ * live identity, and replaceDoc checkpoints undo so ⌘Z walks it back.+ */+function openFileHistory(h: DocHost): void {+ narrow(h.openOverlay(t('Versions in this file'), (body, close) => {+ const list = el('div', 'sp-ab-versions')+ const foot = el('div')+ body.append(list, foot)+ const render = (): void => {+ list.textContent = ''+ foot.textContent = ''+ const doc = h.store.doc+ const revs = revisionsOf(doc)+ if (!revs.length) {+ list.append(el('p', 'sp-note', historyIsForeign(doc)+ ? t('This file carries a history this version cannot read. It is kept exactly as it arrived.')+ : tooLargeForHistory(doc)+ ? t('This space is too large to keep versions inside the file.')+ : t('No versions yet — one is kept every time you save.')))+ }+ // newest first: "what I had before lunch" is nearer the top+ for (let i = revs.length - 1; i >= 0; i--) {+ const v = revs[i]+ const when = new Date(v.at).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })+ const rep = changesAt(revs, i)+ const item = el('div', 'sp-hist-row')+ const b = el('button', 'sp-ab-version')+ b.type = 'button'+ b.append(el('span', 'sp-ab-when', when), el('span', 'sp-ab-vtag', v.label || summary(rep)), el('span', 'sp-ab-vdo', t('Restore')))+ b.disabled = h.store.readOnly+ b.addEventListener('click', () => {+ if (h.store.readOnly) { h.notice(t('This file is open read-only')); return }+ const next = restoredDoc(h.store.doc, i)+ if (!next || !restoreInto(h.store, JSON.stringify(next))) { h.notice(t('That version could not be read')); return }+ h.repaint()+ close()+ h.notice(t('Restored the version from {when} — ⌘Z undoes it', { when }))+ })+ const show = el('button', 'sp-hist-diff-btn', t('Changes'))+ show.type = 'button'+ show.setAttribute('aria-expanded', 'false')+ let panel: HTMLElement | null = null+ show.addEventListener('click', () => {+ if (panel) { panel.remove(); panel = null; show.setAttribute('aria-expanded', 'false'); return }+ panel = renderDiff(rep)+ item.append(panel)+ show.setAttribute('aria-expanded', 'true')+ })+ const head = el('div', 'sp-hist-head')+ head.append(b, show)+ item.append(head)+ list.append(item)+ }+ const size = historyBytes(doc)+ if (size && revs.length) foot.append(el('p', 'sp-note', t('History takes {size} of this file.', { size: humanBytes(size) })))+ // said in the dialog and not only in the source: a deleted page is still+ // in the file until the budget folds it away+ foot.append(el('p', 'sp-note', t('Versions include text you have deleted. They travel in this file and in invites; reading copies, view-only copies and Copy document JSON leave them out.')))+ if (!h.store.readOnly && revs.length) {+ const confirmBox = el('div')+ const clearBtn = button(t('Clear history…'), () => {+ // IN FLOW, not a popover: the card scrolls (CLAUDE.md hard-won #10)+ clearBtn.disabled = true+ confirmBox.append(+ el('p', 'sp-note', t('The past text goes with them, including anything you deleted. Save the file for it to take effect.')),+ actions(button(t('Cancel'), () => { confirmBox.textContent = ''; clearBtn.disabled = false }), button(t('Clear history'), () => {+ if (clearHistory(h.store.doc)) h.store.setDirty(true)+ render()+ h.notice(t('History removed. Save to write the file without it.'))+ }, true)),+ )+ })+ foot.append(actions(clearBtn), confirmBox)+ }+ }+ render()+ }))+}++/** The one-line summary for a revision, made in the reader's language. */+function summary(rep: ChangeReport): string {+ if (rep.first) return t('First version kept in this file')+ if (rep.pagesChanged || rep.blocksChanged) return t('{p} page(s), {b} block(s) changed', { p: rep.pagesChanged, b: rep.blocksChanged })+ if (rep.fieldsChanged.length) return t('Changes outside the pages — title, design, footnotes or templates')+ return t('Nothing changed')+}++/**+ * A change report, drawn — WORD granularity (history.ts), from the block's+ * TEXT, never its markup. textContent throughout: this is the file's own text.+ */+function renderDiff(rep: ChangeReport): HTMLElement {+ const box = el('div', 'sp-hist-diff')+ if (!rep.pages.length) { box.append(el('p', 'sp-note', t('Nothing changed'))); return box }+ for (const p of rep.pages.slice(0, 12)) {+ const head = el('div', 'sp-hist-page', p.title || t('Untitled'))+ if (p.kind === 'added') head.append(el('span', 'sp-hist-chip', t('New page')))+ else if (p.kind === 'removed') head.append(el('span', 'sp-hist-chip', t('Deleted page')))+ else if (p.wasTitled !== undefined) head.append(el('span', 'sp-hist-chip', t('Renamed from “{title}”', { title: p.wasTitled || t('Untitled') })))+ box.append(head)+ for (const b of p.blocks.slice(0, 20)) {+ const line = el('p', 'sp-hist-line')+ for (const part of b.parts) {+ if (part.text) line.append(el(part.op === 'ins' ? 'ins' : part.op === 'del' ? 'del' : 'span', '', part.text))+ }+ if (!line.childNodes.length) line.append(el('span', 'sp-hist-empty', b.type))+ box.append(line)+ }+ if (p.blocks.length > 20) box.append(el('span', 'sp-hist-chip', '…'))+ }+ return box+}+/*** Paste-and-apply (the counterpart of Copy document JSON). The live session* belongs to THIS document, not to the pasted text: content is imported,diff --git a/spaces/src/history.ts b/spaces/src/history.tsnew file mode 100644index 00000000..d94378be--- /dev/null+++ b/spaces/src/history.ts@@ -0,0 +1,588 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// IN-FILE VERSION HISTORY for bento/spaces.+//+// WHY THIS EXISTS AT ALL. `kernel/src/autosave.ts` already keeps a timeline —+// in IndexedDB, in ONE browser. Mail the file and the history is gone; open it+// on a phone and it never existed. A hosted notes app can only do history on+// its server, and a file you send someone simply cannot have it. So this puts+// the timeline where the rest of the document already is: inside the file,+// under `doc.revisions`.+//+// THE ENVELOPE IS THE KERNEL'S. Every entry is `Revision<SpacesPatch>` from+// kernel/src/docfields.ts — `{ id, at, label?, body }` — the one shape every+// app's history shares (type's body is a whole snapshot; this one is a patch).+// `label` is OPTIONAL and absent unless a person typed one: a label minted by+// the app would be a sentence frozen in its author's UI language and shown to+// every reader of a file that opens in eight. The summary on screen is DERIVED+// from the body at render time (`changesAt`), so the file holds language-free+// data. Every entry read from a file passes `validateRevision` and then this+// module's own body check (`readable`); one that fails makes the WHOLE list+// foreign, and a foreign list is never written over.+//+// WHAT IT COVERS IS READ FROM THE FIELD MAP, not listed here. A revision covers+// every top-level field `SPACES_FIELDS` (docclass.ts) classes as `content`,+// except three kinds that are not the space's writing:+// * `assets` — the bytes. The largest thing in the document by orders of+// magnitude and content-addressed by key, so one photograph would be+// bigger than the whole budget below. A revision references `asset:<key>`;+// restoring a page whose asset was later removed from the pool renders the+// missing-image fallback rather than the picture. (`store.ts` keeps assets+// out of undo snapshots for the same reason.)+// * not-an-edit fields (`SPACES_NOT_EDIT`: `modified`) — bookkeeping.+// * encoding tags (`format`, `version`) — which format the file is in, not+// what it says. A restore never changes them.+// So title, home, theme, footnotes, fonts, templates, journalTemplate, design,+// designs, policy and pages are covered TODAY, and a content field added to the+// map tomorrow joins history with no change here. Identity, mode, capability+// and history fields (docId, readonly, template, collab, revisions, trail) are+// other classes and can never be rolled back by a restore. Everything on a page+// rides inside `pages`: blocks, comments, fields, covers.+//+// WHOLE SPACE, NOT ONE PAGE. A page has a `parent`, can be the `home`, and is+// linked to by id, so a page restored on its own lands in a tree that no+// longer matches it. A revision is the whole space's content.+//+// THE BUDGET. The starter space is ~37 KB of pages, and this file gets EMAILED,+// so a whole snapshot per save is out of the question. A revision stores only+// what CHANGED since the one before it: a top-level field whole when it+// changed, a page's metadata whole when any of it changed, a block whole when+// it changed, and the id ORDER only when the sequence changed. A paragraph+// edited in a 37 KB space costs a few hundred bytes.+//+// Two ceilings (`pruneRevisions`), and going over them TIERS rather than fails:+// Tier 1 under both: every revision kept.+// Tier 2 over one: the OLDEST TWO fold into one — resolution is dropped from+// the distant past first. The fold RE-DERIVES the replacement from+// the state those two produce, so every surviving revision still+// restores exactly what it did.+// Tier 3 a space whose content alone exceeds the budget keeps none; the+// dialog says so.+// The constants and the fold are this module's FOR NOW. The kernel's shared+// fold module lands after DocStore; HISTORY_MAX / HISTORY_BUDGET are named and+// valued as the kernel's defaults, and `pruneRevisions` is the one function to+// swap for it — the call sites do not change.+//+// THE INVARIANT: restore(N) == the content that was saved at revision N,+// on the SERIALIZED bytes. `record` diffs against the state the existing chain+// folds to, so the chain can never drift from what it claims to describe.+//+// WHERE RECORDING HAPPENS: inside the save queue's PREPARE step (main.ts,+// beside stampSync), after any write ahead of it and immediately before the+// snapshot is copied — so the revision describes exactly the bytes written,+// and the bytes written contain it. Recording writes `doc.revisions` directly+// (never `store.commit`), so it neither advances the store's revision (the+// write is not stale) nor raises the unsaved dot. `revisions` is also out of+// the recovery key (docclass.ts SPACES_NOT_EDIT): it changes only at a save,+// inside the bytes that save writes, so it is never the unsaved work a+// recovery snapshot exists to keep.+//+// ENCRYPTION. `revisions` is a field of the document, so it is inside the+// `bento/enc` envelope, encrypted by the same pass as the pages it describes.+// Nothing here touches IndexedDB. An encrypted space therefore HAS history —+// which it never did, because the only mechanism was the browser-local one+// that must refuse it.+//+// WHAT HISTORY DISCLOSES: a deleted page's text is still in the file, in the+// revision that last held it, until the budget folds it away. The kernel's copy+// table keeps history in the file, a duplicate and an invite, and DROPS it from+// every copy handed to a reader (reading copy, view-only copy, package, link,+// template, Copy document JSON); a page extract drops it too (portable.ts).+// "Clear history" is in the dialog, and the dialog says this in words.+//+// ADDITIVITY (PLATFORM §3). No revisions = no key at all, never `[]`. Unknown+// fields on an entry or its body survive a later save untouched.++import { validateRevision, type Revision, type FieldsOfClass } from '../../kernel/src/docfields.ts'+import { SPACES_FIELDS, SPACES_NOT_EDIT } from './docclass.ts'+import { uid, type SpacesDoc, type Page, type Block } from './model.ts'+import { textOf } from './sanitize.ts'++/** Serialized bytes of `doc.revisions` above which the oldest entries fold —+ * the kernel fold module's default. */+export const HISTORY_BUDGET = 128 * 1024++/** Entries kept, however small they are — the kernel fold module's default. */+export const HISTORY_MAX = 60++/** How many of the oldest entries one fold step merges. */+export const HISTORY_FOLD = 2++/** Content-class fields that are NOT the space's writing: the asset pool+ * (bytes, never duplicated) and the format's own encoding tags. */+const NOT_COVERED = new Set<string>(['assets', 'format', 'version'])++/** The content-class field names, as a type — so a field classed otherwise+ * can never be named here. */+type ContentField = FieldsOfClass<typeof SPACES_FIELDS, 'content'>++/**+ * The top-level fields a revision covers, in the map's declaration order —+ * which is also the key order `contentOf` writes, so two runs over the same+ * content produce the same bytes. DERIVED: a new content field joins history+ * without an edit here.+ */+export const HISTORY_FIELDS: readonly ContentField[] = (Object.keys(SPACES_FIELDS) as Array<keyof typeof SPACES_FIELDS>)+ .filter((k): k is ContentField =>+ SPACES_FIELDS[k] === 'content' && !NOT_COVERED.has(k) && !SPACES_NOT_EDIT.has(k))++/** The covered fields other than `pages`, which the patch carries per page. */+const DOC_FIELDS: readonly string[] = HISTORY_FIELDS.filter((k) => k !== 'pages')++/** The part of a space that history covers: the covered top-level fields that+ * are present, plus `pages`. */+export type SpaceContent = { pages: Page[] } & Record<string, unknown>++/** One page's change at one revision. */+export interface RevPage {+ id: string+ /** the page no longer exists as of this revision */+ gone?: true+ /** the whole page WITHOUT its blocks (`blocks: []`, in its original key+ * slot, so a rebuilt page serializes to the same bytes) — present only+ * when some page field changed */+ meta?: Page+ /** blocks added or changed, whole */+ put?: Block[]+ /** every block id, in order — present only when the sequence changed */+ order?: string[]+}++/** The body of a spaces revision: the change from the revision before it. */+export interface SpacesPatch {+ /** covered top-level fields (not `pages`) that changed, each whole */+ doc?: Record<string, unknown>+ /** covered top-level fields that became absent */+ unset?: string[]+ /** every page id, in order — present only when the sequence changed */+ order?: string[]+ pages?: RevPage[]+}++/** One recorded revision — the kernel's envelope around this app's patch. */+export type SpacesRevision = Revision<SpacesPatch>++const j = (v: unknown): string => JSON.stringify(v)+const clone = <T>(v: T): T => JSON.parse(JSON.stringify(v)) as T+const bytes = (v: unknown): number => new TextEncoder().encode(j(v) ?? '').length+const isObj = (v: unknown): v is Record<string, unknown> =>+ !!v && typeof v === 'object' && !Array.isArray(v)+const isStrs = (v: unknown): v is string[] => Array.isArray(v) && v.every((s) => typeof s === 'string')++/** A content state in the one key order this module writes: the covered+ * fields that are present, in HISTORY_FIELDS order, `pages` in its slot. */+function canon(fields: Record<string, unknown>, pages: Page[]): SpaceContent {+ const out: Record<string, unknown> = {}+ for (const k of HISTORY_FIELDS) {+ if (k === 'pages') out.pages = pages+ else if (fields[k] !== undefined) out[k] = fields[k]+ }+ return out as SpaceContent+}++/** A page with its blocks emptied, key order untouched. */+function metaOf(p: Page): Page {+ return { ...p, blocks: [] as Block[] } as Page+}++/** The content projection of a live document, detached from it. */+export function contentOf(doc: SpacesDoc): SpaceContent {+ const d = doc as unknown as Record<string, unknown>+ return clone(canon(d, Array.isArray(doc.pages) ? doc.pages : []))+}++/** The non-page part of a content state, keyed. */+function fieldsOf(c: SpaceContent | null): Record<string, unknown> {+ const out: Record<string, unknown> = {}+ if (!c) return out+ for (const k of DOC_FIELDS) if (c[k] !== undefined) out[k] = c[k]+ return out+}++// ---- reading what a file carries ----------------------------------------++/** A page patch this build can apply. */+function readablePage(p: unknown): boolean {+ if (!isObj(p) || typeof p.id !== 'string') return false+ if (p.gone !== undefined && p.gone !== true) return false+ if (p.meta !== undefined && !(isObj(p.meta) && p.meta.id === p.id)) return false+ if (p.put !== undefined && !(Array.isArray(p.put) && p.put.every((b) => isObj(b) && typeof b.id === 'string'))) return false+ if (p.order !== undefined && !isStrs(p.order)) return false+ return true+}++/**+ * The kernel's envelope check, then this app's body check. Every entry read+ * from a file passes this before anything folds it — a malformed entry must+ * not crash a reader, and must not be "repaired" by being written over.+ */+export function readable(e: unknown): e is SpacesRevision {+ if (!validateRevision(e)) return false+ const b = (e as { body: unknown }).body+ if (!isObj(b)) return false+ if (b.doc !== undefined && !isObj(b.doc)) return false+ if (b.unset !== undefined && !isStrs(b.unset)) return false+ if (b.order !== undefined && !isStrs(b.order)) return false+ if (b.pages !== undefined && !(Array.isArray(b.pages) && b.pages.every(readablePage))) return false+ return true+}++/**+ * True when `doc.revisions` holds something this build cannot read: not an+ * array, or any entry that fails `readable`. Such a list is LEFT ALONE —+ * never recorded onto, never pruned, never cleared by a save — because a+ * patch chain cannot be extended past a link it cannot read.+ */+export function historyIsForeign(doc: SpacesDoc): boolean {+ const r = (doc as { revisions?: unknown }).revisions+ if (r === undefined) return false+ return !Array.isArray(r) || !r.every(readable)+}++/** `doc.revisions`, when this build can read every entry of it; else none. */+export function revisionsOf(doc: SpacesDoc): SpacesRevision[] {+ const r = (doc as { revisions?: unknown }).revisions+ if (!Array.isArray(r) || !r.every(readable)) return []+ return r as SpacesRevision[]+}++// ---- the chain -----------------------------------------------------------++/**+ * The change from `prev` (or from nothing) to `next`.+ *+ * Everything stored is stored WHOLE, so applying it rebuilds objects whose key+ * order matches the originals; the saving is in what is left out.+ */+export function diffContent(prev: SpaceContent | null, next: SpaceContent): SpacesPatch {+ const out: SpacesPatch = {}+ const was = fieldsOf(prev), now = fieldsOf(next)+ const set: Record<string, unknown> = {}+ const unset: string[] = []+ for (const k of DOC_FIELDS) {+ if (now[k] === undefined) { if (was[k] !== undefined) unset.push(k); continue }+ if (j(now[k]) !== j(was[k])) set[k] = now[k]+ }+ if (Object.keys(set).length) out.doc = set+ if (unset.length) out.unset = unset++ const prevPages = new Map((prev?.pages ?? []).map((p) => [p.id, p]))+ const nextIds = next.pages.map((p) => p.id)+ const prevIds = (prev?.pages ?? []).map((p) => p.id)+ if (j(nextIds) !== j(prevIds)) out.order = nextIds++ const patches: RevPage[] = []+ for (const p of next.pages) {+ const q = prevPages.get(p.id)+ const patch: RevPage = { id: p.id }+ const meta = metaOf(p)+ if (!q || j(metaOf(q)) !== j(meta)) patch.meta = meta+ const before = new Map((q?.blocks ?? []).map((b) => [b.id, b]))+ const put = (p.blocks ?? []).filter((b) => {+ const o = before.get(b.id)+ return !o || j(o) !== j(b)+ })+ if (put.length) patch.put = put+ const bIds = (p.blocks ?? []).map((b) => b.id)+ if (j(bIds) !== j((q?.blocks ?? []).map((b) => b.id))) patch.order = bIds+ if (patch.meta || patch.put || patch.order) patches.push(patch)+ }+ const nextSet = new Set(nextIds)+ for (const id of prevPages.keys()) if (!nextSet.has(id)) patches.push({ id, gone: true })+ if (patches.length) out.pages = patches+ return out+}++const isEmpty = (b: SpacesPatch): boolean => !b.doc && !b.unset && !b.order && !b.pages++/** Fold one patch onto a state. Only the fields this build knows are read. */+function applyOne(cur: SpaceContent | null, b: SpacesPatch): SpaceContent {+ const fields = fieldsOf(cur)+ for (const [k, v] of Object.entries(b.doc ?? {})) if (DOC_FIELDS.includes(k)) fields[k] = v+ for (const k of b.unset ?? []) delete fields[k]++ const prevPages = new Map((cur?.pages ?? []).map((p) => [p.id, p]))+ const ids = b.order ?? (cur?.pages ?? []).map((p) => p.id)+ const built = new Map<string, Page | null>()+ for (const patch of b.pages ?? []) {+ if (patch.gone) { built.set(patch.id, null); continue }+ const q = prevPages.get(patch.id)+ const base = patch.meta ?? (q ? metaOf(q) : ({ id: patch.id, title: '', blocks: [] } as Page))+ const page = clone(base)+ const by = new Map((q?.blocks ?? []).map((x) => [x.id, x]))+ for (const x of patch.put ?? []) by.set(x.id, x)+ const bIds = patch.order ?? (q?.blocks ?? []).map((x) => x.id)+ page.blocks = bIds.map((i) => by.get(i)).filter((x): x is Block => !!x)+ built.set(patch.id, page)+ }+ const pages: Page[] = []+ for (const id of ids) {+ const p = built.has(id) ? built.get(id) : prevPages.get(id)+ if (p) pages.push(p)+ }+ return clone(canon(fields, pages))+}++/**+ * The content as of revision `upTo` (an index; default the last). This is+ * `restore`: one way to read the chain, and `record` writes against it.+ */+export function applyRevisions(revs: readonly SpacesRevision[], upTo = revs.length - 1): SpaceContent | null {+ if (!revs.length || upTo < 0) return null+ let cur: SpaceContent | null = null+ for (let i = 0; i <= upTo && i < revs.length; i++) cur = applyOne(cur, revs[i].body)+ return cur+}++/**+ * Bring a list back under both ceilings, tiering rather than failing. The+ * fold RE-DERIVES the replacing entry from the state the oldest two produce,+ * so it is a complete description of that state by construction.+ *+ * THE SEAM for the kernel's fold module (after DocStore): same inputs, same+ * defaults, same contract — swap this body, not its callers.+ */+export function pruneRevisions(+ revs: readonly SpacesRevision[],+ budget = HISTORY_BUDGET,+ max = HISTORY_MAX,+): SpacesRevision[] {+ const out = revs.slice()+ while (out.length > 1 && (out.length > max || bytes(out) > budget)) {+ const n = Math.min(HISTORY_FOLD, out.length)+ const state = applyRevisions(out, n - 1)!+ const keep = out[n - 1]+ const folded: SpacesRevision = {+ id: keep.id,+ at: keep.at,+ ...(keep.label !== undefined ? { label: keep.label } : {}),+ body: diffContent(null, state),+ }+ out.splice(0, n, folded)+ }+ // Tier 3: the space's own content will not fit. Half a history is worse+ // than none, because only one of the two is honest about what it can give.+ if (out.length === 1 && bytes(out) > budget) return []+ return out+}++/**+ * Record the document's current content as a revision, in place.+ *+ * Returns the entry if one was written. `null` means nothing changed since the+ * last revision (a save that changed nothing writes no bytes), that+ * `doc.revisions` is foreign and must not be overwritten, or that the space is+ * too large to keep any (tier 3 — the key is then removed).+ */+export function recordRevision(doc: SpacesDoc, label?: string): SpacesRevision | null {+ if (historyIsForeign(doc)) return null+ const revs = revisionsOf(doc)+ const body = diffContent(applyRevisions(revs), contentOf(doc))+ if (isEmpty(body)) return null+ const rev: SpacesRevision = {+ id: uid('rev'),+ at: new Date().toISOString(),+ ...(label ? { label } : {}),+ body,+ }+ const kept = pruneRevisions([...revs, rev])+ if (kept.length) doc.revisions = kept+ else delete doc.revisions+ return kept.length ? rev : null+}++/**+ * What a save calls, in the save queue's prepare: record unless the store is+ * read-only. A frozen file round-trips byte-exact, and a reading copy or a+ * view-only follower does not author history.+ */+export function recordOnSave(store: { readonly readOnly: boolean; readonly doc: SpacesDoc }): SpacesRevision | null {+ if (store.readOnly) return null+ return recordRevision(store.doc)+}++/** Remove history from a document. No key, never an empty array. A foreign+ * list is not ours to remove either. */+export function clearHistory(doc: SpacesDoc): boolean {+ if (historyIsForeign(doc)) return false+ delete doc.revisions+ return true+}++/**+ * The document with the content of revision `index` and everything else —+ * identity, assets, collaboration, modes, the history itself and any field+ * this build does not know — left as it is. A covered field absent at `index`+ * is removed. The caller installs it through the restore gate+ * (restoregate.ts restoreInto), which sanitizes it and keeps live identity.+ */+export function restoredDoc(doc: SpacesDoc, index: number): SpacesDoc | null {+ const state = applyRevisions(revisionsOf(doc), index)+ if (!state) return null+ const out = clone(doc) as unknown as Record<string, unknown>+ for (const k of HISTORY_FIELDS) {+ if (state[k] !== undefined) out[k] = state[k]+ else delete out[k]+ }+ return out as unknown as SpacesDoc+}++/** Serialized bytes history currently costs this file. */+export function historyBytes(doc: SpacesDoc): number {+ const r = (doc as { revisions?: unknown }).revisions+ return r === undefined ? 0 : bytes(r)+}++/** Would this space's content alone overflow the budget (tier 3)? */+export function tooLargeForHistory(doc: SpacesDoc): boolean {+ return bytes([{ id: 'rev', at: new Date(0).toISOString(), body: diffContent(null, contentOf(doc)) }]) > HISTORY_BUDGET+}++// ---------------------------------------------------------------------------+// The diff view.+//+// GRANULARITY IS WORDS, for the reason type/src/redline.ts gives: a line diff+// calls a reflowed paragraph wholly rewritten, and a character diff marks+// "30" → "60" as one glyph nobody can see. NOT IMPORTED from there — that is+// bento/type's runtime; the reasoning is cited, not the code.+// ---------------------------------------------------------------------------++/** Words and the whitespace between them, so a join is lossless. */+export function words(text: string): string[] {+ return text.match(/\s+|[^\s]+/g) ?? []+}++export interface DiffPart { op: 'eq' | 'del' | 'ins'; text: string }++/** Above this many token PAIRS the LCS table is not built; the block is+ * reported as replaced whole rather than freezing the dialog. */+const LCS_CAP = 400_000++/** Word-level diff, returned as runs. */+export function diffWords(a: string, b: string): DiffPart[] {+ const A0 = words(a), B0 = words(b)+ if (!A0.length && !B0.length) return []+ let s = 0+ while (s < A0.length && s < B0.length && A0[s] === B0[s]) s+++ let e = 0+ while (e < A0.length - s && e < B0.length - s && A0[A0.length - 1 - e] === B0[B0.length - 1 - e]) e+++ const A = A0.slice(s, A0.length - e)+ const B = B0.slice(s, B0.length - e)+ const parts: DiffPart[] = []+ const push = (op: DiffPart['op'], text: string) => {+ if (!text) return+ const last = parts[parts.length - 1]+ if (last && last.op === op) last.text += text+ else parts.push({ op, text })+ }+ push('eq', A0.slice(0, s).join(''))+ if (A.length * B.length > LCS_CAP) {+ push('del', A.join(''))+ push('ins', B.join(''))+ } else {+ const N = A.length, M = B.length+ const lcs: Uint32Array[] = []+ for (let i = 0; i <= N; i++) lcs.push(new Uint32Array(M + 1))+ for (let i = N - 1; i >= 0; i--)+ for (let k = M - 1; k >= 0; k--)+ lcs[i][k] = A[i] === B[k] ? lcs[i + 1][k + 1] + 1 : Math.max(lcs[i + 1][k], lcs[i][k + 1])+ let i = 0, k = 0+ while (i < N && k < M) {+ if (A[i] === B[k]) { push('eq', A[i]); i++; k++ }+ else if (lcs[i + 1][k] >= lcs[i][k + 1]) { push('del', A[i]); i++ }+ else { push('ins', B[k]); k++ }+ }+ push('del', A.slice(i).join(''))+ push('ins', B.slice(k).join(''))+ }+ push('eq', A0.slice(A0.length - e).join(''))+ return parts+}++export interface BlockChange {+ id: string+ kind: 'added' | 'removed' | 'changed'+ /** the block's type, for a label when there is no text to show */+ type: string+ parts: DiffPart[]+}++export interface PageChange {+ id: string+ /** the title AFTER the change, or before it when the page was removed */+ title: string+ kind: 'added' | 'removed' | 'changed'+ /** set when the title itself changed */+ wasTitled?: string+ blocks: BlockChange[]+}++export interface ChangeReport {+ pages: PageChange[]+ /** counts, for the one-line summary the list shows */+ pagesChanged: number+ blocksChanged: number+ /** covered top-level fields (not pages) that changed — names, never text */+ fieldsChanged: string[]+ /** the first revision: there is nothing before it to compare with */+ first: boolean+}++const blockText = (b: Block): string => {+ if (Array.isArray(b.rows)) return b.rows.map((r) => r.map((c) => textOf(c)).join('\t')).join('\n')+ const t = textOf(b.html)+ return t || String(b.caption ?? b.alt ?? '')+}++/** What changed between two content states, ready to render. */+export function compareContent(from: SpaceContent | null, to: SpaceContent | null): ChangeReport {+ const rep: ChangeReport = { pages: [], pagesChanged: 0, blocksChanged: 0, fieldsChanged: [], first: !from }+ if (!to) return rep+ if (from) {+ const a = fieldsOf(from), b = fieldsOf(to)+ rep.fieldsChanged = DOC_FIELDS.filter((k) => j(a[k]) !== j(b[k]))+ }+ const was = new Map((from?.pages ?? []).map((p) => [p.id, p]))+ for (const p of to.pages) {+ const q = was.get(p.id)+ const blocks: BlockChange[] = []+ const wasBlocks = new Map((q?.blocks ?? []).map((b) => [b.id, b]))+ for (const b of p.blocks ?? []) {+ const o = wasBlocks.get(b.id)+ if (!o) { blocks.push({ id: b.id, kind: 'added', type: b.type, parts: diffWords('', blockText(b)) }); continue }+ if (j(o) === j(b)) continue+ blocks.push({ id: b.id, kind: 'changed', type: b.type, parts: diffWords(blockText(o), blockText(b)) })+ }+ const live = new Set((p.blocks ?? []).map((b) => b.id))+ for (const o of q?.blocks ?? []) {+ if (!live.has(o.id)) blocks.push({ id: o.id, kind: 'removed', type: o.type, parts: diffWords(blockText(o), '') })+ }+ if (!q) rep.pages.push({ id: p.id, title: p.title, kind: 'added', blocks })+ else if (blocks.length || j(metaOf(q)) !== j(metaOf(p))) {+ rep.pages.push({+ id: p.id, title: p.title, kind: 'changed',+ ...(q.title !== p.title ? { wasTitled: q.title } : {}),+ blocks,+ })+ }+ }+ const live = new Set(to.pages.map((p) => p.id))+ for (const q of from?.pages ?? []) {+ if (live.has(q.id)) continue+ rep.pages.push({+ id: q.id, title: q.title, kind: 'removed',+ blocks: (q.blocks ?? []).map((b) => ({+ id: b.id, kind: 'removed' as const, type: b.type, parts: diffWords(blockText(b), ''),+ })),+ })+ }+ rep.pagesChanged = rep.pages.length+ rep.blocksChanged = rep.pages.reduce((n, p) => n + p.blocks.length, 0)+ return rep+}++/** What one revision changed, against the one before it. */+export function changesAt(revs: readonly SpacesRevision[], index: number): ChangeReport {+ return compareContent(applyRevisions(revs, index - 1), applyRevisions(revs, index))+}diff --git a/spaces/src/i18n/de.ts b/spaces/src/i18n/de.tsindex 073e007c..5d301d23 100644--- a/spaces/src/i18n/de.ts+++ b/spaces/src/i18n/de.ts@@ -947,4 +947,23 @@ export const de: Catalog = {"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…",+ "Changes": "Änderungen",+ "Clear history": "Verlauf löschen",+ "Deleted page": "Gelöschte Seite",+ "History removed. Save to write the file without it.": "Verlauf gelöscht. Speichere, um die Datei ohne ihn zu schreiben.",+ "History takes {size} of this file.": "Der Verlauf belegt {size} dieser Datei.",+ "No versions yet — one is kept every time you save.": "Noch keine Versionen — bei jedem Speichern wird eine aufbewahrt.",+ "Nothing changed": "Nichts hat sich geändert",+ "Renamed from “{title}”": "Umbenannt von „{title}“",+ "The past text goes with them, including anything you deleted. Save the file for it to take effect.": "Der Text von früher geht mit ihnen — auch das, was du gelöscht hast. Speichere die Datei, damit es wirksam wird.",+ "This file carries a history this version cannot read. It is kept exactly as it arrived.": "Diese Datei bringt einen Verlauf mit, den diese Version nicht lesen kann. Er bleibt genau so, wie er ankam.",+ "Versions in this file": "Versionen in dieser Datei",+ "{p} page(s), {b} block(s) changed": "{p} Seite(n), {b} Block/Blöcke geändert",+ "Versions in this file…": "Versionen in dieser Datei…",+ "Kept inside the file, one per save, so they travel with it. Restoring is undoable.": "In der Datei aufbewahrt, eine pro Speichern, und reisen mit ihr. Wiederherstellen lässt sich rückgängig machen.",+ "This space is too large to keep versions inside the file.": "Dieser Bereich ist zu groß, um Versionen in der Datei aufzubewahren.",+ "Versions include text you have deleted. They travel in this file and in invites; reading copies, view-only copies and Copy document JSON leave them out.": "Versionen enthalten auch Text, den du gelöscht hast. Sie reisen in dieser Datei und in Einladungen mit; Lesekopien, Nur-Ansehen-Kopien und „Dokument-JSON kopieren“ lassen sie weg.",+ "Clear history…": "Verlauf löschen…",+ "First version kept in this file": "Erste in dieser Datei aufbewahrte Version",+ "Changes outside the pages — title, design, footnotes or templates": "Änderungen außerhalb der Seiten — Titel, Gestaltung, Fußnoten oder Vorlagen",}diff --git a/spaces/src/i18n/es.ts b/spaces/src/i18n/es.tsindex 9f883e3f..33ade92a 100644--- a/spaces/src/i18n/es.ts+++ b/spaces/src/i18n/es.ts@@ -947,4 +947,23 @@ export const es: Catalog = {"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…",+ "Changes": "Cambios",+ "Clear history": "Borrar el historial",+ "Deleted page": "Página eliminada",+ "History removed. Save to write the file without it.": "Historial borrado. Guarda para escribir el archivo sin él.",+ "History takes {size} of this file.": "El historial ocupa {size} de este archivo.",+ "No versions yet — one is kept every time you save.": "Aún no hay versiones: se guarda una cada vez que guardas.",+ "Nothing changed": "No cambió nada",+ "Renamed from “{title}”": "Renombrada desde «{title}»",+ "The past text goes with them, including anything you deleted. Save the file for it to take effect.": "El texto del pasado se va con ellas, incluido lo que hayas borrado. Guarda el archivo para que surta efecto.",+ "This file carries a history this version cannot read. It is kept exactly as it arrived.": "Este archivo trae un historial que esta versión no sabe leer. Se conserva tal como llegó.",+ "Versions in this file": "Versiones dentro de este archivo",+ "{p} page(s), {b} block(s) changed": "{p} página(s), {b} bloque(s) con cambios",+ "Versions in this file…": "Versiones dentro de este archivo…",+ "Kept inside the file, one per save, so they travel with it. Restoring is undoable.": "Se guardan dentro del archivo, una por cada guardado, y viajan con él. Restaurar se puede deshacer.",+ "This space is too large to keep versions inside the file.": "Este espacio es demasiado grande para guardar versiones dentro del archivo.",+ "Versions include text you have deleted. They travel in this file and in invites; reading copies, view-only copies and Copy document JSON leave them out.": "Las versiones incluyen texto que has borrado. Viajan en este archivo y en las invitaciones; las copias de lectura, las copias de solo ver y «Copiar JSON del documento» las dejan fuera.",+ "Clear history…": "Borrar el historial…",+ "First version kept in this file": "Primera versión guardada en este archivo",+ "Changes outside the pages — title, design, footnotes or templates": "Cambios fuera de las páginas: título, diseño, notas al pie o plantillas",}diff --git a/spaces/src/i18n/fr.ts b/spaces/src/i18n/fr.tsindex 4e5af7c5..222308ed 100644--- a/spaces/src/i18n/fr.ts+++ b/spaces/src/i18n/fr.ts@@ -947,4 +947,23 @@ export const fr: Catalog = {"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…",+ "Changes": "Modifications",+ "Clear history": "Effacer l’historique",+ "Deleted page": "Page supprimée",+ "History removed. Save to write the file without it.": "Historique effacé. Enregistrez pour écrire le fichier sans lui.",+ "History takes {size} of this file.": "L’historique occupe {size} de ce fichier.",+ "No versions yet — one is kept every time you save.": "Pas encore de versions — une est conservée à chaque enregistrement.",+ "Nothing changed": "Rien n’a changé",+ "Renamed from “{title}”": "Renommée depuis « {title} »",+ "The past text goes with them, including anything you deleted. Save the file for it to take effect.": "Le texte du passé part avec elles, y compris ce que vous avez supprimé. Enregistrez le fichier pour que cela prenne effet.",+ "This file carries a history this version cannot read. It is kept exactly as it arrived.": "Ce fichier contient un historique que cette version ne sait pas lire. Il est conservé tel qu’il est arrivé.",+ "Versions in this file": "Versions dans ce fichier",+ "{p} page(s), {b} block(s) changed": "{p} page(s), {b} bloc(s) modifiés",+ "Versions in this file…": "Versions dans ce fichier…",+ "Kept inside the file, one per save, so they travel with it. Restoring is undoable.": "Conservées dans le fichier, une par enregistrement, elles voyagent avec lui. La restauration peut être annulée.",+ "This space is too large to keep versions inside the file.": "Cet espace est trop volumineux pour conserver des versions dans le fichier.",+ "Versions include text you have deleted. They travel in this file and in invites; reading copies, view-only copies and Copy document JSON leave them out.": "Les versions contiennent du texte que vous avez supprimé. Elles voyagent dans ce fichier et dans les invitations ; les copies de lecture, les copies en lecture seule et « Copier le JSON du document » les laissent de côté.",+ "Clear history…": "Effacer l’historique…",+ "First version kept in this file": "Première version conservée dans ce fichier",+ "Changes outside the pages — title, design, footnotes or templates": "Modifications hors des pages — titre, design, notes de bas de page ou modèles",}diff --git a/spaces/src/i18n/it.ts b/spaces/src/i18n/it.tsindex 3bd036a4..a6e7a7e5 100644--- a/spaces/src/i18n/it.ts+++ b/spaces/src/i18n/it.ts@@ -947,4 +947,23 @@ export const it: Catalog = {"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…",+ "Changes": "Modifiche",+ "Clear history": "Cancella la cronologia",+ "Deleted page": "Pagina eliminata",+ "History removed. Save to write the file without it.": "Cronologia cancellata. Salva per scrivere il file senza di essa.",+ "History takes {size} of this file.": "La cronologia occupa {size} di questo file.",+ "No versions yet — one is kept every time you save.": "Ancora nessuna versione: ne viene tenuta una a ogni salvataggio.",+ "Nothing changed": "Non è cambiato nulla",+ "Renamed from “{title}”": "Rinominata da «{title}»",+ "The past text goes with them, including anything you deleted. Save the file for it to take effect.": "Il testo del passato se ne va con esse, compreso ciò che hai eliminato. Salva il file perché abbia effetto.",+ "This file carries a history this version cannot read. It is kept exactly as it arrived.": "Questo file porta una cronologia che questa versione non sa leggere. È conservata esattamente com’è arrivata.",+ "Versions in this file": "Versioni in questo file",+ "{p} page(s), {b} block(s) changed": "{p} pagina/e, {b} blocco/i modificati",+ "Versions in this file…": "Versioni in questo file…",+ "Kept inside the file, one per save, so they travel with it. Restoring is undoable.": "Conservate nel file, una per salvataggio, viaggiano con esso. Il ripristino si può annullare.",+ "This space is too large to keep versions inside the file.": "Questo spazio è troppo grande per conservare versioni nel file.",+ "Versions include text you have deleted. They travel in this file and in invites; reading copies, view-only copies and Copy document JSON leave them out.": "Le versioni includono testo che hai eliminato. Viaggiano in questo file e negli inviti; le copie di lettura, le copie di sola visualizzazione e «Copia JSON del documento» le escludono.",+ "Clear history…": "Cancella la cronologia…",+ "First version kept in this file": "Prima versione conservata in questo file",+ "Changes outside the pages — title, design, footnotes or templates": "Modifiche fuori dalle pagine: titolo, design, note a piè di pagina o modelli",}diff --git a/spaces/src/i18n/ja.ts b/spaces/src/i18n/ja.tsindex 1bfb76f8..83d40bfc 100644--- a/spaces/src/i18n/ja.ts+++ b/spaces/src/i18n/ja.ts@@ -947,4 +947,23 @@ export const ja: Catalog = {"Previous": "前へ","Reading copy saved — it opens as a document, with no keys and no comments": "読むためのコピーを保存しました — 鍵もコメントもない、読むためのドキュメントとして開きます","Save a reading copy…": "読むためのコピーを保存…",+ "Changes": "変更点",+ "Clear history": "履歴を削除",+ "Deleted page": "削除されたページ",+ "History removed. Save to write the file without it.": "履歴を削除しました。保存すると、履歴のないファイルが書き出されます。",+ "History takes {size} of this file.": "履歴はこのファイルの {size} を使っています。",+ "No versions yet — one is kept every time you save.": "まだバージョンはありません。保存するたびに 1 つ記録されます。",+ "Nothing changed": "変更はありません",+ "Renamed from “{title}”": "「{title}」から名前を変更",+ "The past text goes with them, including anything you deleted. Save the file for it to take effect.": "過去の本文も一緒に消えます。削除したものも含めてです。反映するにはファイルを保存してください。",+ "This file carries a history this version cannot read. It is kept exactly as it arrived.": "このファイルには、このバージョンでは読めない履歴が入っています。届いたときのまま保持されます。",+ "Versions in this file": "このファイルの中のバージョン",+ "{p} page(s), {b} block(s) changed": "{p} ページ・{b} ブロックが変更",+ "Versions in this file…": "このファイルの中のバージョン…",+ "Kept inside the file, one per save, so they travel with it. Restoring is undoable.": "保存するたびに 1 つ、ファイルの中に記録され、ファイルと一緒に移動します。復元は取り消せます。",+ "This space is too large to keep versions inside the file.": "このスペースは大きすぎるため、ファイルの中にバージョンを保持できません。",+ "Versions include text you have deleted. They travel in this file and in invites; reading copies, view-only copies and Copy document JSON leave them out.": "バージョンには、削除した本文も含まれます。このファイルと招待には含まれますが、閲覧用コピー、表示専用コピー、「ドキュメント JSON をコピー」には含まれません。",+ "Clear history…": "履歴を削除…",+ "First version kept in this file": "このファイルに記録された最初のバージョン",+ "Changes outside the pages — title, design, footnotes or templates": "ページ以外の変更 — タイトル、デザイン、脚注、テンプレート",}diff --git a/spaces/src/i18n/packed.ts b/spaces/src/i18n/packed.tsindex 4ef81a6b..7b105842 100644--- a/spaces/src/i18n/packed.ts+++ b/spaces/src/i18n/packed.ts@@ -146,6 +146,8 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Change the shape of this canvas": ["このキャンバスの形を変更","更改此画布的形状","變更此畫布的形狀","Cambiar la forma de este lienzo","Changer la forme de ce canevas","Form dieser Leinwand ändern","Cambia la forma di questa tela","Alterar o formato desta tela"],"Change this page's icon": ["このページのアイコンを変更","更改此页面的图标","變更此頁面的圖示","Cambiar el icono de esta página","Changer l’icône de cette page","Symbol dieser Seite ändern","Cambia l’icona di questa pagina","Mudar o ícone desta página"],"Change {field}": ["{field}を変更","更改{field}","變更{field}","Cambiar {field}","Modifier {field}","{field} ändern","Cambia {field}","Alterar {field}"],+ "Changes": ["変更点","改动","變更","Cambios","Modifications","Änderungen","Modifiche","Alterações"],+ "Changes outside the pages — title, design, footnotes or templates": ["ページ以外の変更 — タイトル、デザイン、脚注、テンプレート","页面之外的改动——标题、设计、脚注或模板","頁面之外的變更——標題、設計、註腳或範本","Cambios fuera de las páginas: título, diseño, notas al pie o plantillas","Modifications hors des pages — titre, design, notes de bas de page ou modèles","Änderungen außerhalb der Seiten — Titel, Gestaltung, Fußnoten oder Vorlagen","Modifiche fuori dalle pagine: titolo, design, note a piè di pagina o modelli","Alterações fora das páginas — título, design, notas de rodapé ou modelos"],"Chart": ["グラフ","图表","圖表","Gráfico","Graphique","Diagramm","Grafico","Gráfico"],"Check for updates": ["更新を確認","检查更新","檢查更新","Buscar actualizaciones","Rechercher des mises à jour","Nach Updates suchen","Cerca aggiornamenti","Verificar atualizações"],"Check for updates automatically at launch": ["起動時に自動で更新を確認","启动时自动检查更新","啟動時自動檢查更新","Buscar actualizaciones automáticamente al iniciar","Rechercher automatiquement les mises à jour au démarrage","Beim Start automatisch nach Updates suchen","Cerca aggiornamenti automaticamente all'avvio","Verificar atualizações automaticamente ao abrir"],@@ -164,6 +166,8 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Choose…": ["選択…","选择…","選擇…","Elegir…","Choisir…","Auswählen…","Scegli…","Escolher…"],"Clear filter": ["フィルターを解除","清除筛选","清除篩選","Borrar el filtro","Effacer le filtre","Filter zurücksetzen","Azzera il filtro","Limpar o filtro"],"Clear formatting": ["書式をクリア","清除格式","清除格式","Borrar formato","Effacer la mise en forme","Formatierung entfernen","Cancella formattazione","Limpar formatação"],+ "Clear history": ["履歴を削除","清除历史","清除歷史","Borrar el historial","Effacer l’historique","Verlauf löschen","Cancella la cronologia","Limpar o histórico"],+ "Clear history…": ["履歴を削除…","清除历史…","清除歷史…","Borrar el historial…","Effacer l’historique…","Verlauf löschen…","Cancella la cronologia…","Limpar o histórico…"],"Click a page to open it · drag to move · scroll to zoom": ["ページをクリックで開く · ドラッグで移動 · スクロールで拡大縮小","点击页面即可打开 · 拖动移动 · 滚动缩放","點擊頁面即可開啟 · 拖曳移動 · 捲動縮放","Haz clic en una página para abrirla · arrastra para mover · desplázate para acercar","Cliquez sur une page pour l’ouvrir · glissez pour déplacer · défilez pour zoomer","Auf eine Seite klicken, um sie zu öffnen · ziehen zum Bewegen · scrollen zum Zoomen","Fai clic su una pagina per aprirla · trascina per spostare · scorri per ingrandire","Clica numa página para a abrir · arrasta para mover · desloca para ampliar"],"Clip added ({size})": ["クリップを追加しました({size})","已添加片段 ({size})","已新增片段 ({size})","Clip añadido ({size})","Clip ajouté ({size})","Clip hinzugefügt ({size})","Clip aggiunta ({size})","Clipe adicionado ({size})"],"Close": ["閉じる","关闭","關閉","Cerrar","Fermer","Schließen","Chiudi","Fechar"],@@ -216,6 +220,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Delete": ["削除","删除","刪除","Eliminar","Supprimer","Löschen","Elimina","Eliminar"],"Delete the template “{name}”? Pages already made from it are not touched.": ["テンプレート「{name}」を削除しますか?すでに作成したページはそのままです。","删除模板“{name}”?已经用它创建的页面不受影响。","刪除範本「{name}」?已經用它建立的頁面不受影響。","¿Eliminar la plantilla «{name}»? Las páginas ya creadas a partir de ella no se tocan.","Supprimer le modèle « {name} » ? Les pages déjà créées à partir de lui ne sont pas touchées.","Vorlage „{name}“ löschen? Bereits daraus erstellte Seiten bleiben unberührt.","Eliminare il modello «{name}»? Le pagine già create da esso non vengono toccate.","Eliminar o modelo «{name}»? As páginas já criadas a partir dele não são tocadas."],"Delete “{name}”?": ["「{name}」を削除しますか?","要删除“{name}”吗?","要刪除「{name}」嗎?","¿Eliminar «{name}»?","Supprimer « {name} » ?","„{name}“ löschen?","Eliminare «{name}»?","Eliminar “{name}”?"],+ "Deleted page": ["削除されたページ","已删除的页面","已刪除的頁面","Página eliminada","Page supprimée","Gelöschte Seite","Pagina eliminata","Página eliminada"],"Delete…": ["削除…","删除…","刪除…","Eliminar…","Supprimer…","Löschen…","Elimina…","Eliminar…"],"Descending": ["降順","降序","遞減","Descendente","Décroissant","Absteigend","Decrescente","Decrescente"],"Description": ["説明","描述","描述","Descripción","Description","Beschreibung","Descrizione","Descrição"],@@ -285,6 +290,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Find and replace": ["検索と置換","查找和替换","尋找與取代","Buscar y reemplazar","Rechercher et remplacer","Suchen und ersetzen","Trova e sostituisci","Localizar e substituir"],"Find in this space…": ["このスペース内を検索…","在此空间中查找…","在此空間尋找…","Buscar en este espacio…","Rechercher dans cet espace…","In diesem Space suchen…","Trova in questo spazio…","Localizar neste espaço…"],"Find or create a page…": ["ページを検索または作成…","查找或新建页面…","尋找或建立頁面…","Buscar o crear una página…","Trouver ou créer une page…","Seite finden oder erstellen…","Trova o crea una pagina…","Encontrar ou criar uma página…"],+ "First version kept in this file": ["このファイルに記録された最初のバージョン","此文件中保存的第一个版本","此檔案中保存的第一個版本","Primera versión guardada en este archivo","Première version conservée dans ce fichier","Erste in dieser Datei aufbewahrte Version","Prima versione conservata in questo file","Primeira versão guardada neste ficheiro"],"Fit": ["全体表示","适应窗口","適應視窗","Ajustar","Ajuster","Einpassen","Adatta","Ajustar"],"Following — view only": ["追従中 — 閲覧のみ","跟随中 — 仅供查看","跟隨中 — 僅供檢視","Siguiendo — solo lectura","Suivi en cours — lecture seule","Folgt mit — nur Ansicht","In ascolto — sola lettura","Acompanhando — somente visualização"],"Footnotes": ["脚注","脚注","註腳","Notas al pie","Notes de bas de page","Fußnoten","Note a piè di pagina","Notas de rodapé"],@@ -316,6 +322,8 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Hide the page list ([)": ["ページ一覧を隠す([)","隐藏页面列表([)","隱藏頁面清單([)","Ocultar la lista de páginas ([)","Masquer la liste des pages ([)","Seitenliste ausblenden ([)","Nascondi l'elenco delle pagine ([)","Ocultar a lista de páginas ([)"],"Highlight": ["ハイライト","高亮","螢光標示","Resaltado","Surlignage","Hervorhebung","Evidenziazione","Destaque"],"Highlight — ⇧⌘H": ["ハイライト — ⇧⌘H","高亮 — ⇧⌘H","螢光標示 — ⇧⌘H","Resaltado — ⇧⌘H","Surlignage — ⇧⌘H","Hervorhebung — ⇧⌘H","Evidenziazione — ⇧⌘H","Destaque — ⇧⌘H"],+ "History removed. Save to write the file without it.": ["履歴を削除しました。保存すると、履歴のないファイルが書き出されます。","历史已清除。保存后,文件将不再包含它。","歷史已清除。儲存後,檔案將不再包含它。","Historial borrado. Guarda para escribir el archivo sin él.","Historique effacé. Enregistrez pour écrire le fichier sans lui.","Verlauf gelöscht. Speichere, um die Datei ohne ihn zu schreiben.","Cronologia cancellata. Salva per scrivere il file senza di essa.","Histórico limpo. Guarda para escrever o ficheiro sem ele."],+ "History takes {size} of this file.": ["履歴はこのファイルの {size} を使っています。","历史占用了此文件的 {size}。","歷史佔用了此檔案的 {size}。","El historial ocupa {size} de este archivo.","L’historique occupe {size} de ce fichier.","Der Verlauf belegt {size} dieser Datei.","La cronologia occupa {size} di questo file.","O histórico ocupa {size} deste ficheiro."],"Humanist": ["ヒューマニスト","人文主义","人文主義","Humanista","Humane","Humanistisch","Umanista","Humanista"],"Icon": ["アイコン","图标","圖示","Icono","Icône","Symbol","Icona","Ícone"],"Image": ["画像","图片","影像","Imagen","Image","Bild","Immagine","Imagem"],@@ -354,6 +362,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Italic — ⌘I": ["イタリック — ⌘I","斜体 — ⌘I","斜體 — ⌘I","Cursiva — ⌘I","Italique — ⌘I","Kursiv — ⌘I","Corsivo — ⌘I","Itálico — ⌘I"],"Journal date": ["ジャーナルの日付","日志日期","日誌日期","Fecha del diario","Date du journal","Journaldatum","Data del diario","Data do diário"],"Justified text": ["両端揃え","两端对齐","左右對齊","Texto justificado","Texte justifié","Blocksatz","Testo giustificato","Texto justificado"],+ "Kept inside the file, one per save, so they travel with it. Restoring is undoable.": ["保存するたびに 1 つ、ファイルの中に記録され、ファイルと一緒に移動します。復元は取り消せます。","保存在文件内部,每次保存一个,随文件一起流转。恢复可以撤销。","保存在檔案內部,每次儲存一個,隨檔案一起流轉。還原可以復原。","Se guardan dentro del archivo, una por cada guardado, y viajan con él. Restaurar se puede deshacer.","Conservées dans le fichier, une par enregistrement, elles voyagent avec lui. La restauration peut être annulée.","In der Datei aufbewahrt, eine pro Speichern, und reisen mit ihr. Wiederherstellen lässt sich rückgängig machen.","Conservate nel file, una per salvataggio, viaggiano con esso. Il ripristino si può annullare.","Guardadas dentro do ficheiro, uma por gravação, viajam com ele. Restaurar pode ser anulado."],"Key-verified identity": ["鍵で検証済みのアイデンティティ","密钥验证的身份","金鑰驗證的身份","Identidad verificada por clave","Identité vérifiée par clé","Schlüssel-verifizierte Identität","Identità verificata da chiave","Identidade verificada por chave"],"Label colour": ["ラベルの色","标签颜色","標籤顏色","Color de las etiquetas","Couleur des étiquettes","Farbe der Labels","Colore delle etichette","Cor das etiquetas"],"Labels": ["ラベル","标签","標籤","Etiquetas","Étiquettes","Labels","Etichette","Etiquetas"],@@ -433,6 +442,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"No section named {name} on this page.": ["このページに「{name}」という見出しはありません。","本页没有名为“{name}”的标题。","本頁沒有名為「{name}」的標題。","No hay ninguna sección llamada {name} en esta página.","Aucune section nommée {name} sur cette page.","Kein Abschnitt namens {name} auf dieser Seite.","Nessuna sezione chiamata {name} in questa pagina.","Não há nenhuma secção chamada {name} nesta página."],"No tags match": ["一致するタグはありません","没有匹配的标签","沒有相符的標籤","Ninguna etiqueta coincide","Aucune étiquette ne correspond","Keine passenden Schlagwörter","Nessuna etichetta corrisponde","Nenhuma etiqueta corresponde"],"No templates yet. Open a page you would like to reuse and choose “Save as template”.": ["まだテンプレートはありません。再利用したいページを開いて「テンプレートとして保存」を選んでください。","还没有模板。打开一个想重复使用的页面,选择“保存为模板”。","還沒有範本。開啟一個想重複使用的頁面,選擇「儲存為範本」。","Todavía no hay plantillas. Abre una página que quieras reutilizar y elige «Guardar como plantilla».","Aucun modèle pour l’instant. Ouvrez une page que vous voulez réutiliser et choisissez « Enregistrer comme modèle ».","Noch keine Vorlagen. Öffne eine Seite, die du wiederverwenden möchtest, und wähle „Als Vorlage sichern“.","Ancora nessun modello. Apri una pagina che vuoi riutilizzare e scegli «Salva come modello».","Ainda não há modelos. Abre uma página que queiras reutilizar e escolhe «Guardar como modelo»."],+ "No versions yet — one is kept every time you save.": ["まだバージョンはありません。保存するたびに 1 つ記録されます。","还没有版本——每次保存都会记录一个。","還沒有版本——每次儲存都會記錄一個。","Aún no hay versiones: se guarda una cada vez que guardas.","Pas encore de versions — une est conservée à chaque enregistrement.","Noch keine Versionen — bei jedem Speichern wird eine aufbewahrt.","Ancora nessuna versione: ne viene tenuta una a ogni salvataggio.","Ainda não há versões — é guardada uma sempre que gravas."],"No versions yet — they build up as you write and save.": ["まだバージョンはありません。書いて保存するたびに増えていきます。","暂无版本。随着你的书写和保存,版本会逐渐累积。","尚無版本。隨著你的書寫與儲存,版本會逐漸累積。","Aún no hay versiones: se acumulan a medida que escribes y guardas.","Pas encore de versions — elles s’accumulent à mesure que vous écrivez et enregistrez.","Noch keine Versionen — sie sammeln sich beim Schreiben und Speichern an.","Ancora nessuna versione: si accumulano mentre scrivi e salvi.","Ainda sem versões — vão-se acumulando à medida que escreves e guardas."],"None": ["なし","无","無","Ninguno","Aucun","Keine","Nessuno","Nenhum"],"Not a design this build knows — shown in the default look": ["このバージョンが知らないデザイン — デフォルトの見た目で表示","当前版本不认识此设计 — 以默认外观显示","目前版本不認得此設計 — 以預設外觀顯示","Un diseño que esta versión no conoce: se muestra con el aspecto predeterminado","Un design que cette version ne connaît pas — affiché avec l’apparence par défaut","Eine Gestaltung, die diese Version nicht kennt — im Standard-Aussehen angezeigt","Un design che questa versione non conosce — mostrato con l’aspetto predefinito","Um design que esta versão não conhece — mostrado com o aspeto padrão"],@@ -441,6 +451,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Not loaded — opening it would tell that site you opened this space.": ["未読み込み — 読み込むと、このスペースを開いたことがそのサイトに伝わります。","未加载 — 加载会让该网站知道你打开了这个空间。","未載入 — 載入會讓該網站知道你開啟了這個空間。","No cargada: al cargarla, ese sitio sabría que has abierto este espacio.","Non chargée : la charger indiquerait à ce site que vous avez ouvert cet espace.","Nicht geladen — beim Laden erfährt diese Website, dass du diesen Space geöffnet hast.","Non caricata: caricarla direbbe a quel sito che hai aperto questo spazio.","Não carregada — carregá-la diria a esse site que você abriu este espaço."],"Not sharing yet — click to start a live session": ["まだ共有していません — クリックしてライブセッションを開始","尚未共享 — 点击开始实时协作","尚未共享 — 點擊開始即時協作","Aún no se comparte — haz clic para iniciar una sesión en vivo","Pas encore partagé — cliquez pour démarrer une session en direct","Noch nicht geteilt — zum Starten einer Live-Sitzung klicken","Non ancora condiviso — clicca per avviare una sessione dal vivo","Ainda não está compartilhando — clique para iniciar uma sessão ao vivo"],"Note": ["メモ","备注","備註","Nota","Note","Hinweis","Nota","Nota"],+ "Nothing changed": ["変更はありません","没有任何改动","沒有任何變更","No cambió nada","Rien n’a changé","Nichts hat sich geändert","Non è cambiato nulla","Nada mudou"],"Nothing found": ["見つかりませんでした","没有结果","找不到結果","Sin resultados","Aucun résultat","Nichts gefunden","Nessun risultato","Nada encontrado"],"Nothing is fetched. A card shows what you type here — opening this space never contacts the site.": ["何も取得しません。カードにはここで入力した内容が表示され、このスペースを開いてもサイトに接続することはありません。","不会抓取任何内容。卡片显示的就是你在这里输入的内容——打开这个空间绝不会联系该网站。","不會抓取任何內容。卡片顯示的就是你在這裡輸入的內容——開啟這個空間絕不會連線到該網站。","No se descarga nada. La tarjeta muestra lo que escribas aquí: abrir este espacio nunca contacta con el sitio.","Rien n’est récupéré. La carte affiche ce que vous saisissez ici — ouvrir cet espace ne contacte jamais le site.","Es wird nichts abgerufen. Die Karte zeigt, was Sie hier eintragen — das Öffnen dieses Space kontaktiert die Website nie.","Non viene scaricato nulla. La scheda mostra ciò che scrivi qui: aprire questo spazio non contatta mai il sito.","Nada é obtido. O cartão mostra o que você escrever aqui — abrir este espaço nunca contacta o site."],"Nothing leaves this file until you start a session.": ["セッションを開始するまで、このファイルから外に出るものはありません。","在你开始会话之前,没有任何内容离开这个文件。","在你開始工作階段之前,沒有任何內容離開這個檔案。","Nada sale de este archivo hasta que inicies una sesión.","Rien ne quitte ce fichier tant que vous n’avez pas démarré de session.","Nichts verlässt diese Datei, bis du eine Sitzung startest.","Niente esce da questo file finché non avvii una sessione.","Nada sai deste ficheiro até iniciares uma sessão."],@@ -534,6 +545,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Remove {name} from this space? Their copy drops to read-only.": ["{name} をこの Space から削除しますか?相手のコピーは読み取り専用になります。","要将 {name} 从此 Space 移除吗?对方的副本将变为只读。","要將 {name} 從此 Space 移除嗎?對方的副本將變為唯讀。","¿Quitar a {name} de este Space? Su copia pasará a solo lectura.","Retirer {name} de cet espace ? Sa copie passera en lecture seule.","{name} aus diesem Space entfernen? Die Kopie wird schreibgeschützt.","Rimuovere {name} da questo Space? La sua copia diventerà di sola lettura.","Remover {name} deste Space? A cópia dessa pessoa passa a ser somente leitura."],"Remove {name} — revokes this device’s access; everyone else is unaffected": ["{name} を削除 — このデバイスのアクセスを取り消します。他の人には影響しません","移除 {name} — 撤销该设备的访问权限;其他人不受影响","移除 {name} — 撤銷該裝置的存取權限;其他人不受影響","Quitar a {name} — revoca el acceso de este dispositivo; nadie más se ve afectado","Retirer {name} — révoque l’accès de cet appareil ; personne d’autre n’est affecté","{name} entfernen — widerruft den Zugriff dieses Geräts; alle anderen bleiben unberührt","Rimuovi {name} — revoca l’accesso di questo dispositivo; nessun altro è toccato","Remover {name} — revoga o acesso deste dispositivo; ninguém mais é afetado"],"Rename": ["名前を変更","重命名","重新命名","Cambiar nombre","Renommer","Umbenennen","Rinomina","Mudar o nome"],+ "Renamed from “{title}”": ["「{title}」から名前を変更","由“{title}”改名而来","由「{title}」改名而來","Renombrada desde «{title}»","Renommée depuis « {title} »","Umbenannt von „{title}“","Rinominata da «{title}»","Renomeada a partir de «{title}»"],"Reopen": ["再オープン","重新打开","重新開啟","Reabrir","Rouvrir","Wieder öffnen","Riapri","Reabrir"],"Repeat when it reaches the end": ["最後まで再生したら繰り返す","播放到结尾后重新开始","播放到結尾後重新開始","Repetir al llegar al final","Recommencer à la fin","Am Ende von vorn beginnen","Ricomincia quando arriva alla fine","Recomeçar quando chegar ao fim"],"Replace": ["置き換える","替换","取代","Sustituir","Remplacer","Ersetzen","Sostituisci","Substituir"],@@ -682,6 +694,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"The page becomes a new file of its own: a whole space, with a new document id and none of this one’s sharing keys.": ["そのページが独立した新しいファイルになります。ひとつの完全なスペースで、新しいドキュメント ID を持ち、このスペースの共有キーは一切引き継ぎません。","该页面会成为一个独立的新文件:一个完整的空间,拥有新的文档 ID,且不带本空间的任何共享密钥。","該頁面會成為獨立的新檔案:一個完整的空間,擁有新的文件 ID,且不帶本空間的任何共用金鑰。","La página se convierte en un archivo propio: un espacio completo, con un nuevo id de documento y sin ninguna de las claves de uso compartido de este.","La page devient un fichier à part entière : un espace complet, avec un nouvel identifiant de document et aucune des clés de partage de celui-ci.","Die Seite wird zu einer eigenen Datei: ein vollständiger Space mit einer neuen Dokument-ID und ohne die Freigabeschlüssel dieses Space.","La pagina diventa un file a sé: uno spazio completo, con un nuovo id di documento e senza nessuna delle chiavi di condivisione di questo.","A página passa a ser um ficheiro próprio: um espaço completo, com um novo id de documento e sem nenhuma das chaves de partilha deste."],"The page’s icon is one of this app’s own glyphs, not an emoji, and did not travel.": ["このページのアイコンは絵文字ではなく本アプリ独自のグリフのため、持ち出せませんでした。","该页面的图标是本应用自带的图形而不是表情符号,因此没有带过来。","該頁面的圖示是本應用自帶的圖形而不是表情符號,因此沒有帶過來。","El icono de la página es uno de los glifos propios de esta aplicación, no un emoji, y no viajó.","L’icône de la page est l’un des glyphes propres à cette application, pas un émoji, et n’a pas voyagé.","Das Symbol der Seite ist eine der eigenen Glyphen dieser App, kein Emoji, und ist nicht mitgereist.","L’icona della pagina è uno dei glifi propri di questa app, non un’emoji, e non ha viaggiato.","O ícone da página é um dos glifos da própria aplicação, não um emoji, e não viajou."],"The password cannot be recovered — if it is lost, the file is lost.": ["パスワードは復元できません — 紛失するとファイルも失われます。","密码无法找回 — 密码丢失即文件丢失。","密碼無法復原 — 密碼遺失即檔案遺失。","La contraseña no se puede recuperar: si se pierde, el archivo se pierde.","Le mot de passe ne peut pas être récupéré — s'il est perdu, le fichier l'est aussi.","Das Passwort kann nicht wiederhergestellt werden — geht es verloren, ist die Datei verloren.","La password non può essere recuperata — se la perdi, perdi il file.","A senha não pode ser recuperada — se ela for perdida, o arquivo é perdido."],+ "The past text goes with them, including anything you deleted. Save the file for it to take effect.": ["過去の本文も一緒に消えます。削除したものも含めてです。反映するにはファイルを保存してください。","过去的文字也会随之消失,包括你删掉的内容。需要保存文件才会生效。","過去的文字也會隨之消失,包括你刪掉的內容。需要儲存檔案才會生效。","El texto del pasado se va con ellas, incluido lo que hayas borrado. Guarda el archivo para que surta efecto.","Le texte du passé part avec elles, y compris ce que vous avez supprimé. Enregistrez le fichier pour que cela prenne effet.","Der Text von früher geht mit ihnen — auch das, was du gelöscht hast. Speichere die Datei, damit es wirksam wird.","Il testo del passato se ne va con esse, compreso ciò che hai eliminato. Salva il file perché abbia effetto.","O texto do passado vai com elas, incluindo o que apagaste. Guarda o ficheiro para que tenha efeito."],"The rest name notes that were not in the selection, and are left as text.": ["残りは選択に含まれていないノートを指しており、テキストのまま残ります。","其余指向不在所选范围内的笔记,保留为文字。","其餘指向不在所選範圍內的筆記,保留為文字。","El resto nombra notas que no estaban en la selección y se dejan como texto.","Les autres désignent des notes absentes de la sélection et restent en texte.","Der Rest nennt Notizen, die nicht in der Auswahl waren, und bleibt als Text stehen.","Gli altri nominano note che non erano nella selezione e restano come testo.","Os restantes nomeiam notas que não estavam na seleção e ficam como texto."],"The theme follows whoever opens the file. It is never written into the document.": ["テーマはファイルを開いた人に従います。ドキュメントには書き込まれません。","主题跟随打开文件的人,绝不会写入文档。","主題取決於開啟檔案的人,永遠不會寫入文件中。","El tema sigue a quien abre el archivo. Nunca se escribe en el documento.","Le thème suit la personne qui ouvre le fichier. Il n’est jamais écrit dans le document.","Das Design richtet sich danach, wer die Datei öffnet. Es wird nie ins Dokument geschrieben.","Il tema segue chi apre il file. Non viene mai scritto nel documento.","O tema segue quem abre o ficheiro. Nunca é escrito no documento."],"The whole page": ["ページ全体","整个页面","整個頁面","La página entera","La page entière","Die ganze Seite","L’intera pagina","A página inteira"],@@ -696,6 +709,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"This embed is inside itself — the loop stops here.": ["この埋め込みは自分自身を含んでいます。ここでループを止めました。","该嵌入包含了自身——循环在此停止。","這個嵌入包含了自身——迴圈在此停止。","Esta inserción se contiene a sí misma: el bucle se detiene aquí.","Cette insertion se contient elle-même — la boucle s’arrête ici.","Diese Einbettung enthält sich selbst – die Schleife endet hier.","Questa incorporazione contiene sé stessa — il ciclo si ferma qui.","Esta incorporação contém-se a si própria — o ciclo para aqui."],"This embed points at a page that is not here.": ["この埋め込みの参照先ページが見つかりません。","该嵌入指向的页面不存在。","這個嵌入指向的頁面不存在。","Esta inserción apunta a una página que no está aquí.","Cette insertion pointe vers une page qui n’est pas là.","Diese Einbettung zeigt auf eine Seite, die nicht hier ist.","Questa incorporazione punta a una pagina che non c’è.","Esta incorporação aponta para uma página que não está aqui."],"This file": ["このファイル","此文件","此檔案","Este archivo","Ce fichier","Diese Datei","Questo file","Este ficheiro"],+ "This file carries a history this version cannot read. It is kept exactly as it arrived.": ["このファイルには、このバージョンでは読めない履歴が入っています。届いたときのまま保持されます。","此文件带有当前版本无法读取的历史。它会原样保留。","此檔案帶有目前版本無法讀取的歷史。它會原樣保留。","Este archivo trae un historial que esta versión no sabe leer. Se conserva tal como llegó.","Ce fichier contient un historique que cette version ne sait pas lire. Il est conservé tel qu’il est arrivé.","Diese Datei bringt einen Verlauf mit, den diese Version nicht lesen kann. Er bleibt genau so, wie er ankam.","Questo file porta una cronologia che questa versione non sa leggere. È conservata esattamente com’è arrivata.","Este ficheiro traz um histórico que esta versão não sabe ler. É mantido tal como chegou."],"This file carries its own app — it works offline, forever, as is.": ["このファイルはアプリを内蔵しています — オフラインでも、ずっと、このまま動きます。","此文件自带应用 — 离线可用,永久如此。","此檔案自帶應用程式 — 離線可用,永遠如此。","Este archivo lleva su propia aplicación — funciona sin conexión, para siempre, tal cual.","Ce fichier embarque sa propre application — il fonctionne hors ligne, pour toujours, tel quel.","Diese Datei trägt ihre eigene App — sie funktioniert offline, für immer, so wie sie ist.","Questo file porta con sé la propria app — funziona offline, per sempre, così com'è.","Este arquivo carrega o próprio aplicativo — funciona offline, para sempre, do jeito que está."],"This file could not be opened": ["このファイルを開けませんでした","无法打开此文件","無法開啟此檔案","No se pudo abrir este archivo","Ce fichier n’a pas pu être ouvert","Diese Datei konnte nicht geöffnet werden","Impossibile aprire questo file","Não foi possível abrir este ficheiro"],"This file declares rules this build does not know. It is open read-only so nothing is lost.": ["このファイルには、このビルドが知らないルールが宣言されています。何も失わないよう読み取り専用で開いています。","此文件声明了此版本不认识的规则。已以只读方式打开,以免丢失任何内容。","此檔案宣告了這個版本不認識的規則。已以唯讀方式開啟,以免遺失任何內容。","Este archivo declara reglas que esta versión no conoce. Está abierto en solo lectura para no perder nada.","Ce fichier déclare des règles que cette version ne connaît pas. Il est ouvert en lecture seule pour ne rien perdre.","Diese Datei nennt Regeln, die dieser Build nicht kennt. Sie ist schreibgeschützt geöffnet, damit nichts verloren geht.","Questo file dichiara regole che questa versione non conosce. È aperto in sola lettura per non perdere nulla.","Este ficheiro declara regras que esta versão não conhece. Está aberto apenas para leitura para que nada se perca."],@@ -717,6 +731,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"This space has no pages.": ["このスペースにはページがありません。","此空间没有页面。","此空間沒有任何頁面。","Este espacio no tiene páginas.","Cet espace n’a aucune page.","Dieser Space hat keine Seiten.","Questo spazio non ha pagine.","Este espaço não tem páginas."],"This space is encrypted, so no versions are kept.": ["このスペースは暗号化されているため、バージョンは保存されません。","此空间已加密,因此不保存任何版本。","此空間已加密,因此不保存任何版本。","Este espacio está cifrado, así que no se guarda ninguna versión.","Cet espace est chiffré : aucune version n’est conservée.","Dieser Space ist verschlüsselt, deshalb werden keine Versionen aufbewahrt.","Questo spazio è cifrato, quindi non viene conservata alcuna versione.","Este espaço está cifrado, por isso não são guardadas versões."],"This space is locked": ["このスペースはロックされています","此空间已锁定","此空間已鎖定","Este espacio está bloqueado","Cet espace est verrouillé","Dieser Space ist gesperrt","Questo spazio è bloccato","Este espaço está bloqueado"],+ "This space is too large to keep versions inside the file.": ["このスペースは大きすぎるため、ファイルの中にバージョンを保持できません。","此空间太大,无法在文件内保存版本。","此空間太大,無法在檔案內保存版本。","Este espacio es demasiado grande para guardar versiones dentro del archivo.","Cet espace est trop volumineux pour conserver des versions dans le fichier.","Dieser Bereich ist zu groß, um Versionen in der Datei aufzubewahren.","Questo spazio è troppo grande per conservare versioni nel file.","Este espaço é demasiado grande para guardar versões dentro do ficheiro."],"This space no longer uses a design of its own.": ["このスペースは独自のデザインを使わなくなりました。","此空间不再使用自己的设计。","此空間不再使用自己的設計。","Este espacio ya no usa un diseño propio.","Cet espace n’utilise plus de design qui lui soit propre.","Dieser Space verwendet keine eigene Gestaltung mehr.","Questo spazio non usa più un design proprio.","Este espaço já não usa um design próprio."],"This space reads right-to-left; a deck has no such setting.": ["このスペースは右から左へ読みます。デッキにはその設定がありません。","这个空间从右向左阅读;演示文稿没有这项设置。","這個空間由右至左閱讀;簡報沒有這項設定。","Este espacio se lee de derecha a izquierda; una presentación no tiene ese ajuste.","Cet espace se lit de droite à gauche ; une présentation n’a pas ce réglage.","Dieser Raum wird von rechts nach links gelesen; eine Präsentation hat diese Einstellung nicht.","Questo spazio si legge da destra a sinistra; una presentazione non ha questa impostazione.","Este espaço lê-se da direita para a esquerda; uma apresentação não tem essa definição."],"This view chooses its pages in a way this build does not understand, so it is showing the backlog instead.": ["このビューは、このバージョンが理解できない方法でページを選んでいるため、代わりにバックログを表示しています。","此视图以本版本无法理解的方式选择页面,因此改为显示待办列表。","此檢視以本版本無法理解的方式選擇頁面,因此改為顯示待辦清單。","Esta vista elige sus páginas de una forma que esta versión no entiende, así que muestra la lista de tareas.","Cette vue choisit ses pages d’une façon que cette version ne comprend pas ; elle affiche donc le backlog.","Diese Ansicht wählt ihre Seiten auf eine Weise, die diese Version nicht versteht, und zeigt stattdessen den Backlog.","Questa vista sceglie le sue pagine in un modo che questa versione non comprende, quindi mostra il backlog.","Esta vista escolhe as suas páginas de uma forma que esta versão não entende, por isso mostra o backlog."],@@ -783,6 +798,9 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Version {v} is available — click to update": ["バージョン {v} があります — クリックで更新","版本 {v} 可用 — 点击更新","版本 {v} 可用 — 點按以更新","Versión {v} disponible — clic para actualizar","Version {v} disponible — cliquez pour mettre à jour","Version {v} verfügbar — klicken zum Aktualisieren","Versione {v} disponibile — clic per aggiornare","A versão {v} está disponível — clique para atualizar"],"Version {v} is available.": ["バージョン {v} が利用可能です。","版本 {v} 可用。","版本 {v} 可用。","Versión {v} disponible.","La version {v} est disponible.","Version {v} ist verfügbar.","È disponibile la versione {v}.","A versão {v} está disponível."],"Versions are kept in this browser only — never in the file, never online. Restoring is undoable.": ["バージョンはこのブラウザーにのみ保存されます。ファイルにもオンラインにも残りません。復元は取り消せます。","版本仅保存在此浏览器中,不会写入文件,也不会上传。恢复操作可以撤销。","版本僅保存在此瀏覽器中,不會寫入檔案,也不會上傳。還原操作可以復原。","Las versiones se guardan solo en este navegador: nunca en el archivo ni en línea. Restaurar se puede deshacer.","Les versions sont conservées uniquement dans ce navigateur — jamais dans le fichier, jamais en ligne. La restauration est annulable.","Versionen liegen nur in diesem Browser — nie in der Datei, nie online. Das Wiederherstellen lässt sich rückgängig machen.","Le versioni restano solo in questo browser: mai nel file, mai online. Il ripristino si può annullare.","As versões ficam apenas neste navegador — nunca no ficheiro, nunca online. Restaurar pode ser desfeito."],+ "Versions in this file": ["このファイルの中のバージョン","此文件中的版本","此檔案中的版本","Versiones dentro de este archivo","Versions dans ce fichier","Versionen in dieser Datei","Versioni in questo file","Versões dentro deste ficheiro"],+ "Versions in this file…": ["このファイルの中のバージョン…","此文件中的版本…","此檔案中的版本…","Versiones dentro de este archivo…","Versions dans ce fichier…","Versionen in dieser Datei…","Versioni in questo file…","Versões dentro deste ficheiro…"],+ "Versions include text you have deleted. They travel in this file and in invites; reading copies, view-only copies and Copy document JSON leave them out.": ["バージョンには、削除した本文も含まれます。このファイルと招待には含まれますが、閲覧用コピー、表示専用コピー、「ドキュメント JSON をコピー」には含まれません。","版本中包含你删掉的文字。它们会随此文件和邀请一起流转;阅读副本、仅查看副本和“复制文档 JSON”都不包含它们。","版本中包含你刪掉的文字。它們會隨此檔案和邀請一起流轉;閱讀副本、僅檢視副本和「複製文件 JSON」都不包含它們。","Las versiones incluyen texto que has borrado. Viajan en este archivo y en las invitaciones; las copias de lectura, las copias de solo ver y «Copiar JSON del documento» las dejan fuera.","Les versions contiennent du texte que vous avez supprimé. Elles voyagent dans ce fichier et dans les invitations ; les copies de lecture, les copies en lecture seule et « Copier le JSON du document » les laissent de côté.","Versionen enthalten auch Text, den du gelöscht hast. Sie reisen in dieser Datei und in Einladungen mit; Lesekopien, Nur-Ansehen-Kopien und „Dokument-JSON kopieren“ lassen sie weg.","Le versioni includono testo che hai eliminato. Viaggiano in questo file e negli inviti; le copie di lettura, le copie di sola visualizzazione e «Copia JSON del documento» le escludono.","As versões incluem texto que apagaste. Viajam neste ficheiro e nos convites; as cópias de leitura, as cópias só de visualização e «Copiar JSON do documento» deixam-nas de fora."],"Video": ["動画","视频","影片","Vídeo","Vidéo","Video","Video","Vídeo"],"Video from {host}": ["{host} の動画","来自 {host} 的视频","來自 {host} 的影片","Vídeo de {host}","Vidéo provenant de {host}","Video von {host}","Video da {host}","Vídeo de {host}"],"Video or audio": ["動画または音声","视频或音频","影片或音訊","Vídeo o audio","Vidéo ou audio","Video oder Audio","Video o audio","Vídeo ou áudio"],@@ -893,5 +911,6 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"{pages} page(s) and {blocks} block(s) added from {files} file(s).": ["{files} 個のファイルから {pages} ページ・{blocks} ブロックを追加しました。","从 {files} 个文件新增了 {pages} 个页面、{blocks} 个块。","從 {files} 個檔案新增了 {pages} 個頁面、{blocks} 個區塊。","{pages} página(s) y {blocks} bloque(s) añadidos desde {files} archivo(s).","{pages} page(s) et {blocks} bloc(s) ajoutés depuis {files} fichier(s).","{pages} Seite(n) und {blocks} Block/Blöcke aus {files} Datei(en) hinzugefügt.","{pages} pagine e {blocks} blocchi aggiunti da {files} file.","{pages} página(s) e {blocks} bloco(s) acrescentados a partir de {files} ficheiro(s)."],"{pages} page(s) and {blocks} block(s) will travel.": ["{pages} ページ、{blocks} ブロックが移動します。","将带走 {pages} 个页面、{blocks} 个块。","將帶走 {pages} 個頁面、{blocks} 個區塊。","Viajarán {pages} página(s) y {blocks} bloque(s).","{pages} page(s) et {blocks} bloc(s) feront le voyage.","{pages} Seite(n) und {blocks} Block/Blöcke kommen mit.","Viaggeranno {pages} pagina/e e {blocks} blocco/blocchi.","Vão viajar {pages} página(s) e {blocks} bloco(s)."],"{pages} pages · {links} links": ["{pages} ページ · {links} リンク","{pages} 个页面 · {links} 条链接","{pages} 個頁面 · {links} 條連結","{pages} páginas · {links} enlaces","{pages} pages · {links} liens","{pages} Seiten · {links} Verknüpfungen","{pages} pagine · {links} collegamenti","{pages} páginas · {links} ligações"],+ "{p} page(s), {b} block(s) changed": ["{p} ページ・{b} ブロックが変更","{p} 个页面、{b} 个块有改动","{p} 個頁面、{b} 個區塊有變更","{p} página(s), {b} bloque(s) con cambios","{p} page(s), {b} bloc(s) modifiés","{p} Seite(n), {b} Block/Blöcke geändert","{p} pagina/e, {b} blocco/i modificati","{p} página(s), {b} bloco(s) alterados"],"⌘Z removes the imported pages again.": ["⌘Z で、読み込んだページを取り消せます。","按 ⌘Z 可以把导入的页面再撤销掉。","按 ⌘Z 可以把匯入的頁面再撤銷掉。","⌘Z vuelve a quitar las páginas importadas.","⌘Z supprime à nouveau les pages importées.","Mit ⌘Z verschwinden die importierten Seiten wieder.","⌘Z rimuove di nuovo le pagine importate.","⌘Z remove novamente as páginas importadas."],}diff --git a/spaces/src/i18n/pt.ts b/spaces/src/i18n/pt.tsindex 098a4a5f..dce014da 100644--- a/spaces/src/i18n/pt.ts+++ b/spaces/src/i18n/pt.ts@@ -947,4 +947,23 @@ export const pt: Catalog = {"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…",+ "Changes": "Alterações",+ "Clear history": "Limpar o histórico",+ "Deleted page": "Página eliminada",+ "History removed. Save to write the file without it.": "Histórico limpo. Guarda para escrever o ficheiro sem ele.",+ "History takes {size} of this file.": "O histórico ocupa {size} deste ficheiro.",+ "No versions yet — one is kept every time you save.": "Ainda não há versões — é guardada uma sempre que gravas.",+ "Nothing changed": "Nada mudou",+ "Renamed from “{title}”": "Renomeada a partir de «{title}»",+ "The past text goes with them, including anything you deleted. Save the file for it to take effect.": "O texto do passado vai com elas, incluindo o que apagaste. Guarda o ficheiro para que tenha efeito.",+ "This file carries a history this version cannot read. It is kept exactly as it arrived.": "Este ficheiro traz um histórico que esta versão não sabe ler. É mantido tal como chegou.",+ "Versions in this file": "Versões dentro deste ficheiro",+ "{p} page(s), {b} block(s) changed": "{p} página(s), {b} bloco(s) alterados",+ "Versions in this file…": "Versões dentro deste ficheiro…",+ "Kept inside the file, one per save, so they travel with it. Restoring is undoable.": "Guardadas dentro do ficheiro, uma por gravação, viajam com ele. Restaurar pode ser anulado.",+ "This space is too large to keep versions inside the file.": "Este espaço é demasiado grande para guardar versões dentro do ficheiro.",+ "Versions include text you have deleted. They travel in this file and in invites; reading copies, view-only copies and Copy document JSON leave them out.": "As versões incluem texto que apagaste. Viajam neste ficheiro e nos convites; as cópias de leitura, as cópias só de visualização e «Copiar JSON do documento» deixam-nas de fora.",+ "Clear history…": "Limpar o histórico…",+ "First version kept in this file": "Primeira versão guardada neste ficheiro",+ "Changes outside the pages — title, design, footnotes or templates": "Alterações fora das páginas — título, design, notas de rodapé ou modelos",}diff --git a/spaces/src/i18n/zh-Hans.ts b/spaces/src/i18n/zh-Hans.tsindex b20bc83a..bf04300e 100644--- a/spaces/src/i18n/zh-Hans.ts+++ b/spaces/src/i18n/zh-Hans.ts@@ -947,4 +947,23 @@ export const zh_Hans: Catalog = {"Previous": "上一页","Reading copy saved — it opens as a document, with no keys and no comments": "阅读副本已保存 — 它作为文档打开,不含密钥和评论","Save a reading copy…": "保存阅读副本…",+ "Changes": "改动",+ "Clear history": "清除历史",+ "Deleted page": "已删除的页面",+ "History removed. Save to write the file without it.": "历史已清除。保存后,文件将不再包含它。",+ "History takes {size} of this file.": "历史占用了此文件的 {size}。",+ "No versions yet — one is kept every time you save.": "还没有版本——每次保存都会记录一个。",+ "Nothing changed": "没有任何改动",+ "Renamed from “{title}”": "由“{title}”改名而来",+ "The past text goes with them, including anything you deleted. Save the file for it to take effect.": "过去的文字也会随之消失,包括你删掉的内容。需要保存文件才会生效。",+ "This file carries a history this version cannot read. It is kept exactly as it arrived.": "此文件带有当前版本无法读取的历史。它会原样保留。",+ "Versions in this file": "此文件中的版本",+ "{p} page(s), {b} block(s) changed": "{p} 个页面、{b} 个块有改动",+ "Versions in this file…": "此文件中的版本…",+ "Kept inside the file, one per save, so they travel with it. Restoring is undoable.": "保存在文件内部,每次保存一个,随文件一起流转。恢复可以撤销。",+ "This space is too large to keep versions inside the file.": "此空间太大,无法在文件内保存版本。",+ "Versions include text you have deleted. They travel in this file and in invites; reading copies, view-only copies and Copy document JSON leave them out.": "版本中包含你删掉的文字。它们会随此文件和邀请一起流转;阅读副本、仅查看副本和“复制文档 JSON”都不包含它们。",+ "Clear history…": "清除历史…",+ "First version kept in this file": "此文件中保存的第一个版本",+ "Changes outside the pages — title, design, footnotes or templates": "页面之外的改动——标题、设计、脚注或模板",}diff --git a/spaces/src/i18n/zh-Hant.ts b/spaces/src/i18n/zh-Hant.tsindex dc76495e..30a573f3 100644--- a/spaces/src/i18n/zh-Hant.ts+++ b/spaces/src/i18n/zh-Hant.ts@@ -947,4 +947,23 @@ export const zh_Hant: Catalog = {"Previous": "上一頁","Reading copy saved — it opens as a document, with no keys and no comments": "閱讀副本已儲存 — 它會以文件形式開啟,不含金鑰與評論","Save a reading copy…": "儲存閱讀副本…",+ "Changes": "變更",+ "Clear history": "清除歷史",+ "Deleted page": "已刪除的頁面",+ "History removed. Save to write the file without it.": "歷史已清除。儲存後,檔案將不再包含它。",+ "History takes {size} of this file.": "歷史佔用了此檔案的 {size}。",+ "No versions yet — one is kept every time you save.": "還沒有版本——每次儲存都會記錄一個。",+ "Nothing changed": "沒有任何變更",+ "Renamed from “{title}”": "由「{title}」改名而來",+ "The past text goes with them, including anything you deleted. Save the file for it to take effect.": "過去的文字也會隨之消失,包括你刪掉的內容。需要儲存檔案才會生效。",+ "This file carries a history this version cannot read. It is kept exactly as it arrived.": "此檔案帶有目前版本無法讀取的歷史。它會原樣保留。",+ "Versions in this file": "此檔案中的版本",+ "{p} page(s), {b} block(s) changed": "{p} 個頁面、{b} 個區塊有變更",+ "Versions in this file…": "此檔案中的版本…",+ "Kept inside the file, one per save, so they travel with it. Restoring is undoable.": "保存在檔案內部,每次儲存一個,隨檔案一起流轉。還原可以復原。",+ "This space is too large to keep versions inside the file.": "此空間太大,無法在檔案內保存版本。",+ "Versions include text you have deleted. They travel in this file and in invites; reading copies, view-only copies and Copy document JSON leave them out.": "版本中包含你刪掉的文字。它們會隨此檔案和邀請一起流轉;閱讀副本、僅檢視副本和「複製文件 JSON」都不包含它們。",+ "Clear history…": "清除歷史…",+ "First version kept in this file": "此檔案中保存的第一個版本",+ "Changes outside the pages — title, design, footnotes or templates": "頁面之外的變更——標題、設計、註腳或範本",}diff --git a/spaces/src/main.ts b/spaces/src/main.tsindex 0f05efc3..599bd2e2 100644--- a/spaces/src/main.ts+++ b/spaces/src/main.ts@@ -41,6 +41,7 @@ import { Store } from './store'import { Editor } from './editor'import { SyncSession } from './sync/session.ts'import { isReaderCopy, stampSync } from './share.ts'+import { recordOnSave } from './history.ts'import { projectForCopy } from '../../kernel/src/docfields.ts'import { SPACES_FIELDS } from './docclass.ts'import { downloadMarkdown, launchUpdateCheck } from './about'@@ -347,8 +348,15 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')// collab.sync is stamped in the queue's prepare step: after any write// ahead of this one, immediately before the snapshot is copied, so the// state describes exactly the bytes that reach the file (#594).+ //+ // The in-file revision is recorded in the SAME step for the same reason+ // (history.ts): it describes exactly the bytes written, and those bytes+ // contain it. It writes doc.revisions directly — not through commit — so+ // the store's revision does not move and this write is not made stale.+ // Unconditional on encryption: revisions live inside #bento-doc, so the+ // envelope encrypts them with the pages (unlike addVersion below).const out = await saveRevision(store, saves, (snapshot) => saveFile(snapshot),- () => { stampSync(store, session); editor.status(t('Saving…')) })+ () => { stampSync(store, session); recordOnSave(store); editor.status(t('Saving…')) })if (out.kind === 'failed') {console.error('bento/spaces: save failed', out.error)editor.status(t('Save failed — see console'))@@ -382,8 +390,8 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')* when that snapshot is still the document on screen.*/editor.onUpdateInPlace = async (rel) => {- // stamped in prepare, beside the snapshot, exactly as ⌘S is- const saved = await saves.run(() => { store.endRun(); stampSync(store, session) },+ // stamped and recorded in prepare, beside the snapshot, exactly as ⌘S is+ const saved = await saves.run(() => { store.endRun(); stampSync(store, session); recordOnSave(store) },(snapshot) => applyUpdateInPlace(rel, snapshot))if (!saved?.value) return nullif (saved.isCurrent()) store.setDirty(false)diff --git a/spaces/src/model.ts b/spaces/src/model.tsindex bdad6732..012dd149 100644--- a/spaces/src/model.ts+++ b/spaces/src/model.ts@@ -16,6 +16,7 @@import type { CollabCreds } from './sync/crdt.ts'// Type-only, and therefore erased: no runtime dependency, no import cycle.import type { PageTemplate } from './templates.ts'+import type { SpacesRevision } from './history.ts'import { esc, externalHref } from './sanitize.ts'// A VALUE import, and the cycle it looks like is not one: embed.ts imports// only TYPES from here, and a type import is erased before anything runs.@@ -473,13 +474,20 @@ export interface SpacesDoc {*/collab?: CollabCreds/**- * In-file version history (kernel field class 'history', docfields.ts).- * Declared here, typed loosely, BEFORE the features that write them land, so- * the copy rules already classify them: kept by the file, a duplicate and an- * invite; dropped from every reader-tier copy and from Copy document JSON;- * never synced. Nothing in this build reads or writes either.+ * In-file history (kernel field class 'history', docfields.ts): kept by the+ * file, a duplicate and an invite; dropped from every reader-tier copy and+ * from Copy document JSON; never synced.+ *+ * `revisions` is the space's VERSION HISTORY — oldest first, each entry the+ * kernel's `Revision` envelope around the change from the one before it.+ * The engine, its budget and the reasoning live in history.ts; every entry+ * read from a file is validated there before anything folds it. Absent when+ * there is none — never `revisions: []`. `import type`, so no runtime cycle.+ *+ * `trail` is declared for the tracker's burndown record; nothing in this+ * build reads or writes it.*/- revisions?: unknown[]+ revisions?: SpacesRevision[]trail?: unknown[extra: string]: unknown}@@ -668,7 +676,8 @@ export const newPage = (title = 'Untitled', extra: Partial<Page> = {}): Page =>export function docContentKey(doc: SpacesDoc): string {// The kernel's key (docfields.ts), over this app's field map: every declared// and undeclared top-level field that is PRESENT, sorted, except the- // capability (`collab` — a key is not an edit) and `modified`.+ // capability (`collab` — a key is not an edit), `modified`, and `revisions`+ // (recorded only into the bytes a save writes — docclass.ts SPACES_NOT_EDIT).//// So `footnotes` is in it (a note's text is somebody's writing and lives// nowhere else), the page templates and the journal template are in itdiff --git a/spaces/src/store.ts b/spaces/src/store.tsindex 01b2308d..a02c99df 100644--- a/spaces/src/store.ts+++ b/spaces/src/store.ts@@ -16,6 +16,7 @@ type Scope = 'doc' | 'page'import { type SpacesDoc, type Page, type Block, buildIndex, type SpaceIndex, homePage } from './model'import { buildTagIndex, type TagIndex } from './tags.ts'import { FROM_LIVE, keepLiveIdentity as keepLive } from '../../kernel/src/docfields.ts'+import { SPACES_FIELDS } from './docclass.ts'type Listener = () => voidtype Event = 'doc' | 'page' | 'tree' | 'selection' | 'dirty'@@ -59,9 +60,34 @@ export { FROM_LIVE }* about what "kept live" means. */function keepLiveIdentity(live: SpacesDoc, next: SpacesDoc): SpacesDoc {keepLive(next as Record<string, unknown>, live as Record<string, unknown>)+ keepLiveHistory(live, next)return next}+/**+ * The fields the kernel's map classes 'history' (docclass.ts: `revisions`,+ * `trail`). They are a LOG of the space, not its content, so — like identity —+ * every whole-document restore keeps the LIVE value, and undo snapshots omit+ * them (they would be up to 128 KB per entry, identical in nearly every one).+ *+ * Without this, three ordinary actions silently rewrote the file's history:+ * ⌘Z after a save un-recorded the revision that save wrote; "Replace from+ * JSON" with the output of Copy document JSON (which drops history by the+ * copy table) deleted it outright; and restoring a version or a recovery+ * snapshot rolled the list back to whatever it was when that copy was taken.+ * Read from the map, so a history field added later is kept the same way.+ */+const HISTORY_KEYS: readonly string[] = Object.entries(SPACES_FIELDS)+ .filter(([, cls]) => cls === 'history').map(([k]) => k)++function keepLiveHistory(live: SpacesDoc, next: SpacesDoc): void {+ const n = next as Record<string, unknown>, l = live as Record<string, unknown>+ for (const k of HISTORY_KEYS) {+ if (Object.hasOwn(l, k) && l[k] !== undefined) n[k] = l[k]+ else delete n[k]+ }+}+/*** One undoable step.*@@ -283,8 +309,10 @@ export class Store {// ---- history ------------------------------------------------------------private snapshot(): string {// assets are excluded: they are the largest thing in the document and never- // change during an ordinary edit, so snapshotting them 100 times is waste- const { assets: _assets, ...rest } = this.doc+ // change during an ordinary edit, so snapshotting them 100 times is waste.+ // History fields are excluded too, and restored from live (keepLiveHistory)+ const { assets: _assets, ...rest } = this.doc as Record<string, unknown>+ for (const k of HISTORY_KEYS) delete rest[k]return JSON.stringify(rest)}diff --git a/spaces/src/styles.css b/spaces/src/styles.cssindex 35bebe47..d42eada1 100644--- a/spaces/src/styles.css+++ b/spaces/src/styles.css@@ -1696,6 +1696,45 @@ a.sp-embed-src:hover { color: var(--ink); text-decoration: underline; }.sp-ab-vdo { margin-inline-start: auto; color: var(--muted); }.sp-ab-version:hover .sp-ab-vdo, .sp-ab-version:focus-visible .sp-ab-vdo { color: var(--blue); }+/* Versions in this file (doccmds.ts openFileHistory, history.ts). The row is+ the same .sp-ab-version with a "Changes" button beside it; the word diff+ hangs UNDER the row, because prose needs the card's full width. Colours are+ the shared --c-green/--c-red tokens both themes define. */+.sp-hist-row { display: flex; flex-direction: column; }+.sp-hist-head { display: flex; align-items: center; gap: 4px; }+.sp-hist-head .sp-ab-version { flex: 1 1 auto; min-width: 0; }+.sp-hist-head .sp-ab-when { white-space: nowrap; }+/* the summary WRAPS rather than truncating: in the 440px card a derived+ sentence is the whole point of the row, and an ellipsis hid it */+.sp-hist-head .sp-ab-vtag { flex: 1 1 auto; min-width: 0; overflow-wrap: anywhere; }+.sp-ab-version:disabled { cursor: default; }+.sp-ab-version:disabled:hover { background: transparent; border-color: transparent; }+.sp-ab-version:disabled .sp-ab-vdo { display: none; }+.sp-hist-diff-btn {+ flex: 0 0 auto; padding: 6px 9px; border: 1px solid transparent;+ border-radius: 8px; background: transparent; color: var(--muted);+ font: inherit; font-size: 12px; cursor: pointer;+}+.sp-hist-diff-btn:hover { background: var(--chrome-2); border-color: var(--line); color: var(--ink); }+.sp-hist-diff-btn:focus-visible { border-color: var(--blue); outline: none; }+.sp-hist-diff-btn[aria-expanded='true'] { color: var(--blue); }+.sp-hist-diff {+ margin: 2px 0 10px; padding: 8px 10px; border-inline-start: 2px solid var(--line);+ background: var(--chrome); border-radius: 0 8px 8px 0;+ max-height: 320px; overflow-y: auto;+}+.sp-hist-page { font-size: 12px; font-weight: 600; margin: 6px 0 2px; }+.sp-hist-page:first-child { margin-top: 0; }+.sp-hist-chip {+ display: inline-block; margin-inline-start: 6px; padding: 0 6px;+ border-radius: 999px; background: var(--chrome-2); color: var(--muted);+ font-size: 11px; font-weight: 400;+}+.sp-hist-line { margin: 0 0 4px; font-size: 12.5px; line-height: 1.5; color: var(--ink-2); overflow-wrap: anywhere; }+.sp-hist-line ins { text-decoration: none; background: color-mix(in srgb, var(--c-green) 16%, transparent); color: var(--c-green); }+.sp-hist-line del { background: color-mix(in srgb, var(--c-red) 14%, transparent); color: var(--c-red); }+.sp-hist-empty { color: var(--muted); font-style: italic; }+/* The new-property form inside the add-property popover: a name, a type and abutton, on one line until the popover is too narrow for it. */.sp-newprop { display: flex; flex-wrap: wrap; gap: 6px; padding: 4px 6px 6px; }