Skip to content

Automate browser based workflows with AI

feat(SKY-10971): revamp workflows/folders list into a directory tree (#6631)

Aaron Perezcb6854bc5ce8
diff --git a/skyvern-frontend/src/hooks/useWorkflowsDirectoryTree.ts b/skyvern-frontend/src/hooks/useWorkflowsDirectoryTree.ts
new file mode 100644
index 000000000..74bd51807
--- /dev/null
+++ b/skyvern-frontend/src/hooks/useWorkflowsDirectoryTree.ts
@@ -0,0 +1,10 @@
+import { useFeatureFlagEnabled } from "posthog-js/react";
+
+import { WORKFLOWS_DIRECTORY_TREE_FLAG } from "@/util/featureFlags";
+
+// Read client-side so the flag reflects per-user opt-in (a PostHog person
+// property) rather than the per-org server-evaluated path. Absent flag -> false,
+// which keeps the default flat folders/list experience.
+export function useWorkflowsDirectoryTree(): boolean {
+ return useFeatureFlagEnabled(WORKFLOWS_DIRECTORY_TREE_FLAG) ?? false;
+}
diff --git a/skyvern-frontend/src/routes/workflows/Workflows.test.tsx b/skyvern-frontend/src/routes/workflows/Workflows.test.tsx
new file mode 100644
index 000000000..fda71edd1
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/Workflows.test.tsx
@@ -0,0 +1,45 @@
+// @vitest-environment jsdom
+
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { Workflows } from "./Workflows";
+
+const useWorkflowsDirectoryTreeMock = vi.fn();
+
+vi.mock("@/hooks/useWorkflowsDirectoryTree", () => ({
+ useWorkflowsDirectoryTree: () => useWorkflowsDirectoryTreeMock(),
+}));
+
+vi.mock("./WorkflowsTree", () => ({
+ WorkflowsTree: () => <div data-testid="workflows-tree" />,
+}));
+
+vi.mock("./WorkflowsFlat", () => ({
+ WorkflowsFlat: () => <div data-testid="workflows-flat" />,
+}));
+
+describe("Workflows", () => {
+ afterEach(() => {
+ cleanup();
+ useWorkflowsDirectoryTreeMock.mockReset();
+ });
+
+ it("renders the flat folders/list when the directory-tree preview is off", () => {
+ useWorkflowsDirectoryTreeMock.mockReturnValue(false);
+
+ render(<Workflows />);
+
+ expect(screen.getByTestId("workflows-flat")).toBeTruthy();
+ expect(screen.queryByTestId("workflows-tree")).toBeNull();
+ });
+
+ it("renders the directory tree when the preview is opted in", () => {
+ useWorkflowsDirectoryTreeMock.mockReturnValue(true);
+
+ render(<Workflows />);
+
+ expect(screen.getByTestId("workflows-tree")).toBeTruthy();
+ expect(screen.queryByTestId("workflows-flat")).toBeNull();
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/Workflows.tsx b/skyvern-frontend/src/routes/workflows/Workflows.tsx
index 9f2d2c5c5..8a8513592 100644
--- a/skyvern-frontend/src/routes/workflows/Workflows.tsx
+++ b/skyvern-frontend/src/routes/workflows/Workflows.tsx
@@ -1,1346 +1,11 @@
-import { getClient } from "@/api/AxiosClient";
-import { GetStartedModal } from "@/components/onboarding/GetStartedModal";
-import { useOnboardingStateOptional } from "@/store/onboarding/useOnboardingState";
-import { OnboardingErrorBoundary } from "@/components/onboarding/OnboardingErrorBoundary";
-import { OnboardingTelemetry } from "@/util/onboarding/OnboardingTelemetry";
-import { Button } from "@/components/ui/button";
-import {
- SelectionCheckboxCell,
- SelectionHeaderCheckboxCell,
-} from "@/components/SelectionCheckbox";
-import { useRowSelection } from "@/hooks/useRowSelection";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import {
- Pagination,
- PaginationContent,
- PaginationItem,
- PaginationLink,
- PaginationNext,
- PaginationPrevious,
-} from "@/components/ui/pagination";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableMessageRow,
- TableRow,
-} from "@/components/ui/table";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/components/ui/tooltip";
-import { useCredentialGetter } from "@/hooks/useCredentialGetter";
-import { basicTimeFormat, compactLocalDateTime } from "@/util/timeFormat";
-import {
- BULK_CONCURRENCY_LIMIT,
- runWithConcurrency,
-} from "@/util/runWithConcurrency";
-import { bulkResultToast } from "@/util/bulkResultToast";
-import { cn } from "@/util/utils";
-import {
- BookmarkFilledIcon,
- ChevronDownIcon,
- DotsHorizontalIcon,
- LightningBoltIcon,
- Pencil2Icon,
- PlayIcon,
- PlusIcon,
- ReloadIcon,
-} from "@radix-ui/react-icons";
-import { FolderIcon } from "@/components/icons/FolderIcon";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
-import React, {
- useCallback,
- useEffect,
- useMemo,
- useRef,
- useState,
-} from "react";
-import { Link, useNavigate, useSearchParams } from "react-router-dom";
-import { useDebounce } from "use-debounce";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import { NarrativeCard } from "./components/header/NarrativeCard";
-import { BulkActionBar } from "./components/BulkActionBar";
-import { FolderCard } from "./components/FolderCard";
-import { CreateFolderDialog } from "./components/CreateFolderDialog";
-import { CreateFromTemplateDialog } from "./components/CreateFromTemplateDialog";
-import { ViewAllFoldersDialog } from "./components/ViewAllFoldersDialog";
-import { WorkflowFolderSelector } from "./components/WorkflowFolderSelector";
-import { HighlightText } from "./components/HighlightText";
-import { useCreateWorkflowMutation } from "./hooks/useCreateWorkflowMutation";
-import { useFoldersQuery } from "./hooks/useFoldersQuery";
-import { useTagKeysQuery } from "./hooks/useTagKeysQuery";
-import { useWorkflowTagsBatchQuery } from "./hooks/useWorkflowTagsBatchQuery";
-import { useActiveImportsPolling } from "./hooks/useActiveImportsPolling";
-import { TagChipList } from "./components/tagging/TagChipList";
-import { WorkflowTagFilter } from "./components/tagging/WorkflowTagFilter";
-import { WorkflowTagEditor } from "./components/tagging/WorkflowTagEditor";
-import {
- parseTagFilter,
- serializeTagFilter,
- type TagFilterTerm,
-} from "./types/tagTypes";
-import { ImportWorkflowButton } from "./ImportWorkflowButton";
-import { useNodeCollapseStore } from "./editor/collapse/useNodeCollapseStore";
-import { convert } from "./editor/workflowEditorUtils";
-import { WorkflowApiResponse } from "./types/workflowTypes";
-import { WorkflowActions } from "./WorkflowActions";
-import { WorkflowTemplates } from "../discover/WorkflowTemplates";
-import { Skeleton } from "@/components/ui/skeleton";
-import { TableSearchInput } from "@/components/TableSearchInput";
-import { ParameterDisplayInline } from "./components/ParameterDisplayInline";
-import { useKeywordSearch } from "./hooks/useKeywordSearch";
-import { useParameterExpansion } from "./hooks/useParameterExpansion";
-import { Folder } from "./types/folderTypes";
-import { defaultWorkflowRequest } from "./defaultWorkflowRequest";
+import { useWorkflowsDirectoryTree } from "@/hooks/useWorkflowsDirectoryTree";
-// Utility function to create URL-safe folder slugs from folder names
-function slugifyFolderName(name: string): string {
- return name
- .toLowerCase()
- .trim()
- .replace(/[^\w\s-]/g, "") // Remove special characters except spaces and hyphens
- .replace(/\s+/g, "-") // Replace spaces with hyphens
- .replace(/-+/g, "-") // Replace multiple hyphens with single hyphen
- .replace(/^-|-$/g, ""); // Remove leading/trailing hyphens
-}
-
-const FOLDERS_PAGE_SIZE = 10;
-
-// Generate a unique slug for a folder, appending a number suffix only if there's a collision
-function getUniqueSlugForFolder(folder: Folder, allFolders: Folder[]): string {
- const baseSlug = slugifyFolderName(folder.title);
-
- // Find all folders that would have the same base slug
- const foldersWithSameSlug = allFolders.filter(
- (f) => slugifyFolderName(f.title) === baseSlug,
- );
+import { WorkflowsFlat } from "./WorkflowsFlat";
+import { WorkflowsTree } from "./WorkflowsTree";
- // If no collision, return the base slug
- if (foldersWithSameSlug.length <= 1) {
- return baseSlug;
- }
-
- // Sort by created_at to ensure consistent numbering
- const sortedFolders = [...foldersWithSameSlug].sort(
- (a, b) =>
- new Date(a.created_at).getTime() - new Date(b.created_at).getTime(),
- );
-
- const index = sortedFolders.findIndex(
- (f) => f.folder_id === folder.folder_id,
- );
-
- // First folder (oldest) gets the base slug, others get numbered suffixes
- return index === 0 ? baseSlug : `${baseSlug}-${index + 1}`;
-}
function Workflows() {
- const credentialGetter = useCredentialGetter();
- const queryClient = useQueryClient();
- const navigate = useNavigate();
- const createWorkflowMutation = useCreateWorkflowMutation();
- const [searchParams, setSearchParams] = useSearchParams();
- const [search, setSearch] = useState("");
- const [debouncedSearch] = useDebounce(search, 250);
- const [isBulkOperating, setIsBulkOperating] = useState(false);
- const [bulkDeleteDialog, setBulkDeleteDialog] = useState<{
- open: boolean;
- targets: string[];
- }>({ open: false, targets: [] });
- const page = searchParams.get("page") ? Number(searchParams.get("page")) : 1;
- const itemsPerPage = searchParams.get("page_size")
- ? Number(searchParams.get("page_size"))
- : 10;
-
- // Folder slug from query param (e.g., /workflows?folder=my-folder-name)
- const folderSlug = searchParams.get("folder");
-
- // Tag filter from query param (e.g., /workflows?tags=env:prod,env:staging).
- // The backend accepts both comma-separated pairs and repeated `tags` params,
- // so read every occurrence. The serialized form is canonical (sorted) and is
- // used for both the request and the query key so cache hits are
- // order-independent.
- const tagFilterParam = searchParams.getAll("tags").join(",");
- const tagFilters = useMemo(
- () => parseTagFilter(tagFilterParam),
- [tagFilterParam],
- );
- const serializedTagFilter = serializeTagFilter(tagFilters);
-
- const setTagFilters = useCallback(
- (terms: TagFilterTerm[]) => {
- const params = new URLSearchParams(searchParams);
- const serialized = serializeTagFilter(terms);
- if (serialized) {
- params.set("tags", serialized);
- } else {
- params.delete("tags");
- }
- params.set("page", "1");
- setSearchParams(params, { replace: true });
- },
- [searchParams, setSearchParams],
- );
-
- const [isCreateFolderOpen, setIsCreateFolderOpen] = useState(false);
- const [isViewAllFoldersOpen, setIsViewAllFoldersOpen] = useState(false);
-
- // Template dialog state
- const [isTemplateDialogOpen, setIsTemplateDialogOpen] = useState(false);
-
- // Poll for active imports
- const { activeImports, startPolling } = useActiveImportsPolling();
-
- // Fetch folders
- const { data: allFolders = [], isLoading: isFoldersLoading } =
- useFoldersQuery({ page_size: FOLDERS_PAGE_SIZE });
-
- // Create a memoized map of slugs to folders to avoid O(n²) lookups
- const slugToFolderMap = useMemo(() => {
- const map = new Map<string, Folder>();
- for (const folder of allFolders) {
- const slug = getUniqueSlugForFolder(folder, allFolders);
- map.set(slug, folder);
- }
- return map;
- }, [allFolders]);
-
- // Folder state - derived from URL query param
- // Look up the folder by matching the slug (handles collision suffixes like my-folder-2)
- const resolvedFolderIdBySlug = useRef<Map<string, string>>(new Map());
- // A short list means we saw every folder, so a lookup miss is a real
- // deletion/rename rather than pagination dropping the active folder.
- const foldersListComplete =
- !isFoldersLoading && allFolders.length < FOLDERS_PAGE_SIZE;
- const selectedFolderId = useMemo(() => {
- if (!folderSlug) return null;
- const matchingFolder = slugToFolderMap.get(folderSlug);
- if (matchingFolder) {
- resolvedFolderIdBySlug.current.set(folderSlug, matchingFolder.folder_id);
- return matchingFolder.folder_id;
- }
- if (foldersListComplete) {
- resolvedFolderIdBySlug.current.delete(folderSlug);
- return null;
- }
- // The folders list is paginated, so a refetch can transiently drop the
- // active folder; reuse the last resolution instead of flapping to null.
- return resolvedFolderIdBySlug.current.get(folderSlug) ?? null;
- }, [folderSlug, slugToFolderMap, foldersListComplete]);
-
- // Clear folder param if the folder slug is invalid (folder deleted/renamed)
- // Only validate after folders have finished loading to avoid race conditions
- useEffect(() => {
- if (
- folderSlug &&
- !selectedFolderId &&
- allFolders.length > 0 &&
- !isFoldersLoading
- ) {
- const params = new URLSearchParams(searchParams);
- params.delete("folder");
- setSearchParams(params, { replace: true });
- }
- }, [
- folderSlug,
- selectedFolderId,
- allFolders.length,
- isFoldersLoading,
- searchParams,
- setSearchParams,
- ]);
-
- // Update folder query param
- const setSelectedFolderId = (folderId: string | null) => {
- const params = new URLSearchParams(searchParams);
- if (folderId) {
- const folder = allFolders.find((f) => f.folder_id === folderId);
- if (folder) {
- const slug = getUniqueSlugForFolder(folder, allFolders);
- params.set("folder", slug);
- params.set("page", "1"); // Reset to page 1 when changing folder
- setSearchParams(params, { replace: true });
- return;
- }
- }
- // Remove folder filter
- params.delete("folder");
- params.set("page", "1");
- setSearchParams(params, { replace: true });
- };
-
- // Create folders map for O(1) lookup
- const foldersMap = useMemo(() => {
- return new Map(allFolders.map((f) => [f.folder_id, f]));
- }, [allFolders]);
-
- // Sort folders by modified date (most recent first) and get top 5
- const recentFolders = useMemo(() => {
- return [...allFolders]
- .sort(
- (a, b) =>
- new Date(b.modified_at).getTime() - new Date(a.modified_at).getTime(),
- )
- .slice(0, 5);
- }, [allFolders]);
-
- const {
- data: workflows = [],
- isFetching,
- isPlaceholderData,
- } = useQuery<Array<WorkflowApiResponse>>({
- queryKey: [
- "workflows",
- debouncedSearch,
- page,
- itemsPerPage,
- selectedFolderId,
- serializedTagFilter,
- ],
- queryFn: async () => {
- const client = await getClient(credentialGetter);
- const params = new URLSearchParams();
- params.append("page", String(page));
- params.append("page_size", String(itemsPerPage));
- params.append("only_workflows", "true");
- if (debouncedSearch) {
- params.append("search_key", debouncedSearch);
- }
- if (selectedFolderId) {
- params.append("folder_id", selectedFolderId);
- }
- if (serializedTagFilter) {
- params.append("tags", serializedTagFilter);
- }
- return client
- .get(`/workflows`, {
- params,
- })
- .then((response) => response.data);
- },
- placeholderData: (previousData) => previousData,
- });
-
- // unfiltered "owns any workflow" check; the filtered/paginated list above can read empty for a user who has workflows
- const { data: ownedWorkflows = [], isLoading: ownedWorkflowsLoading } =
- useQuery<Array<WorkflowApiResponse>>({
- queryKey: ["workflows", "exists"],
- queryFn: async () => {
- const client = await getClient(credentialGetter);
- const params = new URLSearchParams();
- params.append("page", "1");
- params.append("page_size", "1");
- params.append("only_workflows", "true");
- return client
- .get(`/workflows`, { params })
- .then((response) => response.data);
- },
- });
-
- const onboarding = useOnboardingStateOptional();
-
- const { data: nextPageWorkflows } = useQuery<Array<WorkflowApiResponse>>({
- queryKey: [
- "workflows",
- debouncedSearch,
- page + 1,
- itemsPerPage,
- selectedFolderId,
- serializedTagFilter,
- ],
- queryFn: async () => {
- const client = await getClient(credentialGetter);
- const params = new URLSearchParams();
- params.append("page", String(page + 1));
- params.append("page_size", String(itemsPerPage));
- params.append("only_workflows", "true");
- if (debouncedSearch) {
- params.append("search_key", debouncedSearch);
- }
- if (selectedFolderId) {
- params.append("folder_id", selectedFolderId);
- }
- if (serializedTagFilter) {
- params.append("tags", serializedTagFilter);
- }
- return client
- .get(`/workflows`, {
- params,
- })
- .then((response) => response.data);
- },
- enabled: workflows.length === itemsPerPage,
- });
-
- const isNextDisabled =
- isFetching || !nextPageWorkflows || nextPageWorkflows.length === 0;
-
- // Tag-key registry: supplies chip-hover descriptions and the filter's key list.
- // Keyed with a Map so tag keys like "constructor"/"toString" can't resolve to
- // inherited Object prototype members when looked up.
- const { data: tagKeys = [] } = useTagKeysQuery();
- const tagDescriptions = useMemo(
- () =>
- new Map(
- tagKeys.map((tagKey): [string, string | null] => [
- tagKey.key,
- tagKey.description,
- ]),
- ),
- [tagKeys],
- );
-
- // One batch fetch of current tags for every workflow on the page (no N+1).
- const workflowIds = useMemo(
- () => workflows.map((workflow) => workflow.workflow_permanent_id),
- [workflows],
- );
- const { data: workflowTagsMap = {} } = useWorkflowTagsBatchQuery(workflowIds);
-
- // Tags observed on the page for editor/filter suggestions: grouped values per
- // key plus standalone labels. Maps avoid prototype-key collisions.
- const { valueSuggestionsByKey, labelSuggestions } = useMemo(() => {
- const collected = new Map<string, Set<string>>();
- const labels = new Set<string>();
- for (const tags of Object.values(workflowTagsMap)) {
- for (const tag of tags) {
- if (tag.key === null) {
- labels.add(tag.value);
- continue;
- }
- let values = collected.get(tag.key);
- if (!values) {
- values = new Set<string>();
- collected.set(tag.key, values);
- }
- values.add(tag.value);
- }
- }
- const byKey = new Map<string, string[]>();
- for (const [key, values] of collected) {
- byKey.set(key, [...values].sort());
- }
- return {
- valueSuggestionsByKey: byKey,
- labelSuggestions: [...labels].sort(),
- };
- }, [workflowTagsMap]);
-
- const { matchesParameter } = useKeywordSearch(debouncedSearch);
- const { expandedRows, toggleExpanded: toggleParametersExpanded } =
- useParameterExpansion();
-
- function handleRowClick(
- event: React.MouseEvent<HTMLTableCellElement>,
- workflowPermanentId: string,
- ) {
- if (event.ctrlKey || event.metaKey) {
- window.open(
- window.location.origin + `/workflows/${workflowPermanentId}/runs`,
- "_blank",
- "noopener,noreferrer",
- );
- return;
- }
- navigate(`/workflows/${workflowPermanentId}/runs`);
- }
-
- function handleIconClick(
- event: React.MouseEvent<HTMLButtonElement>,
- path: string,
- ) {
- if (event.ctrlKey || event.metaKey) {
- window.open(
- window.location.origin + path,
- "_blank",
- "noopener,noreferrer",
- );
- return;
- }
- navigate(path);
- }
-
- function setParamPatch(patch: Record<string, string>) {
- const params = new URLSearchParams(searchParams);
- Object.entries(patch).forEach(([k, v]) => params.set(k, v));
- setSearchParams(params, { replace: true });
- }
-
- function handlePreviousPage() {
- if (page === 1) return;
- setParamPatch({ page: String(page - 1) });
- }
-
- function handleNextPage() {
- if (isNextDisabled) return;
- setParamPatch({ page: String(page + 1) });
- }
-
- // Show importing agents from polling hook (only on page 1)
- const displayWorkflows = useMemo(() => {
- const importingOnly = activeImports.filter(
- (imp) => imp.status === "importing",
- );
-
- if (page === 1 && importingOnly.length > 0) {
- return [...importingOnly, ...workflows];
- }
- return workflows;
- }, [activeImports, workflows, page]);
-
- const selectableWorkflows = useMemo(
- () =>
- displayWorkflows.filter((workflow) => workflow.status !== "importing"),
- [displayWorkflows],
- );
-
- const showCheckbox = selectableWorkflows.length > 0;
- const columnCount = showCheckbox ? 6 : 5;
-
- const {
- selected,
- selectedItems: selectedWorkflows,
- isSelected,
- allSelected,
- someSelected,
- indexById: selectableIndexById,
- handleSelect,
- toggleSelectAll,
- clearSelection,
- replaceSelection,
- } = useRowSelection({
- items: selectableWorkflows,
- getId: (workflow) => workflow.workflow_permanent_id,
- // Keyed on the folder SLUG (user navigation), not the derived id, so folder
- // list refetches can never wipe an in-progress selection.
- resetKey: JSON.stringify([page, folderSlug, debouncedSearch]),
- // Page-size changes keep the selection; only the shift anchor resets.
- anchorResetKey: itemsPerPage,
- });
-
- async function handleBulkMoveToFolder(folderId: string | null) {
- if (selectedWorkflows.length === 0) {
- return;
- }
-
- setIsBulkOperating(true);
- try {
- const client = await getClient(credentialGetter);
- const results = await runWithConcurrency(
- selectedWorkflows.map(
- (workflow) => () =>
- client.put(`/workflows/${workflow.workflow_permanent_id}/folder`, {
- folder_id: folderId,
- }),
- ),
- BULK_CONCURRENCY_LIMIT,
- );
- const succeeded = results.filter((r) => r.status === "fulfilled").length;
- bulkResultToast({
- succeeded,
- total: selectedWorkflows.length,
- results,
- successTitle: (count) =>
- folderId
- ? `Moved ${count} agent${count !== 1 ? "s" : ""} to folder.`
- : `Removed ${count} agent${count !== 1 ? "s" : ""} from folder.`,
- failureTitle: (count) =>
- folderId
- ? `Failed to move ${count} agent${count !== 1 ? "s" : ""} to folder.`
- : `Failed to remove ${count} agent${count !== 1 ? "s" : ""} from folder.`,
- partialTitle: (successCount, failedCount) =>
- folderId
- ? `Moved ${successCount} agent${successCount !== 1 ? "s" : ""} to folder. ${failedCount} failed.`
- : `Removed ${successCount} agent${successCount !== 1 ? "s" : ""} from folder. ${failedCount} failed.`,
- });
- if (succeeded === selectedWorkflows.length) {
- clearSelection();
- }
- if (succeeded > 0) {
- queryClient.invalidateQueries({ queryKey: ["workflows"] });
- queryClient.invalidateQueries({ queryKey: ["folders"] });
- }
- } finally {
- setIsBulkOperating(false);
- }
- }
-
- async function handleBulkDeleteConfirm() {
- // Snapshot from dialog-open time; the live selection may have changed since.
- const targets = bulkDeleteDialog.targets;
- if (targets.length === 0) {
- return;
- }
-
- setIsBulkOperating(true);
- try {
- const client = await getClient(credentialGetter);
- const results = await runWithConcurrency(
- targets.map(
- (workflowId) => () => client.delete(`/workflows/${workflowId}`),
- ),
- BULK_CONCURRENCY_LIMIT,
- );
-
- const succeededIds: string[] = [];
- const failedIds = new Set<string>();
- results.forEach((result, index) => {
- const workflowId = targets[index]!;
- if (result.status === "fulfilled") {
- succeededIds.push(workflowId);
- useNodeCollapseStore.getState().pruneWorkflow(workflowId);
- } else {
- failedIds.add(workflowId);
- }
- });
-
- const succeeded = succeededIds.length;
- const failed = failedIds.size;
-
- bulkResultToast({
- succeeded,
- total: targets.length,
- results,
- successTitle: (count) =>
- `${count} agent${count !== 1 ? "s" : ""} deleted successfully.`,
- failureTitle: (count) =>
- `Failed to delete ${count} agent${count !== 1 ? "s" : ""}.`,
- partialTitle: (successCount, failedCount) =>
- `Deleted ${successCount} agent${successCount !== 1 ? "s" : ""}. ${failedCount} failed.`,
- });
- // Deletions shift row indices; replace/clear also resets the shift anchor.
- if (failed === 0) {
- clearSelection();
- } else {
- replaceSelection(failedIds);
- }
-
- if (succeeded > 0) {
- queryClient.invalidateQueries({ queryKey: ["workflows"] });
- queryClient.invalidateQueries({ queryKey: ["folders"] });
- }
- } finally {
- setIsBulkOperating(false);
- setBulkDeleteDialog({ open: false, targets: [] });
- }
- }
-
- return (
- <div className="space-y-10">
- <div className="flex h-32 justify-between gap-6">
- <div className="space-y-5">
- <div className="flex items-center gap-2">
- <LightningBoltIcon className="size-6" />
- <h1 className="text-2xl">Agents</h1>
- </div>
- <p className="text-sm leading-6 text-muted-foreground">
- Create your own complex agents by connecting web agents together.
- Define a series of actions, set it, and forget it.
- </p>
- </div>
- <div className="flex gap-5">
- <NarrativeCard
- index={1}
- description="Save browser sessions and reuse them in subsequent runs"
- />
- <NarrativeCard
- index={2}
- description="Connect multiple agents together to carry out complex objectives"
- />
- <NarrativeCard
- index={3}
- description="Execute non-browser tasks such as sending emails"
- />
- </div>
- </div>
- <div className="space-y-4">
- {/* Folders Section */}
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-3">
- <h2 className="text-lg font-semibold">Folders</h2>
- <Button
- variant="link"
- size="sm"
- className="h-auto p-0 text-blue-600 dark:text-blue-400"
- onClick={() => setIsCreateFolderOpen(true)}
- >
- + New folder
- </Button>
- </div>
- {allFolders.length > 5 && (
- <Button
- variant="link"
- size="sm"
- className="text-blue-600 dark:text-blue-400"
- onClick={() => setIsViewAllFoldersOpen(true)}
- >
- View all
- </Button>
- )}
- </div>
-
- {recentFolders.length > 0 ? (
- <div className="grid grid-cols-5 gap-4">
- {recentFolders.map((folder) => (
- <FolderCard
- key={folder.folder_id}
- folder={folder}
- isSelected={selectedFolderId === folder.folder_id}
- onClick={() =>
- setSelectedFolderId(
- selectedFolderId === folder.folder_id
- ? null
- : folder.folder_id,
- )
- }
- />
- ))}
- </div>
- ) : (
- <div className="rounded-lg border border-slate-200 bg-slate-elevation1 py-6 text-center dark:border-slate-700">
- <div className="mx-auto max-w-md">
- <FolderIcon className="mx-auto mb-3 h-10 w-10 text-blue-400 opacity-50" />
- <h3 className="mb-2 text-slate-900 dark:text-slate-100">
- Organize Your Agents with Folders
- </h3>
- <p className="mb-4 text-sm text-slate-500 dark:text-slate-400">
- Keep your agents organized by creating folders. Group related
- agents together by project, team, or agent type for easier
- management.
- </p>
- <Button
- variant="link"
- size="sm"
- className="h-auto p-0 text-blue-600 dark:text-blue-400"
- onClick={() => setIsCreateFolderOpen(true)}
- >
- <PlusIcon className="mr-2 h-4 w-4" />
- Create Your First Folder
- </Button>
- </div>
- </div>
- )}
- </div>
-
- {/* Agents Section */}
- <header className="flex items-center justify-between">
- <h1 className="text-xl">My Agents</h1>
- {selectedFolderId && (
- <Button
- variant="link"
- size="sm"
- className="h-auto p-0 text-blue-600 dark:text-blue-400"
- onClick={() => setSelectedFolderId(null)}
- >
- View all agents
- </Button>
- )}
- </header>
- <div className="flex justify-between">
- <div className="flex items-center gap-3">
- <TableSearchInput
- value={search}
- onChange={(value) => {
- setSearch(value);
- setParamPatch({ page: "1" });
- }}
- placeholder="Search by title or input..."
- className="w-48 lg:w-72"
- />
- <WorkflowTagFilter
- tagKeys={tagKeys}
- value={tagFilters}
- onChange={setTagFilters}
- labelSuggestions={labelSuggestions}
- valueSuggestionsByKey={valueSuggestionsByKey}
- />
- </div>
- <div className="flex items-center gap-4">
- <Link
- to="/discover"
- className="text-sm text-muted-foreground hover:text-foreground"
- >
- Or start from a description →
- </Link>
- <ImportWorkflowButton
- onImportStart={startPolling}
- selectedFolderId={selectedFolderId}
- />
- <DropdownMenu modal={false}>
- <DropdownMenuTrigger asChild>
- <Button disabled={createWorkflowMutation.isPending}>
- {createWorkflowMutation.isPending ? (
- <ReloadIcon className="mr-2 h-4 w-4 animate-spin" />
- ) : (
- <PlusIcon className="mr-2 h-4 w-4" />
- )}
- Create
- <ChevronDownIcon className="ml-2 h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem
- onSelect={() => {
- createWorkflowMutation.mutate({
- ...defaultWorkflowRequest,
- folder_id: selectedFolderId,
- _via: "blank",
- });
- }}
- >
- <PlusIcon className="mr-2 h-4 w-4" />
- Blank Agent
- </DropdownMenuItem>
- <DropdownMenuItem
- onSelect={() => setIsTemplateDialogOpen(true)}
- >
- <BookmarkFilledIcon className="mr-2 h-4 w-4" />
- From Template
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </div>
- <div className="overflow-hidden rounded-lg border border-border">
- <Table className="table-fixed">
- <TableHeader>
- <TableRow className="group/header">
- {showCheckbox && (
- <SelectionHeaderCheckboxCell
- className="w-[3%]"
- allSelected={allSelected}
- someSelected={someSelected}
- hasSelection={selected.size > 0}
- onToggleAll={toggleSelectAll}
- ariaLabel="Select all agents"
- />
- )}
- <TableHead className={showCheckbox ? "w-[22%]" : "w-[25%]"}>
- ID
- </TableHead>
- <TableHead className={showCheckbox ? "w-[27%]" : "w-[30%]"}>
- Title
- </TableHead>
- <TableHead className="w-[15%]">Folder</TableHead>
- <TableHead className="w-[15%]">Created At</TableHead>
- <TableHead className="w-[15%] text-right">Actions</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {isFetching &&
- !isPlaceholderData &&
- displayWorkflows.length === 0 ? (
- // Show skeleton rows only on initial load (not during search refinement)
- Array.from({ length: 10 }).map((_, index) => (
- <TableRow key={`skeleton-${index}`}>
- {showCheckbox && (
- <TableCell>
- <Skeleton className="h-4 w-4" />
- </TableCell>
- )}
- <TableCell>
- <Skeleton className="h-5 w-full" />
- </TableCell>
- <TableCell>
- <Skeleton className="h-5 w-full" />
- </TableCell>
- <TableCell>
- <Skeleton className="h-5 w-20" />
- </TableCell>
- <TableCell>
- <Skeleton className="h-5 w-32" />
- </TableCell>
- <TableCell>
- <div className="flex justify-end gap-2">
- <Skeleton className="h-8 w-8 rounded" />
- <Skeleton className="h-8 w-8 rounded" />
- <Skeleton className="h-8 w-8 rounded" />
- <Skeleton className="h-8 w-8 rounded" />
- </div>
- </TableCell>
- </TableRow>
- ))
- ) : displayWorkflows?.length === 0 ? (
- <TableMessageRow colSpan={columnCount}>
- No agents found
- </TableMessageRow>
- ) : (
- displayWorkflows?.map((workflow) => {
- const parameterItems = workflow.workflow_definition.parameters
- .filter((p) => p.parameter_type !== "output")
- .map((param) => ({
- key: param.key,
- value:
- param.parameter_type === "workflow"
- ? (param.default_value ?? "")
- : "",
- description: param.description ?? null,
- }));
- const hasParameters = parameterItems.length > 0;
- const isExpanded = expandedRows.has(
- workflow.workflow_permanent_id,
- );
- const isRowSelected = isSelected(
- workflow.workflow_permanent_id,
- );
- // Check if this is an importing agent
- const isUploading = workflow.status === "importing";
- const workflowTags =
- workflowTagsMap[workflow.workflow_permanent_id];
- const selectableIndex = isUploading
- ? -1
- : (selectableIndexById.get(
- workflow.workflow_permanent_id,
- ) ?? -1);
-
- return (
- <React.Fragment key={workflow.workflow_permanent_id}>
- {/* Main workflow row */}
- {isUploading ? (
- <TableRow className="opacity-70">
- {showCheckbox && <TableCell />}
- <TableCell colSpan={2}>
- <div className="flex min-w-0 items-center gap-2">
- <ReloadIcon className="h-4 w-4 shrink-0 animate-spin text-blue-400" />
- <span className="truncate" title={workflow.title}>
- {workflow.title}
- </span>
- </div>
- </TableCell>
- <TableCell>
- <span className="text-muted-foreground">-</span>
- </TableCell>
- <TableCell className="text-muted-foreground">
- {compactLocalDateTime(workflow.created_at)}
- </TableCell>
- <TableCell>
- <div className="flex justify-end gap-0.5">
- {selected.size === 0 && (
- <Button size="icon" variant="ghost" disabled>
- <FolderIcon className="h-4 w-4" />
- </Button>
- )}
- <Button size="icon" variant="ghost" disabled>
- <Pencil2Icon className="h-4 w-4" />
- </Button>
- <Button size="icon" variant="ghost" disabled>
- <PlayIcon className="h-4 w-4" />
- </Button>
- {selected.size === 0 && (
- <Button size="icon" variant="ghost" disabled>
- <DotsHorizontalIcon className="h-4 w-4" />
- </Button>
- )}
- </div>
- </TableCell>
- </TableRow>
- ) : (
- <TableRow
- className="group/row cursor-pointer select-none"
- data-state={isRowSelected ? "selected" : undefined}
- >
- {showCheckbox && (
- <SelectionCheckboxCell
- className="select-none"
- index={selectableIndex}
- checked={isRowSelected}
- hasSelection={selected.size > 0}
- onSelect={handleSelect}
- ariaLabel={`Select ${workflow.title}`}
- />
- )}
- <TableCell
- onClick={(event) => {
- handleRowClick(
- event,
- workflow.workflow_permanent_id,
- );
- }}
- >
- <div
- className="truncate font-mono text-xs text-muted-foreground"
- title={workflow.workflow_permanent_id}
- >
- <HighlightText
- text={workflow.workflow_permanent_id}
- query={debouncedSearch}
- />
- </div>
- </TableCell>
- <TableCell
- onClick={(event) => {
- handleRowClick(
- event,
- workflow.workflow_permanent_id,
- );
- }}
- >
- <div className="flex min-w-0 flex-col gap-1">
- <div className="flex min-w-0 items-center gap-2">
- <span
- className="truncate"
- title={workflow.title}
- >
- <HighlightText
- text={workflow.title}
- query={debouncedSearch}
- />
- </span>
- {workflow.is_template && (
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <BookmarkFilledIcon className="h-3.5 w-3.5 shrink-0 text-blue-500" />
- </TooltipTrigger>
- <TooltipContent>Template</TooltipContent>
- </Tooltip>
- </TooltipProvider>
- )}
- </div>
- {workflowTags && workflowTags.length > 0 ? (
- <TagChipList
- tags={workflowTags}
- descriptions={tagDescriptions}
- />
- ) : null}
- </div>
- </TableCell>
- <TableCell
- onClick={(event) => {
- handleRowClick(
- event,
- workflow.workflow_permanent_id,
- );
- }}
- >
- {workflow.folder_id ? (
- <div className="flex min-w-0 items-center gap-1.5">
- <FolderIcon className="h-3.5 w-3.5 shrink-0 text-blue-400" />
- <span
- className="truncate text-sm"
- title={
- foldersMap.get(workflow.folder_id)?.title ||
- workflow.folder_id
- }
- >
- <HighlightText
- text={
- foldersMap.get(workflow.folder_id)
- ?.title || workflow.folder_id
- }
- query={debouncedSearch}
- />
- </span>
- </div>
- ) : (
- <span className="text-muted-foreground">-</span>
- )}
- </TableCell>
- <TableCell
- onClick={(event) => {
- handleRowClick(
- event,
- workflow.workflow_permanent_id,
- );
- }}
- className="text-muted-foreground"
- title={basicTimeFormat(workflow.created_at)}
- >
- {compactLocalDateTime(workflow.created_at)}
- </TableCell>
- <TableCell>
- <div className="flex justify-end gap-0.5">
- {/* Folder, tags, and the row menu yield to the bulk bar while any selection is active; Edit and Run stay. */}
- {selected.size === 0 && (
- <>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <WorkflowFolderSelector
- workflowPermanentId={
- workflow.workflow_permanent_id
- }
- currentFolderId={workflow.folder_id}
- disabled={isBulkOperating}
- />
- </div>
- </TooltipTrigger>
- <TooltipContent>
- Assign to Folder
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- <WorkflowTagEditor
- workflowPermanentId={
- workflow.workflow_permanent_id
- }
- tags={workflowTags ?? []}
- tagKeys={tagKeys}
- labelSuggestions={labelSuggestions}
- valueSuggestionsByKey={
- valueSuggestionsByKey
- }
- />
- </>
- )}
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- size="icon"
- variant="ghost"
- className="text-muted-foreground hover:text-foreground"
- onClick={(event) => {
- handleIconClick(
- event,
- `/workflows/${workflow.workflow_permanent_id}/build`,
- );
- }}
- >
- <Pencil2Icon className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- Open in Editor
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- size="icon"
- variant="ghost"
- className="text-cta hover:text-cta"
- onClick={(event) => {
- handleIconClick(
- event,
- `/workflows/${workflow.workflow_permanent_id}/run`,
- );
- }}
- >
- <PlayIcon className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- Create New Run
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- {selected.size === 0 && (
- <WorkflowActions
- workflow={workflow}
- hasParameters={hasParameters}
- parametersExpanded={isExpanded}
- onToggleParameters={() =>
- toggleParametersExpanded(
- workflow.workflow_permanent_id,
- )
- }
- />
- )}
- </div>
- </TableCell>
- </TableRow>
- )}
-
- {/* Expanded parameters section */}
- {isExpanded && hasParameters && (
- <TableRow
- key={`${workflow.workflow_permanent_id}-params`}
- >
- <TableCell
- colSpan={columnCount}
- className="bg-slate-50 dark:bg-slate-900/50"
- >
- <ParameterDisplayInline
- parameters={parameterItems}
- searchQuery={debouncedSearch}
- keywordMatchesParameter={matchesParameter}
- />
- </TableCell>
- </TableRow>
- )}
- </React.Fragment>
- );
- })
- )}
- </TableBody>
- </Table>
- <div className="relative px-3 py-3">
- <div className="absolute left-3 top-1/2 flex -translate-y-1/2 items-center gap-2 text-sm">
- <span className="text-slate-400">Items per page</span>
- <select
- className="h-9 rounded-md border border-slate-300 bg-background px-3"
- value={itemsPerPage}
- onChange={(e) => {
- const next = Number(e.target.value);
- const params = new URLSearchParams(searchParams);
- params.set("page_size", String(next));
- params.set("page", "1");
- setSearchParams(params, { replace: true });
- }}
- >
- <option value={5}>5</option>
- <option value={10}>10</option>
- <option value={20}>20</option>
- <option value={50}>50</option>
- </select>
- </div>
- <Pagination className="pt-0">
- <PaginationContent>
- <PaginationItem>
- <PaginationPrevious
- className={cn({
- "cursor-not-allowed opacity-50": page === 1,
- })}
- onClick={handlePreviousPage}
- />
- </PaginationItem>
- <PaginationItem>
- <PaginationLink>{page}</PaginationLink>
- </PaginationItem>
- <PaginationItem>
- <PaginationNext
- className={cn({
- "cursor-not-allowed opacity-50": isNextDisabled,
- })}
- onClick={handleNextPage}
- />
- </PaginationItem>
- </PaginationContent>
- </Pagination>
- </div>
- </div>
-
- {selectedWorkflows.length > 0 && (
- <BulkActionBar
- selectedWorkflows={selectedWorkflows}
- isOperating={isBulkOperating}
- onOperatingChange={setIsBulkOperating}
- onClearSelection={clearSelection}
- onDeleteRequest={() =>
- setBulkDeleteDialog({
- open: true,
- targets: selectedWorkflows.map(
- (workflow) => workflow.workflow_permanent_id,
- ),
- })
- }
- onMoveToFolder={handleBulkMoveToFolder}
- tagKeys={tagKeys}
- labelSuggestions={labelSuggestions}
- valueSuggestionsByKey={valueSuggestionsByKey}
- />
- )}
-
- <Dialog
- open={bulkDeleteDialog.open}
- onOpenChange={(open) => {
- if (!open && !isBulkOperating) {
- setBulkDeleteDialog({ open: false, targets: [] });
- }
- }}
- >
- <DialogContent>
- <DialogHeader>
- <DialogTitle>
- Delete {bulkDeleteDialog.targets.length} Agent
- {bulkDeleteDialog.targets.length === 1 ? "" : "s"}
- </DialogTitle>
- <DialogDescription>
- Are you sure you want to delete{" "}
- {bulkDeleteDialog.targets.length}{" "}
- {bulkDeleteDialog.targets.length === 1 ? "agent" : "agents"}?
- This action cannot be undone.
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <Button
- variant="secondary"
- disabled={isBulkOperating}
- onClick={() =>
- setBulkDeleteDialog({ open: false, targets: [] })
- }
- >
- Cancel
- </Button>
- <Button
- variant="destructive"
- disabled={isBulkOperating}
- onClick={() => {
- void handleBulkDeleteConfirm();
- }}
- >
- {isBulkOperating ? "Deleting..." : "Delete"}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
-
- {/* Folder Dialogs */}
- <CreateFolderDialog
- open={isCreateFolderOpen}
- onOpenChange={setIsCreateFolderOpen}
- />
- <ViewAllFoldersDialog
- open={isViewAllFoldersOpen}
- onOpenChange={setIsViewAllFoldersOpen}
- selectedFolderId={selectedFolderId}
- onFolderSelect={setSelectedFolderId}
- />
-
- {/* Template Dialog */}
- <CreateFromTemplateDialog
- open={isTemplateDialogOpen}
- onOpenChange={setIsTemplateDialogOpen}
- onSelectTemplate={(template) => {
- const clonedWorkflow = convert({
- ...template,
- title: `${template.title} (copy)`,
- });
- createWorkflowMutation.mutate({
- ...clonedWorkflow,
- folder_id: selectedFolderId,
- });
- }}
- />
-
- <div data-hint="start-template">
- <WorkflowTemplates />
- </div>
-
- {onboarding ? (
- <OnboardingErrorBoundary
- onError={() => OnboardingTelemetry.modalRenderError("dashboard")}
- >
- <GetStartedModal
- hasWorkflows={ownedWorkflows.length > 0}
- isLoading={ownedWorkflowsLoading}
- />
- </OnboardingErrorBoundary>
- ) : null}
- </div>
- </div>
- );
+ const directoryTreeEnabled = useWorkflowsDirectoryTree();
+ return directoryTreeEnabled ? <WorkflowsTree /> : <WorkflowsFlat />;
}
export { Workflows };
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowsFlat.tsx b/skyvern-frontend/src/routes/workflows/WorkflowsFlat.tsx
new file mode 100644
index 000000000..2cca5ed0b
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/WorkflowsFlat.tsx
@@ -0,0 +1,1346 @@
+import { getClient } from "@/api/AxiosClient";
+import { GetStartedModal } from "@/components/onboarding/GetStartedModal";
+import { useOnboardingStateOptional } from "@/store/onboarding/useOnboardingState";
+import { OnboardingErrorBoundary } from "@/components/onboarding/OnboardingErrorBoundary";
+import { OnboardingTelemetry } from "@/util/onboarding/OnboardingTelemetry";
+import { Button } from "@/components/ui/button";
+import {
+ SelectionCheckboxCell,
+ SelectionHeaderCheckboxCell,
+} from "@/components/SelectionCheckbox";
+import { useRowSelection } from "@/hooks/useRowSelection";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ Pagination,
+ PaginationContent,
+ PaginationItem,
+ PaginationLink,
+ PaginationNext,
+ PaginationPrevious,
+} from "@/components/ui/pagination";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableMessageRow,
+ TableRow,
+} from "@/components/ui/table";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { basicTimeFormat, compactLocalDateTime } from "@/util/timeFormat";
+import {
+ BULK_CONCURRENCY_LIMIT,
+ runWithConcurrency,
+} from "@/util/runWithConcurrency";
+import { bulkResultToast } from "@/util/bulkResultToast";
+import { cn } from "@/util/utils";
+import {
+ BookmarkFilledIcon,
+ ChevronDownIcon,
+ DotsHorizontalIcon,
+ LightningBoltIcon,
+ Pencil2Icon,
+ PlayIcon,
+ PlusIcon,
+ ReloadIcon,
+} from "@radix-ui/react-icons";
+import { FolderIcon } from "@/components/icons/FolderIcon";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import React, {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { Link, useNavigate, useSearchParams } from "react-router-dom";
+import { useDebounce } from "use-debounce";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { NarrativeCard } from "./components/header/NarrativeCard";
+import { BulkActionBar } from "./components/BulkActionBar";
+import { FolderCard } from "./components/FolderCard";
+import { CreateFolderDialog } from "./components/CreateFolderDialog";
+import { CreateFromTemplateDialog } from "./components/CreateFromTemplateDialog";
+import { ViewAllFoldersDialog } from "./components/ViewAllFoldersDialog";
+import { WorkflowFolderSelector } from "./components/WorkflowFolderSelector";
+import { HighlightText } from "./components/HighlightText";
+import { useCreateWorkflowMutation } from "./hooks/useCreateWorkflowMutation";
+import { useFoldersQuery } from "./hooks/useFoldersQuery";
+import { useTagKeysQuery } from "./hooks/useTagKeysQuery";
+import { useWorkflowTagsBatchQuery } from "./hooks/useWorkflowTagsBatchQuery";
+import { useActiveImportsPolling } from "./hooks/useActiveImportsPolling";
+import { TagChipList } from "./components/tagging/TagChipList";
+import { WorkflowTagFilter } from "./components/tagging/WorkflowTagFilter";
+import { WorkflowTagEditor } from "./components/tagging/WorkflowTagEditor";
+import {
+ parseTagFilter,
+ serializeTagFilter,
+ type TagFilterTerm,
+} from "./types/tagTypes";
+import { ImportWorkflowButton } from "./ImportWorkflowButton";
+import { useNodeCollapseStore } from "./editor/collapse/useNodeCollapseStore";
+import { convert } from "./editor/workflowEditorUtils";
+import { WorkflowApiResponse } from "./types/workflowTypes";
+import { WorkflowActions } from "./WorkflowActions";
+import { WorkflowTemplates } from "../discover/WorkflowTemplates";
+import { Skeleton } from "@/components/ui/skeleton";
+import { TableSearchInput } from "@/components/TableSearchInput";
+import { ParameterDisplayInline } from "./components/ParameterDisplayInline";
+import { useKeywordSearch } from "./hooks/useKeywordSearch";
+import { useParameterExpansion } from "./hooks/useParameterExpansion";
+import { Folder } from "./types/folderTypes";
+import { defaultWorkflowRequest } from "./defaultWorkflowRequest";
+
+// Utility function to create URL-safe folder slugs from folder names
+function slugifyFolderName(name: string): string {
+ return name
+ .toLowerCase()
+ .trim()
+ .replace(/[^\w\s-]/g, "") // Remove special characters except spaces and hyphens
+ .replace(/\s+/g, "-") // Replace spaces with hyphens
+ .replace(/-+/g, "-") // Replace multiple hyphens with single hyphen
+ .replace(/^-|-$/g, ""); // Remove leading/trailing hyphens
+}
+
+const FOLDERS_PAGE_SIZE = 10;
+
+// Generate a unique slug for a folder, appending a number suffix only if there's a collision
+function getUniqueSlugForFolder(folder: Folder, allFolders: Folder[]): string {
+ const baseSlug = slugifyFolderName(folder.title);
+
+ // Find all folders that would have the same base slug
+ const foldersWithSameSlug = allFolders.filter(
+ (f) => slugifyFolderName(f.title) === baseSlug,
+ );
+
+ // If no collision, return the base slug
+ if (foldersWithSameSlug.length <= 1) {
+ return baseSlug;
+ }
+
+ // Sort by created_at to ensure consistent numbering
+ const sortedFolders = [...foldersWithSameSlug].sort(
+ (a, b) =>
+ new Date(a.created_at).getTime() - new Date(b.created_at).getTime(),
+ );
+
+ const index = sortedFolders.findIndex(
+ (f) => f.folder_id === folder.folder_id,
+ );
+
+ // First folder (oldest) gets the base slug, others get numbered suffixes
+ return index === 0 ? baseSlug : `${baseSlug}-${index + 1}`;
+}
+function WorkflowsFlat() {
+ const credentialGetter = useCredentialGetter();
+ const queryClient = useQueryClient();
+ const navigate = useNavigate();
+ const createWorkflowMutation = useCreateWorkflowMutation();
+ const [searchParams, setSearchParams] = useSearchParams();
+ const [search, setSearch] = useState("");
+ const [debouncedSearch] = useDebounce(search, 250);
+ const [isBulkOperating, setIsBulkOperating] = useState(false);
+ const [bulkDeleteDialog, setBulkDeleteDialog] = useState<{
+ open: boolean;
+ targets: string[];
+ }>({ open: false, targets: [] });
+ const page = searchParams.get("page") ? Number(searchParams.get("page")) : 1;
+ const itemsPerPage = searchParams.get("page_size")
+ ? Number(searchParams.get("page_size"))
+ : 10;
+
+ // Folder slug from query param (e.g., /workflows?folder=my-folder-name)
+ const folderSlug = searchParams.get("folder");
+
+ // Tag filter from query param (e.g., /workflows?tags=env:prod,env:staging).
+ // The backend accepts both comma-separated pairs and repeated `tags` params,
+ // so read every occurrence. The serialized form is canonical (sorted) and is
+ // used for both the request and the query key so cache hits are
+ // order-independent.
+ const tagFilterParam = searchParams.getAll("tags").join(",");
+ const tagFilters = useMemo(
+ () => parseTagFilter(tagFilterParam),
+ [tagFilterParam],
+ );
+ const serializedTagFilter = serializeTagFilter(tagFilters);
+
+ const setTagFilters = useCallback(
+ (terms: TagFilterTerm[]) => {
+ const params = new URLSearchParams(searchParams);
+ const serialized = serializeTagFilter(terms);
+ if (serialized) {
+ params.set("tags", serialized);
+ } else {
+ params.delete("tags");
+ }
+ params.set("page", "1");
+ setSearchParams(params, { replace: true });
+ },
+ [searchParams, setSearchParams],
+ );
+
+ const [isCreateFolderOpen, setIsCreateFolderOpen] = useState(false);
+ const [isViewAllFoldersOpen, setIsViewAllFoldersOpen] = useState(false);
+
+ // Template dialog state
+ const [isTemplateDialogOpen, setIsTemplateDialogOpen] = useState(false);
+
+ // Poll for active imports
+ const { activeImports, startPolling } = useActiveImportsPolling();
+
+ // Fetch folders
+ const { data: allFolders = [], isLoading: isFoldersLoading } =
+ useFoldersQuery({ page_size: FOLDERS_PAGE_SIZE });
+
+ // Create a memoized map of slugs to folders to avoid O(n²) lookups
+ const slugToFolderMap = useMemo(() => {
+ const map = new Map<string, Folder>();
+ for (const folder of allFolders) {
+ const slug = getUniqueSlugForFolder(folder, allFolders);
+ map.set(slug, folder);
+ }
+ return map;
+ }, [allFolders]);
+
+ // Folder state - derived from URL query param
+ // Look up the folder by matching the slug (handles collision suffixes like my-folder-2)
+ const resolvedFolderIdBySlug = useRef<Map<string, string>>(new Map());
+ // A short list means we saw every folder, so a lookup miss is a real
+ // deletion/rename rather than pagination dropping the active folder.
+ const foldersListComplete =
+ !isFoldersLoading && allFolders.length < FOLDERS_PAGE_SIZE;
+ const selectedFolderId = useMemo(() => {
+ if (!folderSlug) return null;
+ const matchingFolder = slugToFolderMap.get(folderSlug);
+ if (matchingFolder) {
+ resolvedFolderIdBySlug.current.set(folderSlug, matchingFolder.folder_id);
+ return matchingFolder.folder_id;
+ }
+ if (foldersListComplete) {
+ resolvedFolderIdBySlug.current.delete(folderSlug);
+ return null;
+ }
+ // The folders list is paginated, so a refetch can transiently drop the
+ // active folder; reuse the last resolution instead of flapping to null.
+ return resolvedFolderIdBySlug.current.get(folderSlug) ?? null;
+ }, [folderSlug, slugToFolderMap, foldersListComplete]);
+
+ // Clear folder param if the folder slug is invalid (folder deleted/renamed)
+ // Only validate after folders have finished loading to avoid race conditions
+ useEffect(() => {
+ if (
+ folderSlug &&
+ !selectedFolderId &&
+ allFolders.length > 0 &&
+ !isFoldersLoading
+ ) {
+ const params = new URLSearchParams(searchParams);
+ params.delete("folder");
+ setSearchParams(params, { replace: true });
+ }
+ }, [
+ folderSlug,
+ selectedFolderId,
+ allFolders.length,
+ isFoldersLoading,
+ searchParams,
+ setSearchParams,
+ ]);
+
+ // Update folder query param
+ const setSelectedFolderId = (folderId: string | null) => {
+ const params = new URLSearchParams(searchParams);
+ if (folderId) {
+ const folder = allFolders.find((f) => f.folder_id === folderId);
+ if (folder) {
+ const slug = getUniqueSlugForFolder(folder, allFolders);
+ params.set("folder", slug);
+ params.set("page", "1"); // Reset to page 1 when changing folder
+ setSearchParams(params, { replace: true });
+ return;
+ }
+ }
+ // Remove folder filter
+ params.delete("folder");
+ params.set("page", "1");
+ setSearchParams(params, { replace: true });
+ };
+
+ // Create folders map for O(1) lookup
+ const foldersMap = useMemo(() => {
+ return new Map(allFolders.map((f) => [f.folder_id, f]));
+ }, [allFolders]);
+
+ // Sort folders by modified date (most recent first) and get top 5
+ const recentFolders = useMemo(() => {
+ return [...allFolders]
+ .sort(
+ (a, b) =>
+ new Date(b.modified_at).getTime() - new Date(a.modified_at).getTime(),
+ )
+ .slice(0, 5);
+ }, [allFolders]);
+
+ const {
+ data: workflows = [],
+ isFetching,
+ isPlaceholderData,
+ } = useQuery<Array<WorkflowApiResponse>>({
+ queryKey: [
+ "workflows",
+ debouncedSearch,
+ page,
+ itemsPerPage,
+ selectedFolderId,
+ serializedTagFilter,
+ ],
+ queryFn: async () => {
+ const client = await getClient(credentialGetter);
+ const params = new URLSearchParams();
+ params.append("page", String(page));
+ params.append("page_size", String(itemsPerPage));
+ params.append("only_workflows", "true");
+ if (debouncedSearch) {
+ params.append("search_key", debouncedSearch);
+ }
+ if (selectedFolderId) {
+ params.append("folder_id", selectedFolderId);
+ }
+ if (serializedTagFilter) {
+ params.append("tags", serializedTagFilter);
+ }
+ return client
+ .get(`/workflows`, {
+ params,
+ })
+ .then((response) => response.data);
+ },
+ placeholderData: (previousData) => previousData,
+ });
+
+ // unfiltered "owns any workflow" check; the filtered/paginated list above can read empty for a user who has workflows
+ const { data: ownedWorkflows = [], isLoading: ownedWorkflowsLoading } =
+ useQuery<Array<WorkflowApiResponse>>({
+ queryKey: ["workflows", "exists"],
+ queryFn: async () => {
+ const client = await getClient(credentialGetter);
+ const params = new URLSearchParams();
+ params.append("page", "1");
+ params.append("page_size", "1");
+ params.append("only_workflows", "true");
+ return client
+ .get(`/workflows`, { params })
+ .then((response) => response.data);
+ },
+ });
+
+ const onboarding = useOnboardingStateOptional();
+
+ const { data: nextPageWorkflows } = useQuery<Array<WorkflowApiResponse>>({
+ queryKey: [
+ "workflows",
+ debouncedSearch,
+ page + 1,
+ itemsPerPage,
+ selectedFolderId,
+ serializedTagFilter,
+ ],
+ queryFn: async () => {
+ const client = await getClient(credentialGetter);
+ const params = new URLSearchParams();
+ params.append("page", String(page + 1));
+ params.append("page_size", String(itemsPerPage));
+ params.append("only_workflows", "true");
+ if (debouncedSearch) {
+ params.append("search_key", debouncedSearch);
+ }
+ if (selectedFolderId) {
+ params.append("folder_id", selectedFolderId);
+ }
+ if (serializedTagFilter) {
+ params.append("tags", serializedTagFilter);
+ }
+ return client
+ .get(`/workflows`, {
+ params,
+ })
+ .then((response) => response.data);
+ },
+ enabled: workflows.length === itemsPerPage,
+ });
+
+ const isNextDisabled =
+ isFetching || !nextPageWorkflows || nextPageWorkflows.length === 0;
+
+ // Tag-key registry: supplies chip-hover descriptions and the filter's key list.
+ // Keyed with a Map so tag keys like "constructor"/"toString" can't resolve to
+ // inherited Object prototype members when looked up.
+ const { data: tagKeys = [] } = useTagKeysQuery();
+ const tagDescriptions = useMemo(
+ () =>
+ new Map(
+ tagKeys.map((tagKey): [string, string | null] => [
+ tagKey.key,
+ tagKey.description,
+ ]),
+ ),
+ [tagKeys],
+ );
+
+ // One batch fetch of current tags for every workflow on the page (no N+1).
+ const workflowIds = useMemo(
+ () => workflows.map((workflow) => workflow.workflow_permanent_id),
+ [workflows],
+ );
+ const { data: workflowTagsMap = {} } = useWorkflowTagsBatchQuery(workflowIds);
+
+ // Tags observed on the page for editor/filter suggestions: grouped values per
+ // key plus standalone labels. Maps avoid prototype-key collisions.
+ const { valueSuggestionsByKey, labelSuggestions } = useMemo(() => {
+ const collected = new Map<string, Set<string>>();
+ const labels = new Set<string>();
+ for (const tags of Object.values(workflowTagsMap)) {
+ for (const tag of tags) {
+ if (tag.key === null) {
+ labels.add(tag.value);
+ continue;
+ }
+ let values = collected.get(tag.key);
+ if (!values) {
+ values = new Set<string>();
+ collected.set(tag.key, values);
+ }
+ values.add(tag.value);
+ }
+ }
+ const byKey = new Map<string, string[]>();
+ for (const [key, values] of collected) {
+ byKey.set(key, [...values].sort());
+ }
+ return {
+ valueSuggestionsByKey: byKey,
+ labelSuggestions: [...labels].sort(),
+ };
+ }, [workflowTagsMap]);
+
+ const { matchesParameter } = useKeywordSearch(debouncedSearch);
+ const { expandedRows, toggleExpanded: toggleParametersExpanded } =
+ useParameterExpansion();
+
+ function handleRowClick(
+ event: React.MouseEvent<HTMLTableCellElement>,
+ workflowPermanentId: string,
+ ) {
+ if (event.ctrlKey || event.metaKey) {
+ window.open(
+ window.location.origin + `/workflows/${workflowPermanentId}/runs`,
+ "_blank",
+ "noopener,noreferrer",
+ );
+ return;
+ }
+ navigate(`/workflows/${workflowPermanentId}/runs`);
+ }
+
+ function handleIconClick(
+ event: React.MouseEvent<HTMLButtonElement>,
+ path: string,
+ ) {
+ if (event.ctrlKey || event.metaKey) {
+ window.open(
+ window.location.origin + path,
+ "_blank",
+ "noopener,noreferrer",
+ );
+ return;
+ }
+ navigate(path);
+ }
+
+ function setParamPatch(patch: Record<string, string>) {
+ const params = new URLSearchParams(searchParams);
+ Object.entries(patch).forEach(([k, v]) => params.set(k, v));
+ setSearchParams(params, { replace: true });
+ }
+
+ function handlePreviousPage() {
+ if (page === 1) return;
+ setParamPatch({ page: String(page - 1) });
+ }
+
+ function handleNextPage() {
+ if (isNextDisabled) return;
+ setParamPatch({ page: String(page + 1) });
+ }
+
+ // Show importing agents from polling hook (only on page 1)
+ const displayWorkflows = useMemo(() => {
+ const importingOnly = activeImports.filter(
+ (imp) => imp.status === "importing",
+ );
+
+ if (page === 1 && importingOnly.length > 0) {
+ return [...importingOnly, ...workflows];
+ }
+ return workflows;
+ }, [activeImports, workflows, page]);
+
+ const selectableWorkflows = useMemo(
+ () =>
+ displayWorkflows.filter((workflow) => workflow.status !== "importing"),
+ [displayWorkflows],
+ );
+
+ const showCheckbox = selectableWorkflows.length > 0;
+ const columnCount = showCheckbox ? 6 : 5;
+
+ const {
+ selected,
+ selectedItems: selectedWorkflows,
+ isSelected,
+ allSelected,
+ someSelected,
+ indexById: selectableIndexById,
+ handleSelect,
+ toggleSelectAll,
+ clearSelection,
+ replaceSelection,
+ } = useRowSelection({
+ items: selectableWorkflows,
+ getId: (workflow) => workflow.workflow_permanent_id,
+ // Keyed on the folder SLUG (user navigation), not the derived id, so folder
+ // list refetches can never wipe an in-progress selection.
+ resetKey: JSON.stringify([page, folderSlug, debouncedSearch]),
+ // Page-size changes keep the selection; only the shift anchor resets.
+ anchorResetKey: itemsPerPage,
+ });
+
+ async function handleBulkMoveToFolder(folderId: string | null) {
+ if (selectedWorkflows.length === 0) {
+ return;
+ }
+
+ setIsBulkOperating(true);
+ try {
+ const client = await getClient(credentialGetter);
+ const results = await runWithConcurrency(
+ selectedWorkflows.map(
+ (workflow) => () =>
+ client.put(`/workflows/${workflow.workflow_permanent_id}/folder`, {
+ folder_id: folderId,
+ }),
+ ),
+ BULK_CONCURRENCY_LIMIT,
+ );
+ const succeeded = results.filter((r) => r.status === "fulfilled").length;
+ bulkResultToast({
+ succeeded,
+ total: selectedWorkflows.length,
+ results,
+ successTitle: (count) =>
+ folderId
+ ? `Moved ${count} agent${count !== 1 ? "s" : ""} to folder.`
+ : `Removed ${count} agent${count !== 1 ? "s" : ""} from folder.`,
+ failureTitle: (count) =>
+ folderId
+ ? `Failed to move ${count} agent${count !== 1 ? "s" : ""} to folder.`
+ : `Failed to remove ${count} agent${count !== 1 ? "s" : ""} from folder.`,
+ partialTitle: (successCount, failedCount) =>
+ folderId
+ ? `Moved ${successCount} agent${successCount !== 1 ? "s" : ""} to folder. ${failedCount} failed.`
+ : `Removed ${successCount} agent${successCount !== 1 ? "s" : ""} from folder. ${failedCount} failed.`,
+ });
+ if (succeeded === selectedWorkflows.length) {
+ clearSelection();
+ }
+ if (succeeded > 0) {
+ queryClient.invalidateQueries({ queryKey: ["workflows"] });
+ queryClient.invalidateQueries({ queryKey: ["folders"] });
+ }
+ } finally {
+ setIsBulkOperating(false);
+ }
+ }
+
+ async function handleBulkDeleteConfirm() {
+ // Snapshot from dialog-open time; the live selection may have changed since.
+ const targets = bulkDeleteDialog.targets;
+ if (targets.length === 0) {
+ return;
+ }
+
+ setIsBulkOperating(true);
+ try {
+ const client = await getClient(credentialGetter);
+ const results = await runWithConcurrency(
+ targets.map(
+ (workflowId) => () => client.delete(`/workflows/${workflowId}`),
+ ),
+ BULK_CONCURRENCY_LIMIT,
+ );
+
+ const succeededIds: string[] = [];
+ const failedIds = new Set<string>();
+ results.forEach((result, index) => {
+ const workflowId = targets[index]!;
+ if (result.status === "fulfilled") {
+ succeededIds.push(workflowId);
+ useNodeCollapseStore.getState().pruneWorkflow(workflowId);
+ } else {
+ failedIds.add(workflowId);
+ }
+ });
+
+ const succeeded = succeededIds.length;
+ const failed = failedIds.size;
+
+ bulkResultToast({
+ succeeded,
+ total: targets.length,
+ results,
+ successTitle: (count) =>
+ `${count} agent${count !== 1 ? "s" : ""} deleted successfully.`,
+ failureTitle: (count) =>
+ `Failed to delete ${count} agent${count !== 1 ? "s" : ""}.`,
+ partialTitle: (successCount, failedCount) =>
+ `Deleted ${successCount} agent${successCount !== 1 ? "s" : ""}. ${failedCount} failed.`,
+ });
+ // Deletions shift row indices; replace/clear also resets the shift anchor.
+ if (failed === 0) {
+ clearSelection();
+ } else {
+ replaceSelection(failedIds);
+ }
+
+ if (succeeded > 0) {
+ queryClient.invalidateQueries({ queryKey: ["workflows"] });
+ queryClient.invalidateQueries({ queryKey: ["folders"] });
+ }
+ } finally {
+ setIsBulkOperating(false);
+ setBulkDeleteDialog({ open: false, targets: [] });
+ }
+ }
+
+ return (
+ <div className="space-y-10">
+ <div className="flex h-32 justify-between gap-6">
+ <div className="space-y-5">
+ <div className="flex items-center gap-2">
+ <LightningBoltIcon className="size-6" />
+ <h1 className="text-2xl">Agents</h1>
+ </div>
+ <p className="text-sm leading-6 text-muted-foreground">
+ Create your own complex agents by connecting web agents together.
+ Define a series of actions, set it, and forget it.
+ </p>
+ </div>
+ <div className="flex gap-5">
+ <NarrativeCard
+ index={1}
+ description="Save browser sessions and reuse them in subsequent runs"
+ />
+ <NarrativeCard
+ index={2}
+ description="Connect multiple agents together to carry out complex objectives"
+ />
+ <NarrativeCard
+ index={3}
+ description="Execute non-browser tasks such as sending emails"
+ />
+ </div>
+ </div>
+ <div className="space-y-4">
+ {/* Folders Section */}
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-3">
+ <h2 className="text-lg font-semibold">Folders</h2>
+ <Button
+ variant="link"
+ size="sm"
+ className="h-auto p-0 text-blue-600 dark:text-blue-400"
+ onClick={() => setIsCreateFolderOpen(true)}
+ >
+ + New folder
+ </Button>
+ </div>
+ {allFolders.length > 5 && (
+ <Button
+ variant="link"
+ size="sm"
+ className="text-blue-600 dark:text-blue-400"
+ onClick={() => setIsViewAllFoldersOpen(true)}
+ >
+ View all
+ </Button>
+ )}
+ </div>
+
+ {recentFolders.length > 0 ? (
+ <div className="grid grid-cols-5 gap-4">
+ {recentFolders.map((folder) => (
+ <FolderCard
+ key={folder.folder_id}
+ folder={folder}
+ isSelected={selectedFolderId === folder.folder_id}
+ onClick={() =>
+ setSelectedFolderId(
+ selectedFolderId === folder.folder_id
+ ? null
+ : folder.folder_id,
+ )
+ }
+ />
+ ))}
+ </div>
+ ) : (
+ <div className="rounded-lg border border-slate-200 bg-slate-elevation1 py-6 text-center dark:border-slate-700">
+ <div className="mx-auto max-w-md">
+ <FolderIcon className="mx-auto mb-3 h-10 w-10 text-blue-400 opacity-50" />
+ <h3 className="mb-2 text-slate-900 dark:text-slate-100">
+ Organize Your Agents with Folders
+ </h3>
+ <p className="mb-4 text-sm text-slate-500 dark:text-slate-400">
+ Keep your agents organized by creating folders. Group related
+ agents together by project, team, or agent type for easier
+ management.
+ </p>
+ <Button
+ variant="link"
+ size="sm"
+ className="h-auto p-0 text-blue-600 dark:text-blue-400"
+ onClick={() => setIsCreateFolderOpen(true)}
+ >
+ <PlusIcon className="mr-2 h-4 w-4" />
+ Create Your First Folder
+ </Button>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Agents Section */}
+ <header className="flex items-center justify-between">
+ <h1 className="text-xl">My Agents</h1>
+ {selectedFolderId && (
+ <Button
+ variant="link"
+ size="sm"
+ className="h-auto p-0 text-blue-600 dark:text-blue-400"
+ onClick={() => setSelectedFolderId(null)}
+ >
+ View all agents
+ </Button>
+ )}
+ </header>
+ <div className="flex justify-between">
+ <div className="flex items-center gap-3">
+ <TableSearchInput
+ value={search}
+ onChange={(value) => {
+ setSearch(value);
+ setParamPatch({ page: "1" });
+ }}
+ placeholder="Search by title or input..."
+ className="w-48 lg:w-72"
+ />
+ <WorkflowTagFilter
+ tagKeys={tagKeys}
+ value={tagFilters}
+ onChange={setTagFilters}
+ labelSuggestions={labelSuggestions}
+ valueSuggestionsByKey={valueSuggestionsByKey}
+ />
+ </div>
+ <div className="flex items-center gap-4">
+ <Link
+ to="/discover"
+ className="text-sm text-muted-foreground hover:text-foreground"
+ >
+ Or start from a description →
+ </Link>
+ <ImportWorkflowButton
+ onImportStart={startPolling}
+ selectedFolderId={selectedFolderId}
+ />
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger asChild>
+ <Button disabled={createWorkflowMutation.isPending}>
+ {createWorkflowMutation.isPending ? (
+ <ReloadIcon className="mr-2 h-4 w-4 animate-spin" />
+ ) : (
+ <PlusIcon className="mr-2 h-4 w-4" />
+ )}
+ Create
+ <ChevronDownIcon className="ml-2 h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onSelect={() => {
+ createWorkflowMutation.mutate({
+ ...defaultWorkflowRequest,
+ folder_id: selectedFolderId,
+ _via: "blank",
+ });
+ }}
+ >
+ <PlusIcon className="mr-2 h-4 w-4" />
+ Blank Agent
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onSelect={() => setIsTemplateDialogOpen(true)}
+ >
+ <BookmarkFilledIcon className="mr-2 h-4 w-4" />
+ From Template
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+ <div className="overflow-hidden rounded-lg border border-border">
+ <Table className="table-fixed">
+ <TableHeader>
+ <TableRow className="group/header">
+ {showCheckbox && (
+ <SelectionHeaderCheckboxCell
+ className="w-[3%]"
+ allSelected={allSelected}
+ someSelected={someSelected}
+ hasSelection={selected.size > 0}
+ onToggleAll={toggleSelectAll}
+ ariaLabel="Select all agents"
+ />
+ )}
+ <TableHead className={showCheckbox ? "w-[22%]" : "w-[25%]"}>
+ ID
+ </TableHead>
+ <TableHead className={showCheckbox ? "w-[27%]" : "w-[30%]"}>
+ Title
+ </TableHead>
+ <TableHead className="w-[15%]">Folder</TableHead>
+ <TableHead className="w-[15%]">Created At</TableHead>
+ <TableHead className="w-[15%] text-right">Actions</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {isFetching &&
+ !isPlaceholderData &&
+ displayWorkflows.length === 0 ? (
+ // Show skeleton rows only on initial load (not during search refinement)
+ Array.from({ length: 10 }).map((_, index) => (
+ <TableRow key={`skeleton-${index}`}>
+ {showCheckbox && (
+ <TableCell>
+ <Skeleton className="h-4 w-4" />
+ </TableCell>
+ )}
+ <TableCell>
+ <Skeleton className="h-5 w-full" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-full" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-20" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-32" />
+ </TableCell>
+ <TableCell>
+ <div className="flex justify-end gap-2">
+ <Skeleton className="h-8 w-8 rounded" />
+ <Skeleton className="h-8 w-8 rounded" />
+ <Skeleton className="h-8 w-8 rounded" />
+ <Skeleton className="h-8 w-8 rounded" />
+ </div>
+ </TableCell>
+ </TableRow>
+ ))
+ ) : displayWorkflows?.length === 0 ? (
+ <TableMessageRow colSpan={columnCount}>
+ No agents found
+ </TableMessageRow>
+ ) : (
+ displayWorkflows?.map((workflow) => {
+ const parameterItems = workflow.workflow_definition.parameters
+ .filter((p) => p.parameter_type !== "output")
+ .map((param) => ({
+ key: param.key,
+ value:
+ param.parameter_type === "workflow"
+ ? (param.default_value ?? "")
+ : "",
+ description: param.description ?? null,
+ }));
+ const hasParameters = parameterItems.length > 0;
+ const isExpanded = expandedRows.has(
+ workflow.workflow_permanent_id,
+ );
+ const isRowSelected = isSelected(
+ workflow.workflow_permanent_id,
+ );
+ // Check if this is an importing agent
+ const isUploading = workflow.status === "importing";
+ const workflowTags =
+ workflowTagsMap[workflow.workflow_permanent_id];
+ const selectableIndex = isUploading
+ ? -1
+ : (selectableIndexById.get(
+ workflow.workflow_permanent_id,
+ ) ?? -1);
+
+ return (
+ <React.Fragment key={workflow.workflow_permanent_id}>
+ {/* Main workflow row */}
+ {isUploading ? (
+ <TableRow className="opacity-70">
+ {showCheckbox && <TableCell />}
+ <TableCell colSpan={2}>
+ <div className="flex min-w-0 items-center gap-2">
+ <ReloadIcon className="h-4 w-4 shrink-0 animate-spin text-blue-400" />
+ <span className="truncate" title={workflow.title}>
+ {workflow.title}
+ </span>
+ </div>
+ </TableCell>
+ <TableCell>
+ <span className="text-muted-foreground">-</span>
+ </TableCell>
+ <TableCell className="text-muted-foreground">
+ {compactLocalDateTime(workflow.created_at)}
+ </TableCell>
+ <TableCell>
+ <div className="flex justify-end gap-0.5">
+ {selected.size === 0 && (
+ <Button size="icon" variant="ghost" disabled>
+ <FolderIcon className="h-4 w-4" />
+ </Button>
+ )}
+ <Button size="icon" variant="ghost" disabled>
+ <Pencil2Icon className="h-4 w-4" />
+ </Button>
+ <Button size="icon" variant="ghost" disabled>
+ <PlayIcon className="h-4 w-4" />
+ </Button>
+ {selected.size === 0 && (
+ <Button size="icon" variant="ghost" disabled>
+ <DotsHorizontalIcon className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ </TableCell>
+ </TableRow>
+ ) : (
+ <TableRow
+ className="group/row cursor-pointer select-none"
+ data-state={isRowSelected ? "selected" : undefined}
+ >
+ {showCheckbox && (
+ <SelectionCheckboxCell
+ className="select-none"
+ index={selectableIndex}
+ checked={isRowSelected}
+ hasSelection={selected.size > 0}
+ onSelect={handleSelect}
+ ariaLabel={`Select ${workflow.title}`}
+ />
+ )}
+ <TableCell
+ onClick={(event) => {
+ handleRowClick(
+ event,
+ workflow.workflow_permanent_id,
+ );
+ }}
+ >
+ <div
+ className="truncate font-mono text-xs text-muted-foreground"
+ title={workflow.workflow_permanent_id}
+ >
+ <HighlightText
+ text={workflow.workflow_permanent_id}
+ query={debouncedSearch}
+ />
+ </div>
+ </TableCell>
+ <TableCell
+ onClick={(event) => {
+ handleRowClick(
+ event,
+ workflow.workflow_permanent_id,
+ );
+ }}
+ >
+ <div className="flex min-w-0 flex-col gap-1">
+ <div className="flex min-w-0 items-center gap-2">
+ <span
+ className="truncate"
+ title={workflow.title}
+ >
+ <HighlightText
+ text={workflow.title}
+ query={debouncedSearch}
+ />
+ </span>
+ {workflow.is_template && (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <BookmarkFilledIcon className="h-3.5 w-3.5 shrink-0 text-blue-500" />
+ </TooltipTrigger>
+ <TooltipContent>Template</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ )}
+ </div>
+ {workflowTags && workflowTags.length > 0 ? (
+ <TagChipList
+ tags={workflowTags}
+ descriptions={tagDescriptions}
+ />
+ ) : null}
+ </div>
+ </TableCell>
+ <TableCell
+ onClick={(event) => {
+ handleRowClick(
+ event,
+ workflow.workflow_permanent_id,
+ );
+ }}
+ >
+ {workflow.folder_id ? (
+ <div className="flex min-w-0 items-center gap-1.5">
+ <FolderIcon className="h-3.5 w-3.5 shrink-0 text-blue-400" />
+ <span
+ className="truncate text-sm"
+ title={
+ foldersMap.get(workflow.folder_id)?.title ||
+ workflow.folder_id
+ }
+ >
+ <HighlightText
+ text={
+ foldersMap.get(workflow.folder_id)
+ ?.title || workflow.folder_id
+ }
+ query={debouncedSearch}
+ />
+ </span>
+ </div>
+ ) : (
+ <span className="text-muted-foreground">-</span>
+ )}
+ </TableCell>
+ <TableCell
+ onClick={(event) => {
+ handleRowClick(
+ event,
+ workflow.workflow_permanent_id,
+ );
+ }}
+ className="text-muted-foreground"
+ title={basicTimeFormat(workflow.created_at)}
+ >
+ {compactLocalDateTime(workflow.created_at)}
+ </TableCell>
+ <TableCell>
+ <div className="flex justify-end gap-0.5">
+ {/* Folder, tags, and the row menu yield to the bulk bar while any selection is active; Edit and Run stay. */}
+ {selected.size === 0 && (
+ <>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <WorkflowFolderSelector
+ workflowPermanentId={
+ workflow.workflow_permanent_id
+ }
+ currentFolderId={workflow.folder_id}
+ disabled={isBulkOperating}
+ />
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ Assign to Folder
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ <WorkflowTagEditor
+ workflowPermanentId={
+ workflow.workflow_permanent_id
+ }
+ tags={workflowTags ?? []}
+ tagKeys={tagKeys}
+ labelSuggestions={labelSuggestions}
+ valueSuggestionsByKey={
+ valueSuggestionsByKey
+ }
+ />
+ </>
+ )}
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ size="icon"
+ variant="ghost"
+ className="text-muted-foreground hover:text-foreground"
+ onClick={(event) => {
+ handleIconClick(
+ event,
+ `/workflows/${workflow.workflow_permanent_id}/build`,
+ );
+ }}
+ >
+ <Pencil2Icon className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ Open in Editor
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ size="icon"
+ variant="ghost"
+ className="text-cta hover:text-cta"
+ onClick={(event) => {
+ handleIconClick(
+ event,
+ `/workflows/${workflow.workflow_permanent_id}/run`,
+ );
+ }}
+ >
+ <PlayIcon className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ Create New Run
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ {selected.size === 0 && (
+ <WorkflowActions
+ workflow={workflow}
+ hasParameters={hasParameters}
+ parametersExpanded={isExpanded}
+ onToggleParameters={() =>
+ toggleParametersExpanded(
+ workflow.workflow_permanent_id,
+ )
+ }
+ />
+ )}
+ </div>
+ </TableCell>
+ </TableRow>
+ )}
+
+ {/* Expanded parameters section */}
+ {isExpanded && hasParameters && (
+ <TableRow
+ key={`${workflow.workflow_permanent_id}-params`}
+ >
+ <TableCell
+ colSpan={columnCount}
+ className="bg-slate-50 dark:bg-slate-900/50"
+ >
+ <ParameterDisplayInline
+ parameters={parameterItems}
+ searchQuery={debouncedSearch}
+ keywordMatchesParameter={matchesParameter}
+ />
+ </TableCell>
+ </TableRow>
+ )}
+ </React.Fragment>
+ );
+ })
+ )}
+ </TableBody>
+ </Table>
+ <div className="relative px-3 py-3">
+ <div className="absolute left-3 top-1/2 flex -translate-y-1/2 items-center gap-2 text-sm">
+ <span className="text-slate-400">Items per page</span>
+ <select
+ className="h-9 rounded-md border border-slate-300 bg-background px-3"
+ value={itemsPerPage}
+ onChange={(e) => {
+ const next = Number(e.target.value);
+ const params = new URLSearchParams(searchParams);
+ params.set("page_size", String(next));
+ params.set("page", "1");
+ setSearchParams(params, { replace: true });
+ }}
+ >
+ <option value={5}>5</option>
+ <option value={10}>10</option>
+ <option value={20}>20</option>
+ <option value={50}>50</option>
+ </select>
+ </div>
+ <Pagination className="pt-0">
+ <PaginationContent>
+ <PaginationItem>
+ <PaginationPrevious
+ className={cn({
+ "cursor-not-allowed opacity-50": page === 1,
+ })}
+ onClick={handlePreviousPage}
+ />
+ </PaginationItem>
+ <PaginationItem>
+ <PaginationLink>{page}</PaginationLink>
+ </PaginationItem>
+ <PaginationItem>
+ <PaginationNext
+ className={cn({
+ "cursor-not-allowed opacity-50": isNextDisabled,
+ })}
+ onClick={handleNextPage}
+ />
+ </PaginationItem>
+ </PaginationContent>
+ </Pagination>
+ </div>
+ </div>
+
+ {selectedWorkflows.length > 0 && (
+ <BulkActionBar
+ selectedWorkflows={selectedWorkflows}
+ isOperating={isBulkOperating}
+ onOperatingChange={setIsBulkOperating}
+ onClearSelection={clearSelection}
+ onDeleteRequest={() =>
+ setBulkDeleteDialog({
+ open: true,
+ targets: selectedWorkflows.map(
+ (workflow) => workflow.workflow_permanent_id,
+ ),
+ })
+ }
+ onMoveToFolder={handleBulkMoveToFolder}
+ tagKeys={tagKeys}
+ labelSuggestions={labelSuggestions}
+ valueSuggestionsByKey={valueSuggestionsByKey}
+ />
+ )}
+
+ <Dialog
+ open={bulkDeleteDialog.open}
+ onOpenChange={(open) => {
+ if (!open && !isBulkOperating) {
+ setBulkDeleteDialog({ open: false, targets: [] });
+ }
+ }}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>
+ Delete {bulkDeleteDialog.targets.length} Agent
+ {bulkDeleteDialog.targets.length === 1 ? "" : "s"}
+ </DialogTitle>
+ <DialogDescription>
+ Are you sure you want to delete{" "}
+ {bulkDeleteDialog.targets.length}{" "}
+ {bulkDeleteDialog.targets.length === 1 ? "agent" : "agents"}?
+ This action cannot be undone.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button
+ variant="secondary"
+ disabled={isBulkOperating}
+ onClick={() =>
+ setBulkDeleteDialog({ open: false, targets: [] })
+ }
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ disabled={isBulkOperating}
+ onClick={() => {
+ void handleBulkDeleteConfirm();
+ }}
+ >
+ {isBulkOperating ? "Deleting..." : "Delete"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ {/* Folder Dialogs */}
+ <CreateFolderDialog
+ open={isCreateFolderOpen}
+ onOpenChange={setIsCreateFolderOpen}
+ />
+ <ViewAllFoldersDialog
+ open={isViewAllFoldersOpen}
+ onOpenChange={setIsViewAllFoldersOpen}
+ selectedFolderId={selectedFolderId}
+ onFolderSelect={setSelectedFolderId}
+ />
+
+ {/* Template Dialog */}
+ <CreateFromTemplateDialog
+ open={isTemplateDialogOpen}
+ onOpenChange={setIsTemplateDialogOpen}
+ onSelectTemplate={(template) => {
+ const clonedWorkflow = convert({
+ ...template,
+ title: `${template.title} (copy)`,
+ });
+ createWorkflowMutation.mutate({
+ ...clonedWorkflow,
+ folder_id: selectedFolderId,
+ });
+ }}
+ />
+
+ <div data-hint="start-template">
+ <WorkflowTemplates />
+ </div>
+
+ {onboarding ? (
+ <OnboardingErrorBoundary
+ onError={() => OnboardingTelemetry.modalRenderError("dashboard")}
+ >
+ <GetStartedModal
+ hasWorkflows={ownedWorkflows.length > 0}
+ isLoading={ownedWorkflowsLoading}
+ />
+ </OnboardingErrorBoundary>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+export { WorkflowsFlat };
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowsTree.tsx b/skyvern-frontend/src/routes/workflows/WorkflowsTree.tsx
new file mode 100644
index 000000000..d9c72c086
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/WorkflowsTree.tsx
@@ -0,0 +1,1118 @@
+import { getClient } from "@/api/AxiosClient";
+import { GetStartedModal } from "@/components/onboarding/GetStartedModal";
+import { useOnboardingStateOptional } from "@/store/onboarding/useOnboardingState";
+import { OnboardingErrorBoundary } from "@/components/onboarding/OnboardingErrorBoundary";
+import { OnboardingTelemetry } from "@/util/onboarding/OnboardingTelemetry";
+import { Button } from "@/components/ui/button";
+import { SelectionHeaderCheckboxCell } from "@/components/SelectionCheckbox";
+import { useRowSelection } from "@/hooks/useRowSelection";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableMessageRow,
+ TableRow,
+} from "@/components/ui/table";
+import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import {
+ BULK_CONCURRENCY_LIMIT,
+ runWithConcurrency,
+} from "@/util/runWithConcurrency";
+import { bulkResultToast } from "@/util/bulkResultToast";
+import {
+ BookmarkFilledIcon,
+ ChevronDownIcon,
+ PlusIcon,
+ ReloadIcon,
+} from "@radix-ui/react-icons";
+import { FolderIcon } from "@/components/icons/FolderIcon";
+import {
+ useInfiniteQuery,
+ useQuery,
+ useQueryClient,
+} from "@tanstack/react-query";
+import React, {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { Link, useNavigate, useSearchParams } from "react-router-dom";
+import { useDebounce } from "use-debounce";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { NarrativeCard } from "./components/header/NarrativeCard";
+import { BulkActionBar } from "./components/BulkActionBar";
+import { CreateFolderDialog } from "./components/CreateFolderDialog";
+import { CreateFromTemplateDialog } from "./components/CreateFromTemplateDialog";
+import { FolderTreeNode } from "./components/tree/FolderTreeNode";
+import { WorkflowRow } from "./components/tree/WorkflowRow";
+import {
+ WorkflowsListContext,
+ type WorkflowsListContextValue,
+} from "./components/tree/WorkflowsListContext";
+import { useCreateWorkflowMutation } from "./hooks/useCreateWorkflowMutation";
+import { useInfiniteFoldersQuery } from "./hooks/useInfiniteFoldersQuery";
+import { useTagKeysQuery } from "./hooks/useTagKeysQuery";
+import { useWorkflowTagsBatchQuery } from "./hooks/useWorkflowTagsBatchQuery";
+import { useActiveImportsPolling } from "./hooks/useActiveImportsPolling";
+import { WorkflowTagFilter } from "./components/tagging/WorkflowTagFilter";
+import {
+ parseTagFilter,
+ serializeTagFilter,
+ type TagFilterTerm,
+} from "./types/tagTypes";
+import { ImportWorkflowButton } from "./ImportWorkflowButton";
+import { useNodeCollapseStore } from "./editor/collapse/useNodeCollapseStore";
+import { convert } from "./editor/workflowEditorUtils";
+import { WorkflowApiResponse } from "./types/workflowTypes";
+import { WorkflowTemplates } from "../discover/WorkflowTemplates";
+import { Skeleton } from "@/components/ui/skeleton";
+import { TableSearchInput } from "@/components/TableSearchInput";
+import { useKeywordSearch } from "./hooks/useKeywordSearch";
+import { useParameterExpansion } from "./hooks/useParameterExpansion";
+import { Folder } from "./types/folderTypes";
+import { getUniqueSlugForFolder } from "@/util/folderSlug";
+import { defaultWorkflowRequest } from "./defaultWorkflowRequest";
+
+const FOLDERS_PAGE_SIZE = 25;
+const AGENTS_PAGE_SIZE = 20;
+
+function WorkflowsTree() {
+ const credentialGetter = useCredentialGetter();
+ const queryClient = useQueryClient();
+ const navigate = useNavigate();
+ const createWorkflowMutation = useCreateWorkflowMutation();
+ const [searchParams, setSearchParams] = useSearchParams();
+ const [search, setSearch] = useState("");
+ const [debouncedSearch] = useDebounce(search, 250);
+ const [isBulkOperating, setIsBulkOperating] = useState(false);
+ const [bulkDeleteDialog, setBulkDeleteDialog] = useState<{
+ open: boolean;
+ targets: string[];
+ }>({ open: false, targets: [] });
+ // Folder slug from query param (e.g., /workflows?folder=my-folder-name).
+ // In the tree this is the "active" folder: highlighted, auto-expanded on load,
+ // and the default target for Create / Import.
+ const folderSlug = searchParams.get("folder");
+
+ // Tag filter from query param (e.g., /workflows?tags=env:prod,env:staging).
+ // The backend accepts both comma-separated pairs and repeated `tags` params,
+ // so read every occurrence. The serialized form is canonical (sorted) and is
+ // used for both the request and the query key so cache hits are
+ // order-independent.
+ const tagFilterParam = searchParams.getAll("tags").join(",");
+ const tagFilters = useMemo(
+ () => parseTagFilter(tagFilterParam),
+ [tagFilterParam],
+ );
+ const serializedTagFilter = serializeTagFilter(tagFilters);
+
+ const setTagFilters = useCallback(
+ (terms: TagFilterTerm[]) => {
+ const params = new URLSearchParams(searchParams);
+ const serialized = serializeTagFilter(terms);
+ if (serialized) {
+ params.set("tags", serialized);
+ } else {
+ params.delete("tags");
+ }
+ setSearchParams(params, { replace: true });
+ },
+ [searchParams, setSearchParams],
+ );
+
+ const [isCreateFolderOpen, setIsCreateFolderOpen] = useState(false);
+
+ // Template dialog state
+ const [isTemplateDialogOpen, setIsTemplateDialogOpen] = useState(false);
+
+ // Tree expansion state and the contents reported by each expanded folder, used
+ // to build one flat selection set spanning every open folder.
+ const [expandedFolderIds, setExpandedFolderIds] = useState<Set<string>>(
+ new Set(),
+ );
+ const [folderContents, setFolderContents] = useState<
+ Map<string, Array<WorkflowApiResponse>>
+ >(new Map());
+
+ // Poll for active imports
+ const { activeImports, startPolling } = useActiveImportsPolling();
+
+ // Fetch folders (paginated, recent-first) for the tree.
+ const {
+ data: foldersData,
+ isLoading: isFoldersLoading,
+ hasNextPage: hasNextFolders,
+ fetchNextPage: fetchNextFolders,
+ isFetchingNextPage: isFetchingNextFolders,
+ } = useInfiniteFoldersQuery({ page_size: FOLDERS_PAGE_SIZE });
+
+ const allFolders = useMemo(
+ () => foldersData?.pages.flatMap((folderPage) => folderPage) ?? [],
+ [foldersData],
+ );
+
+ // Create a memoized map of slugs to folders to avoid O(n²) lookups
+ const slugToFolderMap = useMemo(() => {
+ const map = new Map<string, Folder>();
+ for (const folder of allFolders) {
+ const slug = getUniqueSlugForFolder(folder, allFolders);
+ map.set(slug, folder);
+ }
+ return map;
+ }, [allFolders]);
+
+ // Folder state - derived from URL query param.
+ // Look up the folder by matching the slug (handles collision suffixes like my-folder-2)
+ const resolvedFolderIdBySlug = useRef<Map<string, string>>(new Map());
+ // Once every page has loaded, a lookup miss is a real deletion/rename rather
+ // than pagination not having reached the active folder yet.
+ const foldersListComplete = !isFoldersLoading && !hasNextFolders;
+ const selectedFolderId = useMemo(() => {
+ if (!folderSlug) return null;
+ const matchingFolder = slugToFolderMap.get(folderSlug);
+ if (matchingFolder) {
+ resolvedFolderIdBySlug.current.set(folderSlug, matchingFolder.folder_id);
+ return matchingFolder.folder_id;
+ }
+ if (foldersListComplete) {
+ resolvedFolderIdBySlug.current.delete(folderSlug);
+ return null;
+ }
+ // The folders list is paginated, so a refetch can transiently drop the
+ // active folder; reuse the last resolution instead of flapping to null.
+ return resolvedFolderIdBySlug.current.get(folderSlug) ?? null;
+ }, [folderSlug, slugToFolderMap, foldersListComplete]);
+
+ // Clear folder param if the folder slug is invalid (folder deleted/renamed).
+ useEffect(() => {
+ if (
+ folderSlug &&
+ !selectedFolderId &&
+ allFolders.length > 0 &&
+ foldersListComplete
+ ) {
+ const params = new URLSearchParams(searchParams);
+ params.delete("folder");
+ setSearchParams(params, { replace: true });
+ }
+ }, [
+ folderSlug,
+ selectedFolderId,
+ allFolders.length,
+ foldersListComplete,
+ searchParams,
+ setSearchParams,
+ ]);
+
+ // Update folder query param (active folder). Does not reset pagination — the
+ // folder no longer filters the agent list, it only highlights/targets.
+ const setSelectedFolderId = (folderId: string | null) => {
+ const params = new URLSearchParams(searchParams);
+ if (folderId) {
+ const folder = allFolders.find((f) => f.folder_id === folderId);
+ if (folder) {
+ const slug = getUniqueSlugForFolder(folder, allFolders);
+ params.set("folder", slug);
+ setSearchParams(params, { replace: true });
+ return;
+ }
+ }
+ params.delete("folder");
+ setSearchParams(params, { replace: true });
+ };
+
+ // Auto-expand a deep-linked / active folder exactly once so a manual collapse
+ // afterwards sticks.
+ const deepLinkExpandedRef = useRef<string | null>(null);
+ useEffect(() => {
+ if (selectedFolderId && deepLinkExpandedRef.current !== selectedFolderId) {
+ deepLinkExpandedRef.current = selectedFolderId;
+ setExpandedFolderIds((prev) => {
+ if (prev.has(selectedFolderId)) return prev;
+ const next = new Set(prev);
+ next.add(selectedFolderId);
+ return next;
+ });
+ }
+ }, [selectedFolderId]);
+
+ const toggleFolderExpanded = useCallback((folderId: string) => {
+ setExpandedFolderIds((prev) => {
+ const next = new Set(prev);
+ if (next.has(folderId)) {
+ next.delete(folderId);
+ } else {
+ next.add(folderId);
+ }
+ return next;
+ });
+ }, []);
+
+ const registerFolderContents = useCallback(
+ (folderId: string, workflows: Array<WorkflowApiResponse>) => {
+ setFolderContents((prev) => {
+ const existing = prev.get(folderId);
+ if ((existing?.length ?? 0) === 0 && workflows.length === 0) {
+ return prev;
+ }
+ const next = new Map(prev);
+ if (workflows.length === 0) {
+ next.delete(folderId);
+ } else {
+ next.set(folderId, workflows);
+ }
+ return next;
+ });
+ },
+ [],
+ );
+
+ const handleCreateAgentInFolder = useCallback(
+ (folderId: string) => {
+ if (createWorkflowMutation.isPending) {
+ return;
+ }
+ createWorkflowMutation.mutate({
+ ...defaultWorkflowRequest,
+ folder_id: folderId,
+ _via: "blank",
+ });
+ },
+ [createWorkflowMutation],
+ );
+
+ // Create folders map for O(1) lookup
+ const foldersMap = useMemo(() => {
+ return new Map(allFolders.map((f) => [f.folder_id, f]));
+ }, [allFolders]);
+
+ // Infinite "Load more" list. Folders no longer filter this query, so it
+ // returns every agent (foldered + ungrouped); ungrouped are derived below and
+ // accumulate across pages, which keeps "Load more" coherent for the root list
+ // (a page-number pager over the mixed list would scatter ungrouped agents).
+ const {
+ data: workflowsData,
+ isLoading: isWorkflowsLoading,
+ fetchNextPage: fetchMoreAgents,
+ hasNextPage: hasMoreAgents,
+ isFetchingNextPage: isFetchingMoreAgents,
+ isPlaceholderData: isAgentsPlaceholderData,
+ } = useInfiniteQuery<Array<WorkflowApiResponse>>({
+ queryKey: ["workflows", "list", debouncedSearch, serializedTagFilter],
+ queryFn: async ({ pageParam }) => {
+ const client = await getClient(credentialGetter);
+ const params = new URLSearchParams();
+ params.append("page", String(pageParam));
+ params.append("page_size", String(AGENTS_PAGE_SIZE));
+ params.append("only_workflows", "true");
+ if (debouncedSearch) {
+ params.append("search_key", debouncedSearch);
+ }
+ if (serializedTagFilter) {
+ params.append("tags", serializedTagFilter);
+ }
+ return client
+ .get(`/workflows`, { params })
+ .then((response) => response.data);
+ },
+ getNextPageParam: (lastPage, allPages) =>
+ lastPage.length === AGENTS_PAGE_SIZE ? allPages.length + 1 : undefined,
+ initialPageParam: 1,
+ placeholderData: (previousData) => previousData,
+ });
+
+ const workflows = useMemo(
+ () => workflowsData?.pages.flat() ?? [],
+ [workflowsData],
+ );
+
+ // unfiltered "owns any workflow" check; the filtered/paginated list above can read empty for a user who has workflows
+ const { data: ownedWorkflows = [], isLoading: ownedWorkflowsLoading } =
+ useQuery<Array<WorkflowApiResponse>>({
+ queryKey: ["workflows", "exists"],
+ queryFn: async () => {
+ const client = await getClient(credentialGetter);
+ const params = new URLSearchParams();
+ params.append("page", "1");
+ params.append("page_size", "1");
+ params.append("only_workflows", "true");
+ return client
+ .get(`/workflows`, { params })
+ .then((response) => response.data);
+ },
+ });
+
+ const onboarding = useOnboardingStateOptional();
+
+ // Tag-key registry: supplies chip-hover descriptions and the filter's key list.
+ const { data: tagKeys = [] } = useTagKeysQuery();
+ const tagDescriptions = useMemo(
+ () =>
+ new Map(
+ tagKeys.map((tagKey): [string, string | null] => [
+ tagKey.key,
+ tagKey.description,
+ ]),
+ ),
+ [tagKeys],
+ );
+
+ // One batch fetch of current tags for every workflow on screen (no N+1) -
+ // the main page list plus the contents of every expanded folder.
+ const workflowIds = useMemo(() => {
+ const ids = new Set<string>();
+ for (const workflow of workflows) {
+ ids.add(workflow.workflow_permanent_id);
+ }
+ for (const contents of folderContents.values()) {
+ for (const workflow of contents) {
+ ids.add(workflow.workflow_permanent_id);
+ }
+ }
+ return Array.from(ids);
+ }, [workflows, folderContents]);
+ const { data: workflowTagsMap = {} } = useWorkflowTagsBatchQuery(workflowIds);
+
+ // Tags observed on the page for editor/filter suggestions: grouped values per
+ // key plus standalone labels. Maps avoid prototype-key collisions.
+ const { valueSuggestionsByKey, labelSuggestions } = useMemo(() => {
+ const collected = new Map<string, Set<string>>();
+ const labels = new Set<string>();
+ for (const tags of Object.values(workflowTagsMap)) {
+ for (const tag of tags) {
+ if (tag.key === null) {
+ labels.add(tag.value);
+ continue;
+ }
+ let values = collected.get(tag.key);
+ if (!values) {
+ values = new Set<string>();
+ collected.set(tag.key, values);
+ }
+ values.add(tag.value);
+ }
+ }
+ const byKey = new Map<string, string[]>();
+ for (const [key, values] of collected) {
+ byKey.set(key, [...values].sort());
+ }
+ return {
+ valueSuggestionsByKey: byKey,
+ labelSuggestions: [...labels].sort(),
+ };
+ }, [workflowTagsMap]);
+
+ const { matchesParameter } = useKeywordSearch(debouncedSearch);
+ const { expandedRows, toggleExpanded: toggleParametersExpanded } =
+ useParameterExpansion();
+
+ function handleRowClick(
+ event: React.MouseEvent<HTMLTableCellElement>,
+ workflowPermanentId: string,
+ ) {
+ if (event.ctrlKey || event.metaKey) {
+ window.open(
+ window.location.origin + `/workflows/${workflowPermanentId}/runs`,
+ "_blank",
+ "noopener,noreferrer",
+ );
+ return;
+ }
+ navigate(`/workflows/${workflowPermanentId}/runs`);
+ }
+
+ function handleIconClick(
+ event: React.MouseEvent<HTMLButtonElement>,
+ path: string,
+ ) {
+ if (event.ctrlKey || event.metaKey) {
+ window.open(
+ window.location.origin + path,
+ "_blank",
+ "noopener,noreferrer",
+ );
+ return;
+ }
+ navigate(path);
+ }
+
+ // A search term or tag filter flattens the tree back into a plain, complete
+ // result list (folder hierarchy is not meaningful while filtering).
+ const isFilterActive =
+ debouncedSearch.trim().length > 0 || serializedTagFilter.length > 0;
+
+ const importingOnly = useMemo(
+ () => activeImports.filter((imp) => imp.status === "importing"),
+ [activeImports],
+ );
+
+ const ungroupedWorkflows = useMemo(
+ () => workflows.filter((workflow) => !workflow.folder_id),
+ [workflows],
+ );
+
+ // Flat (filter) mode: the loaded list with importing placeholders pinned on top.
+ const displayWorkflows = useMemo(() => {
+ if (importingOnly.length > 0) {
+ return [...importingOnly, ...workflows];
+ }
+ return workflows;
+ }, [importingOnly, workflows]);
+
+ // Tree mode: ungrouped agents render at the root, below the folders.
+ const treeUngroupedWorkflows = useMemo(() => {
+ if (importingOnly.length > 0) {
+ return [...importingOnly, ...ungroupedWorkflows];
+ }
+ return ungroupedWorkflows;
+ }, [importingOnly, ungroupedWorkflows]);
+
+ // The set of workflows currently on screen, top-to-bottom, so checkbox /
+ // shift-click selection works across folders and the ungrouped section.
+ const visibleWorkflows = useMemo(() => {
+ if (isFilterActive) {
+ return displayWorkflows;
+ }
+ const result: Array<WorkflowApiResponse> = [];
+ for (const folder of allFolders) {
+ if (expandedFolderIds.has(folder.folder_id)) {
+ const contents = folderContents.get(folder.folder_id);
+ if (contents) {
+ result.push(...contents);
+ }
+ }
+ }
+ result.push(...treeUngroupedWorkflows);
+ return result;
+ }, [
+ isFilterActive,
+ displayWorkflows,
+ allFolders,
+ expandedFolderIds,
+ folderContents,
+ treeUngroupedWorkflows,
+ ]);
+
+ const selectionItems = useMemo(
+ () =>
+ visibleWorkflows.filter((workflow) => workflow.status !== "importing"),
+ [visibleWorkflows],
+ );
+
+ const showCheckbox = isFilterActive
+ ? selectionItems.length > 0
+ : allFolders.length > 0 || selectionItems.length > 0;
+ const columnCount = showCheckbox ? 6 : 5;
+
+ const {
+ selected,
+ selectedItems: selectedWorkflows,
+ isSelected,
+ allSelected,
+ someSelected,
+ indexById: selectableIndexById,
+ handleSelect,
+ toggleSelectAll,
+ clearSelection,
+ replaceSelection,
+ } = useRowSelection({
+ items: selectionItems,
+ getId: (workflow) => workflow.workflow_permanent_id,
+ resetKey: JSON.stringify([debouncedSearch, serializedTagFilter]),
+ // The shift-click anchor is a positional index into the visible rows, so it
+ // must reset whenever that order changes (expand/collapse, lazy load, load
+ // more) or a stale anchor would select the wrong range.
+ anchorResetKey: JSON.stringify(
+ selectionItems.map((workflow) => workflow.workflow_permanent_id),
+ ),
+ });
+
+ const handleFolderClick = (folderId: string) => {
+ const willExpand = !expandedFolderIds.has(folderId);
+ toggleFolderExpanded(folderId);
+ if (willExpand) {
+ setSelectedFolderId(folderId);
+ return;
+ }
+ // Collapsing hides this folder's rows; drop any of them from the selection
+ // so the selection set always matches what the user can see and act on.
+ const contents = folderContents.get(folderId);
+ if (contents && contents.length > 0) {
+ const next = new Set(selected);
+ let changed = false;
+ for (const workflow of contents) {
+ if (next.delete(workflow.workflow_permanent_id)) {
+ changed = true;
+ }
+ }
+ if (changed) {
+ replaceSelection(next);
+ }
+ }
+ if (selectedFolderId === folderId) {
+ setSelectedFolderId(null);
+ }
+ };
+
+ async function handleBulkMoveToFolder(folderId: string | null) {
+ if (selectedWorkflows.length === 0) {
+ return;
+ }
+
+ setIsBulkOperating(true);
+ try {
+ const client = await getClient(credentialGetter);
+ const results = await runWithConcurrency(
+ selectedWorkflows.map(
+ (workflow) => () =>
+ client.put(`/workflows/${workflow.workflow_permanent_id}/folder`, {
+ folder_id: folderId,
+ }),
+ ),
+ BULK_CONCURRENCY_LIMIT,
+ );
+ const succeeded = results.filter((r) => r.status === "fulfilled").length;
+ bulkResultToast({
+ succeeded,
+ total: selectedWorkflows.length,
+ results,
+ successTitle: (count) =>
+ folderId
+ ? `Moved ${count} agent${count !== 1 ? "s" : ""} to folder.`
+ : `Removed ${count} agent${count !== 1 ? "s" : ""} from folder.`,
+ failureTitle: (count) =>
+ folderId
+ ? `Failed to move ${count} agent${count !== 1 ? "s" : ""} to folder.`
+ : `Failed to remove ${count} agent${count !== 1 ? "s" : ""} from folder.`,
+ partialTitle: (successCount, failedCount) =>
+ folderId
+ ? `Moved ${successCount} agent${successCount !== 1 ? "s" : ""} to folder. ${failedCount} failed.`
+ : `Removed ${successCount} agent${successCount !== 1 ? "s" : ""} from folder. ${failedCount} failed.`,
+ });
+ if (succeeded === selectedWorkflows.length) {
+ clearSelection();
+ }
+ if (succeeded > 0) {
+ queryClient.invalidateQueries({ queryKey: ["workflows"] });
+ queryClient.invalidateQueries({ queryKey: ["folders"] });
+ }
+ } finally {
+ setIsBulkOperating(false);
+ }
+ }
+
+ async function handleBulkDeleteConfirm() {
+ // Snapshot from dialog-open time; the live selection may have changed since.
+ const targets = bulkDeleteDialog.targets;
+ if (targets.length === 0) {
+ return;
+ }
+
+ setIsBulkOperating(true);
+ try {
+ const client = await getClient(credentialGetter);
+ const results = await runWithConcurrency(
+ targets.map(
+ (workflowId) => () => client.delete(`/workflows/${workflowId}`),
+ ),
+ BULK_CONCURRENCY_LIMIT,
+ );
+
+ const succeededIds: string[] = [];
+ const failedIds = new Set<string>();
+ results.forEach((result, index) => {
+ const workflowId = targets[index]!;
+ if (result.status === "fulfilled") {
+ succeededIds.push(workflowId);
+ useNodeCollapseStore.getState().pruneWorkflow(workflowId);
+ } else {
+ failedIds.add(workflowId);
+ }
+ });
+
+ const succeeded = succeededIds.length;
+ const failed = failedIds.size;
+
+ bulkResultToast({
+ succeeded,
+ total: targets.length,
+ results,
+ successTitle: (count) =>
+ `${count} agent${count !== 1 ? "s" : ""} deleted successfully.`,
+ failureTitle: (count) =>
+ `Failed to delete ${count} agent${count !== 1 ? "s" : ""}.`,
+ partialTitle: (successCount, failedCount) =>
+ `Deleted ${successCount} agent${successCount !== 1 ? "s" : ""}. ${failedCount} failed.`,
+ });
+ // Deletions shift row indices; replace/clear also resets the shift anchor.
+ if (failed === 0) {
+ clearSelection();
+ } else {
+ replaceSelection(failedIds);
+ }
+
+ if (succeeded > 0) {
+ queryClient.invalidateQueries({ queryKey: ["workflows"] });
+ queryClient.invalidateQueries({ queryKey: ["folders"] });
+ }
+ } finally {
+ setIsBulkOperating(false);
+ setBulkDeleteDialog({ open: false, targets: [] });
+ }
+ }
+
+ const listContextValue: WorkflowsListContextValue = {
+ showCheckbox,
+ columnCount,
+ debouncedSearch,
+ isBulkOperating,
+ selectedCount: selectedWorkflows.length,
+ foldersMap,
+ workflowTagsMap,
+ tagDescriptions,
+ tagKeys,
+ labelSuggestions,
+ valueSuggestionsByKey,
+ isSelected,
+ indexById: selectableIndexById,
+ handleSelect,
+ expandedRows,
+ toggleParametersExpanded,
+ matchesParameter,
+ handleRowClick,
+ handleIconClick,
+ };
+
+ const showFlatInitialSkeleton =
+ isFilterActive && isWorkflowsLoading && displayWorkflows.length === 0;
+ const showTreeInitialSkeleton =
+ !isFilterActive &&
+ (isFoldersLoading || isWorkflowsLoading) &&
+ allFolders.length === 0 &&
+ treeUngroupedWorkflows.length === 0;
+ const isEmpty =
+ !isFilterActive &&
+ !showTreeInitialSkeleton &&
+ allFolders.length === 0 &&
+ treeUngroupedWorkflows.length === 0;
+
+ function renderSkeletonRows() {
+ return Array.from({ length: 10 }).map((_, index) => (
+ <TableRow key={`skeleton-${index}`}>
+ {showCheckbox && (
+ <TableCell>
+ <Skeleton className="h-4 w-4" />
+ </TableCell>
+ )}
+ <TableCell>
+ <Skeleton className="h-5 w-full" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-full" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-20" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-32" />
+ </TableCell>
+ <TableCell>
+ <div className="flex justify-end gap-2">
+ <Skeleton className="h-8 w-8 rounded" />
+ <Skeleton className="h-8 w-8 rounded" />
+ <Skeleton className="h-8 w-8 rounded" />
+ <Skeleton className="h-8 w-8 rounded" />
+ </div>
+ </TableCell>
+ </TableRow>
+ ));
+ }
+
+ function renderLoadMoreAgentsRow() {
+ if (!hasMoreAgents) {
+ return null;
+ }
+ return (
+ <TableRow>
+ {showCheckbox && <TableCell />}
+ <TableCell colSpan={showCheckbox ? columnCount - 1 : columnCount}>
+ <Button
+ variant="link"
+ size="sm"
+ className="h-auto p-0 text-blue-600 dark:text-blue-400"
+ disabled={isFetchingMoreAgents || isAgentsPlaceholderData}
+ onClick={() => void fetchMoreAgents()}
+ >
+ {isFetchingMoreAgents ? (
+ <ReloadIcon className="mr-2 h-4 w-4 animate-spin" />
+ ) : null}
+ Load more agents
+ </Button>
+ </TableCell>
+ </TableRow>
+ );
+ }
+
+ function renderTableBody() {
+ if (isFilterActive) {
+ if (showFlatInitialSkeleton) {
+ return renderSkeletonRows();
+ }
+ if (displayWorkflows.length === 0) {
+ return (
+ <TableMessageRow colSpan={columnCount}>
+ No agents found
+ </TableMessageRow>
+ );
+ }
+ return (
+ <>
+ {displayWorkflows.map((workflow) => (
+ <WorkflowRow
+ key={workflow.workflow_permanent_id}
+ workflow={workflow}
+ />
+ ))}
+ {renderLoadMoreAgentsRow()}
+ </>
+ );
+ }
+
+ if (showTreeInitialSkeleton) {
+ return renderSkeletonRows();
+ }
+
+ if (isEmpty) {
+ return (
+ <TableMessageRow colSpan={columnCount}>
+ <div className="flex flex-col items-center gap-3 py-6">
+ <FolderIcon className="h-8 w-8 text-blue-400 opacity-50" />
+ <p className="text-sm text-muted-foreground">
+ No folders or agents yet. Create a folder to organize your work,
+ or create your first agent.
+ </p>
+ <Button
+ variant="link"
+ size="sm"
+ className="h-auto p-0 text-blue-600 dark:text-blue-400"
+ onClick={() => setIsCreateFolderOpen(true)}
+ >
+ <PlusIcon className="mr-1 h-4 w-4" />
+ Create folder
+ </Button>
+ </div>
+ </TableMessageRow>
+ );
+ }
+
+ return (
+ <>
+ {allFolders.map((folder) => (
+ <FolderTreeNode
+ key={folder.folder_id}
+ folder={folder}
+ isExpanded={expandedFolderIds.has(folder.folder_id)}
+ isActive={selectedFolderId === folder.folder_id}
+ onToggle={() => handleFolderClick(folder.folder_id)}
+ onContentsChange={registerFolderContents}
+ onCreateAgentInFolder={handleCreateAgentInFolder}
+ isCreatingAgent={createWorkflowMutation.isPending}
+ />
+ ))}
+ {hasNextFolders && (
+ <TableRow>
+ {showCheckbox && <TableCell />}
+ <TableCell colSpan={showCheckbox ? columnCount - 1 : columnCount}>
+ <Button
+ variant="link"
+ size="sm"
+ className="h-auto p-0 text-blue-600 dark:text-blue-400"
+ disabled={isFetchingNextFolders}
+ onClick={() => void fetchNextFolders()}
+ >
+ {isFetchingNextFolders ? (
+ <ReloadIcon className="mr-2 h-4 w-4 animate-spin" />
+ ) : null}
+ Load more folders
+ </Button>
+ </TableCell>
+ </TableRow>
+ )}
+ {treeUngroupedWorkflows.map((workflow) => (
+ <WorkflowRow
+ key={workflow.workflow_permanent_id}
+ workflow={workflow}
+ />
+ ))}
+ {renderLoadMoreAgentsRow()}
+ </>
+ );
+ }
+
+ return (
+ <div className="space-y-10">
+ <div className="flex h-32 justify-between gap-6">
+ <div className="space-y-5">
+ <div className="flex items-center gap-2">
+ <h1 className="text-2xl">Agents</h1>
+ </div>
+ <p className="text-sm leading-6 text-muted-foreground">
+ Create your own complex agents by connecting web agents together.
+ Define a series of actions, set it, and forget it.
+ </p>
+ </div>
+ <div className="flex gap-5">
+ <NarrativeCard
+ index={1}
+ description="Save browser sessions and reuse them in subsequent runs"
+ />
+ <NarrativeCard
+ index={2}
+ description="Connect multiple agents together to carry out complex objectives"
+ />
+ <NarrativeCard
+ index={3}
+ description="Execute non-browser tasks such as sending emails"
+ />
+ </div>
+ </div>
+ <div className="space-y-4">
+ <header className="flex items-center justify-between">
+ <h1 className="text-xl">My Agents</h1>
+ {selectedFolderId && (
+ <Button
+ variant="link"
+ size="sm"
+ className="h-auto p-0 text-blue-600 dark:text-blue-400"
+ onClick={() => setSelectedFolderId(null)}
+ >
+ Clear folder selection
+ </Button>
+ )}
+ </header>
+ <div className="flex justify-between">
+ <div className="flex items-center gap-3">
+ <TableSearchInput
+ value={search}
+ onChange={(value) => {
+ setSearch(value);
+ }}
+ placeholder="Search by title or input..."
+ className="w-48 lg:w-72"
+ />
+ <WorkflowTagFilter
+ tagKeys={tagKeys}
+ value={tagFilters}
+ onChange={setTagFilters}
+ labelSuggestions={labelSuggestions}
+ valueSuggestionsByKey={valueSuggestionsByKey}
+ />
+ </div>
+ <div className="flex items-center gap-4">
+ <Link
+ to="/discover"
+ className="text-sm text-muted-foreground hover:text-foreground"
+ >
+ Or start from a description →
+ </Link>
+ <Button
+ variant="secondary"
+ onClick={() => setIsCreateFolderOpen(true)}
+ >
+ <FolderIcon className="mr-2 h-4 w-4" />
+ New Folder
+ </Button>
+ <ImportWorkflowButton
+ onImportStart={startPolling}
+ selectedFolderId={selectedFolderId}
+ />
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger asChild>
+ <Button disabled={createWorkflowMutation.isPending}>
+ {createWorkflowMutation.isPending ? (
+ <ReloadIcon className="mr-2 h-4 w-4 animate-spin" />
+ ) : (
+ <PlusIcon className="mr-2 h-4 w-4" />
+ )}
+ Create
+ <ChevronDownIcon className="ml-2 h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onSelect={() => {
+ createWorkflowMutation.mutate({
+ ...defaultWorkflowRequest,
+ folder_id: selectedFolderId,
+ _via: "blank",
+ });
+ }}
+ >
+ <PlusIcon className="mr-2 h-4 w-4" />
+ Blank Agent
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onSelect={() => setIsTemplateDialogOpen(true)}
+ >
+ <BookmarkFilledIcon className="mr-2 h-4 w-4" />
+ From Template
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+ <WorkflowsListContext.Provider value={listContextValue}>
+ <div className="overflow-hidden rounded-lg border border-border">
+ <Table className="table-fixed">
+ <TableHeader>
+ <TableRow className="group/header">
+ {showCheckbox && (
+ <SelectionHeaderCheckboxCell
+ className="w-[3%]"
+ allSelected={allSelected}
+ someSelected={someSelected}
+ hasSelection={selected.size > 0}
+ onToggleAll={toggleSelectAll}
+ ariaLabel="Select all agents"
+ />
+ )}
+ <TableHead className={showCheckbox ? "w-[22%]" : "w-[25%]"}>
+ ID
+ </TableHead>
+ <TableHead className={showCheckbox ? "w-[27%]" : "w-[30%]"}>
+ Title
+ </TableHead>
+ <TableHead className="w-[15%]">Folder</TableHead>
+ <TableHead className="w-[15%]">Created At</TableHead>
+ <TableHead className="w-[15%] text-right">Actions</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>{renderTableBody()}</TableBody>
+ </Table>
+ </div>
+ </WorkflowsListContext.Provider>
+
+ {selectedWorkflows.length > 0 && (
+ <BulkActionBar
+ selectedWorkflows={selectedWorkflows}
+ isOperating={isBulkOperating}
+ onOperatingChange={setIsBulkOperating}
+ onClearSelection={clearSelection}
+ onDeleteRequest={() =>
+ setBulkDeleteDialog({
+ open: true,
+ targets: selectedWorkflows.map(
+ (workflow) => workflow.workflow_permanent_id,
+ ),
+ })
+ }
+ onMoveToFolder={handleBulkMoveToFolder}
+ tagKeys={tagKeys}
+ labelSuggestions={labelSuggestions}
+ valueSuggestionsByKey={valueSuggestionsByKey}
+ />
+ )}
+
+ <Dialog
+ open={bulkDeleteDialog.open}
+ onOpenChange={(open) => {
+ if (!open && !isBulkOperating) {
+ setBulkDeleteDialog({ open: false, targets: [] });
+ }
+ }}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>
+ Delete {bulkDeleteDialog.targets.length} Agent
+ {bulkDeleteDialog.targets.length === 1 ? "" : "s"}
+ </DialogTitle>
+ <DialogDescription>
+ Are you sure you want to delete{" "}
+ {bulkDeleteDialog.targets.length}{" "}
+ {bulkDeleteDialog.targets.length === 1 ? "agent" : "agents"}?
+ This action cannot be undone.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button
+ variant="secondary"
+ disabled={isBulkOperating}
+ onClick={() =>
+ setBulkDeleteDialog({ open: false, targets: [] })
+ }
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ disabled={isBulkOperating}
+ onClick={() => {
+ void handleBulkDeleteConfirm();
+ }}
+ >
+ {isBulkOperating ? "Deleting..." : "Delete"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ {/* Folder Dialogs */}
+ <CreateFolderDialog
+ open={isCreateFolderOpen}
+ onOpenChange={setIsCreateFolderOpen}
+ />
+
+ {/* Template Dialog */}
+ <CreateFromTemplateDialog
+ open={isTemplateDialogOpen}
+ onOpenChange={setIsTemplateDialogOpen}
+ onSelectTemplate={(template) => {
+ const clonedWorkflow = convert({
+ ...template,
+ title: `${template.title} (copy)`,
+ });
+ createWorkflowMutation.mutate({
+ ...clonedWorkflow,
+ folder_id: selectedFolderId,
+ });
+ }}
+ />
+
+ <div data-hint="start-template">
+ <WorkflowTemplates />
+ </div>
+
+ {onboarding ? (
+ <OnboardingErrorBoundary
+ onError={() => OnboardingTelemetry.modalRenderError("dashboard")}
+ >
+ <GetStartedModal
+ hasWorkflows={ownedWorkflows.length > 0}
+ isLoading={ownedWorkflowsLoading}
+ />
+ </OnboardingErrorBoundary>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+export { WorkflowsTree };
diff --git a/skyvern-frontend/src/routes/workflows/components/tree/FolderTreeNode.test.tsx b/skyvern-frontend/src/routes/workflows/components/tree/FolderTreeNode.test.tsx
new file mode 100644
index 000000000..411471835
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/components/tree/FolderTreeNode.test.tsx
@@ -0,0 +1,218 @@
+// @vitest-environment jsdom
+
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type { Folder } from "../../types/folderTypes";
+import type { WorkflowApiResponse } from "../../types/workflowTypes";
+import { FolderTreeNode } from "./FolderTreeNode";
+import {
+ WorkflowsListContext,
+ type WorkflowsListContextValue,
+} from "./WorkflowsListContext";
+
+const useFolderWorkflowsQueryMock = vi.fn();
+
+vi.mock("../../hooks/useFolderWorkflowsQuery", () => ({
+ useFolderWorkflowsQuery: (args: { folderId: string; enabled: boolean }) =>
+ useFolderWorkflowsQueryMock(args),
+ FOLDER_WORKFLOWS_PAGE_SIZE: 20,
+}));
+
+// Keep the leaf rendering trivial so this test isolates the folder node's
+// expand/collapse and empty-state behavior.
+vi.mock("./WorkflowRow", () => ({
+ WorkflowRow: ({ workflow }: { workflow: WorkflowApiResponse }) => (
+ <tr data-testid="workflow-row">
+ <td>{workflow.title}</td>
+ </tr>
+ ),
+}));
+
+vi.mock("../DeleteFolderButton", () => ({
+ DeleteFolderButton: () => <button type="button">delete</button>,
+}));
+
+vi.mock("../EditFolderDialog", () => ({
+ EditFolderDialog: () => null,
+}));
+
+function buildFolder(overrides: Partial<Folder> = {}): Folder {
+ return {
+ folder_id: "fld_1",
+ organization_id: "org_1",
+ title: "Marketing",
+ description: null,
+ workflow_count: 2,
+ created_at: "2026-01-01T00:00:00Z",
+ modified_at: "2026-01-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
+function buildWorkflow(id: string, title: string): WorkflowApiResponse {
+ return { workflow_permanent_id: id, title } as WorkflowApiResponse;
+}
+
+const contextValue: WorkflowsListContextValue = {
+ showCheckbox: false,
+ columnCount: 5,
+ debouncedSearch: "",
+ isBulkOperating: false,
+ selectedCount: 0,
+ foldersMap: new Map(),
+ workflowTagsMap: {},
+ tagDescriptions: new Map(),
+ tagKeys: [],
+ labelSuggestions: [],
+ valueSuggestionsByKey: new Map(),
+ isSelected: () => false,
+ indexById: new Map(),
+ handleSelect: () => {},
+ expandedRows: new Set(),
+ toggleParametersExpanded: () => {},
+ matchesParameter: () => false,
+ handleRowClick: () => {},
+ handleIconClick: () => {},
+};
+
+function renderNode({
+ isExpanded,
+ onToggle = () => {},
+ onCreateAgentInFolder = () => {},
+ isCreatingAgent = false,
+}: {
+ isExpanded: boolean;
+ onToggle?: () => void;
+ onCreateAgentInFolder?: (folderId: string) => void;
+ isCreatingAgent?: boolean;
+}) {
+ return render(
+ <WorkflowsListContext.Provider value={contextValue}>
+ <table>
+ <tbody>
+ <FolderTreeNode
+ folder={buildFolder()}
+ isExpanded={isExpanded}
+ isActive={false}
+ onToggle={onToggle}
+ onContentsChange={() => {}}
+ onCreateAgentInFolder={onCreateAgentInFolder}
+ isCreatingAgent={isCreatingAgent}
+ />
+ </tbody>
+ </table>
+ </WorkflowsListContext.Provider>,
+ );
+}
+
+describe("FolderTreeNode", () => {
+ afterEach(() => {
+ cleanup();
+ useFolderWorkflowsQueryMock.mockReset();
+ });
+
+ it("shows the folder title and agent count, and hides contents while collapsed", () => {
+ useFolderWorkflowsQueryMock.mockReturnValue({
+ data: undefined,
+ isFetching: false,
+ fetchNextPage: vi.fn(),
+ hasNextPage: false,
+ isFetchingNextPage: false,
+ });
+
+ renderNode({ isExpanded: false });
+
+ expect(screen.getByText("Marketing")).toBeTruthy();
+ expect(screen.getByText("2 agents")).toBeTruthy();
+ expect(screen.queryByTestId("workflow-row")).toBeNull();
+ });
+
+ it("renders the folder's agents when expanded", () => {
+ useFolderWorkflowsQueryMock.mockReturnValue({
+ data: { pages: [[buildWorkflow("wpid_1", "Scrape leads")]] },
+ isFetching: false,
+ fetchNextPage: vi.fn(),
+ hasNextPage: false,
+ isFetchingNextPage: false,
+ });
+
+ renderNode({ isExpanded: true });
+
+ expect(screen.getByTestId("workflow-row")).toBeTruthy();
+ expect(screen.getByText("Scrape leads")).toBeTruthy();
+ });
+
+ it("shows an empty state for an expanded folder with no agents", () => {
+ useFolderWorkflowsQueryMock.mockReturnValue({
+ data: { pages: [[]] },
+ isFetching: false,
+ fetchNextPage: vi.fn(),
+ hasNextPage: false,
+ isFetchingNextPage: false,
+ });
+
+ renderNode({ isExpanded: true });
+
+ expect(screen.getByText("This folder is empty")).toBeTruthy();
+ expect(screen.queryByTestId("workflow-row")).toBeNull();
+ });
+
+ it("disables per-folder create and ignores clicks while a create is pending", () => {
+ useFolderWorkflowsQueryMock.mockReturnValue({
+ data: undefined,
+ isFetching: false,
+ fetchNextPage: vi.fn(),
+ hasNextPage: false,
+ isFetchingNextPage: false,
+ });
+ const onCreateAgentInFolder = vi.fn();
+
+ renderNode({
+ isExpanded: false,
+ onCreateAgentInFolder,
+ isCreatingAgent: true,
+ });
+ const createButton = screen.getByLabelText(
+ "New agent in folder",
+ ) as HTMLButtonElement;
+ fireEvent.click(createButton);
+
+ expect(createButton.disabled).toBe(true);
+ expect(onCreateAgentInFolder).not.toHaveBeenCalled();
+ });
+
+ it("toggles when the folder row is clicked", () => {
+ useFolderWorkflowsQueryMock.mockReturnValue({
+ data: undefined,
+ isFetching: false,
+ fetchNextPage: vi.fn(),
+ hasNextPage: false,
+ isFetchingNextPage: false,
+ });
+ const onToggle = vi.fn();
+
+ renderNode({ isExpanded: false, onToggle });
+ fireEvent.click(screen.getByText("Marketing"));
+
+ expect(onToggle).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not toggle the folder when a folder-action button is keyboard-activated", () => {
+ useFolderWorkflowsQueryMock.mockReturnValue({
+ data: undefined,
+ isFetching: false,
+ fetchNextPage: vi.fn(),
+ hasNextPage: false,
+ isFetchingNextPage: false,
+ });
+ const onToggle = vi.fn();
+
+ renderNode({ isExpanded: false, onToggle });
+ fireEvent.keyDown(screen.getByLabelText("New agent in folder"), {
+ key: "Enter",
+ });
+
+ expect(onToggle).not.toHaveBeenCalled();
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/components/tree/FolderTreeNode.tsx b/skyvern-frontend/src/routes/workflows/components/tree/FolderTreeNode.tsx
new file mode 100644
index 000000000..67ebab91e
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/components/tree/FolderTreeNode.tsx
@@ -0,0 +1,228 @@
+import { useEffect, useMemo, useState } from "react";
+import {
+ ChevronRightIcon,
+ Pencil1Icon,
+ PlusIcon,
+ ReloadIcon,
+} from "@radix-ui/react-icons";
+import { FolderIcon } from "@/components/icons/FolderIcon";
+import { Button } from "@/components/ui/button";
+import { Skeleton } from "@/components/ui/skeleton";
+import { TableCell, TableRow } from "@/components/ui/table";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/util/utils";
+import type { Folder } from "../../types/folderTypes";
+import { WorkflowApiResponse } from "../../types/workflowTypes";
+import { useFolderWorkflowsQuery } from "../../hooks/useFolderWorkflowsQuery";
+import { DeleteFolderButton } from "../DeleteFolderButton";
+import { EditFolderDialog } from "../EditFolderDialog";
+import { WorkflowRow } from "./WorkflowRow";
+import { useWorkflowsListContext } from "./WorkflowsListContext";
+
+type FolderTreeNodeProps = {
+ folder: Folder;
+ isExpanded: boolean;
+ isActive: boolean;
+ onToggle: () => void;
+ onContentsChange: (
+ folderId: string,
+ workflows: Array<WorkflowApiResponse>,
+ ) => void;
+ onCreateAgentInFolder: (folderId: string) => void;
+ isCreatingAgent: boolean;
+};
+
+function FolderTreeNode({
+ folder,
+ isExpanded,
+ isActive,
+ onToggle,
+ onContentsChange,
+ onCreateAgentInFolder,
+ isCreatingAgent,
+}: FolderTreeNodeProps) {
+ const { showCheckbox, columnCount } = useWorkflowsListContext();
+ const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
+
+ const { data, isFetching, fetchNextPage, hasNextPage, isFetchingNextPage } =
+ useFolderWorkflowsQuery({
+ folderId: folder.folder_id,
+ enabled: isExpanded,
+ });
+
+ const workflows = useMemo(
+ () => data?.pages.flatMap((page) => page) ?? [],
+ [data],
+ );
+
+ // Report the folder's currently loaded workflows up so the parent can build a
+ // single flat selection set across every expanded folder. Collapsed folders
+ // contribute nothing.
+ useEffect(() => {
+ onContentsChange(folder.folder_id, isExpanded ? workflows : []);
+ }, [folder.folder_id, isExpanded, workflows, onContentsChange]);
+
+ useEffect(() => {
+ return () => onContentsChange(folder.folder_id, []);
+ }, [folder.folder_id, onContentsChange]);
+
+ const contentColSpan = columnCount - (showCheckbox ? 1 : 0);
+ const isInitialLoading = isExpanded && isFetching && workflows.length === 0;
+ const isEmpty = isExpanded && !isFetching && workflows.length === 0;
+
+ return (
+ <>
+ <TableRow
+ className={cn(
+ "group/folder cursor-pointer select-none",
+ isActive && "bg-blue-50 dark:bg-blue-950/20",
+ )}
+ role="button"
+ tabIndex={0}
+ aria-expanded={isExpanded}
+ aria-label={`Folder ${folder.title}, ${folder.workflow_count} ${
+ folder.workflow_count === 1 ? "agent" : "agents"
+ }, ${isExpanded ? "expanded" : "collapsed"}`}
+ onClick={onToggle}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ onToggle();
+ }
+ }}
+ >
+ {showCheckbox && <TableCell />}
+ <TableCell colSpan={contentColSpan}>
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex min-w-0 items-center gap-2">
+ <ChevronRightIcon
+ className={cn(
+ "h-4 w-4 shrink-0 text-muted-foreground transition-transform",
+ isExpanded && "rotate-90",
+ )}
+ />
+ <FolderIcon className="h-4 w-4 shrink-0 text-blue-400" />
+ <span className="truncate font-medium" title={folder.title}>
+ {folder.title}
+ </span>
+ <span className="shrink-0 text-xs text-muted-foreground">
+ {folder.workflow_count}{" "}
+ {folder.workflow_count === 1 ? "agent" : "agents"}
+ </span>
+ {isExpanded && isFetching && (
+ <ReloadIcon className="h-3 w-3 shrink-0 animate-spin text-muted-foreground" />
+ )}
+ </div>
+ <div
+ className="flex shrink-0 items-center gap-1 opacity-0 transition-opacity focus-within:opacity-100 group-hover/folder:opacity-100"
+ onClick={(event) => event.stopPropagation()}
+ onKeyDown={(event) => event.stopPropagation()}
+ >
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ onClick={() => onCreateAgentInFolder(folder.folder_id)}
+ disabled={isCreatingAgent}
+ className="rounded p-1.5 text-slate-400 transition-colors hover:bg-slate-500/20 hover:text-slate-300 disabled:cursor-not-allowed disabled:opacity-50"
+ aria-label="New agent in folder"
+ >
+ <PlusIcon className="h-4 w-4" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>New agent here</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ onClick={() => setIsEditDialogOpen(true)}
+ className="rounded p-1.5 text-slate-400 transition-colors hover:bg-slate-500/20 hover:text-slate-300"
+ aria-label="Edit folder"
+ >
+ <Pencil1Icon className="h-4 w-4" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>Edit folder</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ <DeleteFolderButton
+ folderId={folder.folder_id}
+ folderTitle={folder.title}
+ />
+ </div>
+ </div>
+ </TableCell>
+ </TableRow>
+
+ {isInitialLoading &&
+ Array.from({ length: 2 }).map((_, index) => (
+ <TableRow key={`${folder.folder_id}-skeleton-${index}`}>
+ {showCheckbox && <TableCell />}
+ <TableCell colSpan={contentColSpan}>
+ <Skeleton className="ml-12 h-5 w-2/3" />
+ </TableCell>
+ </TableRow>
+ ))}
+
+ {isEmpty && (
+ <TableRow>
+ {showCheckbox && <TableCell />}
+ <TableCell colSpan={contentColSpan}>
+ <span className="ml-12 text-sm text-muted-foreground">
+ This folder is empty
+ </span>
+ </TableCell>
+ </TableRow>
+ )}
+
+ {isExpanded &&
+ workflows.map((workflow) => (
+ <WorkflowRow
+ key={workflow.workflow_permanent_id}
+ workflow={workflow}
+ depth={1}
+ />
+ ))}
+
+ {isExpanded && hasNextPage && (
+ <TableRow>
+ {showCheckbox && <TableCell />}
+ <TableCell colSpan={contentColSpan}>
+ <Button
+ variant="link"
+ size="sm"
+ className="ml-12 h-auto p-0 text-blue-600 dark:text-blue-400"
+ disabled={isFetchingNextPage}
+ onClick={(event) => {
+ event.stopPropagation();
+ void fetchNextPage();
+ }}
+ >
+ {isFetchingNextPage ? (
+ <ReloadIcon className="mr-2 h-4 w-4 animate-spin" />
+ ) : null}
+ Load more agents
+ </Button>
+ </TableCell>
+ </TableRow>
+ )}
+
+ <EditFolderDialog
+ open={isEditDialogOpen}
+ onOpenChange={setIsEditDialogOpen}
+ folder={folder}
+ />
+ </>
+ );
+}
+
+export { FolderTreeNode };
diff --git a/skyvern-frontend/src/routes/workflows/components/tree/WorkflowRow.tsx b/skyvern-frontend/src/routes/workflows/components/tree/WorkflowRow.tsx
new file mode 100644
index 000000000..186f78bd8
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/components/tree/WorkflowRow.tsx
@@ -0,0 +1,327 @@
+import React from "react";
+import {
+ BookmarkFilledIcon,
+ DotsHorizontalIcon,
+ Pencil2Icon,
+ PlayIcon,
+ ReloadIcon,
+} from "@radix-ui/react-icons";
+import { FolderIcon } from "@/components/icons/FolderIcon";
+import { Button } from "@/components/ui/button";
+import { SelectionCheckboxCell } from "@/components/SelectionCheckbox";
+import { TableCell, TableRow } from "@/components/ui/table";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { basicTimeFormat, compactLocalDateTime } from "@/util/timeFormat";
+import { WorkflowApiResponse } from "../../types/workflowTypes";
+import { WorkflowActions } from "../../WorkflowActions";
+import { HighlightText } from "../HighlightText";
+import { ParameterDisplayInline } from "../ParameterDisplayInline";
+import { TagChipList } from "../tagging/TagChipList";
+import { WorkflowTagEditor } from "../tagging/WorkflowTagEditor";
+import { WorkflowFolderSelector } from "../WorkflowFolderSelector";
+import { useWorkflowsListContext } from "./WorkflowsListContext";
+
+// Pixels of left padding added per level of folder nesting. Level 0 (flat search
+// results and ungrouped agents) uses the cell's default padding. depth 1 lands
+// at 60px so a folder's agents line up under the folder title text (cell px-3 +
+// chevron + icon + gaps).
+const INDENT_STEP_PX = 28;
+const INDENT_BASE_PX = 32;
+
+function indentStyle(depth: number): React.CSSProperties | undefined {
+ if (depth <= 0) {
+ return undefined;
+ }
+ return { paddingLeft: `${INDENT_BASE_PX + depth * INDENT_STEP_PX}px` };
+}
+
+type WorkflowRowProps = {
+ workflow: WorkflowApiResponse;
+ // Folder nesting depth; 0 = top level / flat list.
+ depth?: number;
+};
+
+function WorkflowRow({ workflow, depth = 0 }: WorkflowRowProps) {
+ const {
+ showCheckbox,
+ columnCount,
+ debouncedSearch,
+ isBulkOperating,
+ selectedCount,
+ foldersMap,
+ workflowTagsMap,
+ tagDescriptions,
+ tagKeys,
+ labelSuggestions,
+ valueSuggestionsByKey,
+ isSelected,
+ indexById,
+ handleSelect,
+ expandedRows,
+ toggleParametersExpanded,
+ matchesParameter,
+ handleRowClick,
+ handleIconClick,
+ } = useWorkflowsListContext();
+
+ const parameterItems = (workflow.workflow_definition?.parameters ?? [])
+ .filter((p) => p.parameter_type !== "output")
+ .map((param) => ({
+ key: param.key,
+ value:
+ param.parameter_type === "workflow" ? (param.default_value ?? "") : "",
+ description: param.description ?? null,
+ }));
+ const hasParameters = parameterItems.length > 0;
+ const isExpanded = expandedRows.has(workflow.workflow_permanent_id);
+ const isRowSelected = isSelected(workflow.workflow_permanent_id);
+ const isUploading = workflow.status === "importing";
+ const workflowTags = workflowTagsMap[workflow.workflow_permanent_id];
+ const selectableIndex = isUploading
+ ? -1
+ : (indexById.get(workflow.workflow_permanent_id) ?? -1);
+ const firstCellStyle = indentStyle(depth);
+
+ if (isUploading) {
+ return (
+ <TableRow className="opacity-70">
+ {showCheckbox && <TableCell />}
+ <TableCell colSpan={2} style={firstCellStyle}>
+ <div className="flex min-w-0 items-center gap-2">
+ <ReloadIcon className="h-4 w-4 shrink-0 animate-spin text-blue-400" />
+ <span className="truncate" title={workflow.title}>
+ {workflow.title}
+ </span>
+ </div>
+ </TableCell>
+ <TableCell>
+ <span className="text-muted-foreground">-</span>
+ </TableCell>
+ <TableCell className="text-muted-foreground">
+ {compactLocalDateTime(workflow.created_at)}
+ </TableCell>
+ <TableCell>
+ <div className="flex justify-end gap-0.5">
+ {selectedCount === 0 && (
+ <Button size="icon" variant="ghost" disabled>
+ <FolderIcon className="h-4 w-4" />
+ </Button>
+ )}
+ <Button size="icon" variant="ghost" disabled>
+ <Pencil2Icon className="h-4 w-4" />
+ </Button>
+ <Button size="icon" variant="ghost" disabled>
+ <PlayIcon className="h-4 w-4" />
+ </Button>
+ {selectedCount === 0 && (
+ <Button size="icon" variant="ghost" disabled>
+ <DotsHorizontalIcon className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ </TableCell>
+ </TableRow>
+ );
+ }
+
+ return (
+ <React.Fragment>
+ <TableRow
+ className="group/row cursor-pointer select-none"
+ data-state={isRowSelected ? "selected" : undefined}
+ >
+ {showCheckbox && (
+ <SelectionCheckboxCell
+ className="select-none"
+ index={selectableIndex}
+ checked={isRowSelected}
+ hasSelection={selectedCount > 0}
+ onSelect={handleSelect}
+ ariaLabel={`Select ${workflow.title}`}
+ />
+ )}
+ <TableCell
+ style={firstCellStyle}
+ onClick={(event) => {
+ handleRowClick(event, workflow.workflow_permanent_id);
+ }}
+ >
+ <div
+ className="truncate font-mono text-xs text-muted-foreground"
+ title={workflow.workflow_permanent_id}
+ >
+ <HighlightText
+ text={workflow.workflow_permanent_id}
+ query={debouncedSearch}
+ />
+ </div>
+ </TableCell>
+ <TableCell
+ onClick={(event) => {
+ handleRowClick(event, workflow.workflow_permanent_id);
+ }}
+ >
+ <div className="flex min-w-0 flex-col gap-1">
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="truncate" title={workflow.title}>
+ <HighlightText text={workflow.title} query={debouncedSearch} />
+ </span>
+ {workflow.is_template && (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <BookmarkFilledIcon className="h-3.5 w-3.5 shrink-0 text-blue-500" />
+ </TooltipTrigger>
+ <TooltipContent>Template</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ )}
+ </div>
+ {workflowTags && workflowTags.length > 0 ? (
+ <TagChipList tags={workflowTags} descriptions={tagDescriptions} />
+ ) : null}
+ </div>
+ </TableCell>
+ <TableCell
+ onClick={(event) => {
+ handleRowClick(event, workflow.workflow_permanent_id);
+ }}
+ >
+ {workflow.folder_id ? (
+ <div className="flex min-w-0 items-center gap-1.5">
+ <FolderIcon className="h-3.5 w-3.5 shrink-0 text-blue-400" />
+ <span
+ className="truncate text-sm"
+ title={
+ foldersMap.get(workflow.folder_id)?.title ||
+ workflow.folder_id
+ }
+ >
+ <HighlightText
+ text={
+ foldersMap.get(workflow.folder_id)?.title ||
+ workflow.folder_id
+ }
+ query={debouncedSearch}
+ />
+ </span>
+ </div>
+ ) : (
+ <span className="text-muted-foreground">-</span>
+ )}
+ </TableCell>
+ <TableCell
+ onClick={(event) => {
+ handleRowClick(event, workflow.workflow_permanent_id);
+ }}
+ className="text-muted-foreground"
+ title={basicTimeFormat(workflow.created_at)}
+ >
+ {compactLocalDateTime(workflow.created_at)}
+ </TableCell>
+ <TableCell>
+ <div className="flex justify-end gap-0.5">
+ {/* Folder, tags, and the row menu yield to the bulk bar while any selection is active; Edit and Run stay. */}
+ {selectedCount === 0 && (
+ <>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <WorkflowFolderSelector
+ workflowPermanentId={workflow.workflow_permanent_id}
+ currentFolderId={workflow.folder_id}
+ disabled={isBulkOperating}
+ />
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>Assign to Folder</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ <WorkflowTagEditor
+ workflowPermanentId={workflow.workflow_permanent_id}
+ tags={workflowTags ?? []}
+ tagKeys={tagKeys}
+ labelSuggestions={labelSuggestions}
+ valueSuggestionsByKey={valueSuggestionsByKey}
+ />
+ </>
+ )}
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ size="icon"
+ variant="ghost"
+ className="text-muted-foreground hover:text-foreground"
+ onClick={(event) => {
+ handleIconClick(
+ event,
+ `/workflows/${workflow.workflow_permanent_id}/build`,
+ );
+ }}
+ >
+ <Pencil2Icon className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Open in Editor</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ size="icon"
+ variant="ghost"
+ className="text-cta hover:text-cta"
+ onClick={(event) => {
+ handleIconClick(
+ event,
+ `/workflows/${workflow.workflow_permanent_id}/run`,
+ );
+ }}
+ >
+ <PlayIcon className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Create New Run</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ {selectedCount === 0 && (
+ <WorkflowActions
+ workflow={workflow}
+ hasParameters={hasParameters}
+ parametersExpanded={isExpanded}
+ onToggleParameters={() =>
+ toggleParametersExpanded(workflow.workflow_permanent_id)
+ }
+ />
+ )}
+ </div>
+ </TableCell>
+ </TableRow>
+
+ {isExpanded && hasParameters && (
+ <TableRow>
+ <TableCell
+ colSpan={columnCount}
+ className="bg-slate-50 dark:bg-slate-900/50"
+ >
+ <ParameterDisplayInline
+ parameters={parameterItems}
+ searchQuery={debouncedSearch}
+ keywordMatchesParameter={matchesParameter}
+ />
+ </TableCell>
+ </TableRow>
+ )}
+ </React.Fragment>
+ );
+}
+
+export { WorkflowRow };
diff --git a/skyvern-frontend/src/routes/workflows/components/tree/WorkflowsListContext.ts b/skyvern-frontend/src/routes/workflows/components/tree/WorkflowsListContext.ts
new file mode 100644
index 000000000..0d1ef732d
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/components/tree/WorkflowsListContext.ts
@@ -0,0 +1,49 @@
+import { createContext, useContext, type MouseEvent } from "react";
+import type { ParameterDisplayItem } from "../ParameterDisplayInline";
+import type { Folder } from "../../types/folderTypes";
+import type { Tag, TagKey } from "../../types/tagTypes";
+
+// Shared, read-only state and handlers consumed by every workflow row, whether
+// the row is rendered flat (search results) or nested under a folder node. Lives
+// in context so the folder tree can render rows arbitrarily deep without each
+// level re-threading the same dozen props.
+export interface WorkflowsListContextValue {
+ showCheckbox: boolean;
+ columnCount: number;
+ debouncedSearch: string;
+ isBulkOperating: boolean;
+ selectedCount: number;
+ foldersMap: ReadonlyMap<string, Folder>;
+ workflowTagsMap: Record<string, Array<Tag>>;
+ tagDescriptions: Map<string, string | null>;
+ tagKeys: Array<TagKey>;
+ labelSuggestions: Array<string>;
+ valueSuggestionsByKey: Map<string, Array<string>>;
+ isSelected: (id: string) => boolean;
+ indexById: ReadonlyMap<string, number>;
+ handleSelect: (index: number, shiftKey: boolean) => void;
+ expandedRows: ReadonlySet<string>;
+ toggleParametersExpanded: (id: string) => void;
+ matchesParameter: (parameter: ParameterDisplayItem) => boolean;
+ handleRowClick: (
+ event: MouseEvent<HTMLTableCellElement>,
+ workflowPermanentId: string,
+ ) => void;
+ handleIconClick: (event: MouseEvent<HTMLButtonElement>, path: string) => void;
+}
+
+const WorkflowsListContext = createContext<WorkflowsListContextValue | null>(
+ null,
+);
+
+function useWorkflowsListContext(): WorkflowsListContextValue {
+ const context = useContext(WorkflowsListContext);
+ if (!context) {
+ throw new Error(
+ "useWorkflowsListContext must be used within a WorkflowsListContext.Provider",
+ );
+ }
+ return context;
+}
+
+export { WorkflowsListContext, useWorkflowsListContext };
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useFolderWorkflowsQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useFolderWorkflowsQuery.ts
new file mode 100644
index 000000000..2df49c592
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/hooks/useFolderWorkflowsQuery.ts
@@ -0,0 +1,41 @@
+import { getClient } from "@/api/AxiosClient";
+import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { useInfiniteQuery } from "@tanstack/react-query";
+import { WorkflowApiResponse } from "../types/workflowTypes";
+
+const FOLDER_WORKFLOWS_PAGE_SIZE = 20;
+
+// Lazily loads the workflows inside a single folder. The query only runs while
+// the folder node is expanded (`enabled`), so collapsed folders cost nothing.
+function useFolderWorkflowsQuery({
+ folderId,
+ enabled,
+}: {
+ folderId: string;
+ enabled: boolean;
+}) {
+ const credentialGetter = useCredentialGetter();
+
+ return useInfiniteQuery({
+ queryKey: ["workflows", "folder", folderId, FOLDER_WORKFLOWS_PAGE_SIZE],
+ queryFn: async ({ pageParam = 1 }) => {
+ const client = await getClient(credentialGetter);
+ const params = new URLSearchParams();
+ params.append("page", String(pageParam));
+ params.append("page_size", String(FOLDER_WORKFLOWS_PAGE_SIZE));
+ params.append("only_workflows", "true");
+ params.append("folder_id", folderId);
+ return client
+ .get<Array<WorkflowApiResponse>>("/workflows", { params })
+ .then((response) => response.data);
+ },
+ getNextPageParam: (lastPage, allPages) =>
+ lastPage.length === FOLDER_WORKFLOWS_PAGE_SIZE
+ ? allPages.length + 1
+ : undefined,
+ initialPageParam: 1,
+ enabled,
+ });
+}
+
+export { useFolderWorkflowsQuery, FOLDER_WORKFLOWS_PAGE_SIZE };
diff --git a/skyvern-frontend/src/util/featureFlags.ts b/skyvern-frontend/src/util/featureFlags.ts
index f019f2f77..9aafb8bb6 100644
--- a/skyvern-frontend/src/util/featureFlags.ts
+++ b/skyvern-frontend/src/util/featureFlags.ts
@@ -15,3 +15,7 @@ export const ANALYTICS_DASHBOARD_FLAG = "ANALYTICS_DASHBOARD";
* surfaces gate on a resolved variant (isABVariant), so 0% or rollback hides them.
*/
export const EDITOR_ONBOARDING_TOUR_FLAG = "EDITOR_ONBOARDING_TOUR";
+
+// Opt-in (0% base rollout) preview gating the workflows directory-tree view.
+// Not enrolled reads as disabled, so the default stays the flat folders/list.
+export const WORKFLOWS_DIRECTORY_TREE_FLAG = "WORKFLOWS_DIRECTORY_TREE";