Skip to content

Automate browser based workflows with AI

14.0 KB
Raw Blame
import {
  ActionsApiResponse,
  ActionType,
  ReadableActionTypes,
  Status,
  WorkflowRunStatusApiResponseWithWorkflow,
  WorkflowRunRetryFields,
} from "@/api/types";
import { statusIsAFailureType } from "@/routes/tasks/types";
import {
  isBlockItem,
  WorkflowRunBlock,
  WorkflowRunTimelineItem,
} from "@/routes/workflows/types/workflowRunTypes";
import { taskV3CallText } from "@/routes/workflows/workflowBlockUtils";
import { flattenTimelineChronologically } from "@/routes/workflows/workflowRun/workflowTimelineUtils";
import {
  runIsLogicallyFinal,
  runIsLogicallyActive,
} from "../workflowRun/runRetryState";
import { isRecord } from "@/util/utils";
import { basicLocalTimeFormat, normalizeUtcTimestamp } from "@/util/timeFormat";

export type RunOutcome = "idle" | "running" | "failed" | "success";

// Sentinel formatElapsed returns for a run with no usable start; callers that
// hide the value instead of rendering a bare dash must compare against this.
export const ELAPSED_NEVER_STARTED = "—";

// Run timestamps are naive ISO (no Z), so normalize to UTC before diffing — else
// a live run's (now - start) is skewed by the local timezone offset.
export function formatElapsed(
  startIso: string | null,
  endIso: string | null,
): string {
  if (!startIso) {
    return ELAPSED_NEVER_STARTED;
  }
  const start = new Date(normalizeUtcTimestamp(startIso)).getTime();
  if (Number.isNaN(start)) {
    return ELAPSED_NEVER_STARTED;
  }
  const endMs = endIso
    ? new Date(normalizeUtcTimestamp(endIso)).getTime()
    : Date.now();
  const end = Number.isNaN(endMs) ? Date.now() : endMs;
  const sec = Math.max(0, Math.round((end - start) / 1000));
  if (sec < 60) {
    return `${sec}s`;
  }
  if (sec < 3600) {
    return `${Math.floor(sec / 60)}m ${sec % 60}s`;
  }
  // Without these, a long run reads as raw minutes — a 40-day run rendered
  // "58403m 52s", which is unreadable exactly when elapsed matters most.
  if (sec < 86400) {
    return `${Math.floor(sec / 3600)}h ${Math.floor((sec % 3600) / 60)}m`;
  }
  return `${Math.floor(sec / 86400)}d ${Math.floor((sec % 86400) / 3600)}h`;
}

// The elapsed value's hover tooltip supplements the visible Created timestamp
// with the run's queue/start/finish breakdown.
export function formatRunTimesTooltip(
  workflowRun: WorkflowRunStatusApiResponseWithWorkflow,
): string {
  const finalized = runIsLogicallyFinal(workflowRun);
  return [
    workflowRun.queued_at
      ? `Queued ${basicLocalTimeFormat(workflowRun.queued_at)}`
      : null,
    workflowRun.started_at
      ? `Started ${basicLocalTimeFormat(workflowRun.started_at)}`
      : null,
    finalized && workflowRun.finished_at
      ? `Finished ${basicLocalTimeFormat(workflowRun.finished_at)}`
      : null,
  ]
    .filter(Boolean)
    .join("\n");
}

export function runOutcomeFromStatus(
  run: ({ status: Status } & WorkflowRunRetryFields) | null | undefined,
): RunOutcome {
  if (!run) {
    return "idle";
  }
  if (runIsLogicallyActive(run)) return "running";
  if (run.status === Status.Completed) {
    return "success";
  }
  if (statusIsAFailureType(run) || run.status === Status.Canceled) {
    return "failed";
  }
  return "running";
}

// Null while the run is in-flight; the tab shows only the terminal status.
export function finalizedRunStatus(
  run: ({ status: Status } & WorkflowRunRetryFields) | null | undefined,
): Status | null {
  if (run == null) {
    return null;
  }
  return runIsLogicallyFinal(run) ? run.status : null;
}

type RunOutputSignals = Pick<
  WorkflowRunStatusApiResponseWithWorkflow,
  | "outputs"
  | "errors"
  | "downloaded_files"
  | "downloaded_file_urls"
  | "task_v2"
  | "webhook_failure_reason"
>;

// Every outputs key but the always-appended extracted_information is a block's
// returned value. Shared by the has-outputs gate and RunOutputsSection so they
// can't disagree on what counts as a code-block output.
export function outputFieldEntries(outputs: unknown): Array<[string, unknown]> {
  if (!isRecord(outputs)) {
    return [];
  }
  return Object.entries(outputs).filter(
    ([key]) => key !== "extracted_information",
  );
}

export type RunErrorRow = { code: string | null; message: string | null };

function readStringField(
  record: Record<string, unknown>,
  keys: Array<string>,
): string | null {
  for (const key of keys) {
    const value = record[key];
    if (typeof value !== "string") {
      continue;
    }
    const trimmed = value.trim();
    if (trimmed !== "") {
      return trimmed;
    }
  }
  return null;
}

// One row per distinct (code, message); a code-only entry stays a row so a
// failure with no prose still shows its code. Shared with the has-outputs gate
// so a run whose errors carry neither can't enable an empty Outputs pane.
export function runErrorRows(
  errors: Array<Record<string, unknown>>,
): RunErrorRow[] {
  const seen = new Set<string>();
  const rows: RunErrorRow[] = [];
  for (const error of errors) {
    const code = readStringField(error, ["error_code", "code"]);
    const message = readStringField(error, [
      "reasoning",
      "message",
      "detail",
      "error",
      "error_message",
      "description",
    ]);
    if (!code && !message) {
      continue;
    }
    const key = `${code ?? ""}\u0000${message ?? ""}`;
    if (seen.has(key)) {
      continue;
    }
    seen.add(key);
    rows.push({ code, message });
  }
  return rows;
}

export type RunErrorCode = { code: string; message: string | null };

// The Overview's failure line names each code once, keeping the first message
// that carried it as the hover. Built on runErrorRows so the line and
// Outputs → Errors can't disagree on which codes a run has.
export function runErrorCodes(
  errors: Array<Record<string, unknown>>,
): RunErrorCode[] {
  const byCode = new Map<string, string | null>();
  for (const row of runErrorRows(errors)) {
    if (!row.code || byCode.has(row.code)) {
      continue;
    }
    byCode.set(row.code, row.message);
  }
  return Array.from(byCode, ([code, message]) => ({ code, message }));
}

function nonEmptyString(value: unknown): boolean {
  return typeof value === "string" && value.trim() !== "";
}

// RunView's Outputs tab keys off this. The extracted_information cast below is
// unsound on purpose — a string value must stay truthy via Object.values,
// matching what RunOutputsSection renders.
export function runHasOutputs(
  workflowRun: RunOutputSignals | null | undefined,
): boolean {
  if (!workflowRun) {
    return false;
  }
  const hasErrors =
    Array.isArray(workflowRun.errors) &&
    runErrorRows(workflowRun.errors.filter(isRecord)).length > 0;
  const outputs = workflowRun.outputs;
  const extractedInformation =
    isRecord(outputs) && "extracted_information" in outputs
      ? (outputs.extracted_information as Record<string, unknown>)
      : null;
  const hasExtracted =
    extractedInformation != null &&
    Object.values(extractedInformation).some((value) => value !== null);
  // Unlike the always-appended extracted_information, a block-output key exists
  // only because a block emitted it — so its presence counts even when the value
  // is null (the normal shape for a code-only workflow with no extraction).
  const hasBlockOutputs = outputFieldEntries(outputs).length > 0;
  // A raw-count check, not RunView's deduped file list — dedup only ever
  // shrinks a non-empty input, never zeroes it out, so truthiness matches.
  const hasDownloads =
    (workflowRun.downloaded_files?.length ?? 0) > 0 ||
    (workflowRun.downloaded_file_urls?.length ?? 0) > 0;
  const hasObserverOutput = workflowRun.task_v2?.output != null;
  const hasWebhookFailure =
    nonEmptyString(workflowRun.task_v2?.webhook_failure_reason) ||
    nonEmptyString(workflowRun.webhook_failure_reason);
  return (
    hasErrors ||
    hasExtracted ||
    hasBlockOutputs ||
    hasDownloads ||
    hasObserverOutput ||
    hasWebhookFailure
  );
}

export type FilmstripFrame = {
  id: string;
  index: number;
  blockId: string;
  blockLabel: string | null;
  isBlockStart: boolean;
  actionType: ActionType;
  label: string;
  status: Status;
  blockType: string | null;
  screenshotArtifactId: string | null;
  stepId: string | null;
  actionOrder: number | null;
};

export function actionLabel(action: ActionsApiResponse): string {
  // A Task V3 description is a machine tool-call stamp ("task_v3 click #sign-in"), not a label, so
  // the action's own prose outranks it and the readable type is the floor.
  const description =
    taskV3CallText(action.description) === null
      ? action.description?.trim()
      : undefined;
  const candidate =
    action.intention?.trim() || description || action.reasoning?.trim();
  if (candidate) {
    // Goto actions surface as "page.goto <url>"; show just the URL.
    return candidate.replace(/^page\.goto\s+/i, "");
  }
  return ReadableActionTypes[action.action_type] ?? action.action_type;
}

/**
 * Flattens the run timeline tree into the ordered action frames the filmstrip
 * renders. Thought items (no screenshot) go to the details panel, not the strip.
 */
