mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-20 07:00:58 +08:00
Every user-visible string in the web UI now goes through t() from web/src/i18n. The English source text is the key, so a missing entry falls back to English and nothing breaks; Turkish lives in one flat file, web/src/i18n/locales/tr.json (about 2,600 entries). The locale is chosen once per page load: a saved choice, else the browser language, else English. Switching (new Language toggle under Preferences) stores the choice and reloads, so t() also works in module constants, helpers and toasts without hooks. Also: - hard-coded zh-CN / implicit date locales now follow the UI language - sentences assembled from fragments became single templates - "Toujours autoriser" in approval records is now English - upload.test.mjs stubs the new @/i18n import Values sent to the API or compared in code, agent prompts, and backend messages are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3579 lines
141 KiB
TypeScript
3579 lines
141 KiB
TypeScript
"use client";
|
||
|
||
import * as React from "react";
|
||
|
||
import Link from "next/link";
|
||
|
||
import {
|
||
DndContext,
|
||
type DragEndEvent,
|
||
DragOverlay,
|
||
type DragStartEvent,
|
||
KeyboardSensor,
|
||
PointerSensor,
|
||
useDraggable,
|
||
useDroppable,
|
||
useSensor,
|
||
useSensors,
|
||
} from "@dnd-kit/core";
|
||
import {
|
||
ArchiveIcon,
|
||
ArrowDownIcon,
|
||
ArrowUpDownIcon,
|
||
ArrowUpIcon,
|
||
ChevronRightIcon,
|
||
EyeIcon,
|
||
FolderInputIcon,
|
||
GripVerticalIcon,
|
||
Loader2Icon,
|
||
PaperclipIcon,
|
||
PauseIcon,
|
||
PencilIcon,
|
||
PinIcon,
|
||
PinOffIcon,
|
||
PlayIcon,
|
||
PlusIcon,
|
||
TrashIcon,
|
||
SaveIcon,
|
||
SearchIcon,
|
||
SlidersHorizontalIcon,
|
||
StarIcon,
|
||
TagsIcon,
|
||
Trash2Icon,
|
||
Undo2Icon,
|
||
XIcon,
|
||
} from "lucide-react";
|
||
import { toast } from "sonner";
|
||
|
||
import { AssetInterceptRulesEditor } from "@/components/asset-intercept-rules-editor";
|
||
import { StatusBadge } from "@/components/status-badge";
|
||
import { TablePagination } from "@/components/table-pagination";
|
||
import { TaskLLMProfileChain } from "@/components/task-llm-profile-chain";
|
||
import { TaskTemplateControls } from "@/components/task-template-controls";
|
||
import {
|
||
AlertDialog,
|
||
AlertDialogAction,
|
||
AlertDialogCancel,
|
||
AlertDialogContent,
|
||
AlertDialogDescription,
|
||
AlertDialogFooter,
|
||
AlertDialogHeader,
|
||
AlertDialogTitle,
|
||
AlertDialogTrigger,
|
||
} from "@/components/ui/alert-dialog";
|
||
import { Badge } from "@/components/ui/badge";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Card, CardContent } from "@/components/ui/card";
|
||
import { Checkbox } from "@/components/ui/checkbox";
|
||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
|
||
import {
|
||
Combobox,
|
||
ComboboxChip,
|
||
ComboboxChips,
|
||
ComboboxChipsInput,
|
||
ComboboxContent,
|
||
ComboboxEmpty,
|
||
ComboboxItem,
|
||
ComboboxList,
|
||
ComboboxValue,
|
||
} from "@/components/ui/combobox";
|
||
import {
|
||
Dialog,
|
||
DialogClose,
|
||
DialogContent,
|
||
DialogDescription,
|
||
DialogFooter,
|
||
DialogHeader,
|
||
DialogTitle,
|
||
DialogTrigger,
|
||
} from "@/components/ui/dialog";
|
||
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||
import {
|
||
Field,
|
||
FieldContent,
|
||
FieldDescription,
|
||
FieldGroup,
|
||
FieldLabel,
|
||
FieldLegend,
|
||
FieldSet,
|
||
} from "@/components/ui/field";
|
||
import { Input } from "@/components/ui/input";
|
||
import { Item, ItemActions, ItemContent, ItemDescription, ItemGroup, ItemMedia, ItemTitle } from "@/components/ui/item";
|
||
import { Label } from "@/components/ui/label";
|
||
import { Progress } from "@/components/ui/progress";
|
||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||
import {
|
||
Sheet,
|
||
SheetClose,
|
||
SheetContent,
|
||
SheetDescription,
|
||
SheetFooter,
|
||
SheetHeader,
|
||
SheetTitle,
|
||
SheetTrigger,
|
||
} from "@/components/ui/sheet";
|
||
import { Spinner } from "@/components/ui/spinner";
|
||
import { Switch } from "@/components/ui/switch";
|
||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||
import { Textarea } from "@/components/ui/textarea";
|
||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||
import { intlLocale, t } from "@/i18n";
|
||
import { setVisibleInterval } from "@/lib/polling";
|
||
import { api } from "@/lib/api";
|
||
import { getLocalStorageValue, setLocalStorageValue } from "@/lib/local-storage.client";
|
||
import { type SortDirection, useStoredSortPreference } from "@/lib/sort-preference";
|
||
import type {
|
||
AssetInterceptRuleInput,
|
||
TaskCredentialInput,
|
||
ChatAttachment,
|
||
Company,
|
||
DeleteTaskOptions,
|
||
DeleteTaskResult,
|
||
LLMProfile,
|
||
Task,
|
||
TaskArchive,
|
||
TaskArchiveState,
|
||
TaskCategory,
|
||
TaskStatus,
|
||
} from "@/lib/types";
|
||
import { cn } from "@/lib/utils";
|
||
|
||
// fmtBytes renders a human file size for the upload manifest.
|
||
function fmtBytes(n: number): string {
|
||
if (n >= 1 << 20) return `${(n / (1 << 20)).toFixed(1)} MB`;
|
||
if (n >= 1 << 10) return `${(n / (1 << 10)).toFixed(1)} KB`;
|
||
return `${n} B`;
|
||
}
|
||
|
||
// UPLOAD_MARKER labels the auto-appended block of uploaded-file paths inside the task
|
||
// description, so re-uploads append under the same block instead of adding a new header.
|
||
const UPLOAD_MARKER = "[Uploaded Files (Absolute Paths)]";
|
||
|
||
// appendUploads folds newly-uploaded files' ABSOLUTE paths into the description as a
|
||
// Read/Bash-friendly manifest — the worker opens them by path. Keeps one marked block:
|
||
// first upload adds the header, later uploads append bullets under it.
|
||
function appendUploads(desc: string, atts: ChatAttachment[]): string {
|
||
const bullets = atts.map((a) => `- ${a.abs ?? a.path} (${fmtBytes(a.size)})`).join("\n");
|
||
if (desc.includes(UPLOAD_MARKER)) {
|
||
return `${desc.replace(/\s*$/, "")}\n${bullets}\n`;
|
||
}
|
||
const head = desc.trim() ? `${desc.replace(/\s*$/, "")}\n\n` : "";
|
||
return `${head}${UPLOAD_MARKER} worker can open them by path with Read/Bash:\n${bullets}\n`;
|
||
}
|
||
|
||
// POLL_MS is the task-list refresh interval. Task state moves on the server (planner /
|
||
// worker), so the list has to be pulled; 10s is plenty for status / progress / token changes.
|
||
const POLL_MS = 10_000;
|
||
const MAX_SOURCE_TASKS = 8;
|
||
|
||
// fmtTokens renders a compact token count (1234 → 1.2k, 2_000_000 → 2M).
|
||
function fmtTokens(n: number): string {
|
||
if (n >= 1_000_000) return (n / 1_000_000).toFixed(n >= 10_000_000 ? 0 : 1) + "M";
|
||
if (n >= 1000) return (n / 1000).toFixed(n >= 10000 ? 0 : 1) + "k";
|
||
return String(n);
|
||
}
|
||
|
||
// fmtDuration renders a run duration in seconds as a compact human string.
|
||
function fmtDuration(sec: number): string {
|
||
if (sec <= 0) return "—";
|
||
const d = Math.floor(sec / 86400);
|
||
const h = Math.floor((sec % 86400) / 3600);
|
||
const m = Math.floor((sec % 3600) / 60);
|
||
const s = sec % 60;
|
||
if (d > 0) return t("{d}d {h}h", { d, h });
|
||
if (h > 0) return t("{h}h {m}m", { h, m });
|
||
if (m > 0) return t("{m}m {s}s", { m, s });
|
||
return t("{s}s", { s });
|
||
}
|
||
|
||
// taskDuration is the task's run duration in seconds: created → now while running,
|
||
// created → completion for a finished task, else created → last activity. 0 when it
|
||
// never ran (no activity yet).
|
||
function taskDuration(task: Task, nowSec: number): number {
|
||
const start = task.created_unix ?? 0;
|
||
if (!start) return 0;
|
||
const end =
|
||
task.status === "running"
|
||
? nowSec
|
||
: task.completed_unix && task.completed_unix > 0
|
||
? task.completed_unix
|
||
: (task.last_activity_unix ?? 0);
|
||
return end > start ? end - start : 0;
|
||
}
|
||
|
||
// deleteDetails takes only the countable part of the result so callers can pass an
|
||
// aggregate accumulated over a bulk delete.
|
||
type DeleteCounts = Omit<DeleteTaskResult, "deleted" | "cleanup_warning">;
|
||
|
||
function deleteDetails(result: DeleteCounts): string[] {
|
||
const details: string[] = [];
|
||
if (result.assets_deleted > 0) details.push(t("Deleted {count} assets", { count: result.assets_deleted }));
|
||
if (result.assets_detached > 0) details.push(t("Detached {count} shared assets", { count: result.assets_detached }));
|
||
if (result.traffic_deleted > 0) details.push(t("Deleted {count} traffic records", { count: result.traffic_deleted }));
|
||
if (result.files_deleted) details.push(t("Deleted task files"));
|
||
if (result.findings_deleted > 0) details.push(t("Deleted {count} findings", { count: result.findings_deleted }));
|
||
if (result.llm_records_deleted > 0) details.push(t("Deleted {count} LLM request/response records", { count: result.llm_records_deleted }));
|
||
return details;
|
||
}
|
||
|
||
function deleteSummary(result: DeleteTaskResult): string {
|
||
const details = deleteDetails(result);
|
||
return details.length > 0 ? t("Task deleted ({details})", { details: details.join(", ") }) : t("Task deleted");
|
||
}
|
||
|
||
// fmtDateTime renders a unix-seconds timestamp as a compact local date-time
|
||
// (MM-DD HH:mm), or "—" when unset.
|
||
function fmtDateTime(unix?: number): string {
|
||
if (!unix || unix <= 0) return "—";
|
||
const d = new Date(unix * 1000);
|
||
const p = (n: number) => String(n).padStart(2, "0");
|
||
return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
||
}
|
||
|
||
const STATUS_OPTIONS: { value: TaskStatus; label: string }[] = [
|
||
{ value: "created", label: t("Created") },
|
||
{ value: "queued", label: t("Queued") },
|
||
{ value: "running", label: t("Running") },
|
||
{ value: "paused", label: t("Paused") },
|
||
{ value: "done", label: t("Completed") },
|
||
{ value: "failed", label: t("Failed") },
|
||
{ value: "timeout", label: t("Timed out") },
|
||
];
|
||
|
||
// Select does not accept an empty-string value, so "no category" in the filter, the create form, and the bulk move
|
||
// all use this sentinel value, which is translated back to the backend's null on submit.
|
||
const UNCATEGORIZED_VALUE = "uncategorized";
|
||
|
||
// Pausable = non-terminal and not paused, matching the backend's applyTaskControlWithCause gating
|
||
// (done/failed/timeout are terminal); only paused can be resumed. The inline buttons and the bulk controls share this check,
|
||
// so the two sides can never disagree about one being clickable and the other not.
|
||
const PAUSABLE_STATUSES = new Set<TaskStatus>(["created", "queued", "running"]);
|
||
const ARCHIVABLE_STATUSES = new Set<TaskStatus>(["paused", "done", "failed", "timeout"]);
|
||
|
||
function taskControlAction(status: TaskStatus): "pause" | "resume" | null {
|
||
if (status === "paused") return "resume";
|
||
if (PAUSABLE_STATUSES.has(status)) return "pause";
|
||
return null;
|
||
}
|
||
|
||
type TaskSortField = "id" | "created" | "duration" | "status";
|
||
|
||
const TASK_SORT_FIELDS: readonly TaskSortField[] = ["id", "created", "duration", "status"];
|
||
const TASK_SORT_PREFERENCE_KEY = "artex_task_list_sort";
|
||
const TASK_FILTER_PREFERENCE_KEY = "artex_task_list_filters";
|
||
|
||
const TASK_STATUS_RANK = new Map(STATUS_OPTIONS.map((option, index) => [option.value, index]));
|
||
|
||
function taskIsPinned(task: Task): boolean {
|
||
return task.pinned ?? Boolean(task.pinned_at);
|
||
}
|
||
|
||
function compareTaskIDs(left: string, right: string): number {
|
||
return left.localeCompare(right, undefined, { numeric: true, sensitivity: "base" });
|
||
}
|
||
|
||
function taskCreatedUnix(task: Task): number {
|
||
if (task.created_unix) return task.created_unix;
|
||
const parsed = Date.parse(task.created_at);
|
||
return Number.isNaN(parsed) ? 0 : Math.floor(parsed / 1000);
|
||
}
|
||
|
||
function compareTasks(left: Task, right: Task, field: TaskSortField, direction: SortDirection, nowSec: number): number {
|
||
const leftPinned = taskIsPinned(left);
|
||
const rightPinned = taskIsPinned(right);
|
||
if (leftPinned !== rightPinned) return leftPinned ? -1 : 1;
|
||
if (leftPinned && left.pinned_at !== right.pinned_at) {
|
||
return (right.pinned_at ?? "").localeCompare(left.pinned_at ?? "");
|
||
}
|
||
|
||
let compared = 0;
|
||
switch (field) {
|
||
case "created":
|
||
compared = taskCreatedUnix(left) - taskCreatedUnix(right);
|
||
break;
|
||
case "duration":
|
||
compared = taskDuration(left, nowSec) - taskDuration(right, nowSec);
|
||
break;
|
||
case "status":
|
||
compared = (TASK_STATUS_RANK.get(left.status) ?? 0) - (TASK_STATUS_RANK.get(right.status) ?? 0);
|
||
break;
|
||
default:
|
||
compared = compareTaskIDs(left.id, right.id);
|
||
}
|
||
if (compared !== 0) return direction === "asc" ? compared : -compared;
|
||
return -compareTaskIDs(left.id, right.id);
|
||
}
|
||
|
||
export default function TasksPage() {
|
||
const [activeTab, setActiveTab] = React.useState("current");
|
||
const [tasks, setTasks] = React.useState<Task[]>([]);
|
||
const [categories, setCategories] = React.useState<TaskCategory[]>([]);
|
||
const [categoriesLoaded, setCategoriesLoaded] = React.useState(false);
|
||
const [query, setQuery] = React.useState("");
|
||
const [statusFilter, setStatusFilter] = React.useState<TaskStatus | "all">("all");
|
||
const [categoryFilter, setCategoryFilter] = React.useState("all");
|
||
const [filtersHydrated, setFiltersHydrated] = React.useState(false);
|
||
const [sortPreference, setSortPreference] = useStoredSortPreference(
|
||
TASK_SORT_PREFERENCE_KEY,
|
||
TASK_SORT_FIELDS,
|
||
"id",
|
||
"desc",
|
||
);
|
||
const { field: sortField, direction: sortDirection } = sortPreference;
|
||
const [page, setPage] = React.useState(1);
|
||
const [pageSize, setPageSize] = React.useState(20);
|
||
const [nowSec, setNowSec] = React.useState(() => Math.floor(Date.now() / 1000));
|
||
const [batchControlling, setBatchControlling] = React.useState<"pause" | "resume" | null>(null);
|
||
const [movingCategory, setMovingCategory] = React.useState(false);
|
||
|
||
React.useEffect(() => {
|
||
const raw = getLocalStorageValue(TASK_FILTER_PREFERENCE_KEY);
|
||
if (raw) {
|
||
try {
|
||
const parsed = JSON.parse(raw) as { status?: unknown; category?: unknown };
|
||
if (parsed.status === "all" || STATUS_OPTIONS.some((option) => option.value === parsed.status)) {
|
||
setStatusFilter(parsed.status as TaskStatus | "all");
|
||
}
|
||
if (
|
||
typeof parsed.category === "string" &&
|
||
(parsed.category === "all" || parsed.category === UNCATEGORIZED_VALUE || /^\d+$/.test(parsed.category))
|
||
) {
|
||
setCategoryFilter(parsed.category);
|
||
}
|
||
} catch {
|
||
// Ignore malformed or legacy preferences and retain the defaults.
|
||
}
|
||
}
|
||
setFiltersHydrated(true);
|
||
}, []);
|
||
|
||
React.useEffect(() => {
|
||
if (!filtersHydrated) return;
|
||
setLocalStorageValue(
|
||
TASK_FILTER_PREFERENCE_KEY,
|
||
JSON.stringify({ status: statusFilter, category: categoryFilter }),
|
||
);
|
||
}, [categoryFilter, filtersHydrated, statusFilter]);
|
||
|
||
const filtered = React.useMemo(() => {
|
||
const q = query.trim().toLowerCase();
|
||
return tasks.filter((t) => {
|
||
if (statusFilter !== "all" && t.status !== statusFilter) return false;
|
||
if (categoryFilter === UNCATEGORIZED_VALUE && t.category_id != null) return false;
|
||
if (
|
||
categoryFilter !== "all" &&
|
||
categoryFilter !== UNCATEGORIZED_VALUE &&
|
||
String(t.category_id) !== categoryFilter
|
||
)
|
||
return false;
|
||
if (!q) return true;
|
||
return (
|
||
(t.name ?? "").toLowerCase().includes(q) ||
|
||
(t.category_name ?? "").toLowerCase().includes(q) ||
|
||
t.description.toLowerCase().includes(q) ||
|
||
t.goal.toLowerCase().includes(q) ||
|
||
t.id.toLowerCase().includes(q)
|
||
);
|
||
});
|
||
}, [tasks, query, statusFilter, categoryFilter]);
|
||
|
||
const sortNowSec = sortField === "duration" ? nowSec : 0;
|
||
const ordered = React.useMemo(() => {
|
||
return [...filtered].sort((left, right) => compareTasks(left, right, sortField, sortDirection, sortNowSec));
|
||
}, [filtered, sortDirection, sortField, sortNowSec]);
|
||
|
||
const sortTasksBy = React.useCallback(
|
||
(field: TaskSortField) => {
|
||
setSortPreference((current) => {
|
||
if (current.field !== field) return { field, direction: "desc" };
|
||
return { field, direction: current.direction === "asc" ? "desc" : "asc" };
|
||
});
|
||
},
|
||
[setSortPreference],
|
||
);
|
||
|
||
// reset to page 1 whenever filters or ordering change
|
||
// biome-ignore lint/correctness/useExhaustiveDependencies: both filters intentionally reset pagination.
|
||
React.useEffect(() => {
|
||
setPage(1);
|
||
}, [query, statusFilter, categoryFilter, sortField, sortDirection]);
|
||
|
||
const paginated = React.useMemo(
|
||
() => ordered.slice((page - 1) * pageSize, page * pageSize),
|
||
[ordered, page, pageSize],
|
||
);
|
||
|
||
// Multi-select delete: the selection survives paging/filter changes and only shrinks when a task truly disappears (deleted or no longer returned by the backend).
|
||
const [selectedIds, setSelectedIds] = React.useState<Set<string>>(() => new Set());
|
||
|
||
React.useEffect(() => {
|
||
setSelectedIds((prev) => {
|
||
if (prev.size === 0) return prev;
|
||
const live = new Set(tasks.map((t) => t.id));
|
||
const next = new Set([...prev].filter((id) => live.has(id)));
|
||
return next.size === prev.size ? prev : next;
|
||
});
|
||
}, [tasks]);
|
||
|
||
const toggleSelected = React.useCallback((id: string, checked: boolean) => {
|
||
setSelectedIds((prev) => {
|
||
const next = new Set(prev);
|
||
if (checked) next.add(id);
|
||
else next.delete(id);
|
||
return next;
|
||
});
|
||
}, []);
|
||
|
||
const pageIds = React.useMemo(() => paginated.map((t) => t.id), [paginated]);
|
||
const pageSelectedCount = React.useMemo(
|
||
() => pageIds.filter((id) => selectedIds.has(id)).length,
|
||
[pageIds, selectedIds],
|
||
);
|
||
let headerChecked: boolean | "indeterminate" = false;
|
||
if (pageIds.length > 0 && pageSelectedCount === pageIds.length) {
|
||
headerChecked = true;
|
||
} else if (pageSelectedCount > 0) {
|
||
headerChecked = "indeterminate";
|
||
}
|
||
|
||
const toggleSelectedPage = React.useCallback(
|
||
(checked: boolean) => {
|
||
setSelectedIds((prev) => {
|
||
const next = new Set(prev);
|
||
for (const id of pageIds) {
|
||
if (checked) next.add(id);
|
||
else next.delete(id);
|
||
}
|
||
return next;
|
||
});
|
||
},
|
||
[pageIds],
|
||
);
|
||
|
||
// lastRef holds the previous poll's serialized payload: the list is re-fetched every
|
||
// POLL_MS but usually comes back unchanged, and setTasks on an identical payload would
|
||
// re-render the whole page for nothing. Bail out when it matches.
|
||
const lastRef = React.useRef<string>("");
|
||
|
||
const load = React.useCallback(() => {
|
||
api
|
||
.tasks()
|
||
.then((r) => {
|
||
const next = r.tasks.map((t) => (t.id === r.active ? { ...t, active: true } : t));
|
||
const sig = JSON.stringify(next);
|
||
if (sig === lastRef.current) return;
|
||
lastRef.current = sig;
|
||
setTasks(next);
|
||
})
|
||
.catch(() => {
|
||
// Polling is best-effort; the next interval retries automatically.
|
||
});
|
||
}, []);
|
||
|
||
const loadCategories = React.useCallback(() => {
|
||
api
|
||
.taskCategories()
|
||
.then((next) => {
|
||
setCategories(next);
|
||
setCategoriesLoaded(true);
|
||
})
|
||
.catch(() => {
|
||
// Category management remains retryable without blocking the task list.
|
||
});
|
||
}, []);
|
||
|
||
React.useEffect(() => {
|
||
load();
|
||
loadCategories();
|
||
const stopPolling = setVisibleInterval(load, POLL_MS);
|
||
return stopPolling;
|
||
}, [load, loadCategories]);
|
||
|
||
const refreshCategoriesAndTasks = React.useCallback(() => {
|
||
lastRef.current = "";
|
||
loadCategories();
|
||
load();
|
||
}, [load, loadCategories]);
|
||
|
||
const applyTaskCategoryMove = React.useCallback(
|
||
(taskID: string, category: TaskCategory | null) => {
|
||
setTasks((current) => {
|
||
const next = current.map((task) =>
|
||
task.id === taskID ? { ...task, category_id: category?.id, category_name: category?.name } : task,
|
||
);
|
||
lastRef.current = JSON.stringify(next);
|
||
return next;
|
||
});
|
||
loadCategories();
|
||
},
|
||
[loadCategories],
|
||
);
|
||
|
||
React.useEffect(() => {
|
||
if (!categoriesLoaded) return;
|
||
if (categoryFilter === "all" || categoryFilter === UNCATEGORIZED_VALUE) return;
|
||
if (!categories.some((category) => String(category.id) === categoryFilter)) setCategoryFilter("all");
|
||
}, [categories, categoriesLoaded, categoryFilter]);
|
||
|
||
// Only tick every second when there really is a running task — otherwise "duration" is static, and an idle tick would
|
||
// re-render the whole table for nothing.
|
||
const hasRunning = React.useMemo(() => tasks.some((t) => t.status === "running"), [tasks]);
|
||
|
||
// tick every second so running tasks' duration counts up live.
|
||
React.useEffect(() => {
|
||
if (!hasRunning) return;
|
||
setNowSec(Math.floor(Date.now() / 1000));
|
||
const i = setInterval(() => setNowSec(Math.floor(Date.now() / 1000)), 1000);
|
||
return () => clearInterval(i);
|
||
}, [hasRunning]);
|
||
|
||
const deleteTask = React.useCallback(
|
||
async (id: string, options: DeleteTaskOptions) => {
|
||
try {
|
||
const result = await api.deleteTask(id, options);
|
||
if (result.cleanup_warning) {
|
||
toast.warning(
|
||
t("{summary}; some external data cleanup did not finish: {warning}", {
|
||
summary: deleteSummary(result),
|
||
warning: result.cleanup_warning,
|
||
}),
|
||
);
|
||
} else {
|
||
toast.success(deleteSummary(result));
|
||
}
|
||
load();
|
||
} catch (e) {
|
||
toast.error(t("Delete failed: {error}", { error: (e as Error).message }));
|
||
throw e;
|
||
}
|
||
},
|
||
[load],
|
||
);
|
||
|
||
// controlTask is the inline pause/resume: bulk goes through controlTasksBatch, a single row uses the single-task endpoint, saving the
|
||
// "check first, then click bulk" detour. Clearing lastRef lets the next poll be accepted even with an identical payload; otherwise the state
|
||
// write-back would be swallowed by dedup and the button would look unresponsive.
|
||
const controlTask = React.useCallback(
|
||
async (id: string, action: "pause" | "resume") => {
|
||
try {
|
||
const result = await api.controlTask(id, action);
|
||
toast.success(
|
||
action === "pause"
|
||
? t("Task #{id} paused", { id })
|
||
: result.queued
|
||
? t("Task #{id} resumed, queued", { id })
|
||
: t("Task #{id} resumed", { id }),
|
||
);
|
||
} catch (e) {
|
||
toast.error(
|
||
action === "pause"
|
||
? t("Pause failed: {error}", { error: (e as Error).message })
|
||
: t("Resume failed: {error}", { error: (e as Error).message }),
|
||
);
|
||
} finally {
|
||
// Refresh regardless of outcome: failures usually mean the state changed, and re-fetching restores the right button shape.
|
||
lastRef.current = "";
|
||
load();
|
||
}
|
||
},
|
||
[load],
|
||
);
|
||
|
||
const renameTask = React.useCallback(
|
||
async (task: Task, name: string) => {
|
||
try {
|
||
await api.renameTask(task.id, name);
|
||
toast.success(t("Task #{id} renamed", { id: task.id }));
|
||
lastRef.current = "";
|
||
load();
|
||
} catch (error) {
|
||
toast.error(t("Rename failed: {error}", { error: (error as Error).message }));
|
||
throw error;
|
||
}
|
||
},
|
||
[load],
|
||
);
|
||
|
||
const toggleTaskPinned = React.useCallback(
|
||
async (task: Task) => {
|
||
const pinned = taskIsPinned(task);
|
||
try {
|
||
await api.pinTask(task.id, !pinned);
|
||
toast.success(pinned ? t("Task #{id} unpinned", { id: task.id }) : t("Task #{id} pinned", { id: task.id }));
|
||
lastRef.current = "";
|
||
load();
|
||
} catch (error) {
|
||
toast.error(
|
||
pinned
|
||
? t("Unpin failed: {error}", { error: (error as Error).message })
|
||
: t("Pin failed: {error}", { error: (error as Error).message }),
|
||
);
|
||
throw error;
|
||
}
|
||
},
|
||
[load],
|
||
);
|
||
|
||
const queueTaskArchive = React.useCallback(
|
||
async (task: Task) => {
|
||
try {
|
||
await api.archiveTask(task.id);
|
||
toast.success(t("Task #{id} queued for archiving", { id: task.id }));
|
||
setActiveTab("archived");
|
||
lastRef.current = "";
|
||
load();
|
||
} catch (error) {
|
||
toast.error(t("Archive failed: {error}", { error: (error as Error).message }));
|
||
throw error;
|
||
}
|
||
},
|
||
[load],
|
||
);
|
||
|
||
// deleteTasks deletes the selected tasks one by one: the backend has no batch endpoint, and each delete cascades into cleaning assets/traffic/files,
|
||
// so they run serially to avoid overwhelming the backend at once; successes leave the selection, failures stay for retry.
|
||
const deleteTasks = React.useCallback(
|
||
async (ids: string[], options: DeleteTaskOptions, onProgress: (done: number) => void) => {
|
||
const total: DeleteCounts = {
|
||
assets_deleted: 0,
|
||
assets_detached: 0,
|
||
traffic_deleted: 0,
|
||
files_deleted: false,
|
||
findings_deleted: 0,
|
||
llm_records_deleted: 0,
|
||
};
|
||
const deleted: string[] = [];
|
||
const failed: { id: string; message: string }[] = [];
|
||
const warnings: string[] = [];
|
||
|
||
for (const id of ids) {
|
||
try {
|
||
const r = await api.deleteTask(id, options);
|
||
total.assets_deleted += r.assets_deleted;
|
||
total.assets_detached += r.assets_detached;
|
||
total.traffic_deleted += r.traffic_deleted;
|
||
total.files_deleted = total.files_deleted || r.files_deleted;
|
||
total.findings_deleted += r.findings_deleted;
|
||
total.llm_records_deleted += r.llm_records_deleted;
|
||
if (r.cleanup_warning) warnings.push(`#${id}: ${r.cleanup_warning}`);
|
||
deleted.push(id);
|
||
} catch (e) {
|
||
failed.push({ id, message: (e as Error).message });
|
||
}
|
||
onProgress(deleted.length + failed.length);
|
||
}
|
||
|
||
if (deleted.length > 0) {
|
||
setSelectedIds((prev) => {
|
||
const next = new Set(prev);
|
||
for (const id of deleted) next.delete(id);
|
||
return next;
|
||
});
|
||
const details = deleteDetails(total);
|
||
const summary =
|
||
details.length > 0
|
||
? t("Deleted {count} tasks ({details})", { count: deleted.length, details: details.join(", ") })
|
||
: t("Deleted {count} tasks", { count: deleted.length });
|
||
if (warnings.length > 0) {
|
||
toast.warning(t("{summary}; some external data cleanup did not finish: {warning}", { summary, warning: warnings.join("; ") }));
|
||
} else {
|
||
toast.success(summary);
|
||
}
|
||
}
|
||
if (failed.length > 0) {
|
||
const head = failed
|
||
.slice(0, 3)
|
||
.map((f) => `#${f.id} (${f.message})`)
|
||
.join("; ");
|
||
toast.error(
|
||
failed.length > 3
|
||
? t("{count} tasks failed to delete: {details} and more", { count: failed.length, details: head })
|
||
: t("{count} tasks failed to delete: {details}", { count: failed.length, details: head }),
|
||
);
|
||
}
|
||
load();
|
||
},
|
||
[load],
|
||
);
|
||
|
||
const selectedTasks = React.useMemo(() => tasks.filter((task) => selectedIds.has(task.id)), [tasks, selectedIds]);
|
||
const pausableTaskIDs = React.useMemo(
|
||
() => selectedTasks.filter((task) => taskControlAction(task.status) === "pause").map((task) => task.id),
|
||
[selectedTasks],
|
||
);
|
||
const resumableTaskIDs = React.useMemo(
|
||
() => selectedTasks.filter((task) => taskControlAction(task.status) === "resume").map((task) => task.id),
|
||
[selectedTasks],
|
||
);
|
||
const archivableTaskIDs = React.useMemo(
|
||
() => selectedTasks.filter((task) => ARCHIVABLE_STATUSES.has(task.status) && !task.queued).map((task) => task.id),
|
||
[selectedTasks],
|
||
);
|
||
|
||
const archiveSelectedTasks = React.useCallback(async () => {
|
||
if (archivableTaskIDs.length === 0) return;
|
||
const result = await api.archiveTasks(archivableTaskIDs);
|
||
const succeeded = result.items.filter((item) => item.ok);
|
||
const failed = result.items.filter((item) => !item.ok);
|
||
if (succeeded.length > 0) toast.success(t("Queued {count} tasks for archiving", { count: succeeded.length }));
|
||
if (failed.length > 0) {
|
||
toast.error(
|
||
t("{count} tasks could not be archived: {details}", {
|
||
count: failed.length,
|
||
details: failed
|
||
.slice(0, 3)
|
||
.map((item) => `#${item.id} (${item.error || t("state changed")})`)
|
||
.join("; "),
|
||
}),
|
||
);
|
||
}
|
||
setSelectedIds(new Set());
|
||
setActiveTab("archived");
|
||
lastRef.current = "";
|
||
load();
|
||
}, [archivableTaskIDs, load]);
|
||
|
||
const controlSelectedTasks = React.useCallback(
|
||
async (action: "pause" | "resume", ids: string[]) => {
|
||
if (ids.length === 0 || batchControlling) return;
|
||
if (ids.length > 100) {
|
||
toast.error(t("You can control at most 100 tasks at once"));
|
||
return;
|
||
}
|
||
setBatchControlling(action);
|
||
try {
|
||
const result = await api.controlTasksBatch(ids, action);
|
||
const succeeded = result.items.filter((item) => item.ok);
|
||
const failed = result.items.filter((item) => !item.ok);
|
||
if (succeeded.length > 0) {
|
||
toast.success(
|
||
action === "pause"
|
||
? t("Paused {count} tasks", { count: succeeded.length })
|
||
: succeeded.some((item) => item.queued)
|
||
? t("Resumed {count} tasks, some tasks were queued", { count: succeeded.length })
|
||
: t("Resumed {count} tasks", { count: succeeded.length }),
|
||
);
|
||
}
|
||
if (failed.length > 0) {
|
||
const details = failed
|
||
.slice(0, 3)
|
||
.map((item) => `#${item.id} (${item.error || t("state changed")})`)
|
||
.join("; ");
|
||
toast.error(
|
||
failed.length > 3
|
||
? t("{count} tasks failed: {details} and more", { count: failed.length, details })
|
||
: t("{count} tasks failed: {details}", { count: failed.length, details }),
|
||
);
|
||
}
|
||
lastRef.current = "";
|
||
load();
|
||
} catch (error) {
|
||
toast.error(
|
||
action === "pause"
|
||
? t("Bulk pause failed: {error}", { error: (error as Error).message })
|
||
: t("Bulk resume failed: {error}", { error: (error as Error).message }),
|
||
);
|
||
} finally {
|
||
setBatchControlling(null);
|
||
}
|
||
},
|
||
[batchControlling, load],
|
||
);
|
||
|
||
// The backend writes the whole batch's category changes in one transaction, so the only failures can be tasks deleted after being checked.
|
||
const moveSelectedTasksCategory = React.useCallback(
|
||
async (categoryID?: number) => {
|
||
const ids = [...selectedIds];
|
||
if (ids.length === 0 || movingCategory) return;
|
||
if (ids.length > 100) {
|
||
toast.error(t("You can change the category of at most 100 tasks at once"));
|
||
return;
|
||
}
|
||
setMovingCategory(true);
|
||
try {
|
||
const result = await api.updateTasksCategory(ids, categoryID);
|
||
const succeeded = result.items.filter((item) => item.ok);
|
||
const failed = result.items.filter((item) => !item.ok);
|
||
const target = result.category?.name ?? t("Uncategorized");
|
||
if (succeeded.length > 0) {
|
||
toast.success(t("Moved {count} tasks to \"{target}\"", { count: succeeded.length, target }));
|
||
setSelectedIds(new Set());
|
||
}
|
||
if (failed.length > 0) {
|
||
const details = failed
|
||
.slice(0, 3)
|
||
.map((item) => `#${item.id} (${item.error || t("task no longer exists")})`)
|
||
.join("; ");
|
||
toast.error(
|
||
failed.length > 3
|
||
? t("{count} tasks could not be moved: {details} and more", { count: failed.length, details })
|
||
: t("{count} tasks could not be moved: {details}", { count: failed.length, details }),
|
||
);
|
||
}
|
||
refreshCategoriesAndTasks();
|
||
} catch (error) {
|
||
toast.error(t("Failed to change category: {error}", { error: (error as Error).message }));
|
||
} finally {
|
||
setMovingCategory(false);
|
||
}
|
||
},
|
||
[movingCategory, refreshCategoriesAndTasks, selectedIds],
|
||
);
|
||
|
||
return (
|
||
<Tabs value={activeTab} onValueChange={setActiveTab} className="gap-4">
|
||
<TabsList className="mx-4 lg:mx-6">
|
||
<TabsTrigger value="current">{t("Current tasks")}</TabsTrigger>
|
||
<TabsTrigger value="archived">{t("Archived")}</TabsTrigger>
|
||
</TabsList>
|
||
<TabsContent value="current">
|
||
<Card>
|
||
<CardContent className="flex flex-col gap-4 px-0 pt-6">
|
||
<div className="flex flex-wrap items-center gap-2 px-4 lg:px-6">
|
||
<div className="relative w-full sm:max-w-xs">
|
||
<SearchIcon className="text-muted-foreground pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2" />
|
||
<Input
|
||
placeholder={t("Search description / goal / ID")}
|
||
value={query}
|
||
onChange={(e) => setQuery(e.target.value)}
|
||
className="pl-8"
|
||
/>
|
||
{query && (
|
||
<button
|
||
type="button"
|
||
onClick={() => setQuery("")}
|
||
aria-label={t("Clear search")}
|
||
className="text-muted-foreground hover:text-foreground absolute top-1/2 right-2 -translate-y-1/2"
|
||
>
|
||
<XIcon className="size-4" />
|
||
</button>
|
||
)}
|
||
</div>
|
||
<Select value={statusFilter} onValueChange={(v) => setStatusFilter(v as TaskStatus | "all")}>
|
||
<SelectTrigger className="w-36">
|
||
<SelectValue placeholder={t("Status")} />
|
||
</SelectTrigger>
|
||
<SelectContent>
|
||
<SelectGroup>
|
||
<SelectItem value="all">{t("All statuses")}</SelectItem>
|
||
{STATUS_OPTIONS.map((s) => (
|
||
<SelectItem key={s.value} value={s.value}>
|
||
{s.label}
|
||
</SelectItem>
|
||
))}
|
||
</SelectGroup>
|
||
</SelectContent>
|
||
</Select>
|
||
<Select value={categoryFilter} onValueChange={setCategoryFilter}>
|
||
<SelectTrigger className="w-40">
|
||
<SelectValue placeholder={t("Task category")} />
|
||
</SelectTrigger>
|
||
<SelectContent>
|
||
<SelectGroup>
|
||
<SelectItem value="all">{t("All categories")}</SelectItem>
|
||
<SelectItem value={UNCATEGORIZED_VALUE}>{t("Uncategorized")}</SelectItem>
|
||
{categories.map((category) => (
|
||
<SelectItem key={category.id} value={String(category.id)}>
|
||
{category.name}
|
||
</SelectItem>
|
||
))}
|
||
</SelectGroup>
|
||
</SelectContent>
|
||
</Select>
|
||
<span className="text-muted-foreground text-xs tabular-nums">
|
||
{t("{shown}/{total} tasks", { shown: filtered.length, total: tasks.length })}
|
||
</span>
|
||
{selectedIds.size > 0 && (
|
||
<>
|
||
<span className="text-xs tabular-nums">{t("{count} selected", { count: selectedIds.size })}</span>
|
||
<Button size="sm" variant="ghost" onClick={() => setSelectedIds(new Set())}>
|
||
{t("Clear selection")}
|
||
</Button>
|
||
{pausableTaskIDs.length > 0 && (
|
||
<Button
|
||
size="sm"
|
||
variant="outline"
|
||
disabled={batchControlling !== null}
|
||
onClick={() => void controlSelectedTasks("pause", pausableTaskIDs)}
|
||
>
|
||
{batchControlling === "pause" ? (
|
||
<Spinner data-icon="inline-start" />
|
||
) : (
|
||
<PauseIcon data-icon="inline-start" />
|
||
)}
|
||
{t("Pause {count}", { count: pausableTaskIDs.length })}
|
||
</Button>
|
||
)}
|
||
{resumableTaskIDs.length > 0 && (
|
||
<Button
|
||
size="sm"
|
||
variant="outline"
|
||
disabled={batchControlling !== null}
|
||
onClick={() => void controlSelectedTasks("resume", resumableTaskIDs)}
|
||
>
|
||
{batchControlling === "resume" ? (
|
||
<Spinner data-icon="inline-start" />
|
||
) : (
|
||
<PlayIcon data-icon="inline-start" />
|
||
)}
|
||
{t("Resume {count}", { count: resumableTaskIDs.length })}
|
||
</Button>
|
||
)}
|
||
{archivableTaskIDs.length > 0 && (
|
||
<ArchiveConfirmDialog
|
||
count={archivableTaskIDs.length}
|
||
onConfirm={archiveSelectedTasks}
|
||
trigger={
|
||
<Button size="sm" variant="outline">
|
||
<ArchiveIcon data-icon="inline-start" />
|
||
{t("Archive {count}", { count: archivableTaskIDs.length })}
|
||
</Button>
|
||
}
|
||
/>
|
||
)}
|
||
<MoveTasksCategoryDialog
|
||
categories={categories}
|
||
count={selectedIds.size}
|
||
moving={movingCategory}
|
||
onMove={moveSelectedTasksCategory}
|
||
/>
|
||
<BulkDeleteTasksDialog ids={[...selectedIds]} onDelete={deleteTasks} />
|
||
</>
|
||
)}
|
||
<ConcurrencySettingsDialog />
|
||
<CategoryManagementSheet
|
||
categories={categories}
|
||
tasks={tasks}
|
||
onChanged={refreshCategoriesAndTasks}
|
||
onTaskMoved={applyTaskCategoryMove}
|
||
/>
|
||
<CreateTaskSheet
|
||
tasks={tasks}
|
||
categories={categories}
|
||
onCreated={refreshCategoriesAndTasks}
|
||
onCategoriesChanged={refreshCategoriesAndTasks}
|
||
/>
|
||
</div>
|
||
|
||
{tasks.length === 0 ? (
|
||
<div className="text-muted-foreground mx-4 flex items-center justify-center rounded-lg border border-dashed py-20 text-sm lg:mx-6">
|
||
{t("No tasks yet. Click \"New task\" at the top right to start.")}
|
||
</div>
|
||
) : filtered.length === 0 ? (
|
||
<div className="text-muted-foreground mx-4 flex items-center justify-center rounded-lg border border-dashed py-20 text-sm lg:mx-6">
|
||
{t("No matching tasks.")}
|
||
</div>
|
||
) : (
|
||
<Table className="**:data-[slot='table-cell']:px-4 **:data-[slot='table-head']:px-4">
|
||
<TableHeader className="[&_tr]:border-t">
|
||
<TableRow>
|
||
<TableHead className="w-10">
|
||
<Checkbox
|
||
checked={headerChecked}
|
||
onCheckedChange={(checked) => toggleSelectedPage(checked === true)}
|
||
aria-label={t("Select all tasks on this page")}
|
||
/>
|
||
</TableHead>
|
||
<SortableTaskHead
|
||
field="id"
|
||
label="ID"
|
||
activeField={sortField}
|
||
direction={sortDirection}
|
||
className="font-mono"
|
||
onSort={sortTasksBy}
|
||
/>
|
||
<TableHead>{t("Name")}</TableHead>
|
||
<TableHead>{t("Description")}</TableHead>
|
||
<TableHead>{t("Goal")}</TableHead>
|
||
<SortableTaskHead
|
||
field="status"
|
||
label={t("Status")}
|
||
activeField={sortField}
|
||
direction={sortDirection}
|
||
onSort={sortTasksBy}
|
||
/>
|
||
<TableHead className="text-center">{t("Goal progress")}</TableHead>
|
||
<TableHead className="text-center" title={t("Critical / High / Medium / Low")}>
|
||
{t("Findings")} <span className="text-muted-foreground font-normal">{t("C/H/M/L")}</span>
|
||
</TableHead>
|
||
<TableHead className="text-center">{t("Running workers")}</TableHead>
|
||
<SortableTaskHead
|
||
field="created"
|
||
label={t("Created at")}
|
||
activeField={sortField}
|
||
direction={sortDirection}
|
||
align="right"
|
||
onSort={sortTasksBy}
|
||
/>
|
||
<SortableTaskHead
|
||
field="duration"
|
||
label={t("Duration")}
|
||
activeField={sortField}
|
||
direction={sortDirection}
|
||
align="right"
|
||
onSort={sortTasksBy}
|
||
/>
|
||
<TableHead className="text-right">{t("Token")}</TableHead>
|
||
<TableHead className="sticky right-0 z-10 bg-card text-right shadow-[-1px_0_0_0_hsl(var(--border))]">
|
||
{t("Actions")}
|
||
</TableHead>
|
||
</TableRow>
|
||
</TableHeader>
|
||
<TableBody>
|
||
{paginated.map((task) => (
|
||
<TaskRow
|
||
key={task.id}
|
||
task={task}
|
||
// only running tasks consume nowSec; other rows get 0 — with unchanged props, memo blocks the per-second tick's
|
||
// whole-table re-render and only the running rows advance their duration.
|
||
nowSec={task.status === "running" ? nowSec : 0}
|
||
onDelete={deleteTask}
|
||
onControl={controlTask}
|
||
onRename={renameTask}
|
||
onTogglePinned={toggleTaskPinned}
|
||
onArchive={queueTaskArchive}
|
||
selected={selectedIds.has(task.id)}
|
||
onSelectedChange={toggleSelected}
|
||
/>
|
||
))}
|
||
</TableBody>
|
||
</Table>
|
||
)}
|
||
<TablePagination
|
||
page={page}
|
||
pageSize={pageSize}
|
||
total={filtered.length}
|
||
onPageChange={setPage}
|
||
onPageSizeChange={(nextPageSize) => {
|
||
setPageSize(nextPageSize);
|
||
setPage(1);
|
||
}}
|
||
/>
|
||
</CardContent>
|
||
</Card>
|
||
</TabsContent>
|
||
<TabsContent value="archived">
|
||
<TaskArchivesPanel onChanged={load} />
|
||
</TabsContent>
|
||
</Tabs>
|
||
);
|
||
}
|
||
|
||
function taskSortIcon(active: boolean, direction: SortDirection) {
|
||
if (!active) {
|
||
return <ArrowUpDownIcon className="size-3.5 opacity-40 transition-opacity group-hover/sort:opacity-100" />;
|
||
}
|
||
if (direction === "asc") return <ArrowUpIcon className="size-3.5" />;
|
||
return <ArrowDownIcon className="size-3.5" />;
|
||
}
|
||
|
||
function SortableTaskHead({
|
||
field,
|
||
label,
|
||
activeField,
|
||
direction,
|
||
align = "left",
|
||
className,
|
||
onSort,
|
||
}: {
|
||
field: TaskSortField;
|
||
label: string;
|
||
activeField: TaskSortField;
|
||
direction: SortDirection;
|
||
align?: "left" | "right";
|
||
className?: string;
|
||
onSort: (field: TaskSortField) => void;
|
||
}) {
|
||
const active = activeField === field;
|
||
let ariaSort: React.AriaAttributes["aria-sort"] = "none";
|
||
if (active) ariaSort = direction === "asc" ? "ascending" : "descending";
|
||
|
||
let actionLabel = t("Sort by {label} descending", { label });
|
||
if (active) {
|
||
actionLabel =
|
||
direction === "asc"
|
||
? t("{label} is currently ascending; click to toggle sort direction", { label })
|
||
: t("{label} is currently descending; click to toggle sort direction", { label });
|
||
}
|
||
|
||
return (
|
||
<TableHead className={className} aria-sort={ariaSort}>
|
||
<button
|
||
type="button"
|
||
className={cn(
|
||
"group/sort inline-flex h-full w-full items-center gap-1 outline-none focus-visible:underline",
|
||
align === "right" && "justify-end",
|
||
)}
|
||
aria-label={actionLabel}
|
||
onClick={() => onSort(field)}
|
||
>
|
||
<span>{label}</span>
|
||
{taskSortIcon(active, direction)}
|
||
</button>
|
||
</TableHead>
|
||
);
|
||
}
|
||
|
||
function ConcurrencySettingsDialog() {
|
||
const [open, setOpen] = React.useState(false);
|
||
const [enabled, setEnabled] = React.useState(false);
|
||
const [limit, setLimit] = React.useState("5");
|
||
const [loading, setLoading] = React.useState(false);
|
||
const [saving, setSaving] = React.useState(false);
|
||
|
||
React.useEffect(() => {
|
||
if (!open) return;
|
||
setLoading(true);
|
||
api
|
||
.settings()
|
||
.then((settings) => {
|
||
setEnabled(!!settings.task_concurrency_enabled);
|
||
setLimit(String(settings.task_concurrency_limit ?? 5));
|
||
})
|
||
.catch(() => {
|
||
// Keep the dialog usable with defaults; reopening retries the request.
|
||
})
|
||
.finally(() => setLoading(false));
|
||
}, [open]);
|
||
|
||
async function save() {
|
||
const nextLimit = Math.max(1, Math.floor(Number(limit) || 5));
|
||
setSaving(true);
|
||
try {
|
||
await api.setSettings({ task_concurrency_enabled: enabled, task_concurrency_limit: nextLimit });
|
||
toast.success(
|
||
enabled
|
||
? t("Concurrency limit enabled: at most {count} tasks can run simultaneously", { count: nextLimit })
|
||
: t("Task concurrency limit disabled"),
|
||
);
|
||
setOpen(false);
|
||
} catch (error) {
|
||
toast.error(t("Save failed: {error}", { error: (error as Error).message }));
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
}
|
||
|
||
return (
|
||
<Dialog open={open} onOpenChange={setOpen}>
|
||
<DialogTrigger asChild>
|
||
<Button size="sm" variant="outline" className="ml-auto" aria-label={t("Task concurrency settings")}>
|
||
<SlidersHorizontalIcon /> {t("Concurrency")}
|
||
</Button>
|
||
</DialogTrigger>
|
||
<DialogContent className="sm:max-w-md">
|
||
<DialogHeader>
|
||
<DialogTitle>{t("Task concurrency limit")}</DialogTitle>
|
||
<DialogDescription>
|
||
{t(
|
||
"Limit how many tasks can run simultaneously. Once the limit is reached, new tasks queue in creation order and start automatically as slots free up.",
|
||
)}
|
||
</DialogDescription>
|
||
</DialogHeader>
|
||
<div className="grid gap-5 py-2">
|
||
<div className="flex items-center justify-between gap-4">
|
||
<div className="grid gap-1">
|
||
<Label htmlFor="task-concurrency-enabled">{t("Enable task concurrency limit")}</Label>
|
||
<span className="text-muted-foreground text-xs">{t("Off by default")}</span>
|
||
</div>
|
||
<Switch id="task-concurrency-enabled" checked={enabled} onCheckedChange={setEnabled} disabled={loading} />
|
||
</div>
|
||
{enabled && (
|
||
<div className="grid gap-2">
|
||
<Label htmlFor="task-concurrency-limit">{t("Max concurrent tasks")}</Label>
|
||
<Input
|
||
id="task-concurrency-limit"
|
||
type="number"
|
||
min={1}
|
||
className="w-32"
|
||
value={limit}
|
||
onChange={(event) => setLimit(event.target.value)}
|
||
disabled={loading}
|
||
/>
|
||
</div>
|
||
)}
|
||
</div>
|
||
<DialogFooter>
|
||
<DialogClose asChild>
|
||
<Button variant="outline">{t("Cancel")}</Button>
|
||
</DialogClose>
|
||
<Button onClick={save} disabled={loading || saving}>
|
||
{saving && <Loader2Icon className="animate-spin" />} {t("Save")}
|
||
</Button>
|
||
</DialogFooter>
|
||
</DialogContent>
|
||
</Dialog>
|
||
);
|
||
}
|
||
|
||
// TaskRow renders one row of the task table. Memoized so the per-second duration tick and
|
||
// the POLL_MS list refresh only re-render the rows whose data actually moved — a table page
|
||
// is 20 rows × (StatusBadge + Link + a Radix AlertDialog tree), far too heavy to rebuild
|
||
// wholesale on every parent render.
|
||
const TaskRow = React.memo(function TaskRow({
|
||
task,
|
||
nowSec,
|
||
onDelete,
|
||
onControl,
|
||
onRename,
|
||
onTogglePinned,
|
||
onArchive,
|
||
selected,
|
||
onSelectedChange,
|
||
}: {
|
||
task: Task;
|
||
nowSec: number;
|
||
onDelete: (id: string, options: DeleteTaskOptions) => Promise<void>;
|
||
onControl: (id: string, action: "pause" | "resume") => Promise<void>;
|
||
onRename: (task: Task, name: string) => Promise<void>;
|
||
onTogglePinned: (task: Task) => Promise<void>;
|
||
onArchive: (task: Task) => Promise<void>;
|
||
selected: boolean;
|
||
onSelectedChange: (id: string, checked: boolean) => void;
|
||
}) {
|
||
return (
|
||
<TableRow className="group border-border/60" data-state={selected ? "selected" : undefined}>
|
||
<TableCell>
|
||
<Checkbox
|
||
checked={selected}
|
||
onCheckedChange={(checked) => onSelectedChange(task.id, checked === true)}
|
||
aria-label={t("Select task {id}", { id: task.id })}
|
||
/>
|
||
</TableCell>
|
||
<TableCell>
|
||
<code className="bg-muted rounded px-1.5 py-0.5 font-mono text-xs">{task.id}</code>
|
||
</TableCell>
|
||
<TableCell className="font-medium">
|
||
<div className="flex max-w-xs items-center gap-2">
|
||
<TaskNameEditor task={task} onRename={onRename} />
|
||
{task.active && <StarIcon className="size-4 shrink-0 fill-amber-400 text-amber-400" />}
|
||
{taskIsPinned(task) && <PinIcon className="text-primary size-4 shrink-0" aria-label={t("Pinned")} />}
|
||
</div>
|
||
</TableCell>
|
||
<TableCell className="text-muted-foreground max-w-40">
|
||
<Link
|
||
href={`/function/tasks/detail?id=${encodeURIComponent(task.id)}`}
|
||
className="block truncate rounded-sm hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||
title={task.description}
|
||
>
|
||
{task.description}
|
||
</Link>
|
||
</TableCell>
|
||
<TableCell className="text-muted-foreground max-w-40 truncate" title={task.goal}>
|
||
{task.goal}
|
||
</TableCell>
|
||
<TableCell>
|
||
<StatusBadge domain="task" value={task.status} dot />
|
||
</TableCell>
|
||
<TableCell className="text-muted-foreground text-center text-xs tabular-nums">
|
||
{typeof task.goals_total === "number" && task.goals_total > 0 ? (
|
||
`${task.goals_met}/${task.goals_total}`
|
||
) : (
|
||
<span className="text-muted-foreground">—</span>
|
||
)}
|
||
</TableCell>
|
||
<TableCell className="text-center text-xs tabular-nums">
|
||
{(() => {
|
||
const f = task.findings;
|
||
const total = f ? f.critical + f.high + f.medium + f.low : 0;
|
||
if (!f || total === 0) return <span className="text-muted-foreground">0</span>;
|
||
const seg = (n: number, cls: string) => (
|
||
<span className={n > 0 ? cls : "text-muted-foreground"}>{n}</span>
|
||
);
|
||
return (
|
||
<span className="font-medium whitespace-nowrap" title={t("Critical / High / Medium / Low")}>
|
||
{seg(f.critical, "text-rose-600 dark:text-rose-400")}
|
||
<span className="text-muted-foreground">/</span>
|
||
{seg(f.high, "text-red-600 dark:text-red-400")}
|
||
<span className="text-muted-foreground">/</span>
|
||
{seg(f.medium, "text-amber-600 dark:text-amber-400")}
|
||
<span className="text-muted-foreground">/</span>
|
||
{seg(f.low, "text-slate-600 dark:text-slate-400")}
|
||
</span>
|
||
);
|
||
})()}
|
||
</TableCell>
|
||
<TableCell className="text-center text-xs tabular-nums">
|
||
{task.in_flight && task.in_flight > 0 ? (
|
||
<span className="text-foreground font-medium">{task.in_flight}</span>
|
||
) : (
|
||
<span className="text-muted-foreground">0</span>
|
||
)}
|
||
</TableCell>
|
||
<TableCell className="text-muted-foreground text-right text-xs whitespace-nowrap tabular-nums">
|
||
{fmtDateTime(task.created_unix)}
|
||
</TableCell>
|
||
<TableCell className="text-right text-xs whitespace-nowrap tabular-nums">
|
||
{(() => {
|
||
const secs = taskDuration(task, nowSec);
|
||
if (secs <= 0) return <span className="text-muted-foreground">—</span>;
|
||
return (
|
||
<span className={task.status === "running" ? "text-foreground" : "text-muted-foreground"}>
|
||
{fmtDuration(secs)}
|
||
</span>
|
||
);
|
||
})()}
|
||
</TableCell>
|
||
<TableCell
|
||
className="text-right text-xs whitespace-nowrap tabular-nums"
|
||
title={
|
||
task.tokens
|
||
? t("Input {input} · Cache {cache} · Output {output}", {
|
||
input: task.tokens.input_tokens,
|
||
cache: task.tokens.cache_read_tokens,
|
||
output: task.tokens.output_tokens,
|
||
})
|
||
: undefined
|
||
}
|
||
>
|
||
{task.tokens ? (
|
||
<span className="text-muted-foreground">
|
||
{t("In")} <span className="text-foreground">{fmtTokens(task.tokens.input_tokens)}</span>
|
||
{" · "}
|
||
{t("Cache")} <span className="text-foreground">{fmtTokens(task.tokens.cache_read_tokens)}</span>
|
||
{" · "}
|
||
{t("Out")}{" "}
|
||
<span className="text-foreground">{fmtTokens(task.tokens.output_tokens)}</span>
|
||
</span>
|
||
) : (
|
||
"—"
|
||
)}
|
||
</TableCell>
|
||
<TableCell className="sticky right-0 z-10 bg-card text-right shadow-[-1px_0_0_0_hsl(var(--border))] group-hover:bg-muted/50">
|
||
<div className="flex items-center justify-end gap-0.5">
|
||
<Button size="icon" variant="ghost" asChild aria-label={t("View task details")} title={t("View task details")}>
|
||
<Link href={`/function/tasks/detail?id=${encodeURIComponent(task.id)}`}>
|
||
<EyeIcon />
|
||
</Link>
|
||
</Button>
|
||
<TaskControlButton task={task} onControl={onControl} />
|
||
<TaskPinAction task={task} onTogglePinned={onTogglePinned} />
|
||
<TaskArchiveAction task={task} onArchive={onArchive} />
|
||
<DeleteTaskDialog task={task} onDelete={onDelete} />
|
||
</div>
|
||
</TableCell>
|
||
</TableRow>
|
||
);
|
||
});
|
||
|
||
function TaskNameEditor({ task, onRename }: { task: Task; onRename: (task: Task, name: string) => Promise<void> }) {
|
||
const [editing, setEditing] = React.useState(false);
|
||
const [name, setName] = React.useState(task.name ?? "");
|
||
const [saving, setSaving] = React.useState(false);
|
||
const inputRef = React.useRef<HTMLInputElement>(null);
|
||
const cancelOnBlurRef = React.useRef(false);
|
||
|
||
React.useEffect(() => {
|
||
if (!editing) setName(task.name ?? "");
|
||
}, [editing, task.name]);
|
||
|
||
async function finishEditing() {
|
||
if (cancelOnBlurRef.current) {
|
||
cancelOnBlurRef.current = false;
|
||
setName(task.name ?? "");
|
||
setEditing(false);
|
||
return;
|
||
}
|
||
|
||
const next = name.trim();
|
||
if (!next || next === task.name?.trim()) {
|
||
setName(task.name ?? "");
|
||
setEditing(false);
|
||
return;
|
||
}
|
||
|
||
setSaving(true);
|
||
try {
|
||
await onRename(task, next);
|
||
setEditing(false);
|
||
} catch {
|
||
requestAnimationFrame(() => inputRef.current?.focus());
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
}
|
||
|
||
if (editing) {
|
||
return (
|
||
<div className="flex min-w-0 items-center gap-1">
|
||
<Input
|
||
ref={inputRef}
|
||
value={name}
|
||
maxLength={200}
|
||
autoFocus
|
||
disabled={saving}
|
||
aria-label={t("Task #{id} name", { id: task.id })}
|
||
className="h-7 min-w-28 max-w-48 px-2 font-medium"
|
||
onFocus={(event) => event.currentTarget.select()}
|
||
onChange={(event) => setName(event.target.value)}
|
||
onBlur={() => void finishEditing()}
|
||
onKeyDown={(event) => {
|
||
if (event.key === "Enter") {
|
||
event.preventDefault();
|
||
event.currentTarget.blur();
|
||
} else if (event.key === "Escape") {
|
||
event.preventDefault();
|
||
cancelOnBlurRef.current = true;
|
||
event.currentTarget.blur();
|
||
}
|
||
}}
|
||
/>
|
||
{saving && <Spinner className="shrink-0" />}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
return (
|
||
<div className="flex min-w-0 items-center gap-1">
|
||
<Link
|
||
href={`/function/tasks/detail?id=${encodeURIComponent(task.id)}`}
|
||
className="min-w-0 truncate rounded-sm hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||
title={task.name?.trim() ? task.name : task.description}
|
||
>
|
||
{task.name?.trim() ? task.name : <span className="text-muted-foreground">{t("Unnamed")}</span>}
|
||
</Link>
|
||
<Button
|
||
type="button"
|
||
variant="ghost"
|
||
size="icon-xs"
|
||
className="shrink-0 opacity-100 transition-opacity [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-focus-within:opacity-100 [@media(hover:hover)]:group-hover:opacity-100"
|
||
aria-label={t("Rename task #{id}", { id: task.id })}
|
||
title={t("Rename")}
|
||
onClick={() => {
|
||
setName(task.name ?? "");
|
||
setEditing(true);
|
||
}}
|
||
>
|
||
<PencilIcon />
|
||
</Button>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function taskPinIcon(pinning: boolean, pinned: boolean) {
|
||
if (pinning) return <Spinner />;
|
||
if (pinned) return <PinOffIcon />;
|
||
return <PinIcon />;
|
||
}
|
||
|
||
function TaskPinAction({ task, onTogglePinned }: { task: Task; onTogglePinned: (task: Task) => Promise<void> }) {
|
||
const [pinning, setPinning] = React.useState(false);
|
||
const pinned = taskIsPinned(task);
|
||
|
||
return (
|
||
<Button
|
||
type="button"
|
||
variant="ghost"
|
||
size="icon"
|
||
disabled={pinning}
|
||
aria-label={pinned ? t("Unpin task #{id}", { id: task.id }) : t("Pin task #{id}", { id: task.id })}
|
||
title={pinned ? t("Unpin") : t("Pin")}
|
||
onClick={async () => {
|
||
setPinning(true);
|
||
try {
|
||
await onTogglePinned(task);
|
||
} finally {
|
||
setPinning(false);
|
||
}
|
||
}}
|
||
>
|
||
{taskPinIcon(pinning, pinned)}
|
||
</Button>
|
||
);
|
||
}
|
||
|
||
// The three-state icon is written as separate branches instead of a nested ternary: the repo's Biome baseline bans noNestedTernary.
|
||
function taskControlIcon(pending: boolean, action: "pause" | "resume" | null) {
|
||
if (pending) return <Loader2Icon className="animate-spin" />;
|
||
if (action === "resume") return <PlayIcon />;
|
||
return <PauseIcon />;
|
||
}
|
||
|
||
// TaskControlButton is the inline pause/resume toggle. Terminal tasks render disabled rather than hidden,
|
||
// so every row's action column keeps a consistent width and buttons don't jump around with status.
|
||
function TaskControlButton({
|
||
task,
|
||
onControl,
|
||
}: {
|
||
task: Task;
|
||
onControl: (id: string, action: "pause" | "resume") => Promise<void>;
|
||
}) {
|
||
const [pending, setPending] = React.useState(false);
|
||
const action = taskControlAction(task.status);
|
||
const label = action === "resume" ? t("Resume task") : t("Pause task");
|
||
return (
|
||
<Button
|
||
size="icon"
|
||
variant="ghost"
|
||
aria-label={label}
|
||
title={action ? label : t("Cannot pause or resume in this state")}
|
||
disabled={!action || pending}
|
||
onClick={async () => {
|
||
if (!action) return;
|
||
setPending(true);
|
||
try {
|
||
await onControl(task.id, action);
|
||
} finally {
|
||
setPending(false);
|
||
}
|
||
}}
|
||
>
|
||
{taskControlIcon(pending, action)}
|
||
</Button>
|
||
);
|
||
}
|
||
|
||
function archiveBlockReason(task: Task): string {
|
||
if (task.queued) return t("Queued tasks must be paused first");
|
||
if (!ARCHIVABLE_STATUSES.has(task.status)) return t("Running or unfinished tasks must be paused first");
|
||
if (task.archive_blocked_by_task_id) {
|
||
return t("The task is directly inherited by unarchived task #{id}; archive the dependent task first", {
|
||
id: task.archive_blocked_by_task_id,
|
||
});
|
||
}
|
||
return "";
|
||
}
|
||
|
||
function ArchiveConfirmDialog({
|
||
count,
|
||
trigger,
|
||
onConfirm,
|
||
}: {
|
||
count: number;
|
||
trigger: React.ReactNode;
|
||
onConfirm: () => Promise<void>;
|
||
}) {
|
||
const [open, setOpen] = React.useState(false);
|
||
const [pending, setPending] = React.useState(false);
|
||
return (
|
||
<AlertDialog open={open} onOpenChange={(next) => !pending && setOpen(next)}>
|
||
<AlertDialogTrigger asChild>{trigger}</AlertDialogTrigger>
|
||
<AlertDialogContent>
|
||
<AlertDialogHeader>
|
||
<AlertDialogTitle>{count === 1 ? t("Archive task") : t("Archive {count} tasks", { count })}</AlertDialogTitle>
|
||
<AlertDialogDescription className="[overflow-wrap:anywhere]">
|
||
{t(
|
||
"Archiving stops task scheduling and compresses the graph, LLM history, files, and exclusive assets and traffic into local cold storage. Once archived, a task can be restored from \"Archived\".",
|
||
)}
|
||
</AlertDialogDescription>
|
||
</AlertDialogHeader>
|
||
<AlertDialogFooter>
|
||
<AlertDialogCancel disabled={pending}>{t("Cancel")}</AlertDialogCancel>
|
||
<AlertDialogAction
|
||
disabled={pending}
|
||
onClick={async (event) => {
|
||
event.preventDefault();
|
||
setPending(true);
|
||
try {
|
||
await onConfirm();
|
||
setOpen(false);
|
||
} finally {
|
||
setPending(false);
|
||
}
|
||
}}
|
||
>
|
||
{pending && <Spinner data-icon="inline-start" />}
|
||
{t("Confirm archive")}
|
||
</AlertDialogAction>
|
||
</AlertDialogFooter>
|
||
</AlertDialogContent>
|
||
</AlertDialog>
|
||
);
|
||
}
|
||
|
||
function TaskArchiveAction({ task, onArchive }: { task: Task; onArchive: (task: Task) => Promise<void> }) {
|
||
const reason = archiveBlockReason(task);
|
||
const trigger = (
|
||
<Button size="icon" variant="ghost" disabled={Boolean(reason)} aria-label={t("Archive task #{id}", { id: task.id })}>
|
||
<ArchiveIcon />
|
||
</Button>
|
||
);
|
||
if (reason) {
|
||
return (
|
||
<Tooltip>
|
||
<TooltipTrigger asChild>
|
||
<span className="inline-flex">{trigger}</span>
|
||
</TooltipTrigger>
|
||
<TooltipContent>{reason}</TooltipContent>
|
||
</Tooltip>
|
||
);
|
||
}
|
||
return <ArchiveConfirmDialog count={1} trigger={trigger} onConfirm={() => onArchive(task)} />;
|
||
}
|
||
|
||
const ARCHIVE_PROCESSING_STATES = new Set<TaskArchiveState>([
|
||
"archive_queued",
|
||
"archiving",
|
||
"restore_queued",
|
||
"restoring",
|
||
"delete_queued",
|
||
"deleting",
|
||
]);
|
||
|
||
const ARCHIVE_FAILED_STATES = new Set<TaskArchiveState>(["archive_failed", "restore_failed", "delete_failed"]);
|
||
|
||
function archiveStateLabel(state: TaskArchiveState): string {
|
||
const labels: Record<TaskArchiveState, string> = {
|
||
archive_queued: t("Archive queued"),
|
||
archiving: t("Archiving"),
|
||
archive_failed: t("Archive failed"),
|
||
ready: t("Restorable"),
|
||
restore_queued: t("Restore queued"),
|
||
restoring: t("Restoring"),
|
||
restore_failed: t("Restore failed"),
|
||
delete_queued: t("Delete queued"),
|
||
deleting: t("Deleting"),
|
||
delete_failed: t("Delete failed"),
|
||
};
|
||
return labels[state];
|
||
}
|
||
|
||
function ArchiveStateBadge({ state }: { state: TaskArchiveState }) {
|
||
let variant: "default" | "secondary" | "destructive" | "outline" = "outline";
|
||
if (state === "ready") variant = "secondary";
|
||
if (ARCHIVE_PROCESSING_STATES.has(state)) variant = "default";
|
||
if (ARCHIVE_FAILED_STATES.has(state)) variant = "destructive";
|
||
return <Badge variant={variant}>{archiveStateLabel(state)}</Badge>;
|
||
}
|
||
|
||
function formatArchiveBytes(bytes: number): string {
|
||
if (bytes <= 0) return "—";
|
||
if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
|
||
if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
|
||
if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||
return `${bytes} B`;
|
||
}
|
||
|
||
function archiveCompressionLabel(archive: TaskArchive): string {
|
||
if (archive.original_size <= 0 || archive.compressed_size <= 0) return "—";
|
||
const saved = Math.max(0, 100 - (archive.compressed_size / archive.original_size) * 100);
|
||
return t("{size} · saves {percent}%", { size: formatArchiveBytes(archive.compressed_size), percent: saved.toFixed(0) });
|
||
}
|
||
|
||
function archiveDataTotal(archive: TaskArchive): number {
|
||
return Object.values(archive.data_counts).reduce((sum, value) => sum + (Number(value) || 0), 0);
|
||
}
|
||
|
||
function archiveDate(value?: string): string {
|
||
if (!value) return "—";
|
||
const date = new Date(value);
|
||
if (Number.isNaN(date.getTime())) return "—";
|
||
return date.toLocaleString(intlLocale);
|
||
}
|
||
|
||
function ArchiveDeleteDialog({
|
||
archives,
|
||
onConfirm,
|
||
trigger,
|
||
}: {
|
||
archives: TaskArchive[];
|
||
onConfirm: () => Promise<void>;
|
||
trigger: React.ReactNode;
|
||
}) {
|
||
const [open, setOpen] = React.useState(false);
|
||
const [pending, setPending] = React.useState(false);
|
||
const rows = archives.reduce((sum, archive) => sum + archiveDataTotal(archive), 0);
|
||
const bytes = archives.reduce((sum, archive) => sum + archive.compressed_size, 0);
|
||
return (
|
||
<AlertDialog open={open} onOpenChange={(next) => !pending && setOpen(next)}>
|
||
<AlertDialogTrigger asChild>{trigger}</AlertDialogTrigger>
|
||
<AlertDialogContent>
|
||
<AlertDialogHeader>
|
||
<AlertDialogTitle>{t("Permanently delete {count} task archives?", { count: archives.length })}</AlertDialogTitle>
|
||
<AlertDialogDescription className="[overflow-wrap:anywhere]">
|
||
{t(
|
||
"About {size} of archive packages and {rows} related data snapshots will be permanently deleted. This action cannot be undone.",
|
||
{ size: formatArchiveBytes(bytes), rows: rows.toLocaleString(intlLocale) },
|
||
)}
|
||
</AlertDialogDescription>
|
||
</AlertDialogHeader>
|
||
<AlertDialogFooter>
|
||
<AlertDialogCancel disabled={pending}>{t("Cancel")}</AlertDialogCancel>
|
||
<AlertDialogAction
|
||
variant="destructive"
|
||
disabled={pending}
|
||
onClick={async (event) => {
|
||
event.preventDefault();
|
||
setPending(true);
|
||
try {
|
||
await onConfirm();
|
||
setOpen(false);
|
||
} finally {
|
||
setPending(false);
|
||
}
|
||
}}
|
||
>
|
||
{pending && <Spinner data-icon="inline-start" />}
|
||
{t("Delete permanently")}
|
||
</AlertDialogAction>
|
||
</AlertDialogFooter>
|
||
</AlertDialogContent>
|
||
</AlertDialog>
|
||
);
|
||
}
|
||
|
||
function TaskArchivesPanel({ onChanged }: { onChanged: () => void }) {
|
||
const [archives, setArchives] = React.useState<TaskArchive[]>([]);
|
||
const [query, setQuery] = React.useState("");
|
||
const [stateFilter, setStateFilter] = React.useState("all");
|
||
const [page, setPage] = React.useState(1);
|
||
const [pageSize, setPageSize] = React.useState(20);
|
||
const [total, setTotal] = React.useState(0);
|
||
const [selected, setSelected] = React.useState<Set<number>>(() => new Set());
|
||
const [loading, setLoading] = React.useState(true);
|
||
const pendingRestoreIDs = React.useRef(new Set<number>());
|
||
|
||
const load = React.useCallback(async () => {
|
||
try {
|
||
const result = await api.taskArchives({
|
||
page,
|
||
size: pageSize,
|
||
q: query.trim(),
|
||
state: stateFilter === "all" ? undefined : stateFilter,
|
||
});
|
||
setArchives(result.items);
|
||
setTotal(result.total);
|
||
setSelected((current) => {
|
||
const visible = new Set(result.items.map((archive) => archive.id));
|
||
return new Set([...current].filter((id) => visible.has(id)));
|
||
});
|
||
const pending = [...pendingRestoreIDs.current];
|
||
if (pending.length > 0) {
|
||
const states = await Promise.allSettled(pending.map((id) => api.taskArchive(id)));
|
||
let restored = false;
|
||
states.forEach((state, index) => {
|
||
if (state.status !== "rejected" || !(state.reason instanceof Error)) return;
|
||
if (!state.reason.message.includes("archive not found")) return;
|
||
pendingRestoreIDs.current.delete(pending[index]);
|
||
restored = true;
|
||
});
|
||
if (restored) onChanged();
|
||
}
|
||
} catch (error) {
|
||
toast.error(t("Failed to load the archive list: {error}", { error: (error as Error).message }));
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
}, [onChanged, page, pageSize, query, stateFilter]);
|
||
|
||
React.useEffect(() => {
|
||
void load();
|
||
const stopPolling = setVisibleInterval(() => void load(), 2_000);
|
||
return stopPolling;
|
||
}, [load]);
|
||
|
||
const selectable = React.useMemo(
|
||
() => archives.filter((archive) => !ARCHIVE_PROCESSING_STATES.has(archive.state)),
|
||
[archives],
|
||
);
|
||
const selectedArchives = React.useMemo(
|
||
() => archives.filter((archive) => selected.has(archive.id)),
|
||
[archives, selected],
|
||
);
|
||
const restorable = selectedArchives.filter(
|
||
(archive) => archive.state === "ready" || archive.state === "restore_failed",
|
||
);
|
||
const deletable = selectedArchives.filter(
|
||
(archive) => archive.state === "ready" || archive.state === "delete_failed",
|
||
);
|
||
const selectedAll = selectable.length > 0 && selectable.every((archive) => selected.has(archive.id));
|
||
const selectedSome = selectable.some((archive) => selected.has(archive.id));
|
||
|
||
const afterAction = React.useCallback(() => {
|
||
setSelected(new Set());
|
||
void load();
|
||
onChanged();
|
||
}, [load, onChanged]);
|
||
|
||
async function restoreMany(items: TaskArchive[]) {
|
||
try {
|
||
const result =
|
||
items.length === 1
|
||
? {
|
||
items: [
|
||
{
|
||
id: String(items[0].id),
|
||
ok: true,
|
||
queued: true,
|
||
archive_id: (await api.restoreTaskArchive(items[0].id)).id,
|
||
},
|
||
],
|
||
}
|
||
: await api.restoreTaskArchives(items.map((archive) => archive.id));
|
||
const succeeded = result.items.filter((item) => item.ok).length;
|
||
const failed = result.items.length - succeeded;
|
||
for (const item of result.items) {
|
||
const archiveID = Number(item.archive_id ?? item.id);
|
||
if (item.ok && Number.isSafeInteger(archiveID) && archiveID > 0) pendingRestoreIDs.current.add(archiveID);
|
||
}
|
||
if (succeeded > 0) toast.success(t("Queued {count} tasks for restore", { count: succeeded }));
|
||
if (failed > 0) toast.error(t("{count} tasks could not be restored", { count: failed }));
|
||
afterAction();
|
||
} catch (error) {
|
||
toast.error(t("Restore failed: {error}", { error: (error as Error).message }));
|
||
}
|
||
}
|
||
|
||
async function deleteMany(items: TaskArchive[]) {
|
||
try {
|
||
const result =
|
||
items.length === 1
|
||
? {
|
||
items: [
|
||
{
|
||
id: String(items[0].id),
|
||
ok: true,
|
||
queued: true,
|
||
archive_id: (await api.deleteTaskArchive(items[0].id)).id,
|
||
},
|
||
],
|
||
}
|
||
: await api.deleteTaskArchives(items.map((archive) => archive.id));
|
||
const succeeded = result.items.filter((item) => item.ok).length;
|
||
const failed = result.items.length - succeeded;
|
||
if (succeeded > 0) toast.success(t("Queued {count} archives for permanent deletion", { count: succeeded }));
|
||
if (failed > 0) toast.error(t("{count} archives could not be deleted", { count: failed }));
|
||
afterAction();
|
||
} catch (error) {
|
||
toast.error(t("Permanent delete failed: {error}", { error: (error as Error).message }));
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
async function retry(archive: TaskArchive) {
|
||
try {
|
||
if (archive.state === "archive_failed") await api.archiveTask(String(archive.task_id));
|
||
if (archive.state === "restore_failed") await api.restoreTaskArchive(archive.id);
|
||
if (archive.state === "delete_failed") await api.deleteTaskArchive(archive.id);
|
||
toast.success(t("Re-queued for processing"));
|
||
afterAction();
|
||
} catch (error) {
|
||
toast.error(t("Retry failed: {error}", { error: (error as Error).message }));
|
||
}
|
||
}
|
||
|
||
return (
|
||
<Card>
|
||
<CardContent className="flex flex-col gap-4 px-0 pt-6">
|
||
<div className="flex flex-wrap items-center gap-2 px-4 lg:px-6">
|
||
<div className="relative w-full sm:max-w-xs">
|
||
<SearchIcon className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
|
||
<Input
|
||
value={query}
|
||
onChange={(event) => {
|
||
setQuery(event.target.value);
|
||
setPage(1);
|
||
}}
|
||
placeholder={t("Search task name / description / ID")}
|
||
className="pl-8"
|
||
/>
|
||
</div>
|
||
<Select
|
||
value={stateFilter}
|
||
onValueChange={(value) => {
|
||
setStateFilter(value);
|
||
setPage(1);
|
||
}}
|
||
>
|
||
<SelectTrigger className="w-36">
|
||
<SelectValue placeholder={t("State")} />
|
||
</SelectTrigger>
|
||
<SelectContent>
|
||
<SelectGroup>
|
||
<SelectItem value="all">{t("All statuses")}</SelectItem>
|
||
<SelectItem value="archive_queued">{t("Archive queued")}</SelectItem>
|
||
<SelectItem value="archiving">{t("Archiving")}</SelectItem>
|
||
<SelectItem value="ready">{t("Restorable")}</SelectItem>
|
||
<SelectItem value="restore_queued">{t("Restore queued")}</SelectItem>
|
||
<SelectItem value="restoring">{t("Restoring")}</SelectItem>
|
||
<SelectItem value="delete_queued">{t("Delete queued")}</SelectItem>
|
||
<SelectItem value="deleting">{t("Deleting")}</SelectItem>
|
||
<SelectItem value="archive_failed">{t("Archive failed")}</SelectItem>
|
||
<SelectItem value="restore_failed">{t("Restore failed")}</SelectItem>
|
||
<SelectItem value="delete_failed">{t("Delete failed")}</SelectItem>
|
||
</SelectGroup>
|
||
</SelectContent>
|
||
</Select>
|
||
<span className="text-muted-foreground text-xs tabular-nums">{t("{count} archives", { count: total })}</span>
|
||
{selectedArchives.length > 0 && (
|
||
<>
|
||
<span className="text-xs tabular-nums">{t("{count} selected", { count: selectedArchives.length })}</span>
|
||
{restorable.length > 0 && (
|
||
<Button size="sm" variant="outline" onClick={() => void restoreMany(restorable)}>
|
||
<Undo2Icon data-icon="inline-start" />
|
||
{t("Restore {count}", { count: restorable.length })}
|
||
</Button>
|
||
)}
|
||
{deletable.length > 0 && (
|
||
<ArchiveDeleteDialog
|
||
archives={deletable}
|
||
onConfirm={() => deleteMany(deletable)}
|
||
trigger={
|
||
<Button size="sm" variant="destructive">
|
||
<Trash2Icon data-icon="inline-start" />
|
||
{t("Permanently delete {count}", { count: deletable.length })}
|
||
</Button>
|
||
}
|
||
/>
|
||
)}
|
||
</>
|
||
)}
|
||
</div>
|
||
{loading ? (
|
||
<div className="flex justify-center py-20">
|
||
<Spinner />
|
||
</div>
|
||
) : archives.length === 0 ? (
|
||
<Empty className="mx-4 border border-dashed lg:mx-6">
|
||
<EmptyHeader>
|
||
<EmptyTitle>{t("No task archives")}</EmptyTitle>
|
||
<EmptyDescription>{t("Paused or terminal tasks can be archived from the current task list.")}</EmptyDescription>
|
||
</EmptyHeader>
|
||
</Empty>
|
||
) : (
|
||
<Table className="**:data-[slot='table-cell']:px-4 **:data-[slot='table-head']:px-4">
|
||
<TableHeader className="[&_tr]:border-t">
|
||
<TableRow>
|
||
<TableHead className="w-10">
|
||
<Checkbox
|
||
checked={selectedAll || (selectedSome ? "indeterminate" : false)}
|
||
onCheckedChange={(checked) =>
|
||
setSelected(checked === true ? new Set(selectable.map((archive) => archive.id)) : new Set())
|
||
}
|
||
aria-label={t("Select the archives on this page")}
|
||
/>
|
||
</TableHead>
|
||
<TableHead>{t("Task")}</TableHead>
|
||
<TableHead>{t("Original status")}</TableHead>
|
||
<TableHead>{t("Category")}</TableHead>
|
||
<TableHead>{t("Archived at")}</TableHead>
|
||
<TableHead>{t("Compressed size")}</TableHead>
|
||
<TableHead>{t("Data records")}</TableHead>
|
||
<TableHead className="min-w-44">{t("State")}</TableHead>
|
||
<TableHead className="text-right">{t("Actions")}</TableHead>
|
||
</TableRow>
|
||
</TableHeader>
|
||
<TableBody>
|
||
{archives.map((archive) => {
|
||
const processing = ARCHIVE_PROCESSING_STATES.has(archive.state);
|
||
const canRestore = archive.state === "ready" || archive.state === "restore_failed";
|
||
const canDelete = archive.state === "ready" || archive.state === "delete_failed";
|
||
return (
|
||
<TableRow key={archive.id} data-state={selected.has(archive.id) ? "selected" : undefined}>
|
||
<TableCell>
|
||
<Checkbox
|
||
checked={selected.has(archive.id)}
|
||
disabled={processing}
|
||
onCheckedChange={(checked) =>
|
||
setSelected((current) => {
|
||
const next = new Set(current);
|
||
if (checked === true) next.add(archive.id);
|
||
else next.delete(archive.id);
|
||
return next;
|
||
})
|
||
}
|
||
aria-label={t("Select task archive #{id}", { id: archive.task_id })}
|
||
/>
|
||
</TableCell>
|
||
<TableCell className="max-w-sm">
|
||
<div className="flex min-w-0 flex-col gap-0.5">
|
||
<span className="truncate font-medium">
|
||
{archive.task_name || archive.task_description || t("Task #{id}", { id: archive.task_id })}
|
||
</span>
|
||
<span className="text-muted-foreground truncate text-xs">
|
||
#{archive.task_id} · {archive.task_description}
|
||
</span>
|
||
</div>
|
||
</TableCell>
|
||
<TableCell>
|
||
<StatusBadge domain="task" value={archive.original_status} dot />
|
||
</TableCell>
|
||
<TableCell className="text-muted-foreground">{archive.category_name || t("Uncategorized")}</TableCell>
|
||
<TableCell className="text-muted-foreground whitespace-nowrap text-xs">
|
||
{archiveDate(archive.archived_at || archive.requested_at)}
|
||
</TableCell>
|
||
<TableCell
|
||
className="whitespace-nowrap text-xs"
|
||
title={t("Before compression: {size}", { size: formatArchiveBytes(archive.original_size) })}
|
||
>
|
||
{archiveCompressionLabel(archive)}
|
||
</TableCell>
|
||
<TableCell className="text-xs tabular-nums">{archiveDataTotal(archive).toLocaleString(intlLocale)}</TableCell>
|
||
<TableCell>
|
||
<div className="flex min-w-0 flex-col gap-1.5">
|
||
<ArchiveStateBadge state={archive.state} />
|
||
{processing && <Progress value={archive.progress} />}
|
||
{archive.error && (
|
||
<p className="text-destructive text-xs [overflow-wrap:anywhere]">{archive.error}</p>
|
||
)}
|
||
{[...new Set(archive.warnings ?? [])].map((warning) => (
|
||
<p
|
||
key={warning}
|
||
className="text-amber-700 text-xs [overflow-wrap:anywhere] dark:text-amber-400"
|
||
>
|
||
{warning}
|
||
</p>
|
||
))}
|
||
<span className="text-muted-foreground text-xs">
|
||
{t(archive.phase)} · {archive.progress}%
|
||
</span>
|
||
</div>
|
||
</TableCell>
|
||
<TableCell className="text-right">
|
||
<div className="flex justify-end gap-0.5">
|
||
{ARCHIVE_FAILED_STATES.has(archive.state) && (
|
||
<Button
|
||
size="icon"
|
||
variant="ghost"
|
||
onClick={() => void retry(archive)}
|
||
aria-label={t("Retry archive operation")}
|
||
title={t("Retry")}
|
||
>
|
||
<Undo2Icon />
|
||
</Button>
|
||
)}
|
||
{canRestore && (
|
||
<Button
|
||
size="icon"
|
||
variant="ghost"
|
||
onClick={() => void restoreMany([archive])}
|
||
aria-label={t("Restore task")}
|
||
title={t("Restore task")}
|
||
>
|
||
<Undo2Icon />
|
||
</Button>
|
||
)}
|
||
{canDelete && (
|
||
<ArchiveDeleteDialog
|
||
archives={[archive]}
|
||
onConfirm={() => deleteMany([archive])}
|
||
trigger={
|
||
<Button size="icon" variant="ghost" aria-label={t("Permanently delete archive")} title={t("Permanently delete")}>
|
||
<Trash2Icon />
|
||
</Button>
|
||
}
|
||
/>
|
||
)}
|
||
</div>
|
||
</TableCell>
|
||
</TableRow>
|
||
);
|
||
})}
|
||
</TableBody>
|
||
</Table>
|
||
)}
|
||
<TablePagination
|
||
page={page}
|
||
pageSize={pageSize}
|
||
total={total}
|
||
onPageChange={setPage}
|
||
onPageSizeChange={(size) => {
|
||
setPageSize(size);
|
||
setPage(1);
|
||
}}
|
||
/>
|
||
</CardContent>
|
||
</Card>
|
||
);
|
||
}
|
||
|
||
const emptyDeleteOptions = (): DeleteTaskOptions => ({
|
||
delete_assets: false,
|
||
delete_traffic: false,
|
||
delete_files: false,
|
||
delete_findings: false,
|
||
delete_llm_records: false,
|
||
});
|
||
|
||
const deleteOptionKeys: (keyof DeleteTaskOptions)[] = [
|
||
"delete_assets",
|
||
"delete_traffic",
|
||
"delete_files",
|
||
"delete_findings",
|
||
"delete_llm_records",
|
||
];
|
||
|
||
// DeleteOptionFields renders the "also clean up related data" checkbox block shared by the
|
||
// single-task and bulk delete dialogs. idPrefix keeps the label/input ids unique when
|
||
// several dialogs live in the same table.
|
||
function DeleteOptionFields({
|
||
idPrefix,
|
||
options,
|
||
onOptionsChange,
|
||
disabled,
|
||
}: {
|
||
idPrefix: string;
|
||
options: DeleteTaskOptions;
|
||
onOptionsChange: React.Dispatch<React.SetStateAction<DeleteTaskOptions>>;
|
||
disabled: boolean;
|
||
}) {
|
||
const selectedCount = deleteOptionKeys.filter((key) => options[key]).length;
|
||
let allChecked: boolean | "indeterminate" = false;
|
||
if (selectedCount === deleteOptionKeys.length) {
|
||
allChecked = true;
|
||
} else if (selectedCount > 0) {
|
||
allChecked = "indeterminate";
|
||
}
|
||
|
||
const updateOption = (key: keyof DeleteTaskOptions, checked: boolean) => {
|
||
onOptionsChange((current) => ({ ...current, [key]: checked }));
|
||
};
|
||
|
||
const updateAllOptions = (checked: boolean) => {
|
||
onOptionsChange({
|
||
delete_assets: checked,
|
||
delete_traffic: checked,
|
||
delete_files: checked,
|
||
delete_findings: checked,
|
||
delete_llm_records: checked,
|
||
});
|
||
};
|
||
|
||
return (
|
||
<FieldSet disabled={disabled}>
|
||
<FieldLegend variant="label">{t("Also clean up related data")}</FieldLegend>
|
||
<FieldGroup className="gap-3">
|
||
<Field orientation="horizontal">
|
||
<Checkbox
|
||
id={`delete-all-${idPrefix}`}
|
||
checked={allChecked}
|
||
onCheckedChange={(checked) => updateAllOptions(checked === true)}
|
||
/>
|
||
<FieldContent>
|
||
<FieldLabel htmlFor={`delete-all-${idPrefix}`}>{t("Delete all")}</FieldLabel>
|
||
<FieldDescription>{t("Check every related data type below, including assets, traffic, files, findings, and LLM request/response records.")}</FieldDescription>
|
||
</FieldContent>
|
||
</Field>
|
||
<Field orientation="horizontal">
|
||
<Checkbox
|
||
id={`delete-assets-${idPrefix}`}
|
||
checked={options.delete_assets}
|
||
onCheckedChange={(checked) => updateOption("delete_assets", checked === true)}
|
||
/>
|
||
<FieldContent>
|
||
<FieldLabel htmlFor={`delete-assets-${idPrefix}`}>{t("Related assets")}</FieldLabel>
|
||
<FieldDescription>{t("Delete assets that belong only to this task; shared assets are only detached from the current task.")}</FieldDescription>
|
||
</FieldContent>
|
||
</Field>
|
||
<Field orientation="horizontal">
|
||
<Checkbox
|
||
id={`delete-traffic-${idPrefix}`}
|
||
checked={options.delete_traffic}
|
||
onCheckedChange={(checked) => updateOption("delete_traffic", checked === true)}
|
||
/>
|
||
<FieldContent>
|
||
<FieldLabel htmlFor={`delete-traffic-${idPrefix}`}>{t("Related traffic")}</FieldLabel>
|
||
<FieldDescription>{t("Deleted by the related assets' exact hostnames; traffic of shared hosts still referenced by other tasks is kept.")}</FieldDescription>
|
||
</FieldContent>
|
||
</Field>
|
||
<Field orientation="horizontal">
|
||
<Checkbox
|
||
id={`delete-files-${idPrefix}`}
|
||
checked={options.delete_files}
|
||
onCheckedChange={(checked) => updateOption("delete_files", checked === true)}
|
||
/>
|
||
<FieldContent>
|
||
<FieldLabel htmlFor={`delete-files-${idPrefix}`}>{t("Task files")}</FieldLabel>
|
||
<FieldDescription>{t("Delete uploaded files, command output, and other artifacts in the task's working directory.")}</FieldDescription>
|
||
</FieldContent>
|
||
</Field>
|
||
<Field orientation="horizontal">
|
||
<Checkbox
|
||
id={`delete-findings-${idPrefix}`}
|
||
checked={options.delete_findings}
|
||
onCheckedChange={(checked) => updateOption("delete_findings", checked === true)}
|
||
/>
|
||
<FieldContent>
|
||
<FieldLabel htmlFor={`delete-findings-${idPrefix}`}>{t("Related findings")}</FieldLabel>
|
||
<FieldDescription>{t("Permanently delete the standalone finding records and finding reports produced by this task.")}</FieldDescription>
|
||
</FieldContent>
|
||
</Field>
|
||
<Field orientation="horizontal">
|
||
<Checkbox
|
||
id={`delete-llm-records-${idPrefix}`}
|
||
checked={options.delete_llm_records}
|
||
onCheckedChange={(checked) => updateOption("delete_llm_records", checked === true)}
|
||
/>
|
||
<FieldContent>
|
||
<FieldLabel htmlFor={`delete-llm-records-${idPrefix}`}>{t("LLM request/response records")}</FieldLabel>
|
||
<FieldDescription>{t("Permanently delete the LLM requests, responses, tokens, and error details recorded for this task.")}</FieldDescription>
|
||
</FieldContent>
|
||
</Field>
|
||
</FieldGroup>
|
||
</FieldSet>
|
||
);
|
||
}
|
||
|
||
function DeleteTaskDialog({
|
||
task,
|
||
onDelete,
|
||
}: {
|
||
task: Task;
|
||
onDelete: (id: string, options: DeleteTaskOptions) => Promise<void>;
|
||
}) {
|
||
const [open, setOpen] = React.useState(false);
|
||
const [deleting, setDeleting] = React.useState(false);
|
||
const [options, setOptions] = React.useState<DeleteTaskOptions>(emptyDeleteOptions);
|
||
|
||
const handleOpenChange = (next: boolean) => {
|
||
if (deleting) return;
|
||
setOpen(next);
|
||
if (next) setOptions(emptyDeleteOptions());
|
||
};
|
||
|
||
const handleDelete = async () => {
|
||
setDeleting(true);
|
||
try {
|
||
await onDelete(task.id, options);
|
||
setOpen(false);
|
||
} finally {
|
||
setDeleting(false);
|
||
}
|
||
};
|
||
|
||
return (
|
||
<AlertDialog open={open} onOpenChange={handleOpenChange}>
|
||
<AlertDialogTrigger asChild>
|
||
<Button size="icon" variant="outline" aria-label={t("Delete task")}>
|
||
<Trash2Icon className="text-destructive" />
|
||
</Button>
|
||
</AlertDialogTrigger>
|
||
<AlertDialogContent>
|
||
<AlertDialogHeader>
|
||
<AlertDialogTitle>{t("Delete task #{id}?", { id: task.id })}</AlertDialogTitle>
|
||
<AlertDialogDescription className="[overflow-wrap:anywhere]">
|
||
{task.description
|
||
? t("“{description}” will be permanently deleted together with its execution records and exploration graph.", {
|
||
description: task.description.length > 80 ? `${task.description.slice(0, 80)}…` : task.description,
|
||
})
|
||
: t("This task will be permanently deleted together with its execution records and exploration graph.")}
|
||
</AlertDialogDescription>
|
||
</AlertDialogHeader>
|
||
<DeleteOptionFields idPrefix={task.id} options={options} onOptionsChange={setOptions} disabled={deleting} />
|
||
<AlertDialogFooter>
|
||
<AlertDialogCancel disabled={deleting}>{t("Cancel")}</AlertDialogCancel>
|
||
<AlertDialogAction
|
||
variant="destructive"
|
||
disabled={deleting}
|
||
onClick={(event) => {
|
||
event.preventDefault();
|
||
void handleDelete();
|
||
}}
|
||
>
|
||
{deleting && <Spinner data-icon="inline-start" />}
|
||
{deleting ? t("Deleting") : t("Delete")}
|
||
</AlertDialogAction>
|
||
</AlertDialogFooter>
|
||
</AlertDialogContent>
|
||
</AlertDialog>
|
||
);
|
||
}
|
||
|
||
// BulkDeleteTasksDialog deletes every checked task with one shared set of cleanup options.
|
||
// The backend has no batch endpoint, so deletion runs one task at a time (see deleteTasks)
|
||
// and the button shows live progress.
|
||
// MoveTasksCategoryDialog confirms a target before applying, so a mis-click on a
|
||
// large selection cannot silently re-file every task. UNCATEGORIZED_VALUE stands
|
||
// in for "no category" because Select rejects an empty string value.
|
||
function MoveTasksCategoryDialog({
|
||
categories,
|
||
count,
|
||
moving,
|
||
onMove,
|
||
}: {
|
||
categories: TaskCategory[];
|
||
count: number;
|
||
moving: boolean;
|
||
onMove: (categoryID?: number) => Promise<void>;
|
||
}) {
|
||
const [open, setOpen] = React.useState(false);
|
||
const [target, setTarget] = React.useState(UNCATEGORIZED_VALUE);
|
||
|
||
const handleOpenChange = (next: boolean) => {
|
||
if (moving) return;
|
||
setOpen(next);
|
||
if (next) setTarget(UNCATEGORIZED_VALUE);
|
||
};
|
||
|
||
return (
|
||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||
<DialogTrigger asChild>
|
||
<Button size="sm" variant="outline">
|
||
<FolderInputIcon data-icon="inline-start" /> {t("Change category")}
|
||
</Button>
|
||
</DialogTrigger>
|
||
<DialogContent>
|
||
<DialogHeader>
|
||
<DialogTitle>{t("Change the category of {count} selected tasks", { count })}</DialogTitle>
|
||
<DialogDescription>
|
||
{t(
|
||
"The target category applies to all selected tasks; choosing \"Uncategorized\" moves them out of their current category.",
|
||
)}
|
||
</DialogDescription>
|
||
</DialogHeader>
|
||
<Field>
|
||
<FieldLabel htmlFor="bulk-category">{t("Target category")}</FieldLabel>
|
||
<Select value={target} onValueChange={setTarget} disabled={moving}>
|
||
<SelectTrigger id="bulk-category" className="w-full">
|
||
<SelectValue placeholder={t("Select a category")} />
|
||
</SelectTrigger>
|
||
<SelectContent>
|
||
<SelectGroup>
|
||
<SelectItem value={UNCATEGORIZED_VALUE}>{t("Uncategorized")}</SelectItem>
|
||
{categories.map((category) => (
|
||
<SelectItem key={category.id} value={String(category.id)}>
|
||
{category.name}
|
||
</SelectItem>
|
||
))}
|
||
</SelectGroup>
|
||
</SelectContent>
|
||
</Select>
|
||
{categories.length === 0 && <FieldDescription>{t("No categories yet; create one in \"Category management\" first.")}</FieldDescription>}
|
||
</Field>
|
||
<DialogFooter>
|
||
<DialogClose asChild>
|
||
<Button variant="outline" disabled={moving}>
|
||
{t("Cancel")}
|
||
</Button>
|
||
</DialogClose>
|
||
<Button
|
||
disabled={moving}
|
||
onClick={() => {
|
||
void onMove(target === UNCATEGORIZED_VALUE ? undefined : Number(target)).then(() => setOpen(false));
|
||
}}
|
||
>
|
||
{moving && <Spinner data-icon="inline-start" />}
|
||
{t("Move")}
|
||
</Button>
|
||
</DialogFooter>
|
||
</DialogContent>
|
||
</Dialog>
|
||
);
|
||
}
|
||
|
||
function BulkDeleteTasksDialog({
|
||
ids,
|
||
onDelete,
|
||
}: {
|
||
ids: string[];
|
||
onDelete: (ids: string[], options: DeleteTaskOptions, onProgress: (done: number) => void) => Promise<void>;
|
||
}) {
|
||
const [open, setOpen] = React.useState(false);
|
||
const [deleting, setDeleting] = React.useState(false);
|
||
const [done, setDone] = React.useState(0);
|
||
const [options, setOptions] = React.useState<DeleteTaskOptions>(emptyDeleteOptions);
|
||
|
||
const handleOpenChange = (next: boolean) => {
|
||
if (deleting) return;
|
||
setOpen(next);
|
||
if (next) {
|
||
setOptions(emptyDeleteOptions());
|
||
setDone(0);
|
||
}
|
||
};
|
||
|
||
const handleDelete = async () => {
|
||
setDeleting(true);
|
||
setDone(0);
|
||
try {
|
||
await onDelete(ids, options, setDone);
|
||
setOpen(false);
|
||
} finally {
|
||
setDeleting(false);
|
||
}
|
||
};
|
||
|
||
return (
|
||
<AlertDialog open={open} onOpenChange={handleOpenChange}>
|
||
<AlertDialogTrigger asChild>
|
||
<Button size="sm" variant="outline">
|
||
<Trash2Icon className="text-destructive" /> {t("Delete selected {count}", { count: ids.length })}
|
||
</Button>
|
||
</AlertDialogTrigger>
|
||
<AlertDialogContent className="max-h-[85vh] overflow-y-auto">
|
||
<AlertDialogHeader>
|
||
<AlertDialogTitle>{t("Delete {count} selected tasks?", { count: ids.length })}</AlertDialogTitle>
|
||
<AlertDialogDescription>
|
||
{t(
|
||
"The execution records and exploration graphs of these tasks will be permanently deleted; the cleanup options below apply to all selected tasks.",
|
||
)}
|
||
</AlertDialogDescription>
|
||
</AlertDialogHeader>
|
||
<div className="text-muted-foreground flex flex-wrap gap-1 text-xs">
|
||
{ids.slice(0, 30).map((id) => (
|
||
<code key={id} className="bg-muted rounded px-1.5 py-0.5 font-mono">
|
||
#{id}
|
||
</code>
|
||
))}
|
||
{ids.length > 30 && <span className="self-center">{t("…{count} in total", { count: ids.length })}</span>}
|
||
</div>
|
||
<DeleteOptionFields idPrefix="bulk" options={options} onOptionsChange={setOptions} disabled={deleting} />
|
||
<AlertDialogFooter>
|
||
<AlertDialogCancel disabled={deleting}>{t("Cancel")}</AlertDialogCancel>
|
||
<AlertDialogAction
|
||
variant="destructive"
|
||
disabled={deleting}
|
||
onClick={(event) => {
|
||
event.preventDefault();
|
||
void handleDelete();
|
||
}}
|
||
>
|
||
{deleting && <Spinner data-icon="inline-start" />}
|
||
{deleting
|
||
? t("Deleting {done}/{total}", { done, total: ids.length })
|
||
: t("Delete {count} tasks", { count: ids.length })}
|
||
</AlertDialogAction>
|
||
</AlertDialogFooter>
|
||
</AlertDialogContent>
|
||
</AlertDialog>
|
||
);
|
||
}
|
||
|
||
// CreateTaskSheet is the create-task drawer. Its form state lives HERE, not in TasksPage: with
|
||
// description/goal held by the page component every keystroke re-rendered the whole task table
|
||
// behind the drawer (plus its sticky column and 20 AlertDialog trees), which showed up as
|
||
// input lag. Now typing only re-renders the drawer.
|
||
function SourceTaskPicker({
|
||
tasks,
|
||
value,
|
||
onValueChange,
|
||
portalContainer,
|
||
}: {
|
||
tasks: Task[];
|
||
value: string[];
|
||
onValueChange: (value: string[]) => void;
|
||
portalContainer?: React.RefObject<HTMLElement | null>;
|
||
}) {
|
||
const tasksByID = React.useMemo(() => new Map(tasks.map((task) => [task.id, task])), [tasks]);
|
||
const taskIDs = React.useMemo(() => tasks.map((task) => task.id), [tasks]);
|
||
const atLimit = value.length >= MAX_SOURCE_TASKS;
|
||
|
||
const handleValueChange = (next: string[]) => {
|
||
onValueChange(next.slice(0, MAX_SOURCE_TASKS));
|
||
};
|
||
|
||
return (
|
||
<Combobox
|
||
items={taskIDs}
|
||
itemToStringValue={(taskID) => {
|
||
const task = tasksByID.get(taskID);
|
||
return task ? `${task.id} ${task.description} ${task.goal}` : taskID;
|
||
}}
|
||
multiple
|
||
value={value}
|
||
onValueChange={handleValueChange}
|
||
>
|
||
<ComboboxChips>
|
||
<ComboboxValue>
|
||
{value.map((taskID) => (
|
||
<ComboboxChip key={taskID}>#{taskID}</ComboboxChip>
|
||
))}
|
||
</ComboboxValue>
|
||
<ComboboxChipsInput
|
||
id="source-tasks"
|
||
placeholder={atLimit ? t("Link up to {count} tasks", { count: MAX_SOURCE_TASKS }) : t("Search task ID, description, or goal")}
|
||
disabled={atLimit}
|
||
/>
|
||
</ComboboxChips>
|
||
<ComboboxContent portalContainer={portalContainer}>
|
||
<ComboboxEmpty>{t("No matching tasks")}</ComboboxEmpty>
|
||
<ComboboxList>
|
||
{(taskID) => {
|
||
const task = tasksByID.get(taskID);
|
||
return (
|
||
<ComboboxItem key={taskID} value={taskID} disabled={atLimit && !value.includes(taskID)}>
|
||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||
<div className="min-w-0 flex-1">
|
||
<p className="truncate text-sm font-medium">
|
||
#{taskID} · {task?.description ?? t("Unknown task")}
|
||
</p>
|
||
{task?.goal && <p className="text-muted-foreground truncate text-xs">{task.goal}</p>}
|
||
</div>
|
||
{task && <StatusBadge domain="task" value={task.status} />}
|
||
</div>
|
||
</ComboboxItem>
|
||
);
|
||
}}
|
||
</ComboboxList>
|
||
</ComboboxContent>
|
||
</Combobox>
|
||
);
|
||
}
|
||
|
||
// CategoryPicker is the single-category picker in the create-task form: search existing categories; typing a name not in the
|
||
// library and pressing Enter (or clicking "Create" in the dropdown) creates the category on the fly and selects it; the selection shows as a removable tag. Categories are
|
||
// global resources, so creating one here is equivalent to creating it manually in "Category management". Only one category is allowed.
|
||
function CategoryPicker({
|
||
categories,
|
||
value,
|
||
onValueChange,
|
||
onCategoryCreated,
|
||
portalContainer,
|
||
}: {
|
||
categories: TaskCategory[];
|
||
value?: number;
|
||
onValueChange: (categoryID?: number) => void;
|
||
onCategoryCreated: () => void;
|
||
portalContainer?: React.RefObject<HTMLElement | null>;
|
||
}) {
|
||
const [inputValue, setInputValue] = React.useState("");
|
||
const [creating, setCreating] = React.useState(false);
|
||
// A newly created category only flows back into categories after the parent re-fetches, so keep a local copy to avoid the selected chip and
|
||
// the dropdown showing "Unknown category" during that window.
|
||
const [localExtra, setLocalExtra] = React.useState<TaskCategory[]>([]);
|
||
|
||
const allCategories = React.useMemo(() => {
|
||
const byID = new Map<number, TaskCategory>();
|
||
for (const category of categories) byID.set(category.id, category);
|
||
for (const category of localExtra) if (!byID.has(category.id)) byID.set(category.id, category);
|
||
return [...byID.values()];
|
||
}, [categories, localExtra]);
|
||
|
||
const byID = React.useMemo(() => new Map(allCategories.map((c) => [String(c.id), c])), [allCategories]);
|
||
const categoryIDs = React.useMemo(() => allCategories.map((c) => String(c.id)), [allCategories]);
|
||
const selectedIDs = value != null ? [String(value)] : [];
|
||
|
||
const trimmed = inputValue.trim();
|
||
const lower = trimmed.toLowerCase();
|
||
// Matches base-ui's default substring filter, used to decide whether "any related categories exist".
|
||
const matchCount = trimmed
|
||
? allCategories.filter((c) => c.name.toLowerCase().includes(lower)).length
|
||
: allCategories.length;
|
||
|
||
const createAndSelect = async () => {
|
||
if (!trimmed || creating) return;
|
||
// An exact same-name category already exists: select it directly instead of creating a duplicate.
|
||
const existing = allCategories.find((c) => c.name.toLowerCase() === lower);
|
||
if (existing) {
|
||
onValueChange(existing.id);
|
||
setInputValue("");
|
||
return;
|
||
}
|
||
setCreating(true);
|
||
try {
|
||
const created = await api.createTaskCategory(trimmed);
|
||
setLocalExtra((prev) => [...prev, created]);
|
||
onValueChange(created.id);
|
||
setInputValue("");
|
||
onCategoryCreated();
|
||
toast.success(t("Category \"{name}\" created", { name: created.name }));
|
||
} catch (e) {
|
||
toast.error(t("Failed to create category: {error}", { error: (e as Error).message }));
|
||
} finally {
|
||
setCreating(false);
|
||
}
|
||
};
|
||
|
||
return (
|
||
<Combobox
|
||
items={categoryIDs}
|
||
itemToStringValue={(id) => byID.get(id)?.name ?? id}
|
||
multiple
|
||
value={selectedIDs}
|
||
onValueChange={(next: string[]) => {
|
||
// Single select: keep the most recently selected one; removing the chip (clearing) returns to uncategorized.
|
||
const last = next[next.length - 1];
|
||
onValueChange(last ? Number(last) : undefined);
|
||
setInputValue("");
|
||
}}
|
||
inputValue={inputValue}
|
||
onInputValueChange={setInputValue}
|
||
>
|
||
<ComboboxChips>
|
||
<ComboboxValue>
|
||
{selectedIDs.map((id) => (
|
||
<ComboboxChip key={id}>{byID.get(id)?.name ?? t("Unknown category")}</ComboboxChip>
|
||
))}
|
||
</ComboboxValue>
|
||
<ComboboxChipsInput
|
||
id="task-category"
|
||
placeholder={selectedIDs.length ? "" : t("Search categories, or type a new name and press Enter to create")}
|
||
onKeyDown={(e) => {
|
||
// Enter with zero matches = create; with matches, keep base-ui's "Enter selects the highlighted item".
|
||
if (e.key === "Enter" && matchCount === 0 && trimmed) {
|
||
e.preventDefault();
|
||
void createAndSelect();
|
||
}
|
||
}}
|
||
/>
|
||
</ComboboxChips>
|
||
<ComboboxContent portalContainer={portalContainer}>
|
||
<ComboboxList>
|
||
{(id: string) => (
|
||
<ComboboxItem key={id} value={id}>
|
||
{byID.get(id)?.name ?? id}
|
||
</ComboboxItem>
|
||
)}
|
||
</ComboboxList>
|
||
{matchCount === 0 &&
|
||
(trimmed ? (
|
||
<button
|
||
type="button"
|
||
disabled={creating}
|
||
onClick={() => void createAndSelect()}
|
||
className="flex w-full items-center gap-2 px-2 py-2 text-left text-sm hover:bg-accent hover:text-accent-foreground disabled:opacity-50"
|
||
>
|
||
{creating ? <Spinner className="size-4" /> : <PlusIcon className="size-4" />}
|
||
{t("Create category \"{name}\"", { name: trimmed })}
|
||
</button>
|
||
) : (
|
||
<div className="px-2 py-2 text-sm text-muted-foreground">{t("Type a name to search or create a category")}</div>
|
||
))}
|
||
</ComboboxContent>
|
||
</Combobox>
|
||
);
|
||
}
|
||
|
||
const COMPANY_SCOPE_LABELS: Record<string, string> = {
|
||
domain: t("Domain"),
|
||
ip: "IP",
|
||
cidr: "CIDR",
|
||
icp: "ICP",
|
||
keyword: t("Keyword"),
|
||
};
|
||
|
||
function companyScopeSummary(company: Company): string {
|
||
const rows = company.scope ?? [];
|
||
if (rows.length === 0) return t("No asset scope configured");
|
||
const preview = rows.slice(0, 3).map((row) => {
|
||
const value = row.raw || row.value || row.domain || row.net || "";
|
||
return `${COMPANY_SCOPE_LABELS[row.kind] ?? row.kind}: ${value}`;
|
||
});
|
||
const more = rows.length > preview.length ? ` · ${t("{count} more", { count: rows.length - preview.length })}` : "";
|
||
return `${preview.join(" · ")}${more}`;
|
||
}
|
||
|
||
function CompanyPicker({
|
||
companies,
|
||
value,
|
||
onValueChange,
|
||
portalContainer,
|
||
}: {
|
||
companies: Company[];
|
||
value: number[];
|
||
onValueChange: (value: number[]) => void;
|
||
portalContainer?: React.RefObject<HTMLElement | null>;
|
||
}) {
|
||
const companiesByID = React.useMemo(
|
||
() => new Map(companies.map((company) => [String(company.id), company])),
|
||
[companies],
|
||
);
|
||
const companyIDs = React.useMemo(() => companies.map((company) => String(company.id)), [companies]);
|
||
const selectedIDs = React.useMemo(() => value.map(String), [value]);
|
||
|
||
return (
|
||
<Combobox
|
||
items={companyIDs}
|
||
itemToStringValue={(companyID) => {
|
||
const company = companiesByID.get(companyID);
|
||
return company ? `${company.name} ${companyScopeSummary(company)}` : companyID;
|
||
}}
|
||
multiple
|
||
value={selectedIDs}
|
||
onValueChange={(next) => onValueChange(next.map(Number).filter(Number.isFinite))}
|
||
>
|
||
<ComboboxChips>
|
||
<ComboboxValue>
|
||
{selectedIDs.map((companyID) => (
|
||
<ComboboxChip key={companyID}>{companiesByID.get(companyID)?.name ?? t("Company #{id}", { id: companyID })}</ComboboxChip>
|
||
))}
|
||
</ComboboxValue>
|
||
<ComboboxChipsInput id="task-companies" placeholder={t("Search company name or asset scope")} />
|
||
</ComboboxChips>
|
||
<ComboboxContent portalContainer={portalContainer}>
|
||
<ComboboxEmpty>{t("No matching companies")}</ComboboxEmpty>
|
||
<ComboboxList>
|
||
{(companyID) => {
|
||
const company = companiesByID.get(companyID);
|
||
return (
|
||
<ComboboxItem key={companyID} value={companyID}>
|
||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||
<div className="flex min-w-0 items-center gap-2">
|
||
<span className="min-w-0 flex-1 truncate font-medium">{company?.name ?? t("Company #{id}", { id: companyID })}</span>
|
||
<span className="text-muted-foreground shrink-0 text-xs tabular-nums">
|
||
{t("{count} assets", { count: company?.asset_count ?? 0 })}
|
||
</span>
|
||
</div>
|
||
{company && (
|
||
<span className="text-muted-foreground truncate text-xs" title={companyScopeSummary(company)}>
|
||
{companyScopeSummary(company)}
|
||
</span>
|
||
)}
|
||
</div>
|
||
</ComboboxItem>
|
||
);
|
||
}}
|
||
</ComboboxList>
|
||
</ComboboxContent>
|
||
</Combobox>
|
||
);
|
||
}
|
||
|
||
type CategoryManagementView = number | "uncategorized" | "new";
|
||
|
||
function CategoryDropTarget({
|
||
value,
|
||
name,
|
||
count,
|
||
selected,
|
||
disabled,
|
||
onSelect,
|
||
}: {
|
||
value: string;
|
||
name: string;
|
||
count: number;
|
||
selected: boolean;
|
||
disabled: boolean;
|
||
onSelect: () => void;
|
||
}) {
|
||
const { isOver, setNodeRef } = useDroppable({ id: `category:${value}`, disabled });
|
||
|
||
return (
|
||
<button
|
||
ref={setNodeRef}
|
||
type="button"
|
||
className={cn(
|
||
"min-w-0 rounded-md border border-transparent px-2.5 py-2 text-left transition-colors",
|
||
selected ? "bg-accent text-accent-foreground" : "hover:bg-accent/50",
|
||
isOver && "border-primary bg-primary/10 text-foreground",
|
||
)}
|
||
onClick={onSelect}
|
||
>
|
||
<span className="block truncate font-medium text-sm">{name}</span>
|
||
<span className="block truncate text-muted-foreground text-xs">{isOver ? t("Release to move") : t("{count} tasks", { count })}</span>
|
||
</button>
|
||
);
|
||
}
|
||
|
||
function DraggableCategoryTask({ task, disabled, moving }: { task: Task; disabled: boolean; moving: boolean }) {
|
||
const { attributes, isDragging, listeners, setNodeRef } = useDraggable({
|
||
id: `task:${task.id}`,
|
||
disabled,
|
||
});
|
||
|
||
return (
|
||
<Item ref={setNodeRef} variant="outline" size="sm" className={cn(isDragging && "opacity-40")}>
|
||
<ItemMedia className="group-has-data-[slot=item-description]/item:self-center group-has-data-[slot=item-description]/item:translate-y-0">
|
||
{moving ? (
|
||
<Spinner />
|
||
) : (
|
||
<Button
|
||
type="button"
|
||
size="icon-xs"
|
||
variant="ghost"
|
||
className="touch-none cursor-grab active:cursor-grabbing"
|
||
disabled={disabled}
|
||
{...listeners}
|
||
{...attributes}
|
||
aria-label={t("Drag task #{id}", { id: task.id })}
|
||
title={t("Drag task")}
|
||
>
|
||
<GripVerticalIcon />
|
||
</Button>
|
||
)}
|
||
</ItemMedia>
|
||
<ItemContent className="min-w-0">
|
||
<ItemTitle className="w-full min-w-0">
|
||
<Link href={`/function/tasks/detail?id=${encodeURIComponent(task.id)}`} className="truncate hover:underline">
|
||
{task.name?.trim() || task.description || t("Task #{id}", { id: task.id })}
|
||
</Link>
|
||
</ItemTitle>
|
||
<ItemDescription className="line-clamp-1">
|
||
#{task.id} · {task.description}
|
||
</ItemDescription>
|
||
</ItemContent>
|
||
<ItemActions>
|
||
<StatusBadge domain="task" value={task.status} />
|
||
</ItemActions>
|
||
</Item>
|
||
);
|
||
}
|
||
|
||
function CategoryTaskDragPreview({ task }: { task: Task }) {
|
||
return (
|
||
<Item variant="outline" size="sm" className="w-80 bg-background shadow-lg">
|
||
<ItemMedia className="group-has-data-[slot=item-description]/item:self-center group-has-data-[slot=item-description]/item:translate-y-0">
|
||
<GripVerticalIcon className="size-4 text-muted-foreground" />
|
||
</ItemMedia>
|
||
<ItemContent className="min-w-0">
|
||
<ItemTitle className="w-full min-w-0 truncate">
|
||
{task.name?.trim() || task.description || t("Task #{id}", { id: task.id })}
|
||
</ItemTitle>
|
||
<ItemDescription className="line-clamp-1">#{task.id}</ItemDescription>
|
||
</ItemContent>
|
||
</Item>
|
||
);
|
||
}
|
||
|
||
function CategoryManagementSheet({
|
||
categories,
|
||
tasks,
|
||
onChanged,
|
||
onTaskMoved,
|
||
}: {
|
||
categories: TaskCategory[];
|
||
tasks: Task[];
|
||
onChanged: () => void;
|
||
onTaskMoved: (taskID: string, category: TaskCategory | null) => void;
|
||
}) {
|
||
const [open, setOpen] = React.useState(false);
|
||
const [selectedView, setSelectedView] = React.useState<CategoryManagementView>("new");
|
||
const [draftName, setDraftName] = React.useState("");
|
||
const [saving, setSaving] = React.useState(false);
|
||
const [deleteOpen, setDeleteOpen] = React.useState(false);
|
||
const [deleting, setDeleting] = React.useState(false);
|
||
const [movingTaskID, setMovingTaskID] = React.useState<string | null>(null);
|
||
const [activeTaskID, setActiveTaskID] = React.useState<string | null>(null);
|
||
const wasOpen = React.useRef(false);
|
||
const sensors = useSensors(
|
||
useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
|
||
useSensor(KeyboardSensor),
|
||
);
|
||
|
||
React.useEffect(() => {
|
||
if (open && !wasOpen.current) {
|
||
const first = categories[0];
|
||
if (first) {
|
||
setSelectedView(first.id);
|
||
setDraftName(first.name);
|
||
} else if (tasks.some((task) => task.category_id == null)) {
|
||
setSelectedView("uncategorized");
|
||
setDraftName("");
|
||
} else {
|
||
setSelectedView("new");
|
||
setDraftName("");
|
||
}
|
||
}
|
||
wasOpen.current = open;
|
||
}, [categories, open, tasks]);
|
||
|
||
const selectedCategory = React.useMemo(
|
||
() =>
|
||
typeof selectedView === "number" ? (categories.find((category) => category.id === selectedView) ?? null) : null,
|
||
[categories, selectedView],
|
||
);
|
||
|
||
const uncategorizedCount = React.useMemo(() => tasks.filter((task) => task.category_id == null).length, [tasks]);
|
||
|
||
const visibleTasks = React.useMemo(() => {
|
||
if (selectedView === "uncategorized") return tasks.filter((task) => task.category_id == null);
|
||
if (typeof selectedView === "number") return tasks.filter((task) => task.category_id === selectedView);
|
||
return [];
|
||
}, [selectedView, tasks]);
|
||
|
||
const activeTask = React.useMemo(() => tasks.find((task) => task.id === activeTaskID) ?? null, [activeTaskID, tasks]);
|
||
|
||
const selectCategory = (category: TaskCategory) => {
|
||
setSelectedView(category.id);
|
||
setDraftName(category.name);
|
||
};
|
||
|
||
const selectUncategorized = () => {
|
||
setSelectedView("uncategorized");
|
||
setDraftName("");
|
||
};
|
||
|
||
const startNew = () => {
|
||
setSelectedView("new");
|
||
setDraftName("");
|
||
};
|
||
|
||
async function saveCategory() {
|
||
const name = draftName.trim();
|
||
if (!name || saving || selectedView === "uncategorized") return;
|
||
setSaving(true);
|
||
try {
|
||
if (selectedView === "new") {
|
||
const created = await api.createTaskCategory(name);
|
||
setSelectedView(created.id);
|
||
setDraftName(created.name);
|
||
toast.success(t("Category created"));
|
||
} else {
|
||
const updated = await api.renameTaskCategory(selectedView, name);
|
||
setDraftName(updated.name);
|
||
toast.success(t("Category updated"));
|
||
}
|
||
onChanged();
|
||
} catch (error) {
|
||
toast.error(
|
||
selectedView === "new"
|
||
? t("Failed to create category: {error}", { error: (error as Error).message })
|
||
: t("Failed to update category: {error}", { error: (error as Error).message }),
|
||
);
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
}
|
||
|
||
async function deleteCategory() {
|
||
if (!selectedCategory || deleting) return;
|
||
const deletedID = selectedCategory.id;
|
||
setDeleting(true);
|
||
try {
|
||
await api.deleteTaskCategory(deletedID);
|
||
const next = categories.find((category) => category.id !== deletedID);
|
||
if (next) selectCategory(next);
|
||
else selectUncategorized();
|
||
toast.success(t("Category deleted; its tasks moved to Uncategorized"));
|
||
setDeleteOpen(false);
|
||
onChanged();
|
||
} catch (error) {
|
||
toast.error(t("Failed to delete category: {error}", { error: (error as Error).message }));
|
||
} finally {
|
||
setDeleting(false);
|
||
}
|
||
}
|
||
|
||
async function moveTask(task: Task, destination: string) {
|
||
if (movingTaskID) return;
|
||
const category =
|
||
destination === "uncategorized" ? null : (categories.find((item) => item.id === Number(destination)) ?? null);
|
||
if (destination !== "uncategorized" && !category) {
|
||
toast.error(t("Target category does not exist; refresh and try again"));
|
||
return;
|
||
}
|
||
if (task.category_id === category?.id || (task.category_id == null && category == null)) return;
|
||
|
||
setMovingTaskID(task.id);
|
||
try {
|
||
await api.updateTaskCategory(task.id, category?.id);
|
||
onTaskMoved(task.id, category);
|
||
toast.success(t("Task #{id} moved to \"{category}\"", { id: task.id, category: category?.name ?? t("Uncategorized") }));
|
||
} catch (error) {
|
||
toast.error(t("Failed to move task: {error}", { error: (error as Error).message }));
|
||
} finally {
|
||
setMovingTaskID(null);
|
||
}
|
||
}
|
||
|
||
function handleDragStart(event: DragStartEvent) {
|
||
const id = String(event.active.id);
|
||
setActiveTaskID(id.startsWith("task:") ? id.slice("task:".length) : null);
|
||
}
|
||
|
||
function handleDragEnd(event: DragEndEvent) {
|
||
const activeID = String(event.active.id);
|
||
const taskID = activeID.startsWith("task:") ? activeID.slice("task:".length) : null;
|
||
setActiveTaskID(null);
|
||
if (!taskID || !event.over) return;
|
||
const destination = String(event.over.id);
|
||
if (!destination.startsWith("category:")) return;
|
||
const task = tasks.find((item) => item.id === taskID);
|
||
if (!task) return;
|
||
void moveTask(task, destination.slice("category:".length));
|
||
}
|
||
|
||
const saveLabel = saving ? t("Saving") : selectedView === "new" ? t("Create category") : t("Save changes");
|
||
|
||
return (
|
||
<>
|
||
<Sheet open={open} onOpenChange={setOpen}>
|
||
<SheetTrigger asChild>
|
||
<Button size="sm" variant="outline">
|
||
<TagsIcon data-icon="inline-start" />
|
||
{t("Category management")}
|
||
</Button>
|
||
</SheetTrigger>
|
||
<SheetContent className="grid h-full w-full! max-w-none! grid-rows-[auto_minmax(0,1fr)_auto] gap-0 overflow-hidden p-0 sm:w-[48rem]! sm:max-w-[48rem]!">
|
||
<SheetHeader className="border-b px-6 py-5">
|
||
<SheetTitle>{t("Task category management")}</SheetTitle>
|
||
<SheetDescription>
|
||
{t(
|
||
"Categories are used for task filtering and archiving; edits never affect task execution, and deletion moves tasks to Uncategorized.",
|
||
)}
|
||
</SheetDescription>
|
||
</SheetHeader>
|
||
<DndContext
|
||
sensors={sensors}
|
||
onDragStart={handleDragStart}
|
||
onDragCancel={() => setActiveTaskID(null)}
|
||
onDragEnd={handleDragEnd}
|
||
>
|
||
<div className="grid min-h-0 overflow-y-auto lg:grid-cols-[15rem_minmax(0,1fr)] lg:overflow-hidden">
|
||
<div className="flex min-h-0 flex-col border-b p-3 lg:border-r lg:border-b-0">
|
||
<Button type="button" variant="outline" className="w-full" onClick={startNew}>
|
||
<PlusIcon data-icon="inline-start" />
|
||
{t("New category")}
|
||
</Button>
|
||
<ScrollArea className="mt-2 max-h-44 lg:max-h-none lg:flex-1">
|
||
<div className="flex flex-col gap-1 pr-2">
|
||
<CategoryDropTarget
|
||
value="uncategorized"
|
||
name={t("Uncategorized")}
|
||
count={uncategorizedCount}
|
||
selected={selectedView === "uncategorized"}
|
||
disabled={movingTaskID != null}
|
||
onSelect={selectUncategorized}
|
||
/>
|
||
{categories.map((category) => (
|
||
<CategoryDropTarget
|
||
key={category.id}
|
||
value={String(category.id)}
|
||
name={category.name}
|
||
count={category.task_count}
|
||
selected={selectedView === category.id}
|
||
disabled={movingTaskID != null}
|
||
onSelect={() => selectCategory(category)}
|
||
/>
|
||
))}
|
||
</div>
|
||
</ScrollArea>
|
||
</div>
|
||
<ScrollArea className="min-h-0">
|
||
<FieldGroup className="p-6">
|
||
{selectedView !== "uncategorized" && (
|
||
<Field>
|
||
<FieldLabel htmlFor="task-category-name">{t("Category name")}</FieldLabel>
|
||
<Input
|
||
id="task-category-name"
|
||
value={draftName}
|
||
onChange={(event) => setDraftName(event.target.value)}
|
||
placeholder={t("e.g. External assessment")}
|
||
maxLength={80}
|
||
onKeyDown={(event) => {
|
||
if (event.key === "Enter") void saveCategory();
|
||
}}
|
||
/>
|
||
<FieldDescription>
|
||
{selectedCategory
|
||
? t("{count} tasks currently use this category. Renaming updates the task list accordingly.", {
|
||
count: selectedCategory.task_count,
|
||
})
|
||
: t("Once created, it is usable in the create-task form and task list filters.")}
|
||
</FieldDescription>
|
||
</Field>
|
||
)}
|
||
{selectedView !== "new" && (
|
||
<Field>
|
||
<div className="flex flex-wrap items-end justify-between gap-2">
|
||
<div className="flex min-w-0 flex-col gap-1">
|
||
<FieldLabel>{selectedCategory ? t("Category tasks") : t("Uncategorized tasks")}</FieldLabel>
|
||
<FieldDescription>
|
||
{selectedCategory
|
||
? t("This category contains {count} tasks.", { count: visibleTasks.length })
|
||
: t("{count} tasks are not yet categorized.", { count: visibleTasks.length })}
|
||
</FieldDescription>
|
||
</div>
|
||
</div>
|
||
{visibleTasks.length === 0 ? (
|
||
<Empty className="min-h-36 border">
|
||
<EmptyHeader>
|
||
<EmptyTitle>{selectedCategory ? t("No tasks in this category") : t("No uncategorized tasks")}</EmptyTitle>
|
||
<EmptyDescription>{t("Content appears here once tasks are assigned.")}</EmptyDescription>
|
||
</EmptyHeader>
|
||
</Empty>
|
||
) : (
|
||
<ItemGroup className="gap-2">
|
||
{visibleTasks.map((task) => (
|
||
<DraggableCategoryTask
|
||
key={task.id}
|
||
task={task}
|
||
moving={movingTaskID === task.id}
|
||
disabled={movingTaskID != null}
|
||
/>
|
||
))}
|
||
</ItemGroup>
|
||
)}
|
||
</Field>
|
||
)}
|
||
</FieldGroup>
|
||
</ScrollArea>
|
||
</div>
|
||
<DragOverlay>{activeTask ? <CategoryTaskDragPreview task={activeTask} /> : null}</DragOverlay>
|
||
</DndContext>
|
||
<SheetFooter className="border-t px-6 py-4 sm:flex-row sm:items-center">
|
||
{selectedCategory && (
|
||
<Button
|
||
type="button"
|
||
variant="destructive"
|
||
className="sm:mr-auto"
|
||
disabled={saving || deleting}
|
||
onClick={() => setDeleteOpen(true)}
|
||
>
|
||
<Trash2Icon data-icon="inline-start" />
|
||
{t("Delete category")}
|
||
</Button>
|
||
)}
|
||
<Button type="button" variant="outline" onClick={() => setOpen(false)}>
|
||
{t("Close")}
|
||
</Button>
|
||
{selectedView !== "uncategorized" && (
|
||
<Button
|
||
type="button"
|
||
disabled={!draftName.trim() || saving || deleting}
|
||
onClick={() => void saveCategory()}
|
||
>
|
||
{saving ? <Spinner data-icon="inline-start" /> : <SaveIcon data-icon="inline-start" />}
|
||
{saveLabel}
|
||
</Button>
|
||
)}
|
||
</SheetFooter>
|
||
</SheetContent>
|
||
</Sheet>
|
||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||
<AlertDialogContent>
|
||
<AlertDialogHeader>
|
||
<AlertDialogTitle>
|
||
{t("Delete category \"{name}\"?", { name: selectedCategory?.name || t("Unnamed category") })}
|
||
</AlertDialogTitle>
|
||
<AlertDialogDescription>
|
||
{t(
|
||
"After the category is deleted, its {count} tasks move to \"Uncategorized\" automatically; task data is not deleted.",
|
||
{ count: selectedCategory?.task_count ?? 0 },
|
||
)}
|
||
</AlertDialogDescription>
|
||
</AlertDialogHeader>
|
||
<AlertDialogFooter>
|
||
<AlertDialogCancel disabled={deleting}>{t("Cancel")}</AlertDialogCancel>
|
||
<AlertDialogAction
|
||
variant="destructive"
|
||
disabled={deleting}
|
||
onClick={(event) => {
|
||
event.preventDefault();
|
||
void deleteCategory();
|
||
}}
|
||
>
|
||
{deleting && <Spinner data-icon="inline-start" />}
|
||
{deleting ? t("Deleting") : t("Delete")}
|
||
</AlertDialogAction>
|
||
</AlertDialogFooter>
|
||
</AlertDialogContent>
|
||
</AlertDialog>
|
||
</>
|
||
);
|
||
}
|
||
|
||
function CreateTaskSheet({
|
||
tasks,
|
||
categories,
|
||
onCreated,
|
||
onCategoriesChanged,
|
||
}: {
|
||
tasks: Task[];
|
||
categories: TaskCategory[];
|
||
onCreated: () => void;
|
||
onCategoriesChanged: () => void;
|
||
}) {
|
||
const [open, setOpen] = React.useState(false);
|
||
const [name, setName] = React.useState("");
|
||
const [categoryID, setCategoryID] = React.useState<number | undefined>(undefined);
|
||
const [description, setDescription] = React.useState("");
|
||
const [goal, setGoal] = React.useState("");
|
||
const [selectedTemplateID, setSelectedTemplateID] = React.useState<number | null>(null);
|
||
const [profiles, setProfiles] = React.useState<LLMProfile[]>([]);
|
||
const [companies, setCompanies] = React.useState<Company[]>([]);
|
||
const [sourceTaskIDs, setSourceTaskIDs] = React.useState<string[]>([]);
|
||
const [companyIDs, setCompanyIDs] = React.useState<number[]>([]);
|
||
const [llmProfileIDs, setLLMProfileIDs] = React.useState<string[]>([]);
|
||
const [llmRotate, setLLMRotate] = React.useState(false);
|
||
const [creating, setCreating] = React.useState(false);
|
||
const [timeoutMin, setTimeoutMin] = React.useState(""); // task-level timeout (minutes); empty/0 = no limit
|
||
const [heartbeatMin, setHeartbeatMin] = React.useState("10"); // planner heartbeat (minutes); default 10, minimum 10 (matching the backend)
|
||
const [seedFirstIntent, setSeedFirstIntent] = React.useState(false); // dispatch a seed intent at creation so the worker starts without waiting for the first planner round; off by default, standard plan-then-execute
|
||
const [coverageEnabled, setCoverageEnabled] = React.useState(true); // asset coverage feature; on by default. Off = no coverage computed/displayed, no scope accumulation, scope-related tools hidden (company links unaffected)
|
||
const [interceptRules, setInterceptRules] = React.useState<AssetInterceptRuleInput[]>([]); // task-level asset intercept rules (this task only, never entering the global table)
|
||
const [credentials, setCredentials] = React.useState<TaskCredentialInput[]>([]); // test accounts declared at creation (#3); an empty password = the agent registers that account and records it
|
||
// Method 1, file upload: files are staged under drafts/<draftId>/uploads/ before the task is created, and their absolute paths are appended to the description.
|
||
const [uploading, setUploading] = React.useState(false);
|
||
const [uploadCount, setUploadCount] = React.useState(0);
|
||
const draftIdRef = React.useRef<string>("");
|
||
const fileInputRef = React.useRef<HTMLInputElement>(null);
|
||
const sheetContentRef = React.useRef<HTMLDivElement>(null);
|
||
|
||
// load LLM profiles once for the create-task profile picker.
|
||
React.useEffect(() => {
|
||
api
|
||
.llmProfiles()
|
||
.then(setProfiles)
|
||
.catch(() => setProfiles([]));
|
||
api
|
||
.companies()
|
||
.then(setCompanies)
|
||
.catch(() => setCompanies([]));
|
||
}, []);
|
||
|
||
// pickFiles uploads the chosen files into this draft's staging dir and appends their
|
||
// absolute paths to the description; the task's agents open them by path via Read/Bash.
|
||
async function pickFiles(files: FileList | null) {
|
||
if (!files || files.length === 0) return;
|
||
// crypto.randomUUID is only available in secure contexts (https/localhost); degrade when accessed via IP+http.
|
||
if (!draftIdRef.current) {
|
||
draftIdRef.current =
|
||
globalThis.crypto?.randomUUID?.() ?? `d${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`;
|
||
}
|
||
setUploading(true);
|
||
try {
|
||
const r = await api.chatUpload("staging", draftIdRef.current, Array.from(files));
|
||
setDescription((prev) => appendUploads(prev, r.attachments));
|
||
setUploadCount((n) => n + r.attachments.length);
|
||
} catch (e) {
|
||
toast.error(t("Upload failed: {error}", { error: (e as Error).message }));
|
||
} finally {
|
||
setUploading(false);
|
||
if (fileInputRef.current) fileInputRef.current.value = ""; // allow re-picking the same file
|
||
}
|
||
}
|
||
|
||
async function createTask() {
|
||
if (!description.trim() || !goal.trim()) {
|
||
toast.error(t("Please fill in the description and goal"));
|
||
return;
|
||
}
|
||
if (sourceTaskIDs.length > MAX_SOURCE_TASKS) {
|
||
toast.error(t("Link up to {count} source tasks", { count: MAX_SOURCE_TASKS }));
|
||
return;
|
||
}
|
||
setCreating(true);
|
||
try {
|
||
const timeoutSec = Math.max(0, Math.floor(Number(timeoutMin) || 0)) * 60;
|
||
const heartbeatSec = Math.max(10, Math.floor(Number(heartbeatMin) || 10)) * 60; // minimum 10min, matching the backend's normalization
|
||
await api.createTask({
|
||
name: name.trim(),
|
||
categoryId: categoryID,
|
||
description: description.trim(),
|
||
goal: goal.trim(),
|
||
llmProfileIds: llmProfileIDs.map(Number),
|
||
llmRotate,
|
||
sourceTaskIds: sourceTaskIDs,
|
||
companyIds: companyIDs,
|
||
timeoutSeconds: timeoutSec,
|
||
seedFirstIntent,
|
||
planHeartbeatSeconds: heartbeatSec,
|
||
coverageEnabled,
|
||
interceptRules: interceptRules
|
||
.map((r) => ({ ...r, pattern: r.pattern.trim() }))
|
||
.filter((r) => r.pattern !== ""),
|
||
credentials: credentials
|
||
.map((c) => ({ domain: c.domain.trim(), username: c.username.trim(), password: c.password, note: c.note?.trim() ?? "" }))
|
||
.filter((c) => c.domain !== "" && c.username !== ""),
|
||
});
|
||
toast.success(t("Task created"));
|
||
setName("");
|
||
setCategoryID(undefined);
|
||
setDescription("");
|
||
setGoal("");
|
||
setSelectedTemplateID(null);
|
||
setSourceTaskIDs([]);
|
||
setCompanyIDs([]);
|
||
setLLMProfileIDs([]);
|
||
setLLMRotate(false);
|
||
setTimeoutMin("");
|
||
setHeartbeatMin("10");
|
||
setSeedFirstIntent(false);
|
||
setCoverageEnabled(true);
|
||
setInterceptRules([]);
|
||
setUploadCount(0);
|
||
draftIdRef.current = "";
|
||
setOpen(false);
|
||
onCreated();
|
||
} catch (e) {
|
||
toast.error(t("Create failed: {error}", { error: (e as Error).message }));
|
||
} finally {
|
||
setCreating(false);
|
||
}
|
||
}
|
||
|
||
return (
|
||
<Sheet open={open} onOpenChange={setOpen}>
|
||
<SheetTrigger asChild>
|
||
<Button size="sm">
|
||
<PlusIcon /> {t("New task")}
|
||
</Button>
|
||
</SheetTrigger>
|
||
{/* A 45vw-wide right drawer: full-height and scrollable, so long forms are no longer bound by dialog height. Narrow screens fall back to full width.
|
||
The content is a flex column: header/footer fixed, the middle field area flex-1 scrolling independently. */}
|
||
<SheetContent
|
||
ref={sheetContentRef}
|
||
side="right"
|
||
className="w-full! max-w-none! gap-0 p-0 sm:w-[45vw]! sm:max-w-[45vw]!"
|
||
>
|
||
<SheetHeader className="border-b p-6">
|
||
<SheetTitle>{t("New task")}</SheetTitle>
|
||
<SheetDescription>{t("Fill in the test target and goal; advanced parameters can be expanded as needed.")}</SheetDescription>
|
||
</SheetHeader>
|
||
|
||
<div className="flex-1 overflow-y-auto p-6">
|
||
<div className="grid gap-5">
|
||
<TaskTemplateControls
|
||
description={description}
|
||
goal={goal}
|
||
categoryID={categoryID}
|
||
interceptRules={interceptRules}
|
||
selectedTemplateID={selectedTemplateID}
|
||
onSelectedTemplateIDChange={setSelectedTemplateID}
|
||
onApply={(template) => {
|
||
setDescription(template.description);
|
||
setGoal(template.goal);
|
||
setCategoryID(template.category_id ?? undefined);
|
||
setInterceptRules(template.intercept_rules ?? []);
|
||
setUploadCount(0);
|
||
}}
|
||
portalContainer={sheetContentRef}
|
||
/>
|
||
<div className="grid gap-2">
|
||
<Label htmlFor="name">{t("Name (optional)")}</Label>
|
||
<Input
|
||
id="name"
|
||
placeholder={t("A recognizable name for the task, e.g. Acme website penetration test")}
|
||
value={name}
|
||
onChange={(e) => setName(e.target.value)}
|
||
/>
|
||
</div>
|
||
<Field>
|
||
<FieldLabel htmlFor="task-category">{t("Task category")}</FieldLabel>
|
||
<CategoryPicker
|
||
categories={categories}
|
||
value={categoryID}
|
||
onValueChange={setCategoryID}
|
||
onCategoryCreated={onCategoriesChanged}
|
||
portalContainer={sheetContentRef}
|
||
/>
|
||
<FieldDescription>{t("Optional, single category; used for task list filtering and archiving, never affecting agent execution.")}</FieldDescription>
|
||
</Field>
|
||
<div className="grid gap-2">
|
||
<Label htmlFor="description">{t("Description")}</Label>
|
||
<Textarea
|
||
id="description"
|
||
className="min-h-32"
|
||
placeholder={t("Test target and background, e.g. test the example.com site")}
|
||
value={description}
|
||
onChange={(e) => setDescription(e.target.value)}
|
||
/>
|
||
{/* Upload files (multi-select): staged under drafts/, with absolute paths appended to the description above so the worker can open them with Read/Bash. */}
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<input
|
||
ref={fileInputRef}
|
||
type="file"
|
||
multiple
|
||
className="hidden"
|
||
onChange={(e) => void pickFiles(e.target.files)}
|
||
/>
|
||
<Button
|
||
type="button"
|
||
variant="outline"
|
||
size="sm"
|
||
onClick={() => fileInputRef.current?.click()}
|
||
disabled={uploading}
|
||
>
|
||
{uploading ? <Loader2Icon className="animate-spin" /> : <PaperclipIcon />}
|
||
{t("Upload files")}
|
||
</Button>
|
||
<span className="text-muted-foreground text-xs">
|
||
{uploadCount > 0
|
||
? t("{count} files uploaded; their absolute paths were appended to the end of the description (editable)", {
|
||
count: uploadCount,
|
||
})
|
||
: t("Multi-select; after upload, absolute file paths are appended to the description for the worker to open with Read/Bash")}
|
||
</span>
|
||
</div>
|
||
</div>
|
||
<div className="grid gap-2">
|
||
<Label htmlFor="goal">{t("Goal")}</Label>
|
||
<Textarea
|
||
id="goal"
|
||
className="min-h-32"
|
||
placeholder={t("What to achieve, e.g. gain admin panel access or server privileges")}
|
||
value={goal}
|
||
onChange={(e) => setGoal(e.target.value)}
|
||
/>
|
||
</div>
|
||
<Field>
|
||
<FieldLabel htmlFor="source-tasks">{t("Linked tasks")}</FieldLabel>
|
||
<SourceTaskPicker
|
||
tasks={tasks}
|
||
value={sourceTaskIDs}
|
||
onValueChange={setSourceTaskIDs}
|
||
portalContainer={sheetContentRef}
|
||
/>
|
||
<FieldDescription>
|
||
{t(
|
||
"Link up to {count} tasks. Live, read-only inheritance of the selected tasks' persistent blackboards, asset scope, and related traffic; the new task writes to its own blackboard.",
|
||
{ count: MAX_SOURCE_TASKS },
|
||
)}
|
||
</FieldDescription>
|
||
</Field>
|
||
<Field>
|
||
<FieldLabel htmlFor="task-companies">{t("Linked company asset scope")}</FieldLabel>
|
||
<CompanyPicker
|
||
companies={companies}
|
||
value={companyIDs}
|
||
onValueChange={setCompanyIDs}
|
||
portalContainer={sheetContentRef}
|
||
/>
|
||
<FieldDescription>
|
||
{t(
|
||
"On task creation, the selected companies' current assets are added to \"Test assets\", and their domains, IPs, CIDRs, ICPs, and company keywords are provided to the agent as scope context; no intents are generated automatically and execution goals are not forced to change.",
|
||
)}
|
||
</FieldDescription>
|
||
</Field>
|
||
<Field>
|
||
<FieldLabel htmlFor="task-intercept-rules">{t("Task-level asset intercept / allow rules (optional)")}</FieldLabel>
|
||
<AssetInterceptRulesEditor value={interceptRules} onChange={setInterceptRules} />
|
||
<FieldDescription>
|
||
{t(
|
||
"Applies to this task only and is not written to global rules. Evaluation order: \"Block\" rules (including global ones) match first, and a hit forbids testing; with no hit and \"Allow\" rules configured for this task, an asset must match an allow rule to be permitted, otherwise testing is likewise forbidden; with no allow rules configured, no whitelist is active.",
|
||
)}
|
||
</FieldDescription>
|
||
</Field>
|
||
<Field>
|
||
<FieldLabel htmlFor="llm-profiles">{t("LLM config chain")}</FieldLabel>
|
||
<TaskLLMProfileChain
|
||
profiles={profiles}
|
||
value={llmProfileIDs}
|
||
rotate={llmRotate}
|
||
onRotateChange={setLLMRotate}
|
||
onValueChange={setLLMProfileIDs}
|
||
inputId="llm-profiles"
|
||
portalContainer={sheetContentRef}
|
||
/>
|
||
<FieldDescription>
|
||
{t("Reorder profiles to choose worker rotation order or failover priority. Saving the chain resets exhausted profiles.")}
|
||
</FieldDescription>
|
||
</Field>
|
||
<Field>
|
||
<FieldLabel htmlFor="task-credentials">{t("Test accounts (optional)")}</FieldLabel>
|
||
<div className="grid gap-2">
|
||
{credentials.map((c, i) => (
|
||
<div key={i} className="grid gap-2 sm:grid-cols-[1fr_1fr_1fr_auto]">
|
||
<Input
|
||
placeholder={t("domain (e.g. target.example.com)")}
|
||
value={c.domain}
|
||
onChange={(e) => setCredentials((prev) => prev.map((x, j) => (j === i ? { ...x, domain: e.target.value } : x)))}
|
||
/>
|
||
<Input
|
||
placeholder={t("email or username")}
|
||
value={c.username}
|
||
onChange={(e) => setCredentials((prev) => prev.map((x, j) => (j === i ? { ...x, username: e.target.value } : x)))}
|
||
/>
|
||
<Input
|
||
placeholder={t("password (empty = agent generates)")}
|
||
value={c.password}
|
||
onChange={(e) => setCredentials((prev) => prev.map((x, j) => (j === i ? { ...x, password: e.target.value } : x)))}
|
||
/>
|
||
<Button
|
||
type="button"
|
||
variant="ghost"
|
||
size="icon"
|
||
aria-label={t("Remove account")}
|
||
onClick={() => setCredentials((prev) => prev.filter((_, j) => j !== i))}
|
||
>
|
||
<TrashIcon />
|
||
</Button>
|
||
<Input
|
||
className="sm:col-span-4"
|
||
placeholder={t("note (optional, e.g. program alias account)")}
|
||
value={c.note ?? ""}
|
||
onChange={(e) => setCredentials((prev) => prev.map((x, j) => (j === i ? { ...x, note: e.target.value } : x)))}
|
||
/>
|
||
</div>
|
||
))}
|
||
<Button
|
||
type="button"
|
||
size="sm"
|
||
variant="outline"
|
||
className="w-fit"
|
||
onClick={() => setCredentials((prev) => [...prev, { domain: "", username: "", password: "", note: "" }])}
|
||
>
|
||
<PlusIcon className="size-4" /> {t("Add account")}
|
||
</Button>
|
||
</div>
|
||
<FieldDescription>
|
||
{t(
|
||
"Test accounts reused by the agent for authenticated testing. Leave the password empty to have the agent register that account itself and record the password it chose. Use dedicated test accounts only — anything declared here is sent to the configured LLM provider during the task.",
|
||
)}
|
||
</FieldDescription>
|
||
</Field>
|
||
|
||
{/* Advanced parameters are collapsed by default: timeout/heartbeat/first intent; they take space only when expanded, keeping the common path clean. */}
|
||
<Collapsible>
|
||
<CollapsibleTrigger className="group flex w-full items-center gap-2 border-t pt-4 text-sm font-medium">
|
||
<ChevronRightIcon className="text-muted-foreground size-4 transition-transform group-data-[state=open]:rotate-90" />
|
||
{t("Advanced settings")}
|
||
<span className="text-muted-foreground ml-auto text-xs font-normal">{t("Timeout · Heartbeat · First intent")}</span>
|
||
</CollapsibleTrigger>
|
||
<CollapsibleContent className="grid gap-5 pt-5">
|
||
<div className="grid gap-2">
|
||
<Label htmlFor="timeout-min">{t("Task timeout (minutes, optional)")}</Label>
|
||
<Input
|
||
id="timeout-min"
|
||
type="number"
|
||
min={0}
|
||
className="w-40"
|
||
placeholder={t("Empty = no limit")}
|
||
value={timeoutMin}
|
||
onChange={(e) => setTimeoutMin(e.target.value)}
|
||
/>
|
||
<p className="text-muted-foreground text-xs">
|
||
{t(
|
||
"When the time is up, a graceful wind-down is triggered (each agent writes back + the planner makes the final verdict) and the task enters the timeout terminal state.",
|
||
)}
|
||
</p>
|
||
</div>
|
||
<div className="grid gap-2">
|
||
<Label htmlFor="heartbeat-min">{t("planner heartbeat (minutes)")}</Label>
|
||
<Input
|
||
id="heartbeat-min"
|
||
type="number"
|
||
min={10}
|
||
className="w-40"
|
||
placeholder={t("Default 10")}
|
||
value={heartbeatMin}
|
||
onChange={(e) => setHeartbeatMin(e.target.value)}
|
||
/>
|
||
<p className="text-muted-foreground text-xs">
|
||
{t(
|
||
"When this much time has passed since the last planning round ended or the task started, with no triggers in between, a planning round fires automatically (deadlock backstop + wakes supervision of running workers). Minimum 10 minutes.",
|
||
)}
|
||
</p>
|
||
</div>
|
||
<div className="grid gap-2">
|
||
<label htmlFor="seed-first-intent" className="flex items-center gap-2 text-sm">
|
||
<Checkbox
|
||
id="seed-first-intent"
|
||
checked={seedFirstIntent}
|
||
onCheckedChange={(v) => setSeedFirstIntent(!!v)}
|
||
/>
|
||
{t("Dispatch the first intent directly (description + goal)")}
|
||
</label>
|
||
<p className="text-muted-foreground text-xs">
|
||
{t(
|
||
"When enabled, the \"description + goal\" is dispatched as one intent right at creation; the worker starts without waiting for the first planning round and the planner takes over afterwards to judge/follow up. Recommended for settings like CTF where one run usually solves it directly; disabled follows the standard plan-then-execute flow.",
|
||
)}
|
||
</p>
|
||
</div>
|
||
<div className="grid gap-2">
|
||
<label htmlFor="coverage-enabled" className="flex items-center gap-2 text-sm">
|
||
<Checkbox
|
||
id="coverage-enabled"
|
||
checked={coverageEnabled}
|
||
onCheckedChange={(v) => setCoverageEnabled(!!v)}
|
||
/>
|
||
{t("Asset coverage feature")}
|
||
</label>
|
||
<p className="text-muted-foreground text-xs">
|
||
{t(
|
||
"On by default: computes and displays test coverage, shows testing progress on the situational graph, and automatically accumulates the test scope. When off, coverage is no longer computed or displayed, the situational graph shows assets without progress, and agents no longer receive scope-related tools. Disabling does not affect \"Linked company asset scope\".",
|
||
)}
|
||
</p>
|
||
</div>
|
||
</CollapsibleContent>
|
||
</Collapsible>
|
||
</div>
|
||
</div>
|
||
|
||
<SheetFooter className="flex-row justify-end gap-2 border-t p-4">
|
||
<SheetClose asChild>
|
||
<Button variant="outline">{t("Cancel")}</Button>
|
||
</SheetClose>
|
||
<Button onClick={createTask} disabled={creating || uploading}>
|
||
{creating && <Spinner data-icon="inline-start" />}
|
||
{creating ? t("Creating") : t("Create")}
|
||
</Button>
|
||
</SheetFooter>
|
||
</SheetContent>
|
||
</Sheet>
|
||
);
|
||
}
|