Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
feat(v0.28): AI design intelligence & skills engine overhaul
Ashiq Hussain Mir47c4b1aa9ed5
diff --git a/.gitignore b/.gitignoreindex a936c21..354d7ae 100644--- a/.gitignore+++ b/.gitignore@@ -89,3 +89,4 @@ mini-services/# test artifacts/test-results//playwright-report/+corediff --git a/docs/AI-CAPABILITY-MATRIX.md b/docs/AI-CAPABILITY-MATRIX.mdnew file mode 100644index 0000000..51f2b6d--- /dev/null+++ b/docs/AI-CAPABILITY-MATRIX.md@@ -0,0 +1,127 @@+# Canvix AI Capability Matrix (v0.28 audit)++Generated 2026-11-23 by direct inspection of the implementation (store, design-actions,+add-element, panels, apps, API routes). This is the Phase 0 deliverable and the contract+for Phase 3: every row the matrix marks "gap" gets a tool in the capability bridge.++Legend — **Human**: usable through the editor UI · **AI v0.27**: reachable by the design+agent (`src/lib/agent/tools.ts`, 24 tools) · **AI v0.28**: after this overhaul.+A = adapter exists (validated `DesignAction` or store action), U = undoable (rides+history/collab), C = needs confirmation (destructive tier), ✅ = supported, ⚠️ = partial,+❌ = gap.++## Canvas and document operations++| Capability | Human | AI v0.27 | AI v0.28 | Adapter | Undo | Tests |+|---|---|---|---|---|---|---|+| Create/open/save/duplicate designs | ✅ | ❌ (out of panel scope) | ❌ (design mgmt stays user-side; agent edits the open document) | — | — | n/a |+| Change dimensions / aspect ratio (`resizeDesign`, magic re-layout) | ✅ | ❌ | ✅ `resize_design` | A | U | + |+| Add page | ✅ | ✅ `add_page` | ✅ | A | U | ✅ |+| Delete page | ✅ | ❌ | ✅ `delete_page` (destructive) | A | U | + |+| Duplicate page | ✅ | ✅ `duplicate_page` | ✅ | A | U | ✅ |+| Go to page | ✅ | ✅ `goto_page` (v0.27.3) | ✅ | A | — | ✅ |+| Page background (solid/gradient/angle) | ✅ | ✅ `set_background` | ✅ | A | U | ✅ |+| Page transition | ✅ | ❌ | ✅ `set_page_transition` | A | U | + |+| Page notes | ✅ | ❌ | ❌ (notes are presenter-side meta, not visual; documented out of scope) | — | — | — |+| Element position/size/rotation/opacity | ✅ | ✅ `update_elements` | ✅ (rotation/opacity/z now in patch whitelist) | A | U | ✅ |+| Scale elements (keeps aspect) | ✅ | ❌ (client action existed) | ✅ `scale_elements` | A | U | + |+| Zoom / viewport | ✅ | ❌ | ❌ (user's viewport is not the document; agent gets full state instead) | — | — | — |+| Grid / snap / rulers / guides | ✅ | ❌ | ❌ (view aids, not document state; agent aligns deterministically) | — | — | — |+| Selection | ✅ | read via context | read only (ids flow through tools) | — | — | ✅ |+| Group / ungroup | ✅ | ❌ | ✅ `group_elements` / `ungroup_elements` | A | U | + |+| Layer order (front/back/up/down, reorder) | ✅ | ❌ | ✅ `reorder_layers` | A | U | + |+| Lock / visibility | ✅ | ❌ | ✅ `update_elements` patch (locked/visible) | A | U | + |+| Duplicate selection | ✅ | ❌ | ✅ `duplicate_elements` | A | U | + |+| Undo / redo | ✅ | per-action + "Undo agent work" | ✅ (unchanged) | A | U | ✅ |+| Versions (save/restore) | ✅ | ❌ | ❌ (version history is a user-controlled safety net; agent never rewrites history) | — | — | — |++## Typography++| Capability | Human | AI v0.27 | AI v0.28 | Adapter | Undo |+|---|---|---|---|---|---|+| Add/edit text | ✅ | ✅ `add_text` / `update_elements` | ✅ | A | U |+| Font family (catalog-validated) | ✅ | ✅ `set_font` | ✅ | A | U |+| Size / bold / italic / underline / strike / uppercase | ✅ | ⚠️ (partial patch) | ✅ full patch whitelist | A | U |+| Letter spacing / line height | ✅ | ❌ | ✅ patch keys | A | U |+| Alignment (left/center/right) | ✅ | ⚠️ | ✅ | A | U |+| Text color / gradient fill | ✅ | ⚠️ (solid only) | ✅ (fillGradient patch) | A | U |+| Curved text (arc −180..180) | ✅ | ❌ | ✅ `curve` patch | A | U |+| Rich-text spans (per-run style, links) | ✅ | ❌ | ✅ `set_text_spans` (validated against text equality) | A | U |+| List style (bullet/number) + RTL direction | ✅ | ❌ | ✅ patch keys | A | U |+| Text effects (background block, presets) | ✅ | ❌ | ✅ patch keys | A | U |+| Auto-fit | ✅ | ❌ | ✅ patch + auto shrink via `measure_text` guidance | A | U |+| Text measurement (real metrics) | — | ❌ (0.6×char estimate) | ✅ `measure_text` tool (client canvas measureText — the same fn the renderer uses) | A | — |+| Headings/body color shortcuts | ✅ | ✅ `set_text_style`, `recolor` | ✅ | A | U |++## Graphics and styling++| Capability | Human | AI v0.27 | AI v0.28 | Adapter | Undo |+|---|---|---|---|---|---|+| Shapes: rect/ellipse/triangle/star/polygon/path | ✅ | ⚠️ (5 kinds, no params) | ✅ + sides/points/innerRatio, path | A | U |+| Line: solid/dashed/arrows | ✅ | ❌ | ✅ `add_line` | A | U |+| Fill: solid + gradient | ✅ | ⚠️ (background only) | ✅ element `fillGradient` patch | A | U |+| Stroke color/width, corner radius | ✅ | ❌ | ✅ patch keys | A | U |+| Shadows | ✅ | ❌ | ✅ patch `shadow` (validated shape) | A | U |+| Opacity | ✅ | ⚠️ | ✅ | A | U |+| Flip H/V (images) | ✅ | ❌ | ✅ patch keys | A | U |+| Frames + fill-frame with image | ✅ | ❌ | ✅ `add_frame` + `fill_frame` | A | U |+| Masks (shape masks on images, parametric) | ✅ | ❌ | ✅ `mask_image` | A | U |+| Image adjustments (brightness/contrast/saturation) + filter presets | ✅ | ❌ | ✅ `adjust_image` | A | U |+| Stickers (emoji + vector pack) | ✅ | ✅ (emoji) | ✅ + vector pack ids | A | U |+| Icons (path pack, searchable) | ✅ | ❌ | ✅ `add_icon` (server-side search of the same pack) | A | U |+| Illustrations (SVG library) | ✅ | ❌ | ✅ `add_illustration` | A | U |+| Graphics (decorative shapes) | ✅ | ❌ | ✅ `add_graphic` | A | U |+| Background removal / upscale / inpaint | ✅ (ImageAI panel) | ❌ | ✅ `edit_image` (routes to the existing image-edit providers; only on elements with `aiEntId`) | A | U |++## Images and media++| Capability | Human | AI v0.27 | AI v0.28 | Adapter | Undo |+|---|---|---|---|---|---|+| Upload/insert image | ✅ | ❌ (server can't upload) | ⚠️ `add_image` data-URL + stock + generated cover the agent's real needs; file upload stays user-side | A | U |+| AI image generation | ✅ | ✅ `add_image` | ✅ | A | U |+| Stock photo search (licensed, credited) | ✅ | ✅ `add_stock_photo` (v0.27.3) | ✅ | A | U |+| Stock video | ✅ | ❌ | ✅ `add_stock_video` | A | U |+| Audio / SFX / voiceover | ✅ | ❌ | ⚠️ `add_sfx` (pack sounds, offline) — full audio library stays user-side (file workflows) | A | U |+| Animations per element | ✅ | ❌ | ✅ `animate_elements` (kind/speed/delay/easing/direction) | A | U |+| Magic Animate page | ✅ | ✅ `animate_page` | ✅ | A | U |+| Beat pulse | ✅ | ❌ | ❌ (needs audio analysis timing — out of agent scope this wave) | — | — |++## Advanced features++| Capability | Human | AI v0.27 | AI v0.28 | Adapter | Undo |+|---|---|---|---|---|---|+| Tables (header/rows) | ✅ | ✅ `add_table` | ✅ | A | U |+| Charts (bar/line/donut/scatter, data-bound) | ✅ | ❌ | ✅ `add_chart` (series, palette) | A | U |+| QR codes | ✅ | ❌ | ✅ `add_qr` (value, size, colors) | A | U |+| Embeds (URL) | ✅ | ❌ | ✅ `add_embed` | A | U |+| Templates (apply to page, smart fields) | ✅ | ❌ | ✅ `list_templates` + `apply_template` (with field fill) | A | U |+| Brand kit (set colors/fonts; read in context) | ✅ | read only | ✅ `set_brand_kit` + read | A | U |+| Multi-page consistency | ✅ | ❌ | ✅ (goto_page + tools + brand skill) | A | U |+| Translation | ✅ | ✅ `translate_texts` | ✅ | A | U |+| Palettes | ✅ | ✅ `recolor`, `suggestPalette` | ✅ | A | U |+| Comments | ✅ | ❌ | ❌ (collab surface; agent works on the document, not the conversation) | — | — |+| Exports (PNG/SVG/PDF/PPTX/GIF/WebM) | ✅ | ❌ (MCP-only) | ✅ `export_design` (client-side export pipeline, saved to downloads) | A | — |+| Plugin elements | ✅ | ❌ | ❌ (plugin broker contract requires an install context; agent must not forge caller identity — documented exclusion) | — | — |+| Present/preview modes | ✅ | ❌ | ❌ (user-controlled) | — | — |++## Agent-layer capabilities (new in v0.28)++| Capability | v0.27 | v0.28 |+|---|---|---|+| Intent routing | act/ask/plan | + create/edit/review/improve/explain/plan/discuss **modes**; review/explain/discuss run with zero write tools |+| Step/tool/wall-clock caps | 8 / 12 / 90s (arbitrary) | removed — task-driven termination + resource guards (strikes, cycle detection, idle clock) + forced wrap-up |+| History | 10 messages | compaction (brief + recent observations kept; older steps summarized) |+| Usage observability | none | `usage` SSE events (turns, tool calls, ms, model) + panel display |+| Brief fidelity | none | Design Brief Contract: exact text/hex/dimension extraction + completion validation against real state |+| Visual feedback | none | canvas capture → vision critique (when a vision provider is configured); honest "geometry-only" disclosure otherwise |+| Skills | none | 10-skill engine, progressive disclosure, playbooks injected per run |+| Text measurement | 0.6×chars estimate | real client canvas `measureText` via `measure_text` tool |++## Confirmed exclusions (with technical reasons)++- **Design create/open/delete management** — the agent panel lives inside one open design; lifecycle is the user's (and the dashboard's) job. `apply_template` covers "start from a template" inside the current design.+- **Plugin element creation** — `addPluginElement` requires a verified `ActionCaller` (install id + manifest kinds); the agent cannot hold a plugin's identity without forging provenance. Plugins keep their own runtime.+- **Version-history mutation, comments, presence** — collaboration surfaces, not document state; out of the agent's blast radius by design.+- **File upload** — no server filesystem; uploads are a browser-file workflow. Data-URL images (≤4 MB, validated), stock, and generated media cover agent needs.+- **Zoom/grid/guides/rulers** — view state, not document state; the agent receives full document geometry instead of a viewport.+- **Beat pulse** — requires timing against audio analysis; skipped this wave.diff --git a/research/DESIGN-SKILLS-ENGINE-RESEARCH.md b/research/DESIGN-SKILLS-ENGINE-RESEARCH.mdnew file mode 100644index 0000000..489fe7d--- /dev/null+++ b/research/DESIGN-SKILLS-ENGINE-RESEARCH.md@@ -0,0 +1,71 @@+# Design Skills Engine — External Research (Phase 1)++Date: 2026-11-23 · Method: WebFetch analysis of the six reference projects (no cloning; all fetched content treated as untrusted data, analyzed only).++## Sources and licenses++| Project | Location | License | What it actually is |+|---|---|---|---|+| Anthropic canvas-design skill | github.com/anthropics/skills → skills/canvas-design | Apache-2.0 (skill's own LICENSE.txt) | One SKILL.md + 54 OFL fonts; philosophy-first poster generation |+| ArnavPuri designskills | github.com/ArnavPuri/designskills | MIT (LICENSE + per-skill frontmatter) | 28 SKILL.md skills in 5 categories + small scripts (contrast.py, audit.mjs) |+| UI/UX Pro Max | github.com/nextlevelbuilder/ui-ux-pro-max-skill | MIT (open core; premium tier separate) | 17 CSV datasets (styles, colors, typography, UX rules) + dependency-free search CLI |+| Impeccable | github.com/pbakaus/impeccable | Apache-2.0 (NOTICE: derives from Anthropic frontend-design) | Design-critique skill system: 24 commands, 45 reference files, Rust "slop detector" (62 rules) |+| LangChain design-agent | github.com/langchain-ai/design-agent | Apache-2.0 | Production media agent (Deep Agents/LangGraph → Slack): stills/decks/charts/motion |+| tldraw agent starter kit | tldraw/tldraw **templates/agent** (the standalone repo URL 404s) | MIT (template LICENSE.md; SDK watermark applies to the SDK itself) | Browser canvas agent: client-executed tool streams, 24 action schemas, 3-tier shape serialization |++All six are permissively licensed; selective reuse is legal with notice. We nonetheless implement Canvix-native equivalents and borrow *patterns*, not text: the individual rules are public-standard facts (WCAG, Nielsen, type measurement lore), and reimplementation keeps Canvix maintainable and avoids provenance churn. The one asset directly reusable is Anthropic's OFL font bundle — Canvix already ships its own font catalog, so it is not needed.++## Findings that shaped the implementation++### 1. Progressive disclosure is the load-bearing pattern everywhere+- Anthropic skill spec: metadata (~100 tokens, always loaded) → instructions (<5000 tokens, on activation) → resources (on demand). "Keep SKILL.md under 500 lines."+- UI/UX Pro Max keeps SKILL.md lean by pointing at a search CLI over CSVs, with an explicit zero-result honesty rule ("Never present a 0-result search as if it returned data").+- **Canvix decision**: skills expose `(id, name, description, whenToUse)` cheaply — the router matches the brief against descriptions only; the winning skill's full playbook (principles, planning steps, validation checklist) is injected into the system prompt for that run. No full-registry dumps.++### 2. Structured brief/context beats vibes+- designskills' `design-context` skill persists a brand context file (`agents/design-context.md`) as the inter-skill contract, with 11 detection sources in priority order and "never overwrite the entire file for a single field change."+- UI/UX Pro Max persists `MASTER.md` as "global source of truth" and refuses `--force` without authorization.+- **Canvix decision (Phase 5)**: a validated Design Brief Contract object — mandatory constraints (exact copy strings, hex colors, dimensions), strong preferences, optional guidance — parsed from the user message, carried through the run, and used as the completion checklist. Explicit user values are immutable; brand kit/template suggestions may only fill gaps.++### 3. Evidence-based critique with deterministic + semantic halves+- Impeccable runs two *mutually blind* assessors: an LLM design review and a deterministic Rust detector (62 rules), then synthesizes with provenance; rubric scored 0–4 per heuristic with severity caps; "a critique is not done until the fixes are checked on the rendered page." Honest degradation is explicit ("DEGRADED: single-context").+- tldraw ships `AgentLintManager`: deterministic lints computed **only on shapes the agent created** (text overflow via growY, overlapping text clusters via union-find, friendless arrows), surfaced once with dedupe.+- LangChain's `look` tool: the lead agent never sees images — a separate low-effort vision call returns ~300 tokens (context economy).+- **Canvix decision (Phases 6–7)**: two-layer verification. (a) Deterministic geometry/contrast/brief checks computed from real canvas state (no model involved) — overlap detection with text-on-card exemption (already present), off-canvas, brief fidelity (exact text and hex presence), readability floors. (b) Optional vision critique: the panel captures the canvas to a data URL and posts it to a vision-capable provider; when no vision model is configured the run discloses "geometry-only verification" instead of pretending. Factual claims must be grounded in returned canvas state — the loop already re-serializes fresh state after every apply, and the brief contract closes the hallucinated-review hole.++### 4. Task-driven execution, not fixed step caps+- tldraw: 20 follow-up requests with **remaining-steps disclosed to the model** as it approaches the limit.+- LangChain: soft USD budget (a one-time injected note, "stops nothing in code") + step budget that forces a **toolless final wrap-up call** ("state what is finished, what is not, and the next step") with a machine-readable `partial` marker — "never in prose alone."+- Anthropic auto-mode: deny-and-continue with escalation counters (3 consecutive / 20 total) instead of hard halts.+- **Canvix decision (Phase 4)**: remove the arbitrary `maxSteps: 8 / maxToolCalls: 12 / maxWallMs: 90s` caps. New termination conditions: task complete + verified, user Stop, user declines a required operation, unrecoverable error, provider technical limits, or a *resource guard* (not a product cap): consecutive-failure strikes (already present), cycle detection (identical tool+args hash repeated), and an idle-activity wall clock (no progress for N minutes → wrap up). Long-run support: progress streaming, cancellation, context compaction (keep system + brief + last K observations; summarize older steps), structured `usage` events (turns, tool calls, elapsed ms) so the UI shows cost. The forced wrap-up call pattern (LangChain) becomes the guard's exit: a final "state what's done and what remains" done event.++### 5. Server-streams / client-executes+- tldraw: tool calls stream to the browser, client executes, results ride the next request. Canvix already has exactly this shape (SSE `action` events → `applyDesignAction` → ack bridge) — validated by the v0.27.3 harness. Keep it.++### 6. Sanitize-and-correct at the boundary+- tldraw `sanitizeAction()` corrects model mistakes before touching canvas; poka-yoke tool design (Anthropic ACI doctrine: absolute paths killed a whole error class).+- Canvix already returns actionable errors ("fontSize must be 6–400; you sent 1200"). Keep + extend to every new tool.++### 7. Modes+- tldraw modes = parts[] (what the agent sees) + actions[] (what it can do), with lifecycle hooks; the docs suggest a review mode that strips edit actions.+- **Canvix decision (Phase 8)**: intent becomes a first-class **mode** axis: `create | edit | review | improve | explain | plan | discuss`. Review/explain/plan/discuss modes run with **zero write tools** — structurally incapable of editing, not just prompted not to.++### 8. Composition knowledge worth encoding (from designskills/ui-ux-pro-max/impeccable, all public-standard)+- Type: 45–75ch measure, ~1.25 modular ratio, headline ≥3× body, min readable sizes per format.+- Color: 60/30/10, 3-color cap for posters, WCAG 4.5:1 body / 3:1 large text, "don't silently change brand colors — propose the nearest passing shade."+- Layout: one focal point, safe margins, grid alignment, "whitespace is design."+- Critique severity: P0 blocking / P1 major / P2 minor / P3 polish.++## Decisions++1. **Build original, borrow patterns** (all licenses permit reuse; originality is for maintainability + fit).+2. Skills engine: registry + router + per-skill playbooks, progressive disclosure, Canvix-native (TypeScript, same `src/lib/agent/` surface).+3. Brief Contract: typed object, mandatory-vs-preference tiers, completion validation against real state.+4. Task lifecycle: guards replace caps (strikes, cycle detection, idle clock, forced wrap-up); usage observable.+5. Vision: honest capability detection — vision critique when a vision model is configured; disclosed geometry-only otherwise. Never fabricate a review.+6. Modes: tool-surface restriction per mode (review physically cannot write).+7. Keep the existing client-executes bridge, undo, collab, confirm gates — they match the best practice found in research.++## Not found / corrected+- `github.com/tldraw/agent-starter-kit` → 404; the real artifact is `tldraw/tldraw/templates/agent` (MIT).+- "jaaz tool confirmation manager" → no such project found; the canonical three-tier confirmation pattern is Anthropic's (fixed allowlist / in-scope writes / classifier- or human-gated destructive). Canvix's existing read/write/destructive tiers match it.diff --git a/src/app/api/ai/agent/route.ts b/src/app/api/ai/agent/route.tsindex d94af67..46b328c 100644--- a/src/app/api/ai/agent/route.ts+++ b/src/app/api/ai/agent/route.ts@@ -2,41 +2,49 @@ import { NextRequest } from 'next/server'import { withProvider } from '@/lib/ai/provider'import { withLogging } from '@/lib/observability'import {- AGENT_BUDGETS,AGENT_PROTOCOL_VERSION,parseAgentTurn,sseLine,type AgentEvent,+ type AgentMode,} from '@/lib/agent/protocol'-import { AGENT_TOOL_MAP, fontFamilies } from '@/lib/agent/tools'-import { serializeDesignContext, contextValidIds, type AgentDesignCtx } from '@/lib/agent/context'-import { heuristicIntent, parseIntent, ROUTER_SYSTEM, type AgentIntent } from '@/lib/agent/router'-import { runAgentLoop } from '@/lib/agent/loop'+import { fontFamilies } from '@/lib/agent/tools'+import { serializeDesignContext, type AgentDesignCtx } from '@/lib/agent/context'+import { heuristicMode, parseMode, ROUTER_SYSTEM, modeAllowsWrites, MODE_TOOL_RISK } from '@/lib/agent/router'+import { runAgentLoop, toolsForMode } from '@/lib/agent/loop'+import { selectSkills } from '@/lib/agent/skills'+import { extractBrief } from '@/lib/agent/brief'export const runtime = 'nodejs'-export const maxDuration = 120+export const maxDuration = 800// ─────────────────────────────────────────────────────────────-// POST /api/ai/agent — the design agent (v0.27).+// POST /api/ai/agent — the design agent (v0.28).//-// Streams SSE AgentEvents (src/lib/agent/protocol.ts). The model plans;-// the CLIENT executes actions through applyDesignAction — the same-// validated, undoable, collab-synced path user edits ride. The server-// never writes the document during a run.+// Streams SSE AgentEvents (src/lib/agent/protocol.ts, v2). The model+// plans; the CLIENT executes actions through applyDesignAction — the+// same validated, undoable, collab-synced path user edits ride. The+// server never writes the document during a run.//-// The client bridge: while a run is in flight the client may POST-// side-channel messages (acks + confirmations) to the SAME connection's-// pending promises via the `bridge` map below, keyed by run id. Simpler-// than WebSockets, works on every deploy target (same SSE-only posture-// as the collab rail).+// v0.28 route responsibilities:+// · classify the MODE (create/edit/review/improve/explain/plan/+// discuss) — heuristic first, one cheap model call when unsure+// · extract the Design Brief Contract from the message (Phase 5)+// · pre-select skills for the run (Phase 2, progressive disclosure)+// · explain/plan/discuss/review run a read-only loop; discuss runs+// a single completion (no canvas context needed)+// · the client bridge: while a run is in flight the client may POST+// side-channel messages (acks + confirmations + brief validation+// results) to the SAME connection's pending promises via the+// `bridge` map below, keyed by run id.// ─────────────────────────────────────────────────────────────interface AgentBody {message?: stringhistory?: { role: 'user' | 'assistant'; content: string }[]design?: AgentDesignCtx- /** 'act' | 'ask' | 'plan' — client may pass a pinned intent (chips) */- intent?: AgentIntent+ /** client-pinned mode (chips) */+ mode?: AgentMode/** tools the user pre-approved this run (from the confirm dialog) */confirmed?: string[]}@@ -46,10 +54,12 @@ interface RunBridge {confirms: Map<string, (ok: boolean) => void>/** apply acks, FIFO */acks: ((ack: { ok: boolean; message?: string; design?: AgentDesignCtx }) => void)[]+ /** brief validation result pushed by the client (Phase 5) */+ briefResult: ((r: { satisfied: boolean; unmet: string[] } | null) => void) | null/** the latest context the client pushed (after applying actions) */latestDesign: AgentDesignCtx- /** client-abort flag (Stop button closes the stream; the route notices- * via req.signal too) */+ /** client-abort flag (Stop button closes the stream; the route+ * notices via req.signal too) */aborted: boolean}@@ -65,18 +75,16 @@ async function __canvix_post(req: NextRequest) {const body = (await req.json().catch(() => ({}))) as AgentBody & {confirm?: { tool: string; ok: boolean }ack?: { ok: boolean; message?: string; design?: AgentDesignCtx }+ briefResult?: { satisfied: boolean; unmet: string[] } | null}const message = (body.message ?? '').trim().slice(0, 2000)- // side-channel: an in-flight run's ack / confirmation / refreshed- // context rides a ?bridge=<runId> POST with no `message`. NOTE: the- // body was parsed ONCE above — a second req.json() would throw- // (the stream is consumed), which is why the bridge reads the same- // parsed object instead of re-reading the request. The bridge POSTs- // are handled BEFORE withProvider on purpose: they are same-origin- // by construction (the panel only ever POSTs to its own run id) and- // MUST NOT consume the assistant feature's rate-limit budget — a- // long run's 8 acks + the run itself would otherwise blow 12/min.+ // side-channel: an in-flight run's ack / confirmation / brief+ // validation rides a ?bridge=<runId> POST with no `message`. The+ // body was parsed ONCE above — the bridge reads the same parsed+ // object. Bridge POSTs are handled BEFORE withProvider on purpose:+ // they are same-origin by construction and MUST NOT consume the+ // assistant feature's rate-limit budget.const bridgeId = req.nextUrl.searchParams.get('bridge')if (bridgeId && !message) {const bridge = bridges.get(bridgeId)@@ -93,6 +101,13 @@ async function __canvix_post(req: NextRequest) {const resolve = bridge.acks.shift()resolve?.({ ok: body.ack.ok, message: body.ack.message, design: body.ack.design })}+ if (body.briefResult !== undefined) {+ const resolve = bridge.briefResult+ if (resolve) {+ bridge.briefResult = null+ resolve(body.briefResult)+ }+ }return new Response(JSON.stringify({ ok: true }), { status: 200 })}@@ -103,10 +118,10 @@ async function __canvix_post(req: NextRequest) {// withProvider expects a NextResponse-returning callback — wrap the// SSE Response (a plain web Response) so the provider chain types line// up; the body streams through untouched.- const wrapped = await withProvider('assistant', req, { limit: 12, windowSec: 60 }, async (ctx) => {+ const wrapped = await withProvider('assistant', req, { limit: 20, windowSec: 60 }, async (ctx) => {const design: AgentDesignCtx = body.design ?? {}const history = (body.history ?? [])- .slice(-AGENT_BUDGETS.maxHistory)+ .slice(-12).filter((m) => m && (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string').map((m) => ({ role: m.role, content: m.content.slice(0, 800) }))@@ -119,28 +134,39 @@ async function __canvix_post(req: NextRequest) {return String(completion.choices[0]?.message?.content ?? '')}- // ── 1. route the intent (heuristic first, model fallback) ──- let intent: AgentIntent- if (body.intent && ['act', 'ask', 'plan'].includes(body.intent)) {- intent = body.intent+ // ── 1. classify the mode (heuristic first, model when unsure) ──+ let mode: AgentMode+ if (body.mode && MODE_TOOL_RISK[body.mode]) {+ mode = body.mode // the client pinned a mode (chips)} else {- intent = heuristicIntent(message) ?? 'plan'- if (intent === 'plan') {- // the heuristic's `plan` is a guess — one cheap model call to be- // sure we don't pay loop latency for a simple edit+ const h = heuristicMode(message)+ mode = h.mode+ if (h.confidence === 'low') {try {- intent = parseIntent(+ const modelMode = parseMode(await chat([{ role: 'system', content: ROUTER_SYSTEM },{ role: 'user', content: message.slice(0, 500) },]),)+ if (modelMode) mode = modelMode} catch {/* provider hiccup — the heuristic answer stands */}}}+ // ── 2. extract the brief contract + pre-select skills ─────+ const brief =+ mode === 'create' || mode === 'improve'+ ? extractBrief(message, design.width, design.height)+ : null+ const skills = selectSkills(+ message,+ mode,+ !!(design.brand && (design.brand.colors?.length || design.brand.headingFont)),+ )+const runId = newRunId()const encoder = new TextEncoder()@@ -162,75 +188,61 @@ async function __canvix_post(req: NextRequest) {})try {- emit({ v: AGENT_PROTOCOL_VERSION, type: 'start', intent })+ emit({ v: AGENT_PROTOCOL_VERSION, type: 'start', intent: mode, runId })- // ── 2a. ask → answer only ───────────────────────────- if (intent === 'ask') {+ // ── 3a. discuss → one completion, no canvas loop ────+ // (product/engineering talk; the design is irrelevant)+ if (mode === 'discuss') {const answer = await chat([{role: 'system',content:- 'You are the Canvix design assistant. Answer the question about the CURRENT design concisely (max 120 words), plain text, practical. Do not output JSON.\n\nCURRENT DESIGN:\n' +- serializeDesignContext(design),+ 'You are the Canvix assistant in a product/engineering discussion. Answer concisely (max 200 words), plain text, practical. Do not output JSON. Do not modify anything.',},...history,{ role: 'user', content: message },])- emit({ v: 1, type: 'done', summary: answer.slice(0, 1200), steps: 1, toolCalls: 0 })+ emit({ v: AGENT_PROTOCOL_VERSION, type: 'done', summary: answer.slice(0, 1600), steps: 1, toolCalls: 0 })return}- // ── 2b. act → one completion, ≤3 actions ────────────- if (intent === 'act') {- const system =- 'You are the Canvix design assistant. Reply ONLY with JSON: {"reply": string, "actions": array} — actions are DesignAction objects (same schema as the assistant app). Max ' +- `${AGENT_BUDGETS.maxDirectActions} actions, only when clearly asked. Empty array otherwise. Never invent element ids.\n\n` +- 'Action types: addText{text,fontSize,bold,color,align,y}, updateElements{ids,patch}, deleteElements{ids}, moveElements{ids,dx,dy,to}, ' +- 'setHeadingsColor{color}, setTextColor{color}, setFont{fontFamily,targets}, setBackground{kind,from,to,angle}, alignElements{ids,mode}, ' +- 'distributeElements{ids,axis}, fixOverlaps, balanceLayout, addPage, duplicatePage, gotoPage{page}, addStockPhoto{query}, suggestPalette{colors}, translate{language}, magicAnimate, generateImage{prompt}.\n\n' +- `Fonts (exact names): ${fontFamilies().slice(0, 30).join(', ')}…\n\nCURRENT DESIGN:\n${serializeDesignContext(design)}`- const raw = await chat([{ role: 'system', content: system }, ...history, { role: 'user', content: message }])- // reuse the assistant route's robust parse shape- const parsed = parseAgentTurn(raw)- if (parsed && typeof (parsed as unknown as { reply?: string }).reply !== 'undefined') {- const p = parsed as unknown as { reply?: string; actions?: unknown[] }- const actions = Array.isArray(p.actions) ? p.actions.slice(0, AGENT_BUDGETS.maxDirectActions) : []- if (actions.length > 0) {- emit({- v: 1,- type: 'action',- stepIndex: 1,- callId: `direct-${runId}`,- risk: 'write',- tool: 'direct-actions',- actions,- })- }- emit({ v: 1, type: 'done', summary: String(p.reply ?? '').slice(0, 1200), steps: 1, toolCalls: actions.length })- } else {- // plain-text fallback — treat as an answer- emit({ v: 1, type: 'done', summary: raw.slice(0, 1200) || 'I could not answer that — try rephrasing.', steps: 1, toolCalls: 0 })- }+ // ── 3b. explain → one grounded answer ───────────────+ if (mode === 'explain') {+ const answer = await chat([+ {+ role: 'system',+ content:+ 'You are the Canvix design assistant. Answer the question about the CURRENT design below concisely (max 150 words), plain text. Ground every claim in the state shown — never invent elements. Do not output JSON.\n\nCURRENT DESIGN:\n' ++ serializeDesignContext(design),+ },+ ...history,+ { role: 'user', content: message },+ ])+ emit({ v: AGENT_PROTOCOL_VERSION, type: 'done', summary: answer.slice(0, 1600), steps: 1, toolCalls: 0 })return}- // ── 2c. plan → the agent loop ──────────────────────+ // ── 3c. every other mode → the agent loop (review/+ // plan run read-only tool surfaces inside the loop)const bridge: RunBridge = {confirms: new Map(),acks: [],+ briefResult: null,latestDesign: design,aborted: false,}bridges.set(runId, bridge)- // the FIRST SSE line after start tells the client the run id so- // its side-channel POSTs can find this bridge- emit({ v: 1, type: 'plan', steps: [] })- emit({ v: 1, type: 'observation', stepIndex: 0, message: `__runId:${runId}` })+ // tell the client the run id so its side-channel POSTs can+ // find this bridge (protocol detail: rides an observation)+ emit({ v: AGENT_PROTOCOL_VERSION, type: 'observation', stepIndex: 0, message: `__runId:${runId}` })try {await runAgentLoop({chat,design,+ mode,+ brief,+ skills,emit,confirmed: new Set(body.confirmed ?? []),signal: {@@ -241,7 +253,6 @@ async function __canvix_post(req: NextRequest) {},awaitConfirm: (tool) =>new Promise<boolean>((resolve) => {- // auto-approve if the user already approved this toolbridge.confirms.set(tool, resolve)// safety: never hang forever on a silent clientsetTimeout(() => {@@ -249,21 +260,34 @@ async function __canvix_post(req: NextRequest) {bridge.confirms.delete(tool)resolve(false)}- }, 45_000)+ }, 120_000)}),awaitApply: () =>new Promise<{ ok: boolean; message?: string }>((resolve) => {bridge.acks.push((ack) => resolve({ ok: ack.ok, message: ack.message }))- setTimeout(() => resolve({ ok: true, message: 'ack timeout — assumed applied' }), 30_000)+ setTimeout(() => resolve({ ok: true, message: 'ack timeout — assumed applied' }), 60_000)}),refreshedContext: () => bridge.latestDesign,+ validateBriefOnClient: () =>+ new Promise<{ satisfied: boolean; unmet: string[] } | null>((resolve) => {+ bridge.briefResult = resolve+ // the client answers on the bridge; give it a generous+ // window, then fall back to null (no client validation+ // available — the run continues without the gate)+ setTimeout(() => {+ if (bridge.briefResult === resolve) {+ bridge.briefResult = null+ resolve(null)+ }+ }, 30_000)+ }),})} finally {bridges.delete(runId)}} catch (err) {emit({- v: 1,+ v: AGENT_PROTOCOL_VERSION,type: 'error',message: `Agent run failed: ${err instanceof Error ? err.message.slice(0, 200) : 'unknown error'}.`,})diff --git a/src/app/api/ai/agent/vision/route.ts b/src/app/api/ai/agent/vision/route.tsnew file mode 100644index 0000000..aa69ad4--- /dev/null+++ b/src/app/api/ai/agent/vision/route.ts@@ -0,0 +1,127 @@+import { NextRequest, NextResponse } from 'next/server'+import { getClientForSlot } from '@/lib/ai/provider'+import { withLogging } from '@/lib/observability'++export const runtime = 'nodejs'+export const maxDuration = 120++// ─────────────────────────────────────────────────────────────+// POST /api/ai/agent/vision — Phase 7 visual critique.+//+// The agent panel captures the canvas with the SAME Konva pipeline+// exports use (captureStage), downscales it, and posts it here with+// the run's brief + the current structured state. This route sends+// ONE vision-slot call and returns grounded findings.+//+// Honesty contract (the anti-hallucination rules):+// · No vision provider configured → 503 { available: false } and+// the panel says "visual critique unavailable — geometry-only+// verification". It NEVER pretends a text model looked at a+// screenshot it never received.+// · The prompt forbids inventing elements: findings must reference+// what is visible or explicitly say "cannot determine".+// ─────────────────────────────────────────────────────────────++interface VisionBody {+ image?: string // dataURL (png/jpeg)+ brief?: { requiredTexts?: { text: string }[]; requiredColors?: { hex: string }[] }+ stateSummary?: string // the serialized structured state+}++const SYSTEM =+ 'You are a meticulous design critic looking at a REAL screenshot of a graphic-design canvas. ' ++ 'Report only what you can actually see in the image. Never invent or assume elements that are not visible; ' ++ 'if something cannot be determined from the image, say "cannot determine". ' ++ 'Reply ONLY with JSON: {"findings": [{"severity": "P0"|"P1"|"P2"|"P3", "issue": "what is wrong (concrete, visual)", "fix": "the specific change to make"}], "overall": "one sentence verdict"}\n' ++ 'P0 = broken/unreadable/missing required content; P1 = major (weak hierarchy, poor contrast, crowding); P2 = minor (spacing, balance); P3 = polish.'++async function __canvix_post(req: NextRequest) {+ const body = (await req.json().catch(() => ({}))) as VisionBody+ const image = (body.image ?? '').trim()+ if (!image.startsWith('data:image/')) {+ return NextResponse.json({ error: 'image must be a data URL from the canvas capture.' }, { status: 400 })+ }+ if (image.length > 8 * 1024 * 1024) {+ return NextResponse.json({ error: 'Image too large (max ~8 MB).' }, { status: 413 })+ }++ // the vision slot is a SEPARATE capability — resolve it directly+ // (withProvider resolves the text slot). When unconfigured, answer+ // honestly instead of falling back to a text model.+ const vision = await getClientForSlot('vision')+ if (!vision) {+ return NextResponse.json(+ {+ available: false,+ error: 'Visual critique needs a vision model (admin AI & models page, vision slot). Geometry-only verification was used instead.',+ },+ { status: 503 },+ )+ }++ const brief = body.brief ?? {}+ const requiredTexts = (brief.requiredTexts ?? []).map((t) => t.text).filter(Boolean)+ const requiredColors = (brief.requiredColors ?? []).map((c) => c.hex).filter(Boolean)++ const userText = [+ 'Critique this canvas screenshot for design quality and brief compliance.',+ requiredTexts.length ? `Required exact texts (verify they appear VERBATIM and are readable): ${requiredTexts.map((t) => `"${t}"`).join(', ')}.` : '',+ requiredColors.length ? `Required colors (verify they are visibly used): ${requiredColors.join(', ')}.` : '',+ body.stateSummary ? `Structured element state for cross-checking (ground truth for ids/positions):\n${body.stateSummary.slice(0, 4000)}` : '',+ 'Check: readability of every text at this scale, contrast of text on its background, alignment and spacing consistency, visual hierarchy (is the headline dominant?), accidental overlaps or clipped content, dead space, and overall professional impression.',+ 'Reply with the JSON findings now.',+ ]+ .filter(Boolean)+ .join('\n')++ try {+ const completion = await vision.zai.chat.completions.create({+ ...(vision.model ? { model: vision.model } : {}),+ messages: [+ { role: 'system', content: SYSTEM },+ {+ role: 'user',+ content: [+ { type: 'text', text: userText },+ { type: 'image_url', image_url: { url: image } },+ ] as unknown as string,+ },+ ],+ thinking: { type: 'disabled' },+ })+ const raw = String(completion.choices[0]?.message?.content ?? '')+ // robust parse — the model may fence or add prose+ const cleaned = raw.replace(/```(?:json)?/gi, '').trim()+ const start = cleaned.indexOf('{')+ const end = cleaned.lastIndexOf('}')+ if (start === -1 || end <= start) {+ return NextResponse.json({ error: 'The vision model returned no parseable critique.' }, { status: 502 })+ }+ let parsed: { findings?: unknown; overall?: unknown }+ try {+ parsed = JSON.parse(cleaned.slice(start, end + 1))+ } catch {+ return NextResponse.json({ error: 'The vision model returned malformed critique JSON.' }, { status: 502 })+ }+ const findings = (Array.isArray(parsed.findings) ? parsed.findings : [])+ .filter((f) => !!f && typeof f === 'object')+ .map((f) => {+ const fo = f as { severity?: unknown; issue?: unknown; fix?: unknown }+ const sev = ['P0', 'P1', 'P2', 'P3'].includes(String(fo.severity)) ? (String(fo.severity) as 'P0') : 'P2'+ return {+ severity: sev,+ issue: String(fo.issue ?? '').slice(0, 400) || 'unspecified issue',+ fix: fo.fix === undefined ? undefined : String(fo.fix).slice(0, 400),+ }+ })+ .slice(0, 12)+ return NextResponse.json({ available: true, findings, overall: String(parsed.overall ?? '').slice(0, 400) })+ } catch (err) {+ const message = err instanceof Error ? err.message.slice(0, 150) : 'vision call failed'+ return NextResponse.json({ error: `Visual critique failed: ${message}` }, { status: 502 })+ }+}++// v0.12.5 (H7): opt-in request logging wrapper — passthrough+// unless CANVIX_LOG=requests+export const POST = withLogging('POST /api/ai/agent/vision', __canvix_post)diff --git a/src/components/editor/apps/AssistantApp.tsx b/src/components/editor/apps/AssistantApp.tsxindex a1fe76b..a55fec2 100644--- a/src/components/editor/apps/AssistantApp.tsx+++ b/src/components/editor/apps/AssistantApp.tsx@@ -1,30 +1,39 @@'use client'// ─────────────────────────────────────────────────────────────-// AssistantApp (v0.27) — the Canvix design agent panel.+// AssistantApp (v0.28) — the Canvix design agent panel.//-// Rebuilt from the single-shot chat on the research synthesis-// (docs/AGENT-ARCHITECTURE.md):-// · streaming SSE run view — thought → tool → observation, live-// · auto-apply (kept from v0.26) with a confirm gate for-// destructive tools-// · Stop button mid-run (completed work is kept)-// · "Undo agent work" — rewinds the editor history to the run's-// baseline (every agent action was one undo step)-// · session memory — the conversation persists in the panel; the-// goal of the current run stays in context for scoped refinements-// · ask/act/plan routing happens server-side (src/lib/agent/router)+// The v0.28 overhaul (docs/AGENT-ARCHITECTURE.md):+// · MODE CHIPS — create/edit/review/improve/explain/plan/discuss;+// pinned modes ride the request; read-only modes are also+// enforced server-side (zero write tools in the surface)+// · LIVE RUN VIEW — mode, active skills, the Design Brief+// Contract, steps (thought → tool → observation), usage+// telemetry (turns/tools/time) and compaction notices+// · CLIENT BRIEF VALIDATION (Phase 5 partner) — validate_brief+// and the done-gate call back into the panel, which computes+// the result against the LIVE document and answers on the bridge+// · PER-CALL APPROVALS — destructive calls ask once per callId+// batch (not per tool name); a session-approved tool name still+// auto-applies within the SAME run only+// · VISION CRITIQUE (Phase 7) — after a create/improve run the+// panel captures the canvas (the export pipeline's captureStage)+// and asks the vision slot for grounded findings; when no vision+// model is configured it says so plainly (never pretends)+// · Stop mid-run (completed work kept) + "Undo agent work"// ─────────────────────────────────────────────────────────────import { useCallback, useEffect, useRef, useState } from 'react'-import { Bot, Loader2, Send, Sparkles, User, Wand2, Zap, Square, Undo2, ShieldAlert, ListChecks } from 'lucide-react'+import { Bot, Loader2, Send, Sparkles, User, Square, Undo2, ShieldAlert, ListChecks, Eye, Gauge, Scissors, CheckCircle2 } from 'lucide-react'import type { AnyElement, TextElement } from '@/lib/types'import { useEditorStore } from '@/store/editor-store'import { AppHeader, type AppPanelProps } from './registry'import { cn } from '@/lib/utils'import { applyDesignAction, describeAction, type DesignAction } from '@/lib/design-actions'import { useAICapabilities } from '@/hooks/use-ai-capabilities'-import type { AgentEvent } from '@/lib/agent/protocol'+import type { AgentEvent, AgentMode } from '@/lib/agent/protocol'+import { validateBrief, type DesignBrief } from '@/lib/agent/brief'+import { heuristicMode, MODE_TOOL_RISK } from '@/lib/agent/router'// ── types ────────────────────────────────────────────────────@@ -35,35 +44,45 @@ interface RunStep {observation?: string}+interface Finding {+ severity: 'P0' | 'P1' | 'P2' | 'P3'+ issue: string+ fix?: string+}+interface Turn {role: 'user' | 'assistant'content: string- /** streamed steps of the run that produced this turn */steps?: RunStep[]- /** actions this turn executed (auto or approved) */appliedActions?: number- /** the run's baseline undo length — powers "Undo agent work" */baseline?: number+ mode?: AgentMode+ plan?: string[]+ findings?: Finding[]+ verification?: string+ usage?: { turns: number; toolCalls: number; elapsedMs: number; modelCalls: number }}const SUGGESTIONS = ['Design a bold Instagram post for a coffee launch',- 'Fix anything that overlaps',- 'Make this design more modern',- 'Add a CTA button text',- 'Balance the layout',- 'What do you think of this design?',+ 'Make this design more professional',+ 'What is wrong with this design?',+ 'Add a CTA button',+ 'Build a 3-slide pitch deck for a startup idea',+ 'Explain what fonts this design uses',]-const AUTO_APPLY_KEY = 'canvix-assistant-auto-apply'-function readAutoApply(): boolean {- try {- const v = localStorage.getItem(AUTO_APPLY_KEY)- return v === null ? true : v === '1'- } catch {- return true- }-}+const MODE_CHIPS: { id: AgentMode | 'auto'; label: string }[] = [+ { id: 'auto', label: 'Auto' },+ { id: 'create', label: 'Create' },+ { id: 'edit', label: 'Edit' },+ { id: 'review', label: 'Review' },+ { id: 'improve', label: 'Improve' },+ { id: 'explain', label: 'Explain' },+ { id: 'plan', label: 'Plan' },+]++const READ_ONLY_MODES: AgentMode[] = ['review', 'explain', 'plan', 'discuss']/** Flatten elements (groups included). */function flatElements(els: AnyElement[], out: AnyElement[] = []): AnyElement[] {@@ -117,7 +136,7 @@ function buildDesignContext() {const inter = ix * iyconst minArea = Math.min(a.w * a.h, b.w * b.h)if (minArea > 0 && inter / minArea > 0.08) {- const smaller = a.w * a.h <= b.w * b.h ? a : b+ const smaller = a.w * a.h <= b.w * a.h ? a : bif (inter / minArea > 0.55 && smaller.type === 'text') continue // text-on-cardoverlaps.push(`${a.type}#${a.id} × ${b.type}#${b.id} (${Math.round((inter / minArea) * 100)}%)`)}@@ -161,6 +180,37 @@ function buildDesignContext() {}}+/** Client-side brief validation against the LIVE document (Phase 5).+ * Pure — reads the store, returns the validation shape the loop+ * expects on the bridge. */+function computeBriefValidation(brief: DesignBrief): { satisfied: boolean; unmet: string[] } {+ const s = useEditorStore.getState()+ const page = s.pages[s.currentPage]+ const els = flatElements(page?.elements ?? [])+ const texts = els.filter((e) => e.type === 'text').map((e) => (e as TextElement).text)+ const colors = new Set<string>()+ for (const el of els) {+ if ('fill' in el && typeof (el as { fill?: unknown }).fill === 'string') {+ colors.add(((el as { fill: string }).fill).toLowerCase())+ }+ if ('stroke' in el && typeof (el as { stroke?: unknown }).stroke === 'string') {+ colors.add(((el as { stroke: string }).stroke).toLowerCase())+ }+ }+ if (page?.background?.type === 'solid') colors.add(page.background.color.toLowerCase())+ if (page?.background?.type === 'gradient') {+ colors.add(page.background.from.toLowerCase())+ colors.add(page.background.to.toLowerCase())+ }+ const result = validateBrief(brief, {+ texts,+ colors: [...colors],+ width: s.width,+ height: s.height,+ })+ return { satisfied: result.satisfied, unmet: result.unmet }+}+// ── the component ────────────────────────────────────────────export function AssistantApp({ onClose }: AppPanelProps) {@@ -169,31 +219,46 @@ export function AssistantApp({ onClose }: AppPanelProps) {const [busy, setBusy] = useState(false)/** live steps of the in-flight run */const [liveSteps, setLiveSteps] = useState<RunStep[]>([])+ /** live mode + skills + brief of the in-flight run */+ const [liveMode, setLiveMode] = useState<AgentMode | null>(null)+ const [liveSkills, setLiveSkills] = useState<string[]>([])+ const [liveBrief, setLiveBrief] = useState<DesignBrief | null>(null)+ const [liveUsage, setLiveUsage] = useState<{ turns: number; toolCalls: number; elapsedMs: number; modelCalls: number } | null>(null)+ /** the pinned mode chip ('auto' = classify per message) */+ const [pinnedMode, setPinnedMode] = useState<AgentMode | 'auto'>('auto')/** pending destructive confirmation */const [pendingConfirm, setPendingConfirm] = useState<{ tool: string; actions: DesignAction[]; callId: string } | null>(null)const scrollRef = useRef<HTMLDivElement>(null)const abortRef = useRef<AbortController | null>(null)const runIdRef = useRef<string | null>(null)const confirmedRef = useRef<Set<string>>(new Set())+ const briefRef = useRef<DesignBrief | null>(null)const { configured: aiConfigured, loaded: aiLoaded } = useAICapabilities()const canUndo = useEditorStore((s) => s.past.length > 0)- const [autoApply, setAutoApply] = useState(() => readAutoApply())- const toggleAutoApply = () => {- const next = !autoApply- setAutoApply(next)- try {- localStorage.setItem(AUTO_APPLY_KEY, next ? '1' : '0')- } catch {- /* storage unavailable */- }- }-+ // auto-scroll the threaduseEffect(() => {scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' })- }, [turns, liveSteps, busy, pendingConfirm])+ }, [turns, liveSteps, pendingConfirm])++ const applyActions = useCallback(async (actions: DesignAction[]): Promise<{ ok: boolean; message?: string }> => {+ let lastMsg = ''+ for (const a of actions) {+ try {+ // the __validateBrief pseudo-action is answered separately+ if (a.type === '__validateBrief') {+ lastMsg = 'validated'+ continue+ }+ lastMsg = await applyDesignAction(a)+ } catch (e) {+ return { ok: false, message: e instanceof Error ? e.message : 'Action failed' }+ }+ }+ return { ok: true, message: lastMsg }+ }, [])- /** side-channel POST to the run's bridge (acks + confirmations) */+ /** side-channel POST to the run's bridge */const bridgePost = useCallback(async (payload: Record<string, unknown>) => {const runId = runIdRef.currentif (!runId) return@@ -204,20 +269,42 @@ export function AssistantApp({ onClose }: AppPanelProps) {body: JSON.stringify(payload),})} catch {- /* the run notices the timeout and self-heals */+ /* the run will time the ack out safely */}}, [])- const applyActions = useCallback(async (actions: DesignAction[]): Promise<{ ok: boolean; message?: string }> => {- let lastMsg = ''- for (const a of actions) {- try {- lastMsg = await applyDesignAction(a)- } catch (e) {- return { ok: false, message: e instanceof Error ? e.message : 'Action failed' }+ /** Phase 7: visual critique of the current canvas (honest about+ * availability). Appends findings to the finished turn. */+ const visionCritique = useCallback(async (brief: DesignBrief | null): Promise<{ findings: Finding[]; note: string } | null> => {+ let dataUrl = ''+ try {+ const { captureStage } = await import('@/components/editor/canvas/canvas-bridge')+ // downscale for the payload: capture at a modest scale, jpeg+ dataUrl = await captureStage({ pixelScale: 0.5, mimeType: 'image/jpeg', quality: 0.7 })+ } catch {+ return null+ }+ try {+ const res = await fetch('/api/ai/agent/vision', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ image: dataUrl,+ brief: brief+ ? { requiredTexts: brief.requiredTexts, requiredColors: brief.requiredColors }+ : undefined,+ stateSummary: JSON.stringify(buildDesignContext()).slice(0, 6000),+ }),+ })+ if (res.status === 503) {+ return { findings: [], note: 'Visual critique unavailable (no vision model configured) — verified via geometry checks only.' }}+ const data = (await res.json().catch(() => ({}))) as { findings?: Finding[]; error?: string }+ if (!res.ok) return { findings: [], note: data.error ?? 'Visual critique failed.' }+ return { findings: data.findings ?? [], note: 'Visual critique completed against the rendered canvas.' }+ } catch {+ return null}- return { ok: true, message: lastMsg }}, [])const send = async (message: string) => {@@ -229,13 +316,26 @@ export function AssistantApp({ onClose }: AppPanelProps) {setTurns((ts) => [...ts, { role: 'user', content: text }])setBusy(true)setLiveSteps([])+ setLiveSkills([])+ setLiveBrief(null)+ setLiveUsage(null)confirmedRef.current = new Set()+ // the heuristic pre-classification shows a mode hint even before+ // the server answers (the pinned chip wins when set)+ const expectedMode = pinnedMode === 'auto' ? heuristicMode(text).mode : pinnedMode+ setLiveMode(expectedMode)+const controller = new AbortController()abortRef.current = controllerconst collectedSteps: RunStep[] = []let appliedCount = 0let summary = ''+ let mode = expectedMode+ let plan: string[] | undefined+ let findings: Finding[] | undefined+ let verification: string | undefined+ let runBrief: DesignBrief | null = nulltry {const res = await fetch('/api/ai/agent', {@@ -246,6 +346,7 @@ export function AssistantApp({ onClose }: AppPanelProps) {message: text,history,design: buildDesignContext(),+ ...(pinnedMode !== 'auto' ? { mode: pinnedMode } : {}),confirmed: [...confirmedRef.current],}),})@@ -261,6 +362,26 @@ export function AssistantApp({ onClose }: AppPanelProps) {const handleEvent = async (event: AgentEvent) => {switch (event.type) {case 'start':+ if (event.runId) {+ runIdRef.current = event.runId+ } else {+ // v1-style start: runId arrives via the observation below+ }+ break+ case 'mode':+ mode = event.mode+ setLiveMode(event.mode)+ break+ case 'skill':+ setLiveSkills((s) => [...s, event.name])+ break+ case 'brief':+ runBrief = event.brief as unknown as DesignBrief+ briefRef.current = runBrief+ setLiveBrief(runBrief)+ break+ case 'plan':+ plan = event.stepsbreakcase 'step': {collectedSteps.push({ index: event.index, thought: event.thought, tool: event.tool })@@ -278,12 +399,33 @@ export function AssistantApp({ onClose }: AppPanelProps) {setLiveSteps([...collectedSteps])break}+ case 'usage':+ setLiveUsage({ turns: event.turns, toolCalls: event.toolCalls, elapsedMs: event.elapsedMs, modelCalls: event.modelCalls })+ break+ case 'compact':+ collectedSteps.push({+ index: collectedSteps.length,+ thought: 'Context trimmed',+ tool: 'compact',+ observation: `Older steps summarized (${event.fromMessages} → ${event.toMessages} messages) — the run continues.`,+ })+ setLiveSteps([...collectedSteps])+ breakcase 'action': {const actions = event.actions as DesignAction[]+ // the brief-validation pseudo-action never touches the doc+ if (event.tool === 'validate_brief') {+ const brief = briefRef.current+ const result = brief+ ? computeBriefValidation(brief)+ : { satisfied: true, unmet: [] }+ await applyActions(actions) // no-op for the pseudo action+ await bridgePost({ briefResult: result })+ return+ }if (event.risk === 'destructive') {if (confirmedRef.current.has(event.tool)) {- // user already approved this tool this run (or- // auto-apply is on and they approved earlier)+ // user already approved this tool this runconst ack = await applyActions(actions)if (ack.ok) appliedCount += actions.lengthawait bridgePost({ ack: { ok: ack.ok, message: ack.message, design: buildDesignContext() } })@@ -292,8 +434,7 @@ export function AssistantApp({ onClose }: AppPanelProps) {setPendingConfirm({ tool: event.tool, actions, callId: event.callId })}} else {- // apply immediately (auto and manual modes alike — manual- // reviewers get per-run Undo + the destructive gate)+ // apply immediately; ack the run with refreshed stateconst ack = await applyActions(actions)if (ack.ok) appliedCount += actions.lengthawait bridgePost({ ack: { ok: ack.ok, message: ack.message, design: buildDesignContext() } })@@ -302,6 +443,7 @@ export function AssistantApp({ onClose }: AppPanelProps) {}case 'done':summary = event.summary+ if (event.verification) verification = event.verificationbreakcase 'error':summary = event.message@@ -329,6 +471,18 @@ export function AssistantApp({ onClose }: AppPanelProps) {}}+ // Phase 7: after create/improve runs, one visual critique pass+ let critiqueNote: string | undefined+ if ((mode === 'create' || mode === 'improve') && summary && !controller.signal.aborted) {+ const critique = await visionCritique(runBrief ?? briefRef.current)+ if (critique) {+ critiqueNote = critique.note+ if (critique.findings.length) {+ findings = [...(findings ?? []), ...critique.findings]+ }+ }+ }+setTurns((ts) => [...ts,{@@ -337,36 +491,26 @@ export function AssistantApp({ onClose }: AppPanelProps) {steps: collectedSteps,appliedActions: appliedCount,baseline,+ mode,+ plan,+ findings,+ verification: verification ?? critiqueNote,+ usage: liveUsage ?? undefined,},])- } catch (e) {- if (e instanceof DOMException && e.name === 'AbortError') {- setTurns((ts) => [- ...ts,- {- role: 'assistant',- content: 'Stopped — everything applied so far is kept. Undo it with the button below if needed.',- steps: collectedSteps,- appliedActions: appliedCount,- baseline,- },- ])- } else {- const msg = e instanceof Error ? e.message : 'Something went wrong.'- setTurns((ts) => [- ...ts,- {- role: 'assistant',- content: `${msg}\n\nTip: add your own AI key in Profile & AI keys (account menu) — your key is used before this instance's providers.`,- },- ])- }+ } catch (err) {+ const msg = err instanceof Error && err.name === 'AbortError' ? 'Stopped — applied work is kept.' : err instanceof Error ? err.message : 'The agent failed.'+ setTurns((ts) => [...ts, { role: 'assistant', content: msg, steps: collectedSteps, appliedActions: appliedCount, baseline, mode }])} finally {setBusy(false)setLiveSteps([])+ setLiveMode(null)+ setLiveSkills([])+ setLiveBrief(null)+ setLiveUsage(null)setPendingConfirm(null)- runIdRef.current = nullabortRef.current = null+ runIdRef.current = null}}@@ -379,84 +523,73 @@ export function AssistantApp({ onClose }: AppPanelProps) {await bridgePost({ confirm: { tool: pending.tool, ok: false } })return}- // apply immediately so the user sees the result, then ack the run- // (the loop now also waits for this ack on approved destructive- // calls — a failed apply must be reported, not counted as done).- // The approval only persists on SUCCESS — a failed apply must- // re-ask, not silently auto-apply the retry (v0.27.3 audit fix).+ // apply immediately so the user sees the result, then ack the run.+ // The approval only persists on SUCCESS (per-run scope).const ack = await applyActions(pending.actions)if (ack.ok) confirmedRef.current.add(pending.tool)await bridgePost({ confirm: { tool: pending.tool, ok: true } })await bridgePost({ ack: { ok: ack.ok, message: ack.message, design: buildDesignContext() } })}- const stop = () => {- abortRef.current?.abort()- }-/** rewind to the run baseline — every agent action was one undo step */- const undoAgentWork = (baseline: number) => {- const s = useEditorStore.getState()- const steps = s.past.length - baseline- if (steps <= 0) return- for (let i = 0; i < steps; i++) s.undo()+ const undoAgentWork = () => {+ const last = [...turns].reverse().find((t) => t.role === 'assistant' && t.baseline !== undefined)+ if (!last?.baseline) return+ const store = useEditorStore.getState()+ const target = last.baseline+ while (useEditorStore.getState().past.length > target && useEditorStore.getState().past.length > 0) {+ store.undo()+ }}- const empty = turns.length === 0 && !busy+ const stop = () => abortRef.current?.abort()return (- <div className="flex flex-col">- <AppHeader icon={Bot} title="Canvix AI" onClose={onClose}>- <button- onClick={toggleAutoApply}- className={cn(- 'flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[10.5px] font-bold transition-colors',- autoApply- ? 'border-[#02C0CC]/40 bg-[#02C0CC]/15 text-[#7BE8EC]'- : 'border-white/12 bg-white/[0.04] text-white/55 hover:text-white/80'- )}- title={- autoApply- ? 'Auto-apply ON — actions run automatically; destructive tools still ask first.'- : 'Auto-apply OFF — destructive tools ask first; other actions run and are undoable.'- }- aria-pressed={autoApply}- data-testid="assistant-auto-apply"- >- <Zap size={11} /> Auto {autoApply ? 'on' : 'off'}- </button>- </AppHeader>-- {/* provider hint */}- {aiLoaded && !aiConfigured && !busy && (- <div- className="mb-2.5 rounded-xl border border-[#FFD166]/25 bg-[#FFD166]/10 px-3 py-2 text-[11px] text-[#FFE9A8] leading-relaxed"- data-testid="agent-no-provider"- >- No AI provider on this instance. Add your own key in <span className="font-semibold">Profile & AI keys</span> (account- menu) — your key is used first.+ <div className="flex flex-col h-full">+ <AppHeader icon={Sparkles} title="Canvix agent" onClose={onClose} />++ {aiLoaded && !aiConfigured && (+ <div data-testid="agent-no-provider" className="mx-3 mt-2 rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-2.5 text-[12px] text-amber-200">+ No AI provider configured yet — add a key in Admin → AI & models (or your profile) to use the agent.</div>)}- <div ref={scrollRef} className="flex-1 overflow-y-auto min-h-0 space-y-3 pr-0.5" data-testid="agent-thread">- {/* empty state */}- {empty && (- <div className="py-6 text-center">- <div className="mx-auto h-12 w-12 rounded-2xl bg-brand-gradient flex items-center justify-center text-white mb-3">- <Sparkles size={22} />+ {/* mode chips */}+ <div className="flex items-center gap-1 px-3 py-2 border-b border-white/5 overflow-x-auto" data-testid="agent-modes">+ {MODE_CHIPS.map((chip) => {+ const active = pinnedMode === chip.id+ const readOnly = chip.id !== 'auto' && READ_ONLY_MODES.includes(chip.id as AgentMode)+ return (+ <button+ key={chip.id}+ onClick={() => setPinnedMode(chip.id)}+ className={cn(+ 'shrink-0 px-2.5 h-7 rounded-full text-[11px] font-semibold transition-colors',+ active ? 'bg-[#7630D7] text-white' : 'bg-white/5 text-white/60 hover:bg-white/10 hover:text-white',+ )}+ title={readOnly ? 'Read-only: the agent cannot modify the design' : chip.id === 'auto' ? 'Classify each message automatically' : undefined}+ >+ {readOnly && <Eye size={10} className="inline mr-1 -mt-0.5" />}+ {chip.label}+ </button>+ )+ })}+ </div>++ {/* thread */}+ <div ref={scrollRef} className="flex-1 overflow-y-auto min-h-0 space-y-3 pr-0.5 px-3 py-3" data-testid="agent-thread">+ {turns.length === 0 && !busy && (+ <div className="pt-6 text-center">+ <div className="mx-auto mb-3 w-11 h-11 rounded-2xl bg-[#7630D7]/15 flex items-center justify-center">+ <Bot size={20} className="text-[#a78bfa]" /></div><p className="text-[13px] font-bold text-white/90">Your design agent</p>- <p className="mt-1 text-[11.5px] text-white/45 leading-relaxed max-w-[240px] mx-auto">- Describe a change or a whole design — I'll plan, act on the canvas step by step, and verify the result. Every step- is undoable.+ <p className="text-[11px] text-white/40 mt-1 max-w-[240px] mx-auto">+ Describe what to build or change. The agent plans, edits real elements, validates against your brief, and can critique the result visually.</p>- <div className="mt-4 grid grid-cols-1 gap-1.5">+ <div className="flex flex-wrap gap-1.5 justify-center mt-4">{SUGGESTIONS.map((s) => (- <button- key={s}- onClick={() => void send(s)}- className="rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2 text-left text-[11.5px] font-medium text-white/75 hover:border-[#7630D7]/50 hover:bg-[#7630D7]/10 hover:text-white transition-colors"- >+ <button key={s} onClick={() => send(s)} className="px-2.5 py-1.5 rounded-full bg-white/5 hover:bg-white/10 text-[11px] text-white/70 transition-colors">{s}</button>))}@@ -464,163 +597,214 @@ export function AssistantApp({ onClose }: AppPanelProps) {</div>)}- {/* conversation */}- {turns.map((t, i) => (- <div key={i} className={cn('flex gap-2', t.role === 'user' ? 'justify-end' : 'justify-start')}>- {t.role === 'assistant' && (- <div className="h-6 w-6 rounded-lg bg-brand-gradient flex items-center justify-center text-white shrink-0 mt-0.5">- <Bot size={13} />+ {turns.map((turn, i) =>+ turn.role === 'user' ? (+ <div key={i} className="flex gap-2 justify-end">+ <div className="max-w-[85%] rounded-2xl rounded-br-md bg-[#7630D7] px-3 py-2 text-[12.5px] text-white leading-relaxed">+ {turn.content}+ </div>+ <div className="w-6 h-6 shrink-0 rounded-full bg-white/10 flex items-center justify-center">+ <User size={12} className="text-white/70" /></div>- )}- <div- className={cn(- 'max-w-[85%] rounded-2xl px-3 py-2 text-[12px] leading-relaxed whitespace-pre-wrap',- t.role === 'user' ? 'bg-[#7630D7] text-white rounded-br-sm' : 'bg-white/[0.05] text-white/90 rounded-tl-sm'- )}- >- {t.content}- {/* the run's steps, kept after completion */}- {t.steps && t.steps.length > 0 && (- <div className="mt-2 border-t border-white/10 pt-2 space-y-1">- <div className="text-[9.5px] font-semibold text-white/35 uppercase tracking-wide flex items-center gap-1">- <ListChecks size={10} /> {t.steps.length} step{t.steps.length > 1 ? 's' : ''}- {t.appliedActions ? ` · ${t.appliedActions} change${t.appliedActions > 1 ? 's' : ''} applied` : ''}- </div>- {t.steps.map((s) => (- <div key={s.index} className="text-[10.5px] text-white/50 leading-snug">- <span className="text-[#02C0CC] font-semibold">{s.tool}</span>- {s.thought ? ` — ${s.thought}` : ''}- {s.observation ? <span className="block text-white/35">↳ {s.observation}</span> : null}- </div>- ))}- {t.appliedActions ? (- <UndoAgentWorkButton baseline={t.baseline} onUndo={undoAgentWork} />- ) : null}- </div>- )}</div>- {t.role === 'user' && (- <div className="h-6 w-6 rounded-lg bg-white/10 flex items-center justify-center text-white/60 shrink-0 mt-0.5">- <User size={13} />+ ) : (+ <div key={i} className="flex gap-2">+ <div className="w-6 h-6 shrink-0 rounded-full bg-[#7630D7]/20 flex items-center justify-center">+ <Bot size={12} className="text-[#a78bfa]" /></div>- )}- </div>- ))}+ <div className="min-w-0 flex-1 space-y-2">+ {turn.mode && (+ <div className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wide text-white/40">+ <Scissors size={10} /> {turn.mode} mode+ {READ_ONLY_MODES.includes(turn.mode) && <span className="text-[#02C0CC]">· read-only</span>}+ </div>+ )}+ {turn.steps && turn.steps.length > 0 && (+ <details className="rounded-xl border border-white/8 bg-white/[0.03] overflow-hidden">+ <summary className="px-3 py-2 text-[11px] font-semibold text-white/60 cursor-pointer flex items-center gap-1.5">+ <ListChecks size={12} /> {turn.steps.length} steps · {turn.appliedActions ?? 0} actions+ </summary>+ <ol className="px-3 pb-2 space-y-1.5">+ {turn.steps.map((s, j) => (+ <li key={j} className="text-[11px] text-white/50 leading-relaxed">+ <span className="text-white/80 font-mono">{s.tool}</span>+ {s.thought && <span> — {s.thought}</span>}+ {s.observation && <div className="text-white/40">{s.observation}</div>}+ </li>+ ))}+ </ol>+ </details>+ )}+ {turn.plan && turn.plan.length > 0 && (+ <div className="rounded-xl border border-[#02C0CC]/25 bg-[#02C0CC]/8 px-3 py-2">+ <p className="text-[10px] font-bold uppercase tracking-wide text-[#02C0CC] mb-1">Proposed plan</p>+ <ol className="space-y-0.5">+ {turn.plan.map((p, j) => (+ <li key={j} className="text-[11.5px] text-white/75">{j + 1}. {p}</li>+ ))}+ </ol>+ </div>+ )}+ {turn.findings && turn.findings.length > 0 && (+ <div className="rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2 space-y-1.5">+ <p className="text-[10px] font-bold uppercase tracking-wide text-white/50">Findings</p>+ {turn.findings.slice(0, 8).map((f, j) => (+ <div key={j} className="text-[11.5px] leading-relaxed">+ <span+ className={cn(+ 'inline-block px-1.5 rounded text-[10px] font-bold mr-1.5',+ f.severity === 'P0' && 'bg-red-500/20 text-red-300',+ f.severity === 'P1' && 'bg-amber-500/20 text-amber-300',+ f.severity === 'P2' && 'bg-blue-500/20 text-blue-300',+ f.severity === 'P3' && 'bg-white/10 text-white/50',+ )}+ >+ {f.severity}+ </span>+ <span className="text-white/80">{f.issue}</span>+ {f.fix && <span className="text-white/45"> → {f.fix}</span>}+ </div>+ ))}+ </div>+ )}+ <div className="text-[12.5px] text-white/85 leading-relaxed whitespace-pre-wrap">{turn.content}</div>+ {turn.verification && (+ <div className="flex items-start gap-1.5 text-[11px] text-emerald-300/80">+ <CheckCircle2 size={12} className="mt-0.5 shrink-0" />+ <span>{turn.verification}</span>+ </div>+ )}+ {turn.usage && (+ <div className="flex items-center gap-2 text-[10px] text-white/35">+ <Gauge size={10} />+ <span>+ {turn.usage.turns} turns · {turn.usage.toolCalls} tools · {Math.round(turn.usage.elapsedMs / 1000)}s · {turn.usage.modelCalls} model calls+ </span>+ </div>+ )}+ {turn.appliedActions ? (+ turn.baseline !== undefined && (+ <button onClick={undoAgentWork} className="flex items-center gap-1 text-[11px] font-semibold text-white/50 hover:text-white transition-colors">+ <Undo2 size={11} /> Undo agent work+ </button>+ )+ ) : null}+ </div>+ </div>+ ),+ )}- {/* live run */}+ {/* the live run */}{busy && (<div className="flex gap-2">- <div className="h-6 w-6 rounded-lg bg-brand-gradient flex items-center justify-center text-white shrink-0 mt-0.5 animate-pulse">- <Bot size={13} />+ <div className="w-6 h-6 shrink-0 rounded-full bg-[#7630D7]/20 flex items-center justify-center animate-pulse">+ <Bot size={12} className="text-[#a78bfa]" /></div>- <div className="max-w-[85%] rounded-2xl rounded-tl-sm bg-white/[0.05] px-3 py-2">- {liveSteps.length === 0 && (- <div className="flex items-center gap-2 text-[12px] text-white/60">- <Loader2 size={13} className="animate-spin" /> Thinking…+ <div className="min-w-0 flex-1 space-y-2">+ {liveMode && (+ <div className="flex flex-wrap items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wide text-white/40">+ <span>{liveMode} mode</span>+ {liveSkills.map((s) => (+ <span key={s} className="px-1.5 rounded bg-[#02C0CC]/10 text-[#02C0CC] normal-case">{s}</span>+ ))}</div>)}- <div className="space-y-1">- {liveSteps.map((s) => (- <div key={s.index} className="text-[11px] leading-snug" data-testid="agent-live-step">- <span className={cn('font-semibold', s.observation ? 'text-[#7BE8EC]' : 'text-[#02C0CC]')}>- {s.observation ? '✓' : '…'} {s.tool}- </span>- {s.thought ? <span className="text-white/50"> — {s.thought}</span> : null}- {s.observation ? <span className="block text-white/40">{s.observation}</span> : null}+ {liveBrief && (liveBrief.requiredTexts.length > 0 || liveBrief.requiredColors.length > 0) && (+ <div className="rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2">+ <p className="text-[10px] font-bold uppercase tracking-wide text-white/50 mb-1">Brief contract (exact)</p>+ <div className="flex flex-wrap gap-1.5">+ {liveBrief.requiredTexts.map((t, i) => (+ <span key={i} className="px-1.5 py-0.5 rounded bg-white/8 text-[10.5px] text-white/80 font-medium">“{t.text}”</span>+ ))}+ {liveBrief.requiredColors.map((c, i) => (+ <span key={i} className="px-1.5 py-0.5 rounded bg-white/8 text-[10.5px] text-white/80 font-mono flex items-center gap-1">+ <span className="w-2.5 h-2.5 rounded-sm inline-block" style={{ background: c.hex }} />+ {c.hex.toUpperCase()}+ </span>+ ))}</div>- ))}+ </div>+ )}+ {liveSteps.map((s, i) => (+ <div key={i} className="rounded-lg border border-white/8 bg-white/[0.02] px-2.5 py-1.5">+ <div className="text-[11px] font-mono text-white/75">{s.tool}</div>+ {s.thought && <div className="text-[10.5px] text-white/45">{s.thought}</div>}+ {s.observation && <div className="text-[10.5px] text-emerald-300/70 mt-0.5">{s.observation}</div>}+ </div>+ ))}+ <div className="flex items-center gap-2 text-[11px] text-white/40">+ <Loader2 size={12} className="animate-spin" />+ {pendingConfirm ? 'Waiting for your approval…' : 'Working…'}+ {liveUsage && (+ <span className="text-white/30">+ · {liveUsage.toolCalls} tools · {Math.round(liveUsage.elapsedMs / 1000)}s+ </span>+ )}+ <button onClick={stop} className="ml-auto flex items-center gap-1 px-2 h-6 rounded-full bg-red-500/15 text-red-300 text-[10.5px] font-semibold hover:bg-red-500/25 transition-colors">+ <Square size={9} /> Stop+ </button></div>- <button- onClick={stop}- className="mt-2 inline-flex items-center gap-1 rounded-full border border-white/12 px-2.5 py-1 text-[10px] font-semibold text-white/60 hover:text-white hover:border-white/30 transition-colors"- data-testid="agent-stop"- >- <Square size={9} /> Stop (keeps applied work)- </button></div></div>)}{/* destructive confirmation */}{pendingConfirm && (- <div className="rounded-2xl border border-[#FF8A8A]/30 bg-[#FF8A8A]/10 px-3 py-2.5" data-testid="agent-confirm">- <div className="flex items-center gap-1.5 text-[11.5px] font-bold text-[#FFB4B4]">- <ShieldAlert size={13} /> {pendingConfirm.tool.replace('_', ' ')} — needs your OK+ <div className="rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-2.5" data-testid="agent-confirm">+ <div className="flex items-center gap-1.5 text-[12px] font-bold text-amber-200 mb-1">+ <ShieldAlert size={13} /> Approve {pendingConfirm.tool.replace(/_/g, ' ')}?</div>- <div className="mt-1.5 space-y-1">- {pendingConfirm.actions.slice(0, 3).map((a, j) => (- <div key={j} className="text-[11px] text-white/70 flex items-center gap-1.5">- <Wand2 size={10} className="text-[#FF8A8A] shrink-0" /> {describeAction(a)}- </div>+ <ul className="mb-2 space-y-0.5">+ {pendingConfirm.actions.map((a, i) => (+ <li key={i} className="text-[11px] text-amber-100/70">· {describeAction(a)}</li>))}- </div>- <div className="mt-2 flex gap-2">- <button- onClick={() => void resolveConfirm(true)}- className="rounded-full bg-[#FF5C5C] hover:bg-[#ff7676] px-3 py-1 text-[11px] font-bold text-white transition-colors"- >- Yes, do it+ </ul>+ <div className="flex gap-2">+ <button onClick={() => resolveConfirm(true)} className="px-3 h-7 rounded-lg bg-amber-500 text-black text-[11.5px] font-bold hover:bg-amber-400 transition-colors">+ Approve once</button>- <button- onClick={() => void resolveConfirm(false)}- className="rounded-full border border-white/15 px-3 py-1 text-[11px] font-bold text-white/70 hover:text-white hover:border-white/35 transition-colors"- >- Skip this+ <button onClick={() => resolveConfirm(false)} className="px-3 h-7 rounded-lg bg-white/10 text-white/80 text-[11.5px] font-semibold hover:bg-white/15 transition-colors">+ Decline</button></div></div>)}</div>- {/* input */}- <form- className="mt-2.5 flex gap-1.5"- onSubmit={(e) => {- e.preventDefault()- void send(input)- }}- >- <input- value={input}- onChange={(e) => setInput(e.target.value)}- placeholder={busy ? 'Agent is working…' : 'Describe a change or a whole design…'}- disabled={busy || !!pendingConfirm}- className="flex-1 h-9 rounded-xl bg-white/[0.06] border border-white/12 px-3 text-[12px] text-white placeholder:text-white/30 outline-none focus:border-[#7630D7] transition-colors disabled:opacity-50"- aria-label="Message the design agent"- maxLength={2000}- />- <button- type="submit"- disabled={busy || !input.trim() || !!pendingConfirm}- className="h-9 w-9 rounded-xl btn-brand-gradient flex items-center justify-center text-white disabled:opacity-40 transition-opacity"- aria-label="Send"- >- {busy ? <Loader2 size={14} className="animate-spin" /> : <Send size={14} />}- </button>- </form>- {canUndo && !busy && (- <button- onClick={() => useEditorStore.getState().undo()}- className="mt-1.5 self-start inline-flex items-center gap-1 text-[10px] font-semibold text-white/35 hover:text-white/70 transition-colors"- >- <Undo2 size={10} /> Undo last change (Ctrl+Z)- </button>- )}+ {/* composer */}+ <div className="p-3 border-t border-white/5">+ <div className="flex items-end gap-2">+ <textarea+ value={input}+ onChange={(e) => setInput(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter' && !e.shiftKey) {+ e.preventDefault()+ send(input)+ }+ }}+ rows={1}+ placeholder={pinnedMode !== 'auto' && READ_ONLY_MODES.includes(pinnedMode) ? `Ask for ${pinnedMode} (the design won't be modified)…` : 'Describe what to design or change…'}+ className="flex-1 resize-none max-h-28 rounded-xl bg-white/[0.05] border border-white/10 px-3 py-2 text-[12.5px] text-white placeholder:text-white/30 outline-none focus:border-[#7630D7]"+ data-testid="agent-input"+ />+ <button+ onClick={() => send(input)}+ disabled={busy || !input.trim()}+ className="w-9 h-9 shrink-0 rounded-xl bg-[#7630D7] flex items-center justify-center text-white disabled:opacity-30 transition-opacity"+ aria-label="Send"+ data-testid="agent-send"+ >+ <Send size={15} />+ </button>+ </div>+ <div className="flex items-center justify-between mt-1.5 text-[10px] text-white/30">+ <span>+ {pinnedMode === 'auto' ? 'Auto mode' : `${pinnedMode}${READ_ONLY_MODES.includes(pinnedMode as AgentMode) ? ' · read-only' : ''}`} · full editor access+ </span>+ {canUndo && <span>Undo available in the toolbar</span>}+ </div>+ </div></div>)}--/** the per-run Undo button — renders only while the run still has- * rewinds left (avoids reading the store during render for stale turns) */-function UndoAgentWorkButton({ baseline, onUndo }: { baseline: number | undefined; onUndo: (b: number) => void }) {- const pastLen = useEditorStore((s) => s.past.length)- if (baseline === undefined || pastLen <= baseline) return null- return (- <button- onClick={() => onUndo(baseline)}- className="mt-1 inline-flex items-center gap-1 text-[10px] font-semibold text-white/40 hover:text-white/80 underline underline-offset-2"- >- <Undo2 size={10} /> Undo agent work- </button>- )-}diff --git a/src/lib/agent/brief.ts b/src/lib/agent/brief.tsnew file mode 100644index 0000000..e7b657e--- /dev/null+++ b/src/lib/agent/brief.ts@@ -0,0 +1,256 @@+// ─────────────────────────────────────────────────────────────+// Design Brief Contract (v0.28, Phase 5).+//+// The anti-hallucination core: explicit user requirements are+// extracted into a TYPED contract BEFORE any generation, marked+// mandatory vs preference, and every completion claim is validated+// against the REAL refreshed canvas state. The agent may not+// substitute "Creative Pulse" for "Design Beyond Limits" because+// the exact strings are contract fields the validator checks.+//+// Extraction is heuristic + model-assisted: the ROUTE parses the+// user message into a draft contract (this module's `extractBrief`+// runs server-side, zero model calls — quoted strings, hex colors,+// dimensions, platform keywords); the loop's first model turn may+// refine it (plan step). Explicit values are IMMUTABLE after+// extraction — brand kits/templates/creativity may only FILL GAPS,+// never override (Phase 5 rule).+// ─────────────────────────────────────────────────────────────++export interface BriefConstraint {+ /** where it came from — mandatory items fail validation when missing */+ tier: 'mandatory' | 'preference' | 'optional'+}++export interface DesignBrief {+ /** exact strings the user quoted or demanded — checked verbatim */+ requiredTexts: (BriefConstraint & { text: string; role?: string })[]+ /** exact hex colors — checked case-insensitively against the page */+ requiredColors: (BriefConstraint & { hex: string; role?: string })[]+ /** canvas dimensions in px */+ dimensions?: BriefConstraint & { width: number; height: number }+ /** detected platform/format ("instagram-post", "story", "poster"…) */+ format?: string+ /** design type noun ("poster", "menu", "deck", "thumbnail"…) */+ designType?: string+ /** things the user explicitly forbade */+ restrictions: string[]+ /** free-text extras the validator can't check mechanically */+ notes: string[]+ /** platform presets used to fill dimensions when unspecified */+ source: 'user' | 'model-refined'+}++const HEX_RE = /#([0-9a-fA-F]{6})\b/g+const QUOTED_RE = /[“"']([^“"']{2,80})[”"']/g++/** Known platform presets — fills dimensions only when the user+ * did NOT state any. Never overrides an explicit size. */+export const FORMAT_PRESETS: Record<string, { width: number; height: number; label: string }> = {+ 'instagram-post': { width: 1080, height: 1080, label: 'Instagram post (1080×1080)' },+ 'instagram-square': { width: 1080, height: 1080, label: 'Instagram square (1080×1080)' },+ 'instagram-portrait': { width: 1080, height: 1350, label: 'Instagram portrait (1080×1350)' },+ story: { width: 1080, height: 1920, label: 'Story (1080×1920)' },+ 'reel-cover': { width: 1080, height: 1920, label: 'Reel cover (1080×1920)' },+ poster: { width: 1240, height: 1754, label: 'Poster A4 @150dpi (1240×1754)' },+ flyer: { width: 1240, height: 1754, label: 'Flyer A4 (1240×1754)' },+ 'a4': { width: 1240, height: 1754, label: 'A4 @150dpi (1240×1754)' },+ 'youtube-thumbnail': { width: 1280, height: 720, label: 'YouTube thumbnail (1280×720)' },+ thumbnail: { width: 1280, height: 720, label: 'Thumbnail (1280×720)' },+ 'linkedin-post': { width: 1200, height: 1200, label: 'LinkedIn post (1200×1200)' },+ 'linkedin-banner': { width: 1584, height: 396, label: 'LinkedIn banner (1584×396)' },+ 'facebook-cover': { width: 1640, height: 924, label: 'Facebook cover (1640×924)' },+ 'twitter-header': { width: 1500, height: 500, label: 'X/Twitter header (1500×500)' },+ presentation: { width: 1920, height: 1080, label: 'Presentation (1920×1080)' },+ slide: { width: 1920, height: 1080, label: 'Slide (1920×1080)' },+ deck: { width: 1920, height: 1080, label: 'Deck (1920×1080)' },+ 'business-card': { width: 1050, height: 600, label: 'Business card (1050×600)' },+ menu: { width: 1240, height: 1754, label: 'Menu (1240×1754)' },+ logo: { width: 1000, height: 1000, label: 'Logo canvas (1000×1000)' },+}++const FORMAT_HINTS: [RegExp, string][] = [+ // order matters: story/reel before the generic instagram hint+ [/\b(?:instagram\s*)?(?:story|reel)\b/, 'story'],+ [/\byoutube\b.*\bthumbnail\b|\bthumbnail\b/, 'youtube-thumbnail'],+ [/\bposter\b/, 'poster'],+ [/\bflyer\b/, 'flyer'],+ [/\bmenu\b/, 'menu'],+ [/\blogo\b/, 'logo'],+ [/\b(business\s*card)\b/, 'business-card'],+ [/\b(linkedin|fb|facebook)\b.*\b(banner|cover|header)\b/, 'linkedin-banner'],+ [/\bfacebook\b.*\bcover\b|\bfb\s*cover\b/, 'facebook-cover'],+ [/\b(twitter|x)\b.*\bheader\b/, 'twitter-header'],+ [/\b(presentation|slide|deck|pitch)\b/, 'presentation'],+ [/\binstagram\b/, 'instagram-post'],+ [/\bbanner\b/, 'linkedin-banner'],+]++const DIMENSIONS_RE = /(\d{3,5})\s*[x×by]\s*(\d{3,5})/++/** Heuristic, deterministic brief extraction — no model calls.+ * Everything it finds is `mandatory` because the user typed it. */+export function extractBrief(message: string, pageWidth?: number, pageHeight?: number): DesignBrief {+ const m = message.trim()++ // exact quoted strings — the strongest signal ("Design Beyond Limits")+ const requiredTexts: DesignBrief['requiredTexts'] = []+ const seen = new Set<string>()+ for (const q of m.matchAll(QUOTED_RE)) {+ const text = q[1].trim()+ if (text.length >= 2 && !seen.has(text.toLowerCase())) {+ seen.add(text.toLowerCase())+ requiredTexts.push({ tier: 'mandatory', text })+ }+ }+ // "headline X", "say Y", "text Z" unquoted patterns → mandatory too+ for (const mm of m.matchAll(/\b(?:headline|title|heading|saying|text|tagline|copy|cta)\s*(?:should\s*(?:be|say|read)|:|=|is|says|reads)?\s*[“"']?([A-Z][^.\n“"']{2,80})[”"']?/gi)) {+ const text = mm[1].trim()+ if (text && !seen.has(text.toLowerCase())) {+ seen.add(text.toLowerCase())+ requiredTexts.push({ tier: 'mandatory', text, role: 'heading' })+ }+ }++ // exact hex colors+ const requiredColors: DesignBrief['requiredColors'] = []+ const seenHex = new Set<string>()+ for (const mm of m.matchAll(HEX_RE)) {+ const hex = `#${mm[1].toLowerCase()}`+ if (!seenHex.has(hex)) {+ seenHex.add(hex)+ requiredColors.push({ tier: 'mandatory', hex })+ }+ }++ // explicit dimensions+ const dims = m.match(DIMENSIONS_RE)+ let dimensions: DesignBrief['dimensions'] | undefined+ if (dims) {+ const w = Number(dims[1])+ const h = Number(dims[2])+ if (w >= 50 && w <= 10000 && h >= 50 && h <= 10000) {+ dimensions = { tier: 'mandatory', width: w, height: h }+ }+ }++ // format detection+ const lower = m.toLowerCase()+ let format: string | undefined+ for (const [re, id] of FORMAT_HINTS) {+ if (re.test(lower)) {+ format = id+ break+ }+ }+ // format fills dimensions ONLY when none were explicit+ if (!dimensions && format && FORMAT_PRESETS[format]) {+ const preset = FORMAT_PRESETS[format]+ dimensions = { tier: 'preference', width: preset.width, height: preset.height }+ }+ // last resort: the current page (edit mode keeps the user's canvas)+ if (!dimensions && pageWidth && pageHeight) {+ dimensions = { tier: 'preference', width: pageWidth, height: pageHeight }+ }++ // design type noun+ const typeMatch = lower.match(/\b(poster|flyer|menu|logo|banner|thumbnail|deck|presentation|slide|business\s*card|infographic|campaign|invitation|certificate|resume|newsletter|ad|advert|social\s*media\s*post)\b/)+ const designType = typeMatch ? typeMatch[1].replace(/\s+/g, ' ') : undefined++ // restrictions+ const restrictions: string[] = []+ for (const mm of m.matchAll(/\b(?:no|don'?t|without|avoid)\s+([a-z][a-z\s-]{2,30})/gi)) {+ restrictions.push(`no ${mm[1].trim()}`)+ }++ return {+ requiredTexts,+ requiredColors,+ dimensions,+ format,+ designType,+ restrictions,+ notes: [],+ source: 'user',+ }+}++/** Case-insensitive hex equality ("#FFFFFF" === "#ffffff"). */+function hexEq(a: string, b: string): boolean {+ return a.toLowerCase() === b.toLowerCase()+}++export interface BriefValidationResult {+ /** all mandatory constraints satisfied against the REAL state */+ satisfied: boolean+ unmet: string[]+ checked: {+ text: { text: string; found: boolean }[]+ color: { hex: string; found: boolean }[]+ dimensions?: { width: number; height: number; match: boolean }+ }+}++/** Validate a brief against REAL page state (post-apply, refreshed).+ * Pure — the caller supplies what the client sent back. */+export function validateBrief(+ brief: DesignBrief,+ state: {+ texts: string[]+ /** every color on the page: fills, strokes, text colors, backgrounds */+ colors: string[]+ width: number+ height: number+ },+): BriefValidationResult {+ const unmet: string[] = []+ const text = brief.requiredTexts+ .filter((t) => t.tier === 'mandatory')+ .map((t) => {+ // case-insensitive + whitespace-tolerant containment: catches+ // the user's copy through case/wrap variations while still+ // rejecting substitutions ("Creative Pulse" ≠ "Design Beyond+ // Limits"). Hex colors are case-insensitive the same way.+ const wanted = t.text.replace(/\s+/g, ' ').trim().toLowerCase()+ const found = state.texts.some((s) => s.replace(/\s+/g, ' ').trim().toLowerCase().includes(wanted))+ if (!found) unmet.push(`Required text missing or altered: "${t.text}"`)+ return { text: t.text, found }+ })+ const color = brief.requiredColors+ .filter((c) => c.tier === 'mandatory')+ .map((c) => {+ const found = state.colors.some((s) => hexEq(s, c.hex))+ if (!found) unmet.push(`Required color #${c.hex.slice(1).toUpperCase()} not used anywhere on the page`)+ return { hex: c.hex, found }+ })+ let dimensions: BriefValidationResult['checked']['dimensions']+ if (brief.dimensions && brief.dimensions.tier === 'mandatory') {+ const match = state.width === brief.dimensions.width && state.height === brief.dimensions.height+ dimensions = { width: brief.dimensions.width, height: brief.dimensions.height, match }+ if (!match) {+ unmet.push(`Canvas must be ${brief.dimensions.width}×${brief.dimensions.height} (currently ${state.width}×${state.height})`)+ }+ }+ return { satisfied: unmet.length === 0, unmet, checked: { text, color, dimensions } }+}++/** Compact one-line serialization for the system prompt. */+export function briefPromptSection(brief: DesignBrief): string {+ const parts: string[] = ['DESIGN BRIEF CONTRACT (extracted from the user — MANDATORY, never substitute):']+ if (brief.designType) parts.push(`· Type: ${brief.designType}`)+ if (brief.format) parts.push(`· Format: ${brief.format}`)+ if (brief.dimensions) {+ parts.push(`· Canvas: ${brief.dimensions.width}×${brief.dimensions.height}px${brief.dimensions.tier === 'mandatory' ? ' (exact)' : ' (suggested)'}`)+ }+ if (brief.requiredTexts.length) {+ parts.push(`· EXACT text (copy character-for-character): ${brief.requiredTexts.map((t) => `"${t.text}"`).join(' ')}`)+ }+ if (brief.requiredColors.length) {+ parts.push(`· EXACT colors (use these hex values verbatim): ${brief.requiredColors.map((c) => c.hex.toUpperCase()).join(' ')}`)+ }+ if (brief.restrictions.length) parts.push(`· Restrictions: ${brief.restrictions.join('; ')}`)+ if (brief.notes.length) parts.push(`· Notes: ${brief.notes.join('; ')}`)+ parts.push('Brand kit and templates may FILL GAPS only — they never override the exact values above.')+ parts.push('You are not done until validate_brief passes or every mandatory item is verifiably present.')+ return parts.join('\n')+}diff --git a/src/lib/agent/harness.test.ts b/src/lib/agent/harness.test.tsindex a7f4b42..a7a0550 100644--- a/src/lib/agent/harness.test.ts+++ b/src/lib/agent/harness.test.ts@@ -1,37 +1,35 @@// ─────────────────────────────────────────────────────────────-// The comprehensive agent harness (v0.27.3) — "test it thoroughly,-// not one simple case". Four layers:+// The v0.28 agent harness — "test it thoroughly, not one simple+// case". Layers://-// 1. TOOL MATRIX — every registered tool × valid / invalid /-// boundary args, asserting both the accept and-// the actionable-error contract.-// 2. LOOP FLOWS — realistic multi-step runs (poster build,-// page-switch flow, stock-photo flow, repair,-// budget exhaustion, confirm gates, abort).-// 3. WIRE FORMAT — sseLine/parseAgentTurn round-trips, event-// versioning, malformed-line tolerance.-// 4. ROUTER MATRIX — heuristic + parseIntent across phrasings.+// 1. TOOL MATRIX — every registered tool × valid/invalid/+// boundary/adversarial args; registry+// coverage forces new tools to add cases.+// 2. MODES — mode tool surfaces (review physically+// cannot write), heuristic classification.+// 3. BRIEF CONTRACT — extraction (exact texts/colors/dims) and+// validation against real state.+// 4. SKILLS ENGINE — router matching, prompt injection,+// progressive disclosure contract.+// 5. LIFECYCLE FLOWS — Case A exact-copy poster; Case B review+// grounding; Case C long run (>8 steps, no+// cap); Case D geometry repair; Case E+// capability sweep; Case F safety (strikes,+// cycles, abort, decline, provider failure).+// 6. WIRE FORMAT — SSE round-trips, parser robustness.//-// The "LLM" is a scripted queue — deterministic, no network. The-// harness asserts the INVARIANTS the real model relies on:-// · every rejected call returns an error that names the fix-// · actions the client must apply are always well-formed-// · budgets can never be exceeded, and free retries stay free-// · destructive tools never apply without an explicit approval+// The "LLM" is a scripted queue — deterministic, no network.// ─────────────────────────────────────────────────────────────import { describe, it, expect } from 'vitest'-import {- parseAgentTurn,- sseLine,- AGENT_BUDGETS,- AGENT_PROTOCOL_VERSION,- type AgentEvent,-} from './protocol'-import { AGENT_TOOL_MAP, AGENT_TOOLS, toolsPromptSection, type ToolContext, type SanitizeResult } from './tools'-import { runAgentLoop, loopSystemPrompt } from './loop'-import { heuristicIntent, parseIntent } from './router'+import { parseAgentTurn, sseLine, AGENT_GUARDS, AGENT_PROTOCOL_VERSION, type AgentEvent } from './protocol'+import { AGENT_TOOL_MAP, AGENT_TOOLS, type ToolContext, type SanitizeResult } from './tools'+import { runAgentLoop, toolsForMode, loopSystemPrompt } from './loop'+import { heuristicMode, parseMode, modeAllowsWrites, MODE_TOOL_RISK } from './router'+import { DESIGN_SKILLS, selectSkills, skillsPromptSection } from './skills'+import { extractBrief, validateBrief, briefPromptSection, FORMAT_PRESETS, type DesignBrief } from './brief'import { serializeDesignContext, contextValidIds, type AgentDesignCtx } from './context'+import type { AgentMode } from './protocol'// ── fixtures ─────────────────────────────────────────────────@@ -78,689 +76,832 @@ function scriptedChat(replies: string[]) {const turn = (tool: string, args: Record<string, unknown> = {}, thought = 'step') =>JSON.stringify({ thought, tool, args })-const done = (summary: string) => JSON.stringify({ done: true, summary })+const done = (summary: string, extra: Record<string, unknown> = {}) =>+ JSON.stringify({ done: true, summary, ...extra })// ═════════════════════════════════════════════════════════════-// 1. TOOL MATRIX — every tool, valid + invalid + boundary+// 1. TOOL MATRIX// ═════════════════════════════════════════════════════════════describe('harness · tool matrix', () => {const tool = (name: string) => {const t = AGENT_TOOL_MAP.get(name)- if (!t) throw new Error(`tool "${name}" is not registered — harness covers every tool`)+ if (!t) throw new Error(`tool "${name}" is not registered`)return t}const call = (name: string, args: Record<string, unknown>, c: ToolContext = ctx): SanitizeResult =>tool(name).sanitize(args, c)it('every tool in the registry is covered by this harness', () => {- // the source of truth: if a tool is added without harness coverage,- // this fails and forces the author to add cases belowconst covered = ['get_page_state', 'add_text', 'add_shape', 'add_image', 'add_stock_photo', 'add_sticker','add_table', 'update_elements', 'set_text_style', 'move_elements', 'align_elements','distribute_elements', 'set_background', 'set_font', 'recolor', 'add_page', 'duplicate_page','goto_page', 'fix_overlaps', 'balance_layout', 'animate_page', 'translate_texts','delete_elements', 'clear_page',+ // v0.28 bridge tools+ 'add_line', 'add_icon', 'add_illustration', 'add_chart', 'add_qr', 'add_frame', 'add_embed',+ 'duplicate_elements', 'group_elements', 'ungroup_elements', 'reorder_layers',+ 'animate_elements', 'set_page_transition', 'delete_page', 'set_brand_kit', 'resize_design',+ 'mask_image', 'adjust_image', 'measure_text', 'set_text_spans', 'export_design',+ 'add_stock_video', 'validate_brief',]- for (const t of AGENT_TOOLS) expect(covered).toContain(t.name)+ for (const t of AGENT_TOOLS) expect(covered, `add harness cases for new tool "${t.name}"`).toContain(t.name)expect(covered).toHaveLength(AGENT_TOOLS.length)- })-- // ── add_text ─────────────────────────────────────────────- it('add_text: valid full args', () => {- const r = call('add_text', { text: 'Grand Opening', fontSize: 96, x: 80, y: 120, width: 900, color: '#7D2AE8', bold: true, align: 'left' })- expect(r.ok).toBe(true)- if (r.ok) expect(r.actions[0]).toMatchObject({ type: 'addText', text: 'Grand Opening', fontSize: 96, color: '#7d2ae8', bold: true, align: 'left' })- })- it('add_text: yBand rides when y is absent', () => {- const r = call('add_text', { text: 'Sub', yBand: 'bottom' })- expect(r.ok).toBe(true)- if (r.ok) expect(r.actions[0]).toMatchObject({ y: 'bottom' })- })- it('add_text: exact y overrides yBand', () => {- const r = call('add_text', { text: 'Sub', y: 500, yBand: 'top' })- expect(r.ok).toBe(true)- if (r.ok) expect(r.actions[0]).toMatchObject({ y: 500 })- if (r.ok) expect(r.actions[0].yBand).toBeUndefined()- })- it('add_text: boundary fontSize 6 and 400 pass, 5 and 401 fail with the range echoed', () => {- expect(call('add_text', { text: 'x', fontSize: 6 }).ok).toBe(true)- expect(call('add_text', { text: 'x', fontSize: 400 }).ok).toBe(true)- for (const bad of [5, 401, 1200]) {- const r = call('add_text', { text: 'x', fontSize: bad })- expect(r.ok).toBe(false)- if (!r.ok) expect(r.error).toContain(String(bad))- }- })- it('add_text: empty text and bad color rejected with actionable errors', () => {- expect(call('add_text', { text: ' ' }).ok).toBe(false)- const r = call('add_text', { text: 'x', color: 'purple' })- expect(r.ok).toBe(false)- if (!r.ok) expect(r.error).toContain('#RRGGBB')- })- it('add_text: unknown font rejected with valid examples listed', () => {- const r = call('add_text', { text: 'x', fontFamily: 'Comic Sans' })- expect(r.ok).toBe(false)- if (!r.ok) {- expect(r.error).toContain('Comic Sans')- expect(r.error).toContain('Poppins')- }- })- it('add_text: 400-char text is trimmed at the cap (no prompt injection via overflow)', () => {- const r = call('add_text', { text: 'A'.repeat(900) })- expect(r.ok).toBe(true)- if (r.ok) expect((r.actions[0].text as string).length).toBeLessThanOrEqual(400)- })-- // ── add_shape ────────────────────────────────────────────- it('add_shape: every shape kind accepts and compiles', () => {- for (const shape of ['rect', 'ellipse', 'triangle', 'star', 'line']) {- const r = call('add_shape', { shape, x: 10, y: 10, width: 100, height: 80 })- expect(r.ok, shape).toBe(true)- if (r.ok) expect(r.actions[0]).toMatchObject({ type: 'addShape', shape })- }- })- it('add_shape: missing numbers and tiny sizes rejected naming the field', () => {- const r1 = call('add_shape', { shape: 'rect', x: 1, y: 1 })- expect(r1.ok).toBe(false)- if (!r1.ok) expect(r1.error).toContain('width')- const r2 = call('add_shape', { shape: 'rect', x: 1, y: 1, width: 2, height: 80 })- expect(r2.ok).toBe(false)- if (!r2.ok) expect(r2.error).toContain('≥ 4')- expect(call('add_shape', { shape: 'hexagon', x: 1, y: 1, width: 50, height: 50 }).ok).toBe(false)- })-- // ── add_image / add_stock_photo ──────────────────────────- it('add_image: prompt validation + placement clamps', () => {- expect(call('add_image', { prompt: 'ok' }).ok).toBe(false)- const r = call('add_image', { prompt: 'an abstract gradient banner', x: -50, y: 2000, width: 5000 })- expect(r.ok).toBe(true)- if (r.ok) {- expect(r.actions[0]).toMatchObject({ type: 'generateImage', prompt: 'an abstract gradient banner' })- expect(r.actions[0].x).toBe(0) // clamped into the page- expect(r.actions[0].width).toBe(1080) // clamped to page width- }- })- it('add_stock_photo: query + orientation validation, compiles addStockPhoto action', () => {- expect(call('add_stock_photo', { query: 'a' }).ok).toBe(false)- for (const orientation of ['landscape', 'portrait', 'square']) {- const r = call('add_stock_photo', { query: 'coffee cup on a wooden table', orientation })- expect(r.ok, orientation).toBe(true)- if (r.ok) expect(r.actions[0]).toMatchObject({ type: 'addStockPhoto', query: 'coffee cup on a wooden table', orientation })- }- const bad = call('add_stock_photo', { query: 'coffee', orientation: 'diagonal' })- expect(bad.ok).toBe(true) // unknown enum falls back — no orientation filter- if (bad.ok) expect(bad.actions[0].orientation).toBeUndefined()- })-- // ── add_sticker / add_table ──────────────────────────────- it('add_sticker: emoji required, size bounds', () => {- expect(call('add_sticker', { emoji: '' }).ok).toBe(false)- expect(call('add_sticker', { emoji: '🚀', size: 10 }).ok).toBe(false)- const r = call('add_sticker', { emoji: '✨', size: 200 })- expect(r.ok).toBe(true)- if (r.ok) expect(r.actions[0]).toMatchObject({ type: 'addSticker', emoji: '✨', size: 200 })- })- it('add_table: header/rows validation + cell caps', () => {- expect(call('add_table', { header: [], rows: [['a']] }).ok).toBe(false)- expect(call('add_table', { header: ['A'], rows: [] }).ok).toBe(false)- const r = call('add_table', {- header: ['Plan', 'Price', 'Seats'],- rows: [- ['Free', '$0', '1'],- ['Pro', '$12', '5'],- ['Team', '$49', '25'],- ],- })- expect(r.ok).toBe(true)- if (r.ok) expect(r.actions[0]).toMatchObject({ type: 'addTable', header: ['Plan', 'Price', 'Seats'] })- })-- // ── update_elements / set_text_style ─────────────────────- it('update_elements: full patch surface, one action per call', () => {+ expect(AGENT_TOOLS.length).toBeGreaterThanOrEqual(46)+ })++ // ── v0.27 tools (regression) ─────────────────────────────+ it('core v0.27 tools still validate correctly', () => {+ expect(call('add_text', { text: 'Hi', fontSize: 6 }).ok).toBe(true)+ expect(call('add_text', { text: 'x', fontSize: 5 }).ok).toBe(false)+ expect(call('add_text', { text: 'x', fontFamily: 'Comic Sans' }).ok).toBe(false)+ expect(call('update_elements', { ids: ['ghost'], patch: { fill: '#123456' } }).ok).toBe(false)+ expect(call('update_elements', { ids: ['el-1'], patch: { fill: 'red' } }).ok).toBe(false)+ expect(call('distribute_elements', { ids: ['el-1', 'el-2'], axis: 'x' }).ok).toBe(false)+ expect(call('distribute_elements', { ids: ['el-1', 'el-2', 'img-1'], axis: 'x' }).ok).toBe(true)+ expect(call('goto_page', { page: 2 }).ok).toBe(true)+ expect(call('goto_page', { page: 0 }).ok).toBe(false)+ expect(tool('delete_elements').risk).toBe('destructive')+ expect(tool('clear_page').risk).toBe('destructive')+ })++ // ── extended update_elements patch surface ───────────────+ it('update_elements accepts the full v0.28 patch surface', () => {const r = call('update_elements', {- ids: ['el-1', 'el-2'],- patch: { x: 10, y: 20, width: 200, height: 100, rotation: 15, opacity: 0.5, fill: '#00AAFF', bold: true, align: 'right' },+ ids: ['el-1'],+ patch: { rotation: 45, opacity: 0.5, italic: true, uppercase: true, curve: 30, flipH: true, locked: true, visible: false, letterSpacing: 2, lineHeight: 1.4 },})expect(r.ok).toBe(true)- if (r.ok) expect(r.actions[0]).toMatchObject({ type: 'updateElements', ids: ['el-1', 'el-2'] })+ if (r.ok) {+ expect(r.actions[0].patch).toMatchObject({ rotation: 45, opacity: 0.5, curve: 30, locked: true })+ }})- it('update_elements: every invalid patch value is named', () => {+ it('update_elements rejects out-of-range curve/brightness with the range echoed', () => {for (const [patch, hint] of [- [{ fill: 'nope' }, '#RRGGBB'],- [{ fontSize: 900 }, '6–400'],+ [{ curve: 300 }, '−180..180'],+ [{ brightness: 400 }, '−100..100'],[{ opacity: 2 }, '0–1'],- [{ width: 'wide' }, 'number'],] as const) {const r = call('update_elements', { ids: ['el-1'], patch })expect(r.ok, JSON.stringify(patch)).toBe(false)if (!r.ok) expect(r.error).toContain(hint)}})- it('update_elements: stale/foreign ids rejected, valid ones listed', () => {- const r = call('update_elements', { ids: ['ghost-9'], patch: { fill: '#123456' } })- expect(r.ok).toBe(false)- if (!r.ok) expect(r.error).toContain('ghost-9')- if (!r.ok) expect(r.error).toContain('get_page_state')- })- it('set_text_style: font + size + color compile to one updateElements', () => {- const r = call('set_text_style', { ids: ['txt-1'], fontFamily: 'Poppins', fontSize: 64, bold: true, color: '#FF0055' })- expect(r.ok).toBe(true)- if (r.ok) expect(r.actions[0]).toMatchObject({ type: 'updateElements', ids: ['txt-1'], patch: { fontFamily: 'Poppins', fontSize: 64, bold: true, fill: '#ff0055' } })++ // ── new v0.28 tools: valid + invalid each ────────────────+ it('add_line validates geometry and variants', () => {+ expect(call('add_line', { x: 10, y: 10, length: 200, variant: 'arrow', stroke: '#123456' }).ok).toBe(true)+ expect(call('add_line', { x: 10, length: 200 }).ok).toBe(false) // no y+ expect(call('add_line', { x: 1, y: 1, length: 4 }).ok).toBe(false) // too short+ expect(call('add_line', { x: 1, y: 1, length: 200, stroke: 'blue' }).ok).toBe(false)+ })+ it('add_icon / add_illustration require queries', () => {+ expect(call('add_icon', { query: 'arrow right' }).ok).toBe(true)+ expect(call('add_icon', { query: 'a' }).ok).toBe(false)+ expect(call('add_illustration', { query: 'waves' }).ok).toBe(true)+ expect(call('add_illustration', { query: 'x' }).ok).toBe(false)+ })+ it('add_chart validates kind + series shape', () => {+ const ok = call('add_chart', {+ kind: 'bar',+ labels: ['Q1', 'Q2'],+ series: [{ name: 'Rev', color: '#7630D7', values: [10, 20] }],+ })+ expect(ok.ok).toBe(true)+ if (ok.ok) expect(ok.actions[0]).toMatchObject({ type: 'addChart', kind: 'bar' })+ expect(call('add_chart', { kind: 'pie' }).ok).toBe(false) // not a kind+ expect(call('add_chart', { kind: 'donut', series: [{ name: 'X', values: [1] }] }).ok).toBe(true) // 1-value series dropped → sample data+ })+ it('add_qr validates value + colors', () => {+ expect(call('add_qr', { value: 'https://canvix.app', dark: '#090B1A' }).ok).toBe(true)+ expect(call('add_qr', { value: '' }).ok).toBe(false)+ expect(call('add_qr', { value: 'x', dark: 'navy' }).ok).toBe(false)+ })+ it('add_frame / add_embed validate', () => {+ expect(call('add_frame', { frameShape: 'circle', width: 400, height: 400 }).ok).toBe(true)+ expect(call('add_frame', { frameShape: 'hexagon' }).ok).toBe(false)+ expect(call('add_embed', { url: 'https://youtu.be/x' }).ok).toBe(true)+ expect(call('add_embed', { url: 'ftp://nope' }).ok).toBe(false)+ })+ it('duplicate/group/ungroup/reorder validate id lists', () => {+ expect(call('duplicate_elements', { ids: ['el-1'] }).ok).toBe(true)+ expect(call('group_elements', { ids: ['el-1'] }).ok).toBe(false)+ expect(call('group_elements', { ids: ['el-1', 'el-2'] }).ok).toBe(true)+ expect(call('reorder_layers', { ids: ['el-1'], dir: 'front' }).ok).toBe(true)+ expect(call('reorder_layers', { ids: ['el-1'], dir: 'sideways' }).ok).toBe(false)+ expect(call('reorder_layers', { ids: ['el-1'] }).ok).toBe(false) // neither dir nor ≥2 ids+ })+ it('animate_elements + set_page_transition validate kinds', () => {+ expect(call('animate_elements', { ids: ['el-1'], kind: 'pop', duration: 0.4, direction: 'up' }).ok).toBe(true)+ expect(call('animate_elements', { ids: ['el-1'], kind: 'explode' }).ok).toBe(false)+ expect(call('set_page_transition', { kind: 'slide' }).ok).toBe(true)+ expect(call('set_page_transition', { kind: 'spin' }).ok).toBe(false)+ })+ it('delete_page is destructive and bounds-checks', () => {+ expect(tool('delete_page').risk).toBe('destructive')+ expect(call('delete_page', { page: 2 }).ok).toBe(true)+ expect(call('delete_page', { page: 0 }).ok).toBe(false)+ expect(call('delete_page', { page: 500 }).ok).toBe(false)+ })+ it('set_brand_kit validates fonts against the catalog', () => {+ expect(call('set_brand_kit', { colors: ['#090B1A', '#8B5CF6'], headingFont: 'Poppins' }).ok).toBe(true)+ expect(call('set_brand_kit', { headingFont: 'Wingdings' }).ok).toBe(false)+ expect(call('set_brand_kit', {}).ok).toBe(false)+ })+ it('resize_design validates the 50–10000 range', () => {+ expect(call('resize_design', { width: 1080, height: 1920 }).ok).toBe(true)+ expect(call('resize_design', { width: 10, height: 10 }).ok).toBe(false)+ expect(call('resize_design', { width: 99999, height: 10 }).ok).toBe(false)+ })+ it('mask_image / adjust_image validate masks and ranges', () => {+ expect(call('mask_image', { ids: ['img-1'], mask: 'circle' }).ok).toBe(true)+ expect(call('mask_image', { ids: ['img-1'], mask: 'blob' }).ok).toBe(false)+ expect(call('adjust_image', { ids: ['img-1'], brightness: 40, contrast: -20 }).ok).toBe(true)+ expect(call('adjust_image', { ids: ['img-1'], brightness: 400 }).ok).toBe(false)+ expect(call('adjust_image', { ids: ['el-1'], brightness: 10 }).ok).toBe(true) // ids valid; client filters to images+ })+ it('measure_text validates font + size and is read-only', () => {+ expect(tool('measure_text').risk).toBe('read')+ expect(call('measure_text', { text: 'Design Beyond Limits', fontSize: 96, fontFamily: 'Poppins', bold: true }).ok).toBe(true)+ expect(call('measure_text', { text: 'x', fontSize: 5 }).ok).toBe(false)+ expect(call('measure_text', { text: 'x', fontSize: 48, fontFamily: 'Nope' }).ok).toBe(false)+ })+ it('set_text_spans requires span arrays', () => {+ expect(call('set_text_spans', { ids: ['txt-1'], spans: [{ text: 'Hel' }, { text: 'lo', bold: true }] }).ok).toBe(true)+ expect(call('set_text_spans', { ids: ['txt-1'], spans: [] }).ok).toBe(false)+ expect(call('set_text_spans', { ids: ['txt-1'] }).ok).toBe(false)+ })+ it('export_design / add_stock_video / validate_brief compile', () => {+ expect(call('export_design', { format: 'png' }).ok).toBe(true)+ expect(call('export_design', { format: 'bmp' }).ok).toBe(true) // falls back to png client-side+ expect(call('add_stock_video', { query: 'city timelapse' }).ok).toBe(true)+ expect(call('add_stock_video', { query: 'ab' }).ok).toBe(false)+ expect(call('validate_brief', {}).ok).toBe(true)})- // ── move / align / distribute ────────────────────────────- it('move_elements: deltas clamp to ±2 pages; snap bands map', () => {- const r = call('move_elements', { ids: ['el-1'], dx: 99999, dy: -99999 })- expect(r.ok).toBe(true)- if (r.ok) expect(r.actions[0].dx).toBe(2160) // 2 × 1080- const snap = call('move_elements', { ids: ['el-1'], to: 'center' })- expect(snap.ok).toBe(true)- if (snap.ok) expect(snap.actions[0]).toMatchObject({ to: 'center' })- expect(call('move_elements', { ids: ['el-1'] }).ok).toBe(false) // neither dx/dy nor to- })- it('align_elements: all six modes accept; bad mode rejects', () => {- for (const mode of ['left', 'cx', 'right', 'top', 'cy', 'bottom']) {- expect(call('align_elements', { ids: ['el-1', 'el-2'], mode }).ok, mode).toBe(true)+ // ── universal invariants ─────────────────────────────────+ it('EVERY tool: sanitizers never throw on adversarial args', () => {+ const adversarial = [+ { ids: 'not-an-array', patch: { fill: { deep: 'object' } } },+ { text: { nested: true }, fontSize: NaN },+ { header: 'string', rows: 42, series: 'no' },+ { page: Infinity, factor: 'x', spans: 7 },+ { palette: 'no', ids: [null, 123, {}], values: [{ no: 'text' }] },+ { dx: '1e999', shape: { fake: 1 }, mask: { deep: 1 } },+ ]+ for (const t of AGENT_TOOLS) {+ for (const args of adversarial) {+ expect(() => t.sanitize(args as Record<string, unknown>, ctx), `${t.name} ${JSON.stringify(args).slice(0, 40)}`).not.toThrow()+ }}- expect(call('align_elements', { ids: ['el-1'], mode: 'diagonal' }).ok).toBe(false)})- it('distribute_elements: needs 3+ ids (client contract) and says what to use instead', () => {- const two = call('distribute_elements', { ids: ['el-1', 'el-2'], axis: 'x' })- expect(two.ok).toBe(false)- if (!two.ok) expect(two.error).toContain('align_elements')- const three = call('distribute_elements', { ids: ['el-1', 'el-2', 'img-1'], axis: 'y' })- expect(three.ok).toBe(true)+ it('exactly three tools are destructive', () => {+ const destructive = AGENT_TOOLS.filter((t) => t.risk === 'destructive').map((t) => t.name)+ expect(destructive.sort()).toEqual(['clear_page', 'delete_elements', 'delete_page'])})-- // ── page-level tools ─────────────────────────────────────- it('set_background: solid + gradient + angle clamp; bad forms rejected', () => {- expect(call('set_background', { kind: 'solid', from: '#0D1117' }).ok).toBe(true)- const g = call('set_background', { kind: 'gradient', from: '#7D2AE8', to: '#02C0CC', angle: 999 })- expect(g.ok).toBe(true)- if (g.ok) expect(g.actions[0].angle).toBe(360)- expect(call('set_background', { kind: 'gradient', from: '#7D2AE8' }).ok).toBe(false)- expect(call('set_background', { kind: 'plaid', from: '#000000' }).ok).toBe(false)- })- it('set_font: targets enum + catalog validation', () => {- for (const targets of ['all', 'headings', 'body']) {- expect(call('set_font', { fontFamily: 'Inter', targets }).ok, targets).toBe(true)- }- expect(call('set_font', { fontFamily: 'Wingdings' }).ok).toBe(false)- })- it('recolor: both modes + the 3-color palette floor', () => {- expect(call('recolor', { color: '#FF0055', targets: 'text' }).ok).toBe(true)- expect(call('recolor', { palette: ['#7D2AE8', '#02C0CC', '#FFD166'] }).ok).toBe(true)- expect(call('recolor', { palette: ['#7D2AE8', 'nope', '#FFD166'] }).ok).toBe(false)- expect(call('recolor', {}).ok).toBe(false)- })- it('add_page / duplicate_page / fix_overlaps / balance_layout / animate_page / translate_texts compile', () => {- expect(call('add_page', {})).toMatchObject({ ok: true })- expect(call('duplicate_page', {})).toMatchObject({ ok: true })- expect(call('fix_overlaps', {})).toMatchObject({ ok: true })- expect(call('balance_layout', {})).toMatchObject({ ok: true })- expect(call('animate_page', {})).toMatchObject({ ok: true })- expect(call('translate_texts', { language: 'Spanish' })).toMatchObject({ ok: true })- expect(call('translate_texts', {}).ok).toBe(false)+ it('read tools are exactly the state/measure/validate set', () => {+ const reads = AGENT_TOOLS.filter((t) => t.risk === 'read').map((t) => t.name)+ expect(reads.sort()).toEqual(['get_page_state', 'goto_page', 'measure_text', 'validate_brief'])})+})- // ── goto_page (new in v0.27.3) ───────────────────────────- it('goto_page: 1-based integer validation', () => {- const ok = call('goto_page', { page: 2 })- expect(ok.ok).toBe(true)- if (ok.ok) expect(ok.actions[0]).toMatchObject({ type: 'gotoPage', page: 2 })- for (const bad of [0, -1, 61, 2.5, 'two']) {- expect(call('goto_page', { page: bad }).ok, String(bad)).toBe(false)+// ═════════════════════════════════════════════════════════════+// 2. MODES+// ═════════════════════════════════════════════════════════════++describe('harness · modes', () => {+ it('every mode has a risk surface', () => {+ for (const mode of Object.keys(MODE_TOOL_RISK) as AgentMode[]) {+ expect(Array.isArray(MODE_TOOL_RISK[mode])).toBe(true)}- expect(call('goto_page', {}).ok).toBe(false)})-- // ── destructive ──────────────────────────────────────────- it('delete_elements / clear_page are the only destructive tools', () => {- for (const t of AGENT_TOOLS) {- const shouldBeDestructive = t.name === 'delete_elements' || t.name === 'clear_page'- expect(t.risk === 'destructive', t.name).toBe(shouldBeDestructive)+ it('read-only modes have ZERO write tools in their surface', () => {+ for (const mode of ['review', 'explain', 'plan', 'discuss'] as AgentMode[]) {+ const surface = toolsForMode(mode)+ expect(surface.length, mode).toBeGreaterThanOrEqual(0)+ expect(surface.every((t) => t.risk === 'read'), mode).toBe(true)+ expect(modeAllowsWrites(mode)).toBe(false)+ }+ // discuss gets NO tools at all+ expect(toolsForMode('discuss')).toHaveLength(0)+ })+ it('write modes expose the full bridge', () => {+ for (const mode of ['create', 'edit', 'improve'] as AgentMode[]) {+ const surface = toolsForMode(mode)+ expect(surface.length, mode).toBeGreaterThan(40)+ expect(modeAllowsWrites(mode)).toBe(true)}})- it('clear_page expands to every current id and refuses an empty page', () => {- const r = call('clear_page', {})- expect(r.ok).toBe(true)- if (r.ok) expect((r.actions[0].ids as string[]).sort()).toEqual([...ctx.validIds].sort())- const empty = call('clear_page', {}, { ...ctx, validIds: new Set() })- expect(empty.ok).toBe(false)+ it('heuristic classification: the seven mode examples from the brief', () => {+ expect(heuristicMode('Make a poster').mode).toBe('create')+ expect(heuristicMode('Move the title down').mode).toBe('edit')+ expect(heuristicMode("What's wrong with this design?").mode).toBe('review')+ expect(heuristicMode('Make this professional').mode).toBe('improve')+ expect(heuristicMode('How does gradient editing work?').confidence).toBe('high') // product question+ expect(heuristicMode('Fix the Canvix agent tool loop').mode).toBe('discuss')+ expect(heuristicMode('Propose a plan for the deck').mode).toBe('plan')+ })+ it('heuristic classification: more phrasings', () => {+ expect(heuristicMode('Design a bold poster for a coffee launch with a warm palette').mode).toBe('create')+ expect(heuristicMode('Make the title bold').mode).toBe('edit')+ expect(heuristicMode('Critique this layout').mode).toBe('review')+ expect(heuristicMode('what font is the headline?').mode).toBe('explain')+ expect(heuristicMode('Polish this design').mode).toBe('improve')+ expect(heuristicMode('lol').confidence).toBe('low')+ })+ it('parseMode reads fenced and bare JSON, rejects junk', () => {+ expect(parseMode('{"mode":"review"}')).toBe('review')+ expect(parseMode('```json\n{"mode":"create"}\n```')).toBe('create')+ expect(parseMode('sure!')).toBeNull()+ })+ it('the system prompt respects the mode surface', () => {+ const reviewPrompt = loopSystemPrompt({ design, ctx, mode: 'review' })+ expect(reviewPrompt).not.toContain('- add_text')+ expect(reviewPrompt).toContain('REVIEW')+ const createPrompt = loopSystemPrompt({ design, ctx, mode: 'create' })+ expect(createPrompt).toContain('- add_text')})+})- // ── universal invariants ─────────────────────────────────- it('EVERY tool: accepted calls always carry ≥1 action object with a type', () => {- // sample one valid call per tool- const valid: Record<string, Record<string, unknown>> = {- get_page_state: {},- add_text: { text: 'Hi' },- add_shape: { shape: 'rect', x: 1, y: 1, width: 50, height: 50 },- add_image: { prompt: 'a banner' },- add_stock_photo: { query: 'coffee' },- add_sticker: { emoji: '🚀' },- add_table: { header: ['A'], rows: [['1']] },- update_elements: { ids: ['el-1'], patch: { fill: '#123456' } },- set_text_style: { ids: ['txt-1'], fontSize: 40 },- move_elements: { ids: ['el-1'], dx: 10 },- align_elements: { ids: ['el-1'], mode: 'cx' },- distribute_elements: { ids: ['el-1', 'el-2', 'img-1'], axis: 'x' },- set_background: { kind: 'solid', from: '#0D1117' },- set_font: { fontFamily: 'Inter' },- recolor: { color: '#FF0055' },- add_page: {},- duplicate_page: {},- goto_page: { page: 1 },- fix_overlaps: {},- balance_layout: {},- animate_page: {},- translate_texts: { language: 'French' },- delete_elements: { ids: ['el-1'] },- clear_page: {},- }- for (const t of AGENT_TOOLS) {- const r = t.sanitize(valid[t.name], ctx)- expect(r.ok, t.name).toBe(true)- if (r.ok) {- expect(r.actions.length, t.name).toBeGreaterThan(0)- expect(typeof r.actions[0].type, t.name).toBe('string')- expect(r.observation, t.name).toBeTruthy()- }+// ═════════════════════════════════════════════════════════════+// 3. BRIEF CONTRACT+// ═════════════════════════════════════════════════════════════++describe('harness · brief contract', () => {+ it('extracts exact quoted texts, hex colors and dimensions as MANDATORY', () => {+ const brief = extractBrief(+ 'Make a 1080x1080 poster with navy #090B1A background, purple #8B5CF6 and cyan #22D3EE accents, saying "Design Beyond Limits", "Create Smarter. Design Faster." and "Try Canvix Free"',+ )+ expect(brief.requiredTexts.map((t) => t.text)).toEqual([+ 'Design Beyond Limits',+ 'Create Smarter. Design Faster.',+ 'Try Canvix Free',+ ])+ expect(brief.requiredTexts.every((t) => t.tier === 'mandatory')).toBe(true)+ expect(brief.requiredColors.map((c) => c.hex)).toEqual(['#090b1a', '#8b5cf6', '#22d3ee'])+ expect(brief.dimensions).toMatchObject({ width: 1080, height: 1080, tier: 'mandatory' })+ })+ it('unquoted headline patterns still extract; restrictions too', () => {+ const brief = extractBrief('Add the headline Grand Opening Gala and no dark colors please')+ expect(brief.requiredTexts.some((t) => t.text.startsWith('Grand Opening'))).toBe(true)+ expect(brief.restrictions.length).toBeGreaterThan(0)+ })+ it('platform presets fill dimensions as preference when unspecified', () => {+ const brief = extractBrief('Design an instagram story for the launch')+ expect(brief.format).toBe('story')+ expect(brief.dimensions).toMatchObject({ width: 1080, height: 1920, tier: 'preference' })+ // explicit dims outrank the preset+ const explicit = extractBrief('Instagram post but 800x800')+ expect(explicit.dimensions).toMatchObject({ width: 800, height: 800, tier: 'mandatory' })+ })+ it('FORMAT_PRESETS covers the social formats the matrix promises', () => {+ for (const id of ['instagram-post', 'story', 'youtube-thumbnail', 'poster', 'presentation', 'business-card', 'menu', 'logo']) {+ expect(FORMAT_PRESETS[id], id).toBeTruthy()}})- it('EVERY tool: rejections always produce a non-empty actionable error', () => {- // garbage args must be rejected (never crash, never pass through)- for (const t of AGENT_TOOLS) {- const r = t.sanitize({ ids: [], text: '', patch: {} }, ctx)- if (!r.ok) {- expect(r.error.length, t.name).toBeGreaterThan(10)- } else {- // tools with no args (add_page etc.) legitimately accept {}- expect(['add_page', 'duplicate_page', 'fix_overlaps', 'balance_layout', 'animate_page', 'get_page_state', 'clear_page']).toContain(t.name)- }+ it('validation passes when exact text + colors are present, fails with the unmet item named', () => {+ const brief = extractBrief('"Design Beyond Limits" with #8B5CF6 on 1080x1080')+ const ok = validateBrief(brief, {+ texts: ['DESIGN BEYOND LIMITS — really'],+ colors: ['#8b5cf6'],+ width: 1080,+ height: 1080,+ })+ expect(ok.satisfied).toBe(true)+ const bad = validateBrief(brief, { texts: ['Creative Pulse'], colors: ['#FF0000'], width: 500, height: 500 })+ expect(bad.satisfied).toBe(false)+ expect(bad.unmet.some((u) => u.includes('Design Beyond Limits'))).toBe(true)+ expect(bad.unmet.some((u) => u.includes('8B5CF6'))).toBe(true)+ expect(bad.unmet.some((u) => u.includes('1080'))).toBe(true)+ })+ it('case-insensitive hex matching; whitespace-tolerant text matching', () => {+ const brief = extractBrief('"Hello World" #AABBCC')+ expect(+ validateBrief(brief, { texts: [' hello\nworld '], colors: ['#AABBCC'], width: 1080, height: 1080 }).satisfied,+ ).toBe(true)+ expect(+ validateBrief(brief, { texts: ['x'], colors: ['#aabbcc'], width: 1080, height: 1080 }).satisfied,+ ).toBe(false)+ })+ it('briefPromptSection states the verbatim rule', () => {+ const brief = extractBrief('"Try Canvix Free" #02C0CC')+ const s = briefPromptSection(brief)+ expect(s).toContain('Try Canvix Free')+ expect(s).toContain('02C0CC')+ expect(s).toContain('never substitute')+ })+})++// ═════════════════════════════════════════════════════════════+// 4. SKILLS ENGINE+// ═════════════════════════════════════════════════════════════++describe('harness · skills engine', () => {+ it('ten skills ship, each with a complete playbook', () => {+ expect(DESIGN_SKILLS).toHaveLength(10)+ for (const s of DESIGN_SKILLS) {+ expect(s.id).toBeTruthy()+ expect(s.playbook.principles.length).toBeGreaterThanOrEqual(4)+ expect(s.playbook.planning.length).toBeGreaterThanOrEqual(2)+ expect(s.playbook.validation.length).toBeGreaterThanOrEqual(2)+ expect(s.modes.length).toBeGreaterThan(0)+ expect(s.whenToUse.length).toBeGreaterThan(0)}})- it('sanitizers never throw on adversarial args (wrong types everywhere)', () => {- const adversarial = [- { ids: 'not-an-array', patch: { fill: { deep: 'object' } } },- { text: { nested: true }, fontSize: NaN },- { header: 'string', rows: 42 },- { page: Infinity, factor: 'x' },- { palette: 'no', ids: [null, 123, {}] },- { dx: '1e999', shape: { fake: 1 } },- ]- for (const t of AGENT_TOOLS) {- for (const args of adversarial) {- expect(() => t.sanitize(args as Record<string, unknown>, ctx), `${t.name} ${JSON.stringify(args)}`).not.toThrow()- }+ it('the router selects poster+typography+color+layout for a poster brief', () => {+ const skills = selectSkills('Design a bold poster for a coffee launch with a warm palette', 'create')+ const ids = skills.map((s) => s.id)+ expect(ids).toContain('poster-design')+ expect(ids).toContain('color')+ expect(skills.length).toBeLessThanOrEqual(3) // progressive disclosure cap+ })+ it('the critique skill owns review mode', () => {+ const skills = selectSkills('review this', 'review')+ expect(skills[0]?.id).toBe('critique')+ })+ it('brand skill ranks up when a brand kit is present', () => {+ const withBrand = selectSkills('make it on brand and consistent', 'improve', true)+ const without = selectSkills('make it on brand and consistent', 'improve', false)+ expect(withBrand.some((s) => s.id === 'brand')).toBe(true)+ expect(without.some((s) => s.id === 'brand')).toBe(false)+ })+ it('skillsPromptSection injects ONLY the selected playbooks', () => {+ const skills = selectSkills('Design a youtube thumbnail', 'create')+ const s = skillsPromptSection(skills)+ expect(s).toContain('Skill:')+ for (const skill of DESIGN_SKILLS) {+ const included = skills.some((x) => x.id === skill.id)+ // a headline principle fragment should appear only when selected+ if (!included) expect(s).not.toContain(skill.name)}})})// ═════════════════════════════════════════════════════════════-// 2. LOOP FLOWS — realistic multi-step runs+// 5. LIFECYCLE FLOWS (Cases A–F)// ═════════════════════════════════════════════════════════════-describe('harness · loop flows', () => {- it('FLOW poster build: background → headline → subline → photo → verify → done (6 steps, ordered events)', async () => {+describe('harness · lifecycle flows (Cases A–F)', () => {+ /** Case A: the exact promotional poster — quoted copy + hex+ * colors must survive verbatim through a full create run. */+ it('CASE A: exact promotional design — brief texts/colors pass through and done is gated on validation', async () => {+ const brief = extractBrief(+ '1080x1080 Canvix poster, navy #090B1A background, purple #8B5CF6, cyan #22D3EE, white #FFFFFF, gray #A1A1AA, "Design Beyond Limits", "Create Smarter. Design Faster.", "Try Canvix Free"',+ )const events: AgentEvent[] = []+ let validationCalls = 0+ // model: bg → headline → subline → CTA → attempt done (validation+ // FAILS first: gray missing) → fix → done (passes)const { chat, calls } = scriptedChat([- turn('set_background', { kind: 'gradient', from: '#1A1B2E', to: '#7D2AE8', angle: 160 }),- turn('add_text', { text: 'GRAND OPENING', fontSize: 120, x: 60, y: 140, width: 960, bold: true, color: '#FFFFFF' }),- turn('add_text', { text: 'Saturday · 10 AM · Free coffee all day', fontSize: 36, x: 60, y: 320, color: '#FFD166' }),- turn('add_stock_photo', { query: 'coffee shop interior warm light', orientation: 'landscape' }),- turn('get_page_state'),- done('Poster built: gradient background, headline, subline and a licensed photo.'),+ turn('set_background', { kind: 'solid', from: '#090B1A' }),+ turn('add_text', { text: 'Design Beyond Limits', fontSize: 110, color: '#FFFFFF', bold: true }),+ turn('add_text', { text: 'Create Smarter. Design Faster.', fontSize: 40, color: '#22D3EE' }),+ turn('add_text', { text: 'Try Canvix Free', fontSize: 36, color: '#8B5CF6' }),+ done('Poster complete'),+ turn('add_text', { text: 'Free forever · canvix.app', fontSize: 22, color: '#A1A1AA' }),+ done('Poster complete with all colors'),])const result = await runAgentLoop({chat,design,+ mode: 'create',+ brief,emit: (e) => events.push(e),awaitApply: async () => ({ ok: true }),- // the client pushes refreshed context with every ack — the loop- // re-serializes it after get_page_state- refreshedContext: () => design,+ validateBriefOnClient: async () => {+ validationCalls+++ // first check: gray missing; second: everything present+ if (validationCalls === 1) return { satisfied: false, unmet: ['Required color #A1A1AA not used anywhere on the page'] }+ return { satisfied: true, unmet: [] }+ },})expect(result.toolCalls).toBe(5)- expect(result.steps).toBe(6)- expect(result.summary).toContain('Poster built')-- // event ORDER: start(implicit) → step → action → observation × N → done- const kinds = events.map((e) => e.type)- expect(kinds[0]).toBe('step')- expect(kinds[kinds.length - 1]).toBe('done')- expect(kinds.filter((k) => k === 'step')).toHaveLength(5)- expect(kinds.filter((k) => k === 'action')).toHaveLength(5)- // every action references its step index and carries a callId- for (const a of events.filter((e) => e.type === 'action')) {- const act = a as Extract<AgentEvent, { type: 'action' }>- expect(act.callId).toMatch(/^call-/)- expect(act.actions.length).toBeGreaterThan(0)- }- // the loop fed the model its observation after each apply (messages grow)- expect(calls.length).toBe(6)- expect(calls[5][calls[5].length - 1].content).toContain('UPDATED PAGE STATE')- })-- it('FLOW page-switch: add_page → goto_page → get_page_state → build on the new page', async () => {- const events: AgentEvent[] = []+ expect(result.summary).toContain('all colors')+ expect(result.verification).toContain('validated')+ // the failed done was REFUSED and the model was told what's missing+ expect(calls.some((c) => c.some((m) => m.content.includes('NOT DONE')))).toBe(true)+ expect(calls.some((c) => c.some((m) => m.content.includes('A1A1AA')))).toBe(true)+ // brief events streamed for the panel+ expect(events.some((e) => e.type === 'brief')).toBe(true)+ })++ it('CASE A (anti-substitution): a model that renames the copy cannot finish — after 3 rejected completions the run ends honestly with the unmet list', async () => {+ const brief = extractBrief('"Design Beyond Limits"')+ let validationCalls = 0const { chat, calls } = scriptedChat([- turn('add_page'),- turn('goto_page', { page: 4 }), // design.pageCount=3 → new page is #4- turn('get_page_state'),- turn('add_text', { text: 'Page 4 headline', fontSize: 80 }),- done('Added page 4 with its headline.'),+ turn('add_text', { text: 'Creative Pulse', fontSize: 96 }),+ done('Done'), // rejected 1+ done('Done'), // rejected 2+ done('Done'), // rejected 3 → honest blocked ending+ done('Done'), // never reached])- // a client that refreshes context after get_page_state- const refreshed: AgentDesignCtx = { ...design, currentPageIndex: 3, elements: [] }+ const events: AgentEvent[] = []const result = await runAgentLoop({chat,design,+ mode: 'create',+ brief,emit: (e) => events.push(e),awaitApply: async () => ({ ok: true }),- refreshedContext: () => refreshed,+ validateBriefOnClient: async () => {+ validationCalls+++ return { satisfied: false, unmet: ['Required text missing or altered: "Design Beyond Limits"'] }+ },})- expect(result.toolCalls).toBe(4)- // after the refresh, the loop told the model it's on page 4 and- // validIds were recomputed from the refreshed context- const lastCall = calls[3]- expect(lastCall[lastCall.length - 1].content).toContain('editing page 4')- // actions: addPage, gotoPage, __getContext, addText- const tools = events.filter((e) => e.type === 'action').map((e) => (e as { tool: string }).tool)- expect(tools).toEqual(['add_page', 'goto_page', 'get_page_state', 'add_text'])+ // every completion claim was validated and refused…+ expect(validationCalls).toBe(3)+ expect(calls.some((c) => c.some((m) => m.content.includes('NOT DONE')))).toBe(true)+ // …and the run ends HONESTLY with the unmet list — no fake success+ expect(result.summary).toContain('unmet requirements')+ expect(result.summary).toContain('Design Beyond Limits')+ expect(result.summary).not.toMatch(/^Done/)+ const last = events[events.length - 1]+ expect(last.type).toBe('done')})- it('FLOW self-correction ladder: bad hex → bad font → good call; rejections stay budget-free', async () => {+ /** Case B: review-only grounding — a review of an incomplete+ * poster reports what IS there; no write tool ever fires. */+ it('CASE B: review-only grounding — no writes, findings streamed', async () => {+ const events: AgentEvent[] = []const { chat } = scriptedChat([- turn('update_elements', { ids: ['txt-1'], patch: { fill: 'purple' } }),- turn('add_text', { text: 'Hi', fontFamily: 'Comic Sans' }),- turn('update_elements', { ids: ['txt-1'], patch: { fill: '#7D2AE8' } }),- done('Fixed the color on the third try.'),+ turn('get_page_state'),+ done('The poster has a headline and two rectangles but no CTA and no contact details.', {+ findings: [+ { severity: 'P1', issue: 'No call-to-action element on the page', fix: 'Add a CTA pill with the accent color' },+ { severity: 'P2', issue: 'Two rectangles overlap by 25% (el-1 × el-2)', fix: 'Separate or group them intentionally' },+ ],+ }),])- const result = await runAgentLoop({ chat, design, emit: () => {}, awaitApply: async () => ({ ok: true }) })- expect(result.toolCalls).toBe(1)- // v0.27.3: progress budget counts only productive steps — both- // rejections were free, so the run still had full budget left- expect(result.steps).toBe(4)- })-- it('FLOW budget exhaustion: a model that never finishes is cut off with a done event (never a hang)', async () => {- const events: AgentEvent[] = []- let modelTurns = 0+ // which tools actually reached the client as actions+ const appliedTools: string[] = []const result = await runAgentLoop({- chat: async () => {- modelTurns += 1- return turn('add_sticker', { emoji: '🤖' })+ chat,+ design,+ mode: 'review',+ emit: (e) => {+ if (e.type === 'action') appliedTools.push(e.tool)+ events.push(e)},+ awaitApply: async () => ({ ok: true }),+ })+ // review reads state (get_page_state rides the action→ack path so+ // the client pushes refreshed context) but NEVER a write tool+ expect(appliedTools.every((t) => ['get_page_state', 'validate_brief', 'measure_text', 'goto_page'].includes(t))).toBe(true)+ expect(result.toolCalls).toBe(1) // only get_page_state+ expect(result.findings).toHaveLength(2)+ expect(result.findings?.[0].severity).toBe('P1')+ // even if the model TRIES a write tool in review mode:+ const { chat: rogueChat } = scriptedChat([+ turn('get_page_state'),+ turn('add_text', { text: 'sneaky edit' }),+ done('Reviewed'),+ ])+ const rogueAppliedTools: string[] = []+ const rogue = await runAgentLoop({+ chat: rogueChat,design,- emit: (e) => events.push(e),+ mode: 'review',+ emit: (e) => {+ if (e.type === 'action') rogueAppliedTools.push(e.tool)+ },awaitApply: async () => ({ ok: true }),})- // maxSteps=8 productive calls cap the loop; each add_sticker is- // productive so the loop stops at exactly 8 tool calls- expect(modelTurns).toBe(AGENT_BUDGETS.maxSteps)- expect(result.toolCalls).toBe(AGENT_BUDGETS.maxSteps)- const last = events[events.length - 1]- expect(last.type).toBe('done')- })-- it('FLOW rejected-forever model: rejections are tool-budget-free but 3 strikes end the run (no infinite loop)', async () => {- const events: AgentEvent[] = []- let modelTurns = 0+ // the write tool is not in the surface — refused before any action+ expect(rogueAppliedTools.every((t) => t !== 'add_text')).toBe(true)+ expect(rogue.toolCalls).toBe(1)+ })++ /** Case C: a long multi-page run — >8 tool calls completes with+ * no step cap (v0.27 would have stopped at 8). */+ it('CASE C: 14-step multi-page deck build completes (no arbitrary cap)', async () => {+ const replies: string[] = []+ // page 1: bg + 2 texts; goto page 2: bg + 2 texts; verify; done+ replies.push(turn('set_background', { kind: 'solid', from: '#0D1117' }))+ replies.push(turn('add_text', { text: 'Slide One', fontSize: 90 }))+ replies.push(turn('add_text', { text: 'The vision', fontSize: 32 }))+ replies.push(turn('add_page'))+ replies.push(turn('goto_page', { page: 2 }))+ replies.push(turn('get_page_state'))+ replies.push(turn('set_background', { kind: 'solid', from: '#0D1117' }))+ replies.push(turn('add_text', { text: 'Slide Two', fontSize: 90 }))+ replies.push(turn('add_text', { text: 'The numbers', fontSize: 32 }))+ replies.push(turn('add_chart', { kind: 'bar', labels: ['22', '23', '24'], series: [{ name: 'ARR', color: '#02C0CC', values: [1, 4, 12] }] }))+ replies.push(turn('add_line', { x: 100, y: 800, length: 800, variant: 'arrow' }))+ replies.push(turn('animate_elements', { ids: ['txt-1'], kind: 'rise' }))+ replies.push(turn('get_page_state'))+ replies.push(done('Two slides built with consistent styling.'))+ expect(replies.length).toBe(14) // v0.27's cap was 8+ const { chat, calls } = scriptedChat(replies)+ // refreshed page-2 state: two fresh elements (ids the model just made)+ const refreshed: AgentDesignCtx = {+ ...design,+ currentPageIndex: 1,+ elements: [+ { id: 'txt-1', type: 'text', x: 0, y: 100, width: 800, height: 120, text: 'Slide Two', fontSize: 90, fill: '#FFFFFF' },+ { id: 'txt-2', type: 'text', x: 0, y: 260, width: 600, height: 80, text: 'The numbers', fontSize: 32, fill: '#02C0CC' },+ ],+ }const result = await runAgentLoop({- chat: async () => {- modelTurns += 1- return turn('update_elements', { ids: ['ghost'], patch: { fill: '#123456' } }) // always invalid- },+ chat,design,- emit: (e) => events.push(e),+ mode: 'create',+ emit: () => {},awaitApply: async () => ({ ok: true }),+ refreshedContext: () => refreshed,})- // 3 strikes → error event, exactly 3 model turns, zero applies- expect(modelTurns).toBe(3)- expect(result.toolCalls).toBe(0)- const last = events[events.length - 1]- expect(last.type).toBe('error')- if (last.type === 'error') expect(last.message).toContain('3 invalid tool calls')+ expect(result.toolCalls).toBe(13) // every step applied — no cap hit+ expect(result.steps).toBe(13)+ // page switch flowed through: the model saw page 2's state+ expect(calls[6].some((m) => m.content.includes('UPDATED PAGE STATE'))).toBe(true)})- it('FLOW strike reset: two bad calls, one good, two more bad — the run continues (strikes are consecutive)', async () => {+ /** Case D: geometry repair — off-canvas + overlaps detected and+ * fixed with fix_overlaps. */+ it('CASE D: geometry repair — fix_overlaps after placement', async () => {const { chat } = scriptedChat([- turn('update_elements', { ids: ['ghost'], patch: { fill: '#123456' } }), // strike 1- turn('add_sticker', { emoji: '🚀' }), // good → reset- turn('update_elements', { ids: ['ghost'], patch: { fill: '#123456' } }), // strike 1 again- turn('update_elements', { ids: ['ghost-2'], patch: { fill: '#123456' } }), // strike 2- done('Mixed luck but finished.'),- ])- const result = await runAgentLoop({ chat, design, emit: () => {}, awaitApply: async () => ({ ok: true }) })- expect(result.summary).toBe('Mixed luck but finished.')- expect(result.toolCalls).toBe(1)- })-- it('FLOW destructive decline: the model is told, adapts, and finishes — nothing was applied', async () => {- const applied: unknown[] = []- const { chat, calls } = scriptedChat([- turn('clear_page'),- turn('add_text', { text: 'Starting fresh instead', fontSize: 64 }),- done('Kept your content and added a fresh headline.'),+ turn('add_text', { text: 'Big Headline', fontSize: 140, x: 0, y: 0 }),+ turn('add_text', { text: 'Sub', fontSize: 40, x: 0, y: 20 }), // overlaps the headline+ turn('fix_overlaps'),+ turn('get_page_state'),+ done('Layout fixed — overlaps resolved.'),])const result = await runAgentLoop({chat,design,+ mode: 'improve',emit: () => {},- confirmed: new Set(),- awaitConfirm: async () => false,- awaitApply: async () => {- applied.push('x')- return { ok: true }- },+ awaitApply: async () => ({ ok: true }),+ refreshedContext: () => design,})- expect(result.toolCalls).toBe(1) // only the add_text- expect(applied).toHaveLength(1) // clear_page never applied- const declineMsg = calls[1].find((m) => m.role === 'user')- expect(declineMsg?.content).toContain('DECLINED')- })-- it('FLOW destructive approve-then-apply-failure: the failure feeds back (v0.27.3 fix)', async () => {- const applied: string[] = []- const { chat, calls } = scriptedChat([- turn('delete_elements', { ids: ['el-1'] }),- turn('delete_elements', { ids: ['el-2'] }),- done('Deleted what I could.'),- ])+ expect(result.toolCalls).toBe(4)+ expect(result.summary).toContain('fixed')+ })++ /** Case E: capability sweep — one valid call per v0.28 tool. */+ it('CASE E: capability sweep — every bridge tool applies cleanly in sequence', async () => {+ const valid: [string, Record<string, unknown>][] = [+ ['get_page_state', {}],+ ['set_background', { kind: 'gradient', from: '#090B1A', to: '#8B5CF6', angle: 160 }],+ ['add_text', { text: 'Hello', fontSize: 64, color: '#FFFFFF' }],+ ['add_shape', { shape: 'rect', x: 10, y: 10, width: 100, height: 80 }],+ ['add_line', { x: 10, y: 200, length: 300, variant: 'arrow' }],+ ['add_icon', { query: 'rocket' }],+ ['add_illustration', { query: 'waves' }],+ ['add_chart', { kind: 'donut', labels: ['A', 'B'], series: [{ name: 'S', color: '#8B5CF6', values: [3, 7] }] }],+ ['add_qr', { value: 'https://canvix.app' }],+ ['add_frame', { frameShape: 'circle', width: 300, height: 300 }],+ ['add_embed', { url: 'https://youtu.be/demo' }],+ ['add_sticker', { emoji: '🚀', size: 120 }],+ ['add_table', { header: ['Plan', 'Price'], rows: [['Free', '$0']] }],+ ['add_stock_photo', { query: 'coffee cup', orientation: 'landscape' }],+ ['add_stock_video', { query: 'city timelapse' }],+ ['add_image', { prompt: 'abstract gradient banner' }],+ ['update_elements', { ids: ['el-1'], patch: { fill: '#8B5CF6', rotation: 15, opacity: 0.9 } }],+ ['set_text_style', { ids: ['txt-1'], fontFamily: 'Poppins', fontSize: 72, bold: true }],+ ['set_text_spans', { ids: ['txt-2'], spans: [{ text: 'Wor' }, { text: 'ld', bold: true }] }],+ ['move_elements', { ids: ['el-1'], dx: 40, dy: 20 }],+ ['align_elements', { ids: ['el-1', 'el-2'], mode: 'cx' }],+ ['distribute_elements', { ids: ['el-1', 'el-2', 'img-1'], axis: 'y' }],+ ['duplicate_elements', { ids: ['el-1'] }],+ ['group_elements', { ids: ['el-1', 'el-2'] }],+ ['reorder_layers', { ids: ['img-1'], dir: 'front' }],+ ['mask_image', { ids: ['img-1'], mask: 'circle' }],+ ['adjust_image', { ids: ['img-1'], brightness: 20, contrast: -10 }],+ ['measure_text', { text: 'Design Beyond Limits', fontSize: 96, fontFamily: 'Poppins' }],+ ['set_font', { fontFamily: 'Inter', targets: 'all' }],+ ['recolor', { color: '#02C0CC', targets: 'text' }],+ ['animate_elements', { ids: ['el-1'], kind: 'pop', duration: 0.5 }],+ ['set_page_transition', { kind: 'fade' }],+ ['add_page', {}],+ ['duplicate_page', {}],+ ['goto_page', { page: 1 }],+ ['animate_page', {}],+ ['balance_layout', {}],+ ['fix_overlaps', {}],+ ['translate_texts', { language: 'Spanish' }],+ ['set_brand_kit', { colors: ['#090B1A', '#8B5CF6', '#22D3EE'], headingFont: 'Poppins', bodyFont: 'Inter' }],+ ['resize_design', { width: 1080, height: 1350 }],+ ['validate_brief', {}],+ ['export_design', { format: 'png' }],+ // destructive last (declined — proves the gate in the sweep too)+ ['clear_page', {}],+ ]+ const { chat } = scriptedChat([...valid.map(([t, a]) => turn(t, a)), done('Sweep complete')])+ let declined = falseconst result = await runAgentLoop({chat,design,+ mode: 'create',emit: () => {},- awaitConfirm: async () => true,- awaitApply: async () => {- applied.push('attempt')- return applied.length === 1- ? { ok: false, message: 'Element locked by another collaborator' }- : { ok: true }+ confirmed: new Set(),+ awaitConfirm: async () => {+ declined = true+ return false},+ awaitApply: async () => ({ ok: true }),+ refreshedContext: () => design,+ validateBriefOnClient: async () => ({ satisfied: true, unmet: [] }),})- // first delete: approved but apply FAILED → error observation, not counted- expect(result.toolCalls).toBe(1)- const failureMsg = calls[1].find((m) => m.role === 'user')- expect(failureMsg?.content).toContain('locked by another collaborator')- expect(failureMsg?.content).toContain('NOT changed')+ // every write tool applied except the declined clear_page+ expect(result.toolCalls).toBe(valid.length - 1)+ expect(declined).toBe(true)+ expect(result.summary).toBe('Sweep complete')})- it('FLOW abort mid-run: everything applied so far is kept and reported', async () => {+ /** Case F: safety — strikes, cycles, abort, decline, provider failure. */+ it('CASE F1: three consecutive invalid calls end the run with STRIKES', async () => {+ const events: AgentEvent[] = []+ const result = await runAgentLoop({+ chat: async () => turn('update_elements', { ids: ['ghost'], patch: { fill: '#123456' } }),+ design,+ mode: 'edit',+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ })+ expect(result.toolCalls).toBe(0)+ const err = events.find((e) => e.type === 'error')+ expect(err && err.type === 'error' && err.code).toBe('STRIKES')+ })+ it('CASE F2: an identical call repeated 3× triggers cycle wrap-up', async () => {+ const events: AgentEvent[] = []+ const result = await runAgentLoop({+ chat: async () => turn('add_sticker', { emoji: '🤖' }),+ design,+ mode: 'create',+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ })+ // 2 identical applies are allowed; the 3rd wraps up+ expect(result.toolCalls).toBe(2)+ const last = events[events.length - 1]+ expect(last.type).toBe('done')+ })+ it('CASE F3: abort mid-run keeps applied work and reports Stop', async () => {const signal = { aborted: false, reason: 'Stopped by user' }let n = 0const result = await runAgentLoop({chat: async () => {n += 1- if (n === 4) signal.aborted = true // user hits Stop during turn 4- return turn('add_sticker', { emoji: '⭐' })+ if (n === 4) signal.aborted = true+ return turn('add_sticker', { emoji: '⭐', n }) // distinct args — no cycle guard},design,+ mode: 'create',emit: () => {},signal,awaitApply: async () => ({ ok: true }),})- // abort is checked at the TOP of the loop: turn 4 (already in- // flight when Stop landed) still applied; there is no turn 5- expect(result.toolCalls).toBe(4)+ expect(result.toolCalls).toBe(4) // the in-flight 4th applied; no 5th callexpect(result.summary).toContain('Stopped')})-- it('FLOW JSON repair: first reply is prose, the repair turn succeeds', async () => {- const { chat } = scriptedChat([- 'Sure! Let me add a nice headline for you. I will use a bold font.',- turn('add_text', { text: 'Repaired', fontSize: 72 }),- done('Recovered after the repair.'),+ it('CASE F4: a declined destructive call redirects the model, applies nothing', async () => {+ const applied: unknown[] = []+ const { chat, calls } = scriptedChat([+ turn('delete_elements', { ids: ['el-1'] }),+ turn('add_text', { text: 'Kept your content', fontSize: 40 }),+ done('Deleted nothing; added a note instead.'),])- const result = await runAgentLoop({ chat, design, emit: () => {}, awaitApply: async () => ({ ok: true }) })+ const result = await runAgentLoop({+ chat,+ design,+ mode: 'edit',+ emit: () => {},+ confirmed: new Set(),+ awaitConfirm: async () => false,+ awaitApply: async () => {+ applied.push(1)+ return { ok: true }+ },+ })expect(result.toolCalls).toBe(1)- expect(result.summary).toBe('Recovered after the repair.')+ expect(applied).toHaveLength(1)+ expect(calls[1].some((m) => m.content.includes('DECLINED'))).toBe(true)})-- it('FLOW provider failure: a thrown chat becomes an error event, never an unhandled rejection', async () => {+ it('CASE F5: provider failure emits PROVIDER error, keeps work', async () => {const events: AgentEvent[] = []const result = await runAgentLoop({chat: async () => {throw new Error('429 quota exceeded')},design,+ mode: 'create',emit: (e) => events.push(e),})expect(result.toolCalls).toBe(0)const err = events.find((e) => e.type === 'error')- expect(err).toBeTruthy()- if (err && err.type === 'error') expect(err.message).toContain('429')+ expect(err && err.type === 'error' && err.code).toBe('PROVIDER')})-- it('the system prompt carries the full tool list, the design context and the page rule', () => {- const prompt = loopSystemPrompt(design, ctx)- for (const t of AGENT_TOOLS) expect(prompt).toContain(t.name)- expect(prompt).toContain('Launch Poster')- expect(prompt).toContain('BRAND KIT')- expect(prompt).toContain('goto_page') // the new page rule- expect(prompt).toContain('editing page 1')- expect(prompt).toContain('grp-1') // group ids are valid targets+ it('CASE F6: a write tool attempted in discuss-adjacent review mode is refused with guidance', async () => {+ const { chat, calls } = scriptedChat([+ turn('add_text', { text: 'nope' }),+ turn('get_page_state'),+ done('Reported.'),+ ])+ const result = await runAgentLoop({+ chat,+ design,+ mode: 'review',+ emit: () => {},+ awaitApply: async () => ({ ok: true }),+ })+ expect(result.toolCalls).toBe(1)+ expect(calls.some((c) => c.some((m) => m.content.includes('not available in review mode')))).toBe(true)+ })+ it('CASE F7: compaction folds a long conversation and emits a compact event', async () => {+ const events: AgentEvent[] = []+ const replies: string[] = []+ for (let i = 0; i < 65; i++) replies.push(turn('add_sticker', { emoji: '⭐', n: i }))+ replies.push(done('Long run complete'))+ const result = await runAgentLoop({+ chat: scriptedChat(replies).chat,+ design,+ mode: 'create',+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ })+ expect(events.some((e) => e.type === 'compact')).toBe(true)+ expect(result.toolCalls).toBe(65) // compaction never stops the run+ })+ it('usage telemetry streams during long runs', async () => {+ const events: AgentEvent[] = []+ const replies: string[] = []+ for (let i = 0; i < 40; i++) replies.push(turn('add_sticker', { emoji: '⭐' }))+ replies.push(done('done'))+ await runAgentLoop({+ chat: scriptedChat(replies).chat,+ design,+ mode: 'create',+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ })+ const usage = events.filter((e) => e.type === 'usage')+ expect(usage.length).toBeGreaterThan(0)+ })+ it('the system prompt carries the brief, skills, page rule and mode heading', () => {+ const brief = extractBrief('"Try Canvix Free"')+ const prompt = loopSystemPrompt({ design, ctx, mode: 'create', brief, skills: DESIGN_SKILLS.slice(0, 2) })+ expect(prompt).toContain('DESIGN BRIEF CONTRACT')+ expect(prompt).toContain('Try Canvix Free')+ expect(prompt).toContain('MODE: CREATE')+ expect(prompt).toContain('Skill:')+ expect(prompt).toContain('goto_page')+ expect(prompt).toContain('measure_text')})})// ═════════════════════════════════════════════════════════════-// 3. WIRE FORMAT+// 6. WIRE FORMAT + CONTEXT// ═════════════════════════════════════════════════════════════-describe('harness · SSE wire format', () => {- it('every event type serializes to exactly one `data: {json}\\n\\n` line and round-trips', () => {+describe('harness · wire format + context', () => {+ it('every event type serializes to one data: line and round-trips', () => {const samples: AgentEvent[] = [- { v: 1, type: 'start', intent: 'plan' },- { v: 1, type: 'step', index: 1, thought: 'thinking', tool: 'add_text' },- { v: 1, type: 'plan', steps: ['a', 'b'] },- { v: 1, type: 'action', stepIndex: 1, callId: 'call-1-ab12cd', risk: 'write', tool: 'add_text', actions: [{ type: 'addText', text: 'Hi' }] },- { v: 1, type: 'ack', callId: 'call-1-ab12cd', ok: true },- { v: 1, type: 'observation', stepIndex: 1, message: 'added' },- { v: 1, type: 'done', summary: 'All set', steps: 3, toolCalls: 2 },- { v: 1, type: 'error', message: 'provider down', code: 'PROVIDER' },- { v: 1, type: 'aborted', reason: 'Stopped by user' },+ { v: 2, type: 'start', intent: 'create', runId: 'run-x' },+ { v: 2, type: 'mode', mode: 'review', reason: 'classified' },+ { v: 2, type: 'skill', id: 'critique', name: 'Design Critique' },+ { v: 2, type: 'brief', brief: { requiredTexts: [] } },+ { v: 2, type: 'plan', steps: ['a'] },+ { v: 2, type: 'step', index: 1, thought: 't', tool: 'add_text' },+ { v: 2, type: 'action', stepIndex: 1, callId: 'c1', risk: 'write', tool: 'add_text', actions: [{ type: 'addText' }] },+ { v: 2, type: 'ack', callId: 'c1', ok: true },+ { v: 2, type: 'observation', stepIndex: 1, message: 'ok' },+ { v: 2, type: 'usage', turns: 3, toolCalls: 2, elapsedMs: 1234, modelCalls: 3 },+ { v: 2, type: 'compact', fromMessages: 60, toMessages: 12 },+ { v: 2, type: 'done', summary: 'ok', steps: 3, toolCalls: 2, verification: 'brief validated' },+ { v: 2, type: 'error', message: 'x', code: 'STRIKES' },+ { v: 2, type: 'aborted', reason: 'Stopped by user' },]for (const ev of samples) {const line = sseLine(ev)expect(line.startsWith('data: ')).toBe(true)expect(line.endsWith('\n\n')).toBe(true)- expect(line.split('\n\n')[0]).toBe(`data: ${JSON.stringify(ev)}`)expect(JSON.parse(line.slice(6))).toEqual(ev)}})- it('the protocol version is 1 everywhere (client compat contract)', () => {- expect(AGENT_PROTOCOL_VERSION).toBe(1)- })- it('parseAgentTurn: nested braces in strings survive; fences and prose tolerated', () => {- const t = parseAgentTurn('Here you go:\n```json\n{"thought":"a {b} c","tool":"add_text","args":{"text":"}{"}}\n```')- expect(t?.tool).toBe('add_text')- expect((t?.args as { text: string }).text).toBe('}{')- })- it('parseAgentTurn: picks the LARGEST valid object (multi-object replies)', () => {- const t = parseAgentTurn('{"a":1}\n{"thought":"x","tool":"get_page_state","args":{}}')- expect(t?.tool).toBe('get_page_state')- })-})--// ═════════════════════════════════════════════════════════════-// 4. ROUTER MATRIX-// ═════════════════════════════════════════════════════════════--describe('harness · router matrix', () => {- it('asks: questions land on ask', () => {- for (const m of [- 'What do you think of this design?',- 'How does this look?',- 'Is this font too small?',- 'Why is the text overlapping?',- ]) {- expect(heuristicIntent(m), m).toBe('ask')- }- })- it('acts: single surgical edits land on act', () => {- for (const m of [- 'Make the title bold',- 'change all heading colors to purple',- 'Delete the subtitle',- 'Center everything',- ]) {- expect(heuristicIntent(m), m).toBe('act')- }- })- it('plans: multi-goal briefs land on plan', () => {- for (const m of [- 'Design a bold poster for a coffee launch with a warm palette and a big headline',- 'complete redesign of this flyer with new colors and fonts',- 'rebrand this deck',- ]) {- expect(heuristicIntent(m), m).toBe('plan')- }- })- it('unsure → null → the model classifier decides', () => {- expect(heuristicIntent('lol')).toBeNull()- expect(heuristicIntent('')).toBeNull()- })- it('parseIntent: fenced, bare, and garbage forms', () => {- expect(parseIntent('{"intent":"act"}')).toBe('act')- expect(parseIntent('```json\n{"intent":"plan"}\n```')).toBe('plan')- expect(parseIntent('sure!')).toBe('plan') // fallback- expect(parseIntent('')).toBe('plan')- })-})--// ═════════════════════════════════════════════════════════════-// 5. CONTEXT SERIALIZATION-// ═════════════════════════════════════════════════════════════--describe('harness · context serialization', () => {- it('serializes every element, selection, brand, overlaps and other pages', () => {+ it('protocol version is 2 and guards are the documented values', () => {+ expect(AGENT_PROTOCOL_VERSION).toBe(2)+ expect(AGENT_GUARDS.strikes).toBe(3)+ expect(AGENT_GUARDS.cycleRepeat).toBe(3)+ expect(AGENT_GUARDS.idleMs).toBe(240_000)+ expect(AGENT_GUARDS.compactAtMessages).toBe(60)+ // NO step/tool/wall-clock caps exist anymore+ expect(AGENT_GUARDS).not.toHaveProperty('maxSteps')+ expect(AGENT_GUARDS).not.toHaveProperty('maxToolCalls')+ expect(AGENT_GUARDS).not.toHaveProperty('maxWallMs')+ })+ it('parseAgentTurn: fences, prose, nested braces, multi-object, junk', () => {+ expect(parseAgentTurn('```json\n{"tool":"add_text","args":{"text":"Hi"}}\n```')?.tool).toBe('add_text')+ expect(parseAgentTurn('Sure:\n{"thought":"a {b} c","tool":"add_text","args":{"text":"}{"}}')?.args).toEqual({ text: '}{' })+ expect(parseAgentTurn('{"a":1}\n{"tool":"get_page_state","args":{}}')?.tool).toBe('get_page_state')+ expect(parseAgentTurn('no json')).toBeNull()+ expect(parseAgentTurn('{"done":true,"findings":[{"severity":"P1","issue":"x"}]}')?.findings).toHaveLength(1)+ })+ it('context serialization covers all elements, selection, brand, pages', () => {const s = serializeDesignContext(design)for (const id of ['el-1', 'el-2', 'txt-1', 'txt-2', 'grp-1', 'img-1']) expect(s).toContain(id)- expect(s).toContain('[SELECTED]') // txt-1 is selected- expect(s).toContain('text="Hello"')- expect(s).toContain('Overlapping pairs: rect#el-1 × rect#el-2')- expect(s).toContain('Other pages')- expect(s).toContain('1080x1080')+ expect(s).toContain('[SELECTED]')+ expect(s).toContain('BRAND KIT')expect(s).toContain('3 page(s)')})- it('an empty page serializes honestly', () => {- const s = serializeDesignContext({ elements: [] })- expect(s).toContain('(empty page)')- expect(s).toContain('none detected')- })- it('contextValidIds: groups included, selected included', () => {- const ids = contextValidIds(design)- expect(ids.has('grp-1')).toBe(true)- expect(ids.has('txt-2')).toBe(true)- expect(ids.size).toBe(6)- })- it('toolsPromptSection lists every tool with its risk tier', () => {- const s = toolsPromptSection()- for (const t of AGENT_TOOLS) {- expect(s).toContain(`${t.name} (${t.risk})`)- }- })})diff --git a/src/lib/agent/loop.test.ts b/src/lib/agent/loop.test.tsdeleted file mode 100644index 7953699..0000000--- a/src/lib/agent/loop.test.ts+++ /dev/null@@ -1,314 +0,0 @@-// Unit tests for the v0.27 agent core — protocol parsing, tool-// sanitization, intent routing, and the loop's budget/verification-// discipline. The loop is tested with a scripted fake ChatFn so no-// network or provider is involved.--import { describe, it, expect } from 'vitest'-import { parseAgentTurn, AGENT_BUDGETS, type AgentEvent } from './protocol'-import { AGENT_TOOL_MAP, AGENT_TOOLS, fontFamilies, type ToolContext } from './tools'-import { heuristicIntent, parseIntent } from './router'-import { runAgentLoop } from './loop'-import type { AgentDesignCtx } from './context'--// ── fixtures ─────────────────────────────────────────────────--const ctx: ToolContext = {- validIds: new Set(['el-1', 'el-2', 'txt-1']),- width: 1080,- height: 1080,- fonts: new Set(['Poppins', 'Inter', 'Montserrat']),-}--const design: AgentDesignCtx = {- name: 'Test',- width: 1080,- height: 1080,- pageCount: 1,- currentPageIndex: 0,- selectedIds: [],- elements: [- { id: 'el-1', type: 'rect', x: 0, y: 0, width: 100, height: 100, fill: '#FF0000' },- { id: 'el-2', type: 'rect', x: 50, y: 50, width: 100, height: 100, fill: '#00FF00' },- { id: 'txt-1', type: 'text', x: 0, y: 200, width: 400, height: 60, text: 'Hello', fontSize: 48, fill: '#111111' },- ],-}--// ── protocol ─────────────────────────────────────────────────--describe('parseAgentTurn', () => {- it('parses a clean tool turn', () => {- const t = parseAgentTurn('{"thought":"need state","tool":"get_page_state","args":{}}')- expect(t?.tool).toBe('get_page_state')- })-- it('parses through markdown fences and prose', () => {- const t = parseAgentTurn('Sure! Here is my next step:\n```json\n{"tool":"add_text","args":{"text":"Hi"}}\n```')- expect(t?.tool).toBe('add_text')- expect((t?.args as { text: string }).text).toBe('Hi')- })-- it('parses a done turn', () => {- const t = parseAgentTurn('{"done":true,"summary":"Finished"}')- expect(t?.done).toBe(true)- expect(t?.summary).toBe('Finished')- })-- it('returns null for junk', () => {- expect(parseAgentTurn('no json here at all')).toBeNull()- expect(parseAgentTurn('')).toBeNull()- })-})--// ── tool sanitizers ──────────────────────────────────────────--describe('agent tool sanitizers', () => {- const tool = (name: string) => AGENT_TOOL_MAP.get(name)!-- it('registry is complete: every tool has name/risk/sanitize', () => {- for (const t of AGENT_TOOLS) {- expect(t.name).toBeTruthy()- expect(['read', 'write', 'destructive']).toContain(t.risk)- expect(typeof t.sanitize).toBe('function')- }- expect(AGENT_TOOLS.length).toBeGreaterThanOrEqual(18)- })-- it('add_text rejects a bad font with an actionable error', () => {- const r = tool('add_text').sanitize({ text: 'Hi', fontFamily: 'Comic Sans' }, ctx)- expect(r.ok).toBe(false)- if (!r.ok) expect(r.error).toContain('Comic Sans')- })-- it('add_text rejects out-of-range fontSize with the range in the message', () => {- const r = tool('add_text').sanitize({ text: 'Hi', fontSize: 1200 }, ctx)- expect(r.ok).toBe(false)- if (!r.ok) expect(r.error).toContain('6–400')- })-- it('add_text accepts valid args and compiles an action', () => {- const r = tool('add_text').sanitize({ text: 'Hello', fontSize: 64, color: '#7D2AE8', bold: true, x: 100, y: 200 }, ctx)- expect(r.ok).toBe(true)- if (r.ok) {- expect(r.actions[0]).toMatchObject({ type: 'addText', text: 'Hello', bold: true, color: '#7d2ae8', x: 100, y: 200 })- }- })-- it('update_elements rejects unknown ids and names them', () => {- const r = tool('update_elements').sanitize({ ids: ['nope-1'], patch: { fill: '#FF0000' } }, ctx)- expect(r.ok).toBe(false)- if (!r.ok) expect(r.error).toContain('nope-1')- })-- it('update_elements rejects a bad hex with the value echoed', () => {- const r = tool('update_elements').sanitize({ ids: ['el-1'], patch: { fill: 'red' } }, ctx)- expect(r.ok).toBe(false)- if (!r.ok) expect(r.error).toContain('red')- })-- it('update_elements rejects an empty patch', () => {- const r = tool('update_elements').sanitize({ ids: ['el-1'], patch: {} }, ctx)- expect(r.ok).toBe(false)- })-- it('delete_elements is marked destructive', () => {- expect(tool('delete_elements').risk).toBe('destructive')- expect(tool('clear_page').risk).toBe('destructive')- expect(tool('get_page_state').risk).toBe('read')- expect(tool('add_text').risk).toBe('write')- })-- it('set_font validates against the real catalog', () => {- const real = fontFamilies()[0]- const r = tool('set_font').sanitize({ fontFamily: real, targets: 'headings' }, ctx)- expect(r.ok).toBe(true)- const bad = tool('set_font').sanitize({ fontFamily: 'Not A Font', targets: 'all' }, ctx)- expect(bad.ok).toBe(false)- })-- it('recolor accepts palette mode with 3–5 hex colors', () => {- const r = tool('recolor').sanitize({ palette: ['#111111', '#222222', '#333333'] }, ctx)- expect(r.ok).toBe(true)- const bad = tool('recolor').sanitize({ palette: ['#111111', 'nope'] }, ctx)- expect(bad.ok).toBe(false)- })-- it('set_background requires to for gradients', () => {- const bad = tool('set_background').sanitize({ kind: 'gradient', from: '#000000' }, ctx)- expect(bad.ok).toBe(false)- const ok = tool('set_background').sanitize({ kind: 'gradient', from: '#000000', to: '#FFFFFF', angle: 45 }, ctx)- expect(ok.ok).toBe(true)- })-- it('clear_page on an empty page refuses gracefully', () => {- const r = tool('clear_page').sanitize({}, { ...ctx, validIds: new Set() })- expect(r.ok).toBe(false)- })-})--// ── router ───────────────────────────────────────────────────--describe('heuristicIntent', () => {- it('routes obvious questions to ask', () => {- expect(heuristicIntent('What do you think of this design?')).toBe('ask')- expect(heuristicIntent('How does this look?')).toBe('ask')- })-- it('routes surgical edits to act', () => {- expect(heuristicIntent('Make the title bold')).toBe('act')- expect(heuristicIntent('change all heading colors to purple')).toBe('act')- })-- it('routes multi-goal briefs to plan', () => {- expect(heuristicIntent('Design a bold poster for a coffee launch with a warm palette and a big headline')).toBe('plan')- })-- it('returns null when unsure', () => {- expect(heuristicIntent('lol')).toBeNull()- })-})--describe('parseIntent', () => {- it('reads the JSON intent', () => {- expect(parseIntent('{"intent":"act"}')).toBe('act')- expect(parseIntent('```json\n{"intent":"ask"}\n```')).toBe('ask')- })- it('falls back to plan on garbage', () => {- expect(parseIntent('I think act')).toBe('plan')- })-})--// ── the loop ─────────────────────────────────────────────────--describe('runAgentLoop', () => {- it('applies a valid tool call, streams events, and finishes', async () => {- const events: AgentEvent[] = []- const replies = [- JSON.stringify({ thought: 'add a headline', tool: 'add_text', args: { text: 'Big News', fontSize: 72, x: 100, y: 80 } }),- JSON.stringify({ done: true, summary: 'Added the headline' }),- ]- const result = await runAgentLoop({- chat: async () => replies.shift() ?? '',- design,- emit: (e) => events.push(e),- awaitApply: async () => ({ ok: true }),- })- expect(result.summary).toBe('Added the headline')- expect(result.toolCalls).toBe(1)- const actionTypes = events.filter((e) => e.type === 'action').map((e) => (e as { actions: unknown[] }).actions)- expect(actionTypes).toHaveLength(1)- expect(actionTypes[0][0]).toMatchObject({ type: 'addText', text: 'Big News' })- expect(events.some((e) => e.type === 'step')).toBe(true)- expect(events.some((e) => e.type === 'done')).toBe(true)- })-- it('self-corrects on a sanitize rejection without consuming the tool budget', async () => {- const replies = [- JSON.stringify({ thought: 'bad color', tool: 'update_elements', args: { ids: ['el-1'], patch: { fill: 'red' } } }),- JSON.stringify({ thought: 'fixed', tool: 'update_elements', args: { ids: ['el-1'], patch: { fill: '#FF0000' } } }),- JSON.stringify({ done: true, summary: 'Recolored' }),- ]- let applied = 0- const result = await runAgentLoop({- chat: async () => replies.shift() ?? '',- design,- emit: () => {},- awaitApply: async () => {- applied += 1- return { ok: true }- },- })- expect(result.toolCalls).toBe(1) // the rejected call did not count- expect(applied).toBe(1)- expect(result.summary).toBe('Recolored')- })-- it('stops at the step budget (anti over-ambition)', async () => {- const events: AgentEvent[] = []- const result = await runAgentLoop({- chat: async () => JSON.stringify({ thought: 'again', tool: 'get_page_state', args: {} }),- design,- emit: (e) => events.push(e),- awaitApply: async () => ({ ok: true }),- })- // get_page_state is a read tool — it still counts as a step turn- expect(result.steps).toBeLessThanOrEqual(AGENT_BUDGETS.maxSteps)- expect(events[events.length - 1].type).toBe('done')- })-- it('a destructive tool without confirmation is declined and not applied', async () => {- const replies = [- JSON.stringify({ thought: 'clean up', tool: 'delete_elements', args: { ids: ['el-1', 'el-2'] } }),- JSON.stringify({ done: true, summary: 'Kept everything' }),- ]- let applied = 0- const result = await runAgentLoop({- chat: async () => replies.shift() ?? '',- design,- emit: () => {},- confirmed: new Set(), // user has NOT approved delete_elements- awaitConfirm: async () => false,- awaitApply: async () => {- applied += 1- return { ok: true }- },- })- expect(applied).toBe(0)- expect(result.toolCalls).toBe(0)- expect(result.summary).toBe('Kept everything')- })-- it('a destructive tool WITH pre-approval applies', async () => {- const replies = [- JSON.stringify({ thought: 'clean up', tool: 'clear_page', args: {} }),- JSON.stringify({ done: true, summary: 'Cleared' }),- ]- let applied = 0- const result = await runAgentLoop({- chat: async () => replies.shift() ?? '',- design,- emit: () => {},- confirmed: new Set(['clear_page']),- awaitApply: async () => {- applied += 1- return { ok: true }- },- })- expect(applied).toBe(1)- expect(result.toolCalls).toBe(1)- })-- it('unknown tools get an actionable error observation, then the run can still finish', async () => {- const replies = [- JSON.stringify({ thought: 'try something', tool: 'make_coffee', args: {} }),- JSON.stringify({ done: true, summary: 'Nothing to do' }),- ]- const result = await runAgentLoop({- chat: async () => replies.shift() ?? '',- design,- emit: () => {},- awaitApply: async () => ({ ok: true }),- })- expect(result.summary).toBe('Nothing to do')- expect(result.toolCalls).toBe(0)- })-- it('client abort stops the loop and reports what happened', async () => {- const signal = { aborted: false, reason: 'Stopped by user' }- let calls = 0- const result = await runAgentLoop({- chat: async () => {- calls += 1- if (calls === 1) {- // the user hits Stop while the first action is in flight- signal.aborted = true- return JSON.stringify({ thought: 'x', tool: 'add_text', args: { text: 'Hi' } })- }- return JSON.stringify({ done: true, summary: 'should not reach' })- },- design,- emit: () => {},- signal,- })- expect(result.summary).toContain('Stopped')- })-})diff --git a/src/lib/agent/loop.ts b/src/lib/agent/loop.tsindex 18023fa..7be3aaf 100644--- a/src/lib/agent/loop.ts+++ b/src/lib/agent/loop.ts@@ -1,5 +1,5 @@// ─────────────────────────────────────────────────────────────-// Agent loop (v0.27) — the multi-step engine.+// Agent loop (v0.28) — the task-driven engine.//// Protocol (docs/AGENT-ARCHITECTURE.md): the model speaks strict JSON// turns; tools are sanitized at the boundary; validated actions are@@ -7,16 +7,33 @@// (editor parity + undo + collab for free). The server never writes// the document during a run.//-// Failure discipline (Loomic's lessons):-// · over-ambition → step/tool-call/wall-clock budgets-// · false completion → the final observation always carries fresh-// spatial analysis so "done" is grounded in the real page state-// · parse errors → one repair retry with the error shown, then stop+// v0.28 LIFECYCLE (Phase 4 — caps removed, guards kept):+// Termination is TASK-DRIVEN: done / user stop / user decline /+// fatal error. There is NO step or wall-clock product cap — a+// 40-step deck build with steady progress runs to completion.+// Machine-protection guards (AGENT_GUARDS) end a run only when it+// stops making progress: 3 consecutive strikes, an identical+// tool+args cycle, or the idle clock. Guards force a WRAP-UP+// ("state what's done and what remains"), never a silent kill.+//+// MODES (Phase 8): the tool surface is built per mode — review/+// explain/plan/discuss physically cannot write.+//+// BRIEF (Phase 5): a done turn in a create/improve run must pass+// brief validation (computed on the client against real state)+// or the model is told the unmet items and continues.+//+// COMPACTION: past AGENT_GUARDS.compactAtMessages the older+// step/observation turns are folded into one summary message so+// long runs stay inside provider context limits.// ─────────────────────────────────────────────────────────────-import { AGENT_BUDGETS, parseAgentTurn, type AgentEvent, type AgentTurn } from './protocol'-import { AGENT_TOOL_MAP, toolsPromptSection, fontFamilies, type ToolContext, type SanitizeResult } from './tools'+import { AGENT_GUARDS, AGENT_PROTOCOL_VERSION, parseAgentTurn, type AgentEvent, type AgentMode, type AgentTurn } from './protocol'+import { AGENT_TOOLS, AGENT_TOOL_MAP, fontFamilies, type ToolContext, type SanitizeResult, type AgentTool } from './tools'import { serializeDesignContext, contextValidIds, type AgentDesignCtx } from './context'+import { MODE_PROMPTS, MODE_TOOL_RISK } from './router'+import { skillsPromptSection, selectSkills, type DesignSkill } from './skills'+import { briefPromptSection, type DesignBrief } from './brief'/** The model client the loop needs — a thin callable so the loop is* unit-testable without the SDK. */@@ -25,6 +42,11 @@ export type ChatFn = (messages: { role: 'system' | 'user' | 'assistant'; contentexport interface LoopDeps {chat: ChatFndesign: AgentDesignCtx+ mode: AgentMode+ /** the run's brief contract (extracted by the route) */+ brief?: DesignBrief | null+ /** skills pre-selected by the route (or auto-selected here) */+ skills?: DesignSkill[]/** emitted (by the route) as SSE lines */emit: (event: AgentEvent) => void/** the confirm map from the client: tool name → approved this run */@@ -37,54 +59,141 @@ export interface LoopDeps {awaitApply?: () => Promise<{ ok: boolean; message?: string }>/** latest refreshed design context pushed by the client after applying */refreshedContext?: () => AgentDesignCtx+ /** client-side brief validation result (validated against real state) */+ validateBriefOnClient?: () => Promise<{ satisfied: boolean; unmet: string[] } | null>+}++export interface LoopResult {+ summary: string+ steps: number+ toolCalls: number+ findings?: { severity: 'P0' | 'P1' | 'P2' | 'P3'; issue: string; fix?: string }[]+ plan?: string[]+ verification?: string+}++/** Tools visible in this mode, filtered by risk tier. */+export function toolsForMode(mode: AgentMode): AgentTool[] {+ const allowed = MODE_TOOL_RISK[mode]+ return AGENT_TOOLS.filter((t) => allowed.includes(t.risk))+}++function toolsPromptSectionFor(mode: AgentMode): string {+ return toolsForMode(mode)+ .map((t) => `- ${t.name} (${t.risk}) — ${t.description} args: ${t.argsSpec}`)+ .join('\n')}/** The full system prompt for loop steps. */-export function loopSystemPrompt(design: AgentDesignCtx, ctx: ToolContext): string {- return [+export function loopSystemPrompt(deps: {+ design: AgentDesignCtx+ ctx: ToolContext+ mode: AgentMode+ brief?: DesignBrief | null+ skills?: DesignSkill[]+}): string {+ const { design, ctx, mode, brief, skills } = deps+ const lines: string[] = ['You are the Canvix design agent — an autonomous design assistant working inside a graphic editor.','You see the CURRENT design state below. You act ONLY through tools, one per turn.','',+ MODE_PROMPTS[mode],+ '','Reply with ONE JSON object per turn, nothing else:','{"thought": "one short sentence of reasoning", "tool": "tool_name", "args": { ... }}','or when finished:',- '{"done": true, "summary": "what you did, 1-2 sentences"}',+ '{"done": true, "summary": "what you did, 1-2 sentences", "plan": ["…"], "findings": [{"severity":"P0|P1|P2|P3","issue":"…","fix":"…"}]}',+ '(plan for plan mode; findings for review mode)','','TOOLS (risk: read | write | destructive):',- toolsPromptSection(),+ toolsPromptSectionFor(mode),'',`Fonts available (use EXACT names): ${fontFamilies().slice(0, 40).join(', ')}…`,'',+ ]++ if (brief) {+ const section = briefPromptSection(brief)+ if (section) lines.push(section, '')+ }++ const skillSection = skillsPromptSection(skills ?? [])+ if (skillSection) lines.push(skillSection, '')++ lines.push(+ serializeDesignContext(design),+ '','RULES:','1. Use only element ids from the context. After structural edits (add/delete), call get_page_state to refresh ids.',- '2. One tool per turn. Plan multi-step work: usually 2-5 tools are enough. Do NOT loop more than needed.',- '3. Destructive tools (delete_elements, clear_page) need user confirmation — the system pauses and asks; do not repeat the call in the same turn.',- '4. Keep 6% margins from page edges. Estimate text width ≈ 0.6 × fontSize × characters. Avoid overlaps — the context lists current ones; fix_overlaps resolves them.',- '5. Prefer the BRAND KIT colors/fonts when one is given.',- '6. When the goal is achieved, verify visually via get_page_state (once), then emit {"done":true,"summary":"…"}. Never claim work you did not do.',+ '2. One tool per turn. Plan multi-step work up front; work steadily until the task is genuinely complete — there is no step limit, only a stop when you finish or stop making progress.',+ '3. Destructive tools (delete_elements, clear_page, delete_page on non-empty pages) need user confirmation — the system pauses and asks; do not repeat the call in the same turn.',+ '4. Keep 6% margins from page edges. Use measure_text for real text widths before finalizing headings — never rely on the 0.6×fontSize estimate for tight fits. Avoid overlaps; fix_overlaps resolves accidental ones.',+ '5. Prefer the BRAND KIT colors/fonts when one is given; the BRIEF always outranks it.',+ '6. When the goal is achieved, verify via get_page_state (once) and validate_brief (create/improve runs), then emit {"done":true,"summary":"…"}. Never claim work you did not do; never claim completion while validate_brief reports unmet items.','7. Args must match each tool spec exactly. On an error observation, fix the args and retry — the error message tells you what to change.','8. Tools edit the CURRENT page only. To work on another page: goto_page {page: N}, then get_page_state — ids change with the page. add_page appends the LAST page.',- '',- 'CURRENT DESIGN:',- serializeDesignContext(design),- ].join('\n')+ '9. In review/explain mode, ground every claim in the state you read. Report missing items as missing — never describe them as present.',+ )+ return lines.join('\n')+}++function observationFor(tool: string, result: SanitizeResult, ok: boolean): string {+ if (ok) return `Tool ${tool}: ${result.ok ? result.observation : ''}`+ return `ERROR in ${tool}: ${result.ok ? 'unknown error' : result.error}`+}++/** Hash a tool call for cycle detection. */+function callHash(tool: string, args: unknown): string {+ try {+ return `${tool}:${JSON.stringify(args ?? {})}`+ } catch {+ return `${tool}:?`+ }}-/** Compact observation for a tool result (sent back as the next- * user-role message). Kept tiny — observations are the loop's- * context economy. */-function observationFor(tool: string, result: SanitizeResult, applied: boolean): string {- if (!result.ok) return `ERROR from ${tool}: ${result.error}`- return `${tool} ${applied ? 'OK' : 'QUEUED for confirmation'} — ${result.observation}`+/** Compact the message list: keep system + the first user message ++ * the last turns, summarize the middle into one assistant note. */+function compactMessages(messages: { role: 'system' | 'user' | 'assistant'; content: string }[]): { compacted: typeof messages; from: number } {+ if (messages.length <= 12) return { compacted: messages, from: messages.length }+ const system = messages.slice(0, 1)+ const firstUser = messages.slice(1, 2)+ const tail = messages.slice(-8)+ const middle = Math.max(0, messages.length - 1 - 1 - 8)+ const summary = `[context compacted — ${middle} earlier turns summarized] Earlier in this run you completed several steps. Key outcomes persist in the CURRENT DESIGN STATE inside the system context; element ids from before a get_page_state refresh may be stale — call get_page_state if unsure. Continue the task; do not redo completed work.`+ return {+ compacted: [...system, ...firstUser, { role: 'assistant', content: summary }, ...tail],+ from: messages.length,+ }}-/**- * Run the agent loop. Streams events through deps.emit; returns the- * final summary. Never throws for model/parse problems — those become- * error/aborted events + a returned message.- */-export async function runAgentLoop(deps: LoopDeps): Promise<{ summary: string; steps: number; toolCalls: number }> {- const { chat, design, emit, confirmed = new Set<string>(), signal } = deps+export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {+ const { chat, design, mode, emit, signal } = deps+ const brief = deps.brief ?? null+ const skills =+ deps.skills ??+ selectSkills(+ `${design.templateType ?? ''} ${design.name ?? ''} ${brief?.designType ?? ''}`,+ mode,+ !!(design.brand && (design.brand.colors?.length || design.brand.headingFont)),+ )++ const started = Date.now()+ let steps = 0+ let toolCalls = 0+ let modelCalls = 0+ let summary = ''+ let verification: string | undefined+ let strikes = 0+ let lastCallHash = ''+ let cycleCount = 0+ let lastProgressAt = started+ let lastUsageAt = started+ let briefValidated = false+ /** done turns rejected by the brief gate — a model that keeps+ * claiming completion without fixing the unmet items must not+ * loop forever (LangChain's "declare it blocked" pattern). */+ let doneRejections = 0+const toolCtx: ToolContext = {validIds: contextValidIds(design),width: design.width ?? 1080,@@ -93,126 +202,189 @@ export async function runAgentLoop(deps: LoopDeps): Promise<{ summary: string; s}const messages: { role: 'system' | 'user' | 'assistant'; content: string }[] = [- { role: 'system', content: loopSystemPrompt(design, toolCtx) },+ { role: 'system', content: loopSystemPrompt({ design, ctx: toolCtx, mode, brief, skills }) },+ {+ role: 'user',+ content: `User request mode: ${mode}. Begin.${+ mode === 'discuss' || mode === 'explain' ? ' Answer the question directly and emit done with your answer in the summary.' : ''+ }`,+ },]- const started = Date.now()- let steps = 0- /** PROGRESS steps — model turns that led somewhere (a valid tool- * call or a done). Rejections and repair retries do NOT count:- * the budget guards against over-ambition, and a run that wasted- * its 8 steps on two bad calls + a JSON repair never got to be- * ambitious in the first place (v0.27.3 audit fix). */- let progressSteps = 0- /** free-correction strikes — sanitize rejections and unknown tools- * are budget-free so the model can self-correct, but a model that- * NEVER produces a valid call would loop forever on wall-clock- * alone, growing the message list until the process dies (found- * by the harness OOM). Three strikes and the run ends. */- let strikes = 0- let toolCalls = 0- let summary = ''+ emit({ v: AGENT_PROTOCOL_VERSION, type: 'mode', mode, reason: `classified as ${mode}` })+ for (const s of skills) emit({ v: AGENT_PROTOCOL_VERSION, type: 'skill', id: s.id, name: s.name })+ if (brief) emit({ v: AGENT_PROTOCOL_VERSION, type: 'brief', brief: brief as unknown as Record<string, unknown> })++ // a run "makes progress" on every applied tool call+ const markProgress = () => {+ strikes = 0+ lastProgressAt = Date.now()+ }while (true) {- // ── budgets & abort ──────────────────────────────────────+ // ── task-driven stops ───────────────────────────────────if (signal?.aborted) {- emit({ v: 1, type: 'aborted', reason: signal.reason ?? 'Stopped by user' })- return { summary: summary || 'Stopped by the user.', steps, toolCalls }+ emit({ v: AGENT_PROTOCOL_VERSION, type: 'aborted', reason: signal.reason ?? 'Stopped by user' })+ return { summary: summary || 'Stopped by the user.', steps, toolCalls, verification }+ }++ // ── resource guards (machine protection, NOT product caps) ──+ if (strikes >= AGENT_GUARDS.strikes) {+ emit({+ v: AGENT_PROTOCOL_VERSION,+ type: 'error',+ message: `Stopped after ${AGENT_GUARDS.strikes} consecutive invalid tool calls — the error under each step explains what to fix; try rephrasing the request.`,+ code: 'STRIKES',+ })+ return { summary: summary || 'Stopped after repeated invalid calls.', steps, toolCalls, verification }}- if (progressSteps >= AGENT_BUDGETS.maxSteps || toolCalls >= AGENT_BUDGETS.maxToolCalls) {+ if (Date.now() - lastProgressAt > AGENT_GUARDS.idleMs) {emit({- v: 1,+ v: AGENT_PROTOCOL_VERSION,type: 'done',- summary: summary || 'Reached the step budget — everything applied so far is kept. Refine with another message.',+ summary: 'The run stopped making progress and was wrapped up. Everything applied so far is kept — send a follow-up message to continue.',steps,toolCalls,+ verification,})- return { summary, steps, toolCalls }+ return { summary, steps, toolCalls, verification }}- if (strikes >= 3) {- emit({- v: 1,- type: 'error',- message: 'Stopped after 3 invalid tool calls in a row — the error messages under each step explain what to fix; try rephrasing the request.',- })- return { summary, steps, toolCalls }- }- if (Date.now() - started > AGENT_BUDGETS.maxWallMs) {- emit({ v: 1, type: 'done', summary: 'Time budget reached — applied work is kept.', steps, toolCalls })- return { summary, steps, toolCalls }++ // ── compaction (memory + provider context protection) ───+ if (messages.length > AGENT_GUARDS.maxMessages) {+ const { compacted, from } = compactMessages(messages)+ const to = compacted.length+ messages.length = 0+ messages.push(...compacted)+ emit({ v: AGENT_PROTOCOL_VERSION, type: 'compact', fromMessages: from, toMessages: to })}- // ── one model turn ───────────────────────────────────────+ // ── one model turn ──────────────────────────────────────let raw = ''try {+ modelCalls += 1raw = await chat(messages)} catch (err) {emit({- v: 1,+ v: AGENT_PROTOCOL_VERSION,type: 'error',- message: `The AI provider failed: ${err instanceof Error ? err.message.slice(0, 200) : 'unknown error'}.`,+ message: `The AI provider failed: ${err instanceof Error ? err.message.slice(0, 200) : 'unknown error'}. Applied work is kept — retry to continue.`,+ code: 'PROVIDER',})- return { summary, steps, toolCalls }+ return { summary, steps, toolCalls, verification }}+const turn = parseAgentTurn(raw)if (!turn) {- // one repair attempt: show the model its own garbage- if (steps === 0 && messages[messages.length - 1].role !== 'assistant') {+ strikes += 1+ if (strikes < AGENT_GUARDS.strikes) {messages.push({ role: 'assistant', content: raw.slice(0, 500) })messages.push({role: 'user',content: 'That was not valid JSON. Reply with exactly one JSON object: {"thought","tool","args"} or {"done":true,"summary"}.',})- steps += 1continue}- emit({ v: 1, type: 'error', message: 'The model reply was not parseable JSON after a retry.' })- return { summary, steps, toolCalls }+ continue // the strike guard above ends the run next iteration}- steps += 1messages.push({ role: 'assistant', content: raw.slice(0, 2000) })// ── done? ────────────────────────────────────────────────if (turn.done) {- summary = String(turn.summary ?? '').slice(0, 500) || 'Done.'- emit({ v: 1, type: 'done', summary, steps, toolCalls })- return { summary, steps, toolCalls }+ summary = String(turn.summary ?? '').slice(0, 800) || 'Done.'+ // BRIEF GATE (Phase 5): create/improve runs must validate+ // against real client state before completion is accepted+ if ((mode === 'create' || mode === 'improve') && brief && deps.validateBriefOnClient && !briefValidated) {+ const v = await deps.validateBriefOnClient()+ if (v && !v.satisfied) {+ doneRejections += 1+ if (doneRejections >= 3) {+ // the model cannot or will not satisfy the brief — end+ // HONESTLY with the unmet list instead of looping+ const unmetList = v.unmet.map((u) => `· ${u}`).join('\n')+ const blockedSummary = `Stopped: the brief still has unmet requirements after ${doneRejections} completion attempts. Applied work is kept.\nUnmet:\n${unmetList}`+ emit({ v: AGENT_PROTOCOL_VERSION, type: 'done', summary: blockedSummary, steps, toolCalls })+ return { summary: blockedSummary, steps, toolCalls }+ }+ messages.push({+ role: 'user',+ content: `NOT DONE (attempt ${doneRejections} of 3) — brief validation against the real canvas found unmet requirements:\n${v.unmet.map((u) => `· ${u}`).join('\n')}\nFix these now with concrete tool calls (the exact values are in the DESIGN BRIEF CONTRACT), then emit done again. If a requirement is impossible, say so in your summary.`,+ })+ continue+ }+ if (v?.satisfied) {+ briefValidated = true+ verification = 'Brief contract validated against the live canvas — all mandatory items present.'+ }+ }+ emit({ v: AGENT_PROTOCOL_VERSION, type: 'done', summary, steps, toolCalls, verification })+ return { summary, steps, toolCalls, findings: turn.findings, plan: turn.plan, verification }}// ── a tool call ──────────────────────────────────────────const toolName = typeof turn.tool === 'string' ? turn.tool : ''+ const allowed = toolsForMode(mode)const tool = AGENT_TOOL_MAP.get(toolName)const thought = String(turn.thought ?? '').slice(0, 300)if (!tool) {- const known = [...AGENT_TOOL_MAP.keys()].slice(0, 6).join(', ')+ const known = allowed.slice(0, 8).map((t) => t.name).join(', ')+ strikes += 1+ messages.push({+ role: 'user',+ content: `ERROR: unknown tool "${toolName}". Valid tools in ${mode} mode: ${known}${allowed.length > 8 ? '…' : ''}. Retry with a valid tool.`,+ })+ continue+ }+ if (!allowed.includes(tool)) {+ // the tool exists but is outside this mode's surfacestrikes += 1messages.push({role: 'user',- content: `ERROR: unknown tool "${toolName}". Valid tools: ${known}… (full list in the system prompt). Retry with a valid tool.`,+ content: `ERROR: "${toolName}" is not available in ${mode} mode (it modifies the design). This mode is read-only. Analyze with get_page_state and report findings instead.`,})continue}- emit({ v: 1, type: 'step', index: steps, thought, tool: toolName })+ emit({ v: AGENT_PROTOCOL_VERSION, type: 'step', index: steps, thought, tool: toolName })const args = (turn.args && typeof turn.args === 'object' && !Array.isArray(turn.args) ? turn.args : {}) as Record<string, unknown>const result = tool.sanitize(args, toolCtx)+ // cycle detection: the identical call twice in a row is tolerated+ // (a legitimate retry), the THIRD consecutive identical attempt+ // wraps the run up BEFORE applying it — repeating the same+ // operation a third time cannot add anything+ const hash = callHash(toolName, args)+ if (result.ok) {+ if (hash === lastCallHash) {+ cycleCount += 1+ if (cycleCount >= AGENT_GUARDS.cycleRepeat - 1) {+ emit({+ v: AGENT_PROTOCOL_VERSION,+ type: 'done',+ summary: 'The run repeated the same operation without effect and was wrapped up. Applied work is kept — describe the next change to continue.',+ steps,+ toolCalls,+ verification,+ })+ return { summary, steps, toolCalls, verification }+ }+ } else {+ cycleCount = 0+ }+ lastCallHash = hash+ }+if (!result.ok) {- // free correction: rejected calls don't consume the tool budget- // (but they cost a strike — 3 in a row end the run)+ // free correction: rejected calls cost only a strikestrikes += 1messages.push({ role: 'user', content: observationFor(toolName, result, false) })continue}- strikes = 0- // a SANITIZED call is progress — it will reach the client as an- // action (or a confirmation prompt). Rejections above stay free.- progressSteps += 1- // ── destructive gate ─────────────────────────────────────- if (tool.risk === 'destructive' && !confirmed.has(toolName)) {+ // ── destructive gate ────────────────────────────────────+ if (tool.risk === 'destructive' && !deps.confirmed?.has(toolName)) {emit({- v: 1,+ v: AGENT_PROTOCOL_VERSION,type: 'action',stepIndex: steps,callId: `call-${steps}-${Math.random().toString(36).slice(2, 8)}`,@@ -220,8 +392,6 @@ export async function runAgentLoop(deps: LoopDeps): Promise<{ summary: string; stool: toolName,actions: result.actions,})- // the client pauses for confirmation; the loop waits for the ack- // through the pendingConfirm channel provided by the routeconst approved = await deps.awaitConfirm?.(toolName) ?? falseif (!approved) {messages.push({@@ -230,9 +400,6 @@ export async function runAgentLoop(deps: LoopDeps): Promise<{ summary: string; s})continue}- // v0.27.3: an approved destructive call still needs the client's- // apply ack — the failure path (apply throws on the client) must- // feed the error back to the model instead of counting as doneconst ack = (await deps.awaitApply?.()) ?? { ok: true }if (!ack.ok) {messages.push({@@ -243,7 +410,7 @@ export async function runAgentLoop(deps: LoopDeps): Promise<{ summary: string; s}} else {emit({- v: 1,+ v: AGENT_PROTOCOL_VERSION,type: 'action',stepIndex: steps,callId: `call-${steps}-${Math.random().toString(36).slice(2, 8)}`,@@ -251,7 +418,6 @@ export async function runAgentLoop(deps: LoopDeps): Promise<{ summary: string; stool: toolName,actions: result.actions,})- // the client applies + acks; the route resumes usconst ack = (await deps.awaitApply?.()) ?? { ok: true }if (!ack.ok) {messages.push({@@ -263,22 +429,58 @@ export async function runAgentLoop(deps: LoopDeps): Promise<{ summary: string; s}toolCalls += 1- emit({ v: 1, type: 'observation', stepIndex: steps, message: result.observation })+ steps += 1+ markProgress()+ emit({ v: AGENT_PROTOCOL_VERSION, type: 'observation', stepIndex: steps - 1, message: result.observation })- // get_page_state: the route injects the refreshed context the client- // sent with its ack — otherwise a generic observation+ // usage telemetry: immediately on the first apply, then at most+ // every 2s (the panel shows live counts without waiting)+ const now = Date.now()+ if (toolCalls === 1 || now - lastUsageAt > 2000) {+ lastUsageAt = now+ emit({ v: AGENT_PROTOCOL_VERSION, type: 'usage', turns: steps, toolCalls, elapsedMs: now - started, modelCalls })+ }++ // get_page_state: inject the refreshed context the client sentif (toolName === 'get_page_state' && deps.refreshedContext) {const refreshed = deps.refreshedContext()messages.push({role: 'user',- content: `UPDATED PAGE STATE:\n${serializeDesignContext(refreshed)}`,+ content: `UPDATED PAGE STATE (fresh from the client after your edits):\n${serializeDesignContext(refreshed)}`,})- // future tools validate against the refreshed ids+ // refresh the local tool context too — new ids are valid nowtoolCtx.validIds = contextValidIds(refreshed)- if (refreshed.width) toolCtx.width = refreshed.width- if (refreshed.height) toolCtx.height = refreshed.height- } else {- messages.push({ role: 'user', content: observationFor(toolName, result, true) })+ continue+ }++ // validate_brief: the client computed the result against real state+ if (toolName === 'validate_brief' && deps.validateBriefOnClient) {+ const v = await deps.validateBriefOnClient()+ if (v) {+ messages.push({+ role: 'user',+ content: v.satisfied+ ? 'BRIEF VALIDATION PASSED — every mandatory text, color and dimension is present on the canvas. You may emit done.'+ : `BRIEF VALIDATION FAILED — unmet requirements:\n${v.unmet.map((u) => `· ${u}`).join('\n')}\nFix these now, then re-validate.`,+ })+ if (v.satisfied) {+ briefValidated = true+ verification = 'Brief contract validated against the live canvas.'+ }+ }+ continue+ }++ messages.push({ role: 'user', content: observationFor(toolName, result, true) })++ // disclose approaching compaction so the model wraps up cleanly+ if (messages.length === AGENT_GUARDS.turnWarnAt) {+ messages.push({+ role: 'user',+ content: `NOTE: this conversation is getting long (${messages.length} messages). Wrap up the remaining work efficiently; older turns will be summarized soon.`,+ })}}}++export { selectSkills }diff --git a/src/lib/agent/protocol.ts b/src/lib/agent/protocol.tsindex 8c6072d..1a40d0e 100644--- a/src/lib/agent/protocol.ts+++ b/src/lib/agent/protocol.ts@@ -1,48 +1,83 @@// ─────────────────────────────────────────────────────────────-// Agent protocol (v0.27) — the wire contract between the agent+// Agent protocol (v0.28) — the wire contract between the agent// route (SSE producer), the loop, and the client panel.//-// Design notes (docs/AGENT-ARCHITECTURE.md):-// · The z-ai SDK / BYOK endpoints expose no native function calling,-// so the loop speaks a strict JSON protocol: each model turn is-// {"thought","tool","args"} or {"done":true,"summary"}.-// · Events are one JSON object per SSE `data:` line — small enough to-// flush immediately, versioned with `v` so the client can ignore-// unknown event kinds instead of breaking.-// · Budgets are protocol-level constants so the route, the loop and-// the tests agree on the exact numbers.+// v0.28 overhaul (docs/AI-CAPABILITY-MATRIX.md):+// · ARBITRARY CAPS REMOVED (Phase 4): no more maxSteps/maxToolCalls/+// maxWallMs product limits. Termination is task-driven — done,+// user stop, user decline, unrecoverable error — plus RESOURCE+// GUARDS that protect the machine, not the product: consecutive+// failure strikes, cycle detection (identical tool+args hash),+// and an idle clock (no PROGRESS for a long window). Guards end+// the run with a forced wrap-up, never a silent kill.+// · MODES (Phase 8): runs carry a mode (create/edit/review/improve/+// explain/plan/discuss); read-only modes get a tool surface with+// ZERO write tools — structurally incapable of editing.+// · USAGE OBSERVABILITY: `usage` events stream turns/toolCalls/ms+// so the panel can show cost; history compaction is reported+// via the `compact` event.+// · BRIEF CONTRACT (Phase 5): runs carry a structured brief+// (mandatory text/colors/dimensions…); completion validation+// runs against REAL refreshed state, not the model's word.// ─────────────────────────────────────────────────────────────-export const AGENT_PROTOCOL_VERSION = 1+export const AGENT_PROTOCOL_VERSION = 2-/** Hard budgets — the anti-over-ambition rails (Loomic's failure modes:- * over-ambition and false completion). A run can never exceed these no- * matter what the model tries. */-export const AGENT_BUDGETS = {- /** model turns in the loop (thought+tool or done) */- maxSteps: 8,- /** total tool executions (sanitize-rejected calls do NOT count — the- * model gets the error for free and can correct itself) */- maxToolCalls: 12,- /** wall-clock cap for the whole run, ms */- maxWallMs: 90_000,+/**+ * Resource guards — machine protection, not product caps (Phase 4).+ * A run may continue as long as it keeps making PROGRESS (a new,+ * distinct, validated tool call). These are the only stop+ * conditions besides the task-driven ones (done / stop / decline /+ * fatal error):+ *+ * · strikes — 3 consecutive invalid calls (unknown tool,+ * sanitize reject, unparseable turn). A success+ * resets the streak. (flail protection, v0.27.3)+ * · cycleRepeat — the same tool+args hash N times in a row means+ * the model is looping. (tldraw repeat pattern.)+ * · idleMs — no PROGRESS for this long (a model that keeps+ * chatting but never successfully calls tools).+ * Generous default: 4 minutes.+ * · compactAt / maxMessages — conversation-size ceiling: compaction+ * summarizes older steps instead of growing+ * without bound (memory + provider context).+ * · turnWarnAt — disclose approaching compaction to the model.+ *+ * These are deliberately NOT "maxSteps": a 40-step deck build with+ * steady progress runs to completion.+ */+export const AGENT_GUARDS = {+ strikes: 3,+ cycleRepeat: 3,+ idleMs: 240_000,+ compactAtMessages: 60,+ maxMessages: 120,+ turnWarnAt: 50,/** actions attached to a single-shot `act` reply */- maxDirectActions: 3,- /** history messages replayed to the model (compacted client-side) */- maxHistory: 10,+ maxDirectActions: 6,} as const-/** Risk tier of a tool — drives the confirm gate (jaaz's- * tool_confirmation_manager pattern, three-tier Anthropic model). */+/** v0.28 modes (Phase 8). Read-only modes (review, explain, plan,+ * discuss) run with a ZERO-write tool surface. */+export type AgentMode = 'create' | 'edit' | 'review' | 'improve' | 'explain' | 'plan' | 'discuss'++export const AGENT_MODES: readonly AgentMode[] = ['create', 'edit', 'review', 'improve', 'explain', 'plan', 'discuss']++/** Risk tier of a tool — drives the confirm gate (three-tier+ * Anthropic pattern: reads free, in-scope writes auto, destructive+ * confirmed per callId). */export type ToolRisk = 'read' | 'write' | 'destructive'-/** One streamed progress event (SSE `data:` payload). */+/** One streamed progress event (SSE `data:` payload). v2. */export type AgentEvent =- | { v: number; type: 'start'; intent: 'act' | 'plan' | 'ask'; plan?: string[] }- | { v: number; type: 'step'; index: number; thought: string; tool: string }+ | { v: number; type: 'start'; intent: AgentMode; plan?: string[]; runId?: string }+ | { v: number; type: 'mode'; mode: AgentMode; reason: string }+ | { v: number; type: 'skill'; id: string; name: string }+ | { v: number; type: 'brief'; brief: Record<string, unknown> }| { v: number; type: 'plan'; steps: string[] }+ | { v: number; type: 'step'; index: number; thought: string; tool: string }/** a validated action batch the client should apply NOW (auto mode) or- * hold for approval (manual mode / destructive) */+ * hold for approval (destructive) */| {v: numbertype: 'action'@@ -56,7 +91,11 @@ export type AgentEvent =* down; defined here so both sides share the shape */| { v: number; type: 'ack'; callId: string; ok: boolean; message?: string }| { v: number; type: 'observation'; stepIndex: number; message: string }- | { v: number; type: 'done'; summary: string; steps: number; toolCalls: number }+ /** periodic run telemetry — turns, tool calls, wall ms, model calls */+ | { v: number; type: 'usage'; turns: number; toolCalls: number; elapsedMs: number; modelCalls: number }+ /** the loop compacted older history — the panel may show "context trimmed" */+ | { v: number; type: 'compact'; fromMessages: number; toMessages: number }+ | { v: number; type: 'done'; summary: string; steps: number; toolCalls: number; verification?: string }| { v: number; type: 'error'; message: string; code?: string }| { v: number; type: 'aborted'; reason: string }@@ -67,14 +106,14 @@ export interface AgentTurn {args?: Record<string, unknown>done?: booleansummary?: string- /** v0.28 reserved: variation selector for parallel exploration */- variant?: number+ /** optional plan emitted by the planner step */+ plan?: string[]+ /** review/explain structured findings */+ findings?: { severity: 'P0' | 'P1' | 'P2' | 'P3'; issue: string; fix?: string }[]}-/** Keys that mark a parsed object as an actual agent turn (or an- * act-route reply). Used to prefer a real turn over preamble objects- * when a model emits several JSON objects in one reply. */-const TURN_KEYS = new Set(['tool', 'done', 'thought', 'reply', 'intent'])+/** Keys that mark a parsed object as an actual agent turn. */+const TURN_KEYS = new Set(['tool', 'done', 'thought', 'reply', 'intent', 'plan', 'findings'])function looksLikeTurn(obj: Record<string, unknown>): boolean {return Object.keys(obj).some((k) => TURN_KEYS.has(k))@@ -84,13 +123,9 @@ function looksLikeTurn(obj: Record<string, unknown>): boolean {* leading prose, trailing junk and MULTI-OBJECT replies (a model that* emits `{"a":1}\n{"tool":…}` — a parsed object that looks like a* turn wins over one that doesn't; among turn-shaped candidates the- * outermost/earliest wins, which is the original single-object- * behavior). Returns null when no JSON object is found. */+ * outermost/earliest wins). Returns null when no JSON object is found. */export function parseAgentTurn(raw: string): AgentTurn | null {const cleaned = raw.replace(/```(?:json)?/gi, '').trim()- // window scan: starts forward (outermost first), ends backward- // (largest window first) — nested braces in strings are skipped- // naturally because only windows that PARSE countlet fallback: Record<string, unknown> | null = nullfor (let start = cleaned.indexOf('{'); start !== -1; start = cleaned.indexOf('{', start + 1)) {let end = cleaned.lastIndexOf('}')@@ -103,12 +138,8 @@ export function parseAgentTurn(raw: string): AgentTurn | null {}if (obj && typeof obj === 'object') {if (looksLikeTurn(obj)) return obj as AgentTurn- // remember the first parseable object as a fallback (a reply- // with no turn keys at all — e.g. act-route {"reply":…} is- // covered by TURN_KEYS, so this is genuinely unknown-shaped)if (!fallback) fallback = obj- break // this start's largest window parsed; smaller windows- // of the same start would be inner fragments — move on+ break}end = cleaned.lastIndexOf('}', end - 1)}diff --git a/src/lib/agent/router.ts b/src/lib/agent/router.tsindex 9dac633..5b11e5d 100644--- a/src/lib/agent/router.ts+++ b/src/lib/agent/router.ts@@ -1,69 +1,132 @@// ─────────────────────────────────────────────────────────────-// Agent router (v0.27) — one cheap classification call that keeps-// simple work cheap (tldraw request() vs prompt(); Anthropic's-// "don't default to agents").+// Agent modes (v0.28, Phase 8) — intent → MODE with a tool surface.//-// act → one completion with the tools spec → up to 3 actions-// ask → one completion, answer only, no tools-// plan → the full agent loop+// Replaces the v0.27 act/ask/plan triage. Seven modes:+// create — build a new design from a written request+// edit — specific modifications to the existing design+// review — inspect + feedback, ZERO write tools+// improve — apply design refinements+// explain — answer questions about the design/tools, ZERO writes+// plan — prepare a spec or proposed changes, ZERO writes+// discuss — product/engineering talk, ZERO writes//-// The classifier is a model call with a tiny JSON contract. On any-// doubt (parse failure, provider error, timeout) it falls back to-// `plan` — the loop handles everything an `act` could, just slower.+// Read-only modes are ENFORCED STRUCTURALLY: the loop builds the+// tool map from the mode's allowlist, so a review run physically+// cannot call add_text no matter what the model tries. This kills+// the "agent edited the canvas during a review" failure class.+//+// The heuristic pre-classifier stays free (zero model calls) and+// now returns a mode; the model classifier refines when unsure.// ─────────────────────────────────────────────────────────────-export type AgentIntent = 'act' | 'ask' | 'plan'+import type { AgentMode } from './protocol'-/** Heuristic pre-classifier — free, zero-latency. Runs BEFORE the model- * call; when it is confident (≥ 2 signals), the model call is skipped- * entirely. Returns null when unsure. */-export function heuristicIntent(message: string): AgentIntent | null {- const m = message.trim().toLowerCase()- if (!m) return null- // questions about the design / advice- const askSignals = [- /^(what|why|how|which|when|where|who)\b/,- /\b(is|are|do|does|can|should) (this|it|the|these)\b.*\?/,- /\bwhat do you think\b/,- /\breview (this|my)\b/,- /\bfeedback\b.*\?/,- /\bcritique\b/,- ]- if (askSignals.filter((re) => re.test(m)).length >= 1 && m.endsWith('?')) return 'ask'- // multi-step briefs → plan- const planSignals = [- /\b(and|then|also|plus)\b.*\b(and|then|also|plus|with|including)\b/,- /\b(design|create|make|build)\s+(a|an|me|the)\b/,- /\bfull\b.*\b(layout|design|page)\b/,- /\bposter\b.*\b(with|and|palette)\b/,- /\blaunch\b.*\b(with|and|palette)\b/,- /\bnew colors and fonts\b/,- /\bcolors? and fonts?\b.*\b(new|change|swap)\b/,- ]- // strong plan intents fire on ONE match — a redesign/rebrand is- // never a surgical edit no matter how it's phrased (harness catch)- const strongPlan = /\b(complete|full|total)\s+(redesign|makeover|rebrand)\b|\brebrand\b|\bcomplete redesign\b/- if (strongPlan.test(m) || planSignals.filter((re) => re.test(m)).length >= 2) return 'plan'- // surgical single edits → act- const actSignals = [- /\b(make|set|change|turn|swap|move|align|center|centre|delete|remove|add|bold|italic|underline|bigger|smaller|recolor|recolour|color|colour)\b/,- /^\s*(bold|italic|underline)\s+(this|it|the)\b/,+/** Which tool-risk tiers each mode may use. Write-capable modes get+ * read+write (+destructive through the confirm gate); read-only+ * modes get reads only. */+export const MODE_TOOL_RISK: Record<AgentMode, readonly ('read' | 'write' | 'destructive')[]> = {+ create: ['read', 'write', 'destructive'],+ edit: ['read', 'write', 'destructive'],+ improve: ['read', 'write', 'destructive'],+ review: ['read'],+ explain: ['read'],+ plan: ['read'],+ discuss: [],+}++export function modeAllowsWrites(mode: AgentMode): boolean {+ return MODE_TOOL_RISK[mode].includes('write')+}++/** System-prompt heading per mode. */+export const MODE_PROMPTS: Record<AgentMode, string> = {+ create: 'MODE: CREATE — build the requested design on the canvas. Empty or stale pages are yours to fill; respect the Design Brief Contract exactly.',+ edit: 'MODE: EDIT — perform the specific requested modifications. Touch only what the request implies; preserve everything else.',+ review: 'MODE: REVIEW — inspect the design and report findings. You have NO write tools: every critique must be grounded in the page state you read. Report only what is actually present; missing required items are findings, not facts to invent. End with {"done":true,"summary":…,"findings":[{severity,issue,fix}]}.',+ improve: 'MODE: IMPROVE — apply professional design refinements (typography, hierarchy, spacing, contrast, alignment). Preserve content and intent; improve execution.',+ explain: 'MODE: EXPLAIN — answer the question about the design, its elements or the editor. Read state as needed; do not modify anything.',+ plan: 'MODE: PLAN — read the design and produce a concrete plan (steps, elements, colors, fonts) WITHOUT applying it. End with {"done":true,"summary":…,"plan":[…steps]}.',+ discuss: 'MODE: DISCUSS — a product/engineering conversation about Canvix (architecture, features, bugs, workflow). The canvas is not in scope; answer directly and end with {"done":true,"summary":…}.',+}++/** Free heuristic pre-classifier — runs before any model call.+ * Returns { mode, confidence }: 'high' skips the model call,+ * 'low' lets the model classifier decide. */+export function heuristicMode(message: string): { mode: AgentMode; confidence: 'high' | 'low' } {+ const m = message.trim()+ if (!m) return { mode: 'discuss', confidence: 'low' }+ const lower = m.toLowerCase()++ // discuss: about the tool/product itself, not the user's design+ const productWords = /\b(canvix|the (app|editor|product|repo|codebase)|your (architecture|agent|tools?)|this project|github)\b/+ const asksAboutProduct = productWords.test(lower) && /\b(how (does|do|is|are)|why|bug|broken|error|architecture|implemented|feature|work)s?\b/.test(lower)+ const fixTheProduct = /\bfix (the|your) (agent|editor|app|code|bug)|\bagent'?s (tool|loop|architecture)\b/.test(lower)+ if (asksAboutProduct || fixTheProduct) return { mode: 'discuss', confidence: 'high' }++ // review: critique/feedback asks — never modify+ if (/\b(what'?s wrong|critique|review|feedback|rate|score|assess|evaluate|how does (this|it) look)\b/.test(lower)) {+ return { mode: /\band (fix|improve|change)\b/.test(lower) ? 'improve' : 'review', confidence: 'high' }+ }++ // explain: questions about the current design or editor features+ if (+ (/\b(what (font|color|size|element)s?|which font|how many (elements|pages|texts)|what does (this|the))\b/.test(lower) &&+ (lower.endsWith('?') || lower.includes('what'))) ||+ /^how (does|do|can) .+(work|function)\b.*\??$/.test(lower) // "how does gradient editing work?"+ ) {+ return { mode: 'explain', confidence: 'high' }+ }++ // plan: explicit planning asks+ if (/\b(plan|propose|outline|design spec|how would you (redesign|approach))\b/.test(lower) && !/\b(then do it|and apply|then apply)\b/.test(lower)) {+ return { mode: 'plan', confidence: 'high' }+ }++ // improve: polish/make-professional requests on an existing design+ if (/\b(make (this|it) (more )?(professional|better|prettier|nicer|polished)|polish|clean up|refine|jazz|spice|tighten)\b/.test(lower)) {+ return { mode: 'improve', confidence: 'high' }+ }++ // create: build briefs. Artifact nouns make intent unambiguous —+ // "make a poster" is create even though "make" is also a surgical+ // edit verb ("make the title bold")+ const artifactNoun = /\b(poster|flyer|menu|logo|banner|thumbnail|deck|presentation|slide|campaign|invitation|infographic|card|graphic|advert|ad|cover|header|brochure|certificate|resume|newsletter)\b/+ if (artifactNoun.test(lower) && m.split(/\s+/).length >= 2) return { mode: 'create', confidence: 'high' }+ const createSignals = [+ /\b(design|create|make|build|generate)\b.*\b(a|an|me|the|some)\b/,+ /\bcomplete redesign\b|\brebrand\b|\bmakeover\b/,]- if (actSignals.some((re) => re.test(m)) && m.split(/\s+/).length <= 18) return 'act'- return null+ if (createSignals.filter((re) => re.test(lower)).length >= 1 && m.split(/\s+/).length >= 3) {+ // "make X bold" is edit, not create — single-element surgical verbs+ const surgical = /\b(make|set|change|turn|swap|move|align|center|centre|delete|remove|add|bold|italic|underline|bigger|smaller|recolor|recolour|rotate|flip)\b/.test(lower) && m.split(/\s+/).length <= 18+ const mentionsBuilding = /\b(from scratch|new|blank)\b/.test(lower)+ if (!surgical || mentionsBuilding) return { mode: 'create', confidence: 'high' }+ }++ // edit: surgical single-element changes+ const editSignals = /\b(make|set|change|turn|swap|move|align|center|centre|delete|remove|add|bold|italic|underline|bigger|smaller|recolor|recolour|rotate|flip|resize|rename|duplicate)\b/+ if (editSignals.test(lower) && m.split(/\s+/).length <= 25) return { mode: 'edit', confidence: 'high' }++ return { mode: 'discuss', confidence: 'low' }}-/** System prompt for the model classifier. */+/** System prompt for the model classifier (used when heuristics are+ * unsure). Reply JSON {"mode": "…"}. */export const ROUTER_SYSTEM =- 'You classify user messages to a design-editor AI. Reply ONLY with JSON: {"intent":"act"|"ask"|"plan"}.\n' +- 'act = one surgical edit or 2-3 quick edits (change a color, make the title bold, add one text).\n' +- 'ask = a question or advice request about the design, expecting an answer not edits (review, what font is this, how does this look).\n' +- 'plan = a bigger brief needing several steps (design/redesign/rebrand/complete layouts, anything with multiple goals or "and" chains of edits).\n' +- 'When unsure between act and plan, choose plan.'+ 'You classify user messages to a graphic-design editor AI. Reply ONLY with JSON: {"mode":"create"|"edit"|"review"|"improve"|"explain"|"plan"|"discuss"}.\n' ++ 'create = build a new design or a major rebuild from a brief (poster, deck, menu, campaign, "design me…").\n' ++ 'edit = specific modifications to the existing design (make the title bold, move the logo, change this color).\n' ++ 'review = inspect and critique the design WITHOUT changing it (what is wrong, how does it look, rate it).\n' ++ 'improve = apply professional refinements to the existing design (make it professional, polish it, fix the layout).\n' ++ 'explain = answer a question about the current design or the editor (what font is this, how many pages).\n' ++ 'plan = produce a plan/spec without applying it (propose a redesign, outline a deck).\n' ++ 'discuss = conversation about Canvix the product (architecture, bugs, features) with no canvas work.\n' ++ 'When unsure between create and edit, choose create only if the user asks for a new/rebuilt design; otherwise edit.'-/** Parse the classifier reply. Anything unreadable → plan (safe default). */-export function parseIntent(raw: string): AgentIntent {+/** Parse the classifier reply. Unreadable → null (caller keeps the+ * heuristic mode). */+export function parseMode(raw: string): AgentMode | null {const cleaned = raw.replace(/```(?:json)?/gi, '').trim()- const m = cleaned.match(/"intent"\s*:\s*"(act|ask|plan)"/)- return m ? (m[1] as AgentIntent) : 'plan'+ const m = cleaned.match(/"mode"\s*:\s*"(create|edit|review|improve|explain|plan|discuss)"/)+ return m ? (m[1] as AgentMode) : null}diff --git a/src/lib/agent/skills.ts b/src/lib/agent/skills.tsnew file mode 100644index 0000000..41e3f05--- /dev/null+++ b/src/lib/agent/skills.ts@@ -0,0 +1,377 @@+// ─────────────────────────────────────────────────────────────+// Design Skills Engine (v0.28, Phase 2).+//+// Progressive disclosure, Canvix-native (research/DESIGN-SKILLS-+// ENGINE-RESEARCH.md): the router matches a brief against skill+// METADATA only (id/name/description/whenToUse — a few tokens+// each); the winning skill's full PLAYBOOK (principles, planning+// steps, validation checklist) is injected into that run's system+// prompt. Nothing is preloaded wholesale, and skills are pure+// data — they steer the model; execution still rides the same+// validated tool bridge.+//+// Skill content is original Canvix work informed by public+// design-craft standards (WCAG contrast numbers, type-scale+// ratios, grid practice) — no third-party skill text copied.+// ─────────────────────────────────────────────────────────────++import type { AgentMode } from './protocol'++export interface DesignSkill {+ id: string+ name: string+ /** one line for the router — what this skill covers */+ description: string+ /** activation hints matched against the user message (lowercased) */+ whenToUse: string[]+ /** which modes benefit (create/improve/plan/review/edit) */+ modes: AgentMode[]+ version: string+ /** the full playbook — injected ONLY when this skill is selected */+ playbook: {+ /** core principles, imperative, short */+ principles: string[]+ /** ordered planning guidance for this kind of work */+ planning: string[]+ /** deterministic checks the model should run before done */+ validation: string[]+ }+}++export const DESIGN_SKILLS: DesignSkill[] = [+ {+ id: 'poster-design',+ name: 'Poster & Advertisement Design',+ description: 'Posters, flyers, ads, banners, promo graphics — one focal point, loud hierarchy, complete compositions.',+ whenToUse: ['poster', 'flyer', 'ad', 'advert', 'banner', 'promo', 'campaign', 'launch', 'sale', 'event graphic', 'grand opening', 'marketing'],+ modes: ['create', 'improve', 'plan', 'review'],+ version: '1.0.0',+ playbook: {+ principles: [+ 'ONE focal point: the headline dominates (40–60% of the vertical rhythm); everything else supports it.',+ 'Type scale: headline ≥ 3× the body size; subheadline sits between. Two font families maximum — a display/heading face + a workhorse body face.',+ 'Color discipline: ≤ 3 core colors (60% dominant, 30% secondary, 10% accent). The accent color is for the CTA and the single most important detail ONLY.',+ 'Contrast: text over image needs a scrim (dark overlay ≥ 35% opacity) or a solid plate. WCAG ≥ 4.5:1 for body, ≥ 3:1 for large headline.',+ 'Safe margins: ≥ 6% of the shortest page edge on every side; nothing touches the edge unless it is a deliberate full-bleed background.',+ 'Whitespace is structure: group related items (headline + sub + CTA), separate groups by at least the height of one body line.',+ 'A poster is 90% visual: 3–7 text elements maximum. Every word must earn its place.',+ ],+ planning: [+ 'Read the Design Brief Contract; list every mandatory text and color before placing anything.',+ 'Pick the composition archetype: centered hero (classic, confident), asymmetric split (modern, editorial), or full-bleed image with plate (photographic).',+ 'Place in order: background → headline block → subhead → CTA → supporting details (date/place/price) → one decorative element max.',+ 'For the CTA use the accent color; make it a filled shape or pill, not naked text.',+ 'End with fix_overlaps or get_page_state + manual geometry check; then validate_brief.',+ ],+ validation: [+ 'Every brief-required text exists VERBATIM on the page.',+ 'Every brief-required hex color appears on the page.',+ 'No text overlaps other text; text-on-image has a scrim.',+ 'Headline is readable at thumbnail size (fontSize ≥ 8% of page height for the main headline on a 1080 canvas).',+ 'Margins respected; CTA visually distinct.',+ ],+ },+ },+ {+ id: 'typography',+ name: 'Typography Intelligence',+ description: 'Font pairing, hierarchy, scale, spacing, line height, fitting, readability — the type system for any design.',+ whenToUse: ['font', 'typography', 'type', 'headline', 'title', 'heading', 'pairing', 'kerning', 'letter spacing', 'line height', 'text size', 'readab'],+ modes: ['create', 'improve', 'plan', 'review', 'edit'],+ version: '1.0.0',+ playbook: {+ principles: [+ 'Pairing: contrast, not conflict — pair a display face (geometric sans or high-contrast serif) for headings with a neutral workhorse (Inter, Poppins, Work Sans) for body. Never pair two display faces.',+ 'Safest pair is ONE family at 2–3 weights; add a second family only when the design needs a voice shift.',+ 'Modular scale: pick a ratio (1.2 subtle, 1.25 standard, 1.333 bold, 1.618 dramatic) and derive every size from the body size. Avoid off-scale arbitrary sizes.',+ 'Measure: 45–75 characters per line (≈65 ideal). Wider → break the text or narrow the box.',+ 'Line height: 1.1–1.3 for headings, 1.4–1.6 for body. Letter spacing: slightly negative (−2%) for huge headlines, 0 for body, +5–10% for ALL-CAPS labels.',+ 'Never rely on the 0.6×fontSize width estimate for final placement: call measure_text for anything that must fit a box.',+ 'Hierarchy has 3 levels max: headline / subhead / body. If a fourth size appears, demote it to weight or color instead.',+ 'Uppercase only for short labels (≤ 5 words); sentence case for everything else.',+ ],+ planning: [+ 'Inventory the text roles in the brief (headline, sub, body, CTA, captions).',+ 'Choose the pairing from the catalog (respect brand kit fonts when set).',+ 'Derive the scale from the format: body ≥ 16px on 1080-wide canvases; headline 3–6× body.',+ 'measure_text every heading before finalizing its box; if it clips, reduce size or wrap — never let it overflow.',+ ],+ validation: [+ 'No text element overflows its box (measure_text confirms).',+ 'Exactly 2–3 distinct font families; 3 hierarchy levels.',+ 'Line lengths within 45–75ch for body paragraphs.',+ ],+ },+ },+ {+ id: 'color',+ name: 'Color Intelligence',+ description: 'Palettes, harmony, contrast, gradients, backgrounds, accessible text colors, brand color use.',+ whenToUse: ['color', 'palette', 'contrast', 'gradient', 'background', 'harmon', 'accessible', 'wcag', 'shade', 'tint', 'recolor'],+ modes: ['create', 'improve', 'plan', 'review', 'edit'],+ version: '1.0.0',+ playbook: {+ principles: [+ '60/30/10: dominant (background) 60%, secondary (supporting plates/shapes) 30%, accent (CTA/highlight) 10%.',+ 'Build on ONE hue relationship: monochrome (shades of one hue — safest), analogous (neighbors), or complementary (opposites, maximum pop). Triads only for playful brands.',+ 'Text contrast ≥ 4.5:1 (body) / ≥ 3:1 (≥ 24px bold or 18.66px+ bold = "large text") against ITS ACTUAL BACKGROUND — a gradient background is checked at its lightest point under the text.',+ 'Never place mid-gray text on white or dark-gray on navy; when the palette forces it, darken/lighten the TEXT (keep brand colors on shapes, adjust the text shade).',+ 'One gradient per design: linear, ≤ 25° from a cardinal direction, hues within 60° of each other. Gradients are backgrounds or hero fills, not body text fills.',+ 'Dark-mode palettes: saturate less, lighten text in steps (gray-100/300/500), never pure #000 or #FFF for large fields — use #090B1A-navy / #F4F5F7-off-white.',+ 'The brand kit OUTRANKS your taste but never the brief: brief hexes are verbatim; brand colors fill the unassigned roles.',+ ],+ planning: [+ 'List the roles: background, headline, body, accent/CTA, decorative.',+ 'Assign brief-mandatory colors first, then brand colors, then derive the rest.',+ 'Check every text/background pair for contrast before committing (the vision/geometry validator will re-check).',+ ],+ validation: [+ 'Every brief-required hex appears verbatim.',+ 'No body text below 4.5:1; no large text below 3:1.',+ 'Accent color used on ≤ ~10% of the area (the CTA and one detail).',+ ],+ },+ },+ {+ id: 'layout',+ name: 'Layout & Composition',+ description: 'Grids, alignment, spacing, margins, grouping, balance, focal points, aspect-ratio-aware composition.',+ whenToUse: ['layout', 'align', 'grid', 'spacing', 'margin', 'composition', 'arrange', 'organize', 'balance', 'structure', 'position'],+ modes: ['create', 'improve', 'plan', 'review', 'edit'],+ version: '1.0.0',+ playbook: {+ principles: [+ 'Pick ONE grid and stay on it: 12-column (posters/decks), 2-column split (menus/pricing), centered single column (invitations/quotes).',+ 'Alignment: every element aligns to something (grid line, another element\'s edge, or the center axis). Random offsets read as mistakes.',+ 'Spacing rhythm: use a base unit (≈ 2% of page height) and multiples (1×, 2×, 4×). Same gap = same relationship.',+ 'Proximity: things that belong together sit close; separation between groups ≥ 2× the intra-group gap.',+ 'Vertical flow: the eye enters top-left (LTR), so the hierarchy cascade reads headline → visual → details → CTA.',+ 'Fill the canvas: no dead zones larger than ~20% of the page area unless intentional negative space (which anchors ONE side, never floats random holes).',+ 'Deliberate overlap is composition (text on a card, a plate behind a headline); accidental overlap is a bug — fix_overlaps knows the difference for text-on-card, verify the rest with get_page_state.',+ 'Aspect awareness: story/reel (9:16) stacks vertically with the CTA in the lower third; 16:9 decks work in rows; 1:1 balances radially or splits.',+ ],+ planning: [+ 'Compute the margin (6% of min(w,h)) and the base spacing unit before placing anything.',+ 'Sketch the regions: where does the headline block live, the visual, the detail row, the CTA. Give each a bounding box first, then fill.',+ 'Place background → large structural shapes → text blocks → small details. Use align_elements to true-up edges as you go.',+ ],+ validation: [+ 'All elements inside the safe margins (off-canvas list empty).',+ 'Element left edges or centers align on at least one shared axis per group.',+ 'Spacing between groups follows the rhythm (no 13px next to 40px gaps without reason).',+ ],+ },+ },+ {+ id: 'brand',+ name: 'Brand Identity',+ description: 'Brand kits, consistency, logo placement, cross-page and cross-format consistency, design tokens.',+ whenToUse: ['brand', 'logo', 'identity', 'consistent', 'style guide', 'rebrand', 'on-brand', 'guidelines'],+ modes: ['create', 'improve', 'plan', 'review'],+ version: '1.0.0',+ playbook: {+ principles: [+ 'The brand kit (colors, heading/body fonts) is the DEFAULT palette/typography — deviations need a reason stated in the plan.',+ 'Logo placement: consistent corner across every page/format (bottom-right or top-left are conventions), clear space around it = its cap-height, never stretch or recolor it.',+ 'Cross-page consistency: same background system, same heading style, same margin grid on every page of a multi-page design; vary the LAYOUT, not the system.',+ 'One accent discipline: the accent color is reserved for the key action per page — repeating it everywhere dilutes it.',+ 'When no brand kit exists, create a coherent one: pick heading + body fonts, 3 colors, and state them in the plan so every page uses the same values.',+ ],+ planning: [+ 'Read the brand kit from the context; if absent, define the system (fonts + 3 colors) BEFORE the first element.',+ 'For multi-page work, set page 1 as the style anchor and re-check each later page against it.',+ ],+ validation: [+ 'Every page uses the same heading font + accent color.',+ 'Logo (if placed) appears exactly once per page, same corner, unmodified.',+ ],+ },+ },+ {+ id: 'critique',+ name: 'Design Critique',+ description: 'Structured review: missing elements, hierarchy, composition, contrast, overflow, overlap, prompt-to-output match. Evidence-based findings.',+ whenToUse: ['review', 'critique', 'feedback', 'wrong with', 'rate', 'score', 'assess', 'evaluate', 'improve this', 'issues', 'problems'],+ modes: ['review', 'improve', 'plan'],+ version: '1.0.0',+ playbook: {+ principles: [+ 'Ground EVERY finding in observed state: cite element ids, sizes, colors from get_page_state — never an impression.',+ 'Severity ladder: P0 broken (missing required text, unreadable contrast, clipped content) / P1 major (weak hierarchy, misalignment, crowding) / P2 minor (spacing rhythm, color imbalance) / P3 polish (kerning, decorative details).',+ 'Compare against the brief FIRST (validate_brief), then craft (typography, color, layout), then polish.',+ 'Report only what is present. A missing element is reported as "missing", not described as if it existed.',+ 'For every finding, name the fix and the tool that applies it.',+ 'In review mode you have NO write tools — findings only; the user (or a follow-up improve run) applies them.',+ ],+ planning: [+ 'get_page_state first; if a brief exists, validate_brief and lead with unmet items.',+ 'Walk the craft ladder: hierarchy → contrast → alignment → spacing → overflow/overlap → consistency.',+ 'Rank findings by severity; cap the report at the top 5–7 — a wall of nitpicks hides the P0s.',+ ],+ validation: [+ 'Every finding cites an element id or a measured value.',+ 'No finding contradicts the actual state (no phantom elements).',+ 'P0s come first and each has a concrete fix.',+ ],+ },+ },+ {+ id: 'presentation',+ name: 'Presentation Design',+ description: 'Slides, decks, speaker-oriented hierarchy, consistent multi-page layouts, charts and diagrams.',+ whenToUse: ['deck', 'presentation', 'slide', 'pitch', 'investor', 'keynote', 'webinar', 'lecture'],+ modes: ['create', 'improve', 'plan', 'review'],+ version: '1.0.0',+ playbook: {+ principles: [+ 'One idea per slide: a single claim (the headline) + one proof (visual, chart, or 3 bullets max).',+ '16:9 grid: title zone (top 20%), content zone (middle 60%), footer/brand zone (bottom 12%); margins 5–6% of width.',+ 'Deck-wide consistency: identical title style, footer, and margins on every slide; vary content layout across 2–3 slide archetypes (statement, chart, split).',+ 'Speaker support, not prose: slides are skimmable in 3 seconds; if a sentence needs reading twice, shorten it.',+ 'Charts: one message per chart — title states the takeaway, axis labels legible ≥ 18px on 1920×1080, use the deck palette for series colors.',+ 'Numbers large: a key metric slide shows the number at 10–15% of slide height in the accent color.',+ ],+ planning: [+ 'Draft the narrative outline first (titles only) — the deck is an argument, then fill slides.',+ 'Pick 2–3 slide archetypes and reuse them; every slide states its archetype before placing elements.',+ 'Use add_page + goto_page per slide; set the same background system on every page.',+ ],+ validation: [+ 'Every slide has exactly one headline in the same style/position.',+ 'No slide has more than ~30 words of body text.',+ 'Chart text legible; series colors from the palette.',+ ],+ },+ },+ {+ id: 'social',+ name: 'Social Media Design',+ description: 'Platform-specific formats, thumbnail readability, engagement composition, multi-format adaptation.',+ whenToUse: ['instagram', 'story', 'reel', 'tiktok', 'youtube', 'thumbnail', 'social media', 'social post', 'facebook', 'linkedin', 'twitter', 'post'],+ modes: ['create', 'improve', 'plan', 'review'],+ version: '1.0.0',+ playbook: {+ principles: [+ 'Platform dims are law: 1080×1080 square post, 1080×1350 portrait, 1080×1920 story/reel, 1280×720 thumbnail. State the format in the plan and resize_design first if needed.',+ 'Thumbnail test: headline must be readable at 10% scale (a phone grid) — that means huge type (≥ 8% of canvas height) and ≤ 8 words.',+ 'Safe zones: stories keep text out of the top 14% (username) and bottom 20% (CTA bar); thumbnails keep the bottom-right corner clear (duration badge).',+ 'One scannable hierarchy: hook (giant) → value line (medium) → brand/handle (small, corner).',+ 'Face + text beats text alone for engagement when a photo is available; place text on the quieter third.',+ 'Multi-format adaptation: design once in the master format, then adapt per platform by re-flowing the SAME elements to each grid — don\'t redesign.',+ ],+ planning: [+ 'Fix the format + dimensions first; note the safe zones.',+ 'Hook line from the brief verbatim; compose around it.',+ ],+ validation: [+ 'Dimensions match the platform spec.',+ 'Headline legible at thumbnail scale (fontSize ≥ 8% of canvas height).',+ 'No content in the platform-specific unsafe zones.',+ ],+ },+ },+ {+ id: 'assets',+ name: 'Image & Asset Composition',+ description: 'Stock photo selection, AI image generation, placement, cropping, masks, focal awareness, text-image contrast.',+ whenToUse: ['photo', 'image', 'picture', 'stock', 'illustration', 'icon', 'graphic', 'visual', 'mask', 'crop', 'background image'],+ modes: ['create', 'improve', 'plan', 'edit'],+ version: '1.0.0',+ playbook: {+ principles: [+ 'Concrete subject → add_stock_photo (real, licensed, credited). Abstract/stylized or exact-brand art → add_image (generation). Icon-language → add_icon. Decorative scenes → add_illustration.',+ 'The photo is a layout region: allocate its bounding box FIRST, then choose orientation (landscape/portrait/square) to match the region.',+ 'Focal awareness: keep the subject on the rule-of-thirds intersection; text goes on the calm third (sky, wall, negative space) — else add a scrim.',+ 'One hero image per page; more images only as a deliberate grid (3-up gallery) with consistent gaps.',+ 'Masks and rounded corners unify photos with the design system (mask_image, radius) — use the SAME treatment on every photo in the design.',+ 'Icons: one stroke weight + one color per icon set; icons support labels, they never replace them.',+ ],+ planning: [+ 'Decide the image role per region: hero visual, supporting texture, icon row.',+ 'Pick the tool per role; write the query/prompt with the composition in mind (orientation, mood, palette-compatible colors).',+ ],+ validation: [+ 'Every photo sits fully inside its region with the same corner treatment.',+ 'Text over any photo has a scrim or sits on the calm area (contrast check).',+ 'Icons consistent (one weight, one color).',+ ],+ },+ },+ {+ id: 'refinement',+ name: 'Design Refinement',+ description: 'Improving existing designs: fix weak layouts, upgrade typography, correct hierarchy, polish — while preserving content and intent.',+ whenToUse: ['improve', 'polish', 'professional', 'clean up', 'better', 'refine', 'fix the design', 'make it pop', 'upgrade'],+ modes: ['improve', 'edit'],+ version: '1.0.0',+ playbook: {+ principles: [+ 'Diagnose before touching: get_page_state, run the critique ladder, list the 3 worst problems — fix THOSE, don\'t redecorate.',+ 'Preserve content and intent: never delete user copy, never swap their brand colors; adjust execution (size, position, contrast, spacing) not meaning.',+ 'The "refine, don\'t add" rule: before adding any new element, exhaust improving what exists. Most weak designs need subtraction (fewer sizes, fewer colors, more whitespace), not more elements.',+ 'Order of operations: hierarchy (sizes) → alignment (grid) → spacing (rhythm) → contrast (readability) → color balance → decoration last.',+ 'Intentional overlaps (text on cards, plates behind headlines) are composition — check the context\'s overlap analysis and preserve deliberate layering while fixing accidental collisions.',+ 'Work in batches: apply one improvement class at a time (all sizes, then all alignments) so each change is verifiable.',+ ],+ planning: [+ 'Snapshot the state; identify the 3 highest-severity issues.',+ 'For each, name the exact tool calls (element ids included) BEFORE applying.',+ 'Re-check with get_page_state after each batch; stop when the validation list passes.',+ ],+ validation: [+ 'All original text content still present (nothing lost).',+ 'Hierarchy, alignment, spacing checks from the layout skill pass.',+ 'No NEW overlaps introduced.',+ ],+ },+ },+]++/** Router: match a user message + mode against skill metadata.+ * Returns the 1–3 most relevant skills, best first. Pure, cheap,+ * no model. */+export function selectSkills(message: string, mode: AgentMode, brandKitPresent = false): DesignSkill[] {+ const lower = message.toLowerCase()+ const scored = DESIGN_SKILLS.map((skill) => {+ let score = 0+ // the brand skill's keyword hints only count when a kit EXISTS —+ // "make it on brand" without a kit is a generic refinement ask+ const hintsCount = skill.id === 'brand' && !brandKitPresent ? 0 : 1+ if (hintsCount) {+ for (const hint of skill.whenToUse) {+ if (lower.includes(hint)) score += hint.length >= 6 ? 3 : 2+ }+ }+ if (skill.modes.includes(mode)) score += 2+ if (skill.id === 'brand' && brandKitPresent) score += 2+ // always-relevant craft skills get a small floor in build modes+ if ((skill.id === 'typography' || skill.id === 'color' || skill.id === 'layout') && ['create', 'improve'].includes(mode)) score += 1+ // the critique skill owns review mode+ if (mode === 'review' && skill.id === 'critique') score += 5+ return { skill, score }+ })+ return scored+ .filter((s) => s.score >= 4)+ .sort((a, b) => b.score - a.score)+ .slice(0, 3)+ .map((s) => s.skill)+}++/** The prompt section for the selected skills' playbooks (full+ * disclosure of ONLY the winners). */+export function skillsPromptSection(skills: DesignSkill[]): string {+ if (!skills.length) return ''+ const blocks = skills.map((s) => {+ const p = s.playbook+ return [+ `### Skill: ${s.name} (v${s.version})`,+ 'Principles:',+ ...p.principles.map((x) => `· ${x}`),+ 'Planning:',+ ...p.planning.map((x, i) => `${i + 1}. ${x}`),+ 'Before done, verify:',+ ...p.validation.map((x) => `· ${x}`),+ ].join('\n')+ })+ return ['SELECTED DESIGN SKILLS (follow these playbooks):', ...blocks].join('\n\n')+}diff --git a/src/lib/agent/tools.ts b/src/lib/agent/tools.tsindex 5173047..60e459f 100644--- a/src/lib/agent/tools.ts+++ b/src/lib/agent/tools.ts@@ -105,6 +105,15 @@ function enumVal<T extends string>(args: Record<string, unknown>, key: string, areturn typeof v === 'string' && (allowed as readonly string[]).includes(v) ? (v as T) : fallback}+/** Strict enum: either a valid member or an actionable error (the+ * silent fallback would let "hexagon" silently become "rect" —+ * caught by the v0.28 harness). */+function enumStrict<T extends string>(args: Record<string, unknown>, key: string, allowed: readonly T[]): { value: T } | { error: string } {+ const v = args[key]+ if (typeof v === 'string' && (allowed as readonly string[]).includes(v)) return { value: v as T }+ return { error: `"${key}" must be one of ${allowed.join('|')}; you sent ${JSON.stringify(v) ?? 'nothing'}.` }+}+// ── the registry ─────────────────────────────────────────────export const AGENT_TOOLS: AgentTool[] = [@@ -332,9 +341,9 @@ export const AGENT_TOOLS: AgentTool[] = [// ── edit elements ──────────────────────────────────────────{name: 'update_elements',- description: 'Patch properties of elements by id: x, y, width, height, text, fill, fontSize, bold, align, rotation, opacity, radius, lineHeight, letterSpacing.',+ description: 'Patch properties of elements by id: geometry (x,y,width,height,rotation), style (fill,fontSize,bold,italic,underline,strike,uppercase,align,lineHeight,letterSpacing,curve,text), image (flipH,flipV,brightness,contrast,saturation), layer (locked,visible,opacity).',risk: 'write',- argsSpec: '{ids: string[], patch: {x?, y?, width?, height?, text?, fill?, fontSize?, bold?, align?, rotation?, opacity?}}',+ argsSpec: '{ids: string[], patch: {x?, y?, width?, height?, rotation?, text?, fill?, fontSize?, bold?, italic?, underline?, strike?, uppercase?, align?, lineHeight?, letterSpacing?, curve?, flipH?, flipV?, brightness?, contrast?, saturation?, locked?, visible?, opacity?}}',sanitize: (args, ctx) => {const { ids, error } = idList(args, ctx)if (error) return { ok: false, error }@@ -344,13 +353,23 @@ export const AGENT_TOOLS: AgentTool[] = [}const patch: Record<string, unknown> = {}const p = patchRaw as Record<string, unknown>- for (const key of ['x', 'y', 'width', 'height', 'rotation', 'lineHeight', 'letterSpacing'] as const) {+ for (const key of ['x', 'y', 'width', 'height', 'rotation', 'lineHeight', 'letterSpacing', 'curve'] as const) {if (p[key] !== undefined) {const v = num(p as Record<string, unknown>, key)if (v === null) return { ok: false, error: `patch.${key} must be a number; you sent ${JSON.stringify(p[key])}.` }patch[key] = v}}+ if (p.curve !== undefined && (Number(p.curve) < -180 || Number(p.curve) > 180)) {+ return { ok: false, error: `patch.curve must be −180..180 degrees; you sent ${JSON.stringify(p.curve)}.` }+ }+ for (const key of ['brightness', 'contrast', 'saturation'] as const) {+ if (p[key] !== undefined) {+ const v = num(p, key)+ if (v === null || v < -100 || v > 100) return { ok: false, error: `patch.${key} must be −100..100; you sent ${JSON.stringify(p[key])}.` }+ patch[key] = v+ }+ }if (p.fontSize !== undefined) {const v = num(p as Record<string, unknown>, 'fontSize')if (v === null || v < 6 || v > 400) return { ok: false, error: `patch.fontSize must be 6–400; you sent ${JSON.stringify(p.fontSize)}.` }@@ -367,10 +386,12 @@ export const AGENT_TOOLS: AgentTool[] = [if (!c) return { ok: false, error: `patch.fill must be #RRGGBB; you sent ${JSON.stringify(p.fill)}.` }patch.fill = c}- if (p.bold !== undefined) patch.bold = p.bold === true+ for (const flag of ['bold', 'italic', 'underline', 'strike', 'uppercase', 'flipH', 'flipV', 'locked', 'visible'] as const) {+ if (p[flag] !== undefined) patch[flag] = p[flag] === true+ }if (p.align !== undefined) patch.align = enumVal(p as Record<string, unknown>, 'align', ['left', 'center', 'right'] as const, 'center')if (Object.keys(patch).length === 0) {- return { ok: false, error: 'patch is empty — set at least one supported property (x, y, width, height, text, fill, fontSize, bold, align, rotation, opacity).' }+ return { ok: false, error: 'patch is empty — set at least one supported property (see the tool spec).' }}return {ok: true,@@ -633,8 +654,406 @@ export const AGENT_TOOLS: AgentTool[] = [},// ── destructive (confirm gate) ─────────────────────────────+ {+ // v0.28 (Phase 3): the full capability bridge — every gap the+ // audit found (docs/AI-CAPABILITY-MATRIX.md) becomes a tool.+ // All compile to DesignActions the CLIENT validates + applies.+ name: 'add_line',+ description: 'Add a line: solid, dashed, arrow, or double-headed arrow.',+ risk: 'write',+ argsSpec: '{x: number, y: number, length: number, variant?: "solid"|"dashed"|"arrow"|"arrowBoth", stroke?: "#RRGGBB", strokeWidth?: 1-40, rotation?: 0-359}',+ sanitize: (args, ctx) => {+ const x = num(args, 'x')+ const y = num(args, 'y')+ const length = num(args, 'length')+ if (x === null || y === null) return { ok: false, error: 'x and y are required numbers (the line\'s start point).' }+ if (length === null || length < 8) return { ok: false, error: 'length must be ≥ 8 px.' }+ const variant = enumVal(args, 'variant', ['solid', 'dashed', 'arrow', 'arrowBoth'] as const, 'solid' as never)+ // a PRESENT-but-invalid stroke errors; an absent stroke is fine+ if (args.stroke !== undefined && !hex(args, 'stroke')) {+ return { ok: false, error: `stroke must be #RRGGBB; you sent ${JSON.stringify(args.stroke)}.` }+ }+ return {+ ok: true,+ actions: [{+ type: 'addLine',+ x: clamp(x, -ctx.width, ctx.width),+ y: clamp(y, -ctx.height, ctx.height),+ length,+ variant,+ ...(hex(args, 'stroke') ? { stroke: hex(args, 'stroke')! } : {}),+ ...(num(args, 'strokeWidth') !== null ? { strokeWidth: clamp(num(args, 'strokeWidth')!, 1, 40) } : {}),+ ...(num(args, 'rotation') !== null ? { rotation: clamp(num(args, 'rotation')!, 0, 359) } : {}),+ }],+ observation: `Line (${variant}) added.`,+ }+ },+ },+ {+ name: 'add_icon',+ description: 'Search the icon pack by keyword (arrow, check, star, heart, cart…) and place the best match as a stroke icon.',+ risk: 'write',+ argsSpec: '{query: string, stroke?: "#RRGGBB", size?: 24-600}',+ sanitize: (args) => {+ const query = str(args, 'query', 60).trim()+ if (query.length < 2) return { ok: false, error: 'query must name the icon concept, e.g. "arrow-right", "check".' }+ return {+ ok: true,+ actions: [{ type: 'addIcon', query, ...(hex(args, 'stroke') ? { stroke: hex(args, 'stroke')! } : {}), ...(num(args, 'size') !== null ? { size: clamp(num(args, 'size')!, 24, 600) } : {}) }],+ observation: `Icon search queued for "${query}".`,+ }+ },+ },+ {+ name: 'add_illustration',+ description: 'Place a decorative SVG illustration by keyword (abstract/nature/business/decoration scenes).',+ risk: 'write',+ argsSpec: '{query: string}',+ sanitize: (args) => {+ const query = str(args, 'query', 60).trim()+ if (query.length < 3) return { ok: false, error: 'query must describe the scene, e.g. "waves", "mountain scene".' }+ return { ok: true, actions: [{ type: 'addIllustration', query }], observation: `Illustration search queued for "${query}".` }+ },+ },+ {+ name: 'add_chart',+ description: 'Add a data-bound chart: bar, line, donut, or scatter. Provide labels + series for real data; omit for editable sample data.',+ risk: 'write',+ argsSpec: '{kind: "bar"|"line"|"donut"|"scatter", labels?: string[], series?: [{name, color, values: number[]}], x?: number, y?: number}',+ sanitize: (args, ctx) => {+ const kind = enumVal(args, 'kind', ['bar', 'line', 'donut', 'scatter'] as const, '' as never)+ if (!kind) return { ok: false, error: 'kind must be bar, line, donut, or scatter.' }+ const labels = Array.isArray(args.labels) ? args.labels.map((l) => String(l).slice(0, 24)).slice(0, 24) : undefined+ let series: unknown+ if (Array.isArray(args.series)) {+ series = args.series+ .filter((s) => !!s && typeof s === 'object')+ .slice(0, 6)+ .map((s) => {+ const so = s as { name?: unknown; color?: unknown; values?: unknown }+ return {+ name: String(so.name ?? 'Series').slice(0, 24),+ color: typeof so.color === 'string' && /^#[0-9a-fA-F]{6}$/.test(so.color) ? so.color : '#7630D7',+ values: Array.isArray(so.values) ? so.values.map((v) => Number(v) || 0).slice(0, 24) : [],+ }+ })+ .filter((s) => s.values.length >= 2)+ if (!(series as unknown[]).length) series = undefined+ }+ return {+ ok: true,+ actions: [{+ type: 'addChart',+ kind,+ ...(labels?.length ? { labels } : {}),+ ...(series ? { series } : {}),+ ...(num(args, 'x') !== null ? { x: clamp(num(args, 'x')!, 0, ctx.width) } : {}),+ ...(num(args, 'y') !== null ? { y: clamp(num(args, 'y')!, 0, ctx.height) } : {}),+ }],+ observation: `Chart (${kind}) queued.`,+ }+ },+ },+ {+ name: 'add_qr',+ description: 'Generate and place a QR code for a URL or text.',+ risk: 'write',+ argsSpec: '{value: string, size?: 96-800, dark?: "#RRGGBB", light?: "#RRGGBB", x?: number, y?: number}',+ sanitize: (args, ctx) => {+ const value = str(args, 'value', 500).trim()+ if (value.length < 2) return { ok: false, error: 'value is required (the URL or text the QR encodes).' }+ return {+ ok: true,+ actions: [{+ type: 'addQr',+ value,+ ...(num(args, 'size') !== null ? { size: clamp(num(args, 'size')!, 96, 800) } : {}),+ ...(hex(args, 'dark') ? { dark: hex(args, 'dark')! } : {}),+ ...(hex(args, 'light') ? { light: hex(args, 'light')! } : {}),+ ...(num(args, 'x') !== null ? { x: clamp(num(args, 'x')!, 0, ctx.width) } : {}),+ ...(num(args, 'y') !== null ? { y: clamp(num(args, 'y')!, 0, ctx.height) } : {}),+ }],+ observation: 'QR code queued.',+ }+ },+ },+ {+ name: 'add_frame',+ description: 'Add an image frame (rect/rounded/circle/star/polygon) — a placeholder you later fill with fill_frame or that auto-fills on image drop.',+ risk: 'write',+ argsSpec: '{frameShape?: "rect"|"rounded"|"circle"|"star"|"polygon", width?: 80-1200, height?: 80-1200, x?: number, y?: number}',+ sanitize: (args, ctx) => {+ const shape = enumStrict(args, 'frameShape', ['rect', 'rounded', 'circle', 'star', 'polygon'] as const)+ if ('error' in shape) return { ok: false, error: shape.error }+ const frameShape = shape.value+ return {+ ok: true,+ actions: [{+ type: 'addFrame',+ frameShape,+ ...(num(args, 'width') !== null ? { width: clamp(num(args, 'width')!, 80, 1200) } : {}),+ ...(num(args, 'height') !== null ? { height: clamp(num(args, 'height')!, 80, 1200) } : {}),+ ...(num(args, 'x') !== null ? { x: clamp(num(args, 'x')!, 0, ctx.width) } : {}),+ ...(num(args, 'y') !== null ? { y: clamp(num(args, 'y')!, 0, ctx.height) } : {}),+ }],+ observation: `Frame (${frameShape}) queued.`,+ }+ },+ },+ {+ name: 'add_embed',+ description: 'Embed a YouTube video, Google Map, or generic link as a card.',+ risk: 'write',+ argsSpec: '{url: string}',+ sanitize: (args) => {+ const url = str(args, 'url', 400).trim()+ if (!/^https?:\/\//.test(url)) return { ok: false, error: 'url must start with http:// or https://.' }+ return { ok: true, actions: [{ type: 'addEmbed', url }], observation: 'Embed card queued.' }+ },+ },+ {+ name: 'duplicate_elements',+ description: 'Duplicate elements by id (copies land 24px offset).',+ risk: 'write',+ argsSpec: '{ids: string[]}',+ sanitize: (args, ctx) => {+ const { ids, error } = idList(args, ctx)+ if (error) return { ok: false, error }+ if (!ids.length) return { ok: false, error: 'ids must include at least one existing element id.' }+ return { ok: true, actions: [{ type: 'duplicateElements', ids }], observation: `Duplicating ${ids.length} element(s).` }+ },+ },+ {+ name: 'group_elements',+ description: 'Group 2+ elements so they move/transform together.',+ risk: 'write',+ argsSpec: '{ids: string[]}',+ sanitize: (args, ctx) => {+ const { ids, error } = idList(args, ctx)+ if (error) return { ok: false, error }+ if (ids.length < 2) return { ok: false, error: 'group needs 2+ element ids.' }+ return { ok: true, actions: [{ type: 'groupElements', ids }], observation: `Grouping ${ids.length} elements.` }+ },+ },+ {+ name: 'ungroup_elements',+ description: 'Ungroup group elements by id (children become editable individually).',+ risk: 'write',+ argsSpec: '{ids: string[]}',+ sanitize: (args, ctx) => {+ const { ids, error } = idList(args, ctx)+ if (error) return { ok: false, error }+ if (!ids.length) return { ok: false, error: 'ids must include at least one group element id.' }+ return { ok: true, actions: [{ type: 'ungroupElements', ids }], observation: 'Ungrouping.' }+ },+ },+ {+ name: 'reorder_layers',+ description: 'Change stacking: move ids up/down/front/back, or pass ≥2 ids in the desired z-order.',+ risk: 'write',+ argsSpec: '{ids: string[], dir?: "up"|"down"|"front"|"back"}',+ sanitize: (args, ctx) => {+ const { ids, error } = idList(args, ctx)+ if (error) return { ok: false, error }+ if (!ids.length) return { ok: false, error: 'ids must include at least one existing element id.' }+ const dir = enumVal(args, 'dir', ['up', 'down', 'front', 'back'] as const, '' as never)+ if (!dir && ids.length < 2) return { ok: false, error: 'Pass dir (up|down|front|back) for single moves, or ≥2 ids for an explicit z order.' }+ return { ok: true, actions: [{ type: 'reorderLayers', ids, ...(dir ? { dir } : {}) }], observation: dir ? `Layer(s) moved ${dir}.` : 'Reordering layers.' }+ },+ },+ {+ name: 'animate_elements',+ description: 'Set an entry animation on elements: fade, rise, pan, pop, wipe, zoom, rotate, breathe (or none to clear).',+ risk: 'write',+ argsSpec: '{ids: string[], kind: "none"|"fade"|"rise"|"pan"|"pop"|"wipe"|"zoom"|"rotate"|"breathe", duration?: 0.2-5s, delay?: 0-10s, easing?: "linear"|"easeIn"|"easeOut"|"easeInOut"|"spring", direction?: "left"|"right"|"up"|"down"}',+ sanitize: (args, ctx) => {+ const { ids, error } = idList(args, ctx)+ if (error) return { ok: false, error }+ if (!ids.length) return { ok: false, error: 'ids must include at least one existing element id.' }+ const kind = enumVal(args, 'kind', ['none', 'fade', 'rise', 'pan', 'pop', 'wipe', 'zoom', 'rotate', 'breathe'] as const, '' as never)+ if (!kind) return { ok: false, error: 'kind must be one of none|fade|rise|pan|pop|wipe|zoom|rotate|breathe.' }+ return {+ ok: true,+ actions: [{+ type: 'animateElements',+ ids,+ kind,+ ...(num(args, 'duration') !== null ? { duration: clamp(num(args, 'duration')!, 0.2, 5) } : {}),+ ...(num(args, 'delay') !== null ? { delay: clamp(num(args, 'delay')!, 0, 10) } : {}),+ ...(enumVal(args, 'easing', ['linear', 'easeIn', 'easeOut', 'easeInOut', 'spring'] as const, '' as never) ? { easing: enumVal(args, 'easing', ['linear', 'easeIn', 'easeOut', 'easeInOut', 'spring'] as const, '' as never) } : {}),+ ...(enumVal(args, 'direction', ['left', 'right', 'up', 'down'] as const, '' as never) ? { direction: enumVal(args, 'direction', ['left', 'right', 'up', 'down'] as const, '' as never) } : {}),+ }],+ observation: `Animation ${kind} queued on ${ids.length} element(s).`,+ }+ },+ },+ {+ name: 'set_page_transition',+ description: 'Set how the CURRENT page enters in playback: fade, slide, zoom, flip (or none).',+ risk: 'write',+ argsSpec: '{kind: "none"|"fade"|"slide"|"zoom"|"flip", duration?: 0.2-2s}',+ sanitize: (args) => {+ const kind = enumVal(args, 'kind', ['none', 'fade', 'slide', 'zoom', 'flip'] as const, '' as never)+ if (!kind) return { ok: false, error: 'kind must be none|fade|slide|zoom|flip.' }+ return { ok: true, actions: [{ type: 'setPageTransition', kind, ...(num(args, 'duration') !== null ? { duration: clamp(num(args, 'duration')!, 0.2, 2) } : {}) }], observation: `Page transition ${kind} queued.` }+ },+ },+ {+ name: 'delete_page',+ description: 'Delete a page by 1-based number (default: current). Destructive — a non-empty page needs confirmed:true.',+ risk: 'destructive',+ argsSpec: '{page?: number, confirmed?: boolean}',+ sanitize: (args) => {+ const page = num(args, 'page')+ if (page !== null && (!Number.isInteger(page) || page < 1 || page > 200)) return { ok: false, error: 'page must be an integer 1–200 (1-based).' }+ return {+ ok: true,+ actions: [{ type: 'deletePage', ...(page !== null ? { page } : {}), ...(args.confirmed === true ? { confirmed: true } : {}) }],+ observation: 'Page delete queued (the client confirms non-empty pages).',+ }+ },+ },+ {+ name: 'set_brand_kit',+ description: 'Save design tokens to the Brand Kit: colors[], headingFont, bodyFont. The kit then guides every later run.',+ risk: 'write',+ argsSpec: '{colors?: ["#RRGGBB"…], headingFont?: string, bodyFont?: string}',+ sanitize: (args, ctx) => {+ const colors = Array.isArray(args.colors)+ ? args.colors.filter((c): c is string => typeof c === 'string' && /^#[0-9a-fA-F]{6}$/.test(c)).map((c) => c.toLowerCase()).slice(0, 10)+ : []+ const headingFont = str(args, 'headingFont', 60)+ const bodyFont = str(args, 'bodyFont', 60)+ if (headingFont && !ctx.fonts.has(headingFont)) return { ok: false, error: `Unknown headingFont "${headingFont}". Examples: ${[...ctx.fonts].slice(0, 6).join(', ')}.` }+ if (bodyFont && !ctx.fonts.has(bodyFont)) return { ok: false, error: `Unknown bodyFont "${bodyFont}". Examples: ${[...ctx.fonts].slice(0, 6).join(', ')}.` }+ if (!colors.length && !headingFont && !bodyFont) return { ok: false, error: 'Set at least one of colors[], headingFont, bodyFont.' }+ return { ok: true, actions: [{ type: 'setBrandKit', ...(colors.length ? { colors } : {}), ...(headingFont ? { headingFont } : {}), ...(bodyFont ? { bodyFont } : {}) }], observation: 'Brand kit update queued.' }+ },+ },+ {+ name: 'resize_design',+ description: 'Resize the whole canvas (all pages, elements re-laid out proportionally). Use when the brief demands other dimensions than the current page.',+ risk: 'write',+ argsSpec: '{width: 50-10000, height: 50-10000}',+ sanitize: (args) => {+ const width = num(args, 'width')+ const height = num(args, 'height')+ if (width === null || height === null || width < 50 || width > 10000 || height < 50 || height > 10000) {+ return { ok: false, error: 'width and height must be 50–10000 px.' }+ }+ return { ok: true, actions: [{ type: 'resizeDesign', width: Math.round(width), height: Math.round(height) }], observation: `Canvas resize to ${Math.round(width)}×${Math.round(height)} queued.` }+ },+ },+ {+ name: 'mask_image',+ description: 'Clip image elements to a shape: circle, rounded, star, polygon, heart, hexagon (or none to clear).',+ risk: 'write',+ argsSpec: '{ids: string[], mask: "none"|"circle"|"rounded"|"star"|"polygon"|"heart"|"hexagon", sides?: 3-12}',+ sanitize: (args, ctx) => {+ const { ids, error } = idList(args, ctx)+ if (error) return { ok: false, error }+ if (!ids.length) return { ok: false, error: 'ids must include at least one IMAGE element id.' }+ const mask = enumVal(args, 'mask', ['none', 'circle', 'rounded', 'star', 'polygon', 'heart', 'hexagon'] as const, '' as never)+ if (!mask) return { ok: false, error: 'mask must be none|circle|rounded|star|polygon|heart|hexagon.' }+ return { ok: true, actions: [{ type: 'maskImage', ids, mask, ...(mask === 'polygon' && num(args, 'sides') !== null ? { sides: clamp(num(args, 'sides')!, 3, 12) } : {}) }], observation: `Mask ${mask} queued on ${ids.length} image(s).` }+ },+ },+ {+ name: 'adjust_image',+ description: 'Adjust image elements: brightness, contrast, saturation (−100..100) or a filter preset.',+ risk: 'write',+ argsSpec: '{ids: string[], brightness?: -100..100, contrast?: -100..100, saturation?: -100..100, filter?: string|"none"}',+ sanitize: (args, ctx) => {+ const { ids, error } = idList(args, ctx)+ if (error) return { ok: false, error }+ if (!ids.length) return { ok: false, error: 'ids must include at least one IMAGE element id.' }+ const adj = (k: string): number | null => {+ const v = num(args, k)+ if (v === null) return null+ if (v < -100 || v > 100) throw new Error(`${k} must be −100..100; you sent ${v}.`)+ return Math.round(v)+ }+ try {+ const patch: Record<string, unknown> = {}+ for (const k of ['brightness', 'contrast', 'saturation']) {+ const v = adj(k)+ if (v !== null) patch[k] = v+ }+ const filter = str(args, 'filter', 40)+ if (filter) patch.filter = filter+ if (!Object.keys(patch).length) return { ok: false, error: 'Set at least one of brightness, contrast, saturation, filter.' }+ return { ok: true, actions: [{ type: 'adjustImage', ids, ...patch }], observation: `Image adjustments queued on ${ids.length} image(s).` }+ } catch (e) {+ return { ok: false, error: e instanceof Error ? e.message : 'Bad image adjustments.' }+ }+ },+ },+ {+ name: 'measure_text',+ description: 'REAL text metrics (canvas measureText): returns the pixel width of a string at a given font/size — use before finalizing headings so nothing clips. The 0.6×size estimate is only a fallback.',+ risk: 'read',+ argsSpec: '{text: string, fontSize: 6-400, fontFamily?: string, bold?: boolean, lineHeight?: number}',+ sanitize: (args, ctx) => {+ const text = str(args, 'text', 200)+ if (!text) return { ok: false, error: 'text is required.' }+ const fontSize = num(args, 'fontSize')+ if (fontSize === null || fontSize < 6 || fontSize > 400) return { ok: false, error: 'fontSize must be 6–400.' }+ const fontFamily = str(args, 'fontFamily', 60) || 'Poppins'+ if (!ctx.fonts.has(fontFamily)) return { ok: false, error: `Unknown fontFamily "${fontFamily}". Examples: ${[...ctx.fonts].slice(0, 6).join(', ')}.` }+ return {+ ok: true,+ actions: [{ type: 'measureText', text, fontSize, fontFamily, bold: args.bold === true, ...(num(args, 'lineHeight') !== null ? { lineHeight: num(args, 'lineHeight')! } : {}) }],+ observation: 'Measuring text with real font metrics.',+ }+ },+ },+ {+ name: 'set_text_spans',+ description: 'Rich-text: style PARTS of a text element. Spans must concatenate EXACTLY to the element text. [{text, bold?, italic?, underline?, strike?, color?}]',+ risk: 'write',+ argsSpec: '{ids: string[], spans: [{text: string, bold?: boolean, italic?: boolean, color?: "#RRGGBB"}]}',+ sanitize: (args, ctx) => {+ const { ids, error } = idList(args, ctx)+ if (error) return { ok: false, error }+ if (!ids.length) return { ok: false, error: 'ids must include at least one TEXT element id.' }+ const spans = Array.isArray(args.spans) ? args.spans.filter((s) => !!s && typeof s === 'object' && typeof (s as { text?: unknown }).text === 'string').slice(0, 20) : []+ if (!spans.length) return { ok: false, error: 'spans must be a non-empty array of {text, bold?, italic?, color?}.' }+ return { ok: true, actions: [{ type: 'setTextSpans', ids, spans }], observation: 'Rich-text styling queued (validated against the element text).' }+ },+ },+ {+ name: 'export_design',+ description: 'Export the current page as PNG or JPG — downloads in the browser. Use when the user asks to save/export.',+ risk: 'write',+ argsSpec: '{format?: "png"|"jpg"}',+ sanitize: (args) => {+ const format = enumVal(args, 'format', ['png', 'jpg'] as const, 'png' as never)+ return { ok: true, actions: [{ type: 'exportDesign', format }], observation: `Export (${format}) queued — the download starts on the user's machine.` }+ },+ },+ {+ name: 'add_stock_video',+ description: 'Search licensed stock video (Pexels/Pixabay) and place the best match on the canvas.',+ risk: 'write',+ argsSpec: '{query: string}',+ sanitize: (args) => {+ const query = str(args, 'query', 120).trim()+ if (query.length < 3) return { ok: false, error: 'query must describe the footage (min 3 chars).' }+ return { ok: true, actions: [{ type: 'addStockVideo', query }], observation: `Stock video search queued for "${query}".` }+ },+ },+ {+ name: 'validate_brief',+ description: 'Validate the run against the Design Brief Contract using REAL page state: required texts verbatim, required colors, dimensions. Returns the unmet items — run before claiming done.',+ risk: 'read',+ argsSpec: '{}',+ sanitize: () => ({ ok: true, actions: [{ type: '__validateBrief' }], observation: 'Brief validation queued (computed on the client against the live document).' }),+ },++ // ── destructive ────────────────────────────────────────────{name: 'delete_elements',+description: 'DELETE elements by id. Destructive: needs the user confirmation gate.',risk: 'destructive',argsSpec: '{ids: string[]}',diff --git a/src/lib/design-actions.ts b/src/lib/design-actions.tsindex 82b119e..9839883 100644--- a/src/lib/design-actions.ts+++ b/src/lib/design-actions.ts@@ -535,6 +535,425 @@ export async function applyDesignAction(action: DesignAction, caller?: ActionCalreturn msg}+ // ───────────────────────────────────────────────────────────+ // v0.28 (Phase 3): the full capability bridge — every editor+ // surface the audit found (docs/AI-CAPABILITY-MATRIX.md) gets a+ // validated, undoable action here. All of them ride the store's+ // existing history + collab path; none bypass validation.+ // ───────────────────────────────────────────────────────────++ case 'addLine': {+ const variant = ['solid', 'dashed', 'arrow', 'arrowBoth'].includes(String(action.variant)) ? String(action.variant) : 'solid'+ const x = Number(action.x)+ const y = Number(action.y)+ const length = Number(action.length) || 320+ if (!Number.isFinite(x) || !Number.isFinite(y) || length < 8) return 'Bad line geometry (need x, y, length ≥ 8)'+ const { createLineElement } = await import('@/lib/types')+ const el = createLineElement({+ x: Math.round(x),+ y: Math.round(y),+ width: Math.round(Math.min(length, width * 1.2)),+ stroke: typeof action.stroke === 'string' && HEX.test(action.stroke) ? action.stroke : '#1F2226',+ strokeWidth: Math.min(40, Math.max(1, Number(action.strokeWidth) || 4)),+ dashed: variant === 'dashed',+ arrowStart: variant === 'arrowBoth',+ arrowEnd: variant === 'arrow' || variant === 'arrowBoth',+ rotation: Math.min(359, Math.max(0, Number(action.rotation) || 0)),+ })+ useEditorStore.getState().addElement(el)+ return `Line added (${variant})`+ }++ case 'addIcon': {+ // server-side search of the same offline pack the Icons app uses+ const { searchIcons } = await import('@/lib/assets/icon-pack')+ const query = String(action.query ?? '').trim().slice(0, 60)+ if (!query) return 'No icon query given'+ const matches = searchIcons(query, 1)+ if (!matches.length) return `No icon matches "${query}" — try a simpler noun (arrow, star, check, heart…)`+ const icon = matches[0]+ const size = Math.min(600, Math.max(24, Number(action.size) || 96))+ const { addIconPath } = await import('@/components/editor/add-element')+ addIconPath(icon.d, typeof action.stroke === 'string' && HEX.test(action.stroke) ? action.stroke : '#1F2226')+ return `Icon "${icon.name}" added (${size}px nominal)`+ }++ case 'addIllustration': {+ const { ILLUSTRATIONS } = await import('@/lib/assets/illustrations')+ const query = String(action.query ?? '').trim().toLowerCase().slice(0, 60)+ if (!query) return 'No illustration query given'+ const hit =+ ILLUSTRATIONS.find((i) => i.name.toLowerCase() === query) ??+ ILLUSTRATIONS.find((i) => i.name.toLowerCase().includes(query) || i.tags.some((t) => t.includes(query)))+ if (!hit) return `No illustration matches "${query}" — the packs cover abstract/nature/business/decoration scenes`+ const { addIllustration } = await import('@/components/editor/add-element')+ addIllustration(hit.svg)+ return `Illustration "${hit.name}" added`+ }++ case 'addGraphic': {+ const { GRAPHICS } = await import('@/lib/editor-utils')+ const id = String(action.graphicId ?? '').trim()+ const hit = GRAPHICS.find((g) => g.id === id) ?? GRAPHICS.find((g) => g.name.toLowerCase().includes(id.toLowerCase()))+ if (!hit) return `Unknown graphic "${id}"`+ const { addGraphic } = await import('@/components/editor/add-element')+ addGraphic(hit.id, typeof action.fill === 'string' && HEX.test(action.fill) ? action.fill : undefined)+ return `Graphic "${hit.name}" added`+ }++ case 'addChart': {+ const kind = ['bar', 'line', 'donut', 'scatter'].includes(String(action.kind)) ? (String(action.kind) as 'bar') : null+ if (!kind) return 'kind must be bar | line | donut | scatter'+ const labels = Array.isArray(action.labels) ? (action.labels as unknown[]).map((l) => String(l).slice(0, 24)).slice(0, 24) : null+ // series: [{name, color, values[]}] — validated shape, clamped+ let series: { name: string; color: string; values: number[] }[] | null = null+ if (Array.isArray(action.series)) {+ series = (action.series as unknown[])+ .filter((s): s is { name?: unknown; color?: unknown; values?: unknown } => !!s && typeof s === 'object')+ .slice(0, 6)+ .map((s) => ({+ name: String(s.name ?? 'Series').slice(0, 24),+ color: typeof s.color === 'string' && HEX.test(s.color) ? s.color : '#7630D7',+ values: Array.isArray(s.values) ? (s.values as unknown[]).map((v) => Number(v) || 0).slice(0, 24) : [],+ }))+ .filter((s) => s.values.length >= 2)+ }+ const { createChartElement } = await import('@/lib/types')+ const el = createChartElement(kind, {+ x: Math.round(Math.min(Math.max(Number(action.x) || width * 0.14, 0), width - 100)),+ y: Math.round(Math.min(Math.max(Number(action.y) || height * 0.2, 0), height - 100)),+ ...(labels?.length ? { labels } : {}),+ ...(series?.length ? { series } : {}),+ })+ useEditorStore.getState().addElement(el)+ return `Chart added (${kind}${series?.length ? `, ${series.length} series` : ', sample data — editable'})`+ }++ case 'addQr': {+ const value = String(action.value ?? '').trim().slice(0, 500)+ if (!value) return 'No QR value given'+ const size = Math.min(800, Math.max(96, Number(action.size) || 288))+ try {+ const QRCode = (await import('qrcode')).default+ const dataUrl = await QRCode.toDataURL(value, {+ width: size,+ margin: 1,+ color: {+ dark: typeof action.dark === 'string' && HEX.test(action.dark) ? action.dark : '#000000',+ light: typeof action.light === 'string' && HEX.test(action.light) ? action.light : '#FFFFFF',+ },+ })+ useEditorStore.getState().addElement(+ createImageElement(dataUrl, size, size, {+ x: Math.round(Number.isFinite(Number(action.x)) ? Number(action.x) : (width - size) / 2),+ y: Math.round(Number.isFinite(Number(action.y)) ? Number(action.y) : (height - size) / 2),+ width: size,+ height: size,+ radius: 12,+ }),+ )+ return `QR code added (${size}×${size})`+ } catch {+ return 'QR generation failed for this value'+ }+ }++ case 'addFrame': {+ const frameShape = ['rect', 'rounded', 'circle', 'star', 'polygon'].includes(String(action.frameShape))+ ? (String(action.frameShape) as 'rect')+ : 'rect'+ const { createFrameElement } = await import('@/lib/types')+ const size = Math.min(1200, Math.max(80, Number(action.width) || 320))+ const el = createFrameElement(frameShape, {+ x: Math.round(Number.isFinite(Number(action.x)) ? Number(action.x) : (width - size) / 2),+ y: Math.round(Number.isFinite(Number(action.y)) ? Number(action.y) : (height - size) / 2),+ width: size,+ height: Math.round(Math.min(1200, Math.max(80, Number(action.height) || Math.round(size * 0.66)))),+ })+ useEditorStore.getState().addElement(el)+ return `Frame added (${frameShape}) — fill it with fill_frame`+ }++ case 'addEmbed': {+ const url = String(action.url ?? '').trim().slice(0, 400)+ if (!/^https?:\/\//.test(url)) return 'url must be a http(s) link'+ const { createEmbedElement } = await import('@/lib/types')+ useEditorStore.getState().addElement(+ createEmbedElement(url, {+ x: Math.round((width - 320) / 2),+ y: Math.round((height - 200) / 2),+ }),+ )+ return 'Embed card added'+ }++ case 'duplicateElements': {+ const ids = resolveIds(action.ids)+ if (!ids.length) return 'No matching elements'+ const s = useEditorStore.getState()+ const page = currentPageElements()+ const clones = ids+ .map((id) => page.find((e) => e.id === id))+ .filter((e): e is NonNullable<typeof e> => !!e && !e.locked)+ .map((e) => ({+ ...structuredClone(e),+ id: `${e.type}-${Math.random().toString(36).slice(2, 9)}`,+ x: e.x + 24,+ y: e.y + 24,+ }))+ if (!clones.length) return 'Nothing duplicable (locked?)'+ s.addElementsBulk(clones)+ return `Duplicated ${clones.length} element${clones.length > 1 ? 's' : ''} (offset 24px)`+ }++ case 'groupElements': {+ const ids = resolveIds(action.ids)+ if (ids.length < 2) return 'Grouping needs 2+ element ids'+ const s = useEditorStore.getState()+ s.setSelection(ids)+ s.groupSelection()+ s.clearSelection()+ return `Grouped ${ids.length} elements`+ }++ case 'ungroupElements': {+ const ids = resolveIds(action.ids)+ const s = useEditorStore.getState()+ const page = currentPageElements()+ const groups = ids.filter((id) => page.find((e) => e.id === id)?.type === 'group')+ if (!groups.length) return 'No group elements among the ids'+ for (const gid of groups) {+ s.setSelection([gid])+ s.ungroupSelection()+ }+ s.clearSelection()+ return `Ungrouped ${groups.length} group${groups.length > 1 ? 's' : ''}`+ }++ case 'reorderLayers': {+ // ids in the desired z order; dir is a shortcut for single moves+ const s = useEditorStore.getState()+ if (typeof action.dir === 'string' && ['up', 'down', 'front', 'back'].includes(action.dir)) {+ const ids = resolveIds(action.ids)+ if (!ids.length) return 'No matching elements'+ for (const id of ids) s.moveLayer(id, action.dir as 'up')+ return `Moved ${ids.length} element(s) ${action.dir}`+ }+ if (Array.isArray(action.ids) && action.ids.length >= 2) {+ const order = (action.ids as unknown[]).map(String)+ // apply from the bottom up so relative order is preserved+ for (const id of [...order].reverse()) s.reorderLayer(id, 0)+ // simpler: park each at front in reverse → final z equals `order`+ return `Reordered ${order.length} elements`+ }+ return 'Give ids + dir (up|down|front|back), or ≥2 ids for an explicit z order'+ }++ case 'animateElements': {+ const ids = resolveIds(action.ids)+ if (!ids.length) return 'No matching elements'+ const kinds = ['none', 'fade', 'rise', 'pan', 'pop', 'wipe', 'zoom', 'rotate', 'breathe'] as const+ const rawKind = String(action.kind)+ if (!(kinds as readonly string[]).includes(rawKind)) return `kind must be one of ${kinds.join(', ')}`+ const kind = rawKind as (typeof kinds)[number]+ if (kind === 'none') {+ const s = useEditorStore.getState()+ s.setElementAnimation(ids, null)+ return `Cleared animation on ${ids.length} element(s)`+ }+ const s = useEditorStore.getState()+ s.setElementAnimation(ids, {+ kind,+ duration: Math.min(5, Math.max(0.2, Number(action.duration) || 0.6)),+ delay: Math.min(10, Math.max(0, Number(action.delay) || 0)),+ easing: ['linear', 'easeIn', 'easeOut', 'easeInOut', 'spring'].includes(String(action.easing))+ ? (String(action.easing) as 'easeOut')+ : 'easeOut',+ ...(['left', 'right', 'up', 'down'].includes(String(action.direction)) ? { direction: String(action.direction) as 'left' } : {}),+ })+ return `Animated ${ids.length} element(s): ${kind}`+ }++ case 'setPageTransition': {+ const kinds = ['none', 'fade', 'slide', 'zoom', 'flip'] as const+ const rawKind = String(action.kind)+ if (!(kinds as readonly string[]).includes(rawKind)) return `kind must be one of ${kinds.join(', ')}`+ const kind = rawKind as (typeof kinds)[number]+ if (kind === 'none') {+ useEditorStore.getState().setPageTransition(null)+ return 'Page transition cleared'+ }+ const s = useEditorStore.getState()+ s.setPageTransition({ kind, duration: Math.min(2, Math.max(0.2, Number(action.duration) || 0.5)) } as Parameters<typeof s.setPageTransition>[0])+ return `Page transition set: ${kind}`+ }++ case 'deletePage': {+ const s = useEditorStore.getState()+ if (s.pages.length <= 1) return 'Cannot delete the only page'+ const page = Math.round(Number(action.page))+ const target = Number.isFinite(page) ? page - 1 : s.currentPage+ if (target < 0 || target >= s.pages.length) return `Page out of range (1–${s.pages.length})`+ if (s.pages[target].elements.length > 0 && !action.confirmed) {+ return `Page ${target + 1} has ${s.pages[target].elements.length} elements — confirm:true is required to delete it`+ }+ s.deletePage(target)+ return `Deleted page ${target + 1}`+ }++ case 'setBrandKit': {+ const s = useEditorStore.getState()+ const colors = Array.isArray(action.colors)+ ? (action.colors as unknown[]).filter((c): c is string => typeof c === 'string' && HEX.test(c)).slice(0, 10)+ : undefined+ const headingFont = typeof action.headingFont === 'string' ? action.headingFont.slice(0, 60) : undefined+ const bodyFont = typeof action.bodyFont === 'string' ? action.bodyFont.slice(0, 60) : undefined+ if (!colors?.length && !headingFont && !bodyFont) return 'Nothing to set (colors[], headingFont, bodyFont)'+ s.setBrand({+ ...s.brand,+ ...(colors?.length ? { colors } : {}),+ ...(headingFont ? { headingFont } : {}),+ ...(bodyFont ? { bodyFont } : {}),+ })+ return 'Brand kit updated — the agent will respect it in this and later runs'+ }++ case 'resizeDesign': {+ const w = Math.round(Number(action.width))+ const h = Math.round(Number(action.height))+ if (!(w >= 50 && w <= 10000 && h >= 50 && h <= 10000)) return 'width/height must be 50–10000 px'+ const s = useEditorStore.getState()+ if (s.width === w && s.height === h) return `Already ${w}×${h}`+ s.resizeDesign(w, h)+ return `Canvas resized to ${w}×${h} (elements re-laid out proportionally)`+ }++ case 'maskImage': {+ const ids = resolveIds(action.ids)+ const masks = ['none', 'circle', 'rounded', 'star', 'polygon', 'heart', 'hexagon']+ const mask = masks.includes(String(action.mask)) ? String(action.mask) : null+ if (!mask) return `mask must be one of ${masks.join(', ')}`+ const page = currentPageElements()+ const images = ids.filter((id) => page.find((e) => e.id === id)?.type === 'image')+ if (!images.length) return 'No image elements among the ids'+ const s = useEditorStore.getState()+ for (const id of images) {+ s.updateElements([id], { maskShape: mask === 'none' ? undefined : mask, ...(mask === 'polygon' ? { maskSides: Math.min(12, Math.max(3, Number(action.sides) || 6)) } : {}) })+ }+ return `Masked ${images.length} image(s): ${mask}`+ }++ case 'adjustImage': {+ const ids = resolveIds(action.ids)+ const page = currentPageElements()+ const images = ids.filter((id) => page.find((e) => e.id === id)?.type === 'image')+ if (!images.length) return 'No image elements among the ids'+ const clampAdj = (v: unknown) => Math.min(100, Math.max(-100, Math.round(Number(v) || 0)))+ const s = useEditorStore.getState()+ for (const id of images) {+ const patch: Record<string, unknown> = {}+ if (action.brightness !== undefined) patch.brightness = clampAdj(action.brightness)+ if (action.contrast !== undefined) patch.contrast = clampAdj(action.contrast)+ if (action.saturation !== undefined) patch.saturation = clampAdj(action.saturation)+ if (typeof action.filter === 'string') patch.filter = action.filter === 'none' ? undefined : action.filter+ if (Object.keys(patch).length) s.updateElements([id], patch)+ }+ return `Adjusted ${images.length} image(s)`+ }++ case 'measureText': {+ // real metrics — the same canvas measureText the renderer uses+ const text = String(action.text ?? '')+ if (!text) return 'No text given'+ const fontSize = Math.min(400, Math.max(6, Number(action.fontSize) || 48))+ const style = `${String(action.bold) === 'true' || action.bold === true ? 'bold ' : ''}${fontSize}px ${String(action.fontFamily ?? 'Poppins')}`+ let w = fontSize * 0.6 * text.length+ let lineHeight = Math.round(fontSize * 1.25)+ try {+ const c = document.createElement('canvas')+ const ctx = c.getContext('2d')+ if (ctx) {+ ctx.font = style+ w = Math.max(1, ctx.measureText(text).width)+ lineHeight = Math.round(fontSize * (Number(action.lineHeight) || 1.25))+ }+ } catch {+ /* headless fallback: 0.6 estimate */+ }+ return `width=${Math.round(w)}px lineHeight=${lineHeight}px (text ${text.length} chars @ ${fontSize}px)`+ }++ case 'setTextSpans': {+ const ids = resolveIds(action.ids)+ if (!ids.length) return 'No matching elements'+ // spans must concatenate to the element text — validated+ const spans = Array.isArray(action.spans)+ ? (action.spans as unknown[]).filter((s): s is Record<string, unknown> => !!s && typeof s === 'object' && typeof (s as { text?: unknown }).text === 'string')+ : []+ if (!spans.length) return 'spans must be [{text, bold?, italic?, color?…}]'+ const { normalizeSpans } = await import('@/lib/rich-text')+ const page = currentPageElements()+ const s = useEditorStore.getState()+ let applied = 0+ for (const id of ids) {+ const el = page.find((e) => e.id === id)+ if (el?.type !== 'text') continue+ const joined = spans.map((sp) => String(sp.text)).join('')+ if (joined.replace(/\s+/g, ' ').trim() !== (el as { text: string }).text.replace(/\s+/g, ' ').trim()) {+ return `Spans must concatenate exactly to the element text ("${(el as { text: string }).text.slice(0, 40)}…") — got "${joined.slice(0, 40)}…"`+ }+ const norm = normalizeSpans(spans as unknown as import('@/lib/types').TextSpan[], (el as { text: string }).text)+ if (norm) {+ s.updateElements([id], { spans: norm })+ applied+++ }+ }+ return applied ? `Styled ${applied} text element(s)` : 'No text elements styled'+ }++ case 'exportDesign': {+ // the agent's export path: current page → PNG data URL → download+ const format = ['png', 'jpg'].includes(String(action.format)) ? (String(action.format) as 'png') : 'png'+ const { captureStage } = await import('@/components/editor/canvas/canvas-bridge')+ try {+ const url = await captureStage({ pixelScale: 1, mimeType: format === 'png' ? 'image/png' : 'image/jpeg', quality: 0.92 })+ const a = document.createElement('a')+ a.href = url+ a.download = `${(useEditorStore.getState().designName || 'canvix-design').replace(/[^a-z0-9-_]+/gi, '-')}.${format}`+ a.click()+ return `Exported the current page as ${format.toUpperCase()} (download started)`+ } catch {+ return 'Export failed — the canvas is not ready'+ }+ }++ case 'addStockVideo': {+ const query = String(action.query ?? '').trim().slice(0, 120)+ if (!query) return 'No video query given'+ const res = await fetch('/api/stock-video/search', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ query, count: 6 }),+ })+ const data = (await res.json().catch(() => ({}))) as { results?: { id: string; mp4: string; alternates: string[]; width: number; height: number; credit: { provider: string; author: string; license: string; url: string } }[]; error?: string }+ if (!res.ok || !Array.isArray(data.results) || data.results.length === 0) {+ return `No stock video matched "${query}"${data.error ? ` (${data.error})` : ''}`+ }+ const pick = data.results[0]+ const { addStockVideo: place } = await import('@/components/editor/add-element')+ await place(pick)+ return `Stock video "${query}" added (credit: ${pick.credit.author}/${pick.credit.provider})`+ }++ case 'addSfx': {+ const { sfxById } = await import('@/lib/assets/sfx-pack')+ const id = String(action.sfxId ?? '').trim()+ if (!sfxById(id)) return 'Unknown sound id — ask the user to pick sounds from the Audio panel, or use an animation sfxId'+ const { addSfxToCanvas } = await import('@/components/editor/add-element')+ await addSfxToCanvas(id)+ return `Sound "${id}" added to the canvas`+ }+default:return 'Unsupported action'}