Add show_reasoning config (default: False) to display model thinking/reasoning content in the TUI during streaming. Reasoning is emitted via a new emit_reasoning hook on AgentHook, gated by the channels config. Display uses ✻ prefix with dim italic styling. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
181 lines
5.8 KiB
Python
181 lines
5.8 KiB
Python
"""Streaming renderer for CLI output.
|
|
|
|
Uses Rich Live with ``transient=True`` for in-place markdown updates during
|
|
streaming. After the live display stops, a final clean render is printed
|
|
so the content persists on screen. ``transient=True`` ensures the live
|
|
area is erased before ``stop()`` returns, avoiding the duplication bug
|
|
that plagued earlier approaches.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import sys
|
|
|
|
from rich.console import Console
|
|
from rich.live import Live
|
|
from rich.markdown import Markdown
|
|
from rich.text import Text
|
|
|
|
from nanobot import __logo__
|
|
|
|
|
|
def _make_console() -> Console:
|
|
"""Create a Console that emits plain text when stdout is not a TTY.
|
|
|
|
Rich's spinner, Live render, and cursor-visibility escape codes all
|
|
key off ``Console.is_terminal``. Forcing ``force_terminal=True`` overrode
|
|
the ``isatty()`` check and caused control sequences (``\\x1b[?25l``,
|
|
braille spinner frames) to pollute programmatic consumers such as
|
|
``docker exec -i`` or pipes, even with ``NO_COLOR`` or ``TERM=dumb``.
|
|
Deferring to ``isatty()`` keeps Rich output in interactive terminals
|
|
and plain text everywhere else (#3265).
|
|
"""
|
|
return Console(file=sys.stdout, force_terminal=sys.stdout.isatty())
|
|
|
|
|
|
class ThinkingSpinner:
|
|
"""Spinner that shows 'nanobot is thinking...' with pause support."""
|
|
|
|
def __init__(self, console: Console | None = None):
|
|
c = console or _make_console()
|
|
self._spinner = c.status("[dim]nanobot is thinking...[/dim]", spinner="dots")
|
|
self._active = False
|
|
|
|
def __enter__(self):
|
|
self._spinner.start()
|
|
self._active = True
|
|
return self
|
|
|
|
def __exit__(self, *exc):
|
|
self._active = False
|
|
self._spinner.stop()
|
|
return False
|
|
|
|
def pause(self):
|
|
"""Context manager: temporarily stop spinner for clean output."""
|
|
from contextlib import contextmanager
|
|
|
|
@contextmanager
|
|
def _ctx():
|
|
if self._spinner and self._active:
|
|
self._spinner.stop()
|
|
try:
|
|
yield
|
|
finally:
|
|
if self._spinner and self._active:
|
|
self._spinner.start()
|
|
|
|
return _ctx()
|
|
|
|
|
|
class StreamRenderer:
|
|
"""Streaming renderer with Rich Live for in-place updates.
|
|
|
|
During streaming: updates content in-place via Rich Live.
|
|
On end: stops Live (transient=True erases it), then prints final render.
|
|
|
|
Flow per round:
|
|
spinner -> first delta -> header + Live updates ->
|
|
on_end -> stop Live + final render
|
|
"""
|
|
|
|
def __init__(self, render_markdown: bool = True, show_spinner: bool = True):
|
|
self._md = render_markdown
|
|
self._show_spinner = show_spinner
|
|
self._buf = ""
|
|
self.streamed = False
|
|
self._console = _make_console()
|
|
self._live: Live | None = None
|
|
self._spinner: ThinkingSpinner | None = None
|
|
self._start_spinner()
|
|
|
|
def _renderable(self):
|
|
"""Create a renderable from the current buffer."""
|
|
if self._md and self._buf:
|
|
return Markdown(self._buf)
|
|
return Text(self._buf or "")
|
|
|
|
def _render_str(self) -> str:
|
|
"""Render current buffer to a plain string via Rich."""
|
|
with self._console.capture() as cap:
|
|
self._console.print(self._renderable())
|
|
return cap.get()
|
|
|
|
def _start_spinner(self) -> None:
|
|
if self._show_spinner:
|
|
self._spinner = ThinkingSpinner()
|
|
self._spinner.__enter__()
|
|
|
|
def _stop_spinner(self) -> None:
|
|
if self._spinner:
|
|
self._spinner.__exit__(None, None, None)
|
|
self._spinner = None
|
|
|
|
@property
|
|
def console(self) -> Console:
|
|
"""Expose the Live's console so external print functions can use it."""
|
|
return self._console
|
|
|
|
def pause_spinner(self):
|
|
"""Context manager: temporarily stop spinner for clean output."""
|
|
if self._spinner:
|
|
return self._spinner.pause()
|
|
from contextlib import nullcontext
|
|
return nullcontext()
|
|
|
|
async def on_delta(self, delta: str) -> None:
|
|
self.streamed = True
|
|
self._buf += delta
|
|
if self._live is None:
|
|
if not self._buf.strip():
|
|
return
|
|
self._stop_spinner()
|
|
self._console.print()
|
|
self._console.print(f"[cyan]{__logo__} nanobot[/cyan]")
|
|
self._live = Live(
|
|
self._renderable(),
|
|
console=self._console,
|
|
auto_refresh=False,
|
|
transient=True,
|
|
)
|
|
self._live.start()
|
|
else:
|
|
self._live.update(self._renderable())
|
|
self._live.refresh()
|
|
|
|
async def on_end(self, *, resuming: bool = False) -> None:
|
|
if self._live:
|
|
# Double-refresh to sync _shape before stop() calls refresh().
|
|
self._live.refresh()
|
|
self._live.update(self._renderable())
|
|
self._live.refresh()
|
|
self._live.stop()
|
|
self._live = None
|
|
self._stop_spinner()
|
|
if self._buf.strip():
|
|
# Print final rendered content (persists after Live is gone).
|
|
out = sys.stdout
|
|
out.write(self._render_str())
|
|
out.flush()
|
|
if resuming:
|
|
self._buf = ""
|
|
self._start_spinner()
|
|
|
|
def stop_for_input(self) -> None:
|
|
"""Stop spinner before user input to avoid prompt_toolkit conflicts."""
|
|
self._stop_spinner()
|
|
|
|
def pause(self):
|
|
"""Context manager: pause spinner for external output. No-op once streaming has started."""
|
|
from contextlib import nullcontext
|
|
if self._spinner:
|
|
return self._spinner.pause()
|
|
return nullcontext()
|
|
|
|
async def close(self) -> None:
|
|
"""Stop spinner/live without rendering a final streamed round."""
|
|
if self._live:
|
|
self._live.stop()
|
|
self._live = None
|
|
self._stop_spinner()
|