Skip to content

The platform for continuously improving AI agents.

14.1 KB
Raw Blame
// Adapted from AI SDK Agents workflow-step; source access recorded in NOTICE.md.

import type { CSSProperties, ReactNode } from "react";
import { useEffect, useState } from "react";

import { Icon as AppIcon } from "@/components/ui/icons";
import { Spinner } from "@/components/ui/spinner";
import { cn } from "@/lib/utils";
import { ComponentIcon, type IconSvgElement } from "./component-icon";

const AiBrain01Icon = AppIcon.model;
const GitBranchIcon = AppIcon.gitBranch;
const UserSwitchIcon = AppIcon.agent;
const Wrench01Icon = AppIcon.tool;

export type WorkflowStepKind = "model" | "tool" | "condition" | "handoff";

export type WorkflowStepStatus = "idle" | "running" | "done" | "error" | "skipped";

export interface WorkflowStepPort {
  id: string;
  label?: string;
}

export interface WorkflowStepRun {
  status: WorkflowStepStatus;
  label?: string;
  durationMs?: number;
  startedAt?: number;
  tokens?: number;
  summary?: string;
  error?: string;
  taken?: readonly string[];
}

const STATUS_TEXT: Record<WorkflowStepStatus, string> = {
  done: "Done",
  error: "Failed",
  idle: "Draft",
  running: "Running",
  skipped: "Skipped",
};

export type WorkflowStepPortSide = "in" | "out";

export interface WorkflowStepPortInfo extends WorkflowStepPort {
  side: WorkflowStepPortSide;
  taken: boolean;
}

const clean = (value: number | undefined): number =>
  value !== undefined && Number.isFinite(value) ? Math.max(0, value) : 0;

const trimDecimal = (value: number): string => {
  const rounded = Math.round(value * 10) / 10;
  return Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1);
};

export const formatDuration = (ms: number): string => {
  const value = clean(ms);
  if (value < 1000) {
    return `${Math.round(value)}ms`;
  }
  if (value < 60_000) {
    return `${trimDecimal(value / 1000)}s`;
  }
  const seconds = Math.round(value / 1000);
  return `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, "0")}s`;
};

export const formatTokens = (tokens: number): string => {
  const value = Math.round(clean(tokens));
  if (value < 1000) {
    return String(value);
  }
  if (value < 999_950) {
    return `${trimDecimal(value / 1000)}K`;
  }
  return `${trimDecimal(value / 1_000_000)}M`;
};

interface WorkflowStepClassNames {
  root?: string;
}

export interface WorkflowStepProps {
  kind?: WorkflowStepKind;
  title?: string;
  detail?: string;
  icon?: ReactNode;
  inputs?: readonly WorkflowStepPort[];
  outputs?: readonly WorkflowStepPort[];
  portLabels?: boolean;
  run?: WorkflowStepRun;
  now?: number;
  selected?: boolean;
  onSelect?: () => void;
  children?: ReactNode;
  renderPort: (port: WorkflowStepPortInfo) => ReactNode;
  className?: string;
  classNames?: WorkflowStepClassNames;
  style?: CSSProperties;
}

const DEFAULT_INPUTS: WorkflowStepPort[] = [{ id: "in" }];
const DEFAULT_OUTPUTS: WorkflowStepPort[] = [{ id: "out" }];
const TICK_MS = 100;
const PORT_GAP_PX = 14;

const THEME_VARS =
  "[--workflow-step-model:var(--cat-4)] [--workflow-step-tool:var(--cat-1)] [--workflow-step-condition:var(--cat-3)] [--workflow-step-handoff:var(--cat-2)] [--workflow-step-error:var(--destructive)] [--workflow-step-tone:var(--cat-4)] [--workflow-step-icon-bg:var(--accent)] [--workflow-step-port:var(--muted-foreground)]";

const KIND_ICON: Record<WorkflowStepKind, IconSvgElement> = {
  condition: GitBranchIcon,
  handoff: UserSwitchIcon,
  model: AiBrain01Icon,
  tool: Wrench01Icon,
};

const KIND_TITLE: Record<WorkflowStepKind, string> = {
  condition: "Condition",
  handoff: "Handoff",
  model: "Model call",
  tool: "Tool",
};

const FOCUS_CLASS = "focus-visible:ring-2 focus-visible:ring-ring/50  focus-visible:outline-none";

const TINT_CLASS = "duration-200 ease-out motion-reduce:transition-none";

const formatElapsed = (ms: number): string => {
  const value = clean(ms);
  return value < 60_000 ? `${(Math.floor(value / 100) / 10).toFixed(1)}s` : formatDuration(value);
};

const Elapsed = ({ now, startedAt }: { now: number | undefined; startedAt: number }) => {
  const [clock, setClock] = useState(() => Date.now());

  useEffect(() => {
    if (now !== undefined) {
      return;
    }
    const timer = setInterval(() => {
      setClock(Date.now());
    }, TICK_MS);
    return () => {
      clearInterval(timer);
    };
  }, [now]);

  return (
    // The server and the browser read the clock at different moments.
    <span suppressHydrationWarning>{formatElapsed((now ?? clock) - startedAt)}</span>
  );
};

interface ShownResult {
  failed: boolean;
  text: string | null;
  tokens: string | null;
}

const useLastResult = (result: ShownResult | null): ShownResult | null => {
  const [last, setLast] = useState(result);
  if (
    result !== null &&
    (last === null ||
      last.failed !== result.failed ||
      last.text !== result.text ||
      last.tokens !== result.tokens)
  ) {
    setLast(result);
    return result;
  }
  return result ?? last;
};

const usePreviousStatus = (status: WorkflowStepStatus): WorkflowStepStatus => {
  const [trail, setTrail] = useState({ current: status, previous: status });
  if (trail.current !== status) {
    setTrail({ current: status, previous: trail.current });
    return trail.current;
  }
  return trail.previous;
};

const Collapse = ({ children, open }: { children: ReactNode; open: boolean }) => (
  <div
    className={cn(
      "grid transition-[grid-template-rows,opacity] duration-200 ease-[cubic-bezier(0.25,1,0.5,1)] motion-reduce:transition-none",
      open ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0"
    )}
    inert={!open}
  >
    <div className="min-h-0 overflow-hidden">{children}</div>
  </div>
);

const Port = ({
  port,
  renderPort,
}: {
  port: WorkflowStepPortInfo;
  renderPort: (port: WorkflowStepPortInfo) => ReactNode;
}) => (
  <span
    className="absolute size-0"
    data-port={port.id}
    data-side={port.side}
    data-slot="workflow-step-port"
    data-taken={port.taken ? "true" : undefined}
  >
    {renderPort(port)}
  </span>
);

const StatusText = ({
  className,
  now,
  run,
}: {
  className?: string;
  now: number | undefined;
  run: WorkflowStepRun | undefined;
}) => {
  const status = run?.status ?? "idle";

  const timed = status === "done" && run?.durationMs !== undefined;
  return (
    <span
      className={cn(
        "inline-flex h-6 flex-none items-center gap-1 text-xs leading-none text-muted-foreground tabular-nums",
        status === "error" && "font-medium text-(--workflow-step-error)",
        className
      )}
      data-slot="workflow-step-status"
    >
      {status === "running" ? <Spinner size="sm" /> : null}
      {status === "running" && run?.startedAt !== undefined ? (
        <Elapsed now={now} startedAt={run.startedAt} />
      ) : null}
      {status === "running" && run?.startedAt === undefined ? STATUS_TEXT.running : null}
      {timed ? formatDuration(clean(run?.durationMs)) : null}
      {status !== "running" && !timed ? (run?.label ?? STATUS_TEXT[status]) : null}
    </span>
  );
};

