The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): serve parked-session reads and attach before a stale restart finishes
Tekniumf7027c73d8d4
diff --git a/apps/desktop/electron/local-gateway-stale-restart-owner.test.ts b/apps/desktop/electron/local-gateway-stale-restart-owner.test.tsindex 84300510392..c461b28329c 100644--- a/apps/desktop/electron/local-gateway-stale-restart-owner.test.ts+++ b/apps/desktop/electron/local-gateway-stale-restart-owner.test.ts@@ -12,9 +12,9 @@ test('a second owner on the same stale code is restarted, while a served siblingconst owner = (profile_id: string, control_home: null | string = null) =>({ profile_id, control_home, instance_id: 'i', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1', capabilities: [], supervisor: 'none' })- expect(await restart(owner('/h'), stale)).toBe(true)- expect(await restart(owner('/h/profiles/work'), stale)).toBe(true)+ expect(await restart(owner('/h'), stale)).not.toBeNull()+ expect(await restart(owner('/h/profiles/work'), stale)).not.toBeNull()// A served secondary lives in the multiplexer already restarted above: no second restart.- expect(await restart(owner('/h/profiles/ops', '/h'), stale)).toBe(false)+ expect(await restart(owner('/h/profiles/ops', '/h'), stale)).toBeNull()expect(restarted).toEqual(['default', 'work'])})diff --git a/apps/desktop/electron/local-gateway.test.ts b/apps/desktop/electron/local-gateway.test.tsindex 9df8fd3c107..26cdec84c7f 100644--- a/apps/desktop/electron/local-gateway.test.ts+++ b/apps/desktop/electron/local-gateway.test.ts@@ -152,7 +152,7 @@ test('ensure consumes structured readiness without acquiring a child owner', asytest('a restart-wait owner is attached to answer a parked prompt; a plain drain stays refused (#139041)', async () => {const endpoint = { profile_id: '/private/profile', instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none', code_sha: 'old' }- const restartStale = vi.fn(async () => true)+ const restartStale = vi.fn(async () => ({ done: Promise.resolve() }))const wait = { code: 6, stdout: JSON.stringify({ state: 'draining', reason_code: 'restart_wait', endpoint, client_code_sha: 'new' }) }const connection = await ensureLocalGateway(async () => wait, undefined, restartStale)expect(connection.gatewayEndpoint).toEqual(endpoint)@@ -160,6 +160,27 @@ test('a restart-wait owner is attached to answer a parked prompt; a plain drainawait expect(ensureLocalGateway(async () => ({ code: 6, stdout: JSON.stringify({ state: 'draining', reason_code: 'update_paused', endpoint: null }) }))).rejects.toThrow('Gateway draining (update_paused)')})+test('a stale owner this window restarts is attached in its restart wait before the restart finishes (#139041)', async () => {+ // `hermes gateway restart` waits for the old owner to exit; a turn parked on approval/clarify+ // there waits for an answer only this window can give. Awaiting the restart first deadlocked both.+ const { createStaleGatewayRestarter } = await import('./local-gateway')+ const endpoint = { profile_id: '/h', instance_id: 'old', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none', code_sha: 'old' }+ let finishRestart = () => {}+ const restarted: string[] = []+ const restartStale = createStaleGatewayRestarter(owner => { restarted.push(owner)++ return new Promise<void>(resolve => { finishRestart = resolve }) }, () => undefined)+ const answers = [+ { code: 0, stdout: JSON.stringify({ state: 'ready', endpoint, client_code_sha: 'new' }) },+ { code: 6, stdout: JSON.stringify({ state: 'draining', reason_code: 'restart_wait', endpoint, client_code_sha: 'new' }) }+ ]+ const attached = ensureLocalGateway(async () => answers.shift()!, undefined, restartStale)+ const outcome = await Promise.race([attached, new Promise(resolve => setTimeout(() => resolve('blocked on the restart'), 500))])+ finishRestart()+ expect(outcome).toMatchObject({ gatewayEndpoint: { instance_id: 'old' } })+ expect(restarted).toEqual(['default'])+})+test('an ensure child that never reached the protocol boundary is diagnosed from stderr, not as a JSON parse error', async () => {// `main`'s hermes has no `gateway ensure` subcommand: argparse usage on stderr, nothing on stdout.const legacy = { code: 2, stdout: '', stderr: "usage: hermes gateway [-h] ...\nhermes gateway: 'ensure' is not a `hermes gateway` command.\nRun `hermes gateway --help` to see all commands.\n" }diff --git a/apps/desktop/electron/local-gateway.ts b/apps/desktop/electron/local-gateway.tsindex d865bb5d23a..0d69d183153 100644--- a/apps/desktop/electron/local-gateway.ts+++ b/apps/desktop/electron/local-gateway.ts@@ -71,8 +71,11 @@ export interface GatewayEndpoint {code_sha?: string | null}-/** Restarts a ready owner whose code differs from this client's; true when a restart was requested. */-export type StaleGatewayRestart = (endpoint: GatewayEndpoint, stale: { gateway: string; client: string }) => Promise<boolean>+/** Requests a restart of a ready owner whose code differs from this client's. Resolves as soon as the+ * restart is requested: `{ done }` settles when the restart client exits; null when none was requested.+ * Never awaited to completion before re-discovery: a supervised restart waits for the old owner to+ * drain, and a turn parked on approval/clarify there waits for an answer only this window can give. */+export type StaleGatewayRestart = (endpoint: GatewayEndpoint, stale: { gateway: string; client: string }) => Promise<null | { done: Promise<void> }>/** The profile whose `hermes --profile P gateway restart` replaces the process behind `endpoint`:* the multiplexer root (`default`) for a served secondary, else the endpoint's own profile home. */@@ -98,28 +101,21 @@ export function createStaleGatewayRestarter(const pending = restarts.get(key)if (pending && !pending.done) {- await pending.promise-- return true+ return { done: pending.promise }}if (pending) {log(`[gateway] owner still runs ${stale.gateway} (this Hermes is ${stale.client}) after a restart; attaching as-is`)- return false+ return null}log(`[gateway] owner runs ${stale.gateway} but this Hermes is ${stale.client}; restarting it`)- const entry = { done: false, promise: restart(gatewayOwnerProfile(endpoint)) }+ const entry = { done: false, promise: restart(gatewayOwnerProfile(endpoint)).catch(() => undefined) }restarts.set(key, entry)+ void entry.promise.then(() => { entry.done = true })- try {- await entry.promise- } finally {- entry.done = true- }-- return true+ return { done: entry.promise }}}@@ -166,6 +162,34 @@ function assertLocalGatewayEndpoint(endpoint: GatewayEndpoint): void {}}+/** Poll interval while a requested stale-owner restart is in flight. */+export const STALE_RESTART_POLL_MS = 1000++/** Re-ensure while a stale-owner restart runs, without waiting for it to finish (#139041): the first+ * answer that is no longer the stale owner wins — its restart wait (attach to answer a parked+ * prompt), or a replacement. Once the restart client exits, whatever answers next is final. */+async function reensureDuringRestart(+ run: () => Promise<{ code: number; stdout: string; stderr?: string }>,+ done: Promise<void>,+ staleInstance: string+): Promise<{ result: { code: number; stdout: string; stderr?: string }; payload: Record<string, any> }> {+ let finished = false+ void done.then(() => { finished = true })++ for (;;) {+ const last = finished+ const result = await run()+ const payload = parseGatewayEnsureOutput(result)+ const restartWait = payload.state === 'draining' && payload.reason_code === 'restart_wait' && Boolean(payload.endpoint)+ const replaced = payload.state === 'ready' && payload.endpoint?.instance_id !== staleInstance++ if (last || restartWait || replaced) {return { result, payload }}+ let timer: ReturnType<typeof setTimeout> | undefined+ await Promise.race([done, new Promise(resolve => { timer = setTimeout(resolve, STALE_RESTART_POLL_MS) })])+ clearTimeout(timer)+ }+}+export async function ensureLocalGateway(run: () => Promise<{ code: number; stdout: string; stderr?: string }>,beforeEnsure?: () => Promise<void>,@@ -178,9 +202,10 @@ export async function ensureLocalGateway(// Attaching would pin a stale owner (503 "Restart required" forever): replace it once, then// take whatever answers the re-ensure.- if (stale && await restartStale!(payload.endpoint, stale)) {- result = await run()- payload = parseGatewayEnsureOutput(result)+ const restart = stale ? await restartStale!(payload.endpoint, stale) : null++ if (restart) {+ ({ result, payload } = await reensureDuringRestart(run, restart.done, payload.endpoint.instance_id))}// A graceful restart's after-turn wait still owns its turns (#139041): attach to it so a turn parkeddiff --git a/gateway/drain_control.py b/gateway/drain_control.pyindex a5d28878176..33f7950cb21 100644--- a/gateway/drain_control.py+++ b/gateway/drain_control.py@@ -16,6 +16,7 @@ import contextlibimport functoolsimport jsonimport logging+import refrom datetime import datetime, timezone, UTCfrom pathlib import Pathfrom typing import Any, Optional@@ -45,6 +46,21 @@ def restart_wait_open(runner) -> bool:return (bool(getattr(runner, "_draining", False)) and bool(getattr(runner, "_running", False))and descriptor.get("drain_reason") == RESTART_WAIT_REASON)++# The reads a client needs during that wait to find and open the conversation parked on+# approval/clarify: Desktop's session picker, the session detail and its transcript pages, and the+# health probes. GET only and still authenticated; every write and every other route keeps the+# drain's refusal. The prompt itself (approval.pending / *.respond) rides the WebSocket.+_RESTART_WAIT_READS = re.compile(+ r"/api/(?:health|status|profiles/sessions(?:/sidebar)?"+ r"|sessions/[^/]+(?:/messages(?:/around)?|/timeline)?)")+++def restart_wait_read(runner, method, path) -> bool:+ """True for an allowlisted read request while *runner* is in a restart's after-turn wait."""+ return (method == "GET" and bool(_RESTART_WAIT_READS.fullmatch(path or ""))+ and restart_wait_open(runner))+_DRAIN_REQUEST_FILENAME = ".drain_request.json"# Drain-gated lifecycle actions complete in minutes; an hour bounds the wedge a leaked# marker can cause. Long drains refresh the marker instead of raising this.diff --git a/gateway/run_api.py b/gateway/run_api.pyindex 40679f9ebb6..b537805416a 100644--- a/gateway/run_api.py+++ b/gateway/run_api.py@@ -238,6 +238,11 @@ def _embedded_chat_enabled() -> bool:return True if web is None else bool(getattr(web, "_DASHBOARD_EMBEDDED_CHAT_ENABLED", True))+def _restart_wait_read(runner, scope) -> bool:+ from gateway.drain_control import restart_wait_read+ return scope['type'] == 'http' and restart_wait_read(runner, scope.get('method'), scope.get('path'))++class GatewayRuntimeAPI:"""Redeem private local tickets at the existing WS subprotocol boundary.@@ -256,7 +261,8 @@ class GatewayRuntimeAPI:draining_socket = (descriptor['state'] in {'ready', 'draining'}and (self.runner._draining or descriptor['state'] == 'draining')and scope['type'] == 'websocket' and scope['path'] == '/api/ws')- if (descriptor['state'] != 'ready' or self.runner._draining) and not draining_socket:+ if ((descriptor['state'] != 'ready' or self.runner._draining) and not draining_socket+ and not _restart_wait_read(self.runner, scope)):if scope['type'] == 'websocket':await send({'type': 'websocket.close', 'code': 1013})else:diff --git a/hermes_cli/dashboard_auth/native_http.py b/hermes_cli/dashboard_auth/native_http.pyindex 97d13376a4f..bfedcfe6daa 100644--- a/hermes_cli/dashboard_auth/native_http.py+++ b/hermes_cli/dashboard_auth/native_http.py@@ -126,6 +126,7 @@ async def authenticate_native_http(request):tickets = request.headers.getlist(HEADER)if not tickets:return None+ from gateway.drain_control import restart_wait_readfrom gateway.session_authorities import all_authorities, authority_for_profile_idrunner = getattr(request.app.state, 'gateway_runner', None)descriptor = getattr(runner, 'session_runtime_descriptor', {})@@ -134,7 +135,9 @@ async def authenticate_native_http(request):peer = request.scope.get('hermes.gateway_socket_peer')if (len(tickets) != 1 or 'origin' in request.headers or not peeror peer[0] not in {'127.0.0.1', '::1'}- or descriptor.get('state') != 'ready' or getattr(runner, '_draining', True)+ or descriptor.get('state') != 'ready'+ # A restart's after-turn wait still serves the reads that open a parked prompt (#139041).+ or (getattr(runner, '_draining', True) and not restart_wait_read(runner, request.method, request.url.path))or not authorities or store is Noneor store.instance_id != descriptor.get('instance_id')or any(a is not None and a.instance_id != store.instance_id for a in authorities)diff --git a/tests/gateway/test_restart_wait_prompt_reach.py b/tests/gateway/test_restart_wait_prompt_reach.pyindex 05743a3c3a7..e1229c354af 100644--- a/tests/gateway/test_restart_wait_prompt_reach.py+++ b/tests/gateway/test_restart_wait_prompt_reach.py@@ -77,3 +77,44 @@ async def test_restart_wait_commits_new_input_queued_and_never_claims_it(tmp_patawait authority.submit(actor, Submission("r2", SessionRef("p", "s"), {"text": "late"}, "queue"))finally:db.close()+++async def test_restart_wait_serves_only_the_reads_that_open_the_parked_session():+ """Desktop finds and opens the parked conversation over HTTP (sidebar, detail, transcript); every+ write and unrelated route keeps the drain's 503, and stop() withdraws the reads too."""+ from gateway.run_api import GatewayRuntimeAPI++ reached = []++ async def app(scope, receive, send):+ reached.append((scope['method'], scope['path']))+ await send({'type': 'http.response.start', 'status': 200, 'headers': []})+ await send({'type': 'http.response.body', 'body': b'{}'})++ runner = SimpleNamespace(_draining=True, _running=True,+ session_runtime_descriptor={'state': 'draining', 'drain_reason': 'restart_wait'})+ api = GatewayRuntimeAPI(app, runner, SimpleNamespace(state=None))++ async def status(method, path):+ sent = []++ async def receive():+ return {'type': 'http.request', 'body': b''}++ async def send(message):+ sent.append(message)+ await api({'type': 'http', 'method': method, 'path': path, 'headers': [], 'query_string': b'',+ 'client': ('127.0.0.1', 1)}, receive, send)+ return sent[0]['status']++ reads = ['/api/profiles/sessions/sidebar', '/api/profiles/sessions', '/api/sessions/s1',+ '/api/sessions/s1/messages', '/api/sessions/s1/messages/around', '/api/sessions/s1/timeline',+ '/api/health', '/api/status']+ assert [await status('GET', path) for path in reads] == [200] * len(reads)+ refused = [('PATCH', '/api/sessions/s1'), ('DELETE', '/api/sessions/s1'), ('POST', '/api/sessions'),+ ('GET', '/api/config'), ('GET', '/api/sessions/s1/export/x'), ('POST', '/api/model/set')]+ assert [await status(m, path) for m, path in refused] == [503] * len(refused)+ del runner.session_runtime_descriptor['drain_reason'] # stop() began: nothing is served anymore+ assert await status('GET', '/api/profiles/sessions/sidebar') == 503+ assert reached == [('GET', path) for path in reads]