Skip to content

Automate browser based workflows with AI

11.7 KB
Raw Blame
import {
  runIsRetryWaiting,
  runIsExecuting,
  runIsLogicallyFinal,
} from "@/routes/workflows/workflowRun/runRetryState";
import { useCallback, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import {
  ActivityLogIcon,
  CodeIcon,
  DotsHorizontalIcon,
  FileTextIcon,
  ListBulletIcon,
  ReloadIcon,
  Share1Icon,
} from "@radix-ui/react-icons";
import { useWorkflowPermanentId } from "@/routes/workflows/WorkflowPermanentIdContext";

import { ApiWebhookActionsMenu } from "@/components/ApiWebhookActionsMenu";
import { WebhookReplayDialog } from "@/components/WebhookReplayDialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { useApiCredential } from "@/hooks/useApiCredential";
import { Status } from "@/api/types";

import { useRunViewStore } from "@/store/RunViewStore";
import { useRunPaneViewStore } from "@/store/useRunPaneViewStore";
import { useStudioBrowserStore } from "@/store/useStudioBrowserStore";
import { type ApiCommandOptions } from "@/util/apiCommands";
import { runsApiBaseUrl } from "@/util/env";
import { cn } from "@/util/utils";

import { useIsGeneratingCode } from "../../editor/hooks/useIsGeneratingCode";
import { constructCacheKeyValue } from "../../editor/utils";
import { useWorkflowRunWithWorkflowQuery } from "../../hooks/useWorkflowRunWithWorkflowQuery";
import { WorkflowRunStatusAlert } from "../../workflowRun/WorkflowRunStatusAlert";
import { studioPanelId } from "../constants";
import { useStudioPaneCompact } from "../StudioShellContext";
import { useStudioInspectedRun } from "../useStudioInspectedRun";
import { useStudioPanes } from "../useStudioPanes";
import { ViewToggle } from "../ViewToggle";
import { toReadableSearch } from "../panes";

/**
 * Left header cluster of the Overview pane: the Timeline / Inputs / Outputs
 * view toggles plus a "…" overflow menu holding the Code view, and the Live
 * handoff chip while the run executes. The selected view lives in
 * useRunPaneViewStore; RunView renders the body.
 */
export function RunPaneViewToggles() {
  const compact = useStudioPaneCompact();
  const { runId } = useStudioInspectedRun();
  const workflowPermanentId = useWorkflowPermanentId();
  const { data: workflowRun, isError: statusUnavailable } =
    useWorkflowRunWithWorkflowQuery({ workflowRunId: runId });
  const view = useRunPaneViewStore((s) => s.view);
  const setView = useRunPaneViewStore((s) => s.setView);
  const location = useLocation();
  const navigate = useNavigate();
  const jumpToLive = useRunViewStore((s) => s.jumpToLive);
  const setBrowserPaneView = useStudioBrowserStore((s) => s.setView);
  const { openPane, resolveLivePanes } = useStudioPanes();
  const cacheKey = workflowRun?.workflow?.cache_key ?? "";
  const codeGenerating = useIsGeneratingCode({
    cacheKey,
    cacheKeyValue: constructCacheKeyValue({
      codeKey: cacheKey,
      workflow: workflowRun?.workflow,
      workflowRun,
    }),
    // Script queries 404 once the source agent is deleted.
    workflowPermanentId: workflowRun?.workflow?.deleted_at
      ? undefined
      : workflowPermanentId,
    workflowRunId: runId,
  });
  const selectView = useCallback(
    (nextView: Parameters<typeof setView>[0]) => {
      setView(nextView);
      const next = new URLSearchParams(location.search);
      next.set("view", nextView);
      if (!resolveLivePanes().includes("overview")) openPane("overview");
      navigate({ search: toReadableSearch(next) }, { replace: true });
    },
    [location.search, navigate, openPane, resolveLivePanes, setView],
  );

  const focusBrowserPane = useCallback(() => {
    // An explicit "watch live": unpin back to the live edge and hand the
    // Browser pane a live intent (it may be sitting on a replay view).
    jumpToLive();
    setBrowserPaneView("live");
    openPane("browser");
    // Defer past the pane-open commit so the scroll sees the visible panel.
    requestAnimationFrame(() => {
      const reduceMotion =
        typeof window.matchMedia === "function" &&
        window.matchMedia("(prefers-reduced-motion: reduce)").matches;
      document.getElementById(studioPanelId("browser"))?.scrollIntoView({
        behavior: reduceMotion ? "auto" : "smooth",
        block: "nearest",
        inline: "nearest",
      });
    });
  }, [jumpToLive, setBrowserPaneView, openPane]);

  if (!workflowRun) {
    return null;
  }
  const provisioning =
    workflowRun.status === Status.Created ||
    workflowRun.status === Status.Queued;
  const showLive =
    !statusUnavailable && runIsExecuting(workflowRun) && !provisioning;

  return (
    <>
      <div
        role="group"
        aria-label="Run view"
        className="flex min-w-0 shrink items-center gap-1 overflow-hidden"
      >
        <ViewToggle
          active={view === "timeline"}
          onClick={() => selectView("timeline")}
          compact={compact}
          label="Timeline"
          icon={<ActivityLogIcon className="h-3 w-3" />}
        />
        <ViewToggle
          active={view === "inputs"}
          onClick={() => selectView("inputs")}
          compact={compact}
          label="Inputs"
          icon={<ListBulletIcon className="h-3 w-3" />}
        />
        <ViewToggle
          active={view === "outputs"}
          onClick={() => selectView("outputs")}
          compact={compact}
          label="Outputs"
          icon={<FileTextIcon className="h-3 w-3" />}
        />
        <DropdownMenu>
          <Tooltip>
            <TooltipTrigger asChild>
              <DropdownMenuTrigger asChild>
                <button
                  type="button"
                  aria-label="More views"
                  aria-pressed={view === "code"}
                  className={cn(
                    "inline-flex h-7 items-center gap-1.5 rounded-md px-1.5 text-xs font-medium",
                    "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
                    view === "code"
                      ? "bg-foreground text-background"
                      : "text-muted-foreground hover:bg-accent/50 hover:text-foreground",
                  )}
                >
                  {codeGenerating ? (
                    <ReloadIcon
                      data-testid="code-generating-spinner"
                      className="h-3 w-3 animate-spin"
                    />
                  ) : (
                    <DotsHorizontalIcon className="h-3 w-3" />
                  )}
                </button>
              </DropdownMenuTrigger>
            </TooltipTrigger>
            <TooltipContent side="bottom">
              {codeGenerating
                ? "Generating cached code for this run"
                : "More views"}
            </TooltipContent>
          </Tooltip>
          {/* Sized to the pane-header control grammar (11px, h-7 rows) so the
              menu reads as part of the toggle cluster, not a full-size menu. */}
          <DropdownMenuContent align="start" sideOffset={6} className="min-w-0">
            <DropdownMenuItem
              onSelect={() => selectView("code")}
              className="cursor-pointer gap-1.5 rounded px-2 py-1.5 pr-3 text-xs font-medium text-muted-foreground focus:text-foreground"
            >
              <CodeIcon className="h-3 w-3" />
              Code
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
      {showLive
        ? (() => {
            const liveChip = (
              <button
                type="button"
                onClick={focusBrowserPane}
                // Names the handoff, not the state: the Browser pane's Live
                // *view* toggle already answers to "Live".
                aria-label="Watch live in the Browser pane"
                className="inline-flex h-7 shrink-0 items-center gap-1.5 rounded-md px-1.5 text-xs font-medium text-muted-foreground hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
              >
                <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-success" />
                {compact ? null : "Live"}
              </button>
            );
            // Labelled → self-describing; icon-collapsed keeps the tooltip.
            return compact ? (
              <Tooltip>
                <TooltipTrigger asChild>{liveChip}</TooltipTrigger>
                <TooltipContent side="bottom">
                  Watch live in the Browser pane
                </TooltipContent>
              </Tooltip>
            ) : (
              liveChip
            );
          })()
        : null}
    </>
  );
}

/**
 * Right header cluster of the Overview pane: the API & Webhooks menu for the
 * inspected run, relocated from the retired run-hero header.
 */
export function RunPaneActions() {
  const compact = useStudioPaneCompact();
  const apiCredential = useApiCredential();
  const { runId } = useStudioInspectedRun();
  const { data: workflowRun, isError: statusUnavailable } =
    useWorkflowRunWithWorkflowQuery({ workflowRunId: runId });
  const [replayOpen, setReplayOpen] = useState(false);
  if (!workflowRun) {
    return null;
  }
  const finalized = runIsLogicallyFinal(workflowRun);
  const statusAlert = (
    <WorkflowRunStatusAlert
      run={workflowRun}
      title={workflowRun.workflow?.title}
      visible={!statusUnavailable && !finalized}
    />
  );
  // Legacy parity: the menu re-runs the workflow via API, which is gone with
  // the source agent. Status notifications still apply to its in-flight run.
  if (workflowRun.workflow?.deleted_at) {
    return statusAlert;
  }
  return (
    <>
      {statusAlert}
      <ApiWebhookActionsMenu
        triggerTooltip={compact ? "API & Webhooks" : undefined}
        trigger={
          <button
            type="button"
            aria-label="API & Webhooks"
            className={cn(
              "inline-flex h-7 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-md text-xs font-medium",
              compact ? "w-7 justify-center px-0" : "px-1.5",
              "text-muted-foreground hover:bg-accent hover:text-accent-foreground",
              "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
            )}
          >
            <Share1Icon className="h-3.5 w-3.5" />
            {compact ? null : "API & Webhooks"}
          </button>
        }
        getOptions={() => {
          const headers: Record<string, string> = {
            "Content-Type": "application/json",
            "x-api-key": apiCredential ?? "<your-api-key>",
          };
          const body: Record<string, unknown> = {
            workflow_id: workflowRun.workflow?.workflow_permanent_id,
            parameters: workflowRun.parameters,
            proxy_location: workflowRun.proxy_location,
          };
          if (workflowRun.max_screenshot_scrolls != null) {
            body.max_screenshot_scrolls = workflowRun.max_screenshot_scrolls;
          }
          if (workflowRun.webhook_callback_url) {
            body.webhook_url = workflowRun.webhook_callback_url;
          }
          return {
            method: "POST",
            url: `${runsApiBaseUrl}/run/workflows`,
            body,
            headers,
          } satisfies ApiCommandOptions;
        }}
        disabledReason={
          workflowRun && runIsRetryWaiting(workflowRun)
            ? "Unavailable while a retry is pending"
            : undefined
        }
        webhookDisabled={!finalized}
        onTestWebhook={() => setReplayOpen(true)}
      />
      <WebhookReplayDialog
        runId={workflowRun.workflow_run_id}
        disabled={!finalized}
        open={replayOpen}
        onOpenChange={setReplayOpen}
        hideTrigger
      />
    </>
  );
}