Skip to content

The agent that grows with you

fix(desktop): a retry refused because its id is already admitted settles as delivered

Teknium5e327d2b26ee
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit-admitted-conflict.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit-admitted-conflict.test.tsx
new file mode 100644
index 00000000000..c4444652a3d
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit-admitted-conflict.test.tsx
@@ -0,0 +1,92 @@
+import { JsonRpcGatewayError } from '@hermes/shared'
+import { act, cleanup, renderHook } from '@testing-library/react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+
+import { en } from '@/i18n/en'
+import { createClientSessionState } from '@/lib/chat-runtime'
+import { $activeGatewayProfile } from '@/store/profile'
+import { $connection, $sessions } from '@/store/session'
+import { $sessionStates } from '@/store/session-states'
+
+import { useSubmitPrompt } from './submit'
+import type { GatewayRequest } from './utils'
+
+vi.mock('@/store/gateway', async original => ({
+ ...(await original<Record<string, unknown>>()),
+ retainGatewayForSessionTurn: vi.fn(async () => () => undefined)
+}))
+
+beforeEach(() => {
+ window.localStorage.clear()
+ $sessions.set([])
+ $sessionStates.set({})
+ $connection.set(null)
+ $activeGatewayProfile.set('default')
+})
+afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+})
+
+type ClientSessionState = ReturnType<typeof createClientSessionState>
+
+// An attachment send that reached the owner but whose landed check missed comes back as text under
+// its original submission id. Enter on it is refused `admission_conflict` with `field: request_id`
+// (that id is already admitted with another payload): it was delivered, so it settles with no error
+// and no retained retry. Any other `admission_conflict` (route, binding) stays a visible failure.
+it('a retry refused because its id is already admitted settles as delivered; other conflicts still fail', async () => {
+ let state: ClientSessionState = createClientSessionState()
+ let refusal: Record<string, unknown> = {}
+
+ const requestGateway = vi.fn(async (method: string) => {
+ if (method === 'prompt.submit') {
+ throw new JsonRpcGatewayError('admission_conflict', { code: 4001, data: refusal })
+ }
+
+ return {} as never
+ })
+
+ const deps = {
+ activeSessionIdRef: { current: 'runtime-a' as string | null },
+ selectedStoredSessionIdRef: { current: 'stored-a' as string | null },
+ busyRef: { current: false },
+ copy: en.desktop,
+ createBackendSessionForSend: vi.fn(async () => null),
+ getRoutedStoredSessionId: () => null,
+ getRuntimeIdForStoredSession: () => 'runtime-a',
+ getRouteToken: () => 'same-route',
+ requestGateway: requestGateway as GatewayRequest,
+ runtimeIdByStoredSessionIdRef: { current: new Map([['stored-a', 'runtime-a']]) },
+ resumeStoredSession: vi.fn(),
+ syncAttachmentsForSubmit: vi.fn(async (sessionId: string) => ({ sessionId, attachments: [] })),
+ updateSessionState: vi.fn((_sid: string, updater: (s: ClientSessionState) => ClientSessionState) => {
+ state = updater(state)
+
+ return state
+ })
+ }
+
+ const { result } = renderHook(() => useSubmitPrompt(deps as never))
+
+ refusal = {
+ reason: 'admission_conflict',
+ field: 'request_id',
+ detail: 'this request id was already admitted with another payload'
+ }
+ await act(async () => {
+ expect(await result.current('look at this', { submission_id: 'restored-1' })).toBe(true)
+ })
+
+ expect(requestGateway.mock.calls.filter(([method]) => method === 'prompt.submit')).toHaveLength(1)
+ expect(state.messages.filter(message => message.role === 'user')).toHaveLength(0)
+ expect(state.messages.some(message => message.error)).toBe(false)
+ expect(state.busy).toBe(false)
+ expect(window.localStorage.getItem('hermes.desktop.preparedSubmissions.v1') ?? '').not.toContain('restored-1')
+
+ refusal = { reason: 'admission_conflict' }
+ await act(async () => {
+ expect(await result.current('another chat', { submission_id: 'restored-2' })).toBe(false)
+ })
+
+ expect(state.messages.some(message => message.error)).toBe(true)
+})
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 3104c497283..0c1c480d486 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
@@ -63,6 +63,7 @@ import {
acquireSubmitInFlight,
type GatewayRequest,
inlineErrorMessage,
+ isAdmittedSubmissionConflict,
isForwardedReceipt,
isProviderSetupError,
isSessionBusyError,
@@ -1158,6 +1159,12 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
try {
return await requestGateway<SubmitReceipt>('prompt.submit', params, PROMPT_SUBMIT_REQUEST_TIMEOUT_MS)
} catch (error) {
+ // A retry whose payload no longer matches its admitted original (an attachment send
+ // offered back as text) is that original: settled as the dedupe it is, no new turn.
+ if (isAdmittedSubmissionConflict(error)) {
+ return { status: 'terminal', submission_id: submissionId }
+ }
+
// 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
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.ts
index 2aa0f4bb9de..c35b3096486 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
@@ -305,6 +305,15 @@ export function isCompressionBusyError(error: unknown): boolean {
return data?.reason === 'session_busy' && data.field === 'compression'
}
+/** prompt.submit refused because this principal's submission id on this session is ALREADY admitted
+ * with another payload (hermes_state_runtime.ADMITTED_REQUEST_CONFLICT): the send was delivered.
+ * Every other `admission_conflict` (route, binding, lineage) names no such field and stays an error. */
+export function isAdmittedSubmissionConflict(error: unknown): boolean {
+ const data = error instanceof JsonRpcGatewayError ? (error.data as { field?: unknown; reason?: unknown } | undefined) : null
+
+ return data?.reason === 'admission_conflict' && data.field === 'request_id'
+}
+
// prompt.submit refused because another surface (TUI, messaging gateway)
// holds this session's lease (4090 / SESSION_NOT_OWNED, #106217). The gateway
// stamps the machine reason in `error.data.reason`; the prose fallback covers
diff --git a/gateway/session_ingress_media.py b/gateway/session_ingress_media.py
index 7181e71beca..8f41ecbfb1f 100644
--- a/gateway/session_ingress_media.py
+++ b/gateway/session_ingress_media.py
@@ -20,7 +20,7 @@ import tempfile
import threading
from hermes_dir_acl import make_user_dir
-from hermes_state_runtime import RuntimeStoreError
+from hermes_state_runtime import ADMITTED_REQUEST_CONFLICT, RuntimeStoreError
from utils import fsync_directory
logger = logging.getLogger(__name__)
@@ -167,7 +167,7 @@ def admit_attachments(attachments, *, admitted=None):
raise RuntimeStoreError('invalid_params')
if any(digest is not None and digest != reference['sha256']
for digest, reference in zip(hashes, committed['media'])):
- raise RuntimeStoreError('admission_conflict')
+ raise RuntimeStoreError('admission_conflict', **ADMITTED_REQUEST_CONFLICT)
retry = True
else:
# Retry identity is the committed bytes, not the disposable staging name.
diff --git a/hermes_state_runtime.py b/hermes_state_runtime.py
index 516e3ea4615..49207f5508d 100644
--- a/hermes_state_runtime.py
+++ b/hermes_state_runtime.py
@@ -32,6 +32,12 @@ class RuntimeStoreError(ValueError):
super().__init__(reason)
+#: The one ``admission_conflict`` that proves the request was already admitted: this principal's
+#: request id on this target holds an admission with another payload. Every other conflict (route,
+#: binding, lineage) carries no such proof, so a client tells them apart by this field.
+ADMITTED_REQUEST_CONFLICT = {'field': 'request_id', 'detail': 'this request id was already admitted with another payload'}
+
+
def _one_line(value, limit):
"""A refusal's ``field``/``detail`` as the log line and the client frame carry it: either may hold
client text, so whitespace collapses to single spaces, other non-printables drop (no forged log
@@ -150,7 +156,7 @@ def admit_session_input(db, *, epoch: int, principal_id: str, session_id: str,
WHERE principal_id=? AND target_session_id=? AND request_id=?''', (principal_id, session_id, request_id)).fetchone()
if old is not None:
if old['payload_digest'] != digest:
- raise RuntimeStoreError('admission_conflict')
+ raise RuntimeStoreError('admission_conflict', **ADMITTED_REQUEST_CONFLICT)
if _replay_guard is not None:
_replay_guard(conn)
return _row(old)
diff --git a/hermes_state_terminal.py b/hermes_state_terminal.py
index f9c94764b57..20c2b3daeb7 100644
--- a/hermes_state_terminal.py
+++ b/hermes_state_terminal.py
@@ -7,7 +7,7 @@ Worker receipt reads additionally require the original private adoption proof.
import hmac
import json
-from hermes_state_runtime import RuntimeStoreError, _epoch, _json, _row, _secret_digest, _text, admission_fingerprint
+from hermes_state_runtime import ADMITTED_REQUEST_CONFLICT, RuntimeStoreError, _epoch, _json, _row, _secret_digest, _text, admission_fingerprint
RESULT_PREFIX = 'gateway.admission.result.v1.'
ADMISSION_PREFIX = 'gateway.terminal_admission.v1.'
@@ -142,7 +142,7 @@ def retry_terminal_admission(db, *, epoch, principal_id, session_id, request_id,
raise RuntimeStoreError('not_found')
row = terminal_admission(conn, json.loads(saved[0]))
if row['payload_digest'] != digest:
- raise RuntimeStoreError('admission_conflict')
+ raise RuntimeStoreError('admission_conflict', **ADMITTED_REQUEST_CONFLICT)
return _row(row)