feat(workerd): add host image resizer hook (#67022)

This commit is contained in:
Kit Langton 2026-11-28 13:13:12 -08:00 • committed by GitHub
parent cabe2aeb7a
commit cedabc4eda
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 541 additions and 39 deletions

View file

@ -1,8 +1,9 @@
export * as Image from "./image.js"
import { base64ToBytes, bytesToBase64 } from "@opencode/util/base64"
import { makeLocationNode } from "@opencode/util/effect/app-node"
import { Context, Effect, Layer, Schema } from "effect"
import { FileSystem } from "./filesystem.js"
import type { FileSystem } from "./filesystem.js"
import { State } from "./state.js"
export class ResizerUnavailableError extends Schema.TaggedError<ResizerUnavailableError>()(
@ -28,6 +29,8 @@ export class SizeError extends Schema.TaggedError<SizeError>()("Image.SizeError"
maxBytes: Schema.Number,
}) {
override get message() {
if (this.width <= 0 || this.height <= 0)
return `Image ${this.resource} has base64 size ${this.bytes}, exceeding configured limit ${this.maxBytes} bytes`
return `Image ${this.resource} is ${this.width}x${this.height} with base64 size ${this.bytes}, exceeding configured limits ${this.maxWidth}x${this.maxHeight}/${this.maxBytes} bytes`
}
}
@ -39,6 +42,31 @@ export type Limits = {
maxBase64Bytes: number
}
export type ResizerInput = {
readonly bytes: Uint8Array
readonly mime: string
readonly limits: Readonly<Limits>
}
export type ResizerOutput = {
readonly bytes: Uint8Array
readonly mime: string
}
/**
* Host-supplied image resizer for runtimes without the built-in Photon WASM
* module (such as workerd). Called when `media.image.auto_resize` is enabled;
* when disabled, `Image` enforces `maxBase64Bytes` directly and skips calling
* the resizer. Return `undefined` to keep the original image untouched (subject
* to `limits.maxBase64Bytes`), or return resized bytes with an output MIME type
* of `image/png`, `image/jpeg`, `image/gif`, or `image/webp` within
* `limits.maxWidth` / `limits.maxHeight`. Throwing, rejecting, or returning an
* empty or unsupported output logs a warning and fails with
* `ResizerUnavailableError` so callers fall back gracefully instead of
* rejecting the prompt on transient service failures.
*/
export type Resizer = (input: ResizerInput) => ResizerOutput | undefined | Promise<ResizerOutput | undefined>
export type Editor = {
configure: (limits: Partial<Limits>) => void
}
@ -55,41 +83,108 @@ export interface Interface extends State.Transformable<Editor> {
export class Service extends Context.Service<Service, Interface>()("@opencode/Image") {}
const layer = Layer.effect(
Service,
Effect.gen(function* () {
const state = State.create<Limits, Editor>({
name: "image",
initial: () => ({
autoResize: true,
maxWidth: 2_000,
maxHeight: 2_000,
maxBase64Bytes: 5 * 1024 * 1024,
}),
editor: (editor) => ({
configure: (limits) => {
if (limits.autoResize !== undefined) editor.autoResize = limits.autoResize
if (limits.maxWidth !== undefined) editor.maxWidth = limits.maxWidth
if (limits.maxHeight !== undefined) editor.maxHeight = limits.maxHeight
if (limits.maxBase64Bytes !== undefined) editor.maxBase64Bytes = limits.maxBase64Bytes
},
}),
})
const loadAdapter = yield* Effect.cached(
Effect.tryPromise({
try: () => import("./image/photon.js"),
catch: () => new ResizerUnavailableError(),
}).pipe(Effect.flatMap((adapter) => adapter.make)),
)
const normalize = Effect.fn("Image.normalize")(function* (
resource: string,
content: FileSystem.Content & { readonly encoding: "base64" },
) {
const normalize = yield* loadAdapter
return yield* normalize(resource, content, state.get())
})
return Service.of({ transform: state.transform, reload: state.reload, normalize })
}),
)
const makeState = () =>
State.create<Limits, Editor>({
name: "image",
initial: () => ({
autoResize: true,
maxWidth: 2_000,
maxHeight: 2_000,
maxBase64Bytes: 5 * 1024 * 1024,
}),
editor: (editor) => ({
configure: (limits) => {
if (limits.autoResize !== undefined) editor.autoResize = limits.autoResize
if (limits.maxWidth !== undefined) editor.maxWidth = limits.maxWidth
if (limits.maxHeight !== undefined) editor.maxHeight = limits.maxHeight
if (limits.maxBase64Bytes !== undefined) editor.maxBase64Bytes = limits.maxBase64Bytes
},
}),
})
export const node = makeLocationNode({ service: Service, layer, deps: [] })
const sizeError = (resource: string, bytes: number, limits: Readonly<Limits>) =>
new SizeError({
resource,
width: 0,
height: 0,
bytes,
maxWidth: limits.maxWidth,
maxHeight: limits.maxHeight,
maxBytes: limits.maxBase64Bytes,
})
const ALLOWED_OUTPUT_MIMES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"])
const fallbackError = (resource: string, encodedBytes: number, limits: Readonly<Limits>) =>
encodedBytes > limits.maxBase64Bytes ? sizeError(resource, encodedBytes, limits) : new ResizerUnavailableError()
const layer = (resizer?: Resizer) =>
Layer.effect(
Service,
Effect.gen(function* () {
const state = makeState()
if (resizer !== undefined) {
const normalize = Effect.fn("Image.normalize")(function* (
resource: string,
content: FileSystem.Content & { readonly encoding: "base64" },
) {
const limits = state.get()
if (!limits.autoResize) {
if (content.content.length > limits.maxBase64Bytes)
return yield* sizeError(resource, content.content.length, limits)
return content
}
const bytes = yield* Effect.try({
try: () => base64ToBytes(content.content),
catch: () => new DecodeError({ resource }),
})
if (bytes.length === 0) return yield* new DecodeError({ resource })
const result = yield* Effect.tryPromise({
try: async () => resizer({ bytes, mime: content.mime, limits: { ...limits } }),
catch: (cause) => cause,
}).pipe(
Effect.catch((cause) =>
Effect.logWarning("image.resizer_failed").pipe(
Effect.annotateLogs({ resource, error: String(cause) }),
Effect.andThen(Effect.fail(fallbackError(resource, content.content.length, limits))),
),
),
)
if (result === undefined) {
if (content.content.length > limits.maxBase64Bytes)
return yield* sizeError(resource, content.content.length, limits)
return content
}
const mime = result.mime.toLowerCase()
if (result.bytes.length === 0 || !ALLOWED_OUTPUT_MIMES.has(mime)) {
yield* Effect.logWarning("image.resizer_invalid_output").pipe(
Effect.annotateLogs({ resource, mime: result.mime, bytes: result.bytes.length }),
)
return yield* fallbackError(resource, content.content.length, limits)
}
const encodedBytes = Math.ceil(result.bytes.length / 3) * 4
if (encodedBytes > limits.maxBase64Bytes) return yield* sizeError(resource, encodedBytes, limits)
return { ...content, content: bytesToBase64(result.bytes), encoding: "base64" as const, mime }
})
return Service.of({ transform: state.transform, reload: state.reload, normalize })
}
const loadAdapter = yield* Effect.cached(
Effect.tryPromise({
try: () => import("./image/photon.js"),
catch: () => new ResizerUnavailableError(),
}).pipe(Effect.flatMap((adapter) => adapter.make)),
)
const normalize = Effect.fn("Image.normalize")(function* (
resource: string,
content: FileSystem.Content & { readonly encoding: "base64" },
) {
const normalize = yield* loadAdapter
return yield* normalize(resource, content, state.get())
})
return Service.of({ transform: state.transform, reload: state.reload, normalize })
}),
)
export const configured = (resizer?: Resizer) => makeLocationNode({ service: Service, layer: layer(resizer), deps: [] })
export const node = configured()

View file

@ -0,0 +1,261 @@
import { describe, expect } from "bun:test"
import { Bus } from "@opencode/core/bus"
import { Config } from "@opencode/core/config"
import { ConfigImagePlugin } from "@opencode/core/config/plugin/image"
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
import { Image } from "@opencode/core/image"
import { Plugin } from "@opencode/core/plugin"
import { PluginHost } from "@opencode/core/plugin/host"
import { Document, Event, Info, type Entry } from "@opencode/schema/config"
import { bytesToBase64 } from "@opencode/util/base64"
import { Effect, Layer, Schema } from "effect"
import { testEffect } from "./lib/effect"
import { waitUntil } from "./lib/eventually"
import { PluginTestLayer } from "./plugin/fixture"
const decodeConfig = Schema.decodeUnknownSync(Info)
const inputBytes = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10])
const outputBytes = new Uint8Array([255, 216, 255, 224])
const sample = {
uri: "file:///photo.png",
content: bytesToBase64(inputBytes),
encoding: "base64" as const,
mime: "image/png",
}
const withResizer = (resizer: Image.Resizer) => AppNodeBuilder.build(Image.configured(resizer))
const it = testEffect(Layer.empty)
function document(image: NonNullable<typeof Info.Encoded.media>["image"]): Entry {
return new Document({ type: "document", info: decodeConfig({ media: { image } }) })
}
describe("Image.configured", () => {
it.effect("invokes an async host resizer with decoded bytes, mime, and default limits", () =>
Effect.gen(function* () {
const seen: Image.ResizerInput[] = []
const resizer: Image.Resizer = async (input) => {
seen.push(input)
return { bytes: outputBytes, mime: "image/jpeg" }
}
const image = yield* Image.Service.pipe(Effect.provide(withResizer(resizer)))
const normalized = yield* image.normalize("photo.png", sample)
expect(seen).toHaveLength(1)
expect(seen[0]?.bytes).toEqual(inputBytes)
expect(seen[0]?.mime).toBe("image/png")
expect(seen[0]?.limits).toEqual({
autoResize: true,
maxWidth: 2_000,
maxHeight: 2_000,
maxBase64Bytes: 5 * 1024 * 1024,
})
expect(normalized).toEqual({
...sample,
content: bytesToBase64(outputBytes),
encoding: "base64",
mime: "image/jpeg",
})
}),
)
it.effect("accepts a synchronous host resizer", () =>
Effect.gen(function* () {
const image = yield* Image.Service.pipe(
Effect.provide(withResizer(() => ({ bytes: outputBytes, mime: "image/webp" }))),
)
const normalized = yield* image.normalize("photo.png", sample)
expect(normalized.mime).toBe("image/webp")
expect(normalized.content).toBe(bytesToBase64(outputBytes))
}),
)
it.effect("reflects transform updates and isolates internal state from callback mutations", () =>
Effect.gen(function* () {
const widths: number[] = []
const resizer: Image.Resizer = (input) => {
widths.push(input.limits.maxWidth)
;(input.limits as Image.Limits).maxWidth = 1
return { bytes: outputBytes, mime: input.mime }
}
const image = yield* Image.Service.pipe(Effect.provide(withResizer(resizer)))
yield* image.transform((editor) => editor.configure({ maxWidth: 1_200, maxHeight: 900 }))
yield* image.normalize("first.png", sample)
yield* image.normalize("second.png", sample)
expect(widths).toEqual([1_200, 1_200])
}),
)
it.live("applies media.image config transforms and reloads", () =>
Effect.gen(function* () {
let seenLimits: Readonly<Image.Limits> | undefined
const resizer: Image.Resizer = (input) => {
seenLimits = input.limits
return { bytes: outputBytes, mime: input.mime }
}
const layer = Layer.merge(PluginTestLayer, withResizer(resizer))
yield* Effect.gen(function* () {
const image = yield* Image.Service
const bus = yield* Bus.Service
const config = yield* Config.Test
const plugins = yield* Plugin.Service
yield* ConfigImagePlugin.Plugin.effect(yield* PluginHost.make(plugins, "test"))
yield* image.normalize("photo.png", sample)
expect(seenLimits).toEqual({
autoResize: true,
maxWidth: 1_200,
maxHeight: 900,
maxBase64Bytes: 5 * 1024 * 1024,
})
yield* config.setEntries([document({ max_width: 800, max_base64_bytes: 1_024 })])
yield* bus.publish(Event.Updated, {})
yield* waitUntil(
image
.normalize("photo.png", sample)
.pipe(Effect.map(() => seenLimits?.maxWidth === 800 && seenLimits.maxBase64Bytes === 1_024)),
)
}).pipe(
Effect.provide(Config.testLayer([document({ max_width: 1_200, max_height: 900 })])),
Effect.provide(layer),
)
}),
)
it.effect("skips calling the host resizer when autoResize is false and enforces maxBase64Bytes", () =>
Effect.gen(function* () {
let calls = 0
const image = yield* Image.Service.pipe(
Effect.provide(
withResizer((input) => {
calls++
return { bytes: outputBytes, mime: input.mime }
}),
),
)
yield* image.transform((editor) => editor.configure({ autoResize: false, maxBase64Bytes: sample.content.length }))
expect(yield* image.normalize("photo.png", sample)).toBe(sample)
expect(calls).toBe(0)
yield* image.transform((editor) =>
editor.configure({ autoResize: false, maxBase64Bytes: sample.content.length - 1 }),
)
const error = yield* image.normalize("photo.png", sample).pipe(Effect.flip)
expect(error).toEqual(
new Image.SizeError({
resource: "photo.png",
width: 0,
height: 0,
bytes: sample.content.length,
maxWidth: 2_000,
maxHeight: 2_000,
maxBytes: sample.content.length - 1,
}),
)
expect(calls).toBe(0)
}),
)
it.effect("accepts resizer output at the exact maxBase64Bytes limit and rejects one byte below", () =>
Effect.gen(function* () {
const outputBase64Length = bytesToBase64(outputBytes).length
const image = yield* Image.Service.pipe(
Effect.provide(withResizer(() => ({ bytes: outputBytes, mime: "image/jpeg" }))),
)
yield* image.transform((editor) => editor.configure({ maxBase64Bytes: outputBase64Length }))
expect((yield* image.normalize("photo.png", sample)).content).toBe(bytesToBase64(outputBytes))
yield* image.transform((editor) => editor.configure({ maxBase64Bytes: outputBase64Length - 1 }))
const error = yield* image.normalize("photo.png", sample).pipe(Effect.flip)
expect(error).toEqual(
new Image.SizeError({
resource: "photo.png",
width: 0,
height: 0,
bytes: outputBase64Length,
maxWidth: 2_000,
maxHeight: 2_000,
maxBytes: outputBase64Length - 1,
}),
)
}),
)
it.effect("keeps the original image when the host resizer returns undefined and still enforces maxBase64Bytes", () =>
Effect.gen(function* () {
const image = yield* Image.Service.pipe(Effect.provide(withResizer(() => undefined)))
expect(yield* image.normalize("photo.png", sample)).toBe(sample)
yield* image.transform((editor) => editor.configure({ maxBase64Bytes: sample.content.length - 1 }))
const error = yield* image.normalize("photo.png", sample).pipe(Effect.flip)
expect(error).toBeInstanceOf(Image.SizeError)
expect(error.message).not.toContain("0x0")
expect(error.message).toContain(`base64 size ${sample.content.length}`)
}),
)
it.effect(
"maps invalid base64 to DecodeError and resizer failures or invalid outputs to ResizerUnavailableError",
() =>
Effect.gen(function* () {
const invalid = yield* Image.Service.pipe(
Effect.provide(withResizer(() => ({ bytes: outputBytes, mime: "image/jpeg" }))),
)
expect(
yield* invalid.normalize("bad.png", { ...sample, content: "%%%not-base64%%%" }).pipe(Effect.flip),
).toEqual(new Image.DecodeError({ resource: "bad.png" }))
expect(yield* invalid.normalize("empty-input.png", { ...sample, content: "" }).pipe(Effect.flip)).toEqual(
new Image.DecodeError({ resource: "empty-input.png" }),
)
const syncThrow = yield* Image.Service.pipe(
Effect.provide(
withResizer(() => {
throw new Error("service unavailable")
}),
),
)
expect(yield* syncThrow.normalize("sync.png", sample).pipe(Effect.flip)).toEqual(
new Image.ResizerUnavailableError(),
)
const asyncReject = yield* Image.Service.pipe(
Effect.provide(
withResizer(async () => {
throw new Error("timeout")
}),
),
)
expect(yield* asyncReject.normalize("async.png", sample).pipe(Effect.flip)).toEqual(
new Image.ResizerUnavailableError(),
)
const unsupportedMime = yield* Image.Service.pipe(
Effect.provide(withResizer(() => ({ bytes: outputBytes, mime: "image/avif" }))),
)
expect(yield* unsupportedMime.normalize("avif.png", sample).pipe(Effect.flip)).toEqual(
new Image.ResizerUnavailableError(),
)
const emptyBytes = yield* Image.Service.pipe(
Effect.provide(withResizer(() => ({ bytes: new Uint8Array(0), mime: "image/jpeg" }))),
)
expect(yield* emptyBytes.normalize("empty.png", sample).pipe(Effect.flip)).toEqual(
new Image.ResizerUnavailableError(),
)
yield* syncThrow.transform((editor) => editor.configure({ maxBase64Bytes: sample.content.length - 1 }))
expect(yield* syncThrow.normalize("oversized-throw.png", sample).pipe(Effect.flip)).toBeInstanceOf(
Image.SizeError,
)
yield* unsupportedMime.transform((editor) => editor.configure({ maxBase64Bytes: sample.content.length - 1 }))
expect(yield* unsupportedMime.normalize("oversized-avif.png", sample).pipe(Effect.flip)).toBeInstanceOf(
Image.SizeError,
)
}),
)
})

