The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor: keep the RT-37 owner forward inside the code-health caps
Teknium6c8b5628506e
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.tsxindex 6b10f14d1e0..45d7dc93fe6 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@@ -5616,75 +5616,6 @@ describe('usePromptActions live-owner refusal (#106217)', () => {// Not a stale-runtime symptom: no resume/re-mint attempt hides the refusal.expect(requestGateway.mock.calls.map(c => c[0])).toEqual(['prompt.submit'])})-- it('turns a SESSION_OWNER_BUSY refusal into a retryable card, not "Start new session" (#140385)', async () => {- let latest: Record<string, unknown> | undefined-- const requestGateway = vi.fn(async (method: string) => {- if (method === 'prompt.submit') {- throw new JsonRpcGatewayError(- 'The gateway is running a turn in this chat and a rewind or attachment cannot join its queue. Nothing was sent. Send it again when the current turn ends.',- { code: 4090, data: { reason: 'SESSION_OWNER_BUSY' } }- )- }-- return {} as never- })-- let handle: HarnessHandle | null = null- await actRender(- <Harness- onReady={h => (handle = h)}- onSeedState={next => {- latest = next- }}- refreshSessions={async () => undefined}- requestGateway={requestGateway}- />- )-- expect(await handle!.submitText('continue here')).toBe(false)- const bubble = (latest?.messages as { errorSurface?: Record<string, unknown> }[]).at(-1)- expect(bubble?.errorSurface).toEqual({ layer: 'gateway', code: 'SESSION_OWNER_BUSY', retryable: true })- })-- it('shows a prompt the legacy backend forwarded to the gateway owner as queued, not as a failed turn (#140385)', async () => {- let latest: Record<string, unknown> | undefined-- // The legacy backend refuses `submission_id` (4000, pre-admission), then answers the identityless- // retry with the owner's queued receipt: the prompt waits in the gateway's FIFO.- const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) => {- if (method === 'prompt.submit' && params?.submission_id) {- throw new JsonRpcGatewayError("unknown field 'submission_id'", { code: 4000 })- }-- if (method === 'prompt.submit') {- return { status: 'queued', admission_id: 'owner-admission', forwarded: true } as never- }-- return {} as never- })-- let handle: HarnessHandle | null = null- await actRender(- <Harness- onReady={h => (handle = h)}- onSeedState={next => {- latest = next- }}- refreshSessions={async () => undefined}- requestGateway={requestGateway}- />- )-- expect(await handle!.submitText('my own question')).toBe(true)- const messages = (latest?.messages ?? []) as { error?: string; role?: string }[]- // No failed-turn card and no optimistic bubble: the queued-row card stands for the send.- expect(messages.some(message => message.error)).toBe(false)- expect(messages.some(message => message.role === 'user')).toBe(false)- expect(latest?.busy).toBe(false)- expect(latest?.awaitingResponse).toBe(false)- })})describe('usePromptActions send from a window behind the stored transcript', () => {diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/owner-forward.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/owner-forward.test.tsxnew file mode 100644index 00000000000..4e0041c1e46--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/owner-forward.test.tsx@@ -0,0 +1,84 @@+import { JsonRpcGatewayError } from '@hermes/shared'+import { cleanup } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'++import { clearNotifications } from '@/store/notifications'++import { actRender, Harness, type HarnessHandle } from './index-test-utils'++// RT-37 (#140385): a prompt on a chat whose gateway owner is mid-turn.+describe('usePromptActions gateway-owner queue (#140385)', () => {+ afterEach(() => {+ cleanup()+ clearNotifications()+ })++ it('turns a SESSION_OWNER_BUSY refusal into a retryable card, not "Start new session" (#140385)', async () => {+ let latest: Record<string, unknown> | undefined++ const requestGateway = vi.fn(async (method: string) => {+ if (method === 'prompt.submit') {+ throw new JsonRpcGatewayError(+ 'The gateway is running a turn in this chat and a rewind or attachment cannot join its queue. Nothing was sent. Send it again when the current turn ends.',+ { code: 4090, data: { reason: 'SESSION_OWNER_BUSY' } }+ )+ }++ return {} as never+ })++ let handle: HarnessHandle | null = null+ await actRender(+ <Harness+ onReady={h => (handle = h)}+ onSeedState={next => {+ latest = next+ }}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ />+ )++ expect(await handle!.submitText('continue here')).toBe(false)+ const bubble = (latest?.messages as { errorSurface?: Record<string, unknown> }[]).at(-1)+ expect(bubble?.errorSurface).toEqual({ layer: 'gateway', code: 'SESSION_OWNER_BUSY', retryable: true })+ })++ it('shows a prompt the legacy backend forwarded to the gateway owner as queued, not as a failed turn (#140385)', async () => {+ let latest: Record<string, unknown> | undefined++ // The legacy backend refuses `submission_id` (4000, pre-admission), then answers the identityless+ // retry with the owner's queued receipt: the prompt waits in the gateway's FIFO.+ const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) => {+ if (method === 'prompt.submit' && params?.submission_id) {+ throw new JsonRpcGatewayError("unknown field 'submission_id'", { code: 4000 })+ }++ if (method === 'prompt.submit') {+ return { status: 'queued', admission_id: 'owner-admission', forwarded: true } as never+ }++ return {} as never+ })++ let handle: HarnessHandle | null = null+ await actRender(+ <Harness+ onReady={h => (handle = h)}+ onSeedState={next => {+ latest = next+ }}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ />+ )++ expect(await handle!.submitText('my own question')).toBe(true)+ const messages = (latest?.messages ?? []) as { error?: string; role?: string }[]+ // No failed-turn card and no optimistic bubble: the queued-row card stands for the send.+ expect(messages.some(message => message.error)).toBe(false)+ expect(messages.some(message => message.role === 'user')).toBe(false)+ expect(latest?.busy).toBe(false)+ expect(latest?.awaitingResponse).toBe(false)+ })+})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.tsindex 2631d05fa49..ba43a979897 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@@ -61,11 +61,11 @@ import {acquireSubmitInFlight,type GatewayRequest,inlineErrorMessage,+ isForwardedReceipt,isProviderSetupError,isSessionBusyError,- isSessionNotOwnedError,- isSessionOwnerBusyError,isTargetSessionBusy,+ ownershipErrorSurface,releaseSubmitInFlight,SessionRecoveryAborted,type SubmitTextOptions,@@ -1228,6 +1228,11 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {}}+ // RT-37: forwarded to the gateway owner's FIFO; its queued-row card stands for the send.+ if (isForwardedReceipt(legacyAccepted, result)) {+ abortForSessionSwitch(sessionId)+ }+const rowId = result?.user_row_idif (typeof rowId === 'number' && Number.isSafeInteger(rowId) && rowId > 0) {@@ -1257,15 +1262,6 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {return false}- // RT-37: a legacy backend handed this prompt to the gateway that owns the chat; it- // waits in that owner's FIFO behind the gateway's turn. The queued-row card (the- // backend's pending_submissions) stands for it until the owner starts it, so no- // optimistic bubble or spinner here; the owner's start and completion repaint it.- if (legacyAccepted && result?.forwarded === true && result.status === 'queued') {- dropOptimistic(sessionId)- releaseBusy()- }-acceptedRuntimeSessionId = receiptSessionId} catch (firstErr) {if (firstErr instanceof SessionRecoveryAborted) {@@ -1327,12 +1323,6 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {const message = inlineErrorMessage(err, copy.promptFailed)const occurredAt = Date.now() / 1000- // Another surface owns the session (#106217): a deterministic gateway- // refusal, so the error card drops Retry and offers a new session.- const notOwned = isSessionNotOwnedError(err)- // The gateway owner is mid-turn and could not queue this send (#140385): transient, so the- // card offers to send it again once the turn ends instead of a new session.- const ownerBusy = !notOwned && isSessionOwnerBusyError(err)updateSessionState(sessionId,@@ -1345,8 +1335,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {role: 'assistant',parts: [],error: message || copy.promptFailed,- ...(notOwned && { errorSurface: { layer: 'gateway', code: 'SESSION_NOT_OWNED', retryable: false } }),- ...(ownerBusy && { errorSurface: { layer: 'gateway', code: 'SESSION_OWNER_BUSY', retryable: true } }),+ ...ownershipErrorSurface(err),branchGroupId: state.pendingBranchGroup ?? undefined,completedAt: occurredAt,timestamp: occurredAtdiff --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 d2c130d3bd9..c1685c837f4 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@@ -5,6 +5,7 @@ import { translateNow, type Translations } from '@/i18n'import type { ChatMessage } from '@/lib/chat-messages'import { isReadFileErrorResult } from '@/lib/desktop-fs'import { type CommandsCatalogLike, filterDesktopCommandsCatalog } from '@/lib/desktop-slash-commands'+import type { ErrorSurface } from '@/lib/error-surface'import { isProviderSetupErrorMessage } from '@/lib/provider-setup-errors'import type { ComposerAttachment } from '@/store/composer'@@ -314,6 +315,24 @@ export function isSessionOwnerBusyError(error: unknown): boolean {return error instanceof JsonRpcGatewayError && (error.data as { reason?: unknown } | undefined)?.reason === 'SESSION_OWNER_BUSY'}+// The error card's surface for an ownership refusal: another surface owns the session (#106217,+// deterministic: drop Retry, offer a new session), or the gateway owner is mid-turn and could not+// queue the send (#140385, transient: Retry once the turn ends). Empty for any other error.+export function ownershipErrorSurface(error: unknown): { errorSurface?: ErrorSurface } {+ if (isSessionNotOwnedError(error)) {+ return { errorSurface: { layer: 'gateway', code: 'SESSION_NOT_OWNED', retryable: false } }+ }++ return isSessionOwnerBusyError(error) ? { errorSurface: { layer: 'gateway', code: 'SESSION_OWNER_BUSY', retryable: true } } : {}+}++// RT-37: a legacy backend handed this prompt to the gateway that owns the chat, where it waits in+// the owner's FIFO behind the gateway's turn. The queued-row card (the backend's+// pending_submissions) stands for it until the owner starts it: no optimistic bubble or spinner.+export function isForwardedReceipt(legacyAccepted: boolean, result: { forwarded?: boolean | null; status?: string } | undefined): boolean {+ return legacyAccepted && result?.forwarded === true && result.status === 'queued'+}+const sleep = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))// Retry a gateway call across transient "session busy" so it never reaches thediff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 0e6aa063d90..1f71a8430da 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -3081,8 +3081,7 @@ export const en: Translations = {// Replaces `next` when the stored next_run_at is already past the scheduler grace (#114309).overdueSince: 'Overdue since:',noRuns: 'No runs yet',- // Queued trigger feedback in Run History: the backend accepted the trigger- // but has not materialized the run session yet (#70826).+ // Queued trigger feedback in Run History: the backend accepted the trigger but has not materialized the run session yet (#70826).queuedRun: 'Queued run',manage: 'Manage',showRuns: 'Show runs',@@ -4694,10 +4693,7 @@ export const en: Translations = {title: 'Hermes got stuck in a loop',body: 'The reply kept repeating the same steps, so Hermes stopped it. Retry, or start a new chat if it happens again.'},- SESSION_OWNER_BUSY: {- title: 'Hermes is busy in this chat',- body: 'Another turn is running in this chat and your message could not wait in its queue. Nothing was sent. Retry once the current turn ends.'- },+ SESSION_OWNER_BUSY: { title: 'Hermes is busy in this chat', body: 'Another turn is running here and your message could not join its queue. Nothing was sent. Retry once that turn ends.' },SESSION_NOT_OWNED: {title: 'This chat is open somewhere else',body: 'This chat is currently open in another Hermes window or terminal. Close it there and send your message again, or start a new chat here.'diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex ff67b32dffa..e1f9f5b4ac8 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -700,6 +700,14 @@ _TRUNCATION_PARAMS = (SESSION_OWNER_BUSY = "SESSION_OWNER_BUSY"+def _slot_refusal(rid, sid, session, text, params, refusal, internal_hosted_submit) -> dict:+ """The answer to a refused slot: a ledger refusal of a client submit goes to the owner's FIFO."""+ if getattr(refusal, "ledger_status", None) is not None and not internal_hosted_submit:+ return _submit_to_ledger_owner(rid, sid, session, text, params, refusal)+ reason = getattr(refusal, "reason", None)+ return _err(rid, 4090, str(refusal), {"reason": reason} if reason else None)++def _submit_to_ledger_owner(rid, sid, session, text, params, refusal) -> dict:"""The gateway's durable ledger holds work for this session (#140385, RT-37): one owner, one FIFO.Work that ends on its own (a running or queued gateway turn) gets this prompt queued behind it in@@ -811,10 +819,7 @@ def _(rid, params: dict) -> dict:if (limit_message := _ensure_active_session_slot(sid, session)) is not None:# Refused HERE — before the busy queue, db row and agent build — so a refusal# leaves the session untouched. The reason travels as machine-readable data.- if getattr(limit_message, "ledger_status", None) is not None and not internal_hosted_submit:- return _submit_to_ledger_owner(rid, sid, session, text, params, limit_message)- reason = getattr(limit_message, "reason", None)- return _err(rid, 4090, str(limit_message), {"reason": reason} if reason else None)+ return _slot_refusal(rid, sid, session, text, params, limit_message, internal_hosted_submit)# Rewritten every submit: a session alternates app window / HUD / live voice; a stale value misinforms.session["client_surface"] = params.get("surface") if params.get("surface") in _CLIENT_SURFACES else ""# Live-voice delegations carry the recent spoken transcript for the MODEL INPUT only (the persisteddiff --git a/tui_gateway/owner_forward.py b/tui_gateway/owner_forward.pyindex 76c3f19c9e4..458fb5ddb50 100644--- a/tui_gateway/owner_forward.py+++ b/tui_gateway/owner_forward.py@@ -21,7 +21,6 @@ from __future__ import annotationsimport asyncioimport contextlibimport logging-import threadingimport uuidfrom concurrent.futures import Futurefrom concurrent.futures import TimeoutError as FutureTimeout@@ -91,9 +90,10 @@ def _payload_for(event_type: str, payload: Any) -> dict | None:if contract is None or contract.payload is None or not isinstance(payload, dict):return Noneshaped = {key: value for key, value in payload.items() if key in contract.payload.model_fields}+ from pydantic import ValidationErrortry:contract.payload.model_validate(shaped)- except Exception:+ except ValidationError:if event_type != "message.complete":return Noneshaped = {"text": payload.get("text") if isinstance(payload.get("text"), str) else ""}@@ -110,11 +110,11 @@ class _Relay:def run(self) -> None:try:asyncio.run(self._run())- except BaseException as exc: # thread boundary: hand the failure to the waiting submit+ except BaseException as exc: # health: allow BLE001 -- thread boundary: handed to the waiting submit or logged with tracebackif not self.admitted.done():self.admitted.set_exception(exc)else:- logger.warning("owner relay for %s ended: %s", self.key, exc)+ logger.warning("owner relay for %s ended: %s", self.key, exc, exc_info=True)async def _run(self) -> None:async with connect_owner(self.home, self.endpoint) as client:@@ -186,7 +186,8 @@ def forward_prompt(sid: str, session: dict, text: str, *, emit=None, home: Pathraise OwnerUnavailable("the chat has no stored session yet")home = Path(home or session.get("profile_home") or server._hermes_home).resolve()relay = _Relay(sid, session, key, home, discover_owner(home), text, emit or server._emit)- threading.Thread(target=relay.run, name=f"owner-forward-{key[:24]}", daemon=True).start()+ from agent.memory_provider import spawn_context_thread+ spawn_context_thread(relay.run, name=f"owner-forward-{key[:24]}").start()try:return relay.admitted.result(timeout=ADMIT_TIMEOUT_S)except FutureTimeout as exc: