Skip to content

Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)

Python

Convert localhost URLs for all Replicate image tools

Abi Raja84261d90b4d1
diff --git a/backend/agent/tools/local_assets.py b/backend/agent/tools/local_assets.py
new file mode 100644
index 00000000..51420de8
--- /dev/null
+++ b/backend/agent/tools/local_assets.py
@@ -0,0 +1,45 @@
+"""Helpers for handing locally-served assets to external image APIs.
+
+Replicate (and other hosted model APIs) can't fetch ``localhost`` URLs, so any
+asset 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.
+"""
+
+import base64
+import mimetypes
+import os
+from urllib.parse import unquote, urlparse
+
+from config import LOCAL_ASSET_DIR
+
+LOCAL_ASSET_HOSTS = {"127.0.0.1", "localhost", "::1"}
+
+
+def local_asset_url_to_data_url(image_url: str) -> str:
+ """Inline a localhost ``/local-assets/`` URL as a base64 data URL.
+
+ External URLs and existing data URLs are returned unchanged, as is any
+ localhost URL that doesn't resolve to a real file under ``LOCAL_ASSET_DIR``.
+ """
+ parsed = urlparse(image_url)
+ if parsed.scheme not in {"http", "https"}:
+ return image_url
+ if parsed.hostname not in LOCAL_ASSET_HOSTS:
+ return image_url
+ if not parsed.path.startswith("/local-assets/"):
+ return image_url
+
+ relative_path = unquote(parsed.path.removeprefix("/local-assets/"))
+ asset_root = os.path.abspath(LOCAL_ASSET_DIR)
+ asset_path = os.path.abspath(os.path.join(asset_root, relative_path))
+ if not asset_path.startswith(asset_root + os.sep):
+ return image_url
+ if not os.path.isfile(asset_path):
+ return image_url
+
+ content_type = mimetypes.guess_type(asset_path)[0] or "image/png"
+ with open(asset_path, "rb") as file:
+ encoded = base64.b64encode(file.read()).decode("ascii")
+
+ return f"data:{content_type};base64,{encoded}"
diff --git a/backend/agent/tools/runtime.py b/backend/agent/tools/runtime.py
index 3c219f79..f88b2b65 100644
--- a/backend/agent/tools/runtime.py
+++ b/backend/agent/tools/runtime.py
@@ -1,15 +1,12 @@
# pyright: reportUnknownVariableType=false
import asyncio
-import base64
import difflib
-import mimetypes
-import os
-from urllib.parse import unquote, urlparse
from typing import Any, Dict, List, Optional, Tuple, Union, cast
from codegen.utils import extract_html_content
-from config import LOCAL_ASSET_DIR, REPLICATE_API_KEY
+from config import REPLICATE_API_KEY
from agent.tools.extract_assets import run_extract_assets
+from agent.tools.local_assets import local_asset_url_to_data_url
from agent.tools.screenshot_preview import run_screenshot_preview
from image_generation.generation import process_tasks
from image_generation.replicate import (
@@ -25,34 +22,6 @@ from agent.tools.types import ToolCall, ToolExecutionResult
from agent.tools.summaries import summarize_text
-LOCAL_ASSET_HOSTS = {"127.0.0.1", "localhost", "::1"}
-
-
-def _local_asset_url_to_data_url(image_url: str) -> str:
- """Replicate can't fetch localhost URLs, so inline local assets as data URLs."""
- parsed = urlparse(image_url)
- if parsed.scheme not in {"http", "https"}:
- return image_url
- if parsed.hostname not in LOCAL_ASSET_HOSTS:
- return image_url
- if not parsed.path.startswith("/local-assets/"):
- return image_url
-
- relative_path = unquote(parsed.path.removeprefix("/local-assets/"))
- asset_root = os.path.abspath(LOCAL_ASSET_DIR)
- asset_path = os.path.abspath(os.path.join(asset_root, relative_path))
- if not asset_path.startswith(asset_root + os.sep):
- return image_url
- if not os.path.isfile(asset_path):
- return image_url
-
- content_type = mimetypes.guess_type(asset_path)[0] or "image/png"
- with open(asset_path, "rb") as file:
- encoded = base64.b64encode(file.read()).decode("ascii")
-
- return f"data:{content_type};base64,{encoded}"
-
-
class AgentToolRuntime:
def __init__(
self,
@@ -366,7 +335,11 @@ class AgentToolRuntime:
raw_results: list[str | BaseException] = []
for i in range(0, len(unique_urls), batch_size):
batch = unique_urls[i : i + batch_size]
- tasks = [remove_background(url, REPLICATE_API_KEY) for url in batch]
+ # Replicate can't fetch localhost; inline local assets as data URLs.
+ tasks = [
+ remove_background(local_asset_url_to_data_url(url), REPLICATE_API_KEY)
+ for url in batch
+ ]
raw_results.extend(await asyncio.gather(*tasks, return_exceptions=True))
results: List[Dict[str, Any]] = []
@@ -436,7 +409,7 @@ class AgentToolRuntime:
try:
result_url = await edit_image(
prompt=prompt,
- image_urls=[_local_asset_url_to_data_url(url) for url in unique_urls],
+ image_urls=[local_asset_url_to_data_url(url) for url in unique_urls],
api_token=REPLICATE_API_KEY,
aspect_ratio=aspect_ratio,
)
diff --git a/backend/tests/test_batching.py b/backend/tests/test_batching.py
index 492905e6..8e1b14d1 100644
--- a/backend/tests/test_batching.py
+++ b/backend/tests/test_batching.py
@@ -1,4 +1,5 @@
import asyncio
+from pathlib import Path
import pytest
@@ -71,3 +72,68 @@ async def test_remove_background_batches_calls(
assert len(result.result["images"]) == 25
assert all(r["status"] == "ok" for r in result.result["images"])
assert max_concurrent <= 20
+
+
+async def test_remove_background_accepts_data_urls(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr("agent.tools.runtime.REPLICATE_API_KEY", "fake-key")
+ captured: list[str] = []
+
+ async def tracking_remove_bg(image_url: str, api_token: str) -> str:
+ captured.append(image_url)
+ return "https://replicate.example/no-bg.png"
+
+ monkeypatch.setattr("agent.tools.runtime.remove_background", tracking_remove_bg)
+
+ runtime = AgentToolRuntime(
+ file_state=AgentFileState(),
+ should_generate_images=True,
+ openai_api_key=None,
+ openai_base_url=None,
+ )
+ data_url = "data:image/png;base64,aW1hZ2U="
+
+ result = await runtime.execute(
+ ToolCall(id="t", name="remove_background", arguments={"image_urls": [data_url]})
+ )
+
+ assert result.ok
+ # Data URLs pass through unchanged.
+ assert captured == [data_url]
+ assert result.result["images"][0]["image_url"] == data_url
+
+
+async def test_remove_background_converts_localhost_asset_url_to_data_url(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setattr("agent.tools.runtime.REPLICATE_API_KEY", "fake-key")
+ monkeypatch.setattr("agent.tools.local_assets.LOCAL_ASSET_DIR", str(tmp_path))
+ (tmp_path / "asset_123.png").write_bytes(b"image")
+ captured: list[str] = []
+
+ async def tracking_remove_bg(image_url: str, api_token: str) -> str:
+ captured.append(image_url)
+ return "https://replicate.example/no-bg.png"
+
+ monkeypatch.setattr("agent.tools.runtime.remove_background", tracking_remove_bg)
+
+ runtime = AgentToolRuntime(
+ file_state=AgentFileState(),
+ should_generate_images=True,
+ openai_api_key=None,
+ openai_base_url=None,
+ )
+ 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]})
+ )
+
+ 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
diff --git a/backend/tests/test_local_assets.py b/backend/tests/test_local_assets.py
new file mode 100644
index 00000000..35d8bfe8
--- /dev/null
+++ b/backend/tests/test_local_assets.py
@@ -0,0 +1,53 @@
+import base64
+from pathlib import Path
+
+import pytest
+
+from agent.tools.local_assets import local_asset_url_to_data_url
+
+
+def test_converts_localhost_asset_to_data_url(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.setattr("agent.tools.local_assets.LOCAL_ASSET_DIR", str(tmp_path))
+ (tmp_path / "logo.png").write_bytes(b"image-bytes")
+
+ result = local_asset_url_to_data_url(
+ "http://127.0.0.1:7001/local-assets/logo.png"
+ )
+
+ expected = base64.b64encode(b"image-bytes").decode()
+ assert result == f"data:image/png;base64,{expected}"
+
+
+def test_passes_through_external_urls(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.setattr("agent.tools.local_assets.LOCAL_ASSET_DIR", str(tmp_path))
+ external = "https://replicate.delivery/abc/logo.png"
+ assert local_asset_url_to_data_url(external) == external
+
+
+def test_passes_through_existing_data_urls(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.setattr("agent.tools.local_assets.LOCAL_ASSET_DIR", str(tmp_path))
+ data_url = "data:image/png;base64,aW1hZ2U="
+ assert local_asset_url_to_data_url(data_url) == data_url
+
+
+def test_missing_file_is_left_unchanged(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.setattr("agent.tools.local_assets.LOCAL_ASSET_DIR", str(tmp_path))
+ url = "http://localhost:7001/local-assets/does-not-exist.png"
+ assert local_asset_url_to_data_url(url) == url
+
+
+def test_path_traversal_is_refused(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.setattr("agent.tools.local_assets.LOCAL_ASSET_DIR", str(tmp_path))
+ url = "http://127.0.0.1:7001/local-assets/../../etc/passwd"
+ # Escapes the asset root → returned unchanged, never read from disk.
+ assert local_asset_url_to_data_url(url) == url