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