Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(inbox): a removed Bot's Session leaves every open client, as it leaves the server (#3134)

Call White04f8c24201c5
diff --git a/docs/plans/workbench-refinements.md b/docs/plans/workbench-refinements.md
index de7993161..53c5b9b73 100644
--- a/docs/plans/workbench-refinements.md
+++ b/docs/plans/workbench-refinements.md
@@ -151,12 +151,19 @@ it is still delivered, listed, and unread.
Session, the server's definition. The client reads it from the Owner's live
Bot list (`BotsProvider`, refetched on `bots.changed`), which a small bridge
(`BotRosterContext`) carries up to the Inbox provider above the router; a
- removed Bot's `ses_` Session is an ordinary Session, and a reader without Bots
- has one category. The client computes the badge from its live unread map and
- the switches, and the aggregate badges wait until the map, the switches, and
- the Bot list are all known. A shared fixture
+ reader without Bots has one category. The client computes the badge from its
+ live unread map and the switches, and the aggregate badges wait until the
+ map, the switches, and the Bot list are all known. A shared fixture
(`ui/src/lib/notificationBadge.fixture.json`) runs against both this
- computation and the server's `badge_total`.
+ computation and the server's `badge_total`, including across a Bot's removal.
+- A removed Bot's Session is hidden (`bots.md` D1), not reclassified. Which
+ Sessions exist is the server's answer alone: the event stream drops an
+ `inbox.session.updated` row for a Session the recipient's `GET /api/inbox`
+ hides (the same `hidden_bot_session_ids` owner, per recipient, on the delivery
+ worker thread); on `bots.changed` an open client re-reads its unread map and, while the feed
+ is shown, its window; and a re-read of the window drops loaded rows the server
+ no longer returns within the range it re-read, so a change missed while the
+ stream was down converges on reconnect too.
- Sidebar Inbox icon: a cyan number for `badge_total`; a grey dot with no number
when `badge_total` is 0 and anything is unread.
diff --git a/tests/test_bots.py b/tests/test_bots.py
index 6ab4f5d57..162542dcb 100644
--- a/tests/test_bots.py
+++ b/tests/test_bots.py
@@ -314,6 +314,43 @@ def test_the_inbox_includes_bot_sessions_for_the_owner_only(service):
assert messages_service.total_unread(conn, hidden_session_ids=member_hidden) == 0
+def test_a_removed_bots_session_reaches_no_reader_as_a_realtime_inbox_row(service):
+ """The stream must not hand back a Session the reader's ``GET /api/inbox`` leaves out (D1)."""
+ import json
+
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from vibe.authorization import AuthorizationContext, instance_owner_context
+ from vibe.ui_server import _workbench_event_visible_to_context
+
+ bot = service.create_bot(display_name="Researcher")
+ with create_sqlite_engine().begin() as conn:
+ messages_service.append(
+ conn, scope_id=None, session_id=bot.session_id, platform="avibe", author="agent",
+ message_type="result", text="done",
+ )
+ with create_sqlite_engine().connect() as conn:
+ row = messages_service.get_inbox_session(conn, bot.session_id)
+ frame = json.dumps({"type": "inbox.session.updated", "data": row})
+ ordinary = json.dumps({"type": "inbox.session.updated", "data": {**row, "session_id": "sesordinary1"}})
+ member = AuthorizationContext(instance_role="member", is_remote=True, subject="m1")
+ readers = (None, instance_owner_context())
+
+ def delivered(context, payload=frame) -> bool:
+ return _workbench_event_visible_to_context(context, "inbox.session.updated", payload)
+
+ assert all(delivered(reader) for reader in readers)
+ assert not delivered(member)
+
+ service.remove_bot(bot.handle)
+ # A turn can still land in the kept Session; no reader is told about it.
+ assert not any(delivered(reader) for reader in readers)
+ assert all(delivered(reader, ordinary) for reader in readers)
+
+ service.set_bot(bot.agent.name, display_name="Researcher")
+ assert all(delivered(reader) for reader in readers)
+
+
def test_agents_list_exposes_bot_info(service):
from vibe import api
diff --git a/tests/test_notification_badge_parity.py b/tests/test_notification_badge_parity.py
index ba978913a..9fe7af5ed 100644
--- a/tests/test_notification_badge_parity.py
+++ b/tests/test_notification_badge_parity.py
@@ -3,7 +3,8 @@
The page splits its live unread map by the Owner's Bot list and sums the loud
categories itself (``ui/src/lib/notificationPreferences.ts``); the push worker
and the desktop host read the server's ``badge_total``. Both sides run the same
-fixture, so the sidebar number and the app icon cannot drift apart.
+fixture, so the sidebar number and the app icon cannot drift apart, including
+across a roster change (``removed_bot``).
"""
from __future__ import annotations
@@ -15,10 +16,12 @@ import pytest
from core.notification_categories import split_unread_counts
from core.notification_preferences import badge_total
+from storage.importer import ensure_sqlite_state
FIXTURE = json.loads(
(Path(__file__).resolve().parents[1] / "ui/src/lib/notificationBadge.fixture.json").read_text(encoding="utf-8")
)
+REMOVED = FIXTURE["removed_bot"]
@pytest.mark.parametrize("case", FIXTURE["cases"], ids=lambda case: case["name"])
@@ -27,3 +30,87 @@ def test_server_badge_matches_the_shared_fixture(case):
assert counts == case["unread_by_category"]
assert badge_total(counts, case["preferences"]) == case["badge_total"]
+
+
+def isolated_state(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ yield tmp_path
+
+
+def _seed_ordinary_session(conn, session_id: str, scope_id: str) -> None:
+ from storage.messages_service import _utc_now_iso
+ from storage.models import agent_sessions
+
+ now = _utc_now_iso()
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=scope_id,
+ agent_backend="vibey",
+ agent_variant="default",
+ session_anchor=f"anchor_{session_id}",
+ native_session_id="",
+ title=session_id,
+ status="active",
+ visibility="foreground",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+
+
+def test_removing_a_bot_leaves_its_session_out_of_the_servers_map_and_badge(isolated_state):
+ from core.bots import BotService
+ from core.notification_preferences import set_notification_preferences
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from storage.projects_service import create_project
+ from vibe.ui_server import app
+
+ with BotService() as service:
+ service.ensure_main_bot()
+ for handle in REMOVED["bots"]:
+ service.create_bot(display_name=handle.title(), handle=handle)
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ project_dir = isolated_state / "project"
+ project_dir.mkdir()
+ project = create_project(conn, str(project_dir), display_name="Project")
+ for session_id, replies in REMOVED["agent_replies"].items():
+ ordinary = not session_id.startswith("ses_")
+ if ordinary:
+ _seed_ordinary_session(conn, session_id, project["scope_id"])
+ for index in range(replies):
+ messages_service.append(
+ conn,
+ scope_id=project["scope_id"] if ordinary else None,
+ session_id=session_id,
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="result",
+ text=f"reply {index}",
+ )
+ engine.dispose()
+
+ client = app.test_client()
+
+ def inbox() -> dict:
+ return client.get("/api/inbox?platform=avibe", base_url="http://127.0.0.1:5123").get_json()
+
+ assert inbox()["unread_by_session"] == REMOVED["before"]["unread_by_session"]
+ with BotService() as service:
+ service.remove_bot(REMOVED["removed"])
+ for case in REMOVED["cases"]:
+ set_notification_preferences("local", case["preferences"])
+ after = inbox()
+ assert after["unread_by_session"] == REMOVED["after"]["unread_by_session"], case["name"]
+ assert after["unread_by_category"] == case["unread_by_category"], case["name"]
+ assert after["badge_total"] == case["badge_total"], case["name"]
+ # The page's own computation on what it is then handed agrees.
+ counts = split_unread_counts(after["unread_by_session"], bot_session_ids=REMOVED["after"]["bot_session_ids"])
+ assert badge_total(counts, case["preferences"]) == case["badge_total"], case["name"]
diff --git a/ui/e2e/workbench-general/bots.spec.ts b/ui/e2e/workbench-general/bots.spec.ts
index cfcc3ba2a..84eab23cc 100644
--- a/ui/e2e/workbench-general/bots.spec.ts
+++ b/ui/e2e/workbench-general/bots.spec.ts
@@ -569,3 +569,110 @@ test('the default Agent is offered as a Bot nowhere, and both ways in say what t
await expect(dialog.getByRole('button', { name: 'Set as Bot' })).toBeDisabled();
expect(denied).toEqual([]);
});
+
+// The browser half of the server's Bot-removal contract (docs/plans/bots.md D1):
+// once a Bot is removed its Session is hidden, so every open tab drops it from
+// the Inbox and badges the server's number, without a reload. The fixture is the
+// server: one state behind both tabs, publishing what the real one publishes.
+test('two open tabs follow a Bot removal and a switch change to the server\'s badge', async ({ page }) => {
+ const tabs = [page, await page.context().newPage()];
+ const server = {
+ bots: [MAIN, CSO, PM],
+ sessions: INBOX.sessions,
+ preferences: { enabled: true, bots: true, sessions: false },
+ };
+ const unread = () => Object.fromEntries(server.sessions.filter((row) => row.unread_count > 0).map((row) => [row.session_id, row.unread_count]));
+ const badgeTotal = () => server.sessions.reduce((sum, row) => {
+ const bot = server.bots.some((candidate) => `ses_${candidate.handle}` === row.session_id);
+ const loud = server.preferences.enabled && (bot ? server.preferences.bots : server.preferences.sessions);
+ return sum + (loud ? row.unread_count : 0);
+ }, 0);
+ // What the server publishes reaches every open stream.
+ const publish = (type: string, data: object) => Promise.all(tabs.map((tab) => tab.evaluate(
+ ([name, body]) => (window as unknown as { __serverEvent: (type: string, data: object) => void }).__serverEvent(name, body),
+ [type, data] as const,
+ )));
+
+ const denials: string[][] = [];
+ for (const tab of tabs) {
+ denials.push((await serveBots(tab, 'zh', server.bots)).denied);
+ await tab.addInitScript(() => {
+ const streams = new Set<EventTarget>();
+ class FixtureEvents extends EventTarget {
+ readyState = 1;
+ constructor() { super(); streams.add(this); }
+ close() { streams.delete(this); this.readyState = 2; }
+ }
+ Object.defineProperty(window, 'EventSource', { value: FixtureEvents });
+ const target = window as unknown as { __serverEvent: (type: string, data: object) => void; __appBadges: number[] };
+ target.__serverEvent = (type, data) => streams.forEach((stream) => stream.dispatchEvent(new MessageEvent(type, {
+ data: JSON.stringify({ type, data }),
+ })));
+ target.__appBadges = [];
+ Object.defineProperty(navigator, 'setAppBadge', { configurable: true, value: async (count: number) => { target.__appBadges.push(count); } });
+ Object.defineProperty(navigator, 'clearAppBadge', { configurable: true, value: async () => { target.__appBadges.push(0); } });
+ });
+ await tab.route('**/api/bots', (route) => (route.request().method() === 'GET'
+ ? route.fulfill({ json: { ok: true, bots: server.bots.map(payload) } })
+ : route.fallback()));
+ await tab.route('**/api/inbox**', (route) => {
+ const only = new URL(route.request().url()).searchParams.get('session');
+ const sessions = only ? server.sessions.filter((row) => row.session_id === only) : server.sessions;
+ const map = unread();
+ return route.fulfill({ json: {
+ sessions, next_cursor: null, unread_by_session: map,
+ unread_total: Object.values(map).reduce((sum, n) => sum + n, 0), unread_sessions: Object.keys(map).length,
+ badge_total: badgeTotal(),
+ } });
+ });
+ await tab.route('**/api/notifications/preferences', async (route) => {
+ if (route.request().method() === 'PUT') {
+ server.preferences = { ...server.preferences, ...route.request().postDataJSON() };
+ await route.fulfill({ json: { ok: true, preferences: server.preferences } });
+ await publish('notifications.preferences.updated', { user_key: 'local', preferences: server.preferences });
+ return;
+ }
+ return route.fulfill({ json: { ok: true, preferences: server.preferences } });
+ });
+ await tab.route('**/api/bots/cso', async (route) => {
+ if (route.request().method() !== 'DELETE') return route.fallback();
+ // Removing the Bot hides its Session everywhere the server answers.
+ server.bots = server.bots.filter((bot) => bot.handle !== 'cso');
+ server.sessions = server.sessions.filter((row) => row.session_id !== 'ses_cso');
+ await route.fulfill({ json: { ok: true, bot: payload(CSO, 1) } });
+ await publish('bots.changed', { handle: 'cso' });
+ });
+ await tab.setViewportSize(DESKTOP);
+ await open(tab, '/', { lang: 'zh' });
+ }
+ const [a] = tabs;
+ const lastBadge = (tab: Page) => tab.evaluate(() => (window as unknown as { __appBadges: number[] }).__appBadges.at(-1));
+
+ // Sessions are muted: both tabs count the Bot's 2.
+ for (const tab of tabs) await expect(sidebarOf(tab).getByRole('link', { name: '收件箱,2 条未读' })).toBeVisible();
+
+ await sidebarOf(a).getByRole('button', { name: '首席安全官,2 条未读' }).click({ button: 'right' });
+ await a.getByRole('menu').getByRole('menuitem', { name: '移出伙伴' }).click();
+ // Its Session is gone, not moved to Sessions: only the muted Session's 3 remains.
+ await expect.poll(() => badgeTotal()).toBe(0);
+ for (const tab of tabs) {
+ await expect(sidebarOf(tab).getByRole('button', { name: /^首席安全官/ })).toHaveCount(0);
+ await expect(sidebarOf(tab).getByRole('link', { name: '收件箱:有未读,通知已关闭' })).toBeVisible();
+ await expect.poll(() => lastBadge(tab)).toBe(0);
+ }
+
+ const inbox = sidebarOf(a).getByRole('link', { name: '收件箱:有未读,通知已关闭' });
+ await inbox.hover();
+ const popover = a.getByRole('dialog', { name: '收件箱' });
+ await expect(popover).not.toContainText('首席安全官');
+ await popover.getByRole('button', { name: '通知设置' }).click();
+ await popover.getByRole('switch', { name: '会话消息' }).click();
+
+ // Both tabs show the number the server gives every reader.
+ await expect.poll(() => badgeTotal()).toBe(3);
+ for (const tab of tabs) {
+ await expect(sidebarOf(tab).getByRole('link', { name: '收件箱,3 条未读' })).toBeVisible();
+ await expect.poll(() => lastBadge(tab)).toBe(3);
+ }
+ for (const denied of denials) expect(denied).toEqual([]);
+});
diff --git a/ui/src/components/workbench/InboxHoverPopover.test.tsx b/ui/src/components/workbench/InboxHoverPopover.test.tsx
index 5a820d247..15777c017 100644
--- a/ui/src/components/workbench/InboxHoverPopover.test.tsx
+++ b/ui/src/components/workbench/InboxHoverPopover.test.tsx
@@ -197,9 +197,9 @@ describe('with Bots', () => {
expect(screen.queryByText('bots.tag')).toBeNull();
});
- it("files a removed Bot's Session with the Sessions, as the server counts it", () => {
- // `ses_retired` keeps its id after its Bot is removed, but it is not in the live list.
- mountWithBots([botRow('ses_cso', 1), { ...row(7, 2), session_id: 'ses_retired' }], { ses_cso: 1, ses_retired: 4 });
+ it('files a Session that is not on the Bot list with the Sessions, whatever its id', () => {
+ // The live list decides, as on the server; an id pattern does not.
+ mountWithBots([botRow('ses_cso', 1), { ...row(7, 2), session_id: 'ses_ordinary' }], { ses_cso: 1, ses_ordinary: 4 });
const sessionsSection = screen.getByText('workbench.inbox.sections.sessions').closest('section')!;
expect(sessionsSection.textContent).toContain('Session 7');
const botsSection = screen.getByText('workbench.inbox.sections.bots').closest('section')!;
diff --git a/ui/src/context/BotRosterContext.ts b/ui/src/context/BotRosterContext.ts
index 064bdbc06..046a26e53 100644
--- a/ui/src/context/BotRosterContext.ts
+++ b/ui/src/context/BotRosterContext.ts
@@ -5,8 +5,9 @@ import { createContext, useContext } from 'react';
*
* The answer is the server's: a Session is a Bot's while it is the permanent
* Session of a current Bot, which is exactly the Owner's live Bot list
- * (`BotsProvider`, refetched on `bots.changed`). A removed Bot's `ses_` Session
- * is an ordinary Session again, and a reader who is not the Owner has no Bots.
+ * (`BotsProvider`, refetched on `bots.changed`). A removed Bot's Session is
+ * hidden, not reclassified: the Inbox re-reads on `bots.changed` and the server
+ * leaves it out. A reader who is not the Owner has no Bots.
*
* `BotsProvider` lives inside the router, under the authorization it needs,
* while the Inbox and the badges it drives live above the router. This bridge
diff --git a/ui/src/context/WorkbenchInboxProvider.botRoster.test.tsx b/ui/src/context/WorkbenchInboxProvider.botRoster.test.tsx
new file mode 100644
index 000000000..94a1c202d
--- /dev/null
+++ b/ui/src/context/WorkbenchInboxProvider.botRoster.test.tsx
@@ -0,0 +1,168 @@
+// @vitest-environment jsdom
+
+import { act, cleanup, render } from '@testing-library/react';
+import { useEffect } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { InboxSession, WorkbenchEventHandlers } from './ApiContext';
+import { BotRosterContext, type BotRoster } from './BotRosterContext';
+import { NotificationPreferencesContext } from './NotificationPreferencesContext';
+import { useWorkbenchInbox, type InboxState } from './WorkbenchInboxContext';
+import { WorkbenchInboxProvider } from './WorkbenchInboxProvider';
+import badgeFixture from '../lib/notificationBadge.fixture.json';
+import type { NotificationPreferences } from '../lib/notificationPreferences';
+
+// Which Sessions exist is the server's answer (docs/plans/bots.md D1): a removed
+// Bot's Session is hidden, not an ordinary Session. These tests hold the client
+// to that across the changes no Inbox event announces.
+
+const apiRef = { current: null as unknown };
+vi.mock('./ApiContext', async () => {
+ const actual = await vi.importActual<typeof import('./ApiContext')>('./ApiContext');
+ return { ...actual, useApi: () => apiRef.current };
+});
+
+type ListInboxArgs = { limit?: number; before?: string; onlySession?: string };
+
+const key = (row: InboxSession) => `${row.last_activity_at}|${row.session_id}`;
+const minute = (n: number) => new Date(Date.UTC(2026, 10, 1, 8, 0) - n * 60_000).toISOString();
+const row = (sessionId: string, minutesAgo: number, unread = 0): InboxSession => ({
+ session_id: sessionId, scope_id: null, project_id: null, project_name: null, title: sessionId,
+ last_activity_at: minute(minutesAgo), last_message_author: 'agent', replied: false,
+ preview_text: `Reply in ${sessionId}`, preview_at: minute(minutesAgo), unread_count: unread, unread: unread > 0,
+});
+
+/** The server: the rows a reader may see, newest first, paged the way `GET /api/inbox` pages them. */
+function fakeServer(initial: InboxSession[]) {
+ const server = { rows: initial };
+ const handlers: WorkbenchEventHandlers[] = [];
+ const listInbox = vi.fn(async ({ limit = 30, before, onlySession }: ListInboxArgs) => {
+ const sorted = [...server.rows].sort((a, b) => (key(a) < key(b) ? 1 : -1));
+ const unread = Object.fromEntries(sorted.filter((r) => r.unread_count > 0).map((r) => [r.session_id, r.unread_count]));
+ if (onlySession) {
+ return { sessions: sorted.filter((r) => r.session_id === onlySession), next_cursor: null, unread_by_session: unread };
+ }
+ const window = sorted.filter((r) => before === undefined || key(r) < before).slice(0, limit);
+ const next = window.length === limit ? key(window[window.length - 1]) : null;
+ return { sessions: window, next_cursor: next, unread_by_session: unread };
+ });
+ apiRef.current = {
+ listInbox,
+ markSessionRead: vi.fn(async () => ({ updated: 0 })),
+ connectWorkbenchEvents: (next: WorkbenchEventHandlers) => {
+ handlers.push(next);
+ return () => undefined;
+ },
+ };
+ const emit = (fire: (handler: WorkbenchEventHandlers) => void) => act(async () => {
+ for (const handler of handlers) fire(handler);
+ });
+ return { server, listInbox, emit };
+}
+
+const settle = () => act(async () => {
+ for (let i = 0; i < 20; i += 1) await new Promise((resolve) => setTimeout(resolve, 0));
+});
+
+function mount(roster: BotRoster, preferences: NotificationPreferences) {
+ const state = { current: null as InboxState | null };
+ const Probe = () => {
+ const inbox = useWorkbenchInbox();
+ useEffect(() => { state.current = inbox; });
+ return null;
+ };
+ const tree = (bots: BotRoster) => (
+ <BotRosterContext.Provider value={{ roster: bots, publish: () => {} }}>
+ <NotificationPreferencesContext.Provider value={{ preferences, loaded: true, update: async () => true }}>
+ <WorkbenchInboxProvider><Probe /></WorkbenchInboxProvider>
+ </NotificationPreferencesContext.Provider>
+ </BotRosterContext.Provider>
+ );
+ const view = render(tree(roster));
+ return { state, rerender: (bots: BotRoster) => view.rerender(tree(bots)) };
+}
+
+const roster = (ids: string[]): BotRoster => ({ sessionIds: new Set(ids), known: true });
+const ids = (state: { current: InboxState | null }) => state.current!.inboxSessions.map((r) => r.session_id);
+
+const removal = badgeFixture.removed_bot;
+const fixtureRows = (map: Record<string, number>) =>
+ Object.entries(map).map(([sessionId, unread], index) => row(sessionId, index + 1, unread));
+
+let setAppBadge: ReturnType<typeof vi.fn>;
+let clearAppBadge: ReturnType<typeof vi.fn>;
+beforeEach(() => {
+ setAppBadge = vi.fn(async () => {});
+ clearAppBadge = vi.fn(async () => {});
+ Object.defineProperty(navigator, 'setAppBadge', { configurable: true, value: setAppBadge });
+ Object.defineProperty(navigator, 'clearAppBadge', { configurable: true, value: clearAppBadge });
+});
+afterEach(() => {
+ cleanup();
+ Reflect.deleteProperty(navigator, 'setAppBadge');
+ Reflect.deleteProperty(navigator, 'clearAppBadge');
+});
+
+describe('a Bot roster change', () => {
+ it.each(removal.cases)('takes a removed Bot\'s Session out of the feed, the counts and the badge, as the server does ($name)', async (fixture) => {
+ const { server, emit } = fakeServer(fixtureRows(removal.before.unread_by_session));
+ const { state, rerender } = mount(roster(removal.before.bot_session_ids), fixture.preferences);
+ await settle();
+ expect(ids(state)).toContain(`ses_${removal.removed}`);
+
+ // Removing the Bot hides its Session on the server; no Inbox event says so.
+ server.rows = fixtureRows(removal.after.unread_by_session);
+ await emit((handler) => handler.onBotsChanged?.({ handle: removal.removed }));
+ rerender(roster(removal.after.bot_session_ids));
+ await settle();
+
+ expect(ids(state)).not.toContain(`ses_${removal.removed}`);
+ expect(state.current!.unreadBySession).toEqual(removal.after.unread_by_session);
+ expect(state.current!.unreadByCategory).toEqual(fixture.unread_by_category);
+ // The server's badge_total for the same data (tests/test_notification_badge_parity.py).
+ expect(state.current!.badgeTotal).toBe(fixture.badge_total);
+ expect(setAppBadge).toHaveBeenLastCalledWith(fixture.badge_total);
+ });
+
+ it('brings a Session back when its Bot is set again', async () => {
+ const { server, emit } = fakeServer(fixtureRows(removal.after.unread_by_session));
+ const { state, rerender } = mount(roster(removal.after.bot_session_ids), removal.cases[0].preferences);
+ await settle();
+ expect(ids(state)).not.toContain(`ses_${removal.removed}`);
+
+ server.rows = fixtureRows(removal.before.unread_by_session);
+ await emit((handler) => handler.onBotsChanged?.({ handle: removal.removed }));
+ rerender(roster(removal.before.bot_session_ids));
+ await settle();
+
+ expect(ids(state)).toContain(`ses_${removal.removed}`);
+ expect(state.current!.unreadBySession).toEqual(removal.before.unread_by_session);
+ });
+});
+
+describe('re-reading the window', () => {
+ it('drops loaded rows the server no longer returns within the range it re-read, and keeps the rows below it', async () => {
+ // Forty rows: page one and one "Load more".
+ const original = Array.from({ length: 40 }, (_, index) => row(`sesr${index}`, 100 + index));
+ const { server, emit } = fakeServer(original);
+ const { state } = mount(roster([]), removal.cases[0].preferences);
+ await settle();
+ await act(async () => { await state.current!.loadMore(); });
+ await settle();
+ expect(ids(state)).toHaveLength(40);
+
+ // While the stream was down two Sessions became hidden and five new ones
+ // arrived, so the re-read of 40 rows ends at sesr36.
+ const arrived = Array.from({ length: 5 }, (_, index) => row(`sesn${index}`, index + 1));
+ server.rows = [...arrived, ...original.filter((r) => r.session_id !== 'sesr5' && r.session_id !== 'sesr35')];
+ await emit((handler) => handler.onConnected?.());
+ await settle();
+
+ const shown = ids(state);
+ expect(shown).not.toContain('sesr5');
+ expect(shown).not.toContain('sesr35');
+ // Below the re-read edge nothing was asked, so nothing is concluded.
+ expect(shown.slice(-3)).toEqual(['sesr37', 'sesr38', 'sesr39']);
+ expect(shown.slice(0, 5)).toEqual(['sesn0', 'sesn1', 'sesn2', 'sesn3', 'sesn4']);
+ });
+});
diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsx
index 199f65ed4..55a91cc9b 100644
--- a/ui/src/context/WorkbenchInboxProvider.tsx
+++ b/ui/src/context/WorkbenchInboxProvider.tsx
@@ -556,9 +556,20 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
retryAfterInvalidation();
} else {
const snapshotsToRevalidate = acceptFeedRows(read, result.sessions, true);
+ // The read is the server's whole answer for every row that sorts above its
+ // last one, or for all of them when there is no further page. A loaded row
+ // in that range that the answer leaves out is one this reader may no longer
+ // see — a removed Bot's Session (docs/plans/bots.md D1), say, while the
+ // stream was down — so it goes, with no event needed to say so. Rows below
+ // that edge were not re-read and stay.
+ const edge = result.sessions.at(-1);
+ const reread = (row: InboxSession) =>
+ result.next_cursor === null || (edge !== undefined && byActivityDesc(row, edge) < 0);
setInboxSessions((prev) => {
const incoming = new Map(result.sessions.map((s) => [s.session_id, s]));
- const merged = prev.map((s) => incoming.get(s.session_id) ?? s);
+ const merged = prev
+ .filter((s) => incoming.has(s.session_id) || !reread(s))
+ .map((s) => incoming.get(s.session_id) ?? s);
const have = new Set(prev.map((s) => s.session_id));
for (const s of result.sessions) if (!have.has(s.session_id)) merged.push(s);
merged.sort(byActivityDesc);
@@ -841,6 +852,16 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
// read rather than a reconcile onto rows that are no longer there.
if (isFeedActive()) readFeedForActiveConsumer();
},
+ // The Bot roster decides which Sessions this reader may see: removing a Bot
+ // hides its Session and setting it again brings it back (bots.md D1), with
+ // no Inbox event of its own. The server owns that answer, so read it again
+ // rather than reclassify locally. Owing the whole map does exactly that: it
+ // fences the reads already in flight, and the read that pays it is the
+ // window's reconcile while the feed is shown (which drops rows the server
+ // no longer returns) or the counts read while it is not.
+ onBotsChanged: () => {
+ oweWholeUnread();
+ },
onInboxSessionUpdated: (row) => {
targetedSnapshotsRef.current.delete(row.session_id);
acceptSessionMutation(row.session_id);
diff --git a/ui/src/context/shellBootstrapDemand.test.tsx b/ui/src/context/shellBootstrapDemand.test.tsx
index 066e3820a..2399aef18 100644
--- a/ui/src/context/shellBootstrapDemand.test.tsx
+++ b/ui/src/context/shellBootstrapDemand.test.tsx
@@ -829,12 +829,12 @@ describe('Demand-driven shell bootstrap', () => {
Object.defineProperty(navigator, 'clearAppBadge', { configurable: true, value: clearAppBadge });
try {
- // Two unread replies from a Bot; five from an ordinary Session and three
- // from a removed Bot's, which the server counts as a Session too.
+ // Two unread replies from a Bot; five and three from ordinary Sessions,
+ // one with an id that merely starts like a Bot's: the list decides.
const listInbox = vi.fn(async (_args: ListInboxArgs) => ({
sessions: [],
next_cursor: null,
- unread_by_session: { ses_cso: 2, sesa1b2c3d4e5: 5, ses_retired: 3 },
+ unread_by_session: { ses_cso: 2, sesa1b2c3d4e5: 5, ses_ordinary: 3 },
}));
apiRef.current = { listInbox, connectWorkbenchEvents: vi.fn(() => vi.fn()) };
const roster: BotRoster = { sessionIds: new Set(['ses_main', 'ses_cso']), known: true };
diff --git a/ui/src/lib/notificationBadge.fixture.json b/ui/src/lib/notificationBadge.fixture.json
index 6f15d9d54..852a103ad 100644
--- a/ui/src/lib/notificationBadge.fixture.json
+++ b/ui/src/lib/notificationBadge.fixture.json
@@ -1,47 +1,80 @@
{
- "description": "One set of Inbox unread data and switches, with the category split and badge both sides must compute. Read by ui/src/lib/notificationPreferences.test.ts (the page's live badge) and tests/test_notification_badge_parity.py (the server's badge_total).",
+ "description": "Inbox unread data and switches, with the category split and badge both sides must compute. `cases` run the page's pure functions (ui/src/lib/notificationPreferences.test.ts) and the server's (tests/test_notification_badge_parity.py) on one unread map as the server reports it. `removed_bot` runs the same numbers across a roster change: through GET /api/inbox on the server, and through a live client that held the Bot's unread before the change (ui/src/context/WorkbenchInboxProvider.botRoster.test.tsx).",
"unread_by_session": {
"ses_main": 1,
"ses_cso": 2,
- "ses_retired": 3,
"sesa1b2c3d4e5": 4,
"sesz9y8x7w6v5": 5
},
"cases": [
{
- "name": "Owner, every switch on; a removed Bot's ses_ Session is an ordinary Session",
+ "name": "Owner, every switch on",
"bot_session_ids": ["ses_main", "ses_cso"],
"preferences": { "enabled": true, "bots": true, "sessions": true },
- "unread_by_category": { "bot": 3, "session": 12 },
- "badge_total": 15
+ "unread_by_category": { "bot": 3, "session": 9 },
+ "badge_total": 12
},
{
"name": "Owner, Session messages muted",
"bot_session_ids": ["ses_main", "ses_cso"],
"preferences": { "enabled": true, "bots": true, "sessions": false },
- "unread_by_category": { "bot": 3, "session": 12 },
+ "unread_by_category": { "bot": 3, "session": 9 },
"badge_total": 3
},
{
"name": "Owner, Bot messages muted",
"bot_session_ids": ["ses_main", "ses_cso"],
"preferences": { "enabled": true, "bots": false, "sessions": true },
- "unread_by_category": { "bot": 3, "session": 12 },
- "badge_total": 12
+ "unread_by_category": { "bot": 3, "session": 9 },
+ "badge_total": 9
},
{
"name": "Owner, master switch off",
"bot_session_ids": ["ses_main", "ses_cso"],
"preferences": { "enabled": false, "bots": true, "sessions": true },
- "unread_by_category": { "bot": 3, "session": 12 },
+ "unread_by_category": { "bot": 3, "session": 9 },
"badge_total": 0
},
{
- "name": "A reader without Bots: everything is a Session",
+ "name": "Not on the Bot list, whatever the id: everything is a Session",
"bot_session_ids": [],
"preferences": { "enabled": true, "bots": true, "sessions": false },
- "unread_by_category": { "bot": 0, "session": 15 },
+ "unread_by_category": { "bot": 0, "session": 12 },
"badge_total": 0
}
- ]
+ ],
+ "removed_bot": {
+ "description": "The Owner removes the Bot `retired` while its Session has 3 unread replies. From then on its Session is hidden (docs/plans/bots.md D1), not an ordinary Session: the server leaves it out of the unread map, so neither category and no badge counts it.",
+ "bots": ["cso", "retired"],
+ "removed": "retired",
+ "agent_replies": {
+ "ses_main": 1,
+ "ses_cso": 2,
+ "ses_retired": 3,
+ "sesa1b2c3d4e5": 4,
+ "sesz9y8x7w6v5": 5
+ },
+ "before": {
+ "bot_session_ids": ["ses_main", "ses_cso", "ses_retired"],
+ "unread_by_session": { "ses_main": 1, "ses_cso": 2, "ses_retired": 3, "sesa1b2c3d4e5": 4, "sesz9y8x7w6v5": 5 }
+ },
+ "after": {
+ "bot_session_ids": ["ses_main", "ses_cso"],
+ "unread_by_session": { "ses_main": 1, "ses_cso": 2, "sesa1b2c3d4e5": 4, "sesz9y8x7w6v5": 5 }
+ },
+ "cases": [
+ {
+ "name": "every switch on",
+ "preferences": { "enabled": true, "bots": true, "sessions": true },
+ "unread_by_category": { "bot": 3, "session": 9 },
+ "badge_total": 12
+ },
+ {
+ "name": "Session messages muted",
+ "preferences": { "enabled": true, "bots": true, "sessions": false },
+ "unread_by_category": { "bot": 3, "session": 9 },
+ "badge_total": 3
+ }
+ ]
+ }
}
diff --git a/ui/src/lib/notificationPreferences.test.ts b/ui/src/lib/notificationPreferences.test.ts
index b226ec913..6e72022d5 100644
--- a/ui/src/lib/notificationPreferences.test.ts
+++ b/ui/src/lib/notificationPreferences.test.ts
@@ -16,8 +16,8 @@ const MASTER_OFF = { enabled: false, bots: true, sessions: true };
describe('notification preferences', () => {
// Two Bot replies in the main Bot's and a colleague's conversation, nine in
- // ordinary Sessions, one of them a removed Bot's.
- const unread = { ses_main: 1, ses_cso: 1, ses_retired: 4, sesz9y8x7w6v5: 5, sesq1w2e3r4t5: 0 };
+ // ordinary Sessions, one of them with an id that merely starts like a Bot's.
+ const unread = { ses_main: 1, ses_cso: 1, ses_ordinary: 4, sesz9y8x7w6v5: 5, sesq1w2e3r4t5: 0 };
const counts = unreadByCategory(unread, new Set(['ses_main', 'ses_cso']));
it("splits unread by the live Bot list, not by the id's prefix", () => {
diff --git a/ui/src/lib/notificationPreferences.ts b/ui/src/lib/notificationPreferences.ts
index 3617f4323..dc7e5238c 100644
--- a/ui/src/lib/notificationPreferences.ts
+++ b/ui/src/lib/notificationPreferences.ts
@@ -24,10 +24,11 @@ export const NOTIFICATIONS_SETTINGS_PATH = '/settings/notifications';
/**
* A Session is a Bot conversation while it is a current Bot's permanent Session,
* the server's own definition (`core/notification_categories.py`). The caller
- * passes the Bot Sessions it knows, the live Bot list (`BotRosterContext`); a
- * removed Bot's `ses_` Session is therefore an ordinary Session, as it is on the
- * server. One classifier serves the feed rows and the unread map, so a row's
- * section and the count it adds to cannot disagree.
+ * passes the Bot Sessions it knows, the live Bot list (`BotRosterContext`), not
+ * an id pattern. (A removed Bot's Session is not here at all: the server hides it
+ * from every Inbox read and event, docs/plans/bots.md D1.) One classifier serves
+ * the feed rows and the unread map, so a row's section and the count it adds to
+ * cannot disagree.
*/
export const inboxCategory = (sessionId: string, botSessionIds: ReadonlySet<string>): InboxCategory =>
(botSessionIds.has(sessionId) ? 'bot' : 'session');
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 468e5c2aa..70943518e 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -13507,6 +13507,31 @@ def _workbench_event_heartbeat_frame() -> str:
return f'event: heartbeat\ndata: {{"interval_ms":{interval_ms}}}\n\n'
+#: Frames that hand the client an Inbox row, which it adds to its feed and counts.
+_INBOX_ROW_EVENTS = frozenset({"inbox.session.updated"})
+
+
+def _inbox_row_hidden_from(context, payload: str) -> bool:
+ """Whether an Inbox row names a Session this reader's ``GET /api/inbox`` leaves out.
+
+ That read hides the Bot Sessions in ``_hidden_bot_session_ids`` (a removed Bot's
+ for the Owner, every Bot's for anyone else; ``docs/plans/bots.md`` D1), and a
+ realtime row must not hand one back: the client would show and count a Session
+ the server says does not exist for it. Decided per recipient here, on the
+ delivery worker thread rather than the loop of the process that published the
+ row, so every open client and the desktop host get the same answer. Only ids in
+ the Bots' namespace pay for the read.
+ """
+ from storage.agent_session_rows import is_bot_session_id
+
+ data = _workbench_event_data(payload)
+ session_id = data.get("session_id") if data is not None else None
+ if not isinstance(session_id, str) or not is_bot_session_id(session_id):
+ return False
+ with _projects_engine().connect() as conn:
+ return session_id in _hidden_bot_session_ids(conn, context)
+
+
def _workbench_event_visible_to_context(context, event_type: str, payload: str) -> bool:
if event_type == "notifications.preferences.updated":
data = _workbench_event_data(payload)
@@ -13514,6 +13539,8 @@ def _workbench_event_visible_to_context(context, event_type: str, payload: str)
data is not None
and data.get("user_key") == _notification_user_key_for_context(context)
)
+ if event_type in _INBOX_ROW_EVENTS and _inbox_row_hidden_from(context, payload):
+ return False
if context is None:
return True
if event_type == "show.event":