Skip to content

The agent that grows with you

fix(desktop): recognize canonical gateway protocol metadata

David Dudok de Wit3f352e0c2b74
diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.ts
index 719a6d06b86..8f9da66cbda 100644
--- a/apps/desktop/src/api/canonical-protocol.ts
+++ b/apps/desktop/src/api/canonical-protocol.ts
@@ -1,6 +1,8 @@
// Canonical local authority wire adapter. Remote legacy transports keep their
// existing protocol; unsupported explicit semantics fail before network admission.
+export const CANONICAL_GATEWAY_PROTOCOL = 'hermes-gateway-v1'
+
// Mirrors hermes_cli/gateway_mutations.slash_mutation: the typed directives
// that are canonical mutations, not gateway-executed slash commands. Model
// flags (--global/--once/--refresh) have no canonical mutation and stay on the
diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.ts
index 04fb7e21f97..9a4993d5d7e 100644
--- a/apps/desktop/src/api/client.ts
+++ b/apps/desktop/src/api/client.ts
@@ -2,7 +2,7 @@ import { type GatewayEvent, type GatewayEventName, JsonRpcGatewayClient } from '
import type { HermesApiRequest } from '@/global'
-import { CanonicalDesktopProtocol } from './canonical-protocol'
+import { CANONICAL_GATEWAY_PROTOCOL, CanonicalDesktopProtocol } from './canonical-protocol'
// Desktop startup fires a burst of read-only data calls (config, profiles,
// model info/options, cron) the moment the backend passes readiness. On a
@@ -77,7 +77,7 @@ export class HermesGateway extends JsonRpcGatewayClient {
if (!ticket) {throw new Error('Native gateway requires a fresh private ticket')}
parsed.searchParams.delete('ticket')
- return new WebSocket(parsed.toString(), ['hermes-gateway-v1', `hermes-gateway-ticket.${ticket}`])
+ return new WebSocket(parsed.toString(), [CANONICAL_GATEWAY_PROTOCOL, `hermes-gateway-ticket.${ticket}`])
}
})
this.onEvent(event => { if (this.canonical) { this.protocol.event(event) } })
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
index 721aba729d9..1f2d244bf6f 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
@@ -1678,7 +1678,7 @@ export function applyRuntimeInfo(
// App/profile-level reporting is session-independent — a tile's runtime
// reports backend skew and credential warnings just as usefully.
- reportBackendContract(info.desktop_contract)
+ reportBackendContract(info.desktop_contract, info.desktop_protocol)
if (info.approval_mode !== undefined) {
reconcileApprovalModeForProfile($activeGatewayProfile.get(), info.approval_mode)
diff --git a/apps/desktop/src/store/updates.test.ts b/apps/desktop/src/store/updates.test.ts
index 1fbd284d93e..0b47b6b9059 100644
--- a/apps/desktop/src/store/updates.test.ts
+++ b/apps/desktop/src/store/updates.test.ts
@@ -103,6 +103,7 @@ const {
BACKGROUND_UPDATE_CHECK_MS
} = await import('./updates')
+const { CANONICAL_GATEWAY_PROTOCOL } = await import('@/api/canonical-protocol')
const { setConnection } = await import('./session')
const registryOf = (ids: string[]) => ({
@@ -199,6 +200,18 @@ describe('reportBackendContract', () => {
expect(notifySpy).not.toHaveBeenCalled()
})
+ it('accepts only the matching canonical gateway protocol without claiming the legacy contract', () => {
+ reportBackendContract(undefined, CANONICAL_GATEWAY_PROTOCOL)
+ expect(dismissSpy).toHaveBeenCalledWith('backend-contract-skew')
+ expect(notifySpy).not.toHaveBeenCalled()
+
+ reportBackendContract(undefined, 'hermes-gateway-v0')
+ expect(notifySpy).toHaveBeenCalledTimes(1)
+
+ reportBackendContract(Number.MAX_SAFE_INTEGER, 'hermes-gateway-v0')
+ expect(notifySpy).toHaveBeenCalledTimes(2)
+ })
+
it('warns when the backend is behind (or reports no contract)', () => {
reportBackendContract(undefined)
expect(notifySpy).toHaveBeenCalledTimes(1)
diff --git a/apps/desktop/src/store/updates.ts b/apps/desktop/src/store/updates.ts
index 44ec5241576..ddd5e8e3edc 100644
--- a/apps/desktop/src/store/updates.ts
+++ b/apps/desktop/src/store/updates.ts
@@ -5,6 +5,7 @@
import { atom } from 'nanostores'
+import { CANONICAL_GATEWAY_PROTOCOL } from '@/api/canonical-protocol'
import type {
DesktopUpdateApplyOptions,
DesktopUpdateApplyResult,
@@ -94,8 +95,10 @@ function isUpdateToastSnoozed(): boolean {
}
// Must match tui_gateway's DESKTOP_BACKEND_CONTRACT that this build was written
-// against. The backend reports its own value in session runtime info; a lower
-// value (or none — a pre-GUI checkout) means GUI<->backend skew.
+// against. Legacy backends report their own value in session runtime info; a
+// lower value (or none — a pre-GUI checkout) means GUI<->backend skew.
+// Canonical gateways identify their distinct wire protocol instead. That value
+// does not claim the legacy API features listed below.
// v2: requires the file.attach RPC (remote-gateway non-image file upload).
// v3: requires approvals.mode config RPCs and session.info reconciliation.
// v4: requires explicit Fast-off session creation and session-scoped Fast edits.
@@ -149,8 +152,13 @@ function isInstallMethodToastSnoozed(): boolean {
* Runs on every session open; closing the toast snoozes it for a cooldown so it
* doesn't nag on every thread switch.
*/
-export function reportBackendContract(contract: number | undefined): void {
- if ((contract ?? 0) >= REQUIRED_BACKEND_CONTRACT) {
+export function reportBackendContract(contract: number | undefined, protocol?: string): void {
+ // An unknown explicit protocol must not fall back to a legacy version claim.
+ const compatible = protocol === undefined
+ ? (contract ?? 0) >= REQUIRED_BACKEND_CONTRACT
+ : protocol === CANONICAL_GATEWAY_PROTOCOL
+
+ if (compatible) {
dismissNotification(SKEW_TOAST_ID)
// Backend caught up — forget any prior snooze so a future regression warns
// immediately rather than staying silent for the rest of the window.
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index 6ac291f9b37..a190df0aed2 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -798,6 +798,7 @@ export interface SessionRuntimeInfo {
credential_warning?: string
cwd?: string
desktop_contract?: number
+ desktop_protocol?: string
fast?: boolean
install_warning?: string
model?: string
diff --git a/gateway/run_api.py b/gateway/run_api.py
index 6abbbf736da..f8c1626e21d 100644
--- a/gateway/run_api.py
+++ b/gateway/run_api.py
@@ -156,6 +156,7 @@ class GatewayRuntimeAPI:
return
# The ticket names the served profile; this connection binds to that home's authority.
scope['hermes.session_authority'] = authority
+ from gateway.session_contract import CANONICAL_GATEWAY_PROTOCOL
from tui_gateway.ws import handle_ws
from gateway.session_authorities import owner_scope
with owner_scope(authority):
@@ -163,4 +164,4 @@ class GatewayRuntimeAPI:
'profile_id': grant['profile_id'],
'instance_id': grant['instance_id'],
'capabilities': grant['capabilities'], 'native_bootstrap': True},
- subprotocol='hermes-gateway-v1')
+ subprotocol=CANONICAL_GATEWAY_PROTOCOL)
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 1524c30fec8..55e464b63a6 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -10,7 +10,7 @@ from dataclasses import asdict, dataclass, field
import uuid
from gateway.session_contract import (
- AdmissionReceipt, PendingAdmission, Principal, SessionHandle, SessionRef, Submission,
+ CANONICAL_GATEWAY_PROTOCOL, AdmissionReceipt, PendingAdmission, Principal, SessionHandle, SessionRef, Submission,
SubscriptionSnapshot,
)
from gateway.session_events import SessionEvents
@@ -159,6 +159,7 @@ class SessionAuthority:
# prepared mutation must present.
live.event_stream.publish(ref.session_id, {
'stored_session_id': ref.session_id, 'pending': pending,
+ 'desktop_protocol': CANONICAL_GATEWAY_PROTOCOL,
'running': handle.execution_state == 'running',
'execution_generation': handle.execution_generation,
'revision': handle.revision,
diff --git a/gateway/session_contract.py b/gateway/session_contract.py
index 9a2dce031c7..54554b3f3e6 100644
--- a/gateway/session_contract.py
+++ b/gateway/session_contract.py
@@ -5,6 +5,9 @@ from typing import Literal, Mapping, Protocol
JsonObject = Mapping[str, object]
+# Authenticated local WebSocket family, separate from the legacy Desktop API contract.
+CANONICAL_GATEWAY_PROTOCOL = 'hermes-gateway-v1'
+
@dataclass(frozen=True)
class Principal:
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index a723470f738..1e7e9e77737 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -3,7 +3,8 @@ from dataclasses import asdict
import sqlite3
import uuid
-from gateway.session_contract import Principal, SessionRef, Submission
+from gateway.config import Platform
+from gateway.session_contract import CANONICAL_GATEWAY_PROTOCOL, Principal, SessionRef, Submission
from hermes_state_runtime import RuntimeStoreError
@@ -161,7 +162,7 @@ class AuthorityConnection:
return await readiness(self.authority, self.actor, params, runtime=True)
async def create(self, ref, params):
- from gateway.session_local import create_local_session, local_session_info
+ from gateway.session_local import create_local_session
from gateway.session_local_title import resolve_titled_session, title_new_session, validate_title
# ``-c <title> --create-if-missing``: resolve-or-create is one owner step (no await
# between lookup and creation), so concurrent programmatic callers converge.
@@ -171,9 +172,7 @@ class AuthorityConnection:
ref = create_local_session(self.authority, self.actor, params)
if title:
title_new_session(self.authority, ref, title)
- result = await self.resume(ref, {})
- result['info'] = local_session_info(self.authority, ref)
- return result
+ return await self.resume(ref, {})
async def ping(self, ref, params):
if not self.actor.capabilities:
@@ -222,6 +221,7 @@ class AuthorityConnection:
return {'sessions': sessions[:limit], 'scope': 'live'}
async def resume(self, ref, params):
+ from gateway.session_local import local_session_info
if 'title' in params:
from gateway.session_local_title import resolve_titled_session
ref = resolve_titled_session(self.authority, self.actor, params['title'])
@@ -237,6 +237,11 @@ class AuthorityConnection:
resume_editor_mcp(self.authority, ref, params['editor'])
snapshot = await self.authority.attach(self.actor, ref)
self.subscriptions[ref.session_id] = snapshot.subscription_id
+ # Only local routes have a frozen local launch policy to project.
+ info = {'desktop_protocol': CANONICAL_GATEWAY_PROTOCOL}
+ source = self.authority.sessions[snapshot.handle.ref.session_id].source
+ if source is not None and source.platform == Platform.LOCAL:
+ info = local_session_info(self.authority, snapshot.handle.ref)
return {'session_id': ref.session_id, 'stored_session_id': ref.session_id,
'messages': list(snapshot.history), 'message_count': len(snapshot.history),
'running': snapshot.handle.execution_state == 'running',
@@ -245,7 +250,7 @@ class AuthorityConnection:
'subscription_id': snapshot.subscription_id, 'revision': snapshot.handle.revision,
'execution_generation': snapshot.handle.execution_generation,
'pending': [asdict(r) for r in snapshot.pending],
- 'prompts': list(snapshot.prompts), 'info': {}}
+ 'prompts': list(snapshot.prompts), 'info': info}
async def events_since(self, ref, params):
self.authority.authorize(self.actor, ref, 'session:read')
diff --git a/gateway/session_local.py b/gateway/session_local.py
index eeed4a0b295..4f4a1a27702 100644
--- a/gateway/session_local.py
+++ b/gateway/session_local.py
@@ -9,6 +9,7 @@ import uuid
from gateway.config import Platform, PlatformConfig
from gateway.platforms.base import BasePlatformAdapter, SendResult
from gateway.session import SessionSource
+from gateway.session_contract import CANONICAL_GATEWAY_PROTOCOL
from hermes_state_runtime import RuntimeStoreError
@@ -165,4 +166,5 @@ def local_session_info(authority, ref):
policy = policy_for_source(authority.runner, live.source)
return {'source': policy.source if policy else live.source.platform.value,
'model': getattr(agent, 'model', policy.model if policy else None), 'lazy': agent is None,
- 'profile_id': authority.profile_id, **({'cwd': policy.cwd} if policy else {})}
+ 'profile_id': authority.profile_id, 'desktop_protocol': CANONICAL_GATEWAY_PROTOCOL,
+ **({'cwd': policy.cwd} if policy else {})}
diff --git a/tests/gateway/test_authority_connection.py b/tests/gateway/test_authority_connection.py
index 19bf84f7235..4b564c510aa 100644
--- a/tests/gateway/test_authority_connection.py
+++ b/tests/gateway/test_authority_connection.py
@@ -4,6 +4,7 @@ from types import SimpleNamespace
import pytest
from gateway.session_authority import LiveSession, SessionAuthority
+from gateway.session_contract import CANONICAL_GATEWAY_PROTOCOL
from gateway.session_controls import AuthorityConnection
from hermes_state import SessionDB
from hermes_state_runtime import begin_runtime_epoch
@@ -22,7 +23,8 @@ async def test_repeated_resume_and_close_preserve_only_live_memberships(tmp_path
peer = AuthorityConnection(authority, object(), {'user_id': 'human'})
request = {'id': 1, 'method': 'session.resume', 'params': {'session_id': 's'}}
for connection in (first, peer, first, first):
- assert 'result' in await connection.dispatch(request)
+ result = (await connection.dispatch(request))['result']
+ assert result['info'] == {'desktop_protocol': CANONICAL_GATEWAY_PROTOCOL}
members = authority.sessions['s'].subscribers
assert len(members) == 2
await first.close()
diff --git a/tests/gateway/test_canonical_desktop_metadata.py b/tests/gateway/test_canonical_desktop_metadata.py
new file mode 100644
index 00000000000..bebb585bbed
--- /dev/null
+++ b/tests/gateway/test_canonical_desktop_metadata.py
@@ -0,0 +1,60 @@
+"""Canonical GUI metadata follows the authenticated local-session route."""
+import asyncio
+import json
+
+import pytest
+
+from tests.gateway.fixtures.local_recovery_probe import rpc, websocket
+from tests.gateway.test_session_busy_controls import owner, settled
+
+
+def test_canonical_desktop_metadata_survives_create_info_and_reattach(tmp_path):
+ """The native protocol, not the legacy contract number, identifies this route."""
+ with owner(tmp_path) as (home, _peer, desc):
+ async def probe():
+ async with websocket(home, desc) as creator:
+ created = await rpc(creator, 'session.create', request_id='desktop-metadata',
+ source='gui', toolsets=[])
+ assert 'result' in created, created
+ sid = created['result']['session_id']
+ created_info = created['result']['info']
+ assert created_info['desktop_protocol'] == creator.subprotocol
+ assert 'desktop_contract' not in created_info
+ assert created_info['lazy'] is True
+
+ lazy_info = await rpc(creator, 'session.info', session_id=sid)
+ assert lazy_info['result']['desktop_protocol'] == creator.subprotocol
+ assert lazy_info['result']['lazy'] is True
+
+ # Read every frame: the RPC helper deliberately skips events,
+ # but Desktop reconciles their metadata throughout each turn.
+ await creator.send(json.dumps({'jsonrpc': '2.0', 'id': 'initialize',
+ 'method': 'prompt.submit', 'params': {'session_id': sid,
+ 'input_id': 'initialize', 'text': 'INITIALIZE'}}))
+ submitted = saw_pending = finished = False
+ async with asyncio.timeout(30):
+ while not submitted or not finished:
+ frame = json.loads(await creator.recv())
+ if frame.get('id') == 'initialize':
+ assert frame['result']['status'] == 'queued', frame
+ submitted = True
+ event = frame.get('params', {})
+ if event.get('type') == 'session.info' and event.get('session_id') == sid:
+ info = event['payload']
+ assert info['desktop_protocol'] == creator.subprotocol
+ assert 'desktop_contract' not in info
+ saw_pending |= bool(info['pending'])
+ finished = saw_pending and not info['pending'] and not info['running']
+ await settled(home)
+
+ initialized_info = await rpc(creator, 'session.info', session_id=sid)
+ assert initialized_info['result']['desktop_protocol'] == creator.subprotocol
+ assert initialized_info['result']['lazy'] is False
+
+ async with websocket(home, desc) as reattached:
+ resumed = await rpc(reattached, 'session.resume', session_id=sid)
+ assert resumed['result']['info']['desktop_protocol'] == reattached.subprotocol
+ assert resumed['result']['info']['lazy'] is False
+
+ asyncio.run(probe())