g1t/apps/web/app/components/webhooks.tsx

309 lines12,516 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 } 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 { 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 return (
55 <details className="group border-t border-line first:border-t-0">
56 <summary className="flex cursor-pointer list-none items-center gap-3 px-4 py-2.5 text-sm hover:bg-raised/40">
57 <ChevronRight size={14} className="shrink-0 text-faint transition-transform group-open:rotate-90" />
58 <StatusDot status={delivery.status} />
59 <span className="font-mono text-[0.8125rem]">{delivery.event}</span>
60 <span className="min-w-0 truncate text-xs text-muted">
61 {delivery.responseStatus != null
62 ? `${delivery.responseStatus}`
63 : delivery.error
64 ? delivery.error
65 : "Not yet sent"}
66 {delivery.attempts > 1 && ` · ${delivery.attempts} attempts`}
67 {delivery.status === "pending" && delivery.nextAttemptAt && " · will try again"}
68 </span>
69 <span className="ml-auto shrink-0 font-mono text-xs text-faint">
70 {delivery.durationMs != null && `${delivery.durationMs}ms · `}
71 <TimeAgo at={delivery.createdAt} />
72 </span>
73 </summary>
74 <div className="grid gap-4 border-t border-line bg-bg/40 p-4 lg:grid-cols-2">
75 <div className="min-w-0">
76 <p className="mb-1.5 text-xs font-medium text-muted">Request</p>
77 <pre className="max-h-80 overflow-auto rounded-lg bg-surface p-3 font-mono text-xs ring-1 ring-line">
78 <code>{pretty(delivery.payload)}</code>
79 </pre>
80 </div>
81 <div className="min-w-0">
82 <p className="mb-1.5 text-xs font-medium text-muted">
83 Response{delivery.responseStatus != null && ` · ${delivery.responseStatus}`}
84 </p>
85 <pre className="max-h-80 overflow-auto rounded-lg bg-surface p-3 font-mono text-xs ring-1 ring-line">
86 <code>{delivery.error ?? (pretty(delivery.responseBody) || "No body.")}</code>
87 </pre>
88 {manage && (
89 <Form method="post" className="mt-3">
90 <input type="hidden" name="intent" value="redeliver" />
91 <input type="hidden" name="delivery" value={delivery.id} />
92 <SubmitButton
93 variant="quiet"
94 match={{ intent: "redeliver", delivery: delivery.id }}
95 pending="Redelivering…"
96 >
97 <RotateCw size={14} />
98 Redeliver
99 </SubmitButton>
100 </Form>
101 )}
102 </div>
103 </div>
104 </details>
105 );
106}
107
108function HookRow({ hook, open, deliveries, manage }: { hook: Hook; open: boolean; deliveries: HookDelivery[]; manage: boolean }) {
109 return (
110 <li className="border-t border-line first:border-t-0">
111 <div className="flex items-center gap-3 px-4 py-3">
112 <StatusDot status={hook.active ? hook.lastStatus : null} />
113 <div className="min-w-0 grow">
114 <p className="truncate font-mono text-[0.8125rem]">{hook.url}</p>
115 <p className="truncate text-xs text-muted">
116 {describeEvents(hook.events)}
117 {!hook.active && " · paused"}
118 {hook.lastDeliveredAt && (
119 <>
120 {" · last sent "}
121 <TimeAgo at={hook.lastDeliveredAt} />
122 </>
123 )}
124 {` · secret ${hook.secretHint}`}
125 </p>
126 </div>
127 <Link
128 to={open ? "?" : `?hook=${hook.id}`}
129 preventScrollReset
130 className="shrink-0 rounded-md px-2.5 py-1.5 text-xs text-muted transition-colors hover:bg-raised hover:text-fg"
131 >
132 {open ? "Hide deliveries" : "Deliveries"}
133 </Link>
134 {manage && (
135 <Form method="post" className="flex shrink-0 gap-1">
136 <input type="hidden" name="id" value={hook.id} />
137 <IconButton intent="ping" id={hook.id} label="Send a ping">
138 <Send size={14} />
139 </IconButton>
140 <input type="hidden" name="active" value={hook.active ? "false" : "true"} />
141 <IconButton intent="toggle" id={hook.id} label={hook.active ? "Pause" : "Resume"}>
142 {hook.active ? <Pause size={14} /> : <Play size={14} />}
143 </IconButton>
144 <IconButton intent="delete" id={hook.id} label="Delete">
145 <Trash2 size={14} />
146 </IconButton>
147 </Form>
148 )}
149 </div>
150 {open && (
151 <div className="mx-4 mb-4 overflow-hidden rounded-lg border border-line">
152 {deliveries.length === 0 ? (
153 <p className="px-4 py-3 text-sm text-muted">Nothing sent yet.</p>
154 ) : (
155 deliveries.map((delivery) => <DeliveryRow key={delivery.id} delivery={delivery} manage={manage} />)
156 )}
157 </div>
158 )}
159 </li>
160 );
161}
162
163/** One webhook's action, as an icon: a spinner in its place while that action goes. */
164function IconButton({ intent, id, label, children }: { intent: string; id: string; label: string; children: React.ReactNode }) {
165 return (
166 <SubmitButton
167 icon
168 name="intent"
169 value={intent}
170 match={{ id }}
171 title={label}
172 aria-label={label}
173 className="rounded-md p-2 text-muted transition-colors hover:bg-raised hover:text-fg disabled:opacity-50"
174 >
175 {children}
176 </SubmitButton>
177 );
178}
179
180function AddWebhook() {
181 const [which, setWhich] = useState<"all" | "some">("all");
182 return (
183 <Form method="post" className="space-y-4 rounded-xl border border-line bg-surface p-5">
184 <input type="hidden" name="intent" value="create" />
185 <p className="font-medium">Add a webhook</p>
186 <Field label="Payload URL" hint="An HTTPS address on the public internet. g1t sends it a ping as soon as you add it.">
187 <Input name="url" type="url" required placeholder="https://example.com/g1t/events" />
188 </Field>
189 <fieldset>
190 <legend className="mb-1.5 text-sm font-medium text-muted">Which events</legend>
191 <RadioGroup
192 name="which"
193 value={which}
194 onValueChange={(value) => setWhich(value as typeof which)}
195 aria-label="Which events"
196 className="flex flex-wrap gap-x-6 gap-y-2"
197 >
198 <RadioOption value="all" label="Everything, including events added later" />
199 <RadioOption value="some" label="Let me choose" />
200 </RadioGroup>
201 {which === "some" && (
202 <div className="mt-3 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
203 {GROUPS.map((group) => (
204 <div key={group.title}>
205 <p className="mb-1.5 text-xs font-medium text-faint">{group.title}</p>
206 <div className="space-y-1">
207 {group.events
208 .filter((event) => (EVENT_TYPES as readonly string[]).includes(event))
209 .map((event) => (
210 <CheckboxOption
211 key={event}
212 name="event"
213 value={event}
214 label={event}
215 className="items-center"
216 labelClassName="font-mono text-[0.8125rem]"
217 />
218 ))}
219 </div>
220 </div>
221 ))}
222 </div>
223 )}
224 </fieldset>
225 <Field label="Secret" hint="Optional. Deliveries are signed with it. Leave it empty and g1t makes one, shown once.">
226 <Input name="secret" type="password" autoComplete="off" />
227 </Field>
228 <SubmitButton match={{ intent: "create" }} pending="Adding…">
229 Add webhook
230 </SubmitButton>
231 </Form>
232 );
233}
234
235export function WebhooksPanel({
236 data,
237 action,
238 manage,
239 scope,
240}: {
241 data: WebhooksData;
242 action: WebhooksAction | undefined;
243 manage: boolean;
244 /** Says whose events these are. */
245 scope: string;
246}) {
247 const created = action?.created;
248 return (
249 <div className="max-w-4xl space-y-6">
250 {created && (
251 <div className="space-y-3 rounded-xl border border-accent-dim/60 bg-accent/5 p-5 text-sm">
252 <p className="font-medium">Added. g1t sent it a ping.</p>
253 {created.secret ? (
254 <>
255 <p className="text-muted">
256 Every delivery is signed with this secret in <code>X-G1t-Signature-256</code>. It is shown this once.
257 </p>
258 <CopyLine text={created.secret} />
259 </>
260 ) : (
261 <p className="text-muted">Deliveries are signed with the secret you gave.</p>
262 )}
263 </div>
264 )}
265 {action?.sent && (
266 <p className="text-sm text-muted">
267 Sent {action.sent.event}:{" "}
268 {action.sent.status === "delivered" ? (
269 <span className="text-accent">delivered, {action.sent.responseStatus}</span>
270 ) : (
271 <span className="text-danger">{action.sent.error ?? `answered ${action.sent.responseStatus}`}</span>
272 )}
273 .
274 </p>
275 )}
276 <ErrorText>{action?.error}</ErrorText>
277
278 {data.hooks.length === 0 ? (
279 <EmptyState title="No webhooks yet">
280 Add one and {scope} sends its events to your address as they happen, signed, and retried until it answers.
281 </EmptyState>
282 ) : (
283 <ul className="overflow-hidden rounded-xl border border-line bg-surface">
284 {data.hooks.map((hook) => (
285 <HookRow
286 key={hook.id}
287 hook={hook}
288 open={data.open === hook.id}
289 deliveries={data.open === hook.id ? data.deliveries : []}
290 manage={manage}
291 />
292 ))}
293 </ul>
294 )}
295
296 {/* Keyed to the webhook just added, so the form starts empty for the next. */}
297 {manage && <AddWebhook key={created?.hook.id ?? "new"} />}
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}