Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ’„ style: add Enter / Esc hotkeys to AskUserQuestion intervention (#17733)

YuTengjing8126a8b62eb9
diff --git a/packages/shared-tool-ui/package.json b/packages/shared-tool-ui/package.json
index e174d449f31..9137aa823e0 100644
--- a/packages/shared-tool-ui/package.json
+++ b/packages/shared-tool-ui/package.json
@@ -9,6 +9,7 @@
"./inspectors": "./src/Inspector/index.ts",
"./inspectors/github-labels": "./src/Inspector/GitHub/labels.ts",
"./inspectors/linear-labels": "./src/Inspector/Linear/labels.ts",
+ "./pending-hotkeys": "./src/pendingHotkeys.ts",
"./renders": "./src/Render/index.ts",
"./styles": "./src/styles.ts"
},
diff --git a/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx b/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx
index 4207cd89645..fb7c7881b9f 100644
--- a/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx
+++ b/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx
@@ -1,11 +1,12 @@
'use client';
-import { Flexbox, Icon, Text, TextArea } from '@lobehub/ui';
+import { Flexbox, Hotkey, Icon, KeyMapEnum, Text, TextArea } from '@lobehub/ui';
import { Button, Tabs } from '@lobehub/ui/base-ui';
import { Check, PenLine, Send, X } from 'lucide-react';
-import { memo } from 'react';
+import { memo, useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
+import { registerPendingHotkeyCard } from '../pendingHotkeys';
import { formatRemaining, isQuestionAnswered } from './draft';
import QuestionPanel from './QuestionPanel';
import type { AskUserFormApi } from './useAskUserForm';
@@ -45,7 +46,8 @@ export interface AskUserQuestionViewProps extends AskUserFormApi {
* - a Skip/Submit footer with an optional countdown.
*
* All state and handlers arrive via props (from `useAskUserForm`); this
- * component is pure view and holds no state of its own.
+ * component holds no state of its own β€” its only side effect is the
+ * window-level Enter-to-submit / Esc-to-skip shortcut listener.
*/
export const AskUserQuestionView = memo<AskUserQuestionViewProps>((props) => {
const {
@@ -73,6 +75,71 @@ export const AskUserQuestionView = memo<AskUserQuestionViewProps>((props) => {
submitting,
} = props;
+ const rootRef = useRef<HTMLDivElement>(null);
+ const portalRef = useRef(actionsPortalTarget);
+
+ // Page-level keyboard: Enter submits, Esc skips β€” the card is the pending
+ // interaction, so the shortcuts work without focusing it first. Backs off
+ // while the user is typing anywhere outside the card (chat composer
+ // included; the card's own textareas handle Enter via their onKeyDown while
+ // Esc keeps skipping there), when the event was already consumed (e.g. an
+ // overlay closing itself on Esc), or inside open overlays so Esc keeps
+ // meaning "close this overlay" there.
+ //
+ // Read through a ref so the arbiter registration below stays mount-stable
+ // while the handler always sees fresh state.
+ const onKeyDownRef = useRef<(event: KeyboardEvent) => void>(() => {});
+ useEffect(() => {
+ portalRef.current = actionsPortalTarget;
+ onKeyDownRef.current = (event) => {
+ if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;
+ const target = event.target as HTMLElement | null;
+ if (target) {
+ const tag = target.tagName;
+ if (tag === 'INPUT' || tag === 'TEXTAREA' || target.isContentEditable) {
+ // Typing inside this card only backs off Enter (handled by the
+ // textarea itself) β€” the advertised Esc-to-skip must keep working.
+ // The IME guard keeps Esc-canceling a CJK composition from skipping.
+ const typingInCard = rootRef.current?.contains(target) ?? false;
+ if (!typingInCard || event.key !== 'Escape' || event.isComposing) return;
+ }
+ if (target.closest('[role="dialog"],[role="alertdialog"],[role="menu"]')) return;
+ }
+ if (event.key === 'Enter') {
+ if (event.shiftKey || isSubmitDisabled) return;
+ // A focused interactive control (e.g. tabbing to the Skip button, a
+ // tab, or a link) keeps its native Enter activation β€” hijacking it
+ // into submit would invert the keyboard user's intent.
+ if (
+ target?.closest(
+ 'a,button,select,summary,[role="button"],[role="tab"],[role="option"],[role="menuitem"]',
+ )
+ )
+ return;
+ event.preventDefault();
+ handleSubmit();
+ } else if (event.key === 'Escape') {
+ if (submitting) return;
+ event.preventDefault();
+ handleSkip();
+ }
+ };
+ }, [actionsPortalTarget, handleSubmit, handleSkip, isSubmitDisabled, submitting]);
+
+ // Registered once per mount: the shared arbiter dispatches each keypress to
+ // exactly one pending card (containment first, then newest registration), so
+ // coexisting cards β€” this one, the global notification's, a tool-approval
+ // card β€” never race on the same keystroke, regardless of re-render timing.
+ useEffect(
+ () =>
+ registerPendingHotkeyCard({
+ contains: (node) =>
+ Boolean(rootRef.current?.contains(node)) || Boolean(portalRef.current?.contains(node)),
+ onKeyDown: (event) => onKeyDownRef.current(event),
+ }),
+ [],
+ );
+
const footer = (
<Flexbox
horizontal
@@ -89,6 +156,7 @@ export const AskUserQuestionView = memo<AskUserQuestionViewProps>((props) => {
<Flexbox horizontal gap={8}>
<Button disabled={submitting} icon={<Icon icon={X} />} onClick={handleSkip}>
{labels.skip}
+ <Hotkey compact keys={KeyMapEnum.Esc} variant="borderless" />
</Button>
<Button
disabled={isSubmitDisabled}
@@ -98,13 +166,14 @@ export const AskUserQuestionView = memo<AskUserQuestionViewProps>((props) => {
onClick={handleSubmit}
>
{labels.submit}
+ <Hotkey compact inverseTheme keys={KeyMapEnum.Enter} variant="borderless" />
</Button>
</Flexbox>
</Flexbox>
);
return (
- <Flexbox gap={12}>
+ <Flexbox gap={12} ref={rootRef}>
{isMulti && (
<Tabs
activeKey={escapeActive ? 'escape' : activeTab}
@@ -154,6 +223,16 @@ export const AskUserQuestionView = memo<AskUserQuestionViewProps>((props) => {
value={escapeText}
variant="filled"
onChange={(e) => handleEscapeTextChange(e.target.value)}
+ onKeyDown={(e) => {
+ // Enter submits (Shift+Enter keeps inserting a newline); fall back
+ // to the default newline while submit is unavailable. The IME guard
+ // keeps CJK composition confirms from submitting the form.
+ if (e.key !== 'Enter' || e.shiftKey || e.nativeEvent.isComposing) return;
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
+ if (isSubmitDisabled) return;
+ e.preventDefault();
+ handleSubmit();
+ }}
/>
) : (
activeQuestion && (
@@ -165,6 +244,7 @@ export const AskUserQuestionView = memo<AskUserQuestionViewProps>((props) => {
multiSelectTag={labels.multiSelectTag}
question={activeQuestion}
onCustomChange={handleCustomChange}
+ onPressEnter={isSubmitDisabled ? undefined : handleSubmit}
onToggle={handleToggle}
/>
)
diff --git a/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx b/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx
index 8d83c50a522..c10d9855dce 100644
--- a/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx
+++ b/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx
@@ -49,6 +49,12 @@ interface QuestionPanelProps {
/** Tag shown next to the header when the question is multi-select. */
multiSelectTag: string;
onCustomChange: (q: AskUserQuestionItem, value: string) => void;
+ /**
+ * Submit the whole form from the free-text box on Enter (Shift+Enter still
+ * inserts a newline). Pass `undefined` while submit is unavailable so Enter
+ * falls back to the default newline behavior.
+ */
+ onPressEnter?: () => void;
onToggle: (q: AskUserQuestionItem, label: string) => void;
question: AskUserQuestionItem;
}
@@ -70,6 +76,7 @@ export const QuestionPanel = memo<QuestionPanelProps>(
multiSelectTag,
onToggle,
onCustomChange,
+ onPressEnter,
}) => {
const isOptionSelected = (label: string): boolean =>
question.multiSelect ? Array.isArray(answer) && answer.includes(label) : answer === label;
@@ -110,6 +117,14 @@ export const QuestionPanel = memo<QuestionPanelProps>(
value={customValue}
variant="filled"
onChange={(e) => onCustomChange(question, e.target.value)}
+ onKeyDown={(e) => {
+ // The IME guard keeps CJK composition confirms from submitting.
+ if (e.key !== 'Enter' || e.shiftKey || e.nativeEvent.isComposing) return;
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
+ if (!onPressEnter) return;
+ e.preventDefault();
+ onPressEnter();
+ }}
/>
</Flexbox>
</Flexbox>
diff --git a/packages/shared-tool-ui/src/pendingHotkeys.ts b/packages/shared-tool-ui/src/pendingHotkeys.ts
new file mode 100644
index 00000000000..4f41a009aaa
--- /dev/null
+++ b/packages/shared-tool-ui/src/pendingHotkeys.ts
@@ -0,0 +1,46 @@
+/**
+ * Single-owner arbiter for page-level "pending interaction" hotkeys.
+ *
+ * Several pending-interaction cards can be mounted at once β€” e.g. the active
+ * conversation's AskUserQuestion / tool-approval card plus the global approval
+ * notification surfacing another conversation's card. If each installed its
+ * own `window` keydown listener, one keystroke could drive several cards, and
+ * which card saw it first would follow window listener registration order β€”
+ * which silently reshuffles whenever any card's effect re-registers.
+ *
+ * Instead the arbiter owns the ONE window listener and dispatches each
+ * keypress to exactly one card:
+ * 1. the card containing the event target (focus/containment wins), else
+ * 2. the most recently registered card.
+ *
+ * Registration order only matters as the fallback, and is stable as long as
+ * cards register once per mount.
+ */
+export interface PendingHotkeyCard {
+ /** Whether the node lives inside this card (root or portaled footer). */
+ contains: (node: Node) => boolean;
+ /** Handle a keypress this card owns; apply per-card guards inside. */
+ onKeyDown: (event: KeyboardEvent) => void;
+}
+
+const cards: PendingHotkeyCard[] = [];
+
+const dispatch = (event: KeyboardEvent) => {
+ const target = event.target as Node | null;
+ const owner = (target && cards.find((card) => card.contains(target))) ?? cards.at(-1);
+ owner?.onKeyDown(event);
+};
+
+/**
+ * Register a card for its mount lifetime; returns the unregister cleanup.
+ * The shared window listener exists only while at least one card is mounted.
+ */
+export const registerPendingHotkeyCard = (card: PendingHotkeyCard): (() => void) => {
+ if (cards.length === 0) window.addEventListener('keydown', dispatch);
+ cards.push(card);
+ return () => {
+ const idx = cards.indexOf(card);
+ if (idx >= 0) cards.splice(idx, 1);
+ if (cards.length === 0) window.removeEventListener('keydown', dispatch);
+ };
+};
diff --git a/src/features/Conversation/InterventionBar/index.tsx b/src/features/Conversation/InterventionBar/index.tsx
index 41f10e4ad59..32101a05288 100644
--- a/src/features/Conversation/InterventionBar/index.tsx
+++ b/src/features/Conversation/InterventionBar/index.tsx
@@ -36,6 +36,7 @@ const InterventionBar = memo<InterventionBarProps>(({ interventions }) => {
return (
<ChatInput
+ data-pending-hotkey-scope
className={styles.container}
footer={<div className={styles.actions} ref={setActionsPortalTarget} />}
maxHeight={'50vh' as any}
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx
index f43fed5f51f..9ae8d5faac4 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx
@@ -1,3 +1,4 @@
+import { registerPendingHotkeyCard } from '@lobechat/shared-tool-ui/pending-hotkeys';
import { Flexbox } from '@lobehub/ui';
import { Button } from '@lobehub/ui/base-ui';
import { createStaticStyles, cx } from 'antd-style';
@@ -194,12 +195,17 @@ const ApprovalActions = memo<ApprovalActionsProps>(
}
}, [choice]);
- // Window-level keyboard: 1/2/↑/↓ to switch, Enter to submit. Skip while
+ // Page-level keyboard: 1/2/↑/↓ to switch, Enter to submit. Skip while
// typing anywhere on the page so we never hijack the main chat composer.
// The reject input has its own onKeyDown for Enter / ↑.
+ //
+ // Kept fresh in a ref so the shared-arbiter registration below stays
+ // mount-stable while the handler always sees current state.
+ const containerRef = useRef<HTMLDivElement>(null);
+ const onKeyDownRef = useRef<(e: KeyboardEvent) => void>(() => {});
useEffect(() => {
- if (!canUseResource) return;
- const handler = (e: KeyboardEvent) => {
+ onKeyDownRef.current = (e: KeyboardEvent) => {
+ if (e.defaultPrevented) return;
const target = e.target as HTMLElement | null;
if (target) {
const tag = target.tagName;
@@ -236,11 +242,27 @@ const ApprovalActions = memo<ApprovalActionsProps>(
// No default
}
};
- window.addEventListener('keydown', handler);
- return () => {
- window.removeEventListener('keydown', handler);
- };
- }, [canUseResource, choices, handleSubmit]);
+ }, [choices, handleSubmit]);
+
+ // One registration per mount: the shared arbiter dispatches each keypress
+ // to exactly one pending card (containment first, then newest
+ // registration), so this card and a coexisting AskUserQuestion card (e.g.
+ // in the global approval notification) never race on the same keystroke.
+ useEffect(() => {
+ if (!canUseResource) return;
+ return registerPendingHotkeyCard({
+ // The footer may be portaled away from the intervention body, so
+ // containment covers the whole owning surface (marked with
+ // `data-pending-hotkey-scope`: InterventionBar / global approval
+ // card), falling back to the footer itself when rendered inline.
+ contains: (node) => {
+ const el = containerRef.current;
+ if (!el) return false;
+ return (el.closest('[data-pending-hotkey-scope]') ?? el).contains(node);
+ },
+ onKeyDown: (e) => onKeyDownRef.current(e),
+ });
+ }, [canUseResource]);
const handleRejectInputKeyDown = (e: ReactKeyboardEvent<HTMLInputElement>) => {
if (e.metaKey || e.ctrlKey || e.altKey) return;
@@ -268,7 +290,7 @@ const ApprovalActions = memo<ApprovalActionsProps>(
if (!canUseResource) return null;
return (
- <Flexbox className={styles.container}>
+ <Flexbox className={styles.container} ref={containerRef}>
<div className={styles.optionList} role="radiogroup">
{choices.map((c, index) => {
if (c === 'reject') {
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx
index 6209695b1a9..1efed4091f7 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx
@@ -218,7 +218,7 @@ const Intervention = memo<InterventionProps>(
);
return (
- <Flexbox gap={12}>
+ <Flexbox data-pending-hotkey-scope gap={12}>
<SecurityBlacklistWarning args={parsedArgs} />
<BuiltinToolInterventionRender
apiName={apiName}
diff --git a/src/features/GlobalApprovalNotification/ApprovalCard.tsx b/src/features/GlobalApprovalNotification/ApprovalCard.tsx
index 9260fe48017..efe38628c2a 100644
--- a/src/features/GlobalApprovalNotification/ApprovalCard.tsx
+++ b/src/features/GlobalApprovalNotification/ApprovalCard.tsx
@@ -142,7 +142,7 @@ const ApprovalCard = memo<ApprovalCardProps>(({ group }) => {
operationState={operationState}
onMessagesChange={handleMessagesChange}
>
- <div className={styles.card}>
+ <div data-pending-hotkey-scope className={styles.card}>
<div className={styles.header}>
<Avatar
avatar={meta.avatar}