Skip to content

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

feat(chat): name connected tools in plain words and collapse repeated chips (#394)

Rufus1ce8d972b3f2
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index b726b5db..5cc8a0e6 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -4456,7 +4456,7 @@ chat:
sse_event_types:
- "chunk — one text delta from the assistant response stream. Fields: type, content, 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."
+ - "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` the label comes from `orchestrator/tool_labels.py` in plain words (never the raw name) and `tool` 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."
@@ -4670,6 +4670,25 @@ chat:
audit log remains the independent durable record (every
side-effecting tool also emits a `tool_invocation` row).
+ Chips with the same summary collapse into one chip with a count
+ (`packages/ui/src/lib/actionChips.ts`); tapping a repeat, or a single
+ connected-tool chip that has a target, lists what each run looked at
+ (its `target` and `link`): a bottom sheet on a phone, a card under the
+ chips on wider screens. Saved rows from before connected tools had
+ plain names ("Called server__tool") are turned into words client-side.
+
+ connected_tool_labels: |
+ A connected (MCP) tool reaches the Executive as `call_tool` wrapping a
+ raw name like `google_workspace__search_drive_files`. Users never see
+ that name: `orchestrator/tool_labels.py` holds one table of
+ (done, doing) phrases ("Searched Drive" / "Searching Drive"), read by
+ both `action_chips` (the chip summary) and `activity_labels` (the
+ progress line), so the two always agree. An unlisted tool is turned
+ into words with its service ("Listed task lists · Google"). The chip's
+ `tool` keeps the raw name; its `target` comes from
+ `tool_labels.detail_for`: the search words, the Drive file it opened,
+ or an email subject, cleaned to one short line.
+
audit:
purpose: Persistent, searchable record of valuable events. Separate from episodic memory (which biases future LLM behaviour) — audit is for humans to inspect what the system did.
db: ./episodic_memory.db (shares the SQLite file used by episodic/alerts/cache — one file to look in)
diff --git a/packages/core/openexecutive/architecture/prebuilt/lifecycle.json b/packages/core/openexecutive/architecture/prebuilt/lifecycle.json
index a94e1798..739e326e 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 mints a `client_turn_id` and posts to `POST /chat` (`openexecutive.api.routes.chat`). The turn carries a `<current_speaker>` hint resolved from the caller's `person_id` (followed by that person's `<working_style>` rules when they have any — see the attunement section), 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, as does a `<drive_memory>` block naming the Drive files this conversation already found or opened and the Drive searches that matched nothing (see the memory section). The server registers a stop switch under that id *before* the context fetch, so a Stop pressed during those first seconds halts the turn before any model call is made.\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. The call carries the conversation so far (`Session.get_recent_history`: 20 to 30 turns, its start moving in steps of 10) with a 1h cache marker on the previous reply, so each message reads the earlier conversation from the prompt cache and writes only what is new (see Caching); on the OpenRouter path the translator keeps that marker on the reply's text.\n The person can keep typing while it works. A message sent then (`POST /chat/add`) joins the running turn: the loop adds it after the next round's tool results, so the answer follows it, and it is saved as its own message before the reply. One that arrives while the final answer is being written becomes the next turn instead. A conversation runs one turn at a time.\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. A specialist that raises (a timeout, an overloaded model) or returns no text no longer fails the batch: its tool_result says it is unavailable and tells the Executive not to invent its view, the others' results stand, and the turn goes on. It does not count as consulted, so it takes no committee seat and no department memory records the turn, and its documents are left out of the answer's sources. On the web chat the reply need not mention the gap, because the app shows it under the answer; on every other channel the tool_result asks the Executive to say in one sentence that part of the analysis is missing. A knowledge retrieval that fails likewise leaves that specialist without context rather than failing the turn.\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. Its user turn also carries a `<company_stage>` tag from the session's company profile, so stage-sensitive advice (venture benchmarks vs. cash-first for a bootstrapped company) does not depend on the Executive remembering to mention it. Once the batch is done, the documents each answering specialist's retrieval returned are named, in call order, into the turn's `TurnSources` (`orchestrator/answer_sources.py`), which the web chat route owns and which also holds its own search's documents. Synced Google Drive files are recorded as `drive` sources with their Drive link, and the web chat lists them under **Google Drive**.\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** — after the reply, every rostered speaker's turn (not only the principal's) schedules a fire-and-forget **open-loop pass** (Attunement) beside the episodic extraction: a keyword prefilter, then one forced-tool call that may open or close loops, every item quote-gated against the speaker's own words. The user message is persisted with `sender_person_id` — the resolved speaker, never the principal fallback a Discord / Telegram session uses for ownership — and the session records the speaker for the turn (`Session.caller_person_id`), which `close_open_loop` reads. A DM sent while proactive work is tagged (`attunement.outcomes.tag_proactive` — scheduler dispatch, reflection, research, alert review) also opens an outcome-ledger row at `_record_outbound_context`; a user's own turn is never tagged. Any side-effecting tool call surfaces an `action_taken` chip, which unlike the ephemeral `activity` label is persisted with the assistant message; once the reply is over — also when it was stopped or timed out — the web chat route sends one `sources` event: the documents and web pages the turn looked at (its own search, each specialist that answered, web search results, and the pages the reply cites, which are always kept) and the areas (\"finance\", never a specialist) it had to go without. The web chat shows it under the reply, and it is persisted with the assistant message as `chat_messages.sources`; other channels don't collect it. The stream closes with a `done` event — preceded by a `stopped` event when the user halted the turn, in which case the partial reply is still persisted and flagged so it reads as cut short rather than complete, and is mirrored into the live in-memory session so the next turn's prompt matches what was saved. The stream still ends with `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 one way to widen that set is `find_alerts`, for an item the principal names that has left the live board (already opened, snoozed, older than the board): a keyword search over alerts of every status whose own results — never an id the model supplies — join the trusted set. It runs only in a turn where `render_and_trust` showed the principal their own board (`Session.principal_board_shown`: the verified principal, and on a channel only in their DM), never merely because the session has a set — every `Session` starts with an empty one, and that empty set is how a Google Chat turn, someone else's DM or an unattended pass refuses every ack — and not on the principal's turn in a shared Slack or Discord thread either, where others read the reply and write into what the model reads. It trusts only rows still open (`unread`, `read`), never a roster-request card, and at most 25 ids per turn across calls, and refuses a query with no word of three or more letters. It also moves the admitted limit outward: a model argued into the wrong search can now reach up to 25 open alerts that are off the board, not only live ones. 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` — alert review, the CLI and the unattended workflows all leave it empty while legitimately recording linkage, as does the email poller under its own `email` tag. `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.\n\nThe install's workspace mode (solo or team, see Org) is read fresh at the start of each turn by `memory.workspace_settings.pin_turn_workspace_mode(session)` and pinned on the session for that turn only (`Session.turn_workspace_mode`): the persona, the org block, the tool list and every tool handler in the turn then agree, and a switch made mid-turn applies from the next turn. A session can instead carry an explicit override, `Session.workspace_mode` (`None` by default), which wins over both — so a caller that runs many conversations concurrently on one Executive, such as evals, can pick the mode per session rather than flipping the install-wide setting. Everything reads it through `effective_workspace_mode(session)` (override, then the turn's pin, then the setting). The principal's role is pinned the same way (`pin_turn_principal_role(session, mode)` → `Session.turn_principal_role`: in solo the `Session.principal_role` override, else the workspace settings read fresh; in team an empty role). The org block renders it, each specialist batch gets it as a `<principal_role>` user-turn tag, and a workflow the turn starts reads the same pin through `effective_principal_role` (override, then the pin, then the setting), so a role edited mid-turn applies from the next turn; a team turn sends none.\n\nAct as me is pinned beside them: `delegation.settings.pin_turn_delegation(session, speaker_text)` records on `Session.turn_delegation` whether the speaker has it on, whether `ghostwrite_email` is offered this turn (the principal, or a team member once the owner lets them, on a verified surface, in a conversation private to them, attended), and the speaker's own words. The pin is also held in a context variable for the turn's task, so two turns running at once on one session each read their own. The tool list, the tool handler and the turn's audit privacy all read that one pin, so a switch flipped mid-turn applies from the next turn. Once the tool touches the speaker's mailbox, the conversation is the speaker's alone (`session_store.mark_mail_private`, the principal included when it isn't theirs), the rest of the turn's audit rows are private (a team member's theirs alone) and the turn teaches no memory: no extraction, open-loop, working-style or Honcho pass runs on it.",
+ "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 mints a `client_turn_id` and posts to `POST /chat` (`openexecutive.api.routes.chat`). The turn carries a `<current_speaker>` hint resolved from the caller's `person_id` (followed by that person's `<working_style>` rules when they have any — see the attunement section), 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, as does a `<drive_memory>` block naming the Drive files this conversation already found or opened and the Drive searches that matched nothing (see the memory section). The server registers a stop switch under that id *before* the context fetch, so a Stop pressed during those first seconds halts the turn before any model call is made.\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. The call carries the conversation so far (`Session.get_recent_history`: 20 to 30 turns, its start moving in steps of 10) with a 1h cache marker on the previous reply, so each message reads the earlier conversation from the prompt cache and writes only what is new (see Caching); on the OpenRouter path the translator keeps that marker on the reply's text.\n The person can keep typing while it works. A message sent then (`POST /chat/add`) joins the running turn: the loop adds it after the next round's tool results, so the answer follows it, and it is saved as its own message before the reply. One that arrives while the final answer is being written becomes the next turn instead. A conversation runs one turn at a time.\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. A specialist that raises (a timeout, an overloaded model) or returns no text no longer fails the batch: its tool_result says it is unavailable and tells the Executive not to invent its view, the others' results stand, and the turn goes on. It does not count as consulted, so it takes no committee seat and no department memory records the turn, and its documents are left out of the answer's sources. On the web chat the reply need not mention the gap, because the app shows it under the answer; on every other channel the tool_result asks the Executive to say in one sentence that part of the analysis is missing. A knowledge retrieval that fails likewise leaves that specialist without context rather than failing the turn.\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. Its user turn also carries a `<company_stage>` tag from the session's company profile, so stage-sensitive advice (venture benchmarks vs. cash-first for a bootstrapped company) does not depend on the Executive remembering to mention it. Once the batch is done, the documents each answering specialist's retrieval returned are named, in call order, into the turn's `TurnSources` (`orchestrator/answer_sources.py`), which the web chat route owns and which also holds its own search's documents. Synced Google Drive files are recorded as `drive` sources with their Drive link, and the web chat lists them under **Google Drive**.\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 a connected (MCP) tool, plain words for what it does (\"Searching Drive…\"), from the same table (`orchestrator/tool_labels.py`) that names the finished chip (\"Searched Drive\"). The raw `server__tool` name never reaches the user. Under the reply, repeats of the same action collapse into one chip with a count, and tapping it lists what each run looked at. 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** — after the reply, every rostered speaker's turn (not only the principal's) schedules a fire-and-forget **open-loop pass** (Attunement) beside the episodic extraction: a keyword prefilter, then one forced-tool call that may open or close loops, every item quote-gated against the speaker's own words. The user message is persisted with `sender_person_id` — the resolved speaker, never the principal fallback a Discord / Telegram session uses for ownership — and the session records the speaker for the turn (`Session.caller_person_id`), which `close_open_loop` reads. A DM sent while proactive work is tagged (`attunement.outcomes.tag_proactive` — scheduler dispatch, reflection, research, alert review) also opens an outcome-ledger row at `_record_outbound_context`; a user's own turn is never tagged. Any side-effecting tool call surfaces an `action_taken` chip, which unlike the ephemeral `activity` label is persisted with the assistant message; once the reply is over — also when it was stopped or timed out — the web chat route sends one `sources` event: the documents and web pages the turn looked at (its own search, each specialist that answered, web search results, and the pages the reply cites, which are always kept) and the areas (\"finance\", never a specialist) it had to go without. The web chat shows it under the reply, and it is persisted with the assistant message as `chat_messages.sources`; other channels don't collect it. The stream closes with a `done` event — preceded by a `stopped` event when the user halted the turn, in which case the partial reply is still persisted and flagged so it reads as cut short rather than complete, and is mirrored into the live in-memory session so the next turn's prompt matches what was saved. The stream still ends with `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 one way to widen that set is `find_alerts`, for an item the principal names that has left the live board (already opened, snoozed, older than the board): a keyword search over alerts of every status whose own results — never an id the model supplies — join the trusted set. It runs only in a turn where `render_and_trust` showed the principal their own board (`Session.principal_board_shown`: the verified principal, and on a channel only in their DM), never merely because the session has a set — every `Session` starts with an empty one, and that empty set is how a Google Chat turn, someone else's DM or an unattended pass refuses every ack — and not on the principal's turn in a shared Slack or Discord thread either, where others read the reply and write into what the model reads. It trusts only rows still open (`unread`, `read`), never a roster-request card, and at most 25 ids per turn across calls, and refuses a query with no word of three or more letters. It also moves the admitted limit outward: a model argued into the wrong search can now reach up to 25 open alerts that are off the board, not only live ones. 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` — alert review, the CLI and the unattended workflows all leave it empty while legitimately recording linkage, as does the email poller under its own `email` tag. `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.\n\nThe install's workspace mode (solo or team, see Org) is read fresh at the start of each turn by `memory.workspace_settings.pin_turn_workspace_mode(session)` and pinned on the session for that turn only (`Session.turn_workspace_mode`): the persona, the org block, the tool list and every tool handler in the turn then agree, and a switch made mid-turn applies from the next turn. A session can instead carry an explicit override, `Session.workspace_mode` (`None` by default), which wins over both — so a caller that runs many conversations concurrently on one Executive, such as evals, can pick the mode per session rather than flipping the install-wide setting. Everything reads it through `effective_workspace_mode(session)` (override, then the turn's pin, then the setting). The principal's role is pinned the same way (`pin_turn_principal_role(session, mode)` → `Session.turn_principal_role`: in solo the `Session.principal_role` override, else the workspace settings read fresh; in team an empty role). The org block renders it, each specialist batch gets it as a `<principal_role>` user-turn tag, and a workflow the turn starts reads the same pin through `effective_principal_role` (override, then the pin, then the setting), so a role edited mid-turn applies from the next turn; a team turn sends none.\n\nAct as me is pinned beside them: `delegation.settings.pin_turn_delegation(session, speaker_text)` records on `Session.turn_delegation` whether the speaker has it on, whether `ghostwrite_email` is offered this turn (the principal, or a team member once the owner lets them, on a verified surface, in a conversation private to them, attended), and the speaker's own words. The pin is also held in a context variable for the turn's task, so two turns running at once on one session each read their own. The tool list, the tool handler and the turn's audit privacy all read that one pin, so a switch flipped mid-turn applies from the next turn. Once the tool touches the speaker's mailbox, the conversation is the speaker's alone (`session_store.mark_mail_private`, the principal included when it isn't theirs), the rest of the turn's audit rows are private (a team member's theirs alone) and the turn teaches no memory: no extraction, open-loop, working-style or Honcho pass runs on it.",
"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-10-03T16:56:18Z"
+ "generated_at": "2026-10-08T15:47:46Z"
}
diff --git a/packages/core/openexecutive/orchestrator/action_chips.py b/packages/core/openexecutive/orchestrator/action_chips.py
index 26ebc8b0..7059963e 100644
--- a/packages/core/openexecutive/orchestrator/action_chips.py
+++ b/packages/core/openexecutive/orchestrator/action_chips.py
@@ -20,6 +20,8 @@ from datetime import UTC, datetime
from typing import Any
from urllib.parse import quote
+from openexecutive.orchestrator import tool_labels
+
logger = logging.getLogger(__name__)
@@ -426,15 +428,17 @@ def summarize_action(
)
payload["target"] = str(alert_id) if alert_id is not None else None
elif tool_name == "call_tool":
- # MCP — the underlying tool name lives in tool_input["name"]. We
- # can't tell from here whether the underlying call was a read or a
- # write, so emit a generic chip with the tool name. Users will
- # naturally tolerate "Called google_workspace__send_gmail_message" (or
- # "Called microsoft_365__send-mail") when that's what just happened.
+ # MCP — the underlying tool name lives in tool_input["name"]. The chip
+ # names it in plain words (tool_labels) and keeps the raw name in
+ # `tool`, so the UI can collapse repeats of the same tool into one
+ # chip. `target` says what this one call looked at, for the chip's
+ # tap-to-see list.
mcp_name = tool_input.get("name", "tool")
- payload["tool"] = mcp_name # surface the real tool for UI mapping
- payload["summary"] = f"Called {mcp_name}"
- payload["target"] = mcp_name
+ payload["tool"] = mcp_name if isinstance(mcp_name, str) else "call_tool"
+ payload["summary"] = tool_labels.labels_for(mcp_name)[0]
+ payload["target"] = tool_labels.detail_for(
+ mcp_name, tool_input.get("arguments"), tool_result
+ )
elif tool_name == "send_department_message":
slug = tool_input.get("department_slug", "")
integration = tool_input.get("integration", "")
diff --git a/packages/core/openexecutive/orchestrator/activity_labels.py b/packages/core/openexecutive/orchestrator/activity_labels.py
index 624ea3cf..27b9e6a8 100644
--- a/packages/core/openexecutive/orchestrator/activity_labels.py
+++ b/packages/core/openexecutive/orchestrator/activity_labels.py
@@ -22,6 +22,8 @@ from __future__ import annotations
import re
from typing import Any
+from openexecutive.orchestrator import tool_labels
+
# 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.
@@ -34,6 +36,7 @@ SPECIALIST_LABEL = "Consulting specialists…"
# 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
+_LABEL_MAX = 60
_MCP_NAME_UNSAFE = re.compile(r"[^A-Za-z0-9_.:\- ]")
# Canonical tool name -> present-progressive phrase. Every entry ends in an
@@ -202,17 +205,25 @@ 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.
+ `action_chips.summarize_action` reads. Both take their wording from
+ `tool_labels`, so the line and the finished chip say the same thing in
+ plain words, never the raw `server__tool` name. The second element stays
+ the (sanitized) raw name so clients can still tell tools apart.
"""
raw = tool_input.get("name") if isinstance(tool_input, dict) else None
if not isinstance(raw, str):
- return "Using a connected tool…", "call_tool"
+ return f"{tool_labels.GENERIC_DOING}…", "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
+ return f"{tool_labels.GENERIC_DOING}…", "call_tool"
+ # Label from the full name: the 48-char cut is for `tool` only, and a
+ # cut name would miss the table the chip reads (and the two would differ).
+ doing = tool_labels.labels_for(raw)[1]
+ # One line beside the dots: the fallback for an unlisted tool can run
+ # long, so the whole label (ellipsis included) stays within _LABEL_MAX.
+ if len(doing) >= _LABEL_MAX:
+ doing = doing[: _LABEL_MAX - 1].rstrip()
+ return f"{doing}…", name
def _label_for(tool_use: dict[str, Any]) -> tuple[str, str]:
diff --git a/packages/core/openexecutive/orchestrator/tool_labels.py b/packages/core/openexecutive/orchestrator/tool_labels.py
new file mode 100644
index 00000000..4f4235ef
--- /dev/null
+++ b/packages/core/openexecutive/orchestrator/tool_labels.py
@@ -0,0 +1,230 @@
+"""Plain-language names for connected (MCP) tools, shared by the chat's chips
+and its progress line.
+
+A connected tool reaches the Executive as `call_tool` wrapping a raw name such
+as `google_workspace__search_drive_files` or `microsoft_365__get-mail-message`.
+Those names mean nothing to the person reading the chat, so both
+`action_chips` (the finished chip, past tense) and `activity_labels` (the
+in-flight line, present tense) read their wording from here. Keeping the two
+tenses in one table is what keeps "Searching Drive…" and "Searched Drive"
+saying the same thing.
+
+A tool missing from `_LABELS` is not shown raw: `labels_for` turns its name
+into words ("list_task_lists" on Google -> "Listed task lists · Google").
+When a connected server gains a tool people will see often, add a row here.
+
+`detail_for` names what one call looked at (the search words, the file or
+email it opened). The chat lists these when a chip is tapped, so a chip that
+collapses several runs still says what each one did.
+"""
+from __future__ import annotations
+
+import json
+import re
+from typing import Any
+
+from openexecutive.memory.drive_reads import parse_content_result
+
+# Underlying tool name (without its `server__` prefix, hyphens folded to
+# underscores) -> (done, doing). `doing` carries no ellipsis; the progress line
+# adds it. Google Workspace and Microsoft 365 names share the table: the two
+# servers do not reuse a name for different things.
+_LABELS: dict[str, tuple[str, str]] = {
+ # Mail
+ "search_gmail_messages": ("Searched your mail", "Searching your mail"),
+ "list_mail_messages": ("Searched your mail", "Searching your mail"),
+ "list_mail_folder_messages": ("Searched your mail", "Searching your mail"),
+ "get_gmail_message_content": ("Read an email", "Reading an email"),
+ "get_gmail_messages_content_batch": ("Read an email", "Reading an email"),
+ "get_gmail_thread_content": ("Read an email", "Reading an email"),
+ "get_gmail_threads_content_batch": ("Read an email", "Reading an email"),
+ "get_mail_message": ("Read an email", "Reading an email"),
+ "get_gmail_attachment_content": ("Opened an attachment", "Opening an attachment"),
+ "get_mail_attachment": ("Opened an attachment", "Opening an attachment"),
+ "list_mail_attachments": ("Checked attachments", "Checking attachments"),
+ "draft_gmail_message": ("Drafted an email", "Drafting an email"),
+ "create_draft_email": ("Drafted an email", "Drafting an email"),
+ "create_reply_draft": ("Drafted a reply", "Drafting a reply"),
+ "create_reply_all_draft": ("Drafted a reply", "Drafting a reply"),
+ "create_forward_draft": ("Drafted a forward", "Drafting a forward"),
+ "send_gmail_message": ("Sent an email", "Sending an email"),
+ "send_mail": ("Sent an email", "Sending an email"),
+ "send_draft_message": ("Sent an email", "Sending an email"),
+ "reply_mail_message": ("Sent a reply", "Sending a reply"),
+ "reply_all_mail_message": ("Sent a reply", "Sending a reply"),
+ "forward_mail_message": ("Forwarded an email", "Forwarding an email"),
+ "move_mail_message": ("Filed an email", "Filing an email"),
+ "update_mail_message": ("Updated an email", "Updating an email"),
+ "delete_mail_message": ("Deleted an email", "Deleting an email"),
+ "modify_gmail_message_labels": ("Labeled an email", "Labeling an email"),
+ "list_gmail_labels": ("Checked your mail labels", "Checking your mail labels"),
+ # Files
+ "search_drive_files": ("Searched Drive", "Searching Drive"),
+ "list_drive_items": ("Searched Drive", "Searching Drive"),
+ "get_drive_file_content": ("Read a Drive file", "Reading a Drive file"),
+ "create_drive_file": ("Saved a file to Drive", "Saving a file to Drive"),
+ "search_onedrive_files": ("Searched OneDrive", "Searching OneDrive"),
+ "list_drives": ("Checked OneDrive", "Checking OneDrive"),
+ "list_folder_files": ("Searched OneDrive", "Searching OneDrive"),
+ "get_drive_item": ("Read a OneDrive file", "Reading a OneDrive file"),
+ "download_onedrive_file_content": ("Read a OneDrive file", "Reading a OneDrive file"),
+ "upload_file_content": ("Saved a file to OneDrive", "Saving a file to OneDrive"),
+ "copy_drive_item": ("Copied a file", "Copying a file"),
+ "move_rename_onedrive_item": ("Moved a file", "Moving a file"),
+ "share_drive_item": ("Shared a file", "Sharing a file"),
+ # Docs and sheets
+ "search_docs": ("Searched your docs", "Searching your docs"),
+ "get_doc_content": ("Read a doc", "Reading a doc"),
+ "create_doc": ("Created a doc", "Creating a doc"),
+ "modify_doc_text": ("Edited a doc", "Editing a doc"),
+ "read_sheet_values": ("Read a spreadsheet", "Reading a spreadsheet"),
+ "get_spreadsheet_info": ("Read a spreadsheet", "Reading a spreadsheet"),
+ "list_spreadsheets": ("Searched your spreadsheets", "Searching your spreadsheets"),
+ "modify_sheet_values": ("Updated a spreadsheet", "Updating a spreadsheet"),
+ "create_spreadsheet": ("Created a spreadsheet", "Creating a spreadsheet"),
+ # Calendar
+ "list_calendars": ("Checked your calendar", "Checking your calendar"),
+ "get_events": ("Checked your calendar", "Checking your calendar"),
+ "list_calendar_events": ("Checked your calendar", "Checking your calendar"),
+ "get_calendar_event": ("Checked your calendar", "Checking your calendar"),
+ "get_calendar_view": ("Checked your calendar", "Checking your calendar"),
+ "query_freebusy": ("Checked availability", "Checking availability"),
+ "find_meeting_times": ("Checked availability", "Checking availability"),
+ "manage_event": ("Updated your calendar", "Updating your calendar"),
+ "create_calendar_event": ("Updated your calendar", "Updating your calendar"),
+ "update_calendar_event": ("Updated your calendar", "Updating your calendar"),
+ "update_specific_calendar_event": ("Updated your calendar", "Updating your calendar"),
+ "delete_calendar_event": ("Removed a calendar event", "Removing a calendar event"),
+ "accept_calendar_event": ("Answered an invite", "Answering an invite"),
+ "decline_calendar_event": ("Answered an invite", "Answering an invite"),
+ "tentatively_accept_calendar_event": ("Answered an invite", "Answering an invite"),
+ "forward_calendar_event": ("Forwarded an invite", "Forwarding an invite"),
+}
+
+# Server prefix -> the name people know it by, for the fallback's suffix.
+_SERVICES: dict[str, str] = {
+ "google_workspace": "Google",
+ "microsoft_365": "Microsoft 365",
+ "oe": "Open Executive",
+}
+
+# First word of an unlisted tool -> (done, doing) verb for the fallback.
+_VERBS: dict[str, tuple[str, str]] = {
+ "search": ("Searched", "Searching"),
+ "find": ("Looked up", "Looking up"),
+ "query": ("Looked up", "Looking up"),
+ "get": ("Read", "Reading"),
+ "read": ("Read", "Reading"),
+ "fetch": ("Read", "Reading"),
+ "download": ("Read", "Reading"),
+ "list": ("Listed", "Listing"),
+ "create": ("Created", "Creating"),
+ "add": ("Added", "Adding"),
+ "update": ("Updated", "Updating"),
+ "modify": ("Updated", "Updating"),
+ "edit": ("Edited", "Editing"),
+ "set": ("Updated", "Updating"),
+ "delete": ("Deleted", "Deleting"),
+ "remove": ("Removed", "Removing"),
+ "send": ("Sent", "Sending"),
+ "reply": ("Replied to", "Replying to"),
+ "forward": ("Forwarded", "Forwarding"),
+ "draft": ("Drafted", "Drafting"),
+ "move": ("Moved", "Moving"),
+ "share": ("Shared", "Sharing"),
+ "upload": ("Uploaded", "Uploading"),
+ "copy": ("Copied", "Copying"),
+}
+
+GENERIC_DONE = "Used a connected tool"
+GENERIC_DOING = "Using a connected tool"
+
+# Tool names and argument values are model- or server-authored text on their
+# way to the DOM: keep them to one short, plain line.
+_WORDS_MAX = 40
+_DETAIL_MAX = 60
+_UNSAFE = re.compile(r"[^\w .,:;'&@()/#+-]", re.UNICODE)
+
+# Argument keys that name what a call looked for or at, most telling first.
+_DETAIL_KEYS = (
+ "query", "q", "search", "search_query", "subject", "title",
+ "file_name", "filename", "name", "summary",
+)
+_SUBJECT_RE = re.compile(r"^Subject:[ \t]*(.+)$", re.MULTILINE)
+# The tools whose result is one email, the only ones a subject is read from.
+_MAIL_READS = frozenset({
+ "get_gmail_message_content",
+ "get_gmail_thread_content",
+ "get_mail_message",
+})
+# Larger results are not parsed just to find a subject.
+_JSON_MAX = 200_000
+
+
+def _split(raw: str) -> tuple[str, str]:
+ """`server__tool` -> (server, normalized tool)."""
+ server, sep, tool = raw.partition("__")
+ if not sep:
+ server, tool = "", raw
+ return server, tool.replace("-", "_").lower()
+
+
+def _clean(text: str, limit: int) -> str:
+ text = _UNSAFE.sub("", " ".join(text.split())).strip()
+ return text if len(text) <= limit else text[: limit - 1].rstrip() + "…"
+
+
+def labels_for(raw_name: Any) -> tuple[str, str]:
+ """(done, doing) phrases for an MCP tool name. Never returns the raw name."""
+ if not isinstance(raw_name, str) or not raw_name.strip():
+ return GENERIC_DONE, GENERIC_DOING
+ server, tool = _split(raw_name.strip())
+ if tool in _LABELS:
+ return _LABELS[tool]
+ words = [w for w in tool.split("_") if w]
+ if not words:
+ return GENERIC_DONE, GENERIC_DOING
+ verb = _VERBS.get(words[0])
+ rest = " ".join(words[1:] if verb else words)
+ rest = _clean(rest, _WORDS_MAX)
+ service = _SERVICES.get(server) or _clean(server.replace("_", " ").title(), 24)
+ suffix = f" · {service}" if service else ""
+ if verb and rest:
+ return f"{verb[0]} {rest}{suffix}", f"{verb[1]} {rest}{suffix}"
+ if rest:
+ return f"Used {rest}{suffix}", f"Using {rest}{suffix}"
+ return GENERIC_DONE, GENERIC_DOING
+
+
+def detail_for(raw_name: Any, arguments: Any, result: str) -> str | None:
+ """What one call looked at, in a few words, or None when nothing says."""
+ _, tool = _split(raw_name) if isinstance(raw_name, str) else ("", "")
+ if tool == "get_drive_file_content":
+ opened = parse_content_result(result) if isinstance(result, str) else None
+ if opened and opened.get("name"):
+ return _clean(opened["name"], _DETAIL_MAX) or None
+ if isinstance(arguments, dict):
+ for key in _DETAIL_KEYS:
+ value = arguments.get(key)
+ if isinstance(value, str) and value.strip():
+ cleaned = _clean(value, _DETAIL_MAX)
+ if cleaned:
+ return f'"{cleaned}"' if key in ("query", "q", "search", "search_query") else cleaned
+ if tool in _MAIL_READS and isinstance(result, str) and result:
+ # Only an email's own header block names it: a "Subject:" line in a
+ # body or forwarded text must not become the chip's target.
+ header = result[:4000].split("\n\n", 1)[0]
+ m = _SUBJECT_RE.search(header)
+ if m:
+ return _clean(m.group(1), _DETAIL_MAX) or None
+ parsed = None
+ if len(result) <= _JSON_MAX:
+ try:
+ parsed = json.loads(result)
+ except (ValueError, TypeError):
+ parsed = None
+ if isinstance(parsed, dict):
+ value = parsed.get("subject")
+ if isinstance(value, str) and value.strip():
+ return _clean(value, _DETAIL_MAX) or None
+ return None
diff --git a/packages/core/tests/unit/test_action_chips.py b/packages/core/tests/unit/test_action_chips.py
index daeb091e..ce5f1dbd 100644
--- a/packages/core/tests/unit/test_action_chips.py
+++ b/packages/core/tests/unit/test_action_chips.py
@@ -261,7 +261,8 @@ def test_call_tool_chip_uses_underlying_name() -> None:
assert chip is not None
# `tool` field reflects the actual MCP tool, not "call_tool" — UI can map.
assert chip["tool"] == "google_workspace__send_gmail_message"
- assert "google_workspace__send_gmail_message" in chip["summary"]
+ # The chip reads in plain words, never the raw server__tool name.
+ assert chip["summary"] == "Sent an email"
# ---------------------------------------------------------------------------
diff --git a/packages/core/tests/unit/test_activity_labels.py b/packages/core/tests/unit/test_activity_labels.py
index 2446aeb5..38f058b2 100644
--- a/packages/core/tests/unit/test_activity_labels.py
+++ b/packages/core/tests/unit/test_activity_labels.py
@@ -146,7 +146,7 @@ def test_mcp_call_tool_uses_the_underlying_tool_name() -> None:
[_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["label"] == "Sending an email…"
assert evt["tool"] == "google_workspace__send_gmail_message"
diff --git a/packages/core/tests/unit/test_chat_route_activity_events.py b/packages/core/tests/unit/test_chat_route_activity_events.py
index 68d5758c..87e90be0 100644
--- a/packages/core/tests/unit/test_chat_route_activity_events.py
+++ b/packages/core/tests/unit/test_chat_route_activity_events.py
@@ -26,7 +26,7 @@ from openexecutive.memory.company_profile import CompanyProfile
MCP_ACTIVITY: dict[str, Any] = {
"type": "activity",
- "label": "Using google_workspace__send_gmail_message…",
+ "label": "Sending an email…",
"tool": "google_workspace__send_gmail_message",
"iteration": 1,
}
diff --git a/packages/core/tests/unit/test_executive_activity_events.py b/packages/core/tests/unit/test_executive_activity_events.py
index e365f9a2..0668d277 100644
--- a/packages/core/tests/unit/test_executive_activity_events.py
+++ b/packages/core/tests/unit/test_executive_activity_events.py
@@ -94,7 +94,7 @@ def test_mcp_round_is_named_by_the_underlying_tool_before_thinking() -> None:
acts = _activities(items)
assert len(acts) == 1
- assert acts[0]["label"] == "Using google_workspace__send_gmail_message…"
+ assert acts[0]["label"] == "Sending an email…"
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.
diff --git a/packages/core/tests/unit/test_tool_labels.py b/packages/core/tests/unit/test_tool_labels.py
new file mode 100644
index 00000000..11c516ac
--- /dev/null
+++ b/packages/core/tests/unit/test_tool_labels.py
@@ -0,0 +1,141 @@
+"""Plain-language names for connected tools (orchestrator/tool_labels.py)."""
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from openexecutive.orchestrator import tool_labels
+from openexecutive.orchestrator.action_chips import summarize_action
+from openexecutive.orchestrator.activity_labels import summarize_activity
+
+
+ ("raw", "done", "doing"),
+ [
+ ("google_workspace__search_drive_files", "Searched Drive", "Searching Drive"),
+ ("google_workspace__get_drive_file_content", "Read a Drive file", "Reading a Drive file"),
+ ("google_workspace__search_gmail_messages", "Searched your mail", "Searching your mail"),
+ ("microsoft_365__get-mail-message", "Read an email", "Reading an email"),
+ ("microsoft_365__list-calendar-events", "Checked your calendar", "Checking your calendar"),
+ ("google_workspace__manage_event", "Updated your calendar", "Updating your calendar"),
+ ],
+)
+def test_known_tools_read_in_plain_words(raw: str, done: str, doing: str) -> None:
+ assert tool_labels.labels_for(raw) == (done, doing)
+
+
+def test_unlisted_tool_is_turned_into_words_with_its_service() -> None:
+ assert tool_labels.labels_for("google_workspace__list_task_lists") == (
+ "Listed task lists · Google",
+ "Listing task lists · Google",
+ )
+
+
+def test_unlisted_tool_without_a_known_verb_says_used() -> None:
+ done, doing = tool_labels.labels_for("acme_crm__pipeline_snapshot")
+ assert done == "Used pipeline snapshot · Acme Crm"
+ assert doing == "Using pipeline snapshot · Acme Crm"
+
+
[email protected]("bad", [None, 42, "", " ", "__"])
+def test_unusable_names_fall_back_to_a_generic_phrase(bad: object) -> None:
+ assert tool_labels.labels_for(bad) == (
+ tool_labels.GENERIC_DONE,
+ tool_labels.GENERIC_DOING,
+ )
+
+
+def test_every_label_hides_the_raw_name() -> None:
+ for done, doing in tool_labels._LABELS.values():
+ for phrase in (done, doing):
+ assert "_" not in phrase and "__" not in phrase
+ assert phrase[0].isupper() and not phrase.endswith("…")
+
+
+def test_detail_is_the_search_words_in_quotes() -> None:
+ detail = tool_labels.detail_for(
+ "google_workspace__search_drive_files", {"query": "harbor point lpa"}, "Found 2 files"
+ )
+ assert detail == '"harbor point lpa"'
+
+
+def test_detail_names_the_drive_file_that_was_opened() -> None:
+ result = (
+ 'File: "Harbor Point LPA.pdf" (ID: abc123, Type: application/pdf)\n'
+ "Link: https://drive.google.com/file/d/abc123/view\n\n--- CONTENT ---\nText"
+ )
+ detail = tool_labels.detail_for(
+ "google_workspace__get_drive_file_content", {"file_id": "abc123"}, result
+ )
+ assert detail == "Harbor Point LPA.pdf"
+
+
+def test_detail_reads_an_email_subject_from_the_result() -> None:
+ result = "Message ID: 1\nSubject: Q3 reserve policy\nFrom: [email protected]\n\nBody"
+ detail = tool_labels.detail_for(
+ "google_workspace__get_gmail_message_content", {"message_id": "1"}, result
+ )
+ assert detail == "Q3 reserve policy"
+
+
+def test_detail_reads_a_subject_from_a_json_result() -> None:
+ detail = tool_labels.detail_for(
+ "microsoft_365__get-mail-message", {"messageId": "1"}, json.dumps({"subject": "Budget"})
+ )
+ assert detail == "Budget"
+
+
+def test_detail_is_one_short_clean_line() -> None:
+ detail = tool_labels.detail_for(
+ "x__search", {"query": "<script>\nalert(1)</script> " + "y" * 200}, ""
+ )
+ assert detail is not None
+ assert "<" not in detail and ">" not in detail and "\n" not in detail
+ assert len(detail) <= 62 # 60 plus the quotes
+
+
+def test_detail_is_none_when_nothing_names_the_target() -> None:
+ assert tool_labels.detail_for("x__get_thing", {"id": "1"}, "ok") is None
+
+
+def test_chip_and_progress_line_agree() -> None:
+ tool_input = {"name": "google_workspace__search_drive_files", "arguments": {"query": "lpa"}}
+ chip = summarize_action(tool_name="call_tool", tool_input=tool_input, tool_result="Found 1 files")
+ activity = summarize_activity([{"id": "t", "name": "call_tool", "input": tool_input}])
+ assert chip is not None and activity is not None
+ assert chip["summary"] == "Searched Drive"
+ assert chip["target"] == '"lpa"'
+ assert chip["tool"] == "google_workspace__search_drive_files"
+ assert activity["label"] == "Searching Drive…"
+
+
+def test_long_tool_names_still_agree_between_chip_and_line() -> None:
+ raw = "google_workspace__get_gmail_messages_content_batch"
+ assert len(raw) > 48 # longer than the progress line's `tool` cap
+ tool_input = {"name": raw, "arguments": {}}
+ chip = summarize_action(tool_name="call_tool", tool_input=tool_input, tool_result="ok")
+ activity = summarize_activity([{"id": "t", "name": "call_tool", "input": tool_input}])
+ assert chip is not None and activity is not None
+ assert chip["summary"] == "Read an email"
+ assert activity["label"] == "Reading an email…"
+
+
+def test_a_subject_line_in_a_body_is_not_the_target() -> None:
+ result = "Message ID: 1\nFrom: [email protected]\n\nFwd:\nSubject: Wire transfer approved"
+ assert tool_labels.detail_for(
+ "google_workspace__get_gmail_message_content", {"message_id": "1"}, result
+ ) is None
+
+
+def test_a_subject_is_read_only_from_mail_tools() -> None:
+ result = "Subject: Wire transfer approved\n\nbody"
+ assert tool_labels.detail_for("google_workspace__get_doc_content", {"document_id": "d"}, result) is None
+
+
+def test_a_long_unlisted_tool_keeps_the_progress_line_short() -> None:
+ raw = "microsoft_365__list-" + "very-long-resource-name-" * 3
+ activity = summarize_activity([{"id": "t", "name": "call_tool", "input": {"name": raw}}])
+ assert activity is not None
+ assert len(activity["label"]) <= 60
+ assert activity["label"].endswith("…")
diff --git a/packages/ui/scripts/actionChips.test.mjs b/packages/ui/scripts/actionChips.test.mjs
new file mode 100644
index 00000000..8f581309
--- /dev/null
+++ b/packages/ui/scripts/actionChips.test.mjs
@@ -0,0 +1,66 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { chipSummary, groupActions, opensDetails } from "../src/lib/actionChips.ts";
+
+const drive = (target) => ({
+ tool: "google_workspace__search_drive_files",
+ summary: "Searched Drive",
+ target,
+});
+
+test("repeats of the same action collapse into one chip, in first-seen order", () => {
+ const groups = groupActions([
+ drive('"harbor point lpa"'),
+ { tool: "google_workspace__get_drive_file_content", summary: "Read a Drive file", target: "LPA.pdf" },
+ drive('"cash reserve"'),
+ ]);
+ assert.deepEqual(
+ groups.map((g) => [g.summary, g.runs.length]),
+ [["Searched Drive", 2], ["Read a Drive file", 1]],
+ );
+ assert.deepEqual(
+ groups[0].runs.map((r) => r.target),
+ ['"harbor point lpa"', '"cash reserve"'],
+ );
+});
+
+test("built-in actions with different wording stay separate chips", () => {
+ const groups = groupActions([
+ { tool: "create_alert", summary: "Flagged alert: churn risk" },
+ { tool: "create_alert", summary: "Flagged alert: late invoice" },
+ ]);
+ assert.equal(groups.length, 2);
+});
+
+test("an old raw tool name reads as words", () => {
+ assert.equal(
+ chipSummary("Called google_workspace__search_drive_files"),
+ "Used search drive files",
+ );
+ assert.equal(chipSummary("Called microsoft_365__get-mail-message"), "Used get mail message");
+ assert.equal(chipSummary("Sent an email"), "Sent an email");
+ const groups = groupActions([
+ { tool: "google_workspace__search_drive_files", summary: "Called google_workspace__search_drive_files" },
+ { tool: "google_workspace__search_drive_files", summary: "Called google_workspace__search_drive_files" },
+ ]);
+ assert.deepEqual(groups.map((g) => [g.summary, g.runs.length]), [["Used search drive files", 2]]);
+});
+
+test("a chip opens its list for a repeat or a connected tool with a target", () => {
+ const [repeat] = groupActions([drive("a"), drive("b")]);
+ assert.equal(opensDetails(repeat), true);
+ const [single] = groupActions([drive('"lpa"')]);
+ assert.equal(opensDetails(single), true);
+ const [bare] = groupActions([drive(null)]);
+ assert.equal(opensDetails(bare), false);
+ const [builtIn] = groupActions([{ tool: "create_alert", summary: "Flagged alert: x", target: "x" }]);
+ assert.equal(opensDetails(builtIn), false);
+ const [linked] = groupActions([{ ...drive("x"), link: "/artifacts" }]);
+ assert.equal(opensDetails(linked), false);
+});
+
+test("a repeat with nothing to list stays a plain chip with its count", () => {
+ const [bare] = groupActions([drive(null), drive(null), drive(null)]);
+ assert.equal(bare.runs.length, 3);
+ assert.equal(opensDetails(bare), false);
+});
diff --git a/packages/ui/src/components/Message.tsx b/packages/ui/src/components/Message.tsx
index 59b13ad6..5cdd194d 100644
--- a/packages/ui/src/components/Message.tsx
+++ b/packages/ui/src/components/Message.tsx
@@ -1,6 +1,6 @@
"use client";
-import type { ReactNode } from "react";
+import { useEffect, useMemo, useState, type ReactNode } from "react";
import Link from "next/link";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
@@ -8,6 +8,7 @@ import AnswerSourcesFooter from "@/components/AnswerSourcesFooter";
import BrandMark from "@/components/BrandMark";
import type { AnswerSources } from "@/lib/answerSources";
import type { ActionTaken } from "@/lib/api";
+import { groupActions, opensDetails, type ChipGroup } from "@/lib/actionChips";
import { loadsInline } from "@/lib/markdownImages";
import { isMailboxLink } from "@/lib/replyCards";
import { hostOf } from "@/lib/url";
@@ -80,36 +81,146 @@ function FeedbackButtons({
);
}
-function ActionChip({ action }: { action: ActionTaken }) {
- const inner = (
+function ChipBody({ summary, count }: { summary: string; count: number }) {
+ return (
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] bg-emerald-500/10 border border-emerald-500/30 text-emerald-300">
<span aria-hidden="true" className="text-[10px]">✓</span>
- <span>{action.summary}</span>
+ <span>{summary}</span>
+ {count > 1 && (
+ <span className="rounded-full bg-emerald-400/20 px-1.5 font-semibold tabular-nums">
+ ×{count}
+ </span>
+ )}
</span>
);
- if (action.link) {
- // A draft in your own mailbox (Act as me) opens in a new tab; every other
- // chip links inside the app.
- if (isMailboxLink(action.link)) {
- return (
- <a
- href={action.link}
- target="_blank"
- rel="noopener noreferrer"
- className="inline-flex items-center gap-1.5 hover:opacity-80 transition-opacity"
- >
- <FeatureName feature="act_as_me" className="text-[11px]" />
- {inner}
- </a>
- );
- }
+}
+
+function ChipLink({ link, children }: { link: string; children: ReactNode }) {
+ // A draft in your own mailbox (Act as me) opens in a new tab; every other
+ // chip links inside the app.
+ if (isMailboxLink(link)) {
return (
- <Link href={action.link} className="hover:opacity-80 transition-opacity">
- {inner}
- </Link>
+ <a
+ href={link}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex items-center gap-1.5 hover:opacity-80 transition-opacity"
+ >
+ <FeatureName feature="act_as_me" className="text-[11px]" />
+ {children}
+ </a>
);
}
- return inner;
+ return (
+ <Link href={link} className="hover:opacity-80 transition-opacity">
+ {children}
+ </Link>
+ );
+}
+
+// What each run of a chip looked at. A bottom sheet on a phone, a card under
+// the chips from the tablet breakpoint up.
+function ChipDetails({ group, onClose }: { group: ChipGroup; onClose: () => void }) {
+ const count = group.runs.length;
+ const rows = group.runs.filter((run) => run.target || run.link);
+ return (
+ <>
+ <div
+ aria-hidden="true"
+ onClick={onClose}
+ className="fixed inset-0 z-40 bg-black/40 sm:hidden"
+ />
+ <div
+ role="dialog"
+ aria-label={group.summary}
+ className="fixed inset-x-0 bottom-0 z-50 rounded-t-2xl border-t border-border bg-surface-elevated p-4 pb-[calc(1rem+env(safe-area-inset-bottom,0px))] shadow-2xl sm:static sm:z-auto sm:mt-2 sm:max-w-sm sm:rounded-xl sm:border sm:p-3 sm:shadow-lg"
+ >
+ <div aria-hidden="true" className="mx-auto mb-3 h-1 w-10 rounded-full bg-fg-muted/40 sm:hidden" />
+ <div className="flex items-center justify-between gap-3">
+ <p className="text-sm font-semibold text-fg">
+ {group.summary}
+ {count > 1 && <span className="font-normal text-fg-muted"> · {count} times</span>}
+ </p>
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label="Close"
+ className="min-h-[2rem] min-w-[2rem] rounded-md text-fg-muted hover:text-fg"
+ >
+ ✕
+ </button>
+ </div>
+ {rows.length > 0 && (
+ <ul className="mt-2 divide-y divide-border text-sm">
+ {rows.map((run, i) => (
+ <li key={i} className="py-2 break-words">
+ {run.link ? (
+ <ChipLink link={run.link}>
+ <span className="text-accent">{run.target || "Open"}</span>
+ </ChipLink>
+ ) : (
+ <span className="text-fg">{run.target}</span>
+ )}
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ </>
+ );
+}
+
+function ActionChips({ actions }: { actions: ActionTaken[] }) {
+ const groups = useMemo(() => groupActions(actions), [actions]);
+ const [open, setOpen] = useState<string | null>(null);
+ const openGroup = groups.find((g) => g.key === open) ?? null;
+
+ useEffect(() => {
+ if (!open) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") setOpen(null);
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [open]);
+
+ return (
+ <div className="mt-3">
+ <div
+ className="flex flex-wrap gap-1.5"
+ aria-label={`${actions.length} action${actions.length === 1 ? "" : "s"} taken`}
+ >
+ {groups.map((group) => {
+ const body = <ChipBody summary={group.summary} count={group.runs.length} />;
+ if (opensDetails(group)) {
+ const isOpen = open === group.key;
+ return (
+ <button
+ key={group.key}
+ type="button"
+ aria-expanded={isOpen}
+ onClick={() => setOpen(isOpen ? null : group.key)}
+ className={`rounded-full transition-opacity hover:opacity-80 ${
+ isOpen ? "ring-2 ring-emerald-400/70 ring-offset-1 ring-offset-surface" : ""
+ }`}
+ >
+ {body}
+ </button>
+ );
+ }
+ const link = group.runs[0]?.link;
+ return link ? (
+ <ChipLink key={group.key} link={link}>
+ {body}
+ </ChipLink>
+ ) : (
+ <span key={group.key}>{body}</span>
+ );
+ })}
+ </div>
+ {openGroup && <ChipDetails group={openGroup} onClose={() => setOpen(null)} />}
+ </div>
+ );
}
export default function Message({
@@ -178,16 +289,7 @@ export default function Message({
{status && <div className="mt-3">{status}</div>}
- {actions && actions.length > 0 && (
- <div
- className="mt-3 flex flex-wrap gap-1.5"
- aria-label={`${actions.length} action${actions.length === 1 ? "" : "s"} taken`}
- >
- {actions.map((action, i) => (
- <ActionChip key={`${action.tool}-${i}`} action={action} />
- ))}
- </div>
- )}
+ {actions && actions.length > 0 && <ActionChips actions={actions} />}
{sources && !isStreaming && <AnswerSourcesFooter sources={sources} />}
diff --git a/packages/ui/src/lib/actionChips.ts b/packages/ui/src/lib/actionChips.ts
new file mode 100644
index 00000000..4a7a845d
--- /dev/null
+++ b/packages/ui/src/lib/actionChips.ts
@@ -0,0 +1,71 @@
+// The chips under a chat reply (`action_taken` events): repeats of the same
+// action collapse into one chip with a count, and a chip can list what each
+// run looked at. Kept apart from the component so `npm test` can check it
+// (see scripts/actionChips.test.mjs). The wording comes from the backend
+// (orchestrator/action_chips.py and tool_labels.py); this file only groups.
+
+export interface ChipAction {
+ tool: string;
+ summary: string;
+ target?: string | null;
+ link?: string | null;
+}
+
+export interface ChipRun {
+ target: string | null;
+ link: string | null;
+}
+
+export interface ChipGroup {
+ key: string;
+ tool: string;
+ summary: string;
+ runs: ChipRun[];
+}
+
+// Replies saved before connected tools had plain names carry
+// "Called google_workspace__search_drive_files". Show those as words too.
+const LEGACY_CALLED = /^Called ([A-Za-z0-9_.-]+__[A-Za-z0-9_.-]+)$/;
+
+/** The chip's wording, with an old raw tool name turned into words. */
+export function chipSummary(summary: string): string {
+ const m = LEGACY_CALLED.exec(summary);
+ if (!m) return summary;
+ const tool = m[1].slice(m[1].indexOf("__") + 2);
+ const words = tool.replace(/[_-]+/g, " ").trim();
+ return words ? `Used ${words}` : "Used a connected tool";
+}
+
+/** One chip per distinct wording, in the order each first appeared. */
+export function groupActions(actions: ChipAction[]): ChipGroup[] {
+ const groups = new Map<string, ChipGroup>();
+ for (const action of actions) {
+ const summary = chipSummary(action.summary);
+ let group = groups.get(summary);
+ if (!group) {
+ group = { key: summary, tool: action.tool, summary, runs: [] };
+ groups.set(summary, group);
+ }
+ group.runs.push({ target: action.target || null, link: action.link || null });
+ }
+ return Array.from(groups.values());
+}
+
+/** A connected tool's raw name has a `server__` prefix; built-in tools don't. */
+function isConnectedTool(tool: string): boolean {
+ return tool.includes("__");
+}
+
+/**
+ * Whether tapping the chip opens the list of runs. A repeat does when some
+ * run has a target or link to show. A single built-in action already says
+ * what it did in its own words (and may link somewhere), so only a single
+ * connected-tool run with a target opens.
+ */
+export function opensDetails(group: ChipGroup): boolean {
+ // A list with nothing in it would only repeat the count.
+ if (!group.runs.some((run) => run.target || run.link)) return false;
+ if (group.runs.length > 1) return true;
+ const run = group.runs[0];
+ return !!run && !run.link && !!run.target && isConnectedTool(group.tool);
+}