"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(cli): refresh interactive terminal UI
Haozhe Wu74614f0e7c94
diff --git a/.gitignore b/.gitignoreindex 80ee5255c..5e9f9e5e4 100644--- a/.gitignore+++ b/.gitignore@@ -43,6 +43,8 @@ data/backup/docs/!wiki/docs/!wiki/docs/**+docs/screenshots/agent-run.png+docs/screenshots/boot.pngdata/minutes/data/overnight*.logdata/*.logdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex bc06c31c8..5dc4591b5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,11 @@ This project adheres to [Semantic Versioning](https://semver.org/).## [Unreleased]+### UI+- Redesigned the interactive CLI startup and run-state visuals with a large+ figlet-style banner plus a Claude Code-style activity rail using `●`, `│`,+ and `·` glyphs. Non-TTY prompt runs now fall back to plain text output.+### Added### Changeddiff --git a/README.md b/README.mdindex bfe74078f..e7e15544c 100644--- a/README.md+++ b/README.md@@ -46,12 +46,13 @@## 📰 News+- **2026-05-23** 🖥️ **Interactive CLI refresh**: The terminal front door now opens with a larger Vibe-Trading banner, a cleaner prompt divider, prior-turn recap, post-run timing, and a Claude Code-style activity rail for live agent work. Tool calls, web/data fetches, shell-style actions, Markdown answers, and pipe tables render in a more readable transcript, while piped or non-TTY runs keep plain-text output for automation. Generated CLI screenshots are now treated as local artifacts instead of committed docs files, keeping the repository lighter.- **2026-05-22** 🧭 **Swarm recovery + MCP keepalive**: Swarm status now reconciles from live task files on every read, so API/MCP/SSE/list views recover crashed or stale runs instead of showing permanent `running` snapshots. `run_swarm` sends MCP progress heartbeats while it polls, with a fixed first frame of `swarm_started run_id=<id>` for clients that reconnect after transport drops; workers now heartbeat through LLM streaming, grounding fetches, and tool execution. The stale-run reaper uses per-run thresholds and derives terminal status from task states, `SwarmTool` no longer cancels a still-running team just because its wait budget elapsed, and MCP clients can call `reap_stale_runs()` for explicit cleanup. Today's DX pass also refreshed provider default models and aligned CI syntax checks with the new `agent/cli/` package. 22 new regressions cover hydration, terminal recovery, stale reaping, keepalive cadence, env parsing, and heartbeat wiring; the full swarm/MCP suite is at 169 passed, 4 skipped.- **2026-05-21** 🧱 **CLI package refactor**: `agent/cli.py` (3216 LOC) split into the `agent/cli/` package — interactive front door, slash router, Rich components, plus a `_legacy.py` shim that preserves every subcommand and re-exports every public symbol so `cli.cmd_*` / `cli._INIT_ENV_PATH` / `cli.Confirm` keep working. New FastAPI middleware serves the SPA shell when a browser opens `/runs/{id}` or `/correlation` directly; same narrowing landed in the Vite dev proxy. Version unified via `cli/_version.py` (no more drift between `--version` and the banner), `python -m cli` restored via `__main__.py`, and the chat-gate narrowed so `chat --help` / `chat extra` reach legacy argparse instead of being swallowed by the REPL.-- **2026-05-20** 🔬 **Hypothesis Registry CLI**: Closes the CLI side of the Hypothesis Registry shipped backend-only on 2026-05-16. `vibe-trading hypothesis list` prints a Rich table or JSON (`--status` filter, `--limit`); `show <id>` renders a detail panel including linked run cards; `invalidate <id> --note "..."` flips status to `rejected` while preserving prior invalidation notes when `--note` is omitted. Honors the existing `VIBE_TRADING_HYPOTHESES_PATH` env override and adds a per-invocation `--path`. 22 new tests cover wiring, JSON output, status filter, limit, missing-id errors, and note persistence.<details><summary>Earlier news</summary>+- **2026-05-20** 🔬 **Hypothesis Registry CLI**: Closes the CLI side of the Hypothesis Registry shipped backend-only on 2026-05-16. `vibe-trading hypothesis list` prints a Rich table or JSON (`--status` filter, `--limit`); `show <id>` renders a detail panel including linked run cards; `invalidate <id> --note "..."` flips status to `rejected` while preserving prior invalidation notes when `--note` is omitted. Honors the existing `VIBE_TRADING_HYPOTHESES_PATH` env override and adds a per-invocation `--path`. 22 new tests cover wiring, JSON output, status filter, limit, missing-id errors, and note persistence.- **2026-05-19** ✨ **Live tool feedback + graceful cancel**: Long-running tools (backtests, large PDFs, swarm workers) no longer look frozen. Each tool call now emits a 3-second heartbeat plus structured per-stage progress — `run_backtest` shows phase markers (`validate` / `simulate` / `finalize`), `read_document` ticks per page on PDF or per sheet on Excel, `read_url` marks `fetch` / `parse`. The CLI Rich Live dashboard renders a Unicode spinner, ASCII progress bar, ETA, and stacks up to 3 parallel tools keyed by name; the frontend chat ships a new `ToolProgressIndicator` with rAF-coalesced renders, ARIA `role="status"` + hidden native `<progress>` for screen readers, and a determinate `ProgressRing` SVG when total is known. First `Ctrl+C` during a CLI run now calls `agent.cancel()` for graceful exit (current step finishes, trace closes cleanly); a second within 2s force-quits. Reusable primitives extracted along the way: `ProgressBar.tsx` and `lib/tools.ts` (shared tool-name i18n).- **2026-05-18** 🧹 **Cleanup pass + three latent bug fixes**: `CompositeEngine` no longer misroutes bare Chinese-futures codes like `RB2410` to `GlobalFuturesEngine` — `_is_china_futures` moved into a shared `_market_hooks` module with a case-normalized product table and a non-CN exchange guard, plus 9 new regression cases. Session FTS5 indexes now persist timestamps so cross-session search can sort by date; the same path also fixed a re-upsert that was wall-clocking every session's `started_at`. The Vite dev-mode proxy gained the missing `/alpha` entry so the AlphaZoo page resolves on `npm run dev`. `tests/test_e2e_harness_v2.py` (real-LLM e2e suite) is now gated behind `VIBE_TRADING_RUN_LIVE_E2E=1` so CI no longer changes shape based on env-key presence. Ruff `per-file-ignores` added for the factor zoo (3783 → 0 F401 noise), frontend tsconfig enables `noUnusedLocals` / `noUnusedParameters` as regression guards, and 76 unused `vw = vwap(...)` boilerplate lines were dropped from `gtja191` alphas. Net **-918 LOC**.- **2026-05-17** 🧬 **Alpha Zoo v1 (0.1.8)**: 452 pre-built quant alphas across 4 zoos — `qlib158` (Microsoft Qlib, Apache-2 attribution), `alpha101` (Kakushadze 101 Formulaic Alphas, paper rewrite from arXiv:1601.00991), `gtja191` (Guotai Junan 2014 short-horizon factor report), and `academic` (Fama-French 5 + Carhart price-based proxies). One-line CLI to bench any zoo on your universe: `vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`. Ships with AST purity gate, lookahead-guard test, `pytest-socket` network kill-switch, per-zoo LICENSE.md, and a Developer Certificate of Origin (DCO) workflow for community PRs. Auto-rendered Alpha Library at [vibetrading.wiki/alpha-library/](https://vibetrading.wiki/alpha-library/) + research-lab post [Which of the 191 GTJA alphas still work in 2026?](https://vibetrading.wiki/research-lab/posts/alpha-191-in-2026.html).@@ -463,6 +464,8 @@ The default `agent/.env.example` ships with DeepSeek official API + `deepseek-v4## 🖥 CLI Reference+The interactive TUI (`vibe-trading`) now uses a terminal-native transcript: a startup banner, prompt rule, previous-turn recap, live activity rail, Markdown/table rendering, and run timing all stay in the CLI. Non-interactive invocations such as `vibe-trading run`, pipes, and `--json` remain script-friendly.+```bashvibe-trading # interactive TUIvibe-trading run -p "..." # single rundiff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex 2e437c123..888eb4632 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -784,6 +784,9 @@ class _RunDashboard:return Panel(body, title="Vibe-Trading", border_style="cyan", padding=(1, 1 if compact else 2))+from cli.ui.rail import RailRunDashboard as _RunDashboard # noqa: E402,F811++# ---------------------------------------------------------------------------# Agent execution core# ---------------------------------------------------------------------------@@ -1241,6 +1244,7 @@ def cmd_run(prompt: str, max_iter: int, *, json_mode: bool = False, no_rich: boowith Live(dashboard.render(), console=console, refresh_per_second=6, transient=True) as live:dashboard.live = liveresult = _run_agent(prompt, max_iter=max_iter, dashboard=dashboard)+ dashboard.finish(result, time.perf_counter() - start)except KeyboardInterrupt:if json_mode:_print_json_result({"status": "cancelled", "run_id": None, "run_dir": None, "reason": "Interrupted"})@@ -1334,6 +1338,7 @@ def cmd_continue(max_iter=max_iter,dashboard=dashboard,)+ dashboard.finish(result, time.perf_counter() - start)except KeyboardInterrupt:console.print("\n[yellow]Interrupted[/yellow]")return EXIT_RUN_FAILED@@ -1727,6 +1732,7 @@ def cmd_interactive(max_iter: int) -> None:with Live(dashboard.render(), console=console, refresh_per_second=6, transient=True) as live:dashboard.live = liveresult = _run_agent(user_input, history=history[-6:], max_iter=max_iter, dashboard=dashboard)+ dashboard.finish(result, time.perf_counter() - start)except KeyboardInterrupt:console.print("\n[yellow]Interrupted[/yellow]")continue@@ -3118,6 +3124,10 @@ def main(argv: list[str] | None = None) -> int:args = parser.parse_args(raw_argv)except SystemExit as exc:return int(exc.code) if isinstance(exc.code, int) else EXIT_USAGE_ERROR+ if not sys.stdout.isatty():+ args.no_rich = True+ if hasattr(args, "run_no_rich"):+ args.run_no_rich = Trueif args.command == "init":return cmd_init()diff --git a/agent/cli/components/tool_event.py b/agent/cli/components/tool_event.pyindex da2d9d70d..4c4f3f134 100644--- a/agent/cli/components/tool_event.py+++ b/agent/cli/components/tool_event.py@@ -2,9 +2,9 @@Layout (matches design_proposal §3.5):- ⏺ Get Financials ("AAPL", quarterly, last 8 quarters) 1.4s · 8 quarters+ ● Get Financials ("AAPL", quarterly, last 8 quarters) 1.4s · 8 quarters-* ``⏺`` (U+23FA media-record) marker, color-coded by status:+* ``●`` (U+25CF black circle) marker, color-coded by status:running → ``--warning`` amber (pulse via Rich style ``blink`` whenthe terminal advertises it, otherwise solid amber)ok → ``--success`` green, solid@@ -174,7 +174,7 @@ def render_tool_event(# raising; CLI rendering should never crash the agent loop.status = "running"- marker = Text("⏺ ", style=_STATUS_STYLE[status])+ marker = Text("● ", style=_STATUS_STYLE[status])line = Text()line.append(marker)line.append(_pretty_tool_name(name), style="bold")diff --git a/agent/cli/input.py b/agent/cli/input.pyindex cb0389239..bc96fa144 100644--- a/agent/cli/input.py+++ b/agent/cli/input.py@@ -7,7 +7,7 @@ Wraps a :class:`PromptSession` with:a plain Enter on a balanced buffer submits.* Ctrl+C with three-state semantics (clear buffer → exit hint → exit)* A surrogate-safe :class:`FileHistory` subclass for Windows users- * UTF-8 stdout reconfigure on Windows so the brand glyph ``⏺`` and the+ * UTF-8 stdout reconfigure on Windows so the brand glyph ``●`` and theRich box-drawing characters print without ``UnicodeEncodeError``Cancel-during-generation lives outside the input loop — that is owned by@@ -18,6 +18,7 @@ editing* and *idle* states.from __future__ import annotationsimport sys+import shutilimport timefrom pathlib import Pathfrom typing import Optional@@ -26,6 +27,10 @@ from prompt_toolkit import PromptSessionfrom prompt_toolkit.formatted_text import FormattedTextfrom prompt_toolkit.history import FileHistoryfrom prompt_toolkit.key_binding import KeyBindings+from prompt_toolkit.layout.containers import Window+from prompt_toolkit.layout.controls import FormattedTextControl+from prompt_toolkit.layout.dimension import Dimension+from prompt_toolkit.styles import Style# Sentinel raised by the Ctrl+C path so the caller can distinguish@@ -73,6 +78,32 @@ def _strip_surrogates(text: str) -> str:# ---------------------------------------------------------------- session ----+class _VibePromptSession(PromptSession):+ """PromptSession with a prompt-height that hugs the edited text."""++ def _create_layout(self): # type: ignore[no-untyped-def]+ layout = super()._create_layout()+ # prompt_toolkit's bottom_toolbar is a screen-bottom status bar. Insert+ # our divider directly after the input container so it hugs the prompt.+ layout.container.children.insert(1, _prompt_divider_window())+ return layout++ def _get_default_buffer_control_height(self) -> Dimension: # type: ignore[override]+ line_count = self.default_buffer.document.line_count+ return Dimension.exact(max(1, line_count))+++def _prompt_divider_window() -> Window:+ return Window(+ FormattedTextControl(+ lambda: FormattedText([("class:prompt-border", _prompt_rule())])+ ),+ height=1,+ style="class:prompt-border",+ dont_extend_height=True,+ )++def _force_utf8_stdout() -> None:"""Reconfigure stdout to UTF-8 on Windows so brand glyphs render."""if sys.platform != "win32":@@ -252,7 +283,7 @@ def make_session(history_path: Optional[Path] = None) -> PromptSession:from cli.completer import SlashCompleterctrl_c_state = _CtrlCState()- session = PromptSession(+ session = _VibePromptSession(history=SafeFileHistory(str(path)),completer=SlashCompleter(),complete_while_typing=True,@@ -260,6 +291,13 @@ def make_session(history_path: Optional[Path] = None) -> PromptSession:enable_history_search=True,mouse_support=False,multiline=True,+ reserve_space_for_menu=0,+ style=Style.from_dict(+ {+ "prompt": "#258bff bold",+ "prompt-border": "#4b5563",+ }+ ),)# Expose the state so the outer loop can implement two-press exit.setattr(session, "vibe_ctrl_c_state", ctrl_c_state)@@ -270,7 +308,7 @@ def make_session(history_path: Optional[Path] = None) -> PromptSession:def get_user_input(- prompt_message: str = "> ",+ prompt_message: str = "❯ ",*,session: Optional[PromptSession] = None,) -> str:@@ -284,10 +322,20 @@ def get_user_input(EOFError: When the user hits Ctrl+D, or Ctrl+C on an empty line."""sess = session or make_session()- formatted = FormattedText([("class:prompt", prompt_message)])+ formatted = FormattedText(+ [+ ("class:prompt-border", _prompt_rule() + "\n"),+ ("class:prompt", prompt_message),+ ]+ )return sess.prompt(formatted)+def _prompt_rule() -> str:+ cols = shutil.get_terminal_size((88, 24)).columns+ return "─" * max(10, cols)++def ctrl_c_within_window(session: PromptSession, window_sec: float = _EXIT_HINT_GAP_SEC) -> bool:"""Return True if the most recent Ctrl+C press was a "second press".diff --git a/agent/cli/intro.py b/agent/cli/intro.pyindex 63eb7a68f..d7b204c70 100644--- a/agent/cli/intro.py+++ b/agent/cli/intro.py@@ -1,155 +1,5 @@-"""Startup banner for the interactive CLI.--The layout follows §3.3 of the 2026-05-19 UI/UX design proposal:-- Vibe-Trading v0.2.0- ─────────────────────────────────────────────- Natural-language finance research that- thinks before it answers.-- Model: deepseek/deepseek-v4-pro- Skills: 72 loaded- Tools: 27 registered- Sessions: 3 prior (use /history to browse)-- Try one of these:- > Compare AAPL and MSFT fundamentals- > Backtest a momentum strategy on BTC, 2020-now- > What's the implied vol on TSLA Jan 2026 calls?-- /help for commands · Ctrl+C to clear input · Ctrl+D to exit- ─────────────────────────────────────────────--The wordmark "Vibe-Trading" is rendered in the brand orange (single accent),-everything else uses neutral / dim styles per the "Orange discipline rule".-No emoji, no ASCII-art logo — wordmark-only (proposal §1.3).-"""--from __future__ import annotations--from typing import Final, Sequence--from rich.console import Console-from rich.text import Text--from cli._version import __version__ as _VERSION-from cli.theme import Theme--_TAGLINE: Final[str] = (- "Natural-language finance research that\nthinks before it answers."-)--_DEFAULT_EXAMPLES: Final[tuple[str, ...]] = (- "Compare AAPL and MSFT fundamentals",- "Backtest a momentum strategy on BTC, 2020-now",- "What's the implied vol on TSLA Jan 2026 calls?",-)---def _rule(console: Console, *, width: int = 60) -> None:- """Print a single-character horizontal rule using muted style."""-- char = "─"- target = min(width, max(20, console.size.width - 2))- console.print(Text(char * target, style=Theme.muted))---def print_banner(- console: Console,- *,- model: str,- skills: int,- tools: int,- sessions: int,- examples: Sequence[str] | None = None,- version: str = _VERSION,-) -> None:- """Render the startup banner.-- Args:- console: Shared Rich console (use :func:`cli.theme.get_console`).- model: Active LLM model id, e.g. ``"deepseek/deepseek-v4-pro"``.- skills: Number of skills currently loaded.- tools: Number of tools registered in the agent registry.- sessions: Number of prior sessions on disk. ``0`` suppresses the- "/history to browse" hint.- examples: Three prompt examples to show under "Try one of these:".- Defaults to a curated triplet covering equities / crypto /- options.- version: Override version string (defaults to the package- metadata version via :mod:`cli._version`).-- Notes:- - Wordmark is the *only* primary-orange element (design proposal §1.3- "Orange discipline rule").- - Padding on the left is two spaces, matching dexter's intro.ts.- - Examples are prefixed with ``>`` (not ``•``) so they read as REPL- input prompts, hinting that the user can paste them verbatim.- """-- pad = " "- console.print() # leading blank line-- # ── Wordmark ────────────────────────────────────────────────────────- wordmark = Text()- wordmark.append(pad)- wordmark.append("Vibe-Trading", style=Theme.primary)- wordmark.append(f" v{version}", style=Theme.muted)- console.print(wordmark)-- # ── Rule ────────────────────────────────────────────────────────────- indent = Text(pad)- rule = Text("─" * 50, style=Theme.muted)- console.print(indent + rule)-- # ── Tagline ─────────────────────────────────────────────────────────- for line in _TAGLINE.splitlines():- console.print(Text(pad) + Text(line, style=Theme.muted))- console.print()-- # ── Stats grid ──────────────────────────────────────────────────────- rows: list[tuple[str, str]] = [- ("Model", model),- ("Skills", f"{skills} loaded"),- ("Tools", f"{tools} registered"),- ]- if sessions > 0:- rows.append(("Sessions", f"{sessions} prior (use /history to browse)"))- else:- rows.append(("Sessions", "none yet"))-- label_width = max(len(label) for label, _ in rows) + 2- for label, value in rows:- line = Text(pad)- line.append(f"{label}:".ljust(label_width), style=Theme.label)- line.append(value, style=Theme.muted)- console.print(line)-- console.print()-- # ── Examples ────────────────────────────────────────────────────────- console.print(Text(pad) + Text("Try one of these:", style=Theme.label))- for ex in (examples or _DEFAULT_EXAMPLES):- line = Text(pad)- line.append("> ", style=Theme.primary_dim)- line.append(ex, style=Theme.muted)- console.print(line)-- console.print()-- # ── Footer hint ─────────────────────────────────────────────────────- footer = Text(pad)- footer.append("/help", style=Theme.info)- footer.append(" for commands · ", style=Theme.muted)- footer.append("Ctrl+C", style=Theme.info)- footer.append(" to clear input · ", style=Theme.muted)- footer.append("Ctrl+D", style=Theme.info)- footer.append(" to exit", style=Theme.muted)- console.print(footer)-- # ── Bottom rule ─────────────────────────────────────────────────────- console.print(indent + Text("─" * 60, style=Theme.muted))- console.print()+"""Compatibility wrapper for the interactive startup banner."""+from cli.ui.banner import print_banner__all__ = ["print_banner"]diff --git a/agent/cli/main.py b/agent/cli/main.pyindex 11b91e640..fb3c94df6 100644--- a/agent/cli/main.py+++ b/agent/cli/main.py@@ -235,6 +235,8 @@ class InteractiveContext:agent for follow-up context.max_iter: ReAct iteration ceiling.debug: Whether the ``/debug`` panel is currently shown.+ last_recap_history_len: Number of history messages covered by the+ most recently printed deterministic recap.pending_prompt: Optional prompt queued by a slash handler(``/journal``, ``/shadow``) that the loop should execute asthe next user turn. Consumed by :func:`_interactive_loop`@@ -245,6 +247,7 @@ class InteractiveContext:history: List[Dict[str, str]] = field(default_factory=list)max_iter: int = 50debug: bool = False+ last_recap_history_len: int = 0pending_prompt: Optional[str] = None@@ -575,7 +578,7 @@ def _run_one_turn(user_input: str, ctx: InteractiveContext) -> None:persistent memory, and the ReAct engine remain untouched — we onlyswap in the Rich dashboard and persist the turn to ``SessionStore``."""- from cli._legacy import _RunDashboard, _print_result, _run_agent+ from cli._legacy import _RunDashboard, _run_agentfrom rich.live import Liveconsole = get_console()@@ -602,7 +605,9 @@ def _run_one_turn(user_input: str, ctx: InteractiveContext) -> None:max_iter=ctx.max_iter,dashboard=dashboard,)+ dashboard.finish(result, time.perf_counter() - start)except (KeyboardInterrupt, BrokenPipeError):+ dashboard.close()# BrokenPipe: caller did ``vibe-trading chat | head`` and the# downstream pipe closed mid-render. Print may itself fail on# the closed fd, so swallow that defensively too.@@ -613,7 +618,7 @@ def _run_one_turn(user_input: str, ctx: InteractiveContext) -> None:returnelapsed = time.perf_counter() - start- _print_result(result, elapsed)+ _print_interactive_result(console, result, elapsed)ctx.history.append({"role": "user", "content": user_input})answer = (result.get("content") or "").strip()@@ -625,6 +630,35 @@ def _run_one_turn(user_input: str, ctx: InteractiveContext) -> None:_print_debug_summary(console, result, elapsed, ctx)+def _print_interactive_result(console: Any, result: Dict[str, Any], elapsed: float) -> None:+ """Print the assistant answer after the rail without boxed run panels."""++ from cli.ui.transcript import render_answer, render_elapsed_status++ content = (result.get("content") or "").strip()+ if content:+ console.print(render_answer(content))+ console.print()+ console.print(render_elapsed_status(elapsed))+ run_id = result.get("run_id")+ if run_id:+ console.print(f"[dim]/show {run_id} · {elapsed:.1f}s[/dim]")+++def _print_recap_if_needed(console: Any, ctx: InteractiveContext) -> None:+ """Print a dim recap once per completed turn."""++ if len(ctx.history) <= ctx.last_recap_history_len:+ return+ from cli.ui.transcript import render_recap++ recap = render_recap(ctx.history)+ if recap is not None:+ console.print()+ console.print(recap)+ ctx.last_recap_history_len = len(ctx.history)++def _print_input_hint(console: Any, hint: str) -> None:"""Render the bottom hint bar in muted style."""from cli.components.hint_bar import render_hint_bar@@ -640,8 +674,9 @@ def _interactive_loop(max_iter: int) -> int:"""console = get_console()- # Warm up the preflight in a background thread so the wait is hidden.- _start_preflight_async()+ # Keep the first prompt frame uncontested. The preflight renderer writes to+ # stdout, so running it here races prompt_toolkit on cold start and can make+ # the prompt appear only after the user presses Enter.ctx = InteractiveContext(max_iter=max_iter)@@ -656,7 +691,7 @@ def _interactive_loop(max_iter: int) -> int:# Build the prompt session once so history + completer persist.try:- from cli.input import ctrl_c_within_window, make_session+ from cli.input import ctrl_c_within_window, get_user_input, make_sessionexcept Exception as exc: # noqa: BLE001 — fall back gracefully if prompt_toolkit brokenconsole.print(f"[red]Failed to initialise input layer: {exc}[/red]")console.print("[dim]Falling back to legacy interactive loop.[/dim]")@@ -669,11 +704,11 @@ def _interactive_loop(max_iter: int) -> int:return 0session = make_session()- _print_input_hint(console, "↑/↓ history · / for commands · Esc-Enter newline")while True:+ _print_recap_if_needed(console, ctx)try:- user_input = session.prompt("> ")+ user_input = get_user_input(session=session)except KeyboardInterrupt:# Should not reach here — the keybinding raises EOFError instead.continuediff --git a/agent/cli/stream.py b/agent/cli/stream.pyindex 554f8dd64..992c0aa9a 100644--- a/agent/cli/stream.py+++ b/agent/cli/stream.py@@ -269,7 +269,7 @@ class StreamRenderer:def _print_tool_line(self, call: ToolCall) -> None:line = Text()- line.append("⏺", style=Theme.success)+ line.append("●", style=Theme.success)line.append(" ")line.append(beautify_tool_name(call.name), style=Theme.label)args_preview = summarize_args(@@ -304,7 +304,7 @@ class StreamRenderer:self._spinner = Nonelines = body.splitlines() or [""]head = Text()- head.append("⏺ ", style=Theme.primary)+ head.append("● ", style=Theme.primary)head.append(lines[0])self._console.print(head)for line in lines[1:]:diff --git a/agent/cli/ui/__init__.py b/agent/cli/ui/__init__.pynew file mode 100644index 000000000..43415bd99--- /dev/null+++ b/agent/cli/ui/__init__.py@@ -0,0 +1,14 @@+"""Visual building blocks for the interactive CLI."""++from cli.ui.banner import print_banner+from cli.ui.rail import RailRunDashboard+from cli.ui.transcript import render_answer, render_elapsed_status, render_prompt_footer, render_recap++__all__ = [+ "RailRunDashboard",+ "print_banner",+ "render_answer",+ "render_elapsed_status",+ "render_prompt_footer",+ "render_recap",+]diff --git a/agent/cli/ui/banner.py b/agent/cli/ui/banner.pynew file mode 100644index 000000000..ba92288f3--- /dev/null+++ b/agent/cli/ui/banner.py@@ -0,0 +1,81 @@+"""Large startup banner for the interactive CLI."""++from __future__ import annotations++from typing import Final++from rich.console import Console+from rich.text import Text++from cli._version import __version__ as _VERSION+from cli.theme import Theme++_LOGO: Final[tuple[str, ...]] = (+ r"__ ___ _ _______ _ _ ",+ r"\ \ / (_) | |__ __| | (_) ",+ r" \ \ / / _| |__ ___ | |_ __ __ _ __| |_ _ __ __ _ ",+ r" \ \/ / | | '_ \ / _ \ | | '__/ _` |/ _` | | '_ \ / _` |",+ r" \ / | | |_) | __/ | | | | (_| | (_| | | | | | (_| |",+ r" \/ |_|_.__/ \___| |_|_| \__,_|\__,_|_|_| |_|\__, |",+ r" __/ |",+ r" |___/ ",+)++_GRADIENT_START: Final[tuple[int, int, int]] = (0x25, 0x8B, 0xFF)+_GRADIENT_END: Final[tuple[int, int, int]] = (0xA5, 0xCF, 0xFF)+++def _lerp(start: int, end: int, ratio: float) -> int:+ return round(start + (end - start) * ratio)+++def _gradient_style(index: int, total: int) -> str:+ ratio = 0.0 if total <= 1 else index / (total - 1)+ red = _lerp(_GRADIENT_START[0], _GRADIENT_END[0], ratio)+ green = _lerp(_GRADIENT_START[1], _GRADIENT_END[1], ratio)+ blue = _lerp(_GRADIENT_START[2], _GRADIENT_END[2], ratio)+ return f"bold #{red:02x}{green:02x}{blue:02x}"+++def _gradient_line(line: str) -> Text:+ text = Text()+ total = max(1, len(line.rstrip()))+ for idx, char in enumerate(line):+ text.append(char, style=_gradient_style(idx, total) if char != " " else None)+ return text+++def _center_pad(console: Console, width: int) -> str:+ columns = console.size.width+ if columns >= width + 4:+ return " " * max(0, (columns - width) // 2)+ return " "+++def print_banner(+ console: Console,+ *,+ model: str,+ skills: int,+ tools: int,+ sessions: int,+ version: str = _VERSION,+ mode: str = "cli",+ **_: object,+) -> None:+ """Render the cold-start banner once before the prompt appears."""++ del skills, tools, sessions+ width = max(len(line.rstrip()) for line in _LOGO)+ pad = _center_pad(console, width)++ console.print()+ for line in _LOGO:+ rendered = Text(pad)+ rendered.append(_gradient_line(line.rstrip()))+ console.print(rendered)++ meta = Text(pad)+ meta.append(f"vibe-trading v{version} · {mode} · {model}", style=Theme.muted)+ console.print(meta)+ console.print()diff --git a/agent/cli/ui/rail.py b/agent/cli/ui/rail.pynew file mode 100644index 000000000..a6fff9e47--- /dev/null+++ b/agent/cli/ui/rail.py@@ -0,0 +1,599 @@+"""Codex-style rail renderer for agent activity."""++from __future__ import annotations++import json+import re+import shutil+import textwrap+import threading+import time+from dataclasses import dataclass, field+from pathlib import PureWindowsPath+from typing import Any, Literal+from urllib.parse import urlparse++from rich.console import Group+from rich.text import Text++from cli.theme import Theme+from cli.utils.thinking_verbs import pick_thinking_verb++StepStatus = Literal["active", "done", "error", "warning"]++_MARKER = "#8a8f98"+_MARKER_ACTIVE = "#d1d5db"+_ACTION = "bold white"+_CMD = "bold #3b82f6"+_ARG = "#7dd3fc"+_PATH = "#f0abfc"+_DETAIL = "#6b7280"+_DONE = "bold #22c55e"+_ERROR = "bold #ef4444"+_WARNING = "bold #f59e0b"+_PLAIN_TAG = re.compile(+ r"\[/?(?:#[0-9a-fA-F]{3,6}|[a-zA-Z][a-zA-Z0-9_ -]*)(?:\s+[^\]]+)?\]"+)+_PATH_TOKEN = re.compile(+ r'("[^"]*[\\/][^"]*"|[A-Za-z]:[\\/][^\s,)]+|(?:\.{1,2}[\\/])?[^\s"]*[\\/][^\s"]+)'+)+++@dataclass+class RailStep:+ title: str+ tool: str = ""+ args: Any = None+ status: StepStatus = "active"+ lines: list[str] = field(default_factory=list)+ started_at: float = field(default_factory=time.monotonic)+ duration_s: float = 0.0+++def _strip_markup(value: Any) -> str:+ return _PLAIN_TAG.sub("", str(value or "")).replace("\r\n", "\n").strip()+++def _collapse_ws(value: Any) -> str:+ return re.sub(r"\s+", " ", _strip_markup(value)).strip()+++def _coerce_int(value: Any) -> int:+ try:+ return max(0, int(value or 0))+ except (TypeError, ValueError):+ return 0+++def _format_tool_name(name: str) -> str:+ cleaned = str(name or "tool").strip().replace("-", " ").replace("_", " ")+ if cleaned.lower().startswith("get "):+ cleaned = cleaned[4:]+ return " ".join(part[:1].upper() + part[1:] for part in cleaned.split()) or "Tool"+++def _tool_title(tool: str, args: Any) -> str:+ lower = str(tool or "tool").lower()+ if lower in {"bash", "background_run", "shell"}:+ return "shell command"+ if lower == "load_skill":+ return "skill"+ if lower in {"read_file", "file_read"}:+ return "file"+ if lower in {"write_file", "edit_file"}:+ return "file"+ if lower in {"read_url", "web_fetch", "fetch", "read_url_tool"}:+ return "url"+ if "search" in lower:+ return "web"+ if lower in {"get_market_data", "market_data", "stock_price", "get_stock_price"}:+ return "market data"+ if lower in {"answer", "final_answer"}:+ return "answer"+ return _format_tool_name(tool)+++def _arg_value(args: Any, *keys: str) -> str:+ if not isinstance(args, dict):+ return ""+ for key in keys:+ value = args.get(key)+ if value:+ return _collapse_ws(value)+ return ""+++def _initial_detail(tool: str, args: Any) -> str | None:+ if not isinstance(args, dict):+ return None+ lower = str(tool or "").lower()+ if lower in {"bash", "background_run", "shell"}:+ return None+ if lower in {"read_file", "file_read", "write_file", "edit_file"}:+ return _arg_value(args, "path", "file_path") or None+ if lower in {"read_url", "web_fetch", "fetch", "read_url_tool"}:+ url = _arg_value(args, "url")+ return f"fetching {_short_url(url)}" if url else None+ if "search" in lower:+ query = _arg_value(args, "query", "q")+ return query or None+ symbol = _arg_value(args, "symbol", "ticker", "code", "asset")+ return symbol or None+++def _result_summary(tool: str, status: str, preview: Any) -> list[str]:+ text = _strip_markup(preview)+ lower = str(tool or "").lower()+ if lower == "load_skill":+ match = re.search(r"<skill\s+name=[\"']?([^\"'>\s]+)", text)+ if match:+ return [f"loaded {match.group(1)}"]++ payload: Any = None+ compact = _collapse_ws(text)+ source = text.strip()+ if source.startswith("{") or source.startswith("["):+ try:+ payload = json.loads(source)+ except json.JSONDecodeError:+ try:+ payload = json.loads(compact)+ except json.JSONDecodeError:+ payload = None++ if isinstance(payload, dict):+ if status != "ok":+ detail = payload.get("error") or payload.get("stderr") or payload.get("message") or compact+ return _compact_lines(f"Error: {_collapse_ws(detail)}", max_lines=3)+ if lower in {"bash", "background_run", "shell"}:+ stdout = payload.get("stdout")+ stderr = payload.get("stderr")+ if stdout:+ return _compact_lines(str(stdout), max_lines=5)+ if stderr:+ return _compact_lines(str(stderr), max_lines=4)+ return ["completed"]+ if lower in {"read_file", "file_read"}:+ content = str(payload.get("content") or "")+ return [f"read {len(content):,} chars"] if content else ["read file"]+ if lower == "load_skill":+ content = str(payload.get("content") or "")+ match = re.search(r"<skill\s+name=[\"']([^\"']+)[\"']", content)+ return [f"loaded {match.group(1)}"] if match else ["loaded skill"]+ if lower in {"read_url", "web_fetch", "fetch", "read_url_tool"}:+ title = payload.get("title")+ if title:+ return [_clip(_collapse_ws(title), 96)]+ content = payload.get("content") or payload.get("markdown") or payload.get("text")+ if content:+ return [f"read {len(str(content)):,} chars"]+ results = payload.get("results")+ if isinstance(results, list):+ return [f"Did 1 search · {len(results)} results"]+ for key in ("summary", "message", "stdout", "content"):+ if payload.get(key):+ return _compact_lines(str(payload[key]), max_lines=4)++ if not compact:+ return []+ if status != "ok":+ return _compact_lines(f"Error: {compact}", max_lines=3)+ return _compact_lines(text, max_lines=4)+++def _compact_lines(value: str, *, max_lines: int) -> list[str]:+ raw_lines = [line.rstrip() for line in _strip_markup(value).splitlines() if line.strip()]+ if not raw_lines:+ return []+ clipped = [_clip_preserve(line, 112) for line in raw_lines]+ if len(clipped) <= max_lines:+ return clipped+ head_count = max(1, max_lines // 2)+ tail_count = max(1, max_lines - head_count - 1)+ hidden = len(clipped) - head_count - tail_count+ return [+ *clipped[:head_count],+ f"... +{hidden} lines (ctrl + t to view transcript)",+ *clipped[-tail_count:],+ ]+++def _short_url(url: str, limit: int = 64) -> str:+ if not url:+ return ""+ try:+ parsed = urlparse(url)+ except ValueError:+ return _clip(url, limit)+ if not parsed.netloc:+ return _clip(url, limit)+ display = parsed.netloc + parsed.path+ return _clip(display.rstrip("/") or parsed.netloc, limit)+++def _clip(text: str, limit: int) -> str:+ text = _collapse_ws(text)+ if len(text) <= limit:+ return text+ return text[: max(1, limit - 1)].rstrip() + "…"+++def _clip_preserve(text: str, limit: int) -> str:+ if len(text) <= limit:+ return text+ return text[: max(1, limit - 1)].rstrip() + "…"+++def _wrap(text: str, width: int) -> list[str]:+ if width <= 8:+ return [_clip_preserve(text, max(1, width))]+ return textwrap.wrap(+ text,+ width=width,+ break_long_words=False,+ break_on_hyphens=False,+ replace_whitespace=False,+ drop_whitespace=False,+ ) or [""]+++def _command_from_args(args: Any) -> str:+ return _arg_value(args, "command", "cmd")+++def _split_command(command: str) -> tuple[str, str]:+ command = _collapse_ws(command)+ if not command:+ return "", ""+ if command.startswith('"'):+ end = command.find('"', 1)+ if end > 0:+ return _display_executable(command[1:end]), command[end + 1 :].strip()+ first, _, rest = command.partition(" ")+ return _display_executable(first.strip('"')), rest.strip()+++def _display_executable(executable: str) -> str:+ if not executable:+ return ""+ cleaned = executable.strip('"')+ if "\\" in cleaned or "/" in cleaned:+ cleaned = PureWindowsPath(cleaned).name+ if cleaned.lower().endswith(".exe"):+ cleaned = cleaned[:-4]+ return cleaned or executable+++def _append_arg_text(line: Text, args: str, *, limit: int) -> None:+ args = _clip(args, limit)+ if not args:+ return+ pos = 0+ for match in _PATH_TOKEN.finditer(args):+ if match.start() > pos:+ line.append(args[pos : match.start()], style=_ARG)+ line.append(match.group(0), style=_PATH)+ pos = match.end()+ if pos < len(args):+ line.append(args[pos:], style=_ARG)+++class RailRunDashboard:+ """Compatibility dashboard that renders agent events like Codex transcripts."""++ def __init__(self, prompt: str, max_iter: int) -> None:+ self.prompt = prompt+ self.max_iter = max_iter+ self.start_time = time.monotonic()+ self.iterations = 0+ self.live: Any = None+ self.steps: list[RailStep] = []+ self.latest_text = ""+ self.thinking_active = True+ self.completion_summary: str | None = None+ self.status: str = "running"+ self.thinking_verb = pick_thinking_verb()+ self.input_tokens = 0+ self.output_tokens = 0+ self._last_progress_render = 0.0+ self._ticker_stop = threading.Event()+ self._ticker = threading.Thread(+ target=self._tick,+ daemon=True,+ name="vibe-rail-ticker",+ )+ self._ticker.start()++ def _tick(self) -> None:+ while not self._ticker_stop.wait(1.0):+ if self.status == "running" and self.live is not None:+ self.refresh()++ def close(self) -> None:+ self._ticker_stop.set()++ def refresh(self) -> None:+ if self.live is not None:+ self.live.update(self.render())++ def handle_event(self, event_type: str, data: dict[str, Any]) -> None:+ if event_type == "text_delta":+ delta = _collapse_ws(data.get("delta"))+ if delta:+ self.latest_text = (self.latest_text + delta).strip()[-500:]+ self._append_to_active(delta, throttle=True)+ self.refresh()+ return++ if event_type == "thinking_done":+ self.thinking_active = False+ self.refresh()+ return++ if event_type == "llm_usage":+ input_tokens = _coerce_int(data.get("input_tokens"))+ output_tokens = _coerce_int(data.get("output_tokens"))+ total_tokens = _coerce_int(data.get("total_tokens"))+ if input_tokens or output_tokens:+ self.input_tokens += input_tokens+ self.output_tokens += output_tokens+ else:+ self.output_tokens += total_tokens+ self.refresh()+ return++ if event_type == "tool_call":+ self.thinking_active = False+ tool = str(data.get("tool") or "tool")+ args = data.get("arguments") or {}+ self.iterations += 1+ step = RailStep(title=_tool_title(tool, args), tool=tool, args=args)+ detail = _initial_detail(tool, args)+ if detail:+ step.lines.append(detail)+ self.steps.append(step)+ self.steps = self.steps[-10:]+ self.refresh()+ return++ if event_type == "tool_progress":+ tool = str(data.get("tool") or "")+ step = self._active_step(tool)+ pieces: list[str] = []+ stage = _collapse_ws(data.get("stage"))+ current = data.get("current")+ total = data.get("total")+ message = _collapse_ws(data.get("message"))+ if stage:+ pieces.append(stage)+ if isinstance(current, int) and isinstance(total, int) and total > 0:+ pieces.append(f"{current}/{total}")+ if message:+ pieces.append(message)+ if pieces:+ step.lines.append(" · ".join(pieces))+ step.lines = step.lines[-6:]+ now = time.monotonic()+ if now - self._last_progress_render >= 0.2:+ self._last_progress_render = now+ self.refresh()+ return++ if event_type == "tool_heartbeat":+ tool = str(data.get("tool") or "")+ self._active_step(tool)+ self.refresh()+ return++ if event_type == "tool_result":+ tool = str(data.get("tool") or "")+ status = str(data.get("status") or "ok")+ step = self._active_step(tool)+ step.status = "done" if status == "ok" else "error"+ step.duration_s = float(data.get("elapsed_ms") or 0.0) / 1000+ for line in _result_summary(tool, status, data.get("preview")):+ if not step.lines or step.lines[-1] != line:+ if step.lines and step.lines[-1].startswith("still running…"):+ step.lines[-1] = line+ else:+ step.lines.append(line)+ step.lines = step.lines[-7:]+ self.refresh()+ return++ if event_type == "compact":+ tokens = data.get("tokens_before", "?")+ self.steps.append(+ RailStep(+ title="context",+ tool="compact",+ status="warning",+ lines=[f"{tokens} tokens summarized"],+ duration_s=0.0,+ )+ )+ self.steps = self.steps[-10:]+ self.refresh()++ def finish(self, result: dict[str, Any], elapsed: float | None = None) -> None:+ self.status = str(result.get("status") or "done")+ for step in self.steps:+ if step.status == "active":+ step.status = "done"+ if not step.duration_s and elapsed is not None:+ step.duration_s = max(0.0, elapsed)+ content = _collapse_ws(result.get("content"))+ reason = _collapse_ws(result.get("reason"))+ if content:+ self.completion_summary = "Done."+ elif reason:+ self.completion_summary = f"{self.status.title()}. {reason}"+ else:+ self.completion_summary = f"{self.status.title()}."+ self.thinking_active = False+ self.refresh()+ self.close()++ def render(self) -> Group:+ width = max(44, shutil.get_terminal_size((88, 24)).columns)+ detail_width = max(18, width - 7)+ rows: list[Text] = []++ for step in self.steps:+ rows.append(self._step_line(step, width=max(18, width - 3)))+ for line in self._render_lines(step):+ rows.extend(self._detail_lines(line, width=detail_width, active=step.status == "active"))++ if self.completion_summary is None:+ rows.append(self._activity_line())++ if self.completion_summary is not None:+ if rows:+ rows.append(Text(""))+ rows.append(self._finish_line(self.completion_summary))++ return Group(*rows)++ def _render_lines(self, step: RailStep) -> list[str]:+ lines = list(step.lines)+ return lines[-7:]++ def _active_step(self, tool: str) -> RailStep:+ raw_tool = str(tool or "")+ for step in reversed(self.steps):+ if step.status == "active" and (not raw_tool or step.tool == raw_tool):+ return step+ step = RailStep(title=_tool_title(raw_tool or "tool", None), tool=raw_tool)+ self.steps.append(step)+ self.steps = self.steps[-10:]+ return step++ def _append_to_active(self, text: str, *, throttle: bool) -> None:+ if not text:+ return+ now = time.monotonic()+ if throttle and now - self._last_progress_render < 0.2:+ return+ self._last_progress_render = now+ if self.steps and self.steps[-1].status == "active":+ self.steps[-1].lines.append(_clip(text, 112))+ self.steps[-1].lines = self.steps[-1].lines[-6:]++ def _activity_line(self) -> Text:+ elapsed = time.monotonic() - self.start_time+ line = Text()+ line.append("·", style=_MARKER_ACTIVE)+ line.append(" ")+ line.append(self.thinking_verb, style=Theme.muted)+ line.append(f" ({elapsed:.0f}s)", style=Theme.muted)+ return line++ def _step_line(self, step: RailStep, *, width: int) -> Text:+ marker_style = _MARKER_ACTIVE if step.status == "active" else _MARKER+ if step.status == "error":+ marker_style = _ERROR+ elif step.status == "warning":+ marker_style = _WARNING++ line = Text()+ line.append("•", style=marker_style)+ line.append(" ")++ lower = step.tool.lower()+ if lower in {"bash", "background_run", "shell"}:+ verb = "Running" if step.status == "active" else "Ran"+ command = _command_from_args(step.args)+ exe, rest = _split_command(command)+ duration = self._duration_label(step)+ budget = max(12, width - len(verb) - len(exe) - len(duration) - 7)+ line.append(verb, style=_ACTION)+ if exe:+ line.append(" ")+ line.append(exe, style=_CMD)+ if rest:+ line.append(" ")+ _append_arg_text(line, rest, limit=budget)+ elif not exe:+ line.append(" shell command", style=_ACTION)+ self._append_duration(line, duration)+ return line++ action = self._action_label(step)+ duration = self._duration_label(step)+ line.append(action, style=_ACTION)+ detail = self._title_detail(step)+ if detail:+ line.append(" ")+ if _looks_like_path(detail):+ line.append(_clip(detail, max(12, width - len(action) - len(duration) - 6)), style=_PATH)+ else:+ line.append(_clip(detail, max(12, width - len(action) - len(duration) - 6)), style=_ARG)+ self._append_duration(line, duration)+ return line++ def _duration_label(self, step: RailStep) -> str:+ return ""++ def _append_duration(self, line: Text, duration: str) -> None:+ if duration:+ line.append(" ")+ line.append(duration, style=Theme.muted)++ def _action_label(self, step: RailStep) -> str:+ lower = step.tool.lower()+ active = step.status == "active"+ if lower == "load_skill":+ return "Loading skill…" if active else "Loaded skill"+ if lower in {"read_file", "file_read"}:+ return "Reading file…" if active else "Read file"+ if lower in {"write_file", "edit_file"}:+ return "Writing file…" if active else "Wrote file"+ if lower in {"read_url", "web_fetch", "fetch", "read_url_tool"}:+ return "Fetching…" if active else "Fetched"+ if "search" in lower:+ return "Searching web…" if active else "Searched web"+ if lower in {"get_market_data", "market_data", "stock_price", "get_stock_price"}:+ return "Reading market data…" if active else "Read market data"+ if lower == "compact":+ return "Compacted context"+ return step.title++ def _title_detail(self, step: RailStep) -> str:+ args = step.args+ lower = step.tool.lower()+ if lower == "load_skill":+ return _arg_value(args, "name", "skill")+ if lower in {"read_file", "file_read", "write_file", "edit_file"}:+ return _arg_value(args, "path", "file_path")+ if lower in {"read_url", "web_fetch", "fetch", "read_url_tool"}:+ return _short_url(_arg_value(args, "url"))+ if "search" in lower:+ query = _arg_value(args, "query", "q")+ return f'"{query}"' if query else ""+ return _arg_value(args, "symbol", "ticker", "code", "asset")++ def _detail_lines(self, body: str, *, width: int, active: bool) -> list[Text]:+ style = _DETAIL+ parts = _wrap(_strip_markup(body), width)+ rows: list[Text] = []+ for index, part in enumerate(parts):+ line = Text(" ")+ if index == 0:+ line.append("└", style=style)+ line.append(" ")+ else:+ line.append(" ")+ line.append(part, style=style)+ rows.append(line)+ return rows++ def _finish_line(self, summary: str) -> Text:+ line = Text()+ line.append("•", style=_DONE if self.status in {"success", "ok", "done"} else _WARNING)+ line.append(" ")+ line.append(summary, style="bold")+ return line+++def _looks_like_path(value: str) -> bool:+ return bool(_PATH_TOKEN.search(value))diff --git a/agent/cli/ui/transcript.py b/agent/cli/ui/transcript.pynew file mode 100644index 000000000..dc9c137ac--- /dev/null+++ b/agent/cli/ui/transcript.py@@ -0,0 +1,167 @@+"""Transcript helpers for the interactive CLI."""++from __future__ import annotations++import re+import shutil+from typing import Any++from rich import box+from rich.console import Group+from rich.markdown import Markdown+from rich.table import Table+from rich.text import Text++from cli.theme import Theme++_PIPE_SEPARATOR = re.compile(r"^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$")+_PROMPT_BORDER = "#4b5563"+_MUTED = "#6b7280"+++def render_prompt_footer(width: int | None = None) -> Text:+ """Bottom border printed after prompt_toolkit accepts the user input."""++ cols = width or shutil.get_terminal_size((88, 24)).columns+ return Text("─" * max(10, cols), style=_PROMPT_BORDER)+++def render_recap(history: list[dict[str, str]]) -> Text | None:+ """Return a deterministic dim recap of the previous turn."""++ user = ""+ assistant = ""+ for message in reversed(history):+ role = message.get("role")+ content = (message.get("content") or "").strip()+ if not content:+ continue+ if role == "assistant" and not assistant:+ assistant = content+ elif role == "user" and not user:+ user = content+ if user and assistant:+ break+ if not user and not assistant:+ return None++ parts = []+ if user:+ parts.append(f"Last request: {_sentence(user, 92)}")+ if assistant:+ parts.append(f"Result: {_sentence(assistant, 128)}")+ line = Text("※ recap: ", style=Theme.muted)+ line.append("; ".join(parts), style=Theme.muted)+ return line+++def render_elapsed_status(elapsed: float) -> Text:+ """Render the post-run timing line."""++ line = Text("✻ ", style=_MUTED)+ line.append("Analyzed", style=Theme.muted)+ line.append(f" for {_format_duration(elapsed)}", style=Theme.muted)+ return line+++def render_answer(content: str) -> Group:+ """Render assistant Markdown, upgrading pipe tables to Rich tables."""++ blocks: list[Any] = []+ pending: list[str] = []++ def flush_pending() -> None:+ if pending:+ blocks.append(Markdown("\n".join(pending).strip()))+ pending.clear()++ lines = content.splitlines()+ index = 0+ while index < len(lines):+ if _is_table_start(lines, index):+ flush_pending()+ table_lines = [lines[index], lines[index + 1]]+ index += 2+ while index < len(lines) and _is_pipe_row(lines[index]):+ table_lines.append(lines[index])+ index += 1+ table = _parse_table(table_lines)+ if table is not None:+ blocks.append(table)+ else:+ pending.extend(table_lines)+ continue+ pending.append(lines[index])+ index += 1++ flush_pending()+ return Group(*blocks) if blocks else Group(Text(content))+++def _is_table_start(lines: list[str], index: int) -> bool:+ return (+ index + 1 < len(lines)+ and _is_pipe_row(lines[index])+ and bool(_PIPE_SEPARATOR.match(lines[index + 1]))+ )+++def _is_pipe_row(line: str) -> bool:+ stripped = line.strip()+ return stripped.startswith("|") and stripped.endswith("|") and stripped.count("|") >= 2+++def _parse_table(lines: list[str]) -> Table | None:+ if len(lines) < 2:+ return None+ headers = _split_row(lines[0])+ rows = [_split_row(line) for line in lines[2:] if _is_pipe_row(line)]+ if not headers or not rows:+ return None++ table = Table(+ box=box.SQUARE,+ show_header=True,+ show_lines=True,+ header_style="bold white",+ border_style="dim",+ padding=(0, 1),+ )+ for header in headers:+ table.add_column(_clean_inline_markdown(header), overflow="fold")+ for row in rows:+ cells = list(row[: len(headers)])+ while len(cells) < len(headers):+ cells.append("")+ table.add_row(*[_clean_inline_markdown(cell) for cell in cells])+ return table+++def _split_row(line: str) -> list[str]:+ stripped = line.strip().strip("|")+ return [cell.strip() for cell in stripped.split("|")]+++def _clean_inline_markdown(text: str) -> str:+ cleaned = re.sub(r"(\*\*|__)(.*?)\1", r"\2", text)+ cleaned = re.sub(r"(\*|_)(.*?)\1", r"\2", cleaned)+ cleaned = re.sub(r"`([^`]+)`", r"\1", cleaned)+ return cleaned.strip()+++def _sentence(text: str, limit: int) -> str:+ collapsed = re.sub(r"\s+", " ", _clean_inline_markdown(text)).strip()+ if len(collapsed) <= limit:+ return collapsed+ return collapsed[: max(1, limit - 1)].rstrip() + "…"+++def _format_duration(seconds: float) -> str:+ total = max(0, int(round(seconds)))+ if total < 60:+ return f"{total}s"+ minutes, secs = divmod(total, 60)+ if minutes < 60:+ return f"{minutes}m {secs:02d}s"+ hours, minutes = divmod(minutes, 60)+ return f"{hours}h {minutes:02d}m {secs:02d}s"diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex e1191eb88..932e43e92 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -393,6 +393,17 @@ class AgentLoop:tools=self.registry.get_definitions(),on_text_chunk=_on_text_chunk,)+ usage = getattr(response, "usage_metadata", None) or {}+ if usage:+ self._emit(+ "llm_usage",+ {+ "input_tokens": int(usage.get("input_tokens") or 0),+ "output_tokens": int(usage.get("output_tokens") or 0),+ "total_tokens": int(usage.get("total_tokens") or 0),+ "iter": iteration,+ },+ )thinking_text = "".join(thinking_chunks)if thinking_text:diff --git a/agent/tests/test_cli_ui_redesign.py b/agent/tests/test_cli_ui_redesign.pynew file mode 100644index 000000000..8cb31136e--- /dev/null+++ b/agent/tests/test_cli_ui_redesign.py@@ -0,0 +1,145 @@+from __future__ import annotations++from rich.console import Console++from cli.ui.banner import print_banner+from cli.ui.rail import RailRunDashboard+from cli.ui.transcript import render_answer, render_elapsed_status, render_prompt_footer, render_recap+++def _render(renderable) -> str:+ console = Console(record=True, force_terminal=False, color_system=None, width=100)+ console.print(renderable)+ return console.export_text()+++def test_rail_uses_codex_marker_and_output_branch() -> None:+ dash = RailRunDashboard("check price", 50)+ dash.handle_event("tool_call", {"tool": "get_market_data", "arguments": {"symbol": "AAPL"}})+ dash.handle_event(+ "tool_progress",+ {"tool": "get_market_data", "stage": "fetch", "current": 1, "total": 2, "message": "downloaded candles"},+ )+ dash.handle_event("tool_result", {"tool": "get_market_data", "status": "ok", "elapsed_ms": 1200, "preview": "AAPL 195.00"})+ dash.finish({"status": "success", "content": "AAPL is trading near 195.00."}, 1.2)++ out = _render(dash.render())++ assert "• Read market data AAPL" in out+ assert "└ AAPL" in out+ assert "└ fetch · 1/2 · downloaded candles" in out+ assert "• Done." in out+ assert "●" not in out+ assert "⏺" not in out+++def test_rail_renders_codex_style_shell_transcript() -> None:+ dash = RailRunDashboard("show status", 50)+ dash.handle_event(+ "tool_call",+ {+ "tool": "bash",+ "arguments": {"command": "git status --short agent\\cli\\main.py docs\\screenshots\\boot.png"},+ },+ )+ dash.handle_event(+ "tool_result",+ {+ "tool": "bash",+ "status": "ok",+ "elapsed_ms": 200,+ "preview": (+ '{"status":"ok","stdout":"M CHANGELOG.md\\n M agent/.env.example\\n'+ 'M agent/cli/main.py\\nA docs/screenshots/boot.png\\n'+ 'A docs/screenshots/agent-run.png\\n","stderr":""}'+ ),+ },+ )++ out = _render(dash.render())++ assert "• Ran git status --short agent\\cli\\main.py docs\\screenshots\\boot.png" in out+ assert "└ M CHANGELOG.md" in out+ assert "M agent/.env.example" in out+ assert "A docs/screenshots/boot.png" in out+++def test_run_elapsed_is_rendered_as_last_status_line() -> None:+ dash = RailRunDashboard("long command", 50)+ dash.handle_event(+ "tool_call",+ {"tool": "bash", "arguments": {"command": "python slow_task.py"}},+ )+ dash.start_time -= 2.2++ out = _render(dash.render())+ dash.close()++ assert "Running python slow_task.py" in out+ assert "2s" in out+ assert "tokens" not in out+ assert out.rstrip().splitlines()[-1].startswith("· ")+++def test_initial_rail_renders_status_line_without_steps() -> None:+ dash = RailRunDashboard("starting", 50)+ dash.start_time -= 1.2++ out = _render(dash.render())+ dash.close()++ assert out.rstrip().startswith("· ")+ assert "1s" in out+++def test_banner_renders_large_logo_and_metadata() -> None:+ console = Console(record=True, force_terminal=False, color_system=None, width=100)+ print_banner(console, model="test-model", skills=1, tools=2, sessions=0, version="9.9.9")+ out = console.export_text()++ assert "__ ___ _" in out+ assert "vibe-trading v9.9.9 · cli · test-model" in out+++def test_transcript_helpers_render_prompt_recap_and_elapsed() -> None:+ recap = render_recap(+ [+ {"role": "user", "content": "check the price of AAPL"},+ {"role": "assistant", "content": "AAPL is trading near $217.61."},+ ]+ )++ assert recap is not None+ assert "※ recap:" in recap.plain+ assert "Last request: check the price of AAPL" in recap.plain+ assert render_elapsed_status(159).plain == "✻ Analyzed for 2m 39s"+ assert render_prompt_footer(width=16).plain == "────────────────"+++def test_interactive_result_prints_elapsed_after_answer() -> None:+ from cli.main import _print_interactive_result++ console = Console(record=True, force_terminal=False, color_system=None, width=100)+ _print_interactive_result(+ console,+ {"status": "success", "content": "Final answer text."},+ 56,+ )+ out = console.export_text()++ assert out.index("Final answer text.") < out.index("Analyzed for 56s")+++def test_answer_renderer_upgrades_markdown_pipe_tables() -> None:+ content = """AAPL snapshot:++| Metric | Value |+|------|------|+| **Last** | **$217.61** |+| Change | -$1.90 (-0.86%) |+"""+ out = _render(render_answer(content))++ assert "$217.61" in out+ assert "Metric" in out+ assert "| **Last** | **$217.61** |" not in out