TypeScript
feat(scheduled-tasks): event filters for webhook deliveries (#22194)
Julius Marminge0c85b0d9977f
diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsxindex 8913502da91..aadc124ba4a 100644--- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx@@ -13,6 +13,7 @@ import type {} from "@t3tools/contracts";import {MAX_WEBHOOK_DELIVERY_AGE_MINUTES,+ MAX_WEBHOOK_FILTERS,resolveEnvironmentMachineKind,} from "@t3tools/contracts";import type { MenuAction } from "@react-native-menu/menu";@@ -24,7 +25,12 @@ import {} from "@t3tools/client-runtime/state/runtime";import {DEFAULT_WEBHOOK_PROMPT,+ emptyWebhookFilterDraft,parseMaxDeliveryAge,+ parseWebhookFilterDrafts,+ removeWebhookFilterDraft,+ WEBHOOK_FILTER_OPS,+ type WebhookFilterDraft,} from "@t3tools/client-runtime/scheduled-task-webhook";import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";import { useFocusEffect, useNavigation, usePreventRemove } from "@react-navigation/native";@@ -222,6 +228,84 @@ function SelectRow(props: {);}+function WebhookFilterRows(props: {+ readonly filters: ReadonlyArray<WebhookFilterDraft>;+ readonly disabled: boolean;+ readonly onChange: (filters: ReadonlyArray<WebhookFilterDraft>) => void;+}) {+ const update = (index: number, patch: Partial<WebhookFilterDraft>) =>+ props.onChange(+ props.filters.map((filter, at) => (at === index ? { ...filter, ...patch } : filter)),+ );+ return (+ <>+ {props.filters.map((filter, index) => (+ <View key={filter.id}>+ <View className="flex-row items-center gap-3 border-t border-border-subtle px-4 pt-3">+ <Text className="min-w-0 flex-1 text-sm text-foreground-muted">Filter {index + 1}</Text>+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={`Remove filter ${index + 1}`}+ disabled={props.disabled}+ hitSlop={8}+ onPress={() => props.onChange(removeWebhookFilterDraft(props.filters, filter.id))}+ className="active:opacity-70"+ >+ <SymbolView name="trash" size={16} tintColorClassName="accent-danger-foreground" />+ </Pressable>+ </View>+ <FormField+ label="Path"+ value={filter.path}+ placeholder="body.action"+ disabled={props.disabled}+ onChange={(path) => update(index, { path })}+ />+ <SelectRow+ label="Test"+ value={WEBHOOK_FILTER_OPS.find((option) => option.op === filter.op)?.label ?? ""}+ actions={WEBHOOK_FILTER_OPS.map((option) => ({+ id: option.op,+ title: option.label,+ state: option.op === filter.op ? ("on" as const) : undefined,+ }))}+ onSelect={(id) => {+ const known = WEBHOOK_FILTER_OPS.find((option) => option.op === id);+ if (known) update(index, { op: known.op });+ }}+ />+ {filter.op === "exists" ? null : (+ <FormField+ label={filter.op === "in" ? "Values, comma-separated" : "Value"}+ value={filter.value}+ placeholder={filter.op === "in" ? "opened, reopened" : "opened"}+ disabled={props.disabled}+ onChange={(value) => update(index, { value })}+ />+ )}+ </View>+ ))}+ {props.filters.length < MAX_WEBHOOK_FILTERS ? (+ <Pressable+ accessibilityRole="button"+ disabled={props.disabled}+ onPress={() => props.onChange([...props.filters, emptyWebhookFilterDraft()])}+ className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70"+ >+ <Text className="min-w-0 flex-1 text-lg text-foreground">Add filter</Text>+ <SymbolView name="plus" size={16} tintColorClassName="accent-icon" />+ </Pressable>+ ) : null}+ {props.filters.length > 0 ? (+ <Text className="px-4 pb-3 text-sm text-foreground-muted">+ Runs only when every filter matches. Other requests are logged as filtered. Separate “is+ one of” values with commas; a value can't contain a comma.+ </Text>+ ) : null}+ </>+ );+}+function PickerRow(props: {readonly label: string;readonly value: string;@@ -627,6 +711,11 @@ function TaskForm({);return;}+ const parsedFilters = parseWebhookFilterDrafts(draft.schedule.filters);+ if (draft.schedule.mode === "webhook" && "error" in parsedFilters) {+ Dialog.alert("Invalid filter", parsedFilters.error);+ return;+ }if (!draft.title.trim() ||!draft.prompt.trim() ||@@ -964,6 +1053,13 @@ function TaskForm({setDraft({ ...draft, schedule: { ...draft.schedule, maxDeliveryAgeMinutes } })}/>+ <WebhookFilterRows+ filters={draft.schedule.filters}+ disabled={saving}+ onChange={(filters) =>+ setDraft({ ...draft, schedule: { ...draft.schedule, filters } })+ }+ /></>) : (<>diff --git a/apps/mobile/src/features/settings/scheduledTaskDraft.test.ts b/apps/mobile/src/features/settings/scheduledTaskDraft.test.tsindex 69532b3fd26..bfe363cf065 100644--- a/apps/mobile/src/features/settings/scheduledTaskDraft.test.ts+++ b/apps/mobile/src/features/settings/scheduledTaskDraft.test.ts@@ -65,6 +65,23 @@ describe("scheduleDraftForTask", () => {expect(saved).toEqual({ type: "webhook", signature, maxDeliveryAgeMinutes: null });expect(saved?.type === "webhook" && saved.signature && "secret" in saved.signature).toBe(false);});++ it("round-trips webhook filters and refuses an invalid one", () => {+ const filters = [+ { path: "headers.x-github-event", op: "equals", value: "pull_request" },+ { path: "body.label.name", op: "in", value: ["needs review", "agent:fix"] },+ ] as const;+ const draft = scheduleDraftForTask({ schedule: { type: "webhook", signature: null, filters } });+ // Untouched rows are left out, so the server keeps whatever is stored now.+ expect(scheduleFromDraft(draft)).not.toHaveProperty("filters");+ expect(scheduleFromDraft({ ...draft, filters: [] })).toMatchObject({ filters: [] });+ expect(scheduleFromDraft({ ...draft, filters: draft.filters.slice(1) })).toMatchObject({+ filters: filters.slice(1),+ });+ expect(+ scheduleFromDraft({ ...draft, filters: [{ id: "f1", path: "", op: "exists", value: "" }] }),+ ).toBeNull();+ });});describe("hasScheduledTaskDraftChanges", () => {diff --git a/apps/mobile/src/features/settings/scheduledTaskDraft.ts b/apps/mobile/src/features/settings/scheduledTaskDraft.tsindex eff6674aacc..599fb4780e8 100644--- a/apps/mobile/src/features/settings/scheduledTaskDraft.ts+++ b/apps/mobile/src/features/settings/scheduledTaskDraft.ts@@ -9,7 +9,13 @@ import type {} from "@t3tools/contracts";import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";-import { parseMaxDeliveryAge } from "@t3tools/client-runtime/scheduled-task-webhook";+import {+ parseMaxDeliveryAge,+ parseWebhookFilterDrafts,+ webhookFilterDrafts,+ webhookFilterDraftsChanged,+ type WebhookFilterDraft,+} from "@t3tools/client-runtime/scheduled-task-webhook";import {resolveProjectSettings,type LegacyProjectSettingsFields,@@ -50,6 +56,9 @@ export type ScheduleDraft = {readonly intervalMinutes: string;readonly signature: ScheduledTaskWebhookSignature | null;readonly maxDeliveryAgeMinutes: string;+ readonly filters: ReadonlyArray<WebhookFilterDraft>;+ /** The filter rows the form opened with. */+ readonly savedFilters: ReadonlyArray<WebhookFilterDraft>;};export const DEFAULT_SCHEDULE: ScheduleDraft = {@@ -59,6 +68,8 @@ export const DEFAULT_SCHEDULE: ScheduleDraft = {intervalMinutes: "15",signature: null,maxDeliveryAgeMinutes: "",+ filters: [],+ savedFilters: [],};export function scheduleDraftForTask(task: Pick<ScheduledTask, "schedule">): ScheduleDraft {@@ -86,6 +97,8 @@ export function scheduleDraftForTask(task: Pick<ScheduledTask, "schedule">): Schtask.schedule.maxDeliveryAgeMinutes == null? "": String(task.schedule.maxDeliveryAgeMinutes),+ filters: webhookFilterDrafts(task.schedule.filters),+ savedFilters: webhookFilterDrafts(task.schedule.filters),};}}@@ -94,6 +107,8 @@ export function scheduleFromDraft(draft: ScheduleDraft): ScheduledTaskUpsertScheif (draft.mode === "webhook") {const maxDeliveryAgeMinutes = parseMaxDeliveryAge(draft.maxDeliveryAgeMinutes);if (maxDeliveryAgeMinutes === undefined) return null;+ const parsedFilters = parseWebhookFilterDrafts(draft.filters);+ if (!("filters" in parsedFilters)) return null;// No secret is sent, so the server keeps the stored one.return {type: "webhook",@@ -106,6 +121,10 @@ export function scheduleFromDraft(draft: ScheduleDraft): ScheduledTaskUpsertScheprefix: draft.signature.prefix,},maxDeliveryAgeMinutes,+ // Only edited filters are sent; the server keeps the stored ones otherwise.+ ...(webhookFilterDraftsChanged(draft.savedFilters, draft.filters)+ ? { filters: parsedFilters.filters }+ : {}),};}if (draft.mode === "interval") {@@ -160,6 +179,7 @@ function draftSignature(draft: ScheduledTaskDraft): string {[...draft.schedule.weekdays].sort((a, b) => a - b),draft.schedule.intervalMinutes,draft.schedule.maxDeliveryAgeMinutes,+ draft.schedule.filters.map(({ path, op, value }) => [path, op, value]),draft.workspace,draft.baseRef,draft.checkoutPath,diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.tsindex db291aac7b7..2e74482f690 100644--- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts+++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts@@ -116,7 +116,7 @@ const WorkflowStopTool = Tool.make("t3_workflow_stop", {export const ScheduleTaskTool = Tool.make("schedule_task", {description:- "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.",+ "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.",parameters: OrchestratorMcpScheduleTaskInput,success: OrchestratorMcpScheduleTaskResult,failure: OrchestratorMcpFailure,@@ -143,7 +143,7 @@ const ListScheduledTasksTool = Tool.make("list_scheduled_tasks", {const UpdateScheduledTaskTool = Tool.make("update_scheduled_task", {description:- "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.",+ "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.",parameters: OrchestratorMcpUpdateScheduledTaskInput,success: OrchestratorMcpScheduleTaskResult,failure: OrchestratorMcpFailure,diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.tsindex d9a96299404..89522077bae 100644--- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts@@ -15,6 +15,7 @@ import {type ScheduledTaskListWebhookDeliveriesResult,type ScheduledTaskRotateWebhookTokenInput,type ScheduledTaskWebhookDeliveryOutcome,+ type ScheduledTaskWebhookFilter,type ScheduledTaskListResult,type ScheduledTaskMutationResult,type ScheduledTaskRunNowInput,@@ -53,10 +54,27 @@ import {renderWebhookPrompt,type WebhookRequest,} from "./webhookTemplate.ts";+import { describeFailedWebhookFilter, findFailedWebhookFilter } from "./webhookFilter.ts";import { constantTimeEquals, verifyWebhookSignature } from "./webhookVerification.ts";export const WEBHOOK_ROUTE_PREFIX = "/api/hooks";const WEBHOOK_DELIVERY_RETENTION = 50;+/** Kept apart from the rest, so a stream of filtered requests can't evict real deliveries. */+const WEBHOOK_FILTERED_DELIVERY_RETENTION = 20;+/** The outcomes clients decoded before outcomes became open-ended. */+const LEGACY_DELIVERY_OUTCOMES: ReadonlySet<string> = new Set([+ "accepted",+ "dispatch_failed",+ "rejected_signature",+ "disabled",+ "rate_limited",+ "expired",+]);+/**+ * Filtered requests take no run slot, so this bounds the log writes they+ * cause instead; past it a filtered request is only counted in metrics.+ */+const WEBHOOK_FILTERED_LOG_PER_MINUTE = 10;const WEBHOOK_DELIVERY_LOG_BODY_LIMIT = 64 * 1024;const WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT = 64 * 1024;const WEBHOOK_MAX_QUEUED_PER_TASK = 20;@@ -114,6 +132,7 @@ export type WebhookDeliveryOutcome =| "disabled"| "rejected_signature"| "expired"+ | "filtered"| "not_found"| "error";@@ -121,7 +140,7 @@ export type WebhookTriggerResult =| {readonly _tag: "accepted";readonly deliveryId: ScheduledTaskWebhookDeliveryId;- readonly outcome: "accepted" | "duplicate" | "prompt_too_long";+ readonly outcome: "accepted" | "duplicate" | "prompt_too_long" | "filtered";}| { readonly _tag: "not_found" }| { readonly _tag: "rejected_signature" }@@ -132,6 +151,9 @@ export type WebhookTriggerResult =}| { readonly _tag: "expired" };+const webhookFilters = (filters: ReadonlyArray<ScheduledTaskWebhookFilter> | undefined) =>+ filters?.length ? { filters } : {};+const decodeTask = Schema.decodeUnknownEffect(ScheduledTask);const decodeTaskId = Schema.decodeUnknownOption(ScheduledTaskId);const decodeScheduleJson = Schema.decodeUnknownEffect(@@ -383,6 +405,9 @@ export const layer = Layer.effect(// finish late release their own count, never a recreated task's.const webhookQueued = yield* Ref.make<ReadonlyMap<string, number>>(new Map());const webhookRateWindows = yield* Ref.make<ReadonlyMap<ScheduledTaskId, RateWindow>>(new Map());+ const webhookFilteredLogWindows = yield* Ref.make<+ ReadonlyMap<ScheduledTaskId, ReadonlyArray<number>>+ >(new Map());const activeRuns = yield* Ref.make<ReadonlySet<ScheduledTaskId>>(new Set());// Sliding(1) coalesces the dirty-signal: every notification triggers a// full list() re-emit anyway, so a slow subscriber only ever needs the@@ -992,6 +1017,14 @@ export const layer = Layer.effect(prefix: input.schedule.signature.prefix,},maxDeliveryAgeMinutes: input.schedule.maxDeliveryAgeMinutes ?? null,+ ...webhookFilters(+ // Omitted keeps the stored filters, so a client that predates+ // them can re-save a task without clearing them.+ input.schedule.filters ??+ (existingTask?.schedule.type === "webhook"+ ? existingTask.schedule.filters+ : undefined),+ ),}: input.schedule;const webhook =@@ -1106,6 +1139,11 @@ export const layer = Layer.effect(next.delete(id);return next;}),+ Ref.update(webhookFilteredLogWindows, (windows) => {+ const next = new Map(windows);+ next.delete(id);+ return next;+ }),Ref.update(webhookPermits, (permits) => {const next = new Map(permits);next.delete(id);@@ -1217,7 +1255,12 @@ export const layer = Layer.effect(WHERE task_id = ${input.id}ORDER BY received_at DESC, rowid DESC`.pipe(- Effect.map((rows) => ({ deliveries: rows.map(decodeDeliverySummary) })),+ Effect.map((rows) => ({+ deliveries: (input.acceptAnyOutcome === true+ ? rows+ : rows.filter((row) => LEGACY_DELIVERY_OUTCOMES.has(row.outcome))+ ).map(decodeDeliverySummary),+ })),Effect.mapError((cause) =>taskError("Could not list webhook deliveries.", { taskId: input.id, cause }),),@@ -1295,15 +1338,17 @@ export const layer = Layer.effect(rendered_prompt = excluded.rendered_prompt,error = excluded.error`;+ const filtered = input.outcome === "filtered" ? 1 : 0;yield* sql`DELETE FROM scheduled_task_webhook_deliveriesWHERE task_id = ${input.taskId}+ AND (outcome = 'filtered') = ${filtered}AND delivery_id NOT IN (SELECT delivery_id FROM scheduled_task_webhook_deliveries- WHERE task_id = ${input.taskId}+ WHERE task_id = ${input.taskId} AND (outcome = 'filtered') = ${filtered}-- rowid breaks timestamp ties in arrival order; delivery ids are random.ORDER BY received_at DESC, rowid DESC- LIMIT ${WEBHOOK_DELIVERY_RETENTION}+ LIMIT ${filtered ? WEBHOOK_FILTERED_DELIVERY_RETENTION : WEBHOOK_DELIVERY_RETENTION})`;}),@@ -1351,6 +1396,18 @@ export const layer = Layer.effect(},);+ /** Sliding one-minute window of filtered requests written to the delivery log. */+ const takeFilteredLogSlot = (id: ScheduledTaskId, nowMs: number) =>+ Ref.modify(+ webhookFilteredLogWindows,+ (windows): readonly [boolean, ReadonlyMap<ScheduledTaskId, ReadonlyArray<number>>] => {+ const recent = (windows.get(id) ?? []).filter((at) => nowMs - at < 60_000);+ return recent.length >= WEBHOOK_FILTERED_LOG_PER_MINUTE+ ? [false, windows]+ : [true, new Map(windows).set(id, [...recent, nowMs])];+ },+ );+const webhookPermit = Effect.fn("ScheduledTaskService.webhookPermit")(function* (id: ScheduledTaskId,) {@@ -1514,6 +1571,44 @@ export const layer = Layer.effect(...(details.error === undefined ? {} : { error: details.error }),});+ const signature = schedule.signature;+ const signatureVerified =+ signature === null ||+ (row.webhook_secret !== null &&+ verifyWebhookSignature({+ signature,+ secret: row.webhook_secret,+ headers: request.headers,+ body: request.body,+ }));+ const maxAgeMinutes = schedule.maxDeliveryAgeMinutes ?? null;+ const tooOld =+ maxAgeMinutes !== null &&+ DateTime.toEpochMillis(now) - DateTime.toEpochMillis(receivedAt) >+ maxAgeMinutes * 60_000;++ // Filters: checked after the signature and age, and before the rate+ // limit, so requests the task ignores never take a run's slot. The+ // request is accepted so the sender doesn't retry it, and its relay+ // claim is released because nothing ran.+ if (task.enabled && signatureVerified && !tooOld) {+ const failedFilter = findFailedWebhookFilter(schedule.filters ?? [], request);+ if (failedFilter !== null) {+ if (yield* takeFilteredLogSlot(task.id, DateTime.toEpochMillis(now))) {+ yield* log("filtered", {+ signatureVerified: signature !== null,+ error: describeFailedWebhookFilter(failedFilter),+ });+ }+ yield* observe("filtered");+ return yield* releaseClaim({+ _tag: "accepted" as const,+ deliveryId,+ outcome: "filtered" as const,+ });+ }+ }+// Only the first rejected request in a window is logged, so a flood// cannot write rows or push the real deliveries out of the log.const slot = yield* takeRateSlot(task.id, DateTime.toEpochMillis(now));@@ -1530,28 +1625,12 @@ export const layer = Layer.effect(yield* observe("disabled");return { _tag: "disabled" as const };}- const signature = schedule.signature;- if (signature !== null) {- const verified =- row.webhook_secret !== null &&- verifyWebhookSignature({- signature,- secret: row.webhook_secret,- headers: request.headers,- body: request.body,- });- if (!verified) {- yield* log("rejected_signature");- yield* observe("rejected_signature");- return { _tag: "rejected_signature" as const };- }+ if (!signatureVerified) {+ yield* log("rejected_signature");+ yield* observe("rejected_signature");+ return { _tag: "rejected_signature" as const };}- const maxAgeMinutes = schedule.maxDeliveryAgeMinutes ?? null;- if (- maxAgeMinutes !== null &&- DateTime.toEpochMillis(now) - DateTime.toEpochMillis(receivedAt) >- maxAgeMinutes * 60_000- ) {+ if (tooOld) {yield* log("expired", { signatureVerified: signature !== null });yield* observe("expired");return { _tag: "expired" as const };diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.tsindex ae8594a03f0..2485edf7e09 100644--- a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts@@ -953,3 +953,207 @@ it.effect("counts each handled request by what happened to it", () =>}),),);++it.effect("checks filters after the signature and max age, and runs only matching deliveries", () =>+ withService(({ service, launches }) =>+ Effect.gen(function* () {+ const { task } = yield* service.upsert(+ yield* webhookTaskInput({+ schedule: {+ type: "webhook",+ signature: {+ header: "x-hub-signature-256",+ encoding: "hex",+ prefix: "sha256=",+ secret: "s3cret",+ },+ maxDeliveryAgeMinutes: 30,+ filters: [+ { path: "headers.x-github-event", op: "equals", value: "pull_request" },+ { path: "body.action", op: "in", value: ["opened", "reopened"] },+ ],+ },+ }),+ );+ const delivery = (+ event: string,+ action: string,+ options: { readonly signed?: boolean; readonly receivedAt?: string } = {},+ ) => {+ const body = new TextEncoder().encode(+ JSON.stringify({ action, pull_request: { url: "https://github.com/org/repo/pull/45" } }),+ );+ const signature = `sha256=${NodeCrypto.createHmac("sha256", "s3cret").update(body).digest("hex")}`;+ return requestFor(task, {+ headers: {+ "content-type": "application/json",+ "x-github-event": event,+ ...(options.signed === false ? {} : { "x-hub-signature-256": signature }),+ },+ body,+ bodyText: new TextDecoder().decode(body),+ ...(options.receivedAt === undefined+ ? {}+ : { relayDeliveryId: "old", receivedAt: options.receivedAt }),+ });+ };+ const now = yield* DateTime.now;+ const old = DateTime.formatIso(DateTime.subtract(now, { minutes: 31 }));++ // A request failing a filter is still refused first for its signature or age.+ const unsigned = yield* service.triggerWebhook(delivery("push", "opened", { signed: false }));+ assert.equal(unsigned._tag, "rejected_signature");+ const tooOld = yield* service.triggerWebhook(delivery("push", "opened", { receivedAt: old }));+ assert.equal(tooOld._tag, "expired");++ const wrongEvent = yield* service.triggerWebhook(delivery("push", "opened"));+ const wrongAction = yield* service.triggerWebhook(delivery("pull_request", "closed"));+ assert.deepInclude(wrongEvent, { _tag: "accepted", outcome: "filtered" });+ assert.deepInclude(wrongAction, { _tag: "accepted", outcome: "filtered" });+ assert.equal(yield* Queue.size(launches), 0);+ const [listed] = (yield* service.list()).tasks;+ assert.equal(listed?.runCount, 0);+ assert.equal(listed?.lastRunStatus, "never");++ const matched = yield* service.triggerWebhook(delivery("pull_request", "opened"));+ assert.deepInclude(matched, { _tag: "accepted", outcome: "accepted" });+ assert.include((yield* Queue.take(launches)).initialMessage?.text ?? "", "pull/45");++ const deliveries = (yield* service.listWebhookDeliveries({+ id: task.id,+ acceptAnyOutcome: true,+ })).deliveries;+ const filtered = deliveries+ .filter((entry) => entry.outcome === "filtered")+ .map((entry) => [entry.signatureVerified, entry.error]);+ assert.sameDeepMembers(filtered, [+ [true, "Filter 1 (headers.x-github-event) did not match."],+ [true, "Filter 2 (body.action) did not match."],+ ]);+ }),+ ),+);++const pullRequestFilterInput = () =>+ webhookTaskInput({+ schedule: {+ type: "webhook",+ filters: [{ path: "headers.x-github-event", op: "equals", value: "pull_request" }],+ },+ });+const githubEvent = (event: string) => ({+ headers: { "content-type": "application/json", "x-github-event": event },+});++it.effect("filtered deliveries take no run slot and log at most 10 rows a minute", () =>+ withService(({ service, launches }) =>+ Effect.gen(function* () {+ const { task } = yield* service.upsert(yield* pullRequestFilterInput());+ const ignored = yield* Effect.forEach(Array.from({ length: 70 }), () =>+ service.triggerWebhook(requestFor(task, githubEvent("push"))),+ );+ assert.isTrue(+ ignored.every((result) => result._tag === "accepted" && result.outcome === "filtered"),+ );+ const matched = yield* service.triggerWebhook(requestFor(task, githubEvent("pull_request")));+ assert.deepInclude(matched, { _tag: "accepted", outcome: "accepted" });+ yield* Queue.take(launches);+ yield* Effect.forEach(Array.from({ length: 5 }), () =>+ service.triggerWebhook(requestFor(task, githubEvent("push"))),+ );++ const outcomes = (yield* service.listWebhookDeliveries({+ id: task.id,+ acceptAnyOutcome: true,+ })).deliveries.map((delivery) => delivery.outcome);+ // 75 filtered requests in one window: only the first 10 are written.+ assert.equal(outcomes.filter((outcome) => outcome === "filtered").length, 10);+ assert.equal(outcomes.filter((outcome) => outcome === "accepted").length, 1);++ // Later windows log again, and retention keeps the filtered rows at 20.+ for (const _ of [1, 2]) {+ yield* TestClock.adjust("61 seconds");+ yield* Effect.forEach(Array.from({ length: 15 }), () =>+ service.triggerWebhook(requestFor(task, githubEvent("push"))),+ );+ }+ const later = (yield* service.listWebhookDeliveries({ id: task.id, acceptAnyOutcome: true }))+ .deliveries;+ assert.equal(later.filter((delivery) => delivery.outcome === "filtered").length, 20);+ assert.equal(later.filter((delivery) => delivery.outcome === "accepted").length, 1);+ }),+ ),+);++it.effect("a filtered relay delivery releases its claim, so a redelivery is evaluated again", () =>+ withService(({ service, launches }) =>+ Effect.gen(function* () {+ const { task } = yield* service.upsert(yield* pullRequestFilterInput());+ const held = { relayDeliveryId: "relay-filtered" };+ const first = yield* service.triggerWebhook(+ requestFor(task, { ...held, ...githubEvent("push") }),+ );+ const again = yield* service.triggerWebhook(+ requestFor(task, { ...held, ...githubEvent("push") }),+ );+ assert.deepInclude(first, { _tag: "accepted", outcome: "filtered" });+ assert.deepInclude(again, { _tag: "accepted", outcome: "filtered" });+ const ran = yield* service.triggerWebhook(+ requestFor(task, { ...held, ...githubEvent("pull_request") }),+ );+ assert.deepInclude(ran, { _tag: "accepted", outcome: "accepted" });+ yield* Queue.take(launches);+ const replayed = yield* service.triggerWebhook(+ requestFor(task, { ...held, ...githubEvent("pull_request") }),+ );+ assert.deepInclude(replayed, { _tag: "accepted", outcome: "duplicate" });+ }),+ ),+);++it.effect("a save without filters keeps the stored ones and an empty list clears them", () =>+ withService(({ service }) =>+ Effect.gen(function* () {+ const { task } = yield* service.upsert(yield* pullRequestFilterInput());+ const filters = task.schedule.type === "webhook" ? task.schedule.filters : undefined;+ assert.lengthOf(filters ?? [], 1);++ const kept = yield* service.upsert(+ yield* webhookTaskInput({ title: "Renamed", schedule: { type: "webhook" } }),+ );+ assert.deepEqual(+ kept.task.schedule.type === "webhook" && kept.task.schedule.filters,+ filters,+ );++ const cleared = yield* service.upsert(+ yield* webhookTaskInput({ schedule: { type: "webhook", filters: [] } }),+ );+ assert.notProperty(cleared.task.schedule, "filters");+ }),+ ),+);++it.effect("leaves filtered rows out of the list for clients that only decode older outcomes", () =>+ withService(({ service, launches }) =>+ Effect.gen(function* () {+ const { task } = yield* service.upsert(yield* pullRequestFilterInput());+ yield* service.triggerWebhook(requestFor(task, githubEvent("push")));+ yield* service.triggerWebhook(requestFor(task, githubEvent("pull_request")));+ yield* Queue.take(launches);+ const legacy = (yield* service.listWebhookDeliveries({ id: task.id })).deliveries;+ assert.deepEqual(+ legacy.map((delivery) => delivery.outcome),+ ["accepted"],+ );+ const current = (yield* service.listWebhookDeliveries({+ id: task.id,+ acceptAnyOutcome: true,+ })).deliveries;+ assert.sameMembers(+ current.map((delivery) => delivery.outcome),+ ["accepted", "filtered"],+ );+ }),+ ),+);diff --git a/apps/server/src/scheduledTasks/webhookFilter.test.ts b/apps/server/src/scheduledTasks/webhookFilter.test.tsnew file mode 100644index 00000000000..b8d9d207083--- /dev/null+++ b/apps/server/src/scheduledTasks/webhookFilter.test.ts@@ -0,0 +1,91 @@+import { assert, describe, it } from "@effect/vitest";+import type { ScheduledTaskWebhookFilter } from "@t3tools/contracts";++import { findFailedWebhookFilter, matchesWebhookFilter } from "./webhookFilter.ts";+import type { WebhookRequest } from "./webhookTemplate.ts";++const request: WebhookRequest = {+ method: "POST",+ path: "/api/hooks/task-1",+ query: "source=github",+ headers: { "content-type": "application/json", "x-github-event": "pull_request" },+ bodyText: JSON.stringify({+ action: "labeled",+ number: 45,+ draft: false,+ closed_at: null,+ label: { name: "agent:review" },+ labels: ["bug"],+ }),+};++const matches = (filter: ScheduledTaskWebhookFilter) =>+ findFailedWebhookFilter([filter], request) === null;++describe("matchesWebhookFilter", () => {+ it("compares scalars as strings", () => {+ assert.isTrue(matches({ path: "body.action", op: "equals", value: "labeled" }));+ assert.isTrue(matches({ path: "body.number", op: "equals", value: "45" }));+ assert.isTrue(matches({ path: "body.draft", op: "equals", value: "false" }));+ assert.isFalse(matches({ path: "body.action", op: "equals", value: "Labeled" }));+ assert.isTrue(matches({ path: "body.action", op: "notEquals", value: "closed" }));+ assert.isFalse(matches({ path: "body.action", op: "notEquals", value: "labeled" }));+ assert.isTrue(matches({ path: "body.action", op: "in", value: ["opened", "labeled"] }));+ assert.isTrue(matches({ path: "body.label.name", op: "startsWith", value: "agent:" }));+ assert.isFalse(matches({ path: "body.label.name", op: "startsWith", value: "review" }));+ });++ it("reads headers case-insensitively and query values by name", () => {+ assert.isTrue(matches({ path: "headers.X-GitHub-Event", op: "equals", value: "pull_request" }));+ assert.isTrue(matches({ path: "query.source", op: "equals", value: "github" }));+ });++ it("lets objects and arrays satisfy only exists", () => {+ for (const path of ["body.label", "body.labels"]) {+ assert.isTrue(matches({ path, op: "exists" }));+ assert.isFalse(matches({ path, op: "equals", value: "[object Object]" }));+ assert.isFalse(matches({ path, op: "notEquals", value: "anything" }));+ assert.isFalse(matches({ path, op: "in", value: ["bug"] }));+ assert.isFalse(matches({ path, op: "startsWith", value: "" }));+ }+ });++ it("fails every op on a missing or null path, including notEquals", () => {+ for (const path of [+ "body.missing",+ "body.label.name.deeper",+ "headers.x-none",+ "body.closed_at",+ ]) {+ assert.isFalse(matches({ path, op: "exists" }));+ assert.isFalse(matches({ path, op: "notEquals", value: "x" }));+ assert.isFalse(matchesWebhookFilter({ path, op: "startsWith", value: "" }, undefined));+ }+ });+});++describe("findFailedWebhookFilter", () => {+ it("passes with no filters and reports the first failing filter", () => {+ assert.isNull(findFailedWebhookFilter([], request));+ assert.deepEqual(+ findFailedWebhookFilter(+ [+ { path: "headers.x-github-event", op: "equals", value: "pull_request" },+ { path: "body.action", op: "equals", value: "opened" },+ { path: "body.missing", op: "exists" },+ ],+ request,+ ),+ { index: 1, path: "body.action" },+ );+ });++ it("does not need a JSON body for header filters", () => {+ assert.isNull(+ findFailedWebhookFilter([{ path: "headers.x-github-event", op: "exists" }], {+ ...request,+ bodyText: "not json",+ }),+ );+ });+});diff --git a/apps/server/src/scheduledTasks/webhookFilter.ts b/apps/server/src/scheduledTasks/webhookFilter.tsnew file mode 100644index 00000000000..7f46a15cc4f--- /dev/null+++ b/apps/server/src/scheduledTasks/webhookFilter.ts@@ -0,0 +1,49 @@+import type { ScheduledTaskWebhookFilter } from "@t3tools/contracts";++import { webhookExpressionResolver, type WebhookRequest } from "./webhookTemplate.ts";++export interface FailedWebhookFilter {+ readonly index: number;+ readonly path: string;+}++function scalarText(value: unknown): string | undefined {+ if (typeof value === "string") return value;+ if (typeof value === "number" || typeof value === "boolean") return String(value);+ return undefined;+}++/** Placeholders render null as missing, so filters treat it the same way. */+export function matchesWebhookFilter(filter: ScheduledTaskWebhookFilter, value: unknown): boolean {+ if (filter.op === "exists") return value !== undefined && value !== null;+ const text = scalarText(value);+ if (text === undefined) return false;+ switch (filter.op) {+ case "equals":+ return text === filter.value;+ case "notEquals":+ return text !== filter.value;+ case "in":+ return filter.value.includes(text);+ case "startsWith":+ return text.startsWith(filter.value);+ }+}++/** The first filter the request fails, or null when every filter matches. */+export function findFailedWebhookFilter(+ filters: ReadonlyArray<ScheduledTaskWebhookFilter>,+ request: WebhookRequest,+): FailedWebhookFilter | null {+ if (filters.length === 0) return null;+ const resolve = webhookExpressionResolver(request);+ for (const [index, filter] of filters.entries()) {+ if (!matchesWebhookFilter(filter, resolve(filter.path))) return { index, path: filter.path };+ }+ return null;+}++/** Filters are numbered from 1, in the order the settings form lists them. */+export function describeFailedWebhookFilter(failed: FailedWebhookFilter): string {+ return `Filter ${failed.index + 1} (${failed.path}) did not match.`;+}diff --git a/apps/server/src/scheduledTasks/webhookRoute.test.ts b/apps/server/src/scheduledTasks/webhookRoute.test.tsindex 31261660c62..21828105370 100644--- a/apps/server/src/scheduledTasks/webhookRoute.test.ts+++ b/apps/server/src/scheduledTasks/webhookRoute.test.ts@@ -222,6 +222,7 @@ describe("webhook route", () => {[{ _tag: "accepted", deliveryId, outcome: "accepted" }, 202, "accepted"],[{ _tag: "accepted", deliveryId, outcome: "duplicate" }, 202, "duplicate"],[{ _tag: "accepted", deliveryId, outcome: "prompt_too_long" }, 202, "prompt_too_long"],+ [{ _tag: "accepted", deliveryId, outcome: "filtered" }, 202, "filtered"],[{ _tag: "not_found" }, 404, "not_found"],[{ _tag: "rejected_signature" }, 401, "rejected_signature"],[{ _tag: "disabled" }, 409, "disabled"],diff --git a/apps/server/src/scheduledTasks/webhookTemplate.ts b/apps/server/src/scheduledTasks/webhookTemplate.tsindex b129704f0ab..5f3ef760ad8 100644--- a/apps/server/src/scheduledTasks/webhookTemplate.ts+++ b/apps/server/src/scheduledTasks/webhookTemplate.ts@@ -112,16 +112,17 @@ function formatWebhookRequest(request: WebhookRequest): string {].join("\n");}-export function renderWebhookPrompt(- template: string,+/**+ * Resolves a placeholder expression (`body.action`, `headers.x-github-event`)+ * against the request. Webhook filters share it, so both read the same value.+ */+export function webhookExpressionResolver(request: WebhookRequest,- frameId: string,-): RenderedWebhookPrompt {- const missing: string[] = [];+): (expression: string) => unknown {let body: { parsed: unknown } | undefined;const parsedBody = () => (body ??= { parsed: parseBody(request) }).parsed;- const resolve = (expression: string): unknown => {+ return (expression) => {const [root, ...segments] = expression.split(".");switch (root) {case "request":@@ -143,6 +144,15 @@ export function renderWebhookPrompt(return undefined;}};+}++export function renderWebhookPrompt(+ template: string,+ request: WebhookRequest,+ frameId: string,+): RenderedWebhookPrompt {+ const missing: string[] = [];+ const resolve = webhookExpressionResolver(request);const tag = `webhook-data-${frameId}`;let framed = false;diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsxindex c22bdc188db..5f545816690 100644--- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx+++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx@@ -26,9 +26,17 @@ import type {ScheduledTaskWebhookDeliverySummary,ThreadId,} from "@t3tools/contracts";-import { DEFAULT_WEBHOOK_PROMPT } from "@t3tools/client-runtime/scheduled-task-webhook";+import {+ DEFAULT_WEBHOOK_PROMPT,+ emptyWebhookFilterDraft,+ parseWebhookFilterDrafts,+ removeWebhookFilterDraft,+ WEBHOOK_FILTER_OPS,+ type WebhookFilterDraft,+} from "@t3tools/client-runtime/scheduled-task-webhook";import {MAX_WEBHOOK_DELIVERY_AGE_MINUTES,+ MAX_WEBHOOK_FILTERS,MIN_SCHEDULED_TASK_INTERVAL_MS,ProviderInstanceId,resolveEnvironmentMachineKind,@@ -144,8 +152,103 @@ const EMPTY_DRAFT: DraftState = {...WEBHOOK_SIGNATURE_DEFAULTS,signatureSecret: "",maxDeliveryAgeMinutes: "",+ filters: [],+ savedFilters: [],};+function WebhookFiltersField({+ filters,+ onChange,+}: {+ filters: ReadonlyArray<WebhookFilterDraft>;+ onChange: (filters: ReadonlyArray<WebhookFilterDraft>) => void;+}) {+ const update = (index: number, patch: Partial<WebhookFilterDraft>) =>+ onChange(filters.map((filter, at) => (at === index ? { ...filter, ...patch } : filter)));+ return (+ <div className="space-y-2">+ <div className="flex items-center justify-between gap-2">+ <div className="min-w-0 space-y-1">+ <Label>Filters</Label>+ <p className="text-sm text-muted-foreground">+ Run only when every filter matches. Other requests are logged as filtered. Separate “is+ one of” values with commas; a value can't contain a comma.+ </p>+ </div>+ <Button+ className="shrink-0"+ variant="outline"+ size="sm"+ disabled={filters.length >= MAX_WEBHOOK_FILTERS}+ onClick={() => onChange([...filters, emptyWebhookFilterDraft()])}+ >+ <PlusIcon />+ Add filter+ </Button>+ </div>+ {filters.map((filter, index) => (+ // Always stacked: the dialog stays narrow on wide windows, so a single line+ // would cut off typical paths and values. The grid wrappers size each control+ // without restyling it; a grid item stretches to its minmax(0, 1fr) track.+ <div key={filter.id} className="space-y-2 pt-1">+ <div className="flex items-center gap-2">+ <div className="grid min-w-0 flex-1 grid-cols-1">+ <Input+ aria-label={`Filter ${index + 1} path`}+ placeholder="body.action"+ value={filter.path}+ onChange={(event) => update(index, { path: event.target.value })}+ />+ </div>+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label={`Remove filter ${index + 1}`}+ onClick={() => onChange(removeWebhookFilterDraft(filters, filter.id))}+ >+ <Trash2Icon />+ </Button>+ </div>+ <div className="flex items-center gap-2">+ <Select+ value={filter.op}+ onValueChange={(op) => {+ const known = WEBHOOK_FILTER_OPS.find((option) => option.op === op);+ if (known) update(index, { op: known.op });+ }}+ >+ <div className="grid w-44 shrink-0 grid-cols-1">+ <SelectTrigger size="sm" aria-label={`Filter ${index + 1} test`}>+ <SelectValue>+ {WEBHOOK_FILTER_OPS.find((option) => option.op === filter.op)?.label}+ </SelectValue>+ </SelectTrigger>+ </div>+ <SelectPopup>+ {WEBHOOK_FILTER_OPS.map((option) => (+ <SelectItem key={option.op} value={option.op}>+ {option.label}+ </SelectItem>+ ))}+ </SelectPopup>+ </Select>+ {filter.op === "exists" ? null : (+ <div className="grid min-w-0 flex-1 grid-cols-1">+ <Input+ aria-label={`Filter ${index + 1} value`}+ placeholder={filter.op === "in" ? "opened, reopened" : "opened"}+ value={filter.value}+ onChange={(event) => update(index, { value: event.target.value })}+ />+ </div>+ )}+ </div>+ </div>+ ))}+ </div>+ );+}+function Field({label,hint,@@ -232,14 +335,23 @@ const DELIVERY_OUTCOME_LABELS: Record<ScheduledTaskWebhookDeliveryOutcome, strindisabled: "Task paused",rate_limited: "Rate limited",expired: "Too old",+ filtered: "Filtered",};-function deliveryOutcomeVariant(outcome: ScheduledTaskWebhookDeliveryOutcome) {+// A newer server can report an outcome this client has no label for.+function deliveryOutcomeLabel(outcome: string): string {+ return Object.hasOwn(DELIVERY_OUTCOME_LABELS, outcome)+ ? DELIVERY_OUTCOME_LABELS[outcome as ScheduledTaskWebhookDeliveryOutcome]+ : outcome.replaceAll("_", " ");+}++function deliveryOutcomeVariant(outcome: string) {if (outcome === "accepted") return "success";if (outcome === "disabled" || outcome === "rate_limited" || outcome === "expired") {return "warning";}- return "error";+ if (outcome === "dispatch_failed" || outcome === "rejected_signature") return "error";+ return "outline";}function statusVariant(status: ScheduledTask["lastRunStatus"]) {@@ -697,7 +809,10 @@ function WebhookDeliveriesDialog({readonly onClose: () => void;}) {const deliveriesQuery = useEnvironmentQuery(- serverEnvironment.scheduledTaskWebhookDeliveries({ environmentId, input: { id: task.id } }),+ serverEnvironment.scheduledTaskWebhookDeliveries({+ environmentId,+ input: { id: task.id, acceptAnyOutcome: true },+ }),);const [selectedId, setSelectedId] = useState<ScheduledTaskWebhookDeliverySummary["id"] | null>(null,@@ -736,7 +851,7 @@ function WebhookDeliveriesDialog({<div className="space-y-4"><div className="flex flex-wrap items-center gap-2 text-sm"><Badge variant={deliveryOutcomeVariant(selected.outcome)}>- {DELIVERY_OUTCOME_LABELS[selected.outcome]}+ {deliveryOutcomeLabel(selected.outcome)}</Badge><span>{selected.method} · <ScheduledRelativeLabel value={selected.receivedAt} />@@ -745,7 +860,17 @@ function WebhookDeliveriesDialog({<span className="text-muted-foreground">Signature verified</span>) : null}</div>- {selected.error ? <p className="text-sm text-destructive">{selected.error}</p> : null}+ {selected.error ? (+ <p+ className={+ selected.outcome === "filtered"+ ? "text-sm text-muted-foreground"+ : "text-sm text-destructive"+ }+ >+ {selected.error}+ </p>+ ) : null}<DeliveryBlock title="Prompt sent to the agent">{selected.renderedPrompt ?? "No run was started for this request."}</DeliveryBlock>@@ -782,12 +907,15 @@ function WebhookDeliveriesDialog({onClick={() => setSelectedId(delivery.id)}><Badge variant={deliveryOutcomeVariant(delivery.outcome)}>- {DELIVERY_OUTCOME_LABELS[delivery.outcome]}+ {deliveryOutcomeLabel(delivery.outcome)}</Badge><span>{delivery.method}</span><span className="text-muted-foreground"><ScheduledRelativeLabel value={delivery.receivedAt} /></span>+ {delivery.outcome === "filtered" && delivery.error ? (+ <span className="text-muted-foreground">{delivery.error}</span>+ ) : null}{delivery.missingFields.length > 0 ? (<span className="text-muted-foreground">{delivery.missingFields.length} empty placeholder@@ -1058,6 +1186,11 @@ function ScheduledTaskEditorForm({reportFailure("Scheduled task is incomplete", "Add a title, prompt, project, and model.");return;}+ const parsedFilters = parseWebhookFilterDrafts(draft.filters);+ if (draft.scheduleMode === "webhook" && "error" in parsedFilters) {+ reportFailure("Invalid filter", parsedFilters.error);+ return;+ }const schedule = scheduleFromDraft(draft);if (schedule === null) {reportFailure(@@ -1142,7 +1275,8 @@ function ScheduledTaskEditorForm({</DialogHeader><DialogPanel>- <fieldset disabled={saving} className="space-y-5">+ {/* Fieldsets default to min-width: min-content, which lets one wide control widen the form past the dialog. */}+ <fieldset disabled={saving} className="min-w-0 space-y-5">{!connected ? (<p className="text-sm text-destructive">Reconnect this environment before saving.</p>) : null}@@ -1351,7 +1485,8 @@ function ScheduledTaskEditorForm({minute.</p>) : null}- <div className="flex items-center justify-between gap-2">+ {/* Wraps the toggle below the label when both don't fit, as on phones. */}+ <div className="flex flex-wrap items-center justify-between gap-2"><Label>Schedule</Label><ToggleGrouparia-label="Schedule type"@@ -1404,6 +1539,10 @@ function ScheduledTaskEditorForm({}/></Field>+ <WebhookFiltersField+ filters={draft.filters}+ onChange={(filters) => setDraft((current) => ({ ...current, filters }))}+ /><div className="flex items-center justify-between gap-4"><div className="min-w-0 space-y-1"><Label htmlFor="scheduled-task-signature">Require signature</Label>diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.tsindex 9c67ec46e8e..2b9264b9dd7 100644--- a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts+++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts@@ -218,6 +218,31 @@ describe("webhook scheduled tasks", () => {expect(scheduleFromDraft({ ...draft, maxDeliveryAgeMinutes: invalid })).toBeNull();}});++ it("sends filters only when the form changed them", () => {+ const filters = [+ { path: "headers.x-github-event", op: "equals", value: "pull_request" },+ { path: "body.action", op: "in", value: ["opened", "reopened"] },+ ] as const;+ const draft = taskToDraft({+ ...webhookTask,+ schedule: { type: "webhook", signature, filters },+ });+ expect(draft.filters.map((filter) => filter.op)).toEqual(["equals", "in"]);+ // A title-only save leaves the key out, so the server keeps whatever is stored now.+ expect(scheduleFromDraft({ ...draft, title: "Renamed" })).not.toHaveProperty("filters");+ expect(scheduleFromDraft({ ...draft, filters: draft.filters.slice(0, 1) })).toMatchObject({+ filters: filters.slice(0, 1),+ });+ // Removing every row is a change, so it clears the stored filters.+ expect(scheduleFromDraft({ ...draft, filters: [] })).toMatchObject({ filters: [] });+ expect(+ scheduleFromDraft({+ ...draft,+ filters: [{ id: "f1", path: "body.action", op: "in", value: " , " }],+ }),+ ).toBeNull();+ });});describe("scheduled task model defaults", () => {diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.tsindex 0767f99190c..472ba9b998a 100644--- a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts+++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts@@ -9,7 +9,13 @@ import {type ProviderInteractionMode,type ServerSettings,} from "@t3tools/contracts";-import { parseMaxDeliveryAge } from "@t3tools/client-runtime/scheduled-task-webhook";+import {+ parseMaxDeliveryAge,+ parseWebhookFilterDrafts,+ webhookFilterDrafts,+ webhookFilterDraftsChanged,+ type WebhookFilterDraft,+} from "@t3tools/client-runtime/scheduled-task-webhook";import {resolveProjectSettings,@@ -77,6 +83,9 @@ export interface DraftState {/** Write-only: empty keeps the secret already stored on the server. */readonly signatureSecret: string;readonly maxDeliveryAgeMinutes: string;+ readonly filters: ReadonlyArray<WebhookFilterDraft>;+ /** The filter rows the form opened with. */+ readonly savedFilters: ReadonlyArray<WebhookFilterDraft>;}export const WEBHOOK_SIGNATURE_DEFAULTS = {@@ -89,6 +98,8 @@ export function scheduleFromDraft(draft: DraftState): ScheduledTaskUpsertSchedulif (draft.scheduleMode === "webhook") {const maxDeliveryAgeMinutes = parseMaxDeliveryAge(draft.maxDeliveryAgeMinutes);if (maxDeliveryAgeMinutes === undefined) return null;+ const parsedFilters = parseWebhookFilterDrafts(draft.filters);+ if (!("filters" in parsedFilters)) return null;const secret = draft.signatureSecret.trim();return {type: "webhook",@@ -101,6 +112,10 @@ export function scheduleFromDraft(draft: DraftState): ScheduledTaskUpsertSchedul}: null,maxDeliveryAgeMinutes,+ // Only edited filters are sent; the server keeps the stored ones otherwise.+ ...(webhookFilterDraftsChanged(draft.savedFilters, draft.filters)+ ? { filters: parsedFilters.filters }+ : {}),};}if (draft.scheduleMode === "interval") {@@ -117,6 +132,7 @@ export function scheduleFromDraft(draft: DraftState): ScheduledTaskUpsertSchedulexport function taskToDraft(task: ScheduledTask): DraftState {const schedule = task.schedule;+ const filters = webhookFilterDrafts(schedule.type === "webhook" ? schedule.filters : undefined);const weekdays =schedule.type === "fixed_time" && schedule.weekdays && schedule.weekdays.length > 0? new Set(schedule.weekdays)@@ -161,6 +177,8 @@ export function taskToDraft(task: ScheduledTask): DraftState {schedule.type === "webhook" && schedule.maxDeliveryAgeMinutes != null? String(schedule.maxDeliveryAgeMinutes): "",+ filters,+ savedFilters: filters,};}diff --git a/docs/user/project-settings.md b/docs/user/project-settings.mdindex bb89de6717e..cdae02679be 100644--- a/docs/user/project-settings.md+++ b/docs/user/project-settings.md@@ -109,6 +109,15 @@ same secret in the repository's webhook settings with content typeup on desktop or web; mobile keeps an existing signature check but can't turnone on.+To run only for some requests, add **Filters**. Each one tests a value named+like a placeholder, without the braces, such as `headers.x-github-event` equals+`pull_request` or `body.action` is one of `opened, reopened`. A task runs only+when every filter matches; other requests are answered normally, logged as+**Filtered** with the first filter that failed, and start nothing. Values+compare as text, and a value that is an object or a list only passes+**exists**. Separate **is one of** values with commas; a value can't contain+a comma or start or end with a space.+On desktop and web, pick **Deliveries** from a task's menu to see recentrequests and the prompt each one produced.diff --git a/packages/client-runtime/src/scheduledTaskWebhook.test.ts b/packages/client-runtime/src/scheduledTaskWebhook.test.tsindex c2de7d240bc..6e35d844696 100644--- a/packages/client-runtime/src/scheduledTaskWebhook.test.ts+++ b/packages/client-runtime/src/scheduledTaskWebhook.test.ts@@ -1,6 +1,13 @@import { describe, expect, it } from "vite-plus/test";-import { parseMaxDeliveryAge } from "./scheduledTaskWebhook.ts";+import {+ parseMaxDeliveryAge,+ emptyWebhookFilterDraft,+ parseWebhookFilterDrafts,+ removeWebhookFilterDraft,+ webhookFilterDrafts,+ webhookFilterDraftsChanged,+} from "./scheduledTaskWebhook.ts";describe("parseMaxDeliveryAge", () => {it("treats blank as no limit and rejects values the server would not accept", () => {@@ -11,3 +18,57 @@ describe("parseMaxDeliveryAge", () => {}});});++describe("webhook filter drafts", () => {+ it("round-trips saved filters through the form rows", () => {+ const filters = [+ { path: "headers.x-github-event", op: "equals", value: "pull_request" },+ { path: "body.action", op: "in", value: ["opened", "reopened"] },+ { path: "body.label.name", op: "in", value: ["needs review", "a-b"] },+ { path: "query.source", op: "exists" },+ ] as const;+ const drafts = webhookFilterDrafts(filters);+ expect(drafts[1]).toMatchObject({ path: "body.action", op: "in", value: "opened, reopened" });+ expect(parseWebhookFilterDrafts(drafts)).toEqual({ filters });+ });++ it("names the first row the server would refuse", () => {+ expect(+ parseWebhookFilterDrafts([+ { id: "f1", path: "body.action", op: "equals", value: "opened" },+ { id: "f2", path: "body.action", op: "in", value: " , " },+ { id: "f3", path: "", op: "exists", value: "" },+ ]),+ ).toEqual({+ error: "Filter 2 needs a path under body, headers or query, and at least one value.",+ });+ expect(parseWebhookFilterDrafts([{ id: "f1", path: " ", op: "exists", value: "" }])).toEqual({+ error: "Filter 1 needs a path under body, headers or query.",+ });+ const seventeen = Array.from({ length: 17 }, (_, index) => ({+ id: `f${index}`,+ path: "body.action",+ op: "exists" as const,+ value: "",+ }));+ expect(parseWebhookFilterDrafts(seventeen)).toEqual({ error: "Use at most 16 filters." });+ });++ it("notices added, removed and edited rows but not an untouched list", () => {+ const saved = webhookFilterDrafts([{ path: "body.action", op: "equals", value: "opened" }]);+ expect(webhookFilterDraftsChanged(saved, [...saved])).toBe(false);+ expect(webhookFilterDraftsChanged(saved, [])).toBe(true);+ expect(webhookFilterDraftsChanged(saved, [{ ...saved[0]!, value: "closed" }])).toBe(true);+ expect(webhookFilterDraftsChanged([], [])).toBe(false);+ });++ it("removing the first row keeps the second row's id", () => {+ const drafts = [+ ...webhookFilterDrafts([{ path: "body.action", op: "equals", value: "opened" }]),+ emptyWebhookFilterDraft(),+ ];+ expect(new Set(drafts.map((draft) => draft.id)).size).toBe(2);+ const remaining = removeWebhookFilterDraft(drafts, drafts[0]!.id);+ expect(remaining.map((draft) => draft.id)).toEqual([drafts[1]!.id]);+ });+});diff --git a/packages/client-runtime/src/scheduledTaskWebhook.ts b/packages/client-runtime/src/scheduledTaskWebhook.tsindex 02859170965..2b19d282dce 100644--- a/packages/client-runtime/src/scheduledTaskWebhook.ts+++ b/packages/client-runtime/src/scheduledTaskWebhook.ts@@ -1,4 +1,11 @@-import { MAX_WEBHOOK_DELIVERY_AGE_MINUTES } from "@t3tools/contracts";+import {+ MAX_WEBHOOK_DELIVERY_AGE_MINUTES,+ MAX_WEBHOOK_FILTERS,+ ScheduledTaskWebhookFilter,+ type ScheduledTaskWebhookFilterOp,+} from "@t3tools/contracts";+import * as Option from "effect/Option";+import * as Schema from "effect/Schema";export const DEFAULT_WEBHOOK_PROMPT = "Handle this webhook:\n{{body}}";@@ -10,3 +17,118 @@ export function parseMaxDeliveryAge(value: string): number | null | undefined {? minutes: undefined;}++/**+ * One editable filter row. `in` takes a comma-separated list, which is+ * lossless because list values can't contain commas; `exists` ignores the value.+ */+export interface WebhookFilterDraft {+ /** Stable row identity for the form; never sent to the server. */+ readonly id: string;+ readonly path: string;+ readonly op: ScheduledTaskWebhookFilterOp;+ readonly value: string;+}++export const WEBHOOK_FILTER_OPS: ReadonlyArray<{+ readonly op: ScheduledTaskWebhookFilterOp;+ readonly label: string;+}> = [+ { op: "equals", label: "equals" },+ { op: "notEquals", label: "does not equal" },+ { op: "in", label: "is one of" },+ { op: "startsWith", label: "starts with" },+ { op: "exists", label: "exists" },+];++let lastWebhookFilterDraftId = 0;+const nextWebhookFilterDraftId = () => `filter-${++lastWebhookFilterDraftId}`;++export function emptyWebhookFilterDraft(): WebhookFilterDraft {+ return { id: nextWebhookFilterDraftId(), path: "", op: "equals", value: "" };+}++/** By id, so a removed row's identity never passes to the row after it. */+export function removeWebhookFilterDraft(+ drafts: ReadonlyArray<WebhookFilterDraft>,+ id: string,+): ReadonlyArray<WebhookFilterDraft> {+ return drafts.filter((draft) => draft.id !== id);+}++export function webhookFilterDrafts(+ filters: ReadonlyArray<ScheduledTaskWebhookFilter> | undefined,+): ReadonlyArray<WebhookFilterDraft> {+ return (filters ?? []).map((filter) => ({+ id: nextWebhookFilterDraftId(),+ path: filter.path,+ op: filter.op,+ value:+ filter.op === "exists" ? "" : filter.op === "in" ? filter.value.join(", ") : filter.value,+ }));+}++const decodeFilter = Schema.decodeUnknownOption(ScheduledTaskWebhookFilter);++/**+ * Checks each row with the server's own schema, so a draft that parses here+ * also saves. The error names the first row that would not.+ */+export function parseWebhookFilterDrafts(+ drafts: ReadonlyArray<WebhookFilterDraft>,+): { readonly filters: ReadonlyArray<ScheduledTaskWebhookFilter> } | { readonly error: string } {+ if (drafts.length > MAX_WEBHOOK_FILTERS) {+ return { error: `Use at most ${MAX_WEBHOOK_FILTERS} filters.` };+ }+ const filters: ScheduledTaskWebhookFilter[] = [];+ for (const [index, draft] of drafts.entries()) {+ const path = draft.path.trim();+ const filter = decodeFilter(+ draft.op === "exists"+ ? { path, op: draft.op }+ : draft.op === "in"+ ? {+ path,+ op: draft.op,+ value: draft.value+ .split(",")+ .map((item) => item.trim())+ .filter((item) => item !== ""),+ }+ : { path, op: draft.op, value: draft.value },+ );+ if (Option.isNone(filter)) {+ return {+ error: `Filter ${index + 1} needs a path under body, headers or query${+ draft.op === "exists"+ ? "."+ : draft.op === "in"+ ? ", and at least one value."+ : ", and a value."+ }`,+ };+ }+ filters.push(filter.value);+ }+ return { filters };+}++/**+ * Whether a form's filter rows differ from the ones it opened with. A save+ * leaves `filters` out unless they did, so editing only the title can't+ * overwrite filters another device changed in the meantime.+ */+export function webhookFilterDraftsChanged(+ saved: ReadonlyArray<WebhookFilterDraft>,+ current: ReadonlyArray<WebhookFilterDraft>,+): boolean {+ return (+ saved.length !== current.length ||+ saved.some(+ (filter, index) =>+ filter.path !== current[index]?.path ||+ filter.op !== current[index]?.op ||+ (filter.op !== "exists" && filter.value !== current[index]?.value),+ )+ );+}diff --git a/packages/contracts/src/scheduledTask.test.ts b/packages/contracts/src/scheduledTask.test.tsindex c3373d08abf..61af412b055 100644--- a/packages/contracts/src/scheduledTask.test.ts+++ b/packages/contracts/src/scheduledTask.test.ts@@ -3,6 +3,7 @@ import * as Schema from "effect/Schema";import {MIN_SCHEDULED_TASK_INTERVAL_MS,+ ScheduledTaskListWebhookDeliveriesResult,ScheduledTaskSchedule,ScheduledTaskUpsertSchedule,} from "./scheduledTask.ts";@@ -50,3 +51,72 @@ describe("ScheduledTaskUpsertSchedule", () => {).toThrow();});});++describe("webhook filters", () => {+ const accepts = (filters: unknown) => {+ try {+ decodeUpsertSchedule({ type: "webhook", filters });+ return true;+ } catch {+ return false;+ }+ };++ it("keeps valid filters", () => {+ const filters = [+ { path: "headers.x-github-event", op: "equals", value: "pull_request" },+ { path: "body.action", op: "in", value: ["opened", "labeled"] },+ { path: "body.label.name", op: "startsWith", value: "agent:" },+ { path: "query.source", op: "exists" },+ ];+ expect(decodeUpsertSchedule({ type: "webhook", filters })).toEqual({+ type: "webhook",+ filters,+ });+ expect(decodeSchedule({ type: "webhook", signature: null, filters })).toMatchObject({+ filters,+ });+ });++ it("rejects empty or unknown paths, unknown ops, and values that do not fit the op", () => {+ expect(accepts([{ path: "", op: "exists" }])).toBe(false);+ expect(accepts([{ path: " ", op: "exists" }])).toBe(false);+ expect(accepts([{ path: "request", op: "exists" }])).toBe(false);+ expect(accepts([{ path: "header.x-github-event", op: "exists" }])).toBe(false);+ expect(accepts([{ path: "body.action", op: "in", value: "opened" }])).toBe(false);+ expect(accepts([{ path: "body.action", op: "in", value: [] }])).toBe(false);+ for (const value of ["", " opened", "opened ", "a,b"]) {+ expect(accepts([{ path: "body.action", op: "in", value: [value] }])).toBe(false);+ }+ expect(accepts([{ path: "body.label.name", op: "in", value: ["needs review"] }])).toBe(true);+ expect(accepts([{ path: "body.action", op: "equals" }])).toBe(false);+ expect(accepts([{ path: "body.action", op: "matches", value: "^opened$" }])).toBe(false);+ });++ it("allows at most 16 filters", () => {+ const sixteen = Array.from({ length: 16 }, () => ({ path: "body.action", op: "exists" }));+ expect(accepts(sixteen)).toBe(true);+ expect(accepts([...sixteen, { path: "body.action", op: "exists" }])).toBe(false);+ });+});++describe("ScheduledTaskWebhookDeliverySummary", () => {+ it("decodes an outcome this client does not know yet", () => {+ const summary = {+ id: "delivery:1",+ taskId: "scheduled-task:1",+ receivedAt: "2026-10-20T00:00:00.000Z",+ method: "POST",+ contentType: null,+ bodyBytes: 0,+ outcome: "some_future_outcome",+ signatureVerified: false,+ missingFields: [],+ error: null,+ };+ expect(+ Schema.decodeUnknownSync(ScheduledTaskListWebhookDeliveriesResult)({ deliveries: [summary] })+ .deliveries[0]?.outcome,+ ).toBe("some_future_outcome");+ });+});diff --git a/packages/contracts/src/scheduledTask.ts b/packages/contracts/src/scheduledTask.tsindex 9a24e1b8abe..77825113992 100644--- a/packages/contracts/src/scheduledTask.ts+++ b/packages/contracts/src/scheduledTask.ts@@ -83,12 +83,56 @@ const WebhookMaxDeliveryAgeMinutes = Schema.Int.check("Skip requests the relay held longer than this many minutes while the environment was offline. Null runs every request.",});+export const MAX_WEBHOOK_FILTERS = 16;++const WebhookFilterPath = TrimmedNonEmptyString.check(+ Schema.isPattern(/^(body|headers|query)(\.|$)/),+).annotate({+ description:+ "Request value to test, in placeholder syntax without braces: headers.x-github-event, body.action, query.source.",+});++/**+ * Forms edit an `in` list as comma-separated text, so a value that has no+ * comma and no surrounding whitespace survives that round trip unchanged.+ */+const WebhookFilterListValue = Schema.String.check(+ Schema.isPattern(/^[^,\s](?:[^,]*[^,\s])?$/),+).annotate({ description: "Non-empty, without commas or surrounding whitespace." });++export const ScheduledTaskWebhookFilter = Schema.Union([+ Schema.Struct({+ path: WebhookFilterPath,+ op: Schema.Literals(["equals", "notEquals", "startsWith"]),+ value: Schema.String,+ }),+ Schema.Struct({+ path: WebhookFilterPath,+ op: Schema.Literal("in"),+ value: Schema.Array(WebhookFilterListValue).check(Schema.isMinLength(1)),+ }),+ Schema.Struct({ path: WebhookFilterPath, op: Schema.Literal("exists") }),+]).annotate({+ description:+ "Scalars compare as strings; objects and arrays only satisfy 'exists'. Every op but 'exists' fails when the path is missing.",+});+export type ScheduledTaskWebhookFilter = typeof ScheduledTaskWebhookFilter.Type;+export type ScheduledTaskWebhookFilterOp = ScheduledTaskWebhookFilter["op"];++const ScheduledTaskWebhookFilters = Schema.Array(ScheduledTaskWebhookFilter)+ .check(Schema.isMaxLength(MAX_WEBHOOK_FILTERS))+ .annotate({+ description:+ "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.",+ });+const ScheduledTaskWebhookSchedule = Schema.Struct({type: Schema.Literal("webhook").annotate({description: "Run when the task's webhook URL receives a request.",}),signature: Schema.NullOr(ScheduledTaskWebhookSignature),maxDeliveryAgeMinutes: Schema.optional(Schema.NullOr(WebhookMaxDeliveryAgeMinutes)),+ filters: Schema.optional(ScheduledTaskWebhookFilters),}).annotate({description:"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({description: "Signature check; omit or null to accept requests by URL token only.",}),maxDeliveryAgeMinutes: Schema.optional(Schema.NullOr(WebhookMaxDeliveryAgeMinutes)),+ filters: Schema.optional(ScheduledTaskWebhookFilters),}).annotate({description:"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(["disabled","rate_limited","expired",+ "filtered",]);export type ScheduledTaskWebhookDeliveryOutcome = typeof ScheduledTaskWebhookDeliveryOutcome.Type;@@ -263,7 +309,8 @@ export const ScheduledTaskWebhookDeliverySummary = Schema.Struct({method: TrimmedNonEmptyString,contentType: Schema.NullOr(Schema.String),bodyBytes: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),- outcome: ScheduledTaskWebhookDeliveryOutcome,+ // Any string, so an outcome added later doesn't break a client's whole list.+ outcome: Schema.Union([ScheduledTaskWebhookDeliveryOutcome, Schema.String]),signatureVerified: Schema.Boolean,missingFields: Schema.Array(Schema.String),error: Schema.NullOr(Schema.String),@@ -282,6 +329,12 @@ export type ScheduledTaskWebhookDelivery = typeof ScheduledTaskWebhookDelivery.Texport const ScheduledTaskListWebhookDeliveriesInput = Schema.Struct({id: ScheduledTaskId,+ /**+ * Sent by clients that decode any outcome. Shipped clients decode a closed+ * list and fail on the whole response, so without it the server leaves out+ * rows with outcomes they don't know.+ */+ acceptAnyOutcome: Schema.optional(Schema.Boolean),});export type ScheduledTaskListWebhookDeliveriesInput =typeof ScheduledTaskListWebhookDeliveriesInput.Type;