Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

17.3 KB
Raw Blame
/**
 * FlowRunInspectorDrawer (issue B3b)
 * ----------------------------------
 *
 * Right-side drawer showing a single durable `tinyflows` run's status + step
 * timeline, opened from the "View run" action on {@link FlowApprovalCard}.
 * Drawer chrome mirrors the shared Radix-backed `Sheet` overlay pattern used
 * by `features/conversations/components/AgentProcessSourcePanel.tsx` (fixed
 * overlay + backdrop-click-to-close + Escape-to-close) so it renders as a
 * fixed overlay regardless of where the parent mounts it in the DOM.
 *
 * Data comes from {@link useFlowRunPoller}, which polls
 * `openhuman.flows_get_run` every 2s until the run reaches a terminal status
 * (`completed`/`failed`) — `pending_approval` keeps polling since the run can
 * still be resumed elsewhere.
 *
 * `FlowRunStep` is lean by design (`node_id` + `output` + optional `port`
 * only — no per-step status/timing), so each step renders as a plain label
 * + collapsible output, not a graduated status timeline. Status-dot/pill
 * visual language borrows from `components/intelligence/WorkflowRunDetail.tsx`
 * (`RUN_STATUS_ACCENT`/`PHASE_STATUS_DOT`) and the agent-insights timeline's
 * own status-tone convention — dots, not progress bars (project rule).
 */
import debug from 'debug';
import { X } from 'lucide-react';

import { useEscapeKey } from '../../hooks/useEscapeKey';
import { useFlowPendingApprovals } from '../../hooks/useFlowPendingApprovals';
import { useFlowRunPoller } from '../../hooks/useFlowRunPoller';
import { type FlowNodeRunStatus, useFlowRunProgress } from '../../hooks/useFlowRunProgress';
import { type FlowRunItem, normalizeItems } from '../../lib/flows/runItems';
import { summarizeStep } from '../../lib/flows/runStepSummary';
import { formatRunTimestamp } from '../../lib/flows/runTimestamp';
import { useT } from '../../lib/i18n/I18nContext';
import type { FlowRunStep } from '../../services/api/flowsApi';
import { Alert, AlertDescription, Badge, Button, CenteredLoadingState } from '../ui';
import { FlowRunPendingApprovalCard } from './FlowRunPendingApprovalCard';
import { flowRunStatusDotClass, flowRunStatusLabel, flowRunStatusVariant } from './FlowRunStatus';
import { RunItemDataBrowser } from './RunItemDataBrowser';

/**
 * Context handed to the "Fix with agent" action (Phase 5c) so the canvas
 * copilot can open preloaded with the failed run. `flowId` routes to the flow's
 * canvas; the rest seeds the repair prompt.
 */
export interface FlowRepairRequest {
  flowId: string;
  runId: string;
  error?: string | null;
  failingNodeIds?: string[];
}

const log = debug('flows:run-inspector-drawer');

/**
 * Live per-node status dot colour, keyed off the socket `flow:run_progress`
 * feed (Phase 3e). Mirrors the run-level status-dot language:
 * primary (running, pulsing), sage (success), coral (error). Falls back to the
 * faint dot when the node has no live status yet (the poller stays the source
 * of truth for the durable step list).
 */
const FLOW_STEP_LIVE_DOT: Record<string, string> = {
  running: 'bg-primary-500 animate-pulse',
  success: 'bg-sage-500',
  error: 'bg-coral-500',
  failed: 'bg-coral-500',
};

/** Text color per plain-language summary outcome (issue B20). */
const STEP_SUMMARY_TEXT_CLASS: Record<'success' | 'error' | 'neutral', string> = {
  success: 'text-content-secondary',
  error: 'text-coral-600 dark:text-coral-400',
  neutral: 'italic text-content-faint',
};

/** Leading emoji per plain-language summary outcome (issue B20). */
const STEP_SUMMARY_EMOJI: Record<'success' | 'error' | 'neutral', string> = {
  success: '✅',
  error: '❌',
  neutral: '',
};

