The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): never tell the user an unconfirmed forwarded prompt was not sent
Tekniumde7c17d6a222
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.tsxindex 4e0041c1e46..0cc2cf8c51b 100644--- 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.tsx@@ -2,6 +2,7 @@ import { JsonRpcGatewayError } from '@hermes/shared'import { cleanup } from '@testing-library/react'import { afterEach, describe, expect, it, vi } from 'vitest'+import { errorRecoveryPlan, type ErrorSurface } from '@/lib/error-surface'import { clearNotifications } from '@/store/notifications'import { actRender, Harness, type HarnessHandle } from './index-test-utils'@@ -44,6 +45,38 @@ describe('usePromptActions gateway-owner queue (#140385)', () => {expect(bubble?.errorSurface).toEqual({ layer: 'gateway', code: 'SESSION_OWNER_BUSY', retryable: true })})+ it('turns an unconfirmed forward into a card without Retry: the owner may already hold it', 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 did not confirm your message in time. It may already be queued there: check the chat before sending it again.',+ { code: 4090, data: { reason: 'SESSION_OWNER_UNCONFIRMED' } }+ )+ }++ 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?: ErrorSurface }[]).at(-1)+ expect(bubble?.errorSurface).toEqual({ layer: 'gateway', code: 'SESSION_OWNER_UNCONFIRMED', retryable: false })+ expect(errorRecoveryPlan(bubble?.errorSurface).retry).toBe(false)+ })+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> | undefineddiff --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 c1685c837f4..60acb713fb7 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@@ -312,7 +312,11 @@ export function isSessionNotOwnedError(error: unknown): boolean {// prompt.submit refused because the gateway that owns this chat is mid-turn and could not queue// the send (4090 / SESSION_OWNER_BUSY, #140385). Transient: the turn ends on its own.export function isSessionOwnerBusyError(error: unknown): boolean {- return error instanceof JsonRpcGatewayError && (error.data as { reason?: unknown } | undefined)?.reason === 'SESSION_OWNER_BUSY'+ return gatewayReason(error) === 'SESSION_OWNER_BUSY'+}++function gatewayReason(error: unknown): unknown {+ return error instanceof JsonRpcGatewayError ? (error.data as { reason?: unknown } | undefined)?.reason : undefined}// The error card's surface for an ownership refusal: another surface owns the session (#106217,@@ -323,13 +327,23 @@ export function ownershipErrorSurface(error: unknown): { errorSurface?: ErrorSurreturn { errorSurface: { layer: 'gateway', code: 'SESSION_NOT_OWNED', retryable: false } }}- return isSessionOwnerBusyError(error) ? { errorSurface: { layer: 'gateway', code: 'SESSION_OWNER_BUSY', retryable: true } } : {}+ if (gatewayReason(error) === 'SESSION_OWNER_UNCONFIRMED') {+ // The owner may already hold the send: a Retry would run a second copy.+ return { errorSurface: { layer: 'gateway', code: 'SESSION_OWNER_UNCONFIRMED', 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 {+export function isForwardedReceipt(+ legacyAccepted: boolean,+ result: { forwarded?: boolean | null; status?: string } | undefined+): boolean {return legacyAccepted && result?.forwarded === true && result.status === 'queued'}diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 1f71a8430da..11c289801e9 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -3535,7 +3535,8 @@ export const en: Translations = {restoreImageDraft: 'Restore image draft',queueCancelFailed: "Couldn't remove the queued turn",queueLostDiscard: 'Discard',- queueLostDiscardTip: 'The gateway restarted mid-turn and cannot finish this one. Discard it so the queued turns behind it run.',+ queueLostDiscardTip:+ 'The gateway restarted mid-turn and cannot finish this one. Discard it so the queued turns behind it run.',queueResume: 'Resume',queueResumeTip: 'Paused by Stop — resume sending the queued turns',queueStuckTitle: 'Queued message not sent',@@ -4693,7 +4694,14 @@ 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 here and your message could not join its queue. Nothing was sent. Retry once that 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_OWNER_UNCONFIRMED: {+ title: 'Your message may already be queued',+ body: 'Another turn is running in this chat and the gateway did not confirm your message in time. It may still run after that turn. Check the chat before sending it again.'+ },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/apps/desktop/src/i18n/overlay-gaps.json b/apps/desktop/src/i18n/overlay-gaps.jsonindex 7bf98817afa..80e153ceeec 100644--- a/apps/desktop/src/i18n/overlay-gaps.json+++ b/apps/desktop/src/i18n/overlay-gaps.json@@ -54,6 +54,8 @@"assistant.thread.errorCodes.SESSION_NOT_OWNED.title": ["ar","ja","ru","zh","zh-hant"],"assistant.thread.errorCodes.SESSION_OWNER_BUSY.body": ["ar","de","es","fr","ja","ru","zh","zh-hant"],"assistant.thread.errorCodes.SESSION_OWNER_BUSY.title": ["ar","de","es","fr","ja","ru","zh","zh-hant"],+ "assistant.thread.errorCodes.SESSION_OWNER_UNCONFIRMED.body": ["ar","de","es","fr","ja","ru","zh","zh-hant"],+ "assistant.thread.errorCodes.SESSION_OWNER_UNCONFIRMED.title": ["ar","de","es","fr","ja","ru","zh","zh-hant"],"assistant.thread.errorCodes.auth.body": ["ar","ja","ru","zh","zh-hant"],"assistant.thread.errorCodes.auth.title": ["ar","ja","ru","zh","zh-hant"],"assistant.thread.errorCodes.auth_permanent.body": ["ar","ja","ru","zh","zh-hant"],diff --git a/apps/desktop/src/lib/error-surface.ts b/apps/desktop/src/lib/error-surface.tsindex f9bf015b234..5950e89bf8f 100644--- a/apps/desktop/src/lib/error-surface.ts+++ b/apps/desktop/src/lib/error-surface.ts@@ -51,6 +51,8 @@ export const ERROR_CODE_KEYS = ['SESSION_NOT_OWNED',// The gateway that owns the chat is mid-turn and could not queue this send: transient.'SESSION_OWNER_BUSY',+ // The owner did not confirm a forwarded send in time; it may already be queued: no Retry.+ 'SESSION_OWNER_UNCONFIRMED','disk_full',// Raised by the desktop, never by the backend: the backend reported a turn// over after its events stopped, and no reply reached this window.@@ -270,6 +272,7 @@ const SWITCH_PROVIDER_LAYERS: readonly ErrorSurfaceLayer[] = ['auth', 'billing',const CODE_PLANS: Partial<Record<ErrorCodeKey, Partial<ErrorRecoveryPlan>>> = {SESSION_NOT_OWNED: { retry: false, startNewSession: true },SESSION_OWNER_BUSY: { retry: true, startNewSession: false },+ SESSION_OWNER_UNCONFIRMED: { retry: false, startNewSession: false },content_policy_blocked: { editMessage: true, retry: false },context_overflow: { compress: true, retry: false, startNewSession: true },disk_full: { openHermesFolder: true, retry: true },diff --git a/tests/tui_gateway/test_legacy_submit_forwards_to_owner.py b/tests/tui_gateway/test_legacy_submit_forwards_to_owner.pyindex 40b1fc9fb00..dc4e0e99152 100644--- a/tests/tui_gateway/test_legacy_submit_forwards_to_owner.py+++ b/tests/tui_gateway/test_legacy_submit_forwards_to_owner.py@@ -158,6 +158,40 @@ def test_outcome_unknown_work_is_still_refused_and_never_forwarded(monkeypatch,db.close()+def test_an_unconfirmed_forward_is_never_reported_as_not_sent(monkeypatch, tmp_path):+ """The owner's receipt timed out but the relay keeps going, so the prompt may already sit in the+ owner's FIFO: the refusal says to check the chat, with a reason the client never offers Retry for+ (a retry would admit a second copy under a fresh submission id)."""+ db = SessionDB(db_path=tmp_path / "state.db")+ sid, key, turns, _emitted = _legacy(monkeypatch, db)+ try:+ db.create_session(key, "test")+ epoch = begin_runtime_epoch(db, instance_id="gateway")+ admit_session_input(db, epoch=epoch, principal_id="bot", session_id=key, request_id="dm-1",+ payload={"text": "a DM"})+ claim_session_input(db, epoch=epoch, session_id=key)+ _owner(monkeypatch, db, key, epoch)+ from tui_gateway import owner_forward+ monkeypatch.setattr(owner_forward, "ADMIT_TIMEOUT_S", 0)+ hold = asyncio.Event()++ @contextlib.asynccontextmanager+ async def slow(_home, _endpoint):+ await asyncio.wait_for(hold.wait(), 5) # the owner never answers inside the admit wait+ yield+ monkeypatch.setattr(owner_forward, "connect_owner", slow)+ reply = server.handle_request({"id": "p", "method": "prompt.submit",+ "params": {"session_id": sid, "text": "hi"}})+ assert reply["error"]["code"] == 4090+ assert reply["error"]["data"] == {"reason": "SESSION_OWNER_UNCONFIRMED"}+ message = reply["error"]["message"]+ assert "Nothing was sent" not in message and "check the chat" in message+ assert turns == []+ finally:+ server._sessions.pop(sid, None)+ db.close()++@pytest.mark.parametrize("case", ["owner_refused", "rewind"])def test_a_prompt_the_owner_cannot_queue_is_refused_with_why_and_when(monkeypatch, tmp_path, case):"""Where admission is impossible the refusal names why and says to send when the turn ends,diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex e1f9f5b4ac8..40e8c0a24e1 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -698,6 +698,9 @@ _TRUNCATION_PARAMS = (#: The refusal reason when the owner's FIFO could not take a typed prompt (RT-37): transient, the#: gateway's turn ends on its own, so the client offers "send when the turn ends", not a new chat.SESSION_OWNER_BUSY = "SESSION_OWNER_BUSY"+#: The owner's FIFO did not confirm a forwarded prompt in time; it may still have been queued, so the+#: client must not offer Retry (a second copy would run): check the chat first.+SESSION_OWNER_UNCONFIRMED = "SESSION_OWNER_UNCONFIRMED"def _slot_refusal(rid, sid, session, text, params, refusal, internal_hosted_submit) -> dict:@@ -728,6 +731,10 @@ def _submit_to_ledger_owner(rid, sid, session, text, params, refusal) -> dict:receipt = owner_forward.forward_prompt(sid, session, text)except owner_forward.OwnerNotRunning:return not_owned # no gateway runs the ledger's work: it will not end on its own+ except owner_forward.OwnerUnconfirmed:+ return _err(rid, 4090, "The gateway is running a turn in this chat and did not confirm your message"+ " in time. It may already be queued there: check the chat before sending it again.",+ {"reason": SESSION_OWNER_UNCONFIRMED})except Exception as exc: # every owner failure is the same named refusallogger.info("forwarding prompt for %s to the owner failed: %s",session.get("session_key") or sid, exc, exc_info=True)diff --git a/tui_gateway/owner_forward.py b/tui_gateway/owner_forward.pyindex 458fb5ddb50..d4a5369cef6 100644--- a/tui_gateway/owner_forward.py+++ b/tui_gateway/owner_forward.py@@ -49,6 +49,11 @@ class OwnerNotRunning(OwnerUnavailable):"""No ready gateway serves the home: nothing will end the ledger's work on its own."""+class OwnerUnconfirmed(OwnerUnavailable):+ """The owner's admission receipt did not arrive in time. The relay keeps going, so the prompt+ may still be (or already be) queued there: never "nothing was sent", never a retry."""++def discover_owner(home: Path):"""The ready gateway endpoint serving ``home``. Discovery only: never starts one."""from hermes_cli.gateway_runtime import discover_gateway_endpoint@@ -191,4 +196,4 @@ def forward_prompt(sid: str, session: dict, text: str, *, emit=None, home: Pathtry:return relay.admitted.result(timeout=ADMIT_TIMEOUT_S)except FutureTimeout as exc:- raise OwnerUnavailable("the gateway did not confirm it in time; check the chat before sending again") from exc+ raise OwnerUnconfirmed("the gateway did not confirm it in time") from exc