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.19.0): Wave 4 — AI Power-Up
Ashiq Hussain Mir782cfbe05362
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0de7707..65bf667 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,110 @@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/).+## [0.19.0] — 2026-11-09++Wave 4 of the consolidation programme — AI Power-Up (roadmap:+`docs/COMPETITIVE-ANALYSIS.md`, guide: `docs/AI-POWER-UP.md`). Eight+features on three gradients: **local** image tools that work on any+image offline, **text-slot** features behind editable review gates, and+the **video generation slot**. Scoped directly after a live+verification that vibes.ai-class edit providers only edit images they+generated themselves (422 `source_image_not_editable` on uploads and+on re-encoded generations — byte-hash matched), so the universal path+got local. **No migration this release** — `aiEntId`/`alt` ride as+additive nullable element fields, slots/features ride the existing+AppConfig JSON; pre-v0.19 documents open byte-identically.++### Added++- **Local upscaler (Lanczos-3).** "Upscale" on a selected image: 2×/4×+ with a live target-size preview, output capped at 8192px per side+ (factor auto-reduces). Separable Lanczos-3 with premultiplied alpha+ in pure TypeScript (`lib/upscale.ts`) — cut-outs keep clean edges,+ zero downloads, works offline on any image. Deterministic and+ unit-pinned.+- **Brush magic eraser — local pyramid diffusion.** Paint over+ unwanted objects with an adjustable brush; the region is+ reconstructed from its surroundings by a clean-room LaMa-style+ pipeline (`lib/inpaint.ts`): pull-push pyramid over known pixels,+ boundary-constrained Jacobi diffusion at full resolution, seam+ feather. Zero model download; works on uploads and stock photos —+ exactly the images provider-backed erasers refuse.+- **Agentic planning with an editable review gate.** Apps → AI design+ plan: describe the design, pick 1–6 pages, and the text-slot model+ returns a structured plan that NOTHING applies yet. The gate renders+ page cards with scaled wireframe previews — toggle any page or+ element, rewrite any copy inline — and Apply builds real editor+ elements (`lib/design-plan.ts` `planToPages`, the MCP+ `generate_design` semantics) through one history push. Route+ `POST /api/ai/plan`; hostile-input-safe normalization (clamped+ geometry, validated fonts/colors, ≤6 pages × ≤30 elements).+- **Speaker-notes generation.** "Generate with AI" in the notes+ popover: the page outline (titles from the largest text, bullets,+ media summaries — `lib/notes-outline.ts`; the model sees content,+ never geometry) goes to `POST /api/ai/notes`, the reply renders as+ one editable textarea per page, Apply writes each page's notes.+ Route flag `notesGeneration`.+- **AI theme generation.** Apps → AI theme: a mood prompt returns a+ role-tagged palette (background/surface/ink/inkSoft/accent/+ accentSoft) + font pairing from the installed catalog. Preview all+ six roles, Apply maps them design-wide (`lib/theme.ts` `applyTheme`,+ pure): backgrounds, text ink, shape accents, lines — images, charts+ and stickers are never touched. Two WCAG contrast guards (normalize-+ time ink swap, apply-time per-text flip). One Ctrl+Z reverts.+ Route `POST /api/ai/theme`, flag `themeGeneration`.+- **Alt-text generation.** The image toolbar's Alt button: editor ++ Generate (one vision-slot call, `POST /api/ai/alt-text`) returning a+ single plain sentence the user reviews/edits before Save stores+ `ImageElement.alt` — riding autosave/versions/collab, feeding+ screen-reader landmarks, never burned into exports. Flag `altText`.+- **Video-generation capability slot.** The fifth slot (`video`),+ speaking the OpenAI "Sora-style" async shape the VibesAI worker+ exposes (POST `/videos/generations` → id; poll; `/content` MP4).+ Videos panel gained a "Generate with AI" card (self-hiding without a+ provider): prompt → progress-polled generation → preview → Add to+ design downloads through a same-origin proxy, probes real+ dimensions + first-frame poster, inserts via the chunked media+ store. Route `POST|GET /api/ai/video`; starts (3/min) and polls+ (60/min) rate-limited separately; flag `videoGeneration`; admin+ console slot row + kill switch.+- **MCP `vision_ground` (canvas-screenshot vision grounding).** The+ 21st tool: feed a canvas screenshot + page size, get a grounded+ element inventory — labels, roles, normalized 0..1 bounds AND+ page-pixel boxes, dominant colors, reading-order description — so+ agents reason about layout before acting with `update_element` /+ `add_text`. Pure normalizer in `lib/mcp/vision-ground.ts`;+ no-provider path points at `get_design_content`.++### Changed++- **AI-edit chains are id-based now.** `/api/ai/image` and+ `/api/ai/image-edit` forward the provider's `image_ent_id`; the+ editor stores it on the element (`aiEntId`, additive) and sends it+ back as `sourceEntId` — edit-of-edit chains survive re-encoding+ (the byte-hash match does not, verified live). The provider's+ "only edits its own generations" refusal surfaces as a structured+ 422 `SOURCE_NOT_EDITABLE` whose message points at the local tools+ that work on any image.+- **Capabilities surface.** `/api/ai/capabilities` reports+ `agenticPlanning`, `notesGeneration`, `themeGeneration`, `altText`,+ `videoGeneration` (provider-gated) and `upscale`, `brushEraser`+ (local, always on).+- **Admin console.** Model slots gained the Video generation row+ (endpoint `videos/generations`); feature toggles gained the five+ Wave 4 switches. Stored tables merge over the new defaults (on) —+ the legacy import wires the video slot too.++### Tested++- 1309 unit tests (+54: upscale, inpaint, design-plan, notes-outline,+ theme, vision-ground, video status normalization, config slot table).+- `tests/e2e/wave4-ai-powerup.spec.ts`: plan gate (edit + toggle ++ apply through the designs API), notes review, theme apply with+ contrast assertions, the REAL local upscaler (8→16px verified in the+ document), brush-eraser surface, alt-text round-trip, capabilities+ shape. AI routes mocked at the network layer.+## [0.18.0] — 2026-11-09Wave 3 of the consolidation programme — editor depth parity (roadmap:diff --git a/README.md b/README.mdindex 30eddd1..a7415ca 100644--- a/README.md+++ b/README.md@@ -733,8 +733,9 @@ research/ # architecture decision records & auditsCanvix works fully **without** any AI provider — the editor, templates, exports,collaboration and comments need nothing but the database. AI features-(Magic Layers, Assistant, Magic Write, image generation/editing, translate)-activate when a provider is configured **on the server**. Stock photo+(Magic Layers, Assistant, Magic Write, image generation/editing, translate,+the v0.19 plan/notes/theme/alt-text/video features) activate when a provider+is configured **on the server**. Stock photosearch is separate by design (v0.16.4): it runs on free stock-providerkeys, not on an AI provider — see `docs/STOCK-PHOTO.md`:@@ -768,13 +769,20 @@ limited per IP and logs usage into the `AIUsage` table.| Exports — PNG / JPG / PDF / SVG / video | ✅ always local || Collaboration, presence, comments | ✅ only needs the database || Background remover | ✅ local (in-browser ONNX) |+| **Upscaler (Lanczos 2×/4×)** | ✅ local — v0.19 Wave 4, any image |+| **Brush magic eraser** | ✅ local (pyramid diffusion) — v0.19 Wave 4, any image || Color palettes, layout balancing | ✅ local (deterministic) |+| **AI design plan / notes / theme** | ⚙️ needs a server AI provider (text slot) — v0.19 Wave 4, always review-gated |+| **Alt text generation** | ⚙️ needs a server AI provider (vision slot) — v0.19 Wave 4 || Magic Layers, AI Assistant, Magic Write | ⚙️ needs a server AI provider |-| AI image generation / eraser / enhance | ⚙️ needs a server AI provider |+| AI image generation / eraser / enhance | ⚙️ needs a server AI provider (edits follow the provider's own rules — vibes-style providers only edit images they generated) |+| **AI video generation** | ⚙️ needs a provider on the `video` slot (Sora-style async API) — v0.19 Wave 4 || Translate | ⚙️ needs a server AI provider || Stock photo search | ⚙️ needs `PEXELS_API_KEY` or `PIXABAY_API_KEY` (free) || Stock video search | ⚙️ needs `PEXELS_API_KEY` or `PIXABAY_API_KEY` (free) |-| MCP server (agent tools) | ✅ with token set — `generate_design` additionally needs the AI provider |+| MCP server (agent tools) | ✅ with token set — `generate_design` needs the AI provider, `vision_ground` the vision slot |++See `docs/AI-POWER-UP.md` for the full Wave 4 guide.## 🤖 AI agents (MCP)diff --git a/docs/ADMIN.md b/docs/ADMIN.mdindex 01ab6e1..46c66d9 100644--- a/docs/ADMIN.md+++ b/docs/ADMIN.md@@ -77,10 +77,11 @@ to a different provider + model:| Slot | What answers through it || --- | --- |-| `text` | Magic Write · Translate · Assistant (chat completions) |-| `vision` | Magic Layers (image understanding) |+| `text` | Magic Write · Translate · Assistant · **AI design plan · speaker notes · AI theme** (chat completions) |+| `vision` | Magic Layers · **alt-text generation** (image understanding) || `image` | text-to-image || `imageEdit` | Magic Eraser / Enhance |+| `video` | **AI video generation** — Sora-style async (`videos/generations`), v0.19 Wave 4 |**Photo search is not a slot anymore (v0.16.4 A4).** It rode the AItable as `imageSearch` — an `images/search` endpoint almost no@@ -165,10 +166,10 @@ way (one one-result search each).`/admin/logs` (v0.16.3 A3) answers "why isn't the AI feature working"without an SSH session. Two surfaces:-- **AI slot status** — what each of the four capability slots (`text`,- `vision`, `image`, `imageEdit`) resolves to right now (v0.16.4 A4:+- **AI slot status** — what each of the five capability slots (`text`,+ `vision`, `image`, `imageEdit`, `video`) resolves to right now (v0.16.4 A4:`imageSearch` is retired — photo search runs on the stock keys,- not on an AI slot):+ not on an AI slot; v0.19 Wave 4 added `video`):provider label, base URL, model id and which config layer answered(providers table / legacy override / env / file). Never the key. Aslot wired to a chat-only provider is the classic silent breakage —diff --git a/docs/AI-POWER-UP.md b/docs/AI-POWER-UP.mdnew file mode 100644index 0000000..9aab790--- /dev/null+++ b/docs/AI-POWER-UP.md@@ -0,0 +1,176 @@+# AI Power-Up — Wave 4 (v0.19.0)++> Date: 2026-11-09 · Wave 4 of the consolidation programme+> (roadmap: `docs/COMPETITIVE-ANALYSIS.md`)++Eight features across three gradients of intelligence: **local** (no provider,+works offline on any image), **text-slot** (one chat completion each, behind an+editable review gate), and the **video slot** (async generation). Every+provider-backed feature has an admin kill switch; every AI draft is reviewed+before it lands.++## The design principle: local first, reviewed always++Wave 4 was scoped right after a live verification of the VibesAI worker+(`vibesai-openai.ashiqzback.workers.dev`):++| Test | Result |+| --- | --- |+| Generate → edit the exact generated bytes | ✅ 200 (chain works) |+| Edit an arbitrary uploaded image | ❌ 422 `source_image_not_editable` |+| Edit a vibes image after re-encoding (same pixels) | ❌ 422 — strict sha256 byte-hash registry |++vibes.ai (and therefore the worker proxying it) **only edits images it+generated itself**, matched by exact bytes or its internal `image_ent_id`. The+response is a first-class contract now:++- `/api/ai/image-edit` returns a structured **422 `SOURCE_NOT_EDITABLE`** with+ a pointer to the local tools that work on any image.+- Generation/edit responses forward `image_ent_id`; the editor stores it on+ the element (`ImageElement.aiEntId`) and sends it back as `sourceEntId`, so+ AI-edit chains survive re-encoding (the byte hash does not).+- The two heavy image tools that users need on **uploads and stock photos** —+ upscaling and object removal — run **locally**. No provider can gate them.++## Local image power tools (any image, offline)++### Upscaler — Lanczos-3 (`lib/upscale.ts`)++The "Upscale" button on a selected image offers 2× / 4× with a live+target-size preview. Pure-TypedScript separable Lanczos-3 resampling with+premultiplied alpha (cut-outs keep clean edges — straight RGBA filtering+bleeds transparent-pixel colors). Output capped at 8192px per side; the+factor auto-reduces when the cap would be exceeded. Deterministic and+unit-pinned (`lib/upscale.test.ts`).++### Brush magic eraser — pyramid diffusion (`lib/inpaint.ts`)++Paint over anything — people, objects, watermarks — with an adjustable brush;+the region is reconstructed from its surroundings. Clean-room "LaMa-style"+pipeline, zero model download:++1. **Pull-push pyramid** — downsample *known* pixels only until the hole has+ context at a coarse scale, then fill back up level by level.+2. **Boundary-constrained Jacobi diffusion** at full resolution (the brush+ edge is a fixed boundary, so the reconstruction matches the image by+ construction).+3. One **feather pass** over the seam.++Honest scope: this reconstructs backgrounds (sky, walls, gradients, texture)+very well; it does not hallucinate new complex content the way a generative+model might — that is what the provider-backed Magic Eraser (text-described)+is for, on images the provider generated.++## Agentic planning with an editable review gate++**Apps → AI design plan.** Describe the design ("4-page launch deck for a+coffee subscription, warm and earthy"), pick the page count, and the text-slot+model returns a structured multi-page plan — nothing is applied yet. The+review gate shows each page as a card with a scaled wireframe preview; every+page and element can be toggled off, and every text is inline-editable.+**Apply** builds real editor elements via the same factories the MCP server+uses (`lib/design-plan.ts` → `planToPages`), appends the pages through one+history push, and a single Ctrl+Z removes everything.++- Route: `POST /api/ai/plan` (slot `text`, flag `agenticPlanning`)+- The plan JSON is normalized against a hostile-input-safe coercion+ (clamped geometry, validated fonts/colors, ≤6 pages × ≤30 elements).+- The normalizer is shared logic with the MCP `generate_design` tool's+ semantics — one notion of "what a generated design looks like".++## Speaker-notes generation++The page bar's notes popover gained **"Generate with AI"**. The page *outline*+(titles from the largest text, bullets from the rest, media summaries —+`lib/notes-outline.ts`; the model sees content, never geometry) goes to+`POST /api/ai/notes` (slot `text`, flag `notesGeneration`). The reply renders+as one editable textarea per page; **Apply** writes each page's notes via+`setPageNotes`. Notes ride autosave/versions/collab and appear in presenter+view — never on the canvas or in exports.++## AI theme generation++**Apps → AI theme.** Describe a mood; the model returns a **role-tagged+palette** (background / surface / ink / inkSoft / accent / accentSoft) plus a+font pairing from the installed catalog. The preview shows all six roles;+**Apply** maps them design-wide (`lib/theme.ts` → `applyTheme`, pure):++- page backgrounds → background (gradients → accent→accentSoft)+- headline text → ink + heading font; body text → inkSoft + body font+- grayscale shapes → surface; colored shapes → accent; lines → accent+- images, charts, stickers are **never** touched (recoloring media is a lie)++Two WCAG contrast guards run automatically: unreadable ink gets swapped at+normalize time, and any text that would strand below 3:1 on the new+background flips to ink at apply time. One history push — one Ctrl+Z reverts.++## Alt-text generation (accessibility)++The image toolbar's **Alt** button opens an editor with **Generate**: one+vision-slot call (`POST /api/ai/alt-text`, flag `altText`) returns a single+plain sentence (≤ 200 chars after normalization, `decorative` for+decorative images). The user reviews/edits before **Save** stores it on+`ImageElement.alt` — which rides autosave, versions and collab, and feeds+screen-reader landmarks. Never burned into visual exports.++## Video generation slot++The fifth capability slot. **Videos panel → "Generate with AI"** (the card+hides itself when the slot has no provider): prompt → `POST /api/ai/video`+starts an async generation → the card polls `GET /api/ai/video?id=…` with a+progress bar → preview → **Add to design** downloads the MP4 through the+same-origin proxy (`…&content=1`), probes real dimensions and first-frame+poster, and inserts a native video element through the chunked media store.++The slot speaks the emerging OpenAI "Sora-style" async shape — the exact+surface the VibesAI worker exposes:++```+POST {baseUrl}/videos/generations → { id, status: "queued" }+GET {baseUrl}/videos/generations/:id → { status, progress, videos[] }+GET {baseUrl}/videos/generations/:id/content?index=N → MP4 bytes+```++Admin: flag `videoGeneration`, slot row "Video generation" in the console.+The route rate-limits starts (3/min/IP) and polls (60/min/IP) separately so+watching a generation cannot exhaust the start budget.++## MCP: canvas-screenshot vision grounding++New tool **`vision_ground`** (21 tools total): feed it a screenshot of a+canvas page (dataURL) plus the page's pixel size, and the vision slot returns+a grounded inventory — what is visible, where (normalized 0..1 bounds *and*+page-pixel boxes), in what colors, plus a reading-order description. Agents+use it to reason about layout before acting with `update_element` /+`add_text`, or to answer "what does this design look like". Pure normalizer:+`lib/mcp/vision-ground.ts` (unit-tested); no-provider path fails with a+pointer to `get_design_content`.++## Capability surface++`GET /api/ai/capabilities` (booleans only, never secrets) now reports:++| Capability | Provider | Kill switch |+| --- | --- | --- |+| `agenticPlanning` | text slot | `agenticPlanning` |+| `notesGeneration` | text slot | `notesGeneration` |+| `themeGeneration` | text slot | `themeGeneration` |+| `altText` | vision slot | `altText` |+| `videoGeneration` | video slot | `videoGeneration` |+| `upscale` | — local, always on | — |+| `brushEraser` | — local, always on | — |++## Acceptance++- **Unit**: 1309 tests pass (+54 for Wave 4: upscale, inpaint, design-plan,+ notes-outline, theme, vision-ground, video status, config slot table).+- **e2e**: `tests/e2e/wave4-ai-powerup.spec.ts` — plan gate (edit + toggle ++ apply), notes review, theme apply, real local upscale (8→16px verified+ through the designs API), brush-eraser surface, alt text round-trip,+ capabilities shape. AI routes are mocked at the network layer.+- **No migration**: `aiEntId` / `alt` ride as additive nullable element+ fields; slots/features ride the existing AppConfig JSON. Pre-v0.19+ documents open byte-identically; stored admin tables merge over the new+ feature defaults (on).+- **Export parity**: nothing new is burned into exports — alt text and notes+ are metadata; upscale/eraser swap the element `src` like any edit.diff --git a/docs/COMPETITIVE-ANALYSIS.md b/docs/COMPETITIVE-ANALYSIS.mdindex 69d11d5..31d7e0d 100644--- a/docs/COMPETITIVE-ANALYSIS.md+++ b/docs/COMPETITIVE-ANALYSIS.md@@ -89,10 +89,19 @@ raster-strip approximation for v1. Acceptance: 1304 unit tests (+65), wave3 e2etop-up (lib/templates/sync.ts — auto-deployed instances no longer serve a stale library).Stretch goals deferred with the roadmap; matrix re-score pending (Wave 4 kickoff).-### Wave 4 — AI Power-Up-Local upscaling (Real-ESRGAN/Lanczos) · brush magic eraser (LaMa) · agentic planning with editable-review gate · canvas-screenshot vision grounding (MCP tool) · AI theme generation · speaker-notes-generation · video-generation capability slot · alt-text generation.+### Wave 4 — AI Power-Up ✅ SHIPPED (v0.19.0, 2026-11-09)+Local upscaling (Lanczos-3, any image offline) · brush magic eraser (clean-room+pyramid-diffusion inpainting — zero model download) · agentic planning with+editable review gate (plan → toggle/edit → apply native pages) ·+canvas-screenshot vision grounding (`vision_ground`, the 21st MCP tool) ·+AI theme generation (role-tagged palette + fonts, WCAG contrast guards) ·+speaker-notes generation (outline → draft → editable per page) ·+video-generation capability slot (Sora-style async + same-origin MP4 proxy) ·+alt-text generation (`ImageElement.alt`). Plus: AI-edit chains are id-based+now (`aiEntId`/`sourceEntId`) and the vibes-style "only edits its own+generations" refusal surfaces as a structured 422 pointing at the local+tools. No migration. Guide: docs/AI-POWER-UP.md · acceptance: 1309 unit+tests (+54), wave4 e2e suite (tests/e2e/wave4-ai-powerup.spec.ts).### Wave 5 — Export & Sharing ProfessionalisationShare links with view/comment/edit roles + password + expiry · ZIP batch export · WebP · PPTX ·diff --git a/docs/UPGRADING.md b/docs/UPGRADING.mdindex e4e6892..86ac73a 100644--- a/docs/UPGRADING.md+++ b/docs/UPGRADING.md@@ -5,6 +5,22 @@ release is designed to upgrade with **one migration command**. Thisguide covers the routine path, jumping minors, and — the part mostguides skip — how to roll back, with the honest database caveat.+## v0.19.0 — Wave 4 (AI Power-Up)++**No migration.** The two new element fields (`ImageElement.aiEntId`,+`ImageElement.alt`) and the five new admin flags (plus the `video` slot) ride+as additive, nullable data inside the existing document JSON and AppConfig+rows — `npm run db:migrate:deploy` is a no-op and pre-v0.19 documents open+byte-identically. Stored admin tables merge over the new feature defaults+(all on). After deploying, restart as usual; nothing else to run.++Operators with a vibes.ai-style `imageEdit` provider: the edit flow now+forwards the provider's `image_ent_id` and surfaces the "only edits its own+generations" refusal as a structured 422 — no configuration needed, but see+`docs/AI-POWER-UP.md` for what changed and why. The new `video` slot is+optional; the Videos panel's AI card hides itself until a provider is pinned+to it.+## v0.18.0 — Wave 3 (editor depth parity)**No migration.** Everything rides additive, nullable fields (shapediff --git a/package-lock.json b/package-lock.jsonindex c1cb568..ae1a1d7 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "canvix",- "version": "0.18.0",+ "version": "0.19.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "canvix",- "version": "0.18.0",+ "version": "0.19.0","hasInstallScript": true,"dependencies": {"@imgly/background-removal": "^1.7.0",diff --git a/package.json b/package.jsonindex 03e8cc2..01c6345 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.18.0",+ "version": "0.19.0","private": false,"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/public/plugins/wordcloud/manifest.json b/public/plugins/wordcloud/manifest.jsonindex 4c14007..d33866f 100644--- a/public/plugins/wordcloud/manifest.json+++ b/public/plugins/wordcloud/manifest.json@@ -9,7 +9,7 @@"url": "https://github.com/mir-ashiq/canvix"},"engines": {- "canvix": ">=0.13.4 <0.19.0"+ "canvix": ">=0.13.4 <0.20.0"},"entry": {"panel": "panel.html",diff --git a/scripts/verify-wave4.sh b/scripts/verify-wave4.shnew file mode 100755index 0000000..18834f0--- /dev/null+++ b/scripts/verify-wave4.sh@@ -0,0 +1,98 @@+#!/bin/bash+# scripts/verify-wave4.sh — one-shot Wave 4 verification (sandbox):+# embedded Postgres + migrate deploy + seed + dev server + targeted+# playwright e2e (wave4 + smoke). Everything in ONE shell because+# background processes don't outlive the session.+set -euo pipefail+cd "$(dirname "$0")/.."+ROOT="$(pwd)"++export DATABASE_URL="postgresql://canvix:canvix@localhost:5433/canvix"+PGDIR=/tmp/pgembed+LOG=$PGDIR/verify-w4.log+: > "$LOG"++echo "── 1. embedded postgres ─────────────────────────────"+pkill -f 'pgembed/data3' 2>/dev/null || true+pkill -f 'start3.mjs' 2>/dev/null || true+for i in $(seq 1 15); do+ if node -e "const n=require('net');const s=n.connect(5433,'127.0.0.1',()=>{s.end();process.exit(0)});s.on('error',()=>process.exit(1))" 2>/dev/null; then sleep 1; else break; fi+done+rm -rf "$PGDIR/data3" "$PGDIR/ready3.marker"+mkdir -p "$PGDIR"+# embedded-postgres lives in the repo's node_modules when installed+# (dev sandbox); fall back to the persisted copy when it isn't.+PG_MODULES="$ROOT/node_modules"+if [ ! -f "$PG_MODULES/embedded-postgres/dist/index.js" ]; then+ PG_MODULES=/tmp/my-project/pgembed/node_modules+fi+echo "pg modules: $PG_MODULES"+cat > "$PGDIR/start3.mjs" << EOF+// ESM resolution is file-location based — /tmp has no node_modules, so+// import the modules by absolute path (PG_MODULES comes from the env).+const { default: EmbeddedPostgres } = await import(+ process.env.PG_MODULES + '/embedded-postgres/dist/index.js'+)+import { writeFileSync } from 'node:fs'+const pg = new EmbeddedPostgres({+ databaseDir: '/tmp/pgembed/data3',+ user: 'canvix',+ password: 'canvix',+ port: 5433,+ persistent: true,+})+await pg.initialise()+await pg.start()+await pg.createDatabase('canvix').catch(() => {})+const { Client } = (await import(process.env.PG_MODULES + '/pg/lib/index.js')).default+for (let i = 0; i < 60; i++) {+ try {+ const c = new Client({ connectionString: 'postgresql://canvix:[email protected]:5433/canvix' })+ await c.connect()+ await c.query('SELECT 1')+ await c.end()+ writeFileSync('/tmp/pgembed/ready3.marker', 'ok')+ console.log('PG READY (query verified)')+ break+ } catch {+ await new Promise((r) => setTimeout(r, 500))+ }+}+setInterval(() => {}, 1 << 30)+EOF+setsid nohup env PG_MODULES="$PG_MODULES" node "$PGDIR/start3.mjs" >> "$LOG" 2>&1 < /dev/null &+for i in $(seq 1 150); do+ [ -f "$PGDIR/ready3.marker" ] && break+ sleep 1+done+[ -f "$PGDIR/ready3.marker" ] || { echo "PG FAILED"; tail -25 "$LOG"; exit 1; }+echo "PG up on 5433"++echo "── 2. migrate deploy (Wave 4 = no new migrations; must be a no-op) ──"+npx prisma migrate deploy 2>&1 | tail -3 | tee -a "$LOG"++echo "── 3. seed (366 templates) ──────────────────────────"+npx tsx prisma/seed.ts 2>&1 | grep -E "Seeding|Done" | tee -a "$LOG"++echo "── 4. dev server ────────────────────────────────────"+pkill -f 'next dev -p 3000' 2>/dev/null || true+sleep 1+# CANVIX_RATE_LIMITS=off — the wave4 suite registers/logs in several+# accounts; the sandbox IP budget (5/h) is reserved for production.+setsid nohup env CANVIX_RATE_LIMITS=off npx next dev -p 3000 > /tmp/pgembed/dev-w4.log 2>&1 < /dev/null &+for i in $(seq 1 150); do+ if curl -sf http://localhost:3000/api/health >/dev/null 2>&1; then break; fi+ sleep 1+done+curl -sf http://localhost:3000/api/health >/dev/null || { echo "DEV FAILED"; tail -30 /tmp/pgembed/dev-w4.log; exit 1; }+echo "dev up"++echo "── 5. API spot-checks ───────────────────────────────"+HEALTH=$(curl -sf http://localhost:3000/api/health)+echo "health: $HEALTH"+echo "capabilities: $(curl -sf http://localhost:3000/api/ai/capabilities)"++echo "── 6. playwright e2e (wave4 + smoke) ────────────────"+BASE_URL=http://localhost:3000 npx playwright test tests/e2e/wave4-ai-powerup.spec.ts tests/e2e/smoke.spec.ts 2>&1 | tail -25++echo "── done ─────────────────────────────────────────────"diff --git a/src/app/api/ai/alt-text/route.ts b/src/app/api/ai/alt-text/route.tsnew file mode 100644index 0000000..1f8e96b--- /dev/null+++ b/src/app/api/ai/alt-text/route.ts@@ -0,0 +1,79 @@+import { NextRequest, NextResponse } from 'next/server'+import { withProvider, DEFAULT_VISION_MODEL } from '@/lib/ai/provider'+import { withLogging } from '@/lib/observability'++export const runtime = 'nodejs'+export const maxDuration = 60++interface AltTextBody {+ image?: string // dataURL or remote URL+}++/** Cap the alt text at the length screen readers usefully announce. */+export const ALT_TEXT_MAX = 200++/**+ * Normalize raw model output into one clean alt-text sentence.+ * Exported for unit tests — the route is a thin shell around it.+ */+export function normalizeAltText(raw: string): string {+ return raw+ .replace(/^["'\s]+|["'\s]+$/g, '')+ .replace(/\s+/g, ' ')+ .replace(/^(alt text|description|image( of)?|photo( of)?|illustration( of)?)[:\s-]*/i, '')+ .trim()+ .slice(0, ALT_TEXT_MAX)+}++/**+ * POST /api/ai/alt-text — accessibility alt text for images (Wave 4).+ *+ * One vision-slot call describing the selected image; the result is a+ * SUGGESTION the user can edit before it is stored on the element+ * (ImageElement.alt — rides autosave/versions/collab, feeds screen+ * readers). Kill switch: altText.+ */+async function __canvix_post(req: NextRequest) {+ const body = (await req.json().catch(() => ({}))) as AltTextBody+ const image = (body.image ?? '').trim()+ if (!image || !/^(data:image\/|https?:\/\/)/.test(image)) {+ return NextResponse.json({ error: 'A valid image is required.' }, { status: 400 })+ }+ if (image.length > 8 * 1024 * 1024) {+ return NextResponse.json({ error: 'Image too large — max ~6 MB.' }, { status: 413 })+ }++ 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,+ messages: [+ {+ role: 'system',+ content:+ 'You write alt text for images in a design tool, for screen-reader users. Reply with ONE plain sentence ' ++ `(max 25 words) describing what is IN the image — subjects, setting, action, text shown. ` ++ 'No prefixes like "image of", no quotes, no commentary. If the image is purely decorative, reply exactly: decorative.',+ },+ {+ role: 'user',+ content: [+ { type: 'text', text: 'Write the alt text for this image now.' },+ { type: 'image_url', image_url: { url: image } },+ ],+ },+ ],+ thinking: { type: 'disabled' },+ })++ const raw = completion.choices[0]?.message?.content ?? ''+ const alt = normalizeAltText(raw)+ if (!alt) {+ return NextResponse.json({ error: 'The AI returned no description. Try again.' }, { status: 502 })+ }+ return NextResponse.json({ alt, decorative: alt.toLowerCase() === 'decorative' })+ })+}++// v0.12.5 (H7): opt-in request logging wrapper — passthrough+// unless CANVIX_LOG=requests (see src/lib/observability.ts)+export const POST = withLogging('POST /api/ai/alt-text', __canvix_post)diff --git a/src/app/api/ai/capabilities/route.ts b/src/app/api/ai/capabilities/route.tsindex 679453b..c43e235 100644--- a/src/app/api/ai/capabilities/route.ts+++ b/src/app/api/ai/capabilities/route.ts@@ -22,14 +22,18 @@ async function __canvix_get() {// only — never config, never keys, never which layer answered.// v0.16.4 (A4): photoSearch left the AI table — it answers on the// stock-provider keys (Pexels/Pixabay), like the Videos rail.- const [text, vision, image, imageEdit, stockPhotos] = await Promise.all([+ // v0.19 (Wave 4): five AI Power-Up capabilities — the text-slot+ // trio (plan/notes/theme), vision-slot alt text, the video slot,+ // and the two LOCAL image tools that need no provider at all.+ const [text, vision, image, imageEdit, video, stockPhotos] = await Promise.all([hasProviderForSlot('text'),hasProviderForSlot('vision'),hasProviderForSlot('image'),hasProviderForSlot('imageEdit'),+ hasProviderForSlot('video'),stockPhotoAvailable(), // async since A5 — keys resolve console-first])- const configured = text || vision || image || imageEdit+ const configured = text || vision || image || imageEdit || videoconst flags = await getFeatures()return NextResponse.json({configured,@@ -44,6 +48,14 @@ async function __canvix_get() {backgroundRemoval: true, // local ONNX — always availablecolorPalette: true, // local deterministiclayoutSuggestions: true, // local deterministic+ // v0.19 (Wave 4 — AI Power-Up):+ agenticPlanning: text && flags.agenticPlanning, // plan → review gate → apply+ notesGeneration: text && flags.notesGeneration, // speaker notes+ themeGeneration: text && flags.themeGeneration, // palette + fonts+ altText: vision && flags.altText, // image alt text+ videoGeneration: video && flags.videoGeneration, // text-to-video slot+ upscale: true, // local Lanczos — always available+ brushEraser: true, // local inpainting — always available},})}diff --git a/src/app/api/ai/image-edit/route.ts b/src/app/api/ai/image-edit/route.tsindex 74900b9..153c8e2 100644--- a/src/app/api/ai/image-edit/route.ts+++ b/src/app/api/ai/image-edit/route.ts@@ -15,6 +15,11 @@ interface EditBody {eraseTarget?: string // for mode=erase: what to removenaturalWidth?: numbernaturalHeight?: number+ /** v0.19 (Wave 4): the provider-side handle of a previously generated/+ * edited image (ImageElement.aiEntId). VibesAI-class providers match+ * edits by exact bytes OR this id — the id survives re-encoding, so+ * AI-edit chains keep working after the canvas touches the src. */+ sourceEntId?: string}/** Pick the SDK output size whose aspect ratio is closest to the source image. */@@ -75,22 +80,56 @@ async function __canvix_post(req: NextRequest) {// NOTE: the SDK's TS type declares `image`, but the backend API requires// `images: [{ url }]` (verified — API error 1210 "must provide images").// The SDK forwards the body verbatim, so we send the correct runtime shape.- const response = await ctx.zai.images.generations.edit({- prompt,- images: [{ url: image }],- size,- } as unknown as Parameters<typeof ctx.zai.images.generations.edit>[0])+ // v0.19 (Wave 4): source_image_ent_id rides the same verbatim body —+ // the durable edit handle for images this provider generated.+ const sourceEntId = typeof body.sourceEntId === 'string' ? body.sourceEntId.trim().slice(0, 64) : undefined+ try {+ const response = await ctx.zai.images.generations.edit({+ prompt,+ images: [{ url: image }],+ size,+ ...(sourceEntId ? { source_image_ent_id: sourceEntId } : {}),+ } as unknown as Parameters<typeof ctx.zai.images.generations.edit>[0])- // v0.16.3 (A3): OpenAI-compatible providers return b64_json; the SDK- // passes such items through untouched (it only converts url items).- const item = response.data[0] as { base64?: string; b64_json?: string } | undefined- const base64 = item?.base64 ?? item?.b64_json- if (!base64) {- return NextResponse.json({ error: 'The image service returned no image. Try again.' }, { status: 502 })- }+ // v0.16.3 (A3): OpenAI-compatible providers return b64_json; the SDK+ // passes such items through untouched (it only converts url items).+ // v0.19 (Wave 4): forward the result's image_ent_id so the client can+ // refresh ImageElement.aiEntId — edit-of-edit chains stay robust.+ const item = response.data[0] as { base64?: string; b64_json?: string; image_ent_id?: string } | undefined+ const base64 = item?.base64 ?? item?.b64_json+ if (!base64) {+ return NextResponse.json({ error: 'The image service returned no image. Try again.' }, { status: 502 })+ }- const [outW, outH] = size.split('x').map(Number)- return NextResponse.json({ dataUrl: `data:image/png;base64,${base64}`, width: outW, height: outH })+ const [outW, outH] = size.split('x').map(Number)+ const entId = typeof item?.image_ent_id === 'string' ? item.image_ent_id.slice(0, 64) : undefined+ return NextResponse.json({+ dataUrl: `data:image/png;base64,${base64}`,+ width: outW,+ height: outH,+ ...(entId ? { entId } : {}),+ })+ } catch (err) {+ // v0.19 (Wave 4): VibesAI-class providers refuse to edit images they+ // did not generate (verified live: HTTP 422 source_image_not_editable+ // for arbitrary uploads AND for their own images after re-encoding).+ // Surface that as a structured, actionable 422 instead of the generic+ // 502 — the client points users at the local tools that DO work on+ // any image (BG remover, brush eraser, upscaler).+ const msg = err instanceof Error ? err.message : String(err)+ if (/source_image_not_editable|only edit images it generated/i.test(msg)) {+ return NextResponse.json(+ {+ error:+ 'This AI provider can only edit images it generated itself. ' ++ 'For uploads and stock photos use the local tools — BG Remover, Brush eraser, Upscale — or generate the image with AI first.',+ code: 'SOURCE_NOT_EDITABLE',+ },+ { status: 422 },+ )+ }+ throw err+ }})}diff --git a/src/app/api/ai/image/route.ts b/src/app/api/ai/image/route.tsindex 3bad465..fddf6af 100644--- a/src/app/api/ai/image/route.ts+++ b/src/app/api/ai/image/route.ts@@ -12,7 +12,6 @@ interface ImageBody {prompt?: stringsize?: string}-/** POST /api/ai/image — AI image generation for the canvas. Returns a PNG dataURL. */async function __canvix_post(req: NextRequest) {const body = (await req.json().catch(() => ({}))) as ImageBody@@ -34,14 +33,25 @@ async function __canvix_post(req: NextRequest) {// v0.16.3 (A3): OpenAI-compatible providers return b64_json; the SDK// passes such items through untouched (it only converts url items).- const item = response.data[0] as { base64?: string; b64_json?: string } | undefined+ // v0.19 (Wave 4): VibesAI-class providers also return image_ent_id —+ // the durable handle for editing THIS image later. Forward it so the+ // client can store it on the element (providers only edit images they+ // generated, and the byte-hash match breaks on re-encode — the id is+ // the robust link; see docs/AI-POWER-UP.md).+ const item = response.data[0] as { base64?: string; b64_json?: string; image_ent_id?: string } | undefinedconst base64 = item?.base64 ?? item?.b64_jsonif (!base64) {return NextResponse.json({ error: 'The image service returned no image. Try again.' }, { status: 502 })}const [w, h] = size.split('x').map(Number)- return NextResponse.json({ dataUrl: `data:image/png;base64,${base64}`, width: w, height: h })+ const entId = typeof item?.image_ent_id === 'string' ? item.image_ent_id.slice(0, 64) : undefined+ return NextResponse.json({+ dataUrl: `data:image/png;base64,${base64}`,+ width: w,+ height: h,+ ...(entId ? { entId } : {}),+ })})}diff --git a/src/app/api/ai/notes/route.ts b/src/app/api/ai/notes/route.tsnew file mode 100644index 0000000..93a67ad--- /dev/null+++ b/src/app/api/ai/notes/route.ts@@ -0,0 +1,113 @@+import { NextRequest, NextResponse } from 'next/server'+import { withProvider } from '@/lib/ai/provider'+import { withLogging } from '@/lib/observability'+import { notesSystemPrompt, normalizeNotes, outlineToPrompt, type PageOutline } from '@/lib/notes-outline'++export const runtime = 'nodejs'+export const maxDuration = 60++interface NotesBody {+ outline?: PageOutline[]+ tone?: string+}++const TONES = ['confident', 'warm', 'formal', 'casual', 'inspirational'] as const++/** Coerce the client-supplied outline: keep only structurally valid+ * entries (defensive — the client is trusted but the route is public+ * same-origin). */+function sanitizeOutline(input: unknown): PageOutline[] {+ const list = Array.isArray(input) ? input.slice(0, 40) : []+ const out: PageOutline[] = []+ for (const raw of list) {+ const p = (raw ?? {}) as Record<string, unknown>+ const index = Math.round(Number(p.index))+ if (!Number.isInteger(index) || index < 0 || index > 999) continue+ out.push({+ index,+ title: typeof p.title === 'string' ? p.title.slice(0, 120) : `Page ${index + 1}`,+ bullets: Array.isArray(p.bullets)+ ? p.bullets.filter((b): b is string => typeof b === 'string').map((b) => b.slice(0, 160)).slice(0, 12)+ : [],+ media: Array.isArray(p.media)+ ? p.media.filter((m): m is string => typeof m === 'string').map((m) => m.slice(0, 60)).slice(0, 8)+ : [],+ })+ }+ return out+}++/** Parse the first {...} out of a model reply (shared repair pass). */+function parseJsonObject(raw: string): Record<string, unknown> | null {+ const start = raw.indexOf('{')+ const end = raw.lastIndexOf('}')+ if (start === -1 || end <= start) return null+ const candidate = raw.slice(start, end + 1)+ try {+ return JSON.parse(candidate) as Record<string, unknown>+ } catch {+ try {+ return JSON.parse(candidate.replace(/,\s*([}\]])/g, '$1')) as Record<string, unknown>+ } catch {+ return null+ }+ }+}++/**+ * POST /api/ai/notes — speaker-notes generation (Wave 4).+ *+ * Input: the page outline (extracted client-side by+ * lib/notes-outline.ts extractOutlines — the model sees content, not+ * geometry). Output: {notes:[{page,text}]} which the notes panel shows+ * as an editable preview before saving per page (another review gate).+ * Slot: text. Kill switch: notesGeneration.+ */+async function __canvix_post(req: NextRequest) {+ const body = (await req.json().catch(() => ({}))) as NotesBody+ const outline = sanitizeOutline(body.outline)+ if (!outline.length) {+ return NextResponse.json({ error: 'Nothing to write notes about — add content to the pages first.' }, { status: 400 })+ }+ const tone = TONES.includes((body.tone ?? '') as (typeof TONES)[number]) ? body.tone! : 'confident'++ return withProvider('notes', req, { limit: 5, windowSec: 60 }, async (ctx) => {+ const system = notesSystemPrompt(outline.length, tone)+ const user = outlineToPrompt(outline)+ const messages = [+ { role: 'system' as const, content: system },+ { role: 'user' as const, content: user },+ ]+ let raw = ''+ try {+ const completion = await ctx.zai.chat.completions.create({+ ...(ctx.model ? { model: ctx.model } : {}),+ messages,+ thinking: { type: 'disabled' },+ response_format: { type: 'json_object' },+ } as never)+ raw = completion.choices[0]?.message?.content ?? ''+ } catch {+ const completion = await ctx.zai.chat.completions.create({+ ...(ctx.model ? { model: ctx.model } : {}),+ messages,+ thinking: { type: 'disabled' },+ })+ raw = completion.choices[0]?.message?.content ?? ''+ }++ const parsed = parseJsonObject(raw)+ if (!parsed) {+ return NextResponse.json({ error: 'The AI reply was not parseable. Try again.' }, { status: 502 })+ }+ const notes = normalizeNotes(parsed, outline.length)+ if (!notes.length) {+ return NextResponse.json({ error: 'The AI produced no usable notes. Try again.' }, { status: 502 })+ }+ return NextResponse.json({ notes })+ })+}++// v0.12.5 (H7): opt-in request logging wrapper — passthrough+// unless CANVIX_LOG=requests (see src/lib/observability.ts)+export const POST = withLogging('POST /api/ai/notes', __canvix_post)diff --git a/src/app/api/ai/plan/route.ts b/src/app/api/ai/plan/route.tsnew file mode 100644index 0000000..5311c4b--- /dev/null+++ b/src/app/api/ai/plan/route.ts@@ -0,0 +1,113 @@+import { NextRequest, NextResponse } from 'next/server'+import { withProvider } from '@/lib/ai/provider'+import { withLogging } from '@/lib/observability'+import { normalizePlan, planSystemPrompt } from '@/lib/design-plan'++export const runtime = 'nodejs'+export const maxDuration = 60++interface PlanBody {+ prompt?: string+ width?: number+ height?: number+ pageCount?: number+}++/** Parse the first {...} JSON object out of a model reply, with a+ * trailing-comma / smart-quote repair pass. Mirrors the MCP tool's+ * parser (src/lib/mcp/tools.ts completeGeneration). */+function parseJsonObject(raw: string): Record<string, unknown> | null {+ const start = raw.indexOf('{')+ const end = raw.lastIndexOf('}')+ if (start === -1 || end <= start) return null+ const candidate = raw.slice(start, end + 1)+ try {+ return JSON.parse(candidate) as Record<string, unknown>+ } catch {+ const repaired = candidate+ .replace(/,\s*([}\]])/g, '$1')+ .replace(/[\u201c\u201d]/g, '"')+ .replace(/[\u2018\u2019]/g, "'")+ try {+ return JSON.parse(repaired) as Record<string, unknown>+ } catch {+ return null+ }+ }+}++/**+ * POST /api/ai/plan — agentic design planning (Wave 4).+ *+ * The agent replies with a STRUCTURED multi-page plan; nothing is+ * persisted. The client renders it as an editable review gate (toggle+ * pages/elements, rewrite copy) and only then applies it to the open+ * design — the "editable review gate" of the roadmap. Slot: text.+ * Kill switch: the admin console's agenticPlanning flag.+ */+async function __canvix_post(req: NextRequest) {+ const body = (await req.json().catch(() => ({}))) as PlanBody+ const prompt = (body.prompt ?? '').trim().slice(0, 2000)+ if (prompt.length < 4) {+ return NextResponse.json({ error: 'Describe what you want to design.' }, { status: 400 })+ }+ const width = Math.min(8000, Math.max(200, Math.round(Number(body.width) || 1080)))+ const height = Math.min(8000, Math.max(200, Math.round(Number(body.height) || 1080)))+ const pageCount = Math.min(6, Math.max(1, Math.round(Number(body.pageCount) || 1)))++ return withProvider('plan', req, { limit: 5, windowSec: 60 }, async (ctx) => {+ const system = planSystemPrompt(width, height, pageCount)+ const user = `Design brief: ${prompt}\nPage size: ${width}x${height}px — plan exactly ${pageCount} page(s).`++ const ask = async (extra: string) => {+ const messages = [+ { role: 'system' as const, content: system },+ { role: 'user' as const, content: extra ? `${user}\n\n${extra}` : user },+ ]+ try {+ const completion = await ctx.zai.chat.completions.create({+ ...(ctx.model ? { model: ctx.model } : {}),+ messages,+ thinking: { type: 'disabled' },+ response_format: { type: 'json_object' },+ } as never)+ return completion.choices[0]?.message?.content ?? ''+ } catch {+ // strict JSON mode unsupported — plain completion+ const completion = await ctx.zai.chat.completions.create({+ ...(ctx.model ? { model: ctx.model } : {}),+ messages,+ thinking: { type: 'disabled' },+ })+ return completion.choices[0]?.message?.content ?? ''+ }+ }++ let parsed = parseJsonObject(await ask(''))+ if (!parsed) {+ parsed = parseJsonObject(+ await ask('Your previous reply was not valid JSON. Reply with ONLY the raw JSON object — no markdown fences, no commentary.'),+ )+ }+ if (!parsed) {+ return NextResponse.json(+ { error: 'The AI reply was not parseable. Try rephrasing the brief.' },+ { status: 502 },+ )+ }++ const plan = normalizePlan(parsed, width, height)+ if (!plan.pages.length) {+ return NextResponse.json(+ { error: 'The AI produced no usable pages. Try a more specific brief.' },+ { status: 502 },+ )+ }+ // the plan rides to the client ONLY — the review gate owns what lands+ return NextResponse.json({ plan })+ })+}++// v0.12.5 (H7): opt-in request logging wrapper — passthrough+// unless CANVIX_LOG=requests (see src/lib/observability.ts)+export const POST = withLogging('POST /api/ai/plan', __canvix_post)diff --git a/src/app/api/ai/theme/route.ts b/src/app/api/ai/theme/route.tsnew file mode 100644index 0000000..8e00da4--- /dev/null+++ b/src/app/api/ai/theme/route.ts@@ -0,0 +1,82 @@+import { NextRequest, NextResponse } from 'next/server'+import { withProvider } from '@/lib/ai/provider'+import { withLogging } from '@/lib/observability'+import { normalizeTheme, themeSystemPrompt } from '@/lib/theme'+import { FONTS } from '@/lib/editor-utils'++export const runtime = 'nodejs'+export const maxDuration = 60++interface ThemeBody {+ prompt?: string+}++/** Parse the first {...} out of a model reply (shared repair pass). */+function parseJsonObject(raw: string): Record<string, unknown> | null {+ const start = raw.indexOf('{')+ const end = raw.lastIndexOf('}')+ if (start === -1 || end <= start) return null+ const candidate = raw.slice(start, end + 1)+ try {+ return JSON.parse(candidate) as Record<string, unknown>+ } catch {+ try {+ return JSON.parse(candidate.replace(/,\s*([}\]])/g, '$1')) as Record<string, unknown>+ } catch {+ return null+ }+ }+}++/**+ * POST /api/ai/theme — AI theme generation (Wave 4).+ *+ * The model proposes a role-tagged palette + font pairing; the client+ * previews swatches and applies them design-wide (lib/theme.ts+ * applyTheme — recolors backgrounds/text/shapes with contrast guards).+ * Slot: text. Kill switch: themeGeneration.+ */+async function __canvix_post(req: NextRequest) {+ const body = (await req.json().catch(() => ({}))) as ThemeBody+ const prompt = (body.prompt ?? '').trim().slice(0, 400)+ if (!prompt) {+ return NextResponse.json({ error: 'Describe the mood you want (e.g. "warm bakery, cozy, earthy").' }, { status: 400 })+ }++ const fontList = FONTS.map((f) => (typeof f === 'string' ? f : f.family))+ return withProvider('theme', req, { limit: 6, windowSec: 60 }, async (ctx) => {+ const system = themeSystemPrompt(fontList)+ const messages = [+ { role: 'system' as const, content: system },+ { role: 'user' as const, content: `Design mood: ${prompt}` },+ ]+ let raw = ''+ try {+ const completion = await ctx.zai.chat.completions.create({+ ...(ctx.model ? { model: ctx.model } : {}),+ messages,+ thinking: { type: 'disabled' },+ response_format: { type: 'json_object' },+ } as never)+ raw = completion.choices[0]?.message?.content ?? ''+ } catch {+ const completion = await ctx.zai.chat.completions.create({+ ...(ctx.model ? { model: ctx.model } : {}),+ messages,+ thinking: { type: 'disabled' },+ })+ raw = completion.choices[0]?.message?.content ?? ''+ }++ const parsed = parseJsonObject(raw)+ if (!parsed) {+ return NextResponse.json({ error: 'The AI reply was not parseable. Try rephrasing the mood.' }, { status: 502 })+ }+ const theme = normalizeTheme(parsed, fontList)+ return NextResponse.json({ theme })+ })+}++// v0.12.5 (H7): opt-in request logging wrapper — passthrough+// unless CANVIX_LOG=requests (see src/lib/observability.ts)+export const POST = withLogging('POST /api/ai/theme', __canvix_post)diff --git a/src/app/api/ai/video/route.test.ts b/src/app/api/ai/video/route.test.tsnew file mode 100644index 0000000..a4eb600--- /dev/null+++ b/src/app/api/ai/video/route.test.ts@@ -0,0 +1,54 @@+// Wave 4 — /api/ai/video status normalizer tests.+import { describe, expect, it } from 'vitest'+import { normalizeVideoStatus } from '@/app/api/ai/video/route'++describe('normalizeVideoStatus', () => {+ it('passes through the Sora-style shape and builds proxy URLs', () => {+ const s = normalizeVideoStatus(+ {+ id: 'batch_123',+ status: 'completed',+ progress: 100,+ videos: [+ { index: 0, id: 'v1', url: 'https://cdn.example/x.mp4', download_path: '/v1/videos/generations/batch_123/content?index=0' },+ { index: 1, id: 'v2', url: 'https://cdn.example/y.mp4' },+ ],+ },+ 'batch_123',+ )+ expect(s.status).toBe('completed')+ expect(s.progress).toBe(100)+ expect(s.videos).toEqual([+ { index: 0, url: '/api/ai/video?id=batch_123&content=1&index=0' },+ { index: 1, url: '/api/ai/video?id=batch_123&content=1&index=1' },+ ])+ })++ it('clamps progress and maps unknown statuses to in_progress', () => {+ const s = normalizeVideoStatus({ status: 'weird', progress: 500 }, 'x')+ expect(s.status).toBe('in_progress')+ expect(s.progress).toBe(100)+ const s2 = normalizeVideoStatus({ progress: -3 }, 'x')+ expect(s2.progress).toBe(0)+ expect(s2.status).toBe('in_progress')+ })++ it('carries errors and survives garbage', () => {+ const s = normalizeVideoStatus({ status: 'failed', error: 'boom' }, 'x')+ expect(s.status).toBe('failed')+ expect(s.error).toBe('boom')+ expect(() => normalizeVideoStatus(null, 'x')).not.toThrow()+ expect(normalizeVideoStatus('junk', 'x').videos).toEqual([])+ // non-integer indexes fall back to array position+ const s2 = normalizeVideoStatus({ status: 'completed', videos: [{ index: 'nope' }] }, 'x')+ expect(s2.videos[0].index).toBe(0)+ })++ it('caps the video list at 4', () => {+ const s = normalizeVideoStatus(+ { status: 'completed', videos: Array.from({ length: 9 }, (_, i) => ({ index: i })) },+ 'x',+ )+ expect(s.videos).toHaveLength(4)+ })+})diff --git a/src/app/api/ai/video/route.ts b/src/app/api/ai/video/route.tsnew file mode 100644index 0000000..2807845--- /dev/null+++ b/src/app/api/ai/video/route.ts@@ -0,0 +1,188 @@+import { NextRequest, NextResponse } from 'next/server'+import { withProvider, resolveSlot, rateLimit, describeProviderError, recordUsage } from '@/lib/ai/provider'+import { aiFeatureEnabled } from '@/lib/admin/config'+import { withLogging } from '@/lib/observability'++export const runtime = 'nodejs'+export const maxDuration = 60++interface VideoBody {+ prompt?: string+ size?: string+}++/** Sizes the vibes/Sora-style video APIs accept (landscape/portrait/square). */+const SUPPORTED_SIZES = ['1024x576', '576x1024', '768x768', '1280x720', '720x1280'] as const+type VideoSize = (typeof SUPPORTED_SIZES)[number]++/** provider video endpoint base — `${baseUrl}/videos/generations` */+function videoBase(baseUrl: string): string {+ return `${baseUrl.replace(/\/+$/, '')}/videos/generations`+}++/** Normalized poll status the client polls expect. */+export interface VideoStatus {+ id: string+ status: 'queued' | 'in_progress' | 'completed' | 'failed'+ progress: number+ /** our own proxy URLs — same-origin, no CORS, no expiring CDNs */+ videos: { index: number; url: string }[]+ error?: string+}++/** Coerce a provider poll reply into VideoStatus (unit-tested shape). */+export function normalizeVideoStatus(raw: unknown, id: string): VideoStatus {+ const body = (raw ?? {}) as Record<string, unknown>+ const statusRaw = typeof body.status === 'string' ? body.status : 'in_progress'+ const status: VideoStatus['status'] =+ statusRaw === 'completed' || statusRaw === 'failed' || statusRaw === 'queued' ? statusRaw : 'in_progress'+ const progress = Math.min(100, Math.max(0, Math.round(Number(body.progress) || 0)))+ const videosRaw = Array.isArray(body.videos) ? body.videos : []+ const videos = videosRaw+ .map((v, i) => {+ const item = (v ?? {}) as Record<string, unknown>+ const index = Math.round(Number(item.index))+ return { index: Number.isInteger(index) && index >= 0 ? index : i }+ })+ .slice(0, 4)+ .map(({ index }) => ({ index, url: `/api/ai/video?id=${encodeURIComponent(id)}&content=1&index=${index}` }))+ const error = typeof body.error === 'string' ? body.error.slice(0, 200) : undefined+ return { id, status, progress, videos, ...(error ? { error } : {}) }+}++/** v0.9.2-style abuse guard (GET paths bypass withProvider's POST check). */+function isFromApp(req: NextRequest): boolean {+ const origin = req.headers.get('origin') ?? req.headers.get('referer')+ if (!origin) return false+ try {+ const parsed = new URL(origin)+ const hosts = [req.headers.get('host'), req.headers.get('x-forwarded-host')?.split(',')[0]?.trim()].filter(+ (h): h is string => Boolean(h),+ )+ return hosts.includes(parsed.host)+ } catch {+ return false+ }+}++/**+ * POST /api/ai/video — start a text-to-video generation (Wave 4).+ * GET /api/ai/video?id=… — poll status ({status, progress, videos[]}).+ * GET /api/ai/video?id=…&content=1&index=N — proxy the finished MP4.+ *+ * The video slot speaks the emerging OpenAI "Sora-style" async shape+ * (POST /videos/generations → id; GET …/:id → status; GET …/:id/content+ * → bytes) — the shape the VibesAI worker exposes. The SDK has no video+ * API, so this route talks to the resolved slot directly. Kill switch:+ * videoGeneration.+ */+async function __canvix_post(req: NextRequest) {+ const body = (await req.json().catch(() => ({}))) as VideoBody+ const prompt = (body.prompt ?? '').trim().slice(0, 1000)+ if (!prompt) {+ return NextResponse.json({ error: 'A prompt is required.' }, { status: 400 })+ }+ const size: VideoSize = (SUPPORTED_SIZES as readonly string[]).includes(body.size ?? '')+ ? (body.size as VideoSize)+ : '1024x576'++ return withProvider('video', req, { limit: 3, windowSec: 60 }, async () => {+ const slot = await resolveSlot('video')+ if (!slot) {+ // unreachable — withProvider already 503'd — but stay total+ return NextResponse.json({ error: 'No video provider configured.' }, { status: 503 })+ }+ const r = await fetch(videoBase(slot.baseUrl), {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${slot.apiKey}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ prompt, size, ...(slot.model ? { model: slot.model } : {}) }),+ })+ const text = await r.text()+ let parsed: Record<string, unknown> = {}+ try {+ parsed = JSON.parse(text) as Record<string, unknown>+ } catch {+ /* provider answered non-JSON */+ }+ if (!r.ok || typeof parsed.id !== 'string' || !parsed.id) {+ const info = describeProviderError(new Error(`API request failed with status ${r.status}: ${text.slice(0, 200)}`))+ return NextResponse.json(+ { error: 'The video service rejected the request.', ...(info.message ? { detail: info.message } : {}) },+ { status: 502 },+ )+ }+ return NextResponse.json({ id: String(parsed.id).slice(0, 128), status: 'queued', progress: 0 })+ })+}++async function __canvix_get(req: NextRequest) {+ const url = new URL(req.url)+ const id = (url.searchParams.get('id') ?? '').trim().slice(0, 128)+ if (!id || !/^[A-Za-z0-9_-]+$/.test(id)) {+ return NextResponse.json({ error: 'A valid generation id is required.' }, { status: 400 })+ }+ if (!(await aiFeatureEnabled('videoGeneration'))) {+ return NextResponse.json({ error: 'This AI feature is disabled by the administrator.', code: 'FEATURE_DISABLED' }, { status: 503 })+ }+ if (!isFromApp(req)) {+ return NextResponse.json({ error: 'Same-origin only.' }, { status: 403 })+ }+ const rl = rateLimit('video-poll', req, 60, 60)+ if (!rl.ok) {+ return NextResponse.json({ error: `Too many requests — retry in ${rl.retryAfterSec}s.` }, { status: 429 })+ }+ const slot = await resolveSlot('video')+ if (!slot) {+ return NextResponse.json({ error: 'No video provider configured.' }, { status: 503 })+ }++ // content proxy: stream the provider's MP4 through our origin+ if (url.searchParams.get('content') === '1') {+ const index = Math.max(0, Math.round(Number(url.searchParams.get('index')) || 0))+ const upstream = await fetch(`${videoBase(slot.baseUrl)}/${id}/content?index=${index}`, {+ headers: { Authorization: `Bearer ${slot.apiKey}` },+ })+ if (!upstream.ok || !upstream.body) {+ void recordUsage('video', slot.label ?? slot.source, false, { status: upstream.status })+ return NextResponse.json({ error: 'The video is not ready yet.' }, { status: upstream.status === 404 ? 404 : 502 })+ }+ return new NextResponse(upstream.body, {+ headers: {+ 'Content-Type': upstream.headers.get('content-type') ?? 'video/mp4',+ 'Cache-Control': 'private, max-age=300',+ 'Content-Disposition': `inline; filename="canvix-video-${id}-${index}.mp4"`,+ },+ })+ }++ // status poll+ const r = await fetch(`${videoBase(slot.baseUrl)}/${id}`, {+ headers: { Authorization: `Bearer ${slot.apiKey}` },+ })+ const text = await r.text()+ let parsed: unknown = {}+ try {+ parsed = JSON.parse(text)+ } catch {+ /* non-JSON error body */+ }+ if (!r.ok) {+ const info = describeProviderError(new Error(`API request failed with status ${r.status}: ${text.slice(0, 200)}`))+ void recordUsage('video', slot.label ?? slot.source, false, { status: r.status, error: info.message })+ return NextResponse.json({ error: 'Polling failed.', ...(info.message ? { detail: info.message } : {}) }, { status: 502 })+ }+ const status = normalizeVideoStatus(parsed, id)+ void recordUsage('video', slot.label ?? slot.source, status.status === 'failed', {+ status: r.status,+ error: status.error,+ })+ return NextResponse.json(status)+}++// v0.12.5 (H7): opt-in request logging wrapper — passthrough+// unless CANVIX_LOG=requests (see src/lib/observability.ts)+export const POST = withLogging('POST /api/ai/video', __canvix_post)+export const GET = withLogging('GET /api/ai/video', __canvix_get)diff --git a/src/components/admin/ai-config.tsx b/src/components/admin/ai-config.tsxindex b09e068..d1d2bed 100644--- a/src/components/admin/ai-config.tsx+++ b/src/components/admin/ai-config.tsx@@ -84,6 +84,8 @@ const SLOT_INFO: { key: string; label: string; hint: string; placeholder: string{ key: 'vision', label: 'Vision', hint: 'Magic Layers — image understanding', placeholder: 'e.g. meta/llama-3.2-90b-vision-instruct' },{ key: 'image', label: 'Image generation', hint: 'Text-to-image in the Photos panel', placeholder: 'provider default' },{ key: 'imageEdit', label: 'Image editing', hint: 'Magic Eraser / Enhance', placeholder: 'provider default' },+ // v0.19 (Wave 4): the video slot — Sora-style async generation+ { key: 'video', label: 'Video generation', hint: 'AI video card in the Videos panel', placeholder: 'provider default' },]const FEATURE_INFO: { key: string; label: string; hint: string }[] = [@@ -94,6 +96,12 @@ const FEATURE_INFO: { key: string; label: string; hint: string }[] = [{ key: 'translation', label: 'Translate', hint: 'Text translation in the text toolbar' },{ key: 'assistant', label: 'Assistant', hint: 'The chat assistant that edits designs' },{ key: 'photoSearch', label: 'Photo search', hint: 'Stock photo search in the Photos panel — Pexels/Pixabay keys, not an AI provider' },+ // v0.19 (Wave 4 — AI Power-Up):+ { key: 'agenticPlanning', label: 'AI design plan', hint: 'Describe → review the plan → apply editable pages' },+ { key: 'notesGeneration', label: 'Speaker notes', hint: 'AI drafts presenter notes (reviewed before saving)' },+ { key: 'themeGeneration', label: 'AI theme', hint: 'Palette + font pairing applied design-wide' },+ { key: 'altText', label: 'Alt text', hint: 'AI alt-text suggestions for images (vision slot)' },+ { key: 'videoGeneration', label: 'Video generation', hint: 'Text-to-video in the Videos panel (video slot)' },]const SOURCE_LABEL: Record<string, string> = {@@ -132,6 +140,7 @@ const SLOT_ENDPOINT: Record<string, string> = {vision: 'chat/completions',image: 'images/generations',imageEdit: 'images/generations/edit',+ video: 'videos/generations',}/** The stock-media connectors (A5) — a fixed set, one free key each,diff --git a/src/components/editor/ImageAI.tsx b/src/components/editor/ImageAI.tsxindex c95ff1a..778be77 100644--- a/src/components/editor/ImageAI.tsx+++ b/src/components/editor/ImageAI.tsx@@ -1,10 +1,11 @@'use client'-import { useState } from 'react'-import { Eraser, Wand2, Loader2, Sparkles } from 'lucide-react'+import { useCallback, useEffect, useRef, useState } from 'react'+import { Eraser, Wand2, Loader2, Sparkles, Brush, Maximize2, Accessibility } from 'lucide-react'import { useEditorStore } from '@/store/editor-store'import type { ImageElement } from '@/lib/types'import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'import { Button } from '@/components/ui/button'import { Input } from '@/components/ui/input'import { toast } from '@/hooks/use-toast'@@ -16,6 +17,11 @@ interface EditResponse {error?: string/** scrubbed provider reason (502 PROVIDER_ERROR bodies) — shown to the user */detail?: string+ /** v0.19 (Wave 4): structured error codes — SOURCE_NOT_EDITABLE is the+ * VibesAI-class "only edits its own generations" refusal. */+ code?: string+ /** v0.19 (Wave 4): provider handle of the result (ImageElement.aiEntId) */+ entId?: string}/** Pull a human reason out of a provider `detail` string. The API layer@@ -66,11 +72,22 @@ async function runImageAI(const res = await fetch('/api/ai/image-edit', {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ image, naturalWidth: el.naturalWidth, naturalHeight: el.naturalHeight, ...payload }),+ // v0.19 (Wave 4): forward the provider handle so edits of AI-generated+ // images match by id — the byte-hash match breaks on re-encode.+ body: JSON.stringify({+ image,+ naturalWidth: el.naturalWidth,+ naturalHeight: el.naturalHeight,+ ...(el.aiEntId ? { sourceEntId: el.aiEntId } : {}),+ ...payload,+ }),})const data = (await res.json()) as EditResponseif (!res.ok || !data.dataUrl) {- const reason = providerReason(data.detail)+ // SOURCE_NOT_EDITABLE (422): the provider only edits its own+ // generations — the route's message already points at the local+ // tools that work on any image.+ const reason = data.code === 'SOURCE_NOT_EDITABLE' ? '' : providerReason(data.detail)onDone(reason ? `${data.error ?? 'The edit failed.'} — ${reason.slice(0, 220)}` : (data.error ?? 'The edit failed. Please try again.'))return false}@@ -83,6 +100,9 @@ async function runImageAI(naturalWidth: w,naturalHeight: h,height: newHeight,+ // refresh the provider handle — the edit result is the new+ // editable image (cleared when the provider returns none)+ aiEntId: data.entId,})return true} catch {@@ -239,3 +259,466 @@ export function EnhanceButton({ el }: { el: ImageElement }) {</button>)}++/** ── v0.19 (Wave 4): local image power tools ───────────────────+ * Both run entirely in the browser on ANY image — uploads, stock+ * photos, AI generations — no provider, no network, no model+ * download. This is the universal path: VibesAI-class edit providers+ * only edit images they generated themselves (422 otherwise). */++/** dataURL → HTMLImageElement (decoded) */+function loadImage(src: string): Promise<HTMLImageElement> {+ return new Promise((resolve, reject) => {+ const img = new window.Image()+ img.onload = () => resolve(img)+ img.onerror = () => reject(new Error('Could not decode the image'))+ img.src = src+ })+}++/** Raster bytes → ImageData. TS's ImageData ctor wants+ * Uint8ClampedArray<ArrayBuffer>; a fresh copy satisfies it on every+ * TS version (and costs nothing next to the resample itself). */+function toImageData(data: Uint8ClampedArray, w: number, h: number): ImageData {+ const copy = new Uint8ClampedArray(data.byteLength)+ copy.set(data)+ return new ImageData(copy, w, h)+}++/** Canva-style "Upscale" — Lanczos-3 2x/4x with alpha discipline. */+export function UpscaleButton({ el }: { el: ImageElement }) {+ const [busy, setBusy] = useState(false)+ const [factor, setFactor] = useState<2 | 4>(2)+ const [open, setOpen] = useState(false)++ const run = async () => {+ if (busy) return+ setBusy(true)+ const update = useEditorStore.getState().updateElements+ try {+ const { lanczosUpscale, factorFor } = await import('@/lib/upscale')+ const sendable = await toSendableImage(el.src)+ const img = await loadImage(sendable)+ const src = { width: img.naturalWidth, height: img.naturalHeight }+ const f = factorFor(src.width, src.height, factor)+ if (f === 1) {+ toast({+ title: 'Upscale',+ description: `This image is already at the size cap (${src.width}×${src.height}px).`,+ })+ return+ }+ const canvas = document.createElement('canvas')+ canvas.width = src.width+ canvas.height = src.height+ const ctx = canvas.getContext('2d', { willReadFrequently: true })+ if (!ctx) throw new Error('Canvas is unavailable')+ ctx.drawImage(img, 0, 0)+ const inData = ctx.getImageData(0, 0, src.width, src.height)+ const out = lanczosUpscale(+ { data: inData.data, width: src.width, height: src.height },+ f,+ )+ canvas.width = out.width+ canvas.height = out.height+ ctx.putImageData(toImageData(out.data, out.width, out.height), 0, 0)+ const dataUrl = canvas.toDataURL('image/png')+ const newHeight = Math.max(4, Math.round(el.width * (out.height / Math.max(1, out.width))))+ update([el.id], {+ src: dataUrl,+ naturalWidth: out.width,+ naturalHeight: out.height,+ height: newHeight,+ })+ toast({+ title: `Upscaled ${f}×`,+ description: `${src.width}×${src.height} → ${out.width}×${out.height}px. Ctrl+Z to undo.`,+ })+ setOpen(false)+ } catch (e) {+ toast({+ title: 'Upscale',+ description: e instanceof Error ? e.message : 'Could not upscale this image.',+ variant: 'destructive',+ })+ } finally {+ setBusy(false)+ }+ }++ const target = `${Math.min(8192, el.naturalWidth * factor)}×${Math.min(8192, el.naturalHeight * factor)}`+ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <button className={btnBase} data-active={open} title="Upscale — enlarge this image locally (Lanczos)" aria-label="Upscale image">+ <Maximize2 size={14} />+ <span className="text-[12px] hidden lg:inline">Upscale</span>+ </button>+ </PopoverTrigger>+ <PopoverContent align="center" side="bottom" className="w-[280px] rounded-2xl bg-[#1A1C22] border-white/10 text-white p-3.5">+ <div className="text-[13px] font-bold mb-1 flex items-center gap-1.5">+ <Maximize2 size={13} className="text-[#02C0CC]" /> Upscale+ </div>+ <p className="text-[11px] text-white/55 mb-2.5 leading-snug">+ Enlarge with high-quality Lanczos resampling — runs locally, works on any image, keeps transparency.+ Now {el.naturalWidth}×{el.naturalHeight}px.+ </p>+ <div className="flex gap-1.5 mb-2.5">+ {([2, 4] as const).map((f) => (+ <button+ key={f}+ onClick={() => setFactor(f)}+ className={`flex-1 h-9 rounded-lg text-[12px] font-semibold border transition-colors ${+ factor === f ? 'bg-[#02C0CC] text-black border-[#02C0CC]' : 'bg-white/5 border-white/10 text-white/80 hover:bg-white/10'+ }`}+ aria-pressed={factor === f}+ >+ {f}× → {Math.min(8192, el.naturalWidth * f)}px+ </button>+ ))}+ </div>+ <Button className="btn-cv w-full h-9 text-[12px]" onClick={() => void run()} disabled={busy}>+ {busy ? <Loader2 size={13} className="animate-spin" /> : `Upscale to ${target}`}+ </Button>+ </PopoverContent>+ </Popover>+ )+}++/** Canva-style "Brush eraser" — paint over unwanted objects; the region+ * is reconstructed from its surroundings (local pyramid-diffusion+ * inpainting — no model download, no provider, works offline). */+export function BrushEraserDialog({ el }: { el: ImageElement }) {+ const [open, setOpen] = useState(false)+ const [busy, setBusy] = useState(false)+ const [brush, setBrush] = useState(36)+ const [painted, setPainted] = useState(false)+ const baseRef = useRef<HTMLCanvasElement | null>(null)+ const maskRef = useRef<HTMLCanvasElement | null>(null)+ const wrapRef = useRef<HTMLDivElement | null>(null)+ const painting = useRef(false)+ const lastPt = useRef<{ x: number; y: number } | null>(null)+ /** display geometry, set when the image decodes */+ const [disp, setDisp] = useState<{ w: number; h: number } | null>(null)++ // (re)draw the base image whenever the dialog opens / element changes+ useEffect(() => {+ if (!open || !baseRef.current || !maskRef.current) return+ let cancelled = false+ setPainted(false)+ ;(async () => {+ try {+ const sendable = await toSendableImage(el.src)+ const img = await loadImage(sendable)+ if (cancelled) return+ // fit inside ~62vh / 640px while preserving the aspect ratio+ const maxW = 640+ const maxH = Math.round(window.innerHeight * 0.62)+ const s = Math.min(maxW / img.naturalWidth, maxH / img.naturalHeight, 1)+ const w = Math.max(80, Math.round(img.naturalWidth * s))+ const h = Math.max(80, Math.round(img.naturalHeight * s))+ setDisp({ w, h })+ const base = baseRef.current!+ const mask = maskRef.current!+ base.width = w+ base.height = h+ mask.width = w+ mask.height = h+ const bctx = base.getContext('2d')+ const mctx = mask.getContext('2d')+ if (!bctx || !mctx) return+ bctx.clearRect(0, 0, w, h)+ bctx.drawImage(img, 0, 0, w, h)+ mctx.clearRect(0, 0, w, h)+ } catch {+ /* decode failure leaves disp null → the hint stays visible */+ }+ })()+ return () => {+ cancelled = true+ }+ }, [open, el.src])++ const drawMaskStroke = useCallback(+ (x: number, y: number) => {+ const mask = maskRef.current+ if (!mask) return+ const ctx = mask.getContext('2d')+ if (!ctx) return+ ctx.fillStyle = 'rgba(255,0,128,0.85)'+ const r = brush / 2+ // full-opacity stroke: keep painting round dots along the move path+ ctx.beginPath()+ ctx.arc(x, y, r, 0, Math.PI * 2)+ ctx.fill()+ const lp = lastPt.current+ if (lp) {+ // interpolate between events so fast strokes stay continuous+ const d = Math.hypot(x - lp.x, y - lp.y)+ const steps = Math.max(1, Math.floor(d / (r * 0.5)))+ for (let i = 1; i < steps; i++) {+ const ix = lp.x + ((x - lp.x) * i) / steps+ const iy = lp.y + ((y - lp.y) * i) / steps+ ctx.beginPath()+ ctx.arc(ix, iy, r, 0, Math.PI * 2)+ ctx.fill()+ }+ }+ lastPt.current = { x, y }+ setPainted(true)+ },+ [brush],+ )++ const pointerPos = (e: React.PointerEvent): { x: number; y: number } | null => {+ const mask = maskRef.current+ if (!mask) return null+ const rect = mask.getBoundingClientRect()+ return {+ x: ((e.clientX - rect.left) / rect.width) * mask.width,+ y: ((e.clientY - rect.top) / rect.height) * mask.height,+ }+ }++ const clearMask = () => {+ const mask = maskRef.current+ const ctx = mask?.getContext('2d')+ if (mask && ctx) ctx.clearRect(0, 0, mask.width, mask.height)+ setPainted(false)+ }++ const run = async () => {+ if (busy || !painted || !disp) return+ setBusy(true)+ const update = useEditorStore.getState().updateElements+ try {+ const { inpaint } = await import('@/lib/inpaint')+ const sendable = await toSendableImage(el.src)+ const img = await loadImage(sendable)+ const w = img.naturalWidth+ const h = img.naturalHeight+ // decode the source at natural resolution+ const srcCanvas = document.createElement('canvas')+ srcCanvas.width = w+ srcCanvas.height = h+ const sctx = srcCanvas.getContext('2d', { willReadFrequently: true })+ if (!sctx) throw new Error('Canvas is unavailable')+ sctx.drawImage(img, 0, 0)+ const srcData = sctx.getImageData(0, 0, w, h)+ // scale the painted mask up to natural resolution+ const maskCanvas = document.createElement('canvas')+ maskCanvas.width = w+ maskCanvas.height = h+ const mctx = maskCanvas.getContext('2d', { willReadFrequently: true })+ if (!mctx) throw new Error('Canvas is unavailable')+ mctx.imageSmoothingEnabled = false+ mctx.drawImage(maskRef.current!, 0, 0, w, h)+ const maskData = mctx.getImageData(0, 0, w, h)+ // run the reconstruction on the main thread — hole sizes are+ // brush-scale, and the yields below keep the tab responsive+ await new Promise((r) => requestAnimationFrame(() => r(null)))+ const out = inpaint(+ { data: srcData.data, width: w, height: h },+ { data: maskData.data, width: w, height: h },+ )+ srcCanvas.width = w+ srcCanvas.height = h+ sctx.putImageData(toImageData(out.data, w, h), 0, 0)+ const dataUrl = srcCanvas.toDataURL('image/png')+ update([el.id], { src: dataUrl })+ toast({+ title: 'Erased',+ description: 'The painted region was reconstructed. Ctrl+Z to undo.',+ })+ setOpen(false)+ } catch (e) {+ toast({+ title: 'Brush eraser',+ description: e instanceof Error ? e.message : 'Could not erase. Please try again.',+ variant: 'destructive',+ })+ } finally {+ setBusy(false)+ }+ }++ return (+ <Dialog open={open} onOpenChange={setOpen}>+ <button className={btnBase} onClick={() => setOpen(true)} title="Brush eraser — paint over anything to remove it" aria-label="Brush eraser">+ <Brush size={14} />+ <span className="text-[12px] hidden lg:inline">Brush eraser</span>+ </button>+ <DialogContent className="max-w-[720px] rounded-2xl bg-[#14161B] border-white/10 text-white">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-1.5 text-[15px]">+ <Brush size={15} className="text-[#02C0CC]" /> Brush eraser+ </DialogTitle>+ </DialogHeader>+ <p className="text-[12px] text-white/55 -mt-1 mb-2 leading-snug">+ Paint over whatever should disappear — people, objects, watermarks. The region is rebuilt from+ its surroundings, entirely on your device (works offline, on any image).+ </p>+ <div+ ref={wrapRef}+ className="relative mx-auto select-none touch-none rounded-xl overflow-hidden border border-white/10 bg-[repeating-conic-gradient(#20242c_0%_25%,#181b21_0%_50%)] bg-[length:16px_16px]"+ style={{ width: disp ? disp.w : undefined, height: disp ? disp.h : undefined, cursor: 'crosshair' }}+ >+ <canvas ref={baseRef} className="block max-w-full" />+ <canvas+ ref={maskRef}+ className="absolute inset-0 w-full h-full"+ style={{ cursor: 'crosshair' }}+ aria-label="Erase brush area"+ onPointerDown={(e) => {+ e.currentTarget.setPointerCapture(e.pointerId)+ painting.current = true+ lastPt.current = null+ const p = pointerPos(e)+ if (p) drawMaskStroke(p.x, p.y)+ }}+ onPointerMove={(e) => {+ if (!painting.current) return+ const p = pointerPos(e)+ if (p) drawMaskStroke(p.x, p.y)+ }}+ onPointerUp={() => {+ painting.current = false+ lastPt.current = null+ }}+ onPointerCancel={() => {+ painting.current = false+ lastPt.current = null+ }}+ />+ {!disp && (+ <div className="flex items-center justify-center h-56 text-[12px] text-white/45">Decoding image…</div>+ )}+ </div>+ <div className="flex items-center gap-3 mt-1">+ <span className="text-[11px] text-white/55 shrink-0">Brush</span>+ <input+ type="range"+ min={8}+ max={120}+ value={brush}+ onChange={(e) => setBrush(Number(e.target.value))}+ className="flex-1 accent-[#02C0CC]"+ aria-label="Brush size"+ />+ <span className="text-[11px] text-white/40 w-8 text-right">{brush}px</span>+ <button+ className="text-[11px] text-white/55 hover:text-white px-2 h-7 rounded-md hover:bg-white/10"+ onClick={clearMask}+ >+ Clear+ </button>+ </div>+ <div className="flex justify-end gap-2 mt-1">+ <Button variant="ghost" className="h-9 text-[12px] text-white/70 hover:text-white" onClick={() => setOpen(false)}>+ Cancel+ </Button>+ <Button className="btn-cv h-9 px-4 text-[12px]" onClick={() => void run()} disabled={busy || !painted}>+ {busy ? <Loader2 size={13} className="animate-spin" /> : 'Erase painted area'}+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ )+}++/** ── v0.19 (Wave 4): accessibility alt text ──────────────────── */++/** Alt-text editor + AI suggestion for the selected image. The stored+ * value (ImageElement.alt) feeds screen-reader landmarks; the AI draft+ * is a SUGGESTION the user reviews/edits before saving. */+export function AltTextPopover({ el }: { el: ImageElement }) {+ const [open, setOpen] = useState(false)+ const [value, setValue] = useState(el.alt ?? '')+ const [busy, setBusy] = useState(false)++ // re-sync when the selection moves to another element / the element's+ // alt changes elsewhere — the render-time adjust pattern (React docs),+ // not an effect+ const [lastAlt, setLastAlt] = useState(el.alt ?? '')+ if ((el.alt ?? '') !== lastAlt) {+ setLastAlt(el.alt ?? '')+ setValue(el.alt ?? '')+ }++ const update = useEditorStore.getState().updateElements++ const generate = async () => {+ if (busy) return+ setBusy(true)+ try {+ const image = await toSendableImage(el.src)+ const res = await fetch('/api/ai/alt-text', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ image }),+ })+ const data = (await res.json()) as { alt?: string; error?: string }+ if (!res.ok || !data.alt) throw new Error(data.error ?? 'Generation failed')+ setValue(data.alt)+ } catch (e) {+ toast({+ title: 'Alt text',+ description: e instanceof Error ? e.message : 'Could not generate. Try again.',+ variant: 'destructive',+ })+ } finally {+ setBusy(false)+ }+ }++ const save = () => {+ const alt = value.trim().slice(0, 200)+ update([el.id], alt ? { alt } : { alt: undefined })+ toast({ title: alt ? 'Alt text saved' : 'Alt text cleared', description: 'Used by screen readers — never shown visually.' })+ setOpen(false)+ }++ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <button className={btnBase} data-active={open} title="Alt text — describe this image for screen readers" aria-label="Alt text">+ <Accessibility size={14} />+ <span className="text-[12px] hidden lg:inline">Alt</span>+ {el.alt ? <span className="w-1.5 h-1.5 rounded-full bg-[#02C0CC]" title="Has alt text" /> : null}+ </button>+ </PopoverTrigger>+ <PopoverContent align="center" side="bottom" className="w-[300px] rounded-2xl bg-[#1A1C22] border-white/10 text-white p-3.5">+ <div className="text-[13px] font-bold mb-1 flex items-center gap-1.5">+ <Accessibility size={13} className="text-[#02C0CC]" /> Alt text+ </div>+ <p className="text-[11px] text-white/55 mb-2.5 leading-snug">+ One sentence describing what is in the image — read aloud by screen readers, required for accessible+ exports.+ </p>+ <textarea+ value={value}+ onChange={(e) => setValue(e.target.value)}+ placeholder="e.g. A barista pouring latte art in a sunlit café"+ className="w-full h-20 resize-none rounded-lg bg-white/5 border border-white/10 px-2.5 py-2 text-[12px] text-white/85 placeholder:text-white/30 focus:outline-none focus:border-[#02C0CC]"+ aria-label="Alt text"+ maxLength={200}+ data-testid="alt-text-input"+ />+ <div className="flex gap-1.5 mt-2.5">+ <Button+ variant="ghost"+ className="h-9 px-3 text-[12px] text-white/70 hover:text-white border border-white/10"+ onClick={() => void generate()}+ disabled={busy}+ >+ {busy ? <Loader2 size={13} className="animate-spin" /> : <Sparkles size={13} className="text-[#02C0CC]" />}+ Generate+ </Button>+ <Button className="btn-cv h-9 px-3 ml-auto text-[12px]" onClick={save}>+ Save+ </Button>+ </div>+ </PopoverContent>+ </Popover>+ )+}diff --git a/src/components/editor/NotesAIGenerator.tsx b/src/components/editor/NotesAIGenerator.tsxnew file mode 100644index 0000000..372ec62--- /dev/null+++ b/src/components/editor/NotesAIGenerator.tsx@@ -0,0 +1,132 @@+'use client'++import { useState } from 'react'+import { Loader2, NotebookPen, Sparkles } from 'lucide-react'+import { useEditorStore } from '@/store/editor-store'+import { extractOutlines } from '@/lib/notes-outline'+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'+import { Button } from '@/components/ui/button'+import { toast } from '@/hooks/use-toast'++/**+ * v0.19 (Wave 4) — AI speaker-notes generation with a review gate.+ *+ * The page OUTLINE (titles + bullets, extracted by lib/notes-outline —+ * the model sees content, not geometry) goes to /api/ai/notes; the+ * reply renders as one EDITABLE textarea per page; Apply writes each+ * page's notes via setPageNotes. Nothing lands unreviewed.+ */+export function NotesAIGenerator() {+ const [busy, setBusy] = useState(false)+ const [open, setOpen] = useState(false)+ const [draft, setDraft] = useState<{ page: number; text: string }[]>([])++ const generate = async () => {+ if (busy) return+ const s = useEditorStore.getState()+ const outline = extractOutlines(s.pages)+ if (!outline.length) {+ toast({ title: 'No pages to write notes about.' })+ return+ }+ setBusy(true)+ try {+ const res = await fetch('/api/ai/notes', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ outline, tone: 'confident' }),+ })+ const data = (await res.json()) as { notes?: { page: number; text: string }[]; error?: string }+ if (!res.ok || !data.notes?.length) throw new Error(data.error ?? 'Generation failed')+ setDraft(data.notes)+ setOpen(true)+ } catch (e) {+ toast({+ title: 'Notes generation',+ description: e instanceof Error ? e.message : 'Failed. Try again.',+ variant: 'destructive',+ })+ } finally {+ setBusy(false)+ }+ }++ const apply = () => {+ const s = useEditorStore.getState()+ let written = 0+ for (const n of draft) {+ const page = s.pages[n.page - 1]+ if (page?.id) {+ s.setPageNotes(page.id, n.text)+ written+++ }+ }+ toast({ title: `Notes written for ${written} page${written === 1 ? '' : 's'}`, description: 'Edit them any time — they never appear on the canvas or in exports.' })+ setOpen(false)+ }++ const pages = useEditorStore((s) => s.pages)++ return (+ <>+ <button+ className="flex items-center gap-1 text-[11px] text-[#02C0CC] hover:text-[#4de0e8] px-1.5 h-7 rounded-md hover:bg-[#02C0CC]/10 font-semibold"+ onClick={() => void generate()}+ disabled={busy}+ title="Generate speaker notes for every page with AI"+ aria-label="Generate speaker notes with AI"+ data-testid="notes-ai-generate"+ >+ {busy ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}+ Generate with AI+ </button>++ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent className="max-w-[560px] max-h-[80vh] overflow-y-auto rounded-2xl bg-[#14161B] border-white/10 text-white">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-1.5 text-[15px]">+ <NotebookPen size={15} className="text-[#02C0CC]" /> Speaker notes — review & edit+ </DialogTitle>+ </DialogHeader>+ <p className="text-[12px] text-white/55 -mt-1 mb-2 leading-snug">+ AI drafts for {draft.length} page{draft.length === 1 ? '' : 's'}. Edit anything — Apply writes each+ page's notes (existing notes are replaced).+ </p>+ <div className="space-y-2.5">+ {draft.map((n, i) => (+ <div key={n.page}>+ <div className="text-[11px] font-semibold text-white/60 mb-1 flex items-baseline gap-2">+ Page {n.page}+ <span className="text-white/35 font-normal truncate">+ {pages[n.page - 1]+ ? (pages[n.page - 1].elements ?? [])+ .filter((e) => e.type === 'text')+ .sort((a, b) => b.fontSize - a.fontSize)[0]?.text?.slice(0, 46) ?? '—'+ : '—'}+ </span>+ </div>+ <textarea+ value={n.text}+ onChange={(e) =>+ setDraft((d) => d.map((x, j) => (j === i ? { ...x, text: e.target.value } : x)))+ }+ className="w-full h-20 resize-none rounded-lg bg-black/30 border border-white/10 px-2.5 py-2 text-[12.5px] text-white/85 focus:outline-none focus:border-[#02C0CC]"+ aria-label={`Notes for page ${n.page}`}+ maxLength={600}+ />+ </div>+ ))}+ </div>+ <div className="flex justify-end gap-2 mt-1">+ <Button variant="ghost" className="h-9 text-[12px] text-white/70 hover:text-white" onClick={() => setOpen(false)}>+ Cancel+ </Button>+ <Button className="btn-cv h-9 px-4 text-[12px]" onClick={apply}>+ Apply to pages+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ </>+ )+}diff --git a/src/components/editor/PageBar.tsx b/src/components/editor/PageBar.tsxindex 4e4410a..240e257 100644--- a/src/components/editor/PageBar.tsx+++ b/src/components/editor/PageBar.tsx@@ -6,6 +6,7 @@ import { useEditorStore } from '@/store/editor-store'import { DesignPreview } from '@/components/design-preview'import { pageSize, PRESET_SIZES } from '@/lib/editor-utils'import { cn } from '@/lib/utils'+import { NotesAIGenerator } from './NotesAIGenerator'const THUMB_H = 52@@ -144,6 +145,10 @@ export function PageBar() {data-testid="notes-textarea"className="w-full h-28 resize-none rounded-lg bg-black/30 border border-white/10 px-2.5 py-2 text-[13px] text-white/85 placeholder:text-white/30 focus:outline-none focus:border-[#02C0CC]"/>+ {/* v0.19 (Wave 4): AI notes generation (review gate inside) */}+ <div className="mt-1.5">+ <NotesAIGenerator />+ </div><div className="text-[11px] text-white/40 mt-1.5">Shown in presenter view — never on the canvas or in exports.</div>diff --git a/src/components/editor/PropertiesBar.tsx b/src/components/editor/PropertiesBar.tsxindex a37736c..430d43f 100644--- a/src/components/editor/PropertiesBar.tsx+++ b/src/components/editor/PropertiesBar.tsx@@ -29,7 +29,7 @@ import { IMAGE_FILTER_PRESETS, applyPresetToImageData, isImageFilterId, clampFilimport { MASK_SHAPES, MASK_SHAPE_LABELS, isMaskShape, maskPolygon } from '@/lib/shapes'import { useLoadedImage } from './canvas/use-loaded-image'import { ToolbarPopover, SliderRow, IconTile } from './toolbar/popover-kit'-import { BgRemoverButton, MagicEraserPopover, EnhanceButton } from './ImageAI'+import { BgRemoverButton, MagicEraserPopover, EnhanceButton, UpscaleButton, BrushEraserDialog, AltTextPopover } from './ImageAI'const ALIGN_ICONS = {left: AlignLeft,@@ -446,6 +446,10 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'm<BgRemoverButton el={image} /><MagicEraserPopover el={image} /><EnhanceButton el={image} />+ {/* v0.19 (Wave 4): local image power tools — any image, offline */}+ <UpscaleButton el={image} />+ <BrushEraserDialog el={image} />+ <AltTextPopover el={image} /><Divider /><ImageFilterPopover el={image} ids={ids} /><ToolbarPopover trigger={(open) => (diff --git a/src/components/editor/add-element.ts b/src/components/editor/add-element.tsindex 0b079d5..6d67394 100644--- a/src/components/editor/add-element.ts+++ b/src/components/editor/add-element.ts@@ -655,3 +655,36 @@ export async function addStockPhoto(}throw firstError instanceof Error ? firstError : new Error('Could not add the stock photo.')}++/** v0.19 (Wave 4): insert an AI-GENERATED video (the /api/ai/video+ * proxy URL). Same pipeline as stock video: download the bytes in the+ * browser, ride the chunked media store (quota, dedupe, size cap),+ * probe the real dimensions + first-frame poster, place it. No credit+ * block — the element is the user's own generation. */+export async function addGeneratedVideo(url: string, onProgress?: (ratio: number) => void): Promise<void> {+ const { uploadMediaFile, mediaSrc } = await import('@/lib/media/media-client')+ const { probeVideoFile } = await import('@/lib/media/decode')+ const { createVideoElement } = await import('@/lib/types')++ const blob = await fetch(url).then((r) => {+ if (!r.ok) throw new Error(`Download failed (${r.status}).`)+ return r.blob()+ })+ const file = new File([blob], `ai-video-${Date.now()}.mp4`, { type: blob.type || 'video/mp4' })+ const [handle, probe] = await Promise.all([uploadMediaFile(file, onProgress), probeVideoFile(file)])++ const store = useEditorStore.getState()+ const naturalW = probe.naturalWidth || 1024+ const naturalH = probe.naturalHeight || 576+ const maxW = store.width * 0.7+ const w = Math.round(Math.min(maxW, Math.max(200, naturalW)))+ const h = Math.round((w * naturalH) / naturalW)+ const pos = placement(w, h, store.pages[store.currentPage].elements.length)+ store.addElement(+ createVideoElement(mediaSrc(handle.id), probe.poster, probe.duration, naturalW, naturalH, {+ ...pos,+ width: w,+ height: h,+ }),+ )+}diff --git a/src/components/editor/apps/AIImageApp.tsx b/src/components/editor/apps/AIImageApp.tsxindex 2452a3d..fd5e953 100644--- a/src/components/editor/apps/AIImageApp.tsx+++ b/src/components/editor/apps/AIImageApp.tsx@@ -35,6 +35,9 @@ interface Generated {width: numberheight: numberprompt: string+ /** v0.19 (Wave 4): provider handle (image_ent_id) — stored on the+ * element so AI-edit chains keep matching after re-encodes. */+ entId?: string}export function AIImageApp({ onClose }: AppPanelProps) {@@ -86,6 +89,8 @@ export function AIImageApp({ onClose }: AppPanelProps) {y: Math.max(0, (designH - h) / 2),width: w,height: h,+ // v0.19 (Wave 4): keep the provider handle for later AI edits+ ...(image.entId ? { aiEntId: image.entId } : {}),}))toast({ title: 'AI image added' })diff --git a/src/components/editor/apps/AIPlanApp.tsx b/src/components/editor/apps/AIPlanApp.tsxnew file mode 100644index 0000000..cf06b2e--- /dev/null+++ b/src/components/editor/apps/AIPlanApp.tsx@@ -0,0 +1,328 @@+'use client'++import { useState } from 'react'+import { Bot, Loader2, Check, Eye, EyeOff, Sparkles } from 'lucide-react'+import { useEditorStore } from '@/store/editor-store'+import { planToPages, type DesignPlan, type PlanPageSpec } from '@/lib/design-plan'+import { AppHeader, type AppPanelProps } from './registry'+import { cn } from '@/lib/utils'+import { toast } from '@/hooks/use-toast'++const IDEAS = [+ 'A 4-page launch deck for a specialty coffee subscription — warm, cozy, earthy',+ 'Instagram post + story for a fitness studio opening — bold, high energy',+ '3-page pitch outline for an eco packaging startup — clean, green, minimal',+]++/**+ * v0.19 (Wave 4) — Agentic design planning with an EDITABLE REVIEW GATE.+ *+ * Step 1: the user describes the design; /api/ai/plan returns a+ * structured multi-page plan (nothing is applied yet).+ * Step 2: the gate — every page and element can be toggled, every text+ * rewritten, colors seen — before anything lands.+ * Step 3: Apply → planToPages() → store.appendPages() as fully editable+ * native elements. Ctrl+Z undoes the whole apply.+ */+export function AIPlanApp({ onClose }: AppPanelProps) {+ const [prompt, setPrompt] = useState('')+ const [pageCount, setPageCount] = useState(2)+ const [busy, setBusy] = useState(false)+ const [error, setError] = useState<string | null>(null)+ const [plan, setPlan] = useState<DesignPlan | null>(null)++ const width = useEditorStore((s) => s.width)+ const height = useEditorStore((s) => s.height)++ const generate = async () => {+ if (!prompt.trim() || busy) return+ setBusy(true)+ setError(null)+ setPlan(null)+ try {+ const res = await fetch('/api/ai/plan', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ prompt: prompt.trim(), width, height, pageCount }),+ })+ const data = (await res.json()) as { plan?: DesignPlan; error?: string }+ if (!res.ok || !data.plan) throw new Error(data.error ?? 'Planning failed')+ setPlan(data.plan)+ } catch (e) {+ setError(e instanceof Error ? e.message : 'Planning failed')+ } finally {+ setBusy(false)+ }+ }++ const togglePage = (id: string) => {+ setPlan((p) =>+ p ? { ...p, pages: p.pages.map((pg) => (pg.id === id ? { ...pg, enabled: !pg.enabled } : pg)) } : p,+ )+ }+ const toggleElement = (pageId: string, elId: string) => {+ setPlan((p) =>+ p+ ? {+ ...p,+ pages: p.pages.map((pg) =>+ pg.id !== pageId+ ? pg+ : { ...pg, elements: pg.elements.map((el) => (el.id === elId ? { ...el, enabled: !el.enabled } : el)) },+ ),+ }+ : p,+ )+ }+ const editText = (pageId: string, elId: string, text: string) => {+ setPlan((p) =>+ p+ ? {+ ...p,+ pages: p.pages.map((pg) =>+ pg.id !== pageId+ ? pg+ : { ...pg, elements: pg.elements.map((el) => (el.id === elId ? { ...el, text } : el)) },+ ),+ }+ : p,+ )+ }++ const apply = () => {+ if (!plan) return+ const pages = planToPages(plan)+ if (!pages.length) {+ toast({ title: 'Nothing to apply', description: 'Enable at least one page with elements.' })+ return+ }+ useEditorStore.getState().appendPages(pages)+ toast({+ title: `${pages.length} page${pages.length > 1 ? 's' : ''} added`,+ description: 'Fully editable elements. Ctrl+Z removes them all.',+ })+ onClose()+ }++ const enabledPages = plan?.pages.filter((p) => p.enabled).length ?? 0+ const enabledElements =+ plan?.pages.filter((p) => p.enabled).reduce((n, p) => n + p.elements.filter((e) => e.enabled).length, 0) ?? 0++ return (+ <div>+ <AppHeader icon={Bot} title="AI design plan" onClose={onClose} />+ <p className="text-[11.5px] text-white/50 leading-snug mb-3">+ Describe the design — the agent drafts a full multi-page plan you REVIEW and EDIT before a single+ element lands on the canvas.+ </p>++ <textarea+ value={prompt}+ onChange={(e) => setPrompt(e.target.value)}+ placeholder="e.g. A 3-page menu for an Italian trattoria — rustic, warm, handwritten accents"+ className="w-full h-24 rounded-xl bg-white/[0.05] border border-white/10 text-white text-[12.5px] p-3 resize-none focus:outline-none focus:border-[#02C0CC]"+ maxLength={2000}+ aria-label="Design brief"+ />++ <div className="flex items-center gap-2 mt-2.5">+ <span className="text-[11px] text-white/50">Pages</span>+ <div className="flex gap-1">+ {[1, 2, 3, 4, 6].map((n) => (+ <button+ key={n}+ onClick={() => setPageCount(n)}+ className={cn(+ 'w-8 h-8 rounded-lg text-[11px] font-bold transition-colors',+ pageCount === n ? 'bg-[#7630D7] text-white' : 'bg-white/[0.05] text-white/60 hover:bg-white/10',+ )}+ aria-pressed={pageCount === n}+ >+ {n}+ </button>+ ))}+ </div>+ <button+ className="btn-cv h-9 px-4 ml-auto text-[12px] flex items-center gap-1.5 disabled:opacity-60"+ onClick={() => void generate()}+ disabled={busy || !prompt.trim()}+ >+ {busy ? <Loader2 size={13} className="animate-spin" /> : <Sparkles size={13} />}+ {busy ? 'Planning…' : 'Plan my design'}+ </button>+ </div>++ {!plan && !busy && (+ <div className="mt-3 space-y-1.5">+ {IDEAS.map((idea) => (+ <button+ key={idea}+ onClick={() => setPrompt(idea)}+ className="block w-full text-left text-[11px] text-white/45 hover:text-white/80 px-2.5 py-2 rounded-lg hover:bg-white/[0.04] transition-colors"+ >+ “{idea}”+ </button>+ ))}+ </div>+ )}++ {error && (+ <p className="mt-3 rounded-xl border border-red-400/30 bg-red-400/10 px-3 py-2 text-[11.5px] text-red-200">+ {error}+ </p>+ )}++ {plan && (+ <div className="mt-4 border-t border-white/10 pt-3">+ <div className="flex items-start gap-2 mb-3">+ <div className="min-w-0">+ <p className="text-[12.5px] font-bold text-white truncate">{plan.name}</p>+ {plan.summary && <p className="text-[11px] text-white/50 leading-snug mt-0.5">{plan.summary}</p>}+ </div>+ <div className="ml-auto flex gap-2 shrink-0">+ <button+ className="text-[11px] text-white/55 hover:text-white px-2.5 h-8 rounded-lg hover:bg-white/10"+ onClick={() => setPlan(null)}+ >+ Redraft+ </button>+ <button className="btn-cv h-8 px-3.5 text-[11.5px] flex items-center gap-1.5" onClick={apply}>+ <Check size={12} /> Apply {enabledPages > 0 ? `(${enabledPages}p · ${enabledElements}el)` : ''}+ </button>+ </div>+ </div>++ <div className="space-y-3">+ {plan.pages.map((pg) => (+ <PageCard+ key={pg.id}+ page={pg}+ planWidth={plan.width}+ planHeight={plan.height}+ onTogglePage={togglePage}+ onToggleElement={toggleElement}+ onEditText={editText}+ />+ ))}+ </div>++ <p className="mt-3 text-[10.5px] text-white/35 leading-snug">+ Uncheck anything you don't want; edit any copy inline. Apply adds the checked pages to this design+ as native editable elements — one Ctrl+Z removes them all.+ </p>+ </div>+ )}+ </div>+ )+}++/** One reviewable page: mini preview + element checklist with inline copy editing. */+function PageCard({+ page,+ planWidth,+ planHeight,+ onTogglePage,+ onToggleElement,+ onEditText,+}: {+ page: PlanPageSpec+ planWidth: number+ planHeight: number+ onTogglePage: (id: string) => void+ onToggleElement: (pageId: string, elId: string) => void+ onEditText: (pageId: string, elId: string, text: string) => void+}) {+ return (+ <div+ className={cn(+ 'rounded-xl border p-2.5 transition-colors',+ page.enabled ? 'border-white/12 bg-white/[0.04]' : 'border-white/8 bg-white/[0.015] opacity-60',+ )}+ >+ <div className="flex items-center gap-2">+ <button+ onClick={() => onTogglePage(page.id)}+ className={cn(+ 'w-5 h-5 rounded-md border flex items-center justify-center shrink-0 transition-colors',+ page.enabled ? 'bg-[#02C0CC] border-[#02C0CC] text-black' : 'border-white/25 text-transparent',+ )}+ aria-label={page.enabled ? `Disable page ${page.title}` : `Enable page ${page.title}`}+ aria-pressed={page.enabled}+ >+ <Check size={12} strokeWidth={3.5} />+ </button>+ <span className="text-[12px] font-semibold text-white/90 truncate">{page.title}</span>+ <span className="ml-auto text-[10px] text-white/40">{page.elements.filter((e) => e.enabled).length}/{page.elements.length}</span>+ </div>++ <div className="flex gap-2.5 mt-2">+ {/* scaled geometry preview — the honest wireframe of the plan */}+ <div+ className="relative shrink-0 rounded-lg overflow-hidden border border-white/10"+ style={{+ width: 96,+ height: Math.max(48, Math.round((96 * planHeight) / Math.max(1, planWidth))),+ background:+ page.background.type === 'gradient'+ ? `linear-gradient(${page.background.angle}deg, ${page.background.from}, ${page.background.to})`+ : page.background.color,+ }}+ aria-hidden+ >+ {page.elements.map((el) => (+ <div+ key={el.id}+ className="absolute rounded-[2px]"+ style={{+ left: `${(el.x / planWidth) * 100}%`,+ top: `${(el.y / planHeight) * 100}%`,+ width: `${(el.width / planWidth) * 100}%`,+ height: `${((el.height ?? Math.round(planHeight * 0.06)) / planHeight) * 100}%`,+ background: el.type === 'text' ? 'rgba(255,255,255,0.75)' : (el.fill ?? '#02C0CC'),+ opacity: el.enabled ? 0.9 : 0.25,+ minHeight: 3,+ }}+ />+ ))}+ </div>++ <div className="flex-1 min-w-0 space-y-1 max-h-44 overflow-y-auto pr-0.5">+ {page.elements.map((el) => (+ <div key={el.id} className="flex items-center gap-1.5">+ <button+ onClick={() => onToggleElement(page.id, el.id)}+ className={cn(+ 'w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-colors',+ el.enabled ? 'bg-[#02C0CC] border-[#02C0CC] text-black' : 'border-white/25 text-transparent',+ )}+ aria-label={+ el.enabled+ ? `Disable ${el.type}: ${(el.text ?? '').slice(0, 30) || el.type}`+ : `Enable ${el.type}: ${(el.text ?? '').slice(0, 30) || el.type}`+ }+ aria-pressed={el.enabled}+ >+ <Check size={9} strokeWidth={4} />+ </button>+ {el.type === 'text' ? (+ <input+ value={el.text ?? ''}+ onChange={(e) => onEditText(page.id, el.id, e.target.value)}+ className="flex-1 min-w-0 h-7 rounded-md bg-white/[0.05] border border-white/10 text-[11px] text-white px-2 focus:outline-none focus:border-[#02C0CC]"+ aria-label="Element text"+ maxLength={400}+ />+ ) : (+ <span className="flex items-center gap-1.5 text-[11px] text-white/55 truncate">+ {el.enabled ? <Eye size={11} className="shrink-0" /> : <EyeOff size={11} className="shrink-0" />}+ {el.type} — {el.width}×{el.height ?? 'auto'}+ <span className="w-2.5 h-2.5 rounded-sm border border-white/20 shrink-0" style={{ background: el.fill ?? '#02C0CC' }} />+ </span>+ )}+ </div>+ ))}+ </div>+ </div>+ </div>+ )+}diff --git a/src/components/editor/apps/AIThemeApp.tsx b/src/components/editor/apps/AIThemeApp.tsxnew file mode 100644index 0000000..5610cc7--- /dev/null+++ b/src/components/editor/apps/AIThemeApp.tsx@@ -0,0 +1,163 @@+'use client'++import { useState } from 'react'+import { SwatchBook, Loader2, Check, Sparkles } from 'lucide-react'+import { useEditorStore } from '@/store/editor-store'+import { applyTheme, type Theme } from '@/lib/theme'+import { AppHeader, type AppPanelProps } from './registry'+import { toast } from '@/hooks/use-toast'++const MOODS = [+ 'warm bakery, cozy, earthy',+ 'nordic calm, cool editorial',+ 'bold tech launch, electric',+ 'soft pastel kids brand',+ 'luxury dark, gold accents',+]++const ROLE_LABELS: Record<string, string> = {+ background: 'Background',+ surface: 'Surface',+ ink: 'Text',+ inkSoft: 'Text (soft)',+ accent: 'Accent',+ accentSoft: 'Accent 2',+}++/**+ * v0.19 (Wave 4) — AI theme generation. The model proposes a+ * role-tagged palette + font pairing (contrast-checked server-side);+ * this panel previews it and applies it design-wide with applyTheme()+ * — backgrounds, text ink, shape accents, all as one undoable step.+ */+export function AIThemeApp({ onClose }: AppPanelProps) {+ const [mood, setMood] = useState('')+ const [busy, setBusy] = useState(false)+ const [error, setError] = useState<string | null>(null)+ const [theme, setTheme] = useState<Theme | null>(null)++ const generate = async () => {+ if (!mood.trim() || busy) return+ setBusy(true)+ setError(null)+ setTheme(null)+ try {+ const res = await fetch('/api/ai/theme', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ prompt: mood.trim() }),+ })+ const data = (await res.json()) as { theme?: Theme; error?: string }+ if (!res.ok || !data.theme) throw new Error(data.error ?? 'Generation failed')+ setTheme(data.theme)+ } catch (e) {+ setError(e instanceof Error ? e.message : 'Generation failed')+ } finally {+ setBusy(false)+ }+ }++ const apply = () => {+ if (!theme) return+ const s = useEditorStore.getState()+ // applyTheme is pure — build the next pages, then one history push+ const next = applyTheme(s.pages, theme)+ s.pushHistory()+ useEditorStore.setState({ pages: next, dirty: true })+ toast({+ title: 'Theme applied',+ description: `${theme.name} — recolored backgrounds, text and shapes. Ctrl+Z to revert.`,+ })+ onClose()+ }++ return (+ <div>+ <AppHeader icon={SwatchBook} title="AI theme" onClose={onClose} />+ <p className="text-[11.5px] text-white/50 leading-snug mb-3">+ Describe a mood — get a palette + font pairing, preview it, then recolor the whole design in one+ undoable step. Text contrast is guarded automatically.+ </p>++ <div className="flex gap-1.5">+ <input+ value={mood}+ onChange={(e) => setMood(e.target.value)}+ onKeyDown={(e) => e.key === 'Enter' && !busy && void generate()}+ placeholder="e.g. moody jazz club, deep blues"+ className="flex-1 h-9 rounded-xl bg-white/[0.05] border border-white/10 text-white text-[12px] px-3 focus:outline-none focus:border-[#02C0CC]"+ aria-label="Theme mood"+ maxLength={400}+ />+ <button+ className="btn-cv h-9 px-3.5 text-[12px] flex items-center gap-1.5 shrink-0 disabled:opacity-60"+ onClick={() => void generate()}+ disabled={busy || !mood.trim()}+ >+ {busy ? <Loader2 size={13} className="animate-spin" /> : <Sparkles size={13} />}+ Generate+ </button>+ </div>++ {!theme && !busy && (+ <div className="mt-3 space-y-1.5">+ {MOODS.map((m) => (+ <button+ key={m}+ onClick={() => setMood(m)}+ className="block w-full text-left text-[11px] text-white/45 hover:text-white/80 px-2.5 py-2 rounded-lg hover:bg-white/[0.04] transition-colors"+ >+ “{m}”+ </button>+ ))}+ </div>+ )}++ {error && (+ <p className="mt-3 rounded-xl border border-red-400/30 bg-red-400/10 px-3 py-2 text-[11.5px] text-red-200">+ {error}+ </p>+ )}++ {theme && (+ <div className="mt-4 border-t border-white/10 pt-3">+ <div className="flex items-start gap-2">+ <div className="min-w-0">+ <p className="text-[12.5px] font-bold text-white truncate">{theme.name}</p>+ {theme.mood && <p className="text-[11px] text-white/50 leading-snug mt-0.5">{theme.mood}</p>}+ <p className="text-[11px] text-white/45 mt-1">+ {theme.fonts.heading} + {theme.fonts.body}+ </p>+ </div>+ <div className="ml-auto flex gap-2 shrink-0">+ <button+ className="text-[11px] text-white/55 hover:text-white px-2.5 h-8 rounded-lg hover:bg-white/10"+ onClick={() => setTheme(null)}+ >+ Redraft+ </button>+ <button className="btn-cv h-8 px-3.5 text-[11.5px] flex items-center gap-1.5" onClick={apply}>+ <Check size={12} /> Apply theme+ </button>+ </div>+ </div>++ <div className="mt-3 rounded-xl border border-white/10 overflow-hidden">+ {theme.palette.map((c) => (+ <div key={c.role} className="flex items-center gap-2.5 px-2.5 h-10 border-b border-white/[0.06] last:border-b-0" style={{ background: `${c.hex}14` }}>+ <span className="w-6 h-6 rounded-md border border-white/15 shrink-0" style={{ background: c.hex }} />+ <span className="text-[11.5px] text-white/80">{ROLE_LABELS[c.role] ?? c.role}</span>+ <span className="ml-auto font-mono text-[10.5px] text-white/45">{c.hex}</span>+ </div>+ ))}+ </div>++ <p className="mt-3 text-[10.5px] text-white/35 leading-snug">+ Applying recolors page backgrounds, text, shapes and lines across every page. Images, charts and+ stickers stay untouched; one Ctrl+Z reverts everything.+ </p>+ </div>+ )}+ </div>+ )+}diff --git a/src/components/editor/apps/registry.tsx b/src/components/editor/apps/registry.tsxindex e324b80..6b39252 100644--- a/src/components/editor/apps/registry.tsx+++ b/src/components/editor/apps/registry.tsx@@ -1,6 +1,6 @@'use client'-import { BarChart3, QrCode, Smile, Shapes, Palette, Type, Wand2, ImageIcon, Bot } from 'lucide-react'+import { BarChart3, QrCode, Smile, Shapes, Palette, Type, Wand2, ImageIcon, Bot, LayoutTemplate, SwatchBook, Video } from 'lucide-react'import type { LucideIcon } from 'lucide-react'/** ── Canvix app registry ─────────────────────────────────────@@ -34,12 +34,17 @@ import { StickersApp } from './StickersApp'import { MagicWriteApp } from './MagicWriteApp'import { AIImageApp } from './AIImageApp'import { AssistantApp } from './AssistantApp'+import { AIPlanApp } from './AIPlanApp'+import { AIThemeApp } from './AIThemeApp'export const CANVIX_APPS: CanvixApp[] = [// AI apps first (canva 2026: “Canva AI” is the flagship surface){ id: 'assistant', name: 'Canvix AI', desc: 'Chat copilot — copy, palettes, images, translate', icon: Bot, color: '#7630D7', content: AssistantApp },{ id: 'magic-write', name: 'Magic Write', desc: 'AI copy — headlines, taglines & captions', icon: Wand2, color: '#9B6BFF', content: MagicWriteApp },{ id: 'ai-image', name: 'AI image generator', desc: 'Turn a prompt into a design-ready image', icon: ImageIcon, color: '#02C0CC', content: AIImageApp },+ // v0.19 (Wave 4 — AI Power-Up):+ { id: 'ai-plan', name: 'AI design plan', desc: 'Describe it — review the plan — apply editable pages', icon: LayoutTemplate, color: '#7630D7', content: AIPlanApp },+ { id: 'ai-theme', name: 'AI theme', desc: 'Palette + fonts for the whole design, applied safely', icon: SwatchBook, color: '#FF5C8A', content: AIThemeApp },{ id: 'charts', name: 'Charts', desc: 'Bar, line & donut charts as editable shapes', icon: BarChart3, color: '#7630D7', content: ChartsApp },{ id: 'qr', name: 'QR generator', desc: 'Turn any link or text into a QR code', icon: QrCode, color: '#3B82F6', content: QRApp },{ id: 'icons', name: 'Icons', desc: '562 offline icons + the Iconify universe online', icon: Shapes, color: '#02C0CC', content: IconsApp },diff --git a/src/components/editor/panels/AIVideoCard.tsx b/src/components/editor/panels/AIVideoCard.tsxnew file mode 100644index 0000000..4a62324--- /dev/null+++ b/src/components/editor/panels/AIVideoCard.tsx@@ -0,0 +1,249 @@+'use client'++import { useEffect, useRef, useState } from 'react'+import { Clapperboard, Loader2, Plus, Sparkles, TriangleAlert } from 'lucide-react'+import { addGeneratedVideo } from '../add-element'+import { toast } from '@/hooks/use-toast'++/** Poll cadence and patience for async video generation. */+const POLL_MS = 3000+const MAX_POLLS = 100 // ~5 minutes++interface VideoStatus {+ id: string+ status: 'queued' | 'in_progress' | 'completed' | 'failed'+ progress: number+ videos: { index: number; url: string }[]+ error?: string+}++const delay = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))++/** The poll loop — module scope (no self-referential hooks). `token`+ * invalidates the loop when a newer generation starts; setters are+ * safe no-ops after unmount on React 18+. */+async function pollVideo(+ id: string,+ token: { current: number },+ myToken: number,+ onStatus: (s: VideoStatus) => void,+ onDone: (s: VideoStatus) => void,+ onFail: (msg: string) => void,+) {+ for (let i = 0; i < MAX_POLLS; i++) {+ await delay(POLL_MS)+ if (token.current !== myToken) return+ try {+ const res = await fetch(`/api/ai/video?id=${encodeURIComponent(id)}`)+ const data = (await res.json()) as VideoStatus & { error?: string }+ if (token.current !== myToken) return+ if (!res.ok) throw new Error(data.error ?? 'Polling failed')+ if (data.status === 'completed') {+ onDone(data)+ return+ }+ if (data.status === 'failed') {+ onFail(data.error ?? 'Generation failed')+ return+ }+ onStatus(data)+ } catch (e) {+ // transient network blips keep the loop going (3 strikes out)+ if (i >= 2 || token.current !== myToken) {+ onFail(e instanceof Error ? e.message : 'Polling failed')+ return+ }+ }+ }+ onFail('Timed out waiting for the video.')+}++/**+ * v0.19 (Wave 4) — AI video generation card for the Videos panel.+ *+ * Prompt → POST /api/ai/video (video slot, admin-switchable) → poll the+ * async generation → preview → insert via addGeneratedVideo (chunked+ * media store, real probe, first-frame poster). Renders nothing when+ * the server reports no videoGeneration capability.+ */+export function AIVideoCard() {+ const [available, setAvailable] = useState<boolean | null>(null)+ const [prompt, setPrompt] = useState('')+ const [status, setStatus] = useState<VideoStatus | null>(null)+ const [failed, setFailed] = useState<string | null>(null)+ const [adding, setAdding] = useState(false)+ /** bump to invalidate any running poll loop (new generate / reset / unmount) */+ const runToken = useRef(0)++ useEffect(() => {+ let cancelled = false+ fetch('/api/ai/capabilities')+ .then((r) => r.json())+ .then((d: { capabilities?: Record<string, boolean> }) => {+ if (!cancelled) setAvailable(Boolean(d.capabilities?.videoGeneration))+ })+ .catch(() => {+ if (!cancelled) setAvailable(false)+ })+ return () => {+ cancelled = true+ runToken.current += 1+ }+ }, [])++ const generate = async () => {+ if (!prompt.trim() || status?.status === 'completed') return+ setFailed(null)+ setStatus({ id: 'starting', status: 'queued', progress: 2, videos: [] })+ try {+ const res = await fetch('/api/ai/video', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ prompt: prompt.trim(), size: '1024x576' }),+ })+ const data = (await res.json()) as { id?: string; error?: string; detail?: string }+ if (!res.ok || !data.id) throw new Error(data.detail ?? data.error ?? 'Generation failed')+ const myToken = ++runToken.current+ void pollVideo(+ data.id,+ runToken,+ myToken,+ setStatus,+ (s) => {+ setStatus(s)+ setFailed(null)+ },+ (msg) => {+ setFailed(msg)+ setStatus(null)+ },+ )+ } catch (e) {+ setFailed(e instanceof Error ? e.message : 'Generation failed')+ setStatus(null)+ }+ }++ const add = async (url: string) => {+ if (adding) return+ setAdding(true)+ try {+ await addGeneratedVideo(url)+ toast({ title: 'AI video added', description: 'Downloaded into your media library.' })+ // reset for the next generation+ setPrompt('')+ runToken.current += 1+ setStatus(null)+ setFailed(null)+ } catch (e) {+ toast({+ title: 'Could not add the video',+ description: e instanceof Error ? e.message : 'Try again.',+ variant: 'destructive',+ })+ } finally {+ setAdding(false)+ }+ }++ if (available === false) return null++ const done = status?.status === 'completed'+ const running = Boolean(status) && !done && !failed++ return (+ <div className="rounded-xl border border-[#7630D7]/40 bg-[#7630D7]/[0.08] p-3 mb-3" data-testid="ai-video-card">+ <div className="flex items-center gap-1.5 mb-2">+ <Clapperboard size={12} className="text-[#B79AFF]" />+ <span className="text-[10.5px] font-bold text-white/60 uppercase tracking-wide">Generate with AI</span>+ </div>++ <div className="flex gap-1.5">+ <input+ value={prompt}+ onChange={(e) => setPrompt(e.target.value)}+ onKeyDown={(e) => e.key === 'Enter' && !running && !done && void generate()}+ placeholder="Describe a video — e.g. slow pan over misty mountains at dawn"+ className="flex-1 h-9 rounded-lg bg-white/[0.06] border border-white/10 text-white text-[12px] px-2.5 focus:outline-none focus:border-[#7630D7]"+ aria-label="Video prompt"+ maxLength={1000}+ disabled={running}+ data-testid="ai-video-prompt"+ />+ <button+ className="h-9 px-3 shrink-0 rounded-lg bg-[#7630D7] hover:bg-[#8a49e8] text-white text-[11.5px] font-bold flex items-center gap-1.5 disabled:opacity-60 transition-colors"+ onClick={() => void generate()}+ disabled={running || !prompt.trim()}+ aria-label="Generate video"+ data-testid="ai-video-generate"+ >+ {running ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}+ {running ? `${status?.progress ?? 0}%` : 'Generate'}+ </button>+ </div>++ {running && (+ <div className="mt-2.5">+ <div className="h-1.5 rounded-full bg-white/10 overflow-hidden">+ <div+ className="h-full rounded-full bg-gradient-to-r from-[#7630D7] to-[#02C0CC] transition-all duration-500"+ style={{ width: `${Math.max(4, status?.progress ?? 0)}%` }}+ />+ </div>+ <p className="text-[10.5px] text-white/45 mt-1.5">+ Videos take a few minutes — keep this panel open. You can keep editing meanwhile.+ </p>+ </div>+ )}++ {failed && (+ <div className="mt-2.5 flex items-start gap-1.5 rounded-lg border border-red-400/30 bg-red-400/10 px-2.5 py-2 text-[11px] text-red-200">+ <TriangleAlert size={12} className="mt-0.5 shrink-0" />+ <span className="leading-snug">{failed}</span>+ </div>+ )}++ {done && status?.videos[0] && (+ <div className="mt-2.5">+ <video+ src={status.videos[0].url}+ controls+ muted+ loop+ playsInline+ className="w-full aspect-video rounded-lg bg-black border border-white/10"+ data-testid="ai-video-preview"+ />+ <div className="flex gap-1.5 mt-2">+ <button+ className="flex-1 h-9 rounded-lg bg-[#7630D7] hover:bg-[#8a49e8] text-white text-[11.5px] font-bold flex items-center justify-center gap-1.5 disabled:opacity-60 transition-colors"+ onClick={() => void add(status.videos[0]!.url)}+ disabled={adding}+ aria-label="Add video to design"+ >+ {adding ? <Loader2 size={12} className="animate-spin" /> : <Plus size={12} />}+ {adding ? 'Adding…' : 'Add to design'}+ </button>+ <button+ className="h-9 px-3 rounded-lg border border-white/15 text-white/70 hover:text-white text-[11.5px] font-semibold transition-colors"+ onClick={() => {+ runToken.current += 1+ setStatus(null)+ setFailed(null)+ }}+ >+ Discard+ </button>+ </div>+ </div>+ )}++ {!running && !done && !failed && (+ <p className="text-[10.5px] text-white/35 mt-2 leading-snug">+ Text-to-video via the server's video provider slot (admin-configurable). Generated videos land in+ your media library like uploads.+ </p>+ )}+ </div>+ )+}diff --git a/src/components/editor/panels/VideosPanel.tsx b/src/components/editor/panels/VideosPanel.tsxindex 4d64563..41fe6e7 100644--- a/src/components/editor/panels/VideosPanel.tsx+++ b/src/components/editor/panels/VideosPanel.tsx@@ -18,6 +18,7 @@ import { Plus, Loader2, Clapperboard, VideoOff } from 'lucide-react'import { PanelShell } from './panel-shell'import { addStockVideo } from '../add-element'import { useStockVideo } from '@/hooks/use-stock-video'+import { AIVideoCard } from './AIVideoCard'import { cn } from '@/lib/utils'import { toast } from '@/hooks/use-toast'@@ -254,13 +255,18 @@ export function VideosPanel() {)}</div>) : (- <div className="py-12 text-center">- <Clapperboard size={26} className="mx-auto text-white/25 mb-3" />- <p className="text-[13px] text-white/50 font-medium">Search free stock videos</p>- <p className="text-[11.5px] text-white/35 mt-1 leading-relaxed max-w-[240px] mx-auto">- Type at least two letters. Every video carries its creator and license —- shown when you add it and saved with the design.- </p>+ <div>+ {/* v0.19 (Wave 4): AI text-to-video — hides itself when the+ server has no videoGeneration capability */}+ <AIVideoCard />+ <div className="py-10 text-center">+ <Clapperboard size={26} className="mx-auto text-white/25 mb-3" />+ <p className="text-[13px] text-white/50 font-medium">Search free stock videos</p>+ <p className="text-[11.5px] text-white/35 mt-1 leading-relaxed max-w-[240px] mx-auto">+ Type at least two letters. Every video carries its creator and license —+ shown when you add it and saved with the design.+ </p>+ </div></div>)}diff --git a/src/lib/admin/config.test.ts b/src/lib/admin/config.test.tsindex 2512bd8..2ee4d23 100644--- a/src/lib/admin/config.test.ts+++ b/src/lib/admin/config.test.ts@@ -320,7 +320,8 @@ describe('importLegacyProvider (v0.16.2 A2)', () => {expect(out.value.list).toHaveLength(1)expect(out.value.list[0].baseUrl).toBe('https://legacy.example/v1')expect(out.value.list[0].apiKey).toBe('sk-leg')- expect(Object.keys(out.value.slots)).toHaveLength(4) // all slots wired (imageSearch retired, v0.16.4 A4)+ expect(Object.keys(out.value.slots)).toHaveLength(5) // all slots wired (imageSearch retired v0.16.4 A4; video added v0.19 Wave 4)+ expect(Object.keys(out.value.slots)).toContain('video')}const calls = upsert.mock.calls.map((c) => c[0].where.key)expect(calls).toContain('ai.providers')diff --git a/src/lib/admin/config.ts b/src/lib/admin/config.tsindex 5e3d851..2eea893 100644--- a/src/lib/admin/config.ts+++ b/src/lib/admin/config.ts@@ -53,6 +53,12 @@ export const AI_FEATURES = ['translation','assistant','photoSearch',+ // v0.19 (Wave 4 — AI Power-Up):+ 'agenticPlanning', // describe → AI multi-page plan → editable review gate+ 'notesGeneration', // speaker notes from page content+ 'themeGeneration', // AI palette/font theme, applied design-wide+ 'altText', // accessibility alt text for images (vision slot)+ 'videoGeneration', // text-to-video via the video slot] as constexport type AiFeature = (typeof AI_FEATURES)[number]@@ -65,7 +71,7 @@ export type AiFeature = (typeof AI_FEATURES)[number]* validateSlots only reads known slot keys, so the stale entry is* dropped on the next read and disappears on the next save.*/-export const AI_SLOTS = ['text', 'vision', 'image', 'imageEdit'] as const+export const AI_SLOTS = ['text', 'vision', 'image', 'imageEdit', 'video'] as constexport type AiSlot = (typeof AI_SLOTS)[number]export interface StoredProvider {@@ -109,6 +115,13 @@ export const DEFAULT_FEATURES: StoredFeatures = {translation: true,assistant: true,photoSearch: true,+ // v0.19 (Wave 4) — default ON; stored tables that predate the flags+ // merge over these defaults (getFeatures spreads DEFAULT first).+ agenticPlanning: true,+ notesGeneration: true,+ themeGeneration: true,+ altText: true,+ videoGeneration: true,}export const DEFAULT_SETTINGS: StoredSettings = {diff --git a/src/lib/ai/provider.ts b/src/lib/ai/provider.tsindex dfe4b8f..02fad81 100644--- a/src/lib/ai/provider.ts+++ b/src/lib/ai/provider.ts@@ -181,6 +181,12 @@ const FEATURE_SLOTS: Record<string, AiSlot> = {image: 'image','image-edit': 'imageEdit','magic-layers': 'vision',+ // v0.19 (Wave 4 — AI Power-Up):+ plan: 'text', // agentic planning with review gate+ notes: 'text', // speaker-notes generation+ theme: 'text', // AI theme generation+ 'alt-text': 'vision', // image alt text (vision slot — image understanding)+ video: 'video', // text-to-video generation}/** Async probe — does THIS slot have a provider behind it? */@@ -449,6 +455,12 @@ const FEATURE_FLAGS: Record<string, AiFeature> = {'magic-layers': 'vision',translate: 'translation',assistant: 'assistant',+ // v0.19 (Wave 4 — AI Power-Up):+ plan: 'agenticPlanning',+ notes: 'notesGeneration',+ theme: 'themeGeneration',+ 'alt-text': 'altText',+ video: 'videoGeneration',}export const FEATURE_DISABLED = {diff --git a/src/lib/design-plan.test.ts b/src/lib/design-plan.test.tsnew file mode 100644index 0000000..8ae1d9d--- /dev/null+++ b/src/lib/design-plan.test.ts@@ -0,0 +1,177 @@+// Wave 4 — lib/design-plan.ts unit tests.+// The review-gate transforms: hostile-input coercion + plan→pages.+import { describe, expect, it } from 'vitest'+import { MAX_PLAN_ELEMENTS_PER_PAGE, MAX_PLAN_PAGES, normalizePlan, planToPages, planSystemPrompt } from './design-plan'++const W = 1080+const H = 1080++describe('normalizePlan', () => {+ it('normalizes a well-formed plan', () => {+ const plan = normalizePlan(+ {+ name: 'Coffee launch',+ summary: 'Warm 3-page launch kit',+ pages: [+ {+ title: 'Cover',+ background: { type: 'gradient', from: '#7630D7', to: '#02C0CC', angle: 90 },+ elements: [+ { type: 'text', text: 'Grand Opening', x: 100, y: 200, width: 800, fontSize: 96, fontFamily: 'Poppins', bold: true, fill: '#FFFFFF', align: 'center' },+ { type: 'rect', x: 0, y: 0, width: 1080, height: 120, fill: '#111111', cornerRadius: 0 },+ ],+ },+ ],+ },+ W,+ H,+ )+ expect(plan.name).toBe('Coffee launch')+ expect(plan.summary).toBe('Warm 3-page launch kit')+ expect(plan.pages).toHaveLength(1)+ expect(plan.pages[0].elements).toHaveLength(2)+ expect(plan.pages[0].background).toEqual({ type: 'gradient', from: '#7630D7', to: '#02C0CC', angle: 90 })+ expect(plan.pages[0].elements[0].text).toBe('Grand Opening')+ expect(plan.pages[0].elements[0].enabled).toBe(true)+ })++ it('survives hostile input: nulls, wrong types, junk colors, unknown fonts', () => {+ const plan = normalizePlan(+ {+ name: 42,+ pages: [+ {+ elements: [+ null,+ { type: 'bomb', x: 'x' },+ { type: 'text', text: 7, fontSize: 99999, fontFamily: 'Comic Sans XSS', fill: 'javascript:', align: 'diagonal' },+ { type: 'ellipse', x: -500, y: 1e9, width: 3, height: 2, fill: 'red' },+ ],+ background: { type: 'lava', color: 'nope' },+ },+ ],+ },+ W,+ H,+ )+ // `bomb` is dropped; `null` coerces to a default text element (the+ // MCP normalizer's `e ?? {}` semantics) — 3 of 4 survive+ const els = plan.pages[0].elements+ expect(els).toHaveLength(3)+ expect(els.find((e) => (e.type as string) === 'bomb')).toBeUndefined()+ const text = els.find((e) => e.type === 'text' && e.fill !== '#00C4CC')!+ expect(text.fontSize).toBeLessThanOrEqual(280)+ expect(text.fontFamily).toBe('Poppins')+ expect(text.fill).toMatch(/^#[0-9a-fA-F]{6}$/)+ expect(text.align).toBe('center')+ const ellipse = els.find((e) => e.type === 'ellipse')!+ expect(ellipse.x).toBeGreaterThanOrEqual(0)+ expect(ellipse.x).toBeLessThanOrEqual(W)+ expect(ellipse.y).toBeLessThanOrEqual(H)+ expect(ellipse.fill).toBe('#00C4CC')+ expect(plan.pages[0].background).toEqual({ type: 'solid', color: '#FFFFFF' })+ expect(plan.name).toBe('AI plan')+ })++ it('caps pages and per-page elements', () => {+ const raw = {+ pages: Array.from({ length: 20 }, (_, pi) => ({+ title: `p${pi}`,+ elements: Array.from({ length: 60 }, (_, ei) => ({+ type: 'rect',+ x: ei * 10,+ y: pi * 10,+ width: 20,+ height: 20,+ })),+ })),+ }+ const plan = normalizePlan(raw, W, H)+ expect(plan.pages.length).toBeLessThanOrEqual(MAX_PLAN_PAGES)+ for (const p of plan.pages) {+ expect(p.elements.length).toBeLessThanOrEqual(MAX_PLAN_ELEMENTS_PER_PAGE)+ }+ })++ it('drops element-less pages and defaults to an empty plan on garbage', () => {+ const empty = normalizePlan({ pages: [{ elements: [] }, { elements: [{ type: 'nope' }, { type: 'bomb' }] }] }, W, H)+ expect(empty.pages).toHaveLength(0)+ const garbage = normalizePlan('just a string', W, H)+ expect(garbage.pages).toHaveLength(0)+ expect(garbage.width).toBe(W)+ expect(garbage.height).toBe(H)+ expect(() => normalizePlan(null, W, H)).not.toThrow()+ })++ it('gives every page and element a unique id', () => {+ const plan = normalizePlan(+ {+ pages: [1, 2].map((pi) => ({+ elements: [1, 2, 3].map((ei) => ({ type: 'rect', x: ei * 30, y: pi * 30, width: 20, height: 20 })),+ })),+ },+ W,+ H,+ )+ const ids = [+ ...plan.pages.map((p) => p.id),+ ...plan.pages.flatMap((p) => p.elements.map((e) => e.id)),+ ]+ expect(new Set(ids).size).toBe(ids.length)+ })+})++describe('planToPages', () => {+ const plan = normalizePlan(+ {+ pages: [+ {+ title: 'Cover',+ elements: [+ { type: 'text', text: 'Hello', x: 100, y: 100, width: 400, fontSize: 64 },+ { type: 'rect', x: 0, y: 0, width: 200, height: 100 },+ { type: 'table', x: 100, y: 500, width: 500, rows: 3, header: ['a', 'b'] },+ ],+ },+ { title: 'Skipped', elements: [{ type: 'ellipse', x: 1, y: 1, width: 5, height: 5 }] },+ ],+ },+ W,+ H,+ )++ it('builds real editor elements with fresh ids', () => {+ const pages = planToPages(plan)+ expect(pages).toHaveLength(2)+ const [p1] = pages+ expect(p1.elements).toHaveLength(3)+ expect(p1.elements[0].type).toBe('text')+ expect(p1.elements[0].id).not.toBe(plan.pages[0].elements[0].id)+ expect(p1.elements[1].type).toBe('rect')+ expect(p1.elements[2].type).toBe('table')+ expect(pages.every((p) => p.background.type === 'solid')).toBe(true)+ })++ it('honors the review gate: disabled pages and elements are skipped', () => {+ const edited = {+ ...plan,+ pages: [+ { ...plan.pages[0], enabled: false },+ { ...plan.pages[1], elements: plan.pages[1].elements.map((e, i) => ({ ...e, enabled: i === 0 })) },+ ],+ }+ const pages = planToPages(edited)+ expect(pages).toHaveLength(1)+ expect(pages[0].elements).toHaveLength(1)+ })+})++describe('planSystemPrompt', () => {+ it('pins the page geometry, page count and JSON contract', () => {+ const s = planSystemPrompt(800, 600, 3)+ expect(s).toContain('800x600px')+ expect(s).toContain('3 page(s)')+ expect(s).toContain('"pages"')+ expect(s).toContain('no markdown fences')+ })+})diff --git a/src/lib/design-plan.ts b/src/lib/design-plan.tsnew file mode 100644index 0000000..34ef5cb--- /dev/null+++ b/src/lib/design-plan.ts@@ -0,0 +1,287 @@+// ─────────────────────────────────────────────────────────────+// Canvix agentic design planning (Wave 4 — AI Power-Up).+//+// The in-app planner asks the text-slot provider for a STRUCTURED,+// multi-page design plan, then hands it to the user as an EDITABLE+// REVIEW GATE (toggle pages/elements, rewrite copy, recolor) before a+// single element lands on the canvas. This module owns the plan data+// model and the two pure transforms the feature rides on:+//+// normalizePlan() — hostile-input-safe coercion of whatever JSON the+// model actually replied with (clamped geometry,+// validated fonts/colors, bounded page/element+// counts) into a DesignPlan+// planToPages() — the approved plan → real PageData with real+// editor elements (create* factories, fresh ids)+//+// The MCP generate_design tool keeps its own single-page normalizer+// (src/lib/mcp/tools.ts) — the shapes are deliberately similar so the+// prompt engineering carries over, but this module adds the review+// semantics (enabled flags, editable text) the gate needs.+// ─────────────────────────────────────────────────────────────++import { FONTS } from '@/lib/editor-utils'+import {+ createTextElement,+ createShapeElement,+ createTableElement,+ type AnyElement,+ type PageData,+} from '@/lib/types'++/** Review-gate caps — plans are drafts, not canvases. */+export const MAX_PLAN_PAGES = 6+export const MAX_PLAN_ELEMENTS_PER_PAGE = 30++export type PlanElementType = 'text' | 'rect' | 'ellipse' | 'triangle' | 'table'++export interface PlanElementSpec {+ /** Stable within the plan (`p2e7`) — the gate's React keys + toggles. */+ id: string+ type: PlanElementType+ /** Review gate: unchecked elements are skipped on apply. */+ enabled: boolean+ // text+ text?: string+ fontSize?: number+ fontFamily?: string+ bold?: boolean+ fill?: string+ align?: 'left' | 'center' | 'right'+ curve?: number+ // geometry (px on the plan's page)+ x: number+ y: number+ width: number+ height?: number+ cornerRadius?: number+ // table+ header?: string[]+ cells?: { text: string }[]+ rows?: number+ cols?: number+}++export type PlanBackground =+ | { type: 'solid'; color: string }+ | { type: 'gradient'; from: string; to: string; angle: number }++export interface PlanPageSpec {+ id: string+ /** Short label for the review gate card ("Cover", "Pricing"). */+ title: string+ enabled: boolean+ background: PlanBackground+ elements: PlanElementSpec[]+}++export interface DesignPlan {+ name: string+ /** One-sentence intent — shown above the gate so the user can sanity-+ * check what the agent set out to do before applying. */+ summary: string+ width: number+ height: number+ pages: PlanPageSpec[]+}++// ── coercion primitives (same semantics as the MCP normalizer) ──++function asString(v: unknown, fallback = ''): string {+ return typeof v === 'string' ? v : fallback+}+function asNumber(v: unknown, fallback: number): number {+ const n = typeof v === 'number' ? v : typeof v === 'string' ? Number(v) : NaN+ return Number.isFinite(n) ? n : fallback+}+function asBool(v: unknown, fallback: boolean): boolean {+ return typeof v === 'boolean' ? v : fallback+}+function clamp(n: number, min: number, max: number): number {+ return Math.min(max, Math.max(min, n))+}+function asHex(v: unknown, fallback: string): string {+ return typeof v === 'string' && /^#[0-9a-fA-F]{6}$/.test(v.trim()) ? v.trim() : fallback+}+function asEnum<T extends readonly string[]>(v: unknown, options: T, fallback: T[number]): T[number] {+ return typeof v === 'string' && (options as readonly string[]).includes(v) ? (v as T[number]) : fallback+}+function knownFont(v: unknown): string | undefined {+ const name = asString(v)+ return FONTS.some((f) => (typeof f === 'string' ? f : f.family) === name) ? name : undefined+}++/** Fresh page/element ids — short, unique within a normalize pass. */+let idCounter = 0+function freshId(prefix: string): string {+ idCounter = (idCounter + 1) % 1_000_000+ return `${prefix}${Date.now().toString(36)}${idCounter.toString(36)}`+}++// ── normalizePlan ────────────────────────────────────────────++/** Coerce one raw element into a spec (or null when unusable). */+function normalizeElement(raw: unknown, width: number, height: number, index: number): PlanElementSpec | null {+ const el = (raw ?? {}) as Record<string, unknown>+ const type = asString(el.type, 'text')+ if (!['text', 'rect', 'ellipse', 'triangle', 'table'].includes(type)) return null++ const spec: PlanElementSpec = {+ id: `e${index}_${freshId('')}`,+ type: type as PlanElementType,+ enabled: true,+ x: clamp(asNumber(el.x, 60), 0, width),+ y: clamp(asNumber(el.y, 60), 0, height),+ width: clamp(asNumber(el.width, Math.round(width * 0.7)), 24, width * 1.3),+ }++ if (type === 'text') {+ spec.text = asString(el.text, 'Text').slice(0, 400)+ spec.fontSize = clamp(asNumber(el.fontSize, 40), 10, 280)+ spec.fontFamily = knownFont(el.fontFamily) ?? 'Poppins'+ spec.bold = asBool(el.bold, false)+ spec.fill = asHex(el.fill, '#1F2226')+ spec.align = asEnum(el.align, ['left', 'center', 'right'] as const, 'center')+ const curve = asNumber(el.curve, 0)+ if (Math.abs(curve) > 2) spec.curve = clamp(curve, -180, 180)+ } else if (type === 'table') {+ const header = Array.isArray(el.header)+ ? el.header.map((h) => asString(h).slice(0, 40)).slice(0, 6)+ : undefined+ const cells = Array.isArray(el.cells)+ ? (el.cells as Record<string, unknown>[]).slice(0, 120).map((c) => ({ text: asString(c.text).slice(0, 60) }))+ : undefined+ spec.header = header && header.length ? header : undefined+ spec.cells = cells && cells.length ? cells : undefined+ spec.rows = clamp(Math.round(asNumber(el.rows, 3)), 1, 12)+ spec.cols = clamp(header?.length ?? 3, 1, 6)+ spec.height = clamp(asNumber(el.height, spec.rows * 44), 44, height)+ } else {+ spec.height = clamp(asNumber(el.height, 200), 8, height * 1.5)+ spec.fill = asHex(el.fill, '#00C4CC')+ if (type === 'rect') spec.cornerRadius = clamp(asNumber(el.cornerRadius, 0), 0, 400)+ }+ return spec+}++/**+ * Coerce raw model output into a DesignPlan. Never throws — worst case+ * (no usable pages) it returns an empty single-page plan the gate can+ * still render (and the user can still apply as a blank starting point).+ */+export function normalizePlan(raw: unknown, width: number, height: number): DesignPlan {+ const spec = (raw ?? {}) as Record<string, unknown>+ const pagesRaw = Array.isArray(spec.pages) ? spec.pages.slice(0, MAX_PLAN_PAGES) : []+ const pages: PlanPageSpec[] = []++ pagesRaw.forEach((p, pi) => {+ const page = (p ?? {}) as Record<string, unknown>+ const elementsRaw = Array.isArray(page.elements) ? page.elements.slice(0, MAX_PLAN_ELEMENTS_PER_PAGE) : []+ const elements = elementsRaw+ .map((e, i) => normalizeElement(e, width, height, i))+ .filter((e): e is PlanElementSpec => e !== null)+ if (!elements.length) return // skip element-less pages entirely++ const bg = (page.background ?? {}) as Record<string, unknown>+ const background: PlanBackground =+ asString(bg.type, 'solid') === 'gradient'+ ? {+ type: 'gradient',+ from: asHex(bg.from, '#7630D7'),+ to: asHex(bg.to, '#02C0CC'),+ angle: clamp(asNumber(bg.angle, 135), 0, 360),+ }+ : { type: 'solid', color: asHex(bg.color, '#FFFFFF') }++ pages.push({+ id: `p${pi}_${freshId('')}`,+ title: asString(page.title, `Page ${pi + 1}`).slice(0, 40),+ enabled: true,+ background,+ elements,+ })+ })++ return {+ name: asString(spec.name, 'AI plan').slice(0, 80) || 'AI plan',+ summary: asString(spec.summary, '').slice(0, 300),+ width: clamp(Math.round(asNumber(spec.width, width)), 200, 8000) || width,+ height: clamp(Math.round(asNumber(spec.height, height)), 200, 8000) || height,+ pages,+ }+}++// ── planToPages ──────────────────────────────────────────────++/** The approved plan → real pages with real editor elements. */+export function planToPages(plan: DesignPlan): PageData[] {+ return plan.pages+ .filter((p) => p.enabled)+ .map((p) => {+ const elements: AnyElement[] = []+ for (const spec of p.elements) {+ if (!spec.enabled) continue+ if (spec.type === 'text') {+ elements.push(+ createTextElement({+ text: spec.text ?? 'Text',+ x: spec.x,+ y: spec.y,+ width: spec.width,+ fontSize: spec.fontSize ?? 40,+ fontFamily: spec.fontFamily ?? 'Poppins',+ bold: spec.bold ?? false,+ fill: spec.fill ?? '#1F2226',+ align: spec.align ?? 'center',+ ...(spec.curve !== undefined ? { curve: spec.curve } : {}),+ }),+ )+ } else if (spec.type === 'table') {+ elements.push(+ createTableElement({+ x: spec.x,+ y: spec.y,+ width: spec.width,+ rows: spec.rows ?? 3,+ cols: spec.cols ?? 3,+ rowHeight: 44,+ ...(spec.header ? { header: spec.header } : {}),+ ...(spec.cells ? { cells: spec.cells } : {}),+ }),+ )+ } else {+ elements.push(+ createShapeElement(spec.type, {+ x: spec.x,+ y: spec.y,+ width: spec.width,+ height: spec.height ?? 200,+ fill: spec.fill ?? '#00C4CC',+ ...(spec.type === 'rect' && spec.cornerRadius ? { cornerRadius: spec.cornerRadius } : {}),+ }),+ )+ }+ }+ return { id: freshId('page_'), background: p.background, elements }+ })+}++// ── the planner system prompt (shared contract with the model) ──++/** Build the system prompt for /api/ai/plan. Multi-page, review-gate+ * aware. Kept next to the normalizer so the contract cannot drift. */+export function planSystemPrompt(width: number, height: number, pageCount: number): string {+ const fontList = FONTS.slice(0, 24)+ .map((f) => (typeof f === 'string' ? f : f.family))+ .join(', ')+ return [+ 'You are a senior brand designer planning a Canvix design. Reply with ONLY a JSON object (no markdown fences) of shape:',+ '{"name":string,"summary":string,"pages":[{"title":string,"background":{"type":"solid","color":"#RRGGBB"}|{"type":"gradient","from":"#RRGGBB","to":"#RRGGBB","angle":number},"elements":[ ... ]}]}',+ `Element types (all coordinates in px on a ${width}x${height}px page):`,+ `{"type":"text","text":string,"x":n,"y":n,"width":n,"fontSize":n,"fontFamily":one of [${fontList}],"bold":bool,"fill":"#RRGGBB","align":"left|center|right"}`,+ '{"type":"rect","x":n,"y":n,"width":n,"height":n,"fill":"#RRGGBB","cornerRadius":n}',+ '{"type":"ellipse","x":n,"y":n,"width":n,"height":n,"fill":"#RRGGBB"}',+ '{"type":"triangle","x":n,"y":n,"width":n,"height":n,"fill":"#RRGGBB"}',+ `Plan for ${pageCount} page(s). Rules: max ${MAX_PLAN_ELEMENTS_PER_PAGE} elements per page, 60px margins, hex colors only, text must fit its width (estimate ~0.6*fontSize px per char), clear hierarchy and contrast, professionally designed. The user reviews and edits this plan before anything is applied, so use concise, final-quality copy.`,+ ].join('\n')+}diff --git a/src/lib/inpaint.test.ts b/src/lib/inpaint.test.tsnew file mode 100644index 0000000..7d78980--- /dev/null+++ b/src/lib/inpaint.test.ts@@ -0,0 +1,143 @@+// Wave 4 — lib/inpaint.ts unit tests.+// Pyramid-diffusion reconstruction: constants, gradients, isolation.+import { describe, expect, it } from 'vitest'+import { inpaint, type Mask } from './inpaint'+import type { Raster } from './upscale'++function raster(w: number, h: number, fill: (x: number, y: number) => [number, number, number, number]): Raster {+ const data = new Uint8ClampedArray(w * h * 4)+ for (let y = 0; y < h; y++) {+ for (let x = 0; x < w; x++) {+ const [r, g, b, a] = fill(x, y)+ const i = (y * w + x) * 4+ data[i] = r+ data[i + 1] = g+ data[i + 2] = b+ data[i + 3] = a+ }+ }+ return { data, width: w, height: h }+}++/** rectangular brush mask */+function rectMask(w: number, h: number, x0: number, y0: number, x1: number, y1: number): Mask {+ const data = new Uint8ClampedArray(w * h * 4)+ for (let y = y0; y <= y1; y++) {+ for (let x = x0; x <= x1; x++) {+ data[(y * w + x) * 4 + 3] = 255+ }+ }+ return { data, width: w, height: h }+}++describe('inpaint', () => {+ it('reconstructs a hole in a solid color exactly', () => {+ const src = raster(16, 16, () => [90, 140, 60, 255])+ // paint garbage in the hole region first — it must be ignored+ for (let y = 5; y <= 10; y++)+ for (let x = 5; x <= 10; x++) {+ const i = (y * 16 + x) * 4+ src.data[i] = 255+ src.data[i + 1] = 0+ src.data[i + 2] = 0+ }+ const mask = rectMask(16, 16, 5, 5, 10, 10)+ const out = inpaint(src, mask)+ for (let y = 5; y <= 10; y++) {+ for (let x = 5; x <= 10; x++) {+ const i = (y * 16 + x) * 4+ expect(out.data[i]).toBeLessThanOrEqual(92)+ expect(out.data[i]).toBeGreaterThanOrEqual(88)+ expect(out.data[i + 1]).toBeLessThanOrEqual(142)+ expect(out.data[i + 1]).toBeGreaterThanOrEqual(138)+ expect(out.data[i + 2]).toBeLessThanOrEqual(62)+ expect(out.data[i + 2]).toBeGreaterThanOrEqual(58)+ expect(out.data[i + 3]).toBe(255)+ }+ }+ })++ it('interpolates a linear gradient across the hole', () => {+ // horizontal ramp 0..255 over 32px+ const src = raster(32, 8, (x) => [x * 8, x * 8, x * 8, 255])+ const mask = rectMask(32, 8, 12, 2, 19, 5)+ const out = inpaint(src, mask)+ for (let y = 2; y <= 5; y++) {+ for (let x = 13; x <= 18; x++) {+ const i = (y * 32 + x) * 4+ const want = x * 8+ // diffusion converges toward the harmonic solution ≈ linear ramp+ expect(Math.abs(out.data[i] - want)).toBeLessThanOrEqual(12)+ }+ }+ })++ it('leaves pixels outside the mask byte-identical', () => {+ const src = raster(20, 20, (x, y) => [(x * 13 + y * 7) % 256, x, y, 255])+ const before = new Uint8ClampedArray(src.data)+ const mask = rectMask(20, 20, 8, 8, 12, 12)+ const out = inpaint(src, mask)+ for (let i = 0; i < 20 * 20; i++) {+ const inHole = i % 20 >= 8 && i % 20 <= 12 && Math.floor(i / 20) >= 8 && Math.floor(i / 20) <= 12+ if (inHole) continue+ expect(out.data[i * 4]).toBe(before[i * 4])+ expect(out.data[i * 4 + 3]).toBe(before[i * 4 + 3])+ }+ })++ it('returns a copy unchanged when the mask is empty', () => {+ const src = raster(8, 8, () => [1, 2, 3, 255])+ const mask = rectMask(8, 8, 0, 0, -1, -1) // empty (x1 < x0)+ const out = inpaint(src, mask)+ expect(Array.from(out.data)).toEqual(Array.from(src.data))+ expect(out.data).not.toBe(src.data)+ })++ it('keeps a fully transparent region transparent', () => {+ // left half opaque gradient, right half fully transparent; hole+ // entirely inside the transparent half+ const src = raster(24, 10, (x) =>+ x < 12 ? [10, 20, 30, 255] : [0, 0, 0, 0],+ )+ const mask = rectMask(24, 10, 15, 3, 20, 6)+ const out = inpaint(src, mask)+ for (let y = 3; y <= 6; y++) {+ for (let x = 15; x <= 20; x++) {+ const i = (y * 24 + x) * 4+ expect(out.data[i + 3]).toBeLessThanOrEqual(2)+ }+ }+ })++ it('fills a hole that covers an entire coarse block (mean seed path)', () => {+ // tiny image, hole covers more than half — the pyramid must seed+ // from the coarsest level mean rather than bilinear neighbours+ const src = raster(8, 8, (x, y) => [x < 4 ? 200 : 40, 100, 100, 255])+ const mask = rectMask(8, 8, 0, 0, 6, 6)+ const out = inpaint(src, mask)+ // every hole pixel is opaque and within the value range+ for (let y = 0; y <= 6; y++) {+ for (let x = 0; x <= 6; x++) {+ const i = (y * 8 + x) * 4+ expect(out.data[i + 3]).toBe(255)+ expect(out.data[i]).toBeLessThanOrEqual(210)+ expect(out.data[i]).toBeGreaterThanOrEqual(30)+ }+ }+ })++ it('rejects a mask whose geometry does not match', () => {+ const src = raster(4, 4, () => [0, 0, 0, 255])+ const mask = rectMask(5, 4, 0, 0, 1, 1)+ expect(() => inpaint(src, mask)).toThrow()+ expect(() => inpaint({ data: new Uint8ClampedArray(0), width: 0, height: 0 }, rectMask(0, 0, 0, 0, -1, -1))).toThrow()+ })++ it('is deterministic', () => {+ const src = raster(18, 18, (x, y) => [(x * 5) % 256, (y * 9) % 256, 77, 255])+ const mask = rectMask(18, 18, 4, 4, 12, 12)+ const a = inpaint(src, mask)+ const b = inpaint(src, mask)+ expect(Array.from(a.data)).toEqual(Array.from(b.data))+ })+})diff --git a/src/lib/inpaint.ts b/src/lib/inpaint.tsnew file mode 100644index 0000000..695e8e0--- /dev/null+++ b/src/lib/inpaint.ts@@ -0,0 +1,334 @@+// ─────────────────────────────────────────────────────────────+// Canvix local magic-eraser engine (Wave 4 — AI Power-Up).+//+// Brush-paint a region → the region is reconstructed from its+// surroundings. Clean-room "LaMa-style" pyramid diffusion: a pull-push+// fill seeds the hole from progressively coarser scales, then+// boundary-constrained Jacobi diffusion polishes the full-resolution+// result. Pure TypeScript, deterministic, zero model downloads, works+// offline on ANY image — the property VibesAI-class edit providers+// lack (they refuse images they did not generate themselves).+//+// Pipeline:+// 1. pull-push pyramid: downsample KNOWN pixels only, level by+// level, until every 2×2 block would be unknown (or a floor+// size) — then fill back up, seeding each level's holes from the+// coarser reconstruction.+// 2. diffusion refine: N Jacobi sweeps where each hole pixel+// becomes the mean of its 8 neighbours (known pixels are fixed+// boundary conditions — the reconstruction matches the image at+// the brush edge by construction).+// 3. one feather pass over the hole boundary so the seam is not a+// hard line.+// ─────────────────────────────────────────────────────────────++import type { Raster } from './upscale'++/** Brush mask: same geometry as the raster, alpha 0 = keep, ≥128 = erase. */+export interface Mask {+ data: Uint8ClampedArray+ width: number+ height: number+}++/** Jacobi sweeps at full resolution after the pyramid seed. */+export const REFINE_SWEEPS = 28++/** Pyramid floor — stop descending when a level gets this small. */+const PYRAMID_FLOOR = 4++/** true when the mask paints this pixel */+function isHole(mask: Mask, x: number, y: number): boolean {+ return mask.data[(y * mask.width + x) * 4 + 3] >= 128+}++/** Downsample one level counting only known pixels; blocks with none+ * stay unknown. Returns the coarse raster plus a coarse hole flag map. */+function downsampleKnown(+ img: Float32Array,+ known: Uint8Array,+ w: number,+ h: number,+): { img: Float32Array; known: Uint8Array; w: number; h: number } {+ const cw = Math.max(1, w >> 1)+ const ch = Math.max(1, h >> 1)+ const cimg = new Float32Array(cw * ch * 4)+ const cknown = new Uint8Array(cw * ch)+ for (let cy = 0; cy < ch; cy++) {+ for (let cx = 0; cx < cw; cx++) {+ let r = 0+ let g = 0+ let b = 0+ let a = 0+ let n = 0+ for (let dy = 0; dy < 2; dy++) {+ for (let dx = 0; dx < 2; dx++) {+ const x = cx * 2 + dx+ const y = cy * 2 + dy+ if (x >= w || y >= h) continue+ const i = y * w + x+ if (!known[i]) continue+ n+++ r += img[i * 4]+ g += img[i * 4 + 1]+ b += img[i * 4 + 2]+ a += img[i * 4 + 3]+ }+ }+ const ci = cy * cw + cx+ if (n > 0) {+ cimg[ci * 4] = r / n+ cimg[ci * 4 + 1] = g / n+ cimg[ci * 4 + 2] = b / n+ cimg[ci * 4 + 3] = a / n+ cknown[ci] = 1+ }+ }+ }+ return { img: cimg, known: cknown, w: cw, h: ch }+}++/** Bilinear sample of a coarse level at fine coordinates (pixel centres). */+function bilinear(+ img: Float32Array,+ w: number,+ h: number,+ fx: number,+ fy: number,+ out: Float32Array,+): void {+ const x = Math.min(w - 1, Math.max(0, fx))+ const y = Math.min(h - 1, Math.max(0, fy))+ const x0 = Math.floor(x)+ const y0 = Math.floor(y)+ const x1 = Math.min(w - 1, x0 + 1)+ const y1 = Math.min(h - 1, y0 + 1)+ const tx = x - x0+ const ty = y - y0+ for (let c = 0; c < 4; c++) {+ const top = img[(y0 * w + x0) * 4 + c] * (1 - tx) + img[(y0 * w + x1) * 4 + c] * tx+ const bot = img[(y1 * w + x0) * 4 + c] * (1 - tx) + img[(y1 * w + x1) * 4 + c] * tx+ out[c] = top * (1 - ty) + bot * ty+ }+}++/** One pyramid build (down) + fill (up), mutating `img` in place. */+function pullPush(img: Float32Array, known: Uint8Array, w: number, h: number): void {+ // ── build the pyramid of known-only averages ──+ const levels: { img: Float32Array; known: Uint8Array; w: number; h: number }[] = [+ { img, known, w, h },+ ]+ while (+ levels[levels.length - 1].w > PYRAMID_FLOOR &&+ levels[levels.length - 1].h > PYRAMID_FLOOR+ ) {+ const top = levels[levels.length - 1]+ levels.push(downsampleKnown(top.img, top.known, top.w, top.h))+ }+ // coarsest level still has unknown pixels (the hole covered entire+ // blocks): seed them with the mean of everything known at that level+ const coarse = levels[levels.length - 1]+ let mr = 0+ let mg = 0+ let mb = 0+ let ma = 0+ let mn = 0+ for (let i = 0; i < coarse.w * coarse.h; i++) {+ if (!coarse.known[i]) continue+ mn+++ mr += coarse.img[i * 4]+ mg += coarse.img[i * 4 + 1]+ mb += coarse.img[i * 4 + 2]+ ma += coarse.img[i * 4 + 3]+ }+ const mean = mn > 0 ? [mr / mn, mg / mn, mb / mn, ma / mn] : [0, 0, 0, 0]+ for (let i = 0; i < coarse.w * coarse.h; i++) {+ if (coarse.known[i]) continue+ coarse.img[i * 4] = mean[0]+ coarse.img[i * 4 + 1] = mean[1]+ coarse.img[i * 4 + 2] = mean[2]+ coarse.img[i * 4 + 3] = mean[3]+ }+ // ── fill back up: each level's holes take bilinear samples of the+ // coarser reconstruction ──+ for (let l = levels.length - 2; l >= 0; l--) {+ const fine = levels[l]+ const c = levels[l + 1]+ const sample = new Float32Array(4)+ for (let y = 0; y < fine.h; y++) {+ for (let x = 0; x < fine.w; x++) {+ const i = y * fine.w + x+ if (fine.known[i]) continue+ bilinear(c.img, c.w, c.h, (x - 0.5) / 2, (y - 0.5) / 2, sample)+ fine.img[i * 4] = sample[0]+ fine.img[i * 4 + 1] = sample[1]+ fine.img[i * 4 + 2] = sample[2]+ fine.img[i * 4 + 3] = sample[3]+ }+ }+ }+}++/** Boundary-constrained Jacobi diffusion over the hole pixels only. */+function diffuse(img: Float32Array, known: Uint8Array, w: number, h: number, sweeps: number): void {+ // hole pixel index list + a full index map (pixel → hole slot) so the+ // hot loop below can find a hole neighbour's PREVIOUS-sweep value+ const holes: number[] = []+ for (let i = 0; i < w * h; i++) if (!known[i]) holes.push(i)+ if (!holes.length) return+ const holeMap = new Int32Array(w * h).fill(-1)+ for (let k = 0; k < holes.length; k++) holeMap[holes[k]] = k+ const next = new Float32Array(4)+ for (let s = 0; s < sweeps; s++) {+ // Jacobi: read from the current state, write via a per-sweep copy of+ // the hole values (cheap: only holes are copied)+ const prev = new Float32Array(holes.length * 4)+ for (let k = 0; k < holes.length; k++) {+ const i = holes[k]+ prev[k * 4] = img[i * 4]+ prev[k * 4 + 1] = img[i * 4 + 1]+ prev[k * 4 + 2] = img[i * 4 + 2]+ prev[k * 4 + 3] = img[i * 4 + 3]+ }+ for (let k = 0; k < holes.length; k++) {+ const i = holes[k]+ const x = i % w+ const y = (i / w) | 0+ let r = 0+ let g = 0+ let b = 0+ let a = 0+ let n = 0+ for (let dy = -1; dy <= 1; dy++) {+ for (let dx = -1; dx <= 1; dx++) {+ if (dx === 0 && dy === 0) continue+ const nx = x + dx+ const ny = y + dy+ if (nx < 0 || ny < 0 || nx >= w || ny >= h) continue+ const ni = ny * w + nx+ const nk = holeMap[ni]+ if (nk >= 0) {+ // neighbour is also a hole → its PREVIOUS sweep value+ r += prev[nk * 4]+ g += prev[nk * 4 + 1]+ b += prev[nk * 4 + 2]+ a += prev[nk * 4 + 3]+ } else {+ r += img[ni * 4]+ g += img[ni * 4 + 1]+ b += img[ni * 4 + 2]+ a += img[ni * 4 + 3]+ }+ n+++ }+ }+ if (n > 0) {+ next[0] = r / n+ next[1] = g / n+ next[2] = b / n+ next[3] = a / n+ img[i * 4] = next[0]+ img[i * 4 + 1] = next[1]+ img[i * 4 + 2] = next[2]+ img[i * 4 + 3] = next[3]+ }+ }+ }+}++/** Feather the hole boundary: blend each boundary hole pixel 50/50 with+ * the average of its known neighbours — softens the seam. */+function feather(img: Float32Array, known: Uint8Array, w: number, h: number): void {+ const edges: number[] = []+ for (let y = 0; y < h; y++) {+ for (let x = 0; x < w; x++) {+ const i = y * w + x+ if (known[i]) continue+ let hasKnown = false+ for (let dy = -1; dy <= 1 && !hasKnown; dy++) {+ for (let dx = -1; dx <= 1; dx++) {+ const nx = x + dx+ const ny = y + dy+ if (nx < 0 || ny < 0 || nx >= w || ny >= h) continue+ if (known[ny * w + nx]) {+ hasKnown = true+ break+ }+ }+ }+ if (hasKnown) edges.push(i)+ }+ }+ for (const i of edges) {+ const x = i % w+ const y = (i / w) | 0+ let r = 0+ let g = 0+ let b = 0+ let a = 0+ let n = 0+ for (let dy = -1; dy <= 1; dy++) {+ for (let dx = -1; dx <= 1; dx++) {+ const nx = x + dx+ const ny = y + dy+ if (nx < 0 || ny < 0 || nx >= w || ny >= h) continue+ const ni = ny * w + nx+ if (!known[ni]) continue+ r += img[ni * 4]+ g += img[ni * 4 + 1]+ b += img[ni * 4 + 2]+ a += img[ni * 4 + 3]+ n+++ }+ }+ if (n > 0) {+ img[i * 4] = img[i * 4] * 0.5 + (r / n) * 0.5+ img[i * 4 + 1] = img[i * 4 + 1] * 0.5 + (g / n) * 0.5+ img[i * 4 + 2] = img[i * 4 + 2] * 0.5 + (b / n) * 0.5+ img[i * 4 + 3] = img[i * 4 + 3] * 0.5 + (a / n) * 0.5+ }+ }+}++/**+ * Reconstruct the masked region of `src` from its surroundings.+ * Returns a NEW raster — the input is never mutated. Pixels outside+ * the mask are byte-identical to the input.+ */+export function inpaint(src: Raster, mask: Mask, sweeps = REFINE_SWEEPS): Raster {+ if (src.width !== mask.width || src.height !== mask.height) {+ throw new Error('inpaint: mask geometry must match the raster')+ }+ if (src.width < 1 || src.height < 1) throw new Error('inpaint: empty raster')+ const out = new Uint8ClampedArray(src.data) // untouched pixels stay identical+ // working buffers in float+ const img = new Float32Array(src.width * src.height * 4)+ const known = new Uint8Array(src.width * src.height)+ let holes = 0+ for (let y = 0; y < src.height; y++) {+ for (let x = 0; x < src.width; x++) {+ const i = y * src.width + x+ img[i * 4] = src.data[i * 4]+ img[i * 4 + 1] = src.data[i * 4 + 1]+ img[i * 4 + 2] = src.data[i * 4 + 2]+ img[i * 4 + 3] = src.data[i * 4 + 3]+ if (isHole(mask, x, y)) {+ holes+++ } else {+ known[i] = 1+ }+ }+ }+ if (holes === 0) return { data: out, width: src.width, height: src.height }+ pullPush(img, known, src.width, src.height)+ diffuse(img, known, src.width, src.height, sweeps)+ feather(img, known, src.width, src.height)+ for (let i = 0; i < src.width * src.height; i++) {+ if (known[i]) continue+ out[i * 4] = img[i * 4]+ out[i * 4 + 1] = img[i * 4 + 1]+ out[i * 4 + 2] = img[i * 4 + 2]+ out[i * 4 + 3] = img[i * 4 + 3]+ }+ return { data: out, width: src.width, height: src.height }+}diff --git a/src/lib/mcp/tools.ts b/src/lib/mcp/tools.tsindex 1d61ae8..c19518c 100644--- a/src/lib/mcp/tools.ts+++ b/src/lib/mcp/tools.ts@@ -26,6 +26,8 @@ import {} from '@/lib/types'import { isChartKind, sanitizeChartLabels, sanitizeChartSeries, clampChartHole, CHART_PALETTE } from '@/lib/chart-geometry'import { normalizeSpans } from '@/lib/rich-text'+import { normalizeGrounding, visionGroundPrompt } from './vision-ground'+import { DEFAULT_VISION_MODEL } from '@/lib/ai/provider'export const SERVER_VERSION = '0.6.1'@@ -1161,6 +1163,86 @@ export function buildTools(deps: ToolDeps): ToolDef[] {// ── misc ───────────────────────────────────────────────────+ // v0.19 (Wave 4): canvas-screenshot vision grounding — the agent's+ // eyes. Feed it a page screenshot (the editor's PNG export, or any+ // capture) and get a grounded element inventory with pixel+ // coordinates it can act on via update_element/add_*.+ const visionGround: ToolDef = {+ name: 'vision_ground',+ description:+ 'Analyze a canvas/page SCREENSHOT with the vision provider and return a grounded element inventory: what is visible, ' ++ 'where (normalized 0..1 bounds AND page-pixel boxes), in what colors. Use it to reason about layout before acting with ' ++ 'update_element / add_text / add_shape, or to answer "what does this design look like". Requires the vision slot provider. ' ++ 'Input: image (dataURL) + optional width/height of the page the screenshot shows (for pixel mapping) + optional question (focus).',+ inputSchema: {+ type: 'object',+ properties: {+ image: { type: 'string', description: 'PNG/JPEG dataURL of the canvas screenshot' },+ width: { type: 'number', minimum: 1, maximum: 8000, description: 'Page width in px (default 1080)' },+ height: { type: 'number', minimum: 1, maximum: 8000, description: 'Page height in px (default 1080)' },+ question: { type: 'string', description: 'Optional focus, e.g. "where is the headline?"' },+ },+ required: ['image'],+ },+ handler: async (args) => {+ const image = asString(args.image)+ if (!image || !/^data:image\/(png|jpeg|webp);base64,/.test(image)) {+ return fail('Provide a PNG/JPEG/WebP dataURL screenshot in `image`.')+ }+ if (image.length > 8 * 1024 * 1024) return fail('Screenshot too large — max ~6 MB.')+ const ctx = await getClientForSlot('vision')+ if (!ctx) {+ return fail(+ 'vision_ground requires a vision-slot provider configured on the server (add one in /admin). ' ++ 'Without vision you can still read design structure with get_design_content.',+ )+ }+ const rl = rateLimit('mcp-vision', deps.req, 6, 60)+ if (!rl.ok) return fail('Rate limit reached — try again in a minute.')+ const width = clamp(asInt(args.width, 1080), 1, 8000)+ const height = clamp(asInt(args.height, 1080), 1, 8000)+ const question = asString(args.question).slice(0, 200)++ try {+ const completion = await ctx.zai.chat.completions.createVision({+ model: ctx.model ?? DEFAULT_VISION_MODEL,+ messages: [+ { role: 'system', content: visionGroundPrompt(question) },+ {+ role: 'user',+ content: [+ { type: 'text', text: 'Ground this canvas screenshot now.' },+ { type: 'image_url', image_url: { url: image } },+ ],+ },+ ],+ thinking: { type: 'disabled' },+ })+ const raw = completion.choices[0]?.message?.content ?? ''+ const start = raw.indexOf('{')+ const end = raw.lastIndexOf('}')+ let parsed: unknown = null+ if (start !== -1 && end > start) {+ try {+ parsed = JSON.parse(raw.slice(start, end + 1))+ } catch {+ parsed = null+ }+ }+ if (!parsed) {+ await recordUsage('vision_ground', ctx.label ?? ctx.source ?? 'vision', false).catch(() => undefined)+ return fail('The vision reply was not parseable JSON. Try a cleaner screenshot.')+ }+ const grounding = normalizeGrounding(parsed, width, height)+ await recordUsage('vision_ground', ctx.label ?? ctx.source ?? 'vision', true).catch(() => undefined)+ return ok({ ...grounding, note: 'bounds are fractions; px boxes assume the width/height you supplied.' })+ } catch (err) {+ await recordUsage('vision_ground', ctx.label ?? ctx.source ?? 'vision', false).catch(() => undefined)+ return fail(`Vision grounding failed: ${err instanceof Error ? err.message.slice(0, 200) : 'unknown error'}`)+ }+ },+ }+const listFonts: ToolDef = {name: 'list_fonts',description: 'List the font families available in the editor (use with add_text / update_element).',@@ -1193,6 +1275,7 @@ export function buildTools(deps: ToolDeps): ToolDef[] {getDesignContent,createDesign,generateDesign,+ visionGround,addText,addShape,addImage,diff --git a/src/lib/mcp/vision-ground.test.ts b/src/lib/mcp/vision-ground.test.tsnew file mode 100644index 0000000..54c74a3--- /dev/null+++ b/src/lib/mcp/vision-ground.test.ts@@ -0,0 +1,65 @@+// Wave 4 — MCP vision grounding normalizer tests.+import { describe, expect, it } from 'vitest'+import { MAX_GROUNDED, normalizeGrounding, visionGroundPrompt } from './vision-ground'++describe('normalizeGrounding', () => {+ it('normalizes bounds, maps to pixels, keeps colors', () => {+ const g = normalizeGrounding(+ {+ description: 'Hero layout with headline on top.',+ elements: [+ { label: 'Summer Sale', role: 'headline', bounds: { x: 0.1, y: 0.05, w: 0.8, h: 0.15 }, color: '#ff00aa' },+ { label: 'product photo', role: 'image', bounds: { x: '0.2', y: '0.3', width: 0.6, height: 0.5 } },+ ],+ },+ 1000,+ 500,+ )+ expect(g.description).toBe('Hero layout with headline on top.')+ expect(g.elements).toHaveLength(2)+ const [headline, photo] = g.elements+ expect(headline.px).toEqual({ x: 100, y: 25, w: 800, h: 75 })+ expect(headline.color).toBe('#FF00AA')+ // string numbers + width/height aliases work too+ expect(photo.px).toEqual({ x: 200, y: 150, w: 600, h: 250 })+ expect(photo.color).toBeUndefined()+ })++ it('clamps fractions, drops junk, caps the inventory', () => {+ const g = normalizeGrounding(+ {+ elements: [+ { label: 'x', bounds: { x: -5, y: 2, w: 0.5, h: 0.5 } }, // clamped+ { label: '', bounds: { x: 0, y: 0, w: 0.5, h: 0.5 } }, // no label → dropped+ { label: 'y', bounds: { x: 'junk' } }, // no box → dropped+ { label: 'z' }, // no bounds → dropped+ ...Array.from({ length: 60 }, (_, i) => ({+ label: `e${i}`,+ bounds: { x: 0, y: 0, w: 0.1, h: 0.1 },+ })),+ ],+ },+ 100,+ 100,+ )+ expect(g.elements.length).toBeLessThanOrEqual(MAX_GROUNDED)+ expect(g.elements[0].box.x).toBe(0)+ expect(g.elements.every((e) => e.label)).toBe(true)+ })++ it('is total on garbage input', () => {+ expect(() => normalizeGrounding(null, 10, 10)).not.toThrow()+ expect(normalizeGrounding('junk', 10, 10).elements).toEqual([])+ expect(normalizeGrounding({}, 10, 10).description).toBe('')+ })+})++describe('visionGroundPrompt', () => {+ it('pins the JSON contract and carries the focus question', () => {+ const s = visionGroundPrompt('where is the logo?')+ expect(s).toContain('{"description"')+ expect(s).toContain('FRACTIONS')+ expect(s).toContain('where is the logo?')+ expect(visionGroundPrompt()).not.toContain('Pay special attention')+ })+})diff --git a/src/lib/mcp/vision-ground.ts b/src/lib/mcp/vision-ground.tsnew file mode 100644index 0000000..0f8a119--- /dev/null+++ b/src/lib/mcp/vision-ground.ts@@ -0,0 +1,109 @@+// ─────────────────────────────────────────────────────────────+// Canvix MCP canvas-screenshot vision grounding (Wave 4 — AI Power-Up).+//+// The `vision_ground` tool takes a screenshot of a canvas page, sends+// it through the vision slot, and returns a GROUNDED element inventory:+// what is on the page, where (normalized 0..1 boxes, mapped to page+// pixels), in what colors — so an agent can reason about layout and+// then act with the existing edit tools (update_element, add_text…).+//+// This module holds the pure parts (system prompt + normalizer) so+// they are unit-testable without a provider.+// ─────────────────────────────────────────────────────────────++/** One grounded element the vision model reported. */+export interface GroundedElement {+ label: string+ role: string+ /** normalized 0..1 box (fractions of the screenshot) */+ box: { x: number; y: number; w: number; h: number }+ /** mapped to page pixels (same numbers when no page size given) */+ px: { x: number; y: number; w: number; h: number }+ color?: string+}++export interface Grounding {+ description: string+ elements: GroundedElement[]+}++/** Cap the inventory — screenshots can be busy, prompts can't. */+export const MAX_GROUNDED = 40++function clamp01(n: number): number {+ return Math.min(1, Math.max(0, n))+}++function asRecord(v: unknown): Record<string, unknown> {+ return (v ?? {}) as Record<string, unknown>+}++function asBox(v: unknown): { x: number; y: number; w: number; h: number } | null {+ const b = asRecord(v)+ const n = (x: unknown): number => {+ const num = typeof x === 'number' ? x : typeof x === 'string' ? Number(x) : NaN+ return Number.isFinite(num) ? num : NaN+ }+ const x = n(b.x)+ const y = n(b.y)+ const w = n(b.w ?? b.width)+ const h = n(b.h ?? b.height)+ if ([x, y, w, h].some((c) => Number.isNaN(c))) return null+ return {+ x: clamp01(x),+ y: clamp01(y),+ w: clamp01(w),+ h: clamp01(h),+ }+}++/**+ * Coerce the model reply into a Grounding. Fractions are clamped to+ * 0..1, pixel boxes derived, junk dropped — never throws.+ */+export function normalizeGrounding(raw: unknown, width: number, height: number): Grounding {+ const spec = asRecord(raw)+ const elementsRaw = Array.isArray(spec.elements) ? spec.elements : []+ const elements: GroundedElement[] = []+ for (const item of elementsRaw.slice(0, MAX_GROUNDED)) {+ const e = asRecord(item)+ const box = asBox(e.bounds ?? e.box)+ const label = typeof e.label === 'string' ? e.label.replace(/\s+/g, ' ').trim().slice(0, 80) : ''+ if (!box || !label) continue+ const color = typeof e.color === 'string' && /^#[0-9a-fA-F]{6}$/.test(e.color) ? e.color.toUpperCase() : undefined+ elements.push({+ label,+ role: typeof e.role === 'string' && e.role ? e.role.slice(0, 24) : 'element',+ box,+ px: {+ x: Math.round(box.x * width),+ y: Math.round(box.y * height),+ w: Math.round(box.w * width),+ h: Math.round(box.h * height),+ },+ ...(color ? { color } : {}),+ })+ }+ return {+ description:+ typeof spec.description === 'string' ? spec.description.replace(/\s+/g, ' ').trim().slice(0, 500) : '',+ elements,+ }+}++/** The vision_ground system prompt — pinned next to the normalizer. */+export function visionGroundPrompt(question?: string): string {+ return [+ 'You analyze SCREENSHOTS of a design canvas for a graphic-design agent. Reply with ONLY a JSON object (no markdown fences):',+ '{"description":string,"elements":[{"label":string,"role":"headline|body-text|image|photo|shape|logo|chart|table|button|decoration|other","bounds":{x,y,w,h},"color":"#RRGGBB"}]}',+ 'RULES:',+ '1. bounds are FRACTIONS of the screenshot size (0..1), x/y = top-left.',+ '2. label = what it says/shows (exact visible text for text elements, short subject for images).',+ '3. color: dominant color of the element (omit when unclear).',+ '4. Ground truth only — report what is VISIBLE, never infer hidden structure. Max 40 elements.',+ '5. description: one or two sentences on the overall layout (reading order, visual hierarchy).',+ question ? `6. Pay special attention to: ${question.slice(0, 200)}` : '',+ ]+ .filter(Boolean)+ .join('\n')+}diff --git a/src/lib/notes-outline.test.ts b/src/lib/notes-outline.test.tsnew file mode 100644index 0000000..13a579c--- /dev/null+++ b/src/lib/notes-outline.test.ts@@ -0,0 +1,119 @@+// Wave 4 — lib/notes-outline.ts unit tests.+import { describe, expect, it } from 'vitest'+import { extractOutlines, notesSystemPrompt, normalizeNotes, outlineToPrompt } from './notes-outline'+import type { PageData } from './types'++function page(elements: unknown[], id = 'p1'): PageData {+ return { id, background: { type: 'solid', color: '#fff' }, elements } as unknown as PageData+}++describe('extractOutlines', () => {+ it('titles from the largest text element, bullets from the rest', () => {+ const outlines = extractOutlines([+ page([+ { type: 'text', text: 'Small print', fontSize: 14 },+ { type: 'text', text: 'Quarterly Results', fontSize: 72 },+ { type: 'text', text: 'Revenue up 24% YoY', fontSize: 28 },+ { type: 'rect', x: 0, y: 0, width: 10, height: 10 },+ ]),+ ])+ expect(outlines).toHaveLength(1)+ expect(outlines[0].title).toBe('Quarterly Results')+ expect(outlines[0].bullets).toEqual(['Small print', 'Revenue up 24% YoY'])+ expect(outlines[0].media).toEqual([])+ })++ it('summarizes media elements and skips shapes', () => {+ const outlines = extractOutlines([+ page([+ { type: 'chart', text: 'Sales by region', series: [] },+ { type: 'table', rows: 2, cols: 2 },+ { type: 'image', src: 'x' },+ { type: 'ellipse', x: 1, y: 1, width: 2, height: 2 },+ { type: 'sticker', char: '🎉' },+ ]),+ ])+ expect(outlines[0].title).toBe('Page 1') // no text elements+ expect(outlines[0].media).toEqual([+ 'a chart titled "Sales by region"',+ 'a data table',+ 'an image',+ 'a 🎉 sticker',+ ])+ })++ it('is total on hostile/empty pages and caps length', () => {+ expect(() => extractOutlines([])).not.toThrow()+ const outlines = extractOutlines([page(null as unknown as unknown[])])+ expect(outlines[0].bullets).toEqual([])+ const long = extractOutlines([+ page([{ type: 'text', text: 'x'.repeat(500), fontSize: 10 }]),+ ])+ expect(long[0].bullets[0].length).toBeLessThanOrEqual(160)+ })++ it('caps the page count', () => {+ const many = Array.from({ length: 60 }, (_, i) => page([], `p${i}`))+ expect(extractOutlines(many)).toHaveLength(40)+ })+})++describe('outlineToPrompt', () => {+ it('renders readable prompt blocks', () => {+ const text = outlineToPrompt([+ { index: 0, title: 'Cover', bullets: ['Hello'], media: ['an image'] },+ { index: 1, title: 'End', bullets: [], media: [] },+ ])+ expect(text).toContain('PAGE 1: Cover')+ expect(text).toContain('- Hello')+ expect(text).toContain('- contains an image')+ expect(text).toContain('PAGE 2: End')+ })+})++describe('notesSystemPrompt', () => {+ it('pins count, JSON contract and tone', () => {+ const s = notesSystemPrompt(4, 'confident')+ expect(s).toContain('exactly 4 entries')+ expect(s).toContain('{"notes"')+ expect(s).toContain('confident')+ })+})++describe('normalizeNotes', () => {+ it('keeps valid entries, drops junk, clamps pages, dedupes', () => {+ const notes = normalizeNotes(+ {+ notes: [+ { page: 1, text: ' Welcome everyone. ' },+ { page: 0, text: 'out of range' },+ { page: 9, text: 'out of range' },+ { page: 2, text: 42 },+ { page: 2, text: 'duplicate page' },+ { page: '3', text: 'string page number works' },+ null,+ { text: 'no page' },+ ],+ },+ 3,+ )+ expect(notes).toEqual([+ { page: 1, text: 'Welcome everyone.' },+ // {page:2,text:42} drops first (text not a string), so the string+ // page-2 entry is the first VALID one and stays+ { page: 2, text: 'duplicate page' },+ { page: 3, text: 'string page number works' },+ ])+ })++ it('survives non-object input', () => {+ expect(normalizeNotes('nope', 3)).toEqual([])+ expect(normalizeNotes(null, 3)).toEqual([])+ expect(normalizeNotes({ notes: 'nope' }, 3)).toEqual([])+ })++ it('caps note length', () => {+ const notes = normalizeNotes({ notes: [{ page: 1, text: 'y'.repeat(2000) }] }, 1)+ expect(notes[0].text.length).toBeLessThanOrEqual(600)+ })+})diff --git a/src/lib/notes-outline.ts b/src/lib/notes-outline.tsnew file mode 100644index 0000000..ad367da--- /dev/null+++ b/src/lib/notes-outline.ts@@ -0,0 +1,127 @@+// ─────────────────────────────────────────────────────────────+// Canvix speaker-notes outline (Wave 4 — AI Power-Up).+//+// Pure transform: design pages → a compact, text-only outline the+// notes model can reason about (page titles from the largest text+// elements, bullets from the rest, one line per chart/table/sticker).+// The model never sees element ids, coordinates or JSON — just the+// words, in reading order, so the notes it writes are about CONTENT.+// ─────────────────────────────────────────────────────────────++import type { PageData } from './types'++/** One page's outline — the /api/ai/notes request shape. */+export interface PageOutline {+ index: number+ title: string+ bullets: string[]+ /** non-text element counts, one summary line each */+ media: string[]+}++/** Cap so a 50-page deck cannot blow the prompt budget. */+export const MAX_OUTLINE_PAGES = 40+const MAX_BULLET_LEN = 160+const MAX_TITLE_LEN = 120++function textOf(el: unknown): string {+ const t = el as { text?: unknown } | undefined+ return typeof t?.text === 'string' ? t.text.replace(/\s+/g, ' ').trim() : ''+}++/** fontSize when present (text elements); 0 otherwise. */+function fontSizeOf(el: unknown): number {+ const t = el as { fontSize?: unknown } | undefined+ return typeof t?.fontSize === 'number' ? t.fontSize : 0+}++/**+ * Extract the outline of every page. Deterministic and total — hostile+ * or empty pages yield empty bullets, never a throw.+ */+export function extractOutlines(pages: PageData[]): PageOutline[] {+ const capped = pages.slice(0, MAX_OUTLINE_PAGES)+ return capped.map((page, index) => {+ const elements = Array.isArray(page.elements) ? page.elements : []+ // headline candidates: text elements with a fontSize — the largest+ // non-empty one is the page title+ const texts = elements+ .map((el) => ({ text: textOf(el), size: fontSizeOf(el), type: (el as { type?: string }).type }))+ .filter((t) => t.text.length > 0)+ const title =+ texts+ .filter((t) => t.size > 0)+ .sort((a, b) => b.size - a.size)[0]?.text.slice(0, MAX_TITLE_LEN) ?? `Page ${index + 1}`++ const titleTaken = new Set<string>()+ if (title !== `Page ${index + 1}`) titleTaken.add(title)++ const bullets: string[] = []+ const media: string[] = []+ for (const el of elements) {+ const type = (el as { type?: string }).type+ const text = textOf(el)+ if (type === 'text' || type === undefined) {+ if (!text) continue+ if (titleTaken.has(text)) continue+ const line = text.slice(0, MAX_BULLET_LEN)+ if (line) bullets.push(line)+ } else if (type === 'chart') {+ media.push('a chart' + (text ? ` titled "${text.slice(0, 60)}"` : ''))+ } else if (type === 'table') {+ media.push('a data table')+ } else if (type === 'image' || type === 'video') {+ media.push(`an ${type === 'image' ? 'image' : 'video'}`)+ } else if (type === 'sticker') {+ const ch = (el as { char?: unknown }).char+ if (typeof ch === 'string' && ch) media.push(`a ${ch} sticker`)+ }+ // shapes/lines/draws carry no content — skipped+ }+ return { index, title, bullets: bullets.slice(0, 12), media: media.slice(0, 8) }+ })+}++/** Render one outline back to prompt lines. */+export function outlineToPrompt(outlines: PageOutline[]): string {+ return outlines+ .map((p) => {+ const lines = [`PAGE ${p.index + 1}: ${p.title}`]+ for (const b of p.bullets) lines.push(`- ${b}`)+ for (const m of p.media) lines.push(`- contains ${m}`)+ return lines.join('\n')+ })+ .join('\n\n')+}++/** The notes system prompt — shared contract, pinned next to the+ * transforms so it cannot drift from the response shape. */+export function notesSystemPrompt(count: number, tone: string): string {+ return [+ 'You write presenter speaker notes for a design deck. Reply with ONLY a JSON object (no markdown fences):',+ `{"notes":[{"page":1,"text":string}, ... ]} — exactly ${count} entries, one per page in order.`,+ 'Each note: 2-3 sentences (max 60 words) a presenter would SAY aloud — context, the point to land, a transition hint. ' ++ `Tone: ${tone}. Never read the slide text verbatim; add what the slide does not say.`,+ ].join('\n')+}++/** Coerce the model reply into page-indexed notes; invalid entries are+ * dropped, page numbers clamped to the outline, text trimmed+capped. */+export function normalizeNotes(+ raw: unknown,+ pageCount: number,+): { page: number; text: string }[] {+ const obj = (raw ?? {}) as { notes?: unknown }+ const list = Array.isArray(obj.notes) ? obj.notes : []+ const out: { page: number; text: string }[] = []+ const seen = new Set<number>()+ for (const item of list) {+ const n = (item ?? {}) as { page?: unknown; text?: unknown }+ const page = Math.round(Number(n.page))+ const text = typeof n.text === 'string' ? n.text.replace(/\s+/g, ' ').trim().slice(0, 600) : ''+ if (!Number.isInteger(page) || page < 1 || page > pageCount || !text || seen.has(page)) continue+ seen.add(page)+ out.push({ page, text })+ }+ return out+}diff --git a/src/lib/theme.test.ts b/src/lib/theme.test.tsnew file mode 100644index 0000000..f091c2f--- /dev/null+++ b/src/lib/theme.test.ts@@ -0,0 +1,184 @@+// Wave 4 — lib/theme.ts unit tests.+import { describe, expect, it } from 'vitest'+import { applyTheme, contrast, normalizeTheme, themeSystemPrompt, THEME_ROLES, type Theme } from './theme'+import type { PageData } from './types'++const FONTS = ['Poppins', 'Inter', 'Montserrat', 'Playfair Display']++function page(elements: unknown[]): PageData {+ return { id: 'p1', background: { type: 'solid', color: '#FFFFFF' }, elements } as unknown as PageData+}++describe('contrast', () => {+ it('computes WCAG ratios', () => {+ expect(Math.round(contrast('#000000', '#FFFFFF'))).toBe(21)+ expect(contrast('#FFFFFF', '#FFFFFF')).toBe(1)+ expect(contrast('junk', '#FFFFFF')).toBe(0)+ })+})++describe('normalizeTheme', () => {+ it('normalizes a well-formed theme', () => {+ const t = normalizeTheme(+ {+ name: 'Nordic calm',+ mood: 'cool editorial',+ palette: [+ { hex: '#0B1220', role: 'background' },+ { hex: '#16233A', role: 'surface' },+ { hex: '#F5F7FA', role: 'ink' },+ { hex: '#C3CCDA', role: 'inkSoft' },+ { hex: '#5B8DEF', role: 'accent' },+ { hex: '#9BB8F5', role: 'accentSoft' },+ ],+ fonts: { heading: 'Playfair Display', body: 'Inter' },+ },+ FONTS,+ )+ expect(t.name).toBe('Nordic calm')+ expect(t.palette).toHaveLength(6)+ expect(new Set(t.palette.map((c) => c.role))).toEqual(new Set(THEME_ROLES))+ expect(t.fonts.heading).toBe('Playfair Display')+ // dark bg + light ink = high contrast, guard must not fire+ expect(contrast(t.palette[2].hex, t.palette[0].hex)).toBeGreaterThan(3)+ })++ it('fills missing roles and rejects junk', () => {+ const t = normalizeTheme(+ {+ palette: [+ { hex: 'nope', role: 'background' },+ { hex: '#123456' },+ { hex: '#ABCDEF', role: 'madeup-role' },+ ],+ fonts: { heading: 'Comic Sans', body: 42 },+ },+ FONTS,+ )+ expect(t.palette).toHaveLength(6)+ // junk hex dropped; unroled hex used as a leftover fill+ expect(t.palette.some((c) => c.hex === '#123456' || c.hex === '#ABCDEF')).toBe(true)+ expect(t.fonts.heading).toBe('Poppins') // unknown font → default+ expect(t.fonts.body).toBe('Inter')+ expect(t.name).toBe('AI theme')+ })++ it('contrast guard swaps unreadable ink', () => {+ // model ships light-on-light: white bg, near-white ink+ const t = normalizeTheme(+ {+ palette: [+ { hex: '#FAFAFA', role: 'background' },+ { hex: '#F0F0F0', role: 'ink' },+ { hex: '#111111', role: 'inkSoft' },+ ],+ },+ FONTS,+ )+ const bg = t.palette.find((c) => c.role === 'background')!.hex+ const ink = t.palette.find((c) => c.role === 'ink')!.hex+ expect(contrast(ink, bg)).toBeGreaterThanOrEqual(3)+ })++ it('survives garbage input', () => {+ expect(() => normalizeTheme(null, FONTS)).not.toThrow()+ expect(normalizeTheme('junk', FONTS).palette).toHaveLength(6)+ })+})++describe('applyTheme', () => {+ const theme: Theme = normalizeTheme(+ {+ palette: [+ { hex: '#0B1220', role: 'background' },+ { hex: '#16233A', role: 'surface' },+ { hex: '#F5F7FA', role: 'ink' },+ { hex: '#C3CCDA', role: 'inkSoft' },+ { hex: '#5B8DEF', role: 'accent' },+ { hex: '#9BB8F5', role: 'accentSoft' },+ ],+ fonts: { heading: 'Montserrat', body: 'Inter' },+ },+ FONTS,+ )++ it('recolors backgrounds, text, shapes and lines; leaves media alone', () => {+ const src = page([+ { type: 'text', text: 'Big', fontSize: 80, fill: '#111111', fontFamily: 'Poppins' },+ { type: 'text', text: 'small', fontSize: 20, fill: '#333333', fontFamily: 'Poppins' },+ { type: 'rect', x: 0, y: 0, width: 10, height: 10, fill: '#7630D7', stroke: 'transparent', strokeWidth: 0 },+ { type: 'line', x: 0, y: 0, stroke: '#999999', strokeWidth: 2 },+ { type: 'image', src: 'data:x', fill: '#123456' },+ { type: 'chart', fill: '#654321' },+ { type: 'sticker', char: '🎉', fill: '#ABCABC' },+ ])+ const [out] = applyTheme([src], theme)+ expect(out.background).toEqual({ type: 'solid', color: '#0B1220' })+ const [big, small, rect, line, image, chart, sticker] = out.elements as unknown as Record<string, unknown>[]+ expect(big.fill).toBe('#F5F7FA') // heading ink+ expect(big.fontFamily).toBe('Montserrat')+ expect(small.fill).toBe('#C3CCDA') // body inkSoft+ expect(small.fontFamily).toBe('Inter')+ expect(rect.fill).toBe('#5B8DEF') // accent+ expect(line.stroke).toBe('#5B8DEF')+ expect(image.fill).toBe('#123456') // untouched+ expect(chart.fill).toBe('#654321')+ expect(sticker.fill).toBe('#ABCABC')+ })++ it('gradient backgrounds map to accent→accentSoft preserving the angle', () => {+ const src: PageData = {+ id: 'p',+ background: { type: 'gradient', from: '#111111', to: '#222222', angle: 45 },+ elements: [],+ } as unknown as PageData+ const [out] = applyTheme([src], theme)+ expect(out.background).toEqual({ type: 'gradient', from: '#5B8DEF', to: '#9BB8F5', angle: 45 })+ })++ it('neutral shape fills become surface, loud ones accent', () => {+ const src = page([+ { type: 'rect', fill: '#FFFFFF', stroke: 'transparent', strokeWidth: 0 },+ { type: 'ellipse', fill: '#FF00AA' },+ ])+ const [out] = applyTheme([src], theme)+ expect((out.elements[0] as unknown as Record<string, unknown>).fill).toBe('#16233A') // surface+ expect((out.elements[1] as unknown as Record<string, unknown>).fill).toBe('#5B8DEF') // accent+ })++ it('never strands low-contrast text on the new background', () => {+ // light theme onto a design whose text was already light — the+ // guard must flip body text to ink when inkSoft would vanish+ const lightTheme = normalizeTheme(+ {+ palette: [+ { hex: '#F8FAFC', role: 'background' },+ { hex: '#EEEEEE', role: 'surface' },+ { hex: '#0F172A', role: 'ink' },+ { hex: '#E2E8F0', role: 'inkSoft' }, // low contrast on bg+ ],+ },+ FONTS,+ )+ const src = page([{ type: 'text', text: 'body', fontSize: 18, fill: '#000000' }])+ const [out] = applyTheme([src], lightTheme)+ const body = out.elements[0] as unknown as { fill: string }+ expect(contrast(body.fill, '#F8FAFC')).toBeGreaterThanOrEqual(3)+ })++ it('is pure — the input pages are not mutated', () => {+ const src = page([{ type: 'text', text: 'x', fontSize: 20, fill: '#123123' }])+ const before = JSON.stringify(src)+ applyTheme([src], theme)+ expect(JSON.stringify(src)).toBe(before)+ })+})++describe('themeSystemPrompt', () => {+ it('pins the roles, fonts and JSON contract', () => {+ const s = themeSystemPrompt(FONTS)+ expect(s).toContain(THEME_ROLES.join(', '))+ expect(s).toContain('Playfair Display')+ expect(s).toContain('{"name"')+ })+})diff --git a/src/lib/theme.ts b/src/lib/theme.tsnew file mode 100644index 0000000..6147ef6--- /dev/null+++ b/src/lib/theme.ts@@ -0,0 +1,237 @@+// ─────────────────────────────────────────────────────────────+// Canvix AI theme engine (Wave 4 — AI Power-Up).+//+// Pure transforms for "AI theme generation": the model proposes a+// role-tagged palette + font pairing; applyTheme() maps the roles onto+// a design — page backgrounds, text ink, shape accents, line colors —+// with a contrast guard so light palettes never strand white text on+// white pages (and vice versa). Deterministic and total.+// ─────────────────────────────────────────────────────────────++import type { AnyElement, LineElement, PageData, ShapeElement, TableElement, TextElement } from './types'++/** Palette roles the model may assign (fixed vocabulary). */+export type ThemeRole = 'background' | 'surface' | 'ink' | 'inkSoft' | 'accent' | 'accentSoft'++export interface ThemeColor {+ hex: string+ role: ThemeRole+}++export interface Theme {+ name: string+ mood?: string+ palette: ThemeColor[]+ fonts: { heading: string; body: string }+}++export const THEME_ROLES: ThemeRole[] = ['background', 'surface', 'ink', 'inkSoft', 'accent', 'accentSoft']++const FALLBACK: Theme = {+ name: 'Canvix default',+ palette: [+ { hex: '#FFFFFF', role: 'background' },+ { hex: '#F4F5F7', role: 'surface' },+ { hex: '#1F2226', role: 'ink' },+ { hex: '#5B6472', role: 'inkSoft' },+ { hex: '#7630D7', role: 'accent' },+ { hex: '#02C0CC', role: 'accentSoft' },+ ],+ fonts: { heading: 'Poppins', body: 'Inter' },+}++// ── color math ───────────────────────────────────────────────++/** '#RRGGBB' → [r,g,b] (0..255); null when malformed. */+function hexToRgb(hex: string): [number, number, number] | null {+ if (!/^#[0-9a-fA-F]{6}$/.test(hex)) return null+ return [+ parseInt(hex.slice(1, 3), 16),+ parseInt(hex.slice(3, 5), 16),+ parseInt(hex.slice(5, 7), 16),+ ]+}++/** relative luminance (WCAG) */+function luminance(hex: string): number | null {+ const rgb = hexToRgb(hex)+ if (!rgb) return null+ const [r, g, b] = rgb.map((c) => {+ const s = c / 255+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4+ })+ return 0.2126 * r + 0.7152 * g + 0.0722 * b+}++/** WCAG contrast ratio between two hexes; 0 when either is malformed. */+export function contrast(a: string, b: string): number {+ const la = luminance(a)+ const lb = luminance(b)+ if (la === null || lb === null) return 0+ const hi = Math.max(la, lb)+ const lo = Math.min(la, lb)+ return (hi + 0.05) / (lo + 0.05)+}++// ── normalizeTheme ───────────────────────────────────────────++/**+ * Coerce raw model output into a Theme. Unknown roles drop; missing+ * roles fill from the model's leftovers (or the fallback). Never+ * throws, always returns a complete, contrast-checked palette.+ */+export function normalizeTheme(raw: unknown, fonts: readonly string[]): Theme {+ const spec = (raw ?? {}) as Record<string, unknown>+ const paletteRaw = Array.isArray(spec.palette) ? spec.palette : []+ const byRole = new Map<ThemeRole, string>()+ const leftovers: string[] = []+ for (const item of paletteRaw.slice(0, 12)) {+ const c = (item ?? {}) as Record<string, unknown>+ const hex = typeof c.hex === 'string' && /^#[0-9a-fA-F]{6}$/.test(c.hex.trim()) ? c.hex.trim().toUpperCase() : null+ if (!hex) continue+ const role = typeof c.role === 'string' && (THEME_ROLES as string[]).includes(c.role) ? (c.role as ThemeRole) : null+ if (role && !byRole.has(role)) byRole.set(role, hex)+ else if (!byRole.has(role === null ? 'accent' : role)) leftovers.push(hex)+ }+ // fill missing roles: leftovers first, then the fallback palette+ for (const role of THEME_ROLES) {+ if (byRole.has(role)) continue+ const fromLeft = leftovers.shift()+ if (fromLeft) byRole.set(role, fromLeft)+ else byRole.set(role, FALLBACK.palette.find((c) => c.role === role)!.hex)+ }++ const known = (v: unknown, fallback: string): string => {+ const s = typeof v === 'string' ? v : ''+ return fonts.includes(s) ? s : fallback+ }+ const fontsSpec = (spec.fonts ?? {}) as Record<string, unknown>+ const theme: Theme = {+ name: typeof spec.name === 'string' && spec.name.trim() ? spec.name.trim().slice(0, 60) : 'AI theme',+ mood: typeof spec.mood === 'string' ? spec.mood.slice(0, 120) : undefined,+ palette: THEME_ROLES.map((role) => ({ role, hex: byRole.get(role)! })),+ fonts: {+ heading: known(fontsSpec.heading, FALLBACK.fonts.heading),+ body: known(fontsSpec.body, FALLBACK.fonts.body),+ },+ }++ // contrast guard: ink must be readable on background. If the model+ // picked a low-contrast pair, swap ink for its inverse (black/white+ // by background luminance) rather than shipping unreadable text.+ const bg = byRole.get('background')!+ const ink = byRole.get('ink')!+ if (contrast(bg, ink) < 3) {+ const l = luminance(bg)+ byRole.set('ink', l !== null && l > 0.4 ? '#111318' : '#FFFFFF')+ theme.palette = THEME_ROLES.map((role) => ({ role, hex: byRole.get(role)! }))+ }+ return theme+}++// ── applyTheme ───────────────────────────────────────────────++/** close-ish hex compare (exact after normalize; generous anyway) */+function sameColor(a: string, b: string): boolean {+ return a.toUpperCase() === b.toUpperCase()+}++/** grayscale-ish? (white, black, grays — channel spread ≤ 16). These+ * are "structural" fills (photo frames, dividers) that become surface+ * instead of screaming accent. */+function isNeutral(hex: string): boolean {+ const rgb = hexToRgb(hex)+ if (!rgb) return true+ const [r, g, b] = rgb+ return Math.max(r, g, b) - Math.min(r, g, b) <= 16+}++/**+ * Map a theme onto a design (pure — returns NEW pages).+ *+ * Role mapping (documented contract):+ * - page backgrounds → background (solid) / gradient(accent→accentSoft)+ * - large headline text → ink + heading font+ * - other text → inkSoft + body font+ * - shapes / lines → accent (fills), accentSoft (strokes)+ * - tables → header fill accent, text ink+ *+ * Contrast guard #2: any text whose new fill would sit under 3:1 on its+ * page's new background flips to ink (which passed guard #1). Images,+ * charts, stickers and draws are untouched — recoloring media is a lie.+ */+export function applyTheme(pages: PageData[], theme: Theme): PageData[] {+ const colorOf = (role: ThemeRole): string => theme.palette.find((c) => c.role === role)?.hex ?? '#000000'+ const bg = colorOf('background')+ const ink = colorOf('ink')+ const inkSoft = colorOf('inkSoft')+ const accent = colorOf('accent')+ const accentSoft = colorOf('accentSoft')++ return pages.map((page) => {+ const nextBackground =+ page.background.type === 'gradient'+ ? { type: 'gradient' as const, from: accent, to: accentSoft, angle: page.background.angle }+ : { type: 'solid' as const, color: bg }++ const elements = (page.elements ?? []).map((el) => {+ const next: AnyElement = { ...el }+ switch (el.type) {+ case 'text': {+ // headline heuristic: the page's largest fontSize is the+ // heading; everything else is body (same split the notes+ // outline uses — one shared notion of "headline").+ const isHeading =+ (page.elements ?? []).reduce((max, e) => (e.type === 'text' && e.fontSize > max ? e.fontSize : max), 0) ===+ el.fontSize+ const t = next as TextElement+ t.fill = isHeading ? ink : inkSoft+ t.fontFamily = isHeading ? theme.fonts.heading : theme.fonts.body+ // guard: never strand low-contrast text on the new background+ if (contrast(t.fill, bg) < 3) t.fill = ink+ break+ }+ case 'rect':+ case 'ellipse':+ case 'triangle':+ case 'star':+ case 'polygon': {+ // accent shapes keep accents; neutral (grayscale) fills become+ // surface so photo-frame rects don't turn loud+ const s = next as ShapeElement+ s.fill = isNeutral(el.fill) ? colorOf('surface') : accent+ if ('stroke' in el && typeof el.stroke === 'string' && el.stroke !== 'transparent' && el.strokeWidth > 0) {+ s.stroke = accentSoft+ }+ break+ }+ case 'line': {+ (next as LineElement).stroke = accent+ break+ }+ case 'table': {+ // header row fill rides the table renderer's own field set —+ // recolor text only (safe across schema versions)+ (next as TableElement).fill = inkSoft+ break+ }+ default:+ break // image / video / chart / sticker / path / draw: untouched+ }+ return next+ })+ return { ...page, background: nextBackground, elements }+ })+}++/** The theme system prompt — pinned next to the transforms. */+export function themeSystemPrompt(fonts: readonly string[]): string {+ const fontList = fonts.slice(0, 24).join(', ')+ return [+ 'You are a brand color-system designer. Reply with ONLY a JSON object (no markdown fences):',+ '{"name":string,"mood":string,"palette":[{"hex":"#RRGGBB","role":string}],"fonts":{"heading":string,"body":string}}',+ `Palette roles — exactly these, one hex each: ${THEME_ROLES.join(', ')}.`,+ 'Rules: 6 colors, hex only, ink must contrast strongly with background (WCAG ≥ 7), accents saturated, background/surface calm.',+ `Fonts — heading and body from this list only: ${fontList}.`,+ ].join('\n')+}diff --git a/src/lib/types.ts b/src/lib/types.tsindex 8d4ca6b..0064572 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -238,6 +238,19 @@ export interface ImageElement extends BaseElement {* on selection, never burned into exports (neither provider license* demands on-content credit). */credit?: { provider: string; author: string; license: string; url: string }+ /** v0.19 (Wave 4): the provider-side handle for AI-generated images —+ * the generation/edit response's image_ent_id. VibesAI-class edit+ * providers only edit images THEY generated (matched by exact bytes+ * or this id — re-encoding the src breaks the byte match, so the id+ * is the durable link). Stored on the element, forwarded as+ * sourceEntId by the AI edit calls, refreshed on every successful+ * edit. Absent on uploads, stock photos and bundled assets. */+ aiEntId?: string+ /** v0.19 (Wave 4): accessibility alt text — AI-generatable, always+ * user-editable. Rides autosave/versions/collab like any element+ * field; consumed by screen-reader landmarks and shown in the+ * properties bar. Never burned into visual exports. */+ alt?: string}export interface StickerElement extends BaseElement {diff --git a/src/lib/upscale.test.ts b/src/lib/upscale.test.tsnew file mode 100644index 0000000..215a950--- /dev/null+++ b/src/lib/upscale.test.ts@@ -0,0 +1,145 @@+// Wave 4 — lib/upscale.ts unit tests.+// Lanczos-3 resampling: geometry, alpha discipline, determinism.+import { describe, expect, it } from 'vitest'+import { clampFactor, factorFor, lanczosUpscale, type Raster } from './upscale'++/** solid-color raster */+function solid(w: number, h: number, rgba: [number, number, number, number]): Raster {+ const data = new Uint8ClampedArray(w * h * 4)+ for (let i = 0; i < w * h; i++) {+ data[i * 4] = rgba[0]+ data[i * 4 + 1] = rgba[1]+ data[i * 4 + 2] = rgba[2]+ data[i * 4 + 3] = rgba[3]+ }+ return { data, width: w, height: h }+}++describe('clampFactor', () => {+ it('clamps to 1..4 and floors non-integers', () => {+ expect(clampFactor(0)).toBe(1)+ expect(clampFactor(-3)).toBe(1)+ expect(clampFactor(NaN)).toBe(1)+ expect(clampFactor(1.9)).toBe(1)+ expect(clampFactor(2)).toBe(2)+ expect(clampFactor(4)).toBe(4)+ expect(clampFactor(9)).toBe(4)+ expect(clampFactor(Infinity)).toBe(4)+ })+})++describe('factorFor', () => {+ it('never lets a side exceed the output cap', () => {+ // 5000px side: 2x would be 10000 > 8192 → capped to 1+ expect(factorFor(5000, 100, 2)).toBe(1)+ // 3000px side: 2x = 6000 ok, 4x = 12000 no → 2+ expect(factorFor(3000, 100, 4)).toBe(2)+ expect(factorFor(100, 100, 3)).toBe(3)+ })+})++describe('lanczosUpscale', () => {+ it('factor 1 returns an equal copy (and a copy, not the same buffer)', () => {+ const src = solid(3, 2, [10, 20, 30, 255])+ const out = lanczosUpscale(src, 1)+ expect(out.width).toBe(3)+ expect(out.height).toBe(2)+ expect(Array.from(out.data)).toEqual(Array.from(src.data))+ expect(out.data).not.toBe(src.data)+ })++ it('produces the exact target geometry', () => {+ const src = solid(5, 3, [200, 10, 10, 255])+ const out = lanczosUpscale(src, 3)+ expect(out.width).toBe(15)+ expect(out.height).toBe(9)+ expect(out.data.length).toBe(15 * 9 * 4)+ })++ it('keeps a solid opaque image solid (Lanczos preserves constants)', () => {+ const src = solid(4, 4, [120, 60, 200, 255])+ const out = lanczosUpscale(src, 2)+ for (let i = 0; i < out.width * out.height; i++) {+ expect(out.data[i * 4]).toBeCloseTo(120, 0)+ expect(out.data[i * 4 + 1]).toBeCloseTo(60, 0)+ expect(out.data[i * 4 + 2]).toBeCloseTo(200, 0)+ expect(out.data[i * 4 + 3]).toBe(255)+ }+ })++ it('preserves a horizontal color step within kernel tolerance', () => {+ // left half red, right half blue; upscaling must keep the plateau+ // colors and place the transition between the halves+ const w = 8+ const src: Raster = { data: new Uint8ClampedArray(w * 2 * 4), width: w, height: 2 }+ for (let y = 0; y < 2; y++) {+ for (let x = 0; x < w; x++) {+ const i = (y * w + x) * 4+ const red = x < w / 2+ src.data[i] = red ? 255 : 0+ src.data[i + 1] = 0+ src.data[i + 2] = red ? 0 : 255+ src.data[i + 3] = 255+ }+ }+ const out = lanczosUpscale(src, 4)+ // far-left plateau stays red, far-right stays blue+ const left = 1 * 4+ const right = (out.width - 2) * 4+ expect(out.data[left]).toBeGreaterThan(240)+ expect(out.data[left + 2]).toBeLessThan(15)+ expect(out.data[right]).toBeLessThan(15)+ expect(out.data[right + 2]).toBeGreaterThan(240)+ })++ it('does not bleed transparent-pixel colors into opaque regions', () => {+ // a fully transparent GREEN column next to opaque RED columns —+ // without premultiplication the red edge turns muddy+ const w = 6+ const src: Raster = { data: new Uint8ClampedArray(w * 1 * 4), width: w, height: 1 }+ for (let x = 0; x < w; x++) {+ const i = x * 4+ if (x === 3) {+ src.data[i] = 0+ src.data[i + 1] = 255+ src.data[i + 2] = 0+ src.data[i + 3] = 0+ } else {+ src.data[i] = 255+ src.data[i + 1] = 0+ src.data[i + 2] = 0+ src.data[i + 3] = 255+ }+ }+ const out = lanczosUpscale(src, 2)+ // the opaque plateau must stay pure red; alpha stays opaque there+ const i = 2 * 4 // destination x=2 (source x=1 area)+ expect(out.data[i + 3]).toBe(255)+ expect(out.data[i + 1]).toBeLessThan(30) // no green bleed+ expect(out.data[i]).toBeGreaterThan(225)+ })++ it('is deterministic — same input, same output', () => {+ const src = solid(7, 5, [1, 2, 3, 200])+ // vary a couple of pixels+ src.data[0] = 250+ src.data[9] = 9+ const a = lanczosUpscale(src, 2)+ const b = lanczosUpscale(src, 2)+ expect(Array.from(a.data)).toEqual(Array.from(b.data))+ })++ it('rejects empty rasters and mismatched buffers', () => {+ expect(() => lanczosUpscale({ data: new Uint8ClampedArray(0), width: 0, height: 4 }, 2)).toThrow()+ expect(() =>+ lanczosUpscale({ data: new Uint8ClampedArray(4), width: 4, height: 4 }, 2),+ ).toThrow()+ })++ it('handles odd dimensions', () => {+ const src = solid(3, 5, [9, 9, 9, 255])+ const out = lanczosUpscale(src, 3)+ expect(out.width).toBe(9)+ expect(out.height).toBe(15)+ })+})diff --git a/src/lib/upscale.ts b/src/lib/upscale.tsnew file mode 100644index 0000000..73eb773--- /dev/null+++ b/src/lib/upscale.ts@@ -0,0 +1,154 @@+// ─────────────────────────────────────────────────────────────+// Canvix local upscaler (Wave 4 — AI Power-Up).+//+// High-quality Lanczos-3 resampling in pure TypeScript — the local half+// of the "Real-ESRGAN / Lanczos" roadmap item. Zero downloads, zero+// provider calls, works offline on ANY image (uploads, stock photos,+// AI generations — the VibesAI-class providers only edit images they+// generated themselves, so local tools are the universal path).+//+// Pipeline: premultiply → separable Lanczos-3 (horizontal, then+// vertical) → unpremultiply. Premultiplication matters for cut-outs+// (the BG remover's alpha PNGs): filtering straight RGBA bleeds the+// color of fully-transparent pixels into the edges of the subject.+// ─────────────────────────────────────────────────────────────++/** A raw RGBA raster (the canvas ImageData shape — Uint8ClampedArray). */+export interface Raster {+ data: Uint8ClampedArray+ width: number+ height: number+}++/** Hard output cap — protects the tab from accidental 16k monsters. */+export const MAX_OUTPUT_SIDE = 8192++/** Largest accepted upscale factor. */+export const MAX_FACTOR = 4++function lanczos3(x: number): number {+ if (x === 0) return 1+ const ax = Math.abs(x)+ if (ax >= 3) return 0+ const px = Math.PI * x+ return (3 * Math.sin(px) * Math.sin(px / 3)) / (px * px)+}++/** Clamp an integer factor to the supported range (min 1). */+export function clampFactor(factor: number): number {+ if (Number.isNaN(factor)) return 1+ if (factor === Infinity) return MAX_FACTOR+ const f = Math.floor(factor)+ if (f < 1) return 1+ return Math.min(f, MAX_FACTOR)+}++/**+ * Largest usable factor: never let a side exceed MAX_OUTPUT_SIDE.+ * Returns ≥1 so a tiny upscale of an already-huge image is a no-op+ * (factor 1) rather than an error the UI has to special-case.+ */+export function factorFor(srcW: number, srcH: number, wanted: number): number {+ const f = clampFactor(wanted)+ const maxBySide = Math.max(1, Math.floor(Math.min(MAX_OUTPUT_SIDE / srcW, MAX_OUTPUT_SIDE / srcH)))+ return Math.max(1, Math.min(f, maxBySide))+}++/** One separable pass. `toSrc` maps a destination index to source space. */+function resampleAxis(+ src: Raster,+ dstW: number,+ dstH: number,+ horizontal: boolean,+): Raster {+ const srcLen = horizontal ? src.width : src.height+ const dstLen = horizontal ? dstW : dstH+ const out = new Uint8ClampedArray(dstW * dstH * 4)+ // scale factor: source pixels per destination pixel+ const scale = srcLen / dstLen+ // kernel support in SOURCE pixels (at least 1 so pure upscales keep a+ // meaningful window; downscales widen it proportionally)+ const support = Math.max(1, 3 * scale)+ // weight lookup discretised to 1/256 source px — the kernel is smooth+ // and symmetric, a shared table keeps the loop allocation-light+ const TABLE_N = 1024+ const table = new Float32Array(TABLE_N + 1)+ for (let i = 0; i <= TABLE_N; i++) table[i] = lanczos3((i / TABLE_N) * support)++ const srcStride = src.width * 4+ const dstStride = dstW * 4++ for (let d = 0; d < dstLen; d++) {+ // centre of destination pixel d in source coordinates+ const centre = (d + 0.5) * scale - 0.5+ const lo = Math.max(0, Math.ceil(centre - support))+ const hi = Math.min(srcLen - 1, Math.floor(centre + support))+ const taps: { idx: number; w: number }[] = []+ let wsum = 0+ for (let s = lo; s <= hi; s++) {+ const dist = Math.abs(s - centre)+ const w = dist >= support ? 0 : table[Math.min(TABLE_N, Math.round((dist / support) * TABLE_N))]+ if (w !== 0) {+ taps.push({ idx: s, w })+ wsum += w+ }+ }+ if (wsum === 0) {+ // degenerate window (can't happen with support ≥1, but stay safe):+ // nearest neighbour+ taps.push({ idx: Math.min(srcLen - 1, Math.max(0, Math.round(centre))), w: 1 })+ wsum = 1+ }+ for (let other = 0; other < (horizontal ? src.height : src.width); other++) {+ const dstBase = horizontal+ ? other * dstStride + d * 4+ : d * dstStride + other * 4+ let r = 0+ let g = 0+ let b = 0+ let a = 0+ for (const t of taps) {+ const srcBase = horizontal+ ? other * srcStride + t.idx * 4+ : t.idx * srcStride + other * 4+ const w = t.w / wsum+ const av = src.data[srcBase + 3]+ // premultiplied sampling: weight color by its own alpha so+ // transparent pixels contribute nothing+ r += src.data[srcBase] * (av / 255) * w+ g += src.data[srcBase + 1] * (av / 255) * w+ b += src.data[srcBase + 2] * (av / 255) * w+ a += av * w+ }+ if (a > 0.0001) {+ // unpremultiply+ out[dstBase] = r / (a / 255)+ out[dstBase + 1] = g / (a / 255)+ out[dstBase + 2] = b / (a / 255)+ }+ out[dstBase + 3] = a+ }+ }+ return { data: out, width: dstW, height: dstH }+}++/**+ * Lanczos-3 upscale (or downscale) of an RGBA raster. `factor` is+ * clamped to 1..4 and by the MAX_OUTPUT_SIDE cap; factor 1 returns a+ * copy. Deterministic and pure — the same input always yields the same+ * output, which is what the unit tests pin down.+ */+export function lanczosUpscale(src: Raster, factor: number): Raster {+ if (src.width < 1 || src.height < 1) throw new Error('upscale: empty raster')+ if (src.data.length < src.width * src.height * 4) throw new Error('upscale: data/size mismatch')+ const f = clampFactor(factor)+ if (f === 1) {+ return { data: new Uint8ClampedArray(src.data), width: src.width, height: src.height }+ }+ const dstW = Math.min(MAX_OUTPUT_SIDE, src.width * f)+ const dstH = Math.min(MAX_OUTPUT_SIDE, src.height * f)+ // horizontal pass: W×H → dstW×H+ const mid = resampleAxis(src, dstW, src.height, true)+ // vertical pass: dstW×H → dstW×dstH+ return resampleAxis(mid, dstW, dstH, false)+}diff --git a/src/store/editor-store.ts b/src/store/editor-store.tsindex 2c9ad09..0f543c9 100644--- a/src/store/editor-store.ts+++ b/src/store/editor-store.ts@@ -186,6 +186,9 @@ interface EditorState {addPage: () => voiddeletePage: (index: number) => voidduplicatePage: (index: number) => void+ /** v0.19 (Wave 4): append fully-prepared pages (agentic plan apply).+ * Coarse pages:replace sync — same event undo rides. */+ appendPages: (newPages: PageData[]) => voidsetCurrentPage: (index: number) => voidsetPageBackground: (bg: Background) => voidapplyTemplate: (t: TemplateDef) => void@@ -785,6 +788,16 @@ export const useEditorStore = create<EditorState>((set, get) => ({emit({ kind: 'page:add', page })},+ appendPages: (newPages) => {+ if (!Array.isArray(newPages) || !newPages.length) return+ get().pushHistory()+ const { pages } = get()+ const stamped = stampPages(newPages, nowHlc())+ const next = [...pages, ...stamped]+ set({ pages: next, currentPage: pages.length, selectedIds: [] })+ emit({ kind: 'pages:replace', pages: next, width: get().width, height: get().height })+ },+deletePage: (index) => {const { pages } = get()if (pages.length <= 1) returndiff --git a/tests/e2e/wave4-ai-powerup.spec.ts b/tests/e2e/wave4-ai-powerup.spec.tsnew file mode 100644index 0000000..74d9e00--- /dev/null+++ b/tests/e2e/wave4-ai-powerup.spec.ts@@ -0,0 +1,420 @@+import { test, expect, type Page } from '@playwright/test'+import { readFileSync, writeFileSync } from 'node:fs'++/**+ * v0.19 (Wave 4) — AI Power-Up e2e.+ *+ * Exercises the surfaces a user actually touches, with the AI providers+ * MOCKED at the route layer (the same discipline the suite uses for+ * stock providers): the agentic plan review gate, speaker-notes+ * generation, AI themes, alt text, and the local image power tools+ * (which need no provider at all — the upscaler is driven for real in+ * the browser). Document truth is asserted through the designs API.+ *+ * Register budget: ONE registration per run (the wave3 pattern).+ */++// an 8×8 solid-red PNG (75 bytes)+const RED_PNG_B64 =+ 'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAEklEQVR4nGP4z8CAFWEXHbQSACj/P8Fu7N9hAAAAAElFTkSuQmCC'++function textEl(overrides: Record<string, unknown> = {}) {+ return {+ id: 'w4_text',+ type: 'text',+ name: 'wave4 text',+ x: 100,+ y: 100,+ width: 500,+ height: 80,+ rotation: 0,+ opacity: 1,+ locked: false,+ visible: true,+ text: 'Quarterly Results',+ fontSize: 72,+ fontFamily: 'Inter',+ bold: true,+ italic: false,+ underline: false,+ strike: false,+ uppercase: false,+ fill: '#1F2226',+ align: 'left',+ lineHeight: 1.25,+ letterSpacing: 0,+ ...overrides,+ }+}++function imageEl(overrides: Record<string, unknown> = {}) {+ return {+ id: 'w4_image',+ type: 'image',+ name: 'wave4 image',+ x: 420,+ y: 120,+ width: 300,+ height: 300,+ rotation: 0,+ opacity: 1,+ locked: false,+ visible: true,+ src: `data:image/png;base64,${RED_PNG_B64}`,+ radius: 0,+ naturalWidth: 8,+ naturalHeight: 8,+ ...overrides,+ }+}++let SHARED_ACCOUNT: { username: string; password: string } | null = null+const CRED_FILE = '/tmp/w4-e2e-account.json'++async function register(page: Page, tag: string): Promise<string> {+ if (SHARED_ACCOUNT) return SHARED_ACCOUNT.username+ try {+ const saved = JSON.parse(readFileSync(CRED_FILE, 'utf8')) as { username: string; password: string }+ const res = await page.request.post('/api/auth/login', { data: saved })+ if (res.status() < 300) {+ SHARED_ACCOUNT = saved+ return saved.username+ }+ } catch {+ /* no saved account yet */+ }+ const username = `w4_${tag}_${Date.now().toString(36)}`+ const password = `W4-E2e-${username}-19!q`+ const res = await page.request.post('/api/auth/register', { data: { username, password } })+ expect(res.status(), `register ${username}`).toBeLessThan(300)+ SHARED_ACCOUNT = { username, password }+ try {+ writeFileSync(CRED_FILE, JSON.stringify(SHARED_ACCOUNT))+ } catch {+ /* read-only fs — module fallback covers same-file tests */+ }+ return username+}++async function createDesign(page: Page, name: string, elements: unknown[]): Promise<string> {+ const res = await page.request.post('/api/designs', {+ data: {+ name,+ width: 1080,+ height: 720,+ pages: [{ id: 'p1', background: { type: 'solid', color: '#FFFFFF' }, elements }],+ },+ })+ expect(res.status(), `create design: ${await res.text()}`).toBeLessThan(300)+ return ((await res.json()) as { id: string }).id+}++async function openEditor(page: Page, designId: string) {+ await page.goto(`/design/${designId}`)+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 60_000 })+}++async function doc(page: Page, designId: string) {+ const res = await page.request.get(`/api/designs/${designId}`)+ expect(res.status()).toBe(200)+ return (await res.json()) as {+ pages: { elements: Record<string, any>[]; notes?: string }[]+ }+}++async function waitForDoc(+ page: Page,+ designId: string,+ predicate: (d: Awaited<ReturnType<typeof doc>>) => boolean,+ what: string,+ timeoutMs = 15_000+) {+ const started = Date.now()+ let last: Awaited<ReturnType<typeof doc>> | null = null+ while (Date.now() - started < timeoutMs) {+ last = await doc(page, designId)+ if (predicate(last)) return last+ await page.waitForTimeout(500)+ }+ throw new Error(`document never showed ${what} within ${timeoutMs}ms — last: ${JSON.stringify(last?.pages[0]).slice(0, 300)}`)+}++/** select an element through the Layers tab (Konva is DOM-opaque) */+async function selectViaLayers(page: Page, label: string) {+ const layersTab = page.getByRole('button', { name: 'Layers', exact: true })+ if (!(await layersTab.isVisible().catch(() => false))) {+ await page.getByRole('button', { name: 'Tools', exact: true }).click()+ await layersTab.click()+ }+ await page.getByText(label, { exact: true }).click()+}++/** open a registry app from the Apps rail */+async function openApp(page: Page, appName: string) {+ await page.getByRole('button', { name: 'Apps', exact: true }).click()+ await page.getByText(appName, { exact: true }).first().click()+}++/** the mocked plan the /api/ai/plan route fulfills with */+const MOCK_PLAN = {+ plan: {+ name: 'Trattoria Menu',+ summary: 'Rustic two-page menu with warm accents',+ width: 1080,+ height: 720,+ pages: [+ {+ id: 'pp1',+ title: 'Cover',+ enabled: true,+ background: { type: 'gradient', from: '#7A3B2E', to: '#D9A566', angle: 135 },+ elements: [+ { id: 'e1', type: 'text', enabled: true, text: 'Trattoria da Luca', x: 140, y: 240, width: 800, fontSize: 84, fontFamily: 'Playfair Display', bold: true, fill: '#FFF6EC', align: 'center' },+ { id: 'e2', type: 'rect', enabled: true, x: 340, y: 420, width: 400, height: 8, fill: '#D9A566' },+ ],+ },+ {+ id: 'pp2',+ title: 'Antipasti',+ enabled: true,+ background: { type: 'solid', color: '#FFF6EC' },+ elements: [+ { id: 'e3', type: 'text', enabled: true, text: 'Antipasti', x: 140, y: 120, width: 400, fontSize: 56, fontFamily: 'Playfair Display', bold: true, fill: '#7A3B2E', align: 'left' },+ ],+ },+ ],+ },+}++const MOCK_THEME = {+ theme: {+ name: 'Nordic calm',+ mood: 'cool editorial',+ palette: [+ { hex: '#0B1220', role: 'background' },+ { hex: '#16233A', role: 'surface' },+ { hex: '#F5F7FA', role: 'ink' },+ { hex: '#C3CCDA', role: 'inkSoft' },+ { hex: '#5B8DEF', role: 'accent' },+ { hex: '#9BB8F5', role: 'accentSoft' },+ ],+ fonts: { heading: 'Montserrat', body: 'Inter' },+ },+}++const MOCK_NOTES = {+ notes: [+ { page: 1, text: 'Welcome the room, land the one number that matters, tease the demo.' },+ { page: 2, text: 'Walk the antipasti board left to right; mention the daily cheese.' },+ ],+}++test.describe('Wave 4 — AI Power-Up', () => {+ test.setTimeout(180_000)++ test('agentic plan: review gate lets you edit, toggle, then apply native pages', async ({ page }) => {+ await register(page, 'plan')+ const designId = await createDesign(page, 'w4 plan', [textEl({ text: 'Seed page' })])+ await openEditor(page, designId)++ await page.route('**/api/ai/plan', (route) => route.fulfill({ json: MOCK_PLAN }))+ await openApp(page, 'AI design plan')++ // the brief + generate+ await page.getByLabel('Design brief').fill('Two-page trattoria menu, rustic and warm')+ await page.getByRole('button', { name: 'Plan my design' }).click()++ // the review gate: both pages render as cards+ await expect(page.getByText('Trattoria Menu', { exact: true })).toBeVisible({ timeout: 15_000 })+ await expect(page.getByText('Cover', { exact: true })).toBeVisible()+ await expect(page.getByText('Antipasti', { exact: true })).toBeVisible()++ // editable copy — rewrite the headline+ const headline = page.locator('input[aria-label="Element text"]').first()+ await headline.fill('Trattoria da Enzo')++ // toggle the second page OFF — the gate must skip it on apply+ // (the page checkbox's aria-label is namespaced with "page")+ await page.getByRole('button', { name: 'Disable page Antipasti' }).click()++ await page.getByRole('button', { name: /Apply \(1p/ }).click()++ // document truth: exactly one new page, with the EDITED headline+ const applied = await waitForDoc(page, designId, (d) => d.pages.length === 2, 'the applied plan page')+ expect(applied.pages).toHaveLength(2)+ const newTexts = applied.pages[1].elements.filter((e) => e.type === 'text').map((e) => e.text)+ expect(newTexts).toContain('Trattoria da Enzo')+ expect(newTexts).not.toContain('Trattoria da Luca')+ // the applied page carries the plan's gradient background+ expect(applied.pages[1].elements.some((e) => e.type === 'rect')).toBe(true)+ })++ test('speaker notes: AI draft is reviewed, edited, then saved per page', async ({ page }) => {+ await register(page, 'notes')+ // two pages — the mocked draft covers both+ const res = await page.request.post('/api/designs', {+ data: {+ name: 'w4 notes',+ width: 1080,+ height: 720,+ pages: [+ {+ id: 'p1',+ background: { type: 'solid', color: '#FFFFFF' },+ elements: [+ textEl({ text: 'Quarterly Results', fontSize: 72 }),+ textEl({ id: 'w4_text2', text: 'Revenue up 24% YoY', y: 220, fontSize: 28, bold: false }),+ ],+ },+ {+ id: 'p2',+ background: { type: 'solid', color: '#FFFFFF' },+ elements: [textEl({ id: 'w4_text3', text: 'Antipasti board', fontSize: 56 })],+ },+ ],+ },+ })+ expect(res.status()).toBeLessThan(300)+ const designId = ((await res.json()) as { id: string }).id+ await openEditor(page, designId)++ await page.route('**/api/ai/notes', (route) => route.fulfill({ json: MOCK_NOTES }))++ // open the notes popover on the page bar (exact — the present button+ // is named "Present with speaker notes")+ await page.getByRole('button', { name: 'Speaker notes', exact: true }).click()+ await expect(page.getByTestId('notes-popover')).toBeVisible()+ await page.getByTestId('notes-ai-generate').click()++ // the review dialog shows BOTH pages' drafts, editable+ const dialog = page.getByRole('dialog')+ await expect(dialog).toBeVisible({ timeout: 15_000 })+ const page2box = dialog.locator('textarea[aria-label="Notes for page 2"]')+ await page2box.fill('Walk the board left to right; land the margin story.')++ await dialog.getByRole('button', { name: 'Apply to pages' }).click()+ await expect(dialog).toBeHidden()++ // document truth: each page's notes saved (page 1 verbatim, page 2 edited)+ await waitForDoc(page, designId, (d) => Boolean(d.pages[0]?.notes && d.pages[1]?.notes), 'saved speaker notes')+ const d = await doc(page, designId)+ expect(d.pages[0].notes).toContain('one number that matters')+ expect(d.pages[1].notes).toContain('margin story')+ })++ test('AI theme: palette preview applies design-wide with contrast guards', async ({ page }) => {+ await register(page, 'theme')+ const designId = await createDesign(page, 'w4 theme', [+ textEl({ text: 'Headline', fontSize: 72 }),+ textEl({ id: 'w4_body', text: 'Body copy here', y: 240, fontSize: 24, bold: false }),+ imageEl({ x: 120, y: 400 }),+ ])+ await openEditor(page, designId)++ await page.route('**/api/ai/theme', (route) => route.fulfill({ json: MOCK_THEME }))+ await openApp(page, 'AI theme')++ await page.getByLabel('Theme mood').fill('nordic calm, cool editorial')+ await page.getByRole('button', { name: 'Generate' }).click()++ // the preview: six role rows + the font pairing+ await expect(page.getByText('Nordic calm', { exact: true })).toBeVisible({ timeout: 15_000 })+ await expect(page.getByText('Montserrat + Inter')).toBeVisible()+ await expect(page.getByText('Background', { exact: true })).toBeVisible()++ await page.getByRole('button', { name: 'Apply theme' }).click()++ // document truth: background + text recolored, image untouched+ const applied = await waitForDoc(+ page,+ designId,+ (d) => (d.pages[0].elements as any[]).some((e) => e.fill === '#F5F7FA'),+ 'the applied theme'+ )+ const els = applied.pages[0].elements+ expect(els.find((e) => e.type === 'text' && e.fontSize === 72)?.fill).toBe('#F5F7FA') // heading ink+ expect(els.find((e) => e.type === 'text' && e.fontSize === 24)?.fill).toBe('#C3CCDA') // body inkSoft+ expect(els.find((e) => e.type === 'image')?.src).toContain('data:image/png;base64,') // untouched+ })++ test('local image tools: upscaler really enlarges; brush eraser + alt UI are wired', async ({ page }) => {+ await register(page, 'local')+ const designId = await createDesign(page, 'w4 local', [imageEl()])+ await openEditor(page, designId)++ // select the image through the Layers tab+ await selectViaLayers(page, 'wave4 image')++ // the three Wave-4 toolbar entries exist+ await expect(page.getByRole('button', { name: 'Upscale image' })).toBeVisible()+ await expect(page.getByRole('button', { name: 'Brush eraser' })).toBeVisible()+ await expect(page.getByRole('button', { name: 'Alt text' })).toBeVisible()++ // run the REAL local upscaler — 2x on the 8×8 red square+ await page.getByRole('button', { name: 'Upscale image' }).click()+ await page.getByRole('button', { name: /2× → 16px/ }).click()+ await page.getByRole('button', { name: /Upscale to 16×16/ }).click()+ await expect(page.getByText('Upscaled 2×', { exact: true })).toBeVisible({ timeout: 30_000 })++ // document truth: the element's natural size doubled (8 → 16)+ await waitForDoc(+ page,+ designId,+ (d) => (d.pages[0].elements as any[]).some((e) => e.type === 'image' && e.naturalWidth === 16),+ 'the upscaled image'+ )++ // the brush eraser dialog opens with a paintable surface+ await page.getByRole('button', { name: 'Brush eraser' }).click()+ const dlg = page.getByRole('dialog')+ await expect(dlg).toBeVisible()+ await expect(dlg.getByLabel('Erase brush area')).toBeVisible()+ await expect(dlg.getByRole('button', { name: 'Erase painted area' })).toBeDisabled() // nothing painted yet+ await dlg.getByRole('button', { name: 'Cancel' }).click()+ await expect(dlg).toBeHidden()+ })++ test('alt text: AI suggestion is editable and saved on the element', async ({ page }) => {+ await register(page, 'alt')+ const designId = await createDesign(page, 'w4 alt', [imageEl()])+ await openEditor(page, designId)++ await page.route('**/api/ai/alt-text', (route) =>+ route.fulfill({ json: { alt: 'A solid red square used as a color swatch.', decorative: false } })+ )++ await selectViaLayers(page, 'wave4 image')+ await page.getByRole('button', { name: 'Alt text' }).click()+ await expect(page.getByTestId('alt-text-input')).toBeVisible()++ await page.getByRole('button', { name: 'Generate' }).click()+ await expect(page.getByTestId('alt-text-input')).toHaveValue(/solid red square/, { timeout: 15_000 })++ // review-edit before saving+ await page.getByTestId('alt-text-input').fill('A red color swatch.')+ await page.getByRole('button', { name: 'Save' }).click()++ // document truth: alt saved on the image element+ await waitForDoc(+ page,+ designId,+ (d) => (d.pages[0].elements as any[]).some((e) => e.type === 'image' && e.alt === 'A red color swatch.'),+ 'the saved alt text'+ )+ })++ test('capabilities endpoint reports the Wave 4 feature set', async ({ page }) => {+ const res = await page.request.get('/api/ai/capabilities')+ expect(res.status()).toBe(200)+ const body = (await res.json()) as { capabilities: Record<string, boolean> }+ // locals are always on+ expect(body.capabilities.upscale).toBe(true)+ expect(body.capabilities.brushEraser).toBe(true)+ expect(body.capabilities.backgroundRemoval).toBe(true)+ // the provider-gated Wave 4 keys exist as booleans+ for (const key of ['agenticPlanning', 'notesGeneration', 'themeGeneration', 'altText', 'videoGeneration']) {+ expect(typeof body.capabilities[key]).toBe('boolean')+ }+ })+})