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(agent-chat): close turns a restart left open and stop repeating split thoughts

rubenluetke10-beepddf9a9c999d9
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
index edd4ffe084..9cee095924 100644
--- a/jarvis/agent_chat/service.py
+++ b/jarvis/agent_chat/service.py
@@ -24,6 +24,7 @@ import json
import logging
import re
import shutil
+import sqlite3
import time
import uuid
from collections.abc import Callable
@@ -65,6 +66,12 @@ from jarvis.society.delivery import IncomingMessage
log = logging.getLogger(__name__)
+#: What a turn cut off by a restart says (``_seal_orphaned_turns``).
+_ORPHANED_TURN_ERROR: Final = (
+ "Jarvis restarted while this turn was running. "
+ "Everything after the last step shown here was not captured."
+)
+
Subscriber = asyncio.Queue[dict[str, Any]]
DECISIONS: tuple[str, ...] = ("allow", "allow_always", "deny")
@@ -271,6 +278,49 @@ class AgentChatService:
# The archived voice chat's history while one is continued (bind_voice_chat).
self._voice_archive_history: Callable[[], list[Any]] | None = None
self._retire_cli_seats()
+ self._seal_orphaned_turns()
+
+ def _seal_orphaned_turns(self) -> None:
+ """Close every turn a previous process left open.
+
+ The runner's task lives in memory, so a turn that was running when the
+ app quit, crashed or was restarted can never send another event: its
+ CLI's pipe went with the old process. Left open, the thread showed
+ "Working" for ever and froze on the last line the old process wrote,
+ while the agent's real ending never arrived (2026-10-05). This service
+ is built once per process, before it runs a turn of its own, so every
+ open turn here is such an orphan. It ends as failed, stamped with the
+ last moment the session heard anything, so the thread list keeps its
+ order. A CLI that outlived its parent is not hunted down here: a stop
+ by folder would also hit the person's own terminals in that folder.
+ """
+ try:
+ orphans = self.store.open_turns()
+ except sqlite3.Error:
+ log.warning("agent chat: could not look for turns a restart left open", exc_info=True)
+ return
+ for session_id, turn_id, started_ms, last_ms in orphans:
+ if not turn_id:
+ continue
+ self.store.append_event(
+ session_id,
+ {
+ **make_event(
+ "turn_finished",
+ {
+ "turn_id": turn_id,
+ "status": "error",
+ "duration_ms": max(0, last_ms - started_ms),
+ "usage": {},
+ "error": _ORPHANED_TURN_ERROR,
+ "cost_usd": None,
+ },
+ ),
+ "ts_ms": last_ms,
+ },
+ )
+ if orphans:
+ log.info("agent chat: closed %d turn(s) a restart left open", len(orphans))
def _retire_cli_seats(self) -> None:
"""Move chats off a CLI seat their surface no longer offers.
diff --git a/jarvis/agent_chat/store.py b/jarvis/agent_chat/store.py
index 1f8024a2f1..e8173d2af9 100644
--- a/jarvis/agent_chat/store.py
+++ b/jarvis/agent_chat/store.py
@@ -454,6 +454,30 @@ class AgentChatStore:
receipt.update(payload)
return receipt
+ def open_turns(self) -> list[tuple[str, str, int, int]]:
+ """Every session whose newest turn never got its ``turn_finished``.
+
+ ``(session_id, turn_id, started_ms, last_ts_ms)``: when the turn began
+ and when the session last heard anything at all.
+ """
+ with self._lock:
+ rows = self._conn.execute(
+ "SELECT e.session_id, json_extract(e.payload, '$.turn_id') AS turn_id, "
+ "e.ts_ms AS started_ms, "
+ "(SELECT MAX(x.ts_ms) FROM agent_chat_events x "
+ " WHERE x.session_id = e.session_id) AS last_ms "
+ "FROM (SELECT session_id, MAX(seq) AS seq FROM agent_chat_events "
+ " WHERE kind = 'turn_started' GROUP BY session_id) l "
+ "JOIN agent_chat_events e ON e.session_id = l.session_id AND e.seq = l.seq "
+ "WHERE NOT EXISTS (SELECT 1 FROM agent_chat_events f "
+ " WHERE f.session_id = l.session_id AND f.seq > l.seq "
+ " AND f.kind = 'turn_finished')"
+ ).fetchall()
+ return [
+ (str(r["session_id"]), str(r["turn_id"] or ""), int(r["started_ms"]), int(r["last_ms"]))
+ for r in rows
+ ]
+
def turn_terminal(self, session_id: str, turn_id: str) -> dict[str, Any] | None:
"""Read one durable terminal event for an exact owned turn without loading history."""
with self._lock:
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/reduce.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/reduce.test.ts
index c826ad20a9..de721702ef 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/reduce.test.ts
+++ b/jarvis/ui/web/frontend/src/components/agentchat/reduce.test.ts
@@ -98,6 +98,21 @@ describe("agent-chat reduce", () => {
expect((tl.items[0] as TurnItem).blocks).toHaveLength(2);
});
+ it("grows one thought when a message's thinking arrives in several blocks", () => {
+ // The CLI sends each thinking block of one message as its own event,
+ // carrying everything the message thought so far (2026-10-05 thread).
+ const tl = reduceEvents(EMPTY_TIMELINE, [
+ ev("turn_started", { turn_id: "t7" }),
+ ev("reasoning", { turn_id: "t7", message_id: "m1", text: "first", duration_ms: 7595 }),
+ ev("reasoning", { turn_id: "t7", message_id: "m1", text: "first\n\nsecond", duration_ms: 7597 }),
+ ev("reasoning", { turn_id: "t7", message_id: "m2", text: "other message" }),
+ ]);
+ const turn = tl.items[0] as TurnItem;
+ expect(turn.blocks).toHaveLength(2);
+ expect(turn.blocks[0]).toMatchObject({ kind: "reasoning", text: "first\n\nsecond", durationMs: 7597 });
+ expect(turn.blocks[1]).toMatchObject({ kind: "reasoning", text: "other message" });
+ });
+
it("ends a live thought when text or a tool call follows, and times tool calls from the log", () => {
let tl = reduceEvents(EMPTY_TIMELINE, [
ev("turn_started", { turn_id: "t6" }),
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts b/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts
index e5ab114eb4..0267e16e99 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts
+++ b/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts
@@ -38,6 +38,8 @@ export interface ReasoningBlock {
live: boolean;
/** When the model began to think (drives the live elapsed counter). */
startedMs: number;
+ /** The model message the thought belongs to, when the runner names one. */
+ messageId?: string;
}
export interface ApprovalState {
@@ -606,6 +608,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {
case "reasoning": {
const text = str(p.text);
const durationMs = num(p.duration_ms);
+ const messageId = str(p.message_id) || undefined;
return updateTurn(base, turnId, (turn) => {
const last = turn.blocks[turn.blocks.length - 1];
if (last && last.kind === "reasoning" && last.live) {
@@ -616,6 +619,20 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {
text: text || last.text,
durationMs: durationMs ?? Math.max(0, ev.ts_ms - last.startedMs),
live: false,
+ ...(messageId ? { messageId } : {}),
+ }),
+ };
+ }
+ // The CLI sends a message's thinking blocks one by one, each event
+ // carrying everything that message thought so far. A later block of
+ // the same message replaces the finished one instead of repeating it.
+ if (messageId && last && last.kind === "reasoning" && last.messageId === messageId) {
+ return {
+ ...turn,
+ blocks: replaceAt(turn.blocks, turn.blocks.length - 1, {
+ ...last,
+ text: text || last.text,
+ durationMs: durationMs ?? last.durationMs,
}),
};
}
@@ -633,6 +650,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {
durationMs,
live: false,
startedMs: ev.ts_ms - (durationMs ?? 0),
+ ...(messageId ? { messageId } : {}),
},
],
};
diff --git a/tests/unit/agent_chat/test_agent_chat_service.py b/tests/unit/agent_chat/test_agent_chat_service.py
index 07a0e3d8bd..787423f96c 100644
--- a/tests/unit/agent_chat/test_agent_chat_service.py
+++ b/tests/unit/agent_chat/test_agent_chat_service.py
@@ -741,3 +741,32 @@ def test_allow_always_on_a_kit_that_handles_it_does_not_flip_the_mode(
assert remembered == [(session.session_id, "RunCommand", {"command": "echo x"})]
asyncio.run(scenario())
+
+
+def test_a_new_process_closes_turns_a_restart_left_open(tmp_path: Path) -> None:
+ """A turn whose runner died with the old process ends as failed, not Working for ever."""
+ db = tmp_path / "agent_chat.db"
+ store = AgentChatStore(db)
+ open_chat = store.create_session(provider="claude-api", model="m", effort="medium", cwd=str(tmp_path))
+ done_chat = store.create_session(provider="claude-api", model="m", effort="medium", cwd=str(tmp_path))
+ for sid, ts in ((open_chat.session_id, 1_000), (done_chat.session_id, 1_000)):
+ store.append_event(sid, {"kind": "turn_started", "ts_ms": ts, "payload": {"turn_id": f"t-{sid}"}})
+ store.append_event(sid, {"kind": "tool_call", "ts_ms": ts + 500, "payload": {"turn_id": f"t-{sid}", "call_id": "c"}})
+ store.append_event(
+ done_chat.session_id,
+ {"kind": "turn_finished", "ts_ms": 2_000, "payload": {"turn_id": f"t-{done_chat.session_id}", "status": "done"}},
+ )
+
+ AgentChatService(AgentChatStore(db))
+
+ sealed = store.list_events(open_chat.session_id)[-1]
+ assert sealed["kind"] == "turn_finished"
+ assert sealed["payload"]["turn_id"] == f"t-{open_chat.session_id}"
+ assert sealed["payload"]["status"] == "error"
+ assert sealed["payload"]["error"]
+ # Stamped with the last thing the chat heard, so the thread list keeps its order.
+ assert sealed["ts_ms"] == 1_500
+ assert sealed["payload"]["duration_ms"] == 500
+ finished = [e for e in store.list_events(done_chat.session_id) if e["kind"] == "turn_finished"]
+ assert len(finished) == 1
+ assert store.open_turns() == []