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.

feat(ide): resume the conversation a Claude pane is on now, not its launch id

rubenluetke10-beep2c5d10b1b87f
diff --git a/docs/os-parity.md b/docs/os-parity.md
index 6967397f41..d9d584226a 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -33,6 +33,14 @@ turn the power cut interrupted (measured: killed at step 26 of 30, resumed to
every OS; it depends only on login autostart, which is on by default on
Windows, macOS and Linux (and a no-op on a headless host).
+Which conversation a Claude pane is on is tracked the way Herdr tracks it: each
+pane is launched with `--settings` adding a `SessionStart` hook
+(`jarvis/agentic_ide/claude_session_hook.py`, stdlib only, forward-slash
+command that runs under bash or cmd) that records every conversation start,
+including `/clear`, `/resume` and compaction, so a reboot resumes the current
+one rather than the launch id (herdrdev/herdr#4059). Verified live on Windows
+with Claude Code 2.1.283; POSIX runs the same script through `sys.executable`.
+
"Rebooted" is measured, not guessed: the host records the machine's boot time
(`psutil.boot_time()`, all three OSes), and a host whose process is alive in
this boot but slow to answer raises `HostUnreachable` — the app waits instead
diff --git a/docs/product/extend-and-automate/agentic-ide.md b/docs/product/extend-and-automate/agentic-ide.md
index 24cc11180f..0878ac6d0a 100644
--- a/docs/product/extend-and-automate/agentic-ide.md
+++ b/docs/product/extend-and-automate/agentic-ide.md
@@ -162,7 +162,7 @@ to them depends on what ended:
| What happened | What the agents do | What you see next time |
|---|---|---|
| You closed the app, or it crashed or restarted | They keep working | The last open workspaces come back by themselves in the same layout, with the same focused pane, and each pane shows what its agent printed meanwhile |
-| The computer was turned off or restarted | They stopped with the machine | After you sign in, Jarvis starts again (login autostart is on by default) and brings every agent that was running back on its own conversation. A Claude Code agent that was cut off in the middle of a task finishes it by itself (the CLI's own interrupted-turn resume); a finished one stays finished. Other CLIs come back holding their conversation at their prompt. Jarvis never types anything into a pane |
+| The computer was turned off or restarted | They stopped with the machine | After you sign in, Jarvis starts again (login autostart is on by default) and brings every agent that was running back on its own conversation. A Claude Code agent that was cut off in the middle of a task finishes it by itself (the CLI's own interrupted-turn resume); a finished one stays finished. Other CLIs come back holding their conversation at their prompt. Jarvis never types anything into a pane. If you ran `/clear` or `/resume` inside a Claude Code pane, it is the conversation you switched to that comes back, not the one the pane started with |
| An agent ended by itself (for example `/exit`) | It stays ended | The pane comes back and starts when you open it |
| You closed every workspace before quitting | Nothing runs | Nothing reopens by itself; the workspaces stay in the sidebar |
| You pressed **Stop all agents** in the Agents panel | Every agent in every workspace ends | Same as closing every workspace |
diff --git a/jarvis/agentic_ide/agent_sessions.py b/jarvis/agentic_ide/agent_sessions.py
index 94e98f51a0..fd97b1a8ef 100644
--- a/jarvis/agentic_ide/agent_sessions.py
+++ b/jarvis/agentic_ide/agent_sessions.py
@@ -305,6 +305,17 @@ _NATIVE_RESUME_ENV: dict[str, dict[str, str]] = {
}
+def reports_session_starts(agent: str) -> bool:
+ """Does ``agent`` report every conversation it starts (Claude Code's hook)?
+
+ True for Claude Code and every launch profile built on it; their current
+ conversation is tracked by :mod:`.pane_sessions` rather than trusted from
+ the launch id.
+ """
+ adapter = _adapter_for(agent)
+ return adapter is not None and adapter.kind == "claude_session"
+
+
def resume_env(agent: str) -> dict[str, str]:
"""Extra environment that lets ``agent`` finish an interrupted turn itself."""
adapter = _adapter_for(agent)
diff --git a/jarvis/agentic_ide/claude_session_hook.py b/jarvis/agentic_ide/claude_session_hook.py
new file mode 100644
index 0000000000..5d9ff6bf8f
--- /dev/null
+++ b/jarvis/agentic_ide/claude_session_hook.py
@@ -0,0 +1,79 @@
+"""Claude Code ``SessionStart`` hook: remember which conversation a pane is on.
+
+Why this exists: a pane is resumed after a reboot through the conversation id
+it was launched with (``--session-id``). But that id is not stable for the
+life of the pane — ``/clear`` starts a new conversation, ``/resume`` switches
+to another, and compaction can roll over to a fresh one. Resuming the launch
+id afterwards brings back an OLD conversation, which is exactly the failure
+Herdr hit and fixed (herdrdev/herdr#4059) by recording the id from this hook
+on EVERY session start, whatever its source.
+
+Claude Code runs this script with the hook payload as JSON on stdin; the pane
+it belongs to is named by ``JARVIS_PANE_ID`` in the environment Jarvis gave the
+CLI, and ``JARVIS_PANE_SESSIONS_DIR`` says where to write. One small JSON file
+per pane, written atomically; the registry reads it before saving and before
+resuming (:mod:`jarvis.agentic_ide.session`).
+
+Deliberately stdlib-only and run as a plain script (not ``python -m``), so it
+starts in tens of milliseconds and cannot slow the CLI's startup down, and it
+never fails loudly: a hook that errors would print into the agent's pane.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import time
+from pathlib import Path
+
+PANE_ENV = "JARVIS_PANE_ID"
+DIR_ENV = "JARVIS_PANE_SESSIONS_DIR"
+
+
+def _safe_name(pane_id: str) -> str:
+ return "".join(ch for ch in pane_id if ch.isalnum() or ch in "-_")[:80]
+
+
+def record(pane_id: str, directory: Path, payload: dict) -> Path | None:
+ """Write the pane's current conversation id; None when there is nothing to write."""
+ session_id = str(payload.get("session_id") or "").strip()
+ name = _safe_name(pane_id)
+ if not session_id or not name:
+ return None
+ directory.mkdir(parents=True, exist_ok=True)
+ target = directory / f"{name}.json"
+ tmp = directory / f"{name}.{os.getpid()}.tmp"
+ tmp.write_text(
+ json.dumps(
+ {
+ "session_id": session_id,
+ "source": str(payload.get("source") or ""),
+ "transcript_path": str(payload.get("transcript_path") or ""),
+ "at": time.time(),
+ }
+ ),
+ encoding="utf-8",
+ )
+ os.replace(tmp, target)
+ return target
+
+
+def main() -> int:
+ pane_id = os.environ.get(PANE_ENV, "")
+ directory = os.environ.get(DIR_ENV, "")
+ if not pane_id or not directory:
+ return 0
+ try:
+ payload = json.loads(sys.stdin.read() or "{}")
+ if isinstance(payload, dict):
+ record(pane_id, Path(directory), payload)
+ except Exception as exc: # noqa: BLE001 - a hook must never break the agent's start
+ # Quiet on purpose, but not silent: stderr lands in Claude Code's own
+ # hook log (``--debug``), never on the pane.
+ print(f"jarvis session hook: {exc}", file=sys.stderr)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/jarvis/agentic_ide/pane_sessions.py b/jarvis/agentic_ide/pane_sessions.py
new file mode 100644
index 0000000000..e7d9cb2c22
--- /dev/null
+++ b/jarvis/agentic_ide/pane_sessions.py
@@ -0,0 +1,112 @@
+"""Which conversation each Claude Code pane is on RIGHT NOW (Herdr's rule).
+
+A pane is resumed after a reboot through its conversation id. The id it was
+launched with goes stale the moment the user runs ``/clear`` or ``/resume`` in
+the pane (or compaction rolls it over), so it is re-read from a Claude Code
+``SessionStart`` hook (:mod:`.claude_session_hook`) that fires on every one of
+those, whatever its source — the fix Herdr shipped for the same bug
+(herdrdev/herdr#4059).
+
+Wiring, all at spawn time and all additive:
+
+* ``--settings <file>`` loads the hook as an EXTRA settings source; the user's
+ own settings and hooks stay exactly as they are,
+* ``JARVIS_PANE_ID`` / ``JARVIS_PANE_SESSIONS_DIR`` in the pane's environment
+ tell the hook whom it is reporting for and where to write.
+
+Only Claude Code has such a hook; other CLIs keep the id Jarvis discovered for
+them (``agent_sessions``).
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from pathlib import Path
+
+from loguru import logger
+
+from .claude_session_hook import DIR_ENV, PANE_ENV
+
+
+def _state_dir() -> Path:
+ from jarvis.core.instance import current_instance
+ from jarvis.core.paths import user_data_dir
+
+ suffix = current_instance().state_file_suffix
+ return user_data_dir() / "agentic_ide" / f"pane_sessions{suffix}"
+
+
+def _interpreter() -> Path:
+ """A console interpreter: the hook reads stdin, which pythonw does not have."""
+ exe = Path(sys.executable)
+ console = exe.with_name("python.exe")
+ return console if exe.name.lower() == "pythonw.exe" and console.exists() else exe
+
+
+def settings_file() -> Path:
+ """The extra settings file carrying the hook, written when it changes."""
+ script = Path(__file__).with_name("claude_session_hook.py")
+ # Forward slashes: Claude Code runs hook commands through bash on some
+ # installs and cmd on others; a quoted forward-slash path works in both.
+ command = f'"{_interpreter().as_posix()}" "{script.as_posix()}"'
+ settings = {
+ "hooks": {
+ "SessionStart": [{"hooks": [{"type": "command", "command": command, "timeout": 10}]}]
+ }
+ }
+ target = _state_dir().parent / "claude_session_hook.settings.json"
+ text = json.dumps(settings, indent=2)
+ try:
+ if not target.exists() or target.read_text(encoding="utf-8") != text:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ tmp = target.with_name(target.name + f".{os.getpid()}.tmp")
+ tmp.write_text(text, encoding="utf-8")
+ os.replace(tmp, target)
+ except OSError as exc:
+ logger.warning("Agentic IDE: session hook settings not written: {}", exc)
+ return target
+
+
+def launch_wiring(pane_id: str) -> tuple[tuple[str, ...], dict[str, str]]:
+ """Extra argv and environment that make a Claude pane report its conversation."""
+ return (
+ ("--settings", str(settings_file())),
+ {PANE_ENV: pane_id, DIR_ENV: str(_state_dir())},
+ )
+
+
+def latest_session(pane_id: str) -> tuple[str, float] | None:
+ """The conversation id the pane last started, and when; None if never reported."""
+ name = "".join(ch for ch in pane_id if ch.isalnum() or ch in "-_")[:80]
+ if not name:
+ return None
+ try:
+ data = json.loads((_state_dir() / f"{name}.json").read_text(encoding="utf-8"))
+ except (OSError, ValueError): # never reported (or a torn write): keep what we have
+ return None
+ session_id = str(data.get("session_id") or "").strip() if isinstance(data, dict) else ""
+ if not session_id:
+ return None
+ try:
+ at = float(data.get("at") or 0.0)
+ except (TypeError, ValueError): # a malformed stamp only costs the ordering hint
+ at = 0.0
+ return session_id, at
+
+
+def forget(pane_id: str) -> None:
+ """Drop a closed pane's record."""
+ name = "".join(ch for ch in pane_id if ch.isalnum() or ch in "-_")[:80]
+ if not name:
+ return
+ try:
+ (_state_dir() / f"{name}.json").unlink()
+ except FileNotFoundError: # never reported: nothing to drop
+ return
+ except OSError as exc:
+ logger.debug("Agentic IDE: pane session record not removed: {}", exc)
+
+
+__all__ = ["forget", "latest_session", "launch_wiring", "settings_file"]
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index 17e9a3c619..1d7cc0f213 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -87,6 +87,7 @@ from . import (
layout_tree,
library,
opening,
+ pane_sessions,
prompt_history,
recap_engine,
remote,
@@ -101,6 +102,7 @@ from .agent_sessions import (
fork_argv,
has_conversation,
launch_extra,
+ reports_session_starts,
resume_argv,
resume_env,
)
@@ -3260,6 +3262,31 @@ class Registry:
await self._close_locked(workspace_id)
return count
+ def _sync_hooked_session(self, term: Terminal) -> None:
+ """Adopt the conversation id the pane's session hook last reported.
+
+ Runs off the loop (one small file read). A pane whose hook never fired
+ keeps the id it was launched with.
+ """
+ latest = pane_sessions.latest_session(term.history_id)
+ if latest is None:
+ return
+ session_id, at = latest
+ if term.resume is not None and term.resume.id == session_id:
+ return
+ term.resume = ResumeHandle("claude_session", session_id, at or time.time())
+ logger.info(
+ "Agentic IDE: {} is now on conversation {} (reported by its session hook)",
+ term.name,
+ session_id[:8],
+ )
+
+ def _sync_hooked_sessions(self) -> None:
+ for session in list(self._sessions.values()):
+ for term in list(session.terminals):
+ if not term.computer_id and reports_session_starts(term.agent):
+ self._sync_hooked_session(term)
+
def runtime_status(self) -> dict[str, Any]:
"""Where the agents run right now, for the UI and ``jarvis api``.
@@ -3351,6 +3378,7 @@ class Registry:
than the one the previous save stored.
"""
async with self._persist_lock:
+ await asyncio.to_thread(self._sync_hooked_sessions)
snapshot = self.snapshot()
if snapshot is None:
return
@@ -3917,6 +3945,10 @@ class Registry:
# meant a dozen stalls interleaved with their own spawns. It only ever
# runs on a pane that HAS a handle, which is why the restore path was
# the only one that ever felt it.
+ if not term.computer_id and reports_session_starts(term.agent):
+ # The conversation the pane is on NOW — after a ``/clear`` or a
+ # ``/resume`` inside it that is not the id it was launched with.
+ await asyncio.to_thread(self._sync_hooked_session, term)
home = account_home(term.agent, term.account)
continuing = resume_argv(term.agent, term.resume)
# A remote pane's history lives on that computer; its handle was
@@ -4148,6 +4180,16 @@ class Registry:
# without this proof the agent worked on while every list
# filed it under "done" (maintainer report 2026-09-29).
term.adopted_generation = term.process_generation
+ if not term.computer_id and reports_session_starts(term.agent):
+ # Herdr's rule: the pane reports every conversation it starts, so a
+ # reboot resumes the one it was really on (``pane_sessions``).
+ wiring_argv, wiring_env = await asyncio.to_thread(
+ pane_sessions.launch_wiring, term.history_id
+ )
+ # Right behind the binary, so resume arguments stay last.
+ argv = (argv[0], *wiring_argv, *argv[1:])
+ base = env if env is not None else _without_parent_agent_session(dict(os.environ))
+ env = {**(base if base is not None else os.environ), **wiring_env}
# The provider/account gate is acquired BEFORE the machine-wide gate.
# A Codex pane waiting on shared state must never occupy a CPU slot that
diff --git a/tests/unit/agentic_ide/conftest.py b/tests/unit/agentic_ide/conftest.py
index 7247b05279..9dc3106d15 100644
--- a/tests/unit/agentic_ide/conftest.py
+++ b/tests/unit/agentic_ide/conftest.py
@@ -55,6 +55,22 @@ def _resume_store_in_tmp(
return target
[email protected](autouse=True)
+def _pane_sessions_in_tmp(
+ tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch
+) -> Path:
+ """Point the panes' session-hook records (and the hook settings) at a temp dir.
+
+ A spawned Claude pane writes its hook settings file; without this every
+ test that spawns one would write into the developer's own data folder.
+ """
+ from jarvis.agentic_ide import pane_sessions
+
+ target = tmp_path_factory.mktemp("pane-sessions") / "pane_sessions"
+ monkeypatch.setattr(pane_sessions, "_state_dir", lambda: target)
+ return target
+
+
@pytest.fixture(autouse=True)
def _ui_prefs_in_tmp(
tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch
diff --git a/tests/unit/agentic_ide/test_account_spawn.py b/tests/unit/agentic_ide/test_account_spawn.py
index bbbcd4898c..cd8e3f5626 100644
--- a/tests/unit/agentic_ide/test_account_spawn.py
+++ b/tests/unit/agentic_ide/test_account_spawn.py
@@ -359,6 +359,10 @@ async def test_a_pane_on_the_builtin_account_spawns_exactly_as_it_always_did(
await _attach(registry, registry.session.terminals[0].name)
env = _env_of(fake_pty)
assert env is not None
+ # Plus the pane's session-hook wiring (``pane_sessions``): who it is and
+ # where its hook reports — additive, never an account redirection.
+ assert env.pop("JARVIS_PANE_ID") == registry.session.terminals[0].history_id
+ assert env.pop("JARVIS_PANE_SESSIONS_DIR")
assert env == {**os.environ, "CLAUDE_CODE_DISABLE_MOUSE_CLICKS": "1"}
diff --git a/tests/unit/agentic_ide/test_pane_sessions.py b/tests/unit/agentic_ide/test_pane_sessions.py
new file mode 100644
index 0000000000..58a709ab52
--- /dev/null
+++ b/tests/unit/agentic_ide/test_pane_sessions.py
@@ -0,0 +1,113 @@
+"""Herdr's rule: resume the conversation a pane is on NOW, not the one it began with.
+
+``/clear``, ``/resume`` or compaction inside a Claude Code pane start a new
+conversation id. The pane reports each one through a ``SessionStart`` hook
+(verified live against Claude Code 2.1.283: the launch id arrived, and after
+``/clear`` the new id arrived), and the registry resumes that one.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import time
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import claude_session_hook, pane_sessions, resume_store
+from jarvis.agentic_ide import session as ide
+from jarvis.agentic_ide.agent_sessions import ResumeHandle
+from tests.unit.agentic_ide.test_pty_host_adoption import ConnectRecorder, FakeHostedPool
+
+
[email protected](autouse=True)
+def _isolated(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "lad"))
+ monkeypatch.setattr(ide, "agent_argv", lambda name: (f"/usr/bin/{name}",))
+ monkeypatch.setattr(ide, "has_conversation", lambda agent, handle, home=None: True)
+
+
+def _report(pane_id: str, session_id: str, source: str = "clear") -> None:
+ _argv, env = pane_sessions.launch_wiring(pane_id)
+ claude_session_hook.record(
+ pane_id,
+ Path(env[claude_session_hook.DIR_ENV]),
+ {"session_id": session_id, "source": source},
+ )
+
+
+def test_the_hook_records_and_the_registry_reads_back() -> None:
+ assert pane_sessions.latest_session("pane-1") is None
+ _report("pane-1", "first", "startup")
+ _report("pane-1", "second", "clear")
+ latest = pane_sessions.latest_session("pane-1")
+ assert latest is not None and latest[0] == "second"
+ pane_sessions.forget("pane-1")
+ assert pane_sessions.latest_session("pane-1") is None
+
+
+def test_the_settings_file_adds_one_session_start_hook() -> None:
+ argv, env = pane_sessions.launch_wiring("pane-9")
+ assert argv[0] == "--settings"
+ settings = json.loads(Path(argv[1]).read_text(encoding="utf-8"))
+ (entry,) = settings["hooks"]["SessionStart"]
+ command = entry["hooks"][0]["command"]
+ assert "claude_session_hook.py" in command and "\\" not in command
+ assert env[claude_session_hook.PANE_ENV] == "pane-9"
+
+
+async def test_a_claude_pane_is_launched_reporting_its_conversations(tmp_path: Path) -> None:
+ pool = FakeHostedPool()
+ registry = ide.Registry(pty_manager=pool)
+ session = await registry.start(str(tmp_path), [{"agent": "claude"}])
+ term = session.terminals[0]
+
+ async def noop(_value: object) -> None:
+ return None
+
+ await registry.attach("pane:" + term.history_id, 100, 30, noop, noop, workspace_id=session.id)
+ spawn = pool.spawns[-1]
+ assert "--settings" in spawn["argv"]
+ assert (spawn["env"] or {}).get(claude_session_hook.PANE_ENV) == term.history_id
+
+
+async def test_a_reboot_resumes_the_conversation_after_clear(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ now = time.time()
+ workspace = resume_store.SnapshotWorkspace(
+ session_id="ide_hooked01",
+ folder=str(tmp_path),
+ terminals=[
+ resume_store.SnapshotTerminal(
+ key="t1",
+ name="T1",
+ agent="claude",
+ history_id="hist-1",
+ resume=ResumeHandle("claude_session", "launch-id", 1.0),
+ running=True,
+ )
+ ],
+ saved_at=now,
+ )
+ resume_store.save(
+ resume_store.Snapshot(
+ saved_at=now, workspaces=[workspace], active_session_id="ide_hooked01"
+ )
+ )
+ # Before the power cut the user ran /clear in the pane.
+ _report("hist-1", "after-clear-id")
+ pool = FakeHostedPool()
+ monkeypatch.setattr(ide, "_connect_pty_host", ConnectRecorder(pool))
+
+ registry = ide.Registry()
+ await registry.boot_restore()
+ for _ in range(100):
+ if pool.spawns:
+ break
+ await asyncio.sleep(0.02)
+
+ argv = " ".join(pool.spawns[0]["argv"])
+ assert "--resume after-clear-id" in argv, argv
+ assert "launch-id" not in argv