Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

6.3 KB
Raw Blame
import { Command } from 'cmdk';
import { Dialog } from 'radix-ui';
import { useMemo, useState, useSyncExternalStore } from 'react';

import { GROUP_LABEL_KEYS } from '../../lib/commands/globalActions';
import { hotkeyManager } from '../../lib/commands/hotkeyManager';
import { registry } from '../../lib/commands/registry';
import type { RegisteredAction } from '../../lib/commands/types';
import { useT } from '../../lib/i18n/I18nContext';
import type { Thread } from '../../types/thread';
import Kbd from './Kbd';
import ThreadSearchGroups from './ThreadSearchGroups';

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  /** Conversations searchable by title; their messages are searched in the core. */
  threads?: Thread[];
  /** Open a conversation picked from the search. Thread search is off without it. */
  onOpenThread?: (threadId: string) => void;
}

const NO_THREADS: Thread[] = [];

function subscribe(listener: () => void): () => void {
  const u1 = registry.subscribe(listener);
  const u2 = hotkeyManager.subscribe(listener);
  return () => {
    u1();
    u2();
  };
}

function getSnapshot(): RegisteredAction[] {
  return registry.getActiveActions(hotkeyManager.getStackSymbols());
}

export default function CommandPalette({
  open,
  onOpenChange,
  threads = NO_THREADS,
  onOpenThread,
}: Props) {
  const { t } = useT();
  const actions = useSyncExternalStore(subscribe, getSnapshot);
  const [search, setSearch] = useState('');
  // Every opening starts from an empty query: cleared as the palette closes,
  // during render rather than in an effect.
  const [wasOpen, setWasOpen] = useState(open);
  if (open !== wasOpen) {
    setWasOpen(open);
    if (!open) setSearch('');
  }

  const groups = useMemo(() => {
    const byGroup = new Map<string, RegisteredAction[]>();
    for (const a of actions) {
      const g = a.group ?? 'Actions';
      if (!byGroup.has(g)) byGroup.set(g, []);
      byGroup.get(g)!.push(a);
    }
    const order = ['Navigation', 'Help'];
    const keys = [...byGroup.keys()].sort((a, b) => {
      const ai = order.indexOf(a);
      const bi = order.indexOf(b);
      if (ai === -1 && bi === -1) return a.localeCompare(b);
      if (ai === -1) return 1;
      if (bi === -1) return -1;
      return ai - bi;
    });
    return keys.map(k => [k, byGroup.get(k)!] as const);
  }, [actions]);

  function runAction(action: RegisteredAction): void {
    onOpenChange(false);
    window.requestAnimationFrame(() => {
      registry.runAction(action.id);
    });
  }

  function openThread(threadId: string): void {
    onOpenChange(false);
    onOpenThread?.(threadId);
  }

  return (
    <Dialog.Root open={open} onOpenChange={onOpenChange}>
      <Dialog.Portal>
        <Dialog.Overlay className="fixed inset-0 bg-cmd-overlay z-40" />
        <Dialog.Content
          className="fixed left-1/2 top-[20vh] -translate-x-1/2 w-[min(640px,calc(100vw-32px))] bg-cmd-surface text-cmd-foreground border border-cmd-border rounded-xl shadow-cmd-palette z-50 overflow-hidden"
          aria-label={t('commandPalette.ariaLabel')}>
          <Dialog.Title className="sr-only">{t('commandPalette.title')}</Dialog.Title>
          <Dialog.Description className="sr-only">
            {t('commandPalette.description')}
          </Dialog.Description>
          <Command label={t('commandPalette.label')} shouldFilter={true}>
            <Command.Input
              autoFocus
              value={search}
              onValueChange={setSearch}
              placeholder={t('commandPalette.placeholder')}
              className="w-full px-4 py-3 bg-transparent outline-hidden border-b border-cmd-border text-cmd-foreground placeholder:text-cmd-foreground-muted"
              aria-label={t('commandPalette.searchAria')}
            />
            <Command.List className="max-h-[50vh] overflow-auto py-2">
              <Command.Empty className="px-4 py-8 text-center text-cmd-foreground-muted">
                {t('commandPalette.noResults')}
              </Command.Empty>
              {groups.map(([groupName, items]) => (
                <Command.Group
                  key={groupName}
                  heading={GROUP_LABEL_KEYS[groupName] ? t(GROUP_LABEL_KEYS[groupName]) : groupName}
                  className="**:[[cmdk-group-heading]]:px-4 **:[[cmdk-group-heading]]:py-1 **:[[cmdk-group-heading]]:text-xs **:[[cmdk-group-heading]]:uppercase **:[[cmdk-group-heading]]:text-cmd-foreground-muted">
                  {items.map(action => {
                    const label = action.labelKey ? t(action.labelKey) : action.label;
                    return (
                      <Command.Item
                        key={action.id}
                        value={action.id}
                        keywords={[label, action.label, ...(action.keywords ?? [])]}
                        onSelect={() => runAction(action)}
                        className="flex items-center gap-3 px-4 py-2 cursor-pointer aria-selected:bg-cmd-surface-elevated">
                        {action.icon ? (
                          <action.icon className="w-4 h-4 text-cmd-foreground-muted" />
                        ) : (
                          <span className="w-4" />
                        )}
                        <span className="flex-1 truncate">{label}</span>
                        {action.hint && (
                          <span className="text-xs text-cmd-foreground-muted truncate">
                            {action.hint}
                          </span>
                        )}
                        {action.shortcut && <Kbd shortcut={action.shortcut} />}
                      </Command.Item>
                    );
                  })}
                </Command.Group>
              ))}
              {onOpenThread && (
                <ThreadSearchGroups query={search} threads={threads} onOpenThread={openThread} />
              )}
            </Command.List>
            <div className="flex items-center gap-1.5 px-4 py-2 border-t border-cmd-border text-xs text-cmd-foreground-muted">
              {/* Advertise ⌘/ (allowed while this search box is focused) rather
                  than ?, which the hotkey manager skips inside inputs. */}
              <Kbd shortcut="mod+/" />
              <span>{t('shortcuts.title')}</span>
            </div>
          </Command>
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  );
}