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
31 changes: 27 additions & 4 deletions libs/code/deepagents_code/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -4123,6 +4123,9 @@ def __init__(
"""Active `_run_agent_task` worker, tracked so it can be cancelled
on interrupt (`Ctrl+C`) or exit."""

self._offload_worker: Worker[None] | None = None
"""Active `/offload` worker, tracked so Escape can cancel it."""

self._agent_turn_started = False
"""True once the current `_run_agent_task` invocation has begun.

Expand Down Expand Up @@ -15522,7 +15525,10 @@ async def _handle_command(self, command: str) -> None:
await self.action_open_editor()
elif cmd in {"/offload", "/compact"}:
await self._mount_message(UserMessage(command))
await self._handle_offload()
self._offload_worker = self.run_worker(
self._run_offload_task(),
exclusive=False,
)
Comment thread
robin-agent[bot] marked this conversation as resolved.
Resolved
elif cmd == "/threads" or cmd.startswith("/threads "):
await self._handle_threads_command(command)
elif cmd == "/trace":
Expand Down Expand Up @@ -16461,6 +16467,15 @@ async def _get_conversation_token_count(self) -> int | None:
_, conversation = await self._get_context_usage_counts()
return conversation

async def _run_offload_task(self) -> None:
"""Run `/offload` without blocking the App message pump."""
try:
await self._handle_offload()
finally:
self._offload_worker = None
if not self._startup_sequence_running:
await self._process_next_from_queue()

async def _handle_offload(self) -> None:
"""Offload older messages to free context window space.

Expand All @@ -16471,6 +16486,9 @@ async def _handle_offload(self) -> None:
via `read_file` in every run mode (server, sandbox, in-process). The
client only seeds the tool call, approves the resulting HITL interrupt,
drains the run, and renders the persisted `_summarization_event`.

Raises:
CancelledError: If the offload worker is interrupted.
"""
from langchain_core.messages.utils import count_tokens_approximately

Expand Down Expand Up @@ -16525,7 +16543,7 @@ async def _handle_offload(self) -> None:
)
except ClientHookStopError:
return
except Exception as stream_error:
except (asyncio.CancelledError, Exception) as stream_error:
# A server graph can checkpoint the tool-node update before a
# later stream transport failure reaches this client. Reconcile
# the durable event before reporting the operation as failed.
Expand Down Expand Up @@ -20218,10 +20236,11 @@ def action_interrupt(self) -> None:
5. If approval menu is active, reject it
6. If ask-user menu is active, cancel it
7. If queued messages exist, pop the last one (LIFO)
8. If agent is running, interrupt it (restoring the interrupted prompt
8. If offload is running, interrupt it
9. If agent is running, interrupt it (restoring the interrupted prompt
to the chat input when it is empty and no user-visible model output
— text or a tool call — has appeared yet for the turn)
9. Otherwise, a second Esc clears the chat input draft (undoable)
10. Otherwise, a second Esc clears the chat input draft (undoable)
"""
from deepagents_code.tui.widgets.thread_selector import ThreadSelectorScreen

Expand Down Expand Up @@ -20292,6 +20311,10 @@ def action_interrupt(self) -> None:
self._pop_last_queued_message()
return

if self._offload_worker is not None:
self._cancel_worker(self._offload_worker)
return
Comment thread
robin-agent[bot] marked this conversation as resolved.
Resolved

# If agent is running, interrupt it and discard queued messages
if self._agent_running and self._agent_worker:
if self._active_user_message is not None:
Expand Down
64 changes: 64 additions & 0 deletions libs/code/tests/unit_tests/test_offload.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import asyncio
import os
import stat
import tempfile
Expand All @@ -12,6 +13,7 @@

import pytest
from deepagents.backends.utils import validate_path
from textual.worker import WorkerCancelled

from deepagents_code import offload
from deepagents_code._session_stats import format_token_count
Expand All @@ -24,6 +26,7 @@
_offload_fallback_root,
delete_offloaded_history,
)
from deepagents_code.tui.widgets.chat_input import ChatInput
from deepagents_code.tui.widgets.messages import AppMessage, ErrorMessage


Expand Down Expand Up @@ -1104,6 +1107,67 @@ async def test_agent_running_reset_after_failure(self) -> None:
assert app._agent_running is False


class TestOffloadInterrupt:
"""Test that Escape can cancel `/offload` through the real App dispatch."""

async def test_escape_cancels_offload_worker(self) -> None:
"""Escape should reach and cancel an offload blocked in its stream."""
app = DeepAgentsApp()
async with app.run_test() as pilot:
await pilot.pause()
_setup_server_offload_app(app)

before = _state_values(_make_dict_messages(6))
reconciled = _state_values(_make_dict_messages(6))
drive_started = asyncio.Event()
drive_cancelled = asyncio.Event()

async def block_drive(_config: object, _seed_id: object = None) -> None:
drive_started.set()
try:
await asyncio.Future()
finally:
drive_cancelled.set()

with (
patch.object(
app,
"_get_thread_state_values",
new_callable=AsyncMock,
side_effect=[before, reconciled],
),
patch.object(
app,
"_drive_server_side_compaction",
new_callable=AsyncMock,
side_effect=block_drive,
),
patch.object(
app,
"_remove_unanswered_offload_seed",
new_callable=AsyncMock,
return_value=True,
) as cleanup,
):
app.post_message(ChatInput.Submitted("/offload", "command"))
await asyncio.wait_for(drive_started.wait(), timeout=1)

worker = app._offload_worker
assert worker is not None
assert app._agent_running is True

await pilot.press("escape")
await asyncio.wait_for(drive_cancelled.wait(), timeout=1)
with pytest.raises(WorkerCancelled):
await worker.wait()

cleanup.assert_awaited_once()
assert worker.is_cancelled
assert app._agent_running is False
assert app._agent_quiescent.is_set()
assert app._loading_widget is None


class TestOffloadErrorHandling:
"""Test error handling during offload."""

Expand Down