Files
kandev/apps/web/components/task/task-switcher.tsx
T
José Almeida 8e50fe90e9 feat(web): right-click context menu to move sidebar tasks between steps (#492)
* feat(web): add right-click context menu to move sidebar tasks between workflow steps

* fix: scope Move to submenu to task's own workflow steps

* fix: surgical rollback and disable actions during delete

* fix: wrap TaskItem in div for ContextMenuTrigger asChild ref forwarding

* refactor: unify right-click and 3-dot menus into single context menu

- Delete task-item-menu.tsx (DropdownMenu) — no longer needed
- TaskItem's 3-dot button now dispatches contextmenu event to trigger
  the wrapping ContextMenu
- TaskItemWithContextMenu tracks open state and passes menuOpen to
  TaskItem for hover visibility
- Add Duplicate item to the context menu
- Fix step color dots using block display

* fix: use Tailwind class for step color dots instead of inline style

* fix: disable Duplicate menu item until handler is implemented

* fix: defer move-to-step to let context menu close before optimistic update

* fix: defer move-to-step to let context menu close before optimistic update
2026-04-06 00:57:01 +01:00

416 lines
12 KiB
TypeScript

"use client";
import { cloneElement, isValidElement, memo, useMemo, useState } from "react";
import type { ComponentType } from "react";
import {
IconCircleCheck,
IconCircleDashed,
IconProgress,
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, truncateRepoPath } from "@/lib/utils";
import { TaskItem } from "./task-item";
const SECTION_ICONS: Record<
string,
{ Icon: ComponentType<{ className?: string }>; className: string }
> = {
"Turn Finished": { Icon: IconCircleCheck, className: "text-green-500" },
Running: { Icon: IconProgress, className: "text-yellow-500" },
Backlog: { Icon: IconCircleDashed, className: "text-muted-foreground" },
};
type DiffStats = {
additions: number;
deletions: number;
};
type TaskSwitcherItem = {
id: string;
title: string;
state?: TaskState;
sessionState?: TaskSessionState;
description?: string;
workflowId?: string;
workflowStepId?: string;
repositoryPath?: string;
diffStats?: DiffStats;
isRemoteExecutor?: boolean;
remoteExecutorType?: string;
remoteExecutorName?: string;
updatedAt?: string;
createdAt?: string;
isArchived?: boolean;
primarySessionId?: string | null;
parentTaskTitle?: string;
};
type StepDef = { id: string; title: string; color?: string };
type TaskSwitcherProps = {
tasks: TaskSwitcherItem[];
steps: StepDef[];
stepsByWorkflowId?: Record<string, StepDef[]>;
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 Section = {
label: string;
tasks: TaskSwitcherItem[];
};
const REVIEW_STATES = new Set<TaskSessionState>([
"WAITING_FOR_INPUT",
"COMPLETED",
"FAILED",
"CANCELLED",
]);
const IN_PROGRESS_STATES = new Set<TaskSessionState>(["RUNNING"]);
const BACKLOG_STATES = new Set<TaskSessionState>(["CREATED", "STARTING"]);
const TASK_STATE_REVIEW = new Set<TaskState | undefined>(["REVIEW", "COMPLETED"]);
const TASK_STATE_IN_PROGRESS = new Set<TaskState | undefined>(["IN_PROGRESS"]);
function classifyTask(
sessionState: TaskSessionState | undefined,
taskState?: TaskState,
): "review" | "in_progress" | "backlog" {
if (!sessionState) return "backlog";
// STARTING is transient (e.g., resume after backend restart). Use the
// task-level state so the sidebar position stays stable.
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";
if (BACKLOG_STATES.has(sessionState)) return "backlog";
return "backlog";
}
function TaskSwitcherSkeleton() {
return (
<div className="animate-pulse">
<div className="h-10 bg-foreground/5" />
<div className="h-10 bg-foreground/5 mt-px" />
<div className="h-10 bg-foreground/5 mt-px" />
<div className="h-10 bg-foreground/5 mt-px" />
</div>
);
}
function SectionHeader({ label, count }: { label: string; count: number }) {
const icon = SECTION_ICONS[label];
return (
<div
data-testid={`sidebar-section-${label}`}
className="flex items-center justify-between px-3 py-1.5 bg-background"
>
<span className="flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground uppercase tracking-wide">
{icon && <icon.Icon className={`h-3 w-3 ${icon.className}`} />}
{label}
</span>
<span className="text-[11px] text-muted-foreground/60">{count}</span>
</div>
);
}
function TaskSwitcherSection({
section,
stepsByWorkflowId,
stepNameById,
activeTaskId,
selectedTaskId,
onSelectTask,
onRenameTask,
onArchiveTask,
onDeleteTask,
onMoveToStep,
deletingTaskId,
}: {
section: Section;
stepsByWorkflowId?: Record<string, StepDef[]>;
stepNameById: Map<string, string>;
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;
}) {
if (section.tasks.length === 0) return null;
return (
<div>
<SectionHeader label={section.label} count={section.tasks.length} />
{section.tasks.map((task) => {
const isActive = task.id === activeTaskId;
const isSelected = task.id === selectedTaskId || isActive;
const repoLabel = task.repositoryPath ? truncateRepoPath(task.repositoryPath) : undefined;
const stepName = task.workflowStepId ? stepNameById.get(task.workflowStepId) : undefined;
return (
<TaskItemWithContextMenu
key={task.id}
task={task}
steps={task.workflowId ? stepsByWorkflowId?.[task.workflowId] : undefined}
onRenameTask={onRenameTask}
onArchiveTask={onArchiveTask}
onDeleteTask={onDeleteTask}
onMoveToStep={onMoveToStep}
isDeleting={deletingTaskId === task.id}
>
<TaskItem
title={task.title}
description={repoLabel}
stepName={stepName}
state={task.state}
sessionState={task.sessionState}
isArchived={task.isArchived}
isSelected={isSelected}
diffStats={task.diffStats}
isRemoteExecutor={task.isRemoteExecutor}
remoteExecutorType={task.remoteExecutorType}
remoteExecutorName={task.remoteExecutorName}
taskId={task.id}
primarySessionId={task.primarySessionId ?? null}
updatedAt={task.updatedAt}
parentTaskTitle={task.parentTaskTitle}
onClick={() => onSelectTask(task.id)}
isDeleting={deletingTaskId === task.id}
/>
</TaskItemWithContextMenu>
);
})}
</div>
);
}
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 (
<ContextMenu key={menuKey} onOpenChange={setContextOpen}>
<ContextMenuTrigger asChild>
<div>{cloneWithMenuOpen(children, menuOpen)}</div>
</ContextMenuTrigger>
<ContextMenuContent className="w-48">
{onRenameTask && (
<ContextMenuItem disabled={isDeleting} onClick={() => onRenameTask(task.id, task.title)}>
<IconPencil className="mr-2 h-4 w-4" />
Rename
</ContextMenuItem>
)}
<ContextMenuItem disabled>
<IconCopy className="mr-2 h-4 w-4" />
Duplicate
</ContextMenuItem>
{onArchiveTask && (
<ContextMenuItem disabled={isDeleting} onClick={() => onArchiveTask(task.id)}>
<IconArchive className="mr-2 h-4 w-4" />
Archive
</ContextMenuItem>
)}
{onMoveToStep && task.workflowId && steps && steps.length > 0 && (
<MoveToStepSubmenu
steps={steps}
currentStepId={task.workflowStepId}
disabled={isDeleting}
onSelect={(stepId) => {
setContextOpen(false);
setMenuKey((k) => k + 1);
onMoveToStep(task.id, task.workflowId!, stepId);
}}
/>
)}
{onDeleteTask && (
<>
<ContextMenuSeparator />
<ContextMenuItem
variant="destructive"
disabled={isDeleting}
onClick={() => onDeleteTask(task.id)}
>
{isDeleting ? (
<IconLoader className="mr-2 h-4 w-4 animate-spin" />
) : (
<IconTrash className="mr-2 h-4 w-4" />
)}
Delete
</ContextMenuItem>
</>
)}
</ContextMenuContent>
</ContextMenu>
);
}
function MoveToStepSubmenu({
steps,
currentStepId,
disabled,
onSelect,
}: {
steps: StepDef[];
currentStepId?: string;
disabled?: boolean;
onSelect: (stepId: string) => void;
}) {
return (
<>
<ContextMenuSeparator />
<ContextMenuSub>
<ContextMenuSubTrigger disabled={disabled}>
<IconArrowRight className="mr-2 h-4 w-4" />
Move to
</ContextMenuSubTrigger>
<ContextMenuSubContent className="w-44">
{steps.map((step) => (
<ContextMenuItem
key={step.id}
disabled={step.id === currentStepId}
onSelect={(e) => {
e.preventDefault();
onSelect(step.id);
}}
>
<span className={cn("block h-2 w-2 rounded-full shrink-0", step.color)} />
<span className="flex-1 truncate">{step.title}</span>
{step.id === currentStepId && (
<span className="ml-auto text-[10px] text-muted-foreground">Current</span>
)}
</ContextMenuItem>
))}
</ContextMenuSubContent>
</ContextMenuSub>
</>
);
}
function cloneWithMenuOpen(
children: React.ReactElement<{ menuOpen?: boolean }>,
menuOpen: boolean,
): React.ReactNode {
if (isValidElement(children)) return cloneElement(children, { menuOpen });
return children;
}
export const TaskSwitcher = memo(function TaskSwitcher({
tasks,
steps,
stepsByWorkflowId,
activeTaskId,
selectedTaskId,
onSelectTask,
onRenameTask,
onArchiveTask,
onDeleteTask,
onMoveToStep,
deletingTaskId,
isLoading = false,
}: TaskSwitcherProps) {
const stepNameById = useMemo(() => {
const map = new Map<string, string>();
for (const col of steps) {
map.set(col.id, col.title);
}
return map;
}, [steps]);
const sections = useMemo(() => {
const review: TaskSwitcherItem[] = [];
const inProgress: TaskSwitcherItem[] = [];
const backlog: TaskSwitcherItem[] = [];
for (const task of tasks) {
const bucket = classifyTask(task.sessionState, task.state);
if (bucket === "review") review.push(task);
else if (bucket === "in_progress") inProgress.push(task);
else backlog.push(task);
}
const byCreatedAt = (a: TaskSwitcherItem, b: TaskSwitcherItem) =>
(a.createdAt ?? "").localeCompare(b.createdAt ?? "");
return [
{ label: "Turn Finished", tasks: review.sort(byCreatedAt) },
{ label: "Running", tasks: inProgress.sort(byCreatedAt) },
{ label: "Backlog", tasks: backlog.sort(byCreatedAt) },
] satisfies Section[];
}, [tasks]);
if (isLoading) {
return <TaskSwitcherSkeleton />;
}
if (tasks.length === 0) {
return <div className="px-3 py-3 text-xs text-muted-foreground">No tasks yet.</div>;
}
return (
<div>
{sections.map((section) => (
<TaskSwitcherSection
key={section.label}
section={section}
stepsByWorkflowId={stepsByWorkflowId}
stepNameById={stepNameById}
activeTaskId={activeTaskId}
selectedTaskId={selectedTaskId}
onSelectTask={onSelectTask}
onRenameTask={onRenameTask}
onArchiveTask={onArchiveTask}
onDeleteTask={onDeleteTask}
onMoveToStep={onMoveToStep}
deletingTaskId={deletingTaskId}
/>
))}
</div>
);
});