Skip to content

2026 11 26 admin tick

kubed-io[bot] edited this page Nov 26, 2026 · 1 revision

Admin Tick Implementation Plan

History. Drafted 2026-11-26 for #226 (PR #231), from #226's notes, which Dr K approved. The design, finished against the code and sse-starlette's source, is 2026-11-26-admin-tick-design.md. Its "Found at plan time" list is what this plan adds to the brief. In short:

  • the ping is on a fixed timer, so UI-34 says "every 20 seconds";
  • a joiner on a quiet list is handed the unchanged latest, or it would wait up to 30 s;
  • the tick-counting tests set REFRESH_SECONDS = 0.0.

For agentic workers: REQUIRED SUB-SKILL: Use skill://superpowers/subagent-driven-development/SKILL.md (recommended) or skill://superpowers/executing-plans/SKILL.md to implement this plan task by task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: An open admin page costs next to nothing while the workspace list is unchanged. The list is rebuilt when a change is marked, or every 30 s at least, and the stream beats every 20 s, so the page never falls back to polling.

Architecture:

  • Broadcast in http/admin/workspaces.py gains a change counter. mark() bumps it, and invalidate() and poke() bump it too. _run computes only when the latest is stale.
  • SeleniumMCP subscribes call.finished to broadcast.mark.
  • /admin/events sends event: beat through sse-starlette's ping_message_factory, and Live.#watch listens for it.

Tech Stack: Python 3.11+, Starlette, sse-starlette >=3.3, anyio, pytest; Svelte 5, vitest.

Spec: the design, and the area files Task 3 edits: admin-ui.md (UI-34, UI-35) and runtime.md (the limits row).

Global Constraints

  • Values: POLL_SECONDS = 2.0, REFRESH_SECONDS = 30.0 (new, beside it), HEARTBEAT = 20.0, FRESH_SECONDS = 1.0. The page's 30 s timer and 45 s check don't change.
  • The beat, exactly: ServerSentEvent(event="beat", data=""), imported from sse_starlette. On the wire: event: beat, data: , then a blank line.
  • Names: Broadcast.mark(), Broadcast._changes, Broadcast._seen, and the bus subscription name="admin-calls".
  • _latest keeps its shape, (started, payload, text) (design, Found 4).
  • Every Broadcast method but compute runs on the event loop. _changes is read for a computation on the loop, before run_in_threadpool.
  • The pin stays sse-starlette>=3.3. Both 3.3.0 and 3.7.1 have ping_message_factory.
  • Out of scope: http/admin/files.py's header() and the capture tail's ping.
  • Leave mcp/tools.py, mcp/instructions.py and .github/ alone (AGENTS.md). No golden moves: git status tests/golden stays empty.
  • No integration test (CONTRIBUTING, "Tests").
  • Spec rules (Specification.md, "Ids"): statements only, in the present tense, with no dates or issue numbers. Cite code by symbol.
  • Checks: ruff check . and pytest, as test.yml runs them. Task 2 also runs the UI's: npm --prefix ui run lint, npm --prefix ui run check, npm --prefix ui test, npm --prefix ui run build and npm --prefix ui run size, as ui.yml does.
  • Commits: stage exact paths, never -a. docs/ is committed by the workflow on the wiki branch issue-226.

Review Focus

  1. A page that opens on a quiet list must get its first event at once, not after up to 30 s. Task 1 pins it with test_a_page_joining_a_quiet_list_is_sent_it_at_once.
  2. A call that finishes while a build is under way must not be counted as seen by that build. The tick after it builds again. Task 1 pins it with test_a_mark_during_a_computation_is_not_seen_by_it.
  3. A failed build (a Grid or Redis blip) right after a change must not swallow the change. The next tick tries again. Task 1 pins it with test_a_failed_computation_leaves_the_mark_unseen.
  4. A beat is never a payload. A page that hears beats keeps the list it has, and the payload sink never takes a beat's empty data. Task 2 pins it with test_the_stream_beats_while_nothing_changes.
  5. Steady MCP traffic must still cost at most one build per tick, not one per call. Task 1 pins it with test_many_finished_calls_are_one_computation.

Task 1: The broadcast computes only when the list may have changed

