fix(chat): make capability failures terminal instead of blank messages (#732)

A capability raising an exception emitted a metadata-less error plus a status-less DONE, so turn_runtime stamped the turn 'completed' and the frontend — which renders the error card only on turn_terminal — showed an empty assistant message.

The orchestrator now emits the error/DONE pair with turn_terminal and a failed status, turn_runtime persists the real outcome instead of an unconditional 'completed', and the unknown-capability branch emits a DONE it previously omitted.

Closes #731.
This commit is contained in:
Dongyu
2026-08-03 20:27:43 +08:00
committed by GitHub
parent 44fa7a1552
commit 67283cfeb1
4 changed files with 120 additions and 6 deletions

View File

@@ -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)

View File

@@ -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 short
preamble 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 socket

View File

@@ -131,6 +131,13 @@ class TestOrchestratorRouting:
error_events = [e for e in events if e.type == StreamEventType.ERROR]
assert len(error_events) == 1
assert "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) == 1
assert "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"
# ---------------------------------------------------------------------------

View File

@@ -4,8 +4,54 @@ import asyncio
import pytest
from deeptutor.core.stream import StreamEvent, StreamEventType
from 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