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
45 changes: 36 additions & 9 deletions src/panopticon/terminal/dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
from the task service **on change** — a background worker long-polls the change feed
(``list_tasks_versioned``), so the table redraws within a round-trip of a state change and stays
still when nothing changes (no fixed-interval redraw); `r` forces a refresh now. The redraw
preserves the highlighted row across the rebuild. Terminal (COMPLETE/DROPPED) tasks sink below
preserves the highlighted row across the rebuild. A refresh whose REST read fails (the service
erroring, stalled or down) keeps the last-drawn table and warns once per outage instead of
exiting the app — the feed worker retries it. Terminal (COMPLETE/DROPPED) tasks sink below
active ones and are rendered in faded/dim styling so they recede visually without a hard separator.

The task table, the repo table (`g`), and the `OptionList` pickers (`n`'s repo/workflow choice,
Expand Down Expand Up @@ -367,6 +369,9 @@ def _matches(task: JsonObj, query: str) -> bool:
# Snoozing also **stops the task's container** (the session service reads the same deadline off its
# own clock, `core.snooze`); clearing it — or the deadline lapsing — respawns the task.
_SNOOZE_DURATION = timedelta(hours=12)
# How soon the snooze timer retries a repaint whose REST read failed (it has no fresh snapshot to
# derive the next label change from, and the stale one's delays may already be due).
_REFRESH_RETRY_SECONDS = 5.0
_INDEFINITE_SNOOZE_UNTIL = INDEFINITE_UNTIL


Expand Down Expand Up @@ -2094,6 +2099,7 @@ def __init__(
refresh_interval # change-feed long-poll wait (0/None → manual only)
)
self._version = 0 # the change-feed cursor (X-Tasks-Version) the worker long-polls against
self._refresh_failing = False # the last refresh's REST read failed (warn once per outage)
self._tasks: dict[str, JsonObj] = {}
self._repo_names: dict[str, str] = {} # repo id → name; populated by _load_repo_names
self._repo_clis: dict[
Expand Down Expand Up @@ -2175,11 +2181,14 @@ def _watch_feed(self) -> None:
if worker.is_cancelled:
return
if version != self._version: # a task changed past our cursor → rebuild the table
self._version = version
previous, self._version = self._version, version
try:
self.call_from_thread(self.action_refresh)
refreshed = self.call_from_thread(self._refresh)
except RuntimeError: # app shut down between the cancel check and the dispatch
return
if not refreshed: # the rebuild's read failed — rewind so the next poll retries it
self._version = previous
time.sleep(min(self._refresh_interval or 1.0, 1.0))

def on_unmount(self) -> None:
if self._snooze_timer is not None: # stop the pending snooze-display repaint
Expand All @@ -2196,16 +2205,33 @@ def _artifact_tmpdir(self) -> str:
return self._artifact_tmp.name

def action_refresh(self) -> None:
self._refresh()

def _refresh(self) -> bool:
"""Rebuild the table from the task service; False if its REST read failed.

Every read happens before the table is touched, so a failure (a 5xx, a timeout, the
service down) leaves the last-drawn table in place rather than raising — an exception
here would exit the app, whether it ran on the UI thread or in the feed worker."""
try:
tasks = self._client.list_tasks()
runners = self._client.live_runners()
except httpx.HTTPError:
if not self._refresh_failing: # one notice per outage, not one per retry
self._refresh_failing = True
self.notify("Task service unreachable — retrying…", severity="warning")
if self._snooze_timer is None: # keep snooze labels ticking once the service is back
self._snooze_timer = self.set_timer(
_REFRESH_RETRY_SECONDS, self._refresh_snooze_display
)
return False
self._refresh_failing = False
table = self.query_one("#tasks", DataTable)
selected = self._current # keep the operator's highlight across the rebuild (feed refresh)
display_now = self._now() # one clock read per repaint drives every snooze label/dimming
table.clear()
ordered = sorted(
self._client.list_tasks(), key=_make_sort_key(self._sort_by_updated, display_now)
)
new_multi_runner = (
len({r.get("host") for r in self._client.live_runners() if r.get("host")}) > 1
)
ordered = sorted(tasks, key=_make_sort_key(self._sort_by_updated, display_now))
new_multi_runner = len({r.get("host") for r in runners if r.get("host")}) > 1
if new_multi_runner != self._multi_runner:
table.clear(columns=True) # rows already gone; also clears columns for rebuild
self._multi_runner = new_multi_runner
Expand Down Expand Up @@ -2339,6 +2365,7 @@ def _add_row(task: JsonObj, prefix: str) -> None:
table.move_cursor(row=table.get_row_index(target))
self._current = target # `d` opens the detail modal for whatever's highlighted
self._schedule_snooze_refresh(display_now)
return True

def _schedule_snooze_refresh(self, now: datetime) -> None:
"""(Re)arm a one-shot timer for the soonest finite-snooze display change.
Expand Down
103 changes: 103 additions & 0 deletions tests/terminal/test_dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,8 @@ def __init__(
self._version = 0
self._change = threading.Event()
self.list_tasks_calls = 0 # how many times the table was (re)built — counts feed refreshes
# When set, list_tasks raises it (mimics the task service erroring/stalling mid-refresh).
self.list_error: Exception | None = None
self.created: list[tuple[str, str, str | None]] = []
self.created_artifacts_b64: list[dict[str, str] | None] = []
self.applied: list[tuple[str, str]] = []
Expand All @@ -153,6 +155,8 @@ def __init__(

def list_tasks(self) -> list[dict[str, Any]]:
self.list_tasks_calls += 1
if self.list_error is not None:
raise self.list_error
return self._tasks

def list_tasks_versioned(
Expand Down Expand Up @@ -746,6 +750,105 @@ async def test_auto_refresh_preserves_the_highlighted_task() -> None:
assert table.cursor_row == 1


def _http_500() -> httpx.HTTPStatusError:
"""A 500 from GET /tasks, as the task service returned while stalled on `database is locked`."""
request = httpx.Request("GET", "http://test/tasks")
response = httpx.Response(500, json={"detail": "database is locked"}, request=request)
return httpx.HTTPStatusError("500", request=request, response=response)


def _record_notices(app: Dashboard) -> list[str]:
"""Capture the dashboard's `notify` messages (still forwarding them to the real toast)."""
notices: list[str] = []
real = app.notify

def notify(message: str, **kwargs: Any) -> None:
notices.append(message)
real(message, **kwargs)

app.notify = notify # type: ignore[method-assign]
return notices


async def test_a_failed_refresh_keeps_the_table_and_warns() -> None:
# The service 500s mid-refresh: the app stays up and the last-drawn rows stay (the read happens
# before the table is cleared), with a warning instead of a crash screen.
fake = _FakeClient([_TASK])
app = Dashboard(fake, refresh_interval=0) # type: ignore[arg-type]
async with app.run_test() as pilot:
await pilot.pause()
notices = _record_notices(app)
table = app.query_one("#tasks", DataTable)
fake.list_error = _http_500()
app.action_refresh()
await pilot.pause()
assert app.is_running
assert table.row_count == 1
assert app._current == _TASK["id"]
assert notices == ["Task service unreachable — retrying…"]


async def test_a_failing_service_warns_once_per_outage() -> None:
fake = _FakeClient([_TASK])
app = Dashboard(fake, refresh_interval=0) # type: ignore[arg-type]
async with app.run_test() as pilot:
await pilot.pause()
notices = _record_notices(app)
fake.list_error = httpx.ConnectError("refused")
app.action_refresh()
app.action_refresh() # still down: no second toast
assert len(notices) == 1
fake.list_error = None
app.action_refresh() # recovered...
fake.list_error = httpx.ReadTimeout("stalled")
app.action_refresh() # ...and a new outage warns again
await pilot.pause()
assert len(notices) == 2
assert app.is_running


async def test_a_failed_snooze_timer_refresh_keeps_running_and_retries() -> None:
# The snooze-display timer fires a repaint on the UI thread; a failing read there must not exit
# the app, and the timer re-arms so the countdown resumes once the service is back.
task = {**_TASK, "snoozed_until": _at(2)}
fake = _FakeClient([task])
app = Dashboard(fake, refresh_interval=0, now=lambda: _NOW) # type: ignore[arg-type]
async with app.run_test() as pilot:
await pilot.pause()
assert app._snooze_timer is not None # armed for the finite snooze
app._snooze_timer.stop()
fake.list_error = httpx.ReadTimeout("stalled")
app.set_timer(0.01, app._refresh_snooze_display) # the timer firing, as it does live
await _settle(pilot, lambda: fake.list_tasks_calls >= 2)
await pilot.pause()
assert app.is_running
assert app.query_one("#tasks", DataTable).row_count == 1
assert app._snooze_timer is not None # the retry is armed


async def test_a_failed_feed_refresh_keeps_running_and_retries_the_change() -> None:
# The feed worker marshals the rebuild onto the UI thread; a failure there must neither kill
# the worker nor the app, and once the service recovers the missed change still lands.
fake = _FakeClient([_TASK])
app = Dashboard(fake, refresh_interval=0.05) # type: ignore[arg-type]
async with app.run_test() as pilot:
await pilot.pause()
notices = _record_notices(app)
table = app.query_one("#tasks", DataTable)
builds = fake.list_tasks_calls
fake.list_error = _http_500()
fake._tasks = [_TASK, {**_TASK, "id": "task-second9999", "slug": "other"}]
fake.signal_change()
await _settle(pilot, lambda: fake.list_tasks_calls > builds)
await pilot.pause()
assert app.is_running
assert table.row_count == 1 # the last-drawn table survives
assert notices == ["Task service unreachable — retrying…"]
fake.list_error = None # the service recovers — no further change is signalled
await _settle(pilot, lambda: table.row_count == 2, tries=200)
assert table.row_count == 2 # the rewound cursor retried the missed change


async def test_dashboard_with_no_tasks() -> None:
app = Dashboard(_FakeClient([])) # type: ignore[arg-type]
async with app.run_test() as pilot:
Expand Down
Loading