Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(voice): answer "what is running, what is done" in one call and watch hand-started agents (#629)
Ruben Lütkef77e32ff8c62
diff --git a/docs/igentic-workspaces.md b/docs/igentic-workspaces.mdindex 5acb0fb5a4..9dcdb30413 100644--- a/docs/igentic-workspaces.md+++ b/docs/igentic-workspaces.md@@ -58,6 +58,14 @@ worker tools and does not grant Society agents any new capability.exact session.4. `context` reads recorded results from the addressed session. A deliveryreceipt never asserts that the coding task has completed.+5. `status` answers "what is running, what finished, who needs me" in one call:+ one compact row per open coding session across every workspace (state, how+ long, its job) plus each workspace folder's git state (branch, ahead/behind,+ uncommitted files, linked worktree). It reads no transcript.+6. `watch` reports back to the conversation when a session the user started by+ hand ends its current job. It needs a CLI that keeps a local record, ends+ when a new prompt is typed into that session, and reports a finished turn,+ never verified work. A task sent through `send` is followed without it.For example, a request to fix an installer in a named project can address abackground workspace while the user continues viewing another project. Thediff --git a/jarvis/agentic_ide/followthrough.py b/jarvis/agentic_ide/followthrough.pyindex 4f9c80d0c1..e9956dfef3 100644--- a/jarvis/agentic_ide/followthrough.py+++ b/jarvis/agentic_ide/followthrough.py@@ -1,4 +1,4 @@-"""Track only Jarvis-requested pane jobs and return fresh, attributed evidence."""+"""Track pane jobs Jarvis sent or was asked to watch, and return fresh, attributed evidence."""from __future__ import annotations@@ -28,6 +28,8 @@ class PendingResult:reply_session_id: str = ""submitted_at: float | None = Noneprepared_at: float = 0.0+ #: The job was typed by someone else and only its end is awaited (``watch``).+ watched: bool = Falsedef _events(term: Any) -> list:@@ -77,6 +79,8 @@ def _completion_report(events: list, pending: PendingResult) -> str:if start is None:return ""user = events[start]+ if pending.watched:+ return _watched_report(events[start + 1:], pending)expected = agent_transcript._clip(agent_transcript._spoken(pending.prompt))if (int(user.get("ts_ms") or 0)@@ -101,6 +105,62 @@ def _completion_report(events: list, pending: PendingResult) -> str:)+def _watched_report(own: list, pending: PendingResult) -> str:+ """The final answer of a turn that ended after its watch began.++ A watched job was not typed by Jarvis, so there is no prompt to match. The+ CLI's own end marker, recorded after the watch started, identifies it.+ """+ if not own or own[-1]["kind"] != "turn_finished":+ return ""+ finish = own[-1]["payload"]+ if finish.get("status") != "done" or not finish.get("turn_id"):+ return ""+ if int(own[-1].get("ts_ms") or 0) < int(pending.prepared_at * 1000):+ return ""+ return next(+ (+ str(event["payload"].get("text") or "").strip()+ for event in reversed(own)+ if event["kind"] == "assistant_text"+ and event["payload"].get("turn_id") == finish["turn_id"]+ ),+ "",+ )+++def can_report(term: Any) -> bool:+ """Whether this pane's CLI keeps a local record a completion can be read from."""+ return (+ not getattr(term, "computer_id", "")+ and term.resume is not None+ and agent_transcript.can_read(term.agent)+ )+++async def watch(term: Any, origin: dict[str, str]) -> PendingResult:+ """Await the end of the job this pane is already working on, whoever typed it.++ The pane's own later submission, a restart, or a brief sent through Jarvis+ replaces the watch, exactly as it replaces a tracked brief.+ """+ prepared_at = time.time()+ events = await asyncio.to_thread(_snapshot, term)+ job = " ".join(str(term.last_prompt or "").split())[:600]+ pending = PendingResult(+ request_id=uuid4().hex, prompt=str(term.last_prompt or ""),+ request=f"Report when {term.name} finishes its current job"+ + (f": {job}" if job else "."),+ language=origin.get("lang", ""), baseline=_fingerprint(events),+ generation=term.process_generation,+ reply_session_id=origin.get("reply_session_id", ""),+ submitted_at=term.last_submit_at, prepared_at=prepared_at, watched=True,+ )+ term.delegation_result = pending+ term.delegation_probe_at = 0.0+ return pending++async def prepare(term: Any, prompt: str, request: str, origin: dict[str, str]) -> PendingResult:# The CLI can record the prompt before its input receipt is confirmed and# last_submit_at is stamped. Freshness starts before that write, not after.diff --git a/jarvis/agentic_ide/git_ops.py b/jarvis/agentic_ide/git_ops.pyindex 9ba3d7f705..0cf5ec7163 100644--- a/jarvis/agentic_ide/git_ops.py+++ b/jarvis/agentic_ide/git_ops.py@@ -45,6 +45,8 @@ WORKTREE_DIR = ".worktrees"BRANCH_PREFIX = "agent/"_GIT_TIMEOUT_S = 60+# A spoken status answer does not wait a minute for one slow repository.+_BRIEF_TIMEOUT_S = 10# Network operations (push, fetch, PR creation) get longer: a first push of a# big branch over a slow link legitimately takes a while._NETWORK_TIMEOUT_S = 180@@ -429,6 +431,42 @@ def inspect(folder: str | Path) -> RepoInfo:return info+def brief(folder: str | Path) -> dict[str, Any] | None:+ """Branch, sync state and change count of ``folder``; None outside a repository.++ The status board asks this for every open workspace at once, so it stays at+ the calls a spoken answer needs and leaves branches, remotes and worktree+ lists to :func:`inspect`.+ """+ path = Path(folder).expanduser()+ root = repo_root(path)+ if root is None:+ return None+ info = RepoInfo(folder=str(path), is_repo=True, root=str(root))+ status = _run(+ ["status", "--porcelain=v2", "--branch", "--untracked-files=normal"],+ root,+ timeout=_BRIEF_TIMEOUT_S,+ )+ if status.returncode != 0:+ return None+ _parse_status(status.stdout, info)+ changed = sum(+ 1 for line in status.stdout.splitlines() if line.startswith(("1 ", "2 ", "u ", "? "))+ )+ return {+ "branch": info.branch,+ "detached": info.detached,+ "upstream": info.upstream,+ "ahead": info.ahead,+ "behind": info.behind,+ "changed_files": changed,+ "conflicted": info.conflicted,+ # A linked worktree keeps a ``.git`` FILE pointing at the shared repository.+ "worktree": (root / ".git").is_file(),+ }++# ------------------------------------------------------------------ namingdiff --git a/jarvis/agentic_ide/orchestration.py b/jarvis/agentic_ide/orchestration.pyindex 996c27054d..bc0146063b 100644--- a/jarvis/agentic_ide/orchestration.py+++ b/jarvis/agentic_ide/orchestration.py@@ -62,6 +62,8 @@ _PANE_ACTIONS = frozenset({"observe", "respond", "keys", "interrupt", "restart",# types nothing; restart brings the same pane back on its own conversation._STOPPED = frozenset({"exited", "error"})_WORKSPACE_ACTIONS = frozenset({"open_workspace", "restore", "show"})+# How much of an agent's last prompt the status board repeats.+_STATUS_JOB_CHARS = 200# How many times one request may be re-attempted after receipts proving that# nothing was typed (the pane was busy, closed, or not a coding pane)._REFUSED_ATTEMPTS = 20@@ -237,6 +239,20 @@ def _assignment(args: dict) -> str:return json.dumps([str(args.get("prompt") or "").strip(), args.get("image_refs", [])])+def _git_brief(folder: str) -> dict[str, Any] | None:+ """A workspace folder's git state for the status board; None when there is none."""+ from . import git_ops++ try:+ return git_ops.brief(folder)+ except (git_ops.GitError, OSError) as exc:+ from loguru import logger++ # The board still answers for the agents; only this folder's git row is missing.+ logger.debug("Workspace status: no git state for {}: {}", folder, exc)+ return None++class WorkspaceOrchestrator:"""One graph for Live discovery, explicit resolution and scoped delivery."""@@ -315,16 +331,20 @@ class WorkspaceOrchestrator:),}- def inspect(self, args: dict[str, Any]) -> dict[str, Any]:- """Read current task and transcript evidence only for the requested scope."""+ def _scoped(self, args: dict[str, Any]) -> dict[str, Any]:+ """The graph narrowed to the workspace or project a request names.++ A reference that matches nothing comes back as the reply saying so,+ which carries no ``projects``.+ """graph = self.graph()if args.get("workspace") or args.get("workspace_id"):picked = self._workspace(args, graph, "")if isinstance(picked, dict):return pickedproject, workspace = picked- graph = {**graph, "projects": [{**project, "workspaces": [workspace]}]}- elif args.get("project") or args.get("project_id"):+ return {**graph, "projects": [{**project, "workspaces": [workspace]}]}+ if args.get("project") or args.get("project_id"):reference = str(args.get("project_id") or args["project"])projects = ([p for p in graph["projects"] if p["id"] == reference]@@ -334,7 +354,136 @@ class WorkspaceOrchestrator:)if not projects:return self._choice("project", [], graph, unmatched=reference)- graph = {**graph, "projects": projects}+ return {**graph, "projects": projects}+ return graph++ async def status(self, args: dict[str, Any]) -> dict[str, Any]:+ """One compact row per open coding agent, with each workspace's git state.++ The answer to "what is running, what is done, who needs me": no+ transcript is read, so it stays cheap across every workspace.+ """+ graph = await asyncio.to_thread(self._scoped, args)+ if "projects" not in graph:+ return graph+ now = time.time()+ counts: dict[str, int] = {}+ needs_you: list[str] = []+ rows: list[dict[str, Any]] = []+ closed = 0+ for project in graph["projects"]:+ for workspace in project["workspaces"]:+ owner = self.registry.get(workspace["id"])+ if owner is None:+ closed += 1+ continue+ watched = {+ "pane:" + term.history_id+ for term in owner.terminals+ if getattr(getattr(term, "delegation_result", None), "watched", False)+ }+ agents = []+ for agent in workspace["agents"]:+ state = agent["availability"]+ counts[state] = counts.get(state, 0) + 1+ if state in {"needs_input", "needs_attention"}:+ needs_you.append(f"{agent['name']} ({workspace['name']})")+ since = float(agent.get("activity_since") or 0)+ agents.append({+ "terminal_id": agent["id"],+ "name": agent["name"],+ "cli": agent["agent"],+ "state": state,+ **({"for_seconds": round(max(0.0, now - since))} if since else {}),+ **({"title": agent["title"]} if agent.get("title") else {}),+ **({"job": " ".join(agent["last_prompt"].split())[:_STATUS_JOB_CHARS]}+ if agent.get("last_prompt") else {}),+ **({"watched": True} if agent["id"] in watched else {}),+ })+ rows.append({+ "project_id": project["id"],+ "project": project["name"],+ "workspace_id": workspace["id"],+ "workspace": workspace["name"],+ "folder": workspace["folder"],+ "visible": bool(workspace.get("active")),+ "agents": agents,+ })+ states = await asyncio.gather(+ *(asyncio.to_thread(_git_brief, row["folder"]) for row in rows)+ )+ for row, git in zip(rows, states, strict=True):+ row.pop("folder")+ if git is not None:+ row["git"] = git+ return {+ "status": "ok",+ "counts": counts,+ "needs_you": needs_you,+ "workspaces": rows,+ **({"closed_workspaces": closed} if closed else {}),+ "note": (+ "busy = in a turn; needs_input = showing a question; idle = its conversation "+ "is waiting; empty = unused; needs_attention = stopped, failed or exited. "+ "A finished turn says nothing about whether the work is correct. observe one "+ "agent for what it wrote; git counts uncommitted files per workspace folder."+ ),+ }++ async def watch(self, args: dict[str, Any]) -> dict[str, Any]:+ """Report back when the named agent ends the job it is working on now.++ For work the user started by hand: a brief sent through this+ orchestrator is already followed without asking.+ """+ from jarvis.core.delegation import current_delegation_origin++ from . import followthrough++ picked = await self._pane(args)+ if isinstance(picked, dict):+ return picked+ _owner, term, target = picked+ state = snapshot(term)["availability"]+ reply = {"target": target, "agent": term.name, "state": state}+ tracked = getattr(term, "delegation_result", None)+ if tracked is not None and followthrough.current(term, tracked):+ return {+ **reply, "status": "watching", "already": True,+ "reason": "Its result is already on its way to this conversation when it stops.",+ }+ if state != "busy":+ return {+ **reply, "status": "not_running",+ "reason": "That agent is not in a turn, so there is nothing to wait for. "+ "Its state is above; observe it for what it wrote.",+ }+ origin = current_delegation_origin.get() or {}+ if origin.get("reply_surface") not in {"voice", "chat"}:+ return {+ **reply, "status": "unavailable",+ "reason": "No conversation to report back to; nothing is watched.",+ }+ if not followthrough.can_report(term):+ return {+ **reply, "status": "unavailable",+ "reason": "This agent's CLI keeps no local record its completion can be read "+ "from, so its end cannot be reported. Nothing is watched; use status "+ "to look again.",+ }+ await followthrough.watch(term, origin)+ return {+ **reply, "status": "watching",+ "reason": "Its result is handed to this conversation when it stops or asks. Tell "+ "the user it is being watched, never that it is done, and do not poll. A "+ "new prompt typed into that agent ends the watch.",+ }++ def inspect(self, args: dict[str, Any]) -> dict[str, Any]:+ """Read current task and transcript evidence only for the requested scope."""+ graph = self._scoped(args)+ if "projects" not in graph:+ return graphfor project in graph["projects"]:for workspace in project["workspaces"]:owner = self.registry.get(workspace["id"])@@ -1241,7 +1390,7 @@ class WorkspaceOrchestrator:created = {a["terminal_id"] for a in (creation or {}).get("agents", [])}to_created = action == "send" and str(args.get("terminal_id") or "") in createdif (args.get("_requires_new") or creation) and not to_created and action not in {- "inspect", "create", "open_workspace", "context", "observe",+ "inspect", "create", "open_workspace", "context", "observe", "status", "watch",}:# A NEW request cannot borrow an idle pane for its new task, but it# may also carry independent work for an agent the user NAMED@@ -1280,6 +1429,11 @@ class WorkspaceOrchestrator:return self.resolve(args, graph)if action == "create":return await self.create(args, trace_id=trace_id)+ if action in {"status", "watch"}:+ from . import task_state++ await task_state.refresh(self.registry)+ return await (self.status(args) if action == "status" else self.watch(args))if action in _PANE_ACTIONS:return await self.pane_action(args)if action in _WORKSPACE_ACTIONS:diff --git a/jarvis/brain/workspace_tool.py b/jarvis/brain/workspace_tool.pyindex e610a46066..856ce8a7e3 100644--- a/jarvis/brain/workspace_tool.py+++ b/jarvis/brain/workspace_tool.py@@ -41,6 +41,10 @@ def _point_at_jarvis_agent(args: dict, result: dict) -> dict:return {**result, "jarvis_agent": hint, "reason": f"{reason} {earlier}".strip()}+# Actions that only look. ``watch`` is not one: it arranges a later report.+_READS = frozenset({"status", "inspect", "resolve", "context", "observe"})++class WorkspaceOrchestrationTool:name = "workspace-orchestrate"# Handing a task to the user's own coding agent is Jarvis's job, not an@@ -71,6 +75,14 @@ class WorkspaceOrchestrationTool:"actions: run them when asked, without asking back. A send refused because the agent ""is not running (stopped: true) types nothing: when the user wants that agent to do ""the task, restart it and resend with the same request_id and prompt. "+ "status answers what is running, what finished and who needs the user, in one "+ "call: one row per open agent across every workspace (busy, needs_input, idle, "+ "empty, needs_attention; how long; its job) and each workspace's git state "+ "(branch, ahead/behind, uncommitted files, linked worktree). Use it for 'how far "+ "are they', 'is it done', 'which branch' instead of inspecting or observing each "+ "agent; pass workspace or project to narrow it. watch (agent call-sign or "+ "terminal_id) reports back to this conversation when an agent the USER started by "+ "hand ends its current job; a task you sent is already followed, never watch it. ""Inspect the current graph (pass workspace to scope it): each session includes ""availability, history, last user/assistant messages, recent tools and screen excerpts. ""Empty is unused; idle has an existing conversation; stopped/failed/unknown is not free. "@@ -114,6 +126,8 @@ class WorkspaceOrchestrationTool:"action": {"type": "string","enum": [+ "status",+ "watch","inspect","resolve","send",@@ -236,11 +250,10 @@ class WorkspaceOrchestrationTool:self.gateway = gatewaydef risk_tier_for_args(self, args: dict) -> str:- reads = {"inspect", "resolve", "context", "observe"}- return "safe" if args.get("action") in reads else "monitor"+ return "safe" if args.get("action") in _READS else "monitor"def read_only_for_args(self, args: dict) -> bool:- return args.get("action") in {"inspect", "resolve", "context", "observe"}+ return args.get("action") in _READSdef describe_args(self, args: dict) -> dict:return {diff --git a/jarvis/live/config.py b/jarvis/live/config.pyindex be96200bae..416ef5449b 100644--- a/jarvis/live/config.py+++ b/jarvis/live/config.py@@ -120,6 +120,13 @@ class LiveConfig(BaseModel):"A request for a NEW coding agent (or several: 'two Claude Code agents') is ""workspace-orchestrate create in the named or visible workspace, with cli, ""count and the task as prompt; never an existing agent and never spawn_worker. "+ "When the user asks how far the coding agents are, whether one is done, who "+ "is waiting for them, or which branch a workspace is on, call "+ "workspace-orchestrate status once: it covers every open agent and each "+ "workspace's git state. Say the takeaway in a sentence or two and name who "+ "needs the user; never read out lists, diffs or code. When the user wants to "+ "hear when an agent they started themselves is done, call watch for it; a "+ "task you sent is reported back on its own. "+ AGENT_BRIEF_RULE+ " "+ (COMPUTER_CONTROL_RULES if computer else "")diff --git a/tests/contract/test_workspace_orchestration.py b/tests/contract/test_workspace_orchestration.pyindex 2631de36e0..0d1f9a2e97 100644--- a/tests/contract/test_workspace_orchestration.py+++ b/tests/contract/test_workspace_orchestration.py@@ -944,3 +944,133 @@ async def test_messages_queued_for_one_pane_arrive_in_order(rig, fast_queue):rig[2].refused = Falseawait until(lambda: not rig[0]._queued)assert rig[2].typed == [first["prompt"], second["prompt"]]+++# --- One board for "what is running, what is done, who needs me" ----------------+++async def test_status_lists_every_open_agent_and_who_needs_the_user_in_one_call(rig):+ orchestrator, registry, sessions = rig+ visible = registry.session+ other = next(s for s in registry.sessions if s.id != visible.id)+ visible.terminals[0].activity = "working"+ other.terminals[0].activity = "asking"+ board = await orchestrator.run({"action": "status"})+ assert board["status"] == "ok"+ rows = {row["workspace"]: row for row in board["workspaces"]}+ assert set(rows) == {"Personal Jarvis", "Other project"}+ assert rows[visible.name]["agents"][0]["state"] == "busy"+ assert rows[visible.name]["visible"] is True+ assert rows[other.name]["agents"][0]["state"] == "needs_input"+ assert board["counts"] == {"busy": 1, "needs_input": 1}+ assert board["needs_you"] == [f"Alex ({other.name})"]+ assert "folder" not in rows[visible.name]+ assert not sessions.calls # no pane is read or touched for the overview+++async def test_status_narrows_to_a_named_workspace(rig):+ board = await rig[0].run({"action": "status", "workspace": "Other project"})+ assert [row["workspace"] for row in board["workspaces"]] == ["Other project"]+ missing = await rig[0].run({"action": "status", "workspace": "No such workspace"})+ assert "workspaces" not in missing and missing["status"] != "ok"+++def visible_repo(rig):+ """The visible workspace's folder as a fresh repository with one new file."""+ import subprocess+ from pathlib import Path++ from jarvis.agentic_ide import git_ops+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++ if not git_ops.git_available():+ pytest.skip("git is not installed")+ visible = rig[1].session+ subprocess.run( # noqa: S603 - a fixed git command in a temporary folder+ ["git", "init", "-q"], cwd=visible.folder, check=True, # noqa: S607+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ Path(visible.folder, "notes.txt").write_text("draft", encoding="utf-8")+ return visible+++async def test_status_reports_the_git_state_of_a_workspace_folder(rig, visible_repo):+ board = await rig[0].run({"action": "status"})+ rows = {row["workspace"]: row for row in board["workspaces"]}+ git = rows[visible_repo.name]["git"]+ assert git["branch"] and git["changed_files"] == 1+ assert git["worktree"] is False and git["conflicted"] == 0+ plain = next(name for name in rows if name != visible_repo.name)+ assert "git" not in rows[plain] # a folder outside any repository has no git row+++class _Origin:+ """The conversation a tool call came from, as the workspace tool records it."""++ def __init__(self, surface: str) -> None:+ self.origin = {"reply_surface": surface, "reply_session_id": "", "lang": "en"}++ def __enter__(self):+ from jarvis.core.delegation import current_delegation_origin++ self._var = current_delegation_origin+ self._token = self._var.set(self.origin)++ def __exit__(self, *_exc):+ self._var.reset(self._token)+++def reportable(monkeypatch):+ from jarvis.agentic_ide import followthrough++ monkeypatch.setattr(followthrough, "can_report", lambda _term: True)+ monkeypatch.setattr(followthrough, "_events", lambda _term: [])+++async def test_watch_follows_a_hand_started_job_and_shows_on_the_board(rig, reportable):+ orchestrator, registry, sessions = rig+ term = registry.session.terminals[0]+ term.activity, term.last_prompt = "working", "Refactor the importer"+ watch = {"action": "watch", "workspace": registry.session.name, "agent": term.name}+ with _Origin("voice"):+ first = await orchestrator.run(watch)+ again = await orchestrator.run(watch)+ assert first["status"] == "watching" and "already" not in first+ assert again["status"] == "watching" and again["already"] is True+ assert term.delegation_result.watched+ assert "Refactor the importer" in term.delegation_result.request+ board = await orchestrator.run({"action": "status", "workspace": registry.session.name})+ assert board["workspaces"][0]["agents"][0]["watched"] is True+ assert not sessions.calls # watching types nothing into the pane+++async def test_watch_refuses_honestly_when_there_is_nothing_to_report(rig, monkeypatch):+ orchestrator, registry, _sessions = rig+ term = registry.session.terminals[0]+ watch = {"action": "watch", "workspace": registry.session.name, "agent": term.name}+ with _Origin("voice"):+ idle = await orchestrator.run(watch)+ assert idle["status"] == "not_running" and term.delegation_result is None+ term.activity = "working"+ with _Origin("voice"):+ unreadable = await orchestrator.run(watch) # this CLI session has no record yet+ assert unreadable["status"] == "unavailable" and term.delegation_result is None+ from jarvis.agentic_ide import followthrough++ monkeypatch.setattr(followthrough, "can_report", lambda _term: True)+ with _Origin("none"):+ nowhere = await orchestrator.run(watch)+ assert nowhere["status"] == "unavailable" and term.delegation_result is None+++def test_status_is_a_read_and_watch_is_a_logged_action(rig):+ import jsonschema++ tool = WorkspaceOrchestrationTool(rig[0])+ jsonschema.validate({"action": "status", "workspace": "Other project"}, tool.schema)+ jsonschema.validate({"action": "watch", "agent": "Alex"}, tool.schema)+ assert tool.risk_tier_for_args({"action": "status"}) == "safe"+ assert tool.describe_args({"action": "status"})["level"] == "read"+ assert tool.risk_tier_for_args({"action": "watch"}) == "monitor"diff --git a/tests/unit/agentic_ide/test_followthrough.py b/tests/unit/agentic_ide/test_followthrough.pyindex 98a1240449..a6dca6e2c1 100644--- a/tests/unit/agentic_ide/test_followthrough.py+++ b/tests/unit/agentic_ide/test_followthrough.py@@ -217,3 +217,62 @@ async def test_late_old_record_for_identical_prompt_is_not_fresh_work(pane):assert not await ft.publish_result("completed", term, pending, events.append)assert not eventsassert term.delegation_result is pending+++# --- Watching a job the user typed by hand --------------------------------------+#+# Nothing was sent through the app, so there is no prompt to match: the CLI's+# own end marker, recorded after the watch began, identifies the answer.+++def _hand_typed(turns, *, at=99):+ turns.append({"kind": "user_message", "ts_ms": at * 1000,+ "payload": {"text": "Refactor the importer"}})+++def _turn_end(report, *, at):+ return [+ {"kind": "assistant_text", "ts_ms": at * 1000,+ "payload": {"text": report, "turn_id": "typed"}},+ {"kind": "turn_finished", "ts_ms": (at + 1) * 1000,+ "payload": {"status": "done", "turn_id": "typed"}},+ ]+++async def test_a_watched_hand_typed_job_reports_its_own_end_once(pane):+ term, turns = pane+ _hand_typed(turns)+ pending = await ft.watch(term, {"lang": "en"})+ assert term.delegation_result is pending and pending.watched+ events = []+ assert not await ft.publish_result("completed", term, pending, events.append)+ turns.extend(_turn_end("Importer refactored; 12 tests pass.", at=101))+ assert await ft.publish_result("completed", term, pending, events.append)+ assert not await ft.publish_result("completed", term, pending, events.append)+ assert len(events) == 1 and "Importer refactored" in events[0].report+ assert "T2" in events[0].report and term.delegation_result is None+++async def test_a_watch_never_reads_back_a_turn_that_ended_before_it_began(pane):+ term, turns = pane+ _hand_typed(turns, at=95)+ pending = await ft.watch(term, {"lang": "en"})+ # The record of the earlier end reaches the disk only now.+ turns.extend(_turn_end("Finished long ago.", at=96))+ events = []+ assert not await ft.publish_result("completed", term, pending, events.append)+ assert not events and term.delegation_result is pending+++async def test_a_prompt_typed_after_the_watch_ends_it(pane):+ term, turns = pane+ _hand_typed(turns)+ pending = await ft.watch(term, {"lang": "en"})+ term.last_submit_at += 5+ turns.extend(_turn_end("Answer to the newer prompt.", at=106))+ events = []+ assert not await ft.publish_result("completed", term, pending, events.append)+ assert not events