Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

dash: stopping or rotating sharing marks the workbook unsaved; only a writer copy writes (#597)

nyblnet31b6d7f112af
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ab556be4..57a02636 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -859,6 +859,12 @@ jobs:
- name: bento/dash selection and clipboard
run: node scripts/test-dash-select.ts
+ - name: bento/dash sharing state
+ # Start/stop/rotate sharing mark the workbook unsaved (a rotation is
+ # revocation and must reach the file); only a writer copy offers write
+ # auth or calls itself an Editor — an allowlist, failing closed.
+ run: node scripts/test-dash-share-dirty.ts
+
- name: bento/dash conditional formatting
run: node scripts/test-dash-condfmt.ts
diff --git a/dash/CHANGELOG.md b/dash/CHANGELOG.md
index 3402f6c0..67673c6b 100644
--- a/dash/CHANGELOG.md
+++ b/dash/CHANGELOG.md
@@ -12,6 +12,18 @@ There is no server, so a break here would be permanent.
The release that came out of watching somebody use 0.2.0.
+- **Stopping sharing or rotating its keys now marks the workbook unsaved.**
+ Rotating the keys is how you cut off everyone you sent a copy to, and it only
+ takes effect once the file holds the new keys. It used to change the workbook
+ without lighting the unsaved dot, so closing the window threw the rotation
+ away with no warning and no automatic save. Turning sharing back on after
+ stopping it does the same.
+
+- **A live-show audience copy no longer presents itself as an editor.** Its
+ role was checked as "anything but reader", so it offered its show ticket to
+ the relay as write access and appeared as an Editor to everyone else. Only a
+ writer copy now does either.
+
- **Sheet tabs along the bottom**, where every spreadsheet has kept them since
Excel 5. They were a list inside the left panel; that panel is gone, and the
grid is about 200px wider at every window size. Drag to reorder — and because
diff --git a/dash/src/main.ts b/dash/src/main.ts
index 9c4aa1bb..91208efd 100644
--- a/dash/src/main.ts
+++ b/dash/src/main.ts
@@ -1324,6 +1324,8 @@ function boot(doc: DashDoc, repaired: number, frozen?: 'policy' | 'version', sav
;(window as unknown as Record<string, unknown>).__sync = sync
store.on('doc', markDirty)
+ // sharing switched on/off or keys rotated: no data edit, but the file is behind
+ store.on('unsaved', markDirty)
// The wordmark and the version chip open About. Mounted AFTER markDirty
// exists — it takes it as the dirty signal for the edits it makes itself.
diff --git a/dash/src/store.ts b/dash/src/store.ts
index d1f81143..2a6f8022 100644
--- a/dash/src/store.ts
+++ b/dash/src/store.ts
@@ -38,7 +38,12 @@ import { PROVENANCE_OPS } from './steps.ts'
import type { CellOverride, Comment, View, Column, ColumnData, ColumnType, DashDoc, Measure, Sheet, Step, TableSheet, CanvasCell, CanvasSheet } from './model.ts'
type Listener = () => void
-export type StoreEvent = 'doc' | 'view' | 'selection'
+/**
+ * 'unsaved' — the document changed in a way that is not an edit to its data
+ * and goes through no patch (sharing switched on or off, keys rotated), but
+ * the FILE must still be rewritten for it. See `markUnsaved`.
+ */
+export type StoreEvent = 'doc' | 'view' | 'selection' | 'unsaved'
/** Idle that closes a run. Autosave debounces longer, so no snapshot lands mid-run. */
const RUN_IDLE_MS = 600
@@ -1212,6 +1217,21 @@ export class Store {
this.emit('view')
}
+ /**
+ * The document changed OUTSIDE the patch vocabulary, and the file is now
+ * behind it. Not undoable, not a repaint — just "this needs saving".
+ *
+ * Exists for sharing. Starting, stopping and rotating write `doc.collab`
+ * directly (they are not edits to the workbook's data and must not sit in
+ * its undo history), and nothing told the unsaved dot. So a key ROTATION —
+ * which is revocation — could be closed without a warning and without the
+ * automatic save, and the file kept the keys that were meant to be dead.
+ */
+ markUnsaved(): void {
+ this.touch()
+ this.emit('unsaved')
+ }
+
/** Model changed without a new undo entry (mid-run). */
touch(): void {
this.doc.modified = new Date().toISOString()
diff --git a/dash/src/sync/online.ts b/dash/src/sync/online.ts
index aa4f4b47..9ec1cdb3 100644
--- a/dash/src/sync/online.ts
+++ b/dash/src/sync/online.ts
@@ -105,10 +105,33 @@ export interface CollabBlock {
/** legacy 1.0.2-era shared writer key */
writerPub?: string
writerPriv?: string
- role?: 'writer' | 'reader'
+ /**
+ * What this COPY may do. Absent or 'writer' = it writes; 'reader' = a live
+ * viewer; 'audience' = a live-SHOW member (kernel sync, #454) whose transport
+ * is receive-only. Typed to the kernel's own union — it was narrower here,
+ * which is how a role the kernel can hand us came to be read as a writer.
+ * See `copyCanWrite`.
+ */
+ role?: 'writer' | 'reader' | 'audience'
sync?: SyncStateJSON
}
+/**
+ * May THIS COPY write to its room?
+ *
+ * An ALLOWLIST, failing closed. Both gates used to ask `role !== 'reader'`,
+ * which says yes to every role invented after it — so an 'audience' copy
+ * offered its owner-signed show ticket as WRITE auth and called itself an
+ * Editor in presence. A future role that can write will show as view-only
+ * until this learns about it: visible and harmless. The old shape's failure
+ * was invisible and wrong. Absent means writer because every file older than
+ * the role field is one. Same rule as type's `copyCanWrite` (#588).
+ */
+export function copyCanWrite(collab: CollabBlock | undefined): boolean {
+ if (!collab) return false
+ return collab.role === undefined || collab.role === 'writer'
+}
+
export const collabOf = (doc: DashDoc): CollabBlock | undefined =>
(doc.collab as CollabBlock | undefined) ?? undefined
@@ -740,7 +763,7 @@ export function joinFromDoc(session: SyncSession, store: Store): OnlineTransport
}
active?.close()
let auth: AuthSpec | undefined
- if (collab.role !== 'reader') {
+ if (copyCanWrite(collab)) {
if (collab.v === 2 && collab.owner && collab.ownerPriv) {
auth = { kind: 'direct', pub: collab.owner, priv: collab.ownerPriv }
} else if (collab.v === 2 && collab.owner && collab.invite) {
@@ -768,7 +791,10 @@ export async function startSharing(session: SyncSession, store: Store): Promise<
if (active) return active
const doc = store.doc as DashDoc & { collab?: CollabBlock }
if (!doc.collab) doc.collab = await mintCollab()
+ const was = doc.collab.on
doc.collab.on = true
+ // the file has to learn it is shared, or a copy saved from it never joins
+ if (was !== true) store.markUnsaved()
session.enableSharing()
return joinFromDoc(session, store)
}
@@ -792,7 +818,7 @@ export function stopSharing(session: SyncSession, store: Store) {
active = null
}
const c = collabOf(store.doc)
- if (c && c.on !== false) c.on = false
+ if (c && c.on !== false) { c.on = false; store.markUnsaved() }
}
/** revocation: mint a fresh room + key. Every previously sent copy loses
@@ -803,6 +829,8 @@ export async function rotateKeys(session: SyncSession, store: Store) {
const doc = store.doc as DashDoc & { collab?: CollabBlock }
const sync = doc.collab?.sync
doc.collab = sync ? { ...fresh, sync } : fresh
+ // revocation is only real once the FILE holds the new keys
+ store.markUnsaved()
}
/** Save-a-copy helpers: what to strip for each tier. A reader copy keeps the
diff --git a/dash/src/sync/session.ts b/dash/src/sync/session.ts
index e7f28476..50e543e0 100644
--- a/dash/src/sync/session.ts
+++ b/dash/src/sync/session.ts
@@ -23,7 +23,7 @@
import type { Store, Patch } from '../store.ts'
import type { DashDoc } from '../model.ts'
import { DashSync, SYNC_V, committable, type Op, type SyncStateJSON } from './crdt.ts'
-import { collabOf, mintCollab, type CollabBlock } from './online.ts'
+import { collabOf, copyCanWrite, mintCollab, type CollabBlock } from './online.ts'
import { lsGet, lsJson } from '../../../kernel/src/storage.ts'
export interface PresenceInfo {
@@ -392,7 +392,9 @@ export class SyncSession {
let pub: string | undefined
let role: 'owner' | 'editor' | 'viewer' | undefined
if (c) {
- if (c.role === 'reader') role = 'viewer'
+ // a copy that cannot write is a Viewer whatever keys it carries — an
+ // audience copy holds an owner-signed invite, and was called an Editor
+ if (!copyCanWrite(c)) role = 'viewer'
else if (c.v === 2 && c.ownerPriv) { role = 'owner'; pub = c.owner }
else if (c.v === 2 && c.invite) {
role = 'editor'
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 32c2c193..607c4a8d 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -7442,6 +7442,30 @@ rigs treat a drawn arrow as a deliberate difference: named in
`test-maths-lite.ts`, counted with the identical ones in the coverage floor.
Cost: +966 B of shell.
+## 2026-10-04 — dash: sharing changes mark the workbook unsaved; copy roles are an allowlist
+
+Dash carries its own copy of the sharing verbs (`dash/src/sync/online.ts`), and
+they wrote `doc.collab` directly. Slides, spaces and type use the kernel's
+versions, which go through `store.commit`, and each of those apps lights its
+unsaved state from commit. Checked all three: none has this gap.
+
+- **`Store.markUnsaved()`** advances the document (`touch`) and raises a new
+ `'unsaved'` event that main.ts wires to the same `markDirty` as `doc`. It is
+ deliberately NOT a commit: sharing state is not an edit to the data and must
+ not be undoable. It is called when sharing turns on from off, turns off, or
+ rotates. Minting credentials for a new workbook stays silent, because dash
+ mints with `on: true` and an untouched starter must close without a warning.
+- **`copyCanWrite(collab)`** — absent role or `'writer'` writes; everything else,
+ including any role invented later, does not. It replaces `role !== 'reader'`
+ in the relay auth gate and in presence. The same rule as type's (#588); the
+ kernel's union added `'audience'` and dash's narrower type had hidden it.
+- Rig `scripts/test-dash-share-dirty.ts`, 27 checks, uses a fake WebSocket so
+ no network is touched. Seven sabotages each turn it red.
+
+Observed, not changed: the kernel's `startSharing`/`stopSharing` commit through
+the UNDO history in slides, spaces and type, so ⌘Z after "Stop sharing" sets
+`collab.on` back without reconnecting.
+
## 2026-10-04 — slides: write chrome is an allowlist, and the lock follows a document that arrives
The editor decided whether a copy could write with `collab.role !== 'reader'`. That
diff --git a/scripts/test-dash-share-dirty.ts b/scripts/test-dash-share-dirty.ts
new file mode 100644
index 00000000..4dcf4cde
--- /dev/null
+++ b/scripts/test-dash-share-dirty.ts
@@ -0,0 +1,160 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/dash SHARING STATE rig — two gates in dash/src/sync/online.ts.
+//
+// node scripts/test-dash-share-dirty.ts
+//
+// 1. STARTING, STOPPING OR ROTATING SHARING MARKS THE WORKBOOK UNSAVED. They
+// write `doc.collab` directly — not data edits, so not patches and not undo
+// entries — and nothing told the unsaved dot. A key ROTATION is revocation:
+// closed without saving, the file kept the keys meant to be dead, with no
+// warning and no automatic save to the file. Minting credentials for a new
+// workbook stays silent, or every untouched starter would warn on close.
+//
+// 2. ONLY A WRITER COPY OFFERS WRITE AUTH. Both gates asked
+// `role !== 'reader'`, so the kernel's newer 'audience' role (a live-show
+// member, receive-only) presented its show ticket as write auth and called
+// itself an Editor in presence. Now an allowlist that fails closed —
+// `copyCanWrite`, the same rule as type's (#588).
+
+import { registerHooks } from 'node:module'
+registerHooks({
+ load(url, context, next) {
+ if (url.endsWith('.css')) return { format: 'module', source: 'export {}', shortCircuit: true }
+ return next(url, context)
+ },
+})
+
+// No network, ever: a socket that records what it was asked for and stays shut.
+const opened: string[] = []
+class FakeSocket {
+ readyState = 0
+ constructor(url: string) { opened.push(url) }
+ addEventListener() {}
+ removeEventListener() {}
+ send() {}
+ close() {}
+}
+;(globalThis as { WebSocket: unknown }).WebSocket = FakeSocket
+
+const { parseDoc } = await import('../dash/src/model.ts')
+const { Store } = await import('../dash/src/store.ts')
+const online = await import('../dash/src/sync/online.ts')
+const { SyncSession } = await import('../dash/src/sync/session.ts')
+const { startSharing, stopSharing, rotateKeys, copyCanWrite, joinFromDoc, collabOf, mintCollab, disconnectOnline } = online
+type DashDoc = import('../dash/src/model.ts').DashDoc
+
+let checks = 0, failures = 0
+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`) } else console.log(` ok ${m}`) }
+
+const fresh = (collab?: object): DashDoc => {
+ const r = parseDoc(JSON.stringify({
+ format: 'bento/dash', version: 1, policy: 'bento-dash-1', docId: 'd', title: 'Book',
+ ...(collab ? { collab } : {}),
+ sheets: [{
+ id: 'sh', kind: 'table', name: 'Data', rids: [[1, 1]], nextRid: 2,
+ columns: [{ id: 'v', name: 'Value', type: 'number' }],
+ data: { v: { enc: 'raw', v: [1] } }, steps: [],
+ }],
+ }))
+ if (!r.ok) throw new Error('fixture')
+ return r.doc
+}
+
+/** A session that records the transport it is handed, and connects nothing. */
+function fakeSession() {
+ const made: unknown[] = []
+ return {
+ made,
+ enableSharing() {},
+ addTransport(factory: (docId: string, onFrame: () => void) => unknown) { made.push(factory('d', () => {})) },
+ removeTransport() {},
+ applySnapshot() {}, snapshot() { return null }, hello() {}, onRelayReady() {}, refused() {},
+ }
+}
+const watch = (s: InstanceType<typeof Store>) => {
+ const n = { unsaved: 0 }
+ s.on('unsaved', () => { n.unsaved++ })
+ return n
+}
+
+console.log('starting, stopping and rotating sharing mark the workbook unsaved')
+{
+ // A workbook whose sharing was STOPPED. (A new one is minted with on:true
+ // and stays dormant until opted in — starting it changes no byte of the
+ // document, so there is nothing for the file to learn; that case is below.)
+ const s = new Store(fresh({ ...(await mintCollab()), on: false })), n = watch(s), sess = fakeSession()
+ await startSharing(sess as never, s)
+ ok(collabOf(s.doc)?.on === true, 'sharing is on in the document')
+ ok(n.unsaved === 1, `starting marks it unsaved — the file must learn it is shared (${n.unsaved})`)
+ await startSharing(sess as never, s)
+ ok(n.unsaved === 1, 'starting again when already on changes nothing and says nothing')
+ stopSharing(sess as never, s)
+ ok(collabOf(s.doc)?.on === false && n.unsaved === 2, 'stopping marks it unsaved')
+ stopSharing(sess as never, s)
+ ok(n.unsaved === 2, 'stopping when already off says nothing')
+ const room = collabOf(s.doc)?.room
+ await rotateKeys(sess as never, s)
+ ok(collabOf(s.doc)?.room !== room, 'rotation minted a new room')
+ ok(n.unsaved >= 3, `ROTATION marks it unsaved — revocation is only real once the file holds the new keys (${n.unsaved})`)
+ ok(!s.canUndo, 'and none of it entered the undo history — it is not an edit to the data')
+ disconnectOnline(sess as never)
+}
+
+console.log('\nminting credentials for a NEW workbook stays silent')
+{
+ // and so does opting a never-saved workbook in: its credentials were minted
+ // on:true, so `startSharing` changes no byte of the document
+ const s0 = new Store(fresh({ ...(await mintCollab()) })), n0 = watch(s0), sess0 = fakeSession()
+ await startSharing(sess0 as never, s0)
+ ok(n0.unsaved === 0, 'opting in a workbook already marked on changes nothing in it, and says nothing')
+ disconnectOnline(sess0 as never)
+
+ const s = new Store(fresh()), n = watch(s)
+ new SyncSession(s)
+ await new Promise((r) => setTimeout(r, 50))
+ ok(!!collabOf(s.doc)?.room, 'the session minted credentials at creation')
+ ok(n.unsaved === 0, 'and did NOT mark the workbook unsaved — an untouched starter must close without a warning')
+}
+
+console.log('\ncopyCanWrite is an allowlist that fails closed')
+for (const [role, want] of [
+ [undefined, true], ['writer', true], ['reader', false], ['audience', false], ['commenter', false], ['owner', false],
+] as const) {
+ ok(copyCanWrite({ room: 'r', key: 'k', ...(role ? { role } : {}) } as never) === want,
+ `role ${role ?? '(absent — every file older than the field)'} → ${want ? 'writes' : 'does not write'}`)
+}
+ok(copyCanWrite(undefined) === false, 'no collab block → does not write')
+
+console.log('\nonly a writer copy offers write auth to the relay')
+{
+ const creds = await mintCollab()
+ for (const [role, wantAuth] of [[undefined, true], ['reader', false], ['audience', false]] as const) {
+ const s = new Store(fresh({ ...creds, on: true, ...(role ? { role } : {}) }))
+ const sess = fakeSession()
+ disconnectOnline(sess as never)
+ joinFromDoc(sess as never, s)
+ const t = sess.made[0] as { auth?: unknown } | undefined
+ ok(!!t, `a transport was built for role ${role ?? '(absent)'}`)
+ ok(!!t?.auth === wantAuth, `role ${role ?? '(absent)'} ${wantAuth ? 'signs as a writer' : 'offers NO write auth'}`)
+ ;(t as { close?: () => void } | undefined)?.close?.()
+ disconnectOnline(sess as never)
+ }
+}
+
+console.log('\nan audience copy is a Viewer in presence, not an Editor')
+{
+ const creds = await mintCollab()
+ for (const [role, want] of [['audience', 'viewer'], ['reader', 'viewer'], [undefined, 'owner']] as const) {
+ const s = new Store(fresh({ ...creds, ...(role ? { role } : {}) }))
+ const sess = new SyncSession(s) as unknown as { presence?: () => { role?: string }; selfPresence?: () => { role?: string } }
+ const p = (sess.presence ?? sess.selfPresence)?.call(sess)
+ ok(p?.role === want, `role ${role ?? '(absent, owner keys)'} → ${want} — got ${p?.role}`)
+ }
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+// A SyncSession keeps heartbeat timers, and they would hold the process open
+// after a clean run — which a CI runner reports as a hang, not a pass.
+process.exit(failures ? 1 : 0)