@devries-cameron20 / t3code-1 / commits / 0c85b0d997
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat(scheduled-tasks): event filters for webhook deliveries (#22194)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 20, 2026 at 13:29 UTC 0c85b0d9977fe9376bf9a4b063a4dd8ab8c97ae6
18 files changed +1111 -47
apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
+96
@@ -13,6 +13,7 @@ import type {
13 } from "@t3tools/contracts";
14 import {
15 MAX_WEBHOOK_DELIVERY_AGE_MINUTES,
16 + MAX_WEBHOOK_FILTERS,
17 resolveEnvironmentMachineKind,
18 } from "@t3tools/contracts";
19 import type { MenuAction } from "@react-native-menu/menu";
@@ -24,7 +25,12 @@ import {
25 } from "@t3tools/client-runtime/state/runtime";
26 import {
27 DEFAULT_WEBHOOK_PROMPT,
28 + emptyWebhookFilterDraft,
29 parseMaxDeliveryAge,
30 + parseWebhookFilterDrafts,
31 + removeWebhookFilterDraft,
32 + WEBHOOK_FILTER_OPS,
33 + type WebhookFilterDraft,
34 } from "@t3tools/client-runtime/scheduled-task-webhook";
35 import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
36 import { useFocusEffect, useNavigation, usePreventRemove } from "@react-navigation/native";
@@ -222,6 +228,84 @@ function SelectRow(props: {
228 );
229 }
230
231 +function WebhookFilterRows(props: {
232 + readonly filters: ReadonlyArray<WebhookFilterDraft>;
233 + readonly disabled: boolean;
234 + readonly onChange: (filters: ReadonlyArray<WebhookFilterDraft>) => void;
235 +}) {
236 + const update = (index: number, patch: Partial<WebhookFilterDraft>) =>
237 + props.onChange(
238 + props.filters.map((filter, at) => (at === index ? { ...filter, ...patch } : filter)),
239 + );
240 + return (
241 + <>
242 + {props.filters.map((filter, index) => (
243 + <View key={filter.id}>
244 + <View className="flex-row items-center gap-3 border-t border-border-subtle px-4 pt-3">
245 + <Text className="min-w-0 flex-1 text-sm text-foreground-muted">Filter {index + 1}</Text>
246 + <Pressable
247 + accessibilityRole="button"
248 + accessibilityLabel={`Remove filter ${index + 1}`}
249 + disabled={props.disabled}
250 + hitSlop={8}
251 + onPress={() => props.onChange(removeWebhookFilterDraft(props.filters, filter.id))}
252 + className="active:opacity-70"
253 + >
254 + <SymbolView name="trash" size={16} tintColorClassName="accent-danger-foreground" />
255 + </Pressable>
256 + </View>
257 + <FormField
258 + label="Path"
259 + value={filter.path}
260 + placeholder="body.action"
261 + disabled={props.disabled}
262 + onChange={(path) => update(index, { path })}
263 + />
264 + <SelectRow
265 + label="Test"
266 + value={WEBHOOK_FILTER_OPS.find((option) => option.op === filter.op)?.label ?? ""}
267 + actions={WEBHOOK_FILTER_OPS.map((option) => ({
268 + id: option.op,
269 + title: option.label,
270 + state: option.op === filter.op ? ("on" as const) : undefined,
271 + }))}
272 + onSelect={(id) => {
273 + const known = WEBHOOK_FILTER_OPS.find((option) => option.op === id);
274 + if (known) update(index, { op: known.op });
275 + }}
276 + />
277 + {filter.op === "exists" ? null : (
278 + <FormField
279 + label={filter.op === "in" ? "Values, comma-separated" : "Value"}
280 + value={filter.value}
281 + placeholder={filter.op === "in" ? "opened, reopened" : "opened"}
282 + disabled={props.disabled}
283 + onChange={(value) => update(index, { value })}
284 + />
285 + )}
286 + </View>
287 + ))}
288 + {props.filters.length < MAX_WEBHOOK_FILTERS ? (
289 + <Pressable
290 + accessibilityRole="button"
291 + disabled={props.disabled}
292 + onPress={() => props.onChange([...props.filters, emptyWebhookFilterDraft()])}
293 + className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70"
294 + >
295 + <Text className="min-w-0 flex-1 text-lg text-foreground">Add filter</Text>
296 + <SymbolView name="plus" size={16} tintColorClassName="accent-icon" />
297 + </Pressable>
298 + ) : null}
299 + {props.filters.length > 0 ? (
300 + <Text className="px-4 pb-3 text-sm text-foreground-muted">
301 + Runs only when every filter matches. Other requests are logged as filtered. Separate “is
302 + one of” values with commas; a value can't contain a comma.
303 + </Text>
304 + ) : null}
305 + </>
306 + );
307 +}
308 +
309 function PickerRow(props: {
310 readonly label: string;
311 readonly value: string;
@@ -627,6 +711,11 @@ function TaskForm({
711 );
712 return;
713 }
714 + const parsedFilters = parseWebhookFilterDrafts(draft.schedule.filters);
715 + if (draft.schedule.mode === "webhook" && "error" in parsedFilters) {
716 + Dialog.alert("Invalid filter", parsedFilters.error);
717 + return;
718 + }
719 if (
720 !draft.title.trim() ||
721 !draft.prompt.trim() ||
@@ -964,6 +1053,13 @@ function TaskForm({
1053 setDraft({ ...draft, schedule: { ...draft.schedule, maxDeliveryAgeMinutes } })
1054 }
1055 />
1056 + <WebhookFilterRows
1057 + filters={draft.schedule.filters}
1058 + disabled={saving}
1059 + onChange={(filters) =>
1060 + setDraft({ ...draft, schedule: { ...draft.schedule, filters } })
1061 + }
1062 + />
1063 </>
1064 ) : (
1065 <>
apps/mobile/src/features/settings/scheduledTaskDraft.test.ts
+17
@@ -65,6 +65,23 @@ describe("scheduleDraftForTask", () => {
65 expect(saved).toEqual({ type: "webhook", signature, maxDeliveryAgeMinutes: null });
66 expect(saved?.type === "webhook" && saved.signature && "secret" in saved.signature).toBe(false);
67 });
68 +
69 + it("round-trips webhook filters and refuses an invalid one", () => {
70 + const filters = [
71 + { path: "headers.x-github-event", op: "equals", value: "pull_request" },
72 + { path: "body.label.name", op: "in", value: ["needs review", "agent:fix"] },
73 + ] as const;
74 + const draft = scheduleDraftForTask({ schedule: { type: "webhook", signature: null, filters } });
75 + // Untouched rows are left out, so the server keeps whatever is stored now.
76 + expect(scheduleFromDraft(draft)).not.toHaveProperty("filters");
77 + expect(scheduleFromDraft({ ...draft, filters: [] })).toMatchObject({ filters: [] });
78 + expect(scheduleFromDraft({ ...draft, filters: draft.filters.slice(1) })).toMatchObject({
79 + filters: filters.slice(1),
80 + });
81 + expect(
82 + scheduleFromDraft({ ...draft, filters: [{ id: "f1", path: "", op: "exists", value: "" }] }),
83 + ).toBeNull();
84 + });
85 });
86
87 describe("hasScheduledTaskDraftChanges", () => {
apps/mobile/src/features/settings/scheduledTaskDraft.ts
+21 -1
@@ -9,7 +9,13 @@ import type {
9 } from "@t3tools/contracts";
10
11 import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
12 -import { parseMaxDeliveryAge } from "@t3tools/client-runtime/scheduled-task-webhook";
12 +import {
13 + parseMaxDeliveryAge,
14 + parseWebhookFilterDrafts,
15 + webhookFilterDrafts,
16 + webhookFilterDraftsChanged,
17 + type WebhookFilterDraft,
18 +} from "@t3tools/client-runtime/scheduled-task-webhook";
19 import {
20 resolveProjectSettings,
21 type LegacyProjectSettingsFields,
@@ -50,6 +56,9 @@ export type ScheduleDraft = {
56 readonly intervalMinutes: string;
57 readonly signature: ScheduledTaskWebhookSignature | null;
58 readonly maxDeliveryAgeMinutes: string;
59 + readonly filters: ReadonlyArray<WebhookFilterDraft>;
60 + /** The filter rows the form opened with. */
61 + readonly savedFilters: ReadonlyArray<WebhookFilterDraft>;
62 };
63
64 export const DEFAULT_SCHEDULE: ScheduleDraft = {
@@ -59,6 +68,8 @@ export const DEFAULT_SCHEDULE: ScheduleDraft = {
68 intervalMinutes: "15",
69 signature: null,
70 maxDeliveryAgeMinutes: "",
71 + filters: [],
72 + savedFilters: [],
73 };
74
75 export function scheduleDraftForTask(task: Pick<ScheduledTask, "schedule">): ScheduleDraft {
@@ -86,6 +97,8 @@ export function scheduleDraftForTask(task: Pick<ScheduledTask, "schedule">): Sch
97 task.schedule.maxDeliveryAgeMinutes == null
98 ? ""
99 : String(task.schedule.maxDeliveryAgeMinutes),
100 + filters: webhookFilterDrafts(task.schedule.filters),
101 + savedFilters: webhookFilterDrafts(task.schedule.filters),
102 };
103 }
104 }
@@ -94,6 +107,8 @@ export function scheduleFromDraft(draft: ScheduleDraft): ScheduledTaskUpsertSche
107 if (draft.mode === "webhook") {
108 const maxDeliveryAgeMinutes = parseMaxDeliveryAge(draft.maxDeliveryAgeMinutes);
109 if (maxDeliveryAgeMinutes === undefined) return null;
110 + const parsedFilters = parseWebhookFilterDrafts(draft.filters);
111 + if (!("filters" in parsedFilters)) return null;
112 // No secret is sent, so the server keeps the stored one.
113 return {
114 type: "webhook",
@@ -106,6 +121,10 @@ export function scheduleFromDraft(draft: ScheduleDraft): ScheduledTaskUpsertSche
121 prefix: draft.signature.prefix,
122 },
123 maxDeliveryAgeMinutes,
124 + // Only edited filters are sent; the server keeps the stored ones otherwise.
125 + ...(webhookFilterDraftsChanged(draft.savedFilters, draft.filters)
126 + ? { filters: parsedFilters.filters }
127 + : {}),
128 };
129 }
130 if (draft.mode === "interval") {
@@ -160,6 +179,7 @@ function draftSignature(draft: ScheduledTaskDraft): string {
179 [...draft.schedule.weekdays].sort((a, b) => a - b),
180 draft.schedule.intervalMinutes,
181 draft.schedule.maxDeliveryAgeMinutes,
182 + draft.schedule.filters.map(({ path, op, value }) => [path, op, value]),
183 draft.workspace,
184 draft.baseRef,
185 draft.checkoutPath,
apps/server/src/mcp/toolkits/orchestrator/tools.ts
+2 -2
@@ -116,7 +116,7 @@ const WorkflowStopTool = Tool.make("t3_workflow_stop", {
116
117 export const ScheduleTaskTool = Tool.make("schedule_task", {
118 description:
119 - "Create persistent work in the app scheduler that runs even when no turn is active. Pass schedule as a STRUCTURED OBJECT, never JSON text. Timers: {type:'interval', everyMs:3600000} is hourly; {type:'fixed_time', timeOfDay:'09:00', weekdays:[1,2,3,4,5]} is weekday mornings; report the returned nextRunAt. Webhooks: {type:'webhook'} runs once per request to a generated URL. The run sees the request ONLY through prompt placeholders: {{body.path}} (e.g. {{body.action}}, {{body.release.tag_name}}), {{headers.name}}, {{query.name}}, {{body}}, or {{request}} (method, headers with credentials redacted, and body). Each value arrives framed as untrusted request data, and $skill, @file or /command mentions inside it do not act; without a signature, anyone with the URL can trigger a run. For a sender that signs requests, first call request_secret so the user enters the secret privately (never ask for it in chat or invent one), then set signature with the returned secretRef, e.g. GitHub: {type:'webhook', signature:{header:'x-hub-signature-256', encoding:'hex', prefix:'sha256=', secretRef}}. The result's webhookUrl is the public URL to give the user; if it is absent, this environment has no T3 Connect managed tunnel, so tell the user to enable T3 Connect remote access rather than sharing a path. Omit projectId for this thread's project. In this thread's project, runs post into THIS thread by default (bindToCurrentThread=true), which suits an orchestrator that sees every trigger, delegates work, and can dedupe against what is in flight; use false only when the user wants a fresh top-level thread per run. Elsewhere each run launches a fresh thread. Provider, model, and runtime settings inherit from this thread, or from the project default when there is no calling thread.",
119 + "Create persistent work in the app scheduler that runs even when no turn is active. Pass schedule as a STRUCTURED OBJECT, never JSON text. Timers: {type:'interval', everyMs:3600000} is hourly; {type:'fixed_time', timeOfDay:'09:00', weekdays:[1,2,3,4,5]} is weekday mornings; report the returned nextRunAt. Webhooks: {type:'webhook'} runs once per request to a generated URL. The run sees the request ONLY through prompt placeholders: {{body.path}} (e.g. {{body.action}}, {{body.release.tag_name}}), {{headers.name}}, {{query.name}}, {{body}}, or {{request}} (method, headers with credentials redacted, and body). Each value arrives framed as untrusted request data, and $skill, @file or /command mentions inside it do not act; without a signature, anyone with the URL can trigger a run. For a sender that signs requests, first call request_secret so the user enters the secret privately (never ask for it in chat or invent one), then set signature with the returned secretRef, e.g. GitHub: {type:'webhook', signature:{header:'x-hub-signature-256', encoding:'hex', prefix:'sha256=', secretRef}}. To run only for some requests, add filters, all of which must match, e.g. filters:[{path:'headers.x-github-event', op:'equals', value:'pull_request'}, {path:'body.action', op:'in', value:['opened','reopened']}]; ops are equals, notEquals, in, startsWith and exists. The result's webhookUrl is the public URL to give the user; if it is absent, this environment has no T3 Connect managed tunnel, so tell the user to enable T3 Connect remote access rather than sharing a path. Omit projectId for this thread's project. In this thread's project, runs post into THIS thread by default (bindToCurrentThread=true), which suits an orchestrator that sees every trigger, delegates work, and can dedupe against what is in flight; use false only when the user wants a fresh top-level thread per run. Elsewhere each run launches a fresh thread. Provider, model, and runtime settings inherit from this thread, or from the project default when there is no calling thread.",
120 parameters: OrchestratorMcpScheduleTaskInput,
121 success: OrchestratorMcpScheduleTaskResult,
122 failure: OrchestratorMcpFailure,
@@ -143,7 +143,7 @@ const ListScheduledTasksTool = Tool.make("list_scheduled_tasks", {
143
144 const UpdateScheduledTaskTool = Tool.make("update_scheduled_task", {
145 description:
146 - "Update an existing scheduled task by scheduledTaskId (from list_scheduled_tasks). Only the provided fields change; omit a field to leave it as-is. Use enabled=false to pause a task without deleting it. Set bindToCurrentThread to move the task between posting into this thread and launching a fresh thread per run.",
146 + "Update an existing scheduled task by scheduledTaskId (from list_scheduled_tasks). Only the provided fields change; omit a field to leave it as-is. Use enabled=false to pause a task without deleting it. Set bindToCurrentThread to move the task between posting into this thread and launching a fresh thread per run. A webhook schedule without filters keeps the stored filters; pass filters to replace them, or filters:[] to clear them.",
147 parameters: OrchestratorMcpUpdateScheduledTaskInput,
148 success: OrchestratorMcpScheduleTaskResult,
149 failure: OrchestratorMcpFailure,
apps/server/src/scheduledTasks/ScheduledTaskService.ts
+104 -25
@@ -15,6 +15,7 @@ import {
15 type ScheduledTaskListWebhookDeliveriesResult,
16 type ScheduledTaskRotateWebhookTokenInput,
17 type ScheduledTaskWebhookDeliveryOutcome,
18 + type ScheduledTaskWebhookFilter,
19 type ScheduledTaskListResult,
20 type ScheduledTaskMutationResult,
21 type ScheduledTaskRunNowInput,
@@ -53,10 +54,27 @@ import {
54 renderWebhookPrompt,
55 type WebhookRequest,
56 } from "./webhookTemplate.ts";
57 +import { describeFailedWebhookFilter, findFailedWebhookFilter } from "./webhookFilter.ts";
58 import { constantTimeEquals, verifyWebhookSignature } from "./webhookVerification.ts";
59
60 export const WEBHOOK_ROUTE_PREFIX = "/api/hooks";
61 const WEBHOOK_DELIVERY_RETENTION = 50;
62 +/** Kept apart from the rest, so a stream of filtered requests can't evict real deliveries. */
63 +const WEBHOOK_FILTERED_DELIVERY_RETENTION = 20;
64 +/** The outcomes clients decoded before outcomes became open-ended. */
65 +const LEGACY_DELIVERY_OUTCOMES: ReadonlySet<string> = new Set([
66 + "accepted",
67 + "dispatch_failed",
68 + "rejected_signature",
69 + "disabled",
70 + "rate_limited",
71 + "expired",
72 +]);
73 +/**
74 + * Filtered requests take no run slot, so this bounds the log writes they
75 + * cause instead; past it a filtered request is only counted in metrics.
76 + */
77 +const WEBHOOK_FILTERED_LOG_PER_MINUTE = 10;
78 const WEBHOOK_DELIVERY_LOG_BODY_LIMIT = 64 * 1024;
79 const WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT = 64 * 1024;
80 const WEBHOOK_MAX_QUEUED_PER_TASK = 20;
@@ -114,6 +132,7 @@ export type WebhookDeliveryOutcome =
132 | "disabled"
133 | "rejected_signature"
134 | "expired"
135 + | "filtered"
136 | "not_found"
137 | "error";
138
@@ -121,7 +140,7 @@ export type WebhookTriggerResult =
140 | {
141 readonly _tag: "accepted";
142 readonly deliveryId: ScheduledTaskWebhookDeliveryId;
124 - readonly outcome: "accepted" | "duplicate" | "prompt_too_long";
143 + readonly outcome: "accepted" | "duplicate" | "prompt_too_long" | "filtered";
144 }
145 | { readonly _tag: "not_found" }
146 | { readonly _tag: "rejected_signature" }
@@ -132,6 +151,9 @@ export type WebhookTriggerResult =
151 }
152 | { readonly _tag: "expired" };
153
154 +const webhookFilters = (filters: ReadonlyArray<ScheduledTaskWebhookFilter> | undefined) =>
155 + filters?.length ? { filters } : {};
156 +
157 const decodeTask = Schema.decodeUnknownEffect(ScheduledTask);
158 const decodeTaskId = Schema.decodeUnknownOption(ScheduledTaskId);
159 const decodeScheduleJson = Schema.decodeUnknownEffect(
@@ -383,6 +405,9 @@ export const layer = Layer.effect(
405 // finish late release their own count, never a recreated task's.
406 const webhookQueued = yield* Ref.make<ReadonlyMap<string, number>>(new Map());
407 const webhookRateWindows = yield* Ref.make<ReadonlyMap<ScheduledTaskId, RateWindow>>(new Map());
408 + const webhookFilteredLogWindows = yield* Ref.make<
409 + ReadonlyMap<ScheduledTaskId, ReadonlyArray<number>>
410 + >(new Map());
411 const activeRuns = yield* Ref.make<ReadonlySet<ScheduledTaskId>>(new Set());
412 // Sliding(1) coalesces the dirty-signal: every notification triggers a
413 // full list() re-emit anyway, so a slow subscriber only ever needs the
@@ -992,6 +1017,14 @@ export const layer = Layer.effect(
1017 prefix: input.schedule.signature.prefix,
1018 },
1019 maxDeliveryAgeMinutes: input.schedule.maxDeliveryAgeMinutes ?? null,
1020 + ...webhookFilters(
1021 + // Omitted keeps the stored filters, so a client that predates
1022 + // them can re-save a task without clearing them.
1023 + input.schedule.filters ??
1024 + (existingTask?.schedule.type === "webhook"
1025 + ? existingTask.schedule.filters
1026 + : undefined),
1027 + ),
1028 }
1029 : input.schedule;
1030 const webhook =
@@ -1106,6 +1139,11 @@ export const layer = Layer.effect(
1139 next.delete(id);
1140 return next;
1141 }),
1142 + Ref.update(webhookFilteredLogWindows, (windows) => {
1143 + const next = new Map(windows);
1144 + next.delete(id);
1145 + return next;
1146 + }),
1147 Ref.update(webhookPermits, (permits) => {
1148 const next = new Map(permits);
1149 next.delete(id);
@@ -1217,7 +1255,12 @@ export const layer = Layer.effect(
1255 WHERE task_id = ${input.id}
1256 ORDER BY received_at DESC, rowid DESC
1257 `.pipe(
1220 - Effect.map((rows) => ({ deliveries: rows.map(decodeDeliverySummary) })),
1258 + Effect.map((rows) => ({
1259 + deliveries: (input.acceptAnyOutcome === true
1260 + ? rows
1261 + : rows.filter((row) => LEGACY_DELIVERY_OUTCOMES.has(row.outcome))
1262 + ).map(decodeDeliverySummary),
1263 + })),
1264 Effect.mapError((cause) =>
1265 taskError("Could not list webhook deliveries.", { taskId: input.id, cause }),
1266 ),
@@ -1295,15 +1338,17 @@ export const layer = Layer.effect(
1338 rendered_prompt = excluded.rendered_prompt,
1339 error = excluded.error
1340 `;
1341 + const filtered = input.outcome === "filtered" ? 1 : 0;
1342 yield* sql`
1343 DELETE FROM scheduled_task_webhook_deliveries
1344 WHERE task_id = ${input.taskId}
1345 + AND (outcome = 'filtered') = ${filtered}
1346 AND delivery_id NOT IN (
1347 SELECT delivery_id FROM scheduled_task_webhook_deliveries
1303 - WHERE task_id = ${input.taskId}
1348 + WHERE task_id = ${input.taskId} AND (outcome = 'filtered') = ${filtered}
1349 -- rowid breaks timestamp ties in arrival order; delivery ids are random.
1350 ORDER BY received_at DESC, rowid DESC
1306 - LIMIT ${WEBHOOK_DELIVERY_RETENTION}
1351 + LIMIT ${filtered ? WEBHOOK_FILTERED_DELIVERY_RETENTION : WEBHOOK_DELIVERY_RETENTION}
1352 )
1353 `;
1354 }),
@@ -1351,6 +1396,18 @@ export const layer = Layer.effect(
1396 },
1397 );
1398
1399 + /** Sliding one-minute window of filtered requests written to the delivery log. */
1400 + const takeFilteredLogSlot = (id: ScheduledTaskId, nowMs: number) =>
1401 + Ref.modify(
1402 + webhookFilteredLogWindows,
1403 + (windows): readonly [boolean, ReadonlyMap<ScheduledTaskId, ReadonlyArray<number>>] => {
1404 + const recent = (windows.get(id) ?? []).filter((at) => nowMs - at < 60_000);
1405 + return recent.length >= WEBHOOK_FILTERED_LOG_PER_MINUTE
1406 + ? [false, windows]
1407 + : [true, new Map(windows).set(id, [...recent, nowMs])];
1408 + },
1409 + );
1410 +
1411 const webhookPermit = Effect.fn("ScheduledTaskService.webhookPermit")(function* (
1412 id: ScheduledTaskId,
1413 ) {
@@ -1514,6 +1571,44 @@ export const layer = Layer.effect(
1571 ...(details.error === undefined ? {} : { error: details.error }),
1572 });
1573
1574 + const signature = schedule.signature;
1575 + const signatureVerified =
1576 + signature === null ||
1577 + (row.webhook_secret !== null &&
1578 + verifyWebhookSignature({
1579 + signature,
1580 + secret: row.webhook_secret,
1581 + headers: request.headers,
1582 + body: request.body,
1583 + }));
1584 + const maxAgeMinutes = schedule.maxDeliveryAgeMinutes ?? null;
1585 + const tooOld =
1586 + maxAgeMinutes !== null &&
1587 + DateTime.toEpochMillis(now) - DateTime.toEpochMillis(receivedAt) >
1588 + maxAgeMinutes * 60_000;
1589 +
1590 + // Filters: checked after the signature and age, and before the rate
1591 + // limit, so requests the task ignores never take a run's slot. The
1592 + // request is accepted so the sender doesn't retry it, and its relay
1593 + // claim is released because nothing ran.
1594 + if (task.enabled && signatureVerified && !tooOld) {
1595 + const failedFilter = findFailedWebhookFilter(schedule.filters ?? [], request);
1596 + if (failedFilter !== null) {
1597 + if (yield* takeFilteredLogSlot(task.id, DateTime.toEpochMillis(now))) {
1598 + yield* log("filtered", {
1599 + signatureVerified: signature !== null,
1600 + error: describeFailedWebhookFilter(failedFilter),
1601 + });
1602 + }
1603 + yield* observe("filtered");
1604 + return yield* releaseClaim({
1605 + _tag: "accepted" as const,
1606 + deliveryId,
1607 + outcome: "filtered" as const,
1608 + });
1609 + }
1610 + }
1611 +
1612 // Only the first rejected request in a window is logged, so a flood
1613 // cannot write rows or push the real deliveries out of the log.
1614 const slot = yield* takeRateSlot(task.id, DateTime.toEpochMillis(now));
@@ -1530,28 +1625,12 @@ export const layer = Layer.effect(
1625 yield* observe("disabled");
1626 return { _tag: "disabled" as const };
1627 }
1533 - const signature = schedule.signature;
1534 - if (signature !== null) {
1535 - const verified =
1536 - row.webhook_secret !== null &&
1537 - verifyWebhookSignature({
1538 - signature,
1539 - secret: row.webhook_secret,
1540 - headers: request.headers,
1541 - body: request.body,
1542 - });
1543 - if (!verified) {
1544 - yield* log("rejected_signature");
1545 - yield* observe("rejected_signature");
1546 - return { _tag: "rejected_signature" as const };
1547 - }
1628 + if (!signatureVerified) {
1629 + yield* log("rejected_signature");
1630 + yield* observe("rejected_signature");
1631 + return { _tag: "rejected_signature" as const };
1632 }
1549 - const maxAgeMinutes = schedule.maxDeliveryAgeMinutes ?? null;
1550 - if (
1551 - maxAgeMinutes !== null &&
1552 - DateTime.toEpochMillis(now) - DateTime.toEpochMillis(receivedAt) >
1553 - maxAgeMinutes * 60_000
1554 - ) {
1633 + if (tooOld) {
1634 yield* log("expired", { signatureVerified: signature !== null });
1635 yield* observe("expired");
1636 return { _tag: "expired" as const };
apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts
+204
@@ -953,3 +953,207 @@ it.effect("counts each handled request by what happened to it", () =>
953 }),
954 ),
955 );
956 +
957 +it.effect("checks filters after the signature and max age, and runs only matching deliveries", () =>
958 + withService(({ service, launches }) =>
959 + Effect.gen(function* () {
960 + const { task } = yield* service.upsert(
961 + yield* webhookTaskInput({
962 + schedule: {
963 + type: "webhook",
964 + signature: {
965 + header: "x-hub-signature-256",
966 + encoding: "hex",
967 + prefix: "sha256=",
968 + secret: "s3cret",
969 + },
970 + maxDeliveryAgeMinutes: 30,
971 + filters: [
972 + { path: "headers.x-github-event", op: "equals", value: "pull_request" },
973 + { path: "body.action", op: "in", value: ["opened", "reopened"] },
974 + ],
975 + },
976 + }),
977 + );
978 + const delivery = (
979 + event: string,
980 + action: string,
981 + options: { readonly signed?: boolean; readonly receivedAt?: string } = {},
982 + ) => {
983 + const body = new TextEncoder().encode(
984 + JSON.stringify({ action, pull_request: { url: "https://github.com/org/repo/pull/45" } }),
985 + );
986 + const signature = `sha256=${NodeCrypto.createHmac("sha256", "s3cret").update(body).digest("hex")}`;
987 + return requestFor(task, {
988 + headers: {
989 + "content-type": "application/json",
990 + "x-github-event": event,
991 + ...(options.signed === false ? {} : { "x-hub-signature-256": signature }),
992 + },
993 + body,
994 + bodyText: new TextDecoder().decode(body),
995 + ...(options.receivedAt === undefined
996 + ? {}
997 + : { relayDeliveryId: "old", receivedAt: options.receivedAt }),
998 + });
999 + };
1000 + const now = yield* DateTime.now;
1001 + const old = DateTime.formatIso(DateTime.subtract(now, { minutes: 31 }));
1002 +
1003 + // A request failing a filter is still refused first for its signature or age.
1004 + const unsigned = yield* service.triggerWebhook(delivery("push", "opened", { signed: false }));
1005 + assert.equal(unsigned._tag, "rejected_signature");
1006 + const tooOld = yield* service.triggerWebhook(delivery("push", "opened", { receivedAt: old }));
1007 + assert.equal(tooOld._tag, "expired");
1008 +
1009 + const wrongEvent = yield* service.triggerWebhook(delivery("push", "opened"));
1010 + const wrongAction = yield* service.triggerWebhook(delivery("pull_request", "closed"));
1011 + assert.deepInclude(wrongEvent, { _tag: "accepted", outcome: "filtered" });
1012 + assert.deepInclude(wrongAction, { _tag: "accepted", outcome: "filtered" });
1013 + assert.equal(yield* Queue.size(launches), 0);
1014 + const [listed] = (yield* service.list()).tasks;
1015 + assert.equal(listed?.runCount, 0);
1016 + assert.equal(listed?.lastRunStatus, "never");
1017 +
1018 + const matched = yield* service.triggerWebhook(delivery("pull_request", "opened"));
1019 + assert.deepInclude(matched, { _tag: "accepted", outcome: "accepted" });
1020 + assert.include((yield* Queue.take(launches)).initialMessage?.text ?? "", "pull/45");
1021 +
1022 + const deliveries = (yield* service.listWebhookDeliveries({
1023 + id: task.id,
1024 + acceptAnyOutcome: true,
1025 + })).deliveries;
1026 + const filtered = deliveries
1027 + .filter((entry) => entry.outcome === "filtered")
1028 + .map((entry) => [entry.signatureVerified, entry.error]);
1029 + assert.sameDeepMembers(filtered, [
1030 + [true, "Filter 1 (headers.x-github-event) did not match."],
1031 + [true, "Filter 2 (body.action) did not match."],
1032 + ]);
1033 + }),
1034 + ),
1035 +);
1036 +
1037 +const pullRequestFilterInput = () =>
1038 + webhookTaskInput({
1039 + schedule: {
1040 + type: "webhook",
1041 + filters: [{ path: "headers.x-github-event", op: "equals", value: "pull_request" }],
1042 + },
1043 + });
1044 +const githubEvent = (event: string) => ({
1045 + headers: { "content-type": "application/json", "x-github-event": event },
1046 +});
1047 +
1048 +it.effect("filtered deliveries take no run slot and log at most 10 rows a minute", () =>
1049 + withService(({ service, launches }) =>
1050 + Effect.gen(function* () {
1051 + const { task } = yield* service.upsert(yield* pullRequestFilterInput());
1052 + const ignored = yield* Effect.forEach(Array.from({ length: 70 }), () =>
1053 + service.triggerWebhook(requestFor(task, githubEvent("push"))),
1054 + );
1055 + assert.isTrue(
1056 + ignored.every((result) => result._tag === "accepted" && result.outcome === "filtered"),
1057 + );
1058 + const matched = yield* service.triggerWebhook(requestFor(task, githubEvent("pull_request")));
1059 + assert.deepInclude(matched, { _tag: "accepted", outcome: "accepted" });
1060 + yield* Queue.take(launches);
1061 + yield* Effect.forEach(Array.from({ length: 5 }), () =>
1062 + service.triggerWebhook(requestFor(task, githubEvent("push"))),
1063 + );
1064 +
1065 + const outcomes = (yield* service.listWebhookDeliveries({
1066 + id: task.id,
1067 + acceptAnyOutcome: true,
1068 + })).deliveries.map((delivery) => delivery.outcome);
1069 + // 75 filtered requests in one window: only the first 10 are written.
1070 + assert.equal(outcomes.filter((outcome) => outcome === "filtered").length, 10);
1071 + assert.equal(outcomes.filter((outcome) => outcome === "accepted").length, 1);
1072 +
1073 + // Later windows log again, and retention keeps the filtered rows at 20.
1074 + for (const _ of [1, 2]) {
1075 + yield* TestClock.adjust("61 seconds");
1076 + yield* Effect.forEach(Array.from({ length: 15 }), () =>
1077 + service.triggerWebhook(requestFor(task, githubEvent("push"))),
1078 + );
1079 + }
1080 + const later = (yield* service.listWebhookDeliveries({ id: task.id, acceptAnyOutcome: true }))
1081 + .deliveries;
1082 + assert.equal(later.filter((delivery) => delivery.outcome === "filtered").length, 20);
1083 + assert.equal(later.filter((delivery) => delivery.outcome === "accepted").length, 1);
1084 + }),
1085 + ),
1086 +);
1087 +
1088 +it.effect("a filtered relay delivery releases its claim, so a redelivery is evaluated again", () =>
1089 + withService(({ service, launches }) =>
1090 + Effect.gen(function* () {
1091 + const { task } = yield* service.upsert(yield* pullRequestFilterInput());
1092 + const held = { relayDeliveryId: "relay-filtered" };
1093 + const first = yield* service.triggerWebhook(
1094 + requestFor(task, { ...held, ...githubEvent("push") }),
1095 + );
1096 + const again = yield* service.triggerWebhook(
1097 + requestFor(task, { ...held, ...githubEvent("push") }),
1098 + );
1099 + assert.deepInclude(first, { _tag: "accepted", outcome: "filtered" });
1100 + assert.deepInclude(again, { _tag: "accepted", outcome: "filtered" });
1101 + const ran = yield* service.triggerWebhook(
1102 + requestFor(task, { ...held, ...githubEvent("pull_request") }),
1103 + );
1104 + assert.deepInclude(ran, { _tag: "accepted", outcome: "accepted" });
1105 + yield* Queue.take(launches);
1106 + const replayed = yield* service.triggerWebhook(
1107 + requestFor(task, { ...held, ...githubEvent("pull_request") }),
1108 + );
1109 + assert.deepInclude(replayed, { _tag: "accepted", outcome: "duplicate" });
1110 + }),
1111 + ),
1112 +);
1113 +
1114 +it.effect("a save without filters keeps the stored ones and an empty list clears them", () =>
1115 + withService(({ service }) =>
1116 + Effect.gen(function* () {
1117 + const { task } = yield* service.upsert(yield* pullRequestFilterInput());
1118 + const filters = task.schedule.type === "webhook" ? task.schedule.filters : undefined;
1119 + assert.lengthOf(filters ?? [], 1);
1120 +
1121 + const kept = yield* service.upsert(
1122 + yield* webhookTaskInput({ title: "Renamed", schedule: { type: "webhook" } }),
1123 + );
1124 + assert.deepEqual(
1125 + kept.task.schedule.type === "webhook" && kept.task.schedule.filters,
1126 + filters,
1127 + );
1128 +
1129 + const cleared = yield* service.upsert(
1130 + yield* webhookTaskInput({ schedule: { type: "webhook", filters: [] } }),
1131 + );
1132 + assert.notProperty(cleared.task.schedule, "filters");
1133 + }),
1134 + ),
1135 +);
1136 +
1137 +it.effect("leaves filtered rows out of the list for clients that only decode older outcomes", () =>
1138 + withService(({ service, launches }) =>
1139 + Effect.gen(function* () {
1140 + const { task } = yield* service.upsert(yield* pullRequestFilterInput());
1141 + yield* service.triggerWebhook(requestFor(task, githubEvent("push")));
1142 + yield* service.triggerWebhook(requestFor(task, githubEvent("pull_request")));
1143 + yield* Queue.take(launches);
1144 + const legacy = (yield* service.listWebhookDeliveries({ id: task.id })).deliveries;
1145 + assert.deepEqual(
1146 + legacy.map((delivery) => delivery.outcome),
1147 + ["accepted"],
1148 + );
1149 + const current = (yield* service.listWebhookDeliveries({
1150 + id: task.id,
1151 + acceptAnyOutcome: true,
1152 + })).deliveries;
1153 + assert.sameMembers(
1154 + current.map((delivery) => delivery.outcome),
1155 + ["accepted", "filtered"],
1156 + );
1157 + }),
1158 + ),
1159 +);
apps/server/src/scheduledTasks/webhookFilter.test.ts new
+91
@@ -0,0 +1,91 @@
1 +import { assert, describe, it } from "@effect/vitest";
2 +import type { ScheduledTaskWebhookFilter } from "@t3tools/contracts";
3 +
4 +import { findFailedWebhookFilter, matchesWebhookFilter } from "./webhookFilter.ts";
5 +import type { WebhookRequest } from "./webhookTemplate.ts";
6 +
7 +const request: WebhookRequest = {
8 + method: "POST",
9 + path: "/api/hooks/task-1",
10 + query: "source=github",
11 + headers: { "content-type": "application/json", "x-github-event": "pull_request" },
12 + bodyText: JSON.stringify({
13 + action: "labeled",
14 + number: 45,
15 + draft: false,
16 + closed_at: null,
17 + label: { name: "agent:review" },
18 + labels: ["bug"],
19 + }),
20 +};
21 +
22 +const matches = (filter: ScheduledTaskWebhookFilter) =>
23 + findFailedWebhookFilter([filter], request) === null;
24 +
25 +describe("matchesWebhookFilter", () => {
26 + it("compares scalars as strings", () => {
27 + assert.isTrue(matches({ path: "body.action", op: "equals", value: "labeled" }));
28 + assert.isTrue(matches({ path: "body.number", op: "equals", value: "45" }));
29 + assert.isTrue(matches({ path: "body.draft", op: "equals", value: "false" }));
30 + assert.isFalse(matches({ path: "body.action", op: "equals", value: "Labeled" }));
31 + assert.isTrue(matches({ path: "body.action", op: "notEquals", value: "closed" }));
32 + assert.isFalse(matches({ path: "body.action", op: "notEquals", value: "labeled" }));
33 + assert.isTrue(matches({ path: "body.action", op: "in", value: ["opened", "labeled"] }));
34 + assert.isTrue(matches({ path: "body.label.name", op: "startsWith", value: "agent:" }));
35 + assert.isFalse(matches({ path: "body.label.name", op: "startsWith", value: "review" }));
36 + });
37 +
38 + it("reads headers case-insensitively and query values by name", () => {
39 + assert.isTrue(matches({ path: "headers.X-GitHub-Event", op: "equals", value: "pull_request" }));
40 + assert.isTrue(matches({ path: "query.source", op: "equals", value: "github" }));
41 + });
42 +
43 + it("lets objects and arrays satisfy only exists", () => {
44 + for (const path of ["body.label", "body.labels"]) {
45 + assert.isTrue(matches({ path, op: "exists" }));
46 + assert.isFalse(matches({ path, op: "equals", value: "[object Object]" }));
47 + assert.isFalse(matches({ path, op: "notEquals", value: "anything" }));
48 + assert.isFalse(matches({ path, op: "in", value: ["bug"] }));
49 + assert.isFalse(matches({ path, op: "startsWith", value: "" }));
50 + }
51 + });
52 +
53 + it("fails every op on a missing or null path, including notEquals", () => {
54 + for (const path of [
55 + "body.missing",
56 + "body.label.name.deeper",
57 + "headers.x-none",
58 + "body.closed_at",
59 + ]) {
60 + assert.isFalse(matches({ path, op: "exists" }));
61 + assert.isFalse(matches({ path, op: "notEquals", value: "x" }));
62 + assert.isFalse(matchesWebhookFilter({ path, op: "startsWith", value: "" }, undefined));
63 + }
64 + });
65 +});
66 +
67 +describe("findFailedWebhookFilter", () => {
68 + it("passes with no filters and reports the first failing filter", () => {
69 + assert.isNull(findFailedWebhookFilter([], request));
70 + assert.deepEqual(
71 + findFailedWebhookFilter(
72 + [
73 + { path: "headers.x-github-event", op: "equals", value: "pull_request" },
74 + { path: "body.action", op: "equals", value: "opened" },
75 + { path: "body.missing", op: "exists" },
76 + ],
77 + request,
78 + ),
79 + { index: 1, path: "body.action" },
80 + );
81 + });
82 +
83 + it("does not need a JSON body for header filters", () => {
84 + assert.isNull(
85 + findFailedWebhookFilter([{ path: "headers.x-github-event", op: "exists" }], {
86 + ...request,
87 + bodyText: "not json",
88 + }),
89 + );
90 + });
91 +});
apps/server/src/scheduledTasks/webhookFilter.ts new
+49
@@ -0,0 +1,49 @@
1 +import type { ScheduledTaskWebhookFilter } from "@t3tools/contracts";
2 +
3 +import { webhookExpressionResolver, type WebhookRequest } from "./webhookTemplate.ts";
4 +
5 +export interface FailedWebhookFilter {
6 + readonly index: number;
7 + readonly path: string;
8 +}
9 +
10 +function scalarText(value: unknown): string | undefined {
11 + if (typeof value === "string") return value;
12 + if (typeof value === "number" || typeof value === "boolean") return String(value);
13 + return undefined;
14 +}
15 +
16 +/** Placeholders render null as missing, so filters treat it the same way. */
17 +export function matchesWebhookFilter(filter: ScheduledTaskWebhookFilter, value: unknown): boolean {
18 + if (filter.op === "exists") return value !== undefined && value !== null;
19 + const text = scalarText(value);
20 + if (text === undefined) return false;
21 + switch (filter.op) {
22 + case "equals":
23 + return text === filter.value;
24 + case "notEquals":
25 + return text !== filter.value;
26 + case "in":
27 + return filter.value.includes(text);
28 + case "startsWith":
29 + return text.startsWith(filter.value);
30 + }
31 +}
32 +
33 +/** The first filter the request fails, or null when every filter matches. */
34 +export function findFailedWebhookFilter(
35 + filters: ReadonlyArray<ScheduledTaskWebhookFilter>,
36 + request: WebhookRequest,
37 +): FailedWebhookFilter | null {
38 + if (filters.length === 0) return null;
39 + const resolve = webhookExpressionResolver(request);
40 + for (const [index, filter] of filters.entries()) {
41 + if (!matchesWebhookFilter(filter, resolve(filter.path))) return { index, path: filter.path };
42 + }
43 + return null;
44 +}
45 +
46 +/** Filters are numbered from 1, in the order the settings form lists them. */
47 +export function describeFailedWebhookFilter(failed: FailedWebhookFilter): string {
48 + return `Filter ${failed.index + 1} (${failed.path}) did not match.`;
49 +}
apps/server/src/scheduledTasks/webhookRoute.test.ts
+1
@@ -222,6 +222,7 @@ describe("webhook route", () => {
222 [{ _tag: "accepted", deliveryId, outcome: "accepted" }, 202, "accepted"],
223 [{ _tag: "accepted", deliveryId, outcome: "duplicate" }, 202, "duplicate"],
224 [{ _tag: "accepted", deliveryId, outcome: "prompt_too_long" }, 202, "prompt_too_long"],
225 + [{ _tag: "accepted", deliveryId, outcome: "filtered" }, 202, "filtered"],
226 [{ _tag: "not_found" }, 404, "not_found"],
227 [{ _tag: "rejected_signature" }, 401, "rejected_signature"],
228 [{ _tag: "disabled" }, 409, "disabled"],
apps/server/src/scheduledTasks/webhookTemplate.ts
+16 -6
@@ -112,16 +112,17 @@ function formatWebhookRequest(request: WebhookRequest): string {
112 ].join("\n");
113 }
114
115 -export function renderWebhookPrompt(
116 - template: string,
115 +/**
116 + * Resolves a placeholder expression (`body.action`, `headers.x-github-event`)
117 + * against the request. Webhook filters share it, so both read the same value.
118 + */
119 +export function webhookExpressionResolver(
120 request: WebhookRequest,
118 - frameId: string,
119 -): RenderedWebhookPrompt {
120 - const missing: string[] = [];
121 +): (expression: string) => unknown {
122 let body: { parsed: unknown } | undefined;
123 const parsedBody = () => (body ??= { parsed: parseBody(request) }).parsed;
124
124 - const resolve = (expression: string): unknown => {
125 + return (expression) => {
126 const [root, ...segments] = expression.split(".");
127 switch (root) {
128 case "request":
@@ -143,6 +144,15 @@ export function renderWebhookPrompt(
144 return undefined;
145 }
146 };
147 +}
148 +
149 +export function renderWebhookPrompt(
150 + template: string,
151 + request: WebhookRequest,
152 + frameId: string,
153 +): RenderedWebhookPrompt {
154 + const missing: string[] = [];
155 + const resolve = webhookExpressionResolver(request);
156
157 const tag = `webhook-data-${frameId}`;
158 let framed = false;
apps/web/src/components/settings/ScheduledTasksSettings.tsx
+148 -9
@@ -26,9 +26,17 @@ import type {
26 ScheduledTaskWebhookDeliverySummary,
27 ThreadId,
28 } from "@t3tools/contracts";
29 -import { DEFAULT_WEBHOOK_PROMPT } from "@t3tools/client-runtime/scheduled-task-webhook";
29 +import {
30 + DEFAULT_WEBHOOK_PROMPT,
31 + emptyWebhookFilterDraft,
32 + parseWebhookFilterDrafts,
33 + removeWebhookFilterDraft,
34 + WEBHOOK_FILTER_OPS,
35 + type WebhookFilterDraft,
36 +} from "@t3tools/client-runtime/scheduled-task-webhook";
37 import {
38 MAX_WEBHOOK_DELIVERY_AGE_MINUTES,
39 + MAX_WEBHOOK_FILTERS,
40 MIN_SCHEDULED_TASK_INTERVAL_MS,
41 ProviderInstanceId,
42 resolveEnvironmentMachineKind,
@@ -144,8 +152,103 @@ const EMPTY_DRAFT: DraftState = {
152 ...WEBHOOK_SIGNATURE_DEFAULTS,
153 signatureSecret: "",
154 maxDeliveryAgeMinutes: "",
155 + filters: [],
156 + savedFilters: [],
157 };
158
159 +function WebhookFiltersField({
160 + filters,
161 + onChange,
162 +}: {
163 + filters: ReadonlyArray<WebhookFilterDraft>;
164 + onChange: (filters: ReadonlyArray<WebhookFilterDraft>) => void;
165 +}) {
166 + const update = (index: number, patch: Partial<WebhookFilterDraft>) =>
167 + onChange(filters.map((filter, at) => (at === index ? { ...filter, ...patch } : filter)));
168 + return (
169 + <div className="space-y-2">
170 + <div className="flex items-center justify-between gap-2">
171 + <div className="min-w-0 space-y-1">
172 + <Label>Filters</Label>
173 + <p className="text-sm text-muted-foreground">
174 + Run only when every filter matches. Other requests are logged as filtered. Separate “is
175 + one of” values with commas; a value can't contain a comma.
176 + </p>
177 + </div>
178 + <Button
179 + className="shrink-0"
180 + variant="outline"
181 + size="sm"
182 + disabled={filters.length >= MAX_WEBHOOK_FILTERS}
183 + onClick={() => onChange([...filters, emptyWebhookFilterDraft()])}
184 + >
185 + <PlusIcon />
186 + Add filter
187 + </Button>
188 + </div>
189 + {filters.map((filter, index) => (
190 + // Always stacked: the dialog stays narrow on wide windows, so a single line
191 + // would cut off typical paths and values. The grid wrappers size each control
192 + // without restyling it; a grid item stretches to its minmax(0, 1fr) track.
193 + <div key={filter.id} className="space-y-2 pt-1">
194 + <div className="flex items-center gap-2">
195 + <div className="grid min-w-0 flex-1 grid-cols-1">
196 + <Input
197 + aria-label={`Filter ${index + 1} path`}
198 + placeholder="body.action"
199 + value={filter.path}
200 + onChange={(event) => update(index, { path: event.target.value })}
201 + />
202 + </div>
203 + <Button
204 + variant="ghost"
205 + size="icon-sm"
206 + aria-label={`Remove filter ${index + 1}`}
207 + onClick={() => onChange(removeWebhookFilterDraft(filters, filter.id))}
208 + >
209 + <Trash2Icon />
210 + </Button>
211 + </div>
212 + <div className="flex items-center gap-2">
213 + <Select
214 + value={filter.op}
215 + onValueChange={(op) => {
216 + const known = WEBHOOK_FILTER_OPS.find((option) => option.op === op);
217 + if (known) update(index, { op: known.op });
218 + }}
219 + >
220 + <div className="grid w-44 shrink-0 grid-cols-1">
221 + <SelectTrigger size="sm" aria-label={`Filter ${index + 1} test`}>
222 + <SelectValue>
223 + {WEBHOOK_FILTER_OPS.find((option) => option.op === filter.op)?.label}
224 + </SelectValue>
225 + </SelectTrigger>
226 + </div>
227 + <SelectPopup>
228 + {WEBHOOK_FILTER_OPS.map((option) => (
229 + <SelectItem key={option.op} value={option.op}>
230 + {option.label}
231 + </SelectItem>
232 + ))}
233 + </SelectPopup>
234 + </Select>
235 + {filter.op === "exists" ? null : (
236 + <div className="grid min-w-0 flex-1 grid-cols-1">
237 + <Input
238 + aria-label={`Filter ${index + 1} value`}
239 + placeholder={filter.op === "in" ? "opened, reopened" : "opened"}
240 + value={filter.value}
241 + onChange={(event) => update(index, { value: event.target.value })}
242 + />
243 + </div>
244 + )}
245 + </div>
246 + </div>
247 + ))}
248 + </div>
249 + );
250 +}
251 +
252 function Field({
253 label,
254 hint,
@@ -232,14 +335,23 @@ const DELIVERY_OUTCOME_LABELS: Record<ScheduledTaskWebhookDeliveryOutcome, strin
335 disabled: "Task paused",
336 rate_limited: "Rate limited",
337 expired: "Too old",
338 + filtered: "Filtered",
339 };
340
237 -function deliveryOutcomeVariant(outcome: ScheduledTaskWebhookDeliveryOutcome) {
341 +// A newer server can report an outcome this client has no label for.
342 +function deliveryOutcomeLabel(outcome: string): string {
343 + return Object.hasOwn(DELIVERY_OUTCOME_LABELS, outcome)
344 + ? DELIVERY_OUTCOME_LABELS[outcome as ScheduledTaskWebhookDeliveryOutcome]
345 + : outcome.replaceAll("_", " ");
346 +}
347 +
348 +function deliveryOutcomeVariant(outcome: string) {
349 if (outcome === "accepted") return "success";
350 if (outcome === "disabled" || outcome === "rate_limited" || outcome === "expired") {
351 return "warning";
352 }
242 - return "error";
353 + if (outcome === "dispatch_failed" || outcome === "rejected_signature") return "error";
354 + return "outline";
355 }
356
357 function statusVariant(status: ScheduledTask["lastRunStatus"]) {
@@ -697,7 +809,10 @@ function WebhookDeliveriesDialog({
809 readonly onClose: () => void;
810 }) {
811 const deliveriesQuery = useEnvironmentQuery(
700 - serverEnvironment.scheduledTaskWebhookDeliveries({ environmentId, input: { id: task.id } }),
812 + serverEnvironment.scheduledTaskWebhookDeliveries({
813 + environmentId,
814 + input: { id: task.id, acceptAnyOutcome: true },
815 + }),
816 );
817 const [selectedId, setSelectedId] = useState<ScheduledTaskWebhookDeliverySummary["id"] | null>(
818 null,
@@ -736,7 +851,7 @@ function WebhookDeliveriesDialog({
851 <div className="space-y-4">
852 <div className="flex flex-wrap items-center gap-2 text-sm">
853 <Badge variant={deliveryOutcomeVariant(selected.outcome)}>
739 - {DELIVERY_OUTCOME_LABELS[selected.outcome]}
854 + {deliveryOutcomeLabel(selected.outcome)}
855 </Badge>
856 <span>
857 {selected.method} · <ScheduledRelativeLabel value={selected.receivedAt} />
@@ -745,7 +860,17 @@ function WebhookDeliveriesDialog({
860 <span className="text-muted-foreground">Signature verified</span>
861 ) : null}
862 </div>
748 - {selected.error ? <p className="text-sm text-destructive">{selected.error}</p> : null}
863 + {selected.error ? (
864 + <p
865 + className={
866 + selected.outcome === "filtered"
867 + ? "text-sm text-muted-foreground"
868 + : "text-sm text-destructive"
869 + }
870 + >
871 + {selected.error}
872 + </p>
873 + ) : null}
874 <DeliveryBlock title="Prompt sent to the agent">
875 {selected.renderedPrompt ?? "No run was started for this request."}
876 </DeliveryBlock>
@@ -782,12 +907,15 @@ function WebhookDeliveriesDialog({
907 onClick={() => setSelectedId(delivery.id)}
908 >
909 <Badge variant={deliveryOutcomeVariant(delivery.outcome)}>
785 - {DELIVERY_OUTCOME_LABELS[delivery.outcome]}
910 + {deliveryOutcomeLabel(delivery.outcome)}
911 </Badge>
912 <span>{delivery.method}</span>
913 <span className="text-muted-foreground">
914 <ScheduledRelativeLabel value={delivery.receivedAt} />
915 </span>
916 + {delivery.outcome === "filtered" && delivery.error ? (
917 + <span className="text-muted-foreground">{delivery.error}</span>
918 + ) : null}
919 {delivery.missingFields.length > 0 ? (
920 <span className="text-muted-foreground">
921 {delivery.missingFields.length} empty placeholder
@@ -1058,6 +1186,11 @@ function ScheduledTaskEditorForm({
1186 reportFailure("Scheduled task is incomplete", "Add a title, prompt, project, and model.");
1187 return;
1188 }
1189 + const parsedFilters = parseWebhookFilterDrafts(draft.filters);
1190 + if (draft.scheduleMode === "webhook" && "error" in parsedFilters) {
1191 + reportFailure("Invalid filter", parsedFilters.error);
1192 + return;
1193 + }
1194 const schedule = scheduleFromDraft(draft);
1195 if (schedule === null) {
1196 reportFailure(
@@ -1142,7 +1275,8 @@ function ScheduledTaskEditorForm({
1275 </DialogHeader>
1276
1277 <DialogPanel>
1145 - <fieldset disabled={saving} className="space-y-5">
1278 + {/* Fieldsets default to min-width: min-content, which lets one wide control widen the form past the dialog. */}
1279 + <fieldset disabled={saving} className="min-w-0 space-y-5">
1280 {!connected ? (
1281 <p className="text-sm text-destructive">Reconnect this environment before saving.</p>
1282 ) : null}
@@ -1351,7 +1485,8 @@ function ScheduledTaskEditorForm({
1485 minute.
1486 </p>
1487 ) : null}
1354 - <div className="flex items-center justify-between gap-2">
1488 + {/* Wraps the toggle below the label when both don't fit, as on phones. */}
1489 + <div className="flex flex-wrap items-center justify-between gap-2">
1490 <Label>Schedule</Label>
1491 <ToggleGroup
1492 aria-label="Schedule type"
@@ -1404,6 +1539,10 @@ function ScheduledTaskEditorForm({
1539 }
1540 />
1541 </Field>
1542 + <WebhookFiltersField
1543 + filters={draft.filters}
1544 + onChange={(filters) => setDraft((current) => ({ ...current, filters }))}
1545 + />
1546 <div className="flex items-center justify-between gap-4">
1547 <div className="min-w-0 space-y-1">
1548 <Label htmlFor="scheduled-task-signature">Require signature</Label>
apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts
+25
@@ -218,6 +218,31 @@ describe("webhook scheduled tasks", () => {
218 expect(scheduleFromDraft({ ...draft, maxDeliveryAgeMinutes: invalid })).toBeNull();
219 }
220 });
221 +
222 + it("sends filters only when the form changed them", () => {
223 + const filters = [
224 + { path: "headers.x-github-event", op: "equals", value: "pull_request" },
225 + { path: "body.action", op: "in", value: ["opened", "reopened"] },
226 + ] as const;
227 + const draft = taskToDraft({
228 + ...webhookTask,
229 + schedule: { type: "webhook", signature, filters },
230 + });
231 + expect(draft.filters.map((filter) => filter.op)).toEqual(["equals", "in"]);
232 + // A title-only save leaves the key out, so the server keeps whatever is stored now.
233 + expect(scheduleFromDraft({ ...draft, title: "Renamed" })).not.toHaveProperty("filters");
234 + expect(scheduleFromDraft({ ...draft, filters: draft.filters.slice(0, 1) })).toMatchObject({
235 + filters: filters.slice(0, 1),
236 + });
237 + // Removing every row is a change, so it clears the stored filters.
238 + expect(scheduleFromDraft({ ...draft, filters: [] })).toMatchObject({ filters: [] });
239 + expect(
240 + scheduleFromDraft({
241 + ...draft,
242 + filters: [{ id: "f1", path: "body.action", op: "in", value: " , " }],
243 + }),
244 + ).toBeNull();
245 + });
246 });
247
248 describe("scheduled task model defaults", () => {
apps/web/src/components/settings/scheduledTasksSettings.logic.ts
+19 -1
@@ -9,7 +9,13 @@ import {
9 type ProviderInteractionMode,
10 type ServerSettings,
11 } from "@t3tools/contracts";
12 -import { parseMaxDeliveryAge } from "@t3tools/client-runtime/scheduled-task-webhook";
12 +import {
13 + parseMaxDeliveryAge,
14 + parseWebhookFilterDrafts,
15 + webhookFilterDrafts,
16 + webhookFilterDraftsChanged,
17 + type WebhookFilterDraft,
18 +} from "@t3tools/client-runtime/scheduled-task-webhook";
19
20 import {
21 resolveProjectSettings,
@@ -77,6 +83,9 @@ export interface DraftState {
83 /** Write-only: empty keeps the secret already stored on the server. */
84 readonly signatureSecret: string;
85 readonly maxDeliveryAgeMinutes: string;
86 + readonly filters: ReadonlyArray<WebhookFilterDraft>;
87 + /** The filter rows the form opened with. */
88 + readonly savedFilters: ReadonlyArray<WebhookFilterDraft>;
89 }
90
91 export const WEBHOOK_SIGNATURE_DEFAULTS = {
@@ -89,6 +98,8 @@ export function scheduleFromDraft(draft: DraftState): ScheduledTaskUpsertSchedul
98 if (draft.scheduleMode === "webhook") {
99 const maxDeliveryAgeMinutes = parseMaxDeliveryAge(draft.maxDeliveryAgeMinutes);
100 if (maxDeliveryAgeMinutes === undefined) return null;
101 + const parsedFilters = parseWebhookFilterDrafts(draft.filters);
102 + if (!("filters" in parsedFilters)) return null;
103 const secret = draft.signatureSecret.trim();
104 return {
105 type: "webhook",
@@ -101,6 +112,10 @@ export function scheduleFromDraft(draft: DraftState): ScheduledTaskUpsertSchedul
112 }
113 : null,
114 maxDeliveryAgeMinutes,
115 + // Only edited filters are sent; the server keeps the stored ones otherwise.
116 + ...(webhookFilterDraftsChanged(draft.savedFilters, draft.filters)
117 + ? { filters: parsedFilters.filters }
118 + : {}),
119 };
120 }
121 if (draft.scheduleMode === "interval") {
@@ -117,6 +132,7 @@ export function scheduleFromDraft(draft: DraftState): ScheduledTaskUpsertSchedul
132
133 export function taskToDraft(task: ScheduledTask): DraftState {
134 const schedule = task.schedule;
135 + const filters = webhookFilterDrafts(schedule.type === "webhook" ? schedule.filters : undefined);
136 const weekdays =
137 schedule.type === "fixed_time" && schedule.weekdays && schedule.weekdays.length > 0
138 ? new Set(schedule.weekdays)
@@ -161,6 +177,8 @@ export function taskToDraft(task: ScheduledTask): DraftState {
177 schedule.type === "webhook" && schedule.maxDeliveryAgeMinutes != null
178 ? String(schedule.maxDeliveryAgeMinutes)
179 : "",
180 + filters,
181 + savedFilters: filters,
182 };
183 }
184
docs/user/project-settings.md
+9
@@ -109,6 +109,15 @@ same secret in the repository's webhook settings with content type
109 up on desktop or web; mobile keeps an existing signature check but can't turn
110 one on.
111
112 +To run only for some requests, add **Filters**. Each one tests a value named
113 +like a placeholder, without the braces, such as `headers.x-github-event` equals
114 +`pull_request` or `body.action` is one of `opened, reopened`. A task runs only
115 +when every filter matches; other requests are answered normally, logged as
116 +**Filtered** with the first filter that failed, and start nothing. Values
117 +compare as text, and a value that is an object or a list only passes
118 +**exists**. Separate **is one of** values with commas; a value can't contain
119 +a comma or start or end with a space.
120 +
121 On desktop and web, pick **Deliveries** from a task's menu to see recent
122 requests and the prompt each one produced.
123
packages/client-runtime/src/scheduledTaskWebhook.test.ts
+62 -1
@@ -1,6 +1,13 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import { parseMaxDeliveryAge } from "./scheduledTaskWebhook.ts";
3 +import {
4 + parseMaxDeliveryAge,
5 + emptyWebhookFilterDraft,
6 + parseWebhookFilterDrafts,
7 + removeWebhookFilterDraft,
8 + webhookFilterDrafts,
9 + webhookFilterDraftsChanged,
10 +} from "./scheduledTaskWebhook.ts";
11
12 describe("parseMaxDeliveryAge", () => {
13 it("treats blank as no limit and rejects values the server would not accept", () => {
@@ -11,3 +18,57 @@ describe("parseMaxDeliveryAge", () => {
18 }
19 });
20 });
21 +
22 +describe("webhook filter drafts", () => {
23 + it("round-trips saved filters through the form rows", () => {
24 + const filters = [
25 + { path: "headers.x-github-event", op: "equals", value: "pull_request" },
26 + { path: "body.action", op: "in", value: ["opened", "reopened"] },
27 + { path: "body.label.name", op: "in", value: ["needs review", "a-b"] },
28 + { path: "query.source", op: "exists" },
29 + ] as const;
30 + const drafts = webhookFilterDrafts(filters);
31 + expect(drafts[1]).toMatchObject({ path: "body.action", op: "in", value: "opened, reopened" });
32 + expect(parseWebhookFilterDrafts(drafts)).toEqual({ filters });
33 + });
34 +
35 + it("names the first row the server would refuse", () => {
36 + expect(
37 + parseWebhookFilterDrafts([
38 + { id: "f1", path: "body.action", op: "equals", value: "opened" },
39 + { id: "f2", path: "body.action", op: "in", value: " , " },
40 + { id: "f3", path: "", op: "exists", value: "" },
41 + ]),
42 + ).toEqual({
43 + error: "Filter 2 needs a path under body, headers or query, and at least one value.",
44 + });
45 + expect(parseWebhookFilterDrafts([{ id: "f1", path: " ", op: "exists", value: "" }])).toEqual({
46 + error: "Filter 1 needs a path under body, headers or query.",
47 + });
48 + const seventeen = Array.from({ length: 17 }, (_, index) => ({
49 + id: `f${index}`,
50 + path: "body.action",
51 + op: "exists" as const,
52 + value: "",
53 + }));
54 + expect(parseWebhookFilterDrafts(seventeen)).toEqual({ error: "Use at most 16 filters." });
55 + });
56 +
57 + it("notices added, removed and edited rows but not an untouched list", () => {
58 + const saved = webhookFilterDrafts([{ path: "body.action", op: "equals", value: "opened" }]);
59 + expect(webhookFilterDraftsChanged(saved, [...saved])).toBe(false);
60 + expect(webhookFilterDraftsChanged(saved, [])).toBe(true);
61 + expect(webhookFilterDraftsChanged(saved, [{ ...saved[0]!, value: "closed" }])).toBe(true);
62 + expect(webhookFilterDraftsChanged([], [])).toBe(false);
63 + });
64 +
65 + it("removing the first row keeps the second row's id", () => {
66 + const drafts = [
67 + ...webhookFilterDrafts([{ path: "body.action", op: "equals", value: "opened" }]),
68 + emptyWebhookFilterDraft(),
69 + ];
70 + expect(new Set(drafts.map((draft) => draft.id)).size).toBe(2);
71 + const remaining = removeWebhookFilterDraft(drafts, drafts[0]!.id);
72 + expect(remaining.map((draft) => draft.id)).toEqual([drafts[1]!.id]);
73 + });
74 +});
packages/client-runtime/src/scheduledTaskWebhook.ts
+123 -1
@@ -1,4 +1,11 @@
1 -import { MAX_WEBHOOK_DELIVERY_AGE_MINUTES } from "@t3tools/contracts";
1 +import {
2 + MAX_WEBHOOK_DELIVERY_AGE_MINUTES,
3 + MAX_WEBHOOK_FILTERS,
4 + ScheduledTaskWebhookFilter,
5 + type ScheduledTaskWebhookFilterOp,
6 +} from "@t3tools/contracts";
7 +import * as Option from "effect/Option";
8 +import * as Schema from "effect/Schema";
9
10 export const DEFAULT_WEBHOOK_PROMPT = "Handle this webhook:\n{{body}}";
11
@@ -10,3 +17,118 @@ export function parseMaxDeliveryAge(value: string): number | null | undefined {
17 ? minutes
18 : undefined;
19 }
20 +
21 +/**
22 + * One editable filter row. `in` takes a comma-separated list, which is
23 + * lossless because list values can't contain commas; `exists` ignores the value.
24 + */
25 +export interface WebhookFilterDraft {
26 + /** Stable row identity for the form; never sent to the server. */
27 + readonly id: string;
28 + readonly path: string;
29 + readonly op: ScheduledTaskWebhookFilterOp;
30 + readonly value: string;
31 +}
32 +
33 +export const WEBHOOK_FILTER_OPS: ReadonlyArray<{
34 + readonly op: ScheduledTaskWebhookFilterOp;
35 + readonly label: string;
36 +}> = [
37 + { op: "equals", label: "equals" },
38 + { op: "notEquals", label: "does not equal" },
39 + { op: "in", label: "is one of" },
40 + { op: "startsWith", label: "starts with" },
41 + { op: "exists", label: "exists" },
42 +];
43 +
44 +let lastWebhookFilterDraftId = 0;
45 +const nextWebhookFilterDraftId = () => `filter-${++lastWebhookFilterDraftId}`;
46 +
47 +export function emptyWebhookFilterDraft(): WebhookFilterDraft {
48 + return { id: nextWebhookFilterDraftId(), path: "", op: "equals", value: "" };
49 +}
50 +
51 +/** By id, so a removed row's identity never passes to the row after it. */
52 +export function removeWebhookFilterDraft(
53 + drafts: ReadonlyArray<WebhookFilterDraft>,
54 + id: string,
55 +): ReadonlyArray<WebhookFilterDraft> {
56 + return drafts.filter((draft) => draft.id !== id);
57 +}
58 +
59 +export function webhookFilterDrafts(
60 + filters: ReadonlyArray<ScheduledTaskWebhookFilter> | undefined,
61 +): ReadonlyArray<WebhookFilterDraft> {
62 + return (filters ?? []).map((filter) => ({
63 + id: nextWebhookFilterDraftId(),
64 + path: filter.path,
65 + op: filter.op,
66 + value:
67 + filter.op === "exists" ? "" : filter.op === "in" ? filter.value.join(", ") : filter.value,
68 + }));
69 +}
70 +
71 +const decodeFilter = Schema.decodeUnknownOption(ScheduledTaskWebhookFilter);
72 +
73 +/**
74 + * Checks each row with the server's own schema, so a draft that parses here
75 + * also saves. The error names the first row that would not.
76 + */
77 +export function parseWebhookFilterDrafts(
78 + drafts: ReadonlyArray<WebhookFilterDraft>,
79 +): { readonly filters: ReadonlyArray<ScheduledTaskWebhookFilter> } | { readonly error: string } {
80 + if (drafts.length > MAX_WEBHOOK_FILTERS) {
81 + return { error: `Use at most ${MAX_WEBHOOK_FILTERS} filters.` };
82 + }
83 + const filters: ScheduledTaskWebhookFilter[] = [];
84 + for (const [index, draft] of drafts.entries()) {
85 + const path = draft.path.trim();
86 + const filter = decodeFilter(
87 + draft.op === "exists"
88 + ? { path, op: draft.op }
89 + : draft.op === "in"
90 + ? {
91 + path,
92 + op: draft.op,
93 + value: draft.value
94 + .split(",")
95 + .map((item) => item.trim())
96 + .filter((item) => item !== ""),
97 + }
98 + : { path, op: draft.op, value: draft.value },
99 + );
100 + if (Option.isNone(filter)) {
101 + return {
102 + error: `Filter ${index + 1} needs a path under body, headers or query${
103 + draft.op === "exists"
104 + ? "."
105 + : draft.op === "in"
106 + ? ", and at least one value."
107 + : ", and a value."
108 + }`,
109 + };
110 + }
111 + filters.push(filter.value);
112 + }
113 + return { filters };
114 +}
115 +
116 +/**
117 + * Whether a form's filter rows differ from the ones it opened with. A save
118 + * leaves `filters` out unless they did, so editing only the title can't
119 + * overwrite filters another device changed in the meantime.
120 + */
121 +export function webhookFilterDraftsChanged(
122 + saved: ReadonlyArray<WebhookFilterDraft>,
123 + current: ReadonlyArray<WebhookFilterDraft>,
124 +): boolean {
125 + return (
126 + saved.length !== current.length ||
127 + saved.some(
128 + (filter, index) =>
129 + filter.path !== current[index]?.path ||
130 + filter.op !== current[index]?.op ||
131 + (filter.op !== "exists" && filter.value !== current[index]?.value),
132 + )
133 + );
134 +}
packages/contracts/src/scheduledTask.test.ts
+70
@@ -3,6 +3,7 @@ import * as Schema from "effect/Schema";
3
4 import {
5 MIN_SCHEDULED_TASK_INTERVAL_MS,
6 + ScheduledTaskListWebhookDeliveriesResult,
7 ScheduledTaskSchedule,
8 ScheduledTaskUpsertSchedule,
9 } from "./scheduledTask.ts";
@@ -50,3 +51,72 @@ describe("ScheduledTaskUpsertSchedule", () => {
51 ).toThrow();
52 });
53 });
54 +
55 +describe("webhook filters", () => {
56 + const accepts = (filters: unknown) => {
57 + try {
58 + decodeUpsertSchedule({ type: "webhook", filters });
59 + return true;
60 + } catch {
61 + return false;
62 + }
63 + };
64 +
65 + it("keeps valid filters", () => {
66 + const filters = [
67 + { path: "headers.x-github-event", op: "equals", value: "pull_request" },
68 + { path: "body.action", op: "in", value: ["opened", "labeled"] },
69 + { path: "body.label.name", op: "startsWith", value: "agent:" },
70 + { path: "query.source", op: "exists" },
71 + ];
72 + expect(decodeUpsertSchedule({ type: "webhook", filters })).toEqual({
73 + type: "webhook",
74 + filters,
75 + });
76 + expect(decodeSchedule({ type: "webhook", signature: null, filters })).toMatchObject({
77 + filters,
78 + });
79 + });
80 +
81 + it("rejects empty or unknown paths, unknown ops, and values that do not fit the op", () => {
82 + expect(accepts([{ path: "", op: "exists" }])).toBe(false);
83 + expect(accepts([{ path: " ", op: "exists" }])).toBe(false);
84 + expect(accepts([{ path: "request", op: "exists" }])).toBe(false);
85 + expect(accepts([{ path: "header.x-github-event", op: "exists" }])).toBe(false);
86 + expect(accepts([{ path: "body.action", op: "in", value: "opened" }])).toBe(false);
87 + expect(accepts([{ path: "body.action", op: "in", value: [] }])).toBe(false);
88 + for (const value of ["", " opened", "opened ", "a,b"]) {
89 + expect(accepts([{ path: "body.action", op: "in", value: [value] }])).toBe(false);
90 + }
91 + expect(accepts([{ path: "body.label.name", op: "in", value: ["needs review"] }])).toBe(true);
92 + expect(accepts([{ path: "body.action", op: "equals" }])).toBe(false);
93 + expect(accepts([{ path: "body.action", op: "matches", value: "^opened$" }])).toBe(false);
94 + });
95 +
96 + it("allows at most 16 filters", () => {
97 + const sixteen = Array.from({ length: 16 }, () => ({ path: "body.action", op: "exists" }));
98 + expect(accepts(sixteen)).toBe(true);
99 + expect(accepts([...sixteen, { path: "body.action", op: "exists" }])).toBe(false);
100 + });
101 +});
102 +
103 +describe("ScheduledTaskWebhookDeliverySummary", () => {
104 + it("decodes an outcome this client does not know yet", () => {
105 + const summary = {
106 + id: "delivery:1",
107 + taskId: "scheduled-task:1",
108 + receivedAt: "2026-10-20T00:00:00.000Z",
109 + method: "POST",
110 + contentType: null,
111 + bodyBytes: 0,
112 + outcome: "some_future_outcome",
113 + signatureVerified: false,
114 + missingFields: [],
115 + error: null,
116 + };
117 + expect(
118 + Schema.decodeUnknownSync(ScheduledTaskListWebhookDeliveriesResult)({ deliveries: [summary] })
119 + .deliveries[0]?.outcome,
120 + ).toBe("some_future_outcome");
121 + });
122 +});
packages/contracts/src/scheduledTask.ts
+54 -1
@@ -83,12 +83,56 @@ const WebhookMaxDeliveryAgeMinutes = Schema.Int.check(
83 "Skip requests the relay held longer than this many minutes while the environment was offline. Null runs every request.",
84 });
85
86 +export const MAX_WEBHOOK_FILTERS = 16;
87 +
88 +const WebhookFilterPath = TrimmedNonEmptyString.check(
89 + Schema.isPattern(/^(body|headers|query)(\.|$)/),
90 +).annotate({
91 + description:
92 + "Request value to test, in placeholder syntax without braces: headers.x-github-event, body.action, query.source.",
93 +});
94 +
95 +/**
96 + * Forms edit an `in` list as comma-separated text, so a value that has no
97 + * comma and no surrounding whitespace survives that round trip unchanged.
98 + */
99 +const WebhookFilterListValue = Schema.String.check(
100 + Schema.isPattern(/^[^,\s](?:[^,]*[^,\s])?$/),
101 +).annotate({ description: "Non-empty, without commas or surrounding whitespace." });
102 +
103 +export const ScheduledTaskWebhookFilter = Schema.Union([
104 + Schema.Struct({
105 + path: WebhookFilterPath,
106 + op: Schema.Literals(["equals", "notEquals", "startsWith"]),
107 + value: Schema.String,
108 + }),
109 + Schema.Struct({
110 + path: WebhookFilterPath,
111 + op: Schema.Literal("in"),
112 + value: Schema.Array(WebhookFilterListValue).check(Schema.isMinLength(1)),
113 + }),
114 + Schema.Struct({ path: WebhookFilterPath, op: Schema.Literal("exists") }),
115 +]).annotate({
116 + description:
117 + "Scalars compare as strings; objects and arrays only satisfy 'exists'. Every op but 'exists' fails when the path is missing.",
118 +});
119 +export type ScheduledTaskWebhookFilter = typeof ScheduledTaskWebhookFilter.Type;
120 +export type ScheduledTaskWebhookFilterOp = ScheduledTaskWebhookFilter["op"];
121 +
122 +const ScheduledTaskWebhookFilters = Schema.Array(ScheduledTaskWebhookFilter)
123 + .check(Schema.isMaxLength(MAX_WEBHOOK_FILTERS))
124 + .annotate({
125 + description:
126 + "Run only when every filter matches the request; other requests are logged as filtered. Up to 16. Omit to keep the stored filters; pass [] to clear them.",
127 + });
128 +
129 const ScheduledTaskWebhookSchedule = Schema.Struct({
130 type: Schema.Literal("webhook").annotate({
131 description: "Run when the task's webhook URL receives a request.",
132 }),
133 signature: Schema.NullOr(ScheduledTaskWebhookSignature),
134 maxDeliveryAgeMinutes: Schema.optional(Schema.NullOr(WebhookMaxDeliveryAgeMinutes)),
135 + filters: Schema.optional(ScheduledTaskWebhookFilters),
136 }).annotate({
137 description:
138 "Run on each request to the task's webhook URL. The prompt may use {{body.path}}, {{headers.name}}, {{query.name}}, {{body}} and {{request}} placeholders.",
@@ -115,6 +159,7 @@ const ScheduledTaskUpsertWebhookSchedule = Schema.Struct({
159 description: "Signature check; omit or null to accept requests by URL token only.",
160 }),
161 maxDeliveryAgeMinutes: Schema.optional(Schema.NullOr(WebhookMaxDeliveryAgeMinutes)),
162 + filters: Schema.optional(ScheduledTaskWebhookFilters),
163 }).annotate({
164 description:
165 "Run on each request to the task's webhook URL. The prompt may use {{body.path}}, {{headers.name}}, {{query.name}}, {{body}} and {{request}} placeholders.",
@@ -253,6 +298,7 @@ export const ScheduledTaskWebhookDeliveryOutcome = Schema.Literals([
298 "disabled",
299 "rate_limited",
300 "expired",
301 + "filtered",
302 ]);
303 export type ScheduledTaskWebhookDeliveryOutcome = typeof ScheduledTaskWebhookDeliveryOutcome.Type;
304
@@ -263,7 +309,8 @@ export const ScheduledTaskWebhookDeliverySummary = Schema.Struct({
309 method: TrimmedNonEmptyString,
310 contentType: Schema.NullOr(Schema.String),
311 bodyBytes: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
266 - outcome: ScheduledTaskWebhookDeliveryOutcome,
312 + // Any string, so an outcome added later doesn't break a client's whole list.
313 + outcome: Schema.Union([ScheduledTaskWebhookDeliveryOutcome, Schema.String]),
314 signatureVerified: Schema.Boolean,
315 missingFields: Schema.Array(Schema.String),
316 error: Schema.NullOr(Schema.String),
@@ -282,6 +329,12 @@ export type ScheduledTaskWebhookDelivery = typeof ScheduledTaskWebhookDelivery.T
329
330 export const ScheduledTaskListWebhookDeliveriesInput = Schema.Struct({
331 id: ScheduledTaskId,
332 + /**
333 + * Sent by clients that decode any outcome. Shipped clients decode a closed
334 + * list and fail on the whole response, so without it the server leaves out
335 + * rows with outcomes they don't know.
336 + */
337 + acceptAnyOutcome: Schema.optional(Schema.Boolean),
338 });
339 export type ScheduledTaskListWebhookDeliveriesInput =
340 typeof ScheduledTaskListWebhookDeliveriesInput.Type;