AI-native design editor. Open-source Figma alternative.
fix(scene-graph): keep new layer GUIDs distinct across headless runs (#1028)
Marc Wenta97bef80fd49
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 32579344e..9aba55b28 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -48,6 +48,7 @@- `fetchIcon`, `fetchIcons`, `searchIcons`, `searchIconsBatch`, and `clearIconCache` are removed from `@open-pencil/core`. Icons come from an `IconProvider` instead: `iconify` is the default Iconify provider, `createIconifyProvider()` makes one with its own cache, and `placeIcon` places an icon that keeps its name. A custom provider also implements `previews()`, `collections()`, and `browse()`, which give pickers each icon's SVG markup, the sets, and a set's icons.- The editor's view state has a required `shapeHandleHover`, the selected shape whose radius, point count, and ratio handles the canvas shows; code that creates editor state itself must set it, as `createDefaultEditorViewState` does.- `defineTool` from `@open-pencil/core/tools` takes its `input` as a `v.strictObject` instead of a `v.object`, and `ToolDef.input` is a strict object schema, so a tool rejects arguments it does not declare.+- Every process mints new layer, variable, and collection IDs in a random session, as the editor already did, so `generateId()` no longer starts at `0:1` in the CLI, MCP, or scripts using `@open-pencil/scene-graph`. Layers that separate CLI or MCP runs add to copies of one `.fig` file are saved under their own GUIDs instead of the same `1:n` ones, while layers read from a file keep the same IDs on every run. Code that needs fixed IDs calls `setIdSession`, which now returns the previous session, or gives the `SceneGraph` its own generator (#770).- `RulerTheme` from `@open-pencil/core/canvas` no longer has `label`: ruler badges and size pills draw their text in the `foreground` of the editor state's new `selectionTheme`, which also sets the canvas selection color and defaults to the previous blue with white text.### Addeddiff --git a/packages/cli/src/commands/diff/files.ts b/packages/cli/src/commands/diff/files.tsindex 046a785d0..0690e4ada 100644--- a/packages/cli/src/commands/diff/files.ts+++ b/packages/cli/src/commands/diff/files.ts@@ -23,8 +23,8 @@ export default defineCommand({printError(`--depth must be a non-negative integer, got "${args.depth}"`)process.exit(2)}- // Load in order: node IDs count up per process, so the first document gets the IDs a- // single load gives it, and the patch applies to it with `diff apply`.+ // Each import retains reproducible runtime handles, so patches address the same layers+ // when the original document is loaded again by `diff apply`.const before = await loadDocument(args.before)const after = await loadDocument(args.after)populateWholeDocument(before)diff --git a/packages/core/src/io/formats/fig/export-setup.ts b/packages/core/src/io/formats/fig/export-setup.tsindex ccca397c8..fd2c4fa05 100644--- a/packages/core/src/io/formats/fig/export-setup.ts+++ b/packages/core/src/io/formats/fig/export-setup.ts@@ -347,14 +347,16 @@ export interface FigExportSetup {}export interface FigExportSetupOptions {+ /** Saved identities on pages that may not be loaded; new layer IDs must not claim them. */+ archiveRecordIds?: readonly string[]/** The first local ID a new GUID may take, above every GUID the target archive holds. */nextLocalId?: number/** The target archive's blobs, so the indices of new blobs follow theirs. */blobs?: Uint8Array[]/*** The layer each archive GUID belongs to; only that layer writes the archive's record. Writing- * into an archive also gives new layers and pages counter GUIDs, past every GUID it holds,- * rather than their graph IDs, which a record on a page not loaded may already use.+ * into an archive preserves new layers' numeric graph IDs when unclaimed across all pages;+ * incompatible or colliding IDs fall back to counter GUIDs past the archive's reserved range.*/recordOwners?: ReadonlyMap<string, string>/** Writing into an archive: the variables, collections and modes it holds keep their GUIDs. */@@ -390,6 +392,7 @@ export async function prepareFigExport(const propertyIdToGuid = new Map<string, GUID>()const nodeSourceGuidValues = layerSourceGuids(graph)+ const reservedLayerGuids = new Set([...nodeSourceGuidValues, ...(options.archiveRecordIds ?? [])])const propertyIds = collectComponentPropertyIds(graph)// Before any canvas, variable or layer takes a counter GUID, so none collides.localIdCounter.value = Math.max(@@ -405,8 +408,8 @@ export async function prepareFigExport(localIdCounter,nodeIdToGuid,assignedGuidValues,- nodeSourceGuidValues,- !options.recordOwners+ reservedLayerGuids,+ true)// Archive records keep their GUIDs: claim them before any copy that kept one can.for (const [guid, nodeId] of options.recordOwners ?? []) {@@ -425,7 +428,9 @@ export async function prepareFigExport(modeIdToGuid,assignedGuidValues,nodeSourceGuidValues,- archived ? (id) => archived.has(id) : undefined+ archived+ ? (id) => archived.has(id) || ownGuid(id, reservedLayerGuids, assignedGuidValues) !== null+ : undefined)assignComponentPropertyGuids(@@ -436,8 +441,7 @@ export async function prepareFigExport(nodeSourceGuidValues)const pluginDataOverrides = renamedBehaviourPluginData(graph, propertyIdToGuid)- if (!options.recordOwners)- assignOwnLayerGuids(graph, nodeSourceGuidValues, nodeIdToGuid, assignedGuidValues)+ assignOwnLayerGuids(graph, reservedLayerGuids, nodeIdToGuid, assignedGuidValues)return {graph,diff --git a/packages/core/src/io/formats/fig/patch-export.ts b/packages/core/src/io/formats/fig/patch-export.tsindex d41a819d6..4ba53f46b 100644--- a/packages/core/src/io/formats/fig/patch-export.ts+++ b/packages/core/src/io/formats/fig/patch-export.ts@@ -271,6 +271,7 @@ async function buildPatch(nextLocalId: info.nextLocalId,blobs: Array.from({ length: info.blobCount }, () => new Uint8Array(0)),recordOwners: archived.byGuid,+ archiveRecordIds: info.recordIds,archiveResourceIds: changes.resourceIds})const records = writeRecords(setup, plan)diff --git a/packages/core/tests/io/formats/fig/export/archive-patch.test.ts b/packages/core/tests/io/formats/fig/export/archive-patch.test.tsindex e57633bbe..5e7bd3e21 100644--- a/packages/core/tests/io/formats/fig/export/archive-patch.test.ts+++ b/packages/core/tests/io/formats/fig/export/archive-patch.test.ts@@ -1,21 +1,52 @@import { describe, expect, setDefaultTimeout, test } from 'bun:test'+import { expectDefined } from '#core-tests/helpers/assert'import { isEqual } from 'es-toolkit/predicate'import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'-import { parseFigBuffer } from '@open-pencil/fig'import { populateAllFigPages, populateFigPage } from '@open-pencil/core/io/formats/fig'+import { parseFigBuffer } from '@open-pencil/fig'import type { NodeChange } from '@open-pencil/kiwi/fig/codec'import { guidToString } from '@open-pencil/kiwi/fig/guid'import type { SceneNode } from '@open-pencil/scene-graph'import { cloneNodeProps } from '@open-pencil/scene-graph/copy'import { releaseFigArchive } from '#core/kiwi/fig/session/archive'-import { expectDefined } from '#core-tests/helpers/assert'-import { hasPendingReaderPages, populateFigInternalPages } from '#core/kiwi/fig/session/document-state'+import {+ hasPendingReaderPages,+ populateFigInternalPages+} from '#core/kiwi/fig/session/document-state'setDefaultTimeout(60_000)+test('independent headless branches preserve distinct new GUIDs across patched saves', async () => {+ const bytes = await fixtureBytes()+ const first = await open(bytes)+ const second = await open(bytes)+ // Imported handles remain usable by headless scripts; only newly authored identities differ.+ expect(layerNamed(first, 'A').id).toBe(layerNamed(second, 'A').id)+ const left = first.createNode('RECTANGLE', first.getPages()[0].id, { name: 'Left branch' })+ const right = second.createNode('RECTANGLE', second.getPages()[0].id, { name: 'Right branch' })+ expect(left.id).not.toBe(right.id)+ const savedLeft = await exportFigFile(first)+ const savedRight = await exportFigFile(second)+ const leftRecord = parseFigBuffer(Uint8Array.from(savedLeft).buffer).nodeChanges.find(+ (record) => record.name === left.name+ )+ const rightRecord = parseFigBuffer(Uint8Array.from(savedRight).buffer).nodeChanges.find(+ (record) => record.name === right.name+ )+ expect(guidToString(expectDefined(leftRecord?.guid))).toBe(left.id)+ expect(guidToString(expectDefined(rightRecord?.guid))).toBe(right.id)+ const reopened = await open(savedLeft)+ expect(layerNamed(reopened, left.name).source.id).toBe(left.id)+ // Saving wrote into the archive: the pages not opened stay unpopulated, and every record the+ // file held, theirs included, is saved under its GUID.+ expect(hasPendingReaderPages(first)).toBe(true)+ const saved = recordsOf(savedLeft)+ expect([...recordsOf(bytes).keys()].filter((guid) => !saved.has(guid))).toEqual([])+})+/** A document over three pages: a frame of layers, a component, and a page of its instances. */async function fixtureBytes(): Promise<Uint8Array> {await initCodec()@@ -95,8 +126,7 @@ async function shapeOf(bytes: Uint8Array): Promise<Record<string, LayerShape[]>>)}-const guidKey = (record: NodeChange) =>- record.guid ? guidToString(record.guid) : ''+const guidKey = (record: NodeChange) => (record.guid ? guidToString(record.guid) : '')/** The records of an archive by GUID. */function recordsOf(bytes: Uint8Array) {diff --git a/packages/core/tests/io/formats/fig/session/reader-delta.test.ts b/packages/core/tests/io/formats/fig/session/reader-delta.test.tsindex b4f8758fd..eb7c84a01 100644--- a/packages/core/tests/io/formats/fig/session/reader-delta.test.ts+++ b/packages/core/tests/io/formats/fig/session/reader-delta.test.ts@@ -12,6 +12,31 @@ import {applyFigPopulationDelta} from '#core/kiwi/fig/population/delta'+test('resuming preserves consumed import handles after the highest imported node is deleted', async () => {+ await initCodec()+ const source = new SceneGraph()+ source.createNode('RECTANGLE', source.getPages()[0].id, { name: 'Deleted' })+ source.createNode('RECTANGLE', source.addPage('Pending').id, { name: 'Pending node' })+ const bytes = await exportFigFile(source)+ const session = createFigDocumentSession(Uint8Array.from(bytes).buffer)+ session.loadPage(session.pages[0].id)+ const loaded = session.graph.getChildren(session.graph.getPages()[0].id)[0]+ session.graph.deleteNode(loaded.id)+ const restored = deserializeSceneGraph(serializeSceneGraph(session.graph))+ const resumed = createFigDocumentSession(+ Uint8Array.from(bytes).buffer,+ {},+ {+ graph: restored,+ checkpoint: structuredClone(session.checkpoint())+ }+ )+ session.loadPage(session.pages[1].id)+ resumed.loadPage(resumed.pages[1].id)+ const expected = session.graph.getChildren(session.graph.getPages()[1].id)[0].id+ expect(restored.getChildren(restored.getPages()[1].id)[0].id).toBe(expected)+ expect(expected).not.toBe(loaded.id)+})test('new-reader page loads transfer through the worker delta contract', async () => {await initCodec()const source = new SceneGraph()@@ -73,6 +98,9 @@ test('new-reader page loads transfer through the worker delta contract', async (const secondJournal = installFigMutationJournal(session.graph)try {session.loadPage(session.pages[1].id)+ expect(+ recoveryGraph.getChildren(recoveryGraph.getPages()[1].id).map((node) => node.id)+ ).toEqual(session.graph.getChildren(session.graph.getPages()[1].id).map((node) => node.id))applyFigPopulationDelta(receiver,structuredClone(@@ -91,4 +119,5 @@ test('new-reader page loads transfer through the worker delta contract', async (} finally {secondJournal.stop()}+ expect(recoveryGraph.createNode('RECTANGLE', pageId).id).not.toMatch(/^0:/)})diff --git a/packages/docs/development/document-identity.md b/packages/docs/development/document-identity.mdnew file mode 100644index 000000000..86047b388--- /dev/null+++ b/packages/docs/development/document-identity.md@@ -0,0 +1,24 @@+---+title: Document identity+description: How layers, variables, and collections get IDs, and which of them a saved .fig file keeps.+---++# Document identity++IDs follow Figma's `sessionID:localID` GUIDs, and both halves stay at or below 2^31 − 1 because Figma reads them as signed 32-bit integers and drops records beyond that.++## New IDs++Every process picks a random session at startup, outside sessions 0 and 1, which FIG keeps for document records and counter GUIDs. IDs count up within it, so the editor, the CLI, and MCP never mint the same ID for different layers, whether they share a room or edit copies of one file. Tests and fixtures that need the same IDs on every run call `setIdSession` with a fixed session, or pass a generator to `new SceneGraph()`.++## Imported layers++Reading a `.fig` file gives its layers handles from a counter of their own, `0:1`, `0:2`, and so on, in the order the reader builds them. The same file gets the same handles on every run, which is what lets `openpencil tree` print an ID that a later `openpencil node` or `diff apply` finds. Pages loaded later continue the counter, and a resumed session carries it in its checkpoint. A handle is not the layer's identity: the GUID the file saved it under is its `source.id`.++## Saving++A layer read from the file keeps its saved GUID. A new layer is saved under its own ID when that ID has the GUID shape and no record in the archive, including records on pages never opened, already uses it. Otherwise it takes a counter GUID past every GUID in the file. Reopening the file makes the saved GUID the layer's `source.id`, so later saves keep it.++## Limits++Random sessions make collisions between separate edits unlikely, not impossible, and nothing reconciles two copies of a file automatically. A shared room stays the authority for its live document; merging offline copies means applying the changes to one of them and sharing the result as a new room.diff --git a/packages/fig/src/document/fragment.ts b/packages/fig/src/document/fragment.tsindex 705ed09d2..9be90cfc7 100644--- a/packages/fig/src/document/fragment.ts+++ b/packages/fig/src/document/fragment.ts@@ -2,7 +2,11 @@ import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'import { guidToString } from '@open-pencil/kiwi/fig/guid'import { isUnsupportedFigFragmentType } from '../node-classification'-import { materializeDocument, type DocumentAssemblyOptions } from './materialize'+import {+ materializeDocument,+ type AssemblyState,+ type DocumentAssemblyOptions+} from './materialize'export interface FragmentOptions {/** Only empty instances with no saved claims may lose an unavailable component. */@@ -13,12 +17,17 @@ export interface FragmentMaterializationOptions extends FragmentOptions {images?: DocumentAssemblyOptions['images']}+export interface MaterializedFigFragment extends AssemblyState {+ rootIds: string[]+ dependencyPageIds: string[]+}+/** Interpret a partial document in isolation; retain internal resources separately from pasted roots. */export function materializeFigFragment(source: readonly NodeChange[],blobs: Uint8Array[] = [],options: FragmentMaterializationOptions = {}-) {+): MaterializedFigFragment {const changes = normalizeFigFragment(source, options)const result = materializeDocument(changes, blobs, {derivedBounds: true,diff --git a/packages/fig/src/document/load-transaction.ts b/packages/fig/src/document/load-transaction.tsindex 31ffb39f5..72b7b0554 100644--- a/packages/fig/src/document/load-transaction.ts+++ b/packages/fig/src/document/load-transaction.ts@@ -25,6 +25,7 @@ export function loadPageTransaction(const components = new Map(state.components)const componentIds = new Map(state.componentIds)const sizes = new Set(state.savedSizeNodes)+ const nextImportedId = state.nextImportedIdgraph.withBufferedEvents(() => {try {action()@@ -47,6 +48,7 @@ export function loadPageTransaction(state.components = componentsstate.componentIds = componentIdsstate.savedSizeNodes = sizes+ state.nextImportedId = nextImportedIdfor (const [id, entries] of graph.instanceIndex)if (!entries.size) graph.instanceIndex.delete(id)graph.clearAbsPosCache()diff --git a/packages/fig/src/document/materialize.ts b/packages/fig/src/document/materialize.tsindex 049bdcee1..5707b83ef 100644--- a/packages/fig/src/document/materialize.ts+++ b/packages/fig/src/document/materialize.ts@@ -1,5 +1,5 @@import type { NodeChange } from '@open-pencil/kiwi/fig/codec'-import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'+import { generateId, SceneGraph, type SceneNode } from '@open-pencil/scene-graph'import {reconcileLiveComponentEdits,@@ -28,6 +28,7 @@ import {type ComponentCheckpoint} from './component/checkpoint'import { linkComponentPropertyValues, resolveVariantPropertyValues } from './component/values'+import type { ComponentConstruction } from './components'import { loadPageTransaction } from './load-transaction'import { applyDocumentMetadata } from './metadata'import { createArchiveDocumentReader, createDocumentReader } from './read'@@ -47,18 +48,22 @@ export function materializeDocument(changes: readonly NodeChange[],blobs: Uint8Array[] = [],options: DocumentAssemblyOptions = {}-) {+): AssemblyState {return materializeReader(createDocumentReader(changes, options.pageIds), blobs, options)}/** Own parsed archive records; do not create a second full source tree. */-export function materializeFigArchive(bytes: ArrayBuffer, options: DocumentAssemblyOptions = {}) {+export function materializeFigArchive(+ bytes: ArrayBuffer,+ options: DocumentAssemblyOptions = {}+): AssemblyState {const { reader, blobs, images } = createArchiveDocumentReader(bytes, options.pageIds)return materializeReader(reader, blobs, { ...options, images: options.images ?? new Map(images) })}export interface AssemblyState {graph: SceneGraph+ nextImportedId: numbersources: Map<string, string>components: Map<string, MaterializedComponentOccurrence>componentIds: Map<string, string>@@ -68,6 +73,8 @@ export interface AssemblyState {}export interface FigSessionCheckpoint {+ /** Continuation of imported runtime handles, including handles consumed then deleted. */+ nextImportedId?: numbersources: Array<[string, string]>componentIds: Array<[string, string]>savedSizeNodeIds: string[]@@ -116,6 +123,7 @@ function restoreAssemblyState(}return {graph,+ nextImportedId: checkpoint.nextImportedId ?? inferNextImportedId(graph),components,sources: new Map(checkpoint.sources),componentIds: new Map(checkpoint.componentIds),@@ -130,7 +138,7 @@ export function createFigDocumentSession() {const archive = createArchiveDocumentReader(bytes, new Set())const sessionOptions = { ...options, images: options.images ?? new Map(archive.images) }- const state = resume+ const state: AssemblyState = resume? restoreAssemblyState(resume, archive.reader, sessionOptions): materializeReader(archive.reader, archive.blobs, sessionOptions)state.graph.figKiwiVersion = archive.figKiwiVersion@@ -140,6 +148,7 @@ export function createFigDocumentSession(return {checkpoint(): FigSessionCheckpoint {return structuredClone({+ nextImportedId: state.nextImportedId,sources: [...state.sources],componentIds: [...state.componentIds],savedSizeNodeIds: [...state.savedSizeNodes],@@ -193,13 +202,24 @@ function createAssemblyState(reader: ReturnType<typeof createDocumentReader>,options: DocumentAssemblyOptions): AssemblyState {- const graph = new SceneGraph()+ // Imported runtime handles remain reproducible for CLI inspection and patches. Authored+ // entities use the production allocator even when created in a previously imported graph.+ let initializing = true+ let nextImportedId = 1+ const graph: SceneGraph = new SceneGraph(() =>+ initializing ? `0:${nextImportedId++}` : generateId()+ )+ initializing = falseapplyDocumentMetadata(graph, reader.documentRecord)for (const [hash, bytes] of options.images ?? []) graph.images.set(hash, bytes.slice())- materializeVariableResources(graph, reader.resources, options.onUnsupportedResource)+ graph.applyImportedStateDuring(+ () => materializeVariableResources(graph, reader.resources, options.onUnsupportedResource),+ () => `0:${nextImportedId++}`+ )for (const page of graph.getPages()) graph.deleteNode(page.id)return {graph,+ nextImportedId,sources: new Map(),components: new Map(),componentIds: new Map(),@@ -207,6 +227,24 @@ function createAssemblyState(}}+/** Compatibility with checkpoints saved before they carried the import counter. */+function inferNextImportedId(graph: SceneGraph): number {+ let next = 3+ const ids = [+ ...graph.nodes.keys(),+ ...graph.variables.keys(),+ ...graph.variableCollections.keys(),+ ...[...graph.variableCollections.values()].flatMap((collection) =>+ collection.modes.map((mode) => mode.modeId)+ )+ ]+ for (const id of ids) {+ if (!/^0:\d+$/.test(id)) continue+ next = Math.max(next, Number(id.slice(2)) + 1)+ }+ return next+}+/*** Syncing a resumed load's new instances copies their component's sizes over the sizes Figma* derived for them, such as a field filling its resized instance. Puts the derived sizes back,@@ -237,7 +275,7 @@ function materializeReader(blobs: Uint8Array[],options: DocumentAssemblyOptions,previous?: AssemblyState-) {+): AssemblyState {for (const diagnostic of reader.bindingDiagnostics) {if (!options.onUnresolvedBinding)throw new Error(`Unresolved binding ${diagnostic.sourceId}: ${diagnostic.field}`)@@ -246,6 +284,19 @@ function materializeReader(const pages = reader.pages.map((page) => reader.readPage(page.id, options))const plan = reader.planComponents(pages, options)const state = previous ?? createAssemblyState(reader, options)+ return state.graph.applyImportedStateDuring(+ () => materializeReaderInto(pages, plan, blobs, state, previous !== undefined),+ () => `0:${state.nextImportedId++}`+ )+}++function materializeReaderInto(+ pages: InstanceOccurrence[],+ plan: ComponentConstruction[],+ blobs: Uint8Array[],+ state: AssemblyState,+ resumed: boolean+): AssemblyState {const { graph, sources, components, savedSizeNodes, componentIds } = stateconst existingNodeIds = new Set(graph.nodes.keys())const layoutScales = new Map<string, number>()@@ -311,7 +362,7 @@ function materializeReader(if (!parentId) throw new Error(`Missing source container ${occurrence.sourceId}`)const ordered: string[] = []for (const child of occurrence.children) {- if (previous) reconcileOccurrenceStructure(child, graph, components)+ if (resumed) reconcileOccurrenceStructure(child, graph, components)if (child.mainComponentId !== null && !sources.has(child.sourceId)) {const materialized = materializeInstance(graph, parentId, child, componentIds, {blobs,@@ -319,7 +370,7 @@ function materializeReader(})rememberDerivedSizes(materialized.nodes)linkInstanceSourceChildren(child, materialized, components)- if (previous) {+ if (resumed) {reconcileLiveComponentEdits(graph, materialized)if (materialized.root.componentId) resync.add(materialized.root.id)}diff --git a/packages/fig/src/record-patch.ts b/packages/fig/src/record-patch.tsindex 545cb8885..6ee4a4907 100644--- a/packages/fig/src/record-patch.ts+++ b/packages/fig/src/record-patch.ts@@ -31,6 +31,8 @@ export interface FigRecordPatch {/** Archive facts a patch is built against: where new blob indices and new GUIDs start. */export interface FigArchiveRecordInfo {+ /** Record identities on every page, including pages not materialized in the graph. */+ recordIds: string[]blobCount: number/** Above every local ID the archive uses with session 0 or 1, the sessions new GUIDs take. */nextLocalId: number@@ -84,6 +86,9 @@ export function figArchiveRecordInfo(archive: {imageHashes: readonly string[]}): FigArchiveRecordInfo {return {+ recordIds: archive.records.flatMap((record) =>+ record.guid ? [guidToString(record.guid)] : []+ ),blobCount: archive.blobCount,nextLocalId: highestLocalId(archive.records) + 1,imageHashes: [...archive.imageHashes],diff --git a/packages/fig/tests/document/load-transaction.test.ts b/packages/fig/tests/document/load-transaction.test.tsindex 1b986cc49..7852a164c 100644--- a/packages/fig/tests/document/load-transaction.test.ts+++ b/packages/fig/tests/document/load-transaction.test.ts@@ -14,6 +14,7 @@ test('failed page mutation restores changed existing instance indexes and objectif (!instance) throw new Error('Missing instance')const state: AssemblyState = {graph,+ nextImportedId: 10,sources: new Map([['instance', instance.id]]),components: new Map(),componentIds: new Map(),@@ -37,6 +38,7 @@ test('failed page mutation restores changed existing instance indexes and objectexternalPreferredKeys: new Set()},() => {+ state.nextImportedId++state.sources.set('partial', instance.id)state.componentIds.set('partial', b.id)state.savedSizeNodes.add(instance.id)@@ -55,4 +57,5 @@ test('failed page mutation restores changed existing instance indexes and objectexpect(state.savedSizeNodes.has(instance.id)).toBe(false)expect(graph.getChildren(page.id)).toHaveLength(3)expect(events).toBe(0)+ expect(state.nextImportedId).toBe(10)})diff --git a/packages/fig/tests/document/record-headers.test.ts b/packages/fig/tests/document/record-headers.test.tsindex 19a7511bf..c1b7bbce9 100644--- a/packages/fig/tests/document/record-headers.test.ts+++ b/packages/fig/tests/document/record-headers.test.ts@@ -65,7 +65,7 @@ test('an archive reader with record headers builds the document records decodedconst parsed = parseFigBuffer(bytes.slice(0))const options = { derivedBounds: true, onUnresolvedProperty: () => undefined }- setIdSession(TEST_SESSION)+ const previousSession = setIdSession(TEST_SESSION)try {const whole = materializeDocument(parsed.nodeChanges, parsed.blobs, {...options,@@ -75,7 +75,7 @@ test('an archive reader with record headers builds the document records decodedexpect(canonical(lazy.graph)).toBe(canonical(whole.graph))} finally {- setIdSession(0)+ setIdSession(previousSession)}})diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex a5d4db9cb..7e1ebfe43 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -91,6 +91,7 @@ import * as Instances from './instances'import Matrix, { type Mat3 } from './matrix'import { CONTAINER_TYPES, createDefaultNode } from './node-defaults'import { updateNodePreview, type NodePreviewObserver } from './preview'+import { randomIndex } from './random'import { styleDetachmentChanges } from './shared-styles'import { markSourceFieldsEdited } from './source-metadata'import { GLYPH_AFFECTING_KEYS, invalidateTextCaches, TEXT_PICTURE_KEYS } from './text/picture'@@ -135,20 +136,30 @@ export {/** Figma reads both parts of a GUID as signed 32-bit integers and drops records beyond them. */const MAX_ID_SESSION = 0x7fffffff-let idSession = 0+/** Sessions 0 and 1 hold FIG's document and internal-resource records and counter GUIDs. */+const FIRST_RANDOM_SESSION = 2++/** A random session, as Yjs picks each document's `clientID`, so processes never share IDs. */+function randomIdSession(): number {+ return FIRST_RANDOM_SESSION + randomIndex(MAX_ID_SESSION - FIRST_RANDOM_SESSION + 1)+}++let idSession = randomIdSession()let nextLocalID = 1/*** Sets the session part of the IDs this process mints, as in Figma's `sessionID:localID` GUIDs.- * Headless tools keep session 0, so a file's layers get the same IDs on every run. The editor- * picks a random session at startup, as Yjs picks each document's `clientID`, so peers editing- * one shared room never mint the same ID. Call it before creating any graph.+ * Every process starts in a random session, so layers that the editor, the CLI, or MCP add to+ * copies of one file never share IDs. Tests and fixtures that need the same IDs on every run+ * set a fixed session or give the graph its own generator. Returns the previous session.*/-export function setIdSession(sessionId: number): void {+export function setIdSession(sessionId: number): number {if (!Number.isInteger(sessionId) || sessionId < 0 || sessionId > MAX_ID_SESSION) {throw new RangeError('sessionId must be a non-negative 31-bit integer')}+ const previous = idSessionidSession = sessionId+ return previous}export function generateId(): string {@@ -187,6 +198,7 @@ export class SceneGraph {private readonly changeObservers = new Set<NodeChangeObserver>()private sourceMetadataPreservationDepth = 0private importedStateApplicationDepth = 0+ private importedIdGenerator: (() => string) | undefinedprivate layoutMutationDepth = 0private derivedLayoutDepth = 0positionPreviewVersion = 0@@ -466,7 +478,7 @@ export class SceneGraph {private generateEntityId(issued?: Set<string>): string {let limit = Infinityfor (let attempt = 0; attempt < limit; attempt++) {- const id = this.idGenerator()+ const id = (this.importedIdGenerator ?? this.idGenerator)()if (this.isEntityIdTaken(id) || issued?.has(id)) {if (limit === Infinity) limit = this.entityIdCount() + (issued?.size ?? 0) + 1continue@@ -582,10 +594,10 @@ export class SceneGraph {this.previewMutationDepth--}}- preserveSourceMetadataDuring(fn: () => void): void {+ preserveSourceMetadataDuring<T>(fn: () => T): T {this.sourceMetadataPreservationDepth++try {- fn()+ return fn()} finally {this.sourceMetadataPreservationDepth--}@@ -594,12 +606,15 @@ export class SceneGraph {return this.sourceMetadataPreservationDepth > 0}- applyImportedStateDuring(fn: () => void): void {+ applyImportedStateDuring<T>(fn: () => T, idGenerator?: () => string): T {+ const previousGenerator = this.importedIdGenerator+ this.importedIdGenerator = idGenerator ?? previousGeneratorthis.importedStateApplicationDepth++try {- this.preserveSourceMetadataDuring(fn)+ return this.preserveSourceMetadataDuring(fn)} finally {this.importedStateApplicationDepth--+ this.importedIdGenerator = previousGenerator}}diff --git a/packages/scene-graph/tests/basic/graph.test.ts b/packages/scene-graph/tests/basic/graph.test.tsindex f40608c6f..3690d73ad 100644--- a/packages/scene-graph/tests/basic/graph.test.ts+++ b/packages/scene-graph/tests/basic/graph.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from 'bun:test'-import { generateId, SceneGraph } from '@open-pencil/scene-graph'+import { SceneGraph } from '@open-pencil/scene-graph'import { expectDefined, getNodeOrThrow } from '../helpers/assert'import { pageId, rect } from './helpers'@@ -17,10 +17,10 @@ describe('SceneGraph', () => {})test('create node skips imported ids that collide with the local generator', () => {- const graph = new SceneGraph()+ let nextId = 1+ const graph = new SceneGraph(() => `0:${nextId++}`)const page = pageId(graph)- const probe = generateId()- const nextLocalId = `0:${Number(probe.split(':')[1]) + 1}`+ const nextLocalId = `0:${nextId}`const imported = graph.createNode('RECTANGLE', page, {id: nextLocalId,name: 'Imported node'diff --git a/packages/scene-graph/tests/basic/id-generator.test.ts b/packages/scene-graph/tests/basic/id-generator.test.tsindex 83752d21c..75144f321 100644--- a/packages/scene-graph/tests/basic/id-generator.test.ts+++ b/packages/scene-graph/tests/basic/id-generator.test.ts@@ -10,6 +10,27 @@ function sequence(prefix: string): () => string {}describe('SceneGraph ID generator', () => {+ test('scopes imported allocation through nested work and restores authoring after errors', () => {+ const graph = new SceneGraph(sequence('7'))+ const page = pageId(graph)+ const imported = sequence('12')+ expect(() =>+ graph.applyImportedStateDuring(() => {+ expect(graph.createNode('RECTANGLE', page).id).toBe('12:1')+ graph.applyImportedStateDuring(() => {+ expect(graph.createNode('RECTANGLE', page).id).toBe('12:2')+ })+ graph.applyImportedStateDuring(() => {+ expect(graph.createNode('RECTANGLE', page).id).toBe('13:1')+ }, sequence('13'))+ expect(graph.createNode('RECTANGLE', page).id).toBe('12:3')+ throw new Error('Interrupted import')+ }, imported)+ ).toThrow('Interrupted import')+ expect(graph.isApplyingImportedState).toBe(false)+ expect(graph.createNode('RECTANGLE', page).id).toBe('7:3')+ })+test('uses an injected generator for the root, pages, nodes, variables, and collections', () => {const graph = new SceneGraph(sequence('7'))@@ -55,25 +76,25 @@ describe('SceneGraph ID generator', () => {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)]+ test('the default generator counts up in one random session outside the reserved sessions', () => {+ const graph = new SceneGraph()+ const [root, page] = [graph.rootId, pageId(graph)].map((id) => id.split(':').map(Number))- for (const id of ids) expect(id).toMatch(/^0:\d+$/)- expect(new Set(ids).size).toBe(ids.length)+ expect(root[0]).toBeGreaterThanOrEqual(2)+ expect(root[0]).toBeLessThan(2 ** 31)+ expect(page).toEqual([root[0], root[1] + 1])})test('the ID session prefixes every ID minted afterwards', () => {+ const previous = setIdSession(2_000_000_000)try {- setIdSession(2_000_000_000)const graph = new SceneGraph()const ids = [graph.rootId, pageId(graph), graph.createCollection('Colors').id]for (const id of ids) expect(id).toMatch(/^2000000000:\d+$/)} finally {- setIdSession(0)+ setIdSession(previous)}- expect(new SceneGraph().rootId).toMatch(/^0:\d+$/)+ expect(new SceneGraph().rootId).toMatch(new RegExp(`^${previous}:\\d+$`))})// Figma reads GUID parts as signed 32-bit integers and drops a paste with larger ones.diff --git a/src/boot.ts b/src/boot.tsindex d051ef9d7..4e399c6a0 100644--- a/src/boot.ts+++ b/src/boot.ts@@ -1,8 +1,6 @@import { createHead } from '@unhead/vue/client'import { createApp, nextTick } from 'vue'-import { setIdSession } from '@open-pencil/scene-graph'-import { randomInt } from '@open-pencil/scene-graph/random'import { createRetainedScopePlugin } from '@open-pencil/vue'import './app.css'@@ -21,8 +19,6 @@ import router from './router'* evaluates the app bundle and can still show the gate's guidance.*/export async function boot(): Promise<void> {- // A session of its own, so layers this window creates never share IDs with a collaborator's.- setIdSession(randomInt() >>> 1)preloadFonts()const head = createHead()const app = createApp(App)