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.29): self-critique agent — quality audit, JSON-mode turns, vision retry
Ashiq Hussain Mir062a44f38a06
diff --git a/.env.example b/.env.exampleindex 30813c6..9b81ab3 100644--- a/.env.example+++ b/.env.example@@ -112,3 +112,13 @@ DATABASE_URL=postgresql://postgres.[YOUR-PROJECT-REF]:[YOUR-PASSWORD]@aws-0-eu-cZAI_TEXT_MODEL=ZAI_VISION_MODEL=ZAI_IMAGE_MODEL=++# ── v0.29: JSON-mode + vision-fallback pins ──+# ZAI_JSON_MODE=auto (default) — response_format json_object on agent+# turns; auto-drops it if the gateway rejects the param. 'on' = fail+# loudly, 'off' = never send it.+# ZAI_VISION_FALLBACK_MODEL — second chance for vision calls when NIM's+# media screening transiently 422s a data URL (e.g. the omni model:+# nvidia/nemotron-3-nano-omni-30b-a3b-reasoning, verified data-URL).+ZAI_JSON_MODE=auto+ZAI_VISION_FALLBACK_MODEL=diff --git a/src/app/api/ai/agent/route.ts b/src/app/api/ai/agent/route.tsindex 36d4938..86559dd 100644--- a/src/app/api/ai/agent/route.ts+++ b/src/app/api/ai/agent/route.ts@@ -12,6 +12,7 @@ import { fontFamilies } from '@/lib/agent/tools'import { serializeDesignContext, type AgentDesignCtx } from '@/lib/agent/context'import { heuristicMode, parseMode, ROUTER_SYSTEM, modeAllowsWrites, MODE_TOOL_RISK } from '@/lib/agent/router'import { runAgentLoop, toolsForMode } from '@/lib/agent/loop'+import { auditDesign as runDesignAudit } from '@/lib/agent/audit'import { selectSkills } from '@/lib/agent/skills'import { extractBrief } from '@/lib/agent/brief'@@ -131,13 +132,41 @@ async function __canvix_post(req: NextRequest) {.filter((m) => m && (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string').map((m) => ({ role: m.role, content: m.content.slice(0, 800) }))+ // v0.29: guaranteed-JSON turns. response_format {type:'json_object'}+ // passes through the SDK to any OpenAI-compatible gateway (verified+ // live on NVIDIA NIM: zero malformed turns). ZAI_JSON_MODE=auto (the+ // default) drops the param for the rest of the run if the gateway+ // rejects it, so every OpenAI-ish endpoint keeps working; 'on' fails+ // loudly instead of silently degrading.+ const jsonModePref = (process.env.ZAI_JSON_MODE ?? 'auto').trim().toLowerCase()+ let jsonModeLive = jsonModePref !== 'off'+ const rawCreate = ctx.zai.chat.completions.create as unknown as (+ body: Record<string, unknown>,+ ) => Promise<{ choices: { message?: { content?: unknown } }[] }>const chat = async (msgs: { role: 'system' | 'user' | 'assistant'; content: string }[]) => {- const completion = await ctx.zai.chat.completions.create({+ const base: Record<string, unknown> = {...(ctx.model ? { model: ctx.model } : {}),messages: msgs,thinking: { type: 'disabled' },- })- return String(completion.choices[0]?.message?.content ?? '')+ }+ const callJson = (withJson: boolean) =>+ rawCreate(withJson ? { ...base, response_format: { type: 'json_object' } } : base)+ try {+ const completion = await callJson(jsonModeLive)+ return String(completion.choices[0]?.message?.content ?? '')+ } catch (e) {+ const msg = String((e as Error | undefined)?.message ?? e)+ if (+ jsonModeLive &&+ jsonModePref === 'auto' &&+ /(?:\b(?:400|404|422)\b|response_format|json_object|unknown field|not supported|unsupported)/i.test(msg)+ ) {+ jsonModeLive = false // remember for the whole run+ const completion = await callJson(false)+ return String(completion.choices[0]?.message?.content ?? '')+ }+ throw e+ }}// ── 1. classify the mode (heuristic first, model when unsure) ──@@ -275,6 +304,8 @@ async function __canvix_post(req: NextRequest) {setTimeout(() => resolve({ ok: true, message: 'ack timeout — assumed applied' }), 60_000)}),refreshedContext: () => bridge.latestDesign,+ // v0.29: audit the freshest design snapshot the panel acked+ auditDesign: () => runDesignAudit(bridge.latestDesign ?? design),validateBriefOnClient: async () => {// consume an early answer first, then wait for a live oneif (bridge.pendingBriefResult) {diff --git a/src/app/api/ai/alt-text/route.ts b/src/app/api/ai/alt-text/route.tsindex 1f8e96b..d7941c2 100644--- a/src/app/api/ai/alt-text/route.ts+++ b/src/app/api/ai/alt-text/route.ts@@ -1,5 +1,6 @@import { NextRequest, NextResponse } from 'next/server'import { withProvider, DEFAULT_VISION_MODEL } from '@/lib/ai/provider'+import { visionChatWithRetry } from '@/lib/ai/vision-retry'import { withLogging } from '@/lib/observability'export const runtime = 'nodejs'@@ -44,8 +45,8 @@ async function __canvix_post(req: NextRequest) {}return withProvider('alt-text', req, { limit: 20, windowSec: 60 }, async (ctx) => {- const completion = await ctx.zai.chat.completions.createVision({- model: ctx.model ?? DEFAULT_VISION_MODEL,+ const completion = await visionChatWithRetry((visionRetryModel) => ctx.zai.chat.completions.createVision({+ model: visionRetryModel ?? ctx.model ?? DEFAULT_VISION_MODEL,messages: [{role: 'system',@@ -63,7 +64,7 @@ async function __canvix_post(req: NextRequest) {},],thinking: { type: 'disabled' },- })+ }), ctx.model)const raw = completion.choices[0]?.message?.content ?? ''const alt = normalizeAltText(raw)diff --git a/src/app/api/ai/magic-layers/route.ts b/src/app/api/ai/magic-layers/route.tsindex de248fa..f4d1919 100644--- a/src/app/api/ai/magic-layers/route.ts+++ b/src/app/api/ai/magic-layers/route.ts@@ -1,5 +1,6 @@import { NextRequest, NextResponse } from 'next/server'import { withProvider, DEFAULT_VISION_MODEL } from '@/lib/ai/provider'+import { visionChatWithRetry } from '@/lib/ai/vision-retry'import { validateAnalysis } from '@/lib/magic-layers/validate'import { withLogging } from '@/lib/observability'@@ -55,8 +56,8 @@ async function __canvix_post(req: NextRequest) {'9. If the background is a photo/illustration, use kind=photo and still list visible foreground regions.\n' +'10. notes = one short sentence about what the reconstruction will approximate (e.g. "illustration left of title will become a cropped image region").'- const completion = await ctx.zai.chat.completions.createVision({- model: ctx.model ?? DEFAULT_VISION_MODEL,+ const completion = await visionChatWithRetry((visionRetryModel) => ctx.zai.chat.completions.createVision({+ model: visionRetryModel ?? ctx.model ?? DEFAULT_VISION_MODEL,messages: [{ role: 'system', content: system },{@@ -68,7 +69,7 @@ async function __canvix_post(req: NextRequest) {},],thinking: { type: 'disabled' },- })+ }), ctx.model)const raw = completion.choices[0]?.message?.content ?? ''const analysis = validateAnalysis(raw)diff --git a/src/lib/agent/audit.ts b/src/lib/agent/audit.tsnew file mode 100644index 0000000..993800f--- /dev/null+++ b/src/lib/agent/audit.ts@@ -0,0 +1,94 @@+/**+ * v0.29 QUALITY AUDIT — local design heuristics the agent runs on its+ * own canvas before accepting completion. No model calls, no vision:+ * WCAG 2.x contrast math, the client-computed overlaps/off-canvas from+ * the design ctx, and a text-overflow estimate. The loop consumes the+ * returned issues in ONE auto-fix round (see loop.ts); empty = clean.+ */+import type { AgentDesignCtx } from './context'++const HEX = /^#?[0-9a-f]{6}$/i++/** WCAG 2.x relative luminance of a #RRGGBB color (0..1); -1 unparseable. */+export function luminance(hex: string): number {+ const m = /^#?([0-9a-f]{6})$/i.exec(String(hex).trim())+ if (!m) return -1+ const n = parseInt(m[1], 16)+ const channel = (v: number) => {+ const c = v / 255+ return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4)+ }+ return 0.2126 * channel((n >> 16) & 255) + 0.7152 * channel((n >> 8) & 255) + 0.0722 * channel(n & 255)+}++/** WCAG contrast ratio (1..21); 0 when either color is unparseable. */+export function contrastRatio(fg: string, bg: string): number {+ const lf = luminance(fg)+ const lb = luminance(bg)+ if (lf < 0 || lb < 0) return 0+ return (Math.max(lf, lb) + 0.05) / (Math.min(lf, lb) + 0.05)+}++/** Worst N issues, human-readable and FIXABLE (the model acts on these). */+export function auditDesign(d: AgentDesignCtx): string[] {+ const issues: string[] = []+ const texts = (d.elements ?? []).filter((e) => e && e.type === 'text')+ // background: explicit ctx field, else the dominant color heuristic+ const bg = typeof d.background === 'string' && HEX.test(d.background)+ ? d.background+ : (d.colorsInUse ?? []).find((c) => HEX.test(c)) ?? null++ // 1. text contrast against the page background (WCAG: 3:1 large, 4.5:1 body)+ if (bg) {+ let contrastHits = 0+ for (const t of texts) {+ const fill = typeof t.fill === 'string' ? t.fill : ''+ if (!HEX.test(fill)) continue+ const ratio = contrastRatio(fill, bg)+ if (ratio <= 0) continue+ const size = typeof t.fontSize === 'number' ? t.fontSize : 0+ const need = size >= 24 ? 3 : 4.5+ if (ratio < need) {+ contrastHits += 1+ if (contrastHits <= 4) {+ issues.push(+ `Low contrast: text "${String(t.text ?? '').slice(0, 30)}" ${fill} on background ${bg} is ${ratio.toFixed(1)}:1 (needs ${need}:1) — change the text fill.`,+ )+ }+ }+ }+ if (contrastHits > 4) issues.push(`…and ${contrastHits - 4} more low-contrast text elements.`)+ }++ // 2. element overlaps (client-computed) — hard readability failures+ for (const o of (d.overlaps ?? []).slice(0, 3)) issues.push(`Elements overlap: ${o} — move or resize one of them.`)+ if ((d.overlaps ?? []).length > 3) issues.push(`…and ${(d.overlaps ?? []).length - 3} more overlapping pairs.`)++ // 3. off-canvas elements+ for (const o of (d.offCanvas ?? []).slice(0, 3)) issues.push(`Element is outside the canvas: ${o} — move it back inside ${d.width ?? '?'}x${d.height ?? '?'}.`)+ if ((d.offCanvas ?? []).length > 3) issues.push(`…and ${(d.offCanvas ?? []).length - 3} more off-canvas elements.`)++ // 4. text overflow estimate: average glyph ~0.55em+ let overflowHits = 0+ for (const t of texts) {+ const text = String(t.text ?? '')+ const size = typeof t.fontSize === 'number' ? t.fontSize : 0+ const width = typeof t.width === 'number' ? t.width : 0+ if (!text || size < 8 || width <= 0) continue+ const est = text.length * 0.55 * size+ if (est > width * 1.06) {+ overflowHits += 1+ if (overflowHits <= 3) {+ issues.push(+ `Text may overflow its box: "${text.slice(0, 30)}" (${text.length} chars at ${size}pt needs ~${Math.round(est)}px, box is ${Math.round(width)}px) — reduce fontSize, shorten the text, or widen the box.`,+ )+ }+ }+ }++ // 5. tiny text — illegible at presentation size+ const tiny = texts.filter((t) => typeof t.fontSize === 'number' && t.fontSize > 0 && t.fontSize < 14)+ if (tiny.length) issues.push(`${tiny.length} text element(s) use fontSize under 14 — too small to read; raise them to at least 14.`)++ return issues.slice(0, 12)+}diff --git a/src/lib/agent/context.ts b/src/lib/agent/context.tsindex 22d5cb7..40cab37 100644--- a/src/lib/agent/context.ts+++ b/src/lib/agent/context.ts@@ -49,6 +49,10 @@ export interface AgentDesignCtx {offCanvas?: string[]/** one-line summaries of the OTHER pages */otherPages?: string[]+ /** v0.29: page background hex (solid backgrounds) — enables the+ * contrast part of the quality audit; optional, older clients simply+ * omit it and the audit falls back to the dominant in-use color. */+ background?: string}/** Element summary line — compact but geometry-complete. */diff --git a/src/lib/agent/harness.test.ts b/src/lib/agent/harness.test.tsindex 1902c53..215c37e 100644--- a/src/lib/agent/harness.test.ts+++ b/src/lib/agent/harness.test.ts@@ -25,6 +25,7 @@ import { describe, it, expect } from 'vitest'import { parseAgentTurn, sseLine, AGENT_GUARDS, AGENT_PROTOCOL_VERSION, type AgentEvent } from './protocol'import { AGENT_TOOL_MAP, AGENT_TOOLS, type ToolContext, type SanitizeResult } from './tools'import { runAgentLoop, toolsForMode, loopSystemPrompt } from './loop'+import { auditDesign, contrastRatio } from './audit'import { heuristicMode, parseMode, modeAllowsWrites, MODE_TOOL_RISK } from './router'import { DESIGN_SKILLS, selectSkills, skillsPromptSection } from './skills'import { extractBrief, validateBrief, briefPromptSection, FORMAT_PRESETS, type DesignBrief } from './brief'@@ -264,6 +265,64 @@ describe('harness · tool matrix', () => {const reads = AGENT_TOOLS.filter((t) => t.risk === 'read').map((t) => t.name)expect(reads.sort()).toEqual(['get_page_state', 'goto_page', 'measure_text', 'validate_brief'])})++ it('CASE G: quality audit — one self-critique fix round before done is accepted', async () => {+ const events: AgentEvent[] = []+ let auditCalls = 0+ // model: bg → text → attempt done (audit finds low contrast) → fix+ // fill → done (audit clean, accepted)+ const { chat } = scriptedChat([+ turn('set_background', { kind: 'solid', from: '#090B1A' }),+ turn('add_text', { text: 'Dark text on dark bg', fontSize: 40, color: '#111122' }),+ done('Poster complete'),+ turn('add_text', { text: 'Fixed headline', fontSize: 40, color: '#FFFFFF' }),+ done('Poster complete, contrast fixed'),+ ])+ const result = await runAgentLoop({+ chat,+ design,+ mode: 'create',+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ auditDesign: async () => {+ auditCalls+++ return auditCalls === 1+ ? ['Low contrast: text "Dark text on dark bg" #111122 on background #090B1A is 1.0:1 (needs 3:1) — change the text fill.']+ : []+ },+ })+ // 3 tool turns; the first done was rejected by the audit gate+ expect(result.toolCalls).toBe(3)+ expect(auditCalls).toBe(2)+ expect(events.some((e) => e.type === 'observation' && e.message.includes('QUALITY AUDIT'))).toBe(true)+ const finalEvent = events[events.length - 1]+ expect(finalEvent?.type).toBe('done')+ 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 () => {+ const events: AgentEvent[] = []+ const { chat } = scriptedChat([+ turn('set_background', { kind: 'solid', from: '#090B1A' }),+ turn('add_text', { text: 'Still dark', fontSize: 40, color: '#111122' }),+ done('Done attempt 1'),+ done('Done attempt 2 — unfixable, disclosed'),+ ])+ const result = await runAgentLoop({+ chat,+ design,+ mode: 'create',+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ // the audit NEVER clears — the run must still terminate honestly+ auditDesign: async () => ['Low contrast: text "Still dark" #111122 on #090B1A is 1.0:1 (needs 3:1)'],+ })+ expect(result.toolCalls).toBe(2)+ expect(events.filter((e) => e.type === 'done').length).toBe(1)+ const finalEvent = events[events.length - 1] as { type: string; summary?: string }+ expect(finalEvent.type).toBe('done')+ expect(String(finalEvent.summary)).toContain('disclosed')+ })})// ═════════════════════════════════════════════════════════════@@ -907,3 +966,44 @@ describe('harness · wire format + context', () => {expect(s).toContain('3 page(s)')})})++describe('audit heuristics (v0.29)', () => {+ it('WCAG contrast math — white on black ≈ 21:1, dark on dark < 1.2:1', () => {+ expect(Math.round(contrastRatio('#FFFFFF', '#000000'))).toBe(21)+ expect(contrastRatio('#111122', '#090B1A')).toBeLessThan(1.2)+ expect(contrastRatio('not-a-color', '#000000')).toBe(0)+ })++ it('auditDesign flags low contrast, overflow, tiny text, overlaps and off-canvas', () => {+ const issues = auditDesign({+ width: 1080,+ height: 1080,+ background: '#090B1A',+ elements: [+ { id: 'a1', type: 'text', text: 'Dark headline', fill: '#111122', fontSize: 48, x: 0, y: 0, width: 600, height: 90 },+ { id: 'a2', type: 'text', text: 'A'.repeat(80), fill: '#FFFFFF', fontSize: 48, x: 0, y: 200, width: 600, height: 90 },+ { id: 'a3', type: 'text', text: 'tiny', fill: '#FFFFFF', fontSize: 10, x: 0, y: 400, width: 200, height: 30 },+ ],+ overlaps: ['headline × subline'],+ offCanvas: ['cta runs past the right edge'],+ colorsInUse: ['#090B1A', '#111122'],+ })+ const joined = issues.join('\n')+ expect(joined).toContain('Low contrast')+ expect(joined).toContain('may overflow')+ expect(joined).toContain('under 14')+ expect(joined).toContain('overlap')+ expect(joined).toContain('outside the canvas')+ })++ it('auditDesign falls back to the dominant color when background is absent; clean canvas → no issues', () => {+ const issues = auditDesign({+ width: 1080,+ height: 1080,+ elements: [{ id: 'b1', type: 'text', text: 'Dark', fill: '#111122', fontSize: 48, x: 0, y: 0, width: 600, height: 90 }],+ colorsInUse: ['#090B1A'],+ })+ expect(issues.join('\n')).toContain('Low contrast')+ expect(auditDesign({ width: 1080, height: 1080, background: '#FFFFFF', elements: [{ id: 'c1', type: 'text', text: 'OK', fill: '#111111', fontSize: 32, x: 0, y: 0, width: 300, height: 60 }] })).toEqual([])+ })+})diff --git a/src/lib/agent/loop.ts b/src/lib/agent/loop.tsindex 5675d28..e31a967 100644--- a/src/lib/agent/loop.ts+++ b/src/lib/agent/loop.ts@@ -45,6 +45,10 @@ export interface LoopDeps {mode: AgentMode/** the run's brief contract (extracted by the route) */brief?: DesignBrief | null+ /** v0.29: local quality audit of the latest design snapshot+ * (contrast/overlap/overflow heuristics). The loop runs ONE+ * auto-fix round on its findings before accepting done. */+ auditDesign?: () => string[] | Promise<string[]>/** skills pre-selected by the route (or auto-selected here) */skills?: DesignSkill[]/** emitted (by the route) as SSE lines */@@ -189,6 +193,8 @@ 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) */+ let auditRounds = 0/** done turns rejected by the brief gate — a model that keeps* claiming completion without fixing the unmet items must not* loop forever (LangChain's "declare it blocked" pattern). */@@ -317,6 +323,42 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {verification = 'Brief contract validated against the live canvas — all mandatory items present.'}}+ // 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.+ if ((mode === 'create' || mode === 'improve') && deps.auditDesign) {+ let issues: string[] = []+ try {+ issues = (await deps.auditDesign()) ?? []+ } catch {+ /* audit is best-effort — never block completion on it */+ }+ if (issues.length && auditRounds === 0) {+ auditRounds += 1+ const list = issues.map((i) => `· ${i}`).join('\n')+ emit({+ v: AGENT_PROTOCOL_VERSION,+ type: 'observation',+ stepIndex: steps,+ message: `QUALITY AUDIT — ${issues.length} fixable issue(s) found:\n${list}`,+ })+ messages.push({+ role: 'user',+ content: `QUALITY AUDIT before completion — the canvas has these fixable problems:\n${list}\nFix them now with concrete tool calls (contrast: change the text fill; overflow: reduce fontSize, shorten text or widen the box; overlap/off-canvas: move or resize), then emit done again with an updated summary.`,+ })+ continue+ }+ if (!issues.length) {+ verification = verification+ ? `${verification} Quality audit passed: contrast, spacing and bounds clean.`+ : '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.`+ }+ }emit({ v: AGENT_PROTOCOL_VERSION, type: 'done', summary, steps, toolCalls, verification })return { summary, steps, toolCalls, findings: turn.findings, plan: turn.plan, verification }}diff --git a/src/lib/ai/vision-retry.ts b/src/lib/ai/vision-retry.tsnew file mode 100644index 0000000..52885f7--- /dev/null+++ b/src/lib/ai/vision-retry.ts@@ -0,0 +1,30 @@+/**+ * v0.29: vision-slot call hardening.+ *+ * NVIDIA NIM's media screening occasionally rejects a perfectly valid+ * data URL with 422 "media could not be screened/downloaded" — a+ * transient service blip, not a client error (verified: the SAME data+ * URL fails once then succeeds). One immediate retry, then a final+ * attempt with ZAI_VISION_FALLBACK_MODEL (e.g. the omni model, which+ * takes data URLs through a different path) if it is configured.+ */+export async function visionChatWithRetry<T>(+ call: (model: string | undefined) => Promise<T>,+ primaryModel: string | undefined,+): Promise<T> {+ const isScreeningError = (e: unknown) =>+ /could not be (screened|downloaded)/i.test(String((e as Error | undefined)?.message ?? e))+ try {+ return await call(primaryModel)+ } catch (e) {+ if (!isScreeningError(e)) throw e+ }+ try {+ return await call(primaryModel)+ } catch (e) {+ if (!isScreeningError(e)) throw e+ const fallback = process.env.ZAI_VISION_FALLBACK_MODEL?.trim()+ if (fallback && fallback !== primaryModel) return await call(fallback)+ throw e+ }+}