AI-native design editor. Open-source Figma alternative.
fix(tools): make batch_update all-or-nothing (#1656)
Chavaaa3ef545487a9e
diff --git a/changes/1656/changed.md b/changes/1656/changed.mdnew file mode 100644index 000000000..67eec60a4--- /dev/null+++ b/changes/1656/changed.md@@ -0,0 +1 @@+- `batch_update` applies all of its operations or none: a missing layer, a wrong value, or an unknown prop now fails the whole call and leaves the document unchanged, where it used to apply the rest and list errors (#1651).diff --git a/packages/core/src/tools/structure/batch.ts b/packages/core/src/tools/structure/batch.tsindex c3cebc656..74fb8db44 100644--- a/packages/core/src/tools/structure/batch.ts+++ b/packages/core/src/tools/structure/batch.ts@@ -2,109 +2,81 @@ import * as v from 'valibot'import type { FigmaNodeProxy } from '#core/figma-api'import { textFonts } from '#core/tools/modify/text'-import { defineTool } from '#core/tools/schema'+import { defineTool, nodeNotFound, toolNumber } from '#core/tools/schema'-const batchOpsSchema = v.array(- v.object({ id: v.string(), props: v.record(v.string(), v.unknown()) })+const nonNegative = () => toolNumber(v.pipe(v.number(), v.minValue(0)))++/** Every prop an operation may set; anything else rejects the whole batch. */+const batchPropsSchema = v.strictObject({+ spacing: v.optional(nonNegative()),+ padding: v.optional(nonNegative()),+ padding_horizontal: v.optional(nonNegative()),+ padding_vertical: v.optional(nonNegative()),+ align: v.optional(v.picklist(['MIN', 'CENTER', 'MAX', 'SPACE_BETWEEN'])),+ counter_align: v.optional(v.picklist(['MIN', 'CENTER', 'MAX', 'STRETCH'])),+ sizing_horizontal: v.optional(v.picklist(['FIXED', 'HUG', 'FILL'])),+ sizing_vertical: v.optional(v.picklist(['FIXED', 'HUG', 'FILL'])),+ grow: v.optional(nonNegative()),+ name: v.optional(v.string()),+ visible: v.optional(v.boolean()),+ corner_radius: v.optional(nonNegative()),+ opacity: v.optional(toolNumber(v.pipe(v.number(), v.minValue(0), v.maxValue(1)))),+ auto_resize: v.optional(v.picklist(['NONE', 'WIDTH_AND_HEIGHT', 'HEIGHT', 'TRUNCATE'])),+ direction: v.optional(v.picklist(['HORIZONTAL', 'VERTICAL']))+})+type BatchProps = v.InferOutput<typeof batchPropsSchema>++const batchOpsSchema = v.pipe(+ v.string(),+ v.parseJson(),+ v.array(v.strictObject({ id: v.string(), props: batchPropsSchema })))type BatchOp = v.InferOutput<typeof batchOpsSchema>[number]-/** The operations a call names, or why they cannot be read. */+/** The operations a call names, or every problem with them. */function parseOperations(operations: string): BatchOp[] | { error: string } {- const json = v.safeParse(v.pipe(v.string(), v.parseJson()), operations)- if (!json.success) return { error: 'Invalid JSON in operations' }- const ops = v.safeParse(batchOpsSchema, json.output)- if (!ops.success) return { error: 'operations must be a JSON array of {id, props}' }- return ops.output-}--function str(value: unknown): string {- return typeof value === 'string' ? value : ''-}--function num(value: unknown): number {- return typeof value === 'number' ? value : 0+ const result = v.safeParse(batchOpsSchema, operations)+ if (result.success) return result.output+ return { error: `Invalid operations:\n${v.summarize(result.issues)}` }}-function applyBatchProps(node: FigmaNodeProxy, props: Record<string, unknown>): string[] {- const updated: string[] = []-- if (props.spacing !== undefined) {- node.itemSpacing = num(props.spacing)- updated.push('spacing')- }+function applyBatchProps(node: FigmaNodeProxy, props: BatchProps): void {+ if (props.spacing !== undefined) node.itemSpacing = props.spacingif (props.padding !== undefined) {- const value = num(props.padding)- node.paddingTop = value- node.paddingRight = value- node.paddingBottom = value- node.paddingLeft = value- updated.push('padding')+ node.paddingTop = props.padding+ node.paddingRight = props.padding+ node.paddingBottom = props.padding+ node.paddingLeft = props.padding}if (props.padding_horizontal !== undefined) {- node.paddingLeft = num(props.padding_horizontal)- node.paddingRight = num(props.padding_horizontal)- updated.push('padding_horizontal')+ node.paddingLeft = props.padding_horizontal+ node.paddingRight = props.padding_horizontal}if (props.padding_vertical !== undefined) {- node.paddingTop = num(props.padding_vertical)- node.paddingBottom = num(props.padding_vertical)- updated.push('padding_vertical')- }- if (props.counter_align !== undefined) {- node.counterAxisAlignItems = str(props.counter_align)- updated.push('counter_align')- }- if (props.align !== undefined) {- node.primaryAxisAlignItems = str(props.align)- updated.push('align')- }- if (props.sizing_horizontal !== undefined) {- node.layoutSizingHorizontal = str(props.sizing_horizontal)- updated.push('sizing_horizontal')- }- if (props.sizing_vertical !== undefined) {- node.layoutSizingVertical = str(props.sizing_vertical)- updated.push('sizing_vertical')- }- if (props.grow !== undefined) {- node.layoutGrow = num(props.grow)- updated.push('grow')- }- if (props.name !== undefined) {- node.name = str(props.name)- updated.push('name')- }- if (props.visible !== undefined) {- node.visible = Boolean(props.visible)- updated.push('visible')- }- if (props.corner_radius !== undefined) {- node.cornerRadius = num(props.corner_radius)- updated.push('corner_radius')- }- if (props.opacity !== undefined) {- node.opacity = num(props.opacity)- updated.push('opacity')- }- if (props.auto_resize !== undefined) {- node.textAutoResize = str(props.auto_resize)- updated.push('auto_resize')- }- if (props.direction !== undefined) {- node.layoutMode = str(props.direction) as 'HORIZONTAL' | 'VERTICAL'- updated.push('direction')- }-- return updated+ node.paddingTop = props.padding_vertical+ node.paddingBottom = props.padding_vertical+ }+ if (props.align !== undefined) node.primaryAxisAlignItems = props.align+ if (props.counter_align !== undefined) node.counterAxisAlignItems = props.counter_align+ if (props.sizing_horizontal !== undefined) node.layoutSizingHorizontal = props.sizing_horizontal+ if (props.sizing_vertical !== undefined) node.layoutSizingVertical = props.sizing_vertical+ if (props.grow !== undefined) node.layoutGrow = props.grow+ if (props.name !== undefined) node.name = props.name+ if (props.visible !== undefined) node.visible = props.visible+ if (props.corner_radius !== undefined) node.cornerRadius = props.corner_radius+ if (props.opacity !== undefined) node.opacity = props.opacity+ if (props.auto_resize !== undefined) node.textAutoResize = props.auto_resize+ if (props.direction !== undefined) node.layoutMode = props.direction}export const batchUpdate = defineTool({name: 'batch_update',description:- 'Execute multiple modifications in one call. Each operation is {id, props} where props can include: spacing, padding, padding_horizontal, padding_vertical, counter_align, sizing_horizontal, sizing_vertical, grow, name, visible, corner_radius, auto_resize (for text), direction. Runs all updates with one layout recompute.',- execution: { kind: 'sync', mutation: 'document' },+ 'Execute multiple modifications in one call, all or nothing: if any operation names a missing node or an invalid prop, nothing changes. ' ++ `Each operation is {id, props} where props can include: ${Object.keys(batchPropsSchema.entries).join(', ')}. ` ++ 'Runs all updates with one layout recompute.',+ execution: { kind: 'sync', mutation: 'properties' },input: v.strictObject({operations: v.pipe(v.string(),@@ -123,22 +95,23 @@ export const batchUpdate = defineTool({const ops = parseOperations(operations)if (!Array.isArray(ops)) return ops- const results: Array<{ id: string; updated: string[] }> = []- const errors: string[] = []-+ // Find every layer before writing, so a missing one leaves the document untouched.+ const targets: Array<{ node: FigmaNodeProxy; props: BatchProps }> = []for (const op of ops) {const node = figma.getNodeById(op.id)- if (!node) {- errors.push(`Node "${op.id}" not found`)- continue- }- const updated = applyBatchProps(node, op.props)- if (updated.length > 0) results.push({ id: op.id, updated })+ if (!node) return nodeNotFound(op.id)+ targets.push({ node, props: op.props })+ }++ const results: Array<{ id: string; updated: string[] }> = []+ for (const { node, props } of targets) {+ applyBatchProps(node, props)+ const updated = Object.keys(props)+ if (updated.length > 0) results.push({ id: node.id, updated })}const out: Record<string, unknown> = { updated: results.length }if (results.length > 0) out.results = results- if (errors.length > 0) out.errors = errorsreturn out}})diff --git a/packages/core/tests/editor/history/atomic/contract.test.ts b/packages/core/tests/editor/history/atomic/contract.test.tsindex 4d32b748a..270e6ff90 100644--- a/packages/core/tests/editor/history/atomic/contract.test.ts+++ b/packages/core/tests/editor/history/atomic/contract.test.ts@@ -148,6 +148,12 @@ const ARGS: Record<string, (t: Targets, f: Fixture) => Record<string, unknown>>grow: 1,align_self: 'STRETCH'}),+ batch_update: (t) => ({+ operations: JSON.stringify([+ { id: t.frame, props: { direction: 'VERTICAL', spacing: 4, name: 'Batched' } },+ { id: t.rect, props: { opacity: 0.3, corner_radius: 5 } }+ ])+ }),update_node: (t) => ({id: t.placed,x: 5,diff --git a/packages/core/tests/tools/structure/batch.test.ts b/packages/core/tests/tools/structure/batch.test.tsnew file mode 100644index 000000000..c1611094e--- /dev/null+++ b/packages/core/tests/tools/structure/batch.test.ts@@ -0,0 +1,71 @@+import { describe, expect, test } from 'bun:test'++import { setup, tool } from '#core-tests/helpers/atomic-tool'++import { executeAtomicTool } from '@open-pencil/core'++const batchUpdate = tool('batch_update')++/** A batch that renames the rectangle and changes one prop of the layer named `id`. */+function batch(rectangleId: string, id: string, props: Record<string, unknown>): string {+ return JSON.stringify([+ { id: rectangleId, props: { name: 'Renamed', opacity: 0.5 } },+ { id, props }+ ])+}++describe('batch_update', () => {+ test('applies every operation as one undo step', () => {+ const { figma, editor, undo, rectangle } = setup()+ const other = figma.createRectangle()+ const operations = batch(rectangle.id, other.id, { visible: false, corner_radius: '4' })++ expect(executeAtomicTool(editor, figma, batchUpdate, { operations })).toEqual({+ updated: 2,+ results: [+ { id: rectangle.id, updated: ['name', 'opacity'] },+ { id: other.id, updated: ['visible', 'corner_radius'] }+ ]+ })+ expect([rectangle.name, rectangle.opacity, other.cornerRadius, other.visible]).toEqual([+ 'Renamed',+ 0.5,+ 4,+ false+ ])++ undo.undo()+ expect([rectangle.name, rectangle.opacity, other.cornerRadius, other.visible]).toEqual([+ 'Rectangle',+ 1,+ 0,+ true+ ])+ expect(undo.canUndo).toBe(false)+ })++ test.each([+ ['a missing layer', 'missing', {}, 'Node "missing" not found'],+ ['a value of the wrong type', 'self', { spacing: 'wide' }, 'at 1.props.spacing'],+ ['a value outside its options', 'self', { counter_align: 'middle' }, 'at 1.props.counter_align'],+ ['a prop it does not take', 'self', { fill: '#f00' }, 'at 1.props.fill']+ ])('changes nothing when one operation names %s', (_, target, props, message) => {+ const { figma, editor, undo, rectangle } = setup()+ const id = target === 'self' ? rectangle.id : target+ const operations = batch(rectangle.id, id, props)++ expect(() => executeAtomicTool(editor, figma, batchUpdate, { operations })).toThrow(message)+ expect([rectangle.name, rectangle.opacity]).toEqual(['Rectangle', 1])+ expect(undo.canUndo).toBe(false)+ })++ test('changes nothing when a headless call names a missing layer', () => {+ const { figma, rectangle } = setup()+ const operations = batch(rectangle.id, 'missing', {})++ expect(batchUpdate.execute(figma, { operations })).toEqual({+ error: 'Node "missing" not found'+ })+ expect([rectangle.name, rectangle.opacity]).toEqual(['Rectangle', 1])+ })+})