Files
EvoScientist-Multi/EvoScientist/cli/status_bar.py
T
dinos 65828e9666 perf(cli): cut startup latency and defer MCP loading to the background (#171)
* perf(cli): cut startup time of `evosci --help` from ~2.2s to ~0.3s

Module-level imports were eagerly pulling in langchain.chat_models (with
the whole anthropic/openai/google stack), langgraph, textual, and
prompt_toolkit on every invocation — even for `--help` or `config list`.

Defer those with PEP 562 `__getattr__`, using `lazy_loader.attach` (SPEC-1,
the scientific-python standard) where it's a clean attach pattern:

- `EvoScientist/llm/__init__.py`: attach `models` lazily so importing
  `context_window` from this package no longer drags in langchain.
- `EvoScientist/stream/__init__.py`: attach display/events lazily; split
  the shared Rich `Console` singleton into a new lightweight
  `stream/console.py` so callers that only need `console` skip the
  `stream.events` → `langchain_core.messages` chain.
- `EvoScientist/cli/__init__.py`: hand-rolled `__getattr__` (reaches into
  `..stream.state`, which `lazy_loader` doesn't cover) so `commands` and
  `app` are the only eager loads.
- `EvoScientist/cli/commands.py`: move `cmd_interactive`/`cmd_run` to
  in-function imports so prompt_toolkit + textual only load when the
  interactive path actually runs.
- `EvoScientist/cli/_constants.py`: read `AGENT_NAME` on demand so
  `build_metadata` doesn't eagerly import `sessions` (langgraph/aiosqlite).

Adds `lazy-loader>=0.5` as a dependency.

* feat(cli): defer MCP tool loading with live per-server progress

The CLI was blocking ~5 s on MCP tool enumeration before the first
prompt appeared. Move the agent construction off the event loop and
surface per-server progress so the user can interact immediately and see
what's happening.

MCP client:
- Add an `on_progress` callback to `load_mcp_tools` / `aload_mcp_tools`
  / `_load_tools` emitting `start` / `success` / `error` events per
  server.
- Fan connection attempts out with `asyncio.gather` so latency no longer
  scales linearly with server count; cap simultaneous attempts at
  `_MAX_CONCURRENT_CONNECTIONS` (8) via a semaphore so a big stdio fleet
  doesn't spawn every subprocess at once.

Agent wiring:
- Plumb `on_mcp_progress` through `create_cli_agent` / `_load_agent` /
  `load_mcp_and_build_kwargs` so CLI and TUI can plug in collectors.

CLI (`cmd_interactive`):
- Run `_load_agent` in a background thread via `asyncio.to_thread`; the
  prompt and banner render immediately.
- `_await_agent_ready()` awaits the task before each agent-using site
  (first turn, channel messages, `/channel`, `/compact`). Raises if
  called without a prior `_start_agent_load` instead of silently
  reloading without the SQLite checkpointer.
- Pre-prime the progress dict from `load_mcp_config()` so the
  bottom-toolbar's `N/M` denominator is stable from the first render.
- Wrap `session.prompt_async` in `patch_stdout(raw=True)` so
  `console.print` from the worker-thread progress callback lands cleanly
  above the prompt as inline chat messages instead of stomping the
  prompt cursor.

TUI (`EvoTextualInteractiveApp`):
- Same background load + `_await_agent_ready()` gates on every
  `self._agent` read.
- New `MCPLoaderWidget` mounted at the top of `#input-shell` shows a
  header with `N/M` and one live row per server (spinner → ✓ / ✗ with
  tool count or error detail). On completion:
  - all-clean loads auto-dismiss ~2.5 s later;
  - cache hits (no events ever fired) dismiss immediately rather than
    flashing a misleading "0/N loaded";
  - failures keep the widget mounted so the user can read the errors.
  - `dismissed` property lets the app clear its ref so late events from
    slow servers become no-ops. The error branch of `_on_agent_loaded`
    also settles the widget so a load failure can't leave the spinner
    animating forever.
- Chat input is `disabled` while MCP resolves — no placeholder hack, no
"waiting…" system message.

Shared:
- Hoist braille spinner frames to `status_bar.SPINNER_FRAMES` and import
  them in the TUI widget so CLI and TUI animate in sync.

Tests:
- Extend `test_agent_mcp_cache` fakes to accept the new `on_progress`
  kwarg.
- New `TestLoadToolsProgressCallback` in `test_mcp_client` exercises the
  event sequence for success/failure/mixed fleets, verifies a buggy
  callback doesn't break the load, and asserts the semaphore caps
  in-flight connections.

* style: ruff

* chore: update uv.lock

* chore: uv.lock

* fix: coderabbit issues

* style: fmt

* fix: move _await_agent_ready inside try block

* fix(tui): auto-dismiss MCP loader widget on failure

The widget was designed to stay mounted on failure so the user could
read error detail, but since it's pinned above the input it never went
away in practice — just permanent banner clutter.

Auto-dismiss on failure too, with a longer grace (12s vs 2.5s) so the
error summary stays readable.

* fix: address second coderabbit pass

- Channel handlers (CLI + TUI): catch agent-load failures so the
  channel request doesn't hang; CLI moves `_await_agent_ready()`
  inside the existing try/except, TUI catches explicitly and calls
  `_set_channel_response` with the error.

- Stale background loads: `prev.cancel()` only stops the asyncio
  wrapper, not the thread running `_load_agent`. Added a generation
  token (`agent_load_id` / `self._agent_load_id`) and gated both
  progress and completion callbacks on it so a superseded load can't
  clobber the current session's state or UI.

- TUI prompt lifecycle: added `_agent_load_pending()` and gated the
  `_process_channel_message` / `_handle_command` finally blocks on it
  so `/new` or `/resume` invoked from a command keeps the prompt
  disabled until the fresh load settles.

- TUI readiness failures: `_run_turn` and `_handle_command` now
  catch exceptions from `_await_agent_ready()` and surface a
  "Agent failed to load: …" system message instead of letting the
  exception escape into Textual's traceback panel.

* refactor(cli): share background agent loader between CLI and TUI

The CLI and TUI were carrying near-identical copies of the same
background-load state machine: the `agent_task`, the `agent_load_id`
generation token, the gated progress/completion callbacks, and the
per-server progress dict. Every CodeRabbit finding on that lifecycle
had to be fixed in both files.

Extract it into `cli/_agent_loader.py`:

- `MCPProgressTracker` — owns the `server -> (state, detail)` dict;
  exposes `prime`, `record`, `snapshot`, `totals`.

- `BackgroundAgentLoader` — owns `agent`, the in-flight task, and the
  generation token. Exposes `start(**loader_kwargs)`, `await_ready()`,
  `is_pending`. Internally gates all progress/completion callbacks by
  generation so a superseded load can't clobber the current session.
  UI-specific rendering plugs in via `on_progress` / `on_success` /
  `on_failure` callbacks.

Both surfaces now just wire their UI hooks; the loader file holds no
Rich / prompt_toolkit / Textual dependencies. Net -345 lines from
`interactive.py` + `tui_interactive.py`; +20 unit tests pinning the
lifecycle (generation filtering, cache-hit short-circuit, failure
reset, progress ordering).

* refactor(cli): make _on_done the sole authority for agent state transitions

await_ready no longer sets self.agent — it just awaits the task and
reads what _on_done already wrote. Eliminates the dual-write overlap
(asyncio guarantees done-callbacks fire in registration order).

* fix(tui): let users type during MCP load, only block on send

Remove prompt-disabling during background agent load — the TUI now
matches the CLI approach where the input stays enabled and only gates
on await_ready() at submit time. The MCPLoaderWidget still provides
visual feedback that loading is in progress.

* fix(loader): preserve real load error on await_ready; dedup failure message

CodeRabbit flagged two issues with the new loader:

1. After a failed load, `_on_done` nulled `self._task`, so the next
   `await_ready()` hit the "before start()" branch and the CLI wrapper
   remapped it to a misleading "checkpointer not available" message —
   losing the real exception (bad MCP config, network, etc.).

   Keep `_task` set on failure so `await_ready` re-raises the real
   exception. Added `needs_restart` so TUI's auto-retry check stays a
   one-liner and doesn't need to reach into task internals.

2. TUI reported each load failure twice: once from
   `_on_agent_load_failure` (the done-callback) and once from each
   caller of `_await_agent_ready` (`_run_turn`,
   `_process_channel_message`, `_handle_command`) catching the re-raise.

   `_on_agent_load_failure` is now the sole local reporter; callers
   just handle control flow (return cleanly, set channel response to
   unblock remote).

* fix(cli): wire /model handler through the agent loader

The /model command from main (merged via f1f0d7c) still reached for
`state["agent"]` (CLI) and `self._agent` (TUI) — both removed by the
background-loader refactor. CLI raised KeyError on first invocation;
TUI raised AttributeError. Writes to the old fields also had no effect
because every other code path now reads from `agent_loader.agent`, so
the model switch would have silently failed.

Route everything through the loader: `await _await_agent_ready()` up
front so /model doesn't race with the initial background load, build
the `CommandContext` with the current agent, and sync `ctx.agent` back
into `agent_loader.agent` (plus channel globals) when the command
replaces it.

* fix(cli): isolate progress callback, capture awaited agent, gate by requires_agent

Three CodeRabbit findings on the loader + command dispatch path:

- Wrap ``_on_progress`` in try/except inside the loader's gated wrapper
  so a buggy UI adapter can't bubble into ``loader_fn`` and fail the
  whole background load. The MCP client already protects this, but
  defence-in-depth keeps the loader self-contained.

- In CLI channel + main-loop streaming, capture the agent returned by
  ``_await_agent_ready()`` and pass that into ``run_streaming`` rather
  than reading ``agent_loader.agent`` after a subsequent ``await``.
  A concurrent ``/new``/``/resume``/``/model`` could have swapped it.

- Add ``requires_agent: ClassVar[bool] = False`` to ``Command`` and
  mark ``/compact``, ``/model``, ``/channel`` as ``True``. TUI dispatch
  sites (channel and keyboard) now check ``cmd_manager.resolve(...)``
  and only wait for readiness when the command actually needs the
  agent. ``/mcp add``, ``/skills``, ``/new`` etc. no longer deadlock
  behind a failing MCP load they are meant to fix.

* fix(cli): guard sync-back, subcommand-aware gating, /model adopt-path

Three CodeRabbit findings on command dispatch:

- ``_handle_command`` unconditionally synced ``ctx.agent`` back into
  ``agent_loader``.  For non-agent commands ``ctx.agent`` is ``None``,
  so ``/threads`` / ``/mcp`` / ``/skills`` (etc.) could clobber a valid
  loaded agent — and rebind channel globals to ``None``.  Guard the
  sync on ``ctx.agent is not None``.

- ``/channel status`` and ``/channel stop`` don't touch ``ctx.agent``
  but the class-level ``requires_agent = True`` blocked them behind
  agent readiness.  Added ``Command.needs_agent(args)`` (defaults to
  ``requires_agent``) so ``/channel`` can override with subcommand
  awareness; kept the class flag for the common case.

- ``/model`` builds a new agent from scratch, it never reads the
  existing one — gating it on readiness meant a broken provider
  blocked the command that would fix it.  Flipped it to
  ``requires_agent = False`` and added ``BackgroundAgentLoader.adopt``
  so the UI can seat the replacement and supersede any in-flight
  load (the generation token keeps a late completion from clobbering
  the adopted agent).

Bonus cleanup: ``CommandManager.resolve`` now returns
``(command, args)`` so callers can invoke ``needs_agent`` without
re-implementing ``shlex`` parsing.

---------

Co-authored-by: Xi Zhang <106144707+X-iZhang@users.noreply.github.com>
2026-04-22 18:22:33 +02:00

377 lines
12 KiB
Python

"""Shared session status bar helpers for CLI and TUI frontends."""
from __future__ import annotations
from dataclasses import dataclass, replace
from datetime import datetime
from typing import Any
from langchain_core.messages import AIMessage, HumanMessage
from langchain_core.messages.utils import count_tokens_approximately
from ..llm.context_window import (
DEFAULT_CONTEXT_WINDOW_FALLBACK,
resolve_context_window,
)
from ..sessions import get_thread_messages
_FALLBACK_CONTEXT_WINDOW = DEFAULT_CONTEXT_WINDOW_FALLBACK
STATUS_BAR_BG = "#171a20"
STATUS_TEXT = "#cbd5e1"
STATUS_STRONG = "#e5e7eb"
STATUS_DIM = "#7c8594"
STATUS_GOOD = "#5fcf8b"
STATUS_WARN = "#d7b45a"
STATUS_BAD = "#d08c61"
STATUS_CRITICAL = "#d86f6f"
STATUS_HINT_IDLE = "#8b9bb0"
STATUS_HINT_BUSY = "#f0c36a"
# Braille spinner frames used by the CLI bottom toolbar and TUI status bar
# to animate the "Loading MCP tools" indicator.
SPINNER_FRAMES = "\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f"
@dataclass(slots=True)
class SessionStatusSnapshot:
"""Current session metrics shown in the persistent status bar."""
model_full: str
model_short: str
context_tokens: int
context_window: int
context_percent: int
context_source: str = "estimated"
def _percent_from_context(context_tokens: int, context_window: int) -> int:
"""Convert token counts into a clamped percent value."""
if context_window <= 0:
return 0
return max(0, min(100, round((context_tokens / context_window) * 100)))
def _get_default_chat_model() -> Any:
"""Resolve the default chat model lazily to avoid import cycles."""
from ..EvoScientist import _ensure_chat_model
return _ensure_chat_model()
def _resolve_model_name(model_name: str | None, model_obj: Any | None) -> str:
"""Best-effort model name resolution for display."""
if model_name:
return str(model_name)
if model_obj is None:
model_obj = _get_default_chat_model()
for attr in ("model_name", "model", "name"):
value = getattr(model_obj, attr, None)
if value:
return str(value)
return "unknown"
def _resolve_context_window(model_obj: Any | None) -> int:
"""Resolve the model context window with a safe fallback."""
if model_obj is None:
model_obj = _get_default_chat_model()
return resolve_context_window(model_obj, fallback=_FALLBACK_CONTEXT_WINDOW)
def shorten_model_name(model_name: str, max_len: int = 26) -> str:
"""Shorten provider-prefixed model names for compact display."""
short = (model_name or "unknown").split("/")[-1]
if len(short) > max_len:
return f"{short[: max_len - 3]}..."
return short
def format_token_count_compact(value: int) -> str:
"""Format large token counts into a compact human-readable form."""
abs_value = abs(int(value))
if abs_value >= 1_000_000:
num = value / 1_000_000
suffix = "M"
elif abs_value >= 1_000:
num = value / 1_000
suffix = "K"
else:
return str(value)
if num.is_integer():
return f"{int(num)}{suffix}"
return f"{num:.1f}{suffix}"
def format_duration_compact(started_at: datetime, now: datetime | None = None) -> str:
"""Format elapsed wall time into a compact duration string."""
current = now or datetime.now()
seconds = max(0, int((current - started_at).total_seconds()))
if seconds < 60:
return f"{seconds}s"
minutes = seconds // 60
if minutes < 60:
return f"{minutes}m"
hours = minutes // 60
if hours < 24:
return f"{hours}h"
days = hours // 24
return f"{days}d"
def status_style_name(percent_used: int) -> str:
"""Map utilization percent to shared status bar style buckets."""
if percent_used >= 95:
return "critical"
if percent_used > 80:
return "bad"
if percent_used >= 50:
return "warn"
return "good"
def build_context_bar(percent_used: int, width: int = 10) -> str:
"""Build a compact visual context progress bar."""
safe_percent = max(0, min(100, int(percent_used)))
filled = round((safe_percent / 100) * width)
body = ("█" * filled) + ("░" * max(0, width - filled))
return f"[{body}]"
def _display_width(text: str) -> int:
try:
from prompt_toolkit.utils import get_cwidth
return get_cwidth(text or "")
except Exception:
return len(text or "")
def trim_status_text(text: str, max_width: int) -> str:
"""Trim status-bar content to fit a single terminal row."""
if max_width <= 0:
return ""
if _display_width(text) <= max_width:
return text
ellipsis = "..."
ellipsis_width = _display_width(ellipsis)
if max_width <= ellipsis_width:
return ellipsis[:max_width]
try:
from prompt_toolkit.utils import get_cwidth
except Exception:
get_cwidth = None
out: list[str] = []
width = 0
for ch in text:
ch_width = get_cwidth(ch) if get_cwidth else len(ch)
if width + ch_width + ellipsis_width > max_width:
break
out.append(ch)
width += ch_width
return "".join(out).rstrip() + ellipsis
def build_status_fragments(
snapshot: SessionStatusSnapshot,
started_at: datetime,
width: int,
) -> list[tuple[str, str]]:
"""Build prompt_toolkit formatted-text fragments for the status bar."""
duration_label = format_duration_compact(started_at)
percent = snapshot.context_percent
percent_label = f"{percent}%"
if width < 52:
frags = [
("class:status-bar-strong", snapshot.model_short),
("class:status-bar-dim", " · "),
("class:status-bar-dim", duration_label),
("class:status-bar", " "),
]
elif width < 76:
frags = [
("class:status-bar-strong", snapshot.model_short),
("class:status-bar-dim", " · "),
(f"class:status-bar-{status_style_name(percent)}", percent_label),
("class:status-bar-dim", " · "),
("class:status-bar-dim", duration_label),
("class:status-bar", " "),
]
else:
context_label = (
f"{format_token_count_compact(snapshot.context_tokens)}/"
f"{format_token_count_compact(snapshot.context_window)}"
)
bucket = status_style_name(percent)
frags = [
("class:status-bar-strong", snapshot.model_short),
("class:status-bar-dim", " │ "),
("class:status-bar-dim", context_label),
("class:status-bar-dim", " │ "),
(f"class:status-bar-{bucket}", build_context_bar(percent)),
("class:status-bar-dim", " "),
(f"class:status-bar-{bucket}", percent_label),
("class:status-bar-dim", " │ "),
("class:status-bar-dim", duration_label),
("class:status-bar", " "),
]
total_width = sum(_display_width(text) for _, text in frags)
if total_width > width:
plain_text = "".join(text for _, text in frags)
return [("class:status-bar", trim_status_text(plain_text, width))]
return frags
def build_status_text(
snapshot: SessionStatusSnapshot,
started_at: datetime,
width: int,
):
"""Build a Rich Text object for the persistent TUI status bar."""
from rich.text import Text
rich_styles = {
"status-bar": f"on {STATUS_BAR_BG} {STATUS_TEXT}",
"status-bar-strong": f"on {STATUS_BAR_BG} {STATUS_STRONG} bold",
"status-bar-dim": f"on {STATUS_BAR_BG} {STATUS_DIM}",
"status-bar-good": f"on {STATUS_BAR_BG} {STATUS_GOOD} bold",
"status-bar-warn": f"on {STATUS_BAR_BG} {STATUS_WARN} bold",
"status-bar-bad": f"on {STATUS_BAR_BG} {STATUS_BAD} bold",
"status-bar-critical": f"on {STATUS_BAR_BG} {STATUS_CRITICAL} bold",
}
text = Text(no_wrap=True, overflow="crop")
for style, content in build_status_fragments(snapshot, started_at, width):
rich_style = rich_styles.get(
style.removeprefix("class:"),
f"on {STATUS_BAR_BG} {STATUS_TEXT}",
)
text.append(content, style=rich_style)
return text
def make_empty_status_snapshot(
model_name: str | None = None, model_obj: Any | None = None
) -> SessionStatusSnapshot:
"""Build a placeholder snapshot before async context counting completes."""
resolved_name = _resolve_model_name(model_name, model_obj)
window = _resolve_context_window(model_obj)
return SessionStatusSnapshot(
model_full=resolved_name,
model_short=shorten_model_name(resolved_name),
context_tokens=0,
context_window=window,
context_percent=0,
context_source="estimated",
)
def make_usage_status_snapshot(
input_tokens: int,
*,
model_name: str | None = None,
model_obj: Any | None = None,
) -> SessionStatusSnapshot:
"""Build a snapshot from the last real model input usage."""
resolved_name = _resolve_model_name(model_name, model_obj)
window = _resolve_context_window(model_obj)
context_tokens = max(0, int(input_tokens))
return SessionStatusSnapshot(
model_full=resolved_name,
model_short=shorten_model_name(resolved_name),
context_tokens=context_tokens,
context_window=window,
context_percent=_percent_from_context(context_tokens, window),
context_source="usage",
)
def estimate_message_tokens(
text: str,
*,
message_type: str = "ai",
) -> int:
"""Estimate tokens for a single in-flight message fragment."""
content = (text or "").strip()
if not content:
return 0
try:
if message_type == "human":
messages = [HumanMessage(content=content)]
else:
messages = [AIMessage(content=content)]
return int(count_tokens_approximately(messages))
except Exception:
return 0
def apply_assistant_text_to_snapshot(
snapshot: SessionStatusSnapshot,
assistant_text: str | None,
) -> SessionStatusSnapshot:
"""Overlay in-flight assistant output on top of a base snapshot."""
extra_tokens = estimate_message_tokens(assistant_text or "", message_type="ai")
if extra_tokens <= 0:
return snapshot
context_tokens = snapshot.context_tokens + extra_tokens
return replace(
snapshot,
context_tokens=context_tokens,
context_percent=_percent_from_context(context_tokens, snapshot.context_window),
)
def apply_user_text_to_snapshot(
snapshot: SessionStatusSnapshot,
user_text: str | None,
) -> SessionStatusSnapshot:
"""Overlay pending user input on top of an existing snapshot."""
extra_tokens = estimate_message_tokens(user_text or "", message_type="human")
if extra_tokens <= 0:
return snapshot
context_tokens = snapshot.context_tokens + extra_tokens
return replace(
snapshot,
context_tokens=context_tokens,
context_percent=_percent_from_context(context_tokens, snapshot.context_window),
)
async def build_session_status_snapshot(
thread_id: str,
*,
model_name: str | None = None,
model_obj: Any | None = None,
pending_user_text: str | None = None,
) -> SessionStatusSnapshot:
"""Count current thread context and return a display snapshot."""
resolved_name = _resolve_model_name(model_name, model_obj)
window = _resolve_context_window(model_obj)
messages = list(await get_thread_messages(thread_id))
pending = (pending_user_text or "").strip()
if pending:
messages.append(HumanMessage(content=pending))
try:
context_tokens = int(count_tokens_approximately(messages)) if messages else 0
except Exception:
context_tokens = 0
percent = _percent_from_context(context_tokens, window)
return SessionStatusSnapshot(
model_full=resolved_name,
model_short=shorten_model_name(resolved_name),
context_tokens=context_tokens,
context_window=window,
context_percent=percent,
context_source="estimated",
)