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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(ui): split the Inbox into Bots and Sessions with notification switches (#3130)
Call Whitecd6363f364b0
diff --git a/docs/plans/workbench-refinements.md b/docs/plans/workbench-refinements.mdindex 522a48c2f..de7993161 100644--- a/docs/plans/workbench-refinements.md+++ b/docs/plans/workbench-refinements.md@@ -130,13 +130,33 @@ it is still delivered, listed, and unread.popover header (left of "Mark all read") and from a "Notifications: All /Bots only / Sessions only / Off" button on the Inbox page toolbar. The bell is`Bell` when everything is on, `BellMinus` with a short label when partial, and- `BellOff` when off. The hover popover stays open while the portaled menu is- open.+ `BellOff` when off. In the hover popover the bell swaps the popover's body for+ the menu in place, with a way back, so the hover surface never hosts a second+ floating layer; on the Inbox page the menu is an ordinary popover.- Settings › Notifications, a new page right after General in`ui/src/components/settings/SettingsLayout.tsx`: the same switches withone-line explanations, "This device" with the full `WebPushControl` (moved out- of the Inbox toolbar), and a note that desktop OS notifications are switched- from the tray menu.+ of the Inbox toolbar), and, in the desktop app, a note that its OS+ notifications are switched from the tray menu.+- The client holds the switches in one provider above the router+ (`NotificationPreferencesProvider`), read on mount and re-read on the stream's+ preference nudge, a reconnect, or an authorization change. A change applies+ at once and writes only the switch it changes, which the server merges, so+ two devices changing different switches keep both. Overlapping writes'+ responses cannot say which the server applied last, so each confirms only+ the switches it wrote; a refused save puts its switches back to their last+ confirmed value unless a later change has set them since, and the record is+ read back once the last write of a burst settles.+- A Session is a Bot conversation while it is a current Bot's permanent+ 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+ (`ui/src/lib/notificationBadge.fixture.json`) runs against both this+ computation and the server's `badge_total`.- Sidebar Inbox icon: a cyan number for `badge_total`; a grey dot with no numberwhen `badge_total` is 0 and anything is unread.diff --git a/tests/test_notification_badge_parity.py b/tests/test_notification_badge_parity.pynew file mode 100644index 000000000..ba978913a--- /dev/null+++ b/tests/test_notification_badge_parity.py@@ -0,0 +1,29 @@+"""The server's Inbox badge and the Web page's live badge follow one rule.++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.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from core.notification_categories import split_unread_counts+from core.notification_preferences import badge_total++FIXTURE = json.loads(+ (Path(__file__).resolve().parents[1] / "ui/src/lib/notificationBadge.fixture.json").read_text(encoding="utf-8")+)++[email protected]("case", FIXTURE["cases"], ids=lambda case: case["name"])+def test_server_badge_matches_the_shared_fixture(case):+ counts = split_unread_counts(FIXTURE["unread_by_session"], bot_session_ids=case["bot_session_ids"])++ assert counts == case["unread_by_category"]+ assert badge_total(counts, case["preferences"]) == case["badge_total"]diff --git a/ui/e2e/inbox-return/fixture.tsx b/ui/e2e/inbox-return/fixture.tsxindex 2acfd3bdd..7db5423f9 100644--- a/ui/e2e/inbox-return/fixture.tsx+++ b/ui/e2e/inbox-return/fixture.tsx@@ -63,7 +63,9 @@ export function Fixture() {};return <WorkbenchInboxContext.Provider value={{inboxSessions: sessions, unreadBySession: unread, totalUnread: Object.keys(unread).length,- unreadSessions: Object.keys(unread).length, nextCursor: sessions.length < 90 ? 'next' : null,+ unreadSessions: Object.keys(unread).length,+ unreadByCategory: { bot: 0, session: Object.keys(unread).length }, badgeTotal: Object.keys(unread).length,+ nextCursor: sessions.length < 90 ? 'next' : null,loading: false, loadingMore: false, refresh: async () => {},loadMore: async () => { setSessions(history); }, markRead, activateFeed,}}>diff --git a/ui/e2e/project-order/fixture.tsx b/ui/e2e/project-order/fixture.tsxindex 2e7babdb6..80ff1fa38 100644--- a/ui/e2e/project-order/fixture.tsx+++ b/ui/e2e/project-order/fixture.tsx@@ -71,7 +71,8 @@ export function Fixture() {capabilities: { ...OWNER_INSTANCE_CAPABILITIES, can_read_instance: false },}}><ToastContext.Provider value={{ showToast: noop }}><ApiProvider><UnsavedChangesProvider><WorkbenchProjectsProvider><WorkbenchInboxContext.Provider value={{- inboxSessions: [], unreadBySession: {}, totalUnread: 0, unreadSessions: 0, nextCursor: null,+ inboxSessions: [], unreadBySession: {}, totalUnread: 0, unreadSessions: 0,+ unreadByCategory: { bot: 0, session: 0 }, badgeTotal: 0, nextCursor: null,loading: false, loadingMore: false, refresh: async () => {}, loadMore: async () => {},markRead: async () => true, activateFeed: () => noop,}}><WindowManagerContext.Provider value={{ focusedId: null, focusCanvas: noop, openApp: noop } as unknown as WindowManagerValue}>diff --git a/ui/e2e/session-dot/fixture.tsx b/ui/e2e/session-dot/fixture.tsxindex dddf5c52a..ccbb32a43 100644--- a/ui/e2e/session-dot/fixture.tsx+++ b/ui/e2e/session-dot/fixture.tsx@@ -122,7 +122,8 @@ export function Fixture() {capabilities: { ...OWNER_INSTANCE_CAPABILITIES, can_manage_projects: false },}}><ToastContext.Provider value={{ showToast: noop }}><ApiProvider><UnsavedChangesProvider><WorkbenchProjectsProvider><WorkbenchInboxContext.Provider value={{- inboxSessions: [], unreadBySession: {}, totalUnread: 0, unreadSessions: 0, nextCursor: null,+ inboxSessions: [], unreadBySession: {}, totalUnread: 0, unreadSessions: 0,+ unreadByCategory: { bot: 0, session: 0 }, badgeTotal: 0, nextCursor: null,loading: false, loadingMore: false, refresh: async () => {}, loadMore: async () => {},markRead: async () => true, activateFeed: () => noop,}}><WindowManagerContext.Provider value={{ focusedId: null, focusCanvas: noop, openApp: noop } as unknown as WindowManagerValue}>diff --git a/ui/e2e/workbench-general/bots.spec.ts b/ui/e2e/workbench-general/bots.spec.tsindex 7c51f96e8..b03a09611 100644--- a/ui/e2e/workbench-general/bots.spec.ts+++ b/ui/e2e/workbench-general/bots.spec.ts@@ -168,16 +168,74 @@ for (const theme of ['light', 'dark'] as const) {await expect(page.getByRole('menu').getByRole('menuitem', { name: '移出伙伴' })).toHaveCount(0);await page.keyboard.press('Escape');- // The Inbox popover: a Bot row is the Bot, with its tag.+ // The Inbox popover: Bots above Sessions, and a Bot row is the Bot+ // (docs/plans/workbench-refinements.md §1).await inbox.hover();const popover = page.getByRole('dialog', { name: '收件箱' });await expect(popover).toBeVisible();- await expect(popover.getByRole('button').filter({ hasText: '首席安全官' })).toContainText('伙伴');+ const botsHeader = popover.getByText('伙伴', { exact: true });+ const sessionsHeader = popover.getByText('会话', { exact: true });+ await expect(botsHeader).toBeVisible();+ await expect(sessionsHeader).toBeVisible();+ expect((await botsHeader.boundingBox())!.y).toBeLessThan((await sessionsHeader.boundingBox())!.y);+ await expect(popover.getByRole('button').filter({ hasText: '首席安全官' })).toContainText('avault');await expect(popover.getByRole('button').filter({ hasText: '中文项目' })).toContainText('Fix the cache break');await page.screenshot({ animations: 'disabled', path: `${SHOTS}/bots-inbox-${theme}.png`, clip: { x: 0, y: 0, width: 680, height: 560 } });expect(denied).toEqual([]);});+ test(`muting Session messages leaves the Inbox counting Bots, and the switches are one click away (${theme})`, async ({ page }) => {+ const { denied } = await serveBots(page, 'zh', [MAIN, CSO, PM]);+ let preferences = { enabled: true, bots: true, sessions: false };+ const saved: unknown[] = [];+ await page.route('**/api/notifications/preferences', async (route) => {+ if (route.request().method() === 'PUT') {+ const changes = route.request().postDataJSON();+ saved.push(changes);+ preferences = { ...preferences, ...changes };+ }+ return route.fulfill({ json: { ok: true, preferences } });+ });+ await page.setViewportSize(DESKTOP);+ await open(page, '/', { lang: 'zh', theme });+ const sidebar = sidebarOf(page);++ // The Bot's 2 count; the Session's 3 is quiet (docs/plans/workbench-refinements.md §1).+ const inbox = sidebar.getByRole('link', { name: '收件箱,2 条未读' });+ await expect(inbox).toHaveText('2');+ await inbox.hover();+ const popover = page.getByRole('dialog', { name: '收件箱' });+ await expect(popover.getByText('免打扰')).toHaveCount(1);+ const bell = popover.getByRole('button', { name: '通知设置' });+ await expect(bell).toContainText('仅伙伴');+ await page.screenshot({ animations: 'disabled', path: `${SHOTS}/notifications-inbox-${theme}.png`, clip: { x: 0, y: 0, width: 680, height: 560 } });++ await bell.click();+ const sessions = popover.getByRole('switch', { name: '会话消息' });+ await expect(sessions).toHaveAttribute('aria-checked', 'false');+ await expect(popover).toContainText('会话消息照常进收件箱');+ await page.screenshot({ animations: 'disabled', path: `${SHOTS}/notifications-menu-${theme}.png`, clip: { x: 0, y: 0, width: 680, height: 560 } });+ await sessions.click();+ expect(saved).toEqual([{ sessions: true }]);+ await expect(sidebar.getByRole('link', { name: '收件箱,5 条未读' })).toHaveText('5');++ await popover.getByRole('button', { name: '更多通知设置' }).click();+ await expect(page).toHaveURL(/\/settings\/notifications/);+ await expect(popover).toBeHidden();+ await expect(page.getByRole('heading', { name: '通知', level: 1 })).toBeVisible();+ await expect(page.getByRole('switch', { name: '会话消息' })).toHaveAttribute('aria-checked', 'true');+ await page.screenshot({ animations: 'disabled', path: `${SHOTS}/notifications-settings-${theme}.png` });++ // The full Inbox: the same two sections, and the switches behind one button.+ await open(page, '/inbox', { lang: 'zh', theme });+ const main = page.getByRole('main');+ await expect(main.getByRole('button', { name: /^通知:全部/ })).toBeVisible();+ await expect(main.locator('section').first()).toContainText('首席安全官');+ await expect(main.locator('section').nth(1)).toContainText('Fix the cache break');+ await page.screenshot({ animations: 'disabled', path: `${SHOTS}/notifications-inbox-page-${theme}.png` });+ expect(denied).toEqual([]);+ });+test(`the add dialog generates a handle and offers existing Agents (${theme})`, async ({ page }) => {const { denied } = await serveBots(page, 'zh', [MAIN, CSO, PM]);await page.setViewportSize(DESKTOP);diff --git a/ui/e2e/workbench-general/geometry.spec.ts b/ui/e2e/workbench-general/geometry.spec.tsindex 3d3a8f8ac..9c4312602 100644--- a/ui/e2e/workbench-general/geometry.spec.ts+++ b/ui/e2e/workbench-general/geometry.spec.ts@@ -267,7 +267,7 @@ test.describe('workbench home geometry', () => {const inheritedReads = new Set(['/api/session', '/api/config', '/api/csrf-token', '/api/projects','/api/workbench/projects-bootstrap', '/api/sessions', '/api/agents',- '/api/inbox', '/api/version', '/api/events',+ '/api/inbox', '/api/notifications/preferences', '/api/version', '/api/events',// The home's Computer Use status line reads this on every mount.'/api/desktop/computer-use/status',]);diff --git a/ui/e2e/workbench-general/sidebar-floating.spec.ts b/ui/e2e/workbench-general/sidebar-floating.spec.tsindex 99bd6f47a..24012e403 100644--- a/ui/e2e/workbench-general/sidebar-floating.spec.ts+++ b/ui/e2e/workbench-general/sidebar-floating.spec.ts@@ -22,7 +22,7 @@ async function serveProduct(page: Page, lang: Lang = 'en') {const inheritedReads = new Set(['/api/session', '/api/config', '/api/csrf-token', '/api/projects','/api/workbench/projects-bootstrap', '/api/sessions', '/api/agents',- '/api/inbox', '/api/version', '/api/events', '/api/macos/login-session',+ '/api/inbox', '/api/notifications/preferences', '/api/version', '/api/events', '/api/macos/login-session','/api/desktop/computer-use/status', '/api/bots', '/api/sessions/ses_main',]);await page.route('**/api/**', (route) => {diff --git a/ui/e2e/workbench-general/support.ts b/ui/e2e/workbench-general/support.tsindex b847db7df..8e2bc030f 100644--- a/ui/e2e/workbench-general/support.ts+++ b/ui/e2e/workbench-general/support.ts@@ -111,6 +111,9 @@ export async function serveProduct(page: Page, lang: Lang = 'en') {await page.route('**/api/agents**', (route) => route.fulfill({ json: AGENTS }));await page.route('**/api/bots', (route) => route.fulfill({ json: BOTS }));await page.route('**/api/inbox**', (route) => route.fulfill({ json: { sessions: [], unread: {} } }));+ await page.route('**/api/notifications/preferences', (route) => route.fulfill({+ json: { ok: true, preferences: { enabled: true, bots: true, sessions: true } },+ }));// The service badge polls the bare `/status`, not an `/api` path.await page.route('**/status', (route) => route.fulfill({ json: { state: 'running' } }));await page.route('**/api/version**', (route) => route.fulfill({diff --git a/ui/eslint-baseline.json b/ui/eslint-baseline.jsonindex a6048bf47..42a5e8ef6 100644--- a/ui/eslint-baseline.json+++ b/ui/eslint-baseline.json@@ -506,7 +506,7 @@"react-hooks/set-state-in-effect": 1},"src/components/workbench/WorkbenchSidebar.tsx": {- "avibe/localized-user-text": 5+ "avibe/localized-user-text": 1},"src/components/workbench/harnessLifecycle.test.ts": {"@typescript-eslint/no-explicit-any": 1diff --git a/ui/src/App.tsx b/ui/src/App.tsxindex 969c908fa..be405114e 100644--- a/ui/src/App.tsx+++ b/ui/src/App.tsx@@ -37,6 +37,7 @@ import { SettingsPlatformsPage } from './components/settings/SettingsPlatformsPaimport { SettingsServicePage } from './components/settings/SettingsServicePage';import { SettingsGeneralPage } from './components/settings/SettingsGeneralPage';import { SettingsShortcutsPage } from './components/settings/SettingsShortcutsPage';+import { SettingsNotificationsPage } from './components/settings/SettingsNotificationsPage';import { SettingsComputerUsePage } from './components/settings/SettingsComputerUsePage';import { SettingsLayout } from './components/settings/SettingsLayout';import { SettingsOverlayRouteSurface } from './components/settings/SettingsOverlayRouteSurface';@@ -50,6 +51,8 @@ import { ToastProvider } from './context/ToastProvider';import { ThemeProvider } from './context/ThemeProvider';import { VaultSandboxAppearanceBridge } from './components/VaultSandboxAppearanceBridge';import { WorkbenchInboxProvider } from './context/WorkbenchInboxProvider';+import { NotificationPreferencesProvider } from './context/NotificationPreferencesProvider';+import { BotRosterProvider } from './context/BotRosterProvider';import { WorkbenchProjectsProvider } from './context/WorkbenchProjectsProvider';import { ComposerBridgeProvider } from './context/ComposerBridgeProvider';import { UnsavedChangesProvider } from './context/UnsavedChangesProvider';@@ -729,6 +732,7 @@ const settingsRoute = () => (alias follows them. Account keeps pointing at Replies, which still owns it. */}<Route path="appearance" element={<Navigate to="/settings/general" replace />} /><Route path="account" element={<Navigate to="/settings/replies" replace />} />+ <Route path="notifications" element={<SettingsNotificationsPage />} /><Route path="shortcuts" element={<SettingsShortcutsPage />} /><Route path="computer-use" element={<SettingsComputerUsePage />} /><Route path="service" element={<SettingsServicePage />} />@@ -874,6 +878,8 @@ function App() {<StatusProvider><ToastProvider><ApiProvider>+ <NotificationPreferencesProvider>+ <BotRosterProvider><WorkbenchInboxProvider><WorkbenchProjectsProvider><ComposerBridgeProvider>@@ -882,6 +888,8 @@ function App() {</ComposerBridgeProvider></WorkbenchProjectsProvider></WorkbenchInboxProvider>+ </BotRosterProvider>+ </NotificationPreferencesProvider></ApiProvider></ToastProvider></StatusProvider>diff --git a/ui/src/components/settings/SettingsLayout.tsx b/ui/src/components/settings/SettingsLayout.tsxindex 82a90f268..9f1f1ca64 100644--- a/ui/src/components/settings/SettingsLayout.tsx+++ b/ui/src/components/settings/SettingsLayout.tsx@@ -4,6 +4,7 @@ import React, { useEffect, useMemo, useState } from 'react';import { NavLink, Outlet, useLocation, useNavigate } from 'react-router-dom';import {ArrowLeft,+ Bell,ChevronDown,ChevronLeft,Cpu,@@ -66,6 +67,7 @@ const SETTINGS_GROUPS: SettingsGroup[] = [{items: [{ path: SETTINGS_LANDING_PATH, labelKey: 'settings.sections.general', icon: Settings },+ { path: '/settings/notifications', labelKey: 'settings.sections.notifications', icon: Bell },],},{diff --git a/ui/src/components/settings/SettingsNotificationsPage.test.tsx b/ui/src/components/settings/SettingsNotificationsPage.test.tsxnew file mode 100644index 000000000..cc4c99787--- /dev/null+++ b/ui/src/components/settings/SettingsNotificationsPage.test.tsx@@ -0,0 +1,63 @@+/* @vitest-environment jsdom */++import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { BotsContext, type BotsState } from '@/context/BotsContext';+import { NotificationPreferencesContext } from '@/context/NotificationPreferencesContext';+import type { NotificationPreferences } from '@/lib/notificationPreferences';+import { SettingsNotificationsPage } from './SettingsNotificationsPage';++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@/context/InstanceAuthorizationContext', () => ({+ useInstanceAuthorization: () => ({ capabilities: { can_read_instance: false } }),+}));++function mount(preferences: NotificationPreferences, hasBots: boolean) {+ const update = vi.fn(async () => true);+ render(+ <BotsContext.Provider value={{ enabled: hasBots } as BotsState}>+ <NotificationPreferencesContext.Provider value={{ preferences, loaded: true, update }}>+ <SettingsNotificationsPage />+ </NotificationPreferencesContext.Provider>+ </BotsContext.Provider>,+ );+ return update;+}++const switches = () => screen.getAllByRole('switch').map((node) => ({+ label: node.getAttribute('aria-label'),+ checked: node.getAttribute('aria-checked'),+ disabled: (node as HTMLButtonElement).disabled,+}));++afterEach(() => cleanup());++describe('Settings › Notifications', () => {+ it('saves each switch as a patch of the account record', () => {+ const update = mount({ enabled: true, bots: true, sessions: true }, true);++ expect(switches().map(({ label }) => label)).toEqual([+ 'workbench.notifications.title',+ 'workbench.notifications.bots',+ 'workbench.notifications.sessions',+ ]);+ fireEvent.click(screen.getByRole('switch', { name: 'workbench.notifications.sessions' }));+ expect(update).toHaveBeenCalledWith({ sessions: false });+ });++ it('holds the categories while the master switch is off', () => {+ mount({ enabled: false, bots: true, sessions: false }, true);++ expect(switches()).toEqual([+ { label: 'workbench.notifications.title', checked: 'false', disabled: false },+ { label: 'workbench.notifications.bots', checked: 'true', disabled: true },+ { label: 'workbench.notifications.sessions', checked: 'false', disabled: true },+ ]);+ });++ it('offers only the master switch to a member without Bots', () => {+ mount({ enabled: true, bots: true, sessions: true }, false);++ expect(switches().map(({ label }) => label)).toEqual(['workbench.notifications.title']);+ });+});diff --git a/ui/src/components/settings/SettingsNotificationsPage.tsx b/ui/src/components/settings/SettingsNotificationsPage.tsxnew file mode 100644index 000000000..92b999871--- /dev/null+++ b/ui/src/components/settings/SettingsNotificationsPage.tsx@@ -0,0 +1,91 @@+import { useTranslation } from 'react-i18next';++import { useBots } from '@/context/BotsContext';+import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';+import { useNotificationPreferences } from '@/context/NotificationPreferencesContext';+import { isDesktopShell } from '@/lib/desktopShell';+import { WebPushControl } from '../workbench/WebPushControl';+import { SettingsPageShell } from './SettingsPageShell';+import { SettingsPanel, SettingsRow, ToggleSwitch } from './SettingsPrimitives';++/**+ * Settings › Notifications (docs/plans/workbench-refinements.md §1): the account's+ * switches with what each one means, and this device's own push state. The+ * Inbox's notification menu is the compact form of the same switches.+ */+export const SettingsNotificationsPage: React.FC = () => {+ const { t } = useTranslation();+ const { preferences, update } = useNotificationPreferences();+ const { enabled: hasBots } = useBots();+ const { capabilities } = useInstanceAuthorization();+ const off = !preferences.enabled;+ const desktop = isDesktopShell();++ return (+ <SettingsPageShell+ title={t('settings.sections.notifications')}+ subtitle={t('settings.notifications.subtitle')}+ activeTab="notifications"+ >+ <SettingsPanel>+ <SettingsRow+ title={t('workbench.notifications.title')}+ description={t('settings.notifications.masterHint')}+ control={(+ <ToggleSwitch+ enabled={preferences.enabled}+ onClick={() => void update({ enabled: !preferences.enabled })}+ label={t('workbench.notifications.title')}+ />+ )}+ />+ {hasBots && (+ <>+ <SettingsRow+ title={t('workbench.notifications.bots')}+ description={t('settings.notifications.botsHint')}+ control={(+ <ToggleSwitch+ enabled={preferences.bots}+ disabled={off}+ onClick={() => void update({ bots: !preferences.bots })}+ label={t('workbench.notifications.bots')}+ />+ )}+ />+ <SettingsRow+ title={t('workbench.notifications.sessions')}+ description={t('settings.notifications.sessionsHint')}+ control={(+ <ToggleSwitch+ enabled={preferences.sessions}+ disabled={off}+ onClick={() => void update({ sessions: !preferences.sessions })}+ label={t('workbench.notifications.sessions')}+ />+ )}+ />+ </>+ )}+ </SettingsPanel>++ {(capabilities.can_read_instance || desktop) && (+ <SettingsPanel title={t('settings.notifications.deviceTitle')}>+ {capabilities.can_read_instance && (+ <SettingsRow+ title={t('settings.notifications.pushTitle')}+ description={t('settings.notifications.pushHint')}+ control={<WebPushControl />}+ />+ )}+ {desktop && (+ <SettingsRow+ title={t('settings.notifications.desktopTitle')}+ description={t('settings.notifications.desktopHint')}+ />+ )}+ </SettingsPanel>+ )}+ </SettingsPageShell>+ );+};diff --git a/ui/src/components/workbench/InboxHoverPopover.test.tsx b/ui/src/components/workbench/InboxHoverPopover.test.tsxindex 5bee09af6..5a820d247 100644--- a/ui/src/components/workbench/InboxHoverPopover.test.tsx+++ b/ui/src/components/workbench/InboxHoverPopover.test.tsx@@ -1,12 +1,16 @@/* @vitest-environment jsdom */import { cleanup, fireEvent, render, screen } from '@testing-library/react';-import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { MemoryRouter, Route, Routes } from 'react-router-dom';import { Popover } from '../ui/popover';import type { InboxSession } from '../../context/ApiContext';import { readInboxFilter } from '../../lib/inboxFilterMemory';import { InboxHoverPopover } from './WorkbenchSidebar';+import { BotsContext, type BotsState } from '../../context/BotsContext';+import { BotRosterContext } from '../../context/BotRosterContext';+import { NotificationPreferencesContext } from '../../context/NotificationPreferencesContext';+import type { Bot } from '../../lib/bots';vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));vi.mock('../ui/markdown', () => ({ Markdown: ({ content }: { content: string }) => <p>{content}</p> }));@@ -132,3 +136,101 @@ it('stays quiet when the peek is already full of unread sessions', () => {expect(mount(sessions, unread)).toHaveLength(5);expect(screen.queryByText('workbench.inbox.moreUnreadInFull')).toBeNull();});++describe('with Bots', () => {+ const bots: Bot[] = [+ { handle: 'main', display_name: 'Vibey', avatar: { kind: 'mascot' }, role: '', agent_name: 'main', session_id: 'ses_main', position: 0, builtin: true },+ { handle: 'cso', display_name: 'CSO', avatar: null, role: '', agent_name: 'cso', session_id: 'ses_cso', position: 1, builtin: false },+ ];+ const botsState = {+ enabled: true,+ bots,+ botForSession: (id: string | null | undefined) => bots.find((bot) => bot.session_id === id),+ displayName: (bot: Bot) => bot.display_name,+ } as unknown as BotsState;+ const botRow = (sessionId: string, minutesAgo: number): InboxSession => ({ ...row(0, minutesAgo), session_id: sessionId, title: null });++ function mountWithBots(+ sessions: InboxSession[],+ unreadBySession: Record<string, number>,+ preferences = { enabled: true, bots: true, sessions: true },+ ) {+ const roster = { sessionIds: new Set(bots.map((bot) => bot.session_id)), known: true };+ render(+ <MemoryRouter initialEntries={['/']}>+ <BotRosterContext.Provider value={{ roster, publish: () => {} }}>+ <BotsContext.Provider value={botsState}>+ <NotificationPreferencesContext.Provider value={{ preferences, loaded: true, update: async () => true }}>+ <Popover open>+ <InboxHoverPopover+ sessions={sessions}+ unreadBySession={unreadBySession}+ unreadSessions={Object.values(unreadBySession).filter((n) => n > 0).length}+ totalUnread={Object.values(unreadBySession).reduce((sum, n) => sum + n, 0)}+ canMarkRead+ onItemClick={() => {}}+ onMarkAllRead={() => {}}+ onMouseEnter={() => {}}+ onMouseLeave={() => {}}+ />+ </Popover>+ </NotificationPreferencesContext.Provider>+ </BotsContext.Provider>+ </BotRosterContext.Provider>+ </MemoryRouter>,+ );+ }+ const rowNames = () => screen+ .getAllByRole('button')+ .map((node) => node.textContent ?? '')+ .map((text) => text.match(/Session \d+|Vibey|CSO/)?.[0])+ .filter(Boolean);++ it('puts Bots above Sessions, three rows each and unread first', () => {+ const sessions = [botRow('ses_main', 1), row(1, 2), row(2, 3), botRow('ses_cso', 4), row(3, 5), row(4, 6)];+ mountWithBots(sessions, { ses_cso: 2, 'session-4': 1 });++ const headers = screen.getAllByText(/workbench\.inbox\.sections\.(bots|sessions)/).map((node) => node.textContent);+ expect(headers).toEqual(['workbench.inbox.sections.bots', 'workbench.inbox.sections.sessions']);+ expect(rowNames()).toEqual(['CSO', 'Vibey', 'Session 4', 'Session 1', 'Session 2']);+ // The section says Bot already; its rows carry no Bot tag.+ 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 });+ 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')!;+ expect(botsSection.textContent).not.toContain('Session 7');+ });++ it('leaves the Bots section out until a Bot has spoken', () => {+ mountWithBots([row(1, 1), row(2, 2)], {});+ expect(screen.queryByText('workbench.inbox.sections.bots')).toBeNull();+ expect(screen.getByText('workbench.inbox.sections.sessions')).toBeTruthy();+ });++ it('marks the muted category and pictures the mode on the bell', () => {+ mountWithBots([botRow('ses_cso', 1), row(1, 2)], { ses_cso: 1, 'session-1': 3 }, { enabled: true, bots: true, sessions: false });++ expect(screen.getAllByText('workbench.inbox.sections.muted')).toHaveLength(1);+ expect(screen.getByRole('button', { name: 'workbench.notifications.open' }).textContent).toContain('workbench.notifications.mode.bots');+ });++ it('swaps in the notification switches from the bell and back', () => {+ mountWithBots([botRow('ses_cso', 1), row(1, 2)], {});++ fireEvent.click(screen.getByRole('button', { name: 'workbench.notifications.open' }));+ expect(screen.getAllByRole('switch').map((node) => node.getAttribute('aria-label'))).toEqual([+ 'workbench.notifications.title',+ 'workbench.notifications.bots',+ 'workbench.notifications.sessions',+ ]);+ expect(rowNames()).toEqual([]);++ fireEvent.click(screen.getByRole('button', { name: 'workbench.notifications.back' }));+ expect(rowNames()).toEqual(['CSO', 'Session 1']);+ });+});diff --git a/ui/src/components/workbench/InboxHoverPopover.tsx b/ui/src/components/workbench/InboxHoverPopover.tsxnew file mode 100644index 000000000..fea250f91--- /dev/null+++ b/ui/src/components/workbench/InboxHoverPopover.tsx@@ -0,0 +1,291 @@+import { useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router-dom';+import { ArrowLeft, ArrowRight, MessageSquareReply } from 'lucide-react';+import clsx from 'clsx';++import type { InboxSession } from '../../context/ApiContext';+import { useBots } from '../../context/BotsContext';+import { useNotificationPreferences } from '../../context/NotificationPreferencesContext';+import { useBotRoster } from '../../context/BotRosterContext';+import { writeInboxFilter } from '../../lib/inboxFilterMemory';+import { inboxCategory, isCategoryLoud, type InboxCategory } from '../../lib/notificationPreferences';+import { formatRelativeTime } from '../../lib/relativeTime';+import { BotAvatar } from '../ui/bot-avatar';+import { Markdown } from '../ui/markdown';+import { PopoverContent } from '../ui/popover';+import { NotificationMenu } from './NotificationMenu';+import { useNotificationMode } from './useNotificationMode';+import { BotTag } from './bots/BotTag';+import { InboxSectionHeader } from './InboxSectionHeader';++// How many rows the peek holds: five in one list, or three per section once the+// caller has Bots. Named because two things depend on it: which rows are picked,+// and whether the peek had room it could not fill.+const PEEK_ROWS = 5;+const SECTION_ROWS = 3;++/**+ * The rows a peek shows: unread first, then the rest. `sort` is stable, so within+ * each group the feed keeps the backend's activity order untouched.+ *+ * This decides *which* rows appear, not only how they are stacked, and that is the+ * point: the popover is a short peek at a feed that is usually longer, so a+ * strictly chronological slice hides the unread conversation the user opened it to+ * act on behind ones they have already read. The full Inbox page keeps the+ * chronological order on purpose: it has unread/all tabs and keyset pagination,+ * which a client-side reorder would fight.+ */+const peek = (rows: InboxSession[], unreadBySession: Record<string, number>, limit: number) =>+ [...rows]+ .sort((a, b) => Number((unreadBySession[b.session_id] ?? 0) > 0) - Number((unreadBySession[a.session_id] ?? 0) > 0))+ .slice(0, limit);++type Section = {+ /** Absent for the single list a caller without Bots sees. */+ category?: InboxCategory;+ rows: InboxSession[];+ limit: number;+ /** Unread conversations in the whole feed, including pages not loaded. */+ unreadSessions: number;+ /** Unread replies, for the section header. */+ unread: number;+};++// 360px floating popover that opens when the user hovers the Inbox icon. Mirrors+// design.pen KmQ1L (header, a few conversation cards, an "open full inbox" link),+// split into Bots and Sessions for a caller with Bots+// (docs/plans/workbench-refinements.md §1). The bell swaps the body for the+// notification switches in place, so the hover popover never has to host a second+// floating layer. Data comes from <WorkbenchInboxProvider>.+export const InboxHoverPopover: React.FC<{+ sessions: InboxSession[];+ unreadBySession: Record<string, number>;+ unreadSessions: number;+ totalUnread: number;+ canMarkRead: boolean;+ onItemClick: (session: InboxSession) => void;+ onMarkAllRead: () => void;+ onMouseEnter: () => void;+ onMouseLeave: () => void;+ /** Close the popover: leaving for Settings must not leave it floating over the page. */+ onClose?: () => void;+}> = ({+ sessions,+ unreadBySession,+ unreadSessions,+ totalUnread,+ canMarkRead,+ onItemClick,+ onMarkAllRead,+ onMouseEnter,+ onMouseLeave,+ onClose,+}) => {+ const { t } = useTranslation();+ const navigate = useNavigate();+ const { enabled: hasBots, botForSession, displayName: botName } = useBots();+ const { preferences } = useNotificationPreferences();+ const { roster } = useBotRoster();+ const { mode, icon: BellIcon } = useNotificationMode();+ const [view, setView] = useState<'inbox' | 'notifications'>('inbox');+ // The unread map is authoritative; a session absent from it has 0 unread+ // (don't fall back to the card's stale unread_count — see InboxPage).+ const unreadOf = (s: InboxSession) => unreadBySession[s.session_id] ?? 0;++ const sections = useMemo<Section[]>(() => {+ if (!hasBots) {+ return [{ rows: peek(sessions, unreadBySession, PEEK_ROWS), limit: PEEK_ROWS, unreadSessions, unread: totalUnread }];+ }+ return (['bot', 'session'] as const).flatMap((category) => {+ const rows = sessions.filter((s) => inboxCategory(s.session_id, roster.sessionIds) === category);+ const unreadIds = Object.entries(unreadBySession)+ .filter(([id, n]) => n > 0 && inboxCategory(id, roster.sessionIds) === category);+ const unread = unreadIds.reduce((sum, [, n]) => sum + n, 0);+ // A section with nothing in it says nothing; Bots appear once one has spoken.+ if (category === 'bot' && rows.length === 0 && unread === 0) return [];+ return [{ category, rows: peek(rows, unreadBySession, SECTION_ROWS), limit: SECTION_ROWS, unreadSessions: unreadIds.length, unread }];+ });+ }, [hasBots, roster.sessionIds, sessions, unreadBySession, unreadSessions, totalUnread]);++ const openFullInbox = (filter?: 'unread') => {+ // The Inbox page resolves its tab from this store on entry, so writing it+ // first is how a caller asks for a tab without a new route or prop.+ if (filter) writeInboxFilter(filter, 0);+ navigate('/inbox');+ };++ const renderRow = (s: InboxSession, quiet: boolean, inBotSection: boolean) => {+ const unread = unreadOf(s);+ const bot = botForSession(s.session_id);+ const replied = s.replied ? (+ <MessageSquareReply className="size-3 shrink-0 text-cyan-ink" aria-label={t('workbench.inbox.replied')} />+ ) : null;+ const preview = s.preview_text ? (+ <div className={clsx('line-clamp-2 text-[11.5px] leading-relaxed', unread > 0 ? 'text-foreground' : 'text-muted')}>+ <Markdown content={s.preview_text} interactive={false} className="vr-markdown--preview" />+ </div>+ ) : null;+ // Unread stays marked in a muted category; only the mint that asks for+ // attention is withheld.+ const shell = clsx(+ 'rounded-lg px-3 py-2.5 text-left transition',+ unread > 0+ ? quiet+ ? 'border-l-2 border-border-strong bg-foreground/[0.04] hover:bg-foreground/[0.07]'+ : 'border-l-2 border-mint bg-mint/[0.06] hover:bg-mint/[0.10]'+ : 'hover:bg-foreground/[0.04]',+ );+ if (bot) {+ // A Bot's conversation reads as the Bot: its avatar and name instead of+ // "project · title" (docs/plans/bots.md D5). Inside the Bots section the+ // header already says so, which is why the row carries no Bot tag there.+ const name = botName(bot);+ return (+ <button key={s.session_id} type="button" onClick={() => onItemClick(s)} className={clsx('flex gap-2.5', shell)}>+ <BotAvatar avatar={bot.avatar} name={name} size={28} className="mt-0.5" />+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <div className="flex items-center gap-1.5 text-[11px]">+ <span className="truncate font-bold text-foreground">{name}</span>+ {!inBotSection && <BotTag />}+ <span className="flex-1" />+ {replied}+ <span className="shrink-0 font-mono text-[10px] text-muted">{formatRelativeTime(s.last_activity_at, t)}</span>+ </div>+ {preview}+ </div>+ </button>+ );+ }+ const projectLabel = s.project_name || s.project_id;+ return (+ <button key={s.session_id} type="button" onClick={() => onItemClick(s)} className={clsx('flex flex-col gap-1.5', shell)}>+ <div className="flex items-center gap-1.5 text-[10px]">+ {projectLabel && (+ <span className="truncate font-semibold text-cyan-ink after:ml-1.5 after:font-normal after:text-muted after:content-['·']">+ {projectLabel}+ </span>+ )}+ <span className="flex-1 truncate font-semibold text-foreground">{s.title?.trim() || s.session_id}</span>+ {replied}+ <span className="font-mono text-muted">{formatRelativeTime(s.last_activity_at, t)}</span>+ </div>+ {preview}+ </button>+ );+ };++ const anyRows = sections.some((section) => section.rows.length > 0);++ return (+ // Portaled (PopoverContent) so it escapes the sidebar's stacking context and+ // floats above the chat panel — a plain `absolute z-50` div was painted under+ // the chat's own stacking context, so the two visually overlapped.+ <PopoverContent+ side="right"+ align="start"+ sideOffset={12}+ data-settings-interaction-owner="true"+ onOpenAutoFocus={(e) => e.preventDefault()}+ role="dialog"+ aria-label={t('workbench.inbox.title')}+ onMouseEnter={onMouseEnter}+ onMouseLeave={onMouseLeave}+ className="flex w-[360px] flex-col gap-2.5 rounded-2xl border-border-strong bg-surface-2 p-3.5 shadow-[0_24px_64px_-12px_rgba(0,0,0,0.6)]"+ >+ {view === 'notifications' ? (+ <>+ <button+ type="button"+ onClick={() => setView('inbox')}+ className="flex items-center gap-1.5 self-start rounded-md text-[11px] font-medium text-muted hover:text-foreground"+ >+ <ArrowLeft className="size-3.5" />+ {t('workbench.notifications.back')}+ </button>+ <NotificationMenu onNavigate={onClose} />+ </>+ ) : (+ <>+ <div className="flex items-start gap-2">+ <div className="flex flex-1 flex-col">+ <div className="text-[13px] font-bold text-foreground">{t('workbench.inbox.title')}</div>+ <div className="text-[10px] text-muted">+ {t('workbench.inbox.headerCount', { unread: unreadSessions, total: sessions.length })}+ </div>+ </div>+ <button+ type="button"+ onClick={() => setView('notifications')}+ aria-label={t('workbench.notifications.open')}+ title={t('workbench.notifications.open')}+ className="inline-flex h-[22px] items-center gap-1 rounded-md border border-border-strong px-1.5 text-[10px] font-medium text-foreground transition hover:bg-foreground/[0.04]"+ >+ <BellIcon className={clsx('size-3.5', mode === 'off' && 'text-muted')} />+ {mode !== 'all' && <span>{t(`workbench.notifications.mode.${mode}`)}</span>}+ </button>+ {canMarkRead && <button+ type="button"+ onClick={onMarkAllRead}+ disabled={totalUnread === 0}+ className={clsx(+ 'rounded-md border px-2 py-1 text-[10px] font-medium transition',+ totalUnread === 0+ ? 'cursor-not-allowed border-border bg-foreground/[0.02] text-muted'+ : 'border-border-strong text-foreground hover:bg-foreground/[0.04]',+ )}+ >+ {t('workbench.inbox.markAllRead')}+ </button>}+ </div>++ {!anyRows ? (+ <div className="rounded-lg border border-dashed border-border px-3 py-6 text-center text-[12px] text-muted">+ {t('workbench.inbox.empty')}+ </div>+ ) : (+ sections.map((section, index) => {+ const quiet = section.category ? !isCategoryLoud(preferences, section.category) : false;+ // `unreadSessions` counts the whole feed; the rows hold only the pages the+ // provider has loaded, so an unread conversation older than the loaded+ // window is in the count but not in the rows, and no ordering can+ // surface it. Say so rather than letting a header that reads "3 unread"+ // sit above read rows. The condition is deliberately "the peek had room+ // and could not fill it": a peek already full of unread hides nothing+ // the header does not state.+ const unreadShown = section.rows.filter((s) => unreadOf(s) > 0).length;+ const unreadBeyondPeek = unreadShown < section.limit && section.unreadSessions > unreadShown;+ return (+ <section key={section.category ?? 'all'} className="flex flex-col gap-1">+ {index > 0 && <div className="mx-1 mb-1 h-px bg-border" />}+ {section.category && (+ <InboxSectionHeader category={section.category} unread={section.unread} quiet={quiet} className="px-1" />+ )}+ {section.rows.map((s) => renderRow(s, quiet, section.category === 'bot'))}+ {unreadBeyondPeek && (+ <button+ type="button"+ onClick={() => openFullInbox('unread')}+ className="rounded-lg border border-dashed border-border px-3 py-2 text-left text-[11px] leading-relaxed text-muted transition hover:bg-foreground/[0.04] hover:text-foreground"+ >+ {t('workbench.inbox.moreUnreadInFull')}+ </button>+ )}+ </section>+ );+ })+ )}++ <button+ type="button"+ onClick={() => openFullInbox()}+ className="flex items-center justify-center gap-1.5 rounded-md pt-1 text-[11px] font-medium text-cyan-ink hover:underline"+ >+ {t('workbench.inbox.viewAll')}+ <ArrowRight className="size-3" />+ </button>+ </>+ )}+ </PopoverContent>+ );+};diff --git a/ui/src/components/workbench/InboxPage.tsx b/ui/src/components/workbench/InboxPage.tsxindex bb9be2b9e..f9815e8a9 100644--- a/ui/src/components/workbench/InboxPage.tsx+++ b/ui/src/components/workbench/InboxPage.tsx@@ -1,17 +1,23 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { useLocation, useNavigate } from 'react-router-dom';-import { ArrowRight, CheckCheck, Filter, Inbox, Loader2, MessageSquareReply, RefreshCw, Search } from 'lucide-react';+import { ArrowRight, CheckCheck, ChevronDown, Filter, Inbox, Loader2, MessageSquareReply, RefreshCw, Search } from 'lucide-react';import clsx from 'clsx';import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';import { useBots } from '../../context/BotsContext';+import { useNotificationPreferences } from '../../context/NotificationPreferencesContext';+import { useBotRoster } from '../../context/BotRosterContext';+import { inboxCategory, isCategoryLoud, type InboxCategory } from '../../lib/notificationPreferences';import type { InboxSession } from '../../context/ApiContext';import { formatRelativeTime } from '../../lib/relativeTime';import { Markdown } from '../ui/markdown';import { Button } from '../ui/button';-import { WebPushControl } from './WebPushControl';+import { NotificationMenu } from './NotificationMenu';+import { useNotificationMode } from './useNotificationMode';+import { InboxSectionHeader } from './InboxSectionHeader';+import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';import { useInboxScrollRestoration } from './useInboxScrollRestoration';import { BotAvatar } from '../ui/bot-avatar';import { BotTag } from './bots/BotTag';@@ -28,7 +34,11 @@ export const InboxPage: React.FC<{ onOpenSearch: () => void }> = ({ onOpenSearchconst navigate = useNavigate();const location = useLocation();const listRef = useRef<HTMLDivElement>(null);- const { botForSession, displayName: botName } = useBots();+ const { enabled: hasBots, botForSession, displayName: botName } = useBots();+ const { preferences } = useNotificationPreferences();+ const { roster } = useBotRoster();+ const { mode: notification, icon: NotificationIcon } = useNotificationMode();+ const [notificationsOpen, setNotificationsOpen] = useState(false);const {capabilities,} = useInstanceAuthorization();@@ -37,6 +47,7 @@ export const InboxPage: React.FC<{ onOpenSearch: () => void }> = ({ onOpenSearchunreadBySession,totalUnread,unreadSessions,+ unreadByCategory,nextCursor,loading,loadingMore,@@ -133,6 +144,122 @@ export const InboxPage: React.FC<{ onOpenSearch: () => void }> = ({ onOpenSearchawait Promise.all(ids.map((id) => markRead(id)));};+ // One conversation card. In a muted category an unread card stays marked but+ // drops the mint that asks for attention, and its count turns grey. Inside the+ // Bots section the header already says Bot, so the card carries no Bot tag.+ const renderCard = (s: InboxSession, quiet: boolean, inBotSection: boolean) => {+ const unread = unreadOf(s);+ const projectLabel = s.project_name || s.project_id || 'avibe';+ const sessionLabel = s.title?.trim() || s.session_id;+ // A Bot's conversation reads as the Bot: avatar, name, and a small Bot+ // tag in place of "project · title" (docs/plans/bots.md D5).+ const bot = botForSession(s.session_id);+ return (+ <article+ key={s.session_id}+ data-inbox-session-id={s.session_id}+ className={clsx(+ 'flex flex-col gap-3 rounded-xl border p-4 transition',+ unread > 0+ ? quiet+ ? 'border-border-strong bg-foreground/[0.03]'+ : 'border-mint/30 bg-mint/[0.05] shadow-glow-md-mint'+ : 'border-border bg-surface',+ )}+ >+ <div className="flex items-center gap-2 text-[11px]">+ {bot ? (+ <>+ <BotAvatar avatar={bot.avatar} name={botName(bot)} size={24} />+ <span className="min-w-0 truncate text-[13px] font-semibold text-foreground">{botName(bot)}</span>+ {!inBotSection && <BotTag />}+ <span className="flex-1" />+ </>+ ) : (+ <>+ <span className="inline-flex max-w-[40%] items-center gap-1 truncate rounded-md border border-border-strong bg-surface-2 px-2 py-0.5 font-semibold text-cyan-ink">+ {projectLabel}+ </span>+ <span className="text-muted">·</span>+ <span className="flex-1 truncate text-[13px] font-semibold text-foreground">+ {sessionLabel}+ </span>+ </>+ )}+ {s.replied && (+ <span className="inline-flex items-center gap-1 rounded-md border border-cyan/30 bg-cyan/[0.08] px-1.5 py-0.5 text-[10px] font-semibold text-cyan-ink">+ <MessageSquareReply className="size-2.5" />+ {t('workbench.inbox.replied')}+ </span>+ )}+ <span className="shrink-0 font-mono text-muted">{formatRelativeTime(s.last_activity_at, t)}</span>+ </div>++ <div className="flex flex-col gap-1">+ <div className="text-[10px] font-bold uppercase tracking-wider text-mint-ink">+ {t('workbench.inbox.agent')}+ </div>+ {s.preview_text ? (+ <div+ className={clsx(+ 'line-clamp-3 text-[13px] leading-relaxed',+ unread > 0 ? 'text-foreground' : 'text-muted',+ )}+ >+ <Markdown content={s.preview_text} interactive={false} className="vr-markdown--preview" />+ </div>+ ) : (+ <p className="text-[13px] leading-relaxed text-muted">—</p>+ )}+ </div>++ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={() => openSession(s)}+ className="inline-flex items-center gap-1.5 rounded-md border border-mint/30 bg-mint/[0.06] px-3 py-1.5 text-[11px] font-semibold text-mint-ink transition hover:bg-mint/[0.12]"+ >+ {unread > 0 && (+ <span+ className={clsx(+ 'inline-flex min-w-[1.1rem] items-center justify-center rounded-full px-1.5 font-mono text-[9px] font-bold',+ quiet ? 'bg-foreground/[0.18] text-foreground' : 'bg-mint text-primary-foreground',+ )}+ >+ {unread > 99 ? '99+' : unread}+ </span>+ )}+ {t('workbench.inbox.openSession')}+ <ArrowRight className="size-3" />+ </button>+ {capabilities.can_chat && unread > 0 && (+ <button+ type="button"+ onClick={() => markRead(s.session_id)}+ className="inline-flex items-center gap-1.5 rounded-md border border-border-strong px-3 py-1.5 text-[11px] font-medium text-foreground transition hover:bg-foreground/[0.04]"+ >+ <CheckCheck className="size-3" />+ {t('workbench.inbox.markRead')}+ </button>+ )}+ </div>+ </article>+ );+ };++ // With Bots the feed splits into two sections, Bots first+ // (docs/plans/workbench-refinements.md §1); each keeps the feed's activity order.+ // A section with nothing to show is left out. Without Bots there is one list.+ const sections = useMemo<{ category?: InboxCategory; rows: InboxSession[] }[]>(() => {+ if (!hasBots) return [{ rows: visible }];+ return (['bot', 'session'] as const)+ .map((category) => ({+ category,+ rows: visible.filter((row) => inboxCategory(row.session_id, roster.sessionIds) === category),+ }))+ .filter((section) => section.rows.length > 0);+ }, [hasBots, roster.sessionIds, visible]);+const hasMore = !!nextCursor;// Only declare "all clear" when nothing is visible AND nothing left to load// could match. On the Unread tab that means no unread sessions exist anywhere@@ -216,7 +343,21 @@ export const InboxPage: React.FC<{ onOpenSearch: () => void }> = ({ onOpenSearch))}</div><div className="flex min-w-0 flex-wrap items-center gap-2 sm:ml-auto sm:justify-end">- {capabilities.can_read_instance && <WebPushControl />}+ <Popover open={notificationsOpen} onOpenChange={setNotificationsOpen}>+ <PopoverTrigger asChild>+ <button+ type="button"+ className="flex shrink-0 items-center gap-1.5 rounded-md border border-border-strong px-3 py-1.5 text-[12px] font-semibold text-foreground transition hover:bg-foreground/[0.04]"+ >+ <NotificationIcon className={clsx('size-3.5', notification === 'off' && 'text-muted')} />+ {t('workbench.notifications.button', { mode: t(`workbench.notifications.mode.${notification}`) })}+ <ChevronDown className="size-3 text-muted" />+ </button>+ </PopoverTrigger>+ <PopoverContent align="end" className="w-[320px] p-3">+ <NotificationMenu onNavigate={() => setNotificationsOpen(false)} />+ </PopoverContent>+ </Popover>{capabilities.can_chat && (<buttontype="button"@@ -256,96 +397,37 @@ export const InboxPage: React.FC<{ onOpenSearch: () => void }> = ({ onOpenSearch{t('workbench.inbox.moreUnreadBeyond')}</div>)}- {visible.map((s) => {- const unread = unreadOf(s);- const projectLabel = s.project_name || s.project_id || 'avibe';- const sessionLabel = s.title?.trim() || s.session_id;- // A Bot's conversation reads as the Bot: avatar, name, and a small Bot- // tag in place of "project · title" (docs/plans/bots.md D5).- const bot = botForSession(s.session_id);+ {sections.map((section) => {+ const quiet = section.category ? !isCategoryLoud(preferences, section.category) : false;+ const sectionUnreadIds = section.category+ ? Object.entries(unreadBySession)+ .filter(([id, n]) => n > 0 && inboxCategory(id, roster.sessionIds) === section.category)+ .map(([id]) => id)+ : [];return (- <article- key={s.session_id}- data-inbox-session-id={s.session_id}- className={clsx(- 'flex flex-col gap-3 rounded-xl border p-4 transition',- unread > 0- ? 'border-mint/30 bg-mint/[0.05] shadow-glow-md-mint'- : 'border-border bg-surface',+ <section key={section.category ?? 'all'} className="flex flex-col gap-3">+ {section.category && (+ <InboxSectionHeader+ category={section.category}+ unread={unreadByCategory[section.category]}+ quiet={quiet}+ className="px-1 pt-1"+ action={+ section.category === 'session' && capabilities.can_chat && sectionUnreadIds.length > 0 ? (+ <button+ type="button"+ onClick={() => void Promise.all(sectionUnreadIds.map((id) => markRead(id)))}+ className="inline-flex items-center gap-1 rounded-md border border-border-strong px-2 py-0.5 text-[11px] font-medium text-foreground transition hover:bg-foreground/[0.04]"+ >+ <CheckCheck className="size-3" />+ {t('workbench.inbox.sections.markRead')}+ </button>+ ) : null+ }+ />)}- >- <div className="flex items-center gap-2 text-[11px]">- {bot ? (- <>- <BotAvatar avatar={bot.avatar} name={botName(bot)} size={24} />- <span className="min-w-0 truncate text-[13px] font-semibold text-foreground">{botName(bot)}</span>- <BotTag />- <span className="flex-1" />- </>- ) : (- <>- <span className="inline-flex max-w-[40%] items-center gap-1 truncate rounded-md border border-border-strong bg-surface-2 px-2 py-0.5 font-semibold text-cyan-ink">- {projectLabel}- </span>- <span className="text-muted">·</span>- <span className="flex-1 truncate text-[13px] font-semibold text-foreground">- {sessionLabel}- </span>- </>- )}- {s.replied && (- <span className="inline-flex items-center gap-1 rounded-md border border-cyan/30 bg-cyan/[0.08] px-1.5 py-0.5 text-[10px] font-semibold text-cyan-ink">- <MessageSquareReply className="size-2.5" />- {t('workbench.inbox.replied')}- </span>- )}- <span className="shrink-0 font-mono text-muted">{formatRelativeTime(s.last_activity_at, t)}</span>- </div>-- <div className="flex flex-col gap-1">- <div className="text-[10px] font-bold uppercase tracking-wider text-mint-ink">- {t('workbench.inbox.agent')}- </div>- {s.preview_text ? (- <div- className={clsx(- 'line-clamp-3 text-[13px] leading-relaxed',- unread > 0 ? 'text-foreground' : 'text-muted',- )}- >- <Markdown content={s.preview_text} interactive={false} className="vr-markdown--preview" />- </div>- ) : (- <p className="text-[13px] leading-relaxed text-muted">—</p>- )}- </div>-- <div className="flex items-center gap-2">- <button- type="button"- onClick={() => openSession(s)}- className="inline-flex items-center gap-1.5 rounded-md border border-mint/30 bg-mint/[0.06] px-3 py-1.5 text-[11px] font-semibold text-mint-ink transition hover:bg-mint/[0.12]"- >- {unread > 0 && (- <span className="inline-flex min-w-[1.1rem] items-center justify-center rounded-full bg-mint px-1.5 font-mono text-[9px] font-bold text-primary-foreground">- {unread > 99 ? '99+' : unread}- </span>- )}- {t('workbench.inbox.openSession')}- <ArrowRight className="size-3" />- </button>- {capabilities.can_chat && unread > 0 && (- <button- type="button"- onClick={() => markRead(s.session_id)}- className="inline-flex items-center gap-1.5 rounded-md border border-border-strong px-3 py-1.5 text-[11px] font-medium text-foreground transition hover:bg-foreground/[0.04]"- >- <CheckCheck className="size-3" />- {t('workbench.inbox.markRead')}- </button>- )}- </div>- </article>+ {section.rows.map((s) => renderCard(s, quiet, section.category === 'bot'))}+ </section>);})}diff --git a/ui/src/components/workbench/InboxPageSections.test.tsx b/ui/src/components/workbench/InboxPageSections.test.tsxnew file mode 100644index 000000000..9790eeced--- /dev/null+++ b/ui/src/components/workbench/InboxPageSections.test.tsx@@ -0,0 +1,122 @@+/* @vitest-environment jsdom */++import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { MemoryRouter } from 'react-router-dom';+import type { InboxSession } from '../../context/ApiContext';+import { BotsContext, type BotsState } from '../../context/BotsContext';+import { BotRosterContext } from '../../context/BotRosterContext';+import { NotificationPreferencesContext } from '../../context/NotificationPreferencesContext';+import type { Bot } from '../../lib/bots';+import { writeInboxFilter } from '../../lib/inboxFilterMemory';+import { unreadByCategory, type NotificationPreferences } from '../../lib/notificationPreferences';+import { InboxPage } from './InboxPage';++const feed = vi.hoisted(() => ({+ inboxSessions: [] as InboxSession[],+ unreadBySession: {} as Record<string, number>,+ markRead: vi.fn(async () => true),+}));+vi.mock('../../context/WorkbenchInboxContext', () => ({+ useWorkbenchInbox: () => ({+ ...feed,+ totalUnread: Object.values(feed.unreadBySession).reduce((sum, n) => sum + n, 0),+ unreadSessions: Object.keys(feed.unreadBySession).length,+ unreadByCategory: unreadByCategory(feed.unreadBySession, new Set(['ses_cso'])),+ nextCursor: null,+ loading: false,+ loadingMore: false,+ refresh: vi.fn(),+ loadMore: vi.fn(),+ }),+}));+vi.mock('../../context/InstanceAuthorizationContext', () => ({+ useInstanceAuthorization: () => ({ capabilities: { can_chat: true, can_read_instance: false } }),+}));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: { mode?: string }) => (options?.mode ? `${key}:${options.mode}` : key),+ }),+}));+vi.mock('../ui/markdown', () => ({ Markdown: ({ content }: { content: string }) => <p>{content}</p> }));++const bots: Bot[] = [+ { handle: 'cso', display_name: 'CSO', avatar: null, role: '', agent_name: 'cso', session_id: 'ses_cso', position: 1, builtin: false },+];+const botsState = {+ enabled: true,+ bots,+ botForSession: (id: string | null | undefined) => bots.find((bot) => bot.session_id === id),+ displayName: (bot: Bot) => bot.display_name,+} as unknown as BotsState;++const row = (sessionId: string, title: string | null): InboxSession => ({+ session_id: sessionId, title, scope_id: null, project_id: 'proj_a', project_name: 'avibe',+ last_activity_at: '2026-11-01T12:00:00Z', last_message_author: 'agent', replied: false,+ preview_text: `Reply in ${sessionId}`, preview_at: null, unread_count: 0, unread: false,+});++function mount(preferences: NotificationPreferences = { enabled: true, bots: true, sessions: true }) {+ render(+ <MemoryRouter initialEntries={['/inbox']}>+ <BotRosterContext.Provider value={{ roster: { sessionIds: new Set(['ses_cso']), known: true }, publish: () => {} }}>+ <BotsContext.Provider value={botsState}>+ <NotificationPreferencesContext.Provider value={{ preferences, loaded: true, update: async () => true }}>+ <InboxPage onOpenSearch={() => {}} />+ </NotificationPreferencesContext.Provider>+ </BotsContext.Provider>+ </BotRosterContext.Provider>+ </MemoryRouter>,+ );+}++const sectionOf = (name: string) => screen.getByText(name).closest('section')!;++beforeEach(() => {+ writeInboxFilter('all', 0);+ feed.inboxSessions = [row('sesa1', 'Fix cache'), row('ses_cso', null), row('sesb2', 'Audit'), row('sesc3', 'Billing')];+ feed.unreadBySession = { ses_cso: 2, sesa1: 1, sesb2: 3 };+ feed.markRead.mockClear();+});++afterEach(() => {+ cleanup();+ window.localStorage.clear();+});++describe('Inbox page with Bots', () => {+ it('shows Bots above Sessions, each in the feed order', () => {+ mount();++ const sections = Array.from(document.querySelectorAll('section')).map((section) =>+ Array.from(section.querySelectorAll('[data-inbox-session-id]')).map((node) => node.getAttribute('data-inbox-session-id')),+ );+ expect(sections).toEqual([['ses_cso'], ['sesa1', 'sesb2', 'sesc3']]);+ // The section says Bot already; its card carries no Bot tag.+ expect(within(sectionOf('workbench.inbox.sections.bots')).queryByText('bots.tag')).toBeNull();+ });++ it('marks only the Sessions section read from its header', () => {+ mount();++ fireEvent.click(within(sectionOf('workbench.inbox.sections.sessions')).getByRole('button', { name: /workbench.inbox.sections.markRead/ }));++ expect(feed.markRead.mock.calls.map(([id]) => id).sort()).toEqual(['sesa1', 'sesb2']);+ });++ it('shows the mode on its Notifications button, mutes the quiet section, and opens the switches', () => {+ mount({ enabled: true, bots: true, sessions: false });++ expect(within(sectionOf('workbench.inbox.sections.sessions')).getByText('workbench.inbox.sections.muted')).toBeTruthy();+ expect(within(sectionOf('workbench.inbox.sections.bots')).queryByText('workbench.inbox.sections.muted')).toBeNull();++ const button = screen.getByRole('button', { name: /workbench.notifications.button/ });+ expect(button.textContent).toContain('workbench.notifications.mode.bots');+ fireEvent.click(button);+ expect(screen.getAllByRole('switch').map((node) => [node.getAttribute('aria-label'), node.getAttribute('aria-checked')])).toEqual([+ ['workbench.notifications.title', 'true'],+ ['workbench.notifications.bots', 'true'],+ ['workbench.notifications.sessions', 'false'],+ ]);+ });+});diff --git a/ui/src/components/workbench/InboxSectionHeader.tsx b/ui/src/components/workbench/InboxSectionHeader.tsxnew file mode 100644index 000000000..09276c86b--- /dev/null+++ b/ui/src/components/workbench/InboxSectionHeader.tsx@@ -0,0 +1,53 @@+import { useTranslation } from 'react-i18next';+import { BellOff } from 'lucide-react';+import clsx from 'clsx';++import type { InboxCategory } from '../../lib/notificationPreferences';++const unreadLabel = (count: number) => (count > 99 ? '99+' : String(count));++/**+ * The head of an Inbox section (docs/plans/workbench-refinements.md §1): Bots or+ * Sessions, its unread count, and a "Muted" mark when the category's+ * notifications are off. A muted count is grey: still there to find, asking for+ * nothing. Shared by the Inbox popover and the Inbox page.+ */+export function InboxSectionHeader({+ category,+ unread,+ quiet,+ action,+ className,+}: {+ category: InboxCategory;+ unread: number;+ quiet: boolean;+ action?: React.ReactNode;+ className?: string;+}) {+ const { t } = useTranslation();+ return (+ <div className={clsx('flex items-center gap-1.5', className)}>+ <span className="text-[11px] font-bold text-muted">+ {t(category === 'bot' ? 'workbench.inbox.sections.bots' : 'workbench.inbox.sections.sessions')}+ </span>+ {unread > 0 && (+ <span+ className={clsx(+ 'inline-flex h-4 min-w-4 items-center justify-center rounded-full px-1 font-mono text-[9px] font-bold',+ quiet ? 'bg-foreground/[0.18] text-foreground' : 'bg-cyan text-accent-foreground',+ )}+ >+ {unreadLabel(unread)}+ </span>+ )}+ {quiet && (+ <span className="inline-flex items-center gap-0.5 text-[10px] font-medium text-muted">+ <BellOff className="size-3" />+ {t('workbench.inbox.sections.muted')}+ </span>+ )}+ {action && <span className="ml-auto">{action}</span>}+ </div>+ );+}diff --git a/ui/src/components/workbench/NotificationMenu.tsx b/ui/src/components/workbench/NotificationMenu.tsxnew file mode 100644index 000000000..4b4a65d27--- /dev/null+++ b/ui/src/components/workbench/NotificationMenu.tsx@@ -0,0 +1,127 @@+import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router-dom';+import { ChevronRight, MessagesSquare, Settings2 } from 'lucide-react';+import clsx from 'clsx';++import { useBots } from '../../context/BotsContext';+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';+import { useNotificationPreferences } from '../../context/NotificationPreferencesContext';+import { NOTIFICATIONS_SETTINGS_PATH } from '../../lib/notificationPreferences';+import { BotAvatar } from '../ui/bot-avatar';+import { Switch } from '../ui/switch';+import { WebPushControl } from './WebPushControl';++function CategoryRow({+ icon,+ title,+ hint,+ checked,+ disabled,+ onChange,+}: {+ icon: React.ReactNode;+ title: string;+ hint: string;+ checked: boolean;+ disabled: boolean;+ onChange: (next: boolean) => void;+}) {+ return (+ <div className={clsx('flex items-center gap-2.5 px-1 py-1.5', disabled && 'opacity-50')}>+ {icon}+ <div className="min-w-0 flex-1 leading-tight">+ <div className="text-[12.5px] font-semibold text-foreground">{title}</div>+ <div className="mt-0.5 text-[10.5px] text-muted">{hint}</div>+ </div>+ <Switch size="sm" checked={checked} disabled={disabled} onCheckedChange={onChange} label={title} />+ </div>+ );+}++/**+ * The notification switches in one compact panel (docs/plans/workbench-refinements.md+ * §1): the master switch, the two categories when the caller has Bots, this+ * device's push state, and the way to the full Settings page. The Inbox page's+ * Notifications button and the Inbox popover's bell both open it.+ */+export function NotificationMenu({ onNavigate }: { onNavigate?: () => void }) {+ const { t } = useTranslation();+ const navigate = useNavigate();+ const { preferences, update } = useNotificationPreferences();+ const { enabled: hasBots, bots, displayName } = useBots();+ const { capabilities } = useInstanceAuthorization();+ const off = !preferences.enabled;++ return (+ <div className="flex w-full flex-col gap-1">+ <div className="flex items-center gap-2 px-1 pb-1">+ <div className="min-w-0 flex-1">+ <div className="text-[13px] font-bold text-foreground">{t('workbench.notifications.title')}</div>+ <div className="text-[10.5px] leading-snug text-muted">{t('workbench.notifications.description')}</div>+ </div>+ <Switch+ checked={preferences.enabled}+ onCheckedChange={(enabled) => void update({ enabled })}+ label={t('workbench.notifications.title')}+ />+ </div>+ {hasBots && (+ <>+ <div className="mx-1 h-px bg-border" />+ <CategoryRow+ icon={(+ <span className="flex shrink-0 -space-x-1.5">+ {bots.slice(0, 3).map((bot) => (+ <BotAvatar key={bot.handle} avatar={bot.avatar} name={displayName(bot)} size={18} className="ring-2 ring-surface-2" />+ ))}+ </span>+ )}+ title={t('workbench.notifications.bots')}+ hint={t('workbench.notifications.botsHint')}+ checked={preferences.bots}+ disabled={off}+ onChange={(bots) => void update({ bots })}+ />+ <CategoryRow+ icon={(+ <span className="grid size-[22px] shrink-0 place-items-center rounded-md bg-foreground/[0.06] text-muted">+ <MessagesSquare className="size-3.5" />+ </span>+ )}+ title={t('workbench.notifications.sessions')}+ hint={t('workbench.notifications.sessionsHint')}+ checked={preferences.sessions}+ disabled={off}+ onChange={(sessions) => void update({ sessions })}+ />+ {!off && !preferences.sessions && (+ <div className="mx-1 rounded-md bg-foreground/[0.04] px-2 py-1.5 text-[10.5px] leading-relaxed text-muted">+ {t('workbench.notifications.sessionsOff')}+ </div>+ )}+ </>+ )}+ {capabilities.can_read_instance && (+ <>+ <div className="mx-1 my-1 h-px bg-border" />+ <div className="flex flex-col gap-1.5 px-1">+ <span className="text-[11px] text-muted">{t('workbench.notifications.device')}</span>+ <WebPushControl />+ </div>+ </>+ )}+ <button+ type="button"+ onClick={() => {+ onNavigate?.();+ navigate(NOTIFICATIONS_SETTINGS_PATH);+ }}+ className="mt-1 flex items-center gap-1 rounded-md px-1 py-1 text-left text-[11px] font-medium text-cyan-ink hover:underline"+ >+ <Settings2 className="size-3" />+ {t('workbench.notifications.moreSettings')}+ <ChevronRight className="size-3" />+ </button>+ </div>+ );+}diff --git a/ui/src/components/workbench/WorkbenchSidebar.inbox.test.tsx b/ui/src/components/workbench/WorkbenchSidebar.inbox.test.tsxindex c35ca5828..70269a433 100644--- a/ui/src/components/workbench/WorkbenchSidebar.inbox.test.tsx+++ b/ui/src/components/workbench/WorkbenchSidebar.inbox.test.tsx@@ -10,6 +10,7 @@ import { RouteSurfaceActivityBoundary } from '../RouteSurfaceActivityBoundary';const inbox = vi.hoisted(() => ({totalUnread: 0,+ badgeTotal: 0,unreadSessions: 0,inboxSessions: [] as unknown[],unreadBySession: {} as Record<string, number>,@@ -101,6 +102,7 @@ beforeEach(() => {// Section open state is remembered per browser; every case starts from a fresh one.window.localStorage.clear();inbox.totalUnread = 0;+ inbox.badgeTotal = 0;inbox.unreadSessions = 0;inbox.inboxSessions = [];inbox.unreadBySession = {};@@ -136,6 +138,7 @@ describe('Workbench sidebar inbox counter', () => {it('shows the real unread count and colours the icon with it', () => {inbox.totalUnread = 7;+ inbox.badgeTotal = 7;inbox.unreadSessions = 3;inbox.unreadBySession = { ses_a: 4, ses_b: 3 };renderSidebar();@@ -147,11 +150,35 @@ describe('Workbench sidebar inbox counter', () => {it('caps the badge instead of widening the icon', () => {inbox.totalUnread = 150;+ inbox.badgeTotal = 150;renderSidebar();expect(screen.getByRole('link', { name: en.workbench.inbox.navUnread.replace('{{count}}', '150') }).textContent).toBe('99+');});+ it('counts only categories whose notifications are on', () => {+ // Bot replies are loud, two Session replies are muted (the provider's badgeTotal).+ inbox.totalUnread = 4;+ inbox.badgeTotal = 2;+ renderSidebar();++ const link = screen.getByRole('link', { name: en.workbench.inbox.navUnread.replace('{{count}}', '2') });+ expect(link.textContent).toBe('2');+ expect(inboxIcon().getAttribute('class')).toContain('text-cyan-ink');+ });++ it('marks muted unread with a grey dot instead of a number', () => {+ inbox.totalUnread = 5;+ inbox.badgeTotal = 0;+ renderSidebar();++ const link = screen.getByRole('link', { name: en.workbench.inbox.navQuiet });+ // Unread is there to find, but asks for nothing: no number, no cyan.+ expect(link.textContent).toBe('');+ expect(link.querySelector('span[aria-hidden="true"].rounded-full')).toBeTruthy();+ expect(inboxIcon().getAttribute('class')).toContain('text-foreground');+ });+it('keeps Search in the Projects header, before New Project and without needing it', async () => {const user = userEvent.setup();const onOpenSearch = vi.fn();diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsxindex 964bae0d1..681aa9c2d 100644--- a/ui/src/components/workbench/WorkbenchSidebar.tsx+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx@@ -5,7 +5,6 @@ import { Link, NavLink, useLocation, useNavigate } from 'react-router-dom';import {Activity,Archive,- ArrowRight,Bot,ChevronDown,ChevronRight,@@ -27,7 +26,6 @@ import {import clsx from 'clsx';import type { LucideIcon } from 'lucide-react';-import { writeInboxFilter } from '../../lib/inboxFilterMemory';import { useSidebarSectionOpen } from '../../lib/sidebarSectionsMemory';import { useRouteSurfaceActive } from '../../lib/routeSurfaceActivity';import { useLatestRef } from '../../lib/useLatestRef';@@ -46,20 +44,16 @@ import {} from './sessionRowLayout';import { SessionActionMenuContent, SessionActionsTrigger } from './sessionActions';import { useSessionActions } from './useSessionActions';-import { formatRelativeTime } from '../../lib/relativeTime';import { canCreateLocalProject } from '../../lib/sessionInfo';import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '../ui/popover';import { Button } from '../ui/button';import { Input } from '../ui/input';-import { Markdown } from '../ui/markdown';import { NewProjectDialog } from './NewProjectDialog';import { ProjectAgentsMdDialog } from './ProjectAgentsMdDialog';import { ProjectSettingsDialog } from './ProjectSettingsDialog';import { SortableProjectList, type ProjectDragHandle } from './SortableProjectList';import { BotStrip } from './bots/BotStrip';-import { BotAvatar } from '../ui/bot-avatar';-import { BotTag } from './bots/BotTag';-import { useBots } from '../../context/BotsContext';+import { InboxHoverPopover } from './InboxHoverPopover';import logoImg from '../../assets/logo.png';interface CapabilityNavItem {@@ -111,219 +105,6 @@ const SidebarNavRow: React.FC<{</NavLink>);-// How many session rows the peek holds. Named because two things depend on it:-// which rows are picked, and whether the peek had room it could not fill.-const PEEK_ROWS = 5;--// 360px floating popover that opens when the user hovers the Inbox entry.-// Mirrors design.pen KmQ1L — header + a few session cards + footer "open full-// inbox" link. Pure presentational; data comes from <WorkbenchInboxProvider>.-const InboxHoverPopover: React.FC<{- sessions: InboxSession[];- unreadBySession: Record<string, number>;- unreadSessions: number;- totalUnread: number;- canMarkRead: boolean;- onItemClick: (session: InboxSession) => void;- onMarkAllRead: () => void;- onMouseEnter: () => void;- onMouseLeave: () => void;-}> = ({- sessions,- unreadBySession,- unreadSessions,- totalUnread,- canMarkRead,- onItemClick,- onMarkAllRead,- onMouseEnter,- onMouseLeave,-}) => {- const { t } = useTranslation();- const navigate = useNavigate();- const { botForSession, displayName: botName } = useBots();- // The unread map is authoritative; a session absent from it has 0 unread- // (don't fall back to the card's stale unread_count — see InboxPage).- const unreadOf = (s: InboxSession) => unreadBySession[s.session_id] ?? 0;- // Unread first, then the rest. `sort` is stable, so within each group the feed- // keeps the backend's activity order untouched.- //- // This decides *which* five appear, not only how they are stacked — and that is- // the point. The popover is a five-row peek at a feed that is usually longer, so- // a strictly chronological slice hides the unread session the user opened it to- // act on behind ones they have already read. The full Inbox page keeps the- // chronological order on purpose: it has unread/all tabs and keyset pagination,- // which a client-side reorder would fight.- const shown = useMemo(- () =>- [...sessions]- .sort(- (a, b) =>- Number((unreadBySession[b.session_id] ?? 0) > 0) -- Number((unreadBySession[a.session_id] ?? 0) > 0),- )- .slice(0, PEEK_ROWS),- [sessions, unreadBySession],- );- // `unreadSessions` counts the whole feed; `sessions` holds only the pages the- // provider has loaded, so an unread session older than the loaded window is in- // the count but not in the rows, and no ordering of those rows can surface it.- // Say so rather than letting a header that reads "3 unread" sit above five read- // rows. The condition is deliberately "the peek had room and could not fill it":- // a peek already full of unread is hiding nothing the header does not state.- const unreadShown = shown.filter((s) => unreadOf(s) > 0).length;- const unreadBeyondPeek = unreadShown < PEEK_ROWS && unreadSessions > unreadShown;- const openFullInbox = (filter?: 'unread') => {- // The Inbox page resolves its tab from this store on entry, so writing it- // first is how a caller asks for a tab without a new route or prop.- if (filter) writeInboxFilter(filter, 0);- navigate('/inbox');- };- return (- // Portaled (PopoverContent) so it escapes the sidebar's stacking context and- // floats above the chat panel — a plain `absolute z-50` div was painted under- // the chat's own stacking context, so the two visually overlapped.- <PopoverContent- side="right"- align="start"- sideOffset={12}- data-settings-interaction-owner="true"- onOpenAutoFocus={(e) => e.preventDefault()}- role="dialog"- aria-label={t('workbench.inbox.title')}- onMouseEnter={onMouseEnter}- onMouseLeave={onMouseLeave}- className="flex w-[360px] flex-col gap-2.5 rounded-2xl border-border-strong bg-surface-2 p-3.5 shadow-[0_24px_64px_-12px_rgba(0,0,0,0.6)]"- >- <div className="flex items-start gap-2">- <div className="flex flex-1 flex-col">- <div className="text-[13px] font-bold text-foreground">{t('workbench.inbox.title')}</div>- <div className="text-[10px] text-muted">- {t('workbench.inbox.headerCount', { unread: unreadSessions, total: sessions.length })}- </div>- </div>- {canMarkRead && <button- type="button"- onClick={onMarkAllRead}- disabled={totalUnread === 0}- className={clsx(- 'rounded-md border px-2 py-1 text-[10px] font-medium transition',- totalUnread === 0- ? 'cursor-not-allowed border-border bg-foreground/[0.02] text-muted'- : 'border-border-strong text-foreground hover:bg-foreground/[0.04]',- )}- >- {t('workbench.inbox.markAllRead')}- </button>}- </div>-- {shown.length === 0 ? (- <div className="rounded-lg border border-dashed border-border px-3 py-6 text-center text-[12px] text-muted">- {t('workbench.inbox.empty')}- </div>- ) : (- <div className="flex flex-col gap-1">- {shown.map((s) => {- const unread = unreadOf(s);- const projectLabel = s.project_name || s.project_id || 'avibe';- const bot = botForSession(s.session_id);- const replied = s.replied ? (- <span className="shrink-0 font-semibold text-cyan-ink" title={t('workbench.inbox.replied')}>- ↩- </span>- ) : null;- const preview = s.preview_text ? (- <div- className={clsx(- 'line-clamp-2 text-[11.5px] leading-relaxed',- unread > 0 ? 'text-foreground' : 'text-muted',- )}- >- <Markdown content={s.preview_text} interactive={false} className="vr-markdown--preview" />- </div>- ) : (- <div className="text-[11.5px] leading-relaxed text-muted">—</div>- );- if (bot) {- // A Bot's conversation reads as the Bot: its avatar and name with a- // small Bot tag, instead of "project · title" (docs/plans/bots.md D5).- const name = botName(bot);- return (- <button- key={s.session_id}- type="button"- onClick={() => onItemClick(s)}- className={clsx(- 'flex gap-2.5 rounded-lg px-3 py-2.5 text-left transition',- unread > 0- ? 'border-l-2 border-mint bg-mint/[0.06] hover:bg-mint/[0.10]'- : 'hover:bg-foreground/[0.04]',- )}- >- <BotAvatar avatar={bot.avatar} name={name} size={28} className="mt-0.5" />- <div className="flex min-w-0 flex-1 flex-col gap-1">- <div className="flex items-center gap-1.5 text-[11px]">- <span className="truncate font-bold text-foreground">{name}</span>- <BotTag />- <span className="flex-1" />- {replied}- <span className="shrink-0 font-mono text-[10px] text-muted">{formatRelativeTime(s.last_activity_at, t)}</span>- </div>- {preview}- </div>- </button>- );- }- return (- <button- key={s.session_id}- type="button"- onClick={() => onItemClick(s)}- className={clsx(- 'flex flex-col gap-1.5 rounded-lg px-3 py-2.5 text-left transition',- unread > 0- ? 'border-l-2 border-mint bg-mint/[0.06] hover:bg-mint/[0.10]'- : 'hover:bg-foreground/[0.04]',- )}- >- <div className="flex items-center gap-1.5 text-[10px]">- <span className="truncate font-semibold text-cyan-ink">{projectLabel}</span>- <span className="text-muted">·</span>- <span className="flex-1 truncate font-semibold text-foreground">- {s.title?.trim() || s.session_id}- </span>- {replied}- <span className="font-mono text-muted">{formatRelativeTime(s.last_activity_at, t)}</span>- </div>- {preview}- </button>- );- })}- </div>- )}-- {unreadBeyondPeek && (- <button- type="button"- onClick={() => openFullInbox('unread')}- className="rounded-lg border border-dashed border-border px-3 py-2 text-left text-[11px] leading-relaxed text-muted transition hover:bg-foreground/[0.04] hover:text-foreground"- >- {t('workbench.inbox.moreUnreadInFull')}- </button>- )}-- <button- type="button"- onClick={() => openFullInbox()}- className="flex items-center justify-center gap-1.5 rounded-md pt-1 text-[11px] font-medium text-cyan-ink hover:underline"- >- {t('workbench.inbox.viewAll')}- <ArrowRight className="size-3" />- </button>- </PopoverContent>- );-};-// Session status dot colours. Maps the agent-runtime status to the user's// gray / green / red: idle → muted (gray), running → mint (green) + glow,// failed → destructive (red) + glow. Tokens resolve from src/index.css.@@ -831,7 +612,7 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOpif (to === '/vaults') return capabilities.can_use_vault_secrets;return false;});- const { totalUnread, unreadSessions, inboxSessions, markRead, unreadBySession } = useWorkbenchInbox({+ const { totalUnread, badgeTotal, unreadSessions, inboxSessions, markRead, unreadBySession } = useWorkbenchInbox({feed: surfaceActive,});// Projects/sessions tree — shared with the mobile ProjectsPage via the provider@@ -897,10 +678,14 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOpawait Promise.all(ids.map((id) => markRead(id)));};+ // The number counts only categories whose notifications are on; unread that+ // is all in muted categories shows as a grey dot instead, so it is there to+ // find but asks for nothing (docs/plans/workbench-refinements.md §1).const badge = useMemo(() => {- if (totalUnread <= 0) return null;- return totalUnread > 99 ? '99+' : String(totalUnread);- }, [totalUnread]);+ if (badgeTotal <= 0) return null;+ return badgeTotal > 99 ? '99+' : String(badgeTotal);+ }, [badgeTotal]);+ const quietUnread = !badge && totalUnread > 0;// Fill the sidebar column and cap its height so the project list (and only the// project list) scrolls; the brand row, Inbox and Capabilities stay pinned. The@@ -938,7 +723,13 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp<div className="ml-auto shrink-0" onMouseEnter={openPopover} onMouseLeave={queueClose}><NavLinkto="/inbox"- aria-label={badge ? t('workbench.inbox.navUnread', { count: totalUnread }) : t('workbench.nav.inbox')}+ aria-label={+ badge+ ? t('workbench.inbox.navUnread', { count: badgeTotal })+ : quietUnread+ ? t('workbench.inbox.navQuiet')+ : t('workbench.nav.inbox')+ }title={t('workbench.nav.inbox')}className={({ isActive }) =>clsx(@@ -956,11 +747,16 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp{/* Cyan is what unread means here, so the counter colours theicon on any route — not only while Inbox is the open one. */}<Inbox className={clsx('size-[18px]', badge || isActive ? 'text-cyan-ink' : 'text-foreground')} />- {badge && (+ {badge ? (<span className="absolute -right-1 -top-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-cyan px-1 font-mono text-[9px] font-bold text-accent-foreground shadow-glow-xs-cyan">{badge}</span>- )}+ ) : quietUnread ? (+ <span+ aria-hidden="true"+ className="absolute right-0.5 top-0.5 size-[7px] rounded-full bg-muted ring-2 ring-[var(--sidebar-background)]"+ />+ ) : null}</>)}</NavLink>@@ -976,6 +772,7 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOponMarkAllRead={onMarkAllRead}onMouseEnter={openPopover}onMouseLeave={queueClose}+ onClose={() => setPopoverOpen(false)}/></Popover></div>diff --git a/ui/src/components/workbench/useNotificationMode.ts b/ui/src/components/workbench/useNotificationMode.tsnew file mode 100644index 000000000..32f37a2ab--- /dev/null+++ b/ui/src/components/workbench/useNotificationMode.ts@@ -0,0 +1,21 @@+import { Bell, BellMinus, BellOff } from 'lucide-react';+import type { LucideIcon } from 'lucide-react';++import { useBots } from '../../context/BotsContext';+import { useNotificationPreferences } from '../../context/NotificationPreferencesContext';+import { notificationMode, type NotificationMode } from '../../lib/notificationPreferences';++const MODE_ICON: Record<NotificationMode, LucideIcon> = {+ all: Bell,+ bots: BellMinus,+ sessions: BellMinus,+ off: BellOff,+};++/** The caller's notification mode, and the bell that pictures it. */+export function useNotificationMode(): { mode: NotificationMode; icon: LucideIcon } {+ const { preferences } = useNotificationPreferences();+ const { enabled: hasBots } = useBots();+ const mode = notificationMode(preferences, hasBots);+ return { mode, icon: MODE_ICON[mode] };+}diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 4e08a0482..4cee20e38 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -6,6 +6,7 @@ import type { AgentBackendId, NativeCliBackend, WebOAuthBackend } from '../lib/aimport { apiFetch, recoverRemoteAuthFromSessionProbe, withApiDeadline } from '../lib/apiFetch';import { isAuthorizationSensitiveReadPath } from '../lib/authorizationCache';import { parseBot, type AgentBotSummary, type Bot, type BotEmojiAvatarInput } from '../lib/bots';+import { parseNotificationPreferences, type InboxCategory, type NotificationPreferences } from '../lib/notificationPreferences';import type { TurnActivityGroupWire } from '../lib/agentActivity';import type { AgentGraphParams, AgentGraphResult, AgentGraphVisibility } from '../lib/agentGraph';import { onPageReactivated, type PageReactivationListener } from '../lib/pageActivity';@@ -629,6 +630,10 @@ export type ApiContextType = {sessionId: string,payload: ShowAccessApplyRequest,) => Promise<ShowAccessApplyResult>;+ /** The caller's notification switches (docs/plans/workbench-refinements.md §1). */+ getNotificationPreferences: () => Promise<NotificationPreferences>;+ /** Writes only the switches named; the server merges them into the stored record. */+ updateNotificationPreferences: (changes: Partial<NotificationPreferences>) => Promise<NotificationPreferences>;getWebPushStatus: (payload?: WebPushStatusPayload) => Promise<WebPushStatus>;getWebPushVapidPublicKey: () => Promise<{ ok: boolean; public_key: string }>;subscribeWebPush: (@@ -1373,6 +1378,10 @@ export type WorkbenchEventHandlers = {/** The Owner's Bots changed (created, set, edited, reordered, removed): refetch* ``GET /api/bots``. ``handle`` is a hint, not a filter. */onBotsChanged?: (data: { handle?: string }) => void;+ /** This account's notification switches changed, on this device or another.+ * The server sends it only to the account's own streams; it is taken as a+ * nudge to re-read, so the read path stays the one place a record is adopted. */+ onNotificationPreferencesChanged?: () => void;onConnectionState?: (state: WorkbenchEventConnectionState) => void;onEventBridgeStatus?: (data: { connected: boolean }) => void;onAuthorizationChanged?: (data: {@@ -1630,6 +1639,8 @@ export type InboxSession = {preview_at: string | null;unread_count: number;unread: boolean;+ /** Bot conversation or ordinary Session, by the server's Bot registry. */+ category?: InboxCategory;};export type InboxFeedResult = {@@ -1638,6 +1649,12 @@ export type InboxFeedResult = {unread_by_session: Record<string, number>;unread_total: number;unread_sessions: number;+ /** ``unread_total`` split by category. The page splits its own live map the+ * same way (``lib/notificationPreferences``); these serve readers without one,+ * such as the push worker. */+ unread_by_category?: Record<InboxCategory, number>;+ /** Unread in the caller's loud categories: the worker's and the desktop app's badge. */+ badge_total?: number;};// =============================================================================@@ -3129,6 +3146,15 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenhandlers.onBotsChanged?.(envelope.data ?? {});});});+ source.addEventListener('notifications.preferences.updated', (e: MessageEvent) => {+ const envelope = parseWorkbenchEnvelope<unknown>(e.data);+ if (!envelope) return;+ clearReadCacheMatching((path) => path.startsWith('/api/notifications') || path.startsWith('/api/inbox'));+ dispatchToWorkbenchHandlers((handlers) => {+ handlers.onAny?.(envelope);+ handlers.onNotificationPreferencesChanged?.();+ });+ });source.addEventListener('remote.authorization', (e: MessageEvent) => {try {const payload = JSON.parse(e.data) as { state?: RemoteAuthorizationState };@@ -3743,6 +3769,23 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children`/api/show-pages/${encodeURIComponent(sessionId)}/access-settings/apply`,{ page_id: sessionId, ...payload },),+ getNotificationPreferences: async () => {+ const path = '/api/notifications/preferences';+ const preferences = parseNotificationPreferences(await getJson(path, { handleError: false }));+ if (!preferences) throw new ApiError(`Request failed: ${path}`, 0, null);+ return preferences;+ },+ updateNotificationPreferences: async (changes) => {+ const path = '/api/notifications/preferences';+ const { res, payloadJson } = await requestJson(path, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(changes),+ });+ const saved = res.ok ? parseNotificationPreferences(payloadJson) : null;+ if (!saved) throw new ApiError(`Request failed: ${path} (${res.status})`, res.status, null);+ return saved;+ },getWebPushStatus: (payload) =>payload ? postJson('/api/web-push/status', payload) : getJson('/api/web-push/status'),getWebPushVapidPublicKey: () => getJson('/api/web-push/vapid-public-key'),diff --git a/ui/src/context/BotRosterContext.ts b/ui/src/context/BotRosterContext.tsnew file mode 100644index 000000000..064bdbc06--- /dev/null+++ b/ui/src/context/BotRosterContext.ts@@ -0,0 +1,35 @@+import { createContext, useContext } from 'react';++/** Which Sessions are Bot conversations, for the Inbox's categories+ * (docs/plans/workbench-refinements.md §1).+ *+ * 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` lives inside the router, under the authorization it needs,+ * while the Inbox and the badges it drives live above the router. This bridge+ * carries the one fact the Inbox needs up to it. */+export type BotRoster = {+ sessionIds: ReadonlySet<string>;+ /** The list has answered, or the reader has no Bots to wait for. */+ known: boolean;+};++export const UNKNOWN_BOT_ROSTER: BotRoster = { sessionIds: new Set(), known: false };++/** Outside a `BotRosterProvider` (a test harness, a Show Page) there are no Bots. */+const NO_BOTS: BotRoster = { sessionIds: new Set(), known: true };++export interface BotRosterBridge {+ roster: BotRoster;+ publish: (roster: BotRoster) => void;+}++export const BotRosterContext = createContext<BotRosterBridge>({ roster: NO_BOTS, publish: () => undefined });++export const useBotRoster = (): BotRosterBridge => useContext(BotRosterContext);++export const sameBotRoster = (a: BotRoster, b: BotRoster): boolean =>+ a.known === b.known && a.sessionIds.size === b.sessionIds.size && [...a.sessionIds].every((id) => b.sessionIds.has(id));diff --git a/ui/src/context/BotRosterProvider.tsx b/ui/src/context/BotRosterProvider.tsxnew file mode 100644index 000000000..277e97bdb--- /dev/null+++ b/ui/src/context/BotRosterProvider.tsx@@ -0,0 +1,16 @@+import { useCallback, useMemo, useState } from 'react';+import type { ReactNode } from 'react';++import { BotRosterContext, UNKNOWN_BOT_ROSTER, sameBotRoster, type BotRoster } from './BotRosterContext';++/** Holds the roster `BotsProvider` publishes, for the providers above the router.+ * Unknown until a `BotsProvider` has answered: badges wait for it rather than+ * count a Bot's unread in the wrong category. */+export const BotRosterProvider = ({ children }: { children: ReactNode }) => {+ const [roster, setRoster] = useState<BotRoster>(UNKNOWN_BOT_ROSTER);+ const publish = useCallback((next: BotRoster) => {+ setRoster((previous) => (sameBotRoster(previous, next) ? previous : next));+ }, []);+ const value = useMemo(() => ({ roster, publish }), [roster, publish]);+ return <BotRosterContext.Provider value={value}>{children}</BotRosterContext.Provider>;+};diff --git a/ui/src/context/BotsProvider.test.tsx b/ui/src/context/BotsProvider.test.tsxindex 50bf36c0f..311a43024 100644--- a/ui/src/context/BotsProvider.test.tsx+++ b/ui/src/context/BotsProvider.test.tsx@@ -7,6 +7,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import type { WorkbenchEventHandlers } from './ApiContext';import { BotsProvider } from './BotsProvider';+import { BotRosterContext, type BotRoster } from './BotRosterContext';import { useBots } from './BotsContext';import { InstanceAuthorizationContext } from './InstanceAuthorizationContext';import { ToastContext } from './ToastContext';@@ -119,3 +120,70 @@ describe('saving a Bot from the dialog reads the Bots once', () => {expect(api.listBots.mock.calls.length - readsBefore).toBe(expectedReads);});});++// The Inbox above the router splits its counts by this list (BotRosterContext),+// the server's definition of a Bot conversation: a current Bot's Session.+describe('publishing the Bot list to the Inbox', () => {+ function mountRoster(owner: boolean) {+ const { api, stream } = fakeApi();+ apiRef.current = api;+ const published: BotRoster[] = [];+ const ids = () => [...(published.at(-1)?.sessionIds ?? [])].sort();+ const view = render(+ <BotRosterContext.Provider value={{ roster: published.at(-1) ?? { sessionIds: new Set(), known: false }, publish: (roster) => published.push(roster) }}>+ <InstanceAuthorizationContext.Provider+ value={{+ remote: false,+ instanceKind: null,+ instanceRole: null,+ capabilities: { ...DENIED_INSTANCE_CAPABILITIES, is_instance_owner: owner },+ }}+ >+ <BotsProvider>{null}</BotsProvider>+ </InstanceAuthorizationContext.Provider>+ </BotRosterContext.Provider>,+ );+ return { api, stream, published, ids, view };+ }++ it("publishes the Owner's Bot Sessions once the list answers, and drops a removed Bot's", async () => {+ const { api, stream, published, ids, view } = mountRoster(true);+ // Before the list answers, nothing is known: no Session is a Bot's yet, nor a Session's.+ expect(published[0]).toMatchObject({ known: false });+ await flush();+ expect(published.at(-1)?.known).toBe(true);+ expect(ids()).toEqual(['ses_cso', 'ses_main']);++ api.listBots.mockResolvedValueOnce([MAIN]);+ act(() => stream.handlers?.onBotsChanged?.({ handle: 'cso' }));+ await flush();+ expect(ids()).toEqual(['ses_main']);++ // Signing out unmounts the provider: the next reader's list is not known.+ view.unmount();+ expect(published.at(-1)).toMatchObject({ known: false });+ expect(published.at(-1)?.sessionIds.size).toBe(0);+ });++ it("keeps the Owner's list unknown while it cannot be read", async () => {+ const { api, stream, published, ids } = mountRoster(true);+ api.listBots.mockReset();+ api.listBots.mockRejectedValueOnce(new Error('offline')).mockResolvedValueOnce([MAIN, CSO]);+ await flush();+ // A failed read is not "no Bots": counting every Bot reply as a Session's would be wrong.+ expect(published.at(-1)).toMatchObject({ known: false });++ act(() => stream.handlers?.onConnected?.());+ await flush();+ expect(published.at(-1)?.known).toBe(true);+ expect(ids()).toEqual(['ses_cso', 'ses_main']);+ });++ it('publishes a known, empty list for a reader who is not the Owner', async () => {+ const { api, published } = mountRoster(false);+ await flush();+ expect(published.at(-1)).toMatchObject({ known: true });+ expect(published.at(-1)?.sessionIds.size).toBe(0);+ expect(api.listBots).not.toHaveBeenCalled();+ });+});diff --git a/ui/src/context/BotsProvider.tsx b/ui/src/context/BotsProvider.tsxindex 738dd185b..30706008e 100644--- a/ui/src/context/BotsProvider.tsx+++ b/ui/src/context/BotsProvider.tsx@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';import { useApi } from './ApiContext';import { BotsContext, type BotProfileRequest, type BotRuntimeStatus, type BotsState } from './BotsContext';+import { UNKNOWN_BOT_ROSTER, useBotRoster } from './BotRosterContext';import { useInstanceAuthorization } from './InstanceAuthorizationContext';import { botDisplayName, orderBots, type Bot } from '../lib/bots';@@ -22,6 +23,8 @@ export const BotsProvider = ({ children }: { children: ReactNode }) => {const enabled = capabilities.is_instance_owner === true;const [ownerBots, setBots] = useState<Bot[]>([]);const [loaded, setLoaded] = useState(false);+ // A list the server returned, as opposed to a first read that merely ended.+ const [listed, setListed] = useState(false);const [ownerStatuses, setStatusBySession] = useState<Record<string, BotRuntimeStatus>>({});const [profileRequest, setProfileRequest] = useState<BotProfileRequest | null>(null);const readRef = useRef(0);@@ -54,6 +57,7 @@ export const BotsProvider = ({ children }: { children: ReactNode }) => {const next = await api.listBots({ cache: false });if (read !== readRef.current) return;setBots(orderBots(next));+ setListed(true);const known = sessionIdsRef.current;const fresh = next.map((bot) => bot.session_id).filter((id) => !known.has(id));sessionIdsRef.current = new Set(next.map((bot) => bot.session_id));@@ -158,5 +162,16 @@ export const BotsProvider = ({ children }: { children: ReactNode }) => {};}, [enabled, ownerBots, loaded, ownerStatuses, mainDefault, afterWrite, moveBot, profileRequest]);+ // The Inbox above the router splits its counts by this list (BotRosterContext).+ // A reader who is not the Owner has none to wait for; the Owner's is known once+ // the server has returned it, since a failed read is not "no Bots".+ const { publish } = useBotRoster();+ const rosterKnown = !enabled || listed;+ useEffect(() => {+ publish({ known: rosterKnown, sessionIds: new Set(value.bots.map((bot) => bot.session_id)) });+ }, [publish, rosterKnown, value.bots]);+ // Signing out unmounts this provider; the next reader's list is not known yet.+ useEffect(() => () => publish(UNKNOWN_BOT_ROSTER), [publish]);+return <BotsContext.Provider value={value}>{children}</BotsContext.Provider>;};diff --git a/ui/src/context/NotificationPreferencesContext.ts b/ui/src/context/NotificationPreferencesContext.tsnew file mode 100644index 000000000..6c409fd7e--- /dev/null+++ b/ui/src/context/NotificationPreferencesContext.ts@@ -0,0 +1,30 @@+import { createContext, useContext } from 'react';++import { DEFAULT_NOTIFICATION_PREFERENCES, type NotificationPreferences } from '../lib/notificationPreferences';++// The caller's notification switches (docs/plans/workbench-refinements.md §1).+// `NotificationPreferencesProvider.tsx` owns the read, the stream nudge and the+// write; this module is the component-free handle consumers import.+export interface NotificationPreferencesState {+ preferences: NotificationPreferences;+ /** A record from the server is on screen. Until then the switches read as+ * all on, so nothing that counts them should overwrite a badge the push+ * worker set while the app was closed; a failed read keeps it so. */+ loaded: boolean;+ /** Apply a change at once and save only that switch; a refused save puts it+ * back. Resolves whether the server kept it. */+ update: (patch: Partial<NotificationPreferences>) => Promise<boolean>;+}++// Outside a provider there is nothing to wait for, so the default reads as loaded.+const EMPTY: NotificationPreferencesState = {+ preferences: DEFAULT_NOTIFICATION_PREFERENCES,+ loaded: true,+ update: async () => false,+};++export const NotificationPreferencesContext = createContext<NotificationPreferencesState>(EMPTY);++/** The caller's switches. Outside the provider (a Show Page, a test harness) this+ * is the all-on default, which is also what an account that never chose reads. */+export const useNotificationPreferences = (): NotificationPreferencesState => useContext(NotificationPreferencesContext);diff --git a/ui/src/context/NotificationPreferencesProvider.test.tsx b/ui/src/context/NotificationPreferencesProvider.test.tsxnew file mode 100644index 000000000..e5c64f13d--- /dev/null+++ b/ui/src/context/NotificationPreferencesProvider.test.tsx@@ -0,0 +1,209 @@+// @vitest-environment jsdom++import { act, cleanup, render } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { WorkbenchEventHandlers } from './ApiContext';+import { useNotificationPreferences, type NotificationPreferencesState } from './NotificationPreferencesContext';+import { NotificationPreferencesProvider } from './NotificationPreferencesProvider';+import type { NotificationPreferences } from '../lib/notificationPreferences';++const apiRef = vi.hoisted(() => ({ current: null as unknown }));+vi.mock('./ApiContext', async () => {+ const actual = await vi.importActual<typeof import('./ApiContext')>('./ApiContext');+ return { ...actual, useApi: () => apiRef.current };+});++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (reason?: unknown) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, resolve, reject };+}++const settle = () => act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+});++function mount(api: {+ getNotificationPreferences: () => Promise<NotificationPreferences>;+ updateNotificationPreferences?: (changes: Partial<NotificationPreferences>) => Promise<NotificationPreferences>;+}) {+ const handlers: WorkbenchEventHandlers[] = [];+ apiRef.current = {+ updateNotificationPreferences: async (changes: Partial<NotificationPreferences>) => ({ ...ON, ...changes }),+ ...api,+ connectWorkbenchEvents: (next: WorkbenchEventHandlers) => {+ handlers.push(next);+ return () => undefined;+ },+ };+ const state = { current: null as NotificationPreferencesState | null };+ const Probe = () => {+ state.current = useNotificationPreferences();+ return null;+ };+ render(<NotificationPreferencesProvider><Probe /></NotificationPreferencesProvider>);+ return { state, handlers };+}++const ON = { enabled: true, bots: true, sessions: true };+const SESSIONS_MUTED = { enabled: true, bots: true, sessions: false };++afterEach(() => cleanup());++describe('NotificationPreferencesProvider', () => {+ it('reads the account record, and re-reads it when the stream says it changed', async () => {+ const getNotificationPreferences = vi.fn()+ .mockResolvedValueOnce(ON)+ .mockResolvedValueOnce(SESSIONS_MUTED);+ const { state, handlers } = mount({ getNotificationPreferences });+ expect(state.current?.loaded).toBe(false);+ await settle();+ expect(state.current).toMatchObject({ preferences: ON, loaded: true });++ // Another device changed a switch: the read path adopts the record.+ await act(async () => handlers[0].onNotificationPreferencesChanged?.());+ await settle();+ expect(getNotificationPreferences).toHaveBeenCalledTimes(2);+ expect(state.current?.preferences).toEqual(SESSIONS_MUTED);+ });++ it('stays unknown while the record cannot be read, so the badges keep their number', async () => {+ const getNotificationPreferences = vi.fn()+ .mockRejectedValueOnce(new Error('offline'))+ .mockResolvedValueOnce(SESSIONS_MUTED);+ const { state, handlers } = mount({ getNotificationPreferences });+ await settle();+ // All-on defaults are not the account's switches.+ expect(state.current).toMatchObject({ preferences: ON, loaded: false });++ await act(async () => handlers[0].onConnected?.());+ await settle();+ expect(state.current).toMatchObject({ preferences: SESSIONS_MUTED, loaded: true });+ });++ it('applies a change at once and puts the saved record back when the save is refused', async () => {+ const save = deferred<NotificationPreferences>();+ const { state } = mount({+ getNotificationPreferences: async () => ON,+ updateNotificationPreferences: () => save.promise,+ });+ await settle();++ let kept: boolean | undefined;+ await act(async () => {+ void state.current!.update({ sessions: false }).then((result) => { kept = result; });+ });+ expect(state.current?.preferences).toEqual(SESSIONS_MUTED);++ await act(async () => save.reject(new Error('refused')));+ await settle();+ expect(kept).toBe(false);+ expect(state.current?.preferences).toEqual(ON);+ });++ it('sends only the switch a change names, and shows a second quick change on top of the first', async () => {+ // The server merges each write into the stored record, as the real route does.+ let stored = ON;+ const saves: Partial<NotificationPreferences>[] = [];+ const { state } = mount({+ getNotificationPreferences: async () => stored,+ updateNotificationPreferences: async (changes) => {+ saves.push(changes);+ stored = { ...stored, ...changes };+ return stored;+ },+ });+ await settle();++ await act(async () => {+ void state.current!.update({ sessions: false });+ void state.current!.update({ enabled: false });+ });+ await settle();++ // A whole record would carry this device's stale copy of the other switches+ // over a change another device made to them in the meantime.+ expect(saves).toEqual([{ sessions: false }, { enabled: false }]);+ expect(state.current?.preferences).toEqual({ enabled: false, bots: true, sessions: false });+ });++ it('keeps switches that overlapping saves confirmed when a later save is refused', async () => {+ // The server applies Sessions, then Bots; their answers arrive the other way round.+ const sessionsSave = deferred<NotificationPreferences>();+ const botsSave = deferred<NotificationPreferences>();+ const masterSave = deferred<NotificationPreferences>();+ const saves = [sessionsSave, botsSave, masterSave];+ const getNotificationPreferences = vi.fn()+ .mockResolvedValueOnce(ON)+ // No stream and no reads to fall back on from here: only this page's own record.+ .mockRejectedValue(new Error('offline'));+ const { state } = mount({+ getNotificationPreferences,+ updateNotificationPreferences: () => saves.shift()!.promise,+ });+ await settle();++ await act(async () => {+ void state.current!.update({ sessions: false });+ void state.current!.update({ bots: false });+ });+ await act(async () => botsSave.resolve({ enabled: true, bots: false, sessions: false }));+ await act(async () => sessionsSave.resolve({ enabled: true, bots: true, sessions: false }));+ await settle();+ expect(state.current?.preferences).toEqual({ enabled: true, bots: false, sessions: false });++ await act(async () => { void state.current!.update({ enabled: false }); });+ await act(async () => masterSave.reject(new Error('refused')));+ await settle();+ // The refused save undoes its own switch and nothing else.+ expect(state.current?.preferences).toEqual({ enabled: true, bots: false, sessions: false });+ });++ it('leaves a switch a later change has set since when an earlier change is refused', async () => {+ const first = deferred<NotificationPreferences>();+ const second = deferred<NotificationPreferences>();+ const saves = [first, second];+ const { state } = mount({+ getNotificationPreferences: vi.fn().mockResolvedValueOnce(ON).mockRejectedValue(new Error('offline')),+ updateNotificationPreferences: () => saves.shift()!.promise,+ });+ await settle();++ await act(async () => {+ void state.current!.update({ bots: false });+ void state.current!.update({ bots: false, sessions: false });+ });+ // The second change still wants Bots off: refusing the first must not turn them back on.+ await act(async () => first.reject(new Error('refused')));+ await settle();+ expect(state.current?.preferences).toEqual({ enabled: true, bots: false, sessions: false });++ await act(async () => second.resolve({ enabled: true, bots: false, sessions: false }));+ await settle();+ expect(state.current?.preferences).toEqual({ enabled: true, bots: false, sessions: false });+ });++ it('keeps an in-flight read from putting the old switches back over a change', async () => {+ const slowRead = deferred<NotificationPreferences>();+ const getNotificationPreferences = vi.fn()+ .mockResolvedValueOnce(ON)+ .mockReturnValueOnce(slowRead.promise);+ const { state, handlers } = mount({ getNotificationPreferences });+ await settle();++ await act(async () => handlers[0].onConnected?.());+ await act(async () => { void state.current!.update({ sessions: false }); });+ await settle();+ await act(async () => slowRead.resolve(ON));+ await settle();++ expect(state.current?.preferences).toEqual(SESSIONS_MUTED);+ });+});diff --git a/ui/src/context/NotificationPreferencesProvider.tsx b/ui/src/context/NotificationPreferencesProvider.tsxnew file mode 100644index 000000000..93660197b--- /dev/null+++ b/ui/src/context/NotificationPreferencesProvider.tsx@@ -0,0 +1,119 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import type { ReactNode } from 'react';++import { useApi } from './ApiContext';+import { NotificationPreferencesContext, type NotificationPreferencesState } from './NotificationPreferencesContext';+import { DEFAULT_NOTIFICATION_PREFERENCES, type NotificationPreferences } from '../lib/notificationPreferences';++/** Owns the caller's notification switches (`/api/notifications/preferences`).+ *+ * Read on mount and re-read whenever the stream says this account's switches+ * changed (on any of its devices), reconnects, or authorization moves: the+ * broker replays nothing, and re-reading keeps one path that adopts a record.+ *+ * A change shows at once and sends only the switch it changes, which the server+ * merges, so two devices changing different switches keep both. Responses to+ * overlapping writes cannot say which one the server applied last, so none of+ * them is adopted whole: each confirms only the switches it wrote. A refused+ * write puts its switches back to their last confirmed value, unless a later+ * change has set them since, and once the last write of a burst settles the+ * record is read back (a lone write's response is that read). Every read+ * started before a write is fenced, so a slow read cannot put the old switches+ * back. */+export const NotificationPreferencesProvider = ({ children }: { children: ReactNode }) => {+ const api = useApi();+ const [preferences, setPreferences] = useState<NotificationPreferences>(DEFAULT_NOTIFICATION_PREFERENCES);+ const [loaded, setLoaded] = useState(false);+ // The switches on screen, which the next change builds on (two quick toggles+ // must not lose the first while its save is in flight).+ const shownRef = useRef<NotificationPreferences>(DEFAULT_NOTIFICATION_PREFERENCES);+ const generationRef = useRef(0);+ // Writes in flight and writes since the last quiet moment; which change last+ // set each switch (a refused write may only undo a switch it still owns); and+ // each switch's last value the server confirmed, with the change that did.+ const pendingWritesRef = useRef(0);+ const burstWritesRef = useRef(0);+ const switchOwnerRef = useRef<Partial<Record<keyof NotificationPreferences, number>>>({});+ const confirmedRef = useRef<NotificationPreferences>(DEFAULT_NOTIFICATION_PREFERENCES);+ const confirmedByRef = useRef<Partial<Record<keyof NotificationPreferences, number>>>({});+ const confirm = useCallback((values: Partial<NotificationPreferences>, generation: number) => {+ for (const key of Object.keys(values) as (keyof NotificationPreferences)[]) {+ if ((confirmedByRef.current[key] ?? 0) > generation) continue;+ confirmedByRef.current[key] = generation;+ confirmedRef.current = { ...confirmedRef.current, [key]: values[key] };+ }+ }, []);+ const show = useCallback((next: NotificationPreferences) => {+ shownRef.current = next;+ setPreferences(next);+ }, []);++ const read = useCallback(async () => {+ const generation = ++generationRef.current;+ try {+ const next = await api.getNotificationPreferences();+ if (generation !== generationRef.current) return;+ confirm(next, generation);+ show(next);+ setLoaded(true);+ } catch {+ // Unreadable is not "all off": keep what we have, and stay unknown until a+ // record arrives, so the badges keep the number the push worker set.+ }+ }, [api, confirm, show]);++ useEffect(() => {+ // The first read does not wait for the stream: one that never connects must+ // not leave the switches unread.+ queueMicrotask(() => void read());+ return api.connectWorkbenchEvents({+ onConnected: () => void read(),+ onNotificationPreferencesChanged: () => void read(),+ onAuthorizationChanged: () => void read(),+ });+ }, [api, read]);++ const update = useCallback(+ async (patch: Partial<NotificationPreferences>) => {+ const generation = ++generationRef.current;+ const changed = Object.keys(patch) as (keyof NotificationPreferences)[];+ for (const key of changed) switchOwnerRef.current[key] = generation;+ pendingWritesRef.current += 1;+ burstWritesRef.current += 1;+ show({ ...shownRef.current, ...patch });+ let saved: NotificationPreferences | null = null;+ try {+ saved = await api.updateNotificationPreferences(patch);+ confirm(patch, generation);+ } catch {+ const undo = Object.fromEntries(+ changed+ .filter((key) => switchOwnerRef.current[key] === generation)+ .map((key) => [key, confirmedRef.current[key]]),+ );+ show({ ...shownRef.current, ...undo });+ }+ pendingWritesRef.current -= 1;+ if (pendingWritesRef.current === 0) {+ const alone = burstWritesRef.current === 1;+ burstWritesRef.current = 0;+ if (alone && saved && generation === generationRef.current) {+ confirm(saved, generation);+ show(saved);+ setLoaded(true);+ } else {+ void read();+ }+ }+ return saved !== null;+ },+ [api, confirm, read, show],+ );++ const value = useMemo<NotificationPreferencesState>(+ () => ({ preferences, loaded, update }),+ [preferences, loaded, update],+ );++ return <NotificationPreferencesContext.Provider value={value}>{children}</NotificationPreferencesContext.Provider>;+};diff --git a/ui/src/context/WorkbenchInboxContext.ts b/ui/src/context/WorkbenchInboxContext.tsindex 60a9c09c5..9c170c0ae 100644--- a/ui/src/context/WorkbenchInboxContext.ts+++ b/ui/src/context/WorkbenchInboxContext.ts@@ -1,6 +1,7 @@import { createContext, useContext, useEffect } from 'react';import type { InboxSession } from './ApiContext';+import type { UnreadByCategory } from '../lib/notificationPreferences';// The Inbox state contract and the context handle every consumer reads.// `WorkbenchInboxProvider.tsx` owns the feed, the SSE subscription and the@@ -20,6 +21,12 @@ export interface InboxState {totalUnread: number;/** Number of sessions with ≥1 unread reply — the header "N unread" count. */unreadSessions: number;+ /** ``totalUnread`` split into Bot conversations and ordinary Sessions. */+ unreadByCategory: UnreadByCategory;+ /** The aggregate badge: unread in categories whose notifications are on+ * (docs/plans/workbench-refinements.md §1). The sidebar icon, the app icon and+ * the tab favicon all show this; with every switch on it is ``totalUnread``. */+ badgeTotal: number;/** Keyset cursor for "load more"; null when the feed is fully loaded. */nextCursor: string | null;loading: boolean;diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsxindex b7836fabc..199f65ed4 100644--- a/ui/src/context/WorkbenchInboxProvider.tsx+++ b/ui/src/context/WorkbenchInboxProvider.tsx@@ -4,6 +4,9 @@ import type { ReactNode } from 'react';import { useApi } from './ApiContext';import type { InboxSession } from './ApiContext';import { WorkbenchInboxContext, type InboxState } from './WorkbenchInboxContext';+import { useNotificationPreferences } from './NotificationPreferencesContext';+import { useBotRoster } from './BotRosterContext';+import { badgeTotal as loudUnread, unreadByCategory as splitUnread } from '../lib/notificationPreferences';import { sessionActivityInboxAction } from '../lib/inboxActivity';import { syncFaviconBadge } from '../lib/faviconBadge';import { useConsumerActivation } from '../lib/useConsumerActivation';@@ -939,16 +942,28 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>() => Object.values(unreadBySession).filter((n) => (n || 0) > 0).length,[unreadBySession],);+ // The badges outside the app count only categories whose notifications are on.+ // They wait for the switches and the Bot list as they wait for the map: before+ // all three are known, a badge the push worker set while the app was closed is+ // the better number.+ const { preferences, loaded: preferencesLoaded } = useNotificationPreferences();+ const { roster } = useBotRoster();+ const unreadByCategory = useMemo(+ () => splitUnread(unreadBySession, roster.sessionIds),+ [unreadBySession, roster.sessionIds],+ );+ const badgeTotal = useMemo(() => loudUnread(unreadByCategory, preferences), [unreadByCategory, preferences]);+ const badgeKnown = unreadLoaded && preferencesLoaded && roster.known;- // Mirror the unread total onto the installed PWA's home-screen icon badge so+ // Mirror the badge total onto the installed PWA's home-screen icon badge so// the icon matches the in-app Inbox badge. The push service worker (push-sw.js)// sets this while the app is closed; this keeps it live while the app is open —// reading clears it, a new reply bumps it. Best-effort + feature-detected:// browsers without the Badging API (and non-installed tabs) simply no-op, and a// rejected badge promise is swallowed so it never surfaces as an app error.//- // Gated on ``unreadLoaded``: until the first authoritative unread map arrives,- // ``totalUnread`` is just the default 0, and clearing here would wipe a badge+ // Gated on ``badgeKnown``: until the first authoritative unread map arrives,+ // ``badgeTotal`` is just the default 0, and clearing here would wipe a badge// the service worker set while the app was closed if that initial load is slow,// fails, or redirects on an expired session. Once loaded, a real 0 clears it.// A fresh authoritative map reasserts the badge even when its numeric sum@@ -959,8 +974,8 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>clearAppBadge?: () => Promise<void>;};if (!('setAppBadge' in nav)) return;- if (!unreadLoaded) return;- const op = totalUnread > 0 ? nav.setAppBadge?.(totalUnread) : nav.clearAppBadge?.();+ if (!badgeKnown) return;+ const op = badgeTotal > 0 ? nav.setAppBadge?.(badgeTotal) : nav.clearAppBadge?.();void op?.catch?.(() => {});// Fence a background worker read that started before this authoritative// map arrived. The worker serializes its own setter after this message, so@@ -968,12 +983,12 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>try {navigator.serviceWorker?.controller?.postMessage({type: 'vibe.app-badge-current',- count: totalUnread,+ count: badgeTotal,});} catch {// The direct badge write above still works without a controlling worker.}- }, [unreadBySession, totalUnread, unreadLoaded]);+ }, [unreadBySession, badgeTotal, badgeKnown]);// A worker can finish a background badge write after this page's last// unread update. Revalidate on its completion signal and whenever the page@@ -994,9 +1009,9 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>// Browser tabs have no Badging API. Keep their favicon useful while the// Inbox map is authoritative, and restore the original icon after reading.useEffect(() => {- if (!unreadLoaded) return;- syncFaviconBadge(totalUnread);- }, [totalUnread, unreadLoaded]);+ if (!badgeKnown) return;+ syncFaviconBadge(badgeTotal);+ }, [badgeTotal, badgeKnown]);const value = useMemo<InboxState>(() => ({@@ -1005,6 +1020,8 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>unreadLoaded,totalUnread,unreadSessions,+ unreadByCategory,+ badgeTotal,nextCursor,loading,loadingMore,@@ -1020,6 +1037,8 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>unreadLoaded,totalUnread,unreadSessions,+ unreadByCategory,+ badgeTotal,nextCursor,loading,loadingMore,diff --git a/ui/src/context/shellBootstrapDemand.test.tsx b/ui/src/context/shellBootstrapDemand.test.tsxindex 4ab2bc5e4..066e3820a 100644--- a/ui/src/context/shellBootstrapDemand.test.tsx+++ b/ui/src/context/shellBootstrapDemand.test.tsx@@ -22,6 +22,8 @@ import {type WorkbenchProjectsTree,} from './WorkbenchProjectsContext';import type { WorkbenchEventHandlers } from './ApiContext';+import { NotificationPreferencesContext, type NotificationPreferencesState } from './NotificationPreferencesContext';+import { BotRosterContext, UNKNOWN_BOT_ROSTER, type BotRoster } from './BotRosterContext';const project = {id: 'proj_a',@@ -818,6 +820,65 @@ describe('Demand-driven shell bootstrap', () => {}});+ it('badges only categories whose notifications are on, once the switches and the Bot list are known', async () => {+ const originalSetBadge = Object.getOwnPropertyDescriptor(navigator, 'setAppBadge');+ const originalClearBadge = Object.getOwnPropertyDescriptor(navigator, 'clearAppBadge');+ const setAppBadge = vi.fn(async () => {});+ const clearAppBadge = vi.fn(async () => {});+ Object.defineProperty(navigator, 'setAppBadge', { configurable: true, value: setAppBadge });+ 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.+ const listInbox = vi.fn(async (_args: ListInboxArgs) => ({+ sessions: [],+ next_cursor: null,+ unread_by_session: { ses_cso: 2, sesa1b2c3d4e5: 5, ses_retired: 3 },+ }));+ apiRef.current = { listInbox, connectWorkbenchEvents: vi.fn(() => vi.fn()) };+ const roster: BotRoster = { sessionIds: new Set(['ses_main', 'ses_cso']), known: true };+ const tree = (preferences: NotificationPreferencesState, bots: BotRoster = roster) => (+ <BotRosterContext.Provider value={{ roster: bots, publish: () => {} }}>+ <NotificationPreferencesContext.Provider value={preferences}>+ <WorkbenchInboxProvider>+ <InboxProbe feed={false} onState={(state) => { latest = state; }} />+ </WorkbenchInboxProvider>+ </NotificationPreferencesContext.Provider>+ </BotRosterContext.Provider>+ );+ let latest: InboxState | null = null;+ const sessionsMuted = { enabled: true, bots: true, sessions: false };+ const view = render(tree({ preferences: sessionsMuted, loaded: false, update: async () => true }));+ await settle();+ // The map is in, the switches are not: a badge the push worker set while+ // the app was closed is the better number, so nothing is written yet.+ expect(setAppBadge).not.toHaveBeenCalled();+ expect(clearAppBadge).not.toHaveBeenCalled();++ // The switches are in, the Bot list is not: which unread is a Bot's is unknown.+ view.rerender(tree({ preferences: sessionsMuted, loaded: true, update: async () => true }, UNKNOWN_BOT_ROSTER));+ await settle();+ expect(setAppBadge).not.toHaveBeenCalled();+ expect(clearAppBadge).not.toHaveBeenCalled();++ view.rerender(tree({ preferences: sessionsMuted, loaded: true, update: async () => true }));+ await settle();+ expect(setAppBadge).toHaveBeenLastCalledWith(2);+ expect(latest).toMatchObject({ totalUnread: 10, badgeTotal: 2, unreadByCategory: { bot: 2, session: 8 } });++ view.rerender(tree({ preferences: { ...sessionsMuted, enabled: false }, loaded: true, update: async () => true }));+ await settle();+ expect(clearAppBadge).toHaveBeenCalledOnce();+ } finally {+ cleanup();+ if (originalSetBadge) Object.defineProperty(navigator, 'setAppBadge', originalSetBadge);+ else Reflect.deleteProperty(navigator, 'setAppBadge');+ if (originalClearBadge) Object.defineProperty(navigator, 'clearAppBadge', originalClearBadge);+ else Reflect.deleteProperty(navigator, 'clearAppBadge');+ }+ });+it('reads the counts a dropped feed read was carrying', async () => {const feedRead = deferred<typeof inboxPayload>();const countsOnly = {diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 1f1594373..452cb5698 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -436,6 +436,7 @@},"sections": {"general": "General",+ "notifications": "Notifications","backends": "Backends","models": "Models","replies": "Replies",@@ -2762,6 +2763,17 @@"explain": "This Source refused this reasoning effort, so requests at it skip this Source."}}+ },+ "notifications": {+ "subtitle": "Choose which messages are pushed to your devices and counted in app badges. Every message still arrives in the Inbox. These switches follow your account on every device.",+ "masterHint": "Turn off to stop every push; badges stop showing numbers.",+ "botsHint": "Replies from your Bots.",+ "sessionsHint": "Replies and failure notices from project Sessions. Turn this off when you only follow your Bots: Sessions keep working and keep arriving in the Inbox, just quietly.",+ "deviceTitle": "This device",+ "pushTitle": "Push (browser or Home Screen app)",+ "pushHint": "Whether this browser receives pushes at all.",+ "desktopTitle": "Desktop app notifications",+ "desktopHint": "Vault approvals and finished background runs. Switch them for this computer from the menu bar icon › Notifications."}},"remoteAccess": {@@ -3552,7 +3564,14 @@"testFailed": "Test notification failed","normalBlocked": "normal notifications are currently skipped for you ({{policy}} policy: {{disposition}})"},- "navUnread": "Inbox, {{count}} unread"+ "navUnread": "Inbox, {{count}} unread",+ "sections": {+ "bots": "Bots",+ "sessions": "Sessions",+ "muted": "Muted",+ "markRead": "Mark section read"+ },+ "navQuiet": "Inbox, unread with notifications off"},"modules": {"comingSoonEyebrow": "Coming soon",@@ -3582,6 +3601,26 @@"title": "Vaults","description": "Secrets and API keys that the Agent can pull into ENV / .env without you copy-pasting."}+ },+ "notifications": {+ "title": "Notifications",+ "description": "Pushed to devices with notifications on, and counted in app badges.",+ "bots": "Bot messages",+ "botsHint": "Replies from your Bots",+ "sessions": "Session messages",+ "sessionsHint": "Replies and failure notices from project Sessions",+ "sessionsOff": "Session messages still arrive in the Inbox; they are not pushed or counted in badges.",+ "device": "This device",+ "moreSettings": "More notification settings",+ "back": "Back to Inbox",+ "open": "Notification settings",+ "button": "Notifications: {{mode}}",+ "mode": {+ "all": "All",+ "bots": "Bots only",+ "sessions": "Sessions only",+ "off": "Off"+ }}},"wizard": {diff --git a/ui/src/i18n/keyCoverage.test.ts b/ui/src/i18n/keyCoverage.test.tsindex 479543ccf..e20a610a2 100644--- a/ui/src/i18n/keyCoverage.test.ts+++ b/ui/src/i18n/keyCoverage.test.ts@@ -852,6 +852,7 @@ const NON_KEY_LITERALS = ['inbox.unread.changed','message.new','message.updated',+ 'notifications.preferences.updated','projects.changed','queue.updated','remote.authorization',diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 6c10ae0df..b0b6b00e9 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -436,6 +436,7 @@},"sections": {"general": "常规",+ "notifications": "通知","backends": "后端","models": "模型","replies": "回复",@@ -2762,6 +2763,17 @@"explain": "此供应商拒绝过这个推理强度,之后的请求会跳过它。"}}+ },+ "notifications": {+ "subtitle": "决定哪些消息会推送到你的设备、计入应用图标角标。所有消息都会照常进入收件箱。这些开关跟随账号,在每台设备上生效。",+ "masterHint": "总开关。关闭后不推送任何消息,角标也不再显示数字。",+ "botsHint": "伙伴的回复。",+ "sessionsHint": "项目里普通会话的回复和失败提醒。只关心伙伴时把它关掉:会话照常工作、照常进收件箱,只是安静。",+ "deviceTitle": "本设备",+ "pushTitle": "推送(浏览器 / 主屏幕 App)",+ "pushHint": "这台设备是否接收推送。",+ "desktopTitle": "桌面 App 系统通知",+ "desktopHint": "Vault 审批和后台任务完成。本机的开关在菜单栏图标 › 通知。"}},"remoteAccess": {@@ -3552,7 +3564,14 @@"testFailed": "测试通知发送失败","normalBlocked": "但普通通知当前会跳过你({{policy}} 策略:{{disposition}})"},- "navUnread": "收件箱,{{count}} 条未读"+ "navUnread": "收件箱,{{count}} 条未读",+ "sections": {+ "bots": "伙伴",+ "sessions": "会话",+ "muted": "免打扰",+ "markRead": "本组全部已读"+ },+ "navQuiet": "收件箱:有未读,通知已关闭"},"modules": {"comingSoonEyebrow": "即将就位",@@ -3582,6 +3601,26 @@"title": "Vaults","description": "secrets 和 API key,Agent 可以直接写进 ENV / .env,不用你复制粘贴。"}+ },+ "notifications": {+ "title": "通知",+ "description": "推送到开启了通知的设备,并计入应用角标。",+ "bots": "伙伴消息",+ "botsHint": "伙伴的回复",+ "sessions": "会话消息",+ "sessionsHint": "项目里普通会话的回复和失败提醒",+ "sessionsOff": "会话消息照常进收件箱,只是不推送、不计入角标。",+ "device": "本设备",+ "moreSettings": "更多通知设置",+ "back": "回到收件箱",+ "open": "通知设置",+ "button": "通知:{{mode}}",+ "mode": {+ "all": "全部",+ "bots": "仅伙伴",+ "sessions": "仅会话",+ "off": "已关闭"+ }}},"wizard": {diff --git a/ui/src/lib/applicationRoutes.ts b/ui/src/lib/applicationRoutes.tsindex 2de5888e7..5e1dea86d 100644--- a/ui/src/lib/applicationRoutes.ts+++ b/ui/src/lib/applicationRoutes.ts@@ -48,6 +48,7 @@ export const APPLICATION_ROUTE_PATHS = ['/logs','/settings','/settings/general',+ '/settings/notifications','/settings/memory','/settings/appearance','/settings/account',diff --git a/ui/src/lib/notificationBadge.fixture.json b/ui/src/lib/notificationBadge.fixture.jsonnew file mode 100644index 000000000..6f15d9d54--- /dev/null+++ b/ui/src/lib/notificationBadge.fixture.json@@ -0,0 +1,47 @@+{+ "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).",+ "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",+ "bot_session_ids": ["ses_main", "ses_cso"],+ "preferences": { "enabled": true, "bots": true, "sessions": true },+ "unread_by_category": { "bot": 3, "session": 12 },+ "badge_total": 15+ },+ {+ "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 },+ "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+ },+ {+ "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 },+ "badge_total": 0+ },+ {+ "name": "A reader without Bots: everything is a Session",+ "bot_session_ids": [],+ "preferences": { "enabled": true, "bots": true, "sessions": false },+ "unread_by_category": { "bot": 0, "session": 15 },+ "badge_total": 0+ }+ ]+}diff --git a/ui/src/lib/notificationPreferences.test.ts b/ui/src/lib/notificationPreferences.test.tsnew file mode 100644index 000000000..b226ec913--- /dev/null+++ b/ui/src/lib/notificationPreferences.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest';++import {+ DEFAULT_NOTIFICATION_PREFERENCES,+ badgeTotal,+ notificationMode,+ parseNotificationPreferences,+ unreadByCategory,+} from './notificationPreferences';+import badgeFixture from './notificationBadge.fixture.json';++const ALL_ON = DEFAULT_NOTIFICATION_PREFERENCES;+const BOTS_ONLY = { enabled: true, bots: true, sessions: false };+const SESSIONS_ONLY = { enabled: true, bots: false, sessions: true };+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 };+ const counts = unreadByCategory(unread, new Set(['ses_main', 'ses_cso']));++ it("splits unread by the live Bot list, not by the id's prefix", () => {+ expect(counts).toEqual({ bot: 2, session: 9 });+ });++ // The same fixture runs against the server's split_unread_counts and badge_total+ // (tests/test_notification_badge_parity.py), so the sidebar number and the app+ // icon or Dock badge the server computes cannot follow different rules.+ it.each(badgeFixture.cases)('computes the server\'s badge_total from the same data ($name)', (fixture) => {+ const split = unreadByCategory(badgeFixture.unread_by_session, new Set(fixture.bot_session_ids));+ expect(split).toEqual(fixture.unread_by_category);+ expect(badgeTotal(split, fixture.preferences)).toBe(fixture.badge_total);+ });++ it.each([+ ['every switch on: the whole total, as before', ALL_ON, 11],+ ['Bots only', BOTS_ONLY, 2],+ ['Sessions only', SESSIONS_ONLY, 9],+ ['master off, whatever the categories say', MASTER_OFF, 0],+ ])('badges loud categories only (%s)', (_label, preferences, expected) => {+ expect(badgeTotal(counts, preferences)).toBe(expected);+ });++ it('names the mode, with one category for a caller without Bots', () => {+ expect(notificationMode(ALL_ON, true)).toBe('all');+ expect(notificationMode(BOTS_ONLY, true)).toBe('bots');+ expect(notificationMode(SESSIONS_ONLY, true)).toBe('sessions');+ expect(notificationMode(MASTER_OFF, true)).toBe('off');+ expect(notificationMode({ enabled: true, bots: false, sessions: false }, true)).toBe('off');+ // Without Bots the Bot switch is not theirs to see, so it cannot read as partial.+ expect(notificationMode(SESSIONS_ONLY, false)).toBe('all');+ expect(notificationMode(MASTER_OFF, false)).toBe('off');+ });++ it('reads the wrapped record, and treats a missing switch as on', () => {+ expect(parseNotificationPreferences({ ok: true, preferences: { enabled: true, bots: true, sessions: false } })).toEqual(BOTS_ONLY);+ expect(parseNotificationPreferences({ ok: true, preferences: { sessions: false } })).toEqual(BOTS_ONLY);+ expect(parseNotificationPreferences({ ok: true, preferences: {} })).toEqual(ALL_ON);+ // A body without the record says nothing about the switches, least of all "all on".+ expect(parseNotificationPreferences({ ok: true })).toBeNull();+ expect(parseNotificationPreferences({ enabled: false })).toBeNull();+ expect(parseNotificationPreferences({ ok: false, error: 'forbidden' })).toBeNull();+ expect(parseNotificationPreferences(null)).toBeNull();+ });+});diff --git a/ui/src/lib/notificationPreferences.ts b/ui/src/lib/notificationPreferences.tsnew file mode 100644index 000000000..3617f4323--- /dev/null+++ b/ui/src/lib/notificationPreferences.ts@@ -0,0 +1,81 @@+// Notification preferences and Inbox categories (docs/plans/workbench-refinements.md+// §1). The pure half: what the preference record looks like, which category a+// conversation is in, and the badge those two decide. Every surface that counts+// or switches notifications reads these, so the badge on the sidebar, the app+// icon and the tab favicon cannot disagree.+/** The account's switches. A category is loud while the master switch and its own are on. */+export type NotificationPreferences = {+ enabled: boolean;+ bots: boolean;+ sessions: boolean;+};++export const DEFAULT_NOTIFICATION_PREFERENCES: NotificationPreferences = {+ enabled: true,+ bots: true,+ sessions: true,+};++export type InboxCategory = 'bot' | 'session';++/** Settings › Notifications, the full page the compact menus link to. */+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.+ */+export const inboxCategory = (sessionId: string, botSessionIds: ReadonlySet<string>): InboxCategory =>+ (botSessionIds.has(sessionId) ? 'bot' : 'session');++export const isCategoryLoud = (preferences: NotificationPreferences, category: InboxCategory): boolean =>+ preferences.enabled && (category === 'bot' ? preferences.bots : preferences.sessions);++export type UnreadByCategory = Record<InboxCategory, number>;++/** The unread map split by category: the server's `split_unread_counts`. */+export function unreadByCategory(+ unreadBySession: Record<string, number>,+ botSessionIds: ReadonlySet<string>,+): UnreadByCategory {+ const counts: UnreadByCategory = { bot: 0, session: 0 };+ for (const [sessionId, count] of Object.entries(unreadBySession)) {+ if (count > 0) counts[inboxCategory(sessionId, botSessionIds)] += count;+ }+ return counts;+}++/** The aggregate badge: unread in loud categories only, the server's `badge_total`.+ * With every switch on it is the whole unread total. */+export const badgeTotal = (counts: UnreadByCategory, preferences: NotificationPreferences): number =>+ (isCategoryLoud(preferences, 'bot') ? counts.bot : 0) + (isCategoryLoud(preferences, 'session') ? counts.session : 0);++/**+ * What the switches amount to, for the one-word labels. Without Bots there is+ * one category, so the record reads as all or off.+ */+export type NotificationMode = 'all' | 'bots' | 'sessions' | 'off';++export function notificationMode(preferences: NotificationPreferences, hasBots: boolean): NotificationMode {+ const sessions = isCategoryLoud(preferences, 'session');+ if (!hasBots) return sessions ? 'all' : 'off';+ const bots = isCategoryLoud(preferences, 'bot');+ if (bots && sessions) return 'all';+ if (bots) return 'bots';+ if (sessions) return 'sessions';+ return 'off';+}++/** A read or write response, `{ok, preferences}`. A missing switch is on; a response without the record is none. */+export function parseNotificationPreferences(payload: unknown): NotificationPreferences | null {+ if (!payload || typeof payload !== 'object') return null;+ const outer = payload as Record<string, unknown>;+ if (outer.ok === false || !outer.preferences || typeof outer.preferences !== 'object') return null;+ const record = outer.preferences as Record<string, unknown>;+ const flag = (key: keyof NotificationPreferences) => record[key] !== false;+ return { enabled: flag('enabled'), bots: flag('bots'), sessions: flag('sessions') };+}diff --git a/ui/src/lib/pwaRouteMemory.ts b/ui/src/lib/pwaRouteMemory.tsindex dc1a1c070..5958928cc 100644--- a/ui/src/lib/pwaRouteMemory.ts+++ b/ui/src/lib/pwaRouteMemory.ts@@ -21,6 +21,7 @@ const RESTORABLE_EXACT_PATHS = new Set(['/apps/library','/settings','/settings/general',+ '/settings/notifications','/settings/appearance','/settings/account','/settings/shortcuts',