Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8211: MUL-8209: feat(autopilots): payload conditions on webhook event filters (#9485)
Guillaumeed46a867d294
diff --git a/apps/docs/content/docs/autopilots.fr.mdx b/apps/docs/content/docs/autopilots.fr.mdxindex cee95840a6..71dabbcc78 100644--- a/apps/docs/content/docs/autopilots.fr.mdx+++ b/apps/docs/content/docs/autopilots.fr.mdx@@ -91,6 +91,25 @@ Lorsqu'une même source envoie plusieurs types d'événements, ajoutez des filtrPar exemple, avec `workflow_run` comme nom d'événement et `completed, failed` comme actions, seuls ces deux types de résultats `workflow_run` sont acceptés. Multica reconnaît l'événement et l'action à partir des en-têtes de requête et des champs de charge utile courants, notamment l'en-tête `X-GitHub-Event` de GitHub et le champ `action` du corps.+Chaque ligne peut aussi porter des `conditions` sur les champs de la charge utile : cliquez sur **Ajouter une condition** dans la ligne, ou définissez-les via l'API. Toutes les conditions doivent être vraies pour que la ligne corresponde ; un événement filtré est ignoré avant le démarrage de toute exécution. `path` parcourt la charge utile avec des points : un nombre indexe un tableau et `*` désigne n'importe quel élément (`pull_request.labels.*.name`). `op` vaut `equals`, `not_equals`, `contains`, `in` ou `exists`, et `ignore_case` s'applique au texte. Avec `*`, `equals`, `contains`, `in` et `exists` sont vraies si un élément correspond, et `not_equals` si aucun ne correspond. Un champ absent ne correspond jamais, et `exists` ignore `null`. Par exemple, cette ligne n'accepte que les pull requests prêtes, étiquetées `needs-review`, qui ciblent `main` ou `release` et n'ont pas été ouvertes par un bot :++```json+{+ "event": "pull_request",+ "actions": ["opened", "synchronize"],+ "conditions": [+ { "path": "pull_request.draft", "op": "equals", "value": false },+ { "path": "pull_request.labels.*.name", "op": "equals", "value": "needs-review" },+ { "path": "pull_request.base.ref", "op": "in", "values": ["main", "release"] },+ { "path": "sender.type", "op": "not_equals", "value": "Bot" }+ ]+}+```++Chaque règle accepte au maximum 20 conditions. Un chemin est limité à 256 caractères et une liste `in` à 100 valeurs. La création ou la modification d’un déclencheur avec une condition trop longue renvoie HTTP 400.++Un tableau vide développé par `*` satisfait `not_equals` ; un chemin absent échoue toujours. Les événements ou actions non correspondants sont enregistrés comme `event_filtered`, et les conditions non remplies comme `payload_filtered`. Les deux renvoient HTTP 200 sans créer d’exécution ni de tâche. La liste affiche la raison et le premier champ bloquant ; le détail affiche la condition et la valeur réelle enregistrées à la réception. Modifier la règle ne change pas cet instantané. L’aperçu est limité à 10 valeurs de 256 caractères ; le contenu brut conserve la valeur complète.+Vous pouvez aussi configurer entièrement ces filtres via le CLI avec `--event-filters-file`. Une mise à jour sans option de filtrage conserve les filtres existants ; `--clear-event-filters` les supprime explicitement et accepte tous les événements. Voir les [exemples CLI](/cli#webhook-event-filters) pour le format JSON et les commandes.### Protéger l'URL du webhookdiff --git a/apps/docs/content/docs/autopilots.ja.mdx b/apps/docs/content/docs/autopilots.ja.mdxindex 5d8bba93ea..48d5a5125a 100644--- a/apps/docs/content/docs/autopilots.ja.mdx+++ b/apps/docs/content/docs/autopilots.ja.mdx@@ -91,6 +91,25 @@ Webhook リクエストには次の制約があります。たとえばイベント名に `workflow_run`、Actions に `completed, failed` を指定すると、この 2 種類の `workflow_run` の結果だけを受け取ります。Multica は一般的なリクエストヘッダーと payload からイベントと action を判定します。GitHub の `X-GitHub-Event` と body の `action` にも対応しています。+各行には payload のフィールドに対する `conditions` も設定できます。行の **条件を追加** をクリックするか、API から設定します。すべての条件を満たしたときだけその行に一致し、除外されたイベントは実行が始まる前に無視されます。`path` はドット区切りで payload をたどり、数値は配列の添字、`*` は任意の要素を表します(`pull_request.labels.*.name`)。`op` は `equals`、`not_equals`、`contains`、`in`、`exists` のいずれかで、`ignore_case` はテキストに適用されます。`*` を使う場合、`equals`、`contains`、`in`、`exists` はいずれかの要素が一致すれば成立し、`not_equals` はどの要素も一致しないときに成立します。フィールドが存在しない場合は一致せず、`exists` は `null` を無視します。たとえば次の行は、準備ができていて `needs-review` ラベルが付き、`main` または `release` を対象とし、bot が作成したものではない pull request だけを受け取ります。++```json+{+ "event": "pull_request",+ "actions": ["opened", "synchronize"],+ "conditions": [+ { "path": "pull_request.draft", "op": "equals", "value": false },+ { "path": "pull_request.labels.*.name", "op": "equals", "value": "needs-review" },+ { "path": "pull_request.base.ref", "op": "in", "values": ["main", "release"] },+ { "path": "sender.type", "op": "not_equals", "value": "Bot" }+ ]+}+```++ルールごとに条件は最大 20 個、フィールドのパスは 256 文字、`in` の候補リストは 100 個までです。上限を超える条件でトリガーを作成・更新すると HTTP 400 が返されます。++`*` が空の配列を展開した場合、`not_equals` は成立します。パスが存在しない場合は一致しません。イベントやアクションの不一致は `event_filtered`、本文の条件不一致は `payload_filtered` として記録されます。どちらも HTTP 200 を返し、実行やタスクを作成しません。配信一覧には理由と最初に一致しなかったフィールドを表示し、詳細には受信時の条件と実際の値を表示します。後からルールを変更してもこの記録は変わりません。プレビューは最大 10 個の値、各 256 文字です。完全な値は元の本文で確認できます。+CLI の `--event-filters-file` でも、これらのフィルターをすべて設定できます。更新時にフィルターオプションを省略すると既存の設定を保持し、`--clear-event-filters` を指定すると明示的に削除して全イベントを受け入れます。JSON 形式とコマンドは [CLI の例](/cli#webhook-event-filters)を参照してください。### Webhook URL を保護するdiff --git a/apps/docs/content/docs/autopilots.ko.mdx b/apps/docs/content/docs/autopilots.ko.mdxindex bc5a151557..0a6eb0910e 100644--- a/apps/docs/content/docs/autopilots.ko.mdx+++ b/apps/docs/content/docs/autopilots.ko.mdx@@ -91,6 +91,25 @@ Webhook 요청에는 다음 제약이 있습니다.예를 들어 이벤트 이름에 `workflow_run`, Actions에 `completed, failed`를 입력하면 이 두 종류의 `workflow_run` 결과만 받습니다. Multica는 GitHub의 `X-GitHub-Event`와 body의 `action`을 포함해 일반적인 요청 header와 payload에서 이벤트와 action을 식별합니다.+각 줄에는 payload 필드에 대한 `conditions`도 지정할 수 있습니다. 줄의 **조건 추가**을 클릭하거나 API로 설정하세요. 모든 조건을 만족해야 해당 줄이 일치하며, 걸러진 이벤트는 실행이 시작되기 전에 무시됩니다. `path`는 점으로 payload를 따라가며, 숫자는 배열 인덱스이고 `*`는 임의의 요소를 뜻합니다(`pull_request.labels.*.name`). `op`는 `equals`, `not_equals`, `contains`, `in`, `exists` 중 하나이며, `ignore_case`는 텍스트에 적용됩니다. `*`를 쓰면 `equals`, `contains`, `in`, `exists`는 요소 하나라도 일치하면 성립하고, `not_equals`는 어떤 요소도 일치하지 않을 때 성립합니다. 필드가 없으면 일치하지 않으며, `exists`는 `null`을 무시합니다. 예를 들어 아래 줄은 준비된 상태이고 `needs-review` 라벨이 있으며 `main` 또는 `release`를 대상으로 하고 봇이 열지 않은 pull request만 받습니다.++```json+{+ "event": "pull_request",+ "actions": ["opened", "synchronize"],+ "conditions": [+ { "path": "pull_request.draft", "op": "equals", "value": false },+ { "path": "pull_request.labels.*.name", "op": "equals", "value": "needs-review" },+ { "path": "pull_request.base.ref", "op": "in", "values": ["main", "release"] },+ { "path": "sender.type", "op": "not_equals", "value": "Bot" }+ ]+}+```++규칙당 조건은 최대 20개, 필드 경로는 256자, `in` 후보 목록은 100개까지입니다. 한도를 초과하는 조건으로 트리거를 만들거나 수정하면 HTTP 400을 반환합니다.++`*`가 빈 배열을 펼치면 `not_equals`는 충족됩니다. 경로가 없으면 일치하지 않습니다. 이벤트나 동작 불일치는 `event_filtered`, 본문 조건 불충족은 `payload_filtered`로 기록합니다. 모두 HTTP 200을 반환하며 실행이나 태스크를 만들지 않습니다. 목록에는 이유와 첫 번째 불일치 필드를 표시하고, 상세에는 수신 당시 저장한 조건과 실제 값을 표시합니다. 나중에 규칙을 바꿔도 이 기록은 유지됩니다. 미리보기는 값 10개, 각 256자로 제한됩니다. 전체 값은 원본 본문에서 확인하세요.+CLI의 `--event-filters-file`로도 이 필터들을 모두 설정할 수 있습니다. 업데이트할 때 필터 옵션을 생략하면 기존 설정이 유지되고, `--clear-event-filters`를 지정하면 필터를 명시적으로 삭제하여 모든 이벤트를 받습니다. JSON 형식과 명령은 [CLI 예시](/cli#webhook-event-filters)를 참고하세요.### Webhook URL 보호diff --git a/apps/docs/content/docs/autopilots.mdx b/apps/docs/content/docs/autopilots.mdxindex d91bf38a10..ceb22a9d71 100644--- a/apps/docs/content/docs/autopilots.mdx+++ b/apps/docs/content/docs/autopilots.mdx@@ -91,6 +91,25 @@ When one source sends several event types, add event filters to the trigger. EacFor example, with `workflow_run` as the event name and `completed, failed` as the actions, only those two kinds of `workflow_run` results are accepted. Multica recognizes the event and action from common request headers and payload fields, including GitHub's `X-GitHub-Event` and the `action` field in the body.+Each row can also carry `conditions` on payload fields: click **Add condition** on the row, or set them through the API. Every condition must hold for the row to match; a filtered event is ignored before any run starts. `path` walks the payload with dots, where a number indexes an array and `*` means any element (`pull_request.labels.*.name`). `op` is `equals`, `not_equals`, `contains`, `in` or `exists`, and `ignore_case` applies to text. With `*`, `equals`, `contains`, `in` and `exists` hold if any element matches, and `not_equals` holds if none does. A missing field never matches, and `exists` ignores `null`. For example, this row only accepts ready pull requests labelled `needs-review` that target `main` or `release` and weren't opened by a bot:++```json+{+ "event": "pull_request",+ "actions": ["opened", "synchronize"],+ "conditions": [+ { "path": "pull_request.draft", "op": "equals", "value": false },+ { "path": "pull_request.labels.*.name", "op": "equals", "value": "needs-review" },+ { "path": "pull_request.base.ref", "op": "in", "values": ["main", "release"] },+ { "path": "sender.type", "op": "not_equals", "value": "Bot" }+ ]+}+```++Each rule supports up to 20 conditions. A field path can contain at most 256 characters, and an `in` list can contain at most 100 values. Creating or updating a trigger with an oversized condition returns HTTP 400.++An empty array expanded by `*` satisfies `not_equals`; a missing path still fails. Event/action mismatches are recorded as `event_filtered`; matching events whose payload conditions fail are recorded as `payload_filtered`. Both return HTTP 200 without creating a run or issue. The delivery list shows the reason and first failing field; the detail shows the saved condition and actual value at receipt. Changing the trigger later does not change this snapshot. Previews are limited to 10 values of 256 characters each; open the raw body for the full value.+You can also configure these filters entirely through the CLI with `--event-filters-file`. Updating without either filter option preserves existing filters; `--clear-event-filters` explicitly removes them and accepts all events. See the [CLI examples](/cli#webhook-event-filters) for the JSON format and commands.### Protect the webhook URLdiff --git a/apps/docs/content/docs/autopilots.zh-Hant.mdx b/apps/docs/content/docs/autopilots.zh-Hant.mdxindex 12ef86af94..214e4e28a5 100644--- a/apps/docs/content/docs/autopilots.zh-Hant.mdx+++ b/apps/docs/content/docs/autopilots.zh-Hant.mdx@@ -91,6 +91,22 @@ Webhook 請求的約束:例如,事件名填寫 `workflow_run`,Actions 填寫 `completed, failed`,只會接收這兩類 `workflow_run` 結果。Multica 會從常見請求頭和 payload 中識別事件與 action,包括 GitHub 的 `X-GitHub-Event` 和 body 中的 `action`。+每行還可以設定針對本文欄位的 `conditions`:點選 **新增條件**,或透過 API 設定。同一行的全部條件都要符合,多行之間符合任意一行即可。`path` 用點號存取事件本文,數字表示陣列索引,`*` 表示任意元素(例如 `pull_request.labels.*.name`)。操作支援 `equals`、`not_equals`、`contains`、`in` 和 `exists`,`ignore_case` 忽略文字大小寫。使用 `*` 時,前四種操作中除 `not_equals` 外,只要有一個元素符合即可;`not_equals` 要求沒有元素等於指定值。`exists` 忽略 `null`。字串與布林值必須使用正確類型,例如 `"false"` 與 `false` 不同。++```json+{+ "event": "pull_request",+ "conditions": [+ { "path": "pull_request.draft", "op": "equals", "value": false },+ { "path": "pull_request.base.ref", "op": "equals", "value": "main" }+ ]+}+```++每條規則最多 20 個條件,欄位路徑最多 256 個字元,`in` 候選值清單最多 100 項。建立或更新觸發器時,超出上限的條件會回傳 HTTP 400。++`*` 展開空陣列時,`not_equals` 成立;路徑不存在時仍不符。事件或動作不符記為 `event_filtered`,事件符合但本文條件不符記為 `payload_filtered`。兩者都回傳 HTTP 200,不建立執行或任務。投遞清單顯示原因和第一個不符合條件的欄位,詳情顯示接收時儲存的條件及實際值。之後修改規則不會改變這份記錄。預覽最多顯示 10 個值,每個值最多 256 個字元;完整值請見原始本文。+也可以透過 CLI 的 `--event-filters-file` 完整配置這些條件。更新時不傳過濾引數就保留原值;`--clear-event-filters` 明確清空條件、恢復接收所有事件。JSON 格式和命令見 [CLI 範例](/cli#webhook-event-filters)。### 保護 Webhook URLdiff --git a/apps/docs/content/docs/autopilots.zh.mdx b/apps/docs/content/docs/autopilots.zh.mdxindex 31f9184457..5a5c7a90a5 100644--- a/apps/docs/content/docs/autopilots.zh.mdx+++ b/apps/docs/content/docs/autopilots.zh.mdx@@ -91,6 +91,25 @@ Webhook 请求的约束:例如,事件名填写 `workflow_run`,Actions 填写 `completed, failed`,只会接收这两类 `workflow_run` 结果。Multica 会从常见请求头和 payload 中识别事件与 action,包括 GitHub 的 `X-GitHub-Event` 和 body 中的 `action`。+每行还可以设置针对 payload 字段的 `conditions`:点击该行的 **添加条件**,或通过 API 设置。所有条件都满足时该行才命中;被过滤的事件在任何运行开始前就会被忽略。`path` 用点号访问 payload,数字表示数组下标,`*` 表示任意元素(`pull_request.labels.*.name`)。`op` 可选 `equals`、`not_equals`、`contains`、`in` 或 `exists`,`ignore_case` 作用于文本。使用 `*` 时,`equals`、`contains`、`in` 和 `exists` 只要有一个元素匹配即成立,`not_equals` 要求没有任何元素匹配。字段不存在时永远不命中,`exists` 会忽略 `null`。例如,下面这一行只接收已就绪、带有 `needs-review` 标签、目标分支为 `main` 或 `release`、且不是由机器人创建的 pull request:++```json+{+ "event": "pull_request",+ "actions": ["opened", "synchronize"],+ "conditions": [+ { "path": "pull_request.draft", "op": "equals", "value": false },+ { "path": "pull_request.labels.*.name", "op": "equals", "value": "needs-review" },+ { "path": "pull_request.base.ref", "op": "in", "values": ["main", "release"] },+ { "path": "sender.type", "op": "not_equals", "value": "Bot" }+ ]+}+```++每条规则最多 20 个条件,字段路径最多 256 个字符,`in` 候选值列表最多 100 项。创建或更新触发器时,超出上限的条件会返回 HTTP 400。++`*` 展开空数组时,`not_equals` 成立;路径不存在时仍不命中。事件或动作不匹配记为 `event_filtered`,事件匹配但正文条件不满足记为 `payload_filtered`。两者都返回 HTTP 200,不创建运行或任务。投递列表显示原因和第一个不满足条件的字段,详情显示接收时保存的条件及实际值。之后修改规则不会改变这份记录。预览最多显示 10 个值,每个值最多 256 个字符;完整值见原始正文。+也可以通过 CLI 的 `--event-filters-file` 完整配置这些条件。更新时不传过滤参数就保留原值;`--clear-event-filters` 明确清空条件、恢复接收所有事件。JSON 格式和命令见 [CLI 示例](/cli#webhook-event-filters)。### 保护 Webhook URLdiff --git a/apps/docs/content/docs/cli.fr.mdx b/apps/docs/content/docs/cli.fr.mdxindex 097edd586e..e0a9feed2c 100644--- a/apps/docs/content/docs/cli.fr.mdx+++ b/apps/docs/content/docs/cli.fr.mdx@@ -346,6 +346,20 @@ Utilisez `--event-filters-file` avec `autopilot trigger-add` ou `trigger-update`]```+Chaque ligne peut aussi contenir des `conditions`, avec les mêmes règles sur la charge utile que dans l’application. Par exemple, cette règle accepte les pull requests non brouillon ciblant `main` :++```json+{+ "event": "pull_request",+ "conditions": [+ { "path": "pull_request.draft", "op": "equals", "value": false },+ { "path": "pull_request.base.ref", "op": "equals", "value": "main" }+ ]+}+```++Chaque règle accepte au maximum 20 conditions. Un chemin est limité à 256 caractères et une liste `in` à 100 valeurs. La création ou la modification d’un déclencheur avec une condition trop longue renvoie HTTP 400.+Cet exemple accepte les soumissions de revues de PR et tous les événements push. Omettre `actions` ou fournir un tableau d'actions vide accepte toutes les actions de cet événement.```bashdiff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdxindex ed6d899375..cbb6ad7e9b 100644--- a/apps/docs/content/docs/cli.ja.mdx+++ b/apps/docs/content/docs/cli.ja.mdx@@ -346,6 +346,20 @@ multica autopilot trigger-add <autopilot-id> --cron "0 9 * * 1" --timezone Asia/]```+各行にはアプリと同じ本文フィールドの `conditions` も指定できます。例えば、次のルールは `main` を対象とするドラフト以外の PR のみ受け付けます:++```json+{+ "event": "pull_request",+ "conditions": [+ { "path": "pull_request.draft", "op": "equals", "value": false },+ { "path": "pull_request.base.ref", "op": "equals", "value": "main" }+ ]+}+```++ルールごとに条件は最大 20 個、フィールドのパスは 256 文字、`in` の候補リストは 100 個までです。上限を超える条件でトリガーを作成・更新すると HTTP 400 が返されます。+この例では、PR レビューの送信とすべての push イベントを受け入れます。`actions` を省略するか空の配列を指定すると、そのイベントのすべての action を受け入れます。```bashdiff --git a/apps/docs/content/docs/cli.ko.mdx b/apps/docs/content/docs/cli.ko.mdxindex 33c022ced6..aa1e543df4 100644--- a/apps/docs/content/docs/cli.ko.mdx+++ b/apps/docs/content/docs/cli.ko.mdx@@ -346,6 +346,20 @@ multica autopilot trigger-add <autopilot-id> --cron "0 9 * * 1" --timezone Asia/]```+각 행에는 앱과 같은 본문 필드 규칙을 사용하는 `conditions`도 지정할 수 있습니다. 예를 들어 다음 규칙은 `main`을 대상으로 하는 초안이 아닌 PR만 수락합니다:++```json+{+ "event": "pull_request",+ "conditions": [+ { "path": "pull_request.draft", "op": "equals", "value": false },+ { "path": "pull_request.base.ref", "op": "equals", "value": "main" }+ ]+}+```++규칙당 조건은 최대 20개, 필드 경로는 256자, `in` 후보 목록은 100개까지입니다. 한도를 초과하는 조건으로 트리거를 만들거나 수정하면 HTTP 400을 반환합니다.+이 예시는 PR 리뷰 제출과 모든 push 이벤트를 받습니다. `actions`를 생략하거나 빈 배열을 지정하면 해당 이벤트의 모든 action을 받습니다.```bashdiff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex 951160112e..31102e454d 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -361,6 +361,20 @@ Use `--event-filters-file` on `autopilot trigger-add` or `trigger-update` to con]```+Each row may also include `conditions`, using the same payload-field rules as the app. For example, this row accepts only non-draft pull requests targeting `main`:++```json+{+ "event": "pull_request",+ "conditions": [+ { "path": "pull_request.draft", "op": "equals", "value": false },+ { "path": "pull_request.base.ref", "op": "equals", "value": "main" }+ ]+}+```++Each rule supports up to 20 conditions. A field path can contain at most 256 characters, and an `in` list can contain at most 100 values. Creating or updating a trigger with an oversized condition returns HTTP 400.+This accepts PR review submissions and all push events. Omitting `actions` or using an empty actions array accepts every action for that event.```bashdiff --git a/apps/docs/content/docs/cli.zh-Hant.mdx b/apps/docs/content/docs/cli.zh-Hant.mdxindex 5ec180d5e7..2e4a0e6000 100644--- a/apps/docs/content/docs/cli.zh-Hant.mdx+++ b/apps/docs/content/docs/cli.zh-Hant.mdx@@ -343,6 +343,20 @@ multica autopilot trigger-add <autopilot-id> --cron "0 9 * * 1" --timezone Asia/]```+每行還可以包含 `conditions`,使用與介面相同的本文欄位規則。例如,下面的規則只接收目標分支為 `main` 的非草稿 PR:++```json+{+ "event": "pull_request",+ "conditions": [+ { "path": "pull_request.draft", "op": "equals", "value": false },+ { "path": "pull_request.base.ref", "op": "equals", "value": "main" }+ ]+}+```++每條規則最多 20 個條件,欄位路徑最多 256 個字元,`in` 候選值清單最多 100 項。建立或更新觸發器時,超出上限的條件會回傳 HTTP 400。+這個範例接收 PR 評審提交和所有 push 事件。省略 `actions` 或使用空的 actions 陣列,表示接收該事件的所有 action。```bashdiff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdxindex 50edf9a5fe..da335db5e0 100644--- a/apps/docs/content/docs/cli.zh.mdx+++ b/apps/docs/content/docs/cli.zh.mdx@@ -346,6 +346,20 @@ multica autopilot trigger-add <autopilot-id> --cron "0 9 * * 1" --timezone Asia/]```+每行还可以包含 `conditions`,使用与界面相同的正文字段规则。例如,下面的规则只接收目标分支为 `main` 的非草稿 PR:++```json+{+ "event": "pull_request",+ "conditions": [+ { "path": "pull_request.draft", "op": "equals", "value": false },+ { "path": "pull_request.base.ref", "op": "equals", "value": "main" }+ ]+}+```++每条规则最多 20 个条件,字段路径最多 256 个字符,`in` 候选值列表最多 100 项。创建或更新触发器时,超出上限的条件会返回 HTTP 400。+这个示例接收 PR 评审提交和所有 push 事件。省略 `actions` 或使用空的 actions 数组,表示接收该事件的所有 action。```bashdiff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex a4a4a43e00..ca88690749 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -675,6 +675,12 @@ function assertAgentConversationStartersWriteSupported(data: {}}+function assertWebhookPayloadConditionsWriteSupported(data: Pick<UpdateAutopilotTriggerRequest, "event_filters">): void {+ if (data.event_filters?.some((filter) => filter.conditions?.length) && !configStore.getState().webhookPayloadConditionsSupported) {+ throw new Error("This server version does not support webhook payload conditions. Update the server before saving them.");+ }+}+function requestedIssueCreateProperties(data: CreateIssueRequest,): NonNullable<CreateIssueRequest["properties"]> | undefined {@@ -5323,6 +5329,7 @@ export class ApiClient {}async createAutopilotTrigger(autopilotId: string, data: CreateAutopilotTriggerRequest): Promise<AutopilotTrigger> {+ assertWebhookPayloadConditionsWriteSupported(data);return this.fetch(`/api/autopilots/${autopilotId}/triggers`, {method: "POST",body: JSON.stringify(data),@@ -5330,6 +5337,7 @@ export class ApiClient {}async updateAutopilotTrigger(autopilotId: string, triggerId: string, data: UpdateAutopilotTriggerRequest): Promise<AutopilotTrigger> {+ assertWebhookPayloadConditionsWriteSupported(data);return this.fetch(`/api/autopilots/${autopilotId}/triggers/${triggerId}`, {method: "PATCH",body: JSON.stringify(data),diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 5d34e5a24f..7005e03f96 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1067,6 +1067,7 @@ export interface AppConfigResponse {/** Whether agent create/update persists `conversation_starters`. Older servers* silently ignored the unknown field, so absent must be treated as false. */agent_conversation_starters_supported?: boolean;+ webhook_payload_conditions_supported?: boolean;/** Whether issue create atomically validates and persists `properties`.* Older servers silently ignore the field, so absent means unsupported. */issue_create_properties_supported?: boolean;@@ -1364,6 +1365,7 @@ export const AppConfigSchema = z.object({feature_flags: FeatureFlagsSchema,local_worktree_supported: BooleanWithDefaultSchema(false),agent_conversation_starters_supported: BooleanWithDefaultSchema(false),+ webhook_payload_conditions_supported: BooleanWithDefaultSchema(false),issue_create_properties_supported: BooleanWithDefaultSchema(false),comment_delete_keep_replies_supported: BooleanWithDefaultSchema(false),theme_store_enabled: BooleanWithDefaultSchema(false),@@ -1386,6 +1388,7 @@ export const EMPTY_APP_CONFIG: AppConfigResponse = {local_worktree_supported: false,// Fail closed: old servers returned success while dropping the field.agent_conversation_starters_supported: false,+ webhook_payload_conditions_supported: false,// Fail closed: old servers returned success while dropping create properties.issue_create_properties_supported: false,// Fail closed: old servers delete a comment's replies with it.@@ -2936,6 +2939,21 @@ export interface DuplicateIssueErrorBody {// the empty array. `.loose()` lets unknown fields pass through, matching// the rule used by every other endpoint here.+const WebhookPayloadConditionFailureSchema = z.object({+ filter_index: z.number().int().nonnegative(),+ condition_index: z.number().int().nonnegative(),+ condition: z.object({+ path: z.string(),+ op: z.enum(["equals", "not_equals", "contains", "in", "exists"]),+ value: z.union([z.string(), z.number(), z.boolean()]).optional(),+ values: z.array(z.union([z.string(), z.number(), z.boolean()])).optional(),+ ignore_case: z.boolean().optional(),+ }).loose(),+ actual_values: z.array(z.string()),+ missing: z.boolean(),+ truncated: z.boolean(),+}).loose();+const WebhookDeliverySchema = z.object({id: z.string(),workspace_id: z.string(),@@ -2958,6 +2976,7 @@ const WebhookDeliverySchema = z.object({replayed_from_delivery_id: z.string().nullable(),error: z.string().nullable(),reason_code: z.string().nullable().default(null),+ payload_condition_failure: WebhookPayloadConditionFailureSchema.nullish().catch(null),replay_idempotency_key: z.string().nullable().default(null),received_at: z.string(),last_attempt_at: z.string(),diff --git a/packages/core/api/webhook-delivery-schema.test.ts b/packages/core/api/webhook-delivery-schema.test.tsnew file mode 100644index 0000000000..74d684e545--- /dev/null+++ b/packages/core/api/webhook-delivery-schema.test.ts@@ -0,0 +1,31 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { AppConfigSchema, EMPTY_WEBHOOK_DELIVERY, ListWebhookDeliveriesResponseSchema, WebhookDeliveryResponseSchema } from "./schemas";++describe("webhook delivery filter diagnostics", () => {+ it("requires explicit backend support before enabling payload conditions", () => {+ expect(AppConfigSchema.parse({}).webhook_payload_conditions_supported).toBe(false);+ expect(AppConfigSchema.parse({ webhook_payload_conditions_supported: "yes" }).webhook_payload_conditions_supported).toBe(false);+ expect(AppConfigSchema.parse({ webhook_payload_conditions_supported: true }).webhook_payload_conditions_supported).toBe(true);+ });+ const failure = {+ filter_index: 0, condition_index: 1,+ condition: { path: "pull_request.base.ref", op: "equals", value: "main" },+ actual_values: ['"dev"'], missing: false, truncated: false,+ };++ it("preserves the admission snapshot in list and detail responses", () => {+ const delivery = { ...EMPTY_WEBHOOK_DELIVERY, status: "ignored", reason_code: "payload_filtered", payload_condition_failure: failure };+ expect(WebhookDeliveryResponseSchema.parse(delivery).payload_condition_failure).toEqual(failure);+ expect(ListWebhookDeliveriesResponseSchema.parse({ deliveries: [delivery] }).deliveries[0]?.payload_condition_failure).toEqual(failure);+ });++ it("reads older servers and drops malformed diagnostics without losing the delivery", () => {+ expect(WebhookDeliveryResponseSchema.parse(EMPTY_WEBHOOK_DELIVERY).payload_condition_failure).toBeUndefined();+ for (const malformed of [{}, { ...failure, actual_values: [42] }, { ...failure, condition: { path: "x", op: "future_operator" } }]) {+ const parsed = WebhookDeliveryResponseSchema.parse({ ...EMPTY_WEBHOOK_DELIVERY, id: "kept", payload_condition_failure: malformed });+ expect(parsed.id).toBe("kept");+ expect(parsed.payload_condition_failure).toBeNull();+ }+ });+});diff --git a/packages/core/api/webhook-payload-compatibility.test.ts b/packages/core/api/webhook-payload-compatibility.test.tsnew file mode 100644index 0000000000..b21ccdbb3a--- /dev/null+++ b/packages/core/api/webhook-payload-compatibility.test.ts@@ -0,0 +1,35 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from "vitest";+import { ApiClient } from "./client";+import { configStore } from "../config";++afterEach(() => {+ configStore.getState().setWebhookPayloadConditionsSupported(false);+ vi.unstubAllGlobals();+});++describe("webhook payload condition compatibility", () => {+ const filters = [{ event: "pull_request", conditions: [{ path: "draft", op: "equals" as const, value: false }] }];++ it("refuses condition writes before an older backend can silently drop them", async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ const client = new ApiClient("https://api.example.test");+ await expect(client.createAutopilotTrigger("ap", { kind: "webhook", event_filters: filters })).rejects.toThrow(/does not support webhook payload conditions/);+ await expect(client.updateAutopilotTrigger("ap", "tr", { event_filters: filters })).rejects.toThrow(/does not support webhook payload conditions/);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("allows supported condition writes and keeps old event-only writes working", async () => {+ const fetchMock = vi.fn().mockImplementation(async () => new Response('{"id":"tr"}', { status: 200, headers: { "Content-Type": "application/json" } }));+ vi.stubGlobal("fetch", fetchMock);+ const client = new ApiClient("https://api.example.test");+ await client.createAutopilotTrigger("ap", { kind: "webhook", event_filters: [{ event: "push" }] });+ await client.updateAutopilotTrigger("ap", "tr", { event_filters: [] });+ configStore.getState().setWebhookPayloadConditionsSupported(true);+ await client.createAutopilotTrigger("ap", { kind: "webhook", event_filters: filters });+ await client.updateAutopilotTrigger("ap", "tr", { event_filters: filters });+ expect(JSON.parse(String(fetchMock.mock.calls[2]?.[1]?.body)).event_filters).toEqual(filters);+ expect(JSON.parse(String(fetchMock.mock.calls[3]?.[1]?.body)).event_filters).toEqual(filters);+ });+});diff --git a/packages/core/config/index.ts b/packages/core/config/index.tsindex 40e8644239..46960ff99e 100644--- a/packages/core/config/index.ts+++ b/packages/core/config/index.ts@@ -40,6 +40,7 @@ interface ConfigState {// Older handlers accepted the unknown field and returned success while// dropping it, so absent must fail closed.agentConversationStartersSupported: boolean;+ webhookPayloadConditionsSupported: boolean;// Whether POST /api/issues atomically persists custom-property values.// Older servers silently drop the field, so absent must fail closed.issueCreatePropertiesSupported: boolean;@@ -69,6 +70,7 @@ interface ConfigState {setServerVersion: (version?: string) => void;setLocalWorktreeSupported: (supported?: boolean) => void;setAgentConversationStartersSupported: (supported?: boolean) => void;+ setWebhookPayloadConditionsSupported: (supported?: boolean) => void;setIssueCreatePropertiesSupported: (supported?: boolean) => void;setCommentDeleteKeepRepliesSupported: (supported?: boolean) => void;setThemeStoreEnabled: (enabled?: boolean) => void;@@ -90,6 +92,7 @@ export const configStore = createStore<ConfigState>((set) => ({serverVersion: "",localWorktreeSupported: false,agentConversationStartersSupported: false,+ webhookPayloadConditionsSupported: false,issueCreatePropertiesSupported: false,commentDeleteKeepRepliesSupported: false,themeStoreEnabled: false,@@ -118,6 +121,8 @@ export const configStore = createStore<ConfigState>((set) => ({set({ localWorktreeSupported: supported === true }),setAgentConversationStartersSupported: (supported = false) =>set({ agentConversationStartersSupported: supported === true }),+ setWebhookPayloadConditionsSupported: (supported = false) =>+ set({ webhookPayloadConditionsSupported: supported === true }),setIssueCreatePropertiesSupported: (supported = false) =>set({ issueCreatePropertiesSupported: supported === true }),setCommentDeleteKeepRepliesSupported: (supported = false) =>diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsxindex bbbb883f31..feec330b73 100644--- a/packages/core/platform/auth-initializer.tsx+++ b/packages/core/platform/auth-initializer.tsx@@ -100,6 +100,11 @@ export function AuthInitializer({// Older agent handlers returned success while silently dropping this// additive field, so writes stay disabled unless the server declares// the persistence contract explicitly.+ configStore+ .getState()+ .setWebhookPayloadConditionsSupported(+ cfg.webhook_payload_conditions_supported === true,+ );configStore.getState().setAgentConversationStartersSupported(diff --git a/packages/core/types/autopilot.ts b/packages/core/types/autopilot.tsindex 8ef32f9102..8274241406 100644--- a/packages/core/types/autopilot.ts+++ b/packages/core/types/autopilot.ts@@ -64,9 +64,24 @@ export interface Autopilot {can_manage_access?: boolean;}+export type WebhookPayloadConditionValue = string | number | boolean;++// A payload condition tests one field of the webhook body. `path` walks+// objects with dots; numeric segments index arrays and `*` matches any+// element. A missing path never matches.+export interface WebhookPayloadCondition {+ path: string;+ op: "equals" | "not_equals" | "contains" | "in" | "exists";+ value?: WebhookPayloadConditionValue;+ values?: WebhookPayloadConditionValue[];+ ignore_case?: boolean;+}+export interface WebhookEventFilter {event: string;actions?: string[];+ // Every condition must hold for the filter to match.+ conditions?: WebhookPayloadCondition[];}export interface AutopilotSubscriber {@@ -243,6 +258,15 @@ export type WebhookSignatureStatus =| "invalid"| "missing";+export interface WebhookPayloadConditionFailure {+ filter_index: number;+ condition_index: number;+ condition: WebhookPayloadCondition;+ actual_values: string[];+ missing: boolean;+ truncated: boolean;+}+export interface WebhookDelivery {id: string;workspace_id: string;@@ -263,6 +287,7 @@ export interface WebhookDelivery {replayed_from_delivery_id: string | null;error: string | null;reason_code: string | null;+ payload_condition_failure?: WebhookPayloadConditionFailure | null;replay_idempotency_key: string | null;received_at: string;last_attempt_at: string;diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 6908946270..f2ea2b696e 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -351,6 +351,9 @@ export type {AutopilotRunSource,AutopilotQuotaUsage,WebhookEventFilter,+ WebhookPayloadCondition,+ WebhookPayloadConditionFailure,+ WebhookPayloadConditionValue,CreateAutopilotRequest,UpdateAutopilotRequest,CreateAutopilotTriggerRequest,diff --git a/packages/views/autopilots/components/autopilot-dialog.tsx b/packages/views/autopilots/components/autopilot-dialog.tsxindex c33317d40c..aaf2dfe583 100644--- a/packages/views/autopilots/components/autopilot-dialog.tsx+++ b/packages/views/autopilots/components/autopilot-dialog.tsx@@ -117,11 +117,16 @@ const OUTPUT_MODE_ICONS: Record<AutopilotExecutionMode, typeof FilePlus2> = {// serializeEventFilters returns a stable JSON string so the edit-mode dirty// check can compare the current filters against the snapshot taken on open-// without depending on reference equality. Normalizes empty Actions to []-// so omitted-vs-explicit-empty doesn't show as a phantom change.+// without depending on reference equality. Normalizes empty Actions and+// Conditions to [] so omitted-vs-explicit-empty doesn't show as a phantom+// change.function serializeEventFilters(filters: WebhookEventFilter[]): string {return JSON.stringify(- filters.map((f) => ({ event: f.event, actions: f.actions ?? [] })),+ filters.map((f) => ({+ event: f.event,+ actions: f.actions ?? [],+ conditions: f.conditions ?? [],+ })),);}diff --git a/packages/views/autopilots/components/webhook-deliveries-section.test.tsx b/packages/views/autopilots/components/webhook-deliveries-section.test.tsxnew file mode 100644index 0000000000..6cfd1afb01--- /dev/null+++ b/packages/views/autopilots/components/webhook-deliveries-section.test.tsx@@ -0,0 +1,54 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { screen, fireEvent, within } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import { api } from "@multica/core/api";+import { EMPTY_WEBHOOK_DELIVERY } from "@multica/core/api/schemas";+import type { WebhookDelivery } from "@multica/core/types";+import { renderWithI18n } from "../../test/i18n";+import { WebhookDeliveriesSection } from "./webhook-deliveries-section";++vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws" }));+vi.mock("@multica/core/api", () => ({ api: { listAutopilotDeliveries: vi.fn(), getAutopilotDelivery: vi.fn() } }));++function renderDelivery(delivery: WebhookDelivery) {+ vi.mocked(api.listAutopilotDeliveries).mockResolvedValue({ deliveries: [delivery], total: 1 });+ vi.mocked(api.getAutopilotDelivery).mockResolvedValue(delivery);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return renderWithI18n(+ <QueryClientProvider client={client}>+ <WebhookDeliveriesSection autopilotId="ap" hasWebhookTrigger />+ </QueryClientProvider>,+ );+}++describe("WebhookDeliveriesSection", () => {+ it("shows the failed field in the list and expected/actual typed values in a neutral detail section", async () => {+ renderDelivery({+ ...EMPTY_WEBHOOK_DELIVERY, id: "d", status: "ignored", reason_code: "payload_filtered", error: "payload_filtered: pull_request.base.ref",+ payload_condition_failure: {+ filter_index: 0, condition_index: 0,+ condition: { path: "pull_request.base.ref", op: "equals", value: "main" },+ actual_values: ['"dev"'], missing: false, truncated: false,+ },+ });+ fireEvent.click(await screen.findByRole("button", { name: /Payload conditions not met · pull_request.base.ref/ }));+ const reason = await screen.findByRole("region", { name: "Ignore reason" });+ expect(reason).toHaveTextContent('pull_request.base.ref is "main"');+ expect(reason).toHaveTextContent('Actual value"dev"');+ expect(screen.queryByText("Error", { exact: true })).not.toBeInTheDocument();+ });++ it("supports an older server's event-filtered reason without a condition snapshot", async () => {+ renderDelivery({ ...EMPTY_WEBHOOK_DELIVERY, id: "old", status: "ignored", error: "event_filtered" });+ fireEvent.click(await screen.findByRole("button", { name: /Event or action did not match/ }));+ expect(await screen.findByRole("region", { name: "Ignore reason" })).toHaveTextContent("Event or action did not match");+ });++ it("keeps real failures in the error section", async () => {+ renderDelivery({ ...EMPTY_WEBHOOK_DELIVERY, id: "failed", status: "failed", error: "dispatch failed" });+ fireEvent.click(await screen.findByRole("button", { name: /Failed/ }));+ expect(await screen.findByText("dispatch failed")).toBeInTheDocument();+ expect(within(screen.getByRole("dialog")).getByText("Error", { exact: true })).toBeInTheDocument();+ expect(screen.queryByRole("region", { name: "Ignore reason" })).not.toBeInTheDocument();+ });+});diff --git a/packages/views/autopilots/components/webhook-deliveries-section.tsx b/packages/views/autopilots/components/webhook-deliveries-section.tsxindex 1df701f04c..05f0f88128 100644--- a/packages/views/autopilots/components/webhook-deliveries-section.tsx+++ b/packages/views/autopilots/components/webhook-deliveries-section.tsx@@ -39,6 +39,7 @@ import type {WebhookDeliveryStatus,WebhookSignatureStatus,} from "@multica/core/types";+import { formatConditionValue } from "./webhook-payload-condition";// --- Status visuals -------------------------------------------------------@@ -188,8 +189,11 @@ function DeliveryRow({<span className="w-20 shrink-0 text-caption text-muted-foreground truncate">{providerLabel}</span>- <span className="flex-1 min-w-0 text-caption text-muted-foreground truncate font-mono">- {delivery.event || t(($) => $.webhook_payload.unknown_event)}+ <span className="flex-1 min-w-0 text-caption text-muted-foreground">+ <span className="block truncate font-mono">+ {delivery.event || t(($) => $.webhook_payload.unknown_event)}+ </span>+ <DeliveryIgnoreReason delivery={delivery} /></span>{delivery.replayed_from_delivery_id && (<Badge variant="secondary" className="shrink-0">@@ -334,7 +338,9 @@ function DeliveryDetailDialog({)}</dl>- {full.error && (+ {full.status === "ignored" && <DeliveryIgnoreDetails delivery={full} />}++ {full.error && full.status !== "ignored" && (<div className="rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-caption text-destructive"><div className="font-medium">{t(($) => $.deliveries.detail.error_label)}@@ -361,6 +367,66 @@ function DeliveryDetailDialog({);}+function useDeliveryIgnoreReason(delivery: WebhookDelivery): string | null {+ const { t } = useT("autopilots");+ if (delivery.status !== "ignored") return null;+ // Servers predating reason_code stored these codes in error.+ const code = delivery.reason_code ?? delivery.error;+ switch (code) {+ case "payload_filtered": return t(($) => $.deliveries.ignore.payload_filtered);+ case "event_filtered": return t(($) => $.deliveries.ignore.event_filtered);+ case "trigger_disabled": return t(($) => $.deliveries.ignore.trigger_disabled);+ case "autopilot_paused": return t(($) => $.deliveries.ignore.autopilot_paused);+ case "autopilot_archived": return t(($) => $.deliveries.ignore.autopilot_archived);+ case "quota_exceeded": return t(($) => $.deliveries.ignore.quota_exceeded);+ default: return code;+ }+}++function DeliveryIgnoreReason({ delivery }: { delivery: WebhookDelivery }) {+ const reason = useDeliveryIgnoreReason(delivery);+ if (!reason) return null;+ const path = delivery.payload_condition_failure?.condition.path;+ const label = path ? `${reason} · ${path}` : reason;+ return (+ <TruncatedTooltip content={label}>+ <span className="block truncate text-micro">{label}</span>+ </TruncatedTooltip>+ );+}++function DeliveryIgnoreDetails({ delivery }: { delivery: WebhookDelivery }) {+ const { t } = useT("autopilots");+ const reason = useDeliveryIgnoreReason(delivery);+ const failure = delivery.payload_condition_failure;+ if (!reason) return null;+ return (+ <section aria-label={t(($) => $.deliveries.ignore.title)} className="min-w-0 space-y-2 rounded-md border bg-muted/30 px-3 py-2 text-caption">+ <div className="font-medium">{t(($) => $.deliveries.ignore.title)}</div>+ <p className="text-muted-foreground">{reason}</p>+ {failure && (+ <>+ <p className="break-all">+ <code>{failure.condition.path}</code>{" "}+ {t(($) => $.dialog.event_filter_condition_ops[failure.condition.op])}{" "}+ {failure.condition.op !== "exists" && <code>{formatConditionValue(failure.condition)}</code>}+ {failure.condition.ignore_case && <span className="ml-1 text-muted-foreground">({t(($) => $.dialog.event_filter_condition_ignore_case)})</span>}+ </p>+ <dl className="space-y-1">+ <dt className="text-muted-foreground">{t(($) => $.deliveries.ignore.actual_value)}</dt>+ <dd className="break-all font-mono">+ {failure.missing+ ? t(($) => $.deliveries.ignore.missing)+ : failure.actual_values.length === 0 ? "[]" : failure.actual_values.join(", ")}+ </dd>+ </dl>+ {failure.truncated && <p className="text-muted-foreground">{t(($) => $.deliveries.ignore.truncated)}</p>}+ </>+ )}+ </section>+ );+}+function MetaRow({label,value,diff --git a/packages/views/autopilots/components/webhook-event-filter-section.test.tsx b/packages/views/autopilots/components/webhook-event-filter-section.test.tsxindex d7a0f197df..ed1c9e840a 100644--- a/packages/views/autopilots/components/webhook-event-filter-section.test.tsx+++ b/packages/views/autopilots/components/webhook-event-filter-section.test.tsx@@ -1,5 +1,6 @@-import { describe, it, expect, vi } from "vitest";-import { screen, fireEvent } from "@testing-library/react";+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { configStore } from "@multica/core/config";+import { screen, fireEvent, within } from "@testing-library/react";import { renderWithI18n } from "../../test/i18n";import { WebhookEventFilterSection } from "./webhook-event-filter-section";@@ -9,6 +10,15 @@ import { WebhookEventFilterSection } from "./webhook-event-filter-section";// getByRole(..., { name }) is the assertion that keeps them named.describe("WebhookEventFilterSection", () => {+ beforeEach(() => configStore.getState().setWebhookPayloadConditionsSupported(true));+ afterEach(() => configStore.getState().setWebhookPayloadConditionsSupported(false));++ it("offers only event filters when an older backend cannot enforce payload conditions", () => {+ configStore.getState().setWebhookPayloadConditionsSupported(false);+ renderWithI18n(<WebhookEventFilterSection filters={[{ event: "pull_request" }]} onChange={vi.fn()} />);+ expect(screen.queryByRole("button", { name: "Add condition" })).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Add" })).toBeInTheDocument();+ });it("names the add control instead of shipping a bare + icon", () => {renderWithI18n(<WebhookEventFilterSection filters={[]} onChange={vi.fn()} />,@@ -69,6 +79,88 @@ describe("WebhookEventFilterSection", () => {]);});+ it("lists each payload condition with a readable operator", () => {+ renderWithI18n(+ <WebhookEventFilterSection+ filters={[+ {+ event: "pull_request",+ conditions: [+ { path: "pull_request.draft", op: "equals", value: false },+ { path: "pull_request.base.ref", op: "in", values: ["main", "release"] },+ ],+ },+ ]}+ onChange={vi.fn()}+ />,+ );+ const draft = screen.getByTitle("pull_request.draft equals false");+ expect(draft).toHaveTextContent("pull_request.draftisfalse");+ expect(+ screen.getByTitle('pull_request.base.ref in ["main", "release"]'),+ ).toHaveTextContent('pull_request.base.refis one of"main", "release"');+ });++ it("adds a condition to the filter it was opened on", () => {+ const onChange = vi.fn();+ renderWithI18n(+ <WebhookEventFilterSection+ filters={[{ event: "issues", actions: ["labeled"] }, { event: "push" }]}+ onChange={onChange}+ />,+ );+ fireEvent.click(screen.getAllByRole("button", { name: "Add condition" })[0]!);+ const add = within(screen.getByRole("group", { name: "Add condition" })).getByRole(+ "button",+ { name: "Add" },+ );+ expect(add).toBeDisabled();++ fireEvent.change(screen.getByRole("textbox", { name: "Payload field" }), {+ target: { value: "label.name" },+ });+ fireEvent.change(screen.getByRole("textbox", { name: "Value" }), {+ target: { value: "agent" },+ });+ expect(add).toBeEnabled();+ fireEvent.click(add);++ expect(onChange).toHaveBeenCalledWith([+ {+ event: "issues",+ actions: ["labeled"],+ conditions: [{ path: "label.name", op: "equals", value: "agent" }],+ },+ { event: "push" },+ ]);+ });++ it("closes the editor on cancel without changing filters", () => {+ const onChange = vi.fn();+ renderWithI18n(+ <WebhookEventFilterSection filters={[{ event: "issues" }]} onChange={onChange} />,+ );+ fireEvent.click(screen.getByRole("button", { name: "Add condition" }));+ expect(screen.getByRole("textbox", { name: "Payload field" })).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));+ expect(screen.queryByRole("textbox", { name: "Payload field" })).not.toBeInTheDocument();+ expect(onChange).not.toHaveBeenCalled();+ });++ it("removes one condition and drops the key when none are left", () => {+ const onChange = vi.fn();+ renderWithI18n(+ <WebhookEventFilterSection+ filters={[+ { event: "issues", conditions: [{ path: "label.name", op: "equals", value: "agent" }] },+ ]}+ onChange={onChange}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: "Remove condition" }));+ expect(onChange).toHaveBeenCalledWith([{ event: "issues" }]);+ });+it("drops the row from the list when remove is clicked", () => {const onChange = vi.fn();renderWithI18n(diff --git a/packages/views/autopilots/components/webhook-event-filter-section.tsx b/packages/views/autopilots/components/webhook-event-filter-section.tsxindex dd84da7638..4dcdc31a73 100644--- a/packages/views/autopilots/components/webhook-event-filter-section.tsx+++ b/packages/views/autopilots/components/webhook-event-filter-section.tsx@@ -1,11 +1,36 @@"use client";-import { useState } from "react";+import { useId, useState } from "react";import { X, Plus, Filter, ExternalLink } from "@multica/ui/icons";import { cn } from "@multica/ui/lib/utils";import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";-import type { WebhookEventFilter } from "@multica/core/types";+import { Button } from "@multica/ui/components/ui/button";+import { Checkbox } from "@multica/ui/components/ui/checkbox";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@multica/ui/components/ui/select";+import type {+ WebhookEventFilter,+ WebhookPayloadCondition,+} from "@multica/core/types";import { useT } from "../../i18n";+import { useConfigStore } from "@multica/core/config";+import {+ CONDITION_OPS,+ EMPTY_CONDITION_DRAFT,+ MAX_CONDITIONS,+ MAX_CONDITION_PATH_LENGTH,+ MAX_CONDITION_VALUES,+ buildCondition,+ formatCondition,+ formatConditionValue,+ type ConditionDraft,+ type ConditionOp,+} from "./webhook-payload-condition";import { isTraditionalChinese } from "../../common/docs-locale";interface WebhookEventFilterSectionProps {@@ -18,8 +43,13 @@ export function WebhookEventFilterSection({onChange,}: WebhookEventFilterSectionProps) {const { t, i18n } = useT("autopilots");+ const conditionLimitsId = useId();+ const payloadSupported = useConfigStore((state) => state.webhookPayloadConditionsSupported);const [newEvent, setNewEvent] = useState("");const [newActions, setNewActions] = useState("");+ const [editingIdx, setEditingIdx] = useState<number | null>(null);+ const [draft, setDraft] = useState<ConditionDraft>(EMPTY_CONDITION_DRAFT);+ const draftCondition = buildCondition(draft);const docsHref = isTraditionalChinese(i18n.language)? `https://multica.ai/docs/zh-Hant/autopilots#${encodeURIComponent("事件過濾")}`: i18n.language?.startsWith("zh")@@ -44,8 +74,32 @@ export function WebhookEventFilterSection({const removeFilter = (idx: number) => {onChange(filters.filter((_, i) => i !== idx));+ setEditingIdx(null);};+ const updateConditions = (idx: number, conditions: WebhookPayloadCondition[]) => {+ onChange(+ filters.map((f, i) => {+ if (i !== idx) return f;+ const { conditions: _previous, ...rest } = f;+ return conditions.length > 0 ? { ...rest, conditions } : rest;+ }),+ );+ };++ const openEditor = (idx: number) => {+ setEditingIdx(idx);+ setDraft(EMPTY_CONDITION_DRAFT);+ };++ const addCondition = (idx: number) => {+ if (!draftCondition) return;+ updateConditions(idx, [...(filters[idx]?.conditions ?? []), draftCondition]);+ setEditingIdx(null);+ };++ const opLabel = (op: ConditionOp) => t(($) => $.dialog.event_filter_condition_ops[op]);+return (<div className="space-y-2"><div className="flex items-center gap-1.5 text-micro font-semibold tracking-[0.08em] text-muted-foreground uppercase">@@ -65,31 +119,191 @@ export function WebhookEventFilterSection({{filters.length > 0 && (<div className="space-y-1">- {filters.map((f, idx) => (- <div- key={idx}- className="flex items-center gap-2 rounded-md border bg-background px-2.5 py-1.5 text-caption"- >- <span className="font-mono font-medium text-foreground">- {f.event}- </span>- {f.actions && f.actions.length > 0 && (- <span className="text-muted-foreground">- : {f.actions.join(", ")}- </span>- )}- <TooltipHint label={t(($) => $.dialog.event_filter_remove_label)}>- <button- type="button"- onClick={() => removeFilter(idx)}- aria-label={t(($) => $.dialog.event_filter_remove_label)}- className="ml-auto rounded-xs p-0.5 text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"- >- <X className="size-3" />- </button>- </TooltipHint>- </div>- ))}+ {filters.map((f, idx) => {+ const conditions = f.conditions ?? [];+ const editing = editingIdx === idx;+ const canAddCondition = payloadSupported && !editing && conditions.length < MAX_CONDITIONS;+ return (+ <div key={idx} className="rounded-md border bg-background text-caption">+ <div className="flex min-w-0 items-center gap-2 py-1 pr-1 pl-2.5">+ <span className="shrink-0 font-mono font-medium text-foreground">{f.event}</span>+ {f.actions && f.actions.length > 0 && (+ <span className="min-w-0 truncate text-muted-foreground">+ {f.actions.join(" · ")}+ </span>+ )}+ <div className="ml-auto flex shrink-0 items-center">+ <TooltipHint label={t(($) => $.dialog.event_filter_remove_label)}>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ onClick={() => removeFilter(idx)}+ aria-label={t(($) => $.dialog.event_filter_remove_label)}+ >+ <X />+ </Button>+ </TooltipHint>+ </div>+ </div>++ {conditions.length > 0 && (+ <div className="border-t py-1">+ <p className="px-2.5 py-1 text-micro text-muted-foreground">+ {t(($) => $.dialog.event_filter_condition_all)}+ </p>+ <ul>+ {conditions.map((c, cIdx) => (+ <li+ key={cIdx}+ title={formatCondition(c)}+ className="flex min-w-0 items-center gap-1.5 py-0.5 pr-1 pl-2.5"+ >+ <span className="min-w-0 truncate font-mono text-foreground">{c.path}</span>+ <span className="shrink-0 text-muted-foreground">{opLabel(c.op)}</span>+ {c.op !== "exists" && (+ <span className="max-w-[45%] shrink-0 truncate font-mono text-foreground">+ {formatConditionValue(c)}+ </span>+ )}+ {c.ignore_case && (+ <span className="shrink-0 text-micro text-muted-foreground">+ {t(($) => $.dialog.event_filter_condition_ignore_case)}+ </span>+ )}+ <TooltipHint label={t(($) => $.dialog.event_filter_condition_remove_label)}>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ className="ml-auto"+ onClick={() =>+ updateConditions(+ idx,+ conditions.filter((_, i) => i !== cIdx),+ )+ }+ aria-label={t(($) => $.dialog.event_filter_condition_remove_label)}+ >+ <X />+ </Button>+ </TooltipHint>+ </li>+ ))}+ </ul>+ </div>+ )}++ {canAddCondition && (+ <Button type="button" variant="ghost" size="xs" className="m-1 text-muted-foreground" onClick={() => openEditor(idx)}>+ <Plus />+ {t(($) => $.dialog.event_filter_condition_add_label)}+ </Button>+ )}++ {editing && (+ <div+ role="group"+ aria-label={t(($) => $.dialog.event_filter_condition_add_label)}+ className="space-y-1.5 border-t p-2"+ >+ <input+ type="text"+ autoFocus+ value={draft.path}+ onChange={(e) => setDraft({ ...draft, path: e.target.value })}+ aria-label={t(($) => $.dialog.event_filter_condition_path_label)}+ aria-describedby={conditionLimitsId}+ placeholder={t(($) => $.dialog.event_filter_condition_path_placeholder)}+ className="h-7 w-full rounded-md border bg-background px-2.5 text-caption font-mono outline-none focus:ring-1 focus:ring-ring"+ />+ <div className="flex gap-1.5">+ <Select+ items={CONDITION_OPS.map((op) => ({ value: op, label: opLabel(op) }))}+ value={draft.op}+ onValueChange={(v) => {+ if (v) setDraft({ ...draft, op: v as ConditionOp });+ }}+ >+ <SelectTrigger+ size="sm"+ aria-label={t(($) => $.dialog.event_filter_condition_op_label)}+ className={cn("text-caption", draft.op === "exists" ? "w-full" : "w-28 shrink-0")}+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {CONDITION_OPS.map((op) => (+ <SelectItem key={op} value={op}>+ {opLabel(op)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {draft.op !== "exists" && (+ <input+ type="text"+ value={draft.value}+ onChange={(e) => setDraft({ ...draft, value: e.target.value })}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ addCondition(idx);+ }+ }}+ aria-label={t(($) => $.dialog.event_filter_condition_value_label)}+ aria-describedby={conditionLimitsId}+ placeholder={+ draft.op === "in"+ ? t(($) => $.dialog.event_filter_condition_values_placeholder)+ : t(($) => $.dialog.event_filter_condition_value_placeholder)+ }+ className="h-7 min-w-0 flex-1 rounded-md border bg-background px-2.5 text-caption font-mono outline-none focus:ring-1 focus:ring-ring"+ />+ )}+ </div>+ <p id={conditionLimitsId} className="text-micro text-muted-foreground">+ {t(($) => $.dialog.event_filter_condition_limits, {+ path: MAX_CONDITION_PATH_LENGTH,+ values: MAX_CONDITION_VALUES,+ })}+ </p>+ <div className="flex items-center gap-1.5">+ {draft.op !== "exists" && (+ <label className="inline-flex items-center gap-1.5 whitespace-nowrap text-muted-foreground">+ <Checkbox+ checked={draft.ignoreCase}+ onCheckedChange={(checked) =>+ setDraft({ ...draft, ignoreCase: checked === true })+ }+ />+ {t(($) => $.dialog.event_filter_condition_ignore_case)}+ </label>+ )}+ <Button+ type="button"+ variant="ghost"+ size="xs"+ className="ml-auto"+ onClick={() => setEditingIdx(null)}+ >+ {t(($) => $.dialog.event_filter_condition_cancel)}+ </Button>+ <Button+ type="button"+ variant="secondary"+ size="xs"+ onClick={() => addCondition(idx)}+ disabled={!draftCondition}+ >+ {t(($) => $.dialog.event_filter_add)}+ </Button>+ </div>+ </div>+ )}+ </div>+ );+ })}</div>)}diff --git a/packages/views/autopilots/components/webhook-payload-condition.test.ts b/packages/views/autopilots/components/webhook-payload-condition.test.tsnew file mode 100644index 0000000000..64d9a11b5c--- /dev/null+++ b/packages/views/autopilots/components/webhook-payload-condition.test.ts@@ -0,0 +1,98 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import {+ EMPTY_CONDITION_DRAFT,+ buildCondition,+ formatCondition,+ formatConditionValue,+ parseConditionValue,+} from "./webhook-payload-condition";++describe("parseConditionValue", () => {+ it.each([+ ["main", "main"],+ ['"main"', "main"],+ ["true", true],+ ["false", false],+ ["42", 42],+ ['"42"', "42"],+ [" spaced ", "spaced"],+ ["{\"a\":1}", "{\"a\":1}"],+ ])("reads %s", (raw, want) => {+ expect(parseConditionValue(raw)).toEqual(want);+ });+});++describe("buildCondition", () => {+ const draft = (patch: Partial<typeof EMPTY_CONDITION_DRAFT>) => ({+ ...EMPTY_CONDITION_DRAFT,+ ...patch,+ });++ it("needs a path without empty segments", () => {+ expect(buildCondition(draft({ value: "x" }))).toBeNull();+ expect(buildCondition(draft({ path: "a..b", value: "x" }))).toBeNull();+ });++ it("needs a value except for exists", () => {+ expect(buildCondition(draft({ path: "draft" }))).toBeNull();+ expect(buildCondition(draft({ path: "merged_at", op: "exists", value: "ignored", ignoreCase: true }))).toEqual({+ path: "merged_at",+ op: "exists",+ });+ });++ it("types equals values as JSON scalars", () => {+ expect(buildCondition(draft({ path: "pull_request.draft", value: "false" }))).toEqual({+ path: "pull_request.draft",+ op: "equals",+ value: false,+ });+ });++ it("keeps contains values as text", () => {+ expect(buildCondition(draft({ path: "title", op: "contains", value: "42", ignoreCase: true }))).toEqual({+ path: "title",+ op: "contains",+ value: "42",+ ignore_case: true,+ });+ });++ it("splits in values on commas", () => {+ expect(buildCondition(draft({ path: "base.ref", op: "in", value: "main, release, " }))).toEqual({+ path: "base.ref",+ op: "in",+ values: ["main", "release"],+ });+ expect(buildCondition(draft({ path: "base.ref", op: "in", value: " , " }))).toBeNull();+ });++ it.each(["a", "界", "😀"])("allows 256 path characters and rejects 257 (%s)", (character) => {+ expect(buildCondition(draft({ path: character.repeat(256), op: "exists" }))).not.toBeNull();+ expect(buildCondition(draft({ path: character.repeat(257), op: "exists" }))).toBeNull();+ });++ it("allows 100 in values and rejects 101", () => {+ const values = Array.from({ length: 101 }, (_, i) => String(i));+ expect(buildCondition(draft({ path: "number", op: "in", value: values.slice(0, 100).join(",") }))?.values).toHaveLength(100);+ expect(buildCondition(draft({ path: "number", op: "in", value: values.join(",") }))).toBeNull();+ });+});++describe("formatCondition", () => {+ it("renders each op as code", () => {+ expect(formatCondition({ path: "a", op: "equals", value: false })).toBe("a equals false");+ expect(formatCondition({ path: "a", op: "contains", value: "x", ignore_case: true })).toBe('a contains/i "x"');+ expect(formatCondition({ path: "a", op: "in", values: ["x", 1] })).toBe('a in ["x", 1]');+ expect(formatCondition({ path: "a", op: "exists" })).toBe("a exists");+ });+});++describe("formatConditionValue", () => {+ it("quotes strings and leaves booleans and numbers bare", () => {+ expect(formatConditionValue({ path: "a", op: "equals", value: "x" })).toBe('"x"');+ expect(formatConditionValue({ path: "a", op: "equals", value: false })).toBe("false");+ expect(formatConditionValue({ path: "a", op: "in", values: ["x", 1] })).toBe('"x", 1');+ });+});diff --git a/packages/views/autopilots/components/webhook-payload-condition.ts b/packages/views/autopilots/components/webhook-payload-condition.tsnew file mode 100644index 0000000000..537762e48b--- /dev/null+++ b/packages/views/autopilots/components/webhook-payload-condition.ts@@ -0,0 +1,81 @@+import type {+ WebhookPayloadCondition,+ WebhookPayloadConditionValue,+} from "@multica/core/types";++export type ConditionOp = WebhookPayloadCondition["op"];++export const CONDITION_OPS: ConditionOp[] = ["equals", "not_equals", "contains", "in", "exists"];++// Mirror server limits so the editor never builds a row the API rejects.+export const MAX_CONDITIONS = 20;+export const MAX_CONDITION_PATH_LENGTH = 256;+export const MAX_CONDITION_VALUES = 100;++// formatConditionValue shows strings quoted and booleans/numbers bare, so+// the stored type stays visible.+export function formatConditionValue(c: WebhookPayloadCondition): string {+ if (c.op === "in") return (c.values ?? []).map((v) => JSON.stringify(v)).join(", ");+ return JSON.stringify(c.value);+}++// formatCondition is the full API form, used as the row's tooltip.+export function formatCondition(c: WebhookPayloadCondition): string {+ if (c.op === "exists") return `${c.path} exists`;+ const value = c.op === "in" ? `[${formatConditionValue(c)}]` : formatConditionValue(c);+ return `${c.path} ${c.op}${c.ignore_case ? "/i" : ""} ${value}`;+}++// parseConditionValue reads JSON scalars (true, 42, "42") and falls back to+// plain text, so `main` and `"main"` both mean the string main.+export function parseConditionValue(raw: string): WebhookPayloadConditionValue {+ const trimmed = raw.trim();+ try {+ const parsed: unknown = JSON.parse(trimmed);+ if (+ typeof parsed === "string" ||+ typeof parsed === "number" ||+ typeof parsed === "boolean"+ ) {+ return parsed;+ }+ } catch {+ // Not JSON: plain text.+ }+ return trimmed;+}++export interface ConditionDraft {+ path: string;+ op: ConditionOp;+ value: string;+ ignoreCase: boolean;+}++export const EMPTY_CONDITION_DRAFT: ConditionDraft = { path: "", op: "equals", value: "", ignoreCase: false };++// buildCondition returns null while the draft can't produce a row the+// server accepts.+export function buildCondition(draft: ConditionDraft): WebhookPayloadCondition | null {+ const path = draft.path.trim();+ if (!path || path.split(".").some((seg) => seg === "")) return null;+ if (Array.from(path).length > MAX_CONDITION_PATH_LENGTH) return null;+ if (draft.op === "exists") return { path, op: "exists" };+ if (!draft.value.trim()) return null;+ const condition: WebhookPayloadCondition = { path, op: draft.op };+ if (draft.op === "in") {+ const values = draft.value+ .split(",")+ .map((v) => v.trim())+ .filter((v) => v.length > 0);+ if (values.length === 0 || values.length > MAX_CONDITION_VALUES) return null;+ condition.values = values.map(parseConditionValue);+ } else if (draft.op === "contains") {+ const parsed = parseConditionValue(draft.value);+ condition.value = typeof parsed === "string" ? parsed : draft.value.trim();+ } else {+ condition.value = parseConditionValue(draft.value);+ }+ if (draft.ignoreCase) condition.ignore_case = true;+ return condition;+}diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.jsonindex f47f1c891b..ee8d39e8b3 100644--- a/packages/views/locales/en/autopilots.json+++ b/packages/views/locales/en/autopilots.json@@ -247,6 +247,18 @@"disabled_invalid_signature": "Can't replay — signature was invalid","disabled_rejected": "Can't replay a rejected delivery","disabled_queued": "Still queued — replay once it settles"+ },+ "ignore": {+ "title": "Ignore reason",+ "payload_filtered": "Payload conditions not met",+ "event_filtered": "Event or action did not match",+ "trigger_disabled": "Trigger disabled",+ "autopilot_paused": "Autopilot paused",+ "autopilot_archived": "Autopilot archived",+ "quota_exceeded": "Run quota reached",+ "actual_value": "Actual value",+ "missing": "Field missing",+ "truncated": "Preview truncated. See the raw body for the full value."}},"add_trigger_dialog": {@@ -332,7 +344,24 @@"event_filter_actions_placeholder": "completed, failed","event_filter_add": "Add","event_filter_remove_label": "Remove filter",- "event_filter_hint": "Only process webhooks matching these events. Leave empty to accept all.",+ "event_filter_hint": "Only process events matching a rule and all its payload conditions. Leave empty to accept all events.",+ "event_filter_condition_remove_label": "Remove condition",+ "event_filter_condition_add_label": "Add condition",+ "event_filter_condition_cancel": "Cancel",+ "event_filter_condition_ops": {+ "equals": "is",+ "not_equals": "is not",+ "contains": "contains",+ "in": "is one of",+ "exists": "exists"+ },+ "event_filter_condition_path_label": "Payload field",+ "event_filter_condition_path_placeholder": "e.g. pull_request.labels.*.name",+ "event_filter_condition_op_label": "Operator",+ "event_filter_condition_value_label": "Value",+ "event_filter_condition_value_placeholder": "e.g. main",+ "event_filter_condition_values_placeholder": "main, release",+ "event_filter_condition_ignore_case": "Ignore case","schedule_multiple_notice": "This autopilot has {{count}} schedules. Close this dialog and edit each one under Triggers below.","schedule_empty": "No schedule — this autopilot only runs when triggered manually.","schedule_add": "Add schedule",@@ -347,7 +376,9 @@"label": "Run only","description": "Silent run, no issue created"}- }+ },+ "event_filter_condition_all": "And payload matches all conditions",+ "event_filter_condition_limits": "Paths: up to {{path}} characters. Lists: up to {{values}} values."},"schedule_editor": {"time_label": "Time",diff --git a/packages/views/locales/es/autopilots.json b/packages/views/locales/es/autopilots.jsonindex 0fb4f3cee6..4ff22e21ee 100644--- a/packages/views/locales/es/autopilots.json+++ b/packages/views/locales/es/autopilots.json@@ -247,6 +247,18 @@"disabled_invalid_signature": "No se puede repetir: la firma no era válida","disabled_rejected": "No se puede repetir una entrega rechazada","disabled_queued": "Todavía en cola: repítela cuando se estabilice"+ },+ "ignore": {+ "title": "Motivo de omisión",+ "payload_filtered": "El contenido no cumple las condiciones",+ "event_filtered": "El evento o la acción no coincide",+ "trigger_disabled": "Disparador desactivado",+ "autopilot_paused": "Automatización en pausa",+ "autopilot_archived": "Automatización archivada",+ "quota_exceeded": "Cuota de ejecuciones alcanzada",+ "actual_value": "Valor real",+ "missing": "Campo ausente",+ "truncated": "Vista previa truncada. Consulta el contenido original para ver el valor completo."}},"add_trigger_dialog": {@@ -332,7 +344,7 @@"event_filter_actions_placeholder": "completed, failed","event_filter_add": "Añadir","event_filter_remove_label": "Quitar filtro",- "event_filter_hint": "Solo procesa webhooks que coincidan con estos eventos. Déjalo vacío para aceptar todos.",+ "event_filter_hint": "Solo se procesan eventos que coinciden con una regla y todas sus condiciones. Deja vacío para aceptar todos los eventos.","schedule_multiple_notice": "Esta automatización tiene {{count}} programaciones. Cierra este diálogo y edita cada una en Disparadores, más abajo.","schedule_empty": "Sin programación: esta automatización solo se ejecuta cuando se dispara manualmente.","schedule_add": "Añadir programación",@@ -347,7 +359,26 @@"label": "Solo ejecutar","description": "Ejecución silenciosa, sin crear tarea"}- }+ },+ "event_filter_condition_remove_label": "Eliminar condición",+ "event_filter_condition_add_label": "Añadir condición",+ "event_filter_condition_cancel": "Cancelar",+ "event_filter_condition_ops": {+ "equals": "es",+ "not_equals": "no es",+ "contains": "contiene",+ "in": "es uno de",+ "exists": "existe"+ },+ "event_filter_condition_path_label": "Campo del contenido",+ "event_filter_condition_path_placeholder": "p. ej., pull_request.labels.*.name",+ "event_filter_condition_op_label": "Operador",+ "event_filter_condition_value_label": "Valor",+ "event_filter_condition_value_placeholder": "p. ej., main",+ "event_filter_condition_values_placeholder": "main, release",+ "event_filter_condition_ignore_case": "Ignorar mayúsculas",+ "event_filter_condition_all": "Y el contenido cumple todas las condiciones",+ "event_filter_condition_limits": "Rutas: hasta {{path}} caracteres. Listas: hasta {{values}} valores."},"schedule_editor": {"time_label": "Hora",diff --git a/packages/views/locales/fr/autopilots.json b/packages/views/locales/fr/autopilots.jsonindex 6e617ae271..f4d42511c6 100644--- a/packages/views/locales/fr/autopilots.json+++ b/packages/views/locales/fr/autopilots.json@@ -247,6 +247,18 @@"disabled_invalid_signature": "Rejeu impossible — la signature était invalide","disabled_rejected": "Impossible de rejouer une livraison rejetée","disabled_queued": "Encore en file d'attente — rejouez une fois qu'elle sera traitée"+ },+ "ignore": {+ "title": "Motif du filtrage",+ "payload_filtered": "Conditions de la charge utile non remplies",+ "event_filtered": "Événement ou action non correspondant",+ "trigger_disabled": "Déclencheur désactivé",+ "autopilot_paused": "Automatisation en pause",+ "autopilot_archived": "Automatisation archivée",+ "quota_exceeded": "Quota d’exécutions atteint",+ "actual_value": "Valeur réelle",+ "missing": "Champ absent",+ "truncated": "Aperçu tronqué. Consultez le contenu brut pour la valeur complète."}},"add_trigger_dialog": {@@ -332,7 +344,24 @@"event_filter_actions_placeholder": "completed, failed","event_filter_add": "Ajouter","event_filter_remove_label": "Retirer le filtre",- "event_filter_hint": "Ne traiter que les webhooks correspondant à ces événements. Laissez vide pour tous les accepter.",+ "event_filter_hint": "Seuls les événements correspondant à une règle et à toutes ses conditions sont traités. Laissez vide pour tout accepter.",+ "event_filter_condition_remove_label": "Retirer la condition",+ "event_filter_condition_add_label": "Ajouter une condition",+ "event_filter_condition_cancel": "Annuler",+ "event_filter_condition_ops": {+ "equals": "est",+ "not_equals": "n'est pas",+ "contains": "contient",+ "in": "est parmi",+ "exists": "existe"+ },+ "event_filter_condition_path_label": "Champ de la charge utile",+ "event_filter_condition_path_placeholder": "ex. pull_request.labels.*.name",+ "event_filter_condition_op_label": "Opérateur",+ "event_filter_condition_value_label": "Valeur",+ "event_filter_condition_value_placeholder": "ex. main",+ "event_filter_condition_values_placeholder": "main, release",+ "event_filter_condition_ignore_case": "Ignorer la casse","schedule_multiple_notice": "Cette automatisation a {{count}} planifications. Fermez cette fenêtre et modifiez chacune dans la liste Déclencheurs ci-dessous.","schedule_empty": "Aucune planification — cette automatisation ne s'exécute que sur déclenchement manuel.","schedule_add": "Ajouter une planification",@@ -347,7 +376,9 @@"label": "Exécution seule","description": "Exécution silencieuse, aucune tâche créée"}- }+ },+ "event_filter_condition_all": "Et la charge utile remplit toutes les conditions",+ "event_filter_condition_limits": "Chemins : {{path}} caractères maximum. Listes : {{values}} valeurs maximum."},"schedule_editor": {"time_label": "Heure",diff --git a/packages/views/locales/ja/autopilots.json b/packages/views/locales/ja/autopilots.jsonindex a57828a877..6fd1872a11 100644--- a/packages/views/locales/ja/autopilots.json+++ b/packages/views/locales/ja/autopilots.json@@ -247,6 +247,18 @@"disabled_invalid_signature": "署名が無効だったため再実行できません","disabled_rejected": "拒否された配信は再実行できません","disabled_queued": "まだキュー待ちです。処理が落ち着いてから再実行してください"+ },+ "ignore": {+ "title": "無視した理由",+ "payload_filtered": "本文の条件を満たしていません",+ "event_filtered": "イベントまたはアクションが一致しません",+ "trigger_disabled": "トリガーは無効です",+ "autopilot_paused": "自動化は一時停止中です",+ "autopilot_archived": "自動化はアーカイブ済みです",+ "quota_exceeded": "実行の上限に達しました",+ "actual_value": "実際の値",+ "missing": "フィールドがありません",+ "truncated": "プレビューは省略されています。完全な値は元の本文で確認できます。"}},"add_trigger_dialog": {@@ -332,7 +344,24 @@"event_filter_actions_placeholder": "completed, failed","event_filter_add": "追加","event_filter_remove_label": "フィルターを削除",- "event_filter_hint": "これらのイベントに一致する Webhook のみを処理します。空にするとすべて許可します。",+ "event_filter_hint": "ルールと本文のすべての条件に一致するイベントのみ処理します。空欄の場合はすべて受け付けます。",+ "event_filter_condition_remove_label": "条件を削除",+ "event_filter_condition_add_label": "条件を追加",+ "event_filter_condition_cancel": "キャンセル",+ "event_filter_condition_ops": {+ "equals": "等しい",+ "not_equals": "等しくない",+ "contains": "含む",+ "in": "いずれか",+ "exists": "存在する"+ },+ "event_filter_condition_path_label": "Payload のフィールド",+ "event_filter_condition_path_placeholder": "例: pull_request.labels.*.name",+ "event_filter_condition_op_label": "演算子",+ "event_filter_condition_value_label": "値",+ "event_filter_condition_value_placeholder": "例: main",+ "event_filter_condition_values_placeholder": "main, release",+ "event_filter_condition_ignore_case": "大文字と小文字を区別しない","schedule_multiple_notice": "このオートパイロットにはスケジュールが {{count}} 件あります。このダイアログを閉じて、下の「トリガー」から個別に編集してください。","schedule_empty": "スケジュールはありません。このオートパイロットは手動で実行したときだけ動きます。","schedule_add": "スケジュールを追加",@@ -347,7 +376,9 @@"label": "実行のみ","description": "タスクを作成せず、静かに実行します"}- }+ },+ "event_filter_condition_all": "かつ本文がすべての条件を満たす",+ "event_filter_condition_limits": "パスは {{path}} 文字まで、候補リストは {{values}} 個までです。"},"schedule_editor": {"time_label": "時刻",diff --git a/packages/views/locales/ko/autopilots.json b/packages/views/locales/ko/autopilots.jsonindex 4f96e7c2aa..d5564494dc 100644--- a/packages/views/locales/ko/autopilots.json+++ b/packages/views/locales/ko/autopilots.json@@ -247,6 +247,18 @@"disabled_invalid_signature": "서명이 유효하지 않아 재실행할 수 없습니다","disabled_rejected": "거부된 전달은 재실행할 수 없습니다","disabled_queued": "아직 대기 중입니다. 처리된 후 재실행하세요"+ },+ "ignore": {+ "title": "무시한 이유",+ "payload_filtered": "본문 조건 불충족",+ "event_filtered": "이벤트 또는 동작 불일치",+ "trigger_disabled": "트리거 비활성화됨",+ "autopilot_paused": "자동화 일시 중지됨",+ "autopilot_archived": "자동화 보관됨",+ "quota_exceeded": "실행 할당량 도달",+ "actual_value": "실제 값",+ "missing": "필드 없음",+ "truncated": "미리보기가 잘렸습니다. 전체 값은 원본 본문에서 확인하세요."}},"add_trigger_dialog": {@@ -332,7 +344,24 @@"event_filter_actions_placeholder": "completed, failed","event_filter_add": "추가","event_filter_remove_label": "필터 제거",- "event_filter_hint": "이 이벤트와 일치하는 Webhook만 처리합니다. 비워 두면 모두 허용합니다.",+ "event_filter_hint": "규칙과 모든 본문 조건에 일치하는 이벤트만 처리합니다. 비워 두면 모든 이벤트를 수락합니다.",+ "event_filter_condition_remove_label": "조건 제거",+ "event_filter_condition_add_label": "조건 추가",+ "event_filter_condition_cancel": "취소",+ "event_filter_condition_ops": {+ "equals": "같음",+ "not_equals": "같지 않음",+ "contains": "포함",+ "in": "다음 중 하나",+ "exists": "존재"+ },+ "event_filter_condition_path_label": "Payload 필드",+ "event_filter_condition_path_placeholder": "예: pull_request.labels.*.name",+ "event_filter_condition_op_label": "연산자",+ "event_filter_condition_value_label": "값",+ "event_filter_condition_value_placeholder": "예: main",+ "event_filter_condition_values_placeholder": "main, release",+ "event_filter_condition_ignore_case": "대소문자 무시","schedule_multiple_notice": "이 오토파일럿에는 일정이 {{count}}개 있습니다. 이 대화상자를 닫고 아래 '트리거'에서 각각 수정하세요.","schedule_empty": "일정이 없습니다. 이 오토파일럿은 수동으로 실행할 때만 동작합니다.","schedule_add": "일정 추가",@@ -347,7 +376,9 @@"label": "실행만","description": "태스크를 만들지 않고 조용히 실행합니다"}- }+ },+ "event_filter_condition_all": "본문이 모든 조건을 충족해야 함",+ "event_filter_condition_limits": "경로는 최대 {{path}}자, 후보 목록은 최대 {{values}}개입니다."},"schedule_editor": {"time_label": "시간",diff --git a/packages/views/locales/ru/autopilots.json b/packages/views/locales/ru/autopilots.jsonindex b0b9a7167c..d2f4f1064e 100644--- a/packages/views/locales/ru/autopilots.json+++ b/packages/views/locales/ru/autopilots.json@@ -247,6 +247,18 @@"disabled_invalid_signature": "Нельзя повторить — подпись была неверной","disabled_rejected": "Нельзя повторить отклонённую доставку","disabled_queued": "Ещё в очереди — повторите, когда она обработается"+ },+ "ignore": {+ "title": "Причина пропуска",+ "payload_filtered": "Условия содержимого не выполнены",+ "event_filtered": "Событие или действие не соответствует",+ "trigger_disabled": "Триггер отключён",+ "autopilot_paused": "Автоматизация приостановлена",+ "autopilot_archived": "Автоматизация архивирована",+ "quota_exceeded": "Квота запусков исчерпана",+ "actual_value": "Фактическое значение",+ "missing": "Поле отсутствует",+ "truncated": "Предпросмотр обрезан. Полное значение доступно в исходном содержимом."}},"add_trigger_dialog": {@@ -332,7 +344,7 @@"event_filter_actions_placeholder": "completed, failed","event_filter_add": "Добавить","event_filter_remove_label": "Удалить фильтр",- "event_filter_hint": "Обрабатывать только вебхуки, соответствующие этим событиям. Оставьте пустым, чтобы принимать все.",+ "event_filter_hint": "Обрабатываются события, соответствующие правилу и всем его условиям. Оставьте пустым, чтобы принимать все события.","schedule_multiple_notice": "У этого автопилота {{count}} расписаний. Закройте это окно и измените каждое из них в разделе «Триггеры» ниже.","schedule_empty": "Нет расписания — этот автопилот запускается только вручную.","schedule_add": "Добавить расписание",@@ -347,7 +359,26 @@"label": "Только запуск","description": "Тихий запуск, задача не создаётся"}- }+ },+ "event_filter_condition_remove_label": "Удалить условие",+ "event_filter_condition_add_label": "Добавить условие",+ "event_filter_condition_cancel": "Отмена",+ "event_filter_condition_ops": {+ "equals": "равно",+ "not_equals": "не равно",+ "contains": "содержит",+ "in": "одно из",+ "exists": "существует"+ },+ "event_filter_condition_path_label": "Поле содержимого",+ "event_filter_condition_path_placeholder": "например, pull_request.labels.*.name",+ "event_filter_condition_op_label": "Оператор",+ "event_filter_condition_value_label": "Значение",+ "event_filter_condition_value_placeholder": "например, main",+ "event_filter_condition_values_placeholder": "main, release",+ "event_filter_condition_ignore_case": "Без учёта регистра",+ "event_filter_condition_all": "И содержимое соответствует всем условиям",+ "event_filter_condition_limits": "Путь: до {{path}} символов. Список: до {{values}} значений."},"schedule_editor": {"time_label": "Время",diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.jsonindex f9b7d50425..bae7171a64 100644--- a/packages/views/locales/zh-Hans/autopilots.json+++ b/packages/views/locales/zh-Hans/autopilots.json@@ -247,6 +247,18 @@"disabled_invalid_signature": "无法重放——签名校验失败","disabled_rejected": "无法重放已拒绝的投递","disabled_queued": "投递仍在排队,处理完成后再重放"+ },+ "ignore": {+ "title": "忽略原因",+ "payload_filtered": "正文条件不满足",+ "event_filtered": "事件或动作不匹配",+ "trigger_disabled": "触发器已禁用",+ "autopilot_paused": "自动化已暂停",+ "autopilot_archived": "自动化已归档",+ "quota_exceeded": "已达到运行配额",+ "actual_value": "实际值",+ "missing": "字段不存在",+ "truncated": "预览已截断,完整值见原始正文。"}},"add_trigger_dialog": {@@ -332,7 +344,24 @@"event_filter_actions_placeholder": "completed, failed","event_filter_add": "添加","event_filter_remove_label": "移除过滤条件",- "event_filter_hint": "只处理匹配这些事件的 webhook。留空则接受所有事件。",+ "event_filter_hint": "只处理匹配规则且正文满足全部条件的事件。留空则接收所有事件。",+ "event_filter_condition_remove_label": "移除条件",+ "event_filter_condition_add_label": "添加条件",+ "event_filter_condition_cancel": "取消",+ "event_filter_condition_ops": {+ "equals": "是",+ "not_equals": "不是",+ "contains": "包含",+ "in": "是其中之一",+ "exists": "存在"+ },+ "event_filter_condition_path_label": "Payload 字段",+ "event_filter_condition_path_placeholder": "例如 pull_request.labels.*.name",+ "event_filter_condition_op_label": "运算符",+ "event_filter_condition_value_label": "值",+ "event_filter_condition_value_placeholder": "例如 main",+ "event_filter_condition_values_placeholder": "main, release",+ "event_filter_condition_ignore_case": "忽略大小写","schedule_multiple_notice": "该自动化有 {{count}} 条时间表。关闭此弹窗,在下方「触发器」中逐条编辑。","schedule_empty": "还没有时间表——这个自动化只在手动触发时运行。","schedule_add": "添加时间表",@@ -347,7 +376,9 @@"label": "仅运行","description": "静默运行,不创建任务"}- }+ },+ "event_filter_condition_all": "且正文满足全部条件",+ "event_filter_condition_limits": "字段路径最多 {{path}} 个字符,候选值列表最多 {{values}} 项。"},"schedule_editor": {"time_label": "时间",diff --git a/packages/views/locales/zh-Hant/autopilots.json b/packages/views/locales/zh-Hant/autopilots.jsonindex 690a76a7b6..b2a69bd4f9 100644--- a/packages/views/locales/zh-Hant/autopilots.json+++ b/packages/views/locales/zh-Hant/autopilots.json@@ -247,6 +247,18 @@"disabled_invalid_signature": "無法重放——簽名校驗失敗","disabled_rejected": "無法重放已拒絕的投遞","disabled_queued": "投遞仍在排隊,處理完成後再重放"+ },+ "ignore": {+ "title": "忽略原因",+ "payload_filtered": "本文條件不符",+ "event_filtered": "事件或動作不符",+ "trigger_disabled": "觸發器已停用",+ "autopilot_paused": "自動化已暫停",+ "autopilot_archived": "自動化已封存",+ "quota_exceeded": "已達執行配額",+ "actual_value": "實際值",+ "missing": "欄位不存在",+ "truncated": "預覽已截斷,完整值請見原始本文。"}},"add_trigger_dialog": {@@ -332,7 +344,7 @@"event_filter_actions_placeholder": "completed, failed","event_filter_add": "新增","event_filter_remove_label": "移除過濾條件",- "event_filter_hint": "只處理匹配這些事件的 webhook。留空則接受所有事件。",+ "event_filter_hint": "只處理符合規則且本文符合全部條件的事件。留空則接收所有事件。","schedule_multiple_notice": "該自動化有 {{count}} 條時間表。關閉此彈窗,在下方「觸發器」中逐條編輯。","schedule_empty": "還沒有時間表——這個自動化只在手動觸發時執行。","schedule_add": "新增時間表",@@ -347,7 +359,26 @@"label": "僅執行","description": "靜默執行,不建立任務"}- }+ },+ "event_filter_condition_remove_label": "移除條件",+ "event_filter_condition_add_label": "新增條件",+ "event_filter_condition_cancel": "取消",+ "event_filter_condition_ops": {+ "equals": "是",+ "not_equals": "不是",+ "contains": "包含",+ "in": "是其中之一",+ "exists": "存在"+ },+ "event_filter_condition_path_label": "本文欄位",+ "event_filter_condition_path_placeholder": "例如 pull_request.labels.*.name",+ "event_filter_condition_op_label": "運算子",+ "event_filter_condition_value_label": "值",+ "event_filter_condition_value_placeholder": "例如 main",+ "event_filter_condition_values_placeholder": "main, release",+ "event_filter_condition_ignore_case": "忽略大小寫",+ "event_filter_condition_all": "且本文符合全部條件",+ "event_filter_condition_limits": "欄位路徑最多 {{path}} 個字元,候選值清單最多 {{values}} 項。"},"schedule_editor": {"time_label": "時間",diff --git a/server/cmd/multica/cmd_autopilot.go b/server/cmd/multica/cmd_autopilot.goindex b754ac233e..c0a30562ba 100644--- a/server/cmd/multica/cmd_autopilot.go+++ b/server/cmd/multica/cmd_autopilot.go@@ -837,6 +837,10 @@ func runAutopilotTriggerAdd(cmd *cobra.Command, args []string) error {ctx, cancel := cli.APIContext(context.Background())defer cancel()+ if err := requireWebhookPayloadConditionsSupport(ctx, client, filters); err != nil {+ return err+ }+autopilotRef, err := resolveAutopilotID(ctx, client, args[0])if err != nil {return fmt.Errorf("resolve autopilot: %w", err)@@ -963,6 +967,10 @@ func runAutopilotTriggerUpdate(cmd *cobra.Command, args []string) error {ctx, cancel := cli.APIContext(context.Background())defer cancel()+ if err := requireWebhookPayloadConditionsSupport(ctx, client, filters); err != nil {+ return err+ }+autopilotRef, err := resolveAutopilotID(ctx, client, args[0])if err != nil {return fmt.Errorf("resolve autopilot: %w", err)@@ -987,8 +995,36 @@ func runAutopilotTriggerUpdate(cmd *cobra.Command, args []string) error {}type autopilotEventFilter struct {- Event string `json:"event"`- Actions []string `json:"actions,omitempty"`+ Event string `json:"event"`+ Actions []string `json:"actions,omitempty"`+ Conditions []autopilotPayloadCondition `json:"conditions,omitempty"`+}++type autopilotPayloadCondition struct {+ Path string `json:"path"`+ Op string `json:"op"`+ Value any `json:"value,omitempty"`+ Values []any `json:"values,omitempty"`+ IgnoreCase bool `json:"ignore_case,omitempty"`+}++func requireWebhookPayloadConditionsSupport(ctx context.Context, client *cli.APIClient, filters []autopilotEventFilter) error {+ for _, filter := range filters {+ if len(filter.Conditions) == 0 {+ continue+ }+ var config struct {+ Supported bool `json:"webhook_payload_conditions_supported"`+ }+ if err := client.GetJSON(ctx, "/api/config", &config); err != nil {+ return fmt.Errorf("check webhook payload condition support: %w", err)+ }+ if !config.Supported {+ return fmt.Errorf("this server version does not support webhook payload conditions; update the server before saving them")+ }+ break+ }+ return nil}func autopilotEventFiltersInput(cmd *cobra.Command) ([]autopilotEventFilter, error) {diff --git a/server/cmd/multica/cmd_autopilot_event_filters_test.go b/server/cmd/multica/cmd_autopilot_event_filters_test.goindex 1f8915adb0..23b07cb6c0 100644--- a/server/cmd/multica/cmd_autopilot_event_filters_test.go+++ b/server/cmd/multica/cmd_autopilot_event_filters_test.go@@ -27,7 +27,7 @@ func resetAutopilotFilterFlags(t *testing.T, cmd *cobra.Command) {}func TestAutopilotEventFiltersRequests(t *testing.T) {- const filters = `[{"event":"pull_request_review","actions":["submitted"]},{"event":"push"}]`+ const filters = `[{"event":"pull_request_review","actions":["submitted"],"conditions":[{"path":"pull_request.draft","op":"equals","value":false},{"path":"pull_request.base.ref","op":"in","values":["main","release"],"ignore_case":true}]},{"event":"push"}]`for _, tc := range []struct {name, file, label stringcreate, clear bool@@ -70,6 +70,10 @@ func TestAutopilotEventFiltersRequests(t *testing.T) {var got map[string]anyrequests := 0srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method == http.MethodGet && r.URL.Path == "/api/config" {+ _ = json.NewEncoder(w).Encode(map[string]bool{"webhook_payload_conditions_supported": true})+ return+ }requests++wantMethod, wantPath := http.MethodPatch, "/api/autopilots/11111111-1111-1111-1111-111111111111/triggers/22222222-2222-2222-2222-222222222222"if tc.create {@@ -114,6 +118,41 @@ func TestAutopilotEventFiltersRequests(t *testing.T) {}}+func TestAutopilotEventFiltersRefusesPayloadConditionsOnOlderServer(t *testing.T) {+ for _, create := range []bool{false, true} {+ cmd := autopilotTriggerUpdateCmd+ if create {+ cmd = autopilotTriggerAddCmd+ }+ resetAutopilotFilterFlags(t, cmd)+ if create {+ _ = cmd.Flags().Set("kind", "webhook")+ }+ path := filepath.Join(t.TempDir(), "filters.json")+ if err := os.WriteFile(path, []byte(`[{"event":"pull_request","conditions":[{"path":"draft","op":"equals","value":false}]}]`), 0600); err != nil {+ t.Fatal(err)+ }+ _ = cmd.Flags().Set("event-filters-file", path)+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet || r.URL.Path != "/api/config" {+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)+ }+ _, _ = w.Write([]byte(`{}`))+ }))+ setCLITestServerEnv(t, srv.URL)+ var err error+ if create {+ err = runAutopilotTriggerAdd(cmd, []string{"11111111-1111-1111-1111-111111111111"})+ } else {+ err = runAutopilotTriggerUpdate(cmd, []string{"11111111-1111-1111-1111-111111111111", "22222222-2222-2222-2222-222222222222"})+ }+ srv.Close()+ if err == nil || !strings.Contains(err.Error(), "does not support webhook payload conditions") {+ t.Fatalf("expected unsupported-server error, got %v", err)+ }+ }+}+func TestAutopilotEventFiltersRejectInvalidInput(t *testing.T) {for _, tc := range []struct {name, file, want stringdiff --git a/server/internal/handler/autopilot_webhook.go b/server/internal/handler/autopilot_webhook.goindex 015c64d1cb..594d4fcc0e 100644--- a/server/internal/handler/autopilot_webhook.go+++ b/server/internal/handler/autopilot_webhook.go@@ -17,6 +17,7 @@ import ("strconv""strings""time"+ "unicode/utf8""github.com/go-chi/chi/v5""github.com/jackc/pgx/v5"@@ -549,14 +550,14 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)// 10. Event filter scope → ignored. If the trigger declares a concrete// event_filters list and the incoming event is outside that scope,// record an ignored delivery without creating an expensive run/task.- if !webhookEventAllowedByTriggerScope(trigRow.EventFilters, envelope) {+ if decision := evaluateWebhookTriggerScope(trigRow.EventFilters, envelope); !decision.Allowed {respBody := map[string]any{"status": "ignored","delivery_id": uuidToString(delivery.ID),- "reason": "event_filtered",+ "reason": decision.ReasonCode,"event": envelope.Event,}- h.finaliseDeliveryTerminal(r, delivery.ID, deliveryStatusIgnored, http.StatusOK, respBody, "event_filtered")+ h.finaliseDeliveryTerminal(r, delivery.ID, deliveryStatusIgnored, http.StatusOK, respBody, decision.storedError(), decision.ReasonCode)writeJSON(w, http.StatusOK, respBody)return}@@ -632,16 +633,46 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)// ── Event filter helpers ────────────────────────────────────────────────────-// WebhookEventFilter declares one event and an optional list of actions.-// A nil/empty Actions means "any action" for this event.+// WebhookEventFilter declares one event, an optional list of actions and+// optional payload conditions. A nil/empty Actions means "any action" for+// this event; every condition must hold for the filter to match.type WebhookEventFilter struct {- Event string `json:"event"`- Actions []string `json:"actions,omitempty"`+ Event string `json:"event"`+ Actions []string `json:"actions,omitempty"`+ Conditions []WebhookPayloadCondition `json:"conditions,omitempty"`}+// WebhookPayloadCondition tests one field of the event payload. Path is a+// dot-separated walk through objects; numeric segments index arrays and "*"+// matches any element.+type WebhookPayloadCondition struct {+ Path string `json:"path"`+ Op string `json:"op"`+ Value any `json:"value,omitempty"`+ Values []any `json:"values,omitempty"`+ IgnoreCase bool `json:"ignore_case,omitempty"`+}++const (+ payloadOpEquals = "equals"+ payloadOpNotEquals = "not_equals"+ payloadOpContains = "contains"+ payloadOpIn = "in"+ payloadOpExists = "exists"+)++const webhookPathWildcard = "*"++// Payload condition limits bound rule evaluation before run admission.+const (+ maxWebhookPayloadConditions = 20+ maxWebhookPayloadConditionPathLength = 256+ maxWebhookPayloadConditionValues = 100+)+// validateWebhookEventFilters enforces the contract at the HTTP boundary so// that malformed shapes never reach the database. The matcher (read path)-// trusts whatever is stored — see webhookEventAllowedByTriggerScope.+// also fails closed on malformed stored conditions.func validateWebhookEventFilters(filters []WebhookEventFilter) error {for i, f := range filters {if strings.TrimSpace(f.Event) == "" {@@ -652,10 +683,69 @@ func validateWebhookEventFilters(filters []WebhookEventFilter) error {return fmt.Errorf("event_filters[%d].actions[%d] must not be empty", i, j)}}+ if len(f.Conditions) > maxWebhookPayloadConditions {+ return fmt.Errorf("event_filters[%d].conditions must not exceed %d entries", i, maxWebhookPayloadConditions)+ }+ for j, c := range f.Conditions {+ if err := validateWebhookPayloadCondition(c); err != nil {+ return fmt.Errorf("event_filters[%d].conditions[%d]: %w", i, j, err)+ }+ }+ }+ return nil+}++func validateWebhookPayloadCondition(c WebhookPayloadCondition) error {+ if strings.TrimSpace(c.Path) == "" {+ return errors.New("path must not be empty")+ }+ if utf8.RuneCountInString(c.Path) > maxWebhookPayloadConditionPathLength {+ return fmt.Errorf("path must not exceed %d characters", maxWebhookPayloadConditionPathLength)+ }+ for _, seg := range strings.Split(c.Path, ".") {+ if seg == "" {+ return errors.New("path must not contain empty segments")+ }+ }+ switch c.Op {+ case payloadOpEquals, payloadOpNotEquals:+ if !isScalarConditionValue(c.Value) {+ return errors.New("value must be a string, number or boolean")+ }+ case payloadOpContains:+ if s, ok := c.Value.(string); !ok || s == "" {+ return errors.New("value must be a non-empty string")+ }+ case payloadOpIn:+ if len(c.Values) == 0 {+ return errors.New("values must not be empty")+ }+ if len(c.Values) > maxWebhookPayloadConditionValues {+ return fmt.Errorf("values must not exceed %d entries", maxWebhookPayloadConditionValues)+ }+ for _, v := range c.Values {+ if !isScalarConditionValue(v) {+ return errors.New("values must be strings, numbers or booleans")+ }+ }+ case payloadOpExists:+ if c.Value != nil || len(c.Values) > 0 {+ return errors.New("exists takes no value")+ }+ default:+ return fmt.Errorf("op must be one of %s, %s, %s, %s, %s", payloadOpEquals, payloadOpNotEquals, payloadOpContains, payloadOpIn, payloadOpExists)}return nil}+func isScalarConditionValue(v any) bool {+ switch v.(type) {+ case string, float64, bool:+ return true+ }+ return false+}+// encodeWebhookEventFilters returns the JSONB bytes to persist for a CREATE.// nil/empty input maps to nil bytes (column stays NULL → matcher allows// every event), so we never write an explicit `[]` on create.@@ -678,12 +768,11 @@ func encodeWebhookEventFiltersAlways(filters []WebhookEventFilter) ([]byte, erroreturn json.Marshal(filters)}-// webhookEventAllowedByTriggerScope returns true when the trigger has no-// filters (NULL / empty) or when the incoming envelope matches at least one-// declared filter.-func webhookEventAllowedByTriggerScope(eventFilters []byte, envelope WebhookEnvelope) bool {+// evaluateWebhookTriggerScope records the first failing condition from the+// first event/action-compatible row, unless a later row accepts the delivery.+func evaluateWebhookTriggerScope(eventFilters []byte, envelope WebhookEnvelope) webhookFilterDecision {if len(eventFilters) == 0 {- return true+ return webhookFilterDecision{Allowed: true}}var filters []WebhookEventFilterif err := json.Unmarshal(eventFilters, &filters); err != nil {@@ -693,27 +782,49 @@ func webhookEventAllowedByTriggerScope(eventFilters []byte, envelope WebhookEnve// "only allow X" policy is worse than dropping events until an// operator notices.slog.Warn("webhook: malformed event_filters, denying", "error", err)- return false+ return webhookFilterDecision{ReasonCode: "event_filtered"}}if len(filters) == 0 {- return true+ return webhookFilterDecision{Allowed: true}}_, eventName, eventAction := splitWebhookEvent(envelope.Event)actionCandidates := webhookActionCandidates(eventAction, envelope.EventPayload)- for _, f := range filters {+ var payload any+ payloadDecoded := false+ decision := webhookFilterDecision{ReasonCode: "event_filtered"}+ for filterIndex, f := range filters {if f.Event != eventName {continue}- if len(f.Actions) == 0 {- return true+ if !webhookActionAllowed(f.Actions, actionCandidates) {+ continue}- for _, action := range actionCandidates {- for _, allowed := range f.Actions {- if action == allowed {- return true- }+ if len(f.Conditions) == 0 {+ return webhookFilterDecision{Allowed: true}+ }+ if len(f.Conditions) > maxWebhookPayloadConditions {+ decision.ReasonCode = "payload_filtered"+ continue+ }+ if !payloadDecoded {+ // Undecodable payloads leave payload nil, so every condition+ // fails and the filter denies.+ _ = json.Unmarshal(envelope.EventPayload, &payload)+ payloadDecoded = true+ }+ var failure *WebhookPayloadConditionFailure+ for conditionIndex, c := range f.Conditions {+ if validateWebhookPayloadCondition(c) != nil || !webhookPayloadConditionHolds(c, payload) {+ failure = newWebhookPayloadConditionFailure(c, payload, filterIndex, conditionIndex)+ break}}+ if failure == nil {+ return webhookFilterDecision{Allowed: true}+ }+ if decision.Failure == nil {+ decision = webhookFilterDecision{ReasonCode: "payload_filtered", Failure: failure}+ }// Intentionally do NOT return false here: the UI allows several// filters that share the same event name (e.g. two workflow_run// rows covering disjoint actions). Earlier code short-circuited@@ -721,7 +832,7 @@ func webhookEventAllowedByTriggerScope(eventFilters []byte, envelope WebhookEnve// the others depending on iteration order — see PR #3231 review.// Keep scanning so any later filter still gets its chance.}- return false+ return decision}// splitWebhookEvent splits a normalized event like "github.workflow_run.completed"@@ -778,6 +889,130 @@ func webhookActionCandidates(eventAction string, payload json.RawMessage) []strireturn out}+func webhookActionAllowed(allowed, candidates []string) bool {+ if len(allowed) == 0 {+ return true+ }+ for _, action := range candidates {+ for _, a := range allowed {+ if action == a {+ return true+ }+ }+ }+ return false+}++// webhookPayloadConditionHolds resolves the path to every value it reaches+// (a "*" segment fans out over array elements). equals, contains, in and+// exists hold when any value matches; not_equals holds when none does. A+// missing path never matches. An empty wildcard expansion satisfies+// not_equals; exists ignores JSON nulls.+func webhookPayloadConditionHolds(c WebhookPayloadCondition, payload any) bool {+ values, found := resolveWebhookPayloadPath(payload, strings.Split(c.Path, "."))+ if !found {+ return false+ }+ if c.Op == payloadOpNotEquals {+ for _, got := range values {+ if webhookConditionValuesEqual(got, c.Value, c.IgnoreCase) {+ return false+ }+ }+ return true+ }+ for _, got := range values {+ if webhookConditionValueMatches(c, got) {+ return true+ }+ }+ return false+}++func webhookConditionValueMatches(c WebhookPayloadCondition, got any) bool {+ switch c.Op {+ case payloadOpExists:+ return got != nil+ case payloadOpEquals:+ return webhookConditionValuesEqual(got, c.Value, c.IgnoreCase)+ case payloadOpContains:+ s, ok := got.(string)+ want, wantOK := c.Value.(string)+ if !ok || !wantOK {+ return false+ }+ if c.IgnoreCase {+ return strings.Contains(strings.ToLower(s), strings.ToLower(want))+ }+ return strings.Contains(s, want)+ case payloadOpIn:+ for _, v := range c.Values {+ if webhookConditionValuesEqual(got, v, c.IgnoreCase) {+ return true+ }+ }+ }+ return false+}++// resolveWebhookPayloadPath walks objects by key and arrays by index or+// "*". Each payload node is visited at most once per path, so the work is+// bounded by the body size cap.+func resolveWebhookPayloadPath(node any, segs []string) ([]any, bool) {+ if len(segs) == 0 {+ return []any{node}, true+ }+ seg, rest := segs[0], segs[1:]+ switch n := node.(type) {+ case map[string]any:+ next, ok := n[seg]+ if !ok {+ return nil, false+ }+ return resolveWebhookPayloadPath(next, rest)+ case []any:+ if seg == webhookPathWildcard {+ var out []any+ found := len(n) == 0+ for _, el := range n {+ values, resolved := resolveWebhookPayloadPath(el, rest)+ out = append(out, values...)+ found = found || resolved+ }+ return out, found+ }+ idx, err := strconv.Atoi(seg)+ if err != nil || idx < 0 || idx >= len(n) {+ return nil, false+ }+ return resolveWebhookPayloadPath(n[idx], rest)+ }+ return nil, false+}++// webhookConditionValuesEqual compares JSON-decoded scalars. Mismatched+// types never compare equal, so "false" does not match false.+func webhookConditionValuesEqual(got, want any, ignoreCase bool) bool {+ switch w := want.(type) {+ case string:+ g, ok := got.(string)+ if !ok {+ return false+ }+ if ignoreCase {+ return strings.EqualFold(g, w)+ }+ return g == w+ case float64:+ g, ok := got.(float64)+ return ok && g == w+ case bool:+ g, ok := got.(bool)+ return ok && g == w+ }+ return false+}+// ── Persistence helpers ─────────────────────────────────────────────────────type persistDeliveryInput struct {diff --git a/server/internal/handler/autopilot_webhook_handler_test.go b/server/internal/handler/autopilot_webhook_handler_test.goindex ce6c3ee3a4..b1cb1204e8 100644--- a/server/internal/handler/autopilot_webhook_handler_test.go+++ b/server/internal/handler/autopilot_webhook_handler_test.go@@ -211,6 +211,61 @@ func TestWebhookHandler_AllowsDeclaredEvent(t *testing.T) {}}+func TestWebhookHandler_PayloadConditionsGateRuns(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WebhookConditions Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ trig := createWebhookTriggerWithFilters(t, apID, []WebhookEventFilter{{+ Event: "issues",+ Actions: []string{"labeled"},+ Conditions: []WebhookPayloadCondition{+ {Path: "label.name", Op: payloadOpEquals, Value: "agent"},+ {Path: "sender.type", Op: payloadOpNotEquals, Value: "Bot"},+ },+ }})+ if len(trig.EventFilters) != 1 || len(trig.EventFilters[0].Conditions) != 2 {+ t.Fatalf("conditions should round-trip on create, got %#v", trig.EventFilters)+ }+ headers := map[string]string{"X-GitHub-Event": "issues"}++ w := postWebhook(t, *trig.WebhookToken, map[string]any{+ "action": "labeled", "label": map[string]any{"name": "bug"}, "sender": map[string]any{"type": "User"},+ }, headers)+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if w.Code != http.StatusOK || resp["status"] != "ignored" || resp["reason"] != "payload_filtered" {+ t.Fatalf("expected ignored/payload_filtered, got %d %#v", w.Code, resp)+ }++ w = postWebhook(t, *trig.WebhookToken, map[string]any{+ "action": "labeled", "label": map[string]any{"name": "agent"}, "sender": map[string]any{"type": "User"},+ }, headers)+ delivery := processQueuedWebhookDelivery(t, requireAcceptedWebhookResponse(t, w))+ if delivery.Status != deliveryStatusDispatched || !delivery.AutopilotRunID.Valid {+ t.Fatalf("expected worker dispatch, got status=%s run=%v", delivery.Status, delivery.AutopilotRunID.Valid)+ }+}++func TestCreateAutopilotTrigger_RejectsInvalidPayloadCondition(t *testing.T) {+ agentID := createWebhookTestAgent(t, "ConditionInvalid Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")++ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/autopilots/"+apID+"/triggers", map[string]any{+ "kind": "webhook",+ "event_filters": []map[string]any{{+ "event": "issues",+ "conditions": []map[string]any{{"path": "label.name", "op": "matches", "value": "agent"}},+ }},+ })+ req = withURLParam(req, "id", apID)+ testHandler.CreateAutopilotTrigger(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 on unknown op, got %d body=%s", w.Code, w.Body.String())+ }+}+func TestWebhookHandler_EmptyFiltersAllowsAll(t *testing.T) {agentID := createWebhookTestAgent(t, "WebhookEmptyFilter Agent")apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")@@ -324,7 +379,7 @@ func TestUpdateWebhookTrigger_ExplicitEmptyArrayClearsFilters(t *testing.T) {Event: "github.something_else.opened",EventPayload: json.RawMessage(`{"action":"opened"}`),}- if !webhookEventAllowedByTriggerScope(row.EventFilters, env) {+ if !evaluateWebhookTriggerScope(row.EventFilters, env).Allowed {t.Fatal("after clear, matcher should allow all events")}}diff --git a/server/internal/handler/autopilot_webhook_test.go b/server/internal/handler/autopilot_webhook_test.goindex d79f48097f..45e98cca6e 100644--- a/server/internal/handler/autopilot_webhook_test.go+++ b/server/internal/handler/autopilot_webhook_test.go@@ -204,13 +204,13 @@ func TestNormalizeWebhookPayload_XEventTypeHeader(t *testing.T) {// ── Event filter helpers ────────────────────────────────────────────────────func TestWebhookEventAllowedByTriggerScope_NoFiltersAllowsAll(t *testing.T) {- if !webhookEventAllowedByTriggerScope(nil, WebhookEnvelope{Event: "github.push"}) {+ if !evaluateWebhookTriggerScope(nil, WebhookEnvelope{Event: "github.push"}).Allowed {t.Fatal("nil filters should allow all")}- if !webhookEventAllowedByTriggerScope([]byte{}, WebhookEnvelope{Event: "github.push"}) {+ if !evaluateWebhookTriggerScope([]byte{}, WebhookEnvelope{Event: "github.push"}).Allowed {t.Fatal("empty filters should allow all")}- if !webhookEventAllowedByTriggerScope([]byte("[]"), WebhookEnvelope{Event: "github.push"}) {+ if !evaluateWebhookTriggerScope([]byte("[]"), WebhookEnvelope{Event: "github.push"}).Allowed {t.Fatal("empty JSON array should allow all")}}@@ -218,7 +218,7 @@ func TestWebhookEventAllowedByTriggerScope_NoFiltersAllowsAll(t *testing.T) {func TestWebhookEventAllowedByTriggerScope_FiltersUndeclaredEvent(t *testing.T) {filters := []byte(`[{"event":"workflow_run","actions":["completed"]}]`)env := WebhookEnvelope{Event: "github.push", EventPayload: json.RawMessage(`{"action":"pushed"}`)}- if webhookEventAllowedByTriggerScope(filters, env) {+ if evaluateWebhookTriggerScope(filters, env).Allowed {t.Fatal("undeclared event should be filtered")}}@@ -226,7 +226,7 @@ func TestWebhookEventAllowedByTriggerScope_FiltersUndeclaredEvent(t *testing.T)func TestWebhookEventAllowedByTriggerScope_FiltersUndeclaredAction(t *testing.T) {filters := []byte(`[{"event":"workflow_run","actions":["completed"]}]`)env := WebhookEnvelope{Event: "github.workflow_run.in_progress", EventPayload: json.RawMessage(`{"action":"in_progress"}`)}- if webhookEventAllowedByTriggerScope(filters, env) {+ if evaluateWebhookTriggerScope(filters, env).Allowed {t.Fatal("undeclared action should be filtered")}}@@ -234,7 +234,7 @@ func TestWebhookEventAllowedByTriggerScope_FiltersUndeclaredAction(t *testing.T)func TestWebhookEventAllowedByTriggerScope_AllowsDeclaredAction(t *testing.T) {filters := []byte(`[{"event":"workflow_run","actions":["completed"]}]`)env := WebhookEnvelope{Event: "github.workflow_run.completed", EventPayload: json.RawMessage(`{"action":"completed"}`)}- if !webhookEventAllowedByTriggerScope(filters, env) {+ if !evaluateWebhookTriggerScope(filters, env).Allowed {t.Fatal("declared action should be allowed")}}@@ -242,7 +242,7 @@ func TestWebhookEventAllowedByTriggerScope_AllowsDeclaredAction(t *testing.T) {func TestWebhookEventAllowedByTriggerScope_AnyActionWhenEmpty(t *testing.T) {filters := []byte(`[{"event":"workflow_run"}]`)env := WebhookEnvelope{Event: "github.workflow_run.in_progress", EventPayload: json.RawMessage(`{"action":"in_progress"}`)}- if !webhookEventAllowedByTriggerScope(filters, env) {+ if !evaluateWebhookTriggerScope(filters, env).Allowed {t.Fatal("empty actions should allow any action for the event")}}@@ -263,7 +263,7 @@ func TestWebhookEventAllowedByTriggerScope_MultipleFiltersSameEvent(t *testing.TEvent: "github.workflow_run.completed",EventPayload: json.RawMessage(`{"action":"completed"}`),}- if !webhookEventAllowedByTriggerScope(filters, completed) {+ if !evaluateWebhookTriggerScope(filters, completed).Allowed {t.Fatal("workflow_run.completed should match the first filter")}@@ -271,7 +271,7 @@ func TestWebhookEventAllowedByTriggerScope_MultipleFiltersSameEvent(t *testing.TEvent: "github.workflow_run.requested",EventPayload: json.RawMessage(`{"action":"requested"}`),}- if !webhookEventAllowedByTriggerScope(filters, requested) {+ if !evaluateWebhookTriggerScope(filters, requested).Allowed {t.Fatal("workflow_run.requested should match the second filter — pre-fix this silently dropped")}@@ -279,7 +279,7 @@ func TestWebhookEventAllowedByTriggerScope_MultipleFiltersSameEvent(t *testing.TEvent: "github.workflow_run.in_progress",EventPayload: json.RawMessage(`{"action":"in_progress"}`),}- if webhookEventAllowedByTriggerScope(filters, inProgress) {+ if evaluateWebhookTriggerScope(filters, inProgress).Allowed {t.Fatal("workflow_run.in_progress is in neither filter and should be filtered out")}}@@ -294,7 +294,7 @@ func TestWebhookEventAllowedByTriggerScope_MalformedDenies(t *testing.T) {Event: "github.workflow_run.completed",EventPayload: json.RawMessage(`{"action":"completed"}`),}- if webhookEventAllowedByTriggerScope(corrupt, env) {+ if evaluateWebhookTriggerScope(corrupt, env).Allowed {t.Fatal("malformed event_filters must fail closed (deny), never widen the allowlist")}}@@ -303,21 +303,147 @@ func TestWebhookEventAllowedByTriggerScope_MultipleFilters(t *testing.T) {filters := []byte(`[{"event":"workflow_run","actions":["completed"]},{"event":"check_suite","actions":["completed","failure"]}]`)allowed1 := WebhookEnvelope{Event: "github.check_suite.completed", EventPayload: json.RawMessage(`{"action":"completed"}`)}- if !webhookEventAllowedByTriggerScope(filters, allowed1) {+ if !evaluateWebhookTriggerScope(filters, allowed1).Allowed {t.Fatal("check_suite.completed should be allowed")}allowed2 := WebhookEnvelope{Event: "github.check_suite.failure", EventPayload: json.RawMessage(`{"action":"failure"}`)}- if !webhookEventAllowedByTriggerScope(filters, allowed2) {+ if !evaluateWebhookTriggerScope(filters, allowed2).Allowed {t.Fatal("check_suite.failure should be allowed")}filtered := WebhookEnvelope{Event: "github.check_suite.requested", EventPayload: json.RawMessage(`{"action":"requested"}`)}- if webhookEventAllowedByTriggerScope(filters, filtered) {+ if evaluateWebhookTriggerScope(filters, filtered).Allowed {t.Fatal("check_suite.requested should be filtered")}}+// reviewFilters scopes pull_request deliveries to ready, labelled PRs on+// release branches that weren't opened by a bot.+const reviewFilters = `[{"event":"pull_request","actions":["opened","synchronize"],"conditions":[+ {"path":"pull_request.draft","op":"equals","value":false},+ {"path":"pull_request.labels.*.name","op":"equals","value":"needs-review","ignore_case":true},+ {"path":"pull_request.base.ref","op":"in","values":["main","release"]},+ {"path":"sender.type","op":"not_equals","value":"Bot"}+]}]`++func pullRequestEnvelope(payload string) WebhookEnvelope {+ return WebhookEnvelope{Event: "github.pull_request.opened", EventPayload: json.RawMessage(payload)}+}++func TestWebhookEventAllowedByTriggerScope_PayloadConditions(t *testing.T) {+ filters := []byte(reviewFilters)+ const labelled = `"labels":[{"name":"backend"},{"name":"Needs-Review"}]`+ cases := []struct {+ name string+ payload string+ want bool+ }{+ {"all conditions hold", `{"action":"opened","pull_request":{"draft":false,` + labelled + `,"base":{"ref":"main"}},"sender":{"type":"User"}}`, true},+ {"draft", `{"action":"opened","pull_request":{"draft":true,` + labelled + `,"base":{"ref":"main"}},"sender":{"type":"User"}}`, false},+ {"label missing", `{"action":"opened","pull_request":{"draft":false,"labels":[{"name":"backend"}],"base":{"ref":"main"}},"sender":{"type":"User"}}`, false},+ {"no labels", `{"action":"opened","pull_request":{"draft":false,"labels":[],"base":{"ref":"main"}},"sender":{"type":"User"}}`, false},+ {"other base branch", `{"action":"opened","pull_request":{"draft":false,` + labelled + `,"base":{"ref":"dev"}},"sender":{"type":"User"}}`, false},+ {"bot sender", `{"action":"opened","pull_request":{"draft":false,` + labelled + `,"base":{"ref":"main"}},"sender":{"type":"Bot"}}`, false},+ {"missing path", `{"action":"opened","pull_request":{"draft":false,` + labelled + `}}`, false},+ {"string is not a boolean", `{"action":"opened","pull_request":{"draft":"false",` + labelled + `,"base":{"ref":"main"}},"sender":{"type":"User"}}`, false},+ {"non-object payload", `["needs-review"]`, false},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := evaluateWebhookTriggerScope(filters, pullRequestEnvelope(tc.payload)).Allowed; got != tc.want {+ t.Fatalf("got %v, want %v", got, tc.want)+ }+ })+ }+}++func TestWebhookEventAllowedByTriggerScope_ConditionsDoNotShadowLaterFilters(t *testing.T) {+ filters := []byte(`[+ {"event":"pull_request","conditions":[{"path":"pull_request.draft","op":"equals","value":false}]},+ {"event":"pull_request","conditions":[{"path":"pull_request.number","op":"equals","value":42}]}+ ]`)+ if !evaluateWebhookTriggerScope(filters, pullRequestEnvelope(`{"pull_request":{"draft":true,"number":42}}`)).Allowed {+ t.Fatal("second filter should match when the first one's conditions fail")+ }+}++func TestWebhookEventAllowedByTriggerScope_ConditionOps(t *testing.T) {+ payload := `{"status":"Open","closed_at":null,"count":3,"items":[{"tag":"urgent"},{"tag":"docs"}],"commits":[{"files":["a.go"]},{"files":["README.md"]}]}`+ cases := []struct {+ name string+ cond string+ want bool+ }{+ {"equals is case-sensitive by default", `{"path":"status","op":"equals","value":"open"}`, false},+ {"equals ignore_case", `{"path":"status","op":"equals","value":"open","ignore_case":true}`, true},+ {"not_equals", `{"path":"status","op":"not_equals","value":"Closed"}`, true},+ {"not_equals on missing path", `{"path":"missing","op":"not_equals","value":"x"}`, false},+ {"equals number", `{"path":"count","op":"equals","value":3}`, true},+ {"contains on number", `{"path":"count","op":"contains","value":"3"}`, false},+ {"array index", `{"path":"items.0.tag","op":"equals","value":"urgent"}`, true},+ {"array index out of range", `{"path":"items.2.tag","op":"equals","value":"urgent"}`, false},+ {"wildcard any element", `{"path":"items.*.tag","op":"equals","value":"docs"}`, true},+ {"wildcard no element", `{"path":"items.*.tag","op":"equals","value":"bug"}`, false},+ {"wildcard not_equals means none", `{"path":"items.*.tag","op":"not_equals","value":"docs"}`, false},+ {"wildcard not_equals holds", `{"path":"items.*.tag","op":"not_equals","value":"bug"}`, true},+ {"nested wildcards", `{"path":"commits.*.files.*","op":"contains","value":".md"}`, true},+ {"wildcard on object", `{"path":"status.*","op":"equals","value":"Open"}`, false},+ {"in ignore_case", `{"path":"status","op":"in","values":["closed","open"],"ignore_case":true}`, true},+ {"exists", `{"path":"items.*.tag","op":"exists"}`, true},+ {"exists on missing path", `{"path":"merged_at","op":"exists"}`, false},+ {"exists ignores null", `{"path":"closed_at","op":"exists"}`, false},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ filters := []byte(`[{"event":"pull_request","conditions":[` + tc.cond + `]}]`)+ if got := evaluateWebhookTriggerScope(filters, pullRequestEnvelope(payload)).Allowed; got != tc.want {+ t.Fatalf("got %v, want %v", got, tc.want)+ }+ })+ }+}++func TestValidateWebhookEventFilters_Conditions(t *testing.T) {+ var valid []WebhookEventFilter+ if err := json.Unmarshal([]byte(reviewFilters), &valid); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if err := validateWebhookEventFilters(valid); err != nil {+ t.Fatalf("valid filters rejected: %v", err)+ }++ invalid := map[string]string{+ "empty path": `{"path":"","op":"equals","value":"x"}`,+ "empty segment": `{"path":"sender..type","op":"equals","value":"x"}`,+ "unknown op": `{"path":"sender.type","op":"matches","value":"x"}`,+ "missing value": `{"path":"sender.type","op":"equals"}`,+ "object value": `{"path":"sender.type","op":"equals","value":{"a":1}}`,+ "contains non-text": `{"path":"sender.type","op":"contains","value":1}`,+ "empty in": `{"path":"sender.type","op":"in","values":[]}`,+ "exists with value": `{"path":"sender.type","op":"exists","value":"x"}`,+ }+ for name, cond := range invalid {+ t.Run(name, func(t *testing.T) {+ var filters []WebhookEventFilter+ if err := json.Unmarshal([]byte(`[{"event":"pull_request","conditions":[`+cond+`]}]`), &filters); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if err := validateWebhookEventFilters(filters); err == nil {+ t.Fatal("expected validation error")+ }+ })+ }++ tooMany := WebhookEventFilter{Event: "pull_request"}+ for range maxWebhookPayloadConditions + 1 {+ tooMany.Conditions = append(tooMany.Conditions, WebhookPayloadCondition{Path: "a", Op: payloadOpEquals, Value: "x"})+ }+ if err := validateWebhookEventFilters([]WebhookEventFilter{tooMany}); err == nil {+ t.Fatal("expected error above the condition cap")+ }+}+func TestSplitWebhookEvent(t *testing.T) {tests := []struct {input stringdiff --git a/server/internal/handler/config.go b/server/internal/handler/config.goindex 8f06ee535b..ea9d0da2ad 100644--- a/server/internal/handler/config.go+++ b/server/internal/handler/config.go@@ -93,6 +93,8 @@ type AppConfig struct {// ignored the unknown JSON field and still returned success, so clients// must fail closed when this declaration is absent.AgentConversationStartersSupported bool `json:"agent_conversation_starters_supported"`+ // Older builds acknowledge trigger writes while dropping conditions.+ WebhookPayloadConditionsSupported bool `json:"webhook_payload_conditions_supported"`// IssueCreatePropertiesSupported tells independently deployed clients that// POST /api/issues validates and persists the optional properties bag.@@ -131,6 +133,7 @@ func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {// running, the save gate is running with it.LocalWorktreeSupported: true,AgentConversationStartersSupported: true,+ WebhookPayloadConditionsSupported: true,IssueCreatePropertiesSupported: true,CommentDeleteKeepRepliesSupported: true,IssueBatchOpsSupported: true,diff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.goindex 2fa3d4fdcb..618bfe34ae 100644--- a/server/internal/handler/config_test.go+++ b/server/internal/handler/config_test.go@@ -613,6 +613,9 @@ func TestGetConfigDeclaresAgentConversationStartersSupport(t *testing.T) {if !cfg.AgentConversationStartersSupported {t.Fatal("this build persists conversation_starters but does not advertise the contract")}+ if !cfg.WebhookPayloadConditionsSupported {+ t.Fatal("this build must declare webhook payload condition support")+ }var raw map[string]anyif err := json.Unmarshal(w.Body.Bytes(), &raw); err != nil {t.Fatalf("decode raw config: %v", err)diff --git a/server/internal/handler/webhook_delivery.go b/server/internal/handler/webhook_delivery.goindex 30423ee6bc..82856e080f 100644--- a/server/internal/handler/webhook_delivery.go+++ b/server/internal/handler/webhook_delivery.go@@ -24,29 +24,30 @@ import (// populated; the detail endpoint includes both for debugging. We never echo// the signing secret or token through this surface.type WebhookDeliveryResponse struct {- ID string `json:"id"`- WorkspaceID string `json:"workspace_id"`- AutopilotID string `json:"autopilot_id"`- TriggerID string `json:"trigger_id"`- Provider string `json:"provider"`- Event string `json:"event"`- DedupeKey *string `json:"dedupe_key"`- DedupeSource *string `json:"dedupe_source"`- SignatureStatus string `json:"signature_status"`- Status string `json:"status"`- AttemptCount int32 `json:"attempt_count"`- DispatchAttempts int32 `json:"dispatch_attempts"`- AvailableAt string `json:"available_at"`- ContentType *string `json:"content_type"`- ResponseStatus *int32 `json:"response_status"`- AutopilotRunID *string `json:"autopilot_run_id"`- ReplayedFromDeliveryID *string `json:"replayed_from_delivery_id"`- Error *string `json:"error"`- ReasonCode *string `json:"reason_code"`- ReplayIdempotencyKey *string `json:"replay_idempotency_key"`- ReceivedAt string `json:"received_at"`- LastAttemptAt string `json:"last_attempt_at"`- CreatedAt string `json:"created_at"`+ PayloadConditionFailure *WebhookPayloadConditionFailure `json:"payload_condition_failure,omitempty"`+ ID string `json:"id"`+ WorkspaceID string `json:"workspace_id"`+ AutopilotID string `json:"autopilot_id"`+ TriggerID string `json:"trigger_id"`+ Provider string `json:"provider"`+ Event string `json:"event"`+ DedupeKey *string `json:"dedupe_key"`+ DedupeSource *string `json:"dedupe_source"`+ SignatureStatus string `json:"signature_status"`+ Status string `json:"status"`+ AttemptCount int32 `json:"attempt_count"`+ DispatchAttempts int32 `json:"dispatch_attempts"`+ AvailableAt string `json:"available_at"`+ ContentType *string `json:"content_type"`+ ResponseStatus *int32 `json:"response_status"`+ AutopilotRunID *string `json:"autopilot_run_id"`+ ReplayedFromDeliveryID *string `json:"replayed_from_delivery_id"`+ Error *string `json:"error"`+ ReasonCode *string `json:"reason_code"`+ ReplayIdempotencyKey *string `json:"replay_idempotency_key"`+ ReceivedAt string `json:"received_at"`+ LastAttemptAt string `json:"last_attempt_at"`+ CreatedAt string `json:"created_at"`// Detail-only fields. List responses leave these nil/empty so a page// of N deliveries never serialises ~N × 256 KiB of raw bodies. Detail@@ -96,6 +97,7 @@ func slimDeliveryToResponse(d db.ListWebhookDeliveriesByAutopilotRow) WebhookDelv := d.Error.Stringresp.Error = &v}+ resp.decodePayloadFilterFailure()return resp}@@ -150,6 +152,7 @@ func deliveryToResponse(d db.WebhookDelivery, detail bool) WebhookDeliveryResponresp.ResponseBody = &v}}+ resp.decodePayloadFilterFailure()return resp}diff --git a/server/internal/handler/webhook_delivery_worker.go b/server/internal/handler/webhook_delivery_worker.goindex 1478fefcde..5d848e2cd2 100644--- a/server/internal/handler/webhook_delivery_worker.go+++ b/server/internal/handler/webhook_delivery_worker.go@@ -183,8 +183,9 @@ func (w *WebhookDeliveryWorker) ProcessNext(ctx context.Context) (bool, error) {return true, w.complete(ctx, delivery, deliveryStatusIgnored, pgtype.UUID{}, "autopilot_archived")case autopilot.Status != "active":return true, w.complete(ctx, delivery, deliveryStatusIgnored, pgtype.UUID{}, "autopilot_paused")- case !webhookEventAllowedByTriggerScope(trigger.EventFilters, envelope):- return true, w.complete(ctx, delivery, deliveryStatusIgnored, pgtype.UUID{}, "event_filtered")+ }+ if decision := evaluateWebhookTriggerScope(trigger.EventFilters, envelope); !decision.Allowed {+ return true, w.complete(ctx, delivery, deliveryStatusIgnored, pgtype.UUID{}, decision.storedError(), decision.ReasonCode)}}diff --git a/server/internal/handler/webhook_payload_condition_limits_test.go b/server/internal/handler/webhook_payload_condition_limits_test.gonew file mode 100644index 0000000000..6a96ce6724--- /dev/null+++ b/server/internal/handler/webhook_payload_condition_limits_test.go@@ -0,0 +1,81 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestValidateWebhookPayloadConditionLimits(t *testing.T) {+ for _, character := range []string{"a", "界", "😀"} {+ for _, length := range []int{256, 257} {+ c := WebhookPayloadCondition{Path: strings.Repeat(character, length), Op: payloadOpExists}+ if err := validateWebhookPayloadCondition(c); (err == nil) != (length == 256) {+ t.Errorf("path %q x %d: %v", character, length, err)+ }+ }+ }+ for _, count := range []int{100, 101} {+ values := make([]any, count)+ for i := range values {+ values[i] = float64(i)+ }+ c := WebhookPayloadCondition{Path: "number", Op: payloadOpIn, Values: values}+ if err := validateWebhookPayloadCondition(c); (err == nil) != (count == 100) {+ t.Errorf("in list with %d values: %v", count, err)+ }+ filters, err := json.Marshal([]WebhookEventFilter{{Event: "pull_request", Conditions: []WebhookPayloadCondition{c}}})+ if err != nil {+ t.Fatal(err)+ }+ decision := evaluateWebhookTriggerScope(filters, pullRequestEnvelope(`{"number":0}`))+ if decision.Allowed != (count == 100) {+ t.Errorf("stored list with %d values: %+v", count, decision)+ }+ }+}++func TestWebhookPayloadConditionLimits_RejectCreateAndUpdate(t *testing.T) {+ agentID := createWebhookTestAgent(t, "Condition limit agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ trigger := createWebhookTriggerWithFilters(t, apID, []WebhookEventFilter{{Event: "push"}})+ tooManyValues := make([]any, 101)+ for i := range tooManyValues {+ tooManyValues[i] = float64(i)+ }+ for _, condition := range []WebhookPayloadCondition{+ {Path: strings.Repeat("x", 257), Op: payloadOpExists},+ {Path: "number", Op: payloadOpIn, Values: tooManyValues},+ } {+ for _, method := range []string{http.MethodPost, http.MethodPatch} {+ body := map[string]any{"event_filters": []WebhookEventFilter{{Event: "pull_request", Conditions: []WebhookPayloadCondition{condition}}}}+ if method == http.MethodPost {+ body["kind"] = "webhook"+ }+ req := withURLParams(newRequest(method, "/api/autopilots/"+apID+"/triggers", body), "id", apID, "triggerId", trigger.ID)+ w := httptest.NewRecorder()+ if method == http.MethodPost {+ testHandler.CreateAutopilotTrigger(w, req)+ } else {+ testHandler.UpdateAutopilotTrigger(w, req)+ }+ if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "must not exceed") {+ t.Fatalf("%s oversized condition: %d %s", method, w.Code, w.Body.String())+ }+ }+ }+ stored, err := testHandler.Queries.GetAutopilotTrigger(context.Background(), parseUUID(trigger.ID))+ if err != nil {+ t.Fatal(err)+ }+ var filters []WebhookEventFilter+ if err := json.Unmarshal(stored.EventFilters, &filters); err != nil {+ t.Fatal(err)+ }+ if len(filters) != 1 || filters[0].Event != "push" || len(filters[0].Conditions) != 0 {+ t.Fatalf("rejected updates modified the saved filters: %+v", filters)+ }+}diff --git a/server/internal/handler/webhook_payload_filter.go b/server/internal/handler/webhook_payload_filter.gonew file mode 100644index 0000000000..83728f3042--- /dev/null+++ b/server/internal/handler/webhook_payload_filter.go@@ -0,0 +1,71 @@+package handler++import (+ "encoding/json"+ "strings"+)++// WebhookPayloadConditionFailure is a snapshot of the admission decision,+// independent of subsequent trigger edits. ActualValues are JSON previews.+type WebhookPayloadConditionFailure struct {+ FilterIndex int `json:"filter_index"`+ ConditionIndex int `json:"condition_index"`+ Condition WebhookPayloadCondition `json:"condition"`+ ActualValues []string `json:"actual_values"`+ Missing bool `json:"missing"`+ Truncated bool `json:"truncated"`+}++type webhookFilterDecision struct {+ Allowed bool+ ReasonCode string+ Failure *WebhookPayloadConditionFailure+}++func newWebhookPayloadConditionFailure(c WebhookPayloadCondition, payload any, filterIndex, conditionIndex int) *WebhookPayloadConditionFailure {+ values, found := resolveWebhookPayloadPath(payload, strings.Split(c.Path, "."))+ failure := &WebhookPayloadConditionFailure{+ FilterIndex: filterIndex, ConditionIndex: conditionIndex, Condition: c,+ ActualValues: []string{}, Missing: !found,+ }+ // Keep delivery list responses bounded even for wildcard paths or object+ // values. The detail endpoint still exposes the original body in full.+ const maxValues, maxPreviewRunes = 10, 256+ if len(values) > maxValues {+ failure.Truncated = true+ values = values[:maxValues]+ }+ for _, value := range values {+ encoded, _ := json.Marshal(value)+ preview := []rune(string(encoded))+ if len(preview) > maxPreviewRunes {+ preview = append(preview[:maxPreviewRunes-1], '…')+ failure.Truncated = true+ }+ failure.ActualValues = append(failure.ActualValues, string(preview))+ }+ return failure+}++func (d webhookFilterDecision) storedError() string {+ if d.Failure == nil {+ return d.ReasonCode+ }+ // The existing diagnostic text column holds the snapshot, avoiding a+ // migration. API converters expose it as a typed, optional field and keep+ // error human-readable for older clients.+ encoded, _ := json.Marshal(d.Failure)+ return string(encoded)+}++func (r *WebhookDeliveryResponse) decodePayloadFilterFailure() {+ if r.ReasonCode == nil || *r.ReasonCode != "payload_filtered" || r.Error == nil {+ return+ }+ var failure WebhookPayloadConditionFailure+ if json.Unmarshal([]byte(*r.Error), &failure) == nil && failure.Condition.Path != "" {+ r.PayloadConditionFailure = &failure+ message := "payload_filtered: " + failure.Condition.Path+ r.Error = &message+ }+}diff --git a/server/internal/handler/webhook_payload_filter_test.go b/server/internal/handler/webhook_payload_filter_test.gonew file mode 100644index 0000000000..3fe61e7ccc--- /dev/null+++ b/server/internal/handler/webhook_payload_filter_test.go@@ -0,0 +1,170 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "reflect"+ "strings"+ "testing"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestWebhookPayloadFilter_EmptyWildcardAndMissingPaths(t *testing.T) {+ filters := []byte(`[{"event":"pull_request","conditions":[{"path":"pull_request.labels.*.name","op":"not_equals","value":"wip"}]}]`)+ for _, tc := range []struct {+ name, payload string+ allowed bool+ }{+ {"empty labels", `{"pull_request":{"labels":[]}}`, true},+ {"other label", `{"pull_request":{"labels":[{"name":"bug"}]}}`, true},+ {"wip anywhere", `{"pull_request":{"labels":[{"name":"bug"},{"name":"wip"}]}}`, false},+ {"missing labels", `{"pull_request":{}}`, false},+ {"null labels", `{"pull_request":{"labels":null}}`, false},+ {"wrong array type", `{"pull_request":{"labels":{}}}`, false},+ {"missing leaf", `{"pull_request":{"labels":[{}]}}`, false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ decision := evaluateWebhookTriggerScope(filters, pullRequestEnvelope(tc.payload))+ if decision.Allowed != tc.allowed {+ t.Fatalf("decision = %+v, want allowed=%v", decision, tc.allowed)+ }+ })+ }+}++func TestWebhookPayloadFilter_ReasonAndFirstFailure(t *testing.T) {+ filters := []byte(`[+ {"event":"issues","conditions":[{"path":"missing","op":"exists"}]},+ {"event":"pull_request","actions":["closed"],"conditions":[{"path":"missing","op":"exists"}]},+ {"event":"pull_request","conditions":[{"path":"draft","op":"equals","value":false},{"path":"base.ref","op":"equals","value":"main"},{"path":"sender","op":"equals","value":"alice"}]},+ {"event":"pull_request","conditions":[{"path":"override","op":"equals","value":true}]}+ ]`)+ for _, tc := range []struct {+ name, payload, reason string+ allowed bool+ }{+ {"first failed condition", `{"draft":false,"base":{"ref":"dev"},"sender":"bob"}`, "payload_filtered", false},+ {"later row accepts", `{"draft":false,"base":{"ref":"dev"},"override":true}`, "", true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ decision := evaluateWebhookTriggerScope(filters, pullRequestEnvelope(tc.payload))+ if decision.Allowed != tc.allowed || decision.ReasonCode != tc.reason {+ t.Fatalf("unexpected decision: %+v", decision)+ }+ if tc.allowed {+ if decision.Failure != nil {+ t.Fatal("allowed delivery must not retain a failed row's diagnostic")+ }+ return+ }+ failure := decision.Failure+ if failure == nil || failure.FilterIndex != 2 || failure.ConditionIndex != 1 || failure.Condition.Path != "base.ref" || !reflect.DeepEqual(failure.ActualValues, []string{`"dev"`}) {+ t.Fatalf("unexpected first failure: %+v", failure)+ }+ })+ }+ decision := evaluateWebhookTriggerScope(filters, WebhookEnvelope{Event: "github.push"})+ if decision.ReasonCode != "event_filtered" || decision.Failure != nil {+ t.Fatalf("event mismatch: %+v", decision)+ }+ decision = evaluateWebhookTriggerScope([]byte(`[{"event":"pull_request","actions":["closed"]}]`), pullRequestEnvelope(`{}`))+ if decision.ReasonCode != "event_filtered" || decision.Failure != nil {+ t.Fatalf("action mismatch: %+v", decision)+ }+}++func TestWebhookPayloadFilter_DiagnosticBounds(t *testing.T) {+ var values []any+ for range 11 {+ values = append(values, strings.Repeat("界", 300))+ }+ failure := newWebhookPayloadConditionFailure(WebhookPayloadCondition{Path: "items.*", Op: payloadOpEquals, Value: "x"}, map[string]any{"items": values}, 0, 0)+ if len(failure.ActualValues) != 10 || !failure.Truncated || len([]rune(failure.ActualValues[0])) != 256 {+ t.Fatalf("diagnostic was not bounded: %+v", failure)+ }+ missing := newWebhookPayloadConditionFailure(WebhookPayloadCondition{Path: "missing", Op: payloadOpExists}, nil, 0, 0)+ if !missing.Missing || len(missing.ActualValues) != 0 {+ t.Fatalf("missing diagnostic: %+v", missing)+ }+ null := newWebhookPayloadConditionFailure(WebhookPayloadCondition{Path: "value", Op: payloadOpExists}, map[string]any{"value": nil}, 0, 0)+ if null.Missing || !reflect.DeepEqual(null.ActualValues, []string{"null"}) {+ t.Fatalf("null diagnostic: %+v", null)+ }+}++func TestWebhookPayloadFilter_PersistsIngressAndWorkerDecisions(t *testing.T) {+ for _, worker := range []bool{false, true} {+ name := "ingress"+ if worker {+ name = "recovered worker"+ }+ t.Run(name, func(t *testing.T) {+ ctx := context.Background()+ agentID := createWebhookTestAgent(t, "Payload diagnostic agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "create_issue")+ filters := []WebhookEventFilter{{Event: "pull_request", Conditions: []WebhookPayloadCondition{{Path: "pull_request.base.ref", Op: payloadOpEquals, Value: "main"}}}}+ trig := createWebhookTriggerWithFilters(t, apID, filters)+ var deliveryID string+ if worker {+ row, _, err := testHandler.persistInboundDelivery(httptest.NewRequest(http.MethodPost, "/webhook", nil), persistDeliveryInput{+ WorkspaceID: parseUUID(testWorkspaceID), AutopilotID: parseUUID(apID), TriggerID: parseUUID(trig.ID),+ Provider: "github", Event: "github.pull_request.opened", SignatureStatus: sigStatusNotRequired,+ RawBody: []byte(`{"action":"opened","pull_request":{"base":{"ref":"dev"}}}`),+ SelectedHeaders: selectedHeadersJSON(http.Header{"X-Github-Event": []string{"pull_request"}}),+ })+ if err != nil {+ t.Fatal(err)+ }+ deliveryID = uuidToString(row.ID)+ row = processQueuedWebhookDelivery(t, deliveryID)+ if row.Status != deliveryStatusIgnored {+ t.Fatalf("worker status=%s", row.Status)+ }+ } else {+ w := postWebhook(t, *trig.WebhookToken, map[string]any{"action": "opened", "pull_request": map[string]any{"base": map[string]any{"ref": "dev"}}}, map[string]string{"X-GitHub-Event": "pull_request"})+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatal(err)+ }+ if w.Code != http.StatusOK || resp["reason"] != "payload_filtered" || resp["run_id"] != nil {+ t.Fatalf("unexpected webhook response: %d %v", w.Code, resp)+ }+ deliveryID = resp["delivery_id"].(string)+ }+ // Change the rule after receipt: the diagnostic must remain the old+ // decision, rather than evaluating the new filter at read time.+ if _, err := testPool.Exec(ctx, `UPDATE autopilot_trigger SET event_filters='[]' WHERE id=$1`, trig.ID); err != nil {+ t.Fatal(err)+ }+ var list struct {+ Deliveries []WebhookDeliveryResponse `json:"deliveries"`+ }+ w := httptest.NewRecorder()+ req := withURLParam(newRequest("GET", "/api/autopilots/"+apID+"/deliveries", nil), "id", apID)+ testHandler.ListAutopilotDeliveries(w, req)+ if err := json.Unmarshal(w.Body.Bytes(), &list); err != nil || w.Code != 200 || len(list.Deliveries) != 1 {+ t.Fatalf("list: %d %s", w.Code, w.Body.String())+ }+ detailRow, err := testHandler.Queries.GetWebhookDelivery(ctx, parseUUID(deliveryID))+ if err != nil {+ t.Fatal(err)+ }+ for _, resp := range []WebhookDeliveryResponse{list.Deliveries[0], deliveryToResponse(detailRow, true)} {+ if resp.ReasonCode == nil || *resp.ReasonCode != "payload_filtered" || resp.PayloadConditionFailure == nil {+ t.Fatalf("missing stored diagnostic: %+v", resp)+ }+ failure := resp.PayloadConditionFailure+ if failure.Condition.Value != "main" || !reflect.DeepEqual(failure.ActualValues, []string{`"dev"`}) {+ t.Fatalf("diagnostic changed with trigger: %+v", failure)+ }+ }+ runs, err := testHandler.Queries.ListAutopilotRuns(ctx, db.ListAutopilotRunsParams{AutopilotID: parseUUID(apID), Limit: 10})+ if err != nil || len(runs) != 0 {+ t.Fatalf("filtered delivery created runs: %v %v", runs, err)+ }+ })+ }+}