fix(llm): name a reason when a local SDK turn fails with no text

The Claude Code and CodeBuddy providers report failure as
finish_reason="error" with the reason carried in the result message's
text. The CLI only fills that text when the turn produced assistant
output, so a turn that dies on a rejected tool call or on max_turns ended
empty and reached the operator as a bare "Error calling Claude Code: "
with nothing after the colon (#2539).

- sdk_bridge: render a blank result through a new _result_detail(), which
  keeps the CLI's own wording when present, maps the SDK's subtype
  (error_max_turns / error_during_execution / error_max_budget_usd) to a
  sentence, and never returns an empty string.
- claude_code / codebuddy providers: _friendly_error() names the exception
  type for a blank exception instead of echoing nothing.

Both SDK backends share the bridge, so one fix covers both.
This commit is contained in:
AleFlyX
2026-11-09 16:20:28 +08:00
parent 60fb3bdfdd
commit b1ea6c02fb
6 changed files with 195 additions and 3 deletions

View File

@@ -596,7 +596,7 @@ def _session_signature(
def _friendly_error(exc: Exception) -> str:
message = str(exc)
message = str(exc).strip()
lowered = message.lower()
if "not found" in lowered and "claude" in lowered and "cli" in lowered:
return (
@@ -607,6 +607,14 @@ def _friendly_error(exc: Exception) -> str:
return (
"Error calling Claude Code: not signed in. Run `claude` and enter `/login`, then retry."
)
if not message:
# An exception with no text used to render as a bare "Error calling
# Claude Code: " with nothing after the colon. Name the type so the
# report is actionable rather than blank (#2539).
return (
f"Error calling Claude Code: the SDK raised {type(exc).__name__} "
"without a message. Retry, and check the Claude Code CLI log if it persists."
)
return f"Error calling Claude Code: {message}"

View File

@@ -543,7 +543,7 @@ def _options_has_api_key_env(options: Any | None) -> bool:
def _friendly_error(exc: Exception) -> str:
message = str(exc)
message = str(exc).strip()
if "Authentication required" in message:
return (
"Error calling CodeBuddy: authentication required. Run "
@@ -556,6 +556,11 @@ def _friendly_error(exc: Exception) -> str:
"async task than it was opened on. Retry the message; if it persists, "
"restart the backend."
)
if not message:
return (
f"Error calling CodeBuddy: the SDK raised {type(exc).__name__} "
"without a message. Retry, and check the CodeBuddy CLI log if it persists."
)
return f"Error calling CodeBuddy: {message}"

View File

@@ -29,7 +29,7 @@ async def _consume_messages(
async for message in messages:
if _is_error_result(message):
return LLMResponse(
content=f"Error calling {label}: {_result_text(message)}",
content=f"Error calling {label}: {_result_detail(message)}",
finish_reason="error",
)
if _is_result_message(message):
@@ -239,3 +239,43 @@ def _result_text(message: Any) -> str:
else:
value = getattr(message, "result", None) or getattr(message, "error", None)
return "" if value is None else str(value)
def _result_subtype(message: Any) -> str:
"""The CLI's own one-word verdict for the turn (``error_max_turns`` …)."""
if isinstance(message, dict):
value = message.get("subtype")
else:
value = getattr(message, "subtype", None)
return str(value or "").strip()
# Why a failed turn ended. The CLI reports these in ``subtype`` and leaves
# ``result`` empty, so without this table the operator only ever saw
# ``"Error calling Claude Code: "`` with nothing after the colon.
_RESULT_FAILURES: dict[str, str] = {
"error_max_turns": "the turn hit its maximum number of turns",
"error_during_execution": "the CLI reported an error while running the turn",
"error_max_budget_usd": "the turn hit its budget limit",
}
def _result_detail(message: Any) -> str:
"""An operator-facing reason for a failed SDK turn that is never blank.
The SDK fills ``result`` only when the CLI produced assistant text. A turn
that dies on a rejected tool call or a turn limit ends with an empty
``result`` plus the error flag, and the old code echoed that empty string —
a report of ``write_note`` being unavailable (#2539) reached the UI as
``"Error calling Claude Code: "``, with the cause nowhere on screen.
"""
text = _result_text(message).strip()
subtype = _result_subtype(message)
if text:
# Keep the CLI's wording first; the subtype is a machine-readable hint.
return f"{text} ({subtype})" if subtype and subtype != "success" else text
if subtype in _RESULT_FAILURES:
return f"{_RESULT_FAILURES[subtype]} ({subtype})"
if subtype and subtype != "success":
return f"the CLI ended the turn without a result ({subtype})"
return "the CLI ended the turn without a result and reported no reason"

View File

@@ -499,3 +499,21 @@ async def test_cancel_during_sdk_connect_settles_owner(monkeypatch):
with pytest.raises(asyncio.CancelledError):
await asyncio.wait_for(task, 1)
assert FakeClient.instances[0].disconnected
def test_an_empty_sdk_exception_still_names_a_reason() -> None:
"""#2539: a blank exception must not render as a bare "Error calling …:"."""
from deeptutor.services.llm.provider_core.claude_code_provider import _friendly_error
for exc in (Exception(""), RuntimeError(), ValueError(" ")):
message = _friendly_error(exc)
assert message != "Error calling Claude Code: "
assert type(exc).__name__ in message
def test_a_non_empty_sdk_exception_is_reported_verbatim() -> None:
from deeptutor.services.llm.provider_core.claude_code_provider import _friendly_error
assert _friendly_error(RuntimeError("socket closed")) == (
"Error calling Claude Code: socket closed"
)

View File

@@ -624,3 +624,13 @@ async def test_interrupted_drain_logs_error_type_without_exception_body(caplog):
assert "fake-token" not in caplog.text
assert "private-user-body" not in caplog.text
assert all(record.exc_info is None for record in caplog.records)
def test_an_empty_sdk_exception_still_names_a_reason() -> None:
"""Same blank-error hole as #2539, on the CodeBuddy bridge."""
from deeptutor.services.llm.provider_core.codebuddy_provider import _friendly_error
for exc in (Exception(""), RuntimeError(), ValueError(" ")):
message = _friendly_error(exc)
assert message != "Error calling CodeBuddy: "
assert type(exc).__name__ in message

View File

@@ -0,0 +1,111 @@
"""A failed local-agent-SDK turn must always name a reason.
The Claude Code / CodeBuddy SDK backends report failure with
``is_error=True`` and ``finish_reason="error"``, and the CLI only fills
``result`` when the turn produced assistant text. A turn that dies on a
rejected tool call or on ``max_turns`` therefore ended with an empty
``result``, and the operator saw a bare ``"Error calling Claude Code: "``
with nothing after the colon (#2539). These tests pin the reason to
something the reader can act on.
"""
from __future__ import annotations
import pytest
from deeptutor.services.llm.provider_core.sdk_bridge import (
_consume_messages,
_result_detail,
)
class _ResultMessage:
"""Mirrors the SDK result message: ``result``, ``is_error``, ``subtype``."""
def __init__(self, result: str = "", is_error: bool = False, subtype: str = "success"):
self.result = result
self.is_error = is_error
self.subtype = subtype
async def _stream(*messages):
for message in messages:
yield message
def _consume(*messages, label: str = "Claude Code"):
return _consume_messages(_stream(*messages), on_content_delta=None, label=label)
@pytest.mark.asyncio
async def test_empty_error_result_names_the_cli_subtype() -> None:
response = await _consume(_ResultMessage(result="", is_error=True, subtype="error_max_turns"))
assert response.finish_reason == "error"
# The old rendering was exactly "Error calling Claude Code: ".
assert response.content.startswith("Error calling Claude Code: ")
assert response.content != "Error calling Claude Code: "
assert "maximum number of turns" in response.content
assert "error_max_turns" in response.content
@pytest.mark.asyncio
async def test_unknown_subtype_still_explains_the_empty_turn() -> None:
response = await _consume(
_ResultMessage(result="", is_error=True, subtype="error_something_new")
)
assert response.content != "Error calling Claude Code: "
assert "error_something_new" in response.content
@pytest.mark.asyncio
async def test_no_subtype_and_no_text_is_still_not_blank() -> None:
response = await _consume(_ResultMessage(result="", is_error=True))
assert response.content != "Error calling Claude Code: "
assert "without a result" in response.content
@pytest.mark.asyncio
async def test_cli_message_is_kept_ahead_of_the_subtype() -> None:
response = await _consume(
_ResultMessage(
result="No such tool available: write_note",
is_error=True,
subtype="error_during_execution",
)
)
# The CLI's own wording stays first; the subtype is added as a hint.
assert response.content == (
"Error calling Claude Code: No such tool available: write_note (error_during_execution)"
)
@pytest.mark.asyncio
async def test_a_successfully_empty_turn_does_not_gain_an_error() -> None:
response = await _consume(_ResultMessage(result="", is_error=False))
assert response.finish_reason == "stop"
assert response.content == ""
def test_result_detail_accepts_plain_dicts_from_the_sdk() -> None:
assert _result_detail({"is_error": True, "subtype": "error_max_turns", "result": ""}) == (
"the turn hit its maximum number of turns (error_max_turns)"
)
def test_successful_subtype_is_not_appended_to_real_text() -> None:
assert _result_detail(_ResultMessage(result="done", is_error=True, subtype="success")) == "done"
@pytest.mark.asyncio
async def test_codebuddy_label_is_used_in_the_same_shape() -> None:
response = await _consume(
_ResultMessage(result="", is_error=True, subtype="error_max_turns"),
label="CodeBuddy",
)
assert response.content.startswith("Error calling CodeBuddy: the turn hit")