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
54 changes: 30 additions & 24 deletions libs/code/deepagents_code/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,8 +282,7 @@ def _render_teardown_thread_hints(
Args:
console: Console to print the hints to.
thread_id: Thread whose checkpoints back the hints.
return_code: Process exit code; the resume hint is shown only on a clean
exit (`0`).
return_code: Process exit code; failed sessions add a resume safety caveat.
"""
from rich.style import Style
from rich.text import Text
Expand Down Expand Up @@ -317,15 +316,19 @@ def _render_teardown_thread_hints(
exc_info=True,
)

if return_code == 0:
console.print()
console.print("[dim]Resume this thread with:[/dim]")
# Echo the command the user actually launched (a shim or the
# `deepagents-code` alias), not a hardcoded `dcode` they may not have.
hint = Text(invoked_name(), style="cyan")
hint.append(" -r ", style="cyan")
hint.append(str(thread_id), style="cyan")
console.print(hint)
console.print()
console.print("[dim]Resume this thread with:[/dim]")
# Echo the command the user actually launched (a shim or the
# `deepagents-code` alias), not a hardcoded `dcode` they may not have.
hint = Text(invoked_name(), style="cyan")
hint.append(" -r ", style="cyan")
hint.append(str(thread_id), style="cyan")
console.print(hint)
if return_code != 0:
console.print(
"[dim]Note: the session ended in an error; the last turn may be "
"incomplete and resume may be unsafe.[/dim]"
)


def _confirm_update_after_restart(console: "Console", version: str) -> None:
Expand Down Expand Up @@ -4911,6 +4914,7 @@ def cli_main() -> None:

# Run Textual TUI
return_code = 0
request_count = 0
try:
interpreter_ptc = _parse_interpreter_tools_flag(
getattr(args, "interpreter_tools", None)
Expand Down Expand Up @@ -4976,26 +4980,28 @@ def cli_main() -> None:
# The user may have switched threads via /threads during the
# session; use the final thread ID for teardown messages.
thread_id = result.thread_id or thread_id
request_count = result.session_stats.request_count
_print_session_stats(result.session_stats, console)
except Exception as e: # noqa: BLE001 # Top-level error handler for the application
return_code = 1
error_msg = Text("\nApplication error: ", style="red")
error_msg.append(str(e))
console.print(error_msg)
console.print(Text(traceback.format_exc(), style="dim"))
sys.exit(1)

# Show LangSmith thread link and resume hint for threads with
# checkpointed content. The `thread_id is not None` check narrows the
# type to `str` for the helper; `_should_check_teardown_thread` gates
# whether the teardown lookup runs at all.
if thread_id is not None and _should_check_teardown_thread(
thread_id,
request_count=result.session_stats.request_count,
resume_thread=args.resume_thread,
):
_render_teardown_thread_hints(
console, thread_id, return_code=return_code
)
finally:
# Show LangSmith thread link and resume hint for threads with
# checkpointed content. The `thread_id is not None` check narrows the
# type to `str` for the helper; `_should_check_teardown_thread` gates
# whether the teardown lookup runs at all.
if thread_id is not None and _should_check_teardown_thread(
thread_id,
request_count=request_count,
resume_thread=args.resume_thread,
):
Comment thread
mdrxy marked this conversation as resolved.
Resolved
_render_teardown_thread_hints(
console, thread_id, return_code=return_code
)
Comment thread
robin-agent[bot] marked this conversation as resolved.
Resolved

# Warn about available update on exit
try:
Expand Down
82 changes: 75 additions & 7 deletions libs/code/tests/unit_tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -1746,13 +1746,15 @@ def test_queries_thread_exists_at_most_once(self) -> None:
assert "Resume this thread with:" in output
assert "dcode -r test123" in output

def test_resume_hint_echoes_launch_command(self) -> None:
@pytest.mark.parametrize("return_code", [0, 1])
def test_resume_hint_echoes_launch_command(self, return_code: int) -> None:
"""The hint names the shim the user launched, not a hardcoded `dcode`."""
thread_exists_mock = AsyncMock(return_value=True)

output = self._render(
thread_exists_mock=thread_exists_mock,
thread_url=None,
return_code=return_code,
launch_name="abc",
)

Expand All @@ -1770,11 +1772,16 @@ def test_prints_langsmith_link_when_available(self) -> None:
assert "Resume this thread with:" in output
thread_exists_mock.assert_awaited_once()

def test_no_hints_without_checkpoints(self) -> None:
"""No checkpoint means no link and no resume hint."""
@pytest.mark.parametrize("return_code", [0, 1])
def test_no_hints_without_checkpoints(self, return_code: int) -> None:
"""No checkpoint means no link, resume hint, or crash caveat."""
thread_exists_mock = AsyncMock(return_value=False)

output = self._render(thread_exists_mock=thread_exists_mock, thread_url=None)
output = self._render(
thread_exists_mock=thread_exists_mock,
thread_url=None,
return_code=return_code,
)

assert output == ""
thread_exists_mock.assert_awaited_once()
Expand All @@ -1788,17 +1795,78 @@ def test_lookup_failure_is_swallowed(self) -> None:
assert output == ""
thread_exists_mock.assert_awaited_once()

def test_resume_hint_omitted_on_error_exit(self) -> None:
"""The resume hint is only shown on a clean exit (return_code 0)."""
def test_error_exit_prints_resume_hint_with_caveat(self) -> None:
"""A crashed checkpointed thread remains resumable with a safety caveat."""
thread_exists_mock = AsyncMock(return_value=True)

output = self._render(
thread_exists_mock=thread_exists_mock, thread_url=None, return_code=1
)

assert "Resume this thread with:" not in output
assert "Resume this thread with:" in output
assert "dcode -r test123" in output
assert "the last turn may be incomplete and resume may be unsafe" in output
thread_exists_mock.assert_awaited_once()

def test_clean_exit_prints_resume_hint_without_caveat(self) -> None:
"""Clean teardown output retains the resume hint without a caveat."""
thread_exists_mock = AsyncMock(return_value=True)

output = self._render(
thread_exists_mock=thread_exists_mock, thread_url=None, return_code=0
)

assert "Resume this thread with:" in output
assert "dcode -r test123" in output
assert "the last turn may be incomplete and resume may be unsafe" not in output
thread_exists_mock.assert_awaited_once()


class TestTeardownHintsOnCrash:
"""Test crash handling still renders checkpoint-backed resume guidance."""

def test_runner_crash_prints_resume_hint_and_exits_nonzero(
self, capsys: pytest.CaptureFixture[str]
) -> None:
"""An unhandled TUI exception renders teardown hints before exiting."""
launch = AsyncMock(side_effect=RuntimeError("boom"))
thread_exists_mock = AsyncMock(return_value=True)
invoked_name.cache_clear()

with (
patch("sys.argv", ["dcode"]),
patch("sys.stdin", SimpleNamespace(isatty=lambda: True)),
patch("deepagents_code.main._install_termination_signal_handlers"),
patch("deepagents_code.main._run_startup_auto_update"),
patch("deepagents_code.main._resolve_agent_arg", return_value="agent"),
patch(
"deepagents_code.main._resolve_interpreter_enabled", return_value=False
),
patch("deepagents_code.main._check_mcp_project_trust", return_value=None),
patch("deepagents_code.main._check_project_hooks_trust", return_value=None),
patch(
"deepagents_code.sessions.generate_thread_id", return_value="test123"
),
patch("deepagents_code.main.run_textual_cli_async", launch),
patch("deepagents_code.sessions.thread_exists", thread_exists_mock),
patch(
"deepagents_code.config.build_langsmith_thread_url", return_value=None
),
patch.dict(os.environ, {INVOKED_AS: "dcode"}),
pytest.raises(SystemExit) as exc_info,
):
cli_main()

assert exc_info.value.code == 1
launch.assert_awaited_once()
thread_exists_mock.assert_awaited_once_with("test123")
output = capsys.readouterr().out
flattened = output.replace("\n", "")
assert "Application error: boom" in output
assert "Resume this thread with:" in output
assert "dcode -r test123" in output
assert "the last turn may be incomplete and resume may be unsafe" in flattened


class TestLangSmithTeardownUrl:
"""Test LangSmith thread URL display logic on teardown."""
Expand Down