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.5): the P0 plan-validator regression — server-computed geometry, no strikes for recoverable plans, honest failure UI (#93)

Ashiq Hussain Mirdc80be8e612e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3c2fac9..89ad12d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,33 @@
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/).
+### Fixed — v0.32.5: the P0 plan-validator regression (server-computed geometry)
+
+- **The failure:** a valid creative brief ("Design a bold Instagram
+ post for a coffee launch") died at three rejected plan_layout
+ calls with ZERO elements — every rejection cost a strike, and the
+ model was asked to redo the gap arithmetic it could not do.
+- **The server computes geometry now** (`plan-repair.ts`, pure):
+ valid plans accepted unchanged; repairable plans AUTO-REPAIRED
+ (heights, order, contents kept; positions/gaps computed
+ deterministically and disclosed); infeasible plans rejected with
+ the exact math (never fabricated). The model never re-attempts
+ arithmetic.
+- **Plan rejections are no longer strikes** — a separate bounded
+ budget (3 consecutive) stops honestly with the infeasibility math.
+ Genuine failures (invalid JSON, unknown tools, other tool errors)
+ still strike; destructive confirmation and all resource guards
+ unchanged.
+- **Zero-action runs skip visual critique** — both the loop's
+ done-time vision round and the client's Phase-7 pass (a dead run
+ used to critique the EMPTY canvas).
+- **A failure is never a green check** (`outcome.ts`): disclosed
+ failures render with an amber alert; create/improve turns that
+ applied nothing say so explicitly.
+- **Agent telemetry:** `[agent:telemetry]` JSON lines for plan
+ rejections/repairs and guard-exit outcomes (geometry and outcomes
+ only — no credentials).
+
### Added — v0.32.4: deterministic design correctness
- **Hard plan validation:** plan_layout REJECTS invalid geometry
diff --git a/ROADMAP.md b/ROADMAP.md
index b2262a2..7361666 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -1,4 +1,5 @@
- 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.
# Canvix Roadmap — where we are, what's next
> **Status date:** 2026-11-25 · **Changelog state:** v0.31.0 · `package.json` 0.31.0 · **latest published GitHub release:** v0.31.0 · **Test posture:** 1,693 unit tests across 127 test files (verified full run, 25 Nov, the v0.31.0 release run) · 39 e2e spec files + the plugins & stock-video gated suites · CI gates every PR (`lint-unit` incl. production build + `e2e` running all three suites) · `npm audit` **0 vulnerabilities**.
diff --git a/docs/UNIFIED-AI-MILESTONE.md b/docs/UNIFIED-AI-MILESTONE.md
index 1fd4738..d036a08 100644
--- a/docs/UNIFIED-AI-MILESTONE.md
+++ b/docs/UNIFIED-AI-MILESTONE.md
@@ -473,3 +473,91 @@ margin advisory with shallow-bleed tolerance, empty-section
adherence, wrap-up residue disclosure, list_fonts search/cap/no-
match, ledger rendering + absence, hard validator boundaries incl.
the 39/40px edge and beyond-page rejection). Live re-test below.
+
+---
+
+# v0.32.5 — the P0 regression fix: the server computes geometry
+
+**The production failure (reported against `4d5fa3a`):** "Design a
+bold Instagram post for a coffee launch" on an empty canvas →
+CREATE classified correctly → three `plan_layout` calls → all three
+rejected for <40px gaps → "Stopped after 3 consecutive invalid tool
+calls" → **0 elements**. Retrying with "Create by yourself" failed
+the same way, and the client then critiqued the EMPTY canvas
+("The vision model returned no parseable critique").
+
+**Root cause — confirmed in source, not just reported:**
+
+1. `loop.ts`: every rejected sanitize (including plan geometry)
+ executed `strikes += 1` — three repairable geometry mistakes were
+ fatal. The v0.32.4 milestone report described rejections as
+ "retryable, not strikes"; the merged code contradicted the
+ report. The report was wrong about the merged behavior.
+2. `AssistantApp.tsx`: Phase-7 visual critique ran for ANY
+ create/improve turn with a summary — including zero-action
+ failures — so a dead run critiqued a blank canvas.
+3. The failure turn rendered next to an unconditional emerald
+ verification check.
+
+## The fix: stop asking the model to do arithmetic
+
+**`src/lib/agent/plan-repair.ts` (new, pure):** a deterministic
+layout solver. Given the page height, the 6% margins and the
+requested sections it computes valid positions and gaps:
+
+- **valid plan** → accepted unchanged (zero repairs);
+- **repairable** (heights fit; positions/gaps don't) →
+ **AUTO-REPAIRED**: heights, order and contents kept, y-positions
+ and gaps computed server-side, the repair DISCLOSED in the
+ observation ("your heights, order and contents were kept; the
+ SERVER computed valid positions … Build inside these exact bands —
+ do not recompute them");
+- **infeasible** (content taller than the safe area) → rejected with
+ the exact math ("1200px of content, safe area 950px … smallest
+ fitting layout needs ≤316px per section") — never a fabricated
+ plan.
+
+**Loop:** `plan_layout` rejections are no longer strikes. They count
+against a separate bounded budget (`AGENT_GUARDS.planRejections`,
+3 CONSECUTIVE — a recorded plan resets it); exceeding it stops
+honestly with the infeasibility math. Invalid JSON, unknown tools and
+other tool errors still strike exactly as before; destructive
+confirmation, cycle and idle guards untouched.
+
+**Vision gates:** the loop's done-time vision round AND the client's
+Phase-7 critique both skip when the run applied nothing — there is
+nothing to verify visually on an unchanged canvas.
+
+**Honest outcome UI (`src/lib/agent/outcome.ts`, new):** `turnOutcome()`
+classifies a finished turn (failure markers; create/improve turns
+that applied nothing). A failure renders with an amber
+ShieldAlert and, when there is no verification string, an explicit
+"Run did not produce any design changes." — never the emerald check.
+
+**Telemetry:** `[agent:telemetry]` JSON lines log the plan lifecycle
+(rejected attempt + constraint, recorded/repaired outcome), and
+guard exits log their reason, steps, tool calls and design changes —
+geometry and outcomes only, never credentials.
+
+## Test evidence
+
+Unit **1,740/1,740** (+7): the exact production failure (three
+bad-geometry plans in a row → all auto-repaired → the build
+proceeds — OLD code dies at 3 strikes with 0 elements); three
+consecutive INFEASIBLE plans stop honestly bounded; a repaired plan
+flows into real element creation with repaired bands reaching the
+audit; 39px gap repaired / 40px accepted unchanged; five sections on
+1080×1080 via calculated spacing; 1080×1350 and 1080×1920; infeasible
+on both; honest outcome classification. E2E +2: a failed zero-action
+create run never calls the vision route and shows the amber failure
+status; the coffee prompt then "Create by yourself" as a follow-up
+in the same conversation reaches the route verbatim with history,
+and its edit lands on the AI-created headline.
+
+## Disclosed limitation
+
+The plan solver covers the vertical band layout the planner speaks
+today (page height, margins, per-section y/h). It does not yet solve
+horizontal multi-column placement inside a band — the model still
+places cards within a band (guarded by the audit's overlap and
+duplicate checks).
diff --git a/src/components/editor/apps/AssistantApp.tsx b/src/components/editor/apps/AssistantApp.tsx
index 38ea4cb..6380da6 100644
--- a/src/components/editor/apps/AssistantApp.tsx
+++ b/src/components/editor/apps/AssistantApp.tsx
@@ -25,6 +25,7 @@
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 { turnOutcome } from '@/lib/agent/outcome'
import type { AnyElement, TextElement } from '@/lib/types'
import { useEditorStore } from '@/store/editor-store'
import { AppHeader, type AppPanelProps } from './registry'
@@ -567,9 +568,15 @@ export function AssistantApp({ onClose }: AppPanelProps) {
}
}
- // Phase 7: after create/improve runs, one visual critique pass
+ // Phase 7: after create/improve runs, one visual critique pass.
+ // v0.32.5: only when the run actually APPLIED changes — the P0
+ // run died at three infeasible plans with zero elements and the
+ // client still critiqued the EMPTY canvas ("vision model
+ // returned no parseable critique"). A zero-action run has
+ // nothing to verify visually; the honest status is "nothing
+ // was created", not a critique of a blank page.
let critiqueNote: string | undefined
- if ((mode === 'create' || mode === 'improve') && summary && !controller.signal.aborted) {
+ if ((mode === 'create' || mode === 'improve') && summary && appliedCount > 0 && !controller.signal.aborted) {
const critique = await visionCritique(runBrief ?? briefRef.current)
if (critique) {
critiqueNote = critique.note
@@ -764,12 +771,32 @@ export function AssistantApp({ onClose }: AppPanelProps) {
</div>
)}
<div className="text-[12.5px] text-white/85 leading-relaxed whitespace-pre-wrap">{turn.content}</div>
- {turn.verification && (
- <div className="flex items-start gap-1.5 text-[11px] text-emerald-300/80">
- <CheckCircle2 size={12} className="mt-0.5 shrink-0" />
- <span>{turn.verification}</span>
- </div>
- )}
+ {/* v0.32.5: honest outcome tone — the P0 run's failures
+ rendered with the same emerald check as successes. A
+ disclosed failure gets the amber alert; only a clean
+ verification keeps the green check. */}
+ {(() => {
+ const outcome = turnOutcome({ mode: turn.mode, verification: turn.verification, content: turn.content, appliedActions: turn.appliedActions })
+ if (!turn.verification && outcome !== 'failure') return null
+ if (outcome === 'failure') {
+ const status = turn.verification
+ ?? (turn.mode === 'create' || turn.mode === 'improve'
+ ? 'Run did not produce any design changes.'
+ : 'Run stopped without a verified outcome.')
+ return (
+ <div className="flex items-start gap-1.5 text-[11px] text-amber-300/90">
+ <ShieldAlert size={12} className="mt-0.5 shrink-0" />
+ <span>{status}</span>
+ </div>
+ )
+ }
+ return (
+ <div className="flex items-start gap-1.5 text-[11px] text-emerald-300/80">
+ <CheckCircle2 size={12} className="mt-0.5 shrink-0" />
+ <span>{turn.verification}</span>
+ </div>
+ )
+ })()}
{turn.usage && (
<div className="flex items-center gap-2 text-[10px] text-white/35">
<Gauge size={10} />
diff --git a/src/lib/agent/harness.test.ts b/src/lib/agent/harness.test.ts
index 3ebca10..d712c7f 100644
--- a/src/lib/agent/harness.test.ts
+++ b/src/lib/agent/harness.test.ts
@@ -1452,10 +1452,13 @@ describe('v0.29.3 · loop: planning + fail-closed acks', () => {
expect(result.steps).toBe(2) // plan_layout + set_background each count as a step
})
- it('plan_layout rejects stacked bands with actionable guidance (v0.32.4: hard reject, not a warning)', () => {
+ it('plan_layout AUTO-REPAIRS invalid geometry server-side (v0.32.5: the model never re-does gap arithmetic)', () => {
const tool = AGENT_TOOL_MAP.get('plan_layout')
expect(tool).toBeTruthy()
- const res = tool!.sanitize(
+ // safe area on the 1080px harness canvas: y 65..1015 (950px usable)
+ // a stacked plan (gap −50) is REPAIRED, not rejected: order,
+ // heights and contents kept; the server computes valid positions.
+ const stacked = tool!.sanitize(
{
sections: [
{ name: 'a', y: 100, height: 200, contains: 'x' },
@@ -1464,12 +1467,21 @@ describe('v0.29.3 · loop: planning + fail-closed acks', () => {
},
ctx,
)
- // the 24px overlap slack is gone: gap = 250 - 300 = -50 → REJECTED
- expect(res.ok).toBe(false)
- expect(String((res as { error?: string }).error)).toContain('≥40px gap')
- expect(String((res as { error?: string }).error)).toContain('"a" and "b"')
- // 39px gap: still rejected — the boundary is 40, sharp on both sides
- const res39 = tool!.sanitize(
+ expect(stacked.ok).toBe(true)
+ const stackedObs = String((stacked as { observation?: string }).observation)
+ expect(stackedObs).toContain('AUTO-REPAIRED')
+ expect(stackedObs).toContain('do not recompute')
+ const stackedBands = (stacked as { actions?: { bands?: { name: string; y: number; h: number }[] }[] }).actions?.[0]?.bands
+ expect(stackedBands?.map((b) => b.name)).toEqual(['a', 'b'])
+ expect(stackedBands?.[0]).toEqual({ name: 'a', y: 65, h: 200 })
+ if (stackedBands) {
+ expect(stackedBands[1].y - (stackedBands[0].y + stackedBands[0].h)).toBeGreaterThanOrEqual(40)
+ }
+ expect(stackedBands?.[1].h).toBe(200)
+ expect(stackedBands![1].y + stackedBands![1].h).toBeLessThanOrEqual(1015)
+
+ // 39px gap: REPAIRED to ≥40 — the model never re-attempts the plan
+ const gap39 = tool!.sanitize(
{
sections: [
{ name: 'a', y: 100, height: 200, contains: 'x' },
@@ -1478,36 +1490,53 @@ describe('v0.29.3 · loop: planning + fail-closed acks', () => {
},
ctx,
)
- expect(res39.ok).toBe(false)
- // 40px gap: accepted
- const res40 = tool!.sanitize(
+ expect(gap39.ok).toBe(true)
+ const g39 = (gap39 as { actions?: { bands?: { name: string; y: number; h: number }[] }[] }).actions?.[0]?.bands
+ expect(g39?.map((b) => b.name)).toEqual(['a', 'b'])
+ expect(g39?.[0].h).toBe(200)
+ expect(g39?.[1].h).toBe(100)
+ expect(g39![1].y - (g39![0].y + g39![0].h)).toBeGreaterThanOrEqual(40)
+
+ // a VALID plan (from the safe-area top, exact 40px gaps): accepted
+ // UNCHANGED — no repair note, the model's own geometry stands.
+ const valid = tool!.sanitize(
{
sections: [
- { name: 'a', y: 100, height: 200, contains: 'x' },
- { name: 'b', y: 340, height: 100, contains: 'y' },
+ { name: 'a', y: 65, height: 200, contains: 'x' },
+ { name: 'b', y: 305, height: 100, contains: 'y' },
],
},
ctx,
)
- expect(res40.ok).toBe(true)
- // a band beyond the page: rejected with the exact numbers
- const resBeyond = tool!.sanitize(
+ expect(valid.ok).toBe(true)
+ const validObs = String((valid as { observation?: string }).observation)
+ expect(validObs).toContain('Bands verified')
+ expect(validObs).not.toContain('AUTO-REPAIRED')
+ const validBands = (valid as { actions?: { bands?: { name: string; y: number; h: number }[] }[] }).actions?.[0]?.bands
+ expect(validBands).toEqual([
+ { name: 'a', y: 65, h: 200 },
+ { name: 'b', y: 305, h: 100 },
+ ])
+
+ // truly INFEASIBLE (1200px of content > 950px usable): rejected
+ // with the exact math — never a fabricated plan. No strikes: the
+ // loop's separate plan budget handles it (pinned below).
+ const infeasible = tool!.sanitize(
{
sections: [
- { name: 'a', y: 100, height: 200, contains: 'x' },
- { name: 'b', y: 340, height: 2000, contains: 'y' },
+ { name: 'a', y: 65, height: 400, contains: 'x' },
+ { name: 'b', y: 505, height: 400, contains: 'y' },
+ { name: 'c', y: 945, height: 400, contains: 'z' },
],
},
ctx,
)
- expect(resBeyond.ok).toBe(false)
- expect(String((resBeyond as { error?: string }).error)).toContain('beyond the')
- // the structured bands ride the action for the plan-adherence audit
- const actions = (res40 as { actions?: { bands?: { name: string; y: number; h: number }[] }[] }).actions
- expect(actions?.[0]?.bands).toEqual([
- { name: 'a', y: 100, h: 200 },
- { name: 'b', y: 340, h: 100 },
- ])
+ expect(infeasible.ok).toBe(false)
+ const err = String((infeasible as { error?: string }).error)
+ expect(err).toContain('Infeasible plan')
+ expect(err).toContain('1200px')
+ expect(err).toContain('950px')
+ expect(err).toContain('Reduce the section heights')
})
it('a failed (timed-out) apply ack tells the model the action was NOT applied — fail closed', async () => {
@@ -2165,3 +2194,208 @@ describe('v0.32.4 · run ledger renders into the system prompt', () => {
expect(without).toContain('list_fonts')
})
})
+
+// ═════════════════════════════════════════════════════════════
+// v0.32.5 · THE P0 REGRESSION — a valid creative request must not
+// die at three repairable layout calculations with ZERO elements.
+// The production failure: "Design a bold Instagram post for a
+// coffee launch" → three plan_layout rejections (<40px gaps) →
+// "Stopped after 3 consecutive invalid tool calls" → 0 elements →
+// vision critique of the EMPTY canvas.
+// ═════════════════════════════════════════════════════════════
+
+describe('v0.32.5 · the P0 regression — recoverable geometry must not kill a creative run', () => {
+ const emptyDesign: AgentDesignCtx = {
+ name: 'Untitled', width: 1080, height: 1080, pageCount: 1,
+ currentPageIndex: 0, elements: [], colorsInUse: [], otherPages: [],
+ }
+ // the model's bad arithmetic from the production run: sections
+ // with <40px gaps (auto-repaired now) — sent THREE times in a row
+ const badGeometryPlan = (y2: number) => ({
+ background: '#090B1A',
+ sections: [
+ { name: 'headline', y: 60, height: 200, contains: 'COFFEE' },
+ { name: 'subline', y: y2, height: 120, contains: 'the launch' },
+ { name: 'cta', y: 900, height: 100, contains: 'Shop Now' },
+ ],
+ })
+
+ it('three bad-geometry plans in a row are AUTO-REPAIRED — the run proceeds to real elements (the exact production failure)', async () => {
+ const events: AgentEvent[] = []
+ const { chat, calls } = scriptedChat([
+ turn('plan_layout', badGeometryPlan(220)), // gap -40 → OLD: strike 1
+ turn('plan_layout', badGeometryPlan(240)), // gap 0 → OLD: strike 2
+ turn('plan_layout', badGeometryPlan(259)), // gap 39 → OLD: strike 3 → DEAD
+ turn('set_background', { kind: 'solid', from: '#090B1A' }),
+ turn('add_text', { text: 'COFFEE LAUNCH', fontSize: 64, color: '#FFFFFF', y: 65, x: 100 }),
+ done('Coffee launch post 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 }),
+ })
+ // OLD code: "Stopped after 3 consecutive invalid tool calls", 0 elements.
+ // NEW: every bad plan was repaired server-side; the build happened.
+ expect(result.summary).toContain('Coffee launch post built')
+ expect(result.steps).toBe(5) // 3 plans + set_background + add_text (done is not a step)
+ expect(result.toolCalls).toBe(2) // set_background + add_text applied
+ const planEvents = events.filter((e) => e.type === 'plan')
+ expect(planEvents.length).toBe(3)
+ // the model was never told to redo arithmetic — the server did it
+ expect(calls.some((c) => c.some((m) => m.content.includes('AUTO-REPAIRED')))).toBe(true)
+ })
+
+ it('three INFEASIBLE plans stop honestly with the exact math — bounded, never an infinite retry', async () => {
+ const events: AgentEvent[] = []
+ const infeasible = () => ({
+ sections: [
+ { name: 'a', y: 65, height: 400, contains: 'x' },
+ { name: 'b', y: 505, height: 400, contains: 'y' },
+ { name: 'c', y: 945, height: 400, contains: 'z' },
+ ],
+ })
+ const { chat } = scriptedChat([
+ turn('plan_layout', infeasible()),
+ turn('plan_layout', infeasible()),
+ turn('plan_layout', infeasible()),
+ // if the guard failed to fire, this would apply and the run
+ // would continue — the assertion below pins that it cannot
+ turn('set_background', { kind: 'solid', from: '#090B1A' }),
+ done('Should not get here'),
+ ])
+ const result = await runAgentLoop({
+ chat, design: emptyDesign, mode: 'create',
+ request: 'Design a poster',
+ emit: (e) => events.push(e),
+ awaitApply: async () => ({ ok: true }),
+ })
+ expect(result.summary).toContain('infeasible plans')
+ expect(result.summary).toContain('INCOMPLETE') // guardExit honesty: zero changes
+ expect(result.toolCalls).toBe(0) // nothing applied after the honest stop
+ const last = events[events.length - 1]
+ expect(last.type).toBe('done')
+ })
+
+ it('a repaired plan flows straight into real editable element creation', async () => {
+ const events: AgentEvent[] = []
+ let planBandsSeen: { name: string; y: number; h: number }[] | undefined
+ const { chat } = scriptedChat([
+ turn('plan_layout', badGeometryPlan(220)), // −40px gap → repaired
+ turn('set_background', { kind: 'solid', from: '#090B1A' }),
+ turn('add_text', { text: 'COFFEE', fontSize: 64, color: '#FFFFFF', y: 70, x: 100 }),
+ done('Built.'),
+ ])
+ const result = await runAgentLoop({
+ chat, design: emptyDesign, mode: 'create',
+ request: 'Design a coffee poster',
+ emit: (e) => events.push(e),
+ awaitApply: async () => ({ ok: true }),
+ auditDesign: (bands) => {
+ planBandsSeen = bands
+ return []
+ },
+ })
+ expect(result.summary).toContain('Built')
+ // the plan event carried the REPAIRED geometry (bands start at the
+ // safe-area top y=65, not the model's requested y=60)
+ const plan = events.find((e) => e.type === 'plan') as { steps?: string[] } | undefined
+ expect(plan?.steps?.join('\n')).toContain('y=65')
+ // the audit received the repaired bands (plan-adherence wiring)
+ expect(planBandsSeen?.length).toBe(3)
+ })
+})
+
+describe('v0.32.5 · deterministic plan solver (plan-repair.ts)', () => {
+ it('five sections fit a 1080×1080 canvas with calculated spacing', async () => {
+ const { repairPlanBands } = await import('./plan-repair')
+ const r = repairPlanBands(
+ [
+ { name: 'headline', y: 60, h: 150 },
+ { name: 'subline', y: 300, h: 80 },
+ { name: 'cards', y: 500, h: 300 },
+ { name: 'cta', y: 900, h: 100 },
+ { name: 'footer', y: 950, h: 60 },
+ ],
+ 1080,
+ )
+ expect(r.ok).toBe(true)
+ if (!r.ok) return
+ expect(r.bands).toHaveLength(5)
+ expect(r.bands[0].y).toBe(65) // safe-area top
+ for (let i = 1; i < r.bands.length; i++) {
+ expect(r.bands[i].y - (r.bands[i - 1].y + r.bands[i - 1].h)).toBeGreaterThanOrEqual(40)
+ }
+ const last = r.bands[4]
+ expect(last.y + last.h).toBeLessThanOrEqual(1015)
+ expect(r.repairs.length).toBeGreaterThan(0)
+ })
+
+ it('1080×1350 and 1080×1920 canvases lay out correctly', async () => {
+ const { repairPlanBands } = await import('./plan-repair')
+ // 1350: safe 81..1269 (1188 usable)
+ const a = repairPlanBands([
+ { name: 'h', y: 100, h: 200 },
+ { name: 'c', y: 320, h: 400 },
+ { name: 'f', y: 900, h: 100 },
+ ], 1350)
+ expect(a.ok).toBe(true)
+ if (a.ok) {
+ expect(a.bands[0].y).toBe(81)
+ expect(a.bands[2].y + a.bands[2].h).toBeLessThanOrEqual(1269)
+ expect(a.bands[1].y - (a.bands[0].y + a.bands[0].h)).toBeGreaterThanOrEqual(40)
+ }
+ // 1920: safe 115..1805 (1690 usable)
+ const b = repairPlanBands([
+ { name: 'h', y: 100, h: 200 },
+ { name: 's', y: 320, h: 120 },
+ { name: 'cards', y: 500, h: 400 },
+ { name: 'cta', y: 950, h: 150 },
+ { name: 'footer', y: 1150, h: 100 },
+ ], 1920)
+ expect(b.ok).toBe(true)
+ if (b.ok) {
+ expect(b.bands[0].y).toBe(115)
+ expect(b.bands[4].y + b.bands[4].h).toBeLessThanOrEqual(1805)
+ for (let i = 1; i < b.bands.length; i++) {
+ expect(b.bands[i].y - (b.bands[i - 1].y + b.bands[i - 1].h)).toBeGreaterThanOrEqual(40)
+ }
+ }
+ // infeasible on BOTH: 2000px of content cannot fit either page
+ const inf: { name: string; y: number; h: number }[] = [{ name: 'x', y: 100, h: 2000 }]
+ expect(repairPlanBands(inf, 1350).ok).toBe(false)
+ expect(repairPlanBands(inf, 1920).ok).toBe(false)
+ })
+
+ it('a VALID plan is accepted unchanged — zero repairs', async () => {
+ const { repairPlanBands } = await import('./plan-repair')
+ const r = repairPlanBands([
+ { name: 'a', y: 65, h: 200 },
+ { name: 'b', y: 305, h: 100 },
+ ], 1080)
+ expect(r.ok).toBe(true)
+ if (!r.ok) return
+ expect(r.repairs).toEqual([])
+ expect(r.bands).toEqual([
+ { name: 'a', y: 65, h: 200 },
+ { name: 'b', y: 305, h: 100 },
+ ])
+ })
+})
+
+describe('v0.32.5 · honest outcome classification (a failure is never a green check)', () => {
+ it('failure markers classify as failure; clean verification as success', async () => {
+ const { turnOutcome, isFailureOutcome } = await import('./outcome')
+ expect(isFailureOutcome('NOT completed — the run ended without applying any design change')).toBe(true)
+ expect(isFailureOutcome('Stopped after 3 infeasible plans — the exact math is in the errors above')).toBe(true)
+ expect(isFailureOutcome('Quality audit at wrap-up reports 2 issue(s) — disclosed, unfixed.')).toBe(true)
+ expect(isFailureOutcome('Brief contract validated against the live canvas — all mandatory items present.')).toBe(false)
+ expect(turnOutcome({ mode: 'create', verification: 'Brief contract validated against the live canvas.', appliedActions: 12 })).toBe('success')
+ expect(turnOutcome({ mode: 'create', verification: undefined, content: 'Stopped after 3 consecutive invalid tool calls', appliedActions: 0 })).toBe('failure')
+ // the exact P0 production turn: create, 0 actions, no verification
+ expect(turnOutcome({ mode: 'create', verification: undefined, content: 'Stopped after 3 infeasible plans — ask the user for a smaller composition.', appliedActions: 0 })).toBe('failure')
+ // discuss/review turns apply nothing BY DESIGN — not failures
+ expect(turnOutcome({ mode: 'discuss', verification: undefined, content: 'This poster uses a strong vertical hierarchy…', appliedActions: 0 })).toBe('unknown')
+ })
+})
diff --git a/src/lib/agent/loop.ts b/src/lib/agent/loop.ts
index 760f509..cf33bad 100644
--- a/src/lib/agent/loop.ts
+++ b/src/lib/agent/loop.ts
@@ -29,6 +29,20 @@
// ─────────────────────────────────────────────────────────────
import { AGENT_GUARDS, AGENT_PROTOCOL_VERSION, parseAgentTurn, type AgentEvent, type AgentMode, type AgentTurn } from './protocol'
+
+/** v0.32.5: structured, credential-free agent telemetry — the failed
+ * constraint, the recovery attempts and the final outcome, as one
+ * JSON line the server logs can filter (`[agent:telemetry]`).
+ * Server-side only (this module runs on the route, never shipped to
+ * the browser); carries geometry and outcomes only — never prompts,
+ * keys or provider data. */
+export function telemetry(event: Record<string, unknown>): void {
+ try {
+ console.warn(`[agent:telemetry] ${JSON.stringify({ at: new Date().toISOString(), ...event })}`)
+ } catch {
+ /* logging must never break the loop */
+ }
+}
import { AGENT_TOOLS, AGENT_TOOL_MAP, fontFamilies, type ToolContext, type SanitizeResult, type AgentTool } from './tools'
import { serializeDesignContext, contextValidIds, type AgentDesignCtx } from './context'
import { MODE_PROMPTS, MODE_TOOL_RISK } from './router'
@@ -315,6 +329,12 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
* __planLayout action) — passed to the quality audit so it can
* check plan adherence (empty planned sections). */
const planBands: { name: string; y: number; h: number }[] = []
+ /** v0.32.5: consecutive infeasible plan_layout rejections. These
+ * never touch `strikes` (recoverable geometric constraints, not
+ * model failures) but they are BOUNDED — a model that cannot
+ * produce a fitting plan stops honestly with the exact math
+ * instead of retrying forever. */
+ let planRejections = 0
const toolCtx: ToolContext = {
validIds: contextValidIds(design),
@@ -387,6 +407,15 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
return { summary: base, verification }
}
+ // v0.32.5 telemetry: guard exits log their final outcome — the
+ // failed constraint (in the plan telemetry), the recovery attempts
+ // (rejections/repairs) and how the run actually ended.
+ const guardExitWithTelemetry = async (base: string, reason: string) => {
+ const exit = await guardExit(base)
+ telemetry({ outcome: 'guard-exit', reason, steps, toolCalls, designChanges, planRejections })
+ return exit
+ }
+
while (true) {
// ── task-driven stops ───────────────────────────────────
if (signal?.aborted) {
@@ -411,11 +440,11 @@ 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',
})
- const exit = await guardExit(summary || 'Stopped after repeated invalid calls.')
+ const exit = await guardExitWithTelemetry(summary || 'Stopped after repeated invalid calls.', 'strikes')
return { summary: exit.summary, steps, toolCalls, verification: exit.verification }
}
if (Date.now() - lastProgressAt > AGENT_GUARDS.idleMs) {
- const exit = await guardExit('The run stopped making progress and was wrapped up. Everything applied so far is kept — send a follow-up message to continue.')
+ const exit = await guardExitWithTelemetry('The run stopped making progress and was wrapped up. Everything applied so far is kept — send a follow-up message to continue.', 'no-progress')
emit({
v: AGENT_PROTOCOL_VERSION,
type: 'done',
@@ -448,7 +477,7 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
message: `The AI provider failed: ${err instanceof Error ? err.message.slice(0, 200) : 'unknown error'}. Applied work is kept — retry to continue.`,
code: 'PROVIDER',
})
- const exit = await guardExit(summary)
+ const exit = await guardExitWithTelemetry(summary, 'provider')
return { summary: exit.summary, steps, toolCalls, verification: exit.verification }
}
@@ -563,7 +592,10 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
// never influence the design. Bounded: one critique now, one
// correction round, one verification re-capture. A run whose
// final capture still shows P0 defects does NOT claim success.
- if ((mode === 'create' || mode === 'improve') && deps.critique && visionCritiques < 2) {
+ // v0.32.5: a run that applied NOTHING skips the critique —
+ // capturing an empty canvas produced "vision model returned no
+ // parseable critique" noise on the P0 run and verifies nothing.
+ if ((mode === 'create' || mode === 'improve') && designChanges > 0 && deps.critique && visionCritiques < 2) {
const shot = deps.captureCanvas ? await deps.captureCanvas() : null
if (!shot) {
// fail-closed: no capture → visual quality is NOT verified,
@@ -685,12 +717,16 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
// an observation. No apply/ack round trip: a plan changes nothing.
if (toolName === 'plan_layout' && result.ok) {
planHasRun = true
+ // v0.32.5: a recorded plan (possibly server-repaired) resets the
+ // infeasibility budget — the guard counts CONSECUTIVE rejections
+ planRejections = 0
const planActions = (result.actions as { type: string; lines?: string[]; bands?: { name: string; y: number; h: number }[] }[])
const planLines = planActions.flatMap((a) => (a && a.type === '__planLayout' && Array.isArray(a.lines) ? a.lines : []))
// v0.32.4: keep the structured bands for the quality audit's
// plan-adherence check (empty planned sections)
planBands.length = 0
planBands.push(...planActions.flatMap((a) => (a && a.type === '__planLayout' && Array.isArray(a.bands) ? a.bands : [])))
+ telemetry({ tool: 'plan_layout', outcome: 'recorded', repaired: (result.observation ?? '').includes('AUTO-REPAIRED'), bands: planBands.length })
const lines = planLines.length ? planLines : ['(model emitted an empty plan)']
emit({ v: AGENT_PROTOCOL_VERSION, type: 'plan', steps: lines })
emit({ v: AGENT_PROTOCOL_VERSION, type: 'observation', stepIndex: steps, message: result.observation })
@@ -745,7 +781,7 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
if (hash === lastCallHash) {
cycleCount += 1
if (cycleCount >= AGENT_GUARDS.cycleRepeat - 1) {
- const exit = await guardExit('The run repeated the same operation without effect and was wrapped up. Applied work is kept — describe the next change to continue.')
+ const exit = await guardExitWithTelemetry('The run repeated the same operation without effect and was wrapped up. Applied work is kept — describe the next change to continue.', 'cycle-repeat')
emit({
v: AGENT_PROTOCOL_VERSION,
type: 'done',
@@ -763,6 +799,29 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
}
if (!result.ok) {
+ // v0.32.5 · P0 REGRESSION FIX: plan_layout rejections are
+ // RECOVERABLE geometric constraints, not model failures. The
+ // P0 production run died at "Stopped after 3 consecutive
+ // invalid tool calls" with ZERO elements because every rejected
+ // plan cost a strike. Two changes:
+ // · repairable geometry no longer rejects at all — the
+ // server-side solver auto-repairs it (plan-repair.ts), so
+ // the loop never sees those cases;
+ // · what still rejects (infeasible heights, malformed
+ // sections) counts against a SEPARATE bounded budget —
+ // never the shared strike counter — and stops honestly
+ // with the exact math after PLAN_REJECTION_BUDGET tries.
+ if (toolName === 'plan_layout') {
+ planRejections += 1
+ telemetry({ tool: 'plan_layout', outcome: 'rejected', attempt: planRejections, detail: String((result as { error?: string }).error ?? '').slice(0, 300) })
+ if (planRejections >= AGENT_GUARDS.planRejections) {
+ const exit = await guardExitWithTelemetry(`Stopped after ${planRejections} infeasible plans — the exact math is in the errors above; ask the user for a smaller composition or fewer sections.`, 'plan-infeasible')
+ emit({ v: AGENT_PROTOCOL_VERSION, type: 'done', summary: exit.summary, steps, toolCalls, verification: exit.verification })
+ return { summary: exit.summary, steps, toolCalls, verification: exit.verification }
+ }
+ messages.push({ role: 'user', content: observationFor(toolName, result, false) })
+ continue
+ }
// free correction: rejected calls cost only a strike
strikes += 1
messages.push({ role: 'user', content: observationFor(toolName, result, false) })
diff --git a/src/lib/agent/outcome.ts b/src/lib/agent/outcome.ts
new file mode 100644
index 0000000..93aaa8f
--- /dev/null
+++ b/src/lib/agent/outcome.ts
@@ -0,0 +1,66 @@
+/**
+ * v0.32.5 · honest outcome classification — shared by the chat UI.
+ *
+ * The P0 run ended with zero elements after three infeasible plans,
+ * yet the panel's verification line rendered with an emerald check
+ * (or nothing at all): a failure was displayed as — or next to —
+ * success. The classifier below lets the UI pick the honest tone:
+ * failure markers → amber alert, otherwise the emerald check.
+ *
+ * PURE on purpose (no React, no db) so unit tests can pin it.
+ */
+
+/** Markers that appear ONLY in disclosed failure/partial outcomes —
+ * never in a clean success verification string. */
+const FAILURE_MARKERS: readonly string[] = [
+ 'NOT completed',
+ 'NOT verified',
+ 'Visual critique UNAVAILABLE',
+ 'Visual critique unavailable',
+ 'disclosed, unfixed',
+ 'INCOMPLETE',
+ 'Infeasible',
+ 'infeasible',
+ 'Stopped after',
+ 'wrapped up',
+ 'INCOMPLETE —',
+ 'unmet',
+ 'Unmet',
+ 'failed',
+ 'Failed',
+ 'provider failed',
+ 'no design changes',
+]
+
+/** True when the text discloses a failure or partial outcome. */
+export function isFailureOutcome(text: string | undefined | null): boolean {
+ if (!text) return false
+ return FAILURE_MARKERS.some((m) => text.includes(m))
+}
+
+/** The UI status of a finished agent turn: success, failure or none. */
+export type TurnOutcome = 'success' | 'failure' | 'unknown'
+
+/** Modes whose job is to change the design — a finished turn in one
+ * of these modes that applied nothing did not succeed. */
+const CREATIVE_MODES: readonly string[] = ['create', 'improve']
+
+export function turnOutcome(opts: {
+ mode?: string
+ verification?: string
+ content?: string
+ appliedActions?: number
+}): TurnOutcome {
+ // an explicit verification/content failure marker wins, whatever
+ // the action count (a partial run that stopped honestly is a
+ // failure to present accurately, not a success to gloss)
+ if (isFailureOutcome(opts.verification) || isFailureOutcome(opts.content)) return 'failure'
+ // a CREATE/IMPROVE turn that applied nothing and verified nothing
+ // is not a success either. (review/discuss/explain turns apply
+ // nothing BY DESIGN — they are judged by their markers only.)
+ if (!opts.verification && CREATIVE_MODES.includes(opts.mode ?? '') && (opts.appliedActions ?? 0) === 0) {
+ return 'failure'
+ }
+ if (opts.verification) return 'success'
+ return 'unknown'
+}
diff --git a/src/lib/agent/plan-repair.ts b/src/lib/agent/plan-repair.ts
new file mode 100644
index 0000000..77c602a
--- /dev/null
+++ b/src/lib/agent/plan-repair.ts
@@ -0,0 +1,147 @@
+/**
+ * v0.32.5 · DETERMINISTIC PLAN REPAIR — the P0 regression fix.
+ *
+ * The v0.32.4 hard validator REJECTED invalid plans and told the
+ * model to redo the gap arithmetic. A model that cannot do that
+ * arithmetic failed three times in a row and the run died with
+ * ZERO elements ("Stopped after 3 consecutive invalid tool calls")
+ * — on the panel's own coffee-launch suggestion. Forcing the model
+ * to compute geometry is the bug: the SERVER computes it.
+ *
+ * This module is PURE (no db, no client, no model): given the
+ * canvas, the 6% margins, the 40px minimum gap and the requested
+ * sections, it deterministically produces a valid band layout —
+ * or an honest infeasibility with the exact math. Never a
+ * fabrication: heights, order and contents are the model's own;
+ * only the y-positions and gaps are computed.
+ *
+ * repairPlanBands(sections, H) →
+ * { ok: true, bands, repairs, gap } valid or repaired
+ * { ok: false, infeasible } cannot fit — exact math
+ */
+
+export interface PlanSection {
+ name: string
+ y: number
+ h: number
+}
+
+export interface RepairedBand {
+ name: string
+ y: number
+ h: number
+}
+
+export interface PlanRepairOk {
+ ok: true
+ /** valid bands, ordered top-to-bottom, all inside the safe area */
+ bands: RepairedBand[]
+ /** the gap actually used between consecutive bands (≥ minGap) */
+ gap: number
+ /** human-readable disclosures — EMPTY when the plan was already valid */
+ repairs: string[]
+}
+
+export interface PlanRepairInfeasible {
+ ok: false
+ /** the exact math, for the model AND the UI — never a vague "try again" */
+ infeasible: string
+}
+
+export type PlanRepairResult = PlanRepairOk | PlanRepairInfeasible
+
+export const PLAN_MIN_GAP = 40
+export const PLAN_MARGIN = 0.06
+
+/**
+ * Deterministic layout solver.
+ *
+ * Rules, in order:
+ * 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
+ * safe area, in the model's intended order, with the requested
+ * heights and a uniform gap: max(minGap, leftover / (n-1)) —
+ * the natural composition the model meant to build.
+ * 3. If the content cannot fit even at exactly minGap gaps, the
+ * result is INFEASIBLE with the exact numbers — the model must
+ * shrink heights or drop sections (its choice, its hierarchy).
+ */
+export function repairPlanBands(
+ requested: PlanSection[],
+ H: number,
+ opts?: { minGap?: number; margin?: number },
+): PlanRepairResult {
+ const minGap = opts?.minGap ?? PLAN_MIN_GAP
+ const margin = opts?.margin ?? PLAN_MARGIN
+ const n = requested.length
+ if (n === 0) {
+ return { ok: false, infeasible: 'No sections to lay out.' }
+ }
+ // invalid heights are not geometry to repair — they are rejected
+ // upstream by the tool; here they are clamped defensively
+ const sections = requested
+ .map((s) => ({ name: s.name || 'section', y: Math.max(0, s.y), h: Math.max(1, Math.round(s.h)) }))
+ .sort((a, b) => a.y - b.y)
+
+ const safeTop = Math.round(H * margin)
+ const safeBottom = Math.round(H * (1 - margin))
+ const usable = safeBottom - safeTop
+ const sumH = sections.reduce((acc, s) => acc + s.h, 0)
+
+ if (sumH > usable) {
+ return {
+ ok: false,
+ infeasible:
+ `Infeasible plan: the sections total ${sumH}px of content, but the safe area is only ${usable}px ` +
+ `(page ${H}px, 6% margins top/bottom ${safeTop}px, ${H - safeBottom}px). ` +
+ `Reduce the section heights or drop sections — the smallest fitting layout needs ≤${Math.floor(usable / n)}px per section.`,
+ }
+ }
+
+ // Rule 1 — already valid? Keep the model's exact geometry.
+ const valid =
+ sections[0].y >= safeTop &&
+ sections[n - 1].y + sections[n - 1].h <= safeBottom &&
+ sections.every((s, i) => i === 0 || s.y - (sections[i - 1].y + sections[i - 1].h) >= minGap)
+ if (valid) {
+ return {
+ ok: true,
+ bands: sections.map((s) => ({ name: s.name, y: s.y, h: s.h })),
+ gap: n > 1 ? sections[1].y - (sections[0].y + sections[0].h) : minGap,
+ repairs: [],
+ }
+ }
+
+ // Rule 2 — deterministic re-layout: requested heights, uniform
+ // gap (minGap, or the natural spread when there is room).
+ const gap = n > 1 ? Math.max(minGap, Math.floor((usable - sumH) / (n - 1))) : minGap
+ const bands: RepairedBand[] = []
+ const repairs: string[] = []
+ let y = safeTop
+ 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 (bands[n - 1].y + bands[n - 1].h <= safeBottom) {
+ if (n > 1) repairs.push(`uniform ${gap}px gaps between all ${n} sections`)
+ return { ok: true, bands, gap, repairs }
+ }
+
+ // Single band that still overflows the safe area (clamped h >
+ // usable): shrink honestly with a disclosure.
+ if (n === 1 && sumH > usable) {
+ return {
+ ok: false,
+ infeasible: `Infeasible plan: the single section is ${sumH}px tall, but the safe area is only ${usable}px (page ${H}px).`,
+ }
+ }
+ // unreachable for n ≥ 1 with sumH ≤ usable — kept for honesty
+ return {
+ ok: false,
+ infeasible: `Infeasible plan: the sections (${sumH}px + gaps) cannot fit the ${usable}px safe area.`,
+ }
+}
diff --git a/src/lib/agent/protocol.ts b/src/lib/agent/protocol.ts
index e40cd16..bd579fe 100644
--- a/src/lib/agent/protocol.ts
+++ b/src/lib/agent/protocol.ts
@@ -55,6 +55,11 @@ export const AGENT_GUARDS = {
turnWarnAt: 50,
/** actions attached to a single-shot `act` reply */
maxDirectActions: 6,
+ /** v0.32.5: consecutive infeasible plan_layout rejections before
+ * an honest stop with the exact math (separate from `strikes` —
+ * geometric constraint failures are recoverable, not model
+ * failures, but a run may not retry them forever) */
+ planRejections: 3,
} as const
/** v0.28 modes (Phase 8). Read-only modes (review, explain, plan,
diff --git a/src/lib/agent/tools.ts b/src/lib/agent/tools.ts
index ac99043..b1f966d 100644
--- a/src/lib/agent/tools.ts
+++ b/src/lib/agent/tools.ts
@@ -16,6 +16,7 @@
import { FONTS } from '@/lib/fonts/catalog'
import type { ToolRisk } from './protocol'
+import { repairPlanBands } from './plan-repair'
export interface AgentTool {
name: string
@@ -174,71 +175,68 @@ export const AGENT_TOOLS: AgentTool[] = [
if (!Array.isArray(sectionsRaw) || sectionsRaw.length === 0) {
return { ok: false, error: '"sections" must be a non-empty array: [{name, y, height, contains}].' }
}
- const lines: string[] = []
const H = ctx.height
+ // parse the requested sections (name + numeric y/height + the
+ // model's own `contains` notes). Malformed entries are hard
+ // errors — GEOMETRY, however, is no longer the model's job.
+ const parsed: { name: string; y: number; h: number; contains: string }[] = []
for (const s of sectionsRaw.slice(0, 12)) {
if (!s || typeof s !== 'object') continue
const sec = s as Record<string, unknown>
const name = typeof sec.name === 'string' ? sec.name.trim().slice(0, 40) : ''
- const y = num(sec as Record<string, unknown>, 'y')
- const height = num(sec as Record<string, unknown>, 'height')
+ const y = num(sec, 'y')
+ const height = num(sec, 'height')
const contains = typeof sec.contains === 'string' ? sec.contains.trim().slice(0, 80) : ''
if (!name) return { ok: false, error: 'Each section needs a "name".' }
if (y === null || height === null || height <= 0) {
return { ok: false, error: `Section "${name}" needs numeric y and height (> 0).` }
}
- lines.push(`${name}: y=${Math.round(y)} h=${Math.round(height)}${contains ? ` — ${contains}` : ''}`)
+ parsed.push({ name, y, h: Math.round(height), contains })
}
- if (!lines.length) return { ok: false, error: '"sections" contained no usable entries.' }
- const bg = hex(args, 'background')
- if (bg) lines.unshift(`page background ${bg}`)
- const notes = typeof args.notes === 'string' ? args.notes.trim().slice(0, 200) : ''
- if (notes) lines.push(`notes: ${notes}`)
- // v0.32.4: HARD geometry validation — the plan protocol
- // promises ≥40px gaps and bands inside the page; the plan is
- // now REJECTED when it violates either (the model retries
- // with a corrected plan; sanitize errors are retryable, not
- // strikes). Safe-area intrusion stays a WARNING (content can
- // sit inside bands that start slightly high; the audit flags
- // actual text that hugs the edge). This closes the old `- 24`
- // slack that let sections overlap by up to 24px.
- const bands = sectionsRaw
- .filter((s) => s && typeof s === 'object')
- .map((s) => s as Record<string, unknown>)
- .map((s) => ({
- name: typeof s.name === 'string' ? s.name.trim().slice(0, 40) : '',
- y: num(s, 'y') ?? 0,
- h: num(s, 'height') ?? 0,
- }))
- .filter((b) => b.h > 0)
- const sorted = [...bands].sort((a, b) => a.y - b.y)
- const problems: string[] = []
- const warnings: string[] = []
- if (sorted.length) {
- if (sorted[0].y < 0) problems.push(`section 1 starts at y=${Math.round(sorted[0].y)} — negative y`)
- const last = sorted[sorted.length - 1]
- if (last.y + last.h > H) problems.push(`the last section ends at y=${Math.round(last.y + last.h)} — beyond the ${H}px page`)
- for (let i = 1; i < sorted.length; i++) {
- const gap = sorted[i].y - (sorted[i - 1].y + sorted[i - 1].h)
- if (gap < 40) {
- problems.push(`sections "${sorted[i - 1].name}" and "${sorted[i].name}" need ≥40px gap; found ${Math.round(gap)}px at y=${Math.round(sorted[i].y)}`)
- }
- }
- const safeTop = Math.round(H * 0.06)
- const safeBottom = Math.round(H * 0.94)
- if (sorted[0].y < safeTop) warnings.push(`the first band starts at y=${Math.round(sorted[0].y)}, inside the 6% top margin (${safeTop}px) — prefer starting at y=${safeTop}`)
- if (last.y + last.h > safeBottom) warnings.push(`the last band ends at y=${Math.round(last.y + last.h)}, inside the 6% bottom margin (ends ${safeBottom}px) — prefer ending by y=${safeBottom}`)
- }
- if (problems.length) {
+ if (!parsed.length) return { ok: false, error: '"sections" contained no usable entries.' }
+
+ // v0.32.5 · THE P0 REGRESSION FIX: the v0.32.4 validator
+ // rejected bad geometry and told the model to redo the gap
+ // arithmetic. A model that could NOT do that arithmetic failed
+ // plan_layout three times in a row and the run died with ZERO
+ // elements — on the panel's own coffee-launch suggestion.
+ // Forcing the model to compute geometry was the bug: the
+ // SERVER computes it now (plan-repair.ts, pure + deterministic).
+ // · valid plan → accepted unchanged
+ // · invalid but fitting → AUTO-REPAIRED y-positions and gaps
+ // (heights, order, contents kept) and
+ // the repair is DISCLOSED — the model
+ // builds from the repaired bands
+ // · 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)
+ if (!repair.ok) {
return {
ok: false,
- error: `Invalid plan: ${problems.join('; ')}. Revise plan_layout so the bands tile the page top-to-bottom, each fully inside 0..${H} with ≥40px gaps between sections.`,
+ error: `${repair.infeasible} Resend plan_layout with smaller section heights (keep the names and order).`,
}
}
- const observation = `PLAN RECORDED (${lines.length} lines):\n${lines.join('\n')}${warnings.length ? `\nPLAN WARNINGS: ${warnings.join('; ')} — revise the bands before building.` : '\nBands verified: non-overlapping, ≥40px gaps, inside the page.'}`
+
+ // the plan lines are the REPAIRED geometry — the authoritative
+ // bands the model must build inside (no model arithmetic).
+ const lines: string[] = []
+ const bg = hex(args, 'background')
+ if (bg) lines.push(`page background ${bg}`)
+ for (const b of repair.bands) {
+ const c = parsed.find((p) => p.name === b.name)
+ lines.push(`${b.name}: y=${Math.round(b.y)} h=${Math.round(b.h)}${c?.contains ? ` — ${c.contains}` : ''}`)
+ }
+ const notes = typeof args.notes === 'string' ? args.notes.trim().slice(0, 200) : ''
+ if (notes) lines.push(`notes: ${notes}`)
+
+ 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}`
return {
ok: true,
- actions: [{ type: '__planLayout', lines, bands }],
+ actions: [{ type: '__planLayout', lines, bands: repair.bands }],
observation,
}
},
diff --git a/tests/e2e/unified-ai-reproduction.spec.ts b/tests/e2e/unified-ai-reproduction.spec.ts
index fde0797..6d68a27 100644
--- a/tests/e2e/unified-ai-reproduction.spec.ts
+++ b/tests/e2e/unified-ai-reproduction.spec.ts
@@ -208,3 +208,167 @@ test.describe('Unified Canvix AI reproduction (v0.32.2 fix)', () => {
await page.screenshot({ path: 'test-results/repro-edited.png', fullPage: false })
})
})
+
+/** v0.32.5 · the P0 production failure, browser-level:
+ * "Design a bold Instagram post for a coffee launch" on an empty
+ * canvas → three rejected plan_layout calls (<40px gaps) →
+ * "Stopped after 3 consecutive invalid tool calls" → ZERO elements
+ * → the client then critiqued the EMPTY canvas and the failure sat
+ * next to a green verification check.
+ *
+ * The unit harness pins the SERVER side (auto-repair, no strikes,
+ * bounded infeasibility). This spec pins the CLIENT side: a failed
+ * zero-action create run (a) never calls the vision route and
+ * (b) shows the amber failure status, never a green check. */
+function failedRunScript(): string {
+ const ev = (e: unknown) => `data: ${JSON.stringify(e)}\n\n`
+ const events: unknown[] = [
+ { v: V, type: 'start', runId: 'mock-p0-run' },
+ { v: V, type: 'mode', mode: 'create', reason: 'classified as create' },
+ { v: V, type: 'step', index: 0, thought: 'planning the coffee post', tool: 'plan_layout' },
+ { v: V, type: 'observation', stepIndex: 0, message: 'ERROR: sections "headline" and "subline" need ≥40px gap; found 20px.' },
+ { v: V, type: 'step', index: 1, thought: 'retrying the plan', tool: 'plan_layout' },
+ { v: V, type: 'observation', stepIndex: 1, message: 'ERROR: sections need ≥40px gap; found 10px.' },
+ { v: V, type: 'step', index: 2, thought: 'retrying again', tool: 'plan_layout' },
+ { v: V, type: 'observation', stepIndex: 2, message: 'ERROR: sections need ≥40px gap; found 0px.' },
+ {
+ v: V, type: 'done', steps: 3, toolCalls: 0,
+ summary: 'INCOMPLETE — no design changes were made. Stopped after 3 infeasible plans — the exact math is in the errors above; ask the user for a smaller composition or fewer sections.',
+ verification: 'NOT completed — the run ended without applying any design change; nothing was created.',
+ },
+ ]
+ return events.map(ev).join('')
+}
+
+/** the follow-up turn in the SAME conversation: an edit-run script
+ * that changes the headline — pins that a follow-up request
+ * reaches the route verbatim WITH the prior conversation. */
+function followUpScript(): string {
+ const ev = (e: unknown) => `data: ${JSON.stringify(e)}\n\n`
+ const events: unknown[] = [
+ { v: V, type: 'start', runId: 'mock-followup-run' },
+ { v: V, type: 'mode', mode: 'edit', reason: 'classified as edit' },
+ { v: V, type: 'step', index: 0, thought: 'making the headline the user asked for', tool: 'update_elements' },
+ {
+ v: V, type: 'action', stepIndex: 0, callId: 'f0', risk: 'write', tool: 'update_elements',
+ actions: [{ type: 'updateElements', ids: ['<headline-id>'], patch: { text: 'CREATE IT YOURSELF' } }],
+ },
+ { v: V, type: 'observation', stepIndex: 0, message: 'Headline updated.' },
+ { v: V, type: 'done', steps: 1, toolCalls: 1, summary: 'Headline changed as requested.' },
+ ]
+ return events.map(ev).join('')
+}
+
+test.describe('v0.32.5 · the P0 regression — zero-action failures and follow-ups', () => {
+ test('a failed zero-action create run never critiques the empty canvas and shows the honest failure status', async ({ page }) => {
+ await register(page, 'p0')
+ const designId = await createEmptyDesign(page, 'P0 regression canvas')
+ await openEditor(page, designId)
+
+ // order matters: the agent glob also matches the vision URL, and
+ // the LAST registered handler wins — the vision counter must be
+ // registered after the agent handler to really intercept.
+ await page.route('**/api/ai/agent**', async (route: Route) => {
+ const req = route.request()
+ if (req.method() === 'POST' && (req.url().includes('bridge=') || req.url().includes('/vision'))) {
+ await route.fulfill({ status: 200, contentType: 'application/json', body: '{}' })
+ return
+ }
+ await route.fulfill({
+ status: 200,
+ headers: { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache' },
+ body: failedRunScript(),
+ })
+ })
+ let visionCalls = 0
+ await page.route('**/api/ai/agent/vision**', async (route: Route) => {
+ visionCalls += 1
+ await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ findings: [] }) })
+ })
+
+ 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 honest amber failure status — the disclosed failure
+ // verification IS the status line (never a green check)
+ await expect(page.getByText('NOT completed — the run ended without applying any design change; nothing was created.')).toBeVisible({ timeout: 10_000 })
+ // the empty canvas was never critiqued
+ await page.waitForTimeout(2500)
+ expect(visionCalls).toBe(0)
+ // the document is still empty — no partial residue
+ const still = await doc(page, designId)
+ expect(still.pages[0].elements).toHaveLength(0)
+
+ await page.screenshot({ path: 'test-results/p0-honest-failure.png', fullPage: false })
+ })
+
+ test('the coffee prompt then "Create by yourself" as a follow-up in the same conversation', async ({ page }) => {
+ await register(page, 'followup')
+ const designId = await createEmptyDesign(page, 'Follow-up conversation canvas')
+ await openEditor(page, designId)
+
+ const captured: Record<string, unknown>[] = []
+ let run = 0
+ await page.route('**/api/ai/agent**', async (route: Route) => {
+ const req = route.request()
+ // bridge acks AND the Phase-7 vision critique also match this
+ // glob — neither is an agent run (the vision call has no
+ // `message`; capturing it made captured[1] a vision body)
+ if (req.method() === 'POST' && (req.url().includes('bridge=') || req.url().includes('/vision'))) {
+ await route.fulfill({ status: 200, contentType: 'application/json', body: '{}' })
+ return
+ }
+ run += 1
+ captured.push(req.postDataJSON() as Record<string, unknown>)
+ // run 1: the coffee create script; run 2+: the follow-up edit.
+ // the edit script targets the headline the create run added —
+ // patch the real element id into the scripted action.
+ const body = run === 1
+ ? sseScript()
+ : followUpScript().replace('<headline-id>', String((captured[run - 1] as { design?: { elements?: { id?: string; text?: string }[] } }).design?.elements?.find((e) => e.text === 'ARTISAN ROAST')?.id ?? ''))
+ await route.fulfill({
+ status: 200,
+ headers: { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache' },
+ body,
+ })
+ })
+
+ await page.getByRole('button', { name: 'Apps', exact: true }).click()
+ 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.getByRole('button', { name: 'Send', exact: true }).click()
+ await waitForDoc(
+ page,
+ designId,
+ (d) => (d.pages[0]?.elements ?? []).some((e) => (e as { text?: string }).text === 'ARTISAN ROAST'),
+ 'the first-run headline',
+ )
+
+ // 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.getByRole('button', { name: 'Send', exact: true }).click()
+
+ // the follow-up request reached the route VERBATIM, with the
+ // conversation history riding along
+ await expect
+ .poll(async () => captured.length, { timeout: 10_000 })
+ .toBeGreaterThanOrEqual(2)
+ expect((captured[1] as { message?: string }).message).toBe('Create by yourself')
+ const history = (captured[1] as { history?: { role: string; content: string }[] }).history ?? []
+ expect(history.some((h) => h.content.includes('coffee launch'))).toBe(true)
+
+ // the follow-up's edit really landed on the AI-created headline
+ await waitForDoc(
+ page,
+ designId,
+ (d) => (d.pages[0]?.elements ?? []).some((e) => (e as { text?: string }).text === 'CREATE IT YOURSELF'),
+ 'the follow-up headline change',
+ )
+
+ await page.screenshot({ path: 'test-results/follow-up-conversation.png', fullPage: false })
+ })
+})