Skip to content

Self-improving AI Employees for everyone

feat(approvals): a call that broke off is not run again; the owner gets a card (RFC-0006 1b.1b)

trohitge02cc61fe54f
diff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.md
index af5e5813..d84a6bee 100644
--- a/docs-internal/TEMPORAL_ARCHITECTURE.md
+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md
@@ -850,6 +850,11 @@ unsandboxed like the other framework workflows):
- `approvals.record_outcome` records `sent`, `not_sent` (the node said it did not go) or `unknown` (the activity
broke off, so it may have gone), and leaves the employee an `[update]` note for its next chat turn.
+A send that broke off midway outside this workflow leaves a card the same way (`outcome: unknown`, see "Worker crashes
+mid-execution" below). A graph node's card keeps what the node sent, its templates resolved and its secrets left out;
+its Send again runs the node with no graph and no tool arguments (`approvals.execution.node_context`), so nothing
+resolves again and the node's saved settings put the secrets back.
+
The bookkeeping activities retry until they land. Both are in every framework worker's activity list
(`services/approvals/activities.py::APPROVAL_ACTIVITIES`), and the workflow class is in `_framework_workflows`. A
send that never started (the server stopped between the decision and the start) is started again by the approvals
@@ -922,7 +927,7 @@ Trigger nodes that aren't the firing trigger are:
|----------|----------|
| Ordinary node or agent-support Activity fails transiently | The shared ordinary default is 3 attempts with backoff; declared plugin policies and specialized support policies take precedence. |
| `AgentWorkflow` LLM-step activity fails | `LLM_STEP_RETRY` retries without limit (`maximum_attempts=0`, 5 s → 5 min backoff; `services/temporal/_retry_policies.py`) unless the provider error category is non-retryable (invalid_request, authentication, ...). Provider SDK retries stay disabled so Temporal owns the retry schedule and `retry_after` hints. |
-| Worker crashes mid-execution | Workflow state replays from history; an unfinished Activity retries according to its timeout/retry policy on an eligible worker. Completed recorded work is not explicitly rescheduled by Resume. |
+| Worker crashes mid-execution | Workflow state replays from history; an unfinished Activity retries according to its timeout/retry policy on an eligible worker. Completed recorded work is not explicitly rescheduled by Resume. A node or tool call that is not safe to repeat (`services/approvals/repeats.py`) is not run again: its later attempt answers that it may have happened, and the owner gets a card (`tool_calls.redo_refusal` and `record_unknown`); a graph node's answer carries `requires_user_action`, so its employee pauses at once. |
| A node/tool Activity times out | Temporal applies the scheduled retry policy. Graph timeout/heartbeat defaults and version 1 agent-tool/plugin options differ as described above. |
| All retries exhausted | Workflow receives failure, stops execution |
diff --git a/docs-internal/chat_protocol.md b/docs-internal/chat_protocol.md
index 155df628..a6f3c1cd 100644
--- a/docs-internal/chat_protocol.md
+++ b/docs-internal/chat_protocol.md
@@ -157,9 +157,9 @@ chat reducer remain terminal even when a control snapshot is present.
| Handler | Request | Response |
|---|---|---|
-| `list_approvals` | `{workflow_id?, status?: <row status> \| "open" \| "recent", run_id?, kind?: "gate" \| "tool_call", limit? (at most 100)}`; `status` defaults to `pending` | `{success, approvals, counts: {workflow_id: pending}, server_time}` |
+| `list_approvals` | `{workflow_id?, status?: <row status> \| "open" \| "recent", run_id?, kind?: "gate" \| "tool_call" \| "effect", limit? (at most 100)}`; `status` defaults to `pending` | `{success, approvals, counts: {workflow_id: pending}, server_time}` |
| `get_approvals` | `{approval_ids}` (at most 100) | `{success, approvals, server_time}` |
-| `decide_approval` | `{approval_id, decision: "send" \| "undo" \| "discard" \| "restore" \| "retry", decision_key, text?, subject?, confirm?}` | `{success, approval, idempotent?, will_send_on_resume}` |
+| `decide_approval` | `{approval_id, decision: "send" \| "undo" \| "discard" \| "restore" \| "retry" \| "dismiss", decision_key, text?, subject?, confirm?}` | `{success, approval, idempotent?, will_send_on_resume}` |
| `get_ask_first` | `{workflow_id}` | `{success, workflow_id, ask_first: bool \| null, revision}` (null: the workflow has no rule) |
| `set_ask_first` | `{workflow_id, ask_first, expected_revision?}` | `{success, workflow_id, ask_first, revision, replies_gated, needs_apply}`; `rule_conflict` (with the current value) when it moved |
@@ -170,7 +170,7 @@ and workflows answer; any other id reads as `not_found`. `decide_approval` error
broke off), `approval_conflict`, `send_unavailable` (nothing could start the send; the draft is back as it was),
`not_found`, `invalid_request`. The same `decision_key` again answers `idempotent` with the row as it is.
-**ApprovalSummary**: `{approval_id, workflow_id, node_id, kind: "gate" | "tool_call", status, channel,
+**ApprovalSummary**: `{approval_id, workflow_id, node_id, kind: "gate" | "tool_call" | "effect", status, channel,
channel_label, action?, recipient, recipient_label, body, subject?, context_excerpt?, details: [{label, value}],
created_at, expires_at, revision, max_length, editable, approved_by?: "owner" | "auto", edited?, undo_until?,
restore_until?, consumed_at?, outcome?: {certainty: "sent" | "not_sent" | "unknown", error?, at?},
@@ -538,7 +538,9 @@ What an employee sends to someone waits for the owner's OK while its workflow as
first time anything asks (a seeder the employees package registers), and a change is mirrored back into those
rules and the employee's card. A workflow with no row (one built in the editor) has no rule: its tool calls run
as before, and its approval gates wait for the owner as they always did.
-- **Two kinds of draft.** A `gate` row is an approvalGate node holding its run (an app reply). A `tool_call` row is
+- **Two kinds of draft, and one card for what may have happened.** A `gate` row is an approvalGate node holding its
+ run (an app reply). An `effect` row is a call that broke off midway and may have happened (see "At most once"
+ below); the owner checks it and dismisses it. A `tool_call` row is
a call to a tool whose plugin declares an `approval` spec (`services/plugin/approval.py`: which operations send,
who it goes to, the body and subject the owner may edit, the card's other lines). `BaseNode.as_activity` checks
every agent tool call (`services/approvals/tool_calls.py`): with Ask first on, a call that sends does not run; its
@@ -556,8 +558,8 @@ What an employee sends to someone waits for the owner's OK while its workflow as
- **Decisions** (`services/approvals/decisions.py`), each a compare-and-swap on the row's revision recorded in
`approval_decisions`: `send` (pending -> approved; it goes after `UNDO_SECONDS`, 5, and Undo works until then),
`undo` (approved -> pending), `discard` (pending -> discarded; Restore works for `RESTORE_SECONDS` on a gate's draft,
- whose run waits that long, and until expiry for a held call), `restore` and `retry` (failed -> approved; when the
- send broke off it may have gone, so the owner confirms). A gate waits through the Undo and Restore windows before
+ whose run waits that long, and until expiry for a held call), `restore`, `retry` (failed -> approved; when the
+ send broke off it may have gone, so the owner confirms) and `dismiss` (an `effect` row: failed -> cancelled). A gate waits through the Undo and Restore windows before
it lets the draft through or not.
- **Sending a held call.** Send starts `ApprovedToolCallWorkflow` (`approval-send-<id>-r<revision>`): it sleeps until
the Undo window closes, claims the row at that revision (`approvals.claim_send`: approved -> sending; an Undo, a
@@ -565,14 +567,21 @@ What an employee sends to someone waits for the owner's OK while its workflow as
the outcome (`approvals.record_outcome`): `sent`, `not_sent`, or `unknown` when the activity broke off. The node's
activity runs only under that claim. The first time the drafts are listed after a start, sends that never started
are started again and sends that never reported end `failed` with an unknown outcome.
-- **At most once.** Temporal runs a tool activity again only when an attempt broke off (the worker stopped, a
- timeout); a failure the node reports comes back as a result and is not retried. A later attempt of an agent's call
- that sends (Ask first off, or no rule) therefore does not send again (`tool_calls.resend_refusal`, checked in
- `BaseNode.as_activity` after the gate): the model reads `SendOutcomeUnknown` (it may have gone out), and a call
- answering the owner in the chat is recorded with outcome `unknown`, so the card offers Try again behind a
- confirmation. Held calls are drafts, made once per call, and still retry.
+- **At most once.** Temporal runs an activity again only when an attempt broke off (the worker stopped, a timeout);
+ a failure the node reports comes back as a result and is not retried. A later attempt runs only a call that is
+ safe to repeat (`services/approvals/repeats.py`: reads, waits, keyed calls, operations that do the same thing
+ twice); any other call is not run again (`tool_calls.redo_refusal`, checked in `BaseNode.as_activity` after the
+ approvals check, in the Coding Agent's workspace tools and in the legacy node activity). It answers
+ `SendOutcomeUnknown` (a send the card can show: it may have gone out) or `OutcomeUnknown` (it may have happened),
+ and `tool_calls.record_unknown` leaves the owner a card with outcome `unknown`: a `tool_call` row for such a send,
+ with Send again behind a confirmation, else an `effect` row with Dismiss (`dismiss`: failed -> cancelled), which
+ shows what the call ran with, without secrets. A graph node's answer carries `requires_user_action` and a `hint`,
+ so its employee pauses at once, and its employee reads an `[update]` note; a graph node's send keeps what it sent,
+ its templates resolved and its secrets left out, so Send again resends it and the node's settings put the secrets
+ back. Held calls are drafts, made once per call, and still retry.
- **The employee hears how it went**: an `[update]{...}[/update]` note (`approval:<id>`) at the start of its next
- turn in the chat, for a send that went, failed, was discarded or expired.
+ turn in the chat, for a send that went, failed, was discarded or expired, and for a graph node's call that may
+ have happened.
- **In the chat.** A draft made answering the owner is recorded on the run (`parts.approvals`) and shown at once (an
`activity.snapshot` with `activity_type: "approval"`); its card sits on that reply. A draft made in a run a button
press started (its owner message carries `meta.ui_event`) records that interface (`ui_part_id`,
@@ -580,8 +589,9 @@ What an employee sends to someone waits for the owner's OK while its workflow as
gate's, from the employee's own work) show after the conversation. The card (`features/chat/approval/`): Discard /
Edit / Send while it waits, "Sends in Ns" with Undo, Sending, Sent (and when, and whether Ask first was off),
Restore while it can, Try again (asking first when it may have gone), and "Sends when you resume" for a gate's
- draft whose employee is paused. Countdowns use the server's clock (`server_time`). Ctrl/Cmd+Enter sends the newest
- waiting draft; in the edit box it sends that one.
+ draft whose employee is paused. An `effect` card has no recipient and no message: "{name} tried to …", May have
+ happened, and Dismiss only (Dismissed afterwards). Countdowns use the server's clock (`server_time`).
+ Ctrl/Cmd+Enter sends the newest waiting draft; in the edit box it sends that one.
- **Ends.** Clearing or resetting the chat cancels the drafts its runs made that still wait, and their failed sends,
whose Try again would send from a conversation that is gone; a Reset cancels the waiting gates too
(`approvalGate.reset_execution_state`); deleting the workflow deletes its drafts and its rule. Leaving a branch
diff --git a/server/models/approvals.py b/server/models/approvals.py
index c84cd5cc..5cb78e86 100644
--- a/server/models/approvals.py
+++ b/server/models/approvals.py
@@ -1,6 +1,7 @@
"""What waits for the owner's OK, and what the owner decided.
-``ApprovalRequest`` is one thing to send, of one of two kinds (``kind``):
+``ApprovalRequest`` is one thing to send, or one that may have happened, of
+one of three kinds (``kind``):
- ``gate``: an approvalGate node holds its run until the owner decides. It
creates its row the first time it runs and finds the same row on every
@@ -13,7 +14,13 @@
later (``ApprovedToolCallWorkflow``), once. Its key is
``c:<workflow>:<execution>:<tool call id>``. With Ask first off the call
runs at once, and a Talk call still leaves a row (``approved_by: auto``) so
- the owner sees what went out.
+ the owner sees what went out. A send that broke off midway leaves one too
+ (``failed``, ``outcome: unknown``); a graph node's (key ``u:<temporal
+ workflow>:<run>:<activity>``) keeps what it sent, without secrets.
+- ``effect``: any other call that broke off midway and may have happened
+ (services/approvals/tool_calls.py ``record_unknown``), keyed ``e:`` plus
+ the call's or the activity's identity. It starts ``failed`` with
+ ``outcome: unknown``; the owner checks it and dismisses it.
``status``::
@@ -23,6 +30,7 @@
pending -> discarded Discard
discarded -> pending Restore, before restore_until
failed -> approved Retry (asks to confirm when the outcome is unknown)
+ failed -> cancelled Dismiss (an effect row)
pending | approved | discarded -> expired | cancelled
Every move is a compare-and-swap on ``revision``. ``ApprovalDecision`` keeps
@@ -60,7 +68,7 @@ class ApprovalRequest(SQLModel, table=True):
#: ``temporal`` or ``local``: a local wait cannot outlive its process.
runtime: str = Field(default="local", max_length=20)
status: str = Field(default="pending", index=True, max_length=20)
- #: ``gate`` or ``tool_call`` (see the module docstring).
+ #: ``gate``, ``tool_call`` or ``effect`` (see the module docstring).
kind: str = Field(default="gate", max_length=20)
#: The app it goes out through ("WhatsApp").
@@ -135,7 +143,7 @@ class ApprovalDecision(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
approval_id: str = Field(index=True, max_length=64)
- #: send | undo | discard | restore | retry
+ #: send | undo | discard | restore | retry | dismiss
decision: str = Field(max_length=20)
decision_key: str = Field(max_length=128)
actor: str = Field(default="owner", max_length=255)
diff --git a/server/services/approvals/contract.py b/server/services/approvals/contract.py
index 91866924..55800abd 100644
--- a/server/services/approvals/contract.py
+++ b/server/services/approvals/contract.py
@@ -9,7 +9,9 @@ The gate's output fails closed: ``text``, ``subject`` and ``recipient`` are
empty unless the draft was approved, so a mis-wired graph sends nothing.
A tool call that sends is held the same way (``services/approvals/
-tool_calls.py``), as a row of kind ``tool_call``.
+tool_calls.py``), as a row of kind ``tool_call``. A call that broke off
+midway and may have happened leaves a card: a ``tool_call`` row for a send
+the card can show, else an ``effect`` row, which the owner dismisses.
"""
from __future__ import annotations
@@ -24,7 +26,7 @@ NO_REPLY = "NO_REPLY"
#: How long a draft waits for the owner before it expires.
DEFAULT_TIMEOUT_HOURS = 168
-APPROVAL_KINDS = ("gate", "tool_call")
+APPROVAL_KINDS = ("gate", "tool_call", "effect")
APPROVAL_STATUSES = ("pending", "approved", "sending", "sent", "failed", "discarded", "expired", "cancelled")
#: Nothing moves a row out of these.
FINAL_STATUSES = frozenset({"sent", "expired", "cancelled"})
diff --git a/server/services/approvals/decisions.py b/server/services/approvals/decisions.py
index cef9aebb..7910cb34 100644
--- a/server/services/approvals/decisions.py
+++ b/server/services/approvals/decisions.py
@@ -12,6 +12,9 @@
- **retry** (failed -> approved): a held call whose send failed goes again
after a new grace. When it broke off mid-way it may have gone out already,
so a retry then needs ``confirm``.
+- **dismiss** (failed -> cancelled): an ``effect`` row, a call that broke
+ off midway and may have happened, once the owner has checked it. Nothing
+ runs.
Each decision is a compare-and-swap on the row's revision, recorded with its
``decision_key`` in the same transaction (``approval_decisions``): the same
@@ -32,7 +35,7 @@ from services.approvals import store
from services.approvals.contract import DEFAULT_TIMEOUT_HOURS, RESTORE_SECONDS, UNDO_SECONDS
from services.approvals.listeners import change_of, notify_approval_changed
-DECISIONS = ("send", "undo", "discard", "restore", "retry")
+DECISIONS = ("send", "undo", "discard", "restore", "retry", "dismiss")
#: Why a decision on a row that already moved on was refused.
SETTLED_ERRORS = {
"approved": "already_decided",
@@ -161,6 +164,10 @@ async def decide(
if row.status != "discarded" or restore is None or restore <= now:
raise DecisionRefused("too_late", "It can no longer be restored.")
moved = await _move(database, row, ("discarded",), "pending", {"restore_until": None, "decided_at": None}, record)
+ elif decision == "dismiss":
+ if kind != "effect" or row.status != "failed":
+ raise DecisionRefused("invalid_request", "Only a call that may have happened can be dismissed.")
+ moved = await _move(database, row, ("failed",), "cancelled", {"decided_at": now, "decision_key": decision_key}, record)
else: # retry
if kind != "tool_call" or row.status != "failed":
raise DecisionRefused("invalid_request", "Only a send that failed can be tried again.")
diff --git a/server/services/approvals/execution.py b/server/services/approvals/execution.py
index f69a5e72..e5d3a161 100644
--- a/server/services/approvals/execution.py
+++ b/server/services/approvals/execution.py
@@ -80,15 +80,19 @@ def node_activity_name(node_type: str) -> Optional[str]:
def node_context(row: Any, token: str) -> Dict[str, Any]:
- """What the node's activity runs with."""
+ """What the node's activity runs with. A graph node's card (no agent)
+ keeps what it sent with its templates already resolved: it runs with no
+ graph, so nothing resolves again and blanks it, and with no tool
+ arguments, so a tool node keeps the saved operation."""
+ graph = not row.agent_node_id
return {
"node_id": row.tool_node_id or row.node_id,
"node_type": row.node_type,
"node_data": dict(row.node_data or {}),
- "tool_args": dict(row.args or {}),
+ **({} if graph else {"tool_args": dict(row.args or {})}),
"inputs": {},
- "nodes": [],
- "edges": [],
+ "nodes": None if graph else [],
+ "edges": None if graph else [],
"workflow_id": row.workflow_id,
"session_id": row.workflow_id,
"execution_id": row.execution_id,
@@ -184,9 +188,10 @@ async def record_outcome(database: Any, approval_id: str, token: str, outcome: s
def update_note(row: Any) -> Optional[str]:
"""The ``[update]`` line the employee reads about one of its drafts."""
+ maybe = "may or may not have happened" if row.kind == "effect" else "may or may not have gone out"
result = {
"sent": "sent",
- "failed": "not sent" if row.outcome == "not_sent" else "may or may not have gone out",
+ "failed": "not sent" if row.outcome == "not_sent" else maybe,
"discarded": "discarded by the owner",
"expired": "expired unsent",
"cancelled": "cancelled unsent",
diff --git a/server/services/approvals/handlers.py b/server/services/approvals/handlers.py
index 85775fb0..4ad351f9 100644
--- a/server/services/approvals/handlers.py
+++ b/server/services/approvals/handlers.py
@@ -10,7 +10,7 @@ on its way) or ``recent`` (everything, newest first); default ``pending``.
``decide_approval {approval_id, decision, decision_key, text?, subject?,
confirm?}`` -> ``{approval, idempotent?, will_send_on_resume}``. Decisions:
-``send``, ``undo``, ``discard``, ``restore``, ``retry``
+``send``, ``undo``, ``discard``, ``restore``, ``retry``, ``dismiss``
(services/approvals/decisions.py). Sending a held tool call starts its send
(services/approvals/execution.py). Errors: ``already_decided``,
``expired``, ``cancelled``, ``too_late``, ``confirm_required``,
@@ -35,6 +35,7 @@ from fastapi import WebSocket
from core.logging import get_logger
from services.approvals import decisions, execution, rules, store, waiter
+from services.approvals.contract import APPROVAL_KINDS
from services.approvals.listeners import change_of, notify_approval_changed
from services.approvals.reconcile import reconcile_once
from services.authz.ws_surface import execution_principal
@@ -45,7 +46,7 @@ logger = get_logger(__name__)
MAX_LIST = 100
_ROW_STATUSES = ("pending", "approved", "sending", "sent", "failed", "discarded", "expired", "cancelled")
#: The lifecycle stage each decision announces.
-_STAGES = {"send": "decided", "discard": "decided", "undo": "undone", "restore": "restored", "retry": "decided"}
+_STAGES = {"send": "decided", "discard": "decided", "undo": "undone", "restore": "restored", "retry": "decided", "dismiss": "cancelled"}
def _now() -> str:
@@ -86,7 +87,7 @@ async def handle_list_approvals(data: Dict[str, Any], websocket: WebSocket) -> D
owner = execution_principal(data, websocket)
workflow_id = str(data.get("workflow_id") or "").strip() or None
run_id = str(data.get("run_id") or "").strip() or None
- kind = data.get("kind") if data.get("kind") in ("gate", "tool_call") else None
+ kind = data.get("kind") if data.get("kind") in APPROVAL_KINDS else None
status = data.get("status")
limit = _limit(data)
if status == "open":
diff --git a/server/services/approvals/tool_calls.py b/server/services/approvals/tool_calls.py
index 20bd8796..33097d10 100644
--- a/server/services/approvals/tool_calls.py
+++ b/server/services/approvals/tool_calls.py
@@ -23,16 +23,20 @@ which calls :func:`check_in_process`. Such a call cannot wait as a draft, so
while the workflow asks first a call that sends is refused (a restricted
tool runs restricted); no row is written.
-**At most once.** Temporal runs a tool activity again only when an attempt
+**At most once.** Temporal runs an activity again only when an attempt
broke off (the worker stopped, a timeout): a failure the node reports comes
-back as a result and is not retried. The attempt that broke off may have
-sent the message, so a later attempt of a call that sends does not send it
-again (:func:`resend_refusal`): the model reads that it may have gone out,
-and with Ask first off the chat's record says so (``outcome: unknown``). The
-owner's approved sends already run with no retry
-(services/temporal/approved_tool_call_workflow.py). A tool that Ask first
-restricts instead of holding (the browser) keeps its own retries: its later
-attempt resumes a wait the worker cut short (``NodeWaitInterrupted``).
+back as a result and is not retried. The attempt that broke off may have done
+what it was asked, so a later attempt runs only a call that is safe to repeat
+(services/approvals/repeats.py); any other call answers that it may already
+have happened (:func:`redo_refusal`), and the owner gets a card
+(:func:`record_unknown`, ``outcome: unknown``): "May have sent" for a send
+the card can show, with Send again behind a confirmation, else "May have
+happened" (an ``effect`` row) with Dismiss. A graph node's answer needs the
+owner (``requires_user_action``), so its employee pauses at once; a graph
+node's send keeps what it sent, without secrets, for Send again. The owner's
+approved sends run with no retry
+(services/temporal/approved_tool_call_workflow.py), and the workflow that
+claimed one records how it went.
What a node sends as (its locked ``server_controlled_fields``: the account,
the mailbox) never comes from the model, so the row keeps the call's
@@ -44,10 +48,11 @@ setting first, so it can never talk a call out of being held.
from __future__ import annotations
+import json
import uuid
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
-from typing import Any, Awaitable, Callable, Dict, Mapping, Optional
+from typing import Any, Awaitable, Callable, Dict, List, Mapping, Optional
from core.logging import get_logger
from services.approvals import rules, store
@@ -70,6 +75,14 @@ RESEND_MESSAGE = (
"Not sent again: the first try at this broke off, and it may already have gone out. "
"Do not send it again unless the owner asks; tell them it may or may not have gone out."
)
+REDO_MESSAGE = (
+ "Not run again: the first try at this broke off midway, and it may already have happened. "
+ "Do not run it again unless the owner asks; tell them it may or may not have happened."
+)
+#: What a graph node's answer adds: no model reads it, the owner does.
+REDO_HINT = "The first try broke off midway, so it may already have happened. Check before you resume the employee."
+#: The most of a graph node's send a card keeps for Send again.
+MAX_KEPT_SEND = 64 * 1024
@dataclass
@@ -329,7 +342,8 @@ async def _show_in_chat(database: Any, context: Mapping[str, Any], row: Any) ->
def _auto_recorder(database: Any, context: Mapping[str, Any], node_cls: Any, spec: Any, node_data: Mapping[str, Any]):
async def record(result: Dict[str, Any], *, unknown: bool = False) -> None:
"""Record how the call went; ``unknown``: it may have gone out
- (an attempt broke off, see :func:`resend_refusal`)."""
+ (an attempt broke off, see :func:`redo_refusal`). The card words
+ that itself, so it keeps no error then."""
try:
success = not unknown and bool(isinstance(result, dict) and result.get("success", True) is not False)
now = _utcnow()
@@ -340,7 +354,7 @@ def _auto_recorder(database: Any, context: Mapping[str, Any], node_cls: Any, spe
decided_at=now,
consumed_at=now,
outcome="sent" if success else ("unknown" if unknown else "not_sent"),
- outcome_error=None if success else str((result or {}).get("error") or "It did not go out.")[:1000],
+ outcome_error=None if success or unknown else str((result or {}).get("error") or "It did not go out.")[:1000],
outcome_at=now,
final_text=fields.get("draft_text"),
)
@@ -364,19 +378,210 @@ def _attempt() -> int:
return 1
-def resend_refusal(context: Mapping[str, Any], node_cls: Any, node_data: Mapping[str, Any]) -> Optional[Dict[str, Any]]:
- """What a later attempt of an agent's call that sends answers instead
- of sending (see the module docstring), or None to run it."""
+def _sends(spec: Any, data: Mapping[str, Any]) -> bool:
+ """A send the card can show, and send again. The browser restricts
+ instead of holding, and a page action is not one."""
+ return spec is not None and not spec.restrict_while_asking and spec.sends(data)
+
+
+async def repeatable_call(context: Mapping[str, Any], node_cls: Any, node_data: Mapping[str, Any]) -> bool:
+ """Whether a call may run again after an attempt broke off
+ (services/approvals/repeats.py), judged on what it runs with: the node's
+ settings with the call's data over them, locked fields put back. Not
+ safe when the settings cannot be read."""
+ from services.approvals.repeats import REPEATABLE, REPEATABLE_WHEN, repeatable
+ from services.plugin.base import restore_locked_fields, saved_settings
+
+ node_type = getattr(node_cls, "type", "")
+ if node_type in REPEATABLE or node_type not in REPEATABLE_WHEN:
+ return node_type in REPEATABLE
+ try:
+ saved = await saved_settings(_database(), str(context.get("node_id") or ""), context.get("parameter_snapshot"))
+ except Exception:
+ logger.warning("Could not read a node's settings; the call will not run again", node_id=context.get("node_id"), exc_info=True)
+ return False
+ data = restore_locked_fields(node_cls, {**saved, **dict(node_data or {})}, context.get("tool_args"), saved)
+ return repeatable(node_cls, data, tool_call=is_agent_tool_call(context))
+
+
+def unknown_answer(context: Mapping[str, Any], node_cls: Any, node_data: Mapping[str, Any]) -> Dict[str, Any]:
+ """What a call that may already have happened answers instead of
+ running. A graph node's answer needs the owner, so its employee pauses
+ (MachinaWorkflow reads ``requires_user_action``)."""
from services.plugin.approval import approval_spec
- spec = approval_spec(node_cls)
- if spec is None or _attempt() <= 1:
- return None
+ sends = _sends(approval_spec(node_cls), node_data)
+ answer: Dict[str, Any] = {
+ "success": False,
+ "error": RESEND_MESSAGE if sends else REDO_MESSAGE,
+ "error_type": "SendOutcomeUnknown" if sends else "OutcomeUnknown",
+ }
if context.get("approval_execution") is None and not is_agent_tool_call(context):
+ answer.update(hint=REDO_HINT, requires_user_action=True, retryable=False)
+ return answer
+
+
+async def redo_refusal(context: Mapping[str, Any], node_cls: Any, node_data: Mapping[str, Any]) -> Optional[Dict[str, Any]]:
+ """What a later attempt answers instead of running a call that is not
+ safe to repeat (see the module docstring), or None to run it."""
+ if _attempt() <= 1 or await repeatable_call(context, node_cls, node_data):
+ return None
+ return unknown_answer(context, node_cls, node_data)
+
+
+async def record_unknown(
+ context: Mapping[str, Any],
+ node_cls: Any,
+ node_data: Mapping[str, Any],
+ result: Mapping[str, Any],
+ *,
+ checked: Optional[Checked] = None,
+) -> None:
+ """Leave the owner a card for a call that may already have happened,
+ best-effort (see the module docstring). A send the owner approved is
+ recorded by the workflow that claimed it."""
+ if context.get("approval_execution") is not None:
+ return
+ try:
+ if checked is not None and checked.record is not None:
+ await checked.record(dict(result), unknown=True)
+ return
+ await _record_unknown(context, node_cls, node_data)
+ except Exception: # noqa: BLE001 - the answer stands without its card
+ logger.warning("Could not record a call that may have happened", node_id=context.get("node_id"), exc_info=True)
+
+
+async def _record_unknown(context: Mapping[str, Any], node_cls: Any, node_data: Mapping[str, Any]) -> None:
+ from services.plugin.approval import approval_spec
+
+ database = _database()
+ spec = approval_spec(node_cls)
+ fields: Optional[Dict[str, Any]] = None
+ key = ""
+ if _sends(spec, node_data):
+ if is_agent_tool_call(context):
+ fields, key = _row_fields(context, node_cls, spec, node_data), call_key(context)
+ else:
+ sent = await _graph_send(context, node_cls, node_data)
+ if sent is not None:
+ fields, key = _row_fields(context, node_cls, spec, sent), _unknown_key("u", context)
+ if fields is None:
+ fields, key = _effect_fields(context, node_cls, node_data), _unknown_key("e", context)
+ now = _utcnow()
+ fields.update(
+ status="failed",
+ approved_by="auto",
+ decided_at=now,
+ consumed_at=now,
+ outcome="unknown",
+ outcome_at=now,
+ final_text=fields.get("draft_text"),
+ )
+ row, created = await store.get_or_create(database, idempotency_key=key, fields=fields)
+ if created:
+ logger.info("A call may have happened", approval_id=row.id, workflow_id=row.workflow_id, kind=row.kind)
+ await notify_approval_changed(change_of(row, "failed"))
+ if not row.tool_call_id:
+ # No model read the answer: a graph node's employee hears it.
+ from services.approvals.execution import tell_employee
+
+ await tell_employee(database, row)
+ await _show_in_chat(database, context, row)
+
+
+def _unknown_key(prefix: str, context: Mapping[str, Any]) -> str:
+ """One card per call: an agent's call by its id, a graph node's by its
+ activity, which every attempt shares."""
+ if is_agent_tool_call(context):
+ return f"{prefix}:{context.get('workflow_id') or ''}:{context.get('execution_id') or ''}:{context.get('tool_call_id')}"
+ try:
+ from temporalio import activity
+
+ info = activity.info()
+ return f"{prefix}:{info.workflow_id}:{info.workflow_run_id}:{info.activity_id}"
+ except Exception: # noqa: BLE001 - not in an activity
+ return f"{prefix}:{context.get('workflow_id') or ''}:{context.get('execution_id') or ''}:{context.get('node_id') or ''}"
+
+
+async def _graph_send(context: Mapping[str, Any], node_cls: Any, node_data: Mapping[str, Any]) -> Optional[Dict[str, Any]]:
+ """A graph node's send as it ran, its templates resolved (NodeExecutor's
+ own steps), without secrets or locked fields: Send again resends it, and
+ the node's settings put those back. None when it cannot be rebuilt or is
+ too big to keep."""
+ from core.container import container
+ from services.workflow_sanitizer import sanitize_runtime_payload
+
+ try:
+ resolved = await container.workflow_service().prepare_node_parameters(
+ node_id=str(context.get("node_id") or ""),
+ node_type=node_cls.type,
+ parameters=dict(node_data or {}),
+ nodes=context.get("nodes", []),
+ edges=context.get("edges", []),
+ session_id=context.get("session_id", "default"),
+ execution_id=context.get("execution_id"),
+ workflow_id=context.get("workflow_id"),
+ outputs=context.get("inputs", {}),
+ user_id=str(context.get("user_id") or "owner"),
+ )
+ except Exception: # noqa: BLE001 - the card shows what was tried instead
+ logger.warning("Could not rebuild what a node sent", node_id=context.get("node_id"), exc_info=True)
return None
- if spec.restrict_while_asking or not spec.sends(node_data):
+ locked = _locked(node_cls)
+ kept = {key: value for key, value in sanitize_runtime_payload(dict(resolved or {})).items() if key not in locked}
+ try:
+ size = len(json.dumps(kept, default=str))
+ except (TypeError, ValueError):
return None
- return {"success": False, "error": RESEND_MESSAGE, "error_type": "SendOutcomeUnknown"}
+ return kept if size <= MAX_KEPT_SEND else None
+
+
+def _effect_fields(context: Mapping[str, Any], node_cls: Any, node_data: Mapping[str, Any]) -> Dict[str, Any]:
+ """An ``effect`` row: what was tried and what it ran with (no secrets),
+ for a card the owner checks and dismisses."""
+ from services.approvals.repeats import REPEATABLE_WHEN
+
+ node_type = getattr(node_cls, "type", None) or str(context.get("node_type") or "")
+ name = str(getattr(node_cls, "display_name", None) or node_type or "a tool")
+ field = REPEATABLE_WHEN.get(node_type, ("", frozenset()))[0]
+ operation = node_data.get(field) if field else None
+ tool_args = context.get("tool_args")
+ stream = context.get("chat_stream") if isinstance(context.get("chat_stream"), Mapping) else {}
+ run_id = context.get("chat_run_id") or (stream or {}).get("run_id")
+ return {
+ "owner_id": str(context.get("user_id") or "owner"),
+ "workflow_id": str(context.get("workflow_id") or ""),
+ "node_id": str(context.get("node_id") or ""),
+ "generation": int(context.get("generation") or 0),
+ "execution_id": context.get("execution_id"),
+ "runtime": "temporal",
+ "kind": "effect",
+ "channel": name[:60],
+ "action": (f"Use {name} ({operation})" if isinstance(operation, str) and operation else f"Use {name}")[:200],
+ "details": _argument_lines(node_cls, tool_args if isinstance(tool_args, Mapping) else node_data),
+ "node_type": node_type or None,
+ "tool_node_id": str(context.get("node_id") or ""),
+ "tool_call_id": str(context.get("tool_call_id") or ""),
+ "agent_node_id": str(context.get("parent_node_id") or ""),
+ "run_id": run_id if isinstance(run_id, str) and run_id else None,
+ }
+
+
+def _argument_lines(node_cls: Any, values: Mapping[str, Any]) -> List[Dict[str, str]]:
+ """Up to six of what a call ran with, each cut at 300 characters, with
+ secrets and locked fields left out."""
+ from services.workflow_sanitizer import sanitize_runtime_payload
+
+ locked = _locked(node_cls)
+ lines: List[Dict[str, str]] = []
+ for key, value in sanitize_runtime_payload(dict(values or {})).items():
+ if key in locked or value in (None, "", [], {}):
+ continue
+ text = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False, default=str)
+ lines.append({"label": str(key)[:60], "value": text[:300]})
+ if len(lines) == 6:
+ break
+ return lines
def claim_token() -> str:
@@ -386,6 +591,8 @@ def claim_token() -> str:
__all__ = [
"Checked",
"HELD_MESSAGE",
+ "REDO_HINT",
+ "REDO_MESSAGE",
"RESEND_MESSAGE",
"RUN",
"as_it_runs",
@@ -395,5 +602,8 @@ __all__ = [
"claim_token",
"hold",
"is_agent_tool_call",
- "resend_refusal",
+ "record_unknown",
+ "redo_refusal",
+ "repeatable_call",
+ "unknown_answer",
]
diff --git a/server/services/coding_workspace_tools.py b/server/services/coding_workspace_tools.py
index d07daf17..b947d080 100644
--- a/server/services/coding_workspace_tools.py
+++ b/server/services/coding_workspace_tools.py
@@ -108,8 +108,9 @@ async def execute_workspace_tool(payload: dict) -> dict:
return held.get("result", held)
if checked.tool_args is not None:
args = checked.tool_args
- refusal = approvals.resend_refusal(context, cls, checked.node_data or {})
+ refusal = await approvals.redo_refusal(context, cls, context["node_data"])
if refusal is not None:
+ await approvals.record_unknown(context, cls, context["node_data"], refusal, checked=checked)
return refusal.get("result", refusal)
step = steps.begin(context, cls)
broadcaster = get_status_broadcaster()
diff --git a/server/services/node_executor.py b/server/services/node_executor.py
index ce05e5cd..3b5e1a7d 100644
--- a/server/services/node_executor.py
+++ b/server/services/node_executor.py
@@ -8,7 +8,7 @@ import time
import uuid
from dataclasses import dataclass
from datetime import datetime
-from typing import Dict, Any, Optional, Callable, TYPE_CHECKING
+from typing import Dict, Any, Optional, Callable, Tuple, TYPE_CHECKING
from core.logging import get_logger
from constants import (
@@ -143,49 +143,7 @@ class NodeExecutor:
if context.get("workflow_id"):
from services.employees.permissions import assert_runtime_access
await assert_runtime_access(self.database, str(context["workflow_id"]), node_id, node_type, context)
- # An LLM tool call carries the model's own arguments in
- # ``tool_args``; ``parameters`` already has them merged on top of
- # the node's settings (the agent workflow builds
- # ``{**tool params, **call args}``).
- tool_args = context.get("tool_args")
- if isinstance(tool_args, dict):
- locked = locked_tool_fields(get_node_class(node_type))
- if locked:
- context = {
- **context,
- "tool_args": {k: v for k, v in tool_args.items() if k not in locked},
- }
- else:
- tool_args = None
-
- # Load, validate, enhance parameters
- params = await self._prepare_parameters(node_id, node_type, parameters, session_id, tool_args=tool_args,
- parameter_snapshot=context.get("parameter_snapshot"), principal=str(context.get("user_id") or "owner"),
- context=context, resolve_params_fn=resolve_params_fn)
- email_templates_resolved = context.pop("_employee_email_templates_resolved", None) == node_id
-
- # Resolve templates if resolver provided
- nodes = context.get("nodes")
- edges = context.get("edges")
- logger.debug(
- f"[NodeExecutor] Template resolution check: resolve_fn={resolve_params_fn is not None}, nodes={len(nodes) if nodes else 'None'}, edges={len(edges) if edges else 'None'}"
- )
-
- if resolve_params_fn and nodes is not None and edges is not None and not email_templates_resolved:
- logger.debug(f"[NodeExecutor] Before resolution: params={list(params.keys())}")
- # ``context["outputs"]`` holds what this run's upstream nodes
- # produced. Resolving from it rather than only from the shared
- # session store keeps concurrent firings from reading each
- # other's trigger data.
- params = await resolve_params_fn(
- params,
- node_id,
- nodes,
- edges,
- session_id,
- run_outputs=context.get("outputs") or None,
- )
- logger.debug(f"[NodeExecutor] After resolution: params keys={list(params.keys())}")
+ params, context = await self.prepare_parameters(node_id, node_type, parameters, context, resolve_params_fn)
# Build handler context
handler_ctx = {
@@ -243,6 +201,68 @@ class NodeExecutor:
False, node_id, node_type, error=str(e), execution_id=execution_id, execution_time=time.time() - start_time
).to_dict()
+ async def prepare_parameters(
+ self,
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any],
+ resolve_params_fn: Optional[Callable] = None,
+ *,
+ inject_keys: bool = True,
+ ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
+ """What a node runs with, and the context its handler sees: its saved
+ settings with ``parameters`` over them, locked fields put back,
+ validated, API keys added (unless ``inject_keys`` is off), then its
+ templates resolved. :meth:`execute` starts with it; a card that keeps
+ what a graph node sent rebuilds it here
+ (services/approvals/tool_calls.py)."""
+ session_id = context.get("session_id", "default")
+ # An LLM tool call carries the model's own arguments in
+ # ``tool_args``; ``parameters`` already has them merged on top of
+ # the node's settings (the agent workflow builds
+ # ``{**tool params, **call args}``).
+ tool_args = context.get("tool_args")
+ if isinstance(tool_args, dict):
+ locked = locked_tool_fields(get_node_class(node_type))
+ if locked:
+ context = {
+ **context,
+ "tool_args": {k: v for k, v in tool_args.items() if k not in locked},
+ }
+ else:
+ tool_args = None
+
+ # Load, validate, enhance parameters
+ params = await self._prepare_parameters(node_id, node_type, parameters, session_id, tool_args=tool_args,
+ parameter_snapshot=context.get("parameter_snapshot"), principal=str(context.get("user_id") or "owner"),
+ context=context, resolve_params_fn=resolve_params_fn, inject_keys=inject_keys)
+ email_templates_resolved = context.pop("_employee_email_templates_resolved", None) == node_id
+
+ # Resolve templates if resolver provided
+ nodes = context.get("nodes")
+ edges = context.get("edges")
+ logger.debug(
+ f"[NodeExecutor] Template resolution check: resolve_fn={resolve_params_fn is not None}, nodes={len(nodes) if nodes else 'None'}, edges={len(edges) if edges else 'None'}"
+ )
+
+ if resolve_params_fn and nodes is not None and edges is not None and not email_templates_resolved:
+ logger.debug(f"[NodeExecutor] Before resolution: params={list(params.keys())}")
+ # ``context["outputs"]`` holds what this run's upstream nodes
+ # produced. Resolving from it rather than only from the shared
+ # session store keeps concurrent firings from reading each
+ # other's trigger data.
+ params = await resolve_params_fn(
+ params,
+ node_id,
+ nodes,
+ edges,
+ session_id,
+ run_outputs=context.get("outputs") or None,
+ )
+ logger.debug(f"[NodeExecutor] After resolution: params keys={list(params.keys())}")
+ return params, context
+
async def _prepare_parameters(
self,
node_id: str,
@@ -254,8 +274,10 @@ class NodeExecutor:
principal: str = "owner",
context: Optional[Dict[str, Any]] = None,
resolve_params_fn: Optional[Callable] = None,
+ *,
+ inject_keys: bool = True,
) -> Dict:
- """Load from DB, validate, inject API keys."""
+ """Load from DB, validate, inject API keys (``inject_keys``)."""
# Merge with DB parameters (DB provides defaults, frontend can override)
db_params = await saved_settings(self.database, node_id, parameter_snapshot)
merged = {**db_params, **params} if params else db_params
@@ -289,6 +311,8 @@ class NodeExecutor:
logger.warning("Validation warning", node_type=node_type, errors=str(e))
# Inject API keys
+ if not inject_keys:
+ return merged
return await self._inject_api_keys(node_type, merged, principal=principal)
async def _inject_api_keys(self, node_type: str, params: Dict, *, principal: str = "owner") -> Dict:
diff --git a/server/services/plugin/base.py b/server/services/plugin/base.py
index 6f651f2c..05a9bb0b 100644
--- a/server/services/plugin/base.py
+++ b/server/services/plugin/base.py
@@ -1215,24 +1215,26 @@ class BaseNode:
node_data = checked.node_data
if checked.tool_args is not None:
context = {**context, "tool_args": checked.tool_args}
- # A send runs at most once: a later attempt (the one before broke
- # off) answers that it may have gone out instead of sending again.
- resend = approval_calls.resend_refusal(context, cls, node_data)
- if resend is not None:
+ # A call runs at most once unless it is safe to repeat: a later
+ # attempt (the one before broke off) answers that it may already
+ # have happened, and the owner gets a card.
+ redo = await approval_calls.redo_refusal(context, cls, node_data)
+ if redo is not None:
result = {
"node_id": node_id,
"node_type": cls.type,
"execution_id": execution_id,
"timestamp": datetime.now().isoformat(),
- **resend,
+ **redo,
}
- if checked.record is not None:
- await checked.record(result, unknown=True)
- await chat_steps.end(chat_step, state="failed", detail="It may already have gone out")
+ await approval_calls.record_unknown(context, cls, node_data, result, checked=checked)
+ sent = redo["error_type"] == "SendOutcomeUnknown"
+ await chat_steps.end(chat_step, state="failed", detail="It may already have gone out" if sent else "It may already have happened")
await broadcaster.update_node_status(
node_id,
"error",
- {"error": resend["error"], "execution_id": execution_id},
+ {"error": redo["error"], "execution_id": execution_id,
+ **{key: redo[key] for key in ("hint", "requires_user_action", "error_type") if key in redo}},
workflow_id=workflow_id,
)
return result
diff --git a/server/services/temporal/activities.py b/server/services/temporal/activities.py
index a4e3db53..748d95db 100644
--- a/server/services/temporal/activities.py
+++ b/server/services/temporal/activities.py
@@ -142,6 +142,32 @@ class NodeExecutionActivities:
)
return result
+ # A call runs at most once unless it is safe to repeat
+ # (services/approvals/tool_calls.py): a later attempt answers that it
+ # may already have happened, and the owner gets a card.
+ from services.approvals import tool_calls as approval_calls
+ from services.node_registry import get_node_class
+
+ node_cls = get_node_class(node_type)
+ redo = await approval_calls.redo_refusal(context, node_cls, node_data)
+ if redo is not None:
+ result = {
+ "node_id": node_id,
+ "node_type": node_type,
+ "execution_id": execution_id,
+ "timestamp": datetime.now().isoformat(),
+ **redo,
+ }
+ await approval_calls.record_unknown(context, node_cls, node_data, result)
+ await self._broadcast_status(
+ node_id=node_id,
+ status="error",
+ data={"error": redo["error"], "execution_id": execution_id,
+ **{key: redo[key] for key in ("hint", "requires_user_action", "error_type") if key in redo}},
+ workflow_id=workflow_id,
+ )
+ return result
+
# Broadcast "executing" status for UI updates
await self._broadcast_status(
node_id=node_id,
diff --git a/server/services/workflow.py b/server/services/workflow.py
index 322c7988..b2fef9f9 100644
--- a/server/services/workflow.py
+++ b/server/services/workflow.py
@@ -221,24 +221,10 @@ class WorkflowService:
fields like ``auto_rebind_tools`` through without adding a
dedicated parameter per flag.
"""
- # Resolve slug from DB if caller passed only workflow_id.
- if workflow_slug is None:
- workflow_slug = await self._resolve_workflow_slug(workflow_id)
- workspace_dir = self._get_workspace_dir(workflow_slug)
- context = {
- "nodes": nodes,
- "edges": edges,
- "session_id": session_id,
- "execution_id": execution_id,
- "workflow_id": workflow_id, # UUID — stable system identity, FK target
- "workflow_slug": workflow_slug, # Human-readable, mutable on rename
- "user_id": str(user_id or "owner"),
- "workspace_dir": workspace_dir, # Per-workflow filesystem for nodes and agents
- "get_output_fn": self.get_node_output,
- "outputs": outputs or {}, # Upstream node outputs for data flow (e.g., taskTrigger -> chatAgent)
- }
- if extras:
- context.update(extras)
+ context = await self._node_run_context(
+ nodes=nodes, edges=edges, session_id=session_id, execution_id=execution_id, workflow_id=workflow_id,
+ workflow_slug=workflow_slug, outputs=outputs, extras=extras, user_id=user_id,
+ )
recorded_pi_admission = context.get("pi_harness_version") == 1
from temporalio import activity
if not activity.in_activity() and context.get("coding_native_version") != 1:
@@ -297,6 +283,68 @@ class WorkflowService:
resolve_params_fn=self._param_resolver.resolve,
)
+ async def _node_run_context(
+ self,
+ *,
+ nodes: Optional[List[Dict]],
+ edges: Optional[List[Dict]],
+ session_id: str,
+ execution_id: Optional[str],
+ workflow_id: Optional[str],
+ workflow_slug: Optional[str],
+ outputs: Optional[Dict[str, Any]],
+ extras: Optional[Dict[str, Any]],
+ user_id: str,
+ ) -> Dict[str, Any]:
+ """The context a node runs in (:meth:`execute_node`)."""
+ # Resolve slug from DB if caller passed only workflow_id.
+ if workflow_slug is None:
+ workflow_slug = await self._resolve_workflow_slug(workflow_id)
+ workspace_dir = self._get_workspace_dir(workflow_slug)
+ context = {
+ "nodes": nodes,
+ "edges": edges,
+ "session_id": session_id,
+ "execution_id": execution_id,
+ "workflow_id": workflow_id, # UUID — stable system identity, FK target
+ "workflow_slug": workflow_slug, # Human-readable, mutable on rename
+ "user_id": str(user_id or "owner"),
+ "workspace_dir": workspace_dir, # Per-workflow filesystem for nodes and agents
+ "get_output_fn": self.get_node_output,
+ "outputs": outputs or {}, # Upstream node outputs for data flow (e.g., taskTrigger -> chatAgent)
+ }
+ if extras:
+ context.update(extras)
+ return context
+
+ async def prepare_node_parameters(
+ self,
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ nodes: List[Dict] = None,
+ edges: List[Dict] = None,
+ session_id: str = "default",
+ execution_id: str = None,
+ workflow_id: str = None,
+ workflow_slug: str = None,
+ outputs: Dict[str, Any] = None,
+ extras: Optional[Dict[str, Any]] = None,
+ user_id: str = "owner",
+ ) -> Dict[str, Any]:
+ """The parameters :meth:`execute_node` would run a node with, its
+ templates resolved but no API keys added, without running it. A card
+ that keeps what a graph node sent rebuilds it here
+ (services/approvals/tool_calls.py)."""
+ context = await self._node_run_context(
+ nodes=nodes, edges=edges, session_id=session_id, execution_id=execution_id, workflow_id=workflow_id,
+ workflow_slug=workflow_slug, outputs=outputs, extras=extras, user_id=user_id,
+ )
+ params, _ = await self._node_executor.prepare_parameters(
+ node_id, node_type, parameters, context, resolve_params_fn=self._param_resolver.resolve, inject_keys=False,
+ )
+ return params
+
async def _execute_pi_coding_node(self, node_id: str, parameters: dict, context: dict, *, check_admission: bool = True) -> dict:
"""Admit an isolated manual Coding Agent invocation into Temporal."""
from services.coding_agent_runtime import assert_pi_admissions_enabled
diff --git a/server/tests/nodes/test_coding_workspace_tools.py b/server/tests/nodes/test_coding_workspace_tools.py
index f1a11f5f..46da2714 100644
--- a/server/tests/nodes/test_coding_workspace_tools.py
+++ b/server/tests/nodes/test_coding_workspace_tools.py
@@ -91,7 +91,7 @@ def workspace_runtime(monkeypatch):
check_access = AsyncMock()
monkeypatch.setattr(permissions, "assert_runtime_access", check_access)
monkeypatch.setattr(tool_calls, "check", AsyncMock(return_value=tool_calls.Checked()))
- monkeypatch.setattr(tool_calls, "resend_refusal", lambda *args: None)
+ monkeypatch.setattr(tool_calls, "redo_refusal", AsyncMock(return_value=None))
monkeypatch.setattr(steps, "run_stopped", AsyncMock(return_value=False))
monkeypatch.setattr(steps, "begin", lambda *args: None)
monkeypatch.setattr(steps, "end", AsyncMock())
diff --git a/server/tests/services/approvals/test_decisions.py b/server/tests/services/approvals/test_decisions.py
index f2842abc..4cbd9cd6 100644
--- a/server/tests/services/approvals/test_decisions.py
+++ b/server/tests/services/approvals/test_decisions.py
@@ -59,6 +59,36 @@ async def test_restore_brings_a_discarded_draft_back_while_it_can(harness):
assert late == {**late, "success": False, "error": "too_late"}
+async def unknown_row(harness, kind="effect", key="e:wf:run:act"):
+ """A call that broke off midway: it may have happened."""
+ row, _ = await store.get_or_create(
+ harness.database,
+ idempotency_key=key,
+ fields={"owner_id": "owner", "workflow_id": "wf", "node_id": "wf:shell:1", "kind": kind, "status": "failed",
+ "channel": "Shell", "action": "Use Shell", "approved_by": "auto", "outcome": "unknown"},
+ )
+ return row
+
+
+async def test_dismiss_closes_a_call_that_may_have_happened(harness):
+ row = await unknown_row(harness)
+ dismissed = await decide(harness, row.id, "dismiss", key="x1")
+ assert dismissed["success"] is True and dismissed["approval"]["status"] == "cancelled"
+ assert (await decide(harness, row.id, "dismiss", key="x1"))["idempotent"] is True
+ again = await decide(harness, row.id, "dismiss", key="x2")
+ assert again == {**again, "success": False, "error": "invalid_request"}
+
+
+async def test_only_an_effect_card_is_dismissed_and_it_is_never_sent(harness):
+ effect = await unknown_row(harness)
+ retried = await decide(harness, effect.id, "retry", key="r1", confirm=True)
+ assert retried == {**retried, "success": False, "error": "invalid_request"}
+ send = await unknown_row(harness, kind="tool_call", key="c:wf:run:call_1")
+ refused = await decide(harness, send.id, "dismiss", key="x1")
+ assert refused == {**refused, "success": False, "error": "invalid_request"}
+ assert (await store.get(harness.database, send.id)).status == "failed"
+
+
async def test_a_repeated_decision_key_changes_nothing(harness):
task = asyncio.ensure_future(run_gate(harness))
(row,) = await pending(harness)
diff --git a/server/tests/services/approvals/test_held_activity.py b/server/tests/services/approvals/test_held_activity.py
index 46913305..03a32104 100644
--- a/server/tests/services/approvals/test_held_activity.py
+++ b/server/tests/services/approvals/test_held_activity.py
@@ -2,7 +2,9 @@
(``BaseNode.as_activity``): held, it never reaches the node and the model
reads that it waits; with Ask first off it runs and is recorded; a send
the owner approved runs under its claim; a later attempt (the one before
-broke off) never sends again."""
+broke off) runs only a call that is safe to repeat, and anything else
+leaves the owner a card: a send's (with what a graph node sent, no
+secrets) or an ``effect`` card to dismiss."""
from __future__ import annotations
@@ -105,7 +107,13 @@ async def test_a_later_attempt_does_not_send_again(harness, service):
service.execute_node.assert_not_awaited()
assert result["success"] is False and result["error_type"] == "SendOutcomeUnknown"
assert "may already have gone out" in result["error"]
+ # The model reads it; nothing needs the owner to resume a run.
+ assert "requires_user_action" not in result
assert ("wf:whatsappSend:1", "error") in [(node_id, status) for node_id, status, *_ in harness.broadcaster.statuses]
+ # The owner gets a card: it may have gone out, with Send again.
+ (row,) = await store.list_approvals(harness.database, status="failed")
+ assert (row.kind, row.approved_by, row.outcome, row.outcome_error) == ("tool_call", "auto", "unknown", None)
+ assert row.idempotency_key == "c:wf:wf:execution:1:call_1"
async def test_a_later_attempt_in_the_chat_is_recorded_as_unknown(harness, service, monkeypatch):
@@ -136,17 +144,113 @@ async def test_a_later_attempt_still_holds_or_runs_what_does_not_send(harness, s
assert result["success"] is True
-async def test_a_later_browser_attempt_resumes_instead_of_refusing(harness, service):
- # The browser's later attempt resumes a wait the worker cut short
- # (NodeWaitInterrupted); Ask first restricts it rather than holding it.
+async def test_a_later_browser_page_action_is_not_repeated(harness, service):
+ # A click that broke off may have happened: whatever the rule, it is not
+ # clicked again, and the owner gets one card to check and dismiss.
browsing = {"operation": "click", "ref": "e3"}
call = context(node_id="wf:browser:1", node_data=dict(browsing), tool_args=dict(browsing))
for rule in (None, False, True):
if rule is not None:
await rules.set_ask_first(harness.database, "wf", rule)
result = await attempt(2).run(get_node_class("browser").as_activity(), call)
- assert result["success"] is True, rule
- assert service.execute_node.await_count == 3
+ assert result["success"] is False and result["error_type"] == "OutcomeUnknown", rule
+ assert "may already have happened" in result["error"]
+ service.execute_node.assert_not_awaited()
+ (row,) = await store.list_approvals(harness.database, status="failed")
+ assert (row.kind, row.outcome, row.tool_call_id) == ("effect", "unknown", "call_1")
+ assert row.idempotency_key == "e:wf:wf:execution:1:call_1"
+ assert row.action.endswith("(click)")
+
+
+async def test_a_later_browser_request_for_help_waits_again(harness, service):
+ # Asking the owner for help is a wait the worker cut short: it repeats.
+ asking = {"operation": "request_user", "message": "Please sign in."}
+ call = context(node_id="wf:browser:1", node_data=dict(asking), tool_args=dict(asking))
+ result = await attempt(2).run(get_node_class("browser").as_activity(), call)
+ service.execute_node.assert_awaited_once()
+ assert result["success"] is True
+
+
+async def test_a_later_shell_command_leaves_a_card_to_dismiss(harness, service):
+ command = {"command": "git push origin main"}
+ call = context(node_id="wf:shell:1", node_data=dict(command), tool_args=dict(command))
+ result = await attempt(2).run(get_node_class("shell").as_activity(), call)
+ service.execute_node.assert_not_awaited()
+ assert result["success"] is False and result["error_type"] == "OutcomeUnknown"
+ (row,) = await store.list_approvals(harness.database, status="failed")
+ assert (row.kind, row.approved_by, row.outcome) == ("effect", "auto", "unknown")
+ assert {"label": "command", "value": "git push origin main"} in row.details
+
+
+async def test_a_later_get_runs_again(harness, service):
+ fetch = {"method": "GET", "url": "https://example.com/status"}
+ call = context(node_id="wf:httpRequest:1", node_data=dict(fetch), tool_args=dict(fetch))
+ result = await attempt(2).run(get_node_class("httpRequest").as_activity(), call)
+ service.execute_node.assert_awaited_once()
+ assert result["success"] is True
+ assert await store.list_approvals(harness.database) == []
+
+
+def graph_context(**extra):
+ """A graph node's call: no agent made it."""
+ call = context(**extra)
+ for key in ("parent_node_id", "tool_call_id", "tool_args"):
+ call.pop(key)
+ return call
+
+
+async def test_a_later_graph_send_keeps_what_it_sent_and_needs_the_owner(harness, service):
+ # What it sent, rebuilt with its templates resolved; a secret it ran with
+ # is not kept (the node's settings put it back on Send again).
+ sent = {"message_type": "text", **ARGS, "message": "On my way, Ana.", "api_key": "sk-secret"}
+ service.prepare_node_parameters = AsyncMock(return_value=sent)
+ result = await attempt(2).run(get_node_class("whatsappSend").as_activity(), graph_context())
+ service.execute_node.assert_not_awaited()
+ assert result["success"] is False and result["error_type"] == "SendOutcomeUnknown"
+ # No model reads it: the employee pauses for the owner.
+ assert result["requires_user_action"] is True and result["hint"]
+ status = next(data for node_id, state, data, _ in harness.broadcaster.statuses if state == "error")
+ assert status["requires_user_action"] is True
+ (row,) = await store.list_approvals(harness.database, status="failed")
+ assert (row.kind, row.agent_node_id, row.tool_call_id, row.args) == ("tool_call", "", "", {})
+ assert row.node_data["message"] == "On my way, Ana." and "api_key" not in row.node_data
+ assert row.draft_text == "On my way, Ana."
+ assert row.idempotency_key.startswith("u:")
+
+
+async def test_a_graph_card_sends_again_as_it_was(harness):
+ from services.approvals.execution import node_context
+
+ graph, _ = await store.get_or_create(
+ harness.database,
+ idempotency_key="u:run:1:act",
+ fields={"owner_id": "owner", "workflow_id": "wf", "node_id": "wf:whatsappSend:1", "kind": "tool_call",
+ "node_type": "whatsappSend", "agent_node_id": "", "node_data": {"message": "On my way, Ana."}},
+ )
+ run = node_context(graph, "t1")
+ # Its templates are resolved already: nothing resolves them again, and
+ # with no tool arguments a tool node keeps its saved operation.
+ assert run["nodes"] is None and run["edges"] is None and "tool_args" not in run
+ agent, _ = await store.get_or_create(
+ harness.database,
+ idempotency_key="c:wf:1:call_1",
+ fields={"owner_id": "owner", "workflow_id": "wf", "node_id": "wf:whatsappSend:1", "kind": "tool_call",
+ "node_type": "whatsappSend", "agent_node_id": "wf:aiAgent:1", "args": {"message": "Hi"}},
+ )
+ assert node_context(agent, "t1")["tool_args"] == {"message": "Hi"}
+
+
+async def test_the_legacy_activity_refuses_a_later_attempt_too(harness):
+ from services.temporal.activities import NodeExecutionActivities
+
+ legacy = object.__new__(NodeExecutionActivities)
+ legacy._broadcast_status = AsyncMock()
+ legacy._execute_via_websocket = AsyncMock(return_value={"success": True})
+ result = await attempt(2).run(legacy.execute_node_activity, {**context(), "node_type": "whatsappSend"})
+ legacy._execute_via_websocket.assert_not_awaited()
+ assert result["success"] is False and result["error_type"] == "SendOutcomeUnknown"
+ (row,) = await store.list_approvals(harness.database, status="failed")
+ assert row.outcome == "unknown"
async def test_the_first_attempt_sends_as_before(harness, service):
diff --git a/server/tests/temporal/test_approved_tool_call_workflow.py b/server/tests/temporal/test_approved_tool_call_workflow.py
index 9a10a9df..939ce412 100644
--- a/server/tests/temporal/test_approved_tool_call_workflow.py
+++ b/server/tests/temporal/test_approved_tool_call_workflow.py
@@ -113,6 +113,15 @@ def test_every_worker_registers_the_workflow_and_its_activities() -> None:
assert names == ["approvals.claim_send", "approvals.record_outcome"]
+def test_an_approved_send_has_one_attempt() -> None:
+ # The redo guard (services/approvals/tool_calls.py) leaves an approved
+ # send to the workflow that claimed it: a second attempt would read as
+ # not sent when it may have gone out.
+ from services.temporal.approved_tool_call_workflow import SEND_ONCE
+
+ assert SEND_ONCE.maximum_attempts == 1
+
+
def test_the_send_workflow_on_temporal() -> None:
completed = subprocess.run(
[sys.executable, "-m", "tests.temporal.test_approved_tool_call_workflow"],