SPB Git

Repository Public

ActionView.tsx 13.1 KB 215 lines tsx

1"use client";2import Link from "next/link";3import { useQueryClient } from "@tanstack/react-query";4import { useCallback, useEffect, useRef, useState } from "react";5import { apiGet, apiPost, type Schemas } from "@/api/client";6import { ApiError } from "@/api/errors";7import { invalidatePaths, useApiQuery } from "@/api/query";8import { useI18n } from "@/i18n";9import { Page } from "@/shell/AppShell";10import { hrefFor } from "@/shell/nav";11import { useEvent } from "@/shell/realtime";12import { useSession } from "@/shell/session";13import { Badge, Banner, Button, ConfirmDialog, CopyButton, DataStamp, Dialog, EmptyState, KeyValue, LogView, QueryBoundary, StateDot, TextAreaField, actionIcon, actionTone, criticalityTone, cx, useErrorMessage, useToast, type LogLine } from "@/ui";1415type Action = Schemas["Action"];16const TERMINAL: readonly Schemas["ActionState"][] = ["succeeded", "failed", "cancelled", "timed_out", "rejected", "expired"];17export const isTerminal = (s: Schemas["ActionState"]) => TERMINAL.includes(s);1819/** Incremental output: pages through GET /actions/{id}/output and appends `action.output` events as they arrive. */20function useActionOutput(id: string, live: boolean, enabled: boolean) {21  const [lines, setLines] = useState<Map<number, LogLine>>(new Map());22  const [truncated, setTruncated] = useState(false);23  const [error, setError] = useState<ApiError | null>(null);24  const after = useRef(0);25  const running = useRef(false);2627  const add = useCallback((events: { id: number; data: string; stream?: "stdout" | "stderr" | undefined; kind?: string }[]) => {28    if (events.length === 0) return;29    setLines((prev) => {30      const next = new Map(prev);31      for (const e of events) next.set(e.id, { id: e.id, text: e.data, stream: e.stream ?? (e.kind && e.kind !== "output" ? "system" : undefined) });32      return next;33    });34  }, []);3536  const pull = useCallback(async () => {37    if (running.current || !enabled) return;38    running.current = true;39    try {40      for (let guard = 0; guard < 50; guard++) {41        const page = await apiGet("/actions/{id}/output", { path: { id }, query: { after: after.current, limit: 500 } });42        add(page.items);43        if (page.truncated) setTruncated(true);44        const advanced = page.next_after > after.current;45        after.current = Math.max(after.current, page.next_after);46        if (page.items.length === 0 || !advanced) break;47      }48      setError(null);49    } catch (e) {50      if (e instanceof ApiError) setError(e);51    } finally {52      running.current = false;53    }54  }, [id, enabled, add]);5556  useEffect(() => {57    void pull();58    if (!live) return;59    const timer = window.setInterval(() => void pull(), 3000);60    return () => window.clearInterval(timer);61  }, [pull, live]);6263  useEvent("action.output", (e) => {64    if (e.action_id === id) add([{ id: e.event_id, data: e.data, stream: e.stream }]);65  });6667  return { lines: [...lines.values()].sort((a, b) => Number(a.id) - Number(b.id)), truncated, error, refresh: pull };68}6970export function ActionView({ id }: { id: string }) {71  const { t } = useI18n();72  const qc = useQueryClient();73  const q = useApiQuery("/actions/{id}", { path: { id } }, { refetchInterval: (query) => (query.state.data && !isTerminal(query.state.data.action.state) ? 4000 : false) });74  useEvent("action.changed", (e) => {75    if (e.action_id === id) void invalidatePaths(qc, "/actions");76  });77  return (78    <Page title={q.data ? (q.data.action.target_label ? `${q.data.action.type} · ${q.data.action.target_label}` : q.data.action.type) : t("actions.view.title")} sub={<span className="mono">{id}</span>}>79      <QueryBoundary query={q}>{(d) => <ActionBody detail={d} updatedAt={q.dataUpdatedAt} />}</QueryBoundary>80    </Page>81  );82}8384function ActionBody({ detail, updatedAt }: { detail: Schemas["ActionDetail"]; updatedAt: number }) {85  const { t, fmt } = useI18n();86  const session = useSession();87  const toast = useToast();88  const explain = useErrorMessage();89  const qc = useQueryClient();90  const a = detail.action;91  const live = !isTerminal(a.state);92  const canLogs = session.can("logs.read") || session.can("actions.read");93  const output = useActionOutput(a.id, live, canLogs);94  const [dialog, setDialog] = useState<"approve" | "reject" | "cancel" | null>(null);95  const [text, setText] = useState("");96  const [busy, setBusy] = useState(false);9798  // one last pull when the action reaches a terminal state99  const wasLive = useRef(live);100  useEffect(() => {101    if (wasLive.current && !live) void output.refresh();102    wasLive.current = live;103  }, [live, output]);104105  const run = async (fn: () => Promise<Action>, done: string) => {106    setBusy(true);107    try {108      await fn();109      toast({ tone: "ok", title: done });110      setDialog(null);111      setText("");112      await invalidatePaths(qc, "/actions");113    } catch (e) {114      toast({ tone: "critical", ...explain(e) });115    } finally {116      setBusy(false);117    }118  };119120  const steps: { key: string; label: string; at?: string | undefined; tone: "ok" | "info" | "critical" | "warning" | "offline" }[] = [121    { key: "created", label: t("actions.view.step.created", { name: a.requested_by_display_name ?? t("actions.view.someone"), via: a.requested_via }), at: a.created_at, tone: "ok" },122    ...(a.approval_required ? [{ key: "approval", label: a.approved_at ? t("actions.view.step.approved", { name: a.approved_by_display_name ?? "" }) : a.state === "rejected" ? t("actions.view.step.rejected") : t("actions.view.step.awaitingApproval"), at: a.approved_at, tone: a.approved_at ? ("ok" as const) : a.state === "rejected" ? ("critical" as const) : ("warning" as const) }] : []),123    { key: "queued", label: t("actions.view.step.queued"), at: a.queued_at, tone: "info" },124    { key: "started", label: t("actions.view.step.started"), at: a.started_at, tone: "info" },125    { key: "finished", label: t("actions.view.step.finished", { state: t(`states.action.${a.state}`) }), at: a.finished_at, tone: a.state === "succeeded" ? "ok" : a.state === "cancelled" || a.state === "rejected" || a.state === "expired" ? "offline" : "critical" },126  ];127128  return (129    <>130      <div className="row-between">131        <div className="row-wrap" role="status" aria-live="polite" data-testid="action-state" data-state={a.state}>132          <StateDot tone={actionTone(a.state)} icon={actionIcon(a.state)} label={t(`states.action.${a.state}`)} />133          <Badge tone={criticalityTone(a.criticality)}>{t(`states.criticality.${a.criticality}`)}</Badge>134          {a.outcome_unknown ? <Badge tone="warning" icon="unknown">{t("actions.view.outcomeUnknown")}</Badge> : null}135        </div>136        <div className="row-wrap">137          <DataStamp at={updatedAt} />138          {live && a.state !== "pending_approval" && !a.cancel_requested_at ? <Button icon="stop" onClick={() => setDialog("cancel")}>{t("actions.view.cancel")}</Button> : null}139        </div>140      </div>141142      {a.outcome_unknown ? <Banner tone="warning" icon="unknown" role="alert"><strong>{t("actions.view.outcomeUnknown")}.</strong> {t("actions.view.outcomeUnknownBody")}</Banner> : null}143      {a.cancel_requested_at && live ? <Banner tone="info">{t("actions.view.cancelRequested", { time: fmt.time(a.cancel_requested_at) })}</Banner> : null}144      {a.state === "pending_approval" ? (145        <Banner tone="warning" icon="users"146          actions={session.can("actions.approve") ? (147            <span className="row">148              <Button size="sm" variant="primary" onClick={() => setDialog("approve")} data-testid="action-approve">{t("actions.view.approve")}</Button>149              <Button size="sm" variant="danger" onClick={() => setDialog("reject")}>{t("actions.view.reject")}</Button>150            </span>151          ) : undefined}>152          {t("actions.view.pendingApprovalBody")} {session.can("actions.approve") ? t("actions.view.approverNote") : t("actions.view.notApprover")}153        </Banner>154      ) : null}155      {a.error_message || a.error_code ? <Banner tone="critical" role="alert"><strong className="mono">{a.error_code}</strong> {a.error_message}</Banner> : null}156      {a.rejection_reason ? <Banner tone="offline">{t("actions.view.rejectionReason")} {a.rejection_reason}</Banner> : null}157158      <div className="cols-2">159        <section className="section" aria-label={t("actions.view.details")}>160          <h2>{t("actions.view.details")}</h2>161          <KeyValue162            items={[163              { label: t("actions.type"), value: <span className="mono">{a.type}</span> },164              { label: t("actions.target"), value: <Link href={hrefFor(a.target.kind, a.target.id)} className="mono">{a.target_label ?? a.target.id}</Link> },165              ...(a.node_alias && a.node_id ? [{ label: t("actions.view.node"), value: <Link href={`/nodes/${a.node_id}`} className="mono">{a.node_alias}</Link> }] : []),166              { label: t("actions.view.requestedBy"), value: a.requested_by_display_name ?? <span className="faint">{t("actions.view.someone")}</span> },167              { label: t("actions.justification"), value: a.justification ? <span className="pre">{a.justification}</span> : <span className="faint">{t("actions.view.none")}</span> },168              { label: t("actions.timeout"), value: fmt.duration(a.timeout_s) },169              ...(a.deadline_at ? [{ label: t("actions.view.deadline"), value: <span className="num">{fmt.dateTime(a.deadline_at, { seconds: true })}</span> }] : []),170              { label: t("errors.correlation"), value: <span className="row"><code>{a.correlation_id}</code><CopyButton text={a.correlation_id} label={t("errors.copyCorrelation")} /></span> },171              { label: t("actions.params"), value: Object.keys(a.params).length > 0 ? <code className="pre">{JSON.stringify(a.params, null, 2)}</code> : <span className="faint">{t("actions.view.none")}</span> },172              ...(a.job_id ? [{ label: t("actions.view.job"), value: <Link href={`/jobs/${a.job_id}`} className="mono">{a.job_id}</Link> }] : []),173            ]}174          />175        </section>176        <section className="section" aria-label={t("actions.view.progress")}>177          <h2>{t("actions.view.progress")}</h2>178          <ol className="mcc-timeline">179            {steps.map((s) => (180              <li key={s.key} className={cx(s.at ? `tone-${s.tone}` : undefined)}>181                <span className="pt" aria-hidden="true" />182                <div>183                  <div className={s.at || s.key === "approval" ? undefined : "faint"}>{s.label}</div>184                  <div className="meta num">{s.at ? fmt.dateTime(s.at, { seconds: true }) : t("actions.view.notYet")}</div>185                </div>186              </li>187            ))}188          </ol>189          {a.result && Object.keys(a.result).length > 0 ? (190            <div className="stack-sm"><h3>{t("actions.view.result")}</h3><pre className="mcc-log" tabIndex={0} aria-label={t("actions.view.result")}>{JSON.stringify(a.result, null, 2)}</pre></div>191          ) : null}192        </section>193      </div>194195      <section className="section" aria-label={t("actions.view.output")}>196        <div className="section-head"><h2>{t("actions.view.output")}</h2>{live ? <StateDot tone="info" icon="running" label={t("actions.view.streaming")} subtle /> : null}</div>197        {output.error && output.lines.length === 0 ? <Banner tone={output.error.forbidden ? "offline" : "stale"}>{output.error.forbidden ? t("actions.view.outputForbidden") : output.error.notImplemented ? t("errors.notAvailable.body") : t("actions.view.outputError")}</Banner> : null}198        <LogView lines={output.lines} label={t("actions.view.output")} truncated={output.truncated} empty={<EmptyState compact icon="terminal" title={live ? t("actions.view.noOutputYet") : t("actions.view.noOutput")} />} />199      </section>200201      <Dialog open={dialog === "approve" || dialog === "reject"} onClose={() => setDialog(null)} title={dialog === "approve" ? t("actions.view.approveTitle") : t("actions.view.rejectTitle")} description={t("actions.view.decisionBody", { type: a.type, target: a.target_label ?? a.target.id })} dismissable={!busy}202        footer={<>203          <Button onClick={() => setDialog(null)} disabled={busy}>{t("common.cancel")}</Button>204          {dialog === "approve"205            ? <Button variant="primary" loading={busy} onClick={() => void run(() => apiPost("/actions/{id}/approve", { path: { id: a.id }, body: text.trim() ? { comment: text.trim() } : {} }), t("actions.view.approved"))} data-testid="action-approve-confirm">{t("actions.view.approve")}</Button>206            : <Button variant="danger" loading={busy} disabled={text.trim() === ""} onClick={() => void run(() => apiPost("/actions/{id}/reject", { path: { id: a.id }, body: { reason: text.trim() } }), t("actions.view.rejected"))}>{t("actions.view.reject")}</Button>}207        </>}>208        <TextAreaField label={dialog === "approve" ? t("actions.view.comment") : t("actions.view.reason")} required={dialog === "reject"} value={text} onChange={setText} maxLength={500} />209      </Dialog>210      <ConfirmDialog open={dialog === "cancel"} onClose={() => setDialog(null)} busy={busy} danger title={t("actions.view.cancelTitle")} body={t("actions.view.cancelBody")} confirmLabel={t("actions.view.cancel")}211        onConfirm={() => void run(() => apiPost("/actions/{id}/cancel", { path: { id: a.id } }), t("actions.view.cancelSent"))} />212    </>213  );214}215
Files main
Menu

Theme