Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

spaces: live collaboration, and the five answers a notes app gives differently (#320)

nyblneta38fa5917dcc
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d2b27163..c25894a7 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -701,3 +701,14 @@ jobs:
# flat document, text on the parent, a store with one listener and no
# dirty flag — so a surviving slides assumption shows up there.
run: node --no-warnings scripts/test-sync-session.ts
+
+ - name: the spaces binding of the sync session
+ # Only what bento/spaces answers DIFFERENTLY, because three of the five
+ # host answers are not slides' answers and each one is invisible until
+ # two people are live: a repair id that must be DERIVED (a spare blank
+ # slide is one click to delete; a spare page is a phantom), a view that
+ # clamps by page identity to the nearest surviving ANCESTOR rather than
+ # to home, and a remote op that must not raise this app's 'doc' event —
+ # which paints "Edited" and would credit a colleague's typing to you.
+ # The last section is two real sessions over a real BroadcastChannel.
+ run: node --no-warnings scripts/test-sync-spaces-session.ts
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 10e9b721..d19b874c 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -14,6 +14,118 @@ Decision. Why. Pointers.
---
+## 2026-08-18 — A shared space connects on open; a fresh one still does not
+
+bento/spaces follows the rule bento/slides already ships: `shareEligible()` —
+auto-connect on open ONLY if the document arrived carrying collab credentials
+(it was saved, or somebody shared it), or if the user opted in during this
+session. A never-saved starter space and a template someone is kicking the
+tyres on stay dormant.
+
+The alternative was to connect whenever credentials exist. That is the obvious
+call and it is wrong here for a reason this repo has already paid for: v0.9.0
+of slides connected every visitor to the anonymous demo and v0.9.1 had to undo
+it. The rule is also already written down for this app — "A space does not
+phone home when it is opened" (2026-08-03) — and nothing about collaboration
+changes what that promise means.
+
+Worth being honest about the wrinkle, because it is the reason to revisit
+rather than close this. A space is a whole wiki, so "open the file somebody
+mailed me" is a far more ordinary act than opening a deck, and that file
+carries credentials by construction: the capability IS the file. Receiving a
+space therefore joins its room, which is what the sender intended and may not
+be what the reader expected.
+
+TO BE REVISITED WITH bento/vault, which is where per-recipient access stops
+being a property of the file and starts being something a broker can answer.
+Until then the file is the capability and this rule is the whole of the
+protection. Decided by the user, 2026-08-18.
+
+---
+
+## 2026-08-18 — The healed page's id comes from the ROOM, not from docId
+
+The kernel's `heal()` contract is explicit that a repair does not converge by
+itself: it is minted as an ordinary local op, and two replicas that heal at the
+same moment mint two nodes which the CRDT faithfully keeps. It tells an
+implementer to derive the id from stable document data, and it suggests
+`docId`.
+
+**bento/spaces must not use `docId`**, and the reason was already written down
+next to `repairId` in model.ts before collab existed: `template: true` re-mints
+`docId` on every open, so a docId-derived id gives two readers of ONE file
+different ids — precisely the failure derivation exists to prevent.
+
+`doc.collab.room` is the right seed. Every replica that can race to heal is by
+definition in the same room; the value is identical for all of them by
+construction; and it does not move when a template is opened. The fallback to
+`docId` is safe exactly where it is reached — a document with no room has no
+second replica to disagree with.
+
+Pinned by scripts/test-sync-spaces-session.ts: two replicas with the same room
+and DIFFERENT docIds still heal to one page.
+
+Also settled while binding: "empty" for a space is ZERO PAGES, not an empty
+page — and a dangling `doc.home` is NOT a repair case, because `homePage()`
+already falls back to `pages[0]` on its own. Minting a page for it would
+manufacture a phantom to fix something that was never broken.
+
+---
+
+## 2026-08-18 — 'doc' is this app's dirty signal, so a remote op must not raise it
+
+The kernel session used to emit `'doc'` after every remote change, because that
+is what bento/slides calls "something changed, repaint". In bento/spaces the
+same name means something else: editor.ts binds it to `status('Edited')`, the
+unsaved dot and the undo buttons. Emitting it for a colleague's keystroke would
+put "Edited" in this user's chrome for someone else's work.
+
+The kernel now takes `changeEvents` and `structureEvents` from the app. Spaces
+declares `changeEvents: ['page']` and `structureEvents: ['tree']`: 'page' is
+bound to paintPage + paintTree and carries no status text, so it repaints
+without claiming authorship, and 'tree' covers a structural change to a page
+other than the one on screen.
+
+The first version declared `changeEvents: []`, reasoning that repaints could
+ride on the structural events alone. That is wrong and the rig did not catch
+it — two browser tabs did. A remote TEXT edit is not structural, so nothing
+fired: `block.html` held the new sentence while the DOM still showed the old
+one. Every remote change must repaint; only the authorship claim was ever the
+thing to withhold.
+
+The dot still has to move: the file on disk IS out of date, however the change
+arrived. The kernel calls `store.setDirty(true)` independently of the events,
+and store.ts routes that to its own `'dirty'` event, which the editor binds to
+the dot alone. Two facts, two signals, instead of one signal asked to carry
+both.
+
+A REMOTE APPLY ALSO BYPASSES `commit()` — deliberately, so it never joins this
+person's undo stack — which leaves `store.index` describing the document as it
+was. `clampView()` therefore calls `reindex()` before anything reads the index.
+This was not theoretical: measured, a block that had already arrived in
+`doc.pages[0].blocks` was invisible to `store.block(id)`, and the first version
+of the rig hid it by reindexing by hand.
+
+---
+
+## 2026-08-18 — Where a reader lands when somebody deletes what they are reading
+
+A deck clamps an INDEX. A space navigates by page identity (`#p/<id>`), so the
+only question is whether the page you are reading still exists — and when it
+does not, `reindex()`'s own fallback sends you to the home page, out of the
+part of the space you were working in.
+
+`clampView()` surfaces at the nearest surviving ANCESTOR instead, falling back
+to home only when the whole chain is gone. It needs `captureView()` for that:
+after the apply the page is simply gone and there is nothing left to be near.
+
+Presence reports the PAGE and never the block. A block-level cursor would
+republish presence at typing speed — the typing run in store.ts exists because
+a notes app may never blur — while a page changes only when somebody
+navigates, which is the rate presence is worth.
+
+---
+
## 2026-08-16 — Document search: the list stays native, the indexer is shared by FIXTURE
**Decision.** When the native hosts grow a document library, each keeps its own
diff --git a/scripts/size-budgets.json b/scripts/size-budgets.json
index b437471c..9774ebf8 100644
--- a/scripts/size-budgets.json
+++ b/scripts/size-budgets.json
@@ -3,8 +3,8 @@
"shells": {
"spaces": {
"path": "spaces/dist-single/Bento_Spaces.bento.html",
- "max": 147456,
- "//": "144 KiB. Raised from 140: the view controls (layout, group-by, sort) and the board's Markdown export cost ~3.4 KB compressed — the sort engine, three popovers and 17 strings × 8 locales, which is most of it. Measured with magic notes, daily notes and the mobile fold already in: 142,674 B, which is 99.5% of the old ceiling and 686 B of headroom. That is not enough: the shell is mostly a zlib block and zlib differs across node versions — one commit measured 130,095 B on node 26 locally and 131,246 B on CI node 24, so this would have failed CI while passing here. CI is the number that counts."
+ "max": 163840,
+ "//": "160 KiB. Raised from 144: live collaboration costs 16,772 B compressed — the CRDT engine, the session, the E2EE relay transport and the blob offload, measured at 142,674 B before and 159,446 B after. That is well inside the ~30 KB the feature was budgeted at, and it is the largest single item this shell will take: every saved space carries it whether or not anyone shares that space. Headroom is deliberate — the shell is mostly a zlib block and zlib differs across node versions (one commit measured 130,095 B on node 26 locally and 131,246 B on CI node 24), so a tight ceiling fails in CI for no reason. CI is the number that counts."
}
}
}
diff --git a/scripts/test-sync-spaces-session.ts b/scripts/test-sync-spaces-session.ts
new file mode 100644
index 00000000..766cd366
--- /dev/null
+++ b/scripts/test-sync-spaces-session.ts
@@ -0,0 +1,295 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The bento/spaces binding of the kernel sync session.
+//
+// node --no-warnings scripts/test-sync-spaces-session.ts
+//
+// scripts/test-sync-session.ts already drives the kernel session hard, through
+// slides and through type. This rig covers only what the SPACES host answers
+// differently — because three of the five answers are not slides' answers, and
+// each one is a bug that would be invisible until two people were live:
+//
+// heal() a spare blank slide is visible in a deck's sidebar and
+// deleted in one click; a spare PAGE is a phantom nobody can
+// explain. So the id must be derived, and two replicas that
+// heal at the same moment must produce the SAME page.
+// clampView() a deck clamps an INDEX; a space navigates by page identity,
+// and when the subtree you are reading is deleted the honest
+// destination is the nearest surviving ANCESTOR, not home.
+// changeEvents 'doc' means "you edited something" in this app and paints
+// "Edited". A remote op must not raise it.
+//
+// It drives the REAL session over the REAL Store through a REAL
+// BroadcastChannel: two sessions in one process are two tabs of one file.
+
+const listeners: Record<string, Array<() => void>> = {}
+;(globalThis as unknown as { window: unknown }).window = {
+ setTimeout: (fn: () => void, ms: number) => setTimeout(fn, ms),
+ clearTimeout: (h: number) => clearTimeout(h),
+ setInterval: (fn: () => void, ms: number) => setInterval(fn, ms),
+ clearInterval: (h: number) => clearInterval(h),
+ addEventListener: (ev: string, fn: () => void) => { (listeners[ev] ??= []).push(fn) },
+}
+
+const { register } = await import('node:module')
+register('./lib/ts-resolve-hooks.mjs', import.meta.url)
+
+const { Store } = await import('../spaces/src/store.ts')
+const { SyncSession } = await import('../spaces/src/sync/session.ts')
+const { FORMAT, FORMAT_VERSION, defaultTheme } = await import('../spaces/src/model.ts')
+
+let failures = 0, checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) } else console.log(` ok ${msg}`)
+}
+const H = (s: string) => console.log(`\n=== ${s} ===`)
+const settle = (ms = 300) => new Promise((r) => setTimeout(r, ms))
+
+type AnyStore = InstanceType<typeof Store>
+
+/** the app-shaped answers, which is all this rig is about */
+const host = (s: unknown) => (s as { host: {
+ heal(): boolean
+ captureView(): unknown
+ clampView(v?: unknown): boolean
+ presence(): { at: string; sel: string[] }
+ carriesMedia(o: unknown[]): boolean
+ changeEvents: readonly string[]
+ structureEvents: readonly string[]
+ presenceEvents: readonly string[]
+} }).host
+
+/** a space with a page tree: home, a parent, and a child under it */
+/**
+ * A space with a page tree: home, a section, and a child under it.
+ *
+ * `id` keys BOTH the room and the BroadcastChannel, and every section passes
+ * its own — because two sessions in one process really are two tabs, and a
+ * session left alive by an earlier section is a third tab in the same room
+ * broadcasting a different document. That is not hypothetical: it made the
+ * first assertion of the end-to-end section fail while the later ones passed.
+ */
+function space(id = 'doc-fixed'): AnyStore {
+ const doc = {
+ format: FORMAT,
+ version: FORMAT_VERSION,
+ docId: id,
+ title: 'Test space',
+ theme: defaultTheme(),
+ collab: { room: `room-${id}`, key: 'k' },
+ home: 'home',
+ pages: [] as unknown[],
+ } as never as import('../spaces/src/model.ts').SpacesDoc
+ doc.pages = [
+ { id: 'home', title: 'Home', blocks: [{ id: 'b1', type: 'p', html: 'hello' }] },
+ { id: 'sec', title: 'Section', blocks: [] },
+ { id: 'kid', title: 'Child', parent: 'sec', blocks: [{ id: 'b2', type: 'p', html: 'in the child' }] },
+ ]
+ doc.home = 'home'
+ return new Store(doc)
+}
+
+// ---------------------------------------------------------------------------
+H('heal(): an emptied space repairs to ONE page, not one per replica')
+{
+ // heal() is driven by the kernel from afterRemoteChange — only a REMOTE
+ // change can empty a document under you. The host is exercised directly
+ // here, which is also the only way to put two replicas in the same instant.
+ const a = space('heal'), b = space('heal')
+ a.doc.pages = []
+ b.doc.pages = []
+ const ha = host(new SyncSession(a)), hb = host(new SyncSession(b))
+
+ ok(ha.heal() === true, 'heal reports it mutated the doc')
+ ok(hb.heal() === true, 'on both replicas')
+ ok(a.doc.pages.length === 1, `a healed to one page (got ${a.doc.pages.length})`)
+ ok(b.doc.pages.length === 1, `b healed to one page (got ${b.doc.pages.length})`)
+ ok(a.doc.pages[0].id === b.doc.pages[0].id,
+ `two replicas healing concurrently produce the SAME page id (${a.doc.pages[0].id} / ${b.doc.pages[0].id})`)
+ ok(a.doc.pages[0].id.startsWith('heal-'),
+ `the healed id is derived, not minted (${a.doc.pages[0].id})`)
+ ok(a.doc.home === a.doc.pages[0].id, 'home points at the healed page')
+ ok(ha.heal() === false, 'a space that already has pages is not repaired again')
+
+ // …and it is derived from the ROOM, not docId: `template: true` re-mints
+ // docId on every open, so a docId-derived id would give two readers of one
+ // file different pages — the failure model.ts repairId already warns about.
+ const t1 = space('tmpl'), t2 = space('tmpl')
+ t1.doc.pages = []; t2.doc.pages = []
+ t1.doc.docId = 'minted-once'; t2.doc.docId = 'minted-again'
+ host(new SyncSession(t1)).heal()
+ host(new SyncSession(t2)).heal()
+ ok(t1.doc.pages[0].id === t2.doc.pages[0].id,
+ 'same room + different docId (a template, re-minted on open) still heals to one page')
+}
+
+// ---------------------------------------------------------------------------
+H('heal(): a dangling home is NOT a repair case')
+{
+ const s = space('dangling')
+ s.doc.home = 'no-such-page'
+ const before = s.doc.pages.length
+ ok(host(new SyncSession(s)).heal() === false, 'heal declines: a home pointing nowhere is not "empty"')
+ ok(s.doc.pages.length === before, 'no page is minted for it')
+ ok(s.page?.id === 'home', 'homePage() already falls back to pages[0] on its own')
+}
+
+// ---------------------------------------------------------------------------
+H('clampView(): a deleted subtree surfaces at the nearest ANCESTOR, not home')
+{
+ // The capture must happen BEFORE the change lands — afterwards the page you
+ // were reading is simply gone and there is nothing left to be near.
+ const s = space('clamp')
+ s.goToPage('kid')
+ ok(s.pageId === 'kid', 'reading the child page')
+ const h = host(new SyncSession(s))
+ const snap = h.captureView()
+ s.doc.pages = s.doc.pages.filter((p: { id: string }) => p.id !== 'kid')
+ h.clampView(snap)
+ ok(s.pageId === 'sec', `surfaced at the surviving parent, not home (got ${s.pageId})`)
+
+ // reindex() on its own would have sent the reader home — that is the whole
+ // reason clampView is not just a call to it.
+ const bare = space('bare')
+ bare.goToPage('kid')
+ bare.doc.pages = bare.doc.pages.filter((p: { id: string }) => p.id !== 'kid')
+ bare.reindex()
+ ok(bare.pageId === 'home', 'reindex alone falls back to home (the behaviour being improved on)')
+
+ // …and when the whole chain is gone, home IS the honest answer
+ const deep = space('deep')
+ deep.goToPage('kid')
+ const hd = host(new SyncSession(deep))
+ const snapd = hd.captureView()
+ deep.doc.pages = deep.doc.pages.filter((p: { id: string }) => p.id === 'home')
+ hd.clampView(snapd)
+ ok(deep.pageId === 'home', `whole chain deleted falls back to home (got ${deep.pageId})`)
+
+ // a page that SURVIVES is never moved
+ const stay = space('stay')
+ stay.goToPage('kid')
+ const hs = host(new SyncSession(stay))
+ const snaps = hs.captureView()
+ stay.doc.pages = stay.doc.pages.filter((p: { id: string }) => p.id !== 'home')
+ hs.clampView(snaps)
+ ok(stay.pageId === 'kid', 'deleting a DIFFERENT page leaves the reader where they were')
+}
+
+// ---------------------------------------------------------------------------
+H('clampView(): blocks somebody else deleted leave the selection')
+{
+ const s = space('sel')
+ s.goToPage('home')
+ s.select(['b1'])
+ const h = host(new SyncSession(s))
+ const snap = h.captureView()
+ s.doc.pages[0].blocks = []
+ const changed = h.clampView(snap)
+ ok(changed === true, 'clampView reports the selection changed')
+ ok(s.selection.length === 0, 'the dead block is out of the selection')
+}
+
+// ---------------------------------------------------------------------------
+H("changeEvents: a remote change must not say 'Edited'")
+{
+ const s = space('events')
+ const h = host(new SyncSession(s))
+ ok(h.changeEvents.join(',') === 'page',
+ `changeEvents is 'page' — EVERY remote change repaints, not just structural ones (got [${h.changeEvents}])`)
+ ok(!h.changeEvents.includes('doc') && !h.structureEvents.includes('doc'),
+ "and neither list contains 'doc', which is this app's \"you edited something\" signal")
+ ok(h.structureEvents.join(',') === 'tree', `structureEvents is tree (got [${h.structureEvents}])`)
+ ok(h.presenceEvents.join(',') === 'page,selection', `presenceEvents is page,selection (got [${h.presenceEvents}])`)
+
+ // the dirty dot still moves, on its OWN event
+ let docEvents = 0, dirtyEvents = 0
+ s.on('doc', () => { docEvents++ })
+ s.on('dirty', () => { dirtyEvents++ })
+ s.setDirty(true)
+ ok(dirtyEvents === 1 && docEvents === 0, `setDirty raises 'dirty' only (doc=${docEvents}, dirty=${dirtyEvents})`)
+ ok(s.dirty === true, 'and the flag is set')
+ s.setDirty(true)
+ ok(dirtyEvents === 1, 'setting it twice does not re-announce')
+}
+
+// ---------------------------------------------------------------------------
+H('presence(): the PAGE, never the block')
+{
+ const s = space('presence')
+ s.goToPage('sec')
+ s.select(['b2'])
+ const h = host(new SyncSession(s))
+ const p = h.presence()
+ ok(p.at === 'sec', `presence reports the page (got ${p.at})`)
+ ok(Array.isArray(p.sel), 'and the selection as an array')
+}
+
+// ---------------------------------------------------------------------------
+H('carriesMedia(): names an embedded image, ignores ordinary prose')
+{
+ const s = space('media')
+ const h = host(new SyncSession(s))
+ const img = { op: 'ins', node: { id: 'x', type: 'image', src: 'data:image/png;base64,AAAA' } }
+ const txt = { op: 'ins', node: { id: 'y', type: 'p', html: 'just words' } }
+ const setSrc = { op: 'set', v: 'data:image/png;base64,BBBB' }
+ const setTxt = { op: 'set', v: 'a sentence' }
+ ok(h.carriesMedia([img]) === true, 'an inserted data: image is media')
+ ok(h.carriesMedia([txt]) === false, 'a paragraph is not')
+ ok(h.carriesMedia([setSrc]) === true, 'a data: URI written to a property is media')
+ ok(h.carriesMedia([setTxt]) === false, 'ordinary text is not')
+ ok(h.carriesMedia([{ op: 'ins', node: { id: 'p', title: 'P', blocks: [img.node] } }]) === true,
+ 'a page inserted WITH an embedded image is media')
+}
+
+// ---------------------------------------------------------------------------
+H('end to end: two tabs of one space converge')
+{
+ // Two sessions in one process over a real BroadcastChannel ARE two tabs.
+ // Everything above tests the five answers; this tests that the binding as a
+ // whole actually carries an edit, which is the only claim that matters.
+ const a = space('e2e'), b = space('e2e')
+ const sa = new SyncSession(a), sb = new SyncSession(b)
+ await settle()
+
+ a.commit(() => { a.doc.pages[0].blocks.push({ id: 'new-1', type: 'p', html: 'from tab A' }) },
+ { structure: true })
+ await settle()
+ ok(!!b.block('new-1'), 'a block written in tab A arrives in tab B')
+ ok(b.block('new-1')?.html === 'from tab A', '…with its text')
+
+ b.commit(() => { b.doc.pages.push({ id: 'pg-b', title: 'Made in B', blocks: [] }) },
+ { structure: true })
+ await settle()
+ ok(!!a.index.page.get('pg-b'), 'a page made in tab B arrives in tab A')
+
+ // A remote change must not claim to be a local edit — but it MUST still move
+ // the unsaved dot. Cleared first, or `dirty` is left true by A's own commit
+ // above and the assertion passes for the wrong reason.
+ let saidEdited = 0, dot = 0
+ a.setDirty(false)
+ a.on('doc', () => { saidEdited++ })
+ a.on('dirty', () => { dot++ })
+ b.commit(() => { b.doc.pages[0].blocks.push({ id: 'new-2', type: 'p', html: 'again' }) },
+ { structure: true })
+ await settle()
+ ok(!!a.block('new-2'), 'a second remote block lands')
+
+ // A remote TEXT edit is not structural. It must still repaint, which is the
+ // bug two browser tabs found and this rig had not: the model held the new
+ // sentence while the screen kept the old one.
+ let repaints = 0
+ a.on('page', () => { repaints++ })
+ b.commit(() => { b.doc.pages[0].blocks[0].html = 'rewritten in B' })
+ await settle()
+ ok(a.doc.pages[0].blocks[0].html === 'rewritten in B', 'a remote text edit reaches the model')
+ ok(repaints > 0, `…and raises a repaint (page events ${repaints})`)
+ ok(saidEdited === 0, `and tab A never said 'doc' — no "Edited" for a colleague's typing (got ${saidEdited})`)
+ ok(dot === 1 && a.dirty === true, `but the unsaved dot moved (dirty events ${dot}, flag ${a.dirty})`)
+
+ sa.close?.(); sb.close?.()
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)
diff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.md
index a67a975e..dfd09f5f 100644
--- a/spaces/CHANGELOG.md
+++ b/spaces/CHANGELOG.md
@@ -14,6 +14,20 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.
## [Unreleased]
+- **Live collaboration.** Two tabs of the same space, or two people with the
+ same file, now edit it together: changes merge per character, and the file
+ you save carries the state so a copy edited on a plane rejoins as a fork
+ rather than overwriting anyone.
+
+ A space goes live only when it arrived carrying a session — a file that was
+ saved or shared — or when you start one. A fresh space and a template stay
+ offline, as they always have.
+
+ When somebody else deletes the page you are reading, you surface at the page
+ above it rather than being thrown back to the start. And their typing never
+ says "Edited" in your window; only the unsaved dot moves, because the file on
+ disk is out of date either way.
+
- **Fixed: Save was partly off the screen on a phone.** Measured on a 390×844
viewport, the topbar laid out 467px wide inside 390 and the Save button's
right edge landed at x = 426 — 36px past the edge, on the one control that
diff --git a/spaces/README.md b/spaces/README.md
index 28830926..2e58ac6b 100644
--- a/spaces/README.md
+++ b/spaces/README.md
@@ -77,6 +77,7 @@ load contract and format additivity.
| `src/highlight.ts` | the code lexer — text → `{kind, a, b}` ranges, no DOM, no strings |
| `src/markdown.ts` | markdown → blocks, the folder tree → the page tree, `[[wikilinks]]` → `#p/` links. Pure and DOM-free, so the import is tested in node |
| `src/editor.ts` | topbar, sidebar, block menu, `[[` picker, ⌘K, ⌘F, archive |
+| `src/sync/session.ts` | the five answers the kernel cannot work out: what "empty" means, where a reader lands, what presence reports |
| `src/agent.ts` | the agent surface — `validate()`, `outline()`, `stats()`, and the patch verbs behind `window.bento` |
| `src/assets.ts` | content-addressed images and the downscale |
| `src/about.ts` | updates, language, password, exports |
@@ -136,11 +137,10 @@ pages are one document rather than one file each.
## Not built yet
-- **Collaboration.** No CRDT wiring. The sync engine is slides-shaped
- (composite `slideId ␟ elementId` node keys); spaces needs `pageId ␟ blockId`
- and a token RGA over `html`, which is the same shape — but genericizing it is
- its own project, and PLATFORM §10 permits shipping without collab rather than
- with a half-secure version.
+- **A collaboration UI.** The engine is wired — `src/sync/session.ts` binds
+ this app to the kernel session, and two tabs of one file merge — but there is
+ no People panel, no invite flow and no presence cursors yet. Sharing is
+ whatever the file already carries.
- **Tables and embeds.** Deliberate: the format is permanent, so a block type
ships when its model is right, not when its UI is ready. (Databases DID ship —
as the tracker: `doc.fields` is the schema, a `prop` block is a value, and a
diff --git a/spaces/src/editor.ts b/spaces/src/editor.ts
index 349cf6bb..b055a3f2 100644
--- a/spaces/src/editor.ts
+++ b/spaces/src/editor.ts
@@ -104,6 +104,9 @@ export class Editor {
this.store.on('tree', () => this.paintTree())
this.store.on('page', () => { this.paintPage(); this.paintTree() })
this.store.on('doc', () => { this.status(t('Edited')); this.syncHistoryButtons(); this.syncDirty() })
+ // A REMOTE change moves the unsaved dot without claiming you made it —
+ // 'doc' paints "Edited", 'dirty' paints only the dot. See store.setDirty.
+ this.store.on('dirty', () => this.syncDirty())
window.addEventListener('popstate', () => this.fromHash())
this.fromHash()
}
diff --git a/spaces/src/main.ts b/spaces/src/main.ts
index 893b54e2..a921c610 100644
--- a/spaces/src/main.ts
+++ b/spaces/src/main.ts
@@ -30,6 +30,7 @@ import { evaluate, format, pageContext } from './calc'
import { buildSpacePreview } from './preview'
import { Store } from './store'
import { Editor } from './editor'
+import { SyncSession } from './sync/session.ts'
import { downloadMarkdown } from './about'
configureApp({
@@ -192,6 +193,16 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')
if (frozen || doc.readonly) store.readOnly = true
const editor = new Editor(document.getElementById('app')!, store)
+ // Live collaboration. Constructing the session is enough to make same-machine
+ // tabs of one file sync (BroadcastChannel, keyed on docId); the RELAY is not
+ // dialled here — the kernel's shareEligible() gate decides that, and it says
+ // connect only when the document ARRIVED carrying collab credentials (it was
+ // saved or shared) or the user opted in this session. A fresh starter space
+ // and a template tire-kicker stay dormant, which is the rule this app already
+ // wrote down: "A space does not phone home when it is opened".
+ const session = new SyncSession(store)
+ void session
+
if (!frozen && doc.readonly) {
banner(t('This is a reading copy. It opens for reading; nothing you do here changes the file.'))
}
diff --git a/spaces/src/store.ts b/spaces/src/store.ts
index 015e29bd..252f5705 100644
--- a/spaces/src/store.ts
+++ b/spaces/src/store.ts
@@ -16,7 +16,7 @@ type Scope = 'doc' | 'page'
import { type SpacesDoc, type Page, type Block, buildIndex, type SpaceIndex, homePage } from './model'
type Listener = () => void
-type Event = 'doc' | 'page' | 'tree' | 'selection'
+type Event = 'doc' | 'page' | 'tree' | 'selection' | 'dirty'
/** Idle that closes a run. Autosave debounces longer, so no snapshot lands mid-run. */
const RUN_IDLE_MS = 600
@@ -189,6 +189,24 @@ export class Store {
if (wasClean) this.emit('doc')
}
+ /**
+ * Set the unsaved flag from outside a commit.
+ *
+ * The kernel session calls this after applying a REMOTE change: the document
+ * on screen now differs from the file on disk, which is true however the
+ * change arrived. It is deliberately separate from the `doc` event — this
+ * app reads `doc` as "you edited something" and paints "Edited" from it, so
+ * a colleague's keystroke must move the dot without claiming to be yours.
+ */
+ setDirty(v: boolean): void {
+ if (this.dirty === v) return
+ this.dirty = v
+ // NOT 'doc'. The editor reads 'doc' as "you edited something" and paints
+ // "Edited" from it; a colleague's keystroke must move the unsaved dot
+ // without claiming to be yours. 'dirty' carries the dot and nothing else.
+ this.emit('dirty')
+ }
+
/**
* Rebuild the id index, and fall back to the home page if the page being
* viewed no longer exists.
diff --git a/spaces/src/sync/session.ts b/spaces/src/sync/session.ts
new file mode 100644
index 00000000..6b3e85b5
--- /dev/null
+++ b/spaces/src/sync/session.ts
@@ -0,0 +1,214 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento-sync session for bento/spaces — the kernel session, bound to this app.
+//
+// A FACADE, like crdt.ts beside it. The engine, the transport, the differ, the
+// shadow, catch-up, gap recovery, blobs and the fork snapshot exchange all live
+// in kernel/src/sync/. What is left here is the five things the kernel cannot
+// know: what "empty" means for a space, where the reader is when the document
+// changes underneath them, what presence reports, which store events a remote
+// change should raise, and what embedded media looks like in an op batch.
+//
+// The kernel's SyncHost comment says a word processor answers all five
+// differently. So does a notes app, and three of the five below are NOT what
+// the slides binding does.
+
+export * from '../../../kernel/src/sync/session.ts'
+
+import { SyncSession as KernelSession, type SyncHost } from '../../../kernel/src/sync/session.ts'
+import type { Op } from '../../../kernel/src/sync/crdt.ts'
+import { SyncState } from './crdt.ts'
+import { homePage, type Block, type Page } from '../model.ts'
+import type { Store } from '../store.ts'
+
+/** Where this tab was looking, recorded BEFORE a remote change lands. */
+interface ViewSnapshot {
+ /** the page being read, by identity */
+ pageId: string
+ /** its ancestors, nearest first — the fallback when the page itself dies */
+ ancestors: string[]
+ /** selected block ids, by identity */
+ sel: string[]
+}
+
+/**
+ * The id of the page `heal()` mints.
+ *
+ * DERIVED, never generated. The kernel's heal() contract is explicit that the
+ * repair is minted as an ordinary local op and nothing deduplicates it: two
+ * replicas that heal at the same moment mint two nodes and the CRDT keeps
+ * both. In a deck a spare blank slide is visible in the sidebar and deleted in
+ * one click, which is why slides tolerates a random id. A spare page in a
+ * space is a phantom — it sits in the tree with no content and nothing says
+ * where it came from.
+ *
+ * The contract suggests `docId`. THIS APP MUST NOT USE IT, and the reason is
+ * already written down beside `repairId` in model.ts: `template: true` re-mints
+ * `docId` on every open, so a docId-derived id gives two readers of one file
+ * DIFFERENT ids — the exact failure that derivation exists to prevent.
+ *
+ * The room is the right seed instead. Every replica that can race to heal is
+ * by definition in the same room, the value is identical for all of them by
+ * construction, and it does not move when a template is opened. Falling back
+ * to docId is safe precisely because a document with no room has no second
+ * replica to disagree with.
+ */
+function healId(store: Store): string {
+ const collab = store.doc.collab as { room?: string } | undefined
+ return `heal-${collab?.room || store.doc.docId || 'space'}`
+}
+
+/** The ancestor chain of a page, nearest first, cycle-safe. */
+function ancestorsOf(store: Store, id: string): string[] {
+ const out: string[] = []
+ const seen = new Set<string>([id])
+ let cur = store.doc.pages.find((p) => p.id === id)?.parent ?? ''
+ while (cur && !seen.has(cur)) {
+ seen.add(cur)
+ out.push(cur)
+ cur = store.doc.pages.find((p) => p.id === cur)?.parent ?? ''
+ }
+ return out
+}
+
+/** What a space knows about itself that the session cannot work out. */
+function spacesHost(store: Store): SyncHost {
+ return {
+ store,
+ engine: SyncState,
+
+ heal(): boolean {
+ // "Empty" for a space is ZERO PAGES — not an empty page, and NOT a
+ // dangling `doc.home`: model.ts homePage() already falls back to
+ // pages[0], so a home pointing at a deleted page degrades correctly on
+ // its own and needs no repair op.
+ if (store.doc.pages.length > 0) return false
+ const page: Page = { id: healId(store), title: '', blocks: [] }
+ store.doc.pages.push(page)
+ store.doc.home = page.id
+ return true
+ },
+
+ // Spaces navigates by page IDENTITY (`#p/<id>`), so there is no index to
+ // clamp — the question is only whether the page you are reading still
+ // exists. Captured BEFORE the apply because afterwards the answer is gone.
+ captureView(): unknown {
+ const snap: ViewSnapshot = {
+ pageId: store.pageId,
+ ancestors: ancestorsOf(store, store.pageId),
+ sel: store.selection.slice(),
+ }
+ return snap
+ },
+
+ clampView(view?: unknown): boolean {
+ // FIRST, and before anything reads the index. A remote apply writes
+ // straight to `doc` — deliberately, so it never joins this person's undo
+ // stack — which leaves `store.index` describing the document as it was.
+ // Every `block(id)` and `page` read after that answers from the stale
+ // copy: measured, a block that HAD arrived in `doc.pages[0].blocks` was
+ // invisible to `store.block(id)` until this call. It is why store.ts
+ // makes reindex() public.
+ store.reindex()
+
+ const snap = view as ViewSnapshot | undefined
+ const live = (id: string): boolean => store.index.page.has(id)
+ const before = store.selection
+
+ // PARENT-FIRST, and this is the whole reason clampView is not just
+ // reindex(). When somebody else deletes the subtree you are reading,
+ // reindex()'s fallback sends you to the home page — out of the part of
+ // the space you were working in. The nearest surviving ANCESTOR is where
+ // a reader expects to surface, and only when the whole chain is gone is
+ // home the honest answer.
+ if (snap && !live(snap.pageId)) {
+ const near = snap.ancestors.find(live) ?? homePage(store.doc)?.id ?? ''
+ if (near && near !== store.pageId) {
+ store.pageId = near
+ store.emit('page')
+ store.emit('tree')
+ }
+ }
+
+ // Blocks someone else deleted must leave the selection, or the next
+ // action operates on ids that are not in the document.
+ const kept = before.filter((id) => !!store.block(id))
+ if (kept.length !== before.length) {
+ store.selection = kept
+ return true
+ }
+ return false
+ },
+
+ presence() {
+ // The PAGE, never the block. A block-level cursor would republish
+ // presence at typing speed — store.ts's typing run exists precisely
+ // because a notes app may never blur — while a page changes only when
+ // somebody navigates, which is the rate presence is worth.
+ return { at: store.pageId, sel: store.selection.slice() }
+ },
+
+ // 'doc' is NOT a repaint signal in this app: editor.ts binds it to
+ // status('Edited') + the unsaved dot + the undo buttons, so raising it for
+ // a remote op would credit a colleague's typing to this user. The dot is
+ // handled separately by the kernel's own setDirty(), which store.ts routes
+ // to a 'dirty' event.
+ //
+ // But EVERY remote change still has to repaint, not just structural ones.
+ // changeEvents was empty at first and a remote text edit then landed in the
+ // model while the screen kept the old words — measured in two browser tabs:
+ // `block.html` was the new sentence and the DOM was still the old one. Only
+ // page-level structure (a new page, a delete) was repainting, because those
+ // are the changes that happen to be flagged structural.
+ //
+ // 'page' is the repaint: editor.ts binds it to paintPage + paintTree, and
+ // it carries no status text. 'tree' on top of it is what a structural
+ // change needs when the current page is not the one that moved.
+ changeEvents: ['page'],
+ structureEvents: ['tree'],
+ presenceEvents: ['page', 'selection'],
+
+ carriesMedia,
+ }
+}
+
+/**
+ * Does a refused op batch carry embedded media?
+ *
+ * Structural probe only — a refused batch can be megabytes, so nothing here
+ * re-serializes it or walks deep. App-shaped: in a SPACE an embedded blob is a
+ * block with `type: 'image'` and a data: `src`, or a doc-level `assets.<key>`
+ * (model.ts: `assets?: Record<string, string>`, content-addressed).
+ *
+ * The point is a message somebody can act on: "that image is too big to send"
+ * rather than "the update was refused". Large assets travel out-of-band and
+ * the relay stays blind (docs/DECISIONS.md, 2026-07-25) — this only names what
+ * failed when one slips into a frame.
+ */
+function carriesMedia(ops: Op[]): boolean {
+ const isData = (v: unknown): boolean => typeof v === 'string' && v.startsWith('data:')
+ const inBlock = (n: unknown): boolean => {
+ const b = n as Block | null
+ return !!b && b.type === 'image' && isData(b.src)
+ }
+ return ops.some((o) => {
+ if (o.op === 'set') return isData(o.v) // block src, or a doc-level assets.<k>
+ if (o.op === 'ins') {
+ const node = o.node as { blocks?: unknown[] }
+ return inBlock(o.node) || !!node.blocks?.some(inBlock)
+ }
+ return false
+ })
+}
+
+/**
+ * The session bound to bento/spaces.
+ *
+ * Constructed as `new SyncSession(store)`, the same shape slides uses, so the
+ * editor never sees the host.
+ */
+export class SyncSession extends KernelSession {
+ constructor(store: Store) {
+ super(spacesHost(store))
+ }
+}