Skip to content

The agent that grows with you

fix(desktop): preserve canonical owner and prompt lifecycle

David Dudok de Wit4eeb533f70d0
diff --git a/apps/desktop/src/api/adversarial-attach-deadline.test.ts b/apps/desktop/src/api/adversarial-attach-deadline.test.ts
new file mode 100644
index 00000000000..3d58aa47961
--- /dev/null
+++ b/apps/desktop/src/api/adversarial-attach-deadline.test.ts
@@ -0,0 +1,59 @@
+import { JsonRpcGatewayClient } from '@hermes/shared'
+import { afterEach, expect, test, vi } from 'vitest'
+
+import { HermesGateway } from './client'
+
+afterEach(() => { vi.restoreAllMocks() })
+
+test('the prerequisite attachment shares the caller deadline and cancellation', async () => {
+ let now = 1_000
+ vi.spyOn(Date, 'now').mockImplementation(() => now)
+ vi.spyOn(JsonRpcGatewayClient.prototype, 'connect').mockResolvedValue()
+ const calls: Array<{ method: string; timeout?: number; signal?: AbortSignal }> = []
+ vi.spyOn(JsonRpcGatewayClient.prototype, 'request').mockImplementation(async (method, _params, timeout, signal) => {
+ calls.push({ method, timeout, signal })
+
+ if (method === 'session.resume') {
+ now += 60
+
+ return { session_id: 's', revision: 1, execution_generation: 2, messages: [], info: {} } as never
+ }
+
+ return { ref: { session_id: 's' }, admission_id: 'a', status: 'queued' } as never
+ })
+ const client = new HermesGateway()
+ await client.connect('ws://localhost/api/ws?native_dial=fixture&ticket=fixture')
+ const controller = new AbortController()
+
+ try {
+ await client.request('prompt.submit', { session_id: 's', submission_id: 'one', text: 'hello' }, 100, controller.signal)
+ expect(calls).toEqual([
+ { method: 'session.resume', timeout: 100, signal: controller.signal },
+ { method: 'prompt.submit', timeout: 40, signal: controller.signal }
+ ])
+ } finally { client.close() }
+})
+
+
+
+test('a prerequisite attachment resolves the launch profile alias before preparing a mutation', async () => {
+ vi.spyOn(JsonRpcGatewayClient.prototype, 'connect').mockResolvedValue()
+ const calls: Array<{ method: string; params: unknown }> = []
+ vi.spyOn(JsonRpcGatewayClient.prototype, 'request').mockImplementation(async (method, params) => {
+ calls.push({ method, params })
+
+ if (method === 'session.resume') {
+ return { session_id: 's', revision: 3, execution_generation: 2, replay_epoch: 'named-owner',
+ messages: [], info: { profile_name: 'work', profile_id: '/profiles/work' } } as never
+ }
+
+ return { session_id: 's', revision: 4, operation: 'branch', branched_session_id: 'child', copied_messages: 0 } as never
+ })
+ const client = new HermesGateway()
+ await client.connect('ws://localhost/api/ws?native_dial=fixture&ticket=fixture')
+
+ try {
+ await expect(client.request('session.branch_stored', { parent_session_id: 's' })).resolves.toMatchObject({ session_id: 'child' })
+ expect(calls[1]).toMatchObject({ method: 'session.mutate', params: { profile: 'work', expected_revision: 3 } })
+ } finally { client.close() }
+})
diff --git a/apps/desktop/src/api/adversarial-prompt-profile-collision.test.ts b/apps/desktop/src/api/adversarial-prompt-profile-collision.test.ts
new file mode 100644
index 00000000000..3849d2fe5eb
--- /dev/null
+++ b/apps/desktop/src/api/adversarial-prompt-profile-collision.test.ts
@@ -0,0 +1,100 @@
+import { JsonRpcGatewayClient } from '@hermes/shared'
+import { afterEach, expect, test, vi } from 'vitest'
+
+import { CanonicalDesktopProtocol } from './canonical-protocol'
+import { HermesGateway } from './client'
+
+afterEach(() => vi.restoreAllMocks())
+
+test('retained prompts keep their own profile when imported profiles share a stored session ID', async () => {
+ vi.spyOn(JsonRpcGatewayClient.prototype, 'connect').mockResolvedValue()
+ const replies: Record<string, unknown>[] = []
+ vi.spyOn(JsonRpcGatewayClient.prototype, 'request').mockImplementation(async (method, params) => {
+ if (method === 'session.resume') {return {
+ session_id: 'imported-same-id', revision: 1, execution_generation: 2,
+ prompts: [{ kind: 'approval', prompt_id: `prompt-${params?.profile}`, execution_generation: 2,
+ command: 'build', choices: ['once'] }]
+ } as never}
+
+ if (method === 'approval.respond') {replies.push(params!)}
+
+ return { status: 'resolved' } as never
+ })
+ const client = new HermesGateway()
+ const shown: any[] = []
+ client.onRequest(request => { shown.push(request) })
+ await client.connect('ws://localhost/api/ws?native_dial=fixture&ticket=first')
+ await client.request('session.resume', { session_id: 'imported-same-id', profile: 'alpha' })
+ await client.request('session.resume', { session_id: 'imported-same-id', profile: 'beta' })
+ shown[0].respond({ choice: 'once' })
+ await vi.waitFor(() => expect(replies).toHaveLength(1))
+ expect(replies[0].profile).toBe('alpha')
+ client.close()
+})
+
+test('equal stored IDs keep independent revisions, generations, mutation retries and unknown admissions', () => {
+ const protocol = new CanonicalDesktopProtocol()
+
+ for (const [profile, revision, generation] of [['alpha', 4, 2], ['beta', 20, 9]] as const) {
+ protocol.result('session.resume', { session_id: 'same', profile }, {
+ session_id: 'same', revision, execution_generation: generation,
+ prompts: [{ kind: 'approval', prompt_id: 'same-prompt-id', execution_generation: generation }],
+ pending: [{ admission_id: 'same-admission-id', status: 'unknown', execution_generation: generation - 1 }]
+ })
+ }
+
+ const alpha = protocol.prepare('session.title', { session_id: 'same', profile: 'alpha', title: 'next' })
+ const beta = protocol.prepare('session.title', { session_id: 'same', profile: 'beta', title: 'next' })
+ expect(alpha.expected_revision).toBe(4)
+ expect(beta.expected_revision).toBe(20)
+ expect(alpha.request_id).not.toBe(beta.request_id)
+ protocol.event({ type: 'session.info', session_id: 'same', profile: 'beta', payload: {
+ pending: [], revision: 21, execution_generation: 10
+ } })
+ expect(protocol.prepare('session.title', { session_id: 'same', profile: 'alpha', title: 'next' })).toEqual(alpha)
+ expect(protocol.prepare('session.interrupt', { session_id: 'same', profile: 'alpha' }).execution_generation).toBe(2)
+ expect(protocol.prepare('session.interrupt', { session_id: 'same', profile: 'beta' }).execution_generation).toBe(10)
+ expect(protocol.prepare('approval.respond', { session_id: 'same', profile: 'alpha', prompt_id: 'same-prompt-id', choice: 'once' }).execution_generation).toBe(2)
+ expect(protocol.prepare('prompt.resolve_unknown', { session_id: 'same', profile: 'alpha', admission_id: 'same-admission-id' }).execution_generation).toBe(1)
+ expect(() => protocol.prepare('prompt.resolve_unknown', { session_id: 'same', profile: 'beta', admission_id: 'same-admission-id' })).toThrow('unknown')
+})
+
+test('implicit named-profile creation and explicit follow-ups share one owner and its mutation retry', async () => {
+ vi.spyOn(JsonRpcGatewayClient.prototype, 'connect').mockResolvedValue()
+ const calls: Array<[string, Record<string, unknown> | undefined]> = []
+ let failFirstMutation = true
+ vi.spyOn(JsonRpcGatewayClient.prototype, 'request').mockImplementation(async (method, params) => {
+ calls.push([method, params])
+
+ if (method === 'session.create' || method === 'session.resume') {
+ return { session_id: 'named-session', revision: 4, execution_generation: 2,
+ replay_epoch: 'same-owner', info: { profile_name: 'alpha', profile_id: '/profiles/alpha' }, prompts: [] } as never
+ }
+
+ if (method === 'prompt.submit') {
+ return { admission_id: 'a', status: 'queued', ref: { session_id: 'named-session', profile_id: '/profiles/alpha' } } as never
+ }
+
+ if (method === 'session.mutate' && failFirstMutation) {
+ failFirstMutation = false
+ throw new Error('lost acknowledgement')
+ }
+
+ return { session_id: 'named-session', revision: 5, operation: 'rename' } as never
+ })
+ const client = new HermesGateway()
+ await client.connect('ws://localhost/api/ws?native_dial=fixture&ticket=first')
+ await client.request('session.create', {})
+ await client.request('prompt.submit', { session_id: 'named-session', profile: 'alpha', submission_id: 'input', text: 'next' })
+ expect(calls.filter(([method]) => method === 'session.resume')).toHaveLength(0)
+ await expect(client.request('session.title', { session_id: 'named-session', title: 'retained' })).rejects.toThrow('lost acknowledgement')
+ const first = calls.find(([method]) => method === 'session.mutate')![1]!
+ await client.connect('ws://localhost/api/ws?native_dial=fixture&ticket=second')
+ await client.request('session.resume', { session_id: 'named-session' })
+ await client.request('session.title', { session_id: 'named-session', profile: '/profiles/alpha', title: 'retained' })
+ const second = calls.filter(([method]) => method === 'session.mutate').at(-1)![1]!
+ expect(second.request_id).toBe(first.request_id)
+ expect(second.profile).toBe('alpha')
+ expect(second.expected_revision).toBe(4)
+ client.close()
+})
diff --git a/apps/desktop/src/api/adversarial-prompt-replay.test.ts b/apps/desktop/src/api/adversarial-prompt-replay.test.ts
new file mode 100644
index 00000000000..ced1c713ec2
--- /dev/null
+++ b/apps/desktop/src/api/adversarial-prompt-replay.test.ts
@@ -0,0 +1,63 @@
+import { JsonRpcGatewayClient } from '@hermes/shared'
+import { afterEach, expect, test, vi } from 'vitest'
+
+import { HermesGateway } from './client'
+
+afterEach(() => vi.restoreAllMocks())
+
+test('an unanswered prompt is replayed after its response was lost and the socket reconnects', async () => {
+ vi.spyOn(JsonRpcGatewayClient.prototype, 'connect').mockResolvedValue()
+
+ const pending = { kind: 'approval', prompt_id: 'same-prompt', execution_generation: 2,
+ command: 'build', choices: ['once', 'deny'] }
+
+ vi.spyOn(JsonRpcGatewayClient.prototype, 'request').mockImplementation(async method => {
+ if (method === 'approval.respond') {throw new Error('Gateway connection closed')}
+
+ return { session_id: 's', revision: 1, execution_generation: 2, prompts: [pending] } as never
+ })
+ const client = new HermesGateway()
+ const shown: any[] = []
+ client.onRequest(request => { shown.push(request) })
+ await client.connect('ws://localhost/api/ws?native_dial=fixture&ticket=first')
+ await client.request('session.resume', { session_id: 's' })
+ shown[0].respond({ choice: 'once' })
+ await Promise.resolve()
+ await Promise.resolve()
+ await client.connect('ws://localhost/api/ws?native_dial=fixture&ticket=second')
+ await client.request('session.resume', { session_id: 's' })
+ expect(shown).toHaveLength(2)
+ expect(shown[1].replayed).toBe(true)
+ client.close()
+})
+
+test('failed answers recover an authoritative pending card once and callbacks cannot cross socket generations', async () => {
+ vi.spyOn(JsonRpcGatewayClient.prototype, 'connect').mockResolvedValue()
+ const prompt = { kind: 'approval', prompt_id: 'pending', execution_generation: 2, command: 'build', choices: ['once'] }
+
+ const wire = vi.spyOn(JsonRpcGatewayClient.prototype, 'request').mockImplementation(async method => {
+ if (method === 'approval.respond') { throw new Error('temporary transport failure') }
+
+ return { session_id: 's', revision: 1, execution_generation: 2, prompts: [prompt] } as never
+ })
+
+ const client = new HermesGateway()
+ const shown: any[] = []
+ client.onRequest(request => { shown.push(request) })
+ await client.connect('ws://localhost/api/ws?native_dial=fixture&ticket=first')
+ await client.request('session.resume', { session_id: 's', profile: 'sibling' })
+ shown[0].respond({ choice: 'once' })
+ await vi.waitFor(() => expect(shown).toHaveLength(2))
+ await client.request('session.resume', { session_id: 's', profile: 'sibling' })
+ expect(shown).toHaveLength(2)
+ expect(wire.mock.calls.filter(([method]) => method === 'approval.respond')).toHaveLength(1)
+ const old = shown[1]
+ await client.connect('ws://localhost/api/ws?native_dial=fixture&ticket=second')
+ await client.request('session.resume', { session_id: 's', profile: 'sibling' })
+ const before = wire.mock.calls.length
+ old.respond({ choice: 'once' })
+ await Promise.resolve()
+ expect(wire).toHaveBeenCalledTimes(before)
+ expect(shown).toHaveLength(3)
+ client.close()
+})
diff --git a/apps/desktop/src/api/canonical-clarify-prompt.test.ts b/apps/desktop/src/api/canonical-clarify-prompt.test.ts
index 31a38f48159..6e43061c699 100644
--- a/apps/desktop/src/api/canonical-clarify-prompt.test.ts
+++ b/apps/desktop/src/api/canonical-clarify-prompt.test.ts
@@ -3,6 +3,49 @@ import { expect, test } from 'vitest'
import { HermesGateway } from './client'
+test('a reopened sibling chat delivers retained questions before returning and replies on its route', 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[] = []
+
+ const snapshot = { session_id: 's', revision: 2, execution_generation: 7, prompts: [
+ { kind: 'clarify', prompt_id: 'c1', execution_generation: 7, question: 'Which target?', choices: [] },
+ { kind: 'approval', prompt_id: 'a1', execution_generation: 7, command: 'build', choices: ['once'] }
+ ] }
+
+ server.on('connection', (socket: any) => socket.on('message', (bytes: Buffer) => {
+ const frame = JSON.parse(bytes.toString())
+ sent.push(frame)
+ socket.send(JSON.stringify({ jsonrpc: '2.0', id: frame.id,
+ result: frame.method === 'session.resume' ? snapshot : { status: 'resolved' } }))
+ }))
+ 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' })
+ expect(delivered.map(request => [request.method, request.replayed])).toEqual([['clarify', true], ['approval', true]])
+ await client.request('clarify.lock', { request_id: 'c1', answer: 'staging' })
+ delivered[1].respond({ choice: 'once' })
+ await new Promise<void>(resolve => {
+ const check = () => sent.some(frame => frame.method === 'approval.respond') ? resolve() : setTimeout(check, 5)
+ check()
+ })
+ expect(sent.map(frame => frame.method)).toEqual(['session.resume', 'clarify.respond', 'approval.respond'])
+ expect(sent.slice(1).map(frame => frame.params.profile)).toEqual(['sibling', 'sibling'])
+ } finally {
+ client.close()
+
+ for (const socket of server.clients) { socket.terminate() }
+ await new Promise<void>(resolve => server.close(() => resolve()))
+ }
+})
+
// A canonical shared clarify prompt reaches the question card in its one `questions[]` shape,
// and the card's `clarify.lock` lands as the generation-fenced `clarify.respond`.
test('a canonical clarify prompt drives the question card and its lock answers on the fenced wire', async () => {
@@ -38,8 +81,8 @@ test('a canonical clarify prompt drives the question card and its lock answers o
sent.length = 0
await client.request('clarify.lock', { request_id: 'c1', question_id: 'c1', answer: null })
expect(sent.map(frame => [frame.method, frame.params])).toEqual([
- ['session.resume', { session_id: 's', defer_history: true, omit_messages: true }],
- ['clarify.respond', { session_id: 's', execution_generation: 7, prompt_id: 'c1', answer: '' }]
+ ['session.resume', { session_id: 's', profile: 'default', defer_history: true, omit_messages: true }],
+ ['clarify.respond', { session_id: 's', profile: 'default', execution_generation: 7, prompt_id: 'c1', answer: '' }]
])
} finally {
client.close()
diff --git a/apps/desktop/src/api/canonical-deadline.test.ts b/apps/desktop/src/api/canonical-deadline.test.ts
new file mode 100644
index 00000000000..5ffa7300164
--- /dev/null
+++ b/apps/desktop/src/api/canonical-deadline.test.ts
@@ -0,0 +1,44 @@
+import { JsonRpcGatewayClient } from '@hermes/shared'
+import { afterEach, expect, test, vi } from 'vitest'
+
+import { HermesGateway } from './client'
+
+afterEach(() => { vi.restoreAllMocks() })
+
+test.each([60, 120])('compress follow-up spends only the remaining caller budget after %i ms', async elapsed => {
+ let now = 1_000
+ vi.spyOn(Date, 'now').mockImplementation(() => now)
+ vi.spyOn(JsonRpcGatewayClient.prototype, 'connect').mockResolvedValue()
+ const calls: Array<{ method: string; timeout?: number; signal?: AbortSignal }> = []
+ const snapshot = { session_id: 's', revision: 1, execution_generation: 2, messages: [], info: {} }
+ vi.spyOn(JsonRpcGatewayClient.prototype, 'request').mockImplementation(async (method, _params, timeout, signal) => {
+ calls.push({ method, timeout, signal })
+
+ if (method === 'session.mutate') {
+ now += elapsed
+
+ return { session_id: 's', revision: 2, operation: 'compress', message_count: 0 } as never
+ }
+
+ return snapshot as never
+ })
+ const client = new HermesGateway()
+ await client.connect('ws://localhost/api/ws?native_dial=fixture&ticket=fixture')
+ await client.request('session.resume', { session_id: 's', profile: 'sibling' })
+ calls.length = 0
+ const controller = new AbortController()
+ const compression = client.request('session.compress', { session_id: 's', profile: 'sibling' }, 100, controller.signal)
+
+ if (elapsed < 100) {
+ await expect(compression).resolves.toHaveProperty('messages')
+ expect(calls).toEqual([
+ { method: 'session.mutate', timeout: 100, signal: controller.signal },
+ { method: 'session.resume', timeout: 40, signal: controller.signal }
+ ])
+ } else {
+ await expect(compression).rejects.toThrow('timed out')
+ expect(calls).toHaveLength(1)
+ }
+
+ client.close()
+})
diff --git a/apps/desktop/src/api/canonical-profile-events.test.ts b/apps/desktop/src/api/canonical-profile-events.test.ts
new file mode 100644
index 00000000000..8330e70340d
--- /dev/null
+++ b/apps/desktop/src/api/canonical-profile-events.test.ts
@@ -0,0 +1,72 @@
+// @vitest-environment node
+import { expect, test, vi } from 'vitest'
+
+import { HermesGateway } from './client'
+
+test('shared-socket equal-ID streams use replay owners and unknown epochs reconcile without changing controls', 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 calls: any[] = []
+ let socket: any
+
+ const snapshots: Record<string, any> = {
+ alpha: { session_id: 'same', revision: 4, execution_generation: 2, replay_epoch: 'epoch-alpha', prompts: [] },
+ beta: { session_id: 'same', revision: 20, execution_generation: 9, replay_epoch: 'epoch-beta', prompts: [] }
+ }
+
+ server.on('connection', (connected: any) => {
+ socket = connected
+ socket.on('message', (bytes: Buffer) => {
+ const frame = JSON.parse(bytes.toString())
+ calls.push(frame)
+ const snapshot = snapshots[frame.params.profile]
+
+ const result = frame.method === 'session.resume' ? snapshot : frame.method === 'prompt.submit'
+ ? { admission_id: 'accepted-beta', ref: { profile_id: 'beta', session_id: 'same' }, status: 'queued' }
+ : { ...snapshot, operation: frame.params.operation }
+
+ socket.send(JSON.stringify({ jsonrpc: '2.0', id: frame.id, result }))
+ })
+ })
+ const client = new HermesGateway()
+ const named: any[] = []
+ const wildcard: any[] = []
+ client.on('session.info', event => named.push(event))
+ client.onAny(event => { if (event.type === 'session.info') {wildcard.push(event)} })
+
+ 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: 'same', profile: 'alpha' })
+ await client.request('prompt.submit', { session_id: 'same', profile: 'beta', submission_id: 'beta-input', text: 'beta' })
+ expect(calls.filter(frame => frame.method === 'session.resume').map(frame => frame.params.profile)).toEqual(['alpha', 'beta'])
+
+ const send = (epoch: string, generation: number, revision: number) => socket.send(JSON.stringify({
+ jsonrpc: '2.0', method: 'event', params: { type: 'session.info', session_id: 'same',
+ replay_epoch: epoch, execution_generation: generation, payload: { revision, execution_generation: generation } }
+ }))
+
+ snapshots.alpha = { ...snapshots.alpha, revision: 5, execution_generation: 3 }
+ snapshots.beta = { ...snapshots.beta, revision: 21, execution_generation: 10 }
+ send('epoch-beta', 10, 21)
+ send('epoch-alpha', 3, 5)
+ await vi.waitFor(() => expect(named).toHaveLength(2))
+ expect(named.map(event => event.profile)).toEqual(['beta', 'alpha'])
+ expect(wildcard.map(event => event.profile)).toEqual(['beta', 'alpha'])
+ await client.request('session.title', { session_id: 'same', profile: 'alpha', title: 'alpha title' })
+ expect(calls.find(frame => frame.method === 'session.mutate').params.expected_revision).toBe(5)
+ send('unrecognized-epoch', 999, 999)
+ await vi.waitFor(() => expect(calls.filter(frame => frame.method === 'session.resume')).toHaveLength(4))
+ expect(named).toHaveLength(2)
+ await client.request('session.interrupt', { session_id: 'same', profile: 'alpha' })
+ expect(calls.find(frame => frame.method === 'session.interrupt').params.execution_generation).toBe(3)
+ await expect(client.request('session.interrupt', { session_id: 'same' })).rejects.toThrow('several profiles')
+ } finally {
+ client.close()
+
+ for (const peer of server.clients) {peer.terminate()}
+ await new Promise<void>(resolve => server.close(() => resolve()))
+ }
+})
diff --git a/apps/desktop/src/api/canonical-protocol.test.ts b/apps/desktop/src/api/canonical-protocol.test.ts
index 6c198e02889..8e7e63f53d4 100644
--- a/apps/desktop/src/api/canonical-protocol.test.ts
+++ b/apps/desktop/src/api/canonical-protocol.test.ts
@@ -2,6 +2,56 @@ import { expect, test } from 'vitest'
import { CanonicalDesktopProtocol } from './canonical-protocol'
+test('sibling routes survive every rebuilt control and compression follow-up', async () => {
+ const protocol = new CanonicalDesktopProtocol()
+ protocol.result('session.resume', { session_id: 's', profile: 'sibling' }, {
+ session_id: 's', revision: 4, execution_generation: 9,
+ prompts: [{ kind: 'approval', prompt_id: 'p', execution_generation: 9 }],
+ pending: [{ admission_id: 'lost', status: 'unknown', execution_generation: 3 }]
+ })
+
+ const requests: Array<[string, Record<string, unknown>]> = [
+ ['session.title', { title: 'title' }], ['session.archive', { archived: true }],
+ ['session.branch', {}], ['session.branch_stored', { parent_session_id: 's' }],
+ ['session.compress', {}], ['slash.exec', { command: 'model new-model' }],
+ ['approval.respond', { request_id: 'p', choice: 'once' }],
+ ['prompt.resolve_unknown', { admission_id: 'lost' }]
+ ]
+
+ for (const [method, params] of requests) {
+ expect(protocol.prepare(method, { session_id: 's', profile: 'sibling', ...params })).toMatchObject({ profile: 'sibling' })
+ }
+
+ const calls: unknown[] = []
+ const params = protocol.prepare('session.compress', { session_id: 's', profile: 'sibling' })
+ await protocol.settle('session.compress', params, { message_count: 1 }, async (method, followUp) => {
+ calls.push([method, followUp])
+
+ return { messages: [], info: {} }
+ })
+ expect(calls).toEqual([['session.resume', { session_id: 's', profile: 'sibling' }]])
+})
+
+test('slash compress refreshes its transcript on the owner route and previews stay read-only', async () => {
+ const protocol = new CanonicalDesktopProtocol()
+ protocol.result('session.resume', { profile: 'sibling' }, { session_id: 's', revision: 1, execution_generation: 2 })
+ const prepared = protocol.prepare('slash.exec', { session_id: 's', profile: 'sibling', command: 'compress' })
+ const calls: unknown[] = []
+
+ const followUp = async (method: string, params: Record<string, unknown>) => {
+ calls.push([method, params])
+
+ return { messages: [{ role: 'assistant', content: 'retained' }], info: {} }
+ }
+
+ const result = protocol.result('slash.exec', prepared, { session_id: 's', revision: 2, message_count: 1 })
+ expect(await protocol.settle('slash.exec', prepared, result, followUp)).toMatchObject({ type: 'exec', messages: [{ content: 'retained' }] })
+ expect(calls).toEqual([['session.resume', { session_id: 's', profile: 'sibling' }]])
+ const preview = protocol.result('slash.exec', prepared, { session_id: 's', status: 'preview', lines: ['report'] })
+ await protocol.settle('slash.exec', prepared, preview, followUp)
+ expect(calls).toHaveLength(1)
+})
+
test('corrections preserve intent and fence the observed session generation', () => {
const protocol = new CanonicalDesktopProtocol()
diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.ts
index 796c78ed4f2..6e7ecc77b87 100644
--- a/apps/desktop/src/api/canonical-protocol.ts
+++ b/apps/desktop/src/api/canonical-protocol.ts
@@ -3,6 +3,19 @@
export const CANONICAL_GATEWAY_PROTOCOL = 'hermes-gateway-v1'
+export const canonicalProfile = (profile: unknown): string =>
+ typeof profile === 'string' && profile ? profile : 'default'
+
+export const canonicalSessionKey = (sessionId: unknown, profile?: unknown): string =>
+ JSON.stringify([canonicalProfile(profile), sessionId])
+
+// Only the authenticated adapter can establish this renderer-side provenance;
+// a JSON-RPC payload's ordinary `profile` property cannot impersonate it.
+const canonicalOwners = new WeakMap<object, string>()
+export const canonicalOwnerProfile = (value: object): string | undefined => canonicalOwners.get(value)
+
+export const recordCanonicalOwner = (value: object, profile: string): void => { canonicalOwners.set(value, profile) }
+
// 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
@@ -59,7 +72,7 @@ export class CanonicalDesktopProtocol {
// admission_id → generation of a turn the authority recovered as `unknown`
// (owner died mid-turn). Only these rows may be acknowledged, and only with
// the generation the authority stamped on them, never the live one.
- private unknownAdmissions = new Map<string, { session_id: string; generation: number }>()
+ private unknownAdmissions = new Map<string, { session_id: string; profile: string; generation: number }>()
failure(params: Record<string, unknown>, error: unknown) {
if ((error as { data?: { reason?: string } })?.data?.reason !== 'revision_conflict') { return }
@@ -83,15 +96,16 @@ export class CanonicalDesktopProtocol {
return method === 'slash.exec' && typeof prepared.operation === 'string' ? 'session.mutate' : method
}
- private retainedMutation(sessionId: unknown, operation: string, payload: Record<string, unknown>, withGeneration: boolean): Record<string, unknown> {
- const key = JSON.stringify([sessionId, operation, payload])
+ private retainedMutation(sessionId: unknown, profile: unknown, operation: string, payload: Record<string, unknown>, withGeneration: boolean): Record<string, unknown> {
+ const owner = canonicalSessionKey(sessionId, profile)
+ const key = JSON.stringify([owner, operation, payload])
const retained = this.mutations.get(key)
if (retained) { return retained }
- const revision = this.revisions.get(String(sessionId))
+ const revision = this.revisions.get(owner)
if (revision === undefined) { throw new Error('Session revision unavailable; reopen the session before editing metadata') }
- const generation = this.generations.get(String(sessionId))
+ const generation = this.generations.get(owner)
if (withGeneration && generation === undefined) { throw new Error('Session execution identity unavailable; reconnect before this command') }
@@ -104,6 +118,14 @@ export class CanonicalDesktopProtocol {
}
prepare(method: string, params: Record<string, unknown>): Record<string, unknown> {
+ const prepared = this.preparePayload(method, params)
+
+ // Routing belongs to the envelope, independently of the canonical payload.
+ // Creation applies its own default-profile normalization.
+ return method !== 'session.create' && params.profile !== undefined ? { ...prepared, profile: params.profile } : prepared
+ }
+
+ private preparePayload(method: string, params: Record<string, unknown>): Record<string, unknown> {
const mutation = this.prepareMutation(method, params)
if (mutation) { return mutation }
@@ -115,7 +137,7 @@ export class CanonicalDesktopProtocol {
}
if (method === 'session.interrupt' || method === 'session.redirect' || method === 'session.steer') {
- const generation = params.execution_generation ?? this.generations.get(String(params.session_id))
+ const generation = params.execution_generation ?? this.generations.get(canonicalSessionKey(params.session_id, params.profile))
if (typeof generation !== 'number') { throw new Error('Session execution identity unavailable; reconnect before controlling this turn') }
@@ -123,9 +145,9 @@ export class CanonicalDesktopProtocol {
}
if (method === 'prompt.resolve_unknown') {
- const lost = this.unknownAdmissions.get(String(params.admission_id))
+ const lost = this.unknownAdmissions.get(canonicalSessionKey(params.admission_id, params.profile))
- if (!lost || lost.session_id !== params.session_id) { throw new Error('Admission is not an unknown lost turn; reopen the session before acknowledging') }
+ if (!lost || lost.session_id !== params.session_id || lost.profile !== canonicalProfile(params.profile)) { throw new Error('Admission is not an unknown lost turn; reopen the session before acknowledging') }
return { session_id: params.session_id, admission_id: params.admission_id, execution_generation: lost.generation }
}
@@ -139,7 +161,7 @@ export class CanonicalDesktopProtocol {
private prepareMutation(method: string, params: Record<string, unknown>): Record<string, unknown> | null {
const field = ({ 'session.title': 'title', 'session.archive': 'archived' } as Record<string, string>)[method]
- if (field) { return this.retainedMutation(params.session_id, field === 'title' ? 'rename' : 'archive', { [field]: params[field] }, false) }
+ if (field) { return this.retainedMutation(params.session_id, params.profile, field === 'title' ? 'rename' : 'archive', { [field]: params[field] }, false) }
// Branch and compress fence the execution generation like the slash directives.
const fenced = ({
@@ -147,20 +169,20 @@ export class CanonicalDesktopProtocol {
'session.compress': () => ({ operation: 'compress', payload: params.focus_topic ? { focus: String(params.focus_topic) } : {} })
} as Record<string, () => { operation: string; payload: Record<string, unknown> }>)[method]?.()
- if (fenced) { return this.retainedMutation(params.session_id, fenced.operation, fenced.payload, true) }
+ if (fenced) { return this.retainedMutation(params.session_id, params.profile, fenced.operation, fenced.payload, true) }
if (method === 'session.branch_stored' || method === 'session.branch_whole') {
// The stored-parent form names the parent as `parent_session_id`; the live form as `session_id`.
const parent = params.parent_session_id ?? params.session_id
const payload = typeof params.title === 'string' && params.title ? { title: params.title } : {}
- return this.retainedMutation(parent, 'branch', payload, true)
+ return this.retainedMutation(parent, params.profile, 'branch', payload, true)
}
if (method === 'slash.exec') {
const directive = slashMutation(String(params.command ?? ''))
- if (directive) { return this.retainedMutation(params.session_id, directive.operation, directive.payload, true) }
+ if (directive) { return this.retainedMutation(params.session_id, params.profile, directive.operation, directive.payload, true) }
}
return null
@@ -184,10 +206,11 @@ export class CanonicalDesktopProtocol {
private preparePromptResponse(method: string, params: Record<string, unknown>): Record<string, unknown> {
const id = String(params.prompt_id ?? params.request_id ?? '')
- const prompt = this.prompts.get(id)
+ const prompt = this.prompts.get(canonicalSessionKey(id, params.profile))
const sessionId = params.session_id ?? prompt?.session_id
- if (!prompt || prompt.session_id !== sessionId || prompt.execution_generation !== this.generations.get(String(sessionId))) {
+ if (!prompt || prompt.session_id !== sessionId || prompt.profile !== canonicalProfile(params.profile) ||
+ prompt.execution_generation !== this.generations.get(canonicalSessionKey(sessionId, params.profile))) {
throw new Error('Prompt is stale or unavailable; reconnect before responding')
}
@@ -196,43 +219,53 @@ export class CanonicalDesktopProtocol {
return { session_id: sessionId, execution_generation: prompt.execution_generation, prompt_id: id, [field]: params[field] }
}
- event(event: { type: string; session_id?: string; payload?: unknown }) {
+ private reconcileUnknownAdmissions(sid: string, profile: string, pending: Array<Record<string, unknown>>): void {
+ for (const [id, lost] of this.unknownAdmissions) {
+ if (lost.session_id === sid && lost.profile === profile) { this.unknownAdmissions.delete(id) }
+ }
+
+ for (const row of pending) {
+ if (row?.status === 'unknown' && typeof row.admission_id === 'string' && typeof row.execution_generation === 'number') {
+ this.unknownAdmissions.set(canonicalSessionKey(row.admission_id, profile), { session_id: sid, profile, generation: row.execution_generation })
+ }
+ }
+ }
+
+ event(event: { type: string; session_id?: string; profile?: string; execution_generation?: unknown; payload?: unknown }) {
const payload = event.payload as Record<string, unknown> | undefined
if (!payload || !event.session_id) { return }
const sid = event.session_id
+ const profile = canonicalProfile(event.profile)
+ const owner = canonicalSessionKey(sid, profile)
if (Array.isArray(payload.pending)) {
payload.pending_submissions = payload.pending.map(row => ({ ...row, user: row.text }))
- for (const [id, lost] of this.unknownAdmissions) { if (lost.session_id === sid) { this.unknownAdmissions.delete(id) } }
-
- for (const row of payload.pending) {
- if (row?.status === 'unknown' && typeof row.admission_id === 'string' && typeof row.execution_generation === 'number') {
- this.unknownAdmissions.set(row.admission_id, { session_id: sid, generation: row.execution_generation })
- }
- }
+ this.reconcileUnknownAdmissions(sid, profile, payload.pending)
}
- if (typeof payload.execution_generation === 'number') {
- const current = this.generations.get(sid) ?? -1
+ const generation = event.execution_generation ?? payload.execution_generation
+
+ if (typeof generation === 'number') {
+ const current = this.generations.get(owner) ?? -1
- if (payload.execution_generation < current) { return }
- this.generations.set(sid, payload.execution_generation)
+ if (generation < current) { return }
+ this.generations.set(owner, generation)
}
// Turns advance the CAS revision without a session.updated event; the
// pending fanout is where a viewer learns the value its next mutation must present.
- if (event.type === 'session.info' && typeof payload.revision === 'number') { this.revisions.set(sid, payload.revision) }
+ if (event.type === 'session.info' && typeof payload.revision === 'number') { this.revisions.set(owner, payload.revision) }
if (typeof payload.prompt_id === 'string') {
- if (event.type.endsWith('.settled')) { this.prompts.delete(payload.prompt_id);
+ if (event.type.endsWith('.settled')) { this.prompts.delete(canonicalSessionKey(payload.prompt_id, profile));
return }
if (event.type === 'approval.request' || event.type === 'clarify.request') {
payload.request_id = payload.prompt_id
- this.prompts.set(payload.prompt_id, { ...payload, session_id: sid })
+ this.prompts.set(canonicalSessionKey(payload.prompt_id, profile), { ...payload, session_id: sid, profile })
}
}
}
@@ -241,7 +274,7 @@ export class CanonicalDesktopProtocol {
if (!value || typeof value !== 'object') { return value }
if (typeof value.session_id === 'string' && typeof value.revision === 'number') {
- this.revisions.set(value.session_id, value.revision)
+ this.revisions.set(canonicalSessionKey(value.session_id, params.profile), value.revision)
}
if (MUTATION_METHODS.has(method) || (method === 'slash.exec' && typeof params.operation === 'string')) {
@@ -254,10 +287,10 @@ export class CanonicalDesktopProtocol {
if (method === 'prompt.submit' || method === 'prompt.resolve_unknown') { return this.admissionReceipt(method, params, value) }
- if (method === 'session.resume' || method === 'session.create' || method === 'session.activate') { return this.snapshotResult(value) }
+ if (method === 'session.resume' || method === 'session.create' || method === 'session.activate') { return this.snapshotResult(value, params.profile) }
if (method === 'session.events.since') {
- for (const event of value.events ?? []) { this.event(event) }
+ for (const event of value.events ?? []) { this.event({ ...event, profile: canonicalProfile(params.profile) }) }
}
return value
@@ -276,7 +309,7 @@ export class CanonicalDesktopProtocol {
throw new Error('Canonical admission receipt destination mismatch')
}
- this.unknownAdmissions.delete(String(params.admission_id))
+ this.unknownAdmissions.delete(canonicalSessionKey(params.admission_id, params.profile))
return { ...value, session_id: value.ref.session_id }
}
@@ -290,18 +323,19 @@ export class CanonicalDesktopProtocol {
return { ...value, session_id: value.branched_session_id, stored_session_id: value.branched_session_id, parent_session_id: params.session_id, message_count: value.copied_messages }
}
- if (method === 'slash.exec') { return { type: 'exec', output: mutationSummary(params.operation as string, value) } }
+ if (method === 'slash.exec') { return { ...value, type: 'exec', output: mutationSummary(params.operation as string, value) } }
return { ...value, ok: true }
}
- private snapshotResult(value: any): any {
+ private snapshotResult(value: any, route: unknown): any {
const sid = value.session_id
- this.event({ type: 'session.info', session_id: sid, payload: value })
+ const profile = canonicalProfile(route)
+ this.event({ type: 'session.info', session_id: sid, profile, payload: value })
const prompts = (value.prompts ?? []).map((prompt: Record<string, unknown>) => {
const projected = { ...prompt, request_id: prompt.prompt_id }
- this.event({ type: `${prompt.kind}.request`, session_id: sid, payload: projected })
+ this.event({ type: `${prompt.kind}.request`, session_id: sid, profile, payload: projected })
return projected
})
@@ -313,11 +347,11 @@ export class CanonicalDesktopProtocol {
// the compress action repaints only from `messages`, so resume the session
// through the normal request path (which also re-primes revision/generation).
async settle(method: string, params: Record<string, unknown>, value: any, request: (method: string, params: Record<string, unknown>) => Promise<any>): Promise<any> {
- if (method !== 'session.compress') { return value }
+ if (method !== 'session.compress' && !(method === 'slash.exec' && params.operation === 'compress')) { return value }
// `--preview` in the focus argument is a read-only report: no transcript changed.
if (value?.status === 'preview') { return { ...value, host_ack: { output: (value.lines as string[]).join('\n') } } }
- const resumed = await request('session.resume', { session_id: params.session_id })
+ const resumed = await request('session.resume', { session_id: params.session_id, ...(params.profile !== undefined ? { profile: params.profile } : {}) })
return { ...value, messages: resumed.messages, info: resumed.info, host_ack: { output: `compressed context: ${value.message_count} messages retained` } }
}
diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.ts
index d402ea0bc7f..774c6f626c6 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, siblingRoute } from './canonical-protocol'
+import { CANONICAL_GATEWAY_PROTOCOL, CanonicalDesktopProtocol, canonicalProfile, canonicalSessionKey, recordCanonicalOwner } 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
@@ -62,12 +62,28 @@ function legacyParams(method: string, params: Record<string, unknown>): Record<s
return Object.fromEntries(Object.entries(params).filter(([key]) => !strip.includes(key)))
}
+function remainingRequestBudget(deadline: number, signal?: AbortSignal): number {
+ signal?.throwIfAborted()
+ const remaining = deadline - Date.now()
+
+ if (remaining <= 0) { throw new Error('Hermes gateway request timed out') }
+
+ return remaining
+}
+
export class HermesGateway extends JsonRpcGatewayClient {
private canonical = false
private readonly protocol = new CanonicalDesktopProtocol()
private readonly promptHandlers = new Set<ServerRequestHandler>()
- // Delivered canonical prompt id → its session (the fenced respond needs both).
- private readonly deliveredPrompts = new Map<string, string>()
+ // A stored ID can exist in several profile islands (for example after import).
+ private readonly deliveredPrompts = new Map<string, { sessionId: string; profile: string }>()
+ private readonly sessionProfiles = new Map<string, Set<string>>()
+ private readonly profileAliases = new Map<string, string>()
+ private readonly replayProfiles = new Map<string, { sessionId: string; profile: string }>()
+ private readonly displayProfiles = new Map<string, string>()
+ private readonly eventRoutes = new WeakMap<GatewayEvent, string>()
+ private readonly reconciledEpochs = new Set<string>()
+ private connectionGeneration = 0
override onRequest(handler: ServerRequestHandler): () => void {
this.promptHandlers.add(handler)
@@ -79,16 +95,18 @@ export class HermesGateway extends JsonRpcGatewayClient {
}
}
- private deliverCanonicalPrompt(event: { type: string; session_id?: string; payload?: unknown }, replayed: boolean) {
+ private deliverCanonicalPrompt(event: { type: string; session_id?: string; profile?: string; payload?: unknown }, replayed: boolean) {
const kind = CANONICAL_PROMPT_EVENTS[event.type]
const p = event.payload as Record<string, unknown> | undefined
const sid = event.session_id
if (!kind || !p || !sid || typeof p.prompt_id !== 'string') { return }
const id = p.prompt_id
+ const profile = canonicalProfile(event.profile)
+ const generation = this.connectionGeneration
if (this.deliveredPrompts.has(id)) { return }
- this.deliveredPrompts.set(id, sid)
+ this.deliveredPrompts.set(id, { sessionId: sid, profile })
const choices = Array.isArray(p.choices) ? p.choices : []
// The question card reads one `questions[]` shape. A canonical clarify prompt is one
@@ -108,35 +126,150 @@ export class HermesGateway extends JsonRpcGatewayClient {
params,
replayed,
respond: result => {
- if (settled) { return }
+ if (settled || generation !== this.connectionGeneration) { return }
settled = true
+
// A clarify reply without an answer (skip, Stop, cancel) is the empty answer the
// authority records as skipped; `clarify.respond` refuses a missing field.
const answer = kind === 'clarify'
? { answer: typeof result.answer === 'string' ? result.answer : '' }
: { choice: result.choice }
- void this.request(`${kind}.respond`, { session_id: sid, request_id: id, ...answer }).catch(() => undefined)
+
+ void this.request(`${kind}.respond`, { session_id: sid, profile, request_id: id, ...answer })
+ .catch(() => this.recoverCanonicalPrompt(id, sid, profile, generation))
},
fail: () => { settled = true }
}
+ recordCanonicalOwner(request, this.displayProfiles.get(canonicalSessionKey(sid, profile)) ?? profile)
+
for (const handler of this.promptHandlers) {
if (handler(request) !== false) { return }
}
}
+ private async recoverCanonicalPrompt(id: string, sessionId: string, profile: string, generation: number): Promise<void> {
+ if (generation !== this.connectionGeneration || !this.deliveredPrompts.has(id)) { return }
+ this.deliveredPrompts.delete(id)
+
+ // A lost reply may have committed. Reopen a card only if the authority's
+ // snapshot still lists it; never resend an approval from a cached event.
+ try { await this.request('session.resume', { session_id: sessionId, profile }) } catch {
+ // A disconnected socket will reconcile its pending prompts on reattach.
+ }
+ }
+
+ override close(): void {
+ this.connectionGeneration++
+ this.deliveredPrompts.clear()
+ this.sessionProfiles.clear()
+ this.profileAliases.clear()
+ this.replayProfiles.clear()
+ this.displayProfiles.clear()
+ this.reconciledEpochs.clear()
+ this.attached.clear()
+ super.close()
+ }
+
override on<K extends GatewayEventName>(type: K, handler: (event: GatewayEvent<K>) => void): () => void {
return super.on<K>(type, event => {
// Named listeners run before wildcard listeners in the shared client.
// Normalize before either kind sees the prompt, including replay delivery.
- if (this.canonical) { this.protocol.event(event) }
+ if (this.canonical && !this.normalizeCanonicalEvent(event)) { return }
handler(event)
})
}
+ override onAny(handler: (event: GatewayEvent) => void): () => void {
+ return super.onAny(event => {
+ if (this.canonical && !this.normalizeCanonicalEvent(event)) { return }
+ handler(event)
+ })
+ }
+
+ private rememberSessionProfile(sessionId: string, profile: unknown): void {
+ const profiles = this.sessionProfiles.get(sessionId) ?? new Set<string>()
+ profiles.add(this.resolveSessionProfile(sessionId, profile))
+ this.sessionProfiles.set(sessionId, profiles)
+ }
+
+ private resolveSessionProfile(sessionId: string, profile: unknown): string {
+ return this.profileAliases.get(canonicalSessionKey(sessionId, profile)) ?? canonicalProfile(profile)
+ }
+
+ private snapshotRoute(params: Record<string, unknown>, snapshot: any): Record<string, unknown> {
+ const sid = snapshot?.session_id
+
+ if (typeof sid !== 'string') { return params }
+ const previous = canonicalProfile(params.profile)
+ const replayOwner = this.replayProfiles.get(snapshot.replay_epoch)
+ const named = snapshot.info?.profile_name
+
+ const profile = typeof named === 'string' && named ? named :
+ replayOwner?.sessionId === sid ? replayOwner.profile : previous
+
+ this.profileAliases.set(canonicalSessionKey(sid, previous), profile)
+
+ if (typeof snapshot.info?.profile_id === 'string') {
+ this.profileAliases.set(canonicalSessionKey(sid, snapshot.info.profile_id), profile)
+ }
+
+ const profiles = this.sessionProfiles.get(sid)
+ profiles?.delete(previous)
+ this.rememberSessionProfile(sid, profile)
+
+ // The implicit route of a named launch profile and its explicit name are
+ // one owner. Store retry identities under that stable name across redials.
+ return profile === previous ? params : { ...params, profile }
+ }
+
+ private normalizeCanonicalEvent(event: GatewayEvent): boolean {
+ if (!event.session_id) { return true }
+ const owner = event.replay_epoch ? this.replayProfiles.get(event.replay_epoch) : undefined
+ const profiles = this.sessionProfiles.get(event.session_id)
+
+ let profile = owner?.sessionId === event.session_id ? owner.profile : this.eventRoutes.get(event) ??
+ (profiles?.size === 1 ? profiles.values().next().value : profiles?.size ? undefined : 'default')
+
+ if (profile === undefined) {
+ this.reconcileAmbiguousEvent(event.session_id, event.replay_epoch)
+
+ return false
+ }
+
+ profile = this.resolveSessionProfile(event.session_id, profile)
+ // The renderer already understands an owner profile tag on shared-socket events.
+ this.eventRoutes.set(event, profile)
+ event.profile = this.displayProfiles.get(canonicalSessionKey(event.session_id, profile)) ?? profile
+ recordCanonicalOwner(event, event.profile)
+ this.protocol.event({ ...event, profile })
+
+ return true
+ }
+
+ private reconcileAmbiguousEvent(sessionId: string, epoch?: string): void {
+ const key = JSON.stringify([sessionId, epoch])
+
+ if (this.reconciledEpochs.has(key)) { return }
+ this.reconciledEpochs.add(key)
+
+ // A new/unknown replay epoch cannot choose between equal stored IDs. One
+ // authoritative snapshot per known owner recovers cards and establishes routes.
+ for (const profile of this.sessionProfiles.get(sessionId) ?? []) {
+ void this.request('session.resume', { session_id: sessionId, profile }).catch(() => undefined)
+ }
+ }
+
override async connect(wsUrl: string): Promise<void> {
+ this.connectionGeneration++
this.canonical = new URL(wsUrl).searchParams.has('native_dial')
this.attached.clear()
+ this.deliveredPrompts.clear()
+ this.sessionProfiles.clear()
+ this.profileAliases.clear()
+ this.replayProfiles.clear()
+ this.displayProfiles.clear()
+ this.reconciledEpochs.clear()
return super.connect(wsUrl)
}
@@ -146,34 +279,88 @@ export class HermesGateway extends JsonRpcGatewayClient {
// a redial) the new socket must resume before it may submit or respond.
private attached = new Set<string>()
+ private routeCanonicalParams(method: string, params: Record<string, unknown>): Record<string, unknown> {
+ if (method === 'session.events.since' && params.profile === undefined && typeof params.replay_epoch === 'string') {
+ const owner = this.replayProfiles.get(params.replay_epoch)
+
+ // The shared client's reconnect cursor predates the new socket's
+ // attachments. Never route an unknown old cursor to the launch profile.
+ if (!owner || owner.sessionId !== params.session_id) { throw new Error('Replay owner unavailable; reopen the session') }
+ params = { ...params, profile: owner.profile }
+ }
+
+ // Prompt callbacks carry session identity, while sibling sessions share the
+ // primary socket. Keep the route learned from their successful attachment.
+ const sid = params.session_id ?? params.parent_session_id
+
+ if (typeof sid === 'string' && params.profile !== undefined) {
+ params = { ...params, profile: this.resolveSessionProfile(sid, params.profile) }
+ }
+
+ const profiles = this.sessionProfiles.get(String(sid ?? ''))
+
+ if (params.profile === undefined && profiles?.size) {
+ if (profiles.size !== 1) { throw new Error('Session ID belongs to several profiles; select its owner profile before continuing') }
+ const profile = profiles.values().next().value!
+
+ if (profile !== 'default') { params = { ...params, profile } }
+ }
+
+ if (typeof sid === 'string' && ['session.resume', 'session.activate'].includes(method)) {
+ // Live frames may precede the attachment ACK. Register its explicit route
+ // before the await; concurrent equal-ID mounts are reconciled above.
+ this.rememberSessionProfile(sid, params.profile)
+ }
+
+ return params
+ }
+
override async request<T>(method: string, params: Record<string, unknown> = {}, timeoutMs?: number, signal?: AbortSignal): Promise<T> {
if (!this.canonical) { return super.request<T>(method, legacyParams(method, params), timeoutMs, signal) }
+ const generation = this.connectionGeneration
+ const deadline = Date.now() + (timeoutMs ?? DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS)
- // The card locks each question with `clarify.lock`; a canonical prompt is a single
- // question, so its one lock is the generation-fenced `clarify.respond` (null = skipped).
- const promptSession = method === 'clarify.lock' ? this.deliveredPrompts.get(String(params.request_id ?? '')) : undefined
+ // A question's owner is immutable even when a second profile attaches an
+ // equal stored session ID while the first card remains open.
+ const promptOwner = method === 'clarify.lock' ? this.deliveredPrompts.get(String(params.request_id ?? '')) : undefined
- if (promptSession) {
+ if (promptOwner) {
const answer = typeof params.answer === 'string' ? params.answer : ''
- return this.request<T>('clarify.respond', { session_id: promptSession, request_id: params.request_id, answer }, timeoutMs, signal)
+ return this.request<T>('clarify.respond', { session_id: promptOwner.sessionId, profile: promptOwner.profile, request_id: params.request_id, answer }, timeoutMs, signal)
}
- const route = this.sessionRoute(params)
- await this.attachForRequest(method, { ...params, ...route })
+ params = this.routeCanonicalParams(method, params)
+
+ await this.attachForRequest(method, params, deadline, signal)
+ this.requireConnectionGeneration(generation)
+ // The attach may have identified the named launch profile behind an
+ // implicit route. Its revision and generation are cached under that owner.
+ params = this.routeCanonicalParams(method, params)
- const prepared = this.protocol.prepare(method, params)
+ let prepared = this.protocol.prepare(method, params)
const wireMethod = this.protocol.wire(method, prepared)
try {
- const result = await super.request<T>(wireMethod, { ...prepared, ...route }, timeoutMs, signal)
+ const result = await super.request<T>(wireMethod, prepared, remainingRequestBudget(deadline, signal), signal)
+ this.requireConnectionGeneration(generation)
+
+ if (['session.resume', 'session.create', 'session.activate'].includes(method)) {
+ prepared = this.snapshotRoute(prepared, result)
+ }
// 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 followUp = (m: string, p: Record<string, unknown>) => {
+ this.requireConnectionGeneration(generation)
+
+ return this.request(m, p, remainingRequestBudget(deadline, signal), signal)
+ }
+
const settled = await this.protocol.settle(method, prepared, this.protocol.result(method, prepared, result), followUp) as T
+ this.requireConnectionGeneration(generation)
if (method === 'session.resume' || method === 'session.create' || method === 'session.activate') {
- this.adoptAttachedSnapshot(settled as { session_id?: string; prompts?: Array<Record<string, unknown>> }, route.profile)
+ this.adoptAttachedSnapshot(settled as { session_id?: string; prompts?: Array<Record<string, unknown>> }, prepared.profile)
}
return settled
@@ -183,55 +370,50 @@ 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 } : {}
+ private requireConnectionGeneration(generation: number): void {
+ if (generation !== this.connectionGeneration) { throw new Error('Hermes gateway connection changed; reopen the session') }
}
// 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> {
+ private async attachForRequest(method: string, params: Record<string, unknown>, deadline: number, signal?: AbortSignal): Promise<void> {
const sid = typeof params.session_id === 'string' ? params.session_id : null
- if (sid && ATTACH_REQUIRED.has(method) && !this.attached.has(sid)) {
- await this.request('session.resume', { session_id: sid, defer_history: true, omit_messages: true, ...(params.profile ? { profile: params.profile } : {}) })
+ const resume = (sessionId: string) => this.request('session.resume', {
+ session_id: sessionId, defer_history: true, omit_messages: true,
+ ...(params.profile ? { profile: params.profile } : {})
+ }, remainingRequestBudget(deadline, signal), signal)
+
+ if (sid && ATTACH_REQUIRED.has(method) && !this.attached.has(canonicalSessionKey(sid, params.profile))) {
+ await resume(sid)
}
const parent = PARENT_ATTACH_REQUIRED.has(method) ? params.parent_session_id ?? params.session_id : null
- if (typeof parent === 'string' && parent && !this.attached.has(parent)) {
- await this.request('session.resume', { session_id: parent, defer_history: true, omit_messages: true, ...(params.profile ? { profile: params.profile } : {}) })
+ if (typeof parent === 'string' && parent && !this.attached.has(canonicalSessionKey(parent, params.profile))) {
+ await resume(parent)
}
}
- private adoptAttachedSnapshot(settled: { session_id?: string; prompts?: Array<Record<string, unknown>> }, route?: string): void {
+ private adoptAttachedSnapshot(settled: { session_id?: string; replay_epoch?: string; info?: { profile_name?: string }; prompts?: Array<Record<string, unknown>> }, profile?: unknown): 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) }
+ if (sid) {
+ this.attached.add(canonicalSessionKey(sid, profile))
+ this.rememberSessionProfile(sid, profile)
- // A sibling create learns its session id only here.
- if (sid && route) { this.routes.set(sid, route) }
+ if (settled.info?.profile_name) {
+ this.displayProfiles.set(canonicalSessionKey(sid, profile), settled.info.profile_name)
+ }
+
+ if (typeof settled.replay_epoch === 'string') {
+ this.replayProfiles.set(settled.replay_epoch, { sessionId: sid, profile: canonicalProfile(profile) })
+ }
+ }
for (const prompt of (settled.prompts ?? [])) {
- this.deliverCanonicalPrompt({ type: `${prompt.kind}.request`, session_id: sid, payload: prompt }, true)
+ this.deliverCanonicalPrompt({ type: `${prompt.kind}.request`, session_id: sid, profile: canonicalProfile(profile), payload: prompt }, true)
}
}
@@ -262,10 +444,9 @@ export class HermesGateway extends JsonRpcGatewayClient {
})
this.onEvent(event => {
if (!this.canonical) { return }
- this.protocol.event(event)
if (event.type in CANONICAL_PROMPT_EVENTS) {
- this.deliverCanonicalPrompt(event, false)
+ this.deliverCanonicalPrompt({ ...event, profile: this.eventRoutes.get(event) }, false)
} else if (event.type.endsWith('.settled')) {
const id = (event.payload as { prompt_id?: unknown } | undefined)?.prompt_id
diff --git a/apps/desktop/src/app/gateway/gateway-event-dedupe.ts b/apps/desktop/src/app/gateway/gateway-event-dedupe.ts
index 2c45cd25a01..2fd8c71d425 100644
--- a/apps/desktop/src/app/gateway/gateway-event-dedupe.ts
+++ b/apps/desktop/src/app/gateway/gateway-event-dedupe.ts
@@ -46,9 +46,11 @@ export interface GatewayEventDedupe {
}
function sessionKey(event: GatewayEvent): string {
+ // Native authorities own a replay epoch per session/profile; equal stored
+ // IDs in different profile islands must never share a duplicate bucket.
// Before `gateway.ready` a socket has no epoch; bucket by connection so the
// pair still deduplicates within one backend URL.
- const epoch = event.replayEpoch ?? `conn:${event.connectionId ?? ''}`
+ const epoch = event.replay_epoch ?? event.replayEpoch ?? `conn:${event.connectionId ?? ''}`
return `${epoch}\u0000${event.session_id}`
}
diff --git a/apps/desktop/src/app/gateway/hooks/canonical-owner-routing.test.tsx b/apps/desktop/src/app/gateway/hooks/canonical-owner-routing.test.tsx
new file mode 100644
index 00000000000..dbd5b6a0097
--- /dev/null
+++ b/apps/desktop/src/app/gateway/hooks/canonical-owner-routing.test.tsx
@@ -0,0 +1,125 @@
+import { act, cleanup, render } from '@testing-library/react'
+import { afterEach, beforeEach, expect, test, vi } from 'vitest'
+
+import { activeGateway, closeSecondaryGateways } from '@/store/gateway'
+import { $activeGatewayProfile } from '@/store/profile'
+import { $connection, $gatewayState } from '@/store/session'
+import { clearAllSessionStates, runtimeSessionOwner } from '@/store/session-states'
+
+import { FakeWebSocket } from '../../../test/fake-gateway-socket'
+
+import { takeGatewaySurvivor } from './gateway-hmr-survivor'
+import { useGatewayBoot } from './use-gateway-boot'
+
+const sharedPrimaryConn = {
+ authMode: 'token' as const, baseUrl: 'http://127.0.0.1:8899', connectionId: '',
+ profile: 'default', sharedPrimary: true, token: 'fixture',
+ wsUrl: 'ws://127.0.0.1:8899/api/ws?native_dial=fixture&ticket=one-use'
+}
+
+const originalWebSocket = globalThis.WebSocket
+
+function fakeDesktop() {
+ return {
+ getConnection: vi.fn(async () => sharedPrimaryConn),
+ getGatewayWsUrl: vi.fn(async () => sharedPrimaryConn.wsUrl),
+ getBootProgress: vi.fn(async () => ({ error: null, fakeMode: false, message: '', phase: 'init',
+ progress: 0, retryable: false, running: true, timestamp: Date.now() })),
+ onBootProgress: vi.fn(() => () => undefined), onBackendExit: vi.fn(() => () => undefined),
+ onConnectionApplied: vi.fn(() => () => undefined), onPowerResume: vi.fn(() => () => undefined),
+ onWindowStateChanged: vi.fn(() => () => undefined),
+ revalidateConnection: vi.fn(async () => ({ ok: true, rebuilt: false })),
+ profile: { get: vi.fn(async () => ({ profile: 'default' })) }
+ }
+}
+
+function Harness({ handleGatewayEvent, handleServerRequest }: Pick<Parameters<typeof useGatewayBoot>[0], 'handleGatewayEvent' | 'handleServerRequest'>) {
+ useGatewayBoot({ handleGatewayEvent, handleServerRequest, beforeConnectionSwitch: () => undefined,
+ onConnectionReady: () => undefined, onGatewayReady: () => undefined,
+ refreshHermesConfig: async () => undefined, refreshSessions: async () => undefined })
+
+ return null
+}
+
+beforeEach(() => {
+ takeGatewaySurvivor()?.gateway.close()
+ closeSecondaryGateways()
+ clearAllSessionStates()
+ $activeGatewayProfile.set('default')
+ $connection.set(null)
+ vi.useFakeTimers()
+ FakeWebSocket.mode = 'open'
+ FakeWebSocket.instances = []
+ FakeWebSocket.pingMode = 'pong'
+ ;(globalThis as { WebSocket: unknown }).WebSocket = FakeWebSocket
+ $gatewayState.set('idle')
+})
+
+afterEach(() => {
+ cleanup()
+ takeGatewaySurvivor()?.gateway.close()
+ closeSecondaryGateways()
+ clearAllSessionStates()
+ $activeGatewayProfile.set('default')
+ $connection.set(null)
+ vi.useRealTimers()
+ ;(globalThis as { WebSocket: unknown }).WebSocket = originalWebSocket
+ delete (window as { hermesDesktop?: unknown }).hermesDesktop
+})
+
+async function flushAsync() {
+ await act(async () => { await vi.advanceTimersByTimeAsync(0) })
+}
+
+function deliverEvent(socket: FakeWebSocket, frame: Record<string, unknown>) {
+ ;(socket as unknown as { emit: (type: string, ev: unknown) => void }).emit('message', {
+ data: JSON.stringify({ jsonrpc: '2.0', method: 'event', params: frame })
+ })
+}
+
+test('keeps canonical alpha events and questions on alpha while beta is foreground', async () => {
+ const desktop = fakeDesktop()
+
+ const native = { ...sharedPrimaryConn, profile: 'default',
+ wsUrl: 'ws://127.0.0.1:8899/api/ws?native_dial=fixture&ticket=one-use' }
+
+ desktop.getConnection.mockResolvedValue(native)
+ desktop.getGatewayWsUrl.mockResolvedValue(native.wsUrl)
+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop
+ const events = vi.fn()
+ const questions = vi.fn((_request: unknown) => true)
+ render(<Harness handleGatewayEvent={events} handleServerRequest={questions} />)
+ await flushAsync()
+ const socket = FakeWebSocket.instances[0]
+
+ const emit = (data: object) => (socket as unknown as { emit: (type: string, ev: unknown) => void })
+ .emit('message', { data: JSON.stringify(data) })
+
+ const send = vi.spyOn(socket, 'send').mockImplementation(data => {
+ const frame = JSON.parse(data)
+ emit({ jsonrpc: '2.0', id: frame.id, result: frame.method === 'session.resume'
+ ? { session_id: 'rt-alpha', revision: 1, execution_generation: 2, replay_epoch: `${frame.params.profile}-epoch`, prompts: [] }
+ : { status: 'resolved' } })
+ })
+
+ try {
+ await act(async () => { await activeGateway()!.request('session.resume', { session_id: 'rt-alpha', profile: 'alpha' }) })
+ await act(async () => { await activeGateway()!.request('session.resume', { session_id: 'rt-alpha', profile: 'beta' }) })
+ act(() => { $activeGatewayProfile.set('beta') })
+ act(() => {
+ deliverEvent(socket, { session_id: 'rt-alpha', type: 'session.info', replay_epoch: 'beta-epoch', seq: 1,
+ payload: { revision: 2, execution_generation: 3 } })
+ deliverEvent(socket, { session_id: 'rt-alpha', type: 'session.info', replay_epoch: 'alpha-epoch', seq: 1,
+ payload: { revision: 2, execution_generation: 3 } })
+ deliverEvent(socket, { session_id: 'rt-alpha', type: 'approval.request', replay_epoch: 'alpha-epoch', seq: 2,
+ payload: { kind: 'approval', prompt_id: 'alpha-approval', execution_generation: 3, command: 'build', choices: ['once'] } })
+ })
+ expect(events.mock.calls.at(-1)?.[0]).toMatchObject({ profile: 'alpha', session_id: 'rt-alpha' })
+ expect(events.mock.calls.map(([event]) => event.profile)).toEqual(['beta', 'alpha', 'alpha'])
+ expect(runtimeSessionOwner('rt-alpha')).toBe('alpha')
+ expect(questions.mock.calls.at(-1)?.[0]).toMatchObject({ profile: 'alpha', id: 'alpha-approval' })
+ const question = questions.mock.calls.at(-1)?.[0] as unknown as { respond: (answer: object) => void }
+ await act(async () => { question.respond({ choice: 'once' }) })
+ expect(send.mock.calls.map(([data]) => JSON.parse(data)).find(frame => frame.method === 'approval.respond')?.params.profile).toBe('alpha')
+ } finally { send.mockRestore() }
+ })
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
index ea2f536b97d..4bf0dd8becf 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@ -9,6 +9,7 @@ import {
} from '@hermes/shared'
import { useEffect, useRef } from 'react'
+import { canonicalOwnerProfile } from '@/api/canonical-protocol'
import { createGatewayEventDedupe } from '@/app/gateway/gateway-event-dedupe'
import { reportStartupLatency } from '@/app/gateway/report-startup-latency'
import { shouldApplyPostBootProgressError } from '@/components/boot-failure-reauth'
@@ -1129,7 +1130,7 @@ export function useGatewayBoot({
const offEvent = gateway.onEvent(event => {
const connectionId = activeGatewayConnectionId()
- const sourceProfile = sourceProfileNow()
+ const sourceProfile = canonicalOwnerProfile(event) ?? sourceProfileNow()
const scopedEvent = {
...event,
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index b90ba753003..a5c1f582d5e 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -10,6 +10,7 @@ import {
} from '@hermes/shared'
import { atom } from 'nanostores'
+import { canonicalOwnerProfile } from '@/api/canonical-protocol'
import type { HermesConnection } from '@/global'
import { HermesGateway, setApiRequestConnection } from '@/hermes'
import { translateNow } from '@/i18n'
@@ -351,7 +352,7 @@ function dispatchServerRequest(request: ServerRequest, profile: string, connecti
return false
}
- g.config.onServerRequest({ ...request, ...(connectionId ? { connectionId } : {}), profile })
+ g.config.onServerRequest({ ...request, ...(connectionId ? { connectionId } : {}), profile: canonicalOwnerProfile(request) ?? profile })
return true
}
@@ -1062,12 +1063,11 @@ function createSecondary(profile: string, connectionId: null | string = null): S
activationLeaseUntil: 0
}
- // Events keep carrying the bare profile — session routing is profile-keyed
- // everywhere. A pool secondary with no registry connection has no exact
- // connection id, so stamp this closure-owned profile before registry fan-in;
- // the recorder must not promote an arbitrary wire `profile` field instead.
+ // Canonical adapters prove the owner from their attachment; legacy pooled
+ // sockets prove it through this closure. Stamp before registry fan-in,
+ // never promote an arbitrary wire `profile` field into ownership.
entry.offEvent = gateway.onEvent(event => {
- const scopedEvent = stampSecondaryProfileOwner({ ...event, ...(connectionId ? { connectionId } : {}) }, profile)
+ const scopedEvent = stampSecondaryProfileOwner({ ...event, ...(connectionId ? { connectionId } : {}) }, canonicalOwnerProfile(event) ?? profile)
g.config?.onEvent(scopedEvent)
releaseTerminalTurnLease(entry.scope, event)