export function buildFilmstrip(
  timeline: WorkflowRunTimelineItem[] | undefined,
): FilmstripFrame[] {
  const frames: FilmstripFrame[] = [];

  // Raw timeline is newest-first; flatten chronologically so the strip reads
  // oldest→newest left-to-right and live-edge scroll lands on the newest action.
  const ordered = flattenTimelineChronologically(timeline ?? []);

  const walk = (items: WorkflowRunTimelineItem[]): void => {
    for (const item of items) {
      if (isBlockItem(item)) {
        const block = item.block;
        // block.actions is newest-first; reverse to oldest-first so the strip
        // matches the run timeline tree (which reverses it the same way).
        [...(block.actions ?? [])].reverse().forEach((action, i) => {
          frames.push({
            id: action.action_id ?? `${block.workflow_run_block_id}:${i}`,
            index: 0,
            blockId: block.workflow_run_block_id,
            blockLabel: block.label,
            isBlockStart: false,
            actionType: action.action_type,
            label: actionLabel(action),
            status: action.status,
            blockType: block.block_type ?? null,
            screenshotArtifactId: action.screenshot_artifact_id ?? null,
            stepId: action.step_id,
            actionOrder: action.action_order,
          });
        });
      }
      if (item.children.length > 0) {
        walk(item.children);
      }
    }
  };

  walk(ordered);

  frames.forEach((frame, i) => {
    const prev = i > 0 ? frames[i - 1] : undefined;
    frame.index = i + 1;
    frame.isBlockStart = !prev || prev.blockId !== frame.blockId;
  });

  return frames;
}

// The trailing leaf the run actually reached, walked in the same chronological
// order buildFilmstrip uses so the landing target and the strip cannot disagree.
// Ordering by modified_at would let a late background write on an earlier block
// claim the trailing position; a skipped block is not a state the run reached.
function lastReachedLeafBlock(
  timeline: WorkflowRunTimelineItem[],
): WorkflowRunBlock | null {
  let last: WorkflowRunBlock | null = null;
  const walk = (items: WorkflowRunTimelineItem[]): void => {
    for (const item of items) {
      if (
        isBlockItem(item) &&
        item.children.length === 0 &&
        item.block.status !== null &&
        item.block.status !== Status.Skipped
      ) {
        last = item.block;
      }
      if (item.children.length > 0) {
        walk(item.children);
      }
    }
  };
  walk(flattenTimelineChronologically(timeline));
  return last;
}

/**
 * What a finished run lands on with nothing pinned; shared by the Browser and
 * Overview panes so both resolve the same final state. The filmstrip carries
 * action frames only, so the trailing block wins exactly when it emitted no
 * actions of its own — otherwise its own last frame stays the target.
 */
export function resolveLandingSelectionId(
  frames: FilmstripFrame[],
  timeline: WorkflowRunTimelineItem[] | undefined,
  finalized: boolean,
): string | null {
  const lastFrameId = frames.length > 0 ? frames[frames.length - 1]!.id : null;
  if (!finalized) {
    return lastFrameId;
  }
  const lastBlock = lastReachedLeafBlock(timeline ?? []);
  if (!lastBlock) {
    return lastFrameId;
  }
  const blockHasFrames = frames.some(
    (frame) => frame.blockId === lastBlock.workflow_run_block_id,
  );
  return blockHasFrames ? lastFrameId : lastBlock.workflow_run_block_id;
}

export type BlockRunState = {
  status: Status | null;
  actionCount: number;
  failureReason: string | null;
  duration: number | null;
};

/**
 * Per-block run state keyed by block label, driving the editor BlockCard's inline
 * status bar. For looped blocks the latest occurrence wins.
 */
export function buildBlockStatusMap(
  timeline: WorkflowRunTimelineItem[] | undefined,
): Record<string, BlockRunState> {
  const byLabel: Record<string, BlockRunState> = {};

  const walk = (items: WorkflowRunTimelineItem[]): void => {
    for (const item of items) {
      if (isBlockItem(item)) {
        const block = item.block;
        if (block.label) {
          byLabel[block.label] = {
            status: block.status,
            actionCount: block.actions?.length ?? 0,
            failureReason: block.failure_reason,
            duration: block.duration,
          };
        }
      }
      if (item.children.length > 0) {
        walk(item.children);
      }
    }
  };

  walk(timeline ?? []);
  return byLabel;
}

/** action_id → action, for the run details panel to look up a pinned frame. */
export function buildActionIndex(
  timeline: WorkflowRunTimelineItem[] | undefined,
): Map<string, ActionsApiResponse> {
  const index = new Map<string, ActionsApiResponse>();
  const walk = (items: WorkflowRunTimelineItem[]): void => {
    for (const item of items) {
      if (isBlockItem(item)) {
        for (const action of item.block.actions ?? []) {
          if (action.action_id) {
            index.set(action.action_id, action);
          }
        }
      }
      if (item.children.length > 0) {
        walk(item.children);
      }
    }
  };
  walk(timeline ?? []);
  return index;
}