Repository navigation
2026 11 26 admin tick
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:
-
Broadcastinhttp/admin/workspaces.pygains a change counter.mark()bumps it, andinvalidate()andpoke()bump it too._runcomputes only when the latest is stale. -
SeleniumMCPsubscribescall.finishedtobroadcast.mark. -
/admin/eventssendsevent: beatthrough sse-starlette'sping_message_factory, andLive.#watchlistens 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).
-
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 fromsse_starlette. On the wire:event: beat,data:, then a blank line. -
Names:
Broadcast.mark(),Broadcast._changes,Broadcast._seen, and the bus subscriptionname="admin-calls". -
_latestkeeps its shape,(started, payload, text)(design, Found 4). -
Every
Broadcastmethod butcomputeruns on the event loop._changesis read for a computation on the loop, beforerun_in_threadpool. -
The pin stays
sse-starlette>=3.3. Both 3.3.0 and 3.7.1 haveping_message_factory. -
Out of scope:
http/admin/files.py'sheader()and the capture tail's ping. -
Leave
mcp/tools.py,mcp/instructions.pyand.github/alone (AGENTS.md). No golden moves:git status tests/goldenstays 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 .andpytest, astest.ymlruns 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 buildandnpm --prefix ui run size, asui.ymldoes. -
Commits: stage exact paths, never
-a.docs/is committed by the workflow on the wiki branchissue-226.
-
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. -
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. -
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. -
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 withtest_the_stream_beats_while_nothing_changes. -
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.
Files:
- Modify:
kubed/selenium_flow/http/admin/workspaces.py(the constants,Broadcast) - Modify:
kubed/selenium_flow/server.py(theadmin-callssubscription, besideadmin) - Test:
tests/test_admin_events.py
Interfaces:
-
Produces, in
workspaces.py:-
REFRESH_SECONDS: float = 30.0; -
Broadcast.mark() -> None; -
Broadcast._changes: intandBroadcast._seen: int, both 0 at construction; -
Broadcast._stale() -> boolandBroadcast._current() -> tuple[float, dict, str] | None, which replaces_recent().
-
-
fresh(),invalidate(),poke(),changes(),join()andleave()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_SECONDSThrough 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 + 1test_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_onceand thegatedfixture setREFRESH_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 setsREFRESH_SECONDS = 0.0besideFRESH_SECONDS = 0.0and keepsasked + 2. A stale listing now means one past the bound, or one marked since, whichtest_a_finished_call_is_never_answered_from_before_itcovers. -
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.0goes afterPOLL_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 thanFRESH_SECONDSor not_stale().fresh()andjoin()use it, andjoin()nudges only when it isNone. -
_run's loop body computes onlyif self._stale():. It readschanges = self._changesandstartedbeforerun_in_threadpool, and on success sets_latestand_seen = changestogether under the existingstarted >= self._floorcheck. 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)"Files:
- Modify:
kubed/selenium_flow/http/admin/workspaces.py(admin_events, theHEARTBEATcomment, 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): voidandFakeEventSource.dispatch(type: string): void, which calls every listener oftype. -
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.pyimportsServerSentEventfromsse_starlette.admin_eventspassesping_message_factory=lambda: ServerSentEvent(event="beat", data="")besideping=HEARTBEAT. The comment above_Stream(...)says the beat both keeps proxies from closing the stream and tells the page the stream is alive, sinceEventSourcenever shows a comment. -
HEARTBEAT's comment reads: seconds betweenbeatevents, on a fixed timer from when the stream opens, whatever else it sends (sse-starlette's ping). -
live.svelte.ts: in#watch, afteronmessage, addevents.addEventListener('beat', () => this.#beat()). Thecatchcomment 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)"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)"-
The PR says that
http/admin/files.py'sheader()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/workspacesfor at least 10 minutes.
Both go in the PR, with the image tag and the time window.
The action pages are generated from the server's tool schemas, so they describe the version that shipped.
selenium-flow · MIT
Start here
Guides
Lifecycle
Going places
Doing things
Getting things out
Site data
Console and network