Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
feat(v0.34.2): AUTO-DELETE (optional) + the plan that never dies + the Stop button that stops
Ashiq Hussain Mir927ba0b6c018
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cef7b49..3cfd9a1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,7 +3,53 @@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/).-<<<<<<< HEAD+### feat(v0.34.2): AUTO-DELETE (optional), the plan that never dies, the Stop button that finally stops++Two production reports from the same day, three fixes at the cause:++- **AUTO-DELETE (optional, default OFF).** A toggle in the Canvix AI+ composer pre-approves the destructive tools (`delete_elements`,+ `clear_page`, `delete_page`) for the whole run: no approval dialog,+ server-side `awaitConfirm` skipped via `body.confirmed` — and a+ mid-run flip auto-answers any gate that still asks. Off by default,+ persisted per browser; Undo agent work and version history remain+ the safety net. Fixes along the way: the SECOND destructive call of+ an approved tool used to wait 120s on the server for a confirmation+ the client never showed, time out as "declined" — while the client+ had already applied it (a divergence); every auto/applied+ destructive the server was not pre-told about now answers its+ confirm explicitly.+- **THE PLAN THAT NEVER DIES (the Kashmir incident).** A premium+ travel-ad brief ended at "3 steps · 0 actions — stopped after 3+ rejected plan_layout calls": missing section names, non-numeric+ y/height, more sections than the page can host. The v0.32.4 lesson+ (never make the model redo geometry) now covers ARGUMENTS too —+ names are labels and y is an ordering hint, so both are SYNTHESIZED+ and disclosed (a bare string entry becomes a name); floor-infeasible+ compositions are TRUNCATED to the first fitting prefix by the new+ `solvePlanBandsTruncating` wrapper (order kept, drop disclosed).+ plan_layout now rejects only when the sections are unusable at all+ or the canvas is genuinely full — the bounded rejection budget+ stays as the honest stop.+- **THE STOP BUTTON.** The client-side abort worked mid-stream; three+ server/client dead-ends did not: (1) the post-run vision critique+ rode its own unabortable fetch — Stop during it did nothing and the+ panel stayed busy forever; it now rides the run's AbortSignal.+ (2) An abort left every pending bridge waiter (confirm/ack/brief/+ capture) dangling up to 45–120s before the loop noticed; the abort+ listener now releases them all at once, and the bridge promises+ never register on a stopped run. (3) An aborted run persisted as+ `running` forever (excluded from the ledger AND recovery); it now+ persists and finalizes as `stopped` — recovery never resumes a+ deliberate stop.++Tests: the truncation contract replaces the old reject pin; +4 unit+regressions (arg synthesis, the Kashmir loop run that now builds, the+genuinely-full honest stop, stop-persist); +3 e2e (mocked SSE): the+approval gate default, auto-delete without asking (incl. body.confirmed),+Stop releasing a hanging critique. 1,850/1,850 unit; CHANGELOG's+leftover `<<<<<<< HEAD` merge markers from PR #95 resolved.+### Fixed — v0.33.1: the live-repro convergence — the focal-size default and the unmet-message mathThe v0.33.0 live reproduction (49 steps · 36 actions, brief validated@@ -156,7 +202,7 @@ second audit round, the id alias, the recovery note) — 1,759/1,759.identity and the byte-identical domain copy; e2e smoke + the CI dockerjob assert both routes serve the exact bytes. Unit 1,748/1,748 (+3);e2e smoke +1 spec.-=======+### Changed — v0.32.7: spatial intelligence, intent, persistence, resilience- **2D spatial map** (spatial.ts): rotation-aware AABBs, z-order,@@ -204,7 +250,6 @@ second audit round, the id alias, the recovery note) — 1,759/1,759.state (empty → create, populated → edit) whenever the model routerfails or answers garbage. +5 regressions from the live JNV Baramulaposter session (26 Nov 2026).->>>>>>> pr-95### Changed — v0.32.6: ONE agent, ZERO selectors + the canvas mapdiff --git a/src/app/api/ai/agent/route.ts b/src/app/api/ai/agent/route.tsindex a168c7a..9cce8ff 100644--- a/src/app/api/ai/agent/route.ts+++ b/src/app/api/ai/agent/route.ts@@ -413,6 +413,10 @@ async function __canvix_post(req: NextRequest) {const stream = new ReadableStream<Uint8Array>({async start(controller) {let closed = false+ // v0.34.2: set by the abort listener below — the finally uses+ // it so a user-stopped run finalizes as 'stopped' (never+ // 'interrupted': recovery must not resume a deliberate stop)+ let clientAborted = falseconst emit = (event: AgentEvent) => {if (closed) returntry {@@ -425,6 +429,24 @@ async function __canvix_post(req: NextRequest) {req.signal.addEventListener('abort', () => {const bridge = bridges.get(runId)if (bridge) bridge.aborted = true+ clientAborted = true+ // v0.34.2 · THE STOP BUTTON FIX, server side: release EVERY+ // pending bridge waiter at once. The old flow left them+ // dangling — a run stopped during a confirm/apply/capture+ // window kept waiting up to its 45–120s timeouts before the+ // loop noticed the abort at its next between-step check.+ // Now the loop wakes within milliseconds.+ for (const resolve of bridge?.confirms.values() ?? []) resolve(false)+ bridge?.confirms.clear()+ for (const ack of bridge?.acks.splice(0) ?? []) ack({ ok: false, message: 'the run was stopped' })+ if (bridge?.briefResult) {+ bridge.briefResult(null)+ bridge.briefResult = null+ }+ if (bridge?.capture) {+ bridge.capture(null)+ bridge.capture = null+ }})try {@@ -603,6 +625,11 @@ async function __canvix_post(req: NextRequest) {},awaitConfirm: (tool) =>new Promise<boolean>((resolve) => {+ // v0.34.2: a stopped run never waits on the client+ if (bridge.aborted || req.signal.aborted) {+ resolve(false)+ return+ }bridge.confirms.set(tool, resolve)// safety: never hang forever on a silent clientsetTimeout(() => {@@ -614,6 +641,11 @@ async function __canvix_post(req: NextRequest) {}),awaitApply: () =>new Promise<{ ok: boolean; message?: string }>((resolve) => {+ // v0.34.2: a stopped run never waits on the client+ if (bridge.aborted || req.signal.aborted) {+ resolve({ ok: false, message: 'the run was stopped — the document was not verified as changed' })+ return+ }bridge.acks.push((ack) => resolve({ ok: ack.ok, message: ack.message }))// v0.29.3 — FAIL CLOSED: a timed-out apply ack now// resolves ok:false. The old "ack timeout — assumed@@ -634,6 +666,11 @@ async function __canvix_post(req: NextRequest) {// visual verification was unavailable (never pretends).captureCanvas: () =>new Promise<string | null>((resolve) => {+ // v0.34.2: a stopped run never waits on the client+ if (bridge.aborted || req.signal.aborted) {+ resolve(null)+ return+ }bridge.capture = (r) => resolve(r?.image ?? null)setTimeout(() => {if (bridge.capture) {@@ -663,6 +700,8 @@ async function __canvix_post(req: NextRequest) {bridge.pendingBriefResult = nullreturn r}+ // v0.34.2: a stopped run never waits on the client+ if (bridge.aborted || req.signal.aborted) return nullreturn new Promise<{ satisfied: boolean; unmet: string[] } | null>((resolve) => {bridge.briefResult = resolve// the client answers on the bridge; give it a generous@@ -701,6 +740,11 @@ async function __canvix_post(req: NextRequest) {if (design.designId) {try {const interrupted = loopResult === null+ // v0.34.2: a client-aborted run finalizes as STOPPED+ // even when the loop threw after the abort (emit to a+ // closed stream) — 'interrupted' would make recovery+ // resume a deliberate stop+ const finalStatus = clientAborted ? 'stopped' : interrupted ? 'interrupted' : undefinedif (runRowId) {await db.designAgentRun.update({where: { id: runRowId },@@ -712,7 +756,7 @@ async function __canvix_post(req: NextRequest) {.map((f) => `${f.severity} ${f.issue}`).join(' | ').slice(0, 1200) || null,- ...(interrupted ? { status: 'interrupted' } : {}),+ ...(finalStatus ? { status: finalStatus } : {}),},})} else {diff --git a/src/components/editor/apps/AssistantApp.tsx b/src/components/editor/apps/AssistantApp.tsxindex 3d4f14f..8e5c5fa 100644--- a/src/components/editor/apps/AssistantApp.tsx+++ b/src/components/editor/apps/AssistantApp.tsx@@ -346,7 +346,32 @@ export function AssistantApp({ onClose }: AppPanelProps) {const abortRef = useRef<AbortController | null>(null)const runIdRef = useRef<string | null>(null)const confirmedRef = useRef<Set<string>>(new Set())+ /** the tools the SERVER got in this run's body.confirmed (pre-approved) */+ const serverConfirmedRef = useRef<Set<string>>(new Set())const briefRef = useRef<DesignBrief | null>(null)+ // v0.34.2 · AUTO-DELETE (optional, default OFF): the user may let the+ // agent run the destructive tools (delete_elements / clear_page /+ // delete_page) WITHOUT the per-call approval gate. Pre-approved for+ // the whole run when on at send time; a mid-run flip auto-approves+ // the calls that still ask. Persisted per browser.+ const DESTRUCTIVE_TOOLS = ['delete_elements', 'clear_page', 'delete_page'] as const+ const [autoDelete, setAutoDelete] = useState(() => {+ if (typeof window === 'undefined') return false+ try {+ return window.localStorage.getItem('canvix-agent-autodelete') === '1'+ } catch {+ return false+ }+ })+ const autoDeleteRef = useRef(autoDelete)+ useEffect(() => {+ autoDeleteRef.current = autoDelete+ try {+ window.localStorage.setItem('canvix-agent-autodelete', autoDelete ? '1' : '0')+ } catch {+ /* private mode — the toggle just won't persist */+ }+ }, [autoDelete])const { configured: aiConfigured, loaded: aiLoaded } = useAICapabilities()const canUndo = useEditorStore((s) => s.past.length > 0)@@ -414,7 +439,7 @@ export function AssistantApp({ onClose }: AppPanelProps) {/** Phase 7: visual critique of the current canvas (honest about* availability). Appends findings to the finished turn. */- const visionCritique = useCallback(async (brief: DesignBrief | null): Promise<{ findings: Finding[]; note: string } | null> => {+ const visionCritique = useCallback(async (brief: DesignBrief | null, signal?: AbortSignal): Promise<{ findings: Finding[]; note: string } | null> => {let dataUrl = ''try {const { captureStage } = await import('@/components/editor/canvas/canvas-bridge')@@ -427,6 +452,10 @@ export function AssistantApp({ onClose }: AppPanelProps) {const res = await fetch('/api/ai/agent/vision', {method: 'POST',headers: { 'Content-Type': 'application/json' },+ // v0.34.2: the critique is abortable — Stop during the+ // post-run pass used to do nothing (the button only aborted+ // the already-finished agent stream)+ signal,body: JSON.stringify({image: dataUrl,brief: brief@@ -459,6 +488,18 @@ export function AssistantApp({ onClose }: AppPanelProps) {setLiveBrief(null)setLiveUsage(null)confirmedRef.current = new Set()+ // v0.34.2 · AUTO-DELETE pre-approval: with the toggle on, the+ // destructive tools enter the run pre-confirmed — the server skips+ // awaitConfirm (body.confirmed) and the client applies without the+ // dialog. "Undo agent work" and version history remain the safety+ // net behind every delete.+ if (autoDeleteRef.current) {+ for (const t of DESTRUCTIVE_TOOLS) confirmedRef.current.add(t)+ }+ // what the SERVER knows as pre-approved this run (body.confirmed)+ // — the action handler answers a confirm only for tools NOT in+ // this set (the server gates every destructive it was not told about)+ serverConfirmedRef.current = new Set(confirmedRef.current)// v0.32.6: NO mode selector — the agent classifies every message// itself and does everything by itself (create, edit, review,@@ -592,10 +633,24 @@ export function AssistantApp({ onClose }: AppPanelProps) {return}if (event.risk === 'destructive') {- if (confirmedRef.current.has(event.tool)) {- // user already approved this tool this run+ // v0.34.2 · who may apply without the dialog:+ // · the tool was pre-approved server-side (body.confirmed+ // — an approve-once from earlier, or AUTO-DELETE at send)+ // · AUTO-DELETE flipped on mid-run (the server still asks;+ // the answer below releases it)+ // Any destructive the SERVER did not get in body.confirmed+ // gets its confirm answered explicitly — the old flow let+ // the second clear_page of a run wait on a dialog that was+ // never shown and time out as "declined" while the client+ // had already applied it.+ const serverApproved = serverConfirmedRef.current.has(event.tool)+ if (serverApproved || confirmedRef.current.has(event.tool) || autoDeleteRef.current) {const ack = await applyActions(actions)if (ack.ok) appliedCount += actions.length+ if (!serverApproved) {+ confirmedRef.current.add(event.tool)+ await bridgePost({ confirm: { tool: event.tool, ok: true } })+ }await bridgePost({ ack: { ok: ack.ok, message: ack.message, design: buildDesignContext() } })} else {// pause for the user — the route's awaitConfirm waits@@ -648,7 +703,7 @@ export function AssistantApp({ onClose }: AppPanelProps) {// was created", not a critique of a blank page.let critiqueNote: string | undefinedif ((mode === 'create' || mode === 'improve') && summary && appliedCount > 0 && !controller.signal.aborted) {- const critique = await visionCritique(runBrief ?? briefRef.current)+ const critique = await visionCritique(runBrief ?? briefRef.current, controller.signal)if (critique) {critiqueNote = critique.noteif (critique.findings.length) {@@ -976,8 +1031,31 @@ export function AssistantApp({ onClose }: AppPanelProps) {</button></div><div className="flex items-center justify-between mt-1.5 text-[10px] text-white/30">- <span>One agent — it maps the canvas, plans the geometry, builds, checks and verifies by itself</span>- {canUndo && <span>Undo available in the toolbar</span>}+ <div className="flex items-center gap-2 min-w-0">+ {/* v0.34.2 · AUTO-DELETE: optional pre-approval of the destructive tools */}+ <button+ type="button"+ role="switch"+ aria-checked={autoDelete}+ onClick={() => setAutoDelete((v) => !v)}+ title="When on, the agent may delete elements and pages without asking for approval each time. Off by default. Undo agent work and version history remain the safety net."+ data-testid="agent-autodelete"+ className={`flex items-center gap-1.5 px-2 h-5 rounded-full border transition-colors shrink-0 ${+ autoDelete+ ? 'bg-red-500/20 border-red-400/40 text-red-200'+ : 'border-white/10 text-white/40 hover:text-white/70'+ }`}+ >+ <span+ className={`w-3.5 h-2 rounded-full transition-colors ${autoDelete ? 'bg-red-400/80' : 'bg-white/15'}`}+ />+ Auto-delete+ </button>+ <span className="truncate hidden sm:inline">+ It maps the canvas, plans the geometry, builds, checks and verifies by itself+ </span>+ </div>+ {canUndo && <span className="shrink-0">Undo available</span>}</div></div></div>diff --git a/src/lib/agent/harness.test.ts b/src/lib/agent/harness.test.tsindex d2ba19f..011fec9 100644--- a/src/lib/agent/harness.test.ts+++ b/src/lib/agent/harness.test.ts@@ -1562,21 +1562,125 @@ describe('v0.29.3 · loop: planning + fail-closed acks', () => {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(+ // v0.34.2 · THE KASHMIR INCIDENT: a composition that cannot fit+ // even at the 56px floor (12 sections on this canvas) is no longer+ // REJECTED — the old honest error ended a real run at THREE+ // rejections with ZERO elements. The TRUNCATING solver keeps the+ // first fitting prefix (10 sections here) and DISCLOSES the drop.+ const truncated = tool!.sanitize({sections: Array.from({ length: 12 }, (_, i) => ({ name: `s${i + 1}`, y: 65 + i * 100, height: 140, contains: 'x' })),},ctx,)+ expect(truncated.ok).toBe(true)+ const tb = (truncated as { actions?: { bands?: { name: string; y: number; h: number }[] }[] }).actions?.[0]?.bands+ expect(tb?.length).toBe(10)+ expect(tb?.[0].name).toBe('s1')+ expect(tb?.[9].name).toBe('s10')+ expect(tb![9].y + tb![9].h).toBeLessThanOrEqual(1015)+ const truncObs = String((truncated as { observation?: string }).observation)+ expect(truncObs).toContain('PLAN TRUNCATED')+ expect(truncObs).toContain('12 → 10 sections')+ expect(truncObs).toContain('Merge the dropped sections')++ // truly INFEASIBLE survives only when even ONE section cannot fit:+ // an occupied canvas with no free window — the honest reject (the+ // model must move or clear existing elements, never re-argue math).+ const fullCtx: ToolContext = { ...ctx, occupied: [{ y: 0, h: 1079, label: 'existing content' }] }+ const infeasible = tool!.sanitize(+ {+ sections: [{ name: 'a', y: 100, height: 200, contains: 'x' }],+ },+ fullCtx,+ )expect(infeasible.ok).toBe(false)const err = String((infeasible as { error?: string }).error)expect(err).toContain('Infeasible plan')- expect(err).toContain('56px minimum band')- expect(err).toContain('at most 10 sections')+ expect(err).toContain('Move or clear existing elements')+ })++ it('plan_layout SYNTHESIZES malformed args instead of rejecting them (v0.34.2: the Kashmir run died at three rejected plan_layout calls with zero actions)', () => {+ const tool = AGENT_TOOL_MAP.get('plan_layout')+ expect(tool).toBeTruthy()+ // the exact failure shapes from the production run: missing names,+ // non-numeric y / height — every one is now ACCEPTED with the+ // missing fields synthesized and DISCLOSED (name = label, y =+ // ordering hint: the server computes geometry anyway)+ const res = tool!.sanitize(+ {+ sections: [+ { height: '200', contains: 'KASHMIR headline' },+ { name: 'cta', y: 'auto', contains: 'EXPLORE NOW' },+ ],+ },+ ctx,+ )+ expect(res.ok).toBe(true)+ const obs = String((res as { observation?: string }).observation)+ expect(obs).toContain('ARGS SYNTHESIZED')+ expect(obs).toContain('name synthesized')+ expect(obs).toContain('non-numeric/missing y')+ expect(obs).toContain('non-numeric/missing height')+ const bands = (res as { actions?: { bands?: { name: string; y: number; h: number }[] }[] }).actions?.[0]?.bands+ expect(bands?.length).toBe(2)+ expect(bands?.[0].name).toBe('Section 1')+ expect(bands?.[1].name).toBe('cta')++ // bare STRING entries are accepted as names — models degrade to+ // ["hero", "cta"] when the object shape escapes them+ const strings = tool!.sanitize({ sections: ['hero', 'cta'] }, ctx)+ expect(strings.ok).toBe(true)+ const sb = (strings as { actions?: { bands?: { name: string; y: number; h: number }[] }[] }).actions?.[0]?.bands+ expect(sb?.map((b) => b.name)).toEqual(['hero', 'cta'])++ // the only hard rejects left: nothing to plan at all+ const noArray = tool!.sanitize({ sections: 'hero' }, ctx)+ expect(noArray.ok).toBe(false)+ const empty = tool!.sanitize({ sections: [] }, ctx)+ expect(empty.ok).toBe(false)+ })++ it('THE KASHMIR REGRESSION: a malformed plan no longer ends the run — the loop synthesizes, plans and BUILDS (v0.34.2)', async () => {+ const events: AgentEvent[] = []+ const { chat } = scriptedChat([+ // the exact production failure shape: missing name, non-numeric+ // y/height — rejected three times in a row on v0.34.1, killing+ // the run at zero actions. Now: synthesized + disclosed, and the+ // run proceeds to build.+ turn('plan_layout', { sections: [{ contains: 'KASHMIR hero' }, { name: 'cta', y: 'auto', height: 'big' }] }),+ turn('add_text', { text: 'KASHMIR', x: 0, y: 100, width: 1080, fontSize: 120, bold: true, color: '#FFFFFF' }),+ done('Built the Kashmir ad'),+ ])+ const result = await runAgentLoop({+ chat,+ design,+ mode: 'create',+ request: 'Create a premium travel advertisement promoting Kashmir',+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ })+ // the malformed plan was ACCEPTED (synthesized), not rejected —+ // planRejections never fired, the run never wrapped+ expect(events.some((e) => e.type === 'plan')).toBe(true)+ expect(events.some((e) => e.type === 'aborted' || e.type === 'error')).toBe(false)+ expect(result.summary).toContain('Built the Kashmir ad')+ })++ it('a user STOP persists the run as stopped (v0.34.2: the ledger row used to stay running forever)', async () => {+ const persisted: { status?: string }[] = []+ const { chat } = scriptedChat([turn('get_page_state', {})])+ const result = await runAgentLoop({+ chat,+ design,+ mode: 'create',+ request: 'Design a travel ad',+ emit: () => {},+ persistRun: (s) => persisted.push(s as { status?: string }),+ signal: { aborted: true, reason: 'Stopped by user' },+ })+ expect(result.summary).toContain('Stopped by the user')+ expect(persisted.some((p) => p.status === 'stopped')).toBe(true)})it('a failed (timed-out) apply ack tells the model the action was NOT applied — fail closed', async () => {@@ -2375,14 +2479,24 @@ 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 FLOOR-INFEASIBLE plans stop honestly with the exact math — bounded, never an infinite retry', async () => {+ it('three plans on a GENUINELY FULL canvas stop honestly — 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.+ // v0.34.2: an empty canvas can no longer produce an infeasible plan —+ // oversized plans scale (v0.32.8), malformed args synthesize, and+ // floor-infeasible compositions truncate to the fitting prefix. The+ // rejection budget now fires only when the canvas is GENUINELY full:+ // existing elements leave no free window even for ONE section. Three+ // of those still stop the run honestly.+ const fullDesign: AgentDesignCtx = {+ name: 'Untitled', width: 1080, height: 1080, pageCount: 1,+ currentPageIndex: 0,+ // stacked 1080-wide rects with <40px spacing merge into ONE occupied+ // band covering the whole page — nothing fits anywhere+ elements: Array.from({ length: 27 }, (_, i) => ({ id: `r${i}`, type: 'rect', x: 0, y: i * 40, width: 1080, height: 40, fill: '#222222' })),+ colorsInUse: [], otherPages: [],+ }const infeasible = () => ({- sections: Array.from({ length: 12 }, (_, i) => ({ name: `s${i + 1}`, y: 65 + i * 100, height: 140, contains: 'x' })),+ sections: [{ name: 'a', y: 100, height: 200, contains: 'x' }],})const { chat } = scriptedChat([turn('plan_layout', infeasible()),@@ -2394,12 +2508,13 @@ describe('v0.32.5 · the P0 regression — recoverable geometry must not kill adone('Should not get here'),])const result = await runAgentLoop({- chat, design: emptyDesign, mode: 'create',+ chat, design: fullDesign, mode: 'create',request: 'Design a poster',emit: (e) => events.push(e),awaitApply: async () => ({ ok: true }),})expect(result.summary).toContain('rejected plan_layout calls')+ expect(result.summary).toContain('genuinely full')expect(result.summary).toContain('INCOMPLETE') // guardExit honesty: zero changesexpect(result.toolCalls).toBe(0) // nothing applied after the honest stopconst last = events[events.length - 1]diff --git a/src/lib/agent/loop.ts b/src/lib/agent/loop.tsindex e319d7e..30d303c 100644--- a/src/lib/agent/loop.ts+++ b/src/lib/agent/loop.ts@@ -261,7 +261,7 @@ export function loopSystemPrompt(deps: {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).`,+ `· 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, malformed args are synthesized, floor-infeasible plans are truncated to what fits — every repair is disclosed, so send the plan you MEAN and build inside the bands you get).`,'· 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. The SERVER computes the exact y-positions — with ≥40px gaps into the safe area, and on a canvas that already has content, into the FREE space between existing elements (never on top of them).','· Set the page background EARLY with set_background (a required background color belongs there, not in strips).',@@ -596,6 +596,12 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {while (true) {// ── task-driven stops ───────────────────────────────────if (signal?.aborted) {+ // v0.34.2: a user-stopped run persists as STOPPED. The old+ // early return skipped persist entirely, leaving the ledger+ // row 'running' forever — excluded from both the run ledger+ // (NOT status 'running') and recovery, so the applied work+ // vanished from the design's run context.+ persist('stopped')emit({ v: AGENT_PROTOCOL_VERSION, type: 'aborted', reason: signal.reason ?? 'Stopped by user' })return { summary: summary || 'Stopped by the user.', steps, toolCalls, verification }}@@ -1097,12 +1103,14 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {planRejections += 1telemetry({ tool: 'plan_layout', outcome: 'rejected', attempt: planRejections, detail: String((result as { error?: string }).error ?? '').slice(0, 300) })if (planRejections >= AGENT_GUARDS.planRejections) {- // 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.+ // v0.34.2: with arg synthesis (missing name/y/height are+ // synthesized + disclosed) and the truncating solver+ // (floor-infeasible compositions are truncated + disclosed),+ // a rejection now means the sections were unusable at all or+ // the canvas is genuinely full — the message points at the+ // remaining causes, 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.`,+ `Stopped after ${planRejections} rejected plan_layout calls — each error above names the remaining cause (sections must be an array of {name, y, height, contains} objects or plain names, or the canvas is genuinely full). Resend ONE valid plan_layout, or move/clear existing elements first.`,'plan-infeasible',)emit({ v: AGENT_PROTOCOL_VERSION, type: 'done', summary: exit.summary, steps, toolCalls, verification: exit.verification })diff --git a/src/lib/agent/plan-repair.ts b/src/lib/agent/plan-repair.tsindex 4832ca5..5c2d832 100644--- a/src/lib/agent/plan-repair.ts+++ b/src/lib/agent/plan-repair.ts@@ -70,6 +70,36 @@ export interface PlanRepairInfeasible {export type PlanRepairResult = PlanRepairOk | PlanRepairInfeasible+/** v0.34.2 · the truncating wrapper — plan_layout never gives up.+ *+ * The Kashmir incident: a reasonable travel-ad brief died at THREE+ * rejected plan_layout calls with ZERO elements because the model+ * sent more sections than the page can host at the PLAN_MIN_BAND+ * floor. Scaling cannot rescue a floor-infeasible composition —+ * but DROPPING trailing sections can: fewer sections at the same+ * floor always fits (order and contents kept, the drop DISCLOSED).+ * Run death is strictly worse than a truncated-but-disclosed plan.+ *+ * Returns the first fitting prefix; only a request where even ONE+ * section cannot fit stays infeasible (that canvas is genuinely+ * full — the honest reject nobody can truncate their way out of).+ */+export function solvePlanBandsTruncating(+ requested: PlanSection[],+ H: number,+ opts?: { minGap?: number; margin?: number; occupied?: OccupiedBand[] },+): PlanRepairResult & { truncated?: { from: number; to: number } } {+ let last = repairPlanBands(requested, H, opts)+ if (last.ok || requested.length <= 1) return last+ for (let keep = requested.length - 1; keep >= 1; keep--) {+ last = repairPlanBands(requested.slice(0, keep), H, opts)+ if (last.ok) {+ return { ...last, truncated: { from: requested.length, to: keep } }+ }+ }+ return last+}+export const PLAN_MIN_GAP = 40export const PLAN_MARGIN = 0.06/** v0.32.8 · the smallest band the solver will ever produce. Belowdiff --git a/src/lib/agent/tools.ts b/src/lib/agent/tools.tsindex 151ef82..ea503c8 100644--- a/src/lib/agent/tools.ts+++ b/src/lib/agent/tools.ts@@ -16,7 +16,7 @@import { FONTS } from '@/lib/fonts/catalog'import type { ToolRisk } from './protocol'-import { repairPlanBands } from './plan-repair'+import { PLAN_MARGIN, PLAN_MIN_BAND, solvePlanBandsTruncating } from './plan-repair'// v0.33 · the native asset libraries are PURE data — the SERVER// resolves queries against them (fail-closed at the boundary). The// NEON 2027 incident: unknown concepts were acked as success on the@@ -203,27 +203,43 @@ export const AGENT_TOOLS: AgentTool[] = [sanitize: (args, ctx) => {const sectionsRaw = args.sectionsif (!Array.isArray(sectionsRaw) || sectionsRaw.length === 0) {- return { ok: false, error: '"sections" must be a non-empty array: [{name, y, height, contains}].' }+ return { ok: false, error: '"sections" must be a non-empty array: [{name, y, height, contains}] — plain string names are also accepted.' }}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.+ // v0.34.2 · THE KASHMIR INCIDENT: a reasonable create brief died+ // at THREE rejected plan_layout calls with ZERO elements — the+ // model sent sections with missing names or non-numeric y/height,+ // and a composition that could not fit even at the 56px floor.+ // Forcing the model to re-send well-formed ARGUMENTS repeated+ // the v0.32.4 bug (reject → retry → reject) one level up: the+ // name is a display label, y is only an ordering hint and the+ // SERVER computes geometry anyway — so malformed arguments are+ // now SYNTHESIZED and disclosed, never rejected. plan_layout+ // rejects only when there is nothing at all to plan.+ const synth: string[] = []+ const entries = sectionsRaw.slice(0, 12)+ if (sectionsRaw.length > 12) synth.push(`kept the first 12 of ${sectionsRaw.length} sections (12 is the maximum)`)+ const defaultH = Math.max(PLAN_MIN_BAND, Math.floor((H * (1 - 2 * PLAN_MARGIN)) / Math.max(1, entries.length)))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, 'y')- const height = num(sec, 'height')+ for (let i = 0; i < entries.length; i++) {+ const s = entries[i]+ // a bare string entry is accepted as a section NAME — models+ // degrade to ["hero", "cta"] when the object shape escapes them+ const sec: Record<string, unknown> =+ s && typeof s === 'object' ? (s as Record<string, unknown>) : typeof s === 'string' ? { name: s } : {}+ const rawName = typeof sec.name === 'string' ? sec.name.trim().slice(0, 40) : ''+ const name = rawName || `Section ${parsed.length + 1}`+ if (!rawName) synth.push(`section ${i + 1}: name synthesized → "${name}"`)+ const yRaw = num(sec, 'y')+ const y = yRaw !== null ? yRaw : i // stacking order — the solver recomputes positions anyway+ if (yRaw === null) synth.push(`section "${name}": non-numeric/missing y → stacking order ${i}`)+ const hRaw = num(sec, 'height')+ const h = hRaw !== null && hRaw > 0 ? hRaw : defaultH+ if (!(hRaw !== null && hRaw > 0)) synth.push(`section "${name}": non-numeric/missing height → ${defaultH}px equal split`)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).` }- }- parsed.push({ name, y, h: Math.round(height), contains })+ parsed.push({ name, y, h: Math.round(h), contains })}- if (!parsed.length) return { ok: false, error: '"sections" contained no usable entries.' }+ if (!parsed.length) return { ok: false, error: '"sections" contained no usable entries — send [{name, y, height, contains}] objects or plain string names.' }// v0.32.5 · THE P0 REGRESSION FIX: the v0.32.4 validator// rejected bad geometry and told the model to redo the gap@@ -245,16 +261,19 @@ export const AGENT_TOOLS: AgentTool[] = [// the solver fits the requested sections into the FREE space// between them — the plan can never reserve space on top of// something that is already there.- const repair = repairPlanBands(+ // v0.34.2 · the TRUNCATING solver: a floor-infeasible+ // composition (more sections than the page can host) is+ // truncated to the first fitting prefix — DISCLOSED — instead+ // of rejected (the rejection path was the Kashmir run's death:+ // three honest errors, zero elements). Only a canvas where+ // even ONE section cannot fit stays infeasible.+ const repair = solvePlanBandsTruncating(parsed.map((p) => ({ name: p.name, y: p.y, h: p.h })),H,{ occupied: ctx.occupied },)if (!repair.ok) {- return {- ok: false,- error: `${repair.infeasible} Resend plan_layout with smaller section heights (keep the names and order).`,- }+ return { ok: false, error: repair.infeasible }}// the plan lines are the REPAIRED geometry — the authoritative@@ -286,7 +305,16 @@ export const AGENT_TOOLS: AgentTool[] = [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 = `${mapNote}PLAN RECORDED (${lines.length} lines):\n${lines.join('\n')}\n${repairedNote}`+ // v0.34.2 · disclosure of what the server synthesized (missing+ // names / y / heights) and what it dropped (floor-infeasible+ // compositions truncated to the first fitting prefix)+ const synthNote = synth.length+ ? `\nARGS SYNTHESIZED (your intent was kept; the server filled the missing fields — match the spec next time): ${synth.join('; ')}.`+ : ''+ const truncNote = repair.truncated+ ? `\nPLAN TRUNCATED: ${repair.truncated.from} → ${repair.truncated.to} sections (the page cannot host ${repair.truncated.from} at the ${PLAN_MIN_BAND}px minimum band). Merge the dropped sections' content into the kept sections — do NOT re-send the dropped sections.`+ : ''+ const observation = `${mapNote}PLAN RECORDED (${lines.length} lines):\n${lines.join('\n')}${synthNote}${truncNote}\n${repairedNote}`return {ok: true,actions: [{ type: '__planLayout', lines, bands: repair.bands }],diff --git a/tests/e2e/agent-autodelete-stop.spec.ts b/tests/e2e/agent-autodelete-stop.spec.tsnew file mode 100644index 0000000..6b2ab47--- /dev/null+++ b/tests/e2e/agent-autodelete-stop.spec.ts@@ -0,0 +1,251 @@+import { test, expect, type Page, type Route } from '@playwright/test'++// v0.34.2 — the AUTO-DELETE option and the STOP button, end to end in+// the real editor.+//+// AUTO-DELETE (optional, default OFF): a toggle in the composer+// pre-approves the destructive tools (delete_elements / clear_page /+// delete_page) for the whole run — the approval dialog never appears+// and the deletes apply directly. With it OFF, the per-call approval+// gate still pauses the run. "Undo agent work" and version history+// remain the safety net behind every delete.+//+// THE STOP BUTTON: the client-side abort already worked mid-stream;+// what never worked was stopping the POST-RUN VISION CRITIQUE — the+// button aborted an already-finished fetch while the critique's own+// request hung unabortable, leaving the panel busy forever. The+// critique now rides the run's AbortSignal.+//+// The agent route is MOCKED to scripted SSE streams (no provider+// credentials in CI). The vision route hangs — proving the Stop+// button releases it.++const V = 2++const ev = (e: unknown) => `data: ${JSON.stringify(e)}\n\n`++/** register a fresh user */+async function register(page: Page, tag: string): Promise<string> {+ const username = `v342_${tag}_${Date.now().toString(36)}`+ const password = `V342-E2e-${username}-19!q`+ const res = await page.request.post('/api/auth/register', { data: { username, password } })+ expect(res.status(), `register ${username}`).toBeLessThan(300)+ return username+}++/** a canvas with two named texts — the destructive target */+async function createDesignWithTexts(page: Page, name: string, texts: string[]): Promise<string> {+ const res = await page.request.post('/api/designs', {+ data: {+ name,+ width: 1080,+ height: 1080,+ pages: [+ {+ id: 'p1',+ background: { type: 'solid', color: '#FFFFFF' },+ elements: texts.map((text, i) => ({+ id: `txt-${i + 1}`,+ type: 'text',+ x: 100, y: 100 + i * 120, width: 800, height: 60,+ text, fontSize: 48, fill: '#111111',+ })),+ },+ ],+ },+ })+ expect(res.status(), `create design: ${await res.text()}`).toBeLessThan(300)+ return ((await res.json()) as { id: string }).id+}++async function openEditor(page: Page, designId: string) {+ await page.goto(`/design/${designId}`)+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 60_000 })+}++async function openAgentPanel(page: Page) {+ await page.getByRole('button', { name: 'Apps', exact: true }).click()+ await page.getByText('Canvix AI', { exact: true }).first().click()+}++type Doc = { pages: { elements: { id?: string; type?: string; text?: string }[] }[] }++async function doc(page: Page, designId: string): Promise<Doc> {+ const res = await page.request.get(`/api/designs/${designId}`)+ expect(res.status()).toBe(200)+ return (await res.json()) as Doc+}++async function waitForDoc(page: Page, designId: string, predicate: (d: Doc) => boolean, what: string, timeoutMs = 20_000) {+ const started = Date.now()+ let last: Doc | null = null+ while (Date.now() - started < timeoutMs) {+ last = await doc(page, designId)+ if (predicate(last)) return last+ await page.waitForTimeout(500)+ }+ throw new Error(`document never showed ${what} within ${timeoutMs}ms — last: ${JSON.stringify(last?.pages[0]).slice(0, 300)}`)+}++/** a scripted run whose ONLY call is a destructive delete_elements */+function destructiveScript(runId: string): string {+ const events: unknown[] = [+ { v: V, type: 'start', runId },+ { v: V, type: 'mode', mode: 'edit', reason: 'a delete request' },+ { v: V, type: 'step', index: 0, thought: 'remove the stale text', tool: 'delete_elements' },+ {+ v: V, type: 'action', stepIndex: 0, callId: 'c0', risk: 'destructive', tool: 'delete_elements',+ actions: [{ type: 'deleteElements', ids: ['txt-1'] }],+ },+ { v: V, type: 'observation', stepIndex: 0, message: 'Deleted 1 element(s).' },+ { v: V, type: 'usage', turns: 1, toolCalls: 1, elapsedMs: 400, modelCalls: 1 },+ { v: V, type: 'done', steps: 1, toolCalls: 1, summary: 'Stale text removed.' },+ ]+ return events.map(ev).join('')+}++test.setTimeout(120_000)++test.describe('v0.34.2 · AUTO-DELETE (optional pre-approval of destructive tools)', () => {+ test('default OFF: a destructive call pauses for approval, Approve once applies it', async ({ page }) => {+ await register(page, 'gate')+ const designId = await createDesignWithTexts(page, 'gate canvas', ['STALE TEXT', 'KEEP ME'])+ await openEditor(page, designId)+ await openAgentPanel(page)++ await page.route('**/api/ai/agent**', async (route: Route) => {+ const req = route.request()+ if (req.method() === 'POST' && req.url().includes('bridge=')) {+ 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: destructiveScript('run-gate'),+ })+ })++ // the toggle exists, defaults OFF+ const toggle = page.getByTestId('agent-autodelete')+ await expect(toggle).toBeVisible()+ await expect(toggle).toHaveAttribute('aria-checked', 'false')++ await page.getByPlaceholder('Describe what to design or change — the agent figures out the rest…').fill('Delete the stale text')+ await page.getByRole('button', { name: 'Send', exact: true }).click()++ // the gate PAUSES the run: the approval card appears…+ await expect(page.getByRole('button', { name: 'Approve once' })).toBeVisible({ timeout: 15_000 })+ // …and the element is still there+ let d = await doc(page, designId)+ expect(d.pages[0].elements.some((e) => e.text === 'STALE TEXT')).toBe(true)++ await page.getByRole('button', { name: 'Approve once' }).click()+ await waitForDoc(page, designId, (x) => !x.pages[0].elements.some((e) => e.text === 'STALE TEXT'), 'the approved delete')+ d = await doc(page, designId)+ expect(d.pages[0].elements.some((e) => e.text === 'KEEP ME')).toBe(true)+ })++ test('toggle ON: the same run deletes WITHOUT asking (and body.confirmed pre-approves server-side)', async ({ page }) => {+ await register(page, 'auto')+ const designId = await createDesignWithTexts(page, 'auto canvas', ['STALE TEXT', 'KEEP ME'])+ await openEditor(page, designId)+ await openAgentPanel(page)++ let capturedConfirmed: string[] | null = null+ await page.route('**/api/ai/agent**', async (route: Route) => {+ const req = route.request()+ if (req.method() === 'POST' && req.url().includes('bridge=')) {+ await route.fulfill({ status: 200, contentType: 'application/json', body: '{}' })+ return+ }+ const body = req.postDataJSON() as { confirmed?: string[] }+ capturedConfirmed = body.confirmed ?? []+ await route.fulfill({+ status: 200,+ headers: { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache' },+ body: destructiveScript('run-auto'),+ })+ })++ // flip the toggle ON before sending+ await page.getByTestId('agent-autodelete').click()+ await expect(page.getByTestId('agent-autodelete')).toHaveAttribute('aria-checked', 'true')++ await page.getByPlaceholder('Describe what to design or change — the agent figures out the rest…').fill('Delete the stale text')+ await page.getByRole('button', { name: 'Send', exact: true }).click()++ // NO approval dialog — the delete applies directly+ const deleted = await waitForDoc(page, designId, (x) => !x.pages[0].elements.some((e) => e.text === 'STALE TEXT'), 'the auto-applied delete')+ expect(deleted.pages[0].elements.some((e) => e.text === 'KEEP ME')).toBe(true)+ await expect(page.getByRole('button', { name: 'Approve once' })).toHaveCount(0)+ // the run finished normally (the dialog never gated it)+ await expect(page.getByText('Stale text removed.', { exact: false })).toBeVisible({ timeout: 15_000 })++ // the server was pre-approved too: body.confirmed carried the tool+ expect(capturedConfirmed).toContain('delete_elements')++ // the toggle persists for the next session (localStorage)+ await expect(page.getByTestId('agent-autodelete')).toHaveAttribute('aria-checked', 'true')+ })+})++test.describe('v0.34.2 · the STOP button releases the post-run vision critique', () => {+ test('Stop during the hanging critique finalizes the run instead of leaving the panel busy forever', async ({ page }) => {+ await register(page, 'stop')+ const designId = await createDesignWithTexts(page, 'stop canvas', ['HELLO'])+ await openEditor(page, designId)+ await openAgentPanel(page)++ // a fast scripted create run that APPLIES one action and finishes+ const events: unknown[] = [+ { v: V, type: 'start', runId: 'run-stop' },+ { v: V, type: 'mode', mode: 'create', reason: 'a create request' },+ { v: V, type: 'step', index: 0, thought: 'headline', tool: 'add_text' },+ {+ v: V, type: 'action', stepIndex: 0, callId: 'c0', risk: 'write', tool: 'add_text',+ actions: [{ type: 'addText', text: 'STOP TEST', x: 100, y: 200, width: 800, fontSize: 72, bold: true, color: '#111111' }],+ },+ { v: V, type: 'observation', stepIndex: 0, message: 'Headline added.' },+ { v: V, type: 'usage', turns: 1, toolCalls: 1, elapsedMs: 300, modelCalls: 1 },+ { v: V, type: 'done', steps: 1, toolCalls: 1, summary: 'Created the STOP TEST design.' },+ ]+ // the agent stream mock (bridge POSTs included); the vision route+ // is registered AFTER so it takes precedence for vision URLs+ await page.route('**/api/ai/agent**', async (route: Route) => {+ if (route.request().method() !== 'POST' || route.request().url().includes('bridge=')) {+ 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: events.map(ev).join(''),+ })+ })+ // the post-run vision critique HANGS (the old unabortable fetch)+ await page.route('**/api/ai/agent/vision**', async (route: Route) => {+ await page.waitForTimeout(60_000) // never fulfills within the test+ await route.fulfill({ status: 503, contentType: 'application/json', body: '{}' })+ })++ await page.getByPlaceholder('Describe what to design or change — the agent figures out the rest…').fill('Create a STOP TEST design')+ await page.getByRole('button', { name: 'Send', exact: true }).click()++ // the run stream completed and applied its action — the critique+ // is now in-flight, and the panel is still busy with a Stop button+ await waitForDoc(page, designId, (x) => x.pages[0].elements.some((e) => e.text === 'STOP TEST'), 'the applied action')+ const stopButton = page.getByRole('button', { name: 'Stop', exact: true })+ await expect(stopButton).toBeVisible({ timeout: 15_000 })++ // STOP — with the fix, the abort releases the hanging critique+ // and the turn finalizes; without it, the fetch hung forever and+ // this assertion timed out with the panel stuck on "Working…"+ await stopButton.click()+ await expect(page.getByText('Created the STOP TEST design.', { exact: false })).toBeVisible({ timeout: 10_000 })+ // the panel is usable again — the composer re-enables+ const send = page.getByRole('button', { name: 'Send', exact: true })+ await expect(send).toBeEnabled({ timeout: 10_000 })+ })+})