Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions libs/code/deepagents_code/_debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,12 @@
import sys
from pathlib import Path

from deepagents_code._env_vars import DEBUG, DEBUG_FILE, is_env_truthy
from deepagents_code._env_vars import (
DEBUG,
DEBUG_FILE,
DEFAULT_DEBUG_FILE,
is_env_truthy,
)

_DEBUG_HANDLER_ATTR = "_deepagents_code_debug_handler"

Expand All @@ -25,8 +30,8 @@ def configure_debug_logging(target: logging.Logger) -> None:
module loggers reach the same file via propagation, so individual modules do
not configure logging themselves.

The log file defaults to `'/tmp/deepagents_debug.log'` but can be overridden
with `DEEPAGENTS_CODE_DEBUG_FILE`. The handler appends (`mode='a'`) so logs
The log file defaults to `DEFAULT_DEBUG_FILE` but can be overridden with
`DEEPAGENTS_CODE_DEBUG_FILE`. The handler appends (`mode='a'`) so logs
are preserved across separate process runs. Calling this again with the same
resolved path is a no-op: the existing tagged handler is reused rather than
stacking duplicates. If the resolved path changes, the stale handler is
Expand All @@ -40,12 +45,7 @@ def configure_debug_logging(target: logging.Logger) -> None:
if not is_env_truthy(DEBUG):
return

debug_path = Path(
os.environ.get(
DEBUG_FILE,
"/tmp/deepagents_debug.log", # noqa: S108
)
)
debug_path = Path(os.environ.get(DEBUG_FILE, DEFAULT_DEBUG_FILE))
for existing in list(target.handlers):
if not (
isinstance(existing, logging.FileHandler)
Expand Down
5 changes: 4 additions & 1 deletion libs/code/deepagents_code/_env_vars.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,10 @@
"""

DEBUG_FILE = "DEEPAGENTS_CODE_DEBUG_FILE"
"""Path for the debug log file (default: `/tmp/deepagents_debug.log`)."""
"""Path for the debug log file (default: `DEFAULT_DEBUG_FILE`)."""

DEFAULT_DEBUG_FILE = "/tmp/deepagents_debug.log" # noqa: S108 # opt-in debug log
"""Default path for the debug log when `DEBUG_FILE` is unset."""

DEBUG_MCP_PROJECT_TRUST = "DEEPAGENTS_CODE_DEBUG_MCP_PROJECT_TRUST"
"""Force the project MCP approval prompt for manual UI testing.
Expand Down
57 changes: 53 additions & 4 deletions libs/code/deepagents_code/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -1230,6 +1230,31 @@ def _build_whats_new_message(heading: str) -> Content:
)


_STARTUP_ERROR_HEADLINE_LIMIT = 300
"""Max characters of a startup-error headline shown in chat before truncation.

Long single-line errors (e.g. the `interpreter_ptc` "Available tools: ..." list)
overflow this. `on_deep_agents_app_server_start_failed` appends a pointer to the
full error in the debug log when the headline is clipped, since the truncated
tail is often the actionable part.
"""


def _startup_error_headline(error: BaseException) -> str:
"""Return the untruncated single-line `Type: message` startup headline.

Args:
error: The exception raised during server startup.

Returns:
A single-line `Type: message` summary (may exceed the banner width).
"""
first_line = str(error).splitlines()[0].strip() if str(error) else ""
if not first_line:
first_line = error.__class__.__name__
return f"{type(error).__name__}: {first_line}"


def _format_startup_error(error: BaseException) -> str:
"""Format a server-startup exception for the welcome banner.

Expand All @@ -1245,10 +1270,9 @@ def _format_startup_error(error: BaseException) -> str:
Returns:
A single-line `Type: message` summary suitable for the banner.
"""
first_line = str(error).splitlines()[0].strip() if str(error) else ""
if not first_line:
first_line = error.__class__.__name__
return f"{type(error).__name__}: {_truncate(first_line, limit=300)}"
return _truncate(
_startup_error_headline(error), limit=_STARTUP_ERROR_HEADLINE_LIMIT
)


class TextualSessionState:
Expand Down Expand Up @@ -3083,11 +3107,18 @@ def on_deep_agents_app_server_start_failed(self, event: ServerStartFailed) -> No

self._connecting = False
self._connection_ready_event.set()
headline_truncated = False
if isinstance(event.error, MCPConfigError):
# Already carries the path + hint; showing the class name is noise.
self._server_startup_error = str(event.error)
else:
self._server_startup_error = _format_startup_error(event.error)
# A clipped headline drops the actionable tail (e.g. the
# `interpreter_ptc` available-tools list), so point at the full log.
headline_truncated = (
len(_startup_error_headline(event.error))
> _STARTUP_ERROR_HEADLINE_LIMIT
)

# Stash the provider for the `/model` recovery hint. Reset on every
# failure so a non-credentials retry-failure clears the prior flag.
Expand Down Expand Up @@ -3164,6 +3195,24 @@ def on_deep_agents_app_server_start_failed(self, event: ServerStartFailed) -> No
"to retry. Or pick a different provider with `/model`."
)

if headline_truncated:
from deepagents_code._env_vars import (
DEBUG,
DEBUG_FILE,
DEFAULT_DEBUG_FILE,
is_env_truthy,
)

if is_env_truthy(DEBUG):
debug_path = os.environ.get(DEBUG_FILE, DEFAULT_DEBUG_FILE)
text += f"\n\nNote: error truncated — full error in {debug_path}."
Comment thread
robin-agent[bot] marked this conversation as resolved.
Resolved
else:
text += (
"\n\nNote: error truncated. Re-run with "
"`DEEPAGENTS_CODE_DEBUG=1` to write the full error to the "
"debug log."
)

async def _mount_failure() -> None:
# Drop any prior failure widget (re-entrant on retry-then-fail).
prior = self._startup_failure_widget
Expand Down
169 changes: 169 additions & 0 deletions libs/code/tests/unit_tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -6734,6 +6734,175 @@ async def test_server_failure_trims_multiline_error_to_headline(self) -> None:
assert "Server process exited with code 3" in stored
assert len(stored) < 400

async def test_server_failure_truncated_headline_notes_debug_rerun(self) -> None:
"""A clipped headline appends a re-run hint when debug logging is off.

The full error (e.g. the `interpreter_ptc` available-tools list) only
reaches disk under `DEEPAGENTS_CODE_DEBUG`; without it the note tells
the user how to capture it on the next run.
"""
from deepagents_code._env_vars import DEBUG, DEBUG_FILE
from deepagents_code.widgets.messages import ErrorMessage

app = DeepAgentsApp()
async with app.run_test() as pilot:
await pilot.pause()
# Single-line message long enough to overflow the headline limit.
long_message = "Unknown tool names: " + ", ".join(
f"tool_{i}" for i in range(80)
)
with patch.dict(os.environ, {DEBUG: "0"}, clear=False):
os.environ.pop(DEBUG_FILE, None)
app.on_deep_agents_app_server_start_failed(
DeepAgentsApp.ServerStartFailed(error=RuntimeError(long_message))
)
await pilot.pause()

widget = app._startup_failure_widget
assert isinstance(widget, ErrorMessage)
rendered = str(widget._content)
assert "error truncated" in rendered
assert "DEEPAGENTS_CODE_DEBUG=1" in rendered
# The note stays on the displayed message, not in stored state.
assert app._server_startup_error is not None
assert "error truncated" not in app._server_startup_error

async def test_server_failure_truncated_headline_points_to_debug_file(
self,
) -> None:
"""With debug logging on, the note points at the resolved log path."""
from deepagents_code._env_vars import DEBUG, DEBUG_FILE
from deepagents_code.widgets.messages import ErrorMessage

app = DeepAgentsApp()
async with app.run_test() as pilot:
await pilot.pause()
long_message = "Unknown tool names: " + ", ".join(
f"tool_{i}" for i in range(80)
)
with patch.dict(
os.environ,
{DEBUG: "1", DEBUG_FILE: "/tmp/custom_debug.log"},
clear=False,
):
app.on_deep_agents_app_server_start_failed(
DeepAgentsApp.ServerStartFailed(error=RuntimeError(long_message))
)
await pilot.pause()

widget = app._startup_failure_widget
assert isinstance(widget, ErrorMessage)
rendered = str(widget._content)
assert "error truncated" in rendered
assert "/tmp/custom_debug.log" in rendered

async def test_server_failure_short_headline_omits_truncation_note(self) -> None:
"""A headline within the limit renders no truncation note."""
from deepagents_code.widgets.messages import ErrorMessage

