Skip to content

AI-native design editor. Open-source Figma alternative.

fix(tools): preserve atomic property state and validate inputs

Danila Poyarkovf25e3f72a236
diff --git a/packages/core/src/editor/history/atomic-tool.ts b/packages/core/src/editor/history/atomic-tool.ts
index a03b42fb8..7637e99f4 100644
--- a/packages/core/src/editor/history/atomic-tool.ts
+++ b/packages/core/src/editor/history/atomic-tool.ts
@@ -15,7 +15,12 @@ import { isAtomicTool, type ToolDef } from '#core/tools/schema'
const MAX_TRANSACTION_NODES = 10_000
type MutationEditor = Pick<Editor, 'graph' | 'runLayoutForNode' | 'requestRender' | 'pushUndoEntry'>
-type Changes<T> = { id: string; before: Partial<T>; after: Partial<T> }
+type Changes<T> = {
+ id: string
+ before: Partial<T>
+ after: Partial<T>
+ absent: Record<'before' | 'after', (keyof T)[]>
+}
function changes<T extends object>(before: Map<string, T>, after: Map<string, T>): Changes<T>[] {
const result: Changes<T>[] = []
@@ -24,13 +29,18 @@ function changes<T extends object>(before: Map<string, T>, after: Map<string, T>
if (!current) throw new Error('Atomic tools must not remove nodes or variables')
const inverse: Partial<T> = {}
const forward: Partial<T> = {}
+ const absent: Changes<T>['absent'] = { before: [], after: [] }
const keys = new Set([...Object.keys(previous), ...Object.keys(current)] as (keyof T)[])
for (const key of keys) {
- if (isEqual(previous[key], current[key])) continue
+ const existed = Object.hasOwn(previous, key)
+ const exists = Object.hasOwn(current, key)
+ if (existed === exists && isEqual(previous[key], current[key])) continue
inverse[key] = structuredClone(previous[key])
forward[key] = structuredClone(current[key])
+ if (!existed) absent.before.push(key)
+ if (!exists) absent.after.push(key)
}
- if (Object.keys(forward).length) result.push({ id, before: inverse, after: forward })
+ if (Object.keys(forward).length) result.push({ id, before: inverse, after: forward, absent })
}
if (before.size !== after.size) throw new Error('Atomic tools must not create nodes or variables')
return result
@@ -69,11 +79,18 @@ export function executeAtomicTool(
if (editor.graph !== graph) throw new Error('The target document has been replaced')
for (const change of variableChanges) {
const variable = graph.variables.get(change.id)
- if (variable) Object.assign(variable, structuredClone(change[direction]))
+ if (variable) {
+ Object.assign(variable, structuredClone(change[direction]))
+ for (const key of change.absent[direction]) Reflect.deleteProperty(variable, key)
+ }
}
graph.preserveSourceMetadataDuring(() => {
for (const change of nodeChanges)
- graph.updateNode(change.id, structuredClone(change[direction]))
+ graph.restoreNodeProperties(
+ change.id,
+ structuredClone(change[direction]),
+ change.absent[direction]
+ )
})
layout(
graph,
diff --git a/packages/core/src/tools/analyze/spacing.ts b/packages/core/src/tools/analyze/spacing.ts
index 94c69c6af..f71e01065 100644
--- a/packages/core/src/tools/analyze/spacing.ts
+++ b/packages/core/src/tools/analyze/spacing.ts
@@ -12,7 +12,13 @@ export const analyzeSpacing = defineTool({
exposure: { webmcp: true },
input: v.object({
grid: v.optional(
- toolNumber(v.pipe(v.number(), v.description('Base grid size to check against (default: 8)')))
+ toolNumber(
+ v.pipe(
+ v.number(),
+ v.gtValue(0),
+ v.description('Base grid size to check against (default: 8)')
+ )
+ )
)
}),
execute: (figma, args) => {
diff --git a/packages/core/src/tools/input.ts b/packages/core/src/tools/input.ts
index 629d15bd7..4d3d1b6d3 100644
--- a/packages/core/src/tools/input.ts
+++ b/packages/core/src/tools/input.ts
@@ -15,6 +15,7 @@ export function toolNumber(schema: v.GenericSchema<number, number> = v.number())
finite,
v.pipe(
v.string(),
+ v.regex(/\S/, 'Expected a nonblank numeric string'),
v.description(v.getDescription(schema) ?? 'Numeric value'),
v.transform(Number),
finite
diff --git a/packages/core/src/tools/modify/update.ts b/packages/core/src/tools/modify/update.ts
index 7e3c8206b..5fb1fde6b 100644
--- a/packages/core/src/tools/modify/update.ts
+++ b/packages/core/src/tools/modify/update.ts
@@ -39,7 +39,11 @@ export const updateNode = defineTool({
font_size: v.optional(
toolNumber(v.pipe(v.number(), v.minValue(1), v.description('Font size')))
),
- font_weight: v.optional(toolNumber(v.pipe(v.number(), v.description('Font weight (100-900)')))),
+ font_weight: v.optional(
+ toolNumber(
+ v.pipe(v.number(), v.minValue(100), v.maxValue(900), v.description('Font weight (100-900)'))
+ )
+ ),
name: v.optional(v.pipe(v.string(), v.description('Layer name')))
}),
execute: (figma, args) => {
diff --git a/packages/core/src/tools/read/components.ts b/packages/core/src/tools/read/components.ts
index 11d700fcb..ae5addb44 100644
--- a/packages/core/src/tools/read/components.ts
+++ b/packages/core/src/tools/read/components.ts
@@ -42,7 +42,11 @@ export const getComponents = defineTool({
library_id: v.optional(
v.pipe(v.string(), v.description('Filter library components by library ID'))
),
- limit: v.optional(toolNumber(v.pipe(v.number(), v.description('Max results (default: 50)'))))
+ limit: v.optional(
+ toolNumber(
+ v.pipe(v.number(), v.integer(), v.minValue(0), v.description('Max results (default: 50)'))
+ )
+ )
}),
execute: async (figma, args) => {
const limit = args.limit ?? 50
diff --git a/packages/core/src/tools/structure/arrange.ts b/packages/core/src/tools/structure/arrange.ts
index 1178eae27..1a236f85e 100644
--- a/packages/core/src/tools/structure/arrange.ts
+++ b/packages/core/src/tools/structure/arrange.ts
@@ -26,7 +26,14 @@ export const arrangeNodes = defineTool({
toolNumber(v.pipe(v.number(), v.description('Spacing between nodes (default: 40)')))
),
cols: v.optional(
- toolNumber(v.pipe(v.number(), v.description('Column count for grid mode (default: auto)')))
+ toolNumber(
+ v.pipe(
+ v.number(),
+ v.integer(),
+ v.minValue(1),
+ v.description('Column count for grid mode (default: auto)')
+ )
+ )
)
}),
execute: (figma, args) => {
diff --git a/packages/core/src/tools/structure/hierarchy.ts b/packages/core/src/tools/structure/hierarchy.ts
index c59998908..2b80c4093 100644
--- a/packages/core/src/tools/structure/hierarchy.ts
+++ b/packages/core/src/tools/structure/hierarchy.ts
@@ -27,7 +27,7 @@ export const groupNodes = defineTool({
description: 'Group selected nodes.',
execution: { kind: 'sync', mutation: 'document' },
input: v.object({
- ids: v.pipe(v.array(v.string()), v.minLength(1), v.description('Node IDs to group'))
+ ids: v.pipe(v.array(v.string()), v.minLength(2), v.description('Node IDs to group'))
}),
execute: (figma, { ids }) => {
const nodes = requireNodes(figma, ids)
diff --git a/packages/core/src/tools/vector/boolean.ts b/packages/core/src/tools/vector/boolean.ts
index 991d1c11f..d5411f008 100644
--- a/packages/core/src/tools/vector/boolean.ts
+++ b/packages/core/src/tools/vector/boolean.ts
@@ -8,7 +8,7 @@ export const booleanUnion = defineTool({
description: 'Union (combine) multiple nodes.',
execution: { kind: 'sync', mutation: 'document' },
input: v.object({
- ids: v.pipe(v.array(v.string()), v.minLength(1), v.description('Node IDs to union'))
+ ids: v.pipe(v.array(v.string()), v.minLength(2), v.description('Node IDs to union'))
}),
execute: (figma, { ids }) => {
const result = figma.booleanOperation('UNION', ids)
@@ -22,7 +22,7 @@ export const booleanSubtract = defineTool({
description: 'Subtract the second node from the first.',
execution: { kind: 'sync', mutation: 'document' },
input: v.object({
- ids: v.pipe(v.array(v.string()), v.minLength(1), v.description('Node IDs (first minus rest)'))
+ ids: v.pipe(v.array(v.string()), v.minLength(2), v.description('Node IDs (first minus rest)'))
}),
execute: (figma, { ids }) => {
const result = figma.booleanOperation('SUBTRACT', ids)
@@ -36,7 +36,7 @@ export const booleanIntersect = defineTool({
description: 'Intersect multiple nodes.',
execution: { kind: 'sync', mutation: 'document' },
input: v.object({
- ids: v.pipe(v.array(v.string()), v.minLength(1), v.description('Node IDs to intersect'))
+ ids: v.pipe(v.array(v.string()), v.minLength(2), v.description('Node IDs to intersect'))
}),
execute: (figma, { ids }) => {
const result = figma.booleanOperation('INTERSECT', ids)
@@ -50,7 +50,7 @@ export const booleanExclude = defineTool({
description: 'Exclude (XOR) multiple nodes.',
execution: { kind: 'sync', mutation: 'document' },
input: v.object({
- ids: v.pipe(v.array(v.string()), v.minLength(1), v.description('Node IDs to exclude'))
+ ids: v.pipe(v.array(v.string()), v.minLength(2), v.description('Node IDs to exclude'))
}),
execute: (figma, { ids }) => {
const result = figma.booleanOperation('EXCLUDE', ids)
diff --git a/packages/scene-graph/src/checkpoint.ts b/packages/scene-graph/src/checkpoint.ts
index 247da077d..2b2b89a81 100644
--- a/packages/scene-graph/src/checkpoint.ts
+++ b/packages/scene-graph/src/checkpoint.ts
@@ -58,6 +58,7 @@ export function captureGraphCheckpoint(graph: SceneGraph) {
if (
!isEqual(snapshot.variableCollections, graph.variableCollections) ||
!isEqual(snapshot.activeMode, graph.activeMode) ||
+ !isEqual(snapshot.instanceIndex, graph.instanceIndex) ||
!isEqual(snapshot.enabledLibraries, graph.enabledLibraries) ||
images.size !== graph.images.size ||
[...images].some(([id, bytes]) => graph.images.get(id) !== bytes) ||
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index 07e3d747a..0769a6561 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -430,6 +430,30 @@ export class SceneGraph {
const node = this.nodes.get(id)
if (!node) return
changes = stripUndefinedProps(styleDetachmentChanges(node, stripUndefinedProps(changes)))
+ this.applyNodeChanges(node, changes)
+ }
+
+ /** Replay captured properties without dropping explicit undefined values or absent keys. */
+ restoreNodeProperties(
+ id: string,
+ changes: Partial<SceneNode>,
+ absent: readonly (keyof SceneNode)[]
+ ): void {
+ const node = this.nodes.get(id)
+ if (node) this.applyNodeChanges(node, changes, absent)
+ }
+
+ private applyNodeChanges(
+ node: SceneNode,
+ changes: Partial<SceneNode>,
+ absent: readonly (keyof SceneNode)[] = []
+ ): void {
+ const { id } = node
+ // Include removed keys in cache invalidation and update notifications.
+ if (absent.length) {
+ changes = { ...changes }
+ for (const key of absent) Reflect.set(changes, key, undefined)
+ }
// Only clear absPosCache when layout-affecting properties change.
// Fills, strokes, effects, plugin data changes do NOT affect absolute position.
@@ -460,6 +484,7 @@ export class SceneGraph {
Object.assign(node, changes)
if (changes.fills) removeStaleBindings(node, 'fills', changes)
if (changes.strokes) removeStaleBindings(node, 'strokes', changes)
+ for (const key of absent) Reflect.deleteProperty(node, key)
this.emitter.emit('node:updated', id, changes)
}
diff --git a/tests/engine/editor/history/atomic-tools.test.ts b/tests/engine/editor/history/atomic-tools.test.ts
index 8baf10016..4dadfd320 100644
--- a/tests/engine/editor/history/atomic-tools.test.ts
+++ b/tests/engine/editor/history/atomic-tools.test.ts
@@ -93,6 +93,69 @@ describe('atomic agent tools', () => {
).toMatchObject({ r: 0, g: 1 })
})
+ test.each(['node', 'variable'] as const)('replays %s property presence exactly', (kind) => {
+ for (const before of ['absent', 'undefined', 'value'] as const) {
+ for (const after of ['absent', 'undefined', 'value'] as const) {
+ if (before === after) continue
+ const { graph, figma, editor, undo, rectangle, tool } = setup()
+ const collection = graph.createCollection('Test')
+ const variable = graph.createVariable('Test', 'STRING', collection.id, '')
+ const target = kind === 'node' ? graph.getNode(rectangle.id) : variable
+ if (!target) throw new Error('Missing target')
+ const key = kind === 'node' ? 'booleanOperation' : 'key'
+ const value = kind === 'node' ? 'UNION' : 'variable-key'
+ const set = (state: typeof before) => {
+ if (state === 'absent') Reflect.deleteProperty(target, key)
+ else Reflect.set(target, key, state === 'undefined' ? undefined : value)
+ }
+ const assertState = (state: typeof before) => {
+ expect(Object.hasOwn(target, key)).toBe(state !== 'absent')
+ expect(Reflect.get(target, key)).toBe(state === 'value' ? value : undefined)
+ }
+ set(before)
+ executeAtomicTool(
+ editor,
+ figma,
+ {
+ ...tool('set_opacity'),
+ execute: () => {
+ set(after)
+ }
+ },
+ {}
+ )
+ assertState(after)
+ expect(undo.canUndo).toBe(true)
+ undo.undo()
+ assertState(before)
+ undo.redo()
+ assertState(after)
+ }
+ }
+ })
+
+ test('rejects and restores instance index corruption even on reported success', () => {
+ const { graph, figma, editor, undo, tool } = setup()
+ const component = figma.createComponent()
+ const instance = component.createInstance()
+ const before = structuredClone(graph.instanceIndex)
+ expect(() =>
+ executeAtomicTool(
+ editor,
+ figma,
+ {
+ ...tool('set_opacity'),
+ execute: () => {
+ graph.instanceIndex.get(component.id)?.delete(instance.id)
+ }
+ },
+ {}
+ )
+ ).toThrow('Atomic tools must not change')
+ expect(graph.instanceIndex).toEqual(before)
+ expect(undo.canUndo).toBe(false)
+ })
+
test('partial failures roll back without adding history', () => {
const { figma, editor, undo, rectangle, tool } = setup()
const def: ToolDef = {
diff --git a/tests/engine/tools/input.test.ts b/tests/engine/tools/input.test.ts
index 20c8cfd31..2136db1be 100644
--- a/tests/engine/tools/input.test.ts
+++ b/tests/engine/tools/input.test.ts
@@ -11,17 +11,27 @@ import { getTool, setupToolTest } from '#tests/helpers/tools'
describe('native tool input contracts', () => {
const schema = v.object({ value: toolNumber(v.pipe(v.number(), v.minValue(0), v.maxValue(100))) })
- test.each([Infinity, -Infinity, Number.NaN, 'Infinity', '-Infinity', 'NaN', '1e999', 'abc'])(
- 'rejects non-finite or invalid numeric input %s',
- async (value) => {
- expect(v.safeParse(schema, { value }).success).toBe(false)
- const standard = toStandardJSONSchema(schema)
- expect((await standard['~standard'].validate({ value })).issues).toBeDefined()
- }
- )
+ test.each([
+ Infinity,
+ -Infinity,
+ Number.NaN,
+ 'Infinity',
+ '-Infinity',
+ 'NaN',
+ '1e999',
+ 'abc',
+ '',
+ ' ',
+ '\t\n'
+ ])('rejects non-finite or invalid numeric input %s', async (value) => {
+ expect(v.safeParse(schema, { value }).success).toBe(false)
+ const standard = toStandardJSONSchema(schema)
+ expect((await standard['~standard'].validate({ value })).issues).toBeDefined()
+ })
test('numeric strings share numeric bounds and output types', () => {
expect(v.parse(schema, { value: '42' })).toEqual({ value: 42 })
+ expect(v.parse(schema, { value: ' 42 ' })).toEqual({ value: 42 })
expect(v.safeParse(schema, { value: '101' }).success).toBe(false)
expect(v.safeParse(schema, { value: '-1' }).success).toBe(false)
})
@@ -42,9 +52,50 @@ describe('native tool input contracts', () => {
tool.execute(figma, { id: node.id, value: '0.5' })
expect(node.opacity).toBe(0.5)
expect(() => tool.execute(figma, { id: node.id, value: 'Infinity' })).toThrow()
+ expect(() => tool.execute(figma, { id: node.id, value: ' ' })).toThrow()
expect(node.opacity).toBe(0.5)
})
+ test.each([
+ { name: 'analyze_spacing', field: 'grid', invalid: [0, -1], valid: [0.5, 8] },
+ { name: 'arrange', field: 'cols', invalid: [0, -1, 1.5], valid: [1, 3] },
+ { name: 'get_components', field: 'limit', invalid: [-1, 1.5], valid: [0, 50] },
+ { name: 'update_node', field: 'font_weight', invalid: [99, 901], valid: [100, 900] }
+ ])('$name validates $field before execution', ({ name, field, invalid, valid }) => {
+ const input = getTool(name).input
+ for (const value of invalid) {
+ expect(v.safeParse(input, { id: 'node', [field]: value }).success).toBe(false)
+ expect(v.safeParse(input, { id: 'node', [field]: String(value) }).success).toBe(false)
+ }
+ for (const value of valid) {
+ expect(v.safeParse(input, { id: 'node', [field]: value }).success).toBe(true)
+ expect(v.safeParse(input, { id: 'node', [field]: String(value) }).success).toBe(true)
+ }
+ })
+
+ test.each([
+ 'group_nodes',
+ 'boolean_subtract',
+ 'boolean_union',
+ 'boolean_intersect',
+ 'boolean_exclude'
+ ])('%s advertises and enforces at least two operands', (name) => {
+ const input = getTool(name).input
+ expect(v.safeParse(input, { ids: ['one'] }).success).toBe(false)
+ expect(v.safeParse(input, { ids: ['one', 'two'] }).success).toBe(true)
+ const standard = toStandardJSONSchema(input)
+ expect(standard['~standard'].jsonSchema.input({ target: 'draft-07' })).toMatchObject({
+ properties: { ids: { minItems: 2 } }
+ })
+ })
+
+ test('font weight bounds also appear in the generated schema', () => {
+ const standard = toStandardJSONSchema(getTool('update_node').input)
+ expect(standard['~standard'].jsonSchema.input({ target: 'draft-07' })).toMatchObject({
+ properties: { font_weight: { anyOf: [{ minimum: 100, maximum: 900 }, { type: 'string' }] } }
+ })
+ })
+
test('defaults and enum aliases remain schema-owned', () => {
const tool = getTool('create_shape')
const args = v.parse(tool.input, { type: 'RECTANGLE', x: 0, y: 0, width: 10, height: 10 })