Skip to content

Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.

fix(v0.32.2): Canvix AI ignored creative requests and looped on an empty canvas (#89)

Ashiq Hussain Mirdfe7947954d0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 585e1c5..bc9f6ff 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,12 +3,45 @@
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/).
-## [Unreleased] — Unified Canvix AI (create → verify → refine) + the hardening pass
-
-> One engineering upgrade, four unifications, one external review
-> closed (4 findings) and ONE AI surface — full write-up in
-> `docs/UNIFIED-AI-MILESTONE.md` (the v0.32.1 section), acceptance in
-> `src/lib/design-agent/continuation.test.ts`.
+## [Unreleased] — Unified Canvix AI hardening + the reproduction fix
+
+> The external-review hardening (v0.32.1) and the production
+> reproduction fix (v0.32.2) — write-ups in
+> `docs/UNIFIED-AI-MILESTONE.md`.
+
+### Fixed — the production reproduction (v0.32.2): "Canvix AI ignores creative requests and loops on an empty canvas"
+
+- **Intent classification (`router.ts`):** social-media posts,
+ stories, reels and platform names are first-class artifact nouns
+ ("Design a bold Instagram post for a coffee launch" routed to EDIT
+ because the artifact vocabulary missed them). Styling adjectives
+ (bold/minimal/elegant/dark/colorful) are no longer edit evidence in
+ any list — an adjective describes the requested design; the verb
+ carries edit intent, so "Make the existing title bold" still routes
+ to edit. "What is wrong …" joins the review guard; artifact nouns
+ inside existing-element references ("make the poster title bold")
+ stay edits.
+- **The original request reaches the model (`loop.ts`):** the loop's
+ conversation opened with a synthetic "User request mode: edit.
+ Begin." instead of the user's actual words. `request` is now a
+ MANDATORY `runAgentLoop` input and becomes the first user message,
+ verbatim — preserved through compaction, retries and tool
+ observations.
+- **Honest completion:** a create/improve run that applied zero
+ design changes can no longer report success — the first such done
+ is bounced with build guidance, the second ends as `INCOMPLETE —
+ no design changes were made` with a `NOT completed` verification;
+ the strikes/idle/cycle/provider guards report the same honest
+ framing. Guards unchanged (nothing bypassed, no limits raised).
+ A pinned edit mode on an empty canvas is respected, not converted —
+ the model explains and asks what to create instead of looping.
+- Regressions: 9 new unit tests (the five mandatory mode cases,
+ request-as-first-message, compaction survival, the scripted
+ reproduction with no `get_page_state` loop, the honest empty
+ report) + a new browser e2e (`unified-ai-reproduction.spec.ts`)
+ running the exact reproduction through the real editor: Auto mode
+ sends the verbatim request unpinned, the created design saves,
+ reopens and is editable through the real properties UI.
### Added — design provenance (the contract that persists, verified)
diff --git a/docs/UNIFIED-AI-MILESTONE.md b/docs/UNIFIED-AI-MILESTONE.md
index 220a39c..a4cbd60 100644
--- a/docs/UNIFIED-AI-MILESTONE.md
+++ b/docs/UNIFIED-AI-MILESTONE.md
@@ -225,3 +225,96 @@ plan panel's UI test was retired with the panel.
over-limit refusals with explicit reasons, flat 404 on missing ids.
- Migration `0014` validated offline against Prisma's own schema
derivation (statement-equal) and applied by CI's db:setup.
+
+---
+
+# v0.32.2 — the production reproduction fix (26 Nov 2026)
+
+**Report:** "Canvix AI → Chat → Auto, empty 1080×1920 canvas, the
+suggested prompt 'Design a bold Instagram post for a coffee launch' —
+mode `edit`, repeated `get_page_state`, the model claims no design
+brief was provided, nothing created, cycle guard ends the run."
+
+Both confirmed code defects are fixed, plus the honesty requirements.
+
+## Defect A — intent classification (router.ts)
+
+The artifact vocabulary missed the entire social-media family, so the
+prompt had no create signal; the styling adjective "bold" sat in BOTH
+edit-evidence lists and flipped it to edit. Fixes: platform
+posts/stories/reels and platform names are first-class artifact
+nouns; **styling adjectives are no longer edit evidence in any list**
+(an adjective describes the requested design — "Design a bold
+Instagram post" is create; the VERB carries edit intent, so "Make the
+existing title bold" still routes to edit); "What is wrong …" (and
+its curly-apostrophe form) joins the review guard; an artifact noun
+inside an existing-element reference ("make the poster title bold")
+is exempted from the create-first guards. The classifier prompt
+teaches the same rule.
+
+## Defect B — the request never reached the model (loop.ts)
+
+The loop's conversation opened with the synthetic
+`User request mode: edit. Begin.` — the user's actual request existed
+only in the route, and `runAgentLoop()` had no request parameter.
+`request: string` is now a MANDATORY loop input and becomes the first
+user message, verbatim. `compactMessages` keeps `messages[1]` by
+construction, so it survives compaction (regression-tested through a
+70-turn run that compacts mid-run); tool observations and gate
+feedback append after it. The route passes the original message.
+
+## The honesty requirements
+
+- **Progress gate:** a create/improve run that applied ZERO
+ write/destructive tools cannot claim completion — the first such
+ done is bounced with explicit build guidance; the second ends the
+ run as `INCOMPLETE — no design changes were made` with
+ verification `NOT completed …` (never reported as a created
+ design). The strikes / idle / cycle / provider guards report the
+ same honest framing for empty create runs. Guards are UNCHANGED
+ (no limit raised, no bypass).
+- **Pinned modes are respected, not converted:** an explicitly pinned
+ edit run on an empty canvas keeps edit mode; the edit-mode prompt
+ now instructs the model to say so honestly and ask what to create,
+ instead of inventing elements or re-reading the page forever.
+
+## Should the Chat tab delegate full creation to DesignAgent?
+
+Investigated — recommendation: **not yet, and not silently.** The
+DesignAgent pipeline (plan → compile → deterministic checks → visual
+verify → user review gate) is the stronger engine for COMPLETE
+multi-block designs, but delegating chat create-runs to it would
+change the response contract mid-conversation (the pipeline returns
+pages + a review gate, not the streaming action protocol the chat
+panel renders) and would take the design decisions away from the
+conversation the user is in. The right evolution, as a follow-up with
+its own acceptance: offer the hand-off EXPLICITLY — when a chat
+create run completes, the panel suggests "want the full pipeline? Run
+Generate" (a one-click jump to the Generate tab, already in the
+unified Canvix AI app); and/or an explicit "use the design agent"
+phrase in Auto mode that routes to the pipeline with the same
+request. The fixed chat loop is honest and capable for first drafts
+(as the reproduction proves); the pipeline stays the premium path.
+This PR keeps the chat loop's behavior otherwise untouched — BYOK,
+rate limits, cancellation, brief contracts, ownership checks, tool
+validation, undo and autosave all ride the unchanged bridge.
+
+## Evidence (v0.32.2)
+
+- Unit: 1,718/1,718 (9 new regressions in `harness.test.ts`: the
+ five mandatory mode cases, adjective-vs-verb routing, the
+ request-as-first-message check, compaction survival, the scripted
+ reproduction creation with no `get_page_state` loop, the
+ bounced-then-honest empty done, the pure-cycle honest end, and the
+ brief-gate-before-done case).
+- Browser (new `tests/e2e/unified-ai-reproduction.spec.ts`, the exact
+ reproduction through the real editor): Auto mode sends the verbatim
+ request unpinned; the create run's streamed actions land as native
+ editable elements; autosave persists them; the design reopens; the
+ user edits the AI-created headline through the real properties UI
+ (font size 132→96, unlocked) and it saves. Screenshots captured.
+- Real-provider evaluation: NOT RUN — no provider credentials exist
+ in this sandbox (checked `.z-ai-config*`, provider env vars). The
+ browser regression runs with the agent route mocked to the exact
+ stream the fixed loop emits; the live canvix.app run after deploy
+ is the real-provider check.
diff --git a/src/app/api/ai/agent/route.ts b/src/app/api/ai/agent/route.ts
index b3414f3..e518f5d 100644
--- a/src/app/api/ai/agent/route.ts
+++ b/src/app/api/ai/agent/route.ts
@@ -371,6 +371,10 @@ async function __canvix_post(req: NextRequest) {
chat,
design,
mode,
+ // v0.32.2 (defect B): the ORIGINAL user request rides the
+ // loop as the actual first user message — the model sees
+ // what it was asked for, verbatim, all run long
+ request: message,
brief,
skills,
emit,
diff --git a/src/lib/agent/harness.test.ts b/src/lib/agent/harness.test.ts
index 9433196..fc72645 100644
--- a/src/lib/agent/harness.test.ts
+++ b/src/lib/agent/harness.test.ts
@@ -283,6 +283,7 @@ describe('harness · tool matrix', () => {
chat,
design,
mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
emit: (e) => events.push(e),
awaitApply: async () => ({ ok: true }),
auditDesign: async () => {
@@ -313,6 +314,7 @@ describe('harness · tool matrix', () => {
chat,
design,
mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
emit: (e) => events.push(e),
awaitApply: async () => ({ ok: true }),
// the audit NEVER clears — the run must still terminate honestly
@@ -341,6 +343,7 @@ describe('harness · tool matrix', () => {
chat,
design,
mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
emit: (e) => events.push(e),
awaitApply: async () => ({ ok: true }),
auditDesign: async () => ['Low contrast: text "Dark text" #111122 on #090B1A is 1.0:1 (needs 3:1)'],
@@ -363,6 +366,7 @@ describe('harness · tool matrix', () => {
chat,
design,
mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
emit: (e) => events.push(e),
awaitApply: async () => ({ ok: true }),
})
@@ -584,6 +588,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
chat,
design,
mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
brief,
emit: (e) => events.push(e),
awaitApply: async () => ({ ok: true }),
@@ -619,6 +624,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
chat,
design,
mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
brief,
emit: (e) => events.push(e),
awaitApply: async () => ({ ok: true }),
@@ -657,6 +663,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
chat,
design,
mode: 'review',
+ request: 'What is wrong with this design?',
emit: (e) => {
if (e.type === 'action') appliedTools.push(e.tool)
events.push(e)
@@ -680,6 +687,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
chat: rogueChat,
design,
mode: 'review',
+ request: 'What is wrong with this design?',
emit: (e) => {
if (e.type === 'action') rogueAppliedTools.push(e.tool)
},
@@ -724,6 +732,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
chat,
design,
mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
emit: () => {},
awaitApply: async () => ({ ok: true }),
refreshedContext: () => refreshed,
@@ -748,6 +757,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
chat,
design,
mode: 'improve',
+ request: 'Make this design more professional',
emit: () => {},
awaitApply: async () => ({ ok: true }),
refreshedContext: () => design,
@@ -811,6 +821,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
chat,
design,
mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
emit: () => {},
confirmed: new Set(),
awaitConfirm: async () => {
@@ -836,6 +847,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
chat: async () => turn('update_elements', { ids: ['ghost'], patch: { fill: '#123456' } }),
design,
mode: 'edit',
+ request: 'Make the existing title bigger',
emit: (e) => events.push(e),
awaitApply: async () => ({ ok: true }),
})
@@ -849,6 +861,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
chat: async () => turn('add_sticker', { emoji: '🤖' }),
design,
mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
emit: (e) => events.push(e),
awaitApply: async () => ({ ok: true }),
})
@@ -868,6 +881,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
},
design,
mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
emit: () => {},
signal,
awaitApply: async () => ({ ok: true }),
@@ -886,6 +900,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
chat,
design,
mode: 'edit',
+ request: 'Make the existing title bigger',
emit: () => {},
confirmed: new Set(),
awaitConfirm: async () => false,
@@ -906,6 +921,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
},
design,
mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
emit: (e) => events.push(e),
})
expect(result.toolCalls).toBe(0)
@@ -922,6 +938,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
chat,
design,
mode: 'review',
+ request: 'What is wrong with this design?',
emit: () => {},
awaitApply: async () => ({ ok: true }),
})
@@ -937,6 +954,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
chat: scriptedChat(replies).chat,
design,
mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
emit: (e) => events.push(e),
awaitApply: async () => ({ ok: true }),
})
@@ -952,6 +970,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
chat: scriptedChat(replies).chat,
design,
mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
emit: (e) => events.push(e),
awaitApply: async () => ({ ok: true }),
})
@@ -1313,6 +1332,7 @@ describe('v0.29.3 · loop: vision critique BEFORE completion', () => {
chat,
design,
mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
emit: (e) => events.push(e),
awaitApply: async () => ({ ok: true }),
captureCanvas: async () => {
@@ -1344,6 +1364,7 @@ describe('v0.29.3 · loop: vision critique BEFORE completion', () => {
chat,
design,
mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
emit: (e) => events.push(e),
awaitApply: async () => ({ ok: true }),
captureCanvas: async () => 'data:image/png;base64,AAA',
@@ -1367,6 +1388,7 @@ describe('v0.29.3 · loop: vision critique BEFORE completion', () => {
chat,
design,
mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
emit: (e) => events.push(e),
awaitApply: async () => ({ ok: true }),
captureCanvas: async () => null,
@@ -1385,6 +1407,7 @@ describe('v0.29.3 · loop: vision critique BEFORE completion', () => {
chat,
design,
mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
emit: () => {},
awaitApply: async () => ({ ok: true }),
captureCanvas: async () => 'data:image/png;base64,AAA',
@@ -1408,7 +1431,7 @@ describe('v0.29.3 · loop: planning + fail-closed acks', () => {
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 result = await runAgentLoop({ chat, design, mode: 'create', request: 'Design a bold Instagram post for a coffee launch', 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')
@@ -1440,6 +1463,7 @@ describe('v0.29.3 · loop: planning + fail-closed acks', () => {
chat,
design,
mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
emit: () => {},
// v0.29.3 route semantics: timeout resolves ok:false
awaitApply: async () => ({ ok: false, message: 'ack timeout — the client did NOT confirm the apply' }),
@@ -1515,3 +1539,239 @@ describe('v0.29.4 · new skills (glassmorphism, mockups, accessibility)', () =>
expect(section).toContain('Skill: Realistic Product Mockups')
})
})
+
+// ═════════════════════════════════════════════════════════════
+// v0.32.2 · THE PRODUCTION REPRODUCTION (P0: "Canvix AI ignores
+// creative requests and loops on an empty canvas")
+//
+// "Design a bold Instagram post for a coffee launch" in Auto mode
+// on an empty 1080×1920 canvas routed to EDIT, the model never saw
+// the request ("User request mode: edit. Begin." was the only user
+// message), looped get_page_state, and the run ended with nothing
+// created. Both defects + the honesty requirements are pinned here.
+// ═════════════════════════════════════════════════════════════
+
+describe('v0.32.2 · router: the Instagram-post misroute (defect A)', () => {
+ it('the five mandatory regressions', () => {
+ expect(heuristicMode('Design a bold Instagram post for a coffee launch')).toEqual({ mode: 'create', confidence: 'high' })
+ expect(heuristicMode('Create a colorful social media graphic')).toEqual({ mode: 'create', confidence: 'high' })
+ expect(heuristicMode('Make the existing title bold')).toEqual({ mode: 'edit', confidence: 'high' })
+ expect(heuristicMode('Move the coffee cup image to the right')).toEqual({ mode: 'edit', confidence: 'high' })
+ expect(heuristicMode('What is wrong with this design?')).toEqual({ mode: 'review', confidence: 'high' })
+ })
+
+ it('styling adjectives describe the requested design — they are NOT edit evidence', () => {
+ for (const msg of [
+ 'Design a bold Instagram post for a coffee launch',
+ 'design a minimal instagram story',
+ 'make a vibrant tiktok cover',
+ 'create an elegant linkedin post',
+ 'a colorful facebook ad please',
+ 'Design a bold poster',
+ 'make me a dark moody menu',
+ ]) {
+ expect(heuristicMode(msg).mode, msg).toBe('create')
+ }
+ })
+
+ it('an artifact noun inside an existing-element reference is still an edit', () => {
+ expect(heuristicMode('Make the poster title bold').mode).toBe('edit')
+ expect(heuristicMode('delete the instagram logo on page 2').mode).toBe('edit')
+ expect(heuristicMode('make the existing title bold').mode).toBe('edit')
+ })
+})
+
+describe('v0.32.2 · loop: the original request reaches the model (defect B)', () => {
+ const emptyDesign: AgentDesignCtx = {
+ name: 'Untitled',
+ width: 1080,
+ height: 1920,
+ pageCount: 1,
+ currentPageIndex: 0,
+ elements: [],
+ colorsInUse: [],
+ otherPages: [],
+ }
+ const REQUEST = 'Design a bold Instagram post for a coffee launch'
+
+ it('the FIRST model call carries the full original request as the actual user message, verbatim', async () => {
+ const events: AgentEvent[] = []
+ const { chat, calls } = scriptedChat([
+ turn('set_background', { kind: 'solid', from: '#1B3A6B' }),
+ done('Created'),
+ ])
+ await runAgentLoop({
+ chat,
+ design: emptyDesign,
+ mode: 'create',
+ request: REQUEST,
+ emit: (e) => events.push(e),
+ awaitApply: async () => ({ ok: true }),
+ })
+ expect(calls.length).toBeGreaterThan(0)
+ expect(calls[0]?.[0]?.role).toBe('system')
+ expect(calls[0]?.[1]?.role).toBe('user')
+ // the USER'S OWN WORDS — not "User request mode: create. Begin."
+ expect(calls[0]?.[1]?.content).toBe(REQUEST)
+ })
+
+ it('the request survives compaction — long runs never lose what was asked', async () => {
+ const events: AgentEvent[] = []
+ // 70 distinct writes ≈ 140 messages → past maxMessages(120),
+ // compaction fires mid-run; messages[1] must stay the request
+ const replies = Array.from({ length: 70 }, (_, i) =>
+ turn('add_text', { text: `line ${i}`, y: 40 + i * 20, fontSize: 24, color: '#FFFFFF' }),
+ )
+ replies.push(done('Long build complete'))
+ const { chat, calls } = scriptedChat(replies)
+ const result = await runAgentLoop({
+ chat,
+ design: emptyDesign,
+ mode: 'create',
+ request: REQUEST,
+ emit: (e) => events.push(e),
+ awaitApply: async () => ({ ok: true }),
+ })
+ expect(events.some((e) => e.type === 'compact')).toBe(true)
+ const lastCall = calls[calls.length - 1]
+ expect(lastCall?.[1]?.role).toBe('user')
+ expect(lastCall?.[1]?.content).toBe(REQUEST)
+ expect(result.summary).not.toContain('INCOMPLETE')
+ })
+})
+
+describe('v0.32.2 · loop: the reproduction end-to-end on an empty canvas', () => {
+ const emptyDesign: AgentDesignCtx = {
+ name: 'Untitled',
+ width: 1080,
+ height: 1920,
+ pageCount: 1,
+ currentPageIndex: 0,
+ elements: [],
+ colorsInUse: [],
+ otherPages: [],
+ }
+ const REQUEST = 'Design a bold Instagram post for a coffee launch'
+
+ it('creates a complete native editable design from the reproduction prompt — no get_page_state loop', async () => {
+ const events: AgentEvent[] = []
+ const { chat, calls } = scriptedChat([
+ turn('set_background', { kind: 'gradient', from: '#120A2A', to: '#2E1A47' }),
+ turn('add_text', { text: 'ARTISAN ROAST', y: 210, fontSize: 132, color: '#FFFFFF', bold: true }),
+ turn('add_text', { text: 'our coffee launch — first sip free', y: 400, fontSize: 46, color: '#E8D9FF' }),
+ turn('add_shape', { shape: 'rect', x: 140, y: 780, width: 800, height: 360, fill: '#2E1A47' }),
+ turn('add_text', { text: 'order at canvix.coffee', y: 920, fontSize: 56, color: '#FFFFFF' }),
+ done('Coffee-launch Instagram post created: bold headline, offer line and CTA card, night palette.'),
+ ])
+ const result = await runAgentLoop({
+ chat,
+ design: emptyDesign,
+ mode: 'create',
+ request: REQUEST,
+ emit: (e) => events.push(e),
+ awaitApply: async () => ({ ok: true }),
+ })
+
+ // the model BUILT: five applied write tools
+ expect(result.toolCalls).toBe(5)
+ // native editable elements were emitted as real design actions
+ const actions = events.filter((e) => e.type === 'action') as unknown as { tool: string; actions: unknown[] }[]
+ const actionJson = JSON.stringify(actions.flatMap((a) => a.actions))
+ expect(actionJson).toContain('"type":"addText"')
+ expect(actionJson).toContain('"type":"addShape"')
+ expect(actionJson).toContain('ARTISAN ROAST')
+ // NO state-inspection loop during a successful create
+ expect(actions.map((a) => a.tool)).not.toContain('get_page_state')
+ // honest SUCCESS (changes were made) — not an INCOMPLETE wrap-up
+ expect(result.summary).not.toContain('INCOMPLETE')
+ expect(events[events.length - 1]?.type).toBe('done')
+ // and the model saw what it was asked for
+ expect(calls[0]?.[1]?.content).toBe(REQUEST)
+ })
+
+ it('the failure shape is bounced and reported honestly — never "successfully created"', async () => {
+ const events: AgentEvent[] = []
+ // the exact reproduction behavior: inspect, inspect again, then
+ // claim you cannot proceed because "no design brief was provided"
+ const { chat, calls } = scriptedChat([
+ turn('get_page_state', {}),
+ turn('get_page_state', {}),
+ done('I need more information — no design brief was provided.'),
+ turn('get_page_state', { page: 0 }),
+ done('Still cannot proceed without requirements.'),
+ ])
+ const result = await runAgentLoop({
+ chat,
+ design: emptyDesign,
+ mode: 'create',
+ request: REQUEST,
+ emit: (e) => events.push(e),
+ awaitApply: async () => ({ ok: true }),
+ })
+
+ // the premature done was REJECTED with build guidance
+ const bounce = calls.find((c) => c.some((m) => m.role === 'user' && m.content.includes('NOT DONE — this is a create run')))
+ expect(bounce).toBeDefined()
+ // and the run ended HONESTLY: no design changes → not a success
+ expect(result.summary).toContain('INCOMPLETE — no design changes were made')
+ expect(result.verification).toContain('NOT completed')
+ const final = events[events.length - 1] as { type: string; summary?: string; verification?: string }
+ expect(final.type).toBe('done')
+ expect(String(final.summary)).toContain('INCOMPLETE')
+ expect(String(final.verification)).toContain('NOT completed')
+ })
+
+ it('a pure get_page_state cycle on an empty canvas ends INCOMPLETE — the guard stays, honestly', async () => {
+ const events: AgentEvent[] = []
+ const { chat } = scriptedChat([
+ turn('get_page_state', {}),
+ turn('get_page_state', {}),
+ turn('get_page_state', {}),
+ ])
+ const result = await runAgentLoop({
+ chat,
+ design: emptyDesign,
+ mode: 'create',
+ request: REQUEST,
+ emit: (e) => events.push(e),
+ awaitApply: async () => ({ ok: true }),
+ })
+ expect(result.summary).toContain('INCOMPLETE')
+ expect(result.verification).toContain('NOT completed')
+ })
+
+ it('the brief gate still runs before a create run may claim completion', async () => {
+ const events: AgentEvent[] = []
+ const { chat, calls } = scriptedChat([
+ turn('set_background', { kind: 'solid', from: '#111111' }),
+ turn('add_text', { text: 'Coffee launch', fontSize: 90, color: '#FFFFFF' }),
+ done('Done attempt 1 — missing the required color'),
+ turn('add_text', { text: 'order at canvix.coffee', fontSize: 40, color: '#E2604F' }),
+ done('Done — requirements met'),
+ ])
+ // validation answers unsatisfied until the model's fix round
+ // (the 4th turn adds the missing required text), then passes
+ let validations = 0
+ const result = await runAgentLoop({
+ chat,
+ design: emptyDesign,
+ mode: 'create',
+ request: 'Coffee launch post with "Coffee launch" and the color #E2604F',
+ brief: extractBrief('"Coffee launch" and the color #E2604F'),
+ emit: (e) => events.push(e),
+ awaitApply: async () => ({ ok: true }),
+ validateBriefOnClient: async () => {
+ validations += 1
+ return validations === 1
+ ? { satisfied: false, unmet: ['Required text missing or altered: "order at canvix.coffee"'] }
+ : { satisfied: true, unmet: [] }
+ },
+ })
+ // the first done was rejected for the unmet requirement…
+ expect(calls.some((c) => c.some((m) => m.role === 'user' && m.content.includes('NOT DONE (attempt 1 of 3)')))).toBe(true)
+ // …the fix round added the missing text → the re-validation passed
+ expect(validations).toBe(2)
+ expect(result.summary).not.toContain('INCOMPLETE')
+ expect(result.verification).toContain('Brief contract validated')
+ })
+})
diff --git a/src/lib/agent/loop.ts b/src/lib/agent/loop.ts
index 068218d..734f34c 100644
--- a/src/lib/agent/loop.ts
+++ b/src/lib/agent/loop.ts
@@ -44,6 +44,14 @@ export interface LoopDeps {
chat: ChatFn
design: AgentDesignCtx
mode: AgentMode
+ /** v0.32.2 (defect B, production report): the user's ORIGINAL
+ * request, verbatim. It becomes the first user message of the
+ * model conversation and survives compaction — the model must
+ * always be able to see what it was asked for, not a synthetic
+ * "User request mode: edit. Begin." placeholder (which starved
+ * the model of the actual creative brief: it kept inspecting the
+ * canvas, claimed no brief was given and created nothing). */
+ request: string
/** the run's brief contract (extracted by the route) */
brief?: DesignBrief | null
/** v0.29: local quality audit of the latest design snapshot
@@ -237,6 +245,15 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
* claiming completion without fixing the unmet items must not
* loop forever (LangChain's "declare it blocked" pattern). */
let doneRejections = 0
+ /** v0.32.2 (progress requirement): how many WRITE/DESTRUCTIVE tool
+ * calls were actually applied in this run. A create/improve run
+ * that changed NOTHING must not be reported as successfully
+ * created — the reproduction (empty canvas, model looped on
+ * get_page_state, claimed "no design brief provided") ended with
+ * a normal done summary over an untouched document. */
+ let designChanges = 0
+ /** done turns rejected because the run changed nothing yet */
+ let emptyDoneRejections = 0
const toolCtx: ToolContext = {
validIds: contextValidIds(design),
@@ -247,12 +264,12 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
const messages: { role: 'system' | 'user' | 'assistant'; content: string }[] = [
{ role: 'system', content: loopSystemPrompt({ design, ctx: toolCtx, mode, brief, skills }) },
- {
- role: 'user',
- content: `User request mode: ${mode}. Begin.${
- mode === 'discuss' || mode === 'explain' ? ' Answer the question directly and emit done with your answer in the summary.' : ''
- }`,
- },
+ // v0.32.2 (defect B): the ORIGINAL user request is the actual
+ // first user message. compactMessages always keeps messages[1],
+ // so it survives compaction; tool observations and gate
+ // feedback append AFTER it, never replace it. The mode guidance
+ // lives in the system prompt (MODE_PROMPTS), not here.
+ { role: 'user', content: deps.request },
]
emit({ v: AGENT_PROTOCOL_VERSION, type: 'mode', mode, reason: `classified as ${mode}` })
@@ -265,6 +282,17 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
lastProgressAt = Date.now()
}
+ /** v0.32.2 (progress requirement): guard exits must be HONEST about
+ * what actually happened — a create/improve run that changed
+ * nothing is INCOMPLETE, never a wrapped-up success. */
+ const guardExit = (base: string): { summary: string; verification: string | undefined } =>
+ (mode === 'create' || mode === 'improve') && designChanges === 0
+ ? {
+ summary: `INCOMPLETE — no design changes were made. ${base}`,
+ verification: 'NOT completed — the run ended without applying any design change; nothing was created.',
+ }
+ : { summary: base, verification }
+
while (true) {
// ── task-driven stops ───────────────────────────────────
if (signal?.aborted) {
@@ -289,18 +317,20 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
message: `Stopped after ${AGENT_GUARDS.strikes} consecutive invalid tool calls — the error under each step explains what to fix; try rephrasing the request.`,
code: 'STRIKES',
})
- return { summary: summary || 'Stopped after repeated invalid calls.', steps, toolCalls, verification }
+ const exit = guardExit(summary || 'Stopped after repeated invalid calls.')
+ return { summary: exit.summary, steps, toolCalls, verification: exit.verification }
}
if (Date.now() - lastProgressAt > AGENT_GUARDS.idleMs) {
+ const exit = guardExit('The run stopped making progress and was wrapped up. Everything applied so far is kept — send a follow-up message to continue.')
emit({
v: AGENT_PROTOCOL_VERSION,
type: 'done',
- summary: 'The run stopped making progress and was wrapped up. Everything applied so far is kept — send a follow-up message to continue.',
+ summary: exit.summary,
steps,
toolCalls,
- verification,
+ verification: exit.verification,
})
- return { summary, steps, toolCalls, verification }
+ return { summary: exit.summary, steps, toolCalls, verification: exit.verification }
}
// ── compaction (memory + provider context protection) ───
@@ -324,7 +354,8 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
message: `The AI provider failed: ${err instanceof Error ? err.message.slice(0, 200) : 'unknown error'}. Applied work is kept — retry to continue.`,
code: 'PROVIDER',
})
- return { summary, steps, toolCalls, verification }
+ const exit = guardExit(summary)
+ return { summary: exit.summary, steps, toolCalls, verification: exit.verification }
}
const turn = parseAgentTurn(raw)
@@ -345,6 +376,26 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
// ── done? ────────────────────────────────────────────────
if (turn.done) {
summary = String(turn.summary ?? '').slice(0, 800) || 'Done.'
+ // v0.32.2 (progress requirement): a create/improve run that has
+ // not changed the document yet cannot claim completion. The
+ // first such done is bounced with build guidance; the second
+ // ends the run HONESTLY (never reported as a created design).
+ if ((mode === 'create' || mode === 'improve') && designChanges === 0) {
+ emptyDoneRejections += 1
+ if (emptyDoneRejections >= 2) {
+ const honest = `INCOMPLETE — no design changes were made. ${summary}`
+ const noChangeVerification =
+ 'NOT completed — the run ended without applying any design change; nothing was created.'
+ emit({ v: AGENT_PROTOCOL_VERSION, type: 'done', summary: honest, steps, toolCalls, verification: noChangeVerification })
+ return { summary: honest, steps, toolCalls, verification: noChangeVerification }
+ }
+ messages.push({
+ role: 'user',
+ content:
+ 'NOT DONE — this is a create run and the canvas has not been changed yet. Build the requested design NOW with your tools: set_background first, then add_text for every headline/subline/CTA and add_rect/add_shape for structure (the user\u2019s original request is the first message of this conversation). Emit done only after the design exists on the canvas. If you believe you cannot proceed, explain exactly what is missing in your summary.',
+ })
+ continue
+ }
// BRIEF GATE (Phase 5): create/improve runs must validate
// against real client state before completion is accepted.
// v0.32 (Unified Canvix AI): an EDIT run that carries a brief
@@ -575,15 +626,16 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
if (hash === lastCallHash) {
cycleCount += 1
if (cycleCount >= AGENT_GUARDS.cycleRepeat - 1) {
+ const exit = guardExit('The run repeated the same operation without effect and was wrapped up. Applied work is kept — describe the next change to continue.')
emit({
v: AGENT_PROTOCOL_VERSION,
type: 'done',
- summary: 'The run repeated the same operation without effect and was wrapped up. Applied work is kept — describe the next change to continue.',
+ summary: exit.summary,
steps,
toolCalls,
- verification,
+ verification: exit.verification,
})
- return { summary, steps, toolCalls, verification }
+ return { summary: exit.summary, steps, toolCalls, verification: exit.verification }
}
} else {
cycleCount = 0
@@ -648,6 +700,9 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
toolCalls += 1
steps += 1
markProgress()
+ // v0.32.2: only real writes count as design changes (reads —
+ // get_page_state/measure/plan/validate — never do)
+ if (tool.risk === 'write' || tool.risk === 'destructive') designChanges += 1
emit({ v: AGENT_PROTOCOL_VERSION, type: 'observation', stepIndex: steps - 1, message: result.observation })
// usage telemetry: immediately on the first apply, then at most
diff --git a/src/lib/agent/router.ts b/src/lib/agent/router.ts
index 2737741..6252364 100644
--- a/src/lib/agent/router.ts
+++ b/src/lib/agent/router.ts
@@ -41,7 +41,7 @@ export function modeAllowsWrites(mode: AgentMode): boolean {
/** System-prompt heading per mode. */
export const MODE_PROMPTS: Record<AgentMode, string> = {
create: 'MODE: CREATE — build the requested design on the canvas. Empty or stale pages are yours to fill; respect the Design Brief Contract exactly.',
- edit: 'MODE: EDIT — perform the specific requested modifications. Touch only what the request implies; preserve everything else.',
+ edit: 'MODE: EDIT — perform the specific requested modifications. Touch only what the request implies; preserve everything else. If the canvas is empty with nothing to edit, say so honestly in your summary and ask what to create instead — do not invent elements and do not keep re-reading the page.',
review: 'MODE: REVIEW — inspect the design and report findings. You have NO write tools: every critique must be grounded in the page state you read. Report only what is actually present; missing required items are findings, not facts to invent. End with {"done":true,"summary":…,"findings":[{severity,issue,fix}]}.',
improve: 'MODE: IMPROVE — apply professional design refinements (typography, hierarchy, spacing, contrast, alignment). Preserve content and intent; improve execution.',
explain: 'MODE: EXPLAIN — answer the question about the design, its elements or the editor. Read state as needed; do not modify anything.',
@@ -86,11 +86,27 @@ export function heuristicMode(message: string): { mode: AgentMode; confidence: '
// "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.
+ //
+ // v0.32.2 (defect A, production report): the artifact vocabulary
+ // missed the entire social-media family — "Design a bold Instagram
+ // post for a coffee launch" had NO artifact noun, so the styling
+ // adjective "bold" became the only signal … and "bold" sat in the
+ // EDIT lists. Platform posts/stories/reels are first-class design
+ // artifacts now.
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/
+ /\b(poster|flyer|menu|logo|banner|thumbnail|deck|presentation|slide|campaign|invitation|infographic|card|graphic|advert|ad|cover|header|brochure|certificate|resume|newsletter|posts?|stor(ies|y)|reels?|story)\b|\b(instagram|insta|tiktok|pinterest|linkedin|facebook|twitter|threads|snapchat|youtube|social[- ]media)\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) {
+
+ // v0.32.2 (defect A): an artifact noun + build verb normally means
+ // create — but "make the poster title bold" is an EDIT of an
+ // existing thing. Exempt messages that pair an edit verb with a
+ // reference to an EXISTING element ("the title", "this logo",
+ // "existing headline") from the create-first guard.
+ const editVerb = /\b(make|set|change|turn|swap|move|align|center|centre|delete|remove|add|resize|rename|duplicate|rotate|flip|recolor|recolour)\b/
+ const elementRef = /\b(the|this|that|these|those|existing|current|selected)\s+(\w+\s+){0,2}(title|headline|subtitle|texts?|logo|icon|image|images?|photo|picture|shape|element|background|border|caption|body|copy|button|card|badge|label|grid|rows?|columns?|lines?|boxes?|circles?|cup|price|prices|tagline)\b/
+ const editingExisting = editVerb.test(lower) && elementRef.test(lower)
+ if (artifactNoun.test(lower) && buildVerb.test(lower) && !asksQuestion && !editingExisting) {
return { mode: 'create', confidence: 'high' }
}
@@ -101,7 +117,10 @@ export function heuristicMode(message: string): { mode: AgentMode; confidence: '
if (asksAboutProduct || fixTheProduct) return { mode: 'discuss', confidence: 'high' }
// review: critique/feedback asks — never modify
- if (/\b(what'?s wrong|critique|review|feedback|rate|score|assess|evaluate|how does (this|it) look)\b/.test(lower)) {
+ // v0.32.2: "What is wrong with this design?" (no apostrophe) joins
+ // "what's wrong" — the reproduction report showed it falling past
+ // this guard into the model router
+ if (/\b(what(?:['’]?s| is) wrong|what(?:['’]?s| is) (the problem|missing)|critique|review|feedback|rate|score|assess|evaluate|how does (this|it) look)\b/.test(lower)) {
return { mode: /\band (fix|improve|change)\b/.test(lower) ? 'improve' : 'review', confidence: 'high' }
}
@@ -128,21 +147,33 @@ export function heuristicMode(message: string): { mode: AgentMode; confidence: '
// "make a poster" is create even though "make" is also a surgical
// 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' }
+ // v0.32.2: editingExisting ("make the poster title bold") is exempt
+ // here too — an artifact noun inside an existing-element reference
+ // is still an edit.
+ if (artifactNoun.test(lower) && m.split(/\s+/).length >= 2 && !editingExisting) {
+ return { mode: 'create', confidence: 'high' }
+ }
const createSignals = [
/\b(design|create|make|build|generate)\b.*\b(a|an|me|the|some)\b/,
/\bcomplete redesign\b|\brebrand\b|\bmakeover\b/,
]
if (createSignals.filter((re) => re.test(lower)).length >= 1 && m.split(/\s+/).length >= 3) {
- // "make X bold" is edit, not create — single-element surgical verbs
- const surgical = /\b(make|set|change|turn|swap|move|align|center|centre|delete|remove|add|bold|italic|underline|bigger|smaller|recolor|recolour|rotate|flip)\b/.test(lower) && m.split(/\s+/).length <= 18
+ // "make X bold" is edit, not create — surgical verbs on a short
+ // message. v0.32.2 (defect A): the STYLING ADJECTIVES
+ // (bold/italic/underline/bigger/smaller) are gone from this list —
+ // "Design a bold Instagram post" describes a NEW artifact's style,
+ // it does not ask to bold anything. An adjective alone must never
+ // be edit evidence; the verb carries the intent ("make … bold").
+ const surgical =
+ editVerb.test(lower) && m.split(/\s+/).length <= 18
const mentionsBuilding = /\b(from scratch|new|blank)\b/.test(lower)
if (!surgical || mentionsBuilding) return { mode: 'create', confidence: 'high' }
}
// edit: surgical single-element changes
- const editSignals = /\b(make|set|change|turn|swap|move|align|center|centre|delete|remove|add|bold|italic|underline|bigger|smaller|recolor|recolour|rotate|flip|resize|rename|duplicate)\b/
- if (editSignals.test(lower) && m.split(/\s+/).length <= 25) return { mode: 'edit', confidence: 'high' }
+ // v0.32.2: same adjective removal — edit evidence is a VERB
+ // ("make/move/change …"), never a styling adjective
+ if (editVerb.test(lower) && m.split(/\s+/).length <= 25) return { mode: 'edit', confidence: 'high' }
return { mode: 'discuss', confidence: 'low' }
}
@@ -151,8 +182,8 @@ export function heuristicMode(message: string): { mode: AgentMode; confidence: '
* unsure). Reply JSON {"mode": "…"}. */
export const ROUTER_SYSTEM =
'You classify user messages to a graphic-design editor AI. Reply ONLY with JSON: {"mode":"create"|"edit"|"review"|"improve"|"explain"|"plan"|"discuss"}.\n' +
- 'create = build a new design or a major rebuild from a brief (poster, deck, menu, campaign, "design me…").\n' +
- 'edit = specific modifications to the existing design (make the title bold, move the logo, change this color).\n' +
+ 'create = build a new design or a major rebuild from a brief (poster, deck, menu, campaign, Instagram/social post, "design me…").\n' +
+ 'edit = specific modifications to an existing design (make the title bold, move the logo, change this color). Styling words like "bold", "minimal", "elegant", "dark" or "colorful" describe the design being asked for — they are NOT edit evidence; a request for a new artifact ("a bold Instagram post") is create.\n' +
'review = inspect and critique the design WITHOUT changing it (what is wrong, how does it look, rate it).\n' +
'improve = apply professional refinements to the existing design (make it professional, polish it, fix the layout).\n' +
'explain = answer a question about the current design or the editor (what font is this, how many pages).\n' +
diff --git a/src/lib/design-agent/continuation.test.ts b/src/lib/design-agent/continuation.test.ts
index 64f06a5..cccf119 100644
--- a/src/lib/design-agent/continuation.test.ts
+++ b/src/lib/design-agent/continuation.test.ts
@@ -229,6 +229,7 @@ async function refineWithAgent(
chat,
design,
mode: 'edit',
+ request: 'Make the headline bigger',
brief: storedBrief,
emit: (e) => {
events.push(e)
diff --git a/tests/e2e/unified-ai-reproduction.spec.ts b/tests/e2e/unified-ai-reproduction.spec.ts
new file mode 100644
index 0000000..5f6209d
--- /dev/null
+++ b/tests/e2e/unified-ai-reproduction.spec.ts
@@ -0,0 +1,210 @@
+import { test, expect, type Page, type Route } from '@playwright/test'
+
+// v0.32.2 — THE production reproduction, end to end in the real editor.
+//
+// "Design a bold Instagram post for a coffee launch" (the panel's
+// own suggestion) in Canvix AI → Chat → Auto on an EMPTY 1080×1920
+// canvas used to: route to edit, loop get_page_state, see a
+// synthetic "User request mode: edit. Begin." instead of the
+// request, and finish with nothing created.
+//
+// The agent route is MOCKED to a scripted SSE stream (no provider
+// credentials in CI — the routing/loop logic itself is pinned by
+// src/lib/agent/harness.test.ts, 9 new regressions). What this spec
+// proves at the BROWSER level:
+//
+// 1. Auto mode sends the user's ORIGINAL request, unpinned, to the
+// route (the request body carries the verbatim prompt).
+// 2. A create run's streamed design actions really land as native
+// editable elements on the canvas (and autosave persists them).
+// 3. The created design reopens with its elements intact and the
+// user can edit them through the real properties UI.
+// 4. Screenshots of the created + edited design are captured.
+
+const PROMPT = 'Design a bold Instagram post for a coffee launch'
+
+const V = 2
+
+/** the scripted run the fixed route would stream for this prompt:
+ * routed to CREATE, no state-inspection loop, four writes, done. */
+function sseScript(): string {
+ const ev = (e: unknown) => `data: ${JSON.stringify(e)}\n\n`
+ const events: unknown[] = [
+ { v: V, type: 'start', runId: 'mock-repro-run' },
+ { v: V, type: 'mode', mode: 'create', reason: 'classified as create' },
+ { v: V, type: 'step', index: 0, thought: 'night gradient background', tool: 'set_background' },
+ {
+ v: V, type: 'action', stepIndex: 0, callId: 'c0', risk: 'write', tool: 'set_background',
+ actions: [{ type: 'setBackground', kind: 'gradient', from: '#120a2a', to: '#2e1a47' }],
+ },
+ { v: V, type: 'observation', stepIndex: 0, message: 'Background set to a night gradient.' },
+ { v: V, type: 'step', index: 1, thought: 'bold headline', tool: 'add_text' },
+ {
+ v: V, type: 'action', stepIndex: 1, callId: 'c1', risk: 'write', tool: 'add_text',
+ actions: [{ type: 'addText', text: 'ARTISAN ROAST', y: 210, width: 1080, fontSize: 132, bold: true, color: '#FFFFFF', align: 'center' }],
+ },
+ { v: V, type: 'observation', stepIndex: 1, message: 'Headline added.' },
+ { v: V, type: 'step', index: 2, thought: 'offer line', tool: 'add_text' },
+ {
+ v: V, type: 'action', stepIndex: 2, callId: 'c2', risk: 'write', tool: 'add_text',
+ actions: [{ type: 'addText', text: 'our coffee launch — first sip free', y: 400, width: 1080, fontSize: 46, color: '#E8D9FF', align: 'center' }],
+ },
+ { v: V, type: 'observation', stepIndex: 2, message: 'Offer line added.' },
+ { v: V, type: 'step', index: 3, thought: 'CTA card', tool: 'add_shape' },
+ {
+ v: V, type: 'action', stepIndex: 3, callId: 'c3', risk: 'write', tool: 'add_shape',
+ actions: [{ type: 'addShape', shape: 'rect', x: 140, y: 780, width: 800, height: 360, fill: '#2E1A47' }],
+ },
+ { v: V, type: 'observation', stepIndex: 3, message: 'CTA card added.' },
+ { v: V, type: 'step', index: 4, thought: 'CTA text', tool: 'add_text' },
+ {
+ v: V, type: 'action', stepIndex: 4, callId: 'c4', risk: 'write', tool: 'add_text',
+ actions: [{ type: 'addText', text: 'order at canvix.coffee', y: 920, width: 1080, fontSize: 56, color: '#FFFFFF', align: 'center' }],
+ },
+ { v: V, type: 'observation', stepIndex: 4, message: 'CTA text added.' },
+ { v: V, type: 'usage', turns: 5, toolCalls: 5, elapsedMs: 1400, modelCalls: 6 },
+ {
+ v: V, type: 'done', steps: 5, toolCalls: 5,
+ summary: 'Coffee-launch Instagram post created: bold headline, offer line and CTA card on a night gradient.',
+ verification: 'Brief contract validated against the live canvas — all mandatory items present.',
+ },
+ ]
+ return events.map(ev).join('')
+}
+
+async function register(page: Page, tag: string): Promise<string> {
+ const username = `repro_${tag}_${Date.now().toString(36)}`
+ const password = `Repro-E2e-${username}-19!q`
+ const res = await page.request.post('/api/auth/register', { data: { username, password } })
+ expect(res.status(), `register ${username}`).toBeLessThan(300)
+ return username
+}
+
+async function createEmptyDesign(page: Page, name: string): Promise<string> {
+ // the reproduction canvas: EMPTY, 1080×1920
+ const res = await page.request.post('/api/designs', {
+ data: {
+ name,
+ width: 1080,
+ height: 1920,
+ pages: [{ id: 'p1', background: { type: 'solid', color: '#FFFFFF' }, elements: [] }],
+ },
+ })
+ expect(res.status(), `create design: ${await res.text()}`).toBeLessThan(300)
+ return ((await res.json()) as { id: string }).id
+}
+
+async function openEditor(page: Page, designId: string) {
+ await page.goto(`/design/${designId}`)
+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })
+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 60_000 })
+}
+
+type Doc = { pages: { elements: Record<string, unknown>[] }[] }
+
+async function doc(page: Page, designId: string): Promise<Doc> {
+ const res = await page.request.get(`/api/designs/${designId}`)
+ expect(res.status()).toBe(200)
+ return (await res.json()) as Doc
+}
+
+async function waitForDoc(page: Page, designId: string, predicate: (d: Doc) => boolean, what: string, timeoutMs = 20_000) {
+ const started = Date.now()
+ let last: Doc | null = null
+ while (Date.now() - started < timeoutMs) {
+ last = await doc(page, designId)
+ if (predicate(last)) return last
+ await page.waitForTimeout(500)
+ }
+ throw new Error(`document never showed ${what} within ${timeoutMs}ms — last: ${JSON.stringify(last?.pages[0]).slice(0, 300)}`)
+}
+
+/** select an element through the Layers tab (Konva is DOM-opaque) */
+async function selectViaLayers(page: Page, label: string) {
+ const layersTab = page.getByRole('button', { name: 'Layers', exact: true })
+ if (!(await layersTab.isVisible().catch(() => false))) {
+ await page.getByRole('button', { name: 'Tools', exact: true }).click()
+ await layersTab.click()
+ }
+ await page.getByText(label, { exact: true }).click()
+}
+
+test.setTimeout(120_000)
+
+test.describe('Unified Canvix AI reproduction (v0.32.2 fix)', () => {
+ test('the coffee-launch suggestion works in Auto mode from an empty canvas', async ({ page }) => {
+ await register(page, 'repro')
+ const designId = await createEmptyDesign(page, 'AI repro canvas')
+ await openEditor(page, designId)
+
+ // ── the agent route: scripted create-run stream + request capture ──
+ let capturedBody: Record<string, unknown> | null = null
+ await page.route('**/api/ai/agent**', async (route: Route) => {
+ const req = route.request()
+ if (req.method() === 'POST' && req.url().includes('bridge=')) {
+ // bridge acks from the panel — the scripted stream ignores them
+ await route.fulfill({ status: 200, contentType: 'application/json', body: '{}' })
+ return
+ }
+ capturedBody = req.postDataJSON() as Record<string, unknown>
+ await route.fulfill({
+ status: 200,
+ headers: { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache' },
+ body: sseScript(),
+ })
+ })
+
+ // ── Canvix AI → Chat (default tab) → 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.getByRole('button', { name: 'Send', exact: true }).click()
+
+ // the ORIGINAL request reached the route, verbatim, UNPINNED (Auto)
+ expect((capturedBody as { message?: string } | null)?.message).toBe(PROMPT)
+ expect((capturedBody as Record<string, unknown> | null)?.mode).toBeUndefined()
+
+ // ── document truth: the streamed writes landed as native elements ──
+ const created = await waitForDoc(
+ page,
+ designId,
+ (d) => (d.pages[0]?.elements ?? []).some((e) => (e as { text?: string }).text === 'ARTISAN ROAST'),
+ 'the AI-created headline',
+ )
+ const texts = created.pages[0].elements.filter((e) => e.type === 'text').map((e) => (e as { text: string }).text)
+ expect(texts).toEqual(expect.arrayContaining([
+ 'ARTISAN ROAST',
+ 'our coffee launch — first sip free',
+ 'order at canvix.coffee',
+ ]))
+ expect(created.pages[0].elements.some((e) => e.type === 'rect')).toBe(true)
+
+ // the chat reports the create run honestly (a normal done, no INCOMPLETE)
+ await expect(page.getByText('Coffee-launch Instagram post created', { exact: false })).toBeVisible({ timeout: 10_000 })
+
+ await page.screenshot({ path: '/home/z/my-project/download/repro-created.png', fullPage: false })
+
+ // ── reopen: the created design survives with its elements ──
+ await openEditor(page, designId)
+ await selectViaLayers(page, 'ARTISAN ROAST')
+
+ // ── edit through the REAL properties UI (font size) ──
+ const sizeInput = page.getByRole('spinbutton', { name: 'Font size' })
+ await expect(sizeInput).toBeVisible()
+ await sizeInput.fill('96')
+ await sizeInput.press('Enter')
+
+ const edited = await waitForDoc(
+ page,
+ designId,
+ (d) => (d.pages[0]?.elements ?? []).some((e) => (e as { text?: string; fontSize?: number }).text === 'ARTISAN ROAST' && (e as { fontSize?: number }).fontSize === 96),
+ 'the edited font size',
+ )
+ // the edit landed on the AI-CREATED element — native editable, proven
+ const headline = edited.pages[0].elements.find((e) => (e as { text?: string }).text === 'ARTISAN ROAST') as { fontSize?: number; locked?: boolean }
+ expect(headline.fontSize).toBe(96)
+ expect(headline.locked).toBeFalsy()
+
+ await page.screenshot({ path: '/home/z/my-project/download/repro-edited.png', fullPage: false })
+ })
+})