The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): identity-attribution traces for multi-connection bot rosters
teknium1c55a6e3d9fb2
diff --git a/apps/desktop/src/lib/identity-trace.ts b/apps/desktop/src/lib/identity-trace.tsnew file mode 100644index 00000000000..ac865894c29--- /dev/null+++ b/apps/desktop/src/lib/identity-trace.ts@@ -0,0 +1,31 @@+/**+ * Change-only desktop.log trace for multi-connection identity decisions: which+ * socket a (connection, profile) request rides, the rows each connection+ * returned to the bot relay, and per-route bot titles. Two registry sources can+ * both expose `default`, so a request answered by the wrong backend looks+ * healthy everywhere except in these values; desktop.log is what a+ * `hermes debug share` bundle carries off the user's machine.+ *+ * A line is written only when a key's value changes, so a steady state costs+ * nothing per relay tick. Renderer console lines below error level never+ * reach desktop.log, hence the explicit `logLine` IPC.+ */++const lastTraced = new Map<string, string>()++/** Which renderer wrote the line (`win=` is how Electron tags every non-main+ * window): each window runs its own stores and plugins. */+function windowTraceTag(): string {+ return new URLSearchParams(window.location.search).get('win') || 'main'+}++export function traceIdentityChange(channel: string, key: string, value: string): void {+ const id = `${channel}\u0000${key}`++ if (lastTraced.get(id) === value) {+ return+ }++ lastTraced.set(id, value)+ window.hermesDesktop?.logLine?.(`[${channel} win=${windowTraceTag()}] ${key} ${value}`)+}diff --git a/apps/desktop/src/plugins/hermes-bots/data.ts b/apps/desktop/src/plugins/hermes-bots/data.tsindex 83cb3de2a7f..18323ce7ca8 100644--- a/apps/desktop/src/plugins/hermes-bots/data.ts+++ b/apps/desktop/src/plugins/hermes-bots/data.ts@@ -191,6 +191,15 @@ interface BotMetaStorage {* { [botName]: { shape, color, title } } */export const $botMeta = atom<BotMetaSnapshot>({})+// One desktop.log line per route key whose title changes, from any writer+// (hydrate, server merge, save): a title that jumps between scoped keys names+// the moment, the window and the key it landed on.+$botMeta.listen(snapshot => {+ for (const [key, meta] of Object.entries(snapshot)) {+ host.traceIdentityChange?.('bot-meta', key, `title=${JSON.stringify(meta?.title ?? null)}`)+ }+})+export function commitBotMetaV2(storage: BotMetaStorage | undefined, snapshot: BotMetaSnapshot) {const commit = botMetaV2Commit.then(async () => {if (typeof storage?.remove !== 'function' || typeof storage?.set !== 'function') {@@ -644,6 +653,29 @@ interface UnionRoster {sources?: GatewaySource[]}+/** The rich rows come from the AMBIENT socket and are stamped with+ * `activeConnectionId`; when the install that answered is not that+ * connection's install, every title on the active source is another+ * machine's, so say so in desktop.log. */+function traceRosterSnapshot(+ local: RosterSnapshot | null | undefined,+ sources: GatewaySource[],+ activeConnectionId: null | string | undefined,+ rows: RosterRow[]+): void {+ const answered = String((local as { install_id?: string } | null | undefined)?.install_id || '')+ const active = activeConnectionId || 'local'+ const expected = String(sources.find(source => source.connectionId === active)?.installId || '')+ const flag = answered && expected && answered !== expected ? 'MISROUTED ' : ''+ const shown = rows.map(row => `${row.connectionId ?? '-'}/${row.name}=${JSON.stringify(row.display_name ?? '')}`)++ host.traceIdentityChange?.(+ 'bot-roster',+ 'snapshot',+ `${flag}active=${active} answered=${answered.slice(0, 8) || '-'} expected=${expected.slice(0, 8) || '-'} rows=[${shown.join(' ')}]`+ )+}+/** One roster snapshot for `activeConnectionId` — the pane's query and the* composer's cold-cache prime (`primeRoster`) share it, so both see the same* cross-connection rows. */@@ -696,6 +728,7 @@ async function fetchRosterSnapshot(activeConnectionId: null | string | undefinedconst previous: RosterRow[] = $lastRoster.get().filter(row => !row?.ghost)const merged = mergeMultiSourceRoster(local, union, activeConnectionId, previous)const sources = Array.isArray(union?.sources) ? union.sources : []+ traceRosterSnapshot(local, sources, activeConnectionId, merged?.profiles || [])return {...merged,diff --git a/apps/desktop/src/plugins/hermes-bots/relay.ts b/apps/desktop/src/plugins/hermes-bots/relay.tsindex 93226cebadc..5c9a0b902fe 100644--- a/apps/desktop/src/plugins/hermes-bots/relay.ts+++ b/apps/desktop/src/plugins/hermes-bots/relay.ts@@ -305,14 +305,14 @@ async function relayAgentsOn(labels: Map<string, string>): Promise<RelayAgentRow[] | null> {try {- const res = await host.requestProfile<{ profiles?: RosterRow[] }>(connection.route, 'profiles.list', {+ const res = await host.requestProfile<{ install_id?: string; profiles?: RosterRow[] }>(connection.route, 'profiles.list', {include_sessions: false})const profiles = Array.isArray(res?.profiles) ? res.profiles : []const label = labels.get(connection.id) || connection.id- return profiles+ const rows = profiles.map(profile => ({profile: String(profile?.name || ''),handle: botHandle(profile?.name, profile),@@ -322,11 +322,32 @@ async function relayAgentsOn(description: String(profile?.description || '')})).filter(row => row.profile)++ host.traceIdentityChange?.('bot-relay', `rows ${connection.id}`, rosterTrace(rows, String(res?.install_id || '')))++ return rows} catch {return null}}+/** Which connection last answered from each install: a second connection+ * answering from the same machine is a misrouted request (or one machine+ * registered twice) and is flagged in the trace. */+const answeringInstall = new Map<string, string>()++function rosterTrace(rows: RelayAgentRow[], installId: string): string {+ const connectionId = rows[0]?.connection_id ?? ''+ const other = installId ? answeringInstall.get(installId) : undefined+ const flag = other && other !== connectionId ? `MISROUTED (same install as ${other}) ` : ''++ if (installId && connectionId && !flag) {+ answeringInstall.set(installId, connectionId)+ }++ return `${flag}install=${installId.slice(0, 8) || '-'} n=${rows.length} [${rows.map(row => `${row.connection_id}/${row.profile}=${JSON.stringify(row.title)}`).join(' ')}]`+}+/** Last good agent rows per connection id — reused when a fetch blips so a* transient failure never reads as "everyone on that machine went away".* The sweep below drops disconnected ids, but only on a cycle that had twodiff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex 020568b4710..29900893e82 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -47,6 +47,7 @@ import { onGatewayEvent } from '@/contrib/events'import { registry } from '@/contrib/registry'import type { WorkspaceMode } from '@/contrib/types'import { deleteProfile, getLogs, getStatus, hermesApi, type HermesGateway } from '@/hermes'+import { traceIdentityChange } from '@/lib/identity-trace'import { completeMcpDesktopOAuth } from '@/lib/mcp-dashboard-oauth'import {$gateway,@@ -1635,6 +1636,10 @@ export const host = {* active instance changes on a profile swap. */getGateway: (): HermesGateway | null => $gateway.get(),+ /** Change-only desktop.log line for multi-connection identity diagnostics+ * (`[category win=…] tag detail`). Call as `host.traceIdentityChange?.(…)`. */+ traceIdentityChange,+composer: composerHost,/** Language packs: `host.i18n.registerAppLocale(id, { endonym, rtl?,diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.tsindex 0462e1d1bf1..c0ebec017ed 100644--- a/apps/desktop/src/store/connections.ts+++ b/apps/desktop/src/store/connections.ts@@ -2,6 +2,7 @@ import { atom, computed } from 'nanostores'import { getProfiles } from '@/api/profiles'import type { DesktopConnectionsRegistry } from '@/global'+import { traceIdentityChange } from '@/lib/identity-trace'import { invalidateProfileScopedQueries } from '@/lib/query-client'import { persistStringRecord, storedStringRecord } from '@/lib/storage'import {@@ -62,6 +63,10 @@ export { $connectionsRegistry } from '@/store/connection-registry-state'// route or while a legacy main is still resolving the descriptor.export const $activeConnectionId = computed($connection, connection => connection?.connectionId ?? null)+// The published connection is what plugins stamp rows with; trace it beside+// the active socket ([gateway-route] active) so a disagreement is visible.+$activeConnectionId.listen(id => traceIdentityChange('gateway-route', 'published', `connection=${id ?? '-'}`))+export const $hasMultipleConnections = computed($connectionsRegistry,registry => (registry?.connections.length ?? 0) > 1diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex c25f049b715..9fa64d10d6e 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -19,6 +19,7 @@ import {LIVENESS_REPROBE_DELAY_MS} from '@/lib/gateway-liveness-policy'import { isMissingRpcMethod } from '@/lib/gateway-rpc'+import { traceIdentityChange } from '@/lib/identity-trace'import {isTimeoutError,RECONNECT_ATTEMPT_TIMEOUT_MS,@@ -381,6 +382,10 @@ export function dispatchPrimaryServerRequest(request: ServerRequest, profile: streturn dispatchServerRequest(request, profile, g.config?.activeConnectionId?.() ?? null)}+/** The source the last primary connect/reconnect named, published or not:+ * diverges from `g.primaryConnectionId` only when the publish was refused. */+let primaryDialedConnectionId: null | string = null+export function setPrimaryGateway(gateway: HermesGateway | null, profile = 'default'): void {const next = normKey(profile)@@ -418,7 +423,15 @@ export function setPrimaryGatewayConnectionId(// ambient API/WebSocket helper (and new-session routing) silently lands on// the wrong backend. The primary's own identity is (re)published by its// boot/reconnect path, which runs with the primary route active.+ primaryDialedConnectionId = (connectionId ?? '').trim() || null+if (!isActivePrimary()) {+ traceIdentityChange(+ 'gateway-route',+ 'primary-publish',+ `refused ${primaryDialedConnectionId ?? '-'} keeping=${g.primaryConnectionId ?? '-'} active=${g.activeKey}`+ )+return}@@ -453,6 +466,14 @@ export function setPrimaryGatewayConnection(connection: Pick<HermesConnection, 'setPrimaryGatewayConnectionId(connection?.connectionId, connection?.mode)}+function traceAgentRoute(scope: string, via: string): void {+ traceIdentityChange(+ 'gateway-route',+ scope,+ `via=${via} primary=${g.primaryConnectionId ?? '-'}/${g.primaryProfile} dialed=${primaryDialedConnectionId ?? '-'}`+ )+}+function isPrimaryRegistryRoute(connectionId: null | string, profile: string): boolean {const id = String(connectionId ?? '').trim()@@ -692,6 +713,11 @@ function applyActive(profile: string, activationEpoch: number): boolean {g.$activeProfile.set(routeProfile)g.config?.onActiveRouteChanged?.(routeProfile)+ traceIdentityChange(+ 'gateway-route',+ 'active',+ `key=${g.activeKey} via=${g.activeKey === g.primaryProfile ? 'primary' : 'secondary'} conn=${activeGatewayConnectionId() ?? '-'} profile=${routeProfile}`+ )return true}@@ -1357,13 +1383,19 @@ export async function requestGatewayForAgent<T>(// Require both owner identities to agree before collapsing the route; a// different source or profile must retain its isolated secondary.if (isPrimaryRegistryRoute(connectionId, key)) {+ traceAgentRoute(scope, 'primary')+return requestGatewayForProfile<T>(key, method, params, timeoutMs, signal, { spawnPriority })}if (await ridesPrimaryBackend(connectionId, key, spawnPriority)) {+ traceAgentRoute(scope, 'primary-shared')+return requestOnPrimaryGateway<T>(method, { ...params, profile: key }, timeoutMs, signal)}+ traceAgentRoute(scope, 'secondary')+if (!window.hermesDesktop?.getConnectionFor) {throw new Error('This Desktop build cannot dial registry connections. Update Hermes Desktop.')}diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 4686fdba3dd..711e9a33c63 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -1891,10 +1891,11 @@ export interface ProfilesListParams {profile?: string | nullinclude_sessions?: boolean | string | null}-/** ``bot_mode_protocol`` tells clients this backend injects the teammate protocol itself. */+/** ``bot_mode_protocol`` tells clients this backend injects the teammate protocol itself; ``install_id`` (as on ``/api/status``) names the machine that answered. */export interface ProfilesListResult {profiles?: ProfileRow[]bot_mode_protocol?: boolean+ install_id?: string}/** One roster row; the session fields are present only with ``include_sessions``. */export interface ProfileRow {diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 6af3b006401..bc712ffe74c 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -24434,7 +24434,7 @@},"ProfilesListResult": {"additionalProperties": false,- "description": "``bot_mode_protocol`` tells clients this backend injects the teammate protocol itself.",+ "description": "``bot_mode_protocol`` tells clients this backend injects the teammate protocol itself;\n``install_id`` (as on ``/api/status``) names the machine that answered.","properties": {"profiles": {"items": {@@ -24447,6 +24447,11 @@"default": true,"title": "Bot Mode Protocol","type": "boolean"+ },+ "install_id": {+ "default": "",+ "title": "Install Id",+ "type": "string"}},"title": "ProfilesListResult",diff --git a/tui_gateway/contracts/profiles_vault_complete_foreign_subagents.py b/tui_gateway/contracts/profiles_vault_complete_foreign_subagents.pyindex 21d508b4d1f..13a0f4d0b67 100644--- a/tui_gateway/contracts/profiles_vault_complete_foreign_subagents.py+++ b/tui_gateway/contracts/profiles_vault_complete_foreign_subagents.py@@ -174,10 +174,12 @@ class ProfilesListParams(ProfileParams):class ProfilesListResult(Result):- """``bot_mode_protocol`` tells clients this backend injects the teammate protocol itself."""+ """``bot_mode_protocol`` tells clients this backend injects the teammate protocol itself;+ ``install_id`` (as on ``/api/status``) names the machine that answered."""profiles: list[ProfileRow] = Field(default_factory=list)bot_mode_protocol: bool = True+ install_id: str = ""method("profiles.list", params=ProfilesListParams, result=ProfilesListResult,diff --git a/tui_gateway/methods_bot_relay.py b/tui_gateway/methods_bot_relay.pyindex b679a87f045..4262b811fa6 100644--- a/tui_gateway/methods_bot_relay.py+++ b/tui_gateway/methods_bot_relay.py@@ -7,6 +7,7 @@ the SENDER gateway for its waiter). Plumbing: ``tools/bot_relay.py``; handlers aserver.py's globals (method_ctx.py) and reference ``_ok``/``_err`` bare."""import contextlib+import loggingimport osimport subprocessfrom pathlib import Path@@ -53,10 +54,24 @@ def _run_delivery(profile: str, tmp: str, env: dict | None = None, *,@method("bot_relay.roster.sync")def _(rid, params: dict, _root=_relay_root) -> dict:"""Replace this gateway's view of agents on OTHER connections → ``{count}`` accepted rows- (``agents`` rows ``{profile, handle, connection_id, ...}``; invalid rows are dropped)."""+ (``agents`` rows ``{profile, handle, connection_id, ...}``; invalid rows are dropped).+ A roster that changes is logged with its rows: a peer connection listed with this machine's+ own profiles, or two publishers alternating, shows up as a flapping line (the pushing window+ is in the Desktop's desktop.log ``[bot-relay win=…]`` lines at the same time)."""try:- from tools.bot_relay import write_remote_roster- return _ok(rid, {"count": write_remote_roster(_root(), params.get("agents"))})+ from tools.bot_relay import read_remote_roster, write_remote_roster++ def trace() -> str:+ rows = read_remote_roster(_root())+ return f"n={len(rows)} [" + " ".join(+ f"{r.get('connection_id')}/{r.get('profile')}={r.get('title')!r}" for r in rows) + "]"++ before = trace()+ count = write_remote_roster(_root(), params.get("agents"))+ after = trace()+ if after != before:+ logging.getLogger(__name__).info("bot_relay roster changed: %s -> %s", before, after)+ return _ok(rid, {"count": count})except Exception as e:return _err(rid, 5090, str(e))diff --git a/tui_gateway/methods_profiles.py b/tui_gateway/methods_profiles.pyindex 4436174f4d1..fcafd809266 100644--- a/tui_gateway/methods_profiles.py+++ b/tui_gateway/methods_profiles.py@@ -5,6 +5,7 @@ onto server.py, so they must not collide with its globals."""import contextlib+import loggingimport sqlite3from .method_ctx import HandlerRegistry, bind_module@@ -295,8 +296,10 @@ def _(rid, params: dict) -> dict:_profile_ui_meta_fields(row, Path(str(p.path)))out.append(row)# bot_mode_protocol: this backend injects the Bot Mode teammate-messaging protocol into every- # session, so clients must not append it to SOUL.md.- return _ok(rid, {"profiles": out, "bot_mode_protocol": True})+ # session, so clients must not append it to SOUL.md. install_id (same value as /api/status)+ # lets a multi-connection client prove WHICH machine answered a routed list.+ from hermes_cli.install_identity import get_install_id+ return _ok(rid, {"profiles": out, "bot_mode_protocol": True, "install_id": _try(lambda: get_install_id() or "", "")})@method("profiles.create")@@ -588,6 +591,11 @@ def _describe_toolsets(cfg):return toolsets_out, pinned_set+def _bots_title(ui_meta: dict):+ bots = ui_meta.get("hermes-bots")+ return bots.get("title") if isinstance(bots, dict) else None++def _configure_ui_meta(profile_dir, params, applied) -> None:"""Merge ``params["ui_meta"]`` key-wise into profile.yaml (None deletes). 64KB cap (ridesevery roster paint). ``ui_meta_expected_revisions``: per-key CAS, any mismatch rejects the@@ -615,6 +623,7 @@ def _configure_ui_meta(profile_dir, params, applied) -> None:returncurrent = existing.get("ui_meta")current = current if isinstance(current, dict) else {}+ old_title = _bots_title(current)for key, value in incoming.items():if value is None:current.pop(key, None)@@ -630,6 +639,13 @@ def _configure_ui_meta(profile_dir, params, applied) -> None:atomic_yaml_write(profile_dir / "profile.yaml", existing, sort_keys=False)applied["ui_meta"] = Trueapplied["ui_meta_revisions"] = {key: revisions[key] for key in incoming}+ if _bots_title(current) != old_title:+ # A client writing another machine's bot title lands here; the Desktop's+ # `[bot-meta win=…]` desktop.log line at the same time names the window.+ logging.getLogger(__name__).info(+ "ui_meta hermes-bots title for profile %s: %r -> %r (revision %s)",+ params.get("name") or profile_dir.name, old_title, _bots_title(current),+ revisions.get("hermes-bots"))except Exception:applied["ui_meta"] = False