Cancel session background processes

This commit is contained in:
wuyang6
2026-06-12 16:24:25 +08:00
parent 953126e1d3
commit 0a3e044c9d
4 changed files with 125 additions and 7 deletions
+44
View File
@@ -20,6 +20,7 @@ from fastapi.testclient import TestClient
from backend.api.server import (
AgentState,
create_app,
_bash_bg_manager,
_derive_initial_session_title,
_ensure_session_title,
_generate_session_title,
@@ -28,6 +29,7 @@ from backend.api.server import (
_sanitize_stored_session_for_resume,
)
from src.agent_types import AgentRunResult, AssistantTurn
from src.bash_bg_store import BgTaskSpec
from src.session_store import StoredAgentSession, load_agent_session, save_agent_session
@@ -305,6 +307,48 @@ class GuiServerTests(unittest.TestCase):
self.assertEqual(latest.status_code, 200)
self.assertEqual(latest.json()['status'], 'cancelled')
def test_cancel_run_kills_active_background_tasks_for_session(self) -> None:
with tempfile.TemporaryDirectory() as d:
client, state = _build_client(Path(d))
spec = BgTaskSpec(
task_id='bg_cancel_me',
account_key='alice',
session_id='thread-1',
run_id='old-run',
pid=12345,
task_dir='/tmp/bg_cancel_me',
output_path='/tmp/bg_cancel_me/output',
pid_path='/tmp/bg_cancel_me/pid',
exit_code_path='/tmp/bg_cancel_me/exit_code',
command='sleep 3600',
started_at=123.0,
wait_for_completion=True,
)
state.bash_bg_store.record_start(spec)
killed: list[str] = []
async def fake_kill(_state: AgentState, row: dict[str, object]) -> None:
killed.append(str(row['task_id']))
original = _bash_bg_manager._kill_remote_or_local
_bash_bg_manager._kill_remote_or_local = fake_kill # type: ignore[method-assign]
try:
response = client.post(
'/api/runs/cancel',
json={'account_id': 'alice', 'session_id': 'thread-1'},
)
finally:
_bash_bg_manager._kill_remote_or_local = original # type: ignore[method-assign]
self.assertEqual(response.status_code, 200)
payload = response.json()
self.assertTrue(payload['cancelled'])
self.assertEqual(payload['cancelled_bg_task_ids'], ['bg_cancel_me'])
self.assertEqual(killed, ['bg_cancel_me'])
row = state.bash_bg_store.get('bg_cancel_me')
self.assertIsNotNone(row)
self.assertEqual(row['status'], 'cancelled')
def test_latest_run_prefers_running_over_queued_for_session(self) -> None:
with tempfile.TemporaryDirectory() as d:
client, state = _build_client(Path(d))