Skip to content

Commit 832d29c

Browse files
feat(scheduled-tasks): event filters for webhook deliveries
Webhook tasks take optional filters ({ path, op, value? }) that every request must match before a run starts. Filters reuse the placeholder resolver, run after the signature and age checks, and a request that fails one is answered 202, logged as filtered with the failing filter, and never counts as a run. Web and mobile settings forms edit them; the MCP schedule tools accept them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent effb433 commit 832d29c

18 files changed

Lines changed: 774 additions & 15 deletions

‎apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import type {
1313
} from "@t3tools/contracts";
1414
import {
1515
MAX_WEBHOOK_DELIVERY_AGE_MINUTES,
16+
MAX_WEBHOOK_FILTERS,
1617
resolveEnvironmentMachineKind,
1718
} from "@t3tools/contracts";
1819
import type { MenuAction } from "@react-native-menu/menu";
@@ -24,7 +25,11 @@ import {
2425
} from "@t3tools/client-runtime/state/runtime";
2526
import {
2627
DEFAULT_WEBHOOK_PROMPT,
28+
EMPTY_WEBHOOK_FILTER_DRAFT,
2729
parseMaxDeliveryAge,
30+
parseWebhookFilterDrafts,
31+
WEBHOOK_FILTER_OPS,
32+
type WebhookFilterDraft,
2833
} from "@t3tools/client-runtime/scheduled-task-webhook";
2934
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
3035
import { useFocusEffect, useNavigation, usePreventRemove } from "@react-navigation/native";
@@ -222,6 +227,85 @@ function SelectRow(props: {
222227
);
223228
}
224229

230+
function WebhookFilterRows(props: {
231+
readonly filters: ReadonlyArray<WebhookFilterDraft>;
232+
readonly disabled: boolean;
233+
readonly onChange: (filters: ReadonlyArray<WebhookFilterDraft>) => void;
234+
}) {
235+
const update = (index: number, patch: Partial<WebhookFilterDraft>) =>
236+
props.onChange(
237+
props.filters.map((filter, at) => (at === index ? { ...filter, ...patch } : filter)),
238+
);
239+
return (
240+
<>
241+
{props.filters.map((filter, index) => (
242+
// Rows have no identity of their own; removing one re-renders the rest in order.
243+
// oxlint-disable-next-line react/no-array-index-key
244+
<View key={index}>
245+
<View className="flex-row items-center gap-3 border-t border-border-subtle px-4 pt-3">
246+
<Text className="min-w-0 flex-1 text-sm text-foreground-muted">Filter {index + 1}</Text>
247+
<Pressable
248+
accessibilityRole="button"
249+
accessibilityLabel={`Remove filter ${index + 1}`}
250+
disabled={props.disabled}
251+
hitSlop={8}
252+
onPress={() => props.onChange(props.filters.filter((_, at) => at !== index))}
253+
className="active:opacity-70"
254+
>
255+
<SymbolView name="trash" size={16} tintColorClassName="accent-danger-foreground" />
256+
</Pressable>
257+
</View>
258+
<FormField
259+
label="Path"
260+
value={filter.path}
261+
placeholder="body.action"
262+
disabled={props.disabled}
263+
onChange={(path) => update(index, { path })}
264+
/>
265+
<SelectRow
266+
label="Test"
267+
value={WEBHOOK_FILTER_OPS.find((option) => option.op === filter.op)?.label ?? ""}
268+
actions={WEBHOOK_FILTER_OPS.map((option) => ({
269+
id: option.op,
270+
title: option.label,
271+
state: option.op === filter.op ? ("on" as const) : undefined,
272+
}))}
273+
onSelect={(id) => {
274+
const known = WEBHOOK_FILTER_OPS.find((option) => option.op === id);
275+
if (known) update(index, { op: known.op });
276+
}}
277+
/>
278+
{filter.op === "exists" ? null : (
279+
<FormField
280+
label={filter.op === "in" ? "Values, comma-separated" : "Value"}
281+
value={filter.value}
282+
placeholder={filter.op === "in" ? "opened, reopened" : "opened"}
283+
disabled={props.disabled}
284+
onChange={(value) => update(index, { value })}
285+
/>
286+
)}
287+
</View>
288+
))}
289+
{props.filters.length < MAX_WEBHOOK_FILTERS ? (
290+
<Pressable
291+
accessibilityRole="button"
292+
disabled={props.disabled}
293+
onPress={() => props.onChange([...props.filters, EMPTY_WEBHOOK_FILTER_DRAFT])}
294+
className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70"
295+
>
296+
<Text className="min-w-0 flex-1 text-lg text-foreground">Add filter</Text>
297+
<SymbolView name="plus" size={16} tintColorClassName="accent-icon" />
298+
</Pressable>
299+
) : null}
300+
{props.filters.length > 0 ? (
301+
<Text className="px-4 pb-3 text-sm text-foreground-muted">
302+
Runs only when every filter matches. Other requests are logged as filtered.
303+
</Text>
304+
) : null}
305+
</>
306+
);
307+
}
308+
225309
function PickerRow(props: {
226310
readonly label: string;
227311
readonly value: string;
@@ -627,6 +711,14 @@ function TaskForm({
627711
);
628712
return;
629713
}
714+
const parsedFilters = parseWebhookFilterDrafts(draft.schedule.filters);
715+
if (draft.schedule.mode === "webhook" && "invalidIndex" in parsedFilters) {
716+
Dialog.alert(
717+
"Invalid filter",
718+
`Filter ${parsedFilters.invalidIndex + 1} needs a path under body, headers or query, and a value its test accepts.`,
719+
);
720+
return;
721+
}
630722
if (
631723
!draft.title.trim() ||
632724
!draft.prompt.trim() ||
@@ -964,6 +1056,13 @@ function TaskForm({
9641056
setDraft({ ...draft, schedule: { ...draft.schedule, maxDeliveryAgeMinutes } })
9651057
}
9661058
/>
1059+
<WebhookFilterRows
1060+
filters={draft.schedule.filters}
1061+
disabled={saving}
1062+
onChange={(filters) =>
1063+
setDraft({ ...draft, schedule: { ...draft.schedule, filters } })
1064+
}
1065+
/>
9671066
</>
9681067
) : (
9691068
<>

‎apps/mobile/src/features/settings/scheduledTaskDraft.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,18 @@ describe("scheduleDraftForTask", () => {
6565
expect(saved).toEqual({ type: "webhook", signature, maxDeliveryAgeMinutes: null });
6666
expect(saved?.type === "webhook" && saved.signature && "secret" in saved.signature).toBe(false);
6767
});
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: "matches", value: "^agent:" },
73+
] as const;
74+
const draft = scheduleDraftForTask({ schedule: { type: "webhook", signature: null, filters } });
75+
expect(scheduleFromDraft(draft)).toMatchObject({ filters });
76+
expect(
77+
scheduleFromDraft({ ...draft, filters: [{ path: "", op: "exists", value: "" }] }),
78+
).toBeNull();
79+
});
6880
});
6981