app = DeepAgentsApp()
async with app.run_test() as pilot:
await pilot.pause()
app.on_deep_agents_app_server_start_failed(
DeepAgentsApp.ServerStartFailed(error=RuntimeError("short boom"))
)
await pilot.pause()

widget = app._startup_failure_widget
assert isinstance(widget, ErrorMessage)
assert "error truncated" not in str(widget._content)

async def test_server_failure_long_mcp_config_error_omits_truncation_note(
self,
) -> None:
"""A long `MCPConfigError` never gets a truncation note.

That branch sets `_server_startup_error` to the full (untruncated)
message and leaves `headline_truncated` False, so the note logic must
not fire even when the rendered text far exceeds the headline limit.
Locks the branch against a refactor that hoists the truncation check.
"""
from deepagents_code.mcp_tools import MCPConfigError
from deepagents_code.widgets.messages import ErrorMessage

app = DeepAgentsApp()
async with app.run_test() as pilot:
await pilot.pause()
long_message = "Invalid MCP config at /tmp/x.json: " + "x" * 400
app.on_deep_agents_app_server_start_failed(
DeepAgentsApp.ServerStartFailed(error=MCPConfigError(long_message))
)
await pilot.pause()

widget = app._startup_failure_widget
assert isinstance(widget, ErrorMessage)
assert "error truncated" not in str(widget._content)

async def test_server_failure_truncation_note_boundary(self) -> None:
"""The note fires only when the headline strictly exceeds the limit.

`_startup_error_headline` prepends `"RuntimeError: "` (14 chars), so a
286-char body yields a 300-char headline (no note) and a 287-char body
yields 301 (note) — pinning the `>` vs `>=` boundary against off-by-one.
"""
from deepagents_code.app import _STARTUP_ERROR_HEADLINE_LIMIT
from deepagents_code.widgets.messages import ErrorMessage

prefix_len = len("RuntimeError: ")
at_limit = "a" * (_STARTUP_ERROR_HEADLINE_LIMIT - prefix_len)
over_limit = "a" * (_STARTUP_ERROR_HEADLINE_LIMIT - prefix_len + 1)

app = DeepAgentsApp()
async with app.run_test() as pilot:
await pilot.pause()
app.on_deep_agents_app_server_start_failed(
DeepAgentsApp.ServerStartFailed(error=RuntimeError(at_limit))
)
await pilot.pause()
widget = app._startup_failure_widget
assert isinstance(widget, ErrorMessage)
assert "error truncated" not in str(widget._content)

app = DeepAgentsApp()
async with app.run_test() as pilot:
await pilot.pause()
app.on_deep_agents_app_server_start_failed(
DeepAgentsApp.ServerStartFailed(error=RuntimeError(over_limit))
)
await pilot.pause()
widget = app._startup_failure_widget
assert isinstance(widget, ErrorMessage)
assert "error truncated" in str(widget._content)

async def test_server_failure_truncated_headline_uses_default_debug_path(
self,
) -> None:
"""With debug on and `DEBUG_FILE` unset, the note names the default path.

Guards the `DEFAULT_DEBUG_FILE` fallback this change extracted — a
regression in the `os.environ.get(..., DEFAULT_DEBUG_FILE)` default
would otherwise go uncaught.
"""
from deepagents_code._env_vars import DEBUG, DEBUG_FILE, DEFAULT_DEBUG_FILE
from deepagents_code.widgets.messages import ErrorMessage

app = DeepAgentsApp()
async with app.run_test() as pilot:
await pilot.pause()
long_message = "Unknown tool names: " + ", ".join(
f"tool_{i}" for i in range(80)
)
with patch.dict(os.environ, {DEBUG: "1"}, clear=False):
os.environ.pop(DEBUG_FILE, None)
app.on_deep_agents_app_server_start_failed(
DeepAgentsApp.ServerStartFailed(error=RuntimeError(long_message))
)
await pilot.pause()

widget = app._startup_failure_widget
assert isinstance(widget, ErrorMessage)
assert DEFAULT_DEBUG_FILE in str(widget._content)

async def test_server_failure_mcp_config_error_omits_class_prefix(self) -> None:
"""`MCPConfigError` banner shows the path and reason without class prefix."""
from deepagents_code.mcp_tools import MCPConfigError
Expand Down
Loading