> ## Documentation Index
> Fetch the complete documentation index at: https://docs.embededitor.com/llms.txt
> Use this file to discover all available pages before exploring further.

# onAiEditImage

> Let the editor's AI remove and generate in an area of the photo, and edit the whole photo by words: what the editor sends, what it takes back, which models did best in our measurements, and servers ready for fal and Runware.

`onAiEditImage` fills an area of the photo, or edits the photo whole. The person marks an area with the AI's **Brush**, then, in **Remove Object**, presses **Remove**, to take away what is marked and fill it with what surrounds it, or, in **Edit**, writes what to put there and presses **Generate**. The editor sends the piece of the photo around the mark with its mask, and pastes what this function gives back into the mark alone. With nothing marked, a request in words that adds or changes something, as "Furnish this room with contemporary furniture", edits the whole photo: the editor sends the photo with no mask, and lays what this function gives back over it, the room still the room, with furniture in it. With it, the AI's conversation can fill an area and edit the photo too, through its `retouch_run` and `retouch_remove` tools, and [`retouch.run()`](https://docs.embededitor.com/api-reference/commands/ai#run) and [`retouch.remove()`](https://docs.embededitor.com/api-reference/commands/ai#remove) run it from code. Without it, the AI can't remove or generate.

<video autoPlay muted loop playsInline src="https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-remove-object.mp4?fit=max&auto=format&n=AfjjkfPM_42cL5VY&q=85&s=a973a67c257010d35a93825a5134f87f" />

**Remove Object**: the woman at the end of the dock brushed over, then **Remove**, and the dock and the lake fill where she sat. Bria Eraser's real answer, played four times as fast as it came.

![Before and after Remove Object on a dock on Lake Geneva: on the left, the woman sitting at the end of the dock under the brushed area, labeled Brushed; on the right, the dock and the lake where she sat, labeled Removed](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-remove-object.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=a8d73ad4a38f4fb2b09bbde530fb7ed3)

**Remove Object**, before and after: the area brushed over the woman, then the dock and the lake where she sat. Bria Eraser's real answer.

<video autoPlay muted loop playsInline src="https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-generate.mp4?fit=max&auto=format&n=AfjjkfPM_42cL5VY&q=85&s=04736f1c86caa5e335ed44f1a501fa07" />

**Generate** in **Edit**: the plant on the coffee table brushed over, red roses asked for in words, then white tulips over the same areas, each image one undo step, and Undo and Redo walking between the two. Claude Sonnet 5.5's and FLUX.1 Fill \[pro]'s real answers, played four times as fast as they came.

![Before and after Generate in a living room: on the left, the plant and the vase on the coffee table under the brushed area, labeled with the words sent, A glass vase of red roses on the coffee table; on the right, a glass vase of red roses on the table, labeled Generated](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-generate.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=3d715fb693225d52efb2a28e0b1071a6)

**Generate** in **Edit**, before and after: the plant brushed over with the words asked, then the roses in its place. Claude Sonnet 5.5's and FLUX.1 Fill \[pro]'s real answers.

> [!NOTE]
>
> Full and Trial only. The Free and the Lite accept `onAiEditImage` and ignore it. It works alone: with it, the brush shows even without [`onAiChooseCommands`](https://docs.embededitor.com/ai/on-ai-choose-commands), and **Generate** with nothing marked edits the whole photo by the words and the image the field holds. With `onAiChooseCommands` too, a Generate in words, on a mark, on the new background after **Remove Background** or with nothing marked, goes through the conversation, which fills the area or edits the photo with this function; a Generate with an image comes straight here, on a mark or, with nothing marked, as the whole photo's edit.

## At Work for a Business

Each operation on a job a business does by hand today, with the real models: more, with the commands the AI ran, in [Use Cases](https://docs.embededitor.com/ai/use-cases.md).

The whole photo edited by words, `'EDIT_PHOTO'` on Seedream 5.5: an architecture studio's facade renovated, then its materials named in **Annotate**; a landscape designer's bare backyard made a garden; a café decorated for Christmas.

![A two-story house in blue siding behind its deck, labeled Original; beside it the same house renovated, its walls in white render, its windows in black frames, the chimney and the door's surround clad in timber, with cards in each material's own color: Timber cladding, Chimney, door surround, orange, on two lines; White render, Smooth stucco, white; Black frames, Every window, black, beside a magnifier with an orange rim on the lawn showing a window's black frame on the white render, its line up to the frame; under it, the two requests](https://mintcdn.com/feliperohde/upG7bjEmk-qJmOys/images/ai-facade-renovation.webp?fit=max\&auto=format\&n=upG7bjEmk-qJmOys\&q=85\&s=600d299116ceba282219b5fef133ae5b)

![A bare backyard, a concrete patio beside a lawn inside a tall wooden fence, labeled Original; beside it the same yard, the patio made a timber deck, four olive trees on the lawn and string lights hung across it; under it, the request](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-backyard-garden.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=c3511a4b6cceca52f78296409ea91bee)

![A café's dining room of wooden tables and cross-back chairs, labeled Original; beside it the same room, pine garlands with warm lights and red baubles strung across its ceiling; under it, the request](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-cafe-christmas.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=57a3147d8fcadd736c0a21eed425ffb5)

An area generated, `'GENERATE_AREA'` on FLUX.1 Fill \[pro]: a fashion store's red dress brushed over, then asked in emerald silk, and in sapphire over the same areas.

![A woman in a long red dress on a road under a sandy hillside, the dress under the AI's brushed area, labeled Brushed; the same woman in an emerald green silk dress; and in a sapphire blue silk dress, each labeled with its request](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-dress-colors.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=e14f20b76747e6c9b9b77b2f294d6ef1)

An object removed, `'ERASE_AREA'` on Bria Eraser: a pet photographer's leash; a marketplace seller's clutter round an armchair, then the photo made brighter and a scratch noted in **Annotate**.

![A Pomeranian's portrait on the grass, its leash and its clip under the AI's brushed area, labeled Brushed; beside it the same portrait with no leash, the fur and the grass where it ran, labeled Removed](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-dog-leash.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=2832055bb1697827651b5fd59c05f62e)

![An old striped armchair by a window in a dim room, a lamp on a side table and papers on the floor beside it under the AI's brushed area, labeled Brushed; beside it the armchair alone in the room, brighter, a magnifier over the dark shelves beside it showing the scratch on its left arm, under the card Small scratch, Left arm, priced in, its line to the spot; under it, the steps and the requests](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-armchair-listing.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=f09e841e1931983091b6a2bfac170ef7)

A new background, `'GENERATE_BACKGROUND'` on Bria FIBO 2.0 Edit, after **Remove Background**, and borders, `'GENERATE_BORDERS'` on Bria FIBO Edit 1.5 Expand: a car dealer's SUV on a coastal road at sunset, its features then called out in **Annotate**; a cosmetics brand's serum on water and petals, expanded to a 16:9 banner; a race car in a pit lane at night, expanded to 16:9.

![A matte black SUV parked against a gray concrete wall, labeled Original; the SUV alone on the checkerboard, labeled Background removed; and under them the SUV on a coastal road at sunset, the sea and the cliffs behind it, and black labels with orange dots and lines: Slim headlights, Tinted windows, Slim tail lights and Aero wheels, labeled with the two requests](https://mintcdn.com/feliperohde/upG7bjEmk-qJmOys/images/ai-car-coastal-road.webp?fit=max\&auto=format\&n=upG7bjEmk-qJmOys\&q=85\&s=93025a683318349741b00dcbc4fb6076)

![An amber dropper bottle with a blank label on a concrete block against a beige wall, labeled Original; the bottle and its block on the checkerboard, labeled Background removed; and under them a 16:9 banner, the bottle on its block over still water rippling round it, white petals floating on it, labeled with the request and the ratio](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-serum-banner.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=d25b0e353d403c52dd879bd42fb38369)

![A yellow and blue stock car seen from behind on a banked track, labeled Original; the car alone on the checkerboard, labeled Background removed; and under them a 16:9 banner, the car on a wet pit lane at night between lit garages and stacks of tires under floodlights, labeled with the request and the ratio](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-race-car-pit-lane.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=77ec3f68dfc47d90549148decf525571)

Whole jobs, chained in one take, each with the operations it sends your function, the models' real answers played four times as fast as they came:

<video autoPlay muted loop playsInline src="https://mintcdn.com/feliperohde/upG7bjEmk-qJmOys/images/ai-showcase-listing-at-dusk.mp4?fit=max&auto=format&n=upG7bjEmk-qJmOys&q=85&s=32341b30d1c0b01d5c2d0dfee768e255" />

The real estate agency's listing: a warm dusk with the lights on, asked with nothing marked (`'EDIT_PHOTO'`, Seedream 5.5), then the recycling bins brushed over and removed (`'ERASE_AREA'`, Bria Eraser), the selling points marked and the agency's logo.

<video autoPlay muted loop playsInline src="https://mintcdn.com/feliperohde/97uFNfnZlTo37nAH/images/ai-showcase-sneaker-banner.mp4?fit=max&auto=format&n=97uFNfnZlTo37nAH&q=85&s=931205ecdebb40bc004d39ec9b819920" />

The online store's banner: the sneaker's background removed ([`onAiRemoveBackground`](https://docs.embededitor.com/ai/on-ai-remove-background)), a wet street at night with neon reflections asked in words (`'GENERATE_BACKGROUND'`, Bria FIBO 2.0 Edit), then **Expand** to 16:9 (`'GENERATE_BORDERS'`, Bria FIBO Edit 1.5 Expand), and its selling points called out.

<video autoPlay muted loop playsInline src="https://mintcdn.com/feliperohde/wg-vxNGPN5xa0lfQ/images/ai-showcase-banquet-set-up.mp4?fit=max&auto=format&n=wg-vxNGPN5xa0lfQ&q=85&s=0477a4ba1469f092d244e090afd40768" />

The wedding planner's venue: an empty barn set for a banquet with round tables, white peonies, candles and fairy lights, asked with nothing marked (`'EDIT_PHOTO'`, Seedream 5.5), the walls, windows and arch kept, then the day laid out on it.

## Wire It

In the page, `onAiEditImage` posts what the person asked to your server, by its `operation` with that operation's own fields, and reads the image back:

```ts page.ts theme={"dark"}
import type { EmbedEditorProps } from '@embededitor/full/react';

// the AI's fill through your server's route (route.ts): its fields as a form, its images as files, `borders` as JSON
const onAiEditImage: EmbedEditorProps['onAiEditImage'] = async ({ signal, ...input }) => {
	const body = new FormData();

	for (const [key, value] of Object.entries(input)) {
		if (value instanceof Blob) {
			body.append(key, value);
		} else if (value !== null) {
			body.append(key, typeof value === 'string' ? value : JSON.stringify(value));
		}
	}

	const res = await fetch('/api/ai-edit-image', { body, method: 'POST', signal });

	if (!res.ok) {
		throw new Error('The fill failed.');
	}

	return res.blob();
};
```

On your server, a route makes the fill again, by its operation, and fills it through one of [the servers below](#servers), here as a Next.js route handler:

```ts route.ts theme={"dark"}
import type { AiEditImageInput } from '@embededitor/full/react';

import retouch from './retouch';

// the fill the page posted (page.ts), onAiEditImage's input again by its operation; null for a form without its images or
// its operation
const fillInput = ({ form, signal }: { form: FormData; signal: AbortSignal }): AiEditImageInput | null => {
	const image = form.get('image');
	const mask = form.get('mask');
	const operation = form.get('operation');
	const prompt = `${form.get('prompt') ?? ''}`;
	const reference = form.get('referenceImage');
	const referenceImage = reference instanceof Blob ? reference : null;

	if (!(image instanceof Blob)) {
		return null;
	}

	// the whole photo edited by words has no mask; every other fill has one
	if (operation === 'EDIT_PHOTO') {
		return { image, operation: 'EDIT_PHOTO', prompt, referenceImage, signal };
	}

	if (!(mask instanceof Blob)) {
		return null;
	}

	switch (operation) {
		case 'ERASE_AREA':
			return { image, mask, operation: 'ERASE_AREA', signal };
		case 'GENERATE_AREA':
			return { image, mask, operation: 'GENERATE_AREA', prompt, referenceImage, signal };
		case 'GENERATE_BACKGROUND':
			return { image, mask, operation: 'GENERATE_BACKGROUND', prompt, referenceImage, signal };
		case 'GENERATE_BORDERS':
			return { borders: JSON.parse(`${form.get('borders')}`), image, mask, operation: 'GENERATE_BORDERS', prompt, signal };
		default:
			return null;
	}
};

export const POST = async (request: Request) => {
	const form = await request.formData();
	const input = fillInput({ form, signal: request.signal });

	if (!input) {
		return new Response('No fill', { status: 400 });
	}

	const res = await retouch.editImage(input);

	return new Response(res.image, { headers: { 'content-type': res.image.type } });
};
```

Pass the function to `EmbedEditor`, or as the same option of `mountEditor` and `openEditor`.

`operation` is `onAiEditImage`'s alone. [`onAiRemoveBackground`](https://docs.embededitor.com/ai/on-ai-remove-background) and [`onAiDetectObjects`](https://docs.embededitor.com/ai/on-ai-detect-objects) do one job each, so the editor sends them none: it would only repeat the function's name. To send every function to one route, add the operation you name yourself to their input:

```ts one-route.ts theme={"dark"}
import type { EmbedEditorProps } from '@embededitor/full/react';

// every AI function's input to one route of your server (/api/ai), as a form, its images as files: the route tells them
// apart by `operation`, the one onAiEditImage's input names, or the one added here to the two that do one job each
const post = async ({ signal, ...input }: { signal: AbortSignal } & Record<string, unknown>) => {
	const body = new FormData();

	for (const [key, value] of Object.entries(input)) {
		if (value instanceof Blob) {
			body.append(key, value);
		} else if (value !== null) {
			body.append(key, typeof value === 'string' ? value : JSON.stringify(value));
		}
	}

	const res = await fetch('/api/ai', { body, method: 'POST', signal });

	if (!res.ok) {
		throw new Error('The AI failed.');
	}

	return res;
};

const onAiDetectObjects: EmbedEditorProps['onAiDetectObjects'] = async input => {
	const res = await post({ ...input, operation: 'DETECT_OBJECTS' });

	return res.json();
};

const onAiEditImage: EmbedEditorProps['onAiEditImage'] = async input => {
	const res = await post(input);

	return res.blob();
};

const onAiRemoveBackground: EmbedEditorProps['onAiRemoveBackground'] = async input => {
	const res = await post({ ...input, operation: 'REMOVE_BACKGROUND' });

	return res.blob();
};
```

## What the Editor Sends

![A fill in a living room in five pictures: the photo with the plant and the vase on the coffee table brushed over, labeled Brushed; the piece of the photo round the mark, labeled image; its mask, white where to fill and black elsewhere, labeled mask; the same piece with a glass vase of red roses on the table, labeled Your image; and the photo with the roses pasted into the mark alone, labeled Pasted in the mark](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-fill-pipeline.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=6ee937c8ef8520ace3a7b5ff5ed48a21)

What `onAiEditImage` gets and gives back on a **Generate** in **Edit**, taken from the real editor: the area brushed over the plant, the `image` and `mask` the editor sent, the image the server gave back (FLUX.1 Fill \[pro]'s real answer), and the photo with it pasted into the mark alone.

```ts theme={"dark"}
type AiBorders = { bottom: number; left: number; right: number; top: number };

type AiEditImageInput =
	| { image: Blob; operation: 'EDIT_PHOTO'; prompt: string; referenceImage: Blob | null; signal: AbortSignal }
	| { image: Blob; mask: Blob; operation: 'ERASE_AREA'; signal: AbortSignal }
	| { image: Blob; mask: Blob; operation: 'GENERATE_AREA'; prompt: string; referenceImage: Blob | null; signal: AbortSignal }
	| { image: Blob; mask: Blob; operation: 'GENERATE_BACKGROUND'; prompt: string; referenceImage: Blob | null; signal: AbortSignal }
	| { borders: AiBorders; image: Blob; mask: Blob; operation: 'GENERATE_BORDERS'; prompt: string; signal: AbortSignal };

onAiEditImage?: (input: AiEditImageInput) => Promise<Blob>;
```

**operation** `'EDIT_PHOTO' | 'ERASE_AREA' | 'GENERATE_AREA' | 'GENERATE_BACKGROUND' | 'GENERATE_BORDERS'`

What the person asked, each operation with its own fields alone, so your server routes the fill with one `switch`, as [the servers below](#servers) do:

* `'EDIT_PHOTO'`: the whole photo edited by words, with nothing marked: **Generate** in **Edit** with nothing marked and no [`onAiChooseCommands`](https://docs.embededitor.com/ai/on-ai-choose-commands), the conversation's `retouch_run` with `{ "kind": "ALL" }`, and `retouch.run()` with `{ kind: 'ALL' }`, with `prompt` and `referenceImage` and no `mask`. `image` is the whole photo. Your image is that photo with the request done and the rest as it was: the editor lays it whole over the photo, so what the words don't name must stay where it stood, as a model made to edit a photo by an instruction keeps it. A model that fills a mask, given the whole photo as its mask, draws another photo: on 2026-11-26, FLUX.1 Fill \[pro] asked to furnish an empty room gave back another room, its walls, windows and light new. The servers below send it to Seedream 5.5 ([Which Model](#which-model)).
* `'ERASE_AREA'`: **Remove** in **Remove Object**, to take away what is marked and fill it with what surrounds it. `image`, `mask` and `signal`, no words.
* `'GENERATE_AREA'`: **Generate** on a mark, in **Edit**, with `prompt` and `referenceImage`.
* `'GENERATE_BACKGROUND'`: the new background's **Generate** after **Remove Background**, with `prompt` and `referenceImage`. `image` is the whole photo, transparent where the cut took the background away, and `mask` is white there and black over the subject. The editor lays your image whole under the cut photo, so the subject stays as the cut left it. A model made to put a subject on a new background follows the words better than one that fills a mark: the servers below send the words to Bria FIBO 2.0 Edit ([Which Model](#which-model)), and an image, which only [`retouch.run()`](https://docs.embededitor.com/api-reference/commands/ai#run) sends here, to the model that places the person's image.
* `'GENERATE_BORDERS'`: an **Expand** and its **Generate Again**, with `borders` and `prompt`.

**borders** `AiBorders`

For `'GENERATE_BORDERS'`: the widths in px of `image` of the borders the Expand adds on each side. `image` is then the bigger photo, its borders transparent, and `mask` is white on them alone. A model made to expand takes the photo and these widths, not a mask: [the servers below](#servers) cut the photo out of `image` by them and send it so.

<video autoPlay muted loop playsInline src="https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-expand.mp4?fit=max&auto=format&n=AfjjkfPM_42cL5VY&q=85&s=7c117ed0186adabb8ac1a79dbc21bb2d" />

**Expand** in the Aspect section, at 16:9: the lake and its hills carried into the new borders, with **Generate Again** on the card for another. Bria FIBO Edit 1.5 Expand's real answer, played four times as fast as it came.

![Lake Bled and its island church, labeled Original, then expanded to 16:9, the lake, the forests and the mountains carried into new borders on both sides, labeled Expanded to 16:9](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-expand.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=6b61a2b8b667df356dbc7b0369483851)

**Expand** to 16:9, before and after: the photo, then its borders filled. Bria FIBO Edit 1.5 Expand's real answer.

**image** `Blob`

A PNG of the piece of the photo around the mark: the mark's box, grown by 30 % of its longer side on each side, then to at least 512 px of the photo a side (or the whole photo, when it is smaller), kept inside the photo. For `'EDIT_PHOTO'`, the whole photo. At most 2048 px on its longer side. It is the photo with the AI's own edits alone, such as an earlier fill or a background taken off: no crop, rotation, adjustments, filter, frame, annotations or Obfuscate areas.

**mask** `Blob`

For every operation but `'EDIT_PHOTO'`. A PNG of the same size, opaque: white where to fill, black elsewhere, nothing in between.

**prompt** `string`

For every operation but `'ERASE_AREA'`. What to put there: `'a small glass vase with red roses'`; for `'EDIT_PHOTO'`, what to add or change: `'Furnish this room with contemporary furniture'`. With [`onAiChooseCommands`](https://docs.embededitor.com/ai/on-ai-choose-commands), a Generate in words, on a mark, on the new background after **Remove Background** or with nothing marked, goes through the conversation, and the model writes these words from the person's, in English whatever their language, as the editor's guide asks. Without `onAiChooseCommands`, and for a Generate with an image, they are the person's words as typed, in their language; `''` where they gave only an image. For `'GENERATE_BORDERS'`, the editor's own words, in English: `'Extend the photo into the empty borders: continue the scene as it would be, matching its light and style.'`, for a model that reads words, or yours, your [`aiPrompts`](https://docs.embededitor.com/ai/customize-prompts)' `expandBorders`.

FLUX.1 Fill \[pro] reads English best: on our plate, it ignored the words in Portuguese three times in three, where the same request in English worked, and on a sneaker's photo a new background asked in Portuguese came back as flames and a second sneaker. It is the only model we tried in another language. Without `onAiChooseCommands`, the editor sends the words as the person typed them; where your people write in another language, translate them on your server before the model's call.

For a new background from words, the recommended server uses Bria FIBO 2.0 Edit: in our tests it followed requests that FLUX.1 Fill \[pro] often ignored. See [Which Model](#which-model).

**referenceImage** `Blob | null`

For `'EDIT_PHOTO'`, `'GENERATE_AREA'` and `'GENERATE_BACKGROUND'`. The image the person added with the field's **Add Image** button, to say what to put there: a PNG of at most 2048 px on its longer side, its transparency kept, so a logo stays cut out. `null` without one. With an image, the request is a Generate, even with no words: the recommended server places it with FLUX 3 Image, which fills the mark's box edge to edge, so the mark sets the size of what it places. For `'EDIT_PHOTO'`, with nothing marked, it goes to Seedream 5.5 as its second image, with the server's own words where the person gave none. Where the person marked only a dot, a tap of the brush, the AI's card says to mark the whole area.

**signal** `AbortSignal`

Aborts when the request stops: the **Stop** on the AI's card, Escape, `ask.stop()` or `ask.end()`, the editor closing or leaving the page, or another image opening. Pass it on to your `fetch` and to your model's call.

## What It Gives Back

The image you made: one `Blob` a call. Each fill is one call: a model that fills an area of its own inside a request about another makes a second one. For another image, the person presses **Generate** again, or your code calls `retouch.more()`, and each image is one undo step. The images are held within 128 MB, one rule for every device, counted two ways. The images the photo on screen shows count as decoded pixels: past 128 MB, they are drawn into the photo as the next image lands, the picture identical to the last pixel, and each stays one undo step back; `retouch.more()` rejects `NOT_FOUND` for an image drawn into the photo. The images only Undo or Redo reach are held compressed, losslessly, and count compressed: past 128 MB of them, the history's oldest steps leave it, as past its 100 steps, but never one whose going leaves it past the limit anyway, nor a step of a request under way. On a 12 MP photo, Undo reaches back ten Generates pressed again over half of it and every step of an Expand to 9:16 asked again twice. An Undo or a Redo onto a step whose images are compressed keeps the photo before it on screen until they are ready; meanwhile the editor waits as during a Save, Undo and Redo still take every press, and past 100 ms the one pressed shows a spinner. `history.undo()` and `history.redo()` resolve once the photo is on screen, and Save, Copy and Share pressed meanwhile wait for it.

It can be any size: the editor resizes it to `image`, then pastes it into the mark alone. Its edge is feathered inside the mark and its color matched to a ring just outside it, so the faint seam every model leaves at the mask's edge doesn't show, and a model that redraws the whole piece serves as well as one that keeps it. Outside the mark, the photo stays as it was, every pixel. For `'EDIT_PHOTO'`, the editor resizes it to the photo and lays it whole over the photo: what stays as it was is what your model kept, so give back an image of the photo's ratio.

It lands on the photo as one undo step. A Remove of the person's mark takes it with it. After a Generate, the areas the person marked stay, hidden, until they mark again, and shown while **Remove Object** is chosen. An area your code or the model names (the whole photo, the background, an outline) shows while its work runs, the whole photo with only its edge glowing, and is written into no area of the person's: they stay as they were, whether the work lands, fails or is stopped. **Generate** pressed again over the same areas, and `retouch.more()`, call your function again with the same piece, mask and image, with new words or the same, and its image takes the place of the one before, as one undo step more: Undo brings the one before back. With nothing marked, **Generate** pressed again with the same words asks for another version of the last whole-photo edit the same way, its `'EDIT_PHOTO'` again; other words make a new edit over the photo as it is. The filled pixels are part of the photo, never of the state a host keeps: Save's `src` holds them.

When your function rejects, the editor shows **Couldn’t Generate the Image** (**Couldn’t Remove the Object** for a Remove, with no words and no image; **Couldn’t Expand the Photo** for an Expand), with your error's message under it, and the person's areas stay, so they can try again. A rejection that is no `Error`, an `Error` with no message, or one of the editor's own (`EmbedEditorError`) shows **Try again.** under the title, and so does an answer that is no image: anything but a `Blob`, a list of them too, or a `Blob` the browser can't read as an image. An image that changed nothing fails too. To tell, the editor compares the image with the piece it was sent, byte by byte, and takes the average difference inside the mark and outside it: when the inside's is less than 1 in 255 above the outside's, the mark changed no more than the rest. That catches a model that gives the piece back, and one that redraws the whole piece without putting anything new in the mark. Where the mark covers the whole piece, as for `'EDIT_PHOTO'`, the inside's average alone must be under 1 in 255. When the image changed nothing, the editor shows **Nothing Changed**, with **The marked area stayed the same. Try again.** under it, and the person's areas stay. `retouch.run()` and `retouch.remove()` reject with `AI_FAILED` in each case, your error as its `cause` when it rejected.

Inside a request, the failure goes to the model, not to the person: with [`onAiChooseCommands`](https://docs.embededitor.com/ai/on-ai-choose-commands), a Generate in words is a request, on a mark or on the new background after **Remove Background**, and so is any fill the model asks for with its `retouch_run`, `retouch_remove` or `crop_expand` tool. The model gets the failure as its tool's answer, with nothing on the card nor your error's message, and the request goes on: the model can try again, or tell the person in its reply.

## Which Model

We tested the models with the editor's requests and evaluated each image after the editor's paste. The recommended server uses the models below. Results are from small samples and prices are from November 2026; try them on your own photos and requests.

* **Remove an object — Bria Eraser on fal.** Good results on the first three photos; it made unwanted objects on two harder removals. About US\$ 0.04 a call. Object Eraser on Runware costs less but takes longer and runs at 1024 px.
* **Generate from words in a mark — FLUX.1 Fill \[pro] on Runware.** Good results on the tested photos, with a mask, at US\$ 0.05 a call. Ideogram V3 Edit Turbo on fal costs less; no ready server below runs it.
* **Put a reference image in a mark — Seedream 5.5 on Runware.** Given the mask as an image, it placed the product at the scene's scale in 5 of 6 attempts. About US\$ 0.044 a call. GPT Image 2.6 on fal takes the mask directly.
* **Put a reference image on a new background — FLUX 3 Image on Runware.** Fills the background's box with the reference image. About US\$ 0.048 a call. GPT Image 2.6 on fal is an alternative.
* **Expand — Bria FIBO Edit 1.5 Expand on fal.** No broken borders in ten Expands, at the canvas's size. US\$ 0.04 a call. FLUX Outpainting on Runware is an alternative, with a canvas size limit.
* **Generate a new background from words — Bria FIBO 2.0 Edit on Runware.** Followed both requests on all four test photos, keeping the subject in place. US\$ 0.04 a call. The same model on fal was as good and faster in this test.
* **Edit the whole photo — Seedream 5.5 on Runware.** Kept the parts the request did not name well in our tests. About US\$ 0.043 a call. Seedream 5.5 and Nano Banana 2.1 on fal are alternatives.

A model may leave out or change part of a subject, and Remove only changes what the mark covers: include the shadow when it should go too. The mixed server uses both fal and Runware; the servers below also offer a fal-only and a Runware-only setup.

## What the Editor Sends, What Your Server Adapts

The editor sends every model the same request, and your server turns it into what its model takes.

**What the editor sends**, whichever model your server calls, as [What the Editor Sends](#what-the-editor-sends) gives it field by field:

* `operation`, what the person asked: `'EDIT_PHOTO'`, `'ERASE_AREA'`, `'GENERATE_AREA'`, `'GENERATE_BACKGROUND'` or `'GENERATE_BORDERS'`, each with its own fields alone.
* `image`, the piece of the photo around the mark, as a PNG: the mark's box grown by 30 % of its longer side on each side, to at least 512 px a side where the photo is that large, then shrunk, where it is longer, to 2048 px on its longer side. For `'GENERATE_BACKGROUND'`, the whole photo, transparent where the cut took the background away; for `'EDIT_PHOTO'`, the whole photo.
* `mask`, a PNG of the piece's size, white where to fill and black elsewhere; none for `'EDIT_PHOTO'`.
* `prompt`, for every operation but `'ERASE_AREA'`: the person's words, `''` where they gave only an image. For `'GENERATE_BORDERS'`, the editor's own words instead, asking to continue the scene into the borders; the servers below send them to neither of the models made to expand, which take no words.
* `referenceImage`, for `'EDIT_PHOTO'`, `'GENERATE_AREA'` and `'GENERATE_BACKGROUND'`: the person's image, a PNG of at most 2048 px on its longer side, or `null`.
* `borders`, for `'GENERATE_BORDERS'`: `image` is then the photo on its bigger canvas, at most 2048 px on its longer side, its new borders transparent, `mask` is white on them, and `borders` holds their four widths in that canvas's px.

**What it takes back:** one image of any size. The editor stretches it over the piece, or over the bigger photo for an Expand, and pastes it into the mark alone; a new background goes whole under the cut photo, and the whole photo's edit whole over it. So a model that answers at a size of its own, or redraws the whole piece, serves as well as one that keeps it.

**Why the editor does no more.** It doesn't know which model your server calls, and each model takes the request in its own shape. So the editor sends one request that carries what any of them needs, and your server, the one part of your integration that knows its model, does the adapting. That is also what lets you change the model, or the provider, with no new version of the editor.

**What the servers below adapt**, model by model:

| Model | What the server adapts | Why |
| - | - | - |
| Bria Eraser, on fal | Nothing: the piece and its mask go as they come. | It takes the piece at its size and answers at it. |
| Object Eraser, on Runware | It stretches the piece and its mask to a 1024 px longer side, the mask by its nearest px so it stays black and white, and the image back to the piece's size. | It runs only on an image whose longer side is 512 or 1024 px. |
| FLUX.1 Fill \[pro], on Runware or fal | Nothing: the piece, its mask and the words go as they come. | It takes a mask, at the piece's size. |
| Seedream 5.5, on Runware, the person's image in a mark | Nothing to the images: the piece, the person's image and the mask go as its three references, at 1K. The words go after its own: put the object only where the third image is white, at its true size. | It takes no mask; given the mask as an image, it keeps to the mark, and the editor's paste keeps the mark alone. It answers at its own size, at the piece's ratio. |
| FLUX 3 Image, on Runware, the person's image as the new background | It reads the box around the mask's white, and sends that box with the piece and the person's image as its two references. A mask that marks nothing rejects before any call. | It takes boxes, not a mask, and fills the box. The editor's paste keeps what lands in the mark. |
| GPT Image 2.6, on fal | It shrinks the piece and its mask to a 1024 px longer side, the mask by its nearest px. The person's image goes as it comes. | It answers at about the size it is sent, and fal bills it by its tokens: about a megapixel keeps the call near US\$ 0.07. |
| Bria FIBO Edit 1.5 Expand, on fal | It cuts the photo out of the bigger one by the four widths, every px opaque, and sends it with the canvas's size and the photo's place and size in it. | It takes the photo and where it stands, not the bigger photo and a mask. |
| FLUX Outpainting, on Runware | It cuts the photo out the same way and sends it with the four widths. Where the canvas, padded as BFL pads it to 16 px, passes 4,194,304 px, it shrinks the canvas to a 2000 px longer side, the photo and the widths with it, and stretches the image back to the canvas. | It takes the photo and the widths. In its fast mode it refuses a canvas past 4,194,304 px, which a 2048 × 2048 one is once padded. |
| Bria FIBO 2.0 Edit, on Runware or fal | Nothing to the images: the piece and its mask go as they come. The words go after "Replace the background with:". | It takes a mask at the piece's size and answers at it, the rest of the piece kept, within 3 of 255 on average in our measurements. It edits by an instruction, not by a description. |
| Seedream 5.5, on Runware or fal | Nothing to the images: the photo goes as its first image, the person's image, where there is one, as its second, at 2K. With an image and no words, the server's own words: put what the second image shows into the first, and keep the rest. | It edits by an instruction, with no mask, and takes no empty words. It answers larger than it is sent, at the photo's ratio (2496 × 1664 for 2048 × 1365). |

**The image library.** That adapting runs on photon (`@cf-wasm/photon`), an image library compiled to WebAssembly, through one module, [`images.ts`](#the-image-library). We don't use sharp, the usual image library on Node, because it runs native code, which Cloudflare Workers, Vercel's Edge runtime and Deno Deploy don't run: a server on sharp runs on Node alone. Photon runs on Node and on Cloudflare Workers with the same code, and its package also has builds for Next.js's Edge runtime and other hosts; the editor's playground runs these servers on Node and on a Worker. Install it beside your server:

```bash theme={"dark"}
npm install @cf-wasm/photon
```

On the bench's photos, photon gives what sharp gives: the same sizes and crops, and masks shrunk by the nearest px the same px for px. Its Lanczos3 shrinks of a photo are within 0.2 of 255 of sharp's on average. Where it grows an image, it places each px by its center, where sharp places it half a px off. It is slower, up to five times sharp's time on the servers' own work: a call's image work takes from under 0.05 s of CPU (FLUX 3 Image's box) to about 0.87 s (FLUX Outpainting's whole call on a 2048 × 2048 canvas), measured on Node. On Node, photon runs on your server's main thread, where sharp works on threads of its own, so while one call's image work runs, the other requests of that server process wait for it. On Cloudflare Workers, a server needs the Workers Paid plan for that CPU, and Node.js compatibility ([On Cloudflare Workers](https://docs.embededitor.com/ai/overview.md#on-cloudflare-workers)).

## Servers

Each server is one module for your server, with the same `editImage` function: it takes the editor's input as it comes, and routes it with one `switch` on its `operation`, and resolves to `{ cost, image, model }`, the image it made, what the call cost in US\$, and the model that made it. Each call has two minutes, past which it rejects with "The model took too long." The person's Stop ends the wait at once; on fal, it also asks fal to cancel the job, which fal's own client doesn't do, and fal drops a job it hasn't started yet but finishes, and bills, one it has ([the fal job](#the-fal-job)).

### Bria Eraser, FLUX.1 Fill \[pro], FLUX 3 Image, Bria FIBO Expand, Bria FIBO 2.0 Edit and Seedream 5.5

The recommended server: `'ERASE_AREA'` on fal's Bria Eraser, `'EDIT_PHOTO'` on Runware's Seedream 5.5, `'GENERATE_AREA'`'s words on Runware's FLUX.1 Fill \[pro] and its image on Runware's Seedream 5.5, `'GENERATE_BACKGROUND'`'s words on Runware's Bria FIBO 2.0 Edit and its image placed by Runware's FLUX 3 Image, and `'GENERATE_BORDERS'` on fal's Bria FIBO Edit 1.5 Expand. It runs `retouch-fal.ts`'s `erase` and `outpaint` and `retouch-runware.ts`'s `editPhoto`, `generate`, `place`, `placeObject` and `replaceBackground`, so put those two beside it, with [`bordered.ts`](#the-bigger-photo), [`images.ts`](#the-image-library), [`fal-job.ts`](#the-fal-job), [`runware-task.ts`](#the-runware-task) and [`limit.ts`](#the-time-limit). It needs `@fal-ai/client`, `@cf-wasm/photon`, `FAL_KEY` and `RUNWARE_API_KEY`. The editor's playground runs this file, word for word, on Node and on Cloudflare Workers.

```ts retouch.ts theme={"dark"}
import type { AiEditImageInput } from '@embededitor/full/react';

import retouchFal from './retouch-fal';
import retouchRunware from './retouch-runware';

// The editor's onAiEditImage on the models that did best in our measurements (2026-11-08, 2026-11-09, 2026-11-26 and
// 2026-11-27), for the site's server, by the fill's operation: ERASE_AREA (Remove) on Bria Eraser and GENERATE_BORDERS
// (Expand) on Bria FIBO Edit 1.5 Expand, both through fal (retouch-fal.ts, FAL_KEY); EDIT_PHOTO (the whole photo edited by
// words, nothing marked) on Seedream 5.5, with the person's image where they gave one, GENERATE_AREA (Generate) from the
// words alone on FLUX.1 Fill [pro] and with the person's image, with words or none, on Seedream 5.5, GENERATE_BACKGROUND
// (the new background) from the words alone on Bria FIBO 2.0 Edit and with the person's image placed by FLUX 3 Image, all
// through Runware (retouch-runware.ts, RUNWARE_API_KEY). Each call makes one image, with the model that made it and what it
// cost

// the editor's fill `input`, by its operation, its image placed where it sends one. `input.signal` stops the call when the
// person stops
const editImage = (input: AiEditImageInput) => {
	switch (input.operation) {
		case 'EDIT_PHOTO':
			return retouchRunware.editPhoto(input);
		case 'ERASE_AREA':
			return retouchFal.erase(input);
		case 'GENERATE_AREA':
			return input.referenceImage ? retouchRunware.placeObject({ ...input, referenceImage: input.referenceImage }) : retouchRunware.generate(input);
		case 'GENERATE_BACKGROUND':
			return input.referenceImage ? retouchRunware.place({ ...input, referenceImage: input.referenceImage }) : retouchRunware.replaceBackground(input);
		case 'GENERATE_BORDERS':
			return retouchFal.outpaint(input);
	}
};

export default { editImage };
```

### fal: Bria Eraser, FLUX.1 Fill \[pro], GPT Image 2.6, Bria FIBO Expand, Bria FIBO 2.0 Edit and Seedream 5.5

Everything on fal, with one key. The images go up to fal's storage once each, and [`fal-job.ts`](#the-fal-job) runs each job. fal bills FLUX.1 Fill \[pro] in proportion to the megapixels it gives back, so a larger piece costs more: US\$ 0.05 for a megapixel, US\$ 0.21 for 2048 × 2048 px. GPT Image 2.6 takes the mask and the person's image together and answers at about the size it is sent, so the server shrinks the piece and its mask to a 1024 px longer side with [`images.ts`](#the-image-library) (the mask by its nearest px, so it stays black and white). fal bills it by its tokens and reports none, so its cost is our estimate, about US\$ 0.07. Bria FIBO Edit 1.5 Expand takes the photo, the size of the bigger photo and the photo's place in it, so the server cuts the photo out with [`bordered.ts`](#the-bigger-photo), and answers at the bigger photo's size, at US\$ 0.04 a call. Bria FIBO 2.0 Edit takes the new background's piece and mask as they come, with the words after "Replace the background with:", and answers at the piece's size, at US\$ 0.04 a call. Seedream 5.5 takes the whole photo, and the person's image after it, with no mask, at `auto_2K`, and answers larger than the photo at its ratio; fal bills US\$ 0.0405 for the image and US\$ 0.012 for each image it is sent, US\$ 0.0525 with the photo alone. It needs `@fal-ai/client`, `bordered.ts`, `images.ts` and `FAL_KEY`.

```ts retouch-fal.ts theme={"dark"}
import { fal } from '@fal-ai/client';

import type { AiBorders, AiEditImageInput } from '@embededitor/full/react';

import bordered from './bordered';
import falJob from './fal-job';
import images from './images';

// The editor's onAiEditImage on fal alone, for the site's server, where the key stays (FAL_KEY), by the fill's operation:
// EDIT_PHOTO (the whole photo edited by words, nothing marked) on Seedream 5.5, with the person's image where they gave one;
// ERASE_AREA (Remove) on Bria Eraser; GENERATE_AREA (Generate) from the words alone on FLUX.1 Fill [pro];
// GENERATE_BACKGROUND (the new background) from the words alone on Bria FIBO 2.0 Edit; the person's image for either, with
// words or none, placed by GPT Image 2.6; GENERATE_BORDERS (Expand), where the editor sends the widths of the borders it
// adds, on Bria FIBO Edit 1.5 Expand. The images go up to fal's storage once each, then one job makes one image
// (fal-job.ts runs it, with its time limit and its cancel on a stop), which comes back with the model that made it and
// what the call cost, at fal's prices of November 2026. Bria's Expand takes the photo, not the bigger photo and a mask, so
// the photo goes cut out of it (bordered.ts), with the size of the bigger photo and its place in it. Bria Eraser takes no
// seed, so a second Remove of the same piece may repeat the first. GPT Image 2.6 answers at about the size it is sent, so
// its piece and mask go shrunk to PLACE_SIDE (images.ts; the mask by its nearest px, so it stays black and white), and the
// editor resizes its image to the piece. FLUX.1 Fill [pro] paints around a subject what the subject suggests, whatever the
// words (a restaurant under a plate asked a sky for), so the new background goes to Bria FIBO 2.0 Edit, which followed the
// words in each of our measurements; given the whole photo as its mask, it draws another photo, so the whole photo's edit
// goes to Seedream 5.5, which kept the photo and did what was asked

// fal's endpoints
const BACKGROUND_ENDPOINT = 'bria/fibo-2/edit';
// US$ a call of Bria FIBO 2.0 Edit
const BACKGROUND_PRICE = 0.04;
// what Bria FIBO 2.0 Edit is told, before the person's words
const BACKGROUND_PROMPT = 'Replace the background with:';
const EDIT_ENDPOINT = 'bytedance/seedream/v5.5/edit';
// US$ Seedream 5.5 bills for each image it is sent, beside EDIT_PRICE
const EDIT_INPUT_PRICE = 0.012;
// US$ an image of Seedream 5.5 at 2K
const EDIT_PRICE = 0.0405;
const ERASER_ENDPOINT = 'fal-ai/bria/eraser';
// US$ a call of Bria Eraser
const ERASER_PRICE = 0.04;
const EXPAND_ENDPOINT = 'bria/fibo-edit-1.5/expand';
// US$ a call of Bria FIBO Edit 1.5 Expand
const EXPAND_PRICE = 0.04;
const FILL_ENDPOINT = 'fal-ai/flux-pro/v1/fill';
// US$ a megapixel of the image FLUX.1 Fill [pro] gives back
const FILL_PRICE = 0.05;
const PLACE_ENDPOINT = 'openai/gpt-image-2.6/flare/edit';
// US$ a call of GPT Image 2.6, about: fal bills it by its tokens and reports none, and GPT Image 2's edit of a megapixel at
// the same quality and token prices is US$ 0.061 on fal's page
const PLACE_PRICE = 0.07;
// what GPT Image 2.6 is told, before the person's words
const PLACE_PROMPT =
	"Put the object from the second image into the first image, inside the masked area, standing naturally on what is there, at a realistic scale, matching the first image's light, shadows and perspective. Keep the rest of the first image exactly as it is.";
// the longer side, in px, of the piece and the mask GPT Image 2.6 gets, at most: about a megapixel
const PLACE_SIDE = 1024;
// what Seedream 5.5 is told for the whole photo's edit where the person gave an image and no words (it takes none empty)
const REFERENCE_PROMPT =
	"Put what the second image shows into the first image, at a realistic scale, matching the first image's light, shadows and perspective. Keep the rest of the first image exactly as it is.";

// the editor's fill `input`, by its operation, its image placed where it sends one. `input.signal` stops the call when the
// person stops
const editImage = (input: AiEditImageInput) => {
	switch (input.operation) {
		case 'EDIT_PHOTO':
			return editPhoto(input);
		case 'ERASE_AREA':
			return erase(input);
		case 'GENERATE_AREA':
			return input.referenceImage ? place({ ...input, referenceImage: input.referenceImage }) : generate(input);
		case 'GENERATE_BACKGROUND':
			return input.referenceImage ? place({ ...input, referenceImage: input.referenceImage }) : replaceBackground(input);
		case 'GENERATE_BORDERS':
			return outpaint(input);
	}
};

// `image`, the whole photo, edited by Seedream 5.5 as `prompt`, the person's words, ask, what they don't name kept: the photo
// the first image it gets and `referenceImage`, the person's image, the second where they gave one (REFERENCE_PROMPT the
// words where they gave none), at 2K. One image, larger than the photo with its ratio (the editor resizes it), and the
// call's cost in US$, by the images it was sent. `signal` stops the call when the person stops
const editPhoto = async ({ image, prompt, referenceImage, signal }: { image: Blob; prompt: string; referenceImage: Blob | null; signal: AbortSignal }) => {
	const urls = await Promise.all(referenceImage ? [fal.storage.upload(image), fal.storage.upload(referenceImage)] : [fal.storage.upload(image)]);
	const res = await falJob.run({
		endpoint: EDIT_ENDPOINT,
		signal,
		subscribe: options => {
			return fal.subscribe(EDIT_ENDPOINT, { ...options, input: { image_size: 'auto_2K', image_urls: urls, prompt: prompt || REFERENCE_PROMPT } });
		}
	});
	const [made] = res.data.images;
	const downloaded = await falJob.download({ signal, url: made.url });

	return { cost: EDIT_PRICE + EDIT_INPUT_PRICE * urls.length, image: downloaded, model: 'Seedream 5.5' };
};

// what is marked (white in `mask`) taken out of `image` by Bria Eraser, and filled with what surrounds it: one image, and
// the call's cost in US$. `signal` stops the call when the person stops
const erase = async ({ image, mask, signal }: { image: Blob; mask: Blob; signal: AbortSignal }) => {
	const [imageUrl, maskUrl] = await Promise.all([fal.storage.upload(image), fal.storage.upload(mask)]);
	const res = await falJob.run({
		endpoint: ERASER_ENDPOINT,
		signal,
		subscribe: options => {
			return fal.subscribe(ERASER_ENDPOINT, { ...options, input: { image_url: imageUrl, mask_type: 'manual', mask_url: maskUrl } });
		}
	});
	const downloaded = await falJob.download({ signal, url: res.data.image.url });

	return { cost: ERASER_PRICE, image: downloaded, model: 'Bria Eraser' };
};

// `prompt`, the person's words, put where `mask` is white in `image` by FLUX.1 Fill [pro]: one image, and the call's cost
// in US$, by the megapixels it gave back. `signal` stops the call when the person stops
const generate = async ({ image, mask, prompt, signal }: { image: Blob; mask: Blob; prompt: string; signal: AbortSignal }) => {
	const [imageUrl, maskUrl] = await Promise.all([fal.storage.upload(image), fal.storage.upload(mask)]);
	const res = await falJob.run({
		endpoint: FILL_ENDPOINT,
		signal,
		subscribe: options => {
			return fal.subscribe(FILL_ENDPOINT, { ...options, input: { image_url: imageUrl, mask_url: maskUrl, num_images: 1, output_format: 'png', prompt } });
		}
	});
	const [made] = res.data.images;
	const downloaded = await falJob.download({ signal, url: made.url });

	return { cost: (FILL_PRICE * made.width * made.height) / 1e6, image: downloaded, model: 'FLUX.1 Fill [pro]' };
};

// `image`, the bigger photo the editor sent for an Expand, its borders (`borders`, their widths in its px) filled by Bria
// FIBO Edit 1.5 Expand with the scene carried on: the photo cut out of it goes up to fal's storage, and the model gets the
// size of the bigger photo and the photo's place in it. One image, at the bigger photo's size, and the call's cost in US$.
// `signal` stops the call when the person stops
const outpaint = async ({ borders, image, signal }: { borders: AiBorders; image: Blob; signal: AbortSignal }) => {
	const { canvas, photo } = await bordered.cut({ borders, image });
	const blob = new Blob([new Uint8Array(photo.png)], { type: 'image/png' });
	const url = await fal.storage.upload(blob);
	const res = await falJob.run({
		endpoint: EXPAND_ENDPOINT,
		signal,
		subscribe: options => {
			return fal.subscribe(EXPAND_ENDPOINT, {
				...options,
				input: {
					canvas_size: [canvas.width, canvas.height],
					image_url: url,
					original_image_location: [borders.left, borders.top],
					original_image_size: [photo.width, photo.height]
				}
			});
		}
	});
	const downloaded = await falJob.download({ signal, url: res.data.image.url });

	return { cost: EXPAND_PRICE, image: downloaded, model: 'Bria FIBO Edit 1.5 Expand' };
};

// `referenceImage`, the person's image, placed where `mask` is white in `image` by GPT Image 2.6: the piece and the image its
// two references, the mask its first's, both shrunk to PLACE_SIDE, the person's words after PLACE_PROMPT. One image, at
// the model's own size with the piece's ratio (the editor resizes it), and the call's cost in US$, about. `signal` stops the
// call when the person stops
const place = async ({
	image,
	mask,
	prompt,
	referenceImage,
	signal
}: {
	image: Blob;
	mask: Blob;
	prompt: string;
	referenceImage: Blob;
	signal: AbortSignal;
}) => {
	const [piece, marked] = await Promise.all([shrunk({ blob: image, kernel: 'LANCZOS3' }), shrunk({ blob: mask, kernel: 'NEAREST' })]);
	const [imageUrl, maskUrl, referenceUrl] = await Promise.all([fal.storage.upload(piece), fal.storage.upload(marked), fal.storage.upload(referenceImage)]);
	const res = await falJob.run({
		endpoint: PLACE_ENDPOINT,
		signal,
		subscribe: options => {
			return fal.subscribe(PLACE_ENDPOINT, {
				...options,
				input: {
					image_urls: [imageUrl, referenceUrl],
					mask_url: maskUrl,
					num_images: 1,
					output_format: 'png',
					prompt: prompt ? `${PLACE_PROMPT} ${prompt}` : PLACE_PROMPT,
					quality: 'medium',
					reasoning_effort: 'medium'
				}
			});
		}
	});
	const [made] = res.data.images;
	const downloaded = await falJob.download({ signal, url: made.url });

	return { cost: PLACE_PRICE, image: downloaded, model: 'GPT Image 2.6' };
};

// the new background, `prompt` the person's words, painted by Bria FIBO 2.0 Edit where `mask` is white in `image` (where
// Remove Background took the photo away), the piece and its mask as they came, the words after BACKGROUND_PROMPT. One
// image, at the piece's size, and the call's cost in US$. `signal` stops the call when the person stops
const replaceBackground = async ({ image, mask, prompt, signal }: { image: Blob; mask: Blob; prompt: string; signal: AbortSignal }) => {
	const [imageUrl, maskUrl] = await Promise.all([fal.storage.upload(image), fal.storage.upload(mask)]);
	const res = await falJob.run({
		endpoint: BACKGROUND_ENDPOINT,
		signal,
		subscribe: options => {
			return fal.subscribe(BACKGROUND_ENDPOINT, {
				...options,
				input: { image_urls: [imageUrl], instruction: `${BACKGROUND_PROMPT} ${prompt}`, mask_url: maskUrl }
			});
		}
	});
	const downloaded = await falJob.download({ signal, url: res.data.image.url });

	return { cost: BACKGROUND_PRICE, image: downloaded, model: 'Bria FIBO 2.0 Edit' };
};

// `blob`, a PNG, shrunk by `kernel` to at most PLACE_SIDE px on its longer side (never grown), as a PNG
const shrunk = async ({ blob, kernel }: { blob: Blob; kernel: 'LANCZOS3' | 'NEAREST' }) => {
	const buffer = await blob.arrayBuffer();
	const png = images.shrink({ bytes: new Uint8Array(buffer), kernel, side: PLACE_SIDE });

	return new Blob([new Uint8Array(png)], { type: 'image/png' });
};

export default { editImage, editPhoto, erase, generate, outpaint, place, replaceBackground };
```

### Runware: Object Eraser, FLUX.1 Fill \[pro], FLUX 3 Image, FLUX Outpainting, Bria FIBO 2.0 Edit and Seedream 5.5

Everything on Runware, with one key, and the cheapest Remove. Each call is one task POSTed to Runware's API by [`runware-task.ts`](#the-runware-task), with the images as data URLs; the cost is what Runware billed. Object Eraser fails on any image whose longer side isn't 512 or 1024 px, so the server stretches the piece and its mask to a 1024 px longer side with [`images.ts`](#the-image-library) (the mask by its nearest px, so it stays black and white), and the image back to the piece's size. The person's image in a mark goes to Seedream 5.5, with the piece and the mask as its other references, at `1K`, at a billed US\$ 0.044; as the new background, to FLUX 3 Image, which takes boxes, not a mask: the server gives it the box around the mark, with the person's image as its second reference, and the editor's paste keeps what lands in the mark. Runware holds each call for up to two minutes, then answers a task still running with no image; the server rejects that in the time limit's words. A mask that marks nothing rejects before any call. FLUX Outpainting takes the photo and the borders' widths, so the server cuts the photo out with [`bordered.ts`](#the-bigger-photo); in its fast mode it refuses a canvas past 4 megapixels once padded to 16 px, which a 2048 × 2048 one is, so the server shrinks such a canvas to a 2000 px longer side, the borders with it, and stretches the image back. Bria FIBO 2.0 Edit takes the new background's piece and mask as they come, with the words after "Replace the background with:", and answers at the piece's size. Seedream 5.5 takes the whole photo as its first reference, the person's image as its second, with no mask, at `2K`, and answers larger than the photo at its ratio, at a billed US\$ 0.043 with the photo alone. It needs `bordered.ts`, `images.ts`, `runware-task.ts`, [`limit.ts`](#the-time-limit) and `RUNWARE_API_KEY`, and no SDK: a plain `fetch`.

```ts retouch-runware.ts theme={"dark"}
import type { AiBorders, AiEditImageInput } from '@embededitor/full/react';

import bordered from './bordered';
import images from './images';
import limit from './limit';
import runwareTask from './runware-task';

// The editor's onAiEditImage on Runware alone, for the site's server, where the key stays (RUNWARE_API_KEY), by the fill's
// operation: EDIT_PHOTO (the whole photo edited by words, nothing marked) on Seedream 5.5, with the person's image where
// they gave one; ERASE_AREA (Remove) on Object Eraser; GENERATE_AREA (Generate) from the words alone on FLUX.1 Fill [pro];
// GENERATE_AREA with the person's image, with words or none, on Seedream 5.5; GENERATE_BACKGROUND (the new background) from
// the words alone on Bria FIBO 2.0 Edit, and with the person's image placed by FLUX 3 Image; GENERATE_BORDERS (Expand),
// where the editor sends the widths of the borders it
// adds, on FLUX Outpainting. Each is one task POSTed to Runware's API (runware-task.ts), the images as data URLs, making
// one image, with the model that made it and the cost Runware billed for it. A task runs within limit.ts's time limit and
// stops when the person stops. FLUX Outpainting takes the photo and the borders' widths, not the bigger photo and a mask,
// so the photo goes cut out of it (bordered.ts); in its fast mode it refuses a canvas past OUTPAINT_PX, so a bigger one
// goes shrunk, the borders with it, and its image comes back stretched to the bigger photo. Object Eraser runs only on an
// image whose longer side is ERASER_SIDE, so its piece and mask go stretched to that (the mask by its nearest px, so it
// stays black and white), and its image comes back stretched to the piece (images.ts stretches each). FLUX 3 Image takes
// no mask: it takes boxes, so the image goes into the box around the mask, and the editor's paste keeps what lands in the
// mask. Given the mark's box, FLUX 3 Image fills it with the object edge to edge, so a mark larger than the object gave
// headphones as tall as the sofa behind them; Seedream 5.5 takes no mask either, but given the mask as its third image it
// put the object in the mark at the size the scene gives it (2026-11-27), so the person's image in a mark goes to it.
// FLUX.1 Fill [pro] paints around a subject what the subject suggests, whatever the words (a restaurant under a plate
// asked a sky for), so the new background goes to Bria FIBO 2.0 Edit, which followed the words in each of our measurements.
// Given the whole photo as its mask, FLUX.1 Fill [pro] draws another photo (an empty room asked for furniture came back
// another room), so the whole photo's edit goes to Seedream 5.5, which kept the room and furnished it

// what Bria FIBO 2.0 Edit is told, before the person's words
const BACKGROUND_PROMPT = 'Replace the background with:';
// what a fill with a mask that marks nothing rejects with, before any call to Runware
const EMPTY_MASK = 'The mask marks no area.';
// the longer side, in px, of the images Object Eraser runs on (512 works too; any other size fails)
const ERASER_SIDE = 1024;
// what Seedream 5.5 is told for the person's image put in a mark, before the person's words: the piece, the image and the
// mask its three references
const OBJECT_PROMPT =
	"Put the object from the second image into the first image, only where the third image (a mask of the first) is white, standing naturally on what is there, at its true size against what is around it, matching the first image's light, shadows and perspective. Keep the rest of the first image exactly as it is.";
// BFL's alignment, in px: FLUX Outpainting pads its canvas to a multiple of it, by where the photo stands up to one more
// on a side (BFL counted a 2048 × 2048 canvas as 2064 × 2048 or 2048 × 2064, and one as it was)
const OUTPAINT_ALIGN = 16;
// the most px FLUX Outpainting's fast mode works on, counted on its padded canvas: past it, Runware answers BFL's 422
const OUTPAINT_PX = 4194304;
// the longer side, in px, of a canvas past OUTPAINT_PX once shrunk: the editor sends at most 2048 px, and 2000 × 2000 pads
// to 2016 × 2016 at most
const OUTPAINT_SIDE = 2000;
// what FLUX 3 Image is told, before the person's words: `<object>` is the box that places the image's object
const PLACE_PROMPT =
	"The same photo, with <object> standing where its box is, matching the photo's light, scale and perspective, everything else exactly as it is.";
// what Seedream 5.5 is told for the whole photo's edit where the person gave an image and no words (it takes none empty)
const REFERENCE_PROMPT =
	"Put what the second image shows into the first image, at a realistic scale, matching the first image's light, shadows and perspective. Keep the rest of the first image exactly as it is.";

// `blob`'s bytes
const bytes = async (blob: Blob) => {
	const buffer = await blob.arrayBuffer();

	return new Uint8Array(buffer);
};

// `png`, a PNG's bytes, as a data URL
const dataUrl = (png: Uint8Array) => {
	return `data:image/png;base64,${Buffer.from(png).toString('base64')}`;
};

// the bytes of the image Runware put at `url`, fetched against `signal`
const download = async ({ signal, url }: { signal: AbortSignal; url: string }) => {
	const res = await fetch(url, { signal });

	if (!res.ok) {
		throw new Error(`Runware's image answered ${res.status}`);
	}

	const buffer = await res.arrayBuffer();

	return new Uint8Array(buffer);
};

// the editor's fill `input`, by its operation, its image placed where it sends one. `input.signal` stops the call when the
// person stops
const editImage = (input: AiEditImageInput) => {
	switch (input.operation) {
		case 'EDIT_PHOTO':
			return editPhoto(input);
		case 'ERASE_AREA':
			return erase(input);
		case 'GENERATE_AREA':
			return input.referenceImage ? placeObject({ ...input, referenceImage: input.referenceImage }) : generate(input);
		case 'GENERATE_BACKGROUND':
			return input.referenceImage ? place({ ...input, referenceImage: input.referenceImage }) : replaceBackground(input);
		case 'GENERATE_BORDERS':
			return outpaint(input);
	}
};

// `image`, the whole photo, edited by Seedream 5.5 as `prompt`, the person's words, ask, what they don't name kept: the photo
// its first reference and `referenceImage`, the person's image, its second where they gave one (REFERENCE_PROMPT the words
// where they gave none), at 2K. One image, larger than the photo with its ratio (the editor resizes it), and the cost
// Runware billed in US$. `signal` stops the call when the person stops
const editPhoto = async ({ image, prompt, referenceImage, signal }: { image: Blob; prompt: string; referenceImage: Blob | null; signal: AbortSignal }) => {
	const [photo, reference] = await Promise.all([bytes(image), referenceImage ? bytes(referenceImage) : null]);
	const res = await run({
		signal,
		task: {
			inputs: { referenceImages: reference ? [dataUrl(photo), dataUrl(reference)] : [dataUrl(photo)] },
			model: 'bytedance:seedream@5.5',
			outputFormat: 'PNG',
			positivePrompt: prompt || REFERENCE_PROMPT,
			resolution: '2K',
			taskType: 'imageInference'
		}
	});

	return { cost: res.cost, image: new Blob([new Uint8Array(res.image)], { type: 'image/png' }), model: 'Seedream 5.5' };
};

// what is marked (white in `mask`) taken out of `image` by Object Eraser, and filled with what surrounds it: one image, at
// the piece's size, and the cost Runware billed in US$. `signal` stops the call when the person stops
const erase = async ({ image, mask, signal }: { image: Blob; mask: Blob; signal: AbortSignal }) => {
	const [piece, marked] = await Promise.all([bytes(image), bytes(mask)]);
	const { height, width } = images.size(piece);
	const scale = ERASER_SIDE / Math.max(width, height);
	const size = { height: Math.round(height * scale), width: Math.round(width * scale) };
	const scaledPiece = images.resize({ bytes: piece, kernel: 'LANCZOS3', size });
	const scaledMask = images.resize({ bytes: marked, kernel: 'NEAREST', size });
	const res = await run({
		signal,
		task: { inputs: { image: dataUrl(scaledPiece), mask: dataUrl(scaledMask) }, model: 'runware:300@1', outputFormat: 'PNG', taskType: 'imageInference' }
	});
	const resized = images.resize({ bytes: res.image, kernel: 'LANCZOS3', size: { height, width } });

	return { cost: res.cost, image: new Blob([new Uint8Array(resized)], { type: 'image/png' }), model: 'Object Eraser' };
};

// `prompt`, the person's words, put where `mask` is white in `image` by FLUX.1 Fill [pro]: one image, at the piece's
// size, and the cost Runware billed in US$. `signal` stops the call when the person stops
const generate = async ({ image, mask, prompt, signal }: { image: Blob; mask: Blob; prompt: string; signal: AbortSignal }) => {
	const [piece, marked] = await Promise.all([bytes(image), bytes(mask)]);
	const res = await run({
		signal,
		task: {
			inputs: { maskImage: dataUrl(marked), seedImage: dataUrl(piece) },
			model: 'bfl:1@2',
			outputFormat: 'PNG',
			positivePrompt: prompt,
			taskType: 'imageInference'
		}
	});

	return { cost: res.cost, image: new Blob([new Uint8Array(res.image)], { type: 'image/png' }), model: 'FLUX.1 Fill [pro]' };
};

// the box around the white of `png`, a mask's PNG, as FLUX 3 Image takes it: [top, left, bottom, right] on 0 to 1000; null
// where the mask marks nothing
const maskBox = (png: Uint8Array) => {
	const { data, height, width } = images.pixels(png);
	let bottom = 0;
	let left = width;
	let right = 0;
	let top = height;

	// a plain loop over the mask's px, four bytes each (red first): lodash would box each of them
	for (let p = 0; p < width * height; p += 1) {
		if (data[p * 4] > 127) {
			const x = p % width;
			const y = Math.floor(p / width);

			bottom = Math.max(bottom, y + 1);
			left = Math.min(left, x);
			right = Math.max(right, x + 1);
			top = Math.min(top, y);
		}
	}

	if (!right) {
		return null;
	}

	return [top / height, left / width, bottom / height, right / width].map(edge => {
		return Math.round(edge * 1000);
	});
};

// `image`, the bigger photo the editor sent for an Expand, its borders (`borders`, their widths in its px) filled by FLUX
// Outpainting in its fast mode with the scene carried on: the photo cut out of it and the borders' widths, all shrunk to an
// OUTPAINT_SIDE longer side where the bigger photo, padded, is past OUTPAINT_PX, the photo sent as it was cut otherwise.
// One image, stretched to the bigger photo's size, and the cost Runware billed in US$. `signal` stops the call when the
// person stops
const outpaint = async ({ borders, image, signal }: { borders: AiBorders; image: Blob; signal: AbortSignal }) => {
	const { canvas, photo } = await bordered.cut({ borders, image });
	const scale = padded(canvas.width) * padded(canvas.height) > OUTPAINT_PX ? OUTPAINT_SIDE / Math.max(canvas.width, canvas.height) : 1;
	const size = { height: Math.round(photo.height * scale), width: Math.round(photo.width * scale) };
	const sent = scale === 1 ? photo.png : images.resize({ bytes: photo.png, kernel: 'LANCZOS3', size });
	const res = await run({
		signal,
		task: {
			inputs: { image: dataUrl(sent) },
			model: 'bfl:flux@outpainting',
			// each border rounded on its own, so none goes below 0; the canvas they make may be a px off the shrunk one, and
			// the image is stretched back to the bigger photo anyway
			outpaint: {
				bottom: Math.round(borders.bottom * scale),
				left: Math.round(borders.left * scale),
				right: Math.round(borders.right * scale),
				top: Math.round(borders.top * scale)
			},
			outputFormat: 'PNG',
			settings: { mode: 'fast' },
			taskType: 'imageInference'
		}
	});
	const resized = images.resize({ bytes: res.image, kernel: 'LANCZOS3', size: canvas });

	return { cost: res.cost, image: new Blob([new Uint8Array(resized)], { type: 'image/png' }), model: 'FLUX Outpainting' };
};

// `side`, a side of FLUX Outpainting's canvas in px, as BFL pads it at most (OUTPAINT_ALIGN)
const padded = (side: number) => {
	return Math.ceil(side / OUTPAINT_ALIGN) * OUTPAINT_ALIGN + OUTPAINT_ALIGN;
};

// `referenceImage`, the person's image, placed where `mask` is white in `image` by FLUX 3 Image: the piece and the image
// its two references, one box taking the image's object into the mask's box, the person's words after PLACE_PROMPT. One
// image, at the model's own size with the piece's ratio (the editor resizes it), and the cost Runware billed in US$. A
// mask that marks nothing rejects with EMPTY_MASK, Runware not called. `signal` stops the call when the person stops
const place = async ({
	image,
	mask,
	prompt,
	referenceImage,
	signal
}: {
	image: Blob;
	mask: Blob;
	prompt: string;
	referenceImage: Blob;
	signal: AbortSignal;
}) => {
	const [piece, marked, reference] = await Promise.all([bytes(image), bytes(mask), bytes(referenceImage)]);
	const targetBox = maskBox(marked);

	if (!targetBox) {
		throw new Error(EMPTY_MASK);
	}

	const res = await run({
		signal,
		task: {
			inputs: { referenceImages: [dataUrl(piece), dataUrl(reference)] },
			model: 'bfl:flux@3-image',
			outputFormat: 'PNG',
			positivePrompt: prompt ? `${PLACE_PROMPT} ${prompt}` : PLACE_PROMPT,
			resolution: '1K',
			settings: {
				boundingBoxes: [{ description: 'the object from the second image', id: 'object', referenceIndex: 1, sourceBox: [0, 0, 1000, 1000], targetBox }]
			},
			taskType: 'imageInference'
		}
	});

	return { cost: res.cost, image: new Blob([new Uint8Array(res.image)], { type: 'image/png' }), model: 'FLUX 3 Image' };
};

// `referenceImage`, the person's image, put where `mask` is white in `image` by Seedream 5.5 at the size the scene gives it:
// the piece, the image and the mask its three references, the person's words after OBJECT_PROMPT. One image, at the model's
// own size with the piece's ratio (the editor resizes it), and the cost Runware billed in US$. `signal` stops the call when
// the person stops
const placeObject = async ({
	image,
	mask,
	prompt,
	referenceImage,
	signal
}: {
	image: Blob;
	mask: Blob;
	prompt: string;
	referenceImage: Blob;
	signal: AbortSignal;
}) => {
	const [piece, marked, reference] = await Promise.all([bytes(image), bytes(mask), bytes(referenceImage)]);
	const res = await run({
		signal,
		task: {
			inputs: { referenceImages: [dataUrl(piece), dataUrl(reference), dataUrl(marked)] },
			model: 'bytedance:seedream@5.5',
			outputFormat: 'PNG',
			positivePrompt: prompt ? `${OBJECT_PROMPT} ${prompt}` : OBJECT_PROMPT,
			resolution: '1K',
			taskType: 'imageInference'
		}
	});

	return { cost: res.cost, image: new Blob([new Uint8Array(res.image)], { type: 'image/png' }), model: 'Seedream 5.5' };
};

// the new background, `prompt` the person's words, painted by Bria FIBO 2.0 Edit where `mask` is white in `image` (where
// Remove Background took the photo away), the piece and its mask as they came, the words after BACKGROUND_PROMPT. One
// image, at the piece's size, and the cost Runware billed in US$. `signal` stops the call when the person stops
const replaceBackground = async ({ image, mask, prompt, signal }: { image: Blob; mask: Blob; prompt: string; signal: AbortSignal }) => {
	const [piece, marked] = await Promise.all([bytes(image), bytes(mask)]);
	const res = await run({
		signal,
		task: {
			inputs: { image: dataUrl(piece), mask: dataUrl(marked) },
			model: 'bria:21@1',
			outputFormat: 'PNG',
			positivePrompt: `${BACKGROUND_PROMPT} ${prompt}`,
			taskType: 'imageInference'
		}
	});

	return { cost: res.cost, image: new Blob([new Uint8Array(res.image)], { type: 'image/png' }), model: 'Bria FIBO 2.0 Edit' };
};

// `task` run on Runware (runware-task.ts) against `signal` and the time limit, with the fetch of the image it made: its
// bytes, and the US$ Runware billed. Past the limit it rejects in limit.ts's words
const run = ({ signal, task }: { signal: AbortSignal; task: Record<string, unknown> }) => {
	return limit.within({
		signal,
		work: async bounded => {
			const made = await runwareTask.post<{ cost: number; imageURL: string; status?: 'success' }>({ signal: bounded, task });
			const image = await download({ signal: bounded, url: made.imageURL });

			return { cost: made.cost, image };
		}
	});
};

export default { editImage, editPhoto, erase, generate, outpaint, place, placeObject, replaceBackground };
```

### The bigger photo

For an Expand (`'GENERATE_BORDERS'`), the editor sends the bigger photo, its borders transparent, with the widths of its borders (`borders`). The models made to expand take the photo and where it stands, so the fal and Runware servers cut the photo back out of the bigger one with this module, every px made opaque. It needs [`images.ts`](#the-image-library) beside it.

```ts bordered.ts theme={"dark"}
import type { AiBorders } from '@embededitor/full/react';

import images from './images';

// The editor's Expand, read for the fill servers whose model takes the photo and the borders to add rather than a mask
// (retouch-fal.ts, retouch-runware.ts): the editor sends the bigger photo, its borders transparent, and their widths in
// its px (`borders`), and this cuts the photo back out of it (images.ts)

// the photo inside `image`, the bigger photo the editor sent, cut out by the widths of its borders (`borders`): a PNG's
// bytes, every px opaque, as our measurements sent it (Bria's Expand keeps a transparency it is given), and its size,
// beside the size of `image` (`canvas`)
const cut = async ({ borders, image }: { borders: AiBorders; image: Blob }) => {
	const buffer = await image.arrayBuffer();
	const bytes = new Uint8Array(buffer);
	const { height, width } = images.size(bytes);
	const photo = { height: height - borders.top - borders.bottom, width: width - borders.left - borders.right };
	const cropped = images.crop({ bytes, rect: { ...photo, left: borders.left, top: borders.top } });
	const png = images.opaque(cropped);

	return { canvas: { height, width }, photo: { ...photo, png } };
};

export default { cut };
```

### The image library

Every image the servers touch goes through this module, on photon: a size read from the file's header, a crop, the alpha dropped, the px read and a resize (Lanczos3 for a photo, the nearest px for a mask). It opens PNGs, the format of every image the servers open: the editor sends PNGs, and the servers ask the models for PNGs. It reads a size from a PNG's header or a JPEG's, as the face find reads the editor's photo, a JPEG. Each function frees every image it opens or makes, on an error too: an image lives in WebAssembly's memory, where photon frees its room on its own only once the garbage collector collects the image, late or never, and that memory, once grown, never shrinks, so a server that left its images to the collector could grow until its host stopped it. Photon writes every PNG with an alpha channel, so an image with no transparency comes back opaque. It needs `@cf-wasm/photon`.

Photon can't recover from a failure. On a file it can't decode, or an image too large for its memory, it panics, and a panic in WebAssembly leaves photon's memory and its stack as they were: each one keeps what its call had taken, and after a few thousand (5,000 broken files did it on Node), photon fails every image, good ones too, until the server process restarts. So the module checks what it hands photon, and throws in words before photon sees it:

* A file that isn't a whole PNG throws "The image couldn't be read.": anything but a PNG, a PNG cut short or without its end (its IEND), one that doesn't start with its 13-byte header (its IHDR), or one whose bytes changed on the way, so a chunk's checksum is wrong. That covers a model's broken answer and an error page sent in place of an image.
* An image with less than 1 px on a side, read from its header or asked for, throws "The image needs at least 1 px on each side."; so does a size whose side the request left out. One with more px than 8192 × 8192 throws "The image has more than 67,108,864 px.": resizing an image that large took photon's memory to 2.1 GB, and that memory holds 4 GB at most.
* A crop that leaves its image, or lacks a side, throws "The rectangle leaves the image."

None of those costs photon any memory or breaks it for the next image. The checks can't see a PNG made on purpose to pass them over data photon can't decode: that one still panics photon, and a few thousand of them would break it as above.

```ts images.ts theme={"dark"}
import * as photon from '@cf-wasm/photon';

// Every image operation of the servers (bordered.ts, faces-runware.ts, retouch-fal.ts, retouch-runware.ts), on photon
// (@cf-wasm/photon): an image library compiled to WebAssembly, which runs on Node and on Cloudflare Workers alike,
// where sharp's native code runs on Node alone. Each function that opens an image takes a PNG's bytes, the format of
// every image the servers open (the editor sends PNGs, and the servers ask the models for PNGs), and gives what it
// reads, or a PNG's bytes, which photon always writes with an alpha channel: an image with no transparency comes back
// opaque, every px's alpha 255. A size alone is read from the file's header, a PNG's or a JPEG's, with nothing decoded.
// Each function frees every image it opens or makes, on an error too: an image lives in WebAssembly's memory, where
// photon frees its room on its own only once the garbage collector collects the image, late or never, and that memory,
// once grown, never shrinks.
// Photon can't recover from a failure: on a file it can't decode, or a size past what its memory holds, it panics, and a
// panic in WebAssembly leaves photon's memory and its stack as they were. Each panic keeps what its call had taken, and a
// few thousand make photon fail every image after, until the process ends. So nothing photon would fail on reaches it: a
// PNG only whole (its signature, its IHDR first, each chunk's checksum right, through its IEND), every image from 1 px on
// a side to MAX_PX px, every rectangle inside its image; anything else throws in words first. Those checks can't see a PNG
// made on purpose to pass them over data photon's decoder can't read: that one still panics it

// how an image is resized: by Lanczos3 for a photo, by the nearest px for a mask, so it stays black and white
type Kernel = 'LANCZOS3' | 'NEAREST';
// an image's size, in px
type Size = { height: number; width: number };

// a PNG's IEND chunk, its last, by its type
const IEND = 0x49454e44;
// a PNG's IHDR chunk, its first, which holds its size, by its type
const IHDR = 0x49484452;
// the markers of a JPEG's frame (SOF0 to SOF15, less DHT, JPG and DAC), the segment that holds its size
const JPEG_FRAMES = [0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf];
// a JPEG's first two bytes (its SOI marker)
const JPEG_START = 0xffd8;
// photon's filter for each kernel
const KERNELS = { LANCZOS3: photon.SamplingFilter.Lanczos3, NEAREST: photon.SamplingFilter.Nearest };
// the most px an image may have, 8192 × 8192: resizing one that large took photon's memory to 2.1 GB, and WebAssembly's
// memory holds 4 GB at most
const MAX_PX = 8192 * 8192;
// a PNG's first eight bytes, its signature, as two 32-bit words: one 64-bit BigInt would need a target of ES2020 or later,
// and a Next.js app targets ES2017
const PNG_SIGNATURE = [0x89504e47, 0x0d0a1a0a];

// CRC-32's table, as a PNG's checksums take it: one number for each value of a byte
const crcTable = Uint32Array.from({ length: 256 }, (_value, n) => {
	let c = n;

	for (let bit = 0; bit < 8; bit += 1) {
		c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
	}

	return c;
});

// throws in words on `size` where photon would panic: less than 1 px on a side (a side the request left out, NaN,
// included) or more px than MAX_PX
const checkSize = (size: Size) => {
	if (!(size.width >= 1 && size.height >= 1)) {
		throw new Error('The image needs at least 1 px on each side.');
	}

	if (size.width * size.height > MAX_PX) {
		throw new Error(`The image has more than ${MAX_PX.toLocaleString('en-US')} px.`);
	}
};

// the CRC-32 of `bytes`, as a PNG chunk's checksum holds it
const crc = (bytes: Uint8Array) => {
	let c = 0xffffffff;

	// a plain loop over the bytes: there are millions
	for (let i = 0; i < bytes.length; i += 1) {
		c = crcTable[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
	}

	return (c ^ 0xffffffff) >>> 0;
};

// the rectangle `rect` of `bytes`, a PNG, its px as they were, as a PNG. A rectangle that leaves the image, or lacks a side
// (NaN), throws, before photon would panic on it
const crop = ({ bytes, rect }: { bytes: Uint8Array; rect: { height: number; left: number; top: number; width: number } }) => {
	return opened({
		bytes,
		work: image => {
			const right = rect.left + rect.width;
			const bottom = rect.top + rect.height;
			const inside = rect.left >= 0 && rect.top >= 0 && rect.width >= 1 && rect.height >= 1 && right <= image.get_width() && bottom <= image.get_height();

			if (!inside) {
				throw new Error('The rectangle leaves the image.');
			}

			return encoded(photon.crop(image, rect.left, rect.top, right, bottom));
		}
	});
};

// `bytes`, a PNG, opened by photon once it is whole and its size one photon holds; anything else throws in words. A PNG
// made on purpose to pass those checks still panics photon, the panic reaching JavaScript as "unreachable", here in words
// too
const decoded = (bytes: Uint8Array) => {
	const size = whole(bytes) ? header(bytes) : null;

	if (!size) {
		throw new Error("The image couldn't be read.");
	}

	checkSize(size);

	try {
		return photon.PhotonImage.new_from_byteslice(bytes);
	} catch (err) {
		throw new Error("The image couldn't be read.", { cause: err });
	}
};

// `image`'s PNG bytes, the image freed
const encoded = (image: photon.PhotonImage) => {
	try {
		return image.get_bytes();
	} finally {
		image.free();
	}
};

// the size the header of `bytes` says: a PNG's (its IHDR chunk) or a JPEG's (its frame), or null for any other file or a
// header cut short
const header = (bytes: Uint8Array): Size | null => {
	const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);

	if (bytes.length >= 24 && png(view)) {
		return { height: view.getUint32(20), width: view.getUint32(16) };
	}

	if (bytes.length < 4 || view.getUint16(0) !== JPEG_START) {
		return null;
	}

	// each segment after the SOI: 0xFF, its marker, then its length, its own two bytes included; a frame gives its
	// precision, its height and its width
	for (let at = 2; at + 9 <= bytes.length; at += 2 + view.getUint16(at + 2)) {
		if (bytes[at] !== 0xff) {
			return null;
		}

		if (JPEG_FRAMES.includes(bytes[at + 1])) {
			return { height: view.getUint16(at + 5), width: view.getUint16(at + 7) };
		}
	}

	return null;
};

// `bytes`, a PNG, with its alpha dropped, as a PNG: every px opaque, its color as it was
const opaque = (bytes: Uint8Array) => {
	return opened({
		bytes,
		work: image => {
			const px = image.get_raw_pixels();

			// a plain loop over the px: there are millions
			for (let i = 3; i < px.length; i += 4) {
				px[i] = 255;
			}

			return encoded(new photon.PhotonImage(px, image.get_width(), image.get_height()));
		}
	});
};

// what `work` gives from `bytes` opened as an image, the image freed once it has run, on an error too
const opened = <T>({ bytes, work }: { bytes: Uint8Array; work: (image: photon.PhotonImage) => T }) => {
	const image = decoded(bytes);

	try {
		return work(image);
	} finally {
		image.free();
	}
};

// `bytes`, a PNG, as its px, four bytes each (red, green, blue and alpha) row after row, with its size
const pixels = (bytes: Uint8Array) => {
	return opened({
		bytes,
		work: image => {
			return { data: image.get_raw_pixels(), height: image.get_height(), width: image.get_width() };
		}
	});
};

// whether `view` starts with a PNG's signature; it holds 8 bytes at least
const png = (view: DataView) => {
	return view.getUint32(0) === PNG_SIGNATURE[0] && view.getUint32(4) === PNG_SIGNATURE[1];
};

// `bytes`, a PNG, stretched to `size` by `kernel`, as a PNG
const resize = ({ bytes, kernel, size }: { bytes: Uint8Array; kernel: Kernel; size: Size }) => {
	checkSize(size);

	return opened({
		bytes,
		work: image => {
			return encoded(photon.resize(image, size.width, size.height, KERNELS[kernel]));
		}
	});
};

// `bytes`, a PNG, shrunk by `kernel` to at most `side` px on its longer side, its ratio kept and its shorter side 1 px at
// least, as a PNG; one already inside it keeps its size. A side the request left out (NaN) throws, before photon would
// panic on it
const shrink = ({ bytes, kernel, side }: { bytes: Uint8Array; kernel: Kernel; side: number }) => {
	return opened({
		bytes,
		work: image => {
			const height = image.get_height();
			const width = image.get_width();
			const scale = side / Math.max(width, height);

			if (scale >= 1) {
				return image.get_bytes();
			}

			const shrunk = { height: Math.max(1, Math.round(height * scale)), width: Math.max(1, Math.round(width * scale)) };

			checkSize(shrunk);

			return encoded(photon.resize(image, shrunk.width, shrunk.height, KERNELS[kernel]));
		}
	});
};

// the size of `bytes`, an image, in px, read from a PNG's or a JPEG's header, with nothing decoded; any other file throws
// in words
const size = (bytes: Uint8Array): Size => {
	const res = header(bytes);

	if (!res) {
		throw new Error("The image couldn't be read.");
	}

	return res;
};

// whether `bytes` are a whole PNG: its signature, its IHDR first, then chunk after chunk, each one inside the file and its
// checksum right, through its IEND. A file cut short, a byte changed on its way, or any other file, isn't
const whole = (bytes: Uint8Array) => {
	const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);

	// its signature, then its first chunk's length and type
	if (bytes.length < 16 || !png(view) || view.getUint32(8) !== 13 || view.getUint32(12) !== IHDR) {
		return false;
	}

	// each chunk: its data's length, its type, its data, then the checksum of its type and its data
	let at = 8;

	while (at + 12 <= bytes.length) {
		const end = at + 12 + view.getUint32(at);

		if (end > bytes.length || crc(bytes.subarray(at + 4, end - 4)) !== view.getUint32(end - 4)) {
			return false;
		}

		if (view.getUint32(at + 4) === IEND) {
			return true;
		}

		at = end;
	}

	return false;
};

export default { crop, opaque, pixels, resize, shrink, size };
```

### The fal job

fal's client, when its signal aborts, stops waiting for the job but doesn't cancel it. The fal servers run each job through this module: when the person stops or [the time limit](#the-time-limit) passes, it stops waiting and asks fal to cancel the job by its id, even where the stop comes before fal gives the id, and it fetches the job's image within the same limit. A cancel drops a job fal hasn't started yet. A job fal has already started runs to its end and is billed: fal answers the cancel and finishes the job anyway (on 2026-11-10, a Bria cut canceled 6 seconds in completed at 25.5 seconds). It needs `@fal-ai/client` and `limit.ts` beside it.

```ts fal-job.ts theme={"dark"}
import { fal } from '@fal-ai/client';

import limit from './limit';

// The fal servers' calls (retouch-fal.ts, background.ts, background-cheap.ts, sam3.ts, moondream.ts), for the site's
// server: each job runs within limit.ts's time limit, and when the person stops or the limit passes, the call stops
// waiting and asks fal to cancel the job, since fal's subscribe, on an abort, only stops waiting. fal drops a job it
// hasn't started yet; a job it has started runs to its end, and fal bills it. The image a job made is fetched within
// the same limit, and past it either call rejects in words the editor can show.

// the image fal put at `url`, fetched against `signal` and the time limit
const download = ({ signal, url }: { signal: AbortSignal; url: string }) => {
	return limit.within({
		signal,
		work: async bounded => {
			const res = await fetch(url, { signal: bounded });

			if (!res.ok) {
				throw new Error(`fal's image answered ${res.status}`);
			}

			return res.blob();
		}
	});
};

// fal's answer to `subscribe`, the job it starts on `endpoint` with the options it is given, against `signal` and the
// time limit: at the first of the two, fal is asked to cancel the job by the id it gave, as soon as it gives it where the
// stop came first, and the call rejects once fal has answered the cancel: a server on Cloudflare Workers drops a
// request still in flight once its own has ended. A job fal has started finishes anyway, and is billed
const run = <T>({
	endpoint,
	signal,
	subscribe
}: {
	endpoint: string;
	signal: AbortSignal;
	subscribe: (options: { abortSignal: AbortSignal; onEnqueue: (requestId: string) => void }) => Promise<T>;
}) => {
	return limit.within({
		signal,
		work: async bounded => {
			let requestId = '';
			let canceled: Promise<void> = Promise.resolve();
			const cancel = async () => {
				try {
					await fal.queue.cancel(endpoint, { requestId });
				} catch {
					// a job that ended first has nothing left to cancel
				}
			};
			const abort = () => {
				if (requestId) {
					canceled = cancel();
				}
			};

			bounded.addEventListener('abort', abort, { once: true });

			try {
				return await subscribe({
					abortSignal: bounded,
					onEnqueue: id => {
						requestId = id;

						if (bounded.aborted) {
							canceled = cancel();
						}
					}
				});
			} finally {
				bounded.removeEventListener('abort', abort);
				await canceled;
			}
		}
	});
};

export default { download, run };
```

### The Runware task

The Runware server POSTs each task through this module, which asks Runware for the cost of each and turns Runware's refusals into errors: its own words where it refuses the task, its status where the answer is no JSON, and the time limit's words where Runware ends the call while the task still runs. It needs `limit.ts` beside it and `RUNWARE_API_KEY`.

```ts runware-task.ts theme={"dark"}
import { TOO_LONG } from './limit';

// The Runware servers' calls (retouch-runware.ts, faces-runware.ts), for the site's server, where the key stays
// (RUNWARE_API_KEY): one task POSTed to Runware's API, its images as data URLs, with the cost Runware bills for it. The
// caller runs it within limit.ts's time limit, with whatever else the call does (the fetch of an image it made)

// Runware's API
const RUNWARE_URL = 'https://api.runware.ai/v1';

// the row Runware answers for `task`, POSTed against `signal`. A task Runware refuses rejects with its own words, an
// answer that is no JSON (a gateway's page) with its status, and one whose HTTP call Runware ends while the task still runs
// in limit.ts's words (it waits 120 s, then answers the task's row with nothing made)
const post = async <Row extends { cost: number; status?: 'success' }>({ signal, task }: { signal: AbortSignal; task: Record<string, unknown> }) => {
	const res = await fetch(RUNWARE_URL, {
		body: JSON.stringify([{ ...task, includeCost: true, taskUUID: crypto.randomUUID() }]),
		headers: { authorization: `Bearer ${process.env.RUNWARE_API_KEY}`, 'content-type': 'application/json' },
		method: 'POST',
		signal
	});

	if (!res.headers.get('content-type')?.includes('application/json')) {
		throw new Error(`Runware: answered ${res.status}`);
	}

	const answer: { data?: (Row | { status: 'processing' })[]; errors?: { message: string }[] } = await res.json();
	const made = answer.data?.[0];

	if (!made) {
		throw new Error(`Runware: ${answer.errors?.[0]?.message ?? `answered ${res.status}`}`);
	}

	if (made.status === 'processing') {
		throw new Error(TOO_LONG);
	}

	return made;
};

export default { post };
```

### The time limit

Every call to a model gets two minutes, its image's fetch included: over twice the slowest call we measured of a model our servers run, Object Eraser's 50 seconds on Runware, which fills a Remove. This module gives the call a signal that aborts when the person stops or the two minutes pass, whichever comes first, and past them rejects with "The model took too long.", the words the editor shows. The fal job and the Runware server both run their calls through it.

```ts limit.ts theme={"dark"}
// The time limit of the servers' calls to a model (fal-job.ts runs fal's, retouch-runware.ts and faces-runware.ts
// Runware's), for the site's server: a call gets a signal that aborts when the person stops or TIMEOUT passes,
// whichever comes first. Past TIMEOUT, it rejects in words the editor can show (TOO_LONG), the timeout kept as its
// cause

// the longest a call, with the fetch of its image, may take, in ms: over twice the slowest call our measurements saw of
// a model the servers run (Object Eraser's 50 s, on Runware) and about twice the slowest of Runware's own examples
// (Object Eraser's 63 s), as long as Runware holds a task on an HTTP call before it answers that it is still running
const TIMEOUT = 120000;
// what a call past TIMEOUT rejects with, as does one its provider ends while the task still runs
const TOO_LONG = 'The model took too long.';

// what `work` gives with a signal that aborts at `signal` or past TIMEOUT, whichever comes first: past TIMEOUT, it rejects
// with TOO_LONG; else with the work's own error
const within = async <T>({ signal, work }: { signal: AbortSignal; work: (bounded: AbortSignal) => Promise<T> }) => {
	const bounded = AbortSignal.any([signal, AbortSignal.timeout(TIMEOUT)]);

	try {
		return await work(bounded);
	} catch (err) {
		if (bounded.aborted && !signal.aborted) {
			throw new Error(TOO_LONG, { cause: err });
		}

		throw err;
	}
};

export { TOO_LONG };
export default { within };
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.