"""Direct HTTP checks for ACP authorization, admission, restart, and MCP state. Adapter-visible behavior belongs in acp_test.py. """ import base64 import json from pathlib import Path import re import secrets import sqlite3 import sys import threading import unittest import urllib.error from _imagegen_support import png from harness import ( ROOT, Albedo, Provider, exclusive, exclusive_class, latest_user, mcp_call, mcp_operations, operation_id, python, stored_with, text, wait_until, ) SERVER = Path(__file__).with_name("fake_mcp_server.py") SECRET = "editor-literal-secret-4f1c" def fake_server(name="editor", secret=SECRET): return { "name": name, "command": sys.executable, "args": [str(SERVER)], "env": [ {"name": "FAKE_SECRET", "value": secret}, {"name": "FAKE_REPORT_CWD", "value": "1"}, ], } def token(): return base64.urlsafe_b64encode(secrets.token_bytes(32)).rstrip(b"=").decode() class AcpClient: """One ACP connection's view of the daemon: its token and its sessions.""" def __init__(self, app): self.app = app self.token = token() def headers(self, extra=None): return {"Albedo-Attachment-Token": self.token, **(extra or {})} def create(self, session_id=None, workspace=None, servers=()): session_id = session_id or operation_id() with self.app.api( f"/sessions/{session_id}", { "kind": "acp", "workspace": str(workspace or self.app.workspace), "mcp_servers": list(servers), }, method="PUT", headers=self.headers({"If-None-Match": "*"}), ) as response: created = json.load(response) return session_id, created def attach(self, session_id, workspace=None, servers=()): with self.app.api( f"/sessions/{session_id}/acp-attachment", { "workspace": str(workspace or self.app.workspace), "mcp_servers": list(servers), }, method="PUT", headers=self.headers(), ) as response: return json.load(response) def renew(self, session_id): with self.app.api( f"/sessions/{session_id}/acp-attachment/renew", {}, method="POST", headers=self.headers(), ) as response: return response.status def release(self, session_id): with self.app.api( f"/sessions/{session_id}/acp-attachment", method="DELETE", headers=self.headers(), ) as response: return response.status def prompt(self, session_id, blocks, input_id=None): input_id = input_id or operation_id() with self.app.api( f"/sessions/{session_id}/inputs/{input_id}", {"kind": "acp_prompt", "blocks": blocks}, method="PUT", headers=self.headers(), ) as response: return input_id, json.load(response) def session_mutations(): """Every change under one session that docs/openapi.yaml lists, as (operation id, method, path template, whether other clients are refused on an ACP session). The declaration is x-albedo-acp-other-clients, which cli/tools/apigen requires of each such operation. Read by indentation, so the test needs no YAML parser.""" operations, path, method, operation = [], None, None, None for line in (ROOT / "docs/openapi.yaml").read_text().splitlines(): stripped = line.strip().rstrip(":") if line.startswith(" /"): path, method = stripped, None elif line and not line.startswith(" "): path = None elif path and line.startswith(" ") and line[4] != " ": method = ( stripped.upper() if stripped in ("put", "post", "patch", "delete") else None ) operation = None elif path and method and stripped.startswith("operationId"): operation = line.split(":", 1)[1].strip() elif path and method and stripped.startswith("x-albedo-acp-other-clients"): refused = line.split(":", 1)[1].strip() == "refused" if path.startswith("/sessions/{session_id}"): operations.append((operation, method, path, refused)) method = None return operations # A body that passes validation, so the request reaches the ownership check. VALID_BODY = { "putSideQuestion": {"question": "side question"}, "patchSideQuestion": {"dismissed": True}, "putShellCommand": {"command": "printf not-allowed"}, "putInput": {"kind": "message", "text": "from the terminal"}, "patchSession": {"model": "fixture-model"}, "patchFastMode": {"state": "off"}, } def session_read(app, session_id): with app.api(f"/sessions/{session_id}?tail=0") as response: return json.load(response) def refused(test, call, status, code): with test.assertRaises(urllib.error.HTTPError) as failure: call() test.assertEqual(failure.exception.code, status) test.assertEqual(json.load(failure.exception)["code"], code) class AcpAttachmentTest(unittest.TestCase): def setUp(self): self.app = Albedo() self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None) def test_competing_attachment_is_refused_until_released(self): first, second = AcpClient(self.app), AcpClient(self.app) session_id, _ = first.create() refused(self, lambda: second.attach(session_id), 409, "attachment_held") refused(self, lambda: second.renew(session_id), 409, "attachment_lost") first.attach(session_id) self.assertEqual(first.renew(session_id), 204) self.assertEqual(first.release(session_id), 204) self.assertEqual(first.release(session_id), 204) self.assertEqual( session_read(self.app, session_id)["acp"]["attachment"], "detached" ) second.attach(session_id) self.assertEqual( session_read(self.app, session_id)["acp"]["attachment"], "attached" ) def test_attach_checks_marker_and_exact_workspace(self): editor = AcpClient(self.app) plain = self.app.session() refused(self, lambda: editor.attach(plain), 409, "not_acp_session") session_id, _ = editor.create() other = self.app.workspace / "nested" other.mkdir() refused( self, lambda: editor.attach(session_id, workspace=other), 409, "workspace_mismatch", ) refused(self, lambda: editor.attach(operation_id()), 404, "session_not_found") def test_other_clients_read_but_cannot_drive_an_acp_session(self): editor, stranger = AcpClient(self.app), AcpClient(self.app) session_id, created = editor.create() self.assertEqual(created["acp"]["attachment"], "attached") # A resent creation recovers the same session; another intent under # the same identity conflicts. The request decoding is # acp_creation_test's and the ledger rule operations_ledger_test's. _, again = editor.create(session_id) self.assertEqual(again["id"], created["id"]) other = self.app.workspace / "other" other.mkdir() refused( self, lambda: editor.create(session_id, workspace=other), 409, "creation_conflict", ) bodies = [json.dumps(created), json.dumps(again)] snapshot = session_read(self.app, session_id) etag = snapshot["configuration_resource"]["etag"] VALID_BODY["moveSessionWorkspace"] = { "workspace": str(self.app.workspace), "family_revision": snapshot["family_revision"], } swept = [] for operation, method, template, refused_here in session_mutations(): if not refused_here: continue swept.append(operation) path = re.sub( r"\{(\w+)\}", lambda m: session_id if m[1] == "session_id" else operation_id(), template, ) for token, codes in ( ({}, {"acp_owned"}), (stranger.headers(), {"acp_owned", "attachment_lost"}), ): with self.subTest(operation=operation, token=bool(token)): with self.assertRaises(urllib.error.HTTPError) as failure: self.app.api( path, VALID_BODY.get(operation, {}), method=method, headers={"If-Match": etag, **token}, ).close() body = failure.exception.read() bodies.append(body.decode()) self.assertEqual(failure.exception.code, 409, (operation, body)) self.assertIn(json.loads(body)["code"], codes) self.assertIn("putInput", swept) refused( self, lambda: stranger.prompt(session_id, [{"type": "text", "text": "hi"}]), 409, "attachment_lost", ) refused( self, lambda: self.app.api( f"/sessions/{session_id}/shell-commands/{operation_id()}" ), 404, "shell_command_not_found", ) # The holder may compact; afterwards others still may not read or # repeat its compaction. compaction = f"/sessions/{session_id}/compactions/{operation_id()}" with self.app.api(compaction, {}, method="PUT", headers=editor.headers()): pass refused(self, lambda: self.app.api(compaction), 409, "acp_owned") refused( self, lambda: self.app.api(compaction, {}, method="PUT"), 409, "acp_owned" ) with self.app.api(compaction, headers=editor.headers()): pass with self.app.api(f"/sessions/{session_id}/configuration") as response: etag = response.headers["ETag"] refused( self, lambda: self.app.api( f"/sessions/{session_id}/configuration", { "model": "fixture-model", "selection": {"extensions": {"files": False}}, }, method="PATCH", headers=editor.headers({"If-Match": etag}), ), 409, "acp_owned", ) refused( self, lambda: self.app.api( f"/sessions/{session_id}/configuration", {"model": "fixture-model"}, method="PATCH", headers=stranger.headers({"If-Match": etag}), ), 409, "attachment_lost", ) with self.app.api( f"/sessions/{session_id}/configuration", {"name": "renamed by the operator"}, method="PATCH", headers={"If-Match": etag}, ): pass snapshot = session_read(self.app, session_id) self.assertEqual(snapshot["name"], "renamed by the operator") # The daemon keeps only a digest of the token: no response and no file # in the home carries it. bodies += [json.dumps(editor.attach(session_id)), json.dumps(snapshot)] self.assertFalse([body for body in bodies if editor.token in body]) self.assertEqual(stored_with(self.app.home, editor.token), []) def test_fast_mode_belongs_to_the_editor(self): # Fast mode changes how the session's turns run and what they cost, # like the configuration's model; only the attachment holder may set it. editor, stranger = AcpClient(self.app), AcpClient(self.app) session_id, _ = editor.create() with self.app.api(f"/sessions/{session_id}/fast-mode") as response: etag = response.headers["ETag"] def patch(headers): return self.app.api( f"/sessions/{session_id}/fast-mode", {"state": "off"}, method="PATCH", headers={"If-Match": etag, **headers}, ) refused(self, lambda: patch({}), 409, "acp_owned") refused(self, lambda: patch(stranger.headers()), 409, "attachment_lost") with patch(editor.headers()) as response: self.assertEqual(response.status, 200) def test_moving_an_editor_session_belongs_to_the_editor(self): # A move takes the session away from the editor attached to it. editor, stranger = AcpClient(self.app), AcpClient(self.app) session_id, _ = editor.create() def move(headers, target="host:/srv/albedo"): return self.app.api( f"/sessions/{session_id}/move", {"transfer_id": operation_id(), "target": target}, method="POST", headers=headers, ) refused(self, lambda: move({}), 409, "acp_owned") refused(self, lambda: move(stranger.headers()), 409, "attachment_lost") # The holder passes the ownership check and meets the move's own # validation, here of a target that names no host. refused( self, lambda: move(editor.headers(), target="no-host"), 400, "invalid_request", ) def test_resource_links_reject_invalid_uris_and_unknown_path(self): editor = AcpClient(self.app) session_id, _ = editor.create() bad = [ { "type": "resource_link", "uri": "file:///tmp/a", "name": "a", "path": "/tmp/b", }, { "type": "resource_link", "uri": "file://remote/tmp/a", "name": "a", }, { "type": "resource_link", "uri": "file:///tmp/%zz", "name": "a", }, { "type": "resource_link", "uri": "file:///tmp/a", "name": "a", "size": -1, }, {"type": "image", "data": "", "mime_type": "image/png"}, ] for block in bad: with self.subTest(block=block): refused( self, lambda: editor.prompt(session_id, [block]), 400, "invalid_request", ) @exclusive def test_media_prompt_retry_requires_the_same_payload_and_metadata(self): editor = AcpClient(self.app) session_id, _ = editor.create() image = { "type": "image", "mime_type": "image/png", "data": base64.b64encode(png(3, 2)).decode(), } resource = { "uri": "urn:acp:context", "blob": "AA==", "meta": {"editor": "original"}, } blocks = [image, {"type": "resource", "resource": resource}] input_id, first = editor.prompt(session_id, blocks) self.app.idle(session_id) _, retried = editor.prompt(session_id, blocks, input_id) self.assertEqual(retried["id"], first["id"]) for changed in ( [{**image, "data": base64.b64encode(png(4, 2)).decode()}, blocks[1]], [image, {**blocks[1], "resource": {**resource, "blob": "AQ=="}}], [ image, {**blocks[1], "resource": {**resource, "meta": {"editor": "changed"}}}, ], ): refused( self, lambda: editor.prompt(session_id, changed, input_id), 409, "input_conflict", ) class Gate: """A provider that answers each request only once the test opens it.""" def __init__(self, reply="done"): self.opened = threading.Event() self.requests = [] self.reply = reply self.provider = Provider(self.answer) def answer(self, request): self.requests.append(request) self.opened.wait(30) return text(self.reply) @exclusive_class class AcpTurnTest(unittest.TestCase): def setUp(self): self.gate = Gate() self.addCleanup(self.gate.provider.close) self.addCleanup(self.gate.opened.set) self.app = Albedo(self.gate.provider, protocol="responses") self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None) self.editor = AcpClient(self.app) self.session_id, _ = self.editor.create() def receipt(self, input_id): with self.app.api(f"/sessions/{self.session_id}/inputs/{input_id}") as response: return json.load(response) def test_attach_captures_the_running_turn_and_later_prompts_wait(self): first, _ = self.editor.prompt( self.session_id, [{"type": "text", "text": "one"}] ) wait_until( lambda: self.gate.requests, 30, "the first turn never reached the model" ) second, _ = self.editor.prompt( self.session_id, [{"type": "text", "text": "two"}] ) attached = self.editor.attach(self.session_id) self.assertEqual(attached["active_turn"]["acp_input_id"], first) self.assertEqual(attached["pending_input_ids"], [second]) captured_history = self.app.history(self.session_id)["items"] self.assertEqual( attached["history_cutoff"], max((row["position"] for row in captured_history), default=0), ) self.gate.opened.set() self.app.idle(self.session_id) later = self.app.stream_page( self.session_id, { "generation": attached["cursor"]["generation"], "cursor": attached["cursor"]["sequence"], }, )["events"] later_positions = { event["data"]["entry"]["position"] for event in later if event["type"] == "message" } final_history = self.app.history(self.session_id)["items"] self.assertTrue(later_positions) self.assertTrue( all( any(row["position"] == position for row in final_history) for position in later_positions ) ) self.assertTrue( all(position > attached["history_cutoff"] for position in later_positions) ) self.assertNotEqual( self.receipt(first)["turn"]["id"], self.receipt(second)["turn"]["id"] ) def test_scoped_cancellation_requires_the_current_attachment(self): running, _ = self.editor.prompt( self.session_id, [{"type": "text", "text": "running"}] ) wait_until(lambda: self.gate.requests, 30, "turn never reached the provider") queued, _ = self.editor.prompt( self.session_id, [{"type": "text", "text": "queued"}] ) replacement = AcpClient(self.app) def cancel(input_id, headers=None): with self.app.api( f"/sessions/{self.session_id}/inputs/{input_id}/cancel", {}, method="POST", headers=headers, ) as response: return json.load(response)["result"] for headers in (None, replacement.headers()): refused(self, lambda: cancel(running, headers), 409, "attachment_lost") refused(self, lambda: cancel(queued, headers), 409, "attachment_lost") self.editor.release(self.session_id) replacement.attach(self.session_id) refused( self, lambda: cancel(running, self.editor.headers()), 409, "attachment_lost" ) self.assertEqual(cancel(queued, replacement.headers()), "cancelled") # Even a terminal receipt requires the current writer's token. refused( self, lambda: cancel(queued, self.editor.headers()), 409, "attachment_lost" ) self.assertEqual(cancel(queued, replacement.headers()), "not_pending") self.assertEqual(cancel(running, replacement.headers()), "interrupt_requested") self.app.idle(self.session_id) self.assertEqual(self.receipt(queued)["delivery"], "cancelled") self.assertEqual(len(self.gate.requests), 1) class AcpOverlayValidationTest(unittest.TestCase): def setUp(self): self.app = Albedo() self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None) def patch_settings(self, group, fields): route = "/settings/" + group with self.app.api(route) as response: json.load(response) etag = response.headers["ETag"] with self.app.api( route, fields, method="PATCH", headers={"If-Match": etag} ) as response: return json.load(response) @exclusive def test_disabled_mcp_extensions_still_check_servers_and_overlays(self): self.patch_settings( "extensions", {"defaults": {"mcp": False, "editor-mcp": False}} ) refused( self, lambda: self.patch_settings( "mcp", { "definitions": { "bad": {"transport": "http", "url": "file:///tmp/server"} }, "validate_connection": False, }, ), 400, "invalid_request", ) configured = { "transport": "stdio", "command": sys.executable, "arguments": [str(SERVER)], } refused( self, lambda: self.patch_settings( "mcp", { "definitions": { "shared": {**configured, "command": "/nonexistent/mcp"} } }, ), 503, "settings_unavailable", ) self.patch_settings("mcp", {"definitions": {"shared": configured}}) editor = AcpClient(self.app) marker = self.app.workspace / "shadowed-command-started" shadowed = { **fake_server("shared"), "args": [ "-c", "import pathlib, sys; pathlib.Path(sys.argv[1]).touch()", str(marker), ], } session, _ = editor.create(servers=[shadowed, fake_server()]) editor.create(session, servers=[fake_server()]) editor.attach(session, servers=[shadowed]) self.app.restart(crash=True) editor.attach(session, servers=[shadowed]) with sqlite3.connect(self.app.home / "albedo.sqlite") as db: (identities,) = db.execute( "SELECT acp_overlay_identities FROM sessions WHERE id = ?", (session,) ).fetchone() self.assertEqual(json.loads(identities), []) self.assertFalse(marker.exists()) refused( self, lambda: editor.attach(session, servers=[shadowed, shadowed]), 409, "mcp_overlay_conflict", ) # A server that cannot start rejects the creation and leaves no session. refused_id = operation_id() refused( self, lambda: editor.create( refused_id, servers=[{**fake_server(), "command": "/nonexistent/editor-mcp"}], ), 409, "mcp_overlay_failed", ) refused( self, lambda: session_read(self.app, refused_id), 404, "session_not_found", ) editor.create(servers=[fake_server()]) def test_invalid_http_overlay_leaves_no_session_or_credentials(self): editor = AcpClient(self.app) private = "invalid-http-overlay-secret" server = { "name": "remote", "type": "http", "url": "http://127.0.0.1:1/mcp", "headers": [], } cases = [ ( { "headers": [ {"name": "Authorization", "value": private}, {"name": "authorization", "value": private}, ] }, 400, "invalid_request", ), ( {"url": f"http://user:{private}@127.0.0.1:1/mcp"}, 409, "mcp_overlay_failed", ), ( { "headers": [ {"name": "X-Test", "value": private + "\r\nX-Extra: nope"} ] }, 409, "mcp_overlay_failed", ), ( {"headers": [{"name": "Content-Length", "value": "0"}]}, 409, "mcp_overlay_failed", ), ] for patch, status, code in cases: with self.subTest(fields=list(patch), status=status): session_id = operation_id() refused( self, lambda: editor.create(session_id, servers=[{**server, **patch}]), status, code, ) refused( self, lambda: session_read(self.app, session_id), 404, "session_not_found", ) self.assertEqual(stored_with(self.app.home, private), []) class OverlayTool: """A model that calls the first editor MCP operation once, from Python, then answers.""" def __init__(self): self.opened = threading.Event() self.opened.set() self.results = [] self.provider = Provider(self.answer) def answer(self, request): self.opened.wait(30) inputs = request["input"] last_user = max( (index for index, item in enumerate(inputs) if item.get("role") == "user"), default=-1, ) outputs = [ item for item in inputs[last_user + 1 :] if item.get("type") == "function_call_output" ] if outputs: self.results.append(outputs[-1]["output"]) return text("done") operations = mcp_operations(request) if not operations: return text("no tools") return mcp_call(operations[0], message="hi") @exclusive class AcpOverlayTest(unittest.TestCase): def setUp(self): self.model = OverlayTool() self.addCleanup(self.model.provider.close) self.addCleanup(self.model.opened.set) self.app = Albedo(self.model.provider, protocol="responses") self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None) self.editor = AcpClient(self.app) def send_fixture_mail(self, session): def script(request): inputs = request.get("input", []) if any(item.get("type") == "function_call_output" for item in inputs): return text("sent") if "send fixture mail" in latest_user(request): return python(f"await mail.submit({session!r}, 'editor detached')") return text("mail delivered") self.model.provider.script = script sender = self.app.session() self.app.prompt(sender, "send fixture mail").close() self.app.idle(sender) return sender def test_overlay_requirement_survives_restart_and_a_failed_reload_fences_turns( self, ): """The durable overlay requirement outlives a real restart: mail to the session waits until the editor resupplies its servers. A published overlay whose runtime reload fails fences turns until a reattach reloads it, and the turn then uses the new server's credentials. The readiness rules themselves are acp_attachments_test's model.""" session, _ = self.editor.create(servers=[fake_server()]) self.app.restart() self.send_fixture_mail(session) wait_until( lambda: ( "overlay_reattach_required" in json.dumps(session_read(self.app, session)["activity"]) ), 15, "missing overlay to require editor reattachment", ) self.assertEqual(self.app.history(session)["items"], []) self.editor.attach(session, servers=[fake_server()]) wait_until( lambda: any( row["kind"] == "assistant" for row in self.app.history(session)["items"] ), 15, "pending mail to run after editor reattachment", ) self.app.idle(session) self.model.provider.script = self.model.answer broken_prompt = self.app.workspace / "SYSTEM.md" broken_prompt.write_bytes(b"\xff") replacement = fake_server(secret="replacement-editor-secret") refused( self, lambda: self.editor.attach(session, servers=[replacement]), 503, "overlay_installed_reload_failed", ) requested = len(self.model.provider.requests) refused( self, lambda: self.editor.prompt( session, [{"type": "text", "text": "must not use stale tools"}] ), 409, "overlay_installed_reload_failed", ) self.assertEqual(len(self.model.provider.requests), requested) broken_prompt.unlink() self.editor.attach(session, servers=[replacement]) self.editor.prompt(session, [{"type": "text", "text": "use replacement tool"}]) self.app.idle(session) self.assertIn("replacement-editor-secret", self.model.results[-1]) self.assertNotIn(SECRET, self.model.results[-1]) @exclusive_class class AcpTraceSnapshotsTest(unittest.TestCase): def test_history_preserves_snapshots_and_large_trace_reference(self): def script(request): if request["messages"][-1].get("role") == "user": return python( "from pathlib import Path\nPath('existing.txt').write_text('changed text')\nPath('new.txt').write_text('new text')\nPath('binary.txt').write_bytes(b'\\x00binary')\nPath('oversized.txt').write_text('x' * 140000)\nPath('large.txt').write_text('x' * 100000)\nPath('large2.txt').write_text('y' * 100000)\nPath('large3.txt').write_text('z' * 100000)" ) return text("done") provider = Provider(script) self.addCleanup(provider.close) with Albedo(provider) as app: (app.workspace / "existing.txt").write_text("original text") editor = AcpClient(app) session, _ = editor.create() before = app.stream_page(session) editor.prompt(session, [{"type": "text", "text": "write files"}]) app.idle(session) live = next( event["data"] for event in app.stream_page(session, before)["events"] if event["type"] == "tool" ) self.assertTrue(live["content_complete"]) self.assertIsNotNone(live["trace"]) self.assertIsNone(live["reference"]) tool = next( e for e in app.history(session)["items"] if e["kind"] == "tool_result" ) self.assertEqual(tool["tool"]["status"], "completed") self.assertEqual(tool["tool"]["progress_call_id"], live["progress_call_id"]) reference = next( p["reference"] for p in tool["content"] if p["kind"] == "reference" and p["reference"]["field"] == "trace" ) pieces = [] url = reference["url"] while url: with app.api(url) as response: page = json.load(response) pieces.extend( part["text"] for part in page["parts"] if part["field"] == "trace" ) url = ( reference["url"] + "?next=" + page["next"] if page["next"] else None ) raw = "".join(pieces) self.assertEqual(len(raw.encode()), reference["bytes"]) trace = json.loads(raw) change = next(c for c in trace["changes"] if c["path"].endswith("new.txt")) self.assertIsNone(change["old_text"]) self.assertEqual(change["new_text"], "new text") changes = {Path(c["path"]).name: c for c in trace["changes"]} self.assertEqual(changes["existing.txt"]["old_text"], "original text") self.assertEqual(changes["existing.txt"]["new_text"], "changed text") for name in ("binary.txt", "oversized.txt"): self.assertEqual(changes[name]["kind"], "unavailable") self.assertTrue(changes[name]["reason"]) # Snapshots stop once the 256 KiB budget is spent. total = sum( len((c.get("old_text") or "").encode()) + len(c.get("new_text", "").encode()) for c in changes.values() ) self.assertLessEqual(total, 256 * 1024) # Retained transcript traces take precedence over the live journal. # Seed the pre-snapshot wire shape as it appeared in older sessions. result = next( p["value"] for p in tool["content"] if p.get("field") == "result" ) cell_id = json.loads(result)["cell_id"] legacy = { "activities": [], "changes": [ { "path": "old.txt", "kind": "diff", "diff": "-old\n+new\n", "added": 1, "removed": 1, } ], "truncated": False, } with sqlite3.connect(app.home / "albedo.sqlite", timeout=10) as db: db.execute( "INSERT INTO transcript_traces(session, cell_id, payload) VALUES (?, ?, ?)", (session, cell_id, json.dumps(legacy)), ) row = next( e for e in app.history(session)["items"] if e["kind"] == "tool_result" ) self.assertEqual( next(p["trace"] for p in row["content"] if p["kind"] == "trace"), legacy ) if __name__ == "__main__": unittest.main()