import { Ago, Badge, Banner, Button, LayerCard, LineBadge } from "@refs/design-system"; import { ArrowClockwiseIcon, CaretRightIcon, ShieldWarningIcon, StopCircleIcon } from "@refs/design-system/icons"; import type { CiJob, CiStepLog } from "@refs/backend/contract"; import { useEffect, useRef, useState } from "react"; import { Form, Link, data, redirect, useNavigation, useRevalidator } from "react-router"; import type { Route } from "./+types/repo-run"; import { CI_ENDED, CI_STATE_LABEL, CiStatusIcon, duration, triggerText } from "../components/ci-status"; import { stepViews, type StepView } from "../lib/ci-steps"; import { failed, formText, found, fullName, nowSeconds, refs } from "../lib/session"; export const meta: Route.MetaFunction = ({ params }) => [{ title: `Run · ${fullName(params)} · refs` }]; function pickJob(jobs: readonly CiJob[], wanted: string | null): string | null { if (wanted && jobs.some((job) => job.name === wanted)) return wanted; const order = ["running", "waiting_approval", "failed", "timed_out", "queued"]; for (const state of order) { const found = jobs.find((job) => job.state === state); if (found) return found.name; } return jobs[0]?.name ?? null; } export async function loader({ request, params, context }: Route.LoaderArgs) { const repo = await found(refs(context).repo(fullName(params))); const ci = repo.ci(); const run = await found(ci.run(params.id)); const job = pickJob(run.jobs, new URL(request.url).searchParams.get("job")); const log = job ? await ci.logs(run.id, job) : { steps: [], seq: 0 }; return { repo: repo.summary.name, run, job, log, canRun: ci.canRun, canApprove: ci.canApprove, now: nowSeconds() }; } export async function action({ request, params, context }: Route.ActionArgs) { const repo = await found(refs(context).repo(fullName(params))); const ci = repo.ci(); const form = await request.formData(); const intent = formText(form, "intent"); if (intent === "rerun") { const outcome = await ci.start(formText(form, "branch")); if (!outcome.ok) return failed(outcome.problem, { intent }); throw redirect(`/${repo.summary.name}/runs/${outcome.value.runId}`); } const outcome = intent === "cancel" ? await ci.cancel(params.id) : intent === "approved" || intent === "rejected" ? await ci.decide(params.id, formText(form, "job"), intent) : null; if (!outcome) return data({ intent, error: "Unknown action." }, { status: 400 }); return outcome.ok ? { intent, error: null } : failed(outcome.problem, { intent }); } function useRunStream(repo: string, runId: string, live: boolean, job: string | null, initial: { steps: readonly CiStepLog[]; seq: number }) { const [steps, setSteps] = useState(initial.steps); const revalidator = useRevalidator(); const revalidate = useRef(revalidator.revalidate); revalidate.current = revalidator.revalidate; useEffect(() => setSteps(initial.steps), [initial.steps, job]); useEffect(() => { if (!live) return; const source = new EventSource(`/${repo}/runs/${runId}/events`); let timer: ReturnType | null = null; const refresh = () => { timer ??= setTimeout(() => { timer = null; void revalidate.current(); }, 500); }; source.addEventListener("log", (event) => { const line = JSON.parse((event as MessageEvent).data) as { seq: number; job: string; step: number; at: number; text: string }; if (line.job !== job || line.seq <= initial.seq) return; setSteps((current) => { const step = line.step < 0 ? (current.at(-1)?.step ?? 0) : line.step; const found = current.find((entry) => entry.step === step); if (!found) return [...current, { step, text: line.text, startedAt: line.at, endedAt: null }].sort((a, b) => a.step - b.step); return current.map((entry) => (entry === found ? { ...entry, text: entry.text + line.text } : entry)); }); }); source.addEventListener("step", (event) => { const started = JSON.parse((event as MessageEvent).data) as { job: string; step: number; at: number }; if (started.job !== job) return; setSteps((current) => (current.some((entry) => entry.step === started.step) ? current : [...current, { step: started.step, text: "", startedAt: started.at, endedAt: null }].sort((a, b) => a.step - b.step))); refresh(); }); source.addEventListener("status", refresh); return () => { source.close(); if (timer) clearTimeout(timer); }; }, [repo, runId, live, job, initial.seq]); return steps; } function JobRow({ job, selected, href, canApprove, now }: { job: CiJob; selected: boolean; href: string; canApprove: boolean; now: number }) { const navigation = useNavigation(); const deciding = navigation.state === "submitting" && navigation.formData?.get("job") === job.name ? navigation.formData.get("intent") : null; return (
  • {job.name} {duration(job.startedAt, job.endedAt, now)} {job.image} {job.environment && {job.environment}} {CI_STATE_LABEL[job.state]} {job.reason && {job.reason}} {job.state === "waiting_approval" && canApprove && (
    )}
  • ); } function stepDuration(view: StepView, now: number): string | null { if (view.startedAt === null) return null; const end = view.endedAt ?? (view.state === "running" ? now * 1000 : null); if (end === null) return null; const total = Math.max(0, Math.round((end - view.startedAt) / 1000)); return total >= 60 ? `${Math.floor(total / 60)}m ${total % 60}s` : `${total}s`; } function StepSection({ view, now }: { view: StepView; now: number }) { return (
    {view.name} {stepDuration(view, now)} {view.lines.length ? (
      {view.lines.map((line, index) => (
    1. {index + 1} {line || " "}
    2. ))}
    ) : (

    {view.state === "skipped" ? "This step did not run." : view.state === "pending" ? "This step has not started." : "No output."}

    )}
    ); } function LogView({ steps, live, job, now }: { steps: readonly CiStepLog[]; live: boolean; job: CiJob | null; now: number }) { const box = useRef(null); useEffect(() => { const element = box.current; if (element && live && element.scrollHeight - element.scrollTop - element.clientHeight < 120) element.scrollTop = element.scrollHeight; }, [steps, live]); if (!job) return null; const views = stepViews(job, steps); return ( {job.name} {CI_STATE_LABEL[job.state]} {job.state === "waiting_approval" || job.state === "waiting_image" ? (

    {job.reason ?? "This job waits before it starts."}

    ) : (
    {views.map((view) => ( ))}
    )}
    ); } export default function RepoRun({ loaderData, actionData }: Route.ComponentProps) { const { repo, run, job, log, canRun, canApprove, now } = loaderData; const live = !CI_ENDED.has(run.state); const steps = useRunStream(repo, run.id, live, job, log); const navigation = useNavigation(); const busy = (intent: string) => navigation.state === "submitting" && navigation.formData?.get("intent") === intent; const selected = run.jobs.find((candidate) => candidate.name === job) ?? null; return (

    {triggerText(run)}

    {CI_STATE_LABEL[run.state]} {run.sha.slice(0, 7)} {run.pull !== null && ( #{run.pull} )} started {run.actor.name && by {run.actor.kind === "agent" ? `${run.actor.name}'s agent` : run.actor.name}}
    {canRun && (
    {live ? (
    ) : (
    )}
    )}
    {actionData?.error && } {!run.trusted && ( {run.trustReason} Its jobs get no secrets, and each deploy waits for a person. } /> )}
    Jobs
      {run.jobs.map((candidate) => ( ))}
    ); }