Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-9193: feat(autopilots): edit webhook filter rules and conditions in place (#10800)

Multica Eveb490006d26ad
diff --git a/apps/docs/content/docs/autopilots.fr.mdx b/apps/docs/content/docs/autopilots.fr.mdx
index 108ad57fd9..1c8fa12e91 100644
--- a/apps/docs/content/docs/autopilots.fr.mdx
+++ b/apps/docs/content/docs/autopilots.fr.mdx
@@ -87,11 +87,11 @@ Contraintes applicables aux requêtes webhook :
### Filtres d'événements
-Lorsqu'une même source envoie plusieurs types d'événements, ajoutez des filtres d'événements au déclencheur. Chaque ligne contient un nom d'événement et une liste facultative d'actions ; une exécution est déclenchée si une ligne correspond, et laisser toutes les lignes vides accepte tous les événements. Pour modifier les filtres d'un webhook, cliquez sur **Modifier le webhook** sur sa ligne dans **Déclencheurs**.
+Lorsqu'une même source envoie plusieurs types d'événements, ajoutez des filtres d'événements au déclencheur. Cliquez sur **Ajouter une règle** et saisissez un nom d'événement et une liste facultative d'actions ; une exécution est déclenchée si une règle correspond, et un déclencheur sans règle accepte tous les événements. Pour modifier les filtres d'un webhook, cliquez sur **Modifier le webhook** sur sa ligne dans **Déclencheurs**.
Par 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 :
+Chaque règle peut aussi porter des `conditions` sur les champs de la charge utile : cliquez sur **Ajouter une condition** dans la règle, ou définissez-les via l'API. Toutes les conditions doivent être vraies pour que la règle 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 règle 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
{
diff --git a/apps/docs/content/docs/autopilots.ja.mdx b/apps/docs/content/docs/autopilots.ja.mdx
index 606b9c8955..608886603f 100644
--- a/apps/docs/content/docs/autopilots.ja.mdx
+++ b/apps/docs/content/docs/autopilots.ja.mdx
@@ -87,11 +87,11 @@ Webhook リクエストには次の制約があります。
### イベントをフィルターする [#event-filters]
-同じ送信元から複数種類のイベントが届く場合、トリガーにイベントフィルターを追加できます。各行にイベント名と、任意で action の一覧を指定します。いずれか 1 行に一致すると実行され、すべて空の場合は全イベントを受け入れます。Webhook のフィルターを編集するには、「トリガー」の該当行にある **Webhook を編集** をクリックします。
+同じ送信元から複数種類のイベントが届く場合、トリガーにイベントフィルターを追加できます。**ルールを追加** をクリックし、イベント名と、任意で action の一覧を指定します。いずれか 1 つのルールに一致すると実行され、ルールがない場合は全イベントを受け入れます。Webhook のフィルターを編集するには、「トリガー」の該当行にある **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 だけを受け取ります。
+各ルールには 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
{
diff --git a/apps/docs/content/docs/autopilots.ko.mdx b/apps/docs/content/docs/autopilots.ko.mdx
index 0d9c85d3b0..521bdf94fe 100644
--- a/apps/docs/content/docs/autopilots.ko.mdx
+++ b/apps/docs/content/docs/autopilots.ko.mdx
@@ -87,11 +87,11 @@ Webhook 요청에는 다음 제약이 있습니다.
### 이벤트 필터링 [#event-filters]
-같은 소스에서 여러 종류의 이벤트를 보낸다면 트리거에 이벤트 필터를 추가할 수 있습니다. 각 줄에는 이벤트 이름과 선택적인 action 목록을 입력합니다. 어느 한 줄이라도 일치하면 실행되며 모두 비워 두면 모든 이벤트를 받습니다. Webhook의 필터를 수정하려면 '트리거'에서 해당 줄의 **Webhook 수정**을 클릭하세요.
+같은 소스에서 여러 종류의 이벤트를 보낸다면 트리거에 이벤트 필터를 추가할 수 있습니다. **규칙 추가**를 클릭하고 이벤트 이름과 선택적인 action 목록을 입력합니다. 어느 한 규칙이라도 일치하면 실행되며 규칙이 없으면 모든 이벤트를 받습니다. Webhook의 필터를 수정하려면 '트리거'에서 해당 줄의 **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만 받습니다.
+각 규칙에는 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
{
diff --git a/apps/docs/content/docs/autopilots.mdx b/apps/docs/content/docs/autopilots.mdx
index ab9b10f51f..18def415e6 100644
--- a/apps/docs/content/docs/autopilots.mdx
+++ b/apps/docs/content/docs/autopilots.mdx
@@ -87,11 +87,11 @@ Constraints on webhook requests:
### Filter events [#event-filters]
-When one source sends several event types, add event filters to the trigger. Each row holds one event name plus an optional list of actions; a run fires if any row matches, and leaving all rows empty accepts every event. To edit a webhook's filters, click **Edit webhook** on its row under **Triggers**.
+When one source sends several event types, add event filters to the trigger. Click **Add rule** and enter one event name plus an optional list of actions; a run fires if any rule matches, and a trigger with no rules accepts every event. To edit a webhook's filters, click **Edit webhook** on its row under **Triggers**.
For 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:
+Each rule can also carry `conditions` on payload fields: click **Add condition** on the rule, or set them through the API. Every condition must hold for the rule 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 rule only accepts ready pull requests labelled `needs-review` that target `main` or `release` and weren't opened by a bot:
```json
{
diff --git a/apps/docs/content/docs/autopilots.zh-Hant.mdx b/apps/docs/content/docs/autopilots.zh-Hant.mdx
index 3064d51038..97c7fd75a1 100644
--- a/apps/docs/content/docs/autopilots.zh-Hant.mdx
+++ b/apps/docs/content/docs/autopilots.zh-Hant.mdx
@@ -87,11 +87,11 @@ Webhook 請求的約束:
### 過濾事件 [#事件過濾]
-同一個來源會傳送多種事件時,給觸發器加上事件過濾。每行一個事件名,加可選的 action 列表;任意一行命中就執行,全部留空則接收所有事件。要編輯某個 Webhook 的過濾,點「觸發器」中該行的 **編輯 Webhook**。
+同一個來源會傳送多種事件時,給觸發器加上事件過濾。點 **新增規則**,填一個事件名,加可選的 action 列表;任意一條規則命中就執行,沒有規則則接收所有事件。要編輯某個 Webhook 的過濾,點「觸發器」中該行的 **編輯 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` 不同。
+每條規則還可以設定針對本文欄位的 `conditions`:點選該規則的 **新增條件**,或透過 API 設定。同一條規則的全部條件都要符合,多條規則之間符合任意一條即可。`path` 用點號存取事件本文,數字表示陣列索引,`*` 表示任意元素(例如 `pull_request.labels.*.name`)。操作支援 `equals`、`not_equals`、`contains`、`in` 和 `exists`,`ignore_case` 忽略文字大小寫。使用 `*` 時,前四種操作中除 `not_equals` 外,只要有一個元素符合即可;`not_equals` 要求沒有元素等於指定值。`exists` 忽略 `null`。字串與布林值必須使用正確類型,例如 `"false"` 與 `false` 不同。
```json
{
diff --git a/apps/docs/content/docs/autopilots.zh.mdx b/apps/docs/content/docs/autopilots.zh.mdx
index 3b9ef97f7e..59e3374a7f 100644
--- a/apps/docs/content/docs/autopilots.zh.mdx
+++ b/apps/docs/content/docs/autopilots.zh.mdx
@@ -87,11 +87,11 @@ Webhook 请求的约束:
### 过滤事件 [#事件过滤]
-同一个来源会发送多种事件时,给触发器加上事件过滤。每行一个事件名,加可选的 action 列表;任意一行命中就运行,全部留空则接收所有事件。要编辑某个 Webhook 的过滤,点「触发器」中该行的 **编辑 Webhook**。
+同一个来源会发送多种事件时,给触发器加上事件过滤。点 **添加规则**,填一个事件名,加可选的 action 列表;任意一条规则命中就运行,没有规则则接收所有事件。要编辑某个 Webhook 的过滤,点「触发器」中该行的 **编辑 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:
+每条规则还可以设置针对 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
{
diff --git a/packages/views/autopilots/components/autopilot-dialog.schedule.test.tsx b/packages/views/autopilots/components/autopilot-dialog.schedule.test.tsx
index f4c8756dcb..785b29270b 100644
--- a/packages/views/autopilots/components/autopilot-dialog.schedule.test.tsx
+++ b/packages/views/autopilots/components/autopilot-dialog.schedule.test.tsx
@@ -1,6 +1,6 @@
import { useImperativeHandle, useRef, useState } from "react";
import { describe, it, expect, vi, beforeEach } from "vitest";
-import { screen, waitFor } from "@testing-library/react";
+import { screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { AutopilotTrigger } from "@multica/core/types";
@@ -326,10 +326,9 @@ describe("AutopilotDialog schedule section on an autopilot with several triggers
});
});
-// The webhook panel renders for an autopilot whose first trigger is a webhook.
-// It holds one filter list, so with two webhooks it used to show and save the
-// first as if it were the only one. It now hands those to the trigger rows,
-// each of which edits its own webhook.
+// Event filters are edited in one place, the per-webhook dialog. The webhook
+// panel (rendered when the first trigger is a webhook) reads them back and
+// opens that dialog; the autopilot's own Save never writes them.
describe("AutopilotDialog webhook section", () => {
beforeEach(() => {
mockUpdateAutopilot.mockReset().mockResolvedValue({ id: AUTOPILOT_ID });
@@ -348,12 +347,18 @@ describe("AutopilotDialog webhook section", () => {
...overrides,
});
- it("edits the filters of the autopilot's only webhook", async () => {
+ it("reads the filters back and edits them in the webhook's own dialog", async () => {
const user = userEvent.setup();
renderEditDialog([webhook(), trigger({ id: "trg-sched" })]);
- await user.click(screen.getByRole("button", { name: "Remove filter" }));
- await user.click(saveButton());
+ expect(screen.getByTitle("pull_request")).toBeInTheDocument();
+ expect(screen.queryByRole("textbox", { name: "Event" })).not.toBeInTheDocument();
+ expect(screen.getByText("Saved on their own: Cancel here won't undo them.")).toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: "Edit filters" }));
+ const filters = await screen.findByRole("dialog", { name: "Edit webhook" });
+ await user.click(within(filters).getByRole("button", { name: "Remove rule" }));
+ await user.click(within(filters).getByRole("button", { name: "Save" }));
await waitFor(() => expect(mockUpdateTrigger).toHaveBeenCalledTimes(1));
expect(mockUpdateTrigger.mock.calls[0]?.[0]).toEqual({
@@ -363,6 +368,16 @@ describe("AutopilotDialog webhook section", () => {
});
});
+ it("leaves the filters alone when the autopilot itself is saved", async () => {
+ const user = userEvent.setup();
+ renderEditDialog([webhook()]);
+
+ await user.click(saveButton());
+
+ await waitFor(() => expect(mockUpdateAutopilot).toHaveBeenCalledTimes(1));
+ expect(mockUpdateTrigger).not.toHaveBeenCalled();
+ });
+
it("sends the reader to the trigger rows instead of editing the first of several webhooks", async () => {
const user = userEvent.setup();
renderEditDialog([webhook(), webhook({ id: "trg-hook-2", webhook_token: "tok-2" })]);
@@ -372,7 +387,7 @@ describe("AutopilotDialog webhook section", () => {
"This autopilot has more than one webhook. Close this dialog and edit each one under Triggers below.",
),
).toBeInTheDocument();
- expect(screen.queryByRole("button", { name: "Remove filter" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Edit filters" })).not.toBeInTheDocument();
await user.click(saveButton());
diff --git a/packages/views/autopilots/components/autopilot-dialog.tsx b/packages/views/autopilots/components/autopilot-dialog.tsx
index 3b5b001ea7..ba500ab41c 100644
--- a/packages/views/autopilots/components/autopilot-dialog.tsx
+++ b/packages/views/autopilots/components/autopilot-dialog.tsx
@@ -12,6 +12,7 @@ import {
FolderKanban,
Maximize2,
Minimize2,
+ Pencil,
Play,
Plus,
Rocket,
@@ -67,12 +68,11 @@ import { getDefaultScheduleConfig, type ScheduleConfig } from "./schedule-editor
import { browserTimezone } from "../../common/timezone-select";
import { parseCron, toCron } from "./schedule-editor/cron-mapping";
import { useScheduleSubmitGate } from "./schedule-editor/validate";
-import { WebhookEventFilterSection } from "./webhook-event-filter-section";
+import { WebhookEventFilterSummary } from "./webhook-event-filter-section";
+import { EditWebhookTriggerDialog } from "./edit-webhook-trigger-dialog";
import { WebhookUrlField } from "./webhook-url-field";
-import { serializeEventFilters } from "./webhook-payload-condition";
import { useT } from "../../i18n";
import { formatSchedulePartialFailureToast } from "./autopilot-dialog-toast";
-import type { WebhookEventFilter } from "@multica/core/types";
// Types
@@ -188,34 +188,25 @@ export function AutopilotDialog(props: AutopilotDialogProps) {
})();
const [triggerKind, setTriggerKind] = useState<"schedule" | "webhook">(initialKind);
- // The webhook panel only renders when the first trigger is a webhook, so this
- // is that row. Its filters are editable here only while it is the sole
- // webhook: this panel holds one filter list, and with two webhooks it would
- // show the first as if it were the whole story and save into that one alone.
- // Every webhook row on the detail page carries its own editor regardless.
+ // Event filters are edited in one place, the per-webhook dialog. The webhook
+ // panel (rendered when the first trigger is a webhook) reads them back and
+ // opens that dialog for the autopilot's only webhook; with two or more it
+ // points at their rows. Read live, so a save there shows here at once.
const existingWebhook = isCreate
? null
: props.triggers.find((trig) => trig.kind === "webhook") ?? null;
const webhookTriggerCount = isCreate
? 0
: props.triggers.filter((trig) => trig.kind === "webhook").length;
- const webhookFiltersLocked = webhookTriggerCount >= 2;
-
- const initialEventFilters: WebhookEventFilter[] = existingWebhook?.event_filters ?? [];
- const [eventFilters, setEventFilters] = useState<WebhookEventFilter[]>(initialEventFilters);
const initialCronRef = useRef(toCron(initialCfg));
const initialTimezoneRef = useRef(initialCfg.timezone);
- const initialEventFiltersRef = useRef(serializeEventFilters(initialEventFilters));
const scheduleDirty =
toCron(schedule) !== initialCronRef.current ||
schedule.timezone !== initialTimezoneRef.current;
- const eventFiltersDirty =
- serializeEventFilters(eventFilters) !== initialEventFiltersRef.current;
- const webhookTriggerIdRef = useRef(existingWebhook?.id ?? null);
- // The row the schedule write targets, snapshotted at mount like the one
- // above. Null means there is none to patch, so the write creates one.
+ // The row the schedule write targets, snapshotted at mount. Null means there
+ // is none to patch, so the write creates one.
const scheduleTriggerIdRef = useRef(existingSchedule?.id ?? null);
// Only SCHEDULE rows can make this panel ambiguous, so only they are counted.
@@ -331,7 +322,6 @@ export function AutopilotDialog(props: AutopilotDialogProps) {
webhookTrigger = await createTrigger.mutateAsync({
autopilotId: autopilot.id,
kind: "webhook",
- event_filters: eventFilters.length > 0 ? eventFilters : undefined,
});
} else {
await createTrigger.mutateAsync({
@@ -405,29 +395,6 @@ export function AutopilotDialog(props: AutopilotDialogProps) {
err instanceof Error && err.message ? err.message : null;
}
}
- // Webhook autopilots have no schedule, but the user can still edit
- // event_filters from the same dialog. PATCH only when the snapshot
- // taken on open differs from the live state. Sending an explicit
- // empty array clears filters server-side (tri-state semantics — see
- // UpdateAutopilotTriggerRequest in autopilot.go).
- if (
- triggerKind === "webhook" &&
- !webhookFiltersLocked &&
- eventFiltersDirty &&
- webhookTriggerIdRef.current
- ) {
- try {
- await updateTrigger.mutateAsync({
- autopilotId: props.autopilotId,
- triggerId: webhookTriggerIdRef.current,
- event_filters: eventFilters,
- });
- } catch (err) {
- triggerOk = false;
- triggerErrMessage =
- err instanceof Error && err.message ? err.message : null;
- }
- }
onOpenChange(false);
if (triggerOk) {
toast.success(t(($) => $.dialog.toast_updated));
@@ -676,10 +643,9 @@ export function AutopilotDialog(props: AutopilotDialogProps) {
</div>
) : (
<WebhookSection
- isCreate={isCreate}
- filtersLocked={webhookFiltersLocked}
- eventFilters={eventFilters}
- onEventFiltersChange={setEventFilters}
+ autopilotId={isCreate ? null : props.autopilotId}
+ webhook={existingWebhook}
+ webhookCount={webhookTriggerCount}
/>
)}
</aside>
@@ -1037,17 +1003,19 @@ function TriggerKindSection({
}
function WebhookSection({
- isCreate,
- filtersLocked,
- eventFilters,
- onEventFiltersChange,
+ autopilotId,
+ webhook,
+ webhookCount,
}: {
- isCreate: boolean;
- filtersLocked: boolean;
- eventFilters: WebhookEventFilter[];
- onEventFiltersChange: (filters: WebhookEventFilter[]) => void;
+ // Null while creating: there is no webhook to filter until the autopilot
+ // exists, and its row on the detail page then offers the editor.
+ autopilotId: string | null;
+ webhook: AutopilotTrigger | null;
+ webhookCount: number;
}) {
const { t } = useT("autopilots");
+ const [filtersOpen, setFiltersOpen] = useState(false);
+ const isCreate = autopilotId === null;
return (
<div className="space-y-3">
<div>
@@ -1058,18 +1026,39 @@ function WebhookSection({
: t(($) => $.dialog.webhook_help_edit)}
</p>
</div>
- {filtersLocked ? (
+ {webhookCount >= 2 ? (
<div className="rounded-md border border-dashed p-3">
<p className="text-caption text-muted-foreground">
{t(($) => $.dialog.webhook_multiple_notice)}
</p>
</div>
- ) : (
- <WebhookEventFilterSection
- filters={eventFilters}
- onChange={onEventFiltersChange}
- />
- )}
+ ) : autopilotId && webhook ? (
+ <div className="space-y-1.5">
+ <SectionLabel>{t(($) => $.dialog.event_filter_label)}</SectionLabel>
+ <WebhookEventFilterSummary filters={webhook.event_filters ?? []} />
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ className="text-muted-foreground"
+ onClick={() => setFiltersOpen(true)}
+ >
+ <Pencil />
+ {t(($) => $.dialog.webhook_edit_filters)}
+ </Button>
+ {/* The editor writes on its own Save, so this dialog's Cancel has
+ nothing of it to undo; say so before someone relies on it. */}
+ <p className="text-micro text-muted-foreground">
+ {t(($) => $.dialog.webhook_filters_saved_separately)}
+ </p>
+ <EditWebhookTriggerDialog
+ open={filtersOpen}
+ onOpenChange={setFiltersOpen}
+ autopilotId={autopilotId}
+ trigger={webhook}
+ />
+ </div>
+ ) : null}
</div>
);
}
diff --git a/packages/views/autopilots/components/edit-webhook-trigger-dialog.test.tsx b/packages/views/autopilots/components/edit-webhook-trigger-dialog.test.tsx
index 9e32082114..317916c27a 100644
--- a/packages/views/autopilots/components/edit-webhook-trigger-dialog.test.tsx
+++ b/packages/views/autopilots/components/edit-webhook-trigger-dialog.test.tsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
-import { screen, waitFor } from "@testing-library/react";
+import { screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { AutopilotTrigger } from "@multica/core/types";
@@ -72,8 +72,9 @@ describe("EditWebhookTriggerDialog", () => {
const user = userEvent.setup();
const { onOpenChange } = renderDialog();
- await user.type(screen.getByPlaceholderText("e.g. workflow_run"), "issues");
- await user.click(screen.getByRole("button", { name: "Add" }));
+ await user.click(screen.getByRole("button", { name: "Add rule" }));
+ // The new rule's event input takes focus, so typing goes straight into it.
+ await user.keyboard("issues");
await user.click(saveButton());
await waitFor(() => expect(mockUpdateTrigger).toHaveBeenCalledTimes(1));
@@ -89,7 +90,7 @@ describe("EditWebhookTriggerDialog", () => {
const user = userEvent.setup();
renderDialog();
- await user.click(screen.getByRole("button", { name: "Remove filter" }));
+ await user.click(screen.getByRole("button", { name: "Remove rule" }));
await user.click(saveButton());
await waitFor(() => expect(mockUpdateTrigger).toHaveBeenCalledTimes(1));
@@ -98,6 +99,75 @@ describe("EditWebhookTriggerDialog", () => {
expect(mockUpdateTrigger.mock.calls[0]?.[0].event_filters).toEqual([]);
});
+ it("edits a saved rule in place", async () => {
+ const user = userEvent.setup();
+ renderDialog();
+
+ const actions = within(screen.getByRole("group", { name: "pull_request" })).getByRole("textbox", {
+ name: "Actions",
+ });
+ await user.clear(actions);
+ await user.type(actions, "opened, reopened");
+ await user.click(saveButton());
+
+ await waitFor(() => expect(mockUpdateTrigger).toHaveBeenCalledTimes(1));
+ expect(mockUpdateTrigger.mock.calls[0]?.[0].event_filters).toEqual([
+ { event: "pull_request", actions: ["opened", "reopened"] },
+ ]);
+ });
+
+ // Regression cover for text left in a rule form being dropped on Save: an
+ // incomplete rule now stops the save and says where, and nothing is sent.
+ it("stops a save on an incomplete rule and points at it", async () => {
+ const user = userEvent.setup();
+ const { onOpenChange } = renderDialog();
+
+ await user.click(screen.getByRole("button", { name: "Add rule" }));
+ await user.click(saveButton());
+
+ const [, newEvent] = screen.getAllByRole("textbox", { name: "Event" });
+ expect(newEvent).toHaveAttribute("aria-invalid", "true");
+ expect(newEvent).toHaveFocus();
+ expect(screen.getByText("Enter an event name.")).toBeInTheDocument();
+ expect(mockUpdateTrigger).not.toHaveBeenCalled();
+ expect(onOpenChange).not.toHaveBeenCalled();
+
+ await user.type(newEvent!, "issues");
+ expect(screen.queryByText("Enter an event name.")).not.toBeInTheDocument();
+ await user.click(saveButton());
+ await waitFor(() => expect(mockUpdateTrigger).toHaveBeenCalledTimes(1));
+ });
+
+ // Regression cover: a list value holding a comma came back from the inputs
+ // split in two, so an unrelated save rewrote the rule without saying so.
+ it("leaves saved filters alone when only the switch moved", async () => {
+ const user = userEvent.setup();
+ renderDialog(
+ trigger({
+ event_filters: [
+ {
+ event: "pull_request",
+ conditions: [
+ { path: "pull_request.title", op: "in", values: ["fix, docs", "chore"] },
+ { path: "pull_request.body", op: "equals", value: "" },
+ ],
+ },
+ ],
+ }),
+ );
+
+ expect(saveButton()).toBeDisabled();
+ await user.click(enabledSwitch());
+ await user.click(saveButton());
+
+ await waitFor(() => expect(mockUpdateTrigger).toHaveBeenCalledTimes(1));
+ expect(mockUpdateTrigger.mock.calls[0]?.[0]).toEqual({
+ autopilotId: AUTOPILOT_ID,
+ triggerId: "trg-hook",
+ enabled: false,
+ });
+ });
+
it("sends the label alone when only the label was touched", async () => {
const user = userEvent.setup();
renderDialog(trigger({ label: "Old name" }));
diff --git a/packages/views/autopilots/components/edit-webhook-trigger-dialog.tsx b/packages/views/autopilots/components/edit-webhook-trigger-dialog.tsx
index c533685328..b07fdfc74a 100644
--- a/packages/views/autopilots/components/edit-webhook-trigger-dialog.tsx
+++ b/packages/views/autopilots/components/edit-webhook-trigger-dialog.tsx
@@ -6,9 +6,14 @@ import { Button } from "@multica/ui/components/ui/button";
import { Switch } from "@multica/ui/components/ui/switch";
import { Dialog, DialogContent, DialogTitle } from "@multica/ui/components/ui/dialog";
import { toast } from "sonner";
-import type { AutopilotTrigger, WebhookEventFilter } from "@multica/core/types";
+import type { AutopilotTrigger } from "@multica/core/types";
import { WebhookEventFilterSection } from "./webhook-event-filter-section";
import { serializeEventFilters } from "./webhook-payload-condition";
+import {
+ draftsFromEventFilters,
+ resolveEventFilterDrafts,
+ type EventFilterDraft,
+} from "./webhook-event-filter-draft";
import { useT } from "../../i18n";
// The webhook counterpart of EditScheduleTriggerDialog: every webhook row opens
@@ -49,7 +54,10 @@ function EditWebhookTriggerDialogBody({
}) {
const { t } = useT("autopilots");
const updateTrigger = useUpdateAutopilotTrigger();
- const [filters, setFilters] = useState<WebhookEventFilter[]>(trigger.event_filters ?? []);
+ const [drafts, setDrafts] = useState<EventFilterDraft[]>(() =>
+ draftsFromEventFilters(trigger.event_filters ?? []),
+ );
+ const [showErrors, setShowErrors] = useState(false);
const [label, setLabel] = useState(trigger.label ?? "");
const [enabled, setEnabled] = useState(trigger.enabled);
const [submitting, setSubmitting] = useState(false);
@@ -62,13 +70,21 @@ function EditWebhookTriggerDialogBody({
label: (trigger.label ?? "").trim(),
enabled: trigger.enabled,
});
- const filtersDirty = serializeEventFilters(filters) !== baseline.current.filters;
+ const resolved = resolveEventFilterDrafts(drafts);
+ // An incomplete row counts as a change: Save stays available so pressing it
+ // can point at the row, rather than going quiet over an edit it won't send.
+ const filtersDirty =
+ !resolved.valid || serializeEventFilters(resolved.filters) !== baseline.current.filters;
const labelDirty = label.trim() !== baseline.current.label;
const enabledDirty = enabled !== baseline.current.enabled;
const canSubmit = !submitting && (filtersDirty || labelDirty || enabledDirty);
const handleSubmit = async () => {
if (!canSubmit) return;
+ if (!resolved.valid) {
+ setShowErrors(true);
+ return;
+ }
setSubmitting(true);
try {
// Only the fields that moved. A changed filter list or enabled flag is a
@@ -78,7 +94,7 @@ function EditWebhookTriggerDialogBody({
await updateTrigger.mutateAsync({
autopilotId,
triggerId: trigger.id,
- ...(filtersDirty ? { event_filters: filters } : {}),
+ ...(filtersDirty ? { event_filters: resolved.filters } : {}),
...(labelDirty ? { label: label.trim() } : {}),
...(enabledDirty ? { enabled } : {}),
});
@@ -97,12 +113,12 @@ function EditWebhookTriggerDialogBody({
return (
<Dialog open onOpenChange={onOpenChange}>
- {/* Wider than the schedule dialog: a rule row, its conditions and the
- add-rule inputs share one line each and need the room. */}
- <DialogContent className="sm:max-w-md">
+ {/* Wider than the schedule dialog: rules and conditions are edited in
+ place, and a condition's operator, value and ignore-case share a line. */}
+ <DialogContent className="sm:max-w-lg">
<DialogTitle>{t(($) => $.edit_webhook_dialog.title)}</DialogTitle>
<div className="min-w-0 space-y-4 pt-2">
- <WebhookEventFilterSection filters={filters} onChange={setFilters} />
+ <WebhookEventFilterSection drafts={drafts} onChange={setDrafts} showErrors={showErrors} />
<div>
<label className="text-caption font-medium text-muted-foreground">
diff --git a/packages/views/autopilots/components/trigger-row.test.tsx b/packages/views/autopilots/components/trigger-row.test.tsx
index 0b10dbf09c..597e1165b5 100644
--- a/packages/views/autopilots/components/trigger-row.test.tsx
+++ b/packages/views/autopilots/components/trigger-row.test.tsx
@@ -155,7 +155,7 @@ describe("TriggerRow on a webhook", () => {
const dialog = await screen.findByRole("dialog");
expect(within(dialog).getByText("Edit webhook", { selector: "h2" })).toBeInTheDocument();
- expect(within(dialog).getByText("pull_request")).toBeInTheDocument();
+ expect(within(dialog).getByRole("textbox", { name: "Event" })).toHaveValue("pull_request");
});
it("says a webhook without filters accepts every event", () => {
diff --git a/packages/views/autopilots/components/webhook-event-filter-draft.test.ts b/packages/views/autopilots/components/webhook-event-filter-draft.test.ts
new file mode 100644
index 0000000000..66b4c4379a
--- /dev/null
+++ b/packages/views/autopilots/components/webhook-event-filter-draft.test.ts
@@ -0,0 +1,90 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { WebhookEventFilter } from "@multica/core/types";
+import {
+ conditionValueToText,
+ draftsFromEventFilters,
+ newConditionDraft,
+ newRuleDraft,
+ resolveEventFilterDrafts,
+} from "./webhook-event-filter-draft";
+
+describe("conditionValueToText", () => {
+ it.each([
+ ["main", "main"],
+ [false, "false"],
+ [42, "42"],
+ ["false", '"false"'],
+ ["", '""'],
+ ["42", '"42"'],
+ ['"quoted"', '"\\"quoted\\""'],
+ ] as const)("writes %j as %s", (value, text) => {
+ expect(conditionValueToText(value)).toBe(text);
+ });
+});
+
+describe("draftsFromEventFilters → resolveEventFilterDrafts", () => {
+ it("round-trips every saved shape unchanged", () => {
+ const filters: WebhookEventFilter[] = [
+ {
+ event: "pull_request",
+ actions: ["opened", "synchronize"],
+ conditions: [
+ { path: "pull_request.draft", op: "equals", value: false },
+ { path: "pull_request.number", op: "not_equals", value: 7 },
+ { path: "pull_request.title", op: "contains", value: "false", ignore_case: true },
+ { path: "pull_request.base.ref", op: "in", values: ["main", "release", 3] },
+ // Commas and empty strings inside a list, and an empty string on
+ // its own, are values the API accepts that bare text can't carry.
+ { path: "pull_request.title", op: "in", values: ["fix, docs", "chore", "", '"quoted"'] },
+ { path: "pull_request.body", op: "equals", value: "" },
+ { path: "pull_request.head.ref", op: "not_equals", value: " padded " },
+ { path: "pull_request.labels.*.name", op: "exists" },
+ ],
+ },
+ { event: "issues" },
+ ];
+
+ const resolved = resolveEventFilterDrafts(draftsFromEventFilters(filters));
+
+ expect(resolved.valid).toBe(true);
+ expect(resolved.filters).toEqual(filters);
+ });
+});
+
+describe("resolveEventFilterDrafts", () => {
+ it("reports a rule without an event instead of dropping it", () => {
+ const rule = newRuleDraft();
+ const resolved = resolveEventFilterDrafts([rule]);
+
+ expect(resolved.valid).toBe(false);
+ expect(resolved.errors.events).toEqual({ [rule.key]: "event_required" });
+ });
+
+ it("reports each incomplete condition field", () => {
+ const empty = newConditionDraft();
+ const badPath = { ...newConditionDraft(), path: "a..b", value: "x" };
+ const tooMany = {
+ ...newConditionDraft(),
+ path: "a",
+ op: "in" as const,
+ value: Array.from({ length: 101 }, (_, i) => `v${i}`).join(", "),
+ };
+ const exists = { ...newConditionDraft(), path: "a", op: "exists" as const };
+ const rule = { ...newRuleDraft(), event: "issues", conditions: [empty, badPath, tooMany, exists] };
+
+ const { errors, valid } = resolveEventFilterDrafts([rule]);
+
+ expect(valid).toBe(false);
+ expect(errors.paths).toEqual({ [empty.key]: "path_required", [badPath.key]: "path_invalid" });
+ expect(errors.values).toEqual({ [empty.key]: "value_required", [tooMany.key]: "values_too_many" });
+ });
+
+ it("resolves no rules to an empty list, which accepts every event", () => {
+ expect(resolveEventFilterDrafts([])).toEqual({
+ filters: [],
+ errors: { events: {}, paths: {}, values: {} },
+ valid: true,
+ });
+ });
+});
diff --git a/packages/views/autopilots/components/webhook-event-filter-draft.ts b/packages/views/autopilots/components/webhook-event-filter-draft.ts
new file mode 100644
index 0000000000..45fb89fb71
--- /dev/null
+++ b/packages/views/autopilots/components/webhook-event-filter-draft.ts
@@ -0,0 +1,155 @@
+import type {
+ WebhookEventFilter,
+ WebhookPayloadCondition,
+ WebhookPayloadConditionValue,
+} from "@multica/core/types";
+import {
+ MAX_CONDITION_PATH_LENGTH,
+ MAX_CONDITION_VALUES,
+ buildCondition,
+ parseConditionValue,
+ splitConditionValues,
+ type ConditionOp,
+} from "./webhook-payload-condition";
+
+// The editor edits rules and conditions in place, so what it holds is text as
+// typed, including rows that are not valid yet. Nothing is dropped on the way
+// to a save: an incomplete row blocks it instead (resolveEventFilterDrafts).
+
+export interface ConditionRowDraft {
+ key: string;
+ path: string;
+ op: ConditionOp;
+ value: string;
+ ignoreCase: boolean;
+}
+
+export interface EventFilterDraft {
+ key: string;
+ event: string;
+ actions: string;
+ conditions: ConditionRowDraft[];
+}
+
+export type ConditionFieldError =
+ | "path_required"
+ | "path_invalid"
+ | "value_required"
+ | "values_too_many";
+
+export interface EventFilterDraftErrors {
+ // Keyed by rule draft key.
+ events: Record<string, "event_required">;
+ // Keyed by condition draft key; one error per field.
+ paths: Record<string, ConditionFieldError>;
+ values: Record<string, ConditionFieldError>;
+}
+
+let nextDraftKey = 0;
+const draftKey = (prefix: string) => `${prefix}${++nextDraftKey}`;
+
+export function newRuleDraft(): EventFilterDraft {
+ return { key: draftKey("r"), event: "", actions: "", conditions: [] };
+}
+
+export function newConditionDraft(): ConditionRowDraft {
+ return { key: draftKey("c"), path: "", op: "equals", value: "", ignoreCase: false };
+}
+
+// conditionValueToText writes a stored value back the way it would have to be
+// typed to come out the same. Strings stay bare unless bare text would read
+// differently: as another type ("false", "42"), trimmed (" x "), as nothing
+// (""), or, inside an "is one of" list, as two values ("fix, docs"). Those
+// keep their quotes. Anything else would come back changed, and a save that
+// only renamed the webhook would quietly rewrite its rule.
+export function conditionValueToText(value: WebhookPayloadConditionValue, inList = false): string {
+ if (typeof value !== "string") return String(value);
+ const bareReadsBack =
+ value.trim() !== "" && parseConditionValue(value) === value && !(inList && value.includes(","));
+ return bareReadsBack ? value : JSON.stringify(value);
+}
+
+function conditionToDraft(c: WebhookPayloadCondition): ConditionRowDraft {
+ const value =
+ c.op === "exists"
+ ? ""
+ : c.op === "in"
+ ? (c.values ?? []).map((v) => conditionValueToText(v, true)).join(", ")
+ : c.value === undefined
+ ? ""
+ : conditionValueToText(c.value);
+ return {
+ key: draftKey("c"),
+ path: c.path,
+ op: c.op,
+ value,
+ ignoreCase: c.ignore_case === true,
+ };
+}
+
+export function draftsFromEventFilters(filters: WebhookEventFilter[]): EventFilterDraft[] {
+ return filters.map((f) => ({
+ key: draftKey("r"),
+ event: f.event,
+ actions: (f.actions ?? []).join(", "),
+ conditions: (f.conditions ?? []).map(conditionToDraft),
+ }));
+}
+
+function conditionErrors(
+ row: ConditionRowDraft,
+): { path?: ConditionFieldError; value?: ConditionFieldError } {
+ const errors: { path?: ConditionFieldError; value?: ConditionFieldError } = {};
+ const path = row.path.trim();
+ if (!path) errors.path = "path_required";
+ else if (
+ path.split(".").some((seg) => seg === "") ||
+ Array.from(path).length > MAX_CONDITION_PATH_LENGTH
+ ) {
+ errors.path = "path_invalid";
+ }
+ if (row.op !== "exists") {
+ const values = splitConditionValues(row.value);
+ if (row.op === "in" ? values.length === 0 : !row.value.trim()) errors.value = "value_required";
+ else if (row.op === "in" && values.length > MAX_CONDITION_VALUES) errors.value = "values_too_many";
+ }
+ return errors;
+}
+
+export interface ResolvedEventFilters {
+ filters: WebhookEventFilter[];
+ errors: EventFilterDraftErrors;
+ valid: boolean;
+}
+
+// resolveEventFilterDrafts turns the editor's text into the filters a save
+// sends, and reports every field that keeps it from being one.
+export function resolveEventFilterDrafts(drafts: EventFilterDraft[]): ResolvedEventFilters {
+ const errors: EventFilterDraftErrors = { events: {}, paths: {}, values: {} };
+ const filters: WebhookEventFilter[] = [];
+ for (const draft of drafts) {
+ const event = draft.event.trim();
+ if (!event) errors.events[draft.key] = "event_required";
+ const actions = draft.actions
+ .split(",")
+ .map((a) => a.trim())
+ .filter((a) => a.length > 0);
+ const conditions: WebhookPayloadCondition[] = [];
+ for (const row of draft.conditions) {
+ const rowErrors = conditionErrors(row);
+ if (rowErrors.path) errors.paths[row.key] = rowErrors.path;
+ if (rowErrors.value) errors.values[row.key] = rowErrors.value;
+ const condition = buildCondition(row);
+ if (condition) conditions.push(condition);
+ }
+ const filter: WebhookEventFilter = { event };
+ if (actions.length > 0) filter.actions = actions;
+ if (conditions.length > 0) filter.conditions = conditions;
+ filters.push(filter);
+ }
+ const valid =
+ Object.keys(errors.events).length === 0 &&
+ Object.keys(errors.paths).length === 0 &&
+ Object.keys(errors.values).length === 0;
+ return { filters, errors, valid };
+}
diff --git a/packages/views/autopilots/components/webhook-event-filter-section.test.tsx b/packages/views/autopilots/components/webhook-event-filter-section.test.tsx
index ed1c9e840a..b8dc9645f3 100644
--- a/packages/views/autopilots/components/webhook-event-filter-section.test.tsx
+++ b/packages/views/autopilots/components/webhook-event-filter-section.test.tsx
@@ -1,13 +1,48 @@
+import { useState } from "react";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { configStore } from "@multica/core/config";
+import type { WebhookEventFilter } from "@multica/core/types";
import { screen, fireEvent, within } from "@testing-library/react";
import { renderWithI18n } from "../../test/i18n";
import { WebhookEventFilterSection } from "./webhook-event-filter-section";
-
-// The two icon-only controls in this section used to render with no
-// accessible name at all, so a screen reader announced a bare "button" and
-// sighted users had nothing telling them the row still had to be committed.
-// getByRole(..., { name }) is the assertion that keeps them named.
+import {
+ draftsFromEventFilters,
+ resolveEventFilterDrafts,
+ type ResolvedEventFilters,
+} from "./webhook-event-filter-draft";
+
+// The editor is controlled by its drafts. The harness owns them the way the
+// webhook dialog does and reports what a save would send after every change.
+function Harness({
+ initial = [],
+ showErrors = false,
+ onResolved,
+}: {
+ initial?: WebhookEventFilter[];
+ showErrors?: boolean;
+ onResolved?: (resolved: ResolvedEventFilters) => void;
+}) {
+ const [drafts, setDrafts] = useState(() => draftsFromEventFilters(initial));
+ return (
+ <WebhookEventFilterSection
+ drafts={drafts}
+ showErrors={showErrors}
+ onChange={(next) => {
+ setDrafts(next);
+ onResolved?.(resolveEventFilterDrafts(next));
+ }}
+ />
+ );
+}
+
+function renderEditor(props: Parameters<typeof Harness>[0] = {}, locale?: "zh-Hans" | "zh-Hant") {
+ const onResolved = vi.fn<(resolved: ResolvedEventFilters) => void>();
+ const result = renderWithI18n(<Harness {...props} onResolved={onResolved} />, locale ? { locale } : undefined);
+ const lastResolved = () => onResolved.mock.calls.at(-1)?.[0];
+ return { ...result, lastResolved };
+}
+
+const type = (el: HTMLElement, value: string) => fireEvent.change(el, { target: { value } });
describe("WebhookEventFilterSection", () => {
beforeEach(() => configStore.getState().setWebhookPayloadConditionsSupported(true));
@@ -15,117 +50,69 @@ describe("WebhookEventFilterSection", () => {
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()} />);
+ renderEditor({ initial: [{ event: "pull_request" }] });
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()} />,
- );
- expect(screen.getByRole("button", { name: "Add" })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Add rule" })).toBeInTheDocument();
});
- it("names the remove control on a committed row", () => {
- renderWithI18n(
- <WebhookEventFilterSection
- filters={[{ event: "workflow_run", actions: ["completed"] }]}
- onChange={vi.fn()}
- />,
- );
- expect(
- screen.getByRole("button", { name: "Remove filter" }),
- ).toBeInTheDocument();
- });
+ // Regression cover: rules and conditions each went through a sub-form with
+ // its own "Add", so text left in one was dropped on Save, and a saved rule
+ // could only be removed and typed again. Every field is now edited in place.
+ it("adds a rule as an editable card and focuses its event", () => {
+ const { lastResolved } = renderEditor();
- it("keeps add disabled until an event is typed", () => {
- renderWithI18n(
- <WebhookEventFilterSection filters={[]} onChange={vi.fn()} />,
- );
- const add = screen.getByRole("button", { name: "Add" });
- expect(add).toBeDisabled();
+ fireEvent.click(screen.getByRole("button", { name: "Add rule" }));
+ const event = screen.getByRole("textbox", { name: "Event" });
+ expect(event).toHaveFocus();
- fireEvent.change(screen.getByPlaceholderText("e.g. workflow_run"), {
- target: { value: "workflow_run" },
- });
- expect(add).toBeEnabled();
- });
+ type(event, "workflow_run");
+ type(screen.getByRole("textbox", { name: "Actions" }), "completed, failed");
- it("stays disabled for whitespace-only input", () => {
- renderWithI18n(
- <WebhookEventFilterSection filters={[]} onChange={vi.fn()} />,
- );
- fireEvent.change(screen.getByPlaceholderText("e.g. workflow_run"), {
- target: { value: " " },
+ expect(lastResolved()).toMatchObject({
+ valid: true,
+ filters: [{ event: "workflow_run", actions: ["completed", "failed"] }],
});
- expect(screen.getByRole("button", { name: "Add" })).toBeDisabled();
});
- it("commits the row through onChange when add is clicked", () => {
- const onChange = vi.fn();
- renderWithI18n(
- <WebhookEventFilterSection filters={[]} onChange={onChange} />,
- );
- fireEvent.change(screen.getByPlaceholderText("e.g. workflow_run"), {
- target: { value: "workflow_run" },
+ it("edits a saved rule in place and keeps its conditions", () => {
+ const { lastResolved } = renderEditor({
+ initial: [
+ {
+ event: "pull_request",
+ actions: ["opened"],
+ conditions: [{ path: "pull_request.base.ref", op: "equals", value: "main" }],
+ },
+ ],
});
- fireEvent.change(screen.getByPlaceholderText("completed, failed"), {
- target: { value: "completed, failed" },
- });
- fireEvent.click(screen.getByRole("button", { name: "Add" }));
- expect(onChange).toHaveBeenCalledWith([
- { event: "workflow_run", actions: ["completed", "failed"] },
+ const rule = screen.getByRole("group", { name: "pull_request" });
+ type(within(rule).getByRole("textbox", { name: "Actions" }), "opened, reopened");
+
+ expect(lastResolved()?.filters).toEqual([
+ {
+ event: "pull_request",
+ actions: ["opened", "reopened"],
+ conditions: [{ path: "pull_request.base.ref", op: "equals", value: "main" }],
+ },
]);
});
- 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 row to the rule it was added on", () => {
+ const { lastResolved } = renderEditor({
+ initial: [{ event: "issues", actions: ["labeled"] }, { event: "push" }],
+ });
- 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" },
+ fireEvent.click(
+ within(screen.getByRole("group", { name: "issues" })).getByRole("button", {
+ name: "Add condition",
+ }),
);
- expect(add).toBeDisabled();
+ const path = screen.getByRole("textbox", { name: "Payload field" });
+ expect(path).toHaveFocus();
+ type(path, "label.name");
+ type(screen.getByRole("textbox", { name: "Value" }), "agent");
- 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([
+ expect(lastResolved()?.filters).toEqual([
{
event: "issues",
actions: ["labeled"],
@@ -135,44 +122,63 @@ describe("WebhookEventFilterSection", () => {
]);
});
- 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("shows saved values the way they have to be typed to keep their type", () => {
+ renderEditor({
+ initial: [
+ {
+ event: "pull_request",
+ conditions: [
+ { path: "pull_request.draft", op: "equals", value: false },
+ { path: "pull_request.title", op: "contains", value: "false" },
+ { path: "pull_request.base.ref", op: "in", values: ["main", "release"] },
+ ],
+ },
+ ],
+ });
+
+ expect(screen.getAllByRole("textbox", { name: "Value" }).map((el) => (el as HTMLInputElement).value)).toEqual([
+ "false",
+ '"false"',
+ "main, release",
+ ]);
});
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}
- />,
- );
+ const { lastResolved } = renderEditor({
+ initial: [{ event: "issues", conditions: [{ path: "label.name", op: "equals", value: "agent" }] }],
+ });
fireEvent.click(screen.getByRole("button", { name: "Remove condition" }));
- expect(onChange).toHaveBeenCalledWith([{ event: "issues" }]);
+ expect(lastResolved()?.filters).toEqual([{ event: "issues" }]);
});
- it("drops the row from the list when remove is clicked", () => {
- const onChange = vi.fn();
- renderWithI18n(
- <WebhookEventFilterSection
- filters={[{ event: "issues" }, { event: "workflow_run" }]}
- onChange={onChange}
- />,
- );
- fireEvent.click(
- screen.getAllByRole("button", { name: "Remove filter" })[1]!,
+ it("drops the rule when remove is clicked", () => {
+ const { lastResolved } = renderEditor({ initial: [{ event: "issues" }, { event: "workflow_run" }] });
+ fireEvent.click(screen.getAllByRole("button", { name: "Remove rule" })[1]!);
+ expect(lastResolved()?.filters).toEqual([{ event: "issues" }]);
+ });
+
+ it("marks nothing until a save is attempted", () => {
+ renderEditor({ initial: [{ event: "" }] });
+ expect(screen.getByRole("textbox", { name: "Event" })).not.toHaveAttribute("aria-invalid");
+ expect(screen.queryByText("Enter an event name.")).not.toBeInTheDocument();
+ });
+
+ it("marks every incomplete field after a save attempt and focuses the first", () => {
+ renderEditor({
+ showErrors: true,
+ initial: [
+ { event: "" },
+ { event: "issues", conditions: [{ path: "a..b", op: "equals", value: "x" }] },
+ ],
+ });
+
+ const [emptyEvent] = screen.getAllByRole("textbox", { name: "Event" });
+ expect(emptyEvent).toHaveAttribute("aria-invalid", "true");
+ expect(emptyEvent).toHaveFocus();
+ expect(emptyEvent).toHaveAccessibleDescription("Enter an event name.");
+ expect(screen.getByRole("textbox", { name: "Payload field" })).toHaveAccessibleDescription(
+ "Separate field names with dots, up to 256 characters.",
);
- expect(onChange).toHaveBeenCalledWith([{ event: "issues" }]);
});
it.each([
@@ -185,12 +191,7 @@ describe("WebhookEventFilterSection", () => {
`https://multica.ai/docs/zh-Hant/autopilots#${encodeURIComponent("事件過濾")}`,
],
] as const)("links the %s event filter docs section", (locale, href) => {
- renderWithI18n(
- <WebhookEventFilterSection filters={[]} onChange={vi.fn()} />,
- {
- locale,
- },
- );
+ renderEditor({}, locale);
expect(screen.getByRole("link")).toHaveAttribute("href", href);
});
});
diff --git a/packages/views/autopilots/components/webhook-event-filter-section.tsx b/packages/views/autopilots/components/webhook-event-filter-section.tsx
index dce47ac8fe..aa3f40b2b4 100644
--- a/packages/views/autopilots/components/webhook-event-filter-section.tsx
+++ b/packages/views/autopilots/components/webhook-event-filter-section.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useId, useState } from "react";
+import { useEffect, useId, useRef } 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";
@@ -13,43 +13,52 @@ import {
SelectTrigger,
SelectValue,
} from "@multica/ui/components/ui/select";
-import type {
- WebhookEventFilter,
- WebhookPayloadCondition,
-} from "@multica/core/types";
+import type { WebhookEventFilter } 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 {
+ newConditionDraft,
+ newRuleDraft,
+ resolveEventFilterDrafts,
+ type ConditionFieldError,
+ type ConditionRowDraft,
+ type EventFilterDraft,
+} from "./webhook-event-filter-draft";
import { isTraditionalChinese } from "../../common/docs-locale";
interface WebhookEventFilterSectionProps {
- filters: WebhookEventFilter[];
- onChange: (filters: WebhookEventFilter[]) => void;
+ drafts: EventFilterDraft[];
+ onChange: (drafts: EventFilterDraft[]) => void;
+ // Set once a save was attempted: incomplete fields are marked from then on,
+ // and the first of them takes focus.
+ showErrors: boolean;
}
+const INPUT =
+ "h-7 w-full min-w-0 rounded-md border bg-background px-2.5 text-caption outline-none focus:ring-1 focus:ring-ring aria-invalid:border-destructive aria-invalid:focus:ring-destructive";
+
+// Rules and conditions are edited where they are shown: "Add rule" appends an
+// empty rule card, "Add condition" an empty condition row, and every field is
+// an input, existing ones included. What the inputs hold is what Save sends,
+// so there is no per-row commit to forget, and an incomplete row stops the
+// save and says where instead of being dropped.
export function WebhookEventFilterSection({
- filters,
+ drafts,
onChange,
+ showErrors,
}: WebhookEventFilterSectionProps) {
const { t, i18n } = useT("autopilots");
- const conditionLimitsId = useId();
+ const idPrefix = useId();
+ const rootRef = useRef<HTMLDivElement>(null);
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 { errors } = resolveEventFilterDrafts(drafts);
const docsHref = isTraditionalChinese(i18n.language)
? `https://multica.ai/docs/zh-Hant/autopilots#${encodeURIComponent("事件過濾")}`
: i18n.language?.startsWith("zh")
@@ -58,50 +67,55 @@ export function WebhookEventFilterSection({
? `https://multica.ai/docs/fr/autopilots#${encodeURIComponent("filtres-dévénements")}`
: "https://multica.ai/docs/autopilots#event-filters";
- const addFilter = () => {
- const event = newEvent.trim();
- if (!event) return;
- const actions = newActions
- .split(",")
- .map((a) => a.trim())
- .filter((a) => a.length > 0);
- const next: WebhookEventFilter = { event };
- if (actions.length > 0) next.actions = actions;
- onChange([...filters, next]);
- setNewEvent("");
- setNewActions("");
- };
+ // A blocked save lands the user on the first field that blocked it.
+ useEffect(() => {
+ if (!showErrors) return;
+ rootRef.current?.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus();
+ }, [showErrors]);
- const removeFilter = (idx: number) => {
- onChange(filters.filter((_, i) => i !== idx));
- setEditingIdx(null);
- };
+ // A row added with a button is typed into next, so its first field takes
+ // focus once it renders.
+ const focusKeyRef = useRef<string | null>(null);
+ useEffect(() => {
+ const key = focusKeyRef.current;
+ if (!key) return;
+ focusKeyRef.current = null;
+ rootRef.current?.querySelector<HTMLElement>(`[data-focus-key="${key}"]`)?.focus();
+ }, [drafts]);
+
+ const updateRule = (key: string, patch: Partial<EventFilterDraft>) =>
+ onChange(drafts.map((d) => (d.key === key ? { ...d, ...patch } : d)));
- const updateConditions = (idx: number, conditions: WebhookPayloadCondition[]) => {
+ const updateCondition = (ruleKey: string, rowKey: string, patch: Partial<ConditionRowDraft>) =>
onChange(
- filters.map((f, i) => {
- if (i !== idx) return f;
- const { conditions: _previous, ...rest } = f;
- return conditions.length > 0 ? { ...rest, conditions } : rest;
- }),
+ drafts.map((d) =>
+ d.key === ruleKey
+ ? { ...d, conditions: d.conditions.map((c) => (c.key === rowKey ? { ...c, ...patch } : c)) }
+ : d,
+ ),
);
- };
-
- 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 conditionErrorText = (error: ConditionFieldError) => {
+ switch (error) {
+ case "path_required":
+ return t(($) => $.dialog.event_filter_error_path_required);
+ case "path_invalid":
+ return t(($) => $.dialog.event_filter_error_path_invalid, {
+ path: MAX_CONDITION_PATH_LENGTH,
+ });
+ case "value_required":
+ return t(($) => $.dialog.event_filter_error_value_required);
+ case "values_too_many":
+ return t(($) => $.dialog.event_filter_error_too_many_values, {
+ values: MAX_CONDITION_VALUES,
+ });
+ }
};
const opLabel = (op: ConditionOp) => t(($) => $.dialog.event_filter_condition_ops[op]);
return (
- <div className="space-y-2">
+ <div ref={rootRef} className="space-y-2">
<div className="flex items-center gap-1.5 text-micro font-semibold tracking-[0.08em] text-muted-foreground uppercase">
<Filter className="size-3" />
{t(($) => $.dialog.event_filter_label)}
@@ -117,241 +131,211 @@ export function WebhookEventFilterSection({
</a>
</div>
- {filters.length > 0 && (
- <div className="space-y-1">
- {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>
+ {drafts.map((rule) => {
+ const eventError = showErrors ? errors.events[rule.key] : undefined;
+ const eventErrorId = `${idPrefix}-${rule.key}-event-error`;
+ const canAddCondition = payloadSupported && rule.conditions.length < MAX_CONDITIONS;
+ return (
+ <div
+ key={rule.key}
+ role="group"
+ aria-label={rule.event.trim() || t(($) => $.dialog.event_filter_new_rule_label)}
+ className="space-y-2 rounded-md border bg-background p-2 text-caption"
+ >
+ <div className="flex items-start gap-1.5">
+ <div className="min-w-0 flex-[3]">
+ <input
+ type="text"
+ data-focus-key={rule.key}
+ value={rule.event}
+ onChange={(e) => updateRule(rule.key, { event: e.target.value })}
+ aria-label={t(($) => $.dialog.event_filter_event_label)}
+ aria-invalid={eventError ? true : undefined}
+ aria-describedby={eventError ? eventErrorId : undefined}
+ placeholder={t(($) => $.dialog.event_filter_event_placeholder)}
+ className={cn(INPUT, "font-mono")}
+ />
+ {eventError && (
+ <p id={eventErrorId} className="mt-1 text-micro text-destructive">
+ {t(($) => $.dialog.event_filter_error_event_required)}
+ </p>
+ )}
+ </div>
+ <input
+ type="text"
+ value={rule.actions}
+ onChange={(e) => updateRule(rule.key, { actions: e.target.value })}
+ aria-label={t(($) => $.dialog.event_filter_actions_label)}
+ placeholder={t(($) => $.dialog.event_filter_actions_placeholder)}
+ className={cn(INPUT, "flex-[2]")}
+ />
+ <TooltipHint label={t(($) => $.dialog.event_filter_remove_label)}>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ className="mt-1 shrink-0"
+ onClick={() => onChange(drafts.filter((d) => d.key !== rule.key))}
+ aria-label={t(($) => $.dialog.event_filter_remove_label)}
+ >
+ <X />
+ </Button>
+ </TooltipHint>
+ </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>
- )}
+ {rule.conditions.length > 0 && (
+ <div className="space-y-2">
+ <p className="text-micro text-muted-foreground">
+ {t(($) => $.dialog.event_filter_condition_all)}
+ </p>
+ {rule.conditions.map((row) => {
+ const pathError = showErrors ? errors.paths[row.key] : undefined;
+ const valueError = showErrors ? errors.values[row.key] : undefined;
+ const pathErrorId = `${idPrefix}-${row.key}-path-error`;
+ const valueErrorId = `${idPrefix}-${row.key}-value-error`;
+ return (
+ <div
+ key={row.key}
+ role="group"
+ aria-label={t(($) => $.dialog.event_filter_condition_label)}
+ className="space-y-1.5 border-l-2 pl-2"
+ >
+ <div className="flex items-start gap-1.5">
+ <div className="min-w-0 flex-1">
+ <input
+ type="text"
+ data-focus-key={row.key}
+ value={row.path}
+ onChange={(e) => updateCondition(rule.key, row.key, { path: e.target.value })}
+ aria-label={t(($) => $.dialog.event_filter_condition_path_label)}
+ aria-invalid={pathError ? true : undefined}
+ aria-describedby={pathError ? pathErrorId : undefined}
+ placeholder={t(($) => $.dialog.event_filter_condition_path_placeholder)}
+ className={cn(INPUT, "font-mono")}
+ />
+ {pathError && (
+ <p id={pathErrorId} className="mt-1 text-micro text-destructive">
+ {conditionErrorText(pathError)}
+ </p>
+ )}
+ </div>
<TooltipHint label={t(($) => $.dialog.event_filter_condition_remove_label)}>
<Button
type="button"
variant="ghost"
size="icon-xs"
- className="ml-auto"
+ className="mt-1 shrink-0"
onClick={() =>
- updateConditions(
- idx,
- conditions.filter((_, i) => i !== cIdx),
- )
+ updateRule(rule.key, {
+ conditions: rule.conditions.filter((c) => c.key !== row.key),
+ })
}
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);
- }
+ </div>
+ <div className="flex items-start gap-1.5">
+ <Select
+ items={CONDITION_OPS.map((op) => ({ value: op, label: opLabel(op) }))}
+ value={row.op}
+ onValueChange={(v) => {
+ if (v) updateCondition(rule.key, row.key, { op: v as ConditionOp });
}}
- 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>
+ >
+ <SelectTrigger
+ size="sm"
+ aria-label={t(($) => $.dialog.event_filter_condition_op_label)}
+ className={cn("text-caption", row.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>
+ {row.op !== "exists" && (
+ <>
+ <div className="min-w-0 flex-1">
+ <input
+ type="text"
+ value={row.value}
+ onChange={(e) =>
+ updateCondition(rule.key, row.key, { value: e.target.value })
+ }
+ aria-label={t(($) => $.dialog.event_filter_condition_value_label)}
+ aria-invalid={valueError ? true : undefined}
+ aria-describedby={valueError ? valueErrorId : undefined}
+ placeholder={
+ row.op === "in"
+ ? t(($) => $.dialog.event_filter_condition_values_placeholder)
+ : t(($) => $.dialog.event_filter_condition_value_placeholder)
+ }
+ className={cn(INPUT, "font-mono")}
+ />
+ {valueError && (
+ <p id={valueErrorId} className="mt-1 text-micro text-destructive">
+ {conditionErrorText(valueError)}
+ </p>
+ )}
+ </div>
+ <label className="inline-flex h-7 shrink-0 items-center gap-1.5 whitespace-nowrap text-muted-foreground">
+ <Checkbox
+ checked={row.ignoreCase}
+ onCheckedChange={(checked) =>
+ updateCondition(rule.key, row.key, { ignoreCase: checked === true })
+ }
+ />
+ {t(($) => $.dialog.event_filter_condition_ignore_case)}
+ </label>
+ </>
+ )}
+ </div>
</div>
- </div>
- )}
+ );
+ })}
</div>
- );
- })}
- </div>
- )}
+ )}
- {/* Actions widen only where the row has room (the per-webhook dialog),
- so their placeholder isn't clipped there; the autopilot dialog's side
- panel keeps w-28, which leaves the event placeholder whole. */}
- <div className="@container/ef-add flex gap-2">
- <input
- type="text"
- value={newEvent}
- onChange={(e) => setNewEvent(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter") {
- e.preventDefault();
- addFilter();
- }
- }}
- placeholder={t(($) => $.dialog.event_filter_event_placeholder)}
- className="flex-1 min-w-0 rounded-md border bg-background px-2.5 py-1.5 text-caption font-mono outline-none focus:ring-1 focus:ring-ring"
- />
- <input
- type="text"
- value={newActions}
- onChange={(e) => setNewActions(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter") {
- e.preventDefault();
- addFilter();
- }
- }}
- placeholder={t(($) => $.dialog.event_filter_actions_placeholder)}
- className="w-28 rounded-md border bg-background px-2.5 py-1.5 text-caption outline-none focus:ring-1 focus:ring-ring @sm/ef-add:w-36"
- />
- <button
- type="button"
- onClick={addFilter}
- disabled={!newEvent.trim()}
- className={cn(
- "inline-flex shrink-0 items-center justify-center gap-1 rounded-md border px-2.5 py-1.5 text-caption font-medium transition-colors",
- newEvent.trim()
- ? "border-primary bg-primary text-primary-foreground hover:bg-primary/90 cursor-pointer"
- : "bg-muted text-muted-foreground cursor-not-allowed",
- )}
- >
- <Plus className="size-3.5" />
- {t(($) => $.dialog.event_filter_add)}
- </button>
- </div>
+ {canAddCondition && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ className="text-muted-foreground"
+ onClick={() => {
+ const row = newConditionDraft();
+ focusKeyRef.current = row.key;
+ updateRule(rule.key, { conditions: [...rule.conditions, row] });
+ }}
+ >
+ <Plus />
+ {t(($) => $.dialog.event_filter_condition_add_label)}
+ </Button>
+ )}
+ </div>
+ );
+ })}
+
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ className="text-muted-foreground"
+ onClick={() => {
+ const rule = newRuleDraft();
+ focusKeyRef.current = rule.key;
+ onChange([...drafts, rule]);
+ }}
+ >
+ <Plus />
+ {t(($) => $.dialog.event_filter_add_rule)}
+ </Button>
<p className="text-micro text-muted-foreground">
{t(($) => $.dialog.event_filter_hint)}
</p>
diff --git a/packages/views/autopilots/components/webhook-payload-condition.test.ts b/packages/views/autopilots/components/webhook-payload-condition.test.ts
index 64d9a11b5c..42c6eb8a88 100644
--- a/packages/views/autopilots/components/webhook-payload-condition.test.ts
+++ b/packages/views/autopilots/components/webhook-payload-condition.test.ts
@@ -1,11 +1,11 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import {
- EMPTY_CONDITION_DRAFT,
buildCondition,
- formatCondition,
formatConditionValue,
parseConditionValue,
+ splitConditionValues,
+ type ConditionDraft,
} from "./webhook-payload-condition";
describe("parseConditionValue", () => {
@@ -24,8 +24,11 @@ describe("parseConditionValue", () => {
});
describe("buildCondition", () => {
- const draft = (patch: Partial<typeof EMPTY_CONDITION_DRAFT>) => ({
- ...EMPTY_CONDITION_DRAFT,
+ const draft = (patch: Partial<ConditionDraft>): ConditionDraft => ({
+ path: "",
+ op: "equals",
+ value: "",
+ ignoreCase: false,
...patch,
});
@@ -80,15 +83,6 @@ describe("buildCondition", () => {
});
});
-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"');
@@ -96,3 +90,17 @@ describe("formatConditionValue", () => {
expect(formatConditionValue({ path: "a", op: "in", values: ["x", 1] })).toBe('"x", 1');
});
});
+
+describe("splitConditionValues", () => {
+ it.each([
+ ["main, release", ["main", "release"]],
+ ['"fix, docs", chore', ['"fix, docs"', "chore"]],
+ ['"a\\", b", c', ['"a\\", b"', "c"]],
+ ['a"b, c', ['a"b', "c"]],
+ ['"open, x', ['"open', "x"]],
+ ['"", main', ['""', "main"]],
+ [" , main ,", ["main"]],
+ ] as const)("splits %s outside quoted values", (raw, want) => {
+ expect(splitConditionValues(raw)).toEqual(want);
+ });
+});
diff --git a/packages/views/autopilots/components/webhook-payload-condition.ts b/packages/views/autopilots/components/webhook-payload-condition.ts
index 4d003d99e2..e3315b8775 100644
--- a/packages/views/autopilots/components/webhook-payload-condition.ts
+++ b/packages/views/autopilots/components/webhook-payload-condition.ts
@@ -20,13 +20,6 @@ export function formatConditionValue(c: WebhookPayloadCondition): string {
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 {
@@ -46,6 +39,30 @@ export function parseConditionValue(raw: string): WebhookPayloadConditionValue {
return trimmed;
}
+// splitConditionValues splits an "is one of" list at its commas, except for
+// commas inside a value written as a quoted string ("fix, docs"), so a value
+// that holds a comma survives the trip through the text input. A value that
+// opens a quote without closing it is read as plain text up to its comma.
+export function splitConditionValues(raw: string): string[] {
+ const values: string[] = [];
+ let from = 0;
+ for (;;) {
+ let start = from;
+ while (start < raw.length && /\s/.test(raw[start]!)) start++;
+ let scanFrom = start;
+ if (raw[start] === '"') {
+ let i = start + 1;
+ while (i < raw.length && raw[i] !== '"') i += raw[i] === "\\" ? 2 : 1;
+ if (i < raw.length) scanFrom = i + 1;
+ }
+ const comma = raw.indexOf(",", scanFrom);
+ const value = raw.slice(start, comma === -1 ? raw.length : comma).trim();
+ if (value) values.push(value);
+ if (comma === -1) return values;
+ from = comma + 1;
+ }
+}
+
export interface ConditionDraft {
path: string;
op: ConditionOp;
@@ -53,8 +70,6 @@ export interface ConditionDraft {
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 {
@@ -65,10 +80,7 @@ export function buildCondition(draft: ConditionDraft): WebhookPayloadCondition |
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);
+ const values = splitConditionValues(draft.value);
if (values.length === 0 || values.length > MAX_CONDITION_VALUES) return null;
condition.values = values.map(parseConditionValue);
} else if (draft.op === "contains") {
diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.json
index 6a527e50c3..9741ef23ae 100644
--- a/packages/views/locales/en/autopilots.json
+++ b/packages/views/locales/en/autopilots.json
@@ -350,14 +350,22 @@
"webhook_created_done": "Done",
"event_filter_label": "Event filters",
"event_filter_docs_link_label": "Learn how event filters work",
- "event_filter_event_placeholder": "e.g. workflow_run",
- "event_filter_actions_placeholder": "completed, failed",
- "event_filter_add": "Add",
- "event_filter_remove_label": "Remove filter",
+ "event_filter_event_placeholder": "Event, e.g. pull_request",
+ "event_filter_actions_placeholder": "Actions (optional)",
+ "event_filter_add_rule": "Add rule",
+ "event_filter_event_label": "Event",
+ "event_filter_actions_label": "Actions",
+ "event_filter_new_rule_label": "New rule",
+ "event_filter_condition_label": "Condition",
+ "event_filter_error_event_required": "Enter an event name.",
+ "event_filter_error_path_required": "Enter a payload field.",
+ "event_filter_error_path_invalid": "Separate field names with dots, up to {{path}} characters.",
+ "event_filter_error_value_required": "Enter a value.",
+ "event_filter_error_too_many_values": "Up to {{values}} values.",
+ "event_filter_remove_label": "Remove rule",
"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",
@@ -366,7 +374,7 @@
"exists": "exists"
},
"event_filter_condition_path_label": "Payload field",
- "event_filter_condition_path_placeholder": "e.g. pull_request.labels.*.name",
+ "event_filter_condition_path_placeholder": "Payload field, e.g. pull_request.base.ref",
"event_filter_condition_op_label": "Operator",
"event_filter_condition_value_label": "Value",
"event_filter_condition_value_placeholder": "e.g. main",
@@ -374,6 +382,8 @@
"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.",
"webhook_multiple_notice": "This autopilot has more than one webhook. Close this dialog and edit each one under Triggers below.",
+ "webhook_edit_filters": "Edit filters",
+ "webhook_filters_saved_separately": "Saved on their own: Cancel here won't undo them.",
"schedule_empty": "No schedule — this autopilot only runs when triggered manually.",
"schedule_add": "Add schedule",
"error_title_required": "Enter a name for this autopilot.",
@@ -388,8 +398,7 @@
"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."
+ "event_filter_condition_all": "And payload matches all conditions"
},
"schedule_editor": {
"time_label": "Time",
diff --git a/packages/views/locales/es/autopilots.json b/packages/views/locales/es/autopilots.json
index 5b7ffa9de8..8f4932ff31 100644
--- a/packages/views/locales/es/autopilots.json
+++ b/packages/views/locales/es/autopilots.json
@@ -350,13 +350,24 @@
"webhook_created_done": "Hecho",
"event_filter_label": "Filtros de eventos",
"event_filter_docs_link_label": "Aprende cómo funcionan los filtros de eventos",
- "event_filter_event_placeholder": "p. ej., workflow_run",
- "event_filter_actions_placeholder": "completed, failed",
- "event_filter_add": "Añadir",
- "event_filter_remove_label": "Quitar filtro",
+ "event_filter_event_placeholder": "Evento, p. ej., pull_request",
+ "event_filter_actions_placeholder": "Acciones (opcional)",
+ "event_filter_add_rule": "Añadir regla",
+ "event_filter_event_label": "Evento",
+ "event_filter_actions_label": "Acciones",
+ "event_filter_new_rule_label": "Nueva regla",
+ "event_filter_condition_label": "Condición",
+ "event_filter_error_event_required": "Introduce un nombre de evento.",
+ "event_filter_error_path_required": "Introduce un campo del contenido.",
+ "event_filter_error_path_invalid": "Separa los nombres de campo con puntos, hasta {{path}} caracteres.",
+ "event_filter_error_value_required": "Introduce un valor.",
+ "event_filter_error_too_many_values": "Hasta {{values}} valores.",
+ "event_filter_remove_label": "Eliminar regla",
"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.",
"webhook_multiple_notice": "Esta automatización tiene varios webhooks. Cierra este diálogo y edita cada uno en Disparadores, más abajo.",
+ "webhook_edit_filters": "Editar filtros",
+ "webhook_filters_saved_separately": "Los filtros se guardan por separado: Cancelar aquí no los deshace.",
"schedule_empty": "Sin programación: esta automatización solo se ejecuta cuando se dispara manualmente.",
"schedule_add": "Añadir programación",
"error_title_required": "Introduce un nombre para esta automatización.",
@@ -373,7 +384,6 @@
},
"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",
@@ -382,14 +392,13 @@
"exists": "existe"
},
"event_filter_condition_path_label": "Campo del contenido",
- "event_filter_condition_path_placeholder": "p. ej., pull_request.labels.*.name",
+ "event_filter_condition_path_placeholder": "Campo del contenido, p. ej., pull_request.base.ref",
"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."
+ "event_filter_condition_all": "Y el contenido cumple todas las condiciones"
},
"schedule_editor": {
"time_label": "Hora",
diff --git a/packages/views/locales/fr/autopilots.json b/packages/views/locales/fr/autopilots.json
index 012739a551..c3d22ca6d9 100644
--- a/packages/views/locales/fr/autopilots.json
+++ b/packages/views/locales/fr/autopilots.json
@@ -350,14 +350,22 @@
"webhook_created_done": "Terminé",
"event_filter_label": "Filtres d'événements",
"event_filter_docs_link_label": "Comprendre le fonctionnement des filtres d'événements",
- "event_filter_event_placeholder": "ex. workflow_run",
- "event_filter_actions_placeholder": "completed, failed",
- "event_filter_add": "Ajouter",
- "event_filter_remove_label": "Retirer le filtre",
+ "event_filter_event_placeholder": "Événement, ex. pull_request",
+ "event_filter_actions_placeholder": "Actions (facultatif)",
+ "event_filter_add_rule": "Ajouter une règle",
+ "event_filter_event_label": "Événement",
+ "event_filter_actions_label": "Actions",
+ "event_filter_new_rule_label": "Nouvelle règle",
+ "event_filter_condition_label": "Condition",
+ "event_filter_error_event_required": "Saisissez un nom d'événement.",
+ "event_filter_error_path_required": "Saisissez un champ de la charge utile.",
+ "event_filter_error_path_invalid": "Séparez les noms de champ par des points, {{path}} caractères maximum.",
+ "event_filter_error_value_required": "Saisissez une valeur.",
+ "event_filter_error_too_many_values": "{{values}} valeurs maximum.",
+ "event_filter_remove_label": "Supprimer la règle",
"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",
@@ -366,7 +374,7 @@
"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_path_placeholder": "Champ de la charge utile, ex. pull_request.base.ref",
"event_filter_condition_op_label": "Opérateur",
"event_filter_condition_value_label": "Valeur",
"event_filter_condition_value_placeholder": "ex. main",
@@ -374,6 +382,8 @@
"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.",
"webhook_multiple_notice": "Cette automatisation a plusieurs webhooks. Fermez cette fenêtre et modifiez chacun dans la liste Déclencheurs ci-dessous.",
+ "webhook_edit_filters": "Modifier les filtres",
+ "webhook_filters_saved_separately": "Les filtres sont enregistrés à part : Annuler ici ne les rétablit pas.",
"schedule_empty": "Aucune planification — cette automatisation ne s'exécute que sur déclenchement manuel.",
"schedule_add": "Ajouter une planification",
"error_title_required": "Saisissez un nom pour cette automatisation.",
@@ -388,8 +398,7 @@
"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."
+ "event_filter_condition_all": "Et la charge utile remplit toutes les conditions"
},
"schedule_editor": {
"time_label": "Heure",
diff --git a/packages/views/locales/ja/autopilots.json b/packages/views/locales/ja/autopilots.json
index ef64e8de9f..9a398c7361 100644
--- a/packages/views/locales/ja/autopilots.json
+++ b/packages/views/locales/ja/autopilots.json
@@ -349,14 +349,22 @@
"webhook_created_done": "完了",
"event_filter_label": "イベントフィルター",
"event_filter_docs_link_label": "イベントフィルターの仕組みを学ぶ",
- "event_filter_event_placeholder": "例: workflow_run",
- "event_filter_actions_placeholder": "completed, failed",
- "event_filter_add": "追加",
- "event_filter_remove_label": "フィルターを削除",
+ "event_filter_event_placeholder": "イベント(例: pull_request)",
+ "event_filter_actions_placeholder": "アクション(任意)",
+ "event_filter_add_rule": "ルールを追加",
+ "event_filter_event_label": "イベント",
+ "event_filter_actions_label": "アクション",
+ "event_filter_new_rule_label": "新しいルール",
+ "event_filter_condition_label": "条件",
+ "event_filter_error_event_required": "イベント名を入力してください。",
+ "event_filter_error_path_required": "Payload のフィールドを入力してください。",
+ "event_filter_error_path_invalid": "フィールド名はドットで区切り、{{path}} 文字以内にしてください。",
+ "event_filter_error_value_required": "値を入力してください。",
+ "event_filter_error_too_many_values": "値は {{values}} 個までです。",
+ "event_filter_remove_label": "ルールを削除",
"event_filter_hint": "ルールと本文のすべての条件に一致するイベントのみ処理します。空欄の場合はすべて受け付けます。",
"event_filter_condition_remove_label": "条件を削除",
"event_filter_condition_add_label": "条件を追加",
- "event_filter_condition_cancel": "キャンセル",
"event_filter_condition_ops": {
"equals": "等しい",
"not_equals": "等しくない",
@@ -365,7 +373,7 @@
"exists": "存在する"
},
"event_filter_condition_path_label": "Payload のフィールド",
- "event_filter_condition_path_placeholder": "例: pull_request.labels.*.name",
+ "event_filter_condition_path_placeholder": "Payload のフィールド(例: pull_request.base.ref)",
"event_filter_condition_op_label": "演算子",
"event_filter_condition_value_label": "値",
"event_filter_condition_value_placeholder": "例: main",
@@ -373,6 +381,8 @@
"event_filter_condition_ignore_case": "大文字と小文字を区別しない",
"schedule_multiple_notice": "このオートパイロットにはスケジュールが {{count}} 件あります。このダイアログを閉じて、下の「トリガー」から個別に編集してください。",
"webhook_multiple_notice": "このオートパイロットには Webhook が複数あります。このダイアログを閉じて、下の「トリガー」から個別に編集してください。",
+ "webhook_edit_filters": "フィルターを編集",
+ "webhook_filters_saved_separately": "フィルターは個別に保存され、ここでキャンセルしても元に戻りません。",
"schedule_empty": "スケジュールはありません。このオートパイロットは手動で実行したときだけ動きます。",
"schedule_add": "スケジュールを追加",
"error_title_required": "オートパイロット名を入力してください。",
@@ -387,8 +397,7 @@
"description": "タスクを作成せず、静かに実行します"
}
},
- "event_filter_condition_all": "かつ本文がすべての条件を満たす",
- "event_filter_condition_limits": "パスは {{path}} 文字まで、候補リストは {{values}} 個までです。"
+ "event_filter_condition_all": "かつ本文がすべての条件を満たす"
},
"schedule_editor": {
"time_label": "時刻",
diff --git a/packages/views/locales/ko/autopilots.json b/packages/views/locales/ko/autopilots.json
index 714f22df79..adef8cfba4 100644
--- a/packages/views/locales/ko/autopilots.json
+++ b/packages/views/locales/ko/autopilots.json
@@ -349,14 +349,22 @@
"webhook_created_done": "완료",
"event_filter_label": "이벤트 필터",
"event_filter_docs_link_label": "이벤트 필터 작동 방식 알아보기",
- "event_filter_event_placeholder": "예: workflow_run",
- "event_filter_actions_placeholder": "completed, failed",
- "event_filter_add": "추가",
- "event_filter_remove_label": "필터 제거",
+ "event_filter_event_placeholder": "이벤트 (예: pull_request)",
+ "event_filter_actions_placeholder": "액션 (선택)",
+ "event_filter_add_rule": "규칙 추가",
+ "event_filter_event_label": "이벤트",
+ "event_filter_actions_label": "액션",
+ "event_filter_new_rule_label": "새 규칙",
+ "event_filter_condition_label": "조건",
+ "event_filter_error_event_required": "이벤트 이름을 입력하세요.",
+ "event_filter_error_path_required": "Payload 필드를 입력하세요.",
+ "event_filter_error_path_invalid": "필드 이름은 점으로 구분하고 {{path}}자 이내로 입력하세요.",
+ "event_filter_error_value_required": "값을 입력하세요.",
+ "event_filter_error_too_many_values": "값은 최대 {{values}}개입니다.",
+ "event_filter_remove_label": "규칙 삭제",
"event_filter_hint": "규칙과 모든 본문 조건에 일치하는 이벤트만 처리합니다. 비워 두면 모든 이벤트를 수락합니다.",
"event_filter_condition_remove_label": "조건 제거",
"event_filter_condition_add_label": "조건 추가",
- "event_filter_condition_cancel": "취소",
"event_filter_condition_ops": {
"equals": "같음",
"not_equals": "같지 않음",
@@ -365,7 +373,7 @@
"exists": "존재"
},
"event_filter_condition_path_label": "Payload 필드",
- "event_filter_condition_path_placeholder": "예: pull_request.labels.*.name",
+ "event_filter_condition_path_placeholder": "Payload 필드 (예: pull_request.base.ref)",
"event_filter_condition_op_label": "연산자",
"event_filter_condition_value_label": "값",
"event_filter_condition_value_placeholder": "예: main",
@@ -373,6 +381,8 @@
"event_filter_condition_ignore_case": "대소문자 무시",
"schedule_multiple_notice": "이 오토파일럿에는 일정이 {{count}}개 있습니다. 이 대화상자를 닫고 아래 '트리거'에서 각각 수정하세요.",
"webhook_multiple_notice": "이 오토파일럿에는 Webhook이 여러 개 있습니다. 이 대화상자를 닫고 아래 '트리거'에서 각각 수정하세요.",
+ "webhook_edit_filters": "필터 수정",
+ "webhook_filters_saved_separately": "필터는 따로 저장되며, 여기서 취소해도 되돌려지지 않습니다.",
"schedule_empty": "일정이 없습니다. 이 오토파일럿은 수동으로 실행할 때만 동작합니다.",
"schedule_add": "일정 추가",
"error_title_required": "오토파일럿 이름을 입력하세요.",
@@ -387,8 +397,7 @@
"description": "태스크를 만들지 않고 조용히 실행합니다"
}
},
- "event_filter_condition_all": "본문이 모든 조건을 충족해야 함",
- "event_filter_condition_limits": "경로는 최대 {{path}}자, 후보 목록은 최대 {{values}}개입니다."
+ "event_filter_condition_all": "본문이 모든 조건을 충족해야 함"
},
"schedule_editor": {
"time_label": "시간",
diff --git a/packages/views/locales/ru/autopilots.json b/packages/views/locales/ru/autopilots.json
index dd9c88459b..424e7cab62 100644
--- a/packages/views/locales/ru/autopilots.json
+++ b/packages/views/locales/ru/autopilots.json
@@ -352,13 +352,24 @@
"webhook_created_done": "Готово",
"event_filter_label": "Фильтры событий",
"event_filter_docs_link_label": "Узнать, как работают фильтры событий",
- "event_filter_event_placeholder": "например, workflow_run",
- "event_filter_actions_placeholder": "completed, failed",
- "event_filter_add": "Добавить",
- "event_filter_remove_label": "Удалить фильтр",
+ "event_filter_event_placeholder": "Событие, например pull_request",
+ "event_filter_actions_placeholder": "Действия (необязательно)",
+ "event_filter_add_rule": "Добавить правило",
+ "event_filter_event_label": "Событие",
+ "event_filter_actions_label": "Действия",
+ "event_filter_new_rule_label": "Новое правило",
+ "event_filter_condition_label": "Условие",
+ "event_filter_error_event_required": "Введите название события.",
+ "event_filter_error_path_required": "Введите поле содержимого.",
+ "event_filter_error_path_invalid": "Разделяйте имена полей точками, не более {{path}} символов.",
+ "event_filter_error_value_required": "Введите значение.",
+ "event_filter_error_too_many_values": "Не более {{values}} значений.",
+ "event_filter_remove_label": "Удалить правило",
"event_filter_hint": "Обрабатываются события, соответствующие правилу и всем его условиям. Оставьте пустым, чтобы принимать все события.",
"schedule_multiple_notice": "У этого автопилота {{count}} расписаний. Закройте это окно и измените каждое из них в разделе «Триггеры» ниже.",
"webhook_multiple_notice": "У этого автопилота несколько вебхуков. Закройте это окно и измените каждый из них в разделе «Триггеры» ниже.",
+ "webhook_edit_filters": "Изменить фильтры",
+ "webhook_filters_saved_separately": "Фильтры сохраняются отдельно: «Отмена» здесь их не откатит.",
"schedule_empty": "Нет расписания — этот автопилот запускается только вручную.",
"schedule_add": "Добавить расписание",
"error_title_required": "Введите название для этого автопилота.",
@@ -375,7 +386,6 @@
},
"event_filter_condition_remove_label": "Удалить условие",
"event_filter_condition_add_label": "Добавить условие",
- "event_filter_condition_cancel": "Отмена",
"event_filter_condition_ops": {
"equals": "равно",
"not_equals": "не равно",
@@ -384,14 +394,13 @@
"exists": "существует"
},
"event_filter_condition_path_label": "Поле содержимого",
- "event_filter_condition_path_placeholder": "например, pull_request.labels.*.name",
+ "event_filter_condition_path_placeholder": "Поле содержимого, например pull_request.base.ref",
"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}} значений."
+ "event_filter_condition_all": "И содержимое соответствует всем условиям"
},
"schedule_editor": {
"time_label": "Время",
diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.json
index 8d886aea76..2bee06e3dd 100644
--- a/packages/views/locales/zh-Hans/autopilots.json
+++ b/packages/views/locales/zh-Hans/autopilots.json
@@ -349,14 +349,22 @@
"webhook_created_done": "完成",
"event_filter_label": "事件过滤",
"event_filter_docs_link_label": "了解事件过滤的工作方式",
- "event_filter_event_placeholder": "例如 workflow_run",
- "event_filter_actions_placeholder": "completed, failed",
- "event_filter_add": "添加",
- "event_filter_remove_label": "移除过滤条件",
+ "event_filter_event_placeholder": "事件,例如 pull_request",
+ "event_filter_actions_placeholder": "动作(可选)",
+ "event_filter_add_rule": "添加规则",
+ "event_filter_event_label": "事件",
+ "event_filter_actions_label": "动作",
+ "event_filter_new_rule_label": "新规则",
+ "event_filter_condition_label": "条件",
+ "event_filter_error_event_required": "请填写事件名。",
+ "event_filter_error_path_required": "请填写 Payload 字段。",
+ "event_filter_error_path_invalid": "字段名之间用点分隔,最多 {{path}} 个字符。",
+ "event_filter_error_value_required": "请填写值。",
+ "event_filter_error_too_many_values": "最多 {{values}} 个值。",
+ "event_filter_remove_label": "移除规则",
"event_filter_hint": "只处理匹配规则且正文满足全部条件的事件。留空则接收所有事件。",
"event_filter_condition_remove_label": "移除条件",
"event_filter_condition_add_label": "添加条件",
- "event_filter_condition_cancel": "取消",
"event_filter_condition_ops": {
"equals": "是",
"not_equals": "不是",
@@ -365,7 +373,7 @@
"exists": "存在"
},
"event_filter_condition_path_label": "Payload 字段",
- "event_filter_condition_path_placeholder": "例如 pull_request.labels.*.name",
+ "event_filter_condition_path_placeholder": "Payload 字段,例如 pull_request.base.ref",
"event_filter_condition_op_label": "运算符",
"event_filter_condition_value_label": "值",
"event_filter_condition_value_placeholder": "例如 main",
@@ -373,6 +381,8 @@
"event_filter_condition_ignore_case": "忽略大小写",
"schedule_multiple_notice": "该自动化有 {{count}} 条时间表。关闭此弹窗,在下方「触发器」中逐条编辑。",
"webhook_multiple_notice": "该自动化有多个 Webhook。关闭此弹窗,在下方「触发器」中逐条编辑。",
+ "webhook_edit_filters": "编辑过滤",
+ "webhook_filters_saved_separately": "过滤单独保存,在这里点取消不会撤销。",
"schedule_empty": "还没有时间表——这个自动化只在手动触发时运行。",
"schedule_add": "添加时间表",
"error_title_required": "请填写自动化名称。",
@@ -387,8 +397,7 @@
"description": "静默运行,不创建任务"
}
},
- "event_filter_condition_all": "且正文满足全部条件",
- "event_filter_condition_limits": "字段路径最多 {{path}} 个字符,候选值列表最多 {{values}} 项。"
+ "event_filter_condition_all": "且正文满足全部条件"
},
"schedule_editor": {
"time_label": "时间",
diff --git a/packages/views/locales/zh-Hant/autopilots.json b/packages/views/locales/zh-Hant/autopilots.json
index c1ae47ed12..62110ea655 100644
--- a/packages/views/locales/zh-Hant/autopilots.json
+++ b/packages/views/locales/zh-Hant/autopilots.json
@@ -349,13 +349,24 @@
"webhook_created_done": "完成",
"event_filter_label": "事件過濾",
"event_filter_docs_link_label": "瞭解事件過濾的工作方式",
- "event_filter_event_placeholder": "例如 workflow_run",
- "event_filter_actions_placeholder": "completed, failed",
- "event_filter_add": "新增",
- "event_filter_remove_label": "移除過濾條件",
+ "event_filter_event_placeholder": "事件,例如 pull_request",
+ "event_filter_actions_placeholder": "動作(可選)",
+ "event_filter_add_rule": "新增規則",
+ "event_filter_event_label": "事件",
+ "event_filter_actions_label": "動作",
+ "event_filter_new_rule_label": "新規則",
+ "event_filter_condition_label": "條件",
+ "event_filter_error_event_required": "請填寫事件名稱。",
+ "event_filter_error_path_required": "請填寫本文欄位。",
+ "event_filter_error_path_invalid": "欄位名稱之間用點分隔,最多 {{path}} 個字元。",
+ "event_filter_error_value_required": "請填寫值。",
+ "event_filter_error_too_many_values": "最多 {{values}} 個值。",
+ "event_filter_remove_label": "移除規則",
"event_filter_hint": "只處理符合規則且本文符合全部條件的事件。留空則接收所有事件。",
"schedule_multiple_notice": "該自動化有 {{count}} 條時間表。關閉此彈窗,在下方「觸發器」中逐條編輯。",
"webhook_multiple_notice": "該自動化有多個 Webhook。關閉此彈窗,在下方「觸發器」中逐條編輯。",
+ "webhook_edit_filters": "編輯過濾",
+ "webhook_filters_saved_separately": "過濾單獨儲存,在這裡點取消不會復原。",
"schedule_empty": "還沒有時間表——這個自動化只在手動觸發時執行。",
"schedule_add": "新增時間表",
"error_title_required": "請填寫自動化名稱。",
@@ -372,7 +383,6 @@
},
"event_filter_condition_remove_label": "移除條件",
"event_filter_condition_add_label": "新增條件",
- "event_filter_condition_cancel": "取消",
"event_filter_condition_ops": {
"equals": "是",
"not_equals": "不是",
@@ -381,14 +391,13 @@
"exists": "存在"
},
"event_filter_condition_path_label": "本文欄位",
- "event_filter_condition_path_placeholder": "例如 pull_request.labels.*.name",
+ "event_filter_condition_path_placeholder": "本文欄位,例如 pull_request.base.ref",
"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}} 項。"
+ "event_filter_condition_all": "且本文符合全部條件"
},
"schedule_editor": {
"time_label": "時間",