7082
describe("hasScheduledTaskDraftChanges", () => {

‎apps/mobile/src/features/settings/scheduledTaskDraft.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,12 @@ import type {
99
} from "@t3tools/contracts";
1010

1111
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+
type WebhookFilterDraft,
17+
} from "@t3tools/client-runtime/scheduled-task-webhook";
1318
import {
1419
resolveProjectSettings,
1520
type LegacyProjectSettingsFields,
@@ -50,6 +55,7 @@ export type ScheduleDraft = {
5055
readonly intervalMinutes: string;
5156
readonly signature: ScheduledTaskWebhookSignature | null;
5257
readonly maxDeliveryAgeMinutes: string;
58+
readonly filters: ReadonlyArray<WebhookFilterDraft>;
5359
};
5460

5561
export const DEFAULT_SCHEDULE: ScheduleDraft = {
@@ -59,6 +65,7 @@ export const DEFAULT_SCHEDULE: ScheduleDraft = {
5965
intervalMinutes: "15",
6066
signature: null,
6167
maxDeliveryAgeMinutes: "",
68+
filters: [],
6269
};
6370

6471
export function scheduleDraftForTask(task: Pick<ScheduledTask, "schedule">): ScheduleDraft {
@@ -86,6 +93,7 @@ export function scheduleDraftForTask(task: Pick<ScheduledTask, "schedule">): Sch
8693
task.schedule.maxDeliveryAgeMinutes == null
8794
? ""
8895
: String(task.schedule.maxDeliveryAgeMinutes),
96+
filters: webhookFilterDrafts(task.schedule.filters),
8997
};
9098
}
9199
}
@@ -94,6 +102,8 @@ export function scheduleFromDraft(draft: ScheduleDraft): ScheduledTaskUpsertSche
94102
if (draft.mode === "webhook") {
95103
const maxDeliveryAgeMinutes = parseMaxDeliveryAge(draft.maxDeliveryAgeMinutes);
96104
if (maxDeliveryAgeMinutes === undefined) return null;
105+
const parsedFilters = parseWebhookFilterDrafts(draft.filters);
106+
if (!("filters" in parsedFilters)) return null;
97107
// No secret is sent, so the server keeps the stored one.
98108
return {
99109
type: "webhook",
@@ -106,6 +116,7 @@ export function scheduleFromDraft(draft: ScheduleDraft): ScheduledTaskUpsertSche
106116
prefix: draft.signature.prefix,
107117
},
108118
maxDeliveryAgeMinutes,
119+
...(parsedFilters.filters.length > 0 ? { filters: parsedFilters.filters } : {}),
109120
};
110121
}
111122
if (draft.mode === "interval") {
@@ -160,6 +171,7 @@ function draftSignature(draft: ScheduledTaskDraft): string {
160171
[...draft.schedule.weekdays].sort((a, b) => a - b),
161172
draft.schedule.intervalMinutes,
162173
draft.schedule.maxDeliveryAgeMinutes,
174+
draft.schedule.filters,
163175
draft.workspace,
164176
draft.baseRef,
165177
draft.checkoutPath,

‎apps/server/src/mcp/toolkits/orchestrator/tools.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ const WorkflowStopTool = Tool.make("t3_workflow_stop", {
116116

117117
export const ScheduleTaskTool = Tool.make("schedule_task", {
118118
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, matches (regex) 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.",
120120
parameters: OrchestratorMcpScheduleTaskInput,
121121
success: OrchestratorMcpScheduleTaskResult,
122122
failure: OrchestratorMcpFailure,
@@ -143,7 +143,7 @@ const ListScheduledTasksTool = Tool.make("list_scheduled_tasks", {
143143

144144
const UpdateScheduledTaskTool = Tool.make("update_scheduled_task", {
145145
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 schedule replaces the whole trigger, so to change a webhook's filters pass its full schedule with the new filters.",
147147
parameters: OrchestratorMcpUpdateScheduledTaskInput,
148148
success: OrchestratorMcpScheduleTaskResult,
149149
failure: OrchestratorMcpFailure,

‎apps/server/src/scheduledTasks/ScheduledTaskService.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ import {
5353
renderWebhookPrompt,
5454
type WebhookRequest,
5555
} from "./webhookTemplate.ts";
56+
import { describeFailedWebhookFilter, findFailedWebhookFilter } from "./webhookFilter.ts";
5657
import { constantTimeEquals, verifyWebhookSignature } from "./webhookVerification.ts";
5758

5859
export const WEBHOOK_ROUTE_PREFIX = "/api/hooks";
@@ -114,14 +115,15 @@ export type WebhookDeliveryOutcome =
114115
| "disabled"
115116
| "rejected_signature"
116117
| "expired"
118+
| "filtered"
117119
| "not_found"
118120
| "error";
119121

120122
export type WebhookTriggerResult =
121123
| {
122124
readonly _tag: "accepted";
123125
readonly deliveryId: ScheduledTaskWebhookDeliveryId;
124-
readonly outcome: "accepted" | "duplicate" | "prompt_too_long";
126+
readonly outcome: "accepted" | "duplicate" | "prompt_too_long" | "filtered";
125127
}
126128
| { readonly _tag: "not_found" }
127129
| { readonly _tag: "rejected_signature" }
@@ -995,6 +997,7 @@ export const layer = Layer.effect(
995997
prefix: input.schedule.signature.prefix,
996998
},
997999
maxDeliveryAgeMinutes: input.schedule.maxDeliveryAgeMinutes ?? null,
1000+
...(input.schedule.filters?.length ? { filters: input.schedule.filters } : {}),
9981001
}
9991002
: input.schedule;
10001003
const webhook =
@@ -1560,6 +1563,18 @@ export const layer = Layer.effect(
15601563
return { _tag: "expired" as const };
15611564
}
15621565

1566+
// Filters: a request the task does not care about is accepted, so
1567+
// the sender does not retry it, and logged without starting a run.
1568+
const failedFilter = findFailedWebhookFilter(schedule.filters ?? [], request);
1569+
if (failedFilter !== null) {
1570+
yield* log("filtered", {
1571+
signatureVerified: signature !== null,
1572+
error: describeFailedWebhookFilter(failedFilter),
1573+
});
1574+
yield* observe("filtered");
1575+
return { _tag: "accepted" as const, deliveryId, outcome: "filtered" as const };
1576+
}
1577+
15631578
const frameId = yield* crypto.randomBytes(6).pipe(
15641579
Effect.map((bytes) => Buffer.from(bytes).toString("hex")),
15651580
Effect.mapError((cause) => taskError("Could not generate frame id.", { cause })),

‎apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -953,3 +953,80 @@ it.effect("counts each handled request by what happened to it", () =>
953953
}),
954954
),
955955
);
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({ id: task.id })).deliveries;
1023+
const filtered = deliveries
1024+
.filter((entry) => entry.outcome === "filtered")
1025+
.map((entry) => [entry.signatureVerified, entry.error]);
1026+
assert.sameDeepMembers(filtered, [
1027+
[true, "Filter 1 (headers.x-github-event) did not match."],
1028+
[true, "Filter 2 (body.action) did not match."],
1029+
]);
1030+
}),
1031+
),
1032+
);

0 commit comments

Comments
 (0)