Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
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
47 changes: 46 additions & 1 deletion libs/code/deepagents_code/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2775,6 +2775,14 @@ def __init__(
self._active_mcp_viewer: Any = None
"""Handle to the `/mcp` modal so server-ready events can refresh it."""

self._restart_respawn_task: asyncio.Task[None] | None = None
"""Strong reference to the detached `/restart` respawn task.

`_handle_restart_command` runs the multi-second server respawn off the
Textual message pump via `asyncio.create_task` so the chat input stays
responsive; holding the reference keeps the task from being GC'd
mid-flight and lets tests await it deterministically."""

self._pending_mcp_reconnect: bool = False
"""Set after a successful MCP login when the user defers the server
restart. Cleared by the next reconnect or restart so multiple deferred
Expand Down Expand Up @@ -19467,11 +19475,48 @@ async def _handle_restart_command(self, command: str) -> None:
)
return

restarting = await self._mount_transient_app_message("Restarting server...")
# Run the respawn as a detached task, NOT awaited on the message pump.
# `_respawn_server`'s multi-second `server_proc.restart()` would
# otherwise stall the pump — key events stop being forwarded and the
# chat input freezes ("blocked") for the whole restart. Mirrors the
# MCP viewer/force-reconnect paths: `asyncio.create_task` keeps the
# pump free, so keystrokes stay live and any message the user submits
# while `_connecting` is queued and drained once `ServerReady` fires.
# `_run_restart_respawn` owns the transient status and completion
# banner; `_log_task_exception` surfaces anything unexpected. The
# pre-respawn guards above (remote/starting/failed/deferred) already
# ran synchronously, so the user got immediate feedback before this.
# Mark the app reconnecting before scheduling because `create_task`
# does not run the coroutine inline. Otherwise a submission or second
# `/restart` could enter before `_respawn_server` sets these fields.
self._connecting = True
self._reconnecting = True
self._agent = None
self._sync_status_connection()
task = asyncio.create_task(self._run_restart_respawn())
self._restart_respawn_task = task
Comment thread
robin-agent[bot] marked this conversation as resolved.
Resolved
task.add_done_callback(_log_task_exception)

async def _run_restart_respawn(self) -> None:
"""Respawn the server for `/restart`, detached from the message pump.

Scheduled via `asyncio.create_task` from `_handle_restart_command` so
the multi-second `server_proc.restart()` runs off the Textual message
pump, keeping the chat input responsive. Shows a transient
"Restarting server..." status for the duration, removes it whether the
respawn succeeds, returns `False`, or raises, and mounts the
completion banner only on success.
"""
restarting = None
restarted = False
try:
restarting = await self._mount_transient_app_message("Restarting server...")
restarted = await self._restart_server_manual()
finally:
if not restarted:
self._connecting = False
self._reconnecting = False
self._sync_status_connection()
if restarting is not None:
with suppress(NoMatches, ScreenStackError):
await restarting.remove()
Expand Down
122 changes: 118 additions & 4 deletions libs/code/tests/unit_tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -24202,6 +24202,10 @@ async def _fake_restart() -> bool: # noqa: RUF029 # awaited by handler
monkeypatch.setattr(app, "_restart_server_manual", _fake_restart)

await app._handle_command("/restart")
# The respawn runs as a detached task so the message pump stays
# free; await it to observe the completion banner deterministically.
assert app._restart_respawn_task is not None
await app._restart_respawn_task
await pilot.pause()

assert reload_called
Expand All @@ -24213,12 +24217,117 @@ async def _fake_restart() -> bool: # noqa: RUF029 # awaited by handler
assert not any("Restarting server" in m for m in app_msgs)
assert any("Restart complete" in m for m in app_msgs)

@pytest.mark.timeout(15)
async def test_restart_keeps_chat_input_responsive(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
"""`/restart` must not freeze the chat input while the server respawns.

Regression guard: `_handle_restart_command` used to await the
multi-second `_restart_server_manual()` (i.e. `server_proc.restart()`)
directly on the Textual message pump, so key events could not be
forwarded and the chat input was blocked until the restart finished.
Running the respawn as a detached task keeps the pump free, so typing
lands even while the restart is in-flight. Without the fix this test
times out (pump stalled on the gated coroutine).
"""
app = DeepAgentsApp(agent=MagicMock())
async with app.run_test() as pilot:
await pilot.pause()
assert app._chat_input is not None
app._chat_input.focus_input()
await pilot.pause()

app._server_proc = MagicMock()
app._server_kwargs = {}

gate = asyncio.Event()

async def _blocked_restart() -> bool:
await gate.wait()
return True

from deepagents_code.config import settings

monkeypatch.setattr(settings, "reload_from_environment", list)
monkeypatch.setattr(
"deepagents_code.model_config.clear_caches", lambda: None
)
monkeypatch.setattr(app, "_restart_server_manual", _blocked_restart)

await app._handle_command("/restart")
await pilot.pause()
# The respawn is now in-flight and gated open; the pump must still
# deliver keystrokes to the chat input.
await pilot.press("h", "i")
await pilot.pause()
typed = app._chat_input.value
gate.set()
assert app._restart_respawn_task is not None
await app._restart_respawn_task
await pilot.pause()
assert typed == "hi"

@pytest.mark.timeout(15)
async def test_marks_reconnecting_before_detached_respawn_runs(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Restart state must be visible before the detached task's first await."""
app = DeepAgentsApp(agent=MagicMock())
async with app.run_test() as pilot:
await pilot.pause()
app._server_proc = MagicMock()
app._server_kwargs = {}

status_started = asyncio.Event()
release_status = asyncio.Event()

async def _blocked_status(_content: str) -> None:
status_started.set()
await release_status.wait()

restart = AsyncMock(return_value=False)

from deepagents_code.config import settings

monkeypatch.setattr(settings, "reload_from_environment", list)
monkeypatch.setattr(
"deepagents_code.model_config.clear_caches", lambda: None
)
monkeypatch.setattr(app, "_mount_transient_app_message", _blocked_status)
monkeypatch.setattr(app, "_restart_server_manual", restart)

await app._handle_restart_command("/restart")
task = app._restart_respawn_task
assert task is not None
assert not status_started.is_set()
assert app._connecting is True
assert app._reconnecting is True
assert app._agent is None

try:
await status_started.wait()
await app._submit_input("queued during restart", mode="normal")
assert len(app._pending_messages) == 1
assert app._pending_messages[0].text == "queued during restart"

await app._handle_restart_command("/restart")
assert app._restart_respawn_task is task
restart.assert_not_awaited()
finally:
release_status.set()
await task

restart.assert_awaited_once()
assert app._connecting is False
assert app._reconnecting is False

async def test_failed_restart_removes_transient_and_suppresses_completion(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A failed restart removes "Restarting..." without showing completion.

Guards the conditional gate in `_handle_restart_command`: the success
Guards the conditional gate in `_run_restart_respawn`: the success
banner is only mounted when `_restart_server_manual()` returns `True`.
On failure the recovery UI (via `ServerStartFailed`) is the user's
feedback, so stale transient progress and the misleading completion
Expand Down Expand Up @@ -24250,6 +24359,8 @@ async def _fake_restart() -> bool: # noqa: RUF029 # awaited by handler
monkeypatch.setattr(app, "_restart_server_manual", _fake_restart)

await app._handle_command("/restart")
assert app._restart_respawn_task is not None
await app._restart_respawn_task
await pilot.pause()

assert restart_called
Expand All @@ -24264,10 +24375,11 @@ async def test_raising_restart_removes_transient_and_propagates(

The transient "Restarting server..." status is mounted before
`_restart_server_manual()` is awaited, so the `try/finally` in
`_handle_restart_command` exists solely to remove it when the restart
`_run_restart_respawn` exists solely to remove it when the restart
raises (not merely returns `False`). On a raise the transient must be
gone, the misleading completion banner must never mount, and the
exception must propagate rather than be swallowed.
exception must propagate out of the detached respawn task (surfaced via
`_log_task_exception`) rather than be swallowed.
"""
app = DeepAgentsApp()
async with app.run_test() as pilot:
Expand All @@ -24292,8 +24404,10 @@ async def _boom() -> bool: # noqa: RUF029 # awaited by handler
)
monkeypatch.setattr(app, "_restart_server_manual", _boom)

await app._handle_restart_command("/restart")
assert app._restart_respawn_task is not None
with pytest.raises(RuntimeError, match="respawn exploded"):
await app._handle_restart_command("/restart")
await app._restart_respawn_task
await pilot.pause()

assert restart_called
Expand Down