255 lines · 12.7 KBRaw
| 1 | import { Ago, Badge, Banner, Button, LayerCard, LineBadge } from "@refs/design-system"; |
| 2 | import { ArrowClockwiseIcon, CaretRightIcon, ShieldWarningIcon, StopCircleIcon } from "@refs/design-system/icons"; |
| 3 | import type { CiJob, CiStepLog } from "@refs/backend/contract"; |
| 4 | import { useEffect, useRef, useState } from "react"; |
| 5 | import { Form, Link, data, redirect, useNavigation, useRevalidator } from "react-router"; |
| 6 | import type { Route } from "./+types/repo-run"; |
| 7 | import { CI_ENDED, CI_STATE_LABEL, CiStatusIcon, duration, triggerText } from "../components/ci-status"; |
| 8 | import { stepViews, type StepView } from "../lib/ci-steps"; |
| 9 | import { failed, formText, found, fullName, nowSeconds, refs } from "../lib/session"; |
| 10 | |
| 11 | export const meta: Route.MetaFunction = ({ params }) => [{ title: `Run · ${fullName(params)} · refs` }]; |
| 12 | |
| 13 | function pickJob(jobs: readonly CiJob[], wanted: string | null): string | null { |
| 14 | if (wanted && jobs.some((job) => job.name === wanted)) return wanted; |
| 15 | const order = ["running", "waiting_approval", "failed", "timed_out", "queued"]; |
| 16 | for (const state of order) { |
| 17 | const found = jobs.find((job) => job.state === state); |
| 18 | if (found) return found.name; |
| 19 | } |
| 20 | return jobs[0]?.name ?? null; |
| 21 | } |
| 22 | |
| 23 | export async function loader({ request, params, context }: Route.LoaderArgs) { |
| 24 | const repo = await found(refs(context).repo(fullName(params))); |
| 25 | const ci = repo.ci(); |
| 26 | const run = await found(ci.run(params.id)); |
| 27 | const job = pickJob(run.jobs, new URL(request.url).searchParams.get("job")); |
| 28 | const log = job ? await ci.logs(run.id, job) : { steps: [], seq: 0 }; |
| 29 | return { repo: repo.summary.name, run, job, log, canRun: ci.canRun, canApprove: ci.canApprove, now: nowSeconds() }; |
| 30 | } |
| 31 | |
| 32 | export async function action({ request, params, context }: Route.ActionArgs) { |
| 33 | const repo = await found(refs(context).repo(fullName(params))); |
| 34 | const ci = repo.ci(); |
| 35 | const form = await request.formData(); |
| 36 | const intent = formText(form, "intent"); |
| 37 | if (intent === "rerun") { |
| 38 | const outcome = await ci.start(formText(form, "branch")); |
| 39 | if (!outcome.ok) return failed(outcome.problem, { intent }); |
| 40 | throw redirect(`/${repo.summary.name}/runs/${outcome.value.runId}`); |
| 41 | } |
| 42 | const outcome = intent === "cancel" ? await ci.cancel(params.id) : intent === "approved" || intent === "rejected" ? await ci.decide(params.id, formText(form, "job"), intent) : null; |
| 43 | if (!outcome) return data({ intent, error: "Unknown action." }, { status: 400 }); |
| 44 | return outcome.ok ? { intent, error: null } : failed(outcome.problem, { intent }); |
| 45 | } |
| 46 | |
| 47 | function useRunStream(repo: string, runId: string, live: boolean, job: string | null, initial: { steps: readonly CiStepLog[]; seq: number }) { |
| 48 | const [steps, setSteps] = useState<readonly CiStepLog[]>(initial.steps); |
| 49 | const revalidator = useRevalidator(); |
| 50 | const revalidate = useRef(revalidator.revalidate); |
| 51 | revalidate.current = revalidator.revalidate; |
| 52 | useEffect(() => setSteps(initial.steps), [initial.steps, job]); |
| 53 | useEffect(() => { |
| 54 | if (!live) return; |
| 55 | const source = new EventSource(`/${repo}/runs/${runId}/events`); |
| 56 | let timer: ReturnType<typeof setTimeout> | null = null; |
| 57 | const refresh = () => { |
| 58 | timer ??= setTimeout(() => { |
| 59 | timer = null; |
| 60 | void revalidate.current(); |
| 61 | }, 500); |
| 62 | }; |
| 63 | source.addEventListener("log", (event) => { |
| 64 | const line = JSON.parse((event as MessageEvent<string>).data) as { seq: number; job: string; step: number; at: number; text: string }; |
| 65 | if (line.job !== job || line.seq <= initial.seq) return; |
| 66 | setSteps((current) => { |
| 67 | const step = line.step < 0 ? (current.at(-1)?.step ?? 0) : line.step; |
| 68 | const found = current.find((entry) => entry.step === step); |
| 69 | if (!found) return [...current, { step, text: line.text, startedAt: line.at, endedAt: null }].sort((a, b) => a.step - b.step); |
| 70 | return current.map((entry) => (entry === found ? { ...entry, text: entry.text + line.text } : entry)); |
| 71 | }); |
| 72 | }); |
| 73 | source.addEventListener("step", (event) => { |
| 74 | const started = JSON.parse((event as MessageEvent<string>).data) as { job: string; step: number; at: number }; |
| 75 | if (started.job !== job) return; |
| 76 | 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))); |
| 77 | refresh(); |
| 78 | }); |
| 79 | source.addEventListener("status", refresh); |
| 80 | return () => { |
| 81 | source.close(); |
| 82 | if (timer) clearTimeout(timer); |
| 83 | }; |
| 84 | }, [repo, runId, live, job, initial.seq]); |
| 85 | return steps; |
| 86 | } |
| 87 | |
| 88 | function JobRow({ job, selected, href, canApprove, now }: { job: CiJob; selected: boolean; href: string; canApprove: boolean; now: number }) { |
| 89 | const navigation = useNavigation(); |
| 90 | const deciding = navigation.state === "submitting" && navigation.formData?.get("job") === job.name ? navigation.formData.get("intent") : null; |
| 91 | return ( |
| 92 | <li className={`flex flex-col gap-2 px-4 py-3 shadow-[inset_0_-1px_0_var(--hairline)] last:shadow-none ${selected ? "bg-control" : "hover:bg-hover"}`}> |
| 93 | <Link to={href} replace preventScrollReset className="flex items-center gap-2.5 text-ink" aria-current={selected ? "true" : undefined}> |
| 94 | <CiStatusIcon state={job.state} /> |
| 95 | <span className="min-w-0 flex-1 truncate font-medium">{job.name}</span> |
| 96 | <span className="shrink-0 text-xs text-faint tabular-nums">{duration(job.startedAt, job.endedAt, now)}</span> |
| 97 | </Link> |
| 98 | <span className="flex flex-wrap items-center gap-1.5 pl-6.5 text-xs text-muted"> |
| 99 | <span className="font-mono">{job.image}</span> |
| 100 | {job.environment && <Badge variant="outline">{job.environment}</Badge>} |
| 101 | <span>{CI_STATE_LABEL[job.state]}</span> |
| 102 | </span> |
| 103 | {job.reason && <span className="pl-6.5 text-xs text-muted">{job.reason}</span>} |
| 104 | {job.state === "waiting_approval" && canApprove && ( |
| 105 | <Form method="post" className="flex gap-2 pl-6.5"> |
| 106 | <input type="hidden" name="job" value={job.name} /> |
| 107 | <Button type="submit" name="intent" value="approved" variant="primary" size="sm" loading={deciding === "approved"}> |
| 108 | Approve |
| 109 | </Button> |
| 110 | <Button type="submit" name="intent" value="rejected" variant="secondary" size="sm" loading={deciding === "rejected"}> |
| 111 | Reject |
| 112 | </Button> |
| 113 | </Form> |
| 114 | )} |
| 115 | </li> |
| 116 | ); |
| 117 | } |
| 118 | |
| 119 | function stepDuration(view: StepView, now: number): string | null { |
| 120 | if (view.startedAt === null) return null; |
| 121 | const end = view.endedAt ?? (view.state === "running" ? now * 1000 : null); |
| 122 | if (end === null) return null; |
| 123 | const total = Math.max(0, Math.round((end - view.startedAt) / 1000)); |
| 124 | return total >= 60 ? `${Math.floor(total / 60)}m ${total % 60}s` : `${total}s`; |
| 125 | } |
| 126 | |
| 127 | function StepSection({ view, now }: { view: StepView; now: number }) { |
| 128 | return ( |
| 129 | <details open={view.state === "failed" || view.state === "running"} className="group shadow-[inset_0_-1px_0_var(--hairline)] last:shadow-none"> |
| 130 | <summary className="flex cursor-pointer list-none items-center gap-2.5 px-4 py-2.5 text-compact select-none hover:bg-hover [&::-webkit-details-marker]:hidden"> |
| 131 | <CaretRightIcon size={12} className="shrink-0 text-faint group-open:rotate-90" aria-hidden /> |
| 132 | <CiStatusIcon state={view.state} size={14} /> |
| 133 | <span className={`min-w-0 flex-1 truncate ${view.state === "skipped" || view.state === "pending" ? "text-muted" : "text-ink"}`}>{view.name}</span> |
| 134 | <span className="shrink-0 text-xs text-faint tabular-nums">{stepDuration(view, now)}</span> |
| 135 | </summary> |
| 136 | {view.lines.length ? ( |
| 137 | <ol className="m-0 list-none bg-sunken py-2 font-mono text-xs leading-relaxed"> |
| 138 | {view.lines.map((line, index) => ( |
| 139 | <li key={index} className="grid grid-cols-[3.5rem_minmax(0,1fr)] hover:bg-hover"> |
| 140 | <span className="pr-3 text-right text-faint tabular-nums select-none">{index + 1}</span> |
| 141 | <span className="pr-4 break-all whitespace-pre-wrap text-ink">{line || " "}</span> |
| 142 | </li> |
| 143 | ))} |
| 144 | </ol> |
| 145 | ) : ( |
| 146 | <p className="m-0 bg-sunken px-4 py-2 pl-[3.75rem] text-xs text-muted">{view.state === "skipped" ? "This step did not run." : view.state === "pending" ? "This step has not started." : "No output."}</p> |
| 147 | )} |
| 148 | </details> |
| 149 | ); |
| 150 | } |
| 151 | |
| 152 | function LogView({ steps, live, job, now }: { steps: readonly CiStepLog[]; live: boolean; job: CiJob | null; now: number }) { |
| 153 | const box = useRef<HTMLDivElement>(null); |
| 154 | useEffect(() => { |
| 155 | const element = box.current; |
| 156 | if (element && live && element.scrollHeight - element.scrollTop - element.clientHeight < 120) element.scrollTop = element.scrollHeight; |
| 157 | }, [steps, live]); |
| 158 | if (!job) return null; |
| 159 | const views = stepViews(job, steps); |
| 160 | return ( |
| 161 | <LayerCard> |
| 162 | <LayerCard.Secondary className="justify-between"> |
| 163 | <span className="text-ink">{job.name}</span> |
| 164 | <span className="font-normal text-muted">{CI_STATE_LABEL[job.state]}</span> |
| 165 | </LayerCard.Secondary> |
| 166 | {job.state === "waiting_approval" || job.state === "waiting_image" ? ( |
| 167 | <p className="m-0 px-4 py-6 text-compact text-muted">{job.reason ?? "This job waits before it starts."}</p> |
| 168 | ) : ( |
| 169 | <div ref={box} className="max-h-[75vh] overflow-y-auto"> |
| 170 | {views.map((view) => ( |
| 171 | <StepSection key={view.step} view={view} now={now} /> |
| 172 | ))} |
| 173 | </div> |
| 174 | )} |
| 175 | </LayerCard> |
| 176 | ); |
| 177 | } |
| 178 | |
| 179 | export default function RepoRun({ loaderData, actionData }: Route.ComponentProps) { |
| 180 | const { repo, run, job, log, canRun, canApprove, now } = loaderData; |
| 181 | const live = !CI_ENDED.has(run.state); |
| 182 | const steps = useRunStream(repo, run.id, live, job, log); |
| 183 | const navigation = useNavigation(); |
| 184 | const busy = (intent: string) => navigation.state === "submitting" && navigation.formData?.get("intent") === intent; |
| 185 | const selected = run.jobs.find((candidate) => candidate.name === job) ?? null; |
| 186 | return ( |
| 187 | <div className="flex flex-col gap-5"> |
| 188 | <div className="flex flex-wrap items-start justify-between gap-4"> |
| 189 | <div className="flex min-w-0 flex-col gap-2"> |
| 190 | <h1 className="m-0 flex items-center gap-2.5 text-title font-semibold tracking-[-0.022em]"> |
| 191 | <CiStatusIcon state={run.state} size={22} /> |
| 192 | {triggerText(run)} |
| 193 | </h1> |
| 194 | <span className="flex flex-wrap items-center gap-x-2 gap-y-1 text-compact text-muted"> |
| 195 | <span>{CI_STATE_LABEL[run.state]}</span> |
| 196 | <LineBadge name={run.branch} /> |
| 197 | <Link to={`/${repo}/commit/${run.sha}`} className="font-mono text-xs hover:text-accent-text"> |
| 198 | {run.sha.slice(0, 7)} |
| 199 | </Link> |
| 200 | {run.pull !== null && ( |
| 201 | <Link to={`/${repo}/pulls/${run.pull}`} className="hover:text-accent-text"> |
| 202 | #{run.pull} |
| 203 | </Link> |
| 204 | )} |
| 205 | <span> |
| 206 | started <Ago at={run.createdAt} now={now} /> |
| 207 | </span> |
| 208 | {run.actor.name && <span>by {run.actor.kind === "agent" ? `${run.actor.name}'s agent` : run.actor.name}</span>} |
| 209 | </span> |
| 210 | </div> |
| 211 | {canRun && ( |
| 212 | <div className="flex gap-2"> |
| 213 | {live ? ( |
| 214 | <Form method="post"> |
| 215 | <Button type="submit" name="intent" value="cancel" variant="secondary" icon={<StopCircleIcon />} loading={busy("cancel")}> |
| 216 | Cancel run |
| 217 | </Button> |
| 218 | </Form> |
| 219 | ) : ( |
| 220 | <Form method="post"> |
| 221 | <input type="hidden" name="branch" value={run.branch} /> |
| 222 | <Button type="submit" name="intent" value="rerun" variant="secondary" icon={<ArrowClockwiseIcon />} loading={busy("rerun")}> |
| 223 | Run {run.branch} again |
| 224 | </Button> |
| 225 | </Form> |
| 226 | )} |
| 227 | </div> |
| 228 | )} |
| 229 | </div> |
| 230 | {actionData?.error && <Banner variant="error" description={actionData.error} />} |
| 231 | {!run.trusted && ( |
| 232 | <Banner |
| 233 | title="This run is untrusted" |
| 234 | description={ |
| 235 | <span className="flex items-start gap-2"> |
| 236 | <ShieldWarningIcon size={16} className="mt-px shrink-0 text-caution" aria-hidden /> |
| 237 | {run.trustReason} Its jobs get no secrets, and each deploy waits for a person. |
| 238 | </span> |
| 239 | } |
| 240 | /> |
| 241 | )} |
| 242 | <div className="grid items-start gap-5 lg:grid-cols-[18rem_minmax(0,1fr)]"> |
| 243 | <LayerCard> |
| 244 | <LayerCard.Secondary>Jobs</LayerCard.Secondary> |
| 245 | <ul className="m-0 list-none p-0"> |
| 246 | {run.jobs.map((candidate) => ( |
| 247 | <JobRow key={candidate.name} job={candidate} selected={candidate.name === job} href={`/${repo}/runs/${run.id}?job=${encodeURIComponent(candidate.name)}`} canApprove={canApprove} now={now} /> |
| 248 | ))} |
| 249 | </ul> |
| 250 | </LayerCard> |
| 251 | <LogView steps={steps} live={live} job={selected} now={now} /> |
| 252 | </div> |
| 253 | </div> |
| 254 | ); |
| 255 | } |