g1t/apps/web/app/routes/repo/actions-run.tsx

315 lines13,843 bytesCodeBlame
1import { AlertTriangle, ChevronRight, Cloud, Download, GitBranch, GitCommitHorizontal, Info, Package, RotateCw, ServerCog, Square, XCircle } from "lucide-react";
2import { type ReactNode } from "react";
3import { Form, Link, useLoaderData, useNavigation, useSearchParams } from "react-router";
4
5import type { Annotation, Job, StepState } from "@g1t/contracts";
6
7import type { Route } from "./+types/actions-run";
8import { page } from "../../lib/meta";
9import { LogText, Notes, StatusIcon, duration, shortRef, standingWord, useJobLog } from "../../components/actions";
10import { Button, ErrorText, TimeAgo } from "../../components/ui";
11import { listArtifacts } from "../../lib/artifacts.server";
12import { actions } from "../../lib/services.server";
13import { assertSameOrigin, getViewer, requireUser, roleIn, unwrap } from "../../lib/session.server";
14import { accessTo, refusal } from "../../lib/access.server";
15import { useRefreshWhile } from "../../lib/refresh";
16
17export function meta({ loaderData, params, ...args }: Route.MetaArgs) {
18 const run = loaderData?.detail.run;
19 return page(args, { title: `${run ? `${run.title || run.name} #${run.number}` : "Run"} · ${params.owner}/${params.repo} · g1t` });
20}
21
22export async function loader({ params, context }: Route.LoaderArgs) {
23 const viewer = getViewer(context);
24 const detail = unwrap(await actions.run({ namespace: params.owner, name: params.repo }, viewer, params.id));
25 const artifacts = await listArtifacts(params.id).catch(() => []);
26 // Cancelling and re-running need Write.
27 return {
28 detail,
29 artifacts,
30 member: (await accessTo(context, params)).can.run,
31 // The runners page is the workspace owners'.
32 runnersPage: roleIn(viewer, params.owner) === "owner",
33 };
34}
35
36export async function action({ request, params, context }: Route.ActionArgs) {
37 assertSameOrigin(request);
38 const user = requireUser(context, request);
39 const repo = { namespace: params.owner, name: params.repo };
40 const intent = String((await request.formData()).get("intent"));
41 const refused = await refusal(context, params, "run");
42 if (refused) return { error: refused };
43 const done =
44 intent === "cancel"
45 ? await actions.cancel(user, repo, params.id)
46 : await actions.rerun(user, repo, params.id, intent === "rerun-failed");
47 return done.ok ? {} : { error: done.error.message };
48}
49
50const ANNOTATION_ICON: Record<Annotation["level"], ReactNode> = {
51 error: <XCircle size={14} className="mt-0.5 shrink-0 text-danger" />,
52 warning: <AlertTriangle size={14} className="mt-0.5 shrink-0 text-warn" />,
53 notice: <Info size={14} className="mt-0.5 shrink-0 text-muted" />,
54};
55
56function StepRow({ step, text, defaultOpen }: { step: StepState; text: string | undefined; defaultOpen: boolean }) {
57 return (
58 <details className="group border-t border-line first:border-t-0" open={defaultOpen}>
59 <summary className="flex cursor-pointer list-none items-center gap-2.5 px-4 py-2 text-sm hover:bg-raised/40">
60 <ChevronRight size={14} className="shrink-0 text-faint transition-transform group-open:rotate-90" />
61 <StatusIcon status={step.status} conclusion={step.conclusion} size={14} />
62 <span className={`min-w-0 truncate ${step.conclusion === "skipped" ? "text-faint" : ""}`}>{step.name}</span>
63 <span className="ml-auto shrink-0 font-mono text-xs text-faint">{duration(step.startedAt, step.finishedAt)}</span>
64 </summary>
65 <div className="border-t border-line bg-bg/60">
66 {text === undefined ? (
67 <p className="px-4 py-2 text-xs text-faint">{step.status === "queued" ? "Not started." : step.conclusion === "skipped" ? "Skipped." : "No output yet."}</p>
68 ) : (
69 <LogText text={text} />
70 )}
71 </div>
72 </details>
73 );
74}
75
76/** Why a job did not run as asked, with "Integrations" linked where it says so. */
77function Reason({ text, workspace }: { text: string; workspace: string }) {
78 const [before, after] = text.split("Integrations");
79 return (
80 <p className="rounded-lg bg-raised px-3 py-2 text-sm text-muted">
81 {after === undefined ? (
82 text
83 ) : (
84 <>
85 {before}
86 <Link to={`/${workspace}/-/integrations`} className="text-accent hover:underline">
87 Integrations
88 </Link>
89 {after}
90 </>
91 )}
92 </p>
93 );
94}
95
96/** Where the job ran: g1t's own runners, or a self-hosted one by name. */
97function RanOn({ job, workspace }: { job: Job; workspace: string }) {
98 const runnersPage = useLoaderData<typeof loader>().runnersPage;
99 if (job.selfHosted) {
100 const badge = "ml-auto inline-flex items-center gap-1.5 rounded-full border border-line px-2.5 py-0.5 text-xs text-muted";
101 const label = (
102 <>
103 <ServerCog size={13} />
104 {job.runner ? `Self-hosted: ${job.runner}` : "Self-hosted"}
105 </>
106 );
107 // A link to the runners for those who manage them, a label for everyone else.
108 return runnersPage ? (
109 <Link to={`/${workspace}/-/runners`} className={`${badge} hover:text-fg`} title="Self-hosted runner">
110 {label}
111 </Link>
112 ) : (
113 <span className={badge} title="Self-hosted runner">
114 {label}
115 </span>
116 );
117 }
118 if (!job.startedAt) return null;
119 return (
120 <span className="ml-auto inline-flex items-center gap-1.5 rounded-full border border-line px-2.5 py-0.5 text-xs text-muted">
121 <Cloud size={13} />
122 g1t
123 </span>
124 );
125}
126
127function JobView({ job, base }: { job: Job; base: string }) {
128 const live = job.status !== "completed";
129 const log = useJobLog(`${base}/actions/jobs/${job.id}/log`, live);
130 const failed = job.steps.find((s) => s.conclusion === "failure");
131 const running = job.steps.find((s) => s.status === "in_progress");
132 return (
133 <section className="min-w-0 space-y-4">
134 <div className="flex flex-wrap items-center gap-3">
135 <StatusIcon status={job.status} conclusion={job.conclusion} size={18} />
136 <h3 className="text-base font-semibold">{job.name}</h3>
137 <span className="text-sm text-muted">
138 {standingWord(job)}
139 {job.startedAt && ` · ${duration(job.startedAt, job.finishedAt)}`}
140 </span>
141 <RanOn job={job} workspace={base.split("/")[1]!} />
142 </div>
143 {job.reason && <Reason text={job.reason} workspace={base.split("/")[1]} />}
144 {job.annotations.length > 0 && (
145 <ul className="space-y-2 rounded-xl border border-line bg-surface p-4 text-sm">
146 {job.annotations.map((note, index) => (
147 <li key={index} className="flex gap-2">
148 {ANNOTATION_ICON[note.level]}
149 <span className="min-w-0">
150 {note.title && <span className="font-medium">{note.title}: </span>}
151 <span className="whitespace-pre-wrap">{note.message}</span>
152 {note.file && (
153 <span className="block font-mono text-xs text-faint">
154 {note.file}
155 {note.line != null && `:${note.line}`}
156 </span>
157 )}
158 </span>
159 </li>
160 ))}
161 </ul>
162 )}
163 <div className="overflow-hidden rounded-xl border border-line bg-surface">
164 <StepRow
165 step={{ number: 0, name: "Set up job", status: job.startedAt ? "completed" : "queued", conclusion: job.startedAt ? "success" : null, startedAt: job.startedAt, finishedAt: job.startedAt }}
166 text={log.get(0)}
167 defaultOpen={false}
168 />
169 {job.steps.map((step) => (
170 <StepRow
171 key={step.number}
172 step={step}
173 text={log.get(step.number)}
174 defaultOpen={step.number === (failed ?? running)?.number}
175 />
176 ))}
177 </div>
178 </section>
179 );
180}
181
182export default function ActionsRun({ loaderData, actionData, params }: Route.ComponentProps) {
183 const { detail, artifacts, member } = loaderData;
184 const { run, jobs, notes } = detail;
185 const base = `/${params.owner}/${params.repo}`;
186 const [search] = useSearchParams();
187 const busy = useNavigation().state === "submitting";
188 const live = run.status !== "completed";
189 useRefreshWhile(live, 2500);
190
191 // The job asked for, else one that failed, is running, or the first.
192 const selected =
193 jobs.find((job) => job.id === search.get("job")) ??
194 jobs.find((job) => job.conclusion === "failure" && job.steps.length > 0) ??
195 jobs.find((job) => job.status === "in_progress") ??
196 jobs[0];
197 const anyFailed = jobs.some((job) => job.conclusion === "failure" || job.conclusion === "cancelled");
198
199 return (
200 <div className="max-w-6xl space-y-6">
201 <header className="space-y-3">
202 <Link to={`${base}/actions?workflow=${run.workflowId}`} className="text-sm text-muted hover:text-fg">
203 {run.name}
204 </Link>
205 <div className="flex flex-wrap items-start justify-between gap-4">
206 <h2 className="flex min-w-0 items-center gap-2.5 text-xl font-semibold tracking-tight">
207 <StatusIcon status={run.status} conclusion={run.conclusion} size={20} />
208 <span className="min-w-0 truncate">{run.title || run.name}</span>
209 <span className="font-normal text-muted">#{run.number}</span>
210 </h2>
211 {member && !run.error && (
212 <Form method="post" className="flex gap-2">
213 {live ? (
214 <Button type="submit" name="intent" value="cancel" variant="quiet" disabled={busy}>
215 <Square size={13} />
216 Cancel run
217 </Button>
218 ) : (
219 <>
220 {anyFailed && (
221 <Button type="submit" name="intent" value="rerun-failed" variant="quiet" disabled={busy}>
222 <RotateCw size={13} />
223 Re-run failed jobs
224 </Button>
225 )}
226 <Button type="submit" name="intent" value="rerun" variant="quiet" disabled={busy}>
227 <RotateCw size={13} />
228 Re-run all jobs
229 </Button>
230 </>
231 )}
232 </Form>
233 )}
234 </div>
235 <p className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm text-muted">
236 <span>{standingWord(run)}</span>
237 <span className="inline-flex items-center gap-1 font-mono text-xs">
238 <GitBranch size={12} />
239 {shortRef(run.ref)}
240 </span>
241 <Link to={`${base}/commit/${run.sha}`} className="inline-flex items-center gap-1 font-mono text-xs hover:text-fg">
242 <GitCommitHorizontal size={12} />
243 {run.sha.slice(0, 7)}
244 </Link>
245 {run.pull != null && (
246 <Link to={`${base}/pull/${run.pull}`} className="hover:text-fg">
247 #{run.pull}
248 </Link>
249 )}
250 <span>
251 {run.event}
252 {run.actor && ` by ${run.actor}`} · <TimeAgo at={run.createdAt} />
253 </span>
254 {run.startedAt && <span className="font-mono text-xs">{duration(run.startedAt, run.finishedAt)}</span>}
255 {run.attempt > 1 && <span>Attempt {run.attempt}</span>}
256 </p>
257 </header>
258
259 <ErrorText>{actionData && "error" in actionData ? actionData.error : null}</ErrorText>
260 {run.error && (
261 <div className="rounded-xl border border-danger/30 bg-danger/5 p-4 text-sm">
262 <p className="font-medium text-danger">The workflow file could not be used</p>
263 <p className="mt-1 whitespace-pre-wrap text-fg/85">{run.error}</p>
264 </div>
265 )}
266 <Notes notes={notes} />
267 {artifacts.length > 0 && (
268 <section className="rounded-xl border border-line bg-surface p-4">
269 <h3 className="flex items-center gap-2 text-sm font-medium">
270 <Package size={14} className="text-muted" />
271 Artifacts
272 <span className="font-normal text-faint">· kept for 14 days</span>
273 </h3>
274 <ul className="mt-3 divide-y divide-line text-sm">
275 {artifacts.map((artifact) => (
276 <li key={artifact.name} className="flex items-center gap-3 py-2">
277 <span className="min-w-0 grow truncate font-mono text-[0.8125rem]">{artifact.name}</span>
278 <span className="shrink-0 text-xs text-faint">{Math.max(1, Math.round(artifact.size / 1024))} KB</span>
279 <a
280 href={`${base}/actions/runs/${run.id}/artifacts/${encodeURIComponent(artifact.name)}`}
281 className="inline-flex shrink-0 items-center gap-1 rounded-md px-2 py-1 text-xs text-muted ring-1 ring-line hover:text-fg"
282 >
283 <Download size={12} />
284 Download
285 </a>
286 </li>
287 ))}
288 </ul>
289 </section>
290 )}
291
292 {jobs.length > 0 && (
293 <div className="grid gap-6 lg:grid-cols-[15rem_1fr]">
294 <nav aria-label="Jobs" className="space-y-0.5 text-sm">
295 {jobs.map((job) => (
296 <Link
297 key={job.id}
298 to={`?job=${job.id}`}
299 preventScrollReset
300 className={`flex items-center gap-2 rounded-md px-2.5 py-1.5 ${
301 job.id === selected?.id ? "bg-raised text-fg" : "text-muted hover:bg-raised/60 hover:text-fg"
302 }`}
303 >
304 <StatusIcon status={job.status} conclusion={job.conclusion} size={14} />
305 <span className="min-w-0 truncate">{job.name}</span>
306 <span className="ml-auto shrink-0 font-mono text-xs text-faint">{duration(job.startedAt, job.finishedAt)}</span>
307 </Link>
308 ))}
309 </nav>
310 {selected && <JobView key={selected.id} job={selected} base={base} />}
311 </div>
312 )}
313 </div>
314 );
315}