Skip to content

Automate browser based workflows with AI

14.5 KB
Raw Blame
import { getClient } from "@/api/AxiosClient";
import { useState } from "react";
import { FolderIcon } from "@/components/icons/FolderIcon";
import { GarbageIcon } from "@/components/icons/GarbageIcon";
import { SelectionBar } from "@/components/SelectionBar";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuPortal,
  DropdownMenuSeparator,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
import { bulkResultToast } from "@/util/bulkResultToast";
import {
  BULK_CONCURRENCY_LIMIT,
  runWithConcurrency,
} from "@/util/runWithConcurrency";
import {
  BookmarkFilledIcon,
  BookmarkIcon,
  ChevronDownIcon,
  CopyIcon,
  DownloadIcon,
  TokensIcon,
} from "@radix-ui/react-icons";
import { useQueryClient } from "@tanstack/react-query";
import { strToU8, zipSync } from "fflate";
import { stringify as convertToYAML } from "yaml";
import { convert } from "../editor/workflowEditorUtils";
import { Tag, TagKey } from "../types/tagTypes";
import { WorkflowApiResponse } from "../types/workflowTypes";
import { FolderPickerCommand } from "./FolderPickerCommand";
import { TagPickerCommand } from "./tagging/TagPickerCommand";

type Props = {
  selectedWorkflows: WorkflowApiResponse[];
  isOperating: boolean;
  onOperatingChange: (operating: boolean) => void;
  onClearSelection: () => void;
  onDeleteRequest: () => void;
  onMoveToFolder: (folderId: string | null) => Promise<void>;
  // From useWorkflowTaggingEnabled: true only once the WORKFLOW_TAGGING flag resolves on.
  taggingEnabled: boolean;
  tagKeys: Array<TagKey>;
  labelSuggestions: Array<string>;
  valueSuggestionsByKey?: Map<string, Array<string>>;
};

// Blob URLs avoid the ~2MB data-URI cap that truncates large workflow exports.
function downloadFile(
  fileName: string,
  contents: BlobPart,
  mimeType = "text/plain;charset=utf-8",
) {
  const blob = new Blob([contents], { type: mimeType });
  const url = URL.createObjectURL(blob);
  const element = document.createElement("a");
  element.href = url;
  element.download = fileName;
  element.style.display = "none";
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
  // Deferred so a still-starting download cannot lose its blob.
  setTimeout(() => URL.revokeObjectURL(url), 60_000);
}

