The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): onboarding claims in the default home, skip takes profile, deleting the chat ends the run (review)
alt-glitchb5a77cb23d03
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.pyindex e9b3f3e3ccd..e352028f3c2 100644--- a/gateway/session_mutations.py+++ b/gateway/session_mutations.py@@ -256,8 +256,12 @@ async def write_mutation(authority, ref, params, editor_servers, *, principal_idelse:# The receipt transaction is synchronous SQLite: run it off the event loop so a large# state.db or a contended writer lock never stalls other clients (main 1769024ca3b).- result = await asyncio.to_thread(mutate_runtime_session, authority.db, **fields,- _prepared=prepared, _authorize_write=authorize_write)+ commit = partial(mutate_runtime_session, authority.db, **fields,+ _prepared=prepared, _authorize_write=authorize_write)+ if operation == 'delete':+ from gateway.session_onboarding import ending_run_on_delete+ commit = partial(ending_run_on_delete, authority.db, ref.session_id, commit)+ result = await asyncio.to_thread(commit)try:await _project_result(authority, ref, live, params, result, editor_servers, applied=applied)finally:diff --git a/gateway/session_onboarding.py b/gateway/session_onboarding.pyindex 08b1ed440ee..9b4233bb47c 100644--- a/gateway/session_onboarding.py+++ b/gateway/session_onboarding.py@@ -58,7 +58,10 @@ async def start(connection, ref, params):raise RuntimeStoreError('invalid_params', detail=str(exc)) from exctarget = _onboarding_connection(connection)if target is not connection:- return await start(target, ref, params)+ # Dispatch entered the asking profile's scope; the claim, the facts and the chat's policy are default's.+ from gateway.session_authorities import owner_scope+ with owner_scope(target.authority):+ return await start(target, ref, params)if 'session:create' not in connection.actor.capabilities:raise RuntimeStoreError('permission_denied')authority = connection.authority@@ -69,11 +72,20 @@ async def start(connection, ref, params):async with lock:plan = await asyncio.to_thread(_choose_run, authority, request)stored = plan['stored'] or await _create_chat(connection)- await asyncio.to_thread(_settle_runs, authority, request, plan, stored)+ from gateway.session_mutations import retire_live_sessions+ from gateway.session_runtime_workers import tracked_write+ unwatched = {sid for sid in plan['replaced']+ if (live := authority.sessions.get(sid)) is None or not live.subscribers}++ def retire(deleted):+ retire_live_sessions(authority, deleted)+ return deleted+ deleted = await tracked_write(authority, partial(_settle_runs, authority, request, plan, stored, unwatched),+ retire)if plan['claimed'] is not None:from hermes_cli import free_tier_bootstrapawait asyncio.to_thread(free_tier_bootstrap.refresh_record)- _withdraw_setup_cards(authority, [] if request.fresh_launch else plan['replaced'])+ _withdraw_setup_cards(authority, [sid for sid in plan['replaced'] if sid not in deleted])chat = SessionRef(authority.profile_id, stored)await connection.resume(chat, {})opening = plan['opening'] if plan['stored'] else await asyncio.to_thread(_opening_for, authority, stored)@@ -152,9 +164,10 @@ async def _create_chat(connection):return restore_local_session(authority, staged['session_id']).session_id-def _settle_runs(authority, request, plan, stored):- """The new chat's record and title, and the end of every other open run. One open run at a time:- the kept run is open before the others end, so the install flag never closes in between."""+def _settle_runs(authority, request, plan, stored, unwatched):+ """The new chat's record and title, and the end of every other open run; returns the chats it+ deleted. One open run at a time: the kept run is open before the others end, so the install flag+ never closes in between."""from agent.onboarding_flow import Endfrom agent.onboarding_record import advance, startfrom agent.onboarding_text import CHAT_TITLE@@ -162,36 +175,49 @@ def _settle_runs(authority, request, plan, stored):if plan['stored'] is None:# The record exists before any agent is built, so the first turn already folds the toolset in.start(db, stored, plan['facts'])+ deleted = []if request.fresh_launch:- _discard_unfinished_runs(authority, plan['replaced'])- else:- for old in plan['replaced']:+ deleted = _discard_unfinished_runs(db, [sid for sid in plan['replaced'] if sid in unwatched])+ for old in plan['replaced']:+ if old not in deleted:advance(db, old, End('replaced'))if plan['stored'] is None:# After the discard, so a run started over keeps the title its deleted chat had.db.set_session_title(stored, db.get_next_title_in_lineage(CHAT_TITLE))+ return deleted-def _discard_unfinished_runs(authority, stored_ids):- """A new launch's start: the runs the app was closed on never count as done. A chat nobody holds- live is deleted the way ``session.delete`` deletes it, which ends its run (``deleted``) and tells- every window; a chat still live here (a backend that outlived the app) or one the delete refuses- keeps its messages, and its run ends as ``replaced`` so it is never resumed."""+def _discard_unfinished_runs(db, stored_ids):+ """A new launch's start: the runs the app was closed on never count as done. A chat no window+ watches is deleted the way ``session.delete`` deletes it, which ends its run (``deleted``) and+ tells every window; the caller retires the deleted ids from the authority. A chat a turn still+ writes is refused by the delete and kept, and its run ends as ``replaced`` so it is never resumed."""from pathlib import Path- from agent.onboarding_flow import End- from agent.onboarding_record import advance, delete_chat- db = authority.db+ from agent.onboarding_record import delete_chatsessions_dir = Path(db.db_path).parent / 'sessions'+ deleted = []for old in stored_ids:- deleted = False- if old not in authority.sessions:- try:- deleted = delete_chat(db, old, lambda old=old: db.delete_session(- old, sessions_dir=sessions_dir, exclude_active_write_guards=True))- except Exception:- logger.exception('onboarding.start could not delete unfinished chat %s', old)- if not deleted:- advance(db, old, End('replaced'))+ try:+ if delete_chat(db, old, lambda old=old: db.delete_session(+ old, sessions_dir=sessions_dir, exclude_active_write_guards=True)):+ deleted.append(old)+ except Exception:+ logger.exception('onboarding.start could not delete unfinished chat %s', old)+ return deleted+++def ending_run_on_delete(db, session_id, commit):+ """*commit* (the canonical delete's receipt transaction) wrapped so deleting the chat that holds+ the live run ends that run (``deleted``) and tells every window, as the sidecar's+ ``session.delete`` did. Returns the receipt."""+ from agent.onboarding_record import delete_chat+ receipt = []++ def delete():+ receipt.append(commit())+ return session_id in receipt[0]['deleted_ids']+ delete_chat(db, session_id, delete)+ return receipt[0]def _withdraw_setup_cards(authority, stored_ids):@@ -224,7 +250,13 @@ async def skip(connection, ref, params):from agent.onboarding_record import advance, loadfrom gateway.session_runtime_workers import tracked_writefrom gateway.session_server_requests import withdraw- if set(params) != {'session_id'} or not isinstance(params.get('session_id'), str) or not params['session_id']:+ from pydantic import ValidationError+ from tui_gateway.contracts.profiles_vault_complete_foreign_subagents import OnboardingSkipParams+ try:+ request = OnboardingSkipParams.model_validate(params)+ except ValidationError as exc:+ raise RuntimeStoreError('invalid_params', detail=str(exc)) from exc+ if not request.session_id:raise RuntimeStoreError('invalid_params')authority = connection.authorityauthority.authorize(connection.actor, ref, 'session:control')diff --git a/tests/gateway/test_onboarding_on_the_authority.py b/tests/gateway/test_onboarding_on_the_authority.pyindex e71e48bd8f6..8d1bb0019ba 100644--- a/tests/gateway/test_onboarding_on_the_authority.py+++ b/tests/gateway/test_onboarding_on_the_authority.py@@ -197,3 +197,112 @@ def test_the_authority_turn_plays_the_opening_and_skips_the_note_while_a_card_wa_open.pop("srq-test", None)finally:db.close()+++async def _settled(desktop, session_id):+ """The opening turn's lease released: a delete is not refused as a write in flight."""+ def idle():+ with desktop.db._read_ctx() as conn:+ return not desktop.db._guarded_ids(conn, [session_id])+ await async_wait_until(idle, timeout=10)+++async def test_start_from_a_secondary_profile_claims_in_the_default_home(tmp_path, monkeypatch):+ """Multiplexed host socket on a secondary profile: onboarding runs in ``default``, so the trial claim,+ the provider check and the chat's policy read the default home, never the asking connection's."""+ from gateway.session_authorities import SessionAuthorities+ from gateway.session_authority import initialize_session_authority+ from gateway.session_controls import AuthorityConnection+ from hermes_constants import get_hermes_home+ from hermes_state import SessionDB+ desktop = await _desktop(tmp_path, monkeypatch, [])+ home = tmp_path / ".hermes"+ work = home / "profiles" / "work"+ work.mkdir(parents=True)+ (work / "config.yaml").write_text("{}\n", encoding="utf-8") # nothing to run on in the asking profile+ claims = []++ def claim(*, assume_fresh):+ claims.append(Path(get_hermes_home()))+ monkeypatch.setattr("hermes_cli.welcome_trial.claim_desktop_free_tier", claim)+ runner = desktop.authority.runner+ runner.config = SimpleNamespace(multiplex_profiles=True)+ work_db = SessionDB(db_path=work / "state.db")+ secondary = await initialize_session_authority(runner, profile_id=str(work), instance_id="owner", db=work_db,+ register=False)+ runner.session_authorities = SessionAuthorities(home, multiplexed=True)+ runner.session_authorities.add(home, desktop.authority, name="default")+ runner.session_authorities.add(work, secondary, name="work")+ connection = AuthorityConnection(secondary, desktop.transport, {+ "user_id": "uid:1", "provider": "local", "profile_id": str(work), "instance_id": "owner",+ "profile_scope": "host"})+ try:+ started = await connection.dispatch({"jsonrpc": "2.0", "id": 1, "method": "onboarding.start", "params": {}})+ assert "result" in started, started+ assert claims == [home]+ assert started["result"]["stored_session_id"] in desktop.authority.sessions+ finally:+ await connection.close()+ await desktop.connection.close()+ work_db.close()+++async def test_skip_accepts_the_profile_the_desktop_names(tmp_path, monkeypatch):+ desktop = await _desktop(tmp_path, monkeypatch, [])+ try:+ stored = (await _request(desktop, 1, "onboarding.start", {"rerun": True}))["result"]["stored_session_id"]+ skipped = await _request(desktop, 2, "onboarding.skip", {"session_id": stored, "profile": "default"})+ assert skipped.get("result") == {"skipped": True}, skipped+ finally:+ await desktop.connection.close()+++async def test_deleting_the_onboarding_chat_from_the_sidebar_ends_the_run(tmp_path, monkeypatch):+ from agent import onboarding_record+ from hermes_cli.onboarding_run import _root_config+ from hermes_cli.config import read_user_config_raw+ turns, ended = [], []+ desktop = await _desktop(tmp_path, monkeypatch, turns)+ onboarding_record.on_ended(ended.append)+ try:+ stored = (await _request(desktop, 1, "onboarding.start", {"rerun": True}))["result"]["stored_session_id"]+ await async_wait_until(lambda: turns, timeout=10)+ await _settled(desktop, stored)+ row = desktop.db.get_session(stored)+ deleted = await _request(desktop, 2, "session.mutate", {+ "session_id": stored, "request_id": "delete-onboarding", "expected_revision": row["runtime_revision"],+ "expected_generation": row["runtime_generation"], "operation": "delete", "payload": {}})+ assert "result" in deleted, deleted+ assert [e["outcome"] for e in ended if e["stored_session_id"] == stored] == ["deleted"]+ assert read_user_config_raw(_root_config())["onboarding"]["run"] is False+ finally:+ onboarding_record._ended_listeners.remove(ended.append)+ await desktop.connection.close()+++async def test_a_fresh_launch_deletes_the_chat_the_last_launch_left_with_no_viewer(tmp_path, monkeypatch):+ """The previous launch's chat is still mounted (a backend that outlived the app, or local recovery),+ but no window watches it and no turn runs in it: the new launch's start deletes it and drops it+ from the authority."""+ from gateway.session_controls import AuthorityConnection+ turns = []+ desktop = await _desktop(tmp_path, monkeypatch, turns)+ first = (await _request(desktop, 1, "onboarding.start", {"rerun": True}))["result"]["stored_session_id"]+ await async_wait_until(lambda: turns, timeout=10)+ await _settled(desktop, first)+ await desktop.connection.close() # the app quits+ assert first in desktop.authority.sessions+ identity = {"user_id": "uid:1", "provider": "local", "profile_id": desktop.authority.profile_id,+ "instance_id": "owner"}+ desktop.connection = AuthorityConnection(desktop.authority, desktop.transport, identity)+ try:+ second = (await _request(desktop, 2, "onboarding.start", {"fresh_launch": True}))["result"]+ assert second["stored_session_id"] != first+ assert desktop.db.get_session(first) is None+ assert first not in desktop.authority.sessions+ finally:+ await desktop.connection.close()