View file

@ -7,6 +7,10 @@ import { WorkerdProfile } from "../internal/workerd"
import { OpenCode } from "./opencode"
export type Configuration = WorkerdProfile.Configuration
export type ImageLimits = WorkerdProfile.ImageLimits
export type ImageResizerInput = WorkerdProfile.ImageResizerInput
export type ImageResizerOutput = WorkerdProfile.ImageResizerOutput
export type ImageResizer = WorkerdProfile.ImageResizer
export interface CreateOptions<R = never> extends WorkerdProfile.Options {
readonly log?: OpenCode.CreateOptions["log"]

View file

@ -4,6 +4,10 @@ import type { Config } from "@opencode/schema/config"
import { ServerWorkerd } from "@opencode/server/workerd"
export type Configuration = Omit<typeof Config.Info.Encoded, "plugins">
export type ImageLimits = ServerWorkerd.ImageLimits
export type ImageResizerInput = ServerWorkerd.ImageResizerInput
export type ImageResizerOutput = ServerWorkerd.ImageResizerOutput
export type ImageResizer = ServerWorkerd.ImageResizer
export interface Options extends Omit<ServerWorkerd.Options, "password" | "config"> {
readonly config?: Configuration

View file

@ -6,6 +6,10 @@ import type { LogOptions } from "./logging"
import { OpenCode } from "./opencode"
export type Configuration = WorkerdProfile.Configuration
export type ImageLimits = WorkerdProfile.ImageLimits
export type ImageResizerInput = WorkerdProfile.ImageResizerInput
export type ImageResizerOutput = WorkerdProfile.ImageResizerOutput
export type ImageResizer = WorkerdProfile.ImageResizer
export interface CreateOptions extends WorkerdProfile.Options {
readonly log?: LogOptions

View file

@ -9,6 +9,7 @@ import { makeMemoryDriver } from "@opencode/core/environment/index"
import { SessionRunnerModel } from "@opencode/core/session/runner/model"
import { WorkspaceDriver } from "@opencode/core/workspace/driver"
import { Plugin } from "@opencode/plugin/effect"
import { bytesToBase64 } from "@opencode/util/base64"
import { makeDurableObjectStorage } from "../../core/test/fixture/durable-object-storage"
import { AbsolutePath, Identity, Location } from "../src/effect"
import { EffectSdk } from "../src/internal/effect"
@ -747,3 +748,74 @@ it.live("OpenCodeWorkerd exposes alarm(), workspace.attach, and KV-backed Identi
})
}),
)
it.live(
"OpenCodeWorkerd wires options.image for prompt attachment normalization in Effect and Promise entrypoints",
() =>
Effect.gen(function* () {
const inputBytes = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10])
const resizedBytes = new Uint8Array([255, 216, 255, 224])
const dataUri = `data:image/png;base64,${bytesToBase64(inputBytes)}`
const effectSeen: OpenCodeWorkerd.ImageResizerInput[] = []
const effectSdk = yield* OpenCodeWorkerd.create({
storage: makeDurableObjectStorage(),
models: { fetch: false },
config: { media: { image: { max_width: 1_024 } } },
image: async (input) => {
effectSeen.push(input)
return { bytes: resizedBytes, mime: "image/jpeg" }
},
})
const effectSession = yield* effectSdk.sessions.create({
location: Location.Ref.make({ directory: AbsolutePath.make("/workspace") }),
})
const effectAdmitted = yield* effectSdk.sessions.prompt({
sessionID: effectSession.id,
text: "Check this image",
files: [{ uri: dataUri, name: "photo.png" }],
resume: false,
})
expect(effectSeen).toHaveLength(1)
expect(effectSeen[0]?.bytes).toEqual(inputBytes)
expect(effectSeen[0]?.mime).toBe("image/png")
expect(effectSeen[0]?.limits.maxWidth).toBe(1_024)
expect(effectAdmitted.type).toBe("user")
expect(effectAdmitted.payload.files?.[0]).toMatchObject({
mime: "image/jpeg",
data: bytesToBase64(resizedBytes),
})
yield* Effect.promise(async () => {
const { OpenCodeWorkerd } = await import("../src/workerd")
const promiseSeen: OpenCodeWorkerd.ImageResizerInput[] = []
await using sdk = await OpenCodeWorkerd.create({
storage: makeDurableObjectStorage(),
models: { fetch: false },
config: { media: { image: { max_height: 768 } } },
image: (input) => {
promiseSeen.push(input)
return { bytes: resizedBytes, mime: "image/webp" }
},
})
const session = await sdk.sessions.create({ location: { directory: "/workspace" } })
const admitted = await sdk.sessions.prompt({
sessionID: session.id,
text: "Check this image too",
files: [{ uri: dataUri, name: "photo.png" }],
resume: false,
})
expect(promiseSeen).toHaveLength(1)
expect(promiseSeen[0]?.bytes).toEqual(inputBytes)
expect(promiseSeen[0]?.mime).toBe("image/png")
expect(promiseSeen[0]?.limits.maxHeight).toBe(768)
expect(admitted.type).toBe("user")
expect(admitted.payload.files?.[0]).toMatchObject({
mime: "image/webp",
data: bytesToBase64(resizedBytes),
})
})
}),
)

