AI-native design editor. Open-source Figma alternative.
refactor(collab): move the room's Yjs to SceneGraph mapping into @open-pencil/collab (#1744)
Danila Poyarkov7de6e05a960f
diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfileindex fd4a68645..9af856caa 100644--- a/.devcontainer/Dockerfile+++ b/.devcontainer/Dockerfile@@ -21,6 +21,7 @@ RUN apt-get update \/workspace/open-pencil/node_modules \/workspace/open-pencil/packages/scene-graph/node_modules \/workspace/open-pencil/packages/pen/node_modules \+ /workspace/open-pencil/packages/collab/node_modules \/workspace/open-pencil/packages/kiwi/node_modules \/workspace/open-pencil/packages/fig/node_modules \/workspace/open-pencil/packages/core/node_modules \diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.jsonindex 64620c50e..1191ac23c 100644--- a/.devcontainer/devcontainer.json+++ b/.devcontainer/devcontainer.json@@ -13,6 +13,7 @@"source=open-pencil-root-modules-${devcontainerId},target=/workspace/open-pencil/node_modules,type=volume","source=open-pencil-scene-graph-modules-${devcontainerId},target=/workspace/open-pencil/packages/scene-graph/node_modules,type=volume","source=open-pencil-pen-modules-${devcontainerId},target=/workspace/open-pencil/packages/pen/node_modules,type=volume",+ "source=open-pencil-collab-modules-${devcontainerId},target=/workspace/open-pencil/packages/collab/node_modules,type=volume","source=open-pencil-kiwi-modules-${devcontainerId},target=/workspace/open-pencil/packages/kiwi/node_modules,type=volume","source=open-pencil-fig-modules-${devcontainerId},target=/workspace/open-pencil/packages/fig/node_modules,type=volume","source=open-pencil-core-modules-${devcontainerId},target=/workspace/open-pencil/packages/core/node_modules,type=volume",diff --git a/AGENTS.md b/AGENTS.mdindex 6cad08efe..484e50384 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -10,6 +10,7 @@ This file holds the repository map and the rules that apply everywhere. Rules fo| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- || `packages/scene-graph` | Framework-neutral graph, node types, geometry, copy/snap/undo, variables, instances, hit testing, plus the shared primitives formats need: color conversion and management, CSS value parsing, text/layout direction | `packages/scene-graph/AGENTS.md` || `packages/pen` | Pencil.dev `.pen` model, parser, SceneGraph adapter | — |+| `packages/collab` | How a collaboration room's Yjs document maps to and from a SceneGraph: layers, the shared layer tree, variables, document data; depends on scene-graph and yjs, no Vue or app code, and takes the editor as `CollabEditor` | `packages/collab/AGENTS.md` || `packages/drawio` | draw.io model, reader and writer for `.drawio`/`.dio` files and the diagrams draw.io PNG and SVG exports embed; no SceneGraph | — || `packages/kiwi` | SceneGraph-independent Kiwi schema/runtime, codecs, containers, parse helpers | `packages/fig/AGENTS.md` || `packages/fig` | `.fig` archives, SceneGraph conversion, metadata policy, component/instance interpretation, Figma clipboard | `packages/fig/AGENTS.md` |diff --git a/bun.lock b/bun.lockindex efca0bde7..786f14599 100644--- a/bun.lock+++ b/bun.lock@@ -33,6 +33,7 @@"@nanostores/vue": "^1.1.0","@open-pencil/cli": "workspace:*","@open-pencil/cloud": "workspace:*",+ "@open-pencil/collab": "workspace:*","@open-pencil/core": "workspace:*","@open-pencil/design-jsx": "workspace:*","@open-pencil/dom-css": "workspace:*",@@ -276,6 +277,21 @@"pg": "^8.23.0",},},+ "packages/collab": {+ "name": "@open-pencil/collab",+ "version": "0.17.0-beta.1",+ "dependencies": {+ "@open-pencil/scene-graph": "workspace:*",+ "es-toolkit": "^1.52.0",+ "valibot": "^1.5.0",+ "yjs": "^13.6.32",+ },+ "devDependencies": {+ "@types/bun": "^1.3.14",+ "lib0": "^0.2.117",+ "typescript": "npm:@typescript/typescript6@^6.0.2",+ },+ },"packages/core": {"name": "@open-pencil/core","version": "0.17.0-beta.1",@@ -1710,6 +1726,8 @@"@open-pencil/cloud-tools": ["@open-pencil/cloud-tools@workspace:tools/dev/cloud"],+ "@open-pencil/collab": ["@open-pencil/collab@workspace:packages/collab"],+"@open-pencil/core": ["@open-pencil/core@workspace:packages/core"],"@open-pencil/demo-tools": ["@open-pencil/demo-tools@workspace:tools/generate/demo"],diff --git a/package.json b/package.jsonindex 435f81411..9719dc1ba 100644--- a/package.json+++ b/package.json@@ -14,6 +14,7 @@"packages/dom-css","packages/design-jsx","packages/emit",+ "packages/collab","packages/oxlint-plugin","packages/vue","packages/cli",@@ -67,9 +68,9 @@"build:native-test": "bun run generate:icons --target desktop && bun run build:packages && bun tauri build --debug --no-bundle --features native-test --config desktop/tauri.native-test.conf.json","benchmark:navigation": "bun tools/dev/navigation-benchmark/src/cli.ts run","test:native": "bun run build:native-test && wdio run wdio.conf.ts",- "lint": "bun run lint:structure && oxlint -c oxlint.json --type-aware --type-check src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/feedback/src/ packages/cloud/src/ packages/dom-css/src/ packages/pen/src/ packages/design-jsx/src/ packages/emit/src/ packages/oxlint-plugin/src/ packages/kiwi/src/ packages/fig/src/ packages/drawio/src/ packages/mermaid/src/ packages/docs/.vitepress/theme/landing/",- "lint:structure": "oxlint -c oxlint.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/dom-css/src/ packages/dom-css/tests/ packages/pen/src/ packages/pen/tests/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/emit/src/ packages/oxlint-plugin/src/ packages/oxlint-plugin/tests/ packages/emit/tests/ packages/kiwi/src/ packages/kiwi/tests/ packages/fig/src/ packages/fig/tests/ packages/drawio/src/ packages/drawio/tests/ packages/mermaid/src/ packages/mermaid/tests/ packages/core/tests/ packages/cli/tests/ packages/scene-graph/tests/ packages/vue/tests/ tests/ scripts/ tools/ packages/docs/.vitepress/theme/landing/",- "format": "oxfmt --write .oxfmtrc.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/core/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/cloud/tsdown.config.ts packages/cloud/tsdown.standalone.config.ts packages/vue/src/ packages/dom-css/src/ packages/dom-css/tests/ packages/pen/src/ packages/pen/tests/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/emit/src/ packages/oxlint-plugin/src/ packages/oxlint-plugin/tests/ packages/emit/tests/ packages/kiwi/src/ packages/kiwi/tests/ packages/fig/src/ packages/fig/tests/ packages/drawio/src/ packages/drawio/tests/ packages/mermaid/src/ packages/mermaid/tests/ tests scripts/ tools/ packages/docs/.vitepress/theme/landing/",+ "lint": "bun run lint:structure && oxlint -c oxlint.json --type-aware --type-check src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/feedback/src/ packages/cloud/src/ packages/dom-css/src/ packages/pen/src/ packages/design-jsx/src/ packages/emit/src/ packages/collab/src/ packages/oxlint-plugin/src/ packages/kiwi/src/ packages/fig/src/ packages/drawio/src/ packages/mermaid/src/ packages/docs/.vitepress/theme/landing/",+ "lint:structure": "oxlint -c oxlint.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/dom-css/src/ packages/dom-css/tests/ packages/pen/src/ packages/pen/tests/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/emit/src/ packages/oxlint-plugin/src/ packages/oxlint-plugin/tests/ packages/emit/tests/ packages/collab/src/ packages/collab/tests/ packages/kiwi/src/ packages/kiwi/tests/ packages/fig/src/ packages/fig/tests/ packages/drawio/src/ packages/drawio/tests/ packages/mermaid/src/ packages/mermaid/tests/ packages/core/tests/ packages/cli/tests/ packages/scene-graph/tests/ packages/vue/tests/ tests/ scripts/ tools/ packages/docs/.vitepress/theme/landing/",+ "format": "oxfmt --write .oxfmtrc.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/core/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/cloud/tsdown.config.ts packages/cloud/tsdown.standalone.config.ts packages/vue/src/ packages/dom-css/src/ packages/dom-css/tests/ packages/pen/src/ packages/pen/tests/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/emit/src/ packages/oxlint-plugin/src/ packages/oxlint-plugin/tests/ packages/emit/tests/ packages/collab/src/ packages/collab/tests/ packages/kiwi/src/ packages/kiwi/tests/ packages/fig/src/ packages/fig/tests/ packages/drawio/src/ packages/drawio/tests/ packages/mermaid/src/ packages/mermaid/tests/ tests scripts/ tools/ packages/docs/.vitepress/theme/landing/","format:check": "bun run format && status=$(git status --porcelain -uall) && test -z \"$status\" || (echo \"$status\" && exit 1)","check": "bun run check:icons && bun run build:packages && bun run lint && tsc --noEmit && bun run check:vue && bun run check:native-test && bun run check:i18n && bun run check:docs && bun run check:changelog && bun run check:packages && bun run check:deps && bun run check:audit && bun run check:secrets && bun run check:monorepo && bun run check:arch && bun run check:test-homes && bun run check:cloud-off && bun run check:test-types && bun run test:type-shapes && bun run check:tools && bun run test:tools && bun run test:dupes","check:commits": "commitlint",@@ -106,7 +107,7 @@"test:tools": "bun --filter '@open-pencil/*-tools' test && bun --filter @open-pencil/harness test && bun --filter @open-pencil/oxlint-plugin test","test:feedback": "bun --filter @open-pencil/feedback typecheck && bun --filter @open-pencil/feedback check:types && bun --filter @open-pencil/feedback test","test:cloud": "bun --filter @open-pencil/cloud typecheck && bun --filter @open-pencil/cloud test",- "test:dupes": "jscpd packages/scene-graph/src packages/pen/src packages/design-jsx/src packages/emit/src packages/oxlint-plugin/src packages/core/src packages/cli/src packages/feedback/src packages/cloud/src packages/dom-css/src packages/fig/src src --min-lines 5 --min-tokens 50 --format typescript --threshold 0",+ "test:dupes": "jscpd packages/scene-graph/src packages/collab/src packages/pen/src packages/design-jsx/src packages/emit/src packages/oxlint-plugin/src packages/core/src packages/cli/src packages/feedback/src packages/cloud/src packages/dom-css/src packages/fig/src src --min-lines 5 --min-tokens 50 --format typescript --threshold 0","test:packages": "bun tools/checks/package-quality/src/cli.ts verify","build:packages": "bun tools/release/package-artifacts/src/build.ts","open-pencil": "bun packages/cli/src/index.ts",@@ -155,6 +156,7 @@"@open-pencil/core": "workspace:*","@open-pencil/design-jsx": "workspace:*","@open-pencil/dom-css": "workspace:*",+ "@open-pencil/collab": "workspace:*","@open-pencil/feedback": "workspace:*","@open-pencil/fig": "workspace:*","@open-pencil/harness": "workspace:*",diff --git a/packages/collab/AGENTS.md b/packages/collab/AGENTS.mdnew file mode 100644index 000000000..8856feb51--- /dev/null+++ b/packages/collab/AGENTS.md@@ -0,0 +1,8 @@+# Collab++How a room's Yjs document maps to and from a SceneGraph. The app's rooms, transports, presence, and voice live in `src/app/collab` (`src/AGENTS.md`); this package holds only the document mapping, so a server can read a room the same way the editor does.++- The package depends on `@open-pencil/scene-graph`, `yjs`, `es-toolkit`, and `valibot`, never Vue or app code, and reaches an editor only through the `CollabEditor` interface; a graph with no events and nothing to redraw is a complete editor (`packages/collab/tests/graph-sync.test.ts`).+- A shared document records each layer's parent history, order key and page, never `parentId` or `childIds`, and only Share or a room's conversion sets its root in `meta`; local edits are written by `writeLocalPlacement` and remote changes applied by `applySharedTree` in `packages/collab/src/shared-tree/sync.ts`, which resolve the tree with `LayerTree` from `packages/collab/src/tree/` (`tests/app/collab/random-edits.test.ts`).+- What a document holds outside its layers, its document node's plugin data, comment threads, libraries and color space, travels in the room's own maps through `bindDocumentSync` (`packages/collab/src/document/sync.ts`), entry by entry and thread by thread, never on the root layer, so people changing it at once all keep their change (`tests/app/collab/document/sync.test.ts`).+- Changing how a shared document records data bumps `TREE_FORMAT` and `COLLAB_APP_ID` together, so mismatched builds never meet; rooms saved by an earlier format are not converted (`packages/collab/src/shared-tree/fields.ts`).diff --git a/packages/collab/README.md b/packages/collab/README.mdnew file mode 100644index 000000000..34b59f29e--- /dev/null+++ b/packages/collab/README.md@@ -0,0 +1,10 @@+# @open-pencil/collab++How a collaboration room's [Yjs](https://yjs.dev) document maps to and from an OpenPencil `SceneGraph`. The editor keeps its graph in step with a room through this package, and a server can read a room's document into a graph the same way.++- Layers and their fields, encoded per field so concurrent edits to one layer merge (`node-codec.ts`).+- The shared layer tree: each layer's parents, order key, and page, so concurrent moves converge (`shared-tree/`, `tree/`).+- Variables and collections, and the document's data outside its layers: plugin data, comment threads, libraries, color space, and kind (`variables.ts`, `document/sync.ts`).+- Which of the room's edits its stored revisions hold (`saves.ts`).++It depends on `@open-pencil/scene-graph`, `yjs`, `es-toolkit`, and `valibot`, with no Vue or app code. What a room needs of an editor is the `CollabEditor` interface: its graph, the events of local edits, and the refreshes a peer's edit asks for. Transports, presence, and the room's image storage belong to the app.diff --git a/packages/collab/package.json b/packages/collab/package.jsonnew file mode 100644index 000000000..eab8fe07e--- /dev/null+++ b/packages/collab/package.json@@ -0,0 +1,31 @@+{+ "name": "@open-pencil/collab",+ "version": "0.17.0-beta.1",+ "private": true,+ "description": "How a collaboration room's Yjs document maps to and from an OpenPencil SceneGraph: layers, the shared layer tree, variables, and document data.",+ "license": "MIT",+ "type": "module",+ "sideEffects": false,+ "imports": {+ "#collab/*": "./src/*.ts",+ "#collab-tests/*": "./tests/*.ts"+ },+ "exports": {+ ".": "./src/index.ts"+ },+ "scripts": {+ "test": "bun test tests",+ "typecheck": "bunx tsc --noEmit -p tsconfig.json"+ },+ "dependencies": {+ "@open-pencil/scene-graph": "workspace:*",+ "es-toolkit": "^1.52.0",+ "valibot": "^1.5.0",+ "yjs": "^13.6.32"+ },+ "devDependencies": {+ "@types/bun": "^1.3.14",+ "lib0": "^0.2.117",+ "typescript": "npm:@typescript/typescript6@^6.0.2"+ }+}diff --git a/src/app/collab/document/sync.ts b/packages/collab/src/document/sync.tssimilarity index 91%rename from src/app/collab/document/sync.tsrename to packages/collab/src/document/sync.tsindex e2712d8e4..af8d004b3 100644--- a/src/app/collab/document/sync.ts+++ b/packages/collab/src/document/sync.ts@@ -18,8 +18,7 @@ import {withPluginData} from '@open-pencil/scene-graph/plugin-data'-import type { EditorStore } from '@/app/editor/active-store'-+import type { CollabEditor } from '../editor'import { changedIds, writeChanges, type YRecords } from '../records'import { readRoot, type YMeta } from '../shared-tree/fields'@@ -113,8 +112,8 @@ function documentNodeData(pluginData: readonly PluginDataEntry[]): DocumentNodeD}/** What the document holds that the room shares outside its layers. */-function readDocumentData(store: EditorStore): DocumentData {- const { graph } = store+function readDocumentData(editor: CollabEditor): DocumentData {+ const { graph } = editorreturn {...documentNodeData(graph.getNode(graph.rootId)?.pluginData ?? []),libraries: structuredClone(graph.enabledLibraries),@@ -167,18 +166,18 @@ const readThreadRecord = (value: unknown) => {* the libraries it uses; and its color space. A viewer receives these and sends none.*/export function bindDocumentSync({- store,+ editor,ydoc,data,meta}: {- store: EditorStore+ editor: CollabEditorydoc: Y.Docdata: YDocumentDatameta: YMeta}) {// What the room holds as this peer last wrote or read it, so only what changed since is sent.- let sent = readDocumentData(store)+ let sent = readDocumentData(editor)/** Set while the room's data is applied, so applying it is not sent back. */let receiving = false/** The root the room's document data was last taken in whole for. */@@ -186,12 +185,12 @@ export function bindDocumentSync({function send() {// A joining tab's own document is not the room's until it follows the room.- if (receiving || store.state.hostRestrictions.readOnly || !holdsRoomRoot()) return+ if (receiving || editor.isReadOnly() || !holdsRoomRoot()) returnwrite()}function write() {- const next = readDocumentData(store)+ const next = readDocumentData(editor)ydoc.transact(() => {writeChanges(data.entries, next.entries, sent.entries)writeChanges(data.threads, next.threads, sent.threads, { nested: BY_REPLY })@@ -205,7 +204,7 @@ export function bindDocumentSync({/** Whether this tab shows the room's document, so its document node is the room's. */function holdsRoomRoot(): boolean {const rootId = readRoot(meta)- return rootId !== undefined && rootId === store.graph.rootId+ return rootId !== undefined && rootId === editor.graph.rootId}/**@@ -218,7 +217,7 @@ export function bindDocumentSync({libraries?: ReadonlySet<string>settings?: true}) {- const next = readDocumentData(store)+ const next = readDocumentData(editor)if (!ids || ids.entries) takeRecords(data.entries, next.entries, readEntry, ids?.entries)if (!ids || ids.threads) takeRecords(data.threads, next.threads, readThreadRecord, ids?.threads)if (!ids || ids.libraries) {@@ -244,7 +243,7 @@ export function bindDocumentSync({* peers' layers do, so a viewer, whose editor refuses edits, takes them too.*/function apply(next: DocumentData) {- const { graph } = store+ const { graph } = editorconst root = graph.getNode(graph.rootId)const pluginData = pluginDataOf(next)if (root && !isEqual(root.pluginData, pluginData)) graph.updateNode(root.id, { pluginData })@@ -254,7 +253,7 @@ export function bindDocumentSync({if (next.colorSpace !== undefined) graph.documentColorSpace = next.colorSpaceconst kind = next.kind !== undefined && next.kind !== graph.documentKindif (next.kind !== undefined) graph.documentKind = next.kind- if (libraries || colorSpace || kind) store.refreshDocumentSettings()+ if (libraries || colorSpace || kind) editor.refreshDocumentSettings()}/**@@ -262,8 +261,8 @@ export function bindDocumentSync({* holds what its people changed since the document was saved.*/function follow() {- if (!holdsRoomRoot() || followedRoot === store.graph.rootId) return- followedRoot = store.graph.rootId+ if (!holdsRoomRoot() || followedRoot === editor.graph.rootId) return+ followedRoot = editor.graph.rootIdreceive()}@@ -288,12 +287,12 @@ export function bindDocumentSync({observe('entries'),observe('threads'),observe('libraries'),- store.onEditorEvent('node:updated', (id, changes) => {- if (id === store.graph.rootId && 'pluginData' in changes) send()+ editor.onEditorEvent('node:updated', (id, changes) => {+ if (id === editor.graph.rootId && 'pluginData' in changes) send()}),- store.onEditorEvent('document:libraries-changed', send),- store.onEditorEvent('document:color-space-changed', send),- store.onEditorEvent('document:kind-changed', send)+ editor.onEditorEvent('document:libraries-changed', send),+ editor.onEditorEvent('document:color-space-changed', send),+ editor.onEditorEvent('document:kind-changed', send)]data.settings.observe(onSettings)@@ -303,8 +302,8 @@ export function bindDocumentSync({* root, and the sharing tab is the room's source, so it has nothing to follow.*/share() {- if (store.state.hostRestrictions.readOnly) return- followedRoot = store.graph.rootId+ if (editor.isReadOnly()) return+ followedRoot = editor.graph.rootIdsent = {entries: new Map(),threads: new Map(),diff --git a/packages/collab/src/editor.ts b/packages/collab/src/editor.tsnew file mode 100644index 000000000..4f6ae9762--- /dev/null+++ b/packages/collab/src/editor.ts@@ -0,0 +1,37 @@+import type {+ DocumentColorSpace,+ DocumentKind,+ SceneGraph,+ SceneGraphEvents+} from '@open-pencil/scene-graph'+import type { BindingScope } from '@open-pencil/scene-graph/variables'++/** The editor events a room follows to send this peer's edits. */+export interface CollabEditorEvents extends Omit<SceneGraphEvents, 'node:previewUpdated'> {+ 'history:changed': () => void+ 'document:libraries-changed': () => void+ 'document:color-space-changed': (colorSpace: DocumentColorSpace) => void+ 'document:kind-changed': (kind: DocumentKind) => void+}++/**+ * What a room needs of the editor it keeps in step: the graph it edits, the events of local+ * edits, and the refreshes a peer's edit asks for. An editor in the app, or a graph a server builds+ * a revision from, with no events and nothing to redraw.+ */+export interface CollabEditor {+ /** The graph the editor shows now; opening another document replaces it. */+ readonly graph: SceneGraph+ /** Whether this peer only receives the room's changes and sends none of its own. */+ isReadOnly(): boolean+ onEditorEvent<K extends keyof CollabEditorEvents>(+ event: K,+ handler: CollabEditorEvents[K]+ ): () => void+ /** Redraws after a peer's edit changed the graph. */+ requestRender(): void+ /** Lays out again the layers bound to these variables, after a peer changed them. */+ refreshVariables(scope: BindingScope): void+ /** Applies the document settings a peer changed: libraries, color space, kind. */+ refreshDocumentSettings(): void+}diff --git a/src/app/collab/yjs-sync.ts b/packages/collab/src/graph-sync.tssimilarity index 83%rename from src/app/collab/yjs-sync.tsrename to packages/collab/src/graph-sync.tsindex caadedd7f..8ea2f6235 100644--- a/src/app/collab/yjs-sync.ts+++ b/packages/collab/src/graph-sync.ts@@ -4,11 +4,8 @@ import * as Y from 'yjs'import type { SceneGraph } from '@open-pencil/scene-graph'import { siblingOrderKeys } from '@open-pencil/scene-graph/order-keys'-import {- decodeNodeFromYjs,- DOCUMENT_NODE_FIELDS,- syncEncodedNodeToYMap-} from '@/app/collab/node-codec'+import type { CollabEditor } from './editor'+import { decodeNodeFromYjs, DOCUMENT_NODE_FIELDS, syncEncodedNodeToYMap } from './node-codec'import {claimRoot,markTreeFormat,@@ -18,7 +15,7 @@ import {writeParentEntry,writeRootEntries,type YNodes-} from '@/app/collab/shared-tree/fields'+} from './shared-tree/fields'import {applySharedTree,createLocalEdit,@@ -31,13 +28,12 @@ import {writeLocalPlacement,type LocalEdit,type SharedTree-} from '@/app/collab/shared-tree/sync'-import type { EditorStore } from '@/app/editor/active-store'+} from './shared-tree/sync'type YImages = Y.Map<Uint8Array>type GraphBindingOptions = {- store: EditorStore+ editor: CollabEditorgetYdoc: () => Y.Doc | nullgetYnodes: () => YNodes | nullgetSuppressGraphSync: () => boolean@@ -45,7 +41,7 @@ type GraphBindingOptions = {}type YjsObserverOptions = {- store: EditorStore+ editor: CollabEditorynodes: YNodesyimages: YImages/** Whether the room names an image by reference, which keeps it when its bytes leave. */@@ -56,13 +52,18 @@ type YjsObserverOptions = {}type YjsGraphSyncOptions = {- getStore: () => EditorStore+ getEditor: () => CollabEditorgetYdoc: () => Y.Doc | nullgetYnodes: () => YNodes | nullgetYimages: () => YImages | null/** Takes an image a layer uses to share some other way; false writes its bytes into the room. */shareImage?: (name: string, bytes: Uint8Array) => booleansetSuppressYjsEvents: (value: boolean) => void+ /**+ * Called after the room's layers reach the graph, which may have removed some, such as the page+ * the editor shows.+ */+ onApplied?: () => void}function logCollabSyncError(context: string, error: unknown) {@@ -74,7 +75,7 @@ function logCollabSyncError(context: string, error: unknown) {* transaction, so a move writes its parent entry and order key against the final layer order.*/export function bindCollabGraphEvents({- store,+ editor,getYdoc,getYnodes,getSuppressGraphSync,@@ -85,13 +86,7 @@ export function bindCollabGraphEvents({function record(update: (pending: LocalEdit) => void) {// A read-only document makes no edits of its own; what changes it is the room's.- if (- store.state.hostRestrictions.readOnly ||- getSuppressGraphSync() ||- !getYdoc() ||- !getYnodes()- )- return+ if (editor.isReadOnly() || getSuppressGraphSync() || !getYdoc() || !getYnodes()) returnif (isLocalEditEmpty(edit)) queueMicrotask(flush)update(edit)}@@ -103,7 +98,7 @@ export function bindCollabGraphEvents({}const unbinds = [- store.onEditorEvent('node:updated', (id, changes) =>+ editor.onEditorEvent('node:updated', (id, changes) =>record((pending) => {// A direct parentId write, as a checkpoint restore makes, syncs as a move when it// differs from the shared tree; a childIds write re-keys the children out of order.@@ -111,26 +106,26 @@ export function bindCollabGraphEvents({if ('childIds' in changes) pending.reordered.add(id)})),- store.onEditorEvent('node:created', (node) =>+ editor.onEditorEvent('node:created', (node) =>record((pending) => {pending.changed.add(node.id)pending.placed.add(node.id)})),- store.onEditorEvent('node:reparented', (nodeId, oldParentId) =>+ editor.onEditorEvent('node:reparented', (nodeId, oldParentId) =>record((pending) => {pending.changed.add(nodeId)pending.placed.add(nodeId)if (oldParentId) pending.previousParents.add(oldParentId)})),- store.onEditorEvent('node:reordered', (nodeId, _parentId, _index, previousParentId) =>+ editor.onEditorEvent('node:reordered', (nodeId, _parentId, _index, previousParentId) =>record((pending) => {pending.placed.add(nodeId)if (previousParentId) pending.previousParents.add(previousParentId)})),- store.onEditorEvent('node:deleted', (id) => record((pending) => pending.deleted.add(id)))+ editor.onEditorEvent('node:deleted', (id) => record((pending) => pending.deleted.add(id)))]return () => {// An edit made just before leaving still reaches the room.@@ -141,7 +136,7 @@ export function bindCollabGraphEvents({}export function registerYjsObservers({- store,+ editor,ynodes,yimages,hasImageRef,@@ -154,7 +149,7 @@ export function registerYjsObservers({setSuppressGraphSync(true)try {applyYjsToGraph(events)- store.requestRender()+ editor.requestRender()} catch (error) {logCollabSyncError('Failed to apply remote graph changes', error)} finally {@@ -168,12 +163,12 @@ export function registerYjsObservers({for (const [key, change] of event.changes.keys) {if (change.action === 'add' || change.action === 'update') {const data = yimages.get(key)- if (data) store.graph.images.set(key, new Uint8Array(data))+ if (data) editor.graph.images.set(key, new Uint8Array(data))} else if (!hasImageRef?.(key)) {- store.graph.images.delete(key)+ editor.graph.images.delete(key)}}- store.requestRender()+ editor.requestRender()} catch (error) {logCollabSyncError('Failed to apply remote image changes', error)}@@ -188,21 +183,21 @@ export function registerYjsObservers({}export function createYjsGraphSync({- getStore,+ getEditor,getYdoc,getYnodes,getYimages,shareImage,- setSuppressYjsEvents+ setSuppressYjsEvents,+ onApplied}: YjsGraphSyncOptions) {- let pendingPageSwitch: { store: EditorStore; pageId: string } | undefinedlet shared: SharedTree | null = null/** Edits made before this peer knew the room's root, which the room did not take. */let heldBack = createLocalEdit()function sharedTreeOf(ydoc: Y.Doc): SharedTree {if (shared?.ydoc !== ydoc) {- shared = createSharedTree(ydoc, () => getStore().graph, getYnodes)+ shared = createSharedTree(ydoc, () => getEditor().graph, getYnodes)}return shared}@@ -228,7 +223,7 @@ export function createYjsGraphSync({/** Writes one local edit: changed layers' fields, deletions, and where layers now sit. */function syncLocalEdit(edit: LocalEdit) {- const graph = getStore().graph+ const graph = getEditor().graphconst ydoc = getYdoc()const ynodes = getYnodes()if (!ydoc || !ynodes) return@@ -270,7 +265,7 @@ export function createYjsGraphSync({* order, and its page, with its root as the room's.*/function syncAllNodesToYjs() {- const graph = getStore().graph+ const graph = getEditor().graphconst ydoc = getYdoc()const ynodes = getYnodes()if (!ydoc || !ynodes) return@@ -306,7 +301,7 @@ export function createYjsGraphSync({}function applyYjsToGraph(events: Y.YEvent<Y.Map<unknown>>[]) {- const store = getStore()+ const editor = getEditor()const ydoc = getYdoc()const ynodes = getYnodes()if (!ydoc || !ynodes) return@@ -329,13 +324,13 @@ export function createYjsGraphSync({const roomRoot = readRoot(ydoc.getMap('meta'))for (const nodeId of changed) {const ynode = ynodes.get(nodeId)- if (ynode) applyYnodeToGraph(store.graph, nodeId, ynode, roomRoot)+ if (ynode) applyYnodeToGraph(editor.graph, nodeId, ynode, roomRoot)}const gone = [...deleted].filter((nodeId) => !ynodes.has(nodeId))// Moves go first, so a layer moved out of a deleted parent survives the deletion.- applySharedTree(sharedTreeOf(ydoc), store.graph, ynodes, ydoc.getMap('meta'), changed, gone)- for (const nodeId of gone) store.graph.deleteNode(nodeId)- ensureCurrentPageExists(store)+ applySharedTree(sharedTreeOf(ydoc), editor.graph, ynodes, ydoc.getMap('meta'), changed, gone)+ for (const nodeId of gone) editor.graph.deleteNode(nodeId)+ onApplied?.()}/** Applies a layer's own fields; `applySharedTree` places it in the tree afterwards. */@@ -346,7 +341,7 @@ export function createYjsGraphSync({roomRoot: string | undefined) {const decoded = decodeNodeFromYjs(ynode)- // The document node's plugin data arrives entry by entry (`src/app/collab/document/sync.ts`).+ // The document node's plugin data arrives entry by entry (`document/sync.ts`).const props: ReturnType<typeof decodeNodeFromYjs> =nodeId === roomRoot || nodeId === graph.rootId ? omit(decoded, DOCUMENT_NODE_FIELDS) : decodedconst node = graph.getNode(nodeId)@@ -363,25 +358,6 @@ export function createYjsGraphSync({if (type) graph.createNodeWithId(nodeId, type, null, { ...props, childIds: [] })}- function ensureCurrentPageExists(store: EditorStore) {- const pages = store.graph.getPages()- if (pages.some((page) => page.id === store.state.currentPageId)) return- if (pages.length === 0) return- const pageId = pages[0].id- if (pendingPageSwitch?.store === store && pendingPageSwitch.pageId === pageId) return- const pending = { store, pageId }- pendingPageSwitch = pending- void store- .switchPage(pageId)- .catch((error: unknown) => {- if (error instanceof Error && error.name === 'AbortError') return- logCollabSyncError('Failed to switch to a synced page', error)- })- .finally(() => {- if (pendingPageSwitch === pending) pendingPageSwitch = undefined- })- }-/*** Writes the edits made before the room's root was known, once this peer's document follows* that root, as a stored document's tab does: what was drawn while the room loaded joins it.@@ -403,7 +379,7 @@ export function createYjsGraphSync({* already has would otherwise sit beside the room's own.*/function dropLayersOutsideRoom() {- const graph = getStore().graph+ const graph = getEditor().graphconst ynodes = getYnodes()if (!ynodes) returnconst outside: string[] = []@@ -416,7 +392,7 @@ export function createYjsGraphSync({visit(graph.rootId)for (const id of outside) graph.deleteNode(id)// The page the tab was on may have been the file's own; it moves to one of the room's.- if (outside.length > 0) ensureCurrentPageExists(getStore())+ if (outside.length > 0) onApplied?.()}return {diff --git a/packages/collab/src/index.ts b/packages/collab/src/index.tsnew file mode 100644index 000000000..e3b783f60--- /dev/null+++ b/packages/collab/src/index.ts@@ -0,0 +1,16 @@+export type { CollabEditor, CollabEditorEvents } from './editor'+export { bindDocumentSync, roomDocumentData, type YDocumentData } from './document/sync'+export { bindCollabGraphEvents, createYjsGraphSync, registerYjsObservers } from './graph-sync'+export { decodeNodeFromYjs, syncEncodedNodeToYMap } from './node-codec'+export type { YRecords } from './records'+export { trackRoomSaves, type EditCounts, type RoomSaves } from './saves'+export {+ claimRoot,+ readPage,+ readRoomName,+ readRoot,+ TREE_FORMAT,+ writeRoomName,+ type YNodes+} from './shared-tree/fields'+export { bindVariableSync } from './variables'diff --git a/src/app/collab/node-codec.ts b/packages/collab/src/node-codec.tssimilarity index 98%rename from src/app/collab/node-codec.tsrename to packages/collab/src/node-codec.tsindex 441769572..c804f7673 100644--- a/src/app/collab/node-codec.ts+++ b/packages/collab/src/node-codec.ts@@ -15,9 +15,8 @@ import {type Vector} from '@open-pencil/scene-graph/primitives'-import { ORDER_KEY_FIELD, PAGE_FIELD, PARENTS_FIELD } from '@/app/collab/shared-tree/fields'-import { writeRecord, type YFields } from './records'+import { ORDER_KEY_FIELD, PAGE_FIELD, PARENTS_FIELD } from './shared-tree/fields'const DERIVED_NODE_FIELDS = new Set<keyof SceneNode>(['textPicture'])/**diff --git a/src/app/collab/records.ts b/packages/collab/src/records.tssimilarity index 100%rename from src/app/collab/records.tsrename to packages/collab/src/records.tsdiff --git a/src/app/collab/room/saves.ts b/packages/collab/src/saves.tssimilarity index 97%rename from src/app/collab/room/saves.tsrename to packages/collab/src/saves.tsindex 4135aeae0..11717d404 100644--- a/src/app/collab/room/saves.ts+++ b/packages/collab/src/saves.ts@@ -1,6 +1,6 @@import type * as Y from 'yjs'-import { readCounter } from '@/app/collab/shared-tree/fields'+import { readCounter } from './shared-tree/fields'/** How many edits each peer's client has made to a room's document. */export type EditCounts = ReadonlyMap<string, number>diff --git a/src/app/collab/shared-tree/fields.ts b/packages/collab/src/shared-tree/fields.tssimilarity index 100%rename from src/app/collab/shared-tree/fields.tsrename to packages/collab/src/shared-tree/fields.tsdiff --git a/src/app/collab/shared-tree/sync.ts b/packages/collab/src/shared-tree/sync.tssimilarity index 99%rename from src/app/collab/shared-tree/sync.tsrename to packages/collab/src/shared-tree/sync.tsindex 4f6b9e001..0a2289cc4 100644--- a/src/app/collab/shared-tree/sync.ts+++ b/packages/collab/src/shared-tree/sync.ts@@ -4,8 +4,7 @@ import type * as Y from 'yjs'import type { SceneGraph } from '@open-pencil/scene-graph'import { siblingOrderKeys } from '@open-pencil/scene-graph/order-keys'-import { LayerTree, type TreeMove } from '@/app/collab/tree/layer-tree'-+import { LayerTree, type TreeMove } from '../tree/layer-tree'import {createMoveClock,markTreeFormat,diff --git a/src/app/collab/tree/entries.ts b/packages/collab/src/tree/entries.tssimilarity index 100%rename from src/app/collab/tree/entries.tsrename to packages/collab/src/tree/entries.tsdiff --git a/src/app/collab/tree/layer-tree.ts b/packages/collab/src/tree/layer-tree.tssimilarity index 100%rename from src/app/collab/tree/layer-tree.tsrename to packages/collab/src/tree/layer-tree.tsdiff --git a/src/app/collab/variables.ts b/packages/collab/src/variables.tssimilarity index 94%rename from src/app/collab/variables.tsrename to packages/collab/src/variables.tsindex 784e82fd7..355d02dcc 100644--- a/src/app/collab/variables.ts+++ b/packages/collab/src/variables.ts@@ -5,15 +5,14 @@ import type * as Y from 'yjs'import type { Variable, VariableCollection } from '@open-pencil/scene-graph'import { variableCollectionSchema, variableSchema } from '@open-pencil/scene-graph/variables'-import type { EditorStore } from '@/app/editor/active-store'-+import type { CollabEditor } from './editor'import { changedIds, writeChanges, type YRecords } from './records'/** A variable's values are a map of their own by mode. */const BY_MODE = new Set(['valuesByMode'])type VariableSyncOptions = {- store: EditorStore+ editor: CollabEditorydoc: Y.Docyvariables: YRecordsycollections: YRecords@@ -46,8 +45,8 @@ function applyRecord<T extends object>(target: Map<string, T>, id: string, value* peers' edits are applied without one, and the layers bound to them are laid out again.* Which mode a collection shows is each viewer's own, and stays out of the room.*/-export function bindVariableSync({ store, ydoc, yvariables, ycollections }: VariableSyncOptions) {- const graph = () => store.graph+export function bindVariableSync({ editor, ydoc, yvariables, ycollections }: VariableSyncOptions) {+ const graph = () => editor.graph// What the room holds as this peer last wrote or read it, so only what changed since is sent.let sentVariables = structuredClone(graph().variables)let sentCollections = structuredClone(graph().variableCollections)@@ -133,7 +132,7 @@ export function bindVariableSync({ store, ydoc, yvariables, ycollections }: Varifor (const id of collections) {for (const variableId of variableCollections.get(id)?.variableIds ?? []) scope.add(variableId)}- store.refreshVariables({ variables: scope })+ editor.refreshVariables({ variables: scope })}// This peer's own writes are already in its graph.@@ -151,7 +150,7 @@ export function bindVariableSync({ store, ydoc, yvariables, ycollections }: Variyvariables.observeDeep(onVariables)ycollections.observeDeep(onCollections)- const stopHistory = store.onEditorEvent('history:changed', send)+ const stopHistory = editor.onEditorEvent('history:changed', send)return {share,diff --git a/packages/collab/tests/graph-sync.test.ts b/packages/collab/tests/graph-sync.test.tsnew file mode 100644index 000000000..3a9921840--- /dev/null+++ b/packages/collab/tests/graph-sync.test.ts@@ -0,0 +1,61 @@+import { describe, expect, test } from 'bun:test'++import { createYjsGraphSync, registerYjsObservers, type CollabEditor } from '#collab/index'+import * as Y from 'yjs'++import { SceneGraph } from '@open-pencil/scene-graph'++/** An editor with nothing to redraw and no edits of its own, as a server reading a room has. */+function headlessEditor(graph: SceneGraph): CollabEditor {+ return {+ graph,+ isReadOnly: () => true,+ onEditorEvent: () => () => undefined,+ requestRender: () => undefined,+ refreshVariables: () => undefined,+ refreshDocumentSettings: () => undefined+ }+}++function graphSync(ydoc: Y.Doc, editor: CollabEditor) {+ return createYjsGraphSync({+ getEditor: () => editor,+ getYdoc: () => ydoc,+ getYnodes: () => ydoc.getMap('nodes'),+ getYimages: () => ydoc.getMap('images'),+ setSuppressYjsEvents: () => undefined+ })+}++describe('room document to graph', () => {+ test('reads a room saved as a Yjs update into a graph without an editor', () => {+ const source = new SceneGraph()+ const page = source.addPage('Cover')+ const frame = source.createNode('FRAME', page.id, { name: 'Hero', width: 320, height: 200 })+ source.createNode('RECTANGLE', frame.id, { name: 'Badge', x: 12, y: 8 })+ const room = new Y.Doc()+ graphSync(room, headlessEditor(source)).syncAllNodesToYjs()++ // What a relay stores, read back by something that never saw the editor.+ const saved = Y.encodeStateAsUpdate(room)+ const ydoc = new Y.Doc()+ const graph = new SceneGraph()+ const editor = headlessEditor(graph)+ const sync = graphSync(ydoc, editor)+ registerYjsObservers({+ editor,+ ynodes: ydoc.getMap<Y.Map<unknown>>('nodes'),+ yimages: ydoc.getMap('images'),+ getSuppressYjsEvents: () => false,+ setSuppressGraphSync: () => undefined,+ applyYjsToGraph: sync.applyYjsToGraph+ })+ Y.applyUpdate(ydoc, saved)++ const cover = graph.getPages().find((candidate) => candidate.name === 'Cover')+ expect(cover?.id).toBe(page.id)+ const hero = graph.getNode(frame.id)+ expect(hero).toMatchObject({ name: 'Hero', width: 320, height: 200, parentId: page.id })+ expect(graph.getChildren(frame.id).map((child) => child.name)).toEqual(['Badge'])+ })+})diff --git a/tests/app/collab/records.test.ts b/packages/collab/tests/records.test.tssimilarity index 97%rename from tests/app/collab/records.test.tsrename to packages/collab/tests/records.test.tsindex a47245358..bc0d90b20 100644--- a/tests/app/collab/records.test.ts+++ b/packages/collab/tests/records.test.ts@@ -1,9 +1,8 @@import { describe, expect, test } from 'bun:test'+import { writeRecord } from '#collab/records'import * as Y from 'yjs'-import { writeRecord } from '@/app/collab/records'-/** Two peers of one room, each with the record's map, and a way to exchange what they wrote. */function peers() {const first = new Y.Doc()diff --git a/tests/app/collab/room/saves.test.ts b/packages/collab/tests/saves.test.tssimilarity index 96%rename from tests/app/collab/room/saves.test.tsrename to packages/collab/tests/saves.test.tsindex bc56af30d..9b1b5af68 100644--- a/tests/app/collab/room/saves.test.ts+++ b/packages/collab/tests/saves.test.ts@@ -1,9 +1,8 @@import { describe, expect, test } from 'bun:test'+import { trackRoomSaves } from '#collab/saves'import * as Y from 'yjs'-import { trackRoomSaves } from '@/app/collab/room/saves'-function peer() {const ydoc = new Y.Doc()const nodes = ydoc.getMap<unknown>('nodes')diff --git a/tests/app/collab/shared-tree/fields.test.ts b/packages/collab/tests/shared-tree/fields.test.tssimilarity index 90%rename from tests/app/collab/shared-tree/fields.test.tsrename to packages/collab/tests/shared-tree/fields.test.tsindex d4a88829b..b4afa06a9 100644--- a/tests/app/collab/shared-tree/fields.test.ts+++ b/packages/collab/tests/shared-tree/fields.test.ts@@ -1,9 +1,8 @@import { describe, expect, test } from 'bun:test'+import { claimRoot, readRoot } from '#collab/shared-tree/fields'import * as Y from 'yjs'-import { claimRoot, readRoot } from '@/app/collab/shared-tree/fields'-function meta(): Y.Map<unknown> {return new Y.Doc().getMap('meta')}diff --git a/tests/app/collab/tree/layer-tree.test.ts b/packages/collab/tests/tree/layer-tree.test.tssimilarity index 98%rename from tests/app/collab/tree/layer-tree.test.tsrename to packages/collab/tests/tree/layer-tree.test.tsindex 6798fc0a1..97471286c 100644--- a/tests/app/collab/tree/layer-tree.test.ts+++ b/packages/collab/tests/tree/layer-tree.test.ts@@ -1,10 +1,9 @@import { describe, expect, test } from 'bun:test'+import type { ParentEntries } from '#collab/tree/entries'+import { LayerTree } from '#collab/tree/layer-tree'import { create as createPRNG, oneOf, real53 } from 'lib0/prng'-import type { ParentEntries } from '@/app/collab/tree/entries'-import { LayerTree } from '@/app/collab/tree/layer-tree'-const ROOT = 'root'const PAGE = 'page'diff --git a/packages/collab/tsconfig.json b/packages/collab/tsconfig.jsonnew file mode 100644index 000000000..b47e3665b--- /dev/null+++ b/packages/collab/tsconfig.json@@ -0,0 +1,19 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "lib": ["ES2023"],+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "skipLibCheck": true,+ "noEmit": true,+ "types": ["bun"],+ "paths": {+ "#collab/*": ["./src/*"],+ "#collab-tests/*": ["./tests/*"]+ }+ },+ "include": ["src/**/*.ts", "tests/**/*.ts"]+}diff --git a/src/AGENTS.md b/src/AGENTS.mdindex 31fbfe6d1..03e56b697 100644--- a/src/AGENTS.md+++ b/src/AGENTS.md@@ -37,12 +37,9 @@ Root Tauri/Vite app. Services and state live under `src/app/**`, views under `sr- Which portal pages a visitor may open, by sign-in and account standing, is decided in `portalDestination` alone, and whether an editor page opens the editor or the welcome page in `siteDestination` (`tests/app/cloud-portal/navigation.test.ts`, `site.test.ts`).- On a Cloud server's own build (`__OPENPENCIL_CLOUD_SITE__`), `src/main.ts` runs the welcome check (`enterCloudSite` in `src/app/cloud-portal/site.ts`) after the support check and before `boot()`, so signed-out visitors never load the editor (`tests/app/cloud-portal/site.test.ts`).- A room is a document: every room tab owns its session (`src/app/collab/rooms.ts`, `session.ts`), joining always opens a new tab, and only Share binds an existing document; the collaboration UI reads the active tab's room through `useCollab()` and publishes cursors through the canvas's own tab (`tests/app/collab/session.test.ts`, `tests/e2e/collab/rooms.spec.ts`).-- A shared document records each layer's parent history, order key and page, never `parentId` or `childIds`, and only Share or a room's conversion sets its root in `meta`; local edits are written by `writeLocalPlacement` and remote changes applied by `applySharedTree` in `src/app/collab/shared-tree/sync.ts`, which resolve the tree with `LayerTree` from `src/app/collab/tree/` (`tests/app/collab/random-edits.test.ts`).- A room's voice call lives in its session (`src/app/collab/voice/room.ts`): who is in it and muted travels in awareness, the microphone goes only to peers in the call through the transport's `media`, and speaking comes from WebRTC's reported audio levels. One window holds one call, owned by `useVoiceCall()` in `src/app/collab/voice/call.ts`, which opens the microphone with VueUse and ends the call when its room goes (`tests/app/collab/voice/room.test.ts`).- Every agent at work, the built-in chat's and each MCP session's (`src/app/automation/agents.ts`), is registered with `addAgent` in `src/app/presence/registry.ts`, and presence cursors reach the editor only through `showCursors` in `src/app/presence/cursor-motion.ts`, which glides them; never assign `presenceCursors` directly (`tests/app/presence/registry.test.ts`).- Agent presence in awareness is metadata only. The one content an agent shares is its streamed `render` JSX, published through `publishAgentPreview` (`src/app/presence/preview-stream.ts`) and sent on the room's `agent-preview` channel by `shareAgentPreviews` (`src/app/collab/agent-preview.ts`), which validates and bounds what peers send and draws it with the chat run's canvas preview; never put prompts or other tool arguments in either (`tests/app/collab/agent-preview.test.ts`).-- What a document holds outside its layers, its document node's plugin data, comment threads, libraries and color space, travels in the room's own maps through `bindDocumentSync` (`src/app/collab/document/sync.ts`), entry by entry and thread by thread, never on the root layer, so people changing it at once all keep their change (`tests/app/collab/document/sync.test.ts`).-- Changing how a shared document records data bumps `TREE_FORMAT` and `COLLAB_APP_ID` together, so mismatched builds never meet; rooms saved by an earlier format are not converted (`src/app/collab/shared-tree/fields.ts`).## Browser baselinediff --git a/src/app/collab/editor.ts b/src/app/collab/editor.tsnew file mode 100644index 000000000..51271a1ed--- /dev/null+++ b/src/app/collab/editor.ts@@ -0,0 +1,41 @@+import type { CollabEditor } from '@open-pencil/collab'++import type { EditorStore } from '@/app/editor/active-store'++/** A tab's editor as its room sees it. */+export function collabEditor(store: EditorStore): CollabEditor {+ return {+ get graph() {+ return store.graph+ },+ isReadOnly: () => store.state.hostRestrictions.readOnly,+ onEditorEvent: store.onEditorEvent,+ requestRender: () => store.requestRender(),+ refreshVariables: (scope) => store.refreshVariables(scope),+ refreshDocumentSettings: () => store.refreshDocumentSettings()+ }+}++/**+ * Moves the tab to one of the room's pages when the page it shows is gone, as after a peer deleted+ * it or the tab dropped its file's own pages for the room's.+ */+export function followRoomPages(store: EditorStore): () => void {+ let pending: string | undefined+ return () => {+ const pages = store.graph.getPages()+ if (pages.length === 0 || pages.some((page) => page.id === store.state.currentPageId)) return+ const pageId = pages[0].id+ if (pending === pageId) return+ pending = pageId+ void store+ .switchPage(pageId)+ .catch((error: unknown) => {+ if (error instanceof Error && error.name === 'AbortError') return+ console.error('[Collab] Failed to switch to a synced page:', error)+ })+ .finally(() => {+ if (pending === pageId) pending = undefined+ })+ }+}diff --git a/src/app/collab/session.ts b/src/app/collab/session.tsindex 60ef653fc..8fe41e4e1 100644--- a/src/app/collab/session.ts+++ b/src/app/collab/session.ts@@ -4,35 +4,36 @@ import { IndexeddbPersistence } from 'y-indexeddb'import * as awarenessProtocol from 'y-protocols/awareness'import * as Y from 'yjs'+import {+ bindCollabGraphEvents,+ bindDocumentSync,+ bindVariableSync,+ createYjsGraphSync,+ readRoomName,+ readRoot,+ registerYjsObservers,+ roomDocumentData,+ trackRoomSaves,+ TREE_FORMAT,+ writeRoomName,+ type RoomSaves,+ type YNodes,+ type YRecords+} from '@open-pencil/collab'import type { Color } from '@open-pencil/scene-graph/primitives'import { shareAgentPreviews } from '@/app/collab/agent-preview'import { buildRemotePeers } from '@/app/collab/awareness'-import { bindDocumentSync, roomDocumentData } from '@/app/collab/document/sync'+import { collabEditor, followRoomPages } from '@/app/collab/editor'import { useCollabIdentity } from '@/app/collab/identity'import { bindRoomImages, type RoomImageStore } from '@/app/collab/images'import { publishLocalAgents } from '@/app/collab/local-awareness'-import type { YRecords } from '@/app/collab/records'import { connectCollabRoom } from '@/app/collab/room/connection'-import { trackRoomSaves, type RoomSaves } from '@/app/collab/room/saves'import { deriveRoomStatus, type RoomStatus } from '@/app/collab/room/status'-import {- readRoomName,- readRoot,- TREE_FORMAT,- writeRoomName,- type YNodes-} from '@/app/collab/shared-tree/fields'import type { JoinCollabRoom } from '@/app/collab/transport'import type { CollabAction } from '@/app/collab/transport/types'import type { RemotePeer } from '@/app/collab/types'-import { bindVariableSync } from '@/app/collab/variables'import { attachRoomVoice, type RoomVoice } from '@/app/collab/voice/room'-import {- bindCollabGraphEvents,- createYjsGraphSync,- registerYjsObservers-} from '@/app/collab/yjs-sync'import type { EditorStore } from '@/app/editor/active-store'import { setPeers } from '@/app/presence/registry'import { ROOM_STATUS_TICK_MS, ROOM_UNREACHABLE_MS } from '@/constants'@@ -160,7 +161,8 @@ export function openRoomSession({documentData.libraries,documentData.settings])- const documentSync = bindDocumentSync({ store, ydoc, data: documentData, meta })+ const editor = collabEditor(store)+ const documentSync = bindDocumentSync({ editor, ydoc, data: documentData, meta })const adopt = (apply: () => void) => (holdsDocument ? store.adoptChanges(apply) : apply())const peers = shallowRef<RemotePeer[]>([])@@ -193,14 +195,15 @@ export function openRoomSession({)const sync = createYjsGraphSync({- getStore: () => store,+ getEditor: () => editor,getYdoc: () => (disposed ? null : ydoc),getYnodes: () => (disposed ? null : ynodes),getYimages: () => (disposed ? null : yimages),shareImage: roomImages ? (name, bytes) => roomImages.share(name, bytes) : undefined,setSuppressYjsEvents: (value) => {suppressYjsEvents = value- }+ },+ onApplied: followRoomPages(store)})function refreshDocument() {@@ -240,7 +243,7 @@ export function openRoomSession({}const unregisterYjsObservers = registerYjsObservers({- store,+ editor,ynodes,yimages,hasImageRef: roomImages ? (name) => roomImages.hasRef(name) : undefined,@@ -298,9 +301,9 @@ export function openRoomSession({const stopAgentSync = publishLocalAgents(store, () => awareness, identity.color)const stopAgentPreviews = shareAgentPreviews(store, connection)const voice = attachRoomVoice({ awareness, peers, connection })- const variableSync = bindVariableSync({ store, ydoc, yvariables, ycollections })+ const variableSync = bindVariableSync({ editor, ydoc, yvariables, ycollections })const unbindGraphEvents = bindCollabGraphEvents({- store,+ editor,getYdoc: () => (disposed ? null : ydoc),getYnodes: () => (disposed ? null : ynodes),getSuppressGraphSync: () => suppressGraphSync,diff --git a/tests/app/collab/graph-binding.test.ts b/tests/app/collab/graph-binding.test.tsindex 10d3c0235..709ee0745 100644--- a/tests/app/collab/graph-binding.test.ts+++ b/tests/app/collab/graph-binding.test.ts@@ -2,7 +2,9 @@ import { describe, expect, test } from 'bun:test'import type * as Y from 'yjs'-import { bindCollabGraphEvents } from '@/app/collab/yjs-sync'+import { bindCollabGraphEvents } from '@open-pencil/collab'++import { collabEditor } from '@/app/collab/editor'import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'import { settleGraphSync, withSyncedStores } from '#tests/helpers/collab/synced-stores'@@ -14,7 +16,7 @@ describe('collab graph binding', () => {hostSync.syncAllNodesToYjs()await settleGraphSync()const unbind = bindCollabGraphEvents({- store: hostStore,+ editor: collabEditor(hostStore),getYdoc: () => hostDoc,getYnodes: () => hostDoc.getMap<Y.Map<unknown>>('nodes'),getSuppressGraphSync: () => stores.hostSuppressGraphSync,diff --git a/tests/app/collab/session.test.ts b/tests/app/collab/session.test.tsindex 9c532416d..798b4c423 100644--- a/tests/app/collab/session.test.ts+++ b/tests/app/collab/session.test.ts@@ -2,10 +2,10 @@ import { describe, expect, test } from 'bun:test'import type * as Y from 'yjs'+import { claimRoot } from '@open-pencil/collab'import { SceneGraph } from '@open-pencil/scene-graph'import { openRoomSession, type RoomSession, type RoomSessionOptions } from '@/app/collab/session'-import { claimRoot } from '@/app/collab/shared-tree/fields'import { createEditorStore, type EditorStore } from '@/app/editor/session'import { presenceOf } from '@/app/presence/registry'diff --git a/tests/app/collab/shared-tree/sync.test.ts b/tests/app/collab/shared-tree/sync.test.tsindex 3dce71a9b..9533f8817 100644--- a/tests/app/collab/shared-tree/sync.test.ts+++ b/tests/app/collab/shared-tree/sync.test.ts@@ -2,13 +2,12 @@ import { describe, expect, test } from 'bun:test'import type * as Y from 'yjs'+import { readPage } from '@open-pencil/collab'import {captureGraphCheckpoint,captureTouchedCheckpoint} from '@open-pencil/scene-graph/checkpoint'-import { readPage } from '@/app/collab/shared-tree/fields'-import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'import {expectSameLayerTree,diff --git a/tests/engine/collab/yjs-sync.test.ts b/tests/engine/collab/yjs-sync.test.tsindex e04384ffe..bd2cc5f95 100644--- a/tests/engine/collab/yjs-sync.test.ts+++ b/tests/engine/collab/yjs-sync.test.ts@@ -4,13 +4,12 @@ import { create as createPRNG } from 'lib0/prng'import * as Y from 'yjs'import { TestConnector, type TestYInstance } from 'yjs/testHelper'+import { decodeNodeFromYjs, syncEncodedNodeToYMap } from '@open-pencil/collab'import type { Fill, GeometryPath, SceneNode, VectorNetwork } from '@open-pencil/scene-graph'import { SceneGraph } from '@open-pencil/scene-graph'import { nodeVisualBounds } from '@open-pencil/scene-graph/geometry'import { createDefaultSourceMetadata } from '@open-pencil/scene-graph/node-defaults'-import { decodeNodeFromYjs, syncEncodedNodeToYMap } from '@/app/collab/node-codec'-import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'import { withSyncedStores } from '#tests/helpers/collab/synced-stores'diff --git a/tests/helpers/collab/synced-stores.ts b/tests/helpers/collab/synced-stores.tsindex ad6028996..731ecb4bc 100644--- a/tests/helpers/collab/synced-stores.ts+++ b/tests/helpers/collab/synced-stores.ts@@ -2,13 +2,14 @@ import { expect } from 'bun:test'import * as Y from 'yjs'-import { SceneGraph } from '@open-pencil/scene-graph'-import {bindCollabGraphEvents,createYjsGraphSync,registerYjsObservers-} from '@/app/collab/yjs-sync'+} from '@open-pencil/collab'+import { SceneGraph } from '@open-pencil/scene-graph'++import { collabEditor, followRoomPages } from '@/app/collab/editor'import { createEditorStore } from '@/app/editor/session'import { getNodeOrThrow } from '#tests/helpers/assert'@@ -34,32 +35,36 @@ export function createSyncedStores(options: SyncedStoreOptions = {}) {const peerNodes = peerDoc.getMap<Y.Map<unknown>>('nodes')const hostImages = hostDoc.getMap<Uint8Array>('images')const peerImages = peerDoc.getMap<Uint8Array>('images')+ const hostEditor = collabEditor(hostStore)+ const peerEditor = collabEditor(peerStore)let hostSuppressYjsEvents = falselet peerSuppressYjsEvents = falselet hostSuppressGraphSync = falselet peerSuppressGraphSync = falseconst hostSync = createYjsGraphSync({- getStore: () => hostStore,+ getEditor: () => hostEditor,getYdoc: () => hostDoc,getYnodes: () => hostNodes,getYimages: () => hostImages,setSuppressYjsEvents: (value) => {hostSuppressYjsEvents = value- }+ },+ onApplied: followRoomPages(hostStore)})const peerSync = createYjsGraphSync({- getStore: () => peerStore,+ getEditor: () => peerEditor,getYdoc: () => peerDoc,getYnodes: () => peerNodes,getYimages: () => peerImages,setSuppressYjsEvents: (value) => {peerSuppressYjsEvents = value- }+ },+ onApplied: followRoomPages(peerStore)})registerYjsObservers({- store: hostStore,+ editor: hostEditor,ynodes: hostNodes,yimages: hostImages,getSuppressYjsEvents: () => hostSuppressYjsEvents,@@ -69,7 +74,7 @@ export function createSyncedStores(options: SyncedStoreOptions = {}) {applyYjsToGraph: hostSync.applyYjsToGraph})registerYjsObservers({- store: peerStore,+ editor: peerEditor,ynodes: peerNodes,yimages: peerImages,getSuppressYjsEvents: () => peerSuppressYjsEvents,@@ -82,14 +87,14 @@ export function createSyncedStores(options: SyncedStoreOptions = {}) {const unbindGraphEvents = options.bindGraphEvents? [bindCollabGraphEvents({- store: hostStore,+ editor: hostEditor,getYdoc: () => hostDoc,getYnodes: () => hostNodes,getSuppressGraphSync: () => hostSuppressGraphSync,syncLocalEdit: hostSync.syncLocalEdit}),bindCollabGraphEvents({- store: peerStore,+ editor: peerEditor,getYdoc: () => peerDoc,getYnodes: () => peerNodes,getSuppressGraphSync: () => peerSuppressGraphSync,diff --git a/tools/checks/lint/tests/editor-profile-inputs.test.ts b/tools/checks/lint/tests/editor-profile-inputs.test.tsindex 5bce59dc4..dccb809bd 100644--- a/tools/checks/lint/tests/editor-profile-inputs.test.ts+++ b/tools/checks/lint/tests/editor-profile-inputs.test.ts@@ -73,13 +73,13 @@ describe('no-editor-profile-inputs', () => {test.each(['packages/core/src/editor/read-only/index.ts','packages/core/src/editor/views/profile.ts',- 'src/app/collab/yjs-sync.ts'+ 'src/app/collab/editor.ts'])('accepts reading the restrictions in %s, which owns or sets them', async (path) => {expect(ruleDiagnostics(await lint(restriction, rules, path), rule)).toHaveLength(0)})test('the host still reads the view through the profile', async () => {- const path = 'src/app/collab/yjs-sync.ts'+ const path = 'src/app/collab/editor.ts'expect(ruleDiagnostics(await lint(check, rules, path), rule)).toHaveLength(1)})diff --git a/tools/dev/unit-tests/src/shards.ts b/tools/dev/unit-tests/src/shards.tsindex 3949fe67d..96258211f 100644--- a/tools/dev/unit-tests/src/shards.ts+++ b/tools/dev/unit-tests/src/shards.ts@@ -57,6 +57,7 @@ export const UNIT_TEST_GROUPS = {render: ['tests/engine/render'],'scene-graph': ['packages/scene-graph/tests',+ 'packages/collab/tests','tests/engine/geometry','tests/engine/hit-test','tests/engine/random',