Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🛂 feat: Keyboard Submit and Escape for Tool Approval Cards (#17233)

Marco Beretta30d73382a049
diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx
index 16555bf237..8b510f00e5 100644
--- a/client/src/components/Chat/Input/ChatForm.tsx
+++ b/client/src/components/Chat/Input/ChatForm.tsx
@@ -171,6 +171,7 @@ const ChatForm = memo(function ChatForm({
}: ChatFormProps) {
const submitButtonRef = useRef<HTMLButtonElement>(null);
const textAreaRef = useRef<HTMLTextAreaElement>(null);
+ const approvalTriggerRef = useRef<HTMLButtonElement>(null);
/** The palette anchors to the whole composer, not to its own button, so it
* spans the composer width and sits flush above it. */
const composerBoxRef = useRef<HTMLDivElement>(null);
@@ -808,7 +809,10 @@ const ChatForm = memo(function ChatForm({
<AskUserQuestionPopover conversationId={conversationId} textAreaRef={textAreaRef} />
)}
{index === 0 && conversationId != null && (
- <PendingToolApprovalPanel conversationId={conversationId} />
+ <PendingToolApprovalPanel
+ conversationId={conversationId}
+ triggerRef={approvalTriggerRef}
+ />
)}
<SkillsCommand
index={index}
@@ -1011,7 +1015,10 @@ const ChatForm = memo(function ChatForm({
disabled={disableInputs}
/>
{index === 0 && conversationId != null && (
- <PendingToolApprovalButton conversationId={conversationId} />
+ <PendingToolApprovalButton
+ conversationId={conversationId}
+ triggerRef={approvalTriggerRef}
+ />
)}
</div>
}
diff --git a/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx b/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx
index 15dc9b8477..d4d12044ec 100644
--- a/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx
+++ b/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx
@@ -3,11 +3,11 @@ import { Button, TextareaAutosize, TooltipAnchor } from '@librechat/client';
import { ChevronDown, MessageCircleQuestion, TriangleAlert } from 'lucide-react';
import type { Agents } from 'librechat-data-provider';
import type { KeyboardEvent } from 'react';
-import type { ComposerBindings } from '~/hooks/Input/useComposerBindings';
import { isCancelKey, isReboundSubmitChord, resolveComposerKeyDown } from '~/utils/shortcuts';
import { useApprovalContext, useAskSubmitStatus, useResumeSubmit } from './ApprovalContext';
import { splitOtherOption, ASK_USER_DECLINED_ANSWER } from '~/utils/approval';
import { useOptionalChatSurface } from '~/components/Chat/Subagents/surface';
+import { NO_HOST_BINDINGS } from '~/hooks/Input/useComposerBindings';
import { cn, forceResize, insertTextAtCursor } from '~/utils';
import useAskAnswerMode from '~/hooks/Input/useAskAnswerMode';
import AskOptions from '~/components/Chat/ask/options';
@@ -16,12 +16,6 @@ import AskUserQuestions from './AskUserQuestions';
import { useLocalize } from '~/hooks';
/** Stock preferences for a card rendered outside a chat surface. */
-const NO_HOST_BINDINGS: ComposerBindings = {
- shortcutsEnabled: true,
- submitOverride: undefined,
- yieldedChords: new Set(),
-};
-
/**
* Renders an `ask_user_question` pause: the prompt, optional description, any
* curated option buttons, and a free-form text answer. Single-select options
diff --git a/client/src/components/Chat/Messages/Content/ToolApproval.tsx b/client/src/components/Chat/Messages/Content/ToolApproval.tsx
index afb701808d..1903c4d77f 100644
--- a/client/src/components/Chat/Messages/Content/ToolApproval.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolApproval.tsx
@@ -10,13 +10,23 @@ import {
TriangleAlert,
} from 'lucide-react';
import type { Agents } from 'librechat-data-provider';
+import type { KeyboardEvent } from 'react';
import type { TranslationKeys } from '~/hooks';
+import {
+ isReboundSubmitChord,
+ resolveComposerKeyDown,
+ bindingFromEvent,
+ bindingsMatch,
+ bindingHash,
+} from '~/utils/shortcuts';
import { useComposerPresentsApproval } from '~/components/Chat/approval/state';
+import { useOptionalChatSurface } from '~/components/Chat/Subagents/surface';
import { boundApprovalLabel } from '~/components/Chat/approval/preview';
import { useApprovalContext, useResumeSubmit } from './ApprovalContext';
+import { cn, forceResize, insertTextAtCursor, logger } from '~/utils';
+import { NO_HOST_BINDINGS } from '~/hooks/Input/useComposerBindings';
import { ChatContext } from '~/Providers/ChatContext';
import { useLocalize } from '~/hooks';
-import { cn, logger } from '~/utils';
/**
* The resume route rejects an `edit` whose `editedArguments` isn't a plain object
@@ -125,6 +135,10 @@ export default function ToolApproval({
getRegisteredCount,
} = useApprovalContext();
const { submitToolApproval } = useResumeSubmit();
+ const chatSurface = useOptionalChatSurface();
+ const enterToSend = chatSurface?.enterToSend ?? false;
+ const { shortcutsEnabled, submitOverride, yieldedChords } =
+ chatSurface?.composerBindings ?? NO_HOST_BINDINGS;
const retainedDecision = getDecision(actionId, toolCallId);
const initialDecision =
@@ -252,6 +266,78 @@ export default function ToolApproval({
return null;
}
+ /** Every card submits the whole batch, the same as the lead card's button,
+ * so a field can submit from any card once every call has a decision. */
+ const submitFromField = (repeat: boolean) => {
+ if (!repeat && ready && !locked) {
+ submitToolApproval(actionId);
+ }
+ };
+
+ const isComposingKey = (e: KeyboardEvent<HTMLTextAreaElement>) =>
+ e.nativeEvent.isComposing || e.key === 'Process' || e.keyCode === 229;
+
+ /** The reason and response fields are prose, so they follow the composer's
+ * Enter table, Enter-to-send included. */
+ const handleTextKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
+ const isComposing = isComposingKey(e);
+ if (!isComposing && isReboundSubmitChord(e.nativeEvent, { shortcutsEnabled, submitOverride })) {
+ e.preventDefault();
+ submitFromField(e.repeat);
+ return;
+ }
+ const action = resolveComposerKeyDown(e.nativeEvent, {
+ isComposing,
+ isSubmitting: false,
+ allowSubmitWhileGenerating: false,
+ hasDuringRunModifier: false,
+ shortcutsEnabled,
+ enterToSend,
+ submitOverride,
+ yieldedChords,
+ });
+ if (action === 'none') {
+ return;
+ }
+ e.preventDefault();
+ if (action === 'newline') {
+ insertTextAtCursor(e.currentTarget, '\n');
+ forceResize(e.currentTarget);
+ return;
+ }
+ if (action === 'submit') {
+ submitFromField(e.repeat);
+ }
+ };
+
+ /** The edit field holds JSON, where plain Enter is always a newline. The
+ * submit chord is the composer's: Ctrl/Cmd+Enter by default, the rebound
+ * chord when one is set, and none while shortcuts are off or unbound. */
+ const handleEditKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
+ if (isComposingKey(e)) {
+ return;
+ }
+ if (isReboundSubmitChord(e.nativeEvent, { shortcutsEnabled, submitOverride })) {
+ e.preventDefault();
+ submitFromField(e.repeat);
+ return;
+ }
+ const binding = bindingFromEvent(e.nativeEvent);
+ if (binding == null || binding.key !== 'Enter' || yieldedChords.has(bindingHash(binding))) {
+ return;
+ }
+ const isPlainEnter = !binding.ctrl && !binding.meta && !binding.alt && !binding.shift;
+ const isSubmitChord =
+ submitOverride === undefined
+ ? (binding.ctrl || binding.meta) && !binding.shift && !binding.alt
+ : !isPlainEnter && bindingsMatch(binding, submitOverride);
+ if (!isSubmitChord) {
+ return;
+ }
+ e.preventDefault();
+ submitFromField(e.repeat);
+ };
+
const descriptionNode = safeDescription != null && safeDescription.length > 0 && (
<p className="text-text-secondary text-sm">{safeDescription}</p>
);
@@ -348,6 +434,7 @@ export default function ToolApproval({
value={editText}
disabled={locked}
onChange={(e) => updateDecisionDraft({ editText: e.target.value })}
+ onKeyDown={handleEditKeyDown}
minRows={3}
maxRows={16}
className={cn(fieldClasses, 'font-mono text-xs')}
@@ -368,6 +455,7 @@ export default function ToolApproval({
value={responseText}
disabled={locked}
onChange={(e) => updateDecisionDraft({ responseText: e.target.value })}
+ onKeyDown={handleTextKeyDown}
minRows={2}
maxRows={12}
placeholder={localize('com_ui_tool_response_placeholder')}
@@ -381,6 +469,7 @@ export default function ToolApproval({
value={reason}
disabled={locked}
onChange={(e) => updateDecisionDraft({ reason: e.target.value })}
+ onKeyDown={handleTextKeyDown}
minRows={1}
maxRows={6}
placeholder={localize('com_ui_reject_reason_placeholder')}
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolApproval.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolApproval.test.tsx
index 2d97d53dd8..8ea5e191ae 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ToolApproval.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolApproval.test.tsx
@@ -1,12 +1,15 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { Provider, createStore } from 'jotai';
-import { act, fireEvent, render, screen, within } from '@testing-library/react';
+import { activeGenerationCreatedAtByConvoId } from '@librechat/chat/react';
+import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';
import type { Agents } from 'librechat-data-provider';
+import type { ShortcutBinding } from '~/utils/shortcuts';
import {
approvalPanelOpenFamily,
pendingApprovalActionFamily,
} from '~/components/Chat/approval/state';
+import { ChatSurfaceProvider } from '~/components/Chat/Subagents/surface';
import ApprovalProvider, { useApprovalContext } from '../ApprovalContext';
import { ChatContext } from '~/Providers/ChatContext';
import ToolApproval from '../ToolApproval';
@@ -34,8 +37,18 @@ jest.mock('~/hooks', () => ({
},
}));
+const mockMutate = jest.fn();
+const mockInsertTextAtCursor = jest.fn();
+
+/** jsdom has no execCommand, so the newline path is observed through the mock. */
+jest.mock('~/utils/textarea', () => ({
+ ...jest.requireActual('~/utils/textarea'),
+ forceResize: jest.fn(),
+ insertTextAtCursor: (...args: unknown[]) => mockInsertTextAtCursor(...args),
+}));
+
jest.mock('~/data-provider', () => ({
- useSubmitToolApprovalMutation: () => ({ mutate: jest.fn() }),
+ useSubmitToolApprovalMutation: () => ({ mutate: mockMutate }),
useSubmitAskAnswerMutation: () => ({ mutate: jest.fn() }),
}));
@@ -332,4 +345,173 @@ describe('ToolApproval', () => {
expect(screen.getByTestId('thread')).toHaveTextContent('Review in composer');
});
});
+
+ describe('submitting from a decision field', () => {
+ const conversationId = 'conversation-1';
+
+ beforeEach(() => {
+ mockMutate.mockClear();
+ mockInsertTextAtCursor.mockClear();
+ });
+
+ const renderLive = (
+ allowed: Agents.ToolApprovalDecisionType[],
+ {
+ enterToSend = true,
+ shortcutsEnabled = true,
+ submitOverride,
+ }: {
+ enterToSend?: boolean;
+ shortcutsEnabled?: boolean;
+ submitOverride?: ShortcutBinding | null;
+ } = {},
+ ) => {
+ const store = createStore();
+ store.set(activeGenerationCreatedAtByConvoId(conversationId), 1000);
+ render(
+ <RecoilRoot>
+ <Provider store={store}>
+ <ChatContext.Provider value={{ conversation: { conversationId } } as never}>
+ <ChatSurfaceProvider
+ value={{
+ enterToSend,
+ maximizeChatSpace: false,
+ showScrollButton: false,
+ composerBindings: {
+ shortcutsEnabled,
+ submitOverride,
+ yieldedChords: new Set(),
+ },
+ claimForeground: jest.fn(),
+ handOffComposerText: jest.fn(),
+ }}
+ >
+ <ApprovalProvider>
+ <ToolApproval approval={approval(allowed)} toolCallId="call-1" args={{ a: 1 }} />
+ </ApprovalProvider>
+ </ChatSurfaceProvider>
+ </ChatContext.Provider>
+ </Provider>
+ </RecoilRoot>,
+ );
+ };
+
+ const submittedDecisions = () =>
+ mockMutate.mock.calls.map(([payload]) => (payload as { decisions: unknown }).decisions);
+
+ test('Enter in the reject reason submits with Enter-to-send on; Shift, IME and held Enter do not', () => {
+ renderLive(['approve', 'reject']);
+ fireEvent.click(screen.getByRole('button', { name: 'Reject' }));
+ const reason = screen.getByRole('textbox', { name: 'Reject' });
+ fireEvent.change(reason, { target: { value: 'not now' } });
+
+ fireEvent.keyDown(reason, { key: 'Enter', shiftKey: true });
+ fireEvent.keyDown(reason, { key: 'Enter', isComposing: true });
+ fireEvent.keyDown(reason, { key: 'Enter', keyCode: 229 });
+ fireEvent.keyDown(reason, { key: 'Enter', repeat: true });
+ expect(mockMutate).not.toHaveBeenCalled();
+
+ fireEvent.keyDown(reason, { key: 'Enter' });
+ expect(submittedDecisions()).toEqual([
+ [{ tool_call_id: 'call-1', decision: 'reject', reason: 'not now' }],
+ ]);
+ });
+
+ test('with Enter-to-send off, Enter writes a newline and Ctrl/Cmd+Enter submits', () => {
+ renderLive(['reject'], { enterToSend: false });
+ fireEvent.click(screen.getByRole('button', { name: 'Reject' }));
+ const reason = screen.getByRole('textbox', { name: 'Reject' });
+
+ fireEvent.keyDown(reason, { key: 'Enter' });
+ expect(mockInsertTextAtCursor).toHaveBeenCalledWith(reason, '\n');
+ expect(mockMutate).not.toHaveBeenCalled();
+
+ fireEvent.keyDown(reason, { key: 'Enter', metaKey: true });
+ expect(mockMutate).toHaveBeenCalledTimes(1);
+ });
+
+ test('Enter in an empty response does not submit', () => {
+ renderLive(['approve', 'respond']);
+ fireEvent.click(screen.getByRole('button', { name: 'Respond' }));
+ const response = screen.getByRole('textbox', { name: 'Respond' });
+
+ fireEvent.keyDown(response, { key: 'Enter' });
+ expect(mockMutate).not.toHaveBeenCalled();
+
+ fireEvent.change(response, { target: { value: 'use the cache' } });
+ fireEvent.keyDown(response, { key: 'Enter' });
+ expect(submittedDecisions()).toEqual([
+ [{ tool_call_id: 'call-1', decision: 'respond', responseText: 'use the cache' }],
+ ]);
+ });
+
+ test('Enter in the JSON edit field never submits; Ctrl+Enter submits valid JSON only', () => {
+ renderLive(['approve', 'edit']);
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }));
+ const editor = screen.getByRole('textbox', { name: 'Edit' });
+
+ const enter = fireEvent.keyDown(editor, { key: 'Enter' });
+ expect(enter).toBe(true);
+ expect(mockMutate).not.toHaveBeenCalled();
+
+ fireEvent.change(editor, { target: { value: '{ "a": ' } });
+ fireEvent.keyDown(editor, { key: 'Enter', ctrlKey: true });
+ expect(mockMutate).not.toHaveBeenCalled();
+
+ fireEvent.change(editor, { target: { value: '{ "a": 2 }' } });
+ fireEvent.keyDown(editor, { key: 'Enter', ctrlKey: true, shiftKey: true });
+ fireEvent.keyDown(editor, { key: 'Enter', ctrlKey: true, repeat: true });
+ expect(mockMutate).not.toHaveBeenCalled();
+
+ fireEvent.keyDown(editor, { key: 'Enter', ctrlKey: true });
+ expect(submittedDecisions()).toEqual([
+ [{ tool_call_id: 'call-1', decision: 'edit', editedArguments: { a: 2 } }],
+ ]);
+ });
+
+ test('a submit shortcut rebound off Enter submits from either field', () => {
+ const ctrlJ: ShortcutBinding = {
+ key: 'J',
+ ctrl: true,
+ meta: false,
+ alt: false,
+ shift: false,
+ };
+ renderLive(['reject', 'edit'], { submitOverride: ctrlJ });
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }));
+ fireEvent.keyDown(screen.getByRole('textbox', { name: 'Edit' }), { key: 'j', ctrlKey: true });
+ expect(mockMutate).toHaveBeenCalledTimes(1);
+ });
+
+ test('Ctrl+Enter in the JSON edit field follows the composer submit chord', () => {
+ const altEnter: ShortcutBinding = {
+ key: 'Enter',
+ ctrl: false,
+ meta: false,
+ alt: true,
+ shift: false,
+ };
+ const cases: Array<{ shortcutsEnabled?: boolean; submitOverride: ShortcutBinding | null }> = [
+ { shortcutsEnabled: false, submitOverride: null },
+ { submitOverride: null },
+ { submitOverride: altEnter },
+ ];
+ for (const options of cases) {
+ cleanup();
+ renderLive(['approve', 'edit'], options);
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }));
+ const editor = screen.getByRole('textbox', { name: 'Edit' });
+ fireEvent.change(editor, { target: { value: '{ "a": 2 }' } });
+ expect(fireEvent.keyDown(editor, { key: 'Enter', ctrlKey: true })).toBe(true);
+ expect(fireEvent.keyDown(editor, { key: 'Enter', metaKey: true })).toBe(true);
+ }
+ expect(mockMutate).not.toHaveBeenCalled();
+
+ fireEvent.keyDown(screen.getByRole('textbox', { name: 'Edit' }), {
+ key: 'Enter',
+ altKey: true,
+ });
+ expect(mockMutate).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/client/src/components/Chat/approval/Review.tsx b/client/src/components/Chat/approval/Review.tsx
index a4f5351ca0..652e1c9263 100644
--- a/client/src/components/Chat/approval/Review.tsx
+++ b/client/src/components/Chat/approval/Review.tsx
@@ -3,6 +3,7 @@ import { useAtom, useAtomValue } from 'jotai';
import { Button, TooltipAnchor } from '@librechat/client';
import { ChevronDown, ChevronUp, ShieldQuestion, TriangleAlert } from 'lucide-react';
import type { Agents } from 'librechat-data-provider';
+import type { KeyboardEvent, RefObject } from 'react';
import type { TranslationKeys } from '~/hooks';
import {
useApprovalContext,
@@ -15,6 +16,7 @@ import {
import { buildApprovalPreview, buildApprovalPreviews } from '~/components/Chat/approval/preview';
import ToolApproval from '~/components/Chat/Messages/Content/ToolApproval';
import { useComposerOverlay } from '~/components/Chat/Input/overlay';
+import { isCancelKey } from '~/utils/shortcuts';
import { useLocalize } from '~/hooks';
function usePendingToolApproval(conversationId: string) {
@@ -53,8 +55,11 @@ function previewTitle(
export const PendingToolApprovalPanel = memo(function PendingToolApprovalPanel({
conversationId,
+ triggerRef,
}: {
conversationId: string;
+ /** The composer toggle that reopens the panel; collapsing returns focus to it. */
+ triggerRef?: RefObject<HTMLButtonElement>;
}) {
const localize = useLocalize();
const pendingAction = usePendingToolApproval(conversationId);
@@ -88,6 +93,22 @@ export const PendingToolApprovalPanel = memo(function PendingToolApprovalPanel({
return null;
}
+ /** Collapsing unmounts the focused control, so focus goes back to the
+ * toggle rather than falling to the page. Decisions and drafts are kept. */
+ const collapse = () => {
+ setOpen(false);
+ triggerRef?.current?.focus();
+ };
+
+ const handleKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
+ const isComposing = e.nativeEvent.isComposing || e.key === 'Process' || e.keyCode === 229;
+ if (!isCancelKey(e.nativeEvent) || isComposing) {
+ return;
+ }
+ e.preventDefault();
+ collapse();
+ };
+
const decisions = getDecisions(pendingAction.actionId);
const status = getStatus(pendingAction.actionId);
const locked = status === 'submitting' || status === 'submitted' || status === 'expired';
@@ -102,6 +123,7 @@ export const PendingToolApprovalPanel = memo(function PendingToolApprovalPanel({
role="region"
aria-labelledby="pending-tool-approval-title"
aria-live="polite"
+ onKeyDown={handleKeyDown}
>
<div className="popover border-border-light bg-surface-primary-alt rounded-theme-popover pointer-events-auto flex max-h-[70vh] flex-col border shadow-lg">
<div className="border-border-light flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2">
@@ -120,7 +142,7 @@ export const PendingToolApprovalPanel = memo(function PendingToolApprovalPanel({
size="icon"
aria-label={localize('com_ui_collapse')}
className="size-auto rounded-md p-1"
- onClick={() => setOpen(false)}
+ onClick={collapse}
>
<ChevronDown className="size-4" aria-hidden="true" />
</Button>
@@ -211,8 +233,10 @@ export const PendingToolApprovalPanel = memo(function PendingToolApprovalPanel({
export const PendingToolApprovalButton = memo(function PendingToolApprovalButton({
conversationId,
+ triggerRef,
}: {
conversationId: string;
+ triggerRef?: RefObject<HTMLButtonElement>;
}) {
const localize = useLocalize();
const pendingAction = usePendingToolApproval(conversationId);
@@ -225,6 +249,7 @@ export const PendingToolApprovalButton = memo(function PendingToolApprovalButton
const count = pendingAction.payload.action_requests.length;
return (
<Button
+ ref={triggerRef}
type="button"
variant="quiet"
size="sm"
diff --git a/client/src/components/Chat/approval/__tests__/Review.test.tsx b/client/src/components/Chat/approval/__tests__/Review.test.tsx
index 0441bcefa2..066ee01872 100644
--- a/client/src/components/Chat/approval/__tests__/Review.test.tsx
+++ b/client/src/components/Chat/approval/__tests__/Review.test.tsx
@@ -9,9 +9,18 @@ import ApprovalProvider from '../../Messages/Content/ApprovalContext';
import { pendingApprovalActionFamily } from '../state';
jest.mock('@librechat/client', () => ({
- Button: ({ children, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
- <button {...props}>{children}</button>
- ),
+ Button: jest
+ .requireActual('react')
+ .forwardRef(
+ (
+ { children, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>,
+ ref: React.Ref<HTMLButtonElement>,
+ ) => (
+ <button ref={ref} {...props}>
+ {children}
+ </button>
+ ),
+ ),
TextareaAutosize: (props: React.TextareaHTMLAttributes<HTMLTextAreaElement>) => (
<textarea {...props} />
),
@@ -124,4 +133,60 @@ describe('PendingToolApproval', () => {
'false',
);
});
+
+ describe('collapsing from the keyboard', () => {
+ function Harness() {
+ const triggerRef = React.useRef<HTMLButtonElement>(null);
+ return (
+ <>
+ <PendingToolApprovalPanel conversationId="conversation-1" triggerRef={triggerRef} />
+ <PendingToolApprovalButton conversationId="conversation-1" triggerRef={triggerRef} />
+ </>
+ );
+ }
+
+ const renderPanel = () => {
+ const jotaiStore = createStore();
+ jotaiStore.set(pendingApprovalActionFamily('conversation-1'), pendingAction);
+ render(
+ <RecoilRoot>
+ <JotaiProvider store={jotaiStore}>
+ <ApprovalProvider pendingAction={pendingAction}>
+ <Harness />
+ </ApprovalProvider>
+ </JotaiProvider>
+ </RecoilRoot>,
+ );
+ return jotaiStore;
+ };
+
+ test('Escape collapses the panel, keeps decisions and returns focus to the toggle', async () => {
+ renderPanel();
+ await screen.findByRole('region', { name: 'Review 2 actions' });
+ const approve = screen.getAllByRole('button', { name: 'Approve' })[0];
+ fireEvent.click(approve);
+ approve.focus();
+
+ fireEvent.keyDown(approve, { key: 'Escape', isComposing: true });
+ fireEvent.keyDown(approve, { key: 'Escape', keyCode: 229 });
+ fireEvent.keyDown(approve, { key: 'Escape', shiftKey: true });
+ expect(screen.getByRole('region', { name: 'Review 2 actions' })).toBeInTheDocument();
+
+ fireEvent.keyDown(approve, { key: 'Escape' });
+ expect(screen.queryByRole('region', { name: 'Review 2 actions' })).not.toBeInTheDocument();
+ const toggle = screen.getByTestId('pending-tool-approval-button');
+ expect(toggle).toHaveFocus();
+ expect(toggle).toHaveAttribute('aria-expanded', 'false');
+
+ fireEvent.click(toggle);
+ expect(screen.getByText('1 of 2 decisions selected')).toBeInTheDocument();
+ });
+
+ test('the Collapse button also returns focus to the toggle', async () => {
+ renderPanel();
+ await screen.findByRole('region', { name: 'Review 2 actions' });
+ fireEvent.click(screen.getByRole('button', { name: 'Collapse' }));
+ expect(screen.getByTestId('pending-tool-approval-button')).toHaveFocus();
+ });
+ });
});
diff --git a/client/src/hooks/Input/useComposerBindings.ts b/client/src/hooks/Input/useComposerBindings.ts
index f08377eeea..39a5c356fa 100644
--- a/client/src/hooks/Input/useComposerBindings.ts
+++ b/client/src/hooks/Input/useComposerBindings.ts
@@ -28,6 +28,14 @@ export type ComposerBindings = {
yieldedChords: ReadonlySet<string>;
};
+/** Default bindings for a card rendered without a chat surface host
+ * (Share, search), where the user's custom shortcuts are not in scope. */
+export const NO_HOST_BINDINGS: ComposerBindings = {
+ shortcutsEnabled: true,
+ submitOverride: undefined,
+ yieldedChords: new Set(),
+};
+
/** The user's effective composer-relevant shortcut bindings, shared by the
* composer keydown handler and the during-run hovercard hints. */
export default function useComposerBindings(): ComposerBindings {
diff --git a/e2e/specs/mock/scenarios/tool-approval-keyboard.spec.ts b/e2e/specs/mock/scenarios/tool-approval-keyboard.spec.ts
new file mode 100644
index 0000000000..64ca8abdef
--- /dev/null
+++ b/e2e/specs/mock/scenarios/tool-approval-keyboard.spec.ts
@@ -0,0 +1,131 @@
+import { expect, test } from '@playwright/test';
+import type { Page, Request } from '@playwright/test';
+import type { ApprovalResumeBody } from '../approvals.helpers';
+import {
+ uniqueLabel,
+ isResumeRequest,
+ APPROVAL_PROMPT_MARKER,
+ composerApprovalPanel,
+ clearApprovalInvocations,
+ createAndSelectApprovalAgent,
+ expectApprovalInvocationCount,
+} from '../approvals.helpers';
+import { cleanupAgent, closeMobileDrawer } from '../agents.helpers';
+import { messagesView, sendMessage } from '../helpers';
+
+/**
+ * Keyboard control of a live tool approval in the composer review panel. The
+ * fake model pauses a real agent run on the approval MCP tool for
+ * `E2E_TOOL_APPROVAL:`; the panel, decision state and resume request are the
+ * production ones. The e2e user has Enter-to-send on (setup/authenticate.ts),
+ * so Enter in a decision field submits and Shift+Enter writes a newline.
+ */
+
+const approvalChip = (page: Page) => page.getByTestId('pending-tool-approval-button');
+
+async function openApproval(page: Page, label: string) {
+ const response = await sendMessage(page, `${APPROVAL_PROMPT_MARKER}${label}`);
+ expect(response.ok()).toBeTruthy();
+ await expect(page).toHaveURL(/\/c\/(?!new)/, { timeout: 15000 });
+ const panel = composerApprovalPanel(page);
+ await expect(panel).toBeVisible({ timeout: 30000 });
+ return panel;
+}
+
+function recordResumes(page: Page) {
+ const resumes: Request[] = [];
+ page.on('request', (request) => {
+ if (isResumeRequest(request)) {
+ resumes.push(request);
+ }
+ });
+ return resumes;
+}
+
+test.describe('tool approval keyboard control', () => {
+ test('Escape collapses the review panel to its toggle and keeps the decision @scenario:approval-panel-escape-returns-to-toggle', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ const label = uniqueLabel();
+ const value = `original-${label}`;
+ let agentId: string | undefined;
+ clearApprovalInvocations(value);
+
+ try {
+ agentId = await createAndSelectApprovalAgent(page);
+ await closeMobileDrawer(page);
+ const panel = await openApproval(page, label);
+ const resumes = recordResumes(page);
+
+ const approve = panel.getByRole('button', { name: 'Approve', exact: true });
+ await approve.click();
+ await expect(approve).toHaveAttribute('aria-pressed', 'true');
+ await expect(approve).toBeFocused();
+
+ await page.keyboard.press('Escape');
+ await expect(panel).toHaveCount(0);
+ await expect(approvalChip(page)).toBeFocused();
+ await expect(approvalChip(page)).toHaveAttribute('aria-expanded', 'false');
+ expect(resumes).toHaveLength(0);
+
+ await page.keyboard.press('Enter');
+ await expect(panel).toBeVisible();
+ await expect(panel.getByRole('button', { name: 'Approve', exact: true })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ expect(resumes).toHaveLength(0);
+ await expectApprovalInvocationCount(value, 0);
+ } finally {
+ clearApprovalInvocations(value);
+ await cleanupAgent(page, agentId);
+ }
+ });
+
+ test('a reject reason is submitted from the keyboard @scenario:approval-reject-reason-submits-from-keyboard', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ const label = uniqueLabel();
+ const value = `original-${label}`;
+ let agentId: string | undefined;
+ clearApprovalInvocations(value);
+
+ try {
+ agentId = await createAndSelectApprovalAgent(page);
+ await closeMobileDrawer(page);
+ const panel = await openApproval(page, label);
+ const resumes = recordResumes(page);
+
+ await panel.getByRole('button', { name: 'Reject', exact: true }).click();
+ const reason = panel.getByRole('textbox', { name: 'Reject' });
+ await reason.click();
+ await page.keyboard.type('wrong value');
+ await page.keyboard.press('Shift+Enter');
+ await page.keyboard.type('try again');
+ await expect(reason).toHaveValue('wrong value\ntry again');
+ expect(resumes).toHaveLength(0);
+
+ const [resume] = await Promise.all([
+ page.waitForRequest(isResumeRequest),
+ page.keyboard.press('Enter'),
+ ]);
+ const body = resume.postDataJSON() as ApprovalResumeBody;
+ expect(body.decisions).toEqual([
+ expect.objectContaining({ decision: 'reject', reason: 'wrong value\ntry again' }),
+ ]);
+ await expect(panel).toHaveCount(0, { timeout: 30000 });
+ await expect(
+ messagesView(page)
+ .getByText(/^E2E approval outcomes:/)
+ .last(),
+ ).toBeVisible({ timeout: 30000 });
+ await expectApprovalInvocationCount(value, 0);
+ expect(resumes).toHaveLength(1);
+ } finally {
+ clearApprovalInvocations(value);
+ await cleanupAgent(page, agentId);
+ }
+ });
+});