The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(kanban): start the events stream at the board tail
brooklyn!bfb1d952c01a
diff --git a/apps/desktop/src/plugins/kanban/api.connection-scope.test.ts b/apps/desktop/src/plugins/kanban/api.connection-scope.test.tsindex c29c84eca54..0a2d899298e 100644--- a/apps/desktop/src/plugins/kanban/api.connection-scope.test.ts+++ b/apps/desktop/src/plugins/kanban/api.connection-scope.test.ts@@ -37,7 +37,7 @@ describe('kanban connection scope', () => {expect(boardsKey(result.current)).toEqual(['kanban', 'boards', 'spark'])})- it('remembers the slug per connection and dials the socket once per switch', () => {+ it('remembers the slug per connection and dials the socket once per switch', async () => {const stored = new Map<string, unknown>([['boardSlug', 'ops'],['boardSlug.spark', 'research']@@ -60,7 +60,10 @@ describe('kanban connection scope', () => {const dispose = bindApi(async () => ({}) as never, storage, socket)expect($boardSlug.get()).toBe('ops')- expect(dials).toEqual(['/events?board=ops'])+ // No snapshot yet: the socket waits for /board, then opens. This gateway+ // has no latest_event_id, so the URL stays unscoped by since and the+ // server starts at the tail.+ await vi.waitFor(() => expect(dials).toEqual(['/events?board=ops']))// Boot publishes the local descriptor after plugins bound: same scope, no dial.setConnection({ mode: 'local' } as never)@@ -69,14 +72,16 @@ describe('kanban connection scope', () => {// Different slug on the next gateway: exactly one dial, not one per listener.setConnection({ connectionId: 'spark', mode: 'remote' } as never)expect($boardSlug.get()).toBe('research')- expect(dials).toEqual(['/events?board=ops', '/events?board=research'])+ await vi.waitFor(() => expect(dials).toEqual(['/events?board=ops', '/events?board=research']))// Same slug on the way back to a gateway with an equal selection still// dials once — the backend behind the slug changed.stored.set('boardSlug', 'research')setConnection({ mode: 'local' } as never)expect($boardSlug.get()).toBe('research')- expect(dials).toEqual(['/events?board=ops', '/events?board=research', '/events?board=research'])+ await vi.waitFor(() =>+ expect(dials).toEqual(['/events?board=ops', '/events?board=research', '/events?board=research'])+ )// Writes land under the scope current at write time.$boardSlug.set('triage')diff --git a/apps/desktop/src/plugins/kanban/api.events-cursor.test.ts b/apps/desktop/src/plugins/kanban/api.events-cursor.test.tsnew file mode 100644index 00000000000..70607d0bfb6--- /dev/null+++ b/apps/desktop/src/plugins/kanban/api.events-cursor.test.ts@@ -0,0 +1,148 @@+import { type PluginRestOptions, type PluginStorage, queryClient } from '@hermes/plugin-sdk'+import { afterEach, describe, expect, it, vi } from 'vitest'++// Opening /events with no since replayed the board's whole task_events history.+// The socket must start at the snapshot's tail, and a late snapshot must not+// reopen a board the user already left. The cursor is per connection.++const { $boardSlug, bindApi, boardKey } = await import('./api')+const { setConnection } = await import('@/store/session')++const BOARD = (latest_event_id: number) => ({+ assignees: [],+ columns: [],+ latest_event_id,+ now: 0,+ tenants: []+})++const storage = (slug = ''): PluginStorage => ({+ get: (key, fallback) => (key === 'boardSlug' ? slug : fallback),+ remove: vi.fn(),+ set: vi.fn()+})++afterEach(() => {+ setConnection(null)+ $boardSlug.set('')+ queryClient.clear()+})++describe('kanban event cursor', () => {+ it('does not open the socket until the board snapshot resolves, then starts at its tail', async () => {+ let resolveBoard: (board: ReturnType<typeof BOARD>) => void = () => undefined++ const board = new Promise<ReturnType<typeof BOARD>>(resolve => {+ resolveBoard = resolve+ })++ const rest = async <T>(path: string, _opts?: PluginRestOptions): Promise<T> => {+ if (path === '/board?board=ops') {+ return board as Promise<T>+ }++ throw new Error(`unexpected REST path: ${path}`)+ }++ const socket = vi.fn(() => vi.fn())+ const dispose = bindApi(rest, storage('ops'), socket)++ expect(socket).not.toHaveBeenCalled()+ resolveBoard(BOARD(14_386))++ await vi.waitFor(() => {+ expect(socket).toHaveBeenCalledWith('/events?board=ops&since=14386', expect.any(Function))+ })++ dispose()+ })++ it('seeds since from the cached snapshot instead of replaying history', () => {+ queryClient.setQueryData(boardKey('local', 'ops', false), BOARD(14_386))++ const socket = vi.fn(() => vi.fn())++ const dispose = bindApi(async () => {+ throw new Error('cached snapshot must not refetch')+ }, storage('ops'), socket)++ expect(socket).toHaveBeenCalledWith('/events?board=ops&since=14386', expect.any(Function))+ dispose()+ })++ it('drops a snapshot that resolves after the selected board changed', async () => {+ let resolveOps: (board: ReturnType<typeof BOARD>) => void = () => undefined++ const ops = new Promise<ReturnType<typeof BOARD>>(resolve => {+ resolveOps = resolve+ })++ const rest = async <T>(path: string, _opts?: PluginRestOptions): Promise<T> => {+ if (path === '/board?board=ops') {+ return ops as Promise<T>+ }++ if (path === '/board?board=ship') {+ return BOARD(7) as T+ }++ throw new Error(`unexpected REST path: ${path}`)+ }++ const socket = vi.fn(() => vi.fn())+ const dispose = bindApi(rest, storage('ops'), socket)++ expect(socket).not.toHaveBeenCalled()+ $boardSlug.set('ship')++ await vi.waitFor(() => {+ expect(socket).toHaveBeenCalledWith('/events?board=ship&since=7', expect.any(Function))+ })++ resolveOps(BOARD(14_386))+ await Promise.resolve()+ await Promise.resolve()++ expect(socket.mock.calls.map(([path]) => path)).toEqual(['/events?board=ship&since=7'])+ dispose()+ })++ it('resumes this connection from the last frame, and does not lend that cursor to another gateway', async () => {+ queryClient.setQueryData(boardKey('local', 'ship', false), BOARD(10))+ queryClient.setQueryData(boardKey('spark', 'ship', false), BOARD(4))++ const frames: Array<(data: unknown) => void> = []++ const socket = vi.fn((_path: string, onMessage: (data: unknown) => void) => {+ frames.push(onMessage)++ return vi.fn()+ })++ const dispose = bindApi(+ async () => {+ throw new Error('cached snapshots must not refetch')+ },+ {+ get: <T>(key: string, fallback: T) => (key.startsWith('boardSlug') ? ('ship' as T) : fallback),+ remove: vi.fn(),+ set: vi.fn()+ },+ socket+ )++ expect(socket).toHaveBeenCalledWith('/events?board=ship&since=10', expect.any(Function))+ frames.at(-1)!({ cursor: 25, events: [{ id: 25, kind: 'spawned', task_id: 't_1' }] })++ $boardSlug.set('ops')+ $boardSlug.set('ship')+ expect(socket.mock.calls.at(-1)?.[0]).toBe('/events?board=ship&since=25')++ setConnection({ connectionId: 'spark', mode: 'remote' } as never)+ await vi.waitFor(() => {+ expect(socket.mock.calls.at(-1)?.[0]).toBe('/events?board=ship&since=4')+ })++ dispose()+ })+})diff --git a/apps/desktop/src/plugins/kanban/api.ts b/apps/desktop/src/plugins/kanban/api.tsindex 5917ef70efc..f9c2f49668a 100644--- a/apps/desktop/src/plugins/kanban/api.ts+++ b/apps/desktop/src/plugins/kanban/api.ts@@ -74,6 +74,62 @@ const INTRO_KEY = 'introDismissed'const LANES_KEY = 'lanesByProfile'const COLLAPSED_KEY = 'collapsedLanes'+// Last frame cursor per (connection, board) this plugin bind. The socket+// reopens on every board switch and connection change; resuming from the last+// frame replays only what was missed. Keyed by connection so one gateway's+// cursor cannot resume another's stream. Cleared on bind/unbind — events that+// land while the plugin is unloaded are not replayed.+const eventCursorByBoard = new Map<string, number>()++function cursorKey(scope: string, slug: string): string {+ return `${scope}\0${slug}`+}++function snapshotCursor(scope: string, slug: string): number | undefined {+ for (const archived of [false, true]) {+ const board = queryClient.getQueryData<KanbanBoard>(boardKey(scope, slug, archived))++ if (typeof board?.latest_event_id === 'number') {+ return board.latest_event_id+ }+ }++ return undefined+}++/** Cursor a fresh socket starts from: the last frame this connection saw, else+ * the cached board snapshot's tail. Undefined means nothing is known yet —+ * fetch the snapshot before opening, never open at since=0. */+function eventsSince(scope: string, slug: string): number | undefined {+ const seen = eventCursorByBoard.get(cursorKey(scope, slug))++ if (typeof seen === 'number') {+ return seen+ }++ return snapshotCursor(scope, slug)+}++function eventsUrl(slug: string, since: number | undefined): string {+ const params = new URLSearchParams()++ if (slug) {+ params.set('board', slug)+ }++ if (since !== undefined) {+ params.set('since', String(since))+ }++ const query = params.toString()++ return query ? `/events?${query}` : '/events'+}++function boardSnapshotPath(slug: string): string {+ return slug ? `/board?board=${encodeURIComponent(slug)}` : '/board'+}+/** Cache-scope id for the active connection — the segment every query key* embeds. `'local'` covers the pre-descriptor null; the SDK atom already* reports 'local' for the local pool. For NON-rendering code (mutations,@@ -104,14 +160,19 @@ export const routedToScope = (query: { queryKey: readonly unknown[] }): boolean/** One live `task_events` frame → precise cache invalidation: the board, plus* each touched task's detail. The polls (8s board / 4s drawer) stay as the* fallback — the socket just makes the board feel instant. */-function onEventsFrame(slug: string, data: unknown): void {- const events = (data as { events?: CompletionEvent[] })?.events+function onEventsFrame(scope: string, slug: string, data: unknown): void {+ const frame = data as { cursor?: unknown; events?: CompletionEvent[] }++ if (typeof frame?.cursor === 'number') {+ eventCursorByBoard.set(cursorKey(scope, slug), frame.cursor)+ }++ const events = frame?.eventsif (!events?.length) {return}- const scope = kanbanConnectionScope()void queryClient.invalidateQueries({ queryKey: boardKeyPrefix(scope) })// Any event can change a board's card count — keep the switcher badge honest.void queryClient.invalidateQueries({ queryKey: boardsKey(scope) })@@ -161,11 +222,54 @@ export function bindApi(persist($lanesByProfile, LANES_KEY, false)persist($collapsedLanes, COLLAPSED_KEY, {})+ eventCursorByBoard.clear()+let close: (() => void) | null = null+ let socketGeneration = 0++ const dial = (scope: string, slug: string, since: number | undefined) =>+ socket(eventsUrl(slug, since), data => onEventsFrame(scope, slug, data))const open = (slug: string) => {+ const generation = ++socketGeneration+ const scope = kanbanConnectionScope()+close?.()- close = socket(slug ? `/events?board=${encodeURIComponent(slug)}` : '/events', data => onEventsFrame(slug, data))+ close = null++ const since = eventsSince(scope, slug)++ if (since !== undefined) {+ close = dial(scope, slug, since)++ return+ }++ // No cached tail yet. Wait for the snapshot and open at its+ // latest_event_id. A board switch or unload bumps the generation so a+ // late snapshot cannot open a stale socket. A failed fetch still opens+ // with no since — the server starts at the tail rather than replaying.+ void queryClient+ .fetchQuery({+ queryFn: () => r<KanbanBoard>(boardSnapshotPath(slug)),+ queryKey: boardKey(scope, slug, false)+ })+ .then(board => {+ if (generation !== socketGeneration) {+ return+ }++ const tail = typeof board?.latest_event_id === 'number' ? board.latest_event_id : undefined++ close = dial(scope, slug, tail)+ })+ .catch(() => {+ if (generation !== socketGeneration) {+ return+ }++ close = dial(scope, slug, undefined)+ })}// The local connection keeps the BARE key (the bare-local rule of@@ -203,6 +307,8 @@ export function bindApi()return () => {+ socketGeneration += 1+ eventCursorByBoard.clear()unsubs.forEach(unsub => unsub())close?.()rest = nulldiff --git a/plugins/kanban/dashboard/plugin_api.py b/plugins/kanban/dashboard/plugin_api.pyindex e4a541f71e6..d01836d8dc8 100644--- a/plugins/kanban/dashboard/plugin_api.py+++ b/plugins/kanban/dashboard/plugin_api.py@@ -1666,11 +1666,21 @@ def set_orchestration_settings(payload: OrchestrationSettingsBody):_EVENT_POLL_SECONDS = 0.3-def _int_param(ws: WebSocket, name: str) -> int:+def _since_param(ws: WebSocket) -> Optional[int]:+ """The client's event cursor, or None when it sent none (or garbage).++ None starts the stream at the board's current tail. Only an explicit+ ``since`` replays history — including ``since=0``. A client that just+ opened the board already holds the snapshot; replaying every+ ``task_events`` row (200 per 300 ms) turned each open into a refetch storm.+ """+ raw = ws.query_params.get("since")+ if raw is None or not str(raw).strip():+ return Nonetry:- return int(ws.query_params.get(name, "0"))- except ValueError:- return 0+ return max(0, int(raw))+ except (TypeError, ValueError):+ return Nonedef _ws_board(raw: Optional[str]) -> Optional[str]:@@ -1690,6 +1700,15 @@ class _EventTail:self._conn: Optional[sqlite3.Connection] = Noneself._executor: Optional[ThreadPoolExecutor] = None+ def _latest(self) -> int:+ """The board's current tail: the cursor a client without one starts from."""+ if self._conn is None:+ self._conn = kbc.connect(board=self._board)+ rows = self._conn.execute(+ "SELECT COALESCE(MAX(id), 0) AS m FROM task_events", ()+ ).fetchall()+ return int(rows[0]["m"]) if rows else 0+def _fetch(self, cursor: int) -> tuple[int, list[dict]]:if self._conn is None:self._conn = kbc.connect(board=self._board)@@ -1711,10 +1730,16 @@ class _EventTail:self._conn.close()self._conn = None- async def poll(self, cursor: int) -> tuple[int, list[dict]]:+ def _run(self, fn, *args):if self._executor is None:self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="kanban-events")- return await asyncio.get_running_loop().run_in_executor(self._executor, self._fetch, cursor)+ return asyncio.get_running_loop().run_in_executor(self._executor, fn, *args)++ async def latest(self) -> int:+ return await self._run(self._latest)++ async def poll(self, cursor: int) -> tuple[int, list[dict]]:+ return await self._run(self._fetch, cursor)async def shutdown(self) -> None:if self._executor is None:@@ -1736,8 +1761,12 @@ async def stream_events(ws: WebSocket):# Board is pinned at the handshake; the UI opens a new WS on board change# rather than reconciling two cursors mid-stream.tail = _EventTail(_ws_board(ws.query_params.get("board")))- cursor = _int_param(ws, "since")+ since = _since_param(ws)try:+ # Capture the tail at accept, before the first wait, so an event that+ # lands in that window is still delivered. A missing cursor must not+ # mean 0 — that replays the whole history.+ cursor = since if since is not None else await tail.latest()while True:# Race receive() against the poll interval so a disconnect is detected even when no# events flow (else idle boards leak poll tasks). Other client messages are ignored.diff --git a/tests/plugins/test_kanban_events_tail.py b/tests/plugins/test_kanban_events_tail.pynew file mode 100644index 00000000000..856650a132c--- /dev/null+++ b/tests/plugins/test_kanban_events_tail.py@@ -0,0 +1,140 @@+"""The kanban events stream starts at the board's tail unless the client names a cursor.++``/events`` opened without ``since`` used to start at cursor 0 and replay every+``task_events`` row. The ``/board`` snapshot already holds the past; a client+that wants history asks for it with ``since``.+"""++from __future__ import annotations++import asyncio+import importlib.util+import sys+import threading+from pathlib import Path++import pytest+++def _load_plugin_module():+ repo_root = Path(__file__).resolve().parents[2]+ plugin_file = repo_root / "plugins" / "kanban" / "dashboard" / "plugin_api.py"+ spec = importlib.util.spec_from_file_location(+ "hermes_dashboard_plugin_kanban_events_tail_test", plugin_file+ )+ assert spec is not None and spec.loader is not None+ mod = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = mod+ spec.loader.exec_module(mod)+ return mod+++class _Ws:+ def __init__(self, query_params: dict[str, str]):+ self.query_params = query_params+ self.sent: list[dict] = []+ self._disconnect = asyncio.Event()++ async def accept(self):+ pass++ async def receive(self):+ await self._disconnect.wait()+ return {"type": "websocket.disconnect"}++ async def send_json(self, payload):+ self.sent.append(payload)++ async def close(self, code=None):+ pass+++def _event(event_id: int, kind: str = "created") -> dict:+ return {+ "id": event_id,+ "task_id": "t",+ "run_id": None,+ "kind": kind,+ "payload": None,+ "created_at": event_id,+ }+++class _Conn:+ """Events 1..450 are already on disk; event 451 lands on the second poll."""++ def __init__(self):+ self.calls: list[tuple[str, tuple]] = []+ self.thread_ids: list[int] = []+ self._rows: list[dict] = []++ def execute(self, sql, params=()):+ self.calls.append((sql, tuple(params)))+ self.thread_ids.append(threading.get_ident())+ if "MAX(id)" in sql:+ self._rows = [{"m": 450}]+ return self+ (cursor,) = params+ polls = sum(1 for seen_sql, _ in self.calls if "MAX(id)" not in seen_sql)+ on_disk = [_event(i) for i in range(1, 451)] + (+ [_event(451, "spawned")] if polls >= 2 else []+ )+ self._rows = [row for row in on_disk if row["id"] > cursor][:200]+ return self++ def fetchall(self):+ return self._rows++ def close(self):+ pass+++async def _drive(monkeypatch, mod, ws, conn, polls: int) -> None:+ waits = 0++ async def _wait_for(awaitable, timeout):+ nonlocal waits+ waits += 1+ awaitable.close()+ if waits <= polls:+ raise asyncio.TimeoutError+ return {"type": "websocket.disconnect"}++ monkeypatch.setattr(mod.asyncio, "wait_for", _wait_for)+ monkeypatch.setattr(mod.kbc, "connect", lambda *, board=None: conn)+ monkeypatch.setattr(mod, "_ws_upgrade_authorized", lambda ws: True)+ await mod.stream_events(ws)+++def _poll_cursors(conn: _Conn) -> list[tuple]:+ return [params for sql, params in conn.calls if "MAX(id)" not in sql]+++async def test_without_since_the_stream_starts_at_the_boards_tail(monkeypatch):+ mod = _load_plugin_module()+ conn, ws = _Conn(), _Ws({})+ await _drive(monkeypatch, mod, ws, conn, polls=2)+ assert _poll_cursors(conn)[0] == (450,), "the first poll must start at the tail, not at 0"+ assert [event["id"] for frame in ws.sent for event in frame["events"]] == [451]+ assert ws.sent[-1]["cursor"] == 451+ assert len(set(conn.thread_ids)) == 1++[email protected]("since", ["0", "100"], ids=["replay-all", "catch-up"])+async def test_an_explicit_since_replays_from_exactly_there(monkeypatch, since):+ mod = _load_plugin_module()+ conn, ws = _Conn(), _Ws({"since": since})+ await _drive(monkeypatch, mod, ws, conn, polls=1)+ assert not any("MAX(id)" in sql for sql, _ in conn.calls)+ assert _poll_cursors(conn)[0] == (int(since),)+ assert ws.sent[0]["events"][0]["id"] == int(since) + 1+++async def test_garbage_since_is_treated_as_no_cursor(monkeypatch):+ mod = _load_plugin_module()+ conn, ws = _Conn(), _Ws({"since": "latest"})+ await _drive(monkeypatch, mod, ws, conn, polls=1)+ assert _poll_cursors(conn)[0] == (450,)diff --git a/tests/plugins/test_kanban_ws_idle_disconnect.py b/tests/plugins/test_kanban_ws_idle_disconnect.pyindex 5b715a87a70..d254ac498c0 100644--- a/tests/plugins/test_kanban_ws_idle_disconnect.py+++ b/tests/plugins/test_kanban_ws_idle_disconnect.py@@ -115,6 +115,9 @@ async def test_stream_events_exits_on_idle_disconnect(monkeypatch, tmp_path):monkeypatch.setattr(mod, "_ws_upgrade_authorized", lambda ws: True)ws = _IdleDisconnectingWebSocket()+ # Disconnects before any poll. Name a cursor so the handler does not open+ # the board DB just to find the tail.+ ws.query_params = {"since": "0"}# The disconnect must terminate the handler even though the board is idle# and no event is ever sent. Before the fix this call never returned@@ -162,6 +165,9 @@ async def test_stream_events_reuses_connection_and_closes_after_disconnect(monkeypatch.setattr(mod.asyncio, "wait_for", _poll_twice_then_disconnect)ws = _PollingWebSocket()+ # A named cursor skips the connect-time tail read, so the execute counts+ # below stay the polls alone.+ ws.query_params = {"since": "0"}await mod.stream_events(ws)@@ -214,6 +220,9 @@ async def test_stream_events_closes_connection_when_cancelled(monkeypatch):monkeypatch.setattr(mod.asyncio, "wait_for", _poll_once_then_wait)ws = _PollingWebSocket()+ # A named cursor skips the connect-time tail read, so the execute count+ # below stays the poll alone.+ ws.query_params = {"since": "0"}task = asyncio.create_task(mod.stream_events(ws))await real_wait_for(first_fetch_done.wait(), timeout=5)diff --git a/website/docs/user-guide/features/kanban.md b/website/docs/user-guide/features/kanban.mdindex 7eb9ac85ea1..507fa598ce2 100644--- a/website/docs/user-guide/features/kanban.md+++ b/website/docs/user-guide/features/kanban.md@@ -877,7 +877,7 @@ All routes are mounted under `/api/plugins/kanban/` and protected by the dashboa| `DELETE` | `/links?parent_id=…&child_id=…` | Remove a dependency || `POST` | `/dispatch?max=…&dry_run=…` | Nudge the dispatcher — skip the 60 s wait || `GET` | `/config` | Read `dashboard.kanban` preferences from `config.yaml` — `default_tenant`, `lane_by_profile`, `include_archived_by_default`, `render_markdown` |-| `WS` | `/events?since=<event_id>` | Live stream of `task_events` rows |+| `WS` | `/events?since=<event_id>` | Live stream of `task_events` rows. Without `since` the stream starts at the board's current tail (the `/board` snapshot already holds the past); pass `since=<latest_event_id>` to catch up from there, or `since=0` to replay history |Every handler is a thin wrapper — the plugin is ~700 lines of Python (router + WebSocket tail + bulk batcher + config reader) and adds no new business logic. A tiny `_conn()` helper auto-initializes `kanban.db` on every read and write, so a fresh install works whether the user opened the dashboard first, hit the REST API directly, or ran `hermes kanban init`.