Files
ai-agent/backend/test_tool_image.py
Gabriel VidalandClaude Opus 5.5 dff31ad430 feat(images): an image Claude read opens in a browser tab, from any machine
An image Read on a worker (the Orus Mac) showed "Not previewable", or a
false "No longer available" for a Mac /private/tmp/claude-501/ path read as
an expired lab scratchpad. The transcript already holds the bitmap the model
saw, so the hub serves it (GET /api/conversation-image), and the card:

- previews the lab's own file when it serves one, else that copy (a cleared
  scratchpad falls through to it too); worker paths never map onto the lab;
- header: Open in a new tab, Copy path, and Original ↗ while the run's
  worker is online (the hub fetches the path the call read from the worker's
  new GET /media; a lab file outside the served roots links host-file/raw).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 15:23:11 +01:00

192 lines
8.2 KiB
Python

"""The image a tool call handed the model, served from the transcript
(conversations/toolimage.py + GET /api/conversation-image): the right call's
image, a subagent's call through its parent's id, the bytes never reach a guest
who can't see the conversation, and nothing but raster images comes out — and
``original=1``, the file itself fetched from the worker the run was on.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
import base64
import json
import os
import pathlib
import tempfile
import unittest
TMP = pathlib.Path(tempfile.mkdtemp())
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
"PROFILES_PATH": TMP / "profiles.json",
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
"NOTIF_READ_PATH": TMP / "nr.json",
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
"PROJECTS_DIR": TMP / "projects", "SERVICES_DIR": TMP / "services",
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "claude.example.test",
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
os.environ[k] = str(v)
PNG = b"\x89PNG\r\n\x1a\nmain"
FULL_PNG = b"\x89PNG\r\n\x1a\nfull size"
MAC_SHOT = TMP / "mac" / "shot.png"
SUB_PNG = b"\x89PNG\r\n\x1a\nsub"
SID = "11111111-2222-3333-4444-555555555555"
def _image(data: bytes, media: str = "image/png") -> dict:
return {"type": "image", "source": {"type": "base64", "media_type": media,
"data": base64.b64encode(data).decode()}}
def _read(tid: str, path: str) -> dict:
return {"type": "assistant", "sessionId": SID, "timestamp": "2026-11-03T10:00:00Z",
"message": {"role": "assistant", "content": [
{"type": "tool_use", "id": tid, "name": "Read", "input": {"file_path": path}}]}}
def _result(tid: str, *blocks: dict) -> dict:
return {"type": "user", "sessionId": SID, "timestamp": "2026-11-03T10:00:01Z",
"message": {"role": "user", "content": [
{"type": "tool_result", "tool_use_id": tid, "content": list(blocks)}]}}
def _write(p: pathlib.Path, *recs: dict) -> None:
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("".join(json.dumps(r) + "\n" for r in recs))
CONV = f"-Users-gabriel-orus/{SID}.jsonl"
MAIN = TMP / "arch" / CONV
_write(MAIN,
{"type": "user", "sessionId": SID, "timestamp": "2026-11-03T09:59:00Z",
"message": {"role": "user", "content": "look at the screenshot"}},
_read("toolu_main", str(MAC_SHOT)),
_result("toolu_main", _image(PNG)),
_read("toolu_text", "/Users/gabriel/a.txt"),
_result("toolu_text", {"type": "text", "text": "toolu_main is mentioned here"}),
_read("toolu_svg", "/Users/gabriel/x.svg"),
_result("toolu_svg", _image(b"<svg/>", "image/svg+xml")))
_write(MAIN.parent / SID / "subagents" / "agent-a1.jsonl",
{**_read("toolu_sub", "/Users/gabriel/sub.png"), "isSidechain": True, "agentId": "a1"},
{**_result("toolu_sub", _image(SUB_PNG)), "isSidechain": True, "agentId": "a1"})
(MAIN.parent / SID / "subagents" / "agent-a1.meta.json").write_text("{}")
from fastapi.testclient import TestClient # noqa: E402
import accounts # noqa: E402
import main # noqa: E402
import workers # noqa: E402
from _fakeworker import FakeWorker # noqa: E402
from conversations import toolimage # noqa: E402
from users.caller import SESSION_COOKIE # noqa: E402
DEPS = main.app.state.ai
OWNER_H = {"X-Internal-Auth": "tok"}
class FindInTranscript(unittest.TestCase):
def test_the_calls_own_image(self):
self.assertEqual(toolimage.find(MAIN, "toolu_main"), (PNG, "image/png"))
def test_a_mention_elsewhere_is_not_a_result(self):
self.assertIsNone(toolimage.find(MAIN, "toolu_text"))
self.assertIsNone(toolimage.find(MAIN, "toolu_main", 1))
self.assertIsNone(toolimage.find(MAIN, "toolu_nope"))
self.assertIsNone(toolimage.find(MAIN, ""))
def test_only_raster_images(self):
self.assertIsNone(toolimage.find(MAIN, "toolu_svg"))
class Route(unittest.TestCase):
def setUp(self):
for u in DEPS.users.all():
DEPS.users.delete(u["id"])
self.dom = DEPS.users.create("dom@example.com", "Dom", projects={})
self.owner = TestClient(main.app)
def _get(self, client, tid, **kw):
return client.get("/api/conversation-image",
params={"id": CONV, "toolUseId": tid, **kw}, headers=OWNER_H)
def test_owner_gets_the_bytes(self):
r = self._get(self.owner, "toolu_main")
self.assertEqual(r.status_code, 200)
self.assertEqual(r.content, PNG)
self.assertEqual(r.headers["content-type"], "image/png")
self.assertEqual(r.headers["x-content-type-options"], "nosniff")
def test_a_subagents_call_through_the_parent(self):
self.assertEqual(self._get(self.owner, "toolu_sub").content, SUB_PNG)
def test_no_image_is_404(self):
self.assertEqual(self._get(self.owner, "toolu_text").status_code, 404)
self.assertEqual(self._get(self.owner, "toolu_svg").status_code, 404)
def test_bad_ids_are_refused(self):
r = self.owner.get("/api/conversation-image", headers=OWNER_H,
params={"id": "../../etc/passwd.jsonl", "toolUseId": "x"})
self.assertEqual(r.status_code, 400)
def test_a_guest_who_cant_see_it_gets_404(self):
g = TestClient(main.app, base_url="https://claude.example.test")
g.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(self.dom["id"]))
r = g.get("/api/conversation-image", params={"id": CONV, "toolUseId": "toolu_main"})
self.assertEqual(r.status_code, 404)
DEPS.meta_store.update(SID, {"owner": self.dom["id"]})
try:
r = g.get("/api/conversation-image", params={"id": CONV, "toolUseId": "toolu_main"})
self.assertEqual((r.status_code, r.content), (200, PNG))
finally:
DEPS.meta_store.update(SID, {"owner": None})
class Original(unittest.TestCase):
def setUp(self):
self.fw = FakeWorker(TMP / "remote", TMP / "state")
self.w = workers.pair(DEPS.worker_store, self.fw.pairing_string("work"),
account=None, name="Orus MacBook", hub_name="t",
resolve_login=lambda _l: None,
valid_account=accounts.valid)
MAC_SHOT.parent.mkdir(parents=True, exist_ok=True)
MAC_SHOT.write_bytes(FULL_PNG)
self.owner = TestClient(main.app)
def tearDown(self):
self.fw.stop()
DEPS.worker_store.delete(self.w["id"])
DEPS.meta_store.update(SID, {"workerSource": None})
def _get(self, tid):
return self.owner.get("/api/conversation-image", headers=OWNER_H,
params={"id": CONV, "toolUseId": tid, "original": 1})
def test_fetched_from_the_worker_it_ran_on(self):
DEPS.meta_store.update(SID, {"workerSource": self.w["id"]})
r = self._get("toolu_main")
self.assertEqual((r.status_code, r.content), (200, FULL_PNG))
self.assertEqual(r.headers["content-type"], "image/png")
def test_a_lab_run_has_no_worker_original(self):
self.assertEqual(self._get("toolu_main").status_code, 404)
def test_gone_from_the_mac_or_not_an_image(self):
DEPS.meta_store.update(SID, {"workerSource": self.w["id"]})
self.assertEqual(self._get("toolu_text").status_code, 404) # a .txt read
MAC_SHOT.unlink()
r = self._get("toolu_main")
self.assertEqual(r.status_code, 404)
self.assertIn("no longer on Orus MacBook", r.json()["detail"])
def test_an_offline_worker_is_502(self):
DEPS.meta_store.update(SID, {"workerSource": self.w["id"]})
self.fw.stop()
self.assertEqual(self._get("toolu_main").status_code, 502)
if __name__ == "__main__":
unittest.main()