Skip to content

AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).

fix(chat): name the tool round behind the progress indicator

Rufuse0167a5b1c99
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index bc4fa53b..506da44b 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -1677,7 +1677,8 @@ chat:
endpoint: POST /chat — server-sent events stream of the live turn.
sse_event_types:
- "chunk — one text delta from the assistant response stream. Fields: type, content, session_id."
- - "thinking — keepalive emitted between specialist rounds so the UI can show a Consulting specialists indicator. Fields: type, session_id."
+ - "thinking — keepalive emitted at the start of EVERY tool-use round, not just specialist ones. Fields: type, session_id. It carries no tool information, so the UI uses it purely as an in-flight boolean and takes the wording from the `activity` event that immediately precedes it. It used to be the sole driver of a hardcoded 'Consulting specialists…' string, which is why an MCP or calendar round looked like a specialist fan-out."
+ - "activity — names the tool round that is in flight. Fields: type, label, tool, iteration. Emitted once per tool-use iteration, always immediately before `thinking`, so an ordered consumer has the label before it turns its indicator on. `label` is present-progressive, already ends in an ellipsis, and is capped at 60 chars for the one-line indicator — render it verbatim. `tool` is the canonical tool behind the label; for MCP `call_tool` it is the UNDERLYING tool name (matching the `action_taken` convention), sanitized and truncated to 48 chars because it is model-authored text bound for the DOM. Labels come from `openexecutive.orchestrator.activity_labels._LABELS`; an unmapped tool falls back to 'Working…' rather than going silent. A mixed round collapses to ONE label by priority rank (`_PRIORITY`), never by joining clauses — the indicator is a single muted line. Rank 0 is `consult_specialist`, so a round containing a real fan-out always renders the generic 'Consulting specialists…' and NEVER names an individual specialist (the one-voice invariant). Ephemeral: unlike `action_taken` it is progress only and is never persisted with the assistant message."
- "phase — committee phase transition (drafting | reviewing | finalizing) when committee_review=true. Fields: type, phase, session_id."
- "committee_critique — severity preview from a committee reviewer. Fields: type, reviewer, severity."
- "action_taken — emitted whenever the Executive's tool-use loop completes a side-effecting tool call. Fields: type, tool, summary (≤80 chars, human-readable), target (person / channel ref / resource), link (optional in-app path the UI drills into), iteration. See `openexecutive.orchestrator.action_chips.SIDE_EFFECTING_TOOLS` for the canonical instrumented set; read-only tools (consult_specialist, lookup_person, list_people, search_skills, load_skill, search_tools, web_search, ask_about_person, list_workflows) never emit this event. The chip is suppressed when the handler returned an error payload — no green ✓ over a red outcome."
@@ -1700,6 +1701,32 @@ chat:
prefix, so conditional inclusion would invalidate the cache whenever
panel and non-panel turns alternate. Guarded by
tests/unit/test_executive_form_patch.py::test_tool_list_is_cache_stable_and_includes_form_tool.
+ activity_labels: |
+ The in-flight progress line. `orchestrator/activity_labels.py` is the
+ sibling of `action_chips.py`: same tool -> phrase mapping, but
+ present-progressive, covering every tool including read-only ones,
+ because it describes work that has not finished yet.
+
+ Emission is one place — the agent loop, immediately before it yields the
+ `_THINKING` sentinel. The call is wrapped in try/except: a labelling bug
+ costs the label, never the turn (the UI then falls back to "Working…").
+ The sentinel itself is deliberately unchanged; it is also the
+ "don't accumulate this into full_response" marker read by
+ `stream_chat`, the committee draft pass, and the non-streaming `.chat()`
+ wrapper that every channel adapter uses.
+
+ Rendered in `packages/ui/src/components/Chat.tsx` with precedence
+ committeePhase > activity label > nothing, and in
+ `components/askoe/AskOEPanel.tsx`, where it fills the streaming
+ placeholder that used to be a bare ellipsis. The label clears on the
+ first text chunk, on a committee phase change, at turn start, and in the
+ turn's finally — but deliberately NOT on `action_taken`, since a chip can
+ land while the same round is still running.
+
+ Known limitation: `Chat.tsx` gates the whole indicator row on
+ `!streamingContent`, so a tool round that happens AFTER prose has started
+ streaming shows nothing. Pre-existing, and unchanged by the label work.
+
action_taken_chips: |
Rendered as inline pills under each assistant message in
`packages/ui/src/components/Message.tsx`. Each chip shows a ✓
diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.json
index 01924734..a89a33a7 100644
--- a/packages/core/openexecutive/architecture/prebuilt/api.json
+++ b/packages/core/openexecutive/architecture/prebuilt/api.json
@@ -1,7 +1,7 @@
{
"section_id": "api",
"title": "API Reference",
- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages` | List and read saved chat sessions. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive` | Roster CRUD and scope lookups. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. |\n| `agents` | `GET /agents`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the eight specialist domains or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search` | Skill registry CRUD and search. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}` | Episodic-memory record management. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",
+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages` | List and read saved chat sessions. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive` | Roster CRUD and scope lookups. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. |\n| `agents` | `GET /agents`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the eight specialist domains or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search` | Skill registry CRUD and search. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}` | Episodic-memory record management. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",
"mermaid": null,
- "generated_at": "2026-09-18T22:32:15.703519+00:00"
+ "generated_at": "2026-09-21T17:18:01.394900+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/lifecycle.json b/packages/core/openexecutive/architecture/prebuilt/lifecycle.json
index ae40be74..fb3f3d02 100644
--- a/packages/core/openexecutive/architecture/prebuilt/lifecycle.json
+++ b/packages/core/openexecutive/architecture/prebuilt/lifecycle.json
@@ -1,7 +1,7 @@
{
"section_id": "lifecycle",
"title": "Request Lifecycle",
- "markdown": "A single chat message makes a full round-trip through the API, the orchestrator's tool-use loop, a parallel specialist fan-out, and synthesis — all streamed back as server-sent events.\n\n### Steps\n\n1. **Arrival** — the client posts to `POST /chat` (`openexecutive.api.routes.chat`). The turn carries a `<current_speaker>` hint resolved from the caller's `person_id`, plus a `<briefing>` digest of current open alerts (built in parallel with RAG/episodic/peer-memory fetches) so the Executive can discuss any item shown on the `/today` briefing page A turn arriving from a chat adapter instead of the web app also carries a `<channel>` block naming the surface and stating which approvals can be completed there; on Slack the `<briefing>` digest is gated to the principal's DMs. All three ride in the **user turn**, never a cached system block.\n2. **Tool-use loop** — the `Executive` calls Claude. For a cross-domain question the assistant turn emits multiple `consult_specialist` tool-use blocks at once.\n3. **Parallel fan-out** — `openexecutive.orchestrator.router.route_parallel` dispatches those calls concurrently, bounded by `MAX_PARALLEL_SPECIALISTS`; calls past the cap get a skip tool_result.\n4. **Per-specialist RAG** — each specialist runs its own domain-filtered ChromaDB query, then reasons over the retrieved chunks and returns analysis as a tool_result.\n5. **Synthesis** — the Executive feeds the tool_results back to Claude and streams one coherent reply; a `thinking` keepalive covers the specialist round.\n6. **Optional committee review** — when enabled, `Executive.stream_chat_with_committee()` runs a silent draft, parallel reviewer critiques, then a streamed revision pass.\n7. **Side effects** — any side-effecting tool call surfaces an `action_taken` chip; the stream closes with a `done` event. One side-effecting tool is gated server-side rather than by its description: `ack_alert` will only accept an `alert_id` from the live alert board the server itself derived this turn — the whole live set, not only the rows the `<briefing>` digest printed, since `/today` renders more cards than the digest lists and every one of them is Discuss-able — and it fails closed, so an id it cannot even parse is refused rather than waved through to the handler's own parse. That check runs on **every** session. It used to run only on turns that arrived from a chat channel, keyed on `origin_channel`, which the browser never sets — so the web, the surface the principal actually uses, was unchecked and the model could ack any id, including one quoted out of an alert body by the briefing page's Discuss handoff. What that buys is bounded and worth stating plainly: an id that is invented, closed, snoozed or expired is refused, including one quoted out of an attacker-written alert body; the model being argued into acking the wrong *live* card is not prevented. The board is recorded on the turn's `Session`, and the route binds that session for the **whole** SSE body (`schedule_tools.set_session`, alongside `set_turn`) rather than letting `stream_chat` bind it from inside its own generator. `_sse_body` drives the executive with `asyncio.wait_for(stream.__anext__())`, which runs each step in a fresh Task holding a *copy* of the context, so a binding made inside the generator is discarded with the step that made it: step one sees the session and every later step sees `None`. The tool-call loop runs on those later steps, so the whole guard read an empty set and refused every ack on the web — on live, open cards — until the binding moved out to the route. Anything reading `current_session` mid-turn has the same requirement, and two of them needed more than the binding to behave. `schedule_followup`'s seen-`channel_ref` anti-spam gate refuses a send to an address the session has not seen; with no session it skipped itself, so a web turn could schedule to **any** address, and with an empty one it refused even the principal's own. The route now seeds the caller's own addresses onto the session, so on web the gate means what it means on every other surface. Reply linkage (`_record_outbound_context`, read back by `inbound_hydration` to quote the originating conversation into the turn handling a recipient's reply) is the other: it was never reachable on web, and rather than switch that on for the principal's broadest surface as a side effect it is held back, keyed on an explicit `Session.from_web_chat` flag. Not on an empty `origin_channel` — that names an inbound chat adapter, and the email poller, alert review, the CLI and the unattended workflows all leave it empty while legitimately recording linkage. `scheduled_actions` rows also take their `session_id` from the session. A session that was shown no board has an empty trusted set and can ack nothing, so the unattended passes (the nightly reflection, the research synthesis) are refused by default — they also still withhold the tool outright, which is belt-and-braces rather than the only thing stopping them. After the stream closes, the turn is also handed to the episodic memory extractor (`memory.episodic.schedule_extraction`, fire-and-forget) — on every turn where the principal said anything at all, and only the principal: a turn naming an `origin_channel` must resolve to a person marked `is_principal`, because the quote validator downstream cannot tell whose words it is checking. Both this path and the committee path call the same `should_extract` predicate, and it applies no length floor: the gate used to sum in the assistant's reply, which let a verbose answer drag a trivial turn in and discarded the short, decisive instructions that are the whole point of extracting. A user-side floor would fare no better — \"Do B.\" and \"Done\" are one character apart. See **Memory** for what that cost on a live tenant.\n8. **Tool failures** — a handler that raises instead of returning its JSON error is isolated: both tool gathers run with `return_exceptions=True`, the model gets an error `tool_result` naming only the exception's TYPE — a message can carry a filesystem path, a validation error echoing the input, or a third-party HTTP body, and anything in model context can be quoted back to the user, so the full repr stays in the log and the audit row — and the failure is audited with `ok=false`. Only `CancelledError` is re-raised, so turn-timeout and client-disconnect handling still work. Before this one crashing tool aborted the whole turn, which reached the user as an unexplained apology with no audit row (#136).\n\nWeb search, when invoked on the Anthropic path, executes inside the Anthropic API itself (`web_search_20250305`) and returns within the same generation; for any model routed via OpenRouter the same tool becomes OpenRouter's `openrouter:web_search` server tool, which also runs inside the generation with the same search cap and domain lists.",
+ "markdown": "A single chat message makes a full round-trip through the API, the orchestrator's tool-use loop, a parallel specialist fan-out, and synthesis — all streamed back as server-sent events.\n\n### Steps\n\n1. **Arrival** — the client posts to `POST /chat` (`openexecutive.api.routes.chat`). The turn carries a `<current_speaker>` hint resolved from the caller's `person_id`, plus a `<briefing>` digest of current open alerts (built in parallel with RAG/episodic/peer-memory fetches) so the Executive can discuss any item shown on the `/today` briefing page A turn arriving from a chat adapter instead of the web app also carries a `<channel>` block naming the surface and stating which approvals can be completed there; on Slack the `<briefing>` digest is gated to the principal's DMs. All three ride in the **user turn**, never a cached system block.\n2. **Tool-use loop** — the `Executive` calls Claude. For a cross-domain question the assistant turn emits multiple `consult_specialist` tool-use blocks at once.\n3. **Parallel fan-out** — `openexecutive.orchestrator.router.route_parallel` dispatches those calls concurrently, bounded by `MAX_PARALLEL_SPECIALISTS`; calls past the cap get a skip tool_result.\n4. **Per-specialist RAG** — each specialist runs its own domain-filtered ChromaDB query, then reasons over the retrieved chunks and returns analysis as a tool_result.\n5. **Synthesis** — the Executive feeds the tool_results back to Claude and streams one coherent reply. Every tool round — not just a specialist one — emits an `activity` event naming what is running, immediately followed by a `thinking` keepalive. The label names the *activity*, never the internal agent: \"Putting time on the calendar…\", \"Looking up people…\", or, for an MCP call, the underlying tool by name. A round that really does fan out collapses to the generic \"Consulting specialists…\" — the one voice holds even in the progress line. The keepalive carries no tool information of its own; it used to drive a hardcoded \"Consulting specialists…\" string, so an MCP or calendar round misreported itself as a fan-out.\n6. **Optional committee review** — when enabled, `Executive.stream_chat_with_committee()` runs a silent draft, parallel reviewer critiques, then a streamed revision pass.\n7. **Side effects** — any side-effecting tool call surfaces an `action_taken` chip, which unlike the ephemeral `activity` label is persisted with the assistant message; the stream closes with a `done` event. One side-effecting tool is gated server-side rather than by its description: `ack_alert` will only accept an `alert_id` from the live alert board the server itself derived this turn — the whole live set, not only the rows the `<briefing>` digest printed, since `/today` renders more cards than the digest lists and every one of them is Discuss-able — and it fails closed, so an id it cannot even parse is refused rather than waved through to the handler's own parse. That check runs on **every** session. It used to run only on turns that arrived from a chat channel, keyed on `origin_channel`, which the browser never sets — so the web, the surface the principal actually uses, was unchecked and the model could ack any id, including one quoted out of an alert body by the briefing page's Discuss handoff. What that buys is bounded and worth stating plainly: an id that is invented, closed, snoozed or expired is refused, including one quoted out of an attacker-written alert body; the model being argued into acking the wrong *live* card is not prevented. The board is recorded on the turn's `Session`, and the route binds that session for the **whole** SSE body (`schedule_tools.set_session`, alongside `set_turn`) rather than letting `stream_chat` bind it from inside its own generator. `_sse_body` drives the executive with `asyncio.wait_for(stream.__anext__())`, which runs each step in a fresh Task holding a *copy* of the context, so a binding made inside the generator is discarded with the step that made it: step one sees the session and every later step sees `None`. The tool-call loop runs on those later steps, so the whole guard read an empty set and refused every ack on the web — on live, open cards — until the binding moved out to the route. Anything reading `current_session` mid-turn has the same requirement, and two of them needed more than the binding to behave. `schedule_followup`'s seen-`channel_ref` anti-spam gate refuses a send to an address the session has not seen; with no session it skipped itself, so a web turn could schedule to **any** address, and with an empty one it refused even the principal's own. The route now seeds the caller's own addresses onto the session, so on web the gate means what it means on every other surface. Reply linkage (`_record_outbound_context`, read back by `inbound_hydration` to quote the originating conversation into the turn handling a recipient's reply) is the other: it was never reachable on web, and rather than switch that on for the principal's broadest surface as a side effect it is held back, keyed on an explicit `Session.from_web_chat` flag. Not on an empty `origin_channel` — that names an inbound chat adapter, and the email poller, alert review, the CLI and the unattended workflows all leave it empty while legitimately recording linkage. `scheduled_actions` rows also take their `session_id` from the session. A session that was shown no board has an empty trusted set and can ack nothing, so the unattended passes (the nightly reflection, the research synthesis) are refused by default — they also still withhold the tool outright, which is belt-and-braces rather than the only thing stopping them. After the stream closes, the turn is also handed to the episodic memory extractor (`memory.episodic.schedule_extraction`, fire-and-forget) — on every turn where the principal said anything at all, and only the principal: a turn naming an `origin_channel` must resolve to a person marked `is_principal`, because the quote validator downstream cannot tell whose words it is checking. Both this path and the committee path call the same `should_extract` predicate, and it applies no length floor: the gate used to sum in the assistant's reply, which let a verbose answer drag a trivial turn in and discarded the short, decisive instructions that are the whole point of extracting. A user-side floor would fare no better — \"Do B.\" and \"Done\" are one character apart. See **Memory** for what that cost on a live tenant.\n8. **Tool failures** — a handler that raises instead of returning its JSON error is isolated: both tool gathers run with `return_exceptions=True`, the model gets an error `tool_result` naming only the exception's TYPE — a message can carry a filesystem path, a validation error echoing the input, or a third-party HTTP body, and anything in model context can be quoted back to the user, so the full repr stays in the log and the audit row — and the failure is audited with `ok=false`. Only `CancelledError` is re-raised, so turn-timeout and client-disconnect handling still work. Before this one crashing tool aborted the whole turn, which reached the user as an unexplained apology with no audit row (#136).\n\nWeb search, when invoked on the Anthropic path, executes inside the Anthropic API itself (`web_search_20250305`) and returns within the same generation; for any model routed via OpenRouter the same tool becomes OpenRouter's `openrouter:web_search` server tool, which also runs inside the generation with the same search cap and domain lists.",
"mermaid": "sequenceDiagram\n participant C as Client\n participant API as FastAPI /chat\n participant E as Executive\n participant CL as Claude\n participant S as Specialists\n participant KB as ChromaDB\n C->>API: POST /chat message\n API->>E: start turn\n E->>CL: messages (tool-use loop)\n CL-->>E: consult_specialist calls\n E->>S: route_parallel fan-out\n S->>KB: domain-filtered RAG\n KB-->>S: chunks\n S-->>E: analysis tool_results\n E->>CL: synthesize\n CL-->>E: streamed reply\n E-->>API: SSE chunks then done\n API-->>C: streamed response",
- "generated_at": "2026-09-18T20:54:42.334412+00:00"
+ "generated_at": "2026-09-21T17:18:01.394900+00:00"
}
diff --git a/packages/core/openexecutive/cli.py b/packages/core/openexecutive/cli.py
index 5cfa8fb6..4e81c86a 100644
--- a/packages/core/openexecutive/cli.py
+++ b/packages/core/openexecutive/cli.py
@@ -49,7 +49,7 @@ async def _ask(question: str) -> None:
retrieved_context=retrieved,
episodic_context=episodic,
):
- if isinstance(chunk, str):
+ if isinstance(chunk, str) and chunk != Executive._THINKING:
response += chunk
console.print(chunk, end="", highlight=False)
@@ -106,7 +106,8 @@ async def _chat() -> None:
retrieved_context=retrieved,
episodic_context=episodic,
):
- console.print(chunk, end="", highlight=False)
+ if isinstance(chunk, str) and chunk != Executive._THINKING:
+ console.print(chunk, end="", highlight=False)
console.print("\n")
diff --git a/packages/core/openexecutive/orchestrator/activity_labels.py b/packages/core/openexecutive/orchestrator/activity_labels.py
new file mode 100644
index 00000000..0914f87f
--- /dev/null
+++ b/packages/core/openexecutive/orchestrator/activity_labels.py
@@ -0,0 +1,259 @@
+"""Name the tool round that is currently in flight, for the chat progress line.
+
+The agent loop yields one `_THINKING` sentinel per tool-use iteration, and the
+UI turns that into a single muted line beside the bouncing dots. That line used
+to read "Consulting specialists…" unconditionally, so an MCP call or a calendar
+write looked like a specialist fan-out. This module supplies the label that
+makes it honest: one `activity` SSE event per tool round, naming what actually
+ran.
+
+Sibling of `action_chips.py`, which does the same tool -> phrase mapping in the
+*past* tense for side-effecting calls only. This one is present-progressive and
+covers every tool, read-only included, because the point is to describe work
+that has not finished yet.
+
+Invariant: a real `consult_specialist` round gets exactly one generic label —
+"Consulting specialists…". Individual specialist names are NEVER put in a
+user-facing label (CLAUDE.md: the internal agent architecture is never exposed
+to the user; there is one voice).
+"""
+from __future__ import annotations
+
+import re
+from typing import Any
+
+# Shown when a round contains only tools with no entry in `_LABELS`. Going
+# silent is not an option — a round with no label is the exact failure this
+# event exists to fix, and the UI would fall back to its own placeholder.
+FALLBACK_LABEL = "Working…"
+
+SPECIALIST_LABEL = "Consulting specialists…"
+
+# Longest underlying MCP tool name rendered into a label. MCP names are
+# model-authored text on their way to the DOM, so they are capped and stripped
+# here rather than trusted. React escapes the value, but a 4KB name or an
+# embedded newline would still wreck a one-line indicator.
+_MCP_NAME_MAX = 48
+_MCP_NAME_UNSAFE = re.compile(r"[^A-Za-z0-9_.:\- ]")
+
+# Canonical tool name -> present-progressive phrase. Every entry ends in an
+# ellipsis and is short enough for one line next to the dots; the drift test in
+# tests/unit/test_activity_labels.py enforces both, and also enforces that every
+# registered Executive tool appears here.
+_LABELS: dict[str, str] = {
+ # Specialist fan-out — deliberately generic. See the module docstring.
+ "consult_specialist": SPECIALIST_LABEL,
+
+ # Skills
+ "search_skills": "Looking through saved skills…",
+ "load_skill": "Opening a saved skill…",
+ "create_skill": "Saving a new skill…",
+ "update_skill": "Updating a saved skill…",
+ "delete_skill": "Removing a saved skill…",
+
+ # Scheduling and outbound messages
+ "schedule_followup": "Scheduling a follow-up…",
+ "suggest_workflow": "Queuing a workflow suggestion…",
+ "send_telegram_message": "Sending a Telegram message…",
+ "send_slack_dm": "Sending a Slack DM…",
+ "send_discord_dm": "Sending a Discord DM…",
+ "message_person": "Sending a message…",
+ "lookup_person": "Looking up people…",
+ "ack_alert": "Updating a proposal…",
+
+ # Calendar. These write, so none of them says "checking" — the label is
+ # emitted before the call runs and must not promise a read.
+ "create_calendar_event": "Putting time on the calendar…",
+ "create_instant_meeting": "Spinning up a meeting…",
+ "cancel_calendar_event": "Clearing time from the calendar…",
+
+ # People and org chart
+ "list_people": "Looking up people…",
+ "upsert_person": "Updating the people roster…",
+ "archive_person": "Updating the people roster…",
+ "set_department_head": "Updating the org chart…",
+ "ask_about_person": "Checking what I know about someone…",
+
+ # Departments
+ "list_department_goals": "Reviewing department goals…",
+ "update_department_goal": "Updating a department goal…",
+
+ # Broadcast channels
+ "send_department_message": "Posting to a department channel…",
+ "send_company_broadcast": "Sending a company-wide note…",
+
+ # Watchlist
+ "add_watchlist_entry": "Adding to the watchlist…",
+ "list_watchlist": "Checking the watchlist…",
+ "remove_watchlist_entry": "Updating the watchlist…",
+ "tune_watchlist_entry": "Tuning the watchlist…",
+
+ # Research, alerts, artifacts
+ "run_executive_research": "Researching…",
+ "create_alert": "Flagging something for review…",
+ "draft_artifact": "Writing that up…",
+
+ # Workflows
+ "draft_workflow": "Drafting a workflow…",
+ "save_workflow": "Saving the workflow…",
+ "list_workflows": "Checking available workflows…",
+ "run_workflow": "Running a workflow…",
+
+ # Ask OE panel form fill
+ "propose_form_values": "Filling in the form…",
+
+ # MCP gateway. `call_tool` is dynamic and handled in `_label_for`.
+ "search_tools": "Looking for the right tool…",
+ "load_mcp_server": "Connecting a tool server…",
+}
+
+# One `_THINKING` per iteration means exactly one label per iteration, so a
+# mixed round has to collapse. It collapses by rank rather than by joining
+# clauses: the indicator is a single muted line, and two joined phrases both
+# overflow on a narrow panel and read like generated grammar.
+#
+# Lower rank wins. The order tracks what the user most wants to know is
+# happening, which in practice tracks how long the call blocks the turn.
+# Rank 0 is also what keeps a mixed specialist round generic.
+#
+# A tool in no bucket is not unreachable: when nothing in the round is ranked,
+# `_pick` falls back to the first block it can name, so a read like
+# `list_workflows` still gets its own label even alongside a tool the map has
+# never heard of. Ties inside a bucket break on block order, which the
+# Anthropic response preserves, so the choice is deterministic.
+_PRIORITY: tuple[frozenset[str], ...] = (
+ frozenset({"consult_specialist"}),
+ frozenset({"run_executive_research"}),
+ frozenset({"run_workflow", "draft_workflow", "save_workflow"}),
+ frozenset({"call_tool", "load_mcp_server", "search_tools"}),
+ frozenset({
+ "create_calendar_event",
+ "create_instant_meeting",
+ "cancel_calendar_event",
+ }),
+ frozenset({
+ "send_slack_dm",
+ "send_discord_dm",
+ "send_telegram_message",
+ "message_person",
+ "send_department_message",
+ "send_company_broadcast",
+ "schedule_followup",
+ "suggest_workflow",
+ }),
+ frozenset({
+ "upsert_person",
+ "archive_person",
+ "set_department_head",
+ "update_department_goal",
+ }),
+ frozenset({
+ "create_alert",
+ "ack_alert",
+ "draft_artifact",
+ "add_watchlist_entry",
+ "remove_watchlist_entry",
+ "tune_watchlist_entry",
+ }),
+ frozenset({
+ "create_skill",
+ "update_skill",
+ "delete_skill",
+ "propose_form_values",
+ }),
+)
+
+
+def _mcp_label(tool_input: Any) -> tuple[str, str]:
+ """Label an MCP `call_tool` from the underlying tool it wraps.
+
+ The real tool name lives in `tool_input["name"]` — the same field
+ `action_chips.summarize_action` reads to surface the true tool on an MCP
+ chip. A static label here would be useless, which matters because MCP is
+ the case that made the old indicator wrong most visibly.
+ """
+ raw = tool_input.get("name") if isinstance(tool_input, dict) else None
+ if not isinstance(raw, str):
+ return "Using a connected tool…", "call_tool"
+ name = _MCP_NAME_UNSAFE.sub("", raw).strip()[:_MCP_NAME_MAX].strip()
+ if not name:
+ return "Using a connected tool…", "call_tool"
+ return f"Using {name}…", name
+
+
+def _label_for(tool_use: dict[str, Any]) -> tuple[str, str]:
+ """Return `(label, canonical_tool_name)` for one tool_use block."""
+ name = tool_use.get("name")
+ if not isinstance(name, str):
+ return FALLBACK_LABEL, ""
+ if name == "call_tool":
+ return _mcp_label(tool_use.get("input"))
+ return _LABELS.get(name, FALLBACK_LABEL), name
+
+
+def _is_nameable(tool_use: dict[str, Any]) -> bool:
+ return tool_use.get("name") in _LABELS or tool_use.get("name") == "call_tool"
+
+
+def _pick(tool_uses: list[dict[str, Any]]) -> dict[str, Any]:
+ """Choose the one tool_use block whose label represents the round.
+
+ Ranked tools win first. Failing that, prefer any block we can actually
+ name over block order — otherwise an unlabelled tool sitting in position
+ zero would shadow a nameable one behind it and the round would render
+ "Working…" despite having something to say. Only a round where nothing is
+ nameable falls back to the first block.
+ """
+ for bucket in _PRIORITY:
+ for tool_use in tool_uses:
+ if tool_use.get("name") in bucket:
+ return tool_use
+ for tool_use in tool_uses:
+ if _is_nameable(tool_use):
+ return tool_use
+ return tool_uses[0]
+
+
+def fallback_activity(*, iteration: int | None = None) -> dict[str, Any]:
+ """The unnamed-round event, for when a label could not be produced.
+
+ The agent loop pairs every `_THINKING` sentinel with exactly one `activity`
+ event. Yielding nothing here would break that pairing, and a client that
+ keeps the last label it saw would then caption this round with the previous
+ round's work — a stale label is worse than an honest "Working…".
+ """
+ payload: dict[str, Any] = {
+ "type": "activity",
+ "label": FALLBACK_LABEL,
+ "tool": "",
+ }
+ if iteration is not None:
+ payload["iteration"] = iteration
+ return payload
+
+
+def summarize_activity(
+ tool_uses: list[dict[str, Any]],
+ *,
+ iteration: int | None = None,
+) -> dict[str, Any] | None:
+ """Build the `activity` SSE event for one tool round, or None.
+
+ `tool_uses` holds the `{"id", "name", "input"}` dicts the agent loop
+ collected from the model's tool_use blocks. Returns None only for an empty
+ round — defensive, since the loop reaches this point only on
+ `stop_reason == "tool_use"`. Anything else always produces an event; an
+ unmapped tool falls back to `FALLBACK_LABEL` rather than going silent.
+
+ The returned dict is the SSE event body; `api/routes/chat.py` forwards it
+ verbatim. It is progress only and is never persisted with the assistant
+ message, unlike an `action_taken` chip.
+ """
+ if not tool_uses:
+ return None
+
+ label, tool = _label_for(_pick(tool_uses))
+ payload: dict[str, Any] = {"type": "activity", "label": label, "tool": tool}
+ if iteration is not None:
+ payload["iteration"] = iteration
+ return payload
diff --git a/packages/core/openexecutive/orchestrator/executive.py b/packages/core/openexecutive/orchestrator/executive.py
index b3ac1963..150aa9dd 100644
--- a/packages/core/openexecutive/orchestrator/executive.py
+++ b/packages/core/openexecutive/orchestrator/executive.py
@@ -22,6 +22,10 @@ from openexecutive.audit.usage import log_model_usage
from openexecutive.config import get_settings
from openexecutive.memory.honcho_client import ReasoningLevel as HonchoReasoningLevel
from openexecutive.orchestrator.action_chips import summarize_action
+from openexecutive.orchestrator.activity_labels import (
+ fallback_activity,
+ summarize_activity,
+)
from openexecutive.orchestrator.alert_tools import (
CREATE_ALERT_TOOL,
handle_create_alert,
@@ -1472,6 +1476,23 @@ class Executive:
})
yield debug_collector.to_sse_dict(evt)
+ # Name the round before the sentinel, so an ordered consumer has
+ # the label in hand by the time it switches its in-flight
+ # indicator on. Never fatal: a labelling bug must not take the
+ # turn down with it.
+ try:
+ activity = summarize_activity(tool_uses, iteration=iteration)
+ except Exception:
+ logger.warning(
+ "activity_label_failed iteration=%d", iteration, exc_info=True
+ )
+ activity = None
+ # Exactly one activity per sentinel, unconditionally. Skipping it
+ # on the None/raise paths would leave a client that keeps the last
+ # label it saw captioning this round with the previous round's
+ # work; an honest "Working…" beats a stale name.
+ yield activity or fallback_activity(iteration=iteration)
+
# Signal that tool calls are in flight so the client can show progress.
yield self._THINKING
diff --git a/packages/core/tests/unit/_agent_loop_fakes.py b/packages/core/tests/unit/_agent_loop_fakes.py
new file mode 100644
index 00000000..205f413a
--- /dev/null
+++ b/packages/core/tests/unit/_agent_loop_fakes.py
@@ -0,0 +1,79 @@
+"""Shared fakes for driving `Executive._stream_agent_loop` without a provider.
+
+The loop only needs a provider exposing `messages_stream(**kwargs)` that
+returns an async context manager yielding content-block deltas and, at the end,
+a final message with `.content` and `.stop_reason`. These are the smallest
+objects satisfying that contract, so a test can script a turn as a list of
+final messages and assert on what the loop yields.
+
+Note the stream emits NO text deltas: content rides on the final message.
+That is enough for tool-round behaviour (which is what these fakes exist for)
+but means the loop yields no assistant text, so assert on `ScriptedProvider.
+calls` rather than on streamed prose when you need to prove the loop advanced.
+
+Extracted from the copy in test_executive_form_patch.py. Several older modules
+still carry their own near-identical copies; they can migrate here piecemeal.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+
+class TextBlock:
+ type = "text"
+
+ def __init__(self, text: str) -> None:
+ self.text = text
+
+
+class ToolUseBlock:
+ type = "tool_use"
+
+ def __init__(self, id_: str, name: str, input_: dict[str, Any]) -> None:
+ self.id = id_
+ self.name = name
+ self.input = input_
+
+
+class FinalMsg:
+ usage = None # _emit_cache_event no-ops on usage=None
+
+ def __init__(self, content: list[Any], stop_reason: str) -> None:
+ self.content = content
+ self.stop_reason = stop_reason
+
+
+class FakeStream:
+ def __init__(self, final_msg: FinalMsg) -> None:
+ self._final_msg = final_msg
+
+ async def __aenter__(self) -> FakeStream:
+ return self
+
+ async def __aexit__(self, *_a: Any) -> None:
+ return None
+
+ def __aiter__(self) -> FakeStream:
+ return self
+
+ async def __anext__(self) -> Any:
+ raise StopAsyncIteration # no text deltas; content rides on final_msg
+
+ async def get_final_message(self) -> FinalMsg:
+ return self._final_msg
+
+
+class ScriptedProvider:
+ """Returns one scripted final message per `messages_stream` call.
+
+ `calls` records the kwargs of each call, so a test can prove the loop made
+ its follow-up request after feeding tool results back.
+ """
+
+ def __init__(self, final_msgs: list[FinalMsg]) -> None:
+ self._final_msgs = list(final_msgs)
+ self.calls: list[dict[str, Any]] = []
+
+ def messages_stream(self, **kwargs: Any) -> FakeStream:
+ self.calls.append(kwargs)
+ return FakeStream(self._final_msgs.pop(0))
diff --git a/packages/core/tests/unit/test_activity_labels.py b/packages/core/tests/unit/test_activity_labels.py
new file mode 100644
index 00000000..2b3333fe
--- /dev/null
+++ b/packages/core/tests/unit/test_activity_labels.py
@@ -0,0 +1,238 @@
+"""Unit tests for `orchestrator.activity_labels.summarize_activity`.
+
+Covers:
+ * one label per round, chosen by priority rank, never by concatenation
+ * the one-voice invariant — a specialist round never names a specialist
+ * MCP `call_tool` resolving to the underlying tool name, and its hardening
+ * the "Working…" fallback for tools with no entry in the map
+ * drift: every tool the Executive can actually call has a label
+"""
+from __future__ import annotations
+
+import pytest
+
+from openexecutive.orchestrator import activity_labels as al
+from openexecutive.orchestrator.activity_labels import (
+ FALLBACK_LABEL,
+ SPECIALIST_LABEL,
+ summarize_activity,
+)
+
+
+def _tu(tool_name: str, **input_kwargs: object) -> dict[str, object]:
+ """One tool_use block shaped like the agent loop builds them.
+
+ The first argument is the *tool* name; keyword arguments become the tool
+ input — including MCP's own `name` field, which is why this parameter is
+ not called `name`.
+ """
+ return {
+ "id": f"toolu_{tool_name}",
+ "name": tool_name,
+ "input": dict(input_kwargs),
+ }
+
+
+# --------------------------------------------------------------------------
+# Specialist rounds stay generic
+# --------------------------------------------------------------------------
+
+def test_specialist_round_uses_the_generic_label() -> None:
+ evt = summarize_activity([_tu("consult_specialist", specialist="finance")])
+ assert evt is not None
+ assert evt["label"] == SPECIALIST_LABEL
+
+
+def test_specialist_label_never_names_the_specialist() -> None:
+ """Guards the CLAUDE.md one-voice invariant against a 'helpful' future edit."""
+ evt = summarize_activity([
+ _tu("consult_specialist", specialist="finance", query="runway?"),
+ _tu("consult_specialist", specialist="legal", query="risk?"),
+ ])
+ assert evt is not None
+ blob = " ".join(str(v) for v in evt.values()).lower()
+ for leaked in ("finance", "legal", "runway", "risk"):
+ assert leaked not in blob
+
+
+def test_specialist_wins_a_mixed_round_regardless_of_block_order() -> None:
+ """Specialist is rank 0, so it wins even when it is not the first block."""
+ evt = summarize_activity([
+ _tu("create_calendar_event", title="sync"),
+ _tu("consult_specialist", specialist="finance"),
+ ])
+ assert evt is not None
+ assert evt["label"] == SPECIALIST_LABEL
+
+
+# --------------------------------------------------------------------------
+# Non-specialist rounds — the bug this module exists to fix
+# --------------------------------------------------------------------------
+
+ ("tool_name", "expected"),
+ [
+ ("create_calendar_event", "Putting time on the calendar…"),
+ ("list_people", "Looking up people…"),
+ ("send_slack_dm", "Sending a Slack DM…"),
+ ("run_workflow", "Running a workflow…"),
+ ("run_executive_research", "Researching…"),
+ ("create_alert", "Flagging something for review…"),
+ ("search_tools", "Looking for the right tool…"),
+ ("load_mcp_server", "Connecting a tool server…"),
+ ("propose_form_values", "Filling in the form…"),
+ ("list_workflows", "Checking available workflows…"),
+ ],
+)
+def test_single_tool_round_is_named(tool_name: str, expected: str) -> None:
+ evt = summarize_activity([_tu(tool_name)])
+ assert evt is not None
+ assert evt["label"] == expected
+ assert evt["tool"] == tool_name
+ assert SPECIALIST_LABEL not in evt["label"]
+
+
+def test_unranked_tool_alone_still_gets_its_own_label() -> None:
+ """A tool in no priority bucket falls back to block order, not to 'Working…'."""
+ evt = summarize_activity([_tu("list_watchlist")])
+ assert evt is not None
+ assert evt["label"] == "Checking the watchlist…"
+
+
+def test_nameable_tool_beats_an_unknown_one_in_block_position_zero() -> None:
+ """An unmapped tool must not shadow a nameable one behind it."""
+ evt = summarize_activity([_tu("some_future_tool"), _tu("list_workflows")])
+ assert evt is not None
+ assert evt["label"] == "Checking available workflows…"
+ assert evt["tool"] == "list_workflows"
+
+
+def test_round_with_nothing_nameable_falls_back() -> None:
+ evt = summarize_activity([_tu("aaa_unknown"), _tu("bbb_unknown")])
+ assert evt is not None
+ assert evt["label"] == FALLBACK_LABEL
+
+
+def test_fallback_activity_is_a_well_formed_event() -> None:
+ """The loop pairs every sentinel with one of these when labelling fails."""
+ evt = al.fallback_activity(iteration=2)
+ assert evt == {
+ "type": "activity",
+ "label": FALLBACK_LABEL,
+ "tool": "",
+ "iteration": 2,
+ }
+ assert "iteration" not in al.fallback_activity()
+
+
+def test_priority_rank_decides_a_mixed_non_specialist_round() -> None:
+ evt = summarize_activity([_tu("upsert_person"), _tu("run_workflow")])
+ assert evt is not None
+ assert evt["label"] == "Running a workflow…"
+
+
+def test_repeated_same_tool_yields_one_label() -> None:
+ evt = summarize_activity([_tu("send_slack_dm"), _tu("send_slack_dm")])
+ assert evt is not None
+ assert evt["label"] == "Sending a Slack DM…"
+
+
+# --------------------------------------------------------------------------
+# MCP
+# --------------------------------------------------------------------------
+
+def test_mcp_call_tool_uses_the_underlying_tool_name() -> None:
+ evt = summarize_activity(
+ [_tu("call_tool", name="google_workspace__send_gmail_message", arguments={})]
+ )
+ assert evt is not None
+ assert evt["label"] == "Using google_workspace__send_gmail_message…"
+ assert evt["tool"] == "google_workspace__send_gmail_message"
+
+
[email protected]("bad", [None, 42, "", " ", "<<<>>>"])
+def test_mcp_call_tool_falls_back_when_the_name_is_unusable(bad: object) -> None:
+ tu = {"id": "t", "name": "call_tool", "input": {"name": bad}}
+ evt = summarize_activity([tu])
+ assert evt is not None
+ assert evt["label"] == "Using a connected tool…"
+ assert evt["tool"] == "call_tool"
+
+
+def test_mcp_call_tool_handles_a_missing_input_dict() -> None:
+ evt = summarize_activity([{"id": "t", "name": "call_tool", "input": None}])
+ assert evt is not None
+ assert evt["label"] == "Using a connected tool…"
+
+
+def test_mcp_tool_name_is_sanitized_and_truncated() -> None:
+ """Model-authored text on its way to the DOM: strip and cap it here."""
+ evt = summarize_activity(
+ [_tu("call_tool", name="<b>evil</b>\nnewline " + "x" * 200)]
+ )
+ assert evt is not None
+ label = evt["label"]
+ assert "<" not in label and ">" not in label and "\n" not in label
+ assert len(label) <= 60
+
+
+# --------------------------------------------------------------------------
+# Fallback, shape, and defensive inputs
+# --------------------------------------------------------------------------
+
+def test_unmapped_tool_falls_back_to_working() -> None:
+ evt = summarize_activity([_tu("some_future_tool")])
+ assert evt is not None
+ assert evt["label"] == FALLBACK_LABEL
+
+
+def test_non_string_tool_name_falls_back() -> None:
+ evt = summarize_activity([{"id": "t", "name": None, "input": {}}])
+ assert evt is not None
+ assert evt["label"] == FALLBACK_LABEL
+
+
+def test_empty_round_returns_none() -> None:
+ assert summarize_activity([]) is None
+
+
+def test_iteration_is_echoed_when_given_and_omitted_when_not() -> None:
+ with_it = summarize_activity([_tu("list_people")], iteration=3)
+ without = summarize_activity([_tu("list_people")])
+ assert with_it is not None and without is not None
+ assert with_it["iteration"] == 3
+ assert "iteration" not in without
+ assert with_it["type"] == "activity"
+
+
+# --------------------------------------------------------------------------
+# Drift guards
+# --------------------------------------------------------------------------
+
+def test_every_label_is_present_progressive_and_fits_one_line() -> None:
+ for tool, label in al._LABELS.items():
+ assert label.endswith("…"), tool
+ assert label == label.strip(), tool
+ assert len(label) <= 60, (tool, len(label))
+ assert FALLBACK_LABEL.endswith("…")
+
+
+def test_every_priority_entry_has_a_label() -> None:
+ """A tool can't be ranked without being nameable."""
+ ranked = {name for bucket in al._PRIORITY for name in bucket}
+ assert ranked - set(al._LABELS) == {"call_tool"}
+
+
+def test_every_registered_executive_tool_has_a_label() -> None:
+ """The real drift guard: adding a tool without a label is a silent regression.
+
+ `_ALL_SKILL_HANDLERS` is the merged source of truth for every handler-backed
+ tool the Executive can call; MCP and the specialist tool sit outside it.
+ """
+ from openexecutive.orchestrator.executive import _ALL_SKILL_HANDLERS
+ from openexecutive.orchestrator.mcp_gateway import MCP_TOOL_NAMES
+
+ registered = set(_ALL_SKILL_HANDLERS) | set(MCP_TOOL_NAMES) | {"consult_specialist"}
+ # `call_tool` is labelled dynamically from the tool it wraps.
+ missing = registered - set(al._LABELS) - {"call_tool"}
+ assert not missing, f"tools with no activity label: {sorted(missing)}"
diff --git a/packages/core/tests/unit/test_chat_route_activity_events.py b/packages/core/tests/unit/test_chat_route_activity_events.py
new file mode 100644
index 00000000..3705234c
--- /dev/null
+++ b/packages/core/tests/unit/test_chat_route_activity_events.py
@@ -0,0 +1,163 @@
+"""The `/chat` SSE route forwards `activity` events without touching them.
+
+`api/routes/chat.py` has no event-type allowlist — any non-str stream item is
+serialized straight to the wire, and only `action_taken` is pulled aside for
+persistence. These tests pin both halves of that:
+
+ * an `activity` event reaches the client verbatim, ahead of `thinking`;
+ * it is NOT persisted onto the assistant row as an action chip. The label is
+ progress, not a record of something that happened.
+"""
+from __future__ import annotations
+
+import json
+import sqlite3
+from collections.abc import AsyncIterator
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from openexecutive.api.routes import chat as chat_route
+from openexecutive.memory import episodic, session_store
+from openexecutive.memory.company_profile import CompanyProfile
+
+MCP_ACTIVITY: dict[str, Any] = {
+ "type": "activity",
+ "label": "Using google_workspace__send_gmail_message…",
+ "tool": "google_workspace__send_gmail_message",
+ "iteration": 1,
+}
+SPECIALIST_ACTIVITY: dict[str, Any] = {
+ "type": "activity",
+ "label": "Consulting specialists…",
+ "tool": "consult_specialist",
+ "iteration": 1,
+}
+
+
[email protected](autouse=True)
+def _reset_route_state() -> None:
+ chat_route._sessions.clear()
+ chat_route._last_turn_events.clear()
+ chat_route._last_turn_meta.clear()
+
+
+def temp_db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ monkeypatch.chdir(tmp_path)
+ db_path = Path("./episodic_memory.db").resolve()
+ monkeypatch.setattr(episodic, "DB_PATH", db_path)
+ monkeypatch.setattr(session_store, "DB_PATH", db_path)
+ episodic.initialize_db(db_path)
+ return db_path
+
+
+def patched_deps(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
+
+ from openexecutive.onboarding import profile_builder
+
+ monkeypatch.setattr(
+ profile_builder, "load_or_create_profile", lambda: CompanyProfile()
+ )
+
+ from openexecutive.knowledge import retriever
+
+ monkeypatch.setattr(
+ retriever,
+ "retrieve",
+ lambda query, specialist_name=None, store=None: "",
+ )
+
+ from openexecutive.utils import session_title as _title_mod
+
+ async def _no_title(*_a: Any, **_k: Any) -> None:
+ return None
+
+ monkeypatch.setattr(_title_mod, "generate_session_title", _no_title)
+
+
+def _client_streaming(
+ monkeypatch: pytest.MonkeyPatch, activity: dict[str, Any]
+) -> TestClient:
+ """A fake Executive that yields one activity + sentinel + one text chunk."""
+ from openexecutive.orchestrator import executive as exec_mod
+
+ class _FakeExecutive:
+ _THINKING = exec_mod.Executive._THINKING
+
+ def __init__(self, **_kwargs: Any) -> None:
+ pass
+
+ async def stream_chat(self, **_kwargs: Any) -> AsyncIterator[Any]:
+ yield activity
+ yield self._THINKING
+ yield "all set"
+
+ monkeypatch.setattr(exec_mod, "Executive", _FakeExecutive)
+
+ app = FastAPI()
+ app.include_router(chat_route.router)
+ return TestClient(app)
+
+
+def _sse_events(body: str) -> list[dict[str, Any]]:
+ return [
+ json.loads(line[len("data: ") :])
+ for line in body.splitlines()
+ if line.startswith("data: ")
+ ]
+
+
+def _types(events: list[dict[str, Any]]) -> list[str]:
+ return [e.get("type", "") for e in events]
+
+
+ "activity", [MCP_ACTIVITY, SPECIALIST_ACTIVITY], ids=["mcp", "specialist"]
+)
+def test_activity_event_is_forwarded_verbatim_before_thinking(
+ temp_db: Path,
+ patched_deps: None,
+ monkeypatch: pytest.MonkeyPatch,
+ activity: dict[str, Any],
+) -> None:
+ client = _client_streaming(monkeypatch, activity)
+ resp = client.post("/chat", json={"message": "hi"})
+ assert resp.status_code == 200
+
+ events = _sse_events(resp.text)
+ matches = [e for e in events if e.get("type") == "activity"]
+ assert matches == [activity] # every field, untouched
+
+ types = _types(events)
+ assert types.index("activity") < types.index("thinking") < types.index("chunk")
+
+
+def test_activity_event_is_not_persisted_as_an_action_chip(
+ temp_db: Path, patched_deps: None, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Guards chat.py's collector against widening to "any dict"."""
+ client = _client_streaming(monkeypatch, MCP_ACTIVITY)
+ resp = client.post("/chat", json={"message": "hi"})
+ assert resp.status_code == 200
+ _ = resp.text
+
+ with sqlite3.connect(temp_db) as conn:
+ conn.row_factory = sqlite3.Row
+ rows = [
+ dict(r)
+ for r in conn.execute(
+ "SELECT role, content, action_chips FROM chat_messages "
+ "ORDER BY id"
+ ).fetchall()
+ ]
+
+ assistant = [r for r in rows if r["role"] == "assistant"]
+ assert assistant, "assistant turn was not persisted"
+ assert assistant[-1]["content"] == "all set"
+ assert assistant[-1]["action_chips"] is None
diff --git a/packages/core/tests/unit/test_executive_activity_events.py b/packages/core/tests/unit/test_executive_activity_events.py
new file mode 100644
index 00000000..e365f9a2
--- /dev/null
+++ b/packages/core/tests/unit/test_executive_activity_events.py
@@ -0,0 +1,218 @@
+"""The agent loop names each tool round before it signals one is in flight.
+
+The chat progress line used to read "Consulting specialists…" for every tool
+round, including rounds with no specialist in them. These tests drive the real
+`_stream_agent_loop` and assert on what it yields:
+
+1. an `activity` event per tool round, immediately before the `_THINKING`
+ sentinel, naming what actually ran;
+2. a real specialist round still collapsing to the generic label, with no
+ specialist name anywhere in the event;
+3. no `activity` at all when the turn takes no tool round;
+4. a labelling failure degrading to the old behaviour rather than killing
+ the turn.
+
+Fake-provider scaffolding comes from the shared `_agent_loop_fakes` module.
+"""
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+from unittest.mock import patch
+
+from openexecutive.orchestrator import activity_labels as al
+from openexecutive.orchestrator.executive import Executive
+
+from ._agent_loop_fakes import (
+ FinalMsg,
+ ScriptedProvider,
+ TextBlock,
+ ToolUseBlock,
+)
+
+
+class _StubGateway:
+ """Minimal MCP gateway.
+
+ All three handlers are needed even for a `call_tool`-only round: the loop
+ builds its dispatch dict eagerly from every MCP tool name.
+ """
+
+ async def call_tool(self, _input: dict[str, Any]) -> str:
+ return '{"status": "ok"}'
+
+ async def search_tools(self, _input: dict[str, Any]) -> str:
+ return '{"tools": []}'
+
+ async def load_mcp_server(self, _input: dict[str, Any]) -> str:
+ return '{"status": "ok"}'
+
+
+def _run_loop(provider: ScriptedProvider, executive: Executive) -> list[Any]:
+ async def _go() -> list[Any]:
+ items: list[Any] = []
+ with patch(
+ "openexecutive.orchestrator.executive.get_provider",
+ return_value=provider,
+ ):
+ async for item in executive._stream_agent_loop(
+ system_blocks=[],
+ messages=[{"role": "user", "content": "go"}],
+ model="claude-test",
+ ):
+ items.append(item)
+ return items
+
+ return asyncio.run(_go())
+
+
+def _activities(items: list[Any]) -> list[dict[str, Any]]:
+ return [i for i in items if isinstance(i, dict) and i.get("type") == "activity"]
+
+
+def _two_turn_script(tool_block: ToolUseBlock) -> ScriptedProvider:
+ """One tool round, then a plain text turn that ends the loop."""
+ return ScriptedProvider([
+ FinalMsg([tool_block], "tool_use"),
+ FinalMsg([TextBlock("done")], "end_turn"),
+ ])
+
+
+def test_mcp_round_is_named_by_the_underlying_tool_before_thinking() -> None:
+ executive = Executive()
+ executive._mcp_gateway = _StubGateway() # type: ignore[assignment]
+ items = _run_loop(
+ _two_turn_script(
+ ToolUseBlock(
+ "toolu_1",
+ "call_tool",
+ {"name": "google_workspace__send_gmail_message", "arguments": {}},
+ )
+ ),
+ executive,
+ )
+
+ acts = _activities(items)
+ assert len(acts) == 1
+ assert acts[0]["label"] == "Using google_workspace__send_gmail_message…"
+ assert acts[0]["tool"] == "google_workspace__send_gmail_message"
+ assert acts[0]["iteration"] == 1
+ # This is the regression: an MCP round must not claim a specialist fan-out.
+ assert "specialist" not in acts[0]["label"].lower()
+ assert items.index(acts[0]) < items.index(Executive._THINKING)
+
+
+def test_specialist_round_is_generic_and_names_no_specialist() -> None:
+ executive = Executive()
+ with patch(
+ "openexecutive.orchestrator.executive.route_parallel",
+ new=_async_return(["analysis"]),
+ ):
+ items = _run_loop(
+ _two_turn_script(
+ ToolUseBlock(
+ "toolu_1",
+ "consult_specialist",
+ {"specialist": "finance", "query": "runway?"},
+ )
+ ),
+ executive,
+ )
+
+ acts = _activities(items)
+ assert len(acts) == 1
+ assert acts[0]["label"] == "Consulting specialists…"
+ assert "finance" not in " ".join(str(v) for v in acts[0].values()).lower()
+
+
+def test_no_tool_round_yields_no_activity_and_no_sentinel() -> None:
+ items = _run_loop(
+ ScriptedProvider([FinalMsg([TextBlock("hi")], "end_turn")]),
+ Executive(),
+ )
+ assert _activities(items) == []
+ assert Executive._THINKING not in items
+
+
+def test_each_round_of_a_multi_round_turn_is_named() -> None:
+ """One activity per round, each naming its own round — not the last one's."""
+ executive = Executive()
+ executive._mcp_gateway = _StubGateway() # type: ignore[assignment]
+ provider = ScriptedProvider([
+ FinalMsg([ToolUseBlock("t1", "send_slack_dm", {"user_id": "U1"})], "tool_use"),
+ FinalMsg([ToolUseBlock("t2", "list_people", {})], "tool_use"),
+ FinalMsg([TextBlock("done")], "end_turn"),
+ ])
+ items = _run_loop(provider, executive)
+
+ acts = _activities(items)
+ assert [a["label"] for a in acts] == [
+ "Sending a Slack DM…",
+ "Looking up people…",
+ ]
+ assert [a["iteration"] for a in acts] == [1, 2]
+
+
+def test_a_failed_label_mid_turn_does_not_leave_the_previous_one_standing() -> None:
+ """Every sentinel is paired with an activity, so no round inherits a label.
+
+ Without the pairing, a client that keeps the last label it saw would
+ caption round 2's work with round 1's — "Sending a Slack DM…" while a
+ people lookup runs.
+ """
+ executive = Executive()
+ provider = ScriptedProvider([
+ FinalMsg([ToolUseBlock("t1", "send_slack_dm", {"user_id": "U1"})], "tool_use"),
+ FinalMsg([ToolUseBlock("t2", "list_people", {})], "tool_use"),
+ FinalMsg([TextBlock("done")], "end_turn"),
+ ])
+
+ real = al.summarize_activity
+ calls = {"n": 0}
+
+ def _fail_second(*a: Any, **k: Any) -> Any:
+ calls["n"] += 1
+ if calls["n"] == 2:
+ raise RuntimeError("labeller exploded on round 2")
+ return real(*a, **k)
+
+ with patch(
+ "openexecutive.orchestrator.executive.summarize_activity", new=_fail_second
+ ):
+ items = _run_loop(provider, executive)
+
+ acts = _activities(items)
+ assert [a["label"] for a in acts] == ["Sending a Slack DM…", "Working…"]
+ # One activity per sentinel, always.
+ assert len(acts) == items.count(Executive._THINKING)
+
+
+def test_labelling_failure_does_not_break_the_turn() -> None:
+ """A bug in the labeller must cost the label, not the response."""
+ executive = Executive()
+ executive._mcp_gateway = _StubGateway() # type: ignore[assignment]
+
+ def _boom(*_a: Any, **_k: Any) -> dict[str, Any]:
+ raise RuntimeError("labeller exploded")
+
+ provider = _two_turn_script(
+ ToolUseBlock("toolu_1", "call_tool", {"name": "x__y", "arguments": {}})
+ )
+ with patch(
+ "openexecutive.orchestrator.executive.summarize_activity", new=_boom
+ ):
+ items = _run_loop(provider, executive)
+
+ # The label degrades to the honest fallback rather than vanishing.
+ assert [a["label"] for a in _activities(items)] == ["Working…"]
+ # The round still signals itself, and the loop still makes its follow-up
+ # model call with the tool result — the specific label is all that was lost.
+ assert Executive._THINKING in items
+ assert len(provider.calls) == 2
+
+
+def _async_return(value: Any) -> Any:
+ async def _inner(*_a: Any, **_k: Any) -> Any:
+ return value
+
+ return _inner
diff --git a/packages/ui/src/components/Chat.tsx b/packages/ui/src/components/Chat.tsx
index c53315bd..80e4a5f1 100644
--- a/packages/ui/src/components/Chat.tsx
+++ b/packages/ui/src/components/Chat.tsx
@@ -16,6 +16,7 @@ import {
ChatMessage,
CommitteePhase,
DebugEvent,
+ FALLBACK_ACTIVITY_LABEL,
getSuggestedPrompts,
streamChat,
} from "@/lib/api";
@@ -66,6 +67,7 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
// Reset on every turn; frozen onto the message at `done` event time.
const [streamingActions, setStreamingActions] = useState<ActionTaken[]>([]);
const [isConsulting, setIsConsulting] = useState(false);
+ const [activityLabel, setActivityLabel] = useState<string | null>(null);
const [committeeEnabled, setCommitteeEnabled] = useState(false);
const [committeePhase, setCommitteePhase] = useState<CommitteePhase | null>(null);
const [suggested, setSuggested] = useState<string[]>([]);
@@ -146,6 +148,7 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
setStreamingContent("");
setStreamingActions([]);
setIsConsulting(false);
+ setActivityLabel(null);
setCommitteePhase(null);
onTurnStart?.();
@@ -170,12 +173,20 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
if (item.type === "chunk" && item.content) {
accumulated += item.content;
setIsConsulting(false);
+ setActivityLabel(null);
setStreamingContent(accumulated);
+ } else if (item.type === "activity") {
+ // Arrives immediately before `thinking`, so the label is in place
+ // before the indicator turns on. Deliberately not cleared by
+ // `action_taken`: a chip can land while the same round is still
+ // running, and clearing there would flicker the line off and on.
+ setActivityLabel(item.label);
} else if (item.type === "thinking") {
setIsConsulting(true);
} else if (item.type === "phase" && item.phase) {
setCommitteePhase(item.phase);
setIsConsulting(false);
+ setActivityLabel(null);
} else if (item.type === "committee_critique") {
// Severity preview only; full critique stays server-side.
// Nothing to render yet — phase indicator already reflects the
@@ -215,6 +226,7 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
} finally {
setIsLoading(false);
setIsConsulting(false);
+ setActivityLabel(null);
setCommitteePhase(null);
textareaRef.current?.focus();
}
@@ -341,7 +353,9 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
{committeePhase ? (
<CommitteePhaseIndicator phase={committeePhase} />
) : isConsulting ? (
- <span className="text-xs text-fg-muted italic">Consulting specialists…</span>
+ <span className="text-xs text-fg-muted italic">
+ {activityLabel ?? FALLBACK_ACTIVITY_LABEL}
+ </span>
) : null}
</div>
</div>
diff --git a/packages/ui/src/components/askoe/AskOEPanel.tsx b/packages/ui/src/components/askoe/AskOEPanel.tsx
index 91565a41..3d13f72b 100644
--- a/packages/ui/src/components/askoe/AskOEPanel.tsx
+++ b/packages/ui/src/components/askoe/AskOEPanel.tsx
@@ -85,6 +85,7 @@ export default function AskOEPanel() {
const [input, setInput] = useState("");
const [streaming, setStreaming] = useState(false);
const [streamingContent, setStreamingContent] = useState("");
+ const [activityLabel, setActivityLabel] = useState<string | null>(null);
const [sessionId, setSessionId] = useState<string | undefined>(undefined);
const [error, setError] = useState<string | null>(null);
const scrollRef = useRef<HTMLDivElement>(null);
@@ -137,6 +138,7 @@ export default function AskOEPanel() {
setMessages((prev) => [...prev, { role: "user", content: trimmed }]);
setStreaming(true);
setStreamingContent("");
+ setActivityLabel(null);
let content = "";
const actions: ActionTaken[] = [];
@@ -148,7 +150,10 @@ export default function AskOEPanel() {
for await (const item of streamChat(trimmed, sessionId, { pageContext })) {
if (item.type === "chunk" && item.content) {
content += item.content;
+ setActivityLabel(null);
setStreamingContent(content);
+ } else if (item.type === "activity") {
+ setActivityLabel(item.label);
} else if (item.type === "form_patch") {
patches.push(handlePatch(item));
} else if (item.type === "action_taken") {
@@ -159,6 +164,7 @@ export default function AskOEPanel() {
setSessionId(item.session_id);
}
// thinking / phase / debug_event: no panel surface needed.
+ // `activity` is surfaced — it fills the streaming placeholder.
}
} catch (e) {
setError(e instanceof Error ? e.message : "Request failed.");
@@ -177,6 +183,7 @@ export default function AskOEPanel() {
]);
}
setStreamingContent("");
+ setActivityLabel(null);
setStreaming(false);
sendingRef.current = false;
}
@@ -214,6 +221,7 @@ export default function AskOEPanel() {
setSessionId(undefined);
setError(null);
setStreamingContent("");
+ setActivityLabel(null);
}, []);
if (!ctx.open) return null;
@@ -300,7 +308,7 @@ export default function AskOEPanel() {
{streaming && (
<Message
role="assistant"
- content={streamingContent || "…"}
+ content={streamingContent || activityLabel || "…"}
isStreaming
/>
)}
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index f4d5ae4d..b5cd21c5 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -18,6 +18,29 @@ export interface ActionTaken {
iteration?: number;
}
+// Names the round of tool calls currently in flight, so the progress line can
+// say what is actually happening. One event per tool-use iteration, emitted
+// immediately before `thinking`. Ephemeral — unlike ActionTaken it is never
+// persisted with the assistant message. Real specialist fan-out is
+// deliberately generic ("Consulting specialists…"); individual specialist
+// names are never surfaced. See backend `orchestrator/activity_labels.py`.
+// Shown when a tool round is in flight but no `activity` event named it —
+// an older backend, or the agent loop's defensive fallback when the labeller
+// itself failed. Deliberately worded the same as the backend's own
+// `FALLBACK_LABEL` in orchestrator/activity_labels.py: both mean "something is
+// running that we can't name". Nothing enforces that across the language
+// boundary, so change the two together.
+export const FALLBACK_ACTIVITY_LABEL = "Working…";
+
+export interface Activity {
+ type: "activity";
+ // Present-progressive and already ends in an ellipsis — render verbatim.
+ label: string;
+ // Canonical tool behind the label; for MCP this is the underlying tool name.
+ tool: string;
+ iteration?: number;
+}
+
export interface ChatChunk {
type:
| "chunk"
@@ -98,7 +121,12 @@ export interface FormPatch {
iteration?: number;
}
-export type StreamItem = ChatChunk | DebugEvent | ActionTaken | FormPatch;
+export type StreamItem =
+ | ChatChunk
+ | DebugEvent
+ | ActionTaken
+ | FormPatch
+ | Activity;
export interface StreamChatOptions {
committeeReview?: boolean;