Skip to content

The agent that grows with you

test(desktop): cover queued approval server-request lifecycle

brooklyn!0d8f494a8862
diff --git a/apps/desktop/src/app/hooks/use-keybinds.ts b/apps/desktop/src/app/hooks/use-keybinds.ts
index 1dba2244f77..c545b09b991 100644
--- a/apps/desktop/src/app/hooks/use-keybinds.ts
+++ b/apps/desktop/src/app/hooks/use-keybinds.ts
@@ -451,6 +451,7 @@ export function useKeybinds(deps: KeybindRuntimeDeps): void {
const onBlur = () => {
releaseApprovalKey()
+
if (switcherActive()) {
closeSwitcher()
}
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.approval-timeout.test.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.approval-timeout.test.ts
index 72aa6e7d58b..945aacde4c9 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.approval-timeout.test.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.approval-timeout.test.ts
@@ -45,6 +45,7 @@ describe('approval request.cancel', () => {
it('timeout: tears the bar down and appends a plain system line with a Safety settings action', () => {
parkApproval()
+
const updateSessionState = vi.fn((_: string, updater: (s: { messages: unknown[] }) => unknown) =>
updater({ messages: [] })
)
@@ -52,7 +53,9 @@ describe('approval request.cancel', () => {
expect(handleInputRequestEvent(context('timeout', updateSessionState))).toBe(true)
expect($approvalRequests.get()['s1']).toBeUndefined()
- const next = updateSessionState.mock.results[0]?.value as { messages: { role: string; parts: { text: string }[] }[] }
+ const next = updateSessionState.mock.results[0]?.value as {
+ messages: { role: string; parts: { text: string }[] }[]
+ }
expect(next.messages).toHaveLength(1)
expect(next.messages[0].role).toBe('system')
expect(next.messages[0].parts[0].text).toMatch(/timed out/i)
@@ -65,6 +68,24 @@ describe('approval request.cancel', () => {
expect($routeRequest.get()?.path).toBe('/settings?tab=config:safety')
})
+ it('withdraws a queued request without dropping the front approval', () => {
+ setApprovalRequest({
+ sessionId: 's1',
+ command: 'first',
+ description: '',
+ requestId: 'front',
+ serverRequestId: 'srv-front'
+ })
+ parkApproval()
+ const updateSessionState = vi.fn()
+
+ expect(handleInputRequestEvent(context('answered', updateSessionState))).toBe(true)
+ expect($approvalRequests.get()['s1']?.requestId).toBe('front')
+ clearApprovalRequest('s1', 'front')
+ expect($approvalRequests.get()['s1']).toBeUndefined()
+ expect(updateSessionState).not.toHaveBeenCalled()
+ })
+
it('answered elsewhere: tears the bar down silently', () => {
parkApproval()
const updateSessionState = vi.fn()
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 ae610680dab..4b60698e73c 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,6 @@ import { normalizeConnectionRequest, setConnectionRequest, updateConnectionReque
import { dispatchNativeNotification } from '@/store/native-notifications'
import { notify } from '@/store/notifications'
import {
-
$secretRequests,
$sudoRequests,
$vaultCodeRequests,
@@ -122,7 +121,9 @@ export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {
return true
}
- const approval = sessionApprovalRequests(sessionId ?? null).get().find(request => request.serverRequestId === id)
+ const approval = sessionApprovalRequests(sessionId ?? null)
+ .get()
+ .find(request => request.serverRequestId === id)
if (approval) {
clearApprovalRequest(sessionId, approval.requestId)
@@ -148,7 +149,6 @@ 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 b61e3fa0ac1..886cd5cc9cf 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
@@ -181,7 +181,9 @@ const approval: Handler = ctx => {
void receiveApprovalRequest(null, {
// false only when a tirith warning forbids it; backend omits the field otherwise.
allowPermanent: p.allow_permanent !== false,
- choices: Array.isArray(p.choices) ? p.choices.filter((choice): choice is string => typeof choice === 'string') : undefined,
+ choices: Array.isArray(p.choices)
+ ? p.choices.filter((choice): choice is string => typeof choice === 'string')
+ : undefined,
command,
description,
// The approval queue's own id — `approval.pending` / `approval.received` / `approval.respond` key on it.
@@ -195,8 +197,14 @@ const approval: Handler = ctx => {
if (!request.replayed) {
dispatchNativeNotification({
actions: [
- { 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') }
+ {
+ 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/components/assistant-ui/thread/list.tsx b/apps/desktop/src/components/assistant-ui/thread/list.tsx
index e12d1a0b39f..91757ba4a95 100644
--- a/apps/desktop/src/components/assistant-ui/thread/list.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/list.tsx
@@ -1065,6 +1065,7 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
if (contentRef.current) {
resizeObserver.observe(contentRef.current)
}
+
void scrollToBottom('instant')
}
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 f49b8236aa1..5677f0a9c46 100644
--- a/apps/desktop/src/components/assistant-ui/tool/approval.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/tool/approval.test.tsx
@@ -262,7 +262,11 @@ describe('PendingApprovalStack', () => {
releaseApprovalKey()
expect(rpc.mock.calls.filter(([method]) => method === 'approval.respond')).toHaveLength(3)
- expect(sessionApprovalRequests('sess-2').get().map(request => request.requestId)).toEqual(['other'])
+ expect(
+ sessionApprovalRequests('sess-2')
+ .get()
+ .map(request => request.requestId)
+ ).toEqual(['other'])
expect((draft as HTMLInputElement).value).toBe('keep this')
})
@@ -270,21 +274,36 @@ describe('PendingApprovalStack', () => {
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' })
+ 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 })) })
+ 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))
+
+ 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 4e0ad07c190..6cb93e2fd63 100644
--- a/apps/desktop/src/components/assistant-ui/tool/approval.tsx
+++ b/apps/desktop/src/components/assistant-ui/tool/approval.tsx
@@ -27,8 +27,8 @@ import { $gateway } from '@/store/gateway'
import { reconnectAction } from '@/store/gateway-reconnect'
import { notifyError } from '@/store/notifications'
import {
- type ApprovalRequest,
answerApproval,
+ type ApprovalRequest,
clearApprovalRequest,
replayPendingApproval,
sessionApprovalRequests,
diff --git a/apps/desktop/src/components/assistant-ui/tool/fallback.tsx b/apps/desktop/src/components/assistant-ui/tool/fallback.tsx
index ee05ea69004..92c2d05c3ef 100644
--- a/apps/desktop/src/components/assistant-ui/tool/fallback.tsx
+++ b/apps/desktop/src/components/assistant-ui/tool/fallback.tsx
@@ -945,9 +945,16 @@ function useToolRun(startIndex: number, endIndex: number): ToolRunState {
* the whole of it until the user opens it. `ToolEmbedContext` is false so each
* row still owns its own chrome (timer / copy) when shown.
*/
-const ToolRun: FC<PropsWithChildren<{ endIndex: number; startIndex: number }>> = ({ children, endIndex, startIndex }) => {
+const ToolRun: FC<PropsWithChildren<{ endIndex: number; startIndex: number }>> = ({
+ children,
+ endIndex,
+ startIndex
+}) => {
const messageRunning = useAuiState(selectMessageRunning)
- const { completedAt, count, entryIds, key, live, startedAt, summary, approvalActivity } = useToolRun(startIndex, endIndex)
+ const { completedAt, count, entryIds, key, live, startedAt, summary, approvalActivity } = useToolRun(
+ startIndex,
+ endIndex
+ )
const sessionId = useStore(useSessionView().$runtimeId)
const approval = useStore(useMemo(() => sessionApprovalRequest(sessionId), [sessionId]))
const currentTurn = useAuiState(state => isCurrentTurnMessage(state.thread.messages, state.message.id))
diff --git a/apps/desktop/src/components/ui/card-stack.tsx b/apps/desktop/src/components/ui/card-stack.tsx
index bcd6537a681..7c7e9e87983 100644
--- a/apps/desktop/src/components/ui/card-stack.tsx
+++ b/apps/desktop/src/components/ui/card-stack.tsx
@@ -156,6 +156,7 @@ function StackCard({
if (index !== 0 || !content.current) {
return
}
+
const element = content.current
const measure = () => onMeasure(element.offsetHeight + 2)
measure()
@@ -180,6 +181,7 @@ function StackCard({
if (locked.current || !active) {
return
}
+
locked.current = true
setBusy(true)
setDragging(false)
@@ -262,6 +264,7 @@ function StackCard({
if (!start || start.id !== event.pointerId) {
return
}
+
const delta = event.clientX - start.x
if (!start.moved) {
@@ -299,6 +302,7 @@ function StackCard({
if (!start || start.id !== event.pointerId) {
return
}
+
const delta = event.clientX - start.x
const side = delta < 0 ? 'left' : 'right'
const threshold = Math.min(96, (node.current?.offsetWidth ?? 360) * 0.22)
diff --git a/apps/desktop/src/store/native-notifications.test.ts b/apps/desktop/src/store/native-notifications.test.ts
index b4d012d3cb2..b9358bb8d3f 100644
--- a/apps/desktop/src/store/native-notifications.test.ts
+++ b/apps/desktop/src/store/native-notifications.test.ts
@@ -351,7 +351,12 @@ describe('respondToApprovalAction', () => {
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(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')
diff --git a/apps/desktop/src/store/native-notifications.ts b/apps/desktop/src/store/native-notifications.ts
index b6548e09286..d7a71a40142 100644
--- a/apps/desktop/src/store/native-notifications.ts
+++ b/apps/desktop/src/store/native-notifications.ts
@@ -5,7 +5,13 @@ import { persistString, storedString } from '@/lib/storage'
import { $gateway } from './gateway'
import { withinNativeNotifyBaseline } from './notify-baseline'
-import { answerApproval, clearApprovalRequest, replayPendingApproval, sessionApprovalRequest, sessionApprovalRequests } 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'
@@ -368,12 +374,16 @@ export async function respondToApprovalAction(sessionId: null | string, actionId
}
try {
- const parked = sessionApprovalRequests(sessionId).get().find(request => request.requestId === requestId)
+ const parked = sessionApprovalRequests(sessionId)
+ .get()
+ .find(request => request.requestId === requestId)
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)) {
diff --git a/apps/desktop/src/store/prompts.test.ts b/apps/desktop/src/store/prompts.test.ts
index c0d984abdce..22dbddb5277 100644
--- a/apps/desktop/src/store/prompts.test.ts
+++ b/apps/desktop/src/store/prompts.test.ts
@@ -133,22 +133,72 @@ describe('approval prompt store', () => {
['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'])
+ expect(
+ sessionApprovalRequests('s1')
+ .get()
+ .map(request => request.requestId)
+ ).toEqual(['r1', 'r2'])
clearApprovalRequest('s1', 'r1')
expect($approvalRequest.get()?.requestId).toBe('r2')
})
+ it('preserves live server request routing for every queued replay entry', async () => {
+ for (const id of ['r1', 'r2']) {
+ await receiveApprovalRequest(null, {
+ command: id,
+ description: id,
+ requestId: id,
+ serverRequestId: `srv-${id}`,
+ sessionId: 's1'
+ })
+ }
+
+ await replayPendingApproval(
+ {
+ request: async () => ({
+ approvals: [
+ { command: 'r1', request_id: 'r1' },
+ { command: 'r2', request_id: 'r2' }
+ ]
+ })
+ },
+ 's1'
+ )
+ expect(
+ sessionApprovalRequests('s1')
+ .get()
+ .map(request => request.serverRequestId)
+ ).toEqual(['srv-r1', 'srv-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'])
+ 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')
+ 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' }] })
+ finish({
+ approvals: [
+ { command: 'first', request_id: 'r1' },
+ { command: 'second', request_id: 'r2' }
+ ]
+ })
await replay
expect(sessionApprovalRequests('s1').get()).toEqual([second])
clearAllPrompts('s1')
@@ -177,6 +227,12 @@ describe('approval prompt store', () => {
setApprovalRequest({ ...old, requestId: 'new' })
resolve({ approvals: [] })
await pending
+ expect(
+ sessionApprovalRequests('s1')
+ .get()
+ .map(request => request.requestId)
+ ).toEqual(['old', 'new'])
+ clearApprovalRequest('s1', 'old')
expect($approvalRequest.get()?.requestId).toBe('new')
})
diff --git a/apps/desktop/src/store/prompts.ts b/apps/desktop/src/store/prompts.ts
index f84092f3d61..cfb73106f8a 100644
--- a/apps/desktop/src/store/prompts.ts
+++ b/apps/desktop/src/store/prompts.ts
@@ -221,7 +221,10 @@ export interface VaultCodeRequest extends KeyedPrompt {
const vaultCode = keyedPromptStore<VaultCodeRequest>()
export const $approvalRequests = approval.$all
-export const $approvalRequest = computed([approval.$all, $activeSessionId], (all, activeId) => all[keyFor(activeId)] ?? null)
+export const $approvalRequest = computed(
+ [approval.$all, $activeSessionId],
+ (all, activeId) => all[keyFor(activeId)] ?? null
+)
export const setApprovalRequest = approval.set
export const clearApprovalRequest = approval.clear
@@ -230,7 +233,12 @@ export async function receiveApprovalRequest(gateway: ApprovalGateway | null, re
// request that already carries the same queue entry (it knows how to answer).
const current = $approvalQueues.get()[keyFor(request.sessionId)]?.find(item => item.requestId === request.requestId)
- if (current?.requestId && current.requestId === request.requestId && current.serverRequestId && !request.serverRequestId) {
+ if (
+ current?.requestId &&
+ current.requestId === request.requestId &&
+ current.serverRequestId &&
+ !request.serverRequestId
+ ) {
return
}