Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(tui): add rich textual chat interface (#2507)
DavdGao3c9d5a90dccb
diff --git a/examples/tui/README.md b/examples/tui/README.mdnew file mode 100644index 000000000..d16f67b41--- /dev/null+++ b/examples/tui/README.md@@ -0,0 +1,161 @@+# Terminal UI++This example runs an AgentScope agent in the optional Textual terminal UI.+The UI renders `Msg` snapshots, Markdown, tools, and tool-call confirmation.+The standalone launcher consumes Agent events and maintains the messages;+the display widgets do not consume events or modify conversation history.++## Quickstart++```bash+pip install "agentscope[tui]"+export DASHSCOPE_API_KEY=sk-...+python main.py+```++Controls:++- `Enter` sends the current message and `Shift+Enter` inserts a newline.+- While a reply is running, `Ctrl+C` interrupts that reply.+- HITL uses `↑`/`↓` to choose an action and `Enter` to confirm it; there are+ no clickable action buttons.+- Tool and thinking rows expand with a click or with `Enter` when focused.+- A pending HITL request replaces the composer until it is resolved.+- `AskUser` renders a keyboard-driven form with single-select, multi-select,+ previews, and an `Other` text answer. It returns schema-valid structured+ metadata to the Agent automatically.+- Type `/exit` and press `Enter` to exit the standalone TUI.++The example defaults to `qwen3.8-max`. `LocalWorkspace` instructions are+attached automatically when the workspace is passed as the Agent offloader.++## Embedding the UI++Widget sizes are controlled with Textual CSS rather than constructor+arguments. `MessagesUI` is the read-only building block:++```python+from textual.app import App, ComposeResult++from agentscope.tui import MessagesUI+++class HistoryApp(App):+ CSS = """+ #history {+ width: 96%;+ max-width: 110;+ height: 1fr;+ }+ """++ def compose(self) -> ComposeResult:+ yield MessagesUI(messages=history, id="history")+++HistoryApp().run()+```++An authoritative history refresh reconciles widgets by message and block ID:++```python+history_ui = app.query_one("#history", MessagesUI)+await history_ui.set_messages(await load_messages())+```++For streaming, publish only the changed message. Its ID selects an existing+widget, or appends a new one, without comparing the rest of the history:++```python+await history_ui.update_message(message)+```++`ChatUI` adds the composer and HITL controls while leaving execution and+concurrency policy to the containing application:++```python+from textual import on+from textual.app import App, ComposeResult++from agentscope.tui import ChatUI+++class RuntimeApp(App):+ def compose(self) -> ComposeResult:+ yield ChatUI(messages=history, id="chat")++ def on_mount(self) -> None:+ self.run_worker(self.consume_messages())++ async def consume_messages(self) -> None:+ chat = self.query_one("#chat", ChatUI)+ async for message in runtime.changed_messages:+ await chat.update_message(message)++ @on(ChatUI.Submitted)+ async def submit(self, event: ChatUI.Submitted) -> None:+ await runtime.submit(event.msg)++ @on(ChatUI.Confirmed)+ async def confirm(self, event: ChatUI.Confirmed) -> None:+ await runtime.submit(event.value)++ @on(ChatUI.ExternalExecutionSubmitted)+ async def external_result(+ self,+ event: ChatUI.ExternalExecutionSubmitted,+ ) -> None:+ await runtime.submit(event.value)++ @on(ChatUI.InterruptRequested)+ async def interrupt(self, event: ChatUI.InterruptRequested) -> None:+ await runtime.interrupt(event.reply_id)+```++Here `runtime` is your application's backend. It applies events with+`Msg.append_event()` and publishes the changed Msg. Use `set_messages()` for+initial history or session replacement, and `update_message()` for live+updates, including newly submitted user messages. Mutating the original+messages alone does not refresh the UI.+Unchanged messages reuse their display copies and widgets; changed Markdown+blocks stream appended text without rebuilding the conversation.++HITL and AskUser are derived from message blocks. Answered cards are dismissed+locally while the backend processes their results; this does not modify Msg+objects or append tool results in the UI.++The ordinary composer can be toggled independently. Pending HITL always+replaces it until confirmation or external execution completes:++```python+chat = app.query_one("#chat", ChatUI)+chat.input_enabled = False+chat.input_enabled = True+```++For an Agent or `PipelineProtocol`, the standalone launcher wires the same+events automatically. It keeps the composer available while a reply is+running and queues submissions, calling ``reply_stream`` serially so a shared+agent context is never mutated by concurrent replies:++```python+from agentscope.tui import launch_tui++await launch_tui(agent, messages=history, user_name="user")+```++The launcher displays submitted messages immediately, before waiting for the+reply queue. It retains only unfinished replies in a dictionary keyed by+reply ID, including replies waiting for HITL. After displaying `ReplyEndEvent`,+it releases that reply; the UI keeps its own historical display copy.++## Live CSS editing++Textual can reload external CSS while an app is running. Install its+development tools, put application overrides in a `.tcss` file referenced by+the App's `CSS_PATH`, then launch the app with `textual run --dev`.++The AgentScope widgets keep their base theme in `DEFAULT_CSS`, so that they+work without an application stylesheet. Python-embedded `DEFAULT_CSS` is not+file-watched; external application CSS can override it and is the recommended+place for live design iteration.diff --git a/examples/tui/main.py b/examples/tui/main.pynew file mode 100644index 000000000..b4c8b6e72--- /dev/null+++ b/examples/tui/main.py@@ -0,0 +1,56 @@+# -*- coding: utf-8 -*-+"""Run a full-featured AgentScope agent in the Textual terminal UI.++Set ``DASHSCOPE_API_KEY`` and run ``python main.py``. Use Enter to send,+Shift+Enter for a newline, Ctrl+C to interrupt, and type ``/exit`` to leave.+"""++import argparse+import asyncio+import os++from agentscope.agent import Agent+from agentscope.credential import DashScopeCredential+from agentscope.model import DashScopeChatModel+from agentscope.tool import AskUser, Toolkit+from agentscope.tui import launch_tui+from agentscope.workspace import LocalWorkspace+++async def main() -> None:+ """Build an Agent with local workspace tools and launch the TUI."""+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--model", default="qwen3.8-max")+ parser.add_argument(+ "--workdir",+ default=os.path.join(os.path.dirname(__file__), "workspace"),+ )+ args = parser.parse_args()++ api_key = os.environ.get("DASHSCOPE_API_KEY")+ if not api_key:+ raise RuntimeError("Set DASHSCOPE_API_KEY before running this demo.")++ async with LocalWorkspace(workdir=args.workdir) as workspace:+ agent = Agent(+ name="Friday",+ system_prompt=(+ "You are a helpful assistant named Friday. Use tools when "+ "they help."+ ),+ model=DashScopeChatModel(+ credential=DashScopeCredential(api_key=api_key),+ model=args.model,+ stream=True,+ ),+ toolkit=Toolkit(+ tools=[AskUser(), *(await workspace.list_tools())],+ skills_or_loaders=await workspace.list_skills(),+ ),+ offloader=workspace,+ )+ await launch_tui(agent)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/pyproject.toml b/pyproject.tomlindex 8ba7f9f98..580a4de30 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -111,6 +111,10 @@ realtime = ["websockets>=13","sounddevice",]+# ------------ Terminal UI ------------+tui = [+ "textual>=8.2,<9",+]# ------------ A2A ------------a2a = ["a2a-sdk>=1.1.1",@@ -173,6 +177,7 @@ full = ["agentscope[channel]","agentscope[workspace]","agentscope[tools]",+ "agentscope[tui]","agentscope[a2a]","agentscope[rag]","agentscope[vdb-qdrant]",diff --git a/src/agentscope/tui/__init__.py b/src/agentscope/tui/__init__.pynew file mode 100644index 000000000..db2c6f8d8--- /dev/null+++ b/src/agentscope/tui/__init__.py@@ -0,0 +1,19 @@+# -*- coding: utf-8 -*-+"""Interactive terminal UI components for AgentScope."""++try:+ from ._chat import ChatUI+ from ._launcher import launch_tui+ from ._messages import MessagesUI+except ImportError as error:+ if error.name == "textual":+ raise ImportError(+ 'Install TUI support with: pip install "agentscope[tui]"',+ ) from error+ raise++__all__ = [+ "ChatUI",+ "MessagesUI",+ "launch_tui",+]diff --git a/src/agentscope/tui/_ask_user.py b/src/agentscope/tui/_ask_user.pynew file mode 100644index 000000000..7ef20d2e6--- /dev/null+++ b/src/agentscope/tui/_ask_user.py@@ -0,0 +1,517 @@+# -*- coding: utf-8 -*-+"""Keyboard-first AskUser form for externally executed questions."""++# Textual callbacks inherit their documentation from the owning widget.+# pylint: disable=missing-function-docstring,protected-access+# pylint: disable=attribute-defined-outside-init++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any++from pydantic import ValidationError+from rich.text import Text+from textual import events, on+from textual.app import ComposeResult+from textual.containers import Vertical+from textual.message import Message+from textual.widgets import Input, OptionList, Static+from textual.widgets.option_list import Option++from ..event import ExternalExecutionResultEvent+from ..message import ToolCallBlock, ToolResultBlock, ToolResultState+from ..tool import AskUserAnswer, AskUserMetadata, AskUserParams+++@dataclass+class _Answer:+ """Mutable answer state while the form is being completed."""++ selected: list[str] = field(default_factory=list)+ other: str | None = None+++class _QuestionOptions(OptionList):+ """Option list whose mouse hover follows its keyboard highlight."""++ def _on_mouse_move(self, event: events.MouseMove) -> None:+ super()._on_mouse_move(event)+ hovered = event.style.meta.get("option")+ if isinstance(hovered, int):+ self.highlighted = hovered+++class AskUserUI(Vertical):+ """Render an AskUser call and return a schema-valid external result."""++ DEFAULT_CSS = """+ AskUserUI {+ width: 100%;+ height: auto;+ max-height: 80%;+ overflow-y: auto;+ scrollbar-visibility: hidden;+ padding: 0;+ background: transparent;+ }++ .as-ask-user-rule {+ width: 100%;+ height: 1;+ color: #766b5b;+ background: transparent;+ }++ .as-ask-user-steps,+ .as-ask-user-question,+ .as-ask-user-context,+ .as-ask-user-preview,+ .as-ask-user-hint {+ width: 100%;+ height: auto;+ padding: 0 1;+ background: transparent;+ }++ .as-ask-user-steps {+ height: 1;+ color: $text-muted;+ }++ .as-ask-user-question {+ margin-top: 1;+ color: $foreground;+ text-style: bold;+ }++ .as-ask-user-context,+ .as-ask-user-preview,+ .as-ask-user-hint {+ color: $text-muted;+ }++ .as-ask-user-context,+ .as-ask-user-preview {+ margin-top: 1;+ }++ .as-ask-user-options {+ width: 100%;+ height: auto;+ max-height: 14;+ margin-top: 1;+ padding: 0 1;+ border: none;+ scrollbar-visibility: hidden;+ background: transparent;+ }++ .as-ask-user-options:focus {+ border: none;+ background: transparent;+ background-tint: transparent;+ }++ .as-ask-user-options > .option-list--option-highlighted,+ .as-ask-user-options:focus > .option-list--option-highlighted,+ .as-ask-user-options > .option-list--option-hover {+ color: #d8b66f;+ background: transparent;+ }++ .as-ask-user-other {+ width: 100%;+ height: 1;+ min-height: 1;+ max-height: 5;+ padding: 0 1;+ border: none;+ scrollbar-visibility: hidden;+ background: transparent;+ }++ .as-ask-user-other:focus {+ border: none;+ background: transparent;+ }++ .as-ask-user-hint {+ height: 1;+ }+ """++ class Submitted(Message):+ """A completed AskUser external execution result."""++ def __init__(+ self,+ value: ExternalExecutionResultEvent,+ tool_call_id: str,+ ) -> None:+ super().__init__()+ self.value = value+ self.tool_call_id = tool_call_id++ class InterruptRequested(Message):+ """Request interruption of the parked reply."""++ def __init__(self, reply_id: str) -> None:+ super().__init__()+ self.reply_id = reply_id++ def __init__(self) -> None:+ super().__init__(classes="as-ask-user")+ self._pending: list[tuple[str, str, ToolCallBlock]] = []+ self._params: AskUserParams | None = None+ self._answers: list[_Answer] = []+ self._question_index = 0+ self._editing_other = False+ self._submitting = False+ self._error: str | None = None++ def compose(self) -> ComposeResult:+ yield Static("─" * 4096, classes="as-ask-user-rule")+ yield Static(classes="as-ask-user-steps")+ yield Static(classes="as-ask-user-question")+ context = Static(classes="as-ask-user-context")+ context.display = False+ yield context+ yield _QuestionOptions(classes="as-ask-user-options")+ preview = Static(classes="as-ask-user-preview")+ preview.display = False+ yield preview+ other = Input(+ placeholder="Type your answer…",+ classes="as-ask-user-other",+ )+ other.display = False+ yield other+ yield Static(classes="as-ask-user-hint")++ def set_pending(+ self,+ pending: list[tuple[str, str, ToolCallBlock]],+ ) -> None:+ previous_id = self._pending[0][2].id if self._pending else None+ current_id = pending[0][2].id if pending else None+ self._pending = pending+ self.display = bool(pending)+ if previous_id != current_id:+ self._load_current()+ if self.is_mounted and pending:+ self._render_form()+ if self._error is not None:+ self.call_later(self._submit_invalid)++ def _load_current(self) -> None:+ self._params = None+ self._answers = []+ self._question_index = 0+ self._editing_other = False+ self._submitting = False+ self._error = None+ if not self._pending:+ return+ try:+ self._params = AskUserParams.model_validate_json(+ self._pending[0][2].input,+ )+ except ValidationError as error:+ self._error = f"Invalid AskUser input: {error.errors()[0]['msg']}"+ if self._params is not None:+ self._answers = [_Answer() for _ in self._params.questions]++ @property+ def _question(self) -> Any:+ assert self._params is not None+ return self._params.questions[self._question_index]++ def focus_action(self) -> None:+ if not self.is_mounted or not self._pending:+ return+ if self._editing_other:+ self.query_one(Input).focus()+ elif self._params is not None:+ self.query_one(OptionList).focus()++ def _render_form(self) -> None:+ steps = self.query_one(".as-ask-user-steps", Static)+ question_widget = self.query_one(".as-ask-user-question", Static)+ context_widget = self.query_one(".as-ask-user-context", Static)+ preview_widget = self.query_one(".as-ask-user-preview", Static)+ options = self.query_one(OptionList)+ other = self.query_one(Input)+ hint = self.query_one(".as-ask-user-hint", Static)++ if self._error is not None:+ steps.update(Text("AskUser", style="bold #d8b66f"))+ question_widget.update(Text(self._error, style="bold red"))+ context_widget.display = False+ preview_widget.display = False+ options.display = False+ other.display = False+ hint.update("Returning invalid input to the agent…")+ return++ assert self._params is not None+ question = self._question+ steps.update(self._steps_text())+ question_widget.update(question.question)+ context_widget.display = bool(question.context)+ if question.context:+ context_widget.update(question.context)++ choices = [+ Option("", id=f"option:{index}")+ for index, _ in enumerate(question.options)+ ]+ choices.append(Option("", id="other"))+ if question.multi_select:+ choices.append(Option("", id="continue"))+ options.clear_options().add_options(choices)+ options.display = not self._editing_other+ options.highlighted = 0+ options.disabled = self._submitting+ other.display = self._editing_other+ other.disabled = self._submitting+ self._refresh_options()+ self._update_preview()+ hint.update(+ "Submitting…"+ if self._submitting+ else (+ "Enter submit answer · Esc choices · Ctrl+C interrupt"+ if self._editing_other+ else (+ "↑/↓ select · Enter choose · ← previous "+ "· Ctrl+C interrupt"+ )+ ),+ )++ def _steps_text(self) -> Text:+ assert self._params is not None+ text = Text("← ", style="dim")+ for index, question in enumerate(self._params.questions):+ answered = bool(+ self._answers[index].selected+ or self._answers[index].other is not None,+ )+ marker = "■" if answered else "□"+ style = (+ "bold #d8b66f underline"+ if index == self._question_index+ else "dim"+ )+ text.append(f"{marker} {question.header}", style=style)+ text.append(" ")+ submit_style = (+ "bold #d8b66f"+ if self._question_index == len(self._params.questions) - 1+ else "dim"+ )+ text.append("✓ Submit →", style=submit_style)+ return text++ def _option_prompt(self, index: int) -> Text:+ question = self._question+ highlighted = self.query_one(OptionList).highlighted == index+ marker = "→" if highlighted else " "+ if index < len(question.options):+ option = question.options[index]+ selected = (+ option.label in self._answers[self._question_index].selected+ )+ checkbox = (+ ("■ " if selected else "□ ") if question.multi_select else ""+ )+ prompt = Text(f"{marker} {index + 1}. {checkbox}")+ prompt.append(+ option.label,+ style="bold #d8b66f" if highlighted else "",+ )+ prompt.append(f"\n {option.description}", style="dim")+ return prompt+ if index == len(question.options):+ prompt = Text(f"{marker} {index + 1}. ")+ prompt.append(+ "Type something.",+ style="bold #d8b66f" if highlighted else "",+ )+ return prompt+ prompt = Text(f"{marker} ✓ Continue")+ if highlighted:+ prompt.stylize("bold #d8b66f")+ return prompt++ def _refresh_options(self) -> None:+ if self._params is None:+ return+ options = self.query_one(OptionList)+ for index in range(options.option_count):+ options.replace_option_prompt_at_index(+ index,+ self._option_prompt(index),+ )++ def _update_preview(self) -> None:+ preview = self.query_one(".as-ask-user-preview", Static)+ if self._editing_other or self._params is None:+ preview.display = False+ return+ highlighted = self.query_one(OptionList).highlighted+ question = self._question+ value = (+ question.options[highlighted].preview+ if highlighted is not None+ and highlighted < len(question.options)+ and not question.multi_select+ else None+ )+ preview.display = bool(value)+ if value:+ content = Text("Preview\n", style="bold #d8b66f")+ content.append(value, style="dim")+ preview.update(content)++ def _complete_question(self) -> None:+ if self._question_index + 1 < len(self._answers):+ self._question_index += 1+ self._editing_other = False+ self._render_form()+ self.call_later(self.focus_action)+ return+ self._submit()++ def _submit(self) -> None:+ if self._submitting or not self._pending or self._params is None:+ return+ answers = [+ AskUserAnswer(+ question=question.question,+ selected=answer.selected,+ other=answer.other,+ )+ for question, answer in zip(+ self._params.questions,+ self._answers,+ strict=True,+ )+ ]+ metadata = AskUserMetadata(answers=answers).model_dump(mode="json")+ lines = []+ for answer in answers:+ value = answer.other or ", ".join(answer.selected)+ lines.append(f"{answer.question}\n{value}")+ self._post_result(+ output="\n\n".join(lines),+ state=ToolResultState.SUCCESS,+ metadata=metadata,+ )++ def _submit_invalid(self) -> None:+ if self._error is None:+ return+ metadata = AskUserMetadata(answers=[]).model_dump(mode="json")+ self._post_result(+ output=self._error,+ state=ToolResultState.ERROR,+ metadata=metadata,+ )++ def _post_result(+ self,+ *,+ output: str,+ state: ToolResultState,+ metadata: dict[str, Any],+ ) -> None:+ if self._submitting or not self._pending:+ return+ reply_id, _, tool_call = self._pending[0]+ result = ToolResultBlock(+ id=tool_call.id,+ name=tool_call.name,+ output=output,+ state=state,+ metadata=metadata,+ )+ self._submitting = True+ self._render_form()+ self.post_message(+ self.Submitted(+ ExternalExecutionResultEvent(+ reply_id=reply_id,+ execution_results=[result],+ ),+ tool_call.id,+ ),+ )++ @on(OptionList.OptionSelected, ".as-ask-user-options")+ def _on_option_selected(self, event: OptionList.OptionSelected) -> None:+ if self._submitting or self._params is None:+ return+ option_id = str(event.option_id)+ question = self._question+ answer = self._answers[self._question_index]+ if option_id.startswith("option:"):+ index = int(option_id.split(":", maxsplit=1)[1])+ label = question.options[index].label+ answer.other = None+ if question.multi_select:+ if label in answer.selected:+ answer.selected.remove(label)+ else:+ answer.selected.append(label)+ self._refresh_options()+ else:+ answer.selected = [label]+ self._complete_question()+ elif option_id == "other":+ answer.selected = []+ self._editing_other = True+ self._render_form()+ self.call_later(self.focus_action)+ elif option_id == "continue" and answer.selected:+ self._complete_question()++ @on(OptionList.OptionHighlighted, ".as-ask-user-options")+ def _on_option_highlighted(self) -> None:+ if self._params is None or not self.display:+ return+ self._refresh_options()+ self._update_preview()++ @on(Input.Submitted, ".as-ask-user-other")+ def _on_other_submitted(self, event: Input.Submitted) -> None:+ value = event.value.strip()+ if not value:+ return+ answer = self._answers[self._question_index]+ answer.selected = []+ answer.other = value+ self._complete_question()++ def on_key(self, event: events.Key) -> None:+ if not self._pending or self._submitting:+ return+ if event.key == "ctrl+c":+ event.stop()+ event.prevent_default()+ self._submitting = True+ self.post_message(self.InterruptRequested(self._pending[0][0]))+ elif event.key == "escape" and self._editing_other:+ event.stop()+ event.prevent_default()+ self._editing_other = False+ self._render_form()+ self.call_later(self.focus_action)+ elif event.key == "left" and not self._editing_other:+ if self._question_index > 0:+ event.stop()+ event.prevent_default()+ self._question_index -= 1+ self._render_form()+ self.call_later(self.focus_action)diff --git a/src/agentscope/tui/_chat.py b/src/agentscope/tui/_chat.pynew file mode 100644index 000000000..2864907bf--- /dev/null+++ b/src/agentscope/tui/_chat.py@@ -0,0 +1,649 @@+# -*- coding: utf-8 -*-+"""Composable chat widget with input and human-in-the-loop controls."""++# Textual handlers and nested message payloads are intentionally tiny and+# inherit their behavioral documentation from their owning widgets.+# pylint: disable=missing-function-docstring,missing-class-docstring+# pylint: disable=attribute-defined-outside-init++from __future__ import annotations++from typing import Sequence++from rich.text import Text+from textual import events, on+from textual.app import ComposeResult+from textual.containers import Vertical+from textual.message import Message+from textual.reactive import reactive+from textual.widget import Widget+from textual.widgets import Collapsible, OptionList, Static, TextArea+from textual.widgets.option_list import Option++from ..event import (+ ConfirmResult,+ ExternalExecutionResultEvent,+ UserConfirmResultEvent,+)+from ..message import Msg, ToolCallBlock, ToolCallState, UserMsg+from ._ask_user import AskUserUI+from ._messages import MessagesUI++_ASK_USER_TOOL_NAME = "AskUser"+++class _ComposerTextArea(TextArea):+ """A TextArea where Enter submits and Shift+Enter inserts a newline."""++ class SubmitRequested(Message):+ """Request submission of the current editor contents."""++ class InterruptRequested(Message):+ """Request interruption of the currently running reply."""++ async def _on_key(self, event: events.Key) -> None:+ # Textual reports modified keys in ``event.key`` (e.g.+ # ``shift+enter``). Intercept both variants before TextArea's default+ # handler turns Enter into a newline.+ if event.key == "enter":+ event.stop()+ event.prevent_default()+ self.post_message(self.SubmitRequested())+ return+ if event.key == "shift+enter":+ event.stop()+ event.prevent_default()+ self.insert("\n")+ return+ if event.key == "ctrl+c":+ event.stop()+ event.prevent_default()+ self.post_message(self.InterruptRequested())+ return+ await super()._on_key(event)+++class _HitlOptionList(OptionList):+ """Option list whose mouse hover follows the keyboard highlight."""++ def _on_mouse_move(self, event: events.MouseMove) -> None:+ super()._on_mouse_move(event)+ hovered = event.style.meta.get("option")+ if isinstance(hovered, int):+ self.highlighted = hovered+++class ComposerUI(Vertical):+ """Keyboard-driven multiline composer with targeted interruption."""++ class Submitted(Message):+ def __init__(self, text: str) -> None:+ super().__init__()+ self.text = text++ class InterruptRequested(Message):+ def __init__(self, reply_id: str) -> None:+ super().__init__()+ self.reply_id = reply_id++ def __init__(self) -> None:+ super().__init__(classes="as-composer")+ self._enabled = True+ self._running_reply_id: str | None = None++ def compose(self) -> ComposeResult:+ yield Static("─" * 4096, classes="as-section-rule")+ yield _ComposerTextArea(+ placeholder="Message the agent…",+ id="as-composer-input",+ soft_wrap=True,+ compact=True,+ )+ yield Static("─" * 4096, classes="as-section-rule")+ yield Static(id="as-composer-hint", classes="as-composer-hint")++ @property+ def draft(self) -> str:+ return self.query_one(_ComposerTextArea).text++ def set_enabled(self, enabled: bool) -> None:+ self._enabled = enabled+ if not self.is_mounted:+ return+ editor = self.query_one(_ComposerTextArea)+ editor.disabled = not enabled+ self._update_hint()++ def set_running_reply(self, reply_id: str | None) -> None:+ self._running_reply_id = reply_id+ if self.is_mounted:+ self._update_hint()++ def _update_hint(self) -> None:+ if not self._enabled:+ hint = "Input disabled"+ else:+ hint = "Enter send · Shift+Enter newline · /exit quit"+ if self._running_reply_id is not None:+ hint += " · Ctrl+C interrupt"+ self.query_one("#as-composer-hint", Static).update(hint)++ def focus_editor(self) -> None:+ if self.is_mounted and self._enabled:+ self.query_one(_ComposerTextArea).focus()++ def on_mount(self) -> None:+ self.set_enabled(self._enabled)+ self.set_running_reply(self._running_reply_id)++ def _submit(self) -> None:+ if not self._enabled:+ return+ editor = self.query_one(_ComposerTextArea)+ value = editor.text.strip()+ if not value:+ return+ editor.load_text("")+ self.post_message(self.Submitted(value))++ @on(_ComposerTextArea.SubmitRequested)+ def _on_editor_submit(self) -> None:+ self._submit()++ @on(_ComposerTextArea.InterruptRequested)+ def _on_interrupt(self) -> None:+ if self._running_reply_id is not None:+ self.post_message(+ self.InterruptRequested(self._running_reply_id),+ )+++class HitlUI(Vertical):+ """Bottom-docked modal controls for pending tool interactions."""++ class Confirmed(Message):+ def __init__(self, value: UserConfirmResultEvent) -> None:+ super().__init__()+ self.value = value++ class InterruptRequested(Message):+ def __init__(self, reply_id: str) -> None:+ super().__init__()+ self.reply_id = reply_id++ def __init__(self) -> None:+ super().__init__(classes="as-hitl")+ self._pending: list[tuple[str, str, ToolCallBlock]] = []+ self._choice_labels: list[str] = []+ self._submitting = False++ def compose(self) -> ComposeResult:+ yield Static("─" * 4096, classes="as-section-rule")+ yield Static(id="as-hitl-title", classes="as-hitl-title")+ yield Static(id="as-hitl-body", classes="as-hitl-body")+ yield _HitlOptionList(+ id="as-hitl-options",+ classes="as-hitl-options",+ )+ yield Static(id="as-hitl-hint", classes="as-hitl-hint")++ def set_pending(+ self,+ pending: list[tuple[str, str, ToolCallBlock]],+ ) -> None:+ previous = self._pending[0][2].id if self._pending else None+ current = pending[0][2].id if pending else None+ self._pending = pending+ if previous != current:+ self._submitting = False+ self.display = bool(pending)+ if self.is_mounted and pending:+ self._render_current()++ def focus_action(self) -> None:+ if not self.is_mounted or not self._pending:+ return+ self.query_one(OptionList).focus()++ def _render_current(self) -> None:+ _, agent_name, tool_call = self._pending[0]+ waiting_external = tool_call.state == ToolCallState.SUBMITTED+ total = len(self._pending)+ state = (+ "Waiting for external execution"+ if waiting_external+ else "Approval required"+ )+ self.query_one("#as-hitl-title", Static).update(+ f"{state} · {agent_name} · 1/{total}",+ )+ body = Text(f"{tool_call.name}\n\n", style="bold")+ arguments = tool_call.input or "{}"+ body.append(+ "\n".join(f" {line}" for line in arguments.splitlines()),+ style="dim",+ )+ self.query_one("#as-hitl-body", Static).update(body)++ options = self.query_one(OptionList)+ choice_specs: list[tuple[str, str]] = []+ if not waiting_external:+ choice_specs.append(("Allow once", "allow"))+ if tool_call.suggested_rules:+ rules = "; ".join(+ f"{rule.behavior.value} {rule.tool_name}"+ + (f" ({rule.rule_content})" if rule.rule_content else "")+ for rule in tool_call.suggested_rules+ )+ choice_specs.append(+ (f"Always allow with {rules}", "always"),+ )+ choice_specs.append(("Deny", "deny"))+ choice_specs.append(("Interrupt reply", "interrupt"))+ self._choice_labels = [label for label, _ in choice_specs]+ choices = [+ Option(+ self._choice_prompt(choice_index, label, choice_index == 0),+ id=key,+ )+ for choice_index, (label, key) in enumerate(choice_specs)+ ]+ options.clear_options().add_options(choices)+ options.highlighted = 0+ self._refresh_choice_prompts()+ options.disabled = self._submitting+ hint = (+ "Submitting…"+ if self._submitting+ else "↑/↓ select · Enter confirm · Ctrl+C interrupt"+ )+ self.query_one("#as-hitl-hint", Static).update(hint)++ @staticmethod+ def _choice_prompt(index: int, label: str, selected: bool) -> str:+ marker = "→" if selected else " "+ return f"{marker} {index + 1}. {label}"++ def _refresh_choice_prompts(self) -> None:+ options = self.query_one(OptionList)+ for index, label in enumerate(self._choice_labels):+ options.replace_option_prompt_at_index(+ index,+ self._choice_prompt(+ index,+ label,+ index == options.highlighted,+ ),+ )++ def _confirm(self, confirmed: bool, always: bool = False) -> None:+ if not self._pending or self._submitting:+ return+ reply_id, _, tool_call = self._pending[0]+ if tool_call.state == ToolCallState.SUBMITTED:+ return+ self._submitting = True+ self._render_current()+ self.post_message(+ self.Confirmed(+ UserConfirmResultEvent(+ reply_id=reply_id,+ confirm_results=[+ ConfirmResult(+ confirmed=confirmed,+ tool_call=tool_call,+ rules=(+ tool_call.suggested_rules+ if confirmed and always+ else None+ ),+ ),+ ],+ ),+ ),+ )++ def _interrupt(self) -> None:+ if self._pending and not self._submitting:+ self._submitting = True+ self._render_current()+ self.post_message(self.InterruptRequested(self._pending[0][0]))++ @on(OptionList.OptionSelected, "#as-hitl-options")+ def _on_option_selected(self, event: OptionList.OptionSelected) -> None:+ if event.option_id == "allow":+ self._confirm(True)+ elif event.option_id == "always":+ self._confirm(True, always=True)+ elif event.option_id == "deny":+ self._confirm(False)+ elif event.option_id == "interrupt":+ self._interrupt()++ @on(OptionList.OptionHighlighted, "#as-hitl-options")+ def _on_option_highlighted(self) -> None:+ self._refresh_choice_prompts()++ def on_key(self, event: events.Key) -> None:+ if not self._pending or self._submitting:+ return+ if event.key == "ctrl+c":+ event.stop()+ event.prevent_default()+ self._interrupt()+++class ChatUI(Widget):+ """Messages, composer and HITL controls without an Agent dependency."""++ input_enabled = reactive(True)++ DEFAULT_CSS = """+ ChatUI {+ width: 100%;+ height: 100%;+ layout: vertical;+ padding: 0;+ background: transparent;+ }++ ChatUI > MessagesUI {+ height: 1fr;+ padding: 0 1;+ }++ ComposerUI, HitlUI {+ width: 100%;+ height: auto;+ min-height: 3;+ padding: 0;+ background: transparent;+ }++ .as-section-rule {+ width: 100%;+ height: 1;+ color: #766b5b;+ background: transparent;+ }++ #as-composer-input {+ width: 100%;+ height: auto;+ min-height: 1;+ max-height: 10;+ scrollbar-visibility: hidden;+ border: none;+ padding: 0 1;+ background: transparent;+ }++ #as-composer-input .text-area--cursor-line {+ background: transparent;+ }++ .as-composer-hint, .as-hitl-hint {+ width: 100%;+ height: 1;+ padding: 0 1;+ color: $text-muted;+ }++ .as-hitl-options {+ width: 100%;+ height: auto;+ max-height: 10;+ margin-top: 1;+ scrollbar-visibility: hidden;+ border: none;+ padding: 0 1;+ background: transparent;+ }++ .as-hitl-options:focus {+ border: none;+ background: transparent;+ background-tint: transparent;+ }++ .as-hitl-options > .option-list--option-highlighted,+ .as-hitl-options:focus > .option-list--option-highlighted {+ color: #d8b66f;+ background: transparent;+ text-style: bold;+ }++ .as-hitl-options > .option-list--option-hover {+ color: #d8b66f;+ background: transparent;+ }++ .as-hitl-title {+ height: 1;+ padding: 0 1;+ text-style: bold;+ color: $foreground;+ }++ .as-hitl-body {+ height: auto;+ max-height: 10;+ overflow-y: auto;+ scrollbar-visibility: hidden;+ padding: 0 1;+ background: transparent;+ }+ """++ class Submitted(Message):+ def __init__(self, msg: Msg) -> None:+ super().__init__()+ self.msg = msg++ class Confirmed(Message):+ def __init__(self, value: UserConfirmResultEvent) -> None:+ super().__init__()+ self.value = value++ class ExternalExecutionSubmitted(Message):+ def __init__(self, value: ExternalExecutionResultEvent) -> None:+ super().__init__()+ self.value = value++ class InterruptRequested(Message):+ def __init__(self, reply_id: str) -> None:+ super().__init__()+ self.reply_id = reply_id++ def __init__(+ self,+ messages: Sequence[Msg] = (),+ *,+ user_name: str = "user",+ input_enabled: bool = True,+ show_thinking: bool = True,+ show_usage: bool = False,+ id: str | None = None, # pylint: disable=redefined-builtin+ classes: str | None = None,+ disabled: bool = False,+ ) -> None:+ super().__init__(id=id, classes=classes, disabled=disabled)+ self._initial_messages = messages+ self._active_messages = {+ msg.id: msg.model_copy(deep=True)+ for msg in messages+ if msg.role == "assistant" and msg.finished_at is None+ }+ self.user_name = user_name+ self.show_thinking = show_thinking+ self.show_usage = show_usage+ self.input_enabled = input_enabled+ self._dismissed_call_ids: set[str] = set()++ def compose(self) -> ComposeResult:+ yield MessagesUI(+ self._initial_messages,+ show_thinking=self.show_thinking,+ show_usage=self.show_usage,+ id="as-messages",+ )+ yield ComposerUI()+ hitl = HitlUI()+ hitl.display = False+ yield hitl+ ask_user = AskUserUI()+ ask_user.display = False+ yield ask_user++ def on_mount(self) -> None:+ self._sync_interaction_area()++ @property+ def messages(self) -> tuple[Msg, ...]:+ return self.query_one(MessagesUI).messages++ def _current_messages(self) -> tuple[Msg, ...]:+ return tuple(self._active_messages.values())++ def is_reply_parked(self, reply_id: str) -> bool:+ """Whether a reply is waiting for confirmation or external input."""+ return any(+ message.id == reply_id+ and any(+ isinstance(block, ToolCallBlock)+ and block.state+ in (ToolCallState.ASKING, ToolCallState.SUBMITTED)+ for block in message.content+ )+ for message in self._current_messages()+ )++ async def set_messages(self, messages: Sequence[Msg]) -> None:+ await self.query_one(MessagesUI).set_messages(messages)+ self._active_messages = {+ msg.id: msg.model_copy(deep=True)+ for msg in messages+ if msg.role == "assistant" and msg.finished_at is None+ }+ self._sync_interaction_area()++ async def update_message(self, message: Msg) -> None:+ """Update one message and its associated interaction controls."""+ await self.query_one(MessagesUI).update_message(message)+ if message.role == "assistant" and message.finished_at is None:+ self._active_messages[message.id] = message.model_copy(deep=True)+ else:+ self._active_messages.pop(message.id, None)+ self._sync_interaction_area()++ def watch_input_enabled(self, enabled: bool) -> None:+ if self.is_mounted:+ self.query_one(ComposerUI).set_enabled(enabled)++ def _pending_tools(self) -> list[tuple[str, str, ToolCallBlock]]:+ pending: list[tuple[str, str, ToolCallBlock]] = []+ pending_ids: set[str] = set()+ for message in self._current_messages():+ if message.role != "assistant" or message.finished_at is not None:+ continue+ for block in message.content:+ if isinstance(block, ToolCallBlock) and block.state in (+ ToolCallState.ASKING,+ ToolCallState.SUBMITTED,+ ):+ pending_ids.add(block.id)+ if block.id not in self._dismissed_call_ids:+ pending.append((message.id, message.name, block))+ self._dismissed_call_ids.intersection_update(pending_ids)+ return pending++ def _latest_running_reply_id(self) -> str | None:+ for message in reversed(self._current_messages()):+ if message.role == "assistant" and message.finished_at is None:+ return message.id+ return None++ def _sync_interaction_area(self) -> None:+ composer = self.query_one(ComposerUI)+ hitl = self.query_one(HitlUI)+ ask_user = self.query_one(AskUserUI)+ pending = self._pending_tools()+ ask_pending: list[tuple[str, str, ToolCallBlock]] = []+ hitl_pending: list[tuple[str, str, ToolCallBlock]] = []+ ask_user_first = bool(pending and self._is_ask_user(pending[0][2]))+ active_pending = ask_pending if ask_user_first else hitl_pending+ for item in pending:+ if self._is_ask_user(item[2]) != ask_user_first:+ break+ active_pending.append(item)+ hitl.set_pending(hitl_pending)+ ask_user.set_pending(ask_pending)+ composer.display = not pending+ composer.set_enabled(self.input_enabled and not self.disabled)+ composer.set_running_reply(self._latest_running_reply_id())+ if ask_pending:+ self.call_later(ask_user.focus_action)+ elif hitl_pending:+ self.call_later(hitl.focus_action)+ else:+ self.call_later(composer.focus_editor)++ @staticmethod+ def _is_ask_user(tool_call: ToolCallBlock) -> bool:+ return (+ tool_call.name == _ASK_USER_TOOL_NAME+ and tool_call.state == ToolCallState.SUBMITTED+ )++ @on(Collapsible.Expanded)+ @on(Collapsible.Collapsed)+ def _on_collapsible_toggled(self) -> None:+ ask_user = self.query_one(AskUserUI)+ hitl = self.query_one(HitlUI)+ if ask_user.display:+ self.call_later(ask_user.focus_action)+ elif hitl.display:+ self.call_later(self.query_one(HitlUI).focus_action)+ else:+ self.call_later(self.query_one(ComposerUI).focus_editor)++ @on(ComposerUI.Submitted)+ def _on_composer_submitted(self, event: ComposerUI.Submitted) -> None:+ msg = UserMsg(name=self.user_name, content=event.text)+ self.post_message(self.Submitted(msg))++ @on(ComposerUI.InterruptRequested)+ def _on_composer_interrupt(+ self,+ event: ComposerUI.InterruptRequested,+ ) -> None:+ self.post_message(self.InterruptRequested(event.reply_id))++ @on(HitlUI.Confirmed)+ def _on_hitl_confirmed(self, event: HitlUI.Confirmed) -> None:+ self._dismissed_call_ids.update(+ result.tool_call.id for result in event.value.confirm_results+ )+ self._sync_interaction_area()+ self.post_message(self.Confirmed(event.value))++ @on(AskUserUI.Submitted)+ def _on_ask_user_submitted(self, event: AskUserUI.Submitted) -> None:+ # Dismiss the form locally without changing authoritative messages.+ self._dismissed_call_ids.add(event.tool_call_id)+ self._sync_interaction_area()+ self.post_message(self.ExternalExecutionSubmitted(event.value))++ @on(HitlUI.InterruptRequested)+ def _on_hitl_interrupt(+ self,+ event: HitlUI.InterruptRequested,+ ) -> None:+ self.post_message(self.InterruptRequested(event.reply_id))++ @on(AskUserUI.InterruptRequested)+ def _on_ask_user_interrupt(+ self,+ event: AskUserUI.InterruptRequested,+ ) -> None:+ self.post_message(self.InterruptRequested(event.reply_id))diff --git a/src/agentscope/tui/_launcher.py b/src/agentscope/tui/_launcher.pynew file mode 100644index 000000000..9607b178b--- /dev/null+++ b/src/agentscope/tui/_launcher.py@@ -0,0 +1,202 @@+# -*- coding: utf-8 -*-+"""Standalone Textual application for chatting with an Agent or pipeline."""++# Textual lifecycle and message handlers inherit their intent from the App.+# pylint: disable=missing-function-docstring++from __future__ import annotations++import asyncio+from typing import Sequence, TypeAlias++from textual import on+from textual.app import App, ComposeResult++from .._logging import logger+from ..agent import Agent+from ..event import (+ ExternalExecutionResultEvent,+ ReplyStartEvent,+ ReplyEndEvent,+ UserConfirmResultEvent,+ UserInterruptEvent,+)+from ..message import AssistantMsg, Msg+from ..pipeline import PipelineProtocol+from ._chat import ChatUI++_TUIInput: TypeAlias = (+ Msg+ | UserConfirmResultEvent+ | ExternalExecutionResultEvent+ | UserInterruptEvent+)+++class _AgentScopeTUI(App[None]):+ """The private application used by :func:`launch_tui`."""++ TITLE = "AgentScope"+ SUB_TITLE = "Interactive agent chat"+ BINDINGS = []+ CSS = """+ #agentscope-chat {+ width: 100%;+ height: 100%;+ }+ """++ def __init__(+ self,+ target: Agent | PipelineProtocol,+ messages: Sequence[Msg],+ user_name: str,+ ) -> None:+ # Render ANSI default colors so transparent widgets inherit the+ # user's terminal background rather than Textual's dark theme.+ super().__init__(ansi_color=True)+ self.target = target+ self._initial_messages = messages+ self._replies = {+ msg.id: msg.model_copy(deep=True)+ for msg in messages+ if msg.role == "assistant" and msg.finished_at is None+ }+ self.user_name = user_name+ self._tasks: set[asyncio.Task[None]] = set()+ self._reply_tasks: dict[str, asyncio.Task[None]] = {}+ self._reply_lock = asyncio.Lock()++ def compose(self) -> ComposeResult:+ yield ChatUI(+ self._initial_messages,+ user_name=self.user_name,+ id="agentscope-chat",+ )++ def _start_stream(self, inputs: _TUIInput) -> None:+ # The standalone application accepts input while a reply is running,+ # but queues each reply_stream call so one target context is never+ # mutated by concurrent replies.+ task = asyncio.create_task(self._consume(inputs))+ self._tasks.add(task)+ task.add_done_callback(self._tasks.discard)++ async def _consume(self, inputs: _TUIInput) -> None:+ chat = self.query_one(ChatUI)+ if isinstance(inputs, Msg):+ await chat.update_message(inputs)+ async with self._reply_lock:+ task = asyncio.current_task()+ owned_reply_ids: set[str] = set()+ if not isinstance(inputs, Msg) and task is not None:+ self._reply_tasks[inputs.reply_id] = task+ owned_reply_ids.add(inputs.reply_id)+ try:+ if isinstance(inputs, UserConfirmResultEvent):+ message = self._replies.get(inputs.reply_id)+ if message is not None:+ message.append_event(inputs)+ await chat.update_message(message)+ async for item in self.target.reply_stream(inputs):+ if isinstance(item, ReplyStartEvent) and task is not None:+ self._reply_tasks[item.reply_id] = task+ owned_reply_ids.add(item.reply_id)+ if isinstance(item, Msg):+ message = item.model_copy(deep=True)+ if (+ message.role == "assistant"+ and message.finished_at is None+ ):+ self._replies[message.id] = message+ else:+ reply_id = getattr(item, "reply_id", None)+ if reply_id is None:+ continue+ message = self._replies.get(reply_id)+ if message is None:+ name = (+ item.name+ if isinstance(item, ReplyStartEvent)+ else "agent"+ )+ message = AssistantMsg(+ name=name,+ content=[],+ id=reply_id,+ )+ self._replies[reply_id] = message+ if isinstance(item, ReplyStartEvent):+ message.name = item.name+ else:+ message.append_event(item)+ await chat.update_message(message)+ if (+ isinstance(item, ReplyEndEvent)+ or message.finished_at is not None+ ):+ self._replies.pop(message.id, None)+ # The standalone UI must keep running if its target fails.+ # pylint: disable-next=broad-exception-caught+ except Exception as error:+ logger.exception("TUI reply stream failed")+ self.notify(str(error), title="Agent error", severity="error")+ finally:+ for reply_id in owned_reply_ids:+ if self._reply_tasks.get(reply_id) is task:+ self._reply_tasks.pop(reply_id, None)++ @on(ChatUI.Submitted)+ def _on_submitted(self, event: ChatUI.Submitted) -> None:+ if event.msg.get_text_content().strip().casefold() == "/exit":+ self.exit()+ return+ self._start_stream(event.msg)++ @on(ChatUI.Confirmed)+ def _on_confirmed(self, event: ChatUI.Confirmed) -> None:+ self._start_stream(event.value)++ @on(ChatUI.ExternalExecutionSubmitted)+ def _on_external_execution_submitted(+ self,+ event: ChatUI.ExternalExecutionSubmitted,+ ) -> None:+ self._start_stream(event.value)++ @on(ChatUI.InterruptRequested)+ def _on_interrupt(self, event: ChatUI.InterruptRequested) -> None:+ chat = self.query_one(ChatUI)+ if chat.is_reply_parked(event.reply_id):+ self._start_stream(UserInterruptEvent(reply_id=event.reply_id))+ return+ task = self._reply_tasks.get(event.reply_id)+ if task is not None:+ task.cancel()++ async def on_unmount(self) -> None:+ tasks = list(self._tasks)+ for task in tasks:+ task.cancel()+ if tasks:+ await asyncio.gather(*tasks, return_exceptions=True)+++async def launch_tui(+ target: Agent | PipelineProtocol,+ *,+ messages: Sequence[Msg] = (),+ user_name: str = "user",+) -> None:+ """Launch a full-screen interactive terminal chat.++ Args:+ target (`Agent | PipelineProtocol`):+ Agent or pipeline whose ``reply_stream`` consumes user messages+ and HITL continuation events.+ messages (`Sequence[Msg]`, optional):+ Historical messages displayed before live interaction starts.+ user_name (`str`, defaults to ``"user"``):+ Name assigned to messages submitted from the composer.+ """+ await _AgentScopeTUI(target, messages, user_name).run_async()diff --git a/src/agentscope/tui/_messages.py b/src/agentscope/tui/_messages.pynew file mode 100644index 000000000..13006e397--- /dev/null+++ b/src/agentscope/tui/_messages.py@@ -0,0 +1,937 @@+# -*- coding: utf-8 -*-+"""Message-oriented widgets used by the AgentScope terminal UI."""++# Textual lifecycle callbacks inherit their intent from their widget classes.+# pylint: disable=missing-function-docstring,attribute-defined-outside-init+# pylint: disable=protected-access++from __future__ import annotations++import base64+from dataclasses import dataclass+from datetime import datetime+import json+import os+from typing import Iterable, Sequence, TypeAlias++from rich.console import Group, RenderableType+from rich.rule import Rule+from rich.syntax import Syntax+from rich.text import Text+from textual.app import ComposeResult+from textual.containers import Vertical, VerticalScroll+from textual.markup import escape+from textual.timer import Timer+from textual.widget import Widget+from textual.widgets import Collapsible, Markdown, Static++from ..message import (+ Base64Source,+ ContentBlock,+ DataBlock,+ Msg,+ TextBlock,+ ThinkingBlock,+ ToolCallBlock,+ ToolResultBlock,+)+++def _elapsed(created_at: str, finished_at: str | None) -> str:+ """Return a compact elapsed time for an ISO timestamp pair."""+ try:+ started = datetime.fromisoformat(created_at).timestamp()+ ended = (+ datetime.fromisoformat(finished_at).timestamp()+ if finished_at+ else datetime.now().timestamp()+ )+ except ValueError:+ return ""+ seconds = max(0.0, ended - started)+ if seconds < 10:+ return f"{seconds:.1f}s"+ if seconds < 60:+ return f"{seconds:.0f}s"+ minutes, remainder = divmod(int(seconds), 60)+ return f"{minutes}m {remainder:02d}s"+++def _human_size(n_bytes: int) -> str:+ size = float(n_bytes)+ for unit in ("B", "KB", "MB"):+ if size < 1024:+ return f"{size:.0f}{unit}"+ size /= 1024+ return f"{size:.1f}GB"+++def _pretty_json(raw: str) -> str:+ raw = raw.strip()+ if not raw:+ return "{}"+ try:+ return json.dumps(json.loads(raw), ensure_ascii=False, indent=2)+ except ValueError:+ return raw+++def _result_text(result: ToolResultBlock | None) -> str:+ if result is None:+ return ""+ if isinstance(result.output, str):+ return result.output+ parts: list[str] = []+ for block in result.output:+ if isinstance(block, TextBlock):+ parts.append(block.text)+ else:+ parts.append(_attachment_label(block))+ return "\n".join(parts)+++def _attachment_label(block: DataBlock) -> str:+ source = block.source+ if isinstance(source, Base64Source):+ try:+ size = len(base64.b64decode(source.data, validate=False))+ except ValueError:+ size = len(source.data) * 3 // 4+ location = _human_size(size)+ else:+ location = str(source.url)+ name = block.name or "attachment"+ return f"{name} · {source.media_type} · {location}"+++class TextBlockUI(Markdown):+ """A Markdown block which can consume streaming text deltas."""++ def __init__(self, block: TextBlock) -> None:+ super().__init__(block.text, classes="as-text-block", open_links=True)+ self.block_id = block.id+ self._finished = block.finished_at is not None+ self._stream = None+ self._text = block.text++ def on_mount(self) -> None:+ if not self._finished:+ self._stream = Markdown.get_stream(self)++ async def replace(self, block: TextBlock) -> None:+ text = block.text+ if self._stream is not None and text.startswith(self._text):+ await self._stream.write(text[len(self._text) :])+ if block.finished_at is not None:+ await self._stream.stop()+ self._stream = None+ else:+ if self._stream is not None:+ await self._stream.stop()+ self._stream = None+ await self.update(text)+ self._text = text+ self._finished = block.finished_at is not None++ async def on_unmount(self) -> None:+ if self._stream is not None:+ await self._stream.stop()+ self._stream = None+++class ThinkingUI(Collapsible):+ """Collapsed-by-default display for a thinking content block."""++ def __init__(self, block: ThinkingBlock) -> None:+ self.block = block+ text = block.thinking or "Protected reasoning content"+ self.markdown = Markdown(+ text,+ classes="as-thinking-body",+ open_links=True,+ )+ super().__init__(+ self.markdown,+ title=self._title_text(),+ collapsed=True,+ collapsed_symbol="→",+ expanded_symbol="↓",+ classes="as-thinking",+ )+ self._timer: Timer | None = None++ def on_mount(self) -> None:+ if self.block.finished_at is None:+ self._timer = self.set_interval(1.0, self._update_title)++ def _title_text(self) -> str:+ elapsed = _elapsed(self.block.created_at, self.block.finished_at)+ prefix = (+ "◌ Thinking" if self.block.finished_at is None else "◆ Thought"+ )+ return f"{prefix} · {elapsed}" if elapsed else prefix++ def _update_title(self) -> None:+ self.title = self._title_text()++ def replace(self, block: ThinkingBlock) -> None:+ self.block = block+ self.markdown.update(block.thinking or "Protected reasoning content")+ self.title = self._title_text()+ if block.finished_at is not None and self._timer is not None:+ self._timer.pause()+++class AttachmentUI(Static):+ """Portable terminal representation of a multimodal data block."""++ def __init__(self, block: DataBlock) -> None:+ self.block = block+ super().__init__(self._render_block(), classes="as-attachment")++ def _render_block(self) -> RenderableType:+ media_type = self.block.source.media_type+ category = media_type.split("/", maxsplit=1)[0]+ icon = {+ "image": "▧",+ "audio": "♪",+ "video": "▶",+ }.get(category, "▤")+ label = Text(f"{icon} {self.block.name or 'attachment'}", style="bold")+ label.append(f" {media_type}", style="dim")+ source = self.block.source+ if isinstance(source, Base64Source):+ try:+ size = len(base64.b64decode(source.data, validate=False))+ except ValueError:+ size = len(source.data) * 3 // 4+ label.append(f" {_human_size(size)}", style="dim")+ else:+ url = str(source.url)+ label.append(" open", style=f"underline link {url}")+ if self.block.finished_at is None:+ label.append(" receiving…", style="dim italic")+ return label++ def replace(self, block: DataBlock) -> None:+ self.block = block+ self.update(self._render_block())+++@dataclass+class _ToolPair:+ call: ToolCallBlock+ result: ToolResultBlock | None = None+++@dataclass+class _ToolGroup:+ calls: list[_ToolPair]+++_DisplayBlock: TypeAlias = ContentBlock | _ToolGroup++_TOOL_STATE_STYLES = {+ "success": ("✓", "green"),+ "error": ("✗", "red"),+ "denied": ("⊘", "yellow"),+ "interrupted": ("⚠", "yellow"),+ "running": ("→", "cyan"),+}+++def _group_tool_calls(content: Iterable[ContentBlock]) -> list[_DisplayBlock]:+ """Pair results and group consecutive tool calls like the Web UI."""+ call_map: dict[str, _ToolPair] = {}+ ordering: list[ContentBlock | tuple[str, str]] = []+ orphan_results: list[ToolResultBlock] = []+ for block in content:+ if isinstance(block, ToolCallBlock):+ call_map[block.id] = _ToolPair(block)+ ordering.append(("tool", block.id))+ elif isinstance(block, ToolResultBlock):+ pair = call_map.get(block.id)+ if pair is None:+ orphan_results.append(block)+ else:+ pair.result = block+ else:+ ordering.append(block)++ grouped: list[_DisplayBlock] = []+ pending: list[_ToolPair] = []++ def flush() -> None:+ if pending:+ grouped.append(_ToolGroup(list(pending)))+ pending.clear()++ for item in ordering:+ if isinstance(item, tuple):+ pair = call_map.get(item[1])+ if pair is not None:+ pending.append(pair)+ else:+ flush()+ grouped.append(item)+ flush()++ for result in orphan_results:+ grouped.append(+ _ToolGroup(+ [+ _ToolPair(+ ToolCallBlock(+ id=result.id,+ name=result.name,+ input="",+ state="finished",+ ),+ result,+ ),+ ],+ ),+ )+ return grouped+++def _diff_stats(diff: str) -> tuple[int, int]:+ insertions = 0+ deletions = 0+ for line in diff.splitlines():+ if line.startswith("+") and not line.startswith("+++"):+ insertions += 1+ elif line.startswith("-") and not line.startswith("---"):+ deletions += 1+ return insertions, deletions+++def _file_path(call: ToolCallBlock) -> str | None:+ try:+ value = json.loads(call.input).get("file_path")+ except (AttributeError, ValueError):+ return None+ return value if isinstance(value, str) else None+++def _tool_body(pair: _ToolPair) -> RenderableType:+ """Return the built-in detail rendering for one tool invocation."""+ items: list[RenderableType] = []+ compact_result_only = pair.call.name == "Read"+ if pair.call.input.strip() and not compact_result_only:+ items.append(Text("input", style="dim"))+ items.append(+ Syntax(+ _pretty_json(pair.call.input),+ "json",+ word_wrap=True,+ background_color="default",+ ),+ )+ result = pair.result+ if result is None:+ items.append(Text("Waiting for result…", style="dim italic"))+ return Group(*items)++ output = _result_text(result)+ name = pair.call.name+ diff = result.metadata.get("diff")+ rendered: RenderableType+ if compact_result_only:+ rendered = Text(output or "(no output)", style="dim")+ elif name in ("Edit", "Write") and isinstance(diff, str) and diff:+ rendered = Syntax(+ diff,+ "diff",+ word_wrap=False,+ background_color="default",+ )+ elif name == "Bash":+ rendered = Syntax(+ output,+ "console",+ word_wrap=True,+ background_color="default",+ )+ else:+ rendered = Text(output or "(no output)", style="dim")+ state_style = {+ "success": "dim",+ "error": "bold",+ "denied": "dim italic",+ "interrupted": "dim italic",+ "running": "dim italic",+ }.get(str(result.state), "dim")+ if not compact_result_only:+ items.append(Text(f"output · {result.state}", style=state_style))+ items.append(rendered)+ return Group(*items)+++def _tool_title(+ pair: _ToolPair,+ *,+ show_running_icon: bool = True,+) -> str:+ state = pair.result.state if pair.result is not None else "running"+ icon, style = _TOOL_STATE_STYLES.get(str(state), ("·", ""))+ path = _file_path(pair.call)+ primary = os.path.basename(path) if path else ""+ details = f" {escape(primary)}" if primary else ""+ if pair.call.name in ("Edit", "Write") and pair.result is not None:+ diff = pair.result.metadata.get("diff")+ if isinstance(diff, str) and diff:+ added, removed = _diff_stats(diff)+ details += f" +{added} -{removed}"+ icon_prefix = f"{icon} " if show_running_icon or state != "running" else ""+ name = escape(pair.call.name)+ styled_tool = (+ f"[{style}]{icon_prefix}[bold]{name}[/bold][/]"+ if style+ else f"{icon_prefix}[bold]{name}[/bold]"+ )+ return f"{styled_tool}{details}"+++class ToolCallUI(Vertical):+ """One flat tool call/result row inside an expanded tool group."""++ def __init__(self, pair: _ToolPair, *, show_title: bool) -> None:+ super().__init__(classes="as-tool-call")+ self.pair = pair+ self.show_title = show_title++ def compose(self) -> ComposeResult:+ if self.show_title:+ yield Static(+ _tool_title(self.pair),+ classes="as-tool-call-title",+ )+ yield Static(_tool_body(self.pair), classes="as-tool-body")+++def _tool_group_state(group: _ToolGroup) -> str:+ states = {+ (str(pair.result.state) if pair.result is not None else "running")+ for pair in group.calls+ }+ for state in ("error", "denied", "interrupted", "running"):+ if state in states:+ return state+ return "success"+++def _tool_group_title(group: _ToolGroup, *, expanded: bool = False) -> str:+ state = _tool_group_state(group)+ _, style = _TOOL_STATE_STYLES[state]+ disclosure = "↓" if expanded else "→"+ if len(group.calls) == 1:+ return (+ f"[{style}]{disclosure}[/] "+ f"{_tool_title(group.calls[0], show_running_icon=False)}"+ )+ counts: dict[str, int] = {}+ added = 0+ removed = 0+ for pair in group.calls:+ counts[pair.call.name] = counts.get(pair.call.name, 0) + 1+ if pair.result is not None:+ diff = pair.result.metadata.get("diff")+ if isinstance(diff, str):+ pair_added, pair_removed = _diff_stats(diff)+ added += pair_added+ removed += pair_removed+ pieces = [+ f"{name} ×{count}" if count > 1 else name+ for name, count in counts.items()+ ]+ summary = ", ".join(pieces) or "Tools"+ if added or removed:+ summary += f" +{added} -{removed}"+ icon, _ = _TOOL_STATE_STYLES[state]+ result_prefix = "" if state == "running" else f"{icon} "+ return (+ f"[{style}]{disclosure} {result_prefix}"+ f"[bold]{escape(summary)}[/bold][/]"+ )+++class ToolGroupUI(Collapsible):+ """A collapsed group of consecutive tool invocations."""++ def __init__(self, group: _ToolGroup) -> None:+ self.group = group+ self.call_ids = {pair.call.id for pair in group.calls}+ multiple = len(group.calls) > 1+ super().__init__(+ Vertical(+ *(+ ToolCallUI(pair, show_title=multiple)+ for pair in group.calls+ ),+ classes="as-tool-list",+ ),+ title=_tool_group_title(group),+ collapsed=True,+ collapsed_symbol="",+ expanded_symbol="",+ classes="as-tool-group",+ )++ def _watch_collapsed(self, collapsed: bool) -> None:+ super()._watch_collapsed(collapsed)+ self.title = _tool_group_title(self.group, expanded=not collapsed)+++class MessageUI(Vertical):+ """Rendering of one Msg with block-local streaming updates."""++ def __init__(+ self,+ message: Msg,+ *,+ show_thinking: bool,+ show_usage: bool,+ ) -> None:+ super().__init__(classes=f"as-message as-message-{message.role}")+ self.message = message+ self.show_thinking = show_thinking+ self.show_usage = show_usage+ self._block_uis: dict[str, object] = {}+ self._footer: Static | None = None+ self._timer: Timer | None = None++ def compose(self) -> ComposeResult:+ self._block_uis = {}+ yield Static(self._header_text(), classes="as-message-header")+ for block in _group_tool_calls(self.message.content):+ widget = self._make_block_ui(block)+ if widget is not None:+ yield widget+ if self.message.role == "assistant":+ footer_content = self._footer_text()+ self._footer = Static(+ footer_content,+ classes="as-message-footer",+ )+ self._footer.display = bool(footer_content.plain)+ yield self._footer+ else:+ self._footer = None++ def _header_text(self) -> Rule:+ return Rule(+ Text(self.message.name, style="bold #d8b66f"),+ characters="─",+ style="#766b5b",+ align="left",+ )++ def on_mount(self) -> None:+ if (+ self.message.role == "assistant"+ and self.message.finished_at is None+ ):+ self._timer = self.set_interval(1.0, self._update_footer)++ def _make_block_ui(self, block: _DisplayBlock) -> Widget | None:+ if isinstance(block, TextBlock):+ widget = TextBlockUI(block)+ self._block_uis[block.id] = widget+ return widget+ if isinstance(block, ThinkingBlock):+ if not self.show_thinking:+ return None+ widget = ThinkingUI(block)+ self._block_uis[block.id] = widget+ return widget+ if isinstance(block, DataBlock):+ widget = AttachmentUI(block)+ self._block_uis[block.id] = widget+ return widget+ if isinstance(block, _ToolGroup):+ widget = ToolGroupUI(block)+ for call_id in widget.call_ids:+ self._block_uis[call_id] = widget+ return widget+ if block.type == "hint":+ text = (+ block.hint+ if isinstance(block.hint, str)+ else "\n".join(+ (+ item.text+ if isinstance(item, TextBlock)+ else _attachment_label(item)+ )+ for item in block.hint+ )+ )+ source = f" from {block.source}" if block.source else ""+ widget = Collapsible(+ Markdown(text, classes="as-hint-body"),+ title=f"Hint{source}",+ collapsed=True,+ collapsed_symbol="→",+ expanded_symbol="↓",+ classes="as-hint",+ )+ self._block_uis[block.id] = widget+ return widget+ return None++ def _footer_text(self) -> Text:+ running = self.message.finished_at is None+ text = Text()+ if running:+ text.append("◌ running", style="dim italic")+ elif self.show_usage and self.message.usage is not None:+ text.append(+ f"↑{self.message.usage.input_tokens}"+ f" ↓{self.message.usage.output_tokens}",+ style="dim",+ )+ if self.message.finished_reason not in (None, "completed"):+ text.append(+ f" {self.message.finished_reason}",+ style="italic",+ )+ if self.message.error is not None:+ text.append(+ f" {self.message.error.type}: {self.message.error.message}",+ style="bold",+ )+ return text++ def _update_footer(self) -> None:+ if self._footer is not None:+ content = self._footer_text()+ self._footer.update(content)+ self._footer.display = bool(content.plain)++ async def apply(self, message: Msg) -> None:+ previous = self.message+ self.message = message+ self.query_one(".as-message-header", Static).update(+ self._header_text(),+ )+ self._update_footer()+ if message.finished_at is not None and self._timer is not None:+ self._timer.pause()++ old_blocks = _group_tool_calls(previous.content)+ new_blocks = _group_tool_calls(message.content)+ old_keys = [+ tuple(pair.call.id for pair in block.calls)+ if isinstance(block, _ToolGroup)+ else block.id+ for block in old_blocks+ ]+ new_keys = [+ tuple(pair.call.id for pair in block.calls)+ if isinstance(block, _ToolGroup)+ else block.id+ for block in new_blocks+ ]+ old_by_key = dict(zip(old_keys, old_blocks))+ old_widgets = set(self._block_uis.values())+ next_widgets: dict[str, object] = {}+ retained: set[Widget] = set()+ ordered: list[Widget] = []+ for key, block in zip(new_keys, new_blocks):+ block_id = key[0] if isinstance(key, tuple) else key+ widget = self._block_uis.get(block_id)+ old_block = old_by_key.get(key)+ if isinstance(widget, Widget) and old_block == block:+ pass+ elif isinstance(widget, TextBlockUI) and isinstance(+ block,+ TextBlock,+ ):+ await widget.replace(block)+ elif isinstance(widget, ThinkingUI) and isinstance(+ block,+ ThinkingBlock,+ ):+ widget.replace(block)+ elif isinstance(widget, AttachmentUI) and isinstance(+ block,+ DataBlock,+ ):+ widget.replace(block)+ else:+ collapsed = (+ widget.collapsed+ if isinstance(widget, Collapsible)+ else True+ )+ widget = self._make_block_ui(block)+ if widget is None:+ continue+ if isinstance(widget, Collapsible):+ widget.collapsed = collapsed+ await self.mount(widget)+ retained.add(widget)+ ordered.append(widget)+ if isinstance(block, _ToolGroup):+ for pair in block.calls:+ next_widgets[pair.call.id] = widget+ else:+ next_widgets[block.id] = widget++ for widget in old_widgets - retained:+ if isinstance(widget, Widget) and widget.is_mounted:+ await widget.remove()+ self._block_uis = next_widgets+ previous_widget = self.query_one(".as-message-header", Static)+ for widget in ordered:+ self.move_child(widget, after=previous_widget)+ previous_widget = widget+++class MessagesUI(VerticalScroll):+ """Render authoritative message snapshots without consuming events."""++ DEFAULT_CSS = """+ MessagesUI {+ width: 100%;+ height: 1fr;+ scrollbar-visibility: hidden;+ padding: 0;+ background: transparent;+ }++ MessageUI {+ width: 100%;+ height: auto;+ margin: 0;+ padding: 0;+ }++ .as-message-user {+ margin-left: 0;+ background: transparent;+ }++ .as-message-assistant {+ margin-right: 0;+ background: transparent;+ }++ .as-message-header {+ height: 1;+ margin-bottom: 1;+ color: $text-muted;+ text-style: bold;+ }++ .as-message-user > .as-message-header {+ color: $foreground;+ }++ .as-message-assistant > .as-message-header {+ color: $foreground;+ }++ .as-message-footer {+ height: auto;+ color: $text-muted;+ margin-top: 1;+ }++ .as-text-block, .as-thinking, .as-tool-group, .as-hint {+ width: 100%;+ height: auto;+ }++ .as-text-block {+ padding: 0;+ background: transparent;+ }++ .as-thinking, .as-tool-group, .as-hint {+ background: transparent;+ border-top: none;+ padding: 0;+ margin: 0 0 1 0;+ }++ .as-thinking:ansi, .as-tool-group:ansi, .as-hint:ansi {+ background: transparent;+ border-top: none;+ }++ .as-thinking > CollapsibleTitle,+ .as-tool-group > CollapsibleTitle,+ .as-hint > CollapsibleTitle {+ width: 100%;+ padding: 0 1;+ background: transparent;+ text-style: none;+ }++ .as-thinking > CollapsibleTitle,+ .as-hint > CollapsibleTitle {+ color: $text-muted;+ }++ .as-tool-group > CollapsibleTitle {+ width: auto;+ padding-left: 0;+ }++ .as-thinking > CollapsibleTitle:hover,+ .as-thinking > CollapsibleTitle:focus,+ .as-tool-group > CollapsibleTitle:hover,+ .as-tool-group > CollapsibleTitle:focus,+ .as-hint > CollapsibleTitle:hover,+ .as-hint > CollapsibleTitle:focus {+ background: transparent;+ color: #d8b66f;+ text-style: bold;+ }++ .as-thinking > Contents,+ .as-tool-group > Contents,+ .as-hint > Contents {+ height: auto;+ padding: 0 0 0 2;+ }++ .as-tool-list {+ width: 100%;+ height: auto;+ }++ .as-thinking-body, .as-hint-body {+ padding: 0;+ background: transparent;+ }++ .as-tool-call {+ width: 100%;+ height: auto;+ margin-top: 1;+ }++ .as-tool-call-title {+ width: 100%;+ height: 1;+ color: $foreground;+ }++ .as-tool-body {+ width: 100%;+ height: auto;+ padding-left: 1;+ color: $text-muted;+ background: transparent;+ }++ .as-attachment {+ width: 100%;+ height: auto;+ margin-top: 1;+ padding-left: 2;+ color: $text-muted;+ }+ """++ def __init__(+ self,+ messages: Sequence[Msg] = (),+ *,+ show_thinking: bool = True,+ show_usage: bool = False,+ id: str | None = None, # pylint: disable=redefined-builtin+ classes: str | None = None,+ disabled: bool = False,+ ) -> None:+ super().__init__(id=id, classes=classes, disabled=disabled)+ self.show_thinking = show_thinking+ self.show_usage = show_usage+ self._messages = [msg.model_copy(deep=True) for msg in messages]+ self._by_id = {msg.id: msg for msg in self._messages}+ self._indices = {+ msg.id: index for index, msg in enumerate(self._messages)+ }+ self._message_uis: dict[str, MessageUI] = {}++ @property+ def messages(self) -> tuple[Msg, ...]:+ """A safe snapshot of the messages currently being rendered."""+ return tuple(msg.model_copy(deep=True) for msg in self._messages)++ def current_messages(self) -> tuple[Msg, ...]:+ """Return live messages for coordinated sibling UI components.++ Unlike :attr:`messages`, this avoids deep copies. Callers must treat+ the returned models as read-only.+ """+ return tuple(self._messages)++ def compose(self) -> ComposeResult:+ self._message_uis = {}+ for message in self._messages:+ widget = self._new_message_ui(message)+ self._message_uis[message.id] = widget+ yield widget++ def _new_message_ui(self, message: Msg) -> MessageUI:+ return MessageUI(+ message,+ show_thinking=self.show_thinking,+ show_usage=self.show_usage,+ )++ async def set_messages(self, messages: Sequence[Msg]) -> None:+ """Reconcile an authoritative full conversation snapshot."""+ copied = [+ self._by_id[msg.id]+ if self._by_id.get(msg.id) == msg+ else msg.model_copy(deep=True)+ for msg in messages+ ]+ incoming_ids = [msg.id for msg in copied]+ current_ids = [msg.id for msg in self._messages]+ previous_by_id = self._by_id+ self._messages = copied+ self._by_id = {msg.id: msg for msg in copied}+ self._indices = {msg.id: index for index, msg in enumerate(copied)}++ for msg_id in set(current_ids) - set(incoming_ids):+ await self._message_uis.pop(msg_id).remove()+ previous_widget = None+ for message in copied:+ widget = self._message_uis.get(message.id)+ if widget is None:+ widget = self._new_message_ui(message)+ self._message_uis[message.id] = widget+ await self.mount(widget)+ elif previous_by_id[message.id] != message:+ await widget.apply(message)+ if incoming_ids != current_ids:+ if previous_widget is None:+ self.move_child(widget, before=0)+ else:+ self.move_child(widget, after=previous_widget)+ previous_widget = widget+ self.scroll_end(animate=False)++ async def update_message(self, message: Msg) -> None:+ """Update one message by ID, appending it if it is new."""+ previous = self._by_id.get(message.id)+ if previous == message:+ return+ copied = message.model_copy(deep=True)+ self._by_id[copied.id] = copied+ if previous is None:+ self._indices[copied.id] = len(self._messages)+ self._messages.append(copied)+ widget = self._new_message_ui(copied)+ self._message_uis[copied.id] = widget+ await self.mount(widget)+ else:+ self._messages[self._indices[copied.id]] = copied+ await self._message_uis[copied.id].apply(copied)+ self.scroll_end(animate=False)diff --git a/tests/tui_test.py b/tests/tui_test.pynew file mode 100644index 000000000..97f58fe6e--- /dev/null+++ b/tests/tui_test.py@@ -0,0 +1,1338 @@+# -*- coding: utf-8 -*-+"""Tests for the optional AgentScope Textual UI."""++# Test names describe behavior; fixtures also intentionally exercise private+# widgets because the public ChatUI composes them internally.+# pylint: disable=missing-class-docstring,missing-function-docstring+# pylint: disable=protected-access++import asyncio+from collections.abc import AsyncGenerator+import json+from typing import Any+import unittest+from unittest.mock import patch+from weakref import WeakKeyDictionary++from textual.app import App, ComposeResult+from textual.message import Message as TextualMessage+from textual.widgets import Collapsible, Input, OptionList, Static++from agentscope.event import (+ ExternalExecutionResultEvent,+ ReplyEndEvent,+ ReplyStartEvent,+ RequireExternalExecutionEvent,+ RequireUserConfirmEvent,+ TextBlockDeltaEvent,+ TextBlockEndEvent,+ TextBlockStartEvent,+ ToolCallDeltaEvent,+ ToolCallEndEvent,+ ToolCallStartEvent,+ ToolResultEndEvent,+ ToolResultStartEvent,+ UserConfirmResultEvent,+ UserInterruptEvent,+)+from agentscope.message import (+ AssistantMsg,+ HintBlock,+ Msg,+ TextBlock,+ ThinkingBlock,+ ToolCallBlock,+ ToolCallState,+ ToolResultBlock,+ ToolResultState,+ UserMsg,+)+from agentscope.permission import PermissionBehavior, PermissionRule+from agentscope.tool import AskUser+from agentscope.tui import ChatUI, MessagesUI+from agentscope.tui._ask_user import AskUserUI+from agentscope.tui._chat import ComposerUI, HitlUI, _ComposerTextArea+from agentscope.tui._launcher import _AgentScopeTUI+from agentscope.tui._messages import (+ MessageUI,+ TextBlockUI,+ ThinkingUI,+ ToolGroupUI,+)+++_conversations = WeakKeyDictionary()+++async def _publish(ui: MessagesUI | ChatUI, item: Any) -> None:+ """Assemble test events outside the UI and publish the changed Msg."""+ if ui not in _conversations:+ _conversations[ui] = {msg.id: msg for msg in ui.messages}+ conversation = _conversations[ui]+ if isinstance(item, Msg):+ message = item+ else:+ message = conversation.get(item.reply_id)+ if message is None:+ name = item.name if isinstance(item, ReplyStartEvent) else "agent"+ message = AssistantMsg(name=name, content=[], id=item.reply_id)+ if not isinstance(item, ReplyStartEvent):+ message.append_event(item)+ conversation[message.id] = message+ await ui.update_message(message)+++class _MessagesApp(App):+ def __init__(self, messages: list[Msg]) -> None:+ super().__init__()+ self.initial_messages = messages++ def compose(self) -> ComposeResult:+ yield MessagesUI(self.initial_messages, id="messages")+++class _ChatApp(App):+ def __init__(self, messages: list[Msg] | None = None) -> None:+ super().__init__()+ self.initial_messages = messages or []++ def compose(self) -> ComposeResult:+ yield ChatUI(self.initial_messages, id="chat")+++class MessagesUITest(unittest.IsolatedAsyncioTestCase):+ async def test_update_message_only_compares_the_target(self) -> None:+ history = [+ UserMsg(name="user", content="History", id=f"history-{index}")+ for index in range(100)+ ]+ active = AssistantMsg(+ name="agent",+ id="active",+ content=[TextBlock(id="text", text="First")],+ )+ app = _MessagesApp([*history, active])+ async with app.run_test() as pilot:+ ui = app.query_one(MessagesUI)+ original = ui._message_uis["active"]+ comparisons = []+ equal = Msg.__eq__++ def compare(message: Msg, other: object) -> bool:+ comparisons.append(message.id)+ return equal(message, other)++ active.content[0].text = "First and second"+ with patch.object(Msg, "__eq__", compare):+ await ui.update_message(active)+ await pilot.pause()++ self.assertListEqual(comparisons, ["active"])+ self.assertIs(ui._message_uis["active"], original)+ self.assertEqual(+ original.query_one(TextBlockUI).source,+ "First and second",+ )++ async def test_mutated_snapshot_preserves_existing_widgets(self) -> None:+ message = AssistantMsg(+ name="agent",+ id="reply",+ content=[TextBlock(id="text", text="Hello")],+ )+ app = _MessagesApp([message])+ async with app.run_test() as pilot:+ ui = app.query_one(MessagesUI)+ original = app.query_one(MessageUI)+ text = app.query_one(TextBlockUI)+ message.content[0].text = "Hello world"+ self.assertEqual(text.source, "Hello")++ await ui.set_messages([message])+ await pilot.pause()+ self.assertIs(app.query_one(TextBlockUI), text)+ self.assertEqual(text.source, "Hello world")++ await ui.set_messages(+ [message, UserMsg(name="user", content="Next", id="next")],+ )+ self.assertIs(ui._message_uis["reply"], original)+ self.assertIs(original.query_one(TextBlockUI), text)++ await ui.set_messages([message])+ self.assertListEqual(list(ui._message_uis), ["reply"])+ self.assertIs(app.query_one(MessageUI), original)++ async def test_snapshot_keeps_expanded_thinking_when_text_changes(+ self,+ ) -> None:+ message = AssistantMsg(+ name="agent",+ content=[+ ThinkingBlock(id="thought", thinking="Checking"),+ TextBlock(id="text", text="Answer"),+ ],+ )+ app = _MessagesApp([message])+ async with app.run_test() as pilot:+ ui = app.query_one(MessagesUI)+ thinking = app.query_one(ThinkingUI)+ thinking.collapsed = False+ message.content[1].text = "A revised answer"+ await ui.set_messages([message])+ await pilot.pause()+ self.assertIs(app.query_one(ThinkingUI), thinking)+ self.assertFalse(thinking.collapsed)+ self.assertEqual(+ app.query_one(TextBlockUI).source,+ "A revised answer",+ )++ async def test_running_thinking_updates_elapsed_title(self) -> None:+ msg = AssistantMsg(+ name="agent",+ id="reply-1",+ content=[+ ThinkingBlock(+ id="thinking-1",+ thinking="Working",+ ),+ ],+ )+ app = _MessagesApp([msg])+ async with app.run_test() as pilot:+ thinking = app.query_one(ThinkingUI)+ thinking._update_title()+ await pilot.pause()++ self.assertTrue(str(thinking.title).startswith("◌ Thinking"))+ self.assertEqual(thinking._title.collapsed_symbol, "→")+ self.assertEqual(thinking._title.expanded_symbol, "↓")++ async def test_hint_uses_shared_disclosure_arrows(self) -> None:+ msg = AssistantMsg(+ name="agent",+ content=[HintBlock(id="hint-1", hint="Use the shared arrow")],+ )+ app = _MessagesApp([msg])+ async with app.run_test() as pilot:+ await pilot.pause()+ hint = app.query_one(".as-hint", Collapsible)++ self.assertEqual(hint._title.collapsed_symbol, "→")+ self.assertEqual(hint._title.expanded_symbol, "↓")+ self.assertEqual(hint.styles.margin.top, 0)+ self.assertEqual(hint.styles.margin.bottom, 1)++ async def test_full_snapshot_keeps_unchanged_message_widget(self) -> None:+ msg = UserMsg(name="user", content="first", id="user-1")+ app = _MessagesApp([msg])+ async with app.run_test() as pilot:+ messages_ui = app.query_one(MessagesUI)+ original = app.query_one(MessageUI)+ updated = UserMsg(name="user", content="updated", id="user-1")++ await messages_ui.set_messages([updated])+ await pilot.pause()++ self.assertIs(original, app.query_one(MessageUI))+ self.assertEqual(+ messages_ui.messages[0].get_text_content(),+ "updated",+ )+ self.assertEqual(app.query_one(TextBlockUI).source, "updated")++ async def test_interleaved_reply_events_are_isolated_by_reply_id(+ self,+ ) -> None:+ app = _MessagesApp([])+ async with app.run_test() as pilot:+ ui = app.query_one(MessagesUI)+ await _publish(+ ui,+ ReplyStartEvent(+ session_id="s",+ reply_id="r1",+ name="planner",+ ),+ )+ await _publish(+ ui,+ ReplyStartEvent(+ session_id="s",+ reply_id="r2",+ name="executor",+ ),+ )+ await _publish(+ ui,+ TextBlockStartEvent(reply_id="r1", block_id="t1"),+ )+ await _publish(+ ui,+ TextBlockStartEvent(reply_id="r2", block_id="t2"),+ )+ await _publish(+ ui,+ TextBlockDeltaEvent(+ reply_id="r2",+ block_id="t2",+ delta="execute",+ ),+ )+ await _publish(+ ui,+ TextBlockDeltaEvent(+ reply_id="r1",+ block_id="t1",+ delta="plan",+ ),+ )+ await pilot.pause()++ self.assertEqual([msg.id for msg in ui.messages], ["r1", "r2"])+ self.assertEqual(ui.messages[0].get_text_content(), "plan")+ self.assertEqual(ui.messages[1].get_text_content(), "execute")++ async def test_streaming_text_updates_only_its_block(self) -> None:+ app = _MessagesApp([])+ async with app.run_test() as pilot:+ ui = app.query_one(MessagesUI)+ await _publish(+ ui,+ ReplyStartEvent(+ session_id="s",+ reply_id="r1",+ name="agent",+ ),+ )+ await _publish(+ ui,+ TextBlockStartEvent(reply_id="r1", block_id="t1"),+ )+ await pilot.pause()+ message_widget = app.query_one(MessageUI)+ text_widget = app.query_one(TextBlockUI)++ await _publish(+ ui,+ TextBlockDeltaEvent(+ reply_id="r1",+ block_id="t1",+ delta="hello",+ ),+ )+ await _publish(ui, TextBlockEndEvent(reply_id="r1", block_id="t1"))+ await _publish(ui, ReplyEndEvent(session_id="s", reply_id="r1"))+ await pilot.pause()++ self.assertIs(message_widget, app.query_one(MessageUI))+ self.assertIs(text_widget, app.query_one(TextBlockUI))+ self.assertEqual(ui.messages[0].get_text_content(), "hello")+++class ChatUITest(unittest.IsolatedAsyncioTestCase):+ async def test_submission_does_not_append_history(self) -> None:+ app = _ChatApp()+ async with app.run_test() as pilot:+ await pilot.press("h", "i", "enter")+ await pilot.pause()+ self.assertListEqual(list(app.query_one(ChatUI).messages), [])++ async def test_visual_layout_at_supported_terminal_sizes(self) -> None:+ finished_at = "2026-01-01T00:00:01+00:00"+ history: list[Msg] = [+ UserMsg(name="user", content="Explain the change", id="user-1"),+ AssistantMsg(+ name="agent",+ id="reply-1",+ finished_at=finished_at,+ content=[+ ThinkingBlock(+ id="thinking-1",+ thinking="Check the implementation.",+ finished_at=finished_at,+ ),+ TextBlock(+ id="text-1",+ text="## Result\n\nThe update is **ready**.",+ finished_at=finished_at,+ ),+ ToolCallBlock(+ id="edit-1",+ name="Edit",+ input='{"file_path": "demo.py"}',+ state="finished",+ finished_at=finished_at,+ ),+ ToolResultBlock(+ id="edit-1",+ name="Edit",+ output="updated",+ state="success",+ metadata={"diff": "@@ -1 +1 @@\n-old\n+new\n"},+ finished_at=finished_at,+ ),+ ],+ ),+ ]++ for size in ((120, 40), (80, 24), (50, 20)):+ with self.subTest(size=size):+ app = _ChatApp(history)+ async with app.run_test(size=size) as pilot:+ await pilot.pause()+ chat = app.query_one(ChatUI)+ composer = app.query_one(ComposerUI)+ screenshot = app.export_screenshot(simplify=True)+ message_uis = list(chat.query(MessageUI))+ tool_group = chat.query_one(ToolGroupUI)+ text_block = chat.query_one(TextBlockUI)+ footer = chat.query_one(".as-message-footer", Static)+ messages_ui = chat.query_one(MessagesUI)+ editor = chat.query_one(_ComposerTextArea)++ self.assertEqual(+ (chat.region.width, chat.region.height),+ size,+ )+ self.assertEqual(+ message_uis[0].region.x,+ message_uis[1].region.x,+ )+ self.assertEqual(+ message_uis[0].region.x,+ chat.content_region.x + 1,+ )+ self.assertLessEqual(+ message_uis[0].region.right,+ chat.content_region.right - 1,+ )+ self.assertEqual(+ message_uis[1]+ .query_one(".as-message-header", Static)+ .region.x,+ text_block.region.x,+ )+ self.assertEqual(+ message_uis[1]+ .query_one(".as-message-header", Static)+ .styles.margin.bottom,+ 1,+ )+ self.assertEqual(message_uis[0].styles.margin.bottom, 0)+ self.assertEqual(+ len(tool_group.query(Collapsible)),+ 0,+ )+ self.assertEqual(tool_group.styles.margin.top, 0)+ self.assertEqual(tool_group.styles.margin.bottom, 1)+ self.assertIn("✓", str(tool_group.title))+ self.assertFalse(footer.display)+ self.assertEqual(+ str(messages_ui.styles.scrollbar_visibility),+ "hidden",+ )+ self.assertEqual(editor.styles.background.a, 0)+ self.assertEqual(editor.region.height, 1)+ self.assertEqual(+ str(editor.styles.scrollbar_visibility),+ "hidden",+ )+ self.assertEqual(+ len(composer.query(".as-section-rule")),+ 2,+ )+ for rule in composer.query(".as-section-rule"):+ self.assertEqual(rule.region.x, chat.region.x)+ self.assertEqual(rule.region.width, chat.region.width)+ self.assertEqual(+ message_uis[0]._header_text().title.plain,+ "user",+ )+ self.assertEqual(+ message_uis[1]._header_text().title.plain,+ "agent",+ )+ self.assertNotIn("YOU", screenshot)+ self.assertNotIn("AGENT", screenshot)+ tool_group.collapsed = False+ await pilot.pause()+ self.assertTrue(editor.has_focus)+ self.assertLess(+ tool_group.region.height,+ chat.region.height,+ )+ self.assertLessEqual(composer.region.right, size[0])+ self.assertLessEqual(composer.region.bottom, size[1])+ self.assertEqual(len(chat.query("Button")), 0)+ self.assertIn("<svg", screenshot)++ async def test_running_reply_keeps_composer_available(self) -> None:+ observed: list[ChatUI.Submitted] = []++ def hook(message: TextualMessage) -> None:+ if isinstance(message, ChatUI.Submitted):+ observed.append(message)++ app = _ChatApp()+ async with app.run_test(message_hook=hook) as pilot:+ chat = app.query_one(ChatUI)+ await _publish(+ chat,+ ReplyStartEvent(+ session_id="s",+ reply_id="running",+ name="agent",+ ),+ )+ await pilot.pause()+ composer = app.query_one(ComposerUI)+ self.assertTrue(composer.display)+ self.assertFalse(app.query_one(_ComposerTextArea).disabled)++ app.query_one(_ComposerTextArea).focus()+ await pilot.press("h", "i", "enter")+ await pilot.pause()++ # Textual's message hook sees the same bubbling message at each+ # pump; there must still be only one logical Submitted instance.+ self.assertEqual(len({id(message) for message in observed}), 1)+ self.assertEqual(observed[-1].msg.get_text_content(), "hi")++ async def test_ctrl_c_interrupts_running_reply(self) -> None:+ observed: list[ChatUI.InterruptRequested] = []++ def hook(message: TextualMessage) -> None:+ if isinstance(message, ChatUI.InterruptRequested):+ observed.append(message)++ app = _ChatApp()+ async with app.run_test(message_hook=hook) as pilot:+ chat = app.query_one(ChatUI)+ await _publish(+ chat,+ ReplyStartEvent(+ session_id="s",+ reply_id="running",+ name="agent",+ ),+ )+ await pilot.pause()++ hint = app.query_one("#as-composer-hint", Static)+ self.assertIn("Ctrl+C interrupt", str(hint.render()))+ app.query_one(_ComposerTextArea).focus()+ await pilot.press("ctrl+c")+ await pilot.pause()++ self.assertEqual(len({id(message) for message in observed}), 1)+ self.assertEqual(observed[-1].reply_id, "running")++ async def test_explicit_input_disable(self) -> None:+ app = _ChatApp()+ async with app.run_test() as pilot:+ chat = app.query_one(ChatUI)+ chat.input_enabled = False+ await pilot.pause()+ self.assertTrue(app.query_one(ComposerUI).display)+ self.assertTrue(app.query_one(_ComposerTextArea).disabled)++ async def test_shift_enter_inserts_newline_before_submit(self) -> None:+ observed: list[ChatUI.Submitted] = []++ def hook(message: TextualMessage) -> None:+ if isinstance(message, ChatUI.Submitted):+ observed.append(message)++ app = _ChatApp()+ async with app.run_test(message_hook=hook) as pilot:+ editor = app.query_one(_ComposerTextArea)+ editor.focus()+ await pilot.press("a", "shift+enter", "b")+ await pilot.pause()+ self.assertEqual(editor.region.height, 2)+ await pilot.press("enter")+ await pilot.pause()++ self.assertEqual(observed[-1].msg.get_text_content(), "a\nb")++ async def test_composer_growth_stops_at_hidden_scroll_cap(self) -> None:+ app = _ChatApp()+ async with app.run_test() as pilot:+ editor = app.query_one(_ComposerTextArea)+ editor.focus()+ keys = ["a"]+ for _ in range(12):+ keys.extend(("shift+enter", "a"))+ await pilot.press(*keys)+ await pilot.pause()++ self.assertEqual(editor.region.height, 10)+ self.assertEqual(+ str(editor.styles.scrollbar_visibility),+ "hidden",+ )++ async def test_hitl_uses_keyboard_selection_and_restores_draft(+ self,+ ) -> None:+ observed: list[ChatUI.Confirmed] = []++ def hook(message: TextualMessage) -> None:+ if isinstance(message, ChatUI.Confirmed):+ observed.append(message)++ app = _ChatApp()+ async with app.run_test(message_hook=hook) as pilot:+ chat = app.query_one(ChatUI)+ editor = app.query_one(_ComposerTextArea)+ editor.focus()+ await pilot.press("d", "r", "a", "f", "t")+ await _publish(+ chat,+ ReplyStartEvent(+ session_id="s",+ reply_id="r1",+ name="agent",+ ),+ )+ await _publish(+ chat,+ ToolCallStartEvent(+ reply_id="r1",+ tool_call_id="c1",+ tool_call_name="Edit",+ ),+ )+ await _publish(+ chat,+ ToolCallDeltaEvent(+ reply_id="r1",+ tool_call_id="c1",+ delta='{"file_path": "demo.py"}',+ ),+ )+ await _publish(+ chat,+ ToolCallEndEvent(reply_id="r1", tool_call_id="c1"),+ )+ await _publish(+ chat,+ RequireUserConfirmEvent(+ reply_id="r1",+ tool_calls=[+ ToolCallBlock(+ id="c1",+ name="Edit",+ input='{"file_path": "demo.py"}',+ ),+ ],+ ),+ )+ await pilot.pause()++ self.assertFalse(app.query_one(ComposerUI).display)+ hitl = app.query_one(HitlUI)+ self.assertTrue(hitl.display)+ tool_group = app.query_one(ToolGroupUI)+ self.assertIn("[cyan]→", str(tool_group.title))+ self.assertEqual(tool_group._title.collapsed_symbol, "")+ self.assertEqual(tool_group._title.expanded_symbol, "")+ self.assertEqual(len(hitl.query(".as-section-rule")), 1)+ options = app.query_one(OptionList)+ self.assertTrue(options.has_focus)+ self.assertEqual(options.highlighted, 0)+ self.assertEqual(options.region.height, options.option_count)+ self.assertTrue(+ str(options.get_option_at_index(0).prompt).startswith("→ 1."),+ )+ await pilot.press("down")+ await pilot.pause()+ self.assertTrue(+ str(options.get_option_at_index(0).prompt).startswith(" 1."),+ )+ self.assertTrue(+ str(options.get_option_at_index(1).prompt).startswith("→ 2."),+ )+ await pilot.press("enter")+ await pilot.pause()++ self.assertEqual(len({id(message) for message in observed}), 1)+ value = observed[-1].value+ self.assertIsInstance(value, UserConfirmResultEvent)+ self.assertEqual(value.reply_id, "r1")+ self.assertFalse(value.confirm_results[0].confirmed)++ self.assertTrue(app.query_one(ComposerUI).display)+ self.assertFalse(app.query_one(HitlUI).display)+ self.assertEqual(editor.text, "draft")+ self.assertTrue(editor.has_focus)++ async def test_next_hitl_request_keeps_keyboard_focus(self) -> None:+ observed: list[ChatUI.Confirmed] = []++ def hook(message: TextualMessage) -> None:+ if isinstance(message, ChatUI.Confirmed):+ observed.append(message)++ app = _ChatApp(+ [+ AssistantMsg(+ name="agent",+ id="reply-1",+ content=[+ ToolCallBlock(+ id="call-1",+ name="Read",+ input="{}",+ state="asking",+ ),+ ToolCallBlock(+ id="call-2",+ name="Bash",+ input="{}",+ state="asking",+ ),+ ],+ ),+ ],+ )+ async with app.run_test(message_hook=hook) as pilot:+ options = app.query_one(OptionList)+ self.assertTrue(options.has_focus)+ await pilot.press("enter")+ await pilot.pause()++ self.assertTrue(app.query_one(HitlUI).display)+ self.assertTrue(options.has_focus)+ self.assertEqual(options.highlighted, 0)+ self.assertIn(+ "Bash",+ str(app.query_one("#as-hitl-body", Static).render()),+ )++ async def test_permission_rules_are_embedded_in_always_option(+ self,+ ) -> None:+ app = _ChatApp()+ async with app.run_test() as pilot:+ hitl = app.query_one(HitlUI)+ hitl.set_pending(+ [+ (+ "r1",+ "agent",+ ToolCallBlock(+ id="c1",+ name="Bash",+ input='{"command": "git status"}',+ state="asking",+ suggested_rules=[+ PermissionRule(+ tool_name="Bash",+ rule_content="git status",+ behavior=PermissionBehavior.ALLOW,+ source="tool",+ ),+ ],+ ),+ ),+ ],+ )+ await pilot.pause()++ options = app.query_one(OptionList)+ always = options.get_option_at_index(1)+ body = app.query_one("#as-hitl-body", Static)+ self.assertIn("allow Bash (git status)", str(always.prompt))+ self.assertNotIn("permission rules", str(body.render()).lower())++ async def test_external_execution_waiting_replaces_composer(self) -> None:+ app = _ChatApp()+ async with app.run_test() as pilot:+ chat = app.query_one(ChatUI)+ await _publish(+ chat,+ ReplyStartEvent(+ session_id="s",+ reply_id="r1",+ name="agent",+ ),+ )+ await _publish(+ chat,+ ToolCallStartEvent(+ reply_id="r1",+ tool_call_id="c1",+ tool_call_name="external_tool",+ ),+ )+ await _publish(+ chat,+ ToolCallEndEvent(reply_id="r1", tool_call_id="c1"),+ )+ await _publish(+ chat,+ RequireExternalExecutionEvent(+ reply_id="r1",+ tool_calls=[+ ToolCallBlock(+ id="c1",+ name="external_tool",+ input="{}",+ ),+ ],+ ),+ )+ await pilot.pause()++ self.assertFalse(app.query_one(ComposerUI).display)+ options = app.query_one(OptionList)+ self.assertEqual(options.option_count, 1)+ self.assertEqual(+ options.get_option_at_index(0).id,+ "interrupt",+ )++ async def test_ask_user_collects_schema_valid_answers(self) -> None:+ observed: list[ChatUI.ExternalExecutionSubmitted] = []++ def hook(message: TextualMessage) -> None:+ if isinstance(message, ChatUI.ExternalExecutionSubmitted):+ observed.append(message)++ questions = [+ {+ "header": "Version",+ "question": "Which version should we install?",+ "context": "The current version is too old.",+ "options": [+ {+ "label": "Latest (Recommended)",+ "description": "Upgrade to the supported release.",+ "preview": "current: 4.5\nnext: 5.2",+ },+ {+ "label": "Keep current",+ "description": "Continue without the integration.",+ },+ ],+ },+ {+ "header": "Features",+ "question": "Which features should be enabled?",+ "options": [+ {+ "label": "Rendering",+ "description": "Enable the render pipeline.",+ },+ {+ "label": "Export",+ "description": "Enable file export.",+ },+ ],+ "multi_select": True,+ },+ ]+ app = _ChatApp(+ [+ AssistantMsg(+ name="agent",+ id="reply",+ content=[+ ToolCallBlock(+ id="ask",+ name="AskUser",+ input=json.dumps({"questions": questions}),+ state="submitted",+ ),+ ],+ ),+ ],+ )+ async with app.run_test(message_hook=hook, size=(100, 30)) as pilot:+ ask_user = app.query_one(AskUserUI)+ options = app.query_one(".as-ask-user-options", OptionList)+ self.assertTrue(ask_user.display)+ self.assertFalse(app.query_one(ComposerUI).display)+ self.assertFalse(app.query_one(HitlUI).display)+ self.assertTrue(options.has_focus)+ self.assertIn(+ "Upgrade to the supported release.",+ str(options.get_option_at_index(0).prompt),+ )+ self.assertTrue(+ app.query_one(".as-ask-user-preview", Static).display,+ )++ await pilot.press("enter")+ await pilot.pause()+ self.assertIn(+ "Enable the render pipeline.",+ str(options.get_option_at_index(0).prompt),+ )+ await pilot.press("enter", "down", "down", "down", "enter")+ await pilot.pause()++ unique = {id(message): message for message in observed}+ self.assertEqual(len(unique), 1)+ value = next(iter(unique.values())).value+ self.assertIsInstance(value, ExternalExecutionResultEvent)+ result = value.execution_results[0]+ self.assertEqual(+ result.metadata,+ {+ "answers": [+ {+ "question": "Which version should we install?",+ "selected": ["Latest (Recommended)"],+ "other": None,+ },+ {+ "question": "Which features should be enabled?",+ "selected": ["Rendering"],+ "other": None,+ },+ ],+ },+ )+ await AskUser().check_external_result(result)+ self.assertFalse(ask_user.display)+ self.assertTrue(app.query_one(ComposerUI).display)++ async def test_ask_user_accepts_other_text(self) -> None:+ observed: list[ChatUI.ExternalExecutionSubmitted] = []++ def hook(message: TextualMessage) -> None:+ if isinstance(message, ChatUI.ExternalExecutionSubmitted):+ observed.append(message)++ tool_call = ToolCallBlock(+ id="ask",+ name="AskUser",+ input=json.dumps(+ {+ "questions": [+ {+ "header": "Approach",+ "question": "Which approach should we use?",+ "options": [+ {"label": "A", "description": "First."},+ {"label": "B", "description": "Second."},+ ],+ },+ ],+ },+ ),+ state="submitted",+ )+ app = _ChatApp(+ [AssistantMsg(name="agent", id="reply", content=[tool_call])],+ )+ async with app.run_test(message_hook=hook) as pilot:+ await pilot.press("down", "down", "enter")+ await pilot.pause()+ other = app.query_one(".as-ask-user-other", Input)+ self.assertTrue(other.display)+ self.assertTrue(other.has_focus)+ await pilot.press(*"custom plan", "enter")+ await pilot.pause()++ result = observed[0].value.execution_results[0]+ self.assertEqual(+ result.metadata["answers"][0],+ {+ "question": "Which approach should we use?",+ "selected": [],+ "other": "custom plan",+ },+ )+ await AskUser().check_external_result(result)++ async def test_invalid_ask_user_input_returns_error_result(self) -> None:+ observed: list[ChatUI.ExternalExecutionSubmitted] = []++ def hook(message: TextualMessage) -> None:+ if isinstance(message, ChatUI.ExternalExecutionSubmitted):+ observed.append(message)++ app = _ChatApp(+ [+ AssistantMsg(+ name="agent",+ id="reply",+ content=[+ ToolCallBlock(+ id="ask",+ name="AskUser",+ input=json.dumps({"questions": []}),+ state=ToolCallState.SUBMITTED,+ ),+ ],+ ),+ ],+ )+ async with app.run_test(message_hook=hook) as pilot:+ await pilot.pause()++ unique = {id(message): message for message in observed}+ self.assertEqual(len(unique), 1)+ result = next(iter(unique.values())).value.execution_results[0]+ self.assertEqual(result.state, ToolResultState.ERROR)+ self.assertEqual(result.metadata, {"answers": []})+ self.assertIn("Invalid AskUser input", result.output)+ await AskUser().check_external_result(result)+ self.assertFalse(app.query_one(AskUserUI).display)+ self.assertTrue(app.query_one(ComposerUI).display)++ async def test_edit_tool_uses_authoritative_diff_stats(self) -> None:+ app = _ChatApp()+ async with app.run_test() as pilot:+ chat = app.query_one(ChatUI)+ await _publish(+ chat,+ ReplyStartEvent(+ session_id="s",+ reply_id="r1",+ name="agent",+ ),+ )+ await _publish(+ chat,+ ToolCallStartEvent(+ reply_id="r1",+ tool_call_id="c1",+ tool_call_name="Edit",+ ),+ )+ await _publish(+ chat,+ ToolCallDeltaEvent(+ reply_id="r1",+ tool_call_id="c1",+ delta='{"file_path": "demo.py"}',+ ),+ )+ await _publish(+ chat,+ ToolCallEndEvent(reply_id="r1", tool_call_id="c1"),+ )+ await _publish(+ chat,+ ToolResultStartEvent(+ reply_id="r1",+ tool_call_id="c1",+ tool_call_name="Edit",+ ),+ )+ await _publish(+ chat,+ ToolResultEndEvent(+ reply_id="r1",+ tool_call_id="c1",+ state=ToolResultState.SUCCESS,+ metadata={"diff": "@@ -1 +1 @@\n-old\n+new\n"},+ ),+ )+ await pilot.pause()++ self.assertIn("+1 -1", app.query_one(ToolGroupUI).title)++ async def test_edit_shows_diff_and_read_shows_only_result(self) -> None:+ finished_at = "2026-01-01T00:00:01+00:00"+ msg = AssistantMsg(+ name="agent",+ finished_at=finished_at,+ content=[+ ToolCallBlock(+ id="edit",+ name="Edit",+ input='{"file_path": "demo.py", "old_str": "old"}',+ state="finished",+ ),+ ToolResultBlock(+ id="edit",+ name="Edit",+ output="Successfully updated demo.py",+ state=ToolResultState.SUCCESS,+ metadata={"diff": "@@ -1 +1 @@\n-old\n+new\n"},+ ),+ ToolCallBlock(+ id="read",+ name="Read",+ input='{"file_path": "demo.py"}',+ state="finished",+ ),+ ToolResultBlock(+ id="read",+ name="Read",+ output=" 1\tprint('ready')",+ state=ToolResultState.SUCCESS,+ ),+ ],+ )+ app = _MessagesApp([msg])+ async with app.run_test(size=(100, 24)) as pilot:+ app.query_one(ToolGroupUI).collapsed = False+ await pilot.pause()+ bodies = list(app.query(".as-tool-body"))+ edit_items = bodies[0].render()._renderable.renderables+ read_items = bodies[1].render()._renderable.renderables++ self.assertEqual(+ getattr(edit_items[-1], "code", ""),+ "@@ -1 +1 @@\n-old\n+new\n",+ )+ self.assertEqual(len(read_items), 1)+ self.assertEqual(+ getattr(read_items[0], "plain", ""),+ " 1\tprint('ready')",+ )+ self.assertEqual(bodies[0].styles.padding.left, 1)+ self.assertEqual(bodies[1].styles.padding.left, 1)++ async def test_tool_group_uses_worst_result_state(self) -> None:+ finished_at = "2026-01-01T00:00:01+00:00"+ msg = AssistantMsg(+ name="agent",+ finished_at=finished_at,+ content=[+ ToolCallBlock(+ id="one",+ name="Bash",+ input="{}",+ state="finished",+ ),+ ToolResultBlock(+ id="one",+ name="Bash",+ output="ok",+ state=ToolResultState.SUCCESS,+ ),+ ToolCallBlock(+ id="two",+ name="Bash",+ input="{}",+ state="finished",+ ),+ ToolResultBlock(+ id="two",+ name="Bash",+ output="failed",+ state=ToolResultState.ERROR,+ ),+ ],+ )+ app = _MessagesApp([msg])+ async with app.run_test() as pilot:+ tool_group = app.query_one(ToolGroupUI)+ self.assertIn("[red]→ ✗", str(tool_group.title))++ tool_group.collapsed = False+ await pilot.pause()+ self.assertIn("[red]↓ ✗", str(tool_group.title))+++class _FakeTarget:+ def __init__(self) -> None:+ self.done = asyncio.Event()+ self.inputs: list[Any] = []++ async def reply_stream(+ self,+ inputs: Any,+ ) -> AsyncGenerator[Any, None]:+ self.inputs.append(inputs)+ yield ReplyStartEvent(+ session_id="s",+ reply_id="reply",+ name="agent",+ )+ yield TextBlockStartEvent(reply_id="reply", block_id="text")+ yield TextBlockDeltaEvent(+ reply_id="reply",+ block_id="text",+ delta="response",+ )+ yield TextBlockEndEvent(reply_id="reply", block_id="text")+ yield ReplyEndEvent(session_id="s", reply_id="reply")+ self.done.set()+++class _SerialTarget:+ def __init__(self) -> None:+ self.first_started = asyncio.Event()+ self.release_first = asyncio.Event()+ self.done = asyncio.Event()+ self.inputs: list[str] = []+ self.active = 0+ self.max_active = 0++ async def reply_stream(+ self,+ inputs: Msg,+ ) -> AsyncGenerator[Any, None]:+ text = inputs.get_text_content()+ self.inputs.append(text)+ self.active += 1+ self.max_active = max(self.max_active, self.active)+ reply_id = f"reply-{len(self.inputs)}"+ try:+ yield ReplyStartEvent(+ session_id="s",+ reply_id=reply_id,+ name="agent",+ )+ if text == "first":+ self.first_started.set()+ await self.release_first.wait()+ yield ReplyEndEvent(session_id="s", reply_id=reply_id)+ finally:+ self.active -= 1+ if len(self.inputs) == 2 and self.active == 0:+ self.done.set()+++class LauncherTest(unittest.IsolatedAsyncioTestCase):+ async def test_launcher_serializes_concurrent_submissions(self) -> None:+ target = _SerialTarget()+ app = _AgentScopeTUI(target, [], "user")+ async with app.run_test(size=(80, 24)) as pilot:+ app._start_stream(UserMsg(name="user", content="first"))+ await asyncio.wait_for(target.first_started.wait(), timeout=1)+ app._start_stream(UserMsg(name="user", content="second"))+ await pilot.pause()++ self.assertListEqual(target.inputs, ["first"])+ self.assertEqual(target.max_active, 1)+ self.assertListEqual(+ [+ msg.get_text_content()+ for msg in app.query_one(ChatUI).messages+ ],+ ["first", None, "second"],+ )++ target.release_first.set()+ await asyncio.wait_for(target.done.wait(), timeout=1)+ self.assertListEqual(target.inputs, ["first", "second"])+ self.assertEqual(target.max_active, 1)+ self.assertDictEqual(app._replies, {})++ async def test_interrupt_parked_reply_sends_event(self) -> None:+ target = _FakeTarget()+ app = _AgentScopeTUI(+ target,+ [+ AssistantMsg(+ name="agent",+ id="parked",+ content=[+ ToolCallBlock(+ id="call",+ name="Bash",+ input="{}",+ state=ToolCallState.ASKING,+ ),+ ],+ ),+ ],+ "user",+ )+ async with app.run_test(size=(80, 24)):+ with patch.object(app, "_start_stream") as start_stream:+ app._on_interrupt(ChatUI.InterruptRequested("parked"))++ event = start_stream.call_args.args[0]+ self.assertIsInstance(event, UserInterruptEvent)+ self.assertEqual(event.reply_id, "parked")++ async def test_tool_result_state_does_not_make_reply_parked(self) -> None:+ target = _FakeTarget()+ app = _AgentScopeTUI(+ target,+ [+ AssistantMsg(+ name="agent",+ id="finished-tool",+ content=[+ ToolResultBlock(+ id="call",+ name="Bash",+ output="done",+ state=ToolResultState.SUCCESS,+ ),+ ],+ ),+ ],+ "user",+ )+ async with app.run_test(size=(80, 24)):+ chat = app.query_one(ChatUI)+ self.assertFalse(chat.is_reply_parked("finished-tool"))++ async def test_launcher_forwards_submission_and_streams_reply(+ self,+ ) -> None:+ target = _FakeTarget()+ app = _AgentScopeTUI(target, [], "user")+ async with app.run_test(size=(80, 24)) as pilot:+ editor = app.query_one(_ComposerTextArea)+ editor.focus()+ await pilot.press("h", "i", "enter")+ await asyncio.wait_for(target.done.wait(), timeout=1)+ await pilot.pause()++ messages = app.query_one(ChatUI).messages+ self.assertEqual(len(messages), 2)+ self.assertEqual(messages[0].get_text_content(), "hi")+ self.assertEqual(messages[1].get_text_content(), "response")+ self.assertEqual(target.inputs[0].get_text_content(), "hi")++ async def test_launcher_forwards_ask_user_result(self) -> None:+ target = _FakeTarget()+ app = _AgentScopeTUI(target, [], "user")+ value = ExternalExecutionResultEvent(+ reply_id="reply",+ execution_results=[+ ToolResultBlock(+ id="ask",+ name="AskUser",+ output="Selected A",+ state=ToolResultState.SUCCESS,+ metadata={+ "answers": [+ {+ "question": "Which?",+ "selected": ["A"],+ "other": None,+ },+ ],+ },+ ),+ ],+ )+ async with app.run_test(size=(80, 24)):+ app._on_external_execution_submitted(+ ChatUI.ExternalExecutionSubmitted(value),+ )+ await asyncio.wait_for(target.done.wait(), timeout=1)++ self.assertIs(target.inputs[0], value)++ def test_exit_command_quits_without_forwarding_to_target(self) -> None:+ target = _FakeTarget()+ app = _AgentScopeTUI(target, [], "user")+ event = ChatUI.Submitted(UserMsg(name="user", content=" /EXIT "))++ with patch.object(app, "exit") as exit_app:+ app._on_submitted(event)++ exit_app.assert_called_once_with()+ self.assertEqual(target.inputs, [])+ self.assertEqual(app.BINDINGS, [])+++if __name__ == "__main__":+ unittest.main()