DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(chat): make capability failures terminal instead of blank messages (#732)
Dongyu67283cfeb148
diff --git a/deeptutor/runtime/orchestrator.py b/deeptutor/runtime/orchestrator.pyindex f1eb40237..de97242d8 100644--- a/deeptutor/runtime/orchestrator.py+++ b/deeptutor/runtime/orchestrator.py@@ -52,6 +52,14 @@ class ChatOrchestrator:f"Unknown capability: {cap_name}. "f"Available: {self._cap_registry.list_capabilities()}",source="orchestrator",+ metadata={"turn_terminal": True, "status": "failed"},+ )+ await bus.emit(+ StreamEvent(+ type=StreamEventType.DONE,+ source="orchestrator",+ metadata={"status": "failed"},+ ))await bus.close()async for event in bus.subscribe():@@ -73,13 +81,25 @@ class ChatOrchestrator:register_bus(_turn_id, bus)async def _run() -> None:+ status = "completed"try:await capability.run(context, bus)except Exception as exc:+ status = "failed"logger.error("Capability %s failed: %s", cap_name, exc, exc_info=True)- await bus.error(str(exc), source=cap_name)+ await bus.error(+ str(exc),+ source=cap_name,+ metadata={"turn_terminal": True, "status": status},+ )finally:- await bus.emit(StreamEvent(type=StreamEventType.DONE, source=cap_name))+ await bus.emit(+ StreamEvent(+ type=StreamEventType.DONE,+ source=cap_name,+ metadata={"status": status},+ )+ )await bus.close()if _turn_id:unregister_bus(_turn_id)diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex 8d069c8ee..bc4dcc1ca 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -35,6 +35,7 @@ MemoryReference = Literal["recent", "profile", "scope", "preferences", "summary"# finish round (and forced-finish) are the answer, narration rounds are# filtered back out via their ``call_role`` marker (see _narration_marker_call_id)._ANSWER_CONTENT_CALL_KINDS = frozenset({"llm_final_response", "agent_loop_round"})+_FINAL_TURN_STATUSES = frozenset({"completed", "failed", "cancelled", "rejected"})def _should_capture_assistant_content(event: StreamEvent) -> bool:@@ -47,6 +48,32 @@ def _should_capture_assistant_content(event: StreamEvent) -> bool:return metadata.get("call_kind") in _ANSWER_CONTENT_CALL_KINDS+def _resolve_turn_outcome(+ assistant_events: Sequence[dict[str, Any]],+ done_event: StreamEvent | None,+) -> tuple[str, str]:+ """Resolve the persisted turn status and error from the terminal protocol."""+ done_metadata = (done_event.metadata or {}) if done_event is not None else {}+ status = str(done_metadata.get("status") or "completed")+ if status not in _FINAL_TURN_STATUSES:+ status = "completed"++ error = ""+ for event in reversed(assistant_events):+ metadata = event.get("metadata")+ metadata = metadata if isinstance(metadata, dict) else {}+ if event.get("type") != StreamEventType.ERROR.value or not metadata.get("turn_terminal"):+ continue+ terminal_status = str(metadata.get("status") or "failed")+ status = terminal_status if terminal_status in _FINAL_TURN_STATUSES else "failed"+ if status == "completed":+ status = "failed"+ error = str(event.get("content") or "")+ break++ return status, error++def _narration_marker_call_id(event: StreamEvent) -> str | None:"""call_id of a chat-loop round that resolved as narration (a shortpreamble streamed alongside a tool call). Its text belongs to the trace,@@ -1688,13 +1715,22 @@ class TurnRuntimeManager:attachments=generated_attachments or None,)await self._flush_buffered_events(execution)- await self.store.update_turn_status(turn_id, "completed")+ turn_status, turn_error = _resolve_turn_outcome(+ assistant_events,+ pending_done_event,+ )+ await self.store.update_turn_status(turn_id, turn_status, turn_error)if pending_done_event is None:pending_done_event = StreamEvent(type=StreamEventType.DONE,source=capability_name,- metadata={"status": "completed"},+ metadata={"status": turn_status},)+ else:+ pending_done_event.metadata = {+ **pending_done_event.metadata,+ "status": turn_status,+ }# Attach the persisted row ids so the frontend can reconcile its# optimistic (negative) message ids with a targeted in-place swap# instead of refetching and re-rendering the whole session.@@ -1710,7 +1746,7 @@ class TurnRuntimeManager:pending_done_event.metadata = {**pending_done_event.metadata, **persisted_ids}await self._publish_live_event(execution, pending_done_event)stream_done_sent = True- if not is_regenerate:+ if not is_regenerate and turn_status == "completed":# Title generation is post-turn metadata. Keep it after DONE# so the composer and duration clock stop as soon as the# assistant answer is saved; the frontend keeps this socketdiff --git a/tests/runtime/test_orchestrator.py b/tests/runtime/test_orchestrator.pyindex 97ed4f325..5f75c224a 100644--- a/tests/runtime/test_orchestrator.py+++ b/tests/runtime/test_orchestrator.py@@ -131,6 +131,13 @@ class TestOrchestratorRouting:error_events = [e for e in events if e.type == StreamEventType.ERROR]assert len(error_events) == 1assert "Unknown capability" in error_events[0].content+ assert error_events[0].metadata == {+ "turn_terminal": True,+ "status": "failed",+ }+ done_events = [e for e in events if e.type == StreamEventType.DONE]+ assert len(done_events) == 1+ assert done_events[0].metadata["status"] == "failed"# ---------------------------------------------------------------------------@@ -155,9 +162,14 @@ class TestOrchestratorErrorHandling:error_events = [e for e in events if e.type == StreamEventType.ERROR]assert len(error_events) == 1assert "intentional failure" in error_events[0].content+ assert error_events[0].metadata == {+ "turn_terminal": True,+ "status": "failed",+ }done_events = [e for e in events if e.type == StreamEventType.DONE]assert len(done_events) == 1+ assert done_events[0].metadata["status"] == "failed"# ---------------------------------------------------------------------------diff --git a/tests/services/session/test_turn_runtime_subscribe.py b/tests/services/session/test_turn_runtime_subscribe.pyindex 6da94844f..d52dae524 100644--- a/tests/services/session/test_turn_runtime_subscribe.py+++ b/tests/services/session/test_turn_runtime_subscribe.py@@ -4,8 +4,54 @@ import asyncioimport pytest+from deeptutor.core.stream import StreamEvent, StreamEventTypefrom deeptutor.services.session.sqlite_store import SQLiteSessionStore-from deeptutor.services.session.turn_runtime import TurnRuntimeManager, _TurnExecution+from deeptutor.services.session.turn_runtime import (+ TurnRuntimeManager,+ _resolve_turn_outcome,+ _TurnExecution,+)+++def test_terminal_error_marks_turn_failed() -> None:+ error_message = "provider authentication failed"+ status, error = _resolve_turn_outcome(+ [+ {+ "type": "error",+ "content": error_message,+ "metadata": {"turn_terminal": True, "status": "failed"},+ }+ ],+ StreamEvent(+ type=StreamEventType.DONE,+ source="chat",+ metadata={"status": "failed"},+ ),+ )++ assert status == "failed"+ assert error == error_message+++def test_non_terminal_error_keeps_completed_done_status() -> None:+ status, error = _resolve_turn_outcome(+ [+ {+ "type": "error",+ "content": "recoverable tool error",+ "metadata": {},+ }+ ],+ StreamEvent(+ type=StreamEventType.DONE,+ source="chat",+ metadata={"status": "completed"},+ ),+ )++ assert status == "completed"+ assert error == ""@pytest.mark.asyncio