function StepRow({
  step,
  index,
  liveStatus,
  inputItems,
}: {
  step: FlowRunStep;
  index: number;
  liveStatus?: FlowNodeRunStatus;
  /**
   * Normalized items of this step's *input* (the upstream step's output) so the
   * data browser can resolve `paired_item` back to a source input item.
   * Omitted for the first step, which has no upstream producer here.
   */
  inputItems?: FlowRunItem[];
}) {
  const { t } = useT();
  const items = normalizeItems(step.output);
  // Live socket status (Phase 3e) takes priority while the run is in flight;
  // once it's gone quiet (drawer reopened after the fact), fall back to the
  // durable per-step `status` the observer recorded (`services/api/flowsApi.ts`).
  const dotClass =
    (liveStatus && FLOW_STEP_LIVE_DOT[liveStatus]) ??
    (step.status && FLOW_STEP_LIVE_DOT[step.status]) ??
    'bg-content-faint';
  const summary = summarizeStep({ status: step.status }, items, t);

  return (
    <li
      data-testid={`flow-run-step-${index}`}
      className="rounded-lg border border-line bg-surface-muted p-2.5 text-xs">
      <div className="flex flex-wrap items-center gap-1.5">
        <span
          data-testid={`flow-run-step-dot-${index}`}
          className={`h-1.5 w-1.5 flex-none rounded-full ${dotClass}`}
          aria-hidden
        />
        <span className="truncate font-mono font-medium text-content-secondary">
          {step.node_id}
        </span>
        {step.port !== undefined && (
          <Badge variant="neutral" data-testid={`flow-run-step-port-${index}`}>
            {t('flowRuns.inspector.port')}: {step.port}
          </Badge>
        )}
      </div>
      {/* Null-resolution diagnostics: each config `=`-expression that resolved
          to null during this step (a wiring smell, not a hard failure). */}
      {step.diagnostics && step.diagnostics.length > 0 && (
        <div
          data-testid={`flow-run-step-diagnostics-${index}`}
          className="mt-1.5 rounded-lg border border-amber-200 bg-amber-50 px-2 py-1.5 text-[11px] text-amber-700 dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-300">
          <div className="font-medium">{t('flowRuns.inspector.diagnosticsTitle')}</div>
          <ul className="mt-0.5 space-y-0.5">
            {step.diagnostics.map((diag, diagIdx) => (
              <li key={`${diag.location}-${diagIdx}`} className="break-all font-mono">
                {diag.location} ← {diag.expression}{' '}
                <span className="font-sans">{t('flowRuns.inspector.diagnosticResolvedNull')}</span>
              </li>
            ))}
          </ul>
        </div>
      )}
      {/* Plain-language summary (issue B20) — the primary, always-visible view
          of what this step did. Raw Composio/tool JSON (costUsd, labelIds,
          markdownFormatted, …) lives only behind the "Show raw output"
          disclosure below, never here. */}
      <div
        data-testid={`flow-run-step-summary-${index}`}
        className={`mt-1.5 text-[11px] ${STEP_SUMMARY_TEXT_CLASS[summary.outcome]}`}>
        {STEP_SUMMARY_EMOJI[summary.outcome] && (
          <span aria-hidden>{STEP_SUMMARY_EMOJI[summary.outcome]} </span>
        )}
        {summary.text}
      </div>
      {items.length > 0 && (
        <details className="mt-1.5">
          <summary className="cursor-pointer text-[11px] font-medium text-content-faint hover:text-content-secondary">
            {t('flowRuns.inspector.output')}
          </summary>
          <div className="mt-1.5">
            <RunItemDataBrowser
              items={items}
              inputItems={inputItems}
              testIdPrefix={`flow-run-step-${index}`}
            />
          </div>
        </details>
      )}
    </li>
  );
}

interface Props {
  /** Run id (== thread_id) to inspect. Renders `null` (nothing) when absent. */
  runId: string | null;
  onClose: () => void;
  /**
   * "Fix with agent" (Phase 5c) — when provided and the run failed, a repair
   * action surfaces that hands the run context up so the host can open the
   * canvas copilot preloaded. Omitted where there's no copilot to route to.
   */
  onFixWithAgent?: (request: FlowRepairRequest) => void;
  /**
   * `drawer` (default): a fixed right-side overlay with a backdrop. `panel`:
   * the same header + body laid out to fill a host container (the workflow
   * editor's side panel), with no overlay and no backdrop.
   */
  variant?: 'drawer' | 'panel';
}

/**
 * Renders `null` when `runId` is `null` so the parent can mount this
 * unconditionally and just flip `runId` (same convention as
 * `AgentProcessSourcePanel`).
 */
export function FlowRunInspectorDrawer({
  runId,
  onClose,
  onFixWithAgent,
  variant = 'drawer',
}: Props) {
  const { t } = useT();
  const { run, loading, error } = useFlowRunPoller(runId);
  // Live per-node status overlay (Phase 3e): the socket feed makes the poller's
  // durable step list feel live without replacing it as the source of truth.
  const liveStatuses = useFlowRunProgress(runId);
  // Actionable approval gates for this run (flow-approval surface — run
  // details). Only polls while the run is in an active state; `null`/`null`
  // stops the underlying poll loop.
  const isActiveRun = !!run && (run.status === 'running' || run.status === 'pending_approval');
  const {
    approvals: pendingApprovals,
    decidingId: decidingApprovalId,
    error: pendingApprovalsError,
    decide: decideApproval,
  } = useFlowPendingApprovals(
    isActiveRun && run ? run.flow_id : null,
    isActiveRun && run ? run.thread_id : null
  );

  const handleFixWithAgent = () => {
    if (!run || !onFixWithAgent) return;
    // Best-effort failing-node hints from the live status feed (error/failed).
    const failingNodeIds = Object.entries(liveStatuses)
      .filter(([, status]) => status === 'error' || status === 'failed')
      .map(([nodeId]) => nodeId);
    log(
      'fix-with-agent: flow=%s run=%s failing=%d',
      run.flow_id,
      run.thread_id,
      failingNodeIds.length
    );
    onFixWithAgent({
      flowId: run.flow_id,
      runId: run.thread_id,
      error: run.error,
      failingNodeIds: failingNodeIds.length > 0 ? failingNodeIds : undefined,
    });
  };

  useEscapeKey(
    () => {
      log('escape: closing runId=%s', runId);
      onClose();
    },
    runId !== null && variant === 'drawer'
  );

  if (!runId) return null;

  const startedAt = formatRunTimestamp(run?.started_at, { withSeconds: true });
  const finishedAt = formatRunTimestamp(run?.finished_at, { withSeconds: true });

  const content = (
    <>
      {/* Header */}
      <header className="flex items-start gap-2.5 border-b border-line px-4 py-3">
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-2">
            <span className="truncate font-semibold text-content">
              {t('flowRuns.inspector.title')}
            </span>
            {run && (
              <span
                data-testid="flow-run-status-dot"
                data-status={run.status}
                className={`h-2 w-2 shrink-0 rounded-full ${flowRunStatusDotClass(run.status)}`}
              />
            )}
          </div>
          <div className="mt-1 flex flex-wrap items-center gap-1.5 text-[11px] text-content-muted">
            {run && (
              <Badge
                variant={flowRunStatusVariant(run.status)}
                data-testid="flow-run-status-pill"
                data-status={run.status}>
                {flowRunStatusLabel(run.status, t)}
              </Badge>
            )}
            {/* Internal ids are dev/debug info, not primary-view content (issue
                  B20) — shown short-form only, full value on hover via `title`,
                  matching `FlowRunsDrawer`'s row-level `run.id.slice(0, 8)`. */}
            {run && (
              <span className="truncate font-mono" title={run.flow_id}>
                {run.flow_id.slice(0, 8)}
              </span>
            )}
            {run && (
              <span className="truncate font-mono" title={run.thread_id}>
                {run.thread_id.slice(0, 8)}
              </span>
            )}
          </div>
        </div>
        <Button
          type="button"
          variant="tertiary"
          size="xs"
          iconOnly
          data-testid="flow-run-inspector-close"
          onClick={onClose}
          aria-label={t('conversations.subagent.close')}
          className="shrink-0">
          <X className="h-3.5 w-3.5" aria-hidden />
        </Button>
      </header>

      <div className="flex-1 space-y-3 overflow-y-auto px-4 py-4">
        {loading && !run && (
          <div data-testid="flow-run-inspector-loading">
            <CenteredLoadingState label={t('flowRuns.inspector.loading')} />
          </div>
        )}

        {error && (
          <Alert variant="destructive" density="compact" data-testid="flow-run-inspector-error">
            <AlertDescription>
              {t('flowRuns.inspector.loadError')}: {error}
            </AlertDescription>
          </Alert>
        )}

        {run && (
          <>
            {/* Timing */}
            <div className="text-xs text-content-muted" data-testid="flow-run-timing">
              {startedAt && (
                <div>
                  {t('flowRuns.inspector.startedAt')}: {startedAt}
                </div>
              )}
              {finishedAt ? (
                <div>
                  {t('flowRuns.inspector.finishedAt')}: {finishedAt}
                </div>
              ) : run.status === 'running' || run.status === 'pending_approval' ? (
                <div className="animate-pulse">{t('flowRuns.inspector.running')}</div>
              ) : null}
            </div>

            {/* Error banner */}
            {run.error && (
              <Alert variant="destructive" density="compact" data-testid="flow-run-error-banner">
                <AlertDescription>
                  {t('flowRuns.inspector.error')}: {run.error}
                </AlertDescription>
              </Alert>
            )}

            {/* Repair entry point (Phase 5c): open the canvas copilot preloaded
                  with this failed run so the workflow builder can propose a fix. */}
            {run.status === 'failed' && onFixWithAgent && (
              <div>
                <Button
                  type="button"
                  variant="primary"
                  size="sm"
                  data-testid="flow-run-fix-with-agent"
                  onClick={handleFixWithAgent}>
                  {t('flowRuns.inspector.fixWithAgent')}
                </Button>
              </div>
            )}

            {/* Actionable pending-approval gates for this run (flow-approval
                  surface). Replaces the old read-only "N node(s) awaiting
                  approval" banner — Approve once / Approve always / Deny
                  resolve the gate in place via `openhuman.approval_decide`;
                  the run poller above picks up the resulting steps on its
                  own 2s cadence once the gate clears. */}
            {isActiveRun && pendingApprovals.length > 0 && (
              <div className="space-y-2" data-testid="flow-run-pending-approvals">
                <h3 className="text-xs font-semibold uppercase tracking-wide text-content-muted">
                  {t('flowRuns.inspector.pendingApprovals')}
                </h3>
                {pendingApprovals.map(approval => (
                  <FlowRunPendingApprovalCard
                    key={approval.request_id}
                    approval={approval}
                    deciding={decidingApprovalId === approval.request_id}
                    onDecide={decision => decideApproval(approval.request_id, decision)}
                  />
                ))}
                {pendingApprovalsError && (
                  <p
                    role="alert"
                    data-testid="flow-run-pending-approvals-error"
                    className="text-xs text-coral-600 dark:text-coral-400">
                    {t('flowRuns.inspector.approval.loadError')}
                  </p>
                )}
              </div>
            )}

            {/* Steps timeline */}
            <div>
              <h3 className="mb-1.5 text-xs font-semibold uppercase tracking-wide text-content-muted">
                {t('flowRuns.inspector.steps')}
              </h3>
              {run.steps.length === 0 ? (
                <p className="text-xs italic text-content-faint">
                  {t('flowRuns.inspector.noSteps')}
                </p>
              ) : (
                <ol className="space-y-2" data-testid="flow-run-steps">
                  {run.steps.map((step, idx) => (
                    <StepRow
                      key={`${step.node_id}-${idx}`}
                      step={step}
                      index={idx}
                      liveStatus={liveStatuses[step.node_id]}
                      inputItems={idx > 0 ? normalizeItems(run.steps[idx - 1].output) : undefined}
                    />
                  ))}
                </ol>
              )}
            </div>
          </>
        )}
      </div>
    </>
  );

  if (variant === 'panel') {
    return (
      <div className="flex h-full min-h-0 flex-col" data-testid="flow-run-inspector-panel">
        {content}
      </div>
    );
  }

  return (
    <div className="fixed inset-0 z-50 flex justify-end" data-testid="flow-run-inspector-drawer">
      {/* Backdrop */}
      <Button
        type="button"
        variant="tertiary"
        aria-label={t('conversations.subagent.close')}
        data-testid="flow-run-inspector-backdrop"
        className="absolute inset-0 h-auto w-auto rounded-none bg-surface-overlay/50 backdrop-blur-sm hover:bg-surface-overlay/50"
        onClick={onClose}
      />
      <aside className="relative flex h-full w-full max-w-md flex-col bg-surface shadow-xl">
        {content}
      </aside>
    </div>
  );
}