The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(onboarding): deleting the onboarding chat ends its run only after the delete, on every copy
alt-glitch1ba5dab13b1c
diff --git a/agent/onboarding_record.py b/agent/onboarding_record.pyindex cf155e7a433..8a7af02d285 100644--- a/agent/onboarding_record.py+++ b/agent/onboarding_record.py@@ -47,6 +47,12 @@ def _ends_last_open_run(db, session_id: str, event: Event) -> bool:return not is_active(after) and all(sid == session_id for sid in open_session_ids(db))+def _announce(run_id: str | None, session_id: str, outcome: str) -> None:+ ended = {"run_id": run_id or "", "stored_session_id": session_id, "outcome": outcome}+ for listener in _ended_listeners:+ listener(ended)++def _transition(db, session_id: str, event: Event) -> Step | None:"""Apply *event* and write the result in one database transaction at the compression tip, so Skipsetup pressed while a card answer is being applied is never overwritten by the older copy, and an id@@ -69,10 +75,7 @@ def _transition(db, session_id: str, event: Event) -> Step | None:step = holder.get("step")# Told before the flag write, which can fail: the record already says the run ended.if step is not None and holder["was_active"] and not is_active(step.record):- ended = {"run_id": step.record.get("run_id") or "", "stored_session_id": session_id,- "outcome": step.record["ended_by"]}- for listener in _ended_listeners:- listener(ended)+ _announce(step.record.get("run_id"), session_id, step.record["ended_by"])if step is not None and not is_active(step.record) and active_session_id(db) is None:_close_install_flag() # no-op unless a concurrent change ended the run after the check abovereturn step@@ -129,12 +132,30 @@ def active_session_id(db) -> str | None:return next(iter(open_session_ids(db)), None)-def end_before_delete(db, session_id: str) -> None:- """Deleting the onboarding chat ends its run first (``deleted``), so the install flag closes and the- next launch does not open a fresh run. Only the compression tip holds the live run: deleting a- parent keeps the tip, and the parent's copy is a stale one."""- if (db.resolve_resume_session_id(session_id) or session_id) == session_id and is_active(load(db, session_id)):- advance(db, session_id, End("deleted"))+def delete_chat(db, session_id: str, delete: Callable[[], bool]) -> bool:+ """Run *delete*; when it removed the chat holding the live run, end that run (``deleted``) on every+ compression copy, tell windows once and close the install flag. Only the compression tip holds the+ live run, so deleting an older copy ends nothing."""+ record = load(db, session_id)+ live = is_active(record) and (db.resolve_resume_session_id(session_id) or session_id) == session_id+ if not delete():+ return False+ if live:+ # Each older copy is written on its own row: a tip-routed write would land every copy on the+ # newest one left.+ for sid in db.session_ids_with_model_config_key(KEY) if record.get("run_id") else ():+ if ((older := load(db, sid)) or {}).get("run_id") == record["run_id"]:+ db.patch_session_model_config(sid, {KEY: _end_deleted(older)})+ _announce(record.get("run_id"), session_id, "deleted")+ if active_session_id(db) is None:+ _close_install_flag()+ return True+++def _end_deleted(current: Any) -> Any:+ if not is_active(current):+ return current+ return apply(current, End("deleted"), Facts.from_stored(current["facts"]), now=time.time()).recorddef observe_tool_result(agent, name: str, args: Mapping[str, Any], result: Any) -> Any:diff --git a/tests/tui_gateway/test_onboarding_endings.py b/tests/tui_gateway/test_onboarding_endings.pynew file mode 100644index 00000000000..e9836fba66c--- /dev/null+++ b/tests/tui_gateway/test_onboarding_endings.py@@ -0,0 +1,58 @@+"""Deleting the onboarding chat: the run ends only once the delete succeeded, on every compression copy."""++from __future__ import annotations++from pathlib import Path++import pytest++from agent import onboarding_record+from agent.onboarding_flow import End, Facts+from hermes_cli.config import read_user_config_raw+from tui_gateway import server++FACTS = Facts(os="macos", arch="arm64", machine_kind="Mac", plugins=())+++def db(tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(server, "_hermes_home", str(home))+ monkeypatch.setattr(server, "_db", None)+ db = server._get_db()+ db.create_session("onb", "desktop")+ onboarding_record.start(db, "onb", FACTS)+ return db+++def ended(monkeypatch) -> list[dict]:+ told: list[dict] = []+ monkeypatch.setattr(onboarding_record, "_ended_listeners", [told.append])+ return told+++def _flag(db) -> bool:+ return read_user_config_raw(Path(server._hermes_home) / "config.yaml")["onboarding"]["run"]+++def test_a_refused_delete_leaves_the_run_going(db, ended):+ assert onboarding_record.delete_chat(db, "onb", lambda: False) is False++ assert onboarding_record.active_session_id(db) == "onb" and _flag(db) is True and ended == []+++def test_deleting_the_newest_copy_ends_the_run_on_every_copy(db, ended):+ for parent, child in (("onb", "mid"), ("mid", "tip")):+ db.publish_compression_child(parent_session_id=parent, child_session_id=child, source="desktop",+ messages=[{"role": "user", "content": "summary"}],+ require_compression_lease=False)++ assert onboarding_record.delete_chat(db, "tip", lambda: db.delete_session("tip"))++ assert onboarding_record.active_session_id(db) is None and _flag(db) is False+ assert [onboarding_record.load(db, sid)["ended_by"] for sid in ("onb", "mid")] == ["deleted", "deleted"]+ assert [(e["stored_session_id"], e["outcome"]) for e in ended] == [("tip", "deleted")]diff --git a/tests/tui_gateway/test_onboarding_session.py b/tests/tui_gateway/test_onboarding_session.pyindex 1467756a88d..5ac5961562e 100644--- a/tests/tui_gateway/test_onboarding_session.py+++ b/tests/tui_gateway/test_onboarding_session.py@@ -225,7 +225,7 @@ def test_a_compression_rotation_carries_the_run_record(root):# The parent keeps its active copy; the run is read at the tip, so skipping the child ends it.assert onboarding_record.active_session_id(db) == "child"# Deleting the parent keeps the tip, so the run stays in progress there.- onboarding_record.end_before_delete(db, "parent")+ assert onboarding_record.delete_chat(db, "parent", lambda: db.delete_session("parent"))assert onboarding_record.active_session_id(db) == "child"onboarding_record.advance(db, "child", End())assert onboarding_record.active_session_id(db) is Nonediff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex 273767894e6..c83b0ef4e4d 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -1172,7 +1172,7 @@ def _(rid, params: dict, session: dict) -> dict:@method("session.delete")def _(rid, params: dict) -> dict:"""Delete a stored session + transcripts; refused while live here (FK trips on the agent's next flush)."""- from agent.onboarding_record import end_before_delete+ from agent.onboarding_record import delete_chatfrom hermes_state_errors import SessionActiveWriteGuardError # body runs on server.py globalsif not (target := params.get("session_id", "")):@@ -1188,8 +1188,8 @@ def _(rid, params: dict) -> dict:return _db_unavailable_error(rid, code=5036)try:home = Path(profile_home) if profile_home is not None else get_hermes_home()- end_before_delete(db, target)- deleted = db.delete_session(target, sessions_dir=home / "sessions", exclude_active_write_guards=True)+ deleted = delete_chat(db, target, lambda: db.delete_session(+ target, sessions_dir=home / "sessions", exclude_active_write_guards=True))except SessionActiveWriteGuardError:return _err(rid, 4023, "cannot delete an active session")except Exception as e: