Skip to content

The agent that grows with you

fix(desktop): a correction refused before any agent saw it is re-queued, not dropped

Tekniumbd6e94352b1e
diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.ts
index a248b165be8..6920d24f161 100644
--- a/apps/desktop/src/app/chat/session-tile-actions.ts
+++ b/apps/desktop/src/app/chat/session-tile-actions.ts
@@ -9,6 +9,7 @@
*/
import type { AppendMessage, ThreadMessage } from '@assistant-ui/react'
+import { isUndeliveredCorrectionRefusal } from '@hermes/shared'
import { useCallback, useMemo, useRef } from 'react'
import type { ClientSessionState } from '@/app/types'
@@ -503,6 +504,12 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
}
} catch (err) {
discardOptimisticMessage()
+
+ // Refused before any agent saw it: the composer re-queues the words (#141644).
+ if (isUndeliveredCorrectionRefusal(err)) {
+ return false
+ }
+
notifyError(err, copy.promptFailed)
throw err
}
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
index e11a31df21c..9ce6802945b 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
@@ -1,5 +1,5 @@
import type { AppendMessage, ThreadMessage } from '@assistant-ui/react'
-import { JsonRpcGatewayError } from '@hermes/shared'
+import { isUndeliveredCorrectionRefusal, JsonRpcGatewayError } from '@hermes/shared'
import { stripAnsi } from '@hermes/shared/ansi'
import { useStore } from '@nanostores/react'
import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'
@@ -925,6 +925,13 @@ export function usePromptActions({
}
} catch (err) {
discardOptimisticMessage()
+
+ // Refused before any agent saw it (the turn this pane believed busy is gone):
+ // not a failed send. The composer re-queues the words as the next turn (#141644).
+ if (isUndeliveredCorrectionRefusal(err)) {
+ return false
+ }
+
throw err
}
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/steering-undelivered-refusal.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/steering-undelivered-refusal.test.tsx
new file mode 100644
index 00000000000..c9de02678a1
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/steering-undelivered-refusal.test.tsx
@@ -0,0 +1,164 @@
+import { JsonRpcGatewayError } from '@hermes/shared'
+import { useStore } from '@nanostores/react'
+import { act, cleanup, render } from '@testing-library/react'
+import { afterEach, expect, it, vi } from 'vitest'
+
+import { createSessionRpcDispatcher } from '@/app/contrib/session-rpc-dispatcher'
+import { sessionRoute } from '@/app/routes'
+import { textPart } from '@/lib/chat-messages'
+import { requestGatewayForAgent } from '@/store/gateway'
+import {
+ $activeSessionId,
+ $selectedStoredSessionId,
+ setActiveSessionId,
+ setActiveSessionStoredIdRotation,
+ setAwaitingResponse,
+ setBusy,
+ setMessages,
+ setSelectedStoredSessionId,
+ setSessions
+} from '@/store/session'
+import { clearAllSessionStates } from '@/store/session-states'
+import type { SessionInfo } from '@/types/hermes'
+
+import { useSessionStateCache } from '../use-session-state-cache'
+
+import { clearSingleFlightSessionResumeState } from './single-flight-resume'
+
+import { usePromptActions } from '.'
+
+// Real prompt hooks, cache, ownership router, and dispatcher; only the external
+// gateway edge is substituted. No test injects a corrupted ownership mapping.
+vi.mock('@/store/gateway', async original => ({
+ ...(await original<Record<string, unknown>>()),
+ requestGatewayForAgent: vi.fn(),
+ requestGatewayForProfile: vi.fn(),
+ retainGatewayForSessionTurn: vi.fn(async () => () => undefined)
+}))
+
+const busyRef = { current: false }
+let routedStoredId: string | null = 'stored-B'
+let handle: { actions: ReturnType<typeof usePromptActions>; cache: ReturnType<typeof useSessionStateCache> }
+
+function Harness() {
+ const activeSessionId = useStore($activeSessionId)
+ const selectedStoredSessionId = useStore($selectedStoredSessionId)
+
+ const cache = useSessionStateCache({
+ activeSessionId,
+ selectedStoredSessionId,
+ busyRef,
+ setAwaitingResponse,
+ setBusy,
+ setMessages
+ })
+
+ const requestGateway = createSessionRpcDispatcher({
+ ...cache,
+ ambientRequest: async () => {
+ throw new Error('unexpected ambient request')
+ }
+ })
+
+ const actions = usePromptActions({
+ activeSessionId,
+ ...cache,
+ busyRef,
+ branchCurrentSession: async () => false,
+ createBackendSessionForSend: async () => {
+ throw new Error('unexpected create')
+ },
+ getRoutedStoredSessionId: () => routedStoredId,
+ getRouteToken: () => `${routedStoredId ? sessionRoute(routedStoredId) : '/'}::`,
+ handleSkinCommand: () => '',
+ openMemoryGraph: () => undefined,
+ refreshSessions: async () => undefined,
+ requestGateway,
+ resumeStoredSession: async () => {
+ throw new Error('unexpected foreground resume')
+ },
+ startFreshSessionDraft: () => undefined,
+ sttEnabled: false
+ })
+
+ handle = { actions, cache }
+
+ return null
+}
+
+function seed() {
+ routedStoredId = 'stored-B'
+ busyRef.current = false
+ // Same profile name on distinct backends: profile equality is not ownership.
+ setSessions(
+ ['A', 'B'].map(id => ({
+ id: `stored-${id}`,
+ connection_id: `connection-${id}`,
+ profile: 'default',
+ source: 'desktop',
+ message_count: 1
+ })) as SessionInfo[]
+ )
+ setSelectedStoredSessionId('stored-B')
+ setActiveSessionId('rt-B')
+ render(<Harness />)
+ act(() => {
+ for (const id of ['A', 'B']) {
+ handle.cache.updateSessionState(
+ `rt-${id}`,
+ state => ({
+ ...state,
+ messages: [{ id: `history-${id}`, role: 'assistant', parts: [textPart(`history ${id}`)] }]
+ }),
+ `stored-${id}`
+ )
+ }
+ })
+}
+
+afterEach(() => {
+ cleanup()
+ clearAllSessionStates()
+ clearSingleFlightSessionResumeState()
+ setActiveSessionId(null)
+ setActiveSessionStoredIdRotation(null)
+ setSelectedStoredSessionId(null)
+ setSessions([])
+ setBusy(false)
+ setAwaitingResponse(false)
+ setMessages([])
+ window.localStorage.clear()
+ vi.clearAllMocks()
+})
+
+// #141644: a pane whose busy belief outlived its turn sends the next message as a correction. The
+// owner refuses it before any agent sees it; the action must hand the words back (false) so the
+// composer re-queues them, never throw (which discarded the message with a "prompt failed" toast).
+it.each(['execution_not_ready', 'stale_generation'])(
+ 'redirectPrompt hands back a correction the owner refused undelivered (%s)',
+ async reason => {
+ vi.mocked(requestGatewayForAgent).mockRejectedValue(
+ new JsonRpcGatewayError(reason, { code: 4001, data: { reason } })
+ )
+ seed()
+
+ await act(async () => {
+ expect(await handle.actions.redirectPrompt('next message')).toBe(false)
+ })
+
+ expect(requestGatewayForAgent).toHaveBeenCalledTimes(1)
+ const messages = handle.cache.sessionStateByRuntimeIdRef.current.get('rt-B')!.messages
+ expect(messages.map(message => message.id)).toEqual(['history-B'])
+ }
+)
+
+it('redirectPrompt still surfaces a refusal that may have reached the turn', async () => {
+ vi.mocked(requestGatewayForAgent).mockRejectedValue(
+ new JsonRpcGatewayError('permission_denied', { code: 4001, data: { reason: 'permission_denied' } })
+ )
+ seed()
+
+ await act(async () => {
+ await expect(handle.actions.redirectPrompt('next message')).rejects.toThrow('permission_denied')
+ })
+})
diff --git a/apps/shared/src/index.ts b/apps/shared/src/index.ts
index 0a360d911e1..c249a3e76d1 100644
--- a/apps/shared/src/index.ts
+++ b/apps/shared/src/index.ts
@@ -75,6 +75,7 @@ export {
DEFAULT_HEARTBEAT_DEADLINE_MS,
DEFAULT_HEARTBEAT_INTERVAL_MS,
type GatewayRequestId,
+ isUndeliveredCorrectionRefusal,
JSON_RPC_INTERNAL_ERROR,
JSON_RPC_METHOD_NOT_FOUND,
jsonRpcErrorFromFrame,
diff --git a/apps/shared/src/json-rpc-channel.ts b/apps/shared/src/json-rpc-channel.ts
index 3dc139784a6..b7bcfb61d8e 100644
--- a/apps/shared/src/json-rpc-channel.ts
+++ b/apps/shared/src/json-rpc-channel.ts
@@ -74,6 +74,17 @@ export class JsonRpcGatewayError extends Error {
}
}
+/** Refusals `session.steer` / `session.redirect` answer before the text reaches any agent
+ * (gateway/session_busy_controls.py::correct): the turn the client believed busy is gone or cannot
+ * take a correction, so the words are safe to admit as the next prompt — never retried as a control. */
+const UNDELIVERED_CORRECTION_REASONS = new Set(['execution_not_ready', 'stale_generation', 'unsupported_control'])
+
+export function isUndeliveredCorrectionRefusal(error: unknown): boolean {
+ const reason = error instanceof JsonRpcGatewayError ? (error.data as { reason?: unknown } | undefined)?.reason : null
+
+ return typeof reason === 'string' && UNDELIVERED_CORRECTION_REASONS.has(reason)
+}
+
/** JSON-RPC "method not found" (tui_gateway/server.py::dispatch `_err(rid, -32601, …)`). */
export const JSON_RPC_METHOD_NOT_FOUND = -32601