Skip to content

The agent that grows with you

fix(desktop): legacy backends and branches work again on the canonical client

teknium155c76ab3fc78
diff --git a/apps/desktop/src/api/canonical-protocol-wire.test.ts b/apps/desktop/src/api/canonical-protocol-wire.test.ts
index 5632048afb9..d2a7cdb636d 100644
--- a/apps/desktop/src/api/canonical-protocol-wire.test.ts
+++ b/apps/desktop/src/api/canonical-protocol-wire.test.ts
@@ -37,3 +37,36 @@ test('named canonical prompt listeners receive replay-safe IDs before answering
await new Promise<void>(resolve => server.close(() => resolve()))
}
})
+
+test('a legacy (non-canonical) dial strips canonical-only identity keys the serve contract refuses', async () => {
+ // `hermes serve` answers 4000 "out of sync" for an unknown key, which the remote-topology E2E
+ // surfaced as a permanent "Session unavailable" on a URL+token connection.
+ 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)
+ socket.send(JSON.stringify({ jsonrpc: '2.0', id: frame.id, result: { session_id: 'abc' } }))
+ })
+ })
+ const client = new HermesGateway()
+
+ try {
+ const address = server.address() as { port: number }
+ await client.connect(`ws://127.0.0.1:${address.port}/api/ws?ticket=legacy`)
+ await client.request('session.create', { cols: 96, source: 'desktop', cwd: '/x', fast: false, request_id: 'r1' })
+ expect(sent.at(-1).params).toEqual({ cols: 96, source: 'desktop', cwd: '/x', fast: false })
+ await client.request('session.branch_stored', { cols: 96, source: 'desktop', parent_session_id: 'p', request_id: 'r2' })
+ expect(sent.at(-1).method).toBe('session.branch_stored')
+ expect(sent.at(-1).params).not.toHaveProperty('request_id')
+ } 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.test.ts b/apps/desktop/src/api/canonical-protocol.test.ts
index 225928a7ee7..6c198e02889 100644
--- a/apps/desktop/src/api/canonical-protocol.test.ts
+++ b/apps/desktop/src/api/canonical-protocol.test.ts
@@ -74,6 +74,18 @@ test('pending resume and live updates share the existing queue projection', () =
expect(cleared.payload).toHaveProperty('pending_submissions', [])
})
+test('a stored-parent branch travels as the canonical branch mutation on the parent', () => {
+ // A legacy `session.branch_stored` mints a child the authority cannot restore (no local
+ // policy), so every resume on it answers not_found and the first submit never leaves.
+ const protocol = new CanonicalDesktopProtocol()
+ protocol.result('session.resume', { session_id: 'p' }, { session_id: 'p', revision: 3, execution_generation: 1 })
+ const prepared = protocol.prepare('session.branch_stored', { cols: 96, source: 'desktop', parent_session_id: 'p', profile: 'default' })
+ expect(protocol.wire('session.branch_stored', prepared)).toBe('session.mutate')
+ expect(prepared).toMatchObject({ session_id: 'p', operation: 'branch', payload: {}, expected_revision: 3, expected_generation: 1 })
+ const child = protocol.result('session.branch_stored', prepared, { session_id: 'p', revision: 4, operation: 'branch', branched_session_id: 'c', copied_messages: 4 })
+ expect(child).toMatchObject({ session_id: 'c', stored_session_id: 'c', parent_session_id: 'p', message_count: 4 })
+})
+
test('composer branch and model switch become canonical prepared mutations with identity retained', () => {
const protocol = new CanonicalDesktopProtocol()
protocol.result('session.resume', { session_id: 's' }, { session_id: 's', revision: 4, execution_generation: 9 })
diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.ts
index dd295b88453..324e7c6c085 100644
--- a/apps/desktop/src/api/canonical-protocol.ts
+++ b/apps/desktop/src/api/canonical-protocol.ts
@@ -38,7 +38,12 @@ function mutationSummary(operation: string, value: Record<string, unknown>): str
}
// Explicit desktop methods that travel as canonical `session.mutate`.
-const MUTATION_METHODS = new Set(['session.title', 'session.archive', 'session.branch', 'session.compress'])
+// `session.branch_stored` / `session.branch_whole` are legacy whole-history branches keyed by a
+// 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).
+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])
export class CanonicalDesktopProtocol {
private creates = new Map<string, string>()
@@ -106,6 +111,14 @@ export class CanonicalDesktopProtocol {
if (fenced) { return this.retainedMutation(params.session_id, 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)
+ }
+
if (method === 'slash.exec') {
const directive = slashMutation(String(params.command ?? ''))
@@ -117,9 +130,11 @@ export class CanonicalDesktopProtocol {
const unsupported = Object.keys(params).filter(key => !allowed.has(key) && !(key === 'fast' && params[key] === false))
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')))
+
const key = JSON.stringify(result)
const requestId = params.request_id ?? this.creates.get(key) ?? crypto.randomUUID()
this.creates.set(key, String(requestId))
@@ -217,7 +232,7 @@ export class CanonicalDesktopProtocol {
for (const [key, mutation] of this.mutations) { if (mutation.request_id === params.request_id) { this.mutations.delete(key) } }
- if (method === 'session.branch') {
+ if (BRANCH_METHODS.has(method)) {
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 }
}
diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.ts
index e31fcfe6a6d..bbc0044e590 100644
--- a/apps/desktop/src/api/client.ts
+++ b/apps/desktop/src/api/client.ts
@@ -37,6 +37,23 @@ export const GATEWAY_NOT_CONNECTED_MESSAGE = 'Hermes gateway is not connected'
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'])
+// 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'])
+
+// Canonical-only identity keys. The legacy `hermes serve` contract refuses an unknown key as
+// version skew (4000), so they are stripped on a non-canonical dial. `prompt.submit` keeps its
+// `submission_id` on purpose: the submit path retries identityless on that exact refusal and
+// records the send as legacy-attempted, which a silent strip here would hide.
+const LEGACY_STRIP: Record<string, string[]> = { 'session.create': ['request_id'], 'session.branch_stored': ['request_id'] }
+
+function legacyParams(method: string, params: Record<string, unknown>): Record<string, unknown> {
+ const strip = LEGACY_STRIP[method]
+
+ if (!strip || !strip.some(key => key in params)) { return params }
+
+ return Object.fromEntries(Object.entries(params).filter(([key]) => !strip.includes(key)))
+}
export class HermesGateway extends JsonRpcGatewayClient {
private canonical = false
@@ -114,12 +131,19 @@ export class HermesGateway extends JsonRpcGatewayClient {
private attached = new Set<string>()
override async request<T>(method: string, params: Record<string, unknown> = {}, timeoutMs?: number, signal?: AbortSignal): Promise<T> {
- if (!this.canonical) { return super.request<T>(method, params, timeoutMs, signal) }
+ if (!this.canonical) { return super.request<T>(method, legacyParams(method, params), timeoutMs, signal) }
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 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 } : {}) })
+ }
+
const prepared = this.protocol.prepare(method, params)
const wireMethod = this.protocol.wire(method, prepared)
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx
index 51ba33aef29..98175f2fd12 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx
@@ -377,6 +377,32 @@ describe('durable submit acknowledgement', () => {
expect.any(Number)
)
})
+
+ it('a legacy backend refusing submission_id as version skew (4000) gets one identityless retry', async () => {
+ // `hermes serve` validates params against a strict contract: an unknown key is refused
+ // as 4000 before any handler ran (surfaced by the remote-topology E2E as "Session unavailable").
+ const submits: Array<Record<string, unknown>> = []
+
+ const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) => {
+ if (method !== 'prompt.submit') {return {} as never}
+ submits.push(params!)
+
+ if ('submission_id' in params!) {
+ throw Object.assign(new Error('invalid params for prompt.submit: submission_id: Extra inputs are not permitted — the client and the Hermes backend are out of sync (different versions)'), { code: 4000 })
+ }
+
+ return { status: 'streaming' } as never
+ })
+
+ let handle: HarnessHandle | null = null
+ await actRender(
+ <Harness onReady={h => (handle = h)} rawAdmissionReceipts refreshSessions={async () => undefined} requestGateway={requestGateway} />
+ )
+ expect(await handle!.submitText('hi remote')).toBe(true)
+ expect(submits).toHaveLength(2)
+ expect(submits[1]).not.toHaveProperty('submission_id')
+ expect(submits[1]).toMatchObject({ text: 'hi remote' })
+ })
})
describe('submit timeout admission fences', () => {
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
index 662662cbc31..e443d20a242 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
@@ -119,6 +119,14 @@ type SubmitReceipt = Pick<PromptSubmitResult, 'user_row_id'> & {
status?: string
}
+/** A refusal the backend issued before admitting anything, so an identityless retry cannot duplicate a turn. */
+function isPreAdmissionRefusal(error: unknown): boolean {
+ if (!error || typeof error !== 'object' || !('code' in error)) { return false }
+ const { code, message } = error as { code?: unknown; message?: unknown }
+
+ return code === 4094 || (code === 4000 && typeof message === 'string' && /submission_id/.test(message))
+}
+
export function useSubmitPrompt(deps: SubmitPromptDeps) {
const {
activeSessionIdRef,
@@ -931,9 +939,12 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
'prompt.submit', params, PROMPT_SUBMIT_REQUEST_TIMEOUT_MS
)
} catch (error) {
- // 4094 is an explicit PRE-admission capability refusal. Never
- // downgrade on a timeout, malformed ACK or an ambiguous retry.
- if (!error || typeof error !== 'object' || !('code' in error) || error.code !== 4094 || prepared.legacyAttempted) {
+ // 4094 is an explicit PRE-admission capability refusal; 4000 is the
+ // legacy `hermes serve` contract refusing `submission_id` as an unknown
+ // key (version skew) before any handler ran. Both are pre-admission and
+ // safe to retry identityless. Never downgrade on a timeout, malformed
+ // ACK or an ambiguous retry.
+ if (!isPreAdmissionRefusal(error) || prepared.legacyAttempted) {
throw error
}
diff --git a/hermes_state_mutation_branch.py b/hermes_state_mutation_branch.py
index 52194702e9a..7788496e2fc 100644
--- a/hermes_state_mutation_branch.py
+++ b/hermes_state_mutation_branch.py
@@ -7,6 +7,7 @@ from hermes_state_local import POLICY_PREFIX
from hermes_state_local_lineage import validate_local_lineage
from hermes_state_mutation_guards import require_idle
from hermes_state_runtime import RuntimeStoreError, _json
+from hermes_state_titles import lineage_title_on_conn
def branch_in_transaction(db, conn, session_id, payload):
@@ -41,6 +42,11 @@ def branch_in_transaction(db, conn, session_id, payload):
conn.execute('UPDATE sessions SET message_count=?,tool_call_count=? WHERE id=?', (len(ids), tools, child))
if payload.get('title'):
db._set_session_title_in_transaction(conn, child, payload['title'], source=db.TITLE_SOURCE_USER)
+ else:
+ # Untitled branch: the next name in the parent's lineage ("my session" → "my session #2"),
+ # same rule as the legacy TUI /branch, so the child is its own titled sidebar row.
+ db._set_session_title_in_transaction(conn, child, lineage_title_on_conn(conn, parent['title'] or 'branch'),
+ source=db.TITLE_SOURCE_DERIVED)
receipt = dict(profile_id=saved['profile_id'], principal_id=saved['principal_id'],
request_id=request_id, session_id=child, route=route, entry=entry.to_dict(), policy=policy)
conn.execute("INSERT INTO gateway_routing(scope,session_key,entry_json,updated_at) VALUES('',?,?,?)",
diff --git a/hermes_state_titles.py b/hermes_state_titles.py
index 4c19e9d9651..11faff4c80f 100644
--- a/hermes_state_titles.py
+++ b/hermes_state_titles.py
@@ -193,13 +193,26 @@ class SessionTitlesMixin:
def get_next_title_in_lineage(self, base_title: str) -> str:
"""Next title in a lineage ("my session" -> "my session #2"): strip any " #N" suffix,
then increment the highest existing number."""
- match = _NUMBERED_TITLE_RE.match(base_title)
- base = match.group(1) if match else base_title
- rows = self._read_all(
- "SELECT title FROM sessions WHERE title = ? OR title LIKE ? ESCAPE '\\'",
- (base, f"{_escape_like(base)} #%"))
- if not rows:
- return base
- # The unnumbered original counts as #1.
- numbers = [int(m.group(2)) for m in (_NUMBERED_TITLE_RE.match(row["title"]) for row in rows) if m]
- return f"{base} #{max([1, *numbers]) + 1}"
+ base, sql, args = _lineage_title_query(base_title)
+ return _next_lineage_title(base, self._read_all(sql, args))
+
+
+def _lineage_title_query(base_title: str):
+ match = _NUMBERED_TITLE_RE.match(base_title)
+ base = match.group(1) if match else base_title
+ return base, "SELECT title FROM sessions WHERE title = ? OR title LIKE ? ESCAPE '\\'", (base, f"{_escape_like(base)} #%")
+
+
+def _next_lineage_title(base: str, rows) -> str:
+ if not rows:
+ return base
+ # The unnumbered original counts as #1.
+ numbers = [int(m.group(2)) for m in (_NUMBERED_TITLE_RE.match(row["title"]) for row in rows) if m]
+ return f"{base} #{max([1, *numbers]) + 1}"
+
+
+def lineage_title_on_conn(conn, base_title: str) -> str:
+ """``get_next_title_in_lineage`` inside an authority-owned transaction (same connection, so a
+ sibling branch committed in this transaction is counted)."""
+ base, sql, args = _lineage_title_query(base_title)
+ return _next_lineage_title(base, conn.execute(sql, args).fetchall())
diff --git a/tests/gateway/test_session_mutation_branch.py b/tests/gateway/test_session_mutation_branch.py
index 6ad46290223..e50007bda0d 100644
--- a/tests/gateway/test_session_mutation_branch.py
+++ b/tests/gateway/test_session_mutation_branch.py
@@ -59,5 +59,7 @@ def test_branch_route_and_frozen_policy_survive_owner_restart(tmp_path):
assert policies[0]['principal_id'] == policies[1]['principal_id']
assert policies[0]['route'] != policies[1]['route']
assert db.execute('SELECT parent_session_id FROM sessions WHERE id=?', (child,)).fetchone()[0] == sid
+ # An untitled branch is its own titled sidebar row (next name in the parent's lineage).
+ assert db.execute('SELECT title FROM sessions WHERE id=?', (child,)).fetchone()[0]
with daemon(tmp_path) as (home, descriptor):
assert asyncio.run(branch_round(home, descriptor, previous)) == previous
diff --git a/tests/tui_gateway/test_profile_db_readonly.py b/tests/tui_gateway/test_profile_db_readonly.py
index 016c005639d..64f7836bd9a 100644
--- a/tests/tui_gateway/test_profile_db_readonly.py
+++ b/tests/tui_gateway/test_profile_db_readonly.py
@@ -39,6 +39,19 @@ def test_foreign_profile_db_is_read_only(monkeypatch, tmp_path):
assert db.get_session("seed") is not None
+def test_fresh_served_profile_store_is_seeded_for_its_first_read(monkeypatch, tmp_path):
+ """A brand-new bot's first RPC is the Bot Chat registry lookup (session.list by title). Its
+ state.db does not exist yet; the serving process owns that store, so the read seeds it instead
+ of answering storage_unavailable until a turn happens to run (#120730 remote-secondary E2E)."""
+ fresh = tmp_path / "profiles" / "newbot"
+ fresh.mkdir(parents=True)
+ monkeypatch.setattr(server, "_profile_home", lambda name: fresh if (name or "").strip() == "newbot" else None)
+ with server._profile_db({"profile": "newbot"}) as db:
+ assert db is not None and db.read_only is True
+ assert db.get_session_by_title("Bot Chat") is None
+ assert (fresh / "state.db").stat().st_size > 0
+
+
def test_foreign_profile_db_writer_opt_in(monkeypatch, tmp_path):
_bind_foreign(monkeypatch, tmp_path)
with server._profile_db({"profile": "code"}, writer=True) as db:
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 0440efccb5f..dc94f62b3f7 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -441,6 +441,20 @@ def _open_profile_session_db(profile_home):
raise RuntimeError(f"profile session store unavailable: {db_path}: {exc}") from exc
+def _bootstrap_served_profile_store(db_path: Path) -> None:
+ """A served profile whose first RPC is a read (Bot Chat registry lookup on a fresh bot) has no
+ ``state.db`` yet. Browsing never creates a store, but THIS process is the profile's session
+ owner (``_open_profile_session_db`` acquires the writer for every agent build), so it seeds the
+ store it is about to own instead of answering ``storage_unavailable`` until a turn happens."""
+ try:
+ if db_path.stat().st_size > 0:
+ return
+ except FileNotFoundError:
+ pass
+ from hermes_state_registry import acquire, release_or_close
+ release_or_close(acquire(db_path))
+
+
@contextlib.contextmanager
def _profile_db(params: dict | None = None, *, writer: bool = False):
"""Yield the SessionDB for ``params['profile']`` (None when unavailable); closes dedicated
@@ -461,6 +475,7 @@ def _profile_db(params: dict | None = None, *, writer: bool = False):
db = acquire(Path(profile_home) / "state.db")
else:
from hermes_cli.web_server_sessions import _open_session_db_at_path
+ _bootstrap_served_profile_store(Path(profile_home) / "state.db")
db = _open_session_db_at_path(Path(profile_home) / "state.db", read_only=True)
owns = True
except Exception as exc:
diff --git a/ui-tui/src/app/submissionCore.ts b/ui-tui/src/app/submissionCore.ts
index ae9752a9116..3f07ddab3d1 100644
--- a/ui-tui/src/app/submissionCore.ts
+++ b/ui-tui/src/app/submissionCore.ts
@@ -202,10 +202,13 @@ export function submitPrompt(
}
})
.catch(async (e: Error & { code?: number }) => {
- // 4094 is a pre-admission refusal, not an ambiguous write. Special
- // compute modes still support legacy submit; retry only this refusal,
+ // 4094 is a pre-admission refusal, not an ambiguous write; so is 4000 when the
+ // legacy `hermes serve` contract refuses `submission_id` as an unknown key. Special
+ // compute modes still support legacy submit; retry only these refusals,
// keeping the prepared payload, destination and queue mode unchanged.
- if (item && e.code === 4094 && !deps.gw.isCanonical && !item.attachments?.length) {
+ const preAdmissionRefusal = e.code === 4094 || (e.code === 4000 && /submission_id/.test(e.message ?? ''))
+
+ if (item && preAdmissionRefusal && !deps.gw.isCanonical && !item.attachments?.length) {
if (focused()) {deps.sys('durable admission unavailable for this session — using legacy delivery')}
try {