Skip to content

The agent that grows with you

fix(desktop): scope tool changes and commit rebuild ownership together

Teknium12891ea3bdd2
diff --git a/evals/desktop_bug_campaign/persistence_live.py b/evals/desktop_bug_campaign/persistence_live.py
index 7cf442059ac..d372a48c61c 100644
--- a/evals/desktop_bug_campaign/persistence_live.py
+++ b/evals/desktop_bug_campaign/persistence_live.py
@@ -20,7 +20,10 @@ def main():
parser.add_argument('--port', type=int, default=18020)
parser.add_argument('--compress', action='store_true')
parser.add_argument('--reset', action='store_true')
+ parser.add_argument('--failure', action='store_true', help='inject one model-config preparation failure')
+ parser.add_argument('--observe', action='store_true', help='inspect ownership without injecting failure')
args = parser.parse_args()
+ observe = args.observe or args.failure
args.out.mkdir(parents=True, exist_ok=True)
home = Path(tempfile.mkdtemp(prefix='persistence-live-'))
profile = home / 'profiles' / 'worker'
@@ -66,6 +69,9 @@ def main():
env.update(HERMES_HOME=str(home), HOME=str(home / 'os-home'), HERMES_DASHBOARD_SESSION_TOKEN='persistence-fixture-token', HERMES_IGNORE_RULES='1', PYTHONPATH=str(args.repo), OPENAI_API_KEY='local-fixture')
log = (args.out / 'serve.log').open('w')
cmd = [sys.executable, '-m', 'hermes_cli.main', 'serve', '--isolated', '--port', str(args.port)]
+ if observe:
+ cmd = [sys.executable, str(Path(__file__).with_name('rebuild_observer.py')),
+ 'serve', '--isolated', '--port', str(args.port)]
proc = subprocess.Popen(cmd, cwd=args.repo, env=env, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)
transcript = []
result = {'home': str(home), 'command': cmd, 'sha': subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=args.repo, text=True).strip()}
@@ -111,6 +117,11 @@ def main():
result['created'] = created
sid, key = created['session_id'], created['stored_session_id']
turn(sid, 'PERSISTENCE_BEFORE')
+ launch_before = (home / 'config.yaml').read_bytes()
+ if observe:
+ result['ownership_before'] = rpc('probe.ownership', {'session_id': sid})
+ if args.failure:
+ (home / 'fail-rebuild').touch()
if args.compress:
for i in range(12):
turn(sid, f'Historical note {i}: ' + ('The worker keeps the project history and decisions in its own profile. ' * 100))
@@ -119,15 +130,29 @@ def main():
result['generations'] = db.execute('SELECT role, content, GROUP_CONCAT(active), COUNT(*) FROM messages WHERE session_id=? GROUP BY role, content HAVING COUNT(*)>1', (key,)).fetchall()
result['duplicate_active_groups'] = db.execute('SELECT COUNT(*) FROM (SELECT role, content FROM messages WHERE session_id=? AND active=1 GROUP BY role, content HAVING COUNT(*)>1)', (key,)).fetchone()[0]
if args.reset:
- result['reset'] = rpc('tools.configure', {'session_id': sid, 'profile': 'worker', 'action': 'disable', 'names': ['terminal']})
+ try:
+ result['reset'] = rpc('tools.configure', {'session_id': sid, 'action': 'enable', 'names': ['web']})
+ except RuntimeError as exc:
+ if not args.failure or 'probe config read failure' not in str(exc):
+ raise
+ result['expected_failure'] = str(exc)
+ result['launch_config_unchanged'] = (home / 'config.yaml').read_bytes() == launch_before
+ result['worker_tools'] = yaml.safe_load((profile / 'config.yaml').read_text())['platform_toolsets']['cli']
else:
(profile / 'SOUL.md').write_text('Capabilities changed for the worker.\n')
+ if observe and args.reset:
+ result['ownership_after_failure'] = rpc('probe.ownership', {'session_id': sid})
turn(sid, 'PERSISTENCE_AFTER_REBUILD')
+ if observe and not args.reset:
+ result['ownership_after_failure'] = rpc('probe.ownership', {'session_id': sid})
result['stores'] = {}
for name, p in [('launch', home), ('worker', profile)]:
with sqlite3.connect(p / 'state.db') as db:
result['stores'][name] = db.execute('SELECT role, content, active FROM messages WHERE session_id=? ORDER BY id', (key,)).fetchall()
result['wrong_profile_writes'] = any('PERSISTENCE_AFTER_REBUILD' in str(row) for row in result['stores']['launch'])
+ if observe:
+ rpc('session.close', {'session_id': sid})
+ result['ownership_after_close'] = rpc('probe.ownership', {'session_id': sid})
finally:
proc.terminate()
try:
@@ -136,6 +161,7 @@ def main():
proc.kill()
proc.wait()
model.shutdown()
+ model.server_close()
log.close()
(args.out / 'wire.json').write_text(json.dumps(transcript, indent=2))
result['model_requests'] = requests
@@ -143,6 +169,14 @@ def main():
print(json.dumps({k: result[k] for k in ('sha', 'home', 'wrong_profile_writes', 'duplicate_active_groups') if k in result}, indent=2))
assert not result['wrong_profile_writes'], 'rebuild wrote the next turn to launch state.db'
assert any('PERSISTENCE_AFTER_REBUILD' in str(row) for row in result['stores']['worker'])
+ if args.reset:
+ assert result['launch_config_unchanged'], 'tools.configure changed launch config'
+ assert 'web' in result['worker_tools'], 'tools.configure did not change worker config'
+ if observe:
+ before, after = result['ownership_before'], result['ownership_after_failure']
+ assert before['owns_db'] and after['owns_db'], 'rebuild lost reachable DB owner'
+ assert (before['agent'] == after['agent']) is args.failure, 'unexpected replacement outcome'
+ assert str(profile / 'state.db') not in result['ownership_after_close']['refs'], 'teardown leaked profile DB ref'
if args.compress:
assert result['compression']['status'] == 'compressed'
assert result['generations'], 'compaction must retain archived generations'
diff --git a/evals/desktop_bug_campaign/rebuild_observer.py b/evals/desktop_bug_campaign/rebuild_observer.py
new file mode 100644
index 00000000000..e25562a4de2
--- /dev/null
+++ b/evals/desktop_bug_campaign/rebuild_observer.py
@@ -0,0 +1,44 @@
+"""Probe-only serve bootstrap: observe real ownership and inject config-read failure.
+
+Not imported by production. The failure seam raises once during model-target
+preparation; agent construction, rebuild predicates, WebSocket dispatch, and
+SessionDB teardown remain real.
+"""
+import inspect
+import os
+from pathlib import Path
+
+from tui_gateway import server
+import hermes_state_registry as registry
+
+
+original_target = server._config_model_target
+marker = Path(os.environ["HERMES_HOME"]) / "fail-rebuild"
+
+
+def config_target():
+ if marker.exists() and any(frame.function in {"_reset_session_agent", "_sync_bot_capabilities"}
+ for frame in inspect.stack()):
+ marker.unlink()
+ raise OSError("probe config read failure")
+ return original_target()
+
+
+server._config_model_target = config_target
+
+
+def ownership(rid, params):
+ session = server._sessions.get(params["session_id"])
+ agent = (session or {}).get("agent")
+ with registry._lock:
+ refs = {str(path): generation.refcount for path, generation in registry._generations.items()}
+ return server._ok(rid, {"agent": id(agent) if agent else None,
+ "owns_db": bool(getattr(agent, "_owns_session_db", False)),
+ "refs": refs})
+
+
+server._methods["probe.ownership"] = ownership
+
+if __name__ == "__main__":
+ from hermes_cli.main import main
+ main()
diff --git a/tests/tui_gateway/test_profile_rebuild_commit.py b/tests/tui_gateway/test_profile_rebuild_commit.py
new file mode 100644
index 00000000000..ff8fb987276
--- /dev/null
+++ b/tests/tui_gateway/test_profile_rebuild_commit.py
@@ -0,0 +1,80 @@
+"""Session-only tools ingress and rebuild failure preserve profile isolation."""
+import threading
+from types import SimpleNamespace
+
+import pytest
+import yaml
+
+
[email protected]("explicit_profile", [None, "default"])
+def test_tools_configure_uses_live_session_profile(tmp_path, monkeypatch, explicit_profile):
+ from tui_gateway import server
+ from hermes_constants import get_hermes_home
+
+ home = tmp_path / ".hermes"
+ profile = home / "profiles" / "worker"
+ profile.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
+ config = {"platform_toolsets": {"cli": ["terminal", "web"]}}
+ for path in (home, profile):
+ (path / "config.yaml").write_text(yaml.safe_dump(config))
+ launch_before = (home / "config.yaml").read_bytes()
+ seen = []
+ monkeypatch.setattr(server, "_reset_session_agent", lambda *_: seen.append(get_hermes_home()) or {})
+ monkeypatch.setitem(server._sessions, "profile-tools", {"profile_home": str(profile)})
+ params = {"session_id": "profile-tools", "action": "disable", "names": ["terminal"]}
+ if explicit_profile is not None:
+ params["profile"] = explicit_profile
+ response = server._methods["tools.configure"](1, params)
+ assert "error" not in response
+ assert (home / "config.yaml").read_bytes() == launch_before
+ assert "terminal" not in yaml.safe_load((profile / "config.yaml").read_text())["platform_toolsets"]["cli"]
+ assert seen == [profile]
+ assert get_hermes_home() == home
+
+
[email protected]("path", ["reset", "capabilities"])
[email protected]("has_agent_db", [True, False])
+def test_rebuild_preparation_failure_keeps_reachable_owner(tmp_path, monkeypatch, path, has_agent_db):
+ from tui_gateway import server
+ from hermes_state import SessionDB
+ from hermes_constants import get_hermes_home
+
+ home = tmp_path / ".hermes"
+ profile = home / "profiles" / "worker"
+ profile.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
+ db = SessionDB(db_path=profile / "state.db")
+ old = SimpleNamespace(_session_db=db if has_agent_db else None,
+ _owns_session_db=has_agent_db, _session_title_hint="Bot Chat")
+ session = {"agent": old, "profile_home": str(profile), "session_key": "profile-key",
+ "bot_caps_seen": "before", "source": "desktop", "cwd": str(tmp_path),
+ "history": [], "history_lock": threading.Lock(), "history_version": 0}
+ built = []
+ def make_agent(*_args, session_db=None, **_kwargs):
+ replacement = SimpleNamespace(_session_db=session_db, _owns_session_db=False)
+ built.append(replacement)
+ return replacement
+ def fail_config():
+ raise RuntimeError("preparation failed")
+ monkeypatch.setattr(server, "_make_agent", make_agent)
+ monkeypatch.setattr(server, "_config_model_target", fail_config)
+ monkeypatch.setattr("tools.bot_mode_probe.capability_fingerprint", lambda _: "after")
+ try:
+ if path == "reset":
+ with pytest.raises(RuntimeError, match="preparation failed"):
+ server._reset_session_agent("profile-tools", session)
+ else:
+ server._sync_bot_capabilities("profile-tools", session)
+ assert session["agent"] is old
+ assert old._owns_session_db is has_agent_db
+ assert not built, "prepare config before allocating a replacement"
+ assert get_hermes_home() == home
+ db.create_session("still-owned", "tui")
+ finally:
+ db.close()
+ for agent in built:
+ if agent._session_db is not db and agent._owns_session_db:
+ agent._session_db.close()
diff --git a/tui_gateway/agent_callbacks.py b/tui_gateway/agent_callbacks.py
index ad68f4a0a48..36f421b90b5 100644
--- a/tui_gateway/agent_callbacks.py
+++ b/tui_gateway/agent_callbacks.py
@@ -358,7 +358,7 @@ def _preview_restart_callbacks(parent: str, task_id: str) -> dict:
def _rebuild_session_agent(sid: str, session: dict, **kwargs):
- """Rebuild on the session's profile, transferring its DB ownership without acquiring a second ref.
+ """Prepare and install a replacement on the session's profile, then transfer DB ownership.
An unscoped _make_agent defaults to the launch store: named-profile Bot Chat turns then disappear
from the profile's replay even though they were successfully written to another database (#104079).
@@ -371,6 +371,8 @@ def _rebuild_session_agent(sid: str, session: dict, **kwargs):
opened = session_db is None and bool(profile_home)
scopes = _bind_build_profile_scopes(profile_home) if profile_home else None
try:
+ # Resolve fallible config before allocating a replacement or moving its handle.
+ config_model_seen = _config_model_target()
if opened:
session_db = _open_profile_session_db(profile_home)
agent = _make_agent(sid, session["session_key"], session_db=session_db, **kwargs)
@@ -384,17 +386,24 @@ def _rebuild_session_agent(sid: str, session: dict, **kwargs):
_release_build_profile_scopes(scopes)
# Only a DEDICATED handle carries ownership; the shared launch handle outlives every agent and
# _transfer_db_to_agent refuses it.
- owned = opened or bool(getattr(old_agent, "_owns_session_db", False))
- if owned and _transfer_db_to_agent(agent, session_db):
- if old_agent is not None:
- old_agent._owns_session_db = False
- elif opened:
- with contextlib.suppress(Exception):
- session_db.close()
+ with _sessions_lock:
+ session.update(agent=agent, config_model_seen=config_model_seen)
+ owned = opened or bool(getattr(old_agent, "_owns_session_db", False))
+ if owned and _transfer_db_to_agent(agent, session_db):
+ if old_agent is not None:
+ old_agent._owns_session_db = False
+ elif opened:
+ with contextlib.suppress(Exception):
+ session_db.close()
return agent
def _reset_session_agent(sid: str, session: dict) -> dict:
+ updates = dict(
+ attached_images=[], queued_prompt=None,
+ _queued_prompt_generation=int(session.get("_queued_prompt_generation", 0)) + 1,
+ edit_snapshots={}, image_counter=0, running=False, show_reasoning=_load_show_reasoning(),
+ tool_progress_mode=_load_tool_progress_mode(), tool_started_at={})
tokens = _set_session_context(session["session_key"])
try:
# /new is a full conversation boundary: session-scoped runtime overrides (/model,
@@ -408,12 +417,7 @@ def _reset_session_agent(sid: str, session: dict) -> dict:
context_cwd_is_launch_artifact=_context_cwd_is_launch_artifact(session))
finally:
_clear_session_context(tokens)
- session.update(
- agent=new_agent, config_model_seen=_config_model_target(), attached_images=[],
- queued_prompt=None,
- _queued_prompt_generation=int(session.get("_queued_prompt_generation", 0)) + 1,
- edit_snapshots={}, image_counter=0, running=False, show_reasoning=_load_show_reasoning(),
- tool_progress_mode=_load_tool_progress_mode(), tool_started_at={})
+ session.update(updates)
session.pop("queued_prompts", None)
with session["history_lock"]:
session["history"] = []
diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.py
index 7db1fe544e6..31a10dabd97 100644
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@ -980,6 +980,19 @@ def _(rid, params: dict) -> dict:
@_rpc("tools.configure", 5035)
def _(rid, params: dict) -> dict:
+ sid = params.get("session_id", "")
+ session = _sessions.get(sid)
+ # The client sends session_id, not profile; the live session is authoritative.
+ home = (session or {}).get("profile_home")
+ scopes = _bind_build_profile_scopes(home) if home else None
+ try:
+ return _configure_session_tools(rid, params, sid, session)
+ finally:
+ if scopes is not None:
+ _release_build_profile_scopes(scopes)
+
+
+def _configure_session_tools(rid, params: dict, sid: str, session) -> dict:
action = str(params.get("action", "") or "").strip().lower()
targets = [str(name).strip() for name in params.get("names", []) or [] if str(name).strip()]
if action not in {"disable", "enable"}:
@@ -996,8 +1009,6 @@ def _(rid, params: dict) -> dict:
tc._apply_toolset_change(cfg, "cli", toolset_targets, action)
missing_servers = tc._apply_mcp_change(cfg, mcp_targets, action) if mcp_targets else set()
hc.save_config(cfg)
- sid = params.get("session_id", "")
- session = _sessions.get(sid)
info = _reset_session_agent(sid, session) if session else None
enabled = sorted(tc._get_platform_tools(hc.load_config(), "cli", include_default_mcp_servers=False))
changed = [
diff --git a/tui_gateway/model_switch.py b/tui_gateway/model_switch.py
index 5b353033a72..770732b6514 100644
--- a/tui_gateway/model_switch.py
+++ b/tui_gateway/model_switch.py
@@ -280,7 +280,6 @@ def _sync_bot_capabilities(sid: str, session: dict) -> None:
finally:
_clear_session_context(tokens)
new_agent._session_title_hint = "Bot Chat"
- session.update(agent=new_agent, config_model_seen=_config_model_target())
_emit("notice", sid, {"message": "Capabilities updated — this bot's tools and prompt were refreshed."})
except Exception as e:
logger.warning("Bot capability sync failed for %s: %s", sid, e)
diff --git a/website/docs/developer-guide/session-storage.md b/website/docs/developer-guide/session-storage.md
index 36f4ed2fe26..9fb7da80f76 100644
--- a/website/docs/developer-guide/session-storage.md
+++ b/website/docs/developer-guide/session-storage.md
@@ -13,6 +13,10 @@ including when one `hermes serve` process serves several profiles. In-session
agent rebuilds (Bot Chat capability refresh and `tools.configure`) must retain
that session's database handle and bind its profile home during construction.
Releasing the outgoing agent must not close the handle inherited by its replacement.
+`tools.configure` resolves configuration from the live session's `profile_home`,
+even when the client supplies only `session_id`. Rebuilds prepare model configuration
+before allocating a replacement, then install the agent and transfer ownership
+together; preparation failure leaves the existing agent responsible for teardown.
In-place compaction archives old rows with `active=0` and inserts the retained
context as `active=1` rows. A protected message can therefore legitimately appear