Skip to content

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

feat: image-tools engine — provider by default, this device as the option

Ashiq Hussain Mire3a55cffd40f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1f36dd3..2887f9e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,31 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## [Unreleased]
+### Added
+
+- **Image-tools engine preference — provider by default, this device as
+ the option** (user request). The BG remover and Upscale popovers now
+ carry an engine toggle, persisted per browser
+ (`canvix.image-tools.engine`, new `lib/image-tools-engine.ts`):
+ - **Provider (default)** — the configured image-edit AI does the work
+ server-side. BG remover posts `mode:'bg-remove'` (the server prompt
+ existed since v0.4 but the button never used it — the tool was
+ hardwired to the local ONNX model); Upscale posts a new
+ `mode:'upscale'` (AI re-render with restored detail at the
+ provider's supported sizes, only attempted when it adds pixels) and
+ then finishes to the advertised 2×/4× target with the deterministic
+ Lanczos pass (`lanczosResize()`, new in `lib/upscale.ts`).
+ - **This device** — the previous behaviour: ONNX segmentation cut-out
+ (~40 MB model, first use) and pure Lanczos-3.
+ - Honest failure handling: `NO_PROVIDER`/`FEATURE_DISABLED` makes
+ Upscale fall back to the deterministic pass with a toast note, while
+ BG remover explains and asks you to flip the toggle (no surprise
+ 40 MB downloads); `SOURCE_NOT_EDITABLE` points at the This-device
+ engine; every other provider error shows its reason inline.
+- e2e: the wave-4 local-tools spec now also pins that the engine toggle
+ exists, defaults to Provider, and that the no-provider fallback really
+ enlarges (8→16px through the designs API) with its honest toast.
+
### Fixed
- **Landing-page counts told the v0.1.0 story** — the stats strip still
diff --git a/docs/AI-POWER-UP.md b/docs/AI-POWER-UP.md
index 9aab790..4974115 100644
--- a/docs/AI-POWER-UP.md
+++ b/docs/AI-POWER-UP.md
@@ -29,19 +29,46 @@ response is a first-class contract now:
- Generation/edit responses forward `image_ent_id`; the editor stores it on
the element (`ImageElement.aiEntId`) and sends it back as `sourceEntId`, so
AI-edit chains survive re-encoding (the byte hash does not).
-- The two heavy image tools that users need on **uploads and stock photos** —
- upscaling and object removal — run **locally**. No provider can gate them.
+
+## Engine preference — provider or this device (v0.22)
+
+The one-click image tools — **BG remover** and **Upscale** — carry a small
+engine toggle in their popovers, persisted per browser
+(`canvix.image-tools.engine`, `lib/image-tools-engine.ts`):
+
+| Engine | BG remover | Upscale |
+| --- | --- | --- |
+| **Provider** (default) | the configured image-edit provider cuts the background out server-side — no local compute, no model download | the provider re-renders the image with restored detail at its supported sizes (only attempted when it adds pixels), then the deterministic Lanczos pass finishes to the advertised target |
+| **This device** | the local ONNX segmentation model (first use downloads ~40 MB, then cached) | pure Lanczos-3, exactly as before |
+
+Failure behaviour is honest and structured:
+
+- **No provider configured / feature disabled** (`NO_PROVIDER`,
+ `FEATURE_DISABLED`) — Upscale silently degrades to the deterministic
+ on-device pass and the toast says so; BG remover (whose device engine
+ downloads a 40 MB model) instead explains and asks you to flip the
+ toggle — no surprise downloads.
+- **`SOURCE_NOT_EDITABLE`** (VibesAI-class providers that only edit their
+ own generations) — both popovers point at the **This device** engine,
+ which works on any image.
+- Any other provider error surfaces with its reason, inline in the popover.
+
+The text-driven Magic eraser and Enhance stay provider-only (their local
+counterpart is the brush eraser); the brush eraser stays device-only (its
+provider counterpart is the Magic eraser).
## Local image power tools (any image, offline)
### Upscaler — Lanczos-3 (`lib/upscale.ts`)
The "Upscale" button on a selected image offers 2× / 4× with a live
-target-size preview. Pure-TypedScript separable Lanczos-3 resampling with
+target-size preview. Pure-TypeScript separable Lanczos-3 resampling with
premultiplied alpha (cut-outs keep clean edges — straight RGBA filtering
bleeds transparent-pixel colors). Output capped at 8192px per side; the
factor auto-reduces when the cap would be exceeded. Deterministic and
-unit-pinned (`lib/upscale.test.ts`).
+unit-pinned (`lib/upscale.test.ts`). v0.22 adds `lanczosResize()` — the same
+kernel to exact target dimensions — as the deterministic finish of the
+provider engine's upscale path.
### Brush magic eraser — pyramid diffusion (`lib/inpaint.ts`)
@@ -157,7 +184,7 @@ pointer to `get_design_content`.
| `themeGeneration` | text slot | `themeGeneration` |
| `altText` | vision slot | `altText` |
| `videoGeneration` | video slot | `videoGeneration` |
-| `upscale` | — local, always on | — |
+| `upscale` | — local engine always available; provider engine via image-edit slot when configured | — |
| `brushEraser` | — local, always on | — |
## Acceptance
diff --git a/src/app/api/ai/image-edit/route.ts b/src/app/api/ai/image-edit/route.ts
index 153c8e2..46ba03c 100644
--- a/src/app/api/ai/image-edit/route.ts
+++ b/src/app/api/ai/image-edit/route.ts
@@ -11,7 +11,7 @@ type ImgSize = (typeof SUPPORTED_SIZES)[number]
interface EditBody {
image?: string // dataURL or remote URL
prompt?: string // edit instruction
- mode?: 'edit' | 'bg-remove' | 'erase' | 'enhance'
+ mode?: 'edit' | 'bg-remove' | 'erase' | 'enhance' | 'upscale'
eraseTarget?: string // for mode=erase: what to remove
naturalWidth?: number
naturalHeight?: number
@@ -49,6 +49,14 @@ const MODE_PROMPTS: Record<string, string> = {
enhance:
'Enhance this photo: increase sharpness and clarity, improve lighting and color balance, reduce noise. ' +
'Keep the composition, subject and framing exactly the same. Natural, professional result.',
+ // v0.22: the provider engine of the Upscale tool — an AI re-render that
+ // restores detail at the provider's output size. The client then (or
+ // instead) runs the deterministic Lanczos-3 pass to reach the exact
+ // requested pixel size; see src/components/editor/ImageAI.tsx.
+ upscale:
+ 'Re-render this exact image at a higher resolution. Keep the composition, subject, colors and ' +
+ 'framing pixel-faithful — this is an upscale, not a reinterpretation. Restore fine detail and crisp ' +
+ 'edges; do not add, remove or restyle anything. Output a PNG. No text or watermarks.',
}
/** POST /api/ai/image-edit — Canva-style AI image tools (BG remover, Magic eraser, enhance). */
diff --git a/src/components/editor/ImageAI.tsx b/src/components/editor/ImageAI.tsx
index 778be77..c9cbff6 100644
--- a/src/components/editor/ImageAI.tsx
+++ b/src/components/editor/ImageAI.tsx
@@ -1,7 +1,7 @@
'use client'
import { useCallback, useEffect, useRef, useState } from 'react'
-import { Eraser, Wand2, Loader2, Sparkles, Brush, Maximize2, Accessibility } from 'lucide-react'
+import { Eraser, Wand2, Loader2, Sparkles, Brush, Maximize2, Accessibility, Cloud, Cpu } from 'lucide-react'
import { useEditorStore } from '@/store/editor-store'
import type { ImageElement } from '@/lib/types'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
@@ -9,6 +9,7 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/u
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { toast } from '@/hooks/use-toast'
+import { getImageToolsEngine, setImageToolsEngine, IMAGE_TOOL_ENGINES, type ImageToolsEngine } from '@/lib/image-tools-engine'
interface EditResponse {
dataUrl?: string
@@ -57,16 +58,18 @@ async function toSendableImage(src: string): Promise<string> {
}
/**
- * Shared AI image-edit runner — calls /api/ai/image-edit and swaps the
- * element's image in place, preserving the on-canvas width and adapting
- * the height to the new aspect ratio.
+ * POST /api/ai/image-edit WITHOUT touching the element — the shared
+ * transport under runImageAI and the provider engine of the one-click
+ * tools (BG remover, Upscale). Returns either the provider's image or
+ * the structured failure the caller decides how to present.
*/
-async function runImageAI(
+async function editViaProvider(
el: ImageElement,
payload: Record<string, unknown>,
- onDone: (msg: string) => void
-): Promise<boolean> {
- const update = useEditorStore.getState().updateElements
+): Promise<
+ | { ok: true; dataUrl: string; width?: number; height?: number; entId?: string }
+ | { ok: false; error?: string; code?: string; detail?: string }
+> {
try {
const image = await toSendableImage(el.src)
const res = await fetch('/api/ai/image-edit', {
@@ -84,31 +87,87 @@ async function runImageAI(
})
const data = (await res.json()) as EditResponse
if (!res.ok || !data.dataUrl) {
- // SOURCE_NOT_EDITABLE (422): the provider only edits its own
- // generations — the route's message already points at the local
- // tools that work on any image.
- const reason = data.code === 'SOURCE_NOT_EDITABLE' ? '' : providerReason(data.detail)
- onDone(reason ? `${data.error ?? 'The edit failed.'} — ${reason.slice(0, 220)}` : (data.error ?? 'The edit failed. Please try again.'))
- return false
+ return { ok: false, error: data.error, code: data.code, detail: data.detail }
}
- const w = data.width || el.naturalWidth
- const h = data.height || el.naturalHeight
- // keep on-canvas width; adapt height to the new aspect ratio
- const newHeight = Math.max(4, Math.round(el.width * (h / Math.max(1, w))))
- update([el.id], {
- src: data.dataUrl,
- naturalWidth: w,
- naturalHeight: h,
- height: newHeight,
- // refresh the provider handle — the edit result is the new
- // editable image (cleared when the provider returns none)
- aiEntId: data.entId,
- })
- return true
+ return { ok: true, dataUrl: data.dataUrl, width: data.width, height: data.height, entId: data.entId }
} catch {
- onDone('AI image editing is unavailable right now.')
+ return { ok: false, error: 'AI image editing is unavailable right now.' }
+ }
+}
+
+/**
+ * Shared AI image-edit runner — calls /api/ai/image-edit and swaps the
+ * element's image in place, preserving the on-canvas width and adapting
+ * the height to the new aspect ratio.
+ */
+async function runImageAI(
+ el: ImageElement,
+ payload: Record<string, unknown>,
+ onDone: (msg: string) => void
+): Promise<boolean> {
+ const update = useEditorStore.getState().updateElements
+ const r = await editViaProvider(el, payload)
+ if (!r.ok) {
+ // SOURCE_NOT_EDITABLE (422): the provider only edits its own
+ // generations — the route's message already points at the local
+ // tools that work on any image.
+ const reason = r.code === 'SOURCE_NOT_EDITABLE' ? '' : providerReason(r.detail)
+ onDone(
+ reason
+ ? `${r.error ?? 'The edit failed.'} — ${reason.slice(0, 220)}`
+ : (r.error ?? 'The edit failed. Please try again.'),
+ )
return false
}
+ const w = r.width || el.naturalWidth
+ const h = r.height || el.naturalHeight
+ // keep on-canvas width; adapt height to the new aspect ratio
+ const newHeight = Math.max(4, Math.round(el.width * (h / Math.max(1, w))))
+ update([el.id], {
+ src: r.dataUrl,
+ naturalWidth: w,
+ naturalHeight: h,
+ height: newHeight,
+ // refresh the provider handle — the edit result is the new
+ // editable image (cleared when the provider returns none)
+ aiEntId: r.entId,
+ })
+ return true
+}
+
+/** v0.22: engine selector for the one-click image tools — Provider
+ * (default: the configured AI provider does the work server-side) or
+ * This device (the local paths: ONNX cut-out / Lanczos resampling).
+ * One shared per-browser preference, persisted across both tools. */
+function EngineToggle({ engine, onChange }: { engine: ImageToolsEngine; onChange: (e: ImageToolsEngine) => void }) {
+ return (
+ <div>
+ <div className="flex gap-1 p-0.5 rounded-lg bg-white/[0.06] border border-white/10" role="group" aria-label="Engine — provider or this device">
+ {IMAGE_TOOL_ENGINES.map((e) => (
+ <button
+ key={e.id}
+ onClick={() => {
+ setImageToolsEngine(e.id)
+ onChange(e.id)
+ }}
+ className={`flex-1 h-7 rounded-md text-[11px] font-semibold inline-flex items-center justify-center gap-1 transition-colors ${
+ engine === e.id ? 'bg-[#02C0CC] text-black' : 'text-white/65 hover:text-white'
+ }`}
+ aria-pressed={engine === e.id}
+ data-testid={`engine-${e.id}`}
+ >
+ {e.id === 'provider' ? <Cloud size={11} /> : <Cpu size={11} />}
+ {e.label}
+ </button>
+ ))}
+ </div>
+ <p className="text-[10px] text-white/40 mt-1 leading-snug">
+ {engine === 'provider'
+ ? 'Provider (default) — the configured AI provider does the work server-side.'
+ : 'This device — runs locally in your browser, works offline on any image.'}
+ </p>
+ </div>
+ )
}
const btnBase =
@@ -135,37 +194,97 @@ function imageSize(dataUrl: string): Promise<{ w: number; h: number }> {
}
/** Canva "BG Remover" — one-click background removal on the selected image.
- * Runs a local ONNX segmentation model in the browser (true alpha cut-out);
- * the first use downloads the model (~40 MB) once, then it is cached. */
-export function BgRemoverButton({ el }: { el: ImageElement }) {
+ * v0.22: two engines, user-selectable, provider by default —
+ * · Provider: the configured image-edit AI does the cut-out server-side
+ * (no local compute; refuses on VibesAI-class providers that only
+ * edit their own generations — the popover says so)
+ * · This device: a local ONNX segmentation model (true alpha cut-out);
+ * the first use downloads the model (~40 MB) once, then it is cached
+ */
+export function BgRemoverPopover({ el }: { el: ImageElement }) {
+ const [open, setOpen] = useState(false)
const [busy, setBusy] = useState(false)
- const [phase, setPhase] = useState<'idle' | 'model' | 'removing'>('idle')
+ const [phase, setPhase] = useState<'idle' | 'model' | 'removing' | 'provider'>('idle')
+ const [engine, setEngine] = useState<ImageToolsEngine>('provider')
+ const [error, setError] = useState('')
+
+ // re-sync the shared per-browser preference whenever the popover opens
+ // (render-time adjust — the React-docs pattern, not an effect)
+ const [lastOpen, setLastOpen] = useState(false)
+ if (open !== lastOpen) {
+ setLastOpen(open)
+ if (open) {
+ setEngine(getImageToolsEngine())
+ setError('')
+ }
+ }
+
+ /** The on-device path — ONNX segmentation cut-out. */
+ const runDevice = async () => {
+ const update = useEditorStore.getState().updateElements
+ setPhase('model')
+ const { removeBackground } = await import('@imgly/background-removal')
+ const sendable = await toSendableImage(el.src)
+ const blob = await (await fetch(sendable)).blob()
+ setPhase('removing')
+ const result = await removeBackground(blob, {
+ output: { format: 'image/png' },
+ progress: (key) => {
+ if (key === 'fetch:network' || key.startsWith('fetch:')) setPhase('model')
+ },
+ })
+ const dataUrl = await blobToDataURL(result)
+ const dims = await imageSize(dataUrl)
+ const newHeight = Math.max(4, Math.round(el.width * (dims.h / Math.max(1, dims.w))))
+ update([el.id], {
+ src: dataUrl,
+ naturalWidth: dims.w,
+ naturalHeight: dims.h,
+ height: newHeight,
+ })
+ return dims
+ }
+
const run = async () => {
if (busy) return
setBusy(true)
- setPhase('model')
+ setError('')
const update = useEditorStore.getState().updateElements
try {
- const { removeBackground } = await import('@imgly/background-removal')
- const sendable = await toSendableImage(el.src)
- const blob = await (await fetch(sendable)).blob()
- setPhase('removing')
- const result = await removeBackground(blob, {
- output: { format: 'image/png' },
- progress: (key) => {
- if (key === 'fetch:network' || key.startsWith('fetch:')) setPhase('model')
- },
- })
- const dataUrl = await blobToDataURL(result)
- const dims = await imageSize(dataUrl)
- const newHeight = Math.max(4, Math.round(el.width * (dims.h / Math.max(1, dims.w))))
- update([el.id], {
- src: dataUrl,
- naturalWidth: dims.w,
- naturalHeight: dims.h,
- height: newHeight,
- })
- toast({ title: 'Background removed', description: 'The cut-out replaced your image. Ctrl+Z to undo.' })
+ if (engine === 'provider') {
+ setPhase('provider')
+ const r = await editViaProvider(el, { mode: 'bg-remove' })
+ if (r.ok) {
+ const dims = await imageSize(r.dataUrl)
+ const w = r.width || dims.w
+ const h = r.height || dims.h
+ const newHeight = Math.max(4, Math.round(el.width * (h / Math.max(1, w))))
+ update([el.id], {
+ src: r.dataUrl,
+ naturalWidth: w,
+ naturalHeight: h,
+ height: newHeight,
+ aiEntId: r.entId,
+ })
+ toast({ title: 'Background removed', description: 'Provider cut-out swapped in. Ctrl+Z to undo.' })
+ setOpen(false)
+ } else if (r.code === 'SOURCE_NOT_EDITABLE') {
+ setError(
+ 'This provider only edits images it generated itself. Switch the engine to This device — the local cut-out works on any image.',
+ )
+ } else if (r.code === 'NO_PROVIDER' || r.code === 'FEATURE_DISABLED') {
+ setError(
+ 'No AI provider is configured on this server. Switch the engine to This device — the local model works offline (first use downloads ~40 MB).',
+ )
+ } else {
+ const reason = providerReason(r.detail)
+ setError(reason ? `${r.error ?? 'The edit failed.'} — ${reason.slice(0, 220)}` : (r.error ?? 'The edit failed. Please try again.'))
+ }
+ } else {
+ await runDevice()
+ toast({ title: 'Background removed', description: 'On-device cut-out replaced your image. Ctrl+Z to undo.' })
+ setOpen(false)
+ }
} catch (e) {
toast({
title: 'Background remover',
@@ -177,12 +296,42 @@ export function BgRemoverButton({ el }: { el: ImageElement }) {
setPhase('idle')
}
}
- const label = busy ? (phase === 'model' ? 'Loading model…' : 'Removing…') : 'BG Remover'
+
+ const label = busy
+ ? phase === 'provider'
+ ? 'Removing…'
+ : phase === 'model'
+ ? 'Loading model…'
+ : 'Removing…'
+ : 'BG Remover'
return (
- <button className={btnBase} onClick={() => void run()} disabled={busy} title="BG Remover — remove the image background" aria-label="Remove background">
- {busy ? <Loader2 size={14} className="animate-spin" /> : <Eraser size={14} />}
- <span className="text-[12px] hidden lg:inline">{label}</span>
- </button>
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <button className={btnBase} data-active={open} disabled={busy} title="BG Remover — remove the image background" aria-label="Remove background">
+ {busy ? <Loader2 size={14} className="animate-spin" /> : <Eraser size={14} />}
+ <span className="text-[12px] hidden lg:inline">{label}</span>
+ </button>
+ </PopoverTrigger>
+ <PopoverContent align="center" side="bottom" className="w-[300px] rounded-2xl bg-[#1A1C22] border-white/10 text-white p-3.5">
+ <div className="text-[13px] font-bold mb-1 flex items-center gap-1.5">
+ <Eraser size={13} className="text-[#02C0CC]" /> BG Remover
+ </div>
+ <p className="text-[11px] text-white/55 mb-2.5 leading-snug">
+ One click — the background disappears, the subject stays. Choose who does the work:
+ </p>
+ <div className="mb-2.5">
+ <EngineToggle engine={engine} onChange={setEngine} />
+ </div>
+ {error && (
+ <p className="text-[11px] text-[#FF8A8A] mb-2 leading-snug" data-testid="bg-remover-error" role="alert">
+ {error}
+ </p>
+ )}
+ <Button className="btn-cv w-full h-9 text-[12px]" onClick={() => void run()} disabled={busy}>
+ {busy ? <Loader2 size={13} className="animate-spin" /> : 'Remove background'}
+ </Button>
+ </PopoverContent>
+ </Popover>
)
}
@@ -285,18 +434,64 @@ function toImageData(data: Uint8ClampedArray, w: number, h: number): ImageData {
return new ImageData(copy, w, h)
}
-/** Canva-style "Upscale" — Lanczos-3 2x/4x with alpha discipline. */
+/**
+ * Deterministic Lanczos resize of a dataURL image to exact target
+ * dimensions (both engines' final sizing step — v0.22).
+ */
+async function lanczosTo(dataUrl: string, targetW: number, targetH: number): Promise<{ dataUrl: string; width: number; height: number }> {
+ const { lanczosResize } = await import('@/lib/upscale')
+ const img = await loadImage(dataUrl)
+ const w = img.naturalWidth
+ const h = img.naturalHeight
+ if (w === targetW && h === targetH) return { dataUrl, width: w, height: h }
+ const canvas = document.createElement('canvas')
+ canvas.width = w
+ canvas.height = h
+ const ctx = canvas.getContext('2d', { willReadFrequently: true })
+ if (!ctx) throw new Error('Canvas is unavailable')
+ ctx.drawImage(img, 0, 0)
+ const inData = ctx.getImageData(0, 0, w, h)
+ const out = lanczosResize({ data: inData.data, width: w, height: h }, targetW, targetH)
+ canvas.width = out.width
+ canvas.height = out.height
+ ctx.putImageData(toImageData(out.data, out.width, out.height), 0, 0)
+ return { dataUrl: canvas.toDataURL('image/png'), width: out.width, height: out.height }
+}
+
+/**
+ * Canva-style "Upscale" — 2×/4× enlargement with alpha discipline.
+ * v0.22: two engines, user-selectable, provider by default —
+ * · Provider: the image-edit AI re-renders the image with restored
+ * detail at its supported sizes (only attempted when it adds pixels),
+ * then the deterministic Lanczos pass finishes to the advertised
+ * target. When no provider is configured the local pass runs alone.
+ * · This device: the Lanczos-3 pass only, exactly as before.
+ */
export function UpscaleButton({ el }: { el: ImageElement }) {
const [busy, setBusy] = useState(false)
const [factor, setFactor] = useState<2 | 4>(2)
const [open, setOpen] = useState(false)
+ const [engine, setEngine] = useState<ImageToolsEngine>('provider')
+ const [error, setError] = useState('')
+
+ // re-sync the shared per-browser preference whenever the popover opens
+ // (render-time adjust — the React-docs pattern, not an effect)
+ const [lastOpen, setLastOpen] = useState(false)
+ if (open !== lastOpen) {
+ setLastOpen(open)
+ if (open) {
+ setEngine(getImageToolsEngine())
+ setError('')
+ }
+ }
const run = async () => {
if (busy) return
setBusy(true)
+ setError('')
const update = useEditorStore.getState().updateElements
try {
- const { lanczosUpscale, factorFor } = await import('@/lib/upscale')
+ const { factorFor } = await import('@/lib/upscale')
const sendable = await toSendableImage(el.src)
const img = await loadImage(sendable)
const src = { width: img.naturalWidth, height: img.naturalHeight }
@@ -308,31 +503,70 @@ export function UpscaleButton({ el }: { el: ImageElement }) {
})
return
}
- const canvas = document.createElement('canvas')
- canvas.width = src.width
- canvas.height = src.height
- const ctx = canvas.getContext('2d', { willReadFrequently: true })
- if (!ctx) throw new Error('Canvas is unavailable')
- ctx.drawImage(img, 0, 0)
- const inData = ctx.getImageData(0, 0, src.width, src.height)
- const out = lanczosUpscale(
- { data: inData.data, width: src.width, height: src.height },
- f,
- )
- canvas.width = out.width
- canvas.height = out.height
- ctx.putImageData(toImageData(out.data, out.width, out.height), 0, 0)
- const dataUrl = canvas.toDataURL('image/png')
+ const origTarget = {
+ width: Math.min(8192, src.width * f),
+ height: Math.min(8192, src.height * f),
+ }
+
+ // base the enlargement starts from — the original unless the
+ // provider engine contributes a higher-detail re-render
+ let base = { dataUrl: sendable, width: src.width, height: src.height }
+ let usedProvider = false
+ let fellBackNote = ''
+ let providerEntId: string | undefined
+
+ if (engine === 'provider') {
+ // The provider re-renders at ~1 MP — only worth the call when it
+ // actually adds pixels over the source. Above that, Lanczos alone
+ // is the honest enlargement (and the toast says so).
+ if (src.width * src.height < 1_000_000) {
+ const r = await editViaProvider(el, { mode: 'upscale' })
+ if (r.ok) {
+ const dims = await imageSize(r.dataUrl)
+ if (dims.w * dims.h > src.width * src.height) {
+ base = { dataUrl: r.dataUrl, width: dims.w, height: dims.h }
+ usedProvider = true
+ providerEntId = r.entId
+ }
+ } else if (r.code === 'NO_PROVIDER' || r.code === 'FEATURE_DISABLED') {
+ // nothing configured server-side — the deterministic pass IS
+ // the tool; say so instead of failing
+ fellBackNote = ' No AI provider configured — enlarged on this device.'
+ } else if (r.code === 'SOURCE_NOT_EDITABLE') {
+ setError(
+ 'This provider only edits images it generated itself. Switch the engine to This device — Lanczos enlarges any image.',
+ )
+ return
+ } else {
+ const reason = providerReason(r.detail)
+ setError(reason ? `${r.error ?? 'The edit failed.'} — ${reason.slice(0, 220)}` : (r.error ?? 'The edit failed. Please try again.'))
+ return
+ }
+ } else {
+ fellBackNote = ' Already above the provider re-render size — enlarged on this device.'
+ }
+ }
+
+ // deterministic finish — land on the advertised multiple of the base
+ const target = usedProvider
+ ? { width: Math.min(8192, base.width * f), height: Math.min(8192, base.height * f) }
+ : origTarget
+ const out = await lanczosTo(base.dataUrl, target.width, target.height)
const newHeight = Math.max(4, Math.round(el.width * (out.height / Math.max(1, out.width))))
update([el.id], {
- src: dataUrl,
+ src: out.dataUrl,
naturalWidth: out.width,
naturalHeight: out.height,
height: newHeight,
+ // refresh the provider handle when the provider re-rendered the
+ // image — the result is the new provider-owned editable
+ ...(providerEntId ? { aiEntId: providerEntId } : {}),
})
toast({
title: `Upscaled ${f}×`,
- description: `${src.width}×${src.height} → ${out.width}×${out.height}px. Ctrl+Z to undo.`,
+ description:
+ `${base.width}×${base.height} → ${out.width}×${out.height}px` +
+ `${usedProvider ? ' (provider re-render + Lanczos finish)' : ''}.${fellBackNote} Ctrl+Z to undo.`,
})
setOpen(false)
} catch (e) {
@@ -350,19 +584,26 @@ export function UpscaleButton({ el }: { el: ImageElement }) {
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
- <button className={btnBase} data-active={open} title="Upscale — enlarge this image locally (Lanczos)" aria-label="Upscale image">
+ <button className={btnBase} data-active={open} title="Upscale — enlarge this image (provider or on-device)" aria-label="Upscale image">
<Maximize2 size={14} />
<span className="text-[12px] hidden lg:inline">Upscale</span>
</button>
</PopoverTrigger>
- <PopoverContent align="center" side="bottom" className="w-[280px] rounded-2xl bg-[#1A1C22] border-white/10 text-white p-3.5">
+ <PopoverContent align="center" side="bottom" className="w-[300px] rounded-2xl bg-[#1A1C22] border-white/10 text-white p-3.5">
<div className="text-[13px] font-bold mb-1 flex items-center gap-1.5">
<Maximize2 size={13} className="text-[#02C0CC]" /> Upscale
</div>
<p className="text-[11px] text-white/55 mb-2.5 leading-snug">
- Enlarge with high-quality Lanczos resampling — runs locally, works on any image, keeps transparency.
- Now {el.naturalWidth}×{el.naturalHeight}px.
+ Enlarge to {target}px with alpha discipline. Now {el.naturalWidth}×{el.naturalHeight}px.
</p>
+ <div className="mb-2.5">
+ <EngineToggle engine={engine} onChange={setEngine} />
+ </div>
+ {error && (
+ <p className="text-[11px] text-[#FF8A8A] mb-2 leading-snug" data-testid="upscale-error" role="alert">
+ {error}
+ </p>
+ )}
<div className="flex gap-1.5 mb-2.5">
{([2, 4] as const).map((f) => (
<button
diff --git a/src/components/editor/PropertiesBar.tsx b/src/components/editor/PropertiesBar.tsx
index 8914aa6..3862a8b 100644
--- a/src/components/editor/PropertiesBar.tsx
+++ b/src/components/editor/PropertiesBar.tsx
@@ -29,7 +29,7 @@ import { IMAGE_FILTER_PRESETS, applyPresetToImageData, isImageFilterId, clampFil
import { MASK_SHAPES, MASK_SHAPE_LABELS, isMaskShape, maskPolygon } from '@/lib/shapes'
import { useLoadedImage } from './canvas/use-loaded-image'
import { ToolbarPopover, SliderRow, IconTile } from './toolbar/popover-kit'
-import { BgRemoverButton, MagicEraserPopover, EnhanceButton, UpscaleButton, BrushEraserDialog, AltTextPopover } from './ImageAI'
+import { BgRemoverPopover, MagicEraserPopover, EnhanceButton, UpscaleButton, BrushEraserDialog, AltTextPopover } from './ImageAI'
const ALIGN_ICONS = {
left: AlignLeft,
@@ -443,7 +443,7 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'm
<MaskPopover el={image} ids={ids} />
<ImageAdjustPopover el={image} ids={ids} />
{/* v0.4 Canva AI image tools */}
- <BgRemoverButton el={image} />
+ <BgRemoverPopover el={image} />
<MagicEraserPopover el={image} />
<EnhanceButton el={image} />
{/* v0.19 (Wave 4): local image power tools — any image, offline */}
diff --git a/src/lib/image-tools-engine.test.ts b/src/lib/image-tools-engine.test.ts
new file mode 100644
index 0000000..45c9a5f
--- /dev/null
+++ b/src/lib/image-tools-engine.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it, beforeEach, afterEach } from 'vitest'
+import { getImageToolsEngine, setImageToolsEngine, IMAGE_TOOL_ENGINES } from './image-tools-engine'
+
+/** Minimal localStorage stand-in — the module only uses getItem/setItem. */
+function memoryStorage(): Storage {
+ const map = new Map<string, string>()
+ return {
+ get length() {
+ return map.size
+ },
+ clear: () => map.clear(),
+ getItem: (k: string) => (map.has(k) ? (map.get(k) as string) : null),
+ key: () => null,
+ removeItem: (k: string) => void map.delete(k),
+ setItem: (k: string, v: string) => void map.set(k, v),
+ } as Storage
+}
+
+describe('image-tools-engine', () => {
+ let backing: Storage | undefined
+ const previous = (globalThis as { localStorage?: Storage }).localStorage
+
+ beforeEach(() => {
+ backing = memoryStorage()
+ ;(globalThis as { localStorage?: Storage }).localStorage = backing
+ })
+
+ afterEach(() => {
+ // restore whatever the environment had before the test (usually nothing
+ // — the vitest environment is node)
+ if (previous) (globalThis as { localStorage?: Storage }).localStorage = previous
+ else delete (globalThis as { localStorage?: Storage }).localStorage
+ })
+
+ it('defaults to provider — the user-requested default', () => {
+ expect(getImageToolsEngine()).toBe('provider')
+ })
+
+ it('defaults to provider when storage is unavailable (SSR / private mode)', () => {
+ delete (globalThis as { localStorage?: Storage }).localStorage
+ expect(getImageToolsEngine()).toBe('provider')
+ // set is a no-op, not a throw
+ expect(() => setImageToolsEngine('device')).not.toThrow()
+ })
+
+ it('round-trips an explicit device choice', () => {
+ setImageToolsEngine('device')
+ expect(getImageToolsEngine()).toBe('device')
+ // and back
+ setImageToolsEngine('provider')
+ expect(getImageToolsEngine()).toBe('provider')
+ })
+
+ it('ignores garbage values instead of throwing or switching', () => {
+ backing?.setItem('canvix.image-tools.engine', 'quantum')
+ expect(getImageToolsEngine()).toBe('provider')
+ backing?.setItem('canvix.image-tools.engine', '')
+ expect(getImageToolsEngine()).toBe('provider')
+ })
+
+ it('exposes exactly the two engines, provider first (UI order = default)', () => {
+ expect(IMAGE_TOOL_ENGINES.map((e) => e.id)).toEqual(['provider', 'device'])
+ expect(IMAGE_TOOL_ENGINES.every((e) => e.label.length > 0 && e.hint.length > 0)).toBe(true)
+ })
+})
diff --git a/src/lib/image-tools-engine.ts b/src/lib/image-tools-engine.ts
new file mode 100644
index 0000000..26d27e0
--- /dev/null
+++ b/src/lib/image-tools-engine.ts
@@ -0,0 +1,59 @@
+// ─────────────────────────────────────────────────────────────
+// Image-tools engine preference (v0.22, user request).
+//
+// The one-click image tools — BG remover and Upscale — have two
+// execution engines:
+//
+// 'provider' the configured image-edit AI provider does the work
+// server-side (default — no local compute, no model
+// download)
+// 'device' the local in-browser paths: the ONNX segmentation
+// cut-out (~40 MB model, downloaded once) and the
+// Lanczos-3 resampler (pure math, offline)
+//
+// The choice is a single per-browser preference shared by both tools,
+// persisted in localStorage. Server-side rendering and private-mode
+// failures degrade to the 'provider' default silently.
+// ─────────────────────────────────────────────────────────────
+
+export type ImageToolsEngine = 'provider' | 'device'
+
+const STORAGE_KEY = 'canvix.image-tools.engine'
+
+/** The engines shown in the tool popovers, in UI order. */
+export const IMAGE_TOOL_ENGINES: readonly { id: ImageToolsEngine; label: string; hint: string }[] = [
+ { id: 'provider', label: 'Provider', hint: 'AI provider — server-side, nothing downloads' },
+ { id: 'device', label: 'This device', hint: 'Runs locally in your browser — works offline' },
+] as const
+
+function storage(): Storage | null {
+ try {
+ const s = (globalThis as { localStorage?: Storage }).localStorage
+ return s && typeof s.getItem === 'function' ? s : null
+ } catch {
+ // SecurityError in some sandboxed contexts — behave as no storage
+ return null
+ }
+}
+
+/** Current engine — 'provider' unless the user explicitly chose 'device'. */
+export function getImageToolsEngine(): ImageToolsEngine {
+ const s = storage()
+ if (!s) return 'provider'
+ try {
+ return s.getItem(STORAGE_KEY) === 'device' ? 'device' : 'provider'
+ } catch {
+ return 'provider'
+ }
+}
+
+/** Persist the choice (no-op when storage is unavailable). */
+export function setImageToolsEngine(engine: ImageToolsEngine): void {
+ const s = storage()
+ if (!s) return
+ try {
+ s.setItem(STORAGE_KEY, engine)
+ } catch {
+ /* quota / private mode — the default stands for this session */
+ }
+}
diff --git a/src/lib/upscale.ts b/src/lib/upscale.ts
index 73eb773..5cc8aa0 100644
--- a/src/lib/upscale.ts
+++ b/src/lib/upscale.ts
@@ -152,3 +152,24 @@ export function lanczosUpscale(src: Raster, factor: number): Raster {
// vertical pass: dstW×H → dstW×dstH
return resampleAxis(mid, dstW, dstH, false)
}
+
+/**
+ * Resize to EXACT dimensions with the same separable Lanczos-3 kernel
+ * (v0.22: the provider upscale path lands on the tool's advertised
+ * target size after the provider's AI re-render, which snaps to its own
+ * supported sizes). Sides are rounded and clamped to 1..MAX_OUTPUT_SIDE;
+ * a no-op request returns a copy.
+ */
+export function lanczosResize(src: Raster, dstW: number, dstH: number): Raster {
+ if (src.width < 1 || src.height < 1) throw new Error('upscale: empty raster')
+ if (src.data.length < src.width * src.height * 4) throw new Error('upscale: data/size mismatch')
+ const w = Math.max(1, Math.min(MAX_OUTPUT_SIDE, Math.round(dstW)))
+ const h = Math.max(1, Math.min(MAX_OUTPUT_SIDE, Math.round(dstH)))
+ if (w === src.width && h === src.height) {
+ return { data: new Uint8ClampedArray(src.data), width: w, height: h }
+ }
+ // horizontal pass: W×H → w×H
+ const mid = resampleAxis(src, w, src.height, true)
+ // vertical pass: w×H → w×h
+ return resampleAxis(mid, w, h, false)
+}
diff --git a/tests/e2e/wave4-ai-powerup.spec.ts b/tests/e2e/wave4-ai-powerup.spec.ts
index 74d9e00..01b2128 100644
--- a/tests/e2e/wave4-ai-powerup.spec.ts
+++ b/tests/e2e/wave4-ai-powerup.spec.ts
@@ -351,11 +351,31 @@ test.describe('Wave 4 — AI Power-Up', () => {
await expect(page.getByRole('button', { name: 'Brush eraser' })).toBeVisible()
await expect(page.getByRole('button', { name: 'Alt text' })).toBeVisible()
- // run the REAL local upscaler — 2x on the 8×8 red square
+ // v0.22: the engine toggle — provider is the DEFAULT (user request);
+ // with no provider configured the upscale transparently runs on-device.
+ // The route is mocked to the NO_PROVIDER 503 shape so the test is
+ // deterministic on every host (dev machines may carry a .z-ai-config
+ // whose provider would otherwise answer — or refuse — for real).
+ await page.route('**/api/ai/image-edit', (route) =>
+ route.fulfill({
+ status: 503,
+ json: { error: 'This feature requires an AI provider configured on the server.', code: 'NO_PROVIDER' },
+ }),
+ )
await page.getByRole('button', { name: 'Upscale image' }).click()
+ const engineGroup = page.getByRole('group', { name: 'Engine — provider or this device' })
+ await expect(engineGroup).toBeVisible()
+ await expect(engineGroup.getByTestId('engine-provider')).toHaveAttribute('aria-pressed', 'true')
+ await expect(engineGroup.getByTestId('engine-device')).toHaveAttribute('aria-pressed', 'false')
+
+ // run the upscale with the default (provider) engine — no provider is
+ // configured in this suite, so the deterministic on-device pass runs
+ // and the toast says so; 2x on the 8×8 red square → 16×16
await page.getByRole('button', { name: /2× → 16px/ }).click()
await page.getByRole('button', { name: /Upscale to 16×16/ }).click()
- await expect(page.getByText('Upscaled 2×', { exact: true })).toBeVisible({ timeout: 30_000 })
+ await expect(page.getByText('Upscaled 2×', { exact: true }).first()).toBeVisible({ timeout: 30_000 })
+ // the toast's honest fallback note (aria-live mirrors the text, hence .first())
+ await expect(page.getByText(/No AI provider configured — enlarged on this device/).first()).toBeVisible()
// document truth: the element's natural size doubled (8 → 16)
await waitForDoc(