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(inbox): add notification categories and preferences (#3127)
Call Whitef13a4321561c
diff --git a/core/chat_discovery.py b/core/chat_discovery.pyindex df69004d6..6b34fa96a 100644--- a/core/chat_discovery.py+++ b/core/chat_discovery.py@@ -9,7 +9,7 @@ import timefrom dataclasses import asdict, dataclass, fieldfrom datetime import datetime, timezonefrom pathlib import Path-from typing import Any+from typing import Any, Callablefrom sqlalchemy import Connection, and_, func, select@@ -246,6 +246,38 @@ def set_state_meta(key: str, value: Any, *, db_path: Path | None = None, now: stengine.dispose()+def update_state_meta(+ key: str,+ updater: Callable[[Any], Any],+ *,+ db_path: Path | None = None,+ now: str | None = None,+) -> Any:+ """Atomically read, update, and replace one state metadata document."""++ engine = _engine(db_path)+ try:+ with engine.connect() as conn:+ # A deferred SQLite transaction allows two readers to observe the+ # same JSON document before either writer commits. Acquire the+ # database write reservation before reading so the merge cannot+ # lose a concurrent partial update.+ conn.exec_driver_sql("BEGIN IMMEDIATE")+ try:+ raw = conn.execute(+ select(state_meta.c.value_json).where(state_meta.c.key == key)+ ).scalar_one_or_none()+ value = updater(_json_load_any(raw))+ _set_state_meta(conn, key, value, now=now or _utc_now_iso())+ conn.commit()+ return value+ except Exception:+ conn.rollback()+ raise+ finally:+ engine.dispose()++def _set_state_meta(conn: Connection, key: str, value: Any, *, now: str) -> None:conn.execute(state_meta.delete().where(state_meta.c.key == key))conn.execute(state_meta.insert().values(key=key, value_json=_json_dumps(value), updated_at=now))diff --git a/core/notification_categories.py b/core/notification_categories.pynew file mode 100644index 000000000..3a3815251--- /dev/null+++ b/core/notification_categories.py@@ -0,0 +1,96 @@+"""Shared Inbox notification categorization.++The Bot registry is the only source of truth for whether a permanent Session is+currently a Bot conversation. In particular, a Project scope never implies a+category: Bot Sessions deliberately have no scope, and ordinary scope-less+Sessions remain ordinary Sessions.+"""++from __future__ import annotations++from typing import Iterable, Mapping++from sqlalchemy import case, exists, func, literal, select+from sqlalchemy.engine import Connection++CATEGORY_BOT = "bot"+CATEGORY_SESSION = "session"+INBOX_CATEGORIES = (CATEGORY_BOT, CATEGORY_SESSION)+++def normalize_category(value: object) -> str | None:+ """Validate an optional Inbox category filter."""++ if value is None or value == "":+ return None+ category = str(value).strip().lower()+ if category not in INBOX_CATEGORIES:+ raise ValueError("category must be one of: bot, session")+ return category+++def current_bot_session_ids(conn: Connection) -> frozenset[str]:+ """Return permanent Session ids of current (not removed) Bots."""++ from core.bots import list_bots_in++ return frozenset(bot.session_id for bot in list_bots_in(conn) if bot.agent.enabled)+++def current_bot_session_predicate(session_id_column):+ """Return a SQL predicate for a current Bot permanent Session.++ Keeping this expression here lets the Inbox query classify and filter in the+ same bounded statement; callers do not need a second registry read per row.+ """++ from storage.models import agents++ handle = func.json_extract(agents.c.metadata_json, "$.bot.handle")+ removed_at = func.json_extract(agents.c.metadata_json, "$.bot.removed_at")+ return exists(+ select(1)+ .select_from(agents)+ .where(+ agents.c.archived_at.is_(None),+ agents.c.enabled == 1,+ handle.is_not(None),+ removed_at.is_(None),+ session_id_column == literal("ses_") + handle,+ )+ )+++def category_expression(session_id_column):+ """Return the SQL category expression backed by the current Bot registry."""++ return case(+ (current_bot_session_predicate(session_id_column), CATEGORY_BOT),+ else_=CATEGORY_SESSION,+ )+++def category_for_session_id(+ session_id: object,+ *,+ bot_session_ids: Iterable[str],+) -> str:+ """Classify one Inbox destination from the Bot registry snapshot."""++ bot_ids = bot_session_ids if isinstance(bot_session_ids, (set, frozenset)) else set(bot_session_ids)+ return CATEGORY_BOT if session_id is not None and str(session_id) in bot_ids else CATEGORY_SESSION+++def split_unread_counts(+ unread_by_session: Mapping[str, int],+ *,+ bot_session_ids: Iterable[str],+) -> dict[str, int]:+ """Aggregate per-Session unread counts into the two Inbox categories."""++ bot_ids = set(bot_session_ids)+ counts = {CATEGORY_BOT: 0, CATEGORY_SESSION: 0}+ for session_id, count in unread_by_session.items():+ category = CATEGORY_BOT if session_id in bot_ids else CATEGORY_SESSION+ counts[category] += int(count)+ return countsdiff --git a/core/notification_preferences.py b/core/notification_preferences.pynew file mode 100644index 000000000..cf8468dde--- /dev/null+++ b/core/notification_preferences.py@@ -0,0 +1,97 @@+"""Account-wide Inbox notification preferences stored in ``state_meta``."""++from __future__ import annotations++from pathlib import Path+from typing import Any, Mapping++from core.chat_discovery import get_state_meta, update_state_meta+from core.notification_categories import CATEGORY_BOT, CATEGORY_SESSION++PREFERENCES_KEY_PREFIX = "notification_preferences:"+PREFERENCE_FIELDS = ("enabled", "bots", "sessions")+++def preferences_key(user_key: str) -> str:+ """Return the durable state key for one trusted notification user key."""++ if not isinstance(user_key, str) or not user_key.strip():+ raise ValueError("user_key must be a non-empty string")+ return f"{PREFERENCES_KEY_PREFIX}{user_key.strip()}"+++def _normalized_document(raw: Any) -> dict[str, Any]:+ document = dict(raw) if isinstance(raw, dict) else {}+ for field in PREFERENCE_FIELDS:+ value = document.get(field)+ document[field] = value if isinstance(value, bool) else True+ return document+++def get_notification_preferences(+ user_key: str,+ *,+ db_path: Path | None = None,+) -> dict[str, Any]:+ """Read preferences; missing or malformed known fields default to on."""++ raw = get_state_meta(preferences_key(user_key), db_path=db_path)+ return _normalized_document(raw)+++def set_notification_preferences(+ user_key: str,+ updates: Mapping[str, Any],+ *,+ db_path: Path | None = None,+) -> dict[str, Any]:+ """Merge known boolean fields while preserving unknown stored fields."""++ if not isinstance(updates, Mapping):+ raise ValueError("preferences must be an object")+ def merge(raw: Any) -> dict[str, Any]:+ document = _normalized_document(raw)+ for field in PREFERENCE_FIELDS:+ if field not in updates:+ continue+ value = updates[field]+ if not isinstance(value, bool):+ raise ValueError(f"{field} must be a JSON boolean")+ document[field] = value+ return document++ return update_state_meta(preferences_key(user_key), merge, db_path=db_path)+++def public_notification_preferences(preferences: Mapping[str, Any]) -> dict[str, bool]:+ """Return the stable API/SSE shape, excluding reserved future fields."""++ return {+ field: bool(preferences.get(field, True))+ for field in PREFERENCE_FIELDS+ }+++def category_is_loud(preferences: Mapping[str, Any], category: str) -> bool:+ """Whether a category contributes badges and may trigger Web Push."""++ if category == CATEGORY_BOT:+ field = "bots"+ elif category == CATEGORY_SESSION:+ field = "sessions"+ else:+ raise ValueError(f"unknown notification category: {category}")+ return bool(preferences.get("enabled", True)) and bool(preferences.get(field, True))+++def badge_total(+ unread_by_category: Mapping[str, int],+ preferences: Mapping[str, Any],+) -> int:+ """Sum unread counts only for loud categories."""++ return sum(+ int(unread_by_category.get(category, 0))+ for category in (CATEGORY_BOT, CATEGORY_SESSION)+ if category_is_loud(preferences, category)+ )diff --git a/core/web_push_notifications.py b/core/web_push_notifications.pyindex 3d3b82c5c..f8ee37227 100644--- a/core/web_push_notifications.py+++ b/core/web_push_notifications.py@@ -42,6 +42,7 @@ WEB_PUSH_DISPOSITION_REVOKED = "revoked"WEB_PUSH_DISPOSITION_NO_SUBSCRIPTION = "no_subscription"WEB_PUSH_DISPOSITION_PROVIDER_FAILURE = "provider_failure"WEB_PUSH_DISPOSITION_SUPPRESSED_READ = "suppressed_read"+WEB_PUSH_DISPOSITION_MUTED = "muted"WEB_PUSH_DISPOSITION_CONFIG_UNAVAILABLE = "config_unavailable"@@ -950,37 +951,45 @@ def _badge_count_for_user_key(user_key: str,contexts: dict[str, AuthorizationContext],) -> int:- """Return the unread count visible to one Push subscription owner."""+ """Return the loud unread count visible to one Push subscription owner."""- if user_key == "local":- from core.bots import hidden_bot_session_ids-- return messages_service.total_unread(- conn, platform="avibe", hidden_session_ids=hidden_bot_session_ids(conn, None)- )- context = contexts.get(user_key)- if context is None:- # Legacy remote messages predate persisted authorization claims. Keep- # delivering eligible content, but never attach a machine-global count.- return 0- if context.can_manage_instance:- from core.bots import hidden_bot_session_ids-- return messages_service.total_unread(- conn, platform="avibe", hidden_session_ids=hidden_bot_session_ids(conn, context)- )+ from core.notification_categories import current_bot_session_ids, split_unread_counts+ from core.notification_preferences import badge_total, get_notification_preferences+ from core.bots import hidden_bot_session_ids- from storage import project_access_service+ hidden_session_ids = hidden_bot_session_ids(+ conn,+ None if user_key == "local" else contexts.get(user_key),+ )+ if user_key == "local":+ scope_ids = None+ else:+ context = contexts.get(user_key)+ if context is None:+ # Legacy remote messages predate persisted authorization claims. Keep+ # delivering eligible content, but never attach a machine-global count.+ return 0+ if context.can_manage_instance:+ scope_ids = None+ else:+ from storage import project_access_service++ scope_ids = [+ project_access_service.project_scope_id(project_id)+ for project_id in project_access_service.accessible_project_ids(conn, context)+ ]- scope_ids = [- project_access_service.project_scope_id(project_id)- for project_id in project_access_service.accessible_project_ids(conn, context)- ]- return messages_service.total_unread(+ per_session = messages_service.unread_counts_by_session(conn,platform="avibe",scope_ids=scope_ids,+ hidden_session_ids=hidden_session_ids,)+ category_counts = split_unread_counts(+ per_session,+ bot_session_ids=current_bot_session_ids(conn),+ )+ return badge_total(category_counts, get_notification_preferences(user_key))def _remote_access_enabled() -> bool:@@ -1099,6 +1108,34 @@ def _send_to_enabled_subscriptions(payload: dict[str, Any]) -> None:"disposition": None,"reason": "local fallback with remote access disabled",}++ from core.notification_categories import category_for_session_id, current_bot_session_ids+ from core.notification_preferences import category_is_loud, get_notification_preferences++ notification_category = category_for_session_id(+ session_id,+ bot_session_ids=current_bot_session_ids(conn),+ )+ payload.setdefault("category", notification_category)+ loud_authorized_keys: list[str] = []+ for user_key in authorized_keys:+ preferences = get_notification_preferences(user_key)+ if category_is_loud(preferences, notification_category):+ loud_authorized_keys.append(user_key)+ continue+ attempt["owners"][user_key] = {+ "policy": attempt["owners"].get(user_key, {}).get("policy") or (+ "local" if user_key == "local" else "unknown"+ ),+ "disposition": WEB_PUSH_DISPOSITION_MUTED,+ "reason": f"{notification_category} notifications are muted for this account",+ }+ logger.info(+ "web push: skipping owner %s: %s notifications are muted",+ user_key,+ notification_category,+ )+ authorized_keys = loud_authorized_keysif not authorized_keys:disposition = next((diff --git a/storage/messages_service.py b/storage/messages_service.pyindex 6c35b4568..21b9a605a 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -20,6 +20,15 @@ from sqlalchemy import and_, case, delete, func, or_, select, updatefrom sqlalchemy.engine import Connectionfrom storage.agent_session_rows import INBOX_SESSION_VISIBILITIES+from core.notification_categories import (+ CATEGORY_BOT,+ CATEGORY_SESSION,+ category_expression,+ current_bot_session_ids,+ current_bot_session_predicate,+ normalize_category,+ split_unread_counts,+)from storage.db import escape_sql_likefrom storage.models import (agent_runs,@@ -1278,6 +1287,27 @@ def unread_counts_by_session(return {session_id: int(count) for session_id, count in conn.execute(query).all()}+def unread_counts_by_category(+ conn: Connection,+ *,+ platform: Optional[str] = None,+ scope_ids: Optional[Iterable[str]] = None,+ hidden_session_ids: Optional[Iterable[str]] = None,+) -> dict[str, int]:+ """Return unread result counts split by the current Bot registry."""++ per_session = unread_counts_by_session(+ conn,+ platform=platform,+ scope_ids=scope_ids,+ hidden_session_ids=hidden_session_ids,+ )+ return split_unread_counts(+ per_session,+ bot_session_ids=current_bot_session_ids(conn),+ )++def total_unread(conn: Connection,*,@@ -1314,6 +1344,7 @@ def list_inbox_sessions(only_session: Optional[str] = None,scope_ids: Optional[Iterable[str]] = None,hidden_session_ids: Optional[Iterable[str]] = None,+ category: Optional[str] = None,) -> dict[str, Any]:"""Per-session ("Slack-like") inbox feed.@@ -1336,6 +1367,9 @@ def list_inbox_sessions(if allowed_scope_ids == []:return {"sessions": [], "next_cursor": None}+ normalized_category = normalize_category(category)+ bot_session_predicate = current_bot_session_predicate(agent_sessions.c.id)+def _latest_message_value(column_name: Optional[str],*,@@ -1481,6 +1515,7 @@ def list_inbox_sessions(agent_sessions.c.scope_id,scopes.c.native_id.label("project_id"),scopes.c.display_name.label("project_name"),+ category_expression(agent_sessions.c.id).label("category"),unread_count_col,preview_id.label("preview_id"),preview_at.label("preview_at"),@@ -1513,6 +1548,11 @@ def list_inbox_sessions(session_rows = session_rows.where(agent_sessions.c.id == only_session)if allowed_scope_ids is not None:session_rows = session_rows.where(agent_sessions.c.scope_id.in_(allowed_scope_ids))+ if normalized_category == CATEGORY_BOT:+ session_rows = session_rows.where(bot_session_predicate)+ elif normalized_category == CATEGORY_SESSION:+ session_rows = session_rows.where(~bot_session_predicate)+hidden = _hidden_ids(hidden_session_ids)if hidden:session_rows = session_rows.where(agent_sessions.c.id.not_in(hidden))@@ -1603,6 +1643,7 @@ def list_inbox_sessions("preview_at": row["preview_at"],"unread_count": unread,"unread": unread > 0,+ "category": row["category"],})diff --git a/tests/fixtures/member_management_existing_read_roles.json b/tests/fixtures/member_management_existing_read_roles.jsonindex 3af7bb023..7f567ef4d 100644--- a/tests/fixtures/member_management_existing_read_roles.json+++ b/tests/fixtures/member_management_existing_read_roles.json@@ -38,6 +38,7 @@"GET /api/mcp": "editor","GET /api/mcp/example": "editor","GET /api/mcp/oauth/callback": "viewer",+ "GET /api/notifications/preferences": "viewer","GET /api/media/example": "viewer","GET /api/media/example/meta": "viewer","GET /api/models/agents/example/models": "editor",@@ -145,6 +146,7 @@"POST /api/web-push/test": "viewer","PUT /api/dock/order": "editor","PUT /api/files/write": "editor",+ "PUT /api/notifications/preferences": "viewer","PUT /api/sessions/example/draft": "editor","PUT /api/vault/secrets/example/fields/example": "editor"}diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.pyindex a3b01421e..f6cbc49b3 100644--- a/tests/test_member_management_parity.py+++ b/tests/test_member_management_parity.py@@ -135,8 +135,8 @@ def test_complete_registered_api_management_inventory():for method in (getattr(route, "methods", None) or ())if method not in {"HEAD", "OPTIONS"}}- # master 297 + 10 MCP Hub routes, classified in tests/test_mcp_hub_api.py, + 8 Bots routes (Owner, above)- assert len(endpoints) == 315+ # master 297 + 10 MCP Hub routes, classified in tests/test_mcp_hub_api.py, + 8 Bots routes (Owner, above), + 2 notification preference methods+ assert len(endpoints) == 317# Editors who use Vault read avault's authorization state; the handler admits only# instance managers to raise the Keychain dialog on the host.for method in ("GET", "POST"):diff --git a/tests/test_notification_categories.py b/tests/test_notification_categories.pynew file mode 100644index 000000000..2f8c0d20c--- /dev/null+++ b/tests/test_notification_categories.py@@ -0,0 +1,301 @@+"""Server-side Inbox category and account notification preference contracts."""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from storage.importer import ensure_sqlite_state+from tests.ui_server_test_helpers import csrf_headers+from vibe.ui_server import app+++pytestmark = pytest.mark.real_web_push_sender+++def isolated_state(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ ensure_sqlite_state()+ yield tmp_path+++def _seed_session(conn, session_id: str, *, scope_id: str | None, title: str) -> None:+ from storage.messages_service import _utc_now_iso+ from storage.models import agent_sessions++ now = _utc_now_iso()+ conn.execute(+ agent_sessions.insert().values(+ id=session_id,+ scope_id=scope_id,+ agent_backend="vibey",+ agent_variant="default",+ session_anchor=f"anchor_{session_id}",+ native_session_id="",+ title=title,+ status="active",+ visibility="foreground",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )+++def _seed_result(conn, *, scope_id: str | None, session_id: str, text: str, user_key: str = "local") -> dict:+ from storage import messages_service++ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id=session_id,+ platform="avibe",+ author="user",+ source="user",+ message_type="user",+ text="Please finish",+ metadata={"_web_push_user_key": user_key},+ )+ return messages_service.append(+ conn,+ scope_id=scope_id,+ session_id=session_id,+ platform="avibe",+ author="agent",+ source="agent",+ message_type="result",+ text=text,+ read_at=None,+ )+++def test_preferences_default_and_unknown_state_fields_survive_write(isolated_state):+ from core.chat_discovery import get_state_meta, set_state_meta+ from core.notification_preferences import (+ get_notification_preferences,+ preferences_key,+ set_notification_preferences,+ )++ assert {+ key: get_notification_preferences("local")[key]+ for key in ("enabled", "bots", "sessions")+ } == {"enabled": True, "bots": True, "sessions": True}++ set_state_meta(+ preferences_key("local"),+ {"enabled": False, "bots": True, "muted_bots": ["researcher"], "future": {"x": 1}},+ )+ stored = set_notification_preferences("local", {"sessions": False})++ assert stored["enabled"] is False+ assert stored["bots"] is True+ assert stored["sessions"] is False+ assert stored["muted_bots"] == ["researcher"]+ assert stored["future"] == {"x": 1}+ assert get_state_meta(preferences_key("local")) == stored+++def test_preferences_api_is_account_scoped_and_csrf_protected(isolated_state):+ client = app.test_client()++ default = client.get("/api/notifications/preferences", base_url="http://127.0.0.1:5123")+ assert default.status_code == 200+ assert default.get_json() == {+ "ok": True,+ "preferences": {"enabled": True, "bots": True, "sessions": True},+ }++ forbidden = client.put(+ "/api/notifications/preferences",+ json={"sessions": False},+ base_url="http://127.0.0.1:5123",+ )+ assert forbidden.status_code == 403++ headers = csrf_headers(client, "http://127.0.0.1:5123")+ updated = client.put(+ "/api/notifications/preferences",+ json={"sessions": False},+ headers=headers,+ base_url="http://127.0.0.1:5123",+ )+ assert updated.status_code == 200+ assert updated.get_json()["preferences"] == {+ "enabled": True,+ "bots": True,+ "sessions": False,+ }+++def test_preference_sse_event_is_visible_only_to_the_same_user():+ from vibe.authorization import AuthorizationContext, instance_owner_context+ from vibe.ui_server import _workbench_event_visible_to_context++ payload = json.dumps(+ {+ "type": "notifications.preferences.updated",+ "data": {+ "user_key": "remote:alice",+ "preferences": {"enabled": True, "bots": False, "sessions": True},+ },+ }+ )+ alice = AuthorizationContext(instance_role="member", is_remote=True, subject="alice")+ bob = AuthorizationContext(instance_role="member", is_remote=True, subject="bob")+ assert _workbench_event_visible_to_context(alice, "notifications.preferences.updated", payload)+ assert not _workbench_event_visible_to_context(bob, "notifications.preferences.updated", payload)+ assert not _workbench_event_visible_to_context(instance_owner_context(), "notifications.preferences.updated", payload)+++def test_inbox_categories_filters_and_badge_total_follow_registry_and_preferences(isolated_state):+ from core.bots import BotService+ from core.notification_preferences import set_notification_preferences+ from storage import messages_service+ from storage.db import create_sqlite_engine+ from storage.projects_service import create_project++ with BotService() as service:+ bot = service.ensure_main_bot()+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ project_dir = isolated_state / "inbox-category-project"+ project_dir.mkdir()+ project = create_project(conn, str(project_dir), display_name="Project")+ ordinary_id = "ses_ordinary_category"+ _seed_session(conn, ordinary_id, scope_id=project["scope_id"], title="Ordinary")+ _seed_result(conn, scope_id=None, session_id=bot.session_id, text="Bot reply")+ _seed_result(conn, scope_id=project["scope_id"], session_id=ordinary_id, text="Session reply")++ client = app.test_client()+ all_rows = client.get("/api/inbox?platform=avibe", base_url="http://127.0.0.1:5123").get_json()+ assert {row["category"] for row in all_rows["sessions"]} == {"bot", "session"}+ assert all_rows["unread_by_category"] == {"bot": 1, "session": 1}+ assert all_rows["badge_total"] == 2++ bots = client.get("/api/inbox?platform=avibe&category=bot", base_url="http://127.0.0.1:5123").get_json()+ sessions = client.get("/api/inbox?platform=avibe&category=session", base_url="http://127.0.0.1:5123").get_json()+ assert [row["session_id"] for row in bots["sessions"]] == [bot.session_id]+ assert [row["session_id"] for row in sessions["sessions"]] == [ordinary_id]++ set_notification_preferences("local", {"bots": False})+ muted = client.get("/api/inbox?platform=avibe", base_url="http://127.0.0.1:5123").get_json()+ assert muted["unread_by_category"] == {"bot": 1, "session": 1}+ assert muted["unread_total"] == 2+ assert muted["badge_total"] == 1+ engine.dispose()+++def test_member_cannot_turn_owner_bot_session_into_a_session_category(isolated_state):+ from core.bots import BotService, hidden_bot_session_ids+ from storage import messages_service+ from storage.db import create_sqlite_engine+ from storage.projects_service import create_project+ from vibe.authorization import AuthorizationContext, instance_owner_context++ with BotService() as service:+ bot = service.ensure_main_bot()+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ project_dir = isolated_state / "member-category-project"+ project_dir.mkdir()+ project = create_project(conn, str(project_dir), display_name="Project")+ ordinary_id = "ses_member_category"+ _seed_session(conn, ordinary_id, scope_id=project["scope_id"], title="Ordinary")+ _seed_result(conn, scope_id=None, session_id=bot.session_id, text="Bot reply")+ _seed_result(conn, scope_id=project["scope_id"], session_id=ordinary_id, text="Session reply")++ member = AuthorizationContext(instance_role="member", is_remote=True, subject="member-1")+ with engine.connect() as conn:+ owner_rows = messages_service.list_inbox_sessions(+ conn,+ hidden_session_ids=hidden_bot_session_ids(conn, instance_owner_context()),+ )["sessions"]+ member_rows = messages_service.list_inbox_sessions(+ conn,+ hidden_session_ids=hidden_bot_session_ids(conn, member),+ )["sessions"]++ assert {row["category"] for row in owner_rows} == {"bot", "session"}+ assert [row["session_id"] for row in member_rows] == [ordinary_id]+ assert member_rows[0]["category"] == "session"+ engine.dispose()++[email protected]("updates", [{"bots": False}, {"enabled": False}])+def test_push_gating_records_muted_and_badge_total_excludes_quiet_category(+ monkeypatch,+ isolated_state,+ updates,+):+ from core.bots import BotService+ from core.notification_preferences import set_notification_preferences+ from core import web_push_notifications+ from storage import messages_service, web_push_service+ from storage.db import create_sqlite_engine++ with BotService() as service:+ bot = service.ensure_main_bot()+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ message = _seed_result(conn, scope_id=None, session_id=bot.session_id, text="Bot reply")+ web_push_service.upsert_subscription(+ conn,+ user_key="local",+ payload={+ "endpoint": "https://push.example.test/muted-bot",+ "keys": {"p256dh": "p256dh", "auth": "auth"},+ },+ )+ set_notification_preferences("local", updates)+ sent: list[dict] = []+ monkeypatch.setattr(web_push_notifications.time, "sleep", lambda _seconds: None)+ monkeypatch.setattr("core.web_push.send_web_push", lambda *, subscription, payload: sent.append(payload))++ web_push_notifications._send_to_enabled_subscriptions(+ {"title": "Bot", "body": "Bot reply", "session_id": bot.session_id, "message_id": message["id"]}+ )++ assert sent == []+ recent = web_push_notifications.recent_delivery_dispositions(user_key="local")+ assert recent[0]["owners"]["local"]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_MUTED+ engine.dispose()+++def test_service_worker_badge_prefers_badge_total_and_falls_back_to_unread_total():+ worker = (Path(__file__).resolve().parents[1] / "ui" / "public" / "push-sw.js").read_text()+ assert "payload?.badge_total ?? payload?.unread_total" in worker+++def test_push_badge_uses_loud_category_total(monkeypatch, isolated_state):+ from core.bots import BotService+ from core.notification_preferences import set_notification_preferences+ from core import web_push_notifications+ from storage import messages_service+ from storage.db import create_sqlite_engine+ from storage.projects_service import create_project++ with BotService() as service:+ bot = service.ensure_main_bot()+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ project_dir = isolated_state / "badge-category-project"+ project_dir.mkdir()+ project = create_project(conn, str(project_dir), display_name="Project")+ ordinary_id = "ses_badge_category"+ _seed_session(conn, ordinary_id, scope_id=project["scope_id"], title="Ordinary")+ _seed_result(conn, scope_id=None, session_id=bot.session_id, text="Bot reply")+ _seed_result(conn, scope_id=project["scope_id"], session_id=ordinary_id, text="Session reply")+ set_notification_preferences("local", {"bots": False})++ with engine.connect() as conn:+ assert web_push_notifications._badge_count_for_user_key(+ conn,+ user_key="local",+ contexts={},+ ) == 1+ engine.dispose()diff --git a/ui/public/push-sw.js b/ui/public/push-sw.jsindex d09dfc9e7..577dd6ec3 100644--- a/ui/public/push-sw.js+++ b/ui/public/push-sw.js@@ -81,7 +81,7 @@ async function refreshAppBadge() {requestForegroundBadgeRefresh(clients);return;}- await queueAppBadge(payload?.unread_total, refreshId, pageRevisionAtStart);+ await queueAppBadge(payload?.badge_total ?? payload?.unread_total, refreshId, pageRevisionAtStart);requestForegroundBadgeRefresh(await appWindowClients());} catch {// An unavailable or unauthenticated read is not evidence that the badge is zero.diff --git a/vibe/authorization.py b/vibe/authorization.pyindex 56d468638..f5de92cf9 100644--- a/vibe/authorization.py+++ b/vibe/authorization.py@@ -67,6 +67,7 @@ _VIEWER_WORKBENCH_EVENTS = frozenset("connected","inbox.session.updated","inbox.unread.changed",+ "notifications.preferences.updated","message.new","message.updated","projects.changed",@@ -459,6 +460,7 @@ _VIEWER_HTTP_RULES = tuple(r"^/api/search/messages$",r"^/api/events$",r"^/api/inbox$",+ r"^/api/notifications/preferences$",r"^/api/media/[^/]+(?:/meta)?$",r"^/api/permissions$",r"^/api/permissions/resources/[^/]+/[^/]+/access$",@@ -485,6 +487,7 @@ _VIEWER_HTTP_NAMESPACES = ("/api/web-push",)_VIEWER_HTTP_MUTATION_RULES = (+ ("PUT", re.compile(r"^/api/notifications/preferences$")),("POST", re.compile(r"^/api/sessions/[^/]+/mark-read$")),("DELETE", re.compile(r"^/api/terminal/[^/]+$")),)diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 590f4d5b9..468e5c2aa 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -6899,6 +6899,46 @@ def _web_push_user_key() -> str:return "local"[email protected]("/api/notifications/preferences", methods=["GET", "PUT"])+def notification_preferences_route():+ from core.notification_preferences import (+ get_notification_preferences,+ public_notification_preferences,+ set_notification_preferences,+ )++ user_key = _web_push_user_key()+ if request.method == "GET":+ preferences = get_notification_preferences(user_key)+ return jsonify({"ok": True, "preferences": public_notification_preferences(preferences)})++ payload = request.json+ if not isinstance(payload, dict):+ return jsonify({"ok": False, "error": "invalid_payload"}), 400+ updates = {field: payload[field] for field in ("enabled", "bots", "sessions") if field in payload}+ if not updates:+ return jsonify({"ok": False, "error": "no_preferences"}), 400+ try:+ preferences = set_notification_preferences(user_key, updates)+ except ValueError as exc:+ return jsonify({"ok": False, "error": "invalid_preferences", "message": str(exc)}), 400++ public = public_notification_preferences(preferences)+ from vibe.sse_broker import broker++ broker.publish(+ "notifications.preferences.updated",+ {"user_key": user_key, "preferences": public},+ )+ return jsonify({"ok": True, "preferences": public})+++def _notification_user_key_for_context(context: Any) -> str:+ if context is not None and getattr(context, "is_remote", False) and getattr(context, "subject", None):+ return f"remote:{context.subject}"+ return "local"++def _workbench_author_id() -> str | None:"""Return an author only when the browser passes strict admission."""@@ -13194,6 +13234,11 @@ async def sessions_cancel(session_id: str):@app.route("/api/sessions/<session_id>/mark-read", methods=["POST"])def sessions_mark_read(session_id: str):+ from core.notification_categories import current_bot_session_ids, split_unread_counts+ from core.notification_preferences import (+ badge_total as notification_badge_total,+ get_notification_preferences,+ )from core.services import sessions as workbench_sessions_servicefrom storage import messages_servicefrom vibe.sse_broker import broker@@ -13227,6 +13272,14 @@ def sessions_mark_read(session_id: str):scope_ids=accessible_scope_ids,hidden_session_ids=hidden_session_ids,)+ unread_by_category = split_unread_counts(+ unread_by_session,+ bot_session_ids=current_bot_session_ids(conn),+ )+ current_badge_total = notification_badge_total(+ unread_by_category,+ get_notification_preferences(_web_push_user_key()),+ )except LookupError as err:return jsonify({"error": str(err)}), 404if updated:@@ -13238,6 +13291,8 @@ def sessions_mark_read(session_id: str):"delta": -updated,"unread_counts": unread_counts,"unread_by_session": unread_by_session,+ "unread_by_category": unread_by_category,+ "badge_total": current_badge_total,},)return jsonify(@@ -13245,6 +13300,8 @@ def sessions_mark_read(session_id: str):"updated": updated,"unread_counts": unread_counts,"unread_by_session": unread_by_session,+ "unread_by_category": unread_by_category,+ "badge_total": current_badge_total,})@@ -13451,6 +13508,12 @@ def _workbench_event_heartbeat_frame() -> str:def _workbench_event_visible_to_context(context, event_type: str, payload: str) -> bool:+ if event_type == "notifications.preferences.updated":+ data = _workbench_event_data(payload)+ return bool(+ data is not None+ and data.get("user_key") == _notification_user_key_for_context(context)+ )if context is None:return Trueif event_type == "show.event":@@ -13588,6 +13651,11 @@ def _workbench_event_payload_for_context(context, event_type: str, payload: str)if not isinstance(data, dict):return payload+ from core.notification_categories import current_bot_session_ids, split_unread_counts+ from core.notification_preferences import (+ badge_total as notification_badge_total,+ get_notification_preferences,+ )from storage import messages_serviceengine = _projects_engine()@@ -13606,6 +13674,14 @@ def _workbench_event_payload_for_context(context, event_type: str, payload: str)scope_ids=scope_ids,hidden_session_ids=hidden_session_ids,)+ unread_by_category = split_unread_counts(+ unread_by_session,+ bot_session_ids=current_bot_session_ids(conn),+ )+ current_badge_total = notification_badge_total(+ unread_by_category,+ get_notification_preferences(_notification_user_key_for_context(context)),+ )return json.dumps({**envelope,@@ -13613,6 +13689,8 @@ def _workbench_event_payload_for_context(context, event_type: str, payload: str)**data,"unread_counts": unread_counts,"unread_by_session": unread_by_session,+ "unread_by_category": unread_by_category,+ "badge_total": current_badge_total,},},ensure_ascii=False,@@ -13803,6 +13881,12 @@ def inbox_list():activity first. Defaults to avibe-only per workbench scope."""from storage import messages_service+ from core.notification_categories import (+ current_bot_session_ids,+ normalize_category,+ split_unread_counts,+ )+ from core.notification_preferences import badge_total, get_notification_preferencesplatform = request.args.get("platform") or "avibe"scope_filter = platform if platform != "all" else None@@ -13816,6 +13900,10 @@ def inbox_list():# reconcile) guarantee one specific session's row is (re)loaded even when its# activity sorts past the paged window.only_session = request.args.get("session") or None+ try:+ category = normalize_category(request.args.get("category"))+ except ValueError as exc:+ return jsonify({"ok": False, "error": "invalid_category", "message": str(exc)}), 400engine = _projects_engine()with engine.connect() as conn:@@ -13831,6 +13919,7 @@ def inbox_list():only_session=only_session,scope_ids=accessible_scope_ids,hidden_session_ids=hidden_session_ids,+ category=category,)# Pagination-independent unread map for the sidebar badges (a session# with unread may sit past the first inbox page) + header totals.@@ -13843,6 +13932,15 @@ def inbox_list():result["unread_by_session"] = per_sessionresult["unread_total"] = sum(per_session.values())result["unread_sessions"] = len(per_session)+ category_counts = split_unread_counts(+ per_session,+ bot_session_ids=current_bot_session_ids(conn),+ )+ result["unread_by_category"] = category_counts+ result["badge_total"] = badge_total(+ category_counts,+ get_notification_preferences(_web_push_user_key()),+ )return jsonify(result)