Files:

  • Modify: kubed/selenium_flow/http/admin/workspaces.py (the constants, Broadcast)
  • Modify: kubed/selenium_flow/server.py (the admin-calls subscription, beside admin)
  • Test: tests/test_admin_events.py

Interfaces:

  • Produces, in workspaces.py:

    • REFRESH_SECONDS: float = 30.0;
    • Broadcast.mark() -> None;
    • Broadcast._changes: int and Broadcast._seen: int, both 0 at construction;
    • Broadcast._stale() -> bool and Broadcast._current() -> tuple[float, dict, str] | None, which replaces _recent().
  • fresh(), invalidate(), poke(), changes(), join() and leave() keep their signatures.

  • Step 1: Write the failing tests in tests/test_admin_events.py

The module imports CallFinished from kubed.selenium_flow.monitor.events. A new fixture counts the builds the broadcast makes, by name, so a route's other threadpool work isn't counted:

@pytest.fixture
def computed(monkeypatch):
    """Every `workspaces_payload` run through `run_in_threadpool`: the tick's, and an inline
    `GET /admin/workspaces`."""
    runs = []
    real = admin.run_in_threadpool

    async def counting(fn, *args, **kwargs):
        if getattr(fn, "__name__", "") == "workspaces_payload":
            runs.append(1)
        return await real(fn, *args, **kwargs)

    monkeypatch.setattr(admin, "run_in_threadpool", counting)
    return runs


def _finished(workspace="one"):
    return CallFinished(workspace, "", "chrome", "navigate", "mcp", "ok", 1.0, 0.1)

State tests on a bare Broadcast:

def test_an_unchanged_broadcast_is_current_until_the_refresh_bound(monkeypatch):
    monkeypatch.setattr(admin, "FRESH_SECONDS", 0.0)
    b = admin.Broadcast(compute=dict)
    b._latest = (time.monotonic(), {"workspaces": []}, "{}")
    assert b.fresh() == {"workspaces": []} and not b._stale()
    b._latest = (time.monotonic() - admin.REFRESH_SECONDS, {"workspaces": []}, "{}")
    assert b.fresh() is None and b._stale()


def test_a_mark_makes_the_broadcast_stale_without_a_nudge(monkeypatch):
    monkeypatch.setattr(admin, "FRESH_SECONDS", 0.0)
    b = admin.Broadcast(compute=dict)
    b._latest = (time.monotonic(), {"workspaces": []}, "{}")
    b.mark()
    assert b._stale() and b.fresh() is None
    assert not b._nudge.is_set()


def test_a_marked_broadcast_is_still_handed_out_while_fresh():
    b = admin.Broadcast(compute=dict)
    b._latest = (time.monotonic(), {"workspaces": []}, "{}")
    b.mark()
    assert b._stale() and b.fresh() == {"workspaces": []}  # under FRESH_SECONDS

Through the stream, with POLL_SECONDS = 0.02 and REFRESH_SECONDS = 60.0 unless a test says otherwise. Each opens _listen and waits for the first event, as the tests above them do:

async def test_a_quiet_list_is_computed_once(server, computed, monkeypatch):
    # 10 ticks with nothing marked: one build, the first.
    ...
    await _until(lambda: len(sink) == 1, "the first event")
    await asyncio.sleep(0.2)
    assert len(computed) == 1


async def test_a_changing_route_is_computed_on_the_next_tick(server, computed, monkeypatch):
    # The site-data jar of test_a_forget_with_a_page_open_is_in_the_next_listing.
    ...
    await _until(lambda: len(sink) == 1, "the first event")
    await asyncio.sleep(0.1)
    await _request(app, "DELETE", "/admin/workspaces/one/site-data/app.example.com")
    await _until(lambda: len(sink) == 2, "the change")
    await asyncio.sleep(0.2)
    assert len(computed) == 2
    assert json.loads(sink[1])["workspaces"][0]["site_data_count"] == 0


async def test_a_finished_call_is_computed_on_the_next_tick(server, computed, monkeypatch):
    ...
    await _until(lambda: len(sink) == 1, "the first event")
    server.workspaces.store.set("two", Workspace(session_id=""))
    server.bus.publish(_finished())
    await _until(lambda: len(sink) == 2, "the change")
    await asyncio.sleep(0.2)
    assert len(computed) == 2


