Files
ai-agent/backend/test_worker_attachments.py
gabrielvidalandClaude Opus 5.5 74937cc195 test(workers): fake an outdated worker with a 404, not a filtered route list
FastAPI 0.163 keeps an included router whole (_IncludedRouter), so dropping
/uploads/{batch}/{name} from app.router.routes no longer removed it: the fake
worker kept accepting the upload and the refusal test failed. The hub was
never wrong — a sidecar from before /uploads answers 404 (relayed as-is
through a dial-out tunnel) and _push turns it into the 409 worker_outdated.
FakeWorker.predates now answers 404 on chosen path prefixes, as such a
worker would.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:30:12 +01:00

203 lines
9.8 KiB
Python

"""Composer attachments named by a path the run can open (runs/attachments.py):
on a worker, each stored file the prompt names is copied to its /uploads and
named by its path there; on the lab, by its path on the host — in the guest's
own folder for a guest's run, which its scope may read (the store it may not).
Imports ``main`` against throwaway paths (no startup event → no threads)."""
import os
import pathlib
import tempfile
import unittest
from unittest import mock
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",
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
"CRON_PATH": TMP / "cron.json", "SIDECAR_TOKEN": "",
"PROFILES_PATH": TMP / "profiles.json",
"UPLOADS_DIR": TMP / "uploads",
"UPLOADS_HOST_DIR": "/home/g/homelab/services/ai-agent/data/uploads/",
"PI_TRANSCRIPTS_DIR": ""}.items():
os.environ[k] = str(v)
from fastapi import HTTPException # noqa: E402
import accounts # noqa: E402
import main # noqa: E402
import workers # noqa: E402
from runs import attachments # noqa: E402
from runs.service import _send_message # noqa: E402
DEPS = main.app.state.ai
from _fakeworker import FakeWorker # noqa: E402
SID = "33333333-2222-3333-4444-555555555555"
REL = "services/ai-agent/data/uploads"
HOST = "/home/g/homelab/services/ai-agent/data/uploads"
GUEST_HOST = "/home/g/homelab/services/ai-agent/data/guest-uploads"
def _store(batch: str, name: str, data: bytes) -> str:
p = TMP / "uploads" / batch / name
p.parent.mkdir(parents=True, exist_ok=True)
p.write_bytes(data)
return f"{REL}/{batch}/{name}"
def _prompt(*paths: str) -> str:
return "\n".join(["Look at these", "",
"Attached files (uploaded via the composer — read each to analyze):",
*[f"- {p}" for p in paths]])
class Attachments(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="mac", hub_name="t",
resolve_login=lambda _l: None,
valid_account=accounts.valid)
self.landed = (TMP / "state" / "uploads").resolve()
def tearDown(self):
self.fw.stop()
DEPS.worker_store.delete(self.w["id"])
def test_named_finds_stored_uploads_once(self):
a = _store("aaaaaaaaaaaa", "shot.png", b"png")
text = f"see {a}. and `{a}` and {REL}/bbbbbbbbbbbb/missing.txt"
self.assertEqual(attachments.named(text), [("aaaaaaaaaaaa", "shot.png")])
self.assertEqual(attachments.named(f"/x/{a}"), []) # someone else's tree
def test_new_run_gets_the_files_and_their_paths_there(self):
a = _store("abc123def456", "shot.png", b"\x89PNG")
b = _store("abc123def456", "notes.txt", b"hello")
_send_message(DEPS, _prompt(a, b), worker=self.w["id"])
path, body = self.fw.calls[-1]
self.assertEqual(path, "/spawn")
there = self.landed / "abc123def456"
self.assertEqual((there / "shot.png").read_bytes(), b"\x89PNG")
self.assertEqual((there / "notes.txt").read_bytes(), b"hello")
self.assertIn(f"- {there / 'shot.png'}", body["prompt"])
self.assertIn(f"- {there / 'notes.txt'}", body["prompt"])
self.assertNotIn(REL, body["prompt"])
def test_a_trailing_dot_stays_the_sentences(self):
a = _store("ccc123def456", "x.txt", b"x")
out = attachments.for_worker(DEPS, f"read {a}.", self.w["id"])
self.assertEqual(out, f"read {self.landed / 'ccc123def456' / 'x.txt'}.")
def test_inbox_and_resume_get_the_worker_path_too(self):
a = _store("ddd123def456", "y.txt", b"y")
DEPS.meta_store.update(SID, {"worker": self.w["id"], "state": "running"})
self.fw.live = {SID}
self.fw.inbox = {SID}
_send_message(DEPS, _prompt(a), session_id=SID, cwd="/Users/g/repo")
path, body = self.fw.calls[-1]
self.assertEqual(path, "/message")
self.assertIn(str(self.landed / "ddd123def456" / "y.txt"), body["prompt"])
self.fw.live = set()
_send_message(DEPS, _prompt(a), session_id=SID, cwd="/Users/g/repo")
path, body = self.fw.calls[-1]
self.assertEqual(path, "/resume")
self.assertIn(str(self.landed / "ddd123def456" / "y.txt"), body["prompt"])
def test_unknown_paths_and_plain_prompts_are_untouched(self):
text = _prompt(f"{REL}/eeeeeeeeeeee/gone.png")
self.assertEqual(attachments.for_worker(DEPS, text, self.w["id"]), text)
self.assertEqual(attachments.for_worker(DEPS, "hi", self.w["id"]), "hi")
def test_lab_runs_get_the_host_path(self):
a = _store("ggg123def456", "w.txt", b"w")
host = "/home/g/homelab/services/ai-agent/data/uploads/ggg123def456/w.txt"
text = _prompt(a, f"{REL}/hhhhhhhhhhhh/gone.txt")
out = attachments.place(DEPS, text, None)
self.assertIn(f"- {host}", out)
self.assertIn(f"- {REL}/hhhhhhhhhhhh/gone.txt", out) # not in the store
self.assertEqual(attachments.place(DEPS, out, None), out) # never twice
# …and the worker's path wins over the host's on a worker
out = attachments.place(DEPS, text, self.w["id"])
self.assertIn(str(self.landed / "ggg123def456" / "w.txt"), out)
self.assertNotIn(host, out)
def test_a_guests_lab_run_gets_the_file_in_their_own_folder(self):
a = _store("iii123def456", "entete.png", b"\x89PNG")
scope = {"writeDirs": ["/tmp"], "git": {"user": "dom", "push": []}}
out = attachments.place(DEPS, _prompt(a), None, scope)
self.assertIn(f"- {GUEST_HOST}/dom/iii123def456/entete.png", out)
self.assertNotIn(HOST, out)
src = TMP / "uploads" / "iii123def456" / "entete.png"
there = TMP / "guest-uploads" / "dom" / "iii123def456" / "entete.png"
self.assertEqual(there.read_bytes(), b"\x89PNG")
self.assertFalse(there.is_symlink()) # read rules follow symlinks
self.assertEqual(there.stat().st_ino, src.stat().st_ino) # a hard link
self.assertEqual(attachments.place(DEPS, out, None, scope), out) # never twice
self.assertEqual(attachments.place(DEPS, _prompt(a), None, scope), out) # again: same
# the owner's run (no scope) and a guest's own computer (no git.user)
# keep the store's host path
self.assertIn(f"- {HOST}/iii123def456/entete.png",
attachments.place(DEPS, _prompt(a), None))
self.assertIn(f"- {HOST}/iii123def456/entete.png",
attachments.place(DEPS, _prompt(a), None, {"writeDirs": ["/tmp"]}))
def test_a_guest_scope_reads_its_folder_and_not_the_store(self):
scope = {"writeDirs": ["/tmp"], "denyRead": ["~/.ssh/**"],
"git": {"user": "dom", "push": []}}
self.assertIs(attachments.grant(scope), scope)
attachments.grant(scope) # idempotent
self.assertEqual(scope["readDirs"], [f"{GUEST_HOST}/dom"])
self.assertEqual(scope["denyRead"], ["~/.ssh/**", f"{HOST}/**"])
self.assertTrue((TMP / "guest-uploads" / "dom").is_dir()) # a sandbox binds it
self.assertIsNone(attachments.grant(None))
own = {"writeDirs": ["/tmp"], "denyRead": []} # a guest's computer
self.assertEqual(attachments.grant(own), {"writeDirs": ["/tmp"], "denyRead": []})
bad = {"git": {"user": "../dom"}}
self.assertNotIn("readDirs", attachments.grant(bad))
def test_a_guests_spawn_and_follow_up_reach_the_sidecar_placed(self):
a = _store("jjj123def456", "v.png", b"v")
calls = []
def launch(deps, account, path, payload, worker=None):
calls.append((path, payload))
return {"pid": 1}
def scope():
return {"writeDirs": ["/home/g/projects/oulipo", "/tmp"], "denyRead": [],
"git": {"user": "dom", "push": ["oulipo"]}}
placed = f"{GUEST_HOST}/dom/jjj123def456/v.png"
with mock.patch("runs.service._launch", launch):
out = _send_message(DEPS, _prompt(a), cwd="/home/g/projects/oulipo",
worker="local", scope=scope(), run_as="dom")
path, body = calls[-1]
self.assertEqual(path, "/spawn")
self.assertIn(f"- {placed}", body["prompt"])
self.assertEqual(body["scope"]["readDirs"], [f"{GUEST_HOST}/dom"])
self.assertIn(f"{HOST}/**", body["scope"]["denyRead"])
# a follow-up into the live run (its inbox) names the same file
sid = out["sessionId"]
DEPS.meta_store.update(sid, {"runAs": "dom", "state": "running"})
with mock.patch("runs.service._sidecar_call",
lambda deps, p, b, **k: calls.append((p, b)) or {"pid": 1}):
_send_message(DEPS, _prompt(a), session_id=sid,
cwd="/home/g/projects/oulipo", scope=scope(), run_as="dom")
path, body = calls[-1]
self.assertEqual(path, "/message")
self.assertIn(f"- {placed}", body["prompt"])
def test_a_worker_without_uploads_refuses_the_send(self):
a = _store("fff123def456", "z.txt", b"z")
self.fw.predates.add("/uploads/") # a worker from before /uploads
with self.assertRaises(HTTPException) as cm:
_send_message(DEPS, _prompt(a), worker=self.w["id"])
self.assertEqual(cm.exception.status_code, 409)
self.assertEqual(cm.exception.detail["kind"], "worker_outdated")
self.assertFalse([c for c in self.fw.calls if c[0] == "/spawn"])
if __name__ == "__main__":
unittest.main()