Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
fix(v0.29.4): the failed CANVIX poster run, end to end — brief, audit, planning, vision-in-loop, honest completion
Ashiq Hussain Mirfc8b4f8309a4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2e8ee4f..1891e26 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,90 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).## [Unreleased]+### Fixed++- **Agent v0.29.3 — the failed CANVIX poster run, root-caused and+ fixed end-to-end.** Reproduced from the production transcript (the+ 1080×1080 CANVIX promo prompt, 45 steps / 42 actions, P0 findings+ after "success"): every class of failure below has a regression+ test in `src/lib/agent/harness.test.ts` (86 tests total).+ - `extractBrief` no longer manufactures phantom mandatory strings:+ "Exact text only: …" produced the fake requirement `only:` (and+ even a 300pt heading). The unquoted headline pattern now requires+ a capitalized payload, rejects instruction stopwords ("only",+ "exactly", …) and cannot cross quotes — the seven user strings+ are preserved verbatim.+ - Composite deliverables are contract fields, not decoration:+ "a realistic editor mockup", "3 feature cards" and "glassmorphism"+ extract into `requiredFeatures` and validate structurally (native+ panel with inner elements; N semi-transparent rect+text cards;+ rgba fills with borders) — the client's brief validation sends+ element geometry so `validate_brief` checks them against the live+ canvas.+ - Structural compliance ≠ rendered compliance: the quality audit+ computes each text's **effective backdrop** (z-order + rgba+ compositing — intentional text-on-card layering is preserved, not+ flagged), reports texts **obscured by opaque shapes above them**,+ and uses the panel's **client-measured text widths** (canvas+ measureText) instead of the 0.58×fontSize glyph-average estimate.+ The page background is the ctx's real field only — never a+ guessed dominant color.+ - Required colors used **only as bare decorative strips** (thin+ bars with nothing on them) are flagged: strips satisfied the+ color check without being design.+ - Brief-to-layout planning replaces the reactive add/move/fix+ loop: `plan_layout` (read-risk pseudo-tool) reserves vertical+ bands per section before building, the create-mode prompt+ requires it, and the plan is streamed to the user.+ - Grounded **vision critique runs BEFORE completion**, not after:+ the loop asks the panel to screenshot the live canvas (the export+ pipeline's `captureStage`, via the run bridge), critiques it with+ the vision slot, feeds P0/P1 findings into ONE bounded correction+ pass, re-captures and verifies. Unresolved P0 defects force an+ `INCOMPLETE —` summary ("NOT visually verified"); a capture+ timeout or unconfigured vision model is DISCLOSED, never silently+ skipped.+ - Action acks fail closed: a timed-out apply ack resolves+ `ok:false` ("the client did NOT confirm the apply") instead of+ "assumed applied" — the model is no longer told edits landed when+ nobody confirmed them.+ - The router no longer misroutes obvious build briefs to discuss:+ "Create a premium … promo poster for CANVIX … 3 feature cards"+ triggered the product-discuss guard on the words "canvix" and+ "feature"; artifact-noun + build-verb + not-a-question now wins.+ - Completion summaries are grounded: the document name (e.g.+ "Music Festival") is declared a file name, not the deliverable;+ the prompt separates "element exists" from "text is readable",+ and the verification line reports brief/audit/vision outcomes+ separately.+ - File-configured providers no longer 401: `makeClient` dropped the+ config-file's companion headers (X-Token / X-User-Id / X-Chat-Id),+ so every provider resolved from `.z-ai-config` failed with+ "missing X-Token header" the moment env pins were absent.++ - v0.29.4 — chitchat can never start a build: greetings ("hi",+ "thanks!", "ok cool"…) route to discuss with high confidence and+ never reach the model router, where a provider with a bias could+ invent a build task (and a canned aesthetic) out of pure+ conversation. Real build briefs still route to create.+ - v0.29.4 — three new design skills installed (research-grounded,+ original text): **Glassmorphism & Layered Surfaces** (rgba fill ++ visible border on the same native element, contrast checked+ against the composited backdrop — NN/g and Axess Lab guidance),+ **Realistic Product Mockups** (window chrome + toolbar + sidebar ++ content as an 8–15-element native composite — one empty rectangle+ is a placeholder, not a mockup), and **Visual Accessibility**+ (WCAG floors, minimum type sizes, never meaning by color alone).+ The failed CANVIX prompt now selects poster + glassmorphism ++ mockups skills automatically.+ - v0.29.4 — the system prompt now pins grounding and+ verify-then-stop rules: the element list IS the live canvas+ (never assume empty, never re-create, never invent imagery the+ user did not ask for), and done is only allowed after the checks+ actually ran — a check that cannot run is disclosed, not claimed.+++### Added- **BYO-MCP — personal MCP tokens (v0.25)** — the MCP endpoint now has adiff --git a/src/app/api/ai/agent/route.ts b/src/app/api/ai/agent/route.tsindex 86559dd..253f233 100644--- a/src/app/api/ai/agent/route.ts+++ b/src/app/api/ai/agent/route.ts@@ -14,7 +14,9 @@ import { heuristicMode, parseMode, ROUTER_SYSTEM, modeAllowsWrites, MODE_TOOL_RIimport { runAgentLoop, toolsForMode } from '@/lib/agent/loop'import { auditDesign as runDesignAudit } from '@/lib/agent/audit'import { selectSkills } from '@/lib/agent/skills'-import { extractBrief } from '@/lib/agent/brief'+import { extractBrief, type DesignBrief } from '@/lib/agent/brief'+import { critiqueWithVision } from '@/lib/agent/vision'+import { getClientForSlot } from '@/lib/ai/provider'export const runtime = 'nodejs'export const maxDuration = 800@@ -60,6 +62,10 @@ interface RunBridge {/** briefResult that arrived before the loop asked (the panel answers* immediately on seeing the action event) — consumed first */pendingBriefResult: { satisfied: boolean; unmet: string[] } | null+ /** v0.29.3: canvas capture pushed by the client (the loop's+ * in-run vision critique) — resolves with the image dataURL or+ * null (timeout) */+ capture: ((r: { image: string } | null) => void) | null/** the latest context the client pushed (after applying actions) */latestDesign: AgentDesignCtx/** client-abort flag (Stop button closes the stream; the route@@ -75,11 +81,36 @@ function newRunId(): string {return `run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`}+/** v0.29.3: one grounded vision critique of a REAL captured+ * screenshot — shared by the loop's pre-completion round. Resolves+ * null when the vision slot is unconfigured or the call fails (the+ * caller then discloses, never pretends). */+async function critiqueRoute(+ image: string,+ brief: DesignBrief | null,+ design: AgentDesignCtx,+): Promise<{ findings: { severity: 'P0' | 'P1' | 'P2' | 'P3'; issue: string; fix?: string }[]; note: string } | null> {+ if (!image.startsWith('data:image/')) return null+ const vision = await getClientForSlot('vision')+ if (!vision) return null+ // same structural cast the route's chat fn uses — the SDK's typed+ // create() accepts our body shape at runtime+ const client = vision.zai as unknown as Parameters<typeof critiqueWithVision>[0]+ return critiqueWithVision(client, image, {+ brief: brief+ ? { requiredTexts: brief.requiredTexts, requiredColors: brief.requiredColors }+ : undefined,+ stateSummary: serializeDesignContext(design),+ model: vision.model,+ })+}+async function __canvix_post(req: NextRequest) {const body = (await req.json().catch(() => ({}))) as AgentBody & {confirm?: { tool: string; ok: boolean }ack?: { ok: boolean; message?: string; design?: AgentDesignCtx }briefResult?: { satisfied: boolean; unmet: string[] } | null+ capture?: { image: string } | null}const message = (body.message ?? '').trim().slice(0, 2000)@@ -115,6 +146,15 @@ async function __canvix_post(req: NextRequest) {bridge.pendingBriefResult = body.briefResult}}+ // v0.29.3: the panel's mid-run canvas capture (dataURL screenshot+ // taken with the export pipeline) for the loop's vision critique+ if (body.capture !== undefined) {+ const resolve = bridge.capture+ if (resolve) {+ bridge.capture = null+ resolve(body.capture)+ }+ }return new Response(JSON.stringify({ ok: true }), { status: 200 })}@@ -264,6 +304,7 @@ async function __canvix_post(req: NextRequest) {acks: [],briefResult: null,pendingBriefResult: null,+ capture: null,latestDesign: design,aborted: false,}@@ -301,11 +342,41 @@ async function __canvix_post(req: NextRequest) {awaitApply: () =>new Promise<{ ok: boolean; message?: string }>((resolve) => {bridge.acks.push((ack) => resolve({ ok: ack.ok, message: ack.message }))- setTimeout(() => resolve({ ok: true, message: 'ack timeout — assumed applied' }), 60_000)+ // v0.29.3 — FAIL CLOSED: a timed-out apply ack now+ // resolves ok:false. The old "ack timeout — assumed+ // applied" let the model believe edits landed when+ // the client never confirmed them, so it built on a+ // fiction and the completion summary described work+ // that was never applied. The model is told the+ // action was NOT applied; it can retry or finish+ // honestly.+ setTimeout(+ () => resolve({ ok: false, message: 'ack timeout — the client did NOT confirm the apply; the document was not verified as changed. Retry once, or verify with get_page_state.' }),+ 60_000,+ )+ }),+ // v0.29.3: the loop's mid-run capture — the panel answers+ // on the bridge with {capture: {image: dataUrl}}. A+ // silent client resolves null and the run DISCLOSES that+ // visual verification was unavailable (never pretends).+ captureCanvas: () =>+ new Promise<string | null>((resolve) => {+ bridge.capture = (r) => resolve(r?.image ?? null)+ setTimeout(() => {+ if (bridge.capture) {+ bridge.capture = null+ resolve(null)+ }+ }, 45_000)}),+ // v0.29.3: the grounded vision critique, BEFORE completion.+ // Unconfigured vision slot → null → the loop discloses.+ critique: (image) =>+ critiqueRoute(image, brief, bridge.latestDesign ?? design).then((r) => r ?? null),refreshedContext: () => bridge.latestDesign,// v0.29: audit the freshest design snapshot the panel acked- auditDesign: () => runDesignAudit(bridge.latestDesign ?? design),+ // (v0.29.3: the brief rides along for strip detection)+ auditDesign: () => runDesignAudit(bridge.latestDesign ?? design, brief),validateBriefOnClient: async () => {// consume an early answer first, then wait for a live oneif (bridge.pendingBriefResult) {diff --git a/src/app/api/ai/agent/vision/route.ts b/src/app/api/ai/agent/vision/route.tsindex aa69ad4..01af7d0 100644--- a/src/app/api/ai/agent/vision/route.ts+++ b/src/app/api/ai/agent/vision/route.ts@@ -1,6 +1,7 @@import { NextRequest, NextResponse } from 'next/server'import { getClientForSlot } from '@/lib/ai/provider'import { withLogging } from '@/lib/observability'+import { critiqueWithVision } from '@/lib/agent/vision'export const runtime = 'nodejs'export const maxDuration = 120@@ -28,12 +29,6 @@ interface VisionBody {stateSummary?: string // the serialized structured state}-const SYSTEM =- 'You are a meticulous design critic looking at a REAL screenshot of a graphic-design canvas. ' +- 'Report only what you can actually see in the image. Never invent or assume elements that are not visible; ' +- 'if something cannot be determined from the image, say "cannot determine". ' +- 'Reply ONLY with JSON: {"findings": [{"severity": "P0"|"P1"|"P2"|"P3", "issue": "what is wrong (concrete, visual)", "fix": "the specific change to make"}], "overall": "one sentence verdict"}\n' +- 'P0 = broken/unreadable/missing required content; P1 = major (weak hierarchy, poor contrast, crowding); P2 = minor (spacing, balance); P3 = polish.'async function __canvix_post(req: NextRequest) {const body = (await req.json().catch(() => ({}))) as VisionBody@@ -59,63 +54,20 @@ async function __canvix_post(req: NextRequest) {)}- const brief = body.brief ?? {}- const requiredTexts = (brief.requiredTexts ?? []).map((t) => t.text).filter(Boolean)- const requiredColors = (brief.requiredColors ?? []).map((c) => c.hex).filter(Boolean)-- const userText = [- 'Critique this canvas screenshot for design quality and brief compliance.',- requiredTexts.length ? `Required exact texts (verify they appear VERBATIM and are readable): ${requiredTexts.map((t) => `"${t}"`).join(', ')}.` : '',- requiredColors.length ? `Required colors (verify they are visibly used): ${requiredColors.join(', ')}.` : '',- body.stateSummary ? `Structured element state for cross-checking (ground truth for ids/positions):\n${body.stateSummary.slice(0, 4000)}` : '',- 'Check: readability of every text at this scale, contrast of text on its background, alignment and spacing consistency, visual hierarchy (is the headline dominant?), accidental overlaps or clipped content, dead space, and overall professional impression.',- 'Reply with the JSON findings now.',- ]- .filter(Boolean)- .join('\n')-+ // v0.29.3: the critique engine lives in src/lib/agent/vision.ts and is+ // shared with the agent LOOP (pre-completion round) — one prompt, one+ // honesty contract, no drift between the two paths.try {- const completion = await vision.zai.chat.completions.create({- ...(vision.model ? { model: vision.model } : {}),- messages: [- { role: 'system', content: SYSTEM },- {- role: 'user',- content: [- { type: 'text', text: userText },- { type: 'image_url', image_url: { url: image } },- ] as unknown as string,- },- ],- thinking: { type: 'disabled' },+ const client = vision.zai as unknown as Parameters<typeof critiqueWithVision>[0]+ const result = await critiqueWithVision(client, image, {+ brief: body.brief ?? undefined,+ stateSummary: body.stateSummary,+ model: vision.model,})- const raw = String(completion.choices[0]?.message?.content ?? '')- // robust parse — the model may fence or add prose- const cleaned = raw.replace(/```(?:json)?/gi, '').trim()- const start = cleaned.indexOf('{')- const end = cleaned.lastIndexOf('}')- if (start === -1 || end <= start) {+ if (!result) {return NextResponse.json({ error: 'The vision model returned no parseable critique.' }, { status: 502 })}- let parsed: { findings?: unknown; overall?: unknown }- try {- parsed = JSON.parse(cleaned.slice(start, end + 1))- } catch {- return NextResponse.json({ error: 'The vision model returned malformed critique JSON.' }, { status: 502 })- }- const findings = (Array.isArray(parsed.findings) ? parsed.findings : [])- .filter((f) => !!f && typeof f === 'object')- .map((f) => {- const fo = f as { severity?: unknown; issue?: unknown; fix?: unknown }- const sev = ['P0', 'P1', 'P2', 'P3'].includes(String(fo.severity)) ? (String(fo.severity) as 'P0') : 'P2'- return {- severity: sev,- issue: String(fo.issue ?? '').slice(0, 400) || 'unspecified issue',- fix: fo.fix === undefined ? undefined : String(fo.fix).slice(0, 400),- }- })- .slice(0, 12)- return NextResponse.json({ available: true, findings, overall: String(parsed.overall ?? '').slice(0, 400) })+ return NextResponse.json({ available: true, findings: result.findings.slice(0, 12), overall: result.note })} catch (err) {const message = err instanceof Error ? err.message.slice(0, 150) : 'vision call failed'return NextResponse.json({ error: `Visual critique failed: ${message}` }, { status: 502 })diff --git a/src/components/editor/apps/AssistantApp.tsx b/src/components/editor/apps/AssistantApp.tsxindex a55fec2..65e7b8f 100644--- a/src/components/editor/apps/AssistantApp.tsx+++ b/src/components/editor/apps/AssistantApp.tsx@@ -34,6 +34,7 @@ import { useAICapabilities } from '@/hooks/use-ai-capabilities'import type { AgentEvent, AgentMode } from '@/lib/agent/protocol'import { validateBrief, type DesignBrief } from '@/lib/agent/brief'import { heuristicMode, MODE_TOOL_RISK } from '@/lib/agent/router'+import { contrastBetween } from '@/lib/agent/audit'// ── types ────────────────────────────────────────────────────@@ -97,6 +98,25 @@ function flatElements(els: AnyElement[], out: AnyElement[] = []): AnyElement[] {function buildDesignContext() {const s = useEditorStore.getState()const page = s.pages[s.currentPage]+ // v0.29.3: real text metrics — the same canvas measureText the+ // renderer and the measure_text tool use. The audit's overflow+ // check consumes measuredWidth instead of a glyph-average guess.+ let measureCtx: CanvasRenderingContext2D | null = null+ const measureText = (t: TextElement): number | undefined => {+ try {+ if (!measureCtx) {+ const c = document.createElement('canvas')+ measureCtx = c.getContext('2d')+ }+ if (!measureCtx) return undefined+ measureCtx.font = `${t.bold ? 'bold ' : ''}${Math.max(6, Math.round(t.fontSize))}px ${t.fontFamily || 'Poppins'}`+ const single = t.text.split('\n')[0] ?? ''+ if (!single) return undefined+ return Math.round(measureCtx.measureText(single).width)+ } catch {+ return undefined+ }+ }const elements = (page?.elements ?? []).slice(0, 80).map((el) => {const base: Record<string, unknown> = {id: el.id,@@ -114,18 +134,27 @@ function buildDesignContext() {base.fontSize = Math.round(t.fontSize)base.bold = t.boldbase.fontFamily = t.fontFamily+ const w = measureText(t)+ if (w !== undefined) base.measuredWidth = w} else if ('fill' in el) {base.fill = (el as { fill: string }).fill}+ if ('stroke' in el && typeof (el as { stroke?: unknown }).stroke === 'string') {+ const stroke = (el as { stroke: string }).stroke+ if (stroke.trim()) base.stroke = stroke+ }if (el.name) base.name = el.name.slice(0, 30)return base})const texts = flatElements(page?.elements ?? []).filter((e) => e.type === 'text') as TextElement[]// spatial analysis (v0.26 logic, client-computed for the agent context)+ // v0.29.3: text-on-card layering is INTENTIONAL — a pair is only an+ // overlap problem when the text is NOT readable on the shape: not+ // contained, or the contrast against the shape fill is too low.const boxes = (page?.elements ?? []).filter((e) => (e.width ?? 0) > 0 && (e.height ?? 0) > 0)- .map((e) => ({ id: e.id, type: e.type, x: e.x, y: e.y, w: e.width, h: e.height }))+ .map((e) => ({ id: e.id, type: e.type, x: e.x, y: e.y, w: e.width, h: e.height, fill: 'fill' in e ? String((e as { fill?: unknown }).fill ?? '') : '' }))const overlaps: string[] = []for (let i = 0; i < boxes.length && overlaps.length < 12; i++) {for (let j = i + 1; j < boxes.length && overlaps.length < 12; j++) {@@ -136,8 +165,16 @@ function buildDesignContext() {const inter = ix * iyconst minArea = Math.min(a.w * a.h, b.w * b.h)if (minArea > 0 && inter / minArea > 0.08) {- const smaller = a.w * a.h <= b.w * a.h ? a : b- if (inter / minArea > 0.55 && smaller.type === 'text') continue // text-on-card+ const smaller = a.w * a.h <= b.w * b.h ? a : b+ const bigger = smaller === a ? b : a+ if (smaller.type === 'text') {+ // text vs its card: contained + readable = fine layering+ const contained = inter / minArea > 0.7+ if (contained) {+ const readable = contrastBetween(smaller.fill, bigger.fill) >= 3+ if (readable || isSemiTransparent(bigger.fill)) continue+ }+ }overlaps.push(`${a.type}#${a.id} × ${b.type}#${b.id} (${Math.round((inter / minArea) * 100)}%)`)}}@@ -153,6 +190,18 @@ function buildDesignContext() {? { colors: s.brand.colors, headingFont: s.brand.headingFont, bodyFont: s.brand.bodyFont }: null+ // v0.29.3: the REAL page background — the audit's contrast math and+ // strip detection read this field; it is never guessed server-side.+ const bg = page?.background+ let backgroundHex: string | undefined+ if (bg?.type === 'solid' && /^#?[0-9a-f]{6}$/i.test(bg.color)) {+ backgroundHex = bg.color.startsWith('#') ? bg.color.toLowerCase() : `#${bg.color}`.toLowerCase()+ } else if (bg?.type === 'gradient' && /^#?[0-9a-f]{6}$/i.test(bg.from)) {+ // gradient: report the top-of-list stop; per-text backdrops still+ // handle cards, and the audit treats it as the page base+ backgroundHex = bg.from.startsWith('#') ? bg.from.toLowerCase() : `#${bg.from}`.toLowerCase()+ }+return {name: s.designName,width: s.width,@@ -173,6 +222,7 @@ function buildDesignContext() {brand,overlaps,offCanvas,+ ...(backgroundHex ? { background: backgroundHex } : {}),otherPages: s.pages.filter((_, i) => i !== s.currentPage).slice(0, 8)@@ -180,9 +230,21 @@ function buildDesignContext() {}}+/** rgba/semi-transparent fill → the element is a glass layer, not a+ * solid occluder (text on it is intentional layering). */+function isSemiTransparent(fill: string): boolean {+ const m = /^rgba?\(\s*\d{1,3}[\s,]+\d{1,3}[\s,]+\d{1,3}(?:[\s,/]+([\d.]+%?))?\s*\)/i.exec(String(fill).trim())+ if (!m) return false+ if (m[1] === undefined) return false+ const a = m[1].endsWith('%') ? Number(m[1].slice(0, -1)) / 100 : Number(m[1])+ return Number.isFinite(a) && a <= 0.85+}+/** Client-side brief validation against the LIVE document (Phase 5).* Pure — reads the store, returns the validation shape the loop- * expects on the bridge. */+ * expects on the bridge.+ * v0.29.3: flattened elements ride along so composite deliverables+ * (editor mockup, feature cards, glassmorphism) validate structurally. */function computeBriefValidation(brief: DesignBrief): { satisfied: boolean; unmet: string[] } {const s = useEditorStore.getState()const page = s.pages[s.currentPage]@@ -202,11 +264,22 @@ function computeBriefValidation(brief: DesignBrief): { satisfied: boolean; unmetcolors.add(page.background.from.toLowerCase())colors.add(page.background.to.toLowerCase())}+ const elements = els.slice(0, 120).map((e) => ({+ type: e.type,+ x: Math.round(e.x),+ y: Math.round(e.y),+ width: Math.round(e.width),+ height: Math.round(e.height),+ ...( 'fill' in e && typeof (e as { fill?: unknown }).fill === 'string' ? { fill: (e as { fill: string }).fill } : {}),+ ...('stroke' in e && typeof (e as { stroke?: unknown }).stroke === 'string' ? { stroke: (e as { stroke: string }).stroke } : {}),+ ...(e.type === 'text' ? { text: (e as TextElement).text } : {}),+ }))const result = validateBrief(brief, {texts,colors: [...colors],width: s.width,height: s.height,+ elements,})return { satisfied: result.satisfied, unmet: result.unmet }}@@ -402,6 +475,20 @@ export function AssistantApp({ onClose }: AppPanelProps) {case 'usage':setLiveUsage({ turns: event.turns, toolCalls: event.toolCalls, elapsedMs: event.elapsedMs, modelCalls: event.modelCalls })break+ case 'capture': {+ // v0.29.3: the loop asks for the REAL rendered canvas+ // BEFORE completion — same capture pipeline the export and+ // the post-run critique use. Answer on the bridge; a+ // failure answers null (the loop discloses honestly).+ try {+ const { captureStage } = await import('@/components/editor/canvas/canvas-bridge')+ const dataUrl = await captureStage({ pixelScale: 0.5, mimeType: 'image/jpeg', quality: 0.7 })+ await bridgePost({ capture: { image: dataUrl } })+ } catch {+ await bridgePost({ capture: null })+ }+ break+ }case 'compact':collectedSteps.push({index: collectedSteps.length,diff --git a/src/lib/agent/audit.ts b/src/lib/agent/audit.tsindex 993800f..3f148a7 100644--- a/src/lib/agent/audit.ts+++ b/src/lib/agent/audit.ts@@ -1,94 +1,247 @@/**- * v0.29 QUALITY AUDIT — local design heuristics the agent runs on its+ * v0.29.3 QUALITY AUDIT — local design heuristics the agent runs on its* own canvas before accepting completion. No model calls, no vision:- * WCAG 2.x contrast math, the client-computed overlaps/off-canvas from- * the design ctx, and a text-overflow estimate. The loop consumes the- * returned issues in ONE auto-fix round (see loop.ts); empty = clean.+ * WCAG 2.x contrast math, per-text EFFECTIVE backgrounds (z-order aware,+ * rgba-composited — intentional text-on-card layering is preserved, not+ * flagged), obscuring-shape detection, real client-measured text widths,+ * and decorative color-strip detection. The loop consumes the returned+ * issues in ONE auto-fix round (see loop.ts); empty = clean.+ *+ * v0.29 → v0.29.3 changes (the failed CANVIX production run):+ * · the page background is the ctx's REAL `background` field only —+ * never a guessed "dominant" in-use color (the old guess made+ * contrast checks fire against the wrong backdrop);+ * · contrast is computed per text against what is actually BEHIND it+ * (semi-transparent panels are alpha-composited onto the page), so+ * text on a glass card is judged against the card, not the page;+ * · elements ABOVE a text that cover it (z-order, opaque) are+ * reported as obscured — a present element is not a visible one;+ * · text overflow uses the CLIENT-MEASURED pixel width (canvas+ * measureText) when available — the 0.58×fontSize glyph-average+ * formula is only a last-resort estimate and is labeled as such;+ * · required colors used ONLY as bare decorative strips are flagged+ * (strips satisfy the color check but are not design).*/-import type { AgentDesignCtx } from './context'+import type { AgentDesignCtx, AgentElementCtx } from './context'+import { parseColor } from './brief'const HEX = /^#?[0-9a-f]{6}$/i-/** WCAG 2.x relative luminance of a #RRGGBB color (0..1); -1 unparseable. */-export function luminance(hex: string): number {- const m = /^#?([0-9a-f]{6})$/i.exec(String(hex).trim())- if (!m) return -1- const n = parseInt(m[1], 16)+interface RGB {+ r: number+ g: number+ b: number+ a: number+}++/** WCAG 2.x relative luminance of a parsed color (0..1). */+function luminance(c: RGB): number {const channel = (v: number) => {- const c = v / 255- return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4)+ const x = v / 255+ return x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4)}- return 0.2126 * channel((n >> 16) & 255) + 0.7152 * channel((n >> 8) & 255) + 0.0722 * channel(n & 255)+ return 0.2126 * channel(c.r) + 0.7152 * channel(c.g) + 0.0722 * channel(c.b)}-/** WCAG contrast ratio (1..21); 0 when either color is unparseable. */-export function contrastRatio(fg: string, bg: string): number {+/** WCAG contrast ratio (1..21). */+function contrastRatio(fg: RGB, bg: RGB): number {const lf = luminance(fg)const lb = luminance(bg)- if (lf < 0 || lb < 0) return 0return (Math.max(lf, lb) + 0.05) / (Math.min(lf, lb) + 0.05)}+/** Alpha-composite src over dst (both may carry alpha). */+function blend(src: RGB, dst: RGB): RGB {+ const a = src.a + dst.a * (1 - src.a)+ if (a <= 0) return { r: 0, g: 0, b: 0, a: 0 }+ return {+ r: (src.r * src.a + dst.r * dst.a * (1 - src.a)) / a,+ g: (src.g * src.a + dst.g * dst.a * (1 - src.a)) / a,+ b: (src.b * src.a + dst.b * dst.a * (1 - src.a)) / a,+ a,+ }+}++function toHex(c: RGB): string {+ const h = (n: number) => Math.round(Math.min(255, Math.max(0, n))).toString(16).padStart(2, '0')+ return `#${h(c.r)}${h(c.g)}${h(c.b)}`+}++function box(e: AgentElementCtx) {+ return { x: e.x ?? 0, y: e.y ?? 0, w: e.width ?? 0, h: e.height ?? 0 }+}++/** Fraction of `inner`'s area covered by `outer`'s bounds. */+function coverage(inner: AgentElementCtx, outer: AgentElementCtx): number {+ const a = box(inner)+ const b = box(outer)+ if (a.w <= 0 || a.h <= 0) return 0+ 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) / (a.w * a.h)+}++/** The backdrop a text actually sits on: page background with every+ * semi-transparent covering element BELOW the text composited on top+ * (z-order = array order, bottom first). Preserves text-on-card. */+function effectiveBackdrop(text: AgentElementCtx, els: AgentElementCtx[], pageBg: RGB | null): RGB | null {+ const idx = els.indexOf(text)+ let acc: RGB | null = pageBg+ for (let i = 0; i < idx; i++) {+ const el = els[i]+ if (el.type === 'text') continue // text under text doesn't form a backdrop+ const fill = parseColor(el.fill)+ if (!fill) continue+ // only shapes that actually sit under (cover ≥70% of) the text+ if (coverage(text, el) < 0.7) continue+ acc = acc ? blend(fill, acc) : fill+ }+ return acc+}+/** Worst N issues, human-readable and FIXABLE (the model acts on these). */-export function auditDesign(d: AgentDesignCtx): string[] {+export function auditDesign(+ d: AgentDesignCtx,+ brief?: { requiredColors?: { hex: string; tier?: string }[] } | null,+): string[] {const issues: string[] = []- const texts = (d.elements ?? []).filter((e) => e && e.type === 'text')- // background: explicit ctx field, else the dominant color heuristic- const bg = typeof d.background === 'string' && HEX.test(d.background)- ? d.background- : (d.colorsInUse ?? []).find((c) => HEX.test(c)) ?? null-- // 1. text contrast against the page background (WCAG: 3:1 large, 4.5:1 body)- if (bg) {- let contrastHits = 0- for (const t of texts) {- const fill = typeof t.fill === 'string' ? t.fill : ''- if (!HEX.test(fill)) continue- const ratio = contrastRatio(fill, bg)- if (ratio <= 0) continue- const size = typeof t.fontSize === 'number' ? t.fontSize : 0- const need = size >= 24 ? 3 : 4.5- if (ratio < need) {- contrastHits += 1- if (contrastHits <= 4) {- issues.push(- `Low contrast: text "${String(t.text ?? '').slice(0, 30)}" ${fill} on background ${bg} is ${ratio.toFixed(1)}:1 (needs ${need}:1) — change the text fill.`,- )- }+ const els = d.elements ?? []+ const texts = els.filter((e) => e && e.type === 'text')++ // the REAL page background — hex only; no dominant-color guessing.+ // When the page has no parseable solid background the page-level+ // contrast check is skipped (the per-text backdrop still works when+ // a card sits behind the text).+ const pageBg = typeof d.background === 'string' && HEX.test(d.background) ? parseColor(d.background) : null++ // 1. text contrast against each text's EFFECTIVE backdrop (text on+ // a card is checked against the card — intentional layering)+ let contrastHits = 0+ for (const t of texts) {+ const fill = parseColor(t.fill)+ if (!fill) continue+ const backdrop = effectiveBackdrop(t, els, pageBg)+ if (!backdrop) continue+ const effText = fill.a < 1 ? blend(fill, backdrop) : fill+ const ratio = contrastRatio(effText, backdrop)+ if (ratio <= 0) continue+ const size = typeof t.fontSize === 'number' ? t.fontSize : 0+ const need = size >= 24 ? 3 : 4.5+ if (ratio < need) {+ contrastHits += 1+ if (contrastHits <= 4) {+ issues.push(+ `Low contrast: text "${String(t.text ?? '').slice(0, 30)}" ${String(t.fill)} on its effective backdrop ${toHex(backdrop)} is ${ratio.toFixed(1)}:1 (needs ${need}:1) — change the text fill or the card behind it.`,+ )}}- if (contrastHits > 4) issues.push(`…and ${contrastHits - 4} more low-contrast text elements.`)}+ if (contrastHits > 4) issues.push(`…and ${contrastHits - 4} more low-contrast text elements.`)- // 2. element overlaps (client-computed) — hard readability failures+ // 2. OBSCURED text: an opaque-ish element ABOVE a text covering ≥50%+ // of it — structurally present but not visible (v0.29.3)+ for (const t of texts) {+ const idx = els.indexOf(t)+ for (let i = idx + 1; i < els.length; i++) {+ const el = els[i]+ if (el.type === 'text') continue+ const fill = parseColor(el.fill)+ if (!fill || fill.a < 0.5) continue+ const cov = coverage(t, el)+ if (cov >= 0.5) {+ issues.push(+ `Text "${String(t.text ?? '').slice(0, 30)}" is covered by ${el.type}#${el.id} (${Math.round(cov * 100)}% of it) — move the shape below the text (reorder_layers) or move one of them.`,+ )+ break+ }+ }+ }++ // 3. element overlaps (client-computed) — hard readability failuresfor (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. off-canvas elements+ // 4. off-canvas elementsfor (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 ?? '?'}.`)if ((d.offCanvas ?? []).length > 3) issues.push(`…and ${(d.offCanvas ?? []).length - 3} more off-canvas elements.`)- // 4. text overflow estimate: average glyph ~0.55em+ // 5. text overflow — REAL client-measured width when the panel sent+ // it (canvas measureText, the same pipeline the renderer uses);+ // the glyph-average estimate only when it did not, labeled as suchlet overflowHits = 0for (const t of texts) {const text = String(t.text ?? '')const size = typeof t.fontSize === 'number' ? t.fontSize : 0const width = typeof t.width === 'number' ? t.width : 0if (!text || size < 8 || width <= 0) continue- const est = text.length * 0.55 * size+ const measured = typeof t.measuredWidth === 'number' && t.measuredWidth > 0 ? t.measuredWidth : null+ const est = measured ?? text.length * 0.58 * size+ const tag = measured ? 'measured' : 'estimated'if (est > width * 1.06) {overflowHits += 1if (overflowHits <= 3) {issues.push(- `Text may overflow its box: "${text.slice(0, 30)}" (${text.length} chars at ${size}pt needs ~${Math.round(est)}px, box is ${Math.round(width)}px) — reduce fontSize, shorten the text, or widen the box.`,+ `Text overflows its box: "${text.slice(0, 30)}" (${tag} ${Math.round(est)}px at ${size}px, box is ${Math.round(width)}px) — reduce fontSize, shorten the text, or widen the box. Call measure_text for exact numbers.`,)}}}+ if (overflowHits > 3) issues.push(`…and ${overflowHits - 3} more overflowing text elements.`)- // 5. tiny text — illegible at presentation size+ // 6. tiny text — illegible at presentation sizeconst tiny = texts.filter((t) => typeof t.fontSize === 'number' && t.fontSize > 0 && t.fontSize < 14)if (tiny.length) issues.push(`${tiny.length} text element(s) use fontSize under 14 — too small to read; raise them to at least 14.`)+ // 7. decorative color strips: a required color that appears ONLY as+ // bare strips (thin bars with nothing on them) satisfies the color+ // check without being design — flag it (v0.29.3)+ const required = (brief?.requiredColors ?? []).filter((c) => !c.tier || c.tier === 'mandatory')+ for (const req of required) {+ const want = parseColor(req.hex)+ if (!want) continue+ let realUse = 0+ let stripUse = 0+ let stripExample = ''+ if (pageBg && Math.round(pageBg.r) === Math.round(want.r) && Math.round(pageBg.g) === Math.round(want.g) && Math.round(pageBg.b) === Math.round(want.b)) {+ realUse += 1 // the page background itself is the best use+ continue+ }+ for (const el of els) {+ const fill = parseColor(el.fill)+ const stroke = parseColor(el.stroke)+ const usesIt = (c: RGB | null) => c && Math.round(c.r) === Math.round(want.r) && Math.round(c.g) === Math.round(want.g) && Math.round(c.b) === Math.round(want.b)+ if (!usesIt(fill) && !usesIt(stroke)) continue+ if (el.type === 'text') {+ realUse += 1+ continue+ }+ const w = el.width ?? 0+ const h = el.height ?? 0+ const thin = (w > 0 && h > 0 && (w / h >= 6 || h / w >= 6)) || h <= 56 || w <= 56+ const carriesText = texts.some((t) => coverage(t, el) >= 0.4)+ if (thin && !carriesText) {+ stripUse += 1+ if (!stripExample) stripExample = `${el.type}#${el.id} (${Math.round(w)}x${Math.round(h)})`+ } else {+ realUse += 1+ }+ }+ if (realUse === 0 && stripUse > 0) {+ issues.push(+ `Required color ${req.hex.toUpperCase()} appears only as a bare decorative strip (${stripExample}) — use it as the page background, a text fill, or a real panel/card fill instead.`,+ )+ }+ }+return issues.slice(0, 12)}++export { luminance, contrastRatio }++/** String-friendly contrast (hex or rgba) for client-side guards. */+export function contrastBetween(a: string, b: string): number {+ const ca = parseColor(a)+ const cb = parseColor(b)+ if (!ca || !cb) return 0+ return contrastRatio(ca, cb)+}diff --git a/src/lib/agent/brief.ts b/src/lib/agent/brief.tsindex e7b657e..73bb378 100644--- a/src/lib/agent/brief.ts+++ b/src/lib/agent/brief.ts@@ -22,11 +22,25 @@ export interface BriefConstraint {tier: 'mandatory' | 'preference' | 'optional'}+/** A composite design deliverable the user named explicitly (v0.29.3):+ * "a realistic editor mockup", "3 feature cards", "glassmorphism".+ * These are REQUIREMENTS, not decoration — the validator checks that+ * the corresponding native, editable elements actually exist. */+export interface RequiredFeature extends BriefConstraint {+ kind: 'editor-mockup' | 'feature-cards' | 'glassmorphism'+ /** for feature-cards: how many cards the user asked for */+ count?: number+ /** human label for prompts and unmet messages */+ label: string+}+export interface DesignBrief {/** exact strings the user quoted or demanded — checked verbatim */requiredTexts: (BriefConstraint & { text: string; role?: string })[]/** exact hex colors — checked case-insensitively against the page */requiredColors: (BriefConstraint & { hex: string; role?: string })[]+ /** composite deliverables (mockup, cards, glassmorphism) */+ requiredFeatures?: RequiredFeature[]/** canvas dimensions in px */dimensions?: BriefConstraint & { width: number; height: number }/** detected platform/format ("instagram-post", "story", "poster"…) */@@ -103,10 +117,33 @@ export function extractBrief(message: string, pageWidth?: number, pageHeight?: nrequiredTexts.push({ tier: 'mandatory', text })}}- // "headline X", "say Y", "text Z" unquoted patterns → mandatory too- for (const mm of m.matchAll(/\b(?:headline|title|heading|saying|text|tagline|copy|cta)\s*(?:should\s*(?:be|say|read)|:|=|is|says|reads)?\s*[“"']?([A-Z][^.\n“"']{2,80})[”"']?/gi)) {- const text = mm[1].trim()- if (text && !seen.has(text.toLowerCase())) {+ // "headline: X", "title = Y", "tagline should read Z" unquoted+ // patterns → mandatory too.+ //+ // v0.29.3 REGRESSION GUARD (found on the failed CANVIX production+ // run): the old pattern had an OPTIONAL separator and the /i flag,+ // so "Exact text only:" matched as keyword "text" + capture+ // "only:" — manufacturing a FAKE mandatory string that the agent+ // then placed on the canvas as a real requirement. Three guards now:+ // 1. the separator (:, =, "should be/say/read", "is", …) is+ // REQUIRED between the keyword and the payload;+ // 2. the payload must START WITH A CAPITAL LETTER (matched with+ // a case-sensitive test — real headlines do);+ // 3. known instruction words ("only", "exactly", …) are never+ // valid payloads. Quoted strings already captured above win.+ const UNQUOTED_RE =+ /\b(?:headline|title|heading|saying|tagline|copy|cta|text)\s*(?::|=|should\s+(?:be|say|read)|is|says|reads)?\s*[\"'\u201c\u201d]?([^\n\"'\u201c\u201d.]{2,80})[\"'\u201c\u201d]?/gi+ const STOPWORDS = new Set(['only', 'exactly', 'verbatim', 'character', 'characters', 'word', 'words', 'list', 'following', 'these', 'below', 'above', 'here'])+ for (const mm of m.matchAll(UNQUOTED_RE)) {+ const text = mm[1].trim().replace(/[,;:]\s*$/, '')+ if (!text) continue+ const first = text.split(/\s+/)[0].toLowerCase().replace(/[^a-z]/g, '')+ if (STOPWORDS.has(first)) continue+ // payload must start with a capital letter (case-sensitive)+ if (!/^[A-Z]/.test(text)) continue+ // a quoted list after the keyword is the payload — never also+ // capture the prose between keyword and the first quote+ if (!seen.has(text.toLowerCase())) {seen.add(text.toLowerCase())requiredTexts.push({ tier: 'mandatory', text, role: 'heading' })}@@ -123,6 +160,37 @@ export function extractBrief(message: string, pageWidth?: number, pageHeight?: n}}+ // composite deliverables the user NAMED — these are requirements,+ // not decoration (v0.29.3: "realistic editor mockup", "3 feature+ // cards", "glassmorphism" became verifiable contract fields)+ const requiredFeatures: RequiredFeature[] = []+ const lowerText = m.toLowerCase()+ if (/\bmockup\b/i.test(m)) {+ requiredFeatures.push({+ tier: 'mandatory',+ kind: 'editor-mockup',+ label: 'a realistic editor mockup (a large native panel containing inner UI elements)',+ })+ }+ const cardCount = lowerText.match(/(\d+|three|two|four|five)\s*(?:feature\s*)?cards?\b/)+ if (cardCount) {+ const words: Record<string, number> = { two: 2, three: 3, four: 4, five: 5 }+ const n = /^\d+$/.test(cardCount[1]) ? Number(cardCount[1]) : (words[cardCount[1]] ?? 2)+ requiredFeatures.push({+ tier: 'mandatory',+ kind: 'feature-cards',+ count: Math.min(Math.max(n, 1), 8),+ label: `${Math.min(Math.max(n, 1), 8)} feature cards (semi-transparent native rect + text)`,+ })+ }+ if (/\bglassmorphism\b|\bfrosted\s+glass\b/i.test(m)) {+ requiredFeatures.push({+ tier: 'mandatory',+ kind: 'glassmorphism',+ label: 'glassmorphism (semi-transparent rgba fills with visible borders)',+ })+ }+// explicit dimensionsconst dims = m.match(DIMENSIONS_RE)let dimensions: DesignBrief['dimensions'] | undefined@@ -166,6 +234,7 @@ export function extractBrief(message: string, pageWidth?: number, pageHeight?: nreturn {requiredTexts,requiredColors,+ ...(requiredFeatures.length ? { requiredFeatures } : {}),dimensions,format,designType,@@ -187,10 +256,103 @@ export interface BriefValidationResult {checked: {text: { text: string; found: boolean }[]color: { hex: string; found: boolean }[]+ features?: { label: string; found: boolean }[]dimensions?: { width: number; height: number; match: boolean }}}+/** Minimal element shape the feature validator needs — the client+ * sends this alongside texts/colors (v0.29.3). */+export interface BriefElementLike {+ type: string+ x?: number+ y?: number+ width?: number+ height?: number+ fill?: string+ stroke?: string+ text?: string+}++/** Parse "#RRGGBB" or "rgba(r,g,b,a)" → {r,g,b,a} (a defaults 1); null unparseable.+ * Exported for the audit's effective-background math (shared color model). */+export function parseColor(c: unknown): { r: number; g: number; b: number; a: number } | null {+ if (typeof c !== 'string') return null+ const s = c.trim()+ const hex = /^#?([0-9a-f]{6})$/i.exec(s)+ if (hex) {+ const n = parseInt(hex[1], 16)+ return { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255, a: 1 }+ }+ const rgx =+ /^rgba?\(\s*(\d{1,3})[\s,]+(\d{1,3})[\s,]+(\d{1,3})(?:[\s,/]+([\d.]+%?))?\s*\)$/i.exec(s)+ if (rgx) {+ const a = rgx[4] === undefined ? 1 : rgx[4].endsWith('%') ? Number(rgx[4].slice(0, -1)) / 100 : Number(rgx[4])+ return { r: Number(rgx[1]), g: Number(rgx[2]), b: Number(rgx[3]), a: Math.min(Math.max(a || 0, 0), 1) }+ }+ return null+}++/** Element center inside another's bounds (with tolerance). */+function centerInside(el: BriefElementLike, host: BriefElementLike): boolean {+ const cx = (el.x ?? 0) + (el.width ?? 0) / 2+ const cy = (el.y ?? 0) + (el.height ?? 0) / 2+ return (+ cx >= (host.x ?? 0) && cx <= (host.x ?? 0) + (host.width ?? 0) &&+ cy >= (host.y ?? 0) && cy <= (host.y ?? 0) + (host.height ?? 0)+ )+}++/** Structural validation of the composite deliverables (v0.29.3).+ * Heuristics on purpose — a FALSE PASS here hides a missing+ * deliverable; a false failure only costs one extra build step. */+function validateFeatures(+ features: RequiredFeature[],+ els: BriefElementLike[],+): { label: string; found: boolean }[] {+ const rects = els.filter((e) => e.type === 'rect' && (e.width ?? 0) > 0 && (e.height ?? 0) > 0)+ const texts = els.filter((e) => e.type === 'text' && e.text)+ const out: { label: string; found: boolean }[] = []++ for (const f of features) {+ if (f.kind === 'editor-mockup') {+ // a large panel with ≥3 inner elements, at least one non-text+ // (toolbar/canvas chrome) — built from native elements+ const found = rects.some((r) => {+ if ((r.width ?? 0) < 160 || (r.height ?? 0) < 110) return false+ const inner = els.filter((e) => e !== r && centerInside(e, r))+ return inner.length >= 3 && inner.some((e) => e.type !== 'text')+ })+ out.push({ label: f.label, found })+ } else if (f.kind === 'feature-cards') {+ // semi-transparent or stroked rects, each carrying 1-2 texts+ const need = f.count ?? 2+ const cards = rects.filter((r) => {+ const w = r.width ?? 0+ const h = r.height ?? 0+ if (w < 80 || h < 60 || w > 640 || h > 640) return false+ const fill = parseColor(r.fill)+ const semi = fill !== null && fill.a <= 0.92+ const stroked = typeof r.stroke === 'string' && r.stroke.trim().length > 0+ if (!semi && !stroked) return false+ const inside = texts.filter((t) => centerInside(t, r))+ return inside.length >= 1 && inside.length <= 3+ })+ out.push({ label: f.label, found: cards.length >= need })+ } else if (f.kind === 'glassmorphism') {+ // ≥2 semi-transparent elements with visible structure (fill+ // alpha 0.03–0.6); a border on at least one+ const glass = els.filter((e) => {+ const fill = parseColor(e.fill)+ return fill !== null && fill.a >= 0.03 && fill.a <= 0.6+ })+ const bordered = glass.some((e) => typeof e.stroke === 'string' && e.stroke.trim().length > 0)+ out.push({ label: f.label, found: glass.length >= 2 && bordered })+ }+ }+ return out+}+/** Validate a brief against REAL page state (post-apply, refreshed).* Pure — the caller supplies what the client sent back. */export function validateBrief(@@ -201,6 +363,9 @@ export function validateBrief(colors: string[]width: numberheight: number+ /** flattened page elements — enables feature validation (optional+ * so older callers keep working) */+ elements?: BriefElementLike[]},): BriefValidationResult {const unmet: string[] = []@@ -223,6 +388,13 @@ export function validateBrief(if (!found) unmet.push(`Required color #${c.hex.slice(1).toUpperCase()} not used anywhere on the page`)return { hex: c.hex, found }})+ let features: BriefValidationResult['checked']['features']+ if (brief.requiredFeatures?.length && state.elements?.length) {+ features = validateFeatures(brief.requiredFeatures, state.elements)+ for (const f of features) {+ if (!f.found) unmet.push(`Required element missing: ${f.label} — build it from NATIVE elements (rect panels, semi-transparent fills, borders, text).`)+ }+ }let dimensions: BriefValidationResult['checked']['dimensions']if (brief.dimensions && brief.dimensions.tier === 'mandatory') {const match = state.width === brief.dimensions.width && state.height === brief.dimensions.height@@ -231,7 +403,7 @@ export function validateBrief(unmet.push(`Canvas must be ${brief.dimensions.width}×${brief.dimensions.height} (currently ${state.width}×${state.height})`)}}- return { satisfied: unmet.length === 0, unmet, checked: { text, color, dimensions } }+ return { satisfied: unmet.length === 0, unmet, checked: { text, color, features, dimensions } }}/** Compact one-line serialization for the system prompt. */@@ -248,6 +420,10 @@ export function briefPromptSection(brief: DesignBrief): string {if (brief.requiredColors.length) {parts.push(`· EXACT colors (use these hex values verbatim): ${brief.requiredColors.map((c) => c.hex.toUpperCase()).join(' ')}`)}+ if (brief.requiredFeatures?.length) {+ parts.push(`· REQUIRED ELEMENTS (build these as real native, editable elements — they are deliverables, not decoration): ${brief.requiredFeatures.map((f) => f.label).join('; ')}`)+ parts.push('· COLOR USAGE RULE: required colors must appear as the page background, text fills, or panel/card fills and borders — NEVER as bare decorative strips or bars with no content on them.')+ }if (brief.restrictions.length) parts.push(`· Restrictions: ${brief.restrictions.join('; ')}`)if (brief.notes.length) parts.push(`· Notes: ${brief.notes.join('; ')}`)parts.push('Brand kit and templates may FILL GAPS only — they never override the exact values above.')diff --git a/src/lib/agent/context.ts b/src/lib/agent/context.tsindex 40cab37..380cc99 100644--- a/src/lib/agent/context.ts+++ b/src/lib/agent/context.ts@@ -23,11 +23,18 @@ export interface AgentElementCtx {height?: numbertext?: stringfill?: string+ /** v0.29.3: border color (glassmorphism/feature-card validation) */+ stroke?: stringfontSize?: numberbold?: booleanfontFamily?: stringname?: stringlocked?: boolean+ /** 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+ * uses it instead of the glyph-average estimate. */+ measuredWidth?: number}export interface AgentDesignCtx {@@ -51,7 +58,8 @@ export interface AgentDesignCtx {otherPages?: string[]/** v0.29: page background hex (solid backgrounds) — enables the* contrast part of the quality audit; optional, older clients simply- * omit it and the audit falls back to the dominant in-use color. */+ * omit it and the audit falls back to per-text backdrops only.+ * v0.29.3: NEVER guessed — the audit uses only this real field. */background?: string}@@ -62,7 +70,9 @@ function elementLine(e: AgentElementCtx, selected: boolean): string {if (selected) parts.push('[SELECTED]')if (e.text) parts.push(`text="${e.text.slice(0, 60).replace(/\n/g, ' ')}"`)if (e.fill) parts.push(e.fill)+ if (e.stroke) parts.push(`border:${e.stroke}`)if (e.fontSize) parts.push(`${Math.round(e.fontSize)}px`)+ if (e.measuredWidth && e.text) parts.push(`measured:${Math.round(e.measuredWidth)}px`)if (e.bold) parts.push('bold')if (e.fontFamily) parts.push(e.fontFamily)if (Number.isFinite(e.x) && Number.isFinite(e.y)) {@@ -78,6 +88,7 @@ export function serializeDesignContext(d: AgentDesignCtx): string {const selected = new Set(d.selectedIds ?? [])const lines: string[] = [`Design: "${d.name ?? 'Untitled'}" — ${d.width ?? '?'}x${d.height ?? '?'}px (${d.templateType ?? 'custom'}), ${d.pageCount ?? 1} page(s), editing page ${(d.currentPageIndex ?? 0) + 1}.`,+ `Page background: ${d.background ?? '(not solid — not reported)'}. Elements are listed bottom-to-top (later = in front).`,`Selection: ${selected.size ? [...selected].join(', ') : 'none'}.`,]if (d.brand && ((d.brand.colors?.length ?? 0) > 0 || d.brand.headingFont)) {diff --git a/src/lib/agent/harness.test.ts b/src/lib/agent/harness.test.tsindex a64eb59..f99af7f 100644--- a/src/lib/agent/harness.test.ts+++ b/src/lib/agent/harness.test.ts@@ -25,11 +25,12 @@ import { describe, it, expect } from 'vitest'import { parseAgentTurn, sseLine, AGENT_GUARDS, AGENT_PROTOCOL_VERSION, type AgentEvent } from './protocol'import { AGENT_TOOL_MAP, AGENT_TOOLS, type ToolContext, type SanitizeResult } from './tools'import { runAgentLoop, toolsForMode, loopSystemPrompt } from './loop'-import { auditDesign, contrastRatio } from './audit'+import { auditDesign, contrastBetween } from './audit'import { heuristicMode, parseMode, modeAllowsWrites, MODE_TOOL_RISK } from './router'import { DESIGN_SKILLS, selectSkills, skillsPromptSection } from './skills'import { extractBrief, validateBrief, briefPromptSection, FORMAT_PRESETS, type DesignBrief } from './brief'import { serializeDesignContext, contextValidIds, type AgentDesignCtx } from './context'+import type { VisionCritiqueResult } from './vision'import type { AgentMode } from './protocol'// ── fixtures ─────────────────────────────────────────────────@@ -105,7 +106,7 @@ describe('harness · tool matrix', () => {'duplicate_elements', 'group_elements', 'ungroup_elements', 'reorder_layers','animate_elements', 'set_page_transition', 'delete_page', 'set_brand_kit', 'resize_design','mask_image', 'adjust_image', 'measure_text', 'set_text_spans', 'export_design',- 'add_stock_video', 'validate_brief',+ 'add_stock_video', 'validate_brief', 'plan_layout',]for (const t of AGENT_TOOLS) expect(covered, `add harness cases for new tool "${t.name}"`).toContain(t.name)expect(covered).toHaveLength(AGENT_TOOLS.length)@@ -261,9 +262,9 @@ describe('harness · tool matrix', () => {const destructive = AGENT_TOOLS.filter((t) => t.risk === 'destructive').map((t) => t.name)expect(destructive.sort()).toEqual(['clear_page', 'delete_elements', 'delete_page'])})- it('read tools are exactly the state/measure/validate set', () => {+ it('read tools are exactly the state/measure/validate/plan set', () => {const reads = AGENT_TOOLS.filter((t) => t.risk === 'read').map((t) => t.name)- expect(reads.sort()).toEqual(['get_page_state', 'goto_page', 'measure_text', 'validate_brief'])+ expect(reads.sort()).toEqual(['get_page_state', 'goto_page', 'measure_text', 'plan_layout', 'validate_brief'])})it('CASE G: quality audit — one self-critique fix round before done is accepted', async () => {@@ -504,8 +505,8 @@ describe('harness · brief contract', () => {// ═════════════════════════════════════════════════════════════describe('harness · skills engine', () => {- it('ten skills ship, each with a complete playbook', () => {- expect(DESIGN_SKILLS).toHaveLength(10)+ it('thirteen skills ship, each with a complete playbook', () => {+ expect(DESIGN_SKILLS).toHaveLength(13)for (const s of DESIGN_SKILLS) {expect(s.id).toBeTruthy()expect(s.playbook.principles.length).toBeGreaterThanOrEqual(4)@@ -1016,9 +1017,9 @@ describe('harness · wire format + context', () => {describe('audit heuristics (v0.29)', () => {it('WCAG contrast math — white on black ≈ 21:1, dark on dark < 1.2:1', () => {- expect(Math.round(contrastRatio('#FFFFFF', '#000000'))).toBe(21)- expect(contrastRatio('#111122', '#090B1A')).toBeLessThan(1.2)- expect(contrastRatio('not-a-color', '#000000')).toBe(0)+ expect(Math.round(contrastBetween('#FFFFFF', '#000000'))).toBe(21)+ expect(contrastBetween('#111122', '#090B1A')).toBeLessThan(1.2)+ expect(contrastBetween('not-a-color', '#000000')).toBe(0)})it('auditDesign flags low contrast, overflow, tiny text, overlaps and off-canvas', () => {@@ -1037,20 +1038,469 @@ describe('audit heuristics (v0.29)', () => {})const joined = issues.join('\n')expect(joined).toContain('Low contrast')- expect(joined).toContain('may overflow')+ expect(joined).toContain('overflows its box')expect(joined).toContain('under 14')expect(joined).toContain('overlap')expect(joined).toContain('outside the canvas')})- it('auditDesign falls back to the dominant color when background is absent; clean canvas → no issues', () => {+ it('v0.29.3: no page background → NO fabricated dominant-color backdrop; clean canvas → no issues', () => {+ // the failed production run audited contrast against a GUESSED+ // "first hex in colorsInUse" — the wrong backdrop produced wrong+ // findings. The audit now needs the REAL page background (or a+ // card behind the text); unknown backdrop → no page-level+ // contrast claims at all.const issues = auditDesign({width: 1080,height: 1080,elements: [{ id: 'b1', type: 'text', text: 'Dark', fill: '#111122', fontSize: 48, x: 0, y: 0, width: 600, height: 90 }],colorsInUse: ['#090B1A'],})- expect(issues.join('\n')).toContain('Low contrast')+ expect(issues.join('\n')).not.toContain('Low contrast')+ // with the real background present, the same text IS flagged+ const flagged = auditDesign({+ width: 1080,+ height: 1080,+ background: '#090B1A',+ elements: [{ id: 'b1', type: 'text', text: 'Dark', fill: '#111122', fontSize: 48, x: 0, y: 0, width: 600, height: 90 }],+ })+ expect(flagged.join('\n')).toContain('Low contrast')expect(auditDesign({ width: 1080, height: 1080, background: '#FFFFFF', elements: [{ id: 'c1', type: 'text', text: 'OK', fill: '#111111', fontSize: 32, x: 0, y: 0, width: 300, height: 60 }] })).toEqual([])})})+++// ═════════════════════════════════════════════════════════════+// v0.29.3 REGRESSION SUITE — the failed CANVIX production run+// (1080×1080 promo poster: "only:" phantom requirement, decorative+// color strips, text clipped/obscured, vision critique after the+// fact, "Music Festival" summary, reactive add/move loops)+// ═════════════════════════════════════════════════════════════++const CANVIX_PROMPT =+ 'Create a premium 1080×1080 promo poster for CANVIX. Exact text only: \u201cCANVIX\u201d, \u201cDesign Beyond Limits.\u201d, \u201cYour imagination. Our canvas.\u201d, \u201cAI-Powered Design\u201d, \u201c366+ Templates\u201d, \u201cStart Creating Free\u201d, \u201ccanvix.app\u201d. Use #090B1A, #8B5CF6, #22D3EE, #F8FAFC, #A1A1AA. Add a realistic editor mockup, 3 feature cards, glassmorphism, strong spacing, no clipping, no overlaps, no decorative lines over text. Use native editable elements. Fix issues before finishing.'++describe('v0.29.3 · brief extraction (the "only:" bug)', () => {+ it('the EXACT failed production prompt yields the seven user strings — and never "only:"', () => {+ const brief = extractBrief(CANVIX_PROMPT, 1080, 1080)+ expect(brief.requiredTexts.map((t) => t.text)).toEqual([+ 'CANVIX',+ 'Design Beyond Limits.',+ 'Your imagination. Our canvas.',+ 'AI-Powered Design',+ '366+ Templates',+ 'Start Creating Free',+ 'canvix.app',+ ])+ expect(brief.requiredTexts.some((t) => t.text === 'only:')).toBe(false)+ expect(brief.requiredColors.map((c) => c.hex)).toEqual(['#090b1a', '#8b5cf6', '#22d3ee', '#f8fafc', '#a1a1aa'])+ expect(brief.dimensions).toEqual({ tier: 'mandatory', width: 1080, height: 1080 })+ })++ it('"Exact text only:" never manufactures a requirement — the instruction tail is not content', () => {+ for (const msg of [+ 'Exact text only: "A", "B"',+ 'Text only: hello world',+ 'exact TEXT ONLY: "X"',+ 'Copy: only the best will do', // keyword+separator, payload starts lowercase → ignored+ ]) {+ const brief = extractBrief(msg, 1080, 1080)+ expect(brief.requiredTexts.some((t) => /only/i.test(t.text))).toBe(false)+ }+ })++ it('unquoted headline patterns still extract when a real separator exists', () => {+ const brief = extractBrief('headline: Summer Sale Blast', 1080, 1080)+ expect(brief.requiredTexts.map((t) => t.text)).toContain('Summer Sale Blast')+ const brief2 = extractBrief('title = "Night Market"', 1080, 1080)+ expect(brief2.requiredTexts.map((t) => t.text)).toContain('Night Market')+ })++ it('composite deliverables become mandatory contract fields', () => {+ const brief = extractBrief(CANVIX_PROMPT, 1080, 1080)+ const kinds = brief.requiredFeatures?.map((f) => f.kind)+ expect(kinds).toContain('editor-mockup')+ expect(kinds).toContain('glassmorphism')+ const cards = brief.requiredFeatures?.find((f) => f.kind === 'feature-cards')+ expect(cards?.count).toBe(3)+ })++ it('feature validation: a structurally-correct poster passes; a bare canvas fails with fix guidance', () => {+ const brief = extractBrief(CANVIX_PROMPT, 1080, 1080)+ const good = validateBrief(brief, {+ texts: ['CANVIX', 'Design Beyond Limits.', 'Your imagination. Our canvas.', 'AI-Powered Design', '366+ Templates', 'Start Creating Free', 'canvix.app'],+ colors: ['#090b1a', '#8b5cf6', '#22d3ee', '#f8fafc', '#a1a1aa'],+ width: 1080,+ height: 1080,+ elements: [+ { type: 'rect', x: 80, y: 80, width: 420, height: 280, fill: 'rgba(248,250,252,0.08)', stroke: 'rgba(139,92,246,0.35)' },+ { type: 'rect', x: 100, y: 100, width: 300, height: 24, fill: '#8B5CF6' },+ { type: 'rect', x: 100, y: 140, width: 180, height: 90, fill: 'rgba(34,211,238,0.2)' },+ { type: 'text', x: 120, y: 250, width: 200, height: 30, text: 'Layer 1', fill: '#F8FAFC' },+ { type: 'rect', x: 560, y: 420, width: 200, height: 140, fill: 'rgba(248,250,252,0.1)', stroke: 'rgba(139,92,246,0.3)' },+ { type: 'text', x: 580, y: 470, width: 160, height: 24, text: 'AI-Powered Design', fill: '#F8FAFC' },+ { type: 'rect', x: 560, y: 600, width: 200, height: 140, fill: 'rgba(248,250,252,0.1)', stroke: 'rgba(34,211,238,0.3)' },+ { type: 'text', x: 580, y: 650, width: 160, height: 24, text: '366+ Templates', fill: '#F8FAFC' },+ { type: 'rect', x: 80, y: 600, width: 200, height: 140, fill: 'rgba(248,250,252,0.1)', stroke: 'rgba(139,92,246,0.3)' },+ { type: 'text', x: 100, y: 650, width: 160, height: 24, text: 'Start Creating Free', fill: '#22D3EE' },+ ],+ })+ expect(good.satisfied).toBe(true)+ expect(good.unmet).toEqual([])+ expect(good.checked.features?.every((f) => f.found)).toBe(true)++ const bad = validateBrief(brief, {+ texts: ['CANVIX'],+ colors: ['#090b1a'],+ width: 1080,+ height: 1080,+ elements: [{ type: 'rect', x: 0, y: 0, width: 1080, height: 40, fill: '#8B5CF6' }],+ })+ expect(bad.satisfied).toBe(false)+ expect(bad.unmet.some((u) => u.includes('editor mockup'))).toBe(true)+ expect(bad.unmet.some((u) => u.includes('feature cards'))).toBe(true)+ expect(bad.unmet.some((u) => u.includes('glassmorphism'))).toBe(true)+ })+})++describe('v0.29.3 · router (the discuss misroute)', () => {+ it('the EXACT failed prompt routes to create — brand name + "feature cards" must not trigger the product-discuss guard', () => {+ const h = heuristicMode(CANVIX_PROMPT)+ expect(h.mode).toBe('create')+ expect(h.confidence).toBe('high')+ })++ it('product questions still route to discuss/explain', () => {+ expect(heuristicMode('Why is the Canvix agent broken?').mode).toBe('discuss')+ expect(heuristicMode('How does the poster feature work?').mode).not.toBe('create')+ })+})++describe('v0.29.3 · audit geometry (structural ≠ rendered)', () => {+ it('text on a glass card is judged against the CARD, not the page — intentional layering is preserved', () => {+ const issues = auditDesign({+ width: 1080,+ height: 1080,+ background: '#090B1A',+ elements: [+ // white text on a white-glass card over dark navy: the old+ // page-bg math called this 1.0:1 — wrong backdrop+ { id: 'card', type: 'rect', x: 100, y: 100, width: 400, height: 200, fill: 'rgba(248,250,252,0.08)' },+ { id: 't1', type: 'text', x: 120, y: 150, width: 360, height: 60, text: 'Glass card text', fontSize: 32, fill: '#F8FAFC' },+ ],+ })+ expect(issues.join('\n')).not.toContain('Low contrast')+ })++ it('dark text on a light card IS flagged — the card is the real backdrop', () => {+ const issues = auditDesign({+ width: 1080,+ height: 1080,+ background: '#090B1A',+ elements: [+ { id: 'card', type: 'rect', x: 100, y: 100, width: 400, height: 200, fill: '#F8FAFC' },+ { id: 't1', type: 'text', x: 120, y: 150, width: 360, height: 60, text: 'Dark on light card', fontSize: 32, fill: '#090B1A' },+ ],+ })+ expect(issues.join('\n')).not.toContain('Low contrast') // 15:1+ — correct+ const dark = auditDesign({+ width: 1080,+ height: 1080,+ background: '#F8FAFC',+ elements: [+ { id: 'card', type: 'rect', x: 100, y: 100, width: 400, height: 200, fill: 'rgba(248,250,252,0.9)' },+ { id: 't1', type: 'text', x: 120, y: 150, width: 360, height: 60, text: 'Faint on glass', fontSize: 32, fill: '#94A3B8' },+ ],+ })+ expect(dark.join('\n')).toContain('Low contrast')+ })++ it('an opaque shape ABOVE a text that covers it is reported as obscured — present is not visible', () => {+ const issues = auditDesign({+ width: 1080,+ height: 1080,+ background: '#090B1A',+ elements: [+ { id: 't1', type: 'text', x: 100, y: 100, width: 400, height: 60, text: 'CANVIX', fontSize: 48, fill: '#F8FAFC' },+ { id: 'bar', type: 'rect', x: 0, y: 90, width: 1080, height: 40, fill: '#8B5CF6' }, // ABOVE, covers most of the text+ ],+ })+ expect(issues.join('\n')).toContain('covered by')+ })++ it('a decorative strip is the ONLY use of a required color → flagged, not accepted as compliance', () => {+ const issues = auditDesign(+ {+ width: 1080,+ height: 1080,+ background: '#090B1A',+ elements: [+ { id: 's1', type: 'text', x: 100, y: 100, width: 400, height: 60, text: 'CANVIX', fontSize: 48, fill: '#F8FAFC' },+ { id: 'strip', type: 'rect', x: 20, y: 20, width: 1040, height: 40, fill: '#A1A1AA' },+ ],+ },+ { requiredColors: [{ hex: '#a1a1aa', tier: 'mandatory' }] },+ )+ expect(issues.join('\n')).toContain('bare decorative strip')+ // the same color as a TEXT fill is real usage — no flag+ const ok = auditDesign(+ {+ width: 1080,+ height: 1080,+ background: '#090B1A',+ elements: [{ id: 's1', type: 'text', x: 100, y: 100, width: 400, height: 60, text: 'Footer', fontSize: 24, fill: '#A1A1AA' }],+ },+ { requiredColors: [{ hex: '#a1a1aa', tier: 'mandatory' }] },+ )+ expect(ok.join('\n')).not.toContain('strip')+ })++ it('overflow uses the client-measured width when present (real metrics, not glyph averages)', () => {+ const issues = auditDesign({+ width: 1080,+ height: 1080,+ background: '#090B1A',+ elements: [+ // 14 chars at 72px: the 0.58-avg estimate says ~585px (fits);+ // the REAL measured width is 900px → clips+ { id: 't1', type: 'text', x: 60, y: 100, width: 600, height: 90, text: 'Start Creating Free', fontSize: 72, fill: '#F8FAFC', measuredWidth: 900 },+ ],+ })+ expect(issues.join('\n')).toContain('measured 900px')+ expect(issues.join('\n')).toContain('overflows its box')+ })++ it('unknown page background: no page-level contrast guesses — no fabricated backdrop', () => {+ const issues = auditDesign({+ width: 1080,+ height: 1080,+ elements: [{ id: 't1', type: 'text', x: 100, y: 100, width: 400, height: 60, text: 'Plain', fontSize: 32, fill: '#F8FAFC' }],+ })+ expect(issues.join('\n')).not.toContain('Low contrast')+ })+})++describe('v0.29.3 · loop: vision critique BEFORE completion', () => {+ it('P0 findings drive ONE bounded correction round, then re-capture verifies — done only then', async () => {+ const events: AgentEvent[] = []+ const critiques: string[] = []+ const captures: string[] = []+ const { chat, calls } = scriptedChat([+ turn('set_background', { kind: 'solid', from: '#090B1A' }),+ turn('add_text', { text: 'CANVIX', fontSize: 72, color: '#F8FAFC' }),+ done('Poster complete'),+ turn('move_elements', { ids: ['txt-1'], dx: 0, dy: 40 }),+ done('Poster complete — fixed'),+ ])+ const critique = async (image: string): Promise<VisionCritiqueResult> => {+ critiques.push(image)+ return critiques.length === 1+ ? { findings: [{ severity: 'P0', issue: 'Required text "CANVIX" is missing from the rendered canvas', fix: 'Add it verbatim' }], note: 'first pass' }+ : { findings: [{ severity: 'P2', issue: 'minor spacing' }], note: 'second pass' }+ }+ const result = await runAgentLoop({+ chat,+ design,+ mode: 'create',+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ captureCanvas: async () => {+ captures.push('shot')+ return 'data:image/png;base64,AAA'+ },+ critique,+ })+ expect(critiques).toHaveLength(2) // initial + verification+ expect(captures).toHaveLength(2)+ expect(result.toolCalls).toBe(3) // the correction applied a 4th tool call+ // the correction message reached the model+ expect(calls.some((c) => c.some((m) => m.content.includes('VISION CRITIQUE of the RENDERED canvas')))).toBe(true)+ const finalEvent = events[events.length - 1] as { type: string; verification?: string }+ expect(finalEvent.type).toBe('done')+ expect(String(finalEvent.verification)).toMatch(/PASSED|no P0 defects/)+ expect(result.findings?.some((f) => f.severity === 'P0')).toBe(false)+ })++ it('P0 defects that SURVIVE the correction round block a success claim — summary says INCOMPLETE', async () => {+ const events: AgentEvent[] = []+ const { chat } = scriptedChat([+ turn('set_background', { kind: 'solid', from: '#090B1A' }),+ done('Poster complete'),+ turn('update_elements', { ids: ['txt-1'], fill: '#F8FAFC' }),+ done('Poster complete — attempted'),+ ])+ const result = await runAgentLoop({+ chat,+ design,+ mode: 'create',+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ captureCanvas: async () => 'data:image/png;base64,AAA',+ critique: async (): Promise<VisionCritiqueResult> => ({ findings: [{ severity: 'P0', issue: 'CANVIX still clipped to "Start Cr"' }], note: 'still broken' }),+ })+ const finalEvent = events[events.length - 1] as { type: string; summary?: string; verification?: string }+ expect(finalEvent.type).toBe('done')+ expect(String(finalEvent.summary)).toContain('INCOMPLETE')+ expect(String(finalEvent.verification)).toContain('NOT visually verified')+ expect(String(finalEvent.verification)).toContain('P0')+ expect(result.summary).toContain('INCOMPLETE')+ })++ it('no capture (timeout) → disclosed as unverified, never silently skipped', async () => {+ const events: AgentEvent[] = []+ const { chat } = scriptedChat([+ turn('set_background', { kind: 'solid', from: '#090B1A' }),+ done('Poster complete'),+ ])+ const result = await runAgentLoop({+ chat,+ design,+ mode: 'create',+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ captureCanvas: async () => null,+ critique: async () => ({ findings: [], note: 'never called' }),+ })+ expect(String(result.verification)).toContain('UNAVAILABLE')+ expect(String(result.verification)).toContain('NOT verified')+ })++ it('no vision model configured → honest disclosure, no critique call', async () => {+ const { chat } = scriptedChat([+ turn('set_background', { kind: 'solid', from: '#090B1A' }),+ done('Poster complete'),+ ])+ const result = await runAgentLoop({+ chat,+ design,+ mode: 'create',+ emit: () => {},+ awaitApply: async () => ({ ok: true }),+ captureCanvas: async () => 'data:image/png;base64,AAA',+ critique: async () => null,+ })+ expect(String(result.verification)).toContain('unavailable')+ })+})++describe('v0.29.3 · loop: planning + fail-closed acks', () => {+ it('plan_layout streams a plan event and sets the execution frame', async () => {+ const events: AgentEvent[] = []+ const { chat } = scriptedChat([+ turn('plan_layout', {+ background: '#090B1A',+ sections: [+ { name: 'headline', y: 60, height: 140, contains: 'CANVIX' },+ { name: 'tagline', y: 220, height: 80, contains: 'Design Beyond Limits.' },+ ],+ }),+ turn('set_background', { kind: 'solid', from: '#090B1A' }),+ done('Done'),+ ])+ const result = await runAgentLoop({ chat, design, mode: 'create', emit: (e) => events.push(e), awaitApply: async () => ({ ok: true }) })+ const planEvent = events.find((e) => e.type === 'plan') as { steps?: string[] } | undefined+ expect(planEvent).toBeTruthy()+ expect(planEvent?.steps?.join('\n')).toContain('headline')+ expect(result.steps).toBe(2) // plan_layout + set_background each count as a step+ })++ it('plan_layout rejects stacked bands with actionable guidance', () => {+ const tool = AGENT_TOOL_MAP.get('plan_layout')+ expect(tool).toBeTruthy()+ const res = tool!.sanitize(+ {+ sections: [+ { name: 'a', y: 100, height: 200, contains: 'x' },+ { name: 'b', y: 250, height: 200, contains: 'y' },+ ],+ },+ ctx,+ )+ expect(res.ok).toBe(true)+ expect(String((res as { observation?: string }).observation)).toContain('PLAN WARNINGS')+ })++ it('a failed (timed-out) apply ack tells the model the action was NOT applied — fail closed', async () => {+ const { chat, calls } = scriptedChat([+ turn('set_background', { kind: 'solid', from: '#090B1A' }),+ done('Wrapped up'),+ ])+ const result = await runAgentLoop({+ chat,+ design,+ mode: 'create',+ emit: () => {},+ // v0.29.3 route semantics: timeout resolves ok:false+ awaitApply: async () => ({ ok: false, message: 'ack timeout — the client did NOT confirm the apply' }),+ })+ expect(result.toolCalls).toBe(0) // the un-confirmed action never counts+ expect(calls.some((c) => c.some((m) => m.content.includes('NOT confirm the apply') || m.content.includes('was not verified as changed')))).toBe(true)+ })+})+++// ═════════════════════════════════════════════════════════════+// v0.29.4 REGRESSION — "ask him anything and it builds sunset"+// ═════════════════════════════════════════════════════════════++describe('v0.29.4 · greetings and chitchat never trigger a build', () => {+ it.each(['hi', 'hey there', 'thanks!', 'ok cool', 'hello', 'test', 'thank you so much', 'yo!'])(+ '"%s" routes to discuss with HIGH confidence — no model router call, no invented build task',+ (msg) => {+ const h = heuristicMode(msg)+ expect(h.mode).toBe('discuss')+ expect(h.confidence).toBe('high')+ },+ )++ it('a REAL build brief still routes to create after the greeting guard', () => {+ expect(heuristicMode(CANVIX_PROMPT).mode).toBe('create')+ expect(heuristicMode('make me a poster for a pizza place').mode).toBe('create')+ })++ it('longer conversational messages are not hijacked by the greeting guard', () => {+ // not pure greeting → falls through to the normal ladder (edit here)+ expect(['edit', 'discuss', 'create']).toContain(heuristicMode('make the title bold').mode)+ })+})++describe('v0.29.4 · new skills (glassmorphism, mockups, accessibility)', () => {+ it('the failed CANVIX prompt selects glassmorphism + mockups alongside the poster skill', () => {+ const skills = selectSkills(CANVIX_PROMPT, 'create')+ const ids = skills.map((s) => s.id)+ expect(ids).toContain('poster-design')+ expect(ids).toContain('glassmorphism-ui')+ expect(ids).toContain('realistic-mockups')+ })++ it('accessibility asks select the accessibility skill', () => {+ const ids = selectSkills('improve the contrast and accessibility of this design', 'improve').map((s) => s.id)+ expect(ids).toContain('visual-accessibility')+ })++ it('the glassmorphism playbook teaches rgba fill + border + contrast on the composited backdrop', () => {+ const glass = DESIGN_SKILLS.find((s) => s.id === 'glassmorphism-ui')+ expect(glass).toBeTruthy()+ const text = JSON.stringify(glass!.playbook)+ expect(text).toContain('rgba')+ expect(text.toLowerCase()).toContain('composited')+ expect(text.toLowerCase()).toContain('contrast')+ })++ it('the mockup playbook requires a composite, never one empty rectangle', () => {+ const mock = DESIGN_SKILLS.find((s) => s.id === 'realistic-mockups')+ expect(mock).toBeTruthy()+ const text = JSON.stringify(mock!.playbook)+ expect(text).toContain('title bar')+ expect(text).toContain('sidebar')+ expect(text.toLowerCase()).toContain('composite')+ // the exact structural floor the brief validator enforces+ expect(text).toContain('160×110')+ })++ it('skillsPromptSection discloses the selected new skills', () => {+ const section = skillsPromptSection(selectSkills(CANVIX_PROMPT, 'create'))+ expect(section).toContain('Skill: Glassmorphism')+ expect(section).toContain('Skill: Realistic Product Mockups')+ })+})diff --git a/src/lib/agent/loop.ts b/src/lib/agent/loop.tsindex 52184ae..f04aad2 100644--- a/src/lib/agent/loop.ts+++ b/src/lib/agent/loop.ts@@ -34,6 +34,7 @@ import { serializeDesignContext, contextValidIds, type AgentDesignCtx } from './import { MODE_PROMPTS, MODE_TOOL_RISK } from './router'import { skillsPromptSection, selectSkills, type DesignSkill } from './skills'import { briefPromptSection, type DesignBrief } from './brief'+import type { VisionCritiqueResult } from './vision'/** The model client the loop needs — a thin callable so the loop is* unit-testable without the SDK. */@@ -49,6 +50,14 @@ export interface LoopDeps {* (contrast/overlap/overflow heuristics). The loop runs ONE* auto-fix round on its findings before accepting done. */auditDesign?: () => string[] | Promise<string[]>+ /** v0.29.3: ask the CLIENT to screenshot the live canvas (the real+ * render) — resolved with a dataURL, or null on timeout/absence+ * (fail-closed: visual verification is then DISCLOSED as+ * unavailable, never silently skipped). */+ captureCanvas?: () => Promise<string | null>+ /** v0.29.3: grounded vision critique of a captured screenshot.+ * Null when no vision model is configured — the run says so. */+ critique?: (image: string) => Promise<VisionCritiqueResult | null>/** skills pre-selected by the route (or auto-selected here) */skills?: DesignSkill[]/** emitted (by the route) as SSE lines */@@ -59,7 +68,11 @@ export interface LoopDeps {signal?: { aborted: boolean; reason?: string }/** resolve a destructive tool's confirmation (route bridges the SSE pause) */awaitConfirm?: (tool: string) => Promise<boolean>- /** wait for the client's apply ack */+ /** wait for the client's apply ack. v0.29.3: the route's+ * implementation FAILS CLOSED — a timed-out ack resolves+ * {ok:false} so the model is told the action was NOT applied+ * instead of being told it succeeded. (The undefined default+ * exists for the unit-test harness, which has no bridge.) */awaitApply?: () => Promise<{ ok: boolean; message?: string }>/** latest refreshed design context pushed by the client after applying */refreshedContext?: () => AgentDesignCtx@@ -121,6 +134,19 @@ export function loopSystemPrompt(deps: {if (section) lines.push(section, '')}+ if (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.',+ '· 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.',+ '· Feature cards = one semi-transparent rect + its text per card. Glassmorphism = rgba fills with visible borders.',+ '',+ )+ }+const skillSection = skillsPromptSection(skills ?? [])if (skillSection) lines.push(skillSection, '')@@ -137,6 +163,9 @@ export function loopSystemPrompt(deps: {'7. Args must match each tool spec exactly. On an error observation, fix the args and retry — the error message tells you what to change.','8. Tools edit the CURRENT page only. To work on another page: goto_page {page: N}, then get_page_state — ids change with the page. add_page appends the LAST page.','9. In review/explain mode, ground every claim in the state you read. Report missing items as missing — never describe them as present.',+ '10. The document name in the context (e.g. "Music Festival") is just the FILE this request happens to run in — your summary describes what YOU BUILT FOR THIS REQUEST, never the document name. Distinguish "element exists" from "text is readable": only verified readable text counts as done.',+ '11. GROUND IN THE LIVE DESIGN: the element list above IS the current canvas (bottom-to-top z-order; the page background line is real). Build on THAT state — never assume an empty canvas, never re-create what already exists, and never invent imagery or a topic the user did not ask for. If the state looks stale, call get_page_state before acting.',+ '12. Verify-then-stop: before done, see what you actually built — get_page_state for structure, validate_brief for the contract, and (when the run critiques the captured canvas) the vision findings for what is REALLY visible. Fix what the checks report; only then finish. If a check cannot run, say so in the summary instead of claiming it passed.',)return lines.join('\n')}@@ -195,6 +224,15 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {let briefValidated = false/** v0.29: quality-audit fix rounds already used (max 1 per run) */let auditRounds = 0+ /** v0.29.3: grounded vision passes already run (max 2 — initial+ * critique + verification after the correction round) */+ let visionCritiques = 0+ /** v0.29.3: vision-driven correction rounds used (max 1 per run) */+ let visionCorrections = 0+ /** findings from the LAST vision critique (surface in the result) */+ let visionFindings: { severity: 'P0' | 'P1' | 'P2' | 'P3'; issue: string; fix?: string }[] | undefined+ /** true when the final vision pass still saw P0 defects */+ let visionBlocked = false/** done turns rejected by the brief gate — a model that keeps* claiming completion without fixing the unmet items must not* loop forever (LangChain's "declare it blocked" pattern). */@@ -368,8 +406,81 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {: `Quality audit still reports ${issues.length} issue(s) after the fix round — disclosed, not blocking.`}}++ // ── VISION ROUND (v0.29.3): grounded critique of the REAL+ // rendered canvas BEFORE completion is accepted. The failed+ // production runs critiqued AFTER claiming success — P0+ // findings ("CANVIX missing", clipped text, duplicates) could+ // never influence the design. Bounded: one critique now, one+ // correction round, one verification re-capture. A run whose+ // final capture still shows P0 defects does NOT claim success.+ if ((mode === 'create' || mode === 'improve') && deps.critique && visionCritiques < 2) {+ const shot = deps.captureCanvas ? await deps.captureCanvas() : null+ if (!shot) {+ // fail-closed: no capture → visual quality is NOT verified,+ // and the summary says so instead of implying it+ verification = verification+ ? `${verification} Visual critique UNAVAILABLE (canvas capture timed out or no client) — geometry checks only; visual quality NOT verified.`+ : 'Visual critique UNAVAILABLE (canvas capture timed out or no client) — geometry checks only; visual quality NOT verified.'+ visionCritiques = 2 // don't retry the capture path this run+ } else {+ visionCritiques += 1+ const critique = await deps.critique(shot)+ if (!critique) {+ verification = verification+ ? `${verification} Visual critique unavailable (no vision model configured or provider error) — geometry checks only; visual quality NOT verified.`+ : 'Visual critique unavailable (no vision model configured or provider error) — geometry checks only; visual quality NOT verified.'+ visionCritiques = 2+ } else {+ visionFindings = critique.findings+ const critical = critique.findings.filter((f) => f.severity === 'P0' || f.severity === 'P1')+ const emitList = critique.findings.map((f) => `${f.severity} ${f.issue}`).join('\n')+ if (critical.length && visionCorrections === 0) {+ // one bounded correction pass: feed the grounded P0/P1+ // findings to the model, let it fix, then the NEXT done+ // attempt re-captures and verifies (visionCritiques is+ // already 1, so one more pass is allowed)+ visionCorrections += 1+ emit({+ v: AGENT_PROTOCOL_VERSION,+ type: 'observation',+ stepIndex: steps,+ message: `VISION CRITIQUE (grounded in the rendered canvas):\n${emitList}\nA correction pass for the P0/P1 findings follows; P2/P3 are advisory.`,+ })+ messages.push({+ role: 'user',+ content: `VISION CRITIQUE of the RENDERED canvas (a real screenshot — these are grounded findings, not guesses):\n${emitList}\nFix the P0 and P1 findings now with concrete tool calls (missing text → add it verbatim; clipped/hidden text → resize, move or reorder; duplicates → delete the extras; contrast → change fills). Do not restate your plan — act, then emit done again.`,+ })+ continue+ }+ // verification state after the final pass+ const remainingP0 = critique.findings.filter((f) => f.severity === 'P0')+ if (remainingP0.length) {+ visionBlocked = true+ verification = `NOT visually verified — ${remainingP0.length} P0 visual defect(s) remain on the rendered canvas:\n${remainingP0.map((f) => `· ${f.issue}`).join('\n')}\nThe design is NOT confirmed correct; the issues above need a follow-up.`+ summary = `INCOMPLETE — P0 visual defects remain after the correction pass. ${summary}`+ } else if (critical.length) {+ verification = verification+ ? `${verification} Visual critique: P1/P2/P3 findings remain (disclosed) — no P0 defects on the rendered canvas.`+ : `Visual critique: P1/P2/P3 findings remain (disclosed) — no P0 defects on the rendered canvas.`+ } else {+ verification = verification+ ? `${verification} Visual verification PASSED against the rendered canvas — all required content visibly readable.`+ : 'Visual verification PASSED against the rendered canvas — all required content visibly readable.'+ }+ }+ }+ }+emit({ v: AGENT_PROTOCOL_VERSION, type: 'done', summary, steps, toolCalls, verification })- return { summary, steps, toolCalls, findings: turn.findings, plan: turn.plan, verification }+ return {+ summary,+ steps,+ toolCalls,+ findings: [...(turn.findings ?? []), ...(visionFindings ?? [])],+ plan: turn.plan,+ verification,+ }}// ── a tool call ──────────────────────────────────────────@@ -400,12 +511,29 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {const args = (turn.args && typeof turn.args === 'object' && !Array.isArray(turn.args) ? turn.args : {}) as Record<string, unknown>const result = tool.sanitize(args, toolCtx)+ // plan_layout (v0.29.3): read-only planning pseudo-tool — the+ // plan is streamed to the user (the 'plan' event) and echoed as+ // an observation. No apply/ack round trip: a plan changes nothing.+ if (toolName === 'plan_layout' && result.ok) {+ const planLines = (result.actions as { type: string; lines?: string[] }[])+ .flatMap((a) => (a && a.type === '__planLayout' && Array.isArray(a.lines) ? a.lines : []))+ 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 })+ steps += 1+ markProgress()+ messages.push({+ role: 'user',+ content: `${result.observation}\nNow execute the plan: set_background first, then build section by section. Adjust the plan as reality demands — the plan is a reservation of space, not a cage.`,+ })+ continue+ }+// validate_brief is a read-only pseudo-action: the client answers// on the bridge (briefResult), so there is NO apply/ack round// trip — awaiting one dropped the client's early answer (found by// the live NIM eval: 60s ack timeout + lost validation result)- if (toolName === 'validate_brief' && deps.validateBriefOnClient) {- emit({+ if (toolName === 'validate_brief' && deps.validateBriefOnClient) { emit({v: AGENT_PROTOCOL_VERSION,type: 'action',stepIndex: steps,diff --git a/src/lib/agent/protocol.ts b/src/lib/agent/protocol.tsindex 1a40d0e..e40cd16 100644--- a/src/lib/agent/protocol.ts+++ b/src/lib/agent/protocol.ts@@ -93,6 +93,13 @@ export type AgentEvent =| { 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 }+ /** 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+ * model's imagination. The panel answers on the bridge with+ * {capture: {image}}; a timeout is answered with null and the run+ * DISCLOSES that visual verification was unavailable (fail-closed). */+ | { v: number; type: 'capture'; purpose: string }/** the loop compacted older history — the panel may show "context trimmed" */| { v: number; type: 'compact'; fromMessages: number; toMessages: number }| { v: number; type: 'done'; summary: string; steps: number; toolCalls: number; verification?: string }diff --git a/src/lib/agent/router.ts b/src/lib/agent/router.tsindex 5b11e5d..2737741 100644--- a/src/lib/agent/router.ts+++ b/src/lib/agent/router.ts@@ -57,6 +57,43 @@ export function heuristicMode(message: string): { mode: AgentMode; confidence: 'if (!m) return { mode: 'discuss', confidence: 'low' }const lower = m.toLowerCase()+ // v0.29.4 (user report: "ask him anything and it starts building"):+ // greetings and chitchat must NEVER fall through to the model+ // router, where a provider with a bias can invent a build task out+ // of "hi" or "thanks". Pure conversation → discuss, no model call.+ const words = lower.replace(/[^a-z0-9\s']/g, ' ').split(/\s+/).filter(Boolean)+ const GREETINGS = new Set([+ 'hi', 'hey', 'hello', 'yo', 'hiya', 'howdy', 'hallo', 'hola',+ 'thanks', 'thank', 'thx', 'ty', 'cheers', 'ok', 'okay', 'k', 'cool',+ 'nice', 'great', 'awesome', 'perfect', 'good', 'bye', 'cya', 'test',+ 'ping', 'wassup', 'namaste', 'salam', 'sup', 'goodbye', 'morning',+ 'evening', 'afternoon', 'welcome', 'alright', 'right',+ ])+ const CHITCHAT = new Set([+ 'there', 'you', 'so', 'much', 'very', 'again', 'a', 'the', 'to',+ 'too', 'man', 'dude', 'bro', 'yeah', 'yep', 'nope', 'lol', 'wow',+ 'haha', 'hehe', 'um', 'uh', 'well', 'now', 'then', 'and', 'for',+ ])+ const hasGreeting = words.some((w) => GREETINGS.has(w))+ if (hasGreeting && words.length > 0 && words.length <= 5 && words.every((w) => GREETINGS.has(w) || CHITCHAT.has(w))) {+ return { mode: 'discuss', confidence: 'high' }+ }++ // v0.29.3 (found on the failed CANVIX production prompt): an obvious+ // BUILD brief must win over the product-discuss guard below. The+ // prompt "Create a premium 1080×1080 promo poster for CANVIX … 3+ // feature cards …" mentions the brand ("canvix") and the word+ // "feature" — both discuss-guard triggers — even though it is a+ // creation request for a poster ABOUT the product. Artifact noun ++ // build verb + not a question → create, full stop.+ const artifactNoun =+ /\b(poster|flyer|menu|logo|banner|thumbnail|deck|presentation|slide|campaign|invitation|infographic|card|graphic|advert|ad|cover|header|brochure|certificate|resume|newsletter)\b/+ const buildVerb = /\b(design|create|make|build|generate|add|produce)\b/+ const asksQuestion = /\?\s*$/.test(m) || /^(how|why|what|when|which|who)\b/i.test(m)+ if (artifactNoun.test(lower) && buildVerb.test(lower) && !asksQuestion) {+ return { mode: 'create', confidence: 'high' }+ }+// discuss: about the tool/product itself, not the user's designconst productWords = /\b(canvix|the (app|editor|product|repo|codebase)|your (architecture|agent|tools?)|this project|github)\b/const asksAboutProduct = productWords.test(lower) && /\b(how (does|do|is|are)|why|bug|broken|error|architecture|implemented|feature|work)s?\b/.test(lower)@@ -89,8 +126,8 @@ export function heuristicMode(message: string): { mode: AgentMode; confidence: '// create: build briefs. Artifact nouns make intent unambiguous —// "make a poster" is create even though "make" is also a surgical- // edit verb ("make the title bold")- const artifactNoun = /\b(poster|flyer|menu|logo|banner|thumbnail|deck|presentation|slide|campaign|invitation|infographic|card|graphic|advert|ad|cover|header|brochure|certificate|resume|newsletter)\b/+ // edit verb ("make the title bold"). (artifactNoun is declared in+ // the v0.29.3 create-first guard at the top of this function.)if (artifactNoun.test(lower) && m.split(/\s+/).length >= 2) return { mode: 'create', confidence: 'high' }const createSignals = [/\b(design|create|make|build|generate)\b.*\b(a|an|me|the|some)\b/,diff --git a/src/lib/agent/skills.ts b/src/lib/agent/skills.tsindex 41e3f05..c3d55fc 100644--- a/src/lib/agent/skills.ts+++ b/src/lib/agent/skills.ts@@ -325,6 +325,103 @@ export const DESIGN_SKILLS: DesignSkill[] = [],},},+ {+ // v0.29.4: the failed CANVIX production run asked for glassmorphism+ // and got opaque rectangles — the concept had no skill behind it.+ // Playbook informed by public craft standards (NN/g glassmorphism+ // guidance; Axess Lab contrast rules): original Canvix text.+ id: 'glassmorphism-ui',+ name: 'Glassmorphism & Layered Surfaces',+ description: 'Frosted-glass panels, translucent cards, depth layering — rgba fills with visible borders, native and editable.',+ whenToUse: ['glassmorphism', 'glass', 'frosted', 'translucent', 'transparency', 'blur', 'frosted glass', 'glass panel'],+ modes: ['create', 'improve', 'plan', 'edit'],+ version: '1.0.0',+ playbook: {+ principles: [+ 'Glass = rgba fill + visible border, never a solid guess: fill "rgba(R,G,B,0.05–0.25)" over a dark or gradient page, border 1px "rgba(R,G,B,0.25–0.5)". Both are set on the SAME native element (add_shape then update_elements with stroke).',+ 'Contrast is the non-negotiable: text on glass is checked against the COMPOSITED backdrop (fill over page), not the page alone. White/near-white text on dark glass; dark text only on light glass ≥ 0.5 alpha. If 4.5:1 body / 3:1 large fails, raise the fill alpha before touching the text.',+ 'Keep glass surfaces SMALL and purposeful (cards, one hero panel, one nav bar) — never the whole canvas; large frosted areas read as fog, not depth.',+ 'One glass system per design: every panel uses the SAME fill alpha, border alpha and corner radius; consistency is what sells the material.',+ 'Rounded corners on every glass surface (16–28px at 1080-canvas scale); sharp glass reads as a bug.',+ 'Content sits INSIDE the glass with 24–32px padding on all sides — text touching a glass edge is a clipped composition error.',+ ],+ planning: [+ 'Set the page background first (solid dark or gradient) — glass is invisible on white pages.',+ 'Reserve each glass panel\'s bounding box in the layout plan before building; text and inner UI get their own elements on top.',+ 'Build order: background → glass panels → panel content (text, icons, inner bars) → decorative accents last.',+ 'For feature cards: one glass rect per card with its text centered inside — the card and the text are separate native elements (both editable later).',+ ],+ validation: [+ 'Every glass element has BOTH a semi-transparent fill AND a visible border (check via get_page_state: fill + stroke).',+ 'Text on every glass surface passes contrast against the composited backdrop.',+ 'All glass panels share the same alpha, border and radius system; no panel is fully opaque.',+ 'Nothing overflows its glass panel\'s bounds (measure_text for the card labels).',+ ],+ },+ },+ {+ // v0.29.4: "realistic editor mockup" was delivered as one empty+ // rectangle in the failed run. This skill is how it becomes a+ // real, native, editable product UI composite.+ id: 'realistic-mockups',+ name: 'Realistic Product Mockups',+ description: 'Editor/app/dashboard mockups built from native elements: window chrome, toolbar, sidebar, content area, buttons — believable at a glance, fully editable.',+ whenToUse: ['mockup', 'mock up', 'editor mockup', 'app mockup', 'ui mockup', 'screenshot mockup', 'browser mockup', 'device mockup', 'dashboard mockup', 'wireframe'],+ modes: ['create', 'improve', 'plan', 'edit'],+ version: '1.0.0',+ playbook: {+ principles: [+ 'A believable mockup is a COMPOSITE: outer window (rounded rect, glass fill, border) + title bar (~28–36px tall with 3 dot buttons) + toolbar strip + sidebar (~15% width) + content area + 2–4 real content blocks. One empty rectangle is a placeholder, not a mockup.',+ 'Chrome proportions sell it: title bar dots are 8–12px circles spaced 8px apart; toolbar buttons are 24–40px rects with 8px gaps; sidebar items are 12–15px tall with 10px gaps. Everything inside 8–12px inset from the window edge.',+ 'The content area shows REAL content (a mini canvas with 2–3 shapes, text lines as light rects or actual text elements) — an empty gray box reads as a wireframe, not a product.',+ 'Keep the whole mockup on ONE z-order stack: window rect FIRST (bottom), chrome above it, content on top — build in that order so nothing hides.',+ 'Scale honestly: a mockup in a 1080 poster is 300–600px wide — its inner text uses 10–14px, chrome 8–12px. Micro text below 10px is noise; leave it out.',+ 'One mockup per poster is the hero; more than one competes with the headline.',+ ],+ planning: [+ 'Reserve the mockup\'s full bounding box in the layout plan (typically the visual center or lower-right band).',+ 'List the parts before building: window, title bar, dots, toolbar, buttons, sidebar, sidebar items, content blocks. 8–15 native elements total.',+ 'Build window → chrome → content in z-order; use the SAME corner radius on window and inner panels.',+ 'Give the mockup one accent-color detail (the primary button or selection highlight) so it ties into the poster\'s palette.',+ ],+ validation: [+ 'The mockup panel is ≥160×110 with ≥4 inner native elements (≥1 non-text) — a real composite, not one rect.',+ 'No inner element crosses the window\'s bounds; chrome respects the 8–12px inset.',+ 'Contrast for any readable inner text passes 3:1 against its immediate backdrop; decorative micro-blocks stay decorative.',+ 'The mockup reads as a product at 50% zoom (squint test) — clear title bar, clear toolbar, clear content.',+ ],+ },+ },+ {+ // v0.29.4: the audit computes WCAG numbers; this skill teaches the+ // model to design for them instead of fixing them after the fact.+ id: 'visual-accessibility',+ name: 'Visual Accessibility',+ description: 'WCAG 2.x contrast, readable type sizes, color-blind-safe accents, focus-safe palettes — design everyone can read.',+ whenToUse: ['accessib', 'wcag', 'contrast', 'readable', 'legible', 'color blind', 'colorblind', 'low vision', 'a11y'],+ modes: ['create', 'improve', 'plan', 'review', 'edit'],+ version: '1.0.0',+ playbook: {+ principles: [+ 'Contrast floors: 4.5:1 body text, 3:1 large text (≥24px or ≥18.66px bold) — against the text\'s ACTUAL backdrop (card fill composited over page), never a guessed page color.',+ 'Minimum type sizes: 14px floor on 1080-wide canvases (11px only for legal footnotes); body 16–20px; the poster headline 60–160px.',+ 'Never encode meaning by color alone: pair accent colors with weight, underline or position (the CTA pill shape, not just a tint).',+ 'Safe accent pairs for color-blind vision: blue/orange, teal/magenta, blue+yellow — avoid red/green-only distinctions.',+ 'Dark-mode text is off-white (#F4F5F7-class), never pure #FFF; large pure-white fields glare.',+ 'Opacity floors: text fill alpha ≥ 0.85; anything fainter is a watermark, not content.',+ ],+ planning: [+ 'Pick the background first, then derive text colors that clear the floors — not the reverse.',+ 'For every text/background pair in the plan, state the expected contrast tier (body/large) before placing elements.',+ 'Budget one high-contrast accent (≥3:1 vs background) for the single most important element (the CTA).',+ ],+ validation: [+ 'Every text element passes its contrast floor against its effective backdrop.',+ 'No text below 14px (except legal fine print at 11px).',+ 'The CTA is distinguishable by shape or position, not color alone.',+ ],+ },+ },]/** Router: match a user message + mode against skill metadata.diff --git a/src/lib/agent/tools.ts b/src/lib/agent/tools.tsindex ba2041a..84f3046 100644--- a/src/lib/agent/tools.ts+++ b/src/lib/agent/tools.ts@@ -129,6 +129,64 @@ export const AGENT_TOOLS: AgentTool[] = [observation: 'Fresh page state attached as the next observation.',}),},+ {+ // v0.29.3: brief-to-layout planning. The model reserves the+ // composition BEFORE building — the failed production runs+ // placed text reactively (add → overlap → move → overlap…) for+ // 40+ steps. A plan is displayed to the user and echoed back.+ name: 'plan_layout',+ description:+ 'Plan the composition before building: page background, sections with y-ranges and heights, and what each section contains. REQUIRED as the first call of a create run — reserve a vertical band per section (headline, tagline, features, mockup, CTA, footer) with ≥40px gaps so text never stacks.',+ risk: 'read',+ argsSpec: '{background?: "#RRGGBB", sections: [{name: string, y: number, height: number, contains: string}], notes?: string}',+ sanitize: (args, ctx) => {+ const sectionsRaw = args.sections+ if (!Array.isArray(sectionsRaw) || sectionsRaw.length === 0) {+ return { ok: false, error: '"sections" must be a non-empty array: [{name, y, height, contains}].' }+ }+ const lines: string[] = []+ const H = ctx.height+ for (const s of sectionsRaw.slice(0, 12)) {+ if (!s || typeof s !== 'object') continue+ const sec = s as Record<string, unknown>+ const name = typeof sec.name === 'string' ? sec.name.trim().slice(0, 40) : ''+ const y = num(sec as Record<string, unknown>, 'y')+ const height = num(sec as Record<string, unknown>, 'height')+ const contains = typeof sec.contains === 'string' ? sec.contains.trim().slice(0, 80) : ''+ if (!name) return { ok: false, error: 'Each section needs a "name".' }+ if (y === null || height === null || height <= 0) {+ return { ok: false, error: `Section "${name}" needs numeric y and height (> 0).` }+ }+ lines.push(`${name}: y=${Math.round(y)} h=${Math.round(height)}${contains ? ` — ${contains}` : ''}`)+ }+ if (!lines.length) return { ok: false, error: '"sections" contained no usable entries.' }+ const bg = hex(args, 'background')+ if (bg) lines.unshift(`page background ${bg}`)+ const notes = typeof args.notes === 'string' ? args.notes.trim().slice(0, 200) : ''+ if (notes) lines.push(`notes: ${notes}`)+ // sanity: sections inside the page, in order, not stacked+ const sorted = [...sectionsRaw]+ .map((s) => s as Record<string, unknown>)+ .map((s) => ({ y: num(s, 'y') ?? 0, h: num(s, 'height') ?? 0 }))+ .sort((a, b) => a.y - b.y)+ const problems: string[] = []+ if (sorted.length) {+ const last = sorted[sorted.length - 1]+ if (last.y + last.h > H * 1.02) problems.push(`the last section ends at y=${Math.round(last.y + last.h)} — beyond the ${H}px page`)+ for (let i = 1; i < sorted.length; i++) {+ if (sorted[i].y < sorted[i - 1].y + sorted[i - 1].h - 24) {+ problems.push(`sections ${i} and ${i + 1} overlap or have <24px gap at y=${Math.round(sorted[i].y)}`)+ }+ }+ }+ const observation = `PLAN RECORDED (${lines.length} lines):\n${lines.join('\n')}${problems.length ? `\nPLAN WARNINGS: ${problems.join('; ')} — revise the bands before building.` : '\nBands verified non-overlapping.'}`+ return {+ ok: true,+ actions: [{ type: '__planLayout', lines }],+ observation,+ }+ },+ },// ── add elements ───────────────────────────────────────────{diff --git a/src/lib/agent/vision.ts b/src/lib/agent/vision.tsnew file mode 100644index 0000000..9f5bc77--- /dev/null+++ b/src/lib/agent/vision.ts@@ -0,0 +1,92 @@+// ─────────────────────────────────────────────────────────────+// Vision critique (v0.29.3) — the shared, grounded critique engine.+//+// One vision-slot model call with a REAL screenshot of the rendered+// canvas. Used in TWO places:+// 1. the agent loop, BEFORE completion is accepted (bounded+// correction pass: capture → critique → fix → re-capture →+// verify — the failed production runs critiqued AFTER claiming+// success, so P0 findings could never influence the design);+// 2. the panel's post-run Findings display (Phase 7).+//+// Honesty contract (unchanged from the original route):+// · No vision provider configured → null + note. The caller says+// "visual critique unavailable" and NEVER pretends a text model+// looked at a screenshot it never received.+// · The prompt forbids inventing elements: findings must reference+// what is visible or explicitly say "cannot determine".+// ─────────────────────────────────────────────────────────────++export interface VisionFinding {+ severity: 'P0' | 'P1' | 'P2' | 'P3'+ issue: string+ fix?: string+}++export interface VisionCritiqueResult {+ findings: VisionFinding[]+ note: string+}++export const VISION_CRITIQUE_SYSTEM =+ 'You are a meticulous design critic looking at a REAL screenshot of a graphic-design canvas. ' ++ 'Report only what you can actually see in the image. Never invent or assume elements that are not visible; ' ++ 'if something cannot be determined from the image, say "cannot determine". ' ++ 'Reply ONLY with JSON: {"findings": [{"severity": "P0"|"P1"|"P2"|"P3", "issue": "what is wrong (concrete, visual)", "fix": "the specific change to make"}], "overall": "one sentence verdict"}\n' ++ 'P0 = broken/unreadable/missing required content; P1 = major (weak hierarchy, poor contrast, crowding); P2 = minor (spacing, balance); P3 = polish.'++/** The required-content preamble: tells the critic what the brief+ * demands so missing strings/colors are P0 findings, not opinions. */+export function visionBriefPreamble(brief?: {+ requiredTexts?: { text: string }[]+ requiredColors?: { hex: string }[]+} | null): string {+ const parts: string[] = []+ if (brief?.requiredTexts?.length) {+ parts.push(`The design brief requires these EXACT text strings, verbatim: ${brief.requiredTexts.map((t) => `"${t.text}"`).join(', ')}. A required string that is cut off, hidden, overlapping, or absent is a P0.`)+ }+ if (brief?.requiredColors?.length) {+ parts.push(`The brief requires these colors to be visibly used: ${brief.requiredColors.map((c) => c.hex).join(', ')}.`)+ }+ return parts.length ? `REQUIRED CONTENT (check each one against the image):\n${parts.join('\n')}\n\n` : ''+}++/** Run the critique with a resolved vision client. Returns null when+ * the provider call fails; the CALLER decides what honesty demands. */+export async function critiqueWithVision(+ vision: { chat: { completions: { create: (body: Record<string, unknown>) => Promise<{ choices?: { message?: { content?: unknown } }[] }> } } },+ image: string,+ opts: {+ brief?: { requiredTexts?: { text: string }[]; requiredColors?: { hex: string }[] } | null+ stateSummary?: string+ model?: string+ } = {},+): Promise<VisionCritiqueResult | null> {+ const preamble = visionBriefPreamble(opts.brief)+ const state = opts.stateSummary ? `\n\nSTRUCTURED CANVAS STATE (geometry, may differ from what actually rendered — trust the IMAGE when they conflict):\n${opts.stateSummary.slice(0, 6000)}` : ''+ const content = [+ { type: 'text', text: `${preamble}Critique the rendered design in this screenshot. Findings must be concrete and visual (what you see, where). Check: every required string fully readable and unobscured; clipping (text cut off at box edges); elements overlapping text; contrast; spacing/hierarchy; dead space; overall balance.${state}` },+ { type: 'image_url', image_url: { url: image } },+ ]+ try {+ const completion = await vision.chat.completions.create({+ ...(opts.model ? { model: opts.model } : {}),+ messages: [{ role: 'user', content }],+ })+ const raw = String(completion.choices?.[0]?.message?.content ?? '')+ const cleaned = raw.replace(/```(?:json)?/gi, '').trim()+ const start = cleaned.indexOf('{')+ const end = cleaned.lastIndexOf('}')+ if (start === -1 || end <= start) return null+ const parsed = JSON.parse(cleaned.slice(start, end + 1)) as { findings?: VisionFinding[]; overall?: string }+ const findings = (parsed.findings ?? [])+ .filter((f) => f && typeof f.issue === 'string' && ['P0', 'P1', 'P2', 'P3'].includes(f.severity))+ .map((f) => ({ severity: f.severity, issue: f.issue.slice(0, 500), fix: typeof f.fix === 'string' ? f.fix.slice(0, 400) : undefined }))+ return {+ findings,+ note: parsed.overall ? parsed.overall.slice(0, 300) : 'Visual critique completed against the rendered canvas.',+ }+ } catch {+ return null+ }+}diff --git a/src/lib/ai/provider.ts b/src/lib/ai/provider.tsindex cf5e5fc..397e494 100644--- a/src/lib/ai/provider.ts+++ b/src/lib/ai/provider.ts@@ -348,7 +348,11 @@ export async function providersSummary(): Promise<ProvidersSummary> {// ── SDK client construction ──────────────────────────────────/** Construct an SDK client directly from resolved config (server-side only). */-export async function makeClient(baseUrl: string, apiKey: string): Promise<import('z-ai-web-dev-sdk').default> {+export async function makeClient(+ baseUrl: string,+ apiKey: string,+ headers?: Record<string, string>,+): Promise<import('z-ai-web-dev-sdk').default> {const { default: ZAI } = await import('z-ai-web-dev-sdk')// v0.16.2 (A2): construct the SDK DIRECTLY with the resolved config.//@@ -366,9 +370,30 @@ export async function makeClient(baseUrl: string, apiKey: string): Promise<impor// create()), but the shipped dist/index.js declares a plain public// `constructor(config)` — verified against the installed package.// Cast to a constructor signature; the runtime shape matches.- type ZAIConstructor = new (config: { baseUrl: string; apiKey: string }) => import('z-ai-web-dev-sdk').default+ // v0.29.3: the SDK constructor also accepts token / userId / chatId+ // and turns them into the X-Token / X-User-Id / X-Chat-Id headers the+ // internal gateway requires (verified in the shipped dist). The+ // config-FILE layer resolves those companion fields, but makeClient+ // dropped them — every file-configured provider 401'd with "missing+ // X-Token header" the moment env pins were absent. Pass them through.+ type ZAIConstructor = new (config: {+ baseUrl: string+ apiKey: string+ token?: string+ userId?: string+ chatId?: string+ }) => import('z-ai-web-dev-sdk').defaultconst Ctor = ZAI as unknown as ZAIConstructor- return new Ctor({ baseUrl, apiKey })+ const token = headers?.['X-Token']?.trim()+ const userId = headers?.['X-User-Id']?.trim()+ const chatId = headers?.['X-Chat-Id']?.trim()+ return new Ctor({+ baseUrl,+ apiKey,+ ...(token ? { token } : {}),+ ...(userId ? { userId } : {}),+ ...(chatId ? { chatId } : {}),+ })}/** A usable client plus the model id its slot wants (undefined = default). */@@ -387,7 +412,7 @@ export async function getClientForSlot(slot: AiSlot): Promise<ProviderContext |const resolved = await resolveSlot(slot)if (!resolved) return nulltry {- const zai = await makeClient(resolved.baseUrl, resolved.apiKey)+ const zai = await makeClient(resolved.baseUrl, resolved.apiKey, resolved.headers)return { zai, model: resolved.model, label: resolved.label, source: resolved.source }} catch (err) {console.error(`[ai] provider initialization failed (${slot})`, err)@@ -405,7 +430,7 @@ export async function getClientForSlotForUser(slot: AiSlot, userId: string | nulconst resolved = await resolveSlotForUser(slot, userId)if (!resolved) return nulltry {- const zai = await makeClient(resolved.baseUrl, resolved.apiKey)+ const zai = await makeClient(resolved.baseUrl, resolved.apiKey, resolved.headers)return { zai, model: resolved.model, label: resolved.label, source: resolved.source }} catch (err) {console.error(`[ai] provider initialization failed (${slot}, user rail)`, err)@@ -639,7 +664,7 @@ export async function withProvider(let ctx: ProviderContext | null = nullif (resolved) {try {- const zai = await makeClient(resolved.baseUrl, resolved.apiKey)+ const zai = await makeClient(resolved.baseUrl, resolved.apiKey, resolved.headers)ctx = { zai, model: resolved.model, label: resolved.label, source: resolved.source }} catch (err) {console.error(`[ai] provider initialization failed (${slot}${user ? `, user ${user.username}` : ''})`, err)