309 lines12,501 bytesCodeBlame
1/**
2 * A repository's or a workspace's webhooks: the addresses events are sent
3 * to, adding one, and every delivery with what was sent and what came back.
4 */
5import { ChevronRight, Pause, Play, RotateCw, Send, Trash2, Webhook } from "lucide-react";
6import { useState } from "react";
7import { Form, Link, useNavigation } from "react-router";
8
9import { EVENT_TYPES, type Hook, type HookDelivery } from "@g1t/contracts";
10
11import type { WebhooksAction, WebhooksData } from "../lib/webhooks.server";
12import { Button, CopyLine, EmptyState, ErrorText, Field, Input, TimeAgo } from "./ui";
13import { CheckboxOption } from "./ui/checkbox";
14import { RadioGroup, RadioOption } from "./ui/radio-group";
15
16/** The events, in groups people recognise. */
17const GROUPS: { title: string; events: string[] }[] = [
18 { title: "Code", events: ["git.push", "repo.created", "repo.forked"] },
19 {
20 title: "Issues",
21 events: ["issue.opened", "issue.updated", "issue.assigned", "issue.closed", "issue.reopened", "comment.created"],
22 },
23 {
24 title: "Pull requests",
25 events: ["pull.opened", "pull.ready", "pull.updated", "pull.merge_requested", "pull.merged", "pull.closed"],
26 },
27 { title: "Checks, reviews and the queue", events: ["checks.completed", "workflow.completed", "review.completed", "queue.changed"] },
28 { title: "Agents", events: ["session.appended", "agent.asked"] },
29 { title: "Access", events: ["repo.collaborator_added", "repo.collaborator_removed", "repo.collaborator_role_changed"] },
30];
31
32function StatusDot({ status }: { status: string | null }) {
33 const color =
34 status === "delivered" ? "bg-accent" : status === "failed" ? "bg-danger" : status === "pending" ? "bg-warn" : "bg-faint";
35 return <span aria-hidden="true" className={`size-2 shrink-0 rounded-full ${color}`} />;
36}
37
38function describeEvents(events: string[]): string {
39 if (events.includes("*")) return "Every event";
40 return events.length === 1 ? events[0] : `${events.length} events`;
41}
42
43/** JSON, indented for reading, or the text as it is. */
44function pretty(text: string | null): string {
45 if (!text) return "";
46 try {
47 return JSON.stringify(JSON.parse(text), null, 2);
48 } catch {
49 return text;
50 }
51}
52
53function DeliveryRow({ delivery, manage }: { delivery: HookDelivery; manage: boolean }) {
54 const busy = useNavigation().state === "submitting";
55 return (
56 <details className="group border-t border-line first:border-t-0">
57 <summary className="flex cursor-pointer list-none items-center gap-3 px-4 py-2.5 text-sm hover:bg-raised/40">
58 <ChevronRight size={14} className="shrink-0 text-faint transition-transform group-open:rotate-90" />
59 <StatusDot status={delivery.status} />
60 <span className="font-mono text-[0.8125rem]">{delivery.event}</span>
61 <span className="min-w-0 truncate text-xs text-muted">
62 {delivery.responseStatus != null
63 ? `${delivery.responseStatus}`
64 : delivery.error
65 ? delivery.error
66 : "Not yet sent"}
67 {delivery.attempts > 1 && ` · ${delivery.attempts} attempts`}
68 {delivery.status === "pending" && delivery.nextAttemptAt && " · will try again"}
69 </span>
70 <span className="ml-auto shrink-0 font-mono text-xs text-faint">
71 {delivery.durationMs != null && `${delivery.durationMs}ms · `}
72 <TimeAgo at={delivery.createdAt} />
73 </span>
74 </summary>
75 <div className="grid gap-4 border-t border-line bg-bg/40 p-4 lg:grid-cols-2">
76 <div className="min-w-0">
77 <p className="mb-1.5 text-xs font-medium text-muted">Request</p>
78 <pre className="max-h-80 overflow-auto rounded-lg bg-surface p-3 font-mono text-xs ring-1 ring-line">
79 <code>{pretty(delivery.payload)}</code>
80 </pre>
81 </div>
82 <div className="min-w-0">
83 <p className="mb-1.5 text-xs font-medium text-muted">
84 Response{delivery.responseStatus != null && ` · ${delivery.responseStatus}`}
85 </p>
86 <pre className="max-h-80 overflow-auto rounded-lg bg-surface p-3 font-mono text-xs ring-1 ring-line">
87 <code>{delivery.error ?? (pretty(delivery.responseBody) || "No body.")}</code>
88 </pre>
89 {manage && (
90 <Form method="post" className="mt-3">
91 <input type="hidden" name="intent" value="redeliver" />
92 <input type="hidden" name="delivery" value={delivery.id} />
93 <Button type="submit" variant="quiet" disabled={busy}>
94 <RotateCw size={14} />
95 Redeliver
96 </Button>
97 </Form>
98 )}
99 </div>
100 </div>
101 </details>
102 );
103}
104
105function HookRow({ hook, open, deliveries, manage }: { hook: Hook; open: boolean; deliveries: HookDelivery[]; manage: boolean }) {
106 const busy = useNavigation().state === "submitting";
107 return (
108 <li className="border-t border-line first:border-t-0">
109 <div className="flex items-center gap-3 px-4 py-3">
110 <StatusDot status={hook.active ? hook.lastStatus : null} />
111 <div className="min-w-0 grow">
112 <p className="truncate font-mono text-[0.8125rem]">{hook.url}</p>
113 <p className="truncate text-xs text-muted">
114 {describeEvents(hook.events)}
115 {!hook.active && " · paused"}
116 {hook.lastDeliveredAt && (
117 <>
118 {" · last sent "}
119 <TimeAgo at={hook.lastDeliveredAt} />
120 </>
121 )}
122 {` · secret ${hook.secretHint}`}
123 </p>
124 </div>
125 <Link
126 to={open ? "?" : `?hook=${hook.id}`}
127 preventScrollReset
128 className="shrink-0 rounded-md px-2.5 py-1.5 text-xs text-muted transition-colors hover:bg-raised hover:text-fg"
129 >
130 {open ? "Hide deliveries" : "Deliveries"}
131 </Link>
132 {manage && (
133 <Form method="post" className="flex shrink-0 gap-1">
134 <input type="hidden" name="id" value={hook.id} />
135 <IconButton intent="ping" label="Send a ping" disabled={busy}>
136 <Send size={14} />
137 </IconButton>
138 <input type="hidden" name="active" value={hook.active ? "false" : "true"} />
139 <IconButton intent="toggle" label={hook.active ? "Pause" : "Resume"} disabled={busy}>
140 {hook.active ? <Pause size={14} /> : <Play size={14} />}
141 </IconButton>
142 <IconButton intent="delete" label="Delete" disabled={busy}>
143 <Trash2 size={14} />
144 </IconButton>
145 </Form>
146 )}
147 </div>
148 {open && (
149 <div className="mx-4 mb-4 overflow-hidden rounded-lg border border-line">
150 {deliveries.length === 0 ? (
151 <p className="px-4 py-3 text-sm text-muted">Nothing sent yet.</p>
152 ) : (
153 deliveries.map((delivery) => <DeliveryRow key={delivery.id} delivery={delivery} manage={manage} />)
154 )}
155 </div>
156 )}
157 </li>
158 );
159}
160
161function IconButton({ intent, label, disabled, children }: { intent: string; label: string; disabled: boolean; children: React.ReactNode }) {
162 return (
163 <button
164 type="submit"
165 name="intent"
166 value={intent}
167 title={label}
168 aria-label={label}
169 disabled={disabled}
170 className="rounded-md p-2 text-muted transition-colors hover:bg-raised hover:text-fg disabled:opacity-50"
171 >
172 {children}
173 </button>
174 );
175}
176
177function AddWebhook() {
178 const busy = useNavigation().state === "submitting";
179 const [which, setWhich] = useState<"all" | "some">("all");
180 return (
181 <Form method="post" className="space-y-4 rounded-xl border border-line bg-surface p-5">
182 <input type="hidden" name="intent" value="create" />
183 <p className="font-medium">Add a webhook</p>
184 <Field label="Payload URL" hint="An HTTPS address on the public internet. g1t sends it a ping as soon as you add it.">
185 <Input name="url" type="url" required placeholder="https://example.com/g1t/events" />
186 </Field>
187 <fieldset>
188 <legend className="mb-1.5 text-sm font-medium text-muted">Which events</legend>
189 <RadioGroup
190 name="which"
191 value={which}
192 onValueChange={(value) => setWhich(value as typeof which)}
193 aria-label="Which events"
194 className="flex flex-wrap gap-x-6 gap-y-2"
195 >
196 <RadioOption value="all" label="Everything, including events added later" />
197 <RadioOption value="some" label="Let me choose" />
198 </RadioGroup>
199 {which === "some" && (
200 <div className="mt-3 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
201 {GROUPS.map((group) => (
202 <div key={group.title}>
203 <p className="mb-1.5 text-xs font-medium text-faint">{group.title}</p>
204 <div className="space-y-1">
205 {group.events
206 .filter((event) => (EVENT_TYPES as readonly string[]).includes(event))
207 .map((event) => (
208 <CheckboxOption
209 key={event}
210 name="event"
211 value={event}
212 label={event}
213 className="items-center"
214 labelClassName="font-mono text-[0.8125rem]"
215 />
216 ))}
217 </div>
218 </div>
219 ))}
220 </div>
221 )}
222 </fieldset>
223 <Field label="Secret" hint="Optional. Deliveries are signed with it. Leave it empty and g1t makes one, shown once.">
224 <Input name="secret" type="password" autoComplete="off" />
225 </Field>
226 <Button type="submit" disabled={busy}>
227 {busy ? "Adding…" : "Add webhook"}
228 </Button>
229 </Form>
230 );
231}
232
233export function WebhooksPanel({
234 data,
235 action,
236 manage,
237 scope,
238}: {
239 data: WebhooksData;
240 action: WebhooksAction | undefined;
241 manage: boolean;
242 /** Says whose events these are. */
243 scope: string;
244}) {
245 const created = action?.created;
246 return (
247 <div className="max-w-4xl space-y-6">
248 {created && (
249 <div className="space-y-3 rounded-xl border border-accent-dim/60 bg-accent/5 p-5 text-sm">
250 <p className="font-medium">Added. g1t sent it a ping.</p>
251 {created.secret ? (
252 <>
253 <p className="text-muted">
254 Every delivery is signed with this secret in <code>X-G1t-Signature-256</code>. It is shown this once.
255 </p>
256 <CopyLine text={created.secret} />
257 </>
258 ) : (
259 <p className="text-muted">Deliveries are signed with the secret you gave.</p>
260 )}
261 </div>
262 )}
263 {action?.sent && (
264 <p className="text-sm text-muted">
265 Sent {action.sent.event}:{" "}
266 {action.sent.status === "delivered" ? (
267 <span className="text-accent">delivered, {action.sent.responseStatus}</span>
268 ) : (
269 <span className="text-danger">{action.sent.error ?? `answered ${action.sent.responseStatus}`}</span>
270 )}
271 .
272 </p>
273 )}
274 <ErrorText>{action?.error}</ErrorText>
275
276 {data.hooks.length === 0 ? (
277 <EmptyState title="No webhooks yet">
278 <span className="inline-flex items-center gap-1.5">
279 <Webhook size={14} />
280 Add one and {scope} sends its events to your address as they happen, signed, and retried until it answers.
281 </span>
282 </EmptyState>
283 ) : (
284 <ul className="overflow-hidden rounded-xl border border-line bg-surface">
285 {data.hooks.map((hook) => (
286 <HookRow
287 key={hook.id}
288 hook={hook}
289 open={data.open === hook.id}
290 deliveries={data.open === hook.id ? data.deliveries : []}
291 manage={manage}
292 />
293 ))}
294 </ul>
295 )}
296
297 {manage && <AddWebhook />}
298 <p className="text-xs text-faint">
299 Each delivery is an HTTPS POST of JSON with <code>X-G1t-Event</code>, <code>X-G1t-Delivery</code> and{" "}
300 <code>X-G1t-Signature-256</code>. One that is not answered with a 2xx is tried again after 1 minute, 5 minutes,
301 30 minutes, 2 hours and 5 hours.{" "}
302 <a href="https://docs.g1t.sh/guides/webhooks/" className="text-muted underline underline-offset-4">
303 How to check the signature
304 </a>
305 .
306 </p>
307 </div>
308 );
309}