Files
ai-agent/backend/test_subagent_running.py
gabrielvidalandClaude Opus 5.5 de07e009f1 feat(conversations): UUIDv7 conversation ids — the transcript path stays inside
A conversation (and every subagent) was addressed by its transcript's path
under the archive, which put the owner's home dir, project and branch names in
every URL a guest saw. Now each archived transcript has a UUIDv7:

- timestamp = the transcript's first timestamped record (ids sort by start,
  past conversations included); the other 74 bits = sha256(rel path), so a
  lost registry re-derives the same ids
- registry: conv_uids table in ai-agent.db (conversations/ids.py), bound at
  startup; tree._conv_id is the one door responses go through
- legacy path ids and bare session ids still resolve (_public_id) — old links,
  deploy.sh, the mail trigger, worker terminals
- access.session_of / catalog._meta_key resolve a uid before deriving the sid;
  TRANSCRIPTS_DIR / <id> joins replaced by ids.path_of
- SSE transcript events carry uids + a roots map (subagent → root); the guest
  filter trims it
- thread detail: owner-only `transcript` (the archived copy's host path)
- id_migration: at every start, mint missing uids and swap every known path id
  in /data/*.json for its uid (raw text, .bak-uids-<stamp> copies), re-key
  short titles + their side-call refs; cross-process safe for blue-green

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

262 lines
13 KiB
Python

"""A conversation counts as running while one of its subagents is: the main
thread going quiet (an orchestrator waiting on background agents, a blocking
Task) must not read as finished — and must again once the agents are done or
have gone quiet for the recency window.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
import datetime
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",
"NEW_PROJECTS_PATH": TMP / "np.json", "PROJECTS_DIR": TMP / "projects",
"INTERNAL_API_TOKEN": "tok", "SIDECAR_TOKEN": "",
"PI_TRANSCRIPTS_DIR": "", "RUNNING_WINDOW_SECS": "600"}.items():
os.environ[k] = str(v)
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
from conversations import ids # noqa: E402
from conversations.cards import _resolve_state # noqa: E402
from core import liveruns # noqa: E402
DEPS = main.app.state.ai
PROJ = "-home-x"
TU = "toolu_agent1"
def ago(secs: float) -> str:
t = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(seconds=secs)
return t.isoformat(timespec="milliseconds").replace("+00:00", "Z")
def _write(rel: str, records: list[dict]) -> None:
p = TMP / "arch" / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("\n".join(json.dumps(o) for o in records) + "\n")
def conversation(sid: str, main_tail: list[tuple[float, object]] | None = None,
sub_last: float = 5, launched: float = 1800,
turn_end: bool = False) -> str:
"""A root transcript that launched one background agent ``launched`` s ago
and then ended its turn, plus that agent's sidechain, last written
``sub_last`` s ago. ``main_tail`` appends ``(secs ago, user content)``
records to the main thread; ``turn_end`` closes the turn with the CLI's
``stop_hook_summary``. Returns the conversation id."""
base = {"sessionId": sid}
recs = [
{**base, "type": "user", "uuid": "u1", "timestamp": ago(launched + 5),
"message": {"role": "user", "content": "fan out"}},
{**base, "type": "assistant", "uuid": "a1", "timestamp": ago(launched),
"message": {"role": "assistant", "id": "m1", "model": "claude-opus-5-5",
"content": [{"type": "tool_use", "id": TU, "name": "Agent",
"input": {"description": "dig", "prompt": "dig",
"subagent_type": "general-purpose",
"run_in_background": True}}]}},
{**base, "type": "user", "uuid": "u2", "timestamp": ago(launched),
"message": {"role": "user", "content": [
{"type": "tool_result", "tool_use_id": TU,
"content": "Async agent launched successfully.\nagentId: a1"}]}},
{**base, "type": "assistant", "uuid": "a2", "timestamp": ago(launched - 1),
"message": {"role": "assistant", "id": "m2", "model": "claude-opus-5-5",
"content": [{"type": "text", "text": "I'll wait for it."}]}},
]
if turn_end:
recs.append({**base, "type": "system", "subtype": "stop_hook_summary",
"timestamp": ago(launched - 2)})
for i, (secs, content) in enumerate(main_tail or []):
recs.append({**base, "type": "user", "uuid": f"t{i}", "timestamp": ago(secs),
"message": {"role": "user", "content": content}})
_write(f"{PROJ}/{sid}.jsonl", recs)
side = {**base, "isSidechain": True, "agentId": "a1"}
_write(f"{PROJ}/{sid}/subagents/agent-a1.jsonl", [
{**side, "type": "user", "uuid": "s1", "timestamp": ago(launched),
"message": {"role": "user", "content": "dig"}},
{**side, "type": "assistant", "uuid": "s2", "timestamp": ago(sub_last),
"message": {"role": "assistant", "id": "m3", "model": "claude-opus-5-5",
"content": [{"type": "text", "text": "still digging"}]}},
])
(TMP / "arch" / PROJ / sid / "subagents" / "agent-a1.meta.json").write_text(
json.dumps({"agentType": "general-purpose", "description": "dig",
"toolUseId": TU, "spawnDepth": 1}))
DEPS.indexer.scan_transcripts()
return f"{PROJ}/{sid}.jsonl"
def notification(tool_use_id: str) -> str:
return (f"<task-notification>\n<task-id>x</task-id>\n<tool-use-id>{tool_use_id}"
f"</tool-use-id>\n<status>completed</status>\n</task-notification>")
class SubagentKeepsConversationRunning(unittest.TestCase):
def setUp(self):
self.c = TestClient(main.app, headers={"x-internal-auth": "tok"})
def states(self, cid: str, sid: str) -> dict:
card = self.c.get("/api/conversations", params={"sessions": sid}).json()
[card] = card["conversations"]
summary = self.c.get("/api/conversation-summary", params={"id": cid}).json()
detail = self.c.get("/api/conversation", params={"id": cid}).json()
[sub] = [s for s in self.c.get("/api/subagents").json()["subagents"]
if s["rootId"] == ids.canonical(cid)]
sub_page = self.c.get("/api/conversation", params={
"id": f"{PROJ}/{sid}/subagents/agent-a1.jsonl"}).json()
return {"card": card["meta"]["state"], "cardAgents": len(card["runningAgents"]),
"summary": summary["meta"]["state"],
"detail": detail["meta"]["state"],
"detailAgents": len(detail["runningAgents"]),
"subRef": [s["state"] for s in detail.get("subagents") or []],
"subagents": sub["state"], "subPage": sub_page["meta"]["state"]}
def assertEverywhere(self, got: dict, state: str) -> None:
for k in ("card", "summary", "detail", "subagents", "subPage"):
self.assertEqual(got[k], state, f"{k}: {got}")
self.assertEqual(got["subRef"], [state], got)
def test_main_idle_with_a_live_subagent_is_running(self):
sid = "aaaaaaaa-0000-4000-8000-000000000001"
got = self.states(conversation(sid), sid)
self.assertEverywhere(got, "running")
self.assertEqual((got["cardAgents"], got["detailAgents"]), (1, 1))
def test_a_subagent_gone_quiet_lets_it_finish(self):
# Its call is still open (it died without a result), but nothing has
# written for longer than the recency window.
sid = "aaaaaaaa-0000-4000-8000-000000000002"
got = self.states(conversation(sid, sub_last=660), sid)
self.assertEverywhere(got, "finished")
self.assertEqual((got["cardAgents"], got["detailAgents"]), (0, 0))
def test_every_subagent_done_is_not_running(self):
# The agent's <task-notification> closed its call long ago; a stray
# late write under it doesn't revive the conversation.
sid = "aaaaaaaa-0000-4000-8000-000000000003"
cid = conversation(sid, main_tail=[(1700, notification(TU))])
self.assertEverywhere(self.states(cid, sid), "finished")
def test_agents_writing_after_an_interrupt_keep_it_running(self):
sid = "aaaaaaaa-0000-4000-8000-000000000004"
cid = conversation(sid, main_tail=[(900, "[Request interrupted by user]")])
self.assertEqual(self.states(cid, sid)["card"], "running")
def test_a_turn_ended_on_a_quiet_agent_is_still_running(self):
# The main thread's Stop hooks ran right after the launch, and the
# agent has been inside one long command since — nothing is newer
# than the turn's end, yet the run waits on the agent.
sid = "aaaaaaaa-0000-4000-8000-000000000006"
cid = conversation(sid, launched=60, sub_last=59, turn_end=True)
self.assertEverywhere(self.states(cid, sid), "running")
def test_a_live_run_keeps_its_quiet_agent_running(self):
# Quiet for longer than the recency window: only the run's process
# being alive says the agent still works.
sid = "aaaaaaaa-0000-4000-8000-000000000007"
cid = conversation(sid, sub_last=1500, turn_end=True)
self.assertEverywhere(self.states(cid, sid), "finished")
liveruns.update("w-test", {sid})
try:
self.assertEverywhere(self.states(cid, sid), "running")
finally:
liveruns.drop("w-test")
self.assertEverywhere(self.states(cid, sid), "finished")
def test_agents_that_stopped_with_the_interrupt_dont(self):
sid = "aaaaaaaa-0000-4000-8000-000000000005"
cid = conversation(sid, sub_last=120,
main_tail=[(100, "[Request interrupted by user]")])
self.assertEqual(self.states(cid, sid)["card"], "interrupted")
class ResolveState(unittest.TestCase):
"""The rule itself, on the stamps the transcript can't show."""
summary = {"endedAt": ago(1800), "runningAgents": [{"toolUseId": TU}]}
def test_recent_subagent_outranks_the_quiet_main_thread(self):
self.assertEqual(_resolve_state(self.summary, {}, None, ago(5)), "running")
self.assertEqual(_resolve_state(self.summary, {"state": "running"}, None,
ago(5)), "running")
self.assertEqual(_resolve_state(self.summary, {}, None, None), "finished")
def test_no_open_call_means_no_override(self):
s = {**self.summary, "runningAgents": []}
self.assertEqual(_resolve_state(s, {}, None, ago(5)), "finished")
def test_agents_die_with_their_run(self):
# The sidecar saw the process exit after the agent's last write.
m = {"state": "finished", "exitedAt": ago(60)}
self.assertEqual(_resolve_state(self.summary, m, None, ago(90)), "finished")
# …but writes after the exit mean the session lives on elsewhere.
self.assertEqual(_resolve_state(self.summary, m, None, ago(5)), "running")
def test_done_and_notified_main_still_waits_on_its_agents(self):
s = {**self.summary, "doneMarker": True}
self.assertEqual(_resolve_state(s, {}, ago(1800), ago(5)), "running")
def test_other_explicit_states_are_honoured(self):
self.assertEqual(_resolve_state(self.summary, {"state": "review"}, None,
ago(5)), "review")
self.assertEqual(_resolve_state(self.summary, {"state": "interrupted"}, None,
ago(5)), "interrupted")
class ClosingPush(unittest.TestCase):
"""`notify --final` stamps "finished" before Claude writes its DONE: the
run reads running until that sign-off lands, or its process exits."""
pushed = {"state": "finished"} # the closing push's stamp, no exit yet
def test_running_until_the_sign_off_lands(self):
live = {"endedAt": ago(5)}
self.assertEqual(_resolve_state(live, self.pushed, ago(4)), "running")
for marker in ("doneMarker", "completedMarker"):
self.assertEqual(_resolve_state({**live, marker: True}, self.pushed,
ago(4)), "finished")
def test_finished_once_the_process_exits(self):
m = {**self.pushed, "exitedAt": ago(2)}
self.assertEqual(_resolve_state({"endedAt": ago(5)}, m, ago(4)), "finished")
def test_finished_once_quiet_past_the_window(self):
self.assertEqual(_resolve_state({"endedAt": ago(900)}, self.pushed,
ago(901)), "finished")
def test_a_previous_runs_exit_doesnt_count(self):
# Resumed since that exit: the old stamp says nothing about this run.
m = {**self.pushed, "exitedAt": ago(1800)}
self.assertEqual(_resolve_state({"endedAt": ago(5)}, m, ago(4)), "running")
def test_the_exit_watcher_stamps_the_exit_on_a_pushed_run(self):
from runs.sidecar_client import _mark_run_exited
sid = "aaaaaaaa-0000-4000-8000-0000000000c1"
DEPS.meta_store.update(sid, dict(self.pushed))
_mark_run_exited(DEPS, sid)
m = DEPS.meta_store.get(sid)
self.assertEqual(m.get("state"), "finished")
self.assertTrue(m.get("exitedAt"))
# …but leaves a state an endpoint set alone.
sid = "aaaaaaaa-0000-4000-8000-0000000000c2"
DEPS.meta_store.update(sid, {"state": "interrupted"})
_mark_run_exited(DEPS, sid)
self.assertIsNone(DEPS.meta_store.get(sid).get("exitedAt"))
if __name__ == "__main__":
unittest.main()