async def test_many_finished_calls_are_one_computation(server, computed, monkeypatch):
    monkeypatch.setattr(admin, "POLL_SECONDS", 0.2)
    ...
    await _until(lambda: len(sink) == 1, "the first event")
    for _ in range(50):
        server.bus.publish(_finished())
    await asyncio.sleep(0.1)
    assert len(computed) == 1, "a mark nudged the tick"
    await _until(lambda: len(computed) == 2, "the next tick")
    await asyncio.sleep(0.3)
    assert len(computed) == 2


async def test_an_unchanged_list_is_computed_again_past_the_refresh_bound(
    server, computed, monkeypatch
):
    monkeypatch.setattr(admin, "REFRESH_SECONDS", 0.1)
    ...
    await _until(lambda: len(sink) == 1, "the first event")
    await asyncio.sleep(0.35)  # about 17 ticks, about 3 bounds
    assert 2 <= len(computed) <= 5


async def test_a_page_joining_a_quiet_list_is_sent_it_at_once(server, computed, monkeypatch):
    # FRESH_SECONDS stays 1.0: the first build is older than that when the second page joins.
    ...
    await _until(lambda: len(first) == 1, "the first event")
    await asyncio.sleep(1.2)
    tasks.append(asyncio.create_task(_listen(app, second, stop)))
    await _until(lambda: len(second) == 1, "the joiner's first event", seconds=0.5)
    assert second == first and len(computed) == 1


async def test_a_mark_during_a_computation_is_not_seen_by_it(server, gated, monkeypatch):
    monkeypatch.setattr(admin, "REFRESH_SECONDS", 60.0)  # over the fixture's 0.0
    gate, entered = gated
    ...
    await _until(lambda: len(entered) >= 1, "build 1 under way")
    server.bus.publish(_finished())
    gate.release(1)
    await _until(lambda: len(entered) >= 2, "build 2, for the mark")
    gate.release(1)
    await asyncio.sleep(0.3)
    assert len(entered) == 2


async def test_a_failed_computation_leaves_the_mark_unseen(server, computed, monkeypatch):
    server.workspaces.store.set("one", Workspace(session_id=""))
    failing = []
    real = admin.owner_label

    def owner_label(key):
        if failing:
            failing.pop()
            raise RuntimeError("blip")
        return real(key)

    monkeypatch.setattr(admin, "owner_label", owner_label)
    ...
    await _until(lambda: len(sink) == 1, "the first event")
    failing.append(True)
    server.workspaces.store.set("two", Workspace(session_id=""))
    server.bus.publish(_finished())
    await _until(lambda: len(sink) == 2, "the change, after the blip")
    await asyncio.sleep(0.2)
    assert len(computed) == 3  # the first, the blip, the retry


async def test_a_finished_call_is_never_answered_from_before_it(server, counted, monkeypatch):
    monkeypatch.setattr(admin, "POLL_SECONDS", 60.0)
    monkeypatch.setattr(admin, "FRESH_SECONDS", 0.0)
    ...
    await _until(lambda: len(sink) == 1, "the first event")
    asked = len(counted)
    await _request(app, "GET", "/admin/workspaces")
    assert len(counted) == asked, "an unchanged list within the bound was computed again"
    server.bus.publish(_finished())
    await _request(app, "GET", "/admin/workspaces")
    assert len(counted) == asked + 1

test_a_session_opening_or_ending_pokes_the_admin_broadcast also patches Broadcast.mark to record, publishes _finished() after the two session events, and asserts:

    assert len(pokes) == 2 and isinstance(pokes[0], Broadcast)
    assert len(marks) == 1 and marks[0] is pokes[0]

Fix the tests that count ticks, by meaning (design, Found 5):

  • test_every_connected_page_is_sent_the_same_events, test_nothing_polls_once_the_last_page_has_gone, test_a_page_that_drops_mid_send_leaves_at_once and the gated fixture set REFRESH_SECONDS = 0.0. Every tick then builds, as before.

  • In test_the_listing_is_the_last_broadcast_while_it_is_fresh, the "a stale one is never served" block sets REFRESH_SECONDS = 0.0 beside FRESH_SECONDS = 0.0 and keeps asked + 2. A stale listing now means one past the bound, or one marked since, which test_a_finished_call_is_never_answered_from_before_it covers.

  • The module docstring stops saying "computed once a tick": it is computed on a tick that finds it stale.

  • Step 2: Run them to see them fail

