AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(frontend): ignore Enter and other keys while an IME is composing (#14300)
Krzysztof Czerwinskieb351c870c72
diff --git a/AGENTS.md b/AGENTS.mdindex 37942f8002..049e98ee8d 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -32,6 +32,7 @@ See `/frontend/CONTRIBUTING.md` for complete patterns. Quick reference:4. **Styling**: Tailwind CSS only, use design tokens, Phosphor Icons only5. **Testing**: Integration tests (Vitest + RTL + MSW) are the default (~90%, page-level). Playwright for E2E critical flows. Storybook for design system components. See `autogpt_platform/frontend/TESTING.md`6. **Code conventions**: Function declarations (not arrow functions) for components/handlers+7. **Keyboard handling**: Use `isKey(e, "Enter")` (or `isKey(e, "Enter", " ")`) from `@/lib/keyboard` instead of comparing `e.key`. It returns false while an IME is composing (Japanese, Chinese, Korean input), when Enter/Space/arrows belong to the input method, not the app. The `Input` atom drops composing keydowns before calling `onKeyDown` as a safety net; every handler on a raw `<input>`/`<textarea>`, a container, or `document` must use `isKey` itself. That atom-level guard is deliberately unconditional, so a modifier chord wired through `<Input onKeyDown>` is dropped mid-composition too — handle chords outside the atom. For focus traps and other containment handlers, which must keep holding a key even while composing, use `isKeyIgnoringComposition`. ESLint (`no-restricted-syntax`) flags direct `.key` comparisons and switches against the IME key names only; `// eslint-disable-next-line no-restricted-syntax` is the escape hatch for a domain object that merely has a `.key` field (e.g. `column.key === "Delete"`). Modifier chords like Cmd+K, `.key.toLowerCase()` and `[...].includes(e.key)` are not checked and are out of scope, since an IME never owns them. Passing `e.key` on as a function argument (e.g. into a roving-focus helper) is also invisible to the rule — guard those handlers with `isComposingEvent(e)` at the top.- Component props should be `interface Props { ... }` (not exported) unless the interface needs to be used outside the component- Separate render logic from business logic (component.tsx + useComponent.ts + helpers.ts)diff --git a/autogpt_platform/frontend/.eslintrc.json b/autogpt_platform/frontend/.eslintrc.jsonindex 04a3f05d0f..97e8fccef6 100644--- a/autogpt_platform/frontend/.eslintrc.json+++ b/autogpt_platform/frontend/.eslintrc.json@@ -21,6 +21,36 @@"varsIgnorePattern": "^_","caughtErrorsIgnorePattern": "^_"}+ ],+ // Keyboard handlers must go through `isKey()` from `@/lib/keyboard` so that+ // keydowns fired while an IME is composing (Japanese, Chinese, Korean input)+ // are ignored. See AGENTS.md "Keyboard handling".+ //+ // Scope: direct `.key` comparisons and switches against the IME key names+ // (or KEY_* / *_KEY constants). Modifier chords such as Cmd+K, which read+ // `.key.toLowerCase()` or `.code`, are out of scope by design: an IME never+ // owns them. Keep the key list in sync with KEY_NAMES in src/lib/keyboard.ts.+ //+ // The selectors match any receiver, so a domain object that happens to have+ // a `.key` field (e.g. `column.key === "Delete"`) trips them too. That is+ // the one case for `// eslint-disable-next-line no-restricted-syntax`.+ //+ // Both the key list and the selectors are covered by+ // scripts/eslint-keyboard-rules.test.ts.+ "no-restricted-syntax": [+ "error",+ {+ "selector": "BinaryExpression[operator=/^[!=]==?$/]:matches([right.type='Literal'][right.value=/^(Enter|Escape|Tab|ArrowUp|ArrowDown|ArrowLeft|ArrowRight|PageUp|PageDown|Home|End|Backspace|Delete| )$/], [right.type='Identifier'][right.name=/(^KEY_|_KEY$)/]) > MemberExpression.left[computed=false][property.name='key']",+ "message": "Do not compare e.key directly; use isKey(e, \"Enter\") from @/lib/keyboard so IME composition is respected."+ },+ {+ "selector": "BinaryExpression[operator=/^[!=]==?$/]:matches([left.type='Literal'][left.value=/^(Enter|Escape|Tab|ArrowUp|ArrowDown|ArrowLeft|ArrowRight|PageUp|PageDown|Home|End|Backspace|Delete| )$/], [left.type='Identifier'][left.name=/(^KEY_|_KEY$)/]) > MemberExpression.right[computed=false][property.name='key']",+ "message": "Do not compare e.key directly; use isKey(e, \"Enter\") from @/lib/keyboard so IME composition is respected."+ },+ {+ "selector": "SwitchStatement[discriminant.type='MemberExpression'][discriminant.computed=false][discriminant.property.name='key'] > SwitchCase > :matches(Literal[value=/^(Enter|Escape|Tab|ArrowUp|ArrowDown|ArrowLeft|ArrowRight|PageUp|PageDown|Home|End|Backspace|Delete| )$/], Identifier[name=/(^KEY_|_KEY$)/])",+ "message": "Do not switch on e.key directly; use isKey(e, \"Enter\") from @/lib/keyboard so IME composition is respected."+ }]}}diff --git a/autogpt_platform/frontend/package.json b/autogpt_platform/frontend/package.jsonindex 7f701b2a60..d342d7cd13 100644--- a/autogpt_platform/frontend/package.json+++ b/autogpt_platform/frontend/package.json@@ -156,6 +156,7 @@"@testing-library/user-event": "14.6.1","@types/bcryptjs": "3.0.0","@types/canvas-confetti": "1.9.0",+ "@types/eslint": "8.56.12","@types/lodash": "4.17.20","@types/negotiator": "0.6.4","@types/node": "24.10.0",diff --git a/autogpt_platform/frontend/pnpm-lock.yaml b/autogpt_platform/frontend/pnpm-lock.yamlindex dab18cc464..d657737a22 100644--- a/autogpt_platform/frontend/pnpm-lock.yaml+++ b/autogpt_platform/frontend/pnpm-lock.yaml@@ -380,6 +380,9 @@ importers:'@types/canvas-confetti':specifier: 1.9.0version: 1.9.0+ '@types/eslint':+ specifier: 8.56.12+ version: 8.56.12'@types/lodash':specifier: 4.17.20version: 4.17.20@@ -4014,8 +4017,8 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==}- '@types/[email protected]':- resolution: {integrity: sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==}+ '@types/[email protected]':+ resolution: {integrity: sha512-03ruubjWyOHlmljCVoxSuNDdmfZDzsrrz0P2LeJsOXr+ZwFQ+0yQIwNCwt/GYhV7Z31fgtXJTAEs+FYlEL851g==}'@types/[email protected]':resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==}@@ -13487,10 +13490,10 @@ snapshots:'@types/[email protected]':dependencies:- '@types/eslint': 9.6.1+ '@types/eslint': 8.56.12'@types/estree': 1.0.8- '@types/[email protected]':+ '@types/[email protected]':dependencies:'@types/estree': 1.0.8'@types/json-schema': 7.0.15diff --git a/autogpt_platform/frontend/scripts/eslint-keyboard-rules.test.ts b/autogpt_platform/frontend/scripts/eslint-keyboard-rules.test.tsnew file mode 100644index 0000000000..746684cef0--- /dev/null+++ b/autogpt_platform/frontend/scripts/eslint-keyboard-rules.test.ts@@ -0,0 +1,108 @@+import { ESLint } from "eslint";+import { beforeAll, describe, expect, it } from "vitest";+import { KEY_NAMES } from "../src/lib/keyboard";++// One instance for the whole suite: resolving the Next.js + TypeScript config+// costs ~1.7s and is paid once, while each lintText call afterwards is a few+// milliseconds. Fixtures are batched per file extension for the same reason.+const eslint = new ESLint({ cwd: process.cwd() });++const EXTENSIONS = ["ts", "tsx"] as const;++function fixturePath(extension: string) {+ return `src/keyboard-rule-fixture.${extension}`;+}++async function keyboardRuleMessages(source: string, extension: string) {+ const [result] = await eslint.lintText(source, {+ filePath: fixturePath(extension),+ });+ return result.messages.filter((m) => m.ruleId === "no-restricted-syntax");+}++// The three selectors, read back off the resolved config rather than scraped+// out of .eslintrc.json, so the assertion does not depend on that file's+// textual formatting or on the directory vitest happens to run from.+async function keyboardSelectors(extension: string) {+ const config = await eslint.calculateConfigForFile(fixturePath(extension));+ const [, ...options] = config.rules?.["no-restricted-syntax"] ?? [];+ return (options as { selector: string; message: string }[]).filter((option) =>+ option.message.includes("isKey(e,"),+ );+}++describe.each(EXTENSIONS)("keyboard selectors in a .%s file", (extension) => {+ let selectors: { selector: string; message: string }[];++ beforeAll(async () => {+ selectors = await keyboardSelectors(extension);+ });++ it("is wired into the resolved ESLint config", () => {+ expect(selectors).toHaveLength(3);+ });++ it("guards exactly the KEY_NAMES list", () => {+ const lists = selectors.map((option) => {+ const match = option.selector.match(/value=\/\^\(([^)]+)\)\$\//);+ expect(+ match,+ `no key list in selector: ${option.selector}`,+ ).not.toBeNull();+ return match![1].split("|");+ });+ expect(lists).toHaveLength(3);+ for (const list of lists) {+ expect(new Set(list)).toEqual(new Set(KEY_NAMES));+ }+ });++ it("rejects every KEY_NAME in every shape the selectors cover", async () => {+ // One statement per line so a reported line number identifies the shape+ // that tripped, and every key name is proven to fire all three selectors.+ const lines = KEY_NAMES.flatMap((key) => {+ const literal = JSON.stringify(key);+ return [+ `event.key === ${literal};`,+ `${literal} === event.key;`,+ `switch (event.key) { case ${literal}: break; }`,+ ];+ });+ const source = `declare const event: { key: string };\n${lines.join("\n")}\n`;++ const messages = await keyboardRuleMessages(source, extension);+ expect(messages).toHaveLength(lines.length);+ // Every fixture line reported exactly once, none swallowed or doubled.+ expect(messages.map((m) => m.line).sort((a, b) => a - b)).toEqual(+ lines.map((_, index) => index + 2),+ );+ });++ it.each([+ 'const ENTER_KEY = "Enter"; event.key === ENTER_KEY;',+ 'const ENTER_KEY = "Enter"; ENTER_KEY === event.key;',+ 'const ENTER_KEY = "Enter"; switch (event.key) { case ENTER_KEY: break; }',+ ])("rejects the named-constant form: %s", async (statement) => {+ const source = `declare const event: { key: string };\n${statement}\n`;+ const messages = await keyboardRuleMessages(source, extension);+ expect(messages).toHaveLength(1);+ expect(messages[0].message).toContain('use isKey(e, "Enter")');+ });++ it("leaves unrelated key handling alone", async () => {+ const source = [+ "declare const event: { key: string };",+ "declare const status: string;",+ "declare const plan: { key: string };",+ // Not a `.key` member expression.+ 'status === "Enter";',+ 'switch (status) { case "Enter": break; }',+ // A `.key` that is not a key name.+ 'plan.key === "premium";',+ // Modifier chords and set membership are out of scope by design.+ 'event.key.toLowerCase() === "k";',+ '["Enter", " "].includes(event.key);',+ ].join("\n");+ expect(await keyboardRuleMessages(source, extension)).toEqual([]);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminUserSearch.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminUserSearch.tsxindex 831404e287..4a80181ef0 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminUserSearch.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminUserSearch.tsx@@ -5,6 +5,7 @@ import { Input } from "@/components/__legacy__/ui/input";import { Button } from "@/components/atoms/Button/Button";import { Search01Icon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";+import { isKey } from "@/lib/keyboard";export interface AdminUserSearchProps {/** Current search query value (controlled). Falls back to internal state if omitted. */@@ -55,7 +56,7 @@ export function AdminUserSearch({aria-label={placeholder}value={currentValue}onChange={(e) => handleChange(e.target.value)}- onKeyDown={(e) => e.key === "Enter" && handleSearch()}+ onKeyDown={(e) => isKey(e, "Enter") && handleSearch()}disabled={isLoading}/><Buttondiff --git a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/SearchFilterForm.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/SearchFilterForm.tsxindex 6c32b3b5a0..b6e36d1a0b 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/SearchFilterForm.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/SearchFilterForm.tsx@@ -13,6 +13,7 @@ import {SelectValue,} from "@/components/__legacy__/ui/select";import { SubmissionStatus } from "@/app/api/__generated__/models/submissionStatus";+import { isKey } from "@/lib/keyboard";export function SearchAndFilterAdminMarketplace({initialSearch,@@ -64,7 +65,7 @@ export function SearchAndFilterAdminMarketplace({placeholder="Search agents by Name, Creator, or Description..."value={searchQuery}onChange={(e) => setSearchQuery(e.target.value)}- onKeyDown={(e) => e.key === "Enter" && handleSearch()}+ onKeyDown={(e) => isKey(e, "Enter") && handleSearch()}/><Button variant="outline" onClick={handleSearch}><Search className="h-4 w-4" />diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsxindex 7834a104f1..2b93ce0d9b 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsx@@ -17,6 +17,7 @@ import {import { http, HttpResponse } from "msw";import { RateLimitManager } from "../RateLimitManager";import type { UserRateLimitResponse } from "@/app/api/__generated__/models/userRateLimitResponse";+import { isKey } from "@/lib/keyboard";const toastSpy = vi.hoisted(() => vi.fn());@@ -41,7 +42,7 @@ vi.mock("../../../components/AdminUserSearch", () => ({placeholder={placeholder}disabled={isLoading}onKeyDown={(e) => {- if (e.key === "Enter") onSearch((e.target as HTMLInputElement).value);+ if (isKey(e, "Enter")) onSearch((e.target as HTMLInputElement).value);}}/></div>diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderFormDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderFormDialog.tsxindex 2edf5af94f..cfd8501939 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderFormDialog.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/FolderFormDialog.tsx@@ -4,6 +4,7 @@ import { useEffect, useState } from "react";import { Button } from "@/components/atoms/Button/Button";import { Input } from "@/components/atoms/Input/Input";import { Dialog } from "@/components/molecules/Dialog/Dialog";+import { isKey } from "@/lib/keyboard";interface Props {isOpen: boolean;@@ -54,7 +55,7 @@ export function FolderFormDialog({value={name}onChange={(e) => setName(e.target.value)}onKeyDown={(e) => {- if (e.key === "Enter") handleSubmit();+ if (isKey(e, "Enter")) handleSubmit();}}className="w-full"wrapperClassName="!mb-0"diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/WorkspaceFolder.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/WorkspaceFolder.tsxindex 1effcf5cb4..6124e1c7d0 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/WorkspaceFolder.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/WorkspaceFolders/WorkspaceFolder.tsx@@ -11,6 +11,7 @@ import {PencilIcon,} from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";+import { isKey } from "@/lib/keyboard";interface Props {id: string;@@ -64,7 +65,7 @@ export function WorkspaceFolder({data-folder-id={id}onClick={onClick}onKeyDown={(e) => {- if (e.key === "Enter" || e.key === " ") {+ if (isKey(e, "Enter", " ")) {e.preventDefault();onClick();}diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/useBuilderChatPanel.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/useBuilderChatPanel.tsindex 66d63e1d0e..10e8b7813f 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/useBuilderChatPanel.ts+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/useBuilderChatPanel.ts@@ -22,6 +22,7 @@ import { convertChatSessionMessagesToUiMessages } from "@/app/(platform)/copilotimport { useCopilotStream } from "@/app/(platform)/copilot/useCopilotStream";import { useCopilotPendingChips } from "@/app/(platform)/copilot/useCopilotPendingChips";import { useGetV2GetSession } from "@/app/api/__generated__/endpoints/chat/chat";+import { isKey } from "@/lib/keyboard";import { retryUnlessClientError } from "../../helpers/graphLoadError";interface UseBuilderChatPanelArgs {@@ -405,7 +406,7 @@ export function useBuilderChatPanel({useEffect(() => {if (!isOpen) return;function onKeyDown(e: globalThis.KeyboardEvent) {- if (e.key !== "Escape") return;+ if (!isKey(e, "Escape")) return;if (panelRef &&panelRef.current &&diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/DraftRecoveryDialog/useDraftRecoveryPopup.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/DraftRecoveryDialog/useDraftRecoveryPopup.tsxindex 7a77f7b4cc..32353d7c34 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/DraftRecoveryDialog/useDraftRecoveryPopup.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/DraftRecoveryDialog/useDraftRecoveryPopup.tsx@@ -1,5 +1,6 @@import { useEffect, useRef } from "react";import { useDraftManager } from "../FlowEditor/Flow/useDraftManager";+import { isKey } from "@/lib/keyboard";export const useDraftRecoveryPopup = (isInitialLoadComplete: boolean) => {const popupRef = useRef<HTMLDivElement>(null);@@ -40,7 +41,7 @@ export const useDraftRecoveryPopup = (isInitialLoadComplete: boolean) => {if (!isOpen) return;const handleKeyDown = (event: KeyboardEvent) => {- if (event.key === "Escape") {+ if (isKey(event, "Escape")) {onDiscard();}};diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/NodeHeader.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/NodeHeader.tsxindex f9a7b16431..347d324ed5 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/NodeHeader.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/NodeHeader.tsx@@ -13,6 +13,7 @@ import { formatNodeDisplayTitle, getNodeDisplayTitle } from "../helpers";import { NodeBadges } from "./NodeBadges";import { NodeContextMenu } from "./NodeContextMenu";import { NodeCost } from "./NodeCost";+import { isKey } from "@/lib/keyboard";type Props = {data: CustomNodeData;@@ -44,8 +45,8 @@ export const NodeHeader = ({ data, nodeId }: Props) => {};const handleTitleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {- if (e.key === "Enter") handleTitleEdit();- if (e.key === "Escape") {+ if (isKey(e, "Enter")) handleTitleEdit();+ if (isKey(e, "Escape")) {setEditedTitle(title);setIsEditingTitle(false);}diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/__tests__/NodeHeader.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/__tests__/NodeHeader.test.tsxindex dca3e87598..d9127e5684 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/__tests__/NodeHeader.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/__tests__/NodeHeader.test.tsx@@ -107,6 +107,40 @@ describe("NodeHeader", () => {});});+ it("keeps editing when an IME owns the Enter", () => {+ render(<NodeHeader data={makeData()} nodeId="node-1" />);+ fireEvent.doubleClick(screen.getByText("Agent Executor"));++ const input = screen.getByDisplayValue("AgentExecutorBlock");+ fireEvent.change(input, { target: { value: "猫ノード" } });+ fireEvent.keyDown(input, { key: "Enter", isComposing: true });+ // Safari's confirming Enter arrives after compositionend with only the+ // legacy keyCode left to identify it.+ fireEvent.keyDown(input, { key: "Enter", keyCode: 229 });++ expect(mockUpdateNodeData).not.toHaveBeenCalled();+ expect(screen.getByDisplayValue("猫ノード")).toBeTruthy();++ fireEvent.keyDown(input, { key: "Enter" });++ expect(mockUpdateNodeData).toHaveBeenCalledWith("node-1", {+ metadata: { customized_name: "猫ノード" },+ });+ });++ it("does not revert the title when an IME owns the Escape", () => {+ render(<NodeHeader data={makeData()} nodeId="node-1" />);+ fireEvent.doubleClick(screen.getByText("Agent Executor"));++ const input = screen.getByDisplayValue("AgentExecutorBlock");+ fireEvent.change(input, { target: { value: "猫ノード" } });+ fireEvent.keyDown(input, { key: "Escape", isComposing: true });++ // Escape dismissed the candidate window, not the rename.+ expect(screen.getByDisplayValue("猫ノード")).toBeTruthy();+ expect(mockUpdateNodeData).not.toHaveBeenCalled();+ });+it("cancels edit on Escape key", () => {render(<NodeHeader data={makeData()} nodeId="node-1" />);fireEvent.doubleClick(screen.getByText("Agent Executor"));diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/MCPToolDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/MCPToolDialog.tsxindex 3d0415b0d6..025eec9c5e 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/MCPToolDialog.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/MCPToolDialog.tsx@@ -48,6 +48,7 @@ import {getErrorMessage,getErrorStatus,} from "@/lib/mcp-errors";+import { isKey } from "@/lib/keyboard";import { mcpServerIdentity, normalizeMcpUrl } from "@/lib/mcp-url";import { ArrowDown01Icon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";@@ -447,7 +448,7 @@ export function MCPToolDialog({setError(null);startOAuthRef.current = false;}}- onKeyDown={(e) => e.key === "Enter" && handleDiscoverTools()}+ onKeyDown={(e) => isKey(e, "Enter") && handleDiscoverTools()}disabled={loading || oauthLoading}autoFocus/>@@ -489,7 +490,7 @@ export function MCPToolDialog({setManualToken(value);detectSchemeFrom(value);}}- onKeyDown={(e) => e.key === "Enter" && handleDiscoverTools()}+ onKeyDown={(e) => isKey(e, "Enter") && handleDiscoverTools()}disabled={loading || oauthLoading}autoFocus/>diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewSearchGraph/GraphMenuContent/useGraphContent.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewSearchGraph/GraphMenuContent/useGraphContent.tsindex a7b4bb2721..e0310ea121 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewSearchGraph/GraphMenuContent/useGraphContent.ts+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewSearchGraph/GraphMenuContent/useGraphContent.ts@@ -1,5 +1,6 @@import { useCallback, useEffect, useRef, useState } from "react";import { SearchableNode } from "../GraphMenuSearchBar/useGraphMenuSearchBar";+import { isKey } from "@/lib/keyboard";interface UseGraphContentProps {searchQuery: string;@@ -35,13 +36,13 @@ export function useGraphContent({}, []);function handleKeyDown(e: React.KeyboardEvent) {- if (e.key === "ArrowDown" && filteredNodes.length > 0) {+ if (isKey(e, "ArrowDown") && filteredNodes.length > 0) {e.preventDefault();setSelectedIndex((prev) => Math.min(prev + 1, filteredNodes.length - 1));- } else if (e.key === "ArrowUp" && filteredNodes.length > 0) {+ } else if (isKey(e, "ArrowUp") && filteredNodes.length > 0) {e.preventDefault();setSelectedIndex((prev) => Math.max(prev - 1, 0));- } else if (e.key === "Enter" && filteredNodes.length > 0) {+ } else if (isKey(e, "Enter") && filteredNodes.length > 0) {e.preventDefault();const safeIndex = Math.max(0,diff --git a/autogpt_platform/frontend/src/app/(platform)/components/TabIntroCard/TabIntroCard.tsx b/autogpt_platform/frontend/src/app/(platform)/components/TabIntroCard/TabIntroCard.tsxindex 7c26e226b8..9e3dbe0f55 100644--- a/autogpt_platform/frontend/src/app/(platform)/components/TabIntroCard/TabIntroCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/components/TabIntroCard/TabIntroCard.tsx@@ -8,6 +8,7 @@ import type { IconSvgElement } from "@hugeicons/react";import { AnimatePresence, motion } from "framer-motion";import { useEffect, useRef } from "react";import { getFocusableElements } from "./helpers";+import { isKey, isKeyIgnoringComposition } from "@/lib/keyboard";interface Action {label: string;@@ -61,11 +62,13 @@ export function TabIntroCard({dialogRef.current?.focus();function handleKeyDown(event: KeyboardEvent) {- if (event.key === "Escape") {+ if (isKey(event, "Escape")) {dismissRef.current();return;}- if (event.key !== "Tab") return;+ // Containment, not a shortcut: the trap has to keep holding Tab while an+ // IME composes, since letting it through moves focus out of the dialog.+ if (!isKeyIgnoringComposition(event, "Tab")) return;const dialog = dialogRef.current;if (!dialog) return;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/McpConnectorRow.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/McpConnectorRow.tsxindex c7e70e1687..c1cf708415 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/McpConnectorRow.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/McpConnectorRow.tsx@@ -14,6 +14,7 @@ import {prepareMCPAuthCredential,validateMCPAuthCredential,} from "@/lib/mcp-auth";+import { isKey } from "@/lib/keyboard";import { CheckmarkCircle02Icon } from "@hugeicons/core-free-icons";import { useId, useState } from "react";import type { McpConnectorRequest } from "./helpers";@@ -126,7 +127,7 @@ export function McpConnectorRow({ request }: { request: McpConnectorRequest }) {setValidationError(null);}}onKeyDown={(e) =>- e.key === "Enter" &&+ isKey(e, "Enter") &&!request.loading &&token.trim() &&submitCredential()diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionAnswerField.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionAnswerField.tsxindex 6b9e54aa67..83f9e0d333 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionAnswerField.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionAnswerField.tsx@@ -5,6 +5,7 @@ import { PencilEdit02Icon } from "@hugeicons/core-free-icons";import { useState } from "react";import type { ClarifyingQuestion } from "../../tools/clarifying-questions";import { QuestionOptionList } from "./QuestionOptionList";+import { isKey } from "@/lib/keyboard";interface Props {question: ClarifyingQuestion;@@ -48,7 +49,7 @@ export function QuestionAnswerField({onChange={(e) => onChange(e.target.value)}// Enter advances the pager; Shift+Enter is the newline.onKeyDown={(e) => {- if (e.key !== "Enter" || e.shiftKey) return;+ if (!isKey(e, "Enter") || e.shiftKey) return;e.preventDefault();onSubmit();}}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionOptionList.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionOptionList.tsxindex 20b0dc5f90..7df0f6a35b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionOptionList.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/QuestionOptionList.tsx@@ -3,6 +3,7 @@import { Icon } from "@/components/atoms/Icon/Icon";import { Tick02Icon } from "@hugeicons/core-free-icons";import { useEffect, useRef } from "react";+import { isKey } from "@/lib/keyboard";interface Props {/** Expected trimmed and deduped — `toOptions` establishes that invariant,@@ -44,18 +45,17 @@ export function QuestionOptionList({// tabbing past the pager to reach send. Selecting first means tabbing in// and hitting Enter can't submit an option nobody chose — and arrowing or// clicking already selects, so those reach the pager on the first Enter.- if (event.key === "Enter") {+ if (isKey(event, "Enter")) {event.preventDefault();if (options[index] === value.trim()) onSubmit();else onChange(options[index]);return;}- const step =- event.key === "ArrowDown" || event.key === "ArrowRight"- ? 1- : event.key === "ArrowUp" || event.key === "ArrowLeft"- ? -1- : 0;+ const step = isKey(event, "ArrowDown", "ArrowRight")+ ? 1+ : isKey(event, "ArrowUp", "ArrowLeft")+ ? -1+ : 0;if (step === 0) return;event.preventDefault();moveTo((index + step + options.length) % options.length);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/QuestionAnswerField.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/QuestionAnswerField.test.tsxnew file mode 100644index 0000000000..8bbeab3468--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/QuestionAnswerField.test.tsx@@ -0,0 +1,46 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import { QuestionAnswerField } from "../QuestionAnswerField";++function renderField(value = "ねこ") {+ const onSubmit = vi.fn();+ render(+ <QuestionAnswerField+ question={{ question: "Which animal?", keyword: "animal" }}+ value={value}+ labelId="label-1"+ autoFocus={false}+ onChange={() => {}}+ onSubmit={onSubmit}+ />,+ );+ return { textarea: screen.getByRole("textbox"), onSubmit };+}++describe("QuestionAnswerField Enter handling", () => {+ it("advances the pager on a plain Enter", () => {+ const { textarea, onSubmit } = renderField();++ fireEvent.keyDown(textarea, { key: "Enter" });++ expect(onSubmit).toHaveBeenCalledTimes(1);+ });++ it("does not advance while an IME owns the Enter", () => {+ const { textarea, onSubmit } = renderField();++ fireEvent.keyDown(textarea, { key: "Enter", isComposing: true });+ // Safari's confirming Enter arrives after compositionend.+ fireEvent.keyDown(textarea, { key: "Enter", keyCode: 229 });++ expect(onSubmit).not.toHaveBeenCalled();+ });++ it("leaves Shift+Enter as the newline", () => {+ const { textarea, onSubmit } = renderField();++ fireEvent.keyDown(textarea, { key: "Enter", shiftKey: true });++ expect(onSubmit).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useChatMentions.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useChatMentions.test.tsxindex b625bec9be..fd97c82fc9 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useChatMentions.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useChatMentions.test.tsx@@ -32,9 +32,14 @@ function fakeTextarea(value: string, caret = value.length) {return { value, selectionStart: caret } as HTMLTextAreaElement;}-function keyEvent(key: string) {+function keyEvent(key: string, composing: boolean | "keyCode229" = false) {+ const isComposing = composing === true;+ // Safari confirms a candidate with an Enter fired after compositionend, so+ // isComposing is already false and only the legacy keyCode is left.+ const keyCode = composing === "keyCode229" ? 229 : key === "Enter" ? 13 : 0;return {key,+ nativeEvent: { key, isComposing, keyCode },preventDefault: vi.fn(),} as unknown as React.KeyboardEvent<HTMLTextAreaElement>;}@@ -167,6 +172,83 @@ describe("useChatMentions", () => {expect(addWorkspaceFile).not.toHaveBeenCalled();});+ it("navigates results with arrow keys but ignores composing keydowns", async () => {+ mockListWorkspaceFiles.mockResolvedValue({+ status: 200,+ data: {+ files: [FILE, { ...FILE, id: "file-2", name: "beta.txt" }],+ has_more: false,+ },+ });++ const { result } = renderHook(+ () =>+ useChatMentions({+ enabled: true,+ value: "hi @",+ setValue: vi.fn(),+ addWorkspaceFile: vi.fn(),+ }),+ { wrapper: Wrapper },+ );++ act(() => result.current.detect(fakeTextarea("hi @")));+ await waitFor(() => expect(result.current.files).toHaveLength(2));++ act(() => {+ expect(result.current.onKeyDown(keyEvent("ArrowDown"))).toBe(true);+ });+ expect(result.current.highlightedIndex).toBe(1);++ act(() => {+ expect(result.current.onKeyDown(keyEvent("ArrowUp"))).toBe(true);+ });+ expect(result.current.highlightedIndex).toBe(0);++ act(() => {+ expect(result.current.onKeyDown(keyEvent("ArrowDown", true))).toBe(false);+ });+ expect(result.current.highlightedIndex).toBe(0);+ });++ it("does not accept a mention on a composing Enter or Tab", async () => {+ mockListWorkspaceFiles.mockResolvedValue({+ status: 200,+ data: { files: [FILE], has_more: false },+ });+ const setValue = vi.fn();+ const addWorkspaceFile = vi.fn();++ const { result } = renderHook(+ () =>+ useChatMentions({+ enabled: true,+ value: "hi @al",+ setValue,+ addWorkspaceFile,+ }),+ { wrapper: Wrapper },+ );++ act(() => result.current.detect(fakeTextarea("hi @al")));+ await waitFor(() => expect(result.current.files).toHaveLength(1));++ for (const event of [+ keyEvent("Enter", true),+ keyEvent("Enter", "keyCode229"),+ keyEvent("Tab", true),+ ]) {+ act(() => {+ expect(result.current.onKeyDown(event)).toBe(false);+ });+ expect(event.preventDefault).not.toHaveBeenCalled();+ }++ expect(setValue).not.toHaveBeenCalled();+ expect(addWorkspaceFile).not.toHaveBeenCalled();+ expect(result.current.isOpen).toBe(true);+ });+it("ignores accept when the highlighted item is out of bounds", async () => {mockListWorkspaceFiles.mockResolvedValue({status: 200,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useVoiceRecording.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useVoiceRecording.test.tsxnew file mode 100644index 0000000000..df384f8b11--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useVoiceRecording.test.tsx@@ -0,0 +1,136 @@+import { act, renderHook, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useVoiceRecording } from "../useVoiceRecording";++vi.mock("@/services/feature-flags/use-get-flag", () => ({+ Flag: { ONBOARDING_BRAIN_DUMP: "onboarding-brain-dump" },+ useGetFlag: () => false,+}));++vi.mock("@/components/molecules/Toast/use-toast", () => ({+ useToast: () => ({ toast: vi.fn() }),+}));++const getUserMedia = vi.fn();+const recorderStop = vi.fn();++function keydown(key: string, isComposing = false) {+ return {+ key,+ nativeEvent: { key, isComposing },+ preventDefault: vi.fn(),+ } as unknown as React.KeyboardEvent<HTMLTextAreaElement>;+}++function spaceKeydown(isComposing = false) {+ return keydown(" ", isComposing);+}++// Enough of the MediaRecorder surface for startRecording to reach the+// isRecordingRef.current = true branch. `stop` deliberately never fires+// `onstop`, so no transcription request is made.+class FakeMediaRecorder {+ static isTypeSupported = () => true;+ mimeType = "audio/webm";+ ondataavailable: ((event: unknown) => void) | null = null;+ onstop: (() => void) | null = null;+ start = vi.fn();+ stop = recorderStop;+}++async function renderRecording() {+ getUserMedia.mockResolvedValue({ getTracks: () => [] });+ const { result } = renderVoice();++ await act(async () => {+ result.current.handleKeyDown(spaceKeydown());+ });+ await waitFor(() => expect(result.current.isRecording).toBe(true));++ return result;+}++function renderVoice(value = "") {+ return renderHook(() => useVoiceRecording({ setValue: vi.fn(), value }));+}++beforeEach(() => {+ getUserMedia.mockRejectedValue(new Error("no microphone"));+ vi.stubGlobal("MediaRecorder", FakeMediaRecorder);+ Object.defineProperty(navigator, "mediaDevices", {+ configurable: true,+ value: { getUserMedia },+ });+});++afterEach(() => {+ vi.clearAllMocks();+ vi.unstubAllGlobals();+});++describe("useVoiceRecording Space shortcut", () => {+ it("ignores Space while an IME is composing", () => {+ const { result } = renderVoice();+ const event = spaceKeydown(true);++ act(() => result.current.handleKeyDown(event));++ expect(event.preventDefault).not.toHaveBeenCalled();+ expect(getUserMedia).not.toHaveBeenCalled();+ });++ it("starts recording on a plain Space in an empty composer", async () => {+ const { result } = renderVoice();+ const event = spaceKeydown();++ act(() => result.current.handleKeyDown(event));++ expect(event.preventDefault).toHaveBeenCalled();+ await waitFor(() => expect(getUserMedia).toHaveBeenCalledTimes(1));+ });++ it("leaves Space alone once the composer has text", () => {+ const { result } = renderVoice("draft");+ const event = spaceKeydown();++ act(() => result.current.handleKeyDown(event));++ expect(event.preventDefault).not.toHaveBeenCalled();+ expect(getUserMedia).not.toHaveBeenCalled();+ });++ it("stops an in-progress recording on a plain Space", async () => {+ const result = await renderRecording();+ const event = spaceKeydown();++ act(() => result.current.handleKeyDown(event));++ expect(event.preventDefault).toHaveBeenCalled();+ expect(recorderStop).toHaveBeenCalledTimes(1);+ expect(result.current.isRecording).toBe(false);+ });++ it("does not stop a recording on a composing Space", async () => {+ const result = await renderRecording();+ const event = spaceKeydown(true);++ act(() => result.current.handleKeyDown(event));++ // Still swallowed by the while-recording block below, but the recording+ // itself survives — the Space belonged to the IME, not to the shortcut.+ expect(event.preventDefault).toHaveBeenCalled();+ expect(recorderStop).not.toHaveBeenCalled();+ expect(result.current.isRecording).toBe(true);+ });++ it("swallows every other key while recording", async () => {+ const result = await renderRecording();+ const event = keydown("Enter");++ act(() => result.current.handleKeyDown(event));++ expect(event.preventDefault).toHaveBeenCalled();+ expect(recorderStop).not.toHaveBeenCalled();+ expect(result.current.isRecording).toBe(true);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/ConnectionPicker.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/ConnectionPicker.tsxindex e022cb1c7d..5a2333f63a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/ConnectionPicker.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/ConnectionPicker.tsx@@ -39,6 +39,7 @@ import {tierLock,tierSummary,} from "./helpers";+import { isComposingEvent } from "@/lib/keyboard";import { nextRovingValue, rovingTabIndex } from "./radioKeys";import { TierToggle } from "./TierToggle";import { useConnectionPicker } from "./useConnectionPicker";@@ -239,6 +240,9 @@ export function ConnectionPicker({// the tiers below.className="overflow-hidden rounded-xl"onKeyDown={(event) => {+ // `event.key` goes straight into the roving helper, so guard+ // here instead.+ if (isComposingEvent(event)) return;const to = nextRovingValue(connectionOptions,active?.offer_id ?? "",diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/TierToggle.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/TierToggle.tsxindex 4f480aef6f..cf2bba27bd 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/TierToggle.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/TierToggle.tsx@@ -13,6 +13,7 @@ import { Icon } from "@/components/atoms/Icon/Icon";import { cn } from "@/lib/utils";import type { CopilotLlmModel } from "../../../../store";+import { isComposingEvent } from "@/lib/keyboard";import { nextRovingValue, rovingTabIndex } from "./radioKeys";import { Swap } from "./Swap";@@ -59,6 +60,8 @@ export function TierToggle({function handleKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {if (event.target instanceof Element && event.target.closest("a")) return;+ // `event.key` goes straight into the roving helper, so guard here instead.+ if (isComposingEvent(event)) return;const to = nextRovingValue(options, value, event.key);if (to === null) return;event.preventDefault();diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ConnectionPicker.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ConnectionPicker.test.tsxindex f957e1813c..e00a90214f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ConnectionPicker.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ConnectionPicker.test.tsx@@ -6,6 +6,7 @@ import type { AIConnectionOffer } from "@/app/api/__generated__/models/aIConnectimport type { ConnectionTier } from "@/app/api/__generated__/models/connectionTier";import { server } from "@/mocks/mock-server";import {+ fireEvent,render,screen,waitFor,@@ -240,6 +241,30 @@ describe("ConnectionPicker", () => {});});+ it("ignores arrow keys an IME is composing", async () => {+ // Both radiogroups pass `event.key` straight into nextRovingValue, so the+ // composition guard sits on the handler rather than on a key comparison.+ mockOffers([offer(), chatgpt()]);+ render(<ConnectionPicker />);++ await userEvent.click(await openPicker());+ const connections = await screen.findByRole("radiogroup", {+ name: "Connection this chat runs on",+ });+ within(connections)+ .getByRole("radio", { name: /AutoGPT Platform/ })+ .focus();++ fireEvent.keyDown(connections, { key: "ArrowDown", isComposing: true });++ expect(useCopilotUIStore.getState().copilotLlmAuth).toBeNull();++ const tiers = await screen.findByRole("radiogroup", { name: "Model tier" });+ fireEvent.keyDown(tiers, { key: "ArrowRight", isComposing: true });++ expect(useCopilotUIStore.getState().copilotLlmModel).not.toBe("advanced");+ });+it("is one tab stop, and the arrow keys move and select within it", async () => {// A radio group is not a list of buttons that say role="radio". Tab moves// past the whole group; the arrows move within it and select as they go.diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatMentions.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatMentions.tsindex e60093e546..d0e001ab4f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatMentions.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatMentions.ts@@ -5,6 +5,7 @@ import { useKeyboardNav } from "@/components/organisms/SearchCommandModal/useKeyimport { keepPreviousData, useQuery } from "@tanstack/react-query";import type { KeyboardEvent } from "react";import { useState } from "react";+import { isKey } from "@/lib/keyboard";const MENTION_RE = /(?:^|\s)@([^\s@]*)$/;const QUERY_DEBOUNCE_MS = 200;@@ -92,29 +93,28 @@ export function useChatMentions({function onKeyDown(e: KeyboardEvent<HTMLTextAreaElement>): boolean {if (!isOpen) return false;- if (e.key === "Escape") {+ if (isKey(e, "Escape")) {e.preventDefault();close();return true;}if (files.length === 0) return false;- switch (e.key) {- case "ArrowDown":- e.preventDefault();- moveHighlight(1);- return true;- case "ArrowUp":- e.preventDefault();- moveHighlight(-1);- return true;- case "Enter":- case "Tab":- e.preventDefault();- accept(files[highlightedIndex]);- return true;- default:- return false;+ if (isKey(e, "ArrowDown")) {+ e.preventDefault();+ moveHighlight(1);+ return true;+ }+ if (isKey(e, "ArrowUp")) {+ e.preventDefault();+ moveHighlight(-1);+ return true;+ }+ if (isKey(e, "Enter", "Tab")) {+ e.preventDefault();+ accept(files[highlightedIndex]);+ return true;}+ return false;}return {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useVoiceRecording.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useVoiceRecording.tsindex b520bbec07..b6a292c7da 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useVoiceRecording.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useVoiceRecording.ts@@ -7,6 +7,7 @@ import React, {useRef,useState,} from "react";+import { isKey } from "@/lib/keyboard";const MAX_RECORDING_DURATION = 2 * 60 * 1000; // 2 minutes in ms@@ -232,7 +233,7 @@ export function useVoiceRecording({const handleKeyDown = useCallback((event: KeyboardEvent<HTMLTextAreaElement>) => {// Allow space to toggle recording (start when empty, stop when recording)- if (event.key === " " && !isTranscribing) {+ if (isKey(event, " ") && !isTranscribing) {if (isRecordingRef.current) {// Stop recording on spaceevent.preventDefault();diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/ChatMinimap.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/ChatMinimap.tsxindex c687d24b43..78831ab92b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/ChatMinimap.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/ChatMinimap.tsx@@ -5,6 +5,7 @@ import type { UIDataTypes, UIMessage, UITools } from "ai";import { motion, useReducedMotion } from "framer-motion";import { useMemo, useState } from "react";import { tickColor, tickScale, toMinimapEntries } from "./helpers";+import { isKey } from "@/lib/keyboard";const TICK_SPRING = { type: "spring", stiffness: 200, damping: 15 } as const;const CARD_TRANSITION = { duration: 0.15, delay: 0.0875 } as const;@@ -43,11 +44,11 @@ export function ChatMinimap({ messages }: Props) {onBlur={() => setHovered(null)}onClick={() => scrollToMessage(entry.id)}onKeyDown={(e) => {- if (e.key === "Enter" || e.key === " ") {+ if (isKey(e, "Enter", " ")) {e.preventDefault();scrollToMessage(entry.id);}- if (e.key === "Escape") {+ if (isKey(e, "Escape")) {setHovered(null);}}}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsxindex aaab4a8b34..92bf9a197d 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsx@@ -430,3 +430,46 @@ describe("ChatSidebar — pagination", () => {});}, 10_000);});++describe("ChatSidebar — rename", () => {+ afterEach(() => {+ server.resetHandlers();+ });++ async function startRenaming(title: string) {+ const sessionRow = (await screen.findByText(title)).closest("div.group");+ if (!sessionRow) throw new Error(`row not found for ${title}`);+ const moreButton = within(sessionRow as HTMLElement).getByRole("button", {+ name: /more actions/i,+ });+ fireEvent.pointerDown(moreButton, { button: 0 });+ fireEvent.click(await screen.findByRole("menuitem", { name: /rename/i }));+ return screen.findByLabelText("Rename chat");+ }++ it("keeps editing on Enter while an IME is composing, then commits on a real Enter", async () => {+ const titleBodies: { title: string }[] = [];+ server.use(+ getGetV2ListSessionsMockHandler200({ sessions, total: sessions.length }),+ http.patch("*/api/chat/sessions/:id/title", async ({ request }) => {+ titleBodies.push((await request.json()) as { title: string });+ return HttpResponse.json({ status: "ok" });+ }),+ );+ renderSidebar();++ const input = await startRenaming("Active chat");+ fireEvent.change(input, { target: { value: "新しいチャット" } });++ fireEvent.keyDown(input, { key: "Enter", isComposing: true });+ // The IME owns this Enter: the field stays in edit mode and, more to the+ // point, no rename request goes out.+ expect(screen.queryByLabelText("Rename chat")).not.toBeNull();+ expect(titleBodies).toEqual([]);++ fireEvent.keyDown(input, { key: "Enter" });+ await vi.waitFor(() => {+ expect(titleBodies).toEqual([{ title: "新しいチャット" }]);+ });+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/components/ChatSessionRow/ChatSessionRow.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/components/ChatSessionRow/ChatSessionRow.tsxindex 3bd1118438..d83097eb98 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/components/ChatSessionRow/ChatSessionRow.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/components/ChatSessionRow/ChatSessionRow.tsx@@ -22,6 +22,7 @@ import {Share03Icon,} from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";+import { isKey } from "@/lib/keyboard";interface Props {session: SessionSummaryResponse;@@ -92,9 +93,9 @@ export function ChatSessionRow({value={editingTitle}onChange={(e) => onEditingTitleChange(e.target.value)}onKeyDown={(e) => {- if (e.key === "Enter") {+ if (isKey(e, "Enter")) {e.currentTarget.blur();- } else if (e.key === "Escape") {+ } else if (isKey(e, "Escape")) {onRenameCancel();}}}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/components/EditNameDialog/EditNameDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/components/EditNameDialog/EditNameDialog.tsxindex 5c2ecafae9..f04e037505 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/components/EditNameDialog/EditNameDialog.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/components/EditNameDialog/EditNameDialog.tsx@@ -8,6 +8,7 @@ import { useAuth } from "@/lib/auth/hooks/useAuth";import { useState } from "react";import { PencilIcon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";+import { isKey } from "@/lib/keyboard";interface Props {currentName: string;@@ -88,7 +89,7 @@ export function EditNameDialog({ currentName }: Props) {value={name}onChange={(e) => setName(e.target.value)}onKeyDown={(e) => {- if (e.key === "Enter") {+ if (isKey(e, "Enter")) {e.preventDefault();handleSave();}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/ConnectToolsPanel.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/ConnectToolsPanel.tsxindex d759414792..9aabdf0c62 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/ConnectToolsPanel.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/ConnectToolsPanel.tsx@@ -11,6 +11,7 @@ import { Plug01Icon, Search01Icon } from "@hugeicons/core-free-icons";import { AnimatePresence, motion, useReducedMotion } from "framer-motion";import { useEffect } from "react";import { useConnectToolsPanel } from "./useConnectToolsPanel";+import { isKey } from "@/lib/keyboard";interface Props {onBack: () => void;@@ -66,7 +67,7 @@ export function ConnectToolsPanel({ onBack, onNext }: Props) {// reaching the dialog's skip handler, which would end onboarding.useEffect(() => {function handleKeyDown(event: KeyboardEvent) {- if (event.key !== "Escape") return;+ if (!isKey(event, "Escape")) return;if (selectedProvider) {handleBackToList();return;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/OnboardingWelcomeDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/OnboardingWelcomeDialog.tsxindex a88e728565..d6be27eae5 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/OnboardingWelcomeDialog.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/OnboardingWelcomeDialog.tsx@@ -19,6 +19,7 @@ import { useEffect, useRef, useState } from "react";import { useMeasuredHeight } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/useMeasuredHeight";import { ConnectToolsPanel } from "./ConnectToolsPanel";import { GlassPixelBackdrop } from "@/components/atoms/GlassPixelBackdrop/GlassPixelBackdrop";+import { isKey } from "@/lib/keyboard";interface Props {isOpen: boolean;@@ -105,7 +106,7 @@ export function OnboardingWelcomeDialog({ isOpen, onClose }: Props) {if (!isOpen) return;dialogRef.current?.focus();function handleKeyDown(event: KeyboardEvent) {- if (event.key === "Escape" && !isConnectOpen) finish("skipped");+ if (isKey(event, "Escape") && !isConnectOpen) finish("skipped");}window.addEventListener("keydown", handleKeyDown);return () => window.removeEventListener("keydown", handleKeyDown);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/QuestionDock.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/QuestionDock.tsxindex 7992e8c7f9..ee85db5e3b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/QuestionDock.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/QuestionDock.tsx@@ -9,6 +9,7 @@ import {getPendingQuestions,type PendingQuestions,} from "./helpers";+import { isKey } from "@/lib/keyboard";interface FormProps {dockId: string;@@ -107,7 +108,7 @@ export function QuestionsForm({ dockId, questions }: FormProps) {}))}onKeyDown={(e) => {- if (e.key === "Enter") handleSubmit();+ if (isKey(e, "Enter")) handleSubmit();}}placeholder={q.example ? `e.g. ${q.example}` : "Type your answer"}className="rounded-xl bg-zinc-50 px-2.5 py-1.5 text-[13px] text-zinc-800 ring-1 ring-zinc-200/70 transition-shadow placeholder:text-zinc-400 focus:outline-none focus:ring-zinc-400"diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsxindex f24da2f17d..5d3cc6b9fc 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsx@@ -22,6 +22,7 @@ import {validateMCPAuthCredential,type MCPAuthScheme,} from "@/lib/mcp-auth";+import { isKey } from "@/lib/keyboard";import { normalizeMcpUrl } from "@/lib/mcp-url";import { openOAuthPopup } from "@/lib/oauth-popup";import { CredentialsProvidersContext } from "@/providers/agent-credentials/credentials-provider";@@ -461,7 +462,7 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {detectSchemeFrom(nextToken);}}onKeyDown={(e) =>- e.key === "Enter" && !loading && handleManualToken()+ isKey(e, "Enter") && !loading && handleManualToken()}className="flex-1 rounded border px-2 py-1 text-sm"/>diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/StoreCard/StoreCard.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/StoreCard/StoreCard.tsxindex c9db20e5dc..85cadb1298 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/StoreCard/StoreCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/StoreCard/StoreCard.tsx@@ -9,6 +9,7 @@ import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";import Image from "next/image";import { useState } from "react";import { AddToLibraryButton } from "../AddToLibraryButton/AddToLibraryButton";+import { isKey } from "@/lib/keyboard";interface Props {agentName: string;@@ -55,7 +56,8 @@ export function StoreCard({tabIndex={0}aria-label={`${agentName} workflow card`}onKeyDown={(e) => {- if (e.key === "Enter" || e.key === " ") {+ if (isKey(e, "Enter", " ")) {+ e.preventDefault();handleClick();}}}diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/StoreCard/__tests__/StoreCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/StoreCard/__tests__/StoreCard.test.tsxnew file mode 100644index 0000000000..cb7b96a1d6--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/StoreCard/__tests__/StoreCard.test.tsx@@ -0,0 +1,40 @@+import { createEvent, fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import { StoreCard } from "../StoreCard";++function renderStoreCard(onClick = vi.fn()) {+ render(+ <StoreCard+ agentName="Research workflow"+ agentImage=""+ description="Researches a topic"+ runs={10}+ rating={4.5}+ onClick={onClick}+ avatarSrc=""+ />,+ );++ return { card: screen.getByRole("button"), onClick };+}++describe("StoreCard keyboard handling", () => {+ it("does not activate while an IME is composing", () => {+ const { card, onClick } = renderStoreCard();++ fireEvent.keyDown(card, { key: "Enter", isComposing: true });+ fireEvent.keyDown(card, { key: " ", isComposing: true });++ expect(onClick).not.toHaveBeenCalled();+ });++ it.each(["Enter", " "])("activates on %s without scrolling", (key) => {+ const { card, onClick } = renderStoreCard();+ const event = createEvent.keyDown(card, { key });++ fireEvent(card, event);++ expect(onClick).toHaveBeenCalledTimes(1);+ expect(event.defaultPrevented).toBe(true);+ });+});diff --git a/autogpt_platform/frontend/src/app/(public)/tour/chat/components/TourPromptBar/TourPromptBar.tsx b/autogpt_platform/frontend/src/app/(public)/tour/chat/components/TourPromptBar/TourPromptBar.tsxindex 82b80a770a..08a883e8b5 100644--- a/autogpt_platform/frontend/src/app/(public)/tour/chat/components/TourPromptBar/TourPromptBar.tsx+++ b/autogpt_platform/frontend/src/app/(public)/tour/chat/components/TourPromptBar/TourPromptBar.tsx@@ -6,6 +6,7 @@ import { useRef } from "react";import { useTextReveal } from "../../useTextReveal";import { ArrowUp02Icon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";+import { isKey } from "@/lib/keyboard";interface Props {prompt: string | null;@@ -33,7 +34,7 @@ export function TourPromptBar({ prompt, isStreaming, onSend }: Props) {}function handleKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {- if (event.key === "Enter" || event.key === " ") {+ if (isKey(event, "Enter", " ")) {event.preventDefault();send();}diff --git a/autogpt_platform/frontend/src/components/__legacy__/StoreCard.tsx b/autogpt_platform/frontend/src/components/__legacy__/StoreCard.tsxdeleted file mode 100644index 8778d62105..0000000000--- a/autogpt_platform/frontend/src/components/__legacy__/StoreCard.tsx+++ /dev/null@@ -1,121 +0,0 @@-import * as React from "react";-import Image from "next/image";-import { StarRatingIcons } from "@/components/__legacy__/ui/icons";-import Avatar, { AvatarFallback, AvatarImage } from "../atoms/Avatar/Avatar";--interface StoreCardProps {- agentName: string;- agentImage: string;- description: string;- runs: number;- rating: number;- onClick: () => void;- avatarSrc: string;- hideAvatar?: boolean;- creatorName?: string;-}--export const StoreCard: React.FC<StoreCardProps> = ({- agentName,- agentImage,- description,- runs,- rating,- onClick,- avatarSrc,- hideAvatar = false,- creatorName,-}) => {- const handleClick = () => {- onClick();- };-- return (- <div- className="flex h-[27rem] w-full max-w-md cursor-pointer flex-col items-start rounded-3xl bg-background transition-all duration-300 hover:shadow-lg dark:hover:shadow-gray-700"- onClick={handleClick}- data-testid="store-card"- role="button"- tabIndex={0}- aria-label={`${agentName} agent card`}- onKeyDown={(e) => {- if (e.key === "Enter" || e.key === " ") {- handleClick();- }- }}- >- {/* First Section: Image with Avatar */}- <div className="relative aspect-[2/1.2] w-full overflow-hidden rounded-3xl md:aspect-[2.17/1]">- {agentImage && (- <Image- src={agentImage}- alt={`${agentName} preview image`}- fill- className="object-cover"- priority- />- )}- {!hideAvatar && (- <div className="absolute bottom-4 left-4">- <Avatar className="h-16 w-16">- {avatarSrc && (- <AvatarImage- src={avatarSrc}- alt={`${creatorName || agentName} creator avatar`}- />- )}- <AvatarFallback size={64}>- {(creatorName || agentName).charAt(0)}- </AvatarFallback>- </Avatar>- </div>- )}- </div>-- <div className="mt-3 flex w-full flex-1 flex-col px-4">- {/* Second Section: Agent Name and Creator Name */}- <div className="flex w-full flex-col">- <h3 className="line-clamp-2 font-poppins text-2xl font-semibold text-[#272727] dark:text-neutral-100">- {agentName}- </h3>- {!hideAvatar && creatorName && (- <p className="mt-3 truncate font-sans text-xl font-normal text-neutral-600 dark:text-neutral-400">- by {creatorName}- </p>- )}- </div>-- {/* Third Section: Description */}- <div className="mt-2.5 flex w-full flex-col">- <p className="line-clamp-3 text-base font-normal leading-normal text-neutral-600 dark:text-neutral-400">- {description}- </p>- </div>-- <div className="flex-grow" />- {/* Spacer to push stats to bottom */}-- {/* Fourth Section: Stats Row - aligned to bottom */}- <div className="mt-5 w-full">- <div className="flex items-center justify-between">- <div className="text-lg font-semibold text-neutral-800 dark:text-neutral-200">- {runs.toLocaleString()} runs- </div>- <div className="flex items-center gap-2">- <span className="text-lg font-semibold text-neutral-800 dark:text-neutral-200">- {rating.toFixed(1)}- </span>- <div- className="inline-flex items-center"- role="img"- aria-label={`Rating: ${rating.toFixed(1)} out of 5 stars`}- >- {StarRatingIcons(rating)}- </div>- </div>- </div>- </div>- </div>- </div>- );-};diff --git a/autogpt_platform/frontend/src/components/__legacy__/composite/AgentsSection.tsx b/autogpt_platform/frontend/src/components/__legacy__/composite/AgentsSection.tsxdeleted file mode 100644index 299da3eb17..0000000000--- a/autogpt_platform/frontend/src/components/__legacy__/composite/AgentsSection.tsx+++ /dev/null@@ -1,110 +0,0 @@-"use client";--import * as React from "react";-import { StoreCard } from "@/components/__legacy__/StoreCard";-import {- Carousel,- CarouselContent,- CarouselItem,-} from "@/components/__legacy__/ui/carousel";-import { useRouter } from "next/navigation";--export interface Agent {- slug: string;- agent_name: string;- agent_image: string;- creator: string;- creator_avatar: string;- sub_heading: string;- description: string;- runs: number;- rating: number;-}--interface AgentsSectionProps {- sectionTitle: string;- agents: Agent[];- hideAvatars?: boolean;- margin?: string;-}--export const AgentsSection: React.FC<AgentsSectionProps> = ({- sectionTitle,- agents: allAgents,- hideAvatars = false,- margin = "24px",-}) => {- const router = useRouter();-- // TODO: Update this when we have pagination- const displayedAgents = allAgents;-- const handleCardClick = (creator: string, slug: string) => {- router.push(- `/marketplace/agent/${encodeURIComponent(creator)}/${encodeURIComponent(slug)}`,- );- };-- return (- <div className="flex flex-col items-center justify-center">- <div className="w-full max-w-[1360px]">- <h2- style={{ marginBottom: margin }}- className="font-poppins text-lg font-semibold text-[#282828] dark:text-neutral-200"- >- {sectionTitle}- </h2>- {!displayedAgents || displayedAgents.length === 0 ? (- <div className="text-center text-gray-500 dark:text-gray-400">- No agents found- </div>- ) : (- <>- {/* Mobile Carousel View */}- <Carousel- className="md:hidden"- opts={{- loop: true,- }}- >- <CarouselContent>- {displayedAgents.map((agent, index) => (- <CarouselItem key={index} className="min-w-64 max-w-71">- <StoreCard- agentName={agent.agent_name}- agentImage={agent.agent_image}- description={agent.description}- runs={agent.runs}- rating={agent.rating}- avatarSrc={agent.creator_avatar}- creatorName={agent.creator}- hideAvatar={hideAvatars}- onClick={() => handleCardClick(agent.creator, agent.slug)}- />- </CarouselItem>- ))}- </CarouselContent>- </Carousel>-- <div className="hidden grid-cols-1 place-items-center gap-6 md:grid md:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4">- {displayedAgents.map((agent, index) => (- <StoreCard- key={index}- agentName={agent.agent_name}- agentImage={agent.agent_image}- description={agent.description}- runs={agent.runs}- rating={agent.rating}- avatarSrc={agent.creator_avatar}- creatorName={agent.creator}- hideAvatar={hideAvatars}- onClick={() => handleCardClick(agent.creator, agent.slug)}- />- ))}- </div>- </>- )}- </div>- </div>- );-};diff --git a/autogpt_platform/frontend/src/components/__legacy__/ui/carousel.tsx b/autogpt_platform/frontend/src/components/__legacy__/ui/carousel.tsxindex 923f072d75..4600e1cc11 100644--- a/autogpt_platform/frontend/src/components/__legacy__/ui/carousel.tsx+++ b/autogpt_platform/frontend/src/components/__legacy__/ui/carousel.tsx@@ -9,6 +9,7 @@ import * as React from "react";import { Button } from "@/components/__legacy__/ui/button";import { cn } from "@/lib/utils";+import { isKey } from "@/lib/keyboard";type CarouselApi = UseEmblaCarouselType[1];type UseCarouselParameters = Parameters<typeof useEmblaCarousel>;@@ -88,10 +89,10 @@ const Carousel = React.forwardRef<const handleKeyDown = React.useCallback((event: React.KeyboardEvent<HTMLDivElement>) => {- if (event.key === "ArrowLeft") {+ if (isKey(event, "ArrowLeft")) {event.preventDefault();scrollPrev();- } else if (event.key === "ArrowRight") {+ } else if (isKey(event, "ArrowRight")) {event.preventDefault();scrollNext();}diff --git a/autogpt_platform/frontend/src/components/__legacy__/ui/multiselect.test.tsx b/autogpt_platform/frontend/src/components/__legacy__/ui/multiselect.test.tsxnew file mode 100644index 0000000000..6b56ff2393--- /dev/null+++ b/autogpt_platform/frontend/src/components/__legacy__/ui/multiselect.test.tsx@@ -0,0 +1,156 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import {+ MultiSelector,+ MultiSelectorContent,+ MultiSelectorInput,+ MultiSelectorTrigger,+} from "./multiselect";++function renderMultiSelector({+ dir,+ loop,+ onValuesChange = vi.fn(),+}: {+ dir?: "ltr" | "rtl";+ loop?: boolean;+ onValuesChange?: (value: string[]) => void;+} = {}) {+ render(+ <MultiSelector+ values={["One", "Two"]}+ onValuesChange={onValuesChange}+ dir={dir}+ loop={loop}+ >+ <MultiSelectorTrigger>+ <MultiSelectorInput aria-label="Options" />+ </MultiSelectorTrigger>+ <MultiSelectorContent>+ <div>Choices</div>+ </MultiSelectorContent>+ </MultiSelector>,+ );++ return { input: screen.getByLabelText("Options"), onValuesChange };+}++function isActive(name: string) {+ return screen.getByText(name).parentElement?.classList.contains("ring-2");+}++describe("MultiSelector keyboard handling", () => {+ it.each(["Backspace", "Delete"])(+ "does not remove a value with %s while an IME is composing",+ (key) => {+ const { input, onValuesChange } = renderMultiSelector();++ fireEvent.keyDown(input, { key, isComposing: true });++ expect(onValuesChange).not.toHaveBeenCalled();+ },+ );++ it.each(["Backspace", "Delete"])(+ "removes the final value with a plain %s keydown",+ (key) => {+ const { input, onValuesChange } = renderMultiSelector();++ fireEvent.keyDown(input, { key });++ expect(onValuesChange).toHaveBeenCalledWith(["One"]);+ },+ );++ it("keeps values while deleting text from the filter", () => {+ const { input, onValuesChange } = renderMultiSelector();++ fireEvent.change(input, { target: { value: "filter" } });+ fireEvent.keyDown(input, { key: "Backspace" });++ expect(onValuesChange).not.toHaveBeenCalled();+ });++ it("opens with Enter and closes with Escape", () => {+ const { input } = renderMultiSelector();++ fireEvent.keyDown(input, { key: "Enter" });+ expect(screen.getByText("Choices")).toBeDefined();++ fireEvent.keyDown(input, { key: "Escape" });+ expect(screen.queryByText("Choices")).toBeNull();+ });++ it("ignores Enter and Escape while an IME is composing", () => {+ const { input } = renderMultiSelector();++ fireEvent.keyDown(input, { key: "Enter", isComposing: true });+ expect(screen.queryByText("Choices")).toBeNull();++ fireEvent.focus(input);+ expect(screen.getByText("Choices")).toBeDefined();++ fireEvent.keyDown(input, { key: "Escape", isComposing: true });+ expect(screen.getByText("Choices")).toBeDefined();+ });++ it.each([+ { dir: "ltr" as const, key: "ArrowLeft" },+ { dir: "rtl" as const, key: "ArrowRight" },+ ])("selects the final value with $dir $key", ({ dir, key }) => {+ const { input } = renderMultiSelector({ dir });++ fireEvent.keyDown(input, { key });++ expect(isActive("Two")).toBe(true);+ expect(isActive("One")).toBe(false);+ });++ it.each([+ { dir: "ltr" as const, back: "ArrowLeft", forward: "ArrowRight" },+ { dir: "rtl" as const, back: "ArrowRight", forward: "ArrowLeft" },+ ])(+ "wraps from the final value to the first with $dir $forward when looping",+ ({ dir, back, forward }) => {+ const { input } = renderMultiSelector({ dir, loop: true });++ fireEvent.keyDown(input, { key: back });+ expect(isActive("Two")).toBe(true);++ fireEvent.keyDown(input, { key: forward });+ expect(isActive("One")).toBe(true);+ expect(isActive("Two")).toBe(false);+ },+ );++ it("clears the selection past the final value without looping", () => {+ const { input } = renderMultiSelector();++ fireEvent.keyDown(input, { key: "ArrowLeft" });+ fireEvent.keyDown(input, { key: "ArrowRight" });++ expect(isActive("One")).toBe(false);+ expect(isActive("Two")).toBe(false);+ });++ it("moves forward from an active value in RTL mode", () => {+ const { input } = renderMultiSelector({ dir: "rtl" });++ fireEvent.keyDown(input, { key: "ArrowRight" });+ fireEvent.keyDown(input, { key: "ArrowRight" });+ expect(isActive("One")).toBe(true);++ fireEvent.keyDown(input, { key: "ArrowLeft" });+ expect(isActive("Two")).toBe(true);+ expect(isActive("One")).toBe(false);+ });++ it("does not move forward from no active value without looping", () => {+ const { input } = renderMultiSelector({ dir: "rtl" });++ fireEvent.keyDown(input, { key: "ArrowLeft" });++ expect(isActive("One")).toBe(false);+ expect(isActive("Two")).toBe(false);+ });+});diff --git a/autogpt_platform/frontend/src/components/__legacy__/ui/multiselect.tsx b/autogpt_platform/frontend/src/components/__legacy__/ui/multiselect.tsxindex ae53e92963..19435363d3 100644--- a/autogpt_platform/frontend/src/components/__legacy__/ui/multiselect.tsx+++ b/autogpt_platform/frontend/src/components/__legacy__/ui/multiselect.tsx@@ -18,6 +18,7 @@ import React, {useContext,useState,} from "react";+import { isKey } from "@/lib/keyboard";type MultiSelectorProps = {values: string[];@@ -88,7 +89,7 @@ const MultiSelector = forwardRef<HTMLDivElement, MultiSelectorProps>(setActiveIndex(prevIndex < 0 ? value.length - 1 : prevIndex);};- if ((e.key === "Backspace" || e.key === "Delete") && value.length > 0) {+ if (isKey(e, "Backspace", "Delete") && value.length > 0) {if (inputValue.length === 0) {if (activeIndex !== -1 && activeIndex < value.length) {onValueChange(@@ -102,24 +103,24 @@ const MultiSelector = forwardRef<HTMLDivElement, MultiSelectorProps>();}}- } else if (e.key === "Enter") {+ } else if (isKey(e, "Enter")) {setOpen(true);- } else if (e.key === "Escape") {+ } else if (isKey(e, "Escape")) {if (activeIndex !== -1) {setActiveIndex(-1);} else {setOpen(false);}} else if (dir === "rtl") {- if (e.key === "ArrowRight") {+ if (isKey(e, "ArrowRight")) {movePrev();- } else if (e.key === "ArrowLeft" && (activeIndex !== -1 || loop)) {+ } else if (isKey(e, "ArrowLeft") && (activeIndex !== -1 || loop)) {moveNext();}} else {- if (e.key === "ArrowLeft") {+ if (isKey(e, "ArrowLeft")) {movePrev();- } else if (e.key === "ArrowRight" && (activeIndex !== -1 || loop)) {+ } else if (isKey(e, "ArrowRight") && (activeIndex !== -1 || loop)) {moveNext();}}diff --git a/autogpt_platform/frontend/src/components/ai-elements/__tests__/prompt-input.test.tsx b/autogpt_platform/frontend/src/components/ai-elements/__tests__/prompt-input.test.tsxnew file mode 100644index 0000000000..735cf4054d--- /dev/null+++ b/autogpt_platform/frontend/src/components/ai-elements/__tests__/prompt-input.test.tsx@@ -0,0 +1,85 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import { PromptInput, PromptInputTextarea } from "../prompt-input";++function renderComposer() {+ const onSubmit = vi.fn();+ render(+ <PromptInput onSubmit={onSubmit}>+ <PromptInputTextarea+ aria-label="Message"+ value="こんにちは"+ onChange={() => {}}+ />+ </PromptInput>,+ );+ return { textarea: screen.getByLabelText("Message"), onSubmit };+}++describe("PromptInputTextarea Enter handling", () => {+ it("submits the message on a plain Enter", () => {+ const { textarea, onSubmit } = renderComposer();++ fireEvent.keyDown(textarea, { key: "Enter" });++ expect(onSubmit).toHaveBeenCalledTimes(1);+ expect(onSubmit.mock.calls[0][0]).toBe("こんにちは");+ });++ it("does not submit while an IME is composing", () => {+ const { textarea, onSubmit } = renderComposer();++ fireEvent.keyDown(textarea, { key: "Enter", isComposing: true });+ fireEvent.keyDown(textarea, { key: "Enter", keyCode: 229 });++ expect(onSubmit).not.toHaveBeenCalled();+ });++ // This component used to track composition itself with+ // onCompositionStart/onCompositionEnd state. That layer is gone, so walk the+ // full browser sequence and prove the keydown flags alone are sufficient.+ it("submits only after the composition has ended", () => {+ const { textarea, onSubmit } = renderComposer();++ fireEvent.compositionStart(textarea, { data: "ねこ" });+ // Chrome and Firefox flag the confirming Enter itself.+ fireEvent.keyDown(textarea, { key: "Enter", isComposing: true });+ expect(onSubmit).not.toHaveBeenCalled();++ fireEvent.compositionEnd(textarea, { data: "猫" });+ // Safari fires its confirming Enter after compositionend, with+ // isComposing already false and only keyCode 229 left to go on.+ fireEvent.keyDown(textarea, { key: "Enter", keyCode: 229 });+ expect(onSubmit).not.toHaveBeenCalled();++ // The next Enter is the user asking to send.+ fireEvent.keyDown(textarea, { key: "Enter", keyCode: 13 });+ expect(onSubmit).toHaveBeenCalledTimes(1);+ });++ it("does not submit on Shift+Enter", () => {+ const { textarea, onSubmit } = renderComposer();++ fireEvent.keyDown(textarea, { key: "Enter", shiftKey: true });++ expect(onSubmit).not.toHaveBeenCalled();+ });++ it("lets a consumer onKeyDown claim the key first", () => {+ const onSubmit = vi.fn();+ render(+ <PromptInput onSubmit={onSubmit}>+ <PromptInputTextarea+ aria-label="Message"+ value="hi"+ onChange={() => {}}+ onKeyDown={(e) => e.preventDefault()}+ />+ </PromptInput>,+ );++ fireEvent.keyDown(screen.getByLabelText("Message"), { key: "Enter" });++ expect(onSubmit).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/components/ai-elements/prompt-input.tsx b/autogpt_platform/frontend/src/components/ai-elements/prompt-input.tsxindex 9c1c35a6da..ebab05b6f0 100644--- a/autogpt_platform/frontend/src/components/ai-elements/prompt-input.tsx+++ b/autogpt_platform/frontend/src/components/ai-elements/prompt-input.tsx@@ -32,15 +32,10 @@ import {TooltipTrigger,} from "@/components/ui/tooltip";import { cn } from "@/lib/utils";-import {- Children,- useCallback,- useLayoutEffect,- useRef,- useState,-} from "react";+import { Children, useCallback, useLayoutEffect, useRef } from "react";import { ArrowUp02Icon, StopIcon } from "@hugeicons/core-free-icons";import { Icon as UIIcon } from "@/components/atoms/Icon/Icon";+import { isKey } from "@/lib/keyboard";// ============================================================================// PromptInput — form wrapper@@ -141,7 +136,6 @@ export function PromptInputTextarea({onMultilineChange,...props}: PromptInputTextareaProps) {- const [isComposing, setIsComposing] = useState(false);const textareaRef = useRef<HTMLTextAreaElement | null>(null);// Ref keeps autoResize stable inside the memoized change handler while// still reaching the latest callback.@@ -255,20 +249,16 @@ export function PromptInputTextarea({if (e.defaultPrevented) return;- if (e.key === "Enter") {- if (isComposing || e.nativeEvent.isComposing) return;+ if (isKey(e, "Enter")) {if (e.shiftKey) return;e.preventDefault();e.currentTarget.form?.requestSubmit();}},- [onKeyDown, isComposing],+ [onKeyDown],);- const handleCompositionEnd = useCallback(() => setIsComposing(false), []);- const handleCompositionStart = useCallback(() => setIsComposing(true), []);-return (<InputGroupTextarearef={textareaRef}@@ -280,8 +270,6 @@ export function PromptInputTextarea({name="message"value={value}onChange={handleChange}- onCompositionEnd={handleCompositionEnd}- onCompositionStart={handleCompositionStart}onKeyDown={handleKeyDown}placeholder={placeholder}{...props}diff --git a/autogpt_platform/frontend/src/components/atoms/Input/Input.test.tsx b/autogpt_platform/frontend/src/components/atoms/Input/Input.test.tsxnew file mode 100644index 0000000000..ffe500036f--- /dev/null+++ b/autogpt_platform/frontend/src/components/atoms/Input/Input.test.tsx@@ -0,0 +1,54 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import { Input } from "./Input";++describe("Input keyboard handling", () => {+ it("forwards a plain Enter keydown to onKeyDown", () => {+ const onKeyDown = vi.fn();+ render(<Input id="name" label="Name" onKeyDown={onKeyDown} />);++ fireEvent.keyDown(screen.getByLabelText("Name"), { key: "Enter" });++ expect(onKeyDown).toHaveBeenCalledTimes(1);+ });++ it("swallows keydowns fired while an IME is composing", () => {+ const onKeyDown = vi.fn();+ render(<Input id="name" label="Name" onKeyDown={onKeyDown} />);++ fireEvent.keyDown(screen.getByLabelText("Name"), {+ key: "Enter",+ isComposing: true,+ });++ expect(onKeyDown).not.toHaveBeenCalled();+ });++ it("guards the textarea variant the same way", () => {+ const onKeyDown = vi.fn();+ render(+ <Input id="bio" label="Bio" type="textarea" onKeyDown={onKeyDown} />,+ );+ const textarea = screen.getByLabelText("Bio");++ fireEvent.keyDown(textarea, { key: "Enter", isComposing: true });+ expect(onKeyDown).not.toHaveBeenCalled();++ fireEvent.keyDown(textarea, { key: "Enter" });+ expect(onKeyDown).toHaveBeenCalledTimes(1);+ });++ it("guards and forwards keydowns for the amount variant", () => {+ const onKeyDown = vi.fn();+ render(+ <Input id="amount" label="Amount" type="amount" onKeyDown={onKeyDown} />,+ );+ const amount = screen.getByLabelText("Amount");++ fireEvent.keyDown(amount, { key: "Enter", isComposing: true });+ expect(onKeyDown).not.toHaveBeenCalled();++ fireEvent.keyDown(amount, { key: "Enter" });+ expect(onKeyDown).toHaveBeenCalledTimes(1);+ });+});diff --git a/autogpt_platform/frontend/src/components/atoms/Input/Input.tsx b/autogpt_platform/frontend/src/components/atoms/Input/Input.tsxindex 16680b9d13..a83e4e82e3 100644--- a/autogpt_platform/frontend/src/components/atoms/Input/Input.tsx+++ b/autogpt_platform/frontend/src/components/atoms/Input/Input.tsx@@ -2,6 +2,7 @@ import {Input as BaseInput,type InputProps,} from "@/components/__legacy__/ui/input";+import { isComposingEvent } from "@/lib/keyboard";import { cn } from "@/lib/utils";import { forwardRef, ReactNode, useState } from "react";import CurrencyInput from "react-currency-input-field";@@ -14,7 +15,7 @@ import { Icon } from "@/components/atoms/Icon/Icon";type InputElement = HTMLInputElement | HTMLTextAreaElement;-export interface TextFieldProps extends Omit<InputProps, "size"> {+export interface TextFieldProps extends Omit<InputProps, "size" | "onKeyDown"> {label: string;id: string;hideLabel?: boolean;@@ -37,6 +38,9 @@ export interface TextFieldProps extends Omit<InputProps, "size"> {| "textarea"| "date"| "datetime-local";+ // Widened over InputProps, which only describes the <input> branch, so the+ // handler is callable with either element's event and needs no cast.+ onKeyDown?: React.KeyboardEventHandler<InputElement>;// Textarea-specific propsrows?: number;amountPrefix?: string;@@ -59,10 +63,20 @@ export const Input = forwardRef<InputElement, TextFieldProps>(function Input(wrapperClassName,amountPrefix,amountSuffix,+ onKeyDown,...props},ref,) {+ // Consumers never see keydowns an IME is still composing; see AGENTS.md+ // "Keyboard handling". Left undefined when the consumer passes no handler, so+ // we don't attach a listener that does nothing.+ function handleKeyDown(e: React.KeyboardEvent<InputElement>) {+ if (isComposingEvent(e)) return;+ onKeyDown?.(e);+ }+ const guardedOnKeyDown = onKeyDown ? handleKeyDown : undefined;+const { handleInputChange, handleTextareaChange, handleAmountValueChange } =useInput({type: props.type,@@ -122,11 +136,7 @@ export const Input = forwardRef<InputElement, TextFieldProps>(function Input()}placeholder={placeholder || label}onChange={handleTextareaChange}- onKeyDown={- props.onKeyDown as- | React.KeyboardEventHandler<HTMLTextAreaElement>- | undefined- }+ onKeyDown={guardedOnKeyDown}rows={props.rows || 3}{...(hideLabel ? { "aria-label": label } : {})}id={props.id}@@ -171,6 +181,7 @@ export const Input = forwardRef<InputElement, TextFieldProps>(function Input(// Pass through common handlersonBlur={props.onBlur as any}onFocus={props.onFocus as any}+ onKeyDown={guardedOnKeyDown}prefix={amountPrefix}suffix={amountSuffix}/>@@ -201,6 +212,7 @@ export const Input = forwardRef<InputElement, TextFieldProps>(function Input(onChange={handleInputChange}{...(hideLabel ? { "aria-label": label } : {})}{...props}+ onKeyDown={guardedOnKeyDown}type={inputType}/>);diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/components/RecentChatItem/RecentChatItem.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/components/RecentChatItem/RecentChatItem.tsxindex 28a854c94a..b613005450 100644--- a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/components/RecentChatItem/RecentChatItem.tsx+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/components/RecentChatItem/RecentChatItem.tsx@@ -27,6 +27,7 @@ import {Share03Icon,} from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";+import { isKey } from "@/lib/keyboard";interface Session {id: string;@@ -106,12 +107,12 @@ export function RecentChatItem({value={editingTitle}onChange={(e) => onEditingTitleChange(e.target.value)}onKeyDown={(e) => {- if (e.key === "Enter") {+ if (isKey(e, "Enter")) {e.preventDefault();skipBlurSubmitRef.current = true;onSubmitRename(session.id);e.currentTarget.blur();- } else if (e.key === "Escape") {+ } else if (isKey(e, "Escape")) {e.preventDefault();skipBlurSubmitRef.current = true;onCancelRename();diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/components/RecentChatItem/__tests__/RecentChatItem.test.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/components/RecentChatItem/__tests__/RecentChatItem.test.tsxindex 76f648709c..a361fc0ecb 100644--- a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/components/RecentChatItem/__tests__/RecentChatItem.test.tsx+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/components/RecentChatItem/__tests__/RecentChatItem.test.tsx@@ -91,6 +91,20 @@ describe("RecentChatItem — editing mode", () => {expect(onSubmitRename).toHaveBeenCalledWith("s1");});+ it("ignores Enter while an IME is still composing", () => {+ const onSubmitRename = vi.fn();+ renderItem(+ makeProps({ isEditing: true, editingTitle: "新しい", onSubmitRename }),+ );++ fireEvent.keyDown(screen.getByLabelText("Rename chat"), {+ key: "Enter",+ isComposing: true,+ });++ expect(onSubmitRename).not.toHaveBeenCalled();+ });+it("cancels on Escape", () => {const onCancelRename = vi.fn();renderItem(makeProps({ isEditing: true, onCancelRename }));diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/TopUpDialog.test.tsx b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/TopUpDialog.test.tsxindex 2c366e857a..eb0794ce87 100644--- a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/TopUpDialog.test.tsx+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/TopUpDialog.test.tsx@@ -63,17 +63,12 @@ describe("TopUpDialog", () => {expect(onClose).toHaveBeenCalledTimes(1);});- // Escape is handled twice by the design-system Dialog: `DialogWrap` passes- // `onEscapeKeyDown={handleClose}`, and Radix's dismissable layer then also- // fires `onOpenChange(false)` on the root. Both land on `controlled.set`.- // Closing is idempotent so nothing breaks, but pin the count — if the Dialog- // is ever fixed this test should be the thing that notices.- it("notifies close on Escape (twice, via the shared Dialog)", async () => {+ it("notifies close exactly once on Escape", async () => {const onClose = vi.fn();render(<TopUpDialog isOpen onClose={onClose} />);await userEvent.keyboard("{Escape}");- expect(onClose).toHaveBeenCalledTimes(2);+ expect(onClose).toHaveBeenCalledTimes(1);});});diff --git a/autogpt_platform/frontend/src/components/molecules/Dialog/__tests__/Dialog.test.tsx b/autogpt_platform/frontend/src/components/molecules/Dialog/__tests__/Dialog.test.tsxindex 46569a9214..c043d8027d 100644--- a/autogpt_platform/frontend/src/components/molecules/Dialog/__tests__/Dialog.test.tsx+++ b/autogpt_platform/frontend/src/components/molecules/Dialog/__tests__/Dialog.test.tsx@@ -10,13 +10,16 @@ vi.mock("@/lib/hooks/useBreakpoint", () => ({function renderDialog({title,controlled,+ forceOpen,}: {title?: string;controlled?: { isOpen: boolean; set: (open: boolean) => void };+ forceOpen?: boolean;}) {return render(<Dialogtitle={title}+ forceOpen={forceOpen}controlled={controlled ?? { isOpen: true, set: vi.fn() }}><Dialog.Content>@@ -73,6 +76,38 @@ describe("Dialog", () => {expect(set).toHaveBeenCalledWith(false);});+ test("does not close when Escape belongs to an IME composition", () => {+ const set = vi.fn();+ renderDialog({ title: "Test", controlled: { isOpen: true, set } });++ fireEvent.keyDown(document, { key: "Escape", isComposing: true });++ expect(set).not.toHaveBeenCalled();+ });++ test("keeps a force-open dialog open on Escape", () => {+ const set = vi.fn();+ renderDialog({+ title: "Test",+ forceOpen: true,+ controlled: { isOpen: true, set },+ });++ fireEvent.keyDown(document, { key: "Escape" });+ fireEvent.keyDown(document, { key: "Escape", isComposing: true });++ expect(set).not.toHaveBeenCalled();+ });++ test("closes on a plain Escape keydown", () => {+ const set = vi.fn();+ renderDialog({ title: "Test", controlled: { isOpen: true, set } });++ fireEvent.keyDown(document, { key: "Escape" });++ expect(set).toHaveBeenCalledWith(false);+ });+test("does not render dialog when controlled isOpen is false", () => {renderDialog({title: "Test",diff --git a/autogpt_platform/frontend/src/components/molecules/Dialog/__tests__/Drawer.test.tsx b/autogpt_platform/frontend/src/components/molecules/Dialog/__tests__/Drawer.test.tsxnew file mode 100644index 0000000000..bb5fe1ec99--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/Dialog/__tests__/Drawer.test.tsx@@ -0,0 +1,66 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, test, vi } from "vitest";+import { Dialog } from "../Dialog";++// Below the lg breakpoint the same <Dialog> renders as a drawer. Escape has to+// behave the same in both, which it did not before: only DialogWrap carried the+// composition guard.+vi.mock("@/lib/hooks/useBreakpoint", () => ({+ useBreakpoint: () => "sm",+ isLargeScreen: () => false,+}));++function renderDrawer({+ forceOpen,+ set,+}: {+ forceOpen?: boolean;+ set: (open: boolean) => void;+}) {+ return render(+ <Dialog+ title="Test"+ forceOpen={forceOpen}+ controlled={{ isOpen: true, set }}+ >+ <Dialog.Content>+ <p>Drawer body</p>+ </Dialog.Content>+ </Dialog>,+ );+}++describe("Dialog rendered as a drawer", () => {+ test("renders the drawer variant", () => {+ renderDrawer({ set: vi.fn() });++ expect(screen.getByText("Drawer body")).toBeDefined();+ });++ test("does not close when Escape belongs to an IME composition", () => {+ const set = vi.fn();+ renderDrawer({ set });++ fireEvent.keyDown(document, { key: "Escape", isComposing: true });++ expect(set).not.toHaveBeenCalled();+ });++ test("keeps a force-open drawer open on Escape", () => {+ const set = vi.fn();+ renderDrawer({ forceOpen: true, set });++ fireEvent.keyDown(document, { key: "Escape" });++ expect(set).not.toHaveBeenCalled();+ });++ test("closes on a plain Escape keydown", () => {+ const set = vi.fn();+ renderDrawer({ set });++ fireEvent.keyDown(document, { key: "Escape" });++ expect(set).toHaveBeenCalledWith(false);+ });+});diff --git a/autogpt_platform/frontend/src/components/molecules/Dialog/components/DialogWrap.tsx b/autogpt_platform/frontend/src/components/molecules/Dialog/components/DialogWrap.tsxindex 834ecc9f31..b7ace22735 100644--- a/autogpt_platform/frontend/src/components/molecules/Dialog/components/DialogWrap.tsx+++ b/autogpt_platform/frontend/src/components/molecules/Dialog/components/DialogWrap.tsx@@ -1,5 +1,6 @@import { Button } from "@/components/atoms/Button/Button";import { scrollbarStyles } from "@/components/styles/scrollbars";+import { isComposingEvent } from "@/lib/keyboard";import { cn } from "@/lib/utils";import * as RXDialog from "@radix-ui/react-dialog";import {@@ -75,6 +76,14 @@ export function DialogWrap({[isForceOpen],);+ // Radix closes the dialog on Escape by default, through onOpenChange. Veto it+ // while an IME is composing, so Escape dismisses the candidate window without+ // losing the dialog, and when the dialog is force-open — matching the sibling+ // handlers above and skipping a dismiss path that Dialog.tsx would undo.+ function handleEscapeKeyDown(event: KeyboardEvent) {+ if (isForceOpen || isComposingEvent(event)) event.preventDefault();+ }+useEffect(() => {function update() {const el = scrollRef.current;@@ -99,7 +108,7 @@ export function DialogWrap({onInteractOutside={handleInteractOutside}onPointerDownOutside={handlePointerDownOutside}onFocusOutside={handleFocusOutside}- onEscapeKeyDown={isForceOpen ? undefined : handleClose}+ onEscapeKeyDown={handleEscapeKeyDown}aria-describedby={undefined}className={cn(modalStyles.content,diff --git a/autogpt_platform/frontend/src/components/molecules/Dialog/components/DrawerWrap.tsx b/autogpt_platform/frontend/src/components/molecules/Dialog/components/DrawerWrap.tsxindex bdb89fc762..3363ce703a 100644--- a/autogpt_platform/frontend/src/components/molecules/Dialog/components/DrawerWrap.tsx+++ b/autogpt_platform/frontend/src/components/molecules/Dialog/components/DrawerWrap.tsx@@ -1,5 +1,6 @@import { Button } from "@/components/__legacy__/ui/button";import { scrollbarStyles } from "@/components/styles/scrollbars";+import { isComposingEvent } from "@/lib/keyboard";import { cn } from "@/lib/utils";import { PropsWithChildren } from "react";import { Drawer } from "vaul";@@ -29,6 +30,12 @@ export function DrawerWrap({const hasVisibleTitle = Boolean(title);const isCompact = variant === "compact";+ // Mirrors DialogWrap: below the lg breakpoint the same <Dialog> renders as a+ // drawer, and Escape has to behave identically in both.+ function handleEscapeKeyDown(event: KeyboardEvent) {+ if (isForceOpen || isComposingEvent(event)) event.preventDefault();+ }+const closeBtn = (<Buttonvariant="link"@@ -51,6 +58,7 @@ export function DrawerWrap({className,)}data-testid={testId}+ onEscapeKeyDown={handleEscapeKeyDown}onInteractOutside={handleClose}><divdiff --git a/autogpt_platform/frontend/src/components/molecules/MultiToggle/MultiToggle.test.tsx b/autogpt_platform/frontend/src/components/molecules/MultiToggle/MultiToggle.test.tsxnew file mode 100644index 0000000000..06c3ae9f68--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/MultiToggle/MultiToggle.test.tsx@@ -0,0 +1,59 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import { MultiToggle } from "./MultiToggle";++const ITEMS = [+ { value: "cat", label: "猫" },+ { value: "dog", label: "犬" },+];++function renderToggle(selectedValues: string[] = []) {+ const onChange = vi.fn();+ render(+ <MultiToggle+ items={ITEMS}+ selectedValues={selectedValues}+ onChange={onChange}+ aria-label="Animals"+ />,+ );+ return { onChange, cat: screen.getByRole("checkbox", { name: "猫" }) };+}++describe("MultiToggle keyboard handling", () => {+ it.each([" ", "Enter"])("selects an item on %s", (key) => {+ const { onChange, cat } = renderToggle();++ fireEvent.keyDown(cat, { key });++ expect(onChange).toHaveBeenCalledWith(["cat"]);+ });++ it("deselects an already selected item", () => {+ const { onChange, cat } = renderToggle(["cat", "dog"]);++ fireEvent.keyDown(cat, { key: " " });++ expect(onChange).toHaveBeenCalledWith(["dog"]);+ });++ it.each([+ ["a composing Space", { key: " ", isComposing: true }],+ ["a composing Enter", { key: "Enter", isComposing: true }],+ ["Safari's post-composition Enter", { key: "Enter", keyCode: 229 }],+ ])("leaves the selection alone on %s", (_label, init) => {+ const { onChange, cat } = renderToggle();++ fireEvent.keyDown(cat, init);++ expect(onChange).not.toHaveBeenCalled();+ });++ it("ignores unrelated keys", () => {+ const { onChange, cat } = renderToggle();++ fireEvent.keyDown(cat, { key: "a" });++ expect(onChange).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/components/molecules/MultiToggle/MultiToggle.tsx b/autogpt_platform/frontend/src/components/molecules/MultiToggle/MultiToggle.tsxindex ad74d3d70f..0556c37754 100644--- a/autogpt_platform/frontend/src/components/molecules/MultiToggle/MultiToggle.tsx+++ b/autogpt_platform/frontend/src/components/molecules/MultiToggle/MultiToggle.tsx@@ -2,6 +2,7 @@import { cn } from "@/lib/utils";import React, { useId } from "react";+import { isKey } from "@/lib/keyboard";type MultiToggleItem = {value: string;@@ -37,7 +38,7 @@ export function MultiToggle({}function handleKeyDown(event: React.KeyboardEvent, value: string) {- if (event.key === " " || event.key === "Enter") {+ if (isKey(event, " ", "Enter")) {event.preventDefault();handleToggle(value);}diff --git a/autogpt_platform/frontend/src/components/organisms/SearchCommandModal/SearchCommandModal.tsx b/autogpt_platform/frontend/src/components/organisms/SearchCommandModal/SearchCommandModal.tsxindex 592bba3b10..23f4413010 100644--- a/autogpt_platform/frontend/src/components/organisms/SearchCommandModal/SearchCommandModal.tsx+++ b/autogpt_platform/frontend/src/components/organisms/SearchCommandModal/SearchCommandModal.tsx@@ -16,6 +16,7 @@ import { SearchCommandSkeleton } from "./SearchCommandSkeleton";import { useKeyboardNav } from "./useKeyboardNav";import { Cancel01Icon, Search01Icon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";+import { isKey } from "@/lib/keyboard";interface Props {isOpen: boolean;@@ -84,13 +85,13 @@ export function SearchCommandModal({// Escape closure is handled by Radix's ``onOpenChange``; arrow// keys and Enter stay here so the input keeps focus while the user// navigates the result list.- if (event.key === "ArrowDown") {+ if (isKey(event, "ArrowDown")) {event.preventDefault();moveHighlight(1);- } else if (event.key === "ArrowUp") {+ } else if (isKey(event, "ArrowUp")) {event.preventDefault();moveHighlight(-1);- } else if (event.key === "Enter") {+ } else if (isKey(event, "Enter")) {event.preventDefault();selectHighlightedItem();}diff --git a/autogpt_platform/frontend/src/lib/keyboard.test.ts b/autogpt_platform/frontend/src/lib/keyboard.test.tsnew file mode 100644index 0000000000..05fc61e550--- /dev/null+++ b/autogpt_platform/frontend/src/lib/keyboard.test.ts@@ -0,0 +1,100 @@+import { describe, expect, it } from "vitest";+import { isComposingEvent, isKey, isKeyIgnoringComposition } from "./keyboard";++function keydown(key: string, extra: Partial<KeyboardEvent> = {}) {+ const event = new KeyboardEvent("keydown", { key });+ for (const [name, value] of Object.entries(extra)) {+ Object.defineProperty(event, name, { value });+ }+ return event;+}++function reactKeydown(key: string, extra: Partial<KeyboardEvent> = {}) {+ const nativeEvent = keydown(key, extra);+ return { key, nativeEvent } as unknown as React.KeyboardEvent;+}++describe("isComposingEvent", () => {+ it("is false for a plain key press", () => {+ expect(isComposingEvent(keydown("Enter"))).toBe(false);+ });++ it("is true while the IME reports composition", () => {+ expect(isComposingEvent(keydown("Enter", { isComposing: true }))).toBe(+ true,+ );+ });++ it("is true for the Safari post-composition keyCode 229", () => {+ expect(isComposingEvent(keydown("Enter", { keyCode: 229 }))).toBe(true);+ });++ it("reads the native event behind a React synthetic event", () => {+ expect(isComposingEvent(reactKeydown("Enter", { isComposing: true }))).toBe(+ true,+ );+ expect(isComposingEvent(reactKeydown("Enter"))).toBe(false);+ });+});++describe("isKey", () => {+ it("matches the key when not composing", () => {+ expect(isKey(keydown("Enter"), "Enter")).toBe(true);+ expect(isKey(reactKeydown(" "), " ")).toBe(true);+ });++ it("matches any of several keys", () => {+ expect(isKey(keydown(" "), "Enter", " ")).toBe(true);+ expect(isKey(keydown("Escape"), "Enter", " ")).toBe(false);+ });++ it("does not match a different key", () => {+ expect(isKey(keydown("Escape"), "Enter")).toBe(false);+ });++ it("guards the candidate-window paging keys too", () => {+ expect(isKey(keydown("PageDown"), "PageDown")).toBe(true);+ expect(isKey(keydown("PageDown", { isComposing: true }), "PageDown")).toBe(+ false,+ );+ expect(isKey(keydown("Home", { isComposing: true }), "Home")).toBe(false);+ });++ it("never matches while composing, even if the key name matches", () => {+ expect(isKey(keydown("Enter", { isComposing: true }), "Enter")).toBe(false);+ expect(isKey(reactKeydown("Enter", { keyCode: 229 }), "Enter")).toBe(false);+ });++ it("matches again once composition is over (Safari Enter flow)", () => {+ expect(isKey(keydown("Enter", { keyCode: 229 }), "Enter")).toBe(false);+ expect(isKey(keydown("Enter", { keyCode: 13 }), "Enter")).toBe(true);+ });++ it("lets an Android soft-keyboard Enter (keyCode 13) through", () => {+ expect(+ isKey(+ keydown("Unidentified", { keyCode: 229, isComposing: true }),+ "Enter",+ ),+ ).toBe(false);+ expect(isKey(keydown("Enter", { keyCode: 13 }), "Enter")).toBe(true);+ });+});++describe("isKeyIgnoringComposition", () => {+ it("matches the key name whether or not an IME is composing", () => {+ expect(isKeyIgnoringComposition(keydown("Tab"), "Tab")).toBe(true);+ expect(+ isKeyIgnoringComposition(keydown("Tab", { isComposing: true }), "Tab"),+ ).toBe(true);+ expect(+ isKeyIgnoringComposition(keydown("Tab", { keyCode: 229 }), "Tab"),+ ).toBe(true);+ });++ it("still does not match a different key", () => {+ expect(+ isKeyIgnoringComposition(keydown("Enter", { isComposing: true }), "Tab"),+ ).toBe(false);+ });+});diff --git a/autogpt_platform/frontend/src/lib/keyboard.ts b/autogpt_platform/frontend/src/lib/keyboard.tsnew file mode 100644index 0000000000..98ea2bb2cf--- /dev/null+++ b/autogpt_platform/frontend/src/lib/keyboard.ts@@ -0,0 +1,74 @@+import type { KeyboardEvent as ReactKeyboardEvent } from "react";++type AnyKeyboardEvent = ReactKeyboardEvent | KeyboardEvent;++// The key names `isKey` accepts and the `no-restricted-syntax` selectors in+// .eslintrc.json guard — every key an IME (Japanese, Chinese, Korean, ...) can+// claim while composing, whether to confirm a candidate (Enter, Space), page+// through the candidate window (arrows, PageUp/PageDown, Home/End), cancel it+// (Escape), or edit the reading (Backspace, Delete, Tab).+//+// Keys outside this set are deliberately unguarded: an IME never claims them,+// so comparing `e.key` directly against e.g. "F2" is fine and the lint rule+// ignores it. The eslint-keyboard-rules.test.ts suite fails if this list and+// the selectors drift apart.+export const KEY_NAMES = [+ "Enter",+ "Escape",+ "Tab",+ "ArrowUp",+ "ArrowDown",+ "ArrowLeft",+ "ArrowRight",+ "PageUp",+ "PageDown",+ "Home",+ "End",+ "Backspace",+ "Delete",+ " ",+] as const;++export type KeyName = (typeof KEY_NAMES)[number];++// Legacy keyCode browsers report for a keydown the IME handled. Safari also+// uses it for the Enter that confirms a candidate, which it fires after+// compositionend with `isComposing` already false, so `isComposing` alone+// would let that Enter through as a submit.+//+// Android soft keyboards report 229 too, but only for the composed text+// itself, which arrives as key "Unidentified"/"Process" — never a KeyName, so+// `isKey` rejects it on the key comparison regardless. Their Enter arrives as+// keyCode 13 and is unaffected. cmdk applies the same predicate.+const IME_KEYCODE = 229;++/**+ * True while an IME is composing, so the keydown belongs to the input method+ * rather than to the app. Works on both React synthetic and native events.+ */+export function isComposingEvent(e: AnyKeyboardEvent): boolean {+ const native = "nativeEvent" in e ? e.nativeEvent : e;+ return native.isComposing || native.keyCode === IME_KEYCODE;+}++/**+ * True when the event matches one of `keys` and no IME composition is in+ * progress. Use this for every keyboard shortcut so a Japanese, Chinese or+ * Korean user confirming a candidate does not also trigger the app's action.+ */+export function isKey(e: AnyKeyboardEvent, ...keys: KeyName[]): boolean {+ return !isComposingEvent(e) && (keys as string[]).includes(e.key);+}++/**+ * True when the event matches one of `keys`, whether or not an IME is+ * composing. Only for handlers that enforce containment rather than trigger an+ * action — a focus trap must keep holding Tab during composition, since letting+ * it through moves focus out of the modal entirely. Prefer {@link isKey}.+ */+export function isKeyIgnoringComposition(+ e: AnyKeyboardEvent,+ ...keys: KeyName[]+): boolean {+ return (keys as string[]).includes(e.key);+}