Skip to content

The agent that grows with you

fix(desktop): sibling-profile sessions keep their route for edits, compress and approvals

Teknium568d935dbc6c
diff --git a/apps/desktop/src/api/canonical-attach-snapshot.test.ts b/apps/desktop/src/api/canonical-attach-snapshot.test.ts
index a4644b6dd90..bdfb55234e4 100644
--- a/apps/desktop/src/api/canonical-attach-snapshot.test.ts
+++ b/apps/desktop/src/api/canonical-attach-snapshot.test.ts
@@ -16,10 +16,12 @@ test('a cold attach delivers the snapshot prompt and marks the session attached'
socket.on('message', (bytes: Buffer) => {
const frame = JSON.parse(bytes.toString())
sent.push(frame)
+
const result = frame.method === 'session.resume'
? { session_id: 's', stored_session_id: 's', revision: 2, execution_generation: 5, running: true, messages: [],
prompts: [{ kind: 'clarify', prompt_id: 'c1', execution_generation: 5, question: 'Which target?', choices: [] }] }
: { status: 'resolved' }
+
socket.send(JSON.stringify({ jsonrpc: '2.0', id: frame.id, result }))
})
})
diff --git a/apps/desktop/src/api/canonical-profile-route.test.ts b/apps/desktop/src/api/canonical-profile-route.test.ts
new file mode 100644
index 00000000000..7ddb71227fd
--- /dev/null
+++ b/apps/desktop/src/api/canonical-profile-route.test.ts
@@ -0,0 +1,56 @@
+// @vitest-environment node
+import { expect, test } from 'vitest'
+
+import { HermesGateway } from './client'
+
+// R5: the primary socket serves every multiplexed profile and the authority selects one PER
+// REQUEST from `profile`. A sibling session's rebuilt requests (CAS mutations, prompt replies,
+// the compress follow-up resume) must keep the route, or they reach the launch profile.
+test('a sibling profile route survives canonical request translation', async () => {
+ const wsPackage = 'ws'
+ const { WebSocketServer } = await import(wsPackage)
+ const server = new WebSocketServer({ host: '127.0.0.1', port: 0 })
+ await new Promise<void>(resolve => server.once('listening', resolve))
+ const sent: any[] = []
+ server.on('connection', (socket: any) => {
+ socket.on('message', (bytes: Buffer) => {
+ const frame = JSON.parse(bytes.toString())
+ sent.push(frame)
+
+ const snapshot = { session_id: 's', stored_session_id: 's', revision: 2, execution_generation: 5, messages: [],
+ prompts: [{ kind: 'approval', prompt_id: 'p1', execution_generation: 5, command: 'rm -rf build', choices: ['once', 'deny'] }] }
+
+ const result = frame.method === 'session.resume' ? snapshot
+ : frame.method === 'session.mutate' ? { session_id: 's', revision: 3, operation: frame.params.operation, title: 'Renamed', message_count: 1 }
+ : { status: 'resolved' }
+
+ socket.send(JSON.stringify({ jsonrpc: '2.0', id: frame.id, result }))
+ })
+ })
+ const client = new HermesGateway()
+ const delivered: any[] = []
+ client.onRequest(request => { delivered.push(request) })
+
+ try {
+ const address = server.address() as { port: number }
+ await client.connect(`ws://127.0.0.1:${address.port}/api/ws?native_dial=fixture&ticket=one-use`)
+ await client.request('session.resume', { session_id: 's', profile: 'sibling' })
+ await client.request('session.title', { session_id: 's', title: 'Renamed', profile: 'sibling' })
+ await client.request('session.compress', { session_id: 's', profile: 'sibling' })
+ delivered[0]?.respond({ choice: 'once' })
+ await new Promise(resolve => setTimeout(resolve, 50))
+
+ expect(sent.map(frame => [frame.method, frame.params.profile])).toEqual([
+ ['session.resume', 'sibling'],
+ ['session.mutate', 'sibling'],
+ ['session.mutate', 'sibling'],
+ ['session.resume', 'sibling'],
+ ['approval.respond', 'sibling']
+ ])
+ } finally {
+ client.close()
+
+ for (const socket of server.clients) { socket.terminate() }
+ await new Promise<void>(resolve => server.close(() => resolve()))
+ }
+})
diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.ts
index cc81b2a52e4..796c78ed4f2 100644
--- a/apps/desktop/src/api/canonical-protocol.ts
+++ b/apps/desktop/src/api/canonical-protocol.ts
@@ -42,6 +42,11 @@ function mutationSummary(operation: string, value: Record<string, unknown>): str
// stored parent id; the authority has ONE branch, a `branch` mutation on the parent, whose child
// is a local route the authority can restore (a legacy-minted child has no local policy and every
// resume on it answers not_found).
+// The socket is bound to a profile already; only a sibling the host multiplexes rides as `profile`.
+export function siblingRoute(profile: unknown): string | null {
+ return typeof profile === 'string' && profile && profile !== 'default' ? profile : null
+}
+
const BRANCH_METHODS = new Set(['session.branch', 'session.branch_stored', 'session.branch_whole'])
const MUTATION_METHODS = new Set(['session.title', 'session.archive', 'session.compress', ...BRANCH_METHODS])
@@ -167,9 +172,8 @@ export class CanonicalDesktopProtocol {
if (unsupported.length) { throw new Error(`Canonical gateway does not support explicit session options: ${unsupported.join(', ')}`) }
- // The socket is bound to a profile already; only a sibling the host multiplexes rides as `profile`.
const result = Object.fromEntries(Object.entries(params).filter(([key, value]) =>
- ['request_id', 'cwd', 'model', 'toolsets', 'title', 'hidden'].includes(key) || (key === 'profile' && value && value !== 'default')))
+ ['request_id', 'cwd', 'model', 'toolsets', 'title', 'hidden'].includes(key) || (key === 'profile' && siblingRoute(value))))
const key = JSON.stringify(result)
const requestId = params.request_id ?? this.creates.get(key) ?? crypto.randomUUID()
diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.ts
index 72fc701e79c..d402ea0bc7f 100644
--- a/apps/desktop/src/api/client.ts
+++ b/apps/desktop/src/api/client.ts
@@ -9,7 +9,7 @@ import { map, type MapStore } from 'nanostores'
import type { HermesApiRequest } from '@/global'
-import { CANONICAL_GATEWAY_PROTOCOL, CanonicalDesktopProtocol } from './canonical-protocol'
+import { CANONICAL_GATEWAY_PROTOCOL, CanonicalDesktopProtocol, siblingRoute } 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
@@ -159,20 +159,21 @@ export class HermesGateway extends JsonRpcGatewayClient {
return this.request<T>('clarify.respond', { session_id: promptSession, request_id: params.request_id, answer }, timeoutMs, signal)
}
- await this.attachForRequest(method, params)
+ const route = this.sessionRoute(params)
+ await this.attachForRequest(method, { ...params, ...route })
const prepared = this.protocol.prepare(method, params)
const wireMethod = this.protocol.wire(method, prepared)
try {
- const result = await super.request<T>(wireMethod, prepared, timeoutMs, signal)
+ const result = await super.request<T>(wireMethod, { ...prepared, ...route }, timeoutMs, signal)
// A settle follow-up (compress -> resume) inherits the caller's deadline and cancellation.
const followUp = (m: string, p: Record<string, unknown>) => this.request(m, p, timeoutMs, signal)
const settled = await this.protocol.settle(method, prepared, this.protocol.result(method, prepared, result), followUp) as T
if (method === 'session.resume' || method === 'session.create' || method === 'session.activate') {
- this.adoptAttachedSnapshot(settled as { session_id?: string; prompts?: Array<Record<string, unknown>> })
+ this.adoptAttachedSnapshot(settled as { session_id?: string; prompts?: Array<Record<string, unknown>> }, route.profile)
}
return settled
@@ -182,6 +183,28 @@ export class HermesGateway extends JsonRpcGatewayClient {
}
}
+ // Sibling-profile routes by session. The primary socket serves every profile the host
+ // multiplexes and the authority selects one PER REQUEST from `profile`, so the route rides
+ // beside payload translation: rebuilt mutations, prompt replies and settle follow-ups (which
+ // name only the session) keep the route the session was last addressed with.
+ private readonly routes = new Map<string, string>()
+
+ private sessionRoute(params: Record<string, unknown>): { profile?: string } {
+ const sid = String(params.session_id ?? params.parent_session_id ?? '')
+
+ if (typeof params.profile === 'string') {
+ const route = siblingRoute(params.profile)
+
+ if (sid) { if (route) { this.routes.set(sid, route) } else { this.routes.delete(sid) } }
+
+ return route ? { profile: route } : {}
+ }
+
+ const remembered = this.routes.get(sid)
+
+ return remembered ? { profile: remembered } : {}
+ }
+
// Resume the session (and, for branch-like methods, its parent) on THIS socket before a
// method that needs an authority subscription here.
private async attachForRequest(method: string, params: Record<string, unknown>): Promise<void> {
@@ -198,12 +221,15 @@ export class HermesGateway extends JsonRpcGatewayClient {
}
}
- private adoptAttachedSnapshot(settled: { session_id?: string; prompts?: Array<Record<string, unknown>> }): void {
+ private adoptAttachedSnapshot(settled: { session_id?: string; prompts?: Array<Record<string, unknown>> }, route?: string): void {
// Prompts still open on the authority re-deliver like `open_requests` after a reconnect.
const sid = settled.session_id
if (sid) { this.attached.add(sid) }
+ // A sibling create learns its session id only here.
+ if (sid && route) { this.routes.set(sid, route) }
+
for (const prompt of (settled.prompts ?? [])) {
this.deliverCanonicalPrompt({ type: `${prompt.kind}.request`, session_id: sid, payload: prompt }, true)
}