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.16.4): stock photos on Pexels/Pixabay keys — imageSearch AI slot retired (A4) (#44)
Ashiq Hussain Mircb4cc1dace5f
diff --git a/README.md b/README.mdindex 66fddcc..8d9902e 100644--- a/README.md+++ b/README.md@@ -261,6 +261,16 @@ is right here.`docs/GIF-EXPORT.md`); rides the same deterministic frame rendereras video export. GIFs are silent — the dialog says so before youclick+- **Stock photos** *(v0.16.4 A4)* — the Photos panel's search runs on+ the stock-provider keys (Pexels / Pixabay, the same free keys as the+ Videos rail — no key = the bundled library keeps working and the+ section says so). Until v0.16.4 this was an AI-model slot calling an+ `images/search` endpoint almost no OpenAI-compatible vendor serves —+ the standing 404 the admin Logs view was built to explain. Inserts+ download in the browser into your media library and carry **durable+ attribution** (creator, provider, license — shown at insert and on+ selection). Zero new dependencies; operator guide in+ `docs/STOCK-PHOTO.md`- **Stock videos** *(v0.15 R6)* — a provider-gated **Videos** rail:search Pexels and/or Pixabay with free self-hoster keys (no key =the tab hides itself, everything else works). Inserts download in@@ -723,8 +733,10 @@ 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,-photo search) activate when a provider is configured **on the server**:+(Magic Layers, Assistant, Magic Write, image generation/editing, translate)+activate when a provider is configured **on the server**. Stock photo+search is separate by design (v0.16.4): it runs on free stock-provider+keys, not on an AI provider — see `docs/STOCK-PHOTO.md`:Option A — environment variables (recommended for Vercel etc.):@@ -759,7 +771,8 @@ limited per IP and logs usage into the `AIUsage` table.| Color palettes, layout balancing | ✅ local (deterministic) || Magic Layers, AI Assistant, Magic Write | ⚙️ needs a server AI provider || AI image generation / eraser / enhance | ⚙️ needs a server AI provider |-| Translate, live photo search | ⚙️ needs a server AI provider |+| 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 |diff --git a/docs/ADMIN.md b/docs/ADMIN.mdindex 1fdf92b..43a9852 100644--- a/docs/ADMIN.md+++ b/docs/ADMIN.md@@ -1,4 +1,4 @@-# Admin console (v0.16 A1 · v0.16.2 A2 · v0.16.3 A3)+# Admin console (v0.16 A1 · v0.16.2 A2 · v0.16.3 A3 · v0.16.4 A4)> **TL;DR** — set `CANVIX_ADMIN_USERS="your-username"`, restart, sign in:> the shield icon on the dashboard opens `/admin`. Everything below is@@ -81,7 +81,16 @@ to a different provider + model:| `vision` | Magic Layers (image understanding) || `image` | text-to-image || `imageEdit` | Magic Eraser / Enhance |-| `imageSearch` | stock photo search |++**Photo search is not a slot anymore (v0.16.4 A4).** It rode the AI+table as `imageSearch` — an `images/search` endpoint almost no+OpenAI-compatible vendor serves, the standing 404 behind the A3+incident. It now runs on the free stock-provider keys+(`PEXELS_API_KEY` / `PIXABAY_API_KEY`, the same keys as the Videos+rail — see docs/STOCK-PHOTO.md); the AI & models page's banner+states whether they are set. Stored tables that still carry an+`imageSearch` slot are read fine — unknown slot keys are dropped on+read and disappear on the next save. No migration.A slot left on “— fall back —” ignores the table and walks the legacychain below. `/api/ai/capabilities` now probes **per slot**, so wiring@@ -135,8 +144,10 @@ lookup ignored env vars and broke every test since A1 (see D3).`/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 five capability slots (`text`,- `vision`, `image`, `imageEdit`, `imageSearch`) resolves to right now:+- **AI slot status** — what each of the four capability slots (`text`,+ `vision`, `image`, `imageEdit`) resolves to right now (v0.16.4 A4:+ `imageSearch` is retired — photo search runs on the stock keys,+ not on an AI slot):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 —@@ -153,10 +164,9 @@ without an SSH session. Two surfaces:The per-slot **Test** buttons on the AI & models page probe the realendpoint each slot uses (chat completion for text/vision, a realminimal generation for image, a deliberately image-less probe for-imageEdit — a 400-class rejection proves the endpoint exists — and a-one-result search for imageSearch). A 404 verdict states the fix:-chat-only providers cannot run image slots; pin them to a provider-that serves image endpoints.+imageEdit — a 400-class rejection proves the endpoint exists). A 404+verdict states the fix: chat-only providers cannot run image slots;+pin them to a provider that serves image endpoints.### Settings@@ -320,6 +330,18 @@ probes that provider; `model` overrides the model for the probe.and caps at 240 chars. The same string flows to AIUsage (`error`),the client 502 body (`detail`) and the console — no place shows araw provider body, and no place shows different truths.+- **D17 (A4) — photo search LEFT the AI provider table.** The+ `imageSearch` slot called an `images/search` route that almost no+ OpenAI-compatible vendor serves — a category error: stock photo+ retrieval is a library query with licensing, not a generative+ capability. It now rides the R6 stock-connector architecture+ (`src/lib/stock-photo.ts`, Pexels + Pixabay, the same two env keys+ as the Videos rail), with the same durable-credit acceptance and+ the same F2b gating. The admin table shrinks to four slots; stale+ stored `imageSearch` slot entries are dropped by validation on+ read (no migration); the `photoSearch` feature switch keeps its+ semantics against the new route; historical `search` AIUsage rows+ keep rendering in the Logs view. Recorded in docs/STOCK-PHOTO.md.- **D16 (A3) — slot tests probe real endpoints, classified by verdict.**A chat-only provider passing the old test while image generation404'd was the diagnostic gap; now a 404/405 verdict says "not@@ -341,6 +363,8 @@ CREATE TABLE "DailyActive" (… UNIQUE(day, actor));`npm run db:setup` applies it; nothing else changes. **A2 adds nomigration** — the multi-provider table is one more `AppConfig` row(`ai.providers`), and live traffic keeps no database state at all.+**A4 adds no migration either** — retiring the `imageSearch` slot is+pure code (stored slot entries are dropped by read-side validation).### `0010_ai_request_log` (v0.16.3 A3)diff --git a/docs/STOCK-PHOTO.md b/docs/STOCK-PHOTO.mdnew file mode 100644index 0000000..77dd12d--- /dev/null+++ b/docs/STOCK-PHOTO.md@@ -0,0 +1,143 @@+# Stock photo search — operator guide & decision record (v0.16.4 A4)++The Photos rail ships a bundled library (42 AI-generated photos)+that works with zero configuration. Its **search** section is+**provider-gated**: it answers only when the self-hoster+configures a key for at least one stock-photo provider, and says+so with an operator hint otherwise (the F2b fail-closed pattern).+No key = the bundled library keeps working, `POST+/api/stock-photo/search` answers `503 NO_PROVIDER`, and everything+else in the editor is untouched.++## Why photo search is NOT an AI feature (the A4 decision)++Until v0.16.4 photo search rode the AI provider table as its+fifth capability slot (`imageSearch`), calling an+`images/search` endpoint through the OpenAI-compatible SDK. That+was a mis-design, and the A3 incident proved it: **almost no+OpenAI-compatible vendor serves an `images/search` route**, so a+chat-only provider (or any standard provider) pinned to the slot+404s forever — "why is photo search broken" needed the A3 Logs+view to even diagnose. "Find me a photo of a coffee shop" is a+**library query against licensed stock catalogs**, not a+generative one:++- real photos with real licensing (free commercial use, creator+ attribution) — an AI "search" returns arbitrary web images with+ unknown rights (the old panel had to tell users "check photo+ licenses before commercial use");+- free quota, no AI billing — Pexels and Pixabay keys are free;+- the exact architecture already shipped for the Videos rail+ (v0.15 R6) — and **the same two keys activate both rails**.++The `imageSearch` slot is **retired**: the admin table has four+model slots (text / vision / image / imageEdit), the per-slot+probe and the Logs slot strip show four, and a stored table that+still carries an `imageSearch` slot entry is read fine — unknown+slot keys are dropped by validation on read and disappear on the+next save. No migration.++## Providers++| Provider | Env key | Where to get it | License |+|---|---|---|---|+| Pexels | `PEXELS_API_KEY` | https://www.pexels.com/api/ (free) | Pexels License |+| Pixabay | `PIXABAY_API_KEY` | https://pixabay.com/api/docs/ (free) | Pixabay Content License |++Optional base overrides exist for proxies and test rigs:+`PEXELS_API_BASE` (default `https://api.pexels.com`) and+`PIXABAY_API_BASE` (default `https://pixabay.com/api`) — the same+overrides the Videos rail uses.++```bash+# .env — either key activates photo search (and the Videos rail)+PEXELS_API_KEY=your-free-key+# PIXABAY_API_KEY=your-free-key+```++Both connectors are plain REST/JSON over `fetch`. **Zero new+runtime dependencies** (the house rule).++## How an insert works (and what it costs you)++1. The panel searches **server-side** (your key never reaches the+ browser; responses are cached in memory for 24 h per instance —+ Pixabay's request, Pexels gets it for free).+2. Clicking a tile downloads the chosen rendition **in the+ browser** (both provider CDNs answer `Access-Control-Allow-Origin:+ *` on GET — verified empirically).+3. The file rides the **existing chunked media store**: your+ quota (`CANVIX_UPLOAD_QUOTA_MB`), the per-file cap, sha256+ dedupe and the library listing all apply as for any upload.+ Dimensions are probed from the actual bytes+ (`createImageBitmap`), so the element behaves exactly like an+ uploaded image.+4. The preferred rendition is the largest at most 1920 px wide+ (Pexels `large2x` / Pixabay `fullHDURL` — the design-tool sweet+ spot; multi-megabyte originals are never the primary). If the+ store's cap rejects it or a download fails, the panel retries+ the **next smaller rendition** — the ladder the search route+ returns.++## Attribution model (the R6 acceptance, applied to photos)++Every result carries a sanitized credit block+`{ provider, author, license, url }`:++- **visible at insert** — the success toast names the provider,+ creator and license;+- **durable** — stored on the element (`ImageElement.credit`),+ so it rides autosave, version history, collab replication and+ the offline merge like any element field;+- **visible on selection** — the properties bar shows a credit+ chip (license + source page in the tooltip);+- **never on the canvas or burned into exports** — a forced+ overlay would corrupt the design, and neither license demands+ on-content credit. The provider chip on every search tile keeps+ "show users where the content comes from" satisfied.++Credit fields are capped and cleaned at ingest+(`src/lib/stock-photo.ts`): control characters stripped, lengths+hard-capped, source URLs must be http(s) — a `javascript:` URL+can never become a credit link.++## Admin surface++- The **AI & models** page shows four slots and a banner stating+ where photo search lives (the stock keys) and whether they are+ set — the operator is never sent hunting for a slot that no+ longer exists.+- The **photoSearch feature switch** still works: switched off,+ `/api/stock-photo/search` answers `503 FEATURE_DISABLED` — same+ semantics as every AI feature.+- `/api/ai/capabilities` reports `photoSearch` from the stock+ keys (not from an AI slot).+- Stock-photo searches are **not** AIUsage rows (they spend no AI+ provider quota); historical `search` rows from the retired slot+ keep rendering in the Logs view.++## Honest limits++- **CI never talks to a real provider.** The unit suite parses+ recorded response fixtures; the acceptance e2e+ (`playwright.stockvideo.config.ts` — the same provider-on suite+ as videos) runs against the local **mock provider**+ (`tests/stock-video/mock-provider.mjs`, which also serves the+ documented photo search shape) so the full search → download →+ upload → probe → credit path is exercised without spending+ quota. Live-provider drift is mitigated by defensive parsing+ (unknown keys ignored, every field validated), not by tests we+ can't run keyless.+- **The no-key states are covered by the default e2e suite**+ (`tests/e2e/stock-photo-gated.spec.ts`): availability false,+ 503 NO_PROVIDER with the hint, the Photos rail intact.+- **MCP cannot rewrite credits** — attribution integrity: an+ agent may move or restyle a stock photo but not strip its+ credit.+- Provider search failures surface as a sanitized status-only+ message (`Pexels search failed (429).`) — provider bodies and+ URLs never reach the client because Pixabay's key rides the+ query string.+- **Rate limit:** 20 searches/min/IP (`stockphoto:search` bucket)+ — beyond any typing session (the panel debounces at 600 ms),+ far below scripted drain velocity.diff --git a/package-lock.json b/package-lock.jsonindex f251b07..255f4e6 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "canvix",- "version": "0.16.3",+ "version": "0.16.4","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "canvix",- "version": "0.16.3",+ "version": "0.16.4","hasInstallScript": true,"dependencies": {"@imgly/background-removal": "^1.7.0",diff --git a/package.json b/package.jsonindex 8648745..ef2c209 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.16.3",+ "version": "0.16.4","private": false,"description": "Canvix \u2014 free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/src/app/api/admin/config/ai-test/route.ts b/src/app/api/admin/config/ai-test/route.tsindex 5d80b86..3327ccf 100644--- a/src/app/api/admin/config/ai-test/route.ts+++ b/src/app/api/admin/config/ai-test/route.ts@@ -25,7 +25,9 @@ export const dynamic = 'force-dynamic'// says OK but the feature is broken": a chat-only provider (NVIDIA NIM// et al.) passes every text test yet cannot serve image generation,// because it simply has no POST /v1/images/generations route. Body:-// { slot: "image" | "imageEdit" | "imageSearch" | "text" | "vision" }+// { slot: "image" | "imageEdit" | "text" | "vision" }+// (v0.16.4 A4: imageSearch is gone with the slot — photo search runs+// on the stock-provider keys, not on an AI provider.)//// text / vision → one minimal chat completion (the existing probe).// image → a REAL minimal generation — the only full proof;@@ -35,7 +37,6 @@ export const dynamic = 'force-dynamic'// no input image — a 400-class "must provide images"// answer PROVES the endpoint exists (zero cost); 404// means the provider cannot run this slot.-// imageSearch → one tiny search (count 1); 404 = not served.//// Verdicts classify the provider's answer so the console can say WHY,// not just "failed". The test always goes through the SDK constructor@@ -125,9 +126,9 @@ async function __canvix_post(req: NextRequest) {const slotProbe = typeof body.slot === 'string' ? body.slot.trim() : nullif (slotProbe) {if (!(slotProbe in SLOT_ENDPOINT)) {- return NextResponse.json({ ok: false, error: 'Unknown slot — use text, vision, image, imageEdit or imageSearch.' }, { status: 400 })+ return NextResponse.json({ ok: false, error: 'Unknown slot — use text, vision, image or imageEdit.' }, { status: 400 })}- const resolved = await resolveSlot(slotProbe as 'text' | 'vision' | 'image' | 'imageEdit' | 'imageSearch')+ const resolved = await resolveSlot(slotProbe as 'text' | 'vision' | 'image' | 'imageEdit')if (!resolved) {return NextResponse.json({ ok: false, error: `The ${slotProbe} slot has no provider — pin one on the AI & models page.` },diff --git a/src/app/api/admin/config/route.ts b/src/app/api/admin/config/route.tsindex 86e7e7e..9d06241 100644--- a/src/app/api/admin/config/route.ts+++ b/src/app/api/admin/config/route.ts@@ -25,6 +25,7 @@ import {type AiSlot,} from '@/lib/admin/config'import { resolveProvider, resolveSlot, type ResolvedSlot } from '@/lib/ai/provider'+import { stockPhotoProviders } from '@/lib/stock-photo'import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'import { withLogging } from '@/lib/observability'@@ -45,7 +46,9 @@ export const dynamic = 'force-dynamic'// importLegacyProvider: true — fold the A1 single override into the// table and clear the legacy row-const SLOT_ORDER: AiSlot[] = ['text', 'vision', 'image', 'imageEdit', 'imageSearch']+// v0.16.4 (A4): imageSearch is retired — four model slots remain;+// photo search runs on the stock-provider keys (surfaced below)+const SLOT_ORDER: AiSlot[] = ['text', 'vision', 'image', 'imageEdit']function slotView(resolved: ResolvedSlot | null) {if (!resolved) return null@@ -98,6 +101,13 @@ async function sanitizedView() {models,features,settings,+ // v0.16.4 (A4): photo search left the AI table — the console shows+ // where it lives now (stock keys, shared with the Videos rail) and+ // whether those keys are set. Secret-free: names only, never keys.+ stockPhotos: {+ available: stockPhotoProviders().length > 0,+ providers: stockPhotoProviders(),+ },}}diff --git a/src/app/api/admin/logs/route.ts b/src/app/api/admin/logs/route.tsindex 61e946b..025d987 100644--- a/src/app/api/admin/logs/route.ts+++ b/src/app/api/admin/logs/route.ts@@ -10,7 +10,7 @@ export const dynamic = 'force-dynamic'// GET /api/admin/logs — the console's Logs view (v0.16.3 A3).//// Two payloads in one response:-// slots — what each of the five capability slots currently resolves+// slots — what each of the four capability slots currently resolves// to (provider label, base URL, model, config source) or// null when unconfigured. Never the key — resolveSlot's// apiKey is dropped before serialization.@@ -24,7 +24,10 @@ export const dynamic = 'force-dynamic'// poll itself is a plain admin GET, excluded from nothing — it is// cheap (indexed createdAt range + groupBy) and admin-only.-const SLOT_ORDER = ['text', 'vision', 'image', 'imageEdit', 'imageSearch'] as const+// v0.16.4 (A4): imageSearch is retired — photo search runs on the+// stock-provider keys, not on an AI slot (its searches are not AIUsage+// rows; historical 'search' rows keep rendering in the log below)+const SLOT_ORDER = ['text', 'vision', 'image', 'imageEdit'] as constasync function __canvix_get(req: NextRequest) {const guard = await requireAdmin(req)diff --git a/src/app/api/ai/capabilities/route.ts b/src/app/api/ai/capabilities/route.tsindex 030848b..8646b44 100644--- a/src/app/api/ai/capabilities/route.ts+++ b/src/app/api/ai/capabilities/route.ts@@ -1,5 +1,6 @@import { NextResponse } from 'next/server'import { hasProviderForSlot } from '@/lib/ai/provider'+import { stockPhotoAvailable } from '@/lib/stock-photo'import { getFeatures } from '@/lib/admin/config'import { withLogging } from '@/lib/observability'@@ -19,14 +20,16 @@ async function __canvix_get() {// table you can wire text to one vendor and images to another, so// "a provider exists" is no longer a single boolean. Still booleans// only — never config, never keys, never which layer answered.- const [text, vision, image, imageEdit, imageSearch] = await Promise.all([+ // 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([hasProviderForSlot('text'),hasProviderForSlot('vision'),hasProviderForSlot('image'),hasProviderForSlot('imageEdit'),- hasProviderForSlot('imageSearch'),+ Promise.resolve(stockPhotoAvailable()),])- const configured = text || vision || image || imageEdit || imageSearch+ const configured = text || vision || image || imageEditconst flags = await getFeatures()return NextResponse.json({configured,@@ -37,7 +40,7 @@ async function __canvix_get() {vision: vision && flags.vision, // Magic Layerstranslation: text && flags.translation,assistant: text && flags.assistant,- photoSearch: imageSearch && flags.photoSearch,+ photoSearch: stockPhotos && flags.photoSearch, // stock keys, not a model slotbackgroundRemoval: true, // local ONNX — always availablecolorPalette: true, // local deterministiclayoutSuggestions: true, // local deterministicdiff --git a/src/app/api/photos/search/route.ts b/src/app/api/photos/search/route.tsdeleted file mode 100644index a94b805..0000000--- a/src/app/api/photos/search/route.ts+++ /dev/null@@ -1,37 +0,0 @@-import { NextRequest, NextResponse } from 'next/server'-import { withProvider } from '@/lib/ai/provider'-import { withLogging } from '@/lib/observability'--export const runtime = 'nodejs'-export const maxDuration = 30--interface SearchBody {- query?: string- count?: number-}--/** POST /api/photos/search — runtime stock-photo search (Canva-like photo search). */-async function __canvix_post(req: NextRequest) {- const body = (await req.json().catch(() => ({}))) as SearchBody- const query = (body.query ?? '').trim().slice(0, 120)- if (!query) return NextResponse.json({ error: 'A query is required.' }, { status: 400 })- const count = Math.min(Math.max(Number(body.count) || 24, 1), 40)-- return withProvider('search', req, { limit: 12, windowSec: 60 }, async (ctx) => {- const response = await ctx.zai.images.search.create({ query, count })-- const results = (response.results ?? []).map((r) => ({- url: r.original_url,- caption: r.caption ?? '',- source: r.source ?? '',- width: Number(r.original_width) || 0,- height: Number(r.original_height) || 0,- })).filter((r) => r.url)-- return NextResponse.json({ query, count: results.length, results })- })-}--// 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/photos/search', __canvix_post)diff --git a/src/app/api/stock-photo/available/route.ts b/src/app/api/stock-photo/available/route.tsnew file mode 100644index 0000000..d56eea4--- /dev/null+++ b/src/app/api/stock-photo/available/route.ts@@ -0,0 +1,24 @@+import { NextResponse } from 'next/server'+import { stockPhotoProviders } from '@/lib/stock-photo'+import { withLogging } from '@/lib/observability'++export const runtime = 'nodejs'+export const dynamic = 'force-dynamic'++/**+ * GET /api/stock-photo/available — public, secret-free feature+ * detection for the Photos panel's web-search section (v0.16.4+ * A4, the F2b pattern): the panel queries this to know whether+ * stock photo search is keyed before the first search runs.+ * Exposes WHICH connectors are keyed, never the keys themselves.+ */+async function __canvix_get() {+ return NextResponse.json({+ available: stockPhotoProviders().length > 0,+ providers: stockPhotoProviders(),+ })+}++// v0.12.5 (H7): opt-in request logging wrapper — passthrough+// unless CANVIX_LOG=requests (see src/lib/observability.ts)+export const GET = withLogging('GET /api/stock-photo/available', __canvix_get)diff --git a/src/app/api/stock-photo/search/route.test.ts b/src/app/api/stock-photo/search/route.test.tsnew file mode 100644index 0000000..a48b7b9--- /dev/null+++ b/src/app/api/stock-photo/search/route.test.ts@@ -0,0 +1,177 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++// Route tests for the v0.16.4 A4 stock-photo API. No network, no+// Postgres. Invariants:+// 1. no provider key → 503 NO_PROVIDER (the F2b gate)+// 2. available is secret-free and never leaks the keys+// 3. CSRF on the search POST+// 4. unknown/unconfigured provider → 400+// 5. the happy path proxies the normalized result set++import { NextRequest } from 'next/server'+import { GET as getAvailable } from '../available/route'+import { POST as searchPhotos } from './route'+import { resetStockPhotoCache } from '@/lib/stock-photo'+import { resetRateLimitState } from '@/lib/rate-limit'++function req(url: string, init?: Omit<RequestInit, 'signal' | 'headers'> & { headers?: Record<string, string> }) {+ return new NextRequest(url, {+ ...init,+ headers: { host: 'canvix.test', ...(init?.headers ?? {}) },+ })+}++const PEXELS_FIXTURE = {+ photos: [+ {+ id: 42,+ width: 4000,+ height: 2667,+ url: 'https://www.pexels.com/photo/route-test-42/',+ photographer: 'Route Tester',+ src: {+ original: 'https://images.pexels.com/route-42-original.jpeg',+ large2x: 'https://images.pexels.com/route-42-large2x.jpeg',+ large: 'https://images.pexels.com/route-42-large.jpeg',+ medium: 'https://images.pexels.com/route-42-medium.jpeg',+ },+ },+ ],+}++beforeEach(() => {+ vi.unstubAllEnvs()+ vi.stubEnv('PEXELS_API_KEY', 'route-test-key')+ delete process.env.PEXELS_API_BASE+ delete process.env.PIXABAY_API_KEY+ resetStockPhotoCache()+ resetRateLimitState()+})++afterEach(() => {+ vi.unstubAllEnvs()+ vi.restoreAllMocks()+ resetRateLimitState()+})++describe('GET /api/stock-photo/available', () => {+ it('no keys → available=false, empty providers, no secrets', async () => {+ vi.stubEnv('PEXELS_API_KEY', '')+ const res = await getAvailable(req('http://canvix.test/api/stock-photo/available'))+ expect(res.status).toBe(200)+ const body = (await res.json()) as { available: boolean; providers: string[] }+ expect(body).toEqual({ available: false, providers: [] })+ })++ it('a key flips availability and names only the provider', async () => {+ const res = await getAvailable(req('http://canvix.test/api/stock-photo/available'))+ const body = (await res.json()) as { available: boolean; providers: string[] }+ expect(body).toEqual({ available: true, providers: ['pexels'] })+ expect(JSON.stringify(body)).not.toContain('route-test-key')+ })+})++describe('POST /api/stock-photo/search', () => {+ it('no provider key → 503 NO_PROVIDER with the operator hint', async () => {+ vi.stubEnv('PEXELS_API_KEY', '')+ const res = await searchPhotos(+ req('http://canvix.test/api/stock-photo/search', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ query: 'ocean' }),+ }),+ )+ expect(res.status).toBe(503)+ const body = (await res.json()) as { code?: string; hint?: string }+ expect(body.code).toBe('NO_PROVIDER')+ expect(body.hint).toContain('PEXELS_API_KEY')+ })++ it('cross-site Origin → 403 CSRF_REJECTED', async () => {+ const res = await searchPhotos(+ req('http://canvix.test/api/stock-photo/search', {+ method: 'POST',+ headers: { 'content-type': 'application/json', origin: 'https://evil.example' },+ body: JSON.stringify({ query: 'ocean' }),+ }),+ )+ expect(res.status).toBe(403)+ const body = (await res.json()) as { code?: string }+ expect(body.code).toBe('CSRF_REJECTED')+ })++ it('missing/blank query → 400', async () => {+ for (const query of ['', ' ', undefined]) {+ const res = await searchPhotos(+ req('http://canvix.test/api/stock-photo/search', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ query }),+ }),+ )+ expect(res.status).toBe(400)+ }+ })++ it('unconfigured provider → 400 naming the configured set', async () => {+ const res = await searchPhotos(+ req('http://canvix.test/api/stock-photo/search', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ query: 'ocean', provider: 'pixabay' }),+ }),+ )+ expect(res.status).toBe(400)+ const body = (await res.json()) as { error?: string }+ expect(body.error).toContain('pexels')+ })++ it('happy path → 200 with the normalized results, key never in the response', async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify(PEXELS_FIXTURE), { status: 200, headers: { 'content-type': 'application/json' } }),+ )+ vi.stubGlobal('fetch', fetchMock)++ const res = await searchPhotos(+ req('http://canvix.test/api/stock-photo/search', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ query: 'ocean', count: 12 }),+ }),+ )+ expect(res.status).toBe(200)+ const body = (await res.json()) as {+ query: string+ count: number+ results: { id: string; download: string; credit: { author: string } }[]+ }+ expect(body.query).toBe('ocean')+ expect(body.count).toBe(1)+ expect(body.results[0].id).toBe('pexels-42')+ expect(body.results[0].download).toBe('https://images.pexels.com/route-42-large2x.jpeg')+ expect(body.results[0].credit.author).toBe('Route Tester')+ expect(JSON.stringify(body)).not.toContain('route-test-key')+ // the outbound provider call carried the key in the header+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]+ expect(url).toContain('per_page=12')+ expect((init.headers as Record<string, string>).Authorization).toBe('route-test-key')+ })++ it('provider outage → 502 with the sanitized status-only message', async () => {+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('boom key=secret', { status: 500 })))++ const res = await searchPhotos(+ req('http://canvix.test/api/stock-photo/search', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ query: 'ocean' }),+ }),+ )+ expect(res.status).toBe(502)+ const body = (await res.json()) as { error?: string }+ expect(body.error).toBe('Pexels search failed (500).')+ expect(body.error).not.toContain('secret')+ expect(spy).toHaveBeenCalled()+ })+})diff --git a/src/app/api/stock-photo/search/route.ts b/src/app/api/stock-photo/search/route.tsnew file mode 100644index 0000000..1a064ec--- /dev/null+++ b/src/app/api/stock-photo/search/route.ts@@ -0,0 +1,83 @@+import { NextRequest, NextResponse } from 'next/server'+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'+import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'+import { aiFeatureEnabled } from '@/lib/admin/config'+import { FEATURE_DISABLED } from '@/lib/ai/provider'+import { searchStockPhotos, stockPhotoProviders, type StockPhotoProvider } from '@/lib/stock-photo'+import { withLogging } from '@/lib/observability'++export const runtime = 'nodejs'+export const maxDuration = 30++interface SearchBody {+ query?: unknown+ count?: unknown+ provider?: unknown+}++/**+ * POST /api/stock-photo/search — runtime stock-photo search+ * (v0.16.4 A4). Photo search LEFT the AI provider table: it is a+ * library query against licensed stock catalogs (Pexels/Pixabay),+ * not a generative one, so it rides the R6 self-hoster-key+ * architecture instead of an OpenAI-compatible model slot.+ * Provider-gated the F2b way: no key configured ⇒ 503+ * NO_PROVIDER and the panel shows the operator hint. The response+ * is the normalized, sanitized result set — provider URLs ++ * durable credit blocks; keys never leave the server (and+ * provider error bodies never reach the client).+ */+async function __canvix_post(req: NextRequest) {+ // stock search spends provider quota on every call — same-origin+ // only, like every other mutating POST (fail-closed default)+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })+ // the admin photoSearch kill switch still applies (same semantics+ // as every AI feature: switched off ⇒ 503, everywhere)+ if (!(await aiFeatureEnabled('photoSearch'))) {+ return NextResponse.json(FEATURE_DISABLED, { status: 503 })+ }+ const limit = checkRateLimit(req, 'stockphoto:search')+ if (!limit.ok) return rateLimitResponse(limit)++ const providers = stockPhotoProviders()+ if (providers.length === 0) {+ return NextResponse.json(+ {+ error: 'Photo search needs a stock provider key on the server.',+ code: 'NO_PROVIDER',+ hint: 'Set PEXELS_API_KEY or PIXABAY_API_KEY — free keys from each provider (docs/STOCK-PHOTO.md). The same keys also enable the Videos rail.',+ },+ { status: 503 },+ )+ }++ const body = (await req.json().catch(() => ({}))) as SearchBody+ const query = typeof body.query === 'string' ? body.query.trim().slice(0, 120) : ''+ if (!query) return NextResponse.json({ error: 'A query is required.' }, { status: 400 })+ const count = Math.min(Math.max(Number(body.count) || 24, 1), 40)++ let provider: StockPhotoProvider | undefined+ if (body.provider !== undefined) {+ if (typeof body.provider !== 'string' || !providers.includes(body.provider as StockPhotoProvider)) {+ return NextResponse.json(+ { error: `Unknown or unconfigured provider. Configured: ${providers.join(', ')}.` },+ { status: 400 },+ )+ }+ provider = body.provider as StockPhotoProvider+ }++ try {+ const results = await searchStockPhotos(query, count, provider ? { provider } : {})+ return NextResponse.json({ query, count: results.length, results })+ } catch (error) {+ // sanitized upstream (status-only messages); NEVER echo provider+ // bodies or URLs — pixabay's key rides the query string+ const message = error instanceof Error && error.message !== 'NO_PROVIDER' ? error.message : 'Photo search failed.'+ return NextResponse.json({ error: message }, { status: 502 })+ }+}++// 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/stock-photo/search', __canvix_post)diff --git a/src/components/admin/ai-config.tsx b/src/components/admin/ai-config.tsxindex b15e232..aa4bcc1 100644--- a/src/components/admin/ai-config.tsx+++ b/src/components/admin/ai-config.tsx@@ -7,8 +7,9 @@// endpoint (NVIDIA NIM, OpenRouter, Z.ai, Groq, …), one key each,// write-only credentials, per-provider Test button.// 2. Model slots — pin each capability (text / vision / image /-// imageEdit / imageSearch) to a provider + model id, so different-// features can run on different vendors.+// imageEdit) to a provider + model id, so different features can+// run on different vendors. (v0.16.4 A4: imageSearch is retired —+// photo search runs on the stock-provider keys, see the banner.)// 3. Legacy fallback — the v0.16 A1 single-provider override and model// ids, used only by slots that don't resolve through the table.// 4. Feature kill switches.@@ -52,6 +53,8 @@ interface ConfigView {models: { text?: string; vision?: string; image?: string }features: Record<string, boolean>settings: { signupsOpen: boolean; anonymousEditing: boolean }+ /** v0.16.4 (A4): where photo search lives now (stock keys) */+ stockPhotos: { available: boolean; providers: string[] }}/** Local editing state for one provider row. New rows get a client-generated@@ -74,7 +77,6 @@ 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' },- { key: 'imageSearch', label: 'Photo search', hint: 'Stock photo search', placeholder: 'provider default' },]const FEATURE_INFO: { key: string; label: string; hint: string }[] = [@@ -84,7 +86,7 @@ const FEATURE_INFO: { key: string; label: string; hint: string }[] = [{ key: 'vision', label: 'Magic Layers', hint: 'Image understanding that rebuilds layered designs' },{ 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' },+ { key: 'photoSearch', label: 'Photo search', hint: 'Stock photo search in the Photos panel — Pexels/Pixabay keys, not an AI provider' },]const SOURCE_LABEL: Record<string, string> = {@@ -115,7 +117,6 @@ const SLOT_ENDPOINT: Record<string, string> = {vision: 'chat/completions',image: 'images/generations',imageEdit: 'images/generations/edit',- imageSearch: 'images/search',}export function AdminAiConfig() {@@ -398,7 +399,7 @@ export function AdminAiConfig() {title="Model slots"right={<Chip tone={Object.values(view.providers.resolved).some((r) => r !== null) ? 'good' : 'neutral'}>- {Object.values(view.providers.resolved).filter((r) => r !== null).length}/5 wired+ {Object.values(view.providers.resolved).filter((r) => r !== null).length}/4 wired</Chip>}>@@ -406,6 +407,24 @@ export function AdminAiConfig() {Pin each capability to a provider and model. A slot with no provider falls back to the legacy chain below —every feature can run on a different vendor.</p>+ {/* v0.16.4 (A4): photo search LEFT the AI table — it runs on the+ free stock-provider keys (same keys as the Videos rail), not on+ a model slot. State where it lives and whether the keys are set,+ so the operator is never sent hunting for a slot that no longer+ exists. */}+ <div className="mb-4 rounded-xl border border-cyan-500/30 bg-cyan-500/10 p-3 text-sm">+ <p>+ Photo search is no longer a model slot — it runs on free stock-provider keys (Pexels / Pixabay), the same+ keys as the Videos rail:{' '}+ <code className="rounded bg-muted px-1">PEXELS_API_KEY</code> /{' '}+ <code className="rounded bg-muted px-1">PIXABAY_API_KEY</code> (docs/STOCK-PHOTO.md).+ </p>+ <p className="mt-1 text-xs text-muted-foreground">+ {view.stockPhotos.available+ ? `Active — keyed: ${view.stockPhotos.providers.join(', ')}.`+ : 'No stock key set — the Photos panel keeps only its bundled library.'}+ </p>+ </div><div className="space-y-3">{SLOT_INFO.map((s) => {const resolved = view.providers.resolved[s.key]diff --git a/src/components/admin/logs.tsx b/src/components/admin/logs.tsxindex d87a170..384e48d 100644--- a/src/components/admin/logs.tsx+++ b/src/components/admin/logs.tsx@@ -58,14 +58,12 @@ const SLOT_LABEL: Record<string, string> = {vision: 'Vision',image: 'Image generation',imageEdit: 'Image editing',- imageSearch: 'Photo search',}const SLOT_FEATURES: Record<string, string> = {text: 'Magic Write · Translate · Assistant',vision: 'Magic Layers',image: 'Photos panel → Generate',imageEdit: 'Magic Eraser · Enhance · BG remove',- imageSearch: 'Photos panel → Search',}const SOURCE_LABEL: Record<string, string> = {multi: 'providers table',@@ -74,6 +72,8 @@ const SOURCE_LABEL: Record<string, string> = {file: '.z-ai-config file',}const WINDOWS = ['15m', '1h', '6h', '24h', '7d'] as const+// 'search' stays for HISTORICAL rows (the retired imageSearch slot,+// v0.16.4 A4 — stock-photo searches are not AIUsage rows)const FEATURES = ['assistant', 'write', 'translate', 'image', 'image-edit', 'magic-layers', 'search'] as constfunction fmtTime(iso: string): string {diff --git a/src/components/editor/PropertiesBar.tsx b/src/components/editor/PropertiesBar.tsxindex 300774b..fcc1160 100644--- a/src/components/editor/PropertiesBar.tsx+++ b/src/components/editor/PropertiesBar.tsx@@ -376,6 +376,20 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'monCommit={() => update(ids, { opacity: image.opacity })}format={(v) => `${100 - v}% transparent`} /></ToolbarPopover>+ {/* v0.16.4 (A4): durable stock-photo attribution — same pattern+ as the R6 video credit. User uploads show nothing. */}+ {image.credit ? (+ <a+ href={image.credit.url || undefined}+ target="_blank"+ rel="noreferrer"+ className="text-[11px] font-semibold text-[#02C0CC] bg-[#02C0CC]/10 border border-[#02C0CC]/25 rounded-full px-2 py-0.5 shrink-0 max-w-[190px] truncate"+ title={`${image.credit.license}${image.credit.url ? ` — ${image.credit.url}` : ''}`}+ aria-label={`Stock photo by ${image.credit.author} on ${image.credit.provider}`}+ >+ {image.credit.provider} · {image.credit.author}+ </a>+ ) : null}<Divider /><PositionPopover ids={ids} count={1} element={first} /></>diff --git a/src/components/editor/add-element.ts b/src/components/editor/add-element.tsindex 8c5b909..f24c9e8 100644--- a/src/components/editor/add-element.ts+++ b/src/components/editor/add-element.ts@@ -541,3 +541,70 @@ export async function addStockVideo(}throw firstError instanceof Error ? firstError : new Error('Could not add the stock video.')}++/** v0.16.4 (A4): insert a stock PHOTO from the Photos panel's search+ * (Pexels/Pixabay). The addStockVideo pattern one class over: download+ * the preferred rendition in the browser (provider CDNs are CORS-open),+ * ride the existing chunked media store (quota, sha256 dedupe, size cap+ * all apply), probe the REAL dimensions from the bytes, and store the+ * durable credit on the element. The alternates ladder retries smaller+ * renditions when the store's cap rejects the primary. */+export async function addStockPhoto(+ stock: {+ id: string+ download: string+ alternates: string[]+ width: number+ height: number+ credit: { provider: string; author: string; license: string; url: string }+ },+ onProgress?: (ratio: number) => void,+): Promise<void> {+ const { uploadMediaFile, mediaSrc } = await import('@/lib/media/media-client')+ const { createImageElement } = await import('@/lib/types')++ let firstError: unknown = null+ for (const url of [stock.download, ...stock.alternates]) {+ try {+ const blob = await fetch(url).then((r) => {+ if (!r.ok) throw new Error(`Download failed (${r.status}).`)+ return r.blob()+ })+ // real dimensions from the actual bytes — provider metadata is a+ // hint, the blob is the truth (createImageBitmap, with a metadata+ // fallback for engines without it)+ let naturalW = stock.width || 1200+ let naturalH = stock.height || 800+ try {+ const bmp = await createImageBitmap(blob)+ naturalW = bmp.width || naturalW+ naturalH = bmp.height || naturalH+ bmp.close()+ } catch {+ /* keep the metadata dims */+ }+ const file = new File([blob], `${stock.id}.jpg`, { type: blob.type || 'image/jpeg' })+ const handle = await uploadMediaFile(file, onProgress)++ const store = useEditorStore.getState()+ const maxW = store.width * 0.7+ const maxH = store.height * 0.7+ const scale = Math.min(maxW / naturalW, maxH / naturalH, 1)+ const w = Math.round(naturalW * scale)+ const h = Math.round(naturalH * scale)+ const pos = placement(w, h, store.pages[store.currentPage].elements.length)+ store.addElement(+ createImageElement(mediaSrc(handle.id), naturalW, naturalH, {+ ...pos,+ width: w,+ height: h,+ credit: stock.credit,+ })+ )+ return+ } catch (err) {+ firstError ??= err+ }+ }+ throw firstError instanceof Error ? firstError : new Error('Could not add the stock photo.')+}diff --git a/src/components/editor/panels/PhotosPanel.tsx b/src/components/editor/panels/PhotosPanel.tsxindex b8cfa79..0b34ff7 100644--- a/src/components/editor/panels/PhotosPanel.tsx+++ b/src/components/editor/panels/PhotosPanel.tsx@@ -1,9 +1,30 @@'use client'+// ─────────────────────────────────────────────────────────────+// PhotosPanel — the Photos rail (v0.16.4 A4 rework of the web+// results section).+//+// Two content sources, honestly labelled:+// • STOCK SEARCH (typing ≥2 chars) — Pexels / Pixabay via+// /api/stock-photo/search, the R6 stock-video architecture:+// provider keys on the server, sanitized results, durable+// attribution on the inserted element. Until v0.16.4 this+// rode the AI provider table (the imageSearch slot) — an+// OpenAI-compatible images/search endpoint almost no vendor+// serves, which is why photo search 404'd in production.+// • THE BUNDLED LIBRARY — 42 AI-generated photos that ship+// with the app and work with zero configuration.+//+// The F2 lessons stay: leaving results mode clears BOTH the+// results and any error; a category click exits search mode;+// an unkeyed server says so instead of looking broken.+// ─────────────────────────────────────────────────────────────+import { useEffect, useMemo, useRef, useState } from 'react'-import { Plus, ImageDown, Loader2, Globe } from 'lucide-react'+import { Plus, ImageDown, Loader2, Camera } from 'lucide-react'import { PanelShell } from './panel-shell'-import { addImageFromSrc } from '../add-element'+import { addImageFromSrc, addStockPhoto } from '../add-element'+import { useStockPhoto } from '@/hooks/use-stock-photo'import { cn } from '@/lib/utils'import { toast } from '@/hooks/use-toast'@@ -14,18 +35,22 @@ interface StockPhoto {tags: string[]}-/** web search result — real photos from the z-ai image search service */-interface WebPhoto {- url: string- caption: string- source: string+/** normalized stock-search result — the /api/stock-photo/search shape */+interface StockPhotoTile {+ id: string+ provider: 'pexels' | 'pixabay'width: numberheight: number+ preview: string+ download: string+ alternates: string[]+ credit: { provider: string; author: string; license: string; url: string }}-/** v0.11.6 (F2): why a web search came back empty — surfaced in the panel- * so an unconfigured server says so instead of looking "broken" */-type WebError = { kind: 'no-provider' } | { kind: 'service'; message: string }+/** why a search came back empty — 'no-provider' shows the operator+ * hint instead of looking broken (the F2 pattern; defense in depth+ * under a section that already renders its unkeyed state) */+type SearchError = { kind: 'no-provider' } | { kind: 'service'; message: string }const CATEGORIES = [{ id: 'all', label: 'All photos' },@@ -55,69 +80,82 @@ for (const cat of Object.keys(TAGS)) {}}+function providerLabel(p: string): string {+ return p === 'pexels' ? 'Pexels' : p === 'pixabay' ? 'Pixabay' : p+}+export function PhotosPanel() {+ const { available, providers, loaded } = useStockPhoto()const [cat, setCat] = useState('all')const [query, setQuery] = useState('')// resilient to not-yet-bundled photos: broken tiles hide themselvesconst [hidden, setHidden] = useState<Record<string, boolean>>({})- // v0.4: live web search (debounced)- const [webResults, setWebResults] = useState<WebPhoto[] | null>(null)- const [webBusy, setWebBusy] = useState(false)- // v0.11.6 (F2): last search's failure mode, if any — 'no-provider' gets- // a configuration hint, anything else keeps the plain empty message- const [webError, setWebError] = useState<WebError | null>(null)+ // stock search (debounced) — only fires on a keyed instance+ const [results, setResults] = useState<StockPhotoTile[] | null>(null)+ const [busy, setBusy] = useState(false)+ const [error, setError] = useState<SearchError | null>(null)+ const [busyTile, setBusyTile] = useState<string | null>(null)+ const [provider, setProvider] = useState('')const lastQuery = useRef('')+ // default connector = the first configured one+ const activeProvider = provider || providers[0] || ''+ // a POSITIVE unkeyed answer (not "probe still in flight")+ const noProvider = loaded && !available+useEffect(() => {const q = query.trim()const run = async () => {- if (q.length < 2) {- // v0.11.6 (F2): leaving results mode must clear BOTH the results and- // any error — a stale hint next to the full library is exactly the- // sticky-state bug the QA pass reported- setWebResults(null)- setWebError(null)- return- }- setWebBusy(true)- setWebError(null)+ // the guards live in the debounce wrapper (the race note below);+ // run() only ever fires for a searcheable query on a keyed server+ setBusy(true)+ setError(null)try {- const res = await fetch('/api/photos/search', {+ const res = await fetch('/api/stock-photo/search', {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ query: q, count: 24 }),+ body: JSON.stringify({ query: q, count: 24, provider: activeProvider || undefined }),})const data = (await res.json().catch(() => ({}))) as {- results?: WebPhoto[]+ results?: StockPhotoTile[]error?: stringcode?: string}- // v0.11.6 (F2): 503 NO_PROVIDER means the server has no AI provider- // configured — say that, not "no photos matched"+ // 503 NO_PROVIDER means the server lost its keys since the+ // availability probe — say that, not "no photos matched"if (res.status === 503 && data.code === 'NO_PROVIDER') {- setWebError({ kind: 'no-provider' })- setWebResults([])+ setError({ kind: 'no-provider' })+ setResults([])} else if (!res.ok) {- setWebError(data.error ? { kind: 'service', message: data.error } : null)- setWebResults([])+ setError(data.error ? { kind: 'service', message: data.error } : null)+ setResults([])} else {- setWebResults(Array.isArray(data.results) ? data.results : [])+ setResults(Array.isArray(data.results) ? data.results : [])}} catch {- setWebResults([])+ setResults([])} finally {- setWebBusy(false)+ setBusy(false)}}const t = setTimeout(() => {- if (q !== lastQuery.current) {- lastQuery.current = q- void run()+ if (q === lastQuery.current) return+ // RACE GUARD (caught by the acceptance e2e): while availability is+ // still unresolved we must NOT consume the query — otherwise the+ // user types, run() returns early on !available, and when the probe+ // lands the effect re-runs but q === lastQuery forever. Only a real+ // search (or the <2-char clear) may consume it.+ if (q.length < 2 || !available) {+ setResults(null)+ setError(null)+ return}+ lastQuery.current = q+ void run()}, 600)return () => clearTimeout(t)- }, [query])+ }, [query, activeProvider, available])const photos = useMemo(() => {const q = query.trim().toLowerCase()@@ -136,103 +174,155 @@ export function PhotosPanel() {toast({ title: 'Photo added' })}- const addWeb = (p: WebPhoto) => {- const w = p.width || 1200- const h = p.height || 800- addImageFromSrc(p.url, w, h)- toast({ title: 'Photo added', description: p.source ? `From ${p.source}` : undefined })+ const addStock = async (tile: StockPhotoTile) => {+ if (busyTile) return+ setBusyTile(tile.id)+ try {+ await addStockPhoto(tile)+ toast({+ title: 'Photo added',+ description: `${tile.credit.provider} · ${tile.credit.author} — ${tile.credit.license}`,+ })+ } catch (err) {+ toast({+ title: 'Could not add the photo',+ description: err instanceof Error ? err.message : 'Try again — or pick another result.',+ })+ } finally {+ setBusyTile(null)+ }}- const showWeb = query.trim().length >= 2 && (webResults !== null || webBusy)+ const typing = query.trim().length >= 2+ const showWeb = typing && (results !== null || busy || noProvider)// v0.11.6 (F2): clicking a category tab EXITS results mode — clears the- // query (and with it the visible search box, now controlled), the web+ // query (and with it the visible search box, now controlled), the stock// results and any error. Before, the query kept filtering the bundled// grid, so "All photos" showed the stale 6-photo result set instead of// the 42-photo library until the panel was closed and reopened.- const pickCategory = (id: string) => {+ function pickCategory(id: string) {setCat(id)setQuery('')- setWebResults(null)- setWebError(null)+ setResults(null)+ setError(null)}+ // in results mode the provider row replaces the category row+ // (categories filter the bundled library; they mean nothing while+ // browsing stock results). Browsing mode keeps the categories.+ const belowSearch = showWeb && providers.length > 1 ? (+ <div className="cv-tabscroll -mx-4 mt-2.5 flex gap-1.5 overflow-x-auto px-4">+ {providers.map((p) => (+ <button+ key={p}+ onClick={() => {+ setProvider(p)+ setResults(null)+ setError(null)+ }}+ className={cn(+ 'h-7 shrink-0 whitespace-nowrap rounded-full px-3 text-[11.5px] font-semibold transition-colors border',+ activeProvider === p+ ? 'bg-white/[0.16] text-white border-white/25'+ : 'bg-transparent text-white/65 border-white/10 hover:bg-white/[0.07] hover:text-white',+ )}+ aria-pressed={activeProvider === p}+ >+ {providerLabel(p)}+ </button>+ ))}+ </div>+ ) : !showWeb ? (+ <div className="cv-tabscroll -mx-4 mt-2.5 flex gap-1.5 overflow-x-auto px-4">+ {CATEGORIES.map((c) => (+ <button+ key={c.id}+ onClick={() => pickCategory(c.id)}+ className={cn(+ 'h-7 shrink-0 whitespace-nowrap rounded-full px-3 text-[11.5px] font-semibold transition-colors border',+ cat === c.id+ ? 'bg-white/[0.16] text-white border-white/25'+ : 'bg-transparent text-white/65 border-white/10 hover:bg-white/[0.07] hover:text-white',+ )}+ aria-pressed={cat === c.id}+ >+ {c.label}+ </button>+ ))}+ </div>+ ) : undefined+return (<PanelShelltitle="Photos"- subtitle="Search millions of photos or browse the free library"+ subtitle="Search millions of stock photos or browse the free library"searchPlaceholder="Search photos (e.g. mountain, coffee, beach)"searchValue={query}onSearchValueChange={setQuery}onSearch={setQuery}- belowSearch={- <div className="cv-tabscroll -mx-4 mt-2.5 flex gap-1.5 overflow-x-auto px-4">- {CATEGORIES.map((c) => (- <button- key={c.id}- onClick={() => pickCategory(c.id)}- className={cn(- 'h-7 shrink-0 whitespace-nowrap rounded-full px-3 text-[11.5px] font-semibold transition-colors border',- cat === c.id- ? 'bg-white/[0.16] text-white border-white/25'- : 'bg-transparent text-white/65 border-white/10 hover:bg-white/[0.07] hover:text-white'- )}- aria-pressed={cat === c.id}- >- {c.label}- </button>- ))}- </div>- }+ belowSearch={belowSearch}>- {/* ── live web results (canva-style photo search) ── */}+ {/* ── stock search results (the R6 architecture) ── */}{showWeb && (<div className="mb-4"><div className="flex items-center gap-1.5 mb-2">- <Globe size={12} className="text-[#02C0CC]" />+ <Camera size={12} className="text-[#02C0CC]" /><span className="text-[10.5px] font-bold text-white/55 uppercase tracking-wide">- Web results {webResults ? `(${webResults.length})` : ''}+ Stock photos {results ? `(${results.length})` : ''}</span>- {webBusy && <Loader2 size={11} className="animate-spin text-white/40 ml-1" />}+ {busy && <Loader2 size={11} className="animate-spin text-white/40 ml-1" />}</div>- {webError?.kind === 'no-provider' ? (+ {noProvider || error?.kind === 'no-provider' ? (<p className="text-[11.5px] text-white/40 py-2 leading-relaxed">- Web search needs an AI provider configured on the server — set- the <code className="text-white/55">ZAI_BASE_URL</code> and{' '}- <code className="text-white/55">ZAI_API_KEY</code> environment- variables. The free library below still works.+ Photo search runs on free stock-provider keys — set{' '}+ <code className="text-white/55">PEXELS_API_KEY</code> or{' '}+ <code className="text-white/55">PIXABAY_API_KEY</code> on the server (the+ same keys as the Videos rail; see{' '}+ <code className="text-white/55">docs/STOCK-PHOTO.md</code>). The free+ library below still works.</p>- ) : webError?.kind === 'service' ? (- <p className="text-[11.5px] text-white/40 py-2">{webError.message}</p>- ) : webResults && webResults.length === 0 && !webBusy ? (- <p className="text-[11.5px] text-white/40 py-2">No web photos matched — try other keywords.</p>+ ) : error?.kind === 'service' ? (+ <p className="text-[11.5px] text-white/40 py-2">{error.message}</p>+ ) : results && results.length === 0 && !busy ? (+ <p className="text-[11.5px] text-white/40 py-2">No stock photos matched — try other keywords.</p>) : (<div className="grid grid-cols-2 gap-2.5">- {(webResults ?? []).map((p) => (- <button- key={p.url}- onClick={() => addWeb(p)}- className="group relative aspect-[7/5] rounded-xl overflow-hidden border border-white/10 hover:border-[#7630D7] transition-colors bg-[#0F1015]"- aria-label={`Add web photo ${p.caption || 'result'}`}- title={p.caption}- >- { }- <img- src={p.url}- alt={p.caption || 'web photo'}- loading="lazy"- className="absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-300"- />- <span className="absolute inset-0 bg-black/0 group-hover:bg-black/25 transition-colors" />- <span className="absolute inset-0 hidden group-hover:flex items-center justify-center">- <span className="h-8 px-3 rounded-full bg-[#7630D7] text-white text-[11.5px] font-bold flex items-center gap-1.5 shadow-lg">- <Plus size={12} /> Add+ {(results ?? []).map((t) => {+ const isBusy = busyTile === t.id+ return (+ <button+ key={t.id}+ onClick={() => void addStock(t)}+ disabled={busyTile !== null}+ className="group relative aspect-[7/5] rounded-xl overflow-hidden border border-white/10 hover:border-[#7630D7] transition-colors bg-[#0F1015] disabled:opacity-60"+ aria-label={`Add stock photo by ${t.credit.author}`}+ title={`${t.credit.provider} · ${t.credit.author} — ${t.credit.license}`}+ >+ <img+ src={t.preview}+ alt={`Stock photo by ${t.credit.author}`}+ loading="lazy"+ className="absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-300"+ />+ <span className="absolute inset-0 bg-black/0 group-hover:bg-black/25 transition-colors" />++ {/* provider chip (attribution visibility — the R6 pattern) */}+ <span className="absolute top-1.5 left-1.5 h-5 px-1.5 rounded-md bg-black/60 backdrop-blur-sm text-[9.5px] font-bold text-white/90 flex items-center">+ {t.credit.provider}</span>- </span>- </button>- ))}- {webBusy && Array.from({ length: 4 }).map((_, i) => (- <div key={i} className="aspect-[7/5] rounded-xl cv-skeleton" />++ <span className="absolute inset-0 hidden group-hover:flex items-center justify-center">+ <span className="h-8 px-3 rounded-full bg-[#7630D7] text-white text-[11.5px] font-bold flex items-center gap-1.5 shadow-lg">+ {isBusy ? <Loader2 size={12} className="animate-spin" /> : <Plus size={12} />}+ {isBusy ? 'Adding…' : 'Add'}+ </span>+ </span>+ </button>+ )+ })}+ {busy && Array.from({ length: 4 }).map((_, i) => (+ <div key={`sk-${i}`} className="aspect-[7/5] rounded-xl cv-skeleton" />))}</div>)}@@ -279,8 +369,10 @@ export function PhotosPanel() {)}<p className="text-[10.5px] text-white/30 mt-3 leading-relaxed">- Web results come from a live image search; bundled photos are AI-generated for Canvix. Check- photo licenses before commercial use of web results.+ Stock photos come from {providers.length > 0 ? providers.map(providerLabel).join(' and ') : 'the configured provider'} under+ their free licenses (Pexels License / Pixabay Content License) — inserted photos are downloaded+ into your media library and attribution stays on the element. Bundled photos are AI-generated+ for Canvix.</p></PanelShell>)diff --git a/src/hooks/use-stock-photo.ts b/src/hooks/use-stock-photo.tsnew file mode 100644index 0000000..25f75d6--- /dev/null+++ b/src/hooks/use-stock-photo.ts@@ -0,0 +1,60 @@+'use client'++// ─────────────────────────────────────────────────────────────+// use-stock-photo — client availability probe for the Photos+// panel's stock-search section (v0.16.4 A4, the F2b pattern —+// the use-stock-video twin).+//+// ONE request per editor mount, cached at module level. Fail-+// closed: any fetch/parse failure reads as "not available" —+// on a keyed instance a transient network error hides the+// web-results section until reload, never shows a broken panel.+// The bundled library never depends on this probe.+// ─────────────────────────────────────────────────────────────++import { useEffect, useState } from 'react'++export interface StockPhotoAvailability {+ available: boolean+ providers: string[]+}++const FALLBACK: StockPhotoAvailability = { available: false, providers: [] }++let inflight: Promise<StockPhotoAvailability> | null = null+let resolved: StockPhotoAvailability | null = null++function probe(): Promise<StockPhotoAvailability> {+ if (resolved) return Promise.resolve(resolved)+ inflight ??= fetch('/api/stock-photo/available')+ .then(async (res) => {+ if (!res.ok) return FALLBACK+ const body = (await res.json().catch(() => null)) as StockPhotoAvailability | null+ if (!body || typeof body.available !== 'boolean' || !Array.isArray(body.providers)) return FALLBACK+ resolved = body+ return body+ })+ .catch(() => FALLBACK)+ return inflight+}++/**+ * The stock-photo search state. `loaded` distinguishes "probe still+ * in flight" from "probe answered no" — the web-results section only+ * renders its unkeyed hint on a POSITIVE no (no flash on cold mounts).+ */+export function useStockPhoto(): StockPhotoAvailability & { loaded: boolean } {+ const [state, setState] = useState<StockPhotoAvailability>(resolved ?? FALLBACK)++ useEffect(() => {+ let alive = true+ void probe().then((v) => {+ if (alive) setState(v)+ })+ return () => {+ alive = false+ }+ }, [])++ return { ...state, loaded: state.available || resolved !== null }+}diff --git a/src/lib/admin/config.test.ts b/src/lib/admin/config.test.tsindex 1c8f810..2c16374 100644--- a/src/lib/admin/config.test.ts+++ b/src/lib/admin/config.test.ts@@ -316,7 +316,7 @@ 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(5) // all slots wired+ expect(Object.keys(out.value.slots)).toHaveLength(4) // all slots wired (imageSearch retired, v0.16.4 A4)}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 09948d6..e304843 100644--- a/src/lib/admin/config.ts+++ b/src/lib/admin/config.ts@@ -54,8 +54,16 @@ export const AI_FEATURES = [] as constexport type AiFeature = (typeof AI_FEATURES)[number]-/** Capability slots (v0.16.2 A2) — what a provider can be assigned to. */-export const AI_SLOTS = ['text', 'vision', 'image', 'imageEdit', 'imageSearch'] as const+/**+ * Capability slots (v0.16.2 A2) — what a provider can be assigned to.+ * v0.16.4 (A4): imageSearch is GONE — photo search is not a model+ * capability; it runs on the stock-provider keys (Pexels/Pixabay,+ * src/lib/stock-photo.ts), like the R6 stock-video rail. Stored+ * tables that still carry an imageSearch slot are read fine:+ * 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 constexport type AiSlot = (typeof AI_SLOTS)[number]export interface StoredProvider {@@ -452,7 +460,7 @@ export async function clearProviders(): Promise<void> {* • no legacy override stored → { ok: false } (the route answers 400)* • a provider with the same baseUrl already in the table → don't* duplicate, just clear the legacy row- * • table has no slots yet → point all five at the imported provider+ * • table has no slots yet → point every slot at the imported provider* (preserves the A1 behaviour where the override answered everything)*/export async function importLegacyProvider(): Promise<diff --git a/src/lib/ai/probe.test.ts b/src/lib/ai/probe.test.tsindex f2de18a..a9ebb76 100644--- a/src/lib/ai/probe.test.ts+++ b/src/lib/ai/probe.test.ts@@ -101,12 +101,6 @@ describe('probeSlot (A3)', () => {expect(out.verdict.message).toContain('reachable')})- it('imageSearch reports the result count', async () => {- const out = await probeSlot('imageSearch', TARGET)- expect(out.verdict.ok).toBe(true)- expect(out.verdict.message).toContain('1 result')- })-it('text slot goes through chat completions and returns the reply', async () => {const out = await probeSlot('text', TARGET)expect(out.verdict.ok).toBe(true)diff --git a/src/lib/ai/probe.ts b/src/lib/ai/probe.tsindex f53d38a..50f105b 100644--- a/src/lib/ai/probe.ts+++ b/src/lib/ai/probe.ts@@ -25,7 +25,6 @@ export const SLOT_ENDPOINT: Record<string, string> = {vision: 'POST {base}/chat/completions',image: 'POST {base}/images/generations',imageEdit: 'POST {base}/images/generations/edit',- imageSearch: 'POST {base}/images/search',}export interface ProbeVerdict {@@ -165,26 +164,9 @@ export async function probeSlot(slot: string, target: ProbeTarget): Promise<{ vereturn { verdict: classifyProbeError(slot, err) }}}- if (slot === 'imageSearch') {- try {- const r = await withTimeout(zai.images.search.create({ query: 'red circle', count: 1 }))- const n = (r as { results?: unknown[] }).results?.length ?? 0- return {- verdict: {- ok: true,- slot,- endpoint: SLOT_ENDPOINT.imageSearch,- httpStatus: 200,- message: n- ? `Search answered with ${n} result${n === 1 ? '' : 's'} — the full path works.`- : 'Search answered but returned no results.',- },- }- } catch (err) {- return { verdict: classifyProbeError(slot, err) }- }- }// text / vision — the existing minimal chat completion+ // (v0.16.4 A4: the imageSearch probe is gone with the slot — photo+ // search runs on the stock-provider keys, probed by its own rail)const completion = await withTimeout(zai.chat.completions.create({...(model ? { model } : {}),diff --git a/src/lib/ai/provider.ts b/src/lib/ai/provider.tsindex 0ce5340..77bd3d6 100644--- a/src/lib/ai/provider.ts+++ b/src/lib/ai/provider.ts@@ -34,7 +34,8 @@ export type AICapability =| 'image' // image generation| 'imageEdit' // Magic Eraser / Enhance| 'vision' // image understanding — Magic Layers- | 'imageSearch' // Photo search+// v0.16.4 (A4): imageSearch is retired — photo search runs on the+// stock-provider keys (src/lib/stock-photo.ts), not an AI model slotexport interface AIProviderConfig {baseUrl: string@@ -180,7 +181,6 @@ const FEATURE_SLOTS: Record<string, AiSlot> = {image: 'image','image-edit': 'imageEdit','magic-layers': 'vision',- search: 'imageSearch',}/** Async probe — does THIS slot have a provider behind it? */@@ -442,7 +442,6 @@ const FEATURE_FLAGS: Record<string, AiFeature> = {'magic-layers': 'vision',translate: 'translation',assistant: 'assistant',- search: 'photoSearch',}export const FEATURE_DISABLED = {diff --git a/src/lib/ai/slot-resolution.test.ts b/src/lib/ai/slot-resolution.test.tsindex 0119b27..f520ed5 100644--- a/src/lib/ai/slot-resolution.test.ts+++ b/src/lib/ai/slot-resolution.test.ts@@ -76,13 +76,15 @@ describe('pickSlot (v0.16.2 A2)', () => {expect(pickSlot('text', null, { baseUrl: 'https://x', apiKey: 'k' }, models, {}, null)?.model).toBe('gpt-x')expect(pickSlot('vision', null, { baseUrl: 'https://x', apiKey: 'k' }, models, {}, null)?.model).toBe('glm-4.5v')expect(pickSlot('image', null, { baseUrl: 'https://x', apiKey: 'k' }, models, {}, null)?.model).toBe('cogview-3')- // imageEdit / imageSearch never had legacy model ids — provider default+ // imageEdit never had a legacy model id — provider default+ // (v0.16.4 A4: imageSearch is retired — photo search runs on the+ // stock-provider keys, not on an AI slot)expect(pickSlot('imageEdit', null, { baseUrl: 'https://x', apiKey: 'k' }, models, {}, null)?.model).toBeUndefined()})it('nothing configured anywhere → null (feature reports unavailable)', () => {expect(pickSlot('text', null, null, {}, {}, null)).toBeNull()- expect(pickSlot('imageSearch', table({}), null, {}, {}, null)).toBeNull()+ expect(pickSlot('imageEdit', table({}), null, {}, {}, null)).toBeNull()})it('the multi table does NOT rescue other slots — only pinned ones', () => {diff --git a/src/lib/rate-limit.ts b/src/lib/rate-limit.tsindex 7a51a84..b28e351 100644--- a/src/lib/rate-limit.ts+++ b/src/lib/rate-limit.ts@@ -43,6 +43,8 @@ export type RateLimitBucket =| 'plugins:install'| 'plugins:serve'| 'stockvideo:search'+ | 'stockphoto:search'+ | 'stockphoto:search'export interface RateLimitConfig {/** window length in milliseconds */@@ -80,6 +82,10 @@ export const RATE_LIMITS: Record<RateLimitBucket, RateLimitConfig> = {// debounces at 600 ms and caches server-side for 24 h) while// stopping scripted drain of the self-hoster's key'stockvideo:search': { windowMs: 60_000, max: 20 },+ // v0.16.4 (A4): stock-photo search spends the same PROVIDER quota+ // — one shared bucket shape with the video rail (the panel also+ // debounces at 600 ms and caches server-side for 24 h)+ 'stockphoto:search': { windowMs: 60_000, max: 20 },}export function rateLimitsDisabled(): boolean {diff --git a/src/lib/stock-photo.test.ts b/src/lib/stock-photo.test.tsnew file mode 100644index 0000000..61377cb--- /dev/null+++ b/src/lib/stock-photo.test.ts@@ -0,0 +1,340 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import {+ choosePhotoRenditions,+ resetStockPhotoCache,+ searchStockPhotos,+ stockPhotoAvailable,+ stockPhotoProviders,+ type StockPhotoResult,+} from './stock-photo'++// ── recorded provider response shapes ─────────────────────────+// The Pexels Photo resource + the Pixabay photo hit, exactly as+// documented (fields verified against each provider's API docs;+// CI has no keys, so these fixtures are the parsing oracle).++const PEXELS_PHOTO = {+ id: 417173,+ width: 5472,+ height: 3648,+ url: 'https://www.pexels.com/photo/photo-of-coffee-shop-417173/',+ photographer: 'Nathan Dumlao',+ photographer_url: 'https://www.pexels.com/@nathan-dumlao-268298',+ photographer_id: 268298,+ avg_color: '#8C7B6B',+ alt: 'coffee shop interior',+ src: {+ original: 'https://images.pexels.com/photos/417173/pexels-photo-417173.jpeg?auto=compress&cs=tinysrgb&w=5472',+ large2x: 'https://images.pexels.com/photos/417173/pexels-photo-417173.jpeg?auto=compress&cs=tinysrgb&w=1880',+ large: 'https://images.pexels.com/photos/417173/pexels-photo-417173.jpeg?auto=compress&cs=tinysrgb&w=940',+ medium: 'https://images.pexels.com/photos/417173/pexels-photo-417173.jpeg?auto=compress&cs=tinysrgb&w=400',+ small: 'https://images.pexels.com/photos/417173/pexels-photo-417173.jpeg?auto=compress&cs=tinysrgb&w=200',+ portrait: 'https://images.pexels.com/photos/417173/pexels-photo-417173.jpeg?auto=compress&cs=tinysrgb&w=200&h=300',+ landscape: 'https://images.pexels.com/photos/417173/pexels-photo-417173.jpeg?auto=compress&cs=tinysrgb&w=200',+ tiny: 'https://images.pexels.com/photos/417173/pexels-photo-417173.jpeg?auto=compress&cs=tinysrgb&w=65',+ },+ liked: false,+}++const PEXELS_RESPONSE = {+ total_results: 1000,+ page: 1,+ per_page: 24,+ photos: [+ PEXELS_PHOTO,+ {+ // hostile/malformed: no src object at all — must be dropped, not crash+ id: 999,+ width: 100,+ height: 100,+ url: 'javascript:alert(1)',+ photographer: 'Nobody',+ },+ ],+}++const PIXABAY_HIT = {+ id: 1547301,+ pageURL: 'https://pixabay.com/photos/id-1547301/',+ type: 'photo',+ tags: 'mountain, alps, snow',+ previewURL: 'https://cdn.pixabay.com/photo/2016/08/01/22/34/alps-1562210_150.jpg',+ previewWidth: 150,+ previewHeight: 99,+ webformatURL: 'https://cdn.pixabay.com/photo/2016/08/01/22/34/alps-1562210_640.jpg',+ webformatWidth: 640,+ webformatHeight: 425,+ largeImageURL: 'https://cdn.pixabay.com/photo/2016/08/01/22/34/alps-1562210_1280.jpg',+ fullHDURL: 'https://cdn.pixabay.com/photo/2016/08/01/22/34/alps-1562210_1920.jpg',+ imageWidth: 4896,+ imageHeight: 3264,+ imageSize: 3240110,+ views: 4462,+ downloads: 1464,+ likes: 18,+ comments: 0,+ user_id: 1281706,+ user: 'alps-photographer',+}++const PIXABAY_RESPONSE = {+ total: 42,+ totalHits: 42,+ hits: [PIXABAY_HIT, 'garbage-entry'],+}++function jsonRes(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'Content-Type': 'application/json' },+ })+}++beforeEach(() => {+ resetStockPhotoCache()+ vi.stubEnv('PEXELS_API_KEY', 'test-pexels-key')+ vi.stubEnv('PIXABAY_API_KEY', 'test-pixabay-key')+ delete process.env.PEXELS_API_BASE+ delete process.env.PIXABAY_API_BASE+})++afterEach(() => {+ vi.unstubAllEnvs()+ vi.restoreAllMocks()+})++describe('availability — self-hoster keys gate the feature', () => {+ it('no keys → no providers, not available', () => {+ vi.stubEnv('PEXELS_API_KEY', '')+ vi.stubEnv('PIXABAY_API_KEY', '')+ expect(stockPhotoProviders()).toEqual([])+ expect(stockPhotoAvailable()).toBe(false)+ })++ it('either key enables its provider only', () => {+ vi.stubEnv('PIXABAY_API_KEY', '')+ expect(stockPhotoProviders()).toEqual(['pexels'])+ vi.stubEnv('PEXELS_API_KEY', '')+ vi.stubEnv('PIXABAY_API_KEY', 'k2')+ expect(stockPhotoProviders()).toEqual(['pixabay'])+ expect(stockPhotoAvailable()).toBe(true)+ })+})++describe('choosePhotoRenditions — the fallback ladder', () => {+ it('picks the largest ≤1920px URL, smaller ones as alternates', () => {+ const out = choosePhotoRenditions([+ { url: 'https://x/a.jpg', width: 4000 },+ { url: 'https://x/b.jpg', width: 1880 },+ { url: 'https://x/c.jpg', width: 940 },+ { url: 'https://x/d.jpg', width: 400 },+ ])+ expect(out).toEqual({ primary: 'https://x/b.jpg', alternates: ['https://x/c.jpg', 'https://x/d.jpg'] })+ })++ it('no ≤1920 candidate → the last resort becomes the primary', () => {+ const out = choosePhotoRenditions([{ url: 'https://x/a.jpg', width: 4000 }])+ expect(out).toEqual({ primary: 'https://x/a.jpg', alternates: [] })+ })++ it('dedupes by URL and rejects non-http(s)', () => {+ const out = choosePhotoRenditions([+ { url: 'javascript:alert(1)', width: 100 },+ { url: 'https://x/b.jpg', width: 940 },+ { url: 'https://x/b.jpg', width: 940 },+ ])+ expect(out).toEqual({ primary: 'https://x/b.jpg', alternates: [] })+ })++ it('empty → null', () => {+ expect(choosePhotoRenditions([])).toBeNull()+ expect(choosePhotoRenditions([{ url: 'javascript:alert(1)', width: 100 }])).toBeNull()+ })+})++describe('searchStockPhotos — pexels', () => {+ it('normalizes the documented response shape', async () => {+ const fetchImpl = vi.fn().mockResolvedValue(jsonRes(PEXELS_RESPONSE))+ const results = await searchStockPhotos('coffee shop', 24, { fetchImpl, noCache: true })+ expect(fetchImpl).toHaveBeenCalledOnce()+ const [url, init] = fetchImpl.mock.calls[0] as [string, RequestInit]+ expect(url).toContain('https://api.pexels.com/v1/search?')+ expect(url).toContain('query=')+ expect(url).toContain('per_page=24')+ expect(url).toContain('orientation=landscape')+ expect((init.headers as Record<string, string>).Authorization).toBe('test-pexels-key')++ expect(results).toHaveLength(1) // the malformed second entry is dropped+ const r: StockPhotoResult = results[0]+ expect(r.id).toBe('pexels-417173')+ expect(r.provider).toBe('pexels')+ expect(r.width).toBe(5472)+ expect(r.height).toBe(3648)+ // large2x is the design-tool sweet spot, original (5472px) is NOT the+ // primary; the fallback ladder is the SAME image at smaller sizes —+ // portrait/landscape (crops) and tiny (65px) are excluded by design+ expect(r.download).toBe(PEXELS_PHOTO.src.large2x)+ expect(r.alternates).toEqual([PEXELS_PHOTO.src.large, PEXELS_PHOTO.src.medium, PEXELS_PHOTO.src.small])+ expect(r.preview).toBe(PEXELS_PHOTO.src.medium)+ expect(r.credit).toEqual({+ provider: 'Pexels',+ author: 'Nathan Dumlao',+ license: 'Pexels License',+ url: 'https://www.pexels.com/photo/photo-of-coffee-shop-417173/',+ })+ })++ it('missing large2x falls back down the src ladder', async () => {+ const body = {+ photos: [+ {+ id: 7,+ width: 1200,+ height: 800,+ url: 'https://www.pexels.com/photo/x-7/',+ photographer: 'P',+ src: { large: 'https://x/large.jpg', small: 'https://x/small.jpg' },+ },+ ],+ }+ const fetchImpl = vi.fn().mockResolvedValue(jsonRes(body))+ const results = await searchStockPhotos('x', 10, { fetchImpl, noCache: true })+ expect(results[0].download).toBe('https://x/large.jpg')+ expect(results[0].alternates).toEqual(['https://x/small.jpg'])+ expect(results[0].preview).toBe('https://x/small.jpg') // smallest tile-suitable variant+ })++ it('garbage bodies fail closed to empty lists', async () => {+ for (const body of [null, 'string', {}, { photos: 'not-array' }, { photos: [null, 5, 'x'] }]) {+ const fetchImpl = vi.fn().mockResolvedValue(jsonRes(body))+ const results = await searchStockPhotos('x', 10, { fetchImpl, noCache: true })+ expect(results).toEqual([])+ }+ })+})++describe('searchStockPhotos — pixabay', () => {+ it('normalizes the documented response shape (fullHD preferred, preview tile)', async () => {+ const fetchImpl = vi.fn().mockResolvedValue(jsonRes(PIXABAY_RESPONSE))+ const results = await searchStockPhotos('alps', 24, { provider: 'pixabay', fetchImpl, noCache: true })+ expect(fetchImpl).toHaveBeenCalledOnce()+ const [url] = fetchImpl.mock.calls[0] as [string, RequestInit]+ expect(url).toContain('https://pixabay.com/api/?')+ expect(url).toContain('key=test-pixabay-key')+ expect(url).toContain('image_type=photo')+ expect(url).toContain('safesearch=true')++ expect(results).toHaveLength(1) // the garbage string entry is dropped+ const r: StockPhotoResult = results[0]+ expect(r.id).toBe('pixabay-1547301')+ expect(r.provider).toBe('pixabay')+ expect(r.width).toBe(4896)+ expect(r.height).toBe(3264)+ expect(r.download).toBe(PIXABAY_HIT.fullHDURL)+ expect(r.alternates).toEqual([PIXABAY_HIT.largeImageURL, PIXABAY_HIT.webformatURL])+ expect(r.preview).toBe(PIXABAY_HIT.previewURL)+ expect(r.credit).toEqual({+ provider: 'Pixabay',+ author: 'alps-photographer',+ license: 'Pixabay Content License',+ url: 'https://pixabay.com/photos/id-1547301/',+ })+ })++ it('no fullHDURL → largeImageURL, then webformatURL', async () => {+ const body = {+ hits: [+ {+ id: 8,+ pageURL: 'https://pixabay.com/photos/id-8/',+ user: 'U',+ previewURL: 'https://x/p.jpg',+ webformatURL: 'https://x/web.jpg',+ webformatWidth: 640,+ largeImageURL: 'https://x/large.jpg',+ imageWidth: 1000,+ imageHeight: 700,+ },+ ],+ }+ const fetchImpl = vi.fn().mockResolvedValue(jsonRes(body))+ const results = await searchStockPhotos('x', 10, { provider: 'pixabay', fetchImpl, noCache: true })+ expect(results[0].download).toBe('https://x/large.jpg')+ expect(results[0].alternates).toEqual(['https://x/web.jpg'])+ })++ it('honours the API base override (proxies / tests)', async () => {+ vi.stubEnv('PIXABAY_API_BASE', 'http://127.0.0.1:3210')+ const fetchImpl = vi.fn().mockResolvedValue(jsonRes({ hits: [] }))+ await searchStockPhotos('x', 5, { provider: 'pixabay', fetchImpl, noCache: true })+ const [url] = fetchImpl.mock.calls[0] as [string, RequestInit]+ expect(url.startsWith('http://127.0.0.1:3210/?')).toBe(true)+ })+})++describe('gating + failure modes', () => {+ it('no configured provider → NO_PROVIDER', async () => {+ vi.stubEnv('PEXELS_API_KEY', '')+ vi.stubEnv('PIXABAY_API_KEY', '')+ await expect(searchStockPhotos('x', 10, { noCache: true })).rejects.toThrow('NO_PROVIDER')+ })++ it('provider error → sanitized message, never the request URL or body', async () => {+ const fetchImpl = vi+ .fn()+ .mockResolvedValue(new Response('{"error":"bad key sk-test-pexels-key"}', { status: 401 }))+ await expect(searchStockPhotos('x', 10, { fetchImpl, noCache: true })).rejects.toThrow('Pexels search failed (401).')+ const thrown = await searchStockPhotos('x', 10, { fetchImpl, noCache: true }).catch((e: Error) => e.message)+ expect(thrown).not.toContain('test-pexels-key')+ })++ it('credit fields are hard-capped and control chars stripped', async () => {+ const body = {+ photos: [+ {+ id: 5,+ width: 100,+ height: 50,+ url: 'https://www.pexels.com/photo/x-5/',+ photographer: 'A\u0000B \n'.repeat(40), // control chars + over cap+ src: { large: 'https://x/l.jpg' },+ },+ ],+ }+ const fetchImpl = vi.fn().mockResolvedValue(jsonRes(body))+ const results = await searchStockPhotos('x', 10, { fetchImpl, noCache: true })+ expect(results[0].credit.author.length).toBeLessThanOrEqual(80)+ expect(results[0].credit.author).not.toMatch(/[\u0000-\u001f]/)+ })++ it('javascript: source URLs never become credit links', async () => {+ const body = {+ photos: [{ id: 5, width: 1, height: 1, url: 'javascript:alert(1)', photographer: 'P', src: { large: 'https://x/l.jpg' } }],+ }+ const fetchImpl = vi.fn().mockResolvedValue(jsonRes(body))+ const results = await searchStockPhotos('x', 10, { fetchImpl, noCache: true })+ expect(results[0].credit.url).toBe('')+ })+})++describe('the 24 h response cache', () => {+ it('a repeat query is served from memory — the provider is hit once', async () => {+ const fetchImpl = vi.fn().mockResolvedValue(jsonRes(PEXELS_RESPONSE))+ await searchStockPhotos('coffee', 24, { fetchImpl })+ await searchStockPhotos('coffee', 24, { fetchImpl })+ expect(fetchImpl).toHaveBeenCalledOnce()+ })++ it('different query or provider → different cache slot', async () => {+ // one Response per call — a body can only be read once+ const fetchImpl = vi+ .fn()+ .mockResolvedValueOnce(jsonRes(PEXELS_RESPONSE))+ .mockResolvedValueOnce(jsonRes(PIXABAY_RESPONSE))+ .mockResolvedValueOnce(jsonRes(PEXELS_RESPONSE))+ await searchStockPhotos('coffee', 24, { fetchImpl })+ await searchStockPhotos('tea', 24, { fetchImpl })+ await searchStockPhotos('tea', 24, { fetchImpl, provider: 'pixabay' })+ expect(fetchImpl).toHaveBeenCalledTimes(3)+ })+})diff --git a/src/lib/stock-photo.ts b/src/lib/stock-photo.tsnew file mode 100644index 0000000..8f3a267--- /dev/null+++ b/src/lib/stock-photo.ts@@ -0,0 +1,372 @@+// ─────────────────────────────────────────────────────────────+// stock-photo — provider-gated stock PHOTO search (v0.16.4 A4).+//+// Photo search is NOT an AI-model capability: "find me a photo of+// a coffee shop" is a library query against licensed stock+// catalogs, not a generative one. It used to ride the AI+// provider table (the imageSearch slot), which pinned it to+// OpenAI-compatible endpoints that almost never serve an+// images/search route — the standing 404 behind the A3 incident.+// The slot is retired; photos now ride the SAME self-hoster-key+// architecture as stock video (v0.15 R6): Pexels + Pixabay,+// plain REST, one free key each — and the SAME two env keys+// (PEXELS_API_KEY / PIXABAY_API_KEY) activate both rails.+//+// No provider key configured ⇒ the Photos panel keeps its+// bundled library, web results answer 503 NO_PROVIDER with the+// operator hint, and everything else keeps working (the F2b+// fail-closed pattern; docs/STOCK-PHOTO.md).+//+// Dependency decision (the house rule): ZERO new runtime+// dependencies — both providers are JSON-over-GET with one auth+// value; the whole connector is plain fetch. Recorded in+// docs/STOCK-PHOTO.md alongside the attribution model.+//+// Attribution (the R6 acceptance, applied to photos): every+// result carries a sanitized credit block {provider, author,+// license, url} stored DURABLY on the inserted ImageElement+// (`credit`), shown in the toast at insert and in the+// properties bar whenever the element is selected. It is never+// rendered on the canvas or burned into exports — a forced+// overlay would corrupt the design, and neither license demands+// on-content credit.+//+// Honest limits, stated here so nobody has to rediscover them:+// - provider responses are cached IN MEMORY per instance for+// 24 h (Pixabay's request; Pexels gets it for free). A+// multi-instance fleet caches per instance, not per+// deployment.+// - downloads happen in the BROWSER (both provider CDNs+// answer Access-Control-Allow-Origin: * on GET — verified+// empirically for the video renditions, same CDNs), then+// ride the existing chunked media store: quota, sha256+// dedupe and the 32 MB cap all apply as-is.+// - CI has no provider keys, so the live-provider happy path+// is covered by unit tests against recorded response+// fixtures plus the provider-on e2e against a local mock+// provider (tests/e2e-stock-video/stock-photo.spec.ts);+// the no-provider states are e2e-asserted on the default+// suite (tests/e2e/stock-photo-gated.spec.ts).+// ─────────────────────────────────────────────────────────────++export type StockPhotoProvider = 'pexels' | 'pixabay'++/** Sanitized attribution block — also the shape stored on ImageElement.credit. */+export interface StockPhotoCredit {+ provider: string+ author: string+ license: string+ url: string+}++/** One normalized search result — provider shape erased. */+export interface StockPhotoResult {+ /** provider-prefixed unique id, e.g. 'pexels-417173' */+ id: string+ provider: StockPhotoProvider+ /** original dimensions (the insert probes the real bytes anyway) */+ width: number+ height: number+ /** tile thumbnail — small, CORS-open CDN image */+ preview: string+ /** preferred download rendition: the largest at most 1920 px wide */+ download: string+ /** strictly smaller renditions, widest first — the fallback ladder+ * for when the media store's size cap rejects the primary */+ alternates: string[]+ credit: StockPhotoCredit+}++// ── availability (secret-free — never expose the keys) ────────++export function stockPhotoProviders(): StockPhotoProvider[] {+ const out: StockPhotoProvider[] = []+ if ((process.env.PEXELS_API_KEY ?? '').trim()) out.push('pexels')+ if ((process.env.PIXABAY_API_KEY ?? '').trim()) out.push('pixabay')+ return out+}++export function stockPhotoAvailable(): boolean {+ return stockPhotoProviders().length > 0+}++// ── shared helpers ────────────────────────────────────────────++function isHttpUrl(v: unknown): v is string {+ if (typeof v !== 'string' || v.length === 0 || v.length > 2000) return false+ try {+ const u = new URL(v)+ return u.protocol === 'http:' || u.protocol === 'https:'+ } catch {+ return false+ }+}++function num(v: unknown, fallback = 0): number {+ const n = Number(v)+ return Number.isFinite(n) && n >= 0 ? n : fallback+}++/** Strip control characters + collapse whitespace + hard cap. */+function cleanText(v: unknown, max: number): string {+ // provider ids arrive as JSON numbers — stringify those, drop the rest+ const s = typeof v === 'number' && Number.isFinite(v) ? String(v) : typeof v === 'string' ? v : ''+ if (!s) return ''+ return s.replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max)+}++function sanitizeCredit(raw: {+ provider: string+ author: string+ license: string+ url: unknown+}): StockPhotoCredit | null {+ const url = isHttpUrl(raw.url) ? raw.url : ''+ const provider = cleanText(raw.provider, 24)+ const author = cleanText(raw.author, 80)+ const license = cleanText(raw.license, 80)+ if (!provider || !author || !license) return null+ return { provider, author, license, url }+}++/** The rendition ladder: pick a primary ≤ MAX_PRIMARY_PX wide, list the+ * smaller ones as fallbacks (widest first). Null when no usable+ * http(s) URL exists. (Widths may be 0/unknown — those sort last and+ * only ever become the last resort.) */+const MAX_PRIMARY_PX = 1920++export function choosePhotoRenditions(files: { url: string; width: number }[]): {+ primary: string+ alternates: string[]+} | null {+ const seen = new Set<string>()+ const usable = files+ .filter((f) => isHttpUrl(f.url) && !seen.has(f.url) && seen.add(f.url))+ .sort((a, b) => b.width - a.width)+ if (usable.length === 0) return null+ const primary = usable.find((f) => f.width <= MAX_PRIMARY_PX && f.width > 0) ?? usable[usable.length - 1]+ const below = usable.filter((f) => f !== primary && (f.width < primary.width || primary.width === 0))+ return { primary: primary.url, alternates: below.map((f) => f.url) }+}++// ── Pexels — GET /v1/search, Authorization header ─────────────+// Response (documented Photo resource, parsed defensively — the+// API may add keys, so every field is unknown until validated):+// { photos: [{ id, width, height, url, photographer,+// photographer_url, avg_color, alt,+// src: { original, large2x, large, medium, small,+// portrait, landscape, tiny } }] }++/**+ * pexels src variants we build the download ladder from, widest first.+ * Deliberately EXCLUDED: `portrait`/`landscape` (different CROPS of the+ * same photo — a size-cap fallback must never silently swap the crop)+ * and `tiny` (65 px — useless as an insert). `original` stays as the+ * last resort when nothing else exists (it can be 4000 px+ / multi-MB;+ * the media store's cap then rejects it and the panel reports honestly).+ */+const PEXELS_SRC_ORDER = ['large2x', 'large', 'medium', 'small', 'original'] as const+const PEXELS_SRC_WIDTH: Record<(typeof PEXELS_SRC_ORDER)[number], number> = {+ large2x: 1880,+ large: 940,+ medium: 400,+ small: 200,+ original: 4000,+}++function parsePexels(body: unknown): StockPhotoResult[] {+ const photos = (body as { photos?: unknown })?.photos+ if (!Array.isArray(photos)) return []+ const out: StockPhotoResult[] = []+ for (const p of photos) {+ if (!p || typeof p !== 'object') continue+ const photo = p as Record<string, unknown>+ const src = photo.src && typeof photo.src === 'object' ? (photo.src as Record<string, unknown>) : {}+ const files: { url: string; width: number }[] = []+ for (const key of PEXELS_SRC_ORDER) {+ const link = src[key]+ if (typeof link === 'string' && link) {+ // width estimate per the documented src ladder (the API does+ // not repeat per-variant widths); the insert probes real bytes+ files.push({ url: link, width: PEXELS_SRC_WIDTH[key] })+ }+ }+ const ladder = choosePhotoRenditions(files)+ if (!ladder) continue+ const credit = sanitizeCredit({+ provider: 'Pexels',+ author:+ typeof photo.photographer === 'string' && photo.photographer ? photo.photographer : 'Pexels creator',+ license: 'Pexels License',+ url: photo.url,+ })+ if (!credit) continue+ const preview =+ (typeof src.medium === 'string' && src.medium) ||+ (typeof src.small === 'string' && src.small) ||+ (typeof src.tiny === 'string' && src.tiny) ||+ ladder.primary+ out.push({+ id: `pexels-${cleanText(photo.id, 32) || out.length}`,+ provider: 'pexels',+ width: num(photo.width),+ height: num(photo.height),+ preview: isHttpUrl(preview) ? preview : ladder.primary,+ download: ladder.primary,+ alternates: ladder.alternates,+ credit,+ })+ }+ return out+}++// ── Pixabay — GET /api/, key as query param ───────────────────+// Response (documented, parsed defensively):+// { hits: [{ id, pageURL, previewURL, previewWidth, previewHeight,+// webformatURL, webformatWidth, webformatHeight, largeImageURL,+// fullHDURL, imageWidth, imageHeight, user }] }++function parsePixabay(body: unknown): StockPhotoResult[] {+ const hits = (body as { hits?: unknown })?.hits+ if (!Array.isArray(hits)) return []+ const out: StockPhotoResult[] = []+ for (const h of hits) {+ if (!h || typeof h !== 'object') continue+ const hit = h as Record<string, unknown>+ // the documented size ladder: fullHDURL (1920, only when the+ // original is big enough) → largeImageURL (~936) → webformatURL+ // (640, always present). previewURL is 150 px — tile-sized.+ const files: { url: string; width: number }[] = []+ if (typeof hit.fullHDURL === 'string' && hit.fullHDURL) files.push({ url: hit.fullHDURL, width: 1920 })+ if (typeof hit.largeImageURL === 'string' && hit.largeImageURL) {+ files.push({+ url: hit.largeImageURL,+ width: num(hit.imageWidth) > 0 ? Math.min(num(hit.imageWidth), 1280) : 936,+ })+ }+ if (typeof hit.webformatURL === 'string' && hit.webformatURL) {+ files.push({ url: hit.webformatURL, width: num(hit.webformatWidth) || 640 })+ }+ const ladder = choosePhotoRenditions(files)+ if (!ladder) continue+ const credit = sanitizeCredit({+ provider: 'Pixabay',+ author: typeof hit.user === 'string' && hit.user ? hit.user : 'Pixabay creator',+ license: 'Pixabay Content License',+ url: hit.pageURL,+ })+ if (!credit) continue+ const preview = typeof hit.previewURL === 'string' && hit.previewURL ? hit.previewURL : ladder.primary+ out.push({+ id: `pixabay-${cleanText(hit.id, 32) || out.length}`,+ provider: 'pixabay',+ width: num(hit.imageWidth),+ height: num(hit.imageHeight),+ preview: isHttpUrl(preview) ? preview : ladder.primary,+ download: ladder.primary,+ alternates: ladder.alternates,+ credit,+ })+ }+ return out+}++// ── the 24 h in-memory response cache (per instance) ──────────++interface CacheEntry {+ at: number+ results: StockPhotoResult[]+}+const CACHE_TTL_MS = 24 * 3600_000+const CACHE_MAX = 512+const searchCache = new Map<string, CacheEntry>()++function cacheGet(key: string): StockPhotoResult[] | null {+ const entry = searchCache.get(key)+ if (!entry) return null+ if (Date.now() - entry.at > CACHE_TTL_MS) {+ searchCache.delete(key)+ return null+ }+ return entry.results+}++function cacheSet(key: string, results: StockPhotoResult[]): void {+ searchCache.set(key, { at: Date.now(), results })+ if (searchCache.size > CACHE_MAX) {+ const oldest = [...searchCache.entries()].sort((a, b) => a[1].at - b[1].at)+ for (const [k] of oldest.slice(0, Math.floor(oldest.length / 2))) searchCache.delete(k)+ }+}++/** Test-only: wipe the response cache. */+export function resetStockPhotoCache(): void {+ searchCache.clear()+}++// ── search ─────────────────────────────────────────────────────++const PROVIDER_FETCH_TIMEOUT_MS = 10_000++export interface SearchStockPhotosOptions {+ /** which connector to query (must be configured — the route validates) */+ provider?: StockPhotoProvider+ /** injected for tests — defaults to the global fetch */+ fetchImpl?: typeof fetch+ /** test-only: bypass the response cache */+ noCache?: boolean+}++export async function searchStockPhotos(+ query: string,+ count: number,+ opts: SearchStockPhotosOptions = {},+): Promise<StockPhotoResult[]> {+ const providers = stockPhotoProviders()+ const provider = opts.provider && providers.includes(opts.provider) ? opts.provider : providers[0]+ if (!provider) throw new Error('NO_PROVIDER')++ const q = query.trim().slice(0, 120)+ if (!q) return []+ const n = Math.min(Math.max(count, 1), 40)++ const cacheKey = `${provider}:${q}:${n}`+ if (!opts.noCache) {+ const cached = cacheGet(cacheKey)+ if (cached) return cached+ }++ const doFetch = opts.fetchImpl ?? fetch+ let body: unknown+ if (provider === 'pexels') {+ const base = (process.env.PEXELS_API_BASE ?? 'https://api.pexels.com').replace(/\/+$/, '')+ const url = `${base}/v1/search?query=${encodeURIComponent(q)}&per_page=${n}&orientation=landscape`+ const res = await doFetch(url, {+ headers: { Authorization: (process.env.PEXELS_API_KEY ?? '').trim() },+ signal: AbortSignal.timeout(PROVIDER_FETCH_TIMEOUT_MS),+ })+ if (!res.ok) {+ // never surface the provider body — it may echo the request+ // (and pixabay's key lives in the URL). Status is enough.+ console.error(`[stock-photo] pexels search failed: ${res.status}`)+ throw new Error(`Pexels search failed (${res.status}).`)+ }+ body = await res.json()+ } else {+ const base = (process.env.PIXABAY_API_BASE ?? 'https://pixabay.com/api').replace(/\/+$/, '')+ const key = encodeURIComponent((process.env.PIXABAY_API_KEY ?? '').trim())+ const url = `${base}/?key=${key}&q=${encodeURIComponent(q)}&image_type=photo&per_page=${n}&safesearch=true`+ const res = await doFetch(url, {+ signal: AbortSignal.timeout(PROVIDER_FETCH_TIMEOUT_MS),+ })+ if (!res.ok) {+ console.error(`[stock-photo] pixabay search failed: ${res.status}`)+ throw new Error(`Pixabay search failed (${res.status}).`)+ }+ body = await res.json()+ }++ const results = provider === 'pexels' ? parsePexels(body) : parsePixabay(body)+ cacheSet(cacheKey, results)+ return results+}diff --git a/src/lib/types.ts b/src/lib/types.tsindex 5935ddf..70e0eea 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -204,6 +204,12 @@ export interface ImageElement extends BaseElement {filter?: string/** preset strength 0..100 (default 100) */filterIntensity?: number+ /** v0.16.4 (A4): durable stock-photo attribution (the R6 video+ * pattern) — set by the Photos panel's stock connectors, absent on+ * uploads and bundled photos. Rides autosave/versions/collab; shown+ * on selection, never burned into exports (neither provider license+ * demands on-content credit). */+ credit?: { provider: string; author: string; license: string; url: string }}export interface StickerElement extends BaseElement {diff --git a/tests/e2e-stock-video/stock-photo.spec.ts b/tests/e2e-stock-video/stock-photo.spec.tsnew file mode 100644index 0000000..8fef353--- /dev/null+++ b/tests/e2e-stock-video/stock-photo.spec.ts@@ -0,0 +1,99 @@+import { expect, test } from '@playwright/test'++/**+ * v0.16.4 A4 — stock-photo ACCEPTANCE, provider keyed (mock Pexels).+ *+ * This suite runs under playwright.stockvideo.config.ts: the dev+ * server carries PEXELS_API_KEY + PEXELS_API_BASE pointing at the+ * local mock provider (tests/stock-video/mock-provider.mjs — the+ * same mock serves the photo half since A4), so the whole path+ * runs for real:+ *+ * 1. availability flips true — ONE key now activates BOTH rails+ * (photo + video) — and names only the connector, never the key+ * 2. typing searches the provider (auth header enforced by the+ * mock — the key path is part of the contract)+ * 3. clicking a tile downloads the rendition in the browser+ * (CORS *), uploads it through the chunked media store, probes+ * the real dimensions, and adds the element+ * 4. ATTRIBUTION IS DURABLE: selecting the element shows the+ * credit chip in the properties bar (the toast also fires, but+ * toasts auto-dismiss — assert the OBSERVED end state, the P5+ * lesson)+ * 5. no console/page errors anywhere in the path+ */+test.describe('stock photo search + insert + durable attribution (mock provider)', () => {+ test('Photos panel → search → add → credit chip on the element', async ({ page, request }) => {+ test.setTimeout(240_000)+ const errors: string[] = []+ page.on('pageerror', (err) => errors.push(String(err)))++ // 1. availability answers true, names the connector, leaks no key+ const avail = await request.get('/api/stock-photo/available')+ expect(avail.status()).toBe(200)+ const availBody = (await avail.json()) as { available: boolean; providers: string[] }+ expect(availBody).toEqual({ available: true, providers: ['pexels'] })+ expect(JSON.stringify(availBody)).not.toContain('ci-stock-video-key')++ await page.goto('/')+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })+ await page.getByRole('button', { name: /start designing/i }).first().click()+ await expect(page.getByLabel('Create a design')).toBeVisible()++ await page+ .locator('section:has(h2:text("Start a new design")) [aria-label^="Create "]')+ .first()+ .click()+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 30_000 })++ // 2. open the Photos panel (always visible — bundled library)+ await page.getByRole('button', { name: 'Photos', exact: true }).click()+ await expect(page.getByRole('heading', { name: 'Photos', exact: true })).toBeVisible()++ // 3. search (600 ms debounce) → the mock's tile renders with its+ // preview + provider chip+ await page.getByLabel('Photos search').fill('coffee')+ const tile = page.locator('button[aria-label="Add stock photo by Mock Photographer"]')+ await expect(tile).toBeVisible({ timeout: 20_000 })+ await expect(tile.getByText('Pexels', { exact: true })).toBeVisible()++ // 4. insert → download + upload + dims probe + element. The OBSERVED+ // completion signal is the tile re-enabling (busyTile clears in+ // the finally) — generous timeout: the first upload pays the+ // dev server's cold-route compilation+ await tile.click()+ await expect(tile.getByText('Adding…')).toBeVisible()+ await expect(tile).toBeEnabled({ timeout: 90_000 })++ // 5. the element sits page-center (the placement cascade); select+ // it and read the durable credit from the properties bar+ const canvas = page.getByLabel('Design canvas')+ const box = await canvas.boundingBox()+ expect(box).not.toBeNull()+ await canvas.click({ position: { x: Math.round(box!.width / 2), y: Math.round(box!.height / 2) } })++ await expect(page.getByLabel('Stock photo by Mock Photographer on Pexels')).toBeVisible({ timeout: 20_000 })+ await expect(page.getByLabel('Stock photo by Mock Photographer on Pexels')).toContainText('Pexels · Mock Photographer')++ expect(errors, `page errors: ${errors.join(' | ')}`).toEqual([])+ })++ test('the search route answers the normalized, credited result set', async ({ request }) => {+ // a WRONG key would 401 at the mock; the route maps provider+ // failures to a sanitized 502. The suite's key is correct, so+ // instead prove the search route works end-to-end here and the+ // 401 path stays covered by the unit suite (route.test.ts).+ const res = await request.post('/api/stock-photo/search', { data: { query: 'coffee' } })+ expect(res.status()).toBe(200)+ const body = (await res.json()) as {+ count: number+ results: { id: string; download: string; credit: { author: string; license: string } }[]+ }+ expect(body.count).toBe(1)+ expect(body.results[0].id).toBe('pexels-77007')+ // large2x is the primary rendition (the ladder's design-tool sweet spot)+ expect(body.results[0].download).toContain('/stock-photo.jpg')+ expect(body.results[0].credit.author).toBe('Mock Photographer')+ expect(body.results[0].credit.license).toBe('Pexels License')+ })+})diff --git a/tests/e2e/panel-state.spec.ts b/tests/e2e/panel-state.spec.tsindex 678451d..942b96e 100644--- a/tests/e2e/panel-state.spec.ts+++ b/tests/e2e/panel-state.spec.ts@@ -7,11 +7,12 @@ import { test, expect, type Page } from '@playwright/test'* F2: the Photos panel kept filtering the bundled library by a search query* after a category tab was clicked, so "All photos" showed the stale* 6-photo result set instead of the 42-photo library until the panel- * was closed and reopened; and a server with no AI provider configured- * answered web search with 503 NO_PROVIDER, which the panel rendered- * as "No web photos matched" — reading like broken search.- * Fix: a category click exits results mode (query, box text, web- * results and errors all clear), and the 503 gets a configuration hint.+ * was closed and reopened; and a server with no stock-provider keys+ * (v0.16.4 A4: photo search runs on Pexels/Pixabay, not an AI slot)+ * left web search hintless, which the panel rendered as "no results" —+ * reading like broken search.+ * Fix: a category click exits results mode (query, box text, stock+ * results and errors all clear), and an unkeyed server says so.** F3: the top-bar "Editing mode" control (editingMode) and the Tools-panel* Select/Draw toggle (tool) held separate state, so the panel could@@ -59,9 +60,9 @@ test('F2: clicking a category tab exits Photos search mode and restores the librawait page.getByRole('button', { name: 'All photos' }).click()await expect(aside.locator('img')).toHaveCount(BUNDLED_TOTAL)await expect(search).toHaveValue('')- // the web-results section is gone entirely, not just emptied (the header- // counts — "Web results (N)"; the footnote "Web results come from…" stays)- await expect(aside.getByText(/^Web results \(/)).toBeHidden()+ // the stock-results section is gone entirely, not just emptied (the+ // header counts — "Stock photos (N)"; the licenses footnote stays)+ await expect(aside.getByText(/^Stock photos \(/)).toBeHidden()// a specific category chip exits search mode too (was: same stale filter)await search.fill('mountain')@@ -73,17 +74,14 @@ test('F2: clicking a category tab exits Photos search mode and restores the librawait expect(page.getByRole('button', { name: 'Textures' })).toHaveAttribute('aria-pressed', 'true')})-test('F2: a server without an AI provider says so instead of "no photos matched"', async ({ page }) => {- // mock the provider-less server response — deterministic regardless of- // whether the machine running this spec has ZAI_* configured- await page.route('**/api/photos/search', (route) =>+test('F2: a server without stock keys says so instead of "no photos matched"', async ({ page }) => {+ // mock the unkeyed availability probe — deterministic regardless of+ // whether the machine running this spec has stock keys configured+ await page.route('**/api/stock-photo/available', (route) =>route.fulfill({- status: 503,+ status: 200,contentType: 'application/json',- body: JSON.stringify({- error: 'This feature requires an AI provider configured on the server.',- code: 'NO_PROVIDER',- }),+ body: JSON.stringify({ available: false, providers: [] }),}),)await openEditorPanel(page, 'Photos')@@ -93,9 +91,9 @@ test('F2: a server without an AI provider says so instead of "no photos matched"await page.getByRole('button', { name: 'Search', exact: true }).click()// the configuration hint, not the misleading empty-result message- await expect(aside.getByText('Web search needs an AI provider configured on the server')).toBeVisible()- await expect(aside.getByText(/ZAI_BASE_URL/)).toBeVisible()- await expect(aside.getByText('No web photos matched')).toBeHidden()+ await expect(aside.getByText('Photo search runs on free stock-provider keys')).toBeVisible()+ await expect(aside.getByText(/PEXELS_API_KEY/)).toBeVisible()+ await expect(aside.getByText('No stock photos matched')).toBeHidden()})// ── F3 ────────────────────────────────────────────────────────diff --git a/tests/e2e/stock-photo-gated.spec.ts b/tests/e2e/stock-photo-gated.spec.tsnew file mode 100644index 0000000..04344b4--- /dev/null+++ b/tests/e2e/stock-photo-gated.spec.ts@@ -0,0 +1,63 @@+import { expect, test } from '@playwright/test'++/**+ * v0.16.4 A4 — stock-photo search, NO PROVIDER KEYS (the F2b gate).+ *+ * Unlike the Videos rail, the Photos tab NEVER hides — it ships a+ * bundled library that works with zero configuration. What gates is+ * the web-search section: on the default suite (no PEXELS_API_KEY /+ * PIXABAY_API_KEY):+ * 1. /api/stock-photo/available answers available=false+ * 2. POST /api/stock-photo/search answers 503 NO_PROVIDER (+ the+ * operator hint names the keys; the key never leaks)+ * 3. the Photos tab is right there and the bundled library renders+ * 4. no console/page errors from the probe path+ *+ * The keyed world (search → insert → durable attribution) lives in+ * tests/e2e-stock-video/stock-photo.spec.ts via the mock provider.+ */+test.describe('stock photo search without provider keys (F2b gate)', () => {+ test('available=false, search 503 NO_PROVIDER with hint, Photos rail intact', async ({ page, request }) => {+ const errors: string[] = []+ page.on('pageerror', (err) => errors.push(String(err)))++ // 1. secret-free availability probe+ const avail = await request.get('/api/stock-photo/available')+ expect(avail.status()).toBe(200)+ expect(await avail.json()).toEqual({ available: false, providers: [] })++ // 2. the gated search route — hint names the keys, nothing leaks+ const res = await request.post('/api/stock-photo/search', { data: { query: 'ocean' } })+ expect(res.status()).toBe(503)+ const body = (await res.json()) as { code?: string; hint?: string }+ expect(body.code).toBe('NO_PROVIDER')+ expect(body.hint).toContain('PEXELS_API_KEY')+ expect(JSON.stringify(body)).not.toMatch(/(nvapi-|sk-|pexels-|pixabay-)[A-Za-z0-9]+/)++ // 3. the editor: the Photos tab stays (bundled library), Videos+ // stays hidden (no video keys on this suite either)+ await page.goto('/')+ // Next.js dev tools indicator overlays the first rail button in dev mode+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })+ await page.getByRole('button', { name: /start designing/i }).first().click()+ await expect(page.getByLabel('Create a design')).toBeVisible()++ await page+ .locator('section:has(h2:text("Start a new design")) [aria-label^="Create "]')+ .first()+ .click()+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 30_000 })++ // give the (cached, module-level) availability probe a beat+ await page.waitForTimeout(1200)+ await expect(page.getByRole('button', { name: 'Photos', exact: true })).toBeVisible()+ await expect(page.getByRole('button', { name: 'Videos', exact: true })).toHaveCount(0)++ // the bundled library opens and renders its photos+ await page.getByRole('button', { name: 'Photos', exact: true }).click()+ await expect(page.getByRole('heading', { name: 'Photos', exact: true })).toBeVisible()+ await expect(page.locator('aside').locator('img').first()).toBeVisible({ timeout: 15_000 })++ expect(errors, `page errors: ${errors.join(' | ')}`).toEqual([])+ })+})diff --git a/tests/fixtures/videos/stock-photo.jpg b/tests/fixtures/videos/stock-photo.jpgnew file mode 100644index 0000000..eff0fa4Binary files /dev/null and b/tests/fixtures/videos/stock-photo.jpg differdiff --git a/tests/stock-video/mock-provider.mjs b/tests/stock-video/mock-provider.mjsindex 58a8114..04c8a95 100644--- a/tests/stock-video/mock-provider.mjs+++ b/tests/stock-video/mock-provider.mjs@@ -1,14 +1,15 @@#!/usr/bin/env node// ─────────────────────────────────────────────────────────────// mock-provider — a tiny stand-in Pexels API for the flag-on-// stock-video e2e (v0.15 R6).+// stock e2e (v0.15 R6 videos, v0.16.4 A4 photos).//// CI has no real provider keys, so the acceptance suite points// PEXELS_API_BASE here: it answers the documented /videos/search-// shape (Authorization header enforced — the key path is part of-// the assertion) and serves real, ffmpeg-generated mp4 renditions-// so the full insert path runs: browser download (CORS *) →-// chunked media store → poster probe → VideoElement.credit.+// AND /v1/search (photos) shapes (Authorization header enforced —+// the key path is part of the assertion) and serves real,+// ffmpeg-generated renditions/files so the full insert path runs:+// browser download (CORS *) → chunked media store → poster/dims+// probe → VideoElement/ImageElement credit.//// Zero dependencies: node:http + node:fs/promises only.// ─────────────────────────────────────────────────────────────@@ -23,6 +24,36 @@ const API_KEY = process.env.MOCK_KEY ?? 'ci-stock-video-key'const HERE = dirname(fileURLToPath(import.meta.url))const FIXTURES = join(HERE, '..', 'fixtures', 'videos')+// v0.16.4 (A4): the documented Pexels PHOTO search shape — the+// stock-photo connector's parsing oracle (all src variants point at+// the one fixture JPEG; large2x is the expected primary)+const PHOTO_SEARCH_RESPONSE = {+ total_results: 1,+ page: 1,+ per_page: 24,+ photos: [+ {+ id: 77007,+ width: 1600,+ height: 900,+ url: 'https://www.pexels.com/photo/mock-stock-photo-77007/',+ photographer: 'Mock Photographer',+ photographer_url: 'https://www.pexels.com/@mock-photographer/',+ photographer_id: 90210,+ avg_color: '#2D6A4F',+ alt: 'a mock stock photo',+ src: {+ original: `http://127.0.0.1:${PORT}/stock-photo.jpg`,+ large2x: `http://127.0.0.1:${PORT}/stock-photo.jpg`,+ large: `http://127.0.0.1:${PORT}/stock-photo.jpg`,+ medium: `http://127.0.0.1:${PORT}/stock-photo.jpg`,+ small: `http://127.0.0.1:${PORT}/stock-photo.jpg`,+ },+ liked: false,+ },+ ],+}+const SEARCH_RESPONSE = {url: 'http://127.0.0.1:3210/videos/search?query=ocean',page: 1,@@ -87,6 +118,18 @@ const server = createServer(async (req, res) => {return}+ // v0.16.4 (A4): the PHOTO search path (same auth contract)+ if (url.pathname === '/v1/search') {+ if (req.headers.authorization !== API_KEY) {+ res.writeHead(401, { 'Content-Type': 'application/json', ...cors })+ res.end(JSON.stringify({ error: 'Invalid API key.' }))+ return+ }+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', ...cors })+ res.end(JSON.stringify(PHOTO_SEARCH_RESPONSE))+ return+ }+if (url.pathname === '/videos/search') {// the auth path is part of the contract under testif (req.headers.authorization !== API_KEY) {@@ -99,7 +142,8 @@ const server = createServer(async (req, res) => {return}- const file = ['/stock-720.mp4', '/stock-360.mp4', '/stock-preview.jpg'].find((f) => f === url.pathname)+ // v0.16.4 (A4): stock-photo.jpg — the photo insert fixture+ const file = ['/stock-720.mp4', '/stock-360.mp4', '/stock-preview.jpg', '/stock-photo.jpg'].find((f) => f === url.pathname)if (file) {const bytes = await readFile(join(FIXTURES, file.slice(1)))res.writeHead(200, {