flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

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

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