async def test_cleanup_session_cancels_pending_tasks(
    mock_agent, mock_runtime, mock_controller
):
    """Test that cleanup_session cancels other pending tasks."""
    loop = asyncio.get_running_loop()
    other_task_ran = False
    other_task_cancelled = False

    async def _other_task_func():
        nonlocal other_task_ran, other_task_cancelled
        try:
            other_task_ran = True
            await asyncio.sleep(5)  # Sleep long enough to be cancelled
        except asyncio.CancelledError:
            other_task_cancelled = True
            raise

    other_task = loop.create_task(_other_task_func())

    # Allow the other task to start running
    await asyncio.sleep(0)
    assert other_task_ran is True

    # Run cleanup session directly from the test task
    await cli.cleanup_session(loop, mock_agent, mock_runtime, mock_controller)
    await asyncio.sleep(0)

    # Check that the other task was indeed cancelled
    assert other_task.cancelled() or other_task_cancelled is True

    # Ensure the cleanup finishes (awaiting the task raises CancelledError if cancelled)
    try:
        await other_task
    except asyncio.CancelledError:
        pass  # Expected

    # Verify cleanup still called mocks
    mock_agent.reset.assert_called_once()
    mock_runtime.close.assert_called_once()
    mock_controller.close.assert_called_once()
Test that cleanup_session cancels other pending tasks.
tests/unit/test_cli.py