Skip to content

The agent that grows with you

feat(desktop): keep live approval stacks stable during execution

brooklyn!cb95c278af54
diff --git a/apps/desktop/DESIGN.md b/apps/desktop/DESIGN.md
index 54c241f3b3c..84f2cea564c 100644
--- a/apps/desktop/DESIGN.md
+++ b/apps/desktop/DESIGN.md
@@ -86,12 +86,23 @@ Menus and popovers use their own shared `shadow-md` +
dashed targets and local blur. These are semantic surface classes, not licenses
for call-site shadow or border inventions.
-**Queued cards:** `CardStack` (`src/components/ui/card-stack.tsx`) shows one
-interactive front card and at most two inert, inset back edges. Queue length
-changes the count, not the pile height. Approvals rise above the composer;
-top-center toasts stack downward and bottom-right toasts upward. Pass the
-existing surface tokens/radius; the primitive owns only depth. Hidden cards
-have no live controls. Toasts may explicitly expand to the full list.
+**Queued cards:** `CardStack` (`src/components/ui/card-stack.tsx`) consumes a live,
+keyed list, retaining the current item when more arrive. Inline and floating
+approvals and both toast placements share its gesture handling and geometry.
+The Cursor-reference treatment uses one 96%-scale silhouette 7px above the
+front, 220ms promotion, and 180ms upward clearance; no rotation or lateral throw
+on button/keyboard decisions. Consumers supply the existing surface tokens and
+own the exact-request response. Gestures never grant approval. Departing cards
+are immediately inert; toasts can expand to the full live list. One persistent
+transcript-level host owns approvals, independent of tool rows and assistant
+message boundaries. Prepared approvals can precede tool.start: execution must
+not relocate or remount the stack. While approvals remain, a real activity line
+above the cards changes from awaiting approval to current-turn command status;
+represented execution rows appear only when explicitly expanded. Empty text
+continuations must not introduce paragraph gaps. Keep inline approvals beside
+the conversation and let genuine content scroll normally; do not inject padding
+or write scroll offsets to pin the decision. Preview this order with delayed
+start and completion events, not pre-created tool rows.
## Window glass
diff --git a/apps/desktop/src/app/chat/scroll-to-bottom-button.tsx b/apps/desktop/src/app/chat/scroll-to-bottom-button.tsx
index 589e50e1772..d5fa31717e2 100644
--- a/apps/desktop/src/app/chat/scroll-to-bottom-button.tsx
+++ b/apps/desktop/src/app/chat/scroll-to-bottom-button.tsx
@@ -26,12 +26,8 @@ import { useComposerSurfaceId } from './composer/scope'
* away from the bottom, with an animated count of messages below the viewport.
* Clicking re-arms sticky-bottom and pins the viewport.
*
- * When the turn is BLOCKED on an approval, this same control morphs into an
- * "Approval needed" pill — the only response surface is the inline Run/Reject
- * bar on the parked tool row, which is always the bottom-most content, so the
- * existing scroll-to-bottom action lands the user right on it. One control, no
- * collision, no second scroll path (native scrollIntoView would scroll
- * overflow:hidden ancestors that can't scroll back and wreck the layout).
+ * While approvals are pending, relabel this control to lead back to the
+ * transcript-owned stack using the existing scroll path.
*
* Enter/exit motion lives in styles.css under `.thread-jump-button` — a
* directional scale (contract in from 1.1, contract out to 0.9) keyed off
diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
index 22e02c5ce43..b9d695ecc3b 100644
--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
@@ -26,6 +26,7 @@ import { ResponseLoadingIndicator, TurnActivityIndicator } from '@/components/as
import { MessageTimelineTimestamp } from '@/components/assistant-ui/thread/timeline-timestamp'
import { useMessageReactions, useTapbackDoubleClick } from '@/components/assistant-ui/thread/use-message-reactions'
import { AGENT_MESSAGE_RE } from '@/components/assistant-ui/thread/user-message'
+import { isApprovalActivity, isCurrentTurnMessage } from '@/components/assistant-ui/tool/approval-activity'
import { TooltipIconButton } from '@/components/assistant-ui/tooltip-icon-button'
import { formatElapsed } from '@/components/chat/activity-timer'
import { PreviewAttachment } from '@/components/chat/preview-attachment'
@@ -55,6 +56,7 @@ import { openFreeTierSignIn } from '@/store/free-tier-sign-in'
import { notifyError } from '@/store/notifications'
import { startManualProviderOAuth } from '@/store/onboarding'
import { $activeGatewayProfile, normalizeProfileKey, requestFreshSession } from '@/store/profile'
+import { sessionApprovalRequest } from '@/store/prompts'
import { requestSendDiagnostics } from '@/store/send-diagnostics'
import { $connection, $currentModel, setModelPickerOpen } from '@/store/session'
import { sessionTileDelegate } from '@/store/session-states'
@@ -198,6 +200,18 @@ const AssistantMessageBody: FC<AssistantMessageProps & { collapsedNotice?: null
// the markdown part and the tiny status leaves — not the footer, the
// preview block, or this root.
const hasVisibleText = useAuiState(s => contentHasVisibleText(s.message.content))
+ const sessionId = useStore(useSessionView().$runtimeId)
+ const approval = useStore(useMemo(() => sessionApprovalRequest(sessionId), [sessionId]))
+
+ const activityOnly = useAuiState(
+ state =>
+ isCurrentTurnMessage(state.thread.messages, state.message.id) &&
+ state.message.content.some(part => part.type === 'tool-call' && isApprovalActivity(part)) &&
+ state.message.content.every(
+ part => (part.type === 'tool-call' && isApprovalActivity(part)) || (part.type === 'text' && !part.text.trim())
+ )
+ )
+
// Sealed mid-turn commentary keeps its text but not the footer, so a
// tool-heavy turn doesn't grow a copy/refresh bar per paragraph (see
// ChatMessage.interim).
@@ -239,6 +253,7 @@ const AssistantMessageBody: FC<AssistantMessageProps & { collapsedNotice?: null
'group flex w-full min-w-0 max-w-full flex-col gap-0 self-start overflow-hidden',
collapsedNotice && 'pb-(--conversation-turn-gap)'
)}
+ data-approval-activity-only={approval && activityOnly ? '' : undefined}
data-role="assistant"
data-slot="aui_assistant-message-root"
// Collapsed inter-agent rows never carried the tapback listener; keeping
diff --git a/apps/desktop/src/components/assistant-ui/thread/list.tsx b/apps/desktop/src/components/assistant-ui/thread/list.tsx
index f6efe8b0c26..e12d1a0b39f 100644
--- a/apps/desktop/src/components/assistant-ui/thread/list.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/list.tsx
@@ -42,6 +42,7 @@ import {
import { isSecondaryWindow } from '@/store/windows'
import { MessageRenderBoundary } from '../message-render-boundary'
+import { PendingApprovalStack } from '../tool/approval'
import { responseMessageRole, ResponseMessages } from './response-group'
import { resolveShowEarlierAction, shouldAutoShowEarlier, useTranscriptWindow } from './transcript-window'
@@ -1341,40 +1342,41 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
data-slot="aui_thread-viewport"
ref={scrollRef as React.RefCallback<HTMLDivElement>}
>
- {renderEmpty ? (
- <div
- className="mx-auto grid h-full w-full max-w-(--composer-width) grid-rows-[minmax(0,1fr)_auto] min-w-0 gap-(--conversation-turn-gap) px-6 py-8"
- data-slot="aui_thread-content"
- >
- {emptyPlaceholder}
- </div>
- ) : (
- <div
- className={cn('mx-auto flex w-full max-w-(--composer-width) min-w-0 flex-col px-6', threadContentTopPad)}
- data-slot="aui_thread-content"
- ref={contentRef as React.RefCallback<HTMLDivElement>}
- >
- {(hiddenCount > 0 || olderAvailable) && (
- <button
- className="mx-auto mb-(--conversation-turn-gap) rounded-full border border-border/65 bg-(--composer-fill) px-3 py-1 text-xs text-muted-foreground hover:text-foreground"
- onClick={showEarlier}
- type="button"
- >
- {t.assistant.thread.showEarlier}
- </button>
- )}
- {rows}
- {loadingIndicator}
- {clampToComposer && (
- <div
- aria-hidden="true"
- className="shrink-0"
- data-slot="aui_composer-clearance"
- style={{ height: 'var(--thread-last-message-clearance)' }}
- />
- )}
- </div>
- )}
+ <div
+ className={cn(
+ 'mx-auto flex min-h-full w-full max-w-(--composer-width) min-w-0 flex-col px-6',
+ renderEmpty ? 'py-8' : threadContentTopPad
+ )}
+ data-slot="aui_thread-content"
+ ref={contentRef as React.RefCallback<HTMLDivElement>}
+ >
+ {!renderEmpty && (hiddenCount > 0 || olderAvailable) && (
+ <button
+ className="mx-auto mb-(--conversation-turn-gap) rounded-full border border-border/65 bg-(--composer-fill) px-3 py-1 text-xs text-muted-foreground hover:text-foreground"
+ onClick={showEarlier}
+ type="button"
+ >
+ {t.assistant.thread.showEarlier}
+ </button>
+ )}
+ {renderEmpty ? (
+ <div className="grid flex-1 grid-rows-[minmax(0,1fr)_auto] gap-(--conversation-turn-gap)">
+ {emptyPlaceholder}
+ </div>
+ ) : (
+ rows
+ )}
+ <PendingApprovalStack />
+ {!renderEmpty && loadingIndicator}
+ {!renderEmpty && clampToComposer && (
+ <div
+ aria-hidden="true"
+ className="shrink-0"
+ data-slot="aui_composer-clearance"
+ style={{ height: 'var(--thread-last-message-clearance)' }}
+ />
+ )}
+ </div>
</div>
</div>
)
diff --git a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx
index 8ec340639c2..6e336ced3a2 100644
--- a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx
@@ -3,7 +3,8 @@ import {
type TextMessagePartProps,
type ToolCallMessagePartProps,
useAuiState,
- useMessagePartReasoning
+ useMessagePartReasoning,
+ useMessagePartText
} from '@assistant-ui/react'
import { useStore } from '@nanostores/react'
import { type ComponentProps, type FC, type ReactNode, useEffect, useRef, useState } from 'react'
@@ -140,12 +141,22 @@ const PREVIEW_RELOCK_THRESHOLD_PX = 24
type TimelineTextPartProps = TextMessagePartProps & { completedAt?: number; timestamp?: number }
-const TimelineMarkdownText: FC<TimelineTextPartProps> = ({ completedAt, timestamp }) => (
- <>
- <TimelineTimestamp className="mb-0.5 block" completedAt={completedAt} timestamp={timestamp} />
- <MarkdownText />
- </>
-)
+const TimelineMarkdownText: FC<TimelineTextPartProps> = ({ completedAt, timestamp }) => {
+ const { text } = useMessagePartText()
+
+ // assistant-ui adds an empty continuation after a tool starts. It is not
+ // prose yet and must not create paragraph spacing above pending approvals.
+ if (!text.trim()) {
+ return null
+ }
+
+ return (
+ <>
+ <TimelineTimestamp className="mb-0.5 block" completedAt={completedAt} timestamp={timestamp} />
+ <MarkdownText />
+ </>
+ )
+}
const ThinkingDisclosure: FC<{
children: ReactNode
diff --git a/apps/desktop/src/components/assistant-ui/tool/approval-activity.ts b/apps/desktop/src/components/assistant-ui/tool/approval-activity.ts
new file mode 100644
index 00000000000..16a37629543
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/tool/approval-activity.ts
@@ -0,0 +1,21 @@
+import type { ToolCallLike } from './run-summary'
+
+/** These calls render as activity, not file diffs or other deliverable cards. */
+export const isApprovalActivity = (tool: ToolCallLike): boolean =>
+ tool.toolName === 'terminal' || tool.toolName === 'execute_code'
+
+export function isCurrentTurnMessage(messages: readonly { id: string; role: string }[], messageId: string): boolean {
+ for (let index = messages.length - 1; index >= 0; index--) {
+ const message = messages[index]
+
+ if (message.id === messageId) {
+ return message.role === 'assistant'
+ }
+
+ if (message.role === 'user') {
+ return false
+ }
+ }
+
+ return false
+}
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 ab814031699..f49b8236aa1 100644
--- a/apps/desktop/src/components/assistant-ui/tool/approval.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/tool/approval.test.tsx
@@ -1,4 +1,6 @@
-import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import { AssistantRuntimeProvider, type ThreadMessage, useExternalStoreRuntime } from '@assistant-ui/react'
+import { act, cleanup, fireEvent, render as renderUi, screen, waitFor, within } from '@testing-library/react'
+import type { ReactNode } from 'react'
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import type { HermesGateway } from '@/hermes'
@@ -7,24 +9,23 @@ import { $gateway } from '@/store/gateway'
import { $approvalRequest, clearAllPrompts, sessionApprovalRequests, setApprovalRequest } from '@/store/prompts'
import { hasOpenServerRequest, rememberServerRequest, resetServerRequestsForTests } from '@/store/server-requests'
import { $activeSessionId } from '@/store/session'
+import { stubMenuDomApis, stubResizeObserver } from '@/test/jsdom'
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.
+function Runtime({ children }: { children: ReactNode }) {
+ const runtime = useExternalStoreRuntime<ThreadMessage>({ messages: [], isRunning: false, onNew: async () => {} })
+
+ return <AssistantRuntimeProvider runtime={runtime}>{children}</AssistantRuntimeProvider>
+}
+
+function render(children: ReactNode) {
+ return renderUi(<Runtime>{children}</Runtime>)
+}
+
beforeAll(() => {
- const proto = window.HTMLElement.prototype as unknown as Record<string, () => unknown>
-
- const stubs: Record<string, () => unknown> = {
- hasPointerCapture: () => false,
- releasePointerCapture: () => undefined,
- scrollIntoView: () => undefined,
- setPointerCapture: () => undefined
- }
-
- for (const [name, fn] of Object.entries(stubs)) {
- proto[name] ??= fn
- }
+ stubMenuDomApis()
+ stubResizeObserver()
})
function setRequest(
@@ -65,10 +66,12 @@ afterEach(() => {
})
describe('PendingApprovalStack', () => {
- it('renders nothing when there is no pending approval', () => {
+ it('retains an empty host without consuming keyboard input', () => {
const { container } = render(<PendingApprovalStack />)
- expect(container.innerHTML).toBe('')
+ expect(container.querySelector('[data-approval-stack]')).not.toBeNull()
+ expect(container.querySelector('[data-stack-active="true"]')).toBeNull()
+ expect(handleApprovalKey(new KeyboardEvent('keydown', { key: 'Enter', cancelable: true }))).toBe(false)
})
it('renders run/reject controls for a pending terminal command', () => {
@@ -114,6 +117,7 @@ describe('PendingApprovalStack', () => {
await waitFor(() => {
expect(request).toHaveBeenCalledWith('approval.respond', {
+ all: false,
choice: 'once',
request_id: 'apr-1',
session_id: 'sess-1'
@@ -122,18 +126,13 @@ describe('PendingApprovalStack', () => {
expect($approvalRequest.get()).toBeNull()
})
- it('reveals the full command inline when the Command toggle is clicked', () => {
+ it('keeps the full command in a bounded scrollable body', () => {
const longCommand = 'python -c "' + 'x'.repeat(400) + '"'
setRequest(longCommand)
render(<PendingApprovalStack />)
- // 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).className).not.toContain('truncate')
- expect(screen.getByRole('button', { name: /Command/ }).getAttribute('aria-expanded')).toBe('true')
+ expect(screen.getByText(longCommand).className).toContain('max-h-40')
+ expect(screen.getByText(longCommand).className).toContain('overflow-auto')
})
it('answers the live approval request with {choice: "deny"} on Reject', async () => {
@@ -209,9 +208,13 @@ describe('PendingApprovalStack', () => {
rpc.mockRejectedValueOnce(new Error('Disconnected'))
setRequest('first')
render(<PendingApprovalStack />)
- act(() => { handleApprovalKey(new KeyboardEvent('keydown', { key: 'Enter', cancelable: true })) })
+ 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 })) })
+ 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/ }))
@@ -221,13 +224,20 @@ describe('PendingApprovalStack', () => {
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" /></>)
+ render(
+ <>
+ <PendingApprovalStack />
+ <input aria-label="Draft" />
+ </>
+ )
expect(screen.getAllByRole('button', { name: /Run/ })).toHaveLength(1)
- expect(document.querySelectorAll('[data-slot="card-stack-edge"]')).toHaveLength(2)
+ expect(document.querySelectorAll('[data-slot="card-stack-edge"]')).toHaveLength(1)
const draft = screen.getByRole('textbox')
fireEvent.change(draft, { target: { value: 'keep this' } })
const typing = new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true })
@@ -236,12 +246,21 @@ describe('PendingApprovalStack', () => {
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'
- }))
+ act(() => {
+ handleApprovalKey(new KeyboardEvent('keydown', { key: 'Enter', repeat: index > 0, cancelable: true }))
+ })
+ await waitFor(() =>
+ expect(rpc).toHaveBeenCalledWith('approval.respond', {
+ all: false,
+ choice: 'once',
+ request_id: id,
+ session_id: 'sess-1'
+ })
+ )
await waitFor(() => expect(screen.queryAllByRole('button', { name: /Run/ })).toHaveLength(index === 2 ? 0 : 1))
}
+
+ releaseApprovalKey()
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')
diff --git a/apps/desktop/src/components/assistant-ui/tool/approval.tsx b/apps/desktop/src/components/assistant-ui/tool/approval.tsx
index 4b7fd7f335c..4e0ad07c190 100644
--- a/apps/desktop/src/components/assistant-ui/tool/approval.tsx
+++ b/apps/desktop/src/components/assistant-ui/tool/approval.tsx
@@ -1,12 +1,14 @@
'use client'
+import { useAuiState } from '@assistant-ui/react'
import { useStore } from '@nanostores/react'
-import { type FC, useCallback, useMemo, useRef, useState } from 'react'
+import { createContext, type FC, useCallback, useContext, useMemo, useRef, useState } from 'react'
import { useSessionView } from '@/app/chat/session-view'
-import { WIDGET_SHELL_CLASS } from '@/components/chat/widget-shell'
+import { SCAFFOLD_LABEL_CLASS, ScaffoldRow } from '@/components/chat/scaffold-row'
import { Button } from '@/components/ui/button'
-import { CardStack } from '@/components/ui/card-stack'
+import { CardStack, type CardStackAction } from '@/components/ui/card-stack'
+import { Codicon } from '@/components/ui/codicon'
import {
Dialog,
DialogContent,
@@ -18,7 +20,7 @@ import {
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { useI18n } from '@/i18n'
import { triggerHaptic } from '@/lib/haptics'
-import { AlertCircle, ChevronDown, Loader2 } from '@/lib/icons'
+import { ChevronDown, Loader2 } from '@/lib/icons'
import { releaseApprovalKey } from '@/lib/keybinds/approval-keys'
import { cn } from '@/lib/utils'
import { $gateway } from '@/store/gateway'
@@ -29,43 +31,173 @@ import {
answerApproval,
clearApprovalRequest,
replayPendingApproval,
- sessionApprovalRequests
+ sessionApprovalRequests,
+ sessionApprovalStackSize
} from '@/store/prompts'
+import { setToolDisclosureOpen } from '@/store/tool-view'
+
+import { isApprovalActivity } from './approval-activity'
+import { toolEntryDisclosureId } from './fallback-model/targets'
+import { isToolCallPart, summarizeToolRun } from './run-summary'
-// 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 ApprovalPlacementContext = createContext<'inline' | 'floating'>('inline')
+// One transcript-owned host for the session. Execution rows never mount,
+// register or re-home this queue, including the first delayed tool.start.
export const PendingApprovalStack: FC = () => {
const { t } = useI18n()
+ const placement = useContext(ApprovalPlacementContext)
const sessionId = useStore(useSessionView().$runtimeId)
const requests = useStore(useMemo(() => sessionApprovalRequests(sessionId), [sessionId]))
-
- if (!requests.length) {
- return null
- }
+ const total = useStore(useMemo(() => sessionApprovalStackSize(sessionId), [sessionId]))
return (
<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"
+ className={cn(
+ 'min-w-0 has-[[data-stack-key]]:py-2',
+ placement === 'floating' ? 'sticky bottom-4 z-10 mt-auto w-full max-w-xl self-center' : 'w-full max-w-xl'
+ )}
+ data-approval-placement={placement}
data-approval-stack=""
data-slot="tool-approval-stack"
- style={{ bottom: 'calc(var(--composer-measured-height) + 0.875rem)' }}
>
- <div className="pointer-events-auto">
- <ApprovalCard key={requests[0].requestId ?? 'legacy'} request={requests[0]} count={requests.length} />
- </div>
+ {requests.length > 0 && <ApprovalActivity floating={placement === 'floating'} />}
+ <ApprovalQueue floating={placement === 'floating'} requests={requests} total={total} />
</section>
)
}
+function ApprovalActivity({ floating }: { floating: boolean }) {
+ const { t } = useI18n()
+
+ const summary = useAuiState(state => {
+ const start = state.thread.messages.findLastIndex(message => message.role === 'user')
+
+ const tools = state.thread.messages
+ .slice(start + 1)
+ .filter(message => message.role === 'assistant')
+ .flatMap(message => message.content.filter(isToolCallPart).filter(isApprovalActivity))
+
+ return tools.length
+ ? summarizeToolRun(
+ tools,
+ tools.some(tool => tool.result === undefined)
+ )
+ : ''
+ })
+
+ const disclosureIds = useAuiState(state => {
+ const start = state.thread.messages.findLastIndex(message => message.role === 'user')
+
+ return state.thread.messages
+ .slice(start + 1)
+ .filter(message => message.role === 'assistant')
+ .flatMap(message =>
+ message.content
+ .filter(isToolCallPart)
+ .filter(isApprovalActivity)
+ .map(tool => toolEntryDisclosureId(message.id, tool))
+ )
+ .join('\n')
+ })
+
+ return (
+ <div
+ className={cn('mb-1 min-w-0', floating && 'rounded bg-(--ui-chat-surface-background)')}
+ data-approval-activity=""
+ data-glass-opaque={floating ? '' : undefined}
+ data-tool-summary=""
+ >
+ <ScaffoldRow
+ onToggle={
+ disclosureIds
+ ? () => {
+ for (const id of disclosureIds.split('\n')) {
+ setToolDisclosureOpen(id, true)
+ }
+ }
+ : undefined
+ }
+ open={false}
+ >
+ <span className={cn(SCAFFOLD_LABEL_CLASS, 'truncate')}>{summary || t.assistant.approval.jumpToApproval}</span>
+ </ScaffoldRow>
+ </div>
+ )
+}
+
+async function sendApproval(request: ApprovalRequest, choice: ApprovalChoice) {
+ const gateway = $gateway.get()
+
+ if (!gateway) {
+ throw new Error('Gateway disconnected')
+ }
+
+ if (
+ !sessionApprovalRequests(request.sessionId)
+ .get()
+ .some(item => item.requestId === request.requestId)
+ ) {
+ return
+ }
+
+ await answerApproval(gateway, request, choice)
+ triggerHaptic(choice === 'deny' ? 'cancel' : 'submit')
+ clearApprovalRequest(request.sessionId, request.requestId)
+ void replayPendingApproval(gateway, request.sessionId).catch(() => undefined)
+}
+
+export function ApprovalQueue({
+ requests,
+ total,
+ floating = false
+}: {
+ requests: ApprovalRequest[]
+ total: number
+ floating?: boolean
+}) {
+ const { t } = useI18n()
+
+ return (
+ <CardStack
+ getKey={request => request.requestId ?? 'legacy'}
+ items={requests}
+ onSwipe={(request, _side, action) => {
+ void action
+ .depart(() => sendApproval(request, 'deny'))
+ .catch(error => {
+ releaseApprovalKey()
+ notifyError(error, t.assistant.approval.sendFailed)
+ })
+ }}
+ surfaceClassName={cn(
+ 'rounded-xl border bg-(--ui-chat-surface-background)',
+ floating ? 'border-(--stroke-nous) shadow-nous' : 'border-(--ui-stroke-secondary)'
+ )}
+ swipeDirections={['left']}
+ >
+ {(request, action) => (
+ <ApprovalCard
+ position={total - requests.length + requests.indexOf(request) + 1}
+ request={request}
+ stack={action}
+ total={total}
+ />
+ )}
+ </CardStack>
+ )
+}
+
interface ApprovalCardProps {
request: ApprovalRequest
- count: number
+ total: number
+ position: number
+ stack: CardStackAction
}
-const ApprovalCard: FC<ApprovalCardProps> = ({ request, count }) => {
+const ApprovalCard: FC<ApprovalCardProps> = ({ request, total, position, stack }) => {
const { t } = useI18n()
const copy = t.assistant.approval
const gateway = useStore($gateway)
@@ -74,8 +206,9 @@ const ApprovalCard: FC<ApprovalCardProps> = ({ request, count }) => {
// "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)
- const [showCommand, setShowCommand] = useState(false)
- const busy = submitting !== null
+
+ const present = stack.active
+ const busy = submitting !== null || !present || stack.busy
// false when the backend won't honor a permanent allow (tirith warning) → hide "Always allow".
const allowPermanent = request.allowPermanent !== false
const choices = request.choices ?? (request.smartDenied ? ['once', 'deny'] : undefined)
@@ -87,6 +220,7 @@ const ApprovalCard: FC<ApprovalCardProps> = ({ request, count }) => {
const respond = useCallback(
async (choice: ApprovalChoice) => {
const pending = sessionApprovalRequests(request.sessionId).get()
+
if (submittingRef.current || !pending.some(item => item.requestId === request.requestId)) {
return
}
@@ -101,13 +235,7 @@ const ApprovalCard: FC<ApprovalCardProps> = ({ request, count }) => {
setSubmitting(choice)
try {
- // Live prompt: the response frame rides the socket the request came on
- // (the owner backend by construction). Restored prompt: queue-level
- // `approval.respond`, owner-routed (#91684 client half).
- await answerApproval(gateway, request, choice)
- triggerHaptic(choice === 'deny' ? 'cancel' : 'submit')
- clearApprovalRequest(request.sessionId, request.requestId)
- void replayPendingApproval(gateway, request.sessionId).catch(() => undefined)
+ await stack.depart(() => sendApproval(request, choice))
} catch (error) {
releaseApprovalKey()
notifyError(error, copy.sendFailed)
@@ -115,68 +243,69 @@ const ApprovalCard: FC<ApprovalCardProps> = ({ request, count }) => {
setSubmitting(null)
}
},
- [copy.gatewayDisconnected, copy.sendFailed, gateway, request]
+ [copy.gatewayDisconnected, copy.sendFailed, gateway, request, stack]
)
return (
- <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>
- </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>
+ <article
+ aria-hidden={!present || undefined}
+ className="min-w-0"
+ data-request-id={request.requestId}
+ data-slot="tool-approval-card"
+ inert={!present}
+ >
+ <div className="flex items-center gap-2 px-2.5 pt-2 text-xs text-(--ui-text-secondary)">
+ <Codicon name="terminal" size="0.875rem" />
+ <span>{copy.command}</span>
+ {total > 1 && (
+ <span className="ml-auto text-[0.6875rem] tabular-nums text-(--ui-text-tertiary)">
+ {position} / {total}
+ </span>
+ )}
+ </div>
+ {hasCommand && (
+ <pre className="m-0 max-h-40 overflow-auto whitespace-pre-wrap break-words px-2.5 py-2 font-mono text-xs leading-relaxed text-(--ui-text-primary)">
+ {request.command}
+ </pre>
+ )}
+ <div className="flex items-center justify-end gap-1.5 px-2 pb-2 pt-1" data-slot="tool-approval-actions">
+ <Button data-approval-deny="" disabled={busy} onClick={() => void respond('deny')} size="sm" variant="text">
+ {submitting === 'deny' ? <Loader2 className="size-3 animate-spin" /> : copy.reject}
</Button>
{hasMoreOptions && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <Button aria-label={copy.moreOptions} disabled={busy} size="icon-xs" variant="ghost">
- <ChevronDown />
+ <Button aria-label={copy.moreOptions} disabled={busy} size="sm" variant="secondary">
+ {copy.alwaysAllowMenu}
+ <ChevronDown className="size-3" />
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent align="start" className="min-w-44">
+ <DropdownMenuContent align="end" className="min-w-44">
{allowSession && (
<DropdownMenuItem onSelect={() => void respond('session')}>{copy.allowSession}</DropdownMenuItem>
)}
{allowAlways && (
- <DropdownMenuItem onSelect={() => setTimeout(() => setConfirmAlways(true), 0)}>
+ <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>
)}
- <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 data-approval-run="" disabled={busy} onClick={() => void respond('once')} size="sm">
+ {submitting === 'once' ? <Loader2 className="size-3 animate-spin" /> : copy.run}
+ <span className="opacity-60">↵</span>
</Button>
- {hasCommand && (
- <Button aria-expanded={showCommand} onClick={() => setShowCommand(value => !value)} size="xs" variant="ghost">
- {copy.command}
- <ChevronDown className={cn('transition-transform', showCommand && 'rotate-180')} />
- </Button>
- )}
</div>
<Dialog onOpenChange={setConfirmAlways} open={confirmAlways}>
diff --git a/apps/desktop/src/components/assistant-ui/tool/fallback-model/targets.ts b/apps/desktop/src/components/assistant-ui/tool/fallback-model/targets.ts
index 8423c77add5..c2168f0502c 100644
--- a/apps/desktop/src/components/assistant-ui/tool/fallback-model/targets.ts
+++ b/apps/desktop/src/components/assistant-ui/tool/fallback-model/targets.ts
@@ -27,7 +27,7 @@ export function stableHash(value: string): string {
return Math.abs(hash).toString(36)
}
-export function toolPartDisclosureId(part: ToolPart): string {
+export function toolPartDisclosureId(part: Pick<ToolPart, 'toolCallId' | 'toolName' | 'args'>): string {
if (part.toolCallId) {
return `tool:${part.toolCallId}`
}
@@ -39,6 +39,14 @@ export function toolGroupDisclosureId(parts: ToolPart[]): string {
return `tool-group:${parts.map(toolPartDisclosureId).join('|')}`
}
+/** Shared by a tool row and the activity summaries that open it. */
+export function toolEntryDisclosureId(
+ messageId: string,
+ part: Pick<ToolPart, 'toolCallId' | 'toolName' | 'args'>
+): string {
+ return `tool-entry:${messageId}:${toolPartDisclosureId(part)}`
+}
+
export const URL_PATTERN = /https?:\/\/[^\s'"<>)\]]+/i
export function findFirstUrl(...sources: unknown[]): string {
diff --git a/apps/desktop/src/components/assistant-ui/tool/fallback.tsx b/apps/desktop/src/components/assistant-ui/tool/fallback.tsx
index 9701155f5e2..ee05ea69004 100644
--- a/apps/desktop/src/components/assistant-ui/tool/fallback.tsx
+++ b/apps/desktop/src/components/assistant-ui/tool/fallback.tsx
@@ -48,10 +48,12 @@ 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 { isApprovalActivity, isCurrentTurnMessage } from './approval-activity'
import {
buildToolView,
clampForDisplay,
@@ -67,8 +69,8 @@ import {
selectMessageRunning,
stripInlineDiffChrome,
toolCopyPayload,
+ toolEntryDisclosureId,
type ToolPart,
- toolPartDisclosureId,
type ToolStatus,
type ToolTitleAction
} from './fallback-model'
@@ -336,17 +338,6 @@ function useDisclosureOpen(disclosureId: string, fallbackOpen = false): boolean
return persistedOpen ?? fallbackOpen
}
-/**
- * A row's disclosure id, scoped to the message it was rendered in.
- *
- * Shared with the run that wraps the row: a live run has to know when one of
- * its own rows has been opened, and both sides have to name it identically or
- * the run never hears about it.
- */
-function toolEntryDisclosureId(messageId: string, part: ToolPart): string {
- return `tool-entry:${messageId}:${toolPartDisclosureId(part)}`
-}
-
function ToolEntry({ part }: ToolEntryProps) {
const { t } = useI18n()
const copy = t.assistant.tool
@@ -846,6 +837,7 @@ function ToolRunHeader({
}
interface ToolRunState {
+ approvalActivity: boolean
completedAt?: number
count: number
/** Disclosure id of each row in the run, so the run can tell when one is open. */
@@ -917,6 +909,7 @@ function useToolRun(startIndex: number, endIndex: number): ToolRunState {
undefined
),
count: tools.length,
+ approvalActivity: tools.length > 0 && tools.every(isApprovalActivity),
entryIds: tools.map(tool => toolEntryDisclosureId(state.message.id, tool)),
key: `${state.message.id}:${tools[0]?.toolCallId ?? ''}`,
live,
@@ -952,29 +945,25 @@ 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 } = 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))
const disclosureId = `tool-run:${key}`
const persistedOpen = useStore($toolDisclosureOpen(disclosureId))
const rowOpen = useStore(useMemo(() => $anyToolDisclosureOpen(entryIds), [entryIds]))
const enterRef = useEnterAnimation(messageRunning, `tool-run:${key}`)
+ const representedByApproval = !!approval && currentTurn && approvalActivity
+ const expanded = count < 2 || (persistedOpen ?? rowOpen)
- // A lone call is already its own one-line summary; heading it with a second
- // line would say the same thing twice.
- if (count < 2) {
- return <ToolRunDisclosureContext.Provider value={disclosureId}>{children}</ToolRunDisclosureContext.Provider>
+ // Pending command activity is summarized by the persistent approval host.
+ // An explicit result disclosure still uses the original tool runtime.
+ if (representedByApproval && !rowOpen && !persistedOpen) {
+ return null
}
- // Expanded output stays reachable instead of ticking past in a one-line run.
- const expanded = persistedOpen ?? rowOpen
-
return (
<ToolRunDisclosureContext.Provider value={disclosureId}>
<div
@@ -983,15 +972,17 @@ const ToolRun: FC<PropsWithChildren<{ endIndex: number; startIndex: number }>> =
data-tool-group=""
ref={enterRef}
>
- <ToolRunHeader
- completedAt={completedAt}
- live={live}
- onToggle={() => setToolDisclosureOpen(disclosureId, !expanded)}
- open={expanded}
- startedAt={startedAt}
- summary={summary}
- />
- {live && !expanded && <ToolRunTicker>{children}</ToolRunTicker>}
+ {count > 1 && !representedByApproval && (
+ <ToolRunHeader
+ completedAt={completedAt}
+ live={live}
+ onToggle={() => setToolDisclosureOpen(disclosureId, !expanded)}
+ open={expanded}
+ startedAt={startedAt}
+ summary={summary}
+ />
+ )}
+ {count > 1 && live && !expanded && <ToolRunTicker>{children}</ToolRunTicker>}
{expanded && <div className="grid min-w-0 max-w-full gap-(--tool-row-gap)">{children}</div>}
</div>
</ToolRunDisclosureContext.Provider>
diff --git a/apps/desktop/src/components/notifications.test.tsx b/apps/desktop/src/components/notifications.test.tsx
index 81d4a8a160c..8619f7f5174 100644
--- a/apps/desktop/src/components/notifications.test.tsx
+++ b/apps/desktop/src/components/notifications.test.tsx
@@ -1,15 +1,18 @@
-import { cleanup, fireEvent, render, screen } from '@testing-library/react'
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'
import { I18nProvider } from '@/i18n'
import { $notifications, clearNotifications, notify, notifyError } from '@/store/notifications'
import { $poolLimitsSettingsRequest } from '@/store/pool-limits'
+import { stubResizeObserver } from '@/test/jsdom'
import { NotificationStack, toastTitleClassName } from './notifications'
const LONG_TITLE = 'This turn is no longer in server history (it may have been compressed away).'
const DETAIL = 'target user message is no longer in session history'
+beforeAll(stubResizeObserver)
+
describe('toast titles', () => {
beforeEach(() => {
clearNotifications()
@@ -32,19 +35,23 @@ describe('toast titles', () => {
expect(className).toMatch(/\boverflow-y-auto\b/)
})
- it.each(['default', 'bottom-right'] as const)('caps the %s toast stack at two back edges and keeps older notifications reachable', placement => {
- for (let index = 0; index < 7; index++) {
- notify({ id: `notice-${index}`, message: `Notice ${index}`, placement, durationMs: 0 })
+ it.each(['default', 'bottom-right'] as const)(
+ 'caps the %s toast stack at one back edge and keeps older notifications reachable',
+ async placement => {
+ for (let index = 0; index < 7; index++) {
+ notify({ id: `notice-${index}`, message: `Notice ${index}`, placement, durationMs: 0 })
+ }
+
+ render(<NotificationStack />)
+ expect(screen.getAllByRole('status')).toHaveLength(1)
+ expect(document.querySelectorAll('[data-slot="card-stack-edge"]')).toHaveLength(1)
+ fireEvent.click(screen.getByRole('button', { name: /Show.*6/ }))
+ expect(screen.getByText('Notice 0')).toBeTruthy()
+ expect(screen.getAllByRole('status')).toHaveLength(7)
+ fireEvent.click(screen.getAllByRole('button', { name: /Dismiss/ })[0])
+ await waitFor(() => expect(screen.queryByText('Notice 6')).toBeNull())
}
- render(<NotificationStack />)
- expect(screen.getAllByRole('status')).toHaveLength(1)
- expect(document.querySelectorAll('[data-slot="card-stack-edge"]')).toHaveLength(2)
- fireEvent.click(screen.getByRole('button', { name: /Show.*6/ }))
- expect(screen.getByText('Notice 0')).toBeTruthy()
- expect(screen.getAllByRole('status')).toHaveLength(7)
- fireEvent.click(screen.getAllByRole('button', { name: /Dismiss/ })[0])
- expect(screen.queryByText('Notice 6')).toBeNull()
- })
+ )
it('renders the full title and body instead of truncating them', () => {
notify({ kind: 'error', title: LONG_TITLE, message: DETAIL })
diff --git a/apps/desktop/src/components/notifications.tsx b/apps/desktop/src/components/notifications.tsx
index 8daa92596b6..41881168378 100644
--- a/apps/desktop/src/components/notifications.tsx
+++ b/apps/desktop/src/components/notifications.tsx
@@ -4,7 +4,7 @@ import { createPortal } from 'react-dom'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
-import { CardStack } from '@/components/ui/card-stack'
+import { CardStack, type CardStackAction } from '@/components/ui/card-stack'
import { Codicon } from '@/components/ui/codicon'
import { CopyButton } from '@/components/ui/copy-button'
import { useI18n } from '@/i18n'
@@ -80,15 +80,13 @@ export function NotificationStack() {
return (
<>
- {defaultStack.length > 0 && (
- <TopCenterStack
- copy={copy}
- expanded={expanded}
- notifications={defaultStack}
- onToggleExpanded={() => setExpanded(v => !v)}
- />
- )}
- {bottomRightStack.length > 0 && <BottomRightStack copy={copy} notifications={bottomRightStack} />}
+ <TopCenterStack
+ copy={copy}
+ expanded={expanded}
+ notifications={defaultStack}
+ onToggleExpanded={() => setExpanded(v => !v)}
+ />
+ <BottomRightStack copy={copy} notifications={bottomRightStack} />
</>
)
}
@@ -113,21 +111,19 @@ function TopCenterStack({
notifications: AppNotification[]
onToggleExpanded: () => void
}) {
- const [latest, ...older] = notifications
+ const older = notifications.slice(1)
return createPortal(
<div
aria-label={copy.region}
className={cn(
REGION_BASE,
- 'left-1/2 top-[calc(var(--titlebar-height,34px)+0.75rem)] w-[min(40rem,calc(100%-2rem))] -translate-x-1/2 flex-col max-h-[70vh] overflow-y-auto overscroll-contain p-1'
+ 'left-1/2 top-[calc(var(--titlebar-height,34px)+0.75rem)] w-[min(28rem,calc(100%-2rem))] -translate-x-1/2 flex-col p-1',
+ expanded && 'max-h-[70vh] overflow-y-auto overscroll-contain'
)}
role="region"
>
- <CardStack count={expanded ? 1 : notifications.length} backClassName="rounded-lg border border-(--stroke-nous) bg-popover shadow-nous">
- <NotificationItem notification={latest} />
- </CardStack>
- {expanded && older.map(n => <NotificationItem key={n.id} notification={n} />)}
+ <NotificationDeck expanded={expanded} notifications={notifications} />
{older.length > 0 && (
<div className="pointer-events-auto flex min-h-8 items-center justify-between px-3 text-xs">
<Button className="-ml-2" onClick={onToggleExpanded} size="xs" type="button" variant="text">
@@ -152,7 +148,7 @@ function BottomRightStack({
notifications: AppNotification[]
}) {
const [expanded, setExpanded] = useState(false)
- const [latest, ...older] = notifications
+ const older = notifications.slice(1)
useEffect(() => {
if (!older.length) {
@@ -163,7 +159,11 @@ function BottomRightStack({
return createPortal(
<div
aria-label={copy.region}
- className={cn(REGION_BASE, 'right-4 bottom-4 w-[min(24rem,calc(100%-2rem))] flex-col-reverse max-h-[70vh] overflow-y-auto overscroll-contain p-1')}
+ className={cn(
+ REGION_BASE,
+ 'right-4 bottom-4 w-[min(24rem,calc(100%-2rem))] flex-col-reverse p-1',
+ expanded && 'max-h-[70vh] overflow-y-auto overscroll-contain'
+ )}
role="region"
>
{older.length > 0 && (
@@ -171,20 +171,44 @@ function BottomRightStack({
<Button onClick={() => setExpanded(value => !value)} size="xs" variant="text">
{expanded ? copy.hide : copy.show} {copy.more(older.length)}
</Button>
- <Button onClick={() => notifications.forEach(notification => dismissNotification(notification.id))} size="xs" variant="text">
+ <Button
+ onClick={() => notifications.forEach(notification => dismissNotification(notification.id))}
+ size="xs"
+ variant="text"
+ >
{copy.clearAll}
</Button>
</div>
)}
- <CardStack count={expanded ? 1 : notifications.length} direction="up" backClassName="rounded-lg border border-(--stroke-nous) bg-popover shadow-nous">
- <NotificationItem notification={latest} />
- </CardStack>
- {expanded && older.map(notification => <NotificationItem key={notification.id} notification={notification} />)}
+ <NotificationDeck expanded={expanded} notifications={notifications} />
</div>,
document.body
)
}
+export function NotificationDeck({
+ notifications,
+ expanded = false
+}: {
+ notifications: AppNotification[]
+ expanded?: boolean
+}) {
+ return (
+ <CardStack
+ expanded={expanded}
+ getKey={notification => notification.id}
+ items={notifications}
+ onSwipe={(notification, _side, action) => {
+ void action.depart(() => dismissNotification(notification.id))
+ }}
+ surfaceClassName={cn(STACK_SURFACE, 'rounded-lg')}
+ swipeDirections={['left', 'right']}
+ >
+ {(notification, action) => <NotificationItem notification={notification} stack={action} />}
+ </CardStack>
+ )
+}
+
// Emphasize only the leading money figure ("$16.00" — the amount used) with the
// accent color (semibold), leaving the rest of the line in its default muted
// tone. No accent, or no figure in the message → render the text untouched.
@@ -216,7 +240,7 @@ export function toastTitleClassName() {
return 'col-start-auto line-clamp-none max-h-[4.5em] overflow-y-auto overscroll-contain whitespace-normal wrap-break-word'
}
-function NotificationItem({ notification }: { notification: AppNotification }) {
+function NotificationItem({ notification, stack }: { notification: AppNotification; stack: CardStackAction }) {
const styles = tone[notification.kind]
const Icon = styles.icon
const hasDetail = Boolean(notification.detail && notification.detail !== notification.message)
@@ -231,8 +255,8 @@ function NotificationItem({ notification }: { notification: AppNotification }) {
return (
<Alert
- aria-live={notification.kind === 'error' ? 'assertive' : 'polite'}
- className={cn(STACK_SURFACE, 'grid-cols-[auto_minmax(0,1fr)_auto] pr-2.5')}
+ aria-live={!stack.active ? 'off' : notification.kind === 'error' ? 'assertive' : 'polite'}
+ className="grid-cols-[auto_minmax(0,1fr)_auto] border-0 bg-transparent pr-2.5 shadow-none"
role={notification.kind === 'error' ? 'alert' : 'status'}
variant={styles.variant}
>
@@ -255,9 +279,12 @@ function NotificationItem({ notification }: { notification: AppNotification }) {
<div className="mt-1.5 flex flex-wrap gap-1.5">
{notification.action && (
<Button
+ disabled={stack.busy || !stack.active}
onClick={() => {
- notification.action?.onClick()
- dismissNotification(notification.id)
+ void stack.depart(() => {
+ notification.action?.onClick()
+ dismissNotification(notification.id)
+ })
}}
size="sm"
type="button"
@@ -268,9 +295,12 @@ function NotificationItem({ notification }: { notification: AppNotification }) {
)}
{notification.secondaryAction && (
<Button
+ disabled={stack.busy || !stack.active}
onClick={() => {
- notification.secondaryAction?.onClick()
- dismissNotification(notification.id)
+ void stack.depart(() => {
+ notification.secondaryAction?.onClick()
+ dismissNotification(notification.id)
+ })
}}
size="sm"
type="button"
@@ -286,7 +316,10 @@ function NotificationItem({ notification }: { notification: AppNotification }) {
<Button
aria-label={copy.dismiss}
className="col-start-3 -mr-1 text-muted-foreground"
- onClick={() => dismissNotification(notification.id)}
+ disabled={stack.busy || !stack.active}
+ onClick={() => {
+ void stack.depart(() => dismissNotification(notification.id))
+ }}
size="icon-xs"
type="button"
variant="ghost"
diff --git a/apps/desktop/src/components/prompt-overlays.tsx b/apps/desktop/src/components/prompt-overlays.tsx
index 91b0e37545c..84084c3d547 100644
--- a/apps/desktop/src/components/prompt-overlays.tsx
+++ b/apps/desktop/src/components/prompt-overlays.tsx
@@ -3,7 +3,6 @@
import { useStore } from '@nanostores/react'
import { type FormEvent, useCallback, useEffect, useMemo, useState } from 'react'
-import { PendingApprovalStack } from '@/components/assistant-ui/tool/approval'
import { Button } from '@/components/ui/button'
import {
Dialog,
@@ -582,7 +581,6 @@ function VaultCodeDialog({ sessionId }: { sessionId: string | null }) {
export function PromptOverlays({ sessionId }: { sessionId: string | null }) {
return (
<>
- <PendingApprovalStack />
<SudoDialog sessionId={sessionId} />
<SecretDialog sessionId={sessionId} />
<VaultUnlockDialog sessionId={sessionId} />
diff --git a/apps/desktop/src/components/ui/card-stack.tsx b/apps/desktop/src/components/ui/card-stack.tsx
index d4e136c7ba8..bcd6537a681 100644
--- a/apps/desktop/src/components/ui/card-stack.tsx
+++ b/apps/desktop/src/components/ui/card-stack.tsx
@@ -1,44 +1,321 @@
-import type { ReactNode } from 'react'
+import { animate, AnimatePresence, motion, useIsPresent, useMotionValue, useReducedMotion } from 'motion/react'
+import { type ReactNode, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { cn } from '@/lib/utils'
-interface CardStackProps {
- children: ReactNode
- count: number
- /** Match the existing surface: this primitive owns depth, never its palette. */
- backClassName: string
- direction?: 'up' | 'down'
+export type CardStackDirection = 'left' | 'right'
+
+export interface CardStackAction {
+ active: boolean
+ busy: boolean
+ /** Feedback and departure are shared; persistence stays with the consumer. */
+ depart: (action: () => void | Promise<void>) => Promise<void>
+}
+
+interface CardStackProps<T> {
+ items: readonly T[]
+ getKey: (item: T) => string
+ children: (item: T, action: CardStackAction) => ReactNode
+ /** Surface only. All placements share the geometry and gesture controller. */
+ surfaceClassName: string
+ expanded?: boolean
+ swipeDirections?: readonly CardStackDirection[]
+ onSwipe?: (item: T, direction: CardStackDirection, action: CardStackAction) => void
}
-/** One live card and at most two inert card edges, regardless of queue length. */
-export function CardStack({ children, count, backClassName, direction = 'down' }: CardStackProps) {
- const depth = Math.min(2, Math.max(0, count - 1))
+// Measured from Cursor's shipped AgentTranscriptApprovalStack: one silhouette,
+// 7px/96% promotion and a 14px upward clearance. Shared by every consumer.
+const GAP = 7
+const SCALE = 0.96
+const EASE = [0.23, 1, 0.32, 1] as const
+const PROMOTION = { duration: 0.22, ease: EASE }
+const DEPARTURE = { duration: 0.18, ease: EASE }
+const RETURN = { type: 'spring' as const, stiffness: 460, damping: 34, mass: 0.8 }
+const NO_SWIPES: readonly CardStackDirection[] = []
+
+export function CardStack<T>({
+ items,
+ getKey,
+ children,
+ surfaceClassName,
+ expanded = false,
+ swipeDirections = NO_SWIPES,
+ onSwipe
+}: CardStackProps<T>) {
+ const [height, setHeight] = useState(0)
+ const [frontKey, setFrontKey] = useState<string | undefined>(() => items[0] && getKey(items[0]))
+ // Keep the item being read when newer items arrive. Cursor's live projection
+ // keeps its previous entry id until that entry leaves the pending list.
+ const front = items.find(item => getKey(item) === frontKey) ?? items[0]
+ const currentKey = front && getKey(front)
+ useLayoutEffect(() => {
+ setFrontKey(currentKey)
+ }, [currentKey])
+
+ const shown = expanded ? items : front ? [front] : []
+ const reduced = useReducedMotion()
return (
<div
- className="relative isolate min-w-0"
+ className={cn('relative isolate min-w-0', expanded && 'flex flex-col gap-2')}
+ data-expanded={expanded}
data-slot="card-stack"
- style={{ paddingTop: direction === 'up' ? depth * 6 : 0, paddingBottom: direction === 'down' ? depth * 6 : 0 }}
+ data-stack-count={items.length}
+ style={{
+ paddingTop: !expanded && items.length ? 8 : 0,
+ minHeight: items.length || height ? height + (expanded ? 0 : 8) : undefined
+ }}
>
- {Array.from({ length: depth }, (_, index) => {
- const layer = index + 1
-
- return (
- <div
- aria-hidden="true"
- className={cn('pointer-events-none absolute', backClassName)}
- data-slot="card-stack-edge"
- key={layer}
- style={{
- insetInline: layer * 6,
- top: direction === 'up' ? (depth - layer) * 6 : layer * 6,
- bottom: direction === 'up' ? layer * 6 : (depth - layer) * 6,
- zIndex: -layer
- }}
- />
- )
- })}
- <div className="relative">{children}</div>
+ {!expanded && items.length > 1 && (
+ <motion.div
+ animate={{ opacity: 0.6 }}
+ aria-hidden="true"
+ className={cn('pointer-events-none absolute inset-x-0', surfaceClassName)}
+ data-glass-opaque=""
+ data-slot="card-stack-edge"
+ initial={{ opacity: 0 }}
+ style={{
+ top: 8,
+ height,
+ transform: `translateY(-${GAP}px) scale(${SCALE})`,
+ transformOrigin: 'top center',
+ zIndex: 0
+ }}
+ transition={reduced ? { duration: 0 } : PROMOTION}
+ />
+ )}
+ <AnimatePresence
+ initial={false}
+ onExitComplete={() => {
+ if (!items.length) {
+ setHeight(0)
+ }
+ }}
+ >
+ {shown.map((item, index) => (
+ <StackCard
+ expanded={expanded}
+ index={index}
+ itemKey={getKey(item)}
+ key={getKey(item)}
+ onMeasure={setHeight}
+ onSwipe={onSwipe ? (side, action) => onSwipe(item, side, action) : undefined}
+ surfaceClassName={surfaceClassName}
+ swipeDirections={swipeDirections}
+ >
+ {action => children(item, action)}
+ </StackCard>
+ ))}
+ </AnimatePresence>
</div>
)
}
+
+function StackCard({
+ children,
+ itemKey,
+ index,
+ onMeasure,
+ expanded,
+ surfaceClassName,
+ swipeDirections,
+ onSwipe
+}: {
+ children: (action: CardStackAction) => ReactNode
+ itemKey: string
+ index: number
+ onMeasure: (height: number) => void
+ expanded: boolean
+ surfaceClassName: string
+ swipeDirections: readonly CardStackDirection[]
+ onSwipe?: (direction: CardStackDirection, action: CardStackAction) => void
+}) {
+ const present = useIsPresent()
+ const reduced = useReducedMotion()
+ const active = present && (expanded || index === 0)
+ const [busy, setBusy] = useState(false)
+ const [dragging, setDragging] = useState(false)
+ const locked = useRef(false)
+ const node = useRef<HTMLDivElement>(null)
+ const content = useRef<HTMLDivElement>(null)
+
+ const pointer = useRef<{
+ id: number
+ x: number
+ y: number
+ lastX: number
+ lastTime: number
+ velocity: number
+ moved: boolean
+ } | null>(null)
+
+ const x = useMotionValue(0)
+ const y = useMotionValue(0)
+
+ useLayoutEffect(() => {
+ if (index !== 0 || !content.current) {
+ return
+ }
+ const element = content.current
+ const measure = () => onMeasure(element.offsetHeight + 2)
+ measure()
+ const observer = new ResizeObserver(measure)
+ observer.observe(element)
+
+ return () => observer.disconnect()
+ }, [index, onMeasure])
+
+ useEffect(
+ () => () => {
+ x.stop()
+ y.stop()
+ },
+ [x, y]
+ )
+
+ const action: CardStackAction = {
+ active,
+ busy,
+ async depart(commit) {
+ if (locked.current || !active) {
+ return
+ }
+ locked.current = true
+ setBusy(true)
+ setDragging(false)
+
+ try {
+ // Immediate press feedback. Removal drives the shared keyed exit and
+ // promotion together; a slow or failed reply never leaves a blank pile.
+ animate(y, reduced ? 0 : 1, { duration: 0.08 })
+ await commit()
+ } catch (error) {
+ locked.current = false
+ setBusy(false)
+ animate(x, 0, reduced ? { duration: 0 } : RETURN)
+ animate(y, 0, { duration: reduced ? 0 : 0.12 })
+ throw error
+ }
+ }
+ }
+
+ const resetDrag = () => {
+ pointer.current = null
+ setDragging(false)
+ animate(x, 0, reduced ? { duration: 0 } : RETURN)
+ }
+
+ return (
+ <motion.div
+ animate={{ opacity: 1, y: 0, scale: 1 }}
+ aria-hidden={!active || undefined}
+ className={cn('min-w-0', expanded ? 'relative' : 'absolute inset-x-0')}
+ data-slot="card-stack-front"
+ data-stack-active={active}
+ data-stack-busy={busy}
+ data-stack-key={itemKey}
+ exit={{ opacity: 0, y: reduced ? 0 : -14, transition: reduced ? { duration: 0 } : DEPARTURE }}
+ inert={!active || busy}
+ initial={reduced ? { opacity: 1 } : { opacity: 0.6, y: -GAP, scale: SCALE }}
+ ref={node}
+ style={{
+ zIndex: present ? 1 : 2,
+ top: !expanded ? 8 : undefined,
+ transformOrigin: 'top center'
+ }}
+ transition={reduced ? { duration: 0 } : PROMOTION}
+ >
+ <motion.div
+ className={cn(surfaceClassName, onSwipe && active && 'cursor-grab', dragging && 'cursor-grabbing')}
+ data-glass-opaque=""
+ data-slot="card-stack-surface"
+ onLostPointerCapture={() => {
+ if (pointer.current) {
+ resetDrag()
+ }
+ }}
+ onPointerCancel={resetDrag}
+ onPointerDown={event => {
+ if (
+ !active ||
+ locked.current ||
+ !onSwipe ||
+ event.button !== 0 ||
+ (event.target as HTMLElement).closest('button,a,input,textarea,select,summary,pre,[contenteditable]')
+ ) {
+ return
+ }
+
+ pointer.current = {
+ id: event.pointerId,
+ x: event.clientX,
+ y: event.clientY,
+ lastX: event.clientX,
+ lastTime: event.timeStamp,
+ velocity: 0,
+ moved: false
+ }
+ }}
+ onPointerMove={event => {
+ const start = pointer.current
+
+ if (!start || start.id !== event.pointerId) {
+ return
+ }
+ const delta = event.clientX - start.x
+
+ if (!start.moved) {
+ if (Math.abs(event.clientY - start.y) > Math.abs(delta) && Math.abs(event.clientY - start.y) > 6) {
+ resetDrag()
+
+ return
+ }
+
+ if (Math.abs(delta) < 6) {
+ return
+ }
+
+ if (window.getSelection()?.toString()) {
+ resetDrag()
+
+ return
+ }
+
+ start.moved = true
+ event.currentTarget.setPointerCapture(event.pointerId)
+ setDragging(true)
+ }
+
+ const side = delta < 0 ? 'left' : 'right'
+ const allowed = swipeDirections.includes(side)
+ x.set(allowed ? delta : delta / (1.5 + Math.abs(delta) / 20))
+ start.velocity = (event.clientX - start.lastX) / Math.max(1, event.timeStamp - start.lastTime)
+ start.lastX = event.clientX
+ start.lastTime = event.timeStamp
+ }}
+ onPointerUp={event => {
+ const start = pointer.current
+
+ 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)
+ const fast = event.timeStamp - start.lastTime < 80 && Math.abs(start.velocity) > 0.5 && Math.abs(delta) > 18
+ pointer.current = null
+ setDragging(false)
+
+ if (start.moved && swipeDirections.includes(side) && (Math.abs(delta) > threshold || fast)) {
+ onSwipe?.(side, action)
+ } else {
+ animate(x, 0, reduced ? { duration: 0 } : RETURN)
+ }
+ }}
+ style={{ x, y, touchAction: onSwipe ? 'pan-y' : undefined }}
+ >
+ <div ref={content}>{children(action)}</div>
+ </motion.div>
+ </motion.div>
+ )
+}
diff --git a/apps/desktop/src/lib/keybinds/approval-keys.ts b/apps/desktop/src/lib/keybinds/approval-keys.ts
index 54e6285c427..1cf267b353a 100644
--- a/apps/desktop/src/lib/keybinds/approval-keys.ts
+++ b/apps/desktop/src/lib/keybinds/approval-keys.ts
@@ -17,7 +17,11 @@ function activeApprovalStack(): HTMLElement | undefined {
return queryAllVisible<HTMLElement>('[data-approval-stack]').find(stack => {
const surface = stack.closest<HTMLElement>('[data-composer-target]')
- return !surface || surface.dataset.composerTarget === target
+ return (
+ Boolean(stack.querySelector('[data-stack-active="true"]')) &&
+ !stack.closest('[inert]') &&
+ (!surface || surface.dataset.composerTarget === target)
+ )
})
}
@@ -32,6 +36,7 @@ export function handleApprovalKey(event: KeyboardEvent): boolean {
composerFocusBlockedBySurface()
) {
releaseApprovalKey()
+
return false
}
@@ -46,8 +51,10 @@ export function handleApprovalKey(event: KeyboardEvent): boolean {
if (!heldStack) {
return false
}
+
event.preventDefault()
event.stopPropagation()
+
if (stack !== heldStack || event.key !== 'Enter') {
return true
}
@@ -55,26 +62,34 @@ export function handleApprovalKey(event: KeyboardEvent): boolean {
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)
+
+ const button =
+ event.key === 'Enter' && !event.repeat && runTarget
+ ? (runTarget as HTMLButtonElement)
+ : Array.from(stack?.querySelectorAll<HTMLButtonElement>(selector) ?? []).find(
+ button => !button.closest('[inert]')
+ )
// 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/prompts.ts b/apps/desktop/src/store/prompts.ts
index 457734d17d5..f84092f3d61 100644
--- a/apps/desktop/src/store/prompts.ts
+++ b/apps/desktop/src/store/prompts.ts
@@ -123,9 +123,11 @@ export interface VaultUnlockRequest extends KeyedPrompt {
const EMPTY_APPROVALS: ApprovalRequest[] = []
const $approvalQueues = atom<Record<string, ApprovalRequest[]>>({})
+const $approvalStackSizes = atom<Record<string, number>>({})
// 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]]))
@@ -133,6 +135,7 @@ const approval = {
reset() {
approvalRevision += 1
sessionApprovalRevisions.clear()
+ $approvalStackSizes.set({})
$approvalQueues.set({})
},
set(request: ApprovalRequest) {
@@ -143,6 +146,8 @@ const approval = {
const next = [...queue]
if (index < 0) {
+ const sizes = $approvalStackSizes.get()
+ $approvalStackSizes.set({ ...sizes, [key]: (sizes[key] ?? 0) + 1 })
next.push(request)
} else {
next[index] = request
@@ -157,6 +162,7 @@ const approval = {
const key = keyFor(sessionId)
sessionApprovalRevisions.set(key, (sessionApprovalRevisions.get(key) ?? 0) + 1)
}
+
const queues = $approvalQueues.get()
const next = { ...queues }
let changed = false
@@ -173,10 +179,14 @@ const approval = {
}
changed = true
+
if (remaining.length) {
next[key] = remaining
} else {
delete next[key]
+ const sizes = { ...$approvalStackSizes.get() }
+ delete sizes[key]
+ $approvalStackSizes.set(sizes)
}
}
@@ -185,6 +195,7 @@ const approval = {
}
}
}
+
const sudo = keyedPromptStore<SudoRequest>()
const secret = keyedPromptStore<SecretRequest>()
const vaultUnlock = keyedPromptStore<VaultUnlockRequest>()
@@ -283,27 +294,32 @@ export async function replayPendingApproval(gateway: ApprovalGateway | null, ses
}
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)
}
}
- await Promise.all(result.approvals.map(pending => {
- if (typeof pending.request_id !== 'string') {
- return
- }
+ await Promise.all(
+ result.approvals.map(pending => {
+ if (typeof pending.request_id !== 'string') {
+ return
+ }
- 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
+ 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
+ })
})
- }))
+ )
}
/**
@@ -337,6 +353,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 sessionApprovalStackSize = (sessionId: string | null) =>
+ computed($approvalStackSizes, sizes => sizes[keyFor(sessionId)] ?? 0)
export const sessionApprovalRequests = (sessionId: string | null) =>
computed($approvalQueues, all => all[keyFor(sessionId)] ?? EMPTY_APPROVALS)
export const sessionApprovalRequest = (sessionId: string | null) =>
diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.css
index 98d1c138320..1d495a47db5 100644
--- a/apps/desktop/src/styles.css
+++ b/apps/desktop/src/styles.css
@@ -2090,6 +2090,12 @@ body.guest-pointer-lock :is(webview, iframe) {
opacity: 1;
}
+/* Tool-only continuation bubbles have no independent line while the approval
+ activity row represents them. An explicitly opened result remains in place. */
+[data-approval-activity-only]:not(:has([data-tool-open])) {
+ display: none;
+}
+
/* Conversation block rhythm. assistant-ui renders each range as a direct child
of the message content with no per-part wrapper, so adjacency rules cover
every pairing — first block needs no reset, nested tool rows are untouched.