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(ide): preserve coding agent task duration across reconnects (#306)

Ruben Lütke93e1a932e141
diff --git a/jarvis/agentic_ide/activity.py b/jarvis/agentic_ide/activity.py
index 891cafc50b..70dc1cca17 100644
--- a/jarvis/agentic_ide/activity.py
+++ b/jarvis/agentic_ide/activity.py
@@ -524,6 +524,19 @@ def _submit_graced(term: Any, reading: Reading, moment: float) -> Reading:
return Reading("working", float(getattr(term, "last_submit_at", 0.0) or 0.0))
+def record_work_start(term: Any, at: float) -> None:
+ """Time a delivered task, preserving the clock for input during ongoing work.
+
+ Called before replacing the submit stamp. Observer pauses, resizes and
+ permission answers are not new tasks; a new submission at a settled prompt
+ is. A process spawn clears this clock before accepting another instruction.
+ """
+ current = observed(term, now=at)
+ if current.activity not in {"working", "asking"} or not term.work_started_at:
+ term.work_started_at = at
+ term.work_pty_id = term.pty_id or ""
+
+
def observed(term: Any, *, now: float | None = None) -> Reading:
"""What ``term`` is doing, for a caller with no history of its own.
@@ -546,7 +559,16 @@ def observed(term: Any, *, now: float | None = None) -> Reading:
# can read as working here. Rare by construction — the sweep runs for
# as long as any workspace is open.
reading = Reading(read_activity(term, now=moment), 0.0)
- return _submit_graced(term, reading, moment)
+ reading = _submit_graced(term, reading, moment)
+ if reading.activity == "working":
+ started = float(getattr(term, "work_started_at", 0.0) or 0.0)
+ if 0 < started <= moment:
+ return Reading("working", started)
+ if _adopted_with_work(term):
+ # An observer starting now cannot date a task it joined halfway
+ # through. Older/unsupported records may have no timestamp at all.
+ return Reading("working", 0.0)
+ return reading
def has_work_behind_it(term: Any) -> bool:
diff --git a/jarvis/agentic_ide/resume_store.py b/jarvis/agentic_ide/resume_store.py
index c8116a1636..9b5f514ef4 100644
--- a/jarvis/agentic_ide/resume_store.py
+++ b/jarvis/agentic_ide/resume_store.py
@@ -43,6 +43,7 @@ from loguru import logger
from .agent_sessions import ResumeHandle, has_conversation
from .library import project_id_for
+from .work_timing import timestamp
# Saves arrive from more than one thread (see `save`), and the last one has to
# be the one that lands rather than the one that happened to finish its rename
@@ -89,6 +90,10 @@ class SnapshotTerminal:
# a conversation existing does not mean its last turn was interrupted.
# Missing on older snapshots deliberately means False (fail closed).
continuation_needed: bool = False
+ # Task time survives rejoining the SAME hosted process. Never reuse it for
+ # a replacement process or mistake the snapshot/app time for the task start.
+ work_started_at: float = 0.0
+ work_pty_id: str = ""
# What the pane was OPENED on — the model, the effort level and the
# permission stance chosen for it (jarvis.workspace.launch_picks). Kept so
# a restored pane comes back on the same three picks instead of quietly
@@ -134,6 +139,8 @@ class SnapshotTerminal:
"account": self.account,
"account_pinned": self.account_pinned,
"continuation_needed": self.continuation_needed,
+ "work_started_at": self.work_started_at,
+ "work_pty_id": self.work_pty_id,
"model": self.model,
"effort": self.effort,
"permission_mode": self.permission_mode,
@@ -171,6 +178,8 @@ class SnapshotTerminal:
),
account_pinned=data.get("account_pinned") is True,
continuation_needed=data.get("continuation_needed") is True,
+ work_started_at=timestamp(data.get("work_started_at")),
+ work_pty_id=str(data.get("work_pty_id") or ""),
model=str(data.get("model") or "").strip(),
effort=str(data.get("effort") or "").strip(),
permission_mode=str(data.get("permission_mode") or "").strip(),
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index 38a248dc8e..fd2e0693bc 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -94,7 +94,7 @@ from . import (
remote,
resume_store,
)
-from .activity import NO_READING, Reading, has_work_behind_it, observed
+from .activity import NO_READING, Reading, has_work_behind_it, observed, record_work_start
from .agent_sessions import (
ResumeHandle,
can_fork,
@@ -1238,6 +1238,9 @@ class Terminal:
activity: str = ""
activity_at: float = 0.0
activity_since: float = 0.0
+ # The task's start, independent of activity detection and app uptime.
+ work_started_at: float = 0.0
+ work_pty_id: str = ""
# Monotonic identity for the process currently occupying this pane. The
# notification watcher outlives PTYs, so it uses this to discard the old
# process's screen fingerprint before interpreting a replacement process.
@@ -1522,6 +1525,8 @@ class Terminal:
account=self.account,
account_pinned=self.account_pinned,
continuation_needed=self.resume_continuation_needed,
+ work_started_at=self.work_started_at,
+ work_pty_id=self.work_pty_id,
model=self.model,
effort=self.effort,
permission_mode=self.permission_mode,
@@ -2649,9 +2654,35 @@ class Registry:
term.last_output_at = time.time() if result.replay else None
if await self._adopted_with_work(term):
term.adopted_generation = term.process_generation
+ await self._recover_work_start(term)
logger.info("Agentic IDE: {} re-joined its running agent after an app restart", term.name)
return True
+ @staticmethod
+ async def _recover_work_start(term: Terminal) -> None:
+ """Reconstruct existing tasks off-loop, without sending the agent input."""
+ from .work_timing import recover_start
+
+ saved = term.work_started_at if term.work_pty_id == term.pty_id else 0.0
+ term.work_started_at = saved
+ term.work_pty_id = term.pty_id or ""
+ if term.resume is None:
+ return
+ generation = (term.process_generation, term.pty_id, term.last_submit_at)
+ try:
+ started = await asyncio.to_thread(
+ recover_start, term.agent, term.resume.id, account_home(term.agent, term.account)
+ )
+ except Exception as exc: # noqa: BLE001 - unavailable timing must not break adoption
+ logger.warning("Agentic IDE: could not recover {}'s task clock: {}", term.name, exc)
+ return
+ if generation != (term.process_generation, term.pty_id, term.last_submit_at):
+ return # A new process or submission owns the clock now.
+ if started is not None:
+ # The record also covers tasks started/finished while Jarvis was
+ # closed; a saved clock alone cannot know about those boundaries.
+ term.work_started_at = started if 0 < started <= time.time() else 0.0
+
@staticmethod
async def _adopted_with_work(term: Terminal) -> bool:
"""Had this re-joined agent been given a job before the app restarted?
@@ -3183,6 +3214,8 @@ class Registry:
resume=entry.resume,
prompts_sent=entry.prompts_sent,
resume_continuation_needed=entry.continuation_needed,
+ work_started_at=entry.work_started_at,
+ work_pty_id=entry.work_pty_id,
account=account,
# The pin survives the restart only while the seat it vouches
# for does — a fallback onto the active account is not the
@@ -4490,6 +4523,8 @@ class Registry:
term.activity = ""
term.activity_at = 0.0
term.activity_since = 0.0
+ term.work_started_at = 0.0
+ term.work_pty_id = ""
# And this process has not stood still yet, whatever the previous one
# did. Everything it is about to draw is a CLI painting itself, not an
# agent working — see the field.
@@ -4753,6 +4788,7 @@ class Registry:
term.manual_submit_pending = True
self._schedule_manual_submit_confirmation(owner, term)
else:
+ record_work_start(term, term.last_input_at)
term.last_submit_at = term.last_input_at
term.submit_generation = term.process_generation
# And the pane's conversation may have just begun, which for most
@@ -4794,6 +4830,7 @@ class Registry:
term.manual_submit_pending = False
term.submitted = submitted
if submitted:
+ record_work_start(term, time.time())
term.last_submit_at = time.time()
term.submit_generation = term.process_generation
self._lookup_after_conversation(owner, term)
@@ -6846,6 +6883,7 @@ class Registry:
# at its prompt" bell for work that never started. The moment the user
# presses Enter on that box themselves, `write` stamps it for real.
if submitted is not False:
+ record_work_start(term, term.last_prompt_at)
term.last_submit_at = term.last_prompt_at
term.submit_generation = term.process_generation
term.manual_submit_pending = False
diff --git a/jarvis/agentic_ide/work_timing.py b/jarvis/agentic_ide/work_timing.py
new file mode 100644
index 0000000000..7de0ecadaf
--- /dev/null
+++ b/jarvis/agentic_ide/work_timing.py
@@ -0,0 +1,51 @@
+"""Recover a running task's clock without treating app uptime as work time.
+
+This is timing evidence only. The activity watcher still decides whether the
+agent is working. Transcript IO belongs on a worker thread during adoption,
+never in the activity sweep or a badge's request handler.
+"""
+
+from __future__ import annotations
+
+import math
+from typing import TYPE_CHECKING, Any
+
+from loguru import logger
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+
+def timestamp(value: Any) -> float:
+ """A finite positive epoch timestamp, or unknown for legacy/broken data."""
+ if isinstance(value, bool):
+ return 0.0
+ try:
+ result = float(value)
+ except (TypeError, ValueError, OverflowError):
+ logger.debug("Agentic IDE: ignoring an invalid saved task timestamp")
+ return 0.0
+ return result if math.isfinite(result) and result > 0 else 0.0
+
+
+def active_start(events: list[dict[str, Any]]) -> float:
+ """Start of the last unfinished task, including time awaiting first output."""
+ started = 0.0
+ for event in events:
+ kind = event.get("kind")
+ at = timestamp(event.get("ts_ms")) / 1000.0
+ if kind == "user_message":
+ started = at
+ elif kind == "turn_started" and not started:
+ started = at
+ elif kind == "turn_finished":
+ started = 0.0
+ return started
+
+
+def recover_start(agent: str, session_id: str, home: Path | None) -> float | None:
+ """Read the CLI's existing record; None means no timing source is available."""
+ from .agent_transcript import read_events
+
+ events = read_events(agent, session_id, home=home, live=True)
+ return None if events is None else active_start(events)
diff --git a/tests/unit/agentic_ide/test_work_timing.py b/tests/unit/agentic_ide/test_work_timing.py
new file mode 100644
index 0000000000..566c8d5f44
--- /dev/null
+++ b/tests/unit/agentic_ide/test_work_timing.py
@@ -0,0 +1,209 @@
+"""The Working badge times a task, not the observer or desktop process."""
+
+from __future__ import annotations
+
+import json
+import time
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import session as ide
+from jarvis.agentic_ide.activity import observed, record_work_start, stamp
+from jarvis.agentic_ide.agent_sessions import ResumeHandle
+from jarvis.agentic_ide.notifications import ActivityFeed
+from jarvis.agentic_ide.resume_store import SnapshotTerminal
+from jarvis.agentic_ide.work_timing import active_start, recover_start
+from tests.unit.agentic_ide.test_pty_host_adoption import FakeHostedPool
+
+
+def _pane() -> ide.Terminal:
+ return ide.Terminal(
+ key="t1",
+ name="T1",
+ agent="codex",
+ display_name="Codex",
+ index=0,
+ status="live",
+ pty_id="host-1",
+ process_generation=1,
+ )
+
+
+def _submit(term: ide.Terminal, at: float) -> None:
+ record_work_start(term, at)
+ term.last_submit_at = at
+ term.submit_generation = term.process_generation
+
+
+def test_working_clock_survives_detection_gaps_and_queued_input() -> None:
+ term = _pane()
+ _submit(term, 100.0)
+ stamp(term, "working", now=103.0)
+ assert observed(term, now=104.0).since == 100.0
+ # No repaint for long enough to lose the Working reading, then more work.
+ stamp(term, "waiting", now=800.0)
+ stamp(term, "working", now=810.0)
+ assert observed(term, now=811.0).since == 100.0
+ _submit(term, 812.0) # a queued clarification must not restart the job clock
+ assert observed(term, now=813.0).since == 100.0
+
+
+def test_new_task_resets_but_done_age_remains_the_completion_age() -> None:
+ term = _pane()
+ _submit(term, 100.0)
+ stamp(term, "waiting", now=800.0, since=790.0)
+ assert observed(term, now=801.0).since == 790.0
+ _submit(term, 802.0)
+ assert observed(term, now=803.0).since == 802.0
+
+
+def test_permission_answer_keeps_the_task_start() -> None:
+ term = _pane()
+ _submit(term, 100.0)
+ stamp(term, "asking", now=800.0)
+ _submit(term, 801.0)
+ stamp(term, "working", now=802.0)
+ assert observed(term, now=803.0).since == 100.0
+
+
+def test_unknown_adopted_task_never_claims_observer_uptime() -> None:
+ term = _pane()
+ term.adopted_generation = term.process_generation
+ stamp(term, "working", now=1000.0)
+ assert observed(term, now=1001.0).since == 0.0
+
+
[email protected]("value", [None, "bad", -1, True, float("nan"), float("inf")])
+def test_legacy_or_invalid_snapshot_clock_is_unknown(value: object) -> None:
+ restored = SnapshotTerminal.from_dict(
+ {"name": "T1", "agent": "codex", "work_started_at": value}
+ )
+ assert restored is not None
+ assert restored.work_started_at == 0.0
+
+
+def _record(home: Path, agent: str, *, complete: bool = False) -> None:
+ if agent == "codex":
+ path = home / "sessions" / "2026" / "10" / "01" / "rollout-clock-test.jsonl"
+ rows = [
+ {"type": "session_meta", "payload": {"id": "clock-test"}},
+ {
+ "timestamp": "2026-10-01T18:00:00Z",
+ "type": "response_item",
+ "payload": {
+ "type": "message",
+ "role": "user",
+ "content": [{"type": "input_text", "text": "Fix the login bug"}],
+ },
+ },
+ {
+ "timestamp": "2026-10-01T18:00:09Z",
+ "type": "response_item",
+ "payload": {
+ "type": "message",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": "Checking"}],
+ },
+ },
+ ]
+ if complete:
+ rows.append(
+ {
+ "timestamp": "2026-10-01T18:40:00Z",
+ "type": "event_msg",
+ "payload": {"type": "task_complete"},
+ }
+ )
+ else:
+ path = home / "projects" / "example" / "clock-test.jsonl"
+ rows = [
+ {
+ "timestamp": "2026-10-01T18:00:00Z",
+ "type": "user",
+ "message": {"role": "user", "content": "Fix the login bug"},
+ },
+ {
+ "timestamp": "2026-10-01T18:00:09Z",
+ "type": "assistant",
+ "message": {
+ "id": "m1",
+ "role": "assistant",
+ "content": [{"type": "tool_use", "id": "tool1", "name": "Read", "input": {}}],
+ },
+ },
+ {
+ "timestamp": "2026-10-01T18:40:00Z",
+ "type": "user",
+ "message": {
+ "role": "user",
+ "content": [
+ {"type": "tool_result", "tool_use_id": "tool1", "content": "result"}
+ ],
+ },
+ },
+ ]
+ path.parent.mkdir(parents=True)
+ path.write_text("\n".join(json.dumps(row) for row in rows), encoding="utf-8")
+
+
[email protected]("agent", ["codex", "claude"])
+async def test_adoption_recovers_41_minutes_and_all_readers_agree(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ agent: str,
+) -> None:
+ _record(tmp_path, agent)
+ start = 1790877600.0
+ now = start + 41 * 60 + 34
+ monkeypatch.setattr(time, "time", lambda: now)
+ monkeypatch.setattr(ide, "account_home", lambda *_: tmp_path)
+ pool = FakeHostedPool()
+ pool.add_hosted("host-1", history_id="test", started_at=start - 3600)
+ registry = ide.Registry(pty_manager=pool)
+ term = _pane()
+ term.agent = agent
+ term.resume = ResumeHandle(kind=f"{agent}_session", id="clock-test", captured_at=start)
+ info = pool.hosted()[0]
+ assert await registry._adopt_one(pool, term, info)
+ stamp(term, "working", now=now - 12 * 60)
+ stamp(term, "working", now=now)
+ assert term.to_row()["activity_since"] == start
+ assert term.to_dict()["activity_since"] == start
+ assert now - term.reading().since == 41 * 60 + 34
+
+ # The websocket diff must carry the same corrected clock as REST.
+ class RegistryView:
+ sessions = [type("SessionView", (), {"id": "ws", "terminals": [term]})()]
+
+ assert ActivityFeed().changes(RegistryView())[0]["activity_since"] == start
+
+
+def test_finished_record_does_not_resurrect_an_old_task(tmp_path: Path) -> None:
+ _record(tmp_path, "codex", complete=True)
+ assert recover_start("codex", "clock-test", tmp_path) == 0.0
+
+
+def test_latest_task_does_not_inherit_an_older_tasks_time() -> None:
+ events = [
+ {"kind": "user_message", "ts_ms": 100_000},
+ {"kind": "turn_started", "ts_ms": 105_000},
+ {"kind": "turn_finished", "ts_ms": 200_000},
+ {"kind": "user_message", "ts_ms": 900_000},
+ {"kind": "turn_started", "ts_ms": 910_000},
+ ]
+ assert active_start(events) == 900.0
+
+
[email protected]("same_process", [True, False])
+async def test_snapshot_fallback_is_bound_to_the_hosted_process(same_process: bool) -> None:
+ original = _pane()
+ _submit(original, 100.0)
+ saved = SnapshotTerminal.from_dict(original.to_snapshot().to_dict())
+ assert saved is not None
+ restored = _pane()
+ restored.work_started_at = saved.work_started_at
+ restored.work_pty_id = saved.work_pty_id
+ restored.pty_id = "host-1" if same_process else "replacement"
+ await ide.Registry._recover_work_start(restored)
+ assert restored.work_started_at == (100.0 if same_process else 0.0)