Skip to content

AI-native design editor. Open-source Figma alternative.

feat(ai): send tool images as WebP to providers that document it (#1641)

Danila Poyarkovdba9c60ec886
diff --git a/changes/1641/breaking.md b/changes/1641/breaking.md
new file mode 100644
index 000000000..0ed500129
--- /dev/null
+++ b/changes/1641/breaking.md
@@ -0,0 +1 @@
+- Hosts that serve CanvasKit's WASM themselves must serve `canvaskit-wasm/bin/full/canvaskit.wasm`: `getCanvasKit` from `@open-pencil/core/canvaskit` loads CanvasKit's full build, which encodes WebP and JPEG.
diff --git a/changes/1641/fixed.md b/changes/1641/fixed.md
new file mode 100644
index 000000000..c77398cde
--- /dev/null
+++ b/changes/1641/fixed.md
@@ -0,0 +1,3 @@
+- WEBP and JPEG export work on macOS desktop and in Safari.
+- Images from tools reach MiniMax, OpenPencil Cloud, and OpenAI-compatible Chat Completions models as images instead of Base64 text.
+- A resized WebP image attached in the chat on macOS desktop or in Safari is sent with its actual PNG type.
diff --git a/changes/1641/performance.md b/changes/1641/performance.md
new file mode 100644
index 000000000..d693b37ea
--- /dev/null
+++ b/changes/1641/performance.md
@@ -0,0 +1 @@
+- Images from tools such as `export_image` go to Anthropic, OpenAI, Google Gemini, and DeepSeek models as WebP, about a third the size of PNG for renders with imagery; other connections still get PNG.
diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.md
index ecec45d79..128830a8d 100644
--- a/packages/core/AGENTS.md
+++ b/packages/core/AGENTS.md
@@ -3,7 +3,7 @@
Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and document I/O. Depends on scene-graph, pen, kiwi, and fig. Framework-neutral: no Vue, no app imports, no browser DOM; guard browser globals explicitly.
- The root entry is the editor (`createEditor` and its types); every other domain is a subpath listed in `packages/core/package.json` `exports`. Add a subpath there rather than deep-importing, and never re-export another package's names.
-- CanvasKit runtime loading is centralized in `@open-pencil/core/canvaskit`. Headless raster export may dynamically load `canvaskit-wasm/full`; elsewhere `import type` and pass CanvasKit in.
+- CanvasKit runtime loading is centralized in `@open-pencil/core/canvaskit`, which loads the full build so every host encodes JPEG and WebP itself, as headless raster export's own `canvaskit-wasm/full` does; elsewhere `import type` and pass CanvasKit in (`packages/core/tests/io/formats/raster/pixels.test.ts`).
- Start a worker module with `new Worker(new URL('./worker.js', import.meta.url), { type: 'module' })`: the `.js` spelling reaches the `.ts` source under Vite and Bun and the built file in `dist`, where a `.ts` URL has nothing to load (`packages/core/src/layout/arrange/elk.ts`).
- Node-only helpers live under `@open-pencil/core/node/*`, which nothing browser code imports. Files the CLI, MCP server, and harness replace are written with `writeFileAtomic` from `@open-pencil/core/node/fs` rather than a hand-rolled temporary file and rename; only a document saved in place follows a symlink (`packages/core/tests/node/fs.test.ts`).
- Drawing and input share preview-aware geometry through `@open-pencil/core/geometry`, built on Scene Graph matrices. Use it for world/screen transforms, inverses, bounds, and handle placement.
diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.ts
index 522938f28..e94946e8f 100644
--- a/packages/core/src/canvas/renderer.ts
+++ b/packages/core/src/canvas/renderer.ts
@@ -1,5 +1,4 @@
import { isEqual } from 'es-toolkit'
-import { toUint8Array } from 'js-base64'
import type { SceneNode, SceneGraph, Fill, Stroke } from '@open-pencil/scene-graph'
import type { RenderColorSpace, ResolvedRenderColor } from '@open-pencil/scene-graph/color'
@@ -870,44 +869,6 @@ export class SkiaRenderer {
}
}
- /**
- * Browser fallback for raster formats CanvasKit cannot encode itself
- * (this build returns null from `encodeToBytes` for JPEG/WEBP). Routes the
- * RGBA pixels through an HTMLCanvasElement so `toDataURL` does the encoding.
- * Returns null outside the browser or if encoding fails.
- */
- encodeRasterFallback(
- pixels: Uint8Array,
- width: number,
- height: number,
- format: 'JPG' | 'WEBP',
- quality: number
- ): Uint8Array<ArrayBuffer> | null {
- if (!IS_BROWSER) return null
- try {
- const canvas = document.createElement('canvas')
- canvas.width = width
- canvas.height = height
- const ctx = canvas.getContext('2d')
- if (!ctx) return null
- const imageData = ctx.createImageData(width, height)
- imageData.data.set(pixels)
- ctx.putImageData(imageData, 0, 0)
- const mime = format === 'JPG' ? 'image/jpeg' : 'image/webp'
- const dataURL = canvas.toDataURL(mime, quality / 100)
- // Browsers silently return a PNG data URL when the requested encoder is
- // unsupported; reject that so we never write PNG bytes under a .jpg/.webp file.
- if (!dataURL.startsWith(`data:${mime}`)) return null
- const base64 = dataURL.split(',')[1]
- if (!base64) return null
- // js-base64 types its bytes as any buffer; a copy has the plain one a `Blob` takes.
- return new Uint8Array(toUint8Array(base64))
- } catch (err) {
- console.warn('Raster encode fallback failed:', err)
- return null
- }
- }
-
destroyed: boolean = false
destroy(): void {
diff --git a/packages/core/src/canvaskit.ts b/packages/core/src/canvaskit.ts
index ce92bf1e6..4730b0379 100644
--- a/packages/core/src/canvaskit.ts
+++ b/packages/core/src/canvaskit.ts
@@ -1,4 +1,4 @@
-import CanvasKitInit, { type CanvasKit } from 'canvaskit-wasm'
+import CanvasKitInit, { type CanvasKit } from 'canvaskit-wasm/full'
import { IS_BROWSER } from './constants'
@@ -17,14 +17,17 @@ export interface CanvasKitOptions {
}
let locator: CanvasKitLocator = (file) =>
- IS_BROWSER ? `/${file}` : new URL(file, import.meta.resolve('canvaskit-wasm')).href
+ IS_BROWSER ? `/${file}` : new URL(file, import.meta.resolve('canvaskit-wasm/full')).href
/** Points CanvasKit at the host's copy of its files. Call before the first {@link getCanvasKit}. */
export function setCanvasKitLocator(locate: CanvasKitLocator): void {
locator = locate
}
-/** Loads CanvasKit once; callers that ask while it loads share the load, and a failed load is retried. */
+/**
+ * Loads CanvasKit once; callers that ask while it loads share the load, and a failed load is
+ * retried. It is the full build, whose encoders write JPEG and WebP as well as PNG.
+ */
export function getCanvasKit(options?: CanvasKitOptions): Promise<CanvasKit> {
if (instance) return instance
const loading = CanvasKitInit({ locateFile: options?.locateFile ?? locator })
diff --git a/packages/core/src/io/formats/raster/index.ts b/packages/core/src/io/formats/raster/index.ts
index ba9fcbeec..f137aa9d1 100644
--- a/packages/core/src/io/formats/raster/index.ts
+++ b/packages/core/src/io/formats/raster/index.ts
@@ -8,6 +8,11 @@ export {
type ExportFormat
} from './render'
export { initCanvasKit, headlessRenderNodes, headlessRenderThumbnail } from './headless'
-export { createCanvasKitRasterCodec, type RasterCodec, type RGBAImage } from './pixels'
+export {
+ createCanvasKitRasterCodec,
+ reencodeImage,
+ type RasterCodec,
+ type RGBAImage
+} from './pixels'
export { comparePNGs, type PixelComparison, type PixelComparisonOptions } from './compare'
export { renderRegionToImage, type RegionRenderOptions } from './region'
diff --git a/packages/core/src/io/formats/raster/pixels.ts b/packages/core/src/io/formats/raster/pixels.ts
index 859ea6563..f59e78cca 100644
--- a/packages/core/src/io/formats/raster/pixels.ts
+++ b/packages/core/src/io/formats/raster/pixels.ts
@@ -1,5 +1,7 @@
import type { CanvasKit } from 'canvaskit-wasm'
+import type { ExportFormat, RasterExportFormat } from './render'
+
/** Unpremultiplied sRGB RGBA pixels, row-major with no padding. */
export interface RGBAImage {
width: number
@@ -49,3 +51,31 @@ export function createCanvasKitRasterCodec(ck: CanvasKit): RasterCodec {
}
}
}
+
+export function ckImageFormat(ck: CanvasKit, format: ExportFormat) {
+ switch (format) {
+ case 'JPG':
+ return ck.ImageFormat.JPEG
+ case 'WEBP':
+ return ck.ImageFormat.WEBP
+ default:
+ return ck.ImageFormat.PNG
+ }
+}
+
+/** Encodes an encoded image, such as a PNG, again as `format`; null when CanvasKit cannot. */
+export function reencodeImage(
+ ck: CanvasKit,
+ bytes: Uint8Array,
+ format: RasterExportFormat,
+ quality: number
+): Uint8Array | null {
+ const image = ck.MakeImageFromEncoded(bytes)
+ if (!image) return null
+ try {
+ const encoded = image.encodeToBytes(ckImageFormat(ck, format), quality)
+ return encoded ? new Uint8Array(encoded) : null
+ } finally {
+ image.delete()
+ }
+}
diff --git a/packages/core/src/io/formats/raster/render.ts b/packages/core/src/io/formats/raster/render.ts
index 1559e7ea0..36f3c96fd 100644
--- a/packages/core/src/io/formats/raster/render.ts
+++ b/packages/core/src/io/formats/raster/render.ts
@@ -10,6 +10,8 @@ import type { SkiaRenderer } from '#core/canvas'
import { getPageColor } from '#core/figma-api/page-backgrounds'
import { extractExportGraph, findPageId } from '#core/io/subgraph'
+import { ckImageFormat } from './pixels'
+
export type RasterExportFormat = 'PNG' | 'JPG' | 'WEBP'
export type ExportFormat = RasterExportFormat | 'SVG'
@@ -33,17 +35,6 @@ export function computeContentBounds(graph: SceneGraph, nodeIds: string[]) {
)
}
-function ckImageFormat(ck: CanvasKit, format: ExportFormat) {
- switch (format) {
- case 'JPG':
- return ck.ImageFormat.JPEG
- case 'WEBP':
- return ck.ImageFormat.WEBP
- default:
- return ck.ImageFormat.PNG
- }
-}
-
function findAlphaBounds(ck: CanvasKit, canvas: Canvas, width: number, height: number) {
const pixels = canvas.readPixels(0, 0, {
alphaType: ck.AlphaType.Unpremul,
@@ -177,34 +168,7 @@ function renderToSurface(
])
: downsampleSurface.makeImageSnapshot()
const encoded = image.encodeToBytes(ckImageFormat(ck, format), quality)
- let resultBytes: Uint8Array<ArrayBuffer> | null = encoded ? new Uint8Array(encoded) : null
-
- // CanvasKit's `encodeToBytes` returns null for JPEG/WEBP in this build, so
- // fall back to encoding the raw pixels through the browser canvas.
- if (!resultBytes && (format === 'JPG' || format === 'WEBP')) {
- const exportWidth = alphaBounds ? alphaBounds.maxX - alphaBounds.minX : width
- const exportHeight = alphaBounds ? alphaBounds.maxY - alphaBounds.minY : height
- const exportMinX = alphaBounds ? alphaBounds.minX : 0
- const exportMinY = alphaBounds ? alphaBounds.minY : 0
-
- const rawPixels = downsampleCanvas.readPixels(exportMinX, exportMinY, {
- alphaType: ck.AlphaType.Unpremul,
- colorType: ck.ColorType.RGBA_8888,
- colorSpace: ck.ColorSpace.SRGB,
- width: exportWidth,
- height: exportHeight
- })
-
- if (rawPixels instanceof Uint8Array) {
- resultBytes = renderer.encodeRasterFallback(
- rawPixels,
- exportWidth,
- exportHeight,
- format,
- quality
- )
- }
- }
+ const resultBytes = encoded ? new Uint8Array(encoded) : null
image.delete()
downsampleSurface.delete()
diff --git a/packages/core/src/tools/ai-adapter.ts b/packages/core/src/tools/ai-adapter.ts
index 16f58f317..d25366362 100644
--- a/packages/core/src/tools/ai-adapter.ts
+++ b/packages/core/src/tools/ai-adapter.ts
@@ -61,6 +61,17 @@ export interface AIAdapterOptions {
onFlashNodes?: (nodeIds: string[]) => void
onToolLog?: (entry: ToolLogEntry) => void
getStepBudget?: () => StepBudget
+ /**
+ * Encodes a tool's image again for the model, such as a PNG as WebP for a provider that takes
+ * it. The result keeps the tool's own image, so another connection can still be sent that one.
+ */
+ encodeModelImage?: (image: ModelImage) => Promise<ModelImage>
+}
+
+export interface ModelImage {
+ /** Base64. */
+ data: string
+ mediaType: string
}
const STEP_WARNING_THRESHOLD = 5
@@ -174,6 +185,21 @@ export function toolsToAI(
): ToolSet {
const { tool } = deps
const result: ToolSet = {}
+ // Every request sends the whole conversation, so each image is encoded once, not per request.
+ const encodedImages = new Map<string, Promise<ModelImage>>()
+ const modelImage = (toolCallId: string, image: ModelImage): Promise<ModelImage> => {
+ const { encodeModelImage } = options
+ if (!encodeModelImage) return Promise.resolve(image)
+ let encoded = encodedImages.get(toolCallId)
+ if (!encoded) {
+ encoded = encodeModelImage(image).catch((error: unknown) => {
+ console.warn('[AI] Sending a tool image as the tool returned it:', error)
+ return image
+ })
+ encodedImages.set(toolCallId, encoded)
+ }
+ return encoded
+ }
for (const def of tools) {
if (!isToolExposed(def, 'ai')) continue
@@ -225,13 +251,23 @@ export function toolsToAI(
// Image results reach the model as files, with their metadata as text. Typed against the
// SDK, because a shape it does not know fails the next step's prompt validation.
- toolOpts.toModelOutput = ({ output }: { output: unknown }): ToolResultPart['output'] => {
+ toolOpts.toModelOutput = async ({
+ toolCallId,
+ output
+ }: {
+ toolCallId: string
+ output: unknown
+ }): Promise<ToolResultPart['output']> => {
if (isImageOutput(output)) {
const { base64, mimeType, ...metadata } = output
+ const { data, mediaType } = await modelImage(toolCallId, {
+ data: base64,
+ mediaType: mimeType
+ })
const image = {
type: 'file' as const,
- mediaType: mimeType,
- data: { type: 'data' as const, data: base64 }
+ mediaType,
+ data: { type: 'data' as const, data }
}
return !isEmptyObject(metadata)
? {
diff --git a/packages/core/src/tools/index.ts b/packages/core/src/tools/index.ts
index fd8362f85..89b0eaf68 100644
--- a/packages/core/src/tools/index.ts
+++ b/packages/core/src/tools/index.ts
@@ -27,7 +27,13 @@ export {
} from './schema'
export { toolNumber } from './schema'
export { toolsToAI, buildDebugLog } from './ai-adapter'
-export type { ToolLogEntry, ToolDebugLog, AIAdapterOptions, StepBudget } from './ai-adapter'
+export type {
+ ToolLogEntry,
+ ToolDebugLog,
+ AIAdapterOptions,
+ ModelImage,
+ StepBudget
+} from './ai-adapter'
export {
calcClusterConfidence,
compileScript,
diff --git a/packages/core/tests/io/formats/raster/pixels.test.ts b/packages/core/tests/io/formats/raster/pixels.test.ts
new file mode 100644
index 000000000..a7077e067
--- /dev/null
+++ b/packages/core/tests/io/formats/raster/pixels.test.ts
@@ -0,0 +1,48 @@
+import { expect, setDefaultTimeout, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { getCanvasKit } from '@open-pencil/core/canvaskit'
+import { createCanvasKitRasterCodec, reencodeImage } from '@open-pencil/core/io/formats/raster'
+
+setDefaultTimeout(60_000)
+
+/** A half-transparent gradient, so lossy encoders have colour and alpha to keep. */
+function gradientPNG(codec: ReturnType<typeof createCanvasKitRasterCodec>) {
+ const width = 64
+ const height = 32
+ const data = new Uint8Array(width * height * 4)
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ data.set([x * 4, y * 8, 128, x < width / 2 ? 255 : 128], (y * width + x) * 4)
+ }
+ }
+ return expectDefined(codec.encodePNG({ width, height, data }), 'PNG')
+}
+
+test('the shared CanvasKit encodes a PNG again as WebP, keeping its size and transparency', async () => {
+ const ck = await getCanvasKit()
+ const codec = createCanvasKitRasterCodec(ck)
+ const webp = expectDefined(reencodeImage(ck, gradientPNG(codec), 'WEBP', 90), 'WebP')
+
+ expect(new TextDecoder().decode(webp.subarray(8, 12))).toBe('WEBP')
+ const image = expectDefined(codec.decode(webp), 'decoded WebP')
+ expect([image.width, image.height]).toEqual([64, 32])
+ const right = (16 * 64 + 48) * 4 + 3
+ expect(image.data[right]).toBeGreaterThan(120)
+ expect(image.data[right]).toBeLessThan(136)
+})
+
+test('the shared CanvasKit encodes JPEG', async () => {
+ const ck = await getCanvasKit()
+ const jpeg = expectDefined(
+ reencodeImage(ck, gradientPNG(createCanvasKitRasterCodec(ck)), 'JPG', 90),
+ 'JPEG'
+ )
+
+ expect([...jpeg.subarray(0, 3)]).toEqual([0xff, 0xd8, 0xff])
+})
+
+test('an image CanvasKit cannot decode is not encoded', async () => {
+ expect(reencodeImage(await getCanvasKit(), new Uint8Array([1, 2, 3]), 'WEBP', 90)).toBeNull()
+})
diff --git a/packages/core/tests/tools/ai-adapter.test.ts b/packages/core/tests/tools/ai-adapter.test.ts
index 323dfd6fd..8abf0b64b 100644
--- a/packages/core/tests/tools/ai-adapter.test.ts
+++ b/packages/core/tests/tools/ai-adapter.test.ts
@@ -4,7 +4,12 @@ import { toolModelMessageSchema } from 'ai'
import * as v from 'valibot'
import { FigmaAPI } from '@open-pencil/core/figma-api'
-import { defineTool, toolsToAI, type ToolLogEntry } from '@open-pencil/core/tools'
+import {
+ defineTool,
+ toolsToAI,
+ type AIAdapterOptions,
+ type ToolLogEntry
+} from '@open-pencil/core/tools'
import { SceneGraph } from '@open-pencil/scene-graph'
type ToolFactory = Parameters<typeof toolsToAI>[2]['tool']
@@ -13,10 +18,13 @@ type ToolFactory = Parameters<typeof toolsToAI>[2]['tool']
const tool = ((definition: unknown) => definition) as ToolFactory
type ModelOutputTool = {
- toModelOutput(options: { output: unknown }): unknown
+ toModelOutput(options: { toolCallId: string; output: unknown }): Promise<unknown>
}
-function adapt(output: unknown): ModelOutputTool {
+function adapt(
+ output: unknown,
+ encodeModelImage?: AIAdapterOptions['encodeModelImage']
+): ModelOutputTool {
const def = defineTool({
name: 'image_tool',
description: 'Returns a fixed result',
@@ -25,7 +33,7 @@ function adapt(output: unknown): ModelOutputTool {
execute: () => output
})
const figma = new FigmaAPI(new SceneGraph())
- const tools = toolsToAI([def], { getFigma: () => figma }, { tool })
+ const tools = toolsToAI([def], { getFigma: () => figma, encodeModelImage }, { tool })
const adapted: unknown = tools.image_tool
if (!hasModelOutput(adapted)) throw new Error('image_tool has no toModelOutput')
return adapted
@@ -41,9 +49,9 @@ function hasModelOutput(value: unknown): value is ModelOutputTool {
}
describe('AI adapter model output', () => {
- test('sends any image result as a file with its metadata as text', () => {
+ test('sends any image result as a file with its metadata as text', async () => {
const output = { mimeType: 'image/png', base64: 'AAAA', changedPixels: 12 }
- expect(adapt(output).toModelOutput({ output })).toEqual({
+ expect(await adapt(output).toModelOutput({ toolCallId: 'call', output })).toEqual({
type: 'content',
value: [
{ type: 'text', text: '{"changedPixels":12}' },
@@ -56,7 +64,7 @@ describe('AI adapter model output', () => {
{ mimeType: 'image/png', base64: 'AAAA', changedPixels: 12 },
{ mimeType: 'image/png', base64: 'AAAA' },
{ mimeType: 'application/pdf', base64: 'AAAA' }
- ])('produces a tool message the AI SDK accepts in the next prompt (%p)', (output) => {
+ ])('produces a tool message the AI SDK accepts in the next prompt (%p)', async (output) => {
const message = {
role: 'tool',
content: [
@@ -64,16 +72,50 @@ describe('AI adapter model output', () => {
type: 'tool-result',
toolCallId: 'call',
toolName: 'image_tool',
- output: adapt(output).toModelOutput({ output })
+ output: await adapt(output).toModelOutput({ toolCallId: 'call', output })
}
]
}
expect(toolModelMessageSchema.safeParse(message).success).toBe(true)
})
- test('keeps non-image results as JSON', () => {
+ test('keeps non-image results as JSON', async () => {
const output = { mimeType: 'application/pdf', base64: 'AAAA' }
- expect(adapt(output).toModelOutput({ output })).toEqual({ type: 'json', value: output })
+ expect(await adapt(output).toModelOutput({ toolCallId: 'call', output })).toEqual({
+ type: 'json',
+ value: output
+ })
+ })
+
+ test('sends the image the connection encodes, once per tool call', async () => {
+ const output = { mimeType: 'image/png', base64: 'AAAA' }
+ const encoded: string[] = []
+ const adapted = adapt(output, async (image) => {
+ encoded.push(image.data)
+ return { data: 'BBBB', mediaType: 'image/webp' }
+ })
+ const file = {
+ type: 'file',
+ mediaType: 'image/webp',
+ data: { type: 'data', data: 'BBBB' }
+ }
+ expect(await adapted.toModelOutput({ toolCallId: 'call', output })).toEqual({
+ type: 'content',
+ value: [file]
+ })
+ // Every request sends the conversation again; its images are not encoded again.
+ await adapted.toModelOutput({ toolCallId: 'call', output })
+ await adapted.toModelOutput({ toolCallId: 'other', output })
+ expect(encoded).toEqual(['AAAA', 'AAAA'])
+ })
+
+ test('sends the tool image when encoding it fails', async () => {
+ const output = { mimeType: 'image/png', base64: 'AAAA' }
+ const adapted = adapt(output, () => Promise.reject(new Error('no encoder')))
+ expect(await adapted.toModelOutput({ toolCallId: 'call', output })).toEqual({
+ type: 'content',
+ value: [{ type: 'file', mediaType: 'image/png', data: { type: 'data', data: 'AAAA' } }]
+ })
})
})
diff --git a/packages/docs/development/ai-chat.md b/packages/docs/development/ai-chat.md
index bf0841537..474d46f3d 100644
--- a/packages/docs/development/ai-chat.md
+++ b/packages/docs/development/ai-chat.md
@@ -48,6 +48,17 @@ Every call of an OpenPencil tool, from the chat, a coding agent through MCP, or
- A call's result reaches the model as JSON. `eval` converts what a script returns, as MCP and the CLI print it.
- If you undid or redid the run's own edits since the model last heard, the result carries an `undoNote` saying so.
+## Images a tool returns
+
+An image a call returns, such as `export_image`'s, reaches the model as a file, and every request sends the whole conversation again. On a connection whose provider documents WebP input itself (Anthropic, OpenAI, Google Gemini, and DeepSeek: `webpImages` in `providers/registry.ts`, each beside its documentation link), a PNG goes as WebP at quality 90 (`tools/model-image.ts`), unless the WebP comes out larger, as it can for flat renders.
+
+- Measured at the 1280 px default edge on design renders: flat UI is 14–20 KB as PNG and barely smaller as WebP; renders with imagery are 197–289 KB as PNG and 61–86 KB as WebP, at SSIM 0.984–0.995 against the PNG, with small text as legible.
+- Only a provider's own documentation counts. An Anthropic- or OpenAI-compatible endpoint, OpenRouter, Z.ai, MiniMax, ChatGPT sign-in, and Cloud may forward to a model server that cannot decode WebP (llama.cpp's server reads images with stb_image, which has none), so they get PNG.
+- JPEG is never chosen for the model: our export paints transparent pixels black.
+- Core's adapter encodes the image as each request is built (`encodeModelImage` in `tools/ai-adapter.ts`), once per tool call, and the result keeps the tool's PNG, so a conversation continued on a PNG-only connection still sends PNG.
+- The app loads CanvasKit's full build, which encodes WebP and JPEG, because a WebView cannot be relied on: WKWebView answers a canvas asked for WebP with PNG.
+- Chat Completions takes only text in a tool message, and the AI SDK sends a tool's image there as its Base64 text. On the connections that use it (MiniMax, Cloud, and an OpenAI-compatible endpoint set to Chat Completions), `providers/tool-images.ts` moves each image into a user message after the step's tool results, as opencode does. The same history always gives the same messages, so cached prefixes still match.
+
## A reply ends
A run ends once, in one of three ways: finished (`onFinish`), failed (`handleError`), or stopped (the request's abort signal). The agent goes idle and its cursor leaves the canvas. A tool already running keeps going: its edit lands in its run, but cannot move the agent again.
diff --git a/packages/vue/example/src/main.ts b/packages/vue/example/src/main.ts
index 620ea470b..b0f7c17cf 100644
--- a/packages/vue/example/src/main.ts
+++ b/packages/vue/example/src/main.ts
@@ -1,4 +1,4 @@
-import canvasKitWasm from 'canvaskit-wasm/bin/canvaskit.wasm?url'
+import canvasKitWasm from 'canvaskit-wasm/bin/full/canvaskit.wasm?url'
import { createApp } from 'vue'
import { setCanvasKitLocator } from '@open-pencil/core/canvaskit'
diff --git a/src/app/ai/attachment/image/prepare.ts b/src/app/ai/attachment/image/prepare.ts
index b894bfd2f..55a99c7cf 100644
--- a/src/app/ai/attachment/image/prepare.ts
+++ b/src/app/ai/attachment/image/prepare.ts
@@ -135,8 +135,9 @@ export async function prepareImageAttachment(
if (!isImageAttachmentMediaType(file.type)) {
throw new Error('Choose a PNG, JPEG, or WebP image.')
}
- const mediaType = file.type
- const blob = await canvasToBlob(canvas, mediaType, mediaType === 'image/png' ? undefined : 0.88)
+ const blob = await canvasToBlob(canvas, file.type, file.type === 'image/png' ? undefined : 0.88)
+ // A browser that cannot encode the type asked for, such as WebKit with WebP, returns a PNG.
+ const mediaType = isImageAttachmentMediaType(blob.type) ? blob.type : 'image/png'
return {
data: new Uint8Array(await blob.arrayBuffer()),
diff --git a/src/app/ai/providers/compatible.ts b/src/app/ai/providers/compatible.ts
index ac8f54beb..97aacacad 100644
--- a/src/app/ai/providers/compatible.ts
+++ b/src/app/ai/providers/compatible.ts
@@ -1,8 +1,10 @@
import { createAnthropic } from '@ai-sdk/anthropic'
import { createOpenAI } from '@ai-sdk/openai'
+import { wrapLanguageModel } from 'ai'
import { IS_TAURI } from '@open-pencil/core/constants'
+import { toolImagesInUserMessage } from '@/app/ai/providers/tool-images'
import type { ModelConfig, ModelProviderAdapter } from '@/app/ai/providers/types'
// Anthropic omits CORS headers unless the caller opts in, so browser requests fail with an
@@ -14,10 +16,12 @@ export type CompatibleEndpoint = string | ((config: ModelConfig) => string)
type OpenAICompatibleOptions = {
baseURL?: CompatibleEndpoint
mode?: 'default' | 'chat' | 'configurable'
+ webpImages?: boolean
}
type AnthropicCompatibleOptions = {
baseURL?: CompatibleEndpoint
+ webpImages?: boolean
}
function resolveEndpoint(endpoint: CompatibleEndpoint | undefined, config: ModelConfig) {
@@ -35,14 +39,15 @@ export function createOpenAICompatibleAdapter(
fetch: runtime.fetch
})
const modelID = config.customModelID.trim() || config.modelID
- if (options.mode === 'chat') return provider.chat(modelID)
+ const chat = () =>
+ wrapLanguageModel({ model: provider.chat(modelID), middleware: toolImagesInUserMessage })
+ if (options.mode === 'chat') return chat()
if (options.mode === 'configurable') {
- return config.customAPIType === 'responses'
- ? provider.responses(modelID)
- : provider.chat(modelID)
+ return config.customAPIType === 'responses' ? provider.responses(modelID) : chat()
}
return provider(modelID)
- }
+ },
+ webpImages: options.webpImages
}
}
@@ -58,6 +63,7 @@ export function createAnthropicCompatibleAdapter(
headers: IS_TAURI ? undefined : BROWSER_ACCESS_HEADERS
})
return provider(config.customModelID.trim() || config.modelID)
- }
+ },
+ webpImages: options.webpImages
}
}
diff --git a/src/app/ai/providers/registry.ts b/src/app/ai/providers/registry.ts
index 16128d135..e7c831a6e 100644
--- a/src/app/ai/providers/registry.ts
+++ b/src/app/ai/providers/registry.ts
@@ -27,20 +27,26 @@ const MODEL_PROVIDER_ADAPTERS = {
return provider(config.customModelID.trim() || config.modelID)
}
},
- anthropic: createAnthropicCompatibleAdapter(),
- openai: createOpenAICompatibleAdapter(),
+ // WebP: https://platform.claude.com/docs/en/build-with-claude/vision#supported-formats
+ anthropic: createAnthropicCompatibleAdapter({ webpImages: true }),
+ // WebP: https://developers.openai.com/api/docs/guides/images-vision
+ openai: createOpenAICompatibleAdapter({ webpImages: true }),
chatgpt: chatGPTAdapter,
google: {
create(config, runtime) {
return createGoogleGenerativeAI({ apiKey: config.apiKey, fetch: runtime.fetch })(
config.modelID
)
- }
+ },
+ // https://ai.google.dev/gemini-api/docs/image-understanding
+ webpImages: true
},
deepseek: {
create(config, runtime) {
return createDeepSeek({ apiKey: config.apiKey, fetch: runtime.fetch })(config.modelID)
- }
+ },
+ // https://api-docs.deepseek.com/guides/vision
+ webpImages: true
},
zai: createAnthropicCompatibleAdapter({ baseURL: 'https://api.z.ai/api/anthropic' }),
minimax: createOpenAICompatibleAdapter({ baseURL: 'https://api.minimax.io/v1', mode: 'chat' }),
@@ -62,6 +68,11 @@ function isDirectProviderID(providerID: AIProviderID): providerID is DirectProvi
return !providerID.startsWith('acp:') && providerID !== 'harness:pi'
}
+/** Whether tool images reach the provider's models as WebP; see `ModelProviderAdapter.webpImages`. */
+export function providerTakesWebPImages(providerID: AIProviderID): boolean {
+ return isDirectProviderID(providerID) && modelProviderAdapter(providerID).webpImages === true
+}
+
export function modelProviderAdapter(providerID: AIProviderID): ModelProviderAdapter {
if (!isDirectProviderID(providerID)) {
throw new Error('ACP providers and Harness agents do not use direct API models')
diff --git a/src/app/ai/providers/tool-images.ts b/src/app/ai/providers/tool-images.ts
new file mode 100644
index 000000000..5f8d3ffaf
--- /dev/null
+++ b/src/app/ai/providers/tool-images.ts
@@ -0,0 +1,57 @@
+import type { LanguageModelMiddleware } from 'ai'
+import { partition } from 'es-toolkit'
+
+type Prompt = Parameters<
+ NonNullable<LanguageModelMiddleware['transformParams']>
+>[0]['params']['prompt']
+type PromptMessage = Prompt[number]
+type ToolContent = Extract<PromptMessage, { role: 'tool' }>['content'][number]
+type UserContent = Extract<PromptMessage, { role: 'user' }>['content'][number]
+type ContentOutputPart = Extract<
+ Extract<ToolContent, { type: 'tool-result' }>['output'],
+ { type: 'content' }
+>['value'][number]
+type ImagePart = Extract<ContentOutputPart, { type: 'file' }>
+
+function isImagePart(part: ContentOutputPart): part is ImagePart {
+ return part.type === 'file' && part.mediaType.startsWith('image/')
+}
+
+/**
+ * Chat Completions takes only text in a tool message, so the AI SDK sends a tool's image there as
+ * its Base64 text. This moves each image into a user message after the step's tool results, as
+ * opencode does; the same history always gives the same messages, so cached prefixes still match.
+ */
+export const toolImagesInUserMessage: LanguageModelMiddleware = {
+ transformParams: async ({ params }) => {
+ const prompt: Prompt = []
+ for (const message of params.prompt) {
+ if (message.role !== 'tool') {
+ prompt.push(message)
+ continue
+ }
+ const images: UserContent[] = []
+ const content = message.content.map((part): ToolContent => {
+ if (part.type !== 'tool-result' || part.output.type !== 'content') return part
+ const [moved, rest] = partition(part.output.value, isImagePart)
+ if (moved.length === 0) return part
+ images.push(
+ { type: 'text', text: `Images from the ${part.toolName} call ${part.toolCallId}:` },
+ ...moved.map(({ data, mediaType, filename }) => ({
+ type: 'file' as const,
+ data,
+ mediaType,
+ filename
+ }))
+ )
+ // Text alone goes as text; a content list would be sent as its JSON.
+ const text = rest.flatMap((item) => (item.type === 'text' ? [item.text] : []))
+ text.push('The images follow in the next user message.')
+ return { ...part, output: { type: 'text', value: text.join('\n') } }
+ })
+ prompt.push({ ...message, content })
+ if (images.length > 0) prompt.push({ role: 'user', content: images })
+ }
+ return { ...params, prompt }
+ }
+}
diff --git a/src/app/ai/providers/types.ts b/src/app/ai/providers/types.ts
index 7ead1ff0e..0bc140bbc 100644
--- a/src/app/ai/providers/types.ts
+++ b/src/app/ai/providers/types.ts
@@ -27,4 +27,9 @@ export type ModelProviderRuntime = {
export interface ModelProviderAdapter {
create(config: ModelConfig, runtime: ModelProviderRuntime): LanguageModel
+ /**
+ * The provider documents WebP image input, so tool images reach its models as WebP. Set only
+ * from the provider's own documentation; see `development/ai-chat.md`.
+ */
+ webpImages?: boolean
}
diff --git a/src/app/ai/tools/index.ts b/src/app/ai/tools/index.ts
index abd3bded9..070d77d7f 100644
--- a/src/app/ai/tools/index.ts
+++ b/src/app/ai/tools/index.ts
@@ -2,7 +2,12 @@ import { tool } from 'ai'
import { isPlainObject } from 'es-toolkit'
import { graphFromPageSnapshot } from '@open-pencil/core'
-import { registerComponentCatalog, isAtomicTool, toolsToAI } from '@open-pencil/core/tools'
+import {
+ registerComponentCatalog,
+ isAtomicTool,
+ toolsToAI,
+ type AIAdapterOptions
+} from '@open-pencil/core/tools'
import {
currentRun,
@@ -41,7 +46,11 @@ function withUndoNote(result: unknown, note: string): unknown {
return isPlainObject(result) ? { ...result, undoNote: note } : { result, undoNote: note }
}
-export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnosticContext) {
+export function createAITools(
+ store: EditorStore,
+ diagnosticContext?: AIDiagnosticContext,
+ encodeModelImage?: AIAdapterOptions['encodeModelImage']
+) {
const libraryService = useLibraryService()
libraryService.bindEditor(store)
registerComponentCatalog(store.graph, libraryService)
@@ -91,7 +100,8 @@ export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnost
entry.cause
)
},
- getStepBudget: () => stepBudget(store)
+ getStepBudget: () => stepBudget(store),
+ encodeModelImage
},
{ tool }
)
diff --git a/src/app/ai/tools/model-image.ts b/src/app/ai/tools/model-image.ts
new file mode 100644
index 000000000..526da83f9
--- /dev/null
+++ b/src/app/ai/tools/model-image.ts
@@ -0,0 +1,21 @@
+import { fromUint8Array, toUint8Array } from 'js-base64'
+
+import { getCanvasKit } from '@open-pencil/core/canvaskit'
+import { reencodeImage } from '@open-pencil/core/io/formats/raster'
+import type { ModelImage } from '@open-pencil/core/tools'
+
+/** The export default for WebP, measured on design renders against their PNGs in `ai-chat.md`. */
+const WEBP_QUALITY = 90
+
+/**
+ * A tool's PNG as WebP, for a provider that documents WebP input. The PNG stays when it is the
+ * smaller of the two, as flat renders can be, or when the image is not a PNG.
+ */
+export async function encodeWebPModelImage(image: ModelImage): Promise<ModelImage> {
+ if (image.mediaType !== 'image/png') return image
+ const png = toUint8Array(image.data)
+ const webp = reencodeImage(await getCanvasKit(), png, 'WEBP', WEBP_QUALITY)
+ return webp && webp.length < png.length
+ ? { data: fromUint8Array(webp), mediaType: 'image/webp' }
+ : image
+}
diff --git a/src/app/ai/transports/tool-loop.ts b/src/app/ai/transports/tool-loop.ts
index f645e026e..d7adbc6f6 100644
--- a/src/app/ai/transports/tool-loop.ts
+++ b/src/app/ai/transports/tool-loop.ts
@@ -13,6 +13,7 @@ import { promptCachingOptions } from '@/app/ai/models/caching'
import { reasoningCallSettings, type AIProviderOptions } from '@/app/ai/models/reasoning/settings'
import type { ThinkingLevel } from '@/app/ai/models/types'
import { createRunPreview } from '@/app/ai/preview/run'
+import { providerTakesWebPImages } from '@/app/ai/providers/registry'
import { skillCatalog } from '@/app/ai/skills/catalog'
import { appSkillLibrary, type SkillLibrary } from '@/app/ai/skills/library'
import { createSkillTools, SKILL_TOOL_NAMES } from '@/app/ai/skills/tools'
@@ -25,6 +26,7 @@ import {
type AITools
} from '@/app/ai/tools'
import { enabledAIToolDefinitions } from '@/app/ai/tools/catalog'
+import { encodeWebPModelImage } from '@/app/ai/tools/model-image'
import { aiToolOverrides } from '@/app/ai/tools/preferences'
import { recordModelStepCompleted } from '@/app/diagnostics/events'
import type { AIDiagnosticContext } from '@/app/diagnostics/events/ai'
@@ -87,7 +89,11 @@ export function createToolLoopTransport({
yieldWhen = () => false
}: ToolLoopTransportOptions) {
const tools: AITools = {
- ...createAITools(store, diagnosticContext),
+ ...createAITools(
+ store,
+ diagnosticContext,
+ providerTakesWebPImages(providerID) ? encodeWebPModelImage : undefined
+ ),
...createSkillTools(() => offeredSkills)
}
// Read again for each message, so skills installed or switched off since apply to the next one.
diff --git a/src/app/editor/canvas/canvaskit.ts b/src/app/editor/canvas/canvaskit.ts
index 56f7a7ab5..cce262073 100644
--- a/src/app/editor/canvas/canvaskit.ts
+++ b/src/app/editor/canvas/canvaskit.ts
@@ -1,4 +1,4 @@
-import canvasKitWasm from 'canvaskit-wasm/bin/canvaskit.wasm?url'
+import canvasKitWasm from 'canvaskit-wasm/bin/full/canvaskit.wasm?url'
import { getCanvasKit, setCanvasKitLocator } from '@open-pencil/core/canvaskit'
diff --git a/tests/app/ai/tools/model-image.test.ts b/tests/app/ai/tools/model-image.test.ts
new file mode 100644
index 000000000..3e4739553
--- /dev/null
+++ b/tests/app/ai/tools/model-image.test.ts
@@ -0,0 +1,54 @@
+import { expect, setDefaultTimeout, test } from 'bun:test'
+
+import { fromUint8Array, toUint8Array } from 'js-base64'
+
+import { getCanvasKit } from '@open-pencil/core/canvaskit'
+import { createCanvasKitRasterCodec } from '@open-pencil/core/io/formats/raster'
+
+import { encodeWebPModelImage } from '@/app/ai/tools/model-image'
+
+setDefaultTimeout(60_000)
+
+async function png(pixel: (x: number, y: number) => number[]) {
+ const size = 128
+ const data = new Uint8Array(size * size * 4)
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) data.set(pixel(x, y), (y * size + x) * 4)
+ }
+ const bytes = createCanvasKitRasterCodec(await getCanvasKit()).encodePNG({
+ width: size,
+ height: size,
+ data
+ })
+ if (!bytes) throw new Error('PNG was not encoded')
+ return { data: fromUint8Array(bytes), mediaType: 'image/png' }
+}
+
+/** Continuous tone, like a photo in a render, which PNG stores poorly. */
+const wave = (x: number, y: number) =>
+ [
+ 128 + 127 * Math.sin(x / 5) * Math.cos(y / 7),
+ 128 + 127 * Math.sin((x + y) / 9),
+ 128 + 127 * Math.cos((x * y) / 400),
+ 255
+ ].map(Math.round)
+
+test('sends a PNG render as a smaller WebP', async () => {
+ const image = await png(wave)
+ const encoded = await encodeWebPModelImage(image)
+
+ expect(encoded.mediaType).toBe('image/webp')
+ expect(toUint8Array(encoded.data).length).toBeLessThan(toUint8Array(image.data).length)
+})
+
+test('keeps a PNG that is smaller than its WebP', async () => {
+ const image = await png((x, y) => ((x + y) % 2 ? [0, 0, 0, 255] : [255, 255, 255, 255]))
+
+ expect(await encodeWebPModelImage(image)).toEqual(image)
+})
+
+test('keeps an image that is not a PNG', async () => {
+ const image = { data: 'AAAA', mediaType: 'image/jpeg' }
+
+ expect(await encodeWebPModelImage(image)).toEqual(image)
+})
diff --git a/tests/engine/app/ai/model/providers.test.ts b/tests/engine/app/ai/model/providers.test.ts
index d434f1b61..f3c05db8f 100644
--- a/tests/engine/app/ai/model/providers.test.ts
+++ b/tests/engine/app/ai/model/providers.test.ts
@@ -10,7 +10,7 @@ import { resolveProviderModel } from '@/app/ai/models/reasoning/floors'
import { reasoningCallSettings } from '@/app/ai/models/reasoning/settings'
import type { ThinkingLevel } from '@/app/ai/models/types'
import { createAnthropicCompatibleAdapter } from '@/app/ai/providers/compatible'
-import { modelProviderAdapter } from '@/app/ai/providers/registry'
+import { modelProviderAdapter, providerTakesWebPImages } from '@/app/ai/providers/registry'
import type { ModelConfig } from '@/app/ai/providers/types'
import type { FetchFunction } from '@/app/http/types'
@@ -156,6 +156,91 @@ describe('model provider registry', () => {
'ACP providers and Harness agents do not use direct API models'
)
})
+
+ test('sends a tool image to a Chat Completions endpoint in a user message after the tool result', async () => {
+ let requestBody = ''
+ const fetchSpy: FetchFunction = async (_input, init) => {
+ requestBody = String(init?.body)
+ throw new Error('stop')
+ }
+ const model = languageModelInstance(
+ modelProviderAdapter('minimax').create(
+ {
+ providerID: 'minimax',
+ apiKey: 'test-key',
+ modelID: 'MiniMax-M3',
+ customModelID: '',
+ customBaseURL: '',
+ customAPIType: 'completions'
+ },
+ { fetch: fetchSpy }
+ )
+ )
+ if (model.specificationVersion !== 'v4') throw new Error('Expected a v4 model')
+ await Promise.resolve(
+ model.doGenerate({
+ prompt: [
+ { role: 'user', content: [{ type: 'text', text: 'Check the frame' }] },
+ {
+ role: 'assistant',
+ content: [
+ { type: 'tool-call', toolCallId: 'call-1', toolName: 'export_image', input: {} }
+ ]
+ },
+ {
+ role: 'tool',
+ content: [
+ {
+ type: 'tool-result',
+ toolCallId: 'call-1',
+ toolName: 'export_image',
+ output: {
+ type: 'content',
+ value: [
+ { type: 'text', text: '{"width":2}' },
+ {
+ type: 'file',
+ mediaType: 'image/png',
+ data: { type: 'data', data: 'iVBORw0KGgo=' }
+ }
+ ]
+ }
+ }
+ ]
+ }
+ ]
+ })
+ ).catch(() => undefined)
+
+ const body: unknown = JSON.parse(requestBody)
+ expect(body).toMatchObject({
+ messages: [
+ { role: 'user' },
+ { role: 'assistant' },
+ {
+ role: 'tool',
+ tool_call_id: 'call-1',
+ content: '{"width":2}\nThe images follow in the next user message.'
+ },
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'Images from the export_image call call-1:' },
+ { type: 'image_url', image_url: { url: 'data:image/png;base64,iVBORw0KGgo=' } }
+ ]
+ }
+ ]
+ })
+ })
+
+ test('sends WebP tool images only where the provider itself documents WebP input', () => {
+ // An endpoint behind a compatible API, a router, or Cloud may not decode WebP.
+ const documented = new Set<AIProviderID>(['anthropic', 'openai', 'google', 'deepseek'])
+ for (const { id } of AI_PROVIDERS) {
+ expect({ id, webp: providerTakesWebPImages(id) }).toEqual({ id, webp: documented.has(id) })
+ }
+ expect(providerTakesWebPImages('acp:claude-code')).toBe(false)
+ })
})
describe('anthropic compatible adapter', () => {