Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)
Python
Batch image editing and background removal tools in parallel
Flightdeck Agentd026163f586d
diff --git a/QA.md b/QA.mdindex ea130074..9a18a245 100644--- a/QA.md+++ b/QA.md@@ -5,7 +5,7 @@- Extracted crops are pixel-accurate and actually used in the generated page- Uploaded an exact logo → used verbatim in the output, not redrawn- `screenshot_preview` — agent renders its own HTML and inspects it-- `edit_image` / `remove_background` accept local asset URLs+- `edit_images` / `remove_backgrounds` accept local asset URLs and batch independent work## Existing functionality- Text → codediff --git a/README.md b/README.mdindex 088fd5cf..735c5780 100644--- a/README.md+++ b/README.md@@ -51,7 +51,7 @@ the best results and lets you compare multiple models per generation.| `OPENAI_API_KEY` | One of these three | GPT code-gen variants (GPT-5.5, GPT-5.4 Mini) || `ANTHROPIC_API_KEY` | One of these three | Claude code-gen variants (Opus 5, Opus 4.8, Fable 5, Sonnet 4.6) || `GEMINI_API_KEY` | One of these three — **strongly recommended** | Gemini code-gen variants (3 Flash, 3.1 Pro); extracts real assets from the screenshot; required for video mode |-| `REPLICATE_API_KEY` | **Strongly recommended** | Image editing, background removal, and Replicate-backed image generation — without it, `edit_image` and `remove_background` are unavailable, and image generation falls back to OpenAI if configured |+| `REPLICATE_API_KEY` | **Strongly recommended** | Image editing, background removal, and Replicate-backed image generation — without it, `edit_images` and `remove_backgrounds` are unavailable |With more keys, the app automatically picks a stronger mix of models pervariant; with a single key it uses that provider's models only.diff --git a/backend/agent/providers/factory.py b/backend/agent/providers/factory.pyindex eca55690..767bfb47 100644--- a/backend/agent/providers/factory.py+++ b/backend/agent/providers/factory.py@@ -30,7 +30,7 @@ def create_provider_session() -> ProviderSession:canonical_tools = canonical_tool_definitions(image_generation_enabled=should_generate_images,- # The edit_image tool calls Replicate, so don't offer it without a key.+ # The edit_images tool calls Replicate, so don't offer it without a key.image_editing_enabled=bool(replicate_api_key or REPLICATE_API_KEY),# The extract_assets tool calls Gemini, so don't offer it without a key.asset_extraction_enabled=should_extract_assets and bool(gemini_api_key),diff --git a/backend/agent/tools/definitions.py b/backend/agent/tools/definitions.pyindex 6f367ef7..cfb5628f 100644--- a/backend/agent/tools/definitions.py+++ b/backend/agent/tools/definitions.py@@ -74,7 +74,7 @@ def _image_schema() -> Dict[str, Any]:}-def _remove_background_schema() -> Dict[str, Any]:+def _remove_backgrounds_schema() -> Dict[str, Any]:return {"type": "object","properties": {@@ -90,39 +90,54 @@ def _remove_background_schema() -> Dict[str, Any]:}-def _edit_image_schema() -> Dict[str, Any]:+def _edit_images_schema() -> Dict[str, Any]:+ edit_properties: Dict[str, Any] = {+ "prompt": {+ "type": "string",+ "description": (+ "Clear instruction for this independent edit. Refer to inputs as "+ "image 1, image 2, and so on when multiple images are provided."+ ),+ },+ "image_urls": {+ "type": "array",+ "items": {+ "type": "string",+ "description": "URL of a source or reference image.",+ },+ "description": (+ "Ordered image URLs for this edit: put the main image first, "+ "followed by any reference images."+ ),+ },+ "aspect_ratio": {+ "type": "string",+ "enum": list(P_IMAGE_EDIT_ASPECT_RATIOS),+ "default": "match_input_image",+ "description": (+ "Optional aspect ratio for this edited image. Use match_input_image "+ "to match its main image."+ ),+ },+ }return {"type": "object","properties": {- "prompt": {- "type": "string",- "description": (- "Clear edit instruction. Refer to inputs as image 1, image 2, "- "and so on when multiple images are provided."- ),- },- "image_urls": {+ "edits": {"type": "array",+ "minItems": 1,"items": {- "type": "string",- "description": (- "URL of a source/reference image. For editing, put the main "- "image first."- ),+ "type": "object",+ "properties": edit_properties,+ "required": ["prompt", "image_urls"],},- },- "aspect_ratio": {- "type": "string",- "enum": list(P_IMAGE_EDIT_ASPECT_RATIOS),- "default": "match_input_image","description": (- "Aspect ratio for the edited image. Use match_input_image to "- "match the first image. Allowed values: match_input_image, "- "1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3."+ "Independent image edits to run in parallel. Results are returned "+ "in this same order."),},},- "required": ["prompt", "image_urls"],+ "required": ["edits"],}@@ -209,26 +224,27 @@ def canonical_tool_definitions(tools.extend([CanonicalToolDefinition(- name="remove_background",+ name="remove_backgrounds",description=(- "Remove the background from one or more images. You can pass multiple "- "image URLs at once. Returns URLs to the processed images with "- "transparent backgrounds."+ "Remove the backgrounds from one or more images in one batch. Returns "+ "URLs to the processed images with transparent backgrounds in input "+ "order."),- parameters=_remove_background_schema(),+ parameters=_remove_backgrounds_schema(),),])if image_editing_enabled:tools.append(CanonicalToolDefinition(- name="edit_image",+ name="edit_images",description=(- "Edit or upscale one or more images using a text prompt. Provide the "- "main image first, followed by optional reference images. Returns a "- "URL to the edited image."+ "Edit or upscale one or more images by running independent edits in "+ "one batch. Each edit has its own prompt, ordered main/reference "+ "image URLs, and optional aspect ratio. Results are returned in edit "+ "order."),- parameters=_edit_image_schema(),+ parameters=_edit_images_schema(),))if asset_extraction_enabled:diff --git a/backend/agent/tools/local_assets.py b/backend/agent/tools/local_assets.pyindex 0c1000aa..e5a962a2 100644--- a/backend/agent/tools/local_assets.py+++ b/backend/agent/tools/local_assets.py@@ -2,8 +2,8 @@Replicate (and other hosted model APIs) can't fetch ``localhost`` URLs, so anyasset served by this backend must be inlined as a base64 ``data:`` URL before-being sent. Tools that pass image inputs to Replicate (``remove_background``,-``edit_image``) route their URLs through here.+being sent. Tools that pass image inputs to Replicate (``remove_backgrounds``,+``edit_images``) route their URLs through here."""import base64diff --git a/backend/agent/tools/runtime.py b/backend/agent/tools/runtime.pyindex 09fa3390..b39956c8 100644--- a/backend/agent/tools/runtime.py+++ b/backend/agent/tools/runtime.py@@ -12,8 +12,8 @@ from image_generation.generation import process_tasksfrom image_generation.replicate import (P_IMAGE_EDIT_ASPECT_RATIOS,PImageEditAspectRatio,- edit_image,- remove_background,+ edit_image as edit_image_once,+ remove_background as remove_background_once,)from uploaded_assets.tools import run_save_assets@@ -22,6 +22,9 @@ from agent.tools.types import ToolCall, ToolExecutionResult, ToolMultimodalPartfrom agent.tools.summaries import summarize_text+IMAGE_TOOL_BATCH_SIZE = 20++class AgentToolRuntime:def __init__(self,@@ -68,10 +71,10 @@ class AgentToolRuntime:return self._edit_file(tool_call.arguments)if tool_call.name == "generate_images":return await self._generate_images(tool_call.arguments)- if tool_call.name == "remove_background":- return await self._remove_background(tool_call.arguments)- if tool_call.name == "edit_image":- return await self._edit_image(tool_call.arguments)+ if tool_call.name == "remove_backgrounds":+ return await self._remove_backgrounds(tool_call.arguments)+ if tool_call.name == "edit_images":+ return await self._edit_images(tool_call.arguments)if tool_call.name == "extract_assets":return await run_extract_assets(tool_call.arguments,@@ -318,7 +321,9 @@ class AgentToolRuntime:multimodal_parts=multimodal_parts,)- async def _remove_background(self, args: Dict[str, Any]) -> ToolExecutionResult:+ async def _remove_backgrounds(+ self, args: Dict[str, Any]+ ) -> ToolExecutionResult:replicate_api_key = self._effective_replicate_api_key()if not replicate_api_key:return ToolExecutionResult(@@ -332,7 +337,7 @@ class AgentToolRuntime:return ToolExecutionResult(ok=False,result={- "error": "remove_background requires a non-empty image_urls list"+ "error": "remove_backgrounds requires a non-empty image_urls list"},summary={"error": "Missing image_urls"},)@@ -346,13 +351,14 @@ class AgentToolRuntime:summary={"error": "No valid image_urls"},)- batch_size = 20raw_results: list[str | BaseException] = []- for i in range(0, len(unique_urls), batch_size):- batch = unique_urls[i : i + batch_size]+ for i in range(0, len(unique_urls), IMAGE_TOOL_BATCH_SIZE):+ batch = unique_urls[i : i + IMAGE_TOOL_BATCH_SIZE]# Replicate can't fetch localhost; inline local assets as data URLs.tasks = [- remove_background(local_asset_url_to_data_url(url), replicate_api_key)+ remove_background_once(+ local_asset_url_to_data_url(url), replicate_api_key+ )for url in batch]raw_results.extend(await asyncio.gather(*tasks, return_exceptions=True))@@ -393,7 +399,7 @@ class AgentToolRuntime:multimodal_parts=multimodal_parts,)- async def _edit_image(self, args: Dict[str, Any]) -> ToolExecutionResult:+ async def _edit_images(self, args: Dict[str, Any]) -> ToolExecutionResult:replicate_api_key = self._effective_replicate_api_key()if not replicate_api_key:return ToolExecutionResult(@@ -402,94 +408,117 @@ class AgentToolRuntime:summary={"error": "Missing Replicate API key"},)- prompt = ensure_str(args.get("prompt")).strip()- if not prompt:- return ToolExecutionResult(- ok=False,- result={"error": "edit_image requires a non-empty prompt"},- summary={"error": "Missing prompt"},- )-- image_urls = args.get("image_urls") or args.get("images") or []- if not isinstance(image_urls, list) or not image_urls:- return ToolExecutionResult(- ok=False,- result={"error": "edit_image requires a non-empty image_urls list"},- summary={"error": "Missing image_urls"},- )-- cleaned = [url.strip() for url in image_urls if isinstance(url, str)]- unique_urls = list(dict.fromkeys([u for u in cleaned if u]))- if not unique_urls:+ raw_edits = args.get("edits") or []+ if not isinstance(raw_edits, list) or not raw_edits:return ToolExecutionResult(ok=False,- result={"error": "No valid image URLs provided"},- summary={"error": "No valid image_urls"},+ result={"error": "edit_images requires a non-empty edits list"},+ summary={"error": "Missing edits"},)- aspect_ratio_value = ensure_str(args.get("aspect_ratio") or "match_input_image")- if aspect_ratio_value not in P_IMAGE_EDIT_ASPECT_RATIOS:- aspect_ratio_value = "match_input_image"- aspect_ratio = cast(PImageEditAspectRatio, aspect_ratio_value)-- try:- result_url = await edit_image(- prompt=prompt,- image_urls=[local_asset_url_to_data_url(url) for url in unique_urls],- api_token=replicate_api_key,- aspect_ratio=aspect_ratio,- )- except Exception as exc:- print(f"Image edit failed for {unique_urls}: {exc}")- return ToolExecutionResult(- ok=True,- result={- "image": {- "prompt": prompt,- "image_urls": unique_urls,- "result_url": None,- "status": "error",- }- },- summary={- "image": {- "prompt": prompt,- "image_urls": unique_urls,+ results: List[Dict[str, Any]] = []+ valid_indexes: List[int] = []+ for index, raw_edit in enumerate(cast(List[object], raw_edits)):+ if not isinstance(raw_edit, dict):+ results.append(+ {+ "prompt": "",+ "image_urls": [],"result_url": None,"status": "error",+ "aspect_ratio": "match_input_image",+ "error": f"Edit {index + 1} must be an object.",}- },+ )+ continue++ edit = cast(Dict[str, Any], raw_edit)+ prompt = ensure_str(edit.get("prompt")).strip()+ raw_image_urls = edit.get("image_urls") or []+ image_urls = (+ [+ url.strip()+ for url in cast(List[object], raw_image_urls)+ if isinstance(url, str) and url.strip()+ ]+ if isinstance(raw_image_urls, list)+ else [])+ aspect_ratio_value = ensure_str(+ edit.get("aspect_ratio") or "match_input_image"+ )+ if aspect_ratio_value not in P_IMAGE_EDIT_ASPECT_RATIOS:+ aspect_ratio_value = "match_input_image"- result = {- "image": {+ item: Dict[str, Any] = {"prompt": prompt,- "image_urls": unique_urls,- "result_url": result_url,- "status": "ok",- "aspect_ratio": aspect_ratio,+ "image_urls": image_urls,+ "result_url": None,+ "status": "pending",+ "aspect_ratio": aspect_ratio_value,}- }- summary = {- "image": {- "prompt": prompt,- "image_urls": unique_urls,- "result_url": result_url,- "status": "ok",- "aspect_ratio": aspect_ratio,+ errors: List[str] = []+ if not prompt:+ errors.append("prompt must be non-empty")+ if not image_urls:+ errors.append("image_urls must contain at least one valid URL")+ if errors:+ item["status"] = "error"+ item["error"] = "; ".join(errors)+ else:+ valid_indexes.append(index)+ results.append(item)++ async def execute_single_edit(item: Dict[str, Any]) -> str:+ image_urls = cast(List[str], item["image_urls"])+ return await edit_image_once(+ prompt=ensure_str(item["prompt"]),+ image_urls=[local_asset_url_to_data_url(url) for url in image_urls],+ api_token=replicate_api_key,+ aspect_ratio=cast(PImageEditAspectRatio, item["aspect_ratio"]),+ )++ for i in range(0, len(valid_indexes), IMAGE_TOOL_BATCH_SIZE):+ batch_indexes = valid_indexes[i : i + IMAGE_TOOL_BATCH_SIZE]+ raw_results = await asyncio.gather(+ *(execute_single_edit(results[index]) for index in batch_indexes),+ return_exceptions=True,+ )+ for index, raw in zip(batch_indexes, raw_results):+ item = results[index]+ if isinstance(raw, BaseException):+ print(f"Image edit failed for {item['image_urls']}: {raw}")+ item["status"] = "error"+ item["error"] = str(raw)+ else:+ item["result_url"] = raw+ item["status"] = "ok"++ summary_items = [+ {+ "prompt": item["prompt"],+ "image_urls": cast(List[str], item["image_urls"]),+ "result_url": item["result_url"],+ "status": item["status"],+ "aspect_ratio": item["aspect_ratio"],+ **({"error": item["error"]} if item.get("error") else {}),}- }+ for item in results+ ]+ multimodal_parts = [+ ToolMultimodalPart(+ display_name=f"edited_{index}.png",+ mime_type=guess_image_mime(item["result_url"]),+ image_url=item["result_url"],+ )+ for index, item in enumerate(results)+ if item["status"] == "ok" and item["result_url"]+ ]return ToolExecutionResult(ok=True,- result=result,- summary=summary,- multimodal_parts=[- ToolMultimodalPart(- display_name="edited.png",- mime_type=guess_image_mime(result_url),- image_url=result_url,- )- ],+ result={"images": results},+ summary={"images": summary_items},+ multimodal_parts=multimodal_parts,)def _retrieve_option(self, args: Dict[str, Any]) -> ToolExecutionResult:diff --git a/backend/agent/tools/summaries.py b/backend/agent/tools/summaries.pyindex 4aeb38ff..1db8eed4 100644--- a/backend/agent/tools/summaries.py+++ b/backend/agent/tools/summaries.py@@ -55,7 +55,7 @@ def summarize_tool_input(tool_call: ToolCall, file_state: AgentFileState) -> Dic"prompts": [ensure_str(p) for p in prompts],}- if tool_call.name == "remove_background":+ if tool_call.name == "remove_backgrounds":image_urls = args.get("image_urls") or []if isinstance(image_urls, list):return {@@ -64,16 +64,29 @@ def summarize_tool_input(tool_call: ToolCall, file_state: AgentFileState) -> Dic}return {"image_urls": []}- if tool_call.name == "edit_image":- image_urls = args.get("image_urls") or args.get("images") or []- if isinstance(image_urls, list):- return {- "count": len(image_urls),- "prompt": ensure_str(args.get("prompt")),- "image_urls": [ensure_str(u) for u in image_urls],- "aspect_ratio": args.get("aspect_ratio"),- }- return {"prompt": ensure_str(args.get("prompt")), "image_urls": []}+ if tool_call.name == "edit_images":+ raw_edits = args.get("edits") or []+ if not isinstance(raw_edits, list):+ return {"edits": []}++ edits = []+ for raw_edit in raw_edits:+ if not isinstance(raw_edit, dict):+ continue+ image_urls = raw_edit.get("image_urls") or []+ edits.append(+ {+ "prompt": ensure_str(raw_edit.get("prompt")),+ "image_urls": (+ [ensure_str(url) for url in image_urls]+ if isinstance(image_urls, list)+ else []+ ),+ "aspect_ratio": raw_edit.get("aspect_ratio")+ or "match_input_image",+ }+ )+ return {"count": len(raw_edits), "edits": edits}if tool_call.name == "extract_assets":descriptions = args.get("asset_descriptions") or args.get("descriptions") or []diff --git a/backend/prompts/create/image.py b/backend/prompts/create/image.pyindex bf2949ec..fabdc27d 100644--- a/backend/prompts/create/image.py+++ b/backend/prompts/create/image.py@@ -27,8 +27,8 @@ Generate code for a web page that looks exactly like the provided screenshot(s).- Use the exact text from the screenshot.- Since our goal is to make the web page look as close to the screenshot as possible, we need to extract the exact image assets where possible and generate images for the assets that are not extractable.- Extracting assets can be done with the extract_assets tool. After extracting assets, make sure to inspect the extracted image closely to ensure that it is what we want.-- When available, use edit_image for asset edits such as removing unwanted elements.-- If an extracted or supplied asset is visibly low-resolution or pixelated and must render larger, upscale it with edit_image—not CSS stretching or generate_images.+- When available, use edit_images for asset edits such as removing unwanted elements, batching independent edits into one call.+- If an extracted or supplied asset is visibly low-resolution or pixelated and must render larger, upscale it with edit_images—not CSS stretching or generate_images.- If an asset in the original screenshot is not extractable (for example, occluded by other objects or is the background), when available, use generate_images to create image URLs from prompts (you may pass multiple prompts).- {image_policy}diff --git a/backend/prompts/system_prompt.py b/backend/prompts/system_prompt.pyindex 73fe158f..65719c77 100644--- a/backend/prompts/system_prompt.py+++ b/backend/prompts/system_prompt.py@@ -21,9 +21,9 @@ You are a coding agent that's an expert at building front-ends.## Image manipulation- Use extract_assets (when available) to extract existing visual assets from the input screenshot.- If an asset in the original screenshot is not extractable (for example, occluded by other objects or is the background image), use generate_images (when available) to create image URLs from prompts (you may pass multiple prompts). NEVER USE this tool to extract the entire screenshot and embed it on the page. Our goal here is to create nicely coded pages. We should only use extracted assets for images, not for layout, etc.-- Use edit_image to edit existing images or change their aspect ratios.-- If an extracted or supplied asset is visibly low-resolution or pixelated and must render larger, upscale it with edit_image—not CSS stretching or generate_images.-- Re: transparency, generate_images and edit_image are not capable of generating images with a transparent background. Use remove_background to remove backgrounds when needed (you may pass in multiple image URLs at once).+- Use edit_images to edit existing images. Batch independent edits into one call; each edit can have its own prompt, ordered main/reference images, and aspect ratio.+- If an extracted or supplied asset is visibly low-resolution or pixelated and must render larger, upscale it with edit_images—not CSS stretching or generate_images.+- Re: transparency, generate_images and edit_images are not capable of generating images with a transparent background. Use remove_backgrounds to remove backgrounds when needed (you may pass multiple image URLs at once).# Stack-specific instructionsdiff --git a/backend/tests/test_agent_tools.py b/backend/tests/test_agent_tools.pyindex 2f626d1b..fa64d739 100644--- a/backend/tests/test_agent_tools.py+++ b/backend/tests/test_agent_tools.py@@ -15,6 +15,24 @@ def test_canonical_tool_definitions_include_generate_images_when_enabled() -> Noassert "generate_images" in tool_names+def test_canonical_tool_definitions_use_plural_batch_image_tool_names() -> None:+ tools = canonical_tool_definitions(True)+ tool_names = [tool.name for tool in tools]++ assert "remove_backgrounds" in tool_names+ assert "edit_images" in tool_names+ assert "remove_background" not in tool_names+ assert "edit_image" not in tool_names+ remove_backgrounds_tool = next(+ tool for tool in tools if tool.name == "remove_backgrounds"+ )+ assert remove_backgrounds_tool.parameters["required"] == ["image_urls"]+ assert (+ remove_backgrounds_tool.parameters["properties"]["image_urls"]["type"]+ == "array"+ )++def test_canonical_tool_definitions_exclude_generate_images_when_disabled() -> None:tool_names = [tool.name for tool in canonical_tool_definitions(False)]assert "generate_images" not in tool_names@@ -224,45 +242,73 @@ def test_canonical_tool_definitions_exclude_screenshot_preview_when_disabled() -assert "screenshot_preview" not in tool_names-def test_canonical_tool_definitions_include_edit_image() -> None:+def test_canonical_tool_definitions_include_batched_edit_images() -> None:tools = canonical_tool_definitions(True)tool_names = [tool.name for tool in tools]- assert "edit_image" in tool_names- edit_image_tool = next(tool for tool in tools if tool.name == "edit_image")- assert "upscale" in edit_image_tool.description.lower()- assert edit_image_tool.parameters["required"] == ["prompt", "image_urls"]- properties = edit_image_tool.parameters["properties"]+ assert "edit_images" in tool_names+ edit_images_tool = next(tool for tool in tools if tool.name == "edit_images")+ assert "upscale" in edit_images_tool.description.lower()+ assert edit_images_tool.parameters["required"] == ["edits"]+ edits_schema = edit_images_tool.parameters["properties"]["edits"]+ assert edits_schema["type"] == "array"+ assert edits_schema["minItems"] == 1+ edit_schema = edits_schema["items"]+ assert edit_schema["required"] == ["prompt", "image_urls"]+ properties = edit_schema["properties"]assert properties["image_urls"]["type"] == "array"assert "turbo" not in propertiesassert "seed" not in propertiesassert properties["aspect_ratio"]["enum"] == list(P_IMAGE_EDIT_ASPECT_RATIOS)-def test_canonical_tool_definitions_exclude_edit_image_when_disabled() -> None:+def test_canonical_tool_definitions_exclude_edit_images_when_disabled() -> None:tool_names = [tool.namefor tool in canonical_tool_definitions(True, image_editing_enabled=False)]- assert "edit_image" not in tool_names+ assert "edit_images" not in tool_names-def test_edit_image_tool_input_summary_uses_prompt_and_image_urls() -> None:+def test_edit_images_tool_input_summary_preserves_edit_and_image_order() -> None:summary = summarize_tool_input(ToolCall(id="call-1",- name="edit_image",+ name="edit_images",arguments={- "prompt": "Make image 1 monochrome",- "image_urls": ["https://example.com/input.png"],- "aspect_ratio": "match_input_image",+ "edits": [+ {+ "prompt": "Make image 1 monochrome",+ "image_urls": [+ "https://example.com/main.png",+ "https://example.com/reference.png",+ ],+ "aspect_ratio": "16:9",+ },+ {+ "prompt": "Upscale the logo",+ "image_urls": ["https://example.com/logo.png"],+ },+ ]},),AgentFileState(),)assert summary == {- "count": 1,- "prompt": "Make image 1 monochrome",- "image_urls": ["https://example.com/input.png"],- "aspect_ratio": "match_input_image",+ "count": 2,+ "edits": [+ {+ "prompt": "Make image 1 monochrome",+ "image_urls": [+ "https://example.com/main.png",+ "https://example.com/reference.png",+ ],+ "aspect_ratio": "16:9",+ },+ {+ "prompt": "Upscale the logo",+ "image_urls": ["https://example.com/logo.png"],+ "aspect_ratio": "match_input_image",+ },+ ],}diff --git a/backend/tests/test_batching.py b/backend/tests/test_batching.pyindex 8e1b14d1..130c3af5 100644--- a/backend/tests/test_batching.py+++ b/backend/tests/test_batching.py@@ -37,7 +37,7 @@ async def test_process_tasks_batches_replicate_calls(@pytest.mark.asyncio-async def test_remove_background_batches_calls(+async def test_remove_backgrounds_batches_calls(monkeypatch: pytest.MonkeyPatch,) -> None:monkeypatch.setattr("agent.tools.runtime.REPLICATE_API_KEY", "fake-key")@@ -53,7 +53,7 @@ async def test_remove_background_batches_calls(concurrent -= 1return f"nobg-{image_url}"- monkeypatch.setattr("agent.tools.runtime.remove_background", tracking_remove_bg)+ monkeypatch.setattr("agent.tools.runtime.remove_background_once", tracking_remove_bg)runtime = AgentToolRuntime(file_state=AgentFileState(),@@ -65,7 +65,7 @@ async def test_remove_background_batches_calls(urls = [f"https://example.com/img-{i}.png" for i in range(25)]result = await runtime.execute(- ToolCall(id="test", name="remove_background", arguments={"image_urls": urls})+ ToolCall(id="test", name="remove_backgrounds", arguments={"image_urls": urls}))assert result.ok@@ -75,7 +75,7 @@ async def test_remove_background_batches_calls(@pytest.mark.asyncio-async def test_remove_background_accepts_data_urls(+async def test_remove_backgrounds_accepts_data_urls(monkeypatch: pytest.MonkeyPatch,) -> None:monkeypatch.setattr("agent.tools.runtime.REPLICATE_API_KEY", "fake-key")@@ -85,7 +85,7 @@ async def test_remove_background_accepts_data_urls(captured.append(image_url)return "https://replicate.example/no-bg.png"- monkeypatch.setattr("agent.tools.runtime.remove_background", tracking_remove_bg)+ monkeypatch.setattr("agent.tools.runtime.remove_background_once", tracking_remove_bg)runtime = AgentToolRuntime(file_state=AgentFileState(),@@ -96,7 +96,7 @@ async def test_remove_background_accepts_data_urls(data_url = "data:image/png;base64,aW1hZ2U="result = await runtime.execute(- ToolCall(id="t", name="remove_background", arguments={"image_urls": [data_url]})+ ToolCall(id="t", name="remove_backgrounds", arguments={"image_urls": [data_url]}))assert result.ok@@ -106,7 +106,7 @@ async def test_remove_background_accepts_data_urls(@pytest.mark.asyncio-async def test_remove_background_converts_localhost_asset_url_to_data_url(+async def test_remove_backgrounds_converts_localhost_asset_url_to_data_url(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,) -> None:@@ -119,7 +119,7 @@ async def test_remove_background_converts_localhost_asset_url_to_data_url(captured.append(image_url)return "https://replicate.example/no-bg.png"- monkeypatch.setattr("agent.tools.runtime.remove_background", tracking_remove_bg)+ monkeypatch.setattr("agent.tools.runtime.remove_background_once", tracking_remove_bg)runtime = AgentToolRuntime(file_state=AgentFileState(),@@ -130,10 +130,102 @@ async def test_remove_background_converts_localhost_asset_url_to_data_url(local_url = "http://127.0.0.1:7001/local-assets/asset_123.png"result = await runtime.execute(- ToolCall(id="t", name="remove_background", arguments={"image_urls": [local_url]})+ ToolCall(id="t", name="remove_backgrounds", arguments={"image_urls": [local_url]}))assert result.ok# Replicate receives base64; the result keeps the original URL for display.assert captured == ["data:image/png;base64,aW1hZ2U="]assert result.result["images"][0]["image_url"] == local_url+++async def test_edit_images_batches_independent_edits_and_preserves_order(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr("agent.tools.runtime.REPLICATE_API_KEY", "fake-key")+ monkeypatch.setattr("agent.tools.runtime.IMAGE_TOOL_BATCH_SIZE", 2)++ concurrent = 0+ max_concurrent = 0+ captured: list[tuple[str, list[str], str]] = []++ async def tracking_edit(+ prompt: str,+ image_urls: list[str],+ api_token: str,+ *,+ aspect_ratio: str,+ ) -> str:+ nonlocal concurrent, max_concurrent+ captured.append((prompt, image_urls, aspect_ratio))+ concurrent += 1+ max_concurrent = max(max_concurrent, concurrent)+ await asyncio.sleep(0.01)+ concurrent -= 1+ if prompt == "fail independently":+ raise RuntimeError("intentional edit failure")+ return f"https://example.com/edited-{prompt}.png"++ monkeypatch.setattr("agent.tools.runtime.edit_image_once", tracking_edit)+ runtime = AgentToolRuntime(+ file_state=AgentFileState(),+ should_generate_images=True,+ openai_api_key=None,+ openai_base_url=None,+ )+ edits: list[dict[str, object]] = [+ {+ "prompt": "first",+ "image_urls": [+ "https://example.com/main.png",+ "https://example.com/reference.png",+ ],+ "aspect_ratio": "16:9",+ },+ {+ "prompt": "second",+ "image_urls": ["https://example.com/second.png"],+ },+ {+ "prompt": "fail independently",+ "image_urls": ["https://example.com/failure.png"],+ "aspect_ratio": "1:1",+ },+ {+ "prompt": "fourth",+ "image_urls": ["https://example.com/fourth.png"],+ },+ {+ "prompt": "fifth",+ "image_urls": ["https://example.com/fifth.png"],+ },+ ]++ result = await runtime.execute(+ ToolCall(id="test", name="edit_images", arguments={"edits": edits})+ )++ assert result.ok+ assert max_concurrent <= 2+ assert [item["prompt"] for item in result.result["images"]] == [+ edit["prompt"] for edit in edits+ ]+ assert captured[0] == (+ "first",+ [+ "https://example.com/main.png",+ "https://example.com/reference.png",+ ],+ "16:9",+ )+ assert captured[1][2] == "match_input_image"+ assert [item["status"] for item in result.result["images"]] == [+ "ok",+ "ok",+ "error",+ "ok",+ "ok",+ ]+ assert result.result["images"][2]["result_url"] is None+ assert len(result.multimodal_parts or []) == 4diff --git a/backend/tests/test_prompts.py b/backend/tests/test_prompts.pyindex 3ea32d6b..05eb652e 100644--- a/backend/tests/test_prompts.py+++ b/backend/tests/test_prompts.py@@ -131,7 +131,7 @@ class TestCreatePrompt:assert "Reuse .mockup-frame" in text@pytest.mark.asyncio- async def test_image_mode_create_requires_edit_image_for_upscaling(self) -> None:+ async def test_image_mode_create_requires_edit_images_for_upscaling(self) -> None:messages = await build_prompt_messages(stack=self.TEST_STACK,input_mode="image",@@ -154,7 +154,7 @@ class TestCreatePrompt:upscale_instruction = ("If an extracted or supplied asset is visibly low-resolution or pixelated "- "and must render larger, upscale it with edit_image—not CSS stretching or "+ "and must render larger, upscale it with edit_images—not CSS stretching or ""generate_images.")removed_instruction = 'Pass its source first, set aspect_ratio: "match_input_image"'diff --git a/backend/tests/test_tool_image_outputs.py b/backend/tests/test_tool_image_outputs.pyindex 37b700c4..3c442dd5 100644--- a/backend/tests/test_tool_image_outputs.py+++ b/backend/tests/test_tool_image_outputs.py@@ -280,15 +280,15 @@ async def test_generate_images_uses_replicate_key_from_settings(@pytest.mark.asyncio-async def test_edit_image_summary_preserves_full_prompt_and_source_urls(+async def test_edit_images_summary_preserves_full_prompt_and_source_urls(monkeypatch: pytest.MonkeyPatch,) -> None:monkeypatch.setattr("agent.tools.runtime.REPLICATE_API_KEY", "fake-key")- async def fake_edit_image(**kwargs: Any) -> str:+ async def fake_edit_images(**kwargs: Any) -> str:return "https://replicate.delivery/edited.png"- monkeypatch.setattr("agent.tools.runtime.edit_image", fake_edit_image)+ monkeypatch.setattr("agent.tools.runtime.edit_image_once", fake_edit_images)runtime = AgentToolRuntime(file_state=AgentFileState(),should_generate_images=True,@@ -303,27 +303,29 @@ async def test_edit_image_summary_preserves_full_prompt_and_source_urls(result = await runtime.execute(ToolCall(id="t",- name="edit_image",- arguments={"prompt": prompt, "image_urls": [source_url]},+ name="edit_images",+ arguments={+ "edits": [{"prompt": prompt, "image_urls": [source_url]}]+ },))assert result.multimodal_parts is not Noneassert result.multimodal_parts[0].image_url == "https://replicate.delivery/edited.png"- assert result.summary["image"]["prompt"] == prompt- assert result.summary["image"]["image_urls"] == [source_url]+ assert result.summary["images"][0]["prompt"] == prompt+ assert result.summary["images"][0]["image_urls"] == [source_url]@pytest.mark.asyncio-async def test_edit_image_error_summary_preserves_full_prompt_and_source_urls(+async def test_edit_images_error_summary_preserves_full_prompt_and_source_urls(monkeypatch: pytest.MonkeyPatch,) -> None:monkeypatch.setattr("agent.tools.runtime.REPLICATE_API_KEY", "fake-key")- async def fake_edit_image(**kwargs: Any) -> str:+ async def fake_edit_images(**kwargs: Any) -> str:raise RuntimeError("image edit failed")- monkeypatch.setattr("agent.tools.runtime.edit_image", fake_edit_image)+ monkeypatch.setattr("agent.tools.runtime.edit_image_once", fake_edit_images)runtime = AgentToolRuntime(file_state=AgentFileState(),should_generate_images=True,@@ -338,28 +340,31 @@ async def test_edit_image_error_summary_preserves_full_prompt_and_source_urls(result = await runtime.execute(ToolCall(id="t",- name="edit_image",- arguments={"prompt": prompt, "image_urls": [source_url]},+ name="edit_images",+ arguments={+ "edits": [{"prompt": prompt, "image_urls": [source_url]}]+ },))assert result.ok is True- assert result.summary["image"]["prompt"] == prompt- assert result.summary["image"]["image_urls"] == [source_url]+ assert result.summary["images"][0]["prompt"] == prompt+ assert result.summary["images"][0]["image_urls"] == [source_url]+ assert result.summary["images"][0]["status"] == "error"@pytest.mark.asyncio-async def test_edit_image_uses_replicate_key_from_settings(+async def test_edit_images_uses_replicate_key_from_settings(monkeypatch: pytest.MonkeyPatch,) -> None:monkeypatch.setattr("agent.tools.runtime.REPLICATE_API_KEY", None)captured: dict[str, Any] = {}- async def fake_edit_image(**kwargs: Any) -> str:+ async def fake_edit_images(**kwargs: Any) -> str:captured.update(kwargs)return "https://replicate.delivery/edited.png"- monkeypatch.setattr("agent.tools.runtime.edit_image", fake_edit_image)+ monkeypatch.setattr("agent.tools.runtime.edit_image_once", fake_edit_images)runtime = AgentToolRuntime(file_state=AgentFileState(),should_generate_images=True,@@ -371,8 +376,12 @@ async def test_edit_image_uses_replicate_key_from_settings(result = await runtime.execute(ToolCall(id="t",- name="edit_image",- arguments={"prompt": "bw", "image_urls": ["https://x/in.png"]},+ name="edit_images",+ arguments={+ "edits": [+ {"prompt": "bw", "image_urls": ["https://x/in.png"]}+ ]+ },))diff --git a/design-docs/agent-tool-calling-flow.md b/design-docs/agent-tool-calling-flow.mdindex 95543a11..4ee74a63 100644--- a/design-docs/agent-tool-calling-flow.md+++ b/design-docs/agent-tool-calling-flow.md@@ -60,7 +60,11 @@ Supported tools:- `create_file`- `edit_file`- `generate_images`-- `remove_background`+- `remove_backgrounds`+- `edit_images`+- `extract_assets`+- `screenshot_preview`+- `save_assets`- `retrieve_option`Execution lifecycle per tool call:diff --git a/frontend/src/components/agent/AgentActivity.tsx b/frontend/src/components/agent/AgentActivity.tsxindex 6232ef1f..1e7875d6 100644--- a/frontend/src/components/agent/AgentActivity.tsx+++ b/frontend/src/components/agent/AgentActivity.tsx@@ -168,10 +168,10 @@ function getEventIcon(type: AgentEventType, toolName?: string) {if (toolName === "generate_images") {return <BsImage className="text-pink-500" />;}- if (toolName === "remove_background") {+ if (toolName === "remove_backgrounds") {return <BsScissors className="text-teal-500" />;}- if (toolName === "edit_image") {+ if (toolName === "edit_images") {return <BsImage className="text-violet-500" />;}if (toolName === "retrieve_option") {@@ -214,7 +214,7 @@ function getEventTitle(event: AgentEvent): string {}return count ? `Generated ${count} image${count !== 1 ? "s" : ""}` : "Generated images";}- if (event.toolName === "remove_background") {+ if (event.toolName === "remove_backgrounds") {const rbInput = event.input as any;const rbOutput = event.output as any;const rbCount = rbOutput?.images?.length || rbInput?.image_urls?.length || 0;@@ -223,19 +223,19 @@ function getEventTitle(event: AgentEvent): string {}return rbCount > 1 ? `Removed ${rbCount} backgrounds` : "Background removed";}- if (event.toolName === "edit_image") {- const editInput = event.input as { image_urls?: unknown[] } | null;- const editOutput = event.output as {- image?: { image_urls?: unknown[] };- } | null;+ if (event.toolName === "edit_images") {+ const editInput = event.input as { edits?: unknown[] } | null;+ const editOutput = event.output as { images?: unknown[] } | null;const editCount =- editOutput?.image?.image_urls?.length || editInput?.image_urls?.length || 0;+ editOutput?.images?.length || editInput?.edits?.length || 0;if (event.status === "running") {- return editCount > 1- ? `Editing image with ${editCount} references`- : "Editing image";+ return editCount+ ? `Editing ${editCount} image${editCount !== 1 ? "s" : ""}`+ : "Editing images";}- return "Edited image";+ return editCount+ ? `Edited ${editCount} image${editCount !== 1 ? "s" : ""}`+ : "Edited images";}if (event.toolName === "retrieve_option") {return event.status === "running"@@ -311,12 +311,6 @@ function renderToolDetails(event: AgentEvent, variantCode?: string) {const output = event.output as any;const input = event.input as any;- const editImagePrompt =- typeof input?.prompt === "string"- ? input.prompt- : typeof output?.image?.prompt === "string"- ? output.image.prompt- : null;const hasError = Boolean(output?.error);const images =output && Array.isArray(output.images) ? (output.images as Array<any>) : null;@@ -432,7 +426,7 @@ function renderToolDetails(event: AgentEvent, variantCode?: string) {</div>)}- {event.toolName === "remove_background" && !hasError && (+ {event.toolName === "remove_backgrounds" && !hasError && (<div>{/* While running: show the source images */}{event.status === "running" && input?.image_urls && Array.isArray(input.image_urls) && (@@ -496,95 +490,170 @@ function renderToolDetails(event: AgentEvent, variantCode?: string) {</div>)}- {event.toolName === "edit_image" && !hasError && (+ {event.toolName === "edit_images" && !hasError && (<div>- {event.status === "running" && input?.image_urls && Array.isArray(input.image_urls) && (- <div className="space-y-3">- {editImagePrompt && <ExpandablePrompt prompt={editImagePrompt} />}+ {event.status === "running" &&+ input?.edits &&+ Array.isArray(input.edits) && (<div className="divide-y divide-gray-100 dark:divide-gray-800">- {input.image_urls.map((url: string, index: number) => (- <div key={`${url}-${index}`} className="py-2">- <div className="text-xs text-gray-500 dark:text-gray-400 mb-1">- {index === 0 ? "Main image" : `Reference image ${index + 1}`}+ {input.edits.map((rawItem: unknown, index: number) => {+ const item = getRecord(rawItem);+ const imageUrls = (getArrayField(item, "image_urls") || []).filter(+ (url): url is string => typeof url === "string"+ );+ const prompt =+ typeof item?.prompt === "string" ? item.prompt : null;+ const aspectRatio =+ typeof item?.aspect_ratio === "string"+ ? item.aspect_ratio+ : "match input";+ return (+ <div key={`${prompt || "edit"}-${index}`} className="py-3">+ <div className="flex items-center justify-between gap-2">+ <div className="text-xs font-medium text-gray-700 dark:text-gray-200">+ Edit {index + 1}+ </div>+ <div className="rounded-full bg-violet-50 px-2 py-0.5 text-[10px] text-violet-600 dark:bg-violet-900/30 dark:text-violet-300">+ {aspectRatio}+ </div>+ </div>+ {prompt && (+ <div className="mt-2">+ <ExpandablePrompt prompt={prompt} />+ </div>+ )}+ <div className="mt-3 grid grid-cols-3 gap-2">+ {imageUrls.map((url: string, imageIndex: number) => (+ <div key={`${url}-${imageIndex}`}>+ <div className="mb-1 text-[10px] text-gray-500 dark:text-gray-400">+ {imageIndex === 0+ ? "Main image"+ : `Reference ${imageIndex}`}+ </div>+ <img+ src={url}+ alt={+ imageIndex === 0+ ? `Main image for edit ${index + 1}`+ : `Reference ${imageIndex} for edit ${index + 1}`+ }+ className="aspect-square w-full rounded object-cover bg-gray-50 dark:bg-gray-800"+ loading="lazy"+ />+ </div>+ ))}+ </div></div>- <img- src={url}- alt={index === 0 ? "Main image" : `Reference image ${index + 1}`}- className="w-full rounded object-contain bg-gray-50 dark:bg-gray-800"- loading="lazy"- />- </div>- ))}+ );+ })}</div>- </div>- )}- {event.status !== "running" && output?.image && (- <div className="space-y-3">- {editImagePrompt && <ExpandablePrompt prompt={editImagePrompt} />}- <div className="grid gap-3 sm:grid-cols-2">- <div>- <div className="text-xs text-gray-500 dark:text-gray-400 mb-1">- Main image- </div>- {Array.isArray(output.image.image_urls) && output.image.image_urls[0] ? (- <img- src={output.image.image_urls[0]}- alt="Main image"- className="w-full rounded object-contain bg-gray-50 dark:bg-gray-800"- loading="lazy"- />- ) : (- <div className="aspect-square rounded bg-gray-100 dark:bg-gray-800 flex items-center justify-center text-xs text-gray-400">- Missing+ )}+ {event.status !== "running" && images && (+ <div className="divide-y divide-gray-100 dark:divide-gray-800">+ {images.map((item, index) => {+ const imageUrls = Array.isArray(item?.image_urls)+ ? item.image_urls+ : [];+ const prompt =+ typeof item?.prompt === "string" ? item.prompt : null;+ const succeeded =+ item?.status === "ok" && typeof item?.result_url === "string";+ return (+ <div key={`${prompt || "edit"}-${index}`} className="space-y-3 py-3">+ <div className="flex items-center justify-between gap-2">+ <div className="text-xs font-medium text-gray-700 dark:text-gray-200">+ Edit {index + 1}+ </div>+ <div className="flex items-center gap-1.5">+ <span className="rounded-full bg-gray-100 px-2 py-0.5 text-[10px] text-gray-500 dark:bg-gray-800 dark:text-gray-300">+ {item?.aspect_ratio || "match input"}+ </span>+ <span+ className={`rounded-full px-2 py-0.5 text-[10px] ${+ succeeded+ ? "bg-emerald-50 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-300"+ : "bg-red-50 text-red-600 dark:bg-red-900/30 dark:text-red-300"+ }`}+ >+ {succeeded ? "Complete" : "Failed"}+ </span>+ </div></div>- )}- </div>- <div>- <div className="text-xs text-gray-500 dark:text-gray-400 mb-1">- Edited image- </div>- {output.image.result_url ? (- <img- src={output.image.result_url}- alt="Edited image"- className="w-full rounded object-contain bg-gray-50 dark:bg-gray-800"- loading="lazy"- />- ) : (- <div className="aspect-square rounded bg-gray-100 dark:bg-gray-800 flex items-center justify-center text-xs text-gray-400">- Failed+ {prompt && <ExpandablePrompt prompt={prompt} />}+ <div className="grid grid-cols-2 gap-3">+ <div>+ <div className="mb-1 text-xs text-gray-500 dark:text-gray-400">+ Before+ </div>+ {imageUrls[0] ? (+ <img+ src={imageUrls[0]}+ alt={`Main image for edit ${index + 1}`}+ className="aspect-square w-full rounded object-contain bg-gray-50 dark:bg-gray-800"+ loading="lazy"+ />+ ) : (+ <div className="aspect-square rounded bg-gray-100 dark:bg-gray-800 flex items-center justify-center text-xs text-gray-400">+ Missing+ </div>+ )}+ </div>+ <div>+ <div className="mb-1 text-xs text-gray-500 dark:text-gray-400">+ After+ </div>+ {succeeded ? (+ <img+ src={item.result_url}+ alt={`Edited image ${index + 1}`}+ className="aspect-square w-full rounded object-contain bg-gray-50 dark:bg-gray-800"+ loading="lazy"+ />+ ) : (+ <div className="aspect-square rounded bg-gray-100 dark:bg-gray-800 flex items-center justify-center text-xs text-gray-400">+ Failed+ </div>+ )}+ </div></div>- )}- </div>- </div>- {Array.isArray(output.image.image_urls) && output.image.image_urls.length > 1 && (- <div>- <div className="text-xs text-gray-500 dark:text-gray-400 mb-1">- Reference images- </div>- <div className="grid grid-cols-3 gap-2">- {output.image.image_urls.slice(1).map((url: string, index: number) => (- <img- key={`${url}-${index}`}- src={url}- alt={`Reference image ${index + 2}`}- className="aspect-square w-full rounded object-cover bg-gray-50 dark:bg-gray-800"- loading="lazy"- />- ))}- </div>- </div>- )}- {output.image.result_url && (- <div>- <div className="text-xs text-gray-500 dark:text-gray-400">- Result URL- </div>- <div className="mt-1 break-all rounded bg-gray-50 p-2 font-mono text-xs text-gray-600 dark:bg-gray-800 dark:text-gray-300">- {output.image.result_url}+ {imageUrls.length > 1 && (+ <div>+ <div className="mb-1 text-xs text-gray-500 dark:text-gray-400">+ Reference images+ </div>+ <div className="grid grid-cols-3 gap-2">+ {imageUrls+ .slice(1)+ .map((url: string, referenceIndex: number) => (+ <img+ key={`${url}-${referenceIndex}`}+ src={url}+ alt={`Reference ${referenceIndex + 1} for edit ${index + 1}`}+ className="aspect-square w-full rounded object-cover bg-gray-50 dark:bg-gray-800"+ loading="lazy"+ />+ ))}+ </div>+ </div>+ )}+ {item?.error && (+ <div className="rounded bg-red-50 p-2 text-xs text-red-600 dark:bg-red-900/30 dark:text-red-200">+ {item.error}+ </div>+ )}+ {succeeded && (+ <div>+ <div className="text-xs text-gray-500 dark:text-gray-400">+ Result URL+ </div>+ <div className="mt-1 break-all rounded bg-gray-50 p-2 font-mono text-xs text-gray-600 dark:bg-gray-800 dark:text-gray-300">+ {item.result_url}+ </div>+ </div>+ )}</div>- </div>- )}+ );+ })}</div>)}</div>diff --git a/frontend/src/components/evals/agent-run-timeline.tsx b/frontend/src/components/evals/agent-run-timeline.tsxindex 816ba50c..0024670c 100644--- a/frontend/src/components/evals/agent-run-timeline.tsx+++ b/frontend/src/components/evals/agent-run-timeline.tsx@@ -72,9 +72,9 @@ function toolIcon(toolName: string) {return <BsPencilSquare className="text-purple-400" />;case "generate_images":return <BsImage className="text-pink-400" />;- case "remove_background":+ case "remove_backgrounds":return <BsScissors className="text-teal-400" />;- case "edit_image":+ case "edit_images":return <BsImage className="text-violet-400" />;case "retrieve_option":return <BsFiles className="text-slate-400" />;diff --git a/frontend/src/components/evals/agent-run-tool-preview.tsx b/frontend/src/components/evals/agent-run-tool-preview.tsxindex 73044dd7..ecba7da1 100644--- a/frontend/src/components/evals/agent-run-tool-preview.tsx+++ b/frontend/src/components/evals/agent-run-tool-preview.tsx@@ -70,7 +70,7 @@ function Img({ src, alt }: { src: string; alt: string }) {/*** Human-readable tool previews mirroring the in-app AgentActivity views- * (edit_image shows main/edited images, screenshot_preview shows the captured+ * (edit_images shows main/edited images, screenshot_preview shows the captured* screenshots, etc.), restyled for the dark eval theme. `args` is the full* recorded tool input; `summary` is the compact result the app itself renders.*/@@ -201,7 +201,7 @@ function ToolPreview({}}- if (name === "remove_background") {+ if (name === "remove_backgrounds") {const images = getArray(summary, "images");if (images) {return (@@ -235,60 +235,95 @@ function ToolPreview({}}- if (name === "edit_image") {- const image = getRecord(getRecord(summary)?.image);- const prompt = getString(args, "prompt") ?? getString(image, "prompt");- const imageUrls = getArray(image, "image_urls") ?? getArray(args, "image_urls");- const mainUrl =- imageUrls && typeof imageUrls[0] === "string" ? imageUrls[0] : null;- const resultUrl = getString(image, "result_url");- const referenceUrls = (imageUrls ?? [])- .slice(1)- .filter((url): url is string => typeof url === "string");+ if (name === "edit_images") {+ const resultImages = getArray(summary, "images") ?? [];+ const requestedEdits = getArray(args, "edits") ?? [];+ const edits = resultImages.length > 0 ? resultImages : requestedEdits;return (- <div className="space-y-3">- {prompt && (- <div>- <FieldLabel>Prompt</FieldLabel>- <p className="whitespace-pre-wrap break-words text-xs text-zinc-300">- {prompt}- </p>- </div>- )}- <div className="flex flex-wrap gap-4">- <div>- <FieldLabel>Main image</FieldLabel>- {mainUrl ? <Img src={mainUrl} alt="Main image" /> : <MissingBox />}- </div>- <div>- <FieldLabel>Edited image</FieldLabel>- {resultUrl ? (- <Img src={resultUrl} alt="Edited image" />- ) : (- <MissingBox label="Failed" />- )}- </div>- {referenceUrls.length > 0 && (- <div>- <FieldLabel>Reference images</FieldLabel>- <div className="flex flex-wrap gap-2">- {referenceUrls.map((url, index) => (- <Img- key={`${url}-${index}`}- src={url}- alt={`Reference ${index + 2}`}- />- ))}+ <div className="divide-y divide-zinc-800">+ {edits.map((item, index) => {+ const requestedEdit = requestedEdits[index];+ const prompt =+ getString(item, "prompt") ?? getString(requestedEdit, "prompt");+ const imageUrls =+ getArray(item, "image_urls") ??+ getArray(requestedEdit, "image_urls") ??+ [];+ const mainUrl =+ typeof imageUrls[0] === "string" ? imageUrls[0] : null;+ const resultUrl = getString(item, "result_url");+ const aspectRatio =+ getString(item, "aspect_ratio") ??+ getString(requestedEdit, "aspect_ratio") ??+ "match_input_image";+ const itemError = getString(item, "error");+ const referenceUrls = imageUrls+ .slice(1)+ .filter((url): url is string => typeof url === "string");+ return (+ <div key={`${prompt}-${index}`} className="space-y-3 py-3">+ <div className="flex items-center justify-between gap-3">+ <div className="text-xs font-semibold text-zinc-300">+ Edit {index + 1}+ </div>+ <div className="rounded-full bg-zinc-800 px-2 py-0.5 font-mono text-[10px] text-zinc-400">+ {aspectRatio}+ </div></div>+ {prompt && (+ <div>+ <FieldLabel>Prompt</FieldLabel>+ <p className="whitespace-pre-wrap break-words text-xs text-zinc-300">+ {prompt}+ </p>+ </div>+ )}+ <div className="flex flex-wrap gap-4">+ <div>+ <FieldLabel>Main image</FieldLabel>+ {mainUrl ? (+ <Img src={mainUrl} alt={`Main image ${index + 1}`} />+ ) : (+ <MissingBox />+ )}+ </div>+ <div>+ <FieldLabel>Edited image</FieldLabel>+ {resultUrl ? (+ <Img src={resultUrl} alt={`Edited image ${index + 1}`} />+ ) : (+ <MissingBox label="Failed" />+ )}+ </div>+ {referenceUrls.length > 0 && (+ <div>+ <FieldLabel>Reference images</FieldLabel>+ <div className="flex flex-wrap gap-2">+ {referenceUrls.map((url, referenceIndex) => (+ <Img+ key={`${url}-${referenceIndex}`}+ src={url}+ alt={`Reference ${referenceIndex + 1}`}+ />+ ))}+ </div>+ </div>+ )}+ </div>+ {itemError && (+ <div className="rounded bg-red-950/40 p-2 text-xs text-red-200">+ {itemError}+ </div>+ )}+ {resultUrl && (+ <div>+ <FieldLabel>Result URL</FieldLabel>+ <UrlChip url={resultUrl} />+ </div>+ )}</div>- )}- </div>- {resultUrl && (- <div>- <FieldLabel>Result URL</FieldLabel>- <UrlChip url={resultUrl} />- </div>- )}+ );+ })}</div>);}