View file

@ -8,6 +8,7 @@ import { sqliteLayer } from "@opencode/core/database/sqlite.workerd"
import type { DurableObjectStorage } from "@opencode/core/database/sqlite.workerd"
import { EnvironmentUnavailable } from "@opencode/core/environment/unavailable"
import { WorkspaceConnector } from "@opencode/core/environment/workspace-connector"
import { Image } from "@opencode/core/image"
import { Identity } from "@opencode/core/machine/identity"
import { Pty } from "@opencode/core/pty"
import { VideoGeneration } from "@opencode/core/video-generation"
@ -32,7 +33,7 @@ import { WorkerdMachineLink } from "./workerd-machine-link"
* `handler.alarm()` (or `opencode.alarm()` via `@opencode/sdk/workerd`).
* - Watcher and fff are disabled through their existing option flags; pty, fff,
* and photon native modules resolve to inert stubs under the `workerd` bundle
* condition.
* condition (pass `options.image` to supply a host image resizer).
* - Bare locations use a typed no-execution-plane process spawner; FileSystem,
* FileSystemSearch, Snapshot, Vcs, and Worktree route or gate through
* Environment (working on attached remote workspaces where supported and
@ -48,6 +49,11 @@ import { WorkerdMachineLink } from "./workerd-machine-link"
* `bun build src/workerd.ts --conditions=workerd --target=node`
* (see `script/workerd-probe.ts`).
*/
export type ImageLimits = Image.Limits
export type ImageResizerInput = Image.ResizerInput
export type ImageResizerOutput = Image.ResizerOutput
export type ImageResizer = Image.Resizer
export interface Options {
/** Durable Object storage whose SQLite database backs the opencode database. */
readonly storage: DurableObjectStorage
@ -59,6 +65,15 @@ export interface Options {
readonly models?: ServerOptions["models"]
/** Replaces `globalThis.fetch` for OpenCode's own HTTP requests, e.g. to route them through a Service Binding. */
readonly fetch?: ServerOptions["fetch"]
/**
* Host-supplied image resizer for runtimes without the bundled Photon WASM
* module, e.g. backed by Cloudflare's Images binding. The resizer should
* enforce `limits.maxWidth` / `limits.maxHeight`, output `image/png`,
* `image/jpeg`, `image/gif`, or `image/webp`, and return `undefined` when
* an image already fits. When omitted, image normalization reports
* `ResizerUnavailableError` and images pass through unchanged.
*/
readonly image?: ImageResizer
}
export interface Handler {
@ -134,5 +149,6 @@ export function replacements(options: Options): LayerNode.Replacements {
// Precompiled (internal and SDK) plugins only: no plugin-directory scan, npm
// install, or import of plugin code from disk.
ConfigPluginSource.node.replace(ConfigPluginSource.empty),
...(options.image === undefined ? [] : [Image.node.replace(Image.configured(options.image))]),
]
}

View file

@ -7,6 +7,7 @@ import { Environment, makeFiles, makeMemoryDriver } from "@opencode/core/environ
import { FileSystem } from "@opencode/core/filesystem"
import { Database } from "@opencode/core/database/database"
import { Location } from "@opencode/core/location"
import { Image } from "@opencode/core/image"
import { Identity } from "@opencode/core/machine/identity"
import { Project } from "@opencode/core/project"
import { Pty } from "@opencode/core/pty"
@ -18,6 +19,7 @@ import { Workspace } from "@opencode/core/workspace"
import { Worktree } from "@opencode/core/worktree"
import { LayerNode } from "@opencode/util/effect/layer-node"
import { WorkspaceDriver } from "@opencode/core/workspace/driver"
import { bytesToBase64 } from "@opencode/util/base64"
import { Npm } from "@opencode/util/npm"
import { makeDurableObjectStorage } from "../../core/test/fixture/durable-object-storage"
import { location } from "../../core/test/fixture/location"
@ -297,3 +299,47 @@ it.effect("wires Pty.unsupportedLayer in ServerWorkerd.replacements", () =>
Effect.provide(AppNodeBuilder.build(Pty.node, ServerWorkerd.replacements({ storage: makeDurableObjectStorage() }))),
),
)
it.effect("replaces Image.Service when ServerWorkerd options.image is supplied", () =>
Effect.gen(function* () {
const input = new Uint8Array([1, 2, 3, 4])
const resized = new Uint8Array([9, 8])
const seen: ServerWorkerd.ImageResizerInput[] = []
const storage = makeDurableObjectStorage()
const layer = AppNodeBuilder.build(
Image.node,
ServerWorkerd.replacements({
storage,
image: async (request) => {
seen.push(request)
return { bytes: resized, mime: "image/jpeg" }
},
}),
)
const result = yield* Image.Service.use((image) =>
Effect.gen(function* () {
yield* image.transform((editor) => editor.configure({ maxWidth: 1_024 }))
return yield* image.normalize("photo.png", {
uri: "file:///photo.png",
content: bytesToBase64(input),
encoding: "base64",
mime: "image/png",
})
}),
).pipe(Effect.provide(layer))
expect(seen).toHaveLength(1)
expect(seen[0]?.bytes).toEqual(input)
expect(seen[0]?.mime).toBe("image/png")
expect(seen[0]?.limits.maxWidth).toBe(1_024)
expect(result.mime).toBe("image/jpeg")
expect(result.content).toBe(bytesToBase64(resized))
// Omitting options.image leaves Image.node untouched.
const withoutImage = ServerWorkerd.replacements({ storage })
expect(withoutImage.length).toBe(
ServerWorkerd.replacements({ storage, image: ({ bytes, mime }) => ({ bytes, mime }) }).length - 1,
)
}),
)