Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

30.1 KB
Raw Blame
import { pickFileIcon } from '@/components/ui/file-type-icon';
import { Button } from '@/components/ui/button';
import { MENU_CURRENT_ROW_ATTR, MENU_ROW_ATTR, currentMarkedRow } from '@/components/ui/dropdown-menu-highlight';
import {
  COMPOSER_MENU_ROW,
  MenuHighlightLayer,
  menuPanelAttrs,
  menuRowAttrs,
  useMenuPanel,
  withMenuLabels,
} from '@/components/ui/menu-row';
/**
 * Unified composer suggestion panel (command-palette F2 / F5, `@` + `+`).
 *
 * 2026-08 unification (Codex Desktop pattern): this panel serves BOTH the
 * typed `@` trigger and the composer `+` button (synthetic activation — no
 * `@` char in the doc, typing still filters). It renders the union of:
 *   - action rows from the legacy `+` MorphPopover menu (attach files, new
 *     goal, plan mode, collaboration, add reference directory)
 *   - scanned resources (files / dirs / agents / tabs / windows / tasks)
 *   - installed plugins (unavailable ones stay visible but disabled)
 *   - the reference-directories management section (empty query only)
 *
 * All scanning / ranking / assembly lives in `atResourceService.ts` +
 * `composerSuggestion.ts`; ChatInput passes the final ordered `entries`.
 * This component handles:
 *   - focus-row tracking (↑↓ / hover; disabled rows are skipped by the host)
 *   - empty / loading / error states
 *   - root-query sections (Add / Plugins / Reference directories)
 *   - click-outside close (ignoring the `+` trigger button)
 *
 * Per F2 spec: 480px width and 44px row height. The 480px is owned by the
 * standalone `@` popover, or by MorphPopover's `panelWidth` when `embedded`.
 * Embedded content must be `w-full` — a second 480px inside the 1px-bordered
 * Morph shell overflows by 2px and flashes a 2s horizontal scrollbar.
 */
import {
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type KeyboardEvent as ReactKeyboardEvent,
} from 'react';
import { useTranslation } from 'react-i18next';
import {
  Bot,
  Check,
  ClipboardList,
  Folder as FolderIcon,
  FolderPlus,
  Globe2,
  History,
  Monitor,
  Paperclip,
  Plug,
  RotateCw,
  Search,
  Sparkles,
  Target,
  UsersRound,
  X,
} from 'lucide-react';

import { cn } from '@/lib/utils';
import { Tip } from '@/components/ui/tooltip';
import { GhostPluginIcon } from '@/features/plugin/GhostPluginIcon';
import type { AtResourceItem } from '@/lib/atResourceService';
import {
  composerSuggestionEntryKey,
  isComposerSuggestionEntryDisabled,
  nextEnabledSuggestionIndex,
  type ComposerSuggestionAction,
  type ComposerSuggestionEntry,
} from '@/lib/composerSuggestion';
import { extraDirBasename, extraDirDisplayLabel, isLibraryExtraDirSlot } from './extraDirsActions';

const TOOLTIP_FALLBACK_H = 120;
const VIEWPORT_PAD = 8;

type TooltipMeasure = {
  key: string | null;
  height: number;
};

function isPluginItem(item: AtResourceItem): boolean {
  return item.type === 'plugin-command' || item.type === 'plugin-resource';
}

function isPluginEntry(entry: ComposerSuggestionEntry): boolean {
  return entry.kind === 'resource' && isPluginItem(entry.item);
}

function isAddDirEntry(entry: ComposerSuggestionEntry): boolean {
  return entry.kind === 'action'
    && entry.action.id === 'add-extra-dir';
}

export type AtPanelState =
  | { kind: 'loading' }
  | { kind: 'error'; message: string }
  | { kind: 'ready'; items: AtResourceItem[]; truncated: boolean; searching?: boolean };

interface ReferenceDirsSection {
  dirs: string[];
  onRemove: (path: string) => void;
}

