From f031ec5c14126ad47fb0f84a728aeaab333a945f Mon Sep 17 00:00:00 2001 From: Hunter Xue Date: Sat, 5 Dec 2026 19:23:16 +0800 Subject: [PATCH] feat(cli): restore RuntimeAdapter interactive TUI --- ksadk/cli/cmd_run.py | 27 +- ksadk/cli/runtime_bootstrap.py | 48 ++- ksadk/runtime/conversation_execution.py | 58 ++- ksadk/tui/loop.py | 36 +- ksadk/tui/runtime_runner.py | 351 ++++++++++++++++++ tests/cli/test_run_interactive.py | 82 ++++ tests/runtime/test_semantic_control_events.py | 90 +++++ tests/tui/test_runtime_runner.py | 199 ++++++++++ tests/tui/test_runtime_runner_integration.py | 117 ++++++ 9 files changed, 978 insertions(+), 30 deletions(-) create mode 100644 ksadk/tui/runtime_runner.py create mode 100644 tests/cli/test_run_interactive.py create mode 100644 tests/runtime/test_semantic_control_events.py create mode 100644 tests/tui/test_runtime_runner.py create mode 100644 tests/tui/test_runtime_runner_integration.py diff --git a/ksadk/cli/cmd_run.py b/ksadk/cli/cmd_run.py index 4fecee341..5d678dae6 100644 --- a/ksadk/cli/cmd_run.py +++ b/ksadk/cli/cmd_run.py @@ -15,7 +15,10 @@ from ksadk.cli.error_utils import ensure_json_output_supported, print_exception from ksadk.cli.local_runtime import reexec_with_project_venv_if_needed -from ksadk.cli.runtime_bootstrap import create_runtime_web_app +from ksadk.cli.runtime_bootstrap import ( + create_local_runtime_composition, + create_runtime_web_app, +) from ksadk.cli.ui import ( print_error, print_info, @@ -207,11 +210,25 @@ def _run_custom( print_warn(f"Tracing 初始化失败: {e}") if interactive: - del show_thinking, no_stream, no_alt_screen - print_error( - "RuntimeAdapter TUI 尚未接通;请使用 `ksadk web` 或不带 --interactive 启动" + from ksadk.tui.runtime_runner import CanonicalRuntimeRunner, run_runtime_tui + + try: + composition = create_local_runtime_composition(result, agent_path) + runner = CanonicalRuntimeRunner( + composition, + agent_id=str(result.name), + ) + except Exception as e: + print_exception("RuntimeAdapter 初始化失败", e) + raise SystemExit(1) + run_runtime_tui( + runner, + show_thinking=show_thinking, + no_stream=no_stream, + project_dir=str(agent_path), + no_alt_screen=no_alt_screen, ) - raise SystemExit(2) + return try: runtime_app = create_runtime_web_app(result, agent_path, auto_tracing=not no_trace) diff --git a/ksadk/cli/runtime_bootstrap.py b/ksadk/cli/runtime_bootstrap.py index 9dc326d8e..6d3966174 100644 --- a/ksadk/cli/runtime_bootstrap.py +++ b/ksadk/cli/runtime_bootstrap.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +from dataclasses import dataclass from pathlib import Path from typing import Any @@ -33,10 +34,20 @@ def _managed_a2a_card() -> Any: return build_managed_a2a_card_if_configured() -def create_runtime_web_app( - detection: Any, agent_path: Path, *, auto_tracing: bool = True, -) -> FastAPI: - """Compose one detected project around the canonical RuntimeExecutor.""" +@dataclass +class LocalRuntimeComposition: + """Framework-neutral Runtime objects shared by local CLI frontends.""" + + launch_context: RuntimeLaunchContext + executor: RuntimeExecutor + managed_a2a: Any = None + managed_a2a_adapter: Any = None + + +def create_local_runtime_composition( + detection: Any, agent_path: Path, +) -> LocalRuntimeComposition: + """Build the canonical Runtime boundary without creating an HTTP app.""" config = dict(getattr(detection, "raw_config", None) or {}) managed_runtime = os.getenv("AGENTENGINE_MANAGED_RUNTIME") == "1" @@ -82,13 +93,28 @@ def create_runtime_web_app( ): executor.configure_managed_a2a(managed_a2a) adapter = executor.create_adapter(context) + return LocalRuntimeComposition( + launch_context=context, + executor=executor, + managed_a2a=managed_a2a, + managed_a2a_adapter=adapter, + ) + + +def create_runtime_web_app( + detection: Any, agent_path: Path, *, auto_tracing: bool = True, +) -> FastAPI: + """Compose one detected project around the canonical RuntimeExecutor.""" + + composition = create_local_runtime_composition(detection, agent_path) + managed_runtime = os.getenv("AGENTENGINE_MANAGED_RUNTIME") == "1" return create_runtime_app( RuntimeAppConfig( - runtime_executor=executor, - launch_context=context, + runtime_executor=composition.executor, + launch_context=composition.launch_context, agui=agui_config_for_detection(detection), - a2a=managed_a2a, - a2a_runtime_adapter=adapter, + a2a=composition.managed_a2a, + a2a_runtime_adapter=composition.managed_a2a_adapter, local_mcp_oauth=not managed_runtime, auto_tracing=auto_tracing, ), @@ -96,4 +122,8 @@ def create_runtime_web_app( ) -__all__ = ["create_runtime_web_app"] +__all__ = [ + "LocalRuntimeComposition", + "create_local_runtime_composition", + "create_runtime_web_app", +] diff --git a/ksadk/runtime/conversation_execution.py b/ksadk/runtime/conversation_execution.py index fa75acea2..8e33d086d 100644 --- a/ksadk/runtime/conversation_execution.py +++ b/ksadk/runtime/conversation_execution.py @@ -557,6 +557,36 @@ def _validate_event_scope( @transient_skill_connection async def iter_runtime_conversation_semantic_events( **kwargs: Any, +) -> AsyncIterator[dict[str, Any]]: + """Own the canonical source and its semantic projector for one turn.""" + + include_control_events = bool(kwargs.pop("_include_control_events", False)) + execution_context: dict[str, str] = {} + source_events = iter_runtime_conversation_events( + **kwargs, _execution_context=execution_context + ) + projector = _project_runtime_conversation_semantic_events( + source_events, + execution_context=execution_context, + include_control_events=include_control_events, + **kwargs, + ) + try: + async for event in projector: + yield event + finally: + try: + await projector.aclose() + finally: + await source_events.aclose() + + +async def _project_runtime_conversation_semantic_events( + source_events: AsyncIterator[RuntimeEvent], + *, + execution_context: dict[str, str], + include_control_events: bool = False, + **kwargs: Any, ) -> AsyncIterator[dict[str, Any]]: """Project canonical RuntimeEvents into the transport-neutral serializer input.""" @@ -564,7 +594,6 @@ async def iter_runtime_conversation_semantic_events( emitted_text = "" reasoning_parts: dict[tuple[str, str, str], str] = {} approval: dict[str, Any] | None = None - execution_context: dict[str, str] = {} # (scope_id, call_id) → tool_name:不同子运行可复用原生 call_id。 # (ToolResultContent 不带 name,前端靠 name 关联 call/result)。 _tool_name_by_call_id: dict[tuple[str, str], str] = {} @@ -573,9 +602,7 @@ async def iter_runtime_conversation_semantic_events( # ItemCompleted.snapshot 都带(需去重);LangGraph/ADK 的 ItemStarted.initial=None, # ToolCallContent 只出现在 ItemCompleted.snapshot(需在 Completed 补发,不能跳过)。 _emitted_tool_call_ids: set[tuple[str, str]] = set() - async for event in iter_runtime_conversation_events( - **kwargs, _execution_context=execution_context - ): + async for event in source_events: patch = reducer.apply(event) if not patch.applied: continue @@ -602,11 +629,14 @@ async def iter_runtime_conversation_semantic_events( } emitted_text = current if isinstance(event, RunStarted): - yield { + started = { "type": "started", "session_id": execution_context.get("session_id", ""), "metadata": dict(event.source.metadata), } + if include_control_events: + started["run_id"] = event.run_id + yield started elif isinstance(event, (ContextCompactionStarted, ContextCompactionCompleted)): semantic = {"type": "compaction", "trigger": event.trigger} # Distinguish start vs done for SSE projection (response.compaction.start/done) @@ -677,6 +707,15 @@ async def iter_runtime_conversation_semantic_events( "run_id": part.call_id, } elif isinstance(event, InteractionRequested): + if include_control_events: + yield { + "type": "interaction", + "run_id": event.run_id, + "session_id": execution_context.get("session_id", ""), + "interaction_id": event.interaction_id, + "interaction_kind": event.interaction_kind, + "request": event.request.model_dump(mode="json", by_alias=True), + } if event.interaction_kind == "approval" and event.request.request_type == "approval": detail = event.request.detail approval = dict(detail) if isinstance(detail, Mapping) else {} @@ -687,7 +726,7 @@ async def iter_runtime_conversation_semantic_events( approval.setdefault("call_id", event.request.call_id) approval.setdefault("kind", event.request.kind) elif isinstance(event, RunInterrupted): - yield { + interrupted = { "type": "interrupt", "interrupt_info": approval or { @@ -697,6 +736,13 @@ async def iter_runtime_conversation_semantic_events( }, "session_id": execution_context.get("session_id", ""), } + if include_control_events: + interrupted.update( + run_id=event.run_id, + interaction_id=event.interaction_id, + continuation_id=event.continuation_id, + ) + yield interrupted elif isinstance(event, RunFailed): usage = execution_context.get("terminal_usage") or reducer.usage_snapshot() metrics = event.source.metadata.get("metrics") diff --git a/ksadk/tui/loop.py b/ksadk/tui/loop.py index 749c1355d..d28e360c0 100644 --- a/ksadk/tui/loop.py +++ b/ksadk/tui/loop.py @@ -191,9 +191,10 @@ async def render_stream( chunk_type = str(chunk.get("type") or "text") if chunk_type == "thinking": - delta = chunk.get("delta") or "" - if delta: - full_thinking += str(delta) + delta = str(chunk.get("delta") or "") + replace = bool(chunk.get("replace") or chunk.get("operation") == "replace") + if delta or replace: + full_thinking = delta if replace else full_thinking + delta saw_content = True await r.on_thinking(full_thinking) continue @@ -252,8 +253,9 @@ async def render_stream( await r.on_usage(chunk_usage) saw_content = True continue - if delta: - full_response += delta + replace = bool(chunk.get("replace") or chunk.get("operation") == "replace") + if delta or replace: + full_response = delta if replace else full_response + delta saw_content = True await r.on_text(full_response) except InterruptPending: @@ -354,10 +356,12 @@ def __init__( assistant_entry: TranscriptEntry | None = None, *, show_thinking: bool = False, + stream_updates: bool = True, ) -> None: self.loop = loop self.assistant_entry = assistant_entry self.show_thinking = show_thinking + self.stream_updates = stream_updates self._tool_entries: list[TranscriptEntry] = [] self._ordered_entries: list[TranscriptEntry] = [] self._tool_entries_by_key: dict[str, TranscriptEntry] = {} @@ -400,7 +404,8 @@ async def on_text(self, full_text: str) -> None: self._ordered_entries.append(self._active_text_entry) self._active_text_entry.content += delta self._last_full_text = full_text - self.loop._set_streaming(self._compose_streaming()) + if self.stream_updates: + self.loop._set_streaming(self._compose_streaming()) async def on_thinking(self, full_thinking: str) -> None: if self.loop is not None and self.assistant_entry is not None: @@ -432,7 +437,8 @@ async def on_tool_call( entry = existing entry._tool_call_id = merge_key # type: ignore[attr-defined] # tool 行立即进动态区(就地在文本流里显示),不中途落定避免时序错乱。 - self.loop._set_streaming(self._compose_streaming()) + if self.stream_updates: + self.loop._set_streaming(self._compose_streaming()) async def on_usage(self, usage: dict) -> None: if self.loop is not None and self.assistant_entry is not None: @@ -491,11 +497,13 @@ def __init__( runner, *, show_thinking: bool = False, + no_stream: bool = False, project_dir: str = ".", no_alt_screen: bool = False, ) -> None: self.runner = runner self.show_thinking = show_thinking + self.no_stream = no_stream self.project_dir = Path(project_dir).resolve() self._no_alt_screen = no_alt_screen self.session_id = str(getattr(runner, "session_id", None) or uuid.uuid4().hex[:8]) @@ -992,6 +1000,7 @@ async def _run_turn_async( self, assistant_entry, show_thinking=self.show_thinking, + stream_updates=not self.no_stream, ) try: response, usage = await render_stream(self.runner, input_data, renderer=renderer) @@ -1911,15 +1920,22 @@ def _clean(match: "re.Match[str]") -> str: def run_tui( - runner, *, show_thinking: bool = False, project_dir: str = ".", no_alt_screen: bool = False + runner, + *, + show_thinking: bool = False, + no_stream: bool = False, + project_dir: str = ".", + no_alt_screen: bool = False, ) -> None: - """TUI 入口:被 cmd_invoke._invoke_tui / cmd_run._run_custom 调用。 + """Legacy Runner/RemoteRunner TUI 入口。 - ``no_alt_screen`` 作为兼容参数保留;TUI 现在默认使用 Codex-style inline viewport。 + 本地 RuntimeAdapter 项目使用 ``ksadk.tui.runtime_runner.run_runtime_tui``。 + ``no_alt_screen`` 作为兼容参数保留;TUI 默认使用 inline viewport。 """ InteractionLoop( runner, show_thinking=show_thinking, + no_stream=no_stream, project_dir=project_dir, no_alt_screen=no_alt_screen, ).run() diff --git a/ksadk/tui/runtime_runner.py b/ksadk/tui/runtime_runner.py new file mode 100644 index 000000000..ce810dfd1 --- /dev/null +++ b/ksadk/tui/runtime_runner.py @@ -0,0 +1,351 @@ +"""Canonical RuntimeAdapter backend for the local interactive TUI. + +The existing :class:`InteractionLoop` remains a UI and legacy RemoteRunner +consumer. This module adapts the canonical conversation stream to that UI +without exposing ``adapter._runner`` or starting a loopback HTTP server. +""" + +from __future__ import annotations + +import asyncio +import inspect +import uuid +from collections.abc import AsyncIterator, Callable, Mapping +from typing import TYPE_CHECKING, Any + +from ksadk.runtime.conversation_execution import iter_runtime_conversation_semantic_events + +if TYPE_CHECKING: + from ksadk.cli.runtime_bootstrap import LocalRuntimeComposition + + +async def _shielded_events( + events: AsyncIterator[dict[str, Any]], + pending: dict[str, asyncio.Task | None], +) -> AsyncIterator[dict[str, Any]]: + """Keep an in-flight read alive until the outer consumer handles cancel.""" + + while True: + task = asyncio.ensure_future(anext(events)) + pending["task"] = task + try: + event = await asyncio.shield(task) + except StopAsyncIteration: + pending["task"] = None + return + pending["task"] = None + yield event + + +class CanonicalRuntimeRunner: + """Small Runner-shaped facade backed exclusively by RuntimeExecutor. + + Only the UI-facing shape is Runner-compatible. Execution, history, + persistence and cancellation stay inside the canonical conversation path. + """ + + def __init__( + self, + composition: "LocalRuntimeComposition", + *, + agent_id: str, + user_id: str = "local_user", + session_id: str | None = None, + model: str | None = None, + session_service_provider: Callable[[], Any] | None = None, + ) -> None: + self.composition = composition + self.agent_id = agent_id + self.user_id = user_id + self.session_id = session_id or uuid.uuid4().hex[:8] + configured_model = composition.launch_context.config.get("model") + self.model = model or (str(configured_model) if configured_model else None) + self.available_models = self._configured_models( + composition.launch_context.config.get("models") + or composition.launch_context.config.get("allowed_models") + ) + self.model_metadata: dict[str, Any] = {} + self.api_format = "" + self._observed_model: str | None = None + self._closed = False + self._owns_session_service = session_service_provider is None + if session_service_provider is None: + from ksadk.sessions import create_session_service + + service = create_session_service() + self._session_service_provider = lambda: service + else: + self._session_service_provider = session_service_provider + + @staticmethod + def _configured_models(raw: Any) -> list[dict[str, Any]]: + if not isinstance(raw, (list, tuple, set, frozenset)): + return [] + models = [] + for item in raw: + if isinstance(item, str) and item.strip(): + models.append({"id": item.strip()}) + elif isinstance(item, Mapping): + model_id = str(item.get("id") or item.get("name") or "").strip() + if model_id: + models.append({**dict(item), "id": model_id}) + return models + + @property + def launch_context(self): + return self.composition.launch_context + + @property + def executor(self): + return self.composition.executor + + async def stream(self, input_data: dict[str, Any]) -> AsyncIterator[dict[str, Any]]: + """Execute one new turn and project canonical semantic events. + + Interaction replies are deliberately fail-closed in this first + vertical slice. A live interaction must not leave the TUI blocked on + a stream that can only advance after a reply, so the runner requests a + real Runtime cancellation and reports that limitation honestly. + """ + + if input_data.get("resume"): + yield { + "type": "error", + "message": "当前 Runtime TUI 尚未接入交互恢复;未执行旧式 resume=True 请求。", + } + return + + user_input = str(input_data.get("input") or "") + active_run_id = "" + interrupted_run_id = "" + interaction_cancelled = False + pending: dict[str, asyncio.Task | None] = {"task": None} + events = iter_runtime_conversation_semantic_events( + executor=self.executor, + launch_context=self.launch_context, + agent_id=self.agent_id, + user_id=self.user_id, + messages=[{"role": "user", "content": user_input}], + session_id=self.session_id, + model=self.model, + session_service_provider=self._session_service_provider, + _include_control_events=True, + ) + shielded = _shielded_events(events, pending) + try: + async for event in shielded: + resolved_session = str(event.get("session_id") or "").strip() + if resolved_session: + self.session_id = resolved_session + event_type = str(event.get("type") or "") + if event_type == "started": + active_run_id = str(event.get("run_id") or active_run_id) + if event_type == "interaction": + interaction_cancelled = True + result = await self._cancel_unsupported_interaction(event) + yield { + "type": "error", + "message": ( + "当前 Runtime TUI 尚未接入交互回包,已请求取消本轮 " + f"(cancel={result});请使用 `ksadk web` 处理此类交互。" + ), + } + continue + if event_type == "interrupt": + interrupted_run_id = str(event.get("run_id") or interrupted_run_id) + if not interaction_cancelled: + yield { + "type": "error", + "message": ( + "Runtime 正在等待外部恢复;当前 TUI 尚未接入该操作," + "未自动批准或续跑。请使用 `ksadk web`。" + ), + } + yield {"type": "final", "usage": event.get("usage")} + continue + for chunk in self._semantic_to_chunks( + event, suppress_cancelled=interaction_cancelled + ): + yield chunk + except asyncio.CancelledError: + # A consumer can be cancelled while the semantic generator is + # suspended at a yield. Closing it then injects GeneratorExit, + # not CancelledError, so the conversation layer cannot be relied + # on as the sole cancellation signal. + if active_run_id: + handle = self.executor.find_handle( + self.launch_context.runtime_type, active_run_id, self.session_id, + ) + if handle is not None: + await self.executor.cancel(handle) + raise + finally: + await shielded.aclose() + task = pending.get("task") + if task is not None: + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + await events.aclose() + if interrupted_run_id: + await self._close_interrupted(interrupted_run_id) + + async def invoke(self, input_data: dict[str, Any]) -> dict[str, Any]: + """Collect one canonical execution without starting a second request.""" + + output = "" + usage: dict[str, Any] | None = None + async for chunk in self.stream(input_data): + chunk_type = chunk.get("type") + if chunk_type == "text": + delta = str(chunk.get("delta") or "") + if chunk.get("replace") or chunk.get("operation") == "replace": + output = delta + else: + output += delta + elif chunk_type == "final": + output = str(chunk.get("output") or output) + raw_usage = chunk.get("usage") + if isinstance(raw_usage, Mapping): + usage = dict(raw_usage) + result: dict[str, Any] = {"output": output} + if usage is not None: + result["usage"] = usage + return result + + def _semantic_to_chunks( + self, event: Mapping[str, Any], *, suppress_cancelled: bool + ) -> list[dict[str, Any]]: + event_type = str(event.get("type") or "") + if event_type in {"started", "compaction"}: + return [] + if event_type in {"text", "thinking"}: + return [dict(event)] + if event_type in {"tool_call", "tool_call_started"}: + call_id = str( + event.get("call_id") or event.get("run_id") or event.get("item_id") or "" + ) + return [{ + "type": "tool_call", + "tool_name": event.get("tool_name") or event.get("name") or "tool", + "tool_args": event.get("tool_args", event.get("args")) or {}, + "call_id": call_id, + "status": event.get("status") or "running", + }] + if event_type == "tool_result": + return [{ + "type": "tool_result", + "tool_name": event.get("tool_name") or event.get("name") or "tool", + "tool_output": event.get("tool_output", event.get("output")), + "call_id": str(event.get("call_id") or event.get("run_id") or ""), + }] + if event_type == "error": + return [ + {"type": "error", "message": event.get("message") or "Agent 运行失败"}, + {"type": "final", "usage": event.get("usage")}, + ] + if event_type == "cancelled": + chunks = [] + if not suppress_cancelled: + chunks.append({"type": "error", "message": "Runtime 已取消当前 Run"}) + chunks.append({"type": "final", "usage": event.get("usage")}) + return chunks + if event_type == "completed": + model = event.get("model") + if model: + self._observed_model = str(model) + return [{ + "type": "final", + "output": event.get("output_text") or "", + "usage": event.get("usage"), + "metadata": event.get("metadata"), + }] + return [] + + async def _cancel_unsupported_interaction(self, event: Mapping[str, Any]) -> str: + run_id = str(event.get("run_id") or "").strip() + handle = self.executor.find_handle( + self.launch_context.runtime_type, run_id, self.session_id, + ) + if handle is None: + raise RuntimeError("Runtime 交互需要回包,但已找不到对应的 active Run") + result = await self.executor.cancel(handle) + value = str(getattr(result, "value", result)) + if value == "failed": + raise RuntimeError("Runtime 交互需要回包,且取消当前 Run 失败") + return value + + async def _close_interrupted(self, run_id: str) -> None: + handle = self.executor.find_handle( + self.launch_context.runtime_type, run_id, self.session_id, + ) + if handle is not None: + await self.executor.close(handle) + + async def aclose(self) -> None: + if self._closed: + return + self._closed = True + try: + await self.executor.close_all() + finally: + try: + adapter = self.composition.managed_a2a_adapter + close_adapter = getattr(adapter, "close_app_resources", None) + if callable(close_adapter): + result = close_adapter() + if inspect.isawaitable(result): + await result + finally: + if self._owns_session_service: + service = self._session_service_provider() + close = getattr(service, "aclose", None) + if callable(close): + await close() + + +async def _run_and_close( + runner: CanonicalRuntimeRunner, + *, + show_thinking: bool, + no_stream: bool, + project_dir: str, + no_alt_screen: bool, +) -> None: + from ksadk.tui.loop import InteractionLoop + + try: + loop = InteractionLoop( + runner, + show_thinking=show_thinking, + no_stream=no_stream, + project_dir=project_dir, + no_alt_screen=no_alt_screen, + ) + await loop.run_async() + finally: + await runner.aclose() + + +def run_runtime_tui( + runner: CanonicalRuntimeRunner, + *, + show_thinking: bool = False, + no_stream: bool = False, + project_dir: str = ".", + no_alt_screen: bool = False, +) -> None: + """Run the canonical TUI and release resources in the same event loop.""" + + asyncio.run( + _run_and_close( + runner, + show_thinking=show_thinking, + no_stream=no_stream, + project_dir=project_dir, + no_alt_screen=no_alt_screen, + ) + ) + + +__all__ = ["CanonicalRuntimeRunner", "run_runtime_tui"] diff --git a/tests/cli/test_run_interactive.py b/tests/cli/test_run_interactive.py new file mode 100644 index 000000000..999665fe0 --- /dev/null +++ b/tests/cli/test_run_interactive.py @@ -0,0 +1,82 @@ +from types import SimpleNamespace + +import pytest + +from ksadk.cli import cmd_run + + +def _result(): + return SimpleNamespace( + name="demo-agent", + type=SimpleNamespace(value="langgraph"), + raw_config={}, + ) + + +def test_interactive_run_uses_canonical_runtime_tui(monkeypatch, tmp_path): + composition = SimpleNamespace(launch_context=object(), executor=object()) + monkeypatch.setattr(cmd_run, "create_local_runtime_composition", lambda *_: composition) + monkeypatch.setattr( + cmd_run, + "create_runtime_web_app", + lambda *_args, **_kwargs: pytest.fail("interactive run must not create an HTTP app"), + ) + + from ksadk.tui import runtime_runner + + created = {} + + class FakeRunner: + def __init__(self, actual_composition, *, agent_id): + assert actual_composition is composition + assert agent_id == "demo-agent" + created["runner"] = self + + monkeypatch.setattr(runtime_runner, "CanonicalRuntimeRunner", FakeRunner) + monkeypatch.setattr( + runtime_runner, + "run_runtime_tui", + lambda runner, **kwargs: created.update(runner=runner, kwargs=kwargs), + ) + + cmd_run._run_custom( + _result(), tmp_path, 8080, True, True, True, True, True, + ) + + assert created["runner"] is not None + assert created["kwargs"] == { + "show_thinking": True, + "no_stream": True, + "project_dir": str(tmp_path), + "no_alt_screen": True, + } + + +def test_interactive_run_reports_composition_failure(monkeypatch, tmp_path): + def fail(*_args): + raise ValueError("bad runtime config") + + monkeypatch.setattr(cmd_run, "create_local_runtime_composition", fail) + with pytest.raises(SystemExit) as exc_info: + cmd_run._run_custom( + _result(), tmp_path, 8080, True, True, False, False, False, + ) + assert exc_info.value.code == 1 + + +def test_noninteractive_run_keeps_runtime_web_app(monkeypatch, tmp_path): + app = object() + monkeypatch.setattr(cmd_run, "create_runtime_web_app", lambda *_args, **_kwargs: app) + called = {} + monkeypatch.setattr( + cmd_run.uvicorn, + "run", + lambda actual_app, **kwargs: called.update(app=actual_app, kwargs=kwargs), + ) + + cmd_run._run_custom( + _result(), tmp_path, 8080, False, True, False, False, False, + ) + + assert called["app"] is app + assert called["kwargs"] == {"host": "127.0.0.1", "port": 8080} diff --git a/tests/runtime/test_semantic_control_events.py b/tests/runtime/test_semantic_control_events.py new file mode 100644 index 000000000..f2b33af18 --- /dev/null +++ b/tests/runtime/test_semantic_control_events.py @@ -0,0 +1,90 @@ +import pytest + +from ksadk.events.canonical import ( + ApprovalRequest, + InteractionRequested, + RunInterrupted, + RunStarted, + SourceRef, +) +from ksadk.runtime import conversation_execution + + +def _events(closed): + async def generate(**kwargs): + kwargs["_execution_context"]["session_id"] = "session-1" + common = { + "schema_version": 2, + "timestamp": 1.0, + "run_id": "run-1", + "scope_id": "root", + "source": SourceRef(framework="langgraph"), + } + try: + yield RunStarted(**common, event_id="e1", seq=1, status="running") + yield InteractionRequested( + **common, + event_id="e2", + seq=2, + interaction_id="approval-1", + interaction_kind="approval", + request=ApprovalRequest( + call_id="call-1", kind="tool", detail={"name": "delete_file"} + ), + ) + yield RunInterrupted( + **common, + event_id="e3", + seq=3, + status="interrupted", + reason="input_required", + interaction_id="approval-1", + continuation_id="checkpoint-1", + ) + finally: + closed.append(True) + + return generate + + +@pytest.mark.asyncio +async def test_control_events_are_opt_in_and_carry_public_identity(monkeypatch): + monkeypatch.setattr( + conversation_execution, "iter_runtime_conversation_events", _events([]) + ) + projected = [ + event + async for event in conversation_execution.iter_runtime_conversation_semantic_events( + _include_control_events=True + ) + ] + + assert [event["type"] for event in projected] == ["started", "interaction", "interrupt"] + assert projected[0]["run_id"] == "run-1" + assert projected[1]["interaction_id"] == "approval-1" + assert projected[1]["request"]["call_id"] == "call-1" + assert projected[2]["continuation_id"] == "checkpoint-1" + + +@pytest.mark.asyncio +async def test_http_default_projection_does_not_emit_immediate_control_event(monkeypatch): + monkeypatch.setattr( + conversation_execution, "iter_runtime_conversation_events", _events([]) + ) + projected = [ + event async for event in conversation_execution.iter_runtime_conversation_semantic_events() + ] + assert [event["type"] for event in projected] == ["started", "interrupt"] + assert "run_id" not in projected[0] + + +@pytest.mark.asyncio +async def test_closing_semantic_projection_also_closes_canonical_source(monkeypatch): + closed = [] + monkeypatch.setattr( + conversation_execution, "iter_runtime_conversation_events", _events(closed) + ) + stream = conversation_execution.iter_runtime_conversation_semantic_events() + assert (await anext(stream))["type"] == "started" + await stream.aclose() + assert closed == [True] diff --git a/tests/tui/test_runtime_runner.py b/tests/tui/test_runtime_runner.py new file mode 100644 index 000000000..fb090e7b8 --- /dev/null +++ b/tests/tui/test_runtime_runner.py @@ -0,0 +1,199 @@ +from types import SimpleNamespace + +import pytest + +from ksadk.runtime.adapter import CancelResult +from ksadk.tui import runtime_runner +from ksadk.tui.loop import RichLiveRenderer, TranscriptEntry, render_stream +from ksadk.tui.runtime_runner import CanonicalRuntimeRunner + + +class FakeExecutor: + def __init__(self): + self.handle = SimpleNamespace(run_id="run-1", session_id="session-1") + self.cancelled = [] + self.closed = [] + self.close_all_calls = 0 + + def find_handle(self, runtime_type, run_id, session_id): + assert runtime_type == "langgraph" + assert run_id == "run-1" + assert session_id == "session-1" + return self.handle + + async def cancel(self, handle): + self.cancelled.append(handle) + return CancelResult.INTERRUPTED_ACTIVE_TURN + + async def close(self, handle): + self.closed.append(handle) + + async def close_all(self): + self.close_all_calls += 1 + + +def _runner(monkeypatch, events, executor=None): + executor = executor or FakeExecutor() + composition = SimpleNamespace( + launch_context=SimpleNamespace(runtime_type="langgraph", config={}), + executor=executor, + managed_a2a_adapter=None, + ) + calls = [] + + async def semantic_events(**kwargs): + calls.append(kwargs) + for event in events: + yield event + + monkeypatch.setattr( + runtime_runner, "iter_runtime_conversation_semantic_events", semantic_events + ) + runner = CanonicalRuntimeRunner( + composition, + agent_id="demo", + session_id="session-1", + session_service_provider=lambda: object(), + ) + return runner, calls, executor + + +@pytest.mark.asyncio +async def test_semantic_events_are_normalized_without_runner_execution(monkeypatch): + runner, calls, _ = _runner( + monkeypatch, + [ + {"type": "started", "run_id": "run-1", "session_id": "session-1"}, + {"type": "text", "delta": "partial"}, + {"type": "text", "delta": "final answer", "operation": "replace"}, + {"type": "tool_call", "name": "lookup", "args": {"q": "x"}, "run_id": "call-1"}, + {"type": "tool_result", "name": "lookup", "output": {"ok": True}, "run_id": "call-1"}, + { + "type": "completed", + "output_text": "final answer", + "usage": {"input_tokens": 3, "output_tokens": 2}, + }, + ], + ) + + chunks = [chunk async for chunk in runner.stream({"input": "hello"})] + + assert calls[0]["messages"] == [{"role": "user", "content": "hello"}] + assert calls[0]["_include_control_events"] is True + assert chunks[1]["operation"] == "replace" + assert chunks[2] == { + "type": "tool_call", + "tool_name": "lookup", + "tool_args": {"q": "x"}, + "call_id": "call-1", + "status": "running", + } + assert chunks[3]["tool_output"] == {"ok": True} + assert chunks[-1]["type"] == "final" + assert chunks[-1]["output"] == "final answer" + + +@pytest.mark.asyncio +async def test_render_stream_applies_canonical_replace_without_invoke(monkeypatch): + runner, _, _ = _runner( + monkeypatch, + [ + {"type": "text", "delta": "old"}, + {"type": "text", "delta": "replacement", "replace": True}, + {"type": "completed", "output_text": "replacement", "usage": {}}, + ], + ) + + async def duplicate_invoke(_input): + raise AssertionError("canonical stream must not fall back to a second invocation") + + monkeypatch.setattr(runner, "invoke", duplicate_invoke) + response, _ = await render_stream(runner, {"input": "hello"}) + assert response == "replacement" + + +@pytest.mark.asyncio +async def test_live_interaction_requests_real_runtime_cancel(monkeypatch): + runner, _, executor = _runner( + monkeypatch, + [ + {"type": "started", "run_id": "run-1", "session_id": "session-1"}, + { + "type": "interaction", + "run_id": "run-1", + "session_id": "session-1", + "interaction_id": "approval-1", + "interaction_kind": "approval", + "request": {"request_type": "approval"}, + }, + {"type": "cancelled", "usage": {}}, + ], + ) + + chunks = [chunk async for chunk in runner.stream({"input": "hello"})] + + assert executor.cancelled == [executor.handle] + assert "cancel=interrupted_active_turn" in chunks[0]["message"] + assert chunks[-1]["type"] == "final" + + +@pytest.mark.asyncio +async def test_interrupted_run_is_not_resumed_with_legacy_flag(monkeypatch): + runner, _, executor = _runner( + monkeypatch, + [ + { + "type": "interrupt", + "run_id": "run-1", + "session_id": "session-1", + "interrupt_info": {"reason": "checkpoint"}, + } + ], + ) + + chunks = [chunk async for chunk in runner.stream({"input": "hello"})] + + assert chunks[0]["type"] == "error" + assert "未自动批准或续跑" in chunks[0]["message"] + assert executor.closed == [executor.handle] + + resume_chunks = [chunk async for chunk in runner.stream({"input": "hello", "resume": True})] + assert len(resume_chunks) == 1 + assert "未执行旧式 resume=True" in resume_chunks[0]["message"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("stream_updates", [True, False]) +async def test_no_stream_only_changes_rendering(stream_updates): + class Loop: + def __init__(self): + self.updates = [] + + def _set_streaming(self, value): + self.updates.append(value) + + loop = Loop() + entry = TranscriptEntry(role="assistant", content="", status="streaming") + renderer = RichLiveRenderer(loop, entry, stream_updates=stream_updates) + await renderer.on_text("answer") + + assert bool(loop.updates) is stream_updates + assert [item.content for item in renderer.final_entries("answer")] == ["answer"] + + +@pytest.mark.asyncio +async def test_invoke_collects_one_execution_without_duplicating_final_text(monkeypatch): + runner, _, _ = _runner( + monkeypatch, + [ + {"type": "text", "delta": "answer"}, + { + "type": "completed", + "output_text": "answer", + "usage": {"total_tokens": 5}, + }, + ], + ) + + result = await runner.invoke({"input": "hello"}) + assert result == {"output": "answer", "usage": {"total_tokens": 5}} diff --git a/tests/tui/test_runtime_runner_integration.py b/tests/tui/test_runtime_runner_integration.py new file mode 100644 index 000000000..b20e9a7f5 --- /dev/null +++ b/tests/tui/test_runtime_runner_integration.py @@ -0,0 +1,117 @@ +import asyncio +from types import SimpleNamespace + +import pytest + +from ksadk.cli.runtime_bootstrap import LocalRuntimeComposition +from ksadk.runners.base_runner import BaseRunner +from ksadk.runtime.executor import RuntimeExecutor +from ksadk.runtime.factory import build_default_runtime_registry +from ksadk.runtime.launch import RuntimeLaunchContext, RuntimeServices +from ksadk.sessions.in_memory import InMemorySessionService +from ksadk.tui.runtime_runner import CanonicalRuntimeRunner + + +class _ControlledRunner(BaseRunner): + def __init__(self, detection_result, project_dir, *, block: bool): + super().__init__(detection_result, project_dir) + self.block = block + self.cancelled = False + self.closed = False + self.started = asyncio.Event() + + def load_agent(self): + self._agent = object() + + async def invoke(self, input_data): + return {"output": "invoke must not be used by the canonical TUI"} + + async def stream(self, input_data): + self.started.set() + try: + yield {"type": "text", "delta": "canonical"} + if self.block: + await asyncio.Event().wait() + yield {"type": "final", "output": "canonical", "usage": {"total_tokens": 2}} + except asyncio.CancelledError: + self.cancelled = True + raise + + async def close(self): + self.closed = True + + +def _composition(tmp_path, native_runner): + detection = SimpleNamespace( + name="demo", + type=SimpleNamespace(value="langgraph"), + raw_config={}, + ) + context = RuntimeLaunchContext( + runtime_type="langgraph", + project_dir=tmp_path, + detection=detection, + config={}, + services=RuntimeServices( + runner_factory=lambda *_args: native_runner, + ), + ) + return LocalRuntimeComposition( + launch_context=context, + executor=RuntimeExecutor(build_default_runtime_registry()), + ) + + +@pytest.mark.asyncio +async def test_real_runtime_executor_produces_tui_chunks(tmp_path): + native = _ControlledRunner(SimpleNamespace(), str(tmp_path), block=False) + service = InMemorySessionService() + runner = CanonicalRuntimeRunner( + _composition(tmp_path, native), + agent_id="demo", + session_service_provider=lambda: service, + ) + + chunks = [chunk async for chunk in runner.stream({"input": "hello"})] + + assert [chunk["type"] for chunk in chunks] == ["text", "final"] + assert chunks[0]["delta"] == "canonical" + assert chunks[-1]["output"] == "canonical" + assert native.closed is True + await runner.aclose() + + +@pytest.mark.asyncio +async def test_cancelling_tui_consumption_cancels_native_runner(tmp_path): + native = _ControlledRunner(SimpleNamespace(), str(tmp_path), block=True) + service = InMemorySessionService() + runner = CanonicalRuntimeRunner( + _composition(tmp_path, native), + agent_id="demo", + session_service_provider=lambda: service, + ) + + cancel_calls = [] + original_cancel = runner.executor.cancel + + async def record_cancel(handle): + result = await original_cancel(handle) + cancel_calls.append(result) + return result + + runner.executor.cancel = record_cancel + + async def consume(): + return [chunk async for chunk in runner.stream({"input": "hello"})] + + task = asyncio.create_task(consume()) + await asyncio.wait_for(native.started.wait(), timeout=2) + # Wait until the first chunk has crossed the canonical adapter and pipeline. + await asyncio.sleep(0.05) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + assert native.cancelled is True, (cancel_calls, native.closed) + assert native.closed is True, cancel_calls + await runner.aclose()