AI-native design editor. Open-source Figma alternative.
feat(scene-graph)!: let a SceneGraph take its ID generator (#887)
Danila Poyarkov510cdbc36f8d
diff --git a/AGENTS.md b/AGENTS.mdindex 371dfa2d4..5af9fdaf0 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -13,9 +13,9 @@ This file holds the repository map and the rules that apply everywhere. Rules fo| `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` || `packages/core` | Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, document I/O; depends on scene-graph and the format packages (pen, kiwi, fig, dom-css, design-jsx); no browser DOM | `packages/core/AGENTS.md` |-| `packages/dom-css` | DOM/CSS/HTML/JSX/Tailwind projection and browser/headless adapters; depends only on scene-graph and emit, and takes engine services such as web-font resolution as injected options | `packages/dom-css/AGENTS.md` |-| `packages/emit` | Source emission for exporters: ESTree and JSX builders, template filling, and esrap printing, with the literal rules that keep exported strings from being reinterpreted | — |-| `packages/design-jsx` | OpenPencil design JSX: elements, paint/effect helpers, variables, schema and authoring reference, JSX export, and a renderer that takes icons, SVG, and layout as injected services | `packages/design-jsx/AGENTS.md` |+| `packages/dom-css` | DOM/CSS/HTML/JSX/Tailwind projection and browser/headless adapters; depends only on scene-graph and emit, and takes engine services such as web-font resolution as injected options | `packages/dom-css/AGENTS.md` |+| `packages/emit` | Source emission for exporters: ESTree and JSX builders, template filling, and esrap printing, with the literal rules that keep exported strings from being reinterpreted | — |+| `packages/design-jsx` | OpenPencil design JSX: elements, paint/effect helpers, variables, schema and authoring reference, JSX export, and a renderer that takes icons, SVG, and layout as injected services | `packages/design-jsx/AGENTS.md` || `packages/vue` | Headless Vue 3 SDK primitives, composables, commands, i18n, menu model | `packages/vue/AGENTS.md` || `packages/cli` | Headless `.fig` inspection, export, linting, `eval` | `packages/cli/AGENTS.md` || `packages/mcp` | stdio and Hono HTTP MCP server reusing Core tools | `packages/mcp/AGENTS.md` |@@ -53,7 +53,7 @@ Before a PR run `bun run check`, `bun run format`, `bun run test:unit`, and `bun- Put code and tests in the established owning domain; inspect nearby structure before adding files. Group multi-file domains in subfolders instead of repeated sibling prefixes (`selection/container.ts`, not `selection-container.ts`).- Non-component folders and files use lowercase or kebab-case except standard entrypoints (`README.md`, `AGENTS.md`, `index.ts`). Component domains use kebab-case folders; Vue files stay PascalCase and component composables camelCase. Do not add new PascalCase app folders or root-level base controls; migrate old ones when touched.-- No `any`, non-null assertions, or `Math.random()`; use precise types, guards, and `crypto.getRandomValues()`.+- No `any`, non-null assertions, or `Math.random()`; use precise types, guards, and `crypto.getRandomValues()` — through `randomHex`, `randomInt`, and `randomIndex` from `@open-pencil/scene-graph/random` rather than new copies. New component property IDs come from `createComponentPropertyId()`, and graph entity IDs from the `SceneGraph`'s generator (`createNode`, `createCollection`, `createMode`).- Valibot for first-party runtime validation. Keep Zod only where an upstream dependency requires it; never maintain parallel first-party schemas in both.- Use existing dependencies before writing utilities: `culori` for color conversion, `es-toolkit` for focused helpers (without replacing clear native code), VueUse for browser, event, focus, clipboard, storage, and timer behavior (one-shot rAF or service-owned timers are fine when clearer), `dedent` for multiline prompt composition and embedded examples. Keep substantial prompt prose in the owning Markdown source and compose it.- Use `js-base64` directly for Base64: `fromUint8Array`/`toUint8Array` for bytes, `encode`/`decode` for text, and `isValid` before decoding input from outside (clipboard, imported files, tool arguments). Do not wrap it or use `atob`, `btoa`, or `Buffer` Base64 conversions; `open-pencil/no-hand-rolled-base64` enforces this.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 562498daa..5abd63f4a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,7 @@### Breaking changes+- `randomHex`, `randomInt`, and `randomIndex` moved from `@open-pencil/core/random` and the `@open-pencil/core` barrel to `@open-pencil/scene-graph/random`.- `Stroke` from `@open-pencil/scene-graph` extends `Fill`, so every stroke states a paint `type` that code constructing one must set to `'SOLID'`, and `copyStroke` deep-copies the paint fields a fill already copied.- `Stroke` from `@open-pencil/scene-graph` extends `Fill`, so every stroke states a paint `type` that code constructing one must set to `'SOLID'`, and `copyStroke` deep-copies the paint fields a fill already copied. Rendering, `.fig` round-trips, and the stroke panel still handle solid strokes only.- The `design_to_tokens` AI and MCP tool writes a stylesheet of CSS custom properties built from the document's variables. Its `tailwind` format is a Tailwind v4 `@theme` instead of a JavaScript object, and the `json` format is removed. Names come from the variable's code syntax or from Tailwind namespaces (`--color-gray-50`) instead of the collection name, aliases stay `var()` references instead of resolving through the first mode, and non-default modes go under their condition (`[data-theme="dark"]` by default) instead of a class named after the mode. The result lists the tokens it left out under `issues`.@@ -22,6 +23,7 @@### Added+- Pass an ID generator to `new SceneGraph()` from `@open-pencil/scene-graph` to choose the IDs of the nodes, variables, collections, and modes the graph creates, including modes added later with `createMode`; generated IDs skip any node, variable, collection, or mode ID already in the graph, and an exhausted generator throws instead of hanging. `createComponentPropertyId` gives new component properties the `prop:` IDs the editor, plugin API, and design JSX share.- Diagnose failures from Settings → Diagnostics. Uncaught errors, unhandled rejections, component errors, failed AI chats, and AI tool calls that broke inside OpenPencil are recorded with their message and stack, and other failed tool calls as warnings. Messages and stacks are scrubbed of URL queries and credentials, API keys and tokens, email addresses, and home folder names, and provider errors keep no message. Each event has a specific label, such as *Tool: render · 162 ms* or *Error: TypeError*, expands to its details, and can be filtered by level and category and paged; copied diagnostics include the app version and browser.- Import `resolvePasteTarget` from `@open-pencil/core/editor` to place ordinary pasted or dropped content in an embedding app in the same container the editor would choose. It takes the editor `createEditor` returns. Replacement paste is not covered: it inserts into the selected target's parent.- Import `flattenNodesToVectorProps`, `outlineStrokeNodesToVectorProps`, and the `VectorFlattenProps` type from `@open-pencil/core/canvas` to compute Flatten and Outline stroke geometry in an embedding app without going through the editor's own write path.diff --git a/packages/core/package.json b/packages/core/package.jsonindex db77b397f..f016adc18 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -133,11 +133,6 @@"import": "./dist/constants.js","default": "./dist/constants.js"},- "./random": {- "types": "./dist/random.d.ts",- "import": "./dist/random.js",- "default": "./dist/random.js"- },"./xpath": {"types": "./dist/xpath.d.ts","import": "./dist/xpath.js",diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.tsindex f78407914..f4be9a53d 100644--- a/packages/core/src/clipboard.ts+++ b/packages/core/src/clipboard.ts@@ -1,4 +1,5 @@import { embedClipboardImages, encodeFigmaClipboard } from '@open-pencil/fig/clipboard'+import { randomInt } from '@open-pencil/scene-graph/random'export { parseFigmaClipboard, figmaNodesBounds } from '@open-pencil/fig/clipboard'import { placeSlotContent } from '@open-pencil/fig/node-change'import { initCodec } from '@open-pencil/kiwi/fig/codec'@@ -20,7 +21,6 @@ import {buildFontDigestMap,fractionalPosition} from './kiwi/fig/node-change/serialize'-import { randomInt } from './random'import { buildDerivedTextDataV4 } from './text/derived-text/clipboard'export async function prefetchFigmaSchema(): Promise<void> {diff --git a/packages/core/src/editor/components.ts b/packages/core/src/editor/components.tsindex ae4b9381f..2b6f2a430 100644--- a/packages/core/src/editor/components.ts+++ b/packages/core/src/editor/components.ts@@ -1,8 +1,7 @@import type { SceneNode } from '@open-pencil/scene-graph'+import { createComponentPropertyId } from '@open-pencil/scene-graph'import { deriveSlashVariantProperties } from '@open-pencil/scene-graph/variant-properties'-import { randomHex } from '#core/random'-import { createComponentFocusActions } from './components/focus'import { createComponentInstanceActions } from './components/instances'import { createComponentPropertyActions } from './components/properties'@@ -64,7 +63,7 @@ export function createComponentActions(ctx: EditorContext) {const containerId = wrapSelectionInContainer('COMPONENT_SET', selectedNodes)if (!containerId) return- const derived = deriveSlashVariantProperties(selectedNodes, () => `prop:${randomHex(8)}`)+ const derived = deriveSlashVariantProperties(selectedNodes, createComponentPropertyId)if (!derived) returnfor (const [nodeId, changes] of derived.variants) {diff --git a/packages/core/src/editor/components/slots/authoring.ts b/packages/core/src/editor/components/slots/authoring.tsindex 57877064a..e2c6e8e0f 100644--- a/packages/core/src/editor/components/slots/authoring.ts+++ b/packages/core/src/editor/components/slots/authoring.ts@@ -6,12 +6,12 @@ import {slotPropertyId,updateSlotProperty,type SceneNode,- type SlotPropertyPatch+ type SlotPropertyPatch,+ createComponentPropertyId} from '@open-pencil/scene-graph'import { wrapInAutoLayout } from '#core/editor/structure/auto-layout-wrap'import type { EditorContext } from '#core/editor/types'-import { randomHex } from '#core/random'import { recordSubtreeEdit } from './history'@@ -78,7 +78,7 @@ export function createSlotAuthoringActions(ctx: EditorContext) {const frame = ctx.graph.getNode(frameId)const owner = frame && canCreateSlot(ctx.graph, frame) ? slotOwner(ctx.graph, frame) : undefinedif (!frame || !owner) return null- const id = `prop:${randomHex(8)}`+ const id = createComponentPropertyId()recordDefinitionEdit(ctx, 'Create slot', [owner.id, frame.id], [], () => {createSlotProperty(ctx.graph, frame.id, id)})diff --git a/packages/core/src/editor/components/variants/index.ts b/packages/core/src/editor/components/variants/index.tsindex 38fe091ea..5368f97e1 100644--- a/packages/core/src/editor/components/variants/index.ts+++ b/packages/core/src/editor/components/variants/index.ts@@ -7,13 +7,13 @@ import type {ComponentPropertyType,SceneNode} from '@open-pencil/scene-graph'+import { createComponentPropertyId } from '@open-pencil/scene-graph'import { buildVariantName, parseVariantName } from '@open-pencil/scene-graph/variant-name'import { assertNodeEditable } from '#core/editor/capabilities'import { restoreSubtree, snapshotSubtree } from '#core/editor/clipboard/subtree-history'import { reapplyInstanceComponentProperties } from '#core/editor/components/properties'import type { EditorContext } from '#core/editor/types'-import { randomHex } from '#core/random'export type VariantConflict = {values: Record<string, string>@@ -263,7 +263,7 @@ export function createVariantActions(ctx: EditorContext) {const before = captureVariantSnapshot(componentSetId)if (!before) return undefined- const id = `prop:${randomHex(8)}`+ const id = createComponentPropertyId()const definition: ComponentPropertyDefinition = {id,name: normalizedName,diff --git a/packages/core/src/editor/variables.ts b/packages/core/src/editor/variables.tsindex d683f8c3c..3bd8cfe1c 100644--- a/packages/core/src/editor/variables.ts+++ b/packages/core/src/editor/variables.ts@@ -6,7 +6,6 @@ import type {} from '@open-pencil/scene-graph'import { reconcileVariableLayouts } from '#core/layout/variables'-import { randomHex } from '#core/random'import type { EditorContext } from './types'@@ -171,9 +170,9 @@ export function createVariableActions(ctx: EditorContext) {function addMode(collectionId: string, name?: string): string | undefined {const collection = ctx.graph.variableCollections.get(collectionId)if (!collection) return undefined- const modeId = `mode:${randomHex(8)}`const modeName = name ?? `Mode ${collection.modes.length + 1}`- ctx.graph.addMode(collectionId, modeId, modeName)+ const modeId = ctx.graph.createMode(collectionId, modeName)+ if (!modeId) return undefinedctx.undo.push({label: 'Add mode',forward: () => {@@ -279,9 +278,9 @@ export function createVariableActions(ctx: EditorContext) {if (!collection) return undefinedconst sourceMode = collection.modes.find((m) => m.modeId === sourceModeId)if (!sourceMode) return undefined- const modeId = `mode:${randomHex(8)}`const modeName = `${sourceMode.name} copy`- ctx.graph.addMode(collectionId, modeId, modeName, sourceModeId)+ const modeId = ctx.graph.createMode(collectionId, modeName, sourceModeId)+ if (!modeId) return undefinedctx.undo.push({label: 'Duplicate mode',forward: () => {diff --git a/packages/core/src/figma-api/components.ts b/packages/core/src/figma-api/components.tsindex 9383922cd..10dbac767 100644--- a/packages/core/src/figma-api/components.ts+++ b/packages/core/src/figma-api/components.ts@@ -8,13 +8,12 @@ import type {import {applyComponentPropertyValue,componentPropertyDefinitions as sharedComponentPropertyDefinitions,- removeComponentProperty+ removeComponentProperty,+ createComponentPropertyId} from '@open-pencil/scene-graph'import { computeAbsoluteBounds } from '@open-pencil/scene-graph/geometry'import { deriveSlashVariantProperties } from '@open-pencil/scene-graph/variant-properties'-import { randomHex } from '#core/random'-import type { NodeProxyInternals, ProxyThis } from './accessor-utils'import { graph, raw, updateNode } from './accessor-utils'import type { FigmaNodeProxy } from './proxy'@@ -86,7 +85,7 @@ export function exposeInstanceSwap(if (!slotNodes.every((node) => findPropertyHost(graph, node.parentId)?.id === host.id))throw new Error('All instances must belong to the same component or component set')const definition: ComponentPropertyDefinition = {- id: `prop:${randomHex(8)}`,+ id: createComponentPropertyId(),name,type: 'INSTANCE_SWAP',defaultValue: slotNodes[0].componentId ?? candidateIds[0],@@ -447,7 +446,7 @@ export function installComponentPropertyAccessors(if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET')throw new Error('addComponentProperty() can only be called on components')const definition: ComponentPropertyDefinition = {- id: `prop:${randomHex(8)}`,+ id: createComponentPropertyId(),name: name.trim(),type,defaultValue:@@ -531,7 +530,7 @@ export function combineComponentsAsVariants(for (const component of components) graph.reparentNode(component.id, componentSet.id)if (index !== undefined) graph.reorderChild(componentSet.id, parentId, index)- const derived = deriveSlashVariantProperties(components, () => `prop:${randomHex(8)}`)+ const derived = deriveSlashVariantProperties(components, createComponentPropertyId)if (derived) {for (const [nodeId, changes] of derived.variants) graph.updateNode(nodeId, changes)graph.updateNode(componentSet.id, { componentPropertyDefinitions: derived.definitions })diff --git a/packages/core/src/figma-api/slots.ts b/packages/core/src/figma-api/slots.tsindex ea35c0599..720358f03 100644--- a/packages/core/src/figma-api/slots.ts+++ b/packages/core/src/figma-api/slots.ts@@ -1,4 +1,5 @@import {+ createComponentPropertyId,DEFAULT_SLOT_SETTINGS,claimSlotContent,componentPropertyDefinitions,@@ -13,8 +14,6 @@ import {type SlotSettings} from '@open-pencil/scene-graph'-import { randomHex } from '#core/random'-import type { NodeProxyInternals, ProxyThis } from './accessor-utils'import { assertProxyEditable, graph, nodeId, raw } from './accessor-utils'import type { NodeProxyHost } from './proxy'@@ -122,7 +121,7 @@ export function installSlotAccessors(prototype: object, internals: NodeProxyInteassertProxyEditable(this, internals)const g = graph(this, internals)const frame = g.createNode('FRAME', component.id, { name: 'Slot' })- const definition = createSlotProperty(g, frame.id, `prop:${randomHex(8)}`)+ const definition = createSlotProperty(g, frame.id, createComponentPropertyId())if (!definition) throw new Error('Failed to create slot')g.updateNode(frame.id, { name: definition.name })return host(this, internals).wrapNode(frame.id)diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 306b21c8a..7961629bb 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -1,7 +1,5 @@export { CODEGEN_PROMPT } from './tools/prompts'-export { randomHex, randomInt, randomIndex } from './random'-export * from './constants'export { createDefaultEditorState, createEditor, EDITOR_TOOLS, TOOL_SHORTCUTS } from './editor'diff --git a/packages/core/src/io/formats/fig/read.ts b/packages/core/src/io/formats/fig/read.tsindex d3dc3caf9..be4f91748 100644--- a/packages/core/src/io/formats/fig/read.ts+++ b/packages/core/src/io/formats/fig/read.ts@@ -1,5 +1,6 @@import type { FigPageManifestEntry } from '@open-pencil/kiwi/fig'import type { SceneGraph } from '@open-pencil/scene-graph'+import { randomHex } from '@open-pencil/scene-graph/random'import { IS_BROWSER } from '#core/constants'import { deserializeSceneGraph } from '#core/kiwi/fig/parse/transfer'@@ -14,7 +15,6 @@ import {} from '#core/kiwi/fig/session/document-state'import type { FigSessionOpenRequest, FigSessionResponse } from '#core/kiwi/fig/session/protocol'import { openReaderSession } from '#core/kiwi/fig/session/reader'-import { randomHex } from '#core/random'export interface ParseFigFileOptions {populate?: 'all' | 'first-page' | 'none'diff --git a/packages/core/src/kiwi/fig/population/client.ts b/packages/core/src/kiwi/fig/population/client.tsindex eb07c4c2d..85c1bfda2 100644--- a/packages/core/src/kiwi/fig/population/client.ts+++ b/packages/core/src/kiwi/fig/population/client.ts@@ -1,8 +1,8 @@import type { SceneGraph } from '@open-pencil/scene-graph'+import { randomHex } from '@open-pencil/scene-graph/random'import { updateReaderRecovery, releaseReaderRecovery } from '#core/kiwi/fig/session/document-state'import type { FigSessionResponse } from '#core/kiwi/fig/session/protocol'-import { randomHex } from '#core/random'import { applyFigPopulationDelta } from './delta'diff --git a/packages/core/tests/io/formats/fig/roundtrip/source-metadata.test.ts b/packages/core/tests/io/formats/fig/roundtrip/source-metadata.test.tsindex 2ae20f831..b36cbb98c 100644--- a/packages/core/tests/io/formats/fig/roundtrip/source-metadata.test.ts+++ b/packages/core/tests/io/formats/fig/roundtrip/source-metadata.test.ts@@ -458,4 +458,27 @@ describe('fig roundtrip source metadata', () => {expect(typeof blobIndex).toBe('number')expect(decoded.blobs[blobIndex as number]).toEqual(rawVectorBlob)})++ test('keeps saved GUIDs of reopened nodes when a sibling is inserted before them', async () => {+ const graph = new SceneGraph()+ graph.createNode('FRAME', graph.getPages()[0].id, { name: 'Card' })+ const saved = await exportFigFile(graph)+ const savedGuidOf = (bytes: Uint8Array, name: string) => {+ const nodeChange = decodeExport(bytes).nodeChanges.find((change) => change.name === name)+ return nodeChange?.guid ? guidToString(nodeChange.guid) : undefined+ }++ const reopened = await parseFigFile(saved.slice().buffer)+ const page = reopened.getPages()[0]+ const inserted = reopened.createNode('RECTANGLE', page.id, { name: 'Inserted' })+ reopened.reorderChild(inserted.id, page.id, 0)+ const resaved = await exportFigFile(reopened)++ const cardGuid = savedGuidOf(saved, 'Card')+ expect(cardGuid).toBeDefined()+ expect(savedGuidOf(resaved, 'Card')).toBe(cardGuid)+ const insertedGuid = savedGuidOf(resaved, 'Inserted')+ expect(insertedGuid).toBeDefined()+ expect(insertedGuid).not.toBe(cardGuid)+ })})diff --git a/packages/design-jsx/src/renderer.ts b/packages/design-jsx/src/renderer.tsindex 576e40603..1f6064ee5 100644--- a/packages/design-jsx/src/renderer.ts+++ b/packages/design-jsx/src/renderer.ts@@ -1,4 +1,5 @@import {+ createComponentPropertyId,setInstanceOverride,type Color,type ComponentPropertyDefinition,@@ -63,11 +64,6 @@ export interface RenderResult {}/** Component property ids only need to be unique within a document. */-function randomHex(bytes: number): string {- return Array.from(crypto.getRandomValues(new Uint8Array(bytes)), (byte) =>- byte.toString(16).padStart(2, '0')- ).join('')-}/** The nodes a tree renders as: a fragment's children, or the tree itself. */function treeRoots(tree: TreeNode): TreeNode[] {@@ -334,7 +330,7 @@ function inferComponentSetProperties(graph: SceneGraph, componentSetId: string):.map(([name, values]) => {const variantOptions = [...values]return {- id: `prop:${randomHex(8)}`,+ id: createComponentPropertyId(),name,type: 'VARIANT',defaultValue: variantOptions[0] ?? '',diff --git a/packages/scene-graph/package.json b/packages/scene-graph/package.jsonindex c4ab2c3cc..4643f5be5 100644--- a/packages/scene-graph/package.json+++ b/packages/scene-graph/package.json@@ -167,6 +167,12 @@"import": "./dist/resize.js","default": "./dist/resize.js"},+ "./random": {+ "types": "./dist/random.d.ts",+ "bun": "./src/random.ts",+ "import": "./dist/random.js",+ "default": "./dist/random.js"+ },"./parse-path": {"types": "./dist/parse-path.d.ts","bun": "./src/parse-path.ts",diff --git a/packages/scene-graph/src/components/properties.ts b/packages/scene-graph/src/components/properties.tsindex 4ed51a2a4..6776d0ada 100644--- a/packages/scene-graph/src/components/properties.ts+++ b/packages/scene-graph/src/components/properties.ts@@ -2,6 +2,7 @@ import type { SceneGraph } from '../index'import { getInstanceOverride, setInstanceOverride } from '../instance-overrides'import { findInstanceAncestor } from '../instances'import { instanceMainComponent } from '../instances/main-component'+import { randomHex } from '../random'import type {ComponentPropertyDefinition,ComponentPropertyReferenceField,@@ -249,3 +250,8 @@ export function removeComponentProperty(for (const node of nodes) removePropertyFromNode(graph, node, propertyId)return true}++/** A new component property ID, in the `prop:` form the editor, plugin API, and design JSX share. */+export function createComponentPropertyId(): string {+ return `prop:${randomHex(8)}`+}diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex 3dcc75b02..34c2d7453 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -121,6 +121,9 @@ function stripUndefinedProps<T extends object>(obj: T): T {export { captureGraphCheckpoint } from './checkpoint'+/** How many taken IDs a generator may return in a row before it counts as exhausted. */+const MAX_ID_ATTEMPTS = 1000+export class SceneGraph {nodes = new Map<string, SceneNode>()images = new Map<string, Uint8Array>()@@ -143,8 +146,8 @@ export class SceneGraph {positionPreviewVersion = 0instanceIndex = new Map<string, Set<string>>()- constructor() {- const root = createDefaultNode(generateId, 'FRAME', {+ constructor(private readonly idGenerator: () => string = generateId) {+ const root = createDefaultNode(this.idGenerator, 'FRAME', {name: 'Document',width: 0,height: 0@@ -206,11 +209,30 @@ export class SceneGraph {collectionId: string,value?: VariableValue): Variable {- return Variables.createVariable(this, generateId, name, type, collectionId, value)+ return Variables.createVariable(+ this,+ () => this.generateEntityId(),+ name,+ type,+ collectionId,+ value+ )}createCollection(name: string): VariableCollection {- return Variables.createCollection(this, generateId, name)+ // The collection and its default mode are both created before either is registered.+ const issued = new Set<string>()+ return Variables.createCollection(this, () => this.generateEntityId(issued), name)+ }++ createMode(collectionId: string, name: string, sourceModeId?: string): string | undefined {+ return Variables.createMode(+ this,+ () => this.generateEntityId(),+ collectionId,+ name,+ sourceModeId+ )}removeCollection(id: string): void {@@ -345,10 +367,25 @@ export class SceneGraph {height: node?.height ?? 0}}- private generateNodeId(): string {- let id = generateId()- while (this.nodes.has(id)) id = generateId()- return id+ /** An ID no entity uses; `issued` also excludes IDs handed out earlier in the same creation. */+ private generateEntityId(issued?: Set<string>): string {+ for (let attempt = 0; attempt < MAX_ID_ATTEMPTS; attempt++) {+ const id = this.idGenerator()+ if (this.isEntityIdTaken(id) || issued?.has(id)) continue+ issued?.add(id)+ return id+ }+ throw new Error(`The ID generator returned ${MAX_ID_ATTEMPTS} IDs in a row that are in use`)+ }+ private isEntityIdTaken(id: string): boolean {+ if (this.nodes.has(id) || this.variables.has(id) || this.variableCollections.has(id))+ return true+ // Callers replace collection maps and edit `modes` in place (history snapshots, transfer,+ // undo), so an index of mode IDs would go stale; walk them without allocating instead.+ for (const collection of this.variableCollections.values()) {+ for (const mode of collection.modes) if (mode.modeId === id) return true+ }+ return false}private registerNode(node: SceneNode, parentId: string | null): SceneNode {node.parentId = parentId@@ -370,7 +407,7 @@ export class SceneGraph {}createNode(type: NodeType, parentId: string, overrides: Partial<SceneNode> = {}): SceneNode {- const node = createDefaultNode(() => this.generateNodeId(), type, overrides)+ const node = createDefaultNode(() => this.generateEntityId(), type, overrides)this.nodes.get(parentId)?.childIds.push(node.id)return this.registerNode(node, parentId)}diff --git a/packages/core/src/random.ts b/packages/scene-graph/src/random.tssimilarity index 100%rename from packages/core/src/random.tsrename to packages/scene-graph/src/random.tsdiff --git a/packages/scene-graph/src/variables.ts b/packages/scene-graph/src/variables.tsindex 108897820..7a54494eb 100644--- a/packages/scene-graph/src/variables.ts+++ b/packages/scene-graph/src/variables.ts@@ -182,6 +182,20 @@ export function addMode(}}+/** Add a mode with a new ID from `generateId`; undo and redo replay it with `addMode`. */+export function createMode(+ graph: SceneGraph,+ generateId: () => string,+ collectionId: string,+ name: string,+ sourceMode?: string+): string | undefined {+ if (!graph.variableCollections.has(collectionId)) return undefined+ const modeId = generateId()+ addMode(graph, collectionId, modeId, name, sourceMode)+ return modeId+}+export function removeMode(graph: SceneGraph, collectionId: string, modeId: string): void {const collection = graph.variableCollections.get(collectionId)if (!collection || collection.modes.length <= 1) returndiff --git a/packages/scene-graph/tests/basic/id-generator.test.ts b/packages/scene-graph/tests/basic/id-generator.test.tsnew file mode 100644index 000000000..1bbe357e2--- /dev/null+++ b/packages/scene-graph/tests/basic/id-generator.test.ts@@ -0,0 +1,89 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'++import { pageId } from './helpers'++function sequence(prefix: string): () => string {+ let next = 1+ return () => `${prefix}:${next++}`+}++describe('SceneGraph ID generator', () => {+ test('uses an injected generator for the root, pages, nodes, variables, and collections', () => {+ const graph = new SceneGraph(sequence('7'))++ expect(graph.rootId).toBe('7:1')+ expect(pageId(graph)).toBe('7:2')+ expect(graph.createNode('RECTANGLE', pageId(graph)).id).toBe('7:3')+ const collection = graph.createCollection('Colors')+ expect(collection.id).toBe('7:4')+ expect(collection.defaultModeId).toBe('7:5')+ expect(graph.createVariable('Primary', 'COLOR', collection.id).id).toBe('7:6')+ })++ test('skips generated IDs already used by nodes, variables, collections, or modes', () => {+ const graph = new SceneGraph(sequence('7'))+ const page = pageId(graph)+ graph.createNode('RECTANGLE', page, { id: '7:3' })+ graph.addCollection({+ id: '7:4',+ name: 'Imported',+ modes: [{ modeId: '7:5', name: 'Light' }],+ defaultModeId: '7:5',+ variableIds: []+ })+ graph.addVariable({+ id: '7:6',+ name: 'Imported color',+ type: 'COLOR',+ collectionId: '7:4',+ valuesByMode: { '7:5': { r: 0, g: 0, b: 0, a: 1 } },+ description: '',+ hiddenFromPublishing: false+ })++ expect(graph.createNode('RECTANGLE', page).id).toBe('7:7')+ expect(graph.createCollection('Fresh').id).toBe('7:8')+ })++ test('skips IDs of modes added after their collection', () => {+ const graph = new SceneGraph(sequence('7'))+ const collection = graph.createCollection('Colors')+ graph.addMode(collection.id, '7:5', 'Dark')++ expect(graph.createNode('RECTANGLE', pageId(graph)).id).toBe('7:6')+ })++ test('the default generator keeps the shared session-zero scheme', () => {+ const first = new SceneGraph()+ const second = new SceneGraph()+ const ids = [first.rootId, pageId(first), second.rootId, pageId(second)]++ for (const id of ids) expect(id).toMatch(/^0:\d+$/)+ expect(new Set(ids).size).toBe(ids.length)+ })++ test('gives a new collection and its default mode different IDs even if the generator repeats', () => {+ const ids = ['7:1', '7:2', 'same', 'same', '7:3']+ const graph = new SceneGraph(() => ids.shift() ?? 'exhausted')+ const collection = graph.createCollection('Colors')+ expect(collection.id).toBe('same')+ expect(collection.defaultModeId).toBe('7:3')+ })++ test('throws instead of hanging when the generator only returns IDs in use', () => {+ expect(() => new SceneGraph(() => 'same')).toThrow('IDs in a row that are in use')+ })++ test('gives modes added to a collection IDs from the injected generator', () => {+ const graph = new SceneGraph(sequence('7'))+ const collection = graph.createCollection('Colors')+ const variable = graph.createVariable('Primary', 'COLOR', collection.id)+ const dark = graph.createMode(collection.id, 'Dark')+ expect(dark).toBe('7:6')+ expect(collection.modes.map((mode) => mode.modeId)).toEqual(['7:4', '7:6'])+ expect(Object.keys(variable.valuesByMode)).toContain('7:6')+ expect(graph.createMode('missing', 'Dark')).toBeUndefined()+ })+})diff --git a/tests/engine/random/basic.test.ts b/packages/scene-graph/tests/random.test.tssimilarity index 98%rename from tests/engine/random/basic.test.tsrename to packages/scene-graph/tests/random.test.tsindex dce4a0dbd..71a23c276 100644--- a/tests/engine/random/basic.test.ts+++ b/packages/scene-graph/tests/random.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from 'bun:test'-import { randomHex, randomIndex, randomInt } from '@open-pencil/core/random'+import { randomHex, randomIndex, randomInt } from '@open-pencil/scene-graph/random'describe('random helpers', () => {test('randomHex returns requested byte length as hex', () => {diff --git a/packages/scene-graph/tsdown.config.ts b/packages/scene-graph/tsdown.config.tsindex 24a9fc666..29b2acd0a 100644--- a/packages/scene-graph/tsdown.config.ts+++ b/packages/scene-graph/tsdown.config.ts@@ -28,6 +28,7 @@ export default defineConfig({'layout-guides': './src/layout-guides.ts',resize: './src/resize.ts','parse-path': './src/parse-path.ts',+ random: './src/random.ts',color: './src/color/index.ts','text-direction': './src/text-direction.ts'},diff --git a/packages/vue/src/controls/binding-provider/color.ts b/packages/vue/src/controls/binding-provider/color.tsindex 9ca36c419..47541a7b2 100644--- a/packages/vue/src/controls/binding-provider/color.ts+++ b/packages/vue/src/controls/binding-provider/color.ts@@ -1,7 +1,7 @@import type { Editor } from '@open-pencil/core/editor'-import { randomHex } from '@open-pencil/core/random'import type { VariableCollection } from '@open-pencil/scene-graph'import type { Color } from '@open-pencil/scene-graph/primitives'+import { randomHex } from '@open-pencil/scene-graph/random'import { useOpenPencilBindingProvider } from '#vue/controls/binding-provider/open-pencil'import type { BindingTarget } from '#vue/controls/binding-provider/types'diff --git a/packages/vue/src/controls/binding-provider/number.ts b/packages/vue/src/controls/binding-provider/number.tsindex 427aad2e2..548958922 100644--- a/packages/vue/src/controls/binding-provider/number.ts+++ b/packages/vue/src/controls/binding-provider/number.ts@@ -1,6 +1,6 @@import type { Editor } from '@open-pencil/core/editor'-import { randomHex } from '@open-pencil/core/random'import type { VariableCollection } from '@open-pencil/scene-graph'+import { randomHex } from '@open-pencil/scene-graph/random'import { useOpenPencilBindingProvider } from '#vue/controls/binding-provider/open-pencil'import type { BindingTarget } from '#vue/controls/binding-provider/types'diff --git a/packages/vue/src/controls/color-variable-binding/use.ts b/packages/vue/src/controls/color-variable-binding/use.tsindex 0ad0737e3..301003c38 100644--- a/packages/vue/src/controls/color-variable-binding/use.ts+++ b/packages/vue/src/controls/color-variable-binding/use.ts@@ -1,4 +1,4 @@-import { randomHex } from '@open-pencil/core/random'+import { randomHex } from '@open-pencil/scene-graph/random'import { useVariableBinding } from '#vue/controls/variable-binding/use'diff --git a/packages/vue/src/variables/helpers.ts b/packages/vue/src/variables/helpers.tsindex 65c0f251b..0760fce41 100644--- a/packages/vue/src/variables/helpers.ts+++ b/packages/vue/src/variables/helpers.ts@@ -2,7 +2,6 @@ import type { Ref } from 'vue'import { BLACK } from '@open-pencil/core/constants'import type { Editor } from '@open-pencil/core/editor'-import { randomHex } from '@open-pencil/core/random'import type {Variable,VariableCollection,@@ -10,6 +9,7 @@ import type {VariableValue} from '@open-pencil/scene-graph'import { colorToHexRaw, parseColor } from '@open-pencil/scene-graph/color'+import { randomHex } from '@open-pencil/scene-graph/random'export function createVariableCollectionActions(editor: Editor, activeCollectionId: Ref<string>) {function setActiveCollection(id: string) {diff --git a/src/app/automation/bridge/server.ts b/src/app/automation/bridge/server.tsindex 6f5ece212..b78a50bd4 100644--- a/src/app/automation/bridge/server.ts+++ b/src/app/automation/bridge/server.ts@@ -6,7 +6,7 @@*/import * as v from 'valibot'-import { randomHex } from '@open-pencil/core/random'+import { randomHex } from '@open-pencil/scene-graph/random'import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'import { createAutomationCommandHandlers } from '@/app/automation/bridge/handlers'diff --git a/src/app/automation/mcp/spawn.ts b/src/app/automation/mcp/spawn.tsindex 4a96dbe54..971203d96 100644--- a/src/app/automation/mcp/spawn.ts+++ b/src/app/automation/mcp/spawn.ts@@ -2,13 +2,13 @@ import { promiseTimeout } from '@vueuse/core'import * as v from 'valibot'import { AUTOMATION_HTTP_PORT } from '@open-pencil/core/constants'-import { randomHex } from '@open-pencil/core/random'import type { DiscoveryInfo } from '@open-pencil/mcp/discovery'import {parseToolDescriptor,serializeDisabledTools,type ToolDescriptor} from '@open-pencil/mcp/tools'+import { randomHex } from '@open-pencil/scene-graph/random'import { decodeTauriStderr } from '@/app/shell/ui'import { resolvePlatformCommand } from '@/app/tauri/command'diff --git a/src/app/collab/awareness.ts b/src/app/collab/awareness.tsindex a6f69c948..783c57258 100644--- a/src/app/collab/awareness.ts+++ b/src/app/collab/awareness.ts@@ -1,4 +1,4 @@-import { randomIndex } from '@open-pencil/core/random'+import { randomIndex } from '@open-pencil/scene-graph/random'import { parsePeer } from '@/app/presence/schema'import { ROOM_ID_CHARS, ROOM_ID_LENGTH } from '@/constants'diff --git a/src/app/collab/session.ts b/src/app/collab/session.tsindex 79661359d..4a82c9808 100644--- a/src/app/collab/session.ts+++ b/src/app/collab/session.ts@@ -4,7 +4,7 @@ import * as awarenessProtocol from 'y-protocols/awareness'import type { Awareness } from 'y-protocols/awareness'import * as Y from 'yjs'-import { randomIndex } from '@open-pencil/core/random'+import { randomIndex } from '@open-pencil/scene-graph/random'import { publishLocalAgents } from '@/app/collab/local-awareness'import { connectCollabRoom } from '@/app/collab/room'diff --git a/src/app/presence/callsigns.ts b/src/app/presence/callsigns.tsindex aab0a6b42..b12b4b4e5 100644--- a/src/app/presence/callsigns.ts+++ b/src/app/presence/callsigns.ts@@ -1,4 +1,4 @@-import { randomIndex } from '@open-pencil/core/random'+import { randomIndex } from '@open-pencil/scene-graph/random'/** Short, distinct names that are easy to say: "ask Fern to align the cards". */const CALLSIGNS = [diff --git a/src/app/presence/registry.ts b/src/app/presence/registry.tsindex d7f797213..56309863d 100644--- a/src/app/presence/registry.ts+++ b/src/app/presence/registry.ts@@ -2,8 +2,8 @@ import { shallowRef, type ShallowRef } from 'vue'import type { PresenceCursor } from '@open-pencil/core/canvas'import { AI_ACTIVE_COLOR } from '@open-pencil/core/constants'-import { randomHex } from '@open-pencil/core/random'import type { Color } from '@open-pencil/scene-graph/primitives'+import { randomHex } from '@open-pencil/scene-graph/random'import type { RemotePeer } from '@/app/collab/types'import type { EditorStore } from '@/app/editor/active-store'diff --git a/tests/app/collab/concurrent-edits.test.ts b/tests/app/collab/concurrent-edits.test.tsnew file mode 100644index 000000000..baf228e74--- /dev/null+++ b/tests/app/collab/concurrent-edits.test.ts@@ -0,0 +1,87 @@+import { describe, expect, test } from 'bun:test'++import type { SceneGraph } from '@open-pencil/scene-graph'++import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'+import { type SyncedStores, withSyncedStores } from '#tests/helpers/collab/synced-stores'+import { connectYDocs } from '#tests/helpers/yjs'++/** Edit both peers while their documents are disconnected, then reconnect them. */+async function withConcurrentEdits(+ seed: (graph: SceneGraph, pageId: string) => void,+ edit: (stores: SyncedStores, pageId: string) => void,+ check: (stores: SyncedStores, pageId: string) => void+) {+ await withSyncedStores(+ (stores) => {+ const pageId = expectDefined(stores.hostStore.graph.getPages()[0], 'first page').id+ seed(stores.hostStore.graph, pageId)+ stores.hostSync.syncAllNodesToYjs()+ expectDefined(stores.disconnectYDocs, 'connected peers to disconnect')()+ edit(stores, pageId)+ const disconnect = connectYDocs(stores.hostDoc, stores.peerDoc)+ try {+ check(stores, pageId)+ } finally {+ disconnect()+ }+ },+ { bindGraphEvents: true }+ )+}++describe('collab concurrent edits', () => {+ test('concurrent additions to one parent keep both nodes on both peers', async () => {+ await withConcurrentEdits(+ () => undefined,+ ({ hostStore, peerStore }, pageId) => {+ hostStore.graph.createNode('RECTANGLE', pageId, { id: 'host:1' })+ peerStore.graph.createNode('RECTANGLE', pageId, { id: 'peer:1' })+ },+ ({ hostStore, peerStore }, pageId) => {+ for (const graph of [hostStore.graph, peerStore.graph]) {+ expect(getNodeOrThrow(graph, 'host:1').parentId).toBe(pageId)+ expect(getNodeOrThrow(graph, 'peer:1').parentId).toBe(pageId)+ expect(getNodeOrThrow(graph, pageId).childIds).toEqual(+ expect.arrayContaining(['host:1', 'peer:1'])+ )+ }+ }+ )+ })++ test('concurrent writes to one property converge to the same value', async () => {+ await withConcurrentEdits(+ (graph, pageId) => {+ graph.createNode('RECTANGLE', pageId, { id: 'rect:1' })+ },+ ({ hostStore, peerStore }) => {+ hostStore.graph.updateNode('rect:1', { x: 10 })+ peerStore.graph.updateNode('rect:1', { x: 20 })+ },+ ({ hostStore, peerStore }) => {+ const x = getNodeOrThrow(hostStore.graph, 'rect:1').x+ expect([10, 20]).toContain(x)+ expect(getNodeOrThrow(peerStore.graph, 'rect:1').x).toBe(x)+ }+ )+ })++ test('a deletion wins over a concurrent edit of the deleted node', async () => {+ await withConcurrentEdits(+ (graph, pageId) => {+ graph.createNode('RECTANGLE', pageId, { id: 'rect:1' })+ },+ ({ hostStore, peerStore }) => {+ hostStore.graph.deleteNode('rect:1')+ peerStore.graph.updateNode('rect:1', { x: 20 })+ },+ ({ hostStore, peerStore }, pageId) => {+ for (const graph of [hostStore.graph, peerStore.graph]) {+ expect(graph.getNode('rect:1')).toBeUndefined()+ expect(getNodeOrThrow(graph, pageId).childIds).not.toContain('rect:1')+ }+ }+ )+ })+})diff --git a/tests/engine/collab/yjs-sync.test.ts b/tests/engine/collab/yjs-sync.test.tsindex 2b8dfa371..69258ee3c 100644--- a/tests/engine/collab/yjs-sync.test.ts+++ b/tests/engine/collab/yjs-sync.test.ts@@ -10,11 +10,9 @@ 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 { createYjsGraphSync, registerYjsObservers } from '@/app/collab/yjs-sync'-import { createEditorStore } from '@/app/editor/session'import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'-import { connectYDocs } from '#tests/helpers/yjs'+import { withSyncedStores } from '#tests/helpers/collab/synced-stores'// Test copy of the private apply path.function applyYnodeToGraph(peer: SceneGraph, nodeId: string, ynode: Y.Map<unknown>) {@@ -47,107 +45,6 @@ function firstPage(graph: SceneGraph): SceneNode {return expectDefined(graph.getPages()[0], 'first page')}-type SyncedStores = ReturnType<typeof createSyncedStores>--type SyncedStoreOptions = {- hostDoc?: Y.Doc- peerDoc?: Y.Doc- connectImmediately?: boolean-}--function createSyncedStores(options: SyncedStoreOptions = {}) {- const hostStore = createEditorStore(new SceneGraph())- const peerStore = createEditorStore(new SceneGraph())- const hostDoc = options.hostDoc ?? new Y.Doc()- const peerDoc = options.peerDoc ?? new Y.Doc()- const hostNodes = hostDoc.getMap<Y.Map<unknown>>('nodes')- const peerNodes = peerDoc.getMap<Y.Map<unknown>>('nodes')- const hostImages = hostDoc.getMap<Uint8Array>('images')- const peerImages = peerDoc.getMap<Uint8Array>('images')- let hostSuppressYjsEvents = false- let peerSuppressYjsEvents = false- let hostSuppressGraphSync = false- let peerSuppressGraphSync = false-- const hostSync = createYjsGraphSync({- getStore: () => hostStore,- getYdoc: () => hostDoc,- getYnodes: () => hostNodes,- getYimages: () => hostImages,- setSuppressYjsEvents: (value) => {- hostSuppressYjsEvents = value- }- })- const peerSync = createYjsGraphSync({- getStore: () => peerStore,- getYdoc: () => peerDoc,- getYnodes: () => peerNodes,- getYimages: () => peerImages,- setSuppressYjsEvents: (value) => {- peerSuppressYjsEvents = value- }- })-- registerYjsObservers({- store: hostStore,- ynodes: hostNodes,- yimages: hostImages,- getSuppressYjsEvents: () => hostSuppressYjsEvents,- setSuppressGraphSync: (value) => {- hostSuppressGraphSync = value- },- applyYjsToGraph: hostSync.applyYjsToGraph- })- registerYjsObservers({- store: peerStore,- ynodes: peerNodes,- yimages: peerImages,- getSuppressYjsEvents: () => peerSuppressYjsEvents,- setSuppressGraphSync: (value) => {- peerSuppressGraphSync = value- },- applyYjsToGraph: peerSync.applyYjsToGraph- })-- const disconnectYDocs =- options.connectImmediately === false ? undefined : connectYDocs(hostDoc, peerDoc)-- return {- hostStore,- peerStore,- hostSync,- peerSync,- hostDoc,- peerDoc,- disconnectYDocs,- get hostSuppressGraphSync() {- return hostSuppressGraphSync- },- get peerSuppressGraphSync() {- return peerSuppressGraphSync- },- cleanup: () => {- hostStore.preparationController.dispose()- peerStore.preparationController.dispose()- disconnectYDocs?.()- hostDoc.destroy()- peerDoc.destroy()- }- }-}--async function withSyncedStores(- run: (stores: SyncedStores) => void | Promise<void>,- options: SyncedStoreOptions = {}-) {- const stores = createSyncedStores(options)- try {- await run(stores)- } finally {- stores.cleanup()- }-}-describe('collab yjs-sync', () => {test('createNodeWithId forces the requested id even if synced props contain a stale id', () => {const graph = new SceneGraph()diff --git a/tests/helpers/collab/synced-stores.ts b/tests/helpers/collab/synced-stores.tsnew file mode 100644index 000000000..637af95c8--- /dev/null+++ b/tests/helpers/collab/synced-stores.ts@@ -0,0 +1,142 @@+import * as Y from 'yjs'++import { SceneGraph } from '@open-pencil/scene-graph'++import {+ bindCollabGraphEvents,+ createYjsGraphSync,+ registerYjsObservers+} from '@/app/collab/yjs-sync'+import { createEditorStore } from '@/app/editor/session'++import { connectYDocs } from '#tests/helpers/yjs'++/** Host and peer editor stores whose Yjs documents sync through the app's collab code. */+export type SyncedStores = ReturnType<typeof createSyncedStores>++export type SyncedStoreOptions = {+ hostDoc?: Y.Doc+ peerDoc?: Y.Doc+ connectImmediately?: boolean+ /** Sync local graph edits to Yjs through graph events, as a collab session does. */+ bindGraphEvents?: boolean+}++export function createSyncedStores(options: SyncedStoreOptions = {}) {+ const hostStore = createEditorStore(new SceneGraph())+ const peerStore = createEditorStore(new SceneGraph())+ const hostDoc = options.hostDoc ?? new Y.Doc()+ const peerDoc = options.peerDoc ?? new Y.Doc()+ const hostNodes = hostDoc.getMap<Y.Map<unknown>>('nodes')+ const peerNodes = peerDoc.getMap<Y.Map<unknown>>('nodes')+ const hostImages = hostDoc.getMap<Uint8Array>('images')+ const peerImages = peerDoc.getMap<Uint8Array>('images')+ let hostSuppressYjsEvents = false+ let peerSuppressYjsEvents = false+ let hostSuppressGraphSync = false+ let peerSuppressGraphSync = false++ const hostSync = createYjsGraphSync({+ getStore: () => hostStore,+ getYdoc: () => hostDoc,+ getYnodes: () => hostNodes,+ getYimages: () => hostImages,+ setSuppressYjsEvents: (value) => {+ hostSuppressYjsEvents = value+ }+ })+ const peerSync = createYjsGraphSync({+ getStore: () => peerStore,+ getYdoc: () => peerDoc,+ getYnodes: () => peerNodes,+ getYimages: () => peerImages,+ setSuppressYjsEvents: (value) => {+ peerSuppressYjsEvents = value+ }+ })++ registerYjsObservers({+ store: hostStore,+ ynodes: hostNodes,+ yimages: hostImages,+ getSuppressYjsEvents: () => hostSuppressYjsEvents,+ setSuppressGraphSync: (value) => {+ hostSuppressGraphSync = value+ },+ applyYjsToGraph: hostSync.applyYjsToGraph+ })+ registerYjsObservers({+ store: peerStore,+ ynodes: peerNodes,+ yimages: peerImages,+ getSuppressYjsEvents: () => peerSuppressYjsEvents,+ setSuppressGraphSync: (value) => {+ peerSuppressGraphSync = value+ },+ applyYjsToGraph: peerSync.applyYjsToGraph+ })++ const unbindGraphEvents = options.bindGraphEvents+ ? [+ bindCollabGraphEvents({+ store: hostStore,+ getYdoc: () => hostDoc,+ getYnodes: () => hostNodes,+ getSuppressGraphSync: () => hostSuppressGraphSync,+ setSuppressYjsEvents: (value) => {+ hostSuppressYjsEvents = value+ },+ syncNodeToYjs: hostSync.syncNodeToYjs+ }),+ bindCollabGraphEvents({+ store: peerStore,+ getYdoc: () => peerDoc,+ getYnodes: () => peerNodes,+ getSuppressGraphSync: () => peerSuppressGraphSync,+ setSuppressYjsEvents: (value) => {+ peerSuppressYjsEvents = value+ },+ syncNodeToYjs: peerSync.syncNodeToYjs+ })+ ]+ : []++ const disconnectYDocs =+ options.connectImmediately === false ? undefined : connectYDocs(hostDoc, peerDoc)++ return {+ hostStore,+ peerStore,+ hostSync,+ peerSync,+ hostDoc,+ peerDoc,+ disconnectYDocs,+ get hostSuppressGraphSync() {+ return hostSuppressGraphSync+ },+ get peerSuppressGraphSync() {+ return peerSuppressGraphSync+ },+ cleanup: () => {+ for (const unbind of unbindGraphEvents) unbind()+ hostStore.preparationController.dispose()+ peerStore.preparationController.dispose()+ disconnectYDocs?.()+ hostDoc.destroy()+ peerDoc.destroy()+ }+ }+}++export async function withSyncedStores(+ run: (stores: SyncedStores) => void | Promise<void>,+ options: SyncedStoreOptions = {}+) {+ const stores = createSyncedStores(options)+ try {+ await run(stores)+ } finally {+ stores.cleanup()+ }+}diff --git a/tests/helpers/mcp/server.ts b/tests/helpers/mcp/server.tsindex 60612176e..02b01600b 100644--- a/tests/helpers/mcp/server.ts+++ b/tests/helpers/mcp/server.ts@@ -11,6 +11,7 @@ import {executeRPCCommand} from '@open-pencil/core'import type { ToolDescriptor } from '@open-pencil/mcp/tools'+import { randomHex } from '@open-pencil/scene-graph/random'const ToolDescriptorShape = v.looseObject({ name: v.string(), enabled: v.boolean() })@@ -205,15 +206,6 @@ export function socketRequest(return nodeHttpRequest({ socketPath, path, method, headers: headers ?? {} })}-/** Generate a random hex string of the given byte length using crypto.getRandomValues(). */-function randomHex(bytes: number): string {- const buf = new Uint8Array(bytes)- globalThis.crypto.getRandomValues(buf)- return Array.from(buf)- .map((b) => b.toString(16).padStart(2, '0'))- .join('')-}-// App commands whose mock result does not depend on the graph or arguments.const FIXED_MOCK_RESULTS: Partial<Record<string, object>> = {save_file: {},diff --git a/tools/checks/test-homes/engine-baseline.txt b/tools/checks/test-homes/engine-baseline.txtindex 2ebe8d025..ac7f062bc 100644--- a/tools/checks/test-homes/engine-baseline.txt+++ b/tools/checks/test-homes/engine-baseline.txt@@ -353,7 +353,6 @@ tests/engine/profiler/frame-stats.test.tstests/engine/profiler/gpu-timer.test.tstests/engine/profiler/phase-timer.test.tstests/engine/profiler/speedscope.test.ts-tests/engine/random/basic.test.tstests/engine/render/canvas/arrow-heads-draw.test.tstests/engine/render/canvas/blend.test.tstests/engine/render/canvas/boolean.test.ts