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(pwa): mirror unread total onto the app-icon badge (#524)
Call Whitee1bcbd336d6b
diff --git a/core/web_push_notifications.py b/core/web_push_notifications.pyindex 537657d0e..a1f069066 100644--- a/core/web_push_notifications.py+++ b/core/web_push_notifications.py@@ -10,7 +10,7 @@ from typing import Anyfrom sqlalchemy import or_, select-from storage import web_push_service+from storage import messages_service, web_push_servicefrom storage.models import agent_sessions, messageslogger = logging.getLogger(__name__)@@ -41,12 +41,15 @@ def maybe_notify_inbox_message(message: dict[str, Any] | None, inbox_row: dict[sif not message.get("session_id"):return+ # ``badge_count`` is the app-icon badge number, which is a single global+ # value — not this one session's unread count. It is computed at send time+ # (see ``_send_to_enabled_subscriptions``) so it reflects the real total+ # after the debounce delay and matches the in-app Inbox badge.payload = {"title": inbox_row.get("title") or inbox_row.get("project_name") or "avibe","body": (message.get("text") or inbox_row.get("preview_text") or "").strip()[:240],"url": f"/chat/{message['session_id']}","tag": f"session:{message['session_id']}",- "badge_count": inbox_row.get("unread_count") or 0,"message_id": message.get("id"),"session_id": message.get("session_id"),}@@ -165,6 +168,9 @@ def _send_to_enabled_subscriptions(payload: dict[str, Any]) -> None:if not _message_still_unread(conn, payload.get("message_id")):logger.debug("web push: skip notification for message already read or missing")return+ # The app-icon badge is one global number; compute the live total now+ # (post-debounce) so it matches the in-app Inbox badge on open.+ payload["badge_count"] = messages_service.total_unread(conn, platform="avibe")user_keys = _web_push_user_keys_for_message(conn, payload.get("message_id"))if not user_keys and not _remote_access_enabled():user_keys = ["local"] if web_push_service.has_enabled_user_key(conn, user_key="local") else []diff --git a/storage/messages_service.py b/storage/messages_service.pyindex 15105e5ab..2798b3d59 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -589,6 +589,19 @@ def unread_counts_by_session(return {session_id: int(count) for session_id, count in conn.execute(query).all()}+def total_unread(conn: Connection, *, platform: Optional[str] = None) -> int:+ """Global unread agent-``result`` count across all non-archived sessions.++ This is the sum of :func:`unread_counts_by_session`, i.e. the exact number+ the Inbox nav badge shows (``ui_server`` returns it as ``unread_total``). It+ is mirrored onto the installed PWA's app-icon badge — page-side while the app+ is open, and from the Web Push payload while it is closed — so the home+ screen icon never disagrees with the in-app count.+ """++ return sum(unread_counts_by_session(conn, platform=platform).values())++def list_inbox_sessions(conn: Connection,*,diff --git a/tests/test_messages_service.py b/tests/test_messages_service.pyindex 457e40152..5909c534e 100644--- a/tests/test_messages_service.py+++ b/tests/test_messages_service.py@@ -373,6 +373,28 @@ def test_unread_counts_by_session_splits_within_a_scope(isolated_state):assert by_scope == {scope_id: 3}+def test_total_unread_sums_all_sessions(isolated_state):+ """total_unread is the global sum of per-session unread results — the number+ the Inbox nav badge and the installed PWA's app-icon badge both show."""+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_session(conn, scope_id, "ses_a")+ _seed_session(conn, scope_id, "ses_b")+ for _ in range(2):+ messages_service.append(+ conn, scope_id=scope_id, session_id="ses_a", platform="avibe",+ author="agent", message_type="result", text="a",+ )+ messages_service.append(+ conn, scope_id=scope_id, session_id="ses_b", platform="avibe",+ author="agent", message_type="result", text="b",+ )++ with engine.connect() as conn:+ assert messages_service.total_unread(conn, platform="avibe") == 3++def _seed_titled_session(conn, scope_id: str, session_id: str, title: str) -> None:now = messages_service._utc_now_iso()conn.execute(diff --git a/tests/test_web_push_notifications.py b/tests/test_web_push_notifications.pyindex f6e27bb06..8ca2d0ac7 100644--- a/tests/test_web_push_notifications.py+++ b/tests/test_web_push_notifications.py@@ -39,13 +39,15 @@ def test_maybe_notify_inbox_message_schedules_agent_result(monkeypatch):},)+ # badge_count is intentionally NOT set at schedule time: the app-icon badge+ # is one global number, computed fresh at send time (post-debounce), not this+ # one session's unread count.assert calls == [{"title": "Build fix","body": "Done","url": "/chat/ses_1","tag": "session:ses_1",- "badge_count": 2,"message_id": "msg_1","session_id": "ses_1",}@@ -169,6 +171,90 @@ def test_send_to_enabled_subscriptions_waits_then_sends_to_owner_devices(monkeyp]+def test_send_to_enabled_subscriptions_sets_global_badge_count(monkeypatch, tmp_path):+ """badge_count in the sent payload is the GLOBAL unread total, not the+ triggering session's per-session count — the app-icon badge is one number."""+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ ensure_sqlite_state()+ engine = create_sqlite_engine()+ now = "2026-06-04T00:00:00Z"+ with engine.begin() as conn:+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_badge", now=now)+ for sid in ("ses_badge_a", "ses_badge_b"):+ conn.execute(+ agent_sessions.insert().values(+ id=sid,+ scope_id=scope_id,+ agent_backend="claude",+ agent_variant="default",+ session_anchor=sid,+ native_session_id="",+ title=sid,+ status="active",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )+ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_badge_a",+ platform="avibe",+ author="user",+ source="user",+ author_id="remote:user-a",+ metadata={"_web_push_user_key": "remote:user-a"},+ message_type="user",+ text="Please finish",+ )+ # Triggering reply: session A holds ONE unread result...+ message = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_badge_a",+ platform="avibe",+ author="agent",+ source="agent",+ message_type="result",+ text="Done A",+ )+ # ...and an unrelated session B holds another, so the global total is 2+ # while session A's per-session count is only 1.+ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_badge_b",+ platform="avibe",+ author="agent",+ source="agent",+ message_type="result",+ text="Done B",+ )+ web_push_service.upsert_subscription(+ conn,+ user_key="remote:user-a",+ payload={+ "endpoint": "https://push.example.test/a",+ "keys": {"p256dh": "a-key", "auth": "a-auth"},+ },+ )++ sends = []+ monkeypatch.setattr(web_push_notifications.time, "sleep", lambda _seconds: None)+ monkeypatch.setattr(+ "core.web_push.send_web_push",+ lambda *, subscription, payload: sends.append((subscription, payload)),+ )++ web_push_notifications._send_to_enabled_subscriptions(+ {"title": "Badge", "body": "Done A", "session_id": "ses_badge_a", "message_id": message["id"]}+ )++ assert [send[1]["badge_count"] for send in sends] == [2]++def test_send_to_enabled_subscriptions_uses_legacy_session_owner(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))ensure_sqlite_state()diff --git a/ui/public/push-sw.js b/ui/public/push-sw.jsindex d7aa15e00..0b9640117 100644--- a/ui/public/push-sw.js+++ b/ui/public/push-sw.js@@ -1,3 +1,20 @@+// Mirror the unread total onto the installed app's home-screen icon badge via+// the Badging API. This is distinct from `options.badge` below, which is only+// the small monochrome glyph shown inside the notification itself. Best-effort:+// browsers without the API (and non-installed contexts) simply no-op, and a+// rejected badge promise must never block the notification from showing.+//+// Returns a promise to await, or null when there is nothing to do. `count` is+// the global unread total the server computed for this push; a missing/invalid+// count leaves the existing badge untouched (we don't guess).+function syncAppBadge(count) {+ if (!('setAppBadge' in navigator)) return null;+ if (typeof count !== 'number' || !Number.isFinite(count)) return null;+ const n = Math.max(0, Math.trunc(count));+ const op = n === 0 ? navigator.clearAppBadge?.() : navigator.setAppBadge(n);+ return op && typeof op.catch === 'function' ? op.catch(() => {}) : null;+}+self.addEventListener('push', (event) => {let payload = {};try {@@ -17,7 +34,10 @@ self.addEventListener('push', (event) => {badge: '/icon-192.png',};- event.waitUntil(self.registration.showNotification(title, options));+ const tasks = [self.registration.showNotification(title, options)];+ const badgeTask = syncAppBadge(payload.badge_count);+ if (badgeTask) tasks.push(badgeTask);+ event.waitUntil(Promise.all(tasks));});self.addEventListener('notificationclick', (event) => {diff --git a/ui/src/context/WorkbenchInboxContext.tsx b/ui/src/context/WorkbenchInboxContext.tsxindex 72b51dc3f..0ab87b1a4 100644--- a/ui/src/context/WorkbenchInboxContext.tsx+++ b/ui/src/context/WorkbenchInboxContext.tsx@@ -68,6 +68,14 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>const api = useApi();const [inboxSessions, setInboxSessions] = useState<InboxSession[]>([]);const [unreadBySession, setUnreadBySession] = useState<Record<string, number>>({});+ // Becomes true the first time the server hands us an authoritative whole-account+ // unread map. Until then ``totalUnread`` is only the empty-map default of 0,+ // which must NOT drive the app-icon badge: the push service worker may have set+ // a real badge while the app was closed, so a premature ``clearAppBadge()`` on a+ // slow or failed initial load would wipe a still-accurate count. (The realtime+ // session.updated/archived merges adjust a prior map, so they are not themselves+ // a first authoritative load and deliberately do not flip this.)+ const [unreadLoaded, setUnreadLoaded] = useState(false);const [nextCursor, setNextCursor] = useState<string | null>(null);const [loading, setLoading] = useState(false);const [loadingMore, setLoadingMore] = useState(false);@@ -90,19 +98,28 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>// rerun never collapses a multi-page feed back to page one.const initialFetched = useRef(false);+ // One home for "an authoritative unread map arrived": set the map and flip+ // ``unreadLoaded`` together so the two can never drift apart. Every whole-account+ // write (refresh / reconcile / markRead / unread.changed) goes through here;+ // stable identity, so it never churns the memoized context value.+ const applyUnreadMap = useCallback((map: Record<string, number>) => {+ setUnreadBySession(map);+ setUnreadLoaded(true);+ }, []);+const refresh = useCallback(async () => {setLoading(true);try {const result = await api.listInbox({ platform: 'avibe', limit: PAGE_SIZE });setInboxSessions(result.sessions);setNextCursor(result.next_cursor);- setUnreadBySession(result.unread_by_session ?? {});+ applyUnreadMap(result.unread_by_session ?? {});} catch (err) {console.error('[inbox] refresh failed', err);} finally {setLoading(false);}- }, [api]);+ }, [api, applyUnreadMap]);const loadMore = useCallback(async () => {const cursor = cursorRef.current;@@ -125,9 +142,9 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>// The unread map is authoritative for badges; the card's unread styling// derives from it, so clearing here clears the dot without touching the// feed order (a read doesn't change last activity).- setUnreadBySession(result.unread_by_session ?? {});+ applyUnreadMap(result.unread_by_session ?? {});},- [api],+ [api, applyUnreadMap],);// Resume reconcile: re-read the feed WITHOUT collapsing pagination. A@@ -153,7 +170,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>return merged;});// Whole-account unread map (not paginated) — always authoritative.- setUnreadBySession(result.unread_by_session ?? {});+ applyUnreadMap(result.unread_by_session ?? {});// Cursor: the loaded feed is always a contiguous run from the top, and// this reads the newest `limit` rows. If the read shares ANY row with what// we had (overlap), the two runs are contiguous — no gap below the read —@@ -168,7 +185,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>} catch (err) {console.error('[inbox] reconcile failed', err);}- }, [api]);+ }, [api, applyUnreadMap]);useEffect(() => {// First mount loads page one; every later rerun reconciles the loaded window@@ -197,7 +214,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>},onInboxUnreadChanged: (data) => {if (data?.unread_by_session) {- setUnreadBySession(data.unread_by_session);+ applyUnreadMap(data.unread_by_session);}},onSessionActivity: (data) => {@@ -221,7 +238,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>},}, { reconnect: connectionEpoch > 0 });return disconnect;- }, [api, refresh, reconcile, connectionEpoch]);+ }, [api, refresh, reconcile, connectionEpoch, applyUnreadMap]);// Recover after the OS suspended us. A backgrounded mobile PWA has its page// frozen and its SSE socket dropped, and the broker never replays the gap; on@@ -254,6 +271,28 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>[unreadBySession],);+ // Mirror the unread 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+ // 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.+ useEffect(() => {+ const nav = navigator as Navigator & {+ setAppBadge?: (contents?: number) => Promise<void>;+ clearAppBadge?: () => Promise<void>;+ };+ if (!('setAppBadge' in nav)) return;+ if (!unreadLoaded) return;+ const op = totalUnread > 0 ? nav.setAppBadge?.(totalUnread) : nav.clearAppBadge?.();+ void op?.catch?.(() => {});+ }, [totalUnread, unreadLoaded]);+const value = useMemo<InboxState>(() => ({inboxSessions,