Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
fix(v0.32.8): the NEON 2027 agent runs — scaled plans, the emitted capture, the type#id alias
Ashiq Hussain Mir0ad712d34aa8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b374ec3..4c7b277 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,48 @@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.8: the NEON 2027 agent runs — scaled plans, the emitted capture, the `type#id` alias++One brief, three runs, three deterministic defects:++- **Run 1 (create, 0 actions):** a reasonable 7-section poster plan+ exceeded the safe area; the model cannot redo height arithmetic,+ and three infeasible rejections ended the run with ZERO elements+ ("ask the user for a smaller composition or fewer sections").+ **Fix:** the plan solver now SCALES oversized section heights+ uniformly to fit (each band floored at 56px, the model's relative+ hierarchy kept, the scaling DISCLOSED); on an occupied canvas it+ shrinks sections into the free space (bounded ×0.88 passes,+ floored) before declaring infeasible. Infeasible survives only+ for compositions that cannot fit even at the floor — reported+ with the exact math AND the maximum section count that fits. The+ system prompt states the computed per-page section budget up+ front, and the plan-rejection guard message points at the fixable+ cause (malformed sections / floor-infeasible composition), never+ at the user's brief.+- **Run 2 (create, 70 actions):** "Visual critique UNAVAILABLE+ (canvas capture timed out or no client)" — the `capture` event+ was in the protocol and handled by the panel but NEVER EMITTED,+ so every create/improve run stalled the full capture timeout and+ the in-run vision critique never ran once. **Fix:** the loop+ emits `capture` before awaiting the bridge answer. Also: a+ quality-audit residue after the first fix round now gets ONE more+ bounded pass (`auditFixRounds`: 2) before the honest disclosure.+- **Run 3 (edit, "fix issues"):** "Stopped after 3 consecutive+ invalid tool calls." Root cause: the serialized context, the audit+ findings and the overlap reports all print ids as `text#abc123` —+ the model passed that notation verbatim into `ids:[...]` and was+ rejected three times. **Fix:** id lists accept the `type#id` alias+ (prefix stripped, bare id validated — the same alias discipline as+ the color/fontColor/textColor patch aliases), and the SECOND+ consecutive rejection carries an explicit recovery note (refresh+ ids via get_page_state, retry to spec) before a third can end the+ run.++Unit harness: +11 regression tests (scaled plans, floor+infeasibility, occupied-canvas shrink, the emitted capture, the+second audit round, the id alias, the recovery note) — 1,759/1,759.+### Fixed — v0.32.7: the funding.json .well-known URL-form mismatch- **The failure:** `canvix.app/.well-known/funding-manifest-urls` listeddiff --git a/src/lib/agent/harness.test.ts b/src/lib/agent/harness.test.tsindex 31673ba..064c8c7 100644--- a/src/lib/agent/harness.test.ts+++ b/src/lib/agent/harness.test.ts@@ -322,14 +322,15 @@ describe('harness · tool matrix', () => {expect(String((finalEvent as { verification?: string }).verification ?? '')).toContain('Quality audit passed')})- it('CASE H: audit residue is disclosed, never looped — a second failing audit still accepts done', async () => {+ it('CASE H: audit residue is disclosed, never looped — after the bounded fix rounds a still-failing audit accepts done', async () => {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'),+ done('Done attempt 2'),+ done('Done attempt 3 — unfixable, disclosed'),])const result = await runAgentLoop({chat,@@ -1541,10 +1542,9 @@ describe('v0.29.3 · loop: planning + fail-closed acks', () => {{ 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(+ // v0.32.8: 1200px of content on a 950px usable page is no longer+ // infeasible — it SCALES (disclosed): 3×290px bands with 40px gaps.+ const oversized = tool!.sanitize({sections: [{ name: 'a', y: 65, height: 400, contains: 'x' },@@ -1554,12 +1554,27 @@ describe('v0.29.3 · loop: planning + fail-closed acks', () => {},ctx,)+ expect(oversized.ok).toBe(true)+ const ob = (oversized as { actions?: { bands?: { name: string; y: number; h: number }[] }[] }).actions?.[0]?.bands+ expect(ob?.every((b) => b.h === 290)).toBe(true)+ expect(ob![2].y + ob![2].h).toBeLessThanOrEqual(1015)+ expect(String((oversized as { observation?: string }).observation)).toContain('AUTO-REPAIRED')++ // truly INFEASIBLE remains for compositions that cannot fit even at+ // the 56px floor: 12 sections floor to 672px + 440px of gaps =+ // 1112px > the 950px safe area — rejected with the exact math. No+ // strikes: the loop's separate plan budget handles it (pinned below).+ const infeasible = tool!.sanitize(+ {+ sections: Array.from({ length: 12 }, (_, i) => ({ name: `s${i + 1}`, y: 65 + i * 100, height: 140, contains: 'x' })),+ },+ ctx,+ )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')+ expect(err).toContain('56px minimum band')+ expect(err).toContain('at most 10 sections')})it('a failed (timed-out) apply ack tells the model the action was NOT applied — fail closed', async () => {@@ -2270,14 +2285,14 @@ describe('v0.32.5 · the P0 regression — recoverable geometry must not kill aexpect(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 () => {+ it('three FLOOR-INFEASIBLE plans stop honestly with the exact math — bounded, never an infinite retry', async () => {const events: AgentEvent[] = []+ // v0.32.8: oversized plans are SCALED, not rejected — a plan only+ // stays infeasible when it cannot fit even at the 56px floor (12+ // sections = 672px of floor + 440px of gaps > the 950px safe area).+ // Three of those still stop the run honestly.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' },- ],+ sections: Array.from({ length: 12 }, (_, i) => ({ name: `s${i + 1}`, y: 65 + i * 100, height: 140, contains: 'x' })),})const { chat } = scriptedChat([turn('plan_layout', infeasible()),@@ -2294,7 +2309,7 @@ describe('v0.32.5 · the P0 regression — recoverable geometry must not kill aemit: (e) => events.push(e),awaitApply: async () => ({ ok: true }),})- expect(result.summary).toContain('infeasible plans')+ expect(result.summary).toContain('rejected plan_layout calls')expect(result.summary).toContain('INCOMPLETE') // guardExit honesty: zero changesexpect(result.toolCalls).toBe(0) // nothing applied after the honest stopconst last = events[events.length - 1]@@ -2385,10 +2400,19 @@ describe('v0.32.5 · deterministic plan solver (plan-repair.ts)', () => {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+ // v0.32.8: a single oversized section is a full-bleed intent, not an+ // infeasible composition — scaled to the usable height (disclosed)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)+ const r1350 = repairPlanBands(inf, 1350)+ expect(r1350.ok).toBe(true)+ if (r1350.ok) {+ expect(r1350.bands[0].y).toBe(81)+ expect(r1350.bands[0].h).toBe(1188)+ expect(r1350.repairs.join(' ')).toContain('scaled')+ }+ const r1920 = repairPlanBands(inf, 1920)+ expect(r1920.ok).toBe(true)+ if (r1920.ok) expect(r1920.bands[0].h).toBe(1690)})it('a VALID plan is accepted unchanged — zero repairs', async () => {@@ -2557,3 +2581,275 @@ describe('v0.32.6 · the canvas map — plans fit the FREE space, never on top',expect(plan?.steps?.join('\n')).toContain('y=365')})})++// ═════════════════════════════════════════════════════════════+// v0.32.8 · the NEON 2027 incident — one brief, three runs, three+// defects, all deterministic:+// run 1: a reasonable 7-section poster plan was INFEASIBLE three+// times → create died with ZERO elements;+// run 2: the in-run vision critique never ran — the capture event+// was never emitted, every run stalled the capture timeout+// and disclosed "UNAVAILABLE"; the audit disclosed a+// fixable residue after ONE round;+// run 3: the "fix issues" follow-up died at 3 strikes — the model+// passed the `text#id` notation it reads everywhere into+// id lists.+// ═════════════════════════════════════════════════════════════++describe('v0.32.8 · oversized plans are SCALED to fit, never a dead end', () => {+ it('the incident shape: 7×140px sections on a 1080 page scale in with disclosure', async () => {+ const { repairPlanBands } = await import('./plan-repair')+ const r = repairPlanBands(+ Array.from({ length: 7 }, (_, i) => ({ name: `sec ${i + 1}`, y: 65 + i * 140, h: 140 })),+ 1080,+ )+ expect(r.ok).toBe(true)+ if (!r.ok) return+ expect(r.bands).toHaveLength(7)+ for (const b of r.bands) {+ expect(b.h).toBeGreaterThanOrEqual(56)+ expect(b.h).toBeLessThanOrEqual(140)+ }+ expect(r.bands[0].y).toBe(65)+ expect(r.bands[6].y + r.bands[6].h).toBeLessThanOrEqual(1015)+ 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)+ }+ expect(r.repairs.join(' ')).toContain('scaled')+ })++ it('a composition that cannot fit even at the floor stays honestly infeasible with the max-sections math', async () => {+ const { repairPlanBands } = await import('./plan-repair')+ const r = repairPlanBands(+ Array.from({ length: 12 }, (_, i) => ({ name: `s${i + 1}`, y: 65 + i * 100, h: 140 })),+ 1080,+ )+ expect(r.ok).toBe(false)+ if (r.ok) return+ expect(r.infeasible).toContain('56px minimum band')+ expect(r.infeasible).toContain('at most 10 sections')+ })++ it('an occupied canvas with too little free space shrinks sections into it before declaring infeasible', async () => {+ const { repairPlanBands } = await import('./plan-repair')+ // free space: a 40px sliver + one 210px interval+ const r = repairPlanBands(+ [+ { name: 'offer', y: 400, h: 120 },+ { name: 'fineprint', y: 700, h: 120 },+ ],+ 1080,+ {+ occupied: [+ { y: 65, h: 300, label: 'COFFEE LAUNCH' },+ { y: 405, h: 400, label: 'Artisan Roast' },+ ],+ },+ )+ expect(r.ok).toBe(true)+ if (!r.ok) return+ for (const b of r.bands) {+ expect(b.y).toBeGreaterThanOrEqual(805)+ expect(b.y + b.h).toBeLessThanOrEqual(1015)+ }+ expect(r.bands[1].y - (r.bands[0].y + r.bands[0].h)).toBeGreaterThanOrEqual(40)+ expect(r.repairs.join(' ')).toContain('scaled to fit the free space')+ })++ it('the loop accepts the scaled plan and BUILDS — the run no longer dies at planRejections', async () => {+ const events: AgentEvent[] = []+ const { chat } = scriptedChat([+ turn('plan_layout', {+ background: '#0A0A1A',+ sections: Array.from({ length: 7 }, (_, i) => ({ name: `section ${i + 1}`, y: 65 + i * 140, height: 140, contains: 'content' })),+ }),+ turn('set_background', { kind: 'solid', from: '#0A0A1A' }),+ turn('add_text', { text: 'NEON 2027', fontSize: 96, color: '#02C0CC' }),+ done('Built the NEON 2027 poster'),+ ])+ const result = await runAgentLoop({+ chat,+ design: compactDesign,+ mode: 'create',+ request: 'Create a professional promotional poster for a futuristic technology festival called NEON 2027',+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ })+ expect(result.toolCalls).toBe(2)+ expect(result.summary).toContain('Built')+ const plan = events.find((e) => e.type === 'plan') as { steps?: string[] } | undefined+ expect(plan?.steps?.length).toBeGreaterThanOrEqual(8) // background + 7 scaled bands+ expect(events[events.length - 1]?.type).toBe('done')+ })+})++describe('v0.32.8 · the capture event is EMITTED — the panel is actually asked', () => {+ it('a run with applied changes emits capture BEFORE the capture call — the never-ran critique regression', async () => {+ const events: AgentEvent[] = []+ const captureCallsAt: number[] = []+ const { chat } = scriptedChat([+ turn('set_background', { kind: 'solid', from: '#090B1A' }),+ done('Poster complete'),+ ])+ 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 }),+ captureCanvas: async () => {+ captureCallsAt.push(events.length)+ return 'data:image/png;base64,AAA'+ },+ critique: async () => ({ findings: [], note: 'clean pass' }),+ })+ // the panel was ASKED (the capture event) before the bridge waited+ const captureIdx = events.findIndex((e) => e.type === 'capture')+ expect(captureIdx).toBeGreaterThanOrEqual(0)+ expect((events[captureIdx] as { purpose?: string }).purpose).toContain('visual critique')+ expect(captureCallsAt).toHaveLength(1)+ expect(captureCallsAt[0]).toBeGreaterThan(captureIdx) // emitted first, waited second+ expect(String(result.verification)).toContain('PASSED')+ })++ it('the timeout path still fails closed (disclosed UNAVAILABLE) — but only after the ask', async () => {+ const events: AgentEvent[] = []+ const { chat } = scriptedChat([+ turn('set_background', { kind: 'solid', from: '#090B1A' }),+ done('Poster complete'),+ ])+ const result = await runAgentLoop({+ chat,+ design,+ mode: 'create',+ request: 'Design a bold Instagram post for a coffee launch',+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ captureCanvas: async () => null,+ critique: async () => ({ findings: [], note: 'never used' }),+ })+ expect(events.some((e) => e.type === 'capture')).toBe(true)+ expect(String(result.verification)).toContain('UNAVAILABLE')+ })+})++describe('v0.32.8 · a SECOND audit fix round — the residue after round one gets one more pass', () => {+ it('round 1 clears 3 issues, round 2 clears the straggler, done is accepted clean', async () => {+ const events: AgentEvent[] = []+ let auditCalls = 0+ 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', fontSize: 40, color: '#111122' }),+ done('Done attempt 1'),+ turn('add_text', { text: 'Fix 1', fontSize: 40, color: '#FFFFFF' }),+ done('Done attempt 2'),+ turn('add_text', { text: 'Fix 2', fontSize: 40, color: '#FFFFFF' }),+ done('Done attempt 3 — residue gone'),+ ])+ const result = await runAgentLoop({+ chat,+ design: compactDesign,+ mode: 'create',+ request: 'Design a bold Instagram post for a coffee launch',+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ auditDesign: async () => {+ auditCalls += 1+ return auditCalls <= 2+ ? ['Low contrast: text "Dark" #111122 on #090B1A is 1.0:1 (needs 3:1) — change the text fill.']+ : []+ },+ })+ expect(auditCalls).toBe(3)+ expect(result.toolCalls).toBe(4)+ expect(events.filter((e) => e.type === 'observation' && e.message.includes('QUALITY AUDIT')).length).toBe(2)+ const finalEvent = events[events.length - 1] as { verification?: string }+ expect(String(finalEvent.verification)).toContain('Quality audit passed')+ })++ it('after the second round the residue is disclosed — bounded, never a loop', async () => {+ 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', fontSize: 40, color: '#111122' }),+ done('Done 1'),+ done('Done 2'),+ done('Done 3'),+ ])+ const result = await runAgentLoop({+ chat,+ design: compactDesign,+ mode: 'create',+ request: 'Design a bold Instagram post for a coffee launch',+ emit: () => {},+ awaitApply: async () => ({ ok: true }),+ auditDesign: async () => ['Low contrast: text "Dark" #111122 on #090B1A is 1.0:1 (needs 3:1)'],+ })+ expect(result.toolCalls).toBe(2)+ expect(String(result.verification)).toContain('after the fix rounds — disclosed')+ })+})++describe('v0.32.8 · the `type#id` alias — the "fix issues" strike-out', () => {+ it('id lists accept the notation the context, findings and overlaps print everywhere', () => {+ const update = AGENT_TOOL_MAP.get('update_elements')+ expect(update).toBeTruthy()+ const r = update!.sanitize({ ids: ['text#txt-1', 'rect#el-1', 'txt-2'], patch: { fill: '#FFFFFF' } }, ctx)+ expect(r.ok).toBe(true)+ if (r.ok) {+ expect((r.actions[0] as { ids?: string[] }).ids).toEqual(['txt-1', 'el-1', 'txt-2'])+ }+ const move = AGENT_TOOL_MAP.get('move_elements')+ expect(move).toBeTruthy()+ const m = move!.sanitize({ ids: ['text#nope-xyz'], dx: 10 }, ctx)+ expect(m.ok).toBe(false) // an unknown bare id is still an honest error+ })++ it('the edit-mode flow: a "fix issues" run patches by text#id without striking', async () => {+ const events: AgentEvent[] = []+ const { chat } = scriptedChat([+ turn('update_elements', { ids: ['text#txt-1'], patch: { fill: '#FFFFFF' } }),+ done('Fixed the contrast issue'),+ ])+ const result = await runAgentLoop({+ chat,+ design: compactDesign,+ mode: 'edit',+ request: 'fix issues',+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ })+ expect(result.toolCalls).toBe(1)+ expect(events.some((e) => e.type === 'error')).toBe(false)+ expect(events[events.length - 1]?.type).toBe('done')+ })+})++describe('v0.32.8 · the second-strike recovery note (the "fix issues" strike-out)', () => {+ it('the second consecutive rejection carries the get_page_state note BEFORE the run can die', async () => {+ const events: AgentEvent[] = []+ const bad = turn('update_elements', { ids: ['txt-1'], patch: { font: 'Inter' } })+ const { chat, calls } = scriptedChat([+ turn('set_background', { kind: 'solid', from: '#090B1A' }),+ bad,+ bad,+ turn('update_elements', { ids: ['txt-1'], patch: { fill: '#FFFFFF' } }),+ done('Fixed'),+ ])+ const result = await runAgentLoop({+ chat,+ design: compactDesign,+ mode: 'edit',+ request: 'fix issues',+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ })+ // the two rejects never struck the run dead; the recovery note rode+ // the SECOND error observation (one strike from the end)+ expect(calls.some((cs) => cs.some((m) => m.content.includes('second failed call in a row')))).toBe(true)+ expect(result.toolCalls).toBe(2)+ expect(events[events.length - 1]?.type).toBe('done')+ })+})diff --git a/src/lib/agent/loop.ts b/src/lib/agent/loop.tsindex 25a73d8..05db7f8 100644--- a/src/lib/agent/loop.ts+++ b/src/lib/agent/loop.ts@@ -44,6 +44,7 @@ export function telemetry(event: Record<string, unknown>): void {}}import { AGENT_TOOLS, AGENT_TOOL_MAP, fontFamilies, type ToolContext, type SanitizeResult, type AgentTool } from './tools'+import { PLAN_MIN_BAND, PLAN_MIN_GAP } from './plan-repair'import { serializeDesignContext, contextValidIds, canvasMap, type AgentDesignCtx } from './context'import { MODE_PROMPTS, MODE_TOOL_RISK } from './router'import { skillsPromptSection, selectSkills, type DesignSkill } from './skills'@@ -192,8 +193,17 @@ export function loopSystemPrompt(deps: {}if (mode === 'create' || mode === 'improve') {+ // v0.32.8: the computed budget for THIS page — plan inside it from+ // the start. Oversized plans are auto-scaled down to fit and the+ // scaling disclosed (plan-repair.ts), but a realistic plan+ // composes better than a scaled-down one.+ const safeTopY = Math.round(H * margin)+ const safeBottomY = Math.round(H * (1 - margin))+ const usableH = safeBottomY - safeTopY+ const maxSections = Math.floor((usableH + PLAN_MIN_GAP) / (PLAN_MIN_BAND + PLAN_MIN_GAP))lines.push('LAYOUT PLANNING (required first step):',+ `· This page fits at most ${maxSections} planned sections (safe area y ${safeTopY}–${safeBottomY}px, ${usableH}px tall: sections ≥${PLAN_MIN_BAND}px with ≥${PLAN_MIN_GAP}px gaps; oversized plans are auto-scaled to fit and the scaling disclosed).`,'· Call plan_layout FIRST with your composition: page background, sections with y-ranges, what each contains (headline band, tagline, feature cards row, mockup, CTA, footer).','· Reserve a vertical band per section with ≥40px gaps so nothing stacks or crowds; the brief texts each get their section. Invalid plans (gaps under 40px, bands beyond the page) are REJECTED with the exact numbers — fix the bands and resend.','· Set the page background EARLY with set_background (a required background color belongs there, not in strips).',@@ -294,7 +304,10 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {let lastProgressAt = startedlet lastUsageAt = startedlet briefValidated = false- /** v0.29: quality-audit fix rounds already used (max 1 per run) */+ /** v0.29: quality-audit fix rounds already used (v0.32.8: max+ * AGENT_GUARDS.auditFixRounds — the NEON 2027 run cleared 3 of 4+ * issues in round one and disclosed the straggler; one more+ * bounded pass clears it) */let auditRounds = 0/** v0.29.3: grounded vision passes already run (max 2 — initial* critique + verification after the correction round) */@@ -554,8 +567,11 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {}// QUALITY AUDIT (v0.29): self-critique before the run is// accepted — local heuristics only, no extra model calls.- // Exactly ONE fix round: done is then accepted with the residue- // DISCLOSED (audit → fix → re-audit → honest outcome), never looped.+ // BOUNDED fix rounds (v0.32.8: AGENT_GUARDS.auditFixRounds — the+ // NEON 2027 run cleared 3 of 4 issues in round one and disclosed+ // the straggler; one more bounded pass clears it): done is then+ // accepted with the residue DISCLOSED (audit → fix → re-audit →+ // honest outcome), never looped.if ((mode === 'create' || mode === 'improve') && deps.auditDesign) {let issues: string[] = []try {@@ -563,7 +579,7 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {} catch {/* audit is best-effort — never block completion on it */}- if (issues.length && auditRounds === 0) {+ if (issues.length && auditRounds < AGENT_GUARDS.auditFixRounds) {auditRounds += 1const list = issues.map((i) => `· ${i}`).join('\n')emit({@@ -584,8 +600,8 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {: 'Quality audit passed: contrast, spacing and bounds clean.'} else if (auditRounds > 0) {verification = verification- ? `${verification} Quality audit still reports ${issues.length} issue(s) after the fix round — disclosed, not blocking.`- : `Quality audit still reports ${issues.length} issue(s) after the fix round — disclosed, not blocking.`+ ? `${verification} Quality audit still reports ${issues.length} issue(s) after the fix rounds — disclosed, not blocking.`+ : `Quality audit still reports ${issues.length} issue(s) after the fix rounds — disclosed, not blocking.`}}@@ -600,6 +616,14 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {// 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) {+ // v0.32.8 · ASK before waiting. The capture event has been in+ // the protocol (and handled by the panel) since v0.29.3, but+ // nothing ever EMITTED it — every create/improve run stalled+ // the full capture timeout and disclosed "canvas capture+ // timed out or no client" (the in-run vision critique never+ // actually ran once). The panel captures the live canvas and+ // answers on the bridge.+ emit({ v: AGENT_PROTOCOL_VERSION, type: 'capture', purpose: 'pre-completion visual critique' })const shot = deps.captureCanvas ? await deps.captureCanvas() : nullif (!shot) {// fail-closed: no capture → visual quality is NOT verified,@@ -811,15 +835,23 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {// · 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.+ // · what still rejects (malformed sections, or a composition+ // that cannot fit even at the 56px floor now that oversized+ // plans are scaled in) 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 += 1telemetry({ 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')+ // v0.32.8: with the solver scaling oversized plans, a+ // rejection means a MALFORMED section or a floor-infeasible+ // composition — the message points at the fixable cause,+ // never at the user's brief.+ const exit = await guardExitWithTelemetry(+ `Stopped after ${planRejections} rejected plan_layout calls — each error above names what to fix (a missing section name, non-numeric y/height, or a composition that cannot fit even at the ${PLAN_MIN_BAND}px minimum band). Resend ONE valid plan_layout: numeric y and height per named section, at most ${Math.floor((toolCtx.height * 0.88 + PLAN_MIN_GAP) / (PLAN_MIN_BAND + PLAN_MIN_GAP))} sections on this page.`,+ '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 }}@@ -828,7 +860,19 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {}// free correction: rejected calls cost only a strikestrikes += 1- messages.push({ role: 'user', content: observationFor(toolName, result, false) })+ // v0.32.8: the "fix issues" follow-up died at three strikes in+ // edit mode. One strike from the end, the error observation+ // carries the recovery move explicitly — refresh state, then+ // retry to spec — instead of hoping the model infers it three+ // times in a row.+ messages.push({+ role: 'user',+ content:+ observationFor(toolName, result, false) ++ (strikes === AGENT_GUARDS.strikes - 1+ ? ' NOTE: this is the second failed call in a row — the NEXT failure ends the run. Call get_page_state now to refresh the element ids, then retry with args that match the tool spec exactly.'+ : ''),+ })continue}diff --git a/src/lib/agent/plan-repair.ts b/src/lib/agent/plan-repair.tsindex dc2f8ab..4832ca5 100644--- a/src/lib/agent/plan-repair.ts+++ b/src/lib/agent/plan-repair.ts@@ -12,12 +12,24 @@* 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.+ * fabrication: order and contents are the model's own; only the+ * y-positions, the gaps and (since v0.32.8) the scaling of+ * oversized heights are computed.** repairPlanBands(sections, H) →- * { ok: true, bands, repairs, gap } valid or repaired- * { ok: false, infeasible } cannot fit — exact math+ * { ok: true, bands, repairs, gap } valid, repaired or scaled+ * { ok: false, infeasible } cannot fit even at the+ * 56px floor — exact math+ *+ * v0.32.8 · the NEON 2027 incident: a reasonable 7-section poster+ * plan exceeded the safe area, the model could not redo the height+ * arithmetic in three attempts, and the run died with ZERO elements+ * ("ask the user for a smaller composition"). Heights are the+ * SERVER's job now too: an oversized plan is uniformly SCALED to+ * fit (each band floored at PLAN_MIN_BAND, the model's relative+ * hierarchy preserved) and the scaling is DISCLOSED in repairs.+ * Infeasible survives only for compositions that cannot fit even at+ * the floor — the honest stop nobody can scale their way out of.*/export interface PlanSection {@@ -60,6 +72,11 @@ export type PlanRepairResult = PlanRepairOk | PlanRepairInfeasibleexport const PLAN_MIN_GAP = 40export const PLAN_MARGIN = 0.06+/** v0.32.8 · the smallest band the solver will ever produce. Below+ * this a section cannot hold readable content (a real headline needs+ * ≥40px; the audit flags body text under 14px) — the only plans that+ * stay infeasible are the ones that cannot fit even at this floor. */+export const PLAN_MIN_BAND = 56/** Merge raw occupied extents into disjoint bands. Two occupied* extents closer than minGap merge: the sliver between them cannot@@ -111,18 +128,23 @@ function mapEntry(b: { y: number; h: number; label?: string }): string {* 0. OCCUPIED CANVAS (v0.32.6): when existing elements are present* they are the map — the sections are fitted into the FREE* intervals between them (order preserved, ≥minGap gaps), never- * on top of anything. Sections that cannot fit anywhere produce- * an INFEASIBLE result carrying the full occupancy map with the- * exact numbers.+ * on top of anything. Sections that cannot fit anywhere shrink+ * proportionally first (v0.32.8); only a layout that cannot fit+ * even at the PLAN_MIN_BAND floor produces an INFEASIBLE result+ * carrying the full occupancy map with the exact numbers.* 1. A plan whose bands already tile the safe area top-to-bottom* with ≥minGap gaps is accepted UNCHANGED (repairs = []).* 2. Otherwise the sections are re-laid out from the top of the* 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).+ * 3. OVERSIZED PLANS ARE SCALED, NOT REJECTED (v0.32.8): content+ * taller than the safe area minus its gaps is uniformly scaled+ * down to fit (each band floored at PLAN_MIN_BAND, relative+ * heights kept, the scaling DISCLOSED) — the model never re-does+ * height arithmetic. Only compositions that cannot fit even at+ * the floor are infeasible, with the exact math and the maximum+ * section count that DOES fit.*/export function repairPlanBands(requested: PlanSection[],@@ -154,11 +176,11 @@ export function repairPlanBands(const freeLine = free.length ? free.map(mapEntry).join(', ') : 'nothing'// prefer ONE free interval that fits everything (natural spread)const fitsAll = free.filter((f) => f.h >= sumH + minGap * (n - 1))- const bands: RepairedBand[] = []- const repairs: string[] = []if (fitsAll.length) {const f = fitsAll[0]const gap = n > 1 ? Math.max(minGap, Math.floor((f.h - sumH) / (n - 1))) : minGap+ const bands: RepairedBand[] = []+ const repairs: string[] = []let y = f.yfor (const s of sections) {bands.push({ name: s.name, y, h: s.h })@@ -169,67 +191,114 @@ export function repairPlanBands(return { ok: true, bands, gap, repairs }}// no single interval fits all: first-fit across intervals in- // order (still ≥minGap inside an interval, order preserved)- let fi = 0- let y = free.length ? free[0].y : safeTop- let intervalEnd = free.length ? free[0].y + free[0].h : safeTop- for (const s of sections) {- // advance to an interval with room for this section- while (fi < free.length && y + s.h > intervalEnd) {- fi += 1- if (fi < free.length) {- y = free[fi].y- intervalEnd = free[fi].y + free[fi].h- } else break- }- if (y + s.h > intervalEnd) {- return {- ok: false,- infeasible:- `Infeasible plan on an occupied canvas: existing elements occupy ${mapLine}; ` +- `free space: ${freeLine}. Your ${n} sections (${sumH}px of content) do not fit the free space ` +- `(the largest free interval is ${free.length ? Math.max(...free.map((f) => f.h)) : 0}px). ` +- `Move or clear existing elements first, or plan fewer/smaller sections.`,+ // order (still ≥minGap inside an interval, order preserved).+ // v0.32.8: a first-fit failure is not immediately infeasible —+ // the sections shrink proportionally (floored at PLAN_MIN_BAND,+ // up to 20 passes of ×0.88) until they fit the free space. Only+ // a layout that cannot fit even at the floor is infeasible.+ const firstFit = (secs: PlanSection[]): RepairedBand[] | null => {+ const out: RepairedBand[] = []+ let fi = 0+ let y = free.length ? free[0].y : safeTop+ let intervalEnd = free.length ? free[0].y + free[0].h : safeTop+ for (const s of secs) {+ // advance to an interval with room for this section+ while (fi < free.length && y + s.h > intervalEnd) {+ fi += 1+ if (fi < free.length) {+ y = free[fi].y+ intervalEnd = free[fi].y + free[fi].h+ } else break}+ if (y + s.h > intervalEnd) return null+ out.push({ name: s.name, y, h: s.h })+ y += s.h + minGap}- bands.push({ name: s.name, y, h: s.h })- if (s.y !== y) repairs.push(`"${s.name}" y ${Math.round(s.y)}→${y}`)- y += s.h + minGap+ return out+ }+ let attempt = sections+ let fit = firstFit(attempt)+ for (let pass = 0; !fit && pass < 20; pass++) {+ const shrunk = attempt.map((s) => ({ ...s, h: Math.max(PLAN_MIN_BAND, Math.floor(s.h * 0.88)) }))+ if (shrunk.every((s, i) => s.h === attempt[i].h)) break // already at the floor+ attempt = shrunk+ fit = firstFit(attempt)}- return { ok: true, bands, gap: minGap, repairs }+ if (!fit) {+ return {+ ok: false,+ infeasible:+ `Infeasible plan on an occupied canvas: existing elements occupy ${mapLine}; ` ++ `free space: ${freeLine}. Your ${n} sections (${sumH}px of content) do not fit the free space ` ++ `(the largest free interval is ${free.length ? Math.max(...free.map((f) => f.h)) : 0}px) even scaled to the ${PLAN_MIN_BAND}px minimum band. ` ++ `Move or clear existing elements first, or plan fewer sections.`,+ }+ }+ const repairs: string[] = []+ fit.forEach((b, i) => {+ if (sections[i].y !== b.y) repairs.push(`"${b.name}" y ${Math.round(sections[i].y)}→${b.y}`)+ if (sections[i].h !== b.h) repairs.push(`"${b.name}" h ${sections[i].h}→${b.h} (scaled to fit the free space)`)+ })+ return { ok: true, bands: fit, gap: minGap, repairs }}- 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 3 · v0.32.8 · oversized plans are SCALED to fit ─────+ const budget = usable - minGap * (n - 1)+ let scaled = false+ let eff = sections+ const repairs: string[] = []+ if (sumH > budget) {+ const scale = budget / sumH+ const scaledSections = sections.map((s) => ({+ name: s.name,+ y: s.y,+ h: Math.max(PLAN_MIN_BAND, Math.round(s.h * scale)),+ }))+ const sumScaled = scaledSections.reduce((acc, s) => acc + s.h, 0)+ if (sumScaled > budget) {+ const floorSum = sections.reduce((acc, s) => acc + Math.min(s.h, PLAN_MIN_BAND), 0)+ const maxSections = Math.floor((usable + minGap) / (PLAN_MIN_BAND + minGap))+ return {+ ok: false,+ infeasible:+ `Infeasible plan: ${n} sections at the ${PLAN_MIN_BAND}px minimum band (${floorSum}px) plus ${minGap}px gaps ` ++ `(≥ ${floorSum + minGap * (n - 1)}px) cannot fit the ${usable}px safe area (page ${H}px, 6% margins top/bottom ` ++ `${safeTop}px, ${H - safeBottom}px) — at most ${maxSections} sections fit this page. Drop sections; scaling cannot rescue this composition.`,+ }}+ scaled = true+ eff = scaledSections+ repairs.push(+ `section heights scaled ×${scale.toFixed(2)} to fit the ${usable}px safe area (${sumH}px → ${sumScaled}px, floors at ${PLAN_MIN_BAND}px)`,+ )+ sections.forEach((s, i) => {+ if (s.h !== eff[i].h) repairs.push(`"${s.name}" h ${s.h}→${eff[i].h}`)+ })}- // 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 1 — already valid (and never scaled)? Keep the model's exact geometry.+ if (!scaled) {+ 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+ // Rule 2 — deterministic re-layout: (possibly scaled) heights,+ // uniform gap (minGap, or the natural spread when there is room).+ const sumEff = eff.reduce((acc, s) => acc + s.h, 0)+ const gap = n > 1 ? Math.max(minGap, Math.floor((usable - sumEff) / (n - 1))) : minGapconst bands: RepairedBand[] = []- const repairs: string[] = []let y = safeTop- for (const s of sections) {+ for (const s of eff) {bands.push({ name: s.name, y, h: s.h })if (s.y !== y) {repairs.push(`"${s.name}" y ${Math.round(s.y)}→${y}`)@@ -241,17 +310,10 @@ export function repairPlanBands(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+ // unreachable for n ≥ 1 with the scaled content ≤ budget — kept+ // for honesty: the solver must never claim a fit it cannot prove.return {ok: false,- infeasible: `Infeasible plan: the sections (${sumH}px + gaps) cannot fit the ${usable}px safe area.`,+ infeasible: `Infeasible plan: the sections (${sumEff}px + gaps) cannot fit the ${usable}px safe area.`,}}diff --git a/src/lib/agent/protocol.ts b/src/lib/agent/protocol.tsindex bd579fe..89e6072 100644--- a/src/lib/agent/protocol.ts+++ b/src/lib/agent/protocol.ts@@ -58,8 +58,16 @@ export const AGENT_GUARDS = {/** 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) */+ * failures, but a run may not retry them forever). v0.32.8: with+ * the solver scaling oversized plans, rejection means a malformed+ * section or a composition that cannot fit even at the 56px floor+ * — still bounded, still honest */planRejections: 3,+ /** v0.32.8: quality-audit fix rounds before the residue is+ * disclosed as unfixable-by-this-run (bounded — never a loop).+ * The NEON 2027 run cleared 3 of 4 audit issues in round one and+ * disclosed the straggler; one more bounded pass clears it */+ auditFixRounds: 2,} 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.tsindex 276fd87..82663cc 100644--- a/src/lib/agent/tools.ts+++ b/src/lib/agent/tools.ts@@ -91,8 +91,20 @@ function idList(args: Record<string, unknown>, ctx: ToolContext, key = 'ids'): {const ids: string[] = []const invalid: string[] = []for (const v of raw.slice(0, 60)) {- if (typeof v === 'string' && ctx.validIds.has(v)) ids.push(v)- else if (typeof v === 'string') invalid.push(v)+ if (typeof v !== 'string') continue+ if (ctx.validIds.has(v)) {+ ids.push(v)+ continue+ }+ // v0.32.8 · the `type#id` alias. The serialized context, the audit+ // findings and the overlap reports all print ids as `text#abc123`;+ // an edit run that copies that notation verbatim was rejected+ // three times in a row and died at STRIKES (the "fix issues"+ // incident). Strip the prefix and accept the bare id — the same+ // alias discipline as the color/fontColor/textColor patch aliases.+ const bare = v.includes('#') ? v.slice(v.indexOf('#') + 1) : ''+ if (bare && ctx.validIds.has(bare)) ids.push(bare)+ else invalid.push(v)}if (ids.length === 0) {return {