Skip to content

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.

fix(threads): say when a coding agent waits for its background tasks (#1103)

Ruben Lütke1d47a40d8927
diff --git a/docs/agentic-ide-threads.md b/docs/agentic-ide-threads.md
index 4f4e79a465..84303e1ca8 100644
--- a/docs/agentic-ide-threads.md
+++ b/docs/agentic-ide-threads.md
@@ -38,7 +38,10 @@ for an approval and a blue dot for news since it was last opened.
reading text, the work in between as folded rows ("Ran 3 commands, read 2
files") that open to each call, its diff or its output. A running turn ends
in a live "Working for 12s" line; a finished one says how long it worked and
- which files it changed.
+ which files it changed. When the agent has written its message but still
+ waits for background tasks it started (a test run, a push), the line says
+ so instead: "Waiting for 2 background tasks · 21m 40s", with the tasks
+ named. The agent picks up again when they finish.
- **Composer:** one toolbar — coding agent and model, reasoning effort, access
mode — beside the paperclip and the send button. A new thread starts on the
agent, model, effort and access the person picked last (else the newest
diff --git a/dodaios/agent_chat/events.py b/dodaios/agent_chat/events.py
index 0f33223626..4cd4248610 100644
--- a/dodaios/agent_chat/events.py
+++ b/dodaios/agent_chat/events.py
@@ -48,6 +48,10 @@ Kinds (``payload`` keys in brackets):
duration_ms?] — live only: what the sub-agent is doing now
``subagent_finished`` [turn_id, agent_id, status, summary?, tokens?, tool_uses?,
duration_ms?] status: done | failed | stopped
+``background_wait`` [turn_id, tasks] — the agent ended its message but the CLI
+ still runs background tasks (shells, agents) and will wake
+ it when they finish; ``tasks`` names them, [] = no longer
+ waiting
``turn_finished`` [turn_id, status, duration_ms, usage, error, cost_usd]
status: done | cancelled | error
``session_updated`` [title?, provider?, model?, effort?, cwd?, permission_mode?]
diff --git a/dodaios/agent_chat/runner_cli.py b/dodaios/agent_chat/runner_cli.py
index 797321291d..05062fbd58 100644
--- a/dodaios/agent_chat/runner_cli.py
+++ b/dodaios/agent_chat/runner_cli.py
@@ -1745,6 +1745,13 @@ class _ClaudeState:
agents: dict[str, _ClaudeState] = field(default_factory=dict)
#: The CLI's task id -> the spawning call, for task updates that name only the task.
agent_tasks: dict[str, str] = field(default_factory=dict)
+ #: Tasks the CLI still runs (task id -> what it does): background shells
+ #: and agents. They keep the CLI alive after the agent's message ended.
+ open_tasks: dict[str, str] = field(default_factory=dict)
+ #: The main agent ended its message; only open tasks can wake it again.
+ idle: bool = False
+ #: The task list the last ``background_wait`` event named.
+ wait_sent: tuple[str, ...] = ()
#: Streamed characters per estimated output token (English and code average).
@@ -1912,6 +1919,40 @@ def _claude_subagent_line(
return out
+def _claude_track_task(obj: dict[str, Any], st: _ClaudeState) -> None:
+ """Keep the set of tasks the CLI still runs, shells and agents alike."""
+ subtype = str(obj.get("subtype") or "")
+ task_id = str(obj.get("task_id") or "")
+ if not task_id or subtype not in _CLAUDE_TASK_SUBTYPES:
+ return
+ if subtype == "task_started":
+ what = str(obj.get("description") or "").strip().splitlines()
+ st.open_tasks[task_id] = what[0][:120] if what else str(obj.get("task_type") or "task")
+ return
+ if subtype == "task_updated":
+ patch = obj.get("patch") if isinstance(obj.get("patch"), dict) else {}
+ if str(patch.get("status") or "") in {"", "running", "pending"}:
+ return
+ if subtype in {"task_updated", "task_notification"}:
+ st.open_tasks.pop(task_id, None)
+
+
+def _claude_wait_events(st: _ClaudeState) -> list[dict[str, Any]]:
+ """``background_wait`` whenever what the idle agent waits for changes.
+
+ Claude Code can end its message while background shells or agents still
+ run: the CLI stays alive and wakes the agent again when they finish. The
+ answer then reads finished while the turn is not, so the timeline says
+ what it waits for. An empty list: it no longer waits (it works again,
+ or nothing is left open).
+ """
+ tasks = tuple(st.open_tasks.values()) if st.idle else ()
+ if tasks == st.wait_sent:
+ return []
+ st.wait_sent = tasks
+ return [make_event("background_wait", {"turn_id": st.turn_id, "tasks": list(tasks)})]
+
+
def _claude_task_events(obj: dict[str, Any], st: _ClaudeState) -> list[dict[str, Any]]:
"""A sub-agent's life from Claude Code's task lines: started, working, finished.
@@ -2000,8 +2041,10 @@ def translate_claude_line(obj: dict[str, Any], st: _ClaudeState) -> list[dict[st
if kind == "system":
# init / hooks / status are nothing the timeline shows; a sub-agent's
- # life (started, working, finished) is.
- return _claude_task_events(obj, st)
+ # life (started, working, finished) is, and so is a wait on open tasks.
+ out = _claude_task_events(obj, st)
+ _claude_track_task(obj, st)
+ return out + _claude_wait_events(st)
if kind == "stream_event":
ev = obj.get("event") or {}
@@ -2009,6 +2052,9 @@ def translate_claude_line(obj: dict[str, Any], st: _ClaudeState) -> list[dict[st
if et == "message_start":
mid = ((ev.get("message") or {}).get("id")) or uuid.uuid4().hex
st.current_message_id = str(mid)
+ # The agent works again (a finished task woke it): no longer waiting.
+ st.idle = False
+ out.extend(_claude_wait_events(st))
elif et == "content_block_start":
block = ev.get("content_block") or {}
if block.get("type") == "thinking":
@@ -2065,6 +2111,9 @@ def translate_claude_line(obj: dict[str, Any], st: _ClaudeState) -> list[dict[st
if event is not None:
out.append(event)
elif et == "message_delta":
+ if (ev.get("delta") or {}).get("stop_reason") == "end_turn":
+ st.idle = True
+ out.extend(_claude_wait_events(st))
# The end of a message: its usage carries the true output count.
usage_end = ev.get("usage")
mid = st.current_message_id
@@ -2199,6 +2248,8 @@ def translate_claude_line(obj: dict[str, Any], st: _ClaudeState) -> list[dict[st
if kind == "result":
st.saw_result = True
+ st.idle = True
+ out.extend(_claude_wait_events(st))
st.result_text = str(obj.get("result") or "")
if obj.get("is_error"):
st.status = "error"
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts b/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts
index 0d3169df55..c142c0d693 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts
+++ b/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts
@@ -320,6 +320,11 @@ export interface TurnItem {
* its seat to the next message and the result arrives in a turn of its own.
*/
background?: string[];
+ /**
+ * The background tasks a running turn waits on (`background_wait`): the
+ * agent ended its message, the CLI wakes it again once they finish.
+ */
+ waitingOn?: string[];
}
export interface ErrorItem {
@@ -1174,6 +1179,11 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {
);
}
+ case "background_wait": {
+ const tasks = Array.isArray(p.tasks) ? p.tasks.map((task) => str(task)).filter(Boolean) : [];
+ return updateTurn(base, turnId, (turn) => ({ ...turn, waitingOn: tasks }));
+ }
+
case "usage_delta": {
const usage = p.usage;
if (!usage || typeof usage !== "object") return base;
diff --git a/dodaios/ui/web/frontend/src/components/agentic/threads/ThreadBackgroundWait.test.tsx b/dodaios/ui/web/frontend/src/components/agentic/threads/ThreadBackgroundWait.test.tsx
new file mode 100644
index 0000000000..c78ac2831f
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/agentic/threads/ThreadBackgroundWait.test.tsx
@@ -0,0 +1,44 @@
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { EMPTY_TIMELINE, reduceEvents, type TurnItem } from "@/components/agentchat/reduce";
+import type { AgentChatEvent } from "@/lib/agentChatApi";
+import { ThreadTurn } from "./ThreadTimeline";
+
+let seq = 0;
+const ev = (kind: string, payload: Record<string, unknown>): AgentChatEvent =>
+ ({ seq: ++seq, ts_ms: Date.now(), kind, payload } as AgentChatEvent);
+const turnOf = (events: AgentChatEvent[]) =>
+ reduceEvents(EMPTY_TIMELINE, events).items.find((item) => item.type === "turn") as TurnItem;
+
+/** A Claude Code turn whose agent wrote its answer, then waited for two background shells. */
+const waiting = () => [
+ ev("turn_started", { turn_id: "t1", provider: "claude-cli" }),
+ ev("assistant_text", { turn_id: "t1", message_id: "m1", text: "Tests and push run in the background." }),
+ ev("background_wait", { turn_id: "t1", tasks: ["Run the full test suite", "git push"] }),
+];
+
+afterEach(cleanup);
+
+describe("a thread turn that waits for its background tasks", () => {
+ it("says it waits, and on what, instead of plain Working", () => {
+ render(<ThreadTurn turn={turnOf(waiting())} />);
+ const line = screen.getByTestId("thread-working").textContent ?? "";
+ expect(line).toMatch(/^Waiting for 2 background tasks · /);
+ expect(line).toContain("Run the full test suite, git push");
+ expect(line).not.toContain("Working for");
+ });
+
+ it("goes back to Working once the agent picks up again", () => {
+ const turn = turnOf([...waiting(), ev("background_wait", { turn_id: "t1", tasks: [] })]);
+ render(<ThreadTurn turn={turn} />);
+ expect(screen.queryByTestId("thread-waiting-background")).toBeNull();
+ expect(screen.getByTestId("thread-working").textContent).toMatch(/^Working for /);
+ });
+
+ it("shows no wait on a finished turn", () => {
+ const turn = turnOf([...waiting(), ev("turn_finished", { turn_id: "t1", status: "done", duration_ms: 9000 })]);
+ render(<ThreadTurn turn={turn} />);
+ expect(screen.queryByTestId("thread-working")).toBeNull();
+ expect(screen.queryByTestId("thread-waiting-background")).toBeNull();
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx b/dodaios/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx
index f79f7dea58..c5e7cd98ba 100644
--- a/dodaios/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx
@@ -643,6 +643,9 @@ export const ThreadTurn = memo(function ThreadTurn({ turn, prompts = "composer",
// A call that still waits for the person never folds away.
const waiting = useMemo(() => work.filter((row) => row.kind === "pending" && waitsForPerson(row.block)), [work]);
const agentsWorking = useMemo(() => running ? listSubagents([turn]).filter((entry) => entry.status === "running").length : 0, [turn, running]);
+ // The agent ended its message and waits for its background tasks: the answer
+ // above reads finished, so the live line says what it still waits for.
+ const waitingOn = running ? turn.waitingOn ?? [] : [];
const extraRows = extras ?? [];
const folded = !running && (work.length > 0 || extraRows.length > 0);
const duration = turn.durationMs != null ? traceDuration(turn.durationMs) : "";
@@ -713,8 +716,15 @@ export const ThreadTurn = memo(function ThreadTurn({ turn, prompts = "composer",
{shown.slice(extraAt).map(renderRow)}
{running
? <div className="flex h-6 min-w-0 items-center px-1 text-sm leading-relaxed text-muted-foreground" data-testid="thread-working">
- <span className="whitespace-nowrap"><WorkingFor since={turn.startedMs} />
- {agentsWorking > 0 && <> · {fill(t(`thread_turn.subagents_working_${plural(lang, agentsWorking)}`), { count: agentsWorking })}</>}</span>
+ {waitingOn.length > 0
+ ? <>
+ <span className="whitespace-nowrap" data-testid="thread-waiting-background">
+ {fill(t(`thread_turn.waiting_background_${plural(lang, waitingOn.length)}`), { count: waitingOn.length })} · <Elapsed since={turn.startedMs} />
+ </span>
+ <span className="min-w-0 truncate" title={waitingOn.join("\n")}>&nbsp;· {waitingOn.join(", ")}</span>
+ </>
+ : <span className="whitespace-nowrap"><WorkingFor since={turn.startedMs} />
+ {agentsWorking > 0 && <> · {fill(t(`thread_turn.subagents_working_${plural(lang, agentsWorking)}`), { count: agentsWorking })}</>}</span>}
</div>
: <>
{turn.status === "error" && turn.error && <p role="alert" className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">{turnErrorText(turn.error, t)}</p>}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/de.json b/dodaios/ui/web/frontend/src/i18n/locales/de.json
index ee2435947d..d8d22f803b 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json
@@ -7738,6 +7738,8 @@
"steps_so_far": "{summary}, bisher {count} Schritte",
"subagents_working_one": "{count} Sub-Agent arbeitet",
"subagents_working_other": "{count} Sub-Agenten arbeiten",
+ "waiting_background_one": "Wartet auf {count} Hintergrund-Aufgabe",
+ "waiting_background_other": "Wartet auf {count} Hintergrund-Aufgaben",
"files_changed_one": "{count} Datei geändert",
"files_changed_other": "{count} Dateien geändert",
"changed_files": "Geänderte Dateien",
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.json
index bf6d0f80fb..f8afa8f850 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json
@@ -7738,6 +7738,8 @@
"steps_so_far": "{summary}, {count} steps so far",
"subagents_working_one": "{count} sub-agent working",
"subagents_working_other": "{count} sub-agents working",
+ "waiting_background_one": "Waiting for {count} background task",
+ "waiting_background_other": "Waiting for {count} background tasks",
"files_changed_one": "{count} file changed",
"files_changed_other": "{count} files changed",
"changed_files": "Changed files",
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.json
index fff0e160c8..8048345ece 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json
@@ -7738,6 +7738,8 @@
"steps_so_far": "{summary}, {count} pasos hasta ahora",
"subagents_working_one": "{count} subagente trabajando",
"subagents_working_other": "{count} subagentes trabajando",
+ "waiting_background_one": "Esperando {count} tarea en segundo plano",
+ "waiting_background_other": "Esperando {count} tareas en segundo plano",
"files_changed_one": "{count} archivo cambiado",
"files_changed_other": "{count} archivos cambiados",
"changed_files": "Archivos cambiados",
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.json
index 9646b6cf04..1cb7f8f854 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json
@@ -7738,6 +7738,8 @@
"steps_so_far": "{summary}, {count} passos até agora",
"subagents_working_one": "{count} subagente a trabalhar",
"subagents_working_other": "{count} subagentes a trabalhar",
+ "waiting_background_one": "À espera de {count} tarefa em segundo plano",
+ "waiting_background_other": "À espera de {count} tarefas em segundo plano",
"files_changed_one": "{count} ficheiro alterado",
"files_changed_other": "{count} ficheiros alterados",
"changed_files": "Ficheiros alterados",
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.json
index 256b9e04c8..a7caefd011 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json
@@ -7738,6 +7738,8 @@
"steps_so_far": "{summary},目前 {count} 步",
"subagents_working_one": "{count} 个子代理正在工作",
"subagents_working_other": "{count} 个子代理正在工作",
+ "waiting_background_one": "正在等待 {count} 个后台任务",
+ "waiting_background_other": "正在等待 {count} 个后台任务",
"files_changed_one": "已更改 {count} 个文件",
"files_changed_other": "已更改 {count} 个文件",
"changed_files": "已更改的文件",
diff --git a/tests/unit/agent_chat/test_background_wait.py b/tests/unit/agent_chat/test_background_wait.py
new file mode 100644
index 0000000000..b236634438
--- /dev/null
+++ b/tests/unit/agent_chat/test_background_wait.py
@@ -0,0 +1,100 @@
+"""A Claude Code turn that ended its message but still runs background tasks.
+
+The CLI stays alive and wakes the agent again once its background shells or
+agents finish. Until then the answer reads finished while the turn is not, so
+the translator says what the turn waits for (``background_wait``).
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from dodaios.agent_chat.runner_cli import _ClaudeState, translate_claude_line
+
+
+def _stream(event: dict[str, Any]) -> dict[str, Any]:
+ return {"type": "stream_event", "event": event, "session_id": "s1"}
+
+
+def _start(mid: str) -> dict[str, Any]:
+ return _stream({"type": "message_start", "message": {"id": mid}})
+
+
+def _stop(reason: str) -> dict[str, Any]:
+ return _stream({"type": "message_delta", "delta": {"stop_reason": reason}, "usage": {}})
+
+
+def _task(subtype: str, task_id: str, **extra: Any) -> dict[str, Any]:
+ return {"type": "system", "subtype": subtype, "task_id": task_id, **extra}
+
+
+def _waits(lines: list[dict[str, Any]], st: _ClaudeState | None = None) -> list[list[str]]:
+ st = st or _ClaudeState(turn_id="t1")
+ return [
+ ev["payload"]["tasks"]
+ for line in lines
+ for ev in translate_claude_line(line, st)
+ if ev["kind"] == "background_wait"
+ ]
+
+
+def test_an_ended_message_with_open_shells_waits_on_them() -> None:
+ lines = [
+ _start("m1"),
+ _task("task_started", "b1", task_type="local_bash", description="Run the full test suite"),
+ _task("task_started", "b2", task_type="local_bash", description="git push\nmore"),
+ _stop("tool_use"),
+ _start("m2"),
+ _stop("end_turn"),
+ _task("task_notification", "b2", status="completed"),
+ _task("task_notification", "b1", status="completed"),
+ _start("m3"),
+ _stop("end_turn"),
+ ]
+ assert _waits(lines) == [
+ ["Run the full test suite", "git push"],
+ ["Run the full test suite"],
+ [],
+ ]
+
+
+def test_the_agent_waking_up_clears_the_wait() -> None:
+ lines = [
+ _start("m1"),
+ _task("task_started", "b1", task_type="local_bash", description="sleep 600"),
+ _stop("end_turn"),
+ _start("m2"),
+ ]
+ assert _waits(lines) == [["sleep 600"], []]
+
+
+def test_a_result_line_with_open_tasks_waits_too() -> None:
+ lines = [
+ _task("task_started", "b1", task_type="local_bash", description="pytest"),
+ {"type": "result", "subtype": "success", "result": "Done.", "session_id": "s1"},
+ ]
+ assert _waits(lines) == [["pytest"]]
+
+
+def test_no_wait_without_open_tasks_or_while_the_agent_works() -> None:
+ lines = [
+ _start("m1"),
+ _task("task_started", "b1", task_type="local_bash", description="sleep 8"),
+ _stop("tool_use"),
+ _task("task_notification", "b1", status="completed"),
+ _start("m2"),
+ _stop("end_turn"),
+ {"type": "result", "subtype": "success", "result": "Done.", "session_id": "s1"},
+ ]
+ assert _waits(lines) == []
+
+
+def test_a_task_patched_to_a_final_status_is_no_longer_open() -> None:
+ lines = [
+ _task("task_started", "a1", task_type="local_agent", description="Review the diff",
+ tool_use_id="toolu_a", subagent_type="general-purpose", is_backgrounded=True),
+ _task("task_updated", "a1", patch={"status": "running"}),
+ _stop("end_turn"),
+ _task("task_updated", "a1", patch={"status": "completed"}),
+ ]
+ assert _waits(lines) == [["Review the diff"], []]