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