Files
ai-agent/backend/test_turn_end.py
gabrielvidalandClaude Opus 5.5 937c8a835e fix(parse): a resumed agent's notification closes its reopened call
A SendMessage-resumed agent's <task-notification> names the SendMessage's
tool-use id, not the Agent call's, so the call it reopened never closed.
Notifications now close a call by the tool-use id they name or by the
agentId in their task id.

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

250 lines
12 KiB
Python

"""A conversation ends when its turn does — no DONE needed.
The parser's ``turnEnded``: the transcript ends on a turn-end record (Claude
Code's ``stop_hook_summary`` / ``turn_duration``, a harness mirror's
``turn_end``) or on an API error the CLI gave up on, with no turn activity
after it; ``_resolve_state`` reads that as ``finished``. Not while a
background agent it launched still works: the run waits on it."""
import datetime
import json
import conversations as c
from conversations.cards import _resolve_state
SID = "11111111-2222-3333-4444-555555555555"
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 user(text, ts="2026-11-02T10:00:00.000Z", **kw):
return {"type": "user", "sessionId": SID, "timestamp": ts,
"message": {"role": "user", "content": text}, **kw}
def assistant(text="ok", ts="2026-11-02T10:00:05.000Z", mid="m1", **kw):
return {"type": "assistant", "sessionId": SID, "timestamp": ts,
"message": {"role": "assistant", "id": mid, "model": "claude-opus-5-5",
"content": [{"type": "text", "text": text}],
"usage": {"input_tokens": 1, "output_tokens": 1}}, **kw}
def system(subtype, ts="2026-11-02T10:00:06.000Z", **kw):
return {"type": "system", "subtype": subtype, "sessionId": SID,
"timestamp": ts, **kw}
# What the CLI writes after a turn's end — bookkeeping, not activity.
TAIL = [{"type": "last-prompt", "lastPrompt": "hi", "sessionId": SID},
{"type": "ai-title", "aiTitle": "Hi", "sessionId": SID},
{"type": "atis-latch", "sessionId": SID},
{"type": "cost-state", "sessionId": SID, "totalCostUSD": 0.01}]
def parse(tmp_path, recs) -> dict:
p = tmp_path / f"{SID}.jsonl"
p.write_text("".join(json.dumps(r) + "\n" for r in recs))
return c.parse_conversation(p)
def test_headless_run_ends_on_its_stop_hook_summary(tmp_path):
recs = [user("hi"), assistant(), {"type": "attachment", "sessionId": SID,
"attachment": {"type": "x"}},
system("stop_hook_summary", hookCount=1, hookErrors=[],
preventedContinuation=False), *TAIL]
assert parse(tmp_path, recs)["turnEnded"] is True
def test_no_turn_end_record_means_still_in_the_turn(tmp_path):
assert parse(tmp_path, [user("hi"), assistant(), *TAIL])["turnEnded"] is False
def test_a_blocking_stop_hook_does_not_end_the_turn(tmp_path):
held = [user("hi"), assistant(),
user("Stop hook feedback:\nStop guard (headless run): the turn was held 56 s",
isMeta=True),
system("stop_hook_summary", hookErrors=["Stop guard …"])]
assert parse(tmp_path, held)["turnEnded"] is False
# …the model carries on, and its real end counts.
later = [*held, {"type": "api-request", "sessionId": SID,
"timestamp": "2026-11-02T10:00:07.000Z"},
assistant("done", ts="2026-11-02T10:00:09.000Z", mid="m2"),
system("stop_hook_summary", ts="2026-11-02T10:00:10.000Z",
hookErrors=[]), *TAIL]
assert parse(tmp_path, later)["turnEnded"] is True
def test_interactive_session_ends_on_turn_duration(tmp_path):
recs = [user("hi"), assistant(), system("turn_duration", durationMs=1862),
system("away_summary", content="recap"), *TAIL]
assert parse(tmp_path, recs)["turnEnded"] is True
def test_a_new_prompt_reopens_the_turn(tmp_path):
recs = [user("hi"), assistant(), system("turn_duration"),
{"type": "queue-operation", "operation": "enqueue", "sessionId": SID,
"timestamp": "2026-11-02T10:01:00.000Z", "content": "next"}]
assert parse(tmp_path, recs)["turnEnded"] is False
recs = [user("hi"), assistant(), system("stop_hook_summary"),
user("and now?", ts="2026-11-02T10:02:00.000Z")]
assert parse(tmp_path, recs)["turnEnded"] is False
def test_harness_mirrors_turn_end(tmp_path):
recs = [user("hi"), assistant(), system("turn_end", entrypoint="opencode")]
assert parse(tmp_path, recs)["turnEnded"] is True
def test_an_api_error_the_cli_gave_up_on_ends_the_turn(tmp_path):
recs = [user("hi"), assistant("API Error: 529 overloaded", isApiErrorMessage=True),
*TAIL]
assert parse(tmp_path, recs)["turnEnded"] is True
# ── _resolve_state ──────────────────────────────────────────────────────────
def test_an_ended_turn_is_finished_without_done():
s = {"endedAt": ago(5), "turnEnded": True}
assert _resolve_state(s, {}, None) == "finished"
assert _resolve_state(s, {"state": "running"}, None) == "finished"
def test_a_turn_in_flight_stays_on_recency():
assert _resolve_state({"endedAt": ago(5)}, {}, None) == "running"
assert _resolve_state({"endedAt": ago(5000)}, {}, None) == "finished"
def test_a_parked_run_is_paused_not_finished():
s = {"endedAt": ago(5), "turnEnded": True, "waitingForTrigger": True}
assert _resolve_state(s, {}, None) == "paused"
def test_interrupt_and_explicit_states_still_win():
s = {"endedAt": ago(5), "turnEnded": True, "interruptedByUser": True}
assert _resolve_state(s, {}, None) == "interrupted"
assert _resolve_state({"endedAt": ago(5), "turnEnded": True},
{"state": "review"}, None) == "review"
def test_running_subagents_outrank_the_ended_turn():
s = {"endedAt": ago(60), "turnEnded": True,
"runningAgents": [{"id": "toolu_1"}]}
assert _resolve_state(s, {}, None, subagents_at=ago(5)) == "running"
# ── background agents ───────────────────────────────────────────────────────
def agent_call(tid, background=True, ts="2026-11-02T10:00:01.000Z"):
return {"type": "assistant", "sessionId": SID, "timestamp": ts,
"message": {"role": "assistant", "id": f"m-{tid}", "model": "claude-opus-5-5",
"content": [{"type": "tool_use", "id": tid, "name": "Agent",
"input": {"description": "dig", "prompt": "dig",
"subagent_type": "general-purpose",
"run_in_background": background}}],
"usage": {"input_tokens": 1, "output_tokens": 1}}}
def send_message(tid, to, ts="2026-11-02T10:05:00.000Z"):
return {"type": "assistant", "sessionId": SID, "timestamp": ts,
"message": {"role": "assistant", "id": f"m-{tid}", "model": "claude-opus-5-5",
"content": [{"type": "tool_use", "id": tid, "name": "SendMessage",
"input": {"to": to, "summary": "more",
"message": "one more form"}}],
"usage": {"input_tokens": 1, "output_tokens": 1}}}
def tool_result(tid, text, ts="2026-11-02T10:00:02.000Z"):
return {"type": "user", "sessionId": SID, "timestamp": ts,
"message": {"role": "user", "content": [
{"type": "tool_result", "tool_use_id": tid,
"content": [{"type": "text", "text": text}]}]}}
def notification(tid, ts="2026-11-02T10:04:00.000Z"):
# The task id is the agentId.
return user(f"<task-notification>\n<task-id>a1</task-id>\n<tool-use-id>{tid}"
f"</tool-use-id>\n<status>completed</status>\n</task-notification>",
ts=ts)
LAUNCHED = ("Async agent launched successfully.\nagentId: a1 (internal ID - do not "
"mention to user. Use SendMessage with to: 'a1' to continue this agent.)")
REPORT = ("[Subagent hand-back] The final report.\nagentId: a2 (use SendMessage with "
"to: 'a2', summary: '<5-10 word recap>' to continue this agent)\n"
"<usage>subagent_tokens: 1</usage>")
RESUMED = ('{"success":true,"message":"Resuming agent a1","resumedAgentId":"a1",'
'"pin":{"id":"a1","name":"a1","ref":"x"}}')
QUEUED = ('{"success":true,"message":"Message queued for delivery to a1 at its next '
'tool round.","pin":{"id":"a1","name":"a1","ref":"x"}}')
WAITING = [user("fan out"), agent_call("toolu_A"), tool_result("toolu_A", LAUNCHED),
assistant("I'll wait for it.", ts="2026-11-02T10:00:03.000Z", mid="m2"),
system("stop_hook_summary", ts="2026-11-02T10:00:04.000Z"), *TAIL]
def open_calls(s):
return [(a["toolUseId"], a.get("background")) for a in s["runningAgents"]]
def test_a_turn_waiting_on_a_background_agent_has_not_ended(tmp_path):
s = parse(tmp_path, WAITING)
assert s["turnEnded"] is False
assert open_calls(s) == [("toolu_A", True)]
# Its notification starts the next turn, and that one's end counts.
s = parse(tmp_path, [*WAITING, notification("toolu_A"),
assistant("done", ts="2026-11-02T10:04:05.000Z", mid="m3"),
system("stop_hook_summary", ts="2026-11-02T10:04:06.000Z")])
assert s["turnEnded"] is True and s["runningAgents"] == []
def test_a_blocking_agents_report_closes_its_call(tmp_path):
# Its report ends on an "agentId:" line too — not a background launch.
s = parse(tmp_path, [user("dig"), agent_call("toolu_B", background=False),
tool_result("toolu_B", REPORT), assistant("found it", mid="m2"),
system("stop_hook_summary")])
assert s["runningAgents"] == [] and s["turnEnded"] is True
def test_send_message_resuming_a_stopped_agent_reopens_its_call(tmp_path):
done = [*WAITING, notification("toolu_A")]
resumed = [*done, send_message("toolu_S", "a1"),
tool_result("toolu_S", RESUMED, ts="2026-11-02T10:05:01.000Z"),
assistant("Asked it again.", ts="2026-11-02T10:05:02.000Z", mid="m4"),
system("stop_hook_summary", ts="2026-11-02T10:05:03.000Z")]
s = parse(tmp_path, resumed)
assert open_calls(s) == [("toolu_A", True)]
assert s["turnEnded"] is False
# …until it notifies again — naming the SendMessage, not the Agent call.
s = parse(tmp_path, [*resumed, notification("toolu_S", ts="2026-11-02T10:09:00.000Z")])
assert s["runningAgents"] == []
def test_a_message_only_queued_reopens_nothing(tmp_path):
s = parse(tmp_path, [*WAITING, notification("toolu_A"),
send_message("toolu_S", "a1"),
tool_result("toolu_S", QUEUED, ts="2026-11-02T10:05:01.000Z")])
assert s["runningAgents"] == []
def test_a_live_run_waiting_on_a_quiet_agent_is_running():
s = {"endedAt": ago(3000), "runningAgents": [{"toolUseId": "A", "background": True}]}
assert _resolve_state(s, {}, None, None, run_alive=True) == "running"
# A terminal session (no process to go by) only has the recency window.
assert _resolve_state(s, {}, None, None, run_alive=False) == "finished"
# A blocking call left open (the run died mid-agent) isn't waited on.
s = {**s, "runningAgents": [{"toolUseId": "A"}]}
assert _resolve_state(s, {}, None, None, run_alive=True) == "finished"
def test_live_runs_registry(monkeypatch):
from core import liveruns
liveruns.update("w1", {"s1"})
assert liveruns.alive("s1") and not liveruns.alive("s2") and not liveruns.alive(None)
# A runner not heard from lately knows nothing.
now = liveruns.time.monotonic()
monkeypatch.setattr(liveruns.time, "monotonic", lambda: now + liveruns.STALE_S + 1)
assert not liveruns.alive("s1")
monkeypatch.undo()
liveruns.drop("w1")
assert not liveruns.alive("s1")