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

388 lines16,723 bytesCodeBlame
1import { AlertTriangle, FileCode2, GitBranch, Play, PlayCircle } from "lucide-react";
2import { useEffect, useRef, useState } from "react";
3import { Form, Link, useSearchParams } from "react-router";
4
5import type { DispatchInput, Workflow, WorkflowRun } from "@g1t/contracts";
6
7import type { Route } from "./+types/actions";
8import { page } from "../../lib/meta";
9import { Notes, StatusIcon, duration, shortRef } from "../../components/actions";
10import { AddCiPrompt } from "../../components/add-ci";
11import { Button, ComputeNote, EmptyState, ErrorText, SubmitButton, TimeAgo, usePending } from "../../components/ui";
12import { CheckboxOption } from "../../components/ui/checkbox";
13import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../components/ui/select";
14import { computeNoteFor } from "../../lib/compute.server";
15import { actions } from "../../lib/services.server";
16import { assertSameOrigin, getViewer, requireUser, unwrap } from "../../lib/session.server";
17import { accessFor, refusal, repoFor } from "../../lib/access.server";
18import { useRefreshWhile } from "../../lib/refresh";
19
20export function meta({ params, ...args }: Route.MetaArgs) {
21 return page(args, { title: `Workflows · ${params.owner}/${params.repo} · g1t` });
22}
23
24export async function loader({ params, context, request }: Route.LoaderArgs) {
25 const viewer = getViewer(context);
26 const repo = { namespace: params.owner, name: params.repo };
27 const selected = new URL(request.url).searchParams.get("workflow") ?? undefined;
28 const found = await repoFor(context, params);
29 const can = found.ok ? accessFor(viewer, found.value).can : null;
30 // Starting runs needs Write; turning a workflow on or off, Maintain.
31 const member = can?.run ?? false;
32 // Who may open the pull request that adds a starter workflow.
33 const canPush = can?.push ?? false;
34 const [workflows, runs, computeNote] = await Promise.all([
35 actions.workflows(repo, viewer),
36 actions.runs(repo, viewer, { workflow: selected, limit: 50 }),
37 // Jobs run on g1t's machines as the workspace's plan allows, or from
38 // the open-source pool on a public repository; members are told
39 // before a run is refused for it.
40 member && found.ok
41 ? computeNoteFor(params.owner, "workflow", !found.value.isPrivate).catch(() => null)
42 : Promise.resolve(null),
43 ]);
44 return {
45 workflows: unwrap(workflows),
46 runs: runs.ok ? runs.value : [],
47 member,
48 canPush,
49 manage: can?.manage_settings ?? false,
50 computeNote,
51 selected: selected ?? null,
52 };
53}
54
55export async function action({ request, params, context }: Route.ActionArgs) {
56 assertSameOrigin(request);
57 const user = requireUser(context, request);
58 const repo = { namespace: params.owner, name: params.repo };
59 const form = await request.formData();
60 const workflow = String(form.get("workflow") ?? "");
61 const refused = await refusal(context, params, form.get("intent") === "toggle" ? "manage_settings" : "run");
62 if (refused) return { error: refused };
63 if (form.get("intent") === "toggle") {
64 const changed = await actions.setWorkflowEnabled(user, repo, workflow, form.get("enabled") === "true");
65 return changed.ok ? {} : { error: changed.error.message };
66 }
67 const inputs: Record<string, unknown> = {};
68 for (const [key, value] of form.entries()) {
69 if (key.startsWith("input.")) inputs[key.slice(6)] = value === "on" ? true : value;
70 }
71 // An unticked checkbox sends nothing: it is false.
72 for (const key of String(form.get("booleans") ?? "").split(",").filter(Boolean)) {
73 if (!(key in inputs)) inputs[key] = false;
74 }
75 const ref = String(form.get("ref") ?? "").trim() || undefined;
76 const started = await actions.dispatch(user, repo, workflow, ref, inputs);
77 return started.ok ? { started: started.value } : { error: started.error.message };
78}
79
80/** Re-reads the page every few seconds while something is still running. */
81function useLiveWhile(running: boolean) {
82 useRefreshWhile(running, 3000);
83}
84
85const EVENT_WORDS: Record<string, string> = {
86 push: "push",
87 pull_request: "pull request",
88 pull_request_target: "pull request (target)",
89 pull_request_review: "review",
90 issues: "issue",
91 issue_comment: "comment",
92 schedule: "schedule",
93 workflow_dispatch: "manual",
94};
95
96function RunRow({ run, base, showWorkflow }: { run: WorkflowRun; base: string; showWorkflow: boolean }) {
97 return (
98 <li className="border-t border-line first:border-t-0">
99 <Link to={`${base}/actions/runs/${run.id}`} className="flex items-start gap-3 px-4 py-3 transition-colors hover:bg-raised/40">
100 <span className="mt-0.5">
101 <StatusIcon status={run.status} conclusion={run.conclusion} />
102 </span>
103 <span className="min-w-0 grow">
104 <span className="block truncate text-sm font-medium">{run.title || run.name}</span>
105 <span className="mt-0.5 block truncate text-xs text-muted">
106 {showWorkflow && <span className="text-fg/80">{run.name}</span>}
107 {showWorkflow && " · "}#{run.number}
108 {run.attempt > 1 && ` (attempt ${run.attempt})`}
109 {" · "}
110 {EVENT_WORDS[run.event] ?? run.event}
111 {run.actor && ` by ${run.actor}`}
112 </span>
113 </span>
114 <span className="hidden shrink-0 items-center gap-1 rounded-md bg-raised px-1.5 py-0.5 font-mono text-xs text-muted sm:inline-flex">
115 <GitBranch size={11} />
116 {shortRef(run.ref)}
117 </span>
118 <span className="w-28 shrink-0 text-right text-xs text-faint">
119 <TimeAgo at={run.createdAt} />
120 {run.startedAt && <span className="block font-mono">{duration(run.startedAt, run.finishedAt)}</span>}
121 </span>
122 </Link>
123 </li>
124 );
125}
126
127function InputField({ name, spec }: { name: string; spec: DispatchInput }) {
128 const label = (
129 <span className="mb-1 block text-xs font-medium text-muted">
130 {spec.description || name}
131 {spec.required && <span className="text-danger"> *</span>}
132 </span>
133 );
134 const control = "w-full rounded-md border border-line bg-bg px-2.5 py-1.5 text-sm outline-none focus:border-accent-dim";
135 if (spec.type === "boolean") {
136 return (
137 <CheckboxOption
138 name={`input.${name}`}
139 defaultChecked={spec.default === true || spec.default === "true"}
140 label={spec.description || name}
141 />
142 );
143 }
144 if (spec.type === "choice" && spec.options) {
145 return (
146 <div>
147 {label}
148 <Select name={`input.${name}`} defaultValue={String(spec.default ?? spec.options[0] ?? "") || undefined}>
149 <SelectTrigger size="sm" aria-label={spec.description || name}>
150 <SelectValue placeholder="Choose" />
151 </SelectTrigger>
152 <SelectContent>
153 {/* A Radix item cannot have the value "". */}
154 {spec.options.filter((option) => option !== "").map((option) => (
155 <SelectItem key={option} value={option}>
156 {option}
157 </SelectItem>
158 ))}
159 </SelectContent>
160 </Select>
161 </div>
162 );
163 }
164 return (
165 <label className="block">
166 {label}
167 <input
168 name={`input.${name}`}
169 required={spec.required}
170 defaultValue={spec.default == null ? "" : String(spec.default)}
171 type={spec.type === "number" ? "number" : "text"}
172 className={control}
173 autoComplete="off"
174 />
175 </label>
176 );
177}
178
179function RunWorkflow({ workflow }: { workflow: Workflow }) {
180 const [open, setOpen] = useState(false);
181 // Open, saying it is starting, until the run shows below or the error does.
182 const running = usePending({ intent: "dispatch", workflow: workflow.id });
183 const was = useRef(false);
184 useEffect(() => {
185 if (was.current && !running) setOpen(false);
186 was.current = running;
187 }, [running]);
188 const inputs = Object.entries(workflow.dispatch ?? {});
189 const booleans = inputs.filter(([, spec]) => spec.type === "boolean").map(([name]) => name);
190 return (
191 <div className="relative">
192 <Button type="button" variant="quiet" onClick={() => setOpen((v) => !v)}>
193 <Play size={14} />
194 Run workflow
195 </Button>
196 {open && (
197 <Form
198 method="post"
199 className="absolute right-0 z-20 mt-2 w-80 space-y-3 rounded-xl border border-line bg-surface p-4 shadow-xl"
200 >
201 <input type="hidden" name="intent" value="dispatch" />
202 <input type="hidden" name="workflow" value={workflow.id} />
203 <input type="hidden" name="booleans" value={booleans.join(",")} />
204 <label className="block">
205 <span className="mb-1 block text-xs font-medium text-muted">Branch or tag</span>
206 <input
207 name="ref"
208 placeholder="The default branch"
209 className="w-full rounded-md border border-line bg-bg px-2.5 py-1.5 font-mono text-sm outline-none focus:border-accent-dim"
210 autoComplete="off"
211 />
212 </label>
213 {inputs.map(([name, spec]) => (
214 <InputField key={name} name={name} spec={spec} />
215 ))}
216 <SubmitButton match={{ intent: "dispatch", workflow: workflow.id }} pending="Starting…">
217 <PlayCircle size={14} />
218 Run
219 </SubmitButton>
220 </Form>
221 )}
222 </div>
223 );
224}
225
226function WorkflowHeader({ workflow, base, member, manage }: { workflow: Workflow; base: string; member: boolean; manage: boolean }) {
227 return (
228 <div className="space-y-4">
229 <div className="flex flex-wrap items-start justify-between gap-3">
230 <div className="min-w-0">
231 <h3 className="text-lg font-semibold tracking-tight">{workflow.name}</h3>
232 <Link to={`${base}/blob/HEAD/${workflow.path}`} className="inline-flex items-center gap-1 font-mono text-xs text-faint hover:text-fg">
233 <FileCode2 size={12} />
234 {workflow.path}
235 </Link>
236 {workflow.events.length > 0 && (
237 <p className="mt-1.5 text-xs text-muted">On {workflow.events.map((e) => EVENT_WORDS[e] ?? e).join(", ")}</p>
238 )}
239 </div>
240 {member && !workflow.error && (
241 <div className="flex items-center gap-2">
242 {workflow.dispatch && workflow.state === "active" && <RunWorkflow workflow={workflow} />}
243 {manage && <Form method="post">
244 <input type="hidden" name="intent" value="toggle" />
245 <input type="hidden" name="workflow" value={workflow.id} />
246 <input type="hidden" name="enabled" value={workflow.state === "active" ? "false" : "true"} />
247 <SubmitButton
248 variant="quiet"
249 match={{ intent: "toggle", workflow: workflow.id }}
250 pending={workflow.state === "active" ? "Turning off…" : "Turning on…"}
251 >
252 {workflow.state === "active" ? "Turn off" : "Turn on"}
253 </SubmitButton>
254 </Form>}
255 </div>
256 )}
257 </div>
258 {workflow.error && <p className="rounded-lg bg-danger/10 px-3 py-2 text-sm text-danger">{workflow.error}</p>}
259 {workflow.state === "disabled" && (
260 <p className="rounded-lg bg-raised px-3 py-2 text-sm text-muted">Turned off: nothing starts it until someone with the Maintain role turns it on.</p>
261 )}
262 <Notes notes={workflow.notes} />
263 </div>
264 );
265}
266
267const EXAMPLE = `name: CI
268on:
269 push:
270 branches: [main]
271 pull_request:
272jobs:
273 test:
274 runs-on: ubuntu-latest
275 steps:
276 - uses: actions/checkout@v7
277 - uses: actions/setup-node@v7
278 with:
279 node-version: 24
280 - run: npm ci
281 - run: npm test`;
282
283export default function Actions({ loaderData, actionData, params }: Route.ComponentProps) {
284 const { workflows, runs, member, canPush, manage, computeNote, selected } = loaderData;
285 const [search] = useSearchParams();
286 const base = `/${params.owner}/${params.repo}`;
287 const workflow = workflows.find((w) => w.id === selected || w.path.endsWith(`/${selected}`)) ?? null;
288 useLiveWhile(runs.some((run) => run.status !== "completed"));
289 const started = actionData && "started" in actionData ? actionData.started : null;
290 return (
291 <div className="max-w-6xl">
292 <header className="mb-6 flex flex-wrap items-start justify-between gap-4">
293 <div>
294 <h2 className="flex items-center gap-2 text-xl font-semibold tracking-tight">
295 <PlayCircle size={18} className="text-accent" />
296 Workflows
297 </h2>
298 <p className="mt-1 max-w-2xl text-sm text-muted">
299 Workflows in <code className="text-fg">.g1t/workflows</code>, written as GitHub Actions and run as GitHub runs
300 them. A run on a pull request counts as its checks.
301 </p>
302 </div>
303 <a href="https://docs.g1t.sh/guides/actions/" className="text-sm text-muted underline underline-offset-4 hover:text-fg">
304 How workflows run on g1t
305 </a>
306 </header>
307
308 {member && computeNote && (
309 <div className="mb-6 flex flex-wrap items-center gap-2 rounded-xl bg-surface px-4 py-3 text-sm ring-1 ring-line">
310 <AlertTriangle size={15} className="shrink-0 text-warn" />
311 <ComputeNote note={computeNote} />
312 </div>
313 )}
314
315 {workflows.length === 0 ? (
316 <div className="grid gap-6 lg:grid-cols-2">
317 <div className="lg:col-span-2">
318 <AddCiPrompt owner={params.owner} repo={params.repo} canAdd={canPush} />
319 </div>
320 <EmptyState title="No workflows yet">
321 Coming from GitHub? Rename <code>.github</code> to <code>.g1t</code> and push: your workflows run here as they
322 are. g1t never reads <code>.github</code>.
323 </EmptyState>
324 <div>
325 <p className="font-mono text-xs text-faint">.g1t/workflows/ci.yml</p>
326 <pre className="mt-1.5 rounded-lg bg-surface p-3 font-mono text-xs leading-relaxed whitespace-pre-wrap ring-1 ring-line">
327 <code>{EXAMPLE}</code>
328 </pre>
329 </div>
330 </div>
331 ) : (
332 <div className="grid gap-8 lg:grid-cols-[14rem_1fr]">
333 <nav aria-label="Workflows" className="space-y-0.5 text-sm">
334 <Link
335 to="?"
336 className={`block rounded-md px-2.5 py-1.5 ${!selected ? "bg-raised text-fg" : "text-muted hover:bg-raised/60 hover:text-fg"}`}
337 >
338 All workflows
339 </Link>
340 {workflows.map((w) => (
341 <Link
342 key={w.id}
343 to={`?workflow=${w.id}`}
344 className={`flex items-center gap-2 rounded-md px-2.5 py-1.5 ${
345 w.id === workflow?.id ? "bg-raised text-fg" : "text-muted hover:bg-raised/60 hover:text-fg"
346 }`}
347 >
348 <span className="min-w-0 truncate">
349 {w.name}
350 {/* Two workflows of one name are told apart by their files. */}
351 {workflows.some((other) => other.id !== w.id && other.name === w.name) && (
352 <span className="block truncate font-mono text-[0.6875rem] text-faint">{w.path}</span>
353 )}
354 </span>
355 {w.error && <AlertTriangle size={12} className="shrink-0 text-danger" aria-label="Its file has a problem" />}
356 {w.state === "disabled" && <span className="ml-auto shrink-0 text-xs text-faint">off</span>}
357 </Link>
358 ))}
359 </nav>
360 <div className="min-w-0 space-y-6">
361 {workflow && <WorkflowHeader workflow={workflow} base={base} member={member} manage={manage} />}
362 {started && (
363 <p className="text-sm text-muted">
364 Started{" "}
365 <Link to={`${base}/actions/runs/${started.id}`} className="text-fg underline underline-offset-4">
366 run #{started.number}
367 </Link>
368 .
369 </p>
370 )}
371 <ErrorText>{actionData && "error" in actionData ? actionData.error : null}</ErrorText>
372 {runs.length === 0 ? (
373 <EmptyState title="No runs yet">
374 {workflow?.dispatch ? "Run it by hand, or wait for what starts it." : "Runs appear here when something starts one."}
375 </EmptyState>
376 ) : (
377 <ul className="overflow-hidden rounded-xl border border-line bg-surface">
378 {runs.map((run) => (
379 <RunRow key={run.id} run={run} base={base} showWorkflow={!search.get("workflow")} />
380 ))}
381 </ul>
382 )}
383 </div>
384 </div>
385 )}
386 </div>
387 );
388}