"use client"; import { cloneElement, isValidElement, memo, useMemo, useState } from "react"; import { IconChevronDown, IconArrowRight, IconPencil, IconCopy, IconArchive, IconTrash, IconLoader, } from "@tabler/icons-react"; import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger, } from "@kandev/ui/context-menu"; import type { TaskState, TaskSessionState } from "@/lib/types/http"; import { cn } from "@/lib/utils"; import { TaskItem } from "./task-item"; export type TaskSwitcherItem = { id: string; title: string; state?: TaskState; sessionState?: TaskSessionState; description?: string; workflowId?: string; workflowStepId?: string; repositoryPath?: string; repositories?: string[]; diffStats?: { additions: number; deletions: number }; isRemoteExecutor?: boolean; remoteExecutorType?: string; remoteExecutorName?: string; updatedAt?: string; createdAt?: string; isArchived?: boolean; primarySessionId?: string | null; parentTaskTitle?: string; parentTaskId?: string; prInfo?: { number: number; state: string }; }; type StepDef = { id: string; title: string; color?: string }; type TaskSwitcherProps = { tasks: TaskSwitcherItem[]; steps?: StepDef[]; stepsByWorkflowId?: Record; activeTaskId: string | null; selectedTaskId: string | null; onSelectTask: (taskId: string) => void; onRenameTask?: (taskId: string, currentTitle: string) => void; onArchiveTask?: (taskId: string) => void; onDeleteTask?: (taskId: string) => void; onMoveToStep?: (taskId: string, workflowId: string, targetStepId: string) => void; deletingTaskId?: string | null; isLoading?: boolean; }; type RepoGroup = { key: string; label: string; isMultiRepo?: boolean; tasks: TaskSwitcherItem[]; }; const REVIEW_STATES = new Set([ "WAITING_FOR_INPUT", "COMPLETED", "FAILED", "CANCELLED", ]); const IN_PROGRESS_STATES = new Set(["RUNNING"]); const TASK_STATE_REVIEW = new Set(["REVIEW", "COMPLETED"]); const TASK_STATE_IN_PROGRESS = new Set(["IN_PROGRESS"]); function classifyTask( sessionState: TaskSessionState | undefined, taskState?: TaskState, ): "review" | "in_progress" | "backlog" { if (!sessionState) { if (TASK_STATE_REVIEW.has(taskState)) return "review"; if (TASK_STATE_IN_PROGRESS.has(taskState)) return "in_progress"; return "backlog"; } if (sessionState === "STARTING" && taskState) { if (TASK_STATE_REVIEW.has(taskState)) return "review"; if (TASK_STATE_IN_PROGRESS.has(taskState)) return "in_progress"; return "backlog"; } if (REVIEW_STATES.has(sessionState)) return "review"; if (IN_PROGRESS_STATES.has(sessionState)) return "in_progress"; return "backlog"; } function statePriority(task: TaskSwitcherItem): number { const bucket = classifyTask(task.sessionState, task.state); if (bucket === "in_progress") return 0; if (bucket === "review") return 1; return 2; } function sortByStateThenCreated(a: TaskSwitcherItem, b: TaskSwitcherItem): number { // State first, then newest createdAt first (descending) return ( statePriority(a) - statePriority(b) || (b.createdAt ?? "").localeCompare(a.createdAt ?? "") ); } function TaskSwitcherSkeleton() { return (
); } function RepoGroupHeader({ label, count, isCollapsed, onToggle, }: { label: string; count: number; isCollapsed: boolean; onToggle: () => void; }) { return ( ); } function RepoGroupSection({ group, subTasksByParentId, stepsByWorkflowId, activeTaskId, selectedTaskId, onSelectTask, onRenameTask, onArchiveTask, onDeleteTask, onMoveToStep, deletingTaskId, }: { group: RepoGroup; subTasksByParentId: Map; stepsByWorkflowId?: Record; activeTaskId: string | null; selectedTaskId: string | null; onSelectTask: (taskId: string) => void; onRenameTask?: (taskId: string, currentTitle: string) => void; onArchiveTask?: (taskId: string) => void; onDeleteTask?: (taskId: string) => void; onMoveToStep?: (taskId: string, workflowId: string, targetStepId: string) => void; deletingTaskId?: string | null; }) { const [isCollapsed, setIsCollapsed] = useState(false); const totalCount = group.tasks.reduce( (sum, t) => sum + 1 + (subTasksByParentId.get(t.id)?.length ?? 0), 0, ); function renderItem(task: TaskSwitcherItem, isSubTask?: boolean) { const isSelected = task.id === selectedTaskId || task.id === activeTaskId; const taskSteps = task.workflowId ? stepsByWorkflowId?.[task.workflowId] : undefined; return ( onSelectTask(task.id)} isDeleting={deletingTaskId === task.id} /> ); } return (
setIsCollapsed((v) => !v)} /> {!isCollapsed && group.tasks.map((task) => (
{renderItem(task)} {subTasksByParentId.get(task.id)?.map((sub) => renderItem(sub, true))}
))}
); } function TaskItemWithContextMenu({ task, steps, children, onRenameTask, onArchiveTask, onDeleteTask, onMoveToStep, isDeleting, }: { task: TaskSwitcherItem; steps?: StepDef[]; children: React.ReactElement<{ menuOpen?: boolean }>; onRenameTask?: (taskId: string, currentTitle: string) => void; onArchiveTask?: (taskId: string) => void; onDeleteTask?: (taskId: string) => void; onMoveToStep?: (taskId: string, workflowId: string, targetStepId: string) => void; isDeleting?: boolean; }) { const [contextOpen, setContextOpen] = useState(false); const [menuKey, setMenuKey] = useState(0); const menuOpen = contextOpen || isDeleting === true; return (
{cloneWithMenuOpen(children, menuOpen)}
{onRenameTask && ( onRenameTask(task.id, task.title)}> Rename )} Duplicate {onArchiveTask && ( onArchiveTask(task.id)}> Archive )} {onMoveToStep && task.workflowId && steps && steps.length > 0 && ( { setContextOpen(false); setMenuKey((k) => k + 1); onMoveToStep(task.id, task.workflowId!, stepId); }} /> )} {onDeleteTask && ( <> onDeleteTask(task.id)} > {isDeleting ? ( ) : ( )} Delete )}
); } function MoveToStepSubmenu({ steps, currentStepId, disabled, onSelect, }: { steps: StepDef[]; currentStepId?: string; disabled?: boolean; onSelect: (stepId: string) => void; }) { return ( <> Move to {steps.map((step) => ( { e.preventDefault(); onSelect(step.id); }} > {step.title} {step.id === currentStepId && ( Current )} ))} ); } function cloneWithMenuOpen( children: React.ReactElement<{ menuOpen?: boolean }>, menuOpen: boolean, ): React.ReactNode { if (isValidElement(children)) return cloneElement(children, { menuOpen }); return children; } /** Partition root tasks into multi-repo, per-repo, and unassigned buckets. */ function partitionRootTasks(rootTasks: TaskSwitcherItem[]): { multiRepoTasks: TaskSwitcherItem[]; byRepo: Map; unassigned: TaskSwitcherItem[]; } { const multiRepoTasks: TaskSwitcherItem[] = []; const byRepo = new Map(); const unassigned: TaskSwitcherItem[] = []; for (const task of rootTasks) { if (task.repositories && task.repositories.length > 1) { multiRepoTasks.push(task); } else if (task.repositoryPath) { const arr = byRepo.get(task.repositoryPath) ?? []; arr.push(task); byRepo.set(task.repositoryPath, arr); } else { unassigned.push(task); } } return { multiRepoTasks, byRepo, unassigned }; } /** Build sorted repo groups from partitioned task buckets. */ function buildRepoGroups( multiRepoTasks: TaskSwitcherItem[], byRepo: Map, unassigned: TaskSwitcherItem[], ): RepoGroup[] { const result: RepoGroup[] = []; if (multiRepoTasks.length > 0) { result.push({ key: "multi-repo", label: "Multi-repo", isMultiRepo: true, tasks: [...multiRepoTasks].sort(sortByStateThenCreated), }); } for (const [slug, groupTasks] of byRepo) { result.push({ key: slug, label: slug, tasks: [...groupTasks].sort(sortByStateThenCreated) }); } if (unassigned.length > 0) { // In single-repo workspaces, merge unassigned tasks into the repo group // so every task appears under a meaningful label instead of "Unassigned". const singleRepoGroup = byRepo.size === 1 && multiRepoTasks.length === 0 ? result.find((g) => g.key !== "multi-repo") : undefined; if (singleRepoGroup) { singleRepoGroup.tasks = [...singleRepoGroup.tasks, ...unassigned].sort( sortByStateThenCreated, ); } else { result.push({ key: "unassigned", label: "Unassigned", tasks: [...unassigned].sort(sortByStateThenCreated), }); } } return result; } /** Group tasks by repository, separating sub-tasks from root tasks. */ function groupTasksIntoRepos(tasks: TaskSwitcherItem[]): { groups: RepoGroup[]; subTasksByParentId: Map; } { const allTaskIds = new Set(tasks.map((t) => t.id)); const subMap = new Map(); const rootTasks: TaskSwitcherItem[] = []; for (const t of tasks) { if (t.parentTaskId && allTaskIds.has(t.parentTaskId)) { const arr = subMap.get(t.parentTaskId) ?? []; arr.push(t); subMap.set(t.parentTaskId, arr); } else { rootTasks.push(t); } } const { multiRepoTasks, byRepo, unassigned } = partitionRootTasks(rootTasks); return { groups: buildRepoGroups(multiRepoTasks, byRepo, unassigned), subTasksByParentId: subMap, }; } export const TaskSwitcher = memo(function TaskSwitcher({ tasks, stepsByWorkflowId, activeTaskId, selectedTaskId, onSelectTask, onRenameTask, onArchiveTask, onDeleteTask, onMoveToStep, deletingTaskId, isLoading = false, }: TaskSwitcherProps) { const { groups, subTasksByParentId } = useMemo(() => groupTasksIntoRepos(tasks), [tasks]); if (isLoading) return ; if (tasks.length === 0) { return
No tasks yet.
; } return (
{groups.map((group) => ( ))}
); });