Skip to content

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

feat(chat): suggest a follow-up in the composer (#182)

Rufus7f7c1c1e2304
diff --git a/packages/core/openexecutive/api/routes/chat.py b/packages/core/openexecutive/api/routes/chat.py
index 919fe41d..0b906290 100644
--- a/packages/core/openexecutive/api/routes/chat.py
+++ b/packages/core/openexecutive/api/routes/chat.py
@@ -1419,18 +1419,14 @@ def _cache_key(
return hashlib.md5(raw.encode("utf-8")).hexdigest()
-async def _generate_prompts_via_llm(
- user_content: str,
-) -> tuple[list[str], str] | None:
- """Returns (prompts, subtitle) on success, None on any failure.
+async def _fast_json_call(
+ system: str, user_content: str, max_tokens: int, log_tag: str
+) -> dict[str, Any] | None:
+ """One utility-fast call that must answer with a JSON object.
- Both fields must validate: prompts >= 4 non-empty strings, subtitle a
- non-empty string. Any short-fall returns None so the caller can fall
- back rather than render a half-broken empty state.
+ Returns the parsed object, or None on any failure (timeout, API error,
+ malformed or non-object JSON) — callers fall back rather than raise.
"""
- import asyncio
- import json as _json
-
from openexecutive.agents.utility_fast import get_fast_model
from openexecutive.config import get_settings
from openexecutive.providers import get_provider
@@ -1440,8 +1436,8 @@ async def _generate_prompts_via_llm(
response = await asyncio.wait_for(
get_provider(model).messages_create(
model=model,
- max_tokens=500,
- system=_PROMPTS_SYSTEM,
+ max_tokens=max_tokens,
+ system=system,
messages=[{"role": "user", "content": user_content}],
),
timeout=get_settings().utility_fast_timeout_s,
@@ -1455,21 +1451,91 @@ async def _generate_prompts_via_llm(
parts = raw.split("```")
if len(parts) >= 2:
raw = parts[1].removeprefix("json").strip()
- data = _json.loads(raw)
- if not isinstance(data, dict):
- return None
- prompts_raw = data.get("prompts")
- subtitle_raw = data.get("subtitle")
- if not isinstance(prompts_raw, list) or not isinstance(subtitle_raw, str):
- return None
- prompts = [str(p).strip() for p in prompts_raw if isinstance(p, str) and p.strip()]
- subtitle = subtitle_raw.strip()
- if len(prompts) < 4 or not subtitle:
- return None
- return prompts[:4], subtitle
+ data = json.loads(raw)
except Exception:
- logger.exception("suggested_prompts: LLM call failed")
+ logger.exception("%s: LLM call failed", log_tag)
+ return None
+ return data if isinstance(data, dict) else None
+
+
+async def _generate_prompts_via_llm(
+ user_content: str,
+) -> tuple[list[str], str] | None:
+ """Returns (prompts, subtitle) on success, None on any failure.
+
+ Both fields must validate: prompts >= 4 non-empty strings, subtitle a
+ non-empty string. Any short-fall returns None so the caller can fall
+ back rather than render a half-broken empty state.
+ """
+ data = await _fast_json_call(_PROMPTS_SYSTEM, user_content, 500, "suggested_prompts")
+ if data is None:
+ return None
+ prompts_raw = data.get("prompts")
+ subtitle_raw = data.get("subtitle")
+ if not isinstance(prompts_raw, list) or not isinstance(subtitle_raw, str):
+ return None
+ prompts = [str(p).strip() for p in prompts_raw if isinstance(p, str) and p.strip()]
+ subtitle = subtitle_raw.strip()
+ if len(prompts) < 4 or not subtitle:
+ return None
+ return prompts[:4], subtitle
+
+
+# ---------------------------------------------------------------------------
+# Suggested follow-up for the chat composer, shown after each reply.
+# ---------------------------------------------------------------------------
+
+_FOLLOWUP_SYSTEM = (
+ "You suggest the user's next message in a conversation with their "
+ "virtual executive — a peer on their executive team who helps them "
+ "think, decide, draft, prioritize, and pull the right people in.\n\n"
+ "Read the transcript and write the ONE message the user would most "
+ "naturally send next, in the user's own voice (first person, "
+ "addressed to the executive). Build on the executive's last reply: "
+ "take the obvious next step it opens up — go deeper on one point, "
+ "act on a recommendation, get a draft, pressure-test a claim, or "
+ "decide between options it laid out. Name the concrete thing "
+ "(the person, metric, draft, or decision) rather than saying 'this' "
+ "or 'that'. Never repeat a question the user already asked. Never "
+ "suggest looping in, messaging, or following up with the user "
+ "themselves.\n\n"
+ "Output ONLY a JSON object with exactly one key — no prose, no "
+ "markdown, no fences:\n"
+ ' "suggestion": one sentence, 4-14 words, no greeting, no '
+ "exclamation marks, ending with a period or question mark."
+)
+
+# Per-message budget when building the transcript. The follow-up only
+# needs the thread's gist, and the reply being followed up on can be long.
+_FOLLOWUP_MAX_MESSAGES = 6
+_FOLLOWUP_MAX_CHARS_PER_MESSAGE = 1500
+_FOLLOWUP_MAX_WORDS = 24
+
+
+def _build_followup_transcript(messages: list[dict[str, Any]]) -> str:
+ lines: list[str] = []
+ for m in messages[-_FOLLOWUP_MAX_MESSAGES:]:
+ speaker = "EXECUTIVE" if m.get("role") == "assistant" else "USER"
+ text = str(m.get("content") or "").strip()
+ if len(text) > _FOLLOWUP_MAX_CHARS_PER_MESSAGE:
+ text = text[:_FOLLOWUP_MAX_CHARS_PER_MESSAGE] + " […]"
+ lines.append(f"{speaker}: {text}")
+ return "\n\n".join(lines)
+
+
+async def _generate_followup_via_llm(transcript: str) -> str | None:
+ """Returns one suggested next user message, or None on any failure."""
+ data = await _fast_json_call(_FOLLOWUP_SYSTEM, transcript, 150, "followup_suggestion")
+ if data is None:
+ return None
+ raw = data.get("suggestion")
+ if not isinstance(raw, str):
+ return None
+ suggestion = " ".join(raw.split())
+ # A runaway or empty answer is worse than no suggestion in the composer.
+ if not suggestion or len(suggestion.split()) > _FOLLOWUP_MAX_WORDS:
return None
+ return suggestion
@router.get("/chat/suggested-prompts")
diff --git a/packages/core/openexecutive/api/routes/sessions.py b/packages/core/openexecutive/api/routes/sessions.py
index 1be2a9e4..8c28dfdc 100644
--- a/packages/core/openexecutive/api/routes/sessions.py
+++ b/packages/core/openexecutive/api/routes/sessions.py
@@ -1,11 +1,13 @@
from __future__ import annotations
-from typing import Literal
+import time
+from typing import Any, Literal
from fastapi import APIRouter, HTTPException, Request, Response, status
from pydantic import BaseModel, Field
from openexecutive.api.models import SessionSummary
+from openexecutive.api.routes import chat as chat_route
from openexecutive.api.routes.chat import _resolve_caller_person_id
from openexecutive.memory.session_store import (
delete_session,
@@ -110,3 +112,50 @@ def post_message_feedback(
if caller is not None and rated_reply_speaker(session_id, message_id) == caller:
schedule_style_pass(caller, force=True, session_id=session_id)
return Response(status_code=status.HTTP_204_NO_CONTENT)
+
+
+# (session_id, last assistant message id) -> (monotonic ts, suggestion).
+# Keyed on the reply being followed up on, so reopening a session or
+# remounting the composer does not re-bill the fast model; a new reply is a
+# new key. Single-process, like `_suggested_prompts_cache`.
+_FOLLOWUP_TTL_S = 3600
+_FOLLOWUP_CACHE_MAX = 512
+_followup_cache: dict[tuple[str, int], tuple[float, str]] = {}
+
+
[email protected]("/sessions/{session_id}/followup")
+async def get_followup_suggestion(session_id: str, request: Request) -> dict[str, Any]:
+ """One suggested next message for the chat composer.
+
+ Grounded in the tail of the conversation. ``suggestion`` is null when the
+ conversation does not end on a reply, or when the fast model fails — the
+ composer then falls back to its static placeholder. Only the session's
+ own caller, or the principal, may ask: the suggestion paraphrases the
+ conversation.
+ """
+ exists, owner = get_session_owner(session_id)
+ if not exists:
+ raise HTTPException(status_code=404, detail="Session not found")
+ if not is_principal_or_self(_resolve_caller_person_id(request), owner):
+ raise HTTPException(status_code=403, detail="Not your session")
+
+ messages = load_messages(session_id)
+ last = messages[-1] if messages else None
+ if last is None or last.get("role") != "assistant" or not last.get("id"):
+ return {"suggestion": None}
+
+ key = (session_id, int(last["id"]))
+ now = time.monotonic()
+ hit = _followup_cache.get(key)
+ if hit is not None and (now - hit[0]) < _FOLLOWUP_TTL_S:
+ return {"suggestion": hit[1]}
+
+ transcript = chat_route._build_followup_transcript(messages)
+ suggestion = await chat_route._generate_followup_via_llm(transcript)
+ if suggestion is not None:
+ # Failures are not cached: a transient blip should not pin the
+ # static placeholder on this reply for an hour.
+ if len(_followup_cache) >= _FOLLOWUP_CACHE_MAX:
+ _followup_cache.clear()
+ _followup_cache[key] = (now, suggestion)
+ return {"suggestion": suggestion}
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 0cde031c..033f44c4 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -1484,6 +1484,15 @@ attunement:
AskOEPanel renders 👍/👎. `load_messages` adds `id` (+ `feedback`) to
assistant rows only. Audited as event_type `attunement`, op=feedback.
Stored for later per-person learning; nothing consumes it yet.
+ followup_suggestion: |
+ GET /sessions/{id}/followup → {"suggestion": str|null}. Chat composer's
+ greyed placeholder after each reply (Tab / → / inline chip fills it,
+ never sends). Utility-fast call (`chat._fast_json_call`, shared with
+ /chat/suggested-prompts) over the last 6 messages, each capped at 1500
+ chars; transcript in the user turn, no cached system blocks. Null when
+ the session doesn't end on a persisted assistant reply, or on model
+ failure (not cached). Owner-or-principal only (403). In-process cache
+ keyed (session_id, last assistant message id), 1h TTL.
open_loops:
module: openexecutive.attunement.open_loops
pass: |
diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.json
index 3ac83253..3ec088a7 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`, `POST /chat/stop` | 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. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages`, `POST /sessions/{id}/messages/{message_id}/feedback` | List and read saved chat sessions (assistant messages carry their row `id` and any `feedback`). The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it (403 otherwise). The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. |\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`, `GET /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style. |\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}`, `GET /memories/people` | Episodic-memory record management, plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5). |\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`, `POST /chat/stop` | 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. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List and read saved chat sessions (assistant messages carry their row `id` and any `feedback`). The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it (403 otherwise). The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same owner-or-principal 403 as feedback; successful suggestions are cached in-process per (session, reply id). |\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`, `GET /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style. |\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}`, `GET /memories/people` | Episodic-memory record management, plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5). |\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-22T23:17:20.508677+00:00"
+ "generated_at": "2026-09-23T15:10:14.978268+00:00"
}
diff --git a/packages/core/tests/unit/test_session_followup.py b/packages/core/tests/unit/test_session_followup.py
new file mode 100644
index 00000000..c7eaf739
--- /dev/null
+++ b/packages/core/tests/unit/test_session_followup.py
@@ -0,0 +1,215 @@
+"""Tests for GET /sessions/{id}/followup — the composer's suggested next message.
+
+Covers:
+- A conversation ending on a persisted reply returns the model's suggestion.
+- Model failure / bad output returns ``null`` with a 200, and is not cached.
+- A conversation that does not end on a reply skips the model entirely.
+- Unknown session → 404; someone else's session → 403.
+- Repeat calls for the same reply hit the cache.
+- The fast-model helper parses fenced JSON and rejects runaway answers.
+"""
+from __future__ import annotations
+
+from collections.abc import Iterator
+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.api.routes import sessions as sessions_route
+
+_CONVO: list[dict[str, Any]] = [
+ {"role": "user", "content": "Should we raise prices on the Pro tier?"},
+ {"id": 7, "role": "assistant", "content": "Yes — a 15% increase, grandfathering current Pro accounts."},
+]
+
+
+def _make_app() -> FastAPI:
+ app = FastAPI()
+ app.include_router(sessions_route.router)
+ return app
+
+
[email protected](autouse=True)
+def _reset_cache() -> Iterator[None]:
+ sessions_route._followup_cache.clear()
+ yield
+ sessions_route._followup_cache.clear()
+
+
+def _patch_session(
+ monkeypatch: pytest.MonkeyPatch,
+ messages: list[dict[str, Any]],
+ *,
+ exists: bool = True,
+ allowed: bool = True,
+) -> None:
+ monkeypatch.setattr(sessions_route, "get_session_owner", lambda _sid: (exists, 1))
+ monkeypatch.setattr(sessions_route, "_resolve_caller_person_id", lambda _req: 1)
+ monkeypatch.setattr(sessions_route, "is_principal_or_self", lambda _c, _o: allowed)
+ monkeypatch.setattr(sessions_route, "load_messages", lambda _sid: list(messages))
+
+
+def _patch_llm(monkeypatch: pytest.MonkeyPatch, result: str | None) -> dict[str, Any]:
+ calls: dict[str, Any] = {"n": 0, "transcript": None}
+
+ async def _fake(transcript: str) -> str | None:
+ calls["n"] += 1
+ calls["transcript"] = transcript
+ return result
+
+ monkeypatch.setattr(chat_route, "_generate_followup_via_llm", _fake)
+ return calls
+
+
+def test_returns_suggestion_for_last_reply(monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_session(monkeypatch, _CONVO)
+ calls = _patch_llm(monkeypatch, "Draft the customer email announcing the Pro increase.")
+
+ with TestClient(_make_app()) as client:
+ res = client.get("/sessions/s1/followup")
+
+ assert res.status_code == 200
+ assert res.json() == {"suggestion": "Draft the customer email announcing the Pro increase."}
+ assert calls["n"] == 1
+ assert "USER: Should we raise prices" in calls["transcript"]
+ assert "EXECUTIVE: Yes — a 15% increase" in calls["transcript"]
+
+
+def test_llm_failure_returns_null_and_is_not_cached(monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_session(monkeypatch, _CONVO)
+ calls = _patch_llm(monkeypatch, None)
+
+ with TestClient(_make_app()) as client:
+ first = client.get("/sessions/s1/followup")
+ second = client.get("/sessions/s1/followup")
+
+ assert first.status_code == 200
+ assert first.json() == {"suggestion": None}
+ assert second.json() == {"suggestion": None}
+ assert calls["n"] == 2, "a failure must not pin null for this reply"
+
+
+ "messages",
+ [
+ [],
+ [{"role": "user", "content": "hello"}],
+ # A reply the client never got an id for (no persisted row).
+ [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "hey"}],
+ ],
+)
+def test_no_reply_skips_llm(monkeypatch: pytest.MonkeyPatch, messages: list[dict[str, Any]]) -> None:
+ _patch_session(monkeypatch, messages)
+ calls = _patch_llm(monkeypatch, "should not be used")
+
+ with TestClient(_make_app()) as client:
+ res = client.get("/sessions/s1/followup")
+
+ assert res.status_code == 200
+ assert res.json() == {"suggestion": None}
+ assert calls["n"] == 0
+
+
+def test_unknown_session_is_404(monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_session(monkeypatch, _CONVO, exists=False)
+ calls = _patch_llm(monkeypatch, "x")
+
+ with TestClient(_make_app()) as client:
+ res = client.get("/sessions/nope/followup")
+
+ assert res.status_code == 404
+ assert calls["n"] == 0
+
+
+def test_other_callers_session_is_403(monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_session(monkeypatch, _CONVO, allowed=False)
+ calls = _patch_llm(monkeypatch, "x")
+
+ with TestClient(_make_app()) as client:
+ res = client.get("/sessions/s1/followup")
+
+ assert res.status_code == 403
+ assert calls["n"] == 0
+
+
+def test_same_reply_hits_cache_new_reply_misses(monkeypatch: pytest.MonkeyPatch) -> None:
+ messages = list(_CONVO)
+ _patch_session(monkeypatch, messages)
+ calls = _patch_llm(monkeypatch, "Who should own the rollout?")
+
+ with TestClient(_make_app()) as client:
+ client.get("/sessions/s1/followup")
+ client.get("/sessions/s1/followup")
+ assert calls["n"] == 1
+
+ newer = [*_CONVO, {"role": "user", "content": "ok"}, {"id": 9, "role": "assistant", "content": "Done."}]
+ _patch_session(monkeypatch, newer)
+ client.get("/sessions/s1/followup")
+
+ assert calls["n"] == 2
+
+
+def test_transcript_keeps_tail_and_truncates() -> None:
+ long = "x" * 5000
+ messages = [{"role": "user", "content": f"m{i}"} for i in range(10)]
+ messages.append({"id": 1, "role": "assistant", "content": long})
+
+ transcript = chat_route._build_followup_transcript(messages)
+
+ assert "USER: m4" not in transcript
+ assert "USER: m5" in transcript
+ assert "x" * chat_route._FOLLOWUP_MAX_CHARS_PER_MESSAGE + " […]" in transcript
+ assert "x" * (chat_route._FOLLOWUP_MAX_CHARS_PER_MESSAGE + 1) not in transcript
+
+
+class _FakeBlock:
+ def __init__(self, text: str) -> None:
+ self.type = "text"
+ self.text = text
+
+
+class _FakeResponse:
+ def __init__(self, text: str) -> None:
+ self.content = [_FakeBlock(text)]
+
+
+class _FakeProvider:
+ def __init__(self, text: str) -> None:
+ self._text = text
+
+ async def messages_create(self, **_kwargs: Any) -> _FakeResponse:
+ return _FakeResponse(self._text)
+
+
+def _patch_provider(monkeypatch: pytest.MonkeyPatch, text: str) -> None:
+ from openexecutive import providers
+ from openexecutive.agents import utility_fast
+
+ monkeypatch.setattr(utility_fast, "get_fast_model", lambda: "claude-haiku-test")
+ monkeypatch.setattr(providers, "get_provider", lambda _model: _FakeProvider(text))
+
+
+async def test_generator_parses_fenced_json(monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_provider(monkeypatch, '```json\n{"suggestion": " Draft the Pro pricing email. "}\n```')
+ assert await chat_route._generate_followup_via_llm("t") == "Draft the Pro pricing email."
+
+
+ "raw",
+ [
+ "not json",
+ '["a list"]',
+ '{"suggestion": ""}',
+ '{"suggestion": 42}',
+ '{"other": "key"}',
+ '{"suggestion": "' + " ".join(["word"] * 30) + '"}',
+ ],
+)
+async def test_generator_rejects_bad_output(monkeypatch: pytest.MonkeyPatch, raw: str) -> None:
+ _patch_provider(monkeypatch, raw)
+ assert await chat_route._generate_followup_via_llm("t") is None
diff --git a/packages/ui/src/components/Chat.tsx b/packages/ui/src/components/Chat.tsx
index daed5d6e..0c5ab6cc 100644
--- a/packages/ui/src/components/Chat.tsx
+++ b/packages/ui/src/components/Chat.tsx
@@ -17,6 +17,7 @@ import {
CommitteePhase,
DebugEvent,
FALLBACK_ACTIVITY_LABEL,
+ getFollowupSuggestion,
getSuggestedPrompts,
setMessageFeedback,
streamChat,
@@ -53,6 +54,15 @@ const SUGGESTED_PROMPTS = [
"What's changed since our last sync?",
];
+const DEFAULT_PLACEHOLDER = "What's on your mind?";
+
+// A follow-up is only worth suggesting when the conversation ends on a
+// persisted reply — the backend keys its suggestion on that reply's id.
+function endsOnReply(messages: ChatMessage[] | undefined): boolean {
+ const last = messages?.[messages.length - 1];
+ return last?.role === "assistant" && Boolean(last.id);
+}
+
const FALLBACK_SUBTITLE =
"Pick up where we left off — decisions to revisit, drafts to push forward, people to pull in.";
@@ -79,6 +89,10 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
const [isLoadingPrompts, setIsLoadingPrompts] = useState(true);
const [pendingFiles, setPendingFiles] = useState<File[]>([]);
const [fileError, setFileError] = useState<string | null>(null);
+ // Suggested next message, shown as the composer's greyed placeholder and
+ // accepted with Tab / → or the inline chip. Refreshed after every reply.
+ const [followup, setFollowup] = useState<string | null>(null);
+ const followupCtrlRef = useRef<AbortController | null>(null);
const bottomRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -103,6 +117,33 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
return () => ctrl.abort();
}, []);
+ function clearFollowup() {
+ followupCtrlRef.current?.abort();
+ followupCtrlRef.current = null;
+ setFollowup(null);
+ }
+
+ function loadFollowup(id: string) {
+ followupCtrlRef.current?.abort();
+ const ctrl = new AbortController();
+ followupCtrlRef.current = ctrl;
+ getFollowupSuggestion(id, ctrl.signal)
+ .then((suggestion) => {
+ // A newer fetch (or a send) superseded this one.
+ if (followupCtrlRef.current === ctrl) setFollowup(suggestion);
+ })
+ // Abort or network failure: keep the static placeholder.
+ .catch(() => {});
+ }
+
+ // Opening an existing session suggests a follow-up to its last reply.
+ // Later session switches are handled in the sync effect below.
+ useEffect(() => {
+ if (initialSessionId && endsOnReply(initialMessages)) loadFollowup(initialSessionId);
+ return () => followupCtrlRef.current?.abort();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
// Sync when parent selects a different session (or clears for new chat).
// Skip when the prop change is the parent echoing back an id this turn
// already adopted locally — otherwise we'd wipe the just-streamed reply.
@@ -112,6 +153,9 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
setMessages(initialMessages ?? []);
setSessionId(initialSessionId);
setStreamingContent("");
+ clearFollowup();
+ if (initialSessionId && endsOnReply(initialMessages)) loadFollowup(initialSessionId);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [initialSessionId]);
useEffect(() => {
@@ -177,6 +221,7 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
setInput("");
setPendingFiles([]);
setFileError(null);
+ clearFollowup();
setMessages((prev) => [...prev, { role: "user", content: userBubbleContent }]);
setIsLoading(true);
setStreamingContent("");
@@ -201,6 +246,8 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
// Row id of the persisted reply, from `done`; it is what makes the reply
// rateable with 👍/👎.
let replyId: number | undefined;
+ // Session id from `done`, used to fetch the follow-up for this reply.
+ let doneSessionId: string | undefined;
try {
for await (const item of streamChat(message, sessionId, {
@@ -249,6 +296,7 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
} else if (item.type === "done") {
if (item.message_id) replyId = item.message_id;
if (item.session_id) {
+ doneSessionId = item.session_id;
adoptSessionId(item.session_id);
onTurnComplete?.(item.session_id);
}
@@ -284,6 +332,9 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
id: replyId,
},
]);
+ // Only a complete, persisted reply gets a follow-up: a stopped one
+ // is half an answer, and without an id there is nothing to key on.
+ if (!wasStopped && replyId && doneSessionId) loadFollowup(doneSessionId);
}
setStreamingContent("");
setStreamingActions([]);
@@ -337,7 +388,34 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
setMessageFeedback(sessionId, target.id, value).catch(() => apply(previous));
}
+ // Fill the composer with the suggestion without sending it, so the user
+ // can edit first. The suggestion is kept: clearing the box shows it again.
+ function acceptFollowup() {
+ if (!followup) return;
+ setInput(followup);
+ requestAnimationFrame(() => {
+ const el = textareaRef.current;
+ if (!el) return;
+ el.focus();
+ el.setSelectionRange(followup.length, followup.length);
+ el.style.height = "auto";
+ el.style.height = Math.min(el.scrollHeight, 160) + "px";
+ });
+ }
+
+ const showFollowup = Boolean(followup) && !input && !isLoading;
+
function handleKeyDown(e: React.KeyboardEvent<HTMLTextAreaElement>) {
+ // Tab / → take the suggestion only while the box is empty; otherwise
+ // both keep their usual meaning (focus move, caret move).
+ if (
+ showFollowup &&
+ ((e.key === "Tab" && !e.shiftKey) || e.key === "ArrowRight")
+ ) {
+ e.preventDefault();
+ acceptFollowup();
+ return;
+ }
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSend();
@@ -347,7 +425,9 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
function handleTextareaChange(e: React.ChangeEvent<HTMLTextAreaElement>) {
setInput(e.target.value);
e.target.style.height = "auto";
- e.target.style.height = Math.min(e.target.scrollHeight, 160) + "px";
+ // Emptied: drop the pixel height so the textarea stretches to its grid
+ // cell again, which the suggestion ghost may have made taller.
+ if (e.target.value) e.target.style.height = Math.min(e.target.scrollHeight, 160) + "px";
}
function handleFilesPicked(e: React.ChangeEvent<HTMLInputElement>) {
@@ -533,18 +613,47 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
>
<Icon name="paperclip" size="w-4 h-4" />
</button>
- <textarea
- ref={textareaRef}
- value={input}
- onChange={handleTextareaChange}
- onKeyDown={handleKeyDown}
- placeholder="What's on your mind?"
- rows={1}
- disabled={isLoading}
- aria-label="Message"
- className="flex-1 bg-transparent text-fg placeholder:text-fg-muted text-sm sm:text-base leading-relaxed resize-none focus:outline-none disabled:opacity-50 max-h-40 overflow-y-auto"
- style={{ minHeight: "24px" }}
- />
+ {/* The suggestion is drawn by a ghost layer sharing the textarea's
+ grid cell rather than by the native placeholder, which a
+ one-row textarea clips to its first line. The cell grows to
+ the ghost's wrapped height; the placeholder attribute still
+ carries the text for screen readers, just painted transparent. */}
+ <div className="grid flex-1 min-w-0">
+ {showFollowup && (
+ <div
+ aria-hidden
+ className="col-start-1 row-start-1 pointer-events-none text-fg-muted text-sm sm:text-base leading-relaxed whitespace-pre-wrap break-words max-h-40 overflow-hidden"
+ >
+ {followup}
+ </div>
+ )}
+ <textarea
+ ref={textareaRef}
+ value={input}
+ onChange={handleTextareaChange}
+ onKeyDown={handleKeyDown}
+ placeholder={followup ?? DEFAULT_PLACEHOLDER}
+ rows={1}
+ disabled={isLoading}
+ aria-label="Message"
+ className={
+ "col-start-1 row-start-1 w-full bg-transparent text-fg text-sm sm:text-base leading-relaxed resize-none focus:outline-none disabled:opacity-50 max-h-40 overflow-y-auto " +
+ (showFollowup ? "placeholder:text-transparent" : "placeholder:text-fg-muted")
+ }
+ style={{ minHeight: "24px" }}
+ />
+ </div>
+ {showFollowup && (
+ <button
+ type="button"
+ onClick={acceptFollowup}
+ title="Use the suggested follow-up (Tab)"
+ aria-label={`Use suggested follow-up: ${followup}`}
+ className="hidden sm:flex flex-shrink-0 min-h-touch px-2.5 rounded-lg border border-line bg-surface-overlay text-xs font-mono text-fg-muted hover:text-fg hover:border-line-strong transition-all duration-150 items-center cursor-pointer"
+ >
+ Tab ↹
+ </button>
+ )}
<button
type="button"
onClick={() => setCommitteeEnabled((v) => !v)}
@@ -585,8 +694,23 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
)}
</div>
<p className="text-center text-xs text-fg-muted mt-2 inline-flex items-center justify-center gap-1.5 w-full">
- <span className="hidden sm:inline">Enter to send · Shift+Enter for new line</span>
+ <span className="hidden sm:inline">
+ Enter to send · Shift+Enter for new line
+ {showFollowup && " · Tab to use suggestion"}
+ </span>
<span className="sm:hidden">Tap send</span>
+ {/* Phones have no Tab key and no room in the input row, so the
+ tap target for the suggestion lives on this line instead. */}
+ {showFollowup && (
+ <button
+ type="button"
+ onClick={acceptFollowup}
+ aria-label={`Use suggested follow-up: ${followup}`}
+ className="sm:hidden min-h-touch px-1 text-indigo-400 hover:text-indigo-300 font-medium cursor-pointer"
+ >
+ · Use suggestion
+ </button>
+ )}
<InfoTip align="right">
Your Executive routes your question to the right specialist
behind the scenes — you don&apos;t pick which one.
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index a758f2fb..e1e4f74d 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -803,6 +803,25 @@ export async function getSuggestedPrompts(
return res.json();
}
+// One suggested next message for the chat composer, grounded in the tail of
+// the session. Resolves to null on any non-OK response — the composer then
+// keeps its static placeholder — but rejects on abort so callers can tell a
+// cancelled fetch apart from "no suggestion".
+export async function getFollowupSuggestion(
+ sessionId: string,
+ signal?: AbortSignal,
+): Promise<string | null> {
+ const res = await fetch(
+ `${API_BASE}/sessions/${encodeURIComponent(sessionId)}/followup`,
+ { signal },
+ );
+ if (!res.ok) return null;
+ const body: { suggestion?: unknown } = await res.json();
+ return typeof body.suggestion === "string" && body.suggestion.trim()
+ ? body.suggestion.trim()
+ : null;
+}
+
export interface ChatMessage {
role: "user" | "assistant";
content: string;