Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat: add customizable keyboard shortcuts (#5294)
Jiayuan Zhangb64ebd60b57c
diff --git a/apps/desktop/src/main/keyboard-shortcuts.test.ts b/apps/desktop/src/main/keyboard-shortcuts.test.tsindex 8c86a88333..97fa0e5e2a 100644--- a/apps/desktop/src/main/keyboard-shortcuts.test.ts+++ b/apps/desktop/src/main/keyboard-shortcuts.test.ts@@ -14,13 +14,14 @@ function makeWc(initialLevel = 0) {function key(k: string,- mods: Partial<Pick<ShortcutInput, "control" | "meta" | "shift">> = {},+ mods: Partial<Pick<ShortcutInput, "control" | "meta" | "alt" | "shift">> = {},): ShortcutInput {return {type: "keyDown",key: k,control: false,meta: false,+ alt: false,shift: false,...mods,};@@ -61,7 +62,7 @@ describe("handleAppShortcut — zoom in", () => {it("zooms in on Cmd++ (Shift+=)", () => {const wc = makeWc(0);- expect(handleAppShortcut(key("+", { meta: true }), wc, "darwin")).toBe(true);+ expect(handleAppShortcut(key("+", { meta: true, shift: true }), wc, "darwin")).toBe(true);expect(wc.currentLevel()).toBe(0.5);});@@ -93,7 +94,7 @@ describe("handleAppShortcut — zoom out (regression: MUL-2354)", () => {it("zooms out on Cmd+_ (Shift+-)", () => {const wc = makeWc(1);- expect(handleAppShortcut(key("_", { meta: true }), wc, "darwin")).toBe(true);+ expect(handleAppShortcut(key("_", { meta: true, shift: true }), wc, "darwin")).toBe(true);expect(wc.currentLevel()).toBe(0.5);});@@ -150,6 +151,16 @@ describe("handleAppShortcut — unrelated keys pass through", () => {expect(handleAppShortcut(key("a", { meta: true }), wc, "darwin")).toBe(false);expect(handleAppShortcut(key("k", { meta: true }), wc, "darwin")).toBe(false);});++ it("rejects extra secondary modifiers for owned shortcuts", () => {+ const wc = makeWc();+ expect(+ handleAppShortcut(key("w", { meta: true, control: true }), wc, "darwin"),+ ).toBe(false);+ expect(+ handleAppShortcut(key("-", { control: true, alt: true }), wc, "win32"),+ ).toBe(false);+ });});describe("handleAppShortcut — close tab (Cmd/Ctrl+W)", () => {@@ -183,4 +194,15 @@ describe("handleAppShortcut — close tab (Cmd/Ctrl+W)", () => {const wc = makeWc();expect(handleAppShortcut(key("W", { control: true, shift: true }), wc, "linux")).toBe(false);});++ it("swallows auto-repeat without closing additional tabs", () => {+ const wc = makeWc();+ expect(+ handleAppShortcut(+ { ...key("w", { meta: true }), isAutoRepeat: true },+ wc,+ "darwin",+ ),+ ).toBe(true);+ });});diff --git a/apps/desktop/src/main/keyboard-shortcuts.ts b/apps/desktop/src/main/keyboard-shortcuts.tsindex 761f2c3927..61b0d63110 100644--- a/apps/desktop/src/main/keyboard-shortcuts.ts+++ b/apps/desktop/src/main/keyboard-shortcuts.ts@@ -8,7 +8,9 @@ export type ShortcutInput = {key: string;control: boolean;meta: boolean;+ alt: boolean;shift: boolean;+ isAutoRepeat?: boolean;};// Subset of WebContents the zoom handler needs. Keeps the test mock tiny.@@ -49,32 +51,40 @@ export function handleAppShortcut(platform: NodeJS.Platform = process.platform,): ShortcutResult {if (input.type !== "keyDown") return false;- const cmdOrCtrl = platform === "darwin" ? input.meta : input.control;+ const primary = platform === "darwin" ? input.meta : input.control;+ const secondary = platform === "darwin" ? input.control : input.meta;+ const noSecondaryModifiers = !secondary && !input.alt;// Block reload — accidental Cmd+R / Ctrl+R / F5 destroys in-memory state// (tabs, drafts, WS connections) with no URL bar to recover from.- if ((cmdOrCtrl && input.key.toLowerCase() === "r") || input.key === "F5") {+ if ((primary && input.key.toLowerCase() === "r") || input.key === "F5") {return true;}- if (!cmdOrCtrl) return false;+ if (!primary || !noSecondaryModifiers) return false;// Cmd/Ctrl + "=" (unshifted) or "+" (Shift+=) → zoom in.- if (input.key === "=" || input.key === "+") {+ if (+ (input.key === "=" && !input.shift) ||+ (input.key === "+" && input.shift)+ ) {const next = Math.min(webContents.getZoomLevel() + ZOOM_STEP, ZOOM_MAX);webContents.setZoomLevel(next);return true;}// Cmd/Ctrl + "-" (unshifted) or "_" (Shift+-) → zoom out.- if (input.key === "-" || input.key === "_") {+ if (+ (input.key === "-" && !input.shift) ||+ (input.key === "_" && input.shift)+ ) {const next = Math.max(webContents.getZoomLevel() - ZOOM_STEP, ZOOM_MIN);webContents.setZoomLevel(next);return true;}// Cmd/Ctrl + 0 → reset zoom to 100%.- if (input.key === "0") {+ if (input.key === "0" && !input.shift) {webContents.setZoomLevel(0);return true;}@@ -83,6 +93,9 @@ export function handleAppShortcut(// Cmd/Ctrl + Shift + W is reserved for "close window" — do not intercept.// Return a signal so the caller can send IPC to the renderer.if (input.key.toLowerCase() === "w" && !input.shift) {+ // Holding Cmd/Ctrl+W must not race through several product tabs. Swallow+ // Electron's repeated keydown without issuing another close request.+ if (input.isAutoRepeat) return true;return "close-tab";}diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.tsxindex c3107e4b0a..b4b716c118 100644--- a/apps/desktop/src/renderer/src/components/desktop-layout.tsx+++ b/apps/desktop/src/renderer/src/components/desktop-layout.tsx@@ -11,7 +11,7 @@ import {useSidebar,} from "@multica/ui/components/ui/sidebar";import { ModalRegistry } from "@multica/views/modals/registry";-import { AppSidebar } from "@multica/views/layout";+import { AppSidebar, GlobalShortcuts } from "@multica/views/layout";import { SearchCommand, SearchTrigger } from "@multica/views/search";import { FloatingChat } from "@multica/views/chat";import { WorkspaceSlugProvider, paths, useCurrentWorkspace } from "@multica/core/paths";@@ -213,6 +213,7 @@ export function DesktopShell() {<DesktopInboxBridge /><div className="flex h-screen bg-app-shell"><SidebarProvider className="flex-1 bg-app-shell">+ {slug && <GlobalShortcuts />}{slug && <WindowToolbar />}{slug && <AppSidebar topSlot={<SidebarTopSpacer />} searchSlot={<SearchTrigger />} />}{/* Right side: header + content container */}diff --git a/packages/core/package.json b/packages/core/package.jsonindex 4ce09d0045..fec0f807e9 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -107,6 +107,7 @@"./constants/*": "./constants/*.ts","./feature-flags": "./feature-flags/index.ts","./platform": "./platform/index.ts",+ "./shortcuts": "./shortcuts/index.ts","./analytics": "./analytics/index.ts","./i18n": "./i18n/index.ts","./i18n/react": "./i18n/react.ts",diff --git a/packages/core/platform/core-provider.tsx b/packages/core/platform/core-provider.tsxindex 210d754268..21f07e518f 100644--- a/packages/core/platform/core-provider.tsx+++ b/packages/core/platform/core-provider.tsx@@ -18,6 +18,7 @@ import { defaultStorage } from "./storage";import { AuthInitializer } from "./auth-initializer";import type { CoreProviderProps, ClientIdentity } from "./types";import type { StorageAdapter } from "../types/storage";+import { configureShortcutPlatform } from "../shortcuts/platform";// Module-level singletons — created once at first render, never recreated.// Vite HMR preserves module-level state, so these survive hot reloads.@@ -34,6 +35,15 @@ function initCore() {if (initialized) return;+ configureShortcutPlatform(+ identity?.os === "macos" ||+ identity?.os === "windows" ||+ identity?.os === "linux" ||+ identity?.os === "unknown"+ ? identity.os+ : null,+ );+const api = new ApiClient(apiBaseUrl, {logger: createLogger("api"),onUnauthorized: () => {diff --git a/packages/core/platform/index.ts b/packages/core/platform/index.tsindex 443cde02f9..ed68bfba00 100644--- a/packages/core/platform/index.ts+++ b/packages/core/platform/index.ts@@ -5,7 +5,6 @@ export { defaultStorage } from "./storage";export { createPersistStorage } from "./persist-storage";export { createWorkspaceAwareStorage, setCurrentWorkspace, getCurrentSlug, getCurrentWsId, subscribeToCurrentSlug, registerForWorkspaceRehydration } from "./workspace-storage";export { clearWorkspaceStorage } from "./storage-cleanup";-export { isMac, modKey, enterKey, formatShortcut } from "./keyboard";export {registerSystemNotificationClickHandler,isWebNotificationSupported,diff --git a/packages/core/platform/keyboard.test.ts b/packages/core/platform/keyboard.test.tsdeleted file mode 100644index a82d254785..0000000000--- a/packages/core/platform/keyboard.test.ts+++ /dev/null@@ -1,51 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--afterEach(() => {- vi.unstubAllGlobals();- vi.resetModules();-});--beforeEach(() => {- vi.resetModules();-});--describe("keyboard platform helper", () => {- it("renders Mac symbols when navigator.platform is MacIntel", async () => {- vi.stubGlobal("navigator", { platform: "MacIntel" });- const mod = await import("./keyboard");-- expect(mod.isMac).toBe(true);- expect(mod.modKey).toBe("⌘");- expect(mod.enterKey).toBe("↵");- expect(mod.formatShortcut(mod.modKey, "K")).toBe("⌘K");- expect(mod.formatShortcut(mod.modKey, mod.enterKey)).toBe("⌘↵");- });-- it("renders Ctrl/Enter on Windows", async () => {- vi.stubGlobal("navigator", { platform: "Win32" });- const mod = await import("./keyboard");-- expect(mod.isMac).toBe(false);- expect(mod.modKey).toBe("Ctrl");- expect(mod.enterKey).toBe("Enter");- expect(mod.formatShortcut(mod.modKey, "K")).toBe("Ctrl+K");- expect(mod.formatShortcut(mod.modKey, mod.enterKey)).toBe("Ctrl+Enter");- });-- it("renders Ctrl/Enter on Linux", async () => {- vi.stubGlobal("navigator", { platform: "Linux x86_64" });- const mod = await import("./keyboard");-- expect(mod.isMac).toBe(false);- expect(mod.modKey).toBe("Ctrl");- expect(mod.formatShortcut("Ctrl", "Shift", "P")).toBe("Ctrl+Shift+P");- });-- it("falls back to non-Mac when navigator is unavailable (SSR)", async () => {- vi.stubGlobal("navigator", undefined);- const mod = await import("./keyboard");-- expect(mod.isMac).toBe(false);- expect(mod.modKey).toBe("Ctrl");- });-});diff --git a/packages/core/platform/keyboard.ts b/packages/core/platform/keyboard.tsdeleted file mode 100644index 095eaac2fe..0000000000--- a/packages/core/platform/keyboard.ts+++ /dev/null@@ -1,24 +0,0 @@-/**- * Coarse platform detection for keyboard-shortcut display.- *- * Eagerly evaluated at module load. On the server (no `navigator`) this- * resolves to `false`, so SSR always renders the non-Mac variant; on a- * real Mac the value is true after hydration. Acceptable trade-off for- * cosmetic shortcut hints — never gate functional behavior on this.- */-export const isMac =- typeof navigator !== "undefined" && /Mac/.test(navigator.platform);--/** Modifier key label — ⌘ on Mac, "Ctrl" elsewhere. */-export const modKey: string = isMac ? "⌘" : "Ctrl";--/** Enter / return key label — ↵ on Mac, "Enter" elsewhere. */-export const enterKey: string = isMac ? "↵" : "Enter";--/**- * Join key labels for display. Mac compresses combos with no separator- * ("⌘K", "⌘↵"); other platforms use "+" ("Ctrl+K", "Ctrl+Enter").- */-export function formatShortcut(...keys: string[]): string {- return keys.join(isMac ? "" : "+");-}diff --git a/packages/core/shortcuts/definitions.test.ts b/packages/core/shortcuts/definitions.test.tsnew file mode 100644index 0000000000..2defda5bd0--- /dev/null+++ b/packages/core/shortcuts/definitions.test.ts@@ -0,0 +1,206 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ createShortcutChord,+ formatShortcut,+ isShortcutAllowedForAction,+ isReservedShortcut,+ parseLegacyShortcut,+ SHORTCUT_ACTIONS,+ shortcutFromEvent,+ shortcutMatchesEvent,+} from "./definitions";+import { configureShortcutPlatform, detectShortcutPlatform } from "./platform";++function keyEvent(+ key: string,+ modifiers: Partial<Pick<KeyboardEvent, "metaKey" | "ctrlKey" | "altKey" | "shiftKey">> = {},+): KeyboardEvent {+ return {+ key,+ metaKey: false,+ ctrlKey: false,+ altKey: false,+ shiftKey: false,+ ...modifiers,+ } as KeyboardEvent;+}++afterEach(() => {+ configureShortcutPlatform(null);+ vi.unstubAllGlobals();+});++describe("keyboard shortcut definitions", () => {+ it("keeps every shipped default inside the action safety policy", () => {+ for (const action of SHORTCUT_ACTIONS) {+ if (!action.defaultShortcut) continue;+ expect(+ isShortcutAllowedForAction(+ action.id,+ action.defaultShortcut,+ "macos",+ ),+ ).toBe(true);+ expect(+ isShortcutAllowedForAction(+ action.id,+ action.defaultShortcut,+ "windows",+ ),+ ).toBe(true);+ }+ });++ it("strictly distinguishes Command and Control on macOS", () => {+ const commandF = createShortcutChord("F", { primary: true });+ const controlF = createShortcutChord("F", { control: true });++ expect(shortcutMatchesEvent(commandF, keyEvent("f", { metaKey: true }), "macos")).toBe(true);+ expect(shortcutMatchesEvent(commandF, keyEvent("f", { ctrlKey: true }), "macos")).toBe(false);+ expect(shortcutMatchesEvent(controlF, keyEvent("f", { ctrlKey: true }), "macos")).toBe(true);+ expect(shortcutMatchesEvent(controlF, keyEvent("f", { metaKey: true }), "macos")).toBe(false);+ });++ it("maps Control to primary on Windows/Linux and keeps Meta separate", () => {+ const primaryK = createShortcutChord("K", { primary: true });+ expect(shortcutMatchesEvent(primaryK, keyEvent("k", { ctrlKey: true }), "windows")).toBe(true);+ expect(shortcutMatchesEvent(primaryK, keyEvent("k", { metaKey: true }), "windows")).toBe(false);+ expect(shortcutFromEvent(keyEvent("k", { metaKey: true }), "windows")).toEqual(+ createShortcutChord("K", { meta: true }),+ );+ });++ it("requires every modifier to match exactly", () => {+ const shortcut = createShortcutChord("K", { primary: true });+ expect(+ shortcutMatchesEvent(+ shortcut,+ keyEvent("k", { ctrlKey: true, shiftKey: true }),+ "linux",+ ),+ ).toBe(false);+ });++ it.each([+ ["Meta", { metaKey: true }],+ ["Control", { ctrlKey: true }],+ ["Alt", { altKey: true }],+ ["Shift", { shiftKey: true }],+ ])("never matches an unassigned action when %s is pressed alone", (key, modifiers) => {+ expect(shortcutFromEvent(keyEvent(key, modifiers), "macos")).toBeNull();+ expect(shortcutMatchesEvent(null, keyEvent(key, modifiers), "macos")).toBe(false);+ });++ it("formats the same semantic binding for each platform", () => {+ const shortcut = createShortcutChord("Enter", { primary: true });+ expect(formatShortcut(shortcut, "macos")).toBe("⌘↵");+ expect(formatShortcut(shortcut, "windows")).toBe("Ctrl+Enter");+ expect(formatShortcut(shortcut, "linux")).toBe("Ctrl+Enter");+ });++ it("detects modern and legacy browser platform signals", () => {+ vi.stubGlobal("navigator", {+ userAgentData: { platform: "macOS" },+ platform: "Win32",+ userAgent: "",+ });+ expect(detectShortcutPlatform()).toBe("macos");+ });++ it("falls back past empty or unrecognized platform signals", () => {+ vi.stubGlobal("navigator", {+ userAgentData: { platform: "" },+ platform: "",+ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X)",+ });+ expect(detectShortcutPlatform()).toBe("macos");+ });++ it("uses platform-specific reserved shortcuts", () => {+ expect(+ isReservedShortcut(createShortcutChord("Space", { primary: true }), "macos"),+ ).toBe(true);+ expect(+ isReservedShortcut(createShortcutChord("K", { meta: true }), "windows"),+ ).toBe(true);+ expect(+ isReservedShortcut(createShortcutChord("K", { primary: true }), "windows"),+ ).toBe(false);+ });++ it("rejects modifier-only, composition-only, and unidentified key events", () => {+ for (const key of ["Fn", "CapsLock", "Dead", "Process", "Unidentified"]) {+ expect(shortcutFromEvent(keyEvent(key), "macos")).toBeNull();+ }+ });++ it("prevents unsafe plain keys from hijacking editors and global navigation", () => {+ expect(+ isShortcutAllowedForAction("openSearch", createShortcutChord("J"), "macos"),+ ).toBe(false);+ expect(+ isShortcutAllowedForAction("send", createShortcutChord("J"), "macos"),+ ).toBe(false);+ expect(+ isShortcutAllowedForAction(+ "send",+ createShortcutChord("J", { shift: true }),+ "macos",+ ),+ ).toBe(false);+ expect(+ isShortcutAllowedForAction(+ "openSearch",+ createShortcutChord("J", { alt: true }),+ "macos",+ ),+ ).toBe(false);+ expect(+ isShortcutAllowedForAction("send", createShortcutChord("Enter"), "macos"),+ ).toBe(true);+ expect(+ isShortcutAllowedForAction(+ "send",+ createShortcutChord("Enter", { primary: true }),+ "macos",+ ),+ ).toBe(true);+ expect(+ isShortcutAllowedForAction(+ "send",+ createShortcutChord("Enter", { shift: true }),+ "macos",+ ),+ ).toBe(false);+ expect(+ isShortcutAllowedForAction(+ "send",+ createShortcutChord("Enter", { primary: true, shift: true }),+ "macos",+ ),+ ).toBe(false);+ expect(+ isShortcutAllowedForAction("goInbox", createShortcutChord("Enter"), "macos"),+ ).toBe(false);+ expect(+ isShortcutAllowedForAction("goInbox", createShortcutChord("G"), "macos"),+ ).toBe(true);+ });++ it("protects fundamental editing shortcuts from reassignment", () => {+ expect(+ isShortcutAllowedForAction(+ "send",+ createShortcutChord("C", { primary: true }),+ "macos",+ ),+ ).toBe(false);+ });++ it("parses v1 persisted string bindings", () => {+ expect(parseLegacyShortcut("Mod+Shift+K")).toEqual(+ createShortcutChord("K", { primary: true, shift: true }),+ );+ expect(parseLegacyShortcut("Bogus+K")).toBeNull();+ });+});diff --git a/packages/core/shortcuts/definitions.ts b/packages/core/shortcuts/definitions.tsnew file mode 100644index 0000000000..1282558a34--- /dev/null+++ b/packages/core/shortcuts/definitions.ts@@ -0,0 +1,332 @@+import {+ getShortcutPlatform,+ type ShortcutPlatform,+} from "./platform";++export type ShortcutActionId =+ | "openSearch"+ | "createIssue"+ | "toggleSidebar"+ | "findInIssue"+ | "send"+ | "goInbox"+ | "goChat"+ | "goMyIssues"+ | "goIssues"+ | "goProjects"+ | "goAutopilots"+ | "goAgents"+ | "goSquads"+ | "goUsage"+ | "goRuntimes"+ | "goSkills"+ | "goSettings";++export type ShortcutCategory = "general" | "navigation";++export interface ShortcutModifiers {+ /** Command on macOS, Control on Windows/Linux. */+ primary: boolean;+ /** Literal Control, distinct from Command on macOS. */+ control: boolean;+ /** Literal Meta/Windows/Super, distinct from Control on Windows/Linux. */+ meta: boolean;+ alt: boolean;+ shift: boolean;+}++export interface ShortcutChord {+ /** Logical key (`KeyboardEvent.key`), not physical keyboard position. */+ key: string;+ modifiers: ShortcutModifiers;+}++export interface ShortcutActionDefinition {+ id: ShortcutActionId;+ category: ShortcutCategory;+ defaultShortcut: ShortcutChord | null;+ /** Whether the global handler may run while focus is inside an editor/control. */+ allowInEditable: boolean;+}++export function createShortcutChord(+ key: string,+ modifiers: Partial<ShortcutModifiers> = {},+): ShortcutChord {+ return {+ key,+ modifiers: {+ primary: false,+ control: false,+ meta: false,+ alt: false,+ shift: false,+ ...modifiers,+ },+ };+}++const primary = (key: string) =>+ createShortcutChord(key, { primary: true });++export const SHORTCUT_ACTIONS: readonly ShortcutActionDefinition[] = [+ { id: "openSearch", category: "general", defaultShortcut: primary("K"), allowInEditable: true },+ { id: "createIssue", category: "general", defaultShortcut: createShortcutChord("C"), allowInEditable: false },+ { id: "toggleSidebar", category: "general", defaultShortcut: primary("B"), allowInEditable: false },+ { id: "findInIssue", category: "general", defaultShortcut: primary("F"), allowInEditable: true },+ { id: "send", category: "general", defaultShortcut: primary("Enter"), allowInEditable: true },+ { id: "goInbox", category: "navigation", defaultShortcut: null, allowInEditable: false },+ { id: "goChat", category: "navigation", defaultShortcut: null, allowInEditable: false },+ { id: "goMyIssues", category: "navigation", defaultShortcut: null, allowInEditable: false },+ { id: "goIssues", category: "navigation", defaultShortcut: null, allowInEditable: false },+ { id: "goProjects", category: "navigation", defaultShortcut: null, allowInEditable: false },+ { id: "goAutopilots", category: "navigation", defaultShortcut: null, allowInEditable: false },+ { id: "goAgents", category: "navigation", defaultShortcut: null, allowInEditable: false },+ { id: "goSquads", category: "navigation", defaultShortcut: null, allowInEditable: false },+ { id: "goUsage", category: "navigation", defaultShortcut: null, allowInEditable: false },+ { id: "goRuntimes", category: "navigation", defaultShortcut: null, allowInEditable: false },+ { id: "goSkills", category: "navigation", defaultShortcut: null, allowInEditable: false },+ { id: "goSettings", category: "navigation", defaultShortcut: null, allowInEditable: false },+] as const;++export const SHORTCUT_ACTION_BY_ID = Object.fromEntries(+ SHORTCUT_ACTIONS.map((action) => [action.id, action]),+) as Record<ShortcutActionId, ShortcutActionDefinition>;++const MODIFIER_KEYS = new Set([+ "Alt", "AltGraph", "CapsLock", "Control", "Fn", "FnLock", "Hyper",+ "Meta", "NumLock", "ScrollLock", "Shift", "Super", "Symbol", "SymbolLock",+]);+const NON_ACTIONABLE_KEYS = new Set(["Dead", "Process", "Unidentified"]);+const KEY_LABELS: Record<string, string> = {+ " ": "Space",+ ArrowUp: "Up",+ ArrowDown: "Down",+ ArrowLeft: "Left",+ ArrowRight: "Right",+ Esc: "Escape",+ "+": "Plus",+ "-": "Minus",+ "=": "Equals",+ "_": "Underscore",+};++function eventKey(event: KeyboardEvent): string | null {+ if (MODIFIER_KEYS.has(event.key) || NON_ACTIONABLE_KEYS.has(event.key)) return null;+ const key = KEY_LABELS[event.key] ?? event.key;+ if (key.length === 1 && /[a-z]/i.test(key)) return key.toUpperCase();+ return key;+}++export function isShortcutChordActionable(shortcut: ShortcutChord): boolean {+ return shortcut.key.length > 0 &&+ !MODIFIER_KEYS.has(shortcut.key) &&+ !NON_ACTIONABLE_KEYS.has(shortcut.key);+}++/** Convert a key event into a platform-aware, structured chord. */+export function shortcutFromEvent(+ event: KeyboardEvent,+ platform: ShortcutPlatform = getShortcutPlatform(),+): ShortcutChord | null {+ if (event.getModifierState?.("AltGraph")) return null;+ const key = eventKey(event);+ if (!key) return null;+ const mac = platform === "macos";+ return createShortcutChord(key, {+ primary: mac ? event.metaKey : event.ctrlKey,+ control: mac ? event.ctrlKey : false,+ meta: mac ? false : event.metaKey,+ alt: event.altKey,+ shift: event.shiftKey,+ });+}++export function shortcutChordEquals(+ left: ShortcutChord | null,+ right: ShortcutChord | null,+): boolean {+ if (left === null || right === null) return left === right;+ return (+ left.key === right.key &&+ left.modifiers.primary === right.modifiers.primary &&+ left.modifiers.control === right.modifiers.control &&+ left.modifiers.meta === right.modifiers.meta &&+ left.modifiers.alt === right.modifiers.alt &&+ left.modifiers.shift === right.modifiers.shift+ );+}++/** Exact matcher: any additional modifier intentionally makes the event differ. */+export function shortcutMatchesEvent(+ shortcut: ShortcutChord | null,+ event: KeyboardEvent,+ platform: ShortcutPlatform = getShortcutPlatform(),+): boolean {+ // `null` means two different things at this boundary: an action without an+ // assigned shortcut, or an event that contains no actionable key (for+ // example pressing Command/Control/Shift by itself). Neither may execute an+ // action, even though `shortcutChordEquals(null, null)` is useful elsewhere+ // when comparing persisted values.+ if (!shortcut) return false;+ const eventShortcut = shortcutFromEvent(event, platform);+ return eventShortcut !== null && shortcutChordEquals(shortcut, eventShortcut);+}++export function isPlainShortcut(+ shortcut: ShortcutChord | null,+ key: string,+): boolean {+ return shortcutChordEquals(shortcut, createShortcutChord(key));+}++export function formatShortcut(+ shortcut: ShortcutChord | null,+ platform: ShortcutPlatform = getShortcutPlatform(),+): string {+ if (!shortcut) return "—";+ const { modifiers } = shortcut;+ const keyLabels: Record<string, string> = {+ Enter: platform === "macos" ? "↵" : "Enter",+ Backspace: platform === "macos" ? "⌫" : "Backspace",+ Delete: platform === "macos" ? "⌦" : "Delete",+ Escape: "Esc",+ Up: "↑",+ Down: "↓",+ Left: "←",+ Right: "→",+ Plus: "+",+ Minus: platform === "macos" ? "−" : "-",+ Equals: "=",+ Underscore: "_",+ Space: "Space",+ };+ const key = keyLabels[shortcut.key] ?? shortcut.key;++ if (platform === "macos") {+ return [+ modifiers.primary ? "⌘" : "",+ modifiers.control ? "⌃" : "",+ modifiers.alt ? "⌥" : "",+ modifiers.shift ? "⇧" : "",+ modifiers.meta ? "Meta" : "",+ key,+ ].join("");+ }++ return [+ modifiers.primary ? "Ctrl" : null,+ modifiers.control ? "Control" : null,+ modifiers.meta ? (platform === "windows" ? "Win" : "Super") : null,+ modifiers.alt ? "Alt" : null,+ modifiers.shift ? "Shift" : null,+ key,+ ].filter(Boolean).join("+");+}++export function isEditableShortcutTarget(target: EventTarget | null): boolean {+ if (!(target instanceof HTMLElement)) return false;+ return (+ target.isContentEditable ||+ target.tagName === "INPUT" ||+ target.tagName === "TEXTAREA" ||+ target.tagName === "SELECT" ||+ target.closest("[contenteditable='true']") !== null+ );+}++const PRIMARY_RESERVED_KEYS = new Set([+ // Window/browser operations.+ "W", "R", "L", "T", "N", "P", "Q", "D", "U",+ // Fundamental editing operations should never become product actions.+ "A", "C", "V", "X", "Y", "Z",+ "Equals", "Plus", "Minus", "Underscore", "0",+]);++/** Browser/window/OS accelerators that cannot be reliably owned by the app. */+export function isReservedShortcut(+ shortcut: ShortcutChord,+ platform: ShortcutPlatform = getShortcutPlatform(),+): boolean {+ const { modifiers, key } = shortcut;+ if (key === "F5") return true;+ if (modifiers.primary && PRIMARY_RESERVED_KEYS.has(key)) return true;++ if (platform === "macos") {+ if (modifiers.primary && (key === "Space" || key === "Tab" || key === "M" || key === "H")) return true;+ if (modifiers.control && ["Up", "Down", "Left", "Right"].includes(key)) return true;+ } else {+ // Windows/Super shortcuts are owned by the shell/window manager and often+ // never reach the browser. Reject all of them instead of pretending a+ // recorded binding will be dependable.+ if (modifiers.meta) return true;+ if (modifiers.alt && (key === "Tab" || key === "F4")) return true;+ }++ return false;+}++const PLAIN_GLOBAL_RESERVED_KEYS = new Set([+ "Enter", "Space", "Tab", "Escape", "Backspace", "Delete",+ "Up", "Down", "Left", "Right", "Home", "End", "PageUp", "PageDown",+]);++function hasShortcutModifier(shortcut: ShortcutChord): boolean {+ const { modifiers } = shortcut;+ return modifiers.primary || modifiers.control || modifiers.meta ||+ modifiers.alt || modifiers.shift;+}++function hasCommandModifier(shortcut: ShortcutChord): boolean {+ const { modifiers } = shortcut;+ return modifiers.primary || modifiers.control || modifiers.meta;+}++/**+ * Product-level safety policy layered on top of OS/browser reservations.+ * Plain text keys are useful for non-editable navigation (for example `C`),+ * but an action allowed inside editors must not fire while the user types.+ * Send is the one deliberate exception: plain Enter is supported explicitly.+ */+export function isShortcutAllowedForAction(+ actionId: ShortcutActionId,+ shortcut: ShortcutChord,+ platform: ShortcutPlatform = getShortcutPlatform(),+): boolean {+ if (!isShortcutChordActionable(shortcut)) return false;+ if (isReservedShortcut(shortcut, platform)) return false;+ // Tab is focus navigation (and Ctrl+Tab is browser tab navigation) on every+ // supported platform. It is never a dependable product-level binding.+ if (shortcut.key === "Tab") return false;+ const hasModifier = hasShortcutModifier(shortcut);+ const hasCommand = hasCommandModifier(shortcut);++ if (actionId === "send") {+ return shortcutChordEquals(shortcut, createShortcutChord("Enter")) ||+ shortcutChordEquals(+ shortcut,+ createShortcutChord("Enter", { primary: true }),+ );+ }+ if (SHORTCUT_ACTION_BY_ID[actionId].allowInEditable) {+ return hasCommand;+ }+ return hasModifier || !PLAIN_GLOBAL_RESERVED_KEYS.has(shortcut.key);+}++/** One-time parser for v1 string preferences persisted before structured chords. */+export function parseLegacyShortcut(value: string): ShortcutChord | null {+ if (!value) return null;+ const parts = value.split("+");+ const key = parts.pop();+ if (!key) return null;+ const knownModifiers = new Set(["Mod", "Ctrl", "Meta", "Alt", "Shift"]);+ if (parts.some((part) => !knownModifiers.has(part))) return null;+ return createShortcutChord(key, {+ primary: parts.includes("Mod"),+ control: parts.includes("Ctrl"),+ meta: parts.includes("Meta"),+ alt: parts.includes("Alt"),+ shift: parts.includes("Shift"),+ });+}diff --git a/packages/core/shortcuts/index.ts b/packages/core/shortcuts/index.tsnew file mode 100644index 0000000000..800c119b42--- /dev/null+++ b/packages/core/shortcuts/index.ts@@ -0,0 +1,32 @@+export {+ SHORTCUT_ACTIONS,+ SHORTCUT_ACTION_BY_ID,+ createShortcutChord,+ shortcutFromEvent,+ shortcutChordEquals,+ shortcutMatchesEvent,+ isPlainShortcut,+ formatShortcut,+ isEditableShortcutTarget,+ isReservedShortcut,+ isShortcutAllowedForAction,+ type ShortcutActionDefinition,+ type ShortcutActionId,+ type ShortcutCategory,+ type ShortcutChord,+ type ShortcutModifiers,+} from "./definitions";+export {+ configureShortcutPlatform,+ detectShortcutPlatform,+ getShortcutPlatform,+ type ShortcutPlatform,+} from "./platform";+export {+ useShortcutStore,+ useShortcut,+ resolveShortcut,+ getShortcut,+ findShortcutConflict,+ type ShortcutOverrides,+} from "./store";diff --git a/packages/core/shortcuts/platform.ts b/packages/core/shortcuts/platform.tsnew file mode 100644index 0000000000..27fea6ecb6--- /dev/null+++ b/packages/core/shortcuts/platform.ts@@ -0,0 +1,39 @@+export type ShortcutPlatform = "macos" | "windows" | "linux" | "unknown";++let configuredPlatform: ShortcutPlatform | null = null;++function normalizePlatform(value: string): ShortcutPlatform {+ const platform = value.toLowerCase();+ if (platform.includes("mac") || platform.includes("darwin")) return "macos";+ if (platform.includes("win")) return "windows";+ if (platform.includes("linux") || platform.includes("x11")) return "linux";+ return "unknown";+}++/** Browser fallback. Desktop injects its authoritative OS through CoreProvider. */+export function detectShortcutPlatform(): ShortcutPlatform {+ if (typeof navigator === "undefined") return "unknown";+ const nav = navigator as Navigator & {+ userAgentData?: { platform?: string };+ };+ // Some privacy-hardened browsers expose `platform` as an empty string.+ // Nullish coalescing would stop there and discard a still-useful userAgent,+ // causing Command to be interpreted as Windows/Super on a Mac.+ const signals = [nav.userAgentData?.platform, nav.platform, nav.userAgent];+ for (const signal of signals) {+ if (!signal?.trim()) continue;+ const platform = normalizePlatform(signal);+ if (platform !== "unknown") return platform;+ }+ return "unknown";+}++export function configureShortcutPlatform(+ platform: ShortcutPlatform | null | undefined,+): void {+ configuredPlatform = platform ?? null;+}++export function getShortcutPlatform(): ShortcutPlatform {+ return configuredPlatform ?? detectShortcutPlatform();+}diff --git a/packages/core/shortcuts/store.test.ts b/packages/core/shortcuts/store.test.tsnew file mode 100644index 0000000000..5dbd0dfcc3--- /dev/null+++ b/packages/core/shortcuts/store.test.ts@@ -0,0 +1,129 @@+import { afterEach, describe, expect, it } from "vitest";+import { createShortcutChord } from "./definitions";+import {+ findShortcutConflict,+ getShortcut,+ migrateShortcutState,+ sanitizeShortcutOverrides,+ useShortcutStore,+} from "./store";++afterEach(() => {+ useShortcutStore.getState().resetAll();+});++describe("shortcut store", () => {+ it("uses defaults, persists overrides, and can disable an action", () => {+ expect(getShortcut("openSearch")).toEqual(+ createShortcutChord("K", { primary: true }),+ );+ expect(getShortcut("send")).toEqual(+ createShortcutChord("Enter", { primary: true }),+ );++ const custom = createShortcutChord("J", { primary: true });+ useShortcutStore.getState().setShortcut("openSearch", custom);+ expect(getShortcut("openSearch")).toEqual(custom);++ useShortcutStore.getState().setShortcut("openSearch", null);+ expect(getShortcut("openSearch")).toBeNull();+ });++ it("removes structurally equal overrides when restoring a default", () => {+ useShortcutStore.getState().setShortcut(+ "createIssue",+ createShortcutChord("I", { primary: true }),+ );+ useShortcutStore.getState().setShortcut(+ "createIssue",+ createShortcutChord("C"),+ );++ expect(useShortcutStore.getState().overrides.createIssue).toBeUndefined();+ });++ it("rejects unsafe programmatic overrides as a store invariant", () => {+ useShortcutStore.getState().setShortcut(+ "send",+ createShortcutChord("C"),+ );+ useShortcutStore.getState().setShortcut(+ "send",+ createShortcutChord("Enter", { shift: true }),+ );+ useShortcutStore.getState().setShortcut(+ "send",+ createShortcutChord("Enter", { primary: true, shift: true }),+ );+ expect(getShortcut("send")).toEqual(+ createShortcutChord("Enter", { primary: true }),+ );+ });++ it("drops persisted Send overrides outside Enter and Mod+Enter", () => {+ expect(+ sanitizeShortcutOverrides({+ send: createShortcutChord("Enter", { shift: true }),+ }),+ ).toEqual({});+ });++ it("finds conflicts against defaults and overrides", () => {+ expect(+ findShortcutConflict(+ "createIssue",+ createShortcutChord("K", { primary: true }),+ ),+ ).toBe("openSearch");++ const custom = createShortcutChord("1", { primary: true });+ useShortcutStore.getState().setShortcut("goInbox", custom);+ expect(findShortcutConflict("goChat", custom)).toBe("goInbox");+ });++ it("migrates v1 string overrides without losing disabled actions", () => {+ expect(+ migrateShortcutState({+ overrides: { openSearch: "Mod+Shift+J", createIssue: null },+ }, 1),+ ).toEqual({+ overrides: {+ openSearch: createShortcutChord("J", { primary: true, shift: true }),+ createIssue: null,+ },+ });+ });++ it("drops malformed current-version storage and unknown actions", () => {+ expect(+ sanitizeShortcutOverrides({+ openSearch: { key: "J", modifiers: { primary: true } },+ findInIssue: createShortcutChord("J"),+ send: createShortcutChord("Enter"),+ goInbox: null,+ goChat: createShortcutChord("Meta"),+ unknownAction: createShortcutChord("X"),+ }),+ ).toEqual({+ send: createShortcutChord("Enter"),+ goInbox: null,+ });++ expect(+ migrateShortcutState({ overrides: "corrupt" }, 2),+ ).toEqual({ overrides: {} });+ });++ it("falls back to defaults instead of disabling when legacy data is invalid", () => {+ expect(+ migrateShortcutState({+ overrides: {+ openSearch: "",+ createIssue: 42,+ goInbox: null,+ unknownAction: "Mod+X",+ },+ }, 1),+ ).toEqual({ overrides: { goInbox: null } });+ });+});diff --git a/packages/core/shortcuts/store.ts b/packages/core/shortcuts/store.tsnew file mode 100644index 0000000000..1cbf64f979--- /dev/null+++ b/packages/core/shortcuts/store.ts@@ -0,0 +1,182 @@+"use client";++import { create } from "zustand";+import { createJSONStorage, persist } from "zustand/middleware";+import { defaultStorage } from "../platform/storage";+import {+ SHORTCUT_ACTIONS,+ SHORTCUT_ACTION_BY_ID,+ isShortcutAllowedForAction,+ parseLegacyShortcut,+ shortcutChordEquals,+ type ShortcutActionId,+ type ShortcutChord,+} from "./definitions";++export type ShortcutOverrides = Partial<Record<ShortcutActionId, ShortcutChord | null>>;++const SHORTCUT_ACTION_IDS = new Set<string>(+ SHORTCUT_ACTIONS.map((action) => action.id),+);++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === "object" && !Array.isArray(value);+}++function sanitizeShortcutChord(value: unknown): ShortcutChord | null | undefined {+ if (value === null) return null;+ if (!isRecord(value) || typeof value.key !== "string" || value.key.length === 0) {+ return undefined;+ }+ const modifiers = value.modifiers;+ if (!isRecord(modifiers)) return undefined;+ const { primary, control, meta, alt, shift } = modifiers;+ if (+ typeof primary !== "boolean" ||+ typeof control !== "boolean" ||+ typeof meta !== "boolean" ||+ typeof alt !== "boolean" ||+ typeof shift !== "boolean"+ ) {+ return undefined;+ }+ return {+ key: value.key,+ modifiers: {+ primary,+ control,+ meta,+ alt,+ shift,+ },+ };+}++/** Drop unknown actions and malformed chords instead of letting storage crash matching/UI. */+export function sanitizeShortcutOverrides(value: unknown): ShortcutOverrides {+ if (!isRecord(value)) return {};+ const overrides: ShortcutOverrides = {};+ for (const [actionId, rawShortcut] of Object.entries(value)) {+ if (!SHORTCUT_ACTION_IDS.has(actionId)) continue;+ const shortcut = sanitizeShortcutChord(rawShortcut);+ if (+ shortcut !== undefined &&+ (shortcut === null || isShortcutAllowedForAction(+ actionId as ShortcutActionId,+ shortcut,+ ))+ ) {+ overrides[actionId as ShortcutActionId] = shortcut;+ }+ }+ return overrides;+}++interface ShortcutState {+ overrides: ShortcutOverrides;+ setShortcut: (actionId: ShortcutActionId, shortcut: ShortcutChord | null) => void;+ resetShortcut: (actionId: ShortcutActionId) => void;+ resetAll: () => void;+}++export function migrateShortcutState(+ persisted: unknown,+ version: number,+): { overrides: ShortcutOverrides } {+ if (version >= 2) {+ const current = isRecord(persisted) ? persisted : undefined;+ return { overrides: sanitizeShortcutOverrides(current?.overrides) };+ }+ const previous = isRecord(persisted) && isRecord(persisted.overrides)+ ? persisted.overrides+ : {};+ const overrides: ShortcutOverrides = {};+ for (const [actionId, value] of Object.entries(previous)) {+ if (!SHORTCUT_ACTION_IDS.has(actionId)) continue;+ if (value === null) {+ overrides[actionId as ShortcutActionId] = null;+ continue;+ }+ if (typeof value !== "string") continue;+ const shortcut = parseLegacyShortcut(value);+ // Invalid old data means "use the default", not "disable the action".+ if (shortcut) overrides[actionId as ShortcutActionId] = shortcut;+ }+ return { overrides: sanitizeShortcutOverrides(overrides) };+}++export const useShortcutStore = create<ShortcutState>()(+ persist(+ (set) => ({+ overrides: {},+ setShortcut: (actionId, shortcut) =>+ set((state) => {+ if (shortcut && !isShortcutAllowedForAction(actionId, shortcut)) {+ return state;+ }+ const next = { ...state.overrides };+ if (shortcutChordEquals(shortcut, SHORTCUT_ACTION_BY_ID[actionId].defaultShortcut)) {+ delete next[actionId];+ } else {+ next[actionId] = shortcut;+ }+ return { overrides: next };+ }),+ resetShortcut: (actionId) =>+ set((state) => {+ const next = { ...state.overrides };+ delete next[actionId];+ return { overrides: next };+ }),+ resetAll: () => set({ overrides: {} }),+ }),+ {+ name: "multica_keyboard_shortcuts",+ storage: createJSONStorage(() => defaultStorage),+ partialize: (state) => ({ overrides: state.overrides }),+ version: 2,+ migrate: migrateShortcutState,+ // Zustand only calls `migrate` when versions differ. Sanitize during+ // every hydration as well so corrupt current-version storage is safe.+ merge: (persisted, current) => {+ const stored = isRecord(persisted) ? persisted : undefined;+ return {+ ...current,+ overrides: sanitizeShortcutOverrides(stored?.overrides),+ };+ },+ },+ ),+);++export function resolveShortcut(+ overrides: ShortcutOverrides,+ actionId: ShortcutActionId,+): ShortcutChord | null {+ return Object.prototype.hasOwnProperty.call(overrides, actionId)+ ? overrides[actionId] ?? null+ : SHORTCUT_ACTION_BY_ID[actionId].defaultShortcut;+}++export function useShortcut(actionId: ShortcutActionId): ShortcutChord | null {+ return useShortcutStore((state) => resolveShortcut(state.overrides, actionId));+}++export function getShortcut(actionId: ShortcutActionId): ShortcutChord | null {+ return resolveShortcut(useShortcutStore.getState().overrides, actionId);+}++export function findShortcutConflict(+ actionId: ShortcutActionId,+ shortcut: ShortcutChord,+): ShortcutActionId | null {+ for (const action of SHORTCUT_ACTIONS) {+ if (+ action.id !== actionId &&+ shortcutChordEquals(getShortcut(action.id), shortcut)+ ) {+ return action.id;+ }+ }+ return null;+}diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsxindex 1c0c45a963..60aa35eb63 100644--- a/packages/views/chat/components/chat-input.tsx+++ b/packages/views/chat/components/chat-input.tsx@@ -13,7 +13,7 @@ import { SubmitButton } from "@multica/ui/components/common/submit-button";import { ChatAddMenu } from "./chat-add-menu";import { useChatStore, newSessionDraftKey } from "@multica/core/chat";import { createLogger } from "@multica/core/logger";-import { enterKey, formatShortcut, modKey } from "@multica/core/platform";+import { formatShortcut, useShortcut } from "@multica/core/shortcuts";import type { UploadResult } from "@multica/core/hooks/use-file-upload";import type { MentionItem } from "../../editor/extensions/mention-suggestion";import type { Attachment } from "@multica/core/types";@@ -108,6 +108,7 @@ export function ChatInput({focusRequest,}: ChatInputProps) {const { t } = useT("chat");+ const sendShortcut = useShortcut("send");const editorRef = useRef<ContentEditorRef>(null);const activeSessionId = useChatStore((s) => s.activeSessionId);const selectedAgentId = useChatStore((s) => s.selectedAgentId);@@ -406,11 +407,6 @@ export function ChatInput({// Chat is short-form — the floating formatting toolbar is// more distraction than feature here.showBubbleMenu={false}- // Chat intentionally leaves submitOnEnter at its default false:- // Mod+Enter submits, while bare Enter falls through to Tiptap's- // default behavior for lists, quotes, and paragraph breaks.- // Without this, Enter-as-send would steal the only key that- // continues a bullet list, leaving users stuck after one item./></div>{(uploadEnabled || leftAdornment) && (@@ -430,7 +426,9 @@ export function ChatInput({loading={isSubmitting}running={isRunning}onStop={onStop}- tooltip={`${t(($) => $.input.send_tooltip)} · ${formatShortcut(modKey, enterKey)}`}+ tooltip={sendShortcut+ ? `${t(($) => $.input.send_tooltip)} · ${formatShortcut(sendShortcut)}`+ : t(($) => $.input.send_tooltip)}stopTooltip={t(($) => $.input.stop_tooltip)}/></div>diff --git a/packages/views/common/shortcut-keycaps.test.tsx b/packages/views/common/shortcut-keycaps.test.tsxnew file mode 100644index 0000000000..9682876aed--- /dev/null+++ b/packages/views/common/shortcut-keycaps.test.tsx@@ -0,0 +1,56 @@+import { describe, expect, it } from "vitest";+import { render, screen } from "@testing-library/react";+import { createShortcutChord } from "@multica/core/shortcuts";+import { ShortcutKeycaps } from "./shortcut-keycaps";++describe("ShortcutKeycaps", () => {+ it("uses Lucide icons for macOS Command and Enter", () => {+ const { container } = render(+ <ShortcutKeycaps+ shortcut={createShortcutChord("Enter", { primary: true })}+ platform="macos"+ />,+ );++ expect(screen.getByRole("img", { name: "⌘↵" })).toBeInTheDocument();+ expect(container.querySelector(".lucide-command")).toBeInTheDocument();+ expect(container.querySelector(".lucide-corner-down-left")).toBeInTheDocument();+ expect(container.querySelector("[title='Enter']")?.textContent).toBe("");+ });++ it("keeps platform-specific modifier labels while iconizing function keys", () => {+ const { container } = render(+ <ShortcutKeycaps+ shortcut={createShortcutChord("Enter", { primary: true })}+ platform="windows"+ />,+ );++ expect(screen.getByRole("img", { name: "Ctrl+Enter" })).toBeInTheDocument();+ expect(container.querySelector("[title='Ctrl']")).toHaveTextContent("Ctrl");+ expect(container.querySelector(".lucide-corner-down-left")).toBeInTheDocument();+ expect(container.querySelector(".lucide-command")).not.toBeInTheDocument();+ });++ it("uses the canonical macOS Control glyph instead of an unrelated icon", () => {+ const { container } = render(+ <ShortcutKeycaps+ shortcut={createShortcutChord("F", { control: true })}+ platform="macos"+ />,+ );++ expect(screen.getByRole("img", { name: "⌃F" })).toBeInTheDocument();+ expect(container.querySelector("[title='Control']")).toHaveTextContent("⌃");+ expect(container.querySelector(".lucide-command")).not.toBeInTheDocument();+ });++ it("falls back to compact text when Lucide has no exact semantic icon", () => {+ const { container } = render(+ <ShortcutKeycaps shortcut={createShortcutChord("Escape")} platform="linux" />,+ );++ expect(screen.getByRole("img", { name: "Esc" })).toBeInTheDocument();+ expect(container.querySelector("[title='Esc']")).toHaveTextContent("Esc");+ });+});diff --git a/packages/views/common/shortcut-keycaps.tsx b/packages/views/common/shortcut-keycaps.tsxnew file mode 100644index 0000000000..c99780c0f5--- /dev/null+++ b/packages/views/common/shortcut-keycaps.tsx@@ -0,0 +1,126 @@+"use client";++import {+ ArrowBigUp,+ ArrowDown,+ ArrowLeft,+ ArrowRight,+ ArrowRightToLine,+ ArrowUp,+ Command,+ CornerDownLeft,+ Delete,+ Option,+ Space,+ type LucideIcon,+} from "lucide-react";+import {+ formatShortcut,+ getShortcutPlatform,+ type ShortcutChord,+ type ShortcutPlatform,+} from "@multica/core/shortcuts";+import { Kbd } from "@multica/ui/components/ui/kbd";+import { cn } from "@multica/ui/lib/utils";++type ShortcutToken = {+ id: string;+ label: string;+ text?: string;+ icon?: LucideIcon;+};++const KEY_TOKENS: Record<string, Omit<ShortcutToken, "id">> = {+ Enter: { label: "Enter", icon: CornerDownLeft },+ Backspace: { label: "Backspace", icon: Delete },+ Delete: { label: "Delete", icon: Delete },+ Up: { label: "Up Arrow", icon: ArrowUp },+ Down: { label: "Down Arrow", icon: ArrowDown },+ Left: { label: "Left Arrow", icon: ArrowLeft },+ Right: { label: "Right Arrow", icon: ArrowRight },+ Space: { label: "Space", icon: Space },+ Tab: { label: "Tab", icon: ArrowRightToLine },+ Escape: { label: "Esc" },+ Plus: { label: "+" },+ Minus: { label: "−" },+ Equals: { label: "=" },+ Underscore: { label: "_" },+};++function shortcutTokens(+ shortcut: ShortcutChord,+ platform: ShortcutPlatform,+): ShortcutToken[] {+ const { modifiers } = shortcut;+ const tokens: ShortcutToken[] = [];++ if (platform === "macos") {+ if (modifiers.primary) tokens.push({ id: "primary", label: "Command", icon: Command });+ if (modifiers.control) tokens.push({ id: "control", label: "Control", text: "⌃" });+ if (modifiers.alt) tokens.push({ id: "alt", label: "Option", icon: Option });+ if (modifiers.shift) tokens.push({ id: "shift", label: "Shift", icon: ArrowBigUp });+ if (modifiers.meta) tokens.push({ id: "meta", label: "Meta" });+ } else {+ if (modifiers.primary) tokens.push({ id: "primary", label: "Ctrl" });+ if (modifiers.control) tokens.push({ id: "control", label: "Control" });+ if (modifiers.meta) {+ tokens.push({+ id: "meta",+ label: platform === "windows" ? "Win" : "Super",+ });+ }+ if (modifiers.alt) tokens.push({ id: "alt", label: "Alt" });+ if (modifiers.shift) tokens.push({ id: "shift", label: "Shift", icon: ArrowBigUp });+ }++ const keyToken = KEY_TOKENS[shortcut.key] ?? { label: shortcut.key };+ tokens.push({ id: `key-${shortcut.key}`, ...keyToken });+ return tokens;+}++export function ShortcutKeycaps({+ shortcut,+ platform = getShortcutPlatform(),+ size = "sm",+ decorative = false,+ className,+ keyClassName,+}: {+ shortcut: ShortcutChord;+ platform?: ShortcutPlatform;+ size?: "sm" | "md";+ /** Hide a redundant hint when its parent already names the action. */+ decorative?: boolean;+ className?: string;+ keyClassName?: string;+}) {+ const accessibleLabel = formatShortcut(shortcut, platform);++ return (+ <span+ className={cn("inline-flex items-center gap-1", className)}+ role={decorative ? undefined : "img"}+ aria-label={decorative ? undefined : accessibleLabel}+ aria-hidden={decorative || undefined}+ data-slot="shortcut-keycaps"+ >+ {shortcutTokens(shortcut, platform).map(({ id, label, text, icon: Icon }) => (+ <Kbd+ key={id}+ aria-hidden="true"+ title={label}+ data-shortcut-key={id}+ className={cn(+ "border border-border/70 bg-muted/80 shadow-[0_1px_0_0_color-mix(in_oklab,var(--border)_70%,transparent)]",+ size === "md"+ ? "h-7 min-w-7 rounded-md px-1.5 text-xs [&_svg]:size-3.5"+ : "h-5 min-w-5 px-1 text-[10px] [&_svg]:size-3",+ keyClassName,+ )}+ >+ {Icon ? <Icon aria-hidden="true" strokeWidth={1.8} /> : (text ?? label)}+ </Kbd>+ ))}+ </span>+ );+}diff --git a/packages/views/editor/bubble-menu.tsx b/packages/views/editor/bubble-menu.tsxindex 69f40334c8..93b9a87b97 100644--- a/packages/views/editor/bubble-menu.tsx+++ b/packages/views/editor/bubble-menu.tsx@@ -35,7 +35,8 @@ import { NodeSelection } from "@tiptap/pm/state";import { toast } from "sonner";import { useCreateIssue } from "@multica/core/issues/mutations";import { useT } from "../i18n";-import { modKey } from "@multica/core/platform";+import { createShortcutChord, type ShortcutChord } from "@multica/core/shortcuts";+import { ShortcutKeycaps } from "../common/shortcut-keycaps";import { Toggle } from "@multica/ui/components/ui/toggle";import { Separator } from "@multica/ui/components/ui/separator";import {@@ -116,7 +117,7 @@ function MarkButton({mark: InlineMark;icon: React.ComponentType<{ className?: string }>;label: string;- shortcut: string;+ shortcut: ShortcutChord;isActive: boolean;}) {return (@@ -135,7 +136,7 @@ function MarkButton({</TooltipTrigger><TooltipContent side="top" sideOffset={8}>{label}- <span className="ml-1.5 text-muted-foreground">{shortcut}</span>+ <ShortcutKeycaps shortcut={shortcut} className="ml-1.5" /></TooltipContent></Tooltip>);@@ -604,11 +605,11 @@ function EditorBubbleMenu({) : (<TooltipProvider delay={300}><div className="bubble-menu">- <MarkButton editor={editor} mark="bold" icon={Bold} label={t(($) => $.bubble_menu.bold)} shortcut={`${modKey}+B`} isActive={fmt.bold} />- <MarkButton editor={editor} mark="italic" icon={Italic} label={t(($) => $.bubble_menu.italic)} shortcut={`${modKey}+I`} isActive={fmt.italic} />- <MarkButton editor={editor} mark="strike" icon={Strikethrough} label={t(($) => $.bubble_menu.strikethrough)} shortcut={`${modKey}+Shift+S`} isActive={fmt.strike} />- <MarkButton editor={editor} mark="code" icon={Code} label={t(($) => $.bubble_menu.code)} shortcut={`${modKey}+E`} isActive={fmt.code} />- <MarkButton editor={editor} mark="highlight" icon={Highlighter} label={t(($) => $.bubble_menu.highlight)} shortcut={`${modKey}+Shift+H`} isActive={fmt.highlight} />+ <MarkButton editor={editor} mark="bold" icon={Bold} label={t(($) => $.bubble_menu.bold)} shortcut={createShortcutChord("B", { primary: true })} isActive={fmt.bold} />+ <MarkButton editor={editor} mark="italic" icon={Italic} label={t(($) => $.bubble_menu.italic)} shortcut={createShortcutChord("I", { primary: true })} isActive={fmt.italic} />+ <MarkButton editor={editor} mark="strike" icon={Strikethrough} label={t(($) => $.bubble_menu.strikethrough)} shortcut={createShortcutChord("S", { primary: true, shift: true })} isActive={fmt.strike} />+ <MarkButton editor={editor} mark="code" icon={Code} label={t(($) => $.bubble_menu.code)} shortcut={createShortcutChord("E", { primary: true })} isActive={fmt.code} />+ <MarkButton editor={editor} mark="highlight" icon={Highlighter} label={t(($) => $.bubble_menu.highlight)} shortcut={createShortcutChord("H", { primary: true, shift: true })} isActive={fmt.highlight} /><Separator orientation="vertical" className="mx-0.5 h-5" /><Tooltip><TooltipTrigger render={diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsxindex 11390cf063..1d834cc4f7 100644--- a/packages/views/editor/content-editor.tsx+++ b/packages/views/editor/content-editor.tsx@@ -120,8 +120,6 @@ interface ContentEditorProps {onUploadFile?: (file: File) => Promise<UploadResult | null>;/** Show the floating formatting toolbar on text selection. Defaults true. */showBubbleMenu?: boolean;- /** When true, bare Enter submits (chat-style). Mod-Enter always submits. */- submitOnEnter?: boolean;/*** ID of the issue this editor belongs to. When set, the bubble menu exposes* a "Create sub-issue from selection" action that parents the new issue@@ -198,7 +196,6 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(onBlur,onUploadFile,showBubbleMenu = true,- submitOnEnter = false,currentIssueId,disableMentions = false,mentionMode = "default",@@ -391,7 +388,6 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(queryClient,onSubmitRef,onUploadFileRef,- submitOnEnter,disableMentions,mentionMode,getMentionContextItems: () => mentionContextItemsRef.current,diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.tsindex cd4c5d4556..912e6bd93f 100644--- a/packages/views/editor/extensions/index.ts+++ b/packages/views/editor/extensions/index.ts@@ -49,8 +49,8 @@ import { CodeBlockView } from "./code-block-view";import { PatchedListItem, PatchedTaskItem } from "./list-item";import { createMarkdownPasteExtension } from "./markdown-paste";import { createMarkdownCopyExtension } from "./markdown-copy";-import { createSubmitExtension } from "./submit-shortcut";import { createBlurShortcutExtension } from "./blur-shortcut";+import { createSubmitShortcutExtension } from "./submit-shortcut";import { createFileUploadExtension } from "./file-upload";import { FileCardExtension } from "./file-card";import { ImageView } from "./image-view";@@ -134,8 +134,6 @@ export interface EditorExtensionsOptions {onUploadFileRef?: RefObject<((file: File) => Promise<UploadResult | null>) | undefined>;- /** When true, bare Enter also submits (chat-style). Default false. */- submitOnEnter?: boolean;/*** When true, the `@` suggestion picker is not attached. The mention node* type is still registered in the schema so any mention pasted in from@@ -250,15 +248,12 @@ export function createEditorExtensions(Typography,Placeholder.configure({ placeholder: placeholderText }),createMarkdownPasteExtension(),- createSubmitExtension(- () => {- const fn = options.onSubmitRef?.current;- if (!fn) return false; // no submit wired — let default Enter insert newline- fn();- return true;- },- { submitOnEnter: options.submitOnEnter ?? false },- ),+ createSubmitShortcutExtension(() => {+ const fn = options.onSubmitRef?.current;+ if (!fn) return false;+ fn();+ return true;+ }),createBlurShortcutExtension(),createFileUploadExtension(options.onUploadFileRef!),];diff --git a/packages/views/editor/extensions/submit-shortcut.test.ts b/packages/views/editor/extensions/submit-shortcut.test.tsindex 65c4dafb30..eb7621ee28 100644--- a/packages/views/editor/extensions/submit-shortcut.test.ts+++ b/packages/views/editor/extensions/submit-shortcut.test.ts@@ -1,104 +1,238 @@-import { describe, it, expect, vi } from "vitest";-import { getExtensionField } from "@tiptap/core";-import type { Editor } from "@tiptap/core";-import { createSubmitExtension } from "./submit-shortcut";--function getShortcuts(- ext: ReturnType<typeof createSubmitExtension>,- editor: Partial<Editor>,-): Record<string, () => boolean> {- const fn = getExtensionField<- () => Record<string, () => boolean>- >(ext, "addKeyboardShortcuts", {- name: "submitShortcut",- options: {},- storage: {},- editor: editor as Editor,- type: null,+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { Editor, Extension, type AnyExtension, type Content } from "@tiptap/core";+import { Plugin } from "@tiptap/pm/state";+import StarterKit from "@tiptap/starter-kit";+import { Markdown } from "@tiptap/markdown";+import {+ createShortcutChord,+ configureShortcutPlatform,+ useShortcutStore,+} from "@multica/core/shortcuts";+import { PatchedListItem } from "./list-item";+import {+ createSubmitShortcutExtension,+ shouldHandleSubmitShortcut,+ shouldReplayNativeEnter,+} from "./submit-shortcut";++function event(+ key: string,+ modifiers: Partial<Pick<KeyboardEvent, "metaKey" | "ctrlKey" | "altKey" | "shiftKey" | "repeat">> = {},+): KeyboardEvent {+ return new KeyboardEvent("keydown", {+ key,+ bubbles: true,+ cancelable: true,+ ...modifiers,});- return fn?.() ?? {};}-describe("createSubmitExtension", () => {- const baseEditor = {- view: { composing: false } as unknown as Editor["view"],- isActive: () => false,- } as Partial<Editor>;-- it("Mod-Enter submits when no composition is open", () => {- const onSubmit = vi.fn(() => true);- const shortcuts = getShortcuts(- createSubmitExtension(onSubmit, { submitOnEnter: false }),- baseEditor,- );+function press(editor: Editor, keyboardEvent: KeyboardEvent): boolean {+ let handled = false;+ editor.view.someProp("handleKeyDown", (handler) => {+ if (!handler(editor.view, keyboardEvent)) return false;+ handled = true;+ return true;+ });+ return handled;+}- expect(shortcuts["Mod-Enter"]).toBeDefined();- expect(shortcuts["Mod-Enter"]!()).toBe(true);- expect(onSubmit).toHaveBeenCalledTimes(1);+function makeEditor(+ content: Content,+ onSubmit: () => void,+ extraExtensions: AnyExtension[] = [],+) {+ return new Editor({+ element: document.createElement("div"),+ content,+ extensions: [+ StarterKit.configure({ listItem: false }),+ PatchedListItem,+ Markdown,+ createSubmitShortcutExtension(() => {+ onSubmit();+ return true;+ }),+ ...extraExtensions,+ ],});+}- it("Mod-Enter is suppressed during IME composition", () => {- const onSubmit = vi.fn(() => true);- const shortcuts = getShortcuts(- createSubmitExtension(onSubmit, { submitOnEnter: false }),- {- view: { composing: true } as unknown as Editor["view"],- isActive: () => false,- },- );+const editors: Editor[] = [];++beforeEach(() => {+ configureShortcutPlatform("windows");+});++afterEach(() => {+ editors.splice(0).forEach((editor) => editor.destroy());+ useShortcutStore.getState().resetAll();+ configureShortcutPlatform(null);+});- expect(shortcuts["Mod-Enter"]!()).toBe(false);- expect(onSubmit).not.toHaveBeenCalled();+describe("submit shortcut matching", () => {+ it("handles the configured shortcut exactly", () => {+ const shortcut = createShortcutChord("Enter", { primary: true });+ expect(+ shouldHandleSubmitShortcut(event("Enter", { ctrlKey: true }), {+ configuredShortcut: shortcut,+ composing: false,+ }),+ ).toBe(true);+ expect(+ shouldHandleSubmitShortcut(+ event("Enter", { ctrlKey: true, shiftKey: true }),+ { configuredShortcut: shortcut, composing: false },+ ),+ ).toBe(false);});- it("bare Enter is not bound when submitOnEnter is false", () => {- const onSubmit = vi.fn(() => true);- const shortcuts = getShortcuts(- createSubmitExtension(onSubmit, { submitOnEnter: false }),- baseEditor,- );+ it("does not submit while an IME composition is active", () => {+ expect(+ shouldHandleSubmitShortcut(event("Enter"), {+ configuredShortcut: createShortcutChord("Enter"),+ composing: true,+ }),+ ).toBe(false);+ });++ it("does not submit on Safari's IME commit event or a repeated keydown", () => {+ const safariImeCommit = event("Enter", { metaKey: true });+ Object.defineProperty(safariImeCommit, "keyCode", { value: 229 });+ expect(+ shouldHandleSubmitShortcut(safariImeCommit, {+ configuredShortcut: createShortcutChord("Enter", { primary: true }),+ composing: false,+ }),+ ).toBe(false);- expect(shortcuts.Enter).toBeUndefined();- expect(onSubmit).not.toHaveBeenCalled();+ expect(+ shouldHandleSubmitShortcut(+ event("Enter", { ctrlKey: true, repeat: true }),+ {+ configuredShortcut: createShortcutChord("Enter", { primary: true }),+ composing: false,+ },+ ),+ ).toBe(false);});- it("bare Enter submits when submitOnEnter is true", () => {- const onSubmit = vi.fn(() => true);- const shortcuts = getShortcuts(- createSubmitExtension(onSubmit, { submitOnEnter: true }),- baseEditor,+ it("only remaps Shift+Enter when plain Enter is Send", () => {+ expect(+ shouldReplayNativeEnter(+ event("Enter", { shiftKey: true }),+ createShortcutChord("Enter"),+ false,+ ),+ ).toBe(true);+ expect(+ shouldReplayNativeEnter(+ event("Enter", { shiftKey: true }),+ createShortcutChord("Enter", { primary: true }),+ false,+ ),+ ).toBe(false);+ });+});++describe("Send = Enter editor behavior", () => {+ it("lets an open high-priority suggestion picker consume Enter first", () => {+ useShortcutStore.getState().setShortcut("send", createShortcutChord("Enter"));+ let submitCount = 0;+ let acceptCount = 0;+ const picker = Extension.create({+ name: "testSuggestionPicker",+ priority: 101,+ addProseMirrorPlugins() {+ return [new Plugin({+ props: {+ handleKeyDown: (_view, keyboardEvent) => {+ if (keyboardEvent.key !== "Enter") return false;+ acceptCount += 1;+ return true;+ },+ },+ })];+ },+ });+ const editor = makeEditor(+ "@al",+ () => { submitCount += 1; },+ [picker],);+ editors.push(editor);+ editor.commands.focus("end");++ expect(press(editor, event("Enter"))).toBe(true);+ expect(acceptCount).toBe(1);+ expect(submitCount).toBe(0);+ });++ it("submits on Enter and turns Shift+Enter into the old paragraph Enter", () => {+ useShortcutStore.getState().setShortcut("send", createShortcutChord("Enter"));+ let submitCount = 0;+ const editor = makeEditor("hello", () => { submitCount += 1; });+ editors.push(editor);+ editor.commands.focus("end");++ expect(press(editor, event("Enter"))).toBe(true);+ expect(submitCount).toBe(1);+ expect(editor.state.doc.childCount).toBe(1);- expect(shortcuts.Enter).toBeDefined();- expect(shortcuts.Enter!()).toBe(true);- expect(onSubmit).toHaveBeenCalledTimes(1);+ expect(press(editor, event("Enter", { shiftKey: true }))).toBe(true);+ expect(submitCount).toBe(1);+ expect(editor.state.doc.childCount).toBe(2);+ let hasHardBreak = false;+ editor.state.doc.descendants((node) => {+ if (node.type.name === "hardBreak") hasHardBreak = true;+ });+ expect(hasHardBreak).toBe(false);});- it("Enter is suppressed during IME composition", () => {- const onSubmit = vi.fn(() => true);- const shortcuts = getShortcuts(- createSubmitExtension(onSubmit, { submitOnEnter: true }),+ it("continues list items with Shift+Enter", () => {+ useShortcutStore.getState().setShortcut("send", createShortcutChord("Enter"));+ let submitCount = 0;+ const editor = makeEditor({- view: { composing: true } as unknown as Editor["view"],- isActive: () => false,+ type: "doc",+ content: [{+ type: "bulletList",+ content: [{+ type: "listItem",+ content: [{ type: "paragraph", content: [{ type: "text", text: "one" }] }],+ }],+ }],},+ () => { submitCount += 1; },);+ editors.push(editor);+ editor.commands.focus("end");- expect(shortcuts.Enter!()).toBe(false);- expect(onSubmit).not.toHaveBeenCalled();+ expect(press(editor, event("Enter", { shiftKey: true }))).toBe(true);+ expect(submitCount).toBe(0);+ expect(editor.state.doc.firstChild?.childCount).toBe(2);});- it("Enter is suppressed inside a code block", () => {- const onSubmit = vi.fn(() => true);- const shortcuts = getShortcuts(- createSubmitExtension(onSubmit, { submitOnEnter: true }),+ it("inserts the original code-block newline with Shift+Enter", () => {+ useShortcutStore.getState().setShortcut("send", createShortcutChord("Enter"));+ let submitCount = 0;+ const editor = makeEditor({- view: { composing: false } as unknown as Editor["view"],- isActive: (name: string) => name === "codeBlock",+ type: "doc",+ content: [{+ type: "codeBlock",+ attrs: { language: null },+ content: [{ type: "text", text: "line" }],+ }],},+ () => { submitCount += 1; },);+ editors.push(editor);+ editor.commands.focus("end");- expect(shortcuts.Enter!()).toBe(false);- expect(onSubmit).not.toHaveBeenCalled();+ expect(press(editor, event("Enter"))).toBe(true);+ expect(submitCount).toBe(1);+ expect(press(editor, event("Enter", { shiftKey: true }))).toBe(true);+ expect(editor.state.doc.firstChild?.textContent).toBe("line\n");});});diff --git a/packages/views/editor/extensions/submit-shortcut.ts b/packages/views/editor/extensions/submit-shortcut.tsindex 94654e2f98..1ab8b6cd3a 100644--- a/packages/views/editor/extensions/submit-shortcut.ts+++ b/packages/views/editor/extensions/submit-shortcut.ts@@ -1,44 +1,98 @@import { Extension } from "@tiptap/core";+import { Plugin } from "@tiptap/pm/state";+import {+ getShortcut,+ isPlainShortcut,+ shortcutMatchesEvent,+ type ShortcutChord,+} from "@multica/core/shortcuts";+import { isImeComposing } from "@multica/core/utils";++export function shouldHandleSubmitShortcut(+ event: KeyboardEvent,+ options: {+ configuredShortcut: ShortcutChord | null;+ composing: boolean;+ },+): boolean {+ return (+ !event.repeat &&+ !options.composing &&+ !isImeComposing(event) &&+ shortcutMatchesEvent(options.configuredShortcut, event)+ );+}++/**+ * When plain Enter becomes Send, Shift+Enter must inherit the old Enter+ * behavior instead of Tiptap's normal hard-break behavior. Replaying the+ * editor's Enter keymap preserves paragraphs, patched list exit/continuation,+ * code-block newlines, and open suggestion pickers.+ */+export function shouldReplayNativeEnter(+ event: KeyboardEvent,+ configuredShortcut: ShortcutChord | null,+ composing: boolean,+): boolean {+ return (+ !composing &&+ !isImeComposing(event) &&+ isPlainShortcut(configuredShortcut, "Enter") &&+ event.key === "Enter" &&+ event.shiftKey &&+ !event.metaKey &&+ !event.ctrlKey &&+ !event.altKey+ );+}/**- * `onSubmit` must return true when it actually handled the event and false- * when there's no submit handler wired up. That lets us fall through to the- * default Enter behaviour — inserting a newline — when appropriate.- *- * `submitOnEnter` — when true, bare Enter also submits (chat-style). When- * false, only Mod-Enter submits and bare Enter keeps its default (newline).+ * Tiered-priority dynamic key handler. Suggestion and slash-command plugins+ * get first refusal, while submit still runs before the base editor keymap.*/-export function createSubmitExtension(+export function createSubmitShortcutExtension(onSubmit: () => boolean,- { submitOnEnter }: { submitOnEnter: boolean },) {return Extension.create({name: "submitShortcut",- addKeyboardShortcuts() {- const shortcuts: Record<string, () => boolean> = {- "Mod-Enter": () => {- // IME guard — same as Enter below. While a composition is open the- // composed text is not in the document yet, so submitting here- // would send the doc WITHOUT what the user just typed (e.g. paste- // a screenshot, type a pinyin sentence, hit ⌘↵ before the buffer- // commits — the submission carries only the screenshot).- if (this.editor.view.composing) return false;- return onSubmit();- },- };- if (submitOnEnter) {- shortcuts.Enter = () => {- const editor = this.editor;- // IME guard — never submit while composing a multi-key input- // (Chinese pinyin, Japanese kana, etc). `view.composing` is set- // by ProseMirror between compositionstart and compositionend.- if (editor.view.composing) return false;- // Let Enter insert a newline inside a code block.- if (editor.isActive("codeBlock")) return false;- return onSubmit();- };- }- return shortcuts;+ // Mention/slash extensions use 101, so open pickers get first refusal.+ // Default editor keymaps use 100; reverse extension order places this+ // late-added handler ahead of them while keeping picker priority intact.+ priority: 100,+ addProseMirrorPlugins() {+ const editor = this.editor;+ let replayingEnter = false;+ return [+ new Plugin({+ props: {+ handleKeyDown(view, event) {+ if (replayingEnter) return false;+ const shortcut = getShortcut("send");++ if (+ shouldReplayNativeEnter(event, shortcut, view.composing)+ ) {+ replayingEnter = true;+ try {+ return editor.commands.keyboardShortcut("Enter");+ } finally {+ replayingEnter = false;+ }+ }++ if (+ !shouldHandleSubmitShortcut(event, {+ configuredShortcut: shortcut,+ composing: view.composing,+ })+ ) {+ return false;+ }+ return onSubmit();+ },+ },+ }),+ ];},});}diff --git a/packages/views/issues/components/comment-input.tsx b/packages/views/issues/components/comment-input.tsxindex bd67649484..aa6bb0a117 100644--- a/packages/views/issues/components/comment-input.tsx+++ b/packages/views/issues/components/comment-input.tsx@@ -9,7 +9,7 @@ import { useFileUpload } from "@multica/core/hooks/use-file-upload";import { api } from "@multica/core/api";import type { Attachment } from "@multica/core/types";import { contentReferencesAttachment } from "@multica/core/types";-import { enterKey, formatShortcut, modKey } from "@multica/core/platform";+import { formatShortcut, useShortcut } from "@multica/core/shortcuts";import { useCommentDraftStore } from "@multica/core/issues/stores";import { useT } from "../../i18n";import { CommentTriggerChips } from "./comment-trigger-chips";@@ -25,6 +25,7 @@ interface CommentInputProps {function CommentInput({ issueId, onSubmit }: CommentInputProps) {const { t } = useT("issues");+ const sendShortcut = useShortcut("send");const editorRef = useRef<ContentEditorRef>(null);// Read the persisted draft once on mount. ContentEditor only honors// `defaultValue` at mount time, so this snapshot drives both the editor's@@ -188,7 +189,9 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {onClick={handleSubmit}disabled={isEmpty}loading={submitting}- tooltip={`${t(($) => $.comment.send_tooltip)} · ${formatShortcut(modKey, enterKey)}`}+ tooltip={sendShortcut+ ? `${t(($) => $.comment.send_tooltip)} · ${formatShortcut(sendShortcut)}`+ : t(($) => $.comment.send_tooltip)}/></div>{isDragOver && <FileDropOverlay />}diff --git a/packages/views/issues/components/reply-input.tsx b/packages/views/issues/components/reply-input.tsxindex 954b3b3841..06ae790ac9 100644--- a/packages/views/issues/components/reply-input.tsx+++ b/packages/views/issues/components/reply-input.tsx@@ -9,7 +9,7 @@ import { useFileUpload } from "@multica/core/hooks/use-file-upload";import { api } from "@multica/core/api";import type { Attachment } from "@multica/core/types";import { contentReferencesAttachment } from "@multica/core/types";-import { enterKey, formatShortcut, modKey } from "@multica/core/platform";+import { formatShortcut, useShortcut } from "@multica/core/shortcuts";import { useCommentDraftStore, type CommentDraftKey } from "@multica/core/issues/stores";import { cn } from "@multica/ui/lib/utils";import type { AvatarSize } from "@multica/ui/lib/avatar-size";@@ -52,6 +52,7 @@ function ReplyInput({draftKey,}: ReplyInputProps) {const { t } = useT("issues");+ const sendShortcut = useShortcut("send");const placeholderText = placeholder ?? t(($) => $.reply.placeholder);const editorRef = useRef<ContentEditorRef>(null);// If a draft key is provided, hydrate from store on mount (defaultValue is@@ -216,7 +217,9 @@ function ReplyInput({onClick={handleSubmit}disabled={isEmpty}loading={submitting}- tooltip={`${t(($) => $.comment.send_tooltip)} · ${formatShortcut(modKey, enterKey)}`}+ tooltip={sendShortcut+ ? `${t(($) => $.comment.send_tooltip)} · ${formatShortcut(sendShortcut)}`+ : t(($) => $.comment.send_tooltip)}/></div>{isDragOver && <FileDropOverlay />}diff --git a/packages/views/issues/hooks/use-in-page-find.ts b/packages/views/issues/hooks/use-in-page-find.tsindex 7b5154a1db..31d0f48727 100644--- a/packages/views/issues/hooks/use-in-page-find.ts+++ b/packages/views/issues/hooks/use-in-page-find.ts@@ -1,6 +1,8 @@"use client";import { useCallback, useEffect, useRef, useState } from "react";+import { getShortcut, shortcutMatchesEvent } from "@multica/core/shortcuts";+import { isImeComposing } from "@multica/core/utils";// ---------------------------------------------------------------------------// In-page find (Cmd/Ctrl+F) for the issue detail page.@@ -271,8 +273,8 @@ export function useInPageFind(options: {useEffect(() => {if (!enabled) return;const onKeyDown = (e: KeyboardEvent) => {- if (!(e.metaKey || e.ctrlKey) || e.altKey) return;- if (e.key !== "f" && e.key !== "F") return;+ if (e.defaultPrevented || e.repeat || isImeComposing(e)) return;+ if (!shortcutMatchesEvent(getShortcut("findInIssue"), e)) return;if (!isElementVisible(containerRef.current)) return;e.preventDefault();setOpen(true);diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsxindex c8912a5aa8..285720c2dc 100644--- a/packages/views/layout/app-sidebar.tsx+++ b/packages/views/layout/app-sidebar.tsx@@ -86,6 +86,10 @@ import type { PinnedItem } from "@multica/core/types";import { useLogout } from "../auth";import { ProjectIcon } from "../projects/components/project-icon";import { useT } from "../i18n";+import {+ useShortcut,+} from "@multica/core/shortcuts";+import { ShortcutKeycaps } from "../common/shortcut-keycaps";// Top-level nav items stay active when the user is on a child route// (e.g. "Projects" stays lit on /:slug/projects/:id). Pinned items keep@@ -490,33 +494,7 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }},});- // Global "C" shortcut: opens whichever create mode the user landed on last- // (agent vs manual), persisted in useCreateModeStore. The mode switch lives- // inside both modal footers so users can flip without remembering which- // shortcut goes where — `c` always means "open the create flow I prefer".- useEffect(() => {- const handleKeyDown = (e: KeyboardEvent) => {- if (e.key !== "c" && e.key !== "C") return;- if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return;- const tag = (e.target as HTMLElement)?.tagName;- const isEditable =- tag === "INPUT" ||- tag === "TEXTAREA" ||- tag === "SELECT" ||- (e.target as HTMLElement)?.isContentEditable;- if (isEditable) return;- if (useModalStore.getState().modal) return;- e.preventDefault();- // Auto-fill project when on a project detail page. The manual form- // consumes `project_id`; quick-create also honours it as a seed for- // its project picker, so passing it through is safe for both modes.- const projectMatch = pathname.match(/^\/[^/]+\/projects\/([^/]+)$/);- const data = projectMatch ? { project_id: projectMatch[1] } : undefined;- openCreateIssueWithPreference(data);- };- document.addEventListener("keydown", handleKeyDown);- return () => document.removeEventListener("keydown", handleKeyDown);- }, [pathname]);+ const createIssueShortcut = useShortcut("createIssue");return (<Sidebar variant="inset">@@ -671,7 +649,9 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }<DraftDot /></span><span>{t(($) => $.sidebar.new_issue)}</span>- <kbd className="pointer-events-none ml-auto inline-flex h-5 select-none items-center gap-0.5 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground">{t(($) => $.sidebar.new_issue_shortcut)}</kbd>+ {createIssueShortcut ? (+ <ShortcutKeycaps shortcut={createIssueShortcut} decorative className="pointer-events-none ml-auto" />+ ) : null}</SidebarMenuButton></SidebarMenuItem></SidebarMenu>diff --git a/packages/views/layout/dashboard-layout.tsx b/packages/views/layout/dashboard-layout.tsxindex 1a362461b7..d7adbb47e6 100644--- a/packages/views/layout/dashboard-layout.tsx+++ b/packages/views/layout/dashboard-layout.tsx@@ -8,6 +8,7 @@ import { AppSidebar } from "./app-sidebar";import { DashboardGuard } from "./dashboard-guard";import { NavigationProgress } from "./navigation-progress";import { WorkspacePresencePrefetch } from "./workspace-presence-prefetch";+import { GlobalShortcuts } from "./global-shortcuts";interface DashboardLayoutProps {children: ReactNode;@@ -34,6 +35,7 @@ export function DashboardLayout({}><SidebarProvider className="h-svh bg-app-shell">+ <GlobalShortcuts /><WorkspacePresencePrefetch /><AppSidebar searchSlot={searchSlot} /><SidebarInset className="relative overflow-hidden">diff --git a/packages/views/layout/global-shortcuts.test.ts b/packages/views/layout/global-shortcuts.test.tsnew file mode 100644index 0000000000..262931c535--- /dev/null+++ b/packages/views/layout/global-shortcuts.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from "vitest";+import { shouldIgnoreGlobalShortcutEvent } from "./global-shortcuts";++describe("global shortcut event guard", () => {+ it("respects focused controls that already consumed the shortcut", () => {+ const event = new KeyboardEvent("keydown", {+ key: "k",+ metaKey: true,+ cancelable: true,+ });+ event.preventDefault();+ expect(shouldIgnoreGlobalShortcutEvent(event)).toBe(true);+ });++ it("ignores repeats and both standard and Safari IME composition events", () => {+ expect(+ shouldIgnoreGlobalShortcutEvent(+ new KeyboardEvent("keydown", { key: "k", repeat: true }),+ ),+ ).toBe(true);+ expect(+ shouldIgnoreGlobalShortcutEvent(+ new KeyboardEvent("keydown", { key: "k", isComposing: true }),+ ),+ ).toBe(true);++ const safariIme = new KeyboardEvent("keydown", { key: "k" });+ Object.defineProperty(safariIme, "keyCode", { value: 229 });+ expect(shouldIgnoreGlobalShortcutEvent(safariIme)).toBe(true);+ });++ it("allows a fresh unhandled keydown through", () => {+ expect(+ shouldIgnoreGlobalShortcutEvent(+ new KeyboardEvent("keydown", { key: "k", metaKey: true }),+ ),+ ).toBe(false);+ });+});diff --git a/packages/views/layout/global-shortcuts.tsx b/packages/views/layout/global-shortcuts.tsxnew file mode 100644index 0000000000..6b79358866--- /dev/null+++ b/packages/views/layout/global-shortcuts.tsx@@ -0,0 +1,115 @@+"use client";++import { useEffect } from "react";+import { useSidebar } from "@multica/ui/components/ui/sidebar";+import {+ getShortcut,+ isEditableShortcutTarget,+ shortcutMatchesEvent,+ SHORTCUT_ACTION_BY_ID,+ useShortcutStore,+ type ShortcutActionId,+} from "@multica/core/shortcuts";+import { openCreateIssueWithPreference } from "@multica/core/issues/stores";+import { useModalStore } from "@multica/core/modals";+import { useWorkspacePaths } from "@multica/core/paths";+import { isImeComposing } from "@multica/core/utils";+import { useNavigation } from "../navigation";+import { useSearchStore } from "../search/search-store";++const GLOBAL_ACTIONS: readonly ShortcutActionId[] = [+ "openSearch",+ "createIssue",+ "toggleSidebar",+ "goInbox",+ "goChat",+ "goMyIssues",+ "goIssues",+ "goProjects",+ "goAutopilots",+ "goAgents",+ "goSquads",+ "goUsage",+ "goRuntimes",+ "goSkills",+ "goSettings",+];++export function shouldIgnoreGlobalShortcutEvent(event: KeyboardEvent): boolean {+ return event.defaultPrevented || event.repeat || isImeComposing(event);+}++/** Executes configurable product-level shortcuts inside the dashboard shell. */+export function GlobalShortcuts() {+ const { toggleSidebar } = useSidebar();+ const navigation = useNavigation();+ const workspacePaths = useWorkspacePaths();++ // Subscribe so changing a binding in Settings immediately refreshes the+ // listener closure; getShortcut remains useful to non-React call sites.+ const overrides = useShortcutStore((state) => state.overrides);++ useEffect(() => {+ const destinations: Partial<Record<ShortcutActionId, string>> = {+ goInbox: workspacePaths.inbox(),+ goChat: workspacePaths.chat(),+ goMyIssues: workspacePaths.myIssues(),+ goIssues: workspacePaths.issues(),+ goProjects: workspacePaths.projects(),+ goAutopilots: workspacePaths.autopilots(),+ goAgents: workspacePaths.agents(),+ goSquads: workspacePaths.squads(),+ goUsage: workspacePaths.usage(),+ goRuntimes: workspacePaths.runtimes(),+ goSkills: workspacePaths.skills(),+ goSettings: workspacePaths.settings(),+ };++ const handleKeyDown = (event: KeyboardEvent) => {+ // Component/editor handlers run before this document-level listener.+ // Respect their preventDefault instead of double-triggering a product+ // action after the focused control already consumed the same chord.+ if (shouldIgnoreGlobalShortcutEvent(event)) return;++ const actionId = GLOBAL_ACTIONS.find((candidate) => {+ const action = SHORTCUT_ACTION_BY_ID[candidate];+ if (!action.allowInEditable && isEditableShortcutTarget(event.target)) {+ return false;+ }+ return shortcutMatchesEvent(getShortcut(candidate), event);+ });+ if (!actionId) return;++ event.preventDefault();+ if (actionId === "openSearch") {+ useSearchStore.getState().toggle();+ return;+ }+ if (actionId === "toggleSidebar") {+ toggleSidebar();+ return;+ }+ if (actionId === "createIssue") {+ if (useModalStore.getState().modal) return;+ const projectMatch = navigation.pathname.match(+ /^\/[^/]+\/projects\/([^/]+)$/,+ );+ const data = projectMatch+ ? { project_id: projectMatch[1] }+ : undefined;+ openCreateIssueWithPreference(data);+ return;+ }++ const destination = destinations[actionId];+ if (destination && destination !== navigation.pathname) {+ navigation.push(destination);+ }+ };++ document.addEventListener("keydown", handleKeyDown);+ return () => document.removeEventListener("keydown", handleKeyDown);+ }, [navigation, overrides, toggleSidebar, workspacePaths]);++ return null;+}diff --git a/packages/views/layout/index.ts b/packages/views/layout/index.tsindex 57c5a490c3..d667266029 100644--- a/packages/views/layout/index.ts+++ b/packages/views/layout/index.ts@@ -9,3 +9,4 @@ export { DashboardLayout } from "./dashboard-layout";export { useDashboardGuard } from "./use-dashboard-guard";export { WorkspaceLoader } from "./workspace-loader";export { WorkspacePresencePrefetch } from "./workspace-presence-prefetch";+export { GlobalShortcuts } from "./global-shortcuts";diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 95ada91ca4..78bfcac805 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -28,6 +28,58 @@"sync_failed": "Failed to save your timezone preference."}},+ "shortcuts": {+ "title": "Keyboard Shortcuts",+ "description": "Customize product actions on this device. Click a shortcut, then press the new key combination.",+ "search_placeholder": "Search actions...",+ "reset_all": "Restore defaults",+ "reset": "Reset",+ "disable": "Disable",+ "reset_action": "Reset {{action}}",+ "disable_action": "Disable {{action}} shortcut",+ "record_aria": "Change shortcut for {{action}}",+ "recording": "Press keys",+ "record_hint": "Esc cancels · Delete clears",+ "unassigned": "Unassigned",+ "no_results": "No matching shortcut actions.",+ "conflict_error": "Already used by {{action}}.",+ "reserved_error": "Reserved by the browser or desktop window.",+ "send_error": "Send can only use Enter or Mod+Enter.",+ "unsafe_error": "This key would interfere with typing or basic keyboard navigation.",+ "send_enter_hint": "Shift+Enter inserts a paragraph, continues a list, or adds a code-block newline.",+ "categories": {+ "general": "General",+ "navigation": "Navigation"+ },+ "actions": {+ "openSearch": { "label": "Open search", "description": "Search and run commands from anywhere." },+ "createIssue": { "label": "Create issue", "description": "Open your preferred issue creation flow." },+ "toggleSidebar": { "label": "Toggle sidebar", "description": "Show or hide the main sidebar." },+ "findInIssue": { "label": "Find in issue", "description": "Search within the open issue detail." },+ "send": { "label": "Send", "description": "Send chat messages, comments, replies, feedback, and prompts." },+ "goInbox": { "label": "Go to Inbox", "description": "Open the workspace inbox." },+ "goChat": { "label": "Go to Chat", "description": "Open workspace chat." },+ "goMyIssues": { "label": "Go to My Issues", "description": "Open issues assigned to you." },+ "goIssues": { "label": "Go to Issues", "description": "Open the issue list." },+ "goProjects": { "label": "Go to Projects", "description": "Open the project list." },+ "goAutopilots": { "label": "Go to Autopilot", "description": "Open workspace automations." },+ "goAgents": { "label": "Go to Agents", "description": "Open the agent list." },+ "goSquads": { "label": "Go to Squads", "description": "Open the squad list." },+ "goUsage": { "label": "Go to Usage", "description": "Open usage analytics." },+ "goRuntimes": { "label": "Go to Runtimes", "description": "Open runtime configuration." },+ "goSkills": { "label": "Go to Skills", "description": "Open the skill library." },+ "goSettings": { "label": "Go to Settings", "description": "Open workspace settings." }+ },+ "fixed": {+ "title": "Fixed system shortcuts",+ "description": "Window and accessibility shortcuts stay fixed so they remain reliable. Zoom and tab controls apply to the desktop app.",+ "close_tab": "Close active tab",+ "zoom_in": "Zoom in",+ "zoom_out": "Zoom out",+ "reset_zoom": "Reset zoom",+ "close_dialog": "Close dialog or menu"+ }+ },"chat": {"floating_title": "Floating window","floating_label": "Floating chat window",@@ -40,6 +92,7 @@"tabs": {"profile": "Profile","preferences": "Preferences",+ "shortcuts": "Shortcuts","chat": "Chat","notifications": "Notifications","tokens": "API Tokens",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 9447f525b3..b595359ccc 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -28,6 +28,55 @@"sync_failed": "タイムゾーン設定を保存できませんでした。"}},+ "shortcuts": {+ "title": "キーボードショートカット",+ "description": "このデバイスで製品操作のショートカットをカスタマイズします。ショートカットをクリックして、新しいキーの組み合わせを押してください。",+ "search_placeholder": "操作を検索...",+ "reset_all": "デフォルトに戻す",+ "reset": "リセット",+ "disable": "無効にする",+ "reset_action": "{{action}}をリセット",+ "disable_action": "{{action}}のショートカットを無効にする",+ "record_aria": "{{action}}のショートカットを変更",+ "recording": "キーを入力",+ "record_hint": "Esc でキャンセル · Delete でクリア",+ "unassigned": "未設定",+ "no_results": "一致するショートカット操作はありません。",+ "conflict_error": "すでに{{action}}で使用されています。",+ "reserved_error": "ブラウザまたはデスクトップウィンドウで予約されています。",+ "send_error": "送信には Enter または Mod+Enter のみ使用できます。",+ "unsafe_error": "このキーは文字入力や基本的なキーボード操作と競合します。",+ "send_enter_hint": "Shift+Enterで段落の挿入、リストの継続、コードブロック内の改行ができます。",+ "categories": { "general": "一般", "navigation": "ナビゲーション" },+ "actions": {+ "openSearch": { "label": "検索を開く", "description": "どこからでも検索やコマンドを実行します。" },+ "createIssue": { "label": "Issueを作成", "description": "優先するissue作成フローを開きます。" },+ "toggleSidebar": { "label": "サイドバーを切り替え", "description": "メインサイドバーの表示を切り替えます。" },+ "findInIssue": { "label": "Issue内を検索", "description": "開いているissueの詳細を検索します。" },+ "send": { "label": "送信", "description": "チャット、コメント、返信、フィードバック、プロンプトを送信します。" },+ "goInbox": { "label": "受信トレイへ移動", "description": "ワークスペースの受信トレイを開きます。" },+ "goChat": { "label": "チャットへ移動", "description": "ワークスペースのチャットを開きます。" },+ "goMyIssues": { "label": "自分のIssuesへ移動", "description": "自分に割り当てられたissueを開きます。" },+ "goIssues": { "label": "Issuesへ移動", "description": "Issue一覧を開きます。" },+ "goProjects": { "label": "プロジェクトへ移動", "description": "プロジェクト一覧を開きます。" },+ "goAutopilots": { "label": "自動化へ移動", "description": "ワークスペースの自動化を開きます。" },+ "goAgents": { "label": "エージェントへ移動", "description": "エージェント一覧を開きます。" },+ "goSquads": { "label": "Squadsへ移動", "description": "Squad一覧を開きます。" },+ "goUsage": { "label": "使用量へ移動", "description": "使用量分析を開きます。" },+ "goRuntimes": { "label": "ランタイムへ移動", "description": "ランタイム設定を開きます。" },+ "goSkills": { "label": "Skillsへ移動", "description": "Skillライブラリを開きます。" },+ "goSettings": { "label": "設定へ移動", "description": "ワークスペース設定を開きます。" }+ },+ "fixed": {+ "title": "固定のシステムショートカット",+ "description": "ウィンドウとアクセシビリティのショートカットは信頼性のため固定されています。ズームとタブ操作はデスクトップアプリに適用されます。",+ "close_tab": "アクティブなタブを閉じる",+ "zoom_in": "拡大",+ "zoom_out": "縮小",+ "reset_zoom": "ズームをリセット",+ "close_dialog": "ダイアログまたはメニューを閉じる"+ }+ },"chat": {"floating_title": "フローティングウィンドウ","floating_label": "フローティングチャット",@@ -40,6 +89,7 @@"tabs": {"profile": "プロフィール","preferences": "環境設定",+ "shortcuts": "ショートカット","chat": "チャット","notifications": "通知","tokens": "API トークン",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 46761d465e..a7de2a3fb5 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -28,6 +28,55 @@"sync_failed": "시간대 설정을 저장하지 못했습니다."}},+ "shortcuts": {+ "title": "키보드 단축키",+ "description": "이 기기에서 제품 동작의 단축키를 설정합니다. 단축키를 클릭한 다음 새 키 조합을 누르세요.",+ "search_placeholder": "동작 검색...",+ "reset_all": "기본값 복원",+ "reset": "재설정",+ "disable": "사용 안 함",+ "reset_action": "{{action}} 재설정",+ "disable_action": "{{action}} 단축키 사용 안 함",+ "record_aria": "{{action}} 단축키 변경",+ "recording": "키를 누르세요",+ "record_hint": "Esc 취소 · Delete 지우기",+ "unassigned": "지정되지 않음",+ "no_results": "일치하는 단축키 동작이 없습니다.",+ "conflict_error": "이미 {{action}}에서 사용 중입니다.",+ "reserved_error": "브라우저 또는 데스크톱 창에서 예약된 단축키입니다.",+ "send_error": "보내기는 Enter 또는 Mod+Enter만 사용할 수 있습니다.",+ "unsafe_error": "이 키는 텍스트 입력이나 기본 키보드 탐색을 방해합니다.",+ "send_enter_hint": "Shift+Enter로 단락을 삽입하거나 목록을 이어가고 코드 블록에서 줄을 바꿀 수 있습니다.",+ "categories": { "general": "일반", "navigation": "탐색" },+ "actions": {+ "openSearch": { "label": "검색 열기", "description": "어디서나 검색하고 명령을 실행합니다." },+ "createIssue": { "label": "Issue 만들기", "description": "선호하는 issue 만들기 흐름을 엽니다." },+ "toggleSidebar": { "label": "사이드바 전환", "description": "기본 사이드바를 표시하거나 숨깁니다." },+ "findInIssue": { "label": "Issue에서 찾기", "description": "열린 issue 상세 내용에서 검색합니다." },+ "send": { "label": "보내기", "description": "채팅, 댓글, 답글, 피드백 및 프롬프트를 보냅니다." },+ "goInbox": { "label": "받은 편지함으로 이동", "description": "워크스페이스 받은 편지함을 엽니다." },+ "goChat": { "label": "채팅으로 이동", "description": "워크스페이스 채팅을 엽니다." },+ "goMyIssues": { "label": "내 Issues로 이동", "description": "나에게 할당된 issue를 엽니다." },+ "goIssues": { "label": "Issues로 이동", "description": "Issue 목록을 엽니다." },+ "goProjects": { "label": "프로젝트로 이동", "description": "프로젝트 목록을 엽니다." },+ "goAutopilots": { "label": "자동화로 이동", "description": "워크스페이스 자동화를 엽니다." },+ "goAgents": { "label": "에이전트로 이동", "description": "에이전트 목록을 엽니다." },+ "goSquads": { "label": "스쿼드로 이동", "description": "스쿼드 목록을 엽니다." },+ "goUsage": { "label": "사용량으로 이동", "description": "사용량 분석을 엽니다." },+ "goRuntimes": { "label": "런타임으로 이동", "description": "런타임 설정을 엽니다." },+ "goSkills": { "label": "Skills로 이동", "description": "Skill 라이브러리를 엽니다." },+ "goSettings": { "label": "설정으로 이동", "description": "워크스페이스 설정을 엽니다." }+ },+ "fixed": {+ "title": "고정 시스템 단축키",+ "description": "창 및 접근성 단축키는 안정성을 위해 고정됩니다. 확대/축소 및 탭 제어는 데스크톱 앱에 적용됩니다.",+ "close_tab": "활성 탭 닫기",+ "zoom_in": "확대",+ "zoom_out": "축소",+ "reset_zoom": "확대/축소 재설정",+ "close_dialog": "대화상자 또는 메뉴 닫기"+ }+ },"chat": {"floating_title": "플로팅 창","floating_label": "플로팅 채팅 창",@@ -40,6 +89,7 @@"tabs": {"profile": "프로필","preferences": "환경설정",+ "shortcuts": "단축키","chat": "채팅","notifications": "알림","tokens": "API 토큰",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 42e7cf9207..d6ccc1a7cc 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -28,6 +28,58 @@"sync_failed": "保存时区偏好失败。"}},+ "shortcuts": {+ "title": "快捷键",+ "description": "自定义当前设备上的产品操作。点击一个快捷键,然后按下新的组合键。",+ "search_placeholder": "搜索操作...",+ "reset_all": "恢复默认设置",+ "reset": "重置",+ "disable": "停用",+ "reset_action": "重置「{{action}}」",+ "disable_action": "停用「{{action}}」快捷键",+ "record_aria": "修改「{{action}}」的快捷键",+ "recording": "请按键",+ "record_hint": "Esc 取消 · Delete 清除",+ "unassigned": "未设置",+ "no_results": "没有匹配的快捷键操作。",+ "conflict_error": "已被「{{action}}」使用。",+ "reserved_error": "该快捷键已被浏览器或桌面窗口占用。",+ "send_error": "发送只能使用 Enter 或 Mod + Enter。",+ "unsafe_error": "这个按键会干扰文字输入或基础键盘导航。",+ "send_enter_hint": "Shift+Enter 可插入段落、继续列表,或在代码块中换行。",+ "categories": {+ "general": "常规",+ "navigation": "导航"+ },+ "actions": {+ "openSearch": { "label": "打开搜索", "description": "随时搜索内容或运行命令。" },+ "createIssue": { "label": "新建 issue", "description": "打开你常用的 issue 创建流程。" },+ "toggleSidebar": { "label": "显示或隐藏侧边栏", "description": "切换主侧边栏的显示状态。" },+ "findInIssue": { "label": "在 issue 中查找", "description": "搜索当前打开的 issue 详情。" },+ "send": { "label": "发送", "description": "发送聊天消息、评论、回复、反馈和提示词。" },+ "goInbox": { "label": "前往收件箱", "description": "打开工作区收件箱。" },+ "goChat": { "label": "前往聊天", "description": "打开工作区聊天。" },+ "goMyIssues": { "label": "前往我的 issue", "description": "打开分配给你的 issue。" },+ "goIssues": { "label": "前往 Issues", "description": "打开 issue 列表。" },+ "goProjects": { "label": "前往项目", "description": "打开项目列表。" },+ "goAutopilots": { "label": "前往自动化", "description": "打开工作区自动化。" },+ "goAgents": { "label": "前往智能体", "description": "打开智能体列表。" },+ "goSquads": { "label": "前往小队", "description": "打开小队列表。" },+ "goUsage": { "label": "前往用量", "description": "打开用量分析。" },+ "goRuntimes": { "label": "前往运行时", "description": "打开运行时配置。" },+ "goSkills": { "label": "前往 Skills", "description": "打开 skill 库。" },+ "goSettings": { "label": "前往设置", "description": "打开工作区设置。" }+ },+ "fixed": {+ "title": "固定的系统快捷键",+ "description": "窗口和无障碍快捷键保持固定,确保始终可靠。缩放和标签页操作仅适用于桌面端。",+ "close_tab": "关闭当前标签页",+ "zoom_in": "放大",+ "zoom_out": "缩小",+ "reset_zoom": "重置缩放",+ "close_dialog": "关闭对话框或菜单"+ }+ },"chat": {"floating_title": "悬浮窗","floating_label": "悬浮聊天窗",@@ -40,6 +92,7 @@"tabs": {"profile": "个人资料","preferences": "偏好设置",+ "shortcuts": "快捷键","chat": "聊天","notifications": "通知","tokens": "API Token",diff --git a/packages/views/modals/feedback.test.tsx b/packages/views/modals/feedback.test.tsxindex e6ca593b80..f65638d046 100644--- a/packages/views/modals/feedback.test.tsx+++ b/packages/views/modals/feedback.test.tsx@@ -1,8 +1,10 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { render, screen } from "@testing-library/react";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";import { forwardRef, useImperativeHandle } from "react";let storedDraftMessage = "saved draft";+let liveEditorMarkdown = "";+const feedbackMocks = vi.hoisted(() => ({ mutateAsync: vi.fn() }));vi.mock("react-i18next", () => ({useTranslation: () => ({ t: (key: string) => key, i18n: { changeLanguage: vi.fn() } }),@@ -36,25 +38,30 @@ vi.mock("@multica/core/hooks/use-file-upload", () => ({}));vi.mock("@multica/core/api", () => ({ api: {} }));vi.mock("sonner", () => ({ toast: { info: vi.fn(), error: vi.fn(), success: vi.fn() } }));-vi.mock("@multica/core/platform", () => ({- formatShortcut: () => "⌘↵",- modKey: "mod",- enterKey: "enter",-}));vi.mock("@multica/core/feedback", () => ({FEEDBACK_KINDS: ["bug", "feature", "general", "praise"] as const,- useCreateFeedback: () => ({ isPending: false, mutateAsync: vi.fn() }),+ useCreateFeedback: () => ({ isPending: false, mutateAsync: feedbackMocks.mutateAsync }),useFeedbackDraftStore: (selector: any) =>selector({ draft: { message: storedDraftMessage }, setDraft: vi.fn(), clearDraft: vi.fn() }),}));vi.mock("../editor", () => {- const ContentEditor = forwardRef(({ defaultValue }: any, ref) => {+ const ContentEditor = forwardRef(({ defaultValue, onSubmit }: any, ref) => {+ liveEditorMarkdown = defaultValue;useImperativeHandle(ref, () => ({hasActiveUploads: () => false,- getMarkdown: () => defaultValue,+ getMarkdown: () => liveEditorMarkdown,uploadFile: vi.fn(),}));- return <textarea aria-label="feedback editor" defaultValue={defaultValue} />;+ return (+ <textarea+ aria-label="feedback editor"+ defaultValue={defaultValue}+ onChange={(event) => { liveEditorMarkdown = event.currentTarget.value; }}+ onKeyDown={(event) => {+ if (event.key === "Enter" && event.metaKey) void onSubmit?.();+ }}+ />+ );});ContentEditor.displayName = "MockContentEditor";return {@@ -70,6 +77,7 @@ import { FeedbackModal } from "./feedback";describe("FeedbackModal", () => {beforeEach(() => {vi.spyOn(console, "error").mockImplementation(() => {});+ feedbackMocks.mutateAsync.mockReset().mockResolvedValue(undefined);});afterEach(() => {@@ -93,4 +101,19 @@ describe("FeedbackModal", () => {"saved draft\n\n---\n\nkind: desktop_route_error",);});++ it("submits the editor's latest markdown before debounced state catches up", async () => {+ storedDraftMessage = "";+ render(<FeedbackModal onClose={vi.fn()} />);++ const editor = screen.getByLabelText("feedback editor");+ fireEvent.change(editor, { target: { value: "fresh feedback" } });+ fireEvent.keyDown(editor, { key: "Enter", metaKey: true });++ await waitFor(() => {+ expect(feedbackMocks.mutateAsync).toHaveBeenCalledWith(+ expect.objectContaining({ message: "fresh feedback" }),+ );+ });+ });});diff --git a/packages/views/modals/feedback.tsx b/packages/views/modals/feedback.tsxindex 2e144b6d80..714b1f3a5b 100644--- a/packages/views/modals/feedback.tsx+++ b/packages/views/modals/feedback.tsx@@ -26,7 +26,8 @@ import { useCurrentWorkspace } from "@multica/core/paths";import { useFileUpload } from "@multica/core/hooks/use-file-upload";import { api } from "@multica/core/api";import { useT } from "../i18n";-import { formatShortcut, modKey, enterKey } from "@multica/core/platform";+import { useShortcut } from "@multica/core/shortcuts";+import { ShortcutKeycaps } from "../common/shortcut-keycaps";const MAX_MESSAGE_LEN = 10000;@@ -54,6 +55,7 @@ export function FeedbackModal({data?: Record<string, unknown> | null;initialMessage?: string;}) {+ const sendShortcut = useShortcut("send");const { t } = useT("modals");const workspace = useCurrentWorkspace();const draft = useFeedbackDraftStore((s) => s.draft);@@ -80,7 +82,10 @@ export function FeedbackModal({!mutation.isPending;const handleSubmit = async () => {- if (!canSubmit) return;+ // The button can use debounced `message` state, but the keyboard shortcut+ // must not: Command+Enter can arrive before ContentEditor's 150ms onUpdate+ // fires. The editor ref below is the submit-time source of truth.+ if (mutation.isPending) return;if (editorRef.current?.hasActiveUploads()) {toast.info(t(($) => $.feedback.toast_uploading));return;@@ -159,9 +164,14 @@ export function FeedbackModal({/><Button size="sm" onClick={handleSubmit} disabled={!canSubmit}>{mutation.isPending ? t(($) => $.feedback.sending) : t(($) => $.feedback.send)}- <kbd className="ml-1 inline-flex h-4 items-center gap-0.5 rounded border border-border/50 bg-background/30 px-1 font-mono text-[10px] leading-none">- {formatShortcut(modKey, enterKey)}- </kbd>+ {sendShortcut ? (+ <ShortcutKeycaps+ shortcut={sendShortcut}+ decorative+ className="ml-1"+ keyClassName="border-background/30 bg-background/15 text-primary-foreground shadow-none"+ />+ ) : null}</Button></div></DialogContent>diff --git a/packages/views/modals/quick-create-issue.test.tsx b/packages/views/modals/quick-create-issue.test.tsxindex c8380034b9..7e982029ff 100644--- a/packages/views/modals/quick-create-issue.test.tsx+++ b/packages/views/modals/quick-create-issue.test.tsx@@ -347,7 +347,7 @@ describe("AgentCreatePanel", () => {await user.type(editor, "New agent prompt");expect(mockSetPrompt).toHaveBeenLastCalledWith("New agent prompt");- await user.click(screen.getByRole("button", { name: /^Create \(/i }));+ await user.click(screen.getByRole("button", { name: /^Create$/i }));await waitFor(() => {expect(mockQuickCreateIssue).toHaveBeenCalledWith({@@ -385,7 +385,7 @@ describe("AgentCreatePanel", () => {},});- await user.click(screen.getByRole("button", { name: /^Create \(/i }));+ await user.click(screen.getByRole("button", { name: /^Create$/i }));await waitFor(() => {expect(mockQuickCreateIssue).toHaveBeenCalledWith({@@ -421,7 +421,7 @@ describe("AgentCreatePanel", () => {await user.clear(editor);await user.type(editor, "Investigate the regression");- await user.click(screen.getByRole("button", { name: /^Create \(/i }));+ await user.click(screen.getByRole("button", { name: /^Create$/i }));await waitFor(() => {expect(mockQuickCreateIssue).toHaveBeenCalledWith({@@ -506,7 +506,7 @@ describe("AgentCreatePanel", () => {await user.clear(editor);await user.type(editor, "Investigate the regression");- await user.click(screen.getByRole("button", { name: /^Create \(/i }));+ await user.click(screen.getByRole("button", { name: /^Create$/i }));await waitFor(() => {expect(mockQuickCreateIssue).toHaveBeenCalledWith({diff --git a/packages/views/modals/quick-create-issue.tsx b/packages/views/modals/quick-create-issue.tsxindex ef327ffd1a..12fb900e28 100644--- a/packages/views/modals/quick-create-issue.tsx+++ b/packages/views/modals/quick-create-issue.tsx@@ -25,7 +25,8 @@ import {MIN_QUICK_CREATE_CLI_VERSION,} from "@multica/core/runtimes";import { useFileUpload } from "@multica/core/hooks/use-file-upload";-import { formatShortcut, modKey, enterKey } from "@multica/core/platform";+import { useShortcut } from "@multica/core/shortcuts";+import { ShortcutKeycaps } from "../common/shortcut-keycaps";import { contentReferencesAttachment, type Agent, type Attachment, type Squad } from "@multica/core/types";import { ActorAvatar } from "../common/actor-avatar";import { PillButton } from "../common/pill-button";@@ -82,6 +83,7 @@ export function AgentCreatePanel({setIsExpanded: (v: boolean) => void;}) {const { t } = useT("modals");+ const sendShortcut = useShortcut("send");const workspaceName = useCurrentWorkspace()?.name;const wsId = useWorkspaceId();const userId = useAuthStore((s) => s.user?.id);@@ -580,7 +582,19 @@ export function AgentCreatePanel({>{submitting ? t(($) => $.create_issue.agent.sending) : uploading ? t(($) => $.create_issue.agent.uploading) : justSent ? (<span className="flex items-center gap-1"><Check className="size-3.5" />{t(($) => $.create_issue.agent.sent_label)}</span>- ) : `${t(($) => $.create_issue.agent.submit)} (${formatShortcut(modKey, enterKey)})`}+ ) : (+ <>+ {t(($) => $.create_issue.agent.submit)}+ {sendShortcut ? (+ <ShortcutKeycaps+ shortcut={sendShortcut}+ decorative+ className="ml-1"+ keyClassName="border-background/30 bg-background/15 text-primary-foreground shadow-none"+ />+ ) : null}+ </>+ )}</Button></div></div>diff --git a/packages/views/search/search-command.tsx b/packages/views/search/search-command.tsxindex 6410b09088..891fbda451 100644--- a/packages/views/search/search-command.tsx+++ b/packages/views/search/search-command.tsx@@ -42,6 +42,7 @@ import { useWorkspaceId } from "@multica/core";import { useWorkspacePaths } from "@multica/core/paths";import type { WorkspacePaths } from "@multica/core/paths";import { useModalStore } from "@multica/core/modals";+import { createShortcutChord } from "@multica/core/shortcuts";import { memberListOptions } from "@multica/core/workspace/queries";import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";import { StatusIcon } from "../issues/components";@@ -49,6 +50,7 @@ import { ProjectIcon } from "../projects/components/project-icon";import { PROJECT_STATUS_CONFIG } from "@multica/core/projects/config";import type { ProjectStatus } from "@multica/core/types";import { ActorAvatar } from "../common/actor-avatar";+import { ShortcutKeycaps } from "../common/shortcut-keycaps";import { ActorAvatar as ActorAvatarBase } from "@multica/ui/components/common/actor-avatar";import {Dialog,@@ -333,18 +335,6 @@ export function SearchCommand() {results.projects.length > 0 ||filteredMembers.length > 0;- // Global Cmd+K / Ctrl+K shortcut- useEffect(() => {- const handleKeyDown = (e: KeyboardEvent) => {- if (e.key === "k" && (e.metaKey || e.ctrlKey)) {- e.preventDefault();- useSearchStore.getState().toggle();- }- };- document.addEventListener("keydown", handleKeyDown);- return () => document.removeEventListener("keydown", handleKeyDown);- }, []);-// Close on single ESC — capture phase fires before base-ui Dialog's handlersuseEffect(() => {if (!open) return;@@ -483,9 +473,10 @@ export function SearchCommand() {onValueChange={handleValueChange}className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"/>- <kbd className="hidden shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground sm:inline">- ESC- </kbd>+ <ShortcutKeycaps+ shortcut={createShortcutChord("Escape")}+ className="hidden shrink-0 sm:inline-flex"+ /></div>{/* Results list */}diff --git a/packages/views/search/search-trigger.tsx b/packages/views/search/search-trigger.tsxindex 08c42f1ea0..83b1bacd01 100644--- a/packages/views/search/search-trigger.tsx+++ b/packages/views/search/search-trigger.tsx@@ -2,12 +2,16 @@import { Search } from "lucide-react";import { SidebarMenuButton } from "@multica/ui/components/ui/sidebar";-import { isMac, formatShortcut, modKey } from "@multica/core/platform";+import {+ useShortcut,+} from "@multica/core/shortcuts";import { useSearchStore } from "./search-store";import { useT } from "../i18n";+import { ShortcutKeycaps } from "../common/shortcut-keycaps";export function SearchTrigger() {const { t } = useT("search");+ const shortcut = useShortcut("openSearch");return (<SidebarMenuButtonclassName="text-muted-foreground"@@ -15,15 +19,9 @@ export function SearchTrigger() {><Search /><span>{t(($) => $.trigger.label)}</span>- <kbd className="pointer-events-none ml-auto inline-flex h-5 select-none items-center gap-0.5 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground">- {isMac ? (- <>- <span className="text-xs">{modKey}</span>K- </>- ) : (- formatShortcut(modKey, "K")- )}- </kbd>+ {shortcut ? (+ <ShortcutKeycaps shortcut={shortcut} decorative className="pointer-events-none ml-auto" />+ ) : null}</SidebarMenuButton>);}diff --git a/packages/views/settings/components/keyboard-shortcuts-tab.test.tsx b/packages/views/settings/components/keyboard-shortcuts-tab.test.tsxnew file mode 100644index 0000000000..a465baf582--- /dev/null+++ b/packages/views/settings/components/keyboard-shortcuts-tab.test.tsx@@ -0,0 +1,139 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { cleanup, fireEvent, screen, within } from "@testing-library/react";+import {+ createShortcutChord,+ configureShortcutPlatform,+ getShortcut,+ useShortcutStore,+} from "@multica/core/shortcuts";+import { renderWithI18n } from "../../test/i18n";+import { KeyboardShortcutsTab } from "./keyboard-shortcuts-tab";++describe("KeyboardShortcutsTab", () => {+ beforeEach(() => {+ configureShortcutPlatform("windows");+ useShortcutStore.getState().resetAll();+ });++ afterEach(() => {+ cleanup();+ configureShortcutPlatform(null);+ useShortcutStore.getState().resetAll();+ });++ it("records a shortcut and applies it immediately", () => {+ renderWithI18n(<KeyboardShortcutsTab />);+ const recorder = screen.getByRole("button", {+ name: "Change shortcut for Open search",+ });++ fireEvent.click(recorder);+ fireEvent.keyDown(recorder, { key: "j", ctrlKey: true });++ expect(getShortcut("openSearch")).toEqual(+ createShortcutChord("J", { primary: true }),+ );+ expect(within(recorder).getByTitle("Ctrl")).toHaveTextContent("Ctrl");+ expect(within(recorder).getByTitle("J")).toHaveTextContent("J");+ });++ it("only captures keys while the recorder is active", () => {+ renderWithI18n(<KeyboardShortcutsTab />);+ const recorder = screen.getByRole("button", {+ name: "Change shortcut for Open search",+ });++ recorder.focus();+ fireEvent.keyDown(recorder, { key: "j", ctrlKey: true });+ expect(getShortcut("openSearch")).toEqual(+ createShortcutChord("K", { primary: true }),+ );++ fireEvent.click(recorder);+ fireEvent.keyDown(recorder, { key: "j", ctrlKey: true });+ expect(getShortcut("openSearch")).toEqual(+ createShortcutChord("J", { primary: true }),+ );++ // Focus remains on the button after a successful recording. Tab must move+ // focus normally instead of silently replacing the shortcut with Tab.+ fireEvent.keyDown(recorder, { key: "Tab" });+ expect(getShortcut("openSearch")).toEqual(+ createShortcutChord("J", { primary: true }),+ );+ });++ it("rejects unsafe plain keys in editors while allowing Send = Enter", () => {+ renderWithI18n(<KeyboardShortcutsTab />);+ const searchRecorder = screen.getByRole("button", {+ name: "Change shortcut for Open search",+ });+ fireEvent.click(searchRecorder);+ fireEvent.keyDown(searchRecorder, { key: "j" });+ expect(getShortcut("openSearch")).toEqual(+ createShortcutChord("K", { primary: true }),+ );+ expect(screen.getByRole("alert")).toHaveTextContent(+ "This key would interfere with typing or basic keyboard navigation.",+ );++ const sendRecorder = screen.getByRole("button", {+ name: "Change shortcut for Send",+ });+ fireEvent.click(sendRecorder);+ fireEvent.keyDown(sendRecorder, { key: "Enter" });+ expect(getShortcut("send")).toEqual(createShortcutChord("Enter"));+ });++ it("only allows Enter or Primary+Enter for Send", () => {+ renderWithI18n(<KeyboardShortcutsTab />);+ const sendRecorder = screen.getByRole("button", {+ name: "Change shortcut for Send",+ });++ fireEvent.click(sendRecorder);+ fireEvent.keyDown(sendRecorder, { key: "Enter", shiftKey: true });+ expect(getShortcut("send")).toEqual(+ createShortcutChord("Enter", { primary: true }),+ );+ expect(screen.getByRole("alert")).toHaveTextContent(+ "Send can only use Enter or Mod+Enter.",+ );++ fireEvent.keyDown(sendRecorder, { key: "Enter", ctrlKey: true });+ expect(getShortcut("send")).toEqual(+ createShortcutChord("Enter", { primary: true }),+ );+ });++ it("rejects shortcuts already assigned to another action", () => {+ renderWithI18n(<KeyboardShortcutsTab />);+ const recorder = screen.getByRole("button", {+ name: "Change shortcut for Create issue",+ });++ fireEvent.click(recorder);+ fireEvent.keyDown(recorder, { key: "k", ctrlKey: true });++ expect(getShortcut("createIssue")).toEqual(createShortcutChord("C"));+ expect(screen.getByRole("alert")).toHaveTextContent(+ "Already used by Open search.",+ );+ });++ it("can disable and restore an action", () => {+ renderWithI18n(<KeyboardShortcutsTab />);++ fireEvent.click(+ screen.getByRole("button", {+ name: "Disable Create issue shortcut",+ }),+ );+ expect(getShortcut("createIssue")).toBeNull();++ fireEvent.click(+ screen.getByRole("button", { name: "Reset Create issue" }),+ );+ expect(getShortcut("createIssue")).toEqual(createShortcutChord("C"));+ });+});diff --git a/packages/views/settings/components/keyboard-shortcuts-tab.tsx b/packages/views/settings/components/keyboard-shortcuts-tab.tsxnew file mode 100644index 0000000000..c6e7224508--- /dev/null+++ b/packages/views/settings/components/keyboard-shortcuts-tab.tsx@@ -0,0 +1,327 @@+"use client";++import { useMemo, useState } from "react";+import { Keyboard, RotateCcw, Search, X } from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import { Input } from "@multica/ui/components/ui/input";+import { cn } from "@multica/ui/lib/utils";+import {+ findShortcutConflict,+ createShortcutChord,+ isReservedShortcut,+ isShortcutAllowedForAction,+ isPlainShortcut,+ resolveShortcut,+ shortcutFromEvent,+ SHORTCUT_ACTIONS,+ useShortcutStore,+ type ShortcutActionDefinition,+ type ShortcutActionId,+ type ShortcutCategory,+ type ShortcutChord,+} from "@multica/core/shortcuts";+import { isImeComposing } from "@multica/core/utils";+import { useT } from "../../i18n";+import { ShortcutKeycaps } from "../../common/shortcut-keycaps";+import {+ SettingsCard,+ SettingsRow,+ SettingsSection,+ SettingsTab,+} from "./settings-layout";++type CaptureError =+ | { kind: "conflict"; actionId: ShortcutActionId }+ | { kind: "reserved" }+ | { kind: "send" }+ | { kind: "unsafe" }+ | null;++export function KeyboardShortcutsTab() {+ const { t } = useT("settings");+ const [query, setQuery] = useState("");+ const [recording, setRecording] = useState<ShortcutActionId | null>(null);+ const [captureError, setCaptureError] = useState<CaptureError>(null);+ const overrides = useShortcutStore((state) => state.overrides);+ const setShortcut = useShortcutStore((state) => state.setShortcut);+ const resetShortcut = useShortcutStore((state) => state.resetShortcut);+ const resetAll = useShortcutStore((state) => state.resetAll);++ const visibleActions = useMemo(() => {+ const needle = query.trim().toLocaleLowerCase();+ if (!needle) return SHORTCUT_ACTIONS;+ return SHORTCUT_ACTIONS.filter((action) => {+ const label = t(($) => $.shortcuts.actions[action.id].label);+ const description = t(+ ($) => $.shortcuts.actions[action.id].description,+ );+ return `${label} ${description}`+ .toLocaleLowerCase()+ .includes(needle);+ });+ }, [query, t]);++ const groups: readonly ShortcutCategory[] = ["general", "navigation"];++ const capture = (actionId: ShortcutActionId, event: React.KeyboardEvent) => {+ event.preventDefault();+ event.stopPropagation();+ if (event.repeat || isImeComposing(event)) return;+ if (event.key === "Escape") {+ setRecording(null);+ setCaptureError(null);+ return;+ }+ if (event.key === "Backspace" || event.key === "Delete") {+ setShortcut(actionId, null);+ setRecording(null);+ setCaptureError(null);+ return;+ }++ const shortcut = shortcutFromEvent(event.nativeEvent);+ if (!shortcut) return;+ if (isReservedShortcut(shortcut)) {+ setCaptureError({ kind: "reserved" });+ return;+ }+ if (!isShortcutAllowedForAction(actionId, shortcut)) {+ setCaptureError({ kind: actionId === "send" ? "send" : "unsafe" });+ return;+ }+ const conflict = findShortcutConflict(actionId, shortcut);+ if (conflict) {+ setCaptureError({ kind: "conflict", actionId: conflict });+ return;+ }++ setShortcut(actionId, shortcut);+ setRecording(null);+ setCaptureError(null);+ };++ return (+ <SettingsTab+ title={t(($) => $.shortcuts.title)}+ description={t(($) => $.shortcuts.description)}+ >+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">+ <div className="relative min-w-0 flex-1 sm:max-w-sm">+ <Search className="pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />+ <Input+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ placeholder={t(($) => $.shortcuts.search_placeholder)}+ aria-label={t(($) => $.shortcuts.search_placeholder)}+ className="pl-8"+ />+ </div>+ <Button+ variant="outline"+ size="sm"+ onClick={() => {+ resetAll();+ setCaptureError(null);+ setRecording(null);+ }}+ disabled={Object.keys(overrides).length === 0}+ >+ <RotateCcw className="size-3.5" />+ {t(($) => $.shortcuts.reset_all)}+ </Button>+ </div>++ {groups.map((category) => {+ const actions = visibleActions.filter(+ (action) => action.category === category,+ );+ if (actions.length === 0) return null;+ return (+ <SettingsSection+ key={category}+ title={t(($) => $.shortcuts.categories[category])}+ >+ <SettingsCard>+ {actions.map((action) => (+ <ShortcutRow+ key={action.id}+ action={action}+ shortcut={resolveShortcut(overrides, action.id)}+ customized={Object.prototype.hasOwnProperty.call(+ overrides,+ action.id,+ )}+ recording={recording === action.id}+ error={recording === action.id ? captureError : null}+ onStartRecording={() => {+ setRecording(action.id);+ setCaptureError(null);+ }}+ onCancelRecording={() => {+ setRecording(null);+ setCaptureError(null);+ }}+ onCapture={(event) => capture(action.id, event)}+ onDisable={() => {+ setShortcut(action.id, null);+ setCaptureError(null);+ }}+ onReset={() => {+ resetShortcut(action.id);+ setCaptureError(null);+ }}+ />+ ))}+ </SettingsCard>+ </SettingsSection>+ );+ })}++ {visibleActions.length === 0 ? (+ <div className="rounded-lg border border-dashed px-4 py-10 text-center text-sm text-muted-foreground">+ {t(($) => $.shortcuts.no_results)}+ </div>+ ) : null}++ <SettingsSection+ title={t(($) => $.shortcuts.fixed.title)}+ description={t(($) => $.shortcuts.fixed.description)}+ >+ <SettingsCard>+ <FixedShortcutRow label={t(($) => $.shortcuts.fixed.close_tab)} shortcut={createShortcutChord("W", { primary: true })} />+ <FixedShortcutRow label={t(($) => $.shortcuts.fixed.zoom_in)} shortcut={createShortcutChord("Plus", { primary: true })} />+ <FixedShortcutRow label={t(($) => $.shortcuts.fixed.zoom_out)} shortcut={createShortcutChord("Minus", { primary: true })} />+ <FixedShortcutRow label={t(($) => $.shortcuts.fixed.reset_zoom)} shortcut={createShortcutChord("0", { primary: true })} />+ <FixedShortcutRow label={t(($) => $.shortcuts.fixed.close_dialog)} shortcut={createShortcutChord("Escape")} />+ </SettingsCard>+ </SettingsSection>+ </SettingsTab>+ );+}++function ShortcutRow({+ action,+ shortcut,+ customized,+ recording,+ error,+ onStartRecording,+ onCancelRecording,+ onCapture,+ onDisable,+ onReset,+}: {+ action: ShortcutActionDefinition;+ shortcut: ShortcutChord | null;+ customized: boolean;+ recording: boolean;+ error: CaptureError;+ onStartRecording: () => void;+ onCancelRecording: () => void;+ onCapture: (event: React.KeyboardEvent) => void;+ onDisable: () => void;+ onReset: () => void;+}) {+ const { t } = useT("settings");+ const label = t(($) => $.shortcuts.actions[action.id].label);+ const description = t(($) => $.shortcuts.actions[action.id].description);+ const errorText = error?.kind === "reserved"+ ? t(($) => $.shortcuts.reserved_error)+ : error?.kind === "send"+ ? t(($) => $.shortcuts.send_error)+ : error?.kind === "unsafe"+ ? t(($) => $.shortcuts.unsafe_error)+ : error?.kind === "conflict"+ ? t(($) => $.shortcuts.conflict_error, {+ action: t(($) => $.shortcuts.actions[error.actionId].label),+ })+ : null;++ return (+ <SettingsRow+ label={label}+ description={+ action.id === "send" && isPlainShortcut(shortcut, "Enter") ? (+ <>+ {description}+ <span className="mt-1 block text-brand">+ {t(($) => $.shortcuts.send_enter_hint)}+ </span>+ </>+ ) : description+ }+ align="start"+ size="select-wide"+ >+ <div className="flex flex-col items-stretch gap-1.5 sm:items-end">+ <div className="flex items-center justify-end gap-1.5">+ <button+ type="button"+ onClick={onStartRecording}+ onKeyDown={recording ? onCapture : undefined}+ onBlur={onCancelRecording}+ className={cn(+ "inline-flex h-8 min-w-28 items-center justify-center rounded-md border bg-background px-2.5 font-mono text-xs font-medium shadow-xs outline-none transition-colors hover:bg-surface-hover focus-visible:ring-2 focus-visible:ring-ring",+ recording && "border-brand bg-brand/5 text-brand ring-2 ring-brand/20",+ error && "border-destructive text-destructive ring-destructive/20",+ )}+ aria-label={t(($) => $.shortcuts.record_aria, { action: label })}+ aria-pressed={recording}+ >+ {recording ? (+ <span className="inline-flex items-center gap-1.5 font-sans">+ <Keyboard className="size-3.5" />+ {t(($) => $.shortcuts.recording)}+ </span>+ ) : shortcut ? (+ <ShortcutKeycaps shortcut={shortcut} decorative />+ ) : (+ <span className="font-sans font-normal text-muted-foreground">+ {t(($) => $.shortcuts.unassigned)}+ </span>+ )}+ </button>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ onClick={onReset}+ disabled={!customized}+ aria-label={t(($) => $.shortcuts.reset_action, { action: label })}+ title={t(($) => $.shortcuts.reset)}+ >+ <RotateCcw className="size-3.5" />+ </Button>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ onClick={onDisable}+ disabled={shortcut === null}+ aria-label={t(($) => $.shortcuts.disable_action, { action: label })}+ title={t(($) => $.shortcuts.disable)}+ >+ <X className="size-3.5" />+ </Button>+ </div>+ {errorText ? (+ <span role="alert" className="max-w-72 text-right text-xs text-destructive">+ {errorText}+ </span>+ ) : recording ? (+ <span className="text-right text-[11px] text-muted-foreground">+ {t(($) => $.shortcuts.record_hint)}+ </span>+ ) : null}+ </div>+ </SettingsRow>+ );+}++function FixedShortcutRow({ label, shortcut }: { label: string; shortcut: ShortcutChord }) {+ return (+ <SettingsRow label={label}>+ <ShortcutKeycaps shortcut={shortcut} size="md" className="justify-end" />+ </SettingsRow>+ );+}diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsxindex 888eb64866..108104983f 100644--- a/packages/views/settings/components/settings-page.tsx+++ b/packages/views/settings/components/settings-page.tsx@@ -13,6 +13,7 @@ import {Plug,MessageCircle,Tags,+ Keyboard,} from "lucide-react";import { GitHubMark } from "./github-mark";import { Tabs, TabsList, TabsTrigger, TabsContent } from "@multica/ui/components/ui/tabs";@@ -31,12 +32,14 @@ import { IntegrationsTab } from "./integrations-tab";import { LabsTab } from "./labs-tab";import { NotificationsTab } from "./notifications-tab";import { LabelsTab } from "./labels-tab";+import { KeyboardShortcutsTab } from "./keyboard-shortcuts-tab";import { useT } from "../../i18n";-const ACCOUNT_TAB_KEYS = ["profile", "preferences", "chat", "notifications", "tokens"] as const;+const ACCOUNT_TAB_KEYS = ["profile", "preferences", "shortcuts", "chat", "notifications", "tokens"] as const;const ACCOUNT_TAB_ICONS = {profile: User,preferences: SlidersHorizontal,+ shortcuts: Keyboard,chat: MessageCircle,notifications: Bell,tokens: Key,@@ -197,6 +200,7 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {<div className={`mx-auto w-full p-4 sm:p-6 md:p-8 ${activeTab === "labels" ? "max-w-5xl" : "max-w-3xl"}`}><TabsContent value="profile"><AccountTab /></TabsContent><TabsContent value="preferences"><PreferencesTab /></TabsContent>+ <TabsContent value="shortcuts"><KeyboardShortcutsTab /></TabsContent><TabsContent value="chat"><ChatTab /></TabsContent><TabsContent value="notifications"><NotificationsTab /></TabsContent><TabsContent value="tokens"><TokensTab /></TabsContent>diff --git a/packages/views/squads/components/squad-detail-page.tsx b/packages/views/squads/components/squad-detail-page.tsxindex 58f9c2fb1d..31fd4d6791 100644--- a/packages/views/squads/components/squad-detail-page.tsx+++ b/packages/views/squads/components/squad-detail-page.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useMemo, useState, type ReactNode } from "react";+import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import { api } from "@multica/core/api";import { useAuthStore } from "@multica/core/auth";@@ -8,6 +8,7 @@ import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";import { useWorkspaceId } from "@multica/core/hooks";import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";import { isImeComposing } from "@multica/core/utils";+import { getShortcut, shortcutMatchesEvent } from "@multica/core/shortcuts";import { useTimeAgo } from "../../i18n";import { agentListOptions, memberListOptions, squadMemberStatusOptions, workspaceKeys } from "@multica/core/workspace/queries";import { runtimeListOptions } from "@multica/core/runtimes";@@ -925,10 +926,13 @@ function SquadDescriptionEditorBody({const { t } = useT("squads");const [draft, setDraft] = useState(initialValue);const [saving, setSaving] = useState(false);+ const savingRef = useRef(false);const dirty = draft !== initialValue;const commit = async () => {+ if (savingRef.current) return;if (!dirty) { onClose(); return; }+ savingRef.current = true;setSaving(true);try {await onSave(draft);@@ -936,6 +940,7 @@ function SquadDescriptionEditorBody({} catch {// toast handled by parent's mutation} finally {+ savingRef.current = false;setSaving(false);}};@@ -953,8 +958,8 @@ function SquadDescriptionEditorBody({rows={6}onKeyDown={(e) => {if (e.key === "Escape") { onClose(); return; }- if (isImeComposing(e)) return;- if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {+ if (e.defaultPrevented || e.repeat || isImeComposing(e)) return;+ if (shortcutMatchesEvent(getShortcut("send"), e.nativeEvent)) {e.preventDefault();void commit();}