Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
7 changes: 7 additions & 0 deletions src/github_agent_bridge/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,8 @@ async def _session_stream_events(db: str | Path, job_id: int, *, after_id: int |
async def _journal_stream_events(unit: str, *, shutdown_event: asyncio.Event | None = None):
try:
stream = stream_journal_lines(unit)
line_task: asyncio.Task | None = None
shutdown_task: asyncio.Task | None = None
try:
while shutdown_event is None or not shutdown_event.is_set():
line_task = asyncio.create_task(anext(stream))
Expand All @@ -322,6 +324,11 @@ async def _journal_stream_events(unit: str, *, shutdown_event: asyncio.Event | N
return
yield _sse_event("journal_line", {"unit": unit, "line": line})
finally:
pending_tasks = [task for task in (line_task, shutdown_task) if task is not None and not task.done()]
for task in pending_tasks:
task.cancel()
if pending_tasks:
await asyncio.gather(*pending_tasks, return_exceptions=True)
await stream.aclose()
except FileNotFoundError:
yield _sse_event("journal_error", {"unit": unit, "error": "journalctl_not_found"})
Expand Down
25 changes: 25 additions & 0 deletions tests/test_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -958,6 +958,31 @@ async def stream_until_shutdown():
asyncio.run(stream_until_shutdown())


def test_dashboard_journal_stream_cancels_pending_read_when_client_disconnects(monkeypatch):
closed = False

async def fake_stream_journal_lines(unit):
nonlocal closed
try:
await asyncio.sleep(60)
yield "unreachable"
finally:
closed = True

async def disconnect_stream():
shutdown = asyncio.Event()
monkeypatch.setattr("github_agent_bridge.backend.stream_journal_lines", fake_stream_journal_lines)
stream = _journal_stream_events("github-agent-bridge-dashboard.service", shutdown_event=shutdown)
pending_chunk = asyncio.create_task(anext(stream))
await asyncio.sleep(0)
pending_chunk.cancel()
with pytest.raises(asyncio.CancelledError):
await pending_chunk
assert closed is True

asyncio.run(disconnect_stream())


def test_dashboard_requires_auth_by_default(tmp_path):
db = tmp_path / "bridge.sqlite3"
JobQueue(db)
Expand Down
Loading