interface AtMentionPanelProps {
  /** Query — text after the `@` trigger (typed) or the synthetic anchor (`+`). */
  query: string;
  /** Scan state managed by the host (ChatInput) — drives loading/error/hints. */
  state: AtPanelState;
  /** Final ordered entry list (actions + resources), assembled by the host. */
  entries: ComposerSuggestionEntry[];
  focusedIndex: number;
  onFocusedIndexChange: (i: number) => void;
  onSelect: (entry: ComposerSuggestionEntry) => void;
  onClose: () => void;
  onRetry: () => void;
  /** Reference-directories management rows (empty query only; `+`-menu parity). */
  referenceDirs?: ReferenceDirsSection | null;
  /** Explicit read-write directory grants (empty query only). */
  writableDirs?: ReferenceDirsSection | null;
  /** `+` 的 MorphPopover 内嵌形态;容器、阴影与 outside-click 由 MorphPopover 负责。 */
  embedded?: boolean;
  /**
   * 面板内搜索框(合成「+」形态):传了才渲染搜索框,否则底部只留静态提示行。
   * 「+」面板是浮在输入框上方的,盖住了输入框本身 —— 让用户在看不见的输入框里盲打
   * 是死路,所以这条形态自带一个可见的输入框。
   */
  searchValue?: string;
  onSearchChange?: (value: string) => void;
  /** Panel max-height in px. Defaults to 400 (chat view); NewMaker passes a smaller value so the popover doesn't cover the logo. */
  maxHeight?: number;
}

const ACTION_ICONS: Record<ComposerSuggestionAction['id'], typeof Paperclip> = {
  'retry-plugins': RotateCw,
  'attach-files': Paperclip,
  'new-goal': Target,
  'plan-mode': ClipboardList,
  collaboration: UsersRound,
  'add-extra-dir': FolderPlus,
};

export function AtMentionPanel({
  query,
  state,
  entries,
  focusedIndex,
  onFocusedIndexChange,
  onSelect,
  onClose,
  onRetry,
  referenceDirs = null,
  writableDirs = null,
  embedded = false,
  searchValue = '',
  onSearchChange,
  maxHeight = 400,
}: AtMentionPanelProps) {
  const { t } = useTranslation();
  const libraryReadOnlyLabel = t('extraDirs.libraryReadOnlyLabel');
  // 搜索框的占位文字兼可访问名(五个语言都有,复用同一个 key 不新增词条)。
  const hint = t('newChat.atMention.typeToSearchFiles');
  // 本形态自带搜索框:静态提示行与「继续输入」提示都让位给搜索框。
  const hasSearchBox = Boolean(onSearchChange);
  const rootRef = useRef<HTMLDivElement>(null);
  const focusedRef = useRef<HTMLButtonElement>(null);
  const panelRef = useRef<HTMLDivElement | null>(null);
  // Glide highlight on the focused index; arrow keys are pressed in the editor.
  const highlightPanelRef = useMenuPanel(panelRef, {
    lockWidth: false,
    options: {
      current: currentMarkedRow,
      currentAttributes: [MENU_CURRENT_ROW_ATTR],
      keyboardSource: document,
    },
  });
  const tooltipRef = useRef<HTMLDivElement>(null);
  // 搜索框是本面板的输入面:面板浮在编辑器上方、盖住了编辑器,所以打开就把焦点给它,
  // 用户不用先点一下才能打字。
  const searchRef = useRef<HTMLInputElement | null>(null);
  useEffect(() => {
    if (!onSearchChange) return;
    searchRef.current?.focus();
  }, [onSearchChange]);
  const [panelScroll, setPanelScroll] = useState(0);
  const [tooltipMeasure, setTooltipMeasure] = useState<TooltipMeasure>({
    key: null,
    height: TOOLTIP_FALLBACK_H,
  });
  const [tooltipPos, setTooltipPos] = useState<{ top: number; maxHeight: number } | null>(null);

  const isEmptyRootQuery = !query.trim();
  // Empty-query buckets (assembly order in composerSuggestion.ts guarantees
  // add → plugins → add-extra-dir, so bucketing preserves entry indices).
  const indexed = entries.map((entry, index) => ({ entry, index }));
  const addEntries = isEmptyRootQuery
    ? indexed.filter(({ entry }) => !isPluginEntry(entry) && !isAddDirEntry(entry))
    : [];
  const pluginEntries = isEmptyRootQuery ? indexed.filter(({ entry }) => isPluginEntry(entry)) : [];
  const addDirEntry = isEmptyRootQuery
    ? indexed.find(({ entry }) => entry.kind === 'action' && entry.action.id === 'add-extra-dir')
    : undefined;
  // Merge presentation only: removal keeps each persisted grant's original path.
  const directoryRows = [referenceDirs, writableDirs].flatMap((section) =>
    section ? section.dirs.map((path) => ({ path, onRemove: section.onRemove })) : [],
  );
  const addSectionVisible = isEmptyRootQuery && addEntries.length > 0;
  const pluginSectionVisible = isEmptyRootQuery && pluginEntries.length > 0;
  const directoriesVisible = isEmptyRootQuery && (directoryRows.length > 0 || !!addDirEntry);

  useEffect(() => {
    if (entries.length === 0) return;
    if (focusedIndex < 0 || focusedIndex >= entries.length) {
      onFocusedIndexChange(0);
    }
  }, [entries.length, focusedIndex, onFocusedIndexChange]);

  useEffect(() => {
    focusedRef.current?.scrollIntoView?.({ block: 'nearest' });
  }, [focusedIndex]);

  useEffect(() => {
    if (embedded) return;
    const handleClickOutside = (e: MouseEvent) => {
      if (!rootRef.current) return;
      const target = e.target as Node;
      if (rootRef.current.contains(target)) return;
      // The `+` trigger toggles the panel itself — let its own click handler
      // decide, otherwise mousedown-close + click-toggle would reopen it.
      if (
        target instanceof Element &&
        target.closest('[data-composer-suggestion-trigger]')
      ) {
        return;
      }
      onClose();
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [embedded, onClose]);

  const focusedEntry = entries[focusedIndex];
  const focusedItem = focusedEntry?.kind === 'resource' ? focusedEntry.item : undefined;
  const showTooltip = !embedded && !!focusedItem?.description;
  const tooltipKey = showTooltip && focusedItem
    ? `${focusedItem.type}:${focusedItem.relPath}:${focusedItem.name}:${focusedItem.description ?? ''}`
    : null;
  const tooltipHeight = tooltipMeasure.key === tooltipKey
    ? tooltipMeasure.height
    : TOOLTIP_FALLBACK_H;

  useLayoutEffect(() => {
    if (!showTooltip) {
      setTooltipPos(null);
      return;
    }
    const panel = panelRef.current;
    const root = rootRef.current;
    const focusedEl = focusedRef.current;
    if (!panel || !root || !focusedEl) return;
    const panelRect = panel.getBoundingClientRect();
    const rootRect = root.getBoundingClientRect();
    const bottomBoundary = Math.min(panelRect.bottom, window.innerHeight - VIEWPORT_PAD);
    const maxTooltipHeight = Math.max(1, Math.min(maxHeight, bottomBoundary - VIEWPORT_PAD));
    const measuredHeight = Math.min(tooltipHeight, maxTooltipHeight);
    // Anchor the flyout to the focused row's actual on-screen position — the
    // section layout varies (Add / Plugins / Reference dirs headers), so
    // arithmetic row offsets are no longer reliable.
    const rawTop = focusedEl.getBoundingClientRect().top - rootRect.top;
    const minTop = VIEWPORT_PAD - rootRect.top;
    const bottomBoundaryInRoot = bottomBoundary - rootRect.top;
    const top = Math.max(minTop, Math.min(rawTop, bottomBoundaryInRoot - measuredHeight));
    setTooltipPos({
      top: Math.round(top),
      maxHeight: Math.round(maxTooltipHeight),
    });
  }, [showTooltip, focusedIndex, focusedItem, panelScroll, maxHeight, tooltipHeight]);

  const tooltipVisible = showTooltip && !!tooltipPos;
  useLayoutEffect(() => {
    if (!tooltipVisible || !tooltipKey) return;
    const tooltip = tooltipRef.current;
    if (!tooltip) return;
    const update = () => {
      const next = Math.max(1, Math.round(tooltip.getBoundingClientRect().height));
      setTooltipMeasure((prev) => (
        prev.key === tooltipKey && prev.height === next
          ? prev
          : { key: tooltipKey, height: next }
      ));
    };
    update();
    const observer = new ResizeObserver(update);
    observer.observe(tooltip);
    return () => observer.disconnect();
  }, [tooltipVisible, tooltipKey]);

  const renderSectionHeader = (label: string) => (
    <div
      className={cn(
        'flex h-[24px] items-center px-[10px]',
        'text-12 font-medium text-[var(--cmd-palette-item-meta)]',
      )}
    >
      {label}
    </div>
  );

  const renderActionRow = (action: ComposerSuggestionAction, idx: number) => {
    const focused = idx === focusedIndex;
    const Icon = ACTION_ICONS[action.id];
    const isCheckbox = action.checked !== undefined;
    // Collaboration keeps its Thinking-Orange enabled state from the legacy
    // `+` menu (id-driven presentation; the data model stays lean).
    const emphasized = action.id === 'collaboration' && action.checked === true;
    const row = (
      <button
        key={`action:${action.id}`}
        ref={focused ? focusedRef : undefined}
        type="button"
        role={isCheckbox ? 'menuitemcheckbox' : undefined}
        aria-checked={isCheckbox ? action.checked : undefined}
        aria-disabled={action.disabled ? true : undefined}
        disabled={action.disabled}
        aria-label={
          action.disabledReason ? `${action.label}: ${action.disabledReason}` : undefined
        }
        onMouseDown={(e) => {
          e.preventDefault();
        }}
        onClick={() => {
          if (action.disabled) return;
          onSelect({ kind: 'action', action });
        }}
        onMouseEnter={() => {
          if (!action.disabled) onFocusedIndexChange(idx);
        }}
        // Shared menu row: the panel's glide highlight follows the focused index, a checked
        // action is the check and 500; collaboration's orange tints the text only.
        {...menuRowAttrs({ checked: action.checked === true, current: focused, disabled: action.disabled })}
        className={cn(
          COMPOSER_MENU_ROW,
          'flex w-full items-center gap-2 px-3 py-2 text-left',
          emphasized && 'text-[var(--warning-accent)]',
          action.disabled && 'cursor-not-allowed opacity-50',
        )}
      >
        {withMenuLabels(
          <>
            <Icon size={14} className="shrink-0" />
            <span className="min-w-0 flex-1 truncate">{action.label}</span>
            {isCheckbox && action.checked && (
              <Check size={13} className="ml-auto shrink-0 text-[var(--model-item-check)]" />
            )}
          </>,
        )}
      </button>
    );
    if (action.disabled && action.disabledReason) {
      return (
        <Tip key={`action:${action.id}`} text={action.disabledReason} side="right">
          <span className="block">{row}</span>
        </Tip>
      );
    }
    return row;
  };

  const renderResourceRow = (
    entry: Extract<ComposerSuggestionEntry, { kind: 'resource' }>,
    idx: number,
  ) => {
    const item = entry.item;
    const focused = idx === focusedIndex;
    const disabled = entry.disabled === true;
    let meta: string;
    if (item.type === 'file-picker') {
      meta = '';
    } else if (item.type === 'agent') {
      meta = 'Agent';
    } else if (item.type === 'browser-tab') {
      meta = t('newChat.atMention.browserTab');
    } else if (item.type === 'desktop-window') {
      meta = item.description || t('newChat.atMention.desktopWindow');
    } else if (item.type === 'session') {
      meta = t('newChat.atMention.task');
    } else if (item.type === 'bot') {
      meta = t('newChat.atMention.bot');
    } else if (item.type === 'plugin-command') {
      // Plugin rows follow the compact icon + name presentation used by the
      // installed-plugin menu; the command remains an internal selection key.
      meta = '';
    } else if (item.type === 'plugin-resource') {
      meta = item.sourceLabel || t('newChat.atMention.pluginResource');
    } else {
      const lastSlash = item.relPath.lastIndexOf('/');
      meta = lastSlash >= 0 ? item.relPath.slice(0, lastSlash) : '';
    }
    const displayName = item.type === 'file-picker'
      ? t('newChat.atMention.filesAndFolders')
      : item.type === 'dir'
        ? `${item.name}/`
        : item.name;
    const Icon = item.type === 'file-picker'
      ? Paperclip
      : item.type === 'agent'
      ? Sparkles
      : item.type === 'dir'
        ? FolderIcon
        : item.type === 'browser-tab'
          ? Globe2
          : item.type === 'desktop-window'
            ? Monitor
            : item.type === 'session'
              ? History
              : item.type === 'bot'
                ? Bot
              : item.type === 'plugin-command' || item.type === 'plugin-resource'
                ? Plug
              : pickFileIcon(item.name);

    return (
      <button
        key={composerSuggestionEntryKey(entry)}
        ref={focused ? focusedRef : undefined}
        type="button"
        disabled={disabled}
        aria-disabled={disabled ? true : undefined}
        onMouseDown={(e) => {
          e.preventDefault();
        }}
        onClick={() => {
          if (disabled) return;
          onSelect(entry);
        }}
        onMouseEnter={() => {
          if (!disabled) onFocusedIndexChange(idx);
        }}
        {...menuRowAttrs({ current: focused, disabled })}
        className={cn(
          COMPOSER_MENU_ROW,
          'flex w-full items-center gap-2',
          'h-[44px] px-[10px] text-left',
          disabled && 'cursor-not-allowed opacity-45',
        )}
      >
        {isPluginItem(item) ? (
          <GhostPluginIcon
            iconDataUrl={item.iconDataUrl}
            iconId={item.pluginId ?? item.relPath}
            iconName={item.type === 'plugin-resource' ? (item.sourceLabel ?? item.name) : item.name}
            size="menu"
          />
        ) : (
          <Icon size={16} className="shrink-0 text-[var(--cmd-palette-item-icon)]" />
        )}
        {withMenuLabels(<span className="min-w-0 truncate">{displayName}</span>)}
        {disabled && entry.disabledReason ? (
          <span
            className={cn(
              'shrink-0 text-12 font-normal truncate max-w-[240px]',
              'text-[var(--cmd-palette-item-meta)]',
              'ml-auto',
            )}
          >
            {entry.disabledReason}
          </span>
        ) : meta ? (
          <Tip text={meta} mono>
            <span
              className={cn(
                'shrink-0 text-12 font-normal truncate max-w-[240px]',
                'text-[var(--cmd-palette-item-meta)]',
                'ml-auto',
              )}
            >
              {meta}
            </span>
          </Tip>
        ) : null}
      </button>
    );
  };

  const renderEntryRow = ({ entry, index }: { entry: ComposerSuggestionEntry; index: number }) =>
    entry.kind === 'action'
      ? renderActionRow(entry.action, index)
      : renderResourceRow(entry, index);

  /**
   * 面板内搜索框的按键:↑↓ 移动焦点行,Enter 选中,空框退格收面板。
   * 搜索框拿到焦点后编辑器收不到按键,键盘导航必须在这里自己实现一份。
   */
  const handleSearchKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
    // 输入法组字期间的 Enter 属于候选词确认,不能当成选中条目。
    if (event.nativeEvent.isComposing) return;
    if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
      event.preventDefault();
      onFocusedIndexChange(
        nextEnabledSuggestionIndex(entries, focusedIndex, event.key === 'ArrowDown' ? 1 : -1),
      );
      return;
    }
    if (event.key === 'Enter') {
      const entry = entries[focusedIndex];
      if (!entry || isComposerSuggestionEntryDisabled(entry)) return;
      event.preventDefault();
      onSelect(entry);
      return;
    }
    // 空框退格 = 往回退一步(收面板)。编辑器里同一条规则在 captureKey 里,
    // 但搜索框拿到焦点后编辑器收不到按键,这里补一份。
    if (event.key === 'Backspace' && !searchValue) {
      event.preventDefault();
      onClose();
    }
  };

  const hasDirectoryRows = isEmptyRootQuery && directoryRows.length > 0;
  const showLoadingSkeleton = state.kind === 'loading' && entries.length === 0 && !hasDirectoryRows;
  const showErrorState = state.kind === 'error' && entries.length === 0 && !hasDirectoryRows;
  const showEmptyState = !showLoadingSkeleton && !showErrorState && entries.length === 0 && !hasDirectoryRows;

  return (
    <div
      ref={rootRef}
      // 面板根标记:宿主(ChatInput)用它判定「关闭时焦点是否仍在本面板内」,
      // 决定要不要把焦点交还编辑器(搜索框退格/Esc 收起 vs 用户 Tab 走)。
      data-composer-suggestion-panel=""
      onMouseDown={(event) => {
        // 点面板空白/分组标题时别把焦点挪到面板容器:容器可聚焦(tabIndex=-1)且没有键盘
        // 处理,焦点落它身上会让 ↑↓/Enter 无人接收(打字黑洞)。行与输入框不受影响。
        const target = event.target as Element | null;
        if (target?.closest(`input, textarea, [${MENU_ROW_ATTR}]`)) return;
        event.preventDefault();
      }}
      className={cn(
        'pointer-events-auto',
        embedded ? 'relative' : 'absolute left-0 bottom-full mb-2 z-50',
      )}
    >
      <div
        ref={highlightPanelRef}
        onScroll={(e) => setPanelScroll(e.currentTarget.scrollTop)}
        {...menuPanelAttrs}
        className={cn(
          'relative',
          // embedded: fill the Morph shell. A nested w-[480px] is 2px wider
          // than the border-box panel and paints a horizontal scrollbar thumb
          // for ~2s via the global .is-scrolling auto-hide.
          embedded ? 'w-full min-w-0' : 'w-[480px]',
          'overflow-x-hidden overflow-y-auto',
          'p-[6px]',
          !embedded && [
            'rounded-[12px] border',
            'bg-[var(--cmd-palette-bg)]',
            'border-[var(--cmd-palette-border)]',
          ],
        )}
        // Registered floating-layer shadow, as on the shared menus (DESIGN §4 / §6).
        style={{ boxShadow: embedded ? undefined : 'var(--shadow-menu)', maxHeight }}
      >
        <MenuHighlightLayer />
        {hasSearchBox ? (
          <div className="px-[4px] pb-[6px]">
            <div className="relative">
              <Search
                size={12}
                className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-[var(--cmd-palette-item-meta)]"
              />
              <input
                ref={searchRef}
                data-composer-suggestion-search=""
                type="text"
                value={searchValue}
                onChange={(event) => onSearchChange?.(event.target.value)}
                onKeyDown={handleSearchKeyDown}
                placeholder={hint}
                aria-label={hint}
                className={cn(
                  'h-8 w-full rounded-full border border-[var(--cmd-palette-border)] bg-transparent',
                  'pl-7 pr-2 text-13 text-[var(--cmd-palette-item-text)] outline-none',
                  'placeholder:text-[var(--text-placeholder)]',
                  // 聚焦描边走中性弱化 token(同 composer 输入框口径)。--focus-ring
                  // 是强蓝且只用于键盘可达性环,拿来当输入框聚焦边框会突兀成蓝框
                  // (DESIGN §2:Focus Blue「正常交互流里不出现」);文本输入框的
                  // :focus-visible 恒成立,所以这里不能靠 focus-visible 区分鼠标/键盘。
                  'focus:border-[var(--chat-input-border-focus)]',
                )}
              />
            </div>
          </div>
        ) : null}
        {showLoadingSkeleton && (
          <div className="space-y-[4px] p-[4px]">
            {[0, 1, 2].map((i) => (
              <div
                key={i}
                className="h-[44px] rounded-lg bg-[var(--cmd-palette-item-hover)] opacity-40 animate-pulse"
              />
            ))}
          </div>
        )}
        {showErrorState && (
          <div className="flex flex-col items-center justify-center py-[16px] gap-[10px]">
            <div className="text-13 text-[var(--destructive)]">
              {t('newChat.atMention.scanFailed')}
            </div>
            <div className="text-12 text-[var(--cmd-palette-item-meta)] px-[12px] text-center">
              {state.kind === 'error' ? state.message : ''}
            </div>
            <Button
              variant="secondary"
              size="sm"
              compact
              type="button"
              onMouseDown={(e) => {
                e.preventDefault();
              }}
              onClick={() => {
                onRetry();
              }}
            >
              {t('newChat.atMention.retry')}
            </Button>
          </div>
        )}
        {/* 搜索形态下:空查询不占位(搜索框已经说明了怎么办),有查询但没命中才提示。 */}
        {showEmptyState && (!hasSearchBox || !isEmptyRootQuery) && (
          <div
            className={cn(
              'flex items-center justify-center',
              'select-none h-[40px] text-13',
              'text-[var(--cmd-palette-empty)]',
            )}
          >
            {state.kind === 'ready' && state.searching
              ? t('newChat.atMention.searching')
              : isEmptyRootQuery
                ? t('newChat.atMention.typeToSearchFiles')
                : t('newChat.atMention.noMatch')}
          </div>
        )}
        {(entries.length > 0 || hasDirectoryRows) && (
          <>
            {isEmptyRootQuery ? (
              <>
                {addSectionVisible && renderSectionHeader(t('newChat.atMention.add'))}
                {addEntries.map(renderEntryRow)}
                {pluginSectionVisible && renderSectionHeader(t('extraDirs.pluginsTitle'))}
                {pluginEntries.map(renderEntryRow)}
                {directoriesVisible && (addSectionVisible || pluginSectionVisible) && (
                  <div role="separator" className="my-2 border-t border-[var(--cmd-palette-border)]" />
                )}
                {directoriesVisible && (
                  <>
                    {directoryRows.length > 0 && renderSectionHeader(t('extraDirs.sectionTitle'))}
                    {directoryRows.length > 0 && (
                      <div role="list" aria-label={t('extraDirs.sectionTitle')}>
                        {directoryRows.map(({ path: p, onRemove }) => (
                          <div
                            key={p}
                            {...menuRowAttrs()}
                            className={cn(COMPOSER_MENU_ROW, 'group flex h-[44px] items-center gap-2 px-[10px]')}
                          >
                            <FolderPlus
                              size={16}
                              className="shrink-0 text-[var(--text-tertiary)]"
                            />
                            <Tip
                              text={isLibraryExtraDirSlot(p) ? extraDirDisplayLabel(p, libraryReadOnlyLabel) : p}
                              mono={!isLibraryExtraDirSlot(p)}
                              side="top"
                            >
                              <span className="min-w-0 flex-1 truncate text-left">
                                {extraDirDisplayLabel(p, libraryReadOnlyLabel)}
                              </span>
                            </Tip>
                            {isLibraryExtraDirSlot(p) ? null : (
                              <button
                                type="button"
                                onMouseDown={(e) => e.preventDefault()}
                                onClick={() => onRemove(p)}
                                className={cn(
                                  'rounded-full p-1 opacity-0 transition-opacity',
                                  'hover:bg-[var(--cmd-palette-item-hover)]',
                                  'group-hover:opacity-70 hover:!opacity-100',
                                  'focus-visible:opacity-100 focus-visible:outline-none',
                                  'focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
                                )}
                                aria-label={t('extraDirs.remove', { name: extraDirBasename(p) })}
                              >
                                <X size={12} className="text-[var(--cmd-palette-item-text)]" />
                              </button>
                            )}
                          </div>
                        ))}
                      </div>
                    )}
                    {addDirEntry && renderEntryRow(addDirEntry)}
                  </>
                )}
              </>
            ) : (
              indexed.map(renderEntryRow)
            )}
            {isEmptyRootQuery && !hasSearchBox && (
              <div
                className={cn(
                  'mt-2 border-t border-[var(--cmd-palette-border)] select-none px-[10px] py-[8px] text-12',
                  'text-[var(--cmd-palette-item-meta)]',
                )}
              >
                {t('newChat.atMention.typeToSearchFiles')}
              </div>
            )}
            {!isEmptyRootQuery && !hasSearchBox && state.kind === 'ready' && state.truncated && (
              <div
                className={cn(
                  'select-none px-[10px] py-[8px] text-12',
                  'text-[var(--cmd-palette-item-meta)]',
                )}
              >
                {t('newChat.atMention.keepTyping')}
              </div>
            )}
            {state.kind === 'error' && (
              <button
                type="button"
                onMouseDown={(e) => {
                  e.preventDefault();
                }}
                onClick={() => {
                  onRetry();
                }}
                {...menuRowAttrs()}
                className={cn(
                  COMPOSER_MENU_ROW,
                  'flex w-full items-center gap-2 px-[10px] py-[8px] text-left',
                  'text-12 text-[var(--destructive)]',
                )}
              >
                {t('newChat.atMention.scanFailed')} · {t('newChat.atMention.retry')}
              </button>
            )}
          </>
        )}
      </div>

      {/* Agent tooltip — same pattern as SlashCommandPalette tooltip.
           Only shown for resource entries that have a description. */}
      {showTooltip && tooltipPos && focusedItem && (
        <div
          ref={tooltipRef}
          className={cn(
            'w-[280px] overflow-y-auto rounded-[12px] border p-[14px]',
            'bg-[var(--cmd-palette-bg)]',
            'border-[var(--cmd-palette-border)]',
            'absolute left-[488px]',  // 480 panel + 8 gap
          )}
          style={{
            boxShadow: 'var(--cmd-palette-shadow)',
            top: tooltipPos.top,
            maxHeight: tooltipPos.maxHeight,
          }}
        >
          <div className="text-14 font-medium text-[var(--cmd-palette-item-text)]">
            {focusedItem.name}
          </div>
          <div className="mt-[8px] text-13 leading-[1.5] text-[var(--cmd-palette-tooltip-body)]">
            {focusedItem.description}
          </div>
        </div>
      )}
    </div>
  );
}