Skip to content

Self-improving AI Employees for everyone

docs(approvals): live Ask first, held sends and the chat's cards

trohitg191d670b36ee
diff --git a/CLAUDE.md b/CLAUDE.md
index f32af1cf..d272f0c5 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -13,8 +13,8 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[UI Migration Plan](./docs-internal/ARCHIVE/ui_migration_plan.md)** | *Archived.* antd → shadcn/ui migration completion log (Waves 1–10). Current state lives in [Frontend Architecture](./docs-internal/frontend_architecture.md) and [Theme System](./docs-internal/theme_system.md). |
| **[Temporal Cleanup & Resilience Plan (Waves 15-18)](./docs-internal/ARCHIVE/TEMPORAL_CLEANUP_AND_RESILIENCE_PLAN.md)** | *Archived — all four waves shipped.* 15 dead-code retirement (Redis-Streams branch in event_waiter, APScheduler cron stack, orphaned `connection_status` factory), 16 per-queue task routing (`TemporalWorkerPool`), 17 resilience hardening (cron `catchup_window`, SDK interceptors, `DEPLOYMENT_MODE`, periodic heartbeats; the one-shot LLM-step retry it records was later reverted to unlimited-with-backoff), 18 worker performance tuning. Current settings live in [Temporal Architecture](./docs-internal/TEMPORAL_ARCHITECTURE.md). |
| **[Node Allowlist](./docs-internal/node_allowlist.md)** | Single-config UI visibility — `server/config/node_allowlist.json` controls which nodes / credential categories / skill folders show in the UI. Five lists with two enforcement tiers (mode-gated allowlist + absolute blocklist). `useNodeAllowlist` hook exposes `isVisible` / `isBlocked` / `isAllowed` / `isCredentialCategoryDisabled` / `isSkillFolderDisabled`. Adding a new disabled domain = single JSON edit, no code change. |
-| **[Normal Mode (Home)](./docs-internal/normal_mode.md)** | The owner-facing landing screen: describe a job, an LLM on the server drafts a setup screen (a JSON UI spec the client parses, normalises and renders from a fixed catalogue), and Hire builds, validates, saves and starts one workflow per AI employee (`services/employees/`, graph built from `config/employee_apps.json` plus the owner's skill library and a Canvas node, and checked against `node_allowlist.json` `enabled_nodes`). Covers the screen switch (`app/`, `shellMode` / `ui_shell_mode`, `VITE_NORMAL_MODE=false` kill switch, Home shows light/dark only), the employee page (the shared chat, `features/chat`, with the employee named in the header beside New conversation; Pause is in the Workspace header), deleting an employee from the team sidebar (stopped through Reset first, then gone from every tab), the `approvalGate` "ask me before sending" step, run records for "done today" (`machina-run-record-v1`), automatic-pause reasons, Settings (Profile fields; usage-only Billing via `get_employee_usage`; Skills, the user-skills library each new hire copies onto a Skills node; consumer Connectors with `publisher` / `verified`; Plugins, the starter bundles in `hire/starters.json`; the last three share one catalog page), the Workspace dock (an employee's Canvas board, named by the summary's `canvas_node_id`; a live Browser tab with user takeover, shared with Dev mode; Mobile shows the managed local Android phone), the "Web browser" app (read-only under "ask me first" through the tool's `ask_first_params`; while the agent waits in `request_user` the summary's `browser_request` shows Needs you and Help in browser), Talk on the employee page (a thread over the chat session whose id is the workflow id, rows written through `services/chat_thread.py` and, for the owner's messages and their chat runs, `services/chat/ledger.py` (see [Chat Protocol](./docs-internal/chat_protocol.md)); the talk line is chatTrigger → an agent → `chatReply` "Reply in Chat": a chat hire's own agent is its talk agent, other hires get a "Talk with {name}" agent sharing the worker's tools and skills with its own Context, and schedule hires also "Post to Talk"), Turn on Talk (for talk `off`) and Apply (while the summary's `pending_changes` is true) via `enable_employee_talk` / `apply_employee_changes`, each a restart on the saved graph through `services/deployment/restart.py`, self-extension from Talk through the Agent Builder within the Hire rule (`services/employees/policy.py`), the 3D orb, the wire contract and the `employee_lifecycle` / `approval_lifecycle` / `chat.updated` broadcasts. |
-| **[Chat Protocol](./docs-internal/chat_protocol.md)** | The wire contract between the chat runtime (`server/services/chat/`) and the shared chat UI: AG-UI's event model on the existing WebSocket, snake_case, in the CloudEvents envelope. A message a deployed chat trigger will answer starts a **chat run** admitted with it in one reserved write transaction (`Database.reserved_session`, SQLite `BEGIN IMMEDIATE`): one live run per session (the lane, also a partial unique index; a second send answers `run_in_progress`), idempotent `client_message_id`, claimed and finished by the MachinaWorkflow that answers it behind `machina-chat-run-v1` (the run id is trusted only from an event whose source is `opencompany://services/chat`; `run_scope` rides every node context; only the claimant finishes), the reply saved as `a_<run id>` by `chatReply`, every message appended after the session's active leaf (`chat_threads`) so concurrent writes never fork the thread. `chat_run_event` frames reach only sockets that passed `chat_subscribe`'s owner check (`services/chat/hub.py`: per-run `seq`, `hub_epoch`, bounded per-socket queues with a resync), never the status broadcast. A watchdog (`services/chat/watchdog.py`, started by `main.py`) ends runs nothing will finish (`not_delivered`, `timed_out`, `interrupted`). The agent wired into Reply in Chat (`answers_chat_run`) streams its answer as `text.*` events (`services/chat/stream.py`, activity input only, no workflow patch), its tool calls show as steps (`services/chat/steps.py`; label from the plugin's `chat_step`), and `stop_chat_run` stops a run cooperatively: its LLM step polls the run and returns what was shown, unstarted tools are skipped, the reply is saved `stopped`, and the watchdog cancels a run still stopping after `runs.stop_grace_s`. Generated UI: the `show_ui` tool (`chatUi`) is checked against `config/chat_genui_catalog.json` (`services/genui/spec.py`; refused with every reason so the model retries), saved as a run part, streamed as `activity.*` RFC 6902 patches and sealed into the reply (`services/chat/parts.py`); `chat_ui_state` keeps what the owner set, and a button press comes back as `send_chat_message{ui_event}` -> a `[ui-event]` turn. The answering agent's system prompt ends with a fixed guide (`services/chat/guide.py`), what the owner set reaches its next turn as a `[ui-state]` note (`chat_notes`, `services/chat/notes.py`: claimed by the payload, told when the run answered), a trailing `<followups>` block becomes `parts.followups`, and a `chat_sources` tool's results are numbered per conversation for `[n]` citations (`services/chat/sources.py`). Lists every event, handler, part and error code, including the ones later phases build. |
+| **[Normal Mode (Home)](./docs-internal/normal_mode.md)** | The owner-facing landing screen: describe a job, an LLM on the server drafts a setup screen (a JSON UI spec the client parses, normalises and renders from a fixed catalogue), and Hire builds, validates, saves and starts one workflow per AI employee (`services/employees/`, graph built from `config/employee_apps.json` plus the owner's skill library and a Canvas node, and checked against `node_allowlist.json` `enabled_nodes`). Covers the screen switch (`app/`, `shellMode` / `ui_shell_mode`, `VITE_NORMAL_MODE=false` kill switch, Home shows light/dark only), the employee page (the shared chat, `features/chat`, with the employee named in the header beside New conversation; Pause is in the Workspace header), deleting an employee from the team sidebar (stopped through Reset first, then gone from every tab), the live Ask first rule (`workflow_rules`, the chat's Ask first chip via `set_ask_first`; app replies wait in `approvalGate`, sending tool calls are held as drafts by `services/approvals/tool_calls.py` and sent after a 5 s Undo window by `ApprovedToolCallWorkflow`; cards in the chat), run records for "done today" (`machina-run-record-v1`), automatic-pause reasons, Settings (Profile fields; usage-only Billing via `get_employee_usage`; Skills, the user-skills library each new hire copies onto a Skills node; consumer Connectors with `publisher` / `verified`; Plugins, the starter bundles in `hire/starters.json`; the last three share one catalog page), the Workspace dock (an employee's Canvas board, named by the summary's `canvas_node_id`; a live Browser tab with user takeover, shared with Dev mode; Mobile shows the managed local Android phone), the "Web browser" app (read-only under "ask me first" through the tool's `ask_first_params`; while the agent waits in `request_user` the summary's `browser_request` shows Needs you and Help in browser), Talk on the employee page (a thread over the chat session whose id is the workflow id, rows written through `services/chat_thread.py` and, for the owner's messages and their chat runs, `services/chat/ledger.py` (see [Chat Protocol](./docs-internal/chat_protocol.md)); the talk line is chatTrigger → an agent → `chatReply` "Reply in Chat": a chat hire's own agent is its talk agent, other hires get a "Talk with {name}" agent sharing the worker's tools and skills with its own Context, and schedule hires also "Post to Talk"), Turn on Talk (for talk `off`) and Apply (while the summary's `pending_changes` is true) via `enable_employee_talk` / `apply_employee_changes`, each a restart on the saved graph through `services/deployment/restart.py`, self-extension from Talk through the Agent Builder within the Hire rule (`services/employees/policy.py`), the 3D orb, the wire contract and the `employee_lifecycle` / `approval_lifecycle` / `chat.updated` broadcasts. |
+| **[Chat Protocol](./docs-internal/chat_protocol.md)** | The wire contract between the chat runtime (`server/services/chat/`) and the shared chat UI: AG-UI's event model on the existing WebSocket, snake_case, in the CloudEvents envelope. A message a deployed chat trigger will answer starts a **chat run** admitted with it in one reserved write transaction (`Database.reserved_session`, SQLite `BEGIN IMMEDIATE`): one live run per session (the lane, also a partial unique index; a second send answers `run_in_progress`), idempotent `client_message_id`, claimed and finished by the MachinaWorkflow that answers it behind `machina-chat-run-v1` (the run id is trusted only from an event whose source is `opencompany://services/chat`; `run_scope` rides every node context; only the claimant finishes), the reply saved as `a_<run id>` by `chatReply`, every message appended after the session's active leaf (`chat_threads`) so concurrent writes never fork the thread. `chat_run_event` frames reach only sockets that passed `chat_subscribe`'s owner check (`services/chat/hub.py`: per-run `seq`, `hub_epoch`, bounded per-socket queues with a resync), never the status broadcast. A watchdog (`services/chat/watchdog.py`, started by `main.py`) ends runs nothing will finish (`not_delivered`, `timed_out`, `interrupted`). The agent wired into Reply in Chat (`answers_chat_run`) streams its answer as `text.*` events (`services/chat/stream.py`, activity input only, no workflow patch), its tool calls show as steps (`services/chat/steps.py`; label from the plugin's `chat_step`), and `stop_chat_run` stops a run cooperatively: its LLM step polls the run and returns what was shown, unstarted tools are skipped, the reply is saved `stopped`, and the watchdog cancels a run still stopping after `runs.stop_grace_s`. Generated UI: the `show_ui` tool (`chatUi`) is checked against `config/chat_genui_catalog.json` (`services/genui/spec.py`; refused with every reason so the model retries), saved as a run part, streamed as `activity.*` RFC 6902 patches and sealed into the reply (`services/chat/parts.py`); `chat_ui_state` keeps what the owner set, and a button press comes back as `send_chat_message{ui_event}` -> a `[ui-event]` turn. The answering agent's system prompt ends with a fixed guide (`services/chat/guide.py`), what the owner set reaches its next turn as a `[ui-state]` note (`chat_notes`, `services/chat/notes.py`: claimed by the payload, told when the run answered), a trailing `<followups>` block becomes `parts.followups`, and a `chat_sources` tool's results are numbered per conversation for `[n]` citations (`services/chat/sources.py`). Approvals (`services/approvals/`, its own section): a plugin's `approval` spec marks a tool call that sends; while the workflow asks first it is held as a `tool_call` draft, shown as a card on the reply that made it, sent once after the Undo window by `ApprovedToolCallWorkflow`, with the outcome told to the employee as an `[update]` note. Lists every event, handler, part and error code, including the ones later phases build. |
| **[Theme System](./docs-internal/theme_system.md)** | 12-way visual theme system — 2 base (light, dark) + 5 utopian (renaissance, greek, edo, steampunk, atomic) + 5 dystopian (cyber, wasteland, rot, plague, surveillance) — driven by `<html data-theme>` + per-theme CSS files in `client/src/themes/`. Token taxonomy (surface / fg / border / accent / typography / motion) in **hex + `color-mix()`**; `@theme inline` bridge maps `--color-X: var(--X)` (no `hsl()` wrapper); per-theme files own the colour hex, base.css owns the shared `--tint-*` alpha scale; action role tokens (incl. `-ink` readable text), **per-theme `--code-*` syntax tokens** (tier 6 — the code editor, console/output JSON viewers, and chat code blocks paint in each theme's own palette: keyword→trigger, string→success, number→agent, function→model, on an adaptive dark/light code surface; replaced the global dracula `--prism-*` block + dead `getPrismTokenCSS`; the `OutputPanel` JSON viewer reads the same vars), per-theme `--pulse-keyframe` animation system + `.opencompany-*` helpers in `animations.css`, decorative-layer wrappers (`.app-frame` / `.canvas-host` / `.modal-frame`), per-component decorative ornaments (panel textures + canvas decorations + node pseudo-element overlays + theme-specific keyframes), **canvas-node visual contract via `--node-color` CSS custom property** (no inline `background` / `border` on node components — base.css + per-theme CSS owns visuals; `NodeStyle` helper type at [types/NodeTypes.ts](./client/src/types/NodeTypes.ts) makes the inline custom-prop typecheck-clean), **`--node-pulse-color` separate from `--node-color`** so executing-node glow uses each theme's highest-contrast accent regardless of plugin accent (Cyber neon cyan, Surveillance REC red, Renaissance ultramarine, etc.), **`data-page-hidden` animation pause** (set by `app/usePageActivitySync.ts`, mounted in `AppShell` on both screens, while the tab is hidden or the window is blurred; base.css declares `html[data-page-hidden] *, *::before, *::after { animation-play-state: paused !important }` to prevent compositor stall on tab return), **per-theme icon glyph system** (290 inline SVG glyph strings across 29 keys × 10 themes via [themedGlyphs.ts](./client/src/assets/icons/themedGlyphs.ts) + theme-aware [NodeIcon.tsx](./client/src/assets/icons/NodeIcon.tsx)), **per-theme canvas-grid + custom cursors** via `--canvas-grid` / `--cursor-default` slots, **decorative HTML primitives** (`<SvgFilterDefs>` mounting `#ink-blot` / `#noise` / `#crt` filter IDs at app root, `<DropCap>` wrapper for Renaissance ornament rule), **parameter panel migrated to Tailwind tokens** (no `useAppTheme()` reads; section headers carry the display-typography triplet; raw `<Button>` swapped to `<ActionButton intent>`), **per-theme scrollbar webkit rules** in all 12 themes, 9-event WebAudio sound system (10 packs via `--sound-pack` token + `useSound()` hook + global hover delegate + sonner toast monkey-patch + `withSound()` HOC + `Sounds.unlock()` gesture-unlock for AudioContext autoplay-policy compliance), `@media (prefers-reduced-motion: reduce)` accessibility, 30 ms throttle on `type` / `hover`, migration recipe, anti-patterns. Read this before adding a new theme, migrating a component to the new contract, or adding a canvas-node component. |
| **[Design System Bundle](./docs-internal/design-system/IMPLEMENTATION.md)** | Canonical, vendored design-system reference (extracted from this repo; see its `IMPLEMENTATION.md` for the contract). Tokens are **hex + `color-mix()`** (`tokens/{colors,typography,spacing,motion,fonts,base}.css`) — the format the live codebase standardizes on. Includes 34 reference components (`components/`, inline-style reference only — recreate in Tailwind/shadcn idioms), full-app UI kit (`ui_kits/opencompany/index.html`), 12-theme docs (`guidelines/THEMES.md`), **the merged handoff brief (`HANDOFF.md` — glow-ladder traps, step-edge contract, toolbar layout traps, canvas-layer asymmetries, plus the recorded product amendments)**, and **the panel×theme fidelity target (`reference-mockup/Panel Theme Matrix.dc.html` — 17 panels × 12 themes, open in a browser)**. `reference/themes/` no longer vendors CSS snapshots — it points at the authoritative [client/src/themes/](./client/src/themes/). Copy token values verbatim; do not re-derive by eye. Pairs with [Theme System](./docs-internal/theme_system.md). |
| **[Schema Source of Truth RFC](./docs-internal/ARCHIVE/schema_source_of_truth_rfc.md)** | *Archived — shipped.* Backend is SSOT for node schemas, visual metadata, handlers, palette metadata, icons; `VITE_NODESPEC_BACKEND` defaults on and the frontend node definitions are gone. Plugin pattern: one `BaseNode` subclass in `server/nodes/<group>/<plugin>/__init__.py`. Wire format: `asset:<key>` / `<lib>:<brand>` / URL / emoji. Endpoint: `/api/schemas/nodes/{type}/spec.json`. Current reference: [Plugin System](./docs-internal/plugin_system.md). |
diff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.md
index 3c71dffa..6f7061ec 100644
--- a/docs-internal/TEMPORAL_ARCHITECTURE.md
+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md
@@ -551,6 +551,28 @@ A node class that declares `workspace_task = True` (the phone nodes in `server/n
What the user sees, including what Reset leaves on the phone, is in [docs/mobile-workspace.md](../docs/mobile-workspace.md#resetting-phone-tasks).
+### Approved sends
+
+A tool call that sends, made while the workflow asks first, is held as a draft (`services/approvals/tool_calls.py`)
+instead of running. When the owner presses Send, `decide_approval` starts `ApprovedToolCallWorkflow`
+(`services/temporal/approved_tool_call_workflow.py`, id `approval-send-<approval id>-r<revision>`, `payload_version` 1,
+unsandboxed like the other framework workflows):
+
+- it sleeps until the draft's Undo window closes (`grace_until`);
+- `approvals.claim_send` moves the row from approved to sending, only at the revision the workflow was started for,
+ with a claim token derived from the workflow run; an Undo, a newer Send or a cancel moved the row, and the
+ workflow ends with nothing sent. A retried claim by the same run finds its own claim;
+- it runs the node's own `node.<type>.v<n>` activity once (`maximum_attempts=1`), with the call's arguments over the
+ node's settings; the activity runs only under that claim (`approval_execution` in its input);
+- `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.
+
+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
+reconcile; one that never reported ends `failed` with an unknown outcome. See
+[Chat Protocol, Approvals](./chat_protocol.md#approvals).
+
## Config Node Filtering
Certain nodes provide configuration rather than executing:
@@ -629,6 +651,7 @@ server/services/temporal/
├── polling_trigger_workflow.py # PollingTriggerWorkflow (legacy polling listener)
├── workspace_tasks_workflow.py # WorkspaceTaskControllerWorkflow (per-workflow admission + Reset for direct Workspace tasks)
├── node_invocation.py # NodeInvocationWorkflow (one direct Workspace task)
+├── approved_tool_call_workflow.py # ApprovedToolCallWorkflow (sends a held tool call once the owner approved it)
├── workspace_task_activities.py # reset_workspace_task_runtime (activity workspace_tasks.reset_runtime)
├── schedules.py # Temporal Schedule creation for cronScheduler
├── search_attributes.py # EVENT_SEARCH_ATTRIBUTES (7 custom SAs, incl. ControlEventTypes)
diff --git a/docs-internal/chat_protocol.md b/docs-internal/chat_protocol.md
index 9df3eb97..cb278c76 100644
--- a/docs-internal/chat_protocol.md
+++ b/docs-internal/chat_protocol.md
@@ -148,16 +148,25 @@ text segments or activities (those are stored with the reply).
| Handler | Request | Response |
|---|---|---|
-| `list_approvals` | `{workflow_id?, status?: str \| [str] \| "open" \| "recent", run_id?, kind?, limit?}` | `{success, approvals, counts, server_time}` |
-| `get_approvals` | `{approval_ids}` (at most 50) | `{success, approvals, server_time}` |
-| `decide_approval` | `{approval_id, decision: "send" \| "discard" \| "undo" \| "restore" \| "retry", decision_key, edited_args?, text?, subject?, expected_revision?, confirm?}` | `{success, approval, will_send_on_resume, execution}` |
-| `resolve_interrupt` | `{interrupt_id, status: "resolved" \| "cancelled", payload: {approved, edited_args?}, decision_key}` | as `decide_approval` |
-| `set_ask_first` | `{workflow_id, ask_first, expected_revision?}` | `{success, ask_first, revision, replies_gated, needs_apply}` |
-
-`edited_args` replaces the call's arguments in full and may differ from them only in the editable keys. The approval
-summary adds `kind` (`gate` or `tool_call`), `node_type`, `tool_name`, `tool_call_id`, `run_id`, `args`, `editable`,
-`body_field`, `subject_field`, `approved_by` (`user` or `auto`), `undo_until`, `restore_until` and
-`outcome {certainty: "sent" | "not_sent" | "unknown", error?, at}`.
+| `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}` |
+| `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}` |
+| `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 |
+
+`open` lists what the owner may still act on, or is on its way: pending, approved and not handed on, sending,
+failed, and discarded while it can be restored. `recent` lists everything, newest first. Only the owner's own drafts
+and workflows answer; any other id reads as `not_found`. `decide_approval` errors: `already_decided`, `expired`,
+`cancelled`, `too_late` (Undo after it went, Restore after its window), `confirm_required` (a retry of a send that
+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,
+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?}, run_id?,
+tool_call_id?, ui_part_id?, agent_node_id?, deployment_state?}`. `status` is `pending`, `approved`, `sending`,
+`sent`, `failed`, `discarded`, `expired` or `cancelled`; see [Approvals](#approvals).
### Plugins
@@ -207,7 +216,7 @@ parts: {
}
```
-Approvals are joined live from the approvals store; the part only names them.
+Approvals are joined live from the approvals store; the part only names them (`{approval_id, tool_call_id}`).
A run's tools record parts on the run as they go (`chat_run_parts`, keyed so a retried activity writes the same
row; `services/chat/parts.py`). Reply in Chat saves its reply with the parts recorded so far, and the run's end seals
@@ -366,6 +375,52 @@ editor's console pane (`ConsoleChat`, compact, scope `live`) are the two hosts.
(forward only, so patches arriving in bursts never restart it), and routes any button action (`genui/actions.ts`,
a Proxy over action names). Development builds show the element and patch counts and an Inspect view.
+## Approvals
+
+What an employee sends to someone waits for the owner's OK while its workflow asks first
+(`server/services/approvals/`, models in `server/models/approvals.py`).
+
+- **The rule.** `workflow_rules` holds a workflow's Ask first, read every time something would send, so the chat's
+ Ask first chip (`set_ask_first`) changes it with no restart. An employee's row is seeded from its ground rules the
+ 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
+ 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
+ row keeps what would run (the node's settings with the call's arguments over them, never the identity the node
+ sends as) and the model reads that it waits for the owner. A tool that cannot wait is refused (Stripe) or runs
+ restricted (the browser, read-only). With Ask first off the call runs; one made answering the owner in the chat
+ leaves a row (`approved_by: auto`) with how it went. An approval gate with the rule off lets its draft through at
+ once, recorded the same way.
+- **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
+ 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
+ newer Send or a cancel moved it, and nothing runs), runs the node's own activity once with no retry, and records
+ 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.
+- **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 or was discarded.
+- **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. Drafts no reply in view made (a
+ 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.
+- **Ends.** Clearing or resetting the chat cancels the drafts its runs made that still wait; a Reset cancels the
+ waiting gates too (`approvalGate.reset_execution_state`); deleting the workflow deletes its drafts and its rule.
+- **Broadcast.** `approval_lifecycle` (source `opencompany://services/approvals`, type
+ `com.opencompany.approval.<stage>`: requested, decided, undone, restored, sending, sent, failed, expired,
+ cancelled), identity only, with the chat run when there is one.
+
## Notes to the employee
Things the employee should learn on its next turn are kept in `chat_notes` (`services/chat/notes.py`) and put ahead
diff --git a/docs-internal/node-logic-flows/workflow_triggers/approvalGate.md b/docs-internal/node-logic-flows/workflow_triggers/approvalGate.md
index 25da0228..a182bc76 100644
--- a/docs-internal/node-logic-flows/workflow_triggers/approvalGate.md
+++ b/docs-internal/node-logic-flows/workflow_triggers/approvalGate.md
@@ -4,7 +4,7 @@
|------|-------|
| **Category** | workflow |
| **Backend handler** | [`server/nodes/workflow/approval_gate/__init__.py`](../../../server/nodes/workflow/approval_gate/__init__.py) - `ApprovalGateNode`; dispatched via `BaseNode.execute()` + the `@Operation("request")` method |
-| **Tests** | [`server/tests/services/approvals/test_approval_gate.py`](../../../server/tests/services/approvals/test_approval_gate.py) |
+| **Tests** | [`server/tests/services/approvals/test_approval_gate.py`](../../../server/tests/services/approvals/test_approval_gate.py), [`test_decisions.py`](../../../server/tests/services/approvals/test_decisions.py) |
| **Skill (if any)** | none |
| **Dual-purpose tool** | no - `usable_as_tool = False`, so no agent can approve its own draft |
@@ -13,11 +13,15 @@
Holds a draft until the owner sends or discards it. A Normal-mode employee
with "Ask me before sending anything" on answers through
`agent -> approvalGate -> reply`: the gate records the agent's draft (who it
-goes to, what it says), shows it on the employee's page in Home, and waits.
-Send lets the draft, or the owner's edit of it, through to the reply node;
-Discard, expiry or a Reset lets nothing through. Hire builds this wiring
+goes to, what it says), shows it as a card in the employee's chat, and waits.
+Send lets the draft, or the owner's edit of it, through to the reply node once
+the 5-second Undo window has passed; Discard (once Restore can no longer bring
+it back), expiry or a Reset lets nothing through. The workflow's Ask first rule
+is read live: with it off the draft goes straight through, recorded as sent
+without asking; a workflow with no rule always asks. Hire builds this wiring
(`services/employees/builder.py`); the node is also usable by hand in the
-editor. Feature overview: [Normal mode](../../normal_mode.md).
+editor. Feature overview: [Normal mode](../../normal_mode.md); the decisions and
+the card: [Chat Protocol, Approvals](../../chat_protocol.md#approvals).
## Inputs (handles)
@@ -57,6 +61,7 @@ editor. Feature overview: [Normal mode](../../normal_mode.md).
recipient_label: string; // "" unless approved
approval_id: string | null;
edited: boolean;
+ automatic: boolean; // it went without asking: Ask first was off
}
```
@@ -73,17 +78,21 @@ flowchart TD
A[Receive params] --> B{draft empty or NO_REPLY?}
B -- yes --> S[Return skipped, no row]
B -- no --> C[Idempotency key: activity identity on Temporal, execution + node + inputs fingerprint in-process]
- C --> D[get_or_create approval_requests row]
+ C --> R{new row and Ask first off?}
+ R -- yes --> A2[Create it approved and handed on, approved_by auto] --> O
+ R -- no --> D[get_or_create approval_requests row]
D -- created --> E[Broadcast approval_lifecycle requested]
- D --> F{row pending?}
+ D --> F{row status}
E --> F
- F -- no --> O[Return the outcome]
- F -- yes --> G[Show node status waiting]
- G --> H{expired?}
+ F -- pending --> H{expired?}
H -- yes --> X[Settle expired, broadcast] --> O
- H -- no --> I{worker shutting down?}
- I -- yes --> W[Raise NodeWaitInterrupted: Temporal retries the attempt]
- I -- no --> J[Wait for a notification or POLL_SECONDS, re-read the row] --> F
+ H -- no --> J
+ F -- approved, Undo window open --> J
+ F -- approved, window over --> K[Hand it on: consumed_at] --> O
+ F -- discarded, Restore window open --> J
+ F -- discarded, window over / expired / cancelled --> O[Return the outcome]
+ J{worker shutting down?} -- yes --> W[Raise NodeWaitInterrupted: Temporal retries the attempt]
+ J -- no --> L[Wait for a notification, the window's end or POLL_SECONDS; re-read the row] --> F
```
## Decision Logic
@@ -99,9 +108,10 @@ flowchart TD
`p:{execution}:{node}:{sha256(outputs)[:16]}` in-process, where one
execution id can span several runs of a deployment.
- **Waiting**: a process-local waiter (`services/approvals/waiter.py`) wakes
- the gate the moment `decide_approval` settles the row; it also re-reads
- the row every `POLL_SECONDS` (10) to see decisions made in another process
- and expiry.
+ the gate the moment `decide_approval` moves the row; it also re-reads the
+ row every `POLL_SECONDS` (10), or at the end of an Undo or Restore window, to
+ see decisions made in another process and expiry. Undo moves an approved
+ draft back to pending, and the gate keeps waiting.
- **Error paths**: a worker shutting down mid-wait raises `NodeWaitInterrupted`,
which `BaseNode.as_activity` turns into a retryable `ApplicationError`. On
the in-process path there is no retry, and the run fails as for any error.
@@ -112,10 +122,11 @@ flowchart TD
([`server/models/approvals.py`](../../../server/models/approvals.py)): the
recipient, draft, final text, status, revision and expiry. Decisions are
compare-and-swap on `revision`.
-- **Broadcasts**: `approval_lifecycle` (CloudEvents type
- `com.opencompany.approval.{requested|decided|expired|cancelled}`, subject =
- approval id). Identity only, never the message body or the recipient; the
- page refetches through `list_approvals`. Node status `waiting` while it waits.
+- **Broadcasts**: `approval_lifecycle` (source
+ `opencompany://services/approvals`, CloudEvents type
+ `com.opencompany.approval.<stage>`, subject = approval id). Identity only,
+ never the message body or the recipient; the chat refetches through
+ `list_approvals`. Node status `waiting` while it waits.
- **External API calls**: none.
- **File I/O**: none.
- **Subprocess**: none.
diff --git a/docs-internal/normal_mode.md b/docs-internal/normal_mode.md
index dc480d93..e35e72f1 100644
--- a/docs-internal/normal_mode.md
+++ b/docs-internal/normal_mode.md
@@ -633,20 +633,31 @@ What goes live when:
## Asking before sending
-With the rule on, a reply waits in an `approvalGate` until the owner decides
-on the employee's page. The gate stores the draft in `approval_requests`,
-wakes the moment it is decided, survives restarts (its idempotency key finds
-the same row on every attempt), expires after `timeout_hours`, and fails
-closed: nothing is sent unless it was approved, and the recipient always comes
-from the run's trigger. Full contract:
-[approvalGate](./node-logic-flows/workflow_triggers/approvalGate.md).
-
-The same rule limits what an employee may add to itself from Talk (nothing
+The rule is live: the workflow's Ask first (`workflow_rules`, seeded from the
+hire's ground rules) is read every time something would send, and the Ask
+first chip beside the chat's message box changes it with no restart (turning
+it off asks first). With it on, a reply waits in an `approvalGate`, and a tool
+call that sends (a plugin with an `approval` spec) is held as a draft instead
+of running; both show as cards in the employee's chat, on the reply that made
+them or after the conversation. Send goes after a 5-second Undo window, a
+discarded draft can be restored, and a held call is sent once by its own
+Temporal workflow, which tells the employee how it went on its next turn.
+With it off, replies and calls go at once and the chat still shows what went.
+The gate stores the draft in `approval_requests`, wakes the moment it is
+decided, survives restarts (its idempotency key finds the same row on every
+attempt), expires after `timeout_hours`, and fails closed: nothing is sent
+unless it was approved, and the recipient always comes from the run's
+trigger. Full contract: [Chat Protocol, Approvals](./chat_protocol.md#approvals)
+and [approvalGate](./node-logic-flows/workflow_triggers/approvalGate.md).
+
+The rule also limits what an employee may add to itself from Talk (nothing
that sends or spends; see [Adding tools and skills from Talk](#adding-tools-and-skills-from-talk)),
and a talk agent that asks first is told it cannot send or spend anything for
-the owner, only write it for them to send. The summary's `asks_first` is the
-hire's rule (for a workflow built in Dev mode, whether it has an approval
-gate), shown in a line under the employee's page.
+the owner, only write it for them to send. The summary's `asks_first` follows
+the live rule (for a workflow built in Dev mode with no rule, whether it has an
+approval gate), shown in a line under the employee's page. A graph built
+before the live rule (`builder_version` below 3) needs Apply for a changed rule
+to cover everything: `set_ask_first` says so (`needs_apply`).
## "Done today"
diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.md
index 97546104..37b48654 100644
--- a/docs-internal/plugin_system.md
+++ b/docs-internal/plugin_system.md
@@ -81,6 +81,7 @@ class SpecializedAgentBase(ActionNode, abstract=True):
| `needs_canvas` | `ClassVar[bool]` — when `True`, the F4.B `AgentWorkflow` tool-dispatch forwards the parent workflow's `nodes`/`edges` into the per-tool activity payload. Today only `AgentBuilderNode` opts in: `add_tool` compares the run's canvas with the saved graph, so a tool saved earlier but missing from the running snapshot is handed back to be bound. Its calling agent comes from `invoking_agent_node_id` / `parent_node_id`, not from edges. |
| `chat_step` / `chat_step_hidden` | How a call of this tool reads as a working step in the chat while it answers the owner ("Searched the web"; default "Used <display name>"); `chat_step_hidden = True` shows none (the clock, the checklist). A tool may put a short line in its result as `_step_detail`, shown under the step and removed before the model reads the result. See [Chat Protocol](./chat_protocol.md#streaming-steps-and-stop). |
| `answers_chat_run` | `ClassVar[bool]` — the node posts a chat run's answer (Reply in Chat). The agent wired straight into such a node streams its text into the chat. |
+| `approval` | `ApprovalSpec` (`services/plugin/approval.py`) for a tool that reaches someone outside: which operations send (`operations`, `when`), who it goes to, the body and subject the owner may edit, the card's other lines, `refuse_while_asking` (Stripe) or `restrict_while_asking` (the browser, read-only). While the workflow asks first, an agent's call that sends is held as a draft for the owner instead of running. See [Chat Protocol, Approvals](./chat_protocol.md#approvals). |
| `chat_sources` | `ClassVar[bool]` — the tool returns web results (`results: [{title, snippet, url}]`, the searches). When the agent answering a chat run calls it, the results are numbered for the conversation in what the model reads, so the answer can cite them as `[n]`. See [Chat Protocol](./chat_protocol.md#sources). |
| `task_queue` | Temporal worker pool. See `TaskQueue` constants. |
| `retry_policy` | `RetryPolicy` dataclass (mirrors `temporalio.common.RetryPolicy`). |