Run: pytest tests/test_admin_events.py -p no:randomly Expected: FAIL. AttributeError: module … has no attribute 'REFRESH_SECONDS' (or 'Broadcast' object has no attribute 'mark'), and test_a_quiet_list_is_computed_once sees about 10 builds.

  • Step 3: Implement it in workspaces.py, per the design's §2

  • REFRESH_SECONDS = 30.0 goes after POLL_SECONDS, with a comment: the longest a change with no signal waits to show (UI-34). POLL_SECONDS's comment says it is how often the tick looks, not how often it computes.

  • _current() replaces _recent(): the latest when it is younger than FRESH_SECONDS or not _stale(). fresh() and join() use it, and join() nudges only when it is None.

  • _run's loop body computes only if self._stale():. It reads changes = self._changes and started before run_in_threadpool, and on success sets _latest and _seen = changes together under the existing started >= self._floor check. Delivery stays inside the success branch.

  • The class docstring says the list is computed on a tick that finds it stale, and names the marks. store_failing's comment ("every two-second poll") says once per outage instead.

  • Step 4: Subscribe the calls in server.py

Right after the admin subscription:

        self.bus.subscribe(
            "call.finished", lambda _event: broadcast.mark(), name="admin-calls"
        )

The comment above both subscriptions says a call marks the list for the next tick, and the session events and a filed recording refresh it at once.

  • Step 5: Run the tests to see them pass

Run: pytest tests/test_admin_events.py tests/test_recording_collector.py -p no:randomly Expected: PASS. Then run them again with randomization: pytest tests/test_admin_events.py.

  • Step 6: Run the checks

Run: ruff check . and pytest Expected: both clean.

  • Step 7: Commit
git add kubed/selenium_flow/http/admin/workspaces.py kubed/selenium_flow/server.py \
  tests/test_admin_events.py
git commit -m "Admin: compute the workspace list when it changes, and every 30 s at least (#226)"

Task 2: The stream beats, and the page hears it

Files:

  • Modify: kubed/selenium_flow/http/admin/workspaces.py (admin_events, the HEARTBEAT comment, the import)
  • Modify: ui/src/admin/live.svelte.ts (#watch)
  • Modify: ui/src/test/helpers.ts (FakeEventSource)
  • Test: tests/test_admin_events.py, ui/src/admin/live.test.ts

Interfaces:

  • Produces: FakeEventSource.addEventListener(type: string, fn: () => void): void and FakeEventSource.dispatch(type: string): void, which calls every listener of type.

  • Step 1: Write the failing tests

_listen gains a keyword beats: list | None = None. It splits each body into frames on a blank line. A frame with an event: beat line is appended to beats as its list of lines, and every other frame's data: line goes to sink, as today (design, Found 6).

async def test_the_stream_beats_while_nothing_changes(server, computed, monkeypatch):
    monkeypatch.setattr(admin, "HEARTBEAT", 0.05)
    monkeypatch.setattr(admin, "POLL_SECONDS", 60.0)
    app = server.mcp.server.http_app()
    stop, sink, beats = asyncio.Event(), [], []
    task = asyncio.create_task(_listen(app, sink, stop, beats=beats))
    try:
        await _until(lambda: len(beats) >= 3, "three beats")
        assert beats[0] == ["event: beat", "data: "]
        assert len(sink) == 1, "a beat was read as a payload"
        assert len(computed) == 1
    finally:
        await _close(stop, [task])

ui/src/test/helpers.ts: FakeEventSource keeps a listener map and gains addEventListener and dispatch. ui/src/admin/live.test.ts:

test('a beating stream never falls back, for ten minutes (UI-35)', async () => {
  const { calls } = fakeFetch({ 'GET /admin/workspaces': { body: { workspaces: [], events_url: '/e?sig=1' } } })
  const live = new Live(api, '')
  await live.load()
  const stream = FakeEventSource.last!
  stream.onopen!()
  for (let i = 0; i < 30; i++) {
    await vi.advanceTimersByTimeAsync(20_000)
    stream.dispatch('beat')
  }
  expect(calls.filter((c) => c.path === '/admin/workspaces')).toHaveLength(1)
  expect(FakeEventSource.last).toBe(stream)
  expect(stream.closed).toBe(false)
  expect(live.badge).toEqual({ text: '', cls: 'live' })
})

test('a beat after an error says live again', async () => {
  fakeFetch({ 'GET /admin/workspaces': { body: { workspaces: [{ key: 'a' }], events_url: '/e' } } })
  const live = new Live(api, '')
  await live.load()
  FakeEventSource.last!.onerror!()
  FakeEventSource.last!.dispatch('beat')
  expect(live.badge).toEqual({ text: '', cls: 'live' })
  expect(live.data?.workspaces).toEqual([{ key: 'a' }])
})

a silent stream falls back to polling and reopens on a fresh URL (U3) stays as it is: it is the no-beat case.

  • Step 2: Run them to see them fail

Run: pytest tests/test_admin_events.py -k beats -p no:randomly and npm --prefix ui test -- src/admin/live.test.ts Expected: FAIL. The stream sends only : ping comments, so beats stays empty and _until times out. The ten-minute test sees more than one /admin/workspaces fetch.

  • Step 3: Implement it

  • workspaces.py imports ServerSentEvent from sse_starlette. admin_events passes ping_message_factory=lambda: ServerSentEvent(event="beat", data="") beside ping=HEARTBEAT. The comment above _Stream(...) says the beat both keeps proxies from closing the stream and tells the page the stream is alive, since EventSource never shows a comment.

  • HEARTBEAT's comment reads: seconds between beat events, on a fixed timer from when the stream opens, whatever else it sends (sse-starlette's ping).

  • live.svelte.ts: in #watch, after onmessage, add events.addEventListener('beat', () => this.#beat()). The catch comment becomes /* not a payload */.

  • Step 4: Run the checks

Run: ruff check ., pytest, npm --prefix ui run lint, npm --prefix ui run check, npm --prefix ui test, npm --prefix ui run build and npm --prefix ui run size Expected: all clean.

  • Step 5: Commit
git add kubed/selenium_flow/http/admin/workspaces.py ui/src/admin/live.svelte.ts \
  ui/src/test/helpers.ts tests/test_admin_events.py ui/src/admin/live.test.ts
git commit -m "Admin: the event stream beats every 20 s, and the page counts it (#226)"

Task 3: The spec and the changelog

Files:

  • Modify: docs/superpowers/specs/admin-ui.md (UI-34, UI-35)
  • Modify: docs/superpowers/specs/runtime.md (the admin list row)
  • Modify: docs/superpowers/plans/2026-11-26-admin-tick-design.md (its History header only)
  • Modify: CHANGELOG.md ([Unreleased])

Interfaces:

  • Consumes: Tasks 1 and 2, as built. Check each statement against the code before writing it.

  • Step 1: Edit the area files by the design's "The spec, id by id" table. UI-34 keeps today's list of changing routes word for word. The runtime row reads | Admin list: tick; refresh bound; fallback poll; stream beat | 2 s; 30 s; 30 s; 20 s | none | UI-34, UI-35 |.

  • Step 2: Add the changelog line at the top of [Unreleased]:

- An open admin page costs next to nothing while nothing changes, and no longer refetches the list every minute; a change made outside the server shows within 30 s (#226).
  • Step 3: Say in the design's History header that PR #231 built it, and what Task 1's and Task 2's runs found that differs from the design, if anything.

  • Step 4: Run the checks

Run: ruff check . and pytest Expected: both clean, tests/test_wiki.py included.

  • Step 5: Commit
git add docs CHANGELOG.md
git commit -m "Spec: the admin list is computed on a change, and the stream beats (#226)"

After the tasks

  • The PR says that http/admin/files.py's header() still computes the whole list per request, and that this change leaves it alone.

  • The measurement (#226's "Done when"). No image is built for a pull request, so it needs the branch's image running on the cluster, with one admin page open and no MCP traffic:

    • CPU for 25 min against the same server with no page open, from Pyroscope or the container's CPU metric. The issue's "before" is 23 mCPU with a page open. Expect about 1.5 mCPU over the no-page floor: one build per 30 s at about 46 ms.
    • The access log shows no GET /admin/workspaces for at least 10 minutes.

    Both go in the PR, with the image tag and the time window.

Clone this wiki locally