'use client'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useRouter } from 'next/navigation'; import { formatDistanceToNow } from 'date-fns'; import { IconArrowRight, IconLoader2, IconSearch, } from '@tabler/icons-react'; import { Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandShortcut, } from '@kandev/ui/command'; import { Kbd, KbdGroup } from '@kandev/ui/kbd'; import { Badge } from '@kandev/ui/badge'; import { useCommands, useCommandPanelOpen } from '@/lib/commands/command-registry'; import type { CommandPanelMode, CommandItem as CommandItemType } from '@/lib/commands/types'; import { SHORTCUTS } from '@/lib/keyboard/constants'; import { useKeyboardShortcut } from '@/hooks/use-keyboard-shortcut'; import { formatShortcut } from '@/lib/keyboard/utils'; import { useAppStore } from '@/components/state-provider'; import { useToast } from '@/components/toast-provider'; import { listTasksByWorkspace } from '@/lib/api'; import { linkToSession } from '@/lib/links'; import type { Task } from '@/lib/types/http'; const ARCHIVED_STATES = new Set(['COMPLETED', 'CANCELLED', 'FAILED']); function CommandItemRow({ cmd, onSelect }: { cmd: CommandItemType; onSelect: (cmd: CommandItemType) => void }) { return ( onSelect(cmd)} > {cmd.icon && {cmd.icon}} {cmd.label} {cmd.shortcut && {formatShortcut(cmd.shortcut)}} {cmd.enterMode && ( )} ); } export function CommandPanel() { const { open, setOpen } = useCommandPanelOpen(); const commands = useCommands(); const router = useRouter(); const { toast } = useToast(); const [mode, setMode] = useState('commands'); const [search, setSearch] = useState(''); const [taskResults, setTaskResults] = useState([]); const [isSearching, setIsSearching] = useState(false); const debounceRef = useRef | null>(null); const workspaceId = useAppStore((state) => state.workspaces.activeId); const kanbanSteps = useAppStore((state) => state.kanban.steps); // Map step IDs to step names for display const stepMap = useMemo(() => { const map = new Map(); for (const step of kanbanSteps) { map.set(step.id, { name: step.title, color: step.color }); } return map; }, [kanbanSteps]); // Toggle panel with Cmd+K, Cmd+P, or Cmd+Shift+P const openRef = useRef(open); openRef.current = open; const toggle = useCallback(() => setOpen(!openRef.current), [setOpen]); useKeyboardShortcut(SHORTCUTS.SEARCH, toggle); useKeyboardShortcut(SHORTCUTS.COMMAND_PANEL, toggle); useKeyboardShortcut(SHORTCUTS.COMMAND_PANEL_SHIFT, toggle); // Reset state when panel closes useEffect(() => { if (!open) { // Delay reset to avoid flash during close animation const t = setTimeout(() => { setMode('commands'); setSearch(''); setTaskResults([]); }, 200); return () => clearTimeout(t); } }, [open]); // Debounced task search with AbortController to prevent stale results const abortRef = useRef(null); useEffect(() => { if (mode !== 'search-tasks') return; if (debounceRef.current) clearTimeout(debounceRef.current); abortRef.current?.abort(); if (!search.trim()) { setTaskResults([]); setIsSearching(false); return; } setIsSearching(true); debounceRef.current = setTimeout(async () => { if (!workspaceId) { setIsSearching(false); return; } const controller = new AbortController(); abortRef.current = controller; try { const res = await listTasksByWorkspace( workspaceId, { query: search.trim(), page: 1, pageSize: 10 }, { init: { signal: controller.signal } } ); if (!controller.signal.aborted) { setTaskResults(res.tasks ?? []); } } catch { if (!controller.signal.aborted) { setTaskResults([]); } } finally { if (!controller.signal.aborted) { setIsSearching(false); } } }, 300); return () => { if (debounceRef.current) clearTimeout(debounceRef.current); abortRef.current?.abort(); }; }, [search, mode, workspaceId]); // Group commands by group field, sorted by best (lowest) priority in each group const grouped = useMemo(() => { const map = new Map(); for (const cmd of commands) { const existing = map.get(cmd.group) ?? []; existing.push(cmd); map.set(cmd.group, existing); } // Sort groups by the minimum priority of their items const entries = Array.from(map.entries()).sort(([, a], [, b]) => { const minA = Math.min(...a.map((c) => c.priority ?? 100)); const minB = Math.min(...b.map((c) => c.priority ?? 100)); return minA - minB; }); return entries; }, [commands]); const handleSelect = useCallback( (cmd: CommandItemType) => { if (cmd.enterMode) { setMode(cmd.enterMode); setSearch(''); return; } if (cmd.action) { setOpen(false); cmd.action(); } }, [setOpen] ); const handleTaskSelect = useCallback( (task: Task) => { setOpen(false); if (task.primary_session_id) { router.push(linkToSession(task.primary_session_id)); } else { toast({ title: 'This task has no active session', variant: 'default' }); } }, [setOpen, router, toast] ); // Handle backspace on empty input to go back to commands mode const handleKeyDown = useCallback( (e: React.KeyboardEvent) => { if (mode !== 'commands' && e.key === 'Backspace' && !search) { e.preventDefault(); setMode('commands'); setSearch(''); } }, [mode, search] ); return ( {mode === 'search-tasks' && ( { setMode('commands'); setSearch(''); }} className="shrink-0 pl-2 flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors cursor-pointer" > ← Tasks › )} {mode === 'commands' && ( <> No commands found. {search.trim() ? ( // Flat list when searching — lets cmdk rank by relevance globally {commands.map((cmd) => ( ))} ) : ( // Grouped by priority when browsing grouped.map(([group, items]) => ( {items.map((cmd) => ( ))} )) )} > )} {mode === 'search-tasks' && ( <> {isSearching && ( )} {!isSearching && search.trim() && taskResults.length === 0 && ( No tasks found. )} {!isSearching && !search.trim() && ( Type to search tasks... )} {!isSearching && taskResults.length > 0 && ( {taskResults.map((task) => { const isArchived = ARCHIVED_STATES.has(task.state); const step = stepMap.get(task.workflow_step_id); return ( handleTaskSelect(task)} className={isArchived ? 'opacity-60' : ''} > {task.title} {step && ( {step.name} )} {isArchived && ( {task.state} )} {task.updated_at && ( {formatDistanceToNow(new Date(task.updated_at), { addSuffix: true })} )} ); })} )} > )} {/* Footer bar */} ↑ ↓ Navigate ↵ {mode === 'search-tasks' ? 'Open' : 'Select'} {mode === 'search-tasks' && ( ⌫ Back )} esc Close ); }