export const WorkflowStep = ({
  kind = "model",
  title,
  detail,
  icon,
  inputs = DEFAULT_INPUTS,
  outputs = DEFAULT_OUTPUTS,
  portLabels = true,
  run,
  now,
  selected = false,
  onSelect,
  renderPort,
  children,
  className,
  classNames,
  style,
}: WorkflowStepProps) => {
  const status = run?.status ?? "idle";
  const name = title ?? KIND_TITLE[kind];
  // Several ways out, or any with a name, are listed so each has its own row.
  const listed =
    portLabels && (outputs.length > 1 || outputs.some((port) => port.label !== undefined));
  // A finished run with nothing said about its way out left through every output.
  const isTaken = (port: WorkflowStepPort): boolean =>
    status === "done" && (run?.taken === undefined || run.taken.includes(port.id));
  const reached = status === "done" || status === "error" || status === "running";
  const ran = status === "done" || status === "error";
  const failed = status === "error";
  const text = failed ? (run?.error ?? "The step failed.") : (run?.summary ?? null);
  const tokens = ran && run?.tokens !== undefined ? `${formatTokens(run.tokens)} tokens` : null;
  const hasResult = ran && (text !== null || tokens !== null);
  // A row that is closing keeps what it last said until it is shut.
  const shown = useLastResult(hasResult ? { failed, text, tokens } : null);
  // A rerun keeps the last result in place, dimmed, until the new one lands.
  const previous = usePreviousStatus(status);
  const stale =
    status === "running" && (previous === "done" || previous === "error") && shown !== null;
  const showResult = hasResult || stale;
  const hasBody = listed || showResult || Boolean(children);

  const heading = (
    <>
      <span
        className={cn(
          "inline-flex size-6 flex-none items-center justify-center rounded-md [&_img]:size-full [&_img]:rounded-sm [&_img]:object-cover [&_svg]:size-3.5",
          icon ? "bg-muted " : "bg-(--workflow-step-icon-bg) text-(--workflow-step-tone)"
        )}
        data-slot="workflow-step-icon"
      >
        {icon ?? <ComponentIcon aria-hidden="true" icon={KIND_ICON[kind]} strokeWidth={2} />}
      </span>
      <span className="flex min-w-0 flex-1 flex-col gap-0.5 pt-1">
        <span
          className={cn("truncate text-xs leading-4 font-medium ")}
          data-slot="workflow-step-title"
          title={name}
        >
          {name}
        </span>
        {detail ? (
          <span
            className={cn("truncate text-xs leading-4 text-muted-foreground")}
            data-slot="workflow-step-detail"
            title={detail}
          >
            {detail}
          </span>
        ) : null}
      </span>
    </>
  );

  const result = shown ? (
    <div
      className={cn(
        "flex min-w-0 items-baseline gap-2 transition-opacity",
        TINT_CLASS,
        stale && "opacity-45",
        listed && "mt-1.5 border-t border-border/60 pt-1.5"
      )}
      data-slot="workflow-step-result"
    >
      <span
        className={cn(
          "line-clamp-2 min-w-0 flex-1 text-pretty",
          shown.failed ? "text-(--workflow-step-error)" : "text-card-foreground"
        )}
        title={shown.text ?? undefined}
      >
        {shown.text}
      </span>
      {shown.tokens ? (
        <span className="flex-none text-muted-foreground tabular-nums">{shown.tokens}</span>
      ) : null}
    </div>
  ) : null;

  const well = (
    <div
      className={cn("flex min-w-0 flex-col rounded-md bg-muted px-2 py-1.5 text-xs leading-4 ")}
      data-slot="workflow-step-body"
    >
      {listed ? (
        <div className="flex min-w-0 flex-col gap-1.5">
          {outputs.map((port) => {
            const taken = isTaken(port);
            const label = port.label ?? port.id;
            return (
              <div
                className={cn(
                  "relative flex min-w-0 items-center gap-2 transition-colors",
                  TINT_CLASS,
                  status === "done" && !taken ? "text-muted-foreground/70" : "text-card-foreground"
                )}
                data-slot="workflow-step-branch"
                data-taken={taken ? "true" : undefined}
                key={port.id}
              >
                <span className="min-w-0 flex-1 truncate" title={label}>
                  {label}
                </span>
                {/* The well is inset by its own padding and the card's. */}
                <span className="absolute top-1/2 -right-4.5 size-0">
                  <Port port={{ ...port, side: "out", taken }} renderPort={renderPort} />
                </span>
              </div>
            );
          })}
        </div>
      ) : null}
      {/* Branch ports sit outside the well, so only the result is clipped. */}
      {listed ? <Collapse open={showResult}>{result}</Collapse> : result}
      {children ? (
        <div
          className={cn((listed || showResult) && "mt-1.5 border-t border-border/60 pt-1.5")}
          data-slot="workflow-step-content"
        >
          {children}
        </div>
      ) : null}
    </div>
  );

  return (
    <div
      aria-busy={status === "running" ? true : undefined}
      aria-label={`${name}, ${KIND_TITLE[kind].toLowerCase()}, ${STATUS_TEXT[status].toLowerCase()}`}
      className={cn(
        THEME_VARS,
        "relative flex w-[280px] max-w-full flex-col rounded-md border border-border bg-card p-2.5 text-card-foreground outline-2 outline-offset-1 outline-transparent transition-[opacity,outline-color] duration-200 ease-out motion-reduce:transition-none",
        className,
        classNames?.root
      )}
      data-kind={kind}
      data-selected={selected ? "true" : undefined}
      data-slot="workflow-step"
      data-status={status}
      role="group"
      style={style}
    >
      <div className={cn("flex min-w-0 items-start gap-2")} data-slot="workflow-step-header">
        {onSelect ? (
          <button
            aria-pressed={selected}
            className={cn(
              "flex min-w-0 flex-1 cursor-pointer items-start gap-2 rounded-md border-0 bg-transparent p-0 text-left text-inherit",
              FOCUS_CLASS
            )}
            onClick={onSelect}
            type="button"
          >
            {heading}
          </button>
        ) : (
          heading
        )}
        <StatusText now={now} run={run} />
      </div>

      {/* With branches or content the well always shows. Otherwise it opens with the result. */}
      {listed || children ? (
        <div className="pt-2">{well}</div>
      ) : (
        <Collapse open={hasBody}>
          <div className="pt-2">{well}</div>
        </Collapse>
      )}

      {inputs.map((port, index) => (
        <span
          className="absolute top-5.5 left-0 size-0"
          key={port.id}
          style={{ marginTop: index * PORT_GAP_PX }}
        >
          <Port port={{ ...port, side: "in", taken: reached }} renderPort={renderPort} />
        </span>
      ))}
      {listed
        ? null
        : outputs.map((port, index) => (
            <span
              className="absolute top-10 right-0 size-0"
              key={port.id}
              style={{ marginTop: index * PORT_GAP_PX }}
            >
              <Port port={{ ...port, side: "out", taken: isTaken(port) }} renderPort={renderPort} />
            </span>
          ))}
    </div>
  );
};