Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(hotkeys): fix hotkey scope issues (#5843)
Peter Chinman06a7c8d61d3e
diff --git a/apps/web/src/components/app/app-sidebar/sidebar.tsx b/apps/web/src/components/app/app-sidebar/sidebar.tsxindex f2f1160b62..e24ffd5ac6 100644--- a/apps/web/src/components/app/app-sidebar/sidebar.tsx+++ b/apps/web/src/components/app/app-sidebar/sidebar.tsx@@ -63,6 +63,7 @@ import {useSettingsTabAvailable,} from '@core/constant/settingsTabsConfig';import { useEmail, useUserId } from '@core/context/user';+import { hotkeyScopeNeutralAttribute } from '@core/dom-selectors';import { registerHotkey } from '@core/hotkey/hotkeys';import { clearPressedKeys } from '@core/hotkey/state';import { type HotkeyToken, TOKENS } from '@core/hotkey/tokens';@@ -1467,8 +1468,14 @@ export const AppSidebar = (props: AppSidebarProps) => {onOpenChange: props.onOpenChange,});+ // hotkeyScopeNeutralAttribute: focusing anything in the sidebar (rows, the+ // workspace toggle, ...) must not flip the active hotkey scope to 'global',+ // which would mute the active split's hotkeys until the user clicks back+ // into a split. The sidebar's own hotkeys register on the 'global' scope,+ // which every scope chain reaches, so they don't need the flip either.return (<div+ {...hotkeyScopeNeutralAttribute}class={cn('group/sidebar flex flex-col gap-0 overflow-hidden bg-surface px-3 pb-3 pt-4 text-[13px]',isExpanded() && 'relative h-full shrink-0 max-w-55 w-55 opacity-100',diff --git a/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx b/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsxindex 3826a19101..89a05d6cbf 100644--- a/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx+++ b/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx@@ -108,9 +108,16 @@ function PopoverSplitModal(props: {viewerId: () => undefined,};+ const [bindHotKeyDom, scopeId] = useHotkeyDOMScope(+ `popover-split-${props.popover.id}`+ );+const stubPanelContext: SplitPanelContextType = {handle: stubHandle,- splitHotkeyScope: `popover-${props.popover.id}`,+ // The real registered scope id: blocks register their commands to+ // `splitHotkeyScope`, so a made-up id would send them to a scope that+ // doesn't exist and every registration would silently noop.+ splitHotkeyScope: scopeId,isPanelActive: () => true,panelRef,panelSize: { width: null, height: null },@@ -129,10 +136,6 @@ function PopoverSplitModal(props: {toolbarCollapser: { register: () => () => {} },};- const [bindHotKeyDom, scopeId] = useHotkeyDOMScope(- `popover-split-${props.popover.id}`- );-registerHotkey({hotkey: 'escape',scopeId,diff --git a/apps/web/src/features/block-canvas/component/CanvasController.tsx b/apps/web/src/features/block-canvas/component/CanvasController.tsxindex d3fe493386..d48e5b1210 100644--- a/apps/web/src/features/block-canvas/component/CanvasController.tsx+++ b/apps/web/src/features/block-canvas/component/CanvasController.tsx@@ -16,6 +16,7 @@ import { observedSize } from '@core/directive/observedSize';import { HEIC_EXTENSIONS, HEIC_MIME_TYPES } from '@core/heic/constants';import { registerHotkey } from '@core/hotkey/hotkeys';import { TOKENS } from '@core/hotkey/tokens';+import { HOTKEY_PRIORITY_HIGH } from '@core/hotkey/types';import { createMethodRegistration } from '@core/orchestrator';import { blockHotkeyScopeSignal } from '@core/signal/blockElement';import { blockHandleSignal } from '@core/signal/load';@@ -341,6 +342,10 @@ export function CanvasController(props: ParentProps) {hotkeyToken: TOKENS.canvas.bringToFront,});+ // opt+] / opt+[ / shift+arrows are also bound on the split scope (history+ // forward/back, focus split). Register as 'add' so the split's commands+ // survive this block, with high priority so the canvas wins while+ // mounted; a false return (no selection) falls through to the split's.registerHotkey({hotkey: 'opt+]',scopeId: scopeId(),@@ -351,6 +356,8 @@ export function CanvasController(props: ParentProps) {return true;},hotkeyToken: TOKENS.canvas.bringForward,+ registrationType: 'add',+ handlerPriority: HOTKEY_PRIORITY_HIGH,});registerHotkey({@@ -375,6 +382,8 @@ export function CanvasController(props: ParentProps) {return true;},hotkeyToken: TOKENS.canvas.sendBackward,+ registrationType: 'add',+ handlerPriority: HOTKEY_PRIORITY_HIGH,});registerHotkey({@@ -613,10 +622,13 @@ export function CanvasController(props: ParentProps) {scopeId: scopeId(),description: 'Nudge right more',keyDownHandler: () => {+ if (!selection.active()) return false;nudge('right', true, true);return true;},hotkeyToken: TOKENS.canvas.nudgeRightMore,+ registrationType: 'add',+ handlerPriority: HOTKEY_PRIORITY_HIGH,});registerHotkey({@@ -657,10 +669,13 @@ export function CanvasController(props: ParentProps) {scopeId: scopeId(),description: 'Nudge left more',keyDownHandler: () => {+ if (!selection.active()) return false;nudge('left', true, true);return true;},hotkeyToken: TOKENS.canvas.nudgeLeftMore,+ registrationType: 'add',+ handlerPriority: HOTKEY_PRIORITY_HIGH,});registerHotkey({diff --git a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsxindex 010f9cc64a..198cb6c6b3 100644--- a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx+++ b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx@@ -53,7 +53,6 @@ import {useChannelType,} from '@core/context/channels';import { useUserId } from '@core/context/user';-import { useHotkeyDOMScope } from '@core/hotkey/hotkeys';import { TOKENS } from '@core/hotkey/tokens';import { isMobile } from '@core/mobile/isMobile';import { awaitCondition, createMethodRegistration } from '@core/orchestrator';@@ -265,14 +264,15 @@ function NewTop(props: { channelId: string }) {export function NewChannelBlockAdapter(props: BlockChannelProps) {// Every other block gets its hotkey scope from `BlockContainer`, which the- // channel block does not render — so `blockHotkeyScopeSignal` stayed empty- // here and `useBlockEntityCommands` registered nothing at all. Own the scope- // directly instead of adopting BlockContainer and its entity tracking.- const [attachHotkeys, hotkeyScope] = useHotkeyDOMScope('channel');- blockHotkeyScopeSignal.set(hotkeyScope);- useBlockEntityCommands();-+ // channel block does not render — so set `blockHotkeyScopeSignal` here or+ // `useBlockEntityCommands` would register nothing at all. Commands go on+ // the split scope so they keep working while focus sits on split chrome+ // (header, toolbar, panel div) and across in-split navigation — same as+ // BlockContainer. The adapter requires a split panel, so unlike+ // BlockContainer it needs no fallback DOM scope of its own.const splitPanel = useSplitPanelOrThrow();+ blockHotkeyScopeSignal.set(splitPanel.splitHotkeyScope);+ useBlockEntityCommands();const canAutofocusSplitContent = useCanAutofocusSplitContent();const { navigatedFromJK } = useNavigatedFromJK();const channelId = useBlockId();@@ -513,7 +513,6 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {onHandled={() => setPendingJoinCall(false)}/><div- ref={attachHotkeys}class={cn('h-full flex flex-col px-2 touch:px-0',// The channel block is full-frame on mobile (messages scrolldiff --git a/apps/web/src/features/devtools/HotkeyDebugger.tsx b/apps/web/src/features/devtools/HotkeyDebugger.tsxindex 888b0b60b6..1032800843 100644--- a/apps/web/src/features/devtools/HotkeyDebugger.tsx+++ b/apps/web/src/features/devtools/HotkeyDebugger.tsx@@ -1,8 +1,12 @@import { SplitHeaderLeft } from '@components/app/split-layout/components/SplitHeader';import { StaticSplitLabel } from '@components/app/split-layout/components/SplitLabel';-import { activeScope, hotkeyScopeTree } from '@core/hotkey/state';+import { activeScope, hotkeyScopeTree, pressedKeys } from '@core/hotkey/state';import type { HotkeyCommand, ValidHotkey } from '@core/hotkey/types';-import { prettyPrintHotkeyString } from '@core/hotkey/utils';+import {+ getCommandsForHotkey,+ getKeyString,+ prettyPrintHotkeyString,+} from '@core/hotkey/utils';import { cn } from '@ui';import { createMemo, For, Show } from 'solid-js';@@ -30,14 +34,23 @@ export default function HotkeyDebugger() {let current = hotkeyScopeTree.get(active);let scopeLevel = 0;while (current) {- const scopeCommands = [- ...Array.from(current.hotkeyCommands.values()).flat(),- ...current.unkeyedCommands,- ];- for (const command of scopeCommands) {+ const scopeNode = current;+ for (const command of scopeNode.commands) {const hotkeys = command.hotkeys ?? [];- const hotkeyIsShadowed = hotkeys.some((hk) => hotkeySet.has(hk));- for (const hk of hotkeys) hotkeySet.add(hk);+ // A command eclipsed within its own scope (a later 'override' on all+ // of its keys) can't fire: mark it shadowed and don't let it claim+ // keys for the cross-scope shadow check — otherwise the override+ // that actually runs would be the one shown struck through.+ const isEclipsed =+ hotkeys.length > 0 &&+ !hotkeys.some((hk) =>+ getCommandsForHotkey(scopeNode, hk).includes(command)+ );+ const hotkeyIsShadowed =+ isEclipsed || hotkeys.some((hk) => hotkeySet.has(hk));+ if (!isEclipsed) {+ for (const hk of hotkeys) hotkeySet.add(hk);+ }out.push({...command,scopeLevel,@@ -81,6 +94,12 @@ export default function HotkeyDebugger() {active scope:{' '}<span class="font-semibold text-ink">{activeScope()}</span></span>+ <span class="text-ink-muted">+ pressed keys:{' '}+ <span class="font-semibold text-ink">+ {getKeyString(pressedKeys()) || '—'}+ </span>+ </span><span class="ml-auto text-ink-muted">{commands().length} commands</span>diff --git a/apps/web/src/features/next-soup/soup-view/use-soup-navigation-hotkeys.ts b/apps/web/src/features/next-soup/soup-view/use-soup-navigation-hotkeys.tsindex 8d8a191905..740865dfe3 100644--- a/apps/web/src/features/next-soup/soup-view/use-soup-navigation-hotkeys.ts+++ b/apps/web/src/features/next-soup/soup-view/use-soup-navigation-hotkeys.ts@@ -267,6 +267,7 @@ export const useSoupNavigationHotkeys = (condition: canRunListNavigation,keyDownHandler: navigateDown,hide: true,+ disposeWithOwner: false,});registerHotkey({@@ -288,6 +289,7 @@ export const useSoupNavigationHotkeys = (condition: canRunListNavigation,keyDownHandler: navigateUp,hide: true,+ disposeWithOwner: false,});registerHotkey({diff --git a/apps/web/src/features/next-soup/soup-view/use-soup-view-hotkeys.ts b/apps/web/src/features/next-soup/soup-view/use-soup-view-hotkeys.tsindex 47d1f8e23d..dcc9c52a37 100644--- a/apps/web/src/features/next-soup/soup-view/use-soup-view-hotkeys.ts+++ b/apps/web/src/features/next-soup/soup-view/use-soup-view-hotkeys.ts@@ -304,9 +304,15 @@ export const useSoupViewHotkeys = (options: UseSoupViewHotkeysOptions) => {}).withGroup(group);// escape - Multi-purpose: Clear selection / Close spotlight+ // Deliberately outside the group and kept past this view's unmount: the+ // soup selection and split spotlight it acts on live at the split-panel+ // level, so escape keeps working after a list entity is opened in place.+ // The token is required for a persistent registration: same-token override+ // replacement is what dedupes it when this view remounts on the same split.registerHotkey({hotkey: ['escape'],scopeId,+ hotkeyToken: TOKENS.soup.dismiss,description: escapeDescription,condition: () => clearMultiCondition() || closeSpotlightCondition(),keyDownHandler: () => {@@ -321,6 +327,7 @@ export const useSoupViewHotkeys = (options: UseSoupViewHotkeysOptions) => {}return false;},+ disposeWithOwner: false,});// shift+enter - Open in new splitdiff --git a/apps/web/src/lib/core/component/BlockContainer.tsx b/apps/web/src/lib/core/component/BlockContainer.tsxindex add6634b70..a25f2d9009 100644--- a/apps/web/src/lib/core/component/BlockContainer.tsx+++ b/apps/web/src/lib/core/component/BlockContainer.tsx@@ -1,3 +1,4 @@+import { useSplitPanel } from '@components/app/split-layout/layoutUtils';import { type BlockName, useBlockId, useBlockName } from '@core/block';import { useHotkeyDOMScope } from '@core/hotkey/hotkeys';import { isTabFocused } from '@core/signal/tabFocus';@@ -78,8 +79,26 @@ export function BlockContainer(props: BlockContainerProps) {if (pingInterval) clearInterval(pingInterval);});- const [attachHotkeys, scopeId] = useHotkeyDOMScope(blockName ?? 'block');- setHotkeyScope(scopeId);+ // Block commands register on the split scope: it covers the whole panel+ // (header, toolbar, the focusable panel div), so block hotkeys keep working+ // while focus sits on split chrome outside the block element, and it stays+ // active across in-split navigation. The block gets no DOM scope of its+ // own. Registrations must+ // dispose with their owner (registerHotkey does this automatically) since+ // the split scope survives split navigation.+ //+ // Only a block rendered without a split panel gets its own DOM scope,+ // attached to the block element — a scope that is never attached can never+ // activate, so commands registered to it would silently never run.+ const splitPanel = useSplitPanel();+ let attachFallbackHotkeyScope: ((el: Element) => void) | undefined;+ if (splitPanel) {+ setHotkeyScope(splitPanel.splitHotkeyScope);+ } else {+ const [attachHotkeys, scopeId] = useHotkeyDOMScope(blockName ?? 'block');+ attachFallbackHotkeyScope = attachHotkeys;+ setHotkeyScope(scopeId);+ }const resolved = children(() => props.children);createEffect(() => {@@ -91,7 +110,7 @@ export function BlockContainer(props: BlockContainerProps) {resolved_.id = getBlockElementId(blockId);resolved_.dataset.blockType = blockName;setElement(resolved_);- attachHotkeys(resolved_);+ attachFallbackHotkeyScope?.(resolved_);});return (diff --git a/apps/web/src/lib/core/dom-selectors.ts b/apps/web/src/lib/core/dom-selectors.tsindex 0d1d5dd849..21eece4373 100644--- a/apps/web/src/lib/core/dom-selectors.ts+++ b/apps/web/src/lib/core/dom-selectors.ts@@ -1,6 +1,15 @@export const SPLIT_CONTAINER_DATA_ATTRIBUTE = 'data-split-container';export const SOUP_LIST_CONTAINER_DATA_ATTRIBUTE = 'data-soup-list-container';export const ENTITY_ID_DATA_ATTRIBUTE = 'data-entity-id';+/**+ * Marks a hotkey-neutral region: chrome that lives outside every split (the+ * sidebar, the dock) where taking focus should NOT change the active hotkey+ * scope. Without it, focusing anything outside a DOM scope activates the+ * 'global' scope, muting every split/block command until the user clicks back+ * into a split. Overlays (dialogs, menus) must NOT be marked neutral — their+ * fall-through to 'global' is what mutes app hotkeys beneath them.+ */+export const HOTKEY_SCOPE_NEUTRAL_DATA_ATTRIBUTE = 'data-hotkey-scope-neutral';export const splitContainerAttribute = {[SPLIT_CONTAINER_DATA_ATTRIBUTE]: true,@@ -13,7 +22,12 @@ export function entityIdAttribute(entityId: string) {return { [ENTITY_ID_DATA_ATTRIBUTE]: entityId } as const;}+export const hotkeyScopeNeutralAttribute = {+ [HOTKEY_SCOPE_NEUTRAL_DATA_ATTRIBUTE]: true,+} as const;+export const splitContainerSelector = `[${SPLIT_CONTAINER_DATA_ATTRIBUTE}]`;+export const hotkeyScopeNeutralSelector = `[${HOTKEY_SCOPE_NEUTRAL_DATA_ATTRIBUTE}]`;export const soupListContainerSelector = `[${SOUP_LIST_CONTAINER_DATA_ATTRIBUTE}]`;export function entityIdSelector(entityId: string): string {diff --git a/apps/web/src/lib/core/hotkey/eclipse-override.test.ts b/apps/web/src/lib/core/hotkey/eclipse-override.test.tsnew file mode 100644index 0000000000..4e58be944d--- /dev/null+++ b/apps/web/src/lib/core/hotkey/eclipse-override.test.ts@@ -0,0 +1,146 @@+import { createRoot } from 'solid-js';+import { afterEach, describe, expect, test } from 'vitest';+import { registerHotkey } from './hotkeys';+import { hotkeyScopeTree, hotkeyTokenMap } from './state';+import type { HotkeyToken } from './tokens';+import type { ValidHotkey } from './types';+import { getCommandsForHotkey, registerScope, removeScope } from './utils';++let scopeCounter = 0;+const createdScopes: string[] = [];++function makeScope(): string {+ const scopeId = `eclipse-test-scope-${scopeCounter++}`;+ registerScope({ parentScopeId: 'global', scopeId, type: 'dom' });+ createdScopes.push(scopeId);+ return scopeId;+}++afterEach(() => {+ for (const scopeId of createdScopes) {+ if (hotkeyScopeTree.has(scopeId)) removeScope(scopeId);+ }+ createdScopes.length = 0;+});++/** The registered commands for a key, in registration order, eclipsed included. */+function rawCommands(scopeId: string, key: ValidHotkey) {+ return (+ hotkeyScopeTree+ .get(scopeId)+ ?.commands.filter((c) => c.hotkeys?.includes(key)) ?? []+ );+}++/** Descriptions of the commands that would currently run for a key. */+function effectiveDescriptions(scopeId: string, key: ValidHotkey): string[] {+ const scopeNode = hotkeyScopeTree.get(scopeId);+ if (!scopeNode) return [];+ return getCommandsForHotkey(scopeNode, key).map(+ (c) => c.description as string+ );+}++function register(+ scopeId: string,+ description: string,+ options: Partial<Parameters<typeof registerHotkey>[0]> = {}+) {+ return registerHotkey({+ scopeId,+ description,+ hotkey: 'x',+ keyDownHandler: () => true,+ ...options,+ });+}++describe('eclipse override', () => {+ test('an override eclipses earlier commands and disposal restores them', () => {+ const scopeId = makeScope();+ const first = register(scopeId, 'first');+ const second = register(scopeId, 'second');++ // Both stay registered; only the newest override is effective.+ expect(rawCommands(scopeId, 'x')).toHaveLength(2);+ expect(effectiveDescriptions(scopeId, 'x')).toEqual(['second']);++ second.dispose();+ expect(effectiveDescriptions(scopeId, 'x')).toEqual(['first']);++ first.dispose();+ expect(rawCommands(scopeId, 'x')).toHaveLength(0);+ });++ test("an 'add' command coexists with an earlier override", () => {+ const scopeId = makeScope();+ const override = register(scopeId, 'override');+ register(scopeId, 'added', { registrationType: 'add' });++ expect(effectiveDescriptions(scopeId, 'x')).toEqual(['override', 'added']);++ override.dispose();+ expect(effectiveDescriptions(scopeId, 'x')).toEqual(['added']);+ });++ test('a later override eclipses earlier override and add together', () => {+ const scopeId = makeScope();+ register(scopeId, 'first');+ register(scopeId, 'added', { registrationType: 'add' });+ const last = register(scopeId, 'last');++ expect(effectiveDescriptions(scopeId, 'x')).toEqual(['last']);++ last.dispose();+ expect(effectiveDescriptions(scopeId, 'x')).toEqual(['first', 'added']);+ });++ test('a same-token override replaces the previous registration instead of stacking', () => {+ const scopeId = makeScope();+ const token = 'eclipse-test:same-token' as HotkeyToken;+ const first = register(scopeId, 'first', { hotkeyToken: token });+ register(scopeId, 'second', { hotkeyToken: token });++ expect(rawCommands(scopeId, 'x')).toHaveLength(1);+ expect(effectiveDescriptions(scopeId, 'x')).toEqual(['second']);+ expect(hotkeyTokenMap().get(token)).toHaveLength(1);++ // Disposing the replaced registration must not disturb the replacement.+ first.dispose();+ expect(effectiveDescriptions(scopeId, 'x')).toEqual(['second']);+ expect(hotkeyTokenMap().get(token)).toHaveLength(1);+ });++ test('a same-token override replaces a previous unkeyed registration', () => {+ const scopeId = makeScope();+ const token = 'eclipse-test:unkeyed-token' as HotkeyToken;+ register(scopeId, 'first', { hotkey: undefined, hotkeyToken: token });+ register(scopeId, 'second', { hotkey: undefined, hotkeyToken: token });++ const unkeyed =+ hotkeyScopeTree.get(scopeId)?.commands.filter((c) => !c.hotkeys) ?? [];+ expect(unkeyed.map((c) => c.description)).toEqual(['second']);+ expect(hotkeyTokenMap().get(token)).toHaveLength(1);+ });+});++describe('owner-bound disposal', () => {+ test('registrations dispose with their reactive owner unless opted out', () => {+ const scopeId = makeScope();+ const dispose = createRoot((disposeRoot) => {+ register(scopeId, 'owned');+ register(scopeId, 'persistent', {+ hotkey: 'y',+ disposeWithOwner: false,+ });+ return disposeRoot;+ });++ expect(effectiveDescriptions(scopeId, 'x')).toEqual(['owned']);+ expect(effectiveDescriptions(scopeId, 'y')).toEqual(['persistent']);++ dispose();+ expect(rawCommands(scopeId, 'x')).toHaveLength(0);+ expect(effectiveDescriptions(scopeId, 'y')).toEqual(['persistent']);+ });+});diff --git a/apps/web/src/lib/core/hotkey/getCommands.ts b/apps/web/src/lib/core/hotkey/getCommands.tsindex 4012435b0e..5aa574d8f5 100644--- a/apps/web/src/lib/core/hotkey/getCommands.ts+++ b/apps/web/src/lib/core/hotkey/getCommands.ts@@ -3,6 +3,7 @@ import { isEditableInput } from '@core/util/isEditableInput';import { createMemo } from 'solid-js';import { activeScope, hotkeyScopeTree } from './state';import type { HotkeyCommand, ValidHotkey } from './types';+import { getCommandsForHotkey } from './utils';type sortAndFilterOptions = {// orders commands from the active scope to the global scope, sub-ordered by displayPriority@@ -45,14 +46,19 @@ export function getActiveCommandsFromScope(const commands: CommandWithInfo[] = [];let scopeLevel = 0;while (currentScopeNode) {- // Flatten the arrays of commands from hotkeyCommands (each hotkey can have multiple handlers)- const allHotkeyCommands = Array.from(- currentScopeNode?.hotkeyCommands.values() ?? []- ).flat();- const scopeCommands = [- ...allHotkeyCommands,- ...(currentScopeNode?.unkeyedCommands ?? []),- ]+ const scopeNode = currentScopeNode;+ // A command is enumerable when it is unkeyed (command-palette only) or+ // currently effective on at least one of its keys. Eclipsed commands —+ // older registrations an 'override' displaced — are omitted; they aren't+ // runnable until the override is disposed.+ const scopeCommands = scopeNode.commands+ .filter(+ (command) =>+ !command.hotkeys ||+ command.hotkeys.some((hk) =>+ getCommandsForHotkey(scopeNode, hk).includes(command)+ )+ ).filter(filterCommands(displayOptions)).map((command) => {const hotkeys = command.hotkeys ?? [];diff --git a/apps/web/src/lib/core/hotkey/hotkeys.ts b/apps/web/src/lib/core/hotkey/hotkeys.tsindex 60b63ac6fc..ec5669ddf9 100644--- a/apps/web/src/lib/core/hotkey/hotkeys.ts+++ b/apps/web/src/lib/core/hotkey/hotkeys.ts@@ -1,9 +1,10 @@import { IS_MAC } from '@core/constant/isMac';+import { hotkeyScopeNeutralSelector } from '@core/dom-selectors';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { isEditableInput } from '@core/util/isEditableInput';import { Telemetry } from '@macro-inc/observability';-import { onCleanup, onMount, untrack } from 'solid-js';+import { getOwner, onCleanup, onMount, untrack } from 'solid-js';import {EVENT_MODIFIER_KEYS,EVENT_MODIFIER_NAME_MAP,@@ -14,6 +15,7 @@ import {} from './constants';import {activeScope,+ findLastLiveActiveDOMScope,hotkeyScopeTree,hotkeysAwaitingKeyUp,hotkeyTokenMap,@@ -37,6 +39,7 @@ import {activateClosestDOMScope,findClosestParentScopeElement,findClosestParentScopeId,+ getCommandsForHotkey,getKeyString,getScopeId,normalizeEventKeyPress,@@ -87,7 +90,11 @@ import {* @param args.tags - Optional tags for categorizing in the command palette.* @returns An object with a dispose function to clean up the hotkey* registration. If `activateCommandScope` is true, it also includes the- * `commandScopeId`.+ * `commandScopeId`. When called under a reactive owner, the registration is+ * also disposed automatically with that owner — commands can attach to scopes+ * that outlive their registrant (block commands live on the split scope,+ * which survives split navigation), so they must not depend on scope teardown+ * for cleanup.** @example* // Basic usage@@ -134,6 +141,7 @@ export function registerHotkey(surfaceNestedCommands,shouldReturnFocusOnClose,proxiedHotkey,+ disposeWithOwner,} = args;const noopDisposer: RegisterHotkeyReturn = {@@ -220,6 +228,7 @@ export function registerHotkey(const command: HotkeyCommand = {hotkeyToken,scopeId,+ registrationType,hotkeys,condition,description,@@ -242,19 +251,22 @@ export function registerHotkey(proxiedHotkey,};- // Check for existing hotkeys in the scope and warn if overriding- if (registrationType === 'override') {- hotkeys?.forEach((h) => {- const existingHandlers = scopeNode.hotkeyCommands.get(h);- if (existingHandlers && existingHandlers.length > 0) {- Telemetry.warn(- `Hotkey ${h} already registered in scope ${scopeId}. Previous hotkey is being overwritten.`,- {- error: 'Hotkey already registered in scope',- }- );+ // An override re-registration of the same logical command — same token in+ // this scope — replaces the old registration outright instead of stacking:+ // persistent commands (disposeWithOwner: false) re-register on every mount+ // of their view and must not accumulate eclipsed copies.+ if (registrationType === 'override' && hotkeyToken) {+ const replaced: HotkeyCommand[] = [];+ for (let i = scopeNode.commands.length - 1; i >= 0; i--) {+ const existingCommand = scopeNode.commands[i];+ if (existingCommand && existingCommand.hotkeyToken === hotkeyToken) {+ replaced.push(existingCommand);+ scopeNode.commands.splice(i, 1);}- });+ }+ if (replaced.length > 0) {+ setHotkeyTokenMap((prev) => removeCommandsFromTokenMap(prev, replaced));+ }}if (hotkeyToken) {@@ -266,22 +278,12 @@ export function registerHotkey(});}- if (scopeNode) {- // Register each hotkey with the same command- if (hotkeys) {- hotkeys.forEach((h) => {- const existingHandlers = scopeNode.hotkeyCommands.get(h) || [];- if (registrationType === 'add') {- scopeNode.hotkeyCommands.set(h, [...existingHandlers, command]);- } else {- // Override: replace with single-element array- scopeNode.hotkeyCommands.set(h, [command]);- }- });- } else {- scopeNode.unkeyedCommands.push(command);- }- }+ // Commands append in registration order. An 'override' command eclipses+ // the commands registered before it on its keys (see getCommandsForHotkey)+ // rather than destroying them, so disposing it restores whatever it+ // displaced — a block taking over a split-scope key does not permanently+ // disable it.+ scopeNode.commands.push(command);const primaryHotkey = hotkeys?.[0];const prettyHotkey = primaryHotkey@@ -289,9 +291,15 @@ export function registerHotkey(: undefined;// Create disposer object+ let disposed = false;const disposer: RegisterHotkeyReturn = {hotkey: () => prettyHotkey,dispose: () => {+ // Idempotent: manual disposal (groups, effect re-runs) and the+ // owner-bound auto-dispose below may both fire.+ if (disposed) return;+ disposed = true;+// Remove from hotkey token map if it existsif (hotkeyToken) {setHotkeyTokenMap((prev) =>@@ -299,31 +307,12 @@ export function registerHotkey();}- // Remove this specific command from scope's hotkey handlers+ // Remove this specific command from its scopeconst scope = hotkeyScopeTree.get(scopeId);if (scope) {- if (hotkeys) {- hotkeys.forEach((h) => {- const existingHandlers = scope.hotkeyCommands.get(h);- if (existingHandlers) {- const newHandlers = existingHandlers.filter((c) => c !== command);- if (newHandlers.length > 0) {- scope.hotkeyCommands.set(h, newHandlers);- } else {- scope.hotkeyCommands.delete(h);- }- }- });- } else {- // Unkeyed commands are pushed onto `unkeyedCommands` at registration- // (see above). Without this branch they leaked until the whole scope- // was removed — re-registering unkeyed commands (e.g. per-favorite- // command-menu entries) grew the list unboundedly and left ghost- // rows for removed/renamed entries.- const idx = scope.unkeyedCommands.indexOf(command);- if (idx !== -1) {- scope.unkeyedCommands.splice(idx, 1);- }+ const idx = scope.commands.indexOf(command);+ if (idx !== -1) {+ scope.commands.splice(idx, 1);}}@@ -339,6 +328,15 @@ export function registerHotkey(},};+ // A registration made under a reactive owner must not outlive it: the+ // target scope can persist past the registrant (the split scope survives+ // split navigation), and a leaked command would keep running with closures+ // over unmounted state. `disposeWithOwner: false` opts out for commands+ // meant to persist past their registrant (see HotkeyRegistrationOptions).+ if (disposeWithOwner !== false && getOwner()) {+ onCleanup(() => disposer.dispose());+ }+return disposer;}@@ -531,7 +529,7 @@ export function useHotkeyDOMScope(}export function attachGlobalDOMScope(el: Element) {- const handleFocusIn = () => {+ const handleFocusIn = (e: Event) => {window.clearTimeout(focusoutTimoutId);// just in case focusin fires before focusout@@ -539,8 +537,35 @@ export function attachGlobalDOMScope(el: Element) {window.clearTimeout(focusoutTimoutId);});+ // Focus landing in a neutral region (e.g. the sidebar) must not flip the+ // scope to 'global': that would mute every split/block command just+ // because the user clicked chrome that lives outside the splits. Overlays+ // without a scope of their own (dialogs, menus) are not neutral on+ // purpose — activating 'global' is what mutes app hotkeys beneath them.+ const isNeutralTarget =+ e.target instanceof Element &&+ e.target.closest(hotkeyScopeNeutralSelector) !== null;+if (!scopeActivatedByFocusIn) {- setActiveScope('global');+ if (isNeutralTarget) {+ // A neutral region preserves a live scope but must not preserve a+ // decayed one. Opening an overlay from the sidebar moves focus into+ // a body portal (activating 'global'), and closing it returns focus+ // to the trigger; overlays that own a scope (the launcher) also+ // remove it on close. When the current scope is 'global' or gone,+ // restore the most recent live DOM scope instead.+ const currentScopeId = activeScope();+ const currentIsLive =+ currentScopeId !== 'global' && hotkeyScopeTree.has(currentScopeId);+ if (!currentIsLive) {+ const lastLiveScope = findLastLiveActiveDOMScope();+ if (lastLiveScope) {+ setActiveScope(lastLiveScope);+ }+ }+ } else {+ setActiveScope('global');+ }}scopeActivatedByFocusIn = false;};@@ -573,7 +598,18 @@ export function useHotKeyRoot() {let onHotkeyInterceptor: ((context: HotkeyInterceptorContext) => boolean)[] =[];+ // Synthetic keyboard events must not reach the hotkey system: several+ // components dispatch keydowns to drive Kobalte (e.g.+ // highlightFirstMenuItemOnOpen sends ArrowDown, with no paired keyup), and a+ // keydown without its keyup leaves a phantom key stuck in pressedKeys that+ // makes every subsequent plain-key hotkey resolve to e.g. 'arrowdown+j'+ // until a modifier keyup clears the set. Tests simulate keypresses with+ // dispatched (untrusted) events, so they stay exempt.+ const shouldIgnoreKeyEvent = (e: KeyboardEvent) =>+ !e.isTrusted && import.meta.env.MODE !== 'test';+const handleKeyDown = (e: KeyboardEvent) => {+ if (shouldIgnoreKeyEvent(e)) return;document.documentElement.dataset.modality = 'keyboard';const key = normalizeEventKeyPress(e);@@ -615,6 +651,7 @@ export function useHotKeyRoot() {};const handleKeyUp = (e: KeyboardEvent) => {+ if (shouldIgnoreKeyEvent(e)) return;const key = normalizeEventKeyPress(e);// if we are releasing a modifier key, release all keys, because the user may have triggered some broswer or os shortcut@@ -690,8 +727,8 @@ export function useHotKeyRoot() {let commandScopeActivated = false;while (scopeNode) {- const commands = scopeNode.hotkeyCommands.get(pressedKeysString);- if (commands && commands.length > 0) {+ const commands = getCommandsForHotkey(scopeNode, pressedKeysString);+ if (commands.length > 0) {// Sort commands by handlerPriority (higher priority first)const sortedCommands = [...commands].sort((a, b) => (b.handlerPriority ?? 0) - (a.handlerPriority ?? 0)diff --git a/apps/web/src/lib/core/hotkey/scope-activation.test.ts b/apps/web/src/lib/core/hotkey/scope-activation.test.tsnew file mode 100644index 0000000000..c1c565b03d--- /dev/null+++ b/apps/web/src/lib/core/hotkey/scope-activation.test.ts@@ -0,0 +1,114 @@+import { createRoot } from 'solid-js';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { HOTKEY_SCOPE_NEUTRAL_DATA_ATTRIBUTE } from '../dom-selectors';+import { attachGlobalDOMScope, useHotkeyDOMScope } from './hotkeys';+import { activeScope, setActiveScope } from './state';++let container: HTMLDivElement;+let scopeEl: HTMLDivElement;+let neutralButton: HTMLButtonElement;+let plainButton: HTMLButtonElement;+let scopeId: string;+let disposeRoot: () => void;++const focusIn = (el: Element) => {+ el.dispatchEvent(new FocusEvent('focusin', { bubbles: true }));+};++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);++ scopeEl = document.createElement('div');++ const neutralZone = document.createElement('div');+ neutralZone.setAttribute(HOTKEY_SCOPE_NEUTRAL_DATA_ATTRIBUTE, '');+ neutralButton = document.createElement('button');+ neutralZone.appendChild(neutralButton);++ plainButton = document.createElement('button');++ container.append(scopeEl, neutralZone, plainButton);++ disposeRoot = createRoot((dispose) => {+ attachGlobalDOMScope(container);+ const [attachHotkeys, id] = useHotkeyDOMScope('scope-activation-test');+ attachHotkeys(scopeEl);+ scopeId = id;+ return dispose;+ });+});++afterEach(() => {+ disposeRoot();+ container.remove();+ setActiveScope('global');+});++describe('scope activation on focusin', () => {+ test('focus inside a DOM scope activates it', () => {+ focusIn(scopeEl);+ expect(activeScope()).toBe(scopeId);+ });++ test('focus in a neutral region keeps the current scope active', () => {+ focusIn(scopeEl);+ expect(activeScope()).toBe(scopeId);++ focusIn(neutralButton);+ expect(activeScope()).toBe(scopeId);++ // The neutral focusin must not leave the inner-scope-claimed flag set:+ // the next unscoped focus still falls through to global.+ focusIn(plainButton);+ expect(activeScope()).toBe('global');+ });++ test('focus outside scopes and neutral regions falls through to global', () => {+ focusIn(scopeEl);+ expect(activeScope()).toBe(scopeId);++ focusIn(plainButton);+ expect(activeScope()).toBe('global');+ });++ // The sidebar account-menu flow: opening the menu moves focus into a body+ // portal (unscoped → 'global'), closing it returns focus to the trigger in+ // the neutral sidebar. Preserving the decayed 'global' scope would leave+ // split hotkeys dead until the user clicks back into a split.+ test('returning to a neutral region after the scope decayed to global restores the last live scope', () => {+ focusIn(scopeEl);+ focusIn(plainButton);+ expect(activeScope()).toBe('global');++ focusIn(neutralButton);+ expect(activeScope()).toBe(scopeId);+ });++ // The sidebar create-menu flow: the launcher owns its own scope, which is+ // removed when it closes — so the most recent scope is dead and the one+ // before it is the scope to restore.+ test('restores the previous live scope when the last active scope was removed', () => {+ focusIn(scopeEl);++ let scopeBId = '';+ const scopeBEl = document.createElement('div');+ container.appendChild(scopeBEl);+ const disposeB = createRoot((dispose) => {+ const [attachHotkeys, id] = useHotkeyDOMScope('scope-activation-test-b');+ attachHotkeys(scopeBEl);+ scopeBId = id;+ return dispose;+ });++ focusIn(scopeBEl);+ expect(activeScope()).toBe(scopeBId);++ disposeB();+ scopeBEl.remove();+ expect(activeScope()).toBe('global');++ focusIn(neutralButton);+ expect(activeScope()).toBe(scopeId);+ });+});diff --git a/apps/web/src/lib/core/hotkey/state.ts b/apps/web/src/lib/core/hotkey/state.tsindex 3ee2f9f55c..12e710f48b 100644--- a/apps/web/src/lib/core/hotkey/state.ts+++ b/apps/web/src/lib/core/hotkey/state.ts@@ -11,8 +11,7 @@ const initialTree = new Map<string, ScopeNode>([scopeId: 'global',type: 'dom',childScopeIds: [],- hotkeyCommands: new Map(),- unkeyedCommands: [],+ commands: [],detached: true,},],@@ -23,13 +22,45 @@ export const hotkeyScopeTree = initialTree;export const [activeScope, setActiveScopeInner] =createSignal<string>('global');+// The non-global DOM scopes that were most recently active, newest last.+// Lets neutral regions restore a real scope after the active scope decayed+// to 'global' while focus was away in an overlay (see attachGlobalDOMScope).+// A history rather than a single value because the decay often happens by+// removing the scope that was active (e.g. closing the launcher, which owns+// its own scope) — the scope to restore is then the previous live one.+const activeDOMScopeHistory: string[] = [];+const ACTIVE_DOM_SCOPE_HISTORY_LIMIT = 20;+export function setActiveScope(...params: Parameters<typeof setActiveScopeInner>) {const scopeId = setActiveScopeInner(...params);+ if (scopeId !== 'global' && hotkeyScopeTree.get(scopeId)?.type === 'dom') {+ const existing = activeDOMScopeHistory.indexOf(scopeId);+ if (existing !== -1) activeDOMScopeHistory.splice(existing, 1);+ activeDOMScopeHistory.push(scopeId);+ if (activeDOMScopeHistory.length > ACTIVE_DOM_SCOPE_HISTORY_LIMIT) {+ activeDOMScopeHistory.shift();+ }+ }updateActiveScopeBranch(scopeId);}+/**+ * The most recently active DOM scope that still exists. Dead entries are+ * pruned as they are found.+ */+export function findLastLiveActiveDOMScope(): string | undefined {+ for (let i = activeDOMScopeHistory.length - 1; i >= 0; i--) {+ const scopeId = activeDOMScopeHistory[i];+ if (scopeId && hotkeyScopeTree.get(scopeId)?.type === 'dom') {+ return scopeId;+ }+ activeDOMScopeHistory.splice(i, 1);+ }+ return undefined;+}+export const [pressedKeys, setPressedKeys] = createSignal<Set<string>>(new Set());diff --git a/apps/web/src/lib/core/hotkey/tokens.ts b/apps/web/src/lib/core/hotkey/tokens.tsindex f0e6dd8824..22c6159dcd 100644--- a/apps/web/src/lib/core/hotkey/tokens.ts+++ b/apps/web/src/lib/core/hotkey/tokens.ts@@ -5,6 +5,7 @@ export const TOKENS = {askAi: 'soup.askAi',sort: 'soup.sort',filter: 'soup.filter',+ dismiss: 'soup.dismiss',tabs: {'0': 'soup.tabs.0','1': 'soup.tabs.1',diff --git a/apps/web/src/lib/core/hotkey/types.ts b/apps/web/src/lib/core/hotkey/types.tsindex e253ac8f09..94f7d3bcc5 100644--- a/apps/web/src/lib/core/hotkey/types.ts+++ b/apps/web/src/lib/core/hotkey/types.ts@@ -20,6 +20,12 @@ type HotkeyPriority = (typeof HOTKEY_TYPE)[number];export interface HotkeyCommand {// Used to identify the hotkey in UI elements. Needs to be unique to a particular scope.hotkeyToken?: HotkeyToken;+ // How this command was registered. An 'override' command eclipses every+ // command registered before it on the same key — they stop running until it+ // is disposed, then become effective again (see getEffectiveCommands). An+ // 'add' command coexists with earlier ones. Undefined counts as 'override',+ // the registration default.+ registrationType?: 'add' | 'override';// What scope does this hotkey belong toscopeId: string;// The hotkey strings, e.g. ['cmd+j', 'ctrl+j']@@ -217,6 +223,18 @@ export interface HotkeyRegistrationOptions {* palette with its shortcut while another system owns the actual keystroke.*/proxiedHotkey?: boolean;++ /**+ * By default a registration made under a reactive owner is disposed with+ * that owner. Set false for a registration that must intentionally outlive+ * its registrant — e.g. soup's j/k stay registered on the split scope after+ * the list view unmounts so they keep navigating the originating list from+ * the opened entity. The handler must only close over state that outlives+ * the registrant, and the caller owns disposal: via the returned disposer,+ * or by the scope's own teardown.+ * @default true+ */+ disposeWithOwner?: boolean;}export type HotkeyGroup = {@@ -242,10 +260,11 @@ export type ScopeNodeBase = {description?: string;parentScopeId?: string;childScopeIds: string[];- // Map of hotkey -> array of commands (multiple handlers can be registered for the same hotkey)- hotkeyCommands: Map<ValidHotkey, HotkeyCommand[]>;- // A list of commands that don't have hotkeys.- unkeyedCommands: HotkeyCommand[];+ // Every command registered to this scope, in registration order — the+ // single source of truth. Keyed lookups (dispatch, hotkey UI) derive from+ // it via getCommandsForHotkey; commands without hotkeys (command-palette+ // only) are the entries whose `hotkeys` is undefined.+ commands: HotkeyCommand[];// If true, this scope is detached from the DOM tree, it's parent is global.detached: boolean;};diff --git a/apps/web/src/lib/core/hotkey/utils.ts b/apps/web/src/lib/core/hotkey/utils.tsindex 7896371161..357df55e88 100644--- a/apps/web/src/lib/core/hotkey/utils.ts+++ b/apps/web/src/lib/core/hotkey/utils.ts@@ -64,6 +64,40 @@ export function removeCommandsFromTokenMap(return newMap ?? tokenMap;}+/**+ * The commands that may currently run for a key. An 'override' registration+ * eclipses every command registered before it on that key, so only the slice+ * from the newest override onward is effective. Eclipsed commands stay+ * registered — disposing the commands that eclipse them makes them effective+ * again (e.g. a block taking over a split-scope key returns it on unmount).+ */+export function getEffectiveCommands(+ commands: HotkeyCommand[] | undefined+): HotkeyCommand[] {+ if (!commands || commands.length === 0) return [];+ for (let i = commands.length - 1; i >= 0; i--) {+ const command = commands[i];+ if (command && (command.registrationType ?? 'override') === 'override') {+ return commands.slice(i);+ }+ }+ return commands;+}++/**+ * The commands that may currently run for a key in a scope: the scope's+ * commands registered for that key, in registration order, with eclipsed+ * ones removed.+ */+export function getCommandsForHotkey(+ scopeNode: ScopeNode,+ hotkey: ValidHotkey+): HotkeyCommand[] {+ return getEffectiveCommands(+ scopeNode.commands.filter((c) => c.hotkeys?.includes(hotkey))+ );+}+type GetHotkeyCommandOptions = {/*** The property to sort by. Defaults to 'handlerPriority'.@@ -105,8 +139,8 @@ function getHotkeyCommands(if (!scopeNode) return [];- const commands = scopeNode.hotkeyCommands.get(hotkey);- if (!commands || commands.length === 0) return [];+ const commands = getCommandsForHotkey(scopeNode, hotkey);+ if (commands.length === 0) return [];// Sort by the specified propertyreturn [...commands].sort((a, b) => {@@ -168,8 +202,7 @@ export function registerScope(args: RegisterScopeArgs) {description: description ?? undefined,parentScopeId: parentScopeId,childScopeIds: [],- hotkeyCommands: new Map(),- unkeyedCommands: [],+ commands: [],detached: args.detached ?? false,};@@ -205,10 +238,7 @@ export function removeScope(scopeId: string) {}// Collect all commands from this scope to remove from the global token map- const commandsToRemove = [- ...Array.from(scope.hotkeyCommands.values()).flat(),- ...scope.unkeyedCommands,- ];+ const commandsToRemove = [...scope.commands];if (commandsToRemove.length > 0) {setHotkeyTokenMap((prev) =>@@ -216,8 +246,7 @@ export function removeScope(scopeId: string) {);}- scope.hotkeyCommands.clear();- scope.unkeyedCommands.length = 0;+ scope.commands.length = 0;// if scope is in currently active scope branch, we want to "snip just above it", i.e. set active scope to closest DOM scope parent.if (scope.type === 'dom') {