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
refactor(command): refactor command menu to be look nicer, work faster, be simpler, and use quick access (#1605)
Seamus895bcbbc92ad
diff --git a/js/app/packages/app/component/GlobalHotkeys.tsx b/js/app/packages/app/component/GlobalHotkeys.tsxindex 5cfb12552b..1e9be7061f 100644--- a/js/app/packages/app/component/GlobalHotkeys.tsx+++ b/js/app/packages/app/component/GlobalHotkeys.tsx@@ -17,11 +17,7 @@ import {} from '../../block-theme/signals/themeSignals';import { applyTheme } from '../../block-theme/utils/themeUtils';import { globalSplitManager } from '../signal/splitLayout';-import {- konsoleOpen,- resetKonsoleMode,- toggleKonsoleVisibility,-} from './command/state';+import { CommandState } from './command';import { CREATABLE_BLOCKS, setCreateMenuOpen } from './Launcher';import { useSplitLayout } from './split-layout/layout';@@ -32,8 +28,7 @@ export default function GlobalShortcuts() {const { toggleSettings } = useSettingsState();const handleCommandMenu = () => {- resetKonsoleMode();- toggleKonsoleVisibility();+ CommandState.toggle();};const createCommandScope = registerHotkey({@@ -82,14 +77,14 @@ export default function GlobalShortcuts() {hotkey: 'cmd+k',scopeId: 'global',description: () => {- return konsoleOpen() ? 'Close command menu' : 'Open command menu';+ return CommandState.isOpen() ? 'Close command menu' : 'Open command menu';},keyDownHandler: () => {handleCommandMenu();return true;},displayPriority: 10,- hide: konsoleOpen,+ hide: CommandState.isOpen,runWithInputFocused: true,});diff --git a/js/app/packages/app/component/Layout.tsx b/js/app/packages/app/component/Layout.tsxindex 0aed1217b9..9132a8ef64 100644--- a/js/app/packages/app/component/Layout.tsx+++ b/js/app/packages/app/component/Layout.tsx@@ -12,7 +12,7 @@ import { createEffect, onMount, Show, Suspense } from 'solid-js';import { updateCookie } from '@core/util/cookies';import Banner from './banner/Banner';import { GlobalBulkEditEntityModal } from './bulk-edit-entity/BulkEditEntityModal';-import { KommandMenu } from './command/Konsole';+import { CommandMenu } from './command';import { PropertyEditorModal } from './property-edit-modal/PropertyEditorModal';import GlobalShortcuts from './GlobalHotkeys';import { ItemDndProvider } from './ItemDragAndDrop';@@ -103,7 +103,7 @@ export function Layout(props: RouteSectionProps) {<Show when={isAuthenticated()}><GlobalShortcuts /><Suspense>- <KommandMenu />+ <CommandMenu /></Suspense><Suspense><PropertyEditorModal />diff --git a/js/app/packages/app/component/bulk-edit-entity/BulkDeleteView.tsx b/js/app/packages/app/component/bulk-edit-entity/BulkDeleteView.tsxindex f14f193a46..f4c22cc4d2 100644--- a/js/app/packages/app/component/bulk-edit-entity/BulkDeleteView.tsx+++ b/js/app/packages/app/component/bulk-edit-entity/BulkDeleteView.tsx@@ -1,6 +1,5 @@import type { EntityData } from '@entity';import { createBulkDeleteDssItemsMutation } from '@macro-entity';-import { konsoleContextInformation } from '../command/KonsoleItem';import {BulkEditEntityModalActionFooter,BulkEditEntityModalTitle,@@ -16,9 +15,6 @@ export const BulkDeleteView = (props: {const handleDelete = async () => {try {await bulkDelete.mutateAsync(props.entities);- const context = konsoleContextInformation();- const clearSelection = context.clearSelection as (() => void) | undefined;- clearSelection?.();props.onFinish();} catch (error) {console.error('Failed to delete entities:', error);diff --git a/js/app/packages/app/component/command/CommandItem.tsx b/js/app/packages/app/component/command/CommandItem.tsxnew file mode 100644index 0000000000..9136c8790d--- /dev/null+++ b/js/app/packages/app/component/command/CommandItem.tsx@@ -0,0 +1,127 @@+import { Hotkey } from '@core/component/Hotkey';+import { hasValidHotkey } from '@core/hotkey/utils';+import { Match, Show, Switch } from 'solid-js';+import {+ type QuickAccessItem,+ isEntityItem,+ isCommandItem,+} from '@core/context/quickAccess';+import { Entity, type EntityData } from '@entity';+import { cn } from '@ui/utils/classname';+import Terminal from '@phosphor-icons/core/regular/terminal.svg?component-solid';+import { Dynamic } from 'solid-js/web';++export interface CommandItemProps {+ item: QuickAccessItem;+ index: number;+ selected: boolean;+ onSelect: (item: QuickAccessItem, openInNewSplit: boolean) => void;+ onHover: (index: number) => void;+}++function CommandItemHotkey(props: { item: QuickAccessItem }) {+ const command = () => (isCommandItem(props.item) ? props.item.data : null);+ const token = () => command()?.hotkeyToken;++ const shortcut = () => {+ const cmd = command();+ if (!cmd) return undefined;+ if (hasValidHotkey(token())) return undefined;+ return cmd.hotkeys?.[0];+ };++ const hasHotkey = () => hasValidHotkey(token()) || Boolean(shortcut());++ return (+ <Show when={hasHotkey()}>+ <div class="pr-2 flex items-center justify-center text-[0.75rem] font-medium text-ink-extra-muted">+ <div class="p-2 py-0.5 border border-edge-muted/50 rounded-xs">+ <Hotkey+ token={token()}+ shortcut={shortcut()}+ class="flex gap-1 items-center"+ />+ </div>+ </div>+ </Show>+ );+}++function CommandDisplay(props: { item: QuickAccessItem }) {+ const command = () => (isCommandItem(props.item) ? props.item.data : null);++ const description = () => {+ const cmd = command();+ if (!cmd) return '';+ return typeof cmd.description === 'function'+ ? cmd.description()+ : cmd.description;+ };++ return (+ <div class="flex items-center gap-2 flex-1 min-w-0">+ <div class="size-5 flex items-center justify-center text-ink-muted shrink-0">+ <Show when={command()?.icon} fallback={<Terminal class="size-4" />}>+ {(icon) => <Dynamic component={icon()} class="size-4" />}+ </Show>+ </div>+ <span class="truncate text-ink">{description()}</span>+ </div>+ );+}++function EntityDisplay(props: { entity: EntityData }) {+ return (+ <div class="flex items-center gap-2 flex-1 min-w-0">+ <div class="size-5 p-0.5 flex items-center justify-center text-ink-muted shrink-0">+ <Entity.Icon entity={props.entity} />+ </div>+ <Entity.Title entity={props.entity} />+ </div>+ );+}++function ItemDisplay(props: { item: QuickAccessItem }) {+ return (+ <Switch>+ <Match when={isCommandItem(props.item) && props.item}>+ {(item) => <CommandDisplay item={item()} />}+ </Match>+ <Match when={isEntityItem(props.item) && props.item}>+ {(item) => <EntityDisplay entity={item().data} />}+ </Match>+ </Switch>+ );+}++export function CommandItem(props: CommandItemProps) {+ return (+ <div+ class={cn(+ 'group flex items-center h-10 px-2 text-sm font-semibold relative',+ {+ 'bg-accent/5 outline-1 outline-accent/20 outline-offset-[-1px]':+ props.selected,+ 'hover:bg-hover/30': !props.selected,+ }+ )}+ onMouseMove={() => props.onHover(props.index)}+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ props.onSelect(props.item, e.shiftKey);+ }}+ >+ {/* Accent bar indicator */}+ <div+ class={cn('absolute h-full w-[3px] left-0 top-0 bg-accent opacity-0', {+ 'opacity-100': props.selected,+ })}+ />+ <ItemDisplay item={props.item} />+ <div class="ml-auto">+ <CommandItemHotkey item={props.item} />+ </div>+ </div>+ );+}diff --git a/js/app/packages/app/component/command/CommandMenu.tsx b/js/app/packages/app/component/command/CommandMenu.tsxnew file mode 100644index 0000000000..0a69801c7e--- /dev/null+++ b/js/app/packages/app/component/command/CommandMenu.tsx@@ -0,0 +1,629 @@+import { ClippedPanel } from '@core/component/ClippedPanel';+import { DialogWrapper } from '@core/component/DialogWrapper';+import {+ type QuickAccessItem,+ isEntityItem,+ isCommandItem,+} from '@core/context/quickAccess';+import { getActiveCommandsFromScope } from '@core/hotkey/getCommands';+import { runCommand } from '@core/hotkey/utils';+import { Dialog } from '@kobalte/core/dialog';+import { Tabs } from '@kobalte/core/tabs';+import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';+import type { BlockName, BlockAlias } from '@core/block';+import {+ createEffect,+ createMemo,+ createSelector,+ createSignal,+ For,+ on,+ onMount,+ Show,+} from 'solid-js';+import { type VirtualizerHandle, VList } from 'virtua/solid';+import { beveledCorners } from '../../../block-theme/signals/themeSignals';+import { useSplitLayout } from '../split-layout/layout';+import { CommandItem } from './CommandItem';+import { CommandState } from './state';+import { useCommandItems } from './useCommandItems';+import type { CategoryFilter } from './types';+import { itemToBlockName } from '@core/constant/allBlocks';+import { cn } from '@ui/utils/classname';+import Macro from '@macro-icons/macro-logo.svg';+import ArrowLeft from '@icon/regular/arrow-left.svg';+import { debouncedDependent } from '@core/util/debounce';+import { Hotkey } from '@core/component/Hotkey';+import { InlineEntity, type EntityData } from '@entity';++const CATEGORIES: { id: CategoryFilter; label: string }[] = [+ { id: 'all', label: 'All' },+ { id: 'channels', label: 'Channels' },+ { id: 'dms', label: 'Dms' },+ { id: 'notes', label: 'Notes' },+ { id: 'tasks', label: 'Tasks' },+ { id: 'documents', label: 'Docs' },+ { id: 'chats', label: 'Chats' },+ { id: 'projects', label: 'Projects' },+ { id: 'commands', label: 'Commands' },+];++const VIRTUAL_ITEM_HEIGHT = 40; // tailwind h-10+const MAX_LIST_HEIGHT = VIRTUAL_ITEM_HEIGHT * 8;+const EMPTY_STATE_HEIGHT = VIRTUAL_ITEM_HEIGHT * 1.5;++function getBlockNameForEntity(+ item: QuickAccessItem+): BlockName | BlockAlias | undefined {+ if (isEntityItem(item)) {+ return itemToBlockName(item.data);+ }+ return undefined; // no block for commands or users+}++export function CommandMenu() {+ const [commandMenuRef, setCommandMenuRef] = createSignal<HTMLDivElement>();++ createEffect(() => {+ const open = CommandState.isOpen();+ if (open) {+ CommandState.onMenuOpen();+ } else {+ CommandState.onMenuClose();+ }+ });++ return (+ <Dialog open={CommandState.isOpen()} onOpenChange={CommandState.setIsOpen}>+ <Dialog.Portal>+ <Dialog.Overlay class="fixed inset-0 z-modal bg-transparent" />+ <DialogWrapper>+ <div ref={setCommandMenuRef}>+ <Dialog.Content>+ <ClippedPanel tl={!beveledCorners()} active>+ <CommandMenuInner commandMenuRef={commandMenuRef} />+ </ClippedPanel>+ </Dialog.Content>+ </div>+ </DialogWrapper>+ </Dialog.Portal>+ </Dialog>+ );+}++function CommandMenuInner(props: {+ commandMenuRef: () => HTMLDivElement | undefined;+}) {+ const { openWithSplit } = useSplitLayout();++ const [attachHotkeys, hotkeyScope] = useHotkeyDOMScope('command-menu');++ const query = debouncedDependent(CommandState.query, 60);++ const filteredItems = useCommandItems(query, CommandState.categoryFilter);++ createEffect(() => {+ const items = filteredItems();+ const current = CommandState.selectedIndex();+ if (current >= items.length && items.length > 0) {+ CommandState.setSelectedIndex(items.length - 1);+ }+ });++ createEffect(+ on(query, () => {+ CommandState.setSelectedIndex(0);+ })+ );++ const selectedItem = () => {+ const items = filteredItems();+ const index = CommandState.selectedIndex();+ return items[index];+ };++ function handleItemAction(item: QuickAccessItem, openInNewSplit = false) {+ if (!item) return;++ if (isCommandItem(item)) {+ const command = item.data;++ // Check if this is a multi-stage command+ if (command.activateCommandScopeId) {+ // Get commands from the nested scope+ const nestedCommands = getActiveCommandsFromScope(+ command.activateCommandScopeId,+ {+ sortByScopeLevel: false,+ hideShadowedCommands: false,+ hideCommandsWithoutHotkeys: false,+ limitToCurrentScope: true,+ }+ );+ CommandState.setQuery('');+ CommandState.setCommandScopeCommands(nestedCommands);+ CommandState.setSelectedIndex(0);+ return;+ }++ // Regular command - close and run+ CommandState.close();+ CommandState.setQuery('');+ runCommand(command);+ return;+ }++ // Handle entity items (documents, channels, chats, etc.)+ if (isEntityItem(item)) {+ const blockName = getBlockNameForEntity(item);+ if (blockName) {+ openWithSplit(+ { type: blockName, id: item.id },+ {+ referredFrom: 'kommand-menu',+ preferNewSplit: openInNewSplit,+ }+ );+ }+ CommandState.close();+ CommandState.setQuery('');+ return;+ }++ CommandState.close();+ CommandState.setQuery('');+ }++ registerHotkey({+ hotkey: ['arrowdown', 'ctrl+j'],+ scopeId: hotkeyScope,+ description: 'Move selection down',+ keyDownHandler: () => {+ const items = filteredItems();+ if (items.length === 0) return false;+ CommandState.setSelectedIndex((prev) => (prev + 1) % items.length);+ return true;+ },+ runWithInputFocused: true,+ hide: true,+ });++ registerHotkey({+ hotkey: ['arrowup', 'ctrl+k'],+ scopeId: hotkeyScope,+ description: 'Move selection up',+ keyDownHandler: () => {+ const items = filteredItems();+ if (items.length === 0) return false;+ CommandState.setSelectedIndex(+ (prev) => (prev - 1 + items.length) % items.length+ );+ return true;+ },+ runWithInputFocused: true,+ hide: true,+ });++ registerHotkey({+ hotkey: 'enter',+ scopeId: hotkeyScope,+ description: 'Select item',+ keyDownHandler: () => {+ const item = selectedItem();+ if (item) {+ handleItemAction(item, false);+ return true;+ }+ return false;+ },+ runWithInputFocused: true,+ });++ registerHotkey({+ hotkey: 'shift+enter',+ scopeId: hotkeyScope,+ description: 'Open in new split',+ keyDownHandler: () => {+ const item = selectedItem();+ if (item) {+ handleItemAction(item, true);+ return true;+ }+ return false;+ },+ runWithInputFocused: true,+ });++ registerHotkey({+ hotkey: 'escape',+ scopeId: hotkeyScope,+ description: 'Close command menu',+ keyDownHandler: () => {+ // If in command scope, go back to main menu+ if (CommandState.commandScopeCommands().length > 0) {+ CommandState.clearCommandScopeCommands();+ CommandState.setSelectedIndex(0);+ return true;+ }+ // Entity action mode and normal mode both close the menu+ CommandState.close();+ return true;+ },+ runWithInputFocused: true,+ hide: true,+ });++ // Backspace when query is empty goes back from command scope+ registerHotkey({+ hotkey: 'backspace',+ scopeId: hotkeyScope,+ description: 'Go back',+ keyDownHandler: () => {+ // Only handle if query is empty+ if (CommandState.query() !== '') {+ return false;+ }+ // If in command scope, go back+ if (CommandState.commandScopeCommands().length > 0) {+ CommandState.clearCommandScopeCommands();+ CommandState.setSelectedIndex(0);+ return true;+ }+ // Entity action mode doesn't have "back" - just close with escape+ return false;+ },+ runWithInputFocused: true,+ hide: true,+ });++ registerHotkey({+ hotkey: 'tab',+ scopeId: hotkeyScope,+ description: 'Next category',+ keyDownHandler: () => {+ const currentIndex = CATEGORIES.findIndex(+ (c) => c.id === CommandState.categoryFilter()+ );+ const nextIndex = (currentIndex + 1) % CATEGORIES.length;+ CommandState.setCategoryFilter(CATEGORIES[nextIndex].id);+ CommandState.setSelectedIndex(0);+ return true;+ },+ runWithInputFocused: true,+ hide: true,+ });++ registerHotkey({+ hotkey: 'shift+tab',+ scopeId: hotkeyScope,+ description: 'Previous category',+ keyDownHandler: () => {+ const currentIndex = CATEGORIES.findIndex(+ (c) => c.id === CommandState.categoryFilter()+ );+ const prevIndex =+ (currentIndex - 1 + CATEGORIES.length) % CATEGORIES.length;+ CommandState.setCategoryFilter(CATEGORIES[prevIndex].id);+ CommandState.setSelectedIndex(0);+ return true;+ },+ runWithInputFocused: true,+ hide: true,+ });++ onMount(() => {+ const element = props.commandMenuRef();+ if (element) {+ attachHotkeys(element);+ }+ });++ const [isKeyboardActive, setIsKeyboardActive] = createSignal(false);++ function handleMouseEnter(index: number) {+ if (isKeyboardActive()) return;+ CommandState.setSelectedIndex(index);+ }++ // Track keyboard activity to prevent mouse hover from interfering+ createEffect(() => {+ const handleKeyDown = () => setIsKeyboardActive(true);+ const handleMouseMove = () => setIsKeyboardActive(false);++ document.addEventListener('keydown', handleKeyDown);+ document.addEventListener('mousemove', handleMouseMove);++ return () => {+ document.removeEventListener('keydown', handleKeyDown);+ document.removeEventListener('mousemove', handleMouseMove);+ };+ });++ const isInCommandScope = createMemo(+ () => CommandState.commandScopeCommands().length > 0+ );++ const isEntityActionMode = createMemo(() =>+ CommandState.isEntityActionMode()+ );++ const handleBackFromCommandScope = () => {+ CommandState.clearCommandScopeCommands();+ CommandState.setSelectedIndex(0);+ };++ // Show back button only in command scope (entity action mode just closes)+ const showBackButton = () => isInCommandScope();++ const handleBack = () => {+ if (isInCommandScope()) {+ handleBackFromCommandScope();+ }+ };++ return (+ <div class="flex flex-col">+ {/* Search Input */}+ <div class="flex items-center gap-2 bg-panel px-2 h-10 border-b border-edge-muted/50">+ <Show+ when={showBackButton()}+ fallback={+ <span class="pl-2 text-accent">+ <Macro class="size-3" />+ </span>+ }+ >+ <button+ class="pl-2 text-ink-muted hover:text-ink transition-colors"+ onClick={handleBack}+ title="Back (Esc)"+ >+ <ArrowLeft class="size-3" />+ </button>+ </Show>+ <input+ type="text"+ class="flex-1 bg-transparent border-0 outline-none focus:outline-none ring-0 focus:ring-0 text-ink-muted placeholder:text-ink-placeholder/50"+ placeholder={isEntityActionMode() ? 'Search actions...' : 'Search...'}+ value={CommandState.query()}+ onInput={(e) => CommandState.setQuery(e.currentTarget.value)}+ autofocus+ />+ </div>++ {/* Entity Action Preview Row */}+ <Show when={isEntityActionMode()}>+ <EntityActionPreview entities={CommandState.entityActionEntities()} />+ </Show>++ <Show when={!isInCommandScope() && !isEntityActionMode()}>+ <CategoryFilterTabs />+ </Show>++ <ResultsContainer+ items={filteredItems()}+ selectedIndex={CommandState.selectedIndex()}+ onSelect={(item, openInNewSplit) =>+ handleItemAction(item, openInNewSplit)+ }+ onMouseEnter={handleMouseEnter}+ />++ <CommandMenuFooter+ selectedItem={selectedItem()}+ isInCommandScope={isInCommandScope()}+ isEntityActionMode={isEntityActionMode()}+ />+ </div>+ );+}++/** Preview row showing entities being acted upon in entity action mode */+function EntityActionPreview(props: { entities: EntityData[] }) {+ const displayEntities = () => props.entities.slice(0, 2);+ const remainingCount = () => Math.max(0, props.entities.length - 2);++ return (+ <div class="flex items-center gap-2 px-3 py-2 bg-panel border-b border-edge-muted/50">+ <For each={displayEntities()}>+ {(entity) => {+ return (+ <div+ class={cn('bg-edge/20 px-2 py-1 truncate text-xs rounded-xs', {+ 'max-w-[50%]': props.entities.length === 2,+ })}+ >+ <InlineEntity entity={entity} />+ </div>+ );+ }}+ </For>+ <Show when={remainingCount() > 0}>+ <div class="text-muted-foreground text-xs px-2 py-1">+ +{remainingCount()} more+ </div>+ </Show>+ </div>+ );+}++function ResultsContainer(props: {+ items: QuickAccessItem[];+ selectedIndex: number;+ onSelect: (item: QuickAccessItem, openInNewSplit: boolean) => void;+ onMouseEnter: (index: number) => void;+}) {+ const containerHeight = () => {+ const count = props.items.length;+ if (count === 0) return EMPTY_STATE_HEIGHT;+ const totalHeight = count * VIRTUAL_ITEM_HEIGHT;+ return Math.min(MAX_LIST_HEIGHT, totalHeight);+ };++ return (+ <div+ class="bg-panel overflow-hidden transition-[height] duration-60 ease-out"+ style={{ height: `${containerHeight()}px` }}+ >+ <Show+ when={props.items.length > 0}+ fallback={+ <div class="px-4 py-4 text-center text-ink-muted">+ No results found+ </div>+ }+ >+ <VirtualizedCommandList+ items={props.items}+ selectedIndex={props.selectedIndex}+ onSelect={props.onSelect}+ onMouseEnter={props.onMouseEnter}+ />+ </Show>+ </div>+ );+}++/** Virtualized command list component */+function VirtualizedCommandList(props: {+ items: QuickAccessItem[];+ selectedIndex: number;+ onSelect: (item: QuickAccessItem, openInNewSplit: boolean) => void;+ onMouseEnter: (index: number) => void;+}) {+ let virtualizerHandle: VirtualizerHandle | undefined;++ createEffect(() => {+ const index = props.selectedIndex;+ if (index >= 0 && index < props.items.length && virtualizerHandle) {+ virtualizerHandle.scrollToIndex(index, { align: 'nearest' });+ }+ });++ const selector = createSelector(+ () => props.selectedIndex,+ (ndx, selected) => ndx === selected+ );++ return (+ <VList+ ref={(handle) => {+ virtualizerHandle = handle;+ }}+ data={props.items}+ style={{ height: '100%' }}+ class="scrollbar-hidden"+ >+ {(item, index) => (+ <CommandItem+ item={item}+ index={index()}+ selected={selector(index())}+ onSelect={props.onSelect}+ onHover={props.onMouseEnter}+ />+ )}+ </VList>+ );+}++function HotkeyHint(props: { shortcut: string; label: string }) {+ return (+ <span class="flex items-center gap-1">+ <div class="flex border border-edge-muted text-[0.625rem] rounded-xs items-center px-1.5 py-0.25 font-normal">+ <Hotkey shortcut={props.shortcut} class="space-x-1" />+ </div>+ {props.label}+ </span>+ );+}++function CommandMenuFooter(props: {+ selectedItem: QuickAccessItem | undefined;+ isInCommandScope: boolean;+ isEntityActionMode?: boolean;+}) {+ const isCommand = () =>+ props.selectedItem && isCommandItem(props.selectedItem);+ const isEntity = () => props.selectedItem && isEntityItem(props.selectedItem);++ return (+ <div class="flex items-center gap-4 px-4 py-2 bg-panel border-t border-edge-muted text-xs text-ink-extra-muted/80">+ <span class="flex items-center gap-1">+ <div class="flex gap-1">+ <div class="flex border border-edge-muted text-[0.625rem] rounded-xs items-center px-1.5 py-0.25 font-normal">+ <Hotkey shortcut="arrowup" class="space-x-1" />+ </div>+ <div class="flex border border-edge-muted text-[0.625rem] rounded-xs items-center px-1.5 py-0.25 font-normal">+ <Hotkey shortcut="arrowdown" class="space-x-1" />+ </div>+ </div>+ Navigate+ </span>++ <Show+ when={props.isInCommandScope}+ fallback={+ <Show+ when={isCommand() || props.isEntityActionMode}+ fallback={+ <Show when={isEntity()}>+ <HotkeyHint shortcut="enter" label="Open" />+ <HotkeyHint shortcut="shift+enter" label="Open in new split" />+ </Show>+ }+ >+ <HotkeyHint shortcut="enter" label="Run action" />+ </Show>+ }+ >+ <HotkeyHint shortcut="enter" label="Run action" />+ <HotkeyHint shortcut="escape" label="Back" />+ </Show>++ <Show when={!props.isInCommandScope && !props.isEntityActionMode}>+ <HotkeyHint shortcut="tab" label="Category" />+ </Show>+ <Show+ when={props.isInCommandScope}+ fallback={<HotkeyHint shortcut="escape" label="Close" />}+ >+ <HotkeyHint shortcut="escape" label="Back" />+ </Show>+ </div>+ );+}++function CategoryFilterTabs() {+ return (+ <Tabs+ value={CommandState.categoryFilter()}+ onChange={(value) => {+ if (value) {+ CommandState.setCategoryFilter(value as CategoryFilter);+ CommandState.setSelectedIndex(0);+ }+ }}+ class="border-b border-edge-muted/50"+ >+ <Tabs.List class="flex items-center px-2 py-1.5">+ <For each={CATEGORIES}>+ {(category) => (+ <Tabs.Trigger+ value={category.id}+ class={cn(+ 'px-2 py-1 text-xs border first:border-l-1 border-l-0 border-edge-muted/50 font-semibold',+ CommandState.categoryFilter() === category.id+ ? 'text-ink pattern bg-edge-muted'+ : 'text-ink-muted/70 hover:text-ink hover:bg-hover'+ )}+ tabIndex={-1}+ >+ {category.label}+ </Tabs.Trigger>+ )}+ </For>+ </Tabs.List>+ </Tabs>+ );+}diff --git a/js/app/packages/app/component/command/EmailKonsoleItem.tsx b/js/app/packages/app/component/command/EmailKonsoleItem.tsxdeleted file mode 100644index 131d77f603..0000000000--- a/js/app/packages/app/component/command/EmailKonsoleItem.tsx+++ /dev/null@@ -1,23 +0,0 @@-import EnvelopSimple from '@icon/regular/envelope-simple.svg';-import { CustomEntityIcon } from 'core/component/EntityIcon';--interface EmailCommandItemProps {- sender: string;- subject: string;-}--export function EmailCommandItem(props: EmailCommandItemProps) {- return (- <div class="w-full flex items-center ml-auto text-ink-extra-muted h-5">- <div class="mr-2">- <CustomEntityIcon icon={EnvelopSimple} size="sm" />- </div>- <div class="w-1/4 text-ink truncate sm:text-sm text-xs font-medium">- {props.sender}- </div>- <div class="flex-1 ml-4 text-ink truncate sm:text-sm text-xs font-medium">- {props.subject}- </div>- </div>- );-}diff --git a/js/app/packages/app/component/command/FullTextModeToggle.tsx b/js/app/packages/app/component/command/FullTextModeToggle.tsxdeleted file mode 100644index 8941995448..0000000000--- a/js/app/packages/app/component/command/FullTextModeToggle.tsx+++ /dev/null@@ -1,26 +0,0 @@-import { Switch } from '@kobalte/core/switch';-import { resetKonsoleMode, setKonsoleMode } from './state';--type Props = {- checked: boolean;-};--export default function FullTextModeToggle(props: Props) {- function handleChange(enabled: boolean) {- enabled ? setKonsoleMode('FULL_TEXT_SEARCH') : resetKonsoleMode();- }-- return (- <div class="flex items-center gap-2 pr-3">- <div class="font-mono font-bold text-ink-extra-muted text-xs uppercase">- Full Text Search- </div>- <Switch checked={props.checked} onChange={handleChange}>- <Switch.Input class="sr-only" />- <Switch.Control class="inline-flex bg-edge border-2 border-transparent rounded-full focus-visible:outline-none hover:ring-1 hover:ring-edge focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 w-8 h-4 transition-colors data-[checked]:bg-accent-270">- <Switch.Thumb class="block bg-dialog rounded-full w-3 h-3 transition-transform data-[checked]:translate-x-4" />- </Switch.Control>- </Switch>- </div>- );-}diff --git a/js/app/packages/app/component/command/Konsole.tsx b/js/app/packages/app/component/command/Konsole.tsxdeleted file mode 100644index 842533a088..0000000000--- a/js/app/packages/app/component/command/Konsole.tsx+++ /dev/null@@ -1,374 +0,0 @@-import { useChannelsContext } from '@core/context/channels';-import { ClippedPanel } from '@core/component/ClippedPanel';-import { DialogWrapper } from '@core/component/DialogWrapper';-import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';-import { ENABLE_SEARCH_PAGINATION } from '@core/constant/featureFlags';-import type { CommandWithInfo } from '@core/hotkey/getCommands';-import { createFreshSearch } from '@core/util/freshSort';-import { Dialog } from '@kobalte/core/dialog';-import { Command as CommandK, useCommandState } from 'cmdk-solid';-import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';-import {- type Accessor,- createEffect,- createMemo,- createSignal,- For,- onMount,- Show,- untrack,-} from 'solid-js';-import { VList } from 'virtua/solid';-import { beveledCorners } from '../../../block-theme/signals/themeSignals';-import { KonsoleFilter } from './KonsoleFilter';-import {- type ChannelLookup,- COMMAND_ITEM_HEIGHT,- COMMAND_ITEM_MARGIN,- COMMAND_ITEM_PADDING,- CommandItemCard,- filterItemByCategory,- hydrateChannel,- setCommandCategoryIndex,- useCommandItemAction,-} from './KonsoleItem';-import {- cleanQuery,- createModeListenerEffects,- currentKonsoleMode,- debouncedLocalQuery,- debouncedSearchServiceQuery,- getModeConfig,- konsoleOpen,- lastCommandTime,- rawQuery,- setKonsoleOpen,- setLastCommandTime,- setRawQuery,- toggleKonsoleVisibility,-} from './state';-import { useCommandItems } from './useCommandItems';-import { usePaginatedSearchItems } from './useSearchItems';--// equivalent to h-96-const MAX_CONTAINER_HEIGHT = 96 * 4;--export function KommandMenu() {- const [commandKRef, setCommandKRef] = createSignal<HTMLDivElement>();-- // Clear search term and full text search after 3 seconds when menu closes- createEffect(() => {- const isOpen = konsoleOpen();- const now = Date.now();- const TIME_THRESHOLD = 5 * 1000;-- if (!isOpen) {- setLastCommandTime(now);- } else {- if (now - lastCommandTime() >= TIME_THRESHOLD) {- const mode = getModeConfig(untrack(currentKonsoleMode));- // keep the sigil (e.g., '%' for FULL_TEXT_SEARCH) so mode doesn’t flip- setRawQuery(mode.sigil);- setCommandCategoryIndex(0);- }- }- });-- return (- <StaticMarkdownContext>- <Dialog- open={konsoleOpen()}- onOpenChange={(_) => toggleKonsoleVisibility()}- >- <Dialog.Portal>- <Dialog.Overlay class="fixed inset-0 z-modal bg-transparent" />- <DialogWrapper>- <div ref={setCommandKRef}>- <Dialog.Content>- <ClippedPanel tl={!beveledCorners()} active>- <KommandMenuInner commandKRef={commandKRef} />- </ClippedPanel>- </Dialog.Content>- </div>- </DialogWrapper>- </Dialog.Portal>- </Dialog>- </StaticMarkdownContext>- );-}--export function KommandMenuInner(props: {- commandKRef: Accessor<HTMLDivElement | undefined>;-}) {- const [commandScopeCommands, setCommandScopeCommands] = createSignal<- CommandWithInfo[]- >([]);- const [attachHotkeys, konsoleHotkeyScopeId] = useHotkeyDOMScope('konsole');- const allItemMap = useCommandItems();- const allItems = createMemo(() => {- if (commandScopeCommands().length > 0) {- return commandScopeCommands().map((command) => {- const description =- typeof command.description === 'function'- ? command.description()- : command.description;- return {- type: 'command' as const,- data: {- id: description.replaceAll(' ', '-'),- name: description,- command: command,- },- };- });- }- return Array.from(allItemMap().values());- });- const channelsContext = useChannelsContext();-- const freshSearchConfig = createMemo(() => {- const query = debouncedLocalQuery();- const hasQuery = query && query.trim().length > 0;- return {- useViewedAt: true,- channelBoost: hasQuery ? 1.5 : 1.0,- fuzzyWeight: hasQuery ? 0.7 : 0.1,- timeWeight: hasQuery ? 0.3 : 0.9,- minFuzzyThreshold: hasQuery ? 0.1 : 0,- commaSeparatedChannelMatch: true,- };- });-- const searchItems = createMemo(() => {- const freshSearch = createFreshSearch<CommandItemCard>(- freshSearchConfig(),- (item) => item.data.name,- (item) => item.type === 'channel',- (_item) => ({})- );- return freshSearch(allItems(), debouncedLocalQuery()).map(- (result) => result.item- );- });-- createModeListenerEffects();-- const isFullTextSearch = createMemo(- () => currentKonsoleMode() === 'FULL_TEXT_SEARCH'- );-- // Prevent unnecessary ftsearches- const fullTextQueryOrBlank = createMemo(() => {- if (!isFullTextSearch()) return '';- return cleanQuery(debouncedSearchServiceQuery());- });-- const paginatedSearch = usePaginatedSearchItems(fullTextQueryOrBlank);- const channelLookup = () => channelsContext!.channelsById() as ChannelLookup;-- const handleLoadMore = async () => {- const loadMoreIndex = filteredItems().length - 1; // Position of "Load More" button- setIsLoadingMore(true);- try {- await paginatedSearch.loadMore();- // Set selection to first new item (where "Load More" was)- const newItems = filteredItems();- if (newItems.length > loadMoreIndex) {- const newValue = `${loadMoreIndex}-${newItems[loadMoreIndex]?.data.id}`;- setCurrentValue(newValue);- }- } finally {- setIsLoadingMore(false);- }- };-- const loadMoreItem = () => {- if (!ENABLE_SEARCH_PAGINATION) return [];- if (paginatedSearch.items().length === 0 || !paginatedSearch.hasMore()) {- return [];- }-- return [- {- type: 'loadmore',- data: {- id: 'load-more',- name: paginatedSearch.isLoading() ? 'Loading...' : 'Load More',- },- loadMoreCallback: handleLoadMore,- } as CommandItemCard,- ];- };-- // choose which items to display, based on which menu is open- const filteredItems = createMemo(() => {- if (isFullTextSearch()) {- return [...paginatedSearch.items(), ...loadMoreItem()]- .map((item) => hydrateChannel(item, channelLookup()))- .filter(filterItemByCategory);- }-- return searchItems().filter(filterItemByCategory);- });-- const itemAction = useCommandItemAction({ setCommandScopeCommands });- const [currentValue, setCurrentValue] = createSignal('');- const [isLoadingMore, setIsLoadingMore] = createSignal(false);-- const getSelectedItem = createMemo(() => {- if (!currentValue()) return undefined;- const [indexStr] = currentValue().split('|');- const index = parseInt(indexStr);- return filteredItems()[index];- });-- registerHotkey({- hotkey: 'enter',- scopeId: konsoleHotkeyScopeId,- description: 'Open in current split',- keyDownHandler: () => {- const selectedItem = getSelectedItem();- if (selectedItem) {- itemAction(selectedItem, 'open');- return false;- }- return false;- },- runWithInputFocused: true,- });-- registerHotkey({- hotkey: 'shift+enter',- scopeId: konsoleHotkeyScopeId,- description: 'Open in new split',- keyDownHandler: () => {- const selectedItem = getSelectedItem();- if (selectedItem) {- itemAction(selectedItem, 'new-split');- return true;- }- return false;- },- runWithInputFocused: true,- });-- registerHotkey({- hotkey: 'escape',- scopeId: konsoleHotkeyScopeId,- description: 'Close command menu',- keyDownHandler: () => {- setKonsoleOpen(false);- return true;- },- runWithInputFocused: true,- hide: true,- });-- const CommandKItemWrapper = (props: {- index: number;- item: CommandItemCard;- }) => {- const value = () => {- return `${props.index}|${props.item.data.id}`;- };- const selected = useCommandState((state) => value() === state.value);-- return (- <CommandK.Item value={value()}>- <CommandItemCard- item={props.item}- index={props.index}- selected={selected()}- itemAction={itemAction}- mouseEnter={() => {}}- />- </CommandK.Item>- );- };-- // HACK: the height of the container is dynamic, based on the elements- // but we need a specific height to virtualize the list- const containerHeight = createMemo(() => {- // Full text search always uses max height for consistency- if (currentKonsoleMode() === 'FULL_TEXT_SEARCH')- return `${MAX_CONTAINER_HEIGHT}px`;- const length = filteredItems().length;- if (length === 0) return 0;- let height = 0;- const count = filteredItems().length;- for (let i = 0; i < count; i++) {- if (height >= MAX_CONTAINER_HEIGHT) break;- height +=- COMMAND_ITEM_HEIGHT +- 2 * COMMAND_ITEM_PADDING +- 2 * COMMAND_ITEM_MARGIN;- }- height += COMMAND_ITEM_PADDING;- return `${Math.min(MAX_CONTAINER_HEIGHT, height)}px`;- });-- // Attach hotkey scope when element is available- onMount(() => {- const element = props.commandKRef();- if (element) {- attachHotkeys(element);- }- });-- return (- <CommandK- label="Global CommandK Menu"- class="flex flex-col gap-px w-full"- value={currentValue()}- shouldFilter={false}- onValueChange={(value) => {- if (isLoadingMore()) return;- setCurrentValue(value);- }}- >- <div class="flex items-center gap-2 bg-panel px-2 h-[40px] border-b border-edge-muted">- <span class="pl-2 pointer-events-none">❯</span>- <CommandK.Input- class="flex-1 border-0 outline-none! focus:outline-none ring-0! focus:ring-0"- onValueChange={setRawQuery}- placeholder="Search"- value={rawQuery()}- autofocus- />- </div>- <div class="bg-panel">- <KonsoleFilter />- <CommandK.List class="scrollbar-hidden">- <CommandK.Empty>- <div class="px-2 text-ink-muted min-h-[40px]">- {currentKonsoleMode() === 'FULL_TEXT_SEARCH' &&- cleanQuery().length < 3- ? 'Enter 3 or more characters to search all documents.'- : 'No results found.'}- </div>- </CommandK.Empty>- <Show- when={currentKonsoleMode() === 'FULL_TEXT_SEARCH'}- fallback={- <VList- data={filteredItems()}- style={{ height: containerHeight() }}- class="scrollbar-hidden pb-2 bg-panel"- >- {(item, index) => (- <CommandKItemWrapper index={index()} item={item} />- )}- </VList>- }- >- <For each={filteredItems()}>- {(item, index) => (- <CommandKItemWrapper index={index()} item={item} />- )}- </For>- </Show>- </CommandK.List>- </div>- </CommandK>- );-}diff --git a/js/app/packages/app/component/command/KonsoleFilter.tsx b/js/app/packages/app/component/command/KonsoleFilter.tsxdeleted file mode 100644index 1f6dd87cd5..0000000000--- a/js/app/packages/app/component/command/KonsoleFilter.tsx+++ /dev/null@@ -1,81 +0,0 @@-import { SegmentedControl } from '@core/component/FormControls/SegmentControls';-import { createMemo, onCleanup, onMount } from 'solid-js';-import {- commandCategoryIndex,- searchCategories,- setCommandCategoryIndex,-} from './KonsoleItem';-import { konsoleOpen } from './state';--export function KonsoleFilter() {- const visibleCategories = createMemo(() => {- return searchCategories- .listVisible()- .map((category, index) => {- if (searchCategories.isCategoryActive(index)) {- return category.name;- }- return null;- })- .filter(Boolean) as string[];- });-- const selectedCategoryName = createMemo(() => {- const categories = searchCategories.listVisible();- const index = commandCategoryIndex();- if (index >= 0 && index < categories.length) {- return categories[index].name;- }- return categories[0]?.name || '';- });-- const handleCategoryChange = (categoryName: string) => {- const index = searchCategories- .listVisible()- .findIndex((cat) => cat.name === categoryName);- if (index !== -1) {- setCommandCategoryIndex(index);- }- };-- onMount(() => {- const down = (e: KeyboardEvent) => {- if (!konsoleOpen()) return;- if (e.key === 'Tab') {- e.preventDefault();- e.stopPropagation();- setCommandCategoryIndex((prev) => {- let nextCategoryIndex = -1;- if (e.shiftKey) {- nextCategoryIndex = searchCategories.findNextCategoryIndex(- prev,- true- );- } else {- nextCategoryIndex = searchCategories.findNextCategoryIndex(- prev,- false- );- }- return Math.max(nextCategoryIndex, 0);- });- }- };-- document.addEventListener('keydown', down);- onCleanup(() => {- document.removeEventListener('keydown', down);- });- });-- return (- <div class="flex items-center bg-transparent border-b px-2 border-edge-muted/50 h-[40px]">- <SegmentedControl- onChange={handleCategoryChange}- value={selectedCategoryName()}- list={visibleCategories()}- size="SM"- />- </div>- );-}diff --git a/js/app/packages/app/component/command/KonsoleItem.tsx b/js/app/packages/app/component/command/KonsoleItem.tsxdeleted file mode 100644index 6f7c5cb625..0000000000--- a/js/app/packages/app/component/command/KonsoleItem.tsx+++ /dev/null@@ -1,745 +0,0 @@-import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';-import { URL_PARAMS as MD_PARAMS } from '@block-md/constants';-import { URL_PARAMS as PDF_PARAMS } from '@block-pdf/signal/location';-import type { BlockAlias, BlockName } from '@core/block';-import type { DateValue } from '@core/util/date';-import { BozzyBracket } from '@core/component/BozzyBracket';-import { Hotkey } from '@core/component/Hotkey';-import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';-import { Message } from '@core/component/Message';-import { UserIcon } from '@core/component/UserIcon';-import { fileTypeToBlockName, itemToBlockName } from '@core/constant/allBlocks';-import {- ENABLE_GMAIL_BASED_CONTACTS,- ENABLE_TASKS_TABS,-} from '@core/constant/featureFlags';-import { HotkeyTags } from '@core/hotkey/constants';-import {- type CommandWithInfo,- getActiveCommandsFromScope,-} from '@core/hotkey/getCommands';-import { pressedKeys } from '@core/hotkey/state';-import type { HotkeyCommand } from '@core/hotkey/types';-import { hasValidHotkey, runCommand } from '@core/hotkey/utils';-import type { BlockOrchestrator } from '@core/orchestrator';-import { type ChannelWithParticipants, idToDisplayName } from '@core/user';-import Terminal from '@phosphor-icons/core/regular/terminal.svg?component-solid';-import type { Channel } from '@service-comms/generated/models/channel';-import { ChannelTypeEnum } from '@service-comms/client';-import type { Attachment } from '@service-email/generated/schemas';-import { useUserId } from '@core/context/user';-import type { BasicDocumentSubTypeProperty } from '@service-storage/generated/schemas';-import type { BasicDocumentFileType } from '@service-storage/generated/schemas/basicDocumentFileType';-import type { Item } from '@service-storage/generated/schemas/item';-import { syncServiceClient } from '@service-sync/client';-import {- CustomEntityIcon,- EntityIcon,- type EntityWithValidIcon,-} from 'core/component/EntityIcon';-import {- type Component,- createMemo,- createSignal,- type JSX,- type JSXElement,- Match,- onCleanup,- onMount,- type Setter,- Show,- Switch,-} from 'solid-js';-import { createStore } from 'solid-js/store';-import { useGlobalBlockOrchestrator } from '../GlobalAppState';-import { useSplitLayout } from '../split-layout/layout';-import { EmailCommandItem } from './EmailKonsoleItem';-import {- cleanQuery,- currentKonsoleMode,- resetKonsoleMode,- resetQuery,- setKonsoleOpen,-} from './state';--//NOTE: used to help for virtualization-export const COMMAND_ITEM_PADDING = 6;-export const COMMAND_ITEM_HEIGHT = 20;-export const COMMAND_ITEM_MARGIN = 2;-export const [commandCategoryIndex, setCommandCategoryIndex] = createSignal(0);--export type ChannelLookup = Record<string, Channel>;--// Context information for actions and stuff-export const [konsoleContextInformation, setKonsoleContextInformation] =- createSignal<Record<string, unknown>>({});--// TODO: better naming?-export function hydrateChannel(- item: CommandItemCard,- lookup: ChannelLookup-): CommandItemCard {- if (item.type === 'channel') {- // TODO: error handling. what if channel doesn't exist?- const chan = lookup[item.data.id];- if (!chan) return item;- item.data.channel_type = chan.channel_type;- if (item.data.channel_type === ChannelTypeEnum.DirectMessage) {- item.data.participants = (chan as ChannelWithParticipants).participants;- }- }- return item;-}--const DEFAULT_CATEGORIES = [- { name: 'Selection', visible: false },- { name: 'Everything', visible: true },- { name: 'Channels', visible: true },- { name: 'DMs', visible: true },- { name: 'Notes', visible: true },- { name: 'Tasks', visible: ENABLE_TASKS_TABS },- { name: 'Documents', visible: true },- { name: 'Chats', visible: true },- { name: 'Folders', visible: true },- { name: 'Emails', visible: false },- { name: 'Contacts', visible: ENABLE_GMAIL_BASED_CONTACTS },- { name: 'Companies', visible: ENABLE_GMAIL_BASED_CONTACTS },-] as const;--type DefaultCategoryNames = (typeof DEFAULT_CATEGORIES)[number]['name'];--type KonsoleCategory = {- name: string;- visible: boolean;-};--const [categories, setCategories] = createStore<KonsoleCategory[]>([- ...DEFAULT_CATEGORIES,-]);--export const searchCategories = {- getCategoryIndex(name: DefaultCategoryNames | (string & {})) {- const index = categories.findIndex((c) => c.name === name);-- if (index === -1) return;-- return index;- },- hideCategory(name: DefaultCategoryNames | (string & {})) {- setCategories((p) => p.name === name, 'visible', false);- },- showCategory(name: DefaultCategoryNames | (string & {})) {- setCategories((p) => p.name === name, 'visible', true);- },- toggleCategory(name: DefaultCategoryNames | (string & {})) {- setCategories(- (p) => p.name === name,- 'visible',- (p) => !p- );- },- isCategoryActive(index: number) {- if (categories[index].name === 'Emails') {- // only use emails for the search bar- if (currentKonsoleMode() !== 'FULL_TEXT_SEARCH') return false;-- // TODO only show emails if they are enabled- // NOTE: this also seems to trigger a "computations created outside a 'createRoot' will never be disposed error- //const emailActive = useEmailActive();- const emailEnabled = () => {- // TODO: this causes a loop- //if (emailActive()?.link_exists) return true;- return true;- };- return emailEnabled();- }- return true;- },- findNextCategoryIndex(category: number, backwards: boolean): number {- let candidateCategory = -1;- const length = this.listVisible().length;- for (let i = 1; i < length; i++) {- if (backwards) {- candidateCategory = category - i;- } else {- candidateCategory = category + i;- }-- // Perform wrap-around- if (candidateCategory >= length) {- candidateCategory = 0;- } else if (candidateCategory < 0) {- candidateCategory = length + candidateCategory;- }-- if (this.isCategoryActive(candidateCategory)) break;- candidateCategory = -1;- }- return candidateCategory;- },- listVisible() {- return [...categories.filter((c) => c.visible)];- },- listAll() {- return [...categories];- },-};--export const resetCommandCategoryIndex = () => {- const everything = DEFAULT_CATEGORIES[1].name;- const indexOfEverything = searchCategories- .listVisible()- .findIndex((c) => c.name === everything);-- setCommandCategoryIndex(indexOfEverything === -1 ? 0 : indexOfEverything);-};--export type SearchSnippet = {- content: string;- locationId: string;- fileType: string;- matchIndex?: number;- senderId?: string;- // PDF/DOCX-specific fields for search navigation- searchSnippet?: string;- highlightTerms?: string[];-};--type CommandItemBase = {- snippet?: SearchSnippet;- height?: number;- updatedAt?: DateValue | null;- viewedAt?: DateValue | null;-};--type SimpleText = {- // id + name are needed to match the shape of channels/items- id: string;- name: string;- text: string;-};--type LoadMore = {- // id + name are needed to match the shape of channels/items- id: string;- name: string;-};--export type EmailPreview = {- id: string;- name: string; // subject- sender: string;- timestamp: DateValue;- is_read: boolean;- attachments: Attachment[];-};--export type ContactPreview = {- id: string; // email address- name: string;- email: string;- company?: string;-};--export type CompanyPreview = {- id: string; // domain with @ prefix- name: string; // company name- domain: string;-};--type ItemPreview = {- id: string;- name: string;- fileType?: BasicDocumentFileType;- subType?: BasicDocumentSubTypeProperty;- itemType: Item['type'];-};--export type CommandPreview = {- id: string;- icon?: Component<JSX.SvgSVGAttributes<SVGSVGElement>>;- name: string;- command: HotkeyCommand;-};--export type ChannelPreview = {- id: string;- name: string;- channel_type?: Channel['channel_type'];- participants?: ChannelWithParticipants['participants'];-};--export type CommandItemCard = (- | {- type: 'item';- data: ItemPreview;- }- | {- type: 'channel';- data: ChannelPreview;- }- | {- type: 'text';- data: SimpleText;- }- | {- type: 'email';- data: EmailPreview;- }- | {- type: 'contact';- data: ContactPreview;- }- | {- type: 'company';- data: CompanyPreview;- }- | {- type: 'loadmore';- data: LoadMore;- loadMoreCallback?: () => void;- }- | {- type: 'command';- data: CommandPreview;- }-) &- CommandItemBase;--async function gotoSnippetLocation(- orchestrator: BlockOrchestrator,- id: string,- snippet: SearchSnippet,- searchTerm: string-) {- const handle = await orchestrator.getBlockHandle(id);- if (!handle) return;- switch (snippet.fileType) {- case 'pdf':- case 'docx':- handle.goToLocationFromParams({- [PDF_PARAMS.searchPage]: snippet.locationId,- [PDF_PARAMS.searchRawQuery]: searchTerm,- [PDF_PARAMS.searchHighlightTerms]: JSON.stringify(- snippet.highlightTerms- ),- [PDF_PARAMS.searchSnippet]: snippet.searchSnippet,- });- break;- case 'chat':- handle.goToLocationFromParams({- message_id: snippet.locationId,- });- break;- case 'channel':- handle.goToLocationFromParams({- [CHANNEL_PARAMS.message]: snippet.locationId,- });- break;- case 'md':- handle.goToLocationFromParams({- [MD_PARAMS.nodeId]: snippet.locationId,- });- break;- }-}--// Actions on an item from the command palette-type ItemAction = 'open' | 'new-split';--export function useCommandItemAction(args: {- setCommandScopeCommands: Setter<CommandWithInfo[]>;-}) {- const { setCommandScopeCommands } = args;- const { openWithSplit } = useSplitLayout();- const blockOrchestrator = useGlobalBlockOrchestrator();-- return function itemAction(- item: CommandItemCard | undefined,- action: ItemAction- ) {- if (!item) return;- const blockName = getCommandItemBlockName(item);- const id = item.data.id;-- if (blockName) {- openWithSplit(- { type: blockName, id },- {- referredFrom: 'kommand-menu',- preferNewSplit: action === 'new-split',- }- );-- if (item.snippet) {- gotoSnippetLocation(blockOrchestrator, id, item.snippet, cleanQuery());- }- } else {- switch (item.type) {- case 'loadmore': {- if (item.loadMoreCallback) {- item.loadMoreCallback();- }- break;- }- case 'command': {- if (item.data.command.activateCommandScopeId) {- const commandScopeCommands = getActiveCommandsFromScope(- item.data.command.activateCommandScopeId,- {- sortByScopeLevel: false,- hideShadowedCommands: false,- hideCommandsWithoutHotkeys: false,- limitToCurrentScope: true,- }- );- resetQuery();- setCommandScopeCommands(commandScopeCommands);- break;- } else {- setKonsoleOpen(false, item.data.command.shouldReturnFocusOnClose);- resetQuery();- resetKonsoleMode();- runCommand(item.data.command);- break;- }- }- }- }-- // Clear search term when item action is triggered- if (item.type !== 'loadmore' && item.type !== 'command') {- setKonsoleOpen(false); // Split handles focus.- resetQuery();- resetKonsoleMode();- }- };-}--export interface CommandItemProps {- item: CommandItemCard;- index: number;- selected: boolean;- itemAction: (item: CommandItemCard, action: ItemAction) => void;- mouseEnter: (e: MouseEvent) => void;- snippets?: Record<string, string>;-}--function getCommandItemBlockName(- item: CommandItemCard,- icon?: boolean-): BlockName | BlockAlias | undefined {- if (item.type === 'item') {- return itemToBlockName(- {- ...item.data,- type: item.data.itemType,- },- icon- );- } else if (item.type === 'channel') {- return 'channel';- } else if (item.type === 'email') {- return 'email';- } else if (item.type === 'contact' || item.type === 'company') {- return 'contact';- } else {- return undefined;- }-}--function getCommandItemName(item: CommandItemCard): string {- return item.data.name;-}--export function filterItemByCategory(item: CommandItemCard) {- const categories = searchCategories.listVisible();- const category = categories[commandCategoryIndex()].name;-- // This should appear at the bottom of every category, if there are more items that need to be loaded- if (item.type === 'loadmore') {- return true;- }-- if (category === 'Selection') {- if (- currentKonsoleMode() === 'SELECTION_MODIFICATION' &&- item.type === 'command'- ) {- return item.data.command.tags?.includes(HotkeyTags.SelectionModification);- }- return false;- }-- // Action items should always appear in the "Everything" category- if (item.type === 'command') {- return category === 'Everything';- }-- switch (category) {- case 'Channels':- return (- item.type === 'channel' &&- (item.data.channel_type === ChannelTypeEnum.Organization ||- item.data.channel_type === ChannelTypeEnum.Private)- );- case 'DMs':- return (- item.type === 'channel' &&- item.data.channel_type === ChannelTypeEnum.DirectMessage- );- case 'Documents':- return (- item.type === 'item' &&- item.data.itemType === 'document' &&- fileTypeToBlockName(item.data.fileType) !== 'md'- );- case 'Notes':- return (- item.type === 'item' &&- item.data.itemType === 'document' &&- (!item.data.subType || item.data.subType.type !== 'task') &&- fileTypeToBlockName(item.data.fileType) === 'md'- );- case 'Tasks':- return (- item.type === 'item' &&- item.data.itemType === 'document' &&- item.data.subType !== null &&- item.data.subType !== undefined &&- item.data.subType.type === 'task'- );- case 'Chats':- return item.type === 'item' && item.data.itemType === 'chat';- case 'Emails':- return item.type === 'email';- case 'Contacts':- return item.type === 'contact';- case 'Companies':- return item.type === 'company';- case 'Folders':- return item.type === 'item' && item.data.itemType === 'project';- default:- return true;- }-}--export function CommandItemCard(props: CommandItemProps) {- const blockName = () => getCommandItemBlockName(props.item, true);- const userId = useUserId();- const name = () => {- const name = getCommandItemName(props.item);- return name && name.length > 55 ? `${name.slice(0, 52)}...` : name;- };-- onMount(() => {- if (blockName() === 'md') {- syncServiceClient.safeWakeup(props.item.data.id);- onCleanup(() => {- syncServiceClient.cancelWakeup(props.item.data.id);- });- }- });-- const CommandItemContainer = ({ children }: { children?: JSXElement }) => {- const optionKeyPressed = createMemo(() => {- return pressedKeys().has('shift');- });- return (- <div- onMouseDown={() =>- props.itemAction(- props.item,- optionKeyPressed() ? 'new-split' : 'open'- )- }- onMouseEnter={props.mouseEnter}- class="group flex flex-col px-2"- style={`margin: ${COMMAND_ITEM_MARGIN}px 0`}- >- {children}- </div>- );- };-- const CommandItemIcon = () => {- return (- <Switch>- <Match when={props.item.type === 'command'}>- <CustomEntityIcon- icon={- props.item.type === 'command'- ? (props.item.data.icon ?? Terminal)- : Terminal- }- size="sm"- />- </Match>- <Match when={blockName()}>- {(blockName) => {- let targetType: EntityWithValidIcon = blockName();-- if (- props.item.type === 'channel' &&- props.item.data.channel_type === ChannelTypeEnum.DirectMessage- ) {- const participants = props.item.data.participants;- if (participants && participants.length > 0) {- const other = participants.filter((p) => {- return p.user_id !== userId();- });- if (other.length > 0) {- return (- <UserIcon- size="sm"- suppressClick- id={other[0].user_id}- isDeleted={false}- />- );- }- targetType = 'direct_message';- }- }- if (props.item.type === 'channel' && props.item.data.channel_type) {- targetType = props.item.data.channel_type;- }- return <EntityIcon targetType={targetType} size="sm" />;- }}- </Match>- </Switch>- );- };-- const CommandItemName = () => {- return (- <span class="text-ink text-xs sm:text-sm font-medium font-sans grow overflow-hidden text-nowrap">- {name()}- </span>- );- };-- const CommandItemHotkey = () => {- const token = () => {- if (props.item.type !== 'command') return;- return props.item.data.command.hotkeyToken;- };- const validToken = () => hasValidHotkey(token());- return (- <Show when={validToken()}>- <div class="pr-2 flex items-center justify-center text-[0.75rem] font-medium text-ink-extra-muted">- <div class="p-2 py-0.5 border border-edge-muted/50 rounded-xs">- <Hotkey token={token()} class="flex gap-1 items-center" />- </div>- </div>- </Show>- );- };-- // TODO: move into separate component- const CommandItemEntry = () => {- return (- <BozzyBracket active={props.selected} class="flex h-5">- <div- class="w-full"- style={{- 'padding-top': `${COMMAND_ITEM_PADDING}px`,- 'padding-bottom': `${COMMAND_ITEM_PADDING}px`,- }}- >- <Switch>- <Match when={props.item.type === 'email' && props.item}>- {(item) => (- <EmailCommandItem- sender={item().data.sender}- subject={item().data.name}- />- )}- </Match>- <Match when={props.item.type === 'text' && props.item}>- {(item) => <div>{item().data.text}</div>}- </Match>- <Match when={props.item.type === 'loadmore' && props.item}>- {(_item) => <div>Load More</div>}- </Match>- <Match when={true}>- <div- class="w-full flex gap-1.5 items-center ml-auto text-ink-extra-muted h-5"- style={{- height: `${COMMAND_ITEM_HEIGHT}px`,- }}- >- <div class="flex w-full justify-between">- <div class="flex items-center">- <div class="size-8 flex items-center justify-center">- <CommandItemIcon />- </div>- <CommandItemName />- </div>- <CommandItemHotkey />- </div>- </div>- </Match>- </Switch>- </div>- </BozzyBracket>- );- };-- const FullTextSearchResultItemEntry = () => {- if (!props.item.snippet) return ''; // this should never happen but it makes TS happy!- const isActuallyMessage = props.item.type === 'channel';- const snippet = (() => props.item.snippet!)();-- const timestamp =- props.item.type === 'email'- ? props.item.data.timestamp- : props.item.updatedAt;-- return (- <Message- focused={props.selected}- isFirstMessage={true}- isLastMessage={true}- hideConnectors={true}- senderId={snippet.senderId}- customIconTargetType={blockName()}- >- <Message.TopBar- name={idToDisplayName(snippet.senderId ?? props.item.data.name)}- timestamp={timestamp}- tagLabel={- isActuallyMessage- ? props.item.data.name- : undefined /* Hide redundant name on non-chat things */- }- tagIcon={- isActuallyMessage- ? CommandItemIcon- : undefined /* Hide redundant name on non-chat things */- }- />- <Message.Body>- <StaticMarkdown- markdown={- // TODO: This should be <m-search-match>- snippet.content.replaceAll('\n', ' ')- }- />- </Message.Body>- </Message>- );- };-- return (- <CommandItemContainer>- <Switch fallback={<CommandItemEntry />}>- <Match when={props.item.snippet?.content}>- <FullTextSearchResultItemEntry />- </Match>-- {/* Other modes can go here in the future */}- </Switch>- </CommandItemContainer>- );-}diff --git a/js/app/packages/app/component/command/index.ts b/js/app/packages/app/component/command/index.tsnew file mode 100644index 0000000000..f8b0ed6596--- /dev/null+++ b/js/app/packages/app/component/command/index.ts@@ -0,0 +1,11 @@+export { CommandMenu } from './CommandMenu';+export { CommandState } from './state';+export type { ICommandState } from './state';+export type { CategoryFilter } from './types';++export {+ useCommandItems,+ isEntityItem,+ isUserItem,+ isCommandItem,+} from './useCommandItems';diff --git a/js/app/packages/app/component/command/state.ts b/js/app/packages/app/component/command/state.tsindex e1c1a01633..6a418586ce 100644--- a/js/app/packages/app/component/command/state.ts+++ b/js/app/packages/app/component/command/state.ts@@ -1,109 +1,176 @@import { createControlledOpenSignal } from '@core/util/createControlledOpenSignal';-import { debouncedDependent } from '@core/util/debounce';-import { createEffect, createSignal, untrack } from 'solid-js';+import { createSignal, type Accessor, type Setter } from 'solid-js';+import type { CategoryFilter } from './types';+import type { CommandWithInfo } from '@core/hotkey/getCommands';+import type { EntityData } from '@entity';++/** timestamp threshold for resetting state after menu close */+const STATE_RESET_THRESHOLD_MS = 2_000;++export interface ICommandState {+ /** visibility */+ isOpen: Accessor<boolean>;+ setIsOpen: Setter<boolean>;+ toggle: () => void;+ open: () => void;+ close: () => void;++ /** query */+ query: Accessor<string>;+ setQuery: Setter<string>;+ clearQuery: () => void;++ /** selected index */+ selectedIndex: Accessor<number>;+ setSelectedIndex: Setter<number>;+ resetSelectedIndex: () => void;++ /** category filter */+ categoryFilter: Accessor<CategoryFilter>;+ setCategoryFilter: Setter<CategoryFilter>;+ resetCategoryFilter: () => void;++ /** command scope (for multi-stage commands) */+ commandScopeCommands: Accessor<CommandWithInfo[]>;+ setCommandScopeCommands: Setter<CommandWithInfo[]>;+ clearCommandScopeCommands: () => void;+ isInCommandScope: Accessor<boolean>;++ /** entity action mode (for selection modification commands) */+ entityActionEntities: Accessor<EntityData[]>;+ setEntityActionEntities: Setter<EntityData[]>;+ clearEntityActionEntities: () => void;+ isEntityActionMode: Accessor<boolean>;+ openForEntityAction: (entities: EntityData[]) => void;++ /** lifecycle */+ maybeResetState: () => void;+ forceReset: () => void;+ onMenuClose: () => void;+ onMenuOpen: () => void;+}-const SEARCH_SERVICE_DEBOUNCE_MS = 200;-const LOCAL_FUZZY_SEARCH_DEBOUNCE_MS = 10;+function createCommandState(): ICommandState {+ const [isOpen, setIsOpen] = createControlledOpenSignal();+ const [query, setQuery] = createSignal('');+ const [selectedIndex, setSelectedIndex] = createSignal(0);+ const [categoryFilter, setCategoryFilter] =+ createSignal<CategoryFilter>('all');+ const [lastClosedTime, setLastClosedTime] = createSignal(0);+ const [commandScopeCommands, setCommandScopeCommands] = createSignal<+ CommandWithInfo[]+ >([]);+ const [entityActionEntities, setEntityActionEntities] = createSignal<+ EntityData[]+ >([]);++ function toggle() {+ setIsOpen((prev) => !prev);+ }-export const [konsoleOpen, setKonsoleOpen] = createControlledOpenSignal();-export const toggleKonsoleVisibility = () => {- const isOpen = konsoleOpen();+ function open() {+ setIsOpen(true);+ }- setKonsoleOpen(!isOpen);-};+ function close() {+ setIsOpen(false);+ }-export const [lastCommandTime, setLastCommandTime] = createSignal(Date.now());+ function clearQuery() {+ setQuery('');+ }-export const [rawQuery, setRawQuery] = createSignal('');+ function resetSelectedIndex() {+ setSelectedIndex(0);+ }-export const debouncedSearchServiceQuery = debouncedDependent(- rawQuery,- SEARCH_SERVICE_DEBOUNCE_MS-);-export const debouncedLocalQuery = debouncedDependent(- rawQuery,- LOCAL_FUZZY_SEARCH_DEBOUNCE_MS-);+ function resetCategoryFilter() {+ setCategoryFilter('all');+ }-export const resetQuery = () => setRawQuery('');+ function clearCommandScopeCommands() {+ setCommandScopeCommands([]);+ }-// If we aren't in default mode,-// there will be a prefix SIGIL on the string,-// so we remove it.-// THIS IS WHAT YOU SHOULD USE FOR MOST "WHAT DID THE USER TYPE IN?" THINGS,-// the exception being actually checking for sigils.-export function cleanQuery(query?: string) {- const q = query ?? rawQuery();- const mode = getModeConfig(currentKonsoleMode());+ function isInCommandScope() {+ return commandScopeCommands().length > 0;+ }- if (mode.sigil && q.startsWith(mode.sigil)) {- return q.slice(mode.sigil.length);+ function clearEntityActionEntities() {+ setEntityActionEntities([]);}- return q;-}+ function isEntityActionMode() {+ return entityActionEntities().length > 0;+ }-export const COMMAND_MODES = [- // { id: 'FULL_TEXT_SEARCH', sigil: '%', label: 'Full Text Search' },- // { id: "REGEX_SEARCH", sigil: "/", label: "Regex Search" },- // { id: "RUN_COMMAND", sigil: ">", label: "Run" },- // { id: "TEMP_CHAT", sigil: " ", label: "Temporary Chat" },- { id: 'SELECTION_MODIFICATION', sigil: '', label: 'Modify selection' },-];-export const DEFAULT_MODE = {- id: 'ENTITY_SEARCH',- sigil: '',- label: 'Global Search',-};--type CommandMode = (typeof COMMAND_MODES)[number] | typeof DEFAULT_MODE;--export const [currentKonsoleMode, _setKonsoleMode] = createSignal<- CommandMode['id']->(DEFAULT_MODE.id);--export const setKonsoleMode = (- id: CommandMode['id'] | typeof DEFAULT_MODE.id-) => {- _setKonsoleMode(id);-- // Add sigil when mode is changed programatically- const query = rawQuery();- const mode = getModeConfig(id);-- if (mode.id !== DEFAULT_MODE.id && query.startsWith(mode.sigil)) return;- setRawQuery(mode.sigil + cleanQuery());-};--export const resetKonsoleMode = () => setKonsoleMode(DEFAULT_MODE.id);--export function getModeFromQuery(q: string): CommandMode {- return COMMAND_MODES.find((mode) => q.startsWith(mode.sigil)) ?? DEFAULT_MODE;-}+ function openForEntityAction(entities: EntityData[]) {+ setEntityActionEntities(entities);+ setIsOpen(true);+ }-export function getModeConfig(id: string): CommandMode {- const mode =- COMMAND_MODES.find((mode) => mode.id === id) ??- (id === DEFAULT_MODE.id ? DEFAULT_MODE : undefined);- if (!mode) console.error(`Command+K mode '${id}' does not exist.`);- return mode ?? DEFAULT_MODE;-}+ function maybeResetState() {+ const now = Date.now();+ if (now - lastClosedTime() >= STATE_RESET_THRESHOLD_MS) {+ forceReset();+ }+ }-export const createModeListenerEffects = () => {- // Switch modes when sigil is applied by user- createEffect(() => {- const query = rawQuery();- const detectedMode = getModeFromQuery(query).id;+ function forceReset() {+ clearQuery();+ resetSelectedIndex();+ resetCategoryFilter();+ clearCommandScopeCommands();+ clearEntityActionEntities();+ }- if (detectedMode !== currentKonsoleMode()) {- untrack(() => setKonsoleMode(detectedMode));- }- });-- // createEffect(() => {- // console.log({- // mode: currentKonsoleMode(),- // query: rawQuery()- // })- // })-};+ function onMenuClose() {+ setLastClosedTime(Date.now());+ clearCommandScopeCommands();+ clearEntityActionEntities();+ }++ function onMenuOpen() {+ clearQuery();+ resetSelectedIndex();+ }++ return {+ isOpen,+ setIsOpen,+ toggle,+ open,+ close,++ query,+ setQuery,+ clearQuery,++ selectedIndex,+ setSelectedIndex,+ resetSelectedIndex,++ categoryFilter,+ setCategoryFilter,+ resetCategoryFilter,++ commandScopeCommands,+ setCommandScopeCommands,+ clearCommandScopeCommands,+ isInCommandScope,++ entityActionEntities,+ setEntityActionEntities,+ clearEntityActionEntities,+ isEntityActionMode,+ openForEntityAction,++ maybeResetState,+ forceReset,+ onMenuClose,+ onMenuOpen,+ };+}++/** Global command menu state singleton */+export const CommandState = createCommandState();diff --git a/js/app/packages/app/component/command/types.ts b/js/app/packages/app/component/command/types.tsnew file mode 100644index 0000000000..3ca4d669e0--- /dev/null+++ b/js/app/packages/app/component/command/types.ts@@ -0,0 +1,12 @@+export type CategoryFilter =+ | 'all'+ | 'commands'+ | 'channels'+ | 'dms'+ | 'notes'+ | 'tasks'+ | 'documents'+ | 'channels'+ | 'chats'+ | 'projects'+ | 'people';diff --git a/js/app/packages/app/component/command/useCommandItems.ts b/js/app/packages/app/component/command/useCommandItems.tsindex 7814fd0392..b06a51900e 100644--- a/js/app/packages/app/component/command/useCommandItems.ts+++ b/js/app/packages/app/component/command/useCommandItems.ts@@ -1,113 +1,189 @@-import { useChannelsContext } from '@core/context/channels';-import { getActiveCommandsFromScope } from '@core/hotkey/getCommands';-import { activeScope } from '@core/hotkey/state';-import { mapFromListsByKey } from '@core/util/compareUtils';-import type { DateValue } from '@core/util/date';-import { useHistoryQuery } from '@queries/history/history';-import type { Channel } from '@service-comms/generated/models/channel';-import type { ChannelType } from '@service-comms/generated/models/channelType';-import { ChannelTypeEnum } from '@service-comms/client';+import {+ useQuickAccess,+ type QuickAccessItem,+ type Bucket,+ type CommandItem,+ isEntityItem,+ isUserItem,+ isCommandItem,+ exclude,+} from '@core/context/quickAccess';+import { createFreshSearch } from '@core/util/freshSort';import { createMemo } from 'solid-js';-import type { CommandItemCard } from './KonsoleItem';--type ChannelWithViewedAt = Channel & { viewed_at?: DateValue };+import type { CategoryFilter } from './types';+import {+ getActiveCommandsFromScope,+ type CommandWithInfo,+} from '@core/hotkey/getCommands';+import { activeScope } from '@core/hotkey/state';+import { CommandState } from './state';+import { HotkeyTags } from '@core/hotkey/constants';-const FILTER_PERSISTENT_CHATS = false;+function isChannelItem(item: QuickAccessItem): boolean {+ // only dms get the "channel boost" in command menu+ return item.bucket === 'dm';+}-function channelsIntoCategories(channels: Channel[]) {- const bins: Record<ChannelType, Channel[]> = {- public: [],- organization: [],- direct_message: [],- private: [],+// tune-able freshSearch for query vs non-query sort+function createSearchConfig(hasQuery: boolean) {+ return {+ useViewedAt: true,+ channelBoost: hasQuery ? 1.8 : 1.0,+ fuzzyWeight: hasQuery ? 0.7 : 0.0,+ timeWeight: hasQuery ? 0.3 : 0.9,+ minFuzzyThreshold: hasQuery ? 0.1 : 0,+ commaSeparatedChannelMatch: true,};+}++/**+ * Helper to convert commands to CommandItem format.+ * Deduplicates commands by description since commands with multiple hotkeys+ * (e.g., ['delete', 'backspace']) appear multiple times in the command list.+ */+function commandsToItems(commands: CommandWithInfo[]): CommandItem[] {+ const seen = new Set<string>();+ const dedupedCommands = commands.filter((command) => {+ const description =+ typeof command.description === 'function'+ ? command.description()+ : command.description;+ const id = description.replaceAll(' ', '-');+ if (seen.has(id)) {+ return false;+ }+ seen.add(id);+ return true;+ });- for (const chan of channels) {- bins[chan.channel_type].push(chan);- }+ return dedupedCommands.map((command): CommandItem => {+ const description =+ typeof command.description === 'function'+ ? command.description()+ : command.description;- return bins;+ return {+ id: `command-${description.replaceAll(' ', '-')}`,+ kind: 'command',+ bucket: 'command',+ searchText: description,+ sortTimestamp: 0,+ timestamps: {},+ data: command,+ };+ });}-export function useCommandItems() {- const historyQuery = useHistoryQuery();- const channelsContext = useChannelsContext();- const channels = channelsContext.channels;- const activeCommands = getActiveCommandsFromScope(activeScope(), {+/**+ * Convert active hotkey commands to QuickAccessItem format.+ *+ * IMPORTANT: We capture commands at call time (outside createMemo) to match+ * the old Konsole behavior. This ensures commands are captured from the+ * previous scope BEFORE the command menu's scope becomes active. Otherwise,+ * selection modification commands (delete, mark done, etc.) would be filtered+ * out because their conditions check the soup's selection state.+ */+function useCommandsList(): () => CommandItem[] {+ const scopeId = activeScope() ?? '';+ const capturedCommands = getActiveCommandsFromScope(scopeId, {sortByScopeLevel: false,hideShadowedCommands: false,hideCommandsWithoutHotkeys: false,});- return createMemo<Map<string, CommandItemCard>>(() => {- const commands: CommandItemCard[] = activeCommands.map((command) => {- const description =- typeof command.description === 'function'- ? command.description()- : command.description;- return {- type: 'command' as const,- data: {- id: description.replaceAll(' ', '-'),- name: description,- command: command,- },- updatedAt: new Date(0),- };- });-- const historyData = historyQuery.data ?? [];- const items: CommandItemCard[] = historyData- .filter((item) => {- // Remove the persistent sidebar chats. Those are all called "New Chat"- // and searching against the name is completely useless.- if (FILTER_PERSISTENT_CHATS && item.type === 'chat') {- return !item.isPersistent;- }- if (item.deletedAt) {- return false;- }- return true;- })- .map((item) => ({- type: 'item',- data: {- id: item.id,- name: item.name,- data: item,- itemType: item.type,- fileType: item.type === 'document' ? item.fileType : undefined,- subType: item.type === 'document' ? item.subType : undefined,- },- updatedAt: item.updatedAt,- viewedAt: item.viewedAt,- }));- const bins = channelsIntoCategories(channels());- const channels_: CommandItemCard[] = [- ...bins.direct_message,- ...bins.private,- ...bins.organization,- ...bins.public,- ].map((channel) => ({- type: 'channel',- data: {- id: channel.id,- name: channel.name!,- channel_type: channel.channel_type,- participants:- channel.channel_type === ChannelTypeEnum.DirectMessage- ? (channel as any).participants- : undefined,- },- updatedAt: channel.updated_at,- viewedAt: (channel as ChannelWithViewedAt).viewed_at,- }));-- return mapFromListsByKey<CommandItemCard>(- (item) => item.data.id,- items,- channels_,- commands+ return createMemo(() => {+ // If we're in a command scope (multi-stage command), show those commands instead+ const scopeCommands = CommandState.commandScopeCommands();+ if (scopeCommands.length > 0) {+ return commandsToItems(scopeCommands);+ }++ // If in entity action mode, filter to only show selection modification commands+ if (CommandState.isEntityActionMode()) {+ const selectionCommands = capturedCommands.filter((command) =>+ command.tags?.includes(HotkeyTags.SelectionModification)+ );+ return commandsToItems(selectionCommands);+ }++ // Use the commands captured at mount time+ return commandsToItems(capturedCommands);+ });+}++/**+ * Hook to get items from QuickAccess organized by category.+ * Items are already sorted by recency from QuickAccess.+ */+function useQuickAccessBuckets(): Record<+ CategoryFilter,+ () => QuickAccessItem[]+> {+ const quickAccess = useQuickAccess();+ const commandsList = useCommandsList();+ const entitiesList = quickAccess.useList(...exclude('person'));++ const allWithCommands = createMemo(() => {+ const entities = entitiesList();+ const commands = commandsList();+ return [...entities, ...commands];+ });++ return {+ all: allWithCommands,+ channels: quickAccess.useList('channel'),+ dms: quickAccess.useList('dm'),+ notes: quickAccess.useList('note'),+ tasks: quickAccess.useList('task'),+ documents: quickAccess.useList('document'),+ chats: quickAccess.useList('chat'),+ projects: quickAccess.useList('project'),+ people: quickAccess.useList('person'),+ commands: commandsList,+ };+}++export function useCommandItems(+ query: () => string,+ categoryFilter: () => CategoryFilter+) {+ const buckets = useQuickAccessBuckets();++ // When in command scope or entity action mode, always show commands regardless of category filter+ const categoryItems = () => {+ if (CommandState.commandScopeCommands().length > 0) {+ return buckets.commands();+ }+ if (CommandState.isEntityActionMode()) {+ return buckets.commands();+ }+ return buckets[categoryFilter()]();+ };++ const search = createMemo(() => {+ const q = query();+ const hasQuery = q.trim().length > 0;+ return createFreshSearch<QuickAccessItem>(+ createSearchConfig(hasQuery),+ (item) => item.searchText,+ isChannelItem,+ (item) => item.timestamps);});++ const filteredItems = createMemo(() => {+ const q = query();+ const items = categoryItems();++ if (!q) {+ return items;+ }++ return search()(items, q).map((result) => result.item);+ });++ return filteredItems;}++export { isEntityItem, isUserItem, isCommandItem };+export type { QuickAccessItem, Bucket };diff --git a/js/app/packages/app/component/command/useSearchItems.ts b/js/app/packages/app/component/command/useSearchItems.tsdeleted file mode 100644index 26ee790929..0000000000--- a/js/app/packages/app/component/command/useSearchItems.ts+++ /dev/null@@ -1,335 +0,0 @@-import { ENABLE_SEARCH_SERVICE } from '@core/constant/featureFlags';-import { useSearch } from '@core/signal/search';-import { isErr } from '@core/util/maybeResult';-import {- extractSearchSnippet,- extractSearchTerms,-} from '@core/util/searchHighlight';-import { searchClient } from '@service-search/client';-import type { UnifiedSearchResponse } from '@service-search/generated/models/unifiedSearchResponse';-import type { UnifiedSearchResponseItem } from '@service-search/generated/models/unifiedSearchResponseItem';-import type { BasicDocumentFileType } from '@service-storage/generated/schemas/basicDocumentFileType';-import { createEffect, createMemo, createSignal, on } from 'solid-js';-import type { CommandItemCard } from './KonsoleItem';--function createDocumentItems(- doc: UnifiedSearchResponseItem-): CommandItemCard[] {- const items: CommandItemCard[] = [];- if (doc.type !== 'document') return [];-- if (- doc.document_search_results.length === 0 ||- !doc.metadata ||- doc.metadata.deleted_at- )- return [];-- for (const result of doc.document_search_results) {- const isContentHit = !!result.node_id;- if (!isContentHit) continue;-- const contents = result.highlight.content ?? [];- contents.forEach((content, index) => {- // TODO: Canvas returns some nasty partial <m-foo> tags in plaintext- // so they are banned from search display for now.- if (doc.file_type !== 'canvas') {- items.push({- type: 'item',- data: {- id: doc.document_id,- name: doc.document_name,- fileType: doc.file_type as BasicDocumentFileType,- itemType: 'document',- },- snippet: {- content,- locationId: result.node_id!,- fileType: doc.file_type!,- matchIndex: index,- // For PDF files, extract additional location data- ...(['docx', 'pdf'].includes(doc.file_type!) && {- searchSnippet: extractSearchSnippet(content),- highlightTerms: extractSearchTerms(content),- }),- },- updatedAt: doc.metadata?.updated_at,- });- }- });- }-- return items;-}--function createEmailItems(email: UnifiedSearchResponseItem): CommandItemCard[] {- const items: CommandItemCard[] = [];- if (email.type !== 'email') return [];-- if (email.email_message_search_results.length === 0) return [];-- for (const result of email.email_message_search_results) {- const isContentHit = !!result.message_id;- if (!isContentHit) continue;-- const contents = result.highlight.content ?? [];- contents.forEach((content, index) => {- items.push({- type: 'email',- data: {- id: email.thread_id,- name: email.name ?? '',- sender: result.sender!,- timestamp: result.sent_at ?? email.updated_at,- is_read: !result.labels.includes('UNREAD'),- // TODO: This should be the attachments from the email, need to update the search service to return them- attachments: [],- },- snippet: {- content,- locationId: result.message_id!,- fileType: 'email',- matchIndex: index,- },- });- });- }-- return items;-}--function createChatItems(chat: UnifiedSearchResponseItem): CommandItemCard[] {- const items: CommandItemCard[] = [];- if (chat.type !== 'chat') return [];-- if (- chat.chat_search_results.length === 0 ||- !chat.metadata ||- chat.metadata.deleted_at- )- return [];-- for (const result of chat.chat_search_results) {- const isContentHit = !!result.chat_message_id;- if (!isContentHit) continue;-- const contents = result.highlight.content ?? [];- contents.forEach((content, index) => {- items.push({- type: 'item',- data: {- id: chat.chat_id,- name: chat.name,- itemType: 'chat',- },- snippet: {- content,- locationId: result.chat_message_id!,- fileType: 'chat',- matchIndex: index,- senderId: chat.user_id,- },- updatedAt: chat.metadata?.updated_at,- });- });- }-- return items;-}--function createChannelItems(- channel: UnifiedSearchResponseItem-): CommandItemCard[] {- const items: CommandItemCard[] = [];- if (channel.type !== 'channel') return [];-- if (channel.channel_message_search_results.length === 0) return [];-- for (const result of channel.channel_message_search_results) {- const isContentHit = !!result.message_id;- if (!isContentHit) continue;-- const contents = result.highlight.content ?? [];- contents.forEach((content, index) => {- items.push({- type: 'channel',- data: {- id: channel.channel_id,- // TODO: use channels context to get channel name- name: '', // Set name to empty string since search results don't contain channel names anymore- },- snippet: {- content,- locationId: result.message_id!,- fileType: 'chat',- matchIndex: index,- senderId: result.sender_id!,- },- updatedAt: channel.metadata?.updated_at,- });- });- }-- return items;-}--function createProjectItems(- project: UnifiedSearchResponseItem-): CommandItemCard[] {- const items: CommandItemCard[] = [];- if (project.type !== 'project') return [];-- if (- project.project_search_results.length === 0 ||- !project.metadata ||- project.metadata.deleted_at- )- return [];-- for (const result of project.project_search_results) {- const contents = result.highlight.content ?? [];- contents.forEach((_content, _index) => {- items.push({- type: 'item',- data: {- id: project.id,- name: project.name,- fileType: 'project',- itemType: 'project',- },- });- });- }-- return items;-}--function convertSearchResultsToItems(- searchResults: UnifiedSearchResponse-): CommandItemCard[] {- if (!searchResults || !searchResults.results) return [];-- let items: CommandItemCard[] = [];-- for (const result of searchResults.results) {- switch (result.type) {- case 'email':- items = items.concat(createEmailItems(result));- break;- case 'chat':- items = items.concat(createChatItems(result));- break;- case 'document':- items = items.concat(createDocumentItems(result));- break;- case 'channel':- items = items.concat(createChannelItems(result));- break;- case 'project':- items = items.concat(createProjectItems(result));- break;- default:- break;- }- }-- return items;-}--export function useSearchItems(searchTerm: () => string) {- const unifiedSearchResults = useSearch(searchTerm);- return createMemo(() => {- const searchResults = unifiedSearchResults();- if (!searchResults) return [];- return convertSearchResultsToItems(searchResults);- });-}--export function usePaginatedSearchItems(searchTerm: () => string) {- const [allItems, setAllItems] = createSignal<CommandItemCard[]>([]);- const [nextCursor, setNextCursor] = createSignal<string | null>(null);- const [hasMore, setHasMore] = createSignal(true);- const [isLoading, setIsLoading] = createSignal(false);- let loadMoreAbortController: AbortController | null = null;-- // Reset when search term changes- createEffect(- on(searchTerm, () => {- if (loadMoreAbortController) {- loadMoreAbortController.abort();- loadMoreAbortController = null;- }- setAllItems([]);- setNextCursor(null);- setHasMore(true);- })- );-- // Load first page when search term changes- const searchResults = useSearch(searchTerm);- createEffect(() => {- const results = searchResults();- if (results && nextCursor() === null) {- const items = convertSearchResultsToItems(results);- setAllItems(items);- setNextCursor(results.next_cursor ?? null);- setHasMore(!!results.next_cursor);- }- });-- const loadMore = async () => {- if (isLoading() || !hasMore()) return;-- if (loadMoreAbortController) {- loadMoreAbortController.abort();- }- loadMoreAbortController = new AbortController();-- setIsLoading(true);- try {- const term = searchTerm();- const cursor = nextCursor();-- if (!ENABLE_SEARCH_SERVICE || term.length < 3) {- return;- }-- const result = await searchClient.search(- {- request: {- match_type: 'partial',- query: term,- },- params: { cursor, page_size: 10 },- },- { signal: loadMoreAbortController.signal }- );-- if (isErr(result)) {- console.error('Failed to load more search results');- return;- }-- const [, data] = result;- if (data) {- const newItems = convertSearchResultsToItems(data);- setAllItems((prev) => [...prev, ...newItems]);- setNextCursor(data.next_cursor ?? null);- setHasMore(!!data.next_cursor);- }- } catch (error) {- if (loadMoreAbortController.signal.aborted) return;-- throw error;- } finally {- setIsLoading(false);- }- };-- return {- items: allItems,- hasMore,- isLoading,- loadMore,- };-}diff --git a/js/app/packages/app/component/dock/Dock.tsx b/js/app/packages/app/component/dock/Dock.tsxindex 21d5c0e3eb..11801007ac 100644--- a/js/app/packages/app/component/dock/Dock.tsx+++ b/js/app/packages/app/component/dock/Dock.tsx@@ -13,7 +13,6 @@ import IconAI from '@macro-icons/wide/star.svg';import IconGear from '@macro-icons/macro-gear.svg';import IconLogo from '@macro-icons/macro-logo.svg';import { BasicTierLimit } from './BasicTierLimit';-import { setKonsoleOpen } from '../command/state';import { Hotkey } from '@core/component/Hotkey';import { setCreateMenuOpen } from '../Launcher';import { useHasPaidAccess } from '@core/auth';@@ -21,6 +20,7 @@ import { TOKENS } from '@core/hotkey/tokens';import { Button } from '@ui/components/Button';import { LabelAndHotKey } from '@core/component/Tooltip';import { isMobile } from '@core/mobile/isMobile';+import { CommandState } from '../command';export function Dock() {const notificationSource = useGlobalNotificationSource();@@ -88,7 +88,7 @@ export function Dock() {'height': '24px','gap': '7px'}}- onClick={() => { setKonsoleOpen(true) }}+ onClick={CommandState.toggle}class="dock-button-hover"data-hotkey-token={TOKENS.global.commandMenu}>diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-entity-selection-toolbar.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-entity-selection-toolbar.tsxindex f62edacf12..d59ed7ec0a 100644--- a/js/app/packages/app/component/next-soup/soup-view/soup-entity-selection-toolbar.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/soup-entity-selection-toolbar.tsx@@ -1,14 +1,4 @@-import {- resetCommandCategoryIndex,- searchCategories,- setCommandCategoryIndex,- setKonsoleContextInformation,-} from '@app/component/command/KonsoleItem';-import {- resetKonsoleMode,- setKonsoleMode,- toggleKonsoleVisibility,-} from '@app/component/command/state';+import { CommandState } from '@app/component/command/state';import { EntitySelectionToolbarModal } from '@app/component/EntitySelectionToolbarModal';import type { EntityData } from '@entity';@@ -29,27 +19,12 @@ export const SoupEntitySelectionToolbar = (const selected = props.selected;const hasSelection = selected.length > 0;if (!hasSelection) {- searchCategories.hideCategory('Selection');- resetCommandCategoryIndex();- resetKonsoleMode();return;}- setKonsoleMode('SELECTION_MODIFICATION');- const selectionIndex = searchCategories.getCategoryIndex('Selection');-- if (selectionIndex === undefined) return false;-- setCommandCategoryIndex(selectionIndex);-- searchCategories.showCategory('Selection');-- setKonsoleContextInformation({- selectedEntities: selected.slice(),- clearSelection: props.onClear,- });-- toggleKonsoleVisibility();+ // Open the command menu in entity action mode, which shows only+ // selection modification commands with a preview of the selected entities+ CommandState.openForEntityAction(selected);}}/>);diff --git a/js/app/packages/app/component/next-soup/soup-view/use-soup-view-hotkeys.ts b/js/app/packages/app/component/next-soup/soup-view/use-soup-view-hotkeys.tsindex e518988434..c039a3a810 100644--- a/js/app/packages/app/component/next-soup/soup-view/use-soup-view-hotkeys.ts+++ b/js/app/packages/app/component/next-soup/soup-view/use-soup-view-hotkeys.ts@@ -1,15 +1,4 @@-import {- konsoleOpen,- resetKonsoleMode,- setKonsoleMode,- toggleKonsoleVisibility,-} from '@app/component/command/state';-import {- resetCommandCategoryIndex,- searchCategories,- setCommandCategoryIndex,- setKonsoleContextInformation,-} from '@app/component/command/KonsoleItem';+import { CommandState } from '@app/component/command/state';import type { SplitHandle } from '@app/component/split-layout/layoutManager';import { activeScope, hotkeyScopeTree } from '@core/hotkey/state';import { registerHotkey } from '@core/hotkey/hotkeys';@@ -197,43 +186,30 @@ export const useSoupViewHotkeys = (options: UseSoupViewHotkeysOptions) => {});// cmd+k - Open command menu with selection context+ // When there's a selection, opens in entity action mode showing only+ // selection modification commands with a preview of the selected entitiesregisterHotkey({scopeId,description: () => {- return konsoleOpen() ? 'Close command menu' : 'Open command menu';+ return CommandState.isOpen() ? 'Close command menu' : 'Open command menu';},hotkey: 'cmd+k',- condition: () => !konsoleOpen(),+ condition: () => !CommandState.isOpen(),keyDownHandler: (e) => {e?.preventDefault();const multiSelectEntities = soup.selection.selected();- const hasSelection = multiSelectEntities.length > 0;-- if (hasSelection) {- setKonsoleMode('SELECTION_MODIFICATION');- const selectionIndex = searchCategories.getCategoryIndex('Selection');-- if (selectionIndex === undefined) return false;-- setCommandCategoryIndex(selectionIndex);-- searchCategories.showCategory('Selection');-- setKonsoleContextInformation({- multiSelectEntities: multiSelectEntities.slice(),- });-- toggleKonsoleVisibility();- return true;+ if (multiSelectEntities.length > 0) {+ // Open in entity action mode with selection+ CommandState.openForEntityAction(multiSelectEntities.slice());+ } else {+ // Normal toggle+ CommandState.toggle();}- searchCategories.hideCategory('Selection');- resetCommandCategoryIndex();- resetKonsoleMode();- return false;+ return true;},displayPriority: 10,- hide: konsoleOpen,+ hide: CommandState.isOpen,runWithInputFocused: true,});diff --git a/js/app/packages/app/component/property-edit-modal/PropertyEditorModal.tsx b/js/app/packages/app/component/property-edit-modal/PropertyEditorModal.tsxindex 84b2bdb6a9..543915997a 100644--- a/js/app/packages/app/component/property-edit-modal/PropertyEditorModal.tsx+++ b/js/app/packages/app/component/property-edit-modal/PropertyEditorModal.tsx@@ -337,7 +337,7 @@ function EditingEntityPreview(props: { entities: EntityData[] }) {{(entity) => {return (<div- class={cn('bg-edge/20 px-2 py-1 truncate', {+ class={cn('bg-edge/20 px-2 py-1 truncate text-xs rounded-xs', {'max-w-[50%]': props.entities.length === 2,})}>@@ -347,7 +347,7 @@ function EditingEntityPreview(props: { entities: EntityData[] }) {}}</For><Show when={remainingCount() > 0}>- <div class="text-muted-foreground px-2 py-1">+ <div class="text-muted-foreground text-xs px-2 py-1">+{remainingCount()} more</div></Show>diff --git a/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts b/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.tsindex 45fd79db2d..3dedccc93d 100644--- a/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts+++ b/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts@@ -255,7 +255,7 @@ export async function documentUploadToItem(upload: UploadSuccess) {updatedAt: now,deletedAt: null,documentVersionId: 0,- owner: '',+ ownerId: '',};}@@ -269,7 +269,7 @@ export async function documentUploadToItem(upload: UploadSuccess) {createdAt: now,updatedAt: now,deletedAt: null,- userId: '',+ ownerId: '',};}diff --git a/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsx b/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsxindex 2ed8e64e53..0ff9fe5052 100644--- a/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsx+++ b/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsx@@ -49,6 +49,7 @@ function historyItemToEntity(item: HistoryItem): QuickAccessEntity {createdAt: item.createdAt,updatedAt: item.updatedAt,viewedAt: item.viewedAt,+ ownerId: item.ownerId,};switch (item.type) {diff --git a/js/app/packages/core/context/quickAccess/index.ts b/js/app/packages/core/context/quickAccess/index.tsindex f3f4c72d92..b5fa36f2cd 100644--- a/js/app/packages/core/context/quickAccess/index.ts+++ b/js/app/packages/core/context/quickAccess/index.ts@@ -22,4 +22,5 @@ export {isCommandItem,isEntityOfType,isFromBucket,+ exclude,} from './types';diff --git a/js/app/packages/core/context/quickAccess/types.ts b/js/app/packages/core/context/quickAccess/types.tsindex 3af9594579..c60e890265 100644--- a/js/app/packages/core/context/quickAccess/types.ts+++ b/js/app/packages/core/context/quickAccess/types.ts@@ -12,10 +12,9 @@ import type { HotkeyCommand } from '@core/hotkey/types';import type { IUser } from '@core/user/types';import type { DateValue } from '@core/util/date';-export type QuickAccessEntity<T extends EntityData = EntityData> = Omit<- T,- 'ownerId'->;+// Note (seamus) : Ideally history would return ownerId or we would get actual+// soup entities for quick access+export type QuickAccessEntity<T extends EntityData = EntityData> = T;export type Bucket =| 'channel'@@ -215,3 +214,7 @@ export type QuickAccessContextValue = {*/getById: (id: string) => QuickAccessItem | undefined;};++export function exclude(...buckets: Bucket[]) {+ return ALL_BUCKETS.filter((bucket) => !buckets.includes(bucket));+}diff --git a/js/app/packages/queries/history/transforms.ts b/js/app/packages/queries/history/transforms.tsindex c0a92c7788..1a61e81892 100644--- a/js/app/packages/queries/history/transforms.ts+++ b/js/app/packages/queries/history/transforms.ts@@ -20,6 +20,7 @@ export function transformHistoryItem(item: Item): HistoryItem {type: 'document',fileType: item.fileType,subType: item.subType,+ ownerId: item.owner,};case 'chat':@@ -27,12 +28,14 @@ export function transformHistoryItem(item: Item): HistoryItem {...base,type: 'chat',isPersistent: item.isPersistent,+ ownerId: item.userId,};case 'project':return {...base,type: 'project',+ ownerId: item.userId,};}}diff --git a/js/app/packages/queries/history/types.ts b/js/app/packages/queries/history/types.tsindex f03379356b..8ba9b505a5 100644--- a/js/app/packages/queries/history/types.ts+++ b/js/app/packages/queries/history/types.ts@@ -10,6 +10,8 @@ type BaseHistoryItem = Pick<Item, 'id' | 'name'> & {viewedAt?: DateValue;// TODO: item name without safe name transformrawName?: string;+ // Normalized owner field: BasicDocument.owner, Chat.userId, Project.userId+ ownerId: string;};export type DocumentHistoryItem = BaseHistoryItem &