Skip to content

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

feat(v0.33.0): the design-quality architecture — server-resolved assets, the visual-feature contract, asset-visibility audit, the native effects surface

Ashiq Hussain Mirc6f8fd069cf1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4c7b277..1f96121 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,74 @@
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/).
+### feat(v0.33.0): the design-quality architecture — server-resolved assets, the visual-feature contract, asset-visibility audit, the native effects surface
+
+One brief, one review ("a program that places elements at
+coordinates that passes geometry tests"), five deterministic root
+causes, all fixed at the architecture level — no poster-specific
+hardcoding:
+
+- **Assets resolve SERVER-SIDE (fail-closed).** add_icon,
+ add_illustration and add_sticker passed raw queries to the client
+ and hoped; unknown concepts were acked {ok:true} while NOTHING
+ was created (the NEON 2027 poster claimed four stickers — two
+ never existed: there is no "robot" in the 562-icon pack). The
+ offline packs are pure data: the server resolves queries
+ (add_sticker now reaches the 160+ VECTOR sticker library,
+ add_icon the 562 icons, add_illustration the 48 illustrations),
+ REJECTS unknowns with real resolvable examples, and passes the
+ resolved asset + the model's OWN geometry — icons/illustrations/
+ stickers land exactly where the model placed them (the old path
+ default-centred every icon and ignored x/y/size). The client
+ additionally acks no-op result strings as failures (a no-op is
+ not success), exhaustively pattern-matched so "no overlaps —
+ layout is clean" still acks ok.
+- **The visual-feature contract.** The brief contract knew three
+ composite kinds; the NEON brief's asks (central illustration,
+ floating stickers, call to action, gradients, shadows) extracted
+ NOTHING — "brief validated" was true-and-empty. Six new
+ checkable feature kinds — illustration (a ≥10% focal element;
+ small icons never qualify), stickers (with counts), cta-button
+ (a filled shape + short actionable text; bare text never
+ passes), gradients, shadows, text-effects — are extracted as
+ MANDATORY requirements and validated against real canvas state,
+ including the new gradient/textEffect/shadow context fields.
+- **The audit sees non-text elements.** Present ≠ visible now holds
+ for art too: stickers/icons/illustrations/photos entirely
+ off-canvas, sliver-sized, or fully covered by a higher opaque
+ element are reported as defects.
+- **The native effects surface — exposed (and actually applied).**
+ The editor has supported gradient fills (shapes + text),
+ per-element shadows and neon/glow/drop text effects since v0.3;
+ the agent's tool surface never exposed them, so "use gradients,
+ shadows, creative typography" briefs were physically impossible
+ to satisfy. add_shape takes gradientFrom/gradientTo/
+ gradientAngle, add_text takes effect ("neon", "glow"…),
+ update_elements patches gradient/textEffect/shadow — and now
+ actually APPLIES rotation, opacity, italic, underline, strike,
+ uppercase, align, curve, flipH/V, brightness, contrast,
+ saturation, locked, visible (previously validated server-side,
+ then silently dropped by the client whitelist).
+- **Composition intelligence in the plan.** The create/improve
+ prompt REQUIRES: one dominant focal element (≥10% of the page —
+ never a text-only page), layered background treatment
+ (set_background + low-opacity shapes or a gradient band), a
+ composite CTA button (filled rounded rect + text, never bare
+ text), placed accents (x/y/size on every sticker/icon), and
+ theme effects on futuristic/neon briefs. The skills playbooks
+ teach the same with the concrete tool calls.
+- **Transient-provider retry.** Upstream 429s and network blips
+ killed live runs mid-build and shipped degraded, half-built
+ posters; the route's chat call retries transient errors ×2 with
+ backoff before surfacing them.
+
+Harness: +18 regression tests (server-side resolution, geometry
+passthrough, unknown-concept rejections, the effects surface, the
+feature contract including the bare-CTA failure and the ≥10% focal
+threshold, the asset-visibility audit, and the full-circle
+honesty: done with unmet stickers → the resolved add_sticker →
+accepted only then) — 1,777/1,777 expected.
+
### 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:
diff --git a/src/app/api/ai/agent/route.ts b/src/app/api/ai/agent/route.ts
index b5ae534..a6abaa4 100644
--- a/src/app/api/ai/agent/route.ts
+++ b/src/app/api/ai/agent/route.ts
@@ -228,22 +228,39 @@ async function __canvix_post(req: NextRequest) {
}
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 ?? '')
+ // v0.33 · transient-provider retry. Upstream 429s and network
+ // blips killed live runs mid-build ("Applied work is kept —
+ // retry to continue") and the user received degraded, half-
+ // built posters. A bounded retry with backoff (×2: 1.5s, 3s)
+ // rides out bursts before a transient error surfaces.
+ const callWithRetry = async (): Promise<string> => {
+ for (let tries = 0; ; tries++) {
+ try {
+ const completion = await callJson(jsonModeLive)
+ return String(completion.choices[0]?.message?.content ?? '')
+ } catch (e) {
+ const msg = String((e as Error | undefined)?.message ?? e)
+ // json-mode fallback (unchanged v0.32 behaviour): a gateway
+ // that rejects response_format degrades once and the
+ // choice is remembered for the whole run
+ 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
+ continue
+ }
+ const transient =
+ /\b(?:429|500|502|503|504)\b|rate.?limit|too many requests|fetch failed|network|econnreset|etimedout|socket hang up|aborted/i.test(
+ msg,
+ )
+ if (!transient || tries >= 2) throw e
+ await new Promise((r) => setTimeout(r, 1500 * (tries + 1)))
+ }
}
- throw e
}
+ return callWithRetry()
}
// ── 1. classify the mode (heuristic first, model when unsure) ──
diff --git a/src/components/editor/apps/AssistantApp.tsx b/src/components/editor/apps/AssistantApp.tsx
index 26f3b11..fa54c0b 100644
--- a/src/components/editor/apps/AssistantApp.tsx
+++ b/src/components/editor/apps/AssistantApp.tsx
@@ -76,6 +76,16 @@ const SUGGESTIONS = [
const READ_ONLY_MODES: AgentMode[] = ['review', 'explain', 'plan', 'discuss']
+/** v0.33: the NO-OP prefixes applyDesignAction returns (as strings,
+ * never throws) for unresolved assets and malformed actions. A no-op
+ * must FAIL the ack: the NEON 2027 poster claimed four stickers while
+ * two never existed because these strings were acked {ok:true} and
+ * the loop counted them as applied. Deliberately exhaustive, not a
+ * blanket /^No / — "No overlaps or off-canvas elements found — the
+ * layout is clean" is a SUCCESS message and must keep acking ok. */
+const NO_ACK_MSG_RE =
+ /^(Bad |Grouping needs|Sticker missing|Table needs|Chart needs|Unknown |QR generation failed|Nothing|No QR |No elements from this app|No font specified|No group elements|No icon|No illustration|No image|No language|No matching|No page to fix|No photo|No size change|No text|No video)/
+
/** Flatten elements (groups included). */
function flatElements(els: AnyElement[], out: AnyElement[] = []): AnyElement[] {
for (const el of els) {
@@ -125,11 +135,22 @@ function buildDesignContext() {
base.fontSize = Math.round(t.fontSize)
base.bold = t.bold
base.fontFamily = t.fontFamily
+ if (t.effect && t.effect !== 'none') base.textEffect = t.effect
const w = measureText(t)
if (w !== undefined) base.measuredWidth = w
} else if ('fill' in el) {
base.fill = (el as { fill: string }).fill
}
+ // v0.33: the native effects surface on the context — the brief's
+ // feature validation (gradients/effects/shadows) and the audit's
+ // visibility checks consume these; before, nothing could see them
+ // and "brief validated" said nothing about the visual features.
+ if ('fillGradient' in el && (el as { fillGradient?: unknown }).fillGradient) base.hasGradient = true
+ if ('effect' in el) {
+ const eff = (el as { effect?: unknown }).effect
+ if (typeof eff === 'string' && eff !== 'none') base.textEffect = eff
+ }
+ if (el.shadow?.enabled) base.hasShadow = true
if ('stroke' in el && typeof (el as { stroke?: unknown }).stroke === 'string') {
const stroke = (el as { stroke: string }).stroke
if (stroke.trim()) base.stroke = stroke
@@ -273,6 +294,12 @@ function computeBriefValidation(brief: DesignBrief): { satisfied: boolean; unmet
...( 'fill' in e && typeof (e as { fill?: unknown }).fill === 'string' ? { fill: (e as { fill: string }).fill } : {}),
...('stroke' in e && typeof (e as { stroke?: unknown }).stroke === 'string' ? { stroke: (e as { stroke: string }).stroke } : {}),
...(e.type === 'text' ? { text: (e as TextElement).text } : {}),
+ // v0.33: the effects surface — the feature validation reads these
+ ...('fillGradient' in e && (e as { fillGradient?: unknown }).fillGradient ? { hasGradient: true } : {}),
+ ...(e.shadow?.enabled ? { hasShadow: true } : {}),
+ ...('effect' in e && typeof (e as { effect?: unknown }).effect === 'string' && (e as { effect?: string }).effect !== 'none'
+ ? { textEffect: (e as { effect?: string }).effect }
+ : {}),
}))
const result = validateBrief(brief, {
texts,
@@ -322,6 +349,10 @@ export function AssistantApp({ onClose }: AppPanelProps) {
continue
}
lastMsg = await applyDesignAction(a)
+ // v0.33: a NO-OP IS NOT SUCCESS (see NO_ACK_MSG_RE above).
+ if (NO_ACK_MSG_RE.test(lastMsg)) {
+ return { ok: false, message: lastMsg }
+ }
} catch (e) {
return { ok: false, message: e instanceof Error ? e.message : 'Action failed' }
}
diff --git a/src/lib/agent/audit.ts b/src/lib/agent/audit.ts
index 6c7d65c..f2cfaef 100644
--- a/src/lib/agent/audit.ts
+++ b/src/lib/agent/audit.ts
@@ -341,6 +341,47 @@ export function auditDesign(
}
}
+ // 12. ASSET VISIBILITY (v0.33): present is not visible — for art
+ // too. The text-obscured check predates this; the NEON 2027
+ // poster shipped claimed stickers nobody could see, and
+ // "quality audit passed" said nothing because no stage ever
+ // looked at non-text elements. Stickers/icons/illustrations/
+ // photos that are off-canvas, sliver-sized or fully covered by
+ // a higher opaque element are reported like any other defect.
+ if (d.width && d.height) {
+ let assetHits = 0
+ const art = els.filter(
+ (e) => e && e.type !== 'text' && (e.width ?? 0) > 0 && (e.height ?? 0) > 0,
+ )
+ for (const a of art) {
+ const b = box(a)
+ const label = `${a.type}#${a.id}${a.text ? ` ("${String(a.text).slice(0, 16)}")` : a.name ? ` ("${a.name.slice(0, 16)}")` : ''}`
+ let problem: string | null = null
+ if (b.x + b.w <= 0 || b.y + b.h <= 0 || b.x >= d.width! || b.y >= d.height!) {
+ problem = `is entirely OFF the canvas (@${Math.round(b.x)},${Math.round(b.y)} ${Math.round(b.w)}x${Math.round(b.h)}) — move it inside the page`
+ } else if (b.w < 8 || b.h < 8) {
+ problem = `is a sliver (${Math.round(b.w)}x${Math.round(b.h)}px) — resize it to be visible`
+ } else {
+ // fully covered by a HIGHER opaque element (later = in front)
+ const idx = els.indexOf(a)
+ for (let i = idx + 1; i < els.length; i++) {
+ const cover = els[i]
+ if (!cover || cover.type === 'text') continue
+ const fill = parseColor((cover as { fill?: unknown }).fill)
+ if (!fill || fill.a < 0.9) continue
+ if (coverage(a, cover) >= 0.95) {
+ problem = `is fully COVERED by ${cover.type}#${cover.id} (z-order) — reorder it to the front (update_elements visible:true + move) or move it`
+ break
+ }
+ }
+ }
+ if (problem) {
+ assetHits += 1
+ if (assetHits <= 3) issues.push(`${label} ${problem}.`)
+ }
+ }
+ }
+
return issues.slice(0, 12)
}
diff --git a/src/lib/agent/brief.ts b/src/lib/agent/brief.ts
index e0c80a6..fff59a0 100644
--- a/src/lib/agent/brief.ts
+++ b/src/lib/agent/brief.ts
@@ -27,8 +27,17 @@ export interface BriefConstraint {
* These are REQUIREMENTS, not decoration — the validator checks that
* the corresponding native, editable elements actually exist. */
export interface RequiredFeature extends BriefConstraint {
- kind: 'editor-mockup' | 'feature-cards' | 'glassmorphism'
- /** for feature-cards: how many cards the user asked for */
+ kind:
+ | 'editor-mockup'
+ | 'feature-cards'
+ | 'glassmorphism'
+ | 'illustration'
+ | 'stickers'
+ | 'cta-button'
+ | 'gradients'
+ | 'shadows'
+ | 'text-effects'
+ /** for feature-cards/stickers: how many the user asked for */
count?: number
/** human label for prompts and unmet messages */
label: string
@@ -191,6 +200,62 @@ export function extractBrief(message: string, pageWidth?: number, pageHeight?: n
})
}
+ // v0.33 · the visual-feature contract — the NEON 2027 lesson:
+ // "brief contract validated" was true-and-empty while the poster
+ // had no focal illustration, no CTA button, no gradients and two
+ // of four promised stickers missing, because the contract only
+ // knew three composite kinds. The named visual asks of a brief are
+ // now REQUIREMENTS the validator checks against real elements.
+ if (/\billustrations?\b/i.test(m) && !/\bno\s+illustrations?\b/i.test(m)) {
+ requiredFeatures.push({
+ tier: 'mandatory',
+ kind: 'illustration',
+ label: 'a dominant illustration (a large illustration/photo/graphic focal element, ≥10% of the page — add_illustration / add_stock_photo)',
+ })
+ }
+ const stickerCount =
+ lowerText.match(/(\d+|two|three|four|five|six|seven|eight)\s+(?:floating\s+|vector\s+)?(?:emoji\s+)?stickers?\b/) ??
+ (/\bstickers?\b/i.test(m) && !/\bno\s+stickers?\b/i.test(m) ? [undefined, undefined] : null)
+ if (stickerCount) {
+ const words: Record<string, number> = { two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8 }
+ const named = stickerCount[1]
+ const n = named ? (/^\d+$/.test(named) ? Number(named) : (words[named] ?? 2)) : 2
+ requiredFeatures.push({
+ tier: 'mandatory',
+ kind: 'stickers',
+ count: Math.min(Math.max(n, 1), 8),
+ label: `${Math.min(Math.max(n, 1), 8)} floating stickers (add_sticker — the 160+ vector library or emoji glyphs)`,
+ })
+ }
+ if (/\b(?:call\s+to\s+action|cta)\b/i.test(m)) {
+ requiredFeatures.push({
+ tier: 'mandatory',
+ kind: 'cta-button',
+ label: 'a prominent call-to-action (a filled rounded shape behind a short actionable text — a button, never bare text)',
+ })
+ }
+ if (/\bgradients?\b/i.test(m)) {
+ requiredFeatures.push({
+ tier: 'mandatory',
+ kind: 'gradients',
+ label: 'gradient fills (add_shape gradientFrom/gradientTo or update_elements gradientFrom/To)',
+ })
+ }
+ if (/\bshadows?\b/i.test(m)) {
+ requiredFeatures.push({
+ tier: 'mandatory',
+ kind: 'shadows',
+ label: 'shadow effects (update_elements shadowColor/shadowBlur)',
+ })
+ }
+ if (/\b(?:neon|glow(?:ing)?)\b/i.test(m) && /\b(?:text|title|headline|typography|theme|poster|futuristic|festival)\b/i.test(m)) {
+ requiredFeatures.push({
+ tier: 'mandatory',
+ kind: 'text-effects',
+ label: 'creative text effects (neon/glow on the headline — add_text effect:"neon" or update_elements textEffect)',
+ })
+ }
+
// explicit dimensions
const dims = m.match(DIMENSIONS_RE)
let dimensions: DesignBrief['dimensions'] | undefined
@@ -272,6 +337,11 @@ export interface BriefElementLike {
fill?: string
stroke?: string
text?: string
+ /** v0.33: the effects surface — the visual-feature validation
+ * (gradients / text effects / shadows) reads these. */
+ hasGradient?: boolean
+ hasShadow?: boolean
+ textEffect?: string
}
/** Parse "#RRGGBB" or "rgba(r,g,b,a)" → {r,g,b,a} (a defaults 1); null unparseable.
@@ -303,12 +373,15 @@ function centerInside(el: BriefElementLike, host: BriefElementLike): boolean {
)
}
-/** Structural validation of the composite deliverables (v0.29.3).
- * Heuristics on purpose — a FALSE PASS here hides a missing
- * deliverable; a false failure only costs one extra build step. */
+/** Structural validation of the composite deliverables (v0.29.3,
+ * extended v0.33 with the visual-feature kinds). Heuristics on
+ * purpose — a FALSE PASS here hides a missing deliverable; a false
+ * failure only costs one extra build step. */
function validateFeatures(
features: RequiredFeature[],
els: BriefElementLike[],
+ pageW: number,
+ pageH: number,
): { label: string; found: boolean }[] {
const rects = els.filter((e) => e.type === 'rect' && (e.width ?? 0) > 0 && (e.height ?? 0) > 0)
const texts = els.filter((e) => e.type === 'text' && e.text)
@@ -348,6 +421,43 @@ function validateFeatures(
})
const bordered = glass.some((e) => typeof e.stroke === 'string' && e.stroke.trim().length > 0)
out.push({ label: f.label, found: glass.length >= 2 && bordered })
+ } else if (f.kind === 'illustration') {
+ // v0.33: a focal element — image (illustrations/photos),
+ // sticker or chart covering ≥10% of the page. Small icons and
+ // plain rects never qualify: a focal point must anchor the
+ // composition, not decorate it.
+ const min = 0.1 * pageW * pageH
+ const found = els.some(
+ (e) => ['image', 'sticker', 'chart'].includes(e.type) && (e.width ?? 0) * (e.height ?? 0) >= min,
+ )
+ out.push({ label: f.label, found })
+ } else if (f.kind === 'stickers') {
+ const need = f.count ?? 2
+ out.push({ label: f.label, found: els.filter((e) => e.type === 'sticker').length >= need })
+ } else if (f.kind === 'cta-button') {
+ // v0.33: the button pattern — a short actionable text sitting
+ // on a filled shape. Bare text never passes: the NEON 2027
+ // poster's "GET TICKETS" was plain text on a flat background.
+ const ctaVerbs = /^(?:get|buy|register|book|join|subscribe|start|shop|sign\s?up|reserve|order|download|rsvp|grab|claim|tickets)\b/i
+ const buttons = rects.filter((r) => {
+ const fill = parseColor(r.fill)
+ return (r.width ?? 0) >= 80 && (r.height ?? 0) >= 32 && fill !== null && fill.a >= 0.35
+ })
+ const found = texts.some((t) => {
+ const words = (t.text ?? '').trim().split(/\s+/)
+ if (words.length > 6 || words.length === 0) return false
+ return ctaVerbs.test((t.text ?? '').trim()) && buttons.some((r) => centerInside(t, r))
+ })
+ out.push({ label: f.label, found })
+ } else if (f.kind === 'gradients') {
+ out.push({ label: f.label, found: els.some((e) => e.hasGradient) })
+ } else if (f.kind === 'shadows') {
+ out.push({ label: f.label, found: els.some((e) => e.hasShadow) })
+ } else if (f.kind === 'text-effects') {
+ out.push({
+ label: f.label,
+ found: els.some((e) => e.type === 'text' && !!e.textEffect && e.textEffect !== 'none'),
+ })
}
}
return out
@@ -394,7 +504,7 @@ export function validateBrief(
})
let features: BriefValidationResult['checked']['features']
if (brief.requiredFeatures?.length && state.elements?.length) {
- features = validateFeatures(brief.requiredFeatures, state.elements)
+ features = validateFeatures(brief.requiredFeatures, state.elements, state.width, state.height)
for (const f of features) {
if (!f.found) unmet.push(`Required element missing: ${f.label} — build it from NATIVE elements (rect panels, semi-transparent fills, borders, text).`)
}
diff --git a/src/lib/agent/context.ts b/src/lib/agent/context.ts
index 0eda674..83e4572 100644
--- a/src/lib/agent/context.ts
+++ b/src/lib/agent/context.ts
@@ -28,6 +28,12 @@ export interface AgentElementCtx {
fill?: string
/** v0.29.3: border color (glassmorphism/feature-card validation) */
stroke?: string
+ /** v0.33: the native-effects surface — the feature contract
+ * (gradients / text effects / shadows) validates against these;
+ * the audit's visibility checks read them too. */
+ hasGradient?: boolean
+ hasShadow?: boolean
+ textEffect?: string
fontSize?: number
bold?: boolean
fontFamily?: string
@@ -85,6 +91,11 @@ function elementLine(e: AgentElementCtx, selected: boolean): string {
if (e.text) parts.push(`text="${e.text.slice(0, 60).replace(/\n/g, ' ')}"`)
if (e.fill) parts.push(e.fill)
if (e.stroke) parts.push(`border:${e.stroke}`)
+ // v0.33: the effects on each element — the model sees (and can
+ // verify) gradients, text effects and shadows in the page state.
+ if (e.hasGradient) parts.push('gradient')
+ if (e.textEffect) parts.push(`effect:${e.textEffect}`)
+ if (e.hasShadow) parts.push('shadow')
if (e.fontSize) parts.push(`${Math.round(e.fontSize)}px`)
if (e.measuredWidth && e.text) parts.push(`measured:${Math.round(e.measuredWidth)}px`)
if (e.bold) parts.push('bold')
diff --git a/src/lib/agent/harness.test.ts b/src/lib/agent/harness.test.ts
index 064c8c7..0a0dfc3 100644
--- a/src/lib/agent/harness.test.ts
+++ b/src/lib/agent/harness.test.ts
@@ -2853,3 +2853,339 @@ describe('v0.32.8 · the second-strike recovery note (the "fix issues" strike-ou
expect(events[events.length - 1]?.type).toBe('done')
})
})
+
+// ═════════════════════════════════════════════════════════════
+// v0.33 · the design-quality architecture — the NEON 2027 review
+// ("a coordinate-placement script that passes geometry tests")
+// traced to deterministic root causes:
+// · asset tools acked ok while creating NOTHING (concepts
+// resolved client-side, no-op strings acked as success);
+// · icons that DID resolve landed at default centres — the
+// model's geometry was ignored;
+// · the native gradients / shadows / neon-glow text effects were
+// never exposed to the agent, so "use gradients, shadows"
+// briefs were physically impossible to satisfy;
+// · the feature contract knew only 3 composite kinds —
+// illustration/stickers/CTA/gradients extracted NOTHING, so
+// "brief validated" was true-and-empty;
+// · the audit never looked at non-text elements (present ≠
+// visible).
+// ═════════════════════════════════════════════════════════════
+
+describe('v0.33 · assets resolve server-side — fail-closed, placed exactly', () => {
+ const call33 = (name: string, args: Record<string, unknown>) =>
+ AGENT_TOOL_MAP.get(name)!.sanitize(args, ctx)
+
+ it('add_sticker resolves the 160+ vector library and passes the model geometry', () => {
+ const r = call33('add_sticker', { query: 'sparkle', x: 100, y: 200, size: 160 })
+ expect(r.ok).toBe(true)
+ if (!r.ok) return
+ const action = r.actions[0] as {
+ type: string
+ sticker?: { id: string; name: string; svg: string }
+ x?: number
+ y?: number
+ size?: number
+ }
+ expect(action.type).toBe('addPackSticker')
+ expect(action.sticker?.svg?.startsWith('<svg')).toBe(true)
+ expect(action.x).toBe(100)
+ expect(action.y).toBe(200)
+ expect(action.size).toBe(160)
+ })
+
+ it('add_sticker still accepts emoji glyphs (back-compat: the emoji arg key)', () => {
+ const r = call33('add_sticker', { emoji: '🚀', x: 10, y: 20 })
+ expect(r.ok).toBe(true)
+ if (!r.ok) return
+ expect((r.actions[0] as { type: string }).type).toBe('addSticker')
+ expect((r.actions[0] as { emoji?: string }).emoji).toBe('🚀')
+ })
+
+ it('the NEON incident shape: an unknown sticker CONCEPT is rejected with resolvable examples', () => {
+ const r = call33('add_sticker', { query: 'laser dragon hologram' })
+ expect(r.ok).toBe(false)
+ if (r.ok) return
+ expect(r.error).toContain('No sticker matches')
+ expect(r.error).toContain('star')
+ })
+
+ it('add_icon resolves server-side and carries x/y/size — no more default-centred icons', () => {
+ const r = call33('add_icon', { query: 'rocket', x: 40, y: 60, size: 220, stroke: '#02C0CC' })
+ expect(r.ok).toBe(true)
+ if (!r.ok) return
+ const action = r.actions[0] as {
+ type: string
+ d?: string
+ name?: string
+ x?: number
+ y?: number
+ size?: number
+ stroke?: string
+ }
+ expect(action.type).toBe('addIcon')
+ expect(action.d?.length ?? 0).toBeGreaterThan(20)
+ expect(action.name).toBeTruthy()
+ expect(action.x).toBe(40)
+ expect(action.y).toBe(60)
+ expect(action.size).toBe(220)
+ expect(action.stroke).toBe('#02c0cc')
+ })
+
+ it('the NEON incident: an icon concept the pack lacks is rejected with real alternatives', () => {
+ const r = call33('add_icon', { query: 'robot' })
+ expect(r.ok).toBe(false)
+ if (r.ok) return
+ expect(r.error).toContain('No icon matches')
+ expect(r.error).toContain('add_illustration')
+ })
+
+ it('add_illustration resolves and carries geometry', () => {
+ const r = call33('add_illustration', { query: 'rocket launch', x: 300, y: 400, size: 500 })
+ expect(r.ok).toBe(true)
+ if (!r.ok) return
+ const action = r.actions[0] as {
+ type: string
+ svg?: string
+ name?: string
+ x?: number
+ y?: number
+ size?: number
+ }
+ expect(action.type).toBe('addIllustration')
+ expect(action.svg?.startsWith('<svg')).toBe(true)
+ expect(action.x).toBe(300)
+ expect(action.size).toBe(500)
+ })
+
+ it('an unknown illustration is rejected with the pack themes', () => {
+ const r = call33('add_illustration', { query: 'cyberpunk skyline neon city' })
+ expect(r.ok).toBe(false)
+ if (r.ok) return
+ expect(r.error).toContain('No illustration matches')
+ expect(r.error).toContain('tech')
+ })
+
+ it('the resolvers never throw on adversarial args (registry discipline holds)', () => {
+ const cases: [string, Record<string, unknown>][] = [
+ ['add_sticker', { query: { nested: true } }],
+ ['add_sticker', { query: '' }],
+ ['add_sticker', { query: 42 }],
+ ['add_icon', { query: null }],
+ ['add_illustration', { query: ' ' }],
+ ]
+ for (const [name, args] of cases) {
+ let r: SanitizeResult | null = null
+ expect(() => {
+ r = call33(name, args)
+ }).not.toThrow()
+ expect(r).toBeTruthy()
+ }
+ })
+})
+
+describe('v0.33 · the native effects surface — gradients, text effects, shadows', () => {
+ const call33 = (name: string, args: Record<string, unknown>) =>
+ AGENT_TOOL_MAP.get(name)!.sanitize(args, ctx)
+
+ it('add_shape takes a gradient; a half-given gradient is an error', () => {
+ const ok = call33('add_shape', {
+ shape: 'rect', x: 0, y: 0, width: 400, height: 200,
+ gradientFrom: '#02C0CC', gradientTo: '#7630D7', gradientAngle: 45,
+ })
+ expect(ok.ok).toBe(true)
+ if (ok.ok) {
+ const action = ok.actions[0] as { gradient?: { type: string; from: string; to: string; angle: number } }
+ expect(action.gradient).toEqual({ type: 'linear', from: '#02c0cc', to: '#7630d7', angle: 45 })
+ }
+ const bad = call33('add_shape', { shape: 'rect', x: 0, y: 0, width: 10, height: 10, gradientFrom: '#02C0CC' })
+ expect(bad.ok).toBe(false)
+ })
+
+ it('add_text takes a native text effect (neon/glow/…)', () => {
+ const r = call33('add_text', { text: 'NEON 2027', fontSize: 96, color: '#02C0CC', effect: 'neon' })
+ expect(r.ok).toBe(true)
+ if (r.ok) expect((r.actions[0] as { effect?: string }).effect).toBe('neon')
+ const bad = call33('add_text', { text: 'X', effect: 'sparkly' })
+ expect(bad.ok).toBe(false)
+ })
+
+ it('update_elements patches gradient / textEffect / shadow — validated, never silent', () => {
+ const g = call33('update_elements', { ids: ['txt-1'], patch: { gradientFrom: '#02C0CC', gradientTo: '#7630D7', gradientAngle: 90 } })
+ expect(g.ok).toBe(true)
+ if (g.ok) {
+ const patch = (g.actions[0] as { patch?: Record<string, unknown> }).patch
+ expect(patch?.gradient).toEqual({ type: 'linear', from: '#02c0cc', to: '#7630d7', angle: 90 })
+ }
+ const eff = call33('update_elements', { ids: ['txt-1'], patch: { textEffect: 'glow' } })
+ expect(eff.ok).toBe(true)
+ if (eff.ok) {
+ expect((eff.actions[0] as { patch?: Record<string, unknown> }).patch?.textEffect).toBe('glow')
+ }
+ const sh = call33('update_elements', { ids: ['txt-1'], patch: { shadowColor: '#000000', shadowBlur: 24, shadowOffsetY: 8 } })
+ expect(sh.ok).toBe(true)
+ if (sh.ok) {
+ const shadow = (sh.actions[0] as { patch?: { shadow?: Record<string, unknown> } }).patch?.shadow
+ expect(shadow?.enabled).toBe(true)
+ expect(shadow?.blur).toBe(24)
+ expect(shadow?.offsetY).toBe(8)
+ }
+ expect(call33('update_elements', { ids: ['txt-1'], patch: { gradientFrom: '#02C0CC' } }).ok).toBe(false)
+ expect(call33('update_elements', { ids: ['txt-1'], patch: { textEffect: 'sparkly' } }).ok).toBe(false)
+ })
+})
+
+describe('v0.33 · the visual-feature contract — brief asks become checkable requirements', () => {
+ it('the NEON 2027 brief extracts illustration, stickers, CTA, gradients, shadows and text effects', async () => {
+ const { extractBrief } = await import('./brief')
+ const brief = extractBrief(
+ 'Create a professional promotional poster for a futuristic technology festival called NEON 2027. Use editable text, gradients, shapes, shadows and creative typography. Include a central technology illustration, floating stickers, event information and a prominent call to action.',
+ 1240,
+ 1754,
+ )
+ const kinds = (brief.requiredFeatures ?? []).map((f) => f.kind)
+ expect(kinds).toContain('illustration')
+ expect(kinds).toContain('stickers')
+ expect(kinds).toContain('cta-button')
+ expect(kinds).toContain('gradients')
+ expect(kinds).toContain('shadows')
+ expect(kinds).toContain('text-effects')
+ })
+
+ it('the CTA check: bare text FAILS, a filled button shape + actionable text PASSES', async () => {
+ const { extractBrief, validateBrief } = await import('./brief')
+ const brief = extractBrief('A poster with a prominent call to action')
+ const bare = validateBrief(brief, {
+ texts: ['GET TICKETS NOW'],
+ colors: [],
+ width: 1240,
+ height: 1754,
+ elements: [{ type: 'text', text: 'GET TICKETS NOW', x: 400, y: 900, width: 400, height: 60 }],
+ })
+ expect(bare.satisfied).toBe(false)
+ expect(bare.unmet.some((u) => u.includes('call-to-action'))).toBe(true)
+ const button = validateBrief(brief, {
+ texts: ['GET TICKETS NOW'],
+ colors: [],
+ width: 1240,
+ height: 1754,
+ elements: [
+ { type: 'rect', x: 320, y: 880, width: 600, height: 120, fill: '#02C0CC' },
+ { type: 'text', text: 'GET TICKETS NOW', x: 400, y: 900, width: 400, height: 60 },
+ ],
+ })
+ expect(button.checked.features?.some((f) => f.found)).toBe(true)
+ expect(button.satisfied).toBe(true)
+ })
+
+ it('the illustration check: small icons do NOT qualify, a ≥10% focal element does', async () => {
+ const { extractBrief, validateBrief } = await import('./brief')
+ const brief = extractBrief('a poster with a central technology illustration')
+ const small = validateBrief(brief, {
+ texts: [], colors: [], width: 1000, height: 1000,
+ elements: [{ type: 'image', x: 480, y: 480, width: 120, height: 120 }], // 1.4%
+ })
+ expect(small.satisfied).toBe(false)
+ const focal = validateBrief(brief, {
+ texts: [], colors: [], width: 1000, height: 1000,
+ elements: [{ type: 'image', x: 300, y: 300, width: 400, height: 400 }], // 16%
+ })
+ expect(focal.satisfied).toBe(true)
+ })
+
+ it('gradients/shadows/features validate against the real effects fields', async () => {
+ const { extractBrief, validateBrief } = await import('./brief')
+ const brief = extractBrief('use gradients and shadows and floating stickers')
+ const withEffects = validateBrief(brief, {
+ texts: [], colors: [], width: 1000, height: 1000,
+ elements: [
+ { type: 'rect', x: 0, y: 0, width: 200, height: 200, hasGradient: true, hasShadow: true },
+ { type: 'sticker', x: 0, y: 300, width: 100, height: 100 },
+ { type: 'sticker', x: 200, y: 300, width: 100, height: 100 },
+ ],
+ })
+ expect(withEffects.satisfied).toBe(true)
+ })
+})
+
+describe('v0.33 · the audit sees non-text elements — present is not visible', () => {
+ it('a sticker fully covered by a higher opaque shape is reported', async () => {
+ const { auditDesign } = await import('./audit')
+ const issues = auditDesign({
+ name: 't', width: 1080, height: 1080, pageCount: 1, currentPageIndex: 0,
+ background: '#090B1A',
+ elements: [
+ { id: 'st-1', type: 'sticker', x: 100, y: 100, width: 160, height: 160, fill: '#FFFFFF' },
+ { id: 'cover-1', type: 'rect', x: 0, y: 0, width: 1080, height: 1080, fill: '#000000' },
+ ],
+ colorsInUse: [], otherPages: [],
+ } as never)
+ expect(issues.some((i) => i.includes('sticker#st-1') && i.includes('COVERED'))).toBe(true)
+ })
+
+ it('an off-canvas sticker is reported', async () => {
+ const { auditDesign } = await import('./audit')
+ const issues = auditDesign({
+ name: 't', width: 1080, height: 1080, pageCount: 1, currentPageIndex: 0,
+ background: '#090B1A',
+ elements: [{ id: 'st-2', type: 'sticker', x: 1200, y: 100, width: 160, height: 160, fill: '#FFFFFF' }],
+ colorsInUse: [], otherPages: [],
+ } as never)
+ expect(issues.some((i) => i.includes('OFF the canvas'))).toBe(true)
+ })
+})
+
+describe('v0.33 · the full-circle honesty: a run cannot claim stickers it never built', () => {
+ it('done is bounced with the unmet feature, then the resolved add_sticker satisfies it', async () => {
+ const events: AgentEvent[] = []
+ let appliedSticker = 0
+ const { chat } = scriptedChat([
+ turn('set_background', { kind: 'solid', from: '#0A0A1A' }),
+ turn('plan_layout', { background: '#0A0A1A', sections: [{ name: 'hero', y: 65, height: 300, contains: 'headline + focal' }, { name: 'cta', y: 805, height: 150, contains: 'button' }] }),
+ turn('add_text', { text: 'NEON 2027', fontSize: 96, color: '#02C0CC' }),
+ done('Built with four floating stickers'), // bounced: no stickers on the canvas
+ turn('add_sticker', { query: 'sparkle', x: 120, y: 500, size: 140 }), // resolves → applied
+ done('Built, stickers added'), // accepted
+ ])
+ const result = await runAgentLoop({
+ chat,
+ design: {
+ name: 'Empty poster', width: 1080, height: 1080, pageCount: 1,
+ currentPageIndex: 0, elements: [], colorsInUse: [], otherPages: [],
+ },
+ mode: 'create',
+ request: 'Create a poster for NEON 2027 with floating stickers',
+ // the route extracts the brief from the request; the loop consumes
+ // it via deps — the stickers feature is the contract here
+ brief: {
+ requiredTexts: [],
+ requiredColors: [],
+ requiredFeatures: [
+ { tier: 'mandatory', kind: 'stickers', count: 2, label: '2 floating stickers (add_sticker — the 160+ vector library or emoji glyphs)' },
+ ],
+ restrictions: [],
+ notes: [],
+ source: 'user',
+ },
+ emit: (e) => events.push(e),
+ // 1 = set_background, 2 = add_text, 3 = add_sticker (the resolved
+ // vector sticker that satisfies the feature contract)
+ awaitApply: async () => {
+ appliedSticker += 1
+ return { ok: true }
+ },
+ validateBriefOnClient: async () =>
+ appliedSticker >= 3
+ ? { satisfied: true, unmet: [] }
+ : {
+ satisfied: false,
+ unmet: [
+ 'Required element missing: 2 floating stickers (add_sticker — the 160+ vector library or emoji glyphs) — build it from NATIVE elements (rect panels, semi-transparent fills, borders, text).',
+ ],
+ },
+ })
+ expect(appliedSticker).toBe(3)
+ expect(result.toolCalls).toBe(3)
+ expect(String(result.verification)).toContain('Brief contract validated')
+ })
+})
diff --git a/src/lib/agent/loop.ts b/src/lib/agent/loop.ts
index 05db7f8..8719995 100644
--- a/src/lib/agent/loop.ts
+++ b/src/lib/agent/loop.ts
@@ -210,6 +210,15 @@ export function loopSystemPrompt(deps: {
'· Build section by section after the plan. NEVER add bare decorative bars/strips just to include a required color — use colors as the page background, text fills, or real panel/card fills.',
'· A realistic editor mockup = a large native panel (rounded rect, glass fill, border) CONTAINING inner native elements (toolbar bar, sidebar, canvas area, buttons) — not one empty rectangle.',
'· Feature cards = one semi-transparent rect + its text per card. Glassmorphism = rgba fills with visible borders.',
+ // v0.33 · COMPOSITION INTELLIGENCE — the anti-coordinate-placement
+ // rules. A run that only drops text at y-positions produces the
+ // "unfinished template" the NEON 2027 poster was: no focal point,
+ // flat background, bare-text CTA, disconnected icons.
+ '· COMPOSITION — ONE dominant focal element per page (a large illustration via add_illustration, a photo, or a big graphic composite) covering ≥10% of the page, placed in the hero band. Never ship a text-only page.',
+ '· Background treatment: set_background first, then LAYER 2-3 large low-opacity shapes (rgba fills) or a gradient band (add_shape with gradientFrom/gradientTo) BEHIND the content — a flat empty background reads as unfinished.',
+ '· CTA = a composite button: a filled rounded rect (add_shape with cornerRadius 40-80) with a short bold text centered on top — never bare text alone.',
+ '· Accents are placed, not dropped: give every sticker/icon an x/y/size integrated with the composition (beside headings, corners, edges) — icons floating in dead space is the failure mode.',
+ '· Theme effects: futuristic/neon briefs get neon/glow text effects (add_text effect:"neon", or update_elements textEffect) and shadows (update_elements shadowColor/shadowBlur) — the editor renders them natively.',
'',
)
}
diff --git a/src/lib/agent/skills.ts b/src/lib/agent/skills.ts
index c3d55fc..bdae1b4 100644
--- a/src/lib/agent/skills.ts
+++ b/src/lib/agent/skills.ts
@@ -59,8 +59,9 @@ export const DESIGN_SKILLS: DesignSkill[] = [
planning: [
'Read the Design Brief Contract; list every mandatory text and color before placing anything.',
'Pick the composition archetype: centered hero (classic, confident), asymmetric split (modern, editorial), or full-bleed image with plate (photographic).',
- 'Place in order: background → headline block → subhead → CTA → supporting details (date/place/price) → one decorative element max.',
- 'For the CTA use the accent color; make it a filled shape or pill, not naked text.',
+ 'Place in order: background (set_background + 2-3 large layered rgba shapes or a gradient band via add_shape gradientFrom/gradientTo) → FOCAL ELEMENT (a large add_illustration / add_stock_photo in the hero band, ≥10% of the page) → headline block → subhead → CTA → supporting details → placed accents (add_sticker / add_icon with x/y/size, integrated with the composition).',
+ 'For the CTA use the accent color; build it as a composite: a filled rounded rect (add_shape cornerRadius 40-80, solid or gradient) with the short actionable text centered on top — never naked text.',
+ 'Stickers: add_sticker resolves the 160+ vector library (rocket, star, sparkle, heart, balloon, fireworks, gift, trophy, party…) — query a CONCEPT, give x/y/size so each accent is placed, not dropped.',
'End with fix_overlaps or get_page_state + manual geometry check; then validate_brief.',
],
validation: [
@@ -116,7 +117,7 @@ export const DESIGN_SKILLS: DesignSkill[] = [
'Build on ONE hue relationship: monochrome (shades of one hue — safest), analogous (neighbors), or complementary (opposites, maximum pop). Triads only for playful brands.',
'Text contrast ≥ 4.5:1 (body) / ≥ 3:1 (≥ 24px bold or 18.66px+ bold = "large text") against ITS ACTUAL BACKGROUND — a gradient background is checked at its lightest point under the text.',
'Never place mid-gray text on white or dark-gray on navy; when the palette forces it, darken/lighten the TEXT (keep brand colors on shapes, adjust the text shade).',
- 'One gradient per design: linear, ≤ 25° from a cardinal direction, hues within 60° of each other. Gradients are backgrounds or hero fills, not body text fills.',
+ 'One gradient per design: linear, ≤ 25° from a cardinal direction, hues within 60° of each other. Gradients are backgrounds or hero fills, not body text fills. Build them natively: add_shape {gradientFrom, gradientTo, gradientAngle} or update_elements {gradientFrom, gradientTo} on an existing shape/text.',
'Dark-mode palettes: saturate less, lighten text in steps (gray-100/300/500), never pure #000 or #FFF for large fields — use #090B1A-navy / #F4F5F7-off-white.',
'The brand kit OUTRANKS your taste but never the brief: brief hexes are verbatim; brand colors fill the unassigned roles.',
],
@@ -279,7 +280,8 @@ export const DESIGN_SKILLS: DesignSkill[] = [
version: '1.0.0',
playbook: {
principles: [
- 'Concrete subject → add_stock_photo (real, licensed, credited). Abstract/stylized or exact-brand art → add_image (generation). Icon-language → add_icon. Decorative scenes → add_illustration.',
+ 'Concrete subject → add_stock_photo (real, licensed, credited). Abstract/stylized or exact-brand art → add_image (generation). Icon-language → add_icon (562 stroke icons, resolved + placed at x/y/size). Decorative scenes → add_illustration (tech: robot helper, circuit board, AI chip, cloud sync, rocket launch; nature; abstract; festive). Fun accents → add_sticker (160+ vector stickers).',
+ 'Every asset call carries its OWN geometry (x/y/size): the composition decides where art lands — an asset placed at a default centre is a disconnected graphic, not a design.',
'The photo is a layout region: allocate its bounding box FIRST, then choose orientation (landscape/portrait/square) to match the region.',
'Focal awareness: keep the subject on the rule-of-thirds intersection; text goes on the calm third (sky, wall, negative space) — else add a scrim.',
'One hero image per page; more images only as a deliberate grid (3-up gallery) with consistent gaps.',
diff --git a/src/lib/agent/tools.ts b/src/lib/agent/tools.ts
index 82663cc..582cdc1 100644
--- a/src/lib/agent/tools.ts
+++ b/src/lib/agent/tools.ts
@@ -17,6 +17,15 @@
import { FONTS } from '@/lib/fonts/catalog'
import type { ToolRisk } from './protocol'
import { repairPlanBands } 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
+// client while nothing was created — the poster claimed four
+// stickers and two never existed, and "quality audit passed" said
+// nothing because no stage ever checked assets.
+import { searchStickers } from '@/lib/stickers'
+import { searchIcons } from '@/lib/assets/icon-pack'
+import { ILLUSTRATIONS } from '@/lib/assets/illustrations'
export interface AgentTool {
name: string
@@ -277,9 +286,9 @@ export const AGENT_TOOLS: AgentTool[] = [
// ── add elements ───────────────────────────────────────────
{
name: 'add_text',
- description: 'Add a text box. Positions are px on the page; estimate width ≈ 0.6 × fontSize × chars.',
+ description: 'Add a text box. Positions are px on the page; estimate width ≈ 0.6 × fontSize × chars. effect sets a native text effect (neon, glow, shadow…) — use it for themed headlines.',
risk: 'write',
- argsSpec: '{text: string, x?: number, y?: number, width?: number, fontSize?: 6-400, fontFamily?: string, bold?: bool, color?: "#RRGGBB", align?: "left"|"center"|"right", yBand?: "top"|"center"|"bottom"}',
+ argsSpec: '{text: string, x?: number, y?: number, width?: number, fontSize?: 6-400, fontFamily?: string, bold?: bool, color?: "#RRGGBB", align?: "left"|"center"|"right", yBand?: "top"|"center"|"bottom", effect?: "none"|"shadow"|"lift"|"hollow"|"neon"|"echo"|"glow"|"outline"|"background"|"splice"}',
sanitize: (args, ctx) => {
const text = str(args, 'text', 400).trim()
if (!text) return { ok: false, error: 'text must be a non-empty string (max 400 chars).' }
@@ -295,6 +304,14 @@ export const AGENT_TOOLS: AgentTool[] = [
if (args.color !== undefined && !color) {
return { ok: false, error: 'color must be a #RRGGBB hex string, e.g. "#7D2AE8".' }
}
+ // v0.33: the editor's native text effects (neon, glow, drop…)
+ // existed since v0.3 but the tool surface never exposed them —
+ // briefs asking for neon/futuristic treatments were physically
+ // impossible to satisfy.
+ const effect = enumVal(args, 'effect', ['none', 'shadow', 'lift', 'hollow', 'neon', 'echo', 'glow', 'outline', 'background', 'splice'] as const, '' as never)
+ if (args.effect !== undefined && !effect) {
+ return { ok: false, error: 'effect must be one of: none, shadow, lift, hollow, neon, echo, glow, outline, background, splice.' }
+ }
const x = num(args, 'x')
const y = num(args, 'y')
const width = num(args, 'width')
@@ -316,6 +333,7 @@ export const AGENT_TOOLS: AgentTool[] = [
...(y !== null ? { y: clamp(y, -ctx.height, ctx.height) } : {}),
...(width !== null ? { width: clamp(width, 24, ctx.width * 1.5) } : {}),
align: enumVal(args, 'align', ['left', 'center', 'right'] as const, 'center'),
+ ...(effect ? { effect } : {}),
// the y band only rides along when no exact y was given
...(y === null ? { y: yBand } : {}),
},
@@ -326,9 +344,9 @@ export const AGENT_TOOLS: AgentTool[] = [
},
{
name: 'add_shape',
- description: 'Add a shape: rect, ellipse, triangle, star, line, or rounded rect with a fill.',
+ description: 'Add a shape: rect, ellipse, triangle, star, line, or rounded rect with a solid or gradient fill (gradients: gradientFrom + gradientTo + optional gradientAngle).',
risk: 'write',
- argsSpec: '{shape: "rect"|"ellipse"|"triangle"|"star"|"line", x: number, y: number, width: number, height: number, fill?: "#RRGGBB", cornerRadius?: number, rotation?: deg}',
+ argsSpec: '{shape: "rect"|"ellipse"|"triangle"|"star"|"line", x: number, y: number, width: number, height: number, fill?: "#RRGGBB", gradientFrom?: "#RRGGBB", gradientTo?: "#RRGGBB", gradientAngle?: deg, cornerRadius?: number, rotation?: deg}',
sanitize: (args, ctx) => {
const shape = enumVal(args, 'shape', ['rect', 'ellipse', 'triangle', 'star', 'line'] as const, '' as never)
if (!shape) return { ok: false, error: 'shape must be one of: rect, ellipse, triangle, star, line.' }
@@ -342,6 +360,20 @@ export const AGENT_TOOLS: AgentTool[] = [
if (w < 4 || h < 4) return { ok: false, error: `width/height must be ≥ 4px; you sent ${Math.round(w)}×${Math.round(h)}.` }
const fill = hex(args, 'fill')
if (args.fill !== undefined && !fill) return { ok: false, error: 'fill must be #RRGGBB, e.g. "#FF5C8A".' }
+ // v0.33: native gradient fills — the editor has supported them
+ // since v0.3; the tool surface never exposed them, so "use
+ // gradients" briefs were impossible to satisfy.
+ const gFrom = hex(args, 'gradientFrom')
+ const gTo = hex(args, 'gradientTo')
+ if (args.gradientFrom !== undefined || args.gradientTo !== undefined) {
+ if (!gFrom || !gTo) {
+ return { ok: false, error: 'a gradient needs BOTH gradientFrom and gradientTo as #RRGGBB, e.g. {"gradientFrom":"#02C0CC","gradientTo":"#7630D7","gradientAngle":45}.' }
+ }
+ }
+ const gAngle = num(args, 'gradientAngle')
+ if (gAngle !== null && (gAngle < -360 || gAngle > 360)) {
+ return { ok: false, error: `gradientAngle must be −360–360 degrees; you sent ${gAngle}.` }
+ }
const rotation = num(args, 'rotation')
const cornerRadius = num(args, 'cornerRadius')
return {
@@ -355,11 +387,14 @@ export const AGENT_TOOLS: AgentTool[] = [
width: clamp(w, 4, ctx.width * 2),
height: clamp(h, 4, ctx.height * 2),
...(fill ? { fill } : {}),
+ ...(gFrom && gTo
+ ? { gradient: { type: 'linear', from: gFrom, to: gTo, angle: gAngle !== null ? gAngle : 90 } }
+ : {}),
...(cornerRadius !== null ? { cornerRadius: clamp(cornerRadius, 0, 200) } : {}),
...(rotation !== null ? { rotation: clamp(rotation, -360, 360) } : {}),
},
],
- observation: `${shape} added at (${Math.round(x)},${Math.round(y)}) ${Math.round(w)}×${Math.round(h)}.`,
+ observation: `${shape} added at (${Math.round(x)},${Math.round(y)}) ${Math.round(w)}×${Math.round(h)}${gFrom && gTo ? ' with a gradient fill' : ''}.`,
}
},
},
@@ -424,29 +459,54 @@ export const AGENT_TOOLS: AgentTool[] = [
},
},
{
+ // v0.33 · stickers resolve SERVER-SIDE. The old tool took any
+ // short string as an "emoji" and left resolution to the client;
+ // unknown concepts were acked as success while nothing was
+ // created (the NEON 2027 poster claimed four stickers, two
+ // existed). The 160+ vector sticker library is pure data — the
+ // server resolves the query against it, rejects unknown concepts
+ // with real examples, and passes the resolved sticker + the
+ // model's own geometry through. Emoji glyphs still work.
name: 'add_sticker',
- description: 'Add an emoji sticker (e.g. "🚀", "✨"). Fast, no AI generation.',
+ description: 'Place a library sticker — 160+ vector stickers (rocket, star, sparkle, heart, balloon, fireworks, gift, cake, party, arrow, face…) or an emoji glyph (e.g. "🚀"). Resolved and placed exactly at x/y with the given size.',
risk: 'write',
- argsSpec: '{emoji: string, x?: number, y?: number, size?: 24-400}',
+ argsSpec: '{query: string, x?: number, y?: number, size?: 24-400}',
sanitize: (args, ctx) => {
- const emoji = str(args, 'emoji', 8).trim()
- if (!emoji) return { ok: false, error: 'emoji is required, e.g. "🚀".' }
+ const raw = (str(args, 'query', 60).trim() || str(args, 'emoji', 60).trim()).slice(0, 60)
+ if (!raw) {
+ return { ok: false, error: 'query is required — a sticker concept (rocket, star, sparkle, heart, balloon, fireworks, gift, cake, party) or an emoji glyph like "🚀".' }
+ }
const x = num(args, 'x')
const y = num(args, 'y')
const size = num(args, 'size')
if (size !== null && (size < 24 || size > 400)) return { ok: false, error: `size must be 24–400; you sent ${size}.` }
+ const pos = {
+ ...(x !== null ? { x: clamp(x, -ctx.width, ctx.width) } : {}),
+ ...(y !== null ? { y: clamp(y, -ctx.height, ctx.height) } : {}),
+ ...(size !== null ? { size: clamp(size, 24, 400) } : {}),
+ }
+ // vector library first — richer art, still native editable
+ // sticker elements (svg + stickerId, pack-recolourable)
+ const packs = searchStickers(raw)
+ if (packs.length) {
+ const sticker = packs[0].stickers[0]
+ return {
+ ok: true,
+ actions: [{ type: 'addPackSticker', sticker: { id: sticker.id, name: sticker.name, svg: sticker.svg }, ...pos }],
+ observation: `Sticker "${sticker.name}" (${packs[0].pack.name} pack) added${size !== null ? ` at ${Math.round(clamp(size, 24, 400))}px` : ''}.`,
+ }
+ }
+ // emoji glyph fallback — any short string with no ASCII letters
+ if (!/[a-z0-9]/i.test(raw) && raw.length <= 4) {
+ return {
+ ok: true,
+ actions: [{ type: 'addSticker', emoji: raw, ...pos }],
+ observation: `Sticker ${raw} added.`,
+ }
+ }
return {
- ok: true,
- actions: [
- {
- type: 'addSticker',
- emoji,
- ...(x !== null ? { x: clamp(x, -ctx.width, ctx.width) } : {}),
- ...(y !== null ? { y: clamp(y, -ctx.height, ctx.height) } : {}),
- ...(size !== null ? { size: clamp(size, 24, 400) } : {}),
- },
- ],
- observation: `Sticker ${emoji} added.`,
+ ok: false,
+ error: `No sticker matches "${raw}". Vector library concepts include: rocket, star, sparkle, heart, balloon, fireworks, gift, cake, party, arrow, face, food, travel. Or send an emoji glyph directly (e.g. "🚀", "✨", "⭐").`,
}
},
},
@@ -485,9 +545,9 @@ export const AGENT_TOOLS: AgentTool[] = [
// ── edit elements ──────────────────────────────────────────
{
name: 'update_elements',
- description: 'Patch properties of elements by id: geometry (x,y,width,height,rotation), style (fill,fontSize,bold,italic,underline,strike,uppercase,align,lineHeight,letterSpacing,curve,text), image (flipH,flipV,brightness,contrast,saturation), layer (locked,visible,opacity).',
+ description: 'Patch properties of elements by id: geometry (x,y,width,height,rotation), style (fill,fontSize,bold,italic,underline,strike,uppercase,align,lineHeight,letterSpacing,curve,text), image (flipH,flipV,brightness,contrast,saturation), layer (locked,visible,opacity), effects (gradientFrom+gradientTo+gradientAngle, textEffect, shadowColor/shadowBlur/shadowOffsetX/shadowOffsetY).',
risk: 'write',
- argsSpec: '{ids: string[], patch: {x?, y?, width?, height?, rotation?, text?, fill?, fontSize?, bold?, italic?, underline?, strike?, uppercase?, align?, lineHeight?, letterSpacing?, curve?, flipH?, flipV?, brightness?, contrast?, saturation?, locked?, visible?, opacity?}}',
+ argsSpec: '{ids: string[], patch: {x?, y?, width?, height?, rotation?, text?, fill?, fontSize?, bold?, italic?, underline?, strike?, uppercase?, align?, lineHeight?, letterSpacing?, curve?, flipH?, flipV?, brightness?, contrast?, saturation?, locked?, visible?, opacity?, gradientFrom?, gradientTo?, gradientAngle?, textEffect?, shadowColor?, shadowBlur?, shadowOffsetX?, shadowOffsetY?}}',
sanitize: (args, ctx) => {
const { ids, error } = idList(args, ctx)
if (error) return { ok: false, error }
@@ -541,9 +601,55 @@ export const AGENT_TOOLS: AgentTool[] = [
if (p[flag] !== undefined) patch[flag] = p[flag] === true
}
if (p.align !== undefined) patch.align = enumVal(p as Record<string, unknown>, 'align', ['left', 'center', 'right'] as const, 'center')
+ // v0.33 · the native effects surface — the editor has supported
+ // gradient fills (shapes + text), text effects (neon, glow, drop…)
+ // and per-element shadows since v0.3, but the tool never exposed
+ // them: briefs asking for "gradients, shadows, neon" were
+ // physically impossible for the agent to satisfy.
+ const gFrom = hex(p as Record<string, unknown>, 'gradientFrom')
+ const gTo = hex(p as Record<string, unknown>, 'gradientTo')
+ if (p.gradientFrom !== undefined || p.gradientTo !== undefined) {
+ if (!gFrom || !gTo) {
+ return {
+ ok: false,
+ error: `a gradient needs BOTH gradientFrom and gradientTo as #RRGGBB, e.g. {"gradientFrom":"#02C0CC","gradientTo":"#7630D7","gradientAngle":45}; you sent from=${JSON.stringify(p.gradientFrom)} to=${JSON.stringify(p.gradientTo)}.`,
+ }
+ }
+ const gAngle = num(p as Record<string, unknown>, 'gradientAngle')
+ if (gAngle !== null && (gAngle < -360 || gAngle > 360)) {
+ return { ok: false, error: `gradientAngle must be −360–360 degrees; you sent ${gAngle}.` }
+ }
+ patch.gradient = { type: 'linear', from: gFrom, to: gTo, angle: gAngle !== null ? gAngle : 90 }
+ }
+ if (p.textEffect !== undefined) {
+ const eff = enumVal(p as Record<string, unknown>, 'textEffect', ['none', 'shadow', 'lift', 'hollow', 'neon', 'echo', 'glow', 'outline', 'background', 'splice'] as const, '' as never)
+ if (!eff) {
+ return { ok: false, error: `textEffect must be one of: none, shadow, lift, hollow, neon, echo, glow, outline, background, splice; you sent ${JSON.stringify(p.textEffect)}.` }
+ }
+ patch.textEffect = eff
+ }
+ if (p.shadowColor !== undefined || p.shadowBlur !== undefined || p.shadowOffsetX !== undefined || p.shadowOffsetY !== undefined) {
+ const sc = hex(p as Record<string, unknown>, 'shadowColor')
+ if (p.shadowColor !== undefined && !sc) {
+ return { ok: false, error: `shadowColor must be #RRGGBB, e.g. "#000000"; you sent ${JSON.stringify(p.shadowColor)}.` }
+ }
+ const blur = num(p as Record<string, unknown>, 'shadowBlur')
+ if (blur !== null && (blur < 0 || blur > 120)) {
+ return { ok: false, error: `shadowBlur must be 0–120px; you sent ${blur}.` }
+ }
+ const ox = num(p as Record<string, unknown>, 'shadowOffsetX')
+ const oy = num(p as Record<string, unknown>, 'shadowOffsetY')
+ patch.shadow = {
+ enabled: true,
+ ...(sc ? { color: sc } : {}),
+ ...(blur !== null ? { blur: Math.round(blur) } : {}),
+ ...(ox !== null ? { offsetX: Math.round(clamp(ox, -200, 200)) } : {}),
+ ...(oy !== null ? { offsetY: Math.round(clamp(oy, -200, 200)) } : {}),
+ }
+ }
if (Object.keys(patch).length === 0) {
const sent = Object.keys(p).filter((k) => k !== 'ids')
- const valid = ['x', 'y', 'width', 'height', 'rotation', 'text', 'fill', 'fontSize', 'bold', 'italic', 'underline', 'strike', 'uppercase', 'align', 'lineHeight', 'letterSpacing', 'curve', 'flipH', 'flipV', 'brightness', 'contrast', 'saturation', 'locked', 'visible', 'opacity']
+ const valid = ['x', 'y', 'width', 'height', 'rotation', 'text', 'fill', 'fontSize', 'bold', 'italic', 'underline', 'strike', 'uppercase', 'align', 'lineHeight', 'letterSpacing', 'curve', 'flipH', 'flipV', 'brightness', 'contrast', 'saturation', 'locked', 'visible', 'opacity', 'gradientFrom', 'gradientTo', 'gradientAngle', 'textEffect', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY']
return {
ok: false,
error: `patch had no supported property. You sent: [${sent.join(', ')}]. Valid properties: [${valid.join(', ')}]. The text colour property is named fill.`,
@@ -846,29 +952,89 @@ export const AGENT_TOOLS: AgentTool[] = [
},
},
{
+ // v0.33 · icons resolve SERVER-SIDE (fail-closed). The 562-icon
+ // offline pack is pure data; the client used to re-search it after
+ // the loop had already recorded success — an unknown concept
+ // ("robot" in the NEON 2027 run) was acked as applied while
+ // nothing was created. The server now resolves the query, rejects
+ // unknowns with real examples, and sends the path data + the
+ // model's own geometry so the icon lands EXACTLY where intended
+ // (the old path ignored x/y/size and default-centred every icon).
name: 'add_icon',
- description: 'Search the icon pack by keyword (arrow, check, star, heart, cart…) and place the best match as a stroke icon.',
+ description: 'Search the 562-icon stroke pack by keyword (rocket, sparkles, star, heart, laptop, wifi, circuit board, check…) and place it exactly at x/y with the given size.',
risk: 'write',
- argsSpec: '{query: string, stroke?: "#RRGGBB", size?: 24-600}',
- sanitize: (args) => {
+ argsSpec: '{query: string, x?: number, y?: number, size?: 24-600, stroke?: "#RRGGBB"}',
+ sanitize: (args, ctx) => {
const query = str(args, 'query', 60).trim()
- if (query.length < 2) return { ok: false, error: 'query must name the icon concept, e.g. "arrow-right", "check".' }
+ if (query.length < 2) return { ok: false, error: 'query must name the icon concept, e.g. "rocket", "sparkles", "circuit board".' }
+ const icon = searchIcons(query, 1)[0]
+ if (!icon) {
+ const near = searchIcons(query.split(/\s+/)[0] ?? '', 4).map((i) => i.name.toLowerCase())
+ return {
+ ok: false,
+ error: `No icon matches "${query}". Available concepts include: ${(near.length ? near : ['rocket', 'star', 'sparkles', 'heart', 'wifi', 'zap']).join(', ')}. For scenes (robot helper, circuit board, AI chip, rocket launch, waves) use add_illustration.`,
+ }
+ }
+ const x = num(args, 'x')
+ const y = num(args, 'y')
+ const size = num(args, 'size')
return {
ok: true,
- actions: [{ type: 'addIcon', query, ...(hex(args, 'stroke') ? { stroke: hex(args, 'stroke')! } : {}), ...(num(args, 'size') !== null ? { size: clamp(num(args, 'size')!, 24, 600) } : {}) }],
- observation: `Icon search queued for "${query}".`,
+ actions: [
+ {
+ type: 'addIcon',
+ d: icon.d,
+ name: icon.name,
+ ...(hex(args, 'stroke') ? { stroke: hex(args, 'stroke')! } : {}),
+ ...(x !== null ? { x: clamp(x, -ctx.width, ctx.width) } : {}),
+ ...(y !== null ? { y: clamp(y, -ctx.height, ctx.height) } : {}),
+ ...(size !== null ? { size: clamp(size, 24, 600) } : {}),
+ },
+ ],
+ observation: `Icon "${icon.name}" added${x !== null ? ` at (${Math.round(clamp(x, -ctx.width, ctx.width))},${Math.round(clamp(y ?? 0, -ctx.height, ctx.height))})` : ''}${size !== null ? ` at ${Math.round(clamp(size, 24, 600))}px` : ''}.`,
}
},
},
{
+ // v0.33 · illustrations resolve SERVER-SIDE too (same fail-closed
+ // discipline; the packs are pure data) and honour the model's
+ // geometry — the old path ignored x/y/size entirely.
name: 'add_illustration',
- description: 'Place a decorative SVG illustration by keyword (abstract/nature/business/decoration scenes).',
+ description: 'Place a decorative SVG illustration exactly at x/y with the given size. Tech pack: robot helper, circuit board, AI chip, cloud sync, rocket launch… plus nature, people, business, abstract (waves, blobs), festive.',
risk: 'write',
- argsSpec: '{query: string}',
- sanitize: (args) => {
+ argsSpec: '{query: string, x?: number, y?: number, size?: 60-800}',
+ sanitize: (args, ctx) => {
const query = str(args, 'query', 60).trim()
- if (query.length < 3) return { ok: false, error: 'query must describe the scene, e.g. "waves", "mountain scene".' }
- return { ok: true, actions: [{ type: 'addIllustration', query }], observation: `Illustration search queued for "${query}".` }
+ if (query.length < 3) return { ok: false, error: 'query must describe the scene, e.g. "rocket launch", "circuit board", "waves".' }
+ const q = query.toLowerCase()
+ const hit =
+ ILLUSTRATIONS.find((i) => i.name.toLowerCase() === q) ??
+ ILLUSTRATIONS.find(
+ (i) => i.name.toLowerCase().includes(q) || i.tags.some((t) => t.includes(q) || q.includes(t)),
+ )
+ if (!hit) {
+ return {
+ ok: false,
+ error: `No illustration matches "${query}". Packs: tech (robot helper, circuit board, AI chip, cloud sync, rocket launch, smartphone app), nature, people, business, abstract (waves, blobs), festive. Name a concept or scene.`,
+ }
+ }
+ const x = num(args, 'x')
+ const y = num(args, 'y')
+ const size = num(args, 'size')
+ return {
+ ok: true,
+ actions: [
+ {
+ type: 'addIllustration',
+ svg: hit.svg,
+ name: hit.name,
+ ...(x !== null ? { x: clamp(x, -ctx.width, ctx.width) } : {}),
+ ...(y !== null ? { y: clamp(y, -ctx.height, ctx.height) } : {}),
+ ...(size !== null ? { size: clamp(size, 60, 800) } : {}),
+ },
+ ],
+ observation: `Illustration "${hit.name}" (${hit.pack} pack) added${size !== null ? ` at ${Math.round(clamp(size, 60, 800))}px` : ''}.`,
+ }
},
},
{
diff --git a/src/lib/design-actions.ts b/src/lib/design-actions.ts
index 9839883..f05eeb9 100644
--- a/src/lib/design-actions.ts
+++ b/src/lib/design-actions.ts
@@ -13,9 +13,13 @@ import {
createStickerElement,
createTableElement,
createTextElement,
+ DEFAULT_SHADOW,
+ TEXT_EFFECTS,
type AnyElement,
type Background,
+ type GradientFill,
type PluginElement,
+ type TextEffect,
type TextElement,
} from '@/lib/types'
import { checkCloneSafe } from '@/lib/plugins/data-caps'
@@ -67,6 +71,20 @@ export interface DesignAction {
const HEX = /^#[0-9a-fA-F]{6}$/
+/** v0.33 (agent): defensively normalize a wire gradient into a
+ * GradientFill. The server already validated it; the client still
+ * never trusts it raw (AI output is NEVER trusted). */
+function normalizeGradient(g: unknown): GradientFill | null {
+ if (!g || typeof g !== 'object') return null
+ const o = g as Record<string, unknown>
+ const from = typeof o.from === 'string' && HEX.test(o.from) ? o.from : null
+ const to = typeof o.to === 'string' && HEX.test(o.to) ? o.to : null
+ if (!from || !to) return null
+ const type = o.type === 'radial' ? 'radial' : 'linear'
+ const angle = Number.isFinite(Number(o.angle)) ? Math.min(360, Math.max(-360, Number(o.angle))) : 90
+ return { type, from, to, angle }
+}
+
/** Flatten elements (groups included) for id-based lookups. */
function flatElements(els: AnyElement[], out: AnyElement[] = []): AnyElement[] {
for (const el of els) {
@@ -114,6 +132,10 @@ export async function applyDesignAction(action: DesignAction, caller?: ActionCal
el.align = (action.align as 'left' | 'center' | 'right') ?? 'center'
if (typeof action.font === 'string' && action.font) el.fontFamily = action.font
if (typeof action.color === 'string' && HEX.test(action.color)) el.fill = action.color
+ // v0.33 (agent): native text effects — the editor has had them
+ // since v0.3; the agent's add_text now exposes them.
+ const effect = String(action.effect ?? '')
+ if (effect && TEXT_EFFECTS.some((t) => t.id === effect)) el.effect = effect as TextEffect
useEditorStore.getState().addElement(el)
return 'Text added — fully editable'
}
@@ -136,6 +158,9 @@ export async function applyDesignAction(action: DesignAction, caller?: ActionCal
...(Number.isFinite(Number(action.cornerRadius)) ? { cornerRadius: Math.round(Number(action.cornerRadius)) } : {}),
...(Number.isFinite(Number(action.rotation)) ? { rotation: Number(action.rotation) } : {}),
})
+ // v0.33 (agent): native gradient fill (add_shape gradientFrom/To).
+ const gradient = normalizeGradient(action.gradient)
+ if (gradient) el.fillGradient = gradient
useEditorStore.getState().addElement(el)
return `${shape} added`
}
@@ -157,6 +182,34 @@ export async function applyDesignAction(action: DesignAction, caller?: ActionCal
return `Sticker ${emoji} added`
}
+ // v0.33 (agent): addPackSticker — a server-resolved vector library
+ // sticker placed at the model's geometry. Native sticker element
+ // (svg + stickerId + alt), pack-recolourable like any library
+ // sticker the Stickers app inserts.
+ case 'addPackSticker': {
+ const sticker = action.sticker as { id?: string; name?: string; svg?: string } | undefined
+ if (!sticker || typeof sticker.svg !== 'string' || !sticker.svg.trim().startsWith('<svg')) {
+ return 'Sticker missing its art'
+ }
+ const size = Math.min(400, Math.max(24, Number(action.size) || 200))
+ const x = Number.isFinite(Number(action.x)) ? Number(action.x) : width / 2 - size / 2
+ const y = Number.isFinite(Number(action.y)) ? Number(action.y) : height / 2 - size / 2
+ const name = String(sticker.name ?? 'sticker')
+ const el = createStickerElement(name, {
+ x: Math.round(x),
+ y: Math.round(y),
+ width: size,
+ height: size,
+ fontSize: Math.round(size * 0.75),
+ svg: sticker.svg,
+ stickerId: String(sticker.id ?? ''),
+ })
+ el.name = name
+ el.alt = name
+ useEditorStore.getState().addElement(el)
+ return `Sticker "${name}" added`
+ }
+
// v0.27 (agent): addTable — header + rows on a clamped grid.
case 'addTable': {
const header = Array.isArray(action.header) ? action.header.map((c) => String(c).slice(0, 60)).slice(0, 6) : []
@@ -268,6 +321,38 @@ export async function applyDesignAction(action: DesignAction, caller?: ActionCal
if (Number.isFinite(Number(raw.height))) patch.height = Math.max(8, Number(raw.height))
if (Number.isFinite(Number(raw.lineHeight))) patch.lineHeight = Math.min(3, Math.max(0.8, Number(raw.lineHeight)))
if (Number.isFinite(Number(raw.letterSpacing))) patch.letterSpacing = Number(raw.letterSpacing)
+ // v0.33: the server-validated surface the client used to DROP —
+ // rotation/opacity/align/curve/brightness… were advertised by the
+ // tool, validated server-side, then silently ignored here (the
+ // same "acked but not applied" class as the missing stickers).
+ // Everything the agent is promised now actually applies.
+ if (Number.isFinite(Number(raw.rotation))) patch.rotation = Number(raw.rotation)
+ if (Number.isFinite(Number(raw.opacity))) patch.opacity = Math.min(1, Math.max(0, Number(raw.opacity)))
+ if (raw.align === 'left' || raw.align === 'center' || raw.align === 'right') patch.align = raw.align
+ if (Number.isFinite(Number(raw.curve))) patch.curve = Math.min(180, Math.max(-180, Number(raw.curve)))
+ for (const flag of ['italic', 'underline', 'strike', 'uppercase', 'flipH', 'flipV', 'locked', 'visible'] as const) {
+ if (typeof raw[flag] === 'boolean') patch[flag] = raw[flag] === true
+ }
+ for (const adj of ['brightness', 'contrast', 'saturation'] as const) {
+ if (Number.isFinite(Number(raw[adj]))) patch[adj] = Math.min(100, Math.max(-100, Number(raw[adj])))
+ }
+ // v0.33: the native effects surface — gradient fills, text
+ // effects (neon/glow/drop…), per-element shadows.
+ const gradient = normalizeGradient(raw.gradient)
+ if (gradient) patch.fillGradient = gradient
+ const eff = String(raw.textEffect ?? '')
+ if (eff && TEXT_EFFECTS.some((t) => t.id === eff)) patch.effect = eff
+ if (raw.shadow && typeof raw.shadow === 'object') {
+ const s = raw.shadow as Record<string, unknown>
+ patch.shadow = {
+ ...DEFAULT_SHADOW,
+ ...(typeof s.color === 'string' && HEX.test(s.color) ? { color: s.color } : {}),
+ ...(Number.isFinite(Number(s.blur)) ? { blur: Math.min(120, Math.max(0, Number(s.blur))) } : {}),
+ ...(Number.isFinite(Number(s.offsetX)) ? { offsetX: Number(s.offsetX) } : {}),
+ ...(Number.isFinite(Number(s.offsetY)) ? { offsetY: Number(s.offsetY) } : {}),
+ enabled: true,
+ }
+ }
if (!Object.keys(patch).length) return 'Nothing to update'
useEditorStore.getState().updateElements(ids, patch)
return `Updated ${ids.length} element${ids.length > 1 ? 's' : ''}`
@@ -565,6 +650,27 @@ export async function applyDesignAction(action: DesignAction, caller?: ActionCal
}
case 'addIcon': {
+ // v0.33: the server resolves the icon pack (fail-closed) and
+ // sends the path data + the model's own geometry — the icon is
+ // placed EXACTLY where intended. The old path default-centred
+ // every icon and ignored x/y/size entirely (the "disconnected,
+ // randomly positioned graphics" complaint). The legacy query
+ // path stays for older in-flight actions.
+ if (typeof action.d === 'string' && action.d.trim().length > 4) {
+ const size = Math.min(600, Math.max(24, Number(action.size) || 240))
+ const el = createShapeElement('path', {
+ width: size,
+ height: size,
+ pathData: action.d,
+ fill: 'transparent',
+ stroke: typeof action.stroke === 'string' && HEX.test(action.stroke) ? action.stroke : '#1F2226',
+ strokeWidth: 8.3,
+ ...(Number.isFinite(Number(action.x)) ? { x: Math.round(Number(action.x)) } : {}),
+ ...(Number.isFinite(Number(action.y)) ? { y: Math.round(Number(action.y)) } : {}),
+ })
+ useEditorStore.getState().addElement(el)
+ return `Icon "${String(action.name ?? 'icon')}" added`
+ }
// server-side search of the same offline pack the Icons app uses
const { searchIcons } = await import('@/lib/assets/icon-pack')
const query = String(action.query ?? '').trim().slice(0, 60)
@@ -579,13 +685,26 @@ export async function applyDesignAction(action: DesignAction, caller?: ActionCal
}
case 'addIllustration': {
+ // v0.33: the server resolves the illustration pack and sends
+ // the SVG + geometry — placed exactly. Legacy path for older
+ // in-flight actions.
+ if (typeof action.svg === 'string' && action.svg.trim().startsWith('<svg')) {
+ const size = Math.min(800, Math.max(60, Number(action.size) || 420))
+ const url = `data:image/svg+xml;base64,${typeof btoa === 'function' ? btoa(unescape(encodeURIComponent(action.svg))) : Buffer.from(action.svg, 'utf8').toString('base64')}`
+ const el = createImageElement(url, size, size, {
+ ...(Number.isFinite(Number(action.x)) ? { x: Math.round(Number(action.x)) } : {}),
+ ...(Number.isFinite(Number(action.y)) ? { y: Math.round(Number(action.y)) } : {}),
+ })
+ useEditorStore.getState().addElement(el)
+ return `Illustration "${String(action.name ?? 'illustration')}" added`
+ }
const { ILLUSTRATIONS } = await import('@/lib/assets/illustrations')
const query = String(action.query ?? '').trim().toLowerCase().slice(0, 60)
if (!query) return 'No illustration query given'
const hit =
ILLUSTRATIONS.find((i) => i.name.toLowerCase() === query) ??
ILLUSTRATIONS.find((i) => i.name.toLowerCase().includes(query) || i.tags.some((t) => t.includes(query)))
- if (!hit) return `No illustration matches "${query}" — the packs cover abstract/nature/business/decoration scenes`
+ if (!hit) return `No illustration matches "${query}" — the packs cover abstract/nature/business/tech scenes`
const { addIllustration } = await import('@/components/editor/add-element')
addIllustration(hit.svg)
return `Illustration "${hit.name}" added`
@@ -1087,6 +1206,7 @@ export function describeAction(action: DesignAction): string {
case 'addText': return `Add text: “${String(action.text ?? '').slice(0, 40)}${String(action.text ?? '').length > 40 ? '…' : ''}”`
case 'addShape': return `Add ${String(action.shape ?? 'shape')}`
case 'addSticker': return `Add sticker ${String(action.emoji ?? '')}`
+ case 'addPackSticker': return `Add sticker ${String((action.sticker as { name?: string } | undefined)?.name ?? '')}`
case 'addTable': return `Add table (${(action.header as string[] | undefined)?.length ?? 0} cols)`
case 'addImage': return `Add image (${String(action.src ?? '').startsWith('data:') ? 'embedded' : 'media library'})`
case 'addPluginElement': return `Add ${String(action.kind ?? 'plugin')} element`