Skip to content

Self-improving AI Employees for everyone

fix(stripe): make stripeReceive fire on a canvas Run and when deployed

trohitgfe2efc198804
diff --git a/CLAUDE.md b/CLAUDE.md
index 2b0a6077..70bf8a01 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -31,7 +31,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Browser](./docs-internal/browser.md)** | Current `browser` node: installed Chrome/Edge/Chromium in a dedicated profile rendered inside the workspace by default (`BROWSER_RUNTIME=system`, `BROWSER_HEADLESS=true`) and pinned browser-use CLI. Chrome for Testing requires explicit `BROWSER_RUNTIME=testing`. System mode retains the native user agent and OS password-store/keychain integration; basic/mock keychain flags are restricted to testing mode. Includes persistent employee/shared profiles (the Credentials / Connectors "Web browser" panel adds, deletes and imports logins from a session file; the node's profile dropdown lists only the caller's profiles, via `current_load_options_principal()`), session leases, agent/user handoff, network policy, screenshots as workspace FileRefs and authenticated `/ws/browser` live viewing. Plugin-owned installation is lazy (`_install_chrome.py`, `_install_bu.py`); importing or shutting down the plugin never installs it. Replaces the former agent-browser and separate `browserHarness` implementations. |
| **[Browser Workspace](./docs-internal/browser_workspace.md)** | Home and Dev share `WorkspaceTabs` and `BrowserWorkspace`: Browser / Canvas / Mobile, capability-based discovery, binary JPEG frames, bounded frame credit and decoding, Take control / Hand back, visibility cleanup and payload-free opt-in diagnostics. The Browser node's parameter panel shows the same viewer, and the Dev dock opens on its Browser tab when an agent in the open workflow asks for help (`browser_updated`). Mobile shows the managed local Android phone. |
| **[WhatsApp Business Service](./docs-internal/whatsapp_business_service.md)** | Official Meta Cloud API plugin in [`server/nodes/whatsapp_business/`](./server/nodes/whatsapp_business/) — **distinct from `nodes/whatsapp/`**, which is a personal account over an unofficial Go bridge; they share no node type, credential or palette group. Four nodes: `whatsappBusinessSend` (10 ops — Meta models message type as a *field* on one `/messages` endpoint, so text / media / template / interactive are operations, not nodes), `whatsappBusinessMedia` (the one genuinely separate endpoint family), and the `Receive` / `Status` triggers (kept separate because a canary trigger registers exactly one CloudEvents type). `phone_number_id` is deliberately **absent from Params** — on a dual-purpose ActionNode `execute_as_tool` merges `{**node_params, **tool_args}`, so a declared field is model-settable and a prompt injection could choose the sending identity; it comes from the credential only. Webhook via `register_webhook_source` on the shared catch-all, `X-Hub-Signature-256` HMAC failing closed, composite `wamid:status` dedup ids so `sent→delivered→read` don't collapse. |
-| **[Stripe Service](./docs-internal/stripe_service.md)** | Stripe CLI integration — `stripeAction` (CLI pass-through) + `stripeReceive` (signed-webhook trigger; it never fires today — deploy skips it and a canvas Run waits forever, see the doc's Known gap). Reference plugin for the Wave 12 event framework AND the **CLI-managed-auth pattern**: browser OAuth via `stripe login --non-interactive` + `--complete <url>` (URL extracted from `next_step` shell command via `shlex.split`) + auto-installed binary (`ensure_stripe_cli` from GitHub releases) + marker-token reuse of `auth_service.store_oauth_tokens` + CloudEvents-shaped `broadcast_credential_event("credential.oauth.connected" \| ".disconnected", provider=...)` — zero per-provider hardcoding in the frontend. Daemon stdout/stderr ingested via `ProcessService`'s `line_handler` callback (no log-file tailing); credential gate routed through `await self.has_credential()` so non-api-key auth (`is_logged_in()`) plugs in via subclass override. |
+| **[Stripe Service](./docs-internal/stripe_service.md)** | Stripe CLI integration — `stripeAction` (CLI pass-through) + `stripeReceive` (signed-webhook trigger, on a canvas Run and deployed: every Stripe event travels under one CloudEvents type, `com.opencompany.stripe.event.received`, with the Stripe type in `subject` and `data.event_type`, where the node's own `build_filter` reads it; the source shapes the payload once, wakes the in-process waiter through `WebhookSource.handle` and reaches deployed listeners through `dispatch.emit`; deploying starts `stripe listen` through the generic `TriggerNode.prepare_deployment` hook, at Start and at the boot re-arm). Reference plugin for the Wave 12 event framework AND the **CLI-managed-auth pattern**: browser OAuth via `stripe login --non-interactive` + `--complete <url>` (URL extracted from `next_step` shell command via `shlex.split`) + auto-installed binary (`ensure_stripe_cli` from GitHub releases) + marker-token reuse of `auth_service.store_oauth_tokens` + CloudEvents-shaped `broadcast_credential_event("credential.oauth.connected" \| ".disconnected", provider=...)` — zero per-provider hardcoding in the frontend. Daemon stdout/stderr ingested via `ProcessService`'s `line_handler` callback (no log-file tailing); credential gate routed through `await self.has_credential()` so non-api-key auth (`is_logged_in()`) plugs in via subclass override. |
| **[Vercel Service](./docs-internal/vercel_service.md)** | Vercel CLI integration — `vercelAction` (deploy / inspect / list + `custom` CLI passthrough; AI tool `vercel`). Second reference for the CLI-managed-auth pattern: the **device-flow variant** (`vercel login` is one blocking process — no two-step `--complete`; direct `create_subprocess_exec` + chunk-based banner read for the code-embedding URL, pumps drain pipes for the process lifetime, success gate = auth.json mtime advance + sniff). Dual auth: optional `vercel_token` field (injected as `VERCEL_TOKEN` env, never argv) OR CLI login with marker tokens. All invocations pin `--global-config <DATA_DIR>/vercel/` (the `CLAUDE_CONFIG_DIR` isolation idiom). `bun add` into the shared packages tree (pinned version, via `core/js_runtime.add_package`; the CLI runs on bun). First-deploy project guard raises `NodeUserError` instead of letting Vercel derive an invalid name from the workspace dir. Shipped with the generic OAuthConnect change: Login gates on **required** fields only, so optional fields never block CLI login. |
| **[GitHub Service](./docs-internal/github_service.md)** | GitHub CLI integration — `githubAction` (repo_clone / pr_create / pr_list / pr_merge / issue_create / issue_list + `custom` passthrough; AI tool `github`). **Strict Stripe pattern: the gh CLI owns its own auth** — no token stored/injected by OpenCompany, no auth pre-flight (gh's own error surfaces), marker OAuth row for the modal badge, fieldless catalogue entry. Login = spawned `gh auth login --hostname github.com --git-protocol https --web` — source-verified: headless takes the `isInteractive=false` branch (no Press-Enter), prints one-time code + `github.com/login/device` URL on stderr; the modal shows the code via the generic `verificationCode` plumbing (`useCredentialPanel` → `OAuthConnect`). `login_env()` strips `GH_TOKEN`/`GITHUB_TOKEN` (login aborts otherwise). Success gate = `gh auth status` exit 0, then best-effort **`gh auth setup-git`** (official bridge — the future git node needs zero auth code). gh binary: **project-local, pooch-driven** (temporal `_install.py` idiom) — pinned release under `package_dir("gh")`, system gh never consulted (auth state still shared: gh config paths are user-level). Palette group `vcs`. |
| **[Cloudflare Service](./docs-internal/cloudflare_service.md)** | Cloudflare CLI integration — `cloudflareAction` (whoami / zones_list / dns_records CRUD / `graphql_query` / `custom` passthrough; AI tool `cloudflare`) wrapping the official `cf` CLI (npm `[email protected]`, technical preview — "the next version of Wrangler"). **Two cf-specific variants of the CLI-managed-auth pattern**: (1) the CLI opens the browser ITSELF (loopback PKCE callback on fixed port 8877) so the login handler proxies nothing — single-flight guard (concurrent logins collide on the fixed port) + never-kill-the-shim invariant (killing bun's `cf.exe` launcher shim orphans the child bun process holding 8877); success gate = `cf auth whoami` JSON (`authenticated: true` — cf exits 0 in BOTH auth states). (2) **Fixed 86-scope OAuth grant with no `--scopes` flag** — only `dns_analytics:read` for analytics; no RUM/zone-analytics OAuth scope exists anywhere, so the optional `cloudflare_api_token` field (injected as `CLOUDFLARE_API_TOKEN`, cf's documented first-priority credential) is the only path to Web Analytics/RUM + the GraphQL Analytics API. `graphql_query` op POSTs the official `client/v4/graphql` endpoint directly (outside the OpenAPI schema cf/SDKs are generated from) — the replacement for the sunsetted Zone Analytics REST API; needs `Account > Account Analytics > Read`. Pinned `bun add` into the shared packages tree (the CLI declares `engines.node >= 22`, which bun ignores — verified running on bun with no Node on PATH), system cf never consulted (preview argv surface drifts across versions). Palette group `deployment`. |
diff --git a/docs-internal/discord_service.md b/docs-internal/discord_service.md
index 852ef343..405e481a 100644
--- a/docs-internal/discord_service.md
+++ b/docs-internal/discord_service.md
@@ -250,7 +250,7 @@ whole plugin silently disappear rather than report anything.
`WORKFLOW_TRIGGER_TYPES` is a silent failure: `TriggerManager.find_trigger_nodes`
filters on it, so deploy ignores the node with no listener and no warning (see
the comment inside `WORKFLOW_TRIGGER_TYPES` in [`constants.py`](../server/constants.py);
-`stripeReceive` is missing from it today). `EVENT_TRIGGER_TYPES` has no
+deploy once skipped `stripeReceive` exactly this way). `EVENT_TRIGGER_TYPES` has no
production reader, but the tests assert membership in both.
## Testing
diff --git a/docs-internal/node-logic-flows/stripe/stripeReceive.md b/docs-internal/node-logic-flows/stripe/stripeReceive.md
index 0d147882..4a839bed 100644
--- a/docs-internal/node-logic-flows/stripe/stripeReceive.md
+++ b/docs-internal/node-logic-flows/stripe/stripeReceive.md
@@ -3,21 +3,25 @@
| Field | Value |
|------|-------|
| **Category** | payments / trigger (class `group = ("payments", "trigger")`) |
-| **Backend handler** | [`server/nodes/stripe/stripe_receive.py`](../../../server/nodes/stripe/stripe_receive.py) (`StripeReceiveNode`, on `WebhookTriggerNode`); daemon + webhook plumbing in [`_source.py`](../../../server/nodes/stripe/_source.py) (`StripeListenSource`, `StripeWebhookSource`); framework base [`services/events/triggers.py`](../../../server/services/events/triggers.py), [`services/events/webhook.py`](../../../server/services/events/webhook.py), verifier [`services/events/verifiers/stripe.py`](../../../server/services/events/verifiers/stripe.py) |
-| **Tests** | [`server/tests/nodes/test_stripe_plugin.py`](../../../server/tests/nodes/test_stripe_plugin.py) |
+| **Backend handler** | [`server/nodes/stripe/stripe_receive.py`](../../../server/nodes/stripe/stripe_receive.py) (`StripeReceiveNode`, on `WebhookTriggerNode`); daemon + webhook plumbing in [`_source.py`](../../../server/nodes/stripe/_source.py) (`StripeListenSource`, `StripeWebhookSource`, `shape_stripe_event`); the CloudEvents factory and deployed-path emit in [`_events.py`](../../../server/nodes/stripe/_events.py); framework base [`services/events/triggers.py`](../../../server/services/events/triggers.py), [`services/events/webhook.py`](../../../server/services/events/webhook.py), verifier [`services/events/verifiers/stripe.py`](../../../server/services/events/verifiers/stripe.py) |
+| **Tests** | [`server/tests/nodes/test_stripe_plugin.py`](../../../server/tests/nodes/test_stripe_plugin.py), `TestTriggerPrepareDeployment` in [`server/tests/test_deployment_canary_listener.py`](../../../server/tests/test_deployment_canary_listener.py) |
| **Skill (if any)** | none as a tool (the [stripe-skill](../../../server/skills/payments_agent/stripe-skill/SKILL.md) teaches it in prose; its `allowed-tools` names only `stripe_action`) |
| **Dual-purpose tool** | no (trigger) |
## Purpose
-Fire a workflow when Stripe delivers a webhook event. A supervised
-`stripe listen` daemon forwards every event for the logged-in account to
-`POST /webhook/stripe`; the source verifies the `Stripe-Signature` header
-against the `whsec_` secret captured from the daemon's own stderr, shapes the
-payload into a `WorkflowEvent` of type `stripe.<event type>`, and hands it to
-the in-process event waiter. The node contributes the event-type glob, a
-livemode filter, a precondition that starts the daemon on demand, and the
-output reshape.
+Fire a workflow when Stripe delivers a webhook event, on a canvas Run and in a
+deployed workflow. A supervised `stripe listen` daemon forwards every event for
+the logged-in account to `POST /webhook/stripe`; the source verifies the
+`Stripe-Signature` header against the `whsec_` secret captured from the
+daemon's own stderr, flattens the Stripe event into the trigger's output
+(`shape_stripe_event`), and wraps it in one `WorkflowEvent` type,
+`com.opencompany.stripe.event.received`, with the Stripe type in `subject` and
+`data.event_type`. It hands that envelope to the in-process event waiter (a
+canvas Run, or a deploy that runs without Temporal) and to
+`services.events.dispatch.emit` (deployed listeners on Temporal). The node
+contributes the event-type and livemode filter, the daemon start (on a canvas
+Run and on deploy), and the output unwrap.
## Inputs (handles)
@@ -29,14 +33,14 @@ None - this is a trigger; it is the head of a run.
| Name | Type | Default | Required | displayOptions.show | Description |
|------|------|---------|----------|---------------------|-------------|
-| `event_type_filter` | string | `all` | no | - | `all`, an exact Stripe type, or a `prefix.*` glob. `build_filter` prepends `stripe.` unless the value already starts with it, so users write `charge.*` |
-| `livemode_filter` | `all \| test \| live` | `all` | no | - | Extra filter read from `event.data.livemode` (see Decision Logic for why this does not work end-to-end) |
+| `event_type_filter` | string | `all` | no | - | `all`, an exact Stripe type (`charge.succeeded`), or a `prefix.*` glob (`charge.*`). Matched against `data.event_type`; a leading `stripe.` is accepted and stripped, for patterns written when the node required it |
+| `livemode_filter` | `all \| test \| live` | `all` | no | - | Compared with `data.livemode`: `live` admits live-mode events only, `test` test-mode events only |
## Outputs (handles)
| Handle | Shape | Description |
|--------|-------|-------------|
-| `output-main` | object | `StripeReceiveOutput` (the shaped dict from `shape_output`) |
+| `output-main` | object | `StripeReceiveOutput`: the shaped event (`shape_stripe_event`), identical on a canvas Run and in a deployed run |
### Output payload (TypeScript shape)
@@ -44,14 +48,14 @@ None - this is a trigger; it is the head of a run.
```ts
{
- event_id: string; // WorkflowEvent.id = Stripe evt_... id (empty string when the payload had none)
- event_type: string; // WorkflowEvent.type with the "stripe." prefix stripped, e.g. "charge.succeeded"
- created: number | null; // read from event.data - null in practice (see below)
- livemode: boolean | null; // read from event.data - null in practice
- api_version: string | null; // read from event.data - null in practice
- request_id: string | null; // event.data.request.id or event.data.request - null in practice
- account: string | null; // event.data.account, else the host part of WorkflowEvent.source ("acct_..." or "default")
- data: object; // event.data.data when that is a dict, else event.data itself (= Stripe's data object {object, previous_attributes?})
+ event_id: string; // Stripe's evt_ id ("" when the payload had none)
+ event_type: string; // Stripe's type, e.g. "charge.succeeded" ("unknown" when missing)
+ created: number | null; // Stripe's created (Unix seconds)
+ livemode: boolean | null;
+ api_version: string | null;
+ request_id: string | null; // request.id, or request when Stripe sends a bare value
+ account: string | null; // set only for Connect events
+ data: object; // Stripe's data object {object, previous_attributes?}, {} when missing
}
```
@@ -66,72 +70,69 @@ flowchart TD
V -- ok --> H[StripeVerifier: t= and v1= HMAC-SHA256 hex over t.body]
H -- header missing / mismatch --> R400[400]
H -- ok --> J[json.loads body] -- invalid --> R400
- J --> S[shape: id=evt id, type=stripe.type, source=stripe://account or default, time=created, data=payload.data or empty, subject=type]
- S --> Q[source.receive: internal push queue] --> D[event_waiter.dispatch event]
- D --> M{waiter.event_type == event.type}
- M -- stripe.webhook vs stripe.charge.succeeded --> N[no match: waiter untouched]
- subgraph canvas Run only
- P[_check_precondition] -- daemon not started, not logged in --> E1[error Stripe not connected]
- P -- daemon start failed --> E2[error Stripe daemon failed to start]
- P -- ok --> G[event_waiter.register node_type=stripeReceive: event_type=stripe.webhook, filter=build_filter]
- G --> A[await future] --> O[shape_output]
+ J --> S[shape_stripe_event -> stripe_event_received: id=evt id, type=com.opencompany.stripe.event.received, subject=Stripe type, data=shaped event]
+ S --> D1[event_waiter.dispatch envelope]
+ S --> D2[emit_stripe_event -> dispatch.emit]
+ D1 --> RUN[canvas Run waiter keyed on the same type: build_filter on data -> resolve -> shape_output unwraps data]
+ D2 --> DEP[deployed listener, EventType = that type: evaluate_trigger_filter_activity runs build_filter on data -> run starts with data as the trigger output]
+ subgraph canvas Run
+ P[_check_precondition: start stripe listen if needed] --> RUN
+ end
+ subgraph Start and boot re-arm
+ PD[prepare_deployment: start stripe listen in the background] --> DEP
end
```
## Decision Logic
-- **Precondition** (`_check_precondition`, canvas Run only): if the listen
- source is not `_started`, `has_credential()` (a filesystem sniff for
- `_api_key` in the CLI's `config.toml`) must be true, else the run returns
- the error "Stripe not connected. Log in with Stripe in Credentials."
- Then `source.start()` runs: `ensure_stripe_cli()`, the
- `DaemonEventSource` credential gate, and `ProcessService.start(name=
- "stripe-listen", workflow_id="_stripe", working_directory=daemons_dir())`.
- A failed start returns "Stripe daemon failed to start: <error>". Only a
- canvas Run reaches this precondition (deploy skips the node, see below),
- and the status refresh never starts the daemon.
+- **One CloudEvents type**: every Stripe event is
+ `com.opencompany.stripe.event.received`. A deployed trigger listens for
+ exactly one type (`register_canary_trigger_type` records one string per
+ node type, and the listener's `EventType` Search Attribute and the
+ controller's `on_event` match it exactly), so per-event types such as
+ `stripe.charge.succeeded` could never reach a deployed `stripeReceive`. The
+ node sets `event_type` to the same constant, which keys the canvas-Run
+ waiter.
+- **Two delivery paths**: `WebhookSource.handle` dispatches into the
+ in-process event waiter, which serves a canvas Run and the deploy path
+ without Temporal: the deployment manager arms the in-process collector
+ instead of a Temporal listener when no Temporal client is connected
+ (deployed VMs start with `TEMPORAL_ENABLED=false`) or the event framework
+ is off. `StripeWebhookSource.handle` then calls
+ `emit_stripe_event`, which reaches deployed listeners on Temporal. The
+ envelope carries no `workflow_id`, so every deployment with the trigger
+ receives it.
+- **Filter** (`build_filter`): both callers pass the envelope's `data` (the
+ waiter and `evaluate_trigger_filter_activity`); an envelope is accepted
+ too. `event_type_filter` is matched against `data.event_type` with
+ `event_type_matches` (exact, or `prefix.*`; `all` / empty matches
+ everything); `livemode_filter` compares `bool(data.livemode)`. A payload
+ that is not a dict is rejected.
+- **Output**: shaped once, in the source, because a deployed trigger hands
+ downstream nodes `event.data` verbatim; `shape_output` returns that same
+ `data`, so a canvas Run and a deployed run see the same fields.
+- **Daemon start**:
+ - *Canvas Run* (`_check_precondition`): if the listen source is not
+ `_started`, `has_credential()` (a filesystem sniff for `_api_key` in
+ the CLI's `config.toml`) must be true, else the run returns "Stripe not
+ connected. Log in with Stripe in Credentials."; a failed start returns
+ "Stripe daemon failed to start: <error>".
+ - *Deploy* (`prepare_deployment`, called by
+ `DeploymentManager._prepare_trigger_deployment` at Start and when the boot
+ re-arm restores a running or paused generation): the same start, in a
+ background task so a first-use CLI download never holds up Start. A
+ failure or a missing login is logged as a warning and the trigger stays
+ armed; logging in with Stripe starts the daemon, and events flow from
+ then on.
+ - The status refresh never starts the daemon.
- **Signature verification fails closed**: no captured secret -> HTTP 503
with `Retry-After: 5`; missing header, missing `t=` / `v1=`, or no
matching `v1=` candidate -> HTTP 400. Multiple `v1=` values are accepted
(rotation).
-- **Filter** (`build_filter`): `event_type_filter` is normalised to
- `stripe.<value>` and matched with `WorkflowEvent.matches_type` (exact, or
- `prefix.*`; `all` / empty matches everything). `_extra_filter` returns
- `None` for `livemode_filter=all`, otherwise a predicate comparing
- `bool(event.data.get("livemode"))` with the target.
-- **Event-key mismatch (load-bearing)**: `StripeReceiveNode.event_type` is
- derived by `WebhookTriggerNode.__init_subclass__` from
- `StripeWebhookSource.type = "stripe.webhook"`, and that is the key
- `event_waiter.register` stores on the waiter. `WebhookSource.handle`
- dispatches the envelope, whose `type` is `stripe.<stripe type>`, and
- `event_waiter.dispatch` selects waiters by exact equality
- `w.event_type == event_type`. As written, a real delivery therefore never
- resolves a `stripeReceive` waiter. Deploy never registers one at all:
- `stripeReceive` is not in `constants.WORKFLOW_TRIGGER_TYPES`, and
- `TriggerManager.find_trigger_nodes` filters on that set, so a deployed
- workflow starts no listener for it and logs no warning. It is not
- canary-registered either (no `register_canary_trigger_type` call in
- `nodes/stripe/`).
-- **Filter-input mismatch**: even with matching keys, `event_waiter.dispatch`
- calls each waiter's filter with the envelope's `data`, not the envelope,
- and `WebhookTriggerNode.build_filter` rebuilds a `WorkflowEvent` from what
- it receives. That raises a `ValidationError`, which the dispatcher logs as
- `[EventWaiter] Filter error`, so the waiter would still not resolve. The
- regression test `test_dispatch_with_live_waiter_does_not_crash`
- (`tests/services/test_events.py`) builds its waiter by hand, keyed on the
- envelope type with an always-true filter, so it covers neither mismatch.
-- **Data-shape mismatch**: `StripeWebhookSource.shape` stores only
- `payload["data"]` (Stripe's `{object, previous_attributes?}`) in
- `WorkflowEvent.data`, but `shape_output` and the livemode predicate read
- `created`, `livemode`, `api_version`, `request` and `account` from that
- same `event.data`. Those are top-level Stripe event fields, so they resolve
- to `None`; `livemode_filter=live` rejects every event and
- `livemode_filter=test` accepts every event; the output `data` falls
- through to `event.data` itself. The unit tests exercise `shape` and
- `shape_output` with different envelope shapes, so each passes in isolation.
- **Fallbacks**: `created` missing or non-integer -> `time = now(UTC)`;
- `account` missing -> `source = "stripe://default"`; missing `id` -> empty
- string; missing `type` -> `stripe.unknown`.
+ missing `id` -> empty `event_id`; missing `type` -> `event_type =
+ "unknown"`; `data` not a dict -> `{}`; `account` absent -> `null`, and
+ the envelope's `source` is `stripe://default`.
## Side Effects
@@ -143,12 +144,18 @@ flowchart TD
- **Database writes**: `auth_service.store_api_key("stripe_webhook_secret",
<whsec_...>, models=[])` whenever a `whsec_` token appears on the daemon's
stderr (fire-and-forget task).
-- **Broadcasts**: `update_node_status(..., "waiting", {"event_type":
- "stripe.webhook", "waiter_id": ...})` from the generic trigger handler
- (`services/handlers/triggers.py`) on a canvas Run; `make_status_refresh`
- mirrors `source.status()` (`type` / `running` / `pid`, without login state)
- into `broadcaster._status["stripe"]` once at startup and broadcasts it as
- `stripe_status`, which no frontend code handles.
+- **Event dispatch**: `event_waiter.dispatch` and `dispatch.emit` (wire
+ routing key `stripe_event_received` for the in-process broadcast half of
+ `emit`) for every verified delivery.
+- **Broadcasts**: none of its own on a canvas Run (`TriggerNode.execute`
+ registers the waiter without a `waiting` status; the generic trigger handler
+ in `services/handlers/triggers.py` that sends one serves only
+ `twitterReceive`). A deployed trigger shows `waiting` from the deployment
+ manager (Temporal listener) or the in-process collector.
+ `make_status_refresh` mirrors `source.status()` (`type` / `running` /
+ `pid`, without login state) into `broadcaster._status["stripe"]` once at
+ startup and broadcasts it as `stripe_status`, which no frontend code
+ handles.
- **HTTP**: `POST /webhook/stripe` answered by the router after
`handle()`; the source's `receive()` also enqueues the event on its
internal push queue (nothing consumes that queue for this source).
@@ -173,16 +180,19 @@ flowchart TD
- `TRIGGER_START_TO_CLOSE` (24 h) bounds the Temporal activity for a
canvas Run; there is no shorter wait timeout.
-- Event ids mirror Stripe's `evt_` ids, so retried deliveries carry the same
- `WorkflowEvent.id`; no dedup is performed in this plugin.
+- Redeliveries keep Stripe's `evt_` id as the envelope id, so a deployed
+ listener drops a redelivery as a duplicate; a canvas Run resolves once
+ anyway.
- Secret race: events forwarded before the `whsec_` line is captured get a
503 and are retried by Stripe / the CLI.
- One account per install; the daemon is a single global process.
- No auto-restart on daemon crash, and nothing reports it: the source's
`_started` flag is cleared only by `stop()`, so `stripe_status` still says
- `running: true`, the precondition skips the start, and the Credentials modal
- still shows Stripe as connected. Disconnect, then Login with Stripe,
- restarts it.
+ `running: true`, the precondition and the deploy hook both skip the start,
+ and the Credentials modal still shows Stripe as connected. Disconnect, then
+ Login with Stripe, restarts it.
+- No hire uses `stripeReceive` as a trigger yet: `config/employee_apps.json`
+ keeps Stripe a tool-only app.
## Related
diff --git a/docs-internal/node_creation.md b/docs-internal/node_creation.md
index a215d4d6..f71129cf 100644
--- a/docs-internal/node_creation.md
+++ b/docs-internal/node_creation.md
@@ -69,6 +69,8 @@ server/nodes/<provider>/
├── __init__.py # register_* calls only (zero logic)
├── _credentials.py # Credential subclass (Stripe: StripeCredential(Credential))
├── _source.py # DaemonEventSource + WebhookSource subclasses
+├── _events.py # CloudEvents factory (the one type the trigger is canary-registered
+│ # for) + the dispatch.emit wrapper that reaches deployed listeners
├── _handlers.py # WS_HANDLERS via make_lifecycle_handlers()
├── _install.py # ensure_<provider>_cli() auto-downloader
├── <provider>_action.py # ActionNode + AI tool — uses run_cli_command
diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.md
index 989b0625..1778bef2 100644
--- a/docs-internal/plugin_system.md
+++ b/docs-internal/plugin_system.md
@@ -1066,15 +1066,21 @@ dataschema / data` plus the extras.
```python
WorkflowEvent(
- id=payload["id"], # provider's event id (replay safety)
- source="stripe://acct_test", # URI: scheme://provider/account
- type="stripe.charge.succeeded", # reverse-DNS event type
+ id=payload["id"], # provider's event id (replay safety)
+ source="stripe://acct_test", # URI: scheme://provider/account
+ type="com.opencompany.stripe.event.received", # reverse-DNS event type
time=datetime.fromtimestamp(payload["created"], tz=timezone.utc),
- subject=payload.get("type"),
- data=payload,
+ subject=payload.get("type"), # the provider's own type, "charge.succeeded"
+ data=shape_stripe_event(payload),
)
```
+A deployed trigger listens for exactly one CloudEvents type (the string
+`register_canary_trigger_type` records), so a provider with many event
+types sends them all under one type and carries its own type in
+`subject` and `data`, where the trigger's filter reads it
+(`nodes/stripe/_events.py`).
+
`WorkflowEvent.matches_type(pattern)` does CloudEvents-style glob
matching: `"all"` / `""` matches everything, `"foo.*"` matches
`"foo.X"` and `"foo.X.Y"`, exact strings match exactly.
@@ -1092,6 +1098,7 @@ differs from the generic shape:
from services.events import (
BaseTriggerParams, WebhookTriggerNode, WorkflowEvent,
)
+from services.events.envelope import event_type_matches
class MyParams(BaseTriggerParams):
livemode_filter: Literal["all", "test", "live"] = "all"
@@ -1104,7 +1111,7 @@ class MyReceiveNode(WebhookTriggerNode):
credentials = (MyCredential,)
webhook_source = MyWebhookSource # required: which source feeds events
- event_type_prefix = "my." # auto-prepended to user filters
+ event_type = MY_EVENT_TYPE # the type MyWebhookSource.shape emits
Params = MyParams
Output = MyOutput
@@ -1112,26 +1119,55 @@ class MyReceiveNode(WebhookTriggerNode):
from ._source import get_listen_source
return None if get_listen_source()._started else "Daemon not running"
- def _extra_filter(self, params): # optional; on top of event-type match
- if params.livemode_filter == "all":
- return None
- target = params.livemode_filter == "live"
- return lambda ev: bool(ev.data.get("livemode")) is target
+ def build_filter(self, params): # both callers pass the envelope's data
+ pattern = params.event_type_filter or "all"
+
+ def matches(event):
+ data = event.data if isinstance(event, WorkflowEvent) else event
+ if not isinstance(data, dict):
+ return False
+ if not event_type_matches(str(data.get("event_type") or ""), pattern):
+ return False
+ return params.livemode_filter == "all" or (
+ bool(data.get("livemode")) is (params.livemode_filter == "live")
+ )
+
+ return matches
def shape_output(self, event: WorkflowEvent) -> Dict:
- # Optional override; default returns event.model_dump(mode="json")
- ...
+ return event.data # shaped by the source, as the deployed run sees it
```
`WebhookTriggerNode` provides:
-- `event_type` derived from `webhook_source.type` automatically.
+- `event_type` derived from `webhook_source.type` automatically. It is
+ the canvas-Run waiter key, so set it yourself when `shape` returns
+ envelopes of another type, or `event_waiter.dispatch` matches no
+ waiter (Stripe sets `STRIPE_EVENT_RECEIVED_TYPE`).
- `build_filter` combining CloudEvents type-glob + optional
- `_extra_filter`.
-- `execute()` with `_check_precondition` short-circuit and reshape
- passthrough.
+ `_extra_filter`. **Override it to read the payload instead.** Both
+ callers hand the filter the envelope's `data`, not the envelope: the
+ event waiter on a canvas Run, and `evaluate_trigger_filter_activity`
+ on a deployed listener. The base rebuilds a `WorkflowEvent` from that
+ dict, which raises unless the data happens to carry `source` and
+ `type`; a waiter logs the error and stays unresolved, and a deployed
+ listener fails open and ignores the filter. `StripeReceiveNode`
+ overrides it; the WhatsApp Business triggers do not, so a deployed one
+ admits every event whatever its `event_type_filter`.
+- `execute()` with the `_check_precondition` short-circuit, then
+ `shape_output` on the resolved event (the waiter resolves with
+ `data`, which `_as_event` wraps back into an envelope). A deployed
+ run receives `event.data` verbatim and never calls `shape_output`,
+ so shape the payload in the source and let `shape_output` return
+ `event.data`, or Run and deploy disagree about the fields.
- The `@Operation("wait")` stub.
+A trigger whose events need something running (Stripe's `stripe listen`
+daemon) starts it from the `TriggerNode.prepare_deployment` classmethod,
+which the deployment manager calls for every trigger it arms, at Start
+and at the boot re-arm. Return quickly and schedule slow work; a raise is
+logged and the trigger is armed anyway.
+
### `WebhookSource` — HTTP receiver
Plugin pairs the trigger with a `WebhookSource` that owns signature
@@ -1148,18 +1184,24 @@ class StripeWebhookSource(WebhookSource):
credential = StripeCredential
async def shape(self, request, body, payload) -> WorkflowEvent:
- return WorkflowEvent(
- id=payload["id"],
- type=f"stripe.{payload['type']}",
- source=f"stripe://{payload.get('account', 'default')}",
- time=datetime.fromtimestamp(payload["created"], tz=timezone.utc),
- data=payload,
+ data = shape_stripe_event(payload) # the trigger's output fields
+ return stripe_event_received( # type: com.opencompany.stripe.event.received
+ data, event_id=data["event_id"], account=data["account"], time=...,
)
+
+ async def handle(self, request):
+ event = await super().handle(request) # verify, shape, wake the in-process waiter
+ await emit_stripe_event(event) # dispatch.emit: deployed listeners
+ return event
```
The shared dispatch path lives in `routers/webhook.py` — it consults
`WEBHOOK_SOURCES`, runs the verifier, calls `shape()`, dispatches via
-`event_waiter`. **No plugin name is hardcoded in core.**
+`event_waiter`. **No plugin name is hardcoded in core.** That reaches a
+canvas Run, and a deploy only when it runs without Temporal. A
+trigger that deploys on Temporal also needs `register_canary_trigger_type`
+and a `dispatch.emit` of each envelope, as `StripeWebhookSource.handle`
+does above.
### `DaemonEventSource` — supervised subprocess driver
@@ -1364,8 +1406,10 @@ project that publishes pre-built binaries via GitHub releases.
| Concern | Framework integration | Plugin contribution |
|---|---|---|
| HTTP webhook ingress | `routers/webhook.py` consults `WEBHOOK_SOURCES` registry | `register_webhook_source(MySource())` |
-| Event dispatch into workflows | `event_waiter.dispatch(source.type, event)` from `WebhookSource.handle` | provider-specific `shape()` returning `WorkflowEvent` |
-| Trigger waiting + filtering | `WebhookTriggerNode.build_filter` (CloudEvents glob) | optional `_extra_filter(params)` |
+| Event dispatch into workflows | `event_waiter.dispatch(event)` from `WebhookSource.handle` (canvas Run, and a deploy that runs without Temporal) | provider-specific `shape()` returning `WorkflowEvent` |
+| Deployed delivery (Temporal) | `services.events.dispatch.emit` signals the listeners whose `EventType` matches the envelope's `type` | `register_canary_trigger_type(node_type, <the envelope type>)` + an `emit` of each envelope (Stripe: `_events.emit_stripe_event`, called from `handle`) |
+| Trigger waiting + filtering | `WebhookTriggerNode.build_filter` (CloudEvents glob); both callers pass the envelope's `data` | override `build_filter` to read the payload (the base rebuilds an envelope from it and raises); `_extra_filter(params)` only on top of the base |
+| Deploy-time setup | `DeploymentManager._prepare_trigger_deployment` calls the trigger class's `prepare_deployment` at Start and at the boot re-arm; a raise is logged and the trigger armed anyway | optional `prepare_deployment(node_id=, workflow_id=, parameters=)` classmethod (Stripe starts `stripe listen` in a background task) |
| Daemon lifecycle | `DaemonEventSource.start/stop/restart` via `ProcessService` | `build_command(secrets)` + `parse_line(stream, line)` (subscribed via `ProcessService.start(line_handler=...)` — no log-file tailing) |
| Daemon credential gate | `DaemonEventSource.start` consults `await self.has_credential()` before spawning | optional override when auth is non-api-key (Stripe → `is_logged_in()`); default tests `secrets["api_key"]` |
| Lifecycle WebSocket commands | `make_lifecycle_handlers(prefix, source, extra=…)` | provider-specific extra handlers |
diff --git a/docs-internal/stripe_service.md b/docs-internal/stripe_service.md
index f1dc406d..d7ccf766 100644
--- a/docs-internal/stripe_service.md
+++ b/docs-internal/stripe_service.md
@@ -15,20 +15,22 @@ supervision, lifecycle WebSocket handlers, status broadcasts, CLI
invocation) lives in [`services/events/`](../server/services/events/) —
this folder contributes only the Stripe-specific shapes.
-> **Known gap: `stripeReceive` never fires today.** Deploy skips it: the node
-> is not in `constants.WORKFLOW_TRIGGER_TYPES`, which
-> `TriggerManager.find_trigger_nodes` filters on, and it is not
-> canary-registered, so a deployed workflow starts no listener for it and logs
-> no warning. A canvas Run waits forever: `WebhookTriggerNode.__init_subclass__`
-> keys the waiter on the source type `stripe.webhook`, while
-> `WebhookSource.handle` dispatches the envelope, typed `stripe.<event>`, and
-> `event_waiter.dispatch` matches types exactly. Even with matching keys, the
-> dispatcher hands each filter the envelope's `data`, and
-> `WebhookTriggerNode.build_filter` raises a validation error rebuilding a
-> `WorkflowEvent` from it. The rest of the plugin (`stripeAction`, login, the
-> daemon) does not use this path. The
-> [`stripeReceive` card](./node-logic-flows/stripe/stripeReceive.md) also
-> records a field mismatch in `shape_output`.
+> **How an event reaches `stripeReceive`.** Every Stripe event travels under
+> one CloudEvents type, `com.opencompany.stripe.event.received`
+> ([`_events.py`](../server/nodes/stripe/_events.py)), with the Stripe type
+> in `subject` and in `data.event_type`, which the node's filter reads. A
+> deployed trigger listens for exactly one type (the string
+> `register_canary_trigger_type` records), so per-event types could never
+> reach it. The source flattens each Stripe event once
+> (`shape_stripe_event`), because a deployed trigger hands downstream nodes
+> `event.data` verbatim, and delivers it twice: `WebhookSource.handle` wakes
+> the in-process waiter (a canvas Run, or a deploy that runs without
+> Temporal, the default on deployed VMs), and `emit_stripe_event` calls
+> `dispatch.emit` for deployed listeners on Temporal. Deploying starts `stripe listen` through the generic
+> `TriggerNode.prepare_deployment` hook, at Start and again when the boot
+> re-arm restores a running or paused generation. The
+> [`stripeReceive` card](./node-logic-flows/stripe/stripeReceive.md) walks
+> through both paths.
## Architecture
@@ -85,15 +87,24 @@ StripeWebhookSource.handle(request)
│ raises ValueError → HTTPException(400)
│
├── shape(request, body, payload)
- │ → WorkflowEvent(id=evt_…, type="stripe.charge.succeeded",
- │ source="stripe://acct_…", data=payload["data"])
+ │ data = shape_stripe_event(payload) (event_id, event_type, created,
+ │ livemode, api_version, request_id,
+ │ account, data)
+ │ → WorkflowEvent(id=evt_…, type="com.opencompany.stripe.event.received",
+ │ subject="charge.succeeded", source="stripe://acct_…",
+ │ data=data)
│
├── self.receive(event) (queues it on the source)
│
- └── event_waiter.dispatch(event) (the envelope alone; matched on event.type)
+ ├── event_waiter.dispatch(event) (matched on event.type: a canvas Run's
+ │ stripeReceive waiter, or a deploy that
+ │ runs without Temporal)
+ │
+ └── emit_stripe_event(event) → dispatch.emit
▼
- StripeReceiveNode waiters are keyed "stripe.webhook", so none match
- (see the Known gap at the top)
+ deployed stripeReceive listeners (EventType = the same type);
+ evaluate_trigger_filter_activity runs build_filter on event.data,
+ and the run starts with event.data as the trigger's output
```
### Request flow — outgoing CLI action
@@ -233,7 +244,8 @@ StripeListenSource.stop()
| File | Description |
|---|---|
-| `server/nodes/stripe/__init__.py` | Wiring: `register_ws_handlers`, `register_webhook_source`, `register_service_refresh` (with `make_status_refresh`) and `register_output_schema` for both nodes. There is no `register_canary_trigger_type` call. |
+| `server/nodes/stripe/__init__.py` | Wiring: `register_ws_handlers`, `register_webhook_source`, `register_canary_trigger_type("stripeReceive", STRIPE_EVENT_RECEIVED_TYPE)` (the second argument must equal the type on every envelope the source emits, or the deployed listener's Visibility match silently fails), `register_service_refresh` (with `make_status_refresh`) and `register_output_schema` for both nodes. |
+| `server/nodes/stripe/_events.py` | `STRIPE_EVENT_RECEIVED_TYPE` (`com.opencompany.stripe.event.received`), the `stripe_event_received` CloudEvents factory (id = Stripe's `evt_` id, so a redelivery is a duplicate; no `workflow_id`, so every deployment with the trigger receives it) and `emit_stripe_event`, the `dispatch.emit` call that reaches deployed listeners. |
| `server/nodes/stripe/_credentials.py` | `StripeCredential(Credential)` — thin marker class. The CLI manages auth at `~/.config/stripe/config.toml`; this class only exposes the captured `stripe_webhook_secret` for the framework's signature-verifier path. |
| `server/nodes/stripe/_install.py` | `ensure_stripe_cli()` — async, idempotent, lock-guarded. Resolves the binary path: in-process cache → system PATH → previously-downloaded copy at `<DATA_DIR>/packages/stripe/bin/stripe[.exe]` (`core.paths.package_dir("stripe") / "bin"`) → fresh download from GitHub releases (pinned `_VERSION = "1.40.9"`) into that same dir. Asset-name map covers Windows AMD64, Linux x86_64/arm64, macOS x86_64/arm64. Subsequent calls hit the cache instantly. |
| `server/skills/payments_agent/stripe-skill/SKILL.md` | LLM teaching markdown for the `stripe_action` tool, covering customers, charges, payment_intents, refunds, invoices, products/prices, subscriptions, the `trigger` command, common workflows, quoting/escaping, idempotency, test vs live mode, error patterns, and webhook delivery. |
@@ -241,7 +253,8 @@ StripeListenSource.stop()
| `server/nodes/stripe/_source.py` | `StripeListenSource(DaemonEventSource)` and `StripeWebhookSource(WebhookSource)` plus their singletons. |
| `server/nodes/stripe/_handlers.py` | WS handlers via `make_lifecycle_handlers` (`stripe_connect` / `stripe_disconnect` / `stripe_reconnect`) plus the plugin-specific `stripe_login`, `stripe_logout`, `stripe_trigger` (synthetic test events) and `stripe_status` (overrides the factory's status handler to add login state). See [WebSocket handlers](#websocket-handlers). |
| `server/nodes/stripe/stripe_action.py` | `StripeActionNode` — pass-through over the CLI via `run_cli_command`. Its `tool_name = "stripe_action"` and the matching `tool_description` are what the LLM sees when the node is wired to an agent's `input-tools` handle. |
-| `server/nodes/stripe/stripe_receive.py` | `StripeReceiveNode(WebhookTriggerNode)` — filter overrides + output reshape. Never fires today (see the Known gap at the top). |
+| `server/nodes/stripe/stripe_receive.py` | `StripeReceiveNode(WebhookTriggerNode)`: `event_type = STRIPE_EVENT_RECEIVED_TYPE` (the canvas-Run waiter key), a `build_filter` over the shaped data (event type and livemode), `shape_output` returning that data, the canvas-Run precondition and the `prepare_deployment` hook, both of which start `stripe listen`. |
+| `server/services/plugin/trigger.py` / `server/services/deployment/manager.py` | `TriggerNode.prepare_deployment` (default: nothing) and `DeploymentManager._prepare_trigger_deployment`, which calls it for every trigger it arms, at Start and at the boot re-arm, and logs a raise without failing the deploy. |
| `server/services/events/__init__.py` | Public framework surface — exports every base class + helper. |
| `server/services/events/daemon.py` | `DaemonEventSource` — supervises subprocess via `ProcessService`. Subscribes to ProcessService's per-line callback (`line_handler`) instead of re-tailing the on-disk log files. Credential gate is `await self.has_credential()` so non-api-key auth (Stripe → `is_logged_in()`) plugs in via subclass override. |
| `server/services/process_service.py` | Spawns + supervises long-lived subprocesses. Loops `stream.readline()` per stdout/stderr, writes to `.log`, broadcasts to Terminal, and forwards each decoded line to the optional `line_handler` async callback (Wave 12.B addition for typed event-source subscribers — see `DaemonEventSource._on_line`). |
@@ -255,7 +268,7 @@ StripeListenSource.stop()
| `server/nodes/groups.py` | `payments` palette group. |
| `server/credentials/icons/stripe.svg` | Stripe credential-tile icon, served at `/api/schemas/credentials/stripe/icon`. |
| `server/tests/services/test_events.py` | Framework tests (envelope, verifiers, polling/daemon lifecycle, WebhookSource). |
-| `server/tests/nodes/test_stripe_plugin.py` | Stripe-specific tests (shape, filter, action passthrough, registrations). |
+| `server/tests/nodes/test_stripe_plugin.py` | Stripe-specific tests: shaping, the filter on both paths, a canvas Run resolving, the deployed path (deployable, one canary type matching every emitted envelope, no `workflow_id`, the filter not failing open), `prepare_deployment`, action passthrough and registrations. `TestTriggerPrepareDeployment` in `tests/test_deployment_canary_listener.py` covers the manager's hook call. |
## Plugin classes
@@ -310,19 +323,19 @@ plus the per-line callback subscription via `ProcessService`'s
| `credential = StripeCredential` | Resolved by the framework before `build_command` is called. |
| `start()` (override) | `await ensure_stripe_cli()` then `super().start()`. Caches the resolved binary path so `build_command` (sync) can pick it up. |
| `build_command(secrets)` | Returns `<shlex.quote'd-binary> listen --forward-to … --print-secret`. The binary path is `shlex.quote`d so it round-trips through `ProcessService`'s POSIX-mode `shlex.split` unchanged. No `--api-key`: CLI reads its own config file. |
-| `has_credential()` (override) | Returns `is_logged_in()` — a filesystem check on `~/.config/stripe/config.toml`. Consulted by `DaemonEventSource.start` (the credential gate) and by `StripeReceiveNode._check_precondition` when the trigger runs (the demand-driven start; only a canvas Run reaches it today, because deploy skips the node). The status refresh is a passive probe since July 2026. |
+| `has_credential()` (override) | Returns `is_logged_in()` — a filesystem check on `~/.config/stripe/config.toml`. Consulted by `DaemonEventSource.start` (the credential gate) and by the trigger's demand-driven starts: `StripeReceiveNode._check_precondition` on a canvas Run, and `prepare_deployment` when a deployment arms the trigger. The status refresh is a passive probe since July 2026. |
| `parse_line(stream, line)` | Invoked once per decoded stdout/stderr line via `ProcessService`'s `line_handler` callback. On `whsec_…` match, persists the secret via `auth_service.store_api_key("stripe_webhook_secret", …)`. The Stripe daemon doesn't emit workflow events itself — they arrive via the webhook receiver. |
### `StripeWebhookSource(WebhookSource)`
Receives forwarded events at `/webhook/stripe`. The framework owns
signature verification, JSON parsing, and `event_waiter.dispatch`;
-this class declares only the path, the verifier, the secret-field
-name, and the payload-to-`WorkflowEvent` shaping:
+this class declares the path, the verifier, the secret-field name and
+the shaping, and adds the deployed-path emit:
```python
class StripeWebhookSource(WebhookSource):
- type = "stripe.webhook"
+ type = "stripe.webhook" # the source's own id; no envelope carries it
path = "stripe"
verifier = StripeVerifier
secret_field = "stripe_webhook_secret"
@@ -330,23 +343,20 @@ class StripeWebhookSource(WebhookSource):
async def shape(self, request, body, payload) -> WorkflowEvent:
created = payload.get("created")
- time = (
- datetime.fromtimestamp(int(created), tz=timezone.utc)
- if created else datetime.now(timezone.utc)
- )
- account = payload.get("account") or "default"
- return WorkflowEvent(
- id=payload.get("id") or "", # provider event id (replay safety)
- type=f"stripe.{payload.get('type', 'unknown')}",
- source=f"stripe://{account}",
- time=time,
- data=payload.get("data") or {},
- subject=payload.get("type"),
- )
+ time = ... # created, else now (UTC)
+ data = shape_stripe_event(payload) # the trigger's output fields
+ return stripe_event_received(
+ data, event_id=data["event_id"], account=data["account"], time=time,
+ ) # type = com.opencompany.stripe.event.received
+
+ async def handle(self, request: Request) -> WorkflowEvent:
+ event = await super().handle(request) # verify, shape, wake the in-process waiter
+ await emit_stripe_event(event) # reach deployed listeners on Temporal
+ return event
```
-The `id` mirrors Stripe's `evt_…` so duplicate deliveries (Stripe
-retries on 5xx) are idempotent at the WorkflowEvent level.
+The `id` mirrors Stripe's `evt_…`, so a redelivery (Stripe retries on 5xx)
+carries the same id and a deployed listener drops it as a duplicate.
### `StripeReceiveNode(WebhookTriggerNode)`
@@ -366,27 +376,34 @@ class StripeReceiveNode(WebhookTriggerNode):
)
credentials = (StripeCredential,)
webhook_source = StripeWebhookSource
- event_type_prefix = "stripe." # users write "charge.*" not "stripe.charge.*"
+ event_type = STRIPE_EVENT_RECEIVED_TYPE # the waiter key: the type the source emits
Params = StripeReceiveParams
Output = StripeReceiveOutput
+ def build_filter(self, params):
+ # Match data["event_type"] against event_type_filter (exact, "prefix.*"
+ # or "all"; a leading "stripe." is stripped) and data["livemode"]
+ # against livemode_filter. Both callers pass the envelope's data.
+ ...
+
async def _check_precondition(self) -> Optional[str]:
- # Start the listen daemon on demand; refuse if the CLI is not logged in.
+ # Canvas Run: start the listen daemon on demand; refuse if the CLI is not logged in.
...
- def _extra_filter(self, params): # livemode filter on top of event-type
+ @classmethod
+ async def prepare_deployment(cls, *, node_id, workflow_id, parameters) -> None:
+ # Start and boot re-arm: start the listen daemon in a background task.
...
def shape_output(self, event: WorkflowEvent) -> Dict:
- # Extract Stripe-shaped fields from the WorkflowEvent's CloudEvents data.
- ...
+ return event.data # already shaped by the source
```
-The framework's `WebhookTriggerNode` handles event-type glob matching
-(`charge.*`, `payment_intent.*`, `all`), the
-`event_type_prefix` auto-prepend, the `_check_precondition`
-short-circuit, and the `Operation("wait")` stub. This class only
-contributes the livemode filter and the output reshape.
+The framework's `WebhookTriggerNode` supplies the `_check_precondition`
+short-circuit, the re-wrap of the waiter's `data` into an envelope
+before `shape_output`, and the `Operation("wait")` stub. This class
+overrides `build_filter` because every Stripe event shares one
+CloudEvents type, so the Stripe type has to come from the data.
### `StripeActionNode(ActionNode)` — dual-purpose
@@ -667,9 +684,10 @@ login state) into `broadcaster._status["stripe"]` and broadcasts it as
refresh **never starts the daemon** — a stored credential alone is not
a reason to run `stripe listen`. The demand signals own the starts
instead: `_complete_login` after a successful login, the
-`stripe_connect` command (no modal button sends it), and
-`StripeReceiveNode._check_precondition` when the trigger runs, which
-today means a canvas Run only.
+`stripe_connect` command (no modal button sends it),
+`StripeReceiveNode._check_precondition` on a canvas Run, and
+`StripeReceiveNode.prepare_deployment` whenever a deployment arms the
+trigger (Start, and the boot re-arm after a restart).
### Frontend `connected` derivation (single generic line)
@@ -811,8 +829,9 @@ by id.
If `stripe listen` exits unexpectedly, nothing restarts it, and nothing
reports it either. The source's `_started` flag is cleared only by
-`stop()`, so `stripe_status` still reports `running: true` and
-`StripeReceiveNode._check_precondition` skips the start; the modal's
+`stop()`, so `stripe_status` still reports `running: true`, and both
+`StripeReceiveNode._check_precondition` and `prepare_deployment` skip
+the start; the modal's
indicator follows the stored login marker, so Stripe still reads as
connected. The per-line `parse_line` callback simply stops receiving
lines when `ProcessService` reaps the process. To restart the daemon,
@@ -836,16 +855,16 @@ End-to-end smoke (requires Stripe CLI installed and a Stripe account):
- Within ~3 s the stderr.log contains `whsec_…`.
- `auth_service.get_api_key("stripe_webhook_secret")` returns the
secret.
-3. **Synthetic event (blocked by the Known gap).** Once `stripeReceive`
- fires: build a workflow with `StripeReceiveNode` (filter: `charge.*`)
- → console node, deploy it, and send WS
+3. **Synthetic event.** Build a workflow with `StripeReceiveNode`
+ (filter: `charge.*`) → console node, Start it, and send WS
`{"type":"stripe_trigger","event":"charge.succeeded"}`. The console
- should fire with `event_type="charge.succeeded"` and the CLI's
- `event_id`. Today the forwarded event is verified and dispatched, but
- no trigger fires.
-4. **Filter rejection (blocked by the Known gap).** Set filter to
- `payment_intent.created`, retrigger `charge.succeeded` — node should
- NOT fire. Trigger `payment_intent.created` — it should.
+ fires with `event_type="charge.succeeded"` and the CLI's `event_id`.
+ A canvas Run of the trigger resolves the same way, with the same
+ output fields.
+4. **Filter rejection.** Set the filter to `payment_intent.created` and
+ retrigger `charge.succeeded`: the node does not fire. Trigger
+ `payment_intent.created` and it does. `livemode_filter=live` rejects
+ CLI test events.
5. **Action node.** Configure `StripeActionNode` with
`command="customers create --email [email protected]"`. Run. Output
contains `id: cus_…`, `email: [email protected]`.
@@ -863,9 +882,10 @@ End-to-end smoke (requires Stripe CLI installed and a Stripe account):
9. **Restart.** Restart OpenCompany. The status refresh does not start
the daemon. The modal still shows Stripe as connected (the login
marker survives a restart), so it offers no Login button, and it has
- no Connect button. The daemon starts again on a canvas Run of
- `stripeReceive` (its precondition) or a `stripe_connect` WS message;
- deploy skips Stripe triggers.
+ no Connect button. The daemon starts again when the boot re-arm
+ restores a deployed `stripeReceive` (its `prepare_deployment` hook), on
+ a canvas Run of `stripeReceive` (its precondition), or on a
+ `stripe_connect` WS message.
Unit tests live in [`server/tests/nodes/test_stripe_plugin.py`](../server/tests/nodes/test_stripe_plugin.py)
and [`server/tests/services/test_events.py`](../server/tests/services/test_events.py)
diff --git a/server/config/employee_apps.json b/server/config/employee_apps.json
index 7af06ee7..2b956091 100644
--- a/server/config/employee_apps.json
+++ b/server/config/employee_apps.json
@@ -438,7 +438,7 @@
"invoices",
"refunds"
],
- "_trigger_note": "stripeReceive is not a deployable trigger (constants.WORKFLOW_TRIGGER_TYPES), so Stripe is a tool only.",
+ "_trigger_note": "Stripe is a tool only here. stripeReceive deploys, but no hire uses it as a trigger yet.",
"trigger": null,
"reply": null,
"notify_owner": null,
diff --git a/server/constants.py b/server/constants.py
index 5aa49ef8..68dad8fb 100644
--- a/server/constants.py
+++ b/server/constants.py
@@ -360,6 +360,7 @@ EVENT_TRIGGER_TYPES: FrozenSet[str] = frozenset(
"whatsappBusinessStatus",
"discordReceive",
"discordInteraction",
+ "stripeReceive",
"twitterReceive",
"workflowTrigger",
"chatTrigger",
@@ -403,12 +404,13 @@ WORKFLOW_TRIGGER_TYPES: FrozenSet[str] = frozenset(
"whatsappReceive",
# Omitting a trigger here is a silent failure, not an error:
# find_trigger_nodes filters on this set, so deploy simply ignores
- # the node -- no listener, no warning. It is why stripeReceive is
- # canvas-only today.
+ # the node -- no listener, no warning. Deploy once skipped
+ # stripeReceive exactly this way.
"whatsappBusinessReceive",
"whatsappBusinessStatus",
"discordReceive",
"discordInteraction",
+ "stripeReceive",
"workflowTrigger",
"chatTrigger",
"taskTrigger",
diff --git a/server/nodes/stripe/__init__.py b/server/nodes/stripe/__init__.py
index d1ce8240..0ccb5b92 100644
--- a/server/nodes/stripe/__init__.py
+++ b/server/nodes/stripe/__init__.py
@@ -3,18 +3,21 @@
Self-contained Wave 12 plugin. All boilerplate (lifecycle WS handlers,
status refresh, signature verification, CLI subprocess) lives in
``services.events``. This package contributes only the Stripe-specific
-shapes: command builder, secret-capture regex, output reshape, the
-livemode filter, and the credential class.
+shapes: command builder, secret-capture regex, the event shape and its
+CloudEvents type, the event-type and livemode filter, the daemon start on
+deploy, and the credential class.
"""
from __future__ import annotations
+from services.deployment.canary_registry import register_canary_trigger_type
from services.events import make_status_refresh, register_webhook_source
from services.node_output_schemas import register_output_schema
from services.status_broadcaster import register_service_refresh
from services.ws_handler_registry import register_ws_handlers
from ._credentials import StripeCredential
+from ._events import STRIPE_EVENT_RECEIVED_TYPE
from ._handlers import WS_HANDLERS
from ._source import (
StripeListenSource,
@@ -29,6 +32,10 @@ from .stripe_receive import StripeReceiveNode, StripeReceiveOutput
register_ws_handlers(WS_HANDLERS)
register_webhook_source(get_webhook_source())
+# Opt the trigger into the Temporal listener path. The second argument must
+# equal the type on every envelope the source emits: it becomes the EventType
+# the Visibility query matches, and a mismatch is silent.
+register_canary_trigger_type(StripeReceiveNode.type, STRIPE_EVENT_RECEIVED_TYPE)
register_service_refresh(
make_status_refresh(
get_listen_source(),
diff --git a/server/nodes/stripe/_events.py b/server/nodes/stripe/_events.py
new file mode 100644
index 00000000..362e36ad
--- /dev/null
+++ b/server/nodes/stripe/_events.py
@@ -0,0 +1,67 @@
+"""CloudEvents factory and the dispatch wrapper for Stripe webhook deliveries.
+
+Two things here are load-bearing.
+
+**Every Stripe event travels under one CloudEvents type.** A deployed trigger
+listens for exactly one type: ``register_canary_trigger_type`` records one
+string per node type, and both the listener's ``EventType`` Search Attribute
+and the workflow controller's ``on_event`` match it exactly. Envelopes typed
+per Stripe event (``stripe.charge.succeeded`` and so on) could never reach a
+deployed ``stripeReceive``. The Stripe type rides in ``subject`` and in
+``data["event_type"]``, which is where the node's filter reads it.
+
+**``WebhookSource.handle`` does not reach deployed listeners.** It feeds the
+in-process event waiter, which serves a canvas Run and the Temporal-off
+deploy path. Deployed triggers on Temporal are reached only by
+``services.events.dispatch.emit``, hence :func:`emit_stripe_event`.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any, Mapping, Optional
+
+from services.events.envelope import WorkflowEvent
+
+# The exact string ``register_canary_trigger_type`` records for stripeReceive.
+STRIPE_EVENT_RECEIVED_TYPE = "com.opencompany.stripe.event.received"
+
+# Outer WS wire key for the in-process broadcast half of ``emit``.
+_WIRE_KEY = "stripe_event_received"
+
+
+def stripe_event_received(
+ data: Mapping[str, Any],
+ *,
+ event_id: str,
+ account: Optional[str],
+ time: datetime,
+) -> WorkflowEvent:
+ """One Stripe event forwarded by ``stripe listen``.
+
+ ``event_id`` is Stripe's ``evt_`` id, which stays the same when Stripe
+ redelivers, so the deployed listener drops a redelivery as a duplicate.
+ ``workflow_id`` stays unset: a Stripe event is meant to reach every
+ deployment that carries the trigger.
+ """
+ return WorkflowEvent(
+ id=event_id,
+ source=f"stripe://{account or 'default'}",
+ type=STRIPE_EVENT_RECEIVED_TYPE,
+ time=time,
+ subject=str(data.get("event_type") or "") or None,
+ data=dict(data),
+ )
+
+
+async def emit_stripe_event(event: WorkflowEvent) -> None:
+ from services.events.dispatch import emit
+
+ await emit(event, wire_routing_key=_WIRE_KEY)
+
+
+__all__ = [
+ "STRIPE_EVENT_RECEIVED_TYPE",
+ "emit_stripe_event",
+ "stripe_event_received",
+]
diff --git a/server/nodes/stripe/_source.py b/server/nodes/stripe/_source.py
index 725898bb..edc72f0b 100644
--- a/server/nodes/stripe/_source.py
+++ b/server/nodes/stripe/_source.py
@@ -7,7 +7,8 @@ Two cooperating sources:
captures the ``whsec_…`` signing secret from its stderr banner.
* :class:`StripeWebhookSource` (WebhookSource) is the actual event
producer — verifies the Stripe-Signature header on each forwarded
- POST and turns the payload into a :class:`WorkflowEvent`.
+ POST, shapes the payload into the trigger's output, and hands it to
+ both the canvas-Run waiter and deployed listeners.
Module-level singletons (``get_listen_source`` / ``get_webhook_source``)
plug into the framework registries from ``__init__.py``.
@@ -34,6 +35,7 @@ from services.events import (
)
from ._credentials import StripeCredential
+from ._events import emit_stripe_event, stripe_event_received
logger = get_logger(__name__)
@@ -130,6 +132,30 @@ class StripeListenSource(DaemonEventSource):
logger.warning("[Stripe] persist secret failed: %s", e)
+def shape_stripe_event(payload: Dict[str, Any]) -> Dict[str, Any]:
+ """Flatten one Stripe event into the trigger's output.
+
+ Shaped here rather than in the node's ``shape_output``: a deployed trigger
+ hands downstream nodes ``event.data`` verbatim, so shaping on the node
+ would make Run and deploy disagree about the fields. The envelope used to
+ carry only Stripe's inner ``data``, which left ``created``, ``livemode``,
+ ``api_version`` and ``request`` (top-level Stripe fields) unreadable.
+ ``account`` is set only for Connect events.
+ """
+ request = payload.get("request")
+ nested = payload.get("data")
+ return {
+ "event_id": payload.get("id") or "",
+ "event_type": payload.get("type") or "unknown",
+ "created": payload.get("created"),
+ "livemode": payload.get("livemode"),
+ "api_version": payload.get("api_version"),
+ "request_id": request.get("id") if isinstance(request, dict) else request,
+ "account": payload.get("account"),
+ "data": nested if isinstance(nested, dict) else {},
+ }
+
+
class StripeWebhookSource(WebhookSource):
"""HTTP receiver for Stripe-forwarded events."""
@@ -145,15 +171,16 @@ class StripeWebhookSource(WebhookSource):
time = datetime.fromtimestamp(int(created), tz=timezone.utc) if created else datetime.now(timezone.utc)
except (TypeError, ValueError):
time = datetime.now(timezone.utc)
- account = payload.get("account") or "default"
- return WorkflowEvent(
- id=payload.get("id") or "",
- type=f"stripe.{payload.get('type', 'unknown')}",
- source=f"stripe://{account}",
- time=time,
- data=payload.get("data") or {},
- subject=payload.get("type"),
- )
+ data = shape_stripe_event(payload)
+ return stripe_event_received(data, event_id=data["event_id"], account=data["account"], time=time)
+
+ async def handle(self, request: Request) -> WorkflowEvent:
+ # The base class verifies the signature, shapes the event and wakes a
+ # waiting canvas Run (and the Temporal-off deploy path). Deployed
+ # triggers on Temporal are reached only through emit.
+ event = await super().handle(request)
+ await emit_stripe_event(event)
+ return event
_listen: Optional[StripeListenSource] = None
diff --git a/server/nodes/stripe/stripe_receive.py b/server/nodes/stripe/stripe_receive.py
index c5e0079e..06a6e7e0 100644
--- a/server/nodes/stripe/stripe_receive.py
+++ b/server/nodes/stripe/stripe_receive.py
@@ -3,18 +3,28 @@ forwarded event."""
from __future__ import annotations
-from typing import Callable, Dict, Literal, Optional
+import asyncio
+from typing import Any, Callable, Dict, Literal, Optional, Set
from pydantic import BaseModel, ConfigDict, Field
+from core.logging import get_logger
from services.events import BaseTriggerParams, WebhookTriggerNode, WorkflowEvent
+from services.events.envelope import event_type_matches
from ._credentials import StripeCredential
+from ._events import STRIPE_EVENT_RECEIVED_TYPE
from ._source import StripeWebhookSource
+logger = get_logger(__name__)
+
_PREFIX = "stripe."
+# asyncio keeps only weak references to tasks, so a fire-and-forget daemon
+# start needs a strong one until it finishes.
+_background_tasks: Set[asyncio.Task] = set()
+
class StripeReceiveParams(BaseTriggerParams):
livemode_filter: Literal["all", "test", "live"] = Field(
@@ -36,6 +46,48 @@ class StripeReceiveOutput(BaseModel):
model_config = ConfigDict(extra="allow")
+async def _start_listen_daemon() -> Optional[str]:
+ """Start ``stripe listen`` unless it is already running.
+
+ Returns an error message, or ``None`` once the daemon runs. Stripe events
+ reach ``/webhook/stripe`` only while it does.
+ """
+ from ._source import get_listen_source
+
+ source = get_listen_source()
+ if source._started:
+ return None
+ if not await source.has_credential():
+ return "Stripe not connected. Log in with Stripe in Credentials."
+ result = await source.start()
+ if not (result or {}).get("success", False):
+ error = (result or {}).get("error") or "unknown error"
+ return f"Stripe daemon failed to start: {error}"
+ return None
+
+
+async def _start_listen_daemon_for_deployment(node_id: str, workflow_id: str) -> None:
+ try:
+ error = await _start_listen_daemon()
+ except Exception:
+ logger.warning(
+ "[Stripe] could not start the listen daemon for a deployed stripeReceive",
+ node_id=node_id,
+ workflow_id=workflow_id,
+ exc_info=True,
+ )
+ return
+ if error:
+ # Armed anyway: logging in with Stripe starts the daemon, and events
+ # flow from then on.
+ logger.warning(
+ "[Stripe] deployed stripeReceive is waiting: %s",
+ error,
+ node_id=node_id,
+ workflow_id=workflow_id,
+ )
+
+
class StripeReceiveNode(WebhookTriggerNode):
type = "stripeReceive"
display_name = "Stripe Receive"
@@ -46,56 +98,74 @@ class StripeReceiveNode(WebhookTriggerNode):
handles = ({"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},)
credentials = (StripeCredential,)
webhook_source = StripeWebhookSource
+ # The canvas Run's waiter key, and the type the source dispatches. Left
+ # unset, the base class would derive the source's own type
+ # ("stripe.webhook"), which no envelope carries, so no Run ever resolved.
+ event_type = STRIPE_EVENT_RECEIVED_TYPE
event_type_prefix = _PREFIX
Params = StripeReceiveParams
Output = StripeReceiveOutput
- def _extra_filter(
- self,
- params: StripeReceiveParams,
- ) -> Optional[Callable[[WorkflowEvent], bool]]:
- if params.livemode_filter == "all":
- return None
- target_live = params.livemode_filter == "live"
-
- def matches(ev: WorkflowEvent) -> bool:
- payload = ev.data if isinstance(ev.data, dict) else {}
- return bool(payload.get("livemode")) is target_live
+ def build_filter(self, params: StripeReceiveParams) -> Callable[[Any], bool]:
+ """Match on the shaped event the source emits.
+
+ Both callers hand the predicate the envelope's ``data``: the event
+ waiter on a canvas Run (and the Temporal-off deploy path), and
+ ``evaluate_trigger_filter_activity`` on a deployed Temporal listener.
+ The base filter rebuilds an envelope from what it receives, which
+ raised on every Stripe event; deployed, that failed open and ignored
+ both filters. Every Stripe event shares one CloudEvents type, so the
+ Stripe type is read from ``data["event_type"]``. A pattern may keep the
+ ``stripe.`` prefix the node used to require.
+ """
+ pattern = (params.event_type_filter or "all").strip()
+ if pattern.startswith(_PREFIX):
+ pattern = pattern[len(_PREFIX) :]
+ livemode = params.livemode_filter
+
+ def matches(event: Any) -> bool:
+ data = event.data if isinstance(event, WorkflowEvent) else event
+ if not isinstance(data, dict):
+ return False
+ if not event_type_matches(str(data.get("event_type") or ""), pattern):
+ return False
+ if livemode != "all" and bool(data.get("livemode")) is not (livemode == "live"):
+ return False
+ return True
return matches
async def _check_precondition(self) -> Optional[str]:
- from ._source import get_listen_source
-
- source = get_listen_source()
- if source._started:
- return None
- # Running this trigger is the demand signal: start the listen daemon
- # here instead of relying on a credential-triggered auto-start at boot
- # (the status refresh is a passive probe now). Only a canvas Run gets
- # here: deploy skips stripeReceive, which is not in
- # constants.WORKFLOW_TRIGGER_TYPES.
- if not await source.has_credential():
- return "Stripe not connected. Log in with Stripe in Credentials."
- result = await source.start()
- if not (result or {}).get("success", False):
- error = (result or {}).get("error") or "unknown error"
- return f"Stripe daemon failed to start: {error}"
- return None
+ # A canvas Run is a demand signal, like deploying: start the listen
+ # daemon here instead of relying on a credential-triggered auto-start
+ # at boot (the status refresh is a passive probe).
+ return await _start_listen_daemon()
+
+ @classmethod
+ async def prepare_deployment(
+ cls,
+ *,
+ node_id: str,
+ workflow_id: str,
+ parameters: Dict[str, Any],
+ ) -> None:
+ """Start ``stripe listen`` for a deployed trigger.
+
+ Nothing else starts the daemon after a backend restart, so without
+ this a deployed trigger would stop receiving events at the first
+ restart. Run in the background: a first-use CLI download must not hold
+ up Start or the boot re-arm. When Stripe is not logged in the trigger
+ stays armed, and logging in starts the daemon.
+ """
+ task = asyncio.create_task(_start_listen_daemon_for_deployment(node_id, workflow_id))
+ _background_tasks.add(task)
+ task.add_done_callback(_background_tasks.discard)
def shape_output(self, event: WorkflowEvent) -> Dict:
- payload = event.data if isinstance(event.data, dict) else {}
- stripe_type = event.type[len(_PREFIX) :] if event.type.startswith(_PREFIX) else event.type
- request = payload.get("request")
- request_id = request.get("id") if isinstance(request, dict) else request
- nested = payload.get("data")
- return {
- "event_id": event.id,
- "event_type": stripe_type,
- "created": payload.get("created"),
- "livemode": payload.get("livemode"),
- "api_version": payload.get("api_version"),
- "request_id": request_id,
- "account": payload.get("account") or (event.source.split("://", 1)[1] if "://" in event.source else None),
- "data": nested if isinstance(nested, dict) else payload,
- }
+ """Unwrap the shaped event, which is what the deployed path emits.
+
+ The source already shaped it (``shape_stripe_event``), and a deployed
+ trigger hands downstream nodes ``event.data`` verbatim, so unwrapping
+ here keeps Run and deploy on the same fields.
+ """
+ return event.data if isinstance(event.data, dict) else {}
diff --git a/server/services/deployment/manager.py b/server/services/deployment/manager.py
index 2a6fd687..d27f9554 100644
--- a/server/services/deployment/manager.py
+++ b/server/services/deployment/manager.py
@@ -557,6 +557,8 @@ class DeploymentManager:
node_type = node.get("type", "")
params = await self.database.get_node_parameters(node_id) or {}
+ await self._prepare_trigger_deployment(node_id, node_type, workflow_id, params)
+
# Path 1: Wave 12 C1 canary — Temporal-durable listener.
if await self._canary_listener_enabled_for(node_type):
listener_id = await self._start_canary_listener(node, workflow_id, params)
@@ -600,6 +602,37 @@ class DeploymentManager:
await trigger_manager.setup_event_trigger(node_id, node_type, params, on_event, self._broadcaster, workflow_id=workflow_id)
return TriggerInfo(node_id, node_type)
+ @staticmethod
+ async def _prepare_trigger_deployment(
+ node_id: str,
+ node_type: str,
+ workflow_id: str,
+ params: Dict[str, Any],
+ ) -> None:
+ """Run the trigger class's ``prepare_deployment`` hook.
+
+ Orchestration never branches on node type: a plugin whose events need
+ something running (Stripe's listen daemon) starts it from the hook.
+ Start and the boot re-arm both arrive here. A failing hook is logged
+ and the trigger is armed anyway, so one plugin can never fail a Start
+ or a re-arm.
+ """
+ from services.node_registry import get_node_class
+
+ hook = getattr(get_node_class(node_type), "prepare_deployment", None)
+ if hook is None:
+ return
+ try:
+ await hook(node_id=node_id, workflow_id=workflow_id, parameters=params)
+ except Exception as exc: # noqa: BLE001 — see docstring
+ logger.warning(
+ "Trigger prepare_deployment failed; arming the trigger anyway",
+ node_id=node_id,
+ node_type=node_type,
+ workflow_id=workflow_id,
+ error=str(exc),
+ )
+
# =========================================================================
# WAVE 12 C1 CANARY: TEMPORAL-DURABLE LISTENERS
# =========================================================================
diff --git a/server/services/events/envelope.py b/server/services/events/envelope.py
index 057fadc5..da05d741 100644
--- a/server/services/events/envelope.py
+++ b/server/services/events/envelope.py
@@ -59,6 +59,24 @@ def equivalent_event_types(event_type: str) -> tuple[str, ...]:
return (event_type,)
+def event_type_matches(event_type: str, pattern: str) -> bool:
+ """Glob-style match on an event type. ``"all"``/empty matches any.
+
+ The pattern is matched against the type with the ``com.opencompany.``
+ reverse-DNS prefix stripped. ``"x.*"`` matches ``x`` and every type under
+ it; anything else must match exactly. :meth:`WorkflowEvent.matches_type`
+ applies this to an envelope's ``type``; a trigger whose events share one
+ CloudEvents type applies it to the type it carries in ``data``.
+ """
+ if not pattern or pattern == "all":
+ return True
+ normalized = _unprefixed_event_type(event_type or "")
+ if pattern.endswith(".*"):
+ prefix = pattern[:-2]
+ return normalized.startswith(prefix + ".") or normalized == prefix
+ return normalized == pattern
+
+
def _dataschema_for(event_type: str) -> str:
"""Compute the ``dataschema`` URI for a given event ``type``.
@@ -617,10 +635,4 @@ class WorkflowEvent(BaseModel):
"agent.*" matches "com.opencompany.agent.progress"
"all" or "" matches everything
"""
- if not pattern or pattern == "all":
- return True
- normalized = _unprefixed_event_type(self.type or "")
- if pattern.endswith(".*"):
- prefix = pattern[:-2]
- return normalized.startswith(prefix + ".") or normalized == prefix
- return normalized == pattern
+ return event_type_matches(self.type or "", pattern)
diff --git a/server/services/events/triggers.py b/server/services/events/triggers.py
index 0a5e703c..8cd11c17 100644
--- a/server/services/events/triggers.py
+++ b/server/services/events/triggers.py
@@ -58,6 +58,9 @@ class WebhookTriggerNode(TriggerNode):
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
+ # The canvas Run's waiter key. A source whose ``shape`` returns
+ # envelopes of another type must have its trigger set ``event_type``
+ # to that type, or ``event_waiter.dispatch`` matches no waiter.
if cls.webhook_source is not None and not getattr(cls, "event_type", ""):
cls.event_type = cls.webhook_source.type
@@ -94,11 +97,22 @@ class WebhookTriggerNode(TriggerNode):
return self._wrap_error(start_time=time.time(), error=err)
result = await super().execute(node_id, parameters, context)
if result.get("success"):
- event = result.get("result") or {}
- ev = event if isinstance(event, WorkflowEvent) else WorkflowEvent(**event)
- result["result"] = self.shape_output(ev)
+ result["result"] = self.shape_output(self._as_event(result.get("result")))
return result
+ def _as_event(self, value: Any) -> WorkflowEvent:
+ """Wrap what a resolved waiter returns back into an envelope.
+
+ The event waiter resolves with the envelope's ``data``, not the
+ envelope (``event_waiter._unpack_event``). Rebuilding a
+ ``WorkflowEvent`` from that dict raised, because a payload carries no
+ ``source`` or ``type``.
+ """
+ if isinstance(value, WorkflowEvent):
+ return value
+ path = self.webhook_source.path if self.webhook_source is not None else ""
+ return WorkflowEvent(source=f"webhook://{path}", type=self.event_type, data=value or {})
+
def shape_output(self, event: WorkflowEvent) -> Dict[str, Any]:
"""Default: dump the CloudEvent. Override for provider-shaped output."""
return event.model_dump(mode="json")
diff --git a/server/services/plugin/trigger.py b/server/services/plugin/trigger.py
index 02cfd631..1dc4dc15 100644
--- a/server/services/plugin/trigger.py
+++ b/server/services/plugin/trigger.py
@@ -48,6 +48,24 @@ class TriggerNode(BaseNode, abstract=True):
# ---- subclass hooks ---------------------------------------------------
+ @classmethod
+ async def prepare_deployment(
+ cls,
+ *,
+ node_id: str,
+ workflow_id: str,
+ parameters: Dict[str, Any],
+ ) -> None:
+ """Called each time a deployment arms this trigger: at Start, and when
+ the boot re-arm restores a running or paused generation.
+
+ For a trigger whose events depend on something its plugin runs (the
+ ``stripe listen`` daemon), so deploying is the demand signal. Return
+ quickly and schedule slow work. The deployment manager logs anything
+ this raises and arms the trigger anyway. The default does nothing.
+ """
+ return None
+
def build_filter(self, params: BaseModel) -> Callable[[Dict[str, Any]], bool]:
"""Event mode — return a callable that accepts an event dict
and returns True if this trigger should fire. Default: match all.
diff --git a/server/skills/payments_agent/stripe-skill/SKILL.md b/server/skills/payments_agent/stripe-skill/SKILL.md
index 17e8f92f..e622ae58 100644
--- a/server/skills/payments_agent/stripe-skill/SKILL.md
+++ b/server/skills/payments_agent/stripe-skill/SKILL.md
@@ -219,10 +219,12 @@ include it when reporting issues.
## Webhooks (`stripeReceive` trigger)
-When the Stripe daemon is connected (Credentials Modal → Stripe →
-Connect), every event Stripe sends is forwarded to OpenCompany and
-delivered to any active `stripeReceive` trigger nodes after
-HMAC-SHA256 signature verification (`Stripe-Signature` header).
+While the Stripe listen daemon runs, every event Stripe sends is
+forwarded to OpenCompany and delivered to any active `stripeReceive`
+trigger nodes after HMAC-SHA256 signature verification
+(`Stripe-Signature` header). The daemon starts when you log in with
+Stripe, when a workflow with a `stripeReceive` trigger starts, and on a
+canvas Run of the trigger.
To test event delivery without making real payments, use the
`trigger` command above. Events fire through the same path as real
@@ -298,8 +300,8 @@ and runs `stripe logout --all` to clear the config file.
2. Credentials Modal → Stripe → **Login with Stripe** → a browser
tab opens to the Stripe Dashboard with a pairing code. Authorise.
The modal flips to "Connected" when the CLI's `login --complete`
- subprocess returns and the listen daemon spins up
- (`webhook_secret_captured: true`).
+ subprocess returns and the listen daemon spins up; the daemon
+ captures the webhook signing secret within a few seconds.
3. The `Stripe` action node is connected to your agent's
`input-tools` handle.
4. (For webhook flows) A `stripeReceive` trigger node is wired into
diff --git a/server/tests/nodes/test_stripe_plugin.py b/server/tests/nodes/test_stripe_plugin.py
index 0b810892..3e1ceaeb 100644
--- a/server/tests/nodes/test_stripe_plugin.py
+++ b/server/tests/nodes/test_stripe_plugin.py
@@ -62,6 +62,7 @@ class TestStripeWebhookShape:
)
def test_shape_extracts_stripe_fields(self):
+ from nodes.stripe._events import STRIPE_EVENT_RECEIVED_TYPE
from nodes.stripe._source import get_webhook_source
src = get_webhook_source()
@@ -70,6 +71,8 @@ class TestStripeWebhookShape:
"type": "charge.succeeded",
"created": 1700000000,
"livemode": False,
+ "api_version": "2024-04-10",
+ "request": {"id": "req_9"},
"account": "acct_test",
"data": {"object": {"amount": 1000}},
}
@@ -82,27 +85,52 @@ class TestStripeWebhookShape:
ev = _run(src.shape(FakeReq(), b"", payload))
assert ev.id == "evt_1"
- assert ev.type == "stripe.charge.succeeded"
+ assert ev.type == STRIPE_EVENT_RECEIVED_TYPE
+ assert ev.subject == "charge.succeeded"
assert ev.source == "stripe://acct_test"
- assert ev.data == {"object": {"amount": 1000}}
+ # The top-level Stripe fields survive: the envelope used to carry only
+ # the inner ``data``, so livemode / created / api_version read None.
+ assert ev.data == {
+ "event_id": "evt_1",
+ "event_type": "charge.succeeded",
+ "created": 1700000000,
+ "livemode": False,
+ "api_version": "2024-04-10",
+ "request_id": "req_9",
+ "account": "acct_test",
+ "data": {"object": {"amount": 1000}},
+ }
+
+ def test_account_is_set_only_for_connect_events(self):
+ from nodes.stripe._source import shape_stripe_event
+
+ assert shape_stripe_event({"id": "evt_1", "type": "charge.succeeded"})["account"] is None
- def test_handle_dispatches_on_valid_signature(self):
+ def test_handle_dispatches_and_emits_on_valid_signature(self):
+ from nodes.stripe._events import STRIPE_EVENT_RECEIVED_TYPE
from nodes.stripe._source import get_webhook_source
src = get_webhook_source()
body = json.dumps({"id": "evt_2", "type": "charge.succeeded", "data": {}}).encode()
req = _fake_request(body, headers=_signed(body, self.SECRET))
- with self._stub_secret_resolution(), patch("services.event_waiter.dispatch") as dispatch:
+ with (
+ self._stub_secret_resolution(),
+ patch("services.event_waiter.dispatch") as dispatch,
+ patch("services.events.dispatch.emit", new=AsyncMock()) as emit,
+ ):
ev = _run(src.handle(req))
- assert ev.type == "stripe.charge.succeeded"
- dispatch.assert_called_once()
+ assert ev.type == STRIPE_EVENT_RECEIVED_TYPE
# Dispatched as a lone envelope: the two-argument form means
# ``(event_type, data)``, so passing the event second made ``data``
# the envelope and the dispatcher's ``data.get(...)`` calls raised
# AttributeError once a waiter was active.
(dispatched,) = dispatch.call_args[0]
- assert dispatched.id == "evt_2"
- assert dispatched.type == "stripe.charge.succeeded"
+ assert dispatched is ev
+ # The waiter serves a canvas Run only. Deployed listeners are reached
+ # by emit alone, which the base WebhookSource.handle never calls.
+ emit.assert_awaited_once()
+ assert emit.await_args.args == (ev,)
+ assert emit.await_args.kwargs == {"wire_routing_key": "stripe_event_received"}
def test_handle_rejects_tampered_signature(self):
from fastapi import HTTPException
@@ -111,10 +139,11 @@ class TestStripeWebhookShape:
src = get_webhook_source()
body = json.dumps({"id": "evt_3", "type": "charge.succeeded"}).encode()
req = _fake_request(body, headers=_signed(body, "whsec_other"))
- with self._stub_secret_resolution():
+ with self._stub_secret_resolution(), patch("services.events.dispatch.emit", new=AsyncMock()) as emit:
with pytest.raises(HTTPException) as exc:
_run(src.handle(req))
assert exc.value.status_code == 400
+ emit.assert_not_awaited()
# ============================================================================
@@ -122,70 +151,247 @@ class TestStripeWebhookShape:
# ============================================================================
+def _stripe_payload(stripe_type: str = "charge.succeeded", *, event_id: str = "evt_1", livemode: bool = False) -> dict:
+ """A Stripe event as ``stripe listen`` forwards it."""
+ return {
+ "id": event_id,
+ "object": "event",
+ "type": stripe_type,
+ "created": 1700000000,
+ "livemode": livemode,
+ "api_version": "2024-04-10",
+ "request": {"id": "req_1"},
+ "data": {"object": {"id": "ch_1", "amount": 1000}},
+ }
+
+
class TestStripeReceiveFilter:
+ """Both callers hand the filter the envelope's ``data``: the event waiter
+ on a canvas Run, and ``evaluate_trigger_filter_activity`` once deployed.
+ The base filter rebuilt an envelope from that dict and raised."""
+
def _filter(self, params: dict | None = None):
from nodes.stripe.stripe_receive import StripeReceiveNode, StripeReceiveParams
node = StripeReceiveNode()
return node.build_filter(StripeReceiveParams(**(params or {})))
- def _ev(self, stripe_type: str, livemode: bool = False):
- from services.events import WorkflowEvent
+ def _data(self, stripe_type: str, livemode: bool = False) -> dict:
+ from nodes.stripe._source import shape_stripe_event
- return WorkflowEvent(
- source="stripe://acct_1",
- type=f"stripe.{stripe_type}",
- data={"livemode": livemode},
- )
+ return shape_stripe_event(_stripe_payload(stripe_type, livemode=livemode))
def test_all_matches_anything(self):
f = self._filter({"event_type_filter": "all"})
- assert f(self._ev("charge.succeeded")) is True
- assert f(self._ev("payment_intent.created")) is True
+ assert f(self._data("charge.succeeded")) is True
+ assert f(self._data("payment_intent.created")) is True
def test_exact_match(self):
f = self._filter({"event_type_filter": "charge.succeeded"})
- assert f(self._ev("charge.succeeded")) is True
- assert f(self._ev("charge.refunded")) is False
+ assert f(self._data("charge.succeeded")) is True
+ assert f(self._data("charge.refunded")) is False
def test_wildcard_prefix(self):
f = self._filter({"event_type_filter": "charge.*"})
- assert f(self._ev("charge.succeeded")) is True
- assert f(self._ev("charge.refunded")) is True
- assert f(self._ev("payment_intent.created")) is False
+ assert f(self._data("charge.succeeded")) is True
+ assert f(self._data("charge.refunded")) is True
+ assert f(self._data("payment_intent.created")) is False
+
+ def test_stripe_prefixed_pattern_still_matches(self):
+ """The node once required patterns to work with or without the
+ ``stripe.`` prefix; saved workflows may carry either."""
+ f = self._filter({"event_type_filter": "stripe.charge.*"})
+ assert f(self._data("charge.refunded")) is True
+ assert f(self._data("payment_intent.created")) is False
def test_livemode_filter(self):
live = self._filter({"livemode_filter": "live"})
test = self._filter({"livemode_filter": "test"})
- assert live(self._ev("charge.succeeded", livemode=True)) is True
- assert live(self._ev("charge.succeeded", livemode=False)) is False
- assert test(self._ev("charge.succeeded", livemode=False)) is True
- assert test(self._ev("charge.succeeded", livemode=True)) is False
+ assert live(self._data("charge.succeeded", livemode=True)) is True
+ assert live(self._data("charge.succeeded", livemode=False)) is False
+ assert test(self._data("charge.succeeded", livemode=False)) is True
+ assert test(self._data("charge.succeeded", livemode=True)) is False
+
+ def test_an_envelope_is_accepted_too(self):
+ from nodes.stripe._events import stripe_event_received
+ from datetime import datetime, timezone
+
+ data = self._data("charge.succeeded")
+ envelope = stripe_event_received(data, event_id="evt_1", account=None, time=datetime.now(timezone.utc))
+ assert self._filter({"event_type_filter": "charge.*"})(envelope) is True
class TestStripeReceiveReshape:
- def test_shape_output_extracts_stripe_fields(self):
+ def test_shape_output_is_the_shaped_payload(self):
+ """The source shapes; the node only unwraps, because a deployed
+ trigger hands downstream nodes ``event.data`` verbatim."""
+ from datetime import datetime, timezone
+
+ from nodes.stripe._events import stripe_event_received
+ from nodes.stripe._source import shape_stripe_event
from nodes.stripe.stripe_receive import StripeReceiveNode
- from services.events import WorkflowEvent
-
- ev = WorkflowEvent(
- id="evt_1",
- source="stripe://acct_42",
- type="stripe.charge.succeeded",
- data={
- "request": {"id": "req_99"},
- "data": {"object": {"amount": 2500}},
- "livemode": True,
- "api_version": "2024-04-10",
- },
- )
+
+ data = shape_stripe_event(_stripe_payload())
+ ev = stripe_event_received(data, event_id="evt_1", account=None, time=datetime.now(timezone.utc))
out = StripeReceiveNode().shape_output(ev)
- assert out["event_id"] == "evt_1"
+ assert out == data
assert out["event_type"] == "charge.succeeded"
- assert out["request_id"] == "req_99"
- assert out["account"] == "acct_42"
- assert out["livemode"] is True
- assert out["data"] == {"object": {"amount": 2500}}
+ assert out["request_id"] == "req_1"
+ assert out["livemode"] is False
+ assert out["data"] == {"object": {"id": "ch_1", "amount": 1000}}
+
+
+# ============================================================================
+# StripeReceiveNode — a canvas Run resolves on a real delivery
+# ============================================================================
+
+
+class TestCanvasRunResolves:
+ """End to end through the real event waiter: ``execute`` registers a
+ waiter, ``handle`` dispatches a signed delivery. Before the fix the waiter
+ was keyed ``stripe.webhook``, which no envelope carries; the filter raised
+ on the payload; and ``execute`` raised rebuilding an envelope from it."""
+
+ SECRET = "whsec_run"
+
+ def _scenario(self, params: dict, stripe_type: str):
+ from nodes.stripe._source import get_webhook_source
+ from nodes.stripe.stripe_receive import StripeReceiveNode
+ from services import event_waiter
+
+ node = StripeReceiveNode()
+ body = json.dumps(_stripe_payload(stripe_type)).encode()
+
+ async def run():
+ task = asyncio.create_task(node.execute("stripe-run-node", params, None))
+ # Let execute register its waiter before the delivery arrives.
+ for _ in range(20):
+ if any(w.node_id == "stripe-run-node" for w in event_waiter._waiters.values()):
+ break
+ await asyncio.sleep(0)
+ await get_webhook_source().handle(_fake_request(body, headers=_signed(body, self.SECRET)))
+ try:
+ return await asyncio.wait_for(asyncio.shield(task), timeout=0.5)
+ except asyncio.TimeoutError:
+ return None
+ finally:
+ event_waiter.cancel_for_node("stripe-run-node")
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+
+ with (
+ patch.object(StripeReceiveNode, "_check_precondition", AsyncMock(return_value=None)),
+ patch(
+ "nodes.stripe._source.StripeCredential.resolve",
+ AsyncMock(return_value={"stripe_webhook_secret": self.SECRET}),
+ ),
+ patch("services.events.dispatch.emit", new=AsyncMock()),
+ ):
+ return _run(run())
+
+ def test_matching_delivery_resolves_the_run(self):
+ result = self._scenario({"event_type_filter": "charge.*"}, "charge.succeeded")
+ assert result is not None, "the canvas Run never resolved"
+ assert result["success"] is True, result
+ assert result["result"]["event_id"] == "evt_1"
+ assert result["result"]["event_type"] == "charge.succeeded"
+ assert result["result"]["livemode"] is False
+ assert result["result"]["data"] == {"object": {"id": "ch_1", "amount": 1000}}
+
+ def test_filtered_delivery_leaves_the_run_waiting(self):
+ assert self._scenario({"event_type_filter": "payment_intent.*"}, "charge.succeeded") is None
+
+
+# ============================================================================
+# StripeReceiveNode — the deployed path
+# ============================================================================
+
+
+class TestDeployedPath:
+ def test_trigger_is_deployable(self):
+ """find_trigger_nodes filters on this set. Omission means deploy
+ silently ignores the node -- no listener, no error."""
+ from constants import EVENT_TRIGGER_TYPES, WORKFLOW_TRIGGER_TYPES
+
+ assert "stripeReceive" in WORKFLOW_TRIGGER_TYPES
+ assert "stripeReceive" in EVENT_TRIGGER_TYPES
+
+ def test_canary_type_matches_every_emitted_envelope(self):
+ """The Visibility query asks for the envelope's type and the listener
+ advertises the registered one; a mismatch delivers nothing, silently.
+ Every Stripe event must therefore carry the same type."""
+ from nodes.stripe._events import STRIPE_EVENT_RECEIVED_TYPE
+ from nodes.stripe._source import get_webhook_source
+ from nodes.stripe.stripe_receive import StripeReceiveNode
+ from services.deployment.canary_registry import cloudevent_type_for
+
+ assert cloudevent_type_for("stripeReceive") == STRIPE_EVENT_RECEIVED_TYPE
+ assert StripeReceiveNode.event_type == STRIPE_EVENT_RECEIVED_TYPE
+ for stripe_type in ("charge.succeeded", "payment_intent.created", "customer.subscription.deleted"):
+ ev = _run(get_webhook_source().shape(None, b"", _stripe_payload(stripe_type)))
+ assert ev.type == STRIPE_EVENT_RECEIVED_TYPE
+ assert ev.subject == stripe_type
+
+ def test_envelope_carries_no_workflow_id(self):
+ """Setting it would scope delivery to one deployment; a Stripe event
+ is meant to reach every deployment carrying the trigger."""
+ from nodes.stripe._source import get_webhook_source
+
+ ev = _run(get_webhook_source().shape(None, b"", _stripe_payload()))
+ assert ev.workflow_id is None
+
+ @pytest.mark.parametrize(
+ ("filter_params", "stripe_type", "livemode", "admitted"),
+ [
+ ({"event_type_filter": "charge.*"}, "charge.refunded", False, True),
+ ({"event_type_filter": "charge.*"}, "payment_intent.created", False, False),
+ ({"livemode_filter": "live"}, "charge.succeeded", True, True),
+ ({"livemode_filter": "live"}, "charge.succeeded", False, False),
+ ],
+ )
+ def test_deployed_filter_applies_and_does_not_fail_open(self, filter_params, stripe_type, livemode, admitted):
+ """The deployed listener runs the node's filter through this activity,
+ which admits the event when the filter raises. The old filter raised on
+ every Stripe payload, so deployed filters were silently ignored."""
+ from nodes.stripe._source import shape_stripe_event
+ from services.temporal.activities import evaluate_trigger_filter_activity
+
+ data = shape_stripe_event(_stripe_payload(stripe_type, livemode=livemode))
+ result = _run(
+ evaluate_trigger_filter_activity(
+ {"node_type": "stripeReceive", "filter_params": filter_params, "event_data": data}
+ )
+ )
+ assert result is admitted
+
+
+class TestPrepareDeployment:
+ """Nothing else starts ``stripe listen`` after a backend restart, so the
+ deploy (and boot re-arm) hook must, without holding up Start."""
+
+ def _drain(self):
+ from nodes.stripe import stripe_receive
+
+ async def run(starter):
+ with patch.object(stripe_receive, "_start_listen_daemon", starter):
+ await stripe_receive.StripeReceiveNode.prepare_deployment(
+ node_id="n1", workflow_id="wf1", parameters={}
+ )
+ pending = list(stripe_receive._background_tasks)
+ assert pending, "prepare_deployment scheduled nothing"
+ await asyncio.gather(*pending)
+
+ return run
+
+ def test_starts_the_listen_daemon_in_the_background(self):
+ starter = AsyncMock(return_value=None)
+ _run(self._drain()(starter))
+ starter.assert_awaited_once()
+
+ def test_a_failed_start_is_logged_not_raised(self):
+ _run(self._drain()(AsyncMock(return_value="Stripe not connected. Log in with Stripe in Credentials.")))
+ _run(self._drain()(AsyncMock(side_effect=RuntimeError("download failed"))))
# ============================================================================
@@ -299,10 +505,14 @@ class TestStripePluginRegistration:
assert StripeActionNode.usable_as_tool is True
- def test_receive_node_subscribes_to_stripe_webhook(self):
+ def test_receive_node_waits_for_the_type_the_source_dispatches(self):
+ """Not the source's own type (``stripe.webhook``): no envelope carries
+ that, so a waiter keyed on it never resolved."""
+ from nodes.stripe._events import STRIPE_EVENT_RECEIVED_TYPE
from nodes.stripe.stripe_receive import StripeReceiveNode
- assert StripeReceiveNode.event_type == "stripe.webhook"
+ assert StripeReceiveNode.event_type == STRIPE_EVENT_RECEIVED_TYPE
+ assert StripeReceiveNode.webhook_source.type == "stripe.webhook"
def test_listen_source_has_correct_namespace(self):
from nodes.stripe._source import get_listen_source
diff --git a/server/tests/test_deployment_canary_listener.py b/server/tests/test_deployment_canary_listener.py
index f9390b12..d4c8a13e 100644
--- a/server/tests/test_deployment_canary_listener.py
+++ b/server/tests/test_deployment_canary_listener.py
@@ -859,3 +859,58 @@ async def test_pause_status_disarms_trigger_nodes_without_touching_agents():
broadcaster.update_node_status.assert_awaited_once_with(
"chat-1", "idle", {"paused": True, "message": "Paused"}, workflow_id="wf-pause",
)
+
+
+class TestTriggerPrepareDeployment:
+ """Arming a trigger runs its class's ``prepare_deployment`` hook, so a
+ plugin whose events need something running (Stripe's listen daemon) can
+ start it at Start and at the boot re-arm, both of which arrive in
+ ``_setup_event_trigger``. A failing hook must never stop the trigger
+ from being armed."""
+
+ def _arm(self, monkeypatch, hook):
+ from services import node_registry
+ from services.deployment.manager import DeploymentManager
+
+ class _Trigger:
+ prepare_deployment = hook
+
+ monkeypatch.setattr(node_registry, "get_node_class", lambda node_type: _Trigger)
+ monkeypatch.setattr(DeploymentManager, "_canary_listener_enabled_for", AsyncMock(return_value=False))
+ mgr, _ = _build_manager_with_state("wf-prep", nodes=[], edges=[])
+ mgr.database.get_node_parameters = AsyncMock(return_value={"event_type_filter": "charge.*"})
+ trigger_manager = MagicMock()
+ trigger_manager.setup_event_trigger = AsyncMock()
+ mgr._trigger_managers["wf-prep"] = trigger_manager
+ return mgr, trigger_manager
+
+ @pytest.mark.asyncio
+ async def test_hook_runs_before_the_trigger_is_armed(self, monkeypatch):
+ hook = AsyncMock()
+ mgr, trigger_manager = self._arm(monkeypatch, hook)
+
+ await mgr._setup_event_trigger(_node("stripe-1", "stripeReceive"), "wf-prep")
+
+ hook.assert_awaited_once_with(
+ node_id="stripe-1", workflow_id="wf-prep", parameters={"event_type_filter": "charge.*"},
+ )
+ trigger_manager.setup_event_trigger.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_a_raising_hook_still_arms_the_trigger(self, monkeypatch):
+ mgr, trigger_manager = self._arm(monkeypatch, AsyncMock(side_effect=RuntimeError("boom")))
+
+ await mgr._setup_event_trigger(_node("stripe-1", "stripeReceive"), "wf-prep")
+
+ trigger_manager.setup_event_trigger.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_unknown_node_type_is_armed_without_a_hook(self, monkeypatch):
+ from services import node_registry
+
+ mgr, trigger_manager = self._arm(monkeypatch, AsyncMock())
+ monkeypatch.setattr(node_registry, "get_node_class", lambda node_type: None)
+
+ await mgr._setup_event_trigger(_node("x-1", "notARegisteredType"), "wf-prep")
+
+ trigger_manager.setup_event_trigger.assert_awaited_once()