function sanitizeFileName(name: string): string {
  return name.replace(/[/\\:*?"<>|]/g, "_");
}

// zipSync()'s Uint8Array return type carries whatever ArrayBuffer-ish generic
// the active @types/node augments as its default, which isn't always the
// concrete ArrayBuffer Blob's BlobPart expects. Copying into a plain
// ArrayBuffer sidesteps that: ArrayBuffer itself isn't generic, so this is
// valid under any @types/node version without a cast.
function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {
  const buffer = new ArrayBuffer(bytes.byteLength);
  new Uint8Array(buffer).set(bytes);
  return buffer;
}

// Two selected agents can share a title; number repeats so every archive
// entry name stays unique.
function uniqueFileName(used: Set<string>, title: string, ext: string): string {
  const base = sanitizeFileName(title);
  let candidate = `${base}.${ext}`;
  for (let suffix = 2; used.has(candidate); suffix++) {
    candidate = `${base}-${suffix}.${ext}`;
  }
  used.add(candidate);
  return candidate;
}

function BulkActionBar({
  selectedWorkflows,
  isOperating,
  onOperatingChange,
  onClearSelection,
  onDeleteRequest,
  onMoveToFolder,
  taggingEnabled,
  tagKeys,
  labelSuggestions,
  valueSuggestionsByKey,
}: Props) {
  const credentialGetter = useCredentialGetter();
  const queryClient = useQueryClient();
  const count = selectedWorkflows.length;
  const nonTemplates = selectedWorkflows.filter(
    (workflow) => !workflow.is_template,
  );
  const templates = selectedWorkflows.filter(
    (workflow) => workflow.is_template,
  );
  const [tagError, setTagError] = useState<string | null>(null);

  async function handleBulkClone() {
    onOperatingChange(true);
    try {
      const client = await getClient(credentialGetter);
      const results = await runWithConcurrency(
        selectedWorkflows.map((workflow) => () => {
          const yaml = convertToYAML(
            convert(
              { ...workflow, title: `Copy of ${workflow.title}` },
              { asNewWorkflow: true },
            ),
          );
          return client.post("/workflows", yaml, {
            headers: { "Content-Type": "text/plain" },
          });
        }),
        BULK_CONCURRENCY_LIMIT,
      );
      const succeeded = results.filter((r) => r.status === "fulfilled").length;
      bulkResultToast({
        succeeded,
        total: count,
        results,
        successTitle: (n) => `Duplicated ${n} agent${n !== 1 ? "s" : ""}.`,
        failureTitle: (n) =>
          `Failed to duplicate ${n} agent${n !== 1 ? "s" : ""}.`,
        partialTitle: (successCount, failedCount) =>
          `Duplicated ${successCount} agent${successCount !== 1 ? "s" : ""}. ${failedCount} failed.`,
      });
      if (succeeded === count) {
        onClearSelection();
      }
      if (succeeded > 0) {
        queryClient.invalidateQueries({ queryKey: ["workflows"] });
        queryClient.invalidateQueries({ queryKey: ["folders"] });
      }
    } finally {
      onOperatingChange(false);
    }
  }

  async function handleBulkTemplateUpdate(
    workflows: WorkflowApiResponse[],
    isTemplate: boolean,
  ) {
    if (workflows.length === 0) {
      return;
    }
    onOperatingChange(true);
    try {
      // Template endpoint only exists on /v1 (no /api prefix)
      const client = await getClient(credentialGetter, "sans-api-v1");
      const results = await runWithConcurrency(
        workflows.map(
          (workflow) => () =>
            client.put(
              `/workflows/${workflow.workflow_permanent_id}/template?is_template=${isTemplate}`,
            ),
        ),
        BULK_CONCURRENCY_LIMIT,
      );
      const succeeded = results.filter((r) => r.status === "fulfilled").length;
      bulkResultToast({
        succeeded,
        total: workflows.length,
        results,
        successTitle: (n) =>
          isTemplate
            ? `Saved ${n} agent${n !== 1 ? "s" : ""} as templates.`
            : `Removed ${n} agent${n !== 1 ? "s" : ""} from templates.`,
        failureTitle: (n) =>
          isTemplate
            ? `Failed to save ${n} agent${n !== 1 ? "s" : ""} as templates.`
            : `Failed to remove ${n} agent${n !== 1 ? "s" : ""} from templates.`,
        partialTitle: (successCount, failedCount) =>
          isTemplate
            ? `Saved ${successCount} agent${successCount !== 1 ? "s" : ""} as templates. ${failedCount} failed.`
            : `Removed ${successCount} agent${successCount !== 1 ? "s" : ""} from templates. ${failedCount} failed.`,
      });
      if (succeeded === workflows.length) {
        onClearSelection();
      }
      if (succeeded > 0) {
        queryClient.invalidateQueries({ queryKey: ["workflows"] });
        queryClient.invalidateQueries({ queryKey: ["orgTemplates"] });
      }
    } finally {
      onOperatingChange(false);
    }
  }

  async function handleBulkTagApply(tag: Tag) {
    // The submenu stays open after a pick (tagging is additive), so guard against
    // a second apply racing the first set of POSTs for the same selection.
    if (isOperating) {
      return;
    }
    onOperatingChange(true);
    try {
      const client = await getClient(credentialGetter);
      const results = await runWithConcurrency(
        selectedWorkflows.map(
          (workflow) => () =>
            client.post(`/workflows/${workflow.workflow_permanent_id}/tags`, {
              tags: [tag],
            }),
        ),
        BULK_CONCURRENCY_LIMIT,
      );
      const succeeded = results.filter((r) => r.status === "fulfilled").length;
      const tagLabel =
        tag.key !== null ? `${tag.key}: ${tag.value}` : tag.value;
      bulkResultToast({
        succeeded,
        total: count,
        results,
        successTitle: (n) =>
          `Tagged ${n} agent${n !== 1 ? "s" : ""} with ${tagLabel}.`,
        failureTitle: (n) => `Failed to tag ${n} agent${n !== 1 ? "s" : ""}.`,
        partialTitle: (successCount, failedCount) =>
          `Tagged ${successCount} agent${successCount !== 1 ? "s" : ""}. ${failedCount} failed.`,
      });
      // Tagging is additive; the selection stays for more tags or follow-up actions.
      if (succeeded > 0) {
        queryClient.invalidateQueries({ queryKey: ["workflow-tags"] });
        queryClient.invalidateQueries({ queryKey: ["tag-keys"] });
        queryClient.invalidateQueries({ queryKey: ["workflows"] });
      }
    } finally {
      onOperatingChange(false);
    }
  }

  function handleBulkExport(type: "json" | "yaml") {
    if (selectedWorkflows.length === 1) {
      const workflow = selectedWorkflows[0]!;
      const safeTitle = sanitizeFileName(workflow.title);
      const contents =
        type === "json"
          ? JSON.stringify(convert(workflow), null, 2)
          : convertToYAML(convert(workflow));
      downloadFile(`${safeTitle}.${type}`, contents);
      return;
    }
    // A ZIP with one file per agent triggers a single download. N sequential
    // downloadFile() calls would trip the browser's multiple-downloads
    // permission prompt instead.
    const usedNames = new Set<string>();
    const entries: Record<string, Uint8Array> = {};
    for (const workflow of selectedWorkflows) {
      const contents =
        type === "json"
          ? JSON.stringify(convert(workflow), null, 2)
          : convertToYAML(convert(workflow));
      entries[uniqueFileName(usedNames, workflow.title, type)] =
        strToU8(contents);
    }
    downloadFile(
      `agents-export-${selectedWorkflows.length}.zip`,
      toArrayBuffer(zipSync(entries)),
      "application/zip",
    );
  }

  const agentNoun = count === 1 ? "agent" : "agents";

  return (
    <SelectionBar
      count={count}
      isOperating={isOperating}
      onClear={onClearSelection}
    >
      <DropdownMenu
        onOpenChange={(open) => {
          if (!open) {
            setTagError(null);
          }
        }}
      >
        <DropdownMenuTrigger asChild>
          <Button size="sm" variant="ghost" disabled={isOperating}>
            Actions
            <ChevronDownIcon className="ml-1.5 h-4 w-4" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="start" side="top" className="w-56">
          {taggingEnabled && (
            <DropdownMenuSub
              onOpenChange={(open) => {
                if (!open) {
                  setTagError(null);
                }
              }}
            >
              <DropdownMenuSubTrigger>
                <TokensIcon className="mr-2 h-4 w-4" />
                Tag {count} {agentNoun}
              </DropdownMenuSubTrigger>
              <DropdownMenuPortal>
                <DropdownMenuSubContent className="w-72 p-0">
                  <TagPickerCommand
                    tagKeys={tagKeys}
                    labelSuggestions={labelSuggestions}
                    valueSuggestionsByKey={valueSuggestionsByKey}
                    error={tagError}
                    onErrorChange={setTagError}
                    disabled={isOperating}
                    onApply={(tag) => void handleBulkTagApply(tag)}
                  />
                </DropdownMenuSubContent>
              </DropdownMenuPortal>
            </DropdownMenuSub>
          )}
          <DropdownMenuSub>
            <DropdownMenuSubTrigger>
              <FolderIcon className="mr-2 h-4 w-4" />
              Move {count} to folder
            </DropdownMenuSubTrigger>
            <DropdownMenuPortal>
              <DropdownMenuSubContent className="w-72 p-0">
                <FolderPickerCommand
                  currentFolderId={null}
                  showRemove={selectedWorkflows.some(
                    (workflow) => workflow.folder_id !== null,
                  )}
                  disabled={isOperating}
                  onSelect={(folderId) => void onMoveToFolder(folderId)}
                />
              </DropdownMenuSubContent>
            </DropdownMenuPortal>
          </DropdownMenuSub>
          <DropdownMenuSeparator />
          <DropdownMenuItem onSelect={() => void handleBulkClone()}>
            <CopyIcon className="mr-2 h-4 w-4" />
            Duplicate ({count})
          </DropdownMenuItem>
          <DropdownMenuSub>
            <DropdownMenuSubTrigger>
              <BookmarkIcon className="mr-2 h-4 w-4" />
              Template
            </DropdownMenuSubTrigger>
            <DropdownMenuPortal>
              <DropdownMenuSubContent>
                <DropdownMenuItem
                  disabled={nonTemplates.length === 0}
                  onSelect={() =>
                    void handleBulkTemplateUpdate(nonTemplates, true)
                  }
                >
                  <BookmarkIcon className="mr-2 h-4 w-4" />
                  Save as Templates ({nonTemplates.length})
                </DropdownMenuItem>
                <DropdownMenuItem
                  disabled={templates.length === 0}
                  onSelect={() =>
                    void handleBulkTemplateUpdate(templates, false)
                  }
                >
                  <BookmarkFilledIcon className="mr-2 h-4 w-4" />
                  Remove from Templates ({templates.length})
                </DropdownMenuItem>
              </DropdownMenuSubContent>
            </DropdownMenuPortal>
          </DropdownMenuSub>
          <DropdownMenuSub>
            <DropdownMenuSubTrigger>
              <DownloadIcon className="mr-2 h-4 w-4" />
              Export
            </DropdownMenuSubTrigger>
            <DropdownMenuPortal>
              <DropdownMenuSubContent>
                <DropdownMenuItem onSelect={() => handleBulkExport("yaml")}>
                  YAML
                </DropdownMenuItem>
                <DropdownMenuItem onSelect={() => handleBulkExport("json")}>
                  JSON
                </DropdownMenuItem>
              </DropdownMenuSubContent>
            </DropdownMenuPortal>
          </DropdownMenuSub>
          <DropdownMenuSeparator />
          <DropdownMenuItem
            className="text-destructive focus:text-destructive"
            onSelect={() => onDeleteRequest()}
          >
            <GarbageIcon className="mr-2 h-4 w-4 text-destructive" />
            Delete {count}
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </SelectionBar>
  );
}

export { BulkActionBar };