fix: make desktop approval routing reliable
Correlate approval requests, reject stale responses, replay pending approvals after reconnect or session resume, and preserve fail-closed timeout behavior.
This commit is contained in:
@@ -12,7 +12,7 @@ import { translateNow } from '@/i18n'
|
||||
import { type GatewayEventPayload, textPart } from '@/lib/chat-messages'
|
||||
import { coerceGatewayText, coerceThinkingText, normalizePersonalityValue } from '@/lib/chat-runtime'
|
||||
import { playCompletionSound } from '@/lib/completion-sound'
|
||||
import { resolveGatewayEventSessionId } from '@/lib/gateway-events'
|
||||
import { approvalReplaySessionId, resolveGatewayEventSessionId } from '@/lib/gateway-events'
|
||||
import { triggerHaptic } from '@/lib/haptics'
|
||||
import { modelOptionsQueryKey } from '@/lib/model-options'
|
||||
import { isProviderSetupErrorMessage } from '@/lib/provider-setup-errors'
|
||||
@@ -42,7 +42,13 @@ import { revealDesktopPane } from '@/store/pane-focus'
|
||||
import { flashPetActivity, markPetUnread, setPetActivity } from '@/store/pet'
|
||||
import { $activeGatewayProfile, normalizeProfileKey } from '@/store/profile'
|
||||
import { followActiveSessionCwd } from '@/store/projects'
|
||||
import { clearAllPrompts, setApprovalRequest, setSecretRequest, setSudoRequest } from '@/store/prompts'
|
||||
import {
|
||||
clearAllPrompts,
|
||||
receiveApprovalRequest,
|
||||
replayPendingApproval,
|
||||
setSecretRequest,
|
||||
setSudoRequest
|
||||
} from '@/store/prompts'
|
||||
import { recordAgentReaction } from '@/store/reactions-local'
|
||||
import {
|
||||
$currentCwd,
|
||||
@@ -316,6 +322,11 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
|
||||
const sessionId = route.sessionId
|
||||
const isActiveEvent = !!sessionId && sessionId === activeSessionIdRef.current
|
||||
|
||||
const replaySessionId = approvalReplaySessionId(event.type, activeSessionIdRef.current, sessionId)
|
||||
if (replaySessionId) {
|
||||
void replayPendingApproval($gateway.get(), replaySessionId).catch(() => undefined)
|
||||
}
|
||||
|
||||
// Mid-turn compaction does not emit another message.start. The first
|
||||
// model output or tool event proves summarization has finished and the
|
||||
// turn has resumed, so retire the phase label without waiting for the
|
||||
@@ -1024,7 +1035,7 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
|
||||
const command = typeof payload?.command === 'string' ? payload.command : ''
|
||||
const description = typeof payload?.description === 'string' ? payload.description : 'dangerous command'
|
||||
|
||||
setApprovalRequest({
|
||||
void receiveApprovalRequest($gateway.get(), {
|
||||
// false only when a tirith warning forbids it; backend omits the field otherwise.
|
||||
allowPermanent: payload?.allow_permanent !== false,
|
||||
choices: Array.isArray(payload?.choices)
|
||||
@@ -1032,9 +1043,10 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
|
||||
: undefined,
|
||||
command,
|
||||
description,
|
||||
requestId: typeof payload?.request_id === 'string' ? payload.request_id : undefined,
|
||||
sessionId: sessionId ?? null,
|
||||
smartDenied: payload?.smart_denied === true
|
||||
})
|
||||
}).catch(() => undefined)
|
||||
|
||||
if (sessionId) {
|
||||
updateSessionState(sessionId, state => ({ ...state, needsInput: true }))
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
type ApprovalRequest,
|
||||
clearApprovalRequest,
|
||||
registerApprovalInlineAnchor,
|
||||
replayPendingApproval,
|
||||
sessionApprovalInlineVisible,
|
||||
sessionApprovalRequest
|
||||
} from '@/store/prompts'
|
||||
@@ -144,16 +145,18 @@ const ApprovalBar: FC<{ request: ApprovalRequest; surface: 'floating' | 'inline'
|
||||
try {
|
||||
await gateway.request<{ resolved?: boolean }>('approval.respond', {
|
||||
choice,
|
||||
request_id: request.requestId,
|
||||
session_id: request.sessionId ?? undefined
|
||||
})
|
||||
triggerHaptic(choice === 'deny' ? 'cancel' : 'submit')
|
||||
clearApprovalRequest(request.sessionId)
|
||||
clearApprovalRequest(request.sessionId, request.requestId)
|
||||
void replayPendingApproval(gateway, request.sessionId).catch(() => undefined)
|
||||
} catch (error) {
|
||||
notifyError(error, copy.sendFailed)
|
||||
setSubmitting(null)
|
||||
}
|
||||
},
|
||||
[busy, copy.gatewayDisconnected, copy.sendFailed, gateway, request.sessionId]
|
||||
[busy, copy.gatewayDisconnected, copy.sendFailed, gateway, request.requestId, request.sessionId]
|
||||
)
|
||||
|
||||
// ⌘/Ctrl+Enter → Run, Esc → Reject.
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { gatewayEventRequiresSessionId, resolveGatewayEventSessionId } from './gateway-events'
|
||||
import { approvalReplaySessionId, gatewayEventRequiresSessionId, resolveGatewayEventSessionId } from './gateway-events'
|
||||
|
||||
describe('gateway event routing', () => {
|
||||
it('rehydrates pending approvals on reconnect ready and resumed session info', () => {
|
||||
expect(approvalReplaySessionId('gateway.ready', 'active-1', null)).toBe('active-1')
|
||||
expect(approvalReplaySessionId('session.info', 'active-1', 'routed-1')).toBe('routed-1')
|
||||
expect(approvalReplaySessionId('message.delta', 'active-1', 'routed-1')).toBeNull()
|
||||
})
|
||||
|
||||
it('drops only unscoped subagent events (genuinely background work)', () => {
|
||||
expect(gatewayEventRequiresSessionId('subagent.progress')).toBe(true)
|
||||
expect(gatewayEventRequiresSessionId('subagent.start')).toBe(true)
|
||||
|
||||
@@ -70,6 +70,20 @@ export interface GatewayEventSessionRoute {
|
||||
sessionId: null | string
|
||||
}
|
||||
|
||||
export function approvalReplaySessionId(
|
||||
eventType: string | undefined,
|
||||
activeSessionId: null | string,
|
||||
routedSessionId: null | string
|
||||
): null | string {
|
||||
if (eventType === 'gateway.ready') {
|
||||
return activeSessionId
|
||||
}
|
||||
if (eventType === 'session.info') {
|
||||
return routedSessionId
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve which runtime session owns a gateway event.
|
||||
*
|
||||
|
||||
@@ -10,6 +10,8 @@ import {
|
||||
clearApprovalRequest,
|
||||
clearSecretRequest,
|
||||
clearSudoRequest,
|
||||
receiveApprovalRequest,
|
||||
replayPendingApproval,
|
||||
setApprovalRequest,
|
||||
setSecretRequest,
|
||||
setSudoRequest
|
||||
@@ -67,6 +69,61 @@ describe('approval prompt store', () => {
|
||||
|
||||
expect($approvalRequest.get()?.allowPermanent).toBe(false)
|
||||
})
|
||||
|
||||
it('correlates clearing to the exact approval request id', () => {
|
||||
setApprovalRequest({ command: 'x', description: 'd', requestId: 'r1', sessionId: 's1' })
|
||||
|
||||
clearApprovalRequest('s1', 'stale')
|
||||
expect($approvalRequest.get()?.requestId).toBe('r1')
|
||||
clearApprovalRequest('s1', 'r1')
|
||||
expect($approvalRequest.get()).toBeNull()
|
||||
})
|
||||
|
||||
it('acknowledges an approval only after parking it', async () => {
|
||||
const calls: Array<[string, Record<string, unknown>]> = []
|
||||
const gateway = {
|
||||
request: async (method: string, params: Record<string, unknown>) => {
|
||||
calls.push([method, params])
|
||||
return { acknowledged: true }
|
||||
}
|
||||
}
|
||||
|
||||
await receiveApprovalRequest(gateway, {
|
||||
command: 'x',
|
||||
description: 'd',
|
||||
requestId: 'r1',
|
||||
sessionId: 's1'
|
||||
})
|
||||
|
||||
expect($approvalRequest.get()?.requestId).toBe('r1')
|
||||
expect(calls).toEqual([['approval.received', { request_id: 'r1', session_id: 's1' }]])
|
||||
})
|
||||
|
||||
it('replays and acknowledges the oldest unresolved approval after reconnect', async () => {
|
||||
const calls: Array<[string, Record<string, unknown>]> = []
|
||||
const gateway = {
|
||||
request: async (method: string, params: Record<string, unknown>) => {
|
||||
calls.push([method, params])
|
||||
if (method === 'approval.pending') {
|
||||
return {
|
||||
approvals: [
|
||||
{ command: 'first', description: 'd1', request_id: 'r1' },
|
||||
{ command: 'second', description: 'd2', request_id: 'r2' }
|
||||
]
|
||||
}
|
||||
}
|
||||
return { acknowledged: true }
|
||||
}
|
||||
}
|
||||
|
||||
await replayPendingApproval(gateway, 's1')
|
||||
|
||||
expect($approvalRequest.get()?.requestId).toBe('r1')
|
||||
expect(calls).toEqual([
|
||||
['approval.pending', { session_id: 's1' }],
|
||||
['approval.received', { request_id: 'r1', session_id: 's1' }]
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('sudo prompt store', () => {
|
||||
|
||||
@@ -67,18 +67,32 @@ function keyedPromptStore<T extends KeyedPrompt>(): PromptStore<T> {
|
||||
}
|
||||
}
|
||||
|
||||
// Approval is session-keyed on the backend (one in-flight approval per session,
|
||||
// resolved via approval.respond {choice, session_id}). It carries no request_id,
|
||||
// unlike sudo/secret which are _block()-style request/response.
|
||||
// Approval is session-keyed on the backend and correlated by `request_id` when
|
||||
// available (legacy ID-free responses remain FIFO-compatible). Resolved via
|
||||
// approval.respond {choice, request_id, session_id}.
|
||||
export interface ApprovalRequest extends KeyedPrompt {
|
||||
// false when the backend won't honor a permanent allow (tirith warning) → hide "Always allow".
|
||||
allowPermanent?: boolean
|
||||
choices?: string[]
|
||||
command: string
|
||||
description: string
|
||||
requestId?: string
|
||||
smartDenied?: boolean
|
||||
}
|
||||
|
||||
interface ApprovalGateway {
|
||||
request: (method: string, params: Record<string, unknown>) => Promise<unknown>
|
||||
}
|
||||
|
||||
interface PendingApprovalPayload {
|
||||
allow_permanent?: boolean
|
||||
choices?: unknown
|
||||
command?: unknown
|
||||
description?: unknown
|
||||
request_id?: unknown
|
||||
smart_denied?: boolean
|
||||
}
|
||||
|
||||
export interface SudoRequest extends KeyedPrompt {
|
||||
requestId: string
|
||||
}
|
||||
@@ -101,6 +115,39 @@ export const $approvalRequest = approval.$active
|
||||
export const setApprovalRequest = approval.set
|
||||
export const clearApprovalRequest = approval.clear
|
||||
|
||||
export async function receiveApprovalRequest(gateway: ApprovalGateway | null, request: ApprovalRequest): Promise<void> {
|
||||
setApprovalRequest(request)
|
||||
if (gateway && request.requestId && request.sessionId) {
|
||||
await gateway.request('approval.received', {
|
||||
request_id: request.requestId,
|
||||
session_id: request.sessionId
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function replayPendingApproval(gateway: ApprovalGateway | null, sessionId: string | null): Promise<void> {
|
||||
if (!gateway || !sessionId) {
|
||||
return
|
||||
}
|
||||
const rawResult = await gateway.request('approval.pending', {
|
||||
session_id: sessionId
|
||||
})
|
||||
const result = rawResult && typeof rawResult === 'object' ? (rawResult as { approvals?: PendingApprovalPayload[] }) : {}
|
||||
const pending = Array.isArray(result?.approvals) ? result.approvals[0] : undefined
|
||||
if (!pending || typeof pending.request_id !== 'string') {
|
||||
return
|
||||
}
|
||||
await receiveApprovalRequest(gateway, {
|
||||
allowPermanent: pending.allow_permanent !== false,
|
||||
choices: Array.isArray(pending.choices) ? pending.choices.filter(choice => typeof choice === 'string') : undefined,
|
||||
command: typeof pending.command === 'string' ? pending.command : '',
|
||||
description: typeof pending.description === 'string' ? pending.description : 'dangerous command',
|
||||
requestId: pending.request_id,
|
||||
sessionId,
|
||||
smartDenied: pending.smart_denied === true
|
||||
})
|
||||
}
|
||||
|
||||
/** The prompt request for one specific session — the tile counterpart of the
|
||||
* active-session `$*Request` views (same map, fixed key). */
|
||||
export const sessionApprovalRequest = (sessionId: string | null) =>
|
||||
|
||||
@@ -1311,6 +1311,64 @@ class TestApprovalTimeoutIsNotConsent:
|
||||
]
|
||||
assert hook_calls[-1][1]["choice"] == "notify_failed"
|
||||
|
||||
def test_pending_approval_is_replayable_and_acknowledged(self, monkeypatch):
|
||||
from tools import approval as mod
|
||||
|
||||
self._force_short_timeout(monkeypatch, seconds=2)
|
||||
notified = []
|
||||
mod.register_gateway_notify(self.SESSION_KEY, lambda data: notified.append(data))
|
||||
result_holder = {}
|
||||
|
||||
thread = threading.Thread(
|
||||
target=lambda: result_holder.setdefault(
|
||||
"result", mod.check_all_command_guards("rm -rf .git", "local")
|
||||
)
|
||||
)
|
||||
thread.start()
|
||||
for _ in range(200):
|
||||
if notified:
|
||||
break
|
||||
time.sleep(0.005)
|
||||
|
||||
request_id = notified[0]["request_id"]
|
||||
assert request_id
|
||||
assert mod.list_gateway_approvals(self.SESSION_KEY) == [notified[0]]
|
||||
assert mod.ack_gateway_approval(self.SESSION_KEY, request_id) is True
|
||||
assert mod.resolve_gateway_approval(
|
||||
self.SESSION_KEY, "once", request_id=request_id
|
||||
) == 1
|
||||
thread.join(timeout=5)
|
||||
assert result_holder["result"]["approved"] is True
|
||||
|
||||
def test_stale_request_id_cannot_resolve_current_approval(self, monkeypatch):
|
||||
from tools import approval as mod
|
||||
|
||||
self._force_short_timeout(monkeypatch, seconds=2)
|
||||
notified = []
|
||||
mod.register_gateway_notify(self.SESSION_KEY, lambda data: notified.append(data))
|
||||
result_holder = {}
|
||||
thread = threading.Thread(
|
||||
target=lambda: result_holder.setdefault(
|
||||
"result", mod.check_all_command_guards("rm -rf .git", "local")
|
||||
)
|
||||
)
|
||||
thread.start()
|
||||
for _ in range(200):
|
||||
if notified:
|
||||
break
|
||||
time.sleep(0.005)
|
||||
|
||||
request_id = notified[0]["request_id"]
|
||||
assert mod.resolve_gateway_approval(
|
||||
self.SESSION_KEY, "once", request_id="stale-request"
|
||||
) == 0
|
||||
assert mod.list_gateway_approvals(self.SESSION_KEY)
|
||||
assert mod.resolve_gateway_approval(
|
||||
self.SESSION_KEY, "deny", request_id=request_id
|
||||
) == 1
|
||||
thread.join(timeout=5)
|
||||
assert result_holder["result"]["approved"] is False
|
||||
|
||||
class TestTirithImportErrorFailOpenPolicy:
|
||||
"""Regression guard for #20733.
|
||||
|
||||
|
||||
@@ -274,6 +274,66 @@ def test_late_prompt_response_is_idempotent(server, method, value_key):
|
||||
assert response["result"] == {"status": "expired"}
|
||||
|
||||
|
||||
def test_approval_pending_replays_unresolved_requests(server, monkeypatch):
|
||||
from tools import approval
|
||||
|
||||
server._sessions["ui-1"] = {"session_key": "agent-1", "history": []}
|
||||
pending = [{"request_id": "req-1", "command": "danger"}]
|
||||
monkeypatch.setattr(approval, "list_gateway_approvals", lambda key: pending if key == "agent-1" else [])
|
||||
|
||||
response = server.handle_request(
|
||||
{"id": "r1", "method": "approval.pending", "params": {"session_id": "ui-1"}}
|
||||
)
|
||||
|
||||
assert response["result"] == {"approvals": pending}
|
||||
|
||||
|
||||
def test_approval_received_acknowledges_exact_request(server, monkeypatch):
|
||||
from tools import approval
|
||||
|
||||
server._sessions["ui-1"] = {"session_key": "agent-1", "history": []}
|
||||
calls = []
|
||||
monkeypatch.setattr(
|
||||
approval,
|
||||
"ack_gateway_approval",
|
||||
lambda key, request_id: calls.append((key, request_id)) or True,
|
||||
)
|
||||
|
||||
response = server.handle_request(
|
||||
{
|
||||
"id": "r2",
|
||||
"method": "approval.received",
|
||||
"params": {"session_id": "ui-1", "request_id": "req-1"},
|
||||
}
|
||||
)
|
||||
|
||||
assert response["result"] == {"acknowledged": True}
|
||||
assert calls == [("agent-1", "req-1")]
|
||||
|
||||
|
||||
def test_approval_response_correlates_request_id(server, monkeypatch):
|
||||
from tools import approval
|
||||
|
||||
server._sessions["ui-1"] = {"session_key": "agent-1", "history": []}
|
||||
calls = []
|
||||
monkeypatch.setattr(
|
||||
approval,
|
||||
"resolve_gateway_approval",
|
||||
lambda key, choice, **kwargs: calls.append((key, choice, kwargs)) or 1,
|
||||
)
|
||||
|
||||
response = server.handle_request(
|
||||
{
|
||||
"id": "r3",
|
||||
"method": "approval.respond",
|
||||
"params": {"session_id": "ui-1", "request_id": "req-1", "choice": "once"},
|
||||
}
|
||||
)
|
||||
|
||||
assert response["result"] == {"resolved": 1}
|
||||
assert calls == [("agent-1", "once", {"resolve_all": False, "request_id": "req-1"})]
|
||||
|
||||
|
||||
def test_clear_pending(server):
|
||||
ev = threading.Event()
|
||||
# _pending values are (sid, Event) tuples
|
||||
|
||||
+30
-5
@@ -22,6 +22,7 @@ import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unicodedata
|
||||
import uuid
|
||||
from typing import Optional
|
||||
from hermes_cli.config import cfg_get
|
||||
|
||||
@@ -2562,11 +2563,13 @@ def _denial_breaker_addendum(session_key: str) -> str:
|
||||
|
||||
class _ApprovalEntry:
|
||||
"""One pending dangerous-command approval inside a gateway session."""
|
||||
__slots__ = ("event", "data", "result", "reason")
|
||||
__slots__ = ("event", "data", "result", "reason", "acknowledged")
|
||||
|
||||
def __init__(self, data: dict):
|
||||
self.event = threading.Event()
|
||||
self.data = data # command, description, pattern_keys, …
|
||||
self.data = dict(data)
|
||||
self.data.setdefault("request_id", uuid.uuid4().hex)
|
||||
self.acknowledged = False
|
||||
self.result: Optional[str] = None # "once"|"session"|"always"|"deny"
|
||||
# Optional free-text reason supplied with an explicit deny
|
||||
# (``/deny <reason>``) so the agent can adapt instead of only
|
||||
@@ -2605,7 +2608,8 @@ def unregister_gateway_notify(session_key: str) -> None:
|
||||
|
||||
def resolve_gateway_approval(session_key: str, choice: str,
|
||||
resolve_all: bool = False,
|
||||
reason: Optional[str] = None) -> int:
|
||||
reason: Optional[str] = None,
|
||||
request_id: Optional[str] = None) -> int:
|
||||
"""Called by the gateway's /approve or /deny handler to unblock
|
||||
waiting agent thread(s).
|
||||
|
||||
@@ -2623,7 +2627,12 @@ def resolve_gateway_approval(session_key: str, choice: str,
|
||||
queue = _gateway_queues.get(session_key)
|
||||
if not queue:
|
||||
return 0
|
||||
if resolve_all:
|
||||
if request_id:
|
||||
targets = [entry for entry in queue if entry.data.get("request_id") == request_id]
|
||||
if not targets:
|
||||
return 0
|
||||
queue[:] = [entry for entry in queue if entry not in targets]
|
||||
elif resolve_all:
|
||||
targets = list(queue)
|
||||
queue.clear()
|
||||
else:
|
||||
@@ -2639,6 +2648,22 @@ def resolve_gateway_approval(session_key: str, choice: str,
|
||||
return len(targets)
|
||||
|
||||
|
||||
def list_gateway_approvals(session_key: str) -> list[dict]:
|
||||
"""Return replay-safe snapshots of unresolved approvals for one session."""
|
||||
with _lock:
|
||||
return [dict(entry.data) for entry in _gateway_queues.get(session_key, [])]
|
||||
|
||||
|
||||
def ack_gateway_approval(session_key: str, request_id: str) -> bool:
|
||||
"""Record that a client received a particular pending approval request."""
|
||||
with _lock:
|
||||
for entry in _gateway_queues.get(session_key, []):
|
||||
if entry.data.get("request_id") == request_id:
|
||||
entry.acknowledged = True
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def has_blocking_approval(session_key: str) -> bool:
|
||||
"""Check if a session has one or more blocking gateway approvals waiting."""
|
||||
with _lock:
|
||||
@@ -3930,7 +3955,7 @@ def _await_gateway_decision(session_key: str, notify_cb, approval_data: dict,
|
||||
|
||||
# Notify the user (bridges sync agent thread → async gateway)
|
||||
try:
|
||||
notify_cb(approval_data)
|
||||
notify_cb(dict(entry.data))
|
||||
except Exception as exc:
|
||||
logger.warning("Gateway approval notify failed: %s", exc)
|
||||
_drop_entry()
|
||||
|
||||
@@ -1347,6 +1347,38 @@ def _(rid, params: dict) -> dict:
|
||||
return _respond(rid, params, "value", allow_expired=True)
|
||||
|
||||
|
||||
@method("approval.pending")
|
||||
def _(rid, params: dict) -> dict:
|
||||
session, err = _sess(params, rid)
|
||||
if err:
|
||||
return err
|
||||
try:
|
||||
from tools.approval import list_gateway_approvals
|
||||
|
||||
return _ok(rid, {"approvals": list_gateway_approvals(session["session_key"])})
|
||||
except Exception as e:
|
||||
return _err(rid, 5004, str(e))
|
||||
|
||||
|
||||
@method("approval.received")
|
||||
def _(rid, params: dict) -> dict:
|
||||
session, err = _sess(params, rid)
|
||||
if err:
|
||||
return err
|
||||
request_id = params.get("request_id")
|
||||
if not isinstance(request_id, str) or not request_id:
|
||||
return _err(rid, 4006, "request_id required")
|
||||
try:
|
||||
from tools.approval import ack_gateway_approval
|
||||
|
||||
return _ok(
|
||||
rid,
|
||||
{"acknowledged": ack_gateway_approval(session["session_key"], request_id)},
|
||||
)
|
||||
except Exception as e:
|
||||
return _err(rid, 5004, str(e))
|
||||
|
||||
|
||||
@method("approval.respond")
|
||||
def _(rid, params: dict) -> dict:
|
||||
session, err = _sess(params, rid)
|
||||
@@ -1362,6 +1394,7 @@ def _(rid, params: dict) -> dict:
|
||||
session["session_key"],
|
||||
params.get("choice", "deny"),
|
||||
resolve_all=params.get("all", False),
|
||||
request_id=params.get("request_id"),
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user