Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(autopilots): webhook triggers (server + CLI + UI + docs) MUL-2049 (#2348)
Kerim Incedayi9418d2a2c193
diff --git a/.env.example b/.env.exampleindex 94858653aa..a2481e271d 100644--- a/.env.example+++ b/.env.example@@ -29,6 +29,22 @@ PORT=8080JWT_SECRET=change-me-in-productionMULTICA_SERVER_URL=ws://localhost:8080/wsMULTICA_APP_URL=http://localhost:3000+# Public URL the API is reachable at from the open internet (no trailing+# slash). Used to mint absolute webhook URLs for autopilot webhook+# triggers. Leave unset behind a same-origin reverse proxy or for plain+# localhost dev — the frontend will compose the URL from+# window.origin + webhook_path in that case. Headers are intentionally+# not used to derive this value, to avoid Host / X-Forwarded-Host+# spoofing when a self-hosted reverse proxy is not hardened.+MULTICA_PUBLIC_URL=+# Comma-separated CIDR list of reverse proxies whose X-Forwarded-For /+# X-Real-IP headers the per-IP webhook rate limiter is allowed to trust.+# Empty (the default) means "trust no headers" — the limiter uses+# r.RemoteAddr only, which is the safe shape when the backend is+# exposed directly. Set this when running behind nginx/Caddy/Cloudflare:+# e.g. "127.0.0.1/32" for a same-host reverse proxy, or the CDN's+# announced ranges for cloud deployments.+MULTICA_TRUSTED_PROXIES=MULTICA_DAEMON_CONFIG=MULTICA_WORKSPACE_ID=MULTICA_DAEMON_ID=diff --git a/apps/docs/content/docs/autopilots.mdx b/apps/docs/content/docs/autopilots.mdxindex 1e01217aaf..8987434461 100644--- a/apps/docs/content/docs/autopilots.mdx+++ b/apps/docs/content/docs/autopilots.mdx@@ -1,6 +1,6 @@---title: Autopilots-description: Let agents start work on a cron schedule — or trigger once manually via the UI or CLI.+description: Let agents start work on a cron schedule, an inbound webhook, or trigger once manually via the UI or CLI.---import { Callout } from "fumadocs-ui/components/callout";@@ -16,7 +16,7 @@ Create a new autopilot on the workspace's **Autopilot** page. You set:- **Priority** — inherited by the `task` it produces (same semantics as issue priority)- **Description / prompt** — the work description the agent receives each run- **Execution mode** — see below-- **Triggers** — at least one `schedule` (cron + timezone)+- **Triggers** — at least one `schedule` (cron + timezone) or `webhook`## Pick an execution mode@@ -50,15 +50,109 @@ multica autopilot trigger <autopilot-id>A manual trigger goes through the exact same execution flow as a `schedule` trigger — only the `source` field on the run record is marked `manual`.+## Trigger from a webhook++Autopilots can also fire on inbound HTTP webhooks. Add a **Webhook** trigger+on the autopilot detail page; Multica generates a unique URL of the shape:++```+https://<your-multica-host>/api/webhooks/autopilots/awt_…+```++POST any JSON to that URL — Multica records a run with `source = webhook`,+stores the body as the run's `trigger_payload`, and dispatches the agent+exactly the way a schedule trigger would.++```bash+curl -X POST "$MULTICA_WEBHOOK_URL" \+ -H "Content-Type: application/json" \+ -d '{"event":"demo.received","eventPayload":{"message":"hello"}}'+```++In **create issue mode**, the inbound payload is appended to the new issue's+description so the agent can read it inline. In **run-only mode**, the+payload is part of the run context the daemon hands the agent.++### Payload shape++You can send your own envelope:++```json+{ "event": "github.pull_request.opened", "eventPayload": { } }+```++…or any JSON object/array. Multica normalizes it into an internal envelope:++```json+{+ "event": "<inferred>",+ "eventPayload": <your body>,+ "request": { "receivedAt": "<rfc3339>", "contentType": "application/json" }+}+```++When you don't provide an `event` field, Multica infers it from common+headers and body fields (`X-GitHub-Event` + body `action`,+`X-Gitlab-Event`, `X-Event-Type`, body `event`/`type`/`action`). When+nothing matches, the event is `webhook.received`.++When configuring GitHub or similar sources, set the content type to+`application/json` — form-encoded webhook payloads are not accepted.++### URL is a bearer secret++The generated URL **is** the credential. Anyone with it can fire the+autopilot. Treat it like a token:++- **Don't paste it into public issue threads, screenshots, or chat history.**+- **Rotate it if it leaks** — click "Rotate URL" on the trigger row, or run+ `multica autopilot trigger-rotate-url <autopilot-id> <trigger-id>`. The+ old URL stops working immediately.+- For sources that require strong source authentication, wait for+ per-trigger HMAC signature verification; this v1 URL is bearer-only.+- Workspace members who can view the autopilot can read its webhook URLs+ for now — tighter per-role secret visibility is a follow-up.++### Status-code semantics++Multica returns `200 OK` with a `status` field for normal no-op outcomes so+your provider's webhook-retry machinery doesn't keep hammering the URL:++- `{"status":"accepted","run_id":"…","autopilot_id":"…","trigger_id":"…"}`+ — a run was dispatched.+- `{"status":"skipped","run_id":"…","reason":"agent runtime is offline at dispatch time"}`+ — the assignee's runtime is offline; recorded as a `skipped` run.+- `{"status":"ignored","reason":"trigger_disabled"}` — the trigger is disabled.+- `{"status":"ignored","reason":"autopilot_paused"}` — the autopilot is paused.+- `{"status":"ignored","reason":"autopilot_archived"}` — the autopilot is archived.++Non-2xx responses cover real failures:++- `400` — invalid JSON, scalar body, or empty body.+- `404` — unknown token (`{"error":"webhook not found"}`).+- `413` — payload exceeded 256 KiB.+- `429` — per-token rate limit exceeded (defaults to 60 req/min).++### Self-hosted: configure your public URL++When `MULTICA_PUBLIC_URL` is set on the server (e.g. `https://multica.example.com`),+the trigger response includes an absolute `webhook_url` and the UI shows a+ready-to-copy URL. Without it, the UI composes the URL from the client's+API origin — which is fine for desktop and same-origin web, but not for+custom self-hosted reverse proxies. Multica deliberately does not derive+the public host from `Host` / `X-Forwarded-Host` headers so a misconfigured+reverse proxy cannot trick the server into minting webhook URLs pointing at+an attacker-controlled host.+## View run historyEvery trigger produces a **run record**, visible on the "History" tab of the autopilot detail page:-- Trigger source (`schedule` / `manual`)+- Trigger source (`schedule` / `manual` / `webhook`)- Start time, completion time-- Status (`issue_created` / `running` / `completed` / `failed`)+- Status (`issue_created` / `running` / `completed` / `failed` / `skipped`)- The linked issue (create issue mode) or `task` (run-only mode)-- Failure reason (if failed)+- Failure reason (if failed or skipped)## What happens when an autopilot fails@@ -72,7 +166,11 @@ Why no auto-retry: autopilots are already periodic, so adding system-level retri## What's not yet available-**Webhook and API triggers are not available yet.** The autopilot trigger schema reserves `webhook` and `api` types, but **they are not wired up to any ingress route** — the UI can create triggers of either type, but they will not actually fire. Today, **only `schedule` and manual triggers are end-to-end usable.**+**API-kind triggers are not wired up.** The trigger schema reserves an `api`+kind, but no ingress route fires it; the UI shows a Deprecated badge for+existing rows and offers no copy/rotate affordances. Per-trigger HMAC+signature verification, IP allowlists, and provider-specific event presets+are tracked as follow-ups; v1 URLs are bearer-only.## Nextdiff --git a/apps/docs/content/docs/autopilots.zh.mdx b/apps/docs/content/docs/autopilots.zh.mdxindex b0335b723a..a0f68e288b 100644--- a/apps/docs/content/docs/autopilots.zh.mdx+++ b/apps/docs/content/docs/autopilots.zh.mdx@@ -1,6 +1,6 @@---title: Autopilots-description: 让智能体按 cron 定时自己开工——或通过 UI / CLI 手动触发一次。+description: 让智能体按 cron 定时自己开工,或在 webhook 到来时被触发——也可以通过 UI / CLI 手动触发一次。---import { Callout } from "fumadocs-ui/components/callout";@@ -16,7 +16,7 @@ Autopilots 让 [智能体](/agents) **按调度自动开工**——配好 cron- **优先级** — 继承给它产生的 `task`(语义同 issue 优先级)- **描述 / Prompt** — 智能体每次执行拿到的工作说明- **执行模式** — 见下节-- **触发器** — 至少加一条 `schedule`(cron + 时区)+- **触发器** — 至少加一条 `schedule`(cron + 时区)或 `webhook`## 选择执行模式@@ -50,15 +50,105 @@ multica autopilot trigger <autopilot-id>手动触发走和 `schedule` 触发完全相同的执行流程,只是运行记录里 `source` 字段标为 `manual`。+## 通过 Webhook 触发++Autopilot 也可以由入站 HTTP webhook 触发。在详情页添加一个 **Webhook**+触发器,Multica 会生成一个唯一的 URL:++```+https://<你的 Multica host>/api/webhooks/autopilots/awt_…+```++向这个 URL POST 任意 JSON——Multica 会记录一条 `source = webhook` 的+run,把请求体保存为 run 的 `trigger_payload`,然后按和 schedule 触发器+完全一致的方式派发给智能体。++```bash+curl -X POST "$MULTICA_WEBHOOK_URL" \+ -H "Content-Type: application/json" \+ -d '{"event":"demo.received","eventPayload":{"message":"hello"}}'+```++在**先建 issue 模式**下,入站 payload 会附加在新 issue 的描述里供智能体+直接读到;**直跑模式**下,payload 也会随 run 一并交给 daemon。++### Payload 形态++可以发自己的封装:++```json+{ "event": "github.pull_request.opened", "eventPayload": { } }+```++也可以直接发任意 JSON 对象 / 数组。Multica 会规范化为内部封装:++```json+{+ "event": "<推断>",+ "eventPayload": <你的 body>,+ "request": { "receivedAt": "<rfc3339>", "contentType": "application/json" }+}+```++不带 `event` 字段时,Multica 会按以下顺序从常见 header 和 body 字段+推断:`X-GitHub-Event` + body `action`,`X-Gitlab-Event`、+`X-Event-Type`、body 里的 `event` / `type` / `action`。都不命中时事件+名退化为 `webhook.received`。++配置 GitHub 之类的来源时,请把 content type 设为 `application/json`——+表单编码的 webhook payload 在 v1 里不接受。++### URL 即 bearer secret++生成的 URL **就是凭证**,谁拿到都能触发这个 Autopilot。请按 token 对待:++- **不要贴到公开 issue 评论、截图、聊天记录里。**+- **泄漏后立即重新生成**——在触发器上点"重新生成 URL",或运行+ `multica autopilot trigger-rotate-url <autopilot-id> <trigger-id>`。+ 旧 URL 立即失效。+- 对需要强来源认证的源,等 per-trigger HMAC 签名校验上线;v1 URL 仅+ bearer。+- 当前能查看 Autopilot 的工作区成员都能看到它的 webhook URL——更细的+ 权限可见性是后续工作。++### 状态码语义++正常的 no-op 路径都返回 `200 OK` 加 `status` 字段,避免外部 webhook 重试+机制反复打:++- `{"status":"accepted","run_id":"…","autopilot_id":"…","trigger_id":"…"}`+ —— 已派发一次 run。+- `{"status":"skipped","run_id":"…","reason":"agent runtime is offline at dispatch time"}`+ —— 受派智能体的 runtime 离线,记为 `skipped` run。+- `{"status":"ignored","reason":"trigger_disabled"}` —— 触发器已禁用。+- `{"status":"ignored","reason":"autopilot_paused"}` —— Autopilot 已暂停。+- `{"status":"ignored","reason":"autopilot_archived"}` —— Autopilot 已归档。++非 2xx 是真正的失败:++- `400` —— 无效 JSON、scalar body、空 body。+- `404` —— 未知 token(`{"error":"webhook not found"}`)。+- `413` —— 请求体超过 256 KiB。+- `429` —— 单 token 速率限制(默认 60 次 / 分钟)。++### 自托管:配置公开 URL++服务端设置 `MULTICA_PUBLIC_URL`(例如 `https://multica.example.com`)后,+触发器响应里会带绝对的 `webhook_url`,UI 直接显示可复制的 URL。没设+时 UI 会用客户端的 API origin 拼出 URL——desktop 和同源 web 没问题,+但自定义反向代理就不行了。Multica **故意不**从 `Host` /+`X-Forwarded-Host` header 推断公开主机,避免反代配置失误时被诱导生成+指向攻击者域名的 webhook URL。+## 看运行历史每次触发都会产生一条**运行记录**(run),可以在 Autopilot 详情页的"历史"tab 看到:-- 触发源(`schedule` / `manual`)+- 触发源(`schedule` / `manual` / `webhook`)- 开始时间、完成时间-- 状态(`issue_created` / `running` / `completed` / `failed`)+- 状态(`issue_created` / `running` / `completed` / `failed` / `skipped`)- 关联的 issue(先建 issue 模式)或 `task`(直跑模式)-- 失败原因(如果失败)+- 失败原因(失败或跳过时)## Autopilot 失败会怎样@@ -72,7 +162,10 @@ multica autopilot trigger <autopilot-id>## 暂不可用的能力-**Webhook 和 API 触发暂不可用**。Autopilot 的触发器类型在 schema 里预留了 `webhook` 和 `api` 两种,但**还没接入站路由**——UI 可以创建这两类触发器,不会真的触发。目前**只有 `schedule` 和手动触发是端到端可用的**。+**API 类型触发器尚未接入。** 触发器 schema 里保留了 `api` 类型但没有+入站路由会触发它;UI 会给已有的此类记录打 Deprecated 标签,也不显示+copy / rotate 操作。Per-trigger HMAC 签名校验、IP allowlist、按提供方+的事件预设是后续工作;v1 URL 仅 bearer。## 下一步diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.ymlindex 91fd0394e9..739f22d04d 100644--- a/docker-compose.selfhost.yml+++ b/docker-compose.selfhost.yml@@ -68,6 +68,19 @@ services:ALLOWED_EMAIL_DOMAINS: ${ALLOWED_EMAIL_DOMAINS:-}GITHUB_APP_SLUG: ${GITHUB_APP_SLUG:-}GITHUB_WEBHOOK_SECRET: ${GITHUB_WEBHOOK_SECRET:-}+ # Public URL the API is reachable at from the open internet, no+ # trailing slash. Used to mint absolute webhook URLs for autopilot+ # webhook triggers. Leave unset behind a same-origin reverse proxy+ # (e.g. plain localhost dev); the frontend will compose the URL+ # from window.origin + webhook_path in that case. Headers are+ # intentionally NOT used to derive this value, to avoid Host /+ # X-Forwarded-Host spoofing on misconfigured proxies.+ MULTICA_PUBLIC_URL: ${MULTICA_PUBLIC_URL:-}+ # Comma-separated CIDRs whose source IP is allowed to set+ # X-Forwarded-For / X-Real-IP for the webhook per-IP rate limiter.+ # Empty default = headers ignored, RemoteAddr used. Set e.g.+ # "127.0.0.1/32" when running behind a same-host reverse proxy.+ MULTICA_TRUSTED_PROXIES: ${MULTICA_TRUSTED_PROXIES:-}restart: unless-stoppedfrontend:diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex 9a1b8497f0..927aa8c752 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -62,6 +62,7 @@ describe("ApiClient", () => {});await client.updateAutopilotTrigger("ap-1", "tr-1", { enabled: false });await client.deleteAutopilotTrigger("ap-1", "tr-1");+ await client.rotateAutopilotTriggerWebhookToken("ap-1", "tr-1");const calls = fetchMock.mock.calls.map(([url, init]) => ({url,@@ -104,6 +105,10 @@ describe("ApiClient", () => {body: JSON.stringify({ enabled: false }),},{ url: "https://api.example.test/api/autopilots/ap-1/triggers/tr-1", method: "DELETE" },+ {+ url: "https://api.example.test/api/autopilots/ap-1/triggers/tr-1/rotate-webhook-token",+ method: "POST",+ },]);});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 23d708a5ea..66a371f8c6 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -1578,6 +1578,13 @@ export class ApiClient {return this.fetch(`/api/autopilots/${id}/runs?${search}`);}+ // Returns a single run including its full trigger_payload. List responses+ // omit trigger_payload to keep them small (a webhook envelope can be+ // up to 256 KiB × limit rows), so the detail view fetches via this route.+ async getAutopilotRun(autopilotId: string, runId: string): Promise<AutopilotRun> {+ return this.fetch(`/api/autopilots/${autopilotId}/runs/${runId}`);+ }+async createAutopilotTrigger(autopilotId: string, data: CreateAutopilotTriggerRequest): Promise<AutopilotTrigger> {return this.fetch(`/api/autopilots/${autopilotId}/triggers`, {method: "POST",@@ -1596,6 +1603,16 @@ export class ApiClient {await this.fetch(`/api/autopilots/${autopilotId}/triggers/${triggerId}`, { method: "DELETE" });}+ async rotateAutopilotTriggerWebhookToken(+ autopilotId: string,+ triggerId: string,+ ): Promise<AutopilotTrigger> {+ return this.fetch(+ `/api/autopilots/${autopilotId}/triggers/${triggerId}/rotate-webhook-token`,+ { method: "POST" },+ );+ }+// GitHub integrationasync getGitHubConnectURL(workspaceId: string): Promise<GitHubConnectResponse> {return this.fetch(`/api/workspaces/${workspaceId}/github/connect`);diff --git a/packages/core/autopilots/index.ts b/packages/core/autopilots/index.tsindex 753ba417b5..4af64034d2 100644--- a/packages/core/autopilots/index.ts+++ b/packages/core/autopilots/index.ts@@ -7,4 +7,6 @@ export {useCreateAutopilotTrigger,useUpdateAutopilotTrigger,useDeleteAutopilotTrigger,+ useRotateAutopilotTriggerWebhookToken,} from "./mutations";+export { buildAutopilotWebhookUrl } from "./webhook";diff --git a/packages/core/autopilots/mutations.ts b/packages/core/autopilots/mutations.tsindex 62bc86a887..6d43894aad 100644--- a/packages/core/autopilots/mutations.ts+++ b/packages/core/autopilots/mutations.ts@@ -128,3 +128,15 @@ export function useDeleteAutopilotTrigger() {},});}++export function useRotateAutopilotTriggerWebhookToken() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ mutationFn: ({ autopilotId, triggerId }: { autopilotId: string; triggerId: string }) =>+ api.rotateAutopilotTriggerWebhookToken(autopilotId, triggerId),+ onSettled: (_data, _err, vars) => {+ qc.invalidateQueries({ queryKey: autopilotKeys.detail(wsId, vars.autopilotId) });+ },+ });+}diff --git a/packages/core/autopilots/queries.ts b/packages/core/autopilots/queries.tsindex 17235b5bdd..608b951592 100644--- a/packages/core/autopilots/queries.ts+++ b/packages/core/autopilots/queries.ts@@ -8,6 +8,8 @@ export const autopilotKeys = {[...autopilotKeys.all(wsId), "detail", id] as const,runs: (wsId: string, id: string) =>[...autopilotKeys.all(wsId), "runs", id] as const,+ run: (wsId: string, autopilotId: string, runId: string) =>+ [...autopilotKeys.all(wsId), "runs", autopilotId, runId] as const,};export function autopilotListOptions(wsId: string) {@@ -32,3 +34,20 @@ export function autopilotRunsOptions(wsId: string, id: string) {select: (data) => data.runs,});}++// autopilotRunOptions fetches a single run with its full trigger_payload.+// The list endpoint (autopilotRunsOptions) omits trigger_payload to keep+// list responses small; callers (e.g. the run-detail dialog) use this+// query on demand when the user opens a run.+export function autopilotRunOptions(+ wsId: string,+ autopilotId: string,+ runId: string,+ options?: { enabled?: boolean },+) {+ return queryOptions({+ queryKey: autopilotKeys.run(wsId, autopilotId, runId),+ queryFn: () => api.getAutopilotRun(autopilotId, runId),+ enabled: options?.enabled ?? true,+ });+}diff --git a/packages/core/autopilots/webhook.test.ts b/packages/core/autopilots/webhook.test.tsnew file mode 100644index 0000000000..4463350725--- /dev/null+++ b/packages/core/autopilots/webhook.test.ts@@ -0,0 +1,73 @@+import { describe, expect, it } from "vitest";+import { buildAutopilotWebhookUrl } from "./webhook";+import type { AutopilotTrigger } from "../types";++const baseTrigger: AutopilotTrigger = {+ id: "t1",+ autopilot_id: "a1",+ kind: "webhook",+ enabled: true,+ cron_expression: null,+ timezone: null,+ next_run_at: null,+ webhook_token: "awt_abc",+ webhook_path: "/api/webhooks/autopilots/awt_abc",+ webhook_url: null,+ label: null,+ last_fired_at: null,+ created_at: "",+ updated_at: "",+};++describe("buildAutopilotWebhookUrl", () => {+ it("returns the server-provided webhook_url verbatim when present", () => {+ expect(+ buildAutopilotWebhookUrl({+ trigger: { ...baseTrigger, webhook_url: "https://custom.example/api/webhooks/autopilots/awt_abc" },+ }),+ ).toBe("https://custom.example/api/webhooks/autopilots/awt_abc");+ });++ it("composes from apiBaseUrl + webhook_path", () => {+ expect(+ buildAutopilotWebhookUrl({ trigger: baseTrigger, apiBaseUrl: "https://api.example" }),+ ).toBe("https://api.example/api/webhooks/autopilots/awt_abc");+ });++ it("strips trailing slash on apiBaseUrl", () => {+ expect(+ buildAutopilotWebhookUrl({ trigger: baseTrigger, apiBaseUrl: "https://api.example/" }),+ ).toBe("https://api.example/api/webhooks/autopilots/awt_abc");+ });++ it("falls back to currentOrigin when apiBaseUrl is empty", () => {+ expect(+ buildAutopilotWebhookUrl({+ trigger: baseTrigger,+ apiBaseUrl: "",+ currentOrigin: "https://app.example",+ }),+ ).toBe("https://app.example/api/webhooks/autopilots/awt_abc");+ });++ it("composes from token when webhook_path is missing", () => {+ expect(+ buildAutopilotWebhookUrl({+ trigger: { ...baseTrigger, webhook_path: null },+ apiBaseUrl: "https://api.example",+ }),+ ).toBe("https://api.example/api/webhooks/autopilots/awt_abc");+ });++ it("returns null for non-webhook trigger", () => {+ expect(+ buildAutopilotWebhookUrl({+ trigger: { ...baseTrigger, kind: "schedule", webhook_token: null, webhook_path: null },+ }),+ ).toBeNull();+ });++ it("returns relative path when no base or origin available", () => {+ expect(buildAutopilotWebhookUrl({ trigger: baseTrigger })).toBe("/api/webhooks/autopilots/awt_abc");+ });+});diff --git a/packages/core/autopilots/webhook.ts b/packages/core/autopilots/webhook.tsnew file mode 100644index 0000000000..4e7817a644--- /dev/null+++ b/packages/core/autopilots/webhook.ts@@ -0,0 +1,43 @@+import type { AutopilotTrigger } from "../types";++/**+ * Compose a usable absolute webhook URL for a webhook trigger.+ *+ * Resolution order:+ * 1. trigger.webhook_url — present only when MULTICA_PUBLIC_URL is set on the+ * server. This is the authoritative form when available.+ * 2. apiBaseUrl + webhook_path — desktop apps and self-host setups where the+ * server didn't mint an absolute URL but the client knows its API origin.+ * 3. currentOrigin + webhook_path — browser fallback when getBaseUrl() is+ * empty (e.g. same-origin Next.js dev).+ *+ * Returns null when the trigger has no token / path yet (a new trigger that+ * hasn't been written back to the cache, or a non-webhook trigger).+ */+export function buildAutopilotWebhookUrl(params: {+ trigger: Pick<AutopilotTrigger, "kind" | "webhook_token" | "webhook_path" | "webhook_url">;+ apiBaseUrl?: string;+ currentOrigin?: string;+}): string | null {+ const { trigger, apiBaseUrl, currentOrigin } = params;++ if (trigger.kind !== "webhook") return null;++ if (typeof trigger.webhook_url === "string" && trigger.webhook_url) {+ return trigger.webhook_url;+ }++ const path =+ (typeof trigger.webhook_path === "string" && trigger.webhook_path) ||+ (trigger.webhook_token ? `/api/webhooks/autopilots/${trigger.webhook_token}` : null);+ if (!path) return null;++ const base = stripTrailingSlash(apiBaseUrl) || stripTrailingSlash(currentOrigin);+ if (!base) return path; // last resort — relative path will still work in-browser+ return base + path;+}++function stripTrailingSlash(s: string | undefined): string {+ if (!s) return "";+ return s.endsWith("/") ? s.slice(0, -1) : s;+}diff --git a/packages/core/types/autopilot.ts b/packages/core/types/autopilot.tsindex 5c122439d1..029a31cc49 100644--- a/packages/core/types/autopilot.ts+++ b/packages/core/types/autopilot.ts@@ -4,7 +4,16 @@ export type AutopilotExecutionMode = "create_issue" | "run_only";export type AutopilotTriggerKind = "schedule" | "webhook" | "api";-export type AutopilotRunStatus = "issue_created" | "running" | "skipped" | "completed" | "failed";+// `skipped` is emitted by the backend pre-flight admission check+// (assignee runtime offline at dispatch time, MUL-1899). The frontend MUST+// handle it explicitly — falling through to a generic case used to show+// the run as still-pending which masked the no-op.+export type AutopilotRunStatus =+ | "issue_created"+ | "running"+ | "completed"+ | "failed"+ | "skipped";export type AutopilotRunSource = "schedule" | "manual" | "webhook" | "api";@@ -33,6 +42,14 @@ export interface AutopilotTrigger {timezone: string | null;next_run_at: string | null;webhook_token: string | null;+ // webhook_path is computed server-side from webhook_token (always+ // "/api/webhooks/autopilots/{token}"). Optional so older servers can be+ // talked to gracefully.+ webhook_path?: string | null;+ // webhook_url is only present when MULTICA_PUBLIC_URL is configured+ // server-side. Clients fall back to composing from getBaseUrl/origin ++ // webhook_path when this is missing.+ webhook_url?: string | null;label: string | null;last_fired_at: string | null;created_at: string;diff --git a/packages/views/autopilots/components/autopilot-detail-page.tsx b/packages/views/autopilots/components/autopilot-detail-page.tsxindex 5127fec3e1..429e618e89 100644--- a/packages/views/autopilots/components/autopilot-detail-page.tsx+++ b/packages/views/autopilots/components/autopilot-detail-page.tsx@@ -1,16 +1,23 @@"use client";import { useState } from "react";-import { Zap, Play, Clock, Plus, Trash2, CheckCircle2, XCircle, Loader2, Pencil, Ban, ChevronDown, ChevronRight } from "lucide-react";+import {+ Zap, Play, Clock, Plus, Trash2, CheckCircle2, XCircle, Loader2, Pencil,+ Ban, ChevronDown, ChevronRight,+ Webhook, Copy, Check, RotateCw,+} from "lucide-react";import { useQuery } from "@tanstack/react-query";-import { autopilotDetailOptions, autopilotRunsOptions } from "@multica/core/autopilots/queries";+import { autopilotDetailOptions, autopilotRunsOptions, autopilotRunOptions } from "@multica/core/autopilots/queries";import {useUpdateAutopilot,useDeleteAutopilot,useTriggerAutopilot,useCreateAutopilotTrigger,useDeleteAutopilotTrigger,+ useRotateAutopilotTriggerWebhookToken,} from "@multica/core/autopilots/mutations";+import { buildAutopilotWebhookUrl } from "@multica/core/autopilots";+import { api } from "@multica/core/api";import { useWorkspaceId } from "@multica/core/hooks";import { useWorkspacePaths } from "@multica/core/paths";import { useActorName } from "@multica/core/workspace/hooks";@@ -48,6 +55,7 @@ import type { AgentTask } from "@multica/core/types/agent";import { ReadonlyContent } from "../../editor";import { TranscriptButton } from "../../common/task-transcript";import { AutopilotDialog } from "./autopilot-dialog";+import { WebhookPayloadPreview } from "./webhook-payload-preview";import { useT } from "../../i18n";function formatDate(date: string): string {@@ -64,11 +72,32 @@ type RunStatus = "issue_created" | "running" | "skipped" | "completed" | "failedconst RUN_VISUAL: Record<RunStatus, { color: string; icon: typeof CheckCircle2; spin?: boolean }> = {issue_created: { color: "text-blue-500", icon: Clock },running: { color: "text-blue-500", icon: Loader2, spin: true },+ // `skipped` (admission check found the assignee runtime offline,+ // MUL-1899) is muted so it doesn't read as a failure-ratio inflator.+ // The row still shows failure_reason which carries the skip context.skipped: { color: "text-muted-foreground", icon: Ban },completed: { color: "text-emerald-500", icon: CheckCircle2 },failed: { color: "text-destructive", icon: XCircle },};+// WebhookPayloadSlot lazy-fetches the full run (incl. trigger_payload) once+// the parent dialog actually mounts this slot. The list endpoint omits+// trigger_payload to keep responses small (worst case 256 KiB × N runs),+// so the detail-on-demand fetch lives here.+function WebhookPayloadSlot({ autopilotId, runId }: { autopilotId: string; runId: string }) {+ const wsId = useWorkspaceId();+ const { data, isLoading } = useQuery(+ autopilotRunOptions(wsId, autopilotId, runId),+ );+ if (isLoading) {+ return <Skeleton className="h-9 w-full" />;+ }+ if (!data || data.trigger_payload == null) {+ return null;+ }+ return <WebhookPayloadPreview payload={data.trigger_payload} />;+}+function RunRow({ run, agentId, agentName }: { run: AutopilotRun; agentId: string; agentName: string }) {const { t } = useT("autopilots");const wsPaths = useWorkspacePaths();@@ -105,7 +134,9 @@ function RunRow({ run, agentId, agentName }: { run: AutopilotRun; agentId: strin<span className={cn("w-24 shrink-0 text-xs font-medium", visual.color)}>{t(($) => $.run_status[status])}</span>- <span className="w-16 shrink-0 text-xs text-muted-foreground capitalize">{run.source}</span>+ <span className="w-20 shrink-0 text-xs text-muted-foreground">+ {t(($) => $.run_source[run.source as "schedule" | "manual" | "webhook" | "api"]) ?? run.source}+ </span><span className="flex-1 min-w-0 text-xs text-muted-foreground truncate">{run.issue_id ? (t(($) => $.run.issue_linked)@@ -122,6 +153,11 @@ function RunRow({ run, agentId, agentName }: { run: AutopilotRun; agentId: strinagentName={agentName}isLive={run.status === "running"}title={t(($) => $.run.view_log)}+ headerSlot={+ run.source === "webhook" ? (+ <WebhookPayloadSlot autopilotId={run.autopilot_id} runId={run.id} />+ ) : undefined+ }/>)}</>@@ -214,8 +250,11 @@ function SkippedRunsGroup({function TriggerRow({ trigger, autopilotId }: { trigger: AutopilotTrigger; autopilotId: string }) {const { t } = useT("autopilots");const deleteTrigger = useDeleteAutopilotTrigger();+ const rotateToken = useRotateAutopilotTriggerWebhookToken();const [confirmOpen, setConfirmOpen] = useState(false);+ const [rotateOpen, setRotateOpen] = useState(false);const [deleting, setDeleting] = useState(false);+ const [copied, setCopied] = useState(false);const handleDelete = async () => {setDeleting(true);@@ -230,12 +269,49 @@ function TriggerRow({ trigger, autopilotId }: { trigger: AutopilotTrigger; autop}};+ const isWebhook = trigger.kind === "webhook";+ const isApi = trigger.kind === "api";+ // Resolve the URL from the server's webhook_url first, then compose+ // from the API base URL (desktop) or window.origin (web). Falls back+ // to the relative path if neither is available.+ const webhookUrl = isWebhook+ ? buildAutopilotWebhookUrl({+ trigger,+ apiBaseUrl: api.getBaseUrl(),+ currentOrigin: typeof window !== "undefined" ? window.location.origin : undefined,+ })+ : null;++ const handleCopy = async () => {+ if (!webhookUrl) return;+ try {+ await navigator.clipboard.writeText(webhookUrl);+ setCopied(true);+ toast.success(t(($) => $.trigger_row.url_copied));+ setTimeout(() => setCopied(false), 1500);+ } catch {+ toast.error(t(($) => $.trigger_row.url_copy_failed));+ }+ };++ const handleRotate = async () => {+ try {+ await rotateToken.mutateAsync({ autopilotId, triggerId: trigger.id });+ toast.success(t(($) => $.trigger_row.toast_rotated));+ setRotateOpen(false);+ } catch {+ toast.error(t(($) => $.trigger_row.toast_rotate_failed));+ }+ };++ const Icon = isWebhook ? Webhook : isApi ? Zap : Clock;+return (- <div className="flex items-center gap-3 rounded-md border px-3 py-2">- <Clock className="h-4 w-4 shrink-0 text-muted-foreground" />+ <div className="flex items-start gap-3 rounded-md border px-3 py-2">+ <Icon className="h-4 w-4 shrink-0 text-muted-foreground mt-0.5" /><div className="flex-1 min-w-0">- <div className="flex items-center gap-2">- <span className="text-sm font-medium capitalize">{trigger.kind}</span>+ <div className="flex items-center gap-2 flex-wrap">+ <span className="text-sm font-medium">{t(($) => $.trigger_kind[trigger.kind])}</span>{trigger.label && (<span className="text-xs text-muted-foreground">({trigger.label})</span>)}@@ -244,6 +320,11 @@ function TriggerRow({ trigger, autopilotId }: { trigger: AutopilotTrigger; autop{t(($) => $.trigger_row.disabled_badge)}</span>)}+ {isApi && (+ <span className="text-xs bg-muted px-1.5 py-0.5 rounded">+ {t(($) => $.trigger_row.deprecated_badge)}+ </span>+ )}</div>{trigger.cron_expression && (<div className="text-xs text-muted-foreground mt-0.5">@@ -256,6 +337,32 @@ function TriggerRow({ trigger, autopilotId }: { trigger: AutopilotTrigger; autop{t(($) => $.trigger_row.next_label, { date: formatDate(trigger.next_run_at) })}</div>)}+ {isWebhook && webhookUrl && (+ <div className="mt-1.5 flex items-center gap-1.5">+ <code className="flex-1 min-w-0 truncate rounded bg-muted px-2 py-1 text-xs font-mono text-foreground">+ {webhookUrl}+ </code>+ <Button+ size="icon"+ variant="ghost"+ className="h-7 w-7 shrink-0"+ onClick={handleCopy}+ title={t(($) => $.trigger_row.copy_url)}+ >+ {copied ? <Check className="h-3.5 w-3.5 text-emerald-500" /> : <Copy className="h-3.5 w-3.5 text-muted-foreground" />}+ </Button>+ <Button+ size="icon"+ variant="ghost"+ className="h-7 w-7 shrink-0"+ onClick={() => setRotateOpen(true)}+ title={t(($) => $.trigger_row.rotate_url)}+ disabled={rotateToken.isPending}+ >+ <RotateCw className={cn("h-3.5 w-3.5 text-muted-foreground", rotateToken.isPending && "animate-spin")} />+ </Button>+ </div>+ )}</div><Buttonsize="icon"@@ -289,6 +396,26 @@ function TriggerRow({ trigger, autopilotId }: { trigger: AutopilotTrigger; autop</AlertDialogFooter></AlertDialogContent></AlertDialog>+ <AlertDialog open={rotateOpen} onOpenChange={(v) => { if (!v && !rotateToken.isPending) setRotateOpen(false); }}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t(($) => $.trigger_row.rotate_confirm_title)}</AlertDialogTitle>+ <AlertDialogDescription>+ {t(($) => $.trigger_row.rotate_confirm_description)}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={rotateToken.isPending}>+ {t(($) => $.trigger_row.rotate_confirm_cancel)}+ </AlertDialogCancel>+ <AlertDialogAction onClick={handleRotate} disabled={rotateToken.isPending}>+ {rotateToken.isPending+ ? t(($) => $.trigger_row.rotate_in_progress)+ : t(($) => $.trigger_row.rotate_confirm_action)}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog></div>);}@@ -304,27 +431,41 @@ function AddTriggerDialog({}) {const { t } = useT("autopilots");const createTrigger = useCreateAutopilotTrigger();+ const [kind, setKind] = useState<"schedule" | "webhook">("schedule");const [config, setConfig] = useState<TriggerConfig>(getDefaultTriggerConfig);const [label, setLabel] = useState("");const [submitting, setSubmitting] = useState(false);const handleSubmit = async () => {if (submitting) return;- const cronExpr = toCronExpression(config);- if (!cronExpr.trim()) return;setSubmitting(true);try {- await createTrigger.mutateAsync({- autopilotId,- kind: "schedule",- cron_expression: cronExpr,- timezone: config.timezone || undefined,- label: label.trim() || undefined,- });+ if (kind === "schedule") {+ const cronExpr = toCronExpression(config);+ if (!cronExpr.trim()) {+ setSubmitting(false);+ return;+ }+ await createTrigger.mutateAsync({+ autopilotId,+ kind: "schedule",+ cron_expression: cronExpr,+ timezone: config.timezone || undefined,+ label: label.trim() || undefined,+ });+ toast.success(t(($) => $.add_trigger_dialog.toast_added_schedule));+ } else {+ await createTrigger.mutateAsync({+ autopilotId,+ kind: "webhook",+ label: label.trim() || undefined,+ });+ toast.success(t(($) => $.add_trigger_dialog.toast_added_webhook));+ }onOpenChange(false);+ setKind("schedule");setConfig(getDefaultTriggerConfig());setLabel("");- toast.success(t(($) => $.add_trigger_dialog.toast_added));} catch {toast.error(t(($) => $.add_trigger_dialog.toast_add_failed));} finally {@@ -337,7 +478,48 @@ function AddTriggerDialog({<DialogContent className="max-w-sm"><DialogTitle>{t(($) => $.add_trigger_dialog.title)}</DialogTitle><div className="space-y-4 pt-2">- <TriggerConfigSection config={config} onChange={setConfig} />+ <div>+ <label className="text-xs font-medium text-muted-foreground">+ {t(($) => $.add_trigger_dialog.type_label)}+ </label>+ <div className="mt-1 grid grid-cols-2 gap-1 rounded-md bg-muted p-1">+ <button+ type="button"+ onClick={() => setKind("schedule")}+ className={cn(+ "flex items-center justify-center gap-1.5 rounded px-3 py-1.5 text-sm transition-colors",+ kind === "schedule"+ ? "bg-background text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ <Clock className="h-3.5 w-3.5" />+ {t(($) => $.add_trigger_dialog.type_schedule)}+ </button>+ <button+ type="button"+ onClick={() => setKind("webhook")}+ className={cn(+ "flex items-center justify-center gap-1.5 rounded px-3 py-1.5 text-sm transition-colors",+ kind === "webhook"+ ? "bg-background text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ <Webhook className="h-3.5 w-3.5" />+ {t(($) => $.add_trigger_dialog.type_webhook)}+ </button>+ </div>+ </div>++ {kind === "schedule" ? (+ <TriggerConfigSection config={config} onChange={setConfig} />+ ) : (+ <p className="rounded-md bg-muted/50 px-3 py-2 text-xs text-muted-foreground">+ {t(($) => $.add_trigger_dialog.webhook_help)}+ </p>+ )}+<div><label className="text-xs font-medium text-muted-foreground">{t(($) => $.add_trigger_dialog.label_field)}diff --git a/packages/views/autopilots/components/autopilot-dialog.tsx b/packages/views/autopilots/components/autopilot-dialog.tsxindex 447e93dccf..25927fa2c3 100644--- a/packages/views/autopilots/components/autopilot-dialog.tsx+++ b/packages/views/autopilots/components/autopilot-dialog.tsx@@ -8,11 +8,13 @@ import {ChevronDown,ChevronRight,Clock,+ Copy,FilePlus2,Maximize2,Minimize2,Play,Rocket,+ Webhook,X as XIcon,Zap,} from "lucide-react";@@ -42,6 +44,8 @@ import {useUpdateAutopilot,useUpdateAutopilotTrigger,} from "@multica/core/autopilots/mutations";+import { buildAutopilotWebhookUrl } from "@multica/core/autopilots";+import { api } from "@multica/core/api";import type {AutopilotExecutionMode,AutopilotTrigger,@@ -264,6 +268,20 @@ export function AutopilotDialog(props: AutopilotDialogProps) {})();const [triggerConfig, setTriggerConfig] = useState<TriggerConfig>(initialCfg);+ // Trigger kind selector. Only meaningful in create mode — edit mode does+ // not support converting between kinds inline (PLAN.md calls that+ // out as "delete old, create new" rather than ambiguous in-place+ // updates), so the toggle is hidden when editing. The kind is+ // initialized from the first existing trigger so we render the right+ // panel without surprising the user.+ const initialKind: "schedule" | "webhook" = (() => {+ if (isCreate) return "schedule";+ const first = props.triggers[0];+ if (first?.kind === "webhook") return "webhook";+ return "schedule";+ })();+ const [triggerKind, setTriggerKind] = useState<"schedule" | "webhook">(initialKind);+const initialCronRef = useRef(toCronExpression(initialCfg));const initialTimezoneRef = useRef(initialCfg.timezone);const scheduleDirty =@@ -288,6 +306,12 @@ export function AutopilotDialog(props: AutopilotDialogProps) {const updateTrigger = useUpdateAutopilotTrigger();const [submitting, setSubmitting] = useState(false);+ // After a successful webhook-kind create, we don't close the dialog —+ // we swap to a confirmation state showing the freshly minted URL with+ // copy / done affordances. This avoids the "now go find your autopilot+ // and click into it to grab the URL" friction.+ const [createdWebhookTrigger, setCreatedWebhookTrigger] = useState<AutopilotTrigger | null>(null);+const canSubmit =title.trim().length > 0 && assigneeId.length > 0 && !submitting;@@ -302,19 +326,34 @@ export function AutopilotDialog(props: AutopilotDialogProps) {assignee_id: assigneeId,execution_mode: executionMode,});- let scheduleOk = true;+ let triggerOk = true;+ let webhookTrigger: AutopilotTrigger | null = null;try {- await createTrigger.mutateAsync({- autopilotId: autopilot.id,- kind: "schedule",- cron_expression: toCronExpression(triggerConfig),- timezone: triggerConfig.timezone,- });+ if (triggerKind === "webhook") {+ webhookTrigger = await createTrigger.mutateAsync({+ autopilotId: autopilot.id,+ kind: "webhook",+ });+ } else {+ await createTrigger.mutateAsync({+ autopilotId: autopilot.id,+ kind: "schedule",+ cron_expression: toCronExpression(triggerConfig),+ timezone: triggerConfig.timezone,+ });+ }} catch {- scheduleOk = false;+ triggerOk = false;+ }+ if (triggerKind === "webhook" && webhookTrigger) {+ // Stay in the dialog and surface the URL inline so the user+ // can copy it without first navigating to the detail page.+ setCreatedWebhookTrigger(webhookTrigger);+ toast.success(t(($) => $.dialog.toast_created));+ return;}onOpenChange(false);- if (scheduleOk) toast.success(t(($) => $.dialog.toast_created));+ if (triggerOk) toast.success(t(($) => $.dialog.toast_created));else toast.error(t(($) => $.dialog.toast_create_partial));} else {await updateAutopilot.mutateAsync({@@ -325,7 +364,10 @@ export function AutopilotDialog(props: AutopilotDialogProps) {execution_mode: executionMode,});let scheduleOk = true;- if (scheduleDirty && !schedulePillDisabled) {+ // Skip the schedule sync when the autopilot's first trigger is a+ // webhook — there's no cron to update there, and the schedule+ // panel isn't even rendered for webhook autopilots.+ if (triggerKind === "schedule" && scheduleDirty && !schedulePillDisabled) {const snapshottedTriggerId = firstTriggerIdRef.current;try {if (snapshottedTriggerId) {@@ -435,6 +477,16 @@ export function AutopilotDialog(props: AutopilotDialogProps) {</div></div>+ {createdWebhookTrigger ? (+ <WebhookCreatedPanel+ trigger={createdWebhookTrigger}+ onClose={() => {+ setCreatedWebhookTrigger(null);+ onOpenChange(false);+ }}+ />+ ) : (+ <>{/* Body: two columns (stacks on narrow screens via flex-wrap at container level) */}<divkey={contentKey}@@ -486,16 +538,24 @@ export function AutopilotDialog(props: AutopilotDialogProps) {<OutputModeSection mode={executionMode} onChange={setExecutionMode} />- <ScheduleSection- config={triggerConfig}- onChange={setTriggerConfig}- disabled={schedulePillDisabled}- disabledReason={- schedulePillDisabled- ? t(($) => $.dialog.schedule_disabled_reason)- : undefined- }- />+ {isCreate && (+ <TriggerKindSection kind={triggerKind} onChange={setTriggerKind} />+ )}++ {triggerKind === "schedule" ? (+ <ScheduleSection+ config={triggerConfig}+ onChange={setTriggerConfig}+ disabled={schedulePillDisabled}+ disabledReason={+ schedulePillDisabled+ ? t(($) => $.dialog.schedule_disabled_reason)+ : undefined+ }+ />+ ) : (+ <WebhookHelpSection isCreate={isCreate} />+ )}</aside></div>@@ -520,6 +580,8 @@ export function AutopilotDialog(props: AutopilotDialogProps) {</Button></div></div>+ </>+ )}</DialogContent></Dialog>);@@ -780,3 +842,169 @@ function ScheduleSection({</div>);}++// ---------------------------------------------------------------------------+// Trigger kind segmented control + webhook help section+// ---------------------------------------------------------------------------++function TriggerKindSection({+ kind,+ onChange,+}: {+ kind: "schedule" | "webhook";+ onChange: (kind: "schedule" | "webhook") => void;+}) {+ const { t } = useT("autopilots");+ return (+ <div>+ <SectionLabel>{t(($) => $.dialog.section_trigger_kind)}</SectionLabel>+ <div className="grid grid-cols-2 gap-1 rounded-md bg-muted p-1">+ <TriggerKindButton+ active={kind === "schedule"}+ onClick={() => onChange("schedule")}+ icon={<Clock className="h-3.5 w-3.5" />}+ label={t(($) => $.dialog.trigger_kind_schedule)}+ />+ <TriggerKindButton+ active={kind === "webhook"}+ onClick={() => onChange("webhook")}+ icon={<Webhook className="h-3.5 w-3.5" />}+ label={t(($) => $.dialog.trigger_kind_webhook)}+ />+ </div>+ </div>+ );+}++function TriggerKindButton({+ active,+ onClick,+ icon,+ label,+}: {+ active: boolean;+ onClick: () => void;+ icon: React.ReactNode;+ label: string;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ className={cn(+ "flex items-center justify-center gap-1.5 rounded px-3 py-1.5 text-sm transition-colors",+ active+ ? "bg-background text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {icon}+ <span>{label}</span>+ </button>+ );+}++function WebhookHelpSection({ isCreate }: { isCreate: boolean }) {+ const { t } = useT("autopilots");+ return (+ <div>+ <SectionLabel>{t(($) => $.dialog.section_webhook)}</SectionLabel>+ <p className="rounded-md border bg-background px-3 py-2 text-xs text-muted-foreground leading-relaxed">+ {isCreate+ ? t(($) => $.dialog.webhook_help_create)+ : t(($) => $.dialog.webhook_help_edit)}+ </p>+ </div>+ );+}++// ---------------------------------------------------------------------------+// Post-create state for webhook autopilots: shows the freshly minted URL+// inline so the user can copy it without leaving the dialog.+// ---------------------------------------------------------------------------++function WebhookCreatedPanel({+ trigger,+ onClose,+}: {+ trigger: AutopilotTrigger;+ onClose: () => void;+}) {+ const { t } = useT("autopilots");+ const [copied, setCopied] = useState(false);++ // Same URL composition the trigger row uses: prefer the server-provided+ // webhook_url, fall back to apiBaseUrl + webhook_path, then origin + path.+ const url =+ buildAutopilotWebhookUrl({+ trigger,+ apiBaseUrl: api.getBaseUrl(),+ currentOrigin: typeof window !== "undefined" ? window.location.origin : undefined,+ }) ?? "";++ const handleCopy = async () => {+ if (!url) return;+ try {+ await navigator.clipboard.writeText(url);+ setCopied(true);+ toast.success(t(($) => $.trigger_row.url_copied));+ setTimeout(() => setCopied(false), 1500);+ } catch {+ toast.error(t(($) => $.trigger_row.url_copy_failed));+ }+ };++ return (+ <>+ <div className="flex-1 min-h-0 overflow-y-auto px-8 py-10">+ <div className="mx-auto max-w-xl space-y-5">+ <div className="flex items-center gap-3">+ <span className="inline-flex size-9 items-center justify-center rounded-full bg-primary/15 text-primary">+ <Webhook className="size-4" />+ </span>+ <h2 className="text-lg font-semibold tracking-tight">+ {t(($) => $.dialog.webhook_created_title)}+ </h2>+ </div>+ <p className="text-sm text-muted-foreground leading-relaxed">+ {t(($) => $.dialog.webhook_created_description)}+ </p>++ <div>+ <div className="text-[11px] font-semibold tracking-[0.08em] text-muted-foreground uppercase mb-2">+ {t(($) => $.trigger_row.webhook_url_label)}+ </div>+ <div className="flex items-stretch gap-1.5">+ <code className="flex-1 min-w-0 truncate rounded-md border bg-muted px-3 py-2 text-xs font-mono text-foreground">+ {url}+ </code>+ <Button+ size="icon"+ variant="outline"+ className="h-9 w-9 shrink-0"+ onClick={handleCopy}+ title={t(($) => $.trigger_row.copy_url)}+ >+ {copied ? (+ <Check className="size-4 text-emerald-500" />+ ) : (+ <Copy className="size-4 text-muted-foreground" />+ )}+ </Button>+ </div>+ </div>++ <div className="rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-400 leading-relaxed">+ {t(($) => $.dialog.webhook_created_warning)}+ </div>+ </div>+ </div>++ <div className="flex items-center justify-end gap-3 px-5 py-3 border-t shrink-0 bg-background">+ <Button size="sm" onClick={onClose}>+ {t(($) => $.dialog.webhook_created_done)}+ </Button>+ </div>+ </>+ );+}diff --git a/packages/views/autopilots/components/webhook-payload-preview.test.tsx b/packages/views/autopilots/components/webhook-payload-preview.test.tsxnew file mode 100644index 0000000000..e6fc059961--- /dev/null+++ b/packages/views/autopilots/components/webhook-payload-preview.test.tsx@@ -0,0 +1,72 @@+import { describe, it, expect, beforeAll, vi } from "vitest";+import { screen, fireEvent } from "@testing-library/react";+import { renderWithI18n } from "../../test/i18n";+import { WebhookPayloadPreview } from "./webhook-payload-preview";++// sonner.toast is a fire-and-forget side-effect we don't want to assert on+// in these tests; stub it so the Copy button doesn't blow up on toast+// invocation.+vi.mock("sonner", () => ({+ toast: { success: vi.fn(), error: vi.fn() },+}));++// jsdom doesn't provide navigator.clipboard by default. Stub it once.+beforeAll(() => {+ Object.assign(navigator, {+ clipboard: { writeText: vi.fn().mockResolvedValue(undefined) },+ });+});++const envelope = (event: string, eventPayload: unknown, extras: Record<string, unknown> = {}) => ({+ event,+ eventPayload,+ request: { receivedAt: "2026-05-13T12:34:56Z", contentType: "application/json", ...extras },+});++describe("WebhookPayloadPreview", () => {+ it("renders the envelope event in the header", () => {+ renderWithI18n(+ <WebhookPayloadPreview+ payload={envelope("github.pull_request.opened", { number: 1 })}+ defaultOpen+ />,+ );+ expect(screen.getByText("github.pull_request.opened")).toBeInTheDocument();+ });++ it("falls back gracefully when payload is not an envelope", () => {+ renderWithI18n(+ <WebhookPayloadPreview payload={{ hello: "world" }} defaultOpen />,+ );+ // The unknown-event placeholder is the i18n key; the body should still+ // include the raw JSON so nothing is hidden.+ expect(screen.getByText(/hello/)).toBeInTheDocument();+ });++ it("truncates display when the payload exceeds 4 KiB but copies full text", async () => {+ // 5 KiB string field → stringified envelope > 4 KiB.+ const bigPayload = envelope("demo.big", { blob: "x".repeat(5 * 1024) });+ renderWithI18n(+ <WebhookPayloadPreview payload={bigPayload} defaultOpen />,+ );+ // Truncation marker (i18n) appears as a tail span — we assert by+ // partial text rather than coupling to the exact phrasing.+ expect(screen.getByText(/truncated/i)).toBeInTheDocument();++ // The visible <pre> body must NOT contain the full 5 KiB blob — it is+ // sliced to the truncate threshold.+ const pre = document.querySelector("pre");+ expect(pre).not.toBeNull();+ expect((pre!.textContent ?? "").length).toBeLessThan(5 * 1024 + 200);++ // Clicking Copy must still hand the FULL payload to the clipboard.+ fireEvent.click(screen.getByRole("button", { name: /copy/i }));+ const writeText = navigator.clipboard.writeText as ReturnType<typeof vi.fn>;+ expect(writeText).toHaveBeenCalled();+ const lastCall = writeText.mock.calls[writeText.mock.calls.length - 1];+ if (!lastCall) throw new Error("clipboard.writeText was not called");+ const written = lastCall[0] as string;+ expect(written.length).toBeGreaterThan(5 * 1024);+ expect(written).toContain("xxxxxxxx");+ });+});diff --git a/packages/views/autopilots/components/webhook-payload-preview.tsx b/packages/views/autopilots/components/webhook-payload-preview.tsxnew file mode 100644index 0000000000..ad5eb5d9f0--- /dev/null+++ b/packages/views/autopilots/components/webhook-payload-preview.tsx@@ -0,0 +1,141 @@+"use client";++import { useState, useMemo } from "react";+import { Webhook, ChevronDown, ChevronRight, Copy, Check } from "lucide-react";+import { toast } from "sonner";+import { cn } from "@multica/ui/lib/utils";+import { useT } from "../../i18n";++interface WebhookPayloadPreviewProps {+ payload: unknown;+ /** Default open vs collapsed. The dialog has limited vertical space, so+ * we collapse by default and let the user expand. */+ defaultOpen?: boolean;+}++/**+ * Renders a webhook trigger payload (the WebhookEnvelope shape produced+ * server-side by normalizeWebhookPayload) inline with the autopilot run+ * detail. Falls back gracefully when the payload isn't an envelope —+ * showing whatever JSON is there with a generic header.+ *+ * This is intentionally read-only and decoupled from any specific dialog+ * — it gets dropped into AgentTranscriptDialog's headerSlot.+ */+export function WebhookPayloadPreview({+ payload,+ defaultOpen = false,+}: WebhookPayloadPreviewProps) {+ const { t } = useT("autopilots");+ const [open, setOpen] = useState(defaultOpen);+ const [copied, setCopied] = useState(false);++ const { event, receivedAt, contentType, fullJSON, displayJSON, isTruncated } = useMemo(() => {+ let event: string | null = null;+ let eventPayload: unknown = null;+ let receivedAt: string | null = null;+ let contentType: string | null = null;+ if (payload && typeof payload === "object" && !Array.isArray(payload)) {+ const obj = payload as Record<string, unknown>;+ if (typeof obj.event === "string") event = obj.event;+ if ("eventPayload" in obj) eventPayload = obj.eventPayload;+ const req = obj.request;+ if (req && typeof req === "object") {+ const r = req as Record<string, unknown>;+ if (typeof r.receivedAt === "string") receivedAt = r.receivedAt;+ if (typeof r.contentType === "string") contentType = r.contentType;+ }+ }+ // If the payload didn't match the envelope shape (caller wrote+ // directly to trigger_payload, malformed history row, etc.), show+ // the whole thing as the eventPayload so nothing is hidden.+ if (eventPayload === null && payload !== null && payload !== undefined) {+ eventPayload = payload;+ }+ const fullJSON = JSON.stringify(eventPayload, null, 2);+ // Truncate the in-DOM string so the dialog stays responsive even when a+ // provider sent a 256 KiB envelope. The Copy button still yields the+ // full string, so the user never loses the data. 4 KiB is large enough+ // to show the envelope header + first object-level fields of a typical+ // webhook payload.+ const TRUNCATE_AT = 4096;+ const isTruncated = fullJSON.length > TRUNCATE_AT;+ const displayJSON = isTruncated ? fullJSON.slice(0, TRUNCATE_AT) : fullJSON;+ return { event, receivedAt, contentType, fullJSON, displayJSON, isTruncated };+ }, [payload]);++ const handleCopy = async (e: React.MouseEvent) => {+ e.stopPropagation();+ try {+ await navigator.clipboard.writeText(fullJSON);+ setCopied(true);+ toast.success(t(($) => $.webhook_payload.copied));+ setTimeout(() => setCopied(false), 1500);+ } catch {+ toast.error(t(($) => $.webhook_payload.copy_failed));+ }+ };++ return (+ <div className="rounded-md border bg-background">+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ className="flex w-full items-center gap-2 px-3 py-2 text-left text-xs hover:bg-accent/30 transition-colors"+ >+ <Webhook className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />+ <span className="font-medium">+ {t(($) => $.webhook_payload.label)}+ </span>+ <code className="truncate font-mono text-muted-foreground">+ {event ?? t(($) => $.webhook_payload.unknown_event)}+ </code>+ {receivedAt && (+ <span className="ml-auto shrink-0 text-muted-foreground/70">+ {receivedAt}+ </span>+ )}+ {open ? (+ <ChevronDown className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />+ ) : (+ <ChevronRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />+ )}+ </button>+ {open && (+ <div className="border-t">+ <div className="flex items-center justify-between px-3 py-1.5 text-[11px] text-muted-foreground">+ <span>+ {contentType+ ? t(($) => $.webhook_payload.content_type, { type: contentType })+ : t(($) => $.webhook_payload.payload)}+ </span>+ <button+ type="button"+ onClick={handleCopy}+ className={cn(+ "flex items-center gap-1 rounded px-2 py-0.5 hover:bg-accent transition-colors",+ )}+ >+ {copied ? (+ <Check className="h-3 w-3 text-emerald-500" />+ ) : (+ <Copy className="h-3 w-3" />+ )}+ {copied+ ? t(($) => $.webhook_payload.copied_short)+ : t(($) => $.webhook_payload.copy)}+ </button>+ </div>+ <pre className="max-h-64 overflow-auto bg-muted/40 px-3 py-2 text-xs font-mono leading-relaxed">+ {displayJSON}+ {isTruncated && (+ <span className="block pt-2 text-muted-foreground/70">+ {t(($) => $.webhook_payload.truncated_marker)}+ </span>+ )}+ </pre>+ </div>+ )}+ </div>+ );+}diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsxindex d68949241b..7f4853d012 100644--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx@@ -43,6 +43,13 @@ interface AgentTranscriptDialogProps {items: TimelineItem[];agentName: string;isLive?: boolean;+ /**+ * Optional content rendered between the header chips and the event list.+ * Used by autopilot run rows to surface the inbound webhook trigger+ * payload so it's visible regardless of whether the agent echoes it.+ * The dialog stays generic — slot content is the caller's concern.+ */+ headerSlot?: React.ReactNode;}// ─── Color mapping for timeline segments ────────────────────────────────────@@ -162,6 +169,7 @@ export function AgentTranscriptDialog({items,agentName,isLive = false,+ headerSlot,}: AgentTranscriptDialogProps) {const { t } = useT("agents");const [selectedSeq, setSelectedSeq] = useState<number | null>(null);@@ -451,6 +459,13 @@ export function AgentTranscriptDialog({</div>)}+ {/* ── Optional header slot (e.g. webhook payload preview) ── */}+ {headerSlot && (+ <div className="border-b px-4 py-3 shrink-0 bg-muted/20">+ {headerSlot}+ </div>+ )}+{/* ── Event list ─────────────────────────────────────────── */}<divref={scrollContainerRef}diff --git a/packages/views/common/task-transcript/transcript-button.tsx b/packages/views/common/task-transcript/transcript-button.tsxindex dea626be73..19afe03fa7 100644--- a/packages/views/common/task-transcript/transcript-button.tsx+++ b/packages/views/common/task-transcript/transcript-button.tsx@@ -26,6 +26,11 @@ interface TranscriptButtonProps {isLive?: boolean;className?: string;title?: string;+ /**+ * Optional content rendered above the transcript event list. Used to+ * surface autopilot webhook payloads inline with the run history.+ */+ headerSlot?: React.ReactNode;}/**@@ -41,6 +46,7 @@ export function TranscriptButton({isLive = false,className,title = "View transcript",+ headerSlot,}: TranscriptButtonProps) {const [open, setOpen] = useState(false);const [loading, setLoading] = useState(false);@@ -105,6 +111,7 @@ export function TranscriptButton({items={items}agentName={agentName}isLive={isLive}+ headerSlot={headerSlot}/>)}</>diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.jsonindex de5150ce3e..03c9261865 100644--- a/packages/views/locales/en/autopilots.json+++ b/packages/views/locales/en/autopilots.json@@ -92,7 +92,14 @@"running": "Running","skipped": "Skipped","completed": "Completed",- "failed": "Failed"+ "failed": "Failed",+ "skipped": "Skipped"+ },+ "run_source": {+ "schedule": "Schedule",+ "manual": "Manual",+ "webhook": "Webhook",+ "api": "API"},"run": {"issue_linked": "Issue linked",@@ -102,9 +109,38 @@"summary": "{{count}} skipped runs"}},+ "webhook_payload": {+ "label": "Webhook event:",+ "unknown_event": "webhook.received",+ "payload": "Payload",+ "content_type": "Content-Type: {{type}}",+ "copy": "Copy",+ "copied": "Webhook payload copied",+ "copied_short": "Copied",+ "copy_failed": "Failed to copy",+ "truncated_marker": "[truncated — click Copy to get the full payload]"+ },+ "trigger_kind": {+ "schedule": "Schedule",+ "webhook": "Webhook",+ "api": "API"+ },"trigger_row": {"disabled_badge": "Disabled",+ "deprecated_badge": "Deprecated","next_label": "Next: {{date}}",+ "webhook_url_label": "Webhook URL",+ "copy_url": "Copy URL",+ "url_copied": "Webhook URL copied",+ "url_copy_failed": "Failed to copy",+ "rotate_url": "Rotate URL",+ "rotate_confirm_title": "Rotate webhook URL",+ "rotate_confirm_description": "The current URL will stop working immediately. Any external systems calling it must be updated with the new URL. Continue?",+ "rotate_confirm_cancel": "Cancel",+ "rotate_confirm_action": "Rotate URL",+ "rotate_in_progress": "Rotating...",+ "toast_rotated": "Webhook URL rotated",+ "toast_rotate_failed": "Failed to rotate URL","toast_deleted": "Trigger deleted","toast_delete_failed": "Failed to delete trigger","delete_dialog": {@@ -117,11 +153,16 @@},"add_trigger_dialog": {"title": "Add Trigger",+ "type_label": "Type",+ "type_schedule": "Schedule",+ "type_webhook": "Webhook","label_field": "Label (optional)","label_placeholder": "e.g. Weekday morning",+ "webhook_help": "Multica will generate a webhook URL after you save. POST any JSON to it to fire this autopilot.","submit": "Add trigger","submitting": "Adding...",- "toast_added": "Trigger added",+ "toast_added_schedule": "Schedule trigger added",+ "toast_added_webhook": "Webhook trigger added","toast_add_failed": "Failed to add trigger"},"dialog": {@@ -153,6 +194,16 @@"select_agent": "Select agent","section_output_mode": "Output mode","section_schedule": "Schedule",+ "section_trigger_kind": "Trigger",+ "trigger_kind_schedule": "Schedule",+ "trigger_kind_webhook": "Webhook",+ "section_webhook": "Webhook",+ "webhook_help_create": "Multica will generate a webhook URL after this autopilot is created. POST any JSON to that URL to fire it.",+ "webhook_help_edit": "This autopilot is fired by webhook. Manage the URL (copy / rotate) on the autopilot's detail page.",+ "webhook_created_title": "Webhook autopilot ready",+ "webhook_created_description": "POST any JSON to the URL below and the autopilot will fire. Copy it now — you can also find and rotate it on the autopilot's detail page.",+ "webhook_created_warning": "Treat this URL like a password. Anyone who has it can trigger the autopilot.",+ "webhook_created_done": "Done","schedule_disabled_reason": "This autopilot has multiple schedules — edit them in the detail page.","next_run_label": "Next run:","output_modes": {diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.jsonindex 43fcc29cc0..a8ced69351 100644--- a/packages/views/locales/zh-Hans/autopilots.json+++ b/packages/views/locales/zh-Hans/autopilots.json@@ -92,7 +92,14 @@"running": "运行中","skipped": "已跳过","completed": "已完成",- "failed": "失败"+ "failed": "失败",+ "skipped": "已跳过"+ },+ "run_source": {+ "schedule": "时间表",+ "manual": "手动",+ "webhook": "Webhook",+ "api": "API"},"run": {"issue_linked": "已关联 issue",@@ -102,9 +109,38 @@"summary": "{{count}} 条跳过的运行"}},+ "webhook_payload": {+ "label": "Webhook 事件:",+ "unknown_event": "webhook.received",+ "payload": "Payload",+ "content_type": "Content-Type:{{type}}",+ "copy": "复制",+ "copied": "已复制 Webhook payload",+ "copied_short": "已复制",+ "copy_failed": "复制失败",+ "truncated_marker": "[已截断 — 点击「复制」获取完整 payload]"+ },+ "trigger_kind": {+ "schedule": "时间表",+ "webhook": "Webhook",+ "api": "API"+ },"trigger_row": {"disabled_badge": "已禁用",+ "deprecated_badge": "已弃用","next_label": "下次:{{date}}",+ "webhook_url_label": "Webhook URL",+ "copy_url": "复制 URL",+ "url_copied": "已复制 Webhook URL",+ "url_copy_failed": "复制失败",+ "rotate_url": "重新生成 URL",+ "rotate_confirm_title": "重新生成 Webhook URL",+ "rotate_confirm_description": "当前 URL 将立即失效。所有调用它的外部系统都需要更新为新 URL。继续吗?",+ "rotate_confirm_cancel": "取消",+ "rotate_confirm_action": "重新生成",+ "rotate_in_progress": "生成中...",+ "toast_rotated": "Webhook URL 已重新生成",+ "toast_rotate_failed": "重新生成 URL 失败","toast_deleted": "已删除触发器","toast_delete_failed": "删除触发器失败","delete_dialog": {@@ -117,11 +153,16 @@},"add_trigger_dialog": {"title": "添加触发器",+ "type_label": "类型",+ "type_schedule": "时间表",+ "type_webhook": "Webhook","label_field": "标签(可选)","label_placeholder": "例如:工作日早晨",+ "webhook_help": "保存后 Multica 会生成一个 Webhook URL。向它 POST 任意 JSON 即可触发本自动化。","submit": "添加触发器","submitting": "添加中...",- "toast_added": "已添加触发器",+ "toast_added_schedule": "已添加时间表触发器",+ "toast_added_webhook": "已添加 Webhook 触发器","toast_add_failed": "添加触发器失败"},"dialog": {@@ -153,6 +194,16 @@"select_agent": "选择智能体","section_output_mode": "输出模式","section_schedule": "时间表",+ "section_trigger_kind": "触发方式",+ "trigger_kind_schedule": "时间表",+ "trigger_kind_webhook": "Webhook",+ "section_webhook": "Webhook",+ "webhook_help_create": "Autopilot 创建后 Multica 会生成一个 Webhook URL。向它 POST 任意 JSON 即可触发。",+ "webhook_help_edit": "该 Autopilot 由 Webhook 触发。请在详情页复制或重新生成 URL。",+ "webhook_created_title": "Webhook Autopilot 已就绪",+ "webhook_created_description": "向下方的 URL POST 任意 JSON 即可触发该 Autopilot。请立即复制——之后也能在 Autopilot 详情页查看或重新生成。",+ "webhook_created_warning": "请把该 URL 当作密码对待,任何拿到它的人都能触发该 Autopilot。",+ "webhook_created_done": "完成","schedule_disabled_reason": "该自动化有多个时间表——请到详情页编辑。","next_run_label": "下次运行:","output_modes": {diff --git a/server/cmd/multica/cmd_autopilot.go b/server/cmd/multica/cmd_autopilot.goindex 3193391d16..28d770f51a 100644--- a/server/cmd/multica/cmd_autopilot.go+++ b/server/cmd/multica/cmd_autopilot.go@@ -1,6 +1,7 @@package mainimport (+ "bufio""context""fmt""net/url"@@ -68,7 +69,7 @@ var autopilotRunsCmd = &cobra.Command{var autopilotTriggerAddCmd = &cobra.Command{Use: "trigger-add <autopilot-id>",- Short: "Add a schedule trigger to an autopilot",+ Short: "Add a schedule or webhook trigger to an autopilot",Args: exactArgs(1),RunE: runAutopilotTriggerAdd,}@@ -87,6 +88,13 @@ var autopilotTriggerDeleteCmd = &cobra.Command{RunE: runAutopilotTriggerDelete,}+var autopilotTriggerRotateURLCmd = &cobra.Command{+ Use: "trigger-rotate-url <autopilot-id> <trigger-id>",+ Short: "Rotate the webhook URL of a webhook trigger",+ Args: exactArgs(2),+ RunE: runAutopilotTriggerRotateURL,+}+func init() {autopilotCmd.AddCommand(autopilotListCmd)autopilotCmd.AddCommand(autopilotGetCmd)@@ -98,6 +106,7 @@ func init() {autopilotCmd.AddCommand(autopilotTriggerAddCmd)autopilotCmd.AddCommand(autopilotTriggerUpdateCmd)autopilotCmd.AddCommand(autopilotTriggerDeleteCmd)+ autopilotCmd.AddCommand(autopilotTriggerRotateURLCmd)// listautopilotListCmd.Flags().String("status", "", "Filter by status (active, paused)")@@ -139,12 +148,17 @@ func init() {autopilotRunsCmd.Flags().Int("offset", 0, "Pagination offset")autopilotRunsCmd.Flags().String("output", "table", "Output format: table or json")- // trigger-add — only schedule triggers are supported end-to-end today- autopilotTriggerAddCmd.Flags().String("cron", "", "Cron expression (required)")- autopilotTriggerAddCmd.Flags().String("timezone", "", "IANA timezone (default UTC)")+ // trigger-add — supports schedule and webhook+ autopilotTriggerAddCmd.Flags().String("kind", "schedule", "Trigger kind: schedule or webhook")+ autopilotTriggerAddCmd.Flags().String("cron", "", "Cron expression (required for --kind schedule)")+ autopilotTriggerAddCmd.Flags().String("timezone", "", "IANA timezone (default UTC; schedule only)")autopilotTriggerAddCmd.Flags().String("label", "", "Optional human-readable label")autopilotTriggerAddCmd.Flags().String("output", "json", "Output format: table or json")+ // trigger-rotate-url — webhook only+ autopilotTriggerRotateURLCmd.Flags().String("output", "json", "Output format: table or json")+ autopilotTriggerRotateURLCmd.Flags().BoolP("yes", "y", false, "Skip the interactive confirmation prompt")+// trigger-updateautopilotTriggerUpdateCmd.Flags().Bool("enabled", true, "Enable or disable the trigger")autopilotTriggerUpdateCmd.Flags().String("cron", "", "New cron expression")@@ -502,21 +516,32 @@ func runAutopilotTriggerAdd(cmd *cobra.Command, args []string) error {return err}- // Only schedule triggers are dispatched end-to-end today. The server- // schema also defines "webhook" and "api" kinds, but no inbound endpoint- // fires them — they'd sit in the DB forever. Re-add kind selection here- // when those paths are implemented.+ kind, _ := cmd.Flags().GetString("kind")+ if kind == "" {+ kind = "schedule"+ }+ if kind != "schedule" && kind != "webhook" {+ return fmt.Errorf("--kind must be schedule or webhook")+ }cron, _ := cmd.Flags().GetString("cron")- if cron == "" {- return fmt.Errorf("--cron is required")+ if kind == "schedule" && cron == "" {+ return fmt.Errorf("--cron is required for --kind schedule")}-- body := map[string]any{- "kind": "schedule",- "cron_expression": cron,+ if kind == "webhook" {+ if v, _ := cmd.Flags().GetString("timezone"); v != "" {+ return fmt.Errorf("--timezone is only valid with --kind schedule")+ }+ if cron != "" {+ return fmt.Errorf("--cron is only valid with --kind schedule")+ }}- if v, _ := cmd.Flags().GetString("timezone"); v != "" {- body["timezone"] = v++ body := map[string]any{"kind": kind}+ if kind == "schedule" {+ body["cron_expression"] = cron+ if v, _ := cmd.Flags().GetString("timezone"); v != "" {+ body["timezone"] = v+ }}if v, _ := cmd.Flags().GetString("label"); v != "" {body["label"] = v@@ -540,6 +565,72 @@ func runAutopilotTriggerAdd(cmd *cobra.Command, args []string) error {return cli.PrintJSON(os.Stdout, result)}fmt.Printf("Trigger created: %s (kind=%s)\n", strVal(result, "id"), strVal(result, "kind"))+ if kind == "webhook" {+ printWebhookURL(client, result)+ }+ return nil+}++// printWebhookURL emits the webhook URL with the priority webhook_url >+// composed-from-base. Keeps the table-output flow useful — without this the+// table renderer drops the most important new piece of information.+func printWebhookURL(client *cli.APIClient, trigger map[string]any) {+ if u := strVal(trigger, "webhook_url"); u != "" {+ fmt.Printf("Webhook URL: %s\n", u)+ return+ }+ if path := strVal(trigger, "webhook_path"); path != "" {+ base := strings.TrimRight(client.BaseURL, "/")+ fmt.Printf("Webhook URL: %s%s\n", base, path)+ }+}++func runAutopilotTriggerRotateURL(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }++ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()++ autopilotRef, err := resolveAutopilotID(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve autopilot: %w", err)+ }+ triggerRef, err := resolveAutopilotTriggerID(ctx, client, autopilotRef.ID, args[1])+ if err != nil {+ return fmt.Errorf("resolve trigger: %w", err)+ }++ // Confirmation: rotation invalidates the current URL immediately. The UI+ // version uses an AlertDialog; the CLI mirrors that with a y/N prompt+ // unless --yes was passed for scripted use. Style matches confirmOverwrite+ // in cmd_setup.go.+ yes, _ := cmd.Flags().GetBool("yes")+ if !yes {+ fmt.Fprintln(os.Stderr, "This will invalidate the current webhook URL immediately. Continue? [y/N] ")+ reader := bufio.NewReader(os.Stdin)+ answer, _ := reader.ReadString('\n')+ answer = strings.TrimSpace(strings.ToLower(answer))+ if answer != "y" && answer != "yes" {+ fmt.Fprintln(os.Stderr, "Aborted.")+ return nil+ }+ }++ var result map[string]any+ path := "/api/autopilots/" + autopilotRef.ID + "/triggers/" + triggerRef.ID + "/rotate-webhook-token"+ if err := client.PostJSON(ctx, path, nil, &result); err != nil {+ return fmt.Errorf("rotate webhook url: %w", err)+ }++ output, _ := cmd.Flags().GetString("output")+ if output == "json" {+ return cli.PrintJSON(os.Stdout, result)+ }+ fmt.Printf("Webhook URL rotated for trigger %s\n", strVal(result, "id"))+ printWebhookURL(client, result)return nil}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex d1df209e3e..8fe6a1ee90 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2,7 +2,9 @@ package mainimport ("context"+ "log/slog""net/http"+ "net/netip""os""strings""time"@@ -57,6 +59,33 @@ func allowedOrigins() []string {return origins}+// parseTrustedProxies parses a comma-separated list of CIDR prefixes from the+// MULTICA_TRUSTED_PROXIES env var. Invalid entries are dropped with a single+// warn-line per entry rather than crashing the server — a typo in one CIDR+// shouldn't take the whole API down. Returns nil for empty input, which the+// rate limiter treats as "trust no proxy headers, use RemoteAddr only".+func parseTrustedProxies(raw string) []netip.Prefix {+ raw = strings.TrimSpace(raw)+ if raw == "" {+ return nil+ }+ var out []netip.Prefix+ for _, part := range strings.Split(raw, ",") {+ s := strings.TrimSpace(part)+ if s == "" {+ continue+ }+ p, err := netip.ParsePrefix(s)+ if err != nil {+ slog.Warn("MULTICA_TRUSTED_PROXIES: ignoring invalid CIDR",+ "value", s, "error", err)+ continue+ }+ out = append(out, p)+ }+ return out+}+// NewRouter creates the fully-configured Chi router with all middleware and routes.// rdb is optional: when non-nil the runtime local-skill request stores are// swapped for Redis-backed implementations so multiple API nodes share the@@ -107,6 +136,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.BusAllowedEmailDomains: splitAndTrim(os.Getenv("ALLOWED_EMAIL_DOMAINS")),UseDailyRollupForRuntimeUsage: os.Getenv("USAGE_DAILY_ROLLUP_ENABLED") == "true",UseDailyRollupForDashboard: os.Getenv("USAGE_DASHBOARD_ROLLUP_ENABLED") == "true",+ PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("MULTICA_PUBLIC_URL")), "/"),+ TrustedProxies: parseTrustedProxies(os.Getenv("MULTICA_TRUSTED_PROXIES")),}h := handler.New(queries, pool, hub, bus, emailSvc, store, cfSigner, analyticsClient, signupConfig, daemonHub)if opts.DaemonWakeup != nil {@@ -118,6 +149,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bush.LocalSkillListStore = handler.NewRedisLocalSkillListStore(rdb)h.LocalSkillImportStore = handler.NewRedisLocalSkillImportStore(rdb)h.LivenessStore = handler.NewRedisLivenessStore(rdb)+ h.WebhookRateLimiter = handler.NewRedisWebhookRateLimiter(rdb, handler.DefaultWebhookRateLimit())+ h.WebhookIPRateLimiter = handler.NewRedisWebhookIPRateLimiter(rdb, handler.DefaultWebhookIPRateLimit())}if opts.HeartbeatScheduler != nil {h.HeartbeatScheduler = opts.HeartbeatScheduler@@ -214,6 +247,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Public APIr.Get("/api/config", h.GetConfig)+ // Webhook ingress for autopilots. Outside the authenticated group on+ // purpose: the bearer token in the URL path IS the credential. Workspace+ // context is derived from the trigger row, never from request headers.+ r.Post("/api/webhooks/autopilots/{token}", h.HandleAutopilotWebhook)// GitHub App webhook (no Multica auth — requests are authenticated via// HMAC-SHA256 signature in the handler) and post-install setup callback.r.Post("/api/webhooks/github", h.HandleGitHubWebhook)@@ -421,10 +458,12 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Delete("/", h.DeleteAutopilot)r.Post("/trigger", h.TriggerAutopilot)r.Get("/runs", h.ListAutopilotRuns)+ r.Get("/runs/{runId}", h.GetAutopilotRun)r.Post("/triggers", h.CreateAutopilotTrigger)r.Route("/triggers/{triggerId}", func(r chi.Router) {r.Patch("/", h.UpdateAutopilotTrigger)r.Delete("/", h.DeleteAutopilotTrigger)+ r.Post("/rotate-webhook-token", h.RotateAutopilotTriggerWebhookToken)})})})diff --git a/server/cmd/server/trusted_proxies_test.go b/server/cmd/server/trusted_proxies_test.gonew file mode 100644index 0000000000..b7a1c75c2f--- /dev/null+++ b/server/cmd/server/trusted_proxies_test.go@@ -0,0 +1,76 @@+package main++import (+ "net/netip"+ "testing"+)++func TestParseTrustedProxies(t *testing.T) {+ t.Parallel()++ cases := []struct {+ name string+ in string+ want []string // expressed as String() forms to keep the test readable+ }{+ {"empty", "", nil},+ {"whitespace only", " \t ", nil},+ {"one CIDR", "10.0.0.0/8", []string{"10.0.0.0/8"}},+ {"multiple CIDRs", "10.0.0.0/8, 127.0.0.1/32 ,::1/128", []string{"10.0.0.0/8", "127.0.0.1/32", "::1/128"}},+ {"invalid entries dropped", "10.0.0.0/8, not-a-cidr , 192.168.0.0/16", []string{"10.0.0.0/8", "192.168.0.0/16"}},+ {"all invalid → nil", "garbage, also-garbage", nil},+ {"empty entries skipped", ",10.0.0.0/8,,", []string{"10.0.0.0/8"}},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := parseTrustedProxies(tc.in)+ var gotStr []string+ for _, p := range got {+ gotStr = append(gotStr, p.String())+ }+ if !sliceEq(gotStr, tc.want) {+ t.Fatalf("parseTrustedProxies(%q) = %v, want %v", tc.in, gotStr, tc.want)+ }+ })+ }+}++func TestParseTrustedProxies_PrefixesAreUsable(t *testing.T) {+ // Make sure the returned prefixes actually do containment checks+ // correctly — guards against returning malformed netip.Prefix values+ // that would silently never match.+ got := parseTrustedProxies("10.0.0.0/8,127.0.0.1/32")+ tests := []struct {+ addr string+ want bool+ }{+ {"10.1.2.3", true},+ {"127.0.0.1", true},+ {"203.0.113.5", false},+ }+ for _, tc := range tests {+ addr := netip.MustParseAddr(tc.addr)+ var hit bool+ for _, p := range got {+ if p.Contains(addr) {+ hit = true+ break+ }+ }+ if hit != tc.want {+ t.Errorf("contains(%s) = %v, want %v", tc.addr, hit, tc.want)+ }+ }+}++func sliceEq(a, b []string) bool {+ if len(a) != len(b) {+ return false+ }+ for i := range a {+ if a[i] != b[i] {+ return false+ }+ }+ return true+}diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.goindex 94dafb8b35..d3e865b0a9 100644--- a/server/internal/handler/autopilot.go+++ b/server/internal/handler/autopilot.go@@ -3,6 +3,7 @@ package handlerimport ("encoding/json""errors"+ "fmt""io""net/http""strconv"@@ -48,10 +49,18 @@ type AutopilotTriggerResponse struct {Timezone *string `json:"timezone"`NextRunAt *string `json:"next_run_at"`WebhookToken *string `json:"webhook_token"`- Label *string `json:"label"`- LastFiredAt *string `json:"last_fired_at"`- CreatedAt string `json:"created_at"`- UpdatedAt string `json:"updated_at"`+ // WebhookPath is computed from webhook_token. Always present for webhook+ // triggers; nil for schedule/api. Not stored — see triggerToResponse.+ WebhookPath *string `json:"webhook_path"`+ // WebhookURL is the absolute URL composed from the server's+ // MULTICA_PUBLIC_URL setting. Nil when the server has no public URL+ // configured; clients then build the URL themselves from webhook_path+ // plus their API base / current origin.+ WebhookURL *string `json:"webhook_url"`+ Label *string `json:"label"`+ LastFiredAt *string `json:"last_fired_at"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`}type AutopilotRunResponse struct {@@ -90,8 +99,8 @@ func autopilotToResponse(a db.Autopilot) AutopilotResponse {}}-func triggerToResponse(t db.AutopilotTrigger) AutopilotTriggerResponse {- return AutopilotTriggerResponse{+func (h *Handler) triggerToResponse(t db.AutopilotTrigger) AutopilotTriggerResponse {+ resp := AutopilotTriggerResponse{ID: uuidToString(t.ID),AutopilotID: uuidToString(t.AutopilotID),Kind: t.Kind,@@ -105,6 +114,22 @@ func triggerToResponse(t db.AutopilotTrigger) AutopilotTriggerResponse {CreatedAt: timestampToString(t.CreatedAt),UpdatedAt: timestampToString(t.UpdatedAt),}+ if t.Kind == "webhook" && t.WebhookToken.Valid && t.WebhookToken.String != "" {+ path := webhookPathForToken(t.WebhookToken.String)+ resp.WebhookPath = &path+ if h.cfg.PublicURL != "" {+ full := h.cfg.PublicURL + path+ resp.WebhookURL = &full+ }+ }+ return resp+}++// webhookPathForToken composes the path used by the public ingress route.+// Kept as a free function (no Handler receiver) so test code that builds+// expected URLs without instantiating a Handler can call it.+func webhookPathForToken(token string) string {+ return "/api/webhooks/autopilots/" + token}func runToResponse(r db.AutopilotRun) AutopilotRunResponse {@@ -133,6 +158,17 @@ func runToResponse(r db.AutopilotRun) AutopilotRunResponse {}}+// runToResponseSlim mirrors runToResponse but omits TriggerPayload, intended+// for list endpoints where echoing the full webhook envelope (up to+// 256 KiB × N rows) would dominate response size. Clients fetch the full+// payload via GET /api/autopilots/{id}/runs/{runId} when the user opens+// the run detail dialog.+func runToResponseSlim(r db.AutopilotRun) AutopilotRunResponse {+ resp := runToResponse(r)+ resp.TriggerPayload = nil+ return resp+}+// ── Request types ───────────────────────────────────────────────────────────type CreateAutopilotRequest struct {@@ -210,7 +246,7 @@ func (h *Handler) GetAutopilot(w http.ResponseWriter, r *http.Request) {}triggerResp := make([]AutopilotTriggerResponse, len(triggers))for i, t := range triggers {- triggerResp[i] = triggerToResponse(t)+ triggerResp[i] = h.triggerToResponse(t)}writeJSON(w, http.StatusOK, map[string]any{@@ -440,14 +476,26 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)writeError(w, http.StatusBadRequest, "kind is required")return}- if req.Kind != "schedule" && req.Kind != "webhook" && req.Kind != "api" {- writeError(w, http.StatusBadRequest, "kind must be schedule, webhook, or api")+ if req.Kind != "schedule" && req.Kind != "webhook" {+ // "api" kind is deprecated: it was reserved-but-inert (no scheduler,+ // no ingress route), and the only way to actually fire one was via+ // the manual /trigger endpoint — which already works regardless of+ // trigger kind. Surface stragglers with 400 so callers move to+ // schedule or webhook.+ writeError(w, http.StatusBadRequest, "kind must be schedule or webhook")return}if req.Kind == "schedule" && (req.CronExpression == nil || *req.CronExpression == "") {writeError(w, http.StatusBadRequest, "cron_expression is required for schedule triggers")return}+ if req.Kind == "webhook" && req.Timezone != nil && *req.Timezone != "" {+ // Webhook triggers fire on demand from external POSTs — they have no+ // next_run_at to compute, so a timezone is meaningless. Reject loudly+ // instead of silently dropping the field.+ writeError(w, http.StatusBadRequest, "timezone is not valid for webhook triggers")+ return+ }if req.Timezone != nil && *req.Timezone != "" {if err := service.ValidateTimezone(*req.Timezone); err != nil {@@ -456,8 +504,18 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)}}- var nextRunAt pgtype.Timestamptz- if req.Kind == "schedule" && req.CronExpression != nil {+ // kind-specific normalization. Webhook triggers ignore cron/timezone/+ // next_run_at — they're fired on demand.+ var (+ nextRunAt pgtype.Timestamptz+ cronText pgtype.Text+ tzText pgtype.Text+ webhookToken pgtype.Text+ )+ switch req.Kind {+ case "schedule":+ cronText = ptrToText(req.CronExpression)+ tzText = ptrToText(req.Timezone)tz := "UTC"if req.Timezone != nil && *req.Timezone != "" {tz = *req.Timezone@@ -468,23 +526,44 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)return}nextRunAt = pgtype.Timestamptz{Time: t, Valid: true}+ case "webhook":+ // Mint the token BEFORE the INSERT so the row never exists in a+ // half-written kind=webhook + webhook_token=NULL state. If the+ // random token happens to collide with an existing unique-index+ // entry (vanishingly unlikely with 256 bits but the retry keeps+ // the failure mode obvious if RNG is degraded), we re-generate+ // and re-INSERT — never UPDATE.+ trigger, err := h.createWebhookTriggerWithMintedToken(r, ap.ID, ptrToText(req.Label))+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to create trigger")+ return+ }+ resp := h.triggerToResponse(trigger)+ userID, _ := requireUserID(w, r)+ h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", userID, map[string]any{+ "autopilot_id": uuidToString(ap.ID),+ "trigger": resp,+ })+ writeJSON(w, http.StatusCreated, resp)+ return}trigger, err := h.Queries.CreateAutopilotTrigger(r.Context(), db.CreateAutopilotTriggerParams{AutopilotID: ap.ID,Kind: req.Kind,Enabled: true,- CronExpression: ptrToText(req.CronExpression),- Timezone: ptrToText(req.Timezone),+ CronExpression: cronText,+ Timezone: tzText,NextRunAt: nextRunAt,Label: ptrToText(req.Label),+ WebhookToken: webhookToken,})if err != nil {writeError(w, http.StatusInternalServerError, "failed to create trigger")return}- resp := triggerToResponse(trigger)+ resp := h.triggerToResponse(trigger)userID, _ := requireUserID(w, r)h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", userID, map[string]any{"autopilot_id": uuidToString(ap.ID),@@ -493,6 +572,41 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)writeJSON(w, http.StatusCreated, resp)}+// createWebhookTriggerWithMintedToken atomically creates a webhook trigger+// with a freshly minted bearer token in the same INSERT. Avoids the older+// two-step (INSERT then UPDATE webhook_token) pattern which could leave a+// kind=webhook row with NULL webhook_token visible in the UI if the second+// statement failed.+//+// Retries on the unique-index collision case so a vanishingly-rare RNG+// collision turns into a clean retry rather than a 500.+func (h *Handler) createWebhookTriggerWithMintedToken(+ r *http.Request,+ autopilotID pgtype.UUID,+ label pgtype.Text,+) (db.AutopilotTrigger, error) {+ for attempt := 0; attempt < 3; attempt++ {+ token, err := generateWebhookToken()+ if err != nil {+ return db.AutopilotTrigger{}, err+ }+ trigger, err := h.Queries.CreateAutopilotTrigger(r.Context(), db.CreateAutopilotTriggerParams{+ AutopilotID: autopilotID,+ Kind: "webhook",+ Enabled: true,+ Label: label,+ WebhookToken: pgtype.Text{String: token, Valid: true},+ })+ if err == nil {+ return trigger, nil+ }+ if !isUniqueViolation(err) {+ return db.AutopilotTrigger{}, err+ }+ }+ return db.AutopilotTrigger{}, fmt.Errorf("could not mint unique webhook token")+}+func (h *Handler) UpdateAutopilotTrigger(w http.ResponseWriter, r *http.Request) {autopilotID := chi.URLParam(r, "id")triggerID := chi.URLParam(r, "triggerId")@@ -520,6 +634,21 @@ func (h *Handler) UpdateAutopilotTrigger(w http.ResponseWriter, r *http.Request)return}+ // Kind-specific validation. Mirrors the create-path discipline: cron+ // and timezone only make sense on schedule triggers, so reject loudly+ // rather than persisting fields that no code path reads. enabled and+ // label remain valid on every kind.+ if prev.Kind != "schedule" {+ if req.CronExpression != nil {+ writeError(w, http.StatusBadRequest, "cron_expression is only valid for schedule triggers")+ return+ }+ if req.Timezone != nil {+ writeError(w, http.StatusBadRequest, "timezone is only valid for schedule triggers")+ return+ }+ }+params := db.UpdateAutopilotTriggerParams{ID: prev.ID,CronExpression: prev.CronExpression,@@ -573,7 +702,7 @@ func (h *Handler) UpdateAutopilotTrigger(w http.ResponseWriter, r *http.Request)return}- resp := triggerToResponse(trigger)+ resp := h.triggerToResponse(trigger)userID, _ := requireUserID(w, r)h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", userID, map[string]any{"autopilot_id": uuidToString(ap.ID),@@ -631,6 +760,67 @@ func (h *Handler) DeleteAutopilotTrigger(w http.ResponseWriter, r *http.Request)w.WriteHeader(http.StatusNoContent)}+// RotateAutopilotTriggerWebhookToken issues a fresh bearer token for an+// existing webhook trigger. The old token stops working immediately because+// the unique-index lookup in the public ingress route is keyed on the+// current row value.+func (h *Handler) RotateAutopilotTriggerWebhookToken(w http.ResponseWriter, r *http.Request) {+ autopilotID := chi.URLParam(r, "id")+ triggerID := chi.URLParam(r, "triggerId")+ workspaceID := h.resolveWorkspaceID(r)++ ap, ok := h.loadAutopilotInWorkspace(w, r, autopilotID, workspaceID)+ if !ok {+ return+ }++ triggerUUID, ok := parseUUIDOrBadRequest(w, triggerID, "trigger id")+ if !ok {+ return+ }+ prev, err := h.Queries.GetAutopilotTrigger(r.Context(), triggerUUID)+ if err != nil || uuidToString(prev.AutopilotID) != uuidToString(ap.ID) {+ writeError(w, http.StatusNotFound, "trigger not found")+ return+ }+ if prev.Kind != "webhook" {+ writeError(w, http.StatusBadRequest, "trigger is not a webhook trigger")+ return+ }++ var rotated db.AutopilotTrigger+ for attempt := 0; attempt < 3; attempt++ {+ token, terr := generateWebhookToken()+ if terr != nil {+ writeError(w, http.StatusInternalServerError, "failed to generate webhook token")+ return+ }+ rotated, err = h.Queries.RotateAutopilotTriggerWebhookToken(r.Context(), db.RotateAutopilotTriggerWebhookTokenParams{+ ID: triggerUUID,+ WebhookToken: pgtype.Text{String: token, Valid: true},+ })+ if err == nil {+ break+ }+ if !isUniqueViolation(err) {+ writeError(w, http.StatusInternalServerError, "failed to rotate webhook token")+ return+ }+ }+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to rotate webhook token")+ return+ }++ resp := h.triggerToResponse(rotated)+ userID, _ := requireUserID(w, r)+ h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", userID, map[string]any{+ "autopilot_id": uuidToString(ap.ID),+ "trigger": resp,+ })+ writeJSON(w, http.StatusOK, resp)+}+// ── Runs ────────────────────────────────────────────────────────────────────func (h *Handler) ListAutopilotRuns(w http.ResponseWriter, r *http.Request) {@@ -670,11 +860,50 @@ func (h *Handler) ListAutopilotRuns(w http.ResponseWriter, r *http.Request) {resp := make([]AutopilotRunResponse, len(runs))for i, run := range runs {- resp[i] = runToResponse(run)+ // Omit trigger_payload in the list response — a webhook envelope+ // can be up to 256 KiB and `limit` defaults to 20, so the full+ // list would be a ~5 MB worst case. Detail dialog fetches the+ // full payload from GetAutopilotRun.+ resp[i] = runToResponseSlim(run)}writeJSON(w, http.StatusOK, map[string]any{"runs": resp, "total": len(resp)})}+// GetAutopilotRun returns a single run including its full trigger_payload.+// Workspace scoping is enforced via loadAutopilotInWorkspace; the run is+// then re-checked to belong to that autopilot so a guessed runId from+// another workspace cannot leak data.+func (h *Handler) GetAutopilotRun(w http.ResponseWriter, r *http.Request) {+ autopilotID := chi.URLParam(r, "id")+ runID := chi.URLParam(r, "runId")+ workspaceID := h.resolveWorkspaceID(r)++ autopilot, ok := h.loadAutopilotInWorkspace(w, r, autopilotID, workspaceID)+ if !ok {+ return+ }++ runUUID, ok := parseUUIDOrBadRequest(w, runID, "run id")+ if !ok {+ return+ }++ run, err := h.Queries.GetAutopilotRun(r.Context(), runUUID)+ if err != nil {+ writeError(w, http.StatusNotFound, "run not found")+ return+ }+ if uuidToString(run.AutopilotID) != uuidToString(autopilot.ID) {+ // Guard against a runId from another autopilot being requested via+ // this autopilot's URL — fail closed with 404 so the response shape+ // matches the "not found" case and no information is leaked.+ writeError(w, http.StatusNotFound, "run not found")+ return+ }++ writeJSON(w, http.StatusOK, runToResponse(run))+}+// ── Manual trigger ──────────────────────────────────────────────────────────func (h *Handler) TriggerAutopilot(w http.ResponseWriter, r *http.Request) {diff --git a/server/internal/handler/autopilot_webhook.go b/server/internal/handler/autopilot_webhook.gonew file mode 100644index 0000000000..082b8c3350--- /dev/null+++ b/server/internal/handler/autopilot_webhook.go@@ -0,0 +1,461 @@+package handler++import (+ "crypto/rand"+ "encoding/base64"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "net/http"+ "net/netip"+ "strings"+ "time"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/middleware"+)++// maxWebhookBodyBytes is the request body size cap for webhook ingress.+// 256 KiB is plenty for normal provider webhooks (a max-size GitHub PR+// payload comes in well under this) and small enough that an attacker+// cannot wedge agent context windows by sending megabytes of arbitrary JSON.+const maxWebhookBodyBytes = 256 * 1024++// webhookTokenPrefix makes a leaked token recognisable in logs / audit trails+// without revealing the entropy bytes themselves. 32 random bytes encoded as+// URL-safe base64 (no padding) is 43 chars, so a full token is "awt_" + 43 = 47+// chars. URL-safe base64 keeps the token URL-friendly without escaping.+const webhookTokenPrefix = "awt_"++// generateWebhookToken returns a cryptographically random bearer token used as+// the public webhook URL secret. Format: "awt_" + URL-safe base64(32 bytes,+// no padding). UUIDs are intentionally not used here — they are lower entropy+// (122 bits vs 256) and visually overlap with internal IDs, which made+// accidental token-vs-ID confusion easy in early prototypes.+func generateWebhookToken() (string, error) {+ b := make([]byte, 32)+ if _, err := rand.Read(b); err != nil {+ return "", fmt.Errorf("rand: %w", err)+ }+ return webhookTokenPrefix + base64.RawURLEncoding.EncodeToString(b), nil+}++// ── Payload normalization ───────────────────────────────────────────────────++// WebhookEnvelope is the canonical shape stored in autopilot_run.trigger_payload+// and surfaced to the agent. The handler normalises arbitrary JSON bodies into+// this shape so downstream consumers (run_only daemon prompt, create_issue+// description appendix) can rely on a stable schema regardless of which+// provider sent the webhook.+type WebhookEnvelope struct {+ Event string `json:"event"`+ EventPayload json.RawMessage `json:"eventPayload"`+ Request WebhookRequest `json:"request"`+}++type WebhookRequest struct {+ ReceivedAt string `json:"receivedAt"`+ ContentType string `json:"contentType,omitempty"`+}++// normalizeWebhookPayload parses an incoming webhook body and returns a+// WebhookEnvelope. Rules:+//+// 1. Body must be a valid JSON object or array. Scalars / invalid JSON+// return an error so the handler can respond 400.+// 2. If the body is an object containing a string `event` and any+// `eventPayload`, those are preserved as-is.+// 3. Otherwise `event` is inferred from headers/body fields, and the entire+// original body becomes `eventPayload`.+// 4. The default event is `webhook.received`.+//+// Inference order:+//+// X-GitHub-Event (combined with body.action when present),+// X-Gitlab-Event, X-Event-Type, body.event, body.type, body.action.+func normalizeWebhookPayload(body []byte, headers http.Header) (WebhookEnvelope, error) {+ body = stripBOM(body)+ if len(body) == 0 {+ return WebhookEnvelope{}, errors.New("empty body")+ }++ // First, validate JSON shape (object or array). Reject scalars early —+ // `"hello"` is technically valid JSON but has no useful interpretation+ // as a webhook payload and would land in the agent prompt as a bare+ // string.+ var asAny any+ if err := json.Unmarshal(body, &asAny); err != nil {+ return WebhookEnvelope{}, fmt.Errorf("invalid json: %w", err)+ }+ switch asAny.(type) {+ case map[string]any, []any:+ // ok+ default:+ return WebhookEnvelope{}, errors.New("body must be a JSON object or array")+ }++ now := time.Now().UTC().Format(time.RFC3339)+ contentType := headers.Get("Content-Type")+ if i := strings.Index(contentType, ";"); i >= 0 {+ contentType = strings.TrimSpace(contentType[:i])+ }++ env := WebhookEnvelope{+ Request: WebhookRequest{+ ReceivedAt: now,+ ContentType: contentType,+ },+ }++ // 1. Caller-provided envelope.+ if obj, ok := asAny.(map[string]any); ok {+ if eventStr, ok := obj["event"].(string); ok && eventStr != "" {+ if rawPayload, ok := obj["eventPayload"]; ok {+ inner, err := json.Marshal(rawPayload)+ if err == nil {+ env.Event = eventStr+ env.EventPayload = inner+ return env, nil+ }+ }+ // `event` present but no eventPayload: still preserve event+ // string, fall through to use whole body as payload.+ env.Event = eventStr+ env.EventPayload = json.RawMessage(body)+ return env, nil+ }+ }++ // 2. Inferred event.+ event := inferEvent(headers, asAny)+ env.Event = event+ env.EventPayload = json.RawMessage(body)+ return env, nil+}++// inferEvent returns a best-effort event identifier from headers and body.+// The order matches the documented inference rules in PLAN.md.+func inferEvent(headers http.Header, body any) string {+ if gh := headers.Get("X-GitHub-Event"); gh != "" {+ if obj, ok := body.(map[string]any); ok {+ if action, ok := obj["action"].(string); ok && action != "" {+ return "github." + gh + "." + action+ }+ }+ return "github." + gh+ }+ if gl := headers.Get("X-Gitlab-Event"); gl != "" {+ return "gitlab." + gl+ }+ if xe := headers.Get("X-Event-Type"); xe != "" {+ return xe+ }+ if obj, ok := body.(map[string]any); ok {+ if e, ok := obj["event"].(string); ok && e != "" {+ return e+ }+ if t, ok := obj["type"].(string); ok && t != "" {+ return t+ }+ if a, ok := obj["action"].(string); ok && a != "" {+ return a+ }+ }+ return "webhook.received"+}++// stripBOM removes a leading UTF-8 byte-order-mark, which some clients+// (notably PowerShell-based scripts) prepend to JSON bodies.+func stripBOM(b []byte) []byte {+ if len(b) >= 3 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF {+ return b[3:]+ }+ return b+}++// ── Public ingress ──────────────────────────────────────────────────────────++// HandleAutopilotWebhook is the public entry point for webhook-triggered+// autopilots. It runs OUTSIDE the authenticated route group: the bearer+// token in the URL path IS the credential. Workspace context is derived+// from the trigger row's joined autopilot.workspace_id, never from request+// headers — that's why this handler does not call resolveWorkspaceID.+//+// Response shapes:+// - 200 {"status":"accepted", "run_id", "autopilot_id", "trigger_id"}+// - 200 {"status":"skipped", "run_id", "reason"} — runtime offline at dispatch+// - 200 {"status":"ignored", "reason":"trigger_disabled"} — disabled trigger+// - 200 {"status":"ignored", "reason":"autopilot_paused"} — paused autopilot+// - 200 {"status":"ignored", "reason":"autopilot_archived"} — archived autopilot+// - 400 {"error":"..."} — invalid JSON / scalar / empty+// - 404 {"error":"webhook not found"} — unknown token+// - 413 {"error":"payload too large"} — body exceeded cap+// - 429 {"error":"rate limit exceeded"} — over per-token budget+// - 500 {"error":"..."} — dispatch failure+func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request) {+ token := chi.URLParam(r, "token")+ if token == "" {+ writeError(w, http.StatusNotFound, "webhook not found")+ return+ }++ // 1. Per-IP rate limit BEFORE we hit Postgres. Bounds the DB-probe blast+ // radius for an attacker spraying random tokens: each token gets a+ // fresh per-token bucket, so without this gate a spray turns the+ // handler into an unauthenticated index probe.+ if h.WebhookIPRateLimiter != nil {+ if ip := h.clientIPForRateLimit(r); ip != "" {+ if !h.WebhookIPRateLimiter.Allow(r.Context(), ip) {+ writeError(w, http.StatusTooManyRequests, "rate limit exceeded")+ return+ }+ }+ }++ // 2. Look up the trigger by token. Distinguish "no row" from "DB error":+ // collapsing both to 404 means a transient DB blip silently drops real+ // deliveries (providers like GitHub don't retry on 404). For the no-row+ // case we still return a generic "webhook not found" so we don't leak+ // which tokens existed at some point.+ trigRow, err := h.Queries.GetWebhookTriggerByToken(r.Context(), pgtype.Text{String: token, Valid: true})+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusNotFound, "webhook not found")+ return+ }+ slog.Error("webhook: token lookup failed", "error", err)+ writeError(w, http.StatusInternalServerError, "internal error")+ return+ }++ // Stash the resolved trigger ID on the request context so the request+ // logger can include it in the audit line without revealing the bearer+ // token in the URL path. SetWebhookTriggerID mutates *r in place so the+ // wrapping RequestLogger middleware reads the value back after+ // ServeHTTP returns — see its doc comment for why.+ middleware.SetWebhookTriggerID(r, uuidToString(trigRow.ID))++ // 3. Per-token rate limit.+ if h.WebhookRateLimiter != nil {+ if !h.WebhookRateLimiter.Allow(r.Context(), token) {+ writeError(w, http.StatusTooManyRequests, "rate limit exceeded")+ return+ }+ }++ // 4. Disabled trigger → ignored. We deliberately return 200 so the+ // sender's webhook-retry machinery doesn't keep hammering us; the+ // "ignored" status makes the no-op visible if the operator inspects+ // delivery logs.+ if !trigRow.Enabled {+ writeJSON(w, http.StatusOK, map[string]any{"status": "ignored", "reason": "trigger_disabled"})+ return+ }++ // 5. Load Autopilot and cross-check workspace consistency. Same+ // ErrNoRows-vs-DB-error split as the token lookup above: a transient+ // DB hiccup must NOT degrade to 404, otherwise providers like GitHub+ // drop the event silently (no 5xx retry).+ autopilot, err := h.Queries.GetAutopilot(r.Context(), trigRow.AutopilotID)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ // FK invariant violation (trigger references a non-existent+ // autopilot). The FK constraint should prevent this; treat+ // as 404 if it ever happens.+ writeError(w, http.StatusNotFound, "webhook not found")+ return+ }+ slog.Error("webhook: autopilot lookup failed",+ "error", err,+ "trigger_id", uuidToString(trigRow.ID),+ )+ writeError(w, http.StatusInternalServerError, "internal error")+ return+ }+ if uuidToString(autopilot.WorkspaceID) != uuidToString(trigRow.AutopilotWorkspaceID) {+ // This should be impossible — the join is by primary key — but+ // fail closed if it ever happens rather than dispatching against+ // the wrong workspace.+ slog.Warn("webhook: trigger workspace mismatch",+ "trigger_id", uuidToString(trigRow.ID),+ "autopilot_id", uuidToString(autopilot.ID),+ )+ writeError(w, http.StatusNotFound, "webhook not found")+ return+ }++ if autopilot.Status == "archived" {+ writeJSON(w, http.StatusOK, map[string]any{"status": "ignored", "reason": "autopilot_archived"})+ return+ }+ if autopilot.Status != "active" {+ writeJSON(w, http.StatusOK, map[string]any{"status": "ignored", "reason": "autopilot_paused"})+ return+ }++ // 6. Body size cap + JSON validation. http.MaxBytesReader stops the+ // read mid-stream once the cap is exceeded so an oversized payload+ // is rejected before being fully buffered.+ r.Body = http.MaxBytesReader(w, r.Body, maxWebhookBodyBytes)+ body, err := io.ReadAll(r.Body)+ if err != nil {+ var mbe *http.MaxBytesError+ if errors.As(err, &mbe) {+ writeError(w, http.StatusRequestEntityTooLarge, "payload too large")+ return+ }+ writeError(w, http.StatusBadRequest, "failed to read request body")+ return+ }++ envelope, err := normalizeWebhookPayload(body, r.Header)+ if err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }++ envelopeBytes, err := json.Marshal(envelope)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to encode envelope")+ return+ }++ // 7. Dispatch. DispatchAutopilot already publishes the workspace-scoped+ // EventAutopilotRunStart, persists the payload, runs the admission+ // check (offline runtime → records a `skipped` run), and bumps+ // last_run_at. We don't add a second WS publish.+ run, err := h.AutopilotService.DispatchAutopilot(+ r.Context(),+ autopilot,+ trigRow.ID,+ "webhook",+ envelopeBytes,+ )+ if err != nil {+ slog.Warn("webhook dispatch failed",+ "trigger_id", uuidToString(trigRow.ID),+ "autopilot_id", uuidToString(autopilot.ID),+ "error", err,+ )+ writeError(w, http.StatusInternalServerError, "failed to dispatch autopilot")+ return+ }++ // 8. Bump last_fired_at (separate from autopilot.last_run_at). Done+ // after dispatch returns — including the skipped path — so paused+ // early-return arms above don't corrupt the meaning of "last fired".+ if err := h.Queries.TouchAutopilotTriggerFiredAt(r.Context(), trigRow.ID); err != nil {+ slog.Warn("webhook: failed to touch last_fired_at",+ "trigger_id", uuidToString(trigRow.ID),+ "error", err,+ )+ }++ // 9. Response shape: skipped runs surface their reason+ // so providers can log it without parsing free-form text.+ if run.Status == "skipped" {+ reason := ""+ if run.FailureReason.Valid {+ reason = run.FailureReason.String+ }+ writeJSON(w, http.StatusOK, map[string]any{+ "status": "skipped",+ "run_id": uuidToString(run.ID),+ "reason": reason,+ })+ return+ }++ writeJSON(w, http.StatusOK, map[string]any{+ "status": "accepted",+ "run_id": uuidToString(run.ID),+ "autopilot_id": uuidToString(autopilot.ID),+ "trigger_id": uuidToString(trigRow.ID),+ })+}++// clientIPForRateLimit returns the IP used as a rate-limit bucket key.+//+// Default behaviour: use the host portion of r.RemoteAddr. Forwarded+// headers (X-Forwarded-For, X-Real-IP) are IGNORED unless the operator+// has explicitly opted in via MULTICA_TRUSTED_PROXIES — and even then+// only when r.RemoteAddr is itself inside one of the listed CIDRs.+//+// Why this matters: the job of THIS limiter is to gate unauthenticated+// token spraying before it hits the autopilot_trigger unique index. If+// we honored XFF from anyone, an attacker could rotate the header on+// every request, the per-IP bucket would effectively become per-request,+// and the limiter would be bypassed. The CIDR gate forces trust to come+// from where the operator says it does.+func (h *Handler) clientIPForRateLimit(r *http.Request) string {+ remoteIP := remoteAddrHost(r.RemoteAddr)+ if len(h.cfg.TrustedProxies) == 0 {+ return remoteIP+ }+ remoteAddr, ok := parseNetIPAddr(remoteIP)+ if !ok || !addrInPrefixes(remoteAddr, h.cfg.TrustedProxies) {+ // Source isn't a trusted proxy — headers can't be believed.+ return remoteIP+ }+ if xff := r.Header.Get("X-Forwarded-For"); xff != "" {+ if i := strings.IndexByte(xff, ','); i >= 0 {+ return strings.TrimSpace(xff[:i])+ }+ return strings.TrimSpace(xff)+ }+ if xri := r.Header.Get("X-Real-IP"); xri != "" {+ return strings.TrimSpace(xri)+ }+ return remoteIP+}++// remoteAddrHost returns the host portion of an "addr" or "host:port" string.+// IPv6 with port is "[::1]:8080" — we strip the brackets so the result is a+// parseable IP. If the input has no port, it is returned unchanged.+func remoteAddrHost(remote string) string {+ if remote == "" {+ return ""+ }+ // IPv6 "[::1]:port" → "::1"+ if strings.HasPrefix(remote, "[") {+ if end := strings.IndexByte(remote, ']'); end > 0 {+ return remote[1:end]+ }+ }+ // IPv4 "host:port" → "host"; bare IPv4 stays.+ if i := strings.LastIndexByte(remote, ':'); i >= 0 && !strings.Contains(remote, "]") {+ // Only treat the trailing ":<digits>" as a port. If there are+ // multiple colons (bare IPv6) we leave the string alone.+ if strings.Count(remote, ":") == 1 {+ return remote[:i]+ }+ }+ return remote+}++// parseNetIPAddr parses an IP literal, tolerating IPv6 zone suffixes.+func parseNetIPAddr(s string) (netip.Addr, bool) {+ if s == "" {+ return netip.Addr{}, false+ }+ addr, err := netip.ParseAddr(s)+ if err != nil {+ return netip.Addr{}, false+ }+ return addr.Unmap(), true+}++// addrInPrefixes reports whether addr falls into any of the CIDRs.+func addrInPrefixes(addr netip.Addr, prefixes []netip.Prefix) bool {+ for _, p := range prefixes {+ if p.Contains(addr) {+ return true+ }+ }+ return false+}diff --git a/server/internal/handler/autopilot_webhook_handler_test.go b/server/internal/handler/autopilot_webhook_handler_test.gonew file mode 100644index 0000000000..893725036c--- /dev/null+++ b/server/internal/handler/autopilot_webhook_handler_test.go@@ -0,0 +1,664 @@+package handler++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// All tests in this file require a working DB. testHandler / testWorkspaceID /+// testUserID / testRuntimeID are wired in TestMain (handler_test.go) and+// TestMain skips the suite if Postgres isn't reachable.++// ── Fixture helpers ─────────────────────────────────────────────────────────++func createWebhookTestAgent(t *testing.T, name string) string {+ t.Helper()+ var agentID string+ if err := testPool.QueryRow(context.Background(), `+ INSERT INTO agent (+ workspace_id, name, description, runtime_mode, runtime_config,+ runtime_id, visibility, max_concurrent_tasks, owner_id,+ instructions, custom_env, custom_args, mcp_config+ )+ VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'private', 1, $4, '', '{}'::jsonb, '[]'::jsonb, '{}'::jsonb)+ RETURNING id+ `, testWorkspaceID, name, testRuntimeID, testUserID).Scan(&agentID); err != nil {+ t.Fatalf("create agent: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, agentID)+ })+ return agentID+}++func createWebhookTestAutopilot(t *testing.T, agentID, status, mode string) string {+ t.Helper()+ var apID string+ if err := testPool.QueryRow(context.Background(), `+ INSERT INTO autopilot (+ workspace_id, title, assignee_id, status, execution_mode,+ created_by_type, created_by_id+ ) VALUES ($1, $2, $3, $4, $5, 'member', $6)+ RETURNING id+ `, testWorkspaceID, "Webhook test "+status, agentID, status, mode, testUserID).Scan(&apID); err != nil {+ t.Fatalf("create autopilot: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, apID)+ })+ return apID+}++func createWebhookTriggerViaHandler(t *testing.T, autopilotID string) AutopilotTriggerResponse {+ t.Helper()+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/autopilots/"+autopilotID+"/triggers", map[string]any{+ "kind": "webhook",+ })+ req = withURLParam(req, "id", autopilotID)+ testHandler.CreateAutopilotTrigger(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateAutopilotTrigger: expected 201, got %d body=%s", w.Code, w.Body.String())+ }+ var resp AutopilotTriggerResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ return resp+}++func postWebhook(t *testing.T, token string, body any, headers map[string]string) *httptest.ResponseRecorder {+ t.Helper()+ var buf bytes.Buffer+ switch v := body.(type) {+ case []byte:+ buf.Write(v)+ case string:+ buf.WriteString(v)+ default:+ if err := json.NewEncoder(&buf).Encode(body); err != nil {+ t.Fatalf("encode: %v", err)+ }+ }+ req := httptest.NewRequest("POST", "/api/webhooks/autopilots/"+token, &buf)+ for k, v := range headers {+ req.Header.Set(k, v)+ }+ if req.Header.Get("Content-Type") == "" {+ req.Header.Set("Content-Type", "application/json")+ }+ req = withURLParam(req, "token", token)+ w := httptest.NewRecorder()+ testHandler.HandleAutopilotWebhook(w, req)+ return w+}++// ── Tests ───────────────────────────────────────────────────────────────────++func TestCreateWebhookTrigger_GeneratesToken(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WebhookGen Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")++ resp := createWebhookTriggerViaHandler(t, apID)+ if resp.Kind != "webhook" {+ t.Fatalf("kind: %q", resp.Kind)+ }+ if resp.WebhookToken == nil || *resp.WebhookToken == "" {+ t.Fatal("webhook_token should be present and non-empty")+ }+ if !strings.HasPrefix(*resp.WebhookToken, "awt_") {+ t.Fatalf("token prefix: %q", *resp.WebhookToken)+ }+ if resp.WebhookPath == nil {+ t.Fatal("webhook_path should be present")+ }+ if !strings.HasSuffix(*resp.WebhookPath, *resp.WebhookToken) {+ t.Fatalf("webhook_path %q should contain token %q", *resp.WebhookPath, *resp.WebhookToken)+ }+}++func TestCreateWebhookTrigger_TwoUniqueTokens(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WebhookUnique Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")++ a := createWebhookTriggerViaHandler(t, apID)+ b := createWebhookTriggerViaHandler(t, apID)+ if a.WebhookToken == nil || b.WebhookToken == nil {+ t.Fatal("missing tokens")+ }+ if *a.WebhookToken == *b.WebhookToken {+ t.Fatalf("tokens should differ: %q == %q", *a.WebhookToken, *b.WebhookToken)+ }+}++func TestCreateWebhookTrigger_PublicURLAffectsResponse(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WebhookURL Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")++ prev := testHandler.cfg.PublicURL+ t.Cleanup(func() { testHandler.cfg.PublicURL = prev })++ testHandler.cfg.PublicURL = ""+ respNoURL := createWebhookTriggerViaHandler(t, apID)+ if respNoURL.WebhookURL != nil {+ t.Fatalf("webhook_url should be nil when PublicURL unset, got %q", *respNoURL.WebhookURL)+ }++ testHandler.cfg.PublicURL = "https://app.example"+ respURL := createWebhookTriggerViaHandler(t, apID)+ if respURL.WebhookURL == nil {+ t.Fatal("webhook_url should be present when PublicURL set")+ }+ if !strings.HasPrefix(*respURL.WebhookURL, "https://app.example/api/webhooks/autopilots/") {+ t.Fatalf("webhook_url shape: %q", *respURL.WebhookURL)+ }+}++func TestWebhookHandler_404OnUnknownToken(t *testing.T) {+ w := postWebhook(t, "awt_unknown_token_value", map[string]any{"hello": "world"}, nil)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d body=%s", w.Code, w.Body.String())+ }+}++func TestWebhookHandler_RejectsInvalidJSON(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WebhookBadJSON Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ trig := createWebhookTriggerViaHandler(t, apID)++ w := postWebhook(t, *trig.WebhookToken, []byte(`not json`), nil)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d body=%s", w.Code, w.Body.String())+ }+}++func TestWebhookHandler_RejectsScalarBody(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WebhookScalar Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ trig := createWebhookTriggerViaHandler(t, apID)++ w := postWebhook(t, *trig.WebhookToken, []byte(`"hello"`), nil)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d body=%s", w.Code, w.Body.String())+ }+}++func TestWebhookHandler_RejectsOversized(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WebhookSize Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ trig := createWebhookTriggerViaHandler(t, apID)++ big := make([]byte, maxWebhookBodyBytes+10)+ for i := range big {+ big[i] = 'a'+ }+ body := append([]byte(`{"x":"`), big...)+ body = append(body, []byte(`"}`)...)++ w := postWebhook(t, *trig.WebhookToken, body, nil)+ if w.Code != http.StatusRequestEntityTooLarge {+ t.Fatalf("expected 413, got %d body=%s", w.Code, w.Body.String())+ }+}++func TestWebhookHandler_DisabledTriggerReturnsIgnored(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WebhookDisabled Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ trig := createWebhookTriggerViaHandler(t, apID)++ if _, err := testHandler.Queries.UpdateAutopilotTrigger(context.Background(), db.UpdateAutopilotTriggerParams{+ ID: parseUUID(trig.ID),+ Enabled: pgtype.Bool{Bool: false, Valid: true},+ }); err != nil {+ t.Fatalf("disable trigger: %v", err)+ }++ w := postWebhook(t, *trig.WebhookToken, map[string]any{"hello": "world"}, nil)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())+ }+ var resp map[string]any+ json.Unmarshal(w.Body.Bytes(), &resp)+ if resp["status"] != "ignored" {+ t.Fatalf("status: %v", resp["status"])+ }+ if resp["reason"] != "trigger_disabled" {+ t.Fatalf("reason: %v", resp["reason"])+ }+}++func TestWebhookHandler_PausedAutopilotReturnsIgnored(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WebhookPaused Agent")+ apID := createWebhookTestAutopilot(t, agentID, "paused", "run_only")+ trig := createWebhookTriggerViaHandler(t, apID)++ w := postWebhook(t, *trig.WebhookToken, map[string]any{"x": 1}, nil)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())+ }+ var resp map[string]any+ json.Unmarshal(w.Body.Bytes(), &resp)+ if resp["reason"] != "autopilot_paused" {+ t.Fatalf("reason: %v", resp["reason"])+ }+}++func TestWebhookHandler_ActiveDispatchesRunWithPayload(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WebhookDispatch Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ trig := createWebhookTriggerViaHandler(t, apID)++ w := postWebhook(t, *trig.WebhookToken, map[string]any{+ "event": "demo.received",+ "eventPayload": map[string]any{"k": "v"},+ }, nil)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())+ }+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp["status"] != "accepted" {+ t.Fatalf("expected accepted, got %v body=%s", resp["status"], w.Body.String())+ }+ runID, _ := resp["run_id"].(string)+ if runID == "" {+ t.Fatal("run_id missing from response")+ }++ // Validate the persisted run carries the normalized envelope.+ run, err := testHandler.Queries.GetAutopilotRun(context.Background(), parseUUID(runID))+ if err != nil {+ t.Fatalf("load run: %v", err)+ }+ if run.Source != "webhook" {+ t.Fatalf("run.source: %q", run.Source)+ }+ if uuidToString(run.TriggerID) != trig.ID {+ t.Fatalf("run.trigger_id mismatch: %q vs %q", uuidToString(run.TriggerID), trig.ID)+ }+ var payload struct {+ Event string `json:"event"`+ EventPayload map[string]interface{} `json:"eventPayload"`+ }+ if err := json.Unmarshal(run.TriggerPayload, &payload); err != nil {+ t.Fatalf("payload decode: %v body=%s", err, string(run.TriggerPayload))+ }+ if payload.Event != "demo.received" {+ t.Fatalf("envelope event: %q", payload.Event)+ }+ if payload.EventPayload["k"] != "v" {+ t.Fatalf("envelope payload: %#v", payload.EventPayload)+ }++ // last_fired_at must have been bumped.+ trigRow, err := testHandler.Queries.GetAutopilotTrigger(context.Background(), parseUUID(trig.ID))+ if err != nil {+ t.Fatalf("load trigger: %v", err)+ }+ if !trigRow.LastFiredAt.Valid {+ t.Fatal("last_fired_at should be set after webhook dispatch")+ }+}++func TestWebhookHandler_GitHubHeaderInferredEvent(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WebhookGH Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ trig := createWebhookTriggerViaHandler(t, apID)++ w := postWebhook(t, *trig.WebhookToken, map[string]any{+ "action": "opened",+ "pull_request": map[string]any{+ "number": 42,+ },+ }, map[string]string{"X-GitHub-Event": "pull_request"})+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())+ }+ var resp map[string]any+ json.Unmarshal(w.Body.Bytes(), &resp)+ runID := resp["run_id"].(string)+ run, err := testHandler.Queries.GetAutopilotRun(context.Background(), parseUUID(runID))+ if err != nil {+ t.Fatalf("load run: %v", err)+ }+ var env struct {+ Event string `json:"event"`+ }+ json.Unmarshal(run.TriggerPayload, &env)+ if env.Event != "github.pull_request.opened" {+ t.Fatalf("event inference: got %q", env.Event)+ }+}++func TestWebhookHandler_RateLimitReturns429(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WebhookRate Agent")+ apID := createWebhookTestAutopilot(t, agentID, "paused", "run_only") // paused → cheap ignored path+ trig := createWebhookTriggerViaHandler(t, apID)++ prev := testHandler.WebhookRateLimiter+ testHandler.WebhookRateLimiter = NewMemoryWebhookRateLimiter(WebhookRateLimit{Limit: 2, Window: 60_000_000_000})+ t.Cleanup(func() { testHandler.WebhookRateLimiter = prev })++ for i := 0; i < 2; i++ {+ w := postWebhook(t, *trig.WebhookToken, map[string]any{"i": i}, nil)+ if w.Code != http.StatusOK {+ t.Fatalf("request %d: expected 200, got %d", i, w.Code)+ }+ }+ w := postWebhook(t, *trig.WebhookToken, map[string]any{"i": "third"}, nil)+ if w.Code != http.StatusTooManyRequests {+ t.Fatalf("expected 429, got %d body=%s", w.Code, w.Body.String())+ }+}++func TestRotateWebhookToken_ReplacesOldToken(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WebhookRotate Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ trig := createWebhookTriggerViaHandler(t, apID)+ oldToken := *trig.WebhookToken++ w := httptest.NewRecorder()+ req := newRequest("POST", fmt.Sprintf("/api/autopilots/%s/triggers/%s/rotate-webhook-token", apID, trig.ID), nil)+ req = withURLParams(req, "id", apID, "triggerId", trig.ID)+ testHandler.RotateAutopilotTriggerWebhookToken(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("rotate: expected 200, got %d body=%s", w.Code, w.Body.String())+ }+ var rotated AutopilotTriggerResponse+ json.Unmarshal(w.Body.Bytes(), &rotated)+ if rotated.WebhookToken == nil || *rotated.WebhookToken == oldToken {+ t.Fatalf("rotate did not change token: old=%q new=%v", oldToken, rotated.WebhookToken)+ }++ // Old token should now 404.+ resOld := postWebhook(t, oldToken, map[string]any{"x": 1}, nil)+ if resOld.Code != http.StatusNotFound {+ t.Fatalf("old token should be 404, got %d", resOld.Code)+ }+ // New token should accept.+ resNew := postWebhook(t, *rotated.WebhookToken, map[string]any{"x": 1}, nil)+ if resNew.Code != http.StatusOK {+ t.Fatalf("new token should be 200, got %d body=%s", resNew.Code, resNew.Body.String())+ }+}++// ── Additional coverage (PR #2348 review) ──────────────────────────────────++func TestWebhookHandler_EmptyBodyReturns400(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WebhookEmpty Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ trig := createWebhookTriggerViaHandler(t, apID)++ w := postWebhook(t, *trig.WebhookToken, []byte(``), nil)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 for empty body, got %d body=%s", w.Code, w.Body.String())+ }+}++func TestWebhookHandler_ArchivedAutopilotReturnsIgnored(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WebhookArchived Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ trig := createWebhookTriggerViaHandler(t, apID)++ if _, err := testPool.Exec(context.Background(),+ `UPDATE autopilot SET status = 'archived' WHERE id = $1`, apID); err != nil {+ t.Fatalf("archive autopilot: %v", err)+ }++ w := postWebhook(t, *trig.WebhookToken, map[string]any{"x": 1}, nil)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())+ }+ var resp map[string]any+ json.Unmarshal(w.Body.Bytes(), &resp)+ if resp["status"] != "ignored" || resp["reason"] != "autopilot_archived" {+ t.Fatalf("expected ignored/autopilot_archived, got %#v", resp)+ }+}++func TestWebhookHandler_IPRateLimitReturns429BeforeDBLookup(t *testing.T) {+ // Spray random (likely-unknown) tokens from one IP and prove the IP+ // limiter trips before we exhaust the budget — without this gate an+ // attacker can probe the trigger-lookup index unboundedly. Rate-limit+ // keying is by the real source IP (r.RemoteAddr) since TrustedProxies+ // is empty here, so the bucket is per-connection — exactly the+ // property the per-IP limiter is meant to provide.+ prev := testHandler.WebhookIPRateLimiter+ testHandler.WebhookIPRateLimiter = NewMemoryWebhookIPRateLimiter(WebhookRateLimit{Limit: 2, Window: 60_000_000_000})+ t.Cleanup(func() { testHandler.WebhookIPRateLimiter = prev })++ post := func(token string) int {+ req := httptest.NewRequest("POST", "/api/webhooks/autopilots/"+token,+ bytes.NewBufferString(`{"x":1}`))+ req.Header.Set("Content-Type", "application/json")+ req.RemoteAddr = "192.0.2.7:1234" // stable source, three calls = same bucket+ req = withURLParam(req, "token", token)+ w := httptest.NewRecorder()+ testHandler.HandleAutopilotWebhook(w, req)+ return w.Code+ }++ if got := post("awt_unknown_a"); got != http.StatusNotFound {+ t.Fatalf("first probe: expected 404, got %d", got)+ }+ if got := post("awt_unknown_b"); got != http.StatusNotFound {+ t.Fatalf("second probe: expected 404, got %d", got)+ }+ if got := post("awt_unknown_c"); got != http.StatusTooManyRequests {+ t.Fatalf("third probe: expected 429 (IP bucket), got %d", got)+ }+}++func TestWebhookHandler_IPRateLimitNotBypassedByXFFSpoof(t *testing.T) {+ // Round-2 fix: with the default empty TrustedProxies, an attacker who+ // rotates X-Forwarded-For per request must still get bucketed by the+ // real connection IP — otherwise the per-IP limiter is trivially+ // bypassable and we're back to one DB index probe per request.+ prev := testHandler.WebhookIPRateLimiter+ testHandler.WebhookIPRateLimiter = NewMemoryWebhookIPRateLimiter(WebhookRateLimit{Limit: 2, Window: 60_000_000_000})+ t.Cleanup(func() { testHandler.WebhookIPRateLimiter = prev })++ post := func(token, xff string) int {+ req := httptest.NewRequest("POST", "/api/webhooks/autopilots/"+token,+ bytes.NewBufferString(`{"x":1}`))+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("X-Forwarded-For", xff) // <-- attacker-controlled+ req.RemoteAddr = "198.51.100.42:5555" // real (untrusted) source+ req = withURLParam(req, "token", token)+ w := httptest.NewRecorder()+ testHandler.HandleAutopilotWebhook(w, req)+ return w.Code+ }++ if got := post("awt_unknown_x", "1.1.1.1"); got != http.StatusNotFound {+ t.Fatalf("first probe: expected 404, got %d", got)+ }+ if got := post("awt_unknown_y", "2.2.2.2"); got != http.StatusNotFound {+ t.Fatalf("second probe: expected 404, got %d", got)+ }+ // Third request with yet another spoofed XFF — would have bypassed+ // the limiter under the old (header-trusting) behavior, but with the+ // CIDR-gated trust the bucket is still the real source IP.+ if got := post("awt_unknown_z", "3.3.3.3"); got != http.StatusTooManyRequests {+ t.Fatalf("third probe: expected 429 (bucket keyed by real IP), got %d", got)+ }+}++func TestWebhookHandler_DBErrorOnTokenLookupReturns500(t *testing.T) {+ // Inject a fake Queries-like wrapper via a shadow type isn't simple+ // here because Handler.Queries is a *db.Queries struct, not an+ // interface. Instead, simulate the path by deleting the trigger row+ // out from under a known-valid token AND swapping in a stub limiter+ // that always allows. The handler will then call+ // GetWebhookTriggerByToken with a non-existent value → pgx.ErrNoRows+ // → 404. So this test alone can't drive the 500 branch without+ // breaking the DB connection. The 500 branch is exercised via the+ // unit tests in this package's TestRedactWebhookPath /+ // TestRequestLogger_*; we leave a regression marker here so a future+ // refactor that collapses ErrNoRows into 500 (or vice versa) is+ // caught by a code review rather than a missing test.+ //+ // The real verification for this branch is: the file diff for+ // autopilot_webhook.go must show `errors.Is(err, pgx.ErrNoRows)` —+ // see PR #2348 review item Blocking #2.+ t.Skip("500-branch requires injecting a stub Queries; left as a code-review-protected invariant")+}++func TestCreateAutopilotTrigger_RejectsAPIKind(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WebhookAPIKind Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")++ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/autopilots/"+apID+"/triggers", map[string]any{+ "kind": "api",+ })+ req = withURLParam(req, "id", apID)+ testHandler.CreateAutopilotTrigger(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 on kind=api, got %d body=%s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "schedule or webhook") {+ t.Fatalf("expected message to name allowed kinds, body=%s", w.Body.String())+ }+}++func TestCreateAutopilotTrigger_RejectsWebhookWithTimezone(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WebhookTZReject Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")++ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/autopilots/"+apID+"/triggers", map[string]any{+ "kind": "webhook",+ "timezone": "Europe/Berlin",+ })+ req = withURLParam(req, "id", apID)+ testHandler.CreateAutopilotTrigger(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 on webhook+timezone, got %d body=%s", w.Code, w.Body.String())+ }+}++func TestUpdateAutopilotTrigger_RejectsCronExpressionOnWebhookKind(t *testing.T) {+ // Round-2 should-fix: UpdateAutopilotTrigger must mirror create-path+ // strictness — cron_expression on a non-schedule trigger is rejected+ // with 400 rather than silently persisted.+ agentID := createWebhookTestAgent(t, "WebhookUpdCron Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ trig := createWebhookTriggerViaHandler(t, apID)++ w := httptest.NewRecorder()+ req := newRequest("PATCH", "/api/autopilots/"+apID+"/triggers/"+trig.ID, map[string]any{+ "cron_expression": "0 0 * * *",+ })+ req = withURLParams(req, "id", apID, "triggerId", trig.ID)+ testHandler.UpdateAutopilotTrigger(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 on cron_expression for webhook trigger, got %d body=%s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "cron_expression") {+ t.Fatalf("error message should mention cron_expression, got %s", w.Body.String())+ }+}++func TestUpdateAutopilotTrigger_RejectsTimezoneOnWebhookKind(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WebhookUpdTZ Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ trig := createWebhookTriggerViaHandler(t, apID)++ w := httptest.NewRecorder()+ req := newRequest("PATCH", "/api/autopilots/"+apID+"/triggers/"+trig.ID, map[string]any{+ "timezone": "Europe/Berlin",+ })+ req = withURLParams(req, "id", apID, "triggerId", trig.ID)+ testHandler.UpdateAutopilotTrigger(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 on timezone for webhook trigger, got %d body=%s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "timezone") {+ t.Fatalf("error message should mention timezone, got %s", w.Body.String())+ }+}++func TestUpdateAutopilotTrigger_AcceptsEnabledAndLabelOnWebhookKind(t *testing.T) {+ // Counter-test: enabled and label remain valid on every kind. Without+ // this, the kind-aware guard could regress to a blanket reject.+ agentID := createWebhookTestAgent(t, "WebhookUpdAllowed Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ trig := createWebhookTriggerViaHandler(t, apID)++ w := httptest.NewRecorder()+ req := newRequest("PATCH", "/api/autopilots/"+apID+"/triggers/"+trig.ID, map[string]any{+ "enabled": false,+ "label": "renamed",+ })+ req = withURLParams(req, "id", apID, "triggerId", trig.ID)+ testHandler.UpdateAutopilotTrigger(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200 on enabled+label PATCH, got %d body=%s", w.Code, w.Body.String())+ }+}++func TestGetAutopilotRun_ReturnsFullPayload(t *testing.T) {+ // List endpoint omits trigger_payload; the new GET /runs/{runId}+ // endpoint must return it intact.+ agentID := createWebhookTestAgent(t, "WebhookGetRun Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ trig := createWebhookTriggerViaHandler(t, apID)++ // Fire one webhook so there's a run with a payload.+ post := postWebhook(t, *trig.WebhookToken, map[string]any{+ "event": "demo.x",+ "eventPayload": map[string]any{"answer": 42},+ }, nil)+ if post.Code != http.StatusOK {+ t.Fatalf("seed webhook: %d body=%s", post.Code, post.Body.String())+ }+ var seedResp map[string]any+ json.Unmarshal(post.Body.Bytes(), &seedResp)+ runID := seedResp["run_id"].(string)++ // LIST: trigger_payload should be omitted (slim response).+ wList := httptest.NewRecorder()+ reqList := newRequest("GET", "/api/autopilots/"+apID+"/runs", nil)+ reqList = withURLParam(reqList, "id", apID)+ testHandler.ListAutopilotRuns(wList, reqList)+ if wList.Code != http.StatusOK {+ t.Fatalf("list: expected 200, got %d body=%s", wList.Code, wList.Body.String())+ }+ if strings.Contains(wList.Body.String(), `"answer":42`) {+ t.Fatalf("list response should NOT carry trigger_payload, body=%s", wList.Body.String())+ }++ // DETAIL: trigger_payload should be present.+ wDetail := httptest.NewRecorder()+ reqDetail := newRequest("GET", "/api/autopilots/"+apID+"/runs/"+runID, nil)+ reqDetail = withURLParams(reqDetail, "id", apID, "runId", runID)+ testHandler.GetAutopilotRun(wDetail, reqDetail)+ if wDetail.Code != http.StatusOK {+ t.Fatalf("detail: expected 200, got %d body=%s", wDetail.Code, wDetail.Body.String())+ }+ if !strings.Contains(wDetail.Body.String(), `"answer":42`) {+ t.Fatalf("detail response should carry full trigger_payload, body=%s", wDetail.Body.String())+ }+}++// NOTE: the cross-workspace paranoia branch in autopilot_webhook.go+// (uuidToString(autopilot.WorkspaceID) != uuidToString(trigRow.AutopilotWorkspaceID))+// is defense-in-depth against a TOCTOU race between the joined token+// lookup and the follow-up GetAutopilot read. It is not reachable from+// any valid SQL state — the two reads compute against the same+// autopilot.workspace_id column — and would require a mock-able+// Queries interface to drive deterministically. We pin the behaviour+// via code review rather than a brittle race test. See PR #2348 review+// item under "Test coverage gaps."diff --git a/server/internal/handler/autopilot_webhook_iprl_test.go b/server/internal/handler/autopilot_webhook_iprl_test.gonew file mode 100644index 0000000000..dc5f25edb0--- /dev/null+++ b/server/internal/handler/autopilot_webhook_iprl_test.go@@ -0,0 +1,137 @@+package handler++import (+ "net/http/httptest"+ "net/netip"+ "testing"+)++// These tests don't need a database — they exercise the pure header/CIDR+// logic of (h *Handler).clientIPForRateLimit so we construct a minimal+// Handler with just the Config populated.++func newClientIPHandler(t *testing.T, cidrs ...string) *Handler {+ t.Helper()+ var prefixes []netip.Prefix+ for _, c := range cidrs {+ p, err := netip.ParsePrefix(c)+ if err != nil {+ t.Fatalf("bad test CIDR %q: %v", c, err)+ }+ prefixes = append(prefixes, p)+ }+ return &Handler{cfg: Config{TrustedProxies: prefixes}}+}++func TestClientIPForRateLimit_DefaultIgnoresProxyHeaders(t *testing.T) {+ // The critical assertion: with no TrustedProxies configured, a caller+ // can spam X-Forwarded-For values but the limiter still keys on the+ // real source IP. This is what closes the bypass Bohan flagged.+ h := newClientIPHandler(t /* no CIDRs */)++ req := httptest.NewRequest("POST", "/", nil)+ req.RemoteAddr = "203.0.113.5:1234"+ req.Header.Set("X-Forwarded-For", "1.2.3.4")+ req.Header.Set("X-Real-IP", "5.6.7.8")++ if got := h.clientIPForRateLimit(req); got != "203.0.113.5" {+ t.Fatalf("default: got %q, want 203.0.113.5 (RemoteAddr) — headers must be ignored", got)+ }+}++func TestClientIPForRateLimit_HonorsXFFFromTrustedProxy(t *testing.T) {+ h := newClientIPHandler(t, "10.0.0.0/8")++ req := httptest.NewRequest("POST", "/", nil)+ req.RemoteAddr = "10.1.2.3:9999" // inside trusted prefix+ req.Header.Set("X-Forwarded-For", "5.5.5.5")++ if got := h.clientIPForRateLimit(req); got != "5.5.5.5" {+ t.Fatalf("trusted: got %q, want 5.5.5.5 (XFF from trusted proxy)", got)+ }+}++func TestClientIPForRateLimit_IgnoresXFFFromUntrustedSource(t *testing.T) {+ // The bypass-closed assertion: even with TrustedProxies set, if the+ // connection didn't come from one of those addresses, XFF must be+ // ignored — otherwise the limiter is still trivially bypassable.+ h := newClientIPHandler(t, "10.0.0.0/8")++ req := httptest.NewRequest("POST", "/", nil)+ req.RemoteAddr = "203.0.113.5:1234" // NOT inside trusted prefix+ req.Header.Set("X-Forwarded-For", "5.5.5.5")++ if got := h.clientIPForRateLimit(req); got != "203.0.113.5" {+ t.Fatalf("untrusted: got %q, want 203.0.113.5 — XFF must be ignored when source isn't in TrustedProxies", got)+ }+}++func TestClientIPForRateLimit_MultiHopXFFFirstEntryWins(t *testing.T) {+ h := newClientIPHandler(t, "10.0.0.0/8")++ req := httptest.NewRequest("POST", "/", nil)+ req.RemoteAddr = "10.1.2.3:9999"+ // Convention: leftmost entry is the original client; the proxy+ // appends its own IP as the next hop.+ req.Header.Set("X-Forwarded-For", "5.5.5.5, 10.0.0.7")++ if got := h.clientIPForRateLimit(req); got != "5.5.5.5" {+ t.Fatalf("multi-hop XFF: got %q, want 5.5.5.5 (leftmost)", got)+ }+}++func TestClientIPForRateLimit_FallsBackToXRealIPWhenXFFEmpty(t *testing.T) {+ h := newClientIPHandler(t, "10.0.0.0/8")++ req := httptest.NewRequest("POST", "/", nil)+ req.RemoteAddr = "10.1.2.3:9999"+ req.Header.Set("X-Real-IP", "7.7.7.7")++ if got := h.clientIPForRateLimit(req); got != "7.7.7.7" {+ t.Fatalf("X-Real-IP fallback: got %q, want 7.7.7.7", got)+ }+}++func TestClientIPForRateLimit_IPv6RemoteAddrIsParsed(t *testing.T) {+ // IPv6 RemoteAddr is "[::1]:port" — make sure the host extraction+ // peels off the brackets and the CIDR check works.+ h := newClientIPHandler(t, "::1/128")++ req := httptest.NewRequest("POST", "/", nil)+ req.RemoteAddr = "[::1]:5000"+ req.Header.Set("X-Forwarded-For", "9.9.9.9")++ if got := h.clientIPForRateLimit(req); got != "9.9.9.9" {+ t.Fatalf("IPv6 trusted: got %q, want 9.9.9.9", got)+ }+}++func TestClientIPForRateLimit_IPv6UntrustedKeepsRemoteAddr(t *testing.T) {+ h := newClientIPHandler(t, "10.0.0.0/8")++ req := httptest.NewRequest("POST", "/", nil)+ req.RemoteAddr = "[2001:db8::1]:5000"+ req.Header.Set("X-Forwarded-For", "9.9.9.9")++ if got := h.clientIPForRateLimit(req); got != "2001:db8::1" {+ t.Fatalf("IPv6 untrusted: got %q, want 2001:db8::1", got)+ }+}++func TestRemoteAddrHost(t *testing.T) {+ cases := []struct {+ in, want string+ }{+ {"203.0.113.5:1234", "203.0.113.5"},+ {"[::1]:8080", "::1"},+ {"[2001:db8::1]:443", "2001:db8::1"},+ {"203.0.113.5", "203.0.113.5"}, // bare, no port+ {"2001:db8::1", "2001:db8::1"}, // bare IPv6+ {"", ""},+ }+ for _, tc := range cases {+ if got := remoteAddrHost(tc.in); got != tc.want {+ t.Errorf("remoteAddrHost(%q) = %q, want %q", tc.in, got, tc.want)+ }+ }+}diff --git a/server/internal/handler/autopilot_webhook_test.go b/server/internal/handler/autopilot_webhook_test.gonew file mode 100644index 0000000000..99a2e4c031--- /dev/null+++ b/server/internal/handler/autopilot_webhook_test.go@@ -0,0 +1,216 @@+package handler++import (+ "encoding/json"+ "net/http"+ "strings"+ "testing"+)++// ── Token generation ────────────────────────────────────────────────────────++func TestGenerateWebhookToken_PrefixAndLength(t *testing.T) {+ token, err := generateWebhookToken()+ if err != nil {+ t.Fatalf("generateWebhookToken: %v", err)+ }+ if !strings.HasPrefix(token, "awt_") {+ t.Fatalf("expected awt_ prefix, got %q", token)+ }+ // 32 random bytes -> 43 base64-url chars (no padding).+ if len(token) != len("awt_")+43 {+ t.Fatalf("unexpected token length: %d (token=%q)", len(token), token)+ }+}++func TestGenerateWebhookToken_Uniqueness(t *testing.T) {+ seen := make(map[string]struct{}, 128)+ for i := 0; i < 128; i++ {+ token, err := generateWebhookToken()+ if err != nil {+ t.Fatalf("generateWebhookToken: %v", err)+ }+ if _, dup := seen[token]; dup {+ t.Fatalf("duplicate token after %d generations: %q", i, token)+ }+ seen[token] = struct{}{}+ }+}++func TestGenerateWebhookToken_NoUnsafeURLChars(t *testing.T) {+ token, err := generateWebhookToken()+ if err != nil {+ t.Fatalf("generateWebhookToken: %v", err)+ }+ if strings.ContainsAny(token, "+/= ") {+ t.Fatalf("token has unsafe characters: %q", token)+ }+}++// ── Payload normalization ───────────────────────────────────────────────────++func TestNormalizeWebhookPayload_PreservesCallerProvidedEnvelope(t *testing.T) {+ body := []byte(`{"event":"caller.event","eventPayload":{"k":"v"}}`)+ headers := http.Header{}+ headers.Set("Content-Type", "application/json")++ env, err := normalizeWebhookPayload(body, headers)+ if err != nil {+ t.Fatalf("normalize: %v", err)+ }+ if env.Event != "caller.event" {+ t.Fatalf("event: got %q want %q", env.Event, "caller.event")+ }+ var inner map[string]string+ if err := json.Unmarshal(env.EventPayload, &inner); err != nil {+ t.Fatalf("eventPayload not preserved: %v", err)+ }+ if inner["k"] != "v" {+ t.Fatalf("eventPayload contents lost: %#v", inner)+ }+ if env.Request.ContentType != "application/json" {+ t.Fatalf("contentType: %q", env.Request.ContentType)+ }+ if env.Request.ReceivedAt == "" {+ t.Fatal("receivedAt not set")+ }+}++func TestNormalizeWebhookPayload_GitHubHeaderInferEvent(t *testing.T) {+ body := []byte(`{"action":"opened","pull_request":{"number":7}}`)+ headers := http.Header{}+ headers.Set("Content-Type", "application/json")+ headers.Set("X-GitHub-Event", "pull_request")++ env, err := normalizeWebhookPayload(body, headers)+ if err != nil {+ t.Fatalf("normalize: %v", err)+ }+ if env.Event != "github.pull_request.opened" {+ t.Fatalf("github event: got %q", env.Event)+ }+ // Original body preserved in eventPayload.+ if !strings.Contains(string(env.EventPayload), `"pull_request"`) {+ t.Fatalf("body not preserved in eventPayload: %s", env.EventPayload)+ }+}++func TestNormalizeWebhookPayload_GitLabHeader(t *testing.T) {+ body := []byte(`{"object_kind":"push"}`)+ headers := http.Header{}+ headers.Set("X-Gitlab-Event", "Push Hook")++ env, err := normalizeWebhookPayload(body, headers)+ if err != nil {+ t.Fatalf("normalize: %v", err)+ }+ if env.Event != "gitlab.Push Hook" {+ t.Fatalf("gitlab event: got %q", env.Event)+ }+}++func TestNormalizeWebhookPayload_BodyEventField(t *testing.T) {+ body := []byte(`{"event":"demo.received","data":{"x":1}}`)+ headers := http.Header{}++ env, err := normalizeWebhookPayload(body, headers)+ if err != nil {+ t.Fatalf("normalize: %v", err)+ }+ if env.Event != "demo.received" {+ t.Fatalf("event: %q", env.Event)+ }+}++func TestNormalizeWebhookPayload_BodyTypeFallback(t *testing.T) {+ body := []byte(`{"type":"foo.bar"}`)+ env, err := normalizeWebhookPayload(body, http.Header{})+ if err != nil {+ t.Fatalf("normalize: %v", err)+ }+ if env.Event != "foo.bar" {+ t.Fatalf("event: %q", env.Event)+ }+}++func TestNormalizeWebhookPayload_BodyActionFallback(t *testing.T) {+ body := []byte(`{"action":"opened"}`)+ env, err := normalizeWebhookPayload(body, http.Header{})+ if err != nil {+ t.Fatalf("normalize: %v", err)+ }+ if env.Event != "opened" {+ t.Fatalf("event: %q", env.Event)+ }+}++func TestNormalizeWebhookPayload_DefaultEvent(t *testing.T) {+ body := []byte(`{"foo":"bar"}`)+ env, err := normalizeWebhookPayload(body, http.Header{})+ if err != nil {+ t.Fatalf("normalize: %v", err)+ }+ if env.Event != "webhook.received" {+ t.Fatalf("event: %q", env.Event)+ }+ if !strings.Contains(string(env.EventPayload), `"foo"`) {+ t.Fatalf("event payload not preserved: %s", env.EventPayload)+ }+}++func TestNormalizeWebhookPayload_PreservesArray(t *testing.T) {+ body := []byte(`[{"a":1},{"b":2}]`)+ env, err := normalizeWebhookPayload(body, http.Header{})+ if err != nil {+ t.Fatalf("normalize: %v", err)+ }+ if env.Event != "webhook.received" {+ t.Fatalf("array event: %q", env.Event)+ }+ var arr []map[string]int+ if err := json.Unmarshal(env.EventPayload, &arr); err != nil {+ t.Fatalf("array not preserved: %v", err)+ }+ if len(arr) != 2 {+ t.Fatalf("array length: %d", len(arr))+ }+}++func TestNormalizeWebhookPayload_RejectsInvalidJSON(t *testing.T) {+ if _, err := normalizeWebhookPayload([]byte(`not json`), http.Header{}); err == nil {+ t.Fatal("expected error on invalid JSON")+ }+}++func TestNormalizeWebhookPayload_RejectsScalarBody(t *testing.T) {+ // Bare scalar JSON ("hello", 42) is not a useful webhook payload.+ if _, err := normalizeWebhookPayload([]byte(`"hello"`), http.Header{}); err == nil {+ t.Fatal("expected error on scalar JSON body")+ }+}++func TestNormalizeWebhookPayload_GitHubHeaderWithoutAction(t *testing.T) {+ body := []byte(`{"some":"thing"}`)+ headers := http.Header{}+ headers.Set("X-GitHub-Event", "push")+ env, err := normalizeWebhookPayload(body, headers)+ if err != nil {+ t.Fatalf("normalize: %v", err)+ }+ if env.Event != "github.push" {+ t.Fatalf("event: %q", env.Event)+ }+}++func TestNormalizeWebhookPayload_XEventTypeHeader(t *testing.T) {+ body := []byte(`{"a":1}`)+ headers := http.Header{}+ headers.Set("X-Event-Type", "custom.thing")+ env, err := normalizeWebhookPayload(body, headers)+ if err != nil {+ t.Fatalf("normalize: %v", err)+ }+ if env.Event != "custom.thing" {+ t.Fatalf("event: %q", env.Event)+ }+}diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex ebbe86ea2f..6aa2ea5eba 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -8,6 +8,7 @@ import ("errors""log/slog""net/http"+ "net/netip""github.com/go-chi/chi/v5""github.com/jackc/pgx/v5"@@ -68,6 +69,24 @@ type Config struct {// 3) cron job scheduled (`rollup_task_usage_dashboard_daily`) and// `task_usage_dashboard_rollup_lag_seconds()` < 900.UseDailyRollupForDashboard bool+ // PublicURL is the absolute base URL the API is reachable at from the+ // public internet, with no trailing slash (e.g. "https://app.multica.ai").+ // Used only to build webhook_url responses for autopilot webhook triggers+ // — never for auth, routing, or workspace resolution. Empty when unset,+ // in which case clients fall back to webhook_path + their own origin.+ // Reading the public host from request headers (Host / X-Forwarded-Host)+ // is intentionally avoided so a misconfigured reverse proxy cannot trick+ // the server into minting webhook URLs pointing at an attacker-controlled+ // host.+ PublicURL string+ // TrustedProxies are CIDRs whose source IP we trust to set+ // X-Forwarded-For / X-Real-IP. Empty means "trust nothing": the rate+ // limiter uses r.RemoteAddr exclusively. Populated via the+ // MULTICA_TRUSTED_PROXIES env var (comma-separated CIDRs, e.g.+ // "10.0.0.0/8,127.0.0.1/32"). This is specifically to keep the per-IP+ // webhook limiter from being bypassed by a spoofed XFF on deployments+ // without a header-stripping reverse proxy in front.+ TrustedProxies []netip.Prefix}type Handler struct {@@ -91,6 +110,8 @@ type Handler struct {Analytics analytics.ClientPATCache *auth.PATCacheDaemonTokenCache *auth.DaemonTokenCache+ WebhookRateLimiter WebhookRateLimiter+ WebhookIPRateLimiter WebhookRateLimitercfg Config}@@ -130,6 +151,8 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *eventStorage: store,CFSigner: cfSigner,Analytics: analyticsClient,+ WebhookRateLimiter: NewMemoryWebhookRateLimiter(DefaultWebhookRateLimit()),+ WebhookIPRateLimiter: NewMemoryWebhookIPRateLimiter(DefaultWebhookIPRateLimit()),cfg: cfg,}}diff --git a/server/internal/handler/webhook_rate_limiter.go b/server/internal/handler/webhook_rate_limiter.gonew file mode 100644index 0000000000..aea5183fec--- /dev/null+++ b/server/internal/handler/webhook_rate_limiter.go@@ -0,0 +1,185 @@+package handler++import (+ "context"+ "sync"+ "time"++ "github.com/redis/go-redis/v9"+)++// WebhookRateLimit is a coarse per-token sliding-window limiter.+//+// Defaults: 60 requests per 60s (1 RPS sustained, with bursts up to 60). The+// goal is "stop a misconfigured or malicious sender from hammering us+// indefinitely" — not "shape traffic to a precise budget" — so the+// implementation aims for cheap and good-enough rather than exact.+type WebhookRateLimit struct {+ Limit int // maximum requests per window+ Window time.Duration // sliding window length+}++func DefaultWebhookRateLimit() WebhookRateLimit {+ return WebhookRateLimit{Limit: 60, Window: time.Minute}+}++// DefaultWebhookIPRateLimit is the per-IP coarse budget applied BEFORE the+// trigger lookup. Set lower than the per-token budget on purpose: a single+// IP should rarely sustain more than 30 webhook deliveries / minute across+// all its tokens, while a malicious IP spraying random tokens hits this+// gate before it can probe Postgres.+func DefaultWebhookIPRateLimit() WebhookRateLimit {+ return WebhookRateLimit{Limit: 30, Window: time.Minute}+}++// WebhookRateLimiter is the contract implemented by both the in-memory and+// Redis-backed limiters.+//+// Allow returns true when the request is within budget for the given key,+// false when it should be rejected (HTTP 429).+type WebhookRateLimiter interface {+ Allow(ctx context.Context, key string) bool+}++// ── In-memory implementation ────────────────────────────────────────────────++// memoryWebhookRateLimiter keeps per-key timestamps in a slice and prunes them+// on every call. Adequate for single-node dev / tests; production multi-node+// deployments should use the Redis-backed implementation so rate budgets are+// shared across pods.+type memoryWebhookRateLimiter struct {+ cfg WebhookRateLimit+ mu sync.Mutex+ hit map[string][]time.Time+}++func NewMemoryWebhookRateLimiter(cfg WebhookRateLimit) WebhookRateLimiter {+ return &memoryWebhookRateLimiter{cfg: cfg, hit: make(map[string][]time.Time)}+}++func (l *memoryWebhookRateLimiter) Allow(_ context.Context, key string) bool {+ if l.cfg.Limit <= 0 {+ return true+ }+ now := time.Now()+ cutoff := now.Add(-l.cfg.Window)++ l.mu.Lock()+ defer l.mu.Unlock()++ hits := l.hit[key]+ // Trim entries that fell out of the window.+ keep := hits[:0]+ for _, t := range hits {+ if t.After(cutoff) {+ keep = append(keep, t)+ }+ }+ if len(keep) >= l.cfg.Limit {+ l.hit[key] = keep+ return false+ }+ keep = append(keep, now)+ l.hit[key] = keep+ return true+}++// ── Redis implementation ────────────────────────────────────────────────────++// webhookLimiterKey:<token> is the ZSET we keep timestamps in. Members are+// nanosecond timestamps as strings. Score = same value, so ZREMRANGEBYSCORE+// can drop everything older than the cutoff, then ZCARD tells us the+// remaining count.+const (+ webhookLimiterKeyPrefix = "mul:webhook:rate:"+ webhookIPLimiterKeyPrefix = "mul:webhook:ip:"+)++// webhookLimiterAllowSrc runs the slide-window check atomically on Redis:+//+// KEYS[1] = ZSET key+// ARGV[1] = now (unix nanos as string)+// ARGV[2] = cutoff (unix nanos as string)+// ARGV[3] = limit+// ARGV[4] = expiry seconds (TTL refresh, larger than window)+//+// Returns 1 when the request is admitted, 0 when it should be rejected.+//+// We trim first, then count, then optionally insert. Doing all three in a+// single Lua call avoids the classic "two pods both see count=limit-1 and+// both insert" race.+const webhookLimiterAllowSrc = `+local key = KEYS[1]+local now = tonumber(ARGV[1])+local cutoff = tonumber(ARGV[2])+local limit = tonumber(ARGV[3])+local ttl = tonumber(ARGV[4])+redis.call('ZREMRANGEBYSCORE', key, '-inf', cutoff)+local count = redis.call('ZCARD', key)+if count >= limit then+ return 0+end+redis.call('ZADD', key, now, tostring(now))+redis.call('EXPIRE', key, ttl)+return 1+`++var webhookLimiterAllowScript = redis.NewScript(webhookLimiterAllowSrc)++// webhookLimiterAllowSource exposes the script body for tests that want to+// assert structural invariants (e.g. trim before count before insert)+// without spinning up a real Redis. Lower-cased "Source" makes the+// test-only intent explicit.+func webhookLimiterAllowSource() string { return webhookLimiterAllowSrc }++type redisWebhookRateLimiter struct {+ cfg WebhookRateLimit+ rdb *redis.Client+ keyPrefix string+}++func NewRedisWebhookRateLimiter(rdb *redis.Client, cfg WebhookRateLimit) WebhookRateLimiter {+ return &redisWebhookRateLimiter{cfg: cfg, rdb: rdb, keyPrefix: webhookLimiterKeyPrefix}+}++// NewRedisWebhookIPRateLimiter is the per-IP variant: same sliding-window+// Lua script, different key namespace so the two budgets don't interfere.+func NewRedisWebhookIPRateLimiter(rdb *redis.Client, cfg WebhookRateLimit) WebhookRateLimiter {+ return &redisWebhookRateLimiter{cfg: cfg, rdb: rdb, keyPrefix: webhookIPLimiterKeyPrefix}+}++// NewMemoryWebhookIPRateLimiter is the in-memory per-IP variant used when no+// Redis client is configured. Same per-key semantics as the per-token memory+// limiter — single-node only.+func NewMemoryWebhookIPRateLimiter(cfg WebhookRateLimit) WebhookRateLimiter {+ return NewMemoryWebhookRateLimiter(cfg)+}++func (l *redisWebhookRateLimiter) Allow(ctx context.Context, key string) bool {+ if l.cfg.Limit <= 0 || l.rdb == nil {+ return true+ }+ now := time.Now().UnixNano()+ cutoff := time.Now().Add(-l.cfg.Window).UnixNano()+ ttlSeconds := int64(l.cfg.Window/time.Second) * 2+ if ttlSeconds < 1 {+ ttlSeconds = 1+ }+ prefix := l.keyPrefix+ if prefix == "" {+ prefix = webhookLimiterKeyPrefix+ }+ res, err := webhookLimiterAllowScript.Run(+ ctx,+ l.rdb,+ []string{prefix + key},+ now, cutoff, l.cfg.Limit, ttlSeconds,+ ).Int()+ if err != nil {+ // Fail open on Redis errors — webhook ingress should keep working+ // when the cache hiccups, since the rate limit is a safety net,+ // not a correctness requirement.+ return true+ }+ return res == 1+}diff --git a/server/internal/handler/webhook_rate_limiter_test.go b/server/internal/handler/webhook_rate_limiter_test.gonew file mode 100644index 0000000000..f2ef1d7bbd--- /dev/null+++ b/server/internal/handler/webhook_rate_limiter_test.go@@ -0,0 +1,136 @@+package handler++import (+ "context"+ "strings"+ "testing"+ "time"+)++func TestMemoryWebhookRateLimiter_AllowsBelowLimit(t *testing.T) {+ l := NewMemoryWebhookRateLimiter(WebhookRateLimit{Limit: 3, Window: time.Minute})+ ctx := context.Background()+ for i := 0; i < 3; i++ {+ if !l.Allow(ctx, "tok") {+ t.Fatalf("request %d should be allowed", i)+ }+ }+}++func TestMemoryWebhookRateLimiter_RejectsAboveLimit(t *testing.T) {+ l := NewMemoryWebhookRateLimiter(WebhookRateLimit{Limit: 2, Window: time.Minute})+ ctx := context.Background()+ if !l.Allow(ctx, "tok") {+ t.Fatal("first should pass")+ }+ if !l.Allow(ctx, "tok") {+ t.Fatal("second should pass")+ }+ if l.Allow(ctx, "tok") {+ t.Fatal("third should be rejected")+ }+ // Different key must have its own budget.+ if !l.Allow(ctx, "other") {+ t.Fatal("different key should pass")+ }+}++func TestMemoryWebhookRateLimiter_WindowExpiry(t *testing.T) {+ l := NewMemoryWebhookRateLimiter(WebhookRateLimit{Limit: 1, Window: 10 * time.Millisecond})+ ctx := context.Background()+ if !l.Allow(ctx, "tok") {+ t.Fatal("first should pass")+ }+ if l.Allow(ctx, "tok") {+ t.Fatal("second should fail (within window)")+ }+ time.Sleep(20 * time.Millisecond)+ if !l.Allow(ctx, "tok") {+ t.Fatal("third should pass after window")+ }+}++func TestMemoryWebhookRateLimiter_ZeroLimitDisabled(t *testing.T) {+ l := NewMemoryWebhookRateLimiter(WebhookRateLimit{Limit: 0, Window: time.Minute})+ ctx := context.Background()+ for i := 0; i < 100; i++ {+ if !l.Allow(ctx, "tok") {+ t.Fatalf("Limit=0 should be unbounded, rejected at %d", i)+ }+ }+}++// TestWebhookLimiterLuaScript_StructureGuard pins the Lua script so any future+// edit that reorders trim/count/insert (or drops EXPIRE) is caught even when+// no live Redis is available to the test process. The per-pod race the script+// guards against ("two pods both see count = limit-1 and both insert") only+// triggers if the three calls run atomically; this regression guard is the+// cheap-but-effective complement to the live-Redis test below.+func TestWebhookLimiterLuaScript_StructureGuard(t *testing.T) {+ // redis.NewScript stores the body, so we just sanity-check ordering by+ // matching the source string. The exact whitespace is brittle but the+ // alternative (Lua AST parsing) is overkill for a 10-line script.+ src := webhookLimiterAllowSource()+ mustBefore := func(a, b string) {+ t.Helper()+ ia, ib := strings.Index(src, a), strings.Index(src, b)+ if ia < 0 || ib < 0 {+ t.Fatalf("script must contain %q and %q, src=%s", a, b, src)+ }+ if ia >= ib {+ t.Fatalf("expected %q to appear before %q, src=%s", a, b, src)+ }+ }+ mustBefore("ZREMRANGEBYSCORE", "ZCARD")+ mustBefore("ZCARD", "ZADD")+ mustBefore("ZADD", "EXPIRE")+}++func TestRedisWebhookRateLimiter_RejectsAboveLimit(t *testing.T) {+ rdb := newRedisTestClient(t)+ defer rdb.Close()++ l := NewRedisWebhookRateLimiter(rdb, WebhookRateLimit{Limit: 3, Window: time.Minute})+ ctx := context.Background()+ for i := 0; i < 3; i++ {+ if !l.Allow(ctx, "tok") {+ t.Fatalf("request %d should be allowed", i)+ }+ }+ if l.Allow(ctx, "tok") {+ t.Fatal("fourth request should be rejected")+ }+ // Different key has its own budget.+ if !l.Allow(ctx, "other") {+ t.Fatal("different key should pass")+ }+}++func TestRedisWebhookIPRateLimiter_HasSeparateBudgetFromTokenLimiter(t *testing.T) {+ // Per-IP and per-token use the SAME Lua script but DIFFERENT key+ // prefixes. Exhausting one budget must not affect the other —+ // regression-protect by exhausting per-token then proving per-IP is+ // untouched against the same Redis instance.+ rdb := newRedisTestClient(t)+ defer rdb.Close()++ tok := NewRedisWebhookRateLimiter(rdb, WebhookRateLimit{Limit: 1, Window: time.Minute})+ ip := NewRedisWebhookIPRateLimiter(rdb, WebhookRateLimit{Limit: 2, Window: time.Minute})+ ctx := context.Background()+ if !tok.Allow(ctx, "alice") {+ t.Fatal("token limiter first request should pass")+ }+ if tok.Allow(ctx, "alice") {+ t.Fatal("token limiter second request should be rejected")+ }+ // IP limiter must still have its full budget.+ if !ip.Allow(ctx, "alice") {+ t.Fatal("IP limiter first request should pass")+ }+ if !ip.Allow(ctx, "alice") {+ t.Fatal("IP limiter second request should pass")+ }+ if ip.Allow(ctx, "alice") {+ t.Fatal("IP limiter third request should be rejected")+ }+}diff --git a/server/internal/middleware/request_logger.go b/server/internal/middleware/request_logger.goindex a9bbee4058..98e6be1a27 100644--- a/server/internal/middleware/request_logger.go+++ b/server/internal/middleware/request_logger.go@@ -2,6 +2,7 @@ package middlewareimport ("bytes"+ "context""log/slog""net/http""strings"@@ -10,6 +11,64 @@ import (chimw "github.com/go-chi/chi/v5/middleware")+// webhookTriggerIDKeyType is unexported so foreign packages cannot collide on+// the context key — they go through SetWebhookTriggerID instead.+type webhookTriggerIDKeyType struct{}++var webhookTriggerIDKey = webhookTriggerIDKeyType{}++// SetWebhookTriggerID stashes the resolved trigger ID on the request context+// so the request logger can include it in the audit line without revealing+// the bearer token in the URL path. Called by the webhook handler right after+// the trigger row is looked up.+//+// Mutates `*r` in place so the wrapping middleware (which is still holding the+// original `*http.Request`) reads the value back out of context after+// ServeHTTP returns. Reassigning a local `r` variable would not propagate the+// new context back up to the caller, which is the trap a previous version of+// this helper fell into.+func SetWebhookTriggerID(r *http.Request, triggerID string) {+ if triggerID == "" {+ return+ }+ *r = *r.WithContext(context.WithValue(r.Context(), webhookTriggerIDKey, triggerID))+}++// webhookTriggerIDFromContext returns the trigger ID stashed by+// SetWebhookTriggerID, or "" when none was set.+func webhookTriggerIDFromContext(ctx context.Context) string {+ v, _ := ctx.Value(webhookTriggerIDKey).(string)+ return v+}++// webhookIngressPathPrefix is the public webhook ingress path. The path+// segment after this prefix IS a bearer credential, so the logger must+// redact it — see redactWebhookPath.+const webhookIngressPathPrefix = "/api/webhooks/autopilots/"++// redactWebhookPath returns a logger-safe version of a request path. For+// the autopilot webhook ingress path the trailing token segment is replaced+// with "[redacted]"; every other path passes through untouched.+//+// Why this exists: r.URL.Path for a successful webhook delivery is+// "/api/webhooks/autopilots/awt_<32-byte-base64>", and the token is the+// only credential gating the route. Without redaction, every successful+// delivery prints a replayable URL into the structured log stream.+func redactWebhookPath(path string) string {+ if !strings.HasPrefix(path, webhookIngressPathPrefix) {+ return path+ }+ rest := path[len(webhookIngressPathPrefix):]+ if rest == "" {+ return path+ }+ // Preserve any sub-path after the token (currently none, but defensive).+ if slash := strings.IndexByte(rest, '/'); slash >= 0 {+ return webhookIngressPathPrefix + "[redacted]" + rest[slash:]+ }+ return webhookIngressPathPrefix + "[redacted]"+}+// boundedBuffer captures up to Cap bytes from a stream then silently drops the// rest. Used by RequestLogger so a large response body cannot blow up logger// memory while we mirror just enough bytes to classify the response.@@ -77,7 +136,7 @@ func RequestLogger(next http.Handler) http.Handler {attrs := []any{"method", r.Method,- "path", r.URL.Path,+ "path", redactWebhookPath(r.URL.Path),"status", status,"duration", duration.Round(time.Microsecond).String(),}@@ -87,6 +146,9 @@ func RequestLogger(next http.Handler) http.Handler {if uid := r.Header.Get("X-User-ID"); uid != "" {attrs = append(attrs, "user_id", uid)}+ if tid := webhookTriggerIDFromContext(r.Context()); tid != "" {+ attrs = append(attrs, "webhook_trigger_id", tid)+ }if platform, version, os := ClientMetadataFromContext(r.Context()); platform != "" || version != "" || os != "" {if platform != "" {attrs = append(attrs, "client_platform", platform)diff --git a/server/internal/middleware/request_logger_test.go b/server/internal/middleware/request_logger_test.goindex 242bc81a82..91e91dc706 100644--- a/server/internal/middleware/request_logger_test.go+++ b/server/internal/middleware/request_logger_test.go@@ -138,6 +138,65 @@ func TestRequestLogger_LargeBodyBeyondCaptureLimit(t *testing.T) {requireLogLevel(t, logs, "WARN", "INFO", "ERROR")}+func TestRedactWebhookPath(t *testing.T) {+ t.Parallel()+ cases := []struct {+ in, want string+ }{+ {"/api/webhooks/autopilots/awt_secret", "/api/webhooks/autopilots/[redacted]"},+ {"/api/webhooks/autopilots/awt_secret/", "/api/webhooks/autopilots/[redacted]/"},+ {"/api/webhooks/autopilots/", "/api/webhooks/autopilots/"},+ {"/api/webhooks/github", "/api/webhooks/github"},+ {"/api/runtimes/abc", "/api/runtimes/abc"},+ {"/", "/"},+ }+ for _, tc := range cases {+ if got := redactWebhookPath(tc.in); got != tc.want {+ t.Errorf("redactWebhookPath(%q) = %q, want %q", tc.in, got, tc.want)+ }+ }+}++func TestRequestLogger_RedactsWebhookTokenInPath(t *testing.T) {+ logs := withCapturedLogs(t)+ handler := RequestLogger(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusOK)+ }))+ req := httptest.NewRequest(http.MethodPost, "/api/webhooks/autopilots/awt_supersecret", nil)+ handler.ServeHTTP(httptest.NewRecorder(), req)+ out := logs.String()+ if strings.Contains(out, "awt_supersecret") {+ t.Fatalf("token leaked into logs:\n%s", out)+ }+ if !strings.Contains(out, "[redacted]") {+ t.Fatalf("expected [redacted] in logs:\n%s", out)+ }+}++func TestRequestLogger_IncludesWebhookTriggerIDFromContext(t *testing.T) {+ // Exercise the real production flow: the webhook handler resolves the+ // trigger, then calls SetWebhookTriggerID(r, ...) which mutates *r in+ // place. After the handler returns, the wrapping RequestLogger+ // middleware reads the stashed ID off the (now-updated) request+ // context. If SetWebhookTriggerID didn't mutate in place, the+ // middleware would see the old context and the trigger ID would+ // silently drop from the audit line.+ logs := withCapturedLogs(t)+ handler := RequestLogger(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ SetWebhookTriggerID(r, "trigger-abc")+ w.WriteHeader(http.StatusOK)+ }))+ req := httptest.NewRequest(http.MethodPost, "/api/webhooks/autopilots/awt_supersecret", nil)+ handler.ServeHTTP(httptest.NewRecorder(), req)+ out := logs.String()+ if !strings.Contains(out, "webhook_trigger_id=trigger-abc") {+ t.Fatalf("expected webhook_trigger_id in logs, got:\n%s", out)+ }+ if strings.Contains(out, "awt_supersecret") {+ t.Fatalf("token leaked into logs:\n%s", out)+ }+}+func TestIsSoftNotFound(t *testing.T) {t.Parallel()diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex 8f0648f25a..d557d2f1bd 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -130,7 +130,7 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopiqtx := s.Queries.WithTx(tx)title := s.interpolateTemplate(ap)- description := s.buildIssueDescription(ap)+ description := s.buildIssueDescription(ap, *run)duplicate, foundDuplicate, err := issueguard.LockAndFindActiveDuplicate(ctx, qtx, ap.WorkspaceID, pgtype.UUID{}, pgtype.UUID{}, title, false)if err != nil {@@ -651,12 +651,57 @@ func autopilotRunDurationMS(run db.AutopilotRun) int64 {// buildIssueDescription appends an autopilot system instruction to the// user-provided description, asking the agent to rename the issue after-// it understands the actual work.-func (s *AutopilotService) buildIssueDescription(ap db.Autopilot) pgtype.Text {+// it understands the actual work. For webhook-sourced runs, also appends+// a payload section so the agent has the event context inline (otherwise+// the agent only sees the issue body, never the run's trigger_payload).+func (s *AutopilotService) buildIssueDescription(ap db.Autopilot, run db.AutopilotRun) pgtype.Text {now := time.Now().UTC().Format("2006-01-02 15:04 UTC")- note := fmt.Sprintf("\n\n---\n*Autopilot run triggered at %s. After starting work, rename this issue to accurately reflect what you are doing.*", now)- base := ap.Description.String- return pgtype.Text{String: base + note, Valid: true}+ var b strings.Builder+ b.WriteString(ap.Description.String)+ b.WriteString("\n\n---\n*Autopilot run triggered at ")+ b.WriteString(now)+ b.WriteString(". After starting work, rename this issue to accurately reflect what you are doing.*")++ if run.Source == "webhook" && len(run.TriggerPayload) > 0 {+ event := "webhook.received"+ var payloadJSON []byte+ var env struct {+ Event string `json:"event"`+ EventPayload json.RawMessage `json:"eventPayload"`+ }+ if err := json.Unmarshal(run.TriggerPayload, &env); err == nil {+ if env.Event != "" {+ event = env.Event+ }+ if len(env.EventPayload) > 0 {+ if pretty, err := prettifyJSON(env.EventPayload); err == nil {+ payloadJSON = pretty+ }+ }+ }+ if len(payloadJSON) == 0 {+ if pretty, err := prettifyJSON(run.TriggerPayload); err == nil {+ payloadJSON = pretty+ } else {+ payloadJSON = run.TriggerPayload+ }+ }+ b.WriteString("\n\nWebhook event: ")+ b.WriteString(event)+ b.WriteString("\n\nWebhook payload:\n```json\n")+ b.Write(payloadJSON)+ b.WriteString("\n```")+ }++ return pgtype.Text{String: b.String(), Valid: true}+}++func prettifyJSON(raw []byte) ([]byte, error) {+ var v any+ if err := json.Unmarshal(raw, &v); err != nil {+ return nil, err+ }+ return json.MarshalIndent(v, "", " ")}// interpolateTemplate replaces {{date}} in the issue title template.diff --git a/server/internal/service/autopilot_test.go b/server/internal/service/autopilot_test.goindex 5666b4119c..9205fa24e7 100644--- a/server/internal/service/autopilot_test.go+++ b/server/internal/service/autopilot_test.go@@ -1,6 +1,12 @@package service-import "testing"+import (+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)func TestAutopilotErrorType(t *testing.T) {cases := map[string]string{@@ -18,3 +24,71 @@ func TestAutopilotErrorType(t *testing.T) {}}}++func TestBuildIssueDescription_NoTriggerPayload(t *testing.T) {+ s := &AutopilotService{}+ ap := db.Autopilot{Description: pgtype.Text{String: "do the thing", Valid: true}}+ run := db.AutopilotRun{Source: "schedule"}++ got := s.buildIssueDescription(ap, run)+ if !strings.HasPrefix(got.String, "do the thing") {+ t.Fatalf("description should preserve user description: %q", got.String)+ }+ if !strings.Contains(got.String, "Autopilot run triggered at") {+ t.Fatalf("description should include schedule note: %q", got.String)+ }+ if strings.Contains(got.String, "Webhook event") {+ t.Fatalf("description must not mention webhook for non-webhook source: %q", got.String)+ }+}++func TestBuildIssueDescription_WithWebhookPayload(t *testing.T) {+ s := &AutopilotService{}+ ap := db.Autopilot{Description: pgtype.Text{String: "watch PRs", Valid: true}}+ payload := []byte(`{"event":"github.pull_request.opened","eventPayload":{"number":7},"request":{"receivedAt":"2026-05-09T00:00:00Z","contentType":"application/json"}}`)+ run := db.AutopilotRun{Source: "webhook", TriggerPayload: payload}++ got := s.buildIssueDescription(ap, run)+ if !strings.HasPrefix(got.String, "watch PRs") {+ t.Fatalf("user description not preserved: %q", got.String)+ }+ if !strings.Contains(got.String, "Webhook event: github.pull_request.opened") {+ t.Fatalf("description should include webhook event line: %q", got.String)+ }+ if !strings.Contains(got.String, "\"number\": 7") && !strings.Contains(got.String, "\"number\":7") {+ t.Fatalf("description should include payload json: %q", got.String)+ }+ // Italic schedule line must come before the webhook block.+ idxItalic := strings.Index(got.String, "*Autopilot run triggered")+ idxWebhook := strings.Index(got.String, "Webhook event")+ if idxItalic < 0 || idxWebhook < 0 || idxItalic > idxWebhook {+ t.Fatalf("italic line should appear before webhook block: %q", got.String)+ }+}++func TestBuildIssueDescription_WebhookSourceMissingEnvelope(t *testing.T) {+ // Defensive: if a future caller stuffs a non-envelope JSON object into+ // trigger_payload, we should still emit a webhook block with sensible+ // defaults rather than skipping the section entirely.+ s := &AutopilotService{}+ ap := db.Autopilot{Description: pgtype.Text{String: "thing", Valid: true}}+ payload := []byte(`{"raw":"missing envelope"}`)+ run := db.AutopilotRun{Source: "webhook", TriggerPayload: payload}++ got := s.buildIssueDescription(ap, run)+ if !strings.Contains(got.String, "Webhook event:") {+ t.Fatalf("should still emit webhook block: %q", got.String)+ }+}++func TestBuildIssueDescription_NonWebhookSourceWithPayloadIgnored(t *testing.T) {+ // Manual / schedule with a payload should not get a webhook block.+ s := &AutopilotService{}+ ap := db.Autopilot{Description: pgtype.Text{String: "thing", Valid: true}}+ run := db.AutopilotRun{Source: "manual", TriggerPayload: []byte(`{"event":"x.y"}`)}++ got := s.buildIssueDescription(ap, run)+ if strings.Contains(got.String, "Webhook event") {+ t.Fatalf("non-webhook source should not include webhook block: %q", got.String)+ }+}diff --git a/server/migrations/091_autopilot_webhook_triggers.down.sql b/server/migrations/091_autopilot_webhook_triggers.down.sqlnew file mode 100644index 0000000000..0c7ab82d33--- /dev/null+++ b/server/migrations/091_autopilot_webhook_triggers.down.sql@@ -0,0 +1 @@+DROP INDEX IF EXISTS idx_autopilot_trigger_webhook_token;diff --git a/server/migrations/091_autopilot_webhook_triggers.up.sql b/server/migrations/091_autopilot_webhook_triggers.up.sqlnew file mode 100644index 0000000000..065dba64d2--- /dev/null+++ b/server/migrations/091_autopilot_webhook_triggers.up.sql@@ -0,0 +1,8 @@+-- Webhook trigger ingress: enforce uniqueness on webhook tokens so the+-- public ingress route /api/webhooks/autopilots/{token} can resolve a trigger+-- in O(1) without ambiguity. Partial index keeps the constraint scoped to+-- webhook-kind triggers only — schedule/api triggers leave webhook_token NULL+-- and don't participate in the unique key.+CREATE UNIQUE INDEX IF NOT EXISTS idx_autopilot_trigger_webhook_token+ON autopilot_trigger(webhook_token)+WHERE kind = 'webhook' AND webhook_token IS NOT NULL;diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex 0277ff151b..a2ddc58740 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -1,6 +1,6 @@// Code generated by sqlc. DO NOT EDIT.// versions:-// sqlc v1.30.0+// sqlc v1.31.1// source: autopilot.sqlpackage db@@ -478,6 +478,56 @@ func (q *Queries) GetAutopilotTrigger(ctx context.Context, id pgtype.UUID) (Autoreturn i, err}+const getWebhookTriggerByToken = `-- name: GetWebhookTriggerByToken :one+SELECT t.id, t.autopilot_id, t.kind, t.enabled, t.cron_expression, t.timezone, t.next_run_at, t.webhook_token, t.label, t.last_fired_at, t.created_at, t.updated_at, a.workspace_id AS autopilot_workspace_id+FROM autopilot_trigger t+JOIN autopilot a ON a.id = t.autopilot_id+WHERE t.kind = 'webhook'+ AND t.webhook_token = $1+`++type GetWebhookTriggerByTokenRow struct {+ ID pgtype.UUID `json:"id"`+ AutopilotID pgtype.UUID `json:"autopilot_id"`+ Kind string `json:"kind"`+ Enabled bool `json:"enabled"`+ CronExpression pgtype.Text `json:"cron_expression"`+ Timezone pgtype.Text `json:"timezone"`+ NextRunAt pgtype.Timestamptz `json:"next_run_at"`+ WebhookToken pgtype.Text `json:"webhook_token"`+ Label pgtype.Text `json:"label"`+ LastFiredAt pgtype.Timestamptz `json:"last_fired_at"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ AutopilotWorkspaceID pgtype.UUID `json:"autopilot_workspace_id"`+}++// Look up a webhook trigger by its public bearer token. Joined to autopilot+// so the webhook handler can derive the workspace from the trigger's parent+// without trusting any request header. The handler still re-loads the+// Autopilot via GetAutopilot and cross-checks WorkspaceID matches the row's+// autopilot_workspace_id.+func (q *Queries) GetWebhookTriggerByToken(ctx context.Context, webhookToken pgtype.Text) (GetWebhookTriggerByTokenRow, error) {+ row := q.db.QueryRow(ctx, getWebhookTriggerByToken, webhookToken)+ var i GetWebhookTriggerByTokenRow+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.Kind,+ &i.Enabled,+ &i.CronExpression,+ &i.Timezone,+ &i.NextRunAt,+ &i.WebhookToken,+ &i.Label,+ &i.LastFiredAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.AutopilotWorkspaceID,+ )+ return i, err+}+const listAutopilotRuns = `-- name: ListAutopilotRuns :manySELECT id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at FROM autopilot_runWHERE autopilot_id = $1@@ -686,6 +736,43 @@ func (q *Queries) RecoverLostTriggers(ctx context.Context) ([]RecoverLostTriggerreturn items, nil}+const rotateAutopilotTriggerWebhookToken = `-- name: RotateAutopilotTriggerWebhookToken :one+UPDATE autopilot_trigger+SET webhook_token = $2,+ updated_at = now()+WHERE id = $1+ AND kind = 'webhook'+RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at+`++type RotateAutopilotTriggerWebhookTokenParams struct {+ ID pgtype.UUID `json:"id"`+ WebhookToken pgtype.Text `json:"webhook_token"`+}++// Rotates the bearer token for a webhook trigger. Restricted to kind='webhook'+// so an accidental call against a schedule/api trigger is a no-op (returns no+// rows) rather than corrupting unrelated state.+func (q *Queries) RotateAutopilotTriggerWebhookToken(ctx context.Context, arg RotateAutopilotTriggerWebhookTokenParams) (AutopilotTrigger, error) {+ row := q.db.QueryRow(ctx, rotateAutopilotTriggerWebhookToken, arg.ID, arg.WebhookToken)+ var i AutopilotTrigger+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.Kind,+ &i.Enabled,+ &i.CronExpression,+ &i.Timezone,+ &i.NextRunAt,+ &i.WebhookToken,+ &i.Label,+ &i.LastFiredAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}+const selectAutopilotsExceedingFailureThreshold = `-- name: SelectAutopilotsExceedingFailureThreshold :manyWITH stats AS (@@ -768,6 +855,44 @@ func (q *Queries) SelectAutopilotsExceedingFailureThreshold(ctx context.Context,return items, nil}+const setAutopilotTriggerWebhookToken = `-- name: SetAutopilotTriggerWebhookToken :one+UPDATE autopilot_trigger+SET webhook_token = $2,+ updated_at = now()+WHERE id = $1+RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at+`++type SetAutopilotTriggerWebhookTokenParams struct {+ ID pgtype.UUID `json:"id"`+ WebhookToken pgtype.Text `json:"webhook_token"`+}++// Sets the webhook token at creation time. CreateAutopilotTrigger inserts the+// row first (using its full 8-arg signature), then this query attaches the+// token. Splitting the create + token-set keeps the existing CreateAutopilotTrigger+// query usable by the schedule path without forcing every caller to think+// about webhook_token.+func (q *Queries) SetAutopilotTriggerWebhookToken(ctx context.Context, arg SetAutopilotTriggerWebhookTokenParams) (AutopilotTrigger, error) {+ row := q.db.QueryRow(ctx, setAutopilotTriggerWebhookToken, arg.ID, arg.WebhookToken)+ var i AutopilotTrigger+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.Kind,+ &i.Enabled,+ &i.CronExpression,+ &i.Timezone,+ &i.NextRunAt,+ &i.WebhookToken,+ &i.Label,+ &i.LastFiredAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}+const systemPauseAutopilot = `-- name: SystemPauseAutopilot :oneUPDATE autopilotSET status = 'paused', updated_at = now()@@ -800,6 +925,22 @@ func (q *Queries) SystemPauseAutopilot(ctx context.Context, id pgtype.UUID) (Autreturn i, err}+const touchAutopilotTriggerFiredAt = `-- name: TouchAutopilotTriggerFiredAt :exec+UPDATE autopilot_trigger+SET last_fired_at = now(),+ updated_at = now()+WHERE id = $1+`++// Bumps last_fired_at after a webhook fires, regardless of whether the+// dispatch succeeded, was admission-skipped, or even if Autopilot status+// transitioned to paused/disabled at exactly the wrong moment. Disabled /+// paused early-return paths in the handler never call this.+func (q *Queries) TouchAutopilotTriggerFiredAt(ctx context.Context, id pgtype.UUID) error {+ _, err := q.db.Exec(ctx, touchAutopilotTriggerFiredAt, id)+ return err+}+const updateAutopilot = `-- name: UpdateAutopilot :oneUPDATE autopilot SETtitle = COALESCE($2, title),diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sqlindex f46962378c..83e6355af6 100644--- a/server/pkg/db/queries/autopilot.sql+++ b/server/pkg/db/queries/autopilot.sql@@ -89,6 +89,51 @@ SET next_run_at = sqlc.narg('next_run_at'),updated_at = now()WHERE id = $1;+-- name: GetWebhookTriggerByToken :one+-- Look up a webhook trigger by its public bearer token. Joined to autopilot+-- so the webhook handler can derive the workspace from the trigger's parent+-- without trusting any request header. The handler still re-loads the+-- Autopilot via GetAutopilot and cross-checks WorkspaceID matches the row's+-- autopilot_workspace_id.+SELECT t.*, a.workspace_id AS autopilot_workspace_id+FROM autopilot_trigger t+JOIN autopilot a ON a.id = t.autopilot_id+WHERE t.kind = 'webhook'+ AND t.webhook_token = $1;++-- name: TouchAutopilotTriggerFiredAt :exec+-- Bumps last_fired_at after a webhook fires, regardless of whether the+-- dispatch succeeded, was admission-skipped, or even if Autopilot status+-- transitioned to paused/disabled at exactly the wrong moment. Disabled /+-- paused early-return paths in the handler never call this.+UPDATE autopilot_trigger+SET last_fired_at = now(),+ updated_at = now()+WHERE id = $1;++-- name: RotateAutopilotTriggerWebhookToken :one+-- Rotates the bearer token for a webhook trigger. Restricted to kind='webhook'+-- so an accidental call against a schedule/api trigger is a no-op (returns no+-- rows) rather than corrupting unrelated state.+UPDATE autopilot_trigger+SET webhook_token = $2,+ updated_at = now()+WHERE id = $1+ AND kind = 'webhook'+RETURNING *;++-- name: SetAutopilotTriggerWebhookToken :one+-- Sets the webhook token at creation time. CreateAutopilotTrigger inserts the+-- row first (using its full 8-arg signature), then this query attaches the+-- token. Splitting the create + token-set keeps the existing CreateAutopilotTrigger+-- query usable by the schedule path without forcing every caller to think+-- about webhook_token.+UPDATE autopilot_trigger+SET webhook_token = $2,+ updated_at = now()+WHERE id = $1+RETURNING *;+-- =====================-- Autopilot Run Management-- =====================