The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): give a fresh install its onboarding and free trial again
alt-glitch5e2b545dd998
diff --git a/apps/desktop/src/api/canonical-clarify-prompt.test.ts b/apps/desktop/src/api/canonical-clarify-prompt.test.tsindex 6e43061c699..b7fa358f2b4 100644--- a/apps/desktop/src/api/canonical-clarify-prompt.test.ts+++ b/apps/desktop/src/api/canonical-clarify-prompt.test.ts@@ -17,6 +17,8 @@ test('a reopened sibling chat delivers retained questions before returning and rserver.on('connection', (socket: any) => socket.on('message', (bytes: Buffer) => {const frame = JSON.parse(bytes.toString())+ // The connection's own handshake (the local-Desktop declaration), not a frame under test.+ if (frame.method === 'client.capabilities') { socket.send(JSON.stringify({ jsonrpc: '2.0', id: frame.id, result: { server_requests: [] } })); return }sent.push(frame)socket.send(JSON.stringify({ jsonrpc: '2.0', id: frame.id,result: frame.method === 'session.resume' ? snapshot : { status: 'resolved' } }))@@ -57,6 +59,8 @@ test('a canonical clarify prompt drives the question card and its lock answers oserver.on('connection', (socket: any) => {socket.on('message', (bytes: Buffer) => {const frame = JSON.parse(bytes.toString())+ // The connection's own handshake (the local-Desktop declaration), not a frame under test.+ if (frame.method === 'client.capabilities') { socket.send(JSON.stringify({ jsonrpc: '2.0', id: frame.id, result: { server_requests: [] } })); return }sent.push(frame)socket.send(JSON.stringify({ jsonrpc: '2.0', id: frame.id, result: { status: 'resolved' } }))})diff --git a/apps/desktop/src/api/canonical-create-options.test.ts b/apps/desktop/src/api/canonical-create-options.test.tsindex 44a5f392f9c..9f946dc8263 100644--- a/apps/desktop/src/api/canonical-create-options.test.ts+++ b/apps/desktop/src/api/canonical-create-options.test.ts@@ -39,6 +39,8 @@ test.each(CASES)('%s: the Desktop create frame is admitted by the owner contractserver.on('connection', (socket: any) => {socket.on('message', (bytes: Buffer) => {const frame = JSON.parse(bytes.toString())+ // The connection's own handshake (the local-Desktop declaration), not a frame under test.+ if (frame.method === 'client.capabilities') { socket.send(JSON.stringify({ jsonrpc: '2.0', id: frame.id, result: { server_requests: [] } })); return }sent.push(frame)const fields = Object.keys(frame.params).filter(key => !CREATE_KEYS.has(key))diff --git a/apps/desktop/src/api/canonical-producer-contract.test.ts b/apps/desktop/src/api/canonical-producer-contract.test.tsindex a9def001914..b6b8864f84b 100644--- a/apps/desktop/src/api/canonical-producer-contract.test.ts+++ b/apps/desktop/src/api/canonical-producer-contract.test.ts@@ -233,6 +233,8 @@ test.each(SITES)('%s: the canonical frame fits the generated contract', async (_server.on('connection', (socket: any) => {socket.on('message', (bytes: Buffer) => {const frame = JSON.parse(bytes.toString())+ // The connection's own handshake (the local-Desktop declaration), not a frame under test.+ if (frame.method === 'client.capabilities') { socket.send(JSON.stringify({ jsonrpc: '2.0', id: frame.id, result: { server_requests: [] } })); return }sent.push(frame)const fields = problems(frame.method, frame.params)const error = { code: 4001, message: 'invalid_params', data: { reason: 'invalid_params', fields } }diff --git a/apps/desktop/src/api/canonical-profile-route.test.ts b/apps/desktop/src/api/canonical-profile-route.test.tsindex 7ddb71227fd..2651779b4db 100644--- a/apps/desktop/src/api/canonical-profile-route.test.ts+++ b/apps/desktop/src/api/canonical-profile-route.test.ts@@ -15,6 +15,8 @@ test('a sibling profile route survives canonical request translation', async ()server.on('connection', (socket: any) => {socket.on('message', (bytes: Buffer) => {const frame = JSON.parse(bytes.toString())+ // The connection's own handshake (the local-Desktop declaration), not a frame under test.+ if (frame.method === 'client.capabilities') { socket.send(JSON.stringify({ jsonrpc: '2.0', id: frame.id, result: { server_requests: [] } })); return }sent.push(frame)const snapshot = { session_id: 's', stored_session_id: 's', revision: 2, execution_generation: 5, messages: [],diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.tsindex 3834ee9fab9..53d07b5e668 100644--- a/apps/desktop/src/api/client.ts+++ b/apps/desktop/src/api/client.ts@@ -327,6 +327,12 @@ export class HermesGateway extends JsonRpcGatewayClient {})}+ // Only a local connection dials natively (electron/local-gateway.ts): this machine's gateway, with+ // a ticket from its private control socket, which is what the backend checks the claim against.+ protected override isDesktopLocal(): boolean {+ return this.canonical+ }+override async connect(wsUrl: string): Promise<void> {this.connectionGeneration++this.canonical = new URL(wsUrl).searchParams.has('native_dial')diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 3e678bed20e..262a4794b28 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -1914,6 +1914,7 @@ export interface GatewayCapabilitiesResult {}export interface ClientCapabilitiesParams {server_requests?: boolean+ desktop_local?: boolean}export interface ClientCapabilitiesResult {server_requests: string[]diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex d5fd22f4ad0..94cae092793 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -11957,6 +11957,11 @@"default": false,"title": "Server Requests","type": "boolean"+ },+ "desktop_local": {+ "default": false,+ "title": "Desktop Local",+ "type": "boolean"}},"title": "ClientCapabilitiesParams",diff --git a/apps/shared/src/json-rpc-channel.test.ts b/apps/shared/src/json-rpc-channel.test.tsindex fde24a7f049..00867b01fe3 100644--- a/apps/shared/src/json-rpc-channel.test.ts+++ b/apps/shared/src/json-rpc-channel.test.ts@@ -193,6 +193,26 @@ describe('JsonRpcRequestChannel', () => {expect(sent).toHaveLength(1)})+ it('says it is the local Desktop first on the socket, in a call of its own', () => {+ // The boot's first onboarding.state goes out as soon as the socket opens; the backend reads frames+ // in order, so the declaration must already be ahead of it. Its own call: a backend older than the+ // field refuses only it and keeps server_requests.+ let local = true+ const channel = new JsonRpcRequestChannel({ desktopLocal: () => local, requestIdPrefix: 'c' })+ const { sent, transport } = spyTransport()+ const params = () => sent.map(frame => JSON.parse(frame).params)++ channel.attach(transport)+ void channel.request('onboarding.state', { assume_fresh: true }).catch(() => undefined)+ channel.handleFrame(JSON.stringify({ jsonrpc: '2.0', method: 'event', params: { type: 'gateway.ready', payload: {} } }))+ expect(params()).toEqual([{ desktop_local: true }, { assume_fresh: true }, { server_requests: true }])++ // A remote connection says nothing.+ local = false+ channel.attach(spyTransport().transport)+ expect(params()).toHaveLength(3)+ })+it('sends a not-shown decline only to a backend that advertised counting it', async () => {// An older backend settles a request on the first error frame, so a bystander window's decline// would beat the owner's answer (#113348): there `decline` must stay silent.diff --git a/apps/shared/src/json-rpc-channel.ts b/apps/shared/src/json-rpc-channel.tsindex b7bcfb61d8e..4a753c86958 100644--- a/apps/shared/src/json-rpc-channel.ts+++ b/apps/shared/src/json-rpc-channel.ts@@ -146,6 +146,11 @@ export interface JsonRpcRequestChannelOptions {heartbeatLiveness?: HeartbeatLiveness/** `setTimeout`/`setInterval` handles are `unref`'d when the runtime supports it (Node) so a pending call cannot pin the process. */unrefTimers?: boolean+ /**+ * Read at each attach: this client is the Desktop app connected to a backend on its own machine.+ * The backend offers the welcome trial and first-run onboarding only to that client.+ */+ desktopLocal?: () => boolean}export type HeartbeatLiveness = 'any-inbound' | 'response'@@ -215,6 +220,7 @@ export class JsonRpcRequestChannel {constructor(options: JsonRpcRequestChannelOptions = {}) {this.options = {createRequestId: options.createRequestId ?? ((nextId: number) => `${options.requestIdPrefix ?? 'r'}${nextId}`),+ desktopLocal: options.desktopLocal ?? (() => false),heartbeatDeadlineMs: options.heartbeatDeadlineMs ?? DEFAULT_HEARTBEAT_DEADLINE_MS,heartbeatIntervalMs: options.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS,heartbeatLiveness: options.heartbeatLiveness ?? 'response',@@ -242,6 +248,13 @@ export class JsonRpcRequestChannel {this.transport = transportthis.lastLivenessAt = Date.now()this.backendCountsDeclines = false++ // First on the socket, before the owner's own requests: the backend reads frames in order, and its+ // answer to the boot's first onboarding.state already depends on this. A call of its own, so a+ // backend older than the field refuses just this one (4000) and keeps server_requests.+ if (this.options.desktopLocal()) {+ this.request('client.capabilities', { desktop_local: true }).catch(() => undefined)+ }}/** Drop the transport and fail every in-flight call with `error`. */diff --git a/apps/shared/src/json-rpc-gateway.ts b/apps/shared/src/json-rpc-gateway.tsindex de2d09ee4bb..fa97c67a591 100644--- a/apps/shared/src/json-rpc-gateway.ts+++ b/apps/shared/src/json-rpc-gateway.ts@@ -168,6 +168,14 @@ export class JsonRpcGatewayClient {> &Pick<GatewayClientOptions, 'onRequestHandlerError' | 'onUnhandledRequest' | 'socketFactory'>+ /**+ * This client is the Desktop app on the backend's own machine, read at each socket open+ * (`JsonRpcRequestChannelOptions.desktopLocal`). Only the Desktop's client knows; others are not.+ */+ protected isDesktopLocal(): boolean {+ return false+ }+constructor(options: GatewayClientOptions = {}) {this.options = {closedErrorMessage: options.closedErrorMessage ?? 'WebSocket closed',@@ -187,6 +195,7 @@ export class JsonRpcGatewayClient {}this.channel = new JsonRpcRequestChannel({createRequestId: this.options.createRequestId,+ desktopLocal: () => this.isDesktopLocal(),heartbeatDeadlineMs: this.options.heartbeatDeadlineMs,heartbeatIntervalMs: this.options.heartbeatIntervalMs,// Desktop/web and the TUI alike count any inbound frame as livenessdiff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex f89092af83d..a3e1c479624 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -349,10 +349,10 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway(``multiplex_profiles`` off) still binds once a hosted room has flipped the process-widecredential guard — see ``_standalone_launch_scope``."""from gateway.run import _profile_runtime_scope+ from gateway.session_policy import local_desktop_turnhome = self._profile_scope_key_for_source(source)- if home is not None:- return _profile_runtime_scope(home)- return self._standalone_launch_scope()+ return local_desktop_turn(self, source, _profile_runtime_scope(home) if home is not None+ else self._standalone_launch_scope())def _profile_scope_key_for_source(self, source: SessionSource) -> Optional[Path]:"""Profile home ``_profile_scope_for_source`` binds for ``source``, or ``None`` when it fallsdiff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 5353bb431f4..65887575dec 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -464,7 +464,8 @@ class AuthorityConnection:skills_prompt = await asyncio.to_thread(render_launch_skills, params, sid)# Host-bound client values apply only over the gateway's own ticketed attach (run_api).ref = stage_local_session(self.authority, self.actor, params, skills_prompt=skills_prompt,- client_local=self.native_owner)+ client_local=self.native_owner,+ desktop_local=getattr(self.transport, 'desktop_local', False))if isinstance(ref, dict):# The creation commit runs off the owner loop: a held writer must not freeze# every session behind one new chat (N50).diff --git a/gateway/session_local.py b/gateway/session_local.pyindex f161314395a..eb910662d1e 100644--- a/gateway/session_local.py+++ b/gateway/session_local.py@@ -235,12 +235,22 @@ def staged_creation_follows(authority, actor, request_id):return isinstance(request, dict) and request.get('follow_profile_config') is True+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 as before."""+ from hermes_cli import anon_auth+ return anon_auth.GUEST_MODEL if anon_auth.free_inference_active() else None++def stage_local_session(authority, actor, params, *, trusted_policy=None, trusted_secrets=None, skills_prompt=None,- client_local=False):+ client_local=False, desktop_local=False):"""Everything before the creation commit: the existing session's ref on an exact retry, else thereceipt ``commit_local_session`` writes (the async RPC commits it off the owner loop).``client_local``: the gateway's own proof that the client is on this host (its connection redeemed a- ticket minted over the private control socket), never a value the client sends."""+ ticket minted over the private control socket), never a value the client sends. ``desktop_local``:+ that client is also the Desktop app (``process_identity.local_desktop_client``); a Desktop chat+ records it so its turns run as work for the local Desktop (``session_policy.local_desktop_turn``)."""if actor.profile_id != authority.profile_id:raise RuntimeStoreError('profile_mismatch')if 'session:create' not in actor.capabilities:@@ -272,8 +282,12 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, trustepolicy = 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 # owner-stamped like ``model_requested``: the client cannot send it as a create field+ policy = replace(policy, request_json=json.dumps(+ {**json.loads(policy.request_json), 'desktop_local': True}, sort_keys=True))if policy.model is None:- policy = replace(policy, model=_resolve_gateway_model(policy.config()))+ policy = replace(policy, model=_resolve_gateway_model(policy.config()) or _welcome_trial_model())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.pyindex 9b4233bb47c..1fc7ee1c341 100644--- a/gateway/session_onboarding.py+++ b/gateway/session_onboarding.py@@ -155,7 +155,8 @@ async def _create_chat(connection):from hermes_state_local import commit_local_sessionauthority = connection.authoritystaged = stage_local_session(authority, connection.actor, {'source': 'gui', 'request_id': uuid.uuid4().hex},- client_local=connection.native_owner)+ client_local=connection.native_owner,+ desktop_local=getattr(connection.transport, 'desktop_local', False))if not (staged['policy'] or {}).get('model'):# Nothing to run the chat on (a rerun before any provider is set up): no chat, the way a blocked# claim opens none, instead of a row whose launch policy can never be restored.diff --git a/gateway/session_policy.py b/gateway/session_policy.pyindex 328decbab36..6766439e63f 100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@ -998,6 +998,27 @@ def policy_turn_toolsets(authority, policy, config, session_id):return onboarding_chat_toolsets(list(policy.current_toolsets(config)), getattr(authority, 'db', None), session_id)+def local_desktop_turn(runner, source, scope):+ """*scope* (the profile scope a turn enters), also marked as work for the local Desktop when the+ turn belongs to a Desktop chat its creator's connection declared local (``stage_local_session``);+ any other turn gets *scope* untouched. Read from the live policy without raising: a cold policy+ is restored, or refused, by the turn."""+ from gateway.config import Platform+ 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:+ return scope+ return _serving_local_desktop_within(scope)+++@contextmanager+def _serving_local_desktop_within(scope):+ from hermes_cli.process_identity import serving_local_desktop+ with scope, serving_local_desktop(True):+ yield++def policy_for_source(runner, source):from gateway.session_local import LocalSessionAdapterfrom gateway.config import Platformdiff --git a/hermes_cli/anon_challenge.py b/hermes_cli/anon_challenge.pyindex b1203d447b1..fb383af7131 100644--- a/hermes_cli/anon_challenge.py+++ b/hermes_cli/anon_challenge.py@@ -118,12 +118,15 @@ def server_message(value: Any) -> str:def client_surface() -> str:"""``gateway`` in the process that holds the messaging gateway's runtime lock (nobody is at its- console), ``desktop`` for the backend the desktop app spawned, else ``cli``. ``HERMES_DESKTOP``+ console) unless it is serving the local Desktop app, ``desktop`` for that and for the backend the+ desktop app spawned, else ``cli``. ``HERMES_DESKTOP``alone is inherited by every terminal-pane shell, so desktop ownership needs the spawn credential."""+ from hermes_cli.process_identity import is_desktop_owned_backend, serves_local_desktop_now+ if serves_local_desktop_now(): # the gateway, working for the Desktop app on this machine+ return "desktop"status = sys.modules.get("gateway.status")if status is not None and status.owns_gateway_runtime_lock():return "gateway"- from hermes_cli.process_identity import is_desktop_owned_backendreturn "desktop" if is_desktop_owned_backend() else "cli"diff --git a/hermes_cli/process_identity.py b/hermes_cli/process_identity.pyindex 009e556cfb2..46b95d94de6 100644--- a/hermes_cli/process_identity.py+++ b/hermes_cli/process_identity.py@@ -17,9 +17,11 @@ import platformimport sysimport threadingimport time+from contextlib import contextmanager+from contextvars import ContextVarfrom dataclasses import asdict, dataclassfrom pathlib import Path-from typing import Optional, Sequence+from typing import Iterator, Optional, Sequencefrom utils import atomic_json_write@@ -282,9 +284,41 @@ def is_desktop_owned_backend(argv: Optional[Sequence[str]] = None) -> bool:return is_desktop_ssh_backend_argv(list(sys.argv[1:] if argv is None else argv))+# Set while this process works for the Desktop app on its own machine: one request from, or one turn of+# a chat created by, a client ``local_desktop_client`` accepted. The gateway serves the Desktop, the CLI,+# the TUI and bots from one process, so this is a property of the activity, never of the process.+_SERVING_LOCAL_DESKTOP: ContextVar[bool] = ContextVar("hermes_serving_local_desktop", default=False)+++@contextmanager+def serving_local_desktop(active: bool) -> Iterator[None]:+ """Mark the enclosed activity (and threads it hands its context to) as work for the local Desktop."""+ token = _SERVING_LOCAL_DESKTOP.set(bool(active) or _SERVING_LOCAL_DESKTOP.get())+ try:+ yield+ finally:+ _SERVING_LOCAL_DESKTOP.reset(token)+++def serves_local_desktop_now() -> bool:+ return _SERVING_LOCAL_DESKTOP.get()+++def local_desktop_client(identity: Optional[dict], declared: object) -> bool:+ """A connected client is the Desktop app on this machine when it says so (it knows its connection+ mode) AND it redeemed a native ticket, which only this machine's private control socket mints, for+ this OS user. Neither alone: the CLI and TUI hold native tickets too, and the claim is the client's+ word. A remote Desktop reaches a backend through SSH, URL or Cloud credentials, never a native ticket."""+ return (declared is True and isinstance(identity, dict) and identity.get("provider") == "local"+ and identity.get("native_bootstrap") is True)++def is_local_desktop_backend() -> bool:- """The backend Desktop spawned on this machine: the local pool spawn's credential, never the- SSH spawn (its token arrives as a file on argv, and that host is another computer)."""+ """Working for the Desktop on this machine: inside a ``serving_local_desktop`` activity (the unified+ gateway), or the backend the local Desktop spawned (the pool spawn's credential, never the SSH spawn:+ its token arrives as a file on argv, and that host is another computer)."""+ if _SERVING_LOCAL_DESKTOP.get():+ return Truereturn os.environ.get("HERMES_DESKTOP") == "1" and os.environ.get("HERMES_DASHBOARD_SESSION_TOKEN", "") != ""diff --git a/tests/gateway/test_local_desktop_identity.py b/tests/gateway/test_local_desktop_identity.pynew file mode 100644index 00000000000..7e52686d576--- /dev/null+++ b/tests/gateway/test_local_desktop_identity.py@@ -0,0 +1,195 @@+"""Who counts as the Desktop app on this machine, on the unified gateway.++The welcome trial and first-run onboarding are offered only to the local Desktop. Before the gateway+the Desktop spawned its own ``hermes serve`` and that process carried the proof in its env+(``HERMES_DESKTOP`` + the spawn token). The gateway serves the Desktop, the CLI, the TUI and bots from+one process and has neither variable, so ``onboarding.state`` answered ``eligible: false`` for every+fresh install: the app showed the provider picker and never started onboarding or the trial.++The proof is now per connection: the Desktop says it is local (``client.capabilities+{desktop_local}``), and that counts only on a connection that redeemed a native ticket.+"""+from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace++import pytest++from tests.waiting import async_wait_until+++class _Transport:+ def __init__(self, identity):+ self.frames = []+ self.auth_identity = identity+ self.desktop_local = False++ def write(self, frame):+ self.frames.append(frame)+ return True++ def close(self):+ pass+++async def _connect(tmp_path, monkeypatch, *, native=True, config=None):+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_controls import AuthorityConnection+ from tui_gateway import server++ home = tmp_path / ".hermes"+ home.mkdir()+ if config:+ (home / "config.yaml").write_text(config, encoding="utf-8")+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(server, "_hermes_home", str(home))+ monkeypatch.setattr(server, "_db", None)+ monkeypatch.setattr("gateway.run._hermes_home", home) # frozen at import: the first test's home otherwise+ for name in ("HERMES_DESKTOP", "HERMES_DASHBOARD_SESSION_TOKEN"): # the gateway's own env has neither+ monkeypatch.delenv(name, raising=False)+ store = SessionStore(home / "sessions", GatewayConfig())+ runner = SimpleNamespace(_session_db=store._db, session_store=store, _draining=False, adapters={},+ _evict_cached_agent=lambda route: None, _cached_agent_for=lambda route: None,+ _peek_session_state=lambda key: None)+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)+ authority = await initialize_session_authority(runner, profile_id=str(home), instance_id="owner")+ identity: dict = {"user_id": "uid:1", "provider": "local", "profile_id": str(home), "instance_id": "owner"}+ if native:+ identity["native_bootstrap"] = True # redeemed a ticket from this machine's control socket+ transport = _Transport(identity)+ connection = AuthorityConnection(authority, transport, identity)+ from gateway.session_local_migration import bind_native_transport+ bind_native_transport(authority, connection.actor, identity)+ return SimpleNamespace(authority=authority, connection=connection, transport=transport, runner=runner, home=home)+++async def _request(conn, rid, method, params):+ from tui_gateway.ws import _dispatch_request+ reply = await _dispatch_request(conn.connection, {"jsonrpc": "2.0", "id": rid, "method": method,+ "params": params}, method, conn.transport)+ if reply is None:+ def written():+ return next((f for f in conn.transport.frames if isinstance(f, dict) and f.get("id") == rid), None)+ await async_wait_until(written, timeout=20)+ reply = written()+ return reply+++async def test_a_fresh_install_is_offered_onboarding_once_the_desktop_says_it_is_local(tmp_path, monkeypatch):+ # A brand-new user on their own computer: no provider, no Nous identity, --fresh-install.+ conn = await _connect(tmp_path, monkeypatch)+ try:+ before = await _request(conn, 1, "onboarding.state", {"assume_fresh": True})+ assert before["result"]["eligible"] is False # nothing has said this is the local Desktop yet++ # As the Desktop sends it: on its own after server_requests, so a backend older than the field+ # refuses only this call. The earlier answer stands.+ from tui_gateway import server_requests+ await _request(conn, 2, "client.capabilities", {"server_requests": True})+ declared = await _request(conn, 3, "client.capabilities", {"desktop_local": True})+ assert "result" in declared, declared+ assert server_requests.answers_requests(conn.transport)++ after = await _request(conn, 4, "onboarding.state", {"assume_fresh": True})+ assert after["result"]["run"] is True and after["result"]["eligible"] is True, after+ finally:+ await conn.connection.close()+++async def test_the_declaration_counts_only_on_a_native_ticket(tmp_path, monkeypatch):+ # A client that reached the gateway any other way (a dashboard token, a remote credential) is not+ # the Desktop on this machine, whatever it says.+ conn = await _connect(tmp_path, monkeypatch, native=False)+ try:+ await _request(conn, 1, "client.capabilities", {"server_requests": True, "desktop_local": True})+ state = await _request(conn, 2, "onboarding.state", {"assume_fresh": True})+ assert state["result"]["eligible"] is False+ finally:+ await conn.connection.close()+++async def test_a_desktop_chat_runs_its_turns_as_work_for_the_local_desktop(tmp_path, monkeypatch):+ """The trial's free inference is resolved inside the turn, away from any request: the chat carries+ the fact from its creation, and only a Desktop chat created on a declared connection does."""+ 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", {"server_requests": True, "desktop_local": True})+ desktop = (await _request(conn, 2, "session.create", {"source": "gui", "request_id": "a"}))["result"]+ conn.transport.desktop_local = False # e.g. the same gateway's TUI connection+ tui = (await _request(conn, 3, "session.create", {"source": "tui", "request_id": "b"}))["result"]++ def inside_turn(stored):+ source = local_source(conn.authority, stored, conn.connection.actor.subject)+ with local_desktop_turn(conn.runner, source, nullcontext()):+ return on_local_desktop_backend()++ assert inside_turn(desktop["stored_session_id"]) is True+ assert inside_turn(tui["stored_session_id"]) is False+ assert on_local_desktop_backend() is False # nothing leaks out of the turn+ finally:+ await conn.connection.close()++++async def test_a_trial_users_desktop_chat_runs_on_the_free_model(tmp_path, monkeypatch):+ """A claimed welcome trial and no configured model: the chat freezes the free model instead of+ no model at all (a launch policy with no model can never be restored)."""+ from hermes_cli import anon_auth+ 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"})+ assert "result" in created, created+ from hermes_state_local import local_receipt+ receipt = local_receipt(conn.authority.db, created["result"]["stored_session_id"])+ assert receipt["policy"]["model"] == anon_auth.GUEST_MODEL++ conn.transport.desktop_local = False # the trial is the local Desktop's only+ refused = await _request(conn, 3, "session.create", {"source": "gui", "request_id": "b"})+ assert "error" in refused, refused+ finally:+ await conn.connection.close()+++async def test_a_fresh_launch_claims_the_trial_and_opens_onboarding_on_it(tmp_path, monkeypatch):+ """The whole first launch: the claim mints the guest, and the chat it opens runs on the free model."""+ from hermes_cli import anon_auth, welcome_trial+ state = {}+ guest = {"auth_method": anon_auth.ANON_AUTH_METHOD, anon_auth.WELCOME_CLAIM_FLAG: True}++ def claim(**kwargs): # the portal mint: the guest exists from here on+ if welcome_trial.claim_blocker(assume_fresh=kwargs.get("assume_fresh", False)):+ return None+ state.update(guest)+ return dict(guest)++ monkeypatch.setattr(anon_auth, "current_nous_state", lambda *a, **k: dict(state) if state else None)+ monkeypatch.setattr(welcome_trial, "claim_desktop_free_tier", claim)+ monkeypatch.setattr(welcome_trial, "_has_nous_identity", lambda: bool(state))+ conn = await _connect(tmp_path, monkeypatch)+ try:+ await _request(conn, 1, "client.capabilities", {"desktop_local": True})+ started = await _request(conn, 2, "onboarding.start",+ {"fresh_launch": True, "assume_fresh": True, "facts_source": "local", "locale": "en"})+ assert "result" in started, started+ resumed = await _request(conn, 3, "session.resume", {"session_id": started["result"]["stored_session_id"]})+ assert "error" not in resumed, resumed+ finally:+ await conn.connection.close()diff --git a/tui_gateway/contracts/liveness.py b/tui_gateway/contracts/liveness.pyindex a0fe309f4a5..9367d76e630 100644--- a/tui_gateway/contracts/liveness.py+++ b/tui_gateway/contracts/liveness.py@@ -31,6 +31,11 @@ class ClientCapabilitiesParams(Params):#: error for methods it has no handler for. A WebSocket client that never says so is treated as a#: build older than server→client requests and every such request fails fast for it.server_requests: bool = False+ #: The client is the Desktop app connected to a backend on its own machine (its connection mode is+ #: local). Counted only on a connection that redeemed a native ticket minted over this machine's+ #: private control socket; it is what makes the welcome trial and first-run onboarding available+ #: in a gateway that also serves the CLI, the TUI and bots.+ desktop_local: bool = Falseclass ClientCapabilitiesResult(Result):diff --git a/tui_gateway/methods_voice.py b/tui_gateway/methods_voice.pyindex 9f306488d0d..ff5646e7ec9 100644--- a/tui_gateway/methods_voice.py+++ b/tui_gateway/methods_voice.py@@ -523,9 +523,16 @@ def _(rid, params: dict) -> dict:"""What the calling client handles. ``server_requests: true`` marks this connection as one that answersserver→client requests; a WebSocket client that never sends it gets every such request failed fastinstead of stalling the agent for the deadline (#112548)."""+ from hermes_cli.process_identity import local_desktop_clientfrom tui_gateway import server_requestsfrom tui_gateway.contracts import registry as contracts- server_requests.advertise(_caller_transport(), bool(params.get("server_requests")))+ transport = _caller_transport()+ # Each call updates what it names: the Desktop sends ``desktop_local`` on its own, so a backend older+ # than the field refuses only that call and keeps the ``server_requests`` it already accepted.+ if "server_requests" in params:+ server_requests.advertise(transport, bool(params.get("server_requests")))+ if "desktop_local" in params and hasattr(transport, "auth_identity"): # a WebSocket client+ transport.desktop_local = local_desktop_client(transport.auth_identity, params.get("desktop_local"))return _ok(rid, {"server_requests": sorted(contracts.SERVER_REQUESTS), "declines_not_shown": True})diff --git a/tui_gateway/ws.py b/tui_gateway/ws.pyindex a8f4275b0b5..03afca0ace6 100644--- a/tui_gateway/ws.py+++ b/tui_gateway/ws.py@@ -134,6 +134,8 @@ class WSTransport:#: for legacy-token/stdio. RPC params can never populate it: sole identity authority for browser controllers#: and for the ``user_id`` the agent is built with (``server._session_auth_user_id``).self.auth_identity = auth_identity+ # Accepted ``client.capabilities {desktop_local}`` (process_identity.local_desktop_client).+ self.desktop_local = False#: The served profile home whose skin this peer follows (None = the launch home); see change_watcher.self.skin_home: str | None = Noneself._closed = False@@ -356,19 +358,23 @@ def _authority_connection(ws: Any, transport: WSTransport, auth_identity: dict |async def _dispatch_request(authority_connection: Any, req: Any, req_method: Any, transport: WSTransport) -> Any:- """One request through the authority when attached, else the legacy dispatcher."""- if authority_connection is None:- return await asyncio.to_thread(server.dispatch, req, transport)- resp = await authority_connection.dispatch(req)- actor = authority_connection.actor- if (_is_unknown_method(resp) and req_method in server._methods- and legacy_fallback_allowed(actor, req_method)):- # Session verbs live on the authority; everything else the sidecar still- # registers (pet, wake word, connectors) keeps its legacy handler. A legacy- # session writer keeps the authority's -32601 (ws_legacy_fallback), as does a- # method neither side knows, which is what the client's version-skew notice keys on.- resp = await asyncio.to_thread(dispatch_legacy, server, req, transport, actor)- return resp+ """One request through the authority when attached, else the legacy dispatcher. A request from the+ local Desktop runs as work for it (the welcome trial and onboarding key on that), and so do the+ threads it hands off to: ``to_thread`` and the legacy pool copy this context."""+ from hermes_cli.process_identity import serving_local_desktop+ with serving_local_desktop(getattr(transport, "desktop_local", False)):+ if authority_connection is None:+ return await asyncio.to_thread(server.dispatch, req, transport)+ resp = await authority_connection.dispatch(req)+ actor = authority_connection.actor+ if (_is_unknown_method(resp) and req_method in server._methods+ and legacy_fallback_allowed(actor, req_method)):+ # Session verbs live on the authority; everything else the sidecar still+ # registers (pet, wake word, connectors) keeps its legacy handler. A legacy+ # session writer keeps the authority's -32601 (ws_legacy_fallback), as does a+ # method neither side knows, which is what the client's version-skew notice keys on.+ resp = await asyncio.to_thread(dispatch_legacy, server, req, transport, actor)+ return respdef _start_backend_liveness() -> None: