Skip to content

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

feat(v0.32.3): plan-first, geometry ground truth, conversation memory (#91)

Ashiq Hussain Mir5a54e830aef2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bc9f6ff..17962f9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,21 @@
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/).
+### Added — v0.32.3: plan-first, geometry ground truth, conversation memory
+
+- **Conversation history reaches the loop:** `LoopDeps.history`
+ (route-sanitized, last 12 turns) enters the model conversation
+ verbatim as `[system, ...history, request]`; compaction keeps the
+ whole head — only the tool-observation middle is folded. Follow-ups
+ like "make another one like the last one" keep their meaning.
+- **CANVAS GEOMETRY ground-truth block** in the system prompt: page
+ bounds, origin, y-down, the computed 6% safe area, exact element
+ boxes (`@(x,y) WxH`), background via `set_background` only.
+- **Plan-first is structural:** a create run's first element write
+ before any `plan_layout` is redirected once (geometry first, then
+ colors/content); planned runs and edit runs are never bounced;
+ never a hard block.
+
## [Unreleased] — Unified Canvix AI hardening + the reproduction fix
> The external-review hardening (v0.32.1) and the production
diff --git a/docs/UNIFIED-AI-MILESTONE.md b/docs/UNIFIED-AI-MILESTONE.md
index a4cbd60..32dce60 100644
--- a/docs/UNIFIED-AI-MILESTONE.md
+++ b/docs/UNIFIED-AI-MILESTONE.md
@@ -318,3 +318,63 @@ validation, undo and autosave all ride the unchanged bridge.
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.
+
+---
+
+# v0.32.3 — plan-first, geometry ground truth, conversation memory
+
+**The ask:** the agent should know the canvas geometry (where it
+starts and ends), know every tool/element on it, plan the layout
+geometrically FIRST, then build, then check what it actually made
+(overlap etc.) before stopping — and it should remember the
+conversation it is in.
+
+The survey found most of the pipeline already existed (per-element
+`@(x,y) WxH` boxes, overlaps/off-canvas detection, the full TOOLS +
+fonts vocabulary, `plan_layout` bands, brief/audit/vision
+verify-then-stop). Three gaps were real and are now closed:
+
+## 1. The conversation history never reached the loop
+
+`history` was wired only into the one-shot discuss/explain answers;
+every create/edit/review run started blind to the chat it arrived
+in. `LoopDeps.history` (route-sanitized: last 12 turns × 800 chars)
+now enters the model conversation verbatim —
+`[system, ...history, request]` — and **compaction keeps the whole
+head** (system + history + request); only the long tool-observation
+middle is ever folded. "Make another one like the last one" keeps
+meaning.
+
+## 2. Geometry was implicit, not stated
+
+A **CANVAS GEOMETRY** ground-truth block now leads the system prompt
+with the numbers computed for the page: bounds, origin, y-down, the
+6% safe area (`x 65..1015` for a 1080px page), how to read the
+element boxes (`@(x,y) WxH` edges are exact), and that the page
+background changes via `set_background`, never full-bleed cover
+rects.
+
+## 3. Plan-first was a prompt request, not a rule
+
+A create/improve run whose first element write arrives before any
+`plan_layout` is now redirected ONCE (`PLAN FIRST — … bands with
+y + height that tile the safe area …`): geometry first, then colors
+and content inside the bands. `set_background` stays exempt (the
+LAYOUT PLANNING guidance pairs it with the plan); a run that already
+planned is never bounced; after one bounce the model may proceed —
+guidance, never a hard block. Edit runs are exempt entirely.
+
+## Verify-then-stop (already structural — unchanged)
+
+Brief contract → quality audit (contrast/overlap/overflow/
+off-canvas, ONE fix round) → grounded vision critique → honest
+`INCOMPLETE` framing for empty create runs. The guards were not
+touched.
+
+## Evidence
+
+1,724/1,724 unit (6 new regressions: history-in-first-call verbatim,
+compaction-keeps-the-head, the geometry block's computed numbers, the
+plan-first bounce + redirect, planned-runs-never-bounced,
+edit-runs-exempt). 14 scripted create-run tests updated to encode
+plan-first (their models now plan before building).
diff --git a/src/app/api/ai/agent/route.ts b/src/app/api/ai/agent/route.ts
index e518f5d..f4261a0 100644
--- a/src/app/api/ai/agent/route.ts
+++ b/src/app/api/ai/agent/route.ts
@@ -375,6 +375,9 @@ async function __canvix_post(req: NextRequest) {
// loop as the actual first user message — the model sees
// what it was asked for, verbatim, all run long
request: message,
+ // v0.32.3: the conversation this request arrives in —
+ // the loop's model sees the prior turns verbatim
+ history,
brief,
skills,
emit,
diff --git a/src/lib/agent/harness.test.ts b/src/lib/agent/harness.test.ts
index fc72645..e814723 100644
--- a/src/lib/agent/harness.test.ts
+++ b/src/lib/agent/harness.test.ts
@@ -274,6 +274,7 @@ describe('harness · tool matrix', () => {
// fill → done (audit clean, accepted)
const { chat } = scriptedChat([
turn('set_background', { kind: 'solid', from: '#090B1A' }),
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] }),
turn('add_text', { text: 'Dark text on dark bg', fontSize: 40, color: '#111122' }),
done('Poster complete'),
turn('add_text', { text: 'Fixed headline', fontSize: 40, color: '#FFFFFF' }),
@@ -306,6 +307,7 @@ describe('harness · tool matrix', () => {
const events: AgentEvent[] = []
const { chat } = scriptedChat([
turn('set_background', { kind: 'solid', from: '#090B1A' }),
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] }),
turn('add_text', { text: 'Still dark', fontSize: 40, color: '#111122' }),
done('Done attempt 1'),
done('Done attempt 2 — unfixable, disclosed'),
@@ -333,6 +335,7 @@ describe('harness · tool matrix', () => {
// the fix round → the run must END AS DONE with disclosure, not error
const { chat } = scriptedChat([
turn('set_background', { kind: 'solid', from: '#090B1A' }),
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] }),
turn('add_text', { text: 'Dark text', fontSize: 40, color: '#111122' }),
done('Poster complete'),
turn('patch_things', { nope: true }),
@@ -359,6 +362,7 @@ describe('harness · tool matrix', () => {
const events: AgentEvent[] = []
const { chat, calls } = scriptedChat([
turn('set_background', { kind: 'solid', from: '#090B1A' }),
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] }),
turn('update_elements', { ids: ['txt-1'], patch: { color: '#FFFFFF' } }),
done('Fixed contrast'),
])
@@ -577,6 +581,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
// FAILS first: gray missing) → fix → done (passes)
const { chat, calls } = scriptedChat([
turn('set_background', { kind: 'solid', from: '#090B1A' }),
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] }),
turn('add_text', { text: 'Design Beyond Limits', fontSize: 110, color: '#FFFFFF', bold: true }),
turn('add_text', { text: 'Create Smarter. Design Faster.', fontSize: 40, color: '#22D3EE' }),
turn('add_text', { text: 'Try Canvix Free', fontSize: 36, color: '#8B5CF6' }),
@@ -613,6 +618,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
const brief = extractBrief('"Design Beyond Limits"')
let validationCalls = 0
const { chat, calls } = scriptedChat([
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] }),
turn('add_text', { text: 'Creative Pulse', fontSize: 96 }),
done('Done'), // rejected 1
done('Done'), // rejected 2
@@ -704,6 +710,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
const replies: string[] = []
// page 1: bg + 2 texts; goto page 2: bg + 2 texts; verify; done
replies.push(turn('set_background', { kind: 'solid', from: '#0D1117' }))
+ replies.push(turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] }))
replies.push(turn('add_text', { text: 'Slide One', fontSize: 90 }))
replies.push(turn('add_text', { text: 'The vision', fontSize: 32 }))
replies.push(turn('add_page'))
@@ -717,7 +724,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
replies.push(turn('animate_elements', { ids: ['txt-1'], kind: 'rise' }))
replies.push(turn('get_page_state'))
replies.push(done('Two slides built with consistent styling.'))
- expect(replies.length).toBe(14) // v0.27's cap was 8
+ expect(replies.length).toBe(15) // v0.27's cap was 8; v0.32.3 adds the plan turn
const { chat, calls } = scriptedChat(replies)
// refreshed page-2 state: two fresh elements (ids the model just made)
const refreshed: AgentDesignCtx = {
@@ -737,16 +744,17 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
awaitApply: async () => ({ ok: true }),
refreshedContext: () => refreshed,
})
- expect(result.toolCalls).toBe(13) // every step applied — no cap hit
- expect(result.steps).toBe(13)
+ expect(result.steps).toBe(14) // 13 tools + the plan turn (v0.32.3)
// page switch flowed through: the model saw page 2's state
- expect(calls[6].some((m) => m.content.includes('UPDATED PAGE STATE'))).toBe(true)
+ // (call 8 = index 7, one later now that the plan turn is call 2)
+ expect(calls[7].some((m) => m.content.includes('UPDATED PAGE STATE'))).toBe(true)
})
/** Case D: geometry repair — off-canvas + overlaps detected and
* fixed with fix_overlaps. */
it('CASE D: geometry repair — fix_overlaps after placement', async () => {
const { chat } = scriptedChat([
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] }),
turn('add_text', { text: 'Big Headline', fontSize: 140, x: 0, y: 0 }),
turn('add_text', { text: 'Sub', fontSize: 40, x: 0, y: 20 }), // overlaps the headline
turn('fix_overlaps'),
@@ -771,6 +779,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
const valid: [string, Record<string, unknown>][] = [
['get_page_state', {}],
['set_background', { kind: 'gradient', from: '#090B1A', to: '#8B5CF6', angle: 160 }],
+ ['plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] }],
['add_text', { text: 'Hello', fontSize: 64, color: '#FFFFFF' }],
['add_shape', { shape: 'rect', x: 10, y: 10, width: 100, height: 80 }],
['add_line', { x: 10, y: 200, length: 300, variant: 'arrow' }],
@@ -835,7 +844,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
// every write tool applied except the declined clear_page; the
// validate_brief pseudo-action applies state without an ack and is
// not counted as a tool call (v0.28.1 live-eval fix)
- expect(result.toolCalls).toBe(valid.length - 2)
+ expect(result.toolCalls).toBe(valid.length - 3) // validate_brief + plan_layout are not counted
expect(declined).toBe(true)
expect(result.summary).toBe('Sweep complete')
})
@@ -876,7 +885,8 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
const result = await runAgentLoop({
chat: async () => {
n += 1
- if (n === 4) signal.aborted = true
+ if (n === 1) return turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] })
+ if (n === 5) signal.aborted = true
return turn('add_sticker', { emoji: '⭐', n }) // distinct args — no cycle guard
},
design,
@@ -948,6 +958,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
it('CASE F7: compaction folds a long conversation and emits a compact event', async () => {
const events: AgentEvent[] = []
const replies: string[] = []
+ replies.push(turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] }))
for (let i = 0; i < 65; i++) replies.push(turn('add_sticker', { emoji: '⭐', n: i }))
replies.push(done('Long run complete'))
const result = await runAgentLoop({
@@ -964,6 +975,7 @@ describe('harness · lifecycle flows (Cases A–F)', () => {
it('usage telemetry streams during long runs', async () => {
const events: AgentEvent[] = []
const replies: string[] = []
+ replies.push(turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] }))
for (let i = 0; i < 40; i++) replies.push(turn('add_sticker', { emoji: '⭐' }))
replies.push(done('done'))
await runAgentLoop({
@@ -1317,6 +1329,7 @@ describe('v0.29.3 · loop: vision critique BEFORE completion', () => {
const captures: string[] = []
const { chat, calls } = scriptedChat([
turn('set_background', { kind: 'solid', from: '#090B1A' }),
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] }),
turn('add_text', { text: 'CANVIX', fontSize: 72, color: '#F8FAFC' }),
done('Poster complete'),
turn('move_elements', { ids: ['txt-1'], dx: 0, dy: 40 }),
@@ -1357,6 +1370,7 @@ describe('v0.29.3 · loop: vision critique BEFORE completion', () => {
const { chat } = scriptedChat([
turn('set_background', { kind: 'solid', from: '#090B1A' }),
done('Poster complete'),
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] }),
turn('update_elements', { ids: ['txt-1'], fill: '#F8FAFC' }),
done('Poster complete — attempted'),
])
@@ -1619,9 +1633,12 @@ describe('v0.32.2 · loop: the original request reaches the model (defect B)', (
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' }),
- )
+ const replies = [
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] }),
+ ...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({
@@ -1657,6 +1674,7 @@ describe('v0.32.2 · loop: the reproduction end-to-end on an empty canvas', () =
const events: AgentEvent[] = []
const { chat, calls } = scriptedChat([
turn('set_background', { kind: 'gradient', from: '#120A2A', to: '#2E1A47' }),
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] }),
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' }),
@@ -1744,6 +1762,7 @@ describe('v0.32.2 · loop: the reproduction end-to-end on an empty canvas', () =
const events: AgentEvent[] = []
const { chat, calls } = scriptedChat([
turn('set_background', { kind: 'solid', from: '#111111' }),
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] }),
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' }),
@@ -1775,3 +1794,152 @@ describe('v0.32.2 · loop: the reproduction end-to-end on an empty canvas', () =
expect(result.verification).toContain('Brief contract validated')
})
})
+
+// ═════════════════════════════════════════════════════════════
+// v0.32.3 · plan-first + conversation memory + geometry ground
+// truth (the user's architecture ask, made structural)
+// ═════════════════════════════════════════════════════════════
+
+describe('v0.32.3 · conversation history reaches the loop', () => {
+ const emptyDesign: AgentDesignCtx = {
+ name: 'Untitled', width: 1080, height: 1920, pageCount: 1,
+ currentPageIndex: 0, elements: [], colorsInUse: [], otherPages: [],
+ }
+
+ it('the first model call carries the prior turns verbatim, before the request', async () => {
+ const events: AgentEvent[] = []
+ const history = [
+ { role: 'user' as const, content: 'Design a bold Instagram post for a coffee launch' },
+ { role: 'assistant' as const, content: 'Coffee-launch Instagram post created: bold headline, offer line and CTA card.' },
+ ]
+ const { chat, calls } = scriptedChat([
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }] }),
+ done('Adjusted per the earlier conversation.'),
+ ])
+ await runAgentLoop({
+ chat, design: emptyDesign, mode: 'edit',
+ request: 'make another one like the last one but for tea',
+ history,
+ emit: (e) => events.push(e),
+ awaitApply: async () => ({ ok: true }),
+ })
+ const first = calls[0]
+ // [system, history…, request] — the conversation arrives verbatim
+ expect(first?.[1]?.role).toBe('user')
+ expect(first?.[1]?.content).toBe('Design a bold Instagram post for a coffee launch')
+ expect(first?.[2]?.role).toBe('assistant')
+ expect(first?.[2]?.content).toContain('bold headline')
+ // and the CURRENT request is still the last pre-loop message
+ expect(first?.[3]?.content).toBe('make another one like the last one but for tea')
+ })
+
+ it('compaction keeps the whole head — history and request survive a long run', async () => {
+ const events: AgentEvent[] = []
+ const history = [
+ { role: 'user' as const, content: 'first request in this conversation' },
+ { role: 'assistant' as const, content: 'first answer in this conversation' },
+ ]
+ const replies = [
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }] }),
+ ...Array.from({ length: 70 }, (_, i) =>
+ turn('add_text', { text: `line ${i}`, y: 40 + i * 20, fontSize: 24, color: '#FFFFFF' })),
+ done('Long build complete'),
+ ]
+ const { chat, calls } = scriptedChat(replies)
+ await runAgentLoop({
+ chat, design: emptyDesign, mode: 'create',
+ request: 'build the long thing', history,
+ emit: (e) => events.push(e),
+ awaitApply: async () => ({ ok: true }),
+ })
+ expect(events.some((e) => e.type === 'compact')).toBe(true)
+ const last = calls[calls.length - 1]
+ // the head is never compacted away: history + request stay verbatim
+ const contents = last?.map((m) => m.content)
+ expect(contents).toContain('first request in this conversation')
+ expect(contents).toContain('build the long thing')
+ })
+})
+
+describe('v0.32.3 · geometry ground truth in the system prompt', () => {
+ it('states the page bounds, the safe area numbers and how to read element boxes', () => {
+ const prompt = loopSystemPrompt({ design, ctx: { validIds: new Set(['el-1']), width: 1080, height: 1080, fonts: new Set(['Inter']) }, mode: 'create' })
+ expect(prompt).toContain('CANVAS GEOMETRY')
+ expect(prompt).toContain('1080x1080px')
+ expect(prompt).toContain('origin (0,0) at the TOP-LEFT')
+ expect(prompt).toContain('Safe area (6% margins): x 65..1015, y 65..1015')
+ expect(prompt).toContain('@(x,y) WxH')
+ expect(prompt).toContain('set_background, never with full-bleed cover rects')
+ })
+})
+
+describe('v0.32.3 · plan-first gate (create runs)', () => {
+ const emptyDesign: AgentDesignCtx = {
+ name: 'Untitled', width: 1080, height: 1920, pageCount: 1,
+ currentPageIndex: 0, elements: [], colorsInUse: [], otherPages: [],
+ }
+
+ it('a create run that writes before planning is redirected ONCE, then proceeds', async () => {
+ const events: AgentEvent[] = []
+ // model: tries to build immediately → PLAN FIRST bounce → plans → builds → done
+ const { chat, calls } = scriptedChat([
+ turn('add_text', { text: 'Too eager', fontSize: 64, y: 100 }),
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }, { name: 'body', y: 300, height: 300, contains: 'Body' }] }),
+ turn('set_background', { kind: 'solid', from: '#090B1A' }),
+ turn('add_text', { text: 'Planned headline', fontSize: 96, y: 80, color: '#FFFFFF' }),
+ done('Planned first, then built.'),
+ ])
+ const result = await runAgentLoop({
+ chat, design: emptyDesign, mode: 'create',
+ request: 'Design a bold Instagram post for a coffee launch',
+ emit: (e) => events.push(e),
+ awaitApply: async () => ({ ok: true }),
+ })
+ // the premature write was redirected with the plan-first guidance
+ const bounced = calls.some((c) => c.some((m) => m.role === 'user' && m.content.startsWith('PLAN FIRST —')))
+ expect(bounced).toBe(true)
+ // the too-eager text was NOT applied — only the post-plan work counts
+ const actionJson = JSON.stringify(events.filter((e) => e.type === 'action'))
+ expect(actionJson).not.toContain('Too eager')
+ expect(actionJson).toContain('Planned headline')
+ // and the run completes normally (one bounce, never a block)
+ expect(result.summary).not.toContain('INCOMPLETE')
+ })
+
+ it('a run that plans first never sees the bounce', async () => {
+ const events: AgentEvent[] = []
+ const { chat, calls } = scriptedChat([
+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 60, height: 200, contains: 'Hero' }] }),
+ turn('add_text', { text: 'Planned from the start', fontSize: 72, y: 80 }),
+ done('Done.'),
+ ])
+ await runAgentLoop({
+ chat, design: emptyDesign, mode: 'create',
+ request: 'Design a poster',
+ emit: (e) => events.push(e),
+ awaitApply: async () => ({ ok: true }),
+ })
+ expect(calls.some((c) => c.some((m) => m.role === 'user' && m.content.startsWith('PLAN FIRST —')))).toBe(false)
+ })
+
+ it('edit runs are exempt — surgical edits never require a plan', async () => {
+ const events: AgentEvent[] = []
+ const editDesign: AgentDesignCtx = {
+ ...emptyDesign,
+ elements: [{ id: 'txt-1', type: 'text', x: 100, y: 100, width: 400, height: 80, text: 'Headline', fontSize: 64, fill: '#111111' }],
+ }
+ const { chat, calls } = scriptedChat([
+ turn('update_elements', { ids: ['txt-1'], patch: { fontSize: 96 } }),
+ done('Bigger headline.'),
+ ])
+ const result = await runAgentLoop({
+ chat, design: editDesign, mode: 'edit',
+ request: 'Make the existing title bigger',
+ emit: (e) => events.push(e),
+ awaitApply: async () => ({ ok: true }),
+ })
+ expect(calls.some((c) => c.some((m) => m.role === 'user' && m.content.startsWith('PLAN FIRST —')))).toBe(false)
+ expect(result.toolCalls).toBe(1)
+ expect(result.summary).not.toContain('INCOMPLETE')
+ })
+})
diff --git a/src/lib/agent/loop.ts b/src/lib/agent/loop.ts
index 734f34c..7454c1a 100644
--- a/src/lib/agent/loop.ts
+++ b/src/lib/agent/loop.ts
@@ -52,6 +52,13 @@ export interface LoopDeps {
* the model of the actual creative brief: it kept inspecting the
* canvas, claimed no brief was given and created nothing). */
request: string
+ /** v0.32.3: the CONVERSATION this request arrives in — prior user
+ * and assistant turns (already trimmed/validated by the route).
+ * Inserted before the request so the model knows what it already
+ * did in this chat ("make another one like the last one" keeps
+ * meaning). Compaction never drops this head, only the long
+ * tool-observation middle. */
+ history?: { role: 'user' | 'assistant'; content: string }[]
/** the run's brief contract (extracted by the route) */
brief?: DesignBrief | null
/** v0.29: local quality audit of the latest design snapshot
@@ -118,12 +125,24 @@ export function loopSystemPrompt(deps: {
skills?: DesignSkill[]
}): string {
const { design, ctx, mode, brief, skills } = deps
+ const W = design.width ?? 1080
+ const H = design.height ?? 1080
+ const margin = 0.06
const lines: string[] = [
'You are the Canvix design agent — an autonomous design assistant working inside a graphic editor.',
'You see the CURRENT design state below. You act ONLY through tools, one per turn.',
'',
MODE_PROMPTS[mode],
'',
+ // v0.32.3: the geometry ground truth, stated up front with the
+ // numbers computed for THIS page — where the canvas starts and
+ // ends, where elements may live, how the listed boxes read.
+ `CANVAS GEOMETRY (ground truth for every placement):`,
+ `· Page bounds: ${W}x${H}px, origin (0,0) at the TOP-LEFT, y grows DOWNWARD. Nothing may sit outside 0..${W} x 0..${H}.`,
+ `· Safe area (6% margins): x ${Math.round(W * margin)}..${Math.round(W * (1 - margin))}, y ${Math.round(H * margin)}..${Math.round(H * (1 - margin))}.`,
+ `· Every element below is listed with its exact box @(x,y) WxH — those edges are where it starts and ends; compute band/gap math from them, not from guesses.`,
+ `· The page background line in the state below is real; change it with set_background, never with full-bleed cover rects.`,
+ '',
'Reply with ONE JSON object per turn, nothing else:',
'{"thought": "one short sentence of reasoning", "tool": "tool_name", "args": { ... }}',
'or when finished:',
@@ -192,17 +211,22 @@ function callHash(tool: string, args: unknown): string {
}
}
-/** Compact the message list: keep system + the first user message +
- * the last turns, summarize the middle into one assistant note. */
-function compactMessages(messages: { role: 'system' | 'user' | 'assistant'; content: string }[]): { compacted: typeof messages; from: number } {
+/** Compact the message list: keep the head (system + conversation
+ * history + the request — everything up to requestIndex inclusive)
+ * and the last turns, summarize the tool-observation middle into
+ * one assistant note. The user's original request and the chat's
+ * prior turns are NEVER folded away. */
+function compactMessages(
+ messages: { role: 'system' | 'user' | 'assistant'; content: string }[],
+ requestIndex: number,
+): { compacted: typeof messages; from: number } {
if (messages.length <= 12) return { compacted: messages, from: messages.length }
- const system = messages.slice(0, 1)
- const firstUser = messages.slice(1, 2)
+ const head = messages.slice(0, requestIndex + 1)
const tail = messages.slice(-8)
- const middle = Math.max(0, messages.length - 1 - 1 - 8)
+ const middle = Math.max(0, messages.length - head.length - 8)
const summary = `[context compacted — ${middle} earlier turns summarized] Earlier in this run you completed several steps. Key outcomes persist in the CURRENT DESIGN STATE inside the system context; element ids from before a get_page_state refresh may be stale — call get_page_state if unsure. Continue the task; do not redo completed work.`
return {
- compacted: [...system, ...firstUser, { role: 'assistant', content: summary }, ...tail],
+ compacted: [...head, { role: 'assistant', content: summary }, ...tail],
from: messages.length,
}
}
@@ -254,6 +278,13 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
let designChanges = 0
/** done turns rejected because the run changed nothing yet */
let emptyDoneRejections = 0
+ /** v0.32.3: plan-first gate fired? (create/improve runs whose first
+ * action is a WRITE before any plan_layout get ONE redirect —
+ * guidance, never a hard block) */
+ let planBounced = false
+ /** v0.32.3: has plan_layout run in this run? Once it has, writes
+ * proceed freely — the gate never fires again. */
+ let planHasRun = false
const toolCtx: ToolContext = {
validIds: contextValidIds(design),
@@ -264,13 +295,21 @@ 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 }) },
+ // v0.32.3: the conversation this request arrives in — prior
+ // user/assistant turns, verbatim (route-sanitized). The model
+ // knows what it already did in this chat.
+ ...(deps.history ?? []),
// 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.
+ // user message right after the history. compactMessages keeps the
+ // whole head (system + history + request), 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 },
]
+ /** index of the request message — the head (system + history +
+ * request) is never compacted away */
+ const requestIndex = messages.length - 1
emit({ v: AGENT_PROTOCOL_VERSION, type: 'mode', mode, reason: `classified as ${mode}` })
for (const s of skills) emit({ v: AGENT_PROTOCOL_VERSION, type: 'skill', id: s.id, name: s.name })
@@ -335,7 +374,7 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
// ── compaction (memory + provider context protection) ───
if (messages.length > AGENT_GUARDS.maxMessages) {
- const { compacted, from } = compactMessages(messages)
+ const { compacted, from } = compactMessages(messages, requestIndex)
const to = compacted.length
messages.length = 0
messages.push(...compacted)
@@ -561,6 +600,26 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
})
continue
}
+ // v0.32.3 PLAN-FIRST: a create/improve run whose first action is
+ // a WRITE (before any plan_layout) is redirected ONCE — geometry
+ // first, then build. Reads are always fine; a run that already
+ // planned is never bounced; after one bounce the model may
+ // proceed (never a hard block, the guards still hold).
+ if (
+ !planBounced &&
+ !planHasRun &&
+ (mode === 'create' || mode === 'improve') &&
+ (tool.risk === 'write' || tool.risk === 'destructive') &&
+ toolName !== 'set_background'
+ ) {
+ planBounced = true
+ messages.push({
+ role: 'user',
+ content:
+ 'PLAN FIRST — before adding elements, call plan_layout with your composition: page background, one vertical band per section (headline, subline, cards, CTA, footer) with y + height that tile the safe area with \u226540px gaps. Place geometry first, then colors and content inside those bands. (set_background may run before the plan; every other write waits for it.) This reminder fires once — after planning, build freely.',
+ })
+ continue
+ }
emit({ v: AGENT_PROTOCOL_VERSION, type: 'step', index: steps, thought, tool: toolName })
const args = (turn.args && typeof turn.args === 'object' && !Array.isArray(turn.args) ? turn.args : {}) as Record<string, unknown>
@@ -570,6 +629,7 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
// plan is streamed to the user (the 'plan' event) and echoed as
// an observation. No apply/ack round trip: a plan changes nothing.
if (toolName === 'plan_layout' && result.ok) {
+ planHasRun = true
const planLines = (result.actions as { type: string; lines?: string[] }[])
.flatMap((a) => (a && a.type === '__planLayout' && Array.isArray(a.lines) ? a.lines : []))
const lines = planLines.length ? planLines : ['(model emitted an empty plan)']