The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(onboarding): the first-task answer completes the run, and every end is explicit
alt-glitch3568acf58069
diff --git a/agent/onboarding_flow.py b/agent/onboarding_flow.pyindex 2be3c1ca50a..9517da42a19 100644--- a/agent/onboarding_flow.py+++ b/agent/onboarding_flow.py@@ -17,8 +17,6 @@ from agent.onboarding_first_tasks import FIXED_ID, OWN_ID, card_options, pick_erPENDING, SHOWN, DONE, SKIPPED = "pending", "shown", "done", "skipped"ONBOARDING, COMPLETE, PHASE_SKIPPED = "onboarding", "complete", "skipped"CARD_TIMEOUT_S = 300-# Fallback end: no onboarding change for this long after the build card was reached.-QUIET_COMPLETE_S = 30 * 60MAX_PLUGINS = 5LAYOUT_OPTIONS = ({"id": "sidebar-left", "label": "Basic"}, {"id": "terminal-deck", "label": "Elite"})@@ -94,8 +92,11 @@ class Skipped:@dataclass(frozen=True)-class SkipAll:- pass+class End:+ """The run ended outside the model: ``skipped`` (Skip setup), ``replaced`` (a rerun opened a new+ run) or ``deleted`` (its chat is being deleted)."""++ outcome: str = "skipped"@dataclass(frozen=True)@@ -112,7 +113,7 @@ class Applied:result: Mapping[str, Any]-Event = Shown | Answered | Said | TimedOut | Recorded | Skipped | SkipAll | Done | Applied+Event = Shown | Answered | Said | TimedOut | Recorded | Skipped | End | Done | Applied@dataclass(frozen=True)@@ -199,15 +200,6 @@ def is_active(record: Mapping[str, Any] | None) -> bool:return bool(record) and record.get("phase") == ONBOARDING-def expire(record: dict, *, now: float) -> dict:- """The quiet-spell fallback: a run whose build card was reached and that has not changed for- ``QUIET_COMPLETE_S`` is complete."""- if is_active(record) and record["beats"]["build"] != PENDING and now - record["updated_at"] >= QUIET_COMPLETE_S:- record = copy.deepcopy(record)- record.update(phase=COMPLETE, ended_by="timeout", waiting=None, updated_at=now)- return record--# ── apply ─────────────────────────────────────────────────────────────────────────────────────@@ -315,8 +307,8 @@ def _skipped(record: dict, event: Skipped, facts: Facts, now: float) -> Step:return Step(record, {"recorded": event.beat, "skipped": True, "next": _next_field(record)}, "moved_on")-def _skip_all(record: dict, event: SkipAll, facts: Facts, now: float) -> Step:- record.update(phase=PHASE_SKIPPED, ended_by="skip", waiting=None)+def _end(record: dict, event: End, facts: Facts, now: float) -> Step:+ record.update(phase=PHASE_SKIPPED, ended_by=event.outcome, waiting=None)for beat in BEAT_IDS:if record["beats"][beat] != DONE:record["beats"][beat] = SKIPPED@@ -329,8 +321,7 @@ def _done(record: dict, event: Done, facts: Facts, now: float) -> Step:"answered. If they want to stop, tell them about the Skip setup button.","next": _next_field(record)})record["beats"]["build"] = DONE- record.update(phase=COMPLETE, ended_by="done", waiting=None)- return Step(record, {"completed": True}, "complete")+ return Step(record, {}, "complete")def _applied_beats(event: Applied) -> list[tuple[str, dict]]:@@ -360,23 +351,40 @@ def _applied(record: dict, event: Applied, facts: Facts, now: float) -> Step:elif beat in APPLIED_BY:repeated = beat_settle(record, beat, patch)+ if (record["waiting"] or {}).get("beat") == beat:+ record["waiting"] = Nonereturn Step(record, {}, f"after_{settled}" if settled else f"already_{repeated}" if repeated else "")_HANDLERS: dict[type, Callable[[dict, Any, Facts, float], Step]] = {Shown: _shown, Answered: _answered, Said: _said, TimedOut: _timed_out, Recorded: _recorded,- Skipped: _skipped, SkipAll: _skip_all, Done: _done, Applied: _applied,+ Skipped: _skipped, End: _end, Done: _done, Applied: _applied,}_ENDED = "Onboarding is over in this chat; it is a normal chat now."+def _ended(record: dict, event: Event) -> Step:+ """An ended run ignores general tool results and refuses setup_beat, except a repeat of its own+ end: done on a completed run and any end on an ended run answer as if they had ended it."""+ if isinstance(event, Applied):+ return Step(record, {})+ if isinstance(event, Done) and record.get("phase") == COMPLETE:+ return Step(record, {"completed": True}, "complete")+ if isinstance(event, End):+ return Step(record, {"skipped_all": True})+ return Step(record, {"error": _ENDED})++def apply(record: Mapping[str, Any], event: Event, facts: Facts, *, now: float = 0.0) -> Step:- """The record after ``event``, the model-facing result, and the reminder key. A finished run- refuses every setup_beat event and ignores general tool results."""+ """The record after ``event``, the model-facing result, and the reminder key. The run completes+ when the build beat settles: the answer to the first-task card ends onboarding."""working = copy.deepcopy(dict(record))if not is_active(working):- return Step(working, {} if isinstance(event, Applied) else {"error": _ENDED})+ return _ended(working, event)step = _HANDLERS[type(event)](working, event, facts, now)+ if is_active(step.record) and step.record["beats"]["build"] == DONE:+ step.record.update(phase=COMPLETE, ended_by="done", waiting=None)+ step = Step(step.record, {**step.result, "completed": True}, step.reminder)if step.record != record:step.record["updated_at"] = nowreturn stepdiff --git a/agent/onboarding_record.py b/agent/onboarding_record.pyindex baf7188f47d..cd0bc011b01 100644--- a/agent/onboarding_record.py+++ b/agent/onboarding_record.py@@ -15,7 +15,7 @@ from collections.abc import Mappingfrom typing import Anyfrom agent.onboarding_flow import (- Applied, Event, Facts, Step, applies_to, apply, expire, is_active, new_record,+ Applied, End, Event, Facts, Step, applies_to, apply, is_active, new_record,)from agent.onboarding_text import reminder@@ -24,36 +24,24 @@ logger = logging.getLogger(__name__)KEY = "onboarding_run"-def _read(db, session_id: str) -> dict | None:+def load(db, session_id: str) -> dict | None:record = db.get_session_model_config_value(session_id, KEY) if db is not None and session_id else Nonereturn record if isinstance(record, dict) else None-def load(db, session_id: str) -> dict | None:- """The run record, with the quiet-spell fallback applied (and saved) when it is due."""- record = _read(db, session_id)- if record is not None and expire(record, now=time.time()) is not record:- step = _transition(db, session_id, None)- return step.record if step is not None else None- return record---def _transition(db, session_id: str, event: Event | None) -> Step | None:- """Expire, apply *event* and write the result in one database transaction at the compression tip,- so Skip setup pressed while a card answer is being applied is never overwritten by the older copy,- and an id read before a rotation published still lands on the copy the chat reads. An ended run then- closes the install flag (a Skip or Done retried after a failed config write repairs it), unless- another run is still open: the flag belongs to that run, and an old chat must not end it."""+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 Skip+ setup pressed while a card answer is being applied is never overwritten by the older copy, and an id+ read before a rotation published still lands on the copy the chat reads. An ended run then closes the+ install flag (a Skip or Done retried after a failed config write repairs it), unless another run+ is still open: the flag belongs to that run, and an old chat must not end it."""holder: dict[str, Step] = {}def update(current: Any) -> Any:holder.pop("step", None)if not isinstance(current, dict):return current- now = time.time()- record = expire(current, now=now)- holder["step"] = (apply(record, event, Facts.from_stored(record["facts"]), now=now)- if event is not None else Step(record, {}))+ holder["step"] = apply(current, event, Facts.from_stored(current["facts"]), now=time.time())return holder["step"].recorddb.update_conversation_model_config_value(session_id, KEY, update)@@ -114,14 +102,12 @@ def active_session_id(db) -> str | None:return next(iter(open_session_ids(db)), None)-def intro_seen(db, session_id: str | None) -> bool:- return bool((_read(db, session_id) or {}).get("intro_seen")) if session_id else False---def mark_intro_seen(db, session_id: str) -> None:- """Kept on the run, so a rerun plays the intro again."""- db.update_session_model_config_value(- session_id, KEY, lambda current: {**current, "intro_seen": True} if isinstance(current, dict) else current)+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. The run lives at the chat's compression tip."""+ for sid in dict.fromkeys((session_id, db.resolve_resume_session_id(session_id) or session_id)):+ if is_active(load(db, sid)):+ advance(db, sid, End("deleted"))def observe_tool_result(agent, name: str, args: Mapping[str, Any], result: Any) -> Any:diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 0a90e632572..aae5542c7bb 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -1920,14 +1920,13 @@ export interface ClientCapabilitiesResult {}/** Client→server method params / server→client request params. Unknown keys are rejected. */export type Params = Record<string, never>-/** ``machine_kind`` is ``Spark``, ``Mac``, ``PC`` or ``computer``. ``nvidia_platform`` is ``products.nvidia_platform()``: ``rtx_spark``, ``dgx_spark``, ``discrete`` or null. ``full_name`` is the OS account's real name (never a login handle) and ``locale`` its first UI language; each is null when the OS has none. */+/** ``machine_kind`` is ``Spark``, ``Mac``, ``PC`` or ``computer``. ``nvidia_platform`` is ``products.nvidia_platform()``: ``rtx_spark``, ``dgx_spark``, ``discrete`` or null. ``locale`` is the OS account's first UI language, null when the OS has none. */export interface MachineFactsResult {machine: MachineInfomachine_kind: stringhas_nvidia_gpu: booleannvidia_platform?: 'rtx_spark' | 'dgx_spark' | 'discrete' | nulllocale?: string | null- full_name?: string | null}/** Measured hardware; a key that was not measured is absent. */export interface MachineInfo {@@ -2203,12 +2202,11 @@ export interface OnboardingStateResult {profile?: string | null}export type OnboardingIntro = 'unseen' | 'seen'-/** ``run``: onboarding opens on this launch (root config ``onboarding.run``, else a fresh install). ``eligible``: the free tier is on for this backend (``anon_auth.guest_enabled``). ``session_id``: the stored id of the onboarding chat still in progress, so a relaunch reopens it. ``intro_seen``: the user left that run's intro once, so a relaunch reopens it as a normal chat. */+/** ``run``: onboarding opens on this launch (root config ``onboarding.run``, else a fresh install). ``eligible``: the free tier is on for this backend (``anon_auth.guest_enabled``). ``session_id``: the stored id of the onboarding chat still in progress, so a relaunch reopens it. */export interface OnboardingRunStateResult {run: booleaneligible: booleansession_id?: string | null- intro_seen?: boolean}/** ``mark_profile_offered`` also latches ``onboarding.seen.profile_build_offered`` in the root config, so the first chat after onboarding gets the plain intro instead of the profile offer. */export interface OnboardingSetRunParams {@@ -5401,8 +5399,6 @@ export interface RpcMethods {/** Create-or-read the backend-owned setup profile; the backend picks the name. */'onboarding.ensure_setup_profile': { params: Params; result: OnboardingEnsureSetupProfileResult }'onboarding.ensure_setup_session': { params: OnboardingEnsureSetupSessionParams; result: OnboardingEnsureSetupSessionResult }- /** Record that the user left the intro of the run in progress; returns onboarding.state. */- 'onboarding.intro_seen': { params: Params; result: OnboardingRunStateResult }'onboarding.mark_seen': { params: Params; result: OnboardingStateResult }'onboarding.record_failed_start': { params: Params; result: OnboardingStateResult }/** Restore the setup profile to its created state in place (soul, memories, skills, sessions). */@@ -5816,7 +5812,6 @@ export const RPC_METHODS = ['model.save_key','onboarding.ensure_setup_profile','onboarding.ensure_setup_session',- 'onboarding.intro_seen','onboarding.mark_seen','onboarding.record_failed_start','onboarding.reset_setup_profile',diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 4a596cbcdcc..40b4649cac7 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -2058,24 +2058,6 @@}}},- {- "name": "onboarding.intro_seen",- "summary": "Record that the user left the intro of the run in progress; returns onboarding.state.",- "params": [- {- "name": "params",- "schema": {- "$ref": "#/components/schemas/Params"- }- }- ],- "result": {- "name": "result",- "schema": {- "$ref": "#/components/schemas/OnboardingRunStateResult"- }- }- },{"name": "onboarding.mark_seen","summary": "",@@ -18027,7 +18009,7 @@},"MachineFactsResult": {"additionalProperties": false,- "description": "``machine_kind`` is ``Spark``, ``Mac``, ``PC`` or ``computer``. ``nvidia_platform`` is\n``products.nvidia_platform()``: ``rtx_spark``, ``dgx_spark``, ``discrete`` or null. ``full_name`` is the OS account's\nreal name (never a login handle) and ``locale`` its first UI language; each is null when the OS has none.",+ "description": "``machine_kind`` is ``Spark``, ``Mac``, ``PC`` or ``computer``. ``nvidia_platform`` is\n``products.nvidia_platform()``: ``rtx_spark``, ``dgx_spark``, ``discrete`` or null. ``locale`` is the OS\naccount's first UI language, null when the OS has none.","properties": {"machine": {"$ref": "#/components/schemas/MachineInfo"@@ -18068,18 +18050,6 @@],"default": null,"title": "Locale"- },- "full_name": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "default": null,- "title": "Full Name"}},"required": [@@ -20541,7 +20511,7 @@},"OnboardingRunStateResult": {"additionalProperties": false,- "description": "``run``: onboarding opens on this launch (root config ``onboarding.run``, else a fresh\ninstall). ``eligible``: the free tier is on for this backend (``anon_auth.guest_enabled``).\n``session_id``: the stored id of the onboarding chat still in progress, so a relaunch reopens it.\n``intro_seen``: the user left that run's intro once, so a relaunch reopens it as a normal chat.",+ "description": "``run``: onboarding opens on this launch (root config ``onboarding.run``, else a fresh\ninstall). ``eligible``: the free tier is on for this backend (``anon_auth.guest_enabled``).\n``session_id``: the stored id of the onboarding chat still in progress, so a relaunch reopens it.","properties": {"run": {"title": "Run",@@ -20562,11 +20532,6 @@],"default": null,"title": "Session Id"- },- "intro_seen": {- "default": false,- "title": "Intro Seen",- "type": "boolean"}},"required": [diff --git a/tests/agent/test_onboarding_flow.py b/tests/agent/test_onboarding_flow.pyindex 03da26edc51..9a74b10602a 100644--- a/tests/agent/test_onboarding_flow.py+++ b/tests/agent/test_onboarding_flow.py@@ -10,8 +10,8 @@ import pytestfrom agent import onboarding_flow as flowfrom agent.onboarding_flow import (- DONE, PENDING, SHOWN, SKIPPED, Answered, Applied, Done, Facts, Recorded, Said, Shown, SkipAll, Skipped,- TimedOut, apply, expire, new_record, next_beat,+ DONE, PENDING, SHOWN, SKIPPED, Answered, Applied, Done, Facts, End, Recorded, Said, Shown, Skipped,+ TimedOut, apply, new_record, next_beat,)from agent.onboarding_first_tasks import eligible_tasksfrom agent.onboarding_text import opening_prompt, reminder, turn_note@@ -173,7 +173,7 @@ def test_run_3ofn_pick_for_me_applies_layout_and_offers_the_look_around_once():def test_skip_setup_while_a_card_waits_ends_the_run_and_refuses_later_beats():facts = MACHINES["windows_laptop"]- steps = run(facts, Shown("name"), Answered("name", {"name": "Sid"}), Shown("theme"), SkipAll(), Shown("theme"))+ steps = run(facts, Shown("name"), Answered("name", {"name": "Sid"}), Shown("theme"), End(), Shown("theme"))skipped, refused = steps[-2], steps[-1]assert skipped.result == {"skipped_all": True} and skipped.reminder == "skip_all"@@ -304,14 +304,22 @@ def test_build_guidance_carries_only_this_hosts_commands(machine, present, absenassert 'setup_beat(beat="done")' in text-def test_quiet_spell_after_the_build_card_completes_the_run():+def test_the_build_answer_completes_the_run_and_a_later_done_or_skip_reports_that_end():facts = MACHINES["mac"]- record = run(facts, Shown("build", "", NOTES))[-1].record+ answered, done, skip = run(facts, Shown("build", "", NOTES), Answered("build", {"build": "notes"}), Done(), End())[1:]- assert expire(record, now=record["updated_at"] + flow.QUIET_COMPLETE_S - 1)["phase"] == flow.ONBOARDING- ended = expire(record, now=record["updated_at"] + flow.QUIET_COMPLETE_S)- assert ended["phase"] == flow.COMPLETE and ended["ended_by"] == "timeout"- assert expire(new_record(facts), now=10**9)["phase"] == flow.ONBOARDING+ assert answered.result["completed"] is True and answered.reminder == "build_notes"+ assert answered.record["phase"] == flow.COMPLETE and answered.record["ended_by"] == "done"+ assert done.result == {"completed": True} and done.record == answered.record+ assert skip.result == {"skipped_all": True} and skip.record == answered.record+++def test_a_general_tool_that_settles_the_waiting_beat_clears_waiting():+ facts = MACHINES["mac"]+ step = run(facts, Shown("theme", "call_t"), Applied("set_theme", {"accent": "violet"},+ {"success": True, "applied": {"accent": "violet"}}))[-1]++ assert step.record["beats"]["theme"] == DONE and step.record["waiting"] is Nonedef test_a_card_answer_outside_the_cards_options_is_refused_and_the_beat_stays_open():diff --git a/tests/tools/test_setup_beat_tool.py b/tests/tools/test_setup_beat_tool.pyindex 3cb55d180cb..c99e39dd90b 100644--- a/tests/tools/test_setup_beat_tool.py+++ b/tests/tools/test_setup_beat_tool.py@@ -10,7 +10,7 @@ import pytestfrom agent import onboarding_recordfrom agent.inline_tool_executors import INLINE_TOOL_EXECUTORS, InlineToolContext-from agent.onboarding_flow import Facts, SkipAll+from agent.onboarding_flow import End, Factsfrom hermes_state import SessionDBfrom tools.registry import registry@@ -95,7 +95,7 @@ def test_skip_setup_during_a_card_returns_skipped_all(db, desktop):onboarding_record.start(db, SID, FACTS)def skip_pressed(payload):- onboarding_record.advance(db, SID, SkipAll())+ onboarding_record.advance(db, SID, End())desktop.answer = skip_pressedresult = call(db, desktop, beat="theme")@@ -119,7 +119,7 @@ def test_done_ends_the_run_only_after_the_build_card(db, desktop):done = call(db, desktop, beat="done")assert "error" in refused- assert "How does this look?" in build["reminder"]+ assert "How does this look?" in build["reminder"] and build["completed"] is Trueassert done == {"completed": True, "reminder": done["reminder"]}assert onboarding_record.load(db, SID)["phase"] == "complete"diff --git a/tests/tui_gateway/test_onboarding_run_rpc.py b/tests/tui_gateway/test_onboarding_run_rpc.pyindex 9400af23036..a3a7f8efb29 100644--- a/tests/tui_gateway/test_onboarding_run_rpc.py+++ b/tests/tui_gateway/test_onboarding_run_rpc.py@@ -35,7 +35,7 @@ def _onboarding(home: Path) -> dict:def test_state_answers_run_and_eligible(launched_under_work, monkeypatch):# The user's own "work" profile is install history, so an unset flag is not due.- assert _call("onboarding.state")["result"] == {"run": False, "eligible": True, "session_id": None, "intro_seen": False}+ assert _call("onboarding.state")["result"] == {"run": False, "eligible": True, "session_id": None}monkeypatch.delenv("HERMES_GUEST_ONBOARDING")assert _call("onboarding.state")["result"]["eligible"] is False@@ -44,7 +44,7 @@ def test_state_answers_run_and_eligible(launched_under_work, monkeypatch):def test_set_run_writes_the_root_config(launched_under_work):root, work = launched_under_work- assert _call("onboarding.set_run", {"run": True})["result"] == {"run": True, "eligible": True, "session_id": None, "intro_seen": False}+ assert _call("onboarding.set_run", {"run": True})["result"] == {"run": True, "eligible": True, "session_id": None}assert _onboarding(root)["run"] is Trueassert "run" not in _onboarding(work)assert _call("onboarding.state")["result"]["run"] is Truediff --git a/tests/tui_gateway/test_onboarding_session.py b/tests/tui_gateway/test_onboarding_session.pyindex 42d8aeca5ae..9269ba8b10d 100644--- a/tests/tui_gateway/test_onboarding_session.py+++ b/tests/tui_gateway/test_onboarding_session.py@@ -11,7 +11,7 @@ from types import SimpleNamespaceimport pytestfrom agent import onboarding_record-from agent.onboarding_flow import Facts, Shown, SkipAll+from agent.onboarding_flow import End, Facts, Shownfrom agent.onboarding_text import GREETINGfrom tui_gateway import server, server_requests@@ -73,16 +73,6 @@ def test_start_creates_one_onboarding_chat_and_plays_the_opening_once(client):assert _call("onboarding.start", {"rerun": True})["result"]["stored_session_id"] != stored-def test_leaving_the_intro_is_kept_on_the_run_and_a_rerun_plays_it_again(client):- _call("onboarding.start")- assert _call("onboarding.state")["result"]["intro_seen"] is False- assert _call("onboarding.intro_seen")["result"]["intro_seen"] is True- assert _call("onboarding.state")["result"]["intro_seen"] is True-- _call("onboarding.start", {"rerun": True})- assert _call("onboarding.state")["result"]["intro_seen"] is False--def test_a_restart_before_the_opening_turn_plays_the_opening_on_relaunch(client, monkeypatch):def lost_submit(rid, params):client.append(("lost", params))@@ -231,7 +221,7 @@ def test_a_compression_rotation_carries_the_run_record(root):assert db.get_session_model_config_value("child", "codex_thread_id") is None# 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"- onboarding_record.advance(db, "child", SkipAll())+ onboarding_record.advance(db, "child", End())assert onboarding_record.active_session_id(db) is None@@ -266,12 +256,12 @@ def test_a_skip_retried_after_a_failed_config_write_closes_the_install_flag(rootmonkeypatch.setattr(onboarding_run, "set_run", disk_full)with pytest.raises(OSError):- onboarding_record.advance(db, "onb", SkipAll())+ onboarding_record.advance(db, "onb", End())monkeypatch.setattr(onboarding_run, "set_run", real_set_run)assert onboarding_record.load(db, "onb")["phase"] == "skipped"assert read_user_config_raw(root / "config.yaml")["onboarding"]["run"] is True- onboarding_record.advance(db, "onb", SkipAll())+ onboarding_record.advance(db, "onb", End())assert read_user_config_raw(root / "config.yaml")["onboarding"]["run"] is False@@ -280,11 +270,11 @@ def test_an_old_ended_chat_never_closes_the_flag_of_a_newer_run(root):db = server._get_db()db.create_session("old", "desktop")onboarding_record.start(db, "old", FACTS)- onboarding_record.advance(db, "old", SkipAll())+ onboarding_record.advance(db, "old", End())db.create_session("new", "desktop")onboarding_record.start(db, "new", FACTS)- onboarding_record.advance(db, "old", SkipAll()) # the old chat's agent still carries setup_beat+ onboarding_record.advance(db, "old", End()) # the old chat's agent still carries setup_beatassert read_user_config_raw(root / "config.yaml")["onboarding"]["run"] is Trueassert onboarding_record.active_session_id(db) == "new"@@ -296,7 +286,7 @@ def test_a_rerun_ends_the_run_it_replaces_so_finishing_the_new_one_closes_the_fldb = server._get_db()assert onboarding_record.load(db, old)["phase"] == "skipped"- onboarding_record.advance(db, new, SkipAll())+ onboarding_record.advance(db, new, End())assert onboarding_record.active_session_id(db) is Noneassert read_user_config_raw(root / "config.yaml")["onboarding"]["run"] is False@@ -339,17 +329,13 @@ def test_a_rerun_closes_the_card_waiting_in_the_chat_it_replaces(client, monkeypassert reply == [None] and events[0][0] == "request.cancel"-def test_the_first_state_read_after_the_quiet_spell_says_do_not_run(root):- from agent.onboarding_flow import QUIET_COMPLETE_S, Answered+def test_deleting_the_onboarding_chat_ends_its_run_and_closes_the_flag(root):db = server._get_db()db.create_session("onb", "desktop")onboarding_record.start(db, "onb", FACTS)- for event in (Shown("build", options=[{"id": "notes", "label": "Notes"}]), Answered("build", {"build": "notes"})):- onboarding_record.advance(db, "onb", event)- record = onboarding_record.load(db, "onb")- db.patch_session_model_config("onb", {"onboarding_run": {**record, "updated_at": record["updated_at"] - QUIET_COMPLETE_S}})- assert _call("onboarding.state")["result"] == {"run": False, "eligible": False, "session_id": None, "intro_seen": False}+ assert _call("session.delete", {"session_id": "onb"})["result"] == {"deleted": "onb"}+ assert _call("onboarding.state")["result"] == {"run": False, "eligible": False, "session_id": None}def test_the_onboarding_facts_are_read_in_the_default_profile(root, client, monkeypatch):diff --git a/tests/tui_gateway/test_session_delete_rpc.py b/tests/tui_gateway/test_session_delete_rpc.pynew file mode 100644index 00000000000..68841d9e3b7--- /dev/null+++ b/tests/tui_gateway/test_session_delete_rpc.py@@ -0,0 +1,201 @@+"""``session.delete``: argument checks, the live-session refusal, the profile's db and sessions dir, and+the onboarding run a deleted chat ends first (moved out of test_tui_gateway_server.py)."""++from pathlib import Path++from tui_gateway import server+++class _NoOnboardingRun:+ """A fake state DB whose sessions carry no onboarding run (session.delete reads it first)."""++ def get_session_model_config_value(self, *_args):+ return None++ def resolve_resume_session_id(self, *_args):+ return None+++def test_session_delete_requires_session_id(monkeypatch):+ """Empty / missing session_id is a 4006 client error (no DB call)."""+ called: list[tuple] = []++ class _DB(_NoOnboardingRun):+ def delete_session(self, *a, **kw):+ called.append((a, kw))+ return True++ monkeypatch.setattr(server, "_get_db", lambda: _DB())++ resp = server.handle_request({"id": "1", "method": "session.delete", "params": {}})+ assert "error" in resp+ assert resp["error"]["code"] == 4006+ assert called == []+++def test_session_delete_returns_db_unavailable_when_no_db(monkeypatch):+ monkeypatch.setattr(server, "_get_db", lambda: None)+ monkeypatch.setattr(server, "_db_error", "locked")++ resp = server.handle_request(+ {"id": "1", "method": "session.delete", "params": {"session_id": "abc"}}+ )++ assert "error" in resp+ assert resp["error"]["code"] == 5036+ assert resp["error"]["data"]["code"] == "storage_locked"+++def test_session_delete_refuses_active_session(monkeypatch):+ """Cannot delete a session currently bound to a live TUI session."""+ called: list[str] = []++ class _DB(_NoOnboardingRun):+ def delete_session(self, sid, sessions_dir=None, **_kw):+ called.append(sid)+ return True++ monkeypatch.setattr(server, "_get_db", lambda: _DB())+ monkeypatch.setitem(server._sessions, "live", {"session_key": "key-live"})+ try:+ resp = server.handle_request(+ {+ "id": "1",+ "method": "session.delete",+ "params": {"session_id": "key-live"},+ }+ )+ finally:+ server._sessions.pop("live", None)++ assert "error" in resp+ assert resp["error"]["code"] == 4023+ assert called == [], "delete_session must not be called for active sessions"+++def test_session_delete_fails_closed_when_active_snapshot_raises(monkeypatch):+ """Concurrent ``_sessions`` mutation from another RPC thread can raise+ ``RuntimeError: dictionary changed size during iteration``. When the+ handler can't enumerate active sessions safely it must refuse the+ delete (fail closed) rather than fall through and allow it."""++ class _DB(_NoOnboardingRun):+ def delete_session(self, *a, **kw):+ raise AssertionError("delete must not run when active snapshot fails")++ class _ExplodingDict:+ def values(self):+ raise RuntimeError("dictionary changed size during iteration")++ monkeypatch.setattr(server, "_get_db", lambda: _DB())+ monkeypatch.setattr(server, "_sessions", _ExplodingDict())++ resp = server.handle_request(+ {"id": "1", "method": "session.delete", "params": {"session_id": "x"}}+ )++ assert "error" in resp+ assert resp["error"]["code"] == 5036+++def test_session_delete_returns_4007_when_missing(monkeypatch):+ class _DB(_NoOnboardingRun):+ def delete_session(self, sid, sessions_dir=None, **_kw):+ return False++ monkeypatch.setattr(server, "_get_db", lambda: _DB())++ resp = server.handle_request(+ {"id": "1", "method": "session.delete", "params": {"session_id": "ghost"}}+ )++ assert "error" in resp+ assert resp["error"]["code"] == 4007+++def test_session_delete_propagates_db_exception(monkeypatch):+ class _DB(_NoOnboardingRun):+ def delete_session(self, sid, sessions_dir=None, **_kw):+ raise RuntimeError("disk full")++ monkeypatch.setattr(server, "_get_db", lambda: _DB())++ resp = server.handle_request(+ {"id": "1", "method": "session.delete", "params": {"session_id": "x"}}+ )++ assert "error" in resp+ assert resp["error"]["code"] == 5036+ assert "disk full" in resp["error"]["message"]+++def test_session_delete_success_returns_deleted_id(monkeypatch):+ """Happy path — DB delete succeeds, response carries the deleted id+ and the on-disk sessions dir is forwarded so transcript files get+ cleaned up alongside the row."""+ captured: dict = {}++ class _DB(_NoOnboardingRun):+ def delete_session(self, sid, sessions_dir=None, **_kw):+ captured["sid"] = sid+ captured["sessions_dir"] = sessions_dir+ return True++ monkeypatch.setattr(server, "_get_db", lambda: _DB())++ resp = server.handle_request(+ {"id": "1", "method": "session.delete", "params": {"session_id": "old-1"}}+ )++ assert "result" in resp, resp+ assert resp["result"] == {"deleted": "old-1"}+ assert captured["sid"] == "old-1"+ # sessions_dir must be forwarded so transcript files get cleaned up+ # too — not just the SQLite row. The autouse _isolate_hermes_home+ # fixture pins HERMES_HOME to a temp dir; the handler should append+ # /sessions to it.+ assert captured["sessions_dir"] is not None+ assert str(captured["sessions_dir"]).endswith("sessions")+++++# --------------------------------------------------------------------------+# session.* profile scoping (app-global remote mode) — #62503+# --------------------------------------------------------------------------+++def test_session_delete_honors_params_profile_sessions_dir(monkeypatch, tmp_path):+ """Issue #62503: delete must target the profile state.db + sessions dir."""+ profile_home = tmp_path / "profiles" / "mlperf"+ (profile_home / "sessions").mkdir(parents=True)+ captured: dict = {}++ class ProfileDB(_NoOnboardingRun):+ def __init__(self, db_path=None):+ captured["db_path"] = db_path++ def delete_session(self, sid, sessions_dir=None, **_kw):+ captured["sid"] = sid+ captured["sessions_dir"] = sessions_dir+ return True++ def close(self):+ captured["closed"] = True++ monkeypatch.setattr(server, "_profile_home", lambda p: profile_home if p == "mlperf" else None)+ monkeypatch.setattr(server, "_get_db", lambda: None)+ monkeypatch.setattr("hermes_state_registry.acquire", ProfileDB)++ resp = server.handle_request(+ {+ "id": "1",+ "method": "session.delete",+ "params": {"session_id": "old-ml", "profile": "mlperf"},+ }+ )+ assert "result" in resp, resp+ assert resp["result"] == {"deleted": "old-ml"}+ assert str(captured["db_path"]).endswith("state.db")+ assert Path(captured["sessions_dir"]) == profile_home / "sessions"+ assert captured.get("closed") is Truediff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex c270a0e7639..29c198fbe21 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -215,8 +215,6 @@ def test_handoff_fail_marks_only_inflight_rows(monkeypatch):server._sessions.pop(sid, None)--def test_dashboard_process_isolation_config_coerces_raw_values():cfg = {"dashboard": {@@ -240,8 +238,6 @@ def test_dashboard_process_isolation_config_coerces_raw_values():}--def test_prompt_submit_dispatches_to_compute_host_when_turn_isolation_enabled(monkeypatch):class FakeSupervisor:def __init__(self):@@ -1506,8 +1502,6 @@ def test_usage_ticker_unbounded_join_waits_out_blocked_emit(monkeypatch):assert order == ["session.usage", "message.complete"]--def test_tui_verbose_tool_details_fail_closed_when_redaction_fails(monkeypatch):redact_module = types.ModuleType("agent.redact")@@ -1662,8 +1656,6 @@ def test_dispatch_rejects_non_object_params():assert resp["error"]["code"] == -32602--def test_system_battery_fails_open(monkeypatch):def boom():raise RuntimeError("no battery subsystem")@@ -1745,8 +1737,6 @@ def test_voice_toggle_returns_configured_record_key(monkeypatch):assert status_resp["result"]["record_key"] == "ctrl+o"--def test_voice_toggle_handles_non_dict_voice_cfg(monkeypatch):"""Round-3 Copilot review regression on #19835.@@ -1946,8 +1936,6 @@ def test_prompt_submit_typed_stop_passes_through_when_voice_off(monkeypatch):assert resp.get("result") != {"voice_stopped": True}--def test_wake_owner_is_sticky_and_routes_detection_to_first_transport(monkeypatch):from tools import wake_word@@ -2213,8 +2201,6 @@ def test_wake_toggle_persists_enabled_flag_only_on_explicit_gesture(monkeypatch)server._wake_owner_surface = ""--def test_voice_record_start_forwards_max_recording_seconds(monkeypatch):"""voice.max_recording_seconds must reach start_continuous from the TUI.@@ -2637,8 +2623,6 @@ def test_load_disabled_toolsets_none_when_unset_or_config_fails(monkeypatch):assert server._load_disabled_toolsets() is None--def test_load_enabled_toolsets_reports_disabled_mcp_separately(monkeypatch, capsys):monkeypatch.setenv("HERMES_TUI_TOOLSETS", "web,mcp-off,nope")monkeypatch.setitem(@@ -2852,8 +2836,6 @@ def test_tool_start_ships_full_args(monkeypatch):assert "args" not in events[1][2]--def test_history_to_messages_keeps_reasoning_only_assistant_turn():# A thinking-only assistant turn (reasoning present, no visible text) is# persisted and recallable, but was dropped from the resumed session view@@ -3369,8 +3351,6 @@ def test_session_resume_uses_parent_lineage_for_display(monkeypatch, omit_messagassert resp["result"]["messages_omitted"] is omit_messages--def test_live_visible_history_falls_back_without_db_or_key():in_memory = [{"role": "user", "content": "hi"}]# No DB handle available.@@ -4496,8 +4476,6 @@ def test_config_sync_ignores_env_seed_without_config_model(monkeypatch):server._sync_agent_model_with_config("sid", session)--def test_apply_model_switch_persist_override_false_never_persists(monkeypatch):# Internal callers (config sync, /moa one-shot + restore) pass# persist_override=False; even with persist_switch_by_default=True the@@ -4560,8 +4538,6 @@ def test_startup_runtime_does_not_treat_inference_provider_as_explicit(monkeypatassert server._resolve_startup_runtime() == ("nous/hermes-test", None)--def test_load_fallback_model_merges_chain_providers_first(monkeypatch):# Parity with HermesCLI / gateway: fallback_providers stays first and keeps# its order, with any distinct legacy fallback_model entry merged in after@@ -4790,8 +4766,6 @@ def test_attaching_a_different_login_keeps_the_creator_and_warns_once(monkeypatcassert server._session_auth_user_id(record) == "basic:alice"--def test_background_agent_kwargs_preserves_full_fallback_chain(monkeypatch):chain = [{"provider": "openrouter", "model": "openai/gpt-5.5"},@@ -5315,8 +5289,6 @@ def test_ws_disconnect_running_sidecar_still_closes_without_orphan_timer(monkeypserver._sessions.pop("sidecar-sid", None)--def test_ws_orphan_reap_releases_resume_lock_before_slow_teardown(monkeypatch):"""Grace reaping claims under the lock but finalizes after releasing it."""scheduled = {}@@ -5859,8 +5831,6 @@ def test_superseded_runtime_finalized_without_reclaimed_broadcast(monkeypatch):server._pending_ws_reaps.pop("new-sid", None)--def test_lazy_unpersisted_resume_rebinds_transport_and_cancels_reap(monkeypatch):"""The lazy/unpersisted resume branch (no state.db row yet — every freshBot Chat) must ALSO rebind the transport and cancel the pending reap when@@ -8199,7 +8169,6 @@ def test_run_prompt_submit_prefers_origin_ui_session_id(monkeypatch, tmp_path):process_registry._completion_consumed.discard(event["session_id"])-"""session.create must NOT eagerly write a DB row.Every TUI/desktop launch opens a session here just to paint the composer;@@ -8950,8 +8919,6 @@ def test_pet_info_known_revision_elides_spritesheet(monkeypatch):assert resp["result"]["spritesheetBase64"] == "A" * 1024--def test_config_set_approval_mode_rejects_unknown_value():resp = server.handle_request({@@ -9413,8 +9380,6 @@ def test_enable_gateway_prompts_sets_gateway_env(monkeypatch):assert server.os.environ["HERMES_INTERACTIVE"] == "1"--def test_setup_status_answers_from_the_bootstrap_record_once_it_exists(monkeypatch):"""Under ``hermes serve`` the boot bootstrap owns the free-tier identity; ``setup.status`` reportsits record (blocking for it while it is in flight) instead of re-probing, so a client's first poll@@ -9754,8 +9719,6 @@ def test_setup_readiness_unknown_profile_never_answers_for_launch_profile(monkeyassert resp["result"]["profile"] == "ghost"--def test_complete_slash_returns_plain_string_fields():# prompt_toolkit hands us FormattedText (a list subclass) for# display/display_meta; the TUI's CompletionItem contract is plain@@ -9776,10 +9739,6 @@ def test_complete_slash_returns_plain_string_fields():assert isinstance(item["meta"], str), item----def test_complete_slash_details_args():resp_root = server.handle_request({"id": "0", "method": "complete.slash", "params": {"text": "/details"}}@@ -9801,8 +9760,6 @@ def test_complete_slash_details_args():assert any(item["text"] == "expanded" for item in resp_mode["result"]["items"])--_SLASH_FILLER_COUNT = 60@@ -10049,7 +10006,6 @@ def test_config_set_verbose_updates_session_mode_and_agent(tmp_path, monkeypatchassert agent.verbose_logging is True-def test_config_set_model_waits_for_lazy_agent_before_switch(monkeypatch):"""A model switch against a lazy-created live session must apply to thereal agent, not just process env, before the prompt is dispatched.@@ -10092,7 +10048,6 @@ def test_config_set_model_waits_for_lazy_agent_before_switch(monkeypatch):server._sessions.pop("sid", None)-def test_config_set_model_requires_confirmation_for_expensive_model(monkeypatch):class _Agent:provider = "openrouter"@@ -12111,8 +12066,6 @@ def test_commands_catalog_survives_an_unreadable_usage_sidecar(monkeypatch):)--def test_commands_catalog_has_no_duplicate_or_alias_colliding_names():"""No command may be advertised twice, and no advertised command mayshadow an alias of a different command (e.g. the historical /compact@@ -12375,12 +12328,6 @@ def test_command_dispatch_exec_nonzero_surfaces_error(monkeypatch):assert "failed" in resp["error"]["message"]------def test_input_detect_drop_path_with_spaces(tmp_path):"""input.detect_drop correctly handles image paths containing spaces."""# Create a minimal PNG file with a space in its name@@ -13065,8 +13012,6 @@ def test_session_redirect_rejects_when_idle_without_agent(monkeypatch):assert session.get("queued_prompt") is None--def test_session_info_includes_session_title(monkeypatch):class _FakeDB:def get_session_title(self, key):@@ -15101,8 +15046,6 @@ def test_apply_pending_model_switch_runs_queued_pick(monkeypatch):assert calls == ["anthropic/claude-sonnet-4.6"]--def test_mirror_slash_side_effects_rejects_mutating_commands_while_running(monkeypatch):"""Slash worker passthrough (e.g. /model, /personality, /prompt,/compress) must reject during an in-flight turn. Same race as@@ -15856,155 +15799,6 @@ def test_session_list_returns_clean_error_when_state_db_is_unavailable(monkeypat# ---------------------------------------------------------------------------def test_session_delete_requires_session_id(monkeypatch):- """Empty / missing session_id is a 4006 client error (no DB call)."""- called: list[tuple] = []-- class _DB:- def delete_session(self, *a, **kw):- called.append((a, kw))- return True-- monkeypatch.setattr(server, "_get_db", lambda: _DB())-- resp = server.handle_request({"id": "1", "method": "session.delete", "params": {}})- assert "error" in resp- assert resp["error"]["code"] == 4006- assert called == []---def test_session_delete_returns_db_unavailable_when_no_db(monkeypatch):- monkeypatch.setattr(server, "_get_db", lambda: None)- monkeypatch.setattr(server, "_db_error", "locked")-- resp = server.handle_request(- {"id": "1", "method": "session.delete", "params": {"session_id": "abc"}}- )-- assert "error" in resp- assert resp["error"]["code"] == 5036- assert resp["error"]["data"]["code"] == "storage_locked"---def test_session_delete_refuses_active_session(monkeypatch):- """Cannot delete a session currently bound to a live TUI session."""- called: list[str] = []-- class _DB:- def delete_session(self, sid, sessions_dir=None, **_kw):- called.append(sid)- return True-- monkeypatch.setattr(server, "_get_db", lambda: _DB())- monkeypatch.setitem(server._sessions, "live", {"session_key": "key-live"})- try:- resp = server.handle_request(- {- "id": "1",- "method": "session.delete",- "params": {"session_id": "key-live"},- }- )- finally:- server._sessions.pop("live", None)-- assert "error" in resp- assert resp["error"]["code"] == 4023- assert called == [], "delete_session must not be called for active sessions"---def test_session_delete_fails_closed_when_active_snapshot_raises(monkeypatch):- """Concurrent ``_sessions`` mutation from another RPC thread can raise- ``RuntimeError: dictionary changed size during iteration``. When the- handler can't enumerate active sessions safely it must refuse the- delete (fail closed) rather than fall through and allow it."""-- class _DB:- def delete_session(self, *a, **kw):- raise AssertionError("delete must not run when active snapshot fails")-- class _ExplodingDict:- def values(self):- raise RuntimeError("dictionary changed size during iteration")-- monkeypatch.setattr(server, "_get_db", lambda: _DB())- monkeypatch.setattr(server, "_sessions", _ExplodingDict())-- resp = server.handle_request(- {"id": "1", "method": "session.delete", "params": {"session_id": "x"}}- )-- assert "error" in resp- assert resp["error"]["code"] == 5036---def test_session_delete_returns_4007_when_missing(monkeypatch):- class _DB:- def delete_session(self, sid, sessions_dir=None, **_kw):- return False-- monkeypatch.setattr(server, "_get_db", lambda: _DB())-- resp = server.handle_request(- {"id": "1", "method": "session.delete", "params": {"session_id": "ghost"}}- )-- assert "error" in resp- assert resp["error"]["code"] == 4007---def test_session_delete_propagates_db_exception(monkeypatch):- class _DB:- def delete_session(self, sid, sessions_dir=None, **_kw):- raise RuntimeError("disk full")-- monkeypatch.setattr(server, "_get_db", lambda: _DB())-- resp = server.handle_request(- {"id": "1", "method": "session.delete", "params": {"session_id": "x"}}- )-- assert "error" in resp- assert resp["error"]["code"] == 5036- assert "disk full" in resp["error"]["message"]---def test_session_delete_success_returns_deleted_id(monkeypatch):- """Happy path — DB delete succeeds, response carries the deleted id- and the on-disk sessions dir is forwarded so transcript files get- cleaned up alongside the row."""- captured: dict = {}-- class _DB:- def delete_session(self, sid, sessions_dir=None, **_kw):- captured["sid"] = sid- captured["sessions_dir"] = sessions_dir- return True-- monkeypatch.setattr(server, "_get_db", lambda: _DB())-- resp = server.handle_request(- {"id": "1", "method": "session.delete", "params": {"session_id": "old-1"}}- )-- assert "result" in resp, resp- assert resp["result"] == {"deleted": "old-1"}- assert captured["sid"] == "old-1"- # sessions_dir must be forwarded so transcript files get cleaned up- # too — not just the SQLite row. The autouse _isolate_hermes_home- # fixture pins HERMES_HOME to a temp dir; the handler should append- # /sessions to it.- assert captured["sessions_dir"] is not None- assert str(captured["sessions_dir"]).endswith("sessions")-----# ---------------------------------------------------------------------------# session.* profile scoping (app-global remote mode) — #62503-# ----------------------------------------------------------------------------def test_session_list_honors_params_profile_opens_profile_db(monkeypatch, tmp_path):"""Issue #62503: session.list must read the profile's state.db, not launch."""profile_home = tmp_path / "profiles" / "mlperf"@@ -16193,42 +15987,6 @@ def test_session_create_reports_requested_profile_name(monkeypatch, tmp_path):_clear()-def test_session_delete_honors_params_profile_sessions_dir(monkeypatch, tmp_path):- """Issue #62503: delete must target the profile state.db + sessions dir."""- profile_home = tmp_path / "profiles" / "mlperf"- (profile_home / "sessions").mkdir(parents=True)- captured: dict = {}-- class ProfileDB:- def __init__(self, db_path=None):- captured["db_path"] = db_path-- def delete_session(self, sid, sessions_dir=None, **_kw):- captured["sid"] = sid- captured["sessions_dir"] = sessions_dir- return True-- def close(self):- captured["closed"] = True-- monkeypatch.setattr(server, "_profile_home", lambda p: profile_home if p == "mlperf" else None)- monkeypatch.setattr(server, "_get_db", lambda: None)- monkeypatch.setattr("hermes_state_registry.acquire", ProfileDB)-- resp = server.handle_request(- {- "id": "1",- "method": "session.delete",- "params": {"session_id": "old-ml", "profile": "mlperf"},- }- )- assert "result" in resp, resp- assert resp["result"] == {"deleted": "old-ml"}- assert str(captured["db_path"]).endswith("state.db")- assert Path(captured["sessions_dir"]) == profile_home / "sessions"- assert captured.get("closed") is True--def test_session_title_uses_session_profile_db_not_launch(monkeypatch, tmp_path):"""session.title on a non-launch profile session must not touch launch DB."""profile_home = tmp_path / "profiles" / "mlperf"@@ -17200,8 +16958,6 @@ def test_session_branch_uses_persisted_display_history_after_compaction(monkeypaserver._sessions.pop(key, None)--# --------------------------------------------------------------------------# model.options — curated-list parity with `hermes model` and classic /model# --------------------------------------------------------------------------@@ -17276,8 +17032,6 @@ def test_model_options_propagates_list_exception(monkeypatch):assert "catalog blew up" in resp["error"]["message"]--def test_model_options_preserves_canonical_custom_row_after_agent_init(monkeypatch):from hermes_cli.inventory import ConfigContext@@ -17438,8 +17192,6 @@ def test_model_save_key_reconciles_the_launch_profiles_stale_setup_record(monkey# -----------------------------------------------------------------------------def test_prompt_submit_releases_old_history_before_heap_trim(monkeypatch, tmp_path):"""The post-turn heap trim must run after the turn's pre-turn history snapshots are dropped:malloc_trim cannot return pages still referenced, so a retained snapshot of a large tool@@ -17764,7 +17516,6 @@ def test_session_active_list_excludes_finalized_sessions(monkeypatch):assert [row["id"] for row in session_rows] == ["sid-live"]-def test_session_activate_returns_inflight_stream_before_completion(monkeypatch):"""Switching into a still-running live session must hydrate partial output.@@ -18241,8 +17992,6 @@ def test_browser_manage_use_swaps_the_profiles_browser_tools_for_new_agents(monkassert (backend(other_home), backend(get_hermes_home())) == ("off", "browser-use")--def test_browser_manage_connect_sets_env_and_cleans_twice(monkeypatch):"""`/browser connect` must reach the live process: set env, reap browsersessions before AND after publishing the new URL. The double-cleanup@@ -18824,8 +18573,6 @@ def test_browser_manage_disconnect_drops_env_and_cleans(monkeypatch):# ── config.get indicator normalization ───────────────────────────────--def test_config_get_indicator_normalizes_casing_and_whitespace(monkeypatch):"""Hand-edited config.yaml stays consistent with what the TUI shows.@@ -18853,8 +18600,6 @@ def test_config_get_indicator_falls_back_to_default_for_unknown(monkeypatch):assert resp["result"] == {"value": "kaomoji"}--# ── config.set indicator validation ──────────────────────────────────@@ -18876,15 +18621,9 @@ def test_config_set_indicator_accepts_known_value(monkeypatch):assert written == {"display.tui_status_indicator": "emoji"}----# ── reload.env ───────────────────────────────────────────────────────--def test_reload_env_rpc_surfaces_errors(monkeypatch):def _broken():raise RuntimeError("env path locked")@@ -18934,8 +18673,6 @@ def test_make_agent_reads_nested_max_turns(monkeypatch):assert mock_agent.call_args.kwargs["max_iterations"] == 200--def test_make_agent_nested_max_turns_takes_priority(monkeypatch):_setup_make_agent_mocks(monkeypatch, {"agent": {"max_turns": 400}, "max_turns": 100}@@ -18947,8 +18684,6 @@ def test_make_agent_nested_max_turns_takes_priority(monkeypatch):assert mock_agent.call_args.kwargs["max_iterations"] == 400--def test_make_agent_uses_session_runtime_overrides(monkeypatch):_setup_make_agent_mocks(monkeypatch, {})resolved = {}@@ -19035,8 +18770,6 @@ def test_background_agent_kwargs_falls_back_to_root_max_turns(monkeypatch):assert kwargs["max_iterations"] == 50--def test_background_agent_kwargs_handles_null_agent_config(monkeypatch):monkeypatch.setattr(server, "_load_cfg", lambda: {"agent": None, "max_turns": 40})@@ -19045,8 +18778,6 @@ def test_background_agent_kwargs_handles_null_agent_config(monkeypatch):assert kwargs["max_iterations"] == 40--def test_notification_poller_delivers_completion(monkeypatch):"""Poller picks up completion events and triggers agent turns."""import queue as _queue_mod@@ -19329,7 +19060,6 @@ def test_session_save_writes_under_hermes_home_with_system_prompt(monkeypatch, tassert payload["messages"] == history-def test_session_save_lands_in_the_sessions_own_profile_a_b_a(monkeypatch, tmp_path):"""/save writes under the SESSION's profile home, launch -> secondary -> launch under multiplexing:the RPC runs unscoped, so get_hermes_home() alone names the launch profile (#125241)."""@@ -19924,8 +19654,6 @@ def test_slash_exec_concurrent_first_use_spawns_single_worker(monkeypatch):server._sessions.pop("race-spawn", None)--def test_close_sessions_for_transport_closes_flagged_repoints_rest(monkeypatch):seen = []monkeypatch.setattr(@@ -20671,8 +20399,6 @@ def test_subscription_change_requires_tier_or_cancel():assert res["error"] == "invalid_request"--def test_subscription_upgrade_echoes_status_and_idempotency(monkeypatch):import hermes_cli.nous_billing as nb@@ -20775,8 +20501,6 @@ def test_get_usage_includes_active_subagents(monkeypatch):assert usage["active_subagents"] == 4--def test_get_usage_safe_when_active_count_raises(monkeypatch):"""A raising active_count() must not break the usage payload."""import tools.async_delegation as ad_mod@@ -21507,8 +21231,6 @@ def test_build_persist_message_with_image_refs_appends_existing_paths(monkeypatcassert result == f"what is in this photo?\n@image:{img}"--def test_build_persist_message_with_image_refs_skips_missing_paths(monkeypatch, tmp_path):"""Only paths that still exist are persisted; a missing file must notinject a dangling @image ref into the transcript."""@@ -21660,8 +21382,6 @@ def test_prompt_submit_passes_persist_user_message_to_agent(monkeypatch):server._sessions.pop("sid", None)--def test_fallback_session_info_reports_session_cwd_not_launch_dir(monkeypatch):"""A lazily-resumed session must report ITS workspace, not the gateway's.@@ -22166,8 +21886,6 @@ def test_prompt_submit_truncation_archives_instead_of_deleting(monkeypatch):server._sessions.pop("archive-trunc-sid", None)--def test_prompt_submit_unmatched_row_id_refuses_even_with_ordinal(monkeypatch):"""#82959: Unknown row_id must refuse (4018), not fall back to a client ordinal."""replaced = []diff --git a/tui_gateway/contracts/profiles_vault_complete_foreign_subagents.py b/tui_gateway/contracts/profiles_vault_complete_foreign_subagents.pyindex 59f7f5fd3ae..cdfa29db2f1 100644--- a/tui_gateway/contracts/profiles_vault_complete_foreign_subagents.py+++ b/tui_gateway/contracts/profiles_vault_complete_foreign_subagents.py@@ -401,19 +401,15 @@ method("onboarding.mark_seen", params=Params, result=OnboardingStateResult)class OnboardingRunStateResult(Result):"""``run``: onboarding opens on this launch (root config ``onboarding.run``, else a freshinstall). ``eligible``: the free tier is on for this backend (``anon_auth.guest_enabled``).- ``session_id``: the stored id of the onboarding chat still in progress, so a relaunch reopens it.- ``intro_seen``: the user left that run's intro once, so a relaunch reopens it as a normal chat."""+ ``session_id``: the stored id of the onboarding chat still in progress, so a relaunch reopens it."""run: booleligible: boolsession_id: str | None = None- intro_seen: bool = Falsemethod("onboarding.state", params=Params, result=OnboardingRunStateResult,doc="Whether desktop first-run onboarding is due, and the chat in progress; reads the root profile's config.")-method("onboarding.intro_seen", params=Params, result=OnboardingRunStateResult,- doc="Record that the user left the intro of the run in progress; returns onboarding.state.")class OnboardingSetRunParams(Params):diff --git a/tui_gateway/methods_onboarding.py b/tui_gateway/methods_onboarding.pyindex f42ab80cf5f..088528a3884 100644--- a/tui_gateway/methods_onboarding.py+++ b/tui_gateway/methods_onboarding.py@@ -72,22 +72,7 @@ def _run_state() -> dict:from hermes_cli.anon_auth import guest_enabledfrom hermes_cli.onboarding_run import should_run- from agent.onboarding_record import active_session_id, intro_seen- # The lookup ends a run whose quiet spell ran out and closes the flag, so it goes first.- with _profile_db(_ONBOARDING_PROFILE, writer=True) as db:- session_id = None if db is None else active_session_id(db)- seen = db is not None and intro_seen(db, session_id)- return {"run": should_run(), "eligible": guest_enabled(), "session_id": session_id, "intro_seen": seen}---@method("onboarding.intro_seen")-def _(rid, params: dict) -> dict:- from agent.onboarding_record import active_session_id, mark_intro_seen- with _profile_db(_ONBOARDING_PROFILE, writer=True) as db:- session_id = None if db is None else active_session_id(db)- if session_id is not None:- mark_intro_seen(db, session_id)- return _ok(rid, _run_state())+ return {"run": should_run(), "eligible": guest_enabled(), "session_id": _active_onboarding_session()}# ── first-run onboarding: one chat in the default profile, driven by setup_beat ───────────────@@ -100,14 +85,14 @@ _onboarding_start_lock = threading.Lock()def _active_onboarding_session() -> str | None:from agent.onboarding_record import active_session_id- with _profile_db(_ONBOARDING_PROFILE, writer=True) as db:+ with _profile_db(_ONBOARDING_PROFILE) as db:return None if db is None else active_session_id(db)@method("onboarding.start")def _(rid, params: dict) -> dict:from agent.onboarding_facts import read_facts- from agent.onboarding_flow import Facts, SkipAll+ from agent.onboarding_flow import End, Factsfrom agent.onboarding_record import advance, load, open_session_ids, startfrom agent.onboarding_text import CHAT_TITLE, opening_prompt# Held through the opening submit: two windows pressing start at once get one chat and one opening.@@ -135,7 +120,7 @@ def _(rid, params: dict) -> dict:# flag never closes in between; finishing it closes the flag.replaced = [sid for sid in open_ids if sid != stored]for old in replaced:- advance(db, old, SkipAll())+ advance(db, old, End("replaced"))# A chat with no messages never got its opening (a restart between start and the first turn).opening = None if (db.get_session(stored) or {}).get("message_count") else opening_prompt(facts)except Exception as e:@@ -156,7 +141,7 @@ def _(rid, params: dict) -> dict:@method("onboarding.skip")def _(rid, params: dict) -> dict:- from agent.onboarding_flow import SkipAll+ from agent.onboarding_flow import Endfrom agent.onboarding_record import advance, loadsession, err = _sess_nowait(params, rid)if err:@@ -166,7 +151,7 @@ def _(rid, params: dict) -> dict:with _session_db(session) as db:if load(db, stored) is None:return _ok(rid, {"skipped": False})- step = advance(db, stored, SkipAll())+ step = advance(db, stored, End("skipped"))# The card that waits returns to setup_beat, which reads the skipped record._cancel_session_requests(params["session_id"], "resolved", method="setup_beat")return _ok(rid, {"skipped": bool(step.result.get("skipped_all"))})diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex 71117557da7..273767894e6 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -98,14 +98,6 @@ def _release_db(db) -> None:release_or_close(db)-def _branch_title(db, parent_key: str) -> str:- """Next title in the parent's lineage (mirrors the TUI /branch naming)."""- current = db.get_session_title(parent_key) or "branch"- if hasattr(db, "get_next_title_in_lineage"):- return db.get_next_title_in_lineage(current)- return f"{current} (branch)"--def _cwd_info(session: dict, cwd: str, branch=None) -> dict:"""session.info after a cwd change: the full agent view, or the lazy shape."""if (agent := session.get("agent")) is not None:@@ -1180,6 +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_deletefrom hermes_state_errors import SessionActiveWriteGuardError # body runs on server.py globalsif not (target := params.get("session_id", "")):@@ -1195,6 +1188,7 @@ 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)except SessionActiveWriteGuardError:return _err(rid, 4023, "cannot delete an active session")diff --git a/tui_gateway/methods_session_branch.py b/tui_gateway/methods_session_branch.pyindex a7911b707c2..349110925c2 100644--- a/tui_gateway/methods_session_branch.py+++ b/tui_gateway/methods_session_branch.py@@ -10,6 +10,14 @@ from .method_ctx import HandlerRegistry, bind_module_registry = HandlerRegistry()# ── session.branch ───────────────────────────────────────────────────+def _branch_title(db, parent_key: str) -> str:+ """Next title in the parent's lineage (mirrors the TUI /branch naming)."""+ current = db.get_session_title(parent_key) or "branch"+ if hasattr(db, "get_next_title_in_lineage"):+ return db.get_next_title_in_lineage(current)+ return f"{current} (branch)"++def _visible_branch_history(messages) -> list:"""user/assistant rows with visible text, as FULL copies (reasoning + timeline-marker tags survive)."""return [dict(message) for message in messages or []