Free open-source image editor for the browser
Add serializable commands and run WebMCP tools through them (#57)
Rodrigo Belfiore26c6e6fb4023
diff --git a/API.md b/API.mdindex 280d649..6b80e0e 100644--- a/API.md+++ b/API.md@@ -172,20 +172,37 @@ On a fresh load the start screen shows a notice in the viewport's corner with **Without a document, `documentId`, `size`, `frame`, and `preview` are undefined. Adjustments, details, and the tone curve use their defaults, and history counts are zero. Mutating the snapshot does not edit the document.+## Commands++`run(command)` validates and runs one command: a plain object with a `type` and that command's fields, as JSON can carry it. It returns `{ layerId }` for the layer the command edited or created, so a caller can select it, and throws on an unknown type or an invalid field. Commands make the same edits as the methods above.++```js+editor.run({+ type: "add-mask",+ mask: { kind: "linear", start: [600, 0], end: [600, 400] },+ adjustments: { exposure: -1 },+});+```++| Command | Fields | Behavior |+| --- | --- | --- |+| `set-adjustments` | adjustments, `layerId?` | Like `setAdjustments`. |+| `set-tone-curve` | `points?`, `layerId?` | Like `setToneCurve`. |+| `set-white-balance` | `temperature?`, `tint?` | Like `setWhiteBalance` with a change. |+| `set-color-mixer` | `color`, `hue?`, `saturation?`, `luminance?`, `layerId?` | Like `setColorMixer`. |+| `set-details` | `clarity?`, `sharpening?`, `sharpenRadius?`, `layerId?` | Like `setDetails`. |+| `set-vignette` | `intensity?`, `softness?`, `layerId?` | Like `setVignette`. |+| `add-mask` | `mask`, `adjustments?` | Adds a mask layer with those adjustments on top of the stack as one edit. |+| `delete-layer` | `layerId` | Like `deleteLayer`. |+| `set-crop` | `aspectRatio?`, `straighten?` | Replaces the frame with the largest centered crop of the source at `aspectRatio`, width over height, straightened by −45 to 45 degrees. Without either, it removes the crop. |+| `reset` | none | Removes every layer and returns adjustments, the tone curve, white balance, and the frame to how the photo opened, as one edit. |+| `undo`, `redo` | none | Like `undo` and `redo`. |+| `set-preview` | `comparison` | Shows `"edited"`, `"original"`, or `"split"`. |+## WebMCP-In browsers with [WebMCP](https://webmachinelearning.github.io/webmcp/), OpenLight also registers tools on `document.modelContext`, so a browser agent can edit the open photo. Chrome offers WebMCP from version 149 through an origin trial or `chrome://flags/#enable-webmcp-testing`. Tools validate their JSON input against schemas generated from the same models as the commands above, make the same undoable edits, and return errors as text, so the agent can correct its input.+In browsers with [WebMCP](https://webmachinelearning.github.io/webmcp/), OpenLight registers every command as a tool on `document.modelContext`, so a browser agent can edit the open photo. Chrome offers WebMCP from version 149 through an origin trial or `chrome://flags/#enable-webmcp-testing`. A tool takes its command's fields, with a JSON Schema generated from the same models, and returns `{ layerId }` or `"Done."`; errors come back as text, so the agent can correct its input.-| Tool | Behavior |-| --- | --- |-| `get_state` | Returns the file, source size, frame, layers, comparison, and history; brush strokes and healing patches are counted rather than listed. |-| `open_image` | Opens the image at an http(s) `url` like `loadUrl`, in place of the open photo, and returns the new state like `get_state`, or why the image could not open. |-| `set_adjustments`, `set_tone_curve` | Call `setAdjustments` and `setToneCurve`; `layerId` addresses a mask instead of the image. |-| `set_white_balance`, `set_color_mixer`, `set_details`, `set_vignette` | Call the matching command on the image or the first root effect. |-| `add_mask` | Adds a mask layer with the given mask on top of the stack as one edit and returns its `layerId`. |-| `delete_layer` | Calls `deleteLayer`. |-| `set_crop` | Replaces the frame with the largest centered crop of the source at `aspectRatio`, straightened by −45 to 45 degrees. |-| `undo`, `redo` | Call the matching command and return the history. |-| `set_preview` | Sets the preview `comparison`. |--WebMCP passes only JSON, so no tool takes or returns a file. An agent opens a local file, such as an image attached to its chat, by serving it over HTTP with CORS and passing its URL to `open_image`. From a public origin such as openlight.app, Chrome's [Local Network Access](https://developer.chrome.com/blog/local-network-access) asks the user before the page reaches a local address; an automated browser can grant the `local-network-access` permission instead.+A read-only `get-state` tool returns the file, source size, frame, layers, comparison, and history, counting brush strokes and healing patches rather than listing them.++WebMCP passes only JSON, so no tool takes or returns a file. `open-image` takes an http(s) `url` instead and opens it like `loadUrl`, in place of the open photo; it returns the new state like `get-state`, or why the image could not open. An agent opens a local file, such as an image attached to its chat, by serving it over HTTP with CORS and passing its URL. From a public origin such as openlight.app, Chrome's [Local Network Access](https://developer.chrome.com/blog/local-network-access) asks the user before the page reaches a local address; an automated browser can grant the `local-network-access` permission instead.diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex d8e5942..fc305a4 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -12,7 +12,8 @@ Where the code lives and the rules that keep it in place. Keep this file true: w| `app/loaders` | Image, scene file, and Camera Raw XMP loaders. || `app/draft` | The draft autosaved in the browser. || `app/controls.ts` | `window.openlight`, documented in [API.md](API.md). |-| `app/webmcp.ts` | WebMCP tools for browser agents, built on the controls; see [API.md](API.md#webmcp). |+| `app/commands.ts` | The commands: serializable, validated edits that `run`, WebMCP, and other callers share; see [API.md](API.md#commands). |+| `app/webmcp.ts` | WebMCP tools for browser agents, one per command; see [API.md](API.md#webmcp). || `app/editor/index.tsx` | The editor with a document: header, then a tool's canvas and controls in the layout. A tool's `View` replaces both. || `app/editor/empty.tsx` | The editor before a document opens: welcome or loading status, and the placeholder sidebar. || `app/editor/sidebar.tsx` | Sidebar sections in order: `EditorSidebar` with a document, `PlaceholderSidebar` without one. |@@ -54,7 +55,7 @@ Dependencies point downward. Features do not import each other; `app/` connects- Document edits and rendering run without React, a mounted UI, or an implicit active document: pass workspace, document, and GPU explicitly. Feature processing imports without its panel.- Each document owns a vanilla Zustand scene store, history, and image resources. Scenes hold immutable, serializable content and image-source IDs; files and GPU resources stay outside history.-- UI controls and `window.openlight` call the same edits. A slider or curve gesture is one edit; cancelling restores the previous scene. Preview settings and navigation stay outside history.+- UI controls, `window.openlight`, and commands call the same edits. A slider or curve gesture is one edit; cancelling restores the previous scene. Preview settings and navigation stay outside history.- The engine owns GPU resources, rendering, and derived data such as histogram bins; frame data stays out of React state. Every resource owner disposes what it creates.## Renderingdiff --git a/src/app/commands.ts b/src/app/commands.tsnew file mode 100644index 0000000..bec7318--- /dev/null+++ b/src/app/commands.ts@@ -0,0 +1,213 @@+import { z } from "zod/mini";+import type { EditorDocument } from "@/core/document";+import { imageFrame } from "@/core/image/frame";+import { setAdjustments } from "@/features/adjustments/edits";+import {+ adjustmentsSchema,+ defaultAdjustments,+} from "@/features/adjustments/model";+import { setColorMixer } from "@/features/color-mixer/edits";+import { mixerChange, mixerColor } from "@/features/color-mixer/model";+import { applyCrop } from "@/features/crop/edits";+import { fitRatio, rotate } from "@/features/crop/geometry";+import { setDetails } from "@/features/details/edits";+import { detailsSchema } from "@/features/details/model";+import { addLayer, deleteLayer } from "@/features/layers/edits";+import { maskSchema } from "@/features/layers/model";+import { curveSchema, defaultCurve } from "@/features/tone-curves/curve";+import { setToneCurve } from "@/features/tone-curves/edits";+import { setVignette } from "@/features/vignette/edits";+import { vignetteSchema } from "@/features/vignette/model";+import { setWhiteBalance } from "@/features/white-balance/edits";+import { change, parse, range } from "@/lib/parse";+import { createMask, editEffect } from "./editor/layers";+import type { Workspace } from "./workspace";++/** The layer a command edited or created, so a caller can select it. */+export type CommandResult = { layerId?: string };++function command<S extends z.ZodMiniType>(+ description: string,+ input: S,+ run: (+ document: EditorDocument,+ input: z.output<S>,+ ) => CommandResult | undefined,+) {+ return {+ description,+ input,+ execute: (document: EditorDocument, value: unknown, subject: string) =>+ run(document, parse(input, value, subject)) ?? {},+ };+}++function image(document: EditorDocument) {+ return document.scene.getState().layers[0];+}++function sourceSize(document: EditorDocument) {+ return document.resources.get(image(document).source).image.size;+}++/** Removes every layer and returns the image's settings and frame to how the photo opened, as one entry. */+function reset(document: EditorDocument) {+ const layer = image(document);+ const source = document.resources.get(layer.source);+ document.history.commit();+ document.edit({+ frame: imageFrame(source.image.size),+ layers: [+ {+ ...layer,+ adjustments: { ...defaultAdjustments },+ toneCurve: defaultCurve,+ whiteBalance: source.raw?.asShot,+ },+ ],+ });+ document.selectLayer(layer.id);+ return { layerId: layer.id };+}++const none = z.strictObject({});+const layerId = z.optional(z.string());++/**+ * Serializable edits to the open document, by type. Each validates its input like the matching+ * control; the control API's `run` and the WebMCP tools run them.+ */+export const commands = {+ "set-adjustments": command(+ "Sets basic adjustments, keeping the ones omitted. Exposure is in stops from -5 to 5; the others go from -100 to 100, where 0 is neutral. Without layerId they tone the whole photo; with a mask's layerId they apply inside that mask.",+ z.extend(change(adjustmentsSchema), { layerId }),+ (document, { layerId, ...adjustments }) => {+ setAdjustments(document, adjustments, layerId);+ return { layerId: layerId ?? image(document).id };+ },+ ),+ "set-tone-curve": command(+ "Replaces the tone curve: points map input x to output y, from shadows at x 0 to highlights at x 1, ordered by x. Omit points to reset it. Without layerId it tones the whole photo after its adjustments; with a mask's layerId it applies inside that mask.",+ z.strictObject({ points: z.optional(curveSchema), layerId }),+ (document, { points, layerId }) => {+ setToneCurve(document, points, layerId);+ return { layerId: layerId ?? image(document).id };+ },+ ),+ "set-white-balance": command(+ "Sets a RAW photo's white balance: temperature in Kelvin from 2000 to 25000 and tint from -150 to 150. Other photos have no white balance; warm or cool them with set-adjustments' incrementalTemperature and incrementalTint.",+ z.partial(z.strictObject({ temperature: z.number(), tint: z.number() })),+ (document, change) => {+ setWhiteBalance(document, change);+ return { layerId: image(document).id };+ },+ ),+ "set-color-mixer": command(+ "Shifts one color range's hue, saturation, or luminance from -100 to 100, keeping other colors and omitted values. Neutral grays are unaffected. Without layerId it edits the first Color Mixer layer, creating one when there is none.",+ z.extend(mixerChange, { color: mixerColor, layerId }),+ (document, { color, layerId, ...change }) => ({+ layerId: editEffect(document, "color-mixer", layerId, (id) =>+ setColorMixer(document, color, change, id),+ ),+ }),+ ),+ "set-details": command(+ "Sets clarity (local contrast, -100 to 100), sharpening (0 to 150), and sharpenRadius (0.5 to 3 pixels), keeping omitted values. Without layerId it edits the first Details layer, creating one when there is none.",+ z.extend(change(detailsSchema), { layerId }),+ (document, { layerId, ...details }) => ({+ layerId: editEffect(document, "details", layerId, (id) =>+ setDetails(document, details, id),+ ),+ }),+ ),+ "set-vignette": command(+ "Darkens the photo's edges: intensity from 0 (off) to 100 and softness from 0 to 100, keeping omitted values. Without layerId it edits the first Vignette layer, creating one when there is none.",+ z.extend(change(vignetteSchema), { layerId }),+ (document, { layerId, ...vignette }) => ({+ layerId: editEffect(document, "vignette", layerId, (id) =>+ setVignette(document, vignette, id),+ ),+ }),+ ),+ "add-mask": command(+ "Adds a mask layer on top of the stack with optional adjustments, as one edit, and returns its layerId. Coordinates are source pixels, unaffected by crop. A linear mask covers fully at start and fades out at end; a radial mask covers an ellipse around center with radius [x, y], angle in degrees, and feather from 0 to 1.",+ z.strictObject({+ mask: maskSchema,+ adjustments: z.optional(change(adjustmentsSchema)),+ }),+ (document, { mask, adjustments }) => {+ const layer = createMask(mask);+ return {+ layerId: addLayer(document, {+ ...layer,+ adjustments: { ...layer.adjustments, ...adjustments },+ }),+ };+ },+ ),+ "delete-layer": command(+ "Removes a layer and the layers inside it.",+ z.strictObject({ layerId: z.string() }),+ (document, { layerId }) => {+ deleteLayer(document, layerId);+ },+ ),+ "set-crop": command(+ "Replaces the crop, rotation, and flips with the largest centered crop of the photo. aspectRatio is width / height and defaults to the photo's; straighten rotates by -45 to 45 degrees. Omit both to remove the crop.",+ z.strictObject({+ aspectRatio: z.optional(z.number().check(z.positive())),+ straighten: z.optional(range(-45, 45)),+ }),+ (document, { aspectRatio, straighten = 0 }) => {+ const size = sourceSize(document);+ const frame = rotate(imageFrame(size), straighten, size);+ applyCrop(document, aspectRatio ? fitRatio(frame, aspectRatio) : frame);+ },+ ),+ reset: command(+ "Removes every layer and returns the photo's adjustments, tone curve, white balance, and crop to how it opened, as one edit.",+ none,+ reset,+ ),+ undo: command("Undoes the last edit.", none, (document) => {+ document.history.undo();+ }),+ redo: command("Redoes the last undone edit.", none, (document) => {+ document.history.redo();+ }),+ "set-preview": command(+ "Shows the edited photo, the original, or a split comparison of both, without editing the photo.",+ z.strictObject({ comparison: z.enum(["edited", "original", "split"]) }),+ (document, { comparison }) => {+ document.preview.setState({ comparison });+ },+ ),+};++type Commands = typeof commands;++/** A command's fields; zod types an empty object as a record of `never`, which would forbid `type`. */+type Fields<T> = string extends keyof T ? unknown : T;++/** A command as data: its type and its fields. */+export type Command = {+ [Type in keyof Commands]: { type: Type } & Fields<+ z.input<Commands[Type]["input"]>+ >;+}[keyof Commands];++const byType = new Map(Object.entries(commands));+const envelope = z.looseObject({ type: z.string() });++/** Validates and runs one command on the open document. */+export function runCommand(+ workspace: Workspace,+ value: unknown,+): CommandResult {+ const { type, ...input } = parse(envelope, value, "Invalid command");+ const definition = byType.get(type);+ if (!definition) {+ throw Error(`Unknown command: ${type}.`);+ }+ return definition.execute(workspace.getDocument(), input, `Invalid ${type}`);+}diff --git a/src/app/controls.ts b/src/app/controls.tsindex 50d8794..b55b8af 100644--- a/src/app/controls.ts+++ b/src/app/controls.ts@@ -55,6 +55,7 @@ import { setToneCurve } from "@/features/tone-curves/edits";import { setVignette } from "@/features/vignette/edits";import { defaultVignette } from "@/features/vignette/model";import { setWhiteBalance } from "@/features/white-balance/edits";+import { type Command, runCommand } from "./commands";import {createLayer,createMask,@@ -167,6 +168,8 @@ export function createControls(cancelEdit: () => workspace.getDocument().history.cancel(),undo: () => workspace.getDocument().history.undo(),redo: () => workspace.getDocument().history.redo(),+ /** Validates and runs a serializable command, returning the layer it edited. */+ run: (command: Command) => runCommand(workspace, command),exportImage: (options?: ExportOptions) =>exportImage(gpu, workspace.getDocument(), options),exportScene: () => writeSceneFile(workspace.getDocument()),diff --git a/src/app/editor/layers.ts b/src/app/editor/layers.tsindex 7f1b879..38f60a7 100644--- a/src/app/editor/layers.ts+++ b/src/app/editor/layers.ts@@ -143,7 +143,7 @@ export function findEffect<K extends EffectLayer["kind"]>();}-/** Convenience commands address the first root effect of a kind or create one on top of the stack as one entry. */+/** Convenience commands address the first root effect of a kind or create one on top of the stack as one entry; returns the layer edited. */export function editEffect(document: EditorDocument,kind: EffectLayer["kind"],@@ -154,7 +154,7 @@ export function editEffect(const existing = id ?? findEffect(scene.layers, kind)?.id;if (existing) {edit(existing);- return;+ return existing;}const layer = createLayer(kind);const opened = document.history.begin();@@ -170,4 +170,5 @@ export function editEffect(}throw error;}+ return layer.id;}diff --git a/src/app/webmcp.ts b/src/app/webmcp.tsindex d99787c..e238098 100644--- a/src/app/webmcp.ts+++ b/src/app/webmcp.ts@@ -1,17 +1,8 @@import { z } from "zod/mini";import type { EditorDocument } from "@/core/document";-import { imageFrame } from "@/core/image/frame";-import { adjustmentsSchema } from "@/features/adjustments/model";-import { mixerChange, mixerColor } from "@/features/color-mixer/model";-import { fitRatio, rotate } from "@/features/crop/geometry";-import { detailsSchema } from "@/features/details/model";-import { addLayer } from "@/features/layers/edits";-import { maskSchema } from "@/features/layers/model";-import { curveSchema } from "@/features/tone-curves/curve";-import { vignetteSchema } from "@/features/vignette/model";-import { change, parse, range } from "@/lib/parse";+import { parse } from "@/lib/parse";+import { commands } from "./commands";import type { createControls } from "./controls";-import { createMask } from "./editor/layers";import type { Workspace } from "./workspace";type Controls = ReturnType<typeof createControls>;@@ -39,11 +30,11 @@ declare global {}}-function defineTool<S extends z.ZodMiniType>(+function defineTool(name: string,description: string,- input: S,- run: (input: z.output<S>) => unknown,+ input: z.ZodMiniType,+ run: (input: unknown) => unknown,annotations?: ModelContextTool["annotations"],): ModelContextTool {return {@@ -51,9 +42,9 @@ function defineTool<S extends z.ZodMiniType>(description,inputSchema: z.toJSONSchema(input, { io: "input" }),annotations,- async execute(value) {+ async execute(input) {try {- return (await run(parse(input, value, "Invalid input"))) ?? "Done.";+ return await run(input);} catch (error) {// Returned, since browsers pass a thrown error to the agent without its message.return String(error);@@ -89,10 +80,9 @@ function describe(workspace: Workspace, controls: Controls) {);}-const none = z.strictObject({});-const layerId = z.optional(z.string());+const openImage = z.strictObject({ url: z.url({ protocol: /^https?$/ }) });-/** Registers the editor's commands as WebMCP tools for browser agents until `signal` aborts. */+/** Registers `get-state`, `open-image`, and every command as WebMCP tools for browser agents until `signal` aborts. */export function registerTools(workspace: Workspace,controls: Controls,@@ -104,17 +94,18 @@ export function registerTools(}const tools = [defineTool(- "get_state",- "Describes the open photo: its file, source size in pixels, crop frame, layers from bottom to top with their IDs and settings, and undo history. Color mixer arrays list red, orange, yellow, green, aqua, blue, purple, and magenta. Call it first; when no photo is open, open one with open_image or ask the user to open one.",- none,+ "get-state",+ "Describes the open photo: its file, source size in pixels, crop frame, layers from bottom to top with their IDs and settings, and undo history. Color mixer arrays list red, orange, yellow, green, aqua, blue, purple, and magenta. Call it first; when no photo is open, open one with open-image or ask the user to open one.",+ z.strictObject({}),() => describe(workspace, controls),{ readOnlyHint: true },),defineTool(- "open_image",- "Opens the image at url in place of the open photo, with a new undo history, and describes it like get_state. The page fetches url, so another origin must allow CORS. To open a local file, such as an image attached to the chat, serve it over HTTP with CORS and pass its URL; the browser may first ask the user to let the page reach local addresses.",- z.strictObject({ url: z.url({ protocol: /^https?$/ }) }),- async ({ url }) => {+ "open-image",+ "Opens the image at url in place of the open photo, with a new undo history, and describes it like get-state. The page fetches url, so another origin must allow CORS. To open a local file, such as an image attached to the chat, serve it over HTTP with CORS and pass its URL; the browser may first ask the user to let the page reach local addresses.",+ openImage,+ async (input) => {+ const { url } = parse(openImage, input, "Invalid open-image");if (await controls.loadUrl(url)) {return describe(workspace, controls);}@@ -123,94 +114,16 @@ export function registerTools(throw Error(`Couldn't open ${url}: ${reason}`);},),- defineTool(- "set_adjustments",- "Sets basic adjustments, keeping the ones omitted. Exposure is in stops from -5 to 5; the others go from -100 to 100, where 0 is neutral. Without layerId they tone the whole photo; with a mask's layerId they apply inside that mask.",- z.extend(change(adjustmentsSchema), { layerId }),- ({ layerId, ...adjustments }) =>- controls.setAdjustments(adjustments, layerId),- ),- defineTool(- "set_tone_curve",- "Replaces the tone curve: points map input x to output y, from shadows at x 0 to highlights at x 1, ordered by x. Omit points to reset it. Without layerId it tones the whole photo after its adjustments; with a mask's layerId it applies inside that mask.",- z.strictObject({ points: z.optional(curveSchema), layerId }),- ({ points, layerId }) => controls.setToneCurve(points, layerId),- ),- defineTool(- "set_white_balance",- "Sets a RAW photo's white balance: temperature in Kelvin from 2000 to 25000 and tint from -150 to 150. Other photos have no white balance; warm or cool them with set_adjustments' incrementalTemperature and incrementalTint.",- z.partial(z.strictObject({ temperature: z.number(), tint: z.number() })),- (change) => controls.setWhiteBalance(change),- ),- defineTool(- "set_color_mixer",- "Shifts one color range's hue, saturation, or luminance from -100 to 100, keeping other colors and omitted values. Neutral grays are unaffected.",- z.extend(mixerChange, { color: mixerColor }),- ({ color, ...change }) => controls.setColorMixer(color, change),- ),- defineTool(- "set_details",- "Sets clarity (local contrast, -100 to 100), sharpening (0 to 150), and sharpenRadius (0.5 to 3 pixels), keeping omitted values.",- change(detailsSchema),- (change) => controls.setDetails(change),- ),- defineTool(- "set_vignette",- "Darkens the photo's edges: intensity from 0 (off) to 100 and softness from 0 to 100, keeping omitted values.",- change(vignetteSchema),- (change) => controls.setVignette(change),- ),- defineTool(- "add_mask",- "Adds a mask layer and returns its layerId; give it adjustments or a tone curve with that layerId. Coordinates are source pixels (see sourceSize), unaffected by crop. A linear mask covers fully at start and fades out at end; a radial mask covers an ellipse around center with radius [x, y], angle in degrees, and feather from 0 to 1.",- z.strictObject({ mask: maskSchema }),- ({ mask }) => ({- layerId: addLayer(workspace.getDocument(), createMask(mask)),+ ...Object.entries(commands).map(([type, command]) =>+ defineTool(type, command.description, command.input, (input) => {+ const result = command.execute(+ workspace.getDocument(),+ input,+ `Invalid ${type}`,+ );+ return result.layerId ? result : "Done.";}),),- defineTool(- "delete_layer",- "Removes a layer and the layers inside it.",- z.strictObject({ layerId: z.string() }),- ({ layerId }) => controls.deleteLayer(layerId),- ),- defineTool(- "set_crop",- "Replaces the crop, rotation, and flips with the largest centered crop of the photo. aspectRatio is width / height and defaults to the photo's; straighten rotates by -45 to 45 degrees. Omit both to remove the crop.",- z.strictObject({- aspectRatio: z.optional(z.number().check(z.positive())),- straighten: z.optional(range(-45, 45)),- }),- ({ aspectRatio, straighten = 0 }) => {- const size = sourceSize(workspace.getDocument());- const frame = rotate(imageFrame(size), straighten, size);- controls.setFrame(aspectRatio ? fitRatio(frame, aspectRatio) : frame);- },- ),- defineTool(- "undo",- "Undoes the last edit and returns the history.",- none,- () => {- controls.undo();- return controls.getState().history;- },- ),- defineTool(- "redo",- "Redoes the last undone edit and returns the history.",- none,- () => {- controls.redo();- return controls.getState().history;- },- ),- defineTool(- "set_preview",- "Shows the edited photo, the original, or a split comparison of both, without editing the photo.",- z.strictObject({ comparison: z.enum(["edited", "original", "split"]) }),- ({ comparison }) => controls.setPreview({ comparison }),- ),];for (const tool of tools) {void context.registerTool(tool, { signal });diff --git a/tests/commands.test.ts b/tests/commands.test.tsnew file mode 100644index 0000000..8ccc14d--- /dev/null+++ b/tests/commands.test.ts@@ -0,0 +1,67 @@+import { expect, test } from "bun:test";+import { init, target } from "vgpu/mock";+import { createControls } from "@/app/controls";+import { createImageLayer } from "@/app/editor/layers";+import { createWorkspace } from "@/app/workspace";+import { createDocument, createResources } from "@/core/document";+import { createImageSource } from "@/core/image";+import { imageFrame } from "@/core/image/frame";++test("commands validate their input, return the layer they edit, and reset as one edit", async () => {+ const gpu = await init();+ const source = createImageSource(+ target(gpu, { size: [32, 16], format: "rgba16float" }),+ );+ const resources = createResources();+ const sourceId = resources.add(new File([], "photo.png"), source);+ const document = createDocument(+ {+ frame: imageFrame(source.image.size),+ layers: [{ ...createImageLayer(sourceId, "Photo"), id: "base" }],+ },+ resources,+ );+ const workspace = createWorkspace();+ await workspace.open("photo.png", async () => document);+ const { run } = createControls(gpu, workspace);+ const opened = document.scene.getState();+ const undoCount = () => document.history.status.getState().undoCount;++ expect(() => Reflect.apply(run, undefined, [{ type: "blur" }])).toThrow(+ "Unknown command: blur.",+ );+ expect(() => run({ type: "set-vignette", intensity: 101 })).toThrow(+ "Invalid set-vignette intensity",+ );+ expect(undoCount()).toBe(0);++ expect(run({ type: "set-adjustments", exposure: 1 })).toEqual({+ layerId: "base",+ });+ const vignette = run({ type: "set-vignette", intensity: 40 }).layerId;+ expect(run({ type: "set-vignette", softness: 80 }).layerId).toBe(vignette);+ const mask = run({+ type: "add-mask",+ mask: {+ kind: "radial",+ center: [16, 8],+ radius: [8, 4],+ angle: 0,+ feather: 0.5,+ },+ adjustments: { exposure: -1 },+ }).layerId;+ expect(document.scene.getState().layers.at(-1)).toMatchObject({+ id: mask,+ adjustments: { exposure: -1 },+ });+ run({ type: "set-crop", aspectRatio: 1 });+ expect(undoCount()).toBe(5);++ const edited = document.scene.getState();+ run({ type: "reset" });+ expect(document.scene.getState()).toEqual(opened);+ expect(undoCount()).toBe(6);+ run({ type: "undo" });+ expect(document.scene.getState()).toEqual(edited);+});diff --git a/tests/webmcp.e2e.ts b/tests/webmcp.e2e.tsindex 6d1fd8b..8d1037b 100644--- a/tests/webmcp.e2e.ts+++ b/tests/webmcp.e2e.ts@@ -17,7 +17,7 @@ function callTool(page: Page, name: string, input: object = {}) {);}-test("a browser agent opens, edits, masks, crops, and undoes through WebMCP tools", async ({+test("a browser agent opens, edits, masks, crops, undoes, and resets through WebMCP tools", async ({page,}) => {// Another origin, with CORS and no extension, as an agent serves a local file.@@ -38,46 +38,46 @@ test("a browser agent opens, edits, masks, crops, and undoes through WebMCP tool),).toBeGreaterThan(0);- expect(await callTool(page, "set_adjustments", { exposure: 1 })).toBe(+ expect(await callTool(page, "set-adjustments", { exposure: 1 })).toBe("Error: Load an image before editing.",);- expect(JSON.parse(await callTool(page, "open_image", { url }))).toMatchObject(+ expect(JSON.parse(await callTool(page, "open-image", { url }))).toMatchObject({ file: "gray card", sourceSize: [128, 64] },);+ const state = async () => JSON.parse(await callTool(page, "get-state"));const gray = await readImage(page);+ const [image] = (await state()).layers;- expect(await callTool(page, "set_adjustments", { exposure: 9 })).toMatch(+ expect(await callTool(page, "set-adjustments", { exposure: 9 })).toMatch(/exposure/,);- expect(await callTool(page, "set_adjustments", { exposure: 1 })).toBe(- "Done.",- );+ expect(+ JSON.parse(await callTool(page, "set-adjustments", { exposure: 1 })),+ ).toEqual({ layerId: image.id });const brighter = await readImage(page);expect(brighter.center[0]).toBeGreaterThan(gray.center[0]);- const { layerId } = JSON.parse(- await callTool(page, "add_mask", {- mask: { kind: "linear", start: [0, 0], end: [0, 32] },- }),- );- await callTool(page, "set_adjustments", { layerId, exposure: -2 });- const masked = await readImage(page, undefined, [- [64, 2],- [64, 60],- ]);+ await callTool(page, "add-mask", {+ mask: { kind: "linear", start: [0, 0], end: [0, 32] },+ adjustments: { exposure: -2 },+ });+ const readEnds = () =>+ readImage(page, undefined, [+ [64, 2],+ [64, 60],+ ]);+ const masked = await readEnds();expect(masked.samples?.[0][0]).toBeLessThan(gray.center[0]);expect(masked.samples?.[1]).toEqual(brighter.center);- await callTool(page, "set_crop", { aspectRatio: 1 });+ expect(await callTool(page, "set-crop", { aspectRatio: 1 })).toBe("Done.");expect((await readImage(page)).size).toEqual([64, 64]);-- expect(JSON.parse(await callTool(page, "undo"))).toMatchObject({- undoCount: 3,- redoCount: 1,- });- await callTool(page, "undo");- await callTool(page, "undo");- expect(await readImage(page)).toEqual(brighter);await callTool(page, "undo");+ expect(await readEnds()).toEqual(masked);++ await callTool(page, "reset");+ expect((await state()).layers).toHaveLength(1);expect(await readImage(page)).toEqual(gray);+ await callTool(page, "undo");+ expect(await readEnds()).toEqual(masked);});