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

⌨️ fix: Honor `defaultPrevented` in Global Shortcut Dispatch (#14570)

Danny Avilacdb60e74c215
diff --git a/client/src/components/Chat/Input/__tests__/DuringRunSendButton.test.tsx b/client/src/components/Chat/Input/__tests__/DuringRunSendButton.test.tsx
index 677cf30a59..6bebb0c8bc 100644
--- a/client/src/components/Chat/Input/__tests__/DuringRunSendButton.test.tsx
+++ b/client/src/components/Chat/Input/__tests__/DuringRunSendButton.test.tsx
@@ -201,8 +201,8 @@ describe('DuringRunSendButton — Enter hint follows the interrupt preference',
* Hints come from the same decision table the composer executes
* (`resolveComposerKeyDown`), so a chord that no longer triggers a row is
* never advertised on it. Covers codex round 3: a chord rebound to an
- * editing-allowed global shortcut is yielded to the document handler, and a
- * submit rebound to Alt+Enter submits instead of interrupting.
+ * editing-allowed global shortcut is yielded to the window-level handler,
+ * and a submit rebound to Alt+Enter submits instead of interrupting.
*/
describe('DuringRunSendButton — hints follow the effective bindings', () => {
const kbdFor = (label: string) =>
diff --git a/client/src/hooks/Input/useComposerBindings.ts b/client/src/hooks/Input/useComposerBindings.ts
index 5da7acf476..2330520f12 100644
--- a/client/src/hooks/Input/useComposerBindings.ts
+++ b/client/src/hooks/Input/useComposerBindings.ts
@@ -14,10 +14,11 @@ export type ComposerBindings = {
submitOverride: ShortcutBinding | null | undefined;
/**
* Chords the user has bound to global shortcuts that still run while typing
- * (`EDITING_ALLOWED_SHORTCUTS`). The document-level handler in
- * `useKeyboardShortcuts` runs AFTER the composer's and does not check
- * `defaultPrevented`, so the composer must leave these chords entirely to it
- * — acting on them too would fire both. `submitMessage` is excluded: its
+ * (`EDITING_ALLOWED_SHORTCUTS`). The window-level handler in
+ * `useKeyboardShortcuts` runs AFTER the composer's and yields any keypress
+ * a closer handler claimed via `preventDefault`, so the composer must leave
+ * these chords entirely untouched — acting on them would claim the event
+ * and silently swallow the global action. `submitMessage` is excluded: its
* rebinding is resolved through `submitOverride` instead. No default binding
* uses an Enter chord besides submit, so this only ever yields to a
* deliberate rebinding.
diff --git a/client/src/hooks/useKeyboardShortcuts.spec.tsx b/client/src/hooks/useKeyboardShortcuts.spec.tsx
index 20bc2484ea..ef1833953e 100644
--- a/client/src/hooks/useKeyboardShortcuts.spec.tsx
+++ b/client/src/hooks/useKeyboardShortcuts.spec.tsx
@@ -190,6 +190,57 @@ describe('global shortcut dispatch', () => {
expect(getByTestId('sidebar').textContent).not.toBe(before);
});
+ it('yields when a closer handler already claimed the keypress', () => {
+ const { getByTestId } = renderHarness();
+ const before = getByTestId('sidebar').textContent;
+ const widget = document.createElement('div');
+ widget.addEventListener('keydown', (e) => e.preventDefault());
+ document.body.appendChild(widget);
+
+ dispatchKey({ key: 's', ctrlKey: true, shiftKey: true }, widget);
+
+ expect(getByTestId('sidebar').textContent).toBe(before);
+ });
+
+ it('still acts when the same widget lets the keypress through', () => {
+ const { getByTestId } = renderHarness();
+ const before = getByTestId('sidebar').textContent;
+ const widget = document.createElement('div');
+ document.body.appendChild(widget);
+
+ const event = dispatchKey({ key: 's', ctrlKey: true, shiftKey: true }, widget);
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(getByTestId('sidebar').textContent).not.toBe(before);
+ });
+
+ it('yields to a document-level owner that registered after the dispatcher', () => {
+ const { getByTestId } = renderHarness();
+ const before = getByTestId('sidebar').textContent;
+ const claim = (e: KeyboardEvent) => e.preventDefault();
+ document.addEventListener('keydown', claim);
+
+ try {
+ dispatchKey({ key: 's', ctrlKey: true, shiftKey: true });
+ } finally {
+ document.removeEventListener('keydown', claim);
+ }
+
+ expect(getByTestId('sidebar').textContent).toBe(before);
+ });
+
+ it('yields an editing-allowed chord that the focused input claimed', () => {
+ renderHarness();
+ const escalation = appendEscalationButton('bubble');
+ const input = document.createElement('input');
+ input.addEventListener('keydown', (e) => e.preventDefault());
+ document.body.appendChild(input);
+
+ dispatchKey({ key: '.', ctrlKey: true, shiftKey: true }, input);
+
+ expect(escalation.onClick).not.toHaveBeenCalled();
+ });
+
it('ignores shortcuts while a modal dialog is open', () => {
renderHarness();
const dialog = document.createElement('div');
diff --git a/client/src/hooks/useKeyboardShortcuts.ts b/client/src/hooks/useKeyboardShortcuts.ts
index 290bc50b65..ca4ac620ac 100644
--- a/client/src/hooks/useKeyboardShortcuts.ts
+++ b/client/src/hooks/useKeyboardShortcuts.ts
@@ -288,9 +288,10 @@ export const shortcutDefinitions = {
export type ShortcutActionId = keyof typeof shortcutDefinitions;
/**
- * Shortcuts the document-level handler still runs while an input, textarea, or
- * contenteditable has focus. The composer yields chords bound to these so only
- * one handler acts on a keypress.
+ * Shortcuts the window-level handler still runs while an input, textarea, or
+ * contenteditable has focus. The composer yields chords bound to these by
+ * leaving the keypress unclaimed (no `preventDefault`), so only one handler
+ * acts on it.
*/
export const EDITING_ALLOWED_SHORTCUTS: ReadonlySet<ShortcutActionId> = new Set([
'focusChat',
@@ -1035,6 +1036,10 @@ export default function useKeyboardShortcuts() {
return;
}
+ if (e.defaultPrevented) {
+ return;
+ }
+
const binding = bindingFromEvent(e);
if (!binding) {
return;
@@ -1082,8 +1087,11 @@ export default function useKeyboardShortcuts() {
);
useEffect(() => {
- document.addEventListener('keydown', handler);
- return () => document.removeEventListener('keydown', handler);
+ /** window, not document: every element- and document-level owner sits
+ * earlier in the bubble path, so their `preventDefault` claims are
+ * visible here regardless of mount or registration order. */
+ window.addEventListener('keydown', handler);
+ return () => window.removeEventListener('keydown', handler);
}, [handler]);
}
diff --git a/client/src/utils/shortcuts.ts b/client/src/utils/shortcuts.ts
index f4078cbfa4..e6c0cb41a3 100644
--- a/client/src/utils/shortcuts.ts
+++ b/client/src/utils/shortcuts.ts
@@ -256,9 +256,10 @@ export interface ComposerKeyContext {
* The composer's entire Enter decision table. Every verdict is terminal — no
* interpretation falls through into another, which is what previously let a
* chord that one branch declined reach a branch it never should have.
- * `yieldedChords` belong to the document-level handler in
- * `useKeyboardShortcuts`, which runs after the composer and does not check
- * `defaultPrevented`, so the composer must not act on them at all. `block`
+ * `yieldedChords` belong to the window-level handler in
+ * `useKeyboardShortcuts`, which runs after the composer and yields any
+ * keypress already claimed via `preventDefault` — so the composer must not
+ * act on them at all, or the global action is silently swallowed. `block`
* means preventDefault with no action.
*/
export function resolveComposerKeyDown(
diff --git a/e2e/specs/mock/shortcuts.spec.ts b/e2e/specs/mock/shortcuts.spec.ts
new file mode 100644
index 0000000000..fec3d1a8a7
--- /dev/null
+++ b/e2e/specs/mock/shortcuts.spec.ts
@@ -0,0 +1,137 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import {
+ MOCK_ENDPOINTS,
+ NEW_CHAT_PATH,
+ isAgentsStream,
+ messagesView,
+ replyPrompt,
+ replyText,
+ selectMockEndpoint,
+ sendMessage,
+} from './helpers';
+
+const uniqueLabel = (prefix: string) =>
+ `${prefix}-${Date.now()}-${Math.floor(Math.random() * 1e4)}`;
+
+const messageTurns = (page: Page) => messagesView(page).locator('.message-render');
+const navRail = (page: Page) => page.getByRole('navigation', { name: 'Message navigation' });
+
+/** Persist a custom shortcut binding before the app boots, so the dispatcher
+ * resolves it at init exactly like a user-saved rebinding. */
+async function rebindShortcut(page: Page, actionId: string, chord: string) {
+ await page.addInitScript(
+ ([id, value]) => {
+ window.localStorage.setItem(
+ 'customKeyboardShortcuts',
+ JSON.stringify({ [id]: { mac: value, other: value } }),
+ );
+ },
+ [actionId, chord],
+ );
+}
+
+async function establishTurn(page: Page, label: string) {
+ const response = await sendMessage(page, replyPrompt(label));
+ expect(response.ok()).toBeTruthy();
+ await expect(messagesView(page).getByText(replyText(label))).toBeVisible({ timeout: 30000 });
+}
+
+/** Sending leaves the composer focused, where the dispatcher's editing gate
+ * swallows non-editing shortcuts before the yield contract is even reached.
+ * Both rail presses must happen with focus outside any input. */
+async function blurComposer(page: Page) {
+ await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
+}
+
+/**
+ * Real-browser regression net for the global shortcut dispatcher's yield
+ * contract (PR: honor `defaultPrevented`, window-level listener): a keypress
+ * claimed by a closer handler must not ALSO trigger a global action, while an
+ * unclaimed keypress still must. The jest suite proves the dispatcher logic
+ * against synthetic DOM; these two flows wire the REAL owners (the message-nav
+ * rail's document-level listener and the composer's keydown verdicts) through
+ * real Chromium event propagation.
+ */
+test.describe('global shortcut yield contract', () => {
+ test('a rebound chord fires globally until the message-nav rail claims it', async ({ page }) => {
+ test.setTimeout(120000);
+ const label = uniqueLabel('nav-claim');
+
+ // Bind "New chat" onto the rail's own chord so both want the keypress.
+ await rebindShortcut(page, 'newChat', 'Alt+Shift+M');
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+
+ // One turn: the rail needs 3+ entries, so it is NOT rendered yet and the
+ // chord is unclaimed. The global action must fire — this also proves the
+ // rebinding is live in this browser, so the claim assertion below cannot
+ // pass vacuously.
+ await establishTurn(page, `${label}-a`);
+ await expect(page).toHaveURL(/\/c\/[0-9a-fA-F-]{36}$/, { timeout: 15000 });
+ await expect(navRail(page)).toHaveCount(0);
+ await blurComposer(page);
+ await page.keyboard.press('Alt+Shift+M');
+ await expect(page).toHaveURL(/\/c\/new$/, { timeout: 10000 });
+
+ // Two turns in the fresh chat: the rail renders and now owns the chord.
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+ await establishTurn(page, `${label}-b`);
+ await expect(page).toHaveURL(/\/c\/[0-9a-fA-F-]{36}$/, { timeout: 15000 });
+ await establishTurn(page, `${label}-c`);
+ await expect(navRail(page)).toBeVisible({ timeout: 10000 });
+ const conversationUrl = page.url();
+
+ // The rail claims the keypress (focuses an entry + preventDefault); the
+ // rebound global action must yield: focus moves into the rail and the
+ // URL never flips back to /c/new.
+ await blurComposer(page);
+ await page.keyboard.press('Alt+Shift+M');
+ await expect(page.locator(':focus')).toHaveAttribute('data-msg-id', /.+/, { timeout: 5000 });
+ await expect(page).toHaveURL(conversationUrl);
+ });
+
+ test('a custom submit chord in the composer submits exactly once', async ({ page }) => {
+ test.setTimeout(120000);
+ const label = uniqueLabel('single-submit');
+ const prompt = replyPrompt(label);
+
+ // Rebind submit to Alt+Enter: the composer resolves the chord itself
+ // (claims the keypress), and the dispatcher's submitMessage action must
+ // yield instead of clicking send again — a regression here double-sends
+ // the same message.
+ await rebindShortcut(page, 'submitMessage', 'Alt+Enter');
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+
+ // The generation POST goes to /api/agents/chat/<endpoint>; collect every
+ // agents-chat POST path so a duplicate submit (same path, fired again)
+ // cannot hide, whatever the endpoint suffix is.
+ const agentPosts: string[] = [];
+ page.on('request', (request) => {
+ const { pathname } = new URL(request.url());
+ if (request.method() === 'POST' && pathname.startsWith('/api/agents/chat')) {
+ agentPosts.push(pathname);
+ }
+ });
+
+ const input = page.getByRole('textbox', { name: 'Message input' });
+ await input.click();
+ await input.fill(prompt);
+ const [response] = await Promise.all([
+ page.waitForResponse(isAgentsStream, { timeout: 30000 }),
+ input.press('Alt+Enter'),
+ ]);
+ expect(response.ok()).toBeTruthy();
+ const generationPath = new URL(response.url()).pathname;
+ await expect(messagesView(page).getByText(replyText(label))).toBeVisible({ timeout: 30000 });
+
+ // Settle briefly so a late duplicate submission would surface, then
+ // assert the single-fire invariant at both layers: one generation
+ // request on the wire, one user turn + one reply in the thread.
+ await page.waitForTimeout(750);
+ expect(agentPosts.filter((pathname) => pathname === generationPath)).toHaveLength(1);
+ await expect(messageTurns(page)).toHaveCount(2);
+ await expect(messagesView(page).getByText(prompt)).toHaveCount(1);
+ });
+});