Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
feat(v0.32.6): ONE agent, ZERO selectors — the five AI tabs, the seven mode chips and the third 'Design agent' surface are gone; the agent classifies and does everything itself (#94)
Ashiq Hussain Mir3e8579f3391e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 89ad12d..df7651e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,24 @@All notable changes to Canvix will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).+### Changed — v0.32.6: ONE agent, ZERO selectors + the canvas map++- **One surface:** the five-tab unified app (Chat / Generate / Write /+ Image / Theme) and the seven mode chips (Auto / Create / Edit /+ Review / Improve / Explain / Plan) are GONE — the app IS the agent.+ Every message is classified and executed by the agent itself.+ Deleted surfaces: UnifiedAIApp, DesignAgentApp ("Design agent"),+ MagicWriteApp, AIImageApp, AIThemeApp (their routes remain APIs).+- **The canvas map:** existing elements become occupied bands+ (merged, disjoint, refreshed after every apply). Plans are fitted+ into the FREE intervals between them — never on top of existing+ content. Infeasible plans return the exact occupancy map and the+ largest free interval. The plan observation shows the map ("CANVAS+ MAP — existing elements occupy y …; your sections were fitted into+ the FREE space").+- Unit 1,745/1,745 (+5 canvas-map regressions); e2e updated+ (wave4's AI-theme TAB test retired with its tab).+### Fixed — v0.32.5: the P0 plan-validator regression (server-computed geometry)- **The failure:** a valid creative brief ("Design a bold Instagramdiff --git a/ROADMAP.md b/ROADMAP.mdindex 7361666..324b072 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -1,5 +1,6 @@- v0.32.4 — deterministic design correctness: hard plan validation (real ≥40px gaps, bounds), duplicate-text/shape detection, plan adherence, wrap-up audit disclosure, per-design run ledger (0015), the phantom list_fonts tool made real.- v0.32.5 — P0 regression fix: server-computed plan geometry (auto-repair, bounded infeasibility), no strikes for recoverable plans, zero-action runs skip vision critique, honest failure UI.+- v0.32.6 — one agent, zero selectors (5 tabs + 7 mode chips removed); the canvas map: plans fit the free space between existing elements.# Canvix Roadmap — where we are, what's next> **Status date:** 2026-11-25 · **Changelog state:** v0.31.0 · `package.json` 0.31.0 · **latest published GitHub release:** v0.31.0 · **Test posture:** 1,693 unit tests across 127 test files (verified full run, 25 Nov, the v0.31.0 release run) · 39 e2e spec files + the plugins & stock-video gated suites · CI gates every PR (`lint-unit` incl. production build + `e2e` running all three suites) · `npm audit` **0 vulnerabilities**.diff --git a/docs/UNIFIED-AI-MILESTONE.md b/docs/UNIFIED-AI-MILESTONE.mdindex d036a08..7f6a962 100644--- a/docs/UNIFIED-AI-MILESTONE.md+++ b/docs/UNIFIED-AI-MILESTONE.md@@ -561,3 +561,87 @@ today (page height, margins, per-section y/h). It does not yet solvehorizontal multi-column placement inside a band — the model stillplaces cards within a band (guarded by the audit's overlap andduplicate checks).++---++# v0.32.6 — ONE agent, ZERO selectors + the canvas map++**The review that mattered:** "wtf are you doing bro… no need for+this chat, generate, write and all that — only keep 1… then there is+this [Auto Create Edit Review Improve Explain Plan] — why all these,+remove them as well and keep only one that does all by himself…+just do this: have canvix AI [map] the background and what's present+and all that geometrically so that overlap won't happen and it will+know where to put everything by using geometry and math and+boundaries. once it finishes everything then it should check what I+built and check overlap and errors and all that and fix if any and+after that it should double check if what it wanted is exactly same+as it built and after everything it should stop."++## 1 · ONE surface, no selectors++The v0.32.1 "unified" app had FIVE tabs (Chat / Generate / Write /+Image / Theme); the Chat tab still carried SEVEN mode chips (Auto /+Create / Edit / Review / Improve / Explain / Plan); the Generate tab+was a THIRD agent surface ("Design agent") that broke on a provider+outage with two overlapping failure messages. Three nested agents,+three selectors, zero of them what the user asked for.++Now: **the app IS the agent.** `AssistantApp` is registered+directly — no tab wrapper, no mode chips, no pinned mode. Every+message is classified by the agent itself (the router's Auto+semantics); it creates, edits, reviews, explains — whatever the+message needs. Deleted outright: `UnifiedAIApp`, `DesignAgentApp`,+`MagicWriteApp`, `AIImageApp`, `AIThemeApp` (the server routes stay+— the text panel, notes, alt-text and image features use them as+APIs; only the panel surfaces are gone).++## 2 · the CANVAS MAP — plans fit the free space, deterministically++"First maps the background and what's present, geometrically, so+overlap won't happen." Existing elements are now merged into+**occupied bands** (`context.ts · canvasMap()`), refreshed after+every apply. The plan solver (`plan-repair.ts`) receives them and+fits the model's sections into the **FREE intervals** between them:++- all sections fit one free interval → natural uniform-gap layout+ inside it;+- otherwise first-fit across intervals (order preserved, ≥40px+ gaps);+- nothing fits → **infeasible with the exact map** ("existing+ elements occupy y 65–365 (headline), y 405–805 (cards); free:+ y 805–1015 (210px). Your 3 sections (620px) do not fit…") — the+ model shrinks, drops sections, or asks to clear (destructive,+ confirmed). Never a fabricated plan, never planned on top of+ existing content.++The plan observation opens with the map — visible to the model AND+the user: "CANVAS MAP — existing elements occupy y …; your sections+were fitted into the FREE space (never on top of them)."++## 3 · the pipeline (unchanged in shape, now fully mapped)++map (canvasMap) → plan (occupancy-fitted, auto-repaired) → build →+audit overlap/errors + one bounded fix round → brief double-check+("is what it built what it wanted") → stop. The last three stages+are v0.32.3–v0.32.5 behavior, kept exactly as shipped.++## Test evidence++Unit **1,745/1,745** (+5 canvas-map regressions: free-space fitting,+exact-map infeasibility, canvasMap merging, the plan observation,+loop wiring). Twelve existing flows moved to a compact-top fixture+(the old spread-out fixture left 415px of contiguous free space — a+full-composition plan on it is now honestly infeasible, which is+correct improve-run semantics: plan your ADDITIONS, or clear first).+E2E: wave4 minus the retired AI-theme TAB test (4/4); the+reproduction spec 3/3 with the selector-free app.++## Disclosed limitation++The map is vertical-band (the planner's vocabulary). Two elements+side-by-side at the same y merge into one occupied band — horizontal+carving inside a free band remains the model's job, guarded by the+audit's overlap checks. Image GENERATION is not yet an agent tool+(the former Image tab's route remains an API; the agent places+existing assets, URLs and uploads).diff --git a/src/components/editor/apps/AIImageApp.tsx b/src/components/editor/apps/AIImageApp.tsxdeleted file mode 100644index 5962e68..0000000--- a/src/components/editor/apps/AIImageApp.tsx+++ /dev/null@@ -1,227 +0,0 @@-'use client'--import { useState } from 'react'-import { ImageIcon, Loader2, Plus, RefreshCw, Sparkles } from 'lucide-react'-import { createImageElement } from '@/lib/types'-import { useEditorStore } from '@/store/editor-store'-import { AppHeader, type AppPanelProps } from './registry'-import { cn } from '@/lib/utils'-import { toast } from '@/hooks/use-toast'--const SIZES = [- { id: '1024x1024', label: 'Square 1:1', w: 1, h: 1 },- { id: '1344x768', label: 'Wide 16:9', w: 16, h: 9 },- { id: '768x1344', label: 'Story 9:16', w: 9, h: 16 },- { id: '1152x864', label: 'Photo 4:3', w: 4, h: 3 },-] as const--const STYLES = [- 'Photorealistic, professional photography',- 'Flat vector illustration',- '3D render, soft studio lighting',- 'Watercolour painting',- 'Minimal gradient poster art',-]--const IDEAS = [- 'A minimalist workspace with a plant and coffee, soft morning light',- 'Abstract wave shapes in purple and teal, poster style',- 'Cute 3D character holding a rocket ship',- 'Sunset over calm ocean with pastel sky',-]--interface Generated {- dataUrl: string- width: number- height: number- prompt: string- /** v0.19 (Wave 4): provider handle (image_ent_id) — stored on the- * element so AI-edit chains keep matching after re-encodes. */- entId?: string-}--export function AIImageApp({ onClose }: AppPanelProps) {- const addElement = useEditorStore((s) => s.addElement)- const pages = useEditorStore((s) => s.pages)- const currentPage = useEditorStore((s) => s.currentPage)- const designW = useEditorStore((s) => s.width)- const designH = useEditorStore((s) => s.height)-- const [prompt, setPrompt] = useState('')- const [style, setStyle] = useState<string | null>(null)- const [size, setSize] = useState<(typeof SIZES)[number]['id']>('1024x1024')- const [image, setImage] = useState<Generated | null>(null)- const [busy, setBusy] = useState(false)- const [error, setError] = useState<string | null>(null)-- const generate = async (regen = false) => {- if (!prompt.trim() || busy) return- setBusy(true)- setError(null)- if (!regen) setImage(null)- try {- const fullPrompt = style ? `${prompt}, ${style}` : prompt- const res = await fetch('/api/ai/image', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ prompt: fullPrompt, size }),- })- const data = (await res.json()) as Generated & { error?: string }- if (!res.ok || !data.dataUrl) throw new Error(data.error ?? 'Generation failed')- setImage({ ...data, prompt: fullPrompt })- } catch (e) {- setError(e instanceof Error ? e.message : 'Generation failed')- } finally {- setBusy(false)- }- }-- const addToCanvas = () => {- if (!image) return- const maxW = designW * 0.7- const maxH = designH * 0.7- const scale = Math.min(maxW / image.width, maxH / image.height, 1)- const w = Math.round(image.width * scale)- const h = Math.round(image.height * scale)- addElement(- createImageElement(image.dataUrl, image.width, image.height, {- x: Math.max(0, (designW - w) / 2),- y: Math.max(0, (designH - h) / 2),- width: w,- height: h,- // v0.19 (Wave 4): keep the provider handle for later AI edits- ...(image.entId ? { aiEntId: image.entId } : {}),- })- )- toast({ title: 'AI image added' })- }-- return (- <div>- <AppHeader icon={ImageIcon} title="AI image generator" onClose={onClose} />-- <div className="rounded-xl border border-white/10 bg-white/[0.04] focus-within:border-[#7630D7] transition-colors p-3 mb-2.5">- <textarea- value={prompt}- onChange={(e) => setPrompt(e.target.value)}- onKeyDown={(e) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) generate() }}- rows={2}- maxLength={600}- placeholder="Describe the image — e.g. “A dreamy purple nebula with a lone astronaut”"- className="w-full bg-transparent outline-none text-[12.5px] text-white resize-none placeholder:text-white/35"- aria-label="Image generation prompt"- />- </div>-- <div className="grid grid-cols-4 gap-1.5 mb-2">- {SIZES.map((s) => (- <button- key={s.id}- onClick={() => setSize(s.id)}- className={cn(- 'h-7 rounded-lg text-[10px] font-semibold transition-colors',- size === s.id ? 'bg-[#7630D7] text-white' : 'bg-white/[0.05] text-white/60 hover:text-white'- )}- title={s.label}- >- {s.label}- </button>- ))}- </div>-- <div className="flex gap-1.5 flex-wrap mb-2.5">- {STYLES.map((s) => (- <button- key={s}- onClick={() => setStyle(style === s ? null : s)}- className={cn(- 'h-6 px-2.5 rounded-full text-[10px] font-semibold border transition-colors',- style === s ? 'bg-white/[0.16] text-white border-white/25' : 'text-white/55 border-white/10 hover:text-white'- )}- >- {s.split(',')[0]}- </button>- ))}- </div>-- <button- onClick={() => generate()}- disabled={busy || !prompt.trim()}- className="w-full h-10 rounded-xl bg-gradient-to-r from-[#7630D7] to-[#9B6BFF] text-white text-[13px] font-bold flex items-center justify-center gap-2 disabled:opacity-40 hover:brightness-110 transition-all"- aria-label="Generate image"- >- {busy ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}- {busy ? 'Dreaming…' : 'Generate image'}- </button>-- {error && (- <div className="mt-2.5">- <p className="text-[11px] text-[#FF8095]">{error}</p>- {/* v0.23.1: generation failures often mean "no key on the image slot" */}- <p className="text-[10.5px] text-white/45 mt-1 leading-snug">- Tip: add your own AI key in <span className="text-white/75 font-medium">Profile & AI keys</span> (account menu) — your key is used before this- instance's providers.- </p>- </div>- )}-- {busy && (- <div className="mt-3 rounded-xl border border-white/10 bg-white/[0.03] aspect-square flex flex-col items-center justify-center gap-2">- <Loader2 size={22} className="animate-spin text-[#9B6BFF]" />- <span className="text-[11px] text-white/50">Painting your image…</span>- </div>- )}-- {image && !busy && (- <div className="mt-3">- <button- onClick={addToCanvas}- className="group relative w-full rounded-xl overflow-hidden border border-white/10 hover:border-[#7630D7] transition-colors"- role="button"- aria-label="Add image to canvas"- >- <img src={image.dataUrl} alt={image.prompt} className="w-full block" />- <span className="absolute inset-0 hidden group-hover:flex items-center justify-center bg-black/35">- <span className="h-8 px-4 rounded-full bg-[#7630D7] text-white text-[11.5px] font-bold flex items-center gap-1.5 shadow-lg">- <Plus size={12} /> Add to canvas- </span>- </span>- </button>- <div className="flex gap-2 mt-2">- <button- onClick={() => generate(true)}- className="flex-1 h-8 rounded-lg border border-white/12 text-white/70 hover:text-white text-[11px] font-semibold flex items-center justify-center gap-1.5"- aria-label="Generate another"- >- <RefreshCw size={11} /> Another- </button>- <button- onClick={addToCanvas}- className="flex-1 h-8 rounded-lg bg-[#7630D7] hover:bg-[#8B5CF6] text-white text-[11px] font-semibold flex items-center justify-center gap-1.5"- aria-label="Add to canvas"- >- <Plus size={11} /> Add to canvas- </button>- </div>- </div>- )}-- {!image && !busy && !error && (- <div className="mt-3.5">- <p className="text-[10.5px] font-bold text-white/60 uppercase tracking-wide mb-1.5">Try a prompt like…</p>- <div className="space-y-1">- {IDEAS.map((idea) => (- <button- key={idea}- onClick={() => setPrompt(idea)}- className="block w-full text-left text-[11.5px] text-white/55 hover:text-white rounded-lg border border-white/[0.07] hover:border-white/20 px-2.5 py-1.5 transition-colors"- >- “{idea}”- </button>- ))}- </div>- </div>- )}- </div>- )-}diff --git a/src/components/editor/apps/AIThemeApp.tsx b/src/components/editor/apps/AIThemeApp.tsxdeleted file mode 100644index 5610cc7..0000000--- a/src/components/editor/apps/AIThemeApp.tsx+++ /dev/null@@ -1,163 +0,0 @@-'use client'--import { useState } from 'react'-import { SwatchBook, Loader2, Check, Sparkles } from 'lucide-react'-import { useEditorStore } from '@/store/editor-store'-import { applyTheme, type Theme } from '@/lib/theme'-import { AppHeader, type AppPanelProps } from './registry'-import { toast } from '@/hooks/use-toast'--const MOODS = [- 'warm bakery, cozy, earthy',- 'nordic calm, cool editorial',- 'bold tech launch, electric',- 'soft pastel kids brand',- 'luxury dark, gold accents',-]--const ROLE_LABELS: Record<string, string> = {- background: 'Background',- surface: 'Surface',- ink: 'Text',- inkSoft: 'Text (soft)',- accent: 'Accent',- accentSoft: 'Accent 2',-}--/**- * v0.19 (Wave 4) — AI theme generation. The model proposes a- * role-tagged palette + font pairing (contrast-checked server-side);- * this panel previews it and applies it design-wide with applyTheme()- * — backgrounds, text ink, shape accents, all as one undoable step.- */-export function AIThemeApp({ onClose }: AppPanelProps) {- const [mood, setMood] = useState('')- const [busy, setBusy] = useState(false)- const [error, setError] = useState<string | null>(null)- const [theme, setTheme] = useState<Theme | null>(null)-- const generate = async () => {- if (!mood.trim() || busy) return- setBusy(true)- setError(null)- setTheme(null)- try {- const res = await fetch('/api/ai/theme', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ prompt: mood.trim() }),- })- const data = (await res.json()) as { theme?: Theme; error?: string }- if (!res.ok || !data.theme) throw new Error(data.error ?? 'Generation failed')- setTheme(data.theme)- } catch (e) {- setError(e instanceof Error ? e.message : 'Generation failed')- } finally {- setBusy(false)- }- }-- const apply = () => {- if (!theme) return- const s = useEditorStore.getState()- // applyTheme is pure — build the next pages, then one history push- const next = applyTheme(s.pages, theme)- s.pushHistory()- useEditorStore.setState({ pages: next, dirty: true })- toast({- title: 'Theme applied',- description: `${theme.name} — recolored backgrounds, text and shapes. Ctrl+Z to revert.`,- })- onClose()- }-- return (- <div>- <AppHeader icon={SwatchBook} title="AI theme" onClose={onClose} />- <p className="text-[11.5px] text-white/50 leading-snug mb-3">- Describe a mood — get a palette + font pairing, preview it, then recolor the whole design in one- undoable step. Text contrast is guarded automatically.- </p>-- <div className="flex gap-1.5">- <input- value={mood}- onChange={(e) => setMood(e.target.value)}- onKeyDown={(e) => e.key === 'Enter' && !busy && void generate()}- placeholder="e.g. moody jazz club, deep blues"- className="flex-1 h-9 rounded-xl bg-white/[0.05] border border-white/10 text-white text-[12px] px-3 focus:outline-none focus:border-[#02C0CC]"- aria-label="Theme mood"- maxLength={400}- />- <button- className="btn-cv h-9 px-3.5 text-[12px] flex items-center gap-1.5 shrink-0 disabled:opacity-60"- onClick={() => void generate()}- disabled={busy || !mood.trim()}- >- {busy ? <Loader2 size={13} className="animate-spin" /> : <Sparkles size={13} />}- Generate- </button>- </div>-- {!theme && !busy && (- <div className="mt-3 space-y-1.5">- {MOODS.map((m) => (- <button- key={m}- onClick={() => setMood(m)}- className="block w-full text-left text-[11px] text-white/45 hover:text-white/80 px-2.5 py-2 rounded-lg hover:bg-white/[0.04] transition-colors"- >- “{m}”- </button>- ))}- </div>- )}-- {error && (- <p className="mt-3 rounded-xl border border-red-400/30 bg-red-400/10 px-3 py-2 text-[11.5px] text-red-200">- {error}- </p>- )}-- {theme && (- <div className="mt-4 border-t border-white/10 pt-3">- <div className="flex items-start gap-2">- <div className="min-w-0">- <p className="text-[12.5px] font-bold text-white truncate">{theme.name}</p>- {theme.mood && <p className="text-[11px] text-white/50 leading-snug mt-0.5">{theme.mood}</p>}- <p className="text-[11px] text-white/45 mt-1">- {theme.fonts.heading} + {theme.fonts.body}- </p>- </div>- <div className="ml-auto flex gap-2 shrink-0">- <button- className="text-[11px] text-white/55 hover:text-white px-2.5 h-8 rounded-lg hover:bg-white/10"- onClick={() => setTheme(null)}- >- Redraft- </button>- <button className="btn-cv h-8 px-3.5 text-[11.5px] flex items-center gap-1.5" onClick={apply}>- <Check size={12} /> Apply theme- </button>- </div>- </div>-- <div className="mt-3 rounded-xl border border-white/10 overflow-hidden">- {theme.palette.map((c) => (- <div key={c.role} className="flex items-center gap-2.5 px-2.5 h-10 border-b border-white/[0.06] last:border-b-0" style={{ background: `${c.hex}14` }}>- <span className="w-6 h-6 rounded-md border border-white/15 shrink-0" style={{ background: c.hex }} />- <span className="text-[11.5px] text-white/80">{ROLE_LABELS[c.role] ?? c.role}</span>- <span className="ml-auto font-mono text-[10.5px] text-white/45">{c.hex}</span>- </div>- ))}- </div>-- <p className="mt-3 text-[10.5px] text-white/35 leading-snug">- Applying recolors page backgrounds, text, shapes and lines across every page. Images, charts and- stickers stay untouched; one Ctrl+Z reverts everything.- </p>- </div>- )}- </div>- )-}diff --git a/src/components/editor/apps/AssistantApp.tsx b/src/components/editor/apps/AssistantApp.tsxindex 6380da6..26f3b11 100644--- a/src/components/editor/apps/AssistantApp.tsx+++ b/src/components/editor/apps/AssistantApp.tsx@@ -24,12 +24,12 @@// ─────────────────────────────────────────────────────────────import { useCallback, useEffect, useRef, useState } from 'react'-import { Bot, Loader2, Send, Sparkles, User, Square, Undo2, ShieldAlert, ListChecks, Eye, Gauge, Scissors, CheckCircle2 } from 'lucide-react'+import { Bot, Loader2, Send, Sparkles, User, Square, Undo2, ShieldAlert, ListChecks, Gauge, Scissors, CheckCircle2 } from 'lucide-react'+import { cn } from '@/lib/utils'import { turnOutcome } from '@/lib/agent/outcome'import type { AnyElement, TextElement } from '@/lib/types'import { useEditorStore } from '@/store/editor-store'import { AppHeader, type AppPanelProps } from './registry'-import { cn } from '@/lib/utils'import { applyDesignAction, describeAction, type DesignAction } from '@/lib/design-actions'import { useAICapabilities } from '@/hooks/use-ai-capabilities'import type { AgentEvent, AgentMode } from '@/lib/agent/protocol'@@ -74,16 +74,6 @@ const SUGGESTIONS = ['Explain what fonts this design uses',]-const MODE_CHIPS: { id: AgentMode | 'auto'; label: string }[] = [- { id: 'auto', label: 'Auto' },- { id: 'create', label: 'Create' },- { id: 'edit', label: 'Edit' },- { id: 'review', label: 'Review' },- { id: 'improve', label: 'Improve' },- { id: 'explain', label: 'Explain' },- { id: 'plan', label: 'Plan' },-]-const READ_ONLY_MODES: AgentMode[] = ['review', 'explain', 'plan', 'discuss']/** Flatten elements (groups included). */@@ -307,8 +297,6 @@ export function AssistantApp({ onClose }: AppPanelProps) {const [liveSkills, setLiveSkills] = useState<string[]>([])const [liveBrief, setLiveBrief] = useState<DesignBrief | null>(null)const [liveUsage, setLiveUsage] = useState<{ turns: number; toolCalls: number; elapsedMs: number; modelCalls: number } | null>(null)- /** the pinned mode chip ('auto' = classify per message) */- const [pinnedMode, setPinnedMode] = useState<AgentMode | 'auto'>('auto')/** pending destructive confirmation */const [pendingConfirm, setPendingConfirm] = useState<{ tool: string; actions: DesignAction[]; callId: string } | null>(null)const scrollRef = useRef<HTMLDivElement>(null)@@ -404,9 +392,11 @@ export function AssistantApp({ onClose }: AppPanelProps) {setLiveUsage(null)confirmedRef.current = new Set()- // the heuristic pre-classification shows a mode hint even before- // the server answers (the pinned chip wins when set)- const expectedMode = pinnedMode === 'auto' ? heuristicMode(text).mode : pinnedMode+ // v0.32.6: NO mode selector — the agent classifies every message+ // itself and does everything by itself (create, edit, review,+ // explain…). The hint shows what it classified before the server+ // answers.+ const expectedMode = heuristicMode(text).modesetLiveMode(expectedMode)const controller = new AbortController()@@ -429,7 +419,6 @@ export function AssistantApp({ onClose }: AppPanelProps) {message: text,history,design: buildDesignContext(),- ...(pinnedMode !== 'auto' ? { mode: pinnedMode } : {}),confirmed: [...confirmedRef.current],}),})@@ -657,27 +646,7 @@ export function AssistantApp({ onClose }: AppPanelProps) {</div>)}- {/* mode chips */}- <div className="flex items-center gap-1 px-3 py-2 border-b border-white/5 overflow-x-auto" data-testid="agent-modes">- {MODE_CHIPS.map((chip) => {- const active = pinnedMode === chip.id- const readOnly = chip.id !== 'auto' && READ_ONLY_MODES.includes(chip.id as AgentMode)- return (- <button- key={chip.id}- onClick={() => setPinnedMode(chip.id)}- className={cn(- 'shrink-0 px-2.5 h-7 rounded-full text-[11px] font-semibold transition-colors',- active ? 'bg-[#7630D7] text-white' : 'bg-white/5 text-white/60 hover:bg-white/10 hover:text-white',- )}- title={readOnly ? 'Read-only: the agent cannot modify the design' : chip.id === 'auto' ? 'Classify each message automatically' : undefined}- >- {readOnly && <Eye size={10} className="inline mr-1 -mt-0.5" />}- {chip.label}- </button>- )- })}- </div>+{/* thread */}<div ref={scrollRef} className="flex-1 overflow-y-auto min-h-0 space-y-3 pr-0.5 px-3 py-3" data-testid="agent-thread">@@ -907,7 +876,7 @@ export function AssistantApp({ onClose }: AppPanelProps) {}}}rows={1}- placeholder={pinnedMode !== 'auto' && READ_ONLY_MODES.includes(pinnedMode) ? `Ask for ${pinnedMode} (the design won't be modified)…` : 'Describe what to design or change…'}+ placeholder="Describe what to design or change — the agent figures out the rest…"className="flex-1 resize-none max-h-28 rounded-xl bg-white/[0.05] border border-white/10 px-3 py-2 text-[12.5px] text-white placeholder:text-white/30 outline-none focus:border-[#7630D7]"data-testid="agent-input"/>@@ -922,9 +891,7 @@ export function AssistantApp({ onClose }: AppPanelProps) {</button></div><div className="flex items-center justify-between mt-1.5 text-[10px] text-white/30">- <span>- {pinnedMode === 'auto' ? 'Auto mode' : `${pinnedMode}${READ_ONLY_MODES.includes(pinnedMode as AgentMode) ? ' · read-only' : ''}`} · full editor access- </span>+ <span>One agent — it maps the canvas, plans the geometry, builds, checks and verifies by itself</span>{canUndo && <span>Undo available in the toolbar</span>}</div></div>diff --git a/src/components/editor/apps/DesignAgentApp.tsx b/src/components/editor/apps/DesignAgentApp.tsxdeleted file mode 100644index cd3f57a..0000000--- a/src/components/editor/apps/DesignAgentApp.tsx+++ /dev/null@@ -1,622 +0,0 @@-'use client'--// ─────────────────────────────────────────────────────────────-// DesignAgentApp (v0.31) — the autonomous generation panel.-//-// The P1 gap from docs/DESIGN-AGENT-ACCEPTANCE-REPORT.md: the-// pipeline shipped as a server contract (POST /api/ai/design-agent)-// without a user-facing surface. This panel is that surface, and it-// follows the house rule every generative surface obeys: NOTHING-// lands on the canvas unreviewed.-//-// prompt → [autonomous run, live status + stop]-// → REVIEW GATE: brief contract, per-page toggles,-// conformance failures, the full run report-// → Apply: deterministic canvas fit + appendPages-// (one Ctrl+Z removes everything)-// → optional post-apply critique on the REAL rendered-// pixels (captureStage → vision slot — the browser-// capture path, richer than the server's SVG review)-//-// Honesty rules mirrored from the pipeline: a failed run shows its-// evidence (best-attempt pages + unmet requirements) instead of a-// shrug; visual verification says 'unavailable' when no vision-// model answers; abort keeps nothing applied.-// ─────────────────────────────────────────────────────────────--import { useEffect, useRef, useState } from 'react'-import {- Workflow, Loader2, Sparkles, Check, Square, Gauge, ListChecks, Eye, EyeOff,- ShieldCheck, ShieldAlert, RefreshCw, X,-} from 'lucide-react'-import { useEditorStore } from '@/store/editor-store'-import { AppHeader, type AppPanelProps } from './registry'-import { cn } from '@/lib/utils'-import { toast } from '@/hooks/use-toast'-import { useAICapabilities } from '@/hooks/use-ai-capabilities'-import { requestDesignAgent, critiqueAppliedCanvas, type DesignAgentRunResult } from '@/lib/design-agent/client'-import { fitPagesToCanvas } from '@/lib/design-agent/fit-pages'-import type { PageData, AnyElement } from '@/lib/types'-import type { AgentOutcome } from '@/lib/design-agent/pipeline'--const IDEAS = [- 'A launch poster for a night market — "Friday 6 PM", neon purples, 1080×1350',- 'An Instagram post for a bakery opening — warm cream and chocolate browns, exact text "Opening 12 March"',- 'A conference poster: "AI & Design 2026", 3–5 March, blue #1B4F9C accents',-]--/** the pipeline's fixed stage order — shown while it runs so the wait- * is legible; the authoritative record is the run report at the end */-const EXPECTED_STAGES = [- 'extract brief',- 'plan',- 'compile + checks',- 'brief conformance',- 'self-correction',- 'render',- 'visual critique',- 'final verdict',-]--const OUTCOME_META: Record<AgentOutcome, { label: string; tone: string }> = {- passed: { label: 'Passed — every deterministic check is green', tone: 'border-emerald-400/30 bg-emerald-400/10 text-emerald-200' },- 'failed-honestly': { label: 'Stopped honestly — the agent would not fake a pass', tone: 'border-amber-400/30 bg-amber-400/10 text-amber-200' },- 'guard-cycled': { label: 'Stopped by the cycle guard — the plan repeated itself', tone: 'border-amber-400/30 bg-amber-400/10 text-amber-200' },- aborted: { label: 'Stopped — nothing was applied', tone: 'border-white/15 bg-white/5 text-white/70' },-}--const VISUAL_META: Record<string, string> = {- verified: 'verified',- improved: 'improved after critique',- unverified: 'ran without vision critique',- unavailable: 'unavailable (no vision model)',- aborted: 'aborted',-}--const PASS_ACTION_META: Record<string, string> = {- revised: 'revision accepted',- 'accepted-as-is': 'accepted as-is',- 'rejected-by-checks': 'rejected — checks outrank critique',- 'no-improvement': 'kept previous (no improvement)',- 'budget-exhausted': 'budget exhausted',- 'unparseable-discarded': 'discarded unparseable critique',- unavailable: 'unavailable',-}--export function DesignAgentApp({ onClose }: AppPanelProps) {- const [prompt, setPrompt] = useState('')- const [revisions, setRevisions] = useState(3)- /** null = follow the vision capability; the user can always opt out */- const [visualOverride, setVisualOverride] = useState<boolean | null>(null)- const [busy, setBusy] = useState(false)- const [elapsed, setElapsed] = useState(0)- const [result, setResult] = useState<DesignAgentRunResult | null>(null)- const [enabled, setEnabled] = useState<boolean[]>([])- const [applied, setApplied] = useState(false)- const [critique, setCritique] = useState<{ findings: { severity: string; issue: string; fix?: string }[]; note: string } | null>(null)- const [critiquing, setCritiquing] = useState(false)- const abortRef = useRef<AbortController | null>(null)-- const width = useEditorStore((s) => s.width)- const height = useEditorStore((s) => s.height)- const { configured: aiConfigured, loaded: aiLoaded, vision, designAgent } = useAICapabilities()-- const visualCheck = visualOverride ?? vision- const runAvailable = aiLoaded && aiConfigured && designAgent-- // elapsed timer while the pipeline runs (reset at run start; the- // effect itself only ticks — no synchronous setState in effects)- useEffect(() => {- if (!busy) return- const started = Date.now()- const t = setInterval(() => setElapsed(Math.round((Date.now() - started) / 1000)), 1000)- return () => clearInterval(t)- }, [busy])-- const generate = async () => {- const text = prompt.trim()- if (!text || busy) return- const controller = new AbortController()- abortRef.current = controller- setElapsed(0)- setBusy(true)- setResult(null)- setEnabled([])- setApplied(false)- setCritique(null)- try {- const res = await requestDesignAgent(- text,- { visual: visualCheck, maxRevisions: revisions },- controller.signal,- )- setResult(res)- setEnabled(res.pages.map(() => true))- if (!res.pages.length && res.error) {- toast({ title: 'The design agent stopped', description: res.error })- }- } catch (e) {- if (e instanceof Error && e.name === 'AbortError') {- setResult({ outcome: 'aborted', pages: [], briefConformance: [], warnings: [], report: null, format: null })- } else {- toast({ title: 'The design agent failed', description: e instanceof Error ? e.message : 'Unknown error' })- }- } finally {- setBusy(false)- abortRef.current = null- }- }-- const stop = () => abortRef.current?.abort()-- const apply = () => {- if (!result || applied) return- const chosen = result.pages.filter((_, i) => enabled[i])- if (!chosen.length) {- toast({ title: 'Nothing to apply', description: 'Enable at least one page first.' })- return- }- const from = result.format ?? { width, height }- const fit = fitPagesToCanvas(chosen, from, { width, height })- const store = useEditorStore.getState()- store.appendPages(fit.pages)- setApplied(true)- // v0.32 (Unified Canvix AI — continuation): the applied pages carry- // their contract. The store brief makes every later chat-agent run- // on THIS design merge it (create→verify→refine on one design).- // v0.32.1 (review P1): persistence no longer happens here — the- // PENDING contract rides the next design save (PUT /api/designs/- // [id]), where the server normalizes it in 'reject' mode and- // verifies it against the saved pages. No client-supplied PUT, no- // unearned 'passed', and a failed save can't strand a contract- // for pages that were never saved.- const brief = result.report?.brief ?? null- if (brief) {- store.setAIBrief(brief)- if (!store.readOnly) {- store.setAIPendingProvenance({ prompt, outcome: result.outcome, brief })- }- }- toast({- title: `${chosen.length} page${chosen.length > 1 ? 's' : ''} added`,- description:- (fit.scale !== 1- ? `Rescaled from ${from.width}×${from.height} to fit the ${width}×${height} canvas — fully editable. `- : 'Fully editable elements. ') +- (brief ? 'The brief now guards chat-agent refinements of this design. ' : '') +- 'Ctrl+Z removes them all.',- })- }-- /** post-apply critique: capture the REAL rendered canvas (the newly- * appended page is current) and ask the vision slot against the brief */- const runCritique = async () => {- if (!result || critiquing) return- setCritiquing(true)- try {- const { captureStage } = await import('@/components/editor/canvas/canvas-bridge')- const image = await captureStage({ pixelScale: 0.5, mimeType: 'image/jpeg', quality: 0.7 })- const brief = result.report?.brief- ? {- requiredTexts: result.report.brief.requiredTexts.map((t) => ({ text: t.text })),- requiredColors: result.report.brief.requiredColors.map((c) => ({ hex: c.hex })),- }- : { requiredTexts: [], requiredColors: [] }- setCritique(await critiqueAppliedCanvas(image, brief))- } catch {- setCritique({ findings: [], note: 'Could not capture the canvas — critique skipped.' })- } finally {- setCritiquing(false)- }- }-- const brief = result?.report?.brief- const specFormat = result?.format- const rescale = specFormat && (specFormat.width !== width || specFormat.height !== height)- const enabledCount = enabled.filter(Boolean).length- const meta = result ? OUTCOME_META[result.outcome] : null-- return (- <div data-testid="design-agent-panel">- <AppHeader icon={Workflow} title="Design agent" onClose={onClose} />-- {aiLoaded && !aiConfigured && (- <div data-testid="design-agent-no-provider" className="mb-3 rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-2.5 text-[11.5px] text-amber-200">- No AI provider configured yet — add a key in Admin → AI & models (or your profile) to use the design agent.- </div>- )}- {aiLoaded && aiConfigured && !designAgent && (- <div className="mb-3 rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-2.5 text-[11.5px] text-amber-200">- The design agent is switched off in the admin console (AI & models → features).- </div>- )}-- <p className="text-[11.5px] text-white/50 leading-snug mb-3">- One prompt in — the agent plans, compiles, checks and visually reviews a real design. Nothing lands- until you review it; a failed run shows its evidence, never a fake pass.- </p>-- <textarea- value={prompt}- onChange={(e) => setPrompt(e.target.value)}- placeholder="e.g. A 1080×1350 poster for a marathon — “Run Dal Lake 2026”, 26 Jan, navy #1B3A6B + coral accents, stats band, framed photo area"- className="w-full h-24 rounded-xl bg-white/[0.05] border border-white/10 text-white text-[12.5px] p-3 resize-none focus:outline-none focus:border-[#02C0CC]"- maxLength={2000}- aria-label="Design brief"- data-testid="design-agent-prompt"- />-- {/* options row */}- <div className="flex items-center gap-2 mt-2.5 flex-wrap">- <button- onClick={() => setVisualOverride(!visualCheck)}- disabled={!vision}- title={vision ? 'Render the pages and critique the real pixels before you review' : 'No vision model configured'}- className={cn(- 'flex items-center gap-1.5 h-8 px-2.5 rounded-lg text-[11px] font-semibold transition-colors',- visualCheck ? 'bg-[#02C0CC]/15 text-[#02C0CC]' : 'bg-white/5 text-white/45',- !vision && 'opacity-50 cursor-not-allowed',- )}- aria-pressed={visualCheck}- >- {visualCheck ? <Eye size={12} /> : <EyeOff size={12} />}- Visual check- </button>- <div className="flex items-center gap-1" role="group" aria-label="Revision rounds">- {[1, 2, 3].map((n) => (- <button- key={n}- onClick={() => setRevisions(n)}- className={cn(- 'w-7 h-7 rounded-lg text-[11px] font-bold transition-colors',- revisions === n ? 'bg-[#7630D7] text-white' : 'bg-white/[0.05] text-white/55 hover:bg-white/10',- )}- aria-pressed={revisions === n}- title={`${n} self-correction round${n > 1 ? 's' : ''}`}- >- {n}- </button>- ))}- </div>- <button- className="btn-cv h-9 px-4 ml-auto text-[12px] flex items-center gap-1.5 disabled:opacity-60"- onClick={() => void generate()}- disabled={busy || !prompt.trim() || (aiLoaded && (!aiConfigured || !designAgent))}- data-testid="design-agent-run"- >- {busy ? <Loader2 size={13} className="animate-spin" /> : <Sparkles size={13} />}- {busy ? 'Running…' : 'Generate'}- </button>- </div>-- {!result && !busy && (- <div className="mt-3 space-y-1.5">- {IDEAS.map((idea) => (- <button- key={idea}- onClick={() => setPrompt(idea)}- className="block w-full text-left text-[11px] text-white/45 hover:text-white/80 px-2.5 py-2 rounded-lg hover:bg-white/[0.04] transition-colors"- >- “{idea}”- </button>- ))}- </div>- )}-- {/* the live run */}- {busy && (- <div className="mt-4 rounded-xl border border-white/10 bg-white/[0.02] p-3" data-testid="design-agent-running">- <div className="flex items-center gap-2 text-[11.5px] text-white/60 mb-2">- <Loader2 size={12} className="animate-spin text-[#02C0CC]" />- The autonomous pipeline is running- <span className="text-white/35">{elapsed}s</span>- <button onClick={stop} className="ml-auto flex items-center gap-1 px-2 h-6 rounded-full bg-red-500/15 text-red-300 text-[10.5px] font-semibold hover:bg-red-500/25 transition-colors">- <Square size={9} /> Stop- </button>- </div>- <ol className="space-y-0.5">- {EXPECTED_STAGES.map((s, i) => (- <li key={s} className={cn('text-[11px] flex items-center gap-1.5', i === 0 ? 'text-white/70' : 'text-white/35')}>- <span className={cn('w-1 h-1 rounded-full', i === 0 ? 'bg-[#02C0CC]' : 'bg-white/20')} />- {s}- </li>- ))}- </ol>- <p className="mt-2 text-[10px] text-white/30 leading-snug">- Stage order is fixed; the authoritative record arrives with the run report.- </p>- </div>- )}-- {/* the review gate */}- {result && !busy && (- <div className="mt-4 space-y-3" data-testid="design-agent-result">- {meta && (- <div className={cn('rounded-xl border px-3 py-2 text-[12px] font-semibold flex items-center gap-1.5', meta.tone)} data-testid="design-agent-outcome">- {result.outcome === 'passed' ? <ShieldCheck size={13} /> : <ShieldAlert size={13} />}- {meta.label}- </div>- )}-- {result.error && (- <p className="rounded-xl border border-red-400/30 bg-red-400/10 px-3 py-2 text-[11.5px] text-red-200">- {result.error}- </p>- )}-- {/* brief contract */}- {brief && (brief.requiredTexts.length > 0 || brief.requiredColors.length > 0) && (- <div className="rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2">- <p className="text-[10px] font-bold uppercase tracking-wide text-white/50 mb-1.5">Brief contract (checked verbatim)</p>- <div className="flex flex-wrap gap-1.5">- {brief.requiredTexts.map((t, i) => (- <span key={i} className="px-1.5 py-0.5 rounded bg-white/8 text-[10.5px] text-white/80 font-medium">- “{t.text}”- </span>- ))}- {brief.requiredColors.map((c, i) => (- <span key={i} className="px-1.5 py-0.5 rounded bg-white/8 text-[10.5px] text-white/80 font-mono flex items-center gap-1">- <span className="w-2.5 h-2.5 rounded-sm inline-block border border-white/20" style={{ background: c.hex }} />- {c.hex.toUpperCase()}- </span>- ))}- </div>- </div>- )}-- {/* conformance failures — the honest-failure evidence */}- {result.briefConformance.length > 0 && (- <div className="rounded-xl border border-amber-400/25 bg-amber-400/8 px-3 py-2" data-testid="design-agent-conformance">- <p className="text-[10px] font-bold uppercase tracking-wide text-amber-300/80 mb-1">Unmet requirements</p>- <ul className="space-y-0.5">- {result.briefConformance.map((f, i) => (- <li key={i} className="text-[11px] text-amber-100/80 leading-snug">· {f}</li>- ))}- </ul>- </div>- )}- {result.warnings.length > 0 && (- <div className="rounded-xl border border-white/10 bg-white/[0.02] px-3 py-2">- <p className="text-[10px] font-bold uppercase tracking-wide text-white/45 mb-1">Warnings</p>- <ul className="space-y-0.5">- {result.warnings.map((w, i) => (- <li key={i} className="text-[11px] text-white/55 leading-snug">· {w}</li>- ))}- </ul>- </div>- )}-- {/* pages review */}- {result.pages.length > 0 && (- <div className="space-y-2">- {result.pages.map((page, i) => (- <PageReviewCard- key={i}- index={i}- page={page}- specWidth={specFormat?.width ?? width}- specHeight={specFormat?.height ?? height}- enabled={enabled[i] ?? true}- onToggle={() => setEnabled((e) => e.map((v, j) => (j === i ? !v : v)))}- />- ))}- </div>- )}-- {/* apply row */}- {result.pages.length > 0 && (- <div className="flex items-center gap-2 flex-wrap">- {!applied ? (- <>- <button className="btn-cv h-8 px-3.5 text-[11.5px] flex items-center gap-1.5" onClick={apply} data-testid="design-agent-apply">- <Check size={12} /> Apply {enabledCount > 0 ? `${enabledCount} page${enabledCount > 1 ? 's' : ''}` : ''}- </button>- {rescale && (- <span className="text-[10.5px] text-white/40">- pages were compiled {specFormat!.width}×{specFormat!.height} — they will be rescaled to fit this {width}×{height} design- </span>- )}- <button- className="flex items-center gap-1 text-[11px] text-white/50 hover:text-white px-2 h-8 rounded-lg hover:bg-white/10"- onClick={() => void generate()}- >- <RefreshCw size={11} /> Try again- </button>- <button- className="flex items-center gap-1 text-[11px] text-white/50 hover:text-white px-2 h-8 rounded-lg hover:bg-white/10"- onClick={() => { setResult(null); setPrompt('') }}- >- <X size={11} /> Discard- </button>- </>- ) : (- <>- <button- className="h-8 px-3.5 rounded-lg bg-white/10 text-white/85 text-[11.5px] font-semibold hover:bg-white/15 transition-colors flex items-center gap-1.5 disabled:opacity-50"- onClick={() => void runCritique()}- disabled={critiquing}- data-testid="design-agent-critique"- >- {critiquing ? <Loader2 size={12} className="animate-spin" /> : <Eye size={12} />}- {critiquing ? 'Critiquing…' : 'Critique the result'}- </button>- <button className="btn-cv h-8 px-3.5 text-[11.5px]" onClick={onClose}>- Done- </button>- </>- )}- </div>- )}-- {/* post-apply critique on the real pixels */}- {critique && (- <div className="rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2" data-testid="design-agent-critique-result">- <p className="text-[10px] font-bold uppercase tracking-wide text-white/50 mb-1.5">Visual critique (real pixels)</p>- {critique.findings.length === 0 ? (- <p className="text-[11px] text-white/55 leading-snug">{critique.note}</p>- ) : (- <>- <ul className="space-y-1 mb-1.5">- {critique.findings.slice(0, 8).map((f, i) => (- <li key={i} className="text-[11px] leading-snug">- <span- className={cn(- 'inline-block px-1.5 rounded text-[10px] font-bold mr-1.5',- f.severity === 'P1' && 'bg-amber-500/20 text-amber-300',- f.severity === 'P2' && 'bg-blue-500/20 text-blue-300',- f.severity === 'P3' && 'bg-white/10 text-white/50',- )}- >- {f.severity}- </span>- <span className="text-white/80">{f.issue}</span>- {f.fix && <span className="text-white/45"> → {f.fix}</span>}- </li>- ))}- </ul>- <p className="text-[10px] text-white/35">{critique.note}</p>- </>- )}- </div>- )}-- {/* the run report */}- {result.report && (- <details className="rounded-xl border border-white/8 bg-white/[0.02] overflow-hidden" data-testid="design-agent-report">- <summary className="px-3 py-2 text-[11px] font-semibold text-white/60 cursor-pointer flex items-center gap-1.5">- <ListChecks size={12} /> Run report- {result.report.modelCalls > 0 && (- <span className="text-white/35">- · {result.report.modelCalls} model calls · {result.report.revisionRounds} revision rounds- </span>- )}- </summary>- <div className="px-3 pb-2.5 space-y-2">- <div className="space-y-1">- {result.report.stages.map((s, i) => (- <div key={i} className="flex items-start gap-1.5 text-[10.5px] leading-snug">- <span className={s.ok ? 'text-emerald-400' : 'text-red-400'}>{s.ok ? '✓' : '✗'}</span>- <span className="text-white/75 font-mono shrink-0">{s.name}</span>- {s.modelCall && <span className="text-[#02C0CC]/70 text-[9.5px] mt-px">model</span>}- <span className="text-white/45 min-w-0">{s.detail}</span>- </div>- ))}- </div>- {result.report.visualPasses.length > 0 && (- <div className="border-t border-white/8 pt-2 space-y-1.5">- <p className="text-[10px] font-bold uppercase tracking-wide text-white/40">- Visual verification — {VISUAL_META[result.report.visualVerification] ?? result.report.visualVerification}- </p>- {result.report.visualPasses.map((p, i) => (- <div key={i} className="rounded-lg border border-white/8 px-2.5 py-1.5">- <div className="flex items-center gap-1.5 text-[10.5px] text-white/60">- <span className="font-mono">pass {p.round}</span>- <span className="px-1.5 rounded bg-[#02C0CC]/10 text-[#02C0CC] text-[9.5px] font-semibold">- {PASS_ACTION_META[p.action] ?? p.action}- </span>- </div>- {p.summary && <p className="text-[10.5px] text-white/45 mt-0.5 leading-snug">{p.summary}</p>}- {p.issues.slice(0, 5).map((issue, j) => (- <p key={j} className="text-[10.5px] text-white/55 leading-snug mt-0.5">- <span className="font-bold mr-1">{issue.severity}</span>- {issue.issue}- </p>- ))}- </div>- ))}- </div>- )}- <div className="flex items-center gap-2 text-[10px] text-white/35 border-t border-white/8 pt-2">- <Gauge size={10} />- <span>- {result.report.modelCalls} model calls · {result.report.revisionRounds} revision rounds- {result.report.cycleGuard ? ' · cycle guard tripped' : ''}- {result.report.spec?.format- ? ` · compiled ${result.report.spec.format.width}×${result.report.spec.format.height}`- : ''}- </span>- </div>- </div>- </details>- )}- </div>- )}- </div>- )-}--/** One reviewable compiled page: honest geometry wireframe + toggle. */-function PageReviewCard({- index,- page,- specWidth,- specHeight,- enabled,- onToggle,-}: {- index: number- page: PageData- specWidth: number- specHeight: number- enabled: boolean- onToggle: () => void-}) {- const previewW = 96- const previewH = Math.max(48, Math.round((previewW * specHeight) / Math.max(1, specWidth)))- const bg =- page.background?.type === 'gradient'- ? `linear-gradient(${page.background.angle}deg, ${page.background.from}, ${page.background.to})`- : page.background?.type === 'solid'- ? page.background.color- : '#FFFFFF'-- return (- <div- className={cn(- 'rounded-xl border p-2.5 flex gap-2.5 items-center transition-colors',- enabled ? 'border-white/12 bg-white/[0.04]' : 'border-white/8 bg-white/[0.015] opacity-60',- )}- >- <button- onClick={onToggle}- className={cn(- 'w-5 h-5 rounded-md border flex items-center justify-center shrink-0 transition-colors',- enabled ? 'bg-[#02C0CC] border-[#02C0CC] text-black' : 'border-white/25 text-transparent',- )}- aria-label={enabled ? `Disable page ${index + 1}` : `Enable page ${index + 1}`}- aria-pressed={enabled}- >- <Check size={12} strokeWidth={3.5} />- </button>- <div- className="relative shrink-0 rounded-lg overflow-hidden border border-white/10"- style={{ width: previewW, height: previewH, background: bg }}- aria-hidden- >- {page.elements.map((el: AnyElement) => (- <div- key={el.id}- className="absolute rounded-[2px]"- style={{- left: `${(el.x / specWidth) * 100}%`,- top: `${(el.y / specHeight) * 100}%`,- width: `${(el.width / specWidth) * 100}%`,- height: `${(el.height / specHeight) * 100}%`,- background: el.type === 'text' ? 'rgba(255,255,255,0.75)' : (('fill' in el ? String((el as { fill?: unknown }).fill ?? '') : '') || '#02C0CC'),- opacity: el.type === 'text' ? 0.85 : 0.8,- minHeight: 2,- }}- />- ))}- </div>- <div className="flex-1 min-w-0">- <p className="text-[11.5px] font-semibold text-white/85">- Page {index + 1}- <span className="ml-1.5 text-[10px] text-white/35 font-normal">- {specWidth}×{specHeight} · {page.elements.length} element{page.elements.length === 1 ? '' : 's'}- </span>- </p>- </div>- </div>- )-}diff --git a/src/components/editor/apps/MagicWriteApp.tsx b/src/components/editor/apps/MagicWriteApp.tsxdeleted file mode 100644index 4cc10fa..0000000--- a/src/components/editor/apps/MagicWriteApp.tsx+++ /dev/null@@ -1,197 +0,0 @@-'use client'--import { useState } from 'react'-import { Sparkles, Loader2, Plus, RefreshCw, Wand2 } from 'lucide-react'-import { createTextElement } from '@/lib/types'-import { placement } from '../add-element'-import { useEditorStore } from '@/store/editor-store'-import { AppHeader, type AppPanelProps } from './registry'-import { cn } from '@/lib/utils'-import { toast } from '@/hooks/use-toast'--const KINDS = [- { id: 'headline', label: 'Headline', fontSize: 64, bold: true },- { id: 'tagline', label: 'Tagline', fontSize: 44, bold: true },- { id: 'body', label: 'Body', fontSize: 28, bold: false },- { id: 'social', label: 'Caption', fontSize: 30, bold: false },-] as const--const TONES = ['bold', 'playful', 'elegant', 'minimal', 'corporate', 'warm'] as const--const IDEAS = [- 'A poster for a summer music festival',- 'Instagram caption for a new coffee shop',- 'Headline for an eco-friendly water bottle',- 'Tagline for a fitness app launch',-]--export function MagicWriteApp({ onClose }: AppPanelProps) {- const addElement = useEditorStore((s) => s.addElement)- const pages = useEditorStore((s) => s.pages)- const currentPage = useEditorStore((s) => s.currentPage)- const width = useEditorStore((s) => s.width)- const height = useEditorStore((s) => s.height)-- const [prompt, setPrompt] = useState('')- const [kind, setKind] = useState<(typeof KINDS)[number]['id']>('tagline')- const [tone, setTone] = useState<(typeof TONES)[number]>('bold')- const [options, setOptions] = useState<string[]>([])- const [busy, setBusy] = useState(false)- const [error, setError] = useState<string | null>(null)-- const generate = async () => {- if (!prompt.trim() || busy) return- setBusy(true)- setError(null)- setOptions([])- try {- const res = await fetch('/api/ai/write', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ prompt, kind, tone }),- })- const data = (await res.json()) as { options?: string[]; error?: string }- if (!res.ok || !data.options) throw new Error(data.error ?? 'Generation failed')- setOptions(data.options)- } catch (e) {- setError(e instanceof Error ? e.message : 'Generation failed')- } finally {- setBusy(false)- }- }-- const addToCanvas = (text: string) => {- const preset = KINDS.find((k) => k.id === kind)!- const pos = placement(Math.min(width * 0.7, 800), preset.fontSize, pages[currentPage].elements.length)- addElement(- createTextElement({- ...pos,- width: Math.min(width * 0.72, 820),- height: preset.fontSize * 1.6,- text,- fontSize: preset.fontSize,- bold: preset.bold,- align: 'center',- })- )- toast({ title: 'Added to canvas' })- }-- return (- <div>- <AppHeader icon={Wand2} title="Magic Write" onClose={onClose} />-- <div- className="rounded-xl border border-white/10 bg-white/[0.04] focus-within:border-[#7630D7] transition-colors p-3 mb-2.5"- >- <textarea- value={prompt}- onChange={(e) => setPrompt(e.target.value)}- onKeyDown={(e) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) generate() }}- rows={2}- maxLength={500}- placeholder="Describe what you need — e.g. “A poster tagline for a summer music festival”"- className="w-full bg-transparent outline-none text-[12.5px] text-white resize-none placeholder:text-white/35"- aria-label="Magic Write prompt"- />- </div>-- <div className="grid grid-cols-4 gap-1.5 mb-2">- {KINDS.map((k) => (- <button- key={k.id}- onClick={() => setKind(k.id)}- className={cn(- 'h-7 rounded-lg text-[10.5px] font-semibold transition-colors',- kind === k.id ? 'bg-[#7630D7] text-white' : 'bg-white/[0.05] text-white/60 hover:text-white'- )}- >- {k.label}- </button>- ))}- </div>-- <div className="flex gap-1.5 flex-wrap mb-2.5">- {TONES.map((t) => (- <button- key={t}- onClick={() => setTone(t)}- className={cn(- 'h-6 px-2.5 rounded-full text-[10px] font-semibold border transition-colors capitalize',- tone === t ? 'bg-white/[0.16] text-white border-white/25' : 'text-white/55 border-white/10 hover:text-white'- )}- >- {t}- </button>- ))}- </div>-- <button- onClick={generate}- disabled={busy || !prompt.trim()}- className="w-full h-10 rounded-xl bg-gradient-to-r from-[#7630D7] to-[#9B6BFF] text-white text-[13px] font-bold flex items-center justify-center gap-2 disabled:opacity-40 hover:brightness-110 transition-all"- aria-label="Generate copy"- >- {busy ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}- {busy ? 'Writing…' : 'Generate 3 options'}- </button>-- {error && (- <div className="mt-2.5">- <p className="text-[11px] text-[#FF8095]">{error}</p>- {/* v0.23.1: text-slot failures often mean "no key" */}- <p className="text-[10.5px] text-white/45 mt-1 leading-snug">- Tip: add your own AI key in <span className="text-white/75 font-medium">Profile & AI keys</span> (account menu) — your key is used before this- instance's providers.- </p>- </div>- )}-- {options.length > 0 && (- <div className="mt-3 space-y-1.5">- <div className="flex items-center justify-between">- <span className="text-[10.5px] font-bold text-white/60 uppercase tracking-wide">Results</span>- <button- onClick={generate}- className="text-[10px] text-white/50 hover:text-white flex items-center gap-1"- aria-label="Regenerate"- >- <RefreshCw size={10} /> Regenerate- </button>- </div>- {options.map((opt, i) => (- <button- key={i}- onClick={() => addToCanvas(opt)}- className="group w-full text-left rounded-xl border border-white/10 bg-white/[0.04] hover:border-[#7630D7] p-2.5 transition-colors"- role="button"- aria-label={`Add option ${i + 1}`}- >- <p className="text-[12px] text-white/90 leading-snug">{opt}</p>- <span className="hidden group-hover:flex items-center gap-1 mt-1.5 text-[10px] font-bold text-[#02C0CC]">- <Plus size={10} /> Add to canvas- </span>- </button>- ))}- </div>- )}-- {options.length === 0 && !busy && !error && (- <div className="mt-3.5">- <p className="text-[10.5px] font-bold text-white/60 uppercase tracking-wide mb-1.5">Try asking for…</p>- <div className="space-y-1">- {IDEAS.map((idea) => (- <button- key={idea}- onClick={() => setPrompt(idea)}- className="block w-full text-left text-[11.5px] text-white/55 hover:text-white rounded-lg border border-white/[0.07] hover:border-white/20 px-2.5 py-1.5 transition-colors"- >- “{idea}”- </button>- ))}- </div>- </div>- )}- </div>- )-}diff --git a/src/components/editor/apps/UnifiedAIApp.tsx b/src/components/editor/apps/UnifiedAIApp.tsxdeleted file mode 100644index d6be4d2..0000000--- a/src/components/editor/apps/UnifiedAIApp.tsx+++ /dev/null@@ -1,112 +0,0 @@-'use client'--// ─────────────────────────────────────────────────────────────-// UnifiedAIApp (v0.32.1) — ONE AI surface.-//-// The review that mattered: "I don't want multiple AI apps in-// canvix, just keep it few." Six AI-branded panels (chat copilot,-// design agent, Magic Write, AI image, AI design plan, AI theme)-// became this one app with five modes:-//-// Chat — the agent: refine THIS design in natural language-// (brief-contract gated, edit-safe)-// Generate — the autonomous pipeline: one prompt → planned,-// compiled, checked, visually verified, reviewed by-// you, applied editable-// Write — AI copy: headlines, taglines, captions-// Image — prompt → design-ready image-// Theme — palette + fonts, applied safely with contrast guards-//-// The former AI design plan app is retired — its describe → review-// → apply flow IS the Generate tab, with the stronger engine behind-// it. The /api/ai/plan route stays available as an API.-//-// Each tab renders the original self-contained app component —-// behavior, review gates and honesty contracts unchanged. The panel-// opens on Chat (the most-used mode); switching tabs keeps each-// app's internal state only while it is active, exactly as before.-// ─────────────────────────────────────────────────────────────--import { useState } from 'react'-import type { AppPanelProps } from './registry'-import { cn } from '@/lib/utils'-import { AssistantApp } from './AssistantApp'-import { DesignAgentApp } from './DesignAgentApp'-import { MagicWriteApp } from './MagicWriteApp'-import { AIImageApp } from './AIImageApp'-import { AIThemeApp } from './AIThemeApp'--const TABS = [- {- id: 'chat',- label: 'Chat',- hint: 'Refine this design in natural language — brief-contract gated',- Component: AssistantApp,- },- {- id: 'generate',- label: 'Generate',- hint: 'One prompt in — a checked, reviewed, editable design out',- Component: DesignAgentApp,- },- {- id: 'write',- label: 'Write',- hint: 'AI copy — headlines, taglines & captions',- Component: MagicWriteApp,- },- {- id: 'image',- label: 'Image',- hint: 'Turn a prompt into a design-ready image',- Component: AIImageApp,- },- {- id: 'theme',- label: 'Theme',- hint: 'Palette + fonts for the whole design, applied safely',- Component: AIThemeApp,- },-] as const--type TabId = (typeof TABS)[number]['id']--export function UnifiedAIApp({ onClose }: AppPanelProps) {- const [tab, setTab] = useState<TabId>('chat')- const active = TABS.find((t) => t.id === tab) ?? TABS[0]- const Active = active.Component- const select = (id: TabId) => {- setTab(id)- }- return (- <div className="flex flex-col gap-2">- <div role="tablist" aria-label="Canvix AI modes" className="flex flex-wrap gap-1.5">- {TABS.map((t) => (- <div- key={t.id}- role="tab"- tabIndex={0}- aria-selected={tab === t.id}- title={t.hint}- onClick={() => select(t.id)}- onKeyDown={(e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault()- select(t.id)- }- }}- className={cn(- 'cursor-pointer select-none rounded-full px-3 py-1 text-[11px] font-semibold transition-colors',- tab === t.id- ? 'bg-[#7630D7] text-white'- : 'bg-white/5 text-white/55 hover:bg-white/10 hover:text-white',- )}- >- {t.label}- </div>- ))}- </div>- <Active onClose={onClose} />- </div>- )-}diff --git a/src/components/editor/apps/registry.tsx b/src/components/editor/apps/registry.tsxindex f713866..553cd37 100644--- a/src/components/editor/apps/registry.tsx+++ b/src/components/editor/apps/registry.tsx@@ -31,17 +31,20 @@ import { IllustrationsApp } from './IllustrationsApp'import { PaletteApp } from './PaletteApp'import { LoremApp } from './LoremApp'import { StickersApp } from './StickersApp'-import { UnifiedAIApp } from './UnifiedAIApp'+import { AssistantApp } from './AssistantApp'export const CANVIX_APPS: CanvixApp[] = [- // AI apps first (canva 2026: “Canva AI” is the flagship surface)- // v0.32.1 (Unified Canvix AI): ONE AI surface. The six AI-branded- // apps (chat copilot, design agent, Magic Write, AI image, AI- // design plan, AI theme) consolidated into a single app with five- // modes (Chat / Generate / Write / Image / Theme — see- // UnifiedAIApp). The AI design plan panel is retired: its- // describe → review → apply flow IS the Generate tab.- { id: 'ai', name: 'Canvix AI', desc: 'One AI for the whole design — chat, generate, write, images, theme', icon: Bot, color: '#7630D7', content: UnifiedAIApp },+ // v0.32.6 · ONE agent, ZERO selectors. The v0.32.1 "unified" app+ // kept five tabs (Chat / Generate / Write / Image / Theme) and the+ // chat tab still carried seven mode chips (Auto/Create/Edit/+ // Review/Improve/Explain/Plan) — three nested agent surfaces. The+ // review that mattered: "no need for this chat, generate, write+ // and all that — keep one that does all by himself."+ // AssistantApp is that one agent: it classifies every message+ // itself and runs the whole pipeline autonomously — map the+ // canvas (occupancy), plan the geometry into the free space,+ // build, check and fix overlap, verify against the brief, stop.+ { id: 'ai', name: 'Canvix AI', desc: 'One agent — describe what you want; it maps, plans, builds, checks and verifies by itself', icon: Bot, color: '#7630D7', content: AssistantApp },{ id: 'charts', name: 'Charts', desc: 'Bar, line & donut charts as editable shapes', icon: BarChart3, color: '#7630D7', content: ChartsApp },{ id: 'qr', name: 'QR generator', desc: 'Turn any link or text into a QR code', icon: QrCode, color: '#3B82F6', content: QRApp },{ id: 'icons', name: 'Icons', desc: '562 offline icons + the Iconify universe online', icon: Shapes, color: '#02C0CC', content: IconsApp },diff --git a/src/lib/agent/context.ts b/src/lib/agent/context.tsindex 161553d..0eda674 100644--- a/src/lib/agent/context.ts+++ b/src/lib/agent/context.ts@@ -15,6 +15,7 @@// ─────────────────────────────────────────────────────────────import type { DesignBrief } from './brief'+import { mergeOccupied } from './plan-repair'export interface AgentElementCtx {id: string@@ -124,3 +125,23 @@ export function serializeDesignContext(d: AgentDesignCtx): string {export function contextValidIds(d: AgentDesignCtx): Set<string> {return new Set((d.elements ?? []).map((e) => e.id))}++/** v0.32.6 · the CANVAS MAP: existing elements as occupied vertical+ * bands (merged, disjoint, label = text excerpt or type). The plan+ * solver fits new sections into the FREE space between these bands,+ * so a plan can never reserve space on top of existing content —+ * "it first maps what's present geometrically" happens here, in+ * deterministic code, not in the model's arithmetic. */+export function canvasMap(d: AgentDesignCtx): { y: number; h: number; label?: string }[] {+ const raw = (d.elements ?? [])+ .filter((e) => typeof e.y === 'number' && (typeof e.height === 'number' || typeof e.fontSize === 'number'))+ .map((e) => ({+ y: e.y as number,+ h: Math.max(1, Math.round((e.height as number | undefined) ?? (e.fontSize as number | undefined) ?? 24)),+ label:+ typeof e.text === 'string' && e.text.trim()+ ? e.text.trim().slice(0, 24)+ : undefined,+ }))+ return mergeOccupied(raw)+}diff --git a/src/lib/agent/harness.test.ts b/src/lib/agent/harness.test.tsindex d712c7f..31673ba 100644--- a/src/lib/agent/harness.test.ts+++ b/src/lib/agent/harness.test.ts@@ -66,6 +66,25 @@ const design: AgentDesignCtx = {otherPages: ['p1: 4 elements', 'p2: 7 elements'],}+/** v0.32.6 · the same fixture compacted to the top 240px. Same+ * ids/texts/overlaps (update flows keep their targets), but the+ * canvas has real FREE space (y 240..1015) so a plan of additions+ * fits the canvas map. The spread-out original left only 415px of+ * contiguous free space — a full-composition plan on it is now+ * (correctly) infeasible, which is what a real improve run on a+ * nearly-full canvas should honestly say. */+const compactDesign: AgentDesignCtx = {+ ...design,+ elements: [+ { id: 'el-1', type: 'rect', x: 0, y: 0, width: 100, height: 100, fill: '#FF0000' },+ { id: 'el-2', type: 'rect', x: 40, y: 20, width: 100, height: 100, fill: '#00FF00' },+ { id: 'txt-1', type: 'text', x: 0, y: 60, width: 400, height: 60, text: 'Hello', fontSize: 48, fill: '#111111' },+ { id: 'txt-2', type: 'text', x: 0, y: 150, width: 400, height: 60, text: 'World', fontSize: 32, fill: '#222222' },+ { id: 'grp-1', type: 'group', x: 10, y: 0, width: 150, height: 100 },+ { id: 'img-1', type: 'image', x: 0, y: 140, width: 300, height: 100 },+ ],+}+/** scripted chat: pops replies in order; records every request */function scriptedChat(replies: string[]) {const calls: { role: string; content: string }[][] = []@@ -282,7 +301,7 @@ describe('harness · tool matrix', () => {])const result = await runAgentLoop({chat,- design,+ design: compactDesign,mode: 'create',request: 'Design a bold Instagram post for a coffee launch',emit: (e) => events.push(e),@@ -314,7 +333,7 @@ describe('harness · tool matrix', () => {])const result = await runAgentLoop({chat,- design,+ design: compactDesign,mode: 'create',request: 'Design a bold Instagram post for a coffee launch',emit: (e) => events.push(e),@@ -344,7 +363,7 @@ describe('harness · tool matrix', () => {])const result = await runAgentLoop({chat,- design,+ design: compactDesign,mode: 'create',request: 'Design a bold Instagram post for a coffee launch',emit: (e) => events.push(e),@@ -368,7 +387,7 @@ describe('harness · tool matrix', () => {])const result = await runAgentLoop({chat,- design,+ design: compactDesign,mode: 'create',request: 'Design a bold Instagram post for a coffee launch',emit: (e) => events.push(e),@@ -591,7 +610,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {])const result = await runAgentLoop({chat,- design,+ design: compactDesign,mode: 'create',request: 'Design a bold Instagram post for a coffee launch',brief,@@ -628,7 +647,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {const events: AgentEvent[] = []const result = await runAgentLoop({chat,- design,+ design: compactDesign,mode: 'create',request: 'Design a bold Instagram post for a coffee launch',brief,@@ -737,7 +756,11 @@ describe('harness · lifecycle flows (Cases A–F)', () => {}const result = await runAgentLoop({chat,- design,+ // v0.32.6: the canvas map — C builds on a canvas that already+ // has content; the compact fixture leaves real free space so+ // the plan records (the spread-out original left 415px, and a+ // 540px composition honestly did not fit)+ design: compactDesign,mode: 'create',request: 'Design a bold Instagram post for a coffee launch',emit: () => {},@@ -763,12 +786,12 @@ describe('harness · lifecycle flows (Cases A–F)', () => {])const result = await runAgentLoop({chat,- design,+ design: compactDesign,mode: 'improve',request: 'Make this design more professional',emit: () => {},awaitApply: async () => ({ ok: true }),- refreshedContext: () => design,+ refreshedContext: () => compactDesign,})expect(result.toolCalls).toBe(4)expect(result.summary).toContain('fixed')@@ -828,7 +851,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {let declined = falseconst result = await runAgentLoop({chat,- design,+ design: compactDesign,mode: 'create',request: 'Design a bold Instagram post for a coffee launch',emit: () => {},@@ -838,7 +861,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {return false},awaitApply: async () => ({ ok: true }),- refreshedContext: () => design,+ refreshedContext: () => compactDesign,validateBriefOnClient: async () => ({ satisfied: true, unmet: [] }),})// every write tool applied except the declined clear_page; the@@ -889,7 +912,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {if (n === 5) signal.aborted = truereturn turn('add_sticker', { emoji: '⭐', n }) // distinct args — no cycle guard},- design,+ design: compactDesign,mode: 'create',request: 'Design a bold Instagram post for a coffee launch',emit: () => {},@@ -963,7 +986,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {replies.push(done('Long run complete'))const result = await runAgentLoop({chat: scriptedChat(replies).chat,- design,+ design: compactDesign,mode: 'create',request: 'Design a bold Instagram post for a coffee launch',emit: (e) => events.push(e),@@ -1343,7 +1366,7 @@ describe('v0.29.3 · loop: vision critique BEFORE completion', () => {}const result = await runAgentLoop({chat,- design,+ design: compactDesign,mode: 'create',request: 'Design a bold Instagram post for a coffee launch',emit: (e) => events.push(e),@@ -2399,3 +2422,138 @@ describe('v0.32.5 · honest outcome classification (a failure is never a green cexpect(turnOutcome({ mode: 'discuss', verification: undefined, content: 'This poster uses a strong vertical hierarchy…', appliedActions: 0 })).toBe('unknown')})})++// ═════════════════════════════════════════════════════════════+// v0.32.6 · the CANVAS MAP — "when the user asks it to do+// something it first maps the background and what's present and+// all that geometrically so that overlap won't happen and it will+// know where to put everything by using geometry and math and+// boundaries." Existing elements become occupied bands; plans are+// fitted into the FREE space between them, deterministically.+// ═════════════════════════════════════════════════════════════++describe('v0.32.6 · the canvas map — plans fit the FREE space, never on top', () => {+ const mapCtx = (occupied: { y: number; h: number; label?: string }[]): ToolContext => ({+ ...ctx,+ occupied,+ })+ // a 1080 canvas (safe y 65..1015) with existing content:+ // headline y 65–365, card row y 405–805 → free: 365–405 (40px,+ // unusable for two bands), 805–1015 (210px usable)+ const occupied = [+ { y: 65, h: 300, label: 'COFFEE LAUNCH' },+ { y: 405, h: 400, label: 'Artisan Roast' },+ ]++ it('the solver fits sections into the LARGEST fitting free interval', async () => {+ const { repairPlanBands } = await import('./plan-repair')+ const r = repairPlanBands(+ [+ { name: 'offer', y: 400, h: 100 },+ { name: 'fineprint', y: 950, h: 50 },+ ],+ 1080,+ { occupied },+ )+ expect(r.ok).toBe(true)+ if (!r.ok) return+ // both sections live inside 805..1015 — never on the occupied bands+ for (const b of r.bands) {+ expect(b.y).toBeGreaterThanOrEqual(805)+ expect(b.y + b.h).toBeLessThanOrEqual(1015)+ }+ expect(r.bands[0].y).toBe(805)+ expect(r.bands[1].y - (r.bands[0].y + r.bands[0].h)).toBeGreaterThanOrEqual(40)+ expect(r.repairs.join(' ')).toContain('free space')+ })++ it('sections that cannot fit the free space are INFEASIBLE with the exact map', async () => {+ const { repairPlanBands } = await import('./plan-repair')+ const r = repairPlanBands(+ [+ { name: 'offer', y: 400, h: 200 },+ { name: 'cards', y: 700, h: 300 },+ { name: 'footer', y: 950, h: 60 },+ ],+ 1080,+ { occupied },+ )+ expect(r.ok).toBe(false)+ if (r.ok) return+ // the error carries the occupancy map and the largest free interval+ expect(r.infeasible).toContain('existing elements occupy y 65–365 (COFFEE LAUNCH)')+ expect(r.infeasible).toContain('y 405–805 (Artisan Roast)')+ expect(r.infeasible).toContain('largest free interval is 210px')+ expect(r.infeasible).toContain('Move or clear existing elements')+ })++ it('canvasMap merges close elements into disjoint occupied bands', async () => {+ const { canvasMap } = await import('./context')+ const d = {+ name: 'Map test', width: 1080, height: 1080, pageCount: 1, currentPageIndex: 0,+ // two elements 35px apart merge (a 40px band cannot fit between)+ elements: [+ { id: 'a', type: 'text', y: 65, height: 200, text: 'Headline' },+ { id: 'b', type: 'rect', y: 300, height: 100 },+ { id: 'c', type: 'text', y: 900, fontSize: 60, text: 'Footer line' },+ ],+ colorsInUse: [], otherPages: [],+ } as never as AgentDesignCtx+ const map = canvasMap(d)+ expect(map).toEqual([+ { y: 65, h: 335, label: 'Headline' },+ { y: 900, h: 60, label: 'Footer line' },+ ])+ })++ it('plan_layout on an occupied canvas discloses the CANVAS MAP and fits the free space', () => {+ const tool = AGENT_TOOL_MAP.get('plan_layout')+ expect(tool).toBeTruthy()+ const res = tool!.sanitize(+ { sections: [{ name: 'offer', y: 380, height: 100, contains: 'limited time' }, { name: 'legal', y: 980, height: 50, contains: 'terms' }] },+ mapCtx(occupied),+ )+ expect(res.ok).toBe(true)+ const obs = String((res as { observation?: string }).observation)+ expect(obs).toContain('CANVAS MAP')+ expect(obs).toContain('y 65–365 (COFFEE LAUNCH)')+ expect(obs).toContain('fitted into the FREE space')+ const bands = (res as { actions?: { bands?: { name: string; y: number; h: number }[] }[] }).actions?.[0]?.bands+ for (const b of bands ?? []) {+ expect(b.y).toBeGreaterThanOrEqual(805)+ expect(b.y + b.h).toBeLessThanOrEqual(1015)+ }+ })++ it('the loop maps the design it is GIVEN: plans on a design with elements avoid them', async () => {+ const events: AgentEvent[] = []+ const occupiedDesign: AgentDesignCtx = {+ name: 'Half-built poster', width: 1080, height: 1080, pageCount: 1, currentPageIndex: 0,+ elements: [+ { id: 'txt-1', type: 'text', y: 65, height: 300, text: 'EXISTING HEADLINE' },+ ],+ colorsInUse: [], otherPages: [],+ }+ const { chat } = scriptedChat([+ turn('plan_layout', { sections: [{ name: 'offer', y: 100, height: 100, contains: 'sale' }] }),+ turn('set_background', { kind: 'solid', from: '#090B1A' }),+ done('Planned around the existing headline.'),+ ])+ const result = await runAgentLoop({+ chat, design: occupiedDesign, mode: 'improve',+ request: 'Add an offer banner under the headline',+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ })+ expect(result.summary).toContain('Planned around')+ // the CANVAS MAP rides the OBSERVATION (disclosed to the model+ // AND the user), the fitted band rides the plan event+ const obs = events.find((e) => e.type === 'observation') as { message?: string } | undefined+ expect(obs?.message).toContain('CANVAS MAP')+ expect(obs?.message).toContain('EXISTING HEADLINE')+ const plan = events.find((e) => e.type === 'plan') as { steps?: string[] } | undefined+ // the single band was fitted BELOW the occupied headline: free+ // space starts at y=365 (headline occupies 65–365)+ expect(plan?.steps?.join('\n')).toContain('y=365')+ })+})diff --git a/src/lib/agent/loop.ts b/src/lib/agent/loop.tsindex cf33bad..25a73d8 100644--- a/src/lib/agent/loop.ts+++ b/src/lib/agent/loop.ts@@ -44,7 +44,7 @@ export function telemetry(event: Record<string, unknown>): void {}}import { AGENT_TOOLS, AGENT_TOOL_MAP, fontFamilies, type ToolContext, type SanitizeResult, type AgentTool } from './tools'-import { serializeDesignContext, contextValidIds, type AgentDesignCtx } from './context'+import { serializeDesignContext, contextValidIds, canvasMap, type AgentDesignCtx } from './context'import { MODE_PROMPTS, MODE_TOOL_RISK } from './router'import { skillsPromptSection, selectSkills, type DesignSkill } from './skills'import { briefPromptSection, type DesignBrief } from './brief'@@ -341,6 +341,10 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {width: design.width ?? 1080,height: design.height ?? 1080,fonts: new Set(fontFamilies()),+ // v0.32.6 · the CANVAS MAP: existing elements' occupied bands.+ // The plan solver fits new sections into the FREE space between+ // them — nothing is planned on top of existing content.+ occupied: canvasMap(design),}const messages: { role: 'system' | 'user' | 'assistant'; content: string }[] = [@@ -899,7 +903,9 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {content: `UPDATED PAGE STATE (fresh from the client after your edits):\n${serializeDesignContext(refreshed)}`,})// refresh the local tool context too — new ids are valid now+ // and the canvas map reflects what the edits actually occupytoolCtx.validIds = contextValidIds(refreshed)+ toolCtx.occupied = canvasMap(refreshed)continue}diff --git a/src/lib/agent/plan-repair.ts b/src/lib/agent/plan-repair.tsindex 77c602a..dc2f8ab 100644--- a/src/lib/agent/plan-repair.ts+++ b/src/lib/agent/plan-repair.ts@@ -32,6 +32,14 @@ export interface RepairedBand {h: number}+/** v0.32.6 · an existing element's occupied vertical extent on the+ * page (label = its text or type, for the canvas map disclosure). */+export interface OccupiedBand {+ y: number+ h: number+ label?: string+}+export interface PlanRepairOk {ok: true/** valid bands, ordered top-to-bottom, all inside the safe area */@@ -53,10 +61,59 @@ export type PlanRepairResult = PlanRepairOk | PlanRepairInfeasibleexport const PLAN_MIN_GAP = 40export const PLAN_MARGIN = 0.06+/** Merge raw occupied extents into disjoint bands. Two occupied+ * extents closer than minGap merge: the sliver between them cannot+ * host a new band, so it is occupied for planning purposes. */+export function mergeOccupied(raw: OccupiedBand[], minGap = PLAN_MIN_GAP): OccupiedBand[] {+ const bands = raw+ .filter((b) => b.h > 0)+ .map((b) => ({ y: Math.max(0, Math.round(b.y)), h: Math.round(b.h), label: b.label }))+ .sort((a, b) => a.y - b.y)+ const out: OccupiedBand[] = []+ for (const b of bands) {+ const last = out[out.length - 1]+ if (last && b.y - (last.y + last.h) < minGap) {+ // merge: keep the union extent and the earlier label+ const end = Math.max(last.y + last.h, b.y + b.h)+ last.h = end - last.y+ if (!last.label && b.label) last.label = b.label+ } else {+ out.push({ ...b })+ }+ }+ return out+}++/** The free intervals of [top, bottom] not covered by occupied+ * bands — where new content may be planned. */+function freeIntervals(top: number, bottom: number, occupied: OccupiedBand[]): { y: number; h: number }[] {+ const free: { y: number; h: number }[] = []+ let cursor = top+ for (const b of occupied) {+ const start = Math.max(b.y, top)+ const end = Math.min(b.y + b.h, bottom)+ if (start > cursor) free.push({ y: cursor, h: start - cursor })+ if (end > cursor) cursor = end+ }+ if (bottom > cursor) free.push({ y: cursor, h: bottom - cursor })+ return free.filter((f) => f.h > 0)+}++/** "y 65–365 (headline)" — one map entry */+function mapEntry(b: { y: number; h: number; label?: string }): string {+ return `y ${Math.round(b.y)}–${Math.round(b.y + b.h)}${b.label ? ` (${b.label})` : ''}`+}+/*** Deterministic layout solver.** Rules, in order:+ * 0. OCCUPIED CANVAS (v0.32.6): when existing elements are present+ * they are the map — the sections are fitted into the FREE+ * intervals between them (order preserved, ≥minGap gaps), never+ * on top of anything. Sections that cannot fit anywhere produce+ * an INFEASIBLE result carrying the full occupancy map with the+ * exact numbers.* 1. A plan whose bands already tile the safe area top-to-bottom* with ≥minGap gaps is accepted UNCHANGED (repairs = []).* 2. Otherwise the sections are re-laid out from the top of the@@ -70,7 +127,7 @@ export const PLAN_MARGIN = 0.06export function repairPlanBands(requested: PlanSection[],H: number,- opts?: { minGap?: number; margin?: number },+ opts?: { minGap?: number; margin?: number; occupied?: OccupiedBand[] },): PlanRepairResult {const minGap = opts?.minGap ?? PLAN_MIN_GAPconst margin = opts?.margin ?? PLAN_MARGIN@@ -89,6 +146,59 @@ export function repairPlanBands(const usable = safeBottom - safeTopconst sumH = sections.reduce((acc, s) => acc + s.h, 0)+ // ── Rule 0 · occupied canvas: fit into the FREE space ────────+ const occupied = mergeOccupied(opts?.occupied ?? [], minGap)+ if (occupied.length) {+ const free = freeIntervals(safeTop, safeBottom, occupied)+ const mapLine = occupied.map(mapEntry).join(', ')+ const freeLine = free.length ? free.map(mapEntry).join(', ') : 'nothing'+ // prefer ONE free interval that fits everything (natural spread)+ const fitsAll = free.filter((f) => f.h >= sumH + minGap * (n - 1))+ const bands: RepairedBand[] = []+ const repairs: string[] = []+ if (fitsAll.length) {+ const f = fitsAll[0]+ const gap = n > 1 ? Math.max(minGap, Math.floor((f.h - sumH) / (n - 1))) : minGap+ let y = f.y+ for (const s of sections) {+ bands.push({ name: s.name, y, h: s.h })+ if (s.y !== y) repairs.push(`"${s.name}" y ${Math.round(s.y)}→${y}`)+ y += s.h + gap+ }+ if (n > 1) repairs.push(`uniform ${gap}px gaps inside the free space y ${f.y}–${f.y + f.h}`)+ return { ok: true, bands, gap, repairs }+ }+ // no single interval fits all: first-fit across intervals in+ // order (still ≥minGap inside an interval, order preserved)+ let fi = 0+ let y = free.length ? free[0].y : safeTop+ let intervalEnd = free.length ? free[0].y + free[0].h : safeTop+ for (const s of sections) {+ // advance to an interval with room for this section+ while (fi < free.length && y + s.h > intervalEnd) {+ fi += 1+ if (fi < free.length) {+ y = free[fi].y+ intervalEnd = free[fi].y + free[fi].h+ } else break+ }+ if (y + s.h > intervalEnd) {+ return {+ ok: false,+ infeasible:+ `Infeasible plan on an occupied canvas: existing elements occupy ${mapLine}; ` ++ `free space: ${freeLine}. Your ${n} sections (${sumH}px of content) do not fit the free space ` ++ `(the largest free interval is ${free.length ? Math.max(...free.map((f) => f.h)) : 0}px). ` ++ `Move or clear existing elements first, or plan fewer/smaller sections.`,+ }+ }+ bands.push({ name: s.name, y, h: s.h })+ if (s.y !== y) repairs.push(`"${s.name}" y ${Math.round(s.y)}→${y}`)+ y += s.h + minGap+ }+ return { ok: true, bands, gap: minGap, repairs }+ }+if (sumH > usable) {return {ok: false,diff --git a/src/lib/agent/tools.ts b/src/lib/agent/tools.tsindex b1f966d..276fd87 100644--- a/src/lib/agent/tools.ts+++ b/src/lib/agent/tools.ts@@ -43,6 +43,11 @@ export interface ToolContext {height: number/** fonts available in the catalog (family names) */fonts: Set<string>+ /** v0.32.6 · the CANVAS MAP: existing elements' occupied vertical+ * bands (merged, disjoint — see plan-repair.ts). The plan solver+ * fits new sections into the FREE space between them so nothing+ * is planned on top of existing content. */+ occupied?: { y: number; h: number; label?: string }[]}export type SanitizeResult =@@ -167,7 +172,7 @@ export const AGENT_TOOLS: AgentTool[] = [// 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.',+ '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). The SERVER computes the exact y-positions: with ≥40px gaps into the safe area, and on a canvas that already has content, into the FREE space between existing elements (never on top of them) — supply names, heights and order; approximate y is fine.',risk: 'read',argsSpec: '{background?: "#RRGGBB", sections: [{name: string, y: number, height: number, contains: string}], notes?: string}',sanitize: (args, ctx) => {@@ -210,7 +215,16 @@ export const AGENT_TOOLS: AgentTool[] = [// · cannot fit → honest infeasibility with the exact// math (the model shrinks or drops// sections — never a fabrication)- const repair = repairPlanBands(parsed.map((p) => ({ name: p.name, y: p.y, h: p.h })), H)+ // v0.32.6 · the CANVAS MAP: on a canvas that already has+ // content, ctx.occupied carries the existing elements' bands;+ // the solver fits the requested sections into the FREE space+ // between them — the plan can never reserve space on top of+ // something that is already there.+ const repair = repairPlanBands(+ parsed.map((p) => ({ name: p.name, y: p.y, h: p.h })),+ H,+ { occupied: ctx.occupied },+ )if (!repair.ok) {return {ok: false,@@ -230,10 +244,16 @@ export const AGENT_TOOLS: AgentTool[] = [const notes = typeof args.notes === 'string' ? args.notes.trim().slice(0, 200) : ''if (notes) lines.push(`notes: ${notes}`)+ // the canvas map disclosure: what is already on the page and+ // where the free space is — visible to the user AND the model+ const occupied = ctx.occupied ?? []+ const mapNote = occupied.length+ ? `CANVAS MAP — existing elements occupy y ${occupied.map((o) => `${Math.round(o.y)}–${Math.round(o.y + o.h)}${o.label ? ` (${o.label})` : ''}`).join(', ')}; your sections were fitted into the FREE space (never on top of them).`+ : ''const repairedNote = repair.repairs.length? `PLAN AUTO-REPAIRED (your heights, order and contents were kept; the SERVER computed valid positions): ${repair.repairs.join('; ')}. Build inside these exact bands — do not recompute them.`: 'Bands verified: non-overlapping, ≥40px gaps, inside the safe area. Build inside these exact bands.'- const observation = `PLAN RECORDED (${lines.length} lines):\n${lines.join('\n')}\n${repairedNote}`+ const observation = `${mapNote ? `${mapNote}\n` : ''}PLAN RECORDED (${lines.length} lines):\n${lines.join('\n')}\n${repairedNote}`return {ok: true,actions: [{ type: '__planLayout', lines, bands: repair.bands }],diff --git a/tests/e2e/unified-ai-reproduction.spec.ts b/tests/e2e/unified-ai-reproduction.spec.tsindex 6d68a27..be6220e 100644--- a/tests/e2e/unified-ai-reproduction.spec.ts+++ b/tests/e2e/unified-ai-reproduction.spec.ts@@ -154,10 +154,10 @@ test.describe('Unified Canvix AI reproduction (v0.32.2 fix)', () => {})})- // ── Canvix AI → Chat (default tab) → the reproduction prompt ──+ // ── Canvix AI (the one agent, no tabs) → the reproduction prompt ──await page.getByRole('button', { name: 'Apps', exact: true }).click()await page.getByText('Canvix AI', { exact: true }).first().click()- await page.getByPlaceholder('Describe what to design or change…').fill(PROMPT)+ await page.getByPlaceholder('Describe what to design or change — the agent figures out the rest…').fill(PROMPT)await page.getByRole('button', { name: 'Send', exact: true }).click()// the ORIGINAL request reached the route, verbatim, UNPINNED (Auto)@@ -288,7 +288,7 @@ test.describe('v0.32.5 · the P0 regression — zero-action failures and follow-await page.getByRole('button', { name: 'Apps', exact: true }).click()await page.getByText('Canvix AI', { exact: true }).first().click()- await page.getByPlaceholder('Describe what to design or change…').fill(PROMPT)+ await page.getByPlaceholder('Describe what to design or change — the agent figures out the rest…').fill(PROMPT)await page.getByRole('button', { name: 'Send', exact: true }).click()// the honest amber failure status — the disclosed failure@@ -339,7 +339,7 @@ test.describe('v0.32.5 · the P0 regression — zero-action failures and follow-await page.getByText('Canvix AI', { exact: true }).first().click()// turn 1: the production coffee prompt- await page.getByPlaceholder('Describe what to design or change…').fill(PROMPT)+ await page.getByPlaceholder('Describe what to design or change — the agent figures out the rest…').fill(PROMPT)await page.getByRole('button', { name: 'Send', exact: true }).click()await waitForDoc(page,@@ -349,7 +349,7 @@ test.describe('v0.32.5 · the P0 regression — zero-action failures and follow-)// turn 2: the production follow-up, in the SAME conversation- await page.getByPlaceholder('Describe what to design or change…').fill('Create by yourself')+ await page.getByPlaceholder('Describe what to design or change — the agent figures out the rest…').fill('Create by yourself')await page.getByRole('button', { name: 'Send', exact: true }).click()// the follow-up request reached the route VERBATIM, with thediff --git a/tests/e2e/wave4-ai-powerup.spec.ts b/tests/e2e/wave4-ai-powerup.spec.tsindex 4ce155f..571d376 100644--- a/tests/e2e/wave4-ai-powerup.spec.ts+++ b/tests/e2e/wave4-ai-powerup.spec.ts@@ -150,37 +150,6 @@ async function selectViaLayers(page: Page, label: string) {await page.getByText(label, { exact: true }).click()}-/** open a registry app from the Apps rail */-async function openApp(page: Page, appName: string) {- await page.getByRole('button', { name: 'Apps', exact: true }).click()- await page.getByText(appName, { exact: true }).first().click()-}--/** v0.32.1: the six AI apps consolidated into ONE "Canvix AI" app —- * open it and switch to the named mode tab (Chat / Generate /- * Write / Image / Theme). The tab contents are the original,- * unchanged app components. */-async function openUnifiedAI(page: Page, tab: string) {- await openApp(page, 'Canvix AI')- await page.getByRole('tab', { name: tab, exact: true }).click()-}--const MOCK_THEME = {- theme: {- name: 'Nordic calm',- mood: 'cool editorial',- palette: [- { hex: '#0B1220', role: 'background' },- { hex: '#16233A', role: 'surface' },- { hex: '#F5F7FA', role: 'ink' },- { hex: '#C3CCDA', role: 'inkSoft' },- { hex: '#5B8DEF', role: 'accent' },- { hex: '#9BB8F5', role: 'accentSoft' },- ],- fonts: { heading: 'Montserrat', body: 'Inter' },- },-}-const MOCK_NOTES = {notes: [{ page: 1, text: 'Welcome the room, land the one number that matters, tease the demo.' },@@ -250,40 +219,13 @@ test.describe('Wave 4 — AI Power-Up', () => {expect(d.pages[1].notes).toContain('margin story')})- test('AI theme: palette preview applies design-wide with contrast guards', async ({ page }) => {- await register(page, 'theme')- const designId = await createDesign(page, 'w4 theme', [- textEl({ text: 'Headline', fontSize: 72 }),- textEl({ id: 'w4_body', text: 'Body copy here', y: 240, fontSize: 24, bold: false }),- imageEl({ x: 120, y: 400 }),- ])- await openEditor(page, designId)-- await page.route('**/api/ai/theme', (route) => route.fulfill({ json: MOCK_THEME }))- await openUnifiedAI(page, 'Theme')-- await page.getByLabel('Theme mood').fill('nordic calm, cool editorial')- await page.getByRole('button', { name: 'Generate' }).click()-- // the preview: six role rows + the font pairing- await expect(page.getByText('Nordic calm', { exact: true })).toBeVisible({ timeout: 15_000 })- await expect(page.getByText('Montserrat + Inter')).toBeVisible()- await expect(page.getByText('Background', { exact: true })).toBeVisible()-- await page.getByRole('button', { name: 'Apply theme' }).click()-- // document truth: background + text recolored, image untouched- const applied = await waitForDoc(- page,- designId,- (d) => (d.pages[0].elements as any[]).some((e) => e.fill === '#F5F7FA'),- 'the applied theme'- )- const els = applied.pages[0].elements- expect(els.find((e) => e.type === 'text' && e.fontSize === 72)?.fill).toBe('#F5F7FA') // heading ink- expect(els.find((e) => e.type === 'text' && e.fontSize === 24)?.fill).toBe('#C3CCDA') // body inkSoft- expect(els.find((e) => e.type === 'image')?.src).toContain('data:image/png;base64,') // untouched- })+ // v0.32.6: the AI-theme TAB test is retired WITH its tab — the+ // five-tab unified app (Chat / Generate / Write / Image / Theme)+ // became ONE selector-free agent (AssistantApp: it classifies+ // every message itself and does everything by itself). The theme+ // route (/api/ai/theme) remains available as an API; theming a+ // design through the app is now a plain agent request ("recolor+ // this design…") pinned by the unified-ai-reproduction spec.test('local image tools: upscaler really enlarges; brush eraser + alt UI are wired', async ({ page }) => {await register(page, 'local')