Skip to content

The agent that grows with you

fix(desktop): reconnects keep their chat, trial chats move to a connected provider, a failed boot retries, only the Desktop starts a first run (review)

alt-glitch50245b5dce28
diff --git a/gateway/session_local.py b/gateway/session_local.py
index ca1aae6b02f..9d2e9fac050 100644
--- a/gateway/session_local.py
+++ b/gateway/session_local.py
@@ -238,7 +238,7 @@ def staged_creation_follows(authority, actor, request_id):
def _welcome_trial_model():
"""The free model for a chat that has no configured one, while the welcome trial carries this
activity (the local Desktop, a claimed guest): what the agent pins on the welcome host anyway
- (``anon_auth.pin_model_for_route``). Else None, and the create refuses."""
+ (``anon_auth.pin_model_for_route``). Else None, and the create refuses as before."""
from hermes_cli import anon_auth
return anon_auth.GUEST_MODEL if anon_auth.free_inference_active() else None
@@ -255,7 +255,7 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, truste
raise RuntimeStoreError('profile_mismatch')
if 'session:create' not in actor.capabilities:
raise RuntimeStoreError('permission_denied')
- from gateway.session_policy import build_policy, BYPASS_FIELDS
+ from gateway.session_policy import build_policy, BYPASS_FIELDS, FOLLOW_ADOPTED, LOCAL_DESKTOP_CHAT
from gateway.run import _resolve_gateway_model
from dataclasses import replace
private_secrets = dict(trusted_secrets or {})
@@ -282,12 +282,17 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, truste
policy = replace(policy, request_json=json.dumps(
{**json.loads(policy.request_json), 'model_requested': raw_model, 'route_derived': derived},
sort_keys=True))
- if desktop_local and policy.source == 'gui':
- import json
- policy = replace(policy, request_json=json.dumps(
- {**json.loads(policy.request_json), 'desktop_local': True}, sort_keys=True))
+ marks = {LOCAL_DESKTOP_CHAT: True} if desktop_local and policy.source == 'gui' else {}
if policy.model is None:
- policy = replace(policy, model=_resolve_gateway_model(policy.config()) or _welcome_trial_model())
+ configured = _resolve_gateway_model(policy.config())
+ model = configured or _welcome_trial_model()
+ if model and not configured:
+ # Follows its profile, so the provider the user connects later replaces the trial model.
+ marks[FOLLOW_ADOPTED] = True
+ policy = replace(policy, model=model)
+ if marks:
+ import json
+ policy = replace(policy, config_json=json.dumps({**json.loads(policy.config_json), **marks}))
request_id = params.get('request_id', uuid.uuid4().hex)
if not isinstance(request_id, str) or not request_id or len(request_id) > 256:
raise RuntimeStoreError('invalid_params', field='request_id',
diff --git a/gateway/session_onboarding.py b/gateway/session_onboarding.py
index 0555df633f7..d282327dd0c 100644
--- a/gateway/session_onboarding.py
+++ b/gateway/session_onboarding.py
@@ -129,6 +129,10 @@ def _claim_before_run(*, assume_fresh):
from hermes_cli import anon_auth
from hermes_cli.onboarding_run import set_run
from hermes_cli.welcome_trial import claim_desktop_free_tier, provider_configured
+ if not anon_auth.on_local_desktop_backend():
+ # A CLI or TUI holds a native ticket too: its start schedules nothing. A rerun (Settings, any
+ # Desktop) never claims and never reaches here.
+ raise _NoModelForTheRun('First-run onboarding starts only in the Desktop app on this machine.')
set_run(True)
claimed = claim_desktop_free_tier(assume_fresh=assume_fresh)
if claimed is None and not (anon_auth.free_inference_active() or provider_configured()):
diff --git a/gateway/session_policy.py b/gateway/session_policy.py
index 6766439e63f..a9266322a3c 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -24,7 +24,14 @@ FOLLOW_SECTIONS = ('model', 'providers', 'custom_providers', 'fallback_providers
# A Bot Chat an earlier build committed frozen follows its profile once a client opens it (``follow_bot_chat``).
# The marker sits in the policy's own config, so no other receipt changes shape (an older owner restores
# them all, and reads this chat as frozen), and the creation request, the exact-retry identity, stays as sent.
+# A chat created on the welcome trial's model carries it too (``stage_local_session``), so a provider the user
+# connects later replaces that model.
FOLLOW_ADOPTED = 'follow_adopted'
+# A Desktop chat its creator's connection declared local (``process_identity.local_desktop_client``): its
+# turns run as work for the local Desktop (``local_desktop_turn``). Owner-set in the policy's own config, so
+# an exact create retry from a socket whose declaration has not landed carries the same creation request,
+# and ``launch_request`` never echoes it.
+LOCAL_DESKTOP_CHAT = 'desktop_local'
# A launch field's state as a committed session edit left it, in the policy's own config: ``True`` the
# session chose it (``/reasoning <level>``, a model pick carrying one), ``False`` a reset gave it back to
# the profile. Either wins over the creation request (the launch identity, never rewritten) and the older
@@ -1007,7 +1014,7 @@ def local_desktop_turn(runner, source, scope):
policy = None
if getattr(source, 'platform', None) == Platform.LOCAL:
policy = getattr(runner._adapter_for_source(source), 'policies', {}).get(source.chat_id)
- if policy is None or policy.source != 'gui' or json.loads(policy.request_json).get('desktop_local') is not True:
+ if policy is None or policy.source != 'gui' or json.loads(policy.config_json).get(LOCAL_DESKTOP_CHAT) is not True:
return scope
return _serving_local_desktop_within(scope)
diff --git a/hermes_cli/free_tier_bootstrap.py b/hermes_cli/free_tier_bootstrap.py
index 64c9f989382..8d214acd923 100644
--- a/hermes_cli/free_tier_bootstrap.py
+++ b/hermes_cli/free_tier_bootstrap.py
@@ -63,6 +63,8 @@ _lock = threading.Lock()
_record: Optional[SetupRecord] = None
_done = threading.Event()
_started = False
+_settled = False # the bootstrap recorded the install and settled the claim (``_settle_install``)
+_resettle_lock = threading.Lock()
# ``(mtime_ns, size)`` of the files the inventory reads, taken by the inventory that built the
# current record; ``reconcile_record`` re-inventories only when they moved.
_inventory_stamp: Optional[tuple] = None
@@ -117,10 +119,11 @@ def reconcile_record() -> Optional[SetupRecord]:
def reset_for_tests() -> None:
- global _record, _started, _inventory_stamp
+ global _record, _started, _settled, _inventory_stamp
with _lock:
_record = None
_started = False
+ _settled = False
_inventory_stamp = None
_done.clear()
@@ -189,7 +192,7 @@ def run_bootstrap(*, announce: bool = True) -> SetupRecord:
"""Settle an interrupted claim -> inventory -> resolve inference -> record ->
broadcast. Idempotent per process: a second call returns the existing record. Never raises.
``announce=False`` skips the ``setup.ready`` event."""
- global _record, _started
+ global _record, _started, _settled
with _lock:
if _record is not None:
return _record
@@ -199,25 +202,53 @@ def run_bootstrap(*, announce: bool = True) -> SetupRecord:
return _record
_started = True
+ settled = _settle_install()
+ record = _build_record(other=_inventory_other_providers())
+ with _lock:
+ _record, _settled = record, settled
+ _done.set()
+ if announce:
+ _broadcast(record)
+ return record
+
+
+def _settle_install() -> bool:
+ """Record a fresh install and settle the guest's claim; True when neither step failed. A failure is
+ logged: onboarding.state still answers live, and the record still says who carries inference."""
+ settled = True
try:
from hermes_cli import anon_auth
from hermes_cli.onboarding_run import latch_first_install
if anon_auth.on_local_desktop_backend():
latch_first_install()
- except Exception: # the next boot tries again; onboarding.state still answers live
+ except Exception:
+ settled = False
logger.warning("onboarding: could not record the first-install decision", exc_info=True)
try:
from hermes_cli.welcome_trial import settle_interrupted_claim
settle_interrupted_claim()
- except Exception: # the record still says who carries inference without it
+ except Exception:
+ settled = False
logger.warning("free tier: could not settle an interrupted claim", exc_info=True)
- record = _build_record(other=_inventory_other_providers())
+ return settled
+
+
+def resettle_after_failed_boot() -> None:
+ """The local Desktop connected again to a process whose bootstrap could not settle the install:
+ try those steps again and rebuild the record when they pass. Nothing before the bootstrap
+ finished or once it settled."""
+ global _settled
with _lock:
- _record = record
- _done.set()
- if announce:
- _broadcast(record)
- return record
+ unsettled = _record is not None and not _settled
+ if not unsettled or not _resettle_lock.acquire(blocking=False): # one retry at a time
+ return
+ try:
+ if _settle_install():
+ with _lock:
+ _settled = True
+ refresh_record()
+ finally:
+ _resettle_lock.release()
def refresh_record(*, announce: bool = True) -> Optional[SetupRecord]:
diff --git a/tests/gateway/test_local_desktop_identity.py b/tests/gateway/test_local_desktop_identity.py
index 322642c65c2..6840f2531f4 100644
--- a/tests/gateway/test_local_desktop_identity.py
+++ b/tests/gateway/test_local_desktop_identity.py
@@ -232,3 +232,91 @@ def test_the_desktop_boot_work_runs_for_the_launch_profile_whichever_profile_con
reset_hermes_home_override(token)
free_tier_bootstrap.reset_for_tests()
assert seen == [launch]
+
+
+async def test_an_exact_create_retry_from_a_socket_not_yet_declared_local_resumes_the_chat(tmp_path, monkeypatch):
+ """After a reconnect the Desktop retries ``session.create`` with the same request_id, and its
+ declaration may not have landed on the new socket yet. The retry carries the same request, so it
+ gets the same chat, which still runs as the local Desktop's; no viewer sees the stamp."""
+ from contextlib import nullcontext
+ from gateway.session_local_recovery import local_source
+ from gateway.session_policy import local_desktop_turn
+ from hermes_cli.anon_auth import on_local_desktop_backend
+
+ conn = await _connect(tmp_path, monkeypatch,
+ config="model:\n provider: openrouter\n default: anthropic/claude-sonnet-4\n")
+ try:
+ await _request(conn, 1, "client.capabilities", {"desktop_local": True})
+ first = await _request(conn, 2, "session.create", {"source": "gui", "request_id": "a"})
+ assert "result" in first, first
+ conn.transport.desktop_local = False
+ retry = await _request(conn, 3, "session.create", {"source": "gui", "request_id": "a"})
+ assert "result" in retry, retry
+ stored = first["result"]["stored_session_id"]
+ assert retry["result"]["stored_session_id"] == stored
+
+ source = local_source(conn.authority, stored, conn.connection.actor.subject)
+ with local_desktop_turn(conn.runner, source, nullcontext()):
+ assert on_local_desktop_backend() is True
+ from gateway.session_local import local_session_info
+ from gateway.session_contract import SessionRef
+ info = local_session_info(conn.authority, SessionRef(conn.authority.profile_id, stored))
+ assert "desktop_local" not in info["launch_request"]
+ finally:
+ await conn.connection.close()
+
+
+async def test_a_chat_opened_on_the_trial_moves_to_the_provider_the_user_connects(tmp_path, monkeypatch):
+ """A trial-only chat runs on the free model; once the user connects a real provider, the same
+ chat's next turn runs on that provider's model instead of asking a paid route for nous/welcome."""
+ from hermes_cli import anon_auth
+ from hermes_state_local import local_receipt
+ from gateway.session_policy import restore_policy
+ guest = {"auth_method": anon_auth.ANON_AUTH_METHOD, anon_auth.WELCOME_CLAIM_FLAG: True}
+ monkeypatch.setattr(anon_auth, "current_nous_state", lambda *a, **k: guest)
+ conn = await _connect(tmp_path, monkeypatch)
+ try:
+ await _request(conn, 1, "client.capabilities", {"desktop_local": True})
+ created = await _request(conn, 2, "session.create", {"source": "gui", "request_id": "a"})
+ stored = created["result"]["stored_session_id"]
+
+ def next_model():
+ return restore_policy(local_receipt(conn.authority.db, stored)["policy"]).current_model(conn.authority)
+
+ assert next_model() == anon_auth.GUEST_MODEL
+ (Path(conn.authority.db.db_path).parent / "config.yaml").write_text( # the owning profile's
+ "model:\n provider: openrouter\n default: anthropic/claude-sonnet-4\n", encoding="utf-8")
+ assert next_model() == "anthropic/claude-sonnet-4"
+ finally:
+ await conn.connection.close()
+
+
+async def test_a_desktop_boot_that_could_not_record_the_install_tries_again_on_the_next_connection(
+ tmp_path, monkeypatch):
+ """The gateway outlives app launches. A first boot whose install record failed (a locked
+ config.yaml) is retried when the Desktop next connects, as the per-launch ``hermes serve`` did."""
+ from hermes_cli import free_tier_bootstrap, onboarding_run
+ from tui_gateway import server
+ attempts = []
+
+ def latch():
+ attempts.append(len(attempts))
+ if len(attempts) == 1:
+ raise OSError("config.yaml is locked")
+ return True
+
+ monkeypatch.setattr(onboarding_run, "latch_first_install", latch)
+ monkeypatch.setattr(server, "_local_desktop_boot_started", False)
+ free_tier_bootstrap.reset_for_tests()
+ conn = await _connect(tmp_path, monkeypatch)
+ try:
+ await _request(conn, 1, "client.capabilities", {"desktop_local": True})
+ assert free_tier_bootstrap.wait_for_record(timeout=20) is not None
+ await _request(conn, 2, "client.capabilities", {"desktop_local": True})
+ await async_wait_until(lambda: len(attempts) == 2, timeout=20, what="the boot ran again")
+ finally:
+ await conn.connection.close()
+ free_tier_bootstrap.reset_for_tests()
diff --git a/tests/gateway/test_onboarding_on_the_authority.py b/tests/gateway/test_onboarding_on_the_authority.py
index d2b6707be6e..3828d8d67f6 100644
--- a/tests/gateway/test_onboarding_on_the_authority.py
+++ b/tests/gateway/test_onboarding_on_the_authority.py
@@ -56,7 +56,9 @@ async def _desktop(tmp_path, monkeypatch, turns):
runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)
authority = await initialize_session_authority(runner, profile_id=str(home), instance_id="owner")
transport = _Transport()
- identity = {"user_id": "uid:1", "provider": "local", "profile_id": str(home), "instance_id": "owner"}
+ identity = {"user_id": "uid:1", "provider": "local", "profile_id": str(home), "instance_id": "owner",
+ "native_bootstrap": True}
+ transport.desktop_local = True # the Desktop's accepted ``client.capabilities {desktop_local}``
connection = AuthorityConnection(authority, transport, identity)
from gateway.session_local_migration import bind_native_transport
bind_native_transport(authority, connection.actor, identity)
@@ -229,7 +231,9 @@ async def test_start_from_a_secondary_profile_claims_in_the_default_home(tmp_pat
"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": {}})
+ from hermes_cli.process_identity import serving_local_desktop
+ with serving_local_desktop(True): # what ws._dispatch_request binds for the declared Desktop socket
+ 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
@@ -297,3 +301,19 @@ async def test_a_fresh_launch_deletes_the_chat_the_last_launch_left_with_no_view
assert first not in desktop.authority.sessions
finally:
await desktop.connection.close()
+
+
+async def test_onboarding_start_from_a_client_that_is_not_the_local_desktop_changes_nothing(tmp_path, monkeypatch):
+ """A CLI or TUI holds a native ticket too. Its ``onboarding.start`` is refused before the install
+ flag is written, so it never schedules first-run onboarding for the Desktop."""
+ from hermes_cli.onboarding_run import _explicit_run
+ desktop = await _desktop(tmp_path, monkeypatch, [])
+ desktop.transport.desktop_local = False
+ try:
+ refused = await _request(desktop, 1, "onboarding.start", {"facts_source": "local", "locale": "en"})
+ assert "error" in refused, refused
+ assert _explicit_run() is None
+ assert desktop.authority.sessions == {}
+ finally:
+ await desktop.connection.close()
diff --git a/tests/tui_gateway/test_onboarding_session.py b/tests/tui_gateway/test_onboarding_session.py
index 0a9df1dd5d7..a2c9340c98e 100644
--- a/tests/tui_gateway/test_onboarding_session.py
+++ b/tests/tui_gateway/test_onboarding_session.py
@@ -49,7 +49,9 @@ def client(root, monkeypatch):
monkeypatch.setitem(server._methods, "session.resume", resume)
monkeypatch.setitem(server._methods, "prompt.submit", submit)
- return calls
+ from hermes_cli.process_identity import serving_local_desktop
+ with serving_local_desktop(True): # the local Desktop's requests: only it starts a first run
+ yield calls
def _call(method: str, params: dict | None = None) -> dict:
@@ -391,3 +393,10 @@ def test_the_onboarding_facts_are_read_in_the_default_profile(root, client, monk
_call("onboarding.start")
assert homes == [root]
+
+
+def test_a_start_outside_the_local_desktop_schedules_nothing(root):
+ """A CLI or TUI calling onboarding.start is refused before ``onboarding.run`` is written."""
+ from hermes_cli.onboarding_run import _explicit_run
+ assert _call("onboarding.start")["error"]["code"] == 5080
+ assert _explicit_run() is None
diff --git a/tui_gateway/methods_onboarding.py b/tui_gateway/methods_onboarding.py
index b9771d65cdc..c45f5c8814f 100644
--- a/tui_gateway/methods_onboarding.py
+++ b/tui_gateway/methods_onboarding.py
@@ -106,19 +106,23 @@ _local_desktop_boot_started = False
def begin_local_desktop_boot() -> None:
- """The local Desktop's first accepted connection to this process: record a fresh install, settle an
- interrupted claim, the setup record and the due answer, once, as work for that Desktop."""
+ """An accepted local Desktop connection to this process: record a fresh install, settle an
+ interrupted claim, the setup record and the due answer, once, as work for that Desktop. This
+ process outlives app launches, so a later connection retries the install steps a failed boot
+ left unsettled."""
global _local_desktop_boot_started
+ from agent.memory_provider import spawn_context_thread
from hermes_cli import free_tier_bootstrap
from hermes_cli.process_identity import serving_local_desktop
from tui_gateway.launch_profile_policy import launch_profile_scope_if_multiplexed
with _local_desktop_boot_lock:
- if _local_desktop_boot_started:
- return
- _local_desktop_boot_started = True
+ first, _local_desktop_boot_started = not _local_desktop_boot_started, True
# The record and the latch are the launch profile's; the connecting profile may be another one.
with launch_profile_scope_if_multiplexed(), serving_local_desktop(True): # threads copy this context
+ if not first:
+ spawn_context_thread(free_tier_bootstrap.resettle_after_failed_boot, name="free-tier-resettle").start()
+ return
free_tier_bootstrap.start_background_bootstrap()
start_due_boot()
@@ -152,6 +156,8 @@ def _claim_before_run(scope: dict, *, assume_fresh: bool):
from hermes_cli import anon_auth
from hermes_cli.onboarding_run import set_run
from hermes_cli.welcome_trial import claim_desktop_free_tier, provider_configured
+ if not anon_auth.on_local_desktop_backend(): # gateway/session_onboarding.py::_claim_before_run
+ raise _NoModelForTheRun("First-run onboarding starts only in the Desktop app on this machine.")
set_run(True)
with _session_profile_runtime_scope(scope):
claimed = claim_desktop_free_tier(assume_fresh=assume_fresh)