The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): every Desktop producer fits the owner's closed contracts (class sweep)
Teknium5551a2c3422e
diff --git a/apps/desktop/src/api/canonical-producer-contract.test.ts b/apps/desktop/src/api/canonical-producer-contract.test.tsnew file mode 100644index 00000000000..c41de14c5e6--- /dev/null+++ b/apps/desktop/src/api/canonical-producer-contract.test.ts@@ -0,0 +1,239 @@+// @vitest-environment node+import { readFileSync } from 'node:fs'+import { join } from 'node:path'++import { expect, test } from 'vitest'++import { HermesGateway } from './client'++// Class sweep: every Desktop producer frame that reaches the shared owner must fit the closed+// (`additionalProperties: false`) canonical contract generated from tui_gateway/contracts. The+// fixture owner refuses exactly what `canonical_param_problems` refuses: unknown or missing keys.+interface Schema {+ properties: Record<string, unknown>+ required?: string[]+}++function canonicalContract(): Map<string, Schema> {+ const doc = JSON.parse(+ readFileSync(join(process.cwd(), '..', 'shared', 'src', 'gateway-contract.openrpc.json'), 'utf8')+ )++ const schemas = doc.components.schemas as Record<string, Schema>++ return new Map(+ (doc['x-canonical-methods'] as Array<{ name: string; params: Array<{ schema: { $ref: string } }> }>).map(method => [+ method.name,+ schemas[method.params[0].schema.$ref.split('/').at(-1)!]+ ])+ )+}++const CONTRACT = canonicalContract()++function problems(method: string, params: Record<string, unknown>): string[] {+ const schema = CONTRACT.get(method)++ if (!schema) {+ return []+ }++ return [+ ...Object.keys(params).filter(key => !(key in schema.properties)),+ ...(schema.required ?? []).filter(key => !(key in params))+ ]+}++const SNAPSHOT = {+ session_id: 's',+ stored_session_id: 's',+ revision: 4,+ execution_generation: 2,+ running: false,+ messages: [],+ prompts: []+}++function answer(frame: { method: string; params: Record<string, unknown> }): Record<string, unknown> {+ const p = frame.params++ if (frame.method === 'session.resume') {+ return SNAPSHOT+ }++ if (frame.method === 'session.mutate') {+ return { session_id: p.session_id, revision: 5, rewound_count: 2 }+ }++ if (frame.method === 'prompt.submit') {+ return {+ admission_id: p.submission_id,+ ref: { session_id: p.session_id },+ sequence: 1,+ status: 'queued',+ outcome: null,+ authority_epoch: 1,+ execution_generation: 2+ }+ }++ return { status: 'settled', delivery_id: p.id, value: 'x' }+}++// [label, Desktop method, exact producer params, expected: wire methods sent (after attach) or a named refusal]+const SITES: Array<[string, string, Record<string, unknown>, string[] | RegExp]> = [+ [+ 'hermes-bots/relay.ts relayDeliverParams',+ 'bot_relay.deliver',+ {+ id: 'e',+ profile: 'ops',+ message: 'Message from 🤖 S (@s): hi',+ from_profile: 's',+ from_handle: 's',+ from_connection: 'c'+ },+ ['bot_relay.deliver']+ ],+ [+ 'reasoning-slash.ts /reasoning --global',+ 'config.set',+ { key: 'reasoning', session_id: 's', value: 'high', scope: 'global' },+ /reasoning .*not available/+ ],+ [+ 'reasoning-step.ts keybind step',+ 'config.set',+ { key: 'reasoning', session_id: 's', value: 'high' },+ /reasoning is not available/+ ],+ ['model-presets.ts fast', 'config.set', { key: 'fast', session_id: 's', value: 'fast' }, /fast is not available/],+ [+ 'approval-mode.ts menu',+ 'config.set',+ { key: 'approvals.mode', value: 'manual', profile: 'default' },+ /approvals\.mode is not available/+ ],+ [+ 'voice-live.ts engine',+ 'config.set',+ { key: 'voice.voice_chat_mode', value: 'chained' },+ /voice\.voice_chat_mode is not available/+ ],+ [+ 'yolo-session.ts Shift+click zap',+ 'config.set',+ { key: 'yolo', scope: 'global', value: '1' },+ /yolo \(global\) is not available/+ ],+ ['yolo-session.ts session toggle', 'config.set', { key: 'yolo', session_id: 's', value: '1' }, ['config.set']],+ [+ 'session-tile-delegate / quick entry / bot chats (identityless)',+ 'prompt.submit',+ { session_id: 's', text: 'hi' },+ ['prompt.submit']+ ],+ [+ 'rewind.ts edit / regenerate / restore',+ 'prompt.submit',+ {+ session_id: 's',+ text: 'again',+ confirm_truncate: true,+ truncate_before_row_id: 9,+ confirm_empty_truncate: true,+ rebind_survivor_row_ids: [3]+ },+ ['session.mutate', 'prompt.submit']+ ],+ [+ 'use-prompt-actions /handoff',+ 'handoff.request',+ { session_id: 's', platform: 'telegram' },+ /handoff\.request is not available/+ ],+ ['use-prompt-actions handoff poll', 'handoff.state', { session_id: 's' }, /handoff\.state is not available/],+ [+ 'use-preview-routing restart',+ 'preview.restart',+ { session_id: 's', url: 'http://x' },+ /preview\.restart is not available/+ ],+ [+ 'connector-tool.tsx in-chat connect',+ 'connectors.connect',+ { connectors: ['gh'], owner: { session_id: 's', type: 'session' } },+ /connectors\.connect is not available/+ ],+ [+ 'connectors rpc.ts account connect',+ 'connectors.connect',+ { connectors: ['gh'], owner: { type: 'account' } },+ ['connectors.connect']+ ]+]++test.each(SITES)('%s: the canonical frame fits the generated contract', async (_label, method, params, expected) => {+ 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 fields = problems(frame.method, frame.params)+ const error = { code: 4001, message: 'invalid_params', data: { reason: 'invalid_params', fields } }+ socket.send(+ JSON.stringify(+ fields.length+ ? { jsonrpc: '2.0', id: frame.id, error }+ : { jsonrpc: '2.0', id: frame.id, result: answer(frame) }+ )+ )+ })+ })+ const client = new HermesGateway()++ 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`)+ const call = client.request(method, params)++ if (expected instanceof RegExp) {+ await expect(call).rejects.toThrow(expected)+ expect(sent.filter(frame => frame.method !== 'session.resume')).toEqual([])+ } else {+ await call+ expect(sent.map(frame => frame.method).filter(name => name !== 'session.resume')).toEqual(expected)+ expect(sent.map(frame => [frame.method, problems(frame.method, frame.params)])).toEqual(+ sent.map(frame => [frame.method, []])+ )+ }++ if (method === 'prompt.submit' && Array.isArray(expected)) {+ const submit = sent.at(-1).params+ expect(submit).toMatchObject({ session_id: 's', text: params.text })+ expect(typeof submit.submission_id).toBe('string')+ }++ if (Array.isArray(expected) && expected[0] === 'session.mutate') {+ expect(sent.find(frame => frame.method === 'session.mutate').params).toMatchObject({+ session_id: 's',+ operation: 'rewind',+ payload: { target_message_id: 9 },+ expected_revision: 4,+ expected_generation: 2+ })+ }+ } 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.tsindex ebc9725f777..400c8bca05d 100644--- a/apps/desktop/src/api/canonical-protocol.ts+++ b/apps/desktop/src/api/canonical-protocol.ts@@ -110,10 +110,60 @@ function canonicalBotDelivery(params: Record<string, unknown>): Record<string, ureturn { ...rest, message, author }}+// The legacy `prompt.submit` truncation keys (edit / regenerate / restore). The owner has no such+// keys: the cut is a revision-fenced `rewind` mutation on the user row, then a plain submit.+const TRUNCATE_KEYS = ['confirm_truncate', 'confirm_empty_truncate', 'truncate_before_row_id', 'truncate_before_message_id',+ 'truncate_before_user_ordinal', 'rebind_survivor_row_ids']++export function splitRewindSubmit(params: Record<string, unknown>): { rewind: Record<string, unknown> | null; submit: Record<string, unknown> } | null {+ if (!TRUNCATE_KEYS.some(key => key in params)) { return null }+ const row = params.truncate_before_row_id+ const submit = Object.fromEntries(Object.entries(params).filter(([key]) => !TRUNCATE_KEYS.includes(key)))++ if (typeof row === 'number' && Number.isInteger(row) && row > 0) {+ return { rewind: { session_id: params.session_id, target_message_id: row, ...(params.profile !== undefined ? { profile: params.profile } : {}) }, submit }+ }++ // Only a durable row id names the owner's cut; a message id or ordinal would be a guess.+ if (['truncate_before_row_id', 'truncate_before_message_id', 'truncate_before_user_ordinal'].some(key => key in params)) {+ throw new Error('This message is not saved yet; wait for it to settle, then edit it again')+ }++ return { rewind: null, submit }+}++// Session verbs only the legacy sidecar implements: it looks the session up in its own table,+// which never holds an owner session, and answers `session not found` (read by the renderer as a+// reaped runtime). Refused by name until the owner serves them.+const SIDECAR_SESSION_VERBS = new Set(['handoff.request', 'handoff.state', 'handoff.fail', 'preview.restart'])++// `config.set` keys the owner serves (tui_gateway/contracts/canonical_projections.py::CanonicalConfigSetParams).+const CANONICAL_CONFIG_KEYS = new Set(['busy', 'verbose', 'yolo', 'model'])++// The one guard between a Desktop producer and the owner's closed contracts: translate a legacy+// shape the owner has a canonical form for, refuse by name what it does not serve.+function canonicalProducerFrame(method: string, params: Record<string, unknown>): Record<string, unknown> {+ // No verb for other settings (reasoning, fast, approvals.mode, voice, display.*) nor a global+ // scope: refuse before the wire, like Ink, instead of a bare invalid_params.+ if (method === 'config.set' && (!CANONICAL_CONFIG_KEYS.has(String(params.key)) || 'scope' in params)) {+ throw new Error(`Changing ${params.key}${'scope' in params ? ` (${params.scope})` : ''} is not available on the shared gateway yet`)+ }++ if (SIDECAR_SESSION_VERBS.has(method) || (method.startsWith('connect') && (params.owner as { type?: unknown } | undefined)?.type === 'session')) {+ throw new Error(`${method} is not available on the shared gateway yet`)+ }++ // The owner admits identified input only. An identityless producer (session tile, quick entry,+ // bot chats) is a fresh send on every call, which is what the legacy wire did with it.+ if (method === 'prompt.submit' && !params.submission_id && !params.input_id) { return { ...params, submission_id: crypto.randomUUID() } }++ return method === 'bot_relay.deliver' ? canonicalBotDelivery(params) : params+}+const BRANCH_METHODS = new Set(['session.branch', 'session.branch_stored', 'session.branch_whole'])// Value-setting mutations: re-applying one is harmless, so a later acknowledged edit retires it.const VALUE_OPERATIONS = new Set(['rename', 'archive', 'model'])-const MUTATION_METHODS = new Set(['session.title', 'session.archive', 'session.compress', ...BRANCH_METHODS])+const MUTATION_METHODS = new Set(['session.title', 'session.archive', 'session.compress', 'session.rewind', ...BRANCH_METHODS])export class CanonicalDesktopProtocol {private creates = new Map<string, string>()@@ -142,7 +192,8 @@ export class CanonicalDesktopProtocol {// failure carries no reason; its outcome is unknown and the token stays for the exact retry.if (typeof reason === 'string') { this.settleModelConfirmation(params) }- if (reason !== 'revision_conflict') { return }+ // A typed busy refusal of a rewind wrote nothing either; the caller interrupts and retries at the new revision.+ if (reason !== 'revision_conflict' && !(reason === 'session_busy' && params.operation === 'rewind')) { return }// A confirmed CAS refusal did not mutate. Ambiguous transport failures keep// the original revision/id so a retry cannot overwrite another user's edit.@@ -221,11 +272,7 @@ export class CanonicalDesktopProtocol {if (method === 'approval.respond' || method === 'clarify.respond') { return this.preparePromptResponse(method, params) }- // The owner has no revision-fenced reasoning verb yet (`config.set` admits busy / verbose /- // yolo / model): refuse by name before the wire, like Ink, instead of a bare invalid_params.- if (method === 'config.set' && params.key === 'reasoning') { throw new Error('Changing reasoning is not available on the shared gateway yet') }-- return method === 'bot_relay.deliver' ? canonicalBotDelivery(params) : params+ return canonicalProducerFrame(method, params)}// Metadata, branch and typed slash directives that travel as canonical `session.mutate`; null otherwise.@@ -237,7 +284,8 @@ export class CanonicalDesktopProtocol {// Branch and compress fence the execution generation like the slash directives.const fenced = ({'session.branch': () => ({ operation: 'branch', payload: branchBoundary(params) }),- 'session.compress': () => ({ operation: 'compress', payload: params.focus_topic ? { focus: String(params.focus_topic) } : {} })+ 'session.compress': () => ({ operation: 'compress', payload: params.focus_topic ? { focus: String(params.focus_topic) } : {} }),+ 'session.rewind': () => ({ operation: 'rewind', payload: { target_message_id: params.target_message_id } })} as Record<string, () => { operation: string; payload: Record<string, unknown> }>)[method]?.()if (fenced) { return this.retainedMutation(params.session_id, params.profile, fenced.operation, fenced.payload, true) }diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.tsindex 13c79c35dfd..8255a4e8651 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, canonicalProfile, canonicalSessionKey, recordCanonicalOwner } from './canonical-protocol'+import { CANONICAL_GATEWAY_PROTOCOL, CanonicalDesktopProtocol, canonicalProfile, canonicalSessionKey, recordCanonicalOwner, splitRewindSubmit } 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@@ -43,7 +43,7 @@ export const GATEWAY_NOT_CONNECTED_MESSAGE = 'Hermes gateway is not connected'// the same `onRequest` registry as a request whose `respond` issues the RPC.const CANONICAL_PROMPT_EVENTS: Record<string, 'approval' | 'clarify'> = { 'approval.request': 'approval', 'clarify.request': 'clarify' }-const ATTACH_REQUIRED = new Set(['prompt.submit', 'approval.respond', 'clarify.respond', 'session.interrupt', 'prompt.cancel'])+const ATTACH_REQUIRED = new Set(['prompt.submit', 'approval.respond', 'clarify.respond', 'session.interrupt', 'prompt.cancel', 'session.rewind'])// A branch is a CAS mutation on the PARENT: an un-attached parent (right-click on a sidebar row// that was never opened) has no cached revision, so attach it first to learn one.const PARENT_ATTACH_REQUIRED = new Set(['session.branch_stored', 'session.branch_whole'])@@ -324,6 +324,14 @@ export class HermesGateway extends JsonRpcGatewayClient {if (!this.canonical) { return super.request<T>(method, legacyParams(method, params), timeoutMs, signal) }const generation = this.connectionGenerationconst deadline = Date.now() + (timeoutMs ?? DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS)+ // A truncating submit (edit / regenerate / restore) is the owner's rewind, then the submit.+ const rewind = method === 'prompt.submit' ? splitRewindSubmit(params) : null++ if (rewind) {+ if (rewind.rewind) { await this.request('session.rewind', rewind.rewind, remainingRequestBudget(deadline, signal), signal) }++ return this.request<T>('prompt.submit', rewind.submit, remainingRequestBudget(deadline, signal), signal)+ }// A question's owner is immutable even when a second profile attaches an// equal stored session ID while the first card remains open.diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.tsindex f544371755c..a2708c6ed7c 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts@@ -281,7 +281,8 @@ export const SESSION_BUSY_RETRY_TIMEOUT_MS = 6_000export const SESSION_BUSY_RETRY_INTERVAL_MS = 150export function isSessionBusyError(error: unknown): boolean {- return /session busy/i.test(error instanceof Error ? error.message : String(error))+ // The shared owner answers its typed reason (`session_busy`), the legacy sidecar prose.+ return /session[ _]busy/i.test(error instanceof Error ? error.message : String(error))}// prompt.submit refused because another surface (TUI, messaging gateway)diff --git a/gateway/session_ancillary.py b/gateway/session_ancillary.pyindex 48ea479e683..d5320b9b150 100644--- a/gateway/session_ancillary.py+++ b/gateway/session_ancillary.py@@ -2,7 +2,7 @@No legacy server, manager construction, process recovery, or execution on reads. ``process.stop``and ``process.kill`` stop only processes ``process.list`` projects for the session; ``reload.mcp``-reconciles only the requesting profile's MCP servers.+reconciles only the requesting profile's MCP servers; ``file.attach`` stages for one owned session."""import asynciofrom functools import partial@@ -26,7 +26,40 @@ def handlers(connection):}.items()}, 'approval.pending': partial(approvals, connection),'approval.received': partial(approvals, connection, ack=True),'process.stop': partial(stop_processes, connection),- 'process.kill': partial(kill_process, connection), 'reload.mcp': partial(reload_mcp, connection)}+ 'process.kill': partial(kill_process, connection), 'reload.mcp': partial(reload_mcp, connection),+ 'file.attach': partial(attach_file, connection)}+++async def attach_file(connection, ref, params):+ """Desktop's non-image attachment: stage the file for this session (its frozen launch cwd and+ the owner profile's ``attachments/``) and hand back the ``@file:`` ref its next submit carries.+ The sidecar handler looked the session up in its own table, which never holds an authority+ session, so every file drop failed with ``session not found``."""+ if (set(params) - {'session_id', 'profile', 'path', 'data_url', 'name'} or not ref.session_id+ or any(not isinstance(value, str) for value in params.values())):+ raise RuntimeStoreError('invalid_params')+ if ref.session_id not in connection.subscriptions:+ raise RuntimeStoreError('permission_denied')+ authorize(connection, ref, params, 'session:submit')+ from gateway.session_policy import policy_for_source+ authority = connection.authority+ policy = policy_for_source(authority.runner, authority.sessions[ref.session_id].source)+ if policy is None:+ raise RuntimeStoreError('permission_denied')+ # The staging helpers are bound onto the sidecar module's globals (method_ctx.bind_module).+ from tui_gateway import server+ session = {'cwd': policy.cwd, 'profile_home': authority.profile_id}+ try:+ stored, uploaded = await asyncio.to_thread(+ server._stage_session_file_attachment, session, raw_path=params.get('path', ''),+ data_url=params.get('data_url', ''), name=params.get('name', ''))+ except ValueError as exc:+ raise RuntimeStoreError('invalid_params') from exc+ except OSError as exc:+ raise RuntimeStoreError('storage_unavailable') from exc+ ref_path = server._attachment_ref_path(session, stored)+ return {'attached': True, 'name': stored.name, 'path': str(stored), 'ref_path': ref_path,+ 'ref_text': f'@file:{server._format_ref_value(ref_path)}', 'uploaded': uploaded}async def approvals(connection, ref, params, *, ack=False):diff --git a/tests/gateway/fixtures/desktop_process_verbs_peer.py b/tests/gateway/fixtures/desktop_process_verbs_peer.pyindex d47ac605b6a..398a0effece 100644--- a/tests/gateway/fixtures/desktop_process_verbs_peer.py+++ b/tests/gateway/fixtures/desktop_process_verbs_peer.py@@ -48,6 +48,13 @@ async def probe():# use-mcp-servers.ts / mcp.ts / repair.ts.reload = await rpc(ws, 'reload.mcp', confirm=True, session_id=sid)receipt['reload_mcp'] = reload.get('result', {}).get('status', reload.get('error'))+ # use-prompt-actions/index.ts: a non-image drop, by path and by bytes (remote backend).+ (home / 'note.txt').write_text('hello')+ by_path = await rpc(ws, 'file.attach', name='note.txt', path=str(home / 'note.txt'), session_id=sid)+ by_bytes = await rpc(ws, 'file.attach', name='n.txt', path='C:/x/n.txt', data_url='data:text/plain;base64,aGk=',+ session_id=sid)+ receipt['file_attach'] = [r.get('result', {}).get('ref_text', r.get('error')) for r in (by_path, by_bytes)]+ receipt['staged'] = sorted(p.read_text() for p in (home / 'attachments').iterdir())finally:for proc in processes:if not proc.exited:diff --git a/tests/gateway/test_desktop_process_verbs.py b/tests/gateway/test_desktop_process_verbs.pyindex 0704b18b0d7..e79b3f3d9d1 100644--- a/tests/gateway/test_desktop_process_verbs.py+++ b/tests/gateway/test_desktop_process_verbs.py@@ -1,4 +1,4 @@-"""Desktop's /stop, per-process Stop and MCP reload are served by the shared owner (dokterdok N27)."""+"""Desktop's /stop, per-process Stop, MCP reload and file attach are served by the shared owner (dokterdok N27)."""import jsonfrom pathlib import Pathimport subprocess@@ -27,3 +27,6 @@ def test_desktop_process_kill_stop_and_mcp_reload_reach_only_this_session(tmp_paassert receipt['stop'] == {'killed': 1}, receiptassert receipt['exited'] == [True, True, False], receiptassert receipt['reload_mcp'] == 'reloaded', receipt+ # file.attach: the sidecar answered ``session not found`` for every authority session.+ assert [ref.startswith('@file:') for ref in receipt['file_attach']] == [True, True], receipt+ assert receipt['staged'] == ['hello', 'hi'], receipt