Skip to content

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.

feat(v0.32.7): 2D spatial intelligence, edit intents, persistent+recoverable runs, provider resilience, authoritative re-audit

Ashiq Hussain Mir5b74344bbccc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index df7651e..66d15f6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,39 @@
All notable changes to Canvix will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
+### Changed — v0.32.7: spatial intelligence, intent, persistence, resilience
+
+- **2D spatial map** (spatial.ts): rotation-aware AABBs, z-order,
+ intentional layering (a card behind its text is not a collision),
+ section-scale band blocking with partial-occupancy disclosures,
+ 2D free regions, text-hierarchy ladder — wired into the plan
+ solver, tool observations, the audit and the system prompt.
+- **Context-aware editing** (intent.ts): add / replace / reposition
+ / restyle / redesign / remove / refine / review — deterministic,
+ shown live in the panel. The plan-first gate fires only for
+ create/add/redesign; a "check and fix" run is never bounced into
+ planning new sections.
+- **Persistent execution + recovery:** DesignAgentRun.status/state
+ (migration 0016) — the run's brief, plan, applied actions and
+ verification milestones persist live; a provider/network
+ interruption marks the run interrupted and the NEXT run injects
+ the snapshot as recovery context: complete, never re-add.
+- **Provider resilience** (chat-resilience.ts): bounded exponential
+ backoff for transient errors (auth/config errors fail fast), a
+ per-provider circuit breaker, and the CONFIGURED fallback chain
+ (user BYOK → instance slot → env/file; ZAI_NO_FALLBACK=1 opts
+ out). Gateway-reported tokens accumulate in the run's usage.
+- **Verification completed:** blocking audit issues (contrast,
+ overlap, off-canvas, obscured, duplicates, empty sections) get
+ one bounded fix round, then the re-audit is authoritative —
+ remaining blockers end the run INCOMPLETE. Advisories (alignment,
+ typography, hierarchy, deep margins) disclose, never block. The
+ brief validator adopts the design engine's NFC-exact contract.
+- **Tests:** +50 regressions (spatial, intent, resilience, loop);
+ recovery e2e (mocked route, real editor); the live benchmark spec
+ (CANVIX_BENCH_LIVE=1, real provider) writes docs/BENCHMARK-v0.32.7.md.
+ Fixed: the panel crashed on a partial brief event.
+
### Changed — v0.32.6: ONE agent, ZERO selectors + the canvas map
- **One surface:** the five-tab unified app (Chat / Generate / Write /
@@ -4139,3 +4172,11 @@ Canva-style dashboard & mobile polish.
Initial release: Konva.js editor (text/shapes/lines/graphics/stickers/images),
smart snapping, layers, templates, dashboard, autosave, PNG/JPG export,
responsive mobile/tablet/desktop UI.
+
+### Evaluation note — v0.32.7
+
+The live benchmark spec exists (`tests/e2e/live-agent-benchmark.spec.ts`,
+`CANVIX_BENCH_LIVE=1`, writes `docs/BENCHMARK-v0.32.7.md` itself). Both
+session attempts were cut short by the provider gateway's real rate
+limits; no completion rates are claimed and the milestone PR was not
+merged on mocked results alone.
diff --git a/ROADMAP.md b/ROADMAP.md
index 324b072..6177cff 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -1,6 +1,7 @@
- v0.32.4 — deterministic design correctness: hard plan validation (real ≥40px gaps, bounds), duplicate-text/shape detection, plan adherence, wrap-up audit disclosure, per-design run ledger (0015), the phantom list_fonts tool made real.
- v0.32.5 — P0 regression fix: server-computed plan geometry (auto-repair, bounded infeasibility), no strikes for recoverable plans, zero-action runs skip vision critique, honest failure UI.
- v0.32.6 — one agent, zero selectors (5 tabs + 7 mode chips removed); the canvas map: plans fit the free space between existing elements.
+- v0.32.7 — 2D spatial map, edit intents, persistent+recoverable runs, provider fallback chain, authoritative re-audit.
# Canvix Roadmap — where we are, what's next
> **Status date:** 2026-11-25 · **Changelog state:** v0.31.0 · `package.json` 0.31.0 · **latest published GitHub release:** v0.31.0 · **Test posture:** 1,693 unit tests across 127 test files (verified full run, 25 Nov, the v0.31.0 release run) · 39 e2e spec files + the plugins & stock-video gated suites · CI gates every PR (`lint-unit` incl. production build + `e2e` running all three suites) · `npm audit` **0 vulnerabilities**.
diff --git a/docs/UNIFIED-AI-MILESTONE.md b/docs/UNIFIED-AI-MILESTONE.md
index 7f6a962..1be98d8 100644
--- a/docs/UNIFIED-AI-MILESTONE.md
+++ b/docs/UNIFIED-AI-MILESTONE.md
@@ -645,3 +645,137 @@ carving inside a free band remains the model's job, guarded by the
audit's overlap checks. Image GENERATION is not yet an agent tool
(the former Image tab's route remains an API; the agent places
existing assets, URLs and uploads).
+
+---
+
+# v0.32.7 — spatial intelligence, intent, persistence, resilience
+
+**The mandate:** "True 2D spatial intelligence… context-aware editing…
+persistent execution and recovery… provider resilience… multilevel
+verification… autonomous correction… test integrity… comprehensive
+evaluation… transparent reporting. Do not claim production readiness
+based solely on passing unit tests."
+
+## 1 · True 2D spatial intelligence (`src/lib/agent/spatial.ts`)
+
+The v0.32.6 canvas map was vertical-only. Now:
+
+- **AABBs with rotation** — a rotated rect expands to its true
+ footprint (`aabb()`, rotation rides the client context).
+- **Intentional layering** — a card behind its contained text, a
+ near-page backdrop, a backing card: `intentionalOverlaps()`
+ classifies them so the audit never flags correct layering (the
+ client's overlap list is filtered through it).
+- **Section-scale band blocking** — only elements ≥40% of the page
+ width block a full-width section band; smaller elements become
+ disclosed *partials* ("180x60 icon at (460,500) — plan around it
+ horizontally").
+- **2D free regions** — the largest free rectangles
+ (`freeRegions2D`), disclosed to the model in the design context
+ and the plan observation.
+- **Visual hierarchy** — the descending text-size ladder + a
+ flat-hierarchy advisory.
+
+## 2 · Context-aware editing (`src/lib/agent/intent.ts`)
+
+"Not every instruction on a populated canvas is an addition."
+`classifyEditIntent()` (deterministic, no model call) classifies
+the message as **add / replace / reposition / restyle / redesign /
+remove / refine / review / create**; the plan-first gate now fires
+only for create/add/redesign — a "check and fix issues" REFINE run
+is never bounced into planning six new sections (the live defect).
+Per-intent guidance rides the system prompt; the intent streams to
+the panel (SSE `intent` event) and shows live + on each turn.
+
+## 3 · Persistent execution + recovery
+
+`DesignAgentRun` gains `status` (running | interrupted | completed |
+stopped) + `state` (RunStateSnapshot: intent, request, brief, plan
+bands, applied actions, pending, verification milestones,
+migration `0016_agent_run_state`). The row is created at run START,
+updated live by the loop (`persistRun`), finalized at exit. A
+provider/network guard exit marks it **interrupted** — and the NEXT
+run on that design loads the snapshot and injects **INTERRUPTED RUN
+RECOVERY** into the system prompt: original request, what already
+landed, the plan, the verification state, and the instruction to
+COMPLETE, never re-add. No new surfaces, no selectors — the same
+agent, now recoverable.
+
+## 4 · Provider resilience (`src/lib/ai/chat-resilience.ts`)
+
+The 26 Nov incident (502 → fetch failed → 429, two hours) killed
+every mid-flight run. Now every agent model call goes through
+`chatResilient()`:
+
+- **bounded exponential backoff** (3 attempts, full jitter, capped)
+ for TRANSIENT failures only — auth/bad-request/unsupported-param
+ errors fail fast (retrying them burns money, not time);
+- **circuit breaker** per provider (5 consecutive transient
+ failures → open 30s → skip straight to fallback);
+- **the configured fallback chain** — the user's other BYOK text
+ providers, the instance slot, the env/file layers. Nothing is
+ invented: only already-configured providers answer, every attempt
+ passes the feature rate limit + AIUsage accounting, and
+ `ZAI_NO_FALLBACK=1` disables the chain for spend control.
+
+Token accounting: gateway-reported usage is accumulated + surfaced
+in the run's final usage event and the panel ("· 12.4k tokens");
+absent gateway usage is disclosed as "not reported", never estimated.
+
+## 5 · Multilevel verification + autonomous correction
+
+The audit (now 14 checks) understands intentional layering and adds
+alignment, typography-sprawl and hierarchy advisories. The
+**blocking contract**: contrast, overlap, off-canvas, obscured
+text, duplicates and empty planned sections trigger ONE bounded fix
+round, then the re-audit is AUTHORITATIVE — remaining blockers end
+the run **INCOMPLETE** (the same contract the vision round's P0
+gate already had). Advisories are disclosed, never blocking. The
+brief validator adopts the design engine's NFC-exact contract
+(composed accents are matches, not alterations).
+
+## 6 · Test integrity (the PR #94 fixtures, reviewed)
+
+All 13 v0.32.6-modified flows re-reviewed: the 11 moved to
+`compactDesign` + CASE C keep their original assertions and
+behavioral coverage (the plan-validation, brief-gate, audit,
+compaction and capability semantics are identical — the fixture
+only provides real free space, which PR #94's tests had made
+necessary and which remains CORRECT: a full-composition plan on a
+nearly-full canvas is honestly infeasible). None of them test the
+spread-out geometry itself; the spatial module now has dedicated
+coverage of both layouts. New regressions: 13 spatial, 15 intent,
+11 resilience, 11 loop-level (gate exemptions, blocking audit,
+interrupted-run persistence, recovery injection, intentional
+layering, advisories, NFC). A panel crash on partial brief events
+(found by the new e2e) is fixed defensively.
+
+## 7 · Evaluation — mocked vs real, labeled
+
+- **Mocked (CI):** unified-ai-reproduction 3/3, wave4 4/4, and the
+ new interrupted-run recovery e2e (mocked route, real editor).
+- **REAL (not in CI):** `tests/e2e/live-agent-benchmark.spec.ts`
+ (`CANVIX_BENCH_LIVE=1`) — real provider, real browser, real
+ route: seven design types + one editing scenario, each measured
+ for completion, brief fidelity, geometry (off-canvas, text-on-text
+ overlaps), intent, latency, turns/tools/model calls/tokens, and
+ provider failures. The report (`docs/BENCHMARK-v0.32.7.md`) is
+ written by the run itself — never hand-typed. See it for the
+ actual completion rates.
+
+## 8 · Evaluation state — HONEST
+
+The live benchmark (`tests/e2e/live-agent-benchmark.spec.ts`,
+`CANVIX_BENCH_LIVE=1`) was launched twice against the live provider.
+Both attempts were interrupted by the gateway's rate limits
+(real 429s under sustained load — the same incident class as
+26 Nov): the first attempt's poster run reached 13 steps · 11
+actions before a 429, the honest provider-failure message appeared,
+and the run persisted as interrupted exactly as designed. The
+benchmark spec (recovery-aware, cooldowns, 429 backoff ladder) did
+not complete a full 7-scenario pass in the session, so **no
+completion rates are claimed** — `docs/BENCHMARK-v0.32.7.md` is
+written only by a real completed run, never by hand. No merge was
+made from unit/mocked results alone (per the milestone's own
+rule); the PR stays open until a completed live benchmark is on
+record.
diff --git a/prisma/migrations/0016_agent_run_state/migration.sql b/prisma/migrations/0016_agent_run_state/migration.sql
new file mode 100644
index 0000000..e50d4d3
--- /dev/null
+++ b/prisma/migrations/0016_agent_run_state/migration.sql
@@ -0,0 +1,8 @@
+-- v0.32.7 · PERSISTENT EXECUTION — an interrupted run's live state.
+-- status: running | interrupted | completed | stopped — a run cut
+-- off mid-flight (429/502/network) persists 'interrupted' so the
+-- next message COMPLETES it instead of restarting (and duplicating).
+-- state: RunStateSnapshot (intent, request, brief, plan bands,
+-- applied tool calls, pending items, verification milestones).
+ALTER TABLE "DesignAgentRun" ADD COLUMN "status" TEXT;
+ALTER TABLE "DesignAgentRun" ADD COLUMN "state" JSONB;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 9d9f008..110d92c 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -489,6 +489,15 @@ model DesignAgentRun {
summary String @db.VarChar(600)
toolCalls Int @default(0)
findings String? @db.VarChar(1200)
+ /// v0.32.7 · PERSISTENT EXECUTION: running | interrupted |
+ /// completed | stopped — an interrupted run (429/502/network,
+ /// mid-flight) is recoverable; the next message COMPLETES it.
+ status String?
+ /// v0.32.7 · the run's live state, persisted as it happens:
+ /// intent, request, brief, plan bands, applied tool calls,
+ /// pending items, verification milestones (RunStateSnapshot).
+ /// Best-effort — the canvas stays the authority.
+ state Json?
@@index([designId, createdAt])
}
diff --git a/src/app/api/ai/agent/route.ts b/src/app/api/ai/agent/route.ts
index b5ae534..09ecd77 100644
--- a/src/app/api/ai/agent/route.ts
+++ b/src/app/api/ai/agent/route.ts
@@ -16,7 +16,10 @@ import { auditDesign as runDesignAudit } from '@/lib/agent/audit'
import { selectSkills } from '@/lib/agent/skills'
import { extractBrief, mergeBriefs, normalizeStoredBrief, type DesignBrief } from '@/lib/agent/brief'
import { critiqueWithVision } from '@/lib/agent/vision'
-import { getClientForSlotForUser } from '@/lib/ai/provider'
+import { classifyEditIntent } from '@/lib/agent/intent'
+import { chatResilient } from '@/lib/ai/chat-resilience'
+import { getClientForSlotForUser, getClientForSlot, makeClient, resolveSlot } from '@/lib/ai/provider'
+import { getProviders } from '@/lib/admin/config'
import { getSessionUser } from '@/lib/auth/session'
import { getDesignProvenance } from '@/lib/design-provenance'
import { db } from '@/lib/db'
@@ -217,19 +220,33 @@ async function __canvix_post(req: NextRequest) {
// loudly instead of silently degrading.
const jsonModePref = (process.env.ZAI_JSON_MODE ?? 'auto').trim().toLowerCase()
let jsonModeLive = jsonModePref !== 'off'
- const rawCreate = ctx.zai.chat.completions.create as unknown as (
- body: Record<string, unknown>,
- ) => Promise<{ choices: { message?: { content?: unknown } }[] }>
- const chat = async (msgs: { role: 'system' | 'user' | 'assistant'; content: string }[]) => {
+ type RawCreate = (body: Record<string, unknown>) => Promise<{ choices: { message?: { content?: unknown } }[] }>
+ interface ChatTarget {
+ /** circuit-breaker key — the provider's label/source */
+ key: string
+ zai: { chat: { completions: { create: RawCreate } } }
+ model?: string
+ }
+ const rawCreateOf = (t: ChatTarget): RawCreate =>
+ t.zai.chat.completions.create as unknown as RawCreate
+ /** one turn through ONE target (json-mode negotiation included).
+ * Token usage is accumulated when the gateway reports it. */
+ const callOnce = async (t: ChatTarget, msgs: { role: 'system' | 'user' | 'assistant'; content: string }[]) => {
const base: Record<string, unknown> = {
- ...(ctx.model ? { model: ctx.model } : {}),
+ ...(t.model ? { model: t.model } : {}),
messages: msgs,
thinking: { type: 'disabled' },
}
const callJson = (withJson: boolean) =>
- rawCreate(withJson ? { ...base, response_format: { type: 'json_object' } } : base)
+ rawCreateOf(t)(withJson ? { ...base, response_format: { type: 'json_object' } } : base)
+ const capture = (completion: { choices?: { message?: { content?: unknown } }[]; usage?: { prompt_tokens?: number; completion_tokens?: number } }) => {
+ const u = completion.usage
+ if (u && typeof u.prompt_tokens === 'number') promptTokens += u.prompt_tokens
+ if (u && typeof u.completion_tokens === 'number') completionTokens += u.completion_tokens
+ }
try {
const completion = await callJson(jsonModeLive)
+ capture(completion)
return String(completion.choices[0]?.message?.content ?? '')
} catch (e) {
const msg = String((e as Error | undefined)?.message ?? e)
@@ -240,12 +257,91 @@ async function __canvix_post(req: NextRequest) {
) {
jsonModeLive = false // remember for the whole run
const completion = await callJson(false)
+ capture(completion)
return String(completion.choices[0]?.message?.content ?? '')
}
throw e
}
}
+ // v0.32.7 · PROVIDER RESILIENCE — the configured fallback chain.
+ // The 26 Nov 2026 incident: the gateway flapped 502 → fetch
+ // failed → 429 for two hours and every mid-flight run DIED.
+ // chatResilient (chat-resilience.ts) wraps every model call:
+ // bounded exponential backoff for TRANSIENT failures (429/5xx/
+ // network — permanent errors fail fast), a per-provider circuit
+ // breaker, and the CONFIGURED fallback chain — other providers
+ // the user (BYOK) or the instance already configured for the
+ // text slot. Nothing is invented; every attempt still passes the
+ // feature rate limit and rides AIUsage accounting. ZAI_NO_FALLBACK=1
+ // disables the chain (spend control).
+ const primary: ChatTarget = {
+ key: ctx.label ?? ctx.source ?? 'primary',
+ zai: ctx.zai as unknown as ChatTarget['zai'],
+ model: ctx.model,
+ }
+ const chatTargets: ChatTarget[] = [primary]
+ const seenBase = new Set<string>([primary.key])
+ const addTarget = async (t: ChatTarget | null) => {
+ if (!t) return
+ if (seenBase.has(t.key)) return
+ seenBase.add(t.key)
+ chatTargets.push(t)
+ }
+ // the instance-wide slot (distinct when the user's BYOK answered)
+ if (ctx.source === 'user') {
+ try {
+ const inst = await getClientForSlot('text')
+ if (inst?.zai) await addTarget({ key: inst.label ?? `instance:${inst.source}`, zai: inst.zai as unknown as ChatTarget['zai'], model: inst.model })
+ } catch {
+ /* the chain answers with what it has */
+ }
+ }
+ // the env/file layers when a table/DB layer answered the primary
+ try {
+ const base = await resolveSlot('text')
+ if (base && (base.source === 'env' || base.source === 'file') && ctx.source !== 'env' && ctx.source !== 'file') {
+ const zai = await makeClient(base.baseUrl, base.apiKey, base.headers)
+ await addTarget({ key: `${base.source}:${base.baseUrl}`, zai: zai as unknown as ChatTarget['zai'], model: base.model })
+ }
+ } catch {
+ /* best-effort chain */
+ }
+ // the user's OTHER BYOK providers that answer the text slot
+ if (userId) {
+ try {
+ const rows = await db.userAIProvider.findMany({ where: { userId }, orderBy: { createdAt: 'asc' }, take: 8 })
+ for (const r of rows) {
+ const slots = r.slots.split(',').map((s) => s.trim())
+ if (!slots.includes('text')) continue
+ const model = (() => { try { const m = r.models as { text?: string } | null; return m?.text } catch { return undefined } })()
+ if (seenBase.has(`byok:${r.id}`)) continue
+ const zai = await makeClient(r.baseUrl, r.apiKey)
+ await addTarget({ key: `byok:${r.label}`, zai: zai as unknown as ChatTarget['zai'], model })
+ }
+ } catch {
+ /* BYOK must never break the fallback chain */
+ }
+ }
+
+ // v0.32.7: token accounting — accumulated from gateway-reported
+ // usage when present (never estimated; absent providers simply
+ // report nothing). Surfaced in the run's final usage event.
+ let promptTokens = 0
+ let completionTokens = 0
+ const chat = async (msgs: { role: 'system' | 'user' | 'assistant'; content: string }[]) => {
+ const text = await chatResilient(
+ chatTargets.map((t) => ({ key: t.key, fn: () => callOnce(t, msgs) })),
+ {
+ attempts: 3,
+ onRetry: (attempt, err, delay) => {
+ console.warn(`[ai/agent] transient provider failure (attempt ${attempt}), ${delay}ms backoff: ${String((err as Error)?.message ?? err).slice(0, 120)}`)
+ },
+ },
+ )
+ return text
+ }
+
// ── 1. classify the mode (heuristic first, model when unsure) ──
let mode: AgentMode
if (body.mode && MODE_TOOL_RISK[body.mode]) {
@@ -296,6 +392,12 @@ async function __canvix_post(req: NextRequest) {
!!(design.brand && (design.brand.colors?.length || design.brand.headingFont)),
)
+ // v0.32.7 · CONTEXT-AWARE EDITING: what does this message want
+ // DONE to the existing design? (deterministic — intent.ts). The
+ // loop's plan-first gate and per-intent guidance follow it, and
+ // the panel shows it live (SSE intent event).
+ const { intent, reason: intentReason } = classifyEditIntent(message, design)
+
const runId = newRunId()
const encoder = new TextEncoder()
@@ -371,21 +473,88 @@ async function __canvix_post(req: NextRequest) {
// THIS design (mode, request, actions, outcome) enter the
// system prompt. Best-effort: a ledger failure must never
// break the run itself.
+ // v0.32.7 · PERSISTENT EXECUTION: an unfinished 'running'
+ // row (server died mid-run) is excluded; an 'interrupted'
+ // row (429/502/network cut a run mid-flight) is loaded as
+ // RECOVERY so the next message COMPLETES the work instead
+ // of restarting (and duplicating) it.
let ledgerLines: string[] = []
+ let recoveryLines: string[] = []
if (design.designId) {
try {
const rows = await db.designAgentRun.findMany({
- where: { designId: design.designId },
+ where: { designId: design.designId, NOT: { status: 'running' } },
orderBy: { createdAt: 'desc' },
take: 3,
})
ledgerLines = rows.map(
(r) =>
- `${r.mode} "${r.request.slice(0, 80)}" → ${r.toolCalls} action(s): ${r.summary.slice(0, 160)}${r.findings ? ` [residue to fix: ${r.findings.slice(0, 140)}]` : ''}`,
+ `${r.mode} "${r.request.slice(0, 80)}" → ${r.toolCalls} action(s): ${r.summary.slice(0, 160)}${r.status === 'interrupted' ? ' [INTERRUPTED mid-run — its work is on the canvas]' : ''}${r.findings ? ` [residue to fix: ${r.findings.slice(0, 140)}]` : ''}`,
)
} catch {
/* best-effort — run without the ledger */
}
+ try {
+ const last = await db.designAgentRun.findFirst({
+ where: { designId: design.designId, status: 'interrupted' },
+ orderBy: { createdAt: 'desc' },
+ })
+ const state = last?.state as
+ | {
+ intent?: string
+ request?: string
+ plan?: { name: string; y: number; h: number }[]
+ applied?: { tool: string; detail?: string }[]
+ pending?: string[]
+ verification?: string[]
+ brief?: { requiredTexts?: string[] } | null
+ }
+ | null
+ if (last && state?.applied?.length) {
+ recoveryLines = [
+ `the interrupted run asked: "${state.request ?? last.request}" (intent: ${state.intent ?? '?'})`,
+ `it applied ${state.applied.length} action(s) — ALL of it is already on the canvas: ${state.applied.slice(-8).map((a) => a.tool).join(', ')}`,
+ state.plan?.length ? `its plan had ${state.plan.length} section(s): ${state.plan.map((b) => `${b.name} (y ${Math.round(b.y)}–${Math.round(b.y + b.h)})`).join(', ')}` : '',
+ state.pending?.length ? `pending items it had not finished: ${state.pending.join('; ')}` : '',
+ state.verification?.length ? `verification reached: ${state.verification.join(', ')}` : 'verification had not started',
+ ].filter(Boolean)
+ }
+ } catch {
+ /* best-effort — run without recovery */
+ }
+ }
+
+ // v0.32.7 · the run row: created at START (status 'running'),
+ // updated live by the loop's persistRun, finalized in the
+ // finally below. The canvas stays the authority; the row is
+ // the recoverable trace.
+ const runStartedAt = Date.now()
+ let runRowId: string | null = null
+ if (design.designId) {
+ try {
+ const row = await db.designAgentRun.create({
+ data: {
+ designId: design.designId,
+ mode,
+ request: message.slice(0, 240),
+ summary: '',
+ toolCalls: 0,
+ status: 'running',
+ },
+ })
+ runRowId = row.id
+ } catch {
+ /* best-effort — run without persistence */
+ }
+ }
+ const persistRun = (state: Record<string, unknown>) => {
+ if (!runRowId) return
+ void db.designAgentRun
+ .update({
+ where: { id: runRowId },
+ data: { status: String(state.status ?? 'running'), state: state as never },
+ })
+ .catch(() => {})
}
let loopResult: Awaited<ReturnType<typeof runAgentLoop>> | null = null
@@ -406,6 +575,15 @@ async function __canvix_post(req: NextRequest) {
ledger: ledgerLines,
brief,
skills,
+ // v0.32.7 · what this message wants done to the existing
+ // design (add/replace/reposition/restyle/redesign/remove/
+ // refine/review — deterministic, intent.ts) + the interrupted
+ // run's persisted state, so a retry COMPLETES the work
+ intent,
+ recovery: recoveryLines,
+ // v0.32.7 · live run-state persistence (best-effort) — the
+ // loop calls it after plans, applies and at exits
+ persistRun: (state) => persistRun(state as unknown as Record<string, unknown>),
emit,
confirmed: new Set(body.confirmed ?? []),
signal: {
@@ -490,29 +668,60 @@ async function __canvix_post(req: NextRequest) {
})
},
})
+ // v0.32.7: the run's final usage — turns, tools, wall time,
+ // model calls, and tokens when the gateway reported them
+ if (loopResult) {
+ emit({
+ v: AGENT_PROTOCOL_VERSION,
+ type: 'usage',
+ turns: loopResult.steps,
+ toolCalls: loopResult.toolCalls,
+ elapsedMs: Date.now() - runStartedAt,
+ modelCalls: 0,
+ ...(promptTokens || completionTokens ? { promptTokens, completionTokens } : {}),
+ })
+ }
} finally {
bridges.delete(runId)
- // v0.32.4: persist the run ledger row — what THIS run did,
- // so the next run in this design starts with grounded
- // execution memory. Best-effort: the run's outcome is
- // already streamed; a ledger write failure never
- // surfaces as an agent error.
+ // v0.32.4 → v0.32.7: finalize the run row (created at run
+ // START above): the loop's persistRun already set status/
+ // state; this writes the human summary + findings. An
+ // exception path (loopResult null) marks the row
+ // interrupted — its applied work is recoverable. Best-effort:
+ // a ledger write failure never surfaces as an agent error.
if (design.designId) {
try {
- await db.designAgentRun.create({
- data: {
- designId: design.designId,
- mode,
- request: message.slice(0, 240),
- summary: String(loopResult?.summary ?? '').slice(0, 600),
- toolCalls: loopResult?.toolCalls ?? 0,
- findings:
- (loopResult?.findings ?? [])
- .map((f) => `${f.severity} ${f.issue}`)
- .join(' | ')
- .slice(0, 1200) || null,
- },
- })
+ const interrupted = loopResult === null
+ if (runRowId) {
+ await db.designAgentRun.update({
+ where: { id: runRowId },
+ data: {
+ summary: String(loopResult?.summary ?? '(the run ended without a summary)').slice(0, 600),
+ toolCalls: loopResult?.toolCalls ?? 0,
+ findings:
+ (loopResult?.findings ?? [])
+ .map((f) => `${f.severity} ${f.issue}`)
+ .join(' | ')
+ .slice(0, 1200) || null,
+ ...(interrupted ? { status: 'interrupted' } : {}),
+ },
+ })
+ } else {
+ await db.designAgentRun.create({
+ data: {
+ designId: design.designId,
+ mode,
+ request: message.slice(0, 240),
+ summary: String(loopResult?.summary ?? '').slice(0, 600),
+ toolCalls: loopResult?.toolCalls ?? 0,
+ findings:
+ (loopResult?.findings ?? [])
+ .map((f) => `${f.severity} ${f.issue}`)
+ .join(' | ')
+ .slice(0, 1200) || null,
+ },
+ })
+ }
} catch {
/* best-effort ledger */
}
diff --git a/src/components/editor/apps/AssistantApp.tsx b/src/components/editor/apps/AssistantApp.tsx
index 26f3b11..81352af 100644
--- a/src/components/editor/apps/AssistantApp.tsx
+++ b/src/components/editor/apps/AssistantApp.tsx
@@ -59,10 +59,14 @@ interface Turn {
appliedActions?: number
baseline?: number
mode?: AgentMode
+ /** v0.32.7: what the run wanted done to the existing design
+ * (add / replace / reposition / restyle / redesign / remove /
+ * refine / review — deterministic, intent.ts) */
+ intent?: string
plan?: string[]
findings?: Finding[]
verification?: string
- usage?: { turns: number; toolCalls: number; elapsedMs: number; modelCalls: number }
+ usage?: { turns: number; toolCalls: number; elapsedMs: number; modelCalls: number; promptTokens?: number; completionTokens?: number }
}
const SUGGESTIONS = [
@@ -118,6 +122,12 @@ function buildDesignContext() {
height: Math.round(el.height),
locked: el.locked,
}
+ // v0.32.7: rotation rides the context — the server's spatial map
+ // expands rotated elements to their true AABB footprint
+ if ('rotation' in el && typeof (el as { rotation?: unknown }).rotation === 'number') {
+ const rot = (el as { rotation: number }).rotation
+ if (Math.abs(rot) >= 0.5) base.rotation = Math.round(rot * 10) / 10
+ }
if (el.type === 'text') {
const t = el as TextElement
base.text = t.text.slice(0, 80)
@@ -294,9 +304,11 @@ export function AssistantApp({ onClose }: AppPanelProps) {
const [liveSteps, setLiveSteps] = useState<RunStep[]>([])
/** live mode + skills + brief of the in-flight run */
const [liveMode, setLiveMode] = useState<AgentMode | null>(null)
+ /** v0.32.7: the live run's edit intent (add/replace/restyle/…) */
+ const [liveIntent, setLiveIntent] = useState<string | 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)
+ const [liveUsage, setLiveUsage] = useState<{ turns: number; toolCalls: number; elapsedMs: number; modelCalls: number; promptTokens?: number; completionTokens?: number } | null>(null)
/** pending destructive confirmation */
const [pendingConfirm, setPendingConfirm] = useState<{ tool: string; actions: DesignAction[]; callId: string } | null>(null)
const scrollRef = useRef<HTMLDivElement>(null)
@@ -405,6 +417,7 @@ export function AssistantApp({ onClose }: AppPanelProps) {
let appliedCount = 0
let summary = ''
let mode = expectedMode
+ let turnIntent: string | undefined
let plan: string[] | undefined
let findings: Finding[] | undefined
let verification: string | undefined
@@ -444,6 +457,12 @@ export function AssistantApp({ onClose }: AppPanelProps) {
mode = event.mode
setLiveMode(event.mode)
break
+ case 'intent':
+ // v0.32.7: what this message wants DONE to the existing
+ // design — shown live under the mode
+ turnIntent = event.intent
+ setLiveIntent(event.intent)
+ break
case 'skill':
setLiveSkills((s) => [...s, event.name])
break
@@ -472,7 +491,14 @@ export function AssistantApp({ onClose }: AppPanelProps) {
break
}
case 'usage':
- setLiveUsage({ turns: event.turns, toolCalls: event.toolCalls, elapsedMs: event.elapsedMs, modelCalls: event.modelCalls })
+ setLiveUsage({
+ turns: event.turns,
+ toolCalls: event.toolCalls,
+ elapsedMs: event.elapsedMs,
+ modelCalls: event.modelCalls,
+ ...(event.promptTokens !== undefined ? { promptTokens: event.promptTokens } : {}),
+ ...(event.completionTokens !== undefined ? { completionTokens: event.completionTokens } : {}),
+ })
break
case 'capture': {
// v0.29.3: the loop asks for the REAL rendered canvas
@@ -582,6 +608,7 @@ export function AssistantApp({ onClose }: AppPanelProps) {
content: summary || 'Done.',
steps: collectedSteps,
appliedActions: appliedCount,
+ intent: turnIntent,
baseline,
mode,
plan,
@@ -592,7 +619,7 @@ export function AssistantApp({ onClose }: AppPanelProps) {
])
} 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 }])
+ setTurns((ts) => [...ts, { role: 'assistant', content: msg, steps: collectedSteps, appliedActions: appliedCount, baseline, mode, intent: turnIntent }])
} finally {
setBusy(false)
setLiveSteps([])
@@ -694,7 +721,7 @@ export function AssistantApp({ onClose }: AppPanelProps) {
{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
+ <ListChecks size={12} /> {turn.steps.length} steps · {turn.appliedActions ?? 0} actions{turn.intent ? ` · ${turn.intent}` : ''}
</summary>
<ol className="px-3 pb-2 space-y-1.5">
{turn.steps.map((s, j) => (
@@ -770,7 +797,7 @@ export function AssistantApp({ onClose }: AppPanelProps) {
<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
+ {turn.usage.turns} turns · {turn.usage.toolCalls} tools · {Math.round(turn.usage.elapsedMs / 1000)}s · {turn.usage.modelCalls} model calls{turn.usage.promptTokens !== undefined ? ` · ${((turn.usage.promptTokens + (turn.usage.completionTokens ?? 0)) / 1000).toFixed(1)}k tokens` : ''}
</span>
</div>
)}
@@ -795,20 +822,22 @@ export function AssistantApp({ onClose }: AppPanelProps) {
<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>
+ <span>
+ {liveMode} mode{liveIntent ? ` · ${liveIntent}` : ''}
+ </span>
{liveSkills.map((s) => (
<span key={s} className="px-1.5 rounded bg-[#02C0CC]/10 text-[#02C0CC] normal-case">{s}</span>
))}
</div>
)}
- {liveBrief && (liveBrief.requiredTexts.length > 0 || liveBrief.requiredColors.length > 0) && (
+ {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) => (
+ {(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">&ldquo;{t.text}&rdquo;</span>
))}
- {liveBrief.requiredColors.map((c, i) => (
+ {(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()}
diff --git a/src/lib/agent/audit.ts b/src/lib/agent/audit.ts
index 6c7d65c..ba70258 100644
--- a/src/lib/agent/audit.ts
+++ b/src/lib/agent/audit.ts
@@ -24,6 +24,7 @@
*/
import type { AgentDesignCtx, AgentElementCtx } from './context'
import { parseColor } from './brief'
+import { elementBoxes, intentionalOverlaps, isIntentional, hierarchyLines } from './spatial'
const HEX = /^#?[0-9a-f]{6}$/i
@@ -164,9 +165,20 @@ export function auditDesign(
}
}
- // 3. element overlaps (client-computed) — hard readability failures
- for (const o of (d.overlaps ?? []).slice(0, 3)) issues.push(`Elements overlap: ${o} — move or resize one of them.`)
- if ((d.overlaps ?? []).length > 3) issues.push(`…and ${(d.overlaps ?? []).length - 3} more overlapping pairs.`)
+ // 3. element overlaps (client-computed) — hard readability failures.
+ // v0.32.7: INTENTIONAL layering is not a defect — spatial.ts
+ // classifies container/backdrop/backing-card pairs (a card
+ // behind its text is layering); only GENUINE collisions remain.
+ if (d.overlaps?.length) {
+ const intentional = intentionalOverlaps(elementBoxes(d), d.width ?? 1080, d.height ?? 1080)
+ const genuine = (d.overlaps ?? []).filter((o) => {
+ const ids = [...o.matchAll(/#([\w-]+)/g)].map((m) => m[1])
+ if (ids.length !== 2) return true // unparseable — keep the finding
+ return !isIntentional(intentional, ids[0], ids[1])
+ })
+ for (const o of genuine.slice(0, 3)) issues.push(`Elements overlap: ${o} — move or resize one of them.`)
+ if (genuine.length > 3) issues.push(`…and ${genuine.length - 3} more overlapping pairs.`)
+ }
// 4. off-canvas elements
for (const o of (d.offCanvas ?? []).slice(0, 3)) issues.push(`Element is outside the canvas: ${o} — move it back inside ${d.width ?? '?'}x${d.height ?? '?'}.`)
@@ -341,6 +353,40 @@ export function auditDesign(
}
}
+ // 12. ALIGNMENT (v0.32.7): wide text elements (≥30% page width)
+ // that claim to span the content column should sit centered
+ // (x-center within 12px of the page center) — advisory, not
+ // a hard failure (asymmetric layouts are legitimate).
+ if (d.width) {
+ const cx = d.width / 2
+ const misaligned: string[] = []
+ for (const t of texts) {
+ const b = box(t)
+ if (b.w < 0.3 * d.width!) continue
+ const c = b.x + b.w / 2
+ if (Math.abs(c - cx) > 12) misaligned.push(`"${String(t.text ?? '').slice(0, 24)}" (x-center ${Math.round(c)} vs page center ${Math.round(cx)})`)
+ }
+ if (misaligned.length === 1) {
+ issues.push(`ADVISORY alignment: wide text is off the page center — ${misaligned[0]}; center it (align_elements cx) unless the asymmetry is intentional.`)
+ } else if (misaligned.length > 1) {
+ issues.push(`ADVISORY alignment: ${misaligned.length} wide text elements are off the page center (${misaligned.slice(0, 2).join('; ')}); align them (align_elements cx) unless the asymmetry is intentional.`)
+ }
+ }
+
+ // 13. TYPOGRAPHY (v0.32.7): more than 3 font families on one page
+ // reads as noise — advisory (decorative pairings are legitimate).
+ const families = new Set(texts.map((t) => t.fontFamily).filter((f): f is string => !!f && f !== 'Poppins'))
+ if (families.size > 3) {
+ issues.push(`ADVISORY typography: ${families.size} font families on one page (${[...families].slice(0, 5).join(', ')}) — reduce to a heading + body pairing (set_text_style / set_font).`)
+ }
+
+ // 14. VISUAL HIERARCHY (v0.32.7): the largest text should clearly
+ // dominate the body (spatial.ts ladder) — advisory.
+ const hierarchy = hierarchyLines(d)
+ for (const h of hierarchy) {
+ if (h.startsWith('ADVISORY')) issues.push(h)
+ }
+
return issues.slice(0, 12)
}
diff --git a/src/lib/agent/brief.ts b/src/lib/agent/brief.ts
index e0c80a6..63f93b9 100644
--- a/src/lib/agent/brief.ts
+++ b/src/lib/agent/brief.ts
@@ -380,8 +380,13 @@ export function validateBrief(
// rejections the gate bounces back to fix. (Whitespace is still
// collapsed — line-wrap artifacts are benign, everything else
// must match character for character.)
- const wanted = t.text.replace(/\s+/g, ' ').trim()
- const found = state.texts.some((s) => s.replace(/\s+/g, ' ').trim() === wanted)
+ // v0.32.7 (design-engine hardening): NFC normalization both
+ // sides — the deterministic engine's exactEquals contract
+ // (compile.ts). A required text containing "café" must match
+ // an element whose "é" was stored as e + U+0301 (unicode
+ // composition differences are not alterations).
+ const wanted = t.text.replace(/\s+/g, ' ').trim().normalize('NFC')
+ const found = state.texts.some((s) => s.replace(/\s+/g, ' ').trim().normalize('NFC') === wanted)
if (!found) unmet.push(`Required text missing or altered: "${t.text}"`)
return { text: t.text, found }
})
diff --git a/src/lib/agent/context.ts b/src/lib/agent/context.ts
index 0eda674..e8f26c4 100644
--- a/src/lib/agent/context.ts
+++ b/src/lib/agent/context.ts
@@ -15,7 +15,7 @@
// ─────────────────────────────────────────────────────────────
import type { DesignBrief } from './brief'
-import { mergeOccupied } from './plan-repair'
+import { freeVerticalBands, freeRegions2D, hierarchyLines, spatialMap } from './spatial'
export interface AgentElementCtx {
id: string
@@ -33,6 +33,9 @@ export interface AgentElementCtx {
fontFamily?: string
name?: string
locked?: boolean
+ /** v0.32.7: rotation in degrees — the spatial map expands the
+ * AABB so rotated elements occupy their true footprint. */
+ rotation?: number
/** v0.29.3: client-measured rendered text width in px (canvas
* measureText — the same metrics the renderer uses). Present when
* a v0.29.3+ panel built the context; the audit's overflow check
@@ -117,6 +120,22 @@ export function serializeDesignContext(d: AgentDesignCtx): string {
lines.push(`Fonts in use: ${(d.fontsInUse ?? []).slice(0, 8).join(', ') || 'none'}`)
lines.push(`Overlapping pairs: ${d.overlaps?.length ? d.overlaps.join('; ') : 'none detected'}`)
lines.push(`Off-canvas elements: ${d.offCanvas?.length ? d.offCanvas.join('; ') : 'none detected'}`)
+ // v0.32.7 · the 2D SPATIAL MAP — z-order, intentional layering,
+ // free space and hierarchy, computed deterministically (spatial.ts)
+ if (els.length) {
+ const map = spatialMap(d)
+ if (map.intentional.length) {
+ lines.push(`Intentional layering (NOT defects): ${map.intentional.slice(0, 6).map((p) => `${p.front.type}#${p.front.id} on its ${p.kind} ${p.back.type}#${p.back.id}`).join('; ')}`)
+ }
+ if (map.partials.length) {
+ lines.push(`Small elements to plan around horizontally: ${map.partials.slice(0, 4).join('; ')}`)
+ }
+ const regions = freeRegions2D(d, 5)
+ if (regions.length) {
+ lines.push(`Largest free regions (x,y w×h): ${regions.map((r) => `(${r.x},${r.y}) ${r.w}×${r.h}`).join(' | ')}`)
+ }
+ lines.push(...hierarchyLines(d))
+ }
if (d.otherPages?.length) lines.push(`Other pages: ${d.otherPages.join(' | ')}`)
return lines.join('\n')
}
@@ -126,22 +145,10 @@ export function contextValidIds(d: AgentDesignCtx): Set<string> {
return new Set((d.elements ?? []).map((e) => e.id))
}
-/** v0.32.6 · the CANVAS MAP: existing elements as occupied vertical
- * bands (merged, disjoint, label = text excerpt or type). The plan
- * solver fits new sections into the FREE space between these bands,
- * so a plan can never reserve space on top of existing content —
- * "it first maps what's present geometrically" happens here, in
- * deterministic code, not in the model's arithmetic. */
+/** v0.32.6 · the CANVAS MAP → v0.32.7: TRUE 2D. The vertical bands
+ * the plan solver eats now come from spatial.ts (rotation-aware
+ * AABBs, z-order, section-scale blocking, partial-occupancy
+ * disclosures) instead of a naive every-element merge. */
export function canvasMap(d: AgentDesignCtx): { y: number; h: number; label?: string }[] {
- const raw = (d.elements ?? [])
- .filter((e) => typeof e.y === 'number' && (typeof e.height === 'number' || typeof e.fontSize === 'number'))
- .map((e) => ({
- y: e.y as number,
- h: Math.max(1, Math.round((e.height as number | undefined) ?? (e.fontSize as number | undefined) ?? 24)),
- label:
- typeof e.text === 'string' && e.text.trim()
- ? e.text.trim().slice(0, 24)
- : undefined,
- }))
- return mergeOccupied(raw)
+ return freeVerticalBands(d).occupied
}
diff --git a/src/lib/agent/harness.test.ts b/src/lib/agent/harness.test.ts
index 31673ba..851fe94 100644
--- a/src/lib/agent/harness.test.ts
+++ b/src/lib/agent/harness.test.ts
@@ -2487,23 +2487,26 @@ describe('v0.32.6 · the canvas map — plans fit the FREE space, never on top',
expect(r.infeasible).toContain('Move or clear existing elements')
})
- it('canvasMap merges close elements into disjoint occupied bands', async () => {
+ it('canvasMap (v0.32.7 2D): section-scale elements block bands; close ones merge; small ones do not', async () => {
const { canvasMap } = await import('./context')
+ const { freeVerticalBands } = await import('./spatial')
const d = {
name: 'Map test', width: 1080, height: 1080, pageCount: 1, currentPageIndex: 0,
- // two elements 35px apart merge (a 40px band cannot fit between)
elements: [
- { id: 'a', type: 'text', y: 65, height: 200, text: 'Headline' },
- { id: 'b', type: 'rect', y: 300, height: 100 },
- { id: 'c', type: 'text', y: 900, fontSize: 60, text: 'Footer line' },
+ // two wide elements 35px apart merge (a 40px band cannot fit between)
+ { id: 'a', type: 'text', x: 100, y: 65, width: 800, height: 200, text: 'Headline' },
+ { id: 'b', type: 'rect', x: 100, y: 300, width: 700, height: 100 },
+ // small elements do NOT block a full-width section band
+ { id: 'c', type: 'text', x: 450, y: 900, width: 180, height: 60, fontSize: 60, text: 'Footer line' },
],
colorsInUse: [], otherPages: [],
} as never as AgentDesignCtx
const map = canvasMap(d)
- expect(map).toEqual([
- { y: 65, h: 335, label: 'Headline' },
- { y: 900, h: 60, label: 'Footer line' },
- ])
+ expect(map).toEqual([{ y: 65, h: 335, label: 'Headline' }])
+ // …and they are disclosed as partials instead
+ const bands = freeVerticalBands(d)
+ expect(bands.partials.join(' ')).toContain('Footer line')
+ expect(bands.partials.join(' ')).toContain('180x60')
})
it('plan_layout on an occupied canvas discloses the CANVAS MAP and fits the free space', () => {
@@ -2517,7 +2520,7 @@ describe('v0.32.6 · the canvas map — plans fit the FREE space, never on top',
const obs = String((res as { observation?: string }).observation)
expect(obs).toContain('CANVAS MAP')
expect(obs).toContain('y 65–365 (COFFEE LAUNCH)')
- expect(obs).toContain('fitted into the FREE space')
+ expect(obs).toContain('fitted into the FREE vertical space')
const bands = (res as { actions?: { bands?: { name: string; y: number; h: number }[] }[] }).actions?.[0]?.bands
for (const b of bands ?? []) {
expect(b.y).toBeGreaterThanOrEqual(805)
@@ -2530,7 +2533,7 @@ describe('v0.32.6 · the canvas map — plans fit the FREE space, never on top',
const occupiedDesign: AgentDesignCtx = {
name: 'Half-built poster', width: 1080, height: 1080, pageCount: 1, currentPageIndex: 0,
elements: [
- { id: 'txt-1', type: 'text', y: 65, height: 300, text: 'EXISTING HEADLINE' },
+ { id: 'txt-1', type: 'text', x: 140, y: 65, width: 800, height: 300, text: 'EXISTING HEADLINE' },
],
colorsInUse: [], otherPages: [],
}
@@ -2557,3 +2560,248 @@ describe('v0.32.6 · the canvas map — plans fit the FREE space, never on top',
expect(plan?.steps?.join('\n')).toContain('y=365')
})
})
+
+// ═════════════════════════════════════════════════════════════
+// v0.32.7 · CONTEXT-AWARE EDITING + PERSISTENT EXECUTION
+// ═════════════════════════════════════════════════════════════
+
+describe('v0.32.7 · the edit intent drives the loop', () => {
+ it('a REFINE instruction never gets the plan-first bounce (the live defect is dead)', async () => {
+ const { chat, calls } = scriptedChat([
+ turn('update_elements', { ids: ['txt-1'], patch: { fill: '#FFFFFF' } }),
+ done('Contrast fixed.'),
+ ])
+ const events: AgentEvent[] = []
+ const result = await runAgentLoop({
+ chat,
+ design: compactDesign,
+ mode: 'improve',
+ request: 'Check the design for overlaps and errors, fix any issues, then stop',
+ emit: (e) => events.push(e),
+ awaitApply: async () => ({ ok: true }),
+ })
+ expect(result.summary).toContain('Contrast fixed.')
+ // the write applied on the FIRST attempt — no plan bounce turn
+ expect(result.toolCalls).toBe(1)
+ expect(events.some((e) => e.type === 'intent')).toBe(true)
+ const intentEvt = events.find((e) => e.type === 'intent') as { intent: string }
+ expect(intentEvt.intent).toBe('refine')
+ // the system prompt carries the EDIT INTENT guidance, not the
+ // full-composition planning boilerplate
+ const sys = calls[0].find((m) => m.role === 'system')?.content ?? ''
+ expect(sys).toContain('REFINE: polish what exists')
+ expect(sys).not.toContain('LAYOUT PLANNING (required first step)')
+ })
+
+ it('an ADD instruction keeps the plan-first gate (additions plan into free space)', async () => {
+ const { chat } = scriptedChat([
+ turn('add_text', { text: 'Too eager', fontSize: 40 }),
+ turn('plan_layout', { sections: [{ name: 'offer', y: 900, height: 100, contains: 'sale' }] }),
+ turn('add_text', { text: 'Sale', fontSize: 40 }),
+ done('Added the offer.'),
+ ])
+ const result = await runAgentLoop({
+ chat,
+ design: compactDesign,
+ mode: 'improve',
+ request: 'Add an offer banner under the headline',
+ emit: () => {},
+ awaitApply: async () => ({ ok: true }),
+ })
+ // the first write was bounced once (no plan yet) — the gate still
+ // guards ADDITIVE intent on a populated canvas
+ expect(result.toolCalls).toBe(1)
+ expect(result.summary).toContain('Added the offer.')
+ })
+
+ it('a RESTYLE instruction reaches the system prompt as restyle guidance', async () => {
+ const { chat, calls } = scriptedChat([
+ turn('set_background', { kind: 'solid', from: '#090B1A' }),
+ done('Background darkened.'),
+ ])
+ await runAgentLoop({
+ chat,
+ design: compactDesign,
+ mode: 'improve',
+ request: 'Recolor the background to deep navy and increase contrast',
+ emit: () => {},
+ awaitApply: async () => ({ ok: true }),
+ })
+ const sys = calls[0].find((m) => m.role === 'system')?.content ?? ''
+ expect(sys).toContain('RESTYLE: change colors')
+ })
+})
+
+describe('v0.32.7 · blocking audit: no success claim until checks complete', () => {
+ it('a blocking issue after the fix round ends the run INCOMPLETE (advisories do not)', async () => {
+ let auditCalls = 0
+ const { chat } = scriptedChat([
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] }),
+ turn('set_background', { kind: 'solid', from: '#090B1A' }),
+ turn('add_text', { text: 'Fixable', fontSize: 40 }),
+ done('Poster complete'),
+ turn('add_text', { text: 'Second try', fontSize: 40 }),
+ done('Poster complete again'),
+ ])
+ const result = await runAgentLoop({
+ chat,
+ design: compactDesign,
+ mode: 'create',
+ request: 'Design a poster',
+ emit: () => {},
+ awaitApply: async () => ({ ok: true }),
+ auditDesign: async () => {
+ auditCalls += 1
+ // round 1: a blocking contrast issue → fix round.
+ // round 2 (re-audit): still blocking → INCOMPLETE, never a pass.
+ return ['Low contrast: text "Hero" on its effective backdrop is 1.2:1 (needs 4.5:1) — change the fill.', 'ADVISORY alignment: wide text is off the page center']
+ },
+ })
+ expect(auditCalls).toBe(2)
+ expect(result.summary).toContain('INCOMPLETE — blocking quality issues remain')
+ expect(result.verification).toContain('NOT verified')
+ })
+
+ it('an advisory-only audit never blocks: fix round only for blockers, pass with advisories', async () => {
+ const { chat } = scriptedChat([
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }] }),
+ turn('set_background', { kind: 'solid', from: '#090B1A' }),
+ turn('add_text', { text: 'Done', fontSize: 40 }),
+ done('Done.')
+ ])
+ const result = await runAgentLoop({
+ chat,
+ design: compactDesign,
+ mode: 'create',
+ request: 'Design a poster',
+ emit: () => {},
+ awaitApply: async () => ({ ok: true }),
+ auditDesign: async () => ['ADVISORY typography: 4 font families on one page'],
+ })
+ expect(result.summary).toBe('Done.')
+ expect(result.verification).toContain('no blocking issues remain (1 advisory/disclosed)')
+ })
+})
+
+describe('v0.32.7 · persistent execution + recovery', () => {
+ it('a provider failure mid-run persists INTERRUPTED state with the applied work', async () => {
+ const snapshots: { status: string; appliedCount: number }[] = []
+ const { chat } = scriptedChat([
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }] }),
+ turn('set_background', { kind: 'solid', from: '#090B1A' }),
+ turn('add_text', { text: 'Half-built', fontSize: 40 }),
+ // the next model call explodes — the 502 mid-run
+ '{not json',
+ JSON.stringify({ done: true, summary: '(never reached)' }),
+ ])
+ const result = await runAgentLoop({
+ chat: async (msgs) => {
+ const reply = chat(msgs)
+ const text = await reply
+ if (text === '{not json') throw new Error('API request failed with status 502: Bad Gateway')
+ return text
+ },
+ design: compactDesign,
+ mode: 'create',
+ request: 'Design a poster',
+ emit: () => {},
+ awaitApply: async () => ({ ok: true }),
+ persistRun: (state) => snapshots.push({ status: state.status, appliedCount: state.applied.length }),
+ })
+ // the run died on the provider error with the applied work kept
+ expect(result.summary).toContain('provider')
+ const last = snapshots[snapshots.length - 1]
+ expect(last.status).toBe('interrupted')
+ expect(last.appliedCount).toBe(2) // set_background + add_text applied; the next model call died
+ expect(snapshots.some((s) => s.status === 'running')).toBe(true)
+ })
+
+ it('recovery lines ride the system prompt: COMPLETE the work, never re-add', async () => {
+ const { chat, calls } = scriptedChat([
+ turn('get_page_state'),
+ done('Recovered: the section was already on the canvas; nothing duplicated.'),
+ ])
+ const events: AgentEvent[] = []
+ await runAgentLoop({
+ chat,
+ design: compactDesign,
+ mode: 'improve',
+ request: 'Continue and finish the design',
+ recovery: [
+ 'the interrupted run asked: "Design a poster" (intent: create)',
+ 'it applied 3 action(s) — ALL of it is already on the canvas: set_background, add_text',
+ 'its plan had 3 section(s): hero (y 60–260), body (y 300–600), cta (y 640–800)',
+ ],
+ emit: (e) => events.push(e),
+ awaitApply: async () => ({ ok: true }),
+ })
+ const sys = calls[0].find((m) => m.role === 'system')?.content ?? ''
+ expect(sys).toContain('INTERRUPTED RUN RECOVERY')
+ expect(sys).toContain('already on the canvas')
+ expect(sys).toContain('NEVER re-add existing content')
+ })
+})
+
+describe('v0.32.7 · the audit understands layering + design quality', () => {
+ it('a card behind its text is NOT an overlap finding (intentional layering)', async () => {
+ const { auditDesign } = await import('./audit')
+ const issues = auditDesign(
+ {
+ name: 'Layered', width: 1080, height: 1080,
+ elements: [
+ { id: 'card', type: 'rect', x: 100, y: 400, width: 400, height: 200, fill: '#16233A' },
+ { id: 'label', type: 'text', x: 120, y: 440, width: 360, height: 60, text: 'Feature one', fill: '#F5F7FA', fontSize: 28, fontFamily: 'Poppins' },
+ ],
+ overlaps: ['rect#card × text#label (95%)'],
+ colorsInUse: [],
+ } as never as AgentDesignCtx,
+ )
+ expect(issues.some((i) => i.startsWith('Elements overlap'))).toBe(false)
+ })
+
+ it('a genuine same-layer collision IS a finding', async () => {
+ const { auditDesign } = await import('./audit')
+ const issues = auditDesign(
+ {
+ name: 'Clash', width: 1080, height: 1080,
+ elements: [
+ { id: 'a', type: 'text', x: 100, y: 100, width: 500, height: 120, text: 'Headline', fill: '#FFFFFF', fontSize: 60, fontFamily: 'Poppins' },
+ { id: 'b', type: 'rect', x: 300, y: 140, width: 500, height: 200, fill: '#FF5500' },
+ ],
+ overlaps: ['text#a × rect#b (55%)'],
+ colorsInUse: [],
+ } as never as AgentDesignCtx,
+ )
+ expect(issues.some((i) => i.startsWith('Elements overlap'))).toBe(true)
+ })
+
+ it('wide off-center text and font sprawl surface as ADVISORIES (never blocking)', async () => {
+ const { auditDesign } = await import('./audit')
+ const issues = auditDesign(
+ {
+ name: 'Quality', width: 1080, height: 1080,
+ elements: [
+ { id: 't1', type: 'text', x: 40, y: 200, width: 500, height: 80, text: 'Off-center wide text', fill: '#FFFFFF', fontSize: 40, fontFamily: 'Poppins' },
+ { id: 't2', type: 'text', x: 60, y: 400, width: 400, height: 60, text: 'Another one', fill: '#FFFFFF', fontSize: 30, fontFamily: 'Montserrat' },
+ { id: 't3', type: 'text', x: 60, y: 520, width: 400, height: 60, text: 'Third', fill: '#FFFFFF', fontSize: 30, fontFamily: 'Playfair Display' },
+ { id: 't4', type: 'text', x: 60, y: 640, width: 400, height: 60, text: 'Fourth', fill: '#FFFFFF', fontSize: 30, fontFamily: 'Bebas Neue' },
+ { id: 't5', type: 'text', x: 60, y: 760, width: 400, height: 60, text: 'Fifth', fill: '#FFFFFF', fontSize: 30, fontFamily: 'Space Grotesk' },
+ ],
+ overlaps: [],
+ colorsInUse: [],
+ } as never as AgentDesignCtx,
+ )
+ expect(issues.some((i) => i.startsWith('ADVISORY alignment'))).toBe(true)
+ expect(issues.some((i) => i.startsWith('ADVISORY typography'))).toBe(true)
+ })
+
+ it('the design-engine NFC contract: composed accents satisfy exact text', async () => {
+ const { validateBrief } = await import('./brief')
+ // "café" in the brief vs "cafe\u0301" (e + combining acute) on canvas
+ const r = validateBrief(
+ { requiredTexts: [{ text: 'Café Latte Special', tier: 'mandatory' }], requiredColors: [] } as never,
+ { texts: ['Cafe\u0301 Latte Special'], colors: [], elements: [] } as never,
+ )
+ expect(r.satisfied).toBe(true)
+ })
+})
diff --git a/src/lib/agent/intent.test.ts b/src/lib/agent/intent.test.ts
new file mode 100644
index 0000000..d74dacb
--- /dev/null
+++ b/src/lib/agent/intent.test.ts
@@ -0,0 +1,99 @@
+/**
+ * v0.32.7 · EDIT INTENT — the deterministic classifier's contract.
+ * "Not every instruction on a populated canvas is an addition."
+ */
+import { describe, expect, it } from 'vitest'
+import { classifyEditIntent, intentRequiresPlan, intentGuidance } from './intent'
+import type { AgentDesignCtx } from './context'
+
+const EMPTY: AgentDesignCtx = { name: 'Blank', width: 1080, height: 1080, elements: [] }
+const POPULATED: AgentDesignCtx = {
+ name: 'Coffee launch',
+ width: 1080,
+ height: 1080,
+ elements: [{ id: 'a', type: 'text', x: 100, y: 65, width: 800, height: 200, text: 'Sip the Future' }],
+}
+
+describe('intent · classification', () => {
+ it('an empty canvas is always a create', () => {
+ expect(classifyEditIntent('recolor the background', EMPTY)).toMatchObject({ intent: 'create' })
+ expect(classifyEditIntent('whatever', EMPTY).intent).toBe('create')
+ })
+
+ it('additive language on a populated canvas is an add', () => {
+ expect(classifyEditIntent('Add a CTA button below the headline', POPULATED).intent).toBe('add')
+ expect(classifyEditIntent('insert a footer with hashtags', POPULATED).intent).toBe('add')
+ })
+
+ it('replacement language is a replace', () => {
+ expect(classifyEditIntent('Replace the headline with "Grand Opening"', POPULATED).intent).toBe('replace')
+ expect(classifyEditIntent('swap the subline for a shorter tagline', POPULATED).intent).toBe('replace')
+ })
+
+ it('positioning language is a reposition (no plan, ever)', () => {
+ expect(classifyEditIntent('Move the headline down 40px', POPULATED).intent).toBe('reposition')
+ expect(classifyEditIntent('center the title', POPULATED).intent).toBe('reposition')
+ expect(classifyEditIntent('align the cards', POPULATED).intent).toBe('reposition')
+ })
+
+ it('styling language is a restyle (no plan)', () => {
+ expect(classifyEditIntent('Recolor the background to dark navy', POPULATED).intent).toBe('restyle')
+ expect(classifyEditIntent('make the headline bold and bigger', POPULATED).intent).toBe('restyle')
+ expect(classifyEditIntent('change the font to Montserrat', POPULATED).intent).toBe('restyle')
+ })
+
+ it('rebuild language is a redesign (destructive, plan first)', () => {
+ expect(classifyEditIntent('redesign this from scratch as a food festival poster', POPULATED).intent).toBe('redesign')
+ expect(classifyEditIntent('start over with a completely different layout', POPULATED).intent).toBe('redesign')
+ })
+
+ it('removal language is a remove (no plan)', () => {
+ expect(classifyEditIntent('delete the footer', POPULATED).intent).toBe('remove')
+ expect(classifyEditIntent('get rid of the sticker', POPULATED).intent).toBe('remove')
+ })
+
+ it('review language is a review', () => {
+ expect(classifyEditIntent('What is wrong with this design?', POPULATED).intent).toBe('review')
+ expect(classifyEditIntent('review the contrast', POPULATED).intent).toBe('review')
+ })
+
+ it('the live defect: "check for overlaps and fix any issues" is a REFINE, not a review or an add', () => {
+ const r = classifyEditIntent('Check the design for overlaps and errors, fix any issues, verify it matches the brief, then stop', POPULATED)
+ expect(r.intent).toBe('refine')
+ expect(r.reason).toBe('fix language on an existing design')
+ })
+
+ it('polish language is a refine', () => {
+ expect(classifyEditIntent('Make this design more professional', POPULATED).intent).toBe('refine')
+ expect(classifyEditIntent('polish the spacing', POPULATED).intent).toBe('refine')
+ })
+
+ it('no matching verb on a populated canvas defaults to refine (never an unrequested rebuild)', () => {
+ expect(classifyEditIntent('the coffee launch promo', POPULATED).intent).toBe('refine')
+ })
+})
+
+describe('intent · the plan-first gate respects the intent', () => {
+ it('create / add / redesign require a plan', () => {
+ expect(intentRequiresPlan('create')).toBe(true)
+ expect(intentRequiresPlan('add')).toBe(true)
+ expect(intentRequiresPlan('redesign')).toBe(true)
+ })
+ it('replace / reposition / restyle / remove / refine / review never need a section plan', () => {
+ for (const i of ['replace', 'reposition', 'restyle', 'remove', 'refine', 'review'] as const) {
+ expect(intentRequiresPlan(i)).toBe(false)
+ }
+ })
+})
+
+describe('intent · guidance', () => {
+ it('every intent has concrete guidance mentioning its tool verbs', () => {
+ expect(intentGuidance('add')).toContain('ADDITIONS ONLY')
+ expect(intentGuidance('reposition')).toContain('move_elements')
+ expect(intentGuidance('restyle')).toContain('No plan_layout')
+ expect(intentGuidance('redesign')).toContain('clear_page')
+ expect(intentGuidance('remove')).toContain('delete_elements')
+ expect(intentGuidance('refine')).toContain('polish')
+ expect(intentGuidance('review')).toContain('read-only')
+ })
+})
diff --git a/src/lib/agent/intent.ts b/src/lib/agent/intent.ts
new file mode 100644
index 0000000..87da371
--- /dev/null
+++ b/src/lib/agent/intent.ts
@@ -0,0 +1,177 @@
+/**
+ * v0.32.7 · CONTEXT-AWARE EDITING — what does this instruction
+ * actually want to DO to the existing design?
+ *
+ * The defect (seen live): "Check the design for overlaps and fix
+ * issues" was treated as an ADDITIVE instruction — the model planned
+ * a full new composition and the plan solver tried to fit six new
+ * sections onto a nearly-full canvas. Not every instruction on a
+ * populated canvas adds content.
+ *
+ * classifyEditIntent() is a DETERMINISTIC keyword router (the same
+ * philosophy as heuristicMode — no model call, no latency, testable):
+ *
+ * create empty canvas — build from scratch (plan required)
+ * add add NEW content alongside what exists (plan the
+ * ADDITIONS into the free space, never on top)
+ * replace swap specific elements for something else
+ * reposition move/align existing elements (no plan — the layout
+ * already exists; planning sections here is noise)
+ * restyle recolor / fonts / background / contrast / theme
+ * (no plan, no geometry)
+ * redesign rebuild the composition from scratch (destructive:
+ * plan first, clearing needs confirmation)
+ * remove delete elements (no plan)
+ * refine polish/improve in place (default on a populated
+ * canvas when no verb matches — balance, audit-fix)
+ * review read-only analysis
+ */
+
+import type { AgentDesignCtx } from './context'
+
+export type EditIntent =
+ | 'create'
+ | 'add'
+ | 'replace'
+ | 'reposition'
+ | 'restyle'
+ | 'redesign'
+ | 'remove'
+ | 'refine'
+ | 'review'
+
+export interface IntentResult {
+ intent: EditIntent
+ /** one deterministic reason line, for tests + telemetry */
+ reason: string
+}
+
+interface Rule {
+ intent: Exclude<EditIntent, 'create'>
+ /** matched against the lowercased message */
+ re: RegExp
+ /** rules earlier in the list win when several match */
+ order: number
+ reason: string
+}
+
+/** Ordered: the FIRST matching rule classifies the message. */
+const RULES: Rule[] = [
+ {
+ intent: 'redesign',
+ re: /\b(redesign|start over|start again|rebuild|recreate|re-?do|from scratch|completely different|overhaul)\b/,
+ order: 1,
+ reason: 'rebuild language',
+ },
+ {
+ intent: 'remove',
+ re: /\b(remove|delete|get rid of|erase|take (it|that|them) out|clear (it|that|them)( up)?|drop (it|that|them))\b/,
+ order: 2,
+ reason: 'removal language',
+ },
+ {
+ intent: 'replace',
+ re: /\b(replace|swap|substitute|change .{3,40} (to|into|with) .{3,40}|instead of\b.{3,40}\buse|make it a different)\b/,
+ order: 3,
+ reason: 'replacement language',
+ },
+ {
+ intent: 'reposition',
+ re: /\b(move|shift|nudge|reposition|center|centre|align|distribute|space (them|it|that)? ?out|spread out|raise|lower|bring (it|that) (up|down)|push (it|that) (up|down|left|right))\b/,
+ order: 4,
+ reason: 'positioning language',
+ },
+ {
+ intent: 'review',
+ re: /\b(review|check|audit|critique|inspect|look at|assess|feedback|issues?|problems?|wrong with|score|rate)\b/,
+ order: 5,
+ reason: 'review language',
+ },
+ {
+ intent: 'restyle',
+ re: /\b(recolou?r|colou?r|palette|font|typography|bold|italic|weight|theme|contrast|brighter|darker|background|fill|stroke|opacity|shade|tint|round(ed)? corners|restyle|style)\b/,
+ order: 6,
+ reason: 'styling language',
+ },
+ {
+ intent: 'add',
+ re: /\b(add|insert|put|place|include|append|also (add|make|create|put)|another|on top|underneath|below (it|that|the)|above (it|that|the)|next to|more (content|elements?|sections?|text|space|cards?))\b/,
+ order: 7,
+ reason: 'additive language',
+ },
+]
+
+/** A "change <style-noun> to …" is a RESTYLE, not a replace — the
+ * target of the change is the look of an existing element, not its
+ * content ("change the font to Montserrat" restyles; "change the
+ * headline to 'Grand Opening'" replaces). */
+const STYLE_NOUN_CHANGE_RE = /\bchange (the )?(font|colou?r|fill|stroke|background|palette|size|typeface|typography|style|weight|spacing|opacity)\b/
+
+const REFINE_RE = /\b(improve|polish|refine|balance|fix|clean up|tidy|finish|complete|better|enhance|perfect)\b/
+
+/** "check … and fix …" is a fix/refine, not a review — a check
+ * followed by an action verb wants the action done. */
+function fixOverridesReview(message: string): boolean {
+ return /\b(fix|repair|resolve|correct)\b/.test(message)
+}
+
+export function classifyEditIntent(message: string, design: AgentDesignCtx): IntentResult {
+ const m = (message || '').toLowerCase().slice(0, 600)
+ const populated = (design.elements ?? []).length > 0
+
+ // an EMPTY canvas: every build instruction is a create
+ if (!populated) {
+ return { intent: 'create', reason: 'empty canvas' }
+ }
+
+ if (fixOverridesReview(m)) {
+ return { intent: 'refine', reason: 'fix language on an existing design' }
+ }
+
+ for (const rule of RULES) {
+ if (rule.re.test(m)) {
+ if (rule.intent === 'replace' && STYLE_NOUN_CHANGE_RE.test(m)) {
+ return { intent: 'restyle', reason: 'styling language (change <style-noun>)' }
+ }
+ return { intent: rule.intent, reason: rule.reason }
+ }
+ }
+
+ if (REFINE_RE.test(m)) {
+ return { intent: 'refine', reason: 'refinement language' }
+ }
+
+ // no verb matched: on a populated canvas the safe default is a
+ // refinement of what exists (never an unrequested rebuild)
+ return { intent: 'refine', reason: 'default on a populated canvas' }
+}
+
+/** Which intents still require a section plan before writes? */
+export function intentRequiresPlan(intent: EditIntent): boolean {
+ return intent === 'create' || intent === 'add' || intent === 'redesign'
+}
+
+/** The per-intent guidance injected into the system prompt (the
+ * agent knows what the user wants DONE, not just the mode). */
+export function intentGuidance(intent: EditIntent): string {
+ switch (intent) {
+ case 'create':
+ return 'CREATE: the canvas is empty — plan the full composition (plan_layout), then build section by section.'
+ case 'add':
+ return 'ADD: existing content stays. plan_layout is for YOUR ADDITIONS ONLY (the sections you are about to add), fitted by the server into the FREE space — never plan sections that describe existing content. Add around what is there, never on top of it.'
+ case 'replace':
+ return 'REPLACE: swap the named elements for the new content — update the existing element in place (update_elements / set_text_style / set_text_spans) or delete the target then add the replacement AT THE SAME POSITION. Do NOT re-plan the whole page; the rest of the design stays untouched.'
+ case 'reposition':
+ return 'REPOSITION: move/align the existing elements (move_elements / align_elements / distribute_elements). No plan_layout — the composition already exists; geometry only shifts.'
+ case 'restyle':
+ return 'RESTYLE: change colors, fonts, background or contrast of the EXISTING design (recolor / set_text_style / set_font / set_background). No plan_layout and no new sections — same content, new look.'
+ case 'redesign':
+ return 'REDESIGN: rebuild the composition from scratch. plan_layout first (the new full composition), then clear_page/delete_elements (the destructive gate will ask the user for approval) and rebuild. The stored brief still applies.'
+ case 'remove':
+ return 'REMOVE: delete the named elements (delete_elements — approval will be asked). Nothing else changes; no plan_layout.'
+ case 'refine':
+ return 'REFINE: polish what exists — fix overlaps, contrast, alignment, balance; complete missing pieces of the brief. No plan_layout unless you ADD whole new sections; work on the existing elements.'
+ case 'review':
+ return 'REVIEW: read-only — get_page_state, inspect, report findings with evidence. Do not modify the design.'
+ }
+}
diff --git a/src/lib/agent/loop.ts b/src/lib/agent/loop.ts
index 25a73d8..44c5758 100644
--- a/src/lib/agent/loop.ts
+++ b/src/lib/agent/loop.ts
@@ -44,7 +44,9 @@ export function telemetry(event: Record<string, unknown>): void {
}
}
import { AGENT_TOOLS, AGENT_TOOL_MAP, fontFamilies, type ToolContext, type SanitizeResult, type AgentTool } from './tools'
-import { serializeDesignContext, contextValidIds, canvasMap, type AgentDesignCtx } from './context'
+import { serializeDesignContext, contextValidIds, type AgentDesignCtx } from './context'
+import { spatialCtx } from './spatial'
+import { classifyEditIntent, intentRequiresPlan, intentGuidance, type EditIntent } from './intent'
import { MODE_PROMPTS, MODE_TOOL_RISK } from './router'
import { skillsPromptSection, selectSkills, type DesignSkill } from './skills'
import { briefPromptSection, type DesignBrief } from './brief'
@@ -114,6 +116,43 @@ export interface LoopDeps {
refreshedContext?: () => AgentDesignCtx
/** client-side brief validation result (validated against real state) */
validateBriefOnClient?: () => Promise<{ satisfied: boolean; unmet: string[] } | null>
+ /** v0.32.7: what this message wants DONE to the existing design
+ * (add / replace / reposition / restyle / redesign / remove /
+ * refine / review). Default: classified here from the request.
+ * Drives the plan-first gate (create/add/redesign plan; the rest
+ * never need a section plan) and the EDIT INTENT guidance. */
+ intent?: EditIntent
+ /** v0.32.7: persisted state of the INTERRUPTED previous run on
+ * this design (brief / plan / applied / pending / verification)
+ * — injected into the system prompt so a retry completes the
+ * work instead of duplicating it. */
+ recovery?: string[]
+ /** v0.32.7: persist the run's live state (best-effort, non-
+ * blocking) so an interrupted run can be recovered. Called after
+ * a plan records, after each applied action, and at run exits. */
+ persistRun?: (state: RunStateSnapshot) => void
+}
+
+/** v0.32.7 · the persisted run state — what an interrupted run
+ * needs to be COMPLETED (not restarted): the original request,
+ * brief, plan, the actions already applied, what remains, and how
+ * far verification got. Written by the loop, persisted by the
+ * route into DesignAgentRun.state. */
+export interface RunStateSnapshot {
+ intent: EditIntent
+ request: string
+ /** the run's brief contract, if any */
+ brief?: { requiredTexts?: string[] } | null
+ /** the validated plan's bands, if a plan ran */
+ plan?: { name: string; y: number; h: number }[]
+ /** applied tool calls in order */
+ applied: { tool: string; detail?: string }[]
+ /** plan sections with no content yet (from the audit) */
+ pending: string[]
+ /** verification milestones reached so far */
+ verification: string[]
+ /** running | interrupted | completed | stopped */
+ status: 'running' | 'interrupted' | 'completed' | 'stopped'
}
export interface LoopResult {
@@ -150,8 +189,18 @@ export function loopSystemPrompt(deps: {
* got there, so follow-ups build on prior work instead of
* re-deriving it. */
ledger?: string[]
+ /** v0.32.7: what the user wants DONE to the existing design
+ * (add / replace / reposition / restyle / redesign / remove /
+ * refine / review) — per-intent guidance replaces the old
+ * "every populated-canvas instruction is additive" assumption. */
+ intent?: EditIntent
+ /** v0.32.7: interrupted-run recovery lines — the persisted brief,
+ * plan, applied/pending actions and verification state of the
+ * interrupted run (from DesignAgentRun), injected so a retry
+ * COMPLETES the work instead of duplicating it. */
+ recovery?: string[]
}): string {
- const { design, ctx, mode, brief, skills, ledger } = deps
+ const { design, ctx, mode, brief, skills, ledger, intent, recovery } = deps
const W = design.width ?? 1080
const H = design.height ?? 1080
const margin = 0.06
@@ -161,6 +210,10 @@ export function loopSystemPrompt(deps: {
'',
MODE_PROMPTS[mode],
'',
+ // v0.32.7 · CONTEXT-AWARE EDITING: the classified intent of THIS
+ // message — what the user wants done to the existing design.
+ ...(intent ? ['EDIT INTENT (what this message wants done):', `· ${intentGuidance(intent)}`, ''] : []),
+ '',
// v0.32.3: the geometry ground truth, stated up front with the
// numbers computed for THIS page — where the canvas starts and
// ends, where elements may live, how the listed boxes read.
@@ -191,11 +244,15 @@ export function loopSystemPrompt(deps: {
if (section) lines.push(section, '')
}
- if (mode === 'create' || mode === 'improve') {
+ // v0.32.7: planning guidance is INTENT-aware. Full-composition
+ // planning is for create/redesign; an ADD plans only its additions
+ // into the free space; reposition/restyle/remove/refine never need
+ // a section plan (the composition already exists).
+ if (intent ? intentRequiresPlan(intent) : mode === 'create' || mode === 'improve') {
lines.push(
'LAYOUT PLANNING (required first step):',
'· Call plan_layout FIRST with your composition: page background, sections with y-ranges, what each contains (headline band, tagline, feature cards row, mockup, CTA, footer).',
- '· Reserve a vertical band per section with ≥40px gaps so nothing stacks or crowds; the brief texts each get their section. Invalid plans (gaps under 40px, bands beyond the page) are REJECTED with the exact numbers — fix the bands and resend.',
+ '· Reserve a vertical band per section with ≥40px gaps so nothing stacks or crowds; the brief texts each get their section. The SERVER computes the exact y-positions — with ≥40px gaps into the safe area, and on a canvas that already has content, into the FREE space between existing elements (never on top of them).',
'· Set the page background EARLY with set_background (a required background color belongs there, not in strips).',
'· Build section by section after the plan. NEVER add bare decorative bars/strips just to include a required color — use colors as the page background, text fills, or real panel/card fills.',
'· A realistic editor mockup = a large native panel (rounded rect, glass fill, border) CONTAINING inner native elements (toolbar bar, sidebar, canvas area, buttons) — not one empty rectangle.',
@@ -204,6 +261,16 @@ export function loopSystemPrompt(deps: {
)
}
+ // v0.32.7 · INTERRUPTED RUN RECOVERY — the previous run on this
+ // design was cut off mid-flight (provider/network). Its persisted
+ // brief, plan, applied and pending work ride the prompt so a
+ // retry COMPLETES the work instead of duplicating it.
+ if (recovery?.length) {
+ lines.push('INTERRUPTED RUN RECOVERY (the previous run on this design was interrupted — its state, persisted):')
+ for (const entry of recovery) lines.push(`· ${entry}`)
+ lines.push('· The canvas ALREADY contains the applied work — verify with get_page_state before adding anything, and NEVER re-add existing content. Complete only the missing pieces.', '')
+ }
+
// v0.32.4: the per-design run ledger — what the agent did in THIS
// design recently. The canvas state above stays the authority; the
// ledger explains how it got there (so "another one like the last
@@ -242,6 +309,16 @@ function observationFor(tool: string, result: SanitizeResult, ok: boolean): stri
return `ERROR in ${tool}: ${result.ok ? 'unknown error' : result.error}`
}
+/** v0.32.7 · which audit issues BLOCK completion? Everything the
+ * audit itself marks ADVISORY (alignment, typography, hierarchy,
+ * deep-margin text) is disclosed but never blocking; the rest
+ * (contrast, overlap, off-canvas, obscured text, duplicates,
+ * empty planned sections) are hard readability failures — a run
+ * with one of them left after the fix round ends INCOMPLETE. */
+function isAuditBlocking(issue: string): boolean {
+ return !/^(ADVISORY|Text ".*" sits deep inside the page margin)/.test(issue)
+}
+
/** Hash a tool call for cycle detection. */
function callHash(tool: string, args: unknown): string {
try {
@@ -274,6 +351,10 @@ function compactMessages(
export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
const { chat, design, mode, emit, signal } = deps
const brief = deps.brief ?? null
+ // v0.32.7 · CONTEXT-AWARE EDITING: what does this message want
+ // DONE to the existing design? (classifyEditIntent is deterministic
+ // — the route pre-computes it, the harness lets it default here)
+ const intent = deps.intent ?? classifyEditIntent(deps.request, design).intent
const skills =
deps.skills ??
selectSkills(
@@ -335,20 +416,46 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
* produce a fitting plan stops honestly with the exact math
* instead of retrying forever. */
let planRejections = 0
+ // ── v0.32.7 · PERSISTENT EXECUTION ─────────────────────────
+ // The run's live state: what was asked, planned, applied, verified.
+ // deps.persistRun (best-effort) writes it to DesignAgentRun so an
+ // interrupted run (429/502/network) can be COMPLETED by the next
+ // message instead of restarted-and-duplicated.
+ const appliedLog: { tool: string; detail?: string }[] = []
+ const verificationLog: string[] = []
+ const persist = (status: RunStateSnapshot['status'], pending: string[] = []) => {
+ if (!deps.persistRun) return
+ try {
+ deps.persistRun({
+ intent,
+ request: deps.request.slice(0, 240),
+ brief: brief ? { requiredTexts: (brief.requiredTexts ?? []).map((t) => t.text) } : null,
+ plan: planBands.length ? planBands.map((b) => ({ name: b.name, y: Math.round(b.y), h: Math.round(b.h) })) : undefined,
+ applied: appliedLog.slice(-40),
+ pending,
+ verification: verificationLog.slice(-8),
+ status,
+ })
+ } catch {
+ /* best-effort — persistence must never break the run */
+ }
+ }
const toolCtx: ToolContext = {
validIds: contextValidIds(design),
width: design.width ?? 1080,
height: design.height ?? 1080,
fonts: new Set(fontFamilies()),
- // v0.32.6 · the CANVAS MAP: existing elements' occupied bands.
- // The plan solver fits new sections into the FREE space between
- // them — nothing is planned on top of existing content.
- occupied: canvasMap(design),
+ // v0.32.6 · the CANVAS MAP → v0.32.7: TRUE 2D — occupied bands
+ // (section-scale), small-element partials and the largest free
+ // regions all ride the tool context now (spatial.ts). The plan
+ // solver fits new sections into the FREE space; the plan
+ // observation discloses the whole map.
+ ...spatialCtx(design),
}
const messages: { role: 'system' | 'user' | 'assistant'; content: string }[] = [
- { role: 'system', content: loopSystemPrompt({ design, ctx: toolCtx, mode, brief, skills, ledger: deps.ledger }) },
+ { role: 'system', content: loopSystemPrompt({ design, ctx: toolCtx, mode, brief, skills, ledger: deps.ledger, intent, recovery: deps.recovery }) },
// v0.32.3: the conversation this request arrives in — prior
// user/assistant turns, verbatim (route-sanitized). The model
// knows what it already did in this chat.
@@ -366,6 +473,7 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
const requestIndex = messages.length - 1
emit({ v: AGENT_PROTOCOL_VERSION, type: 'mode', mode, reason: `classified as ${mode}` })
+ emit({ v: AGENT_PROTOCOL_VERSION, type: 'intent', intent, reason: classifyEditIntent(deps.request, design).reason })
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> })
@@ -417,6 +525,11 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
const guardExitWithTelemetry = async (base: string, reason: string) => {
const exit = await guardExit(base)
telemetry({ outcome: 'guard-exit', reason, steps, toolCalls, designChanges, planRejections })
+ // v0.32.7: a provider/network guard exit is an INTERRUPTION —
+ // the run state persists so the next message COMPLETES the work.
+ // Every other guard exit is an honest stop (state keeps what
+ // landed, for the ledger + recovery context).
+ persist(reason === 'provider' ? 'interrupted' : 'stopped')
return exit
}
@@ -481,7 +594,10 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
message: `The AI provider failed: ${err instanceof Error ? err.message.slice(0, 200) : 'unknown error'}. Applied work is kept — retry to continue.`,
code: 'PROVIDER',
})
- const exit = await guardExitWithTelemetry(summary, 'provider')
+ const exit = await guardExitWithTelemetry(
+ summary || 'The run was interrupted by an AI provider failure — applied work is kept; send a follow-up to complete it.',
+ 'provider',
+ )
return { summary: exit.summary, steps, toolCalls, verification: exit.verification }
}
@@ -510,6 +626,7 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
if ((mode === 'create' || mode === 'improve') && designChanges === 0) {
emptyDoneRejections += 1
if (emptyDoneRejections >= 2) {
+ persist('stopped')
const honest = `INCOMPLETE — no design changes were made. ${summary}`
const noChangeVerification =
'NOT completed — the run ended without applying any design change; nothing was created.'
@@ -537,6 +654,7 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
// 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')
+ persist('stopped', v.unmet.slice(0, 8))
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 }
@@ -550,12 +668,18 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
if (v?.satisfied) {
briefValidated = true
verification = 'Brief contract validated against the live canvas — all mandatory items present.'
+ verificationLog.push('brief validated')
}
}
// QUALITY AUDIT (v0.29): self-critique before the run is
// accepted — local heuristics only, no extra model calls.
- // Exactly ONE fix round: done is then accepted with the residue
- // DISCLOSED (audit → fix → re-audit → honest outcome), never looped.
+ // v0.32.7 · AUTONOMOUS CORRECTION, COMPLETED: exactly ONE fix
+ // round, then the re-audit is AUTHORITATIVE — remaining
+ // BLOCKING issues (overlap, off-canvas, covered text,
+ // duplicates, contrast — anything not marked ADVISORY) end the
+ // run INCOMPLETE, exactly like the vision round's P0 gate. A
+ // run may not claim success while a required check still
+ // fails; advisories stay disclosed, never blocking.
if ((mode === 'create' || mode === 'improve') && deps.auditDesign) {
let issues: string[] = []
try {
@@ -563,18 +687,19 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
} catch {
/* audit is best-effort — never block completion on it */
}
- if (issues.length && auditRounds === 0) {
+ const blocking = issues.filter(isAuditBlocking)
+ if (blocking.length && auditRounds === 0) {
auditRounds += 1
- const list = issues.map((i) => `· ${i}`).join('\n')
+ const list = blocking.map((i) => `· ${i}`).join('\n')
emit({
v: AGENT_PROTOCOL_VERSION,
type: 'observation',
stepIndex: steps,
- message: `QUALITY AUDIT — ${issues.length} fixable issue(s) found:\n${list}`,
+ message: `QUALITY AUDIT — ${blocking.length} blocking issue(s) found (advisories disclosed):\n${list}${issues.length > blocking.length ? `\nAdvisories (not blocking): ${issues.filter((i) => !isAuditBlocking(i)).slice(0, 2).join('; ')}` : ''}`,
})
messages.push({
role: 'user',
- content: `QUALITY AUDIT before completion — the canvas has these fixable problems:\n${list}\nFix them now with concrete tool calls (contrast: change the text fill; overflow: reduce fontSize, shorten text or widen the box; overlap/off-canvas: move or resize), then emit done again with an updated summary.`,
+ content: `QUALITY AUDIT before completion — the canvas has these blocking problems:\n${list}\nFix them now with concrete tool calls (contrast: change the text fill; overflow: reduce fontSize, shorten text or widen the box; overlap/off-canvas: move or resize), then emit done again with an updated summary.`,
})
continue
}
@@ -582,10 +707,24 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
verification = verification
? `${verification} Quality audit passed: contrast, spacing and bounds clean.`
: 'Quality audit passed: contrast, spacing and bounds clean.'
- } else if (auditRounds > 0) {
- verification = verification
- ? `${verification} Quality audit still reports ${issues.length} issue(s) after the fix round — disclosed, not blocking.`
- : `Quality audit still reports ${issues.length} issue(s) after the fix round — disclosed, not blocking.`
+ } else if (auditRounds > 0 && blocking.length) {
+ // the fix round ran, the re-audit still finds blockers —
+ // honest INCOMPLETE (the same contract as the vision round)
+ verificationLog.push(`audit: ${blocking.length} blocking issue(s) remained after the fix round`)
+ const blockList = blocking.map((i) => `· ${i}`).join('\n')
+ verification = `NOT verified — ${blocking.length} blocking quality issue(s) remain after the correction pass:\n${blockList}\nThe design is NOT confirmed correct; the issues above need a follow-up.`
+ const blocked = `INCOMPLETE — blocking quality issues remain after the correction pass. ${summary}`
+ persist('stopped', blocking.slice(0, 6))
+ emit({ v: AGENT_PROTOCOL_VERSION, type: 'done', summary: blocked, steps, toolCalls, verification })
+ return { summary: blocked, steps, toolCalls, verification }
+ } else {
+ // no blocking issue (none at all, or advisories only —
+ // advisories never trigger a fix round and never block)
+ const note = issues.length
+ ? `no blocking issues remain (${issues.length} advisory/disclosed)`
+ : 'contrast, spacing and bounds clean'
+ const when = auditRounds > 0 ? 'Quality audit after the fix round' : 'Quality audit passed'
+ verification = verification ? `${verification} ${when}: ${note}.` : `${when}: ${note}.`
}
}
@@ -657,6 +796,12 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
}
}
+ // v0.32.7 · persistent execution: the completed run's state —
+ // for the ledger + the recovery context of any FUTURE run
+ if (visionBlocked) verificationLog.push('vision: P0 defects remained')
+ else if (visionCritiques > 0) verificationLog.push('vision pass complete')
+ if (briefValidated) verificationLog.push('brief validated')
+ persist('completed')
emit({ v: AGENT_PROTOCOL_VERSION, type: 'done', summary, steps, toolCalls, verification })
return {
summary,
@@ -691,15 +836,20 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
})
continue
}
- // v0.32.3 PLAN-FIRST: a create/improve run whose first action is
- // a WRITE (before any plan_layout) is redirected ONCE — geometry
- // first, then build. Reads are always fine; a run that already
- // planned is never bounced; after one bounce the model may
- // proceed (never a hard block, the guards still hold).
+ // v0.32.3 PLAN-FIRST (v0.32.7: intent-aware): a run whose FIRST
+ // action is a WRITE (before any plan_layout) is redirected ONCE —
+ // geometry first, then build. Reads are always fine; a run that
+ // already planned is never bounced; after one bounce the model
+ // may proceed (never a hard block). INTENT-AWARE: create / add /
+ // redesign plan their composition; reposition / restyle / remove
+ // / refine never need a section plan — the composition already
+ // exists, and forcing one is noise (the live defect: "check and
+ // fix issues" was bounced into planning six new sections).
if (
!planBounced &&
!planHasRun &&
(mode === 'create' || mode === 'improve') &&
+ intentRequiresPlan(intent) &&
(tool.risk === 'write' || tool.risk === 'destructive') &&
toolName !== 'set_background'
) {
@@ -731,6 +881,9 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
planBands.length = 0
planBands.push(...planActions.flatMap((a) => (a && a.type === '__planLayout' && Array.isArray(a.bands) ? a.bands : [])))
telemetry({ tool: 'plan_layout', outcome: 'recorded', repaired: (result.observation ?? '').includes('AUTO-REPAIRED'), bands: planBands.length })
+ // v0.32.7: persist the run state (the plan is the backbone of
+ // recovery — an interrupted run's next message completes it)
+ persist('running')
const lines = planLines.length ? planLines : ['(model emitted an empty plan)']
emit({ v: AGENT_PROTOCOL_VERSION, type: 'plan', steps: lines })
emit({ v: AGENT_PROTOCOL_VERSION, type: 'observation', stepIndex: steps, message: result.observation })
@@ -884,7 +1037,16 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
markProgress()
// v0.32.2: only real writes count as design changes (reads —
// get_page_state/measure/plan/validate — never do)
- if (tool.risk === 'write' || tool.risk === 'destructive') designChanges += 1
+ if (tool.risk === 'write' || tool.risk === 'destructive') {
+ designChanges += 1
+ // v0.32.7 · persistent execution: applied writes ride the
+ // run state — recovery knows what already landed
+ appliedLog.push({
+ tool: toolName,
+ detail: (result.actions as { type?: string }[] | undefined)?.slice(0, 2).map((a) => a.type).join(','),
+ })
+ persist('running')
+ }
emit({ v: AGENT_PROTOCOL_VERSION, type: 'observation', stepIndex: steps - 1, message: result.observation })
// usage telemetry: immediately on the first apply, then at most
@@ -903,9 +1065,9 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
content: `UPDATED PAGE STATE (fresh from the client after your edits):\n${serializeDesignContext(refreshed)}`,
})
// refresh the local tool context too — new ids are valid now
- // and the canvas map reflects what the edits actually occupy
+ // and the 2D canvas map reflects what the edits actually occupy
toolCtx.validIds = contextValidIds(refreshed)
- toolCtx.occupied = canvasMap(refreshed)
+ Object.assign(toolCtx, spatialCtx(refreshed))
continue
}
diff --git a/src/lib/agent/protocol.ts b/src/lib/agent/protocol.ts
index bd579fe..c69230f 100644
--- a/src/lib/agent/protocol.ts
+++ b/src/lib/agent/protocol.ts
@@ -77,6 +77,10 @@ export type ToolRisk = 'read' | 'write' | 'destructive'
export type AgentEvent =
| { v: number; type: 'start'; intent: AgentMode; plan?: string[]; runId?: string }
| { v: number; type: 'mode'; mode: AgentMode; reason: string }
+ /** v0.32.7: what this message wants DONE to the existing design —
+ * add / replace / reposition / restyle / redesign / remove /
+ * refine / review (deterministic classification, intent.ts) */
+ | { v: number; type: 'intent'; intent: string; reason: string }
| { v: number; type: 'skill'; id: string; name: string }
| { v: number; type: 'brief'; brief: Record<string, unknown> }
| { v: number; type: 'plan'; steps: string[] }
@@ -96,8 +100,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 }
- /** periodic run telemetry — turns, tool calls, wall ms, model calls */
- | { v: number; type: 'usage'; turns: number; toolCalls: number; elapsedMs: number; modelCalls: number }
+ /** periodic run telemetry — turns, tool calls, wall ms, model calls.
+ * v0.32.7: prompt/completion tokens when the gateway reports them
+ * (the route's final usage event carries the run total; absent when
+ * the provider does not report usage — never estimated). */
+ | { v: number; type: 'usage'; turns: number; toolCalls: number; elapsedMs: number; modelCalls: number; promptTokens?: number; completionTokens?: number }
/** v0.29.3: the loop asks the CLIENT to screenshot the live canvas
* (the export pipeline's captureStage) mid-run, BEFORE completion —
* the grounded vision critique runs on the real render, not the
diff --git a/src/lib/agent/spatial.test.ts b/src/lib/agent/spatial.test.ts
new file mode 100644
index 0000000..3f572dc
--- /dev/null
+++ b/src/lib/agent/spatial.test.ts
@@ -0,0 +1,134 @@
+/**
+ * v0.32.7 · SPATIAL INTELLIGENCE — the 2D canvas map's contracts.
+ * Pure geometry: rotation-aware AABBs, intentional layering (a card
+ * behind its text is NOT a collision), section-scale band blocking,
+ * free regions, hierarchy. Deterministic — no model in the loop.
+ */
+import { describe, expect, it } from 'vitest'
+import {
+ aabb,
+ elementBoxes,
+ intentionalOverlaps,
+ freeVerticalBands,
+ freeRegions2D,
+ hierarchyLines,
+ spatialCtx,
+ isIntentional,
+ overlapArea,
+} from './spatial'
+import type { AgentDesignCtx } from './context'
+
+const W = 1080
+const H = 1080
+const d = (elements: unknown[]): AgentDesignCtx =>
+ ({ name: 'S', width: W, height: H, elements }) as never as AgentDesignCtx
+
+describe('spatial · rotation-aware AABB', () => {
+ it('an unrotated box is unchanged', () => {
+ expect(aabb(10, 20, 100, 50)).toEqual({ x: 10, y: 20, w: 100, h: 50 })
+ })
+ it('a 90° rotation swaps the extents around the center', () => {
+ // 200x100 rotated 90° about its center keeps the center and
+ // becomes 100x200
+ const b = aabb(0, 0, 200, 100, 90)
+ expect(Math.round(b.w)).toBe(100)
+ expect(Math.round(b.h)).toBe(200)
+ expect(Math.round(b.x + b.w / 2)).toBe(100) // center x preserved
+ expect(Math.round(b.y + b.h / 2)).toBe(50) // center y preserved
+ })
+ it('a 45° rotation expands to w·√2/… (max coverage)', () => {
+ const b = aabb(0, 0, 100, 100, 45)
+ expect(b.w).toBeCloseTo(100 * Math.SQRT2, 0)
+ expect(b.h).toBeCloseTo(100 * Math.SQRT2, 0)
+ })
+ it('elementBoxes expands a rotated element to its true footprint', () => {
+ const boxes = elementBoxes(d([{ id: 'r', type: 'rect', x: 100, y: 100, width: 300, height: 100, rotation: 90 }]))
+ expect(boxes).toHaveLength(1)
+ expect(Math.round(boxes[0].w)).toBe(100)
+ expect(Math.round(boxes[0].h)).toBe(300)
+ })
+})
+
+describe('spatial · intentional layering is NOT a defect', () => {
+ it('a card behind its text (≥80% contained) is intentional', () => {
+ const boxes = elementBoxes(d([
+ { id: 'card', type: 'rect', x: 100, y: 400, width: 400, height: 200 },
+ { id: 'label', type: 'text', x: 120, y: 440, width: 360, height: 60, text: 'Feature one' },
+ ]))
+ const pairs = intentionalOverlaps(boxes, W, H)
+ expect(pairs).toHaveLength(1)
+ expect(pairs[0]).toMatchObject({ back: { id: 'card' }, front: { id: 'label' }, kind: 'backing-card' })
+ expect(isIntentional(pairs, 'card', 'label')).toBe(true)
+ })
+ it('a near-page-size backdrop behind anything is intentional', () => {
+ const boxes = elementBoxes(d([
+ { id: 'bg', type: 'rect', x: 0, y: 0, width: 1080, height: 1080 },
+ { id: 'hero', type: 'text', x: 200, y: 100, width: 680, height: 200, text: 'Hero' },
+ ]))
+ expect(intentionalOverlaps(boxes, W, H)[0]).toMatchObject({ kind: 'backdrop' })
+ })
+ it('two same-layer elements side by side are NOT intentional (genuine collision stays a finding)', () => {
+ const boxes = elementBoxes(d([
+ { id: 'a', type: 'text', x: 100, y: 100, width: 500, height: 120, text: 'Headline' },
+ { id: 'b', type: 'rect', x: 300, y: 140, width: 500, height: 200 },
+ ]))
+ // 55% contained at most — not a container; overlap exists but is genuine
+ expect(overlapArea(boxes[0], boxes[1])).toBeGreaterThan(0)
+ expect(isIntentional(intentionalOverlaps(boxes, W, H), 'a', 'b')).toBe(false)
+ })
+})
+
+describe('spatial · vertical bands + partials (the plan solver feed)', () => {
+ it('only section-scale elements (≥40% page width) block bands', () => {
+ const { occupied, partials } = freeVerticalBands(d([
+ { id: 'wide', type: 'text', x: 140, y: 65, width: 800, height: 200, text: 'Headline' },
+ { id: 'tiny', type: 'icon', x: 460, y: 500, width: 160, height: 120 },
+ ]))
+ expect(occupied).toEqual([{ y: 65, h: 200, label: 'Headline' }])
+ expect(partials.join(' ')).toContain('160x120 icon')
+ })
+ it('close blocking elements merge into one band (<40px gap)', () => {
+ const { occupied } = freeVerticalBands(d([
+ { id: 'a', type: 'rect', x: 0, y: 65, width: 900, height: 200 },
+ { id: 'b', type: 'rect', x: 0, y: 300, width: 900, height: 100 },
+ ]))
+ expect(occupied).toEqual([{ y: 65, h: 335 }])
+ })
+ it('spatialCtx carries occupied + partials + freeRegions for ToolContext', () => {
+ const ctx = spatialCtx(d([{ id: 'a', type: 'rect', x: 0, y: 65, width: 1080, height: 300 }]))
+ expect(ctx.occupied).toHaveLength(1)
+ expect(ctx.freeRegions.length).toBeGreaterThanOrEqual(1)
+ expect(ctx.freeRegions[0].y).toBeGreaterThanOrEqual(365)
+ })
+})
+
+describe('spatial · 2D free regions', () => {
+ it('finds the free right half when the left half is occupied', () => {
+ const regions = freeRegions2D(d([{ id: 'panel', type: 'rect', x: 0, y: 65, width: 500, height: 950 }]))
+ expect(regions[0].x).toBeGreaterThanOrEqual(500)
+ expect(regions[0].w).toBeGreaterThan(400)
+ })
+ it('an empty canvas yields the full safe area as the largest region', () => {
+ const regions = freeRegions2D(d([]))
+ expect(regions[0]).toMatchObject({ x: 65, y: 65, w: 950, h: 950 })
+ })
+})
+
+describe('spatial · visual hierarchy', () => {
+ it('reports the descending size ladder', () => {
+ const lines = hierarchyLines(d([
+ { id: 'h', type: 'text', x: 0, y: 65, width: 800, height: 140, fontSize: 96, text: 'Big headline' },
+ { id: 's', type: 'text', x: 0, y: 300, width: 600, height: 40, fontSize: 30, text: 'Subline' },
+ ]))
+ expect(lines[0]).toContain('96px "Big headline" → 30px "Subline"')
+ expect(lines).toHaveLength(1) // no flat-hierarchy advisory (96 ≫ 30)
+ })
+ it('flags a flat hierarchy as advisory', () => {
+ const lines = hierarchyLines(d([
+ { id: 'h', type: 'text', x: 0, y: 65, width: 800, height: 80, fontSize: 34, text: 'Meh headline' },
+ { id: 'b1', type: 'text', x: 0, y: 200, width: 600, height: 40, fontSize: 32, text: 'body one' },
+ { id: 'b2', type: 'text', x: 0, y: 300, width: 600, height: 40, fontSize: 30, text: 'body two' },
+ ]))
+ expect(lines.some((l) => l.startsWith('ADVISORY: flat hierarchy'))).toBe(true)
+ })
+})
diff --git a/src/lib/agent/spatial.ts b/src/lib/agent/spatial.ts
new file mode 100644
index 0000000..0e801b5
--- /dev/null
+++ b/src/lib/agent/spatial.ts
@@ -0,0 +1,295 @@
+/**
+ * v0.32.7 · TRUE 2D SPATIAL INTELLIGENCE — the canvas map, grown up.
+ *
+ * v0.32.6 mapped the canvas as vertical bands only. Real designs are
+ * 2D: elements have x-extent, rotation, z-order and INTENT (a card
+ * behind its text is layering, not a collision). This module turns
+ * the agent's design context into a real spatial model — pure,
+ * deterministic, no model arithmetic:
+ *
+ * · elementBox() AABB incl. rotation (rect rotated about its
+ * center → axis-aligned bounds)
+ * · intentionalOverlaps() containers, backgrounds, backing
+ * cards — layering that is CORRECT, not a defect
+ * · freeVerticalBands() what the plan solver eats: y-ranges
+ * blocked by section-scale elements (≥40% page
+ * width), with partial-occupancy disclosures
+ * · freeRegions2D() the largest free rectangles (where new
+ * content can actually go)
+ * · hierarchyLines() the text scale ordering (headline → body)
+ *
+ * Everything is derived from AgentDesignCtx — the client's own
+ * numbers, never a guess.
+ */
+
+import type { AgentDesignCtx, AgentElementCtx } from './context'
+
+/** ── boxes ──────────────────────────────────────────────────── */
+
+export interface SpatialBox {
+ id: string
+ type: string
+ /** axis-aligned bounds (rotation-expanded) */
+ x: number
+ y: number
+ w: number
+ h: number
+ /** 0 = bottom … n = top (element list order IS z-order) */
+ z: number
+ label?: string
+ /** the element's own (unrotated) width in px */
+ ownW: number
+ fontSize?: number
+ fill?: string
+}
+
+/** AABB of a possibly-rotated rect: rotate about the center, then
+ * take the axis-aligned covering box (w·|cosθ| + h·|sinθ| etc.). */
+export function aabb(x: number, y: number, w: number, h: number, rotationDeg?: number): { x: number; y: number; w: number; h: number } {
+ if (!rotationDeg || Math.abs(rotationDeg) < 0.5) return { x, y, w, h }
+ const t = (Math.abs(rotationDeg) * Math.PI) / 180
+ const c = Math.abs(Math.cos(t))
+ const s = Math.abs(Math.sin(t))
+ const bw = w * c + h * s
+ const bh = w * s + h * c
+ return { x: x + (w - bw) / 2, y: y + (h - bh) / 2, w: bw, h: bh }
+}
+
+/** The design's elements as z-ordered spatial boxes (skipping the
+ * geometry-less). `partial` marks small elements that do not block
+ * a full-width section band. */
+export function elementBoxes(d: AgentDesignCtx): SpatialBox[] {
+ return (d.elements ?? [])
+ .map((e, z) => boxOf(e, z))
+ .filter((b): b is SpatialBox => b !== null)
+}
+
+function boxOf(e: AgentElementCtx, z: number): SpatialBox | null {
+ if (typeof e.x !== 'number' || typeof e.y !== 'number') return null
+ const w = typeof e.width === 'number' ? e.width : typeof e.fontSize === 'number' ? e.fontSize * 6 : 0
+ const h = typeof e.height === 'number' ? e.height : typeof e.fontSize === 'number' ? e.fontSize * 1.3 : 0
+ if (w <= 0 || h <= 0) return null
+ const rot = typeof (e as { rotation?: unknown }).rotation === 'number' ? (e as { rotation: number }).rotation : undefined
+ const b = aabb(e.x, e.y, w, h, rot)
+ return {
+ id: e.id,
+ type: e.type,
+ x: b.x,
+ y: b.y,
+ w: b.w,
+ h: b.h,
+ z,
+ label: typeof e.text === 'string' && e.text.trim() ? e.text.trim().slice(0, 24) : e.name?.slice(0, 24),
+ ownW: w,
+ fontSize: typeof e.fontSize === 'number' ? e.fontSize : undefined,
+ fill: e.fill,
+ }
+}
+
+/** ── intentional overlaps ───────────────────────────────────── */
+
+export interface IntentionalPair {
+ /** the behind element (container/backdrop) */
+ back: SpatialBox
+ /** the in-front element (the contained content) */
+ front: SpatialBox
+ kind: 'container' | 'backdrop' | 'backing-card'
+}
+
+function contains(outer: SpatialBox, inner: SpatialBox, frac = 0.8): boolean {
+ const ix = Math.max(0, Math.min(outer.x + outer.w, inner.x + inner.w) - Math.max(outer.x, inner.x))
+ const iy = Math.max(0, Math.min(outer.y + outer.h, inner.y + inner.h) - Math.max(outer.y, inner.y))
+ const innerArea = inner.w * inner.h
+ return innerArea > 0 && (ix * iy) / innerArea >= frac
+}
+
+export function overlapArea(a: SpatialBox, b: SpatialBox): number {
+ const ix = Math.max(0, Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x))
+ const iy = Math.max(0, Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y))
+ return ix * iy
+}
+
+/**
+ * Pairs whose overlap is CORRECT design layering — never a finding:
+ * · container: front sits ≥80% inside a LARGER non-text element
+ * that is behind it (cards, frames, mockup bodies)
+ * · backdrop: a near-page-size element behind everything
+ * (≥75% of the canvas area, low z)
+ * · backing-card: a text ≥70% on a plain shape behind it
+ */
+export function intentionalOverlaps(boxes: SpatialBox[], pageW: number, pageH: number): IntentionalPair[] {
+ const out: IntentionalPair[] = []
+ for (let i = 0; i < boxes.length; i++) {
+ for (let j = i + 1; j < boxes.length; j++) {
+ const a = boxes[i] // earlier in list = BEHIND
+ const b = boxes[j] // later = IN FRONT
+ if (overlapArea(a, b) <= 0) continue
+ // backdrop: behind covers most of the page
+ if (a.w * a.h >= 0.75 * pageW * pageH && a.z <= 3) {
+ out.push({ back: a, front: b, kind: 'backdrop' })
+ continue
+ }
+ // container: front ≥80% inside a larger non-text behind element
+ const backIsSurface = a.type !== 'text' && a.w * a.h > b.w * b.h * 1.1
+ if (backIsSurface && contains(a, b, 0.8)) {
+ out.push({ back: a, front: b, kind: b.type === 'text' ? 'backing-card' : 'container' })
+ }
+ }
+ }
+ return out
+}
+
+/** Is this (behind, front) pair an intentional overlap? */
+export function isIntentional(pairs: IntentionalPair[], backId: string, frontId: string): boolean {
+ return pairs.some((p) => (p.back.id === backId && p.front.id === frontId) || (p.back.id === frontId && p.front.id === backId))
+}
+
+/** ── vertical bands for the plan solver ─────────────────────── */
+
+export interface OccupiedBand {
+ y: number
+ h: number
+ label?: string
+}
+
+/**
+ * Y-ranges genuinely blocked for full-width section planning: only
+ * elements at section scale (own width ≥ 40% of the page width and
+ * ≥24px tall) block a band. Smaller elements become `partials` —
+ * disclosed in the map so the model plans AROUND them horizontally
+ * inside its band.
+ */
+export function freeVerticalBands(
+ d: AgentDesignCtx,
+): { occupied: OccupiedBand[]; partials: string[]; pageHeight: number } {
+ const pageW = d.width ?? 1080
+ const pageH = d.height ?? 1080
+ const boxes = elementBoxes(d)
+ const sectionScale = (b: SpatialBox) => b.ownW >= 0.4 * pageW && b.h >= 24
+ const blocking = boxes.filter(sectionScale)
+ const partial = boxes.filter((b) => !sectionScale(b))
+
+ // merge blocking extents into disjoint bands (a <40px gap cannot
+ // host a new section, so close gaps merge — same rule as the
+ // plan solver's minGap)
+ const bands: OccupiedBand[] = []
+ for (const b of [...blocking].sort((p, q) => p.y - q.y)) {
+ const last = bands[bands.length - 1]
+ if (last && b.y - (last.y + last.h) < 40) {
+ const end = Math.max(last.y + last.h, b.y + b.h)
+ last.h = end - last.y
+ if (!last.label && b.label) last.label = b.label
+ } else {
+ bands.push({ y: Math.max(0, Math.round(b.y)), h: Math.round(b.h), label: b.label })
+ }
+ }
+ const partials = partial
+ .slice(0, 8)
+ .sort((p, q) => q.w * q.h - p.w * p.h)
+ .map((p) => `${Math.round(p.ownW)}x${Math.round(p.h)} ${p.type}${p.label ? ` "${p.label}"` : ''} at (${Math.round(p.x)},${Math.round(p.y)})`)
+ return { occupied: bands, partials, pageHeight: pageH }
+}
+
+/** ── 2D free regions ───────────────────────────────────────── */
+
+export interface FreeRegion {
+ x: number
+ y: number
+ w: number
+ h: number
+}
+
+/**
+ * The largest free rectangles in the safe area (6% margins): for
+ * each horizontal slab bounded by element y-edges, the free x-spans
+ * of that slab. Bounded, deterministic, no model arithmetic.
+ */
+export function freeRegions2D(d: AgentDesignCtx, limit = 8): FreeRegion[] {
+ const pageW = d.width ?? 1080
+ const pageH = d.height ?? 1080
+ const top = Math.round(pageH * 0.06)
+ const bottom = Math.round(pageH * 0.94)
+ const left = Math.round(pageW * 0.06)
+ const right = Math.round(pageW * 0.94)
+ const boxes = elementBoxes(d)
+ .map((b) => ({ x0: Math.max(left, b.x), y0: Math.max(top, b.y), x1: Math.min(right, b.x + b.w), y1: Math.min(bottom, b.y + b.h) }))
+ .filter((b) => b.x1 > b.x0 && b.y1 > b.y0)
+
+ const ys = [...new Set([top, bottom, ...boxes.flatMap((b) => [b.y0, b.y1])])].filter((y) => y >= top && y <= bottom).sort((a, b) => a - b)
+ const regions: FreeRegion[] = []
+ for (let i = 0; i < ys.length - 1; i++) {
+ const y0 = ys[i]
+ const y1 = ys[i + 1]
+ if (y1 - y0 < 40) continue
+ // boxes crossing this slab horizontally
+ const spans = boxes.filter((b) => b.y0 < y1 && b.y1 > y0).map((b) => [b.x0, b.x1] as const).sort((a, b) => a[0] - b[0])
+ // free x-spans between the covered spans
+ let cursor = left
+ const freeSpans: [number, number][] = []
+ for (const [x0, x1] of spans) {
+ if (x0 > cursor) freeSpans.push([cursor, x0])
+ cursor = Math.max(cursor, x1)
+ }
+ if (right > cursor) freeSpans.push([cursor, right])
+ for (const [fx0, fx1] of freeSpans) {
+ if (fx1 - fx0 >= 80) regions.push({ x: Math.round(fx0), y: Math.round(y0), w: Math.round(fx1 - fx0), h: Math.round(y1 - y0) })
+ }
+ }
+ // collapse vertically-adjacent same-x regions (keep it simple:
+ // sort by area, return the largest)
+ return regions.sort((a, b) => b.w * b.h - a.w * a.h).slice(0, limit)
+}
+
+/** ── visual hierarchy ───────────────────────────────────────── */
+
+/**
+ * The text scale ordering — what the eye reads first. Returns the
+ * descending font-size ladder plus an advisory when the hierarchy is
+ * flat (largest text < 1.3× the body median).
+ */
+export function hierarchyLines(d: AgentDesignCtx): string[] {
+ const texts = (d.elements ?? []).filter((e): e is AgentElementCtx & { fontSize: number; text: string } => typeof e.fontSize === 'number' && e.fontSize > 0 && typeof e.text === 'string' && e.text.trim().length > 0)
+ if (texts.length < 2) return []
+ const sorted = [...texts].sort((a, b) => b.fontSize - a.fontSize)
+ const ladder = sorted.slice(0, 5).map((t) => `${Math.round(t.fontSize)}px "${t.text.trim().slice(0, 20)}"`)
+ const lines = [`Text hierarchy (descending): ${ladder.join(' → ')}`]
+ const body = sorted.slice(1)
+ const median = body.length ? body[Math.floor(body.length / 2)].fontSize : 0
+ if (median > 0 && sorted[0].fontSize < 1.3 * median) {
+ lines.push(`ADVISORY: flat hierarchy — the largest text (${Math.round(sorted[0].fontSize)}px) is under 1.3× the body median (${Math.round(median)}px); make the headline clearly bigger`)
+ }
+ return lines
+}
+
+/** ── the full map ───────────────────────────────────────────── */
+
+export interface SpatialMap {
+ boxes: SpatialBox[]
+ intentional: IntentionalPair[]
+ occupied: OccupiedBand[]
+ partials: string[]
+ freeRegions: FreeRegion[]
+ hierarchy: string[]
+}
+
+export function spatialMap(d: AgentDesignCtx): SpatialMap {
+ const pageW = d.width ?? 1080
+ const pageH = d.height ?? 1080
+ const boxes = elementBoxes(d)
+ const bands = freeVerticalBands(d)
+ return {
+ boxes,
+ intentional: intentionalOverlaps(boxes, pageW, pageH),
+ occupied: bands.occupied,
+ partials: bands.partials,
+ freeRegions: freeRegions2D(d),
+ hierarchy: hierarchyLines(d),
+ }
+}
+
+/** The ToolContext's spatial slice (v0.32.7): occupied bands,
+ * partials and free regions, structurally typed for ToolContext. */
+export function spatialCtx(d: AgentDesignCtx): { occupied: { y: number; h: number; label?: string }[]; partials: string[]; freeRegions: { x: number; y: number; w: number; h: number }[] } {
+ const bands = freeVerticalBands(d)
+ return { occupied: bands.occupied, partials: bands.partials, freeRegions: freeRegions2D(d, 6) }
+}
diff --git a/src/lib/agent/tools.ts b/src/lib/agent/tools.ts
index 276fd87..bfda5bb 100644
--- a/src/lib/agent/tools.ts
+++ b/src/lib/agent/tools.ts
@@ -46,8 +46,12 @@ export interface ToolContext {
/** v0.32.6 · the CANVAS MAP: existing elements' occupied vertical
* bands (merged, disjoint — see plan-repair.ts). The plan solver
* fits new sections into the FREE space between them so nothing
- * is planned on top of existing content. */
+ * is planned on top of existing content.
+ * v0.32.7: partials (small elements to plan around horizontally)
+ * and freeRegions (the largest 2D free rectangles) join the map. */
occupied?: { y: number; h: number; label?: string }[]
+ partials?: string[]
+ freeRegions?: { x: number; y: number; w: number; h: number }[]
}
export type SanitizeResult =
@@ -245,15 +249,23 @@ export const AGENT_TOOLS: AgentTool[] = [
if (notes) lines.push(`notes: ${notes}`)
// the canvas map disclosure: what is already on the page and
- // where the free space is — visible to the user AND the model
+ // where the free space is — visible to the user AND the model.
+ // v0.32.7: TRUE 2D — occupied bands (section-scale elements),
+ // the small elements to plan around horizontally, and the
+ // largest free regions.
const occupied = ctx.occupied ?? []
- const mapNote = occupied.length
- ? `CANVAS MAP — existing elements occupy y ${occupied.map((o) => `${Math.round(o.y)}–${Math.round(o.y + o.h)}${o.label ? ` (${o.label})` : ''}`).join(', ')}; your sections were fitted into the FREE space (never on top of them).`
- : ''
+ let mapNote = ''
+ if (occupied.length || ctx.partials?.length || ctx.freeRegions?.length) {
+ const mapLines: string[] = []
+ if (occupied.length) mapLines.push(`occupied bands: ${occupied.map((o) => `y ${Math.round(o.y)}–${Math.round(o.y + o.h)}${o.label ? ` (${o.label})` : ''}`).join(', ')}`)
+ if (ctx.partials?.length) mapLines.push(`small elements to plan around horizontally: ${ctx.partials.slice(0, 4).join('; ')}`)
+ if (ctx.freeRegions?.length) mapLines.push(`largest free regions: ${ctx.freeRegions.slice(0, 4).map((r) => `(${r.x},${r.y}) ${r.w}×${r.h}`).join(' | ')}`)
+ mapNote = `CANVAS MAP (2D) — ${mapLines.join('\n')}\nYour sections were fitted into the FREE vertical space (never on top of existing content); inside each band, place content around the small elements listed. `
+ }
const repairedNote = repair.repairs.length
? `PLAN AUTO-REPAIRED (your heights, order and contents were kept; the SERVER computed valid positions): ${repair.repairs.join('; ')}. Build inside these exact bands — do not recompute them.`
: 'Bands verified: non-overlapping, ≥40px gaps, inside the safe area. Build inside these exact bands.'
- const observation = `${mapNote ? `${mapNote}\n` : ''}PLAN RECORDED (${lines.length} lines):\n${lines.join('\n')}\n${repairedNote}`
+ const observation = `${mapNote}PLAN RECORDED (${lines.length} lines):\n${lines.join('\n')}\n${repairedNote}`
return {
ok: true,
actions: [{ type: '__planLayout', lines, bands: repair.bands }],
diff --git a/src/lib/ai/chat-resilience.test.ts b/src/lib/ai/chat-resilience.test.ts
new file mode 100644
index 0000000..c8785e0
--- /dev/null
+++ b/src/lib/ai/chat-resilience.test.ts
@@ -0,0 +1,149 @@
+/**
+ * v0.32.7 · PROVIDER RESILIENCE — retry, circuit breaker, fallback.
+ * The 26 Nov 2026 production incident as tests: 502 → fetch failed →
+ * 429 must never kill a run when a configured provider can answer.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { chatWithRetry, chatResilient, circuitBreaker, isTransientError } from './chat-resilience'
+
+const noSleep = () => Promise.resolve()
+
+describe('chat-resilience · transient classification', () => {
+ it('429 / 5xx / network / timeouts are transient', () => {
+ for (const msg of [
+ 'API request failed with status 502: Bad Gateway',
+ 'fetch failed',
+ 'API request failed with status 429: Too Many Requests',
+ 'status 503: service unavailable',
+ 'gateway timeout',
+ 'network error: ECONNRESET',
+ ]) {
+ expect(isTransientError(new Error(msg))).toBe(true)
+ }
+ })
+ it('auth / bad-request / unsupported-param errors are PERMANENT (fail fast)', () => {
+ for (const msg of [
+ 'invalid api key',
+ 'status 401: unauthorized',
+ 'status 404: model not found',
+ 'response_format is not supported',
+ 'unknown field: thinking',
+ ]) {
+ expect(isTransientError(new Error(msg))).toBe(false)
+ }
+ })
+})
+
+describe('chat-resilience · chatWithRetry (bounded exponential backoff)', () => {
+ it('retries transient failures and succeeds', async () => {
+ let calls = 0
+ const out = await chatWithRetry(
+ async () => {
+ calls += 1
+ if (calls < 3) throw new Error('fetch failed')
+ return 'ok'
+ },
+ { attempts: 3, sleep: noSleep },
+ )
+ expect(out).toBe('ok')
+ expect(calls).toBe(3)
+ })
+ it('PERMANENT errors fail fast — no retry, no wasted spend', async () => {
+ const fn = vi.fn(async () => {
+ throw new Error('status 401: invalid api key')
+ })
+ await expect(chatWithRetry(fn, { attempts: 3, sleep: noSleep })).rejects.toThrow('401')
+ expect(fn).toHaveBeenCalledTimes(1)
+ })
+ it('gives up after the bounded attempts and rethrows the last error', async () => {
+ let calls = 0
+ const delays: number[] = []
+ await expect(
+ chatWithRetry(
+ async () => {
+ calls += 1
+ throw new Error('status 502: bad gateway')
+ },
+ { attempts: 3, baseDelayMs: 10, maxDelayMs: 20, sleep: async (ms) => { delays.push(ms) } },
+ ),
+ ).rejects.toThrow('502')
+ expect(calls).toBe(3)
+ expect(delays).toHaveLength(2) // 3 attempts → 2 waits between them
+ })
+})
+
+describe('chat-resilience · circuit breaker', () => {
+ afterEach(() => circuitBreaker.reset())
+ it('opens after the consecutive-failure threshold and recovers after the cooldown', () => {
+ const key = 'test:provider'
+ for (let i = 0; i < 5; i++) circuitBreaker.recordFailure(key)
+ expect(circuitBreaker.canPass(key)).toBe(false)
+ // after the cooldown the key is half-open again
+ expect(circuitBreaker.canPass(key, Date.now() + 31_000)).toBe(true)
+ circuitBreaker.recordSuccess(key)
+ expect(circuitBreaker.canPass(key)).toBe(true)
+ })
+})
+
+describe('chat-resilience · chatResilient (the configured fallback chain)', () => {
+ afterEach(() => circuitBreaker.reset())
+ it('fails over to the next CONFIGURED provider on transient failure', async () => {
+ const out = await chatResilient(
+ [
+ { key: 'primary', fn: async () => { throw new Error('fetch failed') } },
+ { key: 'backup', fn: async () => 'backup answer' },
+ ],
+ { attempts: 2, sleep: noSleep },
+ )
+ expect(out).toBe('backup answer')
+ })
+ it('PERMANENT primary errors do NOT fail over (report immediately)', async () => {
+ const backup = vi.fn(async () => 'backup')
+ await expect(
+ chatResilient(
+ [
+ { key: 'primary', fn: async () => { throw new Error('status 401: invalid api key') } },
+ { key: 'backup', fn: backup },
+ ],
+ { attempts: 2, sleep: noSleep },
+ ),
+ ).rejects.toThrow('401')
+ expect(backup).not.toHaveBeenCalled()
+ })
+ it('an OPEN circuit skips straight to the fallback (the dead gateway is not retried)', async () => {
+ const key = 'flapping:gateway'
+ for (let i = 0; i < 5; i++) circuitBreaker.recordFailure(key)
+ const dead = vi.fn(async () => 'should not run')
+ const out = await chatResilient(
+ [
+ { key, fn: dead },
+ { key: 'healthy', fn: async () => 'healthy answer' },
+ ],
+ { attempts: 1, sleep: noSleep },
+ )
+ expect(out).toBe('healthy answer')
+ expect(dead).not.toHaveBeenCalled()
+ })
+ it('noFallback=1 keeps the failure on the primary (spend control)', async () => {
+ await expect(
+ chatResilient(
+ [
+ { key: 'primary', fn: async () => { throw new Error('fetch failed') } },
+ { key: 'backup', fn: async () => 'backup' },
+ ],
+ { attempts: 1, noFallback: true, sleep: noSleep },
+ ),
+ ).rejects.toThrow('fetch failed')
+ })
+ it('all providers failing rethrows the last transient error', async () => {
+ await expect(
+ chatResilient(
+ [
+ { key: 'a', fn: async () => { throw new Error('status 502') } },
+ { key: 'b', fn: async () => { throw new Error('fetch failed') } },
+ ],
+ { attempts: 1, sleep: noSleep },
+ ),
+ ).rejects.toThrow('fetch failed')
+ })
+})
diff --git a/src/lib/ai/chat-resilience.ts b/src/lib/ai/chat-resilience.ts
new file mode 100644
index 0000000..b0035e3
--- /dev/null
+++ b/src/lib/ai/chat-resilience.ts
@@ -0,0 +1,198 @@
+/**
+ * v0.32.7 · PROVIDER RESILIENCE — bounded retries, circuit breaker,
+ * configured fallback.
+ *
+ * The production incident (26 Nov 2026): the upstream gateway
+ * flapped 502 → "fetch failed" → 429 for two hours. Every run that
+ * hit a transient failure DIED mid-flight and the user retyped into
+ * the same broken gateway. withProvider has NO retry (one-shot 502
+ * → PROVIDER error); the run loop had no idea the failure was
+ * transient.
+ *
+ * Three layers, in order:
+ *
+ * 1. chatWithRetry — bounded exponential backoff for TRANSIENT
+ * failures only (429/5xx/network/timeout). Permanent errors
+ * (400/401/403/404/422 — bad request, bad key, bad model) fail
+ * fast: retrying them wastes the user's time and money.
+ * Retry-After is respected, capped.
+ *
+ * 2. circuitBreaker — per provider-key consecutive-failure count;
+ * after `threshold` consecutive transient failures the key is
+ * OPEN for `cooldownMs` (skip straight to fallback instead of
+ * burning the same dead gateway). Half-open after cooldown.
+ *
+ * 3. fallback chain — OTHER providers already configured for the
+ * slot (the user's other BYOK providers, then the instance
+ * table's other providers). Nothing is invented: only providers
+ * an admin or the user explicitly configured are ever used,
+ * each request still passes the feature rate limit, and every
+ * attempt is recorded by the existing AIUsage accounting. A
+ * BYOK primary falling back to the instance provider is the
+ * documented behavior (BYOK "must never break the fallback
+ * chain" — provider.ts). ZAI_NO_FALLBACK=1 disables the chain
+ * entirely (spend control).
+ */
+
+/** Is this error transient (worth retrying / falling back)? */
+export function isTransientError(err: unknown): boolean {
+ const msg = String((err as Error | undefined)?.message ?? err ?? '')
+ if (/\b(?:400|401|403|404|422)\b|invalid api key|unauthorized|forbidden|not found|model .* (not found|does not exist)|response_format|unknown field|not supported|unsupported/i.test(msg)) {
+ // json-mode negotiation and auth/model config errors are
+ // PERMANENT — the caller handles json-mode itself; keys and
+ // model names do not heal with retries
+ return false
+ }
+ if (/\b(?:429|500|502|503|504)\b|rate.?limit|too many requests|upstream|bad gateway|service unavailable|gateway timeout|timeout|timed out|econnreset|econnrefused|enotfound|eai_again|socket|network|fetch failed|terminated|aborted/i.test(msg)) {
+ return true
+ }
+ return false
+}
+
+export interface RetryOpts {
+ /** total attempts including the first (default 3) */
+ attempts?: number
+ /** first backoff delay (default 400ms) */
+ baseDelayMs?: number
+ /** backoff cap (default 4000ms) */
+ maxDelayMs?: number
+ /** 429-specific ladder (default 8s base, 45s cap) — rate limits
+ * say "try again later" and mean it */
+ rateLimitBaseDelayMs?: number
+ rateLimitMaxDelayMs?: number
+ /** diagnostic hook (telemetry/tests); called before each retry */
+ onRetry?: (attempt: number, err: unknown, delayMs: number) => void
+ /** injectable sleep (tests) */
+ sleep?: (ms: number) => Promise<void>
+}
+
+const sleepDefault = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))
+
+/**
+ * Run `fn` with bounded exponential backoff for transient errors.
+ * Permanent errors and the final attempt's error are re-thrown
+ * unchanged.
+ */
+export async function chatWithRetry<T>(fn: () => Promise<T>, opts: RetryOpts = {}): Promise<T> {
+ const attempts = Math.max(1, opts.attempts ?? 3)
+ const base = opts.baseDelayMs ?? 400
+ const cap = opts.maxDelayMs ?? 4000
+ const sleep = opts.sleep ?? sleepDefault
+ let lastErr: unknown
+ for (let attempt = 1; attempt <= attempts; attempt++) {
+ try {
+ const out = await fn()
+ return out
+ } catch (err) {
+ lastErr = err
+ if (attempt === attempts || !isTransientError(err)) throw err
+ // RATE LIMITS get a longer ladder than generic 5xx blips: a
+ // gateway answering 429 "try again later" needs tens of
+ // seconds, not a 400ms jitter — retrying fast only burns
+ // budget against a closed door.
+ const msg = String((err as Error | undefined)?.message ?? err ?? '')
+ const rateLimited = /\b429\b|rate.?limit|too many requests/i.test(msg)
+ const rlBase = opts.rateLimitBaseDelayMs ?? 8_000
+ const rlCap = opts.rateLimitMaxDelayMs ?? 45_000
+ const exp = rateLimited
+ ? Math.min(rlCap, rlBase * 2 ** (attempt - 1))
+ : Math.min(cap, base * 2 ** (attempt - 1))
+ const delay = Math.round(exp / 2 + Math.random() * (exp / 2))
+ opts.onRetry?.(attempt, err, delay)
+ await sleep(delay)
+ }
+ }
+ throw lastErr
+}
+
+/** ── circuit breaker ────────────────────────────────────────── */
+
+interface BreakerState {
+ consecutiveFailures: number
+ openedAt: number | null
+}
+
+const breakers = new Map<string, BreakerState>()
+export const BREAKER_THRESHOLD = 5
+export const BREAKER_COOLDOWN_MS = 30_000
+
+/**
+ * In-memory, per-server-instance breaker keyed by provider label.
+ * OPEN → callers skip straight to the fallback chain; HALF-OPEN
+ * after the cooldown lets the primary prove itself again.
+ */
+export const circuitBreaker = {
+ canPass(key: string, now = Date.now()): boolean {
+ const s = breakers.get(key)
+ if (!s || s.openedAt === null) return true
+ return now - s.openedAt >= BREAKER_COOLDOWN_MS
+ },
+ recordSuccess(key: string): void {
+ breakers.set(key, { consecutiveFailures: 0, openedAt: null })
+ },
+ recordFailure(key: string, now = Date.now()): void {
+ const s = breakers.get(key) ?? { consecutiveFailures: 0, openedAt: null }
+ s.consecutiveFailures += 1
+ if (s.consecutiveFailures >= BREAKER_THRESHOLD) s.openedAt = now
+ breakers.set(key, s)
+ },
+ /** test hook */
+ reset(): void {
+ breakers.clear()
+ },
+}
+
+/** ── the resilient call: primary (retry) → fallbacks (once each) ── */
+
+export interface ResilientCallTarget<T> {
+ /** a stable key for the circuit breaker (provider label) */
+ key: string
+ /** one attempt of the call (the caller composes model + params) */
+ fn: () => Promise<T>
+ /** diagnostic hook when this target is skipped or fails over */
+ onFailover?: (info: string) => void
+}
+
+export interface ResilientCallOpts extends RetryOpts {
+ /** disable the fallback chain entirely (default: enabled) */
+ noFallback?: boolean
+ now?: () => number
+}
+
+/**
+ * Try each target in order: the first with a closed breaker gets the
+ * full bounded-retry treatment; still-failing transient errors fail
+ * over to the NEXT configured target (one retry round each).
+ * Non-transient errors skip the fallbacks — a permanent error on
+ * the primary is reported to the user immediately (falling back
+ * would only duplicate the same mistake elsewhere).
+ */
+export async function chatResilient<T>(
+ targets: ResilientCallTarget<T>[],
+ opts: ResilientCallOpts = {},
+): Promise<T> {
+ if (!targets.length) throw new Error('No AI provider configured for this slot.')
+ const now = opts.now ?? Date.now
+ const useFallback = !opts.noFallback && process.env.ZAI_NO_FALLBACK !== '1'
+ let lastErr: unknown
+ for (let i = 0; i < targets.length; i++) {
+ const t = targets[i]
+ if (i > 0 && !useFallback) break
+ if (i > 0 && opts.onRetry) opts.onRetry(i, lastErr, 0) // failover trace
+ if (!circuitBreaker.canPass(t.key, now())) {
+ t.onFailover?.(`circuit open for ${t.key} — skipping to the next configured provider`)
+ continue
+ }
+ try {
+ const out = await chatWithRetry(t.fn, opts)
+ circuitBreaker.recordSuccess(t.key)
+ return out
+ } catch (err) {
+ lastErr = err
+ if (!isTransientError(err)) throw err
+ circuitBreaker.recordFailure(t.key, now())
+ t.onFailover?.(`${t.key} failed transiently after retries: ${String((err as Error)?.message ?? err).slice(0, 120)}`)
+ }
+ }
+ throw lastErr ?? new Error('All configured AI providers failed.')
+}
diff --git a/tests/e2e/agent-recovery.spec.ts b/tests/e2e/agent-recovery.spec.ts
new file mode 100644
index 0000000..6a37423
--- /dev/null
+++ b/tests/e2e/agent-recovery.spec.ts
@@ -0,0 +1,185 @@
+import { test, expect, type Page } from '@playwright/test'
+
+// v0.32.7 · PERSISTENT EXECUTION + RECOVERY, end to end in the real
+// editor. The 26 Nov 2026 production incident: a mid-flight provider
+// 502 killed a run with 19 actions applied; the user had no grounded
+// way to continue without duplicating work.
+//
+// The agent route is MOCKED to scripted SSE streams (the server-side
+// persistence + recovery-prompt injection is pinned by
+// src/lib/agent/harness.test.ts — "recovery lines ride the system
+// prompt" — and the DesignAgentRun row lifecycle is verified live by
+// the benchmark in tests/benchmark/agent-benchmark.spec.ts). What
+// THIS spec proves at the BROWSER level:
+//
+// 1. an interrupted run's error arrives as ONE honest message with
+// the applied work KEPT on the canvas (autosaved);
+// 2. the follow-up (retry) message completes the design with the
+// SAME conversation and NEVER duplicates the applied elements;
+// 3. the retry's request body carries the conversation history
+// (the model knows what already happened).
+
+const V = 2
+const ev = (e: unknown) => `data: ${JSON.stringify(e)}\n\n`
+
+/** stream 1: the run dies MID-BUILD — one action applied, then the
+ * honest provider error (exactly what the loop emits on a 502). */
+function interruptedStream(): string {
+ return [
+ { v: V, type: 'start', runId: 'mock-recovery-1' },
+ { v: V, type: 'mode', mode: 'create', reason: 'classified as create' },
+ { v: V, type: 'intent', intent: 'create', reason: 'empty canvas' },
+ { v: V, type: 'brief', brief: { requiredTexts: [{ text: 'ARTISAN ROAST', tier: 'mandatory' }], requiredColors: [] } },
+ { v: V, type: 'step', index: 0, thought: 'bold headline', tool: 'add_text' },
+ {
+ v: V, type: 'action', stepIndex: 0, callId: 'c0', risk: 'write', tool: 'add_text',
+ actions: [{ type: 'addText', text: 'ARTISAN ROAST', y: 210, width: 1080, fontSize: 132, bold: true, color: '#FFFFFF', align: 'center' }],
+ },
+ { v: V, type: 'observation', stepIndex: 0, message: 'Headline added.' },
+ {
+ v: V, type: 'error', code: 'PROVIDER',
+ message: 'The AI provider failed: API request failed with status 502: Bad Gateway. Applied work is kept — retry to continue.',
+ },
+ ].map(ev).join('')
+}
+
+/** stream 2: the retry COMPLETES the design — grounded in the current
+ * canvas (get_page_state first), adding only what is missing. */
+function recoveryStream(): string {
+ return [
+ { v: V, type: 'start', runId: 'mock-recovery-2' },
+ { v: V, type: 'mode', mode: 'improve', reason: 'classified as improve' },
+ { v: V, type: 'intent', intent: 'refine', reason: 'fix language on an existing design' },
+ { v: V, type: 'step', index: 0, thought: 'the headline is already here — do not re-add', tool: 'get_page_state' },
+ { v: V, type: 'observation', stepIndex: 0, message: 'CANVAS MAP (2D) — occupied bands: y 210–342 (ARTISAN ROAST). Build the missing sections in the FREE space.' },
+ { v: V, type: 'step', index: 1, thought: 'offer line — free space', tool: 'add_text' },
+ {
+ v: V, type: 'action', stepIndex: 1, callId: 'c1', risk: 'write', tool: 'add_text',
+ actions: [{ type: 'addText', text: 'our coffee launch — first sip free', y: 500, width: 1080, fontSize: 46, color: '#E8D9FF', align: 'center' }],
+ },
+ { v: V, type: 'observation', stepIndex: 1, message: 'Offer line added.' },
+ { v: V, type: 'step', index: 2, thought: 'CTA card — free space', tool: 'add_shape' },
+ {
+ v: V, type: 'action', stepIndex: 2, callId: 'c2', risk: 'write', tool: 'add_shape',
+ actions: [{ type: 'addShape', shape: 'rect', x: 140, y: 900, width: 800, height: 320, fill: '#2E1A47' }],
+ },
+ { v: V, type: 'observation', stepIndex: 2, message: 'CTA card added.' },
+ { v: V, type: 'step', index: 3, thought: 'CTA text', tool: 'add_text' },
+ {
+ v: V, type: 'action', stepIndex: 3, callId: 'c3', risk: 'write', tool: 'add_text',
+ actions: [{ type: 'addText', text: 'order at canvix.coffee', y: 1000, width: 1080, fontSize: 56, color: '#FFFFFF', align: 'center' }],
+ },
+ { v: V, type: 'observation', stepIndex: 3, message: 'CTA text added.' },
+ { v: V, type: 'usage', turns: 4, toolCalls: 4, elapsedMs: 1800, modelCalls: 5 },
+ {
+ v: V, type: 'done', steps: 4, toolCalls: 3,
+ summary: 'Recovered and completed: the headline from the interrupted run was kept; the offer line and CTA were added in the free space.',
+ verification: 'Brief contract validated against the live canvas — all mandatory items present.',
+ },
+ ].map(ev).join('')
+}
+
+async function register(page: Page, tag: string): Promise<string> {
+ const username = `recov_${tag}_${Date.now().toString(36)}`
+ const password = `Recov-E2e-${username}-19!q`
+ const res = await page.request.post('/api/auth/register', { data: { username, password } })
+ expect(res.status(), `register ${username}`).toBeLessThan(300)
+ return username
+}
+
+type Doc = { pages: { elements: { text?: string; y?: number }[] }[] }
+
+async function doc(page: Page, designId: string): Promise<Doc> {
+ const res = await page.request.get(`/api/designs/${designId}`)
+ expect(res.status()).toBe(200)
+ return (await res.json()) as Doc
+}
+
+test.setTimeout(150_000)
+
+test.describe('v0.32.7 · interrupted-run recovery (mocked route, real editor)', () => {
+ test('a provider failure mid-build keeps applied work; the retry completes it without duplicates', async ({ page }) => {
+ page.on('pageerror', (e) => console.log('[pageerror]', e.message))
+ page.on('console', (m) => { if (m.type() === 'error') console.log('[console.error]', m.text().slice(0, 300)) })
+ await register(page, 'a')
+ const res = await page.request.post('/api/designs', {
+ data: {
+ name: 'Recovery test',
+ width: 1080,
+ height: 1920,
+ pages: [{ id: 'p1', background: { type: 'solid', color: '#FFFFFF' }, elements: [] }],
+ },
+ })
+ expect(res.status()).toBeLessThan(300)
+ const designId = ((await res.json()) as { id: string }).id
+ await page.goto(`/design/${designId}`)
+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })
+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 60_000 })
+
+ // the two scripted streams, served in order
+ const streams = [interruptedStream(), recoveryStream()]
+ const bodies: Record<string, unknown>[] = []
+ await page.route('**/api/ai/agent', (route) => {
+ bodies.push(route.request().postDataJSON() as Record<string, unknown>)
+ const body = streams.shift() ?? ''
+ return route.fulfill({
+ status: 200,
+ headers: { 'Content-Type': 'text/event-stream; charset=utf-8' },
+ body,
+ })
+ })
+
+ // ── 1. the interrupted run ─────────────────────────────────
+ await page.getByRole('button', { name: 'Apps', exact: true }).click()
+ await page.getByText('Canvix AI', { exact: true }).first().click()
+ const input = page.getByPlaceholder('Describe what to design or change — the agent figures out the rest…')
+ await input.fill('Design a bold Instagram post for a coffee launch')
+ await page.getByRole('button', { name: 'Send', exact: true }).click()
+
+ // the honest provider failure, shown once
+ await expect(page.getByText('The AI provider failed: API request failed with status 502', { exact: false })).toBeVisible({ timeout: 30_000 })
+
+ // the applied headline is KEPT on the canvas (autosaved)
+ const started = Date.now()
+ let kept: Doc | null = null
+ while (Date.now() - started < 20_000) {
+ kept = await doc(page, designId)
+ if (kept.pages[0].elements.some((e) => e.text === 'ARTISAN ROAST')) break
+ await page.waitForTimeout(500)
+ }
+ expect(kept?.pages[0].elements.filter((e) => e.text === 'ARTISAN ROAST')).toHaveLength(1)
+
+ // ── 2. the retry completes the design ─────────────────────
+ await input.fill('Continue and finish the design')
+ await page.getByRole('button', { name: 'Send', exact: true }).click()
+
+ // the recovery summary arrives
+ await expect(page.getByText('Recovered and completed', { exact: false })).toBeVisible({ timeout: 30_000 })
+
+ // ── 3. the document truth: complete, and NOTHING duplicated ──
+ // (poll — autosave lands the final actions after the done event)
+ const wanted = ['ARTISAN ROAST', 'our coffee launch — first sip free', 'order at canvix.coffee']
+ const started2 = Date.now()
+ let final: Doc | null = null
+ while (Date.now() - started2 < 20_000) {
+ final = await doc(page, designId)
+ const texts = final.pages[0].elements.map((e) => e.text ?? '')
+ if (wanted.every((t) => texts.includes(t))) break
+ await page.waitForTimeout(500)
+ }
+ const texts = final?.pages[0].elements.map((e) => e.text ?? '') ?? []
+ expect(texts.filter((t) => t === 'ARTISAN ROAST')).toHaveLength(1)
+ expect(texts.filter((t) => t === 'our coffee launch — first sip free')).toHaveLength(1)
+ expect(texts.filter((t) => t === 'order at canvix.coffee')).toHaveLength(1)
+
+ // the retry's request body carried the conversation history —
+ // the model knew what already happened in this chat
+ expect(bodies).toHaveLength(2)
+ const history = (bodies[1].history ?? []) as { role: string; content: string }[]
+ expect(history.length).toBeGreaterThan(0)
+ expect(history.some((h) => h.role === 'user' && h.content.includes('coffee launch'))).toBe(true)
+
+ // and the intent of the retry was classified, live in the panel
+ await expect(page.getByText('· refine', { exact: false }).first()).toBeVisible()
+ })
+})
diff --git a/tests/e2e/live-agent-benchmark.spec.ts b/tests/e2e/live-agent-benchmark.spec.ts
new file mode 100644
index 0000000..5fd955b
--- /dev/null
+++ b/tests/e2e/live-agent-benchmark.spec.ts
@@ -0,0 +1,271 @@
+import { test, expect, type Page } from '@playwright/test'
+
+// ═══════════════════════════════════════════════════════════════
+// v0.32.7 · THE LIVE BENCHMARK — real provider, real browser,
+// real route. NOT part of CI: runs only with CANVIX_BENCH_LIVE=1
+// (a configured provider + spent budget are prerequisites; CI runs
+// the mocked e2e suites instead — this file says REAL when it runs).
+//
+// What is measured per scenario (a design type + one honest prompt):
+// · completion — a done turn that is NOT an INCOMPLETE wrap-up
+// · brief fidelity — the required texts present as element values
+// · geometry — no off-canvas elements; no text-on-text overlaps
+// · latency — wall time from send to the done turn
+// · usage — turns, tools, model calls, tokens (from the
+// panel's usage line; tokens only when the
+// gateway reports them — never estimated)
+// · provider failures + RECOVERY — a run interrupted by a provider
+// failure (429/5xx — real gateways do this under sustained load)
+// is recovered with a follow-up "Continue and finish the design"
+// message (up to 2 recovery rounds; the recovery itself is one
+// of the things this benchmark measures). Recovered scenarios
+// are reported as recovered, not as clean passes.
+//
+// Results land in docs/BENCHMARK-v0.32.7.md (checked in, written by
+// the run itself — never hand-typed). Mocked tests are a different,
+// labeled thing; everything in THIS spec is live.
+// ═══════════════════════════════════════════════════════════════
+
+const LIVE = process.env.CANVIX_BENCH_LIVE === '1'
+const OUT_DIR = 'docs/benchmark-runs'
+const RUN_TIMEOUT_MS = 300_000
+const RECOVERY_MESSAGE = 'Continue and finish the design'
+/** cooldown between scenarios — real gateways rate-limit under
+ * sustained load; hammering them measures nothing but the limit */
+const INTER_SCENARIO_COOLDOWN_MS = 30_000
+
+const PROMPTS: {
+ id: string
+ name: string
+ w: number
+ h: number
+ prompt: string
+ requiredTexts: string[]
+ /** editing scenarios start with seeded content (intent ≠ create) */
+ seed?: { text: string; x: number; y: number; w: number; fontSize: number }[]
+}[] = [
+ {
+ id: 'poster', name: 'A3 poster', w: 1080, h: 1527,
+ prompt: 'Design a bold A3 poster for a summer music festival called Forest Beats on 12 July, tickets 40 euro',
+ requiredTexts: ['Forest Beats'],
+ },
+ {
+ id: 'social', name: 'Instagram story', w: 1080, h: 1920,
+ prompt: 'Design a bold Instagram post for a coffee launch',
+ requiredTexts: [],
+ },
+ {
+ id: 'deck', name: 'Pitch deck (3 slides)', w: 1920, h: 1080,
+ prompt: 'Build a 3-slide pitch deck for a startup called RiverPay that banks the unbanked',
+ requiredTexts: ['RiverPay'],
+ },
+ {
+ id: 'thumbnail', name: 'YouTube thumbnail', w: 1280, h: 720,
+ prompt: 'Design a YouTube thumbnail for a video called "I Built a House in 7 Days" — bold, readable at small size',
+ requiredTexts: ['I Built a House in 7 Days'],
+ },
+ {
+ id: 'logo', name: 'Logo', w: 1080, h: 1080,
+ prompt: 'Design a minimal logo for a bakery called Crumb in warm cream and chocolate brown',
+ requiredTexts: ['Crumb'],
+ },
+ {
+ id: 'ad', name: 'Web ad banner', w: 1200, h: 628,
+ prompt: 'Design a web ad banner for 50% off winter jackets at NorthPeak this weekend only, exact text "Winter Sale"',
+ requiredTexts: ['Winter Sale', 'NorthPeak'],
+ },
+ {
+ id: 'edit-restyle', name: 'Editing: restyle an existing design', w: 1080, h: 1350,
+ prompt: 'Recolor this design to warm cream and chocolate browns and increase the headline contrast',
+ requiredTexts: ['Sunrise Yoga'],
+ seed: [
+ { text: 'Sunrise Yoga', x: 140, y: 180, w: 800, fontSize: 96 },
+ { text: 'every morning at 6', x: 140, y: 320, w: 600, fontSize: 40 },
+ ],
+ },
+]
+
+interface Result {
+ id: string
+ ok: boolean
+ recovered: boolean
+ incomplete: boolean
+ intent: string | null
+ steps: number
+ tools: number
+ modelCalls: number
+ tokens: number | null
+ seconds: number
+ elements: number
+ requiredTextsPresent: Record<string, boolean>
+ offCanvas: number
+ textOverlaps: number
+ providerFailures: number
+ recoveryRounds: number
+ error: string | null
+}
+
+type Doc = { pages: { elements: { x?: number; y?: number; width?: number; height?: number; text?: string; type?: string }[] }[] }
+
+async function register(page: Page, tag: string): Promise<string> {
+ const username = `bench_${tag}_${Date.now().toString(36)}`
+ const password = `Bench-E2e-${username}-19!q`
+ const res = await page.request.post('/api/auth/register', { data: { username, password } })
+ expect(res.status(), `register ${username}`).toBeLessThan(300)
+ return username
+}
+
+/** One run round: send `message`, wait for the usage line (a
+ * finished run) or the provider-failure message (an interrupted
+ * one). Returns what happened. */
+async function oneRound(page: Page, input: ReturnType<Page['getByPlaceholder']>, message: string, timeoutMs: number): Promise<'done' | 'provider-failed' | 'timeout'> {
+ await input.fill(message)
+ await page.getByRole('button', { name: 'Send', exact: true }).click()
+ const usage = page.getByText(/turns · \d+ tools · \d+s · \d+ model calls/)
+ const failure = page.getByText('The AI provider failed')
+ const deadline = Date.now() + timeoutMs
+ while (Date.now() < deadline) {
+ if (await failure.last().isVisible().catch(() => false)) return 'provider-failed'
+ if (await usage.last().isVisible().catch(() => false)) return 'done'
+ await page.waitForTimeout(1_000)
+ }
+ return 'timeout'
+}
+
+test.describe('v0.32.7 live benchmark (real provider, real browser)', () => {
+ test.setTimeout(45 * 60_000)
+
+ test('seven design types + editing, measured honestly', async ({ page }) => {
+ test.skip(!LIVE, 'CANVIX_BENCH_LIVE=1 required — this spec spends a real provider budget')
+ const results: Result[] = []
+
+ for (const scenario of PROMPTS) {
+ const started = Date.now()
+ const r: Result = {
+ id: scenario.id, ok: false, recovered: false, incomplete: false, intent: null,
+ steps: 0, tools: 0, modelCalls: 0, tokens: null, seconds: 0, elements: 0,
+ requiredTextsPresent: {}, offCanvas: 0, textOverlaps: 0, providerFailures: 0,
+ recoveryRounds: 0, error: null,
+ }
+ try {
+ await register(page, scenario.id)
+ const res = await page.request.post('/api/designs', {
+ data: {
+ name: `Bench ${scenario.name}`,
+ width: scenario.w,
+ height: scenario.h,
+ pages: [{
+ id: 'p1',
+ background: { type: 'solid', color: scenario.seed ? '#0D1117' : '#FFFFFF' },
+ elements: (scenario.seed ?? []).map((s, i) => ({
+ id: `seed-${i}`, type: 'text', x: s.x, y: s.y, width: s.w, height: Math.round(s.fontSize * 1.4),
+ text: s.text, fontSize: s.fontSize, fontFamily: 'Poppins', bold: i === 0, fill: i === 0 ? '#FFFFFF' : '#C3CCDA',
+ })),
+ }],
+ },
+ })
+ expect(res.status()).toBeLessThan(300)
+ const designId = ((await res.json()) as { id: string }).id
+ await page.goto(`/design/${designId}`)
+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })
+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 60_000 })
+
+ await page.getByRole('button', { name: 'Apps', exact: true }).click()
+ await page.getByText('Canvix AI', { exact: true }).first().click()
+ const input = page.getByPlaceholder('Describe what to design or change — the agent figures out the rest…')
+
+ // ── the run, with bounded live recovery ────────────────────
+ let outcome = await oneRound(page, input, scenario.prompt, RUN_TIMEOUT_MS)
+ while (outcome === 'provider-failed' && r.recoveryRounds < 2) {
+ r.providerFailures += 1
+ r.recoveryRounds += 1
+ await page.waitForTimeout(20_000) // let the gateway breathe
+ outcome = await oneRound(page, input, RECOVERY_MESSAGE, RUN_TIMEOUT_MS)
+ }
+ if (outcome === 'provider-failed') r.providerFailures += 1
+ r.seconds = Math.round((Date.now() - started) / 1000)
+
+ // usage from the LAST usage line (the run's final total)
+ const usageLine = page.getByText(/turns · \d+ tools · \d+s · \d+ model calls/)
+ const usageText = (await usageLine.last().innerText().catch(() => '')).trim()
+ const m = usageText.match(/(\d+) turns · (\d+) tools · (\d+)s · (\d+) model calls(?: · ([\d.]+)k tokens)?/)
+ if (m) {
+ r.steps = Number(m[1]); r.tools = Number(m[2]); r.modelCalls = Number(m[4])
+ if (m[5]) r.tokens = Math.round(Number(m[5]) * 1000)
+ }
+
+ // completion honesty + the transcript facts
+ const panel = page.locator('[data-testid="agent-input"]').locator('..').locator('..')
+ const transcript = await panel.innerText().catch(() => '')
+ r.incomplete = /INCOMPLETE —/.test(transcript)
+ r.recovered = r.recoveryRounds > 0 && !r.incomplete && outcome === 'done'
+ r.ok = !r.incomplete && outcome === 'done'
+ const intentMatch = transcript.match(/· (create|add|replace|reposition|restyle|redesign|remove|refine|review)\b/)
+ r.intent = intentMatch ? intentMatch[1] : null
+
+ // document truth after autosave
+ await page.waitForTimeout(4_000)
+ const docRes = await page.request.get(`/api/designs/${designId}`)
+ const doc = (await docRes.json()) as Doc
+ const els = doc.pages[0].elements ?? []
+ r.elements = els.length
+ for (const t of scenario.requiredTexts) {
+ r.requiredTextsPresent[t] = els.some((e) => e.type === 'text' && (e.text ?? '').replace(/\s+/g, ' ') === t.replace(/\s+/g, ' '))
+ if (!r.requiredTextsPresent[t]) r.ok = false
+ }
+ // geometry: off-canvas + text-on-text overlaps (always defects)
+ for (const e of els) {
+ const x = e.x ?? 0, y = e.y ?? 0, w = e.width ?? 0, h = e.height ?? 0
+ if (x < -2 || y < -2 || x + w > scenario.w + 2 || y + h > scenario.h + 2) r.offCanvas += 1
+ }
+ const texts = els.filter((e) => e.type === 'text')
+ for (let i = 0; i < texts.length; i++) {
+ for (let j = i + 1; j < texts.length; j++) {
+ const a = texts[i], b = texts[j]
+ const ix = Math.max(0, Math.min((a.x ?? 0) + (a.width ?? 0), (b.x ?? 0) + (b.width ?? 0)) - Math.max(a.x ?? 0, b.x ?? 0))
+ const iy = Math.max(0, Math.min((a.y ?? 0) + (a.height ?? 0), (b.y ?? 0) + (b.height ?? 0)) - Math.max(a.y ?? 0, b.y ?? 0))
+ if (ix > 0 && iy > 0) r.textOverlaps += 1
+ }
+ }
+ if (r.offCanvas > 0 || r.textOverlaps > 0) r.ok = false
+
+ // evidence: a screenshot of the finished design + panel
+ await page.screenshot({ path: `${OUT_DIR}/${scenario.id}.png`, fullPage: false })
+ } catch (err) {
+ r.error = String((err as Error)?.message ?? err).slice(0, 220)
+ }
+ results.push(r)
+ if (scenario !== PROMPTS[PROMPTS.length - 1]) {
+ await page.waitForTimeout(INTER_SCENARIO_COOLDOWN_MS)
+ }
+ }
+
+ // ── the honest report ────────────────────────────────────────
+ const passed = results.filter((r) => r.ok && !r.recovered).length
+ const recoveredPassed = results.filter((r) => r.ok && r.recovered).length
+ const md = [
+ '# v0.32.7 live benchmark — REAL provider, REAL browser, REAL route',
+ '',
+ `Run: ${new Date().toISOString()} · ${passed}/${results.length} scenarios fully passed · ${recoveredPassed} recovered after a provider failure and completed · ${results.length - passed - recoveredPassed} did not complete`,
+ '("fully passed" = a non-INCOMPLETE done + every required text present + no off-canvas elements + no text-on-text overlaps. "recovered" = a provider failure interrupted the run and the recovery follow-up completed it. Everything in this table ran against the live provider through the real editor — the mocked suites are labeled separately in CI.)',
+ '',
+ '| scenario | outcome | intent | turns | tools | model calls | tokens | wall | elements | required texts | off-canvas | text overlaps | provider failures | recovery rounds |',
+ '| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |',
+ ...results.map((r) =>
+ `| ${r.id} | ${r.ok ? (r.recovered ? '✅ (recovered)' : '✅') : '❌'}${r.incomplete ? ' INCOMPLETE' : ''} | ${r.intent ?? '—'} | ${r.steps} | ${r.tools} | ${r.modelCalls} | ${r.tokens !== null ? `${r.tokens}k` : 'not reported'} | ${r.seconds}s | ${r.elements} | ${Object.values(r.requiredTextsPresent).every(Boolean) ? 'all present' : Object.entries(r.requiredTextsPresent).filter(([, v]) => !v).map(([k]) => `"${k}" missing`).join(', ') || '—'} | ${r.offCanvas} | ${r.textOverlaps} | ${r.providerFailures} | ${r.recoveryRounds} |`,
+ ),
+ '',
+ ...results.filter((r) => r.error).map((r) => `> error in ${r.id}: ${r.error}`),
+ '',
+ 'Token counts appear only when the gateway reports usage; "not reported" is a provider limitation, never an estimate.',
+ ].join('\n')
+ const { mkdirSync, writeFileSync } = await import('node:fs')
+ mkdirSync(OUT_DIR, { recursive: true })
+ writeFileSync(`${OUT_DIR}/v0.32.7-results.json`, JSON.stringify(results, null, 2))
+ writeFileSync('docs/BENCHMARK-v0.32.7.md', md)
+
+ // the benchmark itself asserts nothing beyond honest recording —
+ // completion-rate claims live in the report, judged by a human
+ expect(results.length).toBe(PROMPTS.length)
+ })
+})