Constraining AI Mutations to Typed Canvas AST Operations
Language models excel at generating natural language but often hallucinate malformed JSON structures, invalid coordinate numbers, or dangling edge references when attempting to generate whole canvas states.
Risk: Corrupted board state, infinite render loops in the frontend canvas, or detached connectors floating in space.
Rather than asking the LLM to output entire canvas documents, the model is equipped with a strictly typed toolset: `createNode()`, `updateNode()`, `deleteNode()`, `createEdge()`, `deleteEdge()`, and `moveNode()`. Each tool argument is validated via a discriminated union Zod schema at runtime. If any operation references a nonexistent node or an illegal protocol, the pipeline rejects the batch and prompts the agent to rectify the operation.
✓ 100% syntactically valid canvas modifications with zero board corruption and zero dangling references across thousands of automated test runs.
import { z } from "zod"
export const CanvasNodeSchema = z.object({
id: z.string().uuid(),
type: z.enum(["service", "database", "gateway", "queue", "cache", "client"]),
label: z.string().min(1).max(64),
position: z.object({ x: z.number(), y: z.number() }),
metadata: z.record(z.string(), z.unknown()).default({}),
})
export const CanvasEdgeSchema = z.object({
id: z.string().uuid(),
source: z.string().uuid(),
target: z.string().uuid(),
protocol: z.enum(["http", "grpc", "ws", "sql", "amqp"]),
label: z.string().optional(),
})
export const CanvasOperationSchema = z.discriminatedUnion("action", [
z.object({ action: z.literal("createNode"), node: CanvasNodeSchema }),
z.object({
action: z.literal("updateNode"),
id: z.string().uuid(),
patch: CanvasNodeSchema.partial().omit({ id: true }),
}),
z.object({ action: z.literal("deleteNode"), id: z.string().uuid() }),
z.object({ action: z.literal("createEdge"), edge: CanvasEdgeSchema }),
z.object({ action: z.literal("deleteEdge"), id: z.string().uuid() }),
])
export type CanvasOperation = z.infer<typeof CanvasOperationSchema>Enforces strict type safety on every discrete operation emitted by the AI copilot before any mutation touches the whiteboard state.