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
fix(ui): refine Web Push delivery behavior (#439)
Call Whitef27d9f464bea
diff --git a/core/session_turns.py b/core/session_turns.pyindex d45b563a5..9862e16a4 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -21,6 +21,7 @@ import loggingfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Callable, Optional+from core.web_push_notifications import WEB_PUSH_USER_KEY_METADATA, WEB_PUSH_USER_KEYS_METADATAfrom core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turnif TYPE_CHECKING:@@ -379,6 +380,20 @@ class SessionTurnManager:]if not texts and not queued_attachments:return False+ user_owners = list(+ dict.fromkeys(+ owner.strip()+ for r in segment+ if isinstance((owner := (r.get("metadata") or {}).get(WEB_PUSH_USER_KEY_METADATA)), str)+ and owner.strip()+ )+ )+ user_owner = user_owners[0] if len(user_owners) == 1 else None+ user_metadata = None+ if user_owner:+ user_metadata = {WEB_PUSH_USER_KEY_METADATA: user_owner}+ elif user_owners:+ user_metadata = {WEB_PUSH_USER_KEYS_METADATA: user_owners}attachment_specs = resolve_attachment_specs(conn, session_id=session_id, attachments=queued_attachments)@@ -392,6 +407,8 @@ class SessionTurnManager:message_type="user",text="\n".join(texts),content={"attachments": queued_attachments} if queued_attachments else None,+ metadata=user_metadata,+ author_id=user_owner,)inbox_row = messages_service.get_inbox_session(conn, session_id)except Exception:diff --git a/core/web_push_notifications.py b/core/web_push_notifications.pyindex cd23479bc..3e2b95e6f 100644--- a/core/web_push_notifications.py+++ b/core/web_push_notifications.py@@ -2,18 +2,24 @@from __future__ import annotations+import jsonimport loggingimport threading+import timefrom typing import Any-from sqlalchemy import select+from sqlalchemy import or_, selectfrom storage import web_push_service-from storage.models import agent_sessions+from storage.models import agent_sessions, messageslogger = logging.getLogger(__name__)-_NOTIFIABLE_TYPES = {"result", "notify", "error"}+_NOTIFIABLE_TYPES = {"result", "error"}+_UNREAD_GATED_TYPES = {"result"}+WEB_PUSH_NOTIFICATION_DELAY_SECONDS = 3.0+WEB_PUSH_USER_KEY_METADATA = "_web_push_user_key"+WEB_PUSH_USER_KEYS_METADATA = "_web_push_user_keys"def maybe_notify_inbox_message(message: dict[str, Any] | None, inbox_row: dict[str, Any] | None) -> None:@@ -48,52 +54,132 @@ def maybe_notify_inbox_message(message: dict[str, Any] | None, inbox_row: dict[sthread.start()-def _user_key_for_session(conn: Any, session_id: str | None) -> str | None:- if not session_id:- return None+def _message_still_unread(conn: Any, message_id: str | None) -> bool:+ if not message_id:+ return Falserow = conn.execute(- select(agent_sessions.c.metadata_json).where(agent_sessions.c.id == session_id)+ select(messages.c.type, messages.c.read_at)+ .where(messages.c.id == message_id)+ .where(messages.c.platform == "avibe")+ .where(messages.c.author == "agent")+ .where(messages.c.type.in_(_NOTIFIABLE_TYPES))).first()- if row is None:- return None- try:- import json+ return bool(row is not None and (row[0] not in _UNREAD_GATED_TYPES or row[1] is None))- metadata = json.loads(row[0] or "{}")- except Exception:- return None- user_key = metadata.get("_web_push_user_key") if isinstance(metadata, dict) else None++def _metadata_user_keys(metadata: dict[str, Any]) -> list[str]:+ keys: list[str] = []++ user_key = metadata.get(WEB_PUSH_USER_KEY_METADATA)if isinstance(user_key, str) and user_key.strip():- return user_key- return _local_fallback_user_key()+ keys.append(user_key.strip())+ user_keys = metadata.get(WEB_PUSH_USER_KEYS_METADATA)+ if isinstance(user_keys, list):+ keys.extend(key.strip() for key in user_keys if isinstance(key, str) and key.strip())-def _local_fallback_user_key() -> str | None:+ return list(dict.fromkeys(keys))+++def _web_push_user_keys_for_message(conn: Any, message_id: str | None) -> list[str]:+ """Resolve trusted browser owners for a Workbench agent message.++ New sessions do not write a Web Push owner field: that made future behavior+ depend on session creation time. For upgraded rows, still honor the legacy+ stored session owner, but only after checking newer trusted user-message+ metadata.+ """++ if not message_id:+ return []+ agent_row = conn.execute(+ select(messages.c.session_id, messages.c.created_at, messages.c.id)+ .where(messages.c.id == message_id)+ .where(messages.c.platform == "avibe")+ .where(messages.c.author == "agent")+ .where(messages.c.type.in_(_NOTIFIABLE_TYPES))+ ).first()+ if not agent_row or not agent_row[0]:+ return []+ session_id, created_at, row_id = agent_row++ user_rows = conn.execute(+ select(messages.c.metadata_json)+ .where(messages.c.session_id == session_id)+ .where(messages.c.platform == "avibe")+ .where(messages.c.author == "user")+ .where(messages.c.type == "user")+ .where(messages.c.metadata_json.is_not(None))+ .where(+ or_(+ messages.c.metadata_json.contains(WEB_PUSH_USER_KEY_METADATA),+ messages.c.metadata_json.contains(WEB_PUSH_USER_KEYS_METADATA),+ )+ )+ .where(+ (messages.c.created_at < created_at)+ | ((messages.c.created_at == created_at) & (messages.c.id < row_id))+ )+ .order_by(messages.c.created_at.desc(), messages.c.id.desc())+ ).all()+ for user_row in user_rows:+ try:+ user_keys = _metadata_user_keys(json.loads(user_row[0] or "{}") or {})+ except (TypeError, ValueError):+ continue+ if user_keys:+ return user_keys++ session_metadata = conn.execute(+ select(agent_sessions.c.metadata_json).where(agent_sessions.c.id == session_id)+ ).scalar_one_or_none()+ try:+ return _metadata_user_keys(json.loads(session_metadata or "{}") or {})+ except (TypeError, ValueError):+ return []+++def _remote_access_enabled() -> bool:try:from core.services import settings as settings_serviceconfig = settings_service.load_config()+ cloud = getattr(getattr(config, "remote_access", None), "vibe_cloud", None)+ return bool(cloud is not None and cloud.enabled)except Exception:- logger.warning("web push: could not load config for local fallback", exc_info=True)- return None- cloud = getattr(getattr(config, "remote_access", None), "vibe_cloud", None)- if cloud is not None and getattr(cloud, "enabled", False):- return None- return "local"+ logger.debug("web push: could not load remote access config", exc_info=True)+ return Truedef _send_to_enabled_subscriptions(payload: dict[str, Any]) -> None:from core.web_push import send_web_pushfrom storage.db import create_sqlite_engine+ delay = max(0.0, WEB_PUSH_NOTIFICATION_DELAY_SECONDS)+ if delay:+ time.sleep(delay)+engine = create_sqlite_engine()try:with engine.connect() as conn:- user_key = _user_key_for_session(conn, payload.get("session_id"))- if user_key is None:- logger.debug("web push: skip notification for session without push owner")+ if not _message_still_unread(conn, payload.get("message_id")):+ logger.debug("web push: skip notification for message already read or missing")+ return+ 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 []+ if not user_keys:+ logger.debug("web push: skip notification without a unique subscription owner")return- subscriptions = web_push_service.list_enabled(conn, user_key=user_key)+ subscriptions = []+ seen_endpoints: set[str] = set()+ for user_key in user_keys:+ for subscription in web_push_service.list_enabled(conn, user_key=user_key):+ endpoint = subscription.get("endpoint")+ if not isinstance(endpoint, str) or endpoint in seen_endpoints:+ continue+ seen_endpoints.add(endpoint)+ subscriptions.append(subscription)for subscription in subscriptions:try:send_web_push(subscription=subscription, payload=payload)diff --git a/storage/web_push_service.py b/storage/web_push_service.pyindex 7e7473c7a..87700f61b 100644--- a/storage/web_push_service.py+++ b/storage/web_push_service.py@@ -119,6 +119,38 @@ def list_enabled(conn: Connection, *, user_key: str | None = None) -> list[dict[return [_row_to_dict(row) for row in rows]+def has_enabled_user_key(conn: Connection, *, user_key: str) -> bool:+ if not isinstance(user_key, str) or not user_key.strip():+ return False+ row = conn.execute(+ select(web_push_subscriptions.c.id)+ .where(web_push_subscriptions.c.enabled == 1)+ .where(web_push_subscriptions.c.user_key == user_key.strip())+ .limit(1)+ ).first()+ return row is not None+++def get_enabled_by_endpoint(+ conn: Connection,+ *,+ endpoint: str,+ user_key: str | None = None,+) -> dict[str, Any] | None:+ endpoint = endpoint.strip() if isinstance(endpoint, str) else ""+ if not endpoint:+ return None+ stmt = (+ select(web_push_subscriptions)+ .where(web_push_subscriptions.c.endpoint == endpoint)+ .where(web_push_subscriptions.c.enabled == 1)+ )+ if user_key is not None:+ stmt = stmt.where(web_push_subscriptions.c.user_key == user_key)+ row = conn.execute(stmt).mappings().first()+ return _row_to_dict(row) if row else None++def mark_send_success(conn: Connection, *, endpoint: str) -> None:now = _utc_now_iso()conn.execute(diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 02fc2fbca..9b0fed091 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -550,8 +550,28 @@ def test_async_dispatch_flushes_queue_on_turn_end(monkeypatch, tmp_path):# real flow — queued rows only exist during an active turn).if text == "first turn":with engine.begin() as conn:- messages_service.enqueue_queued(conn, scope_id=scope_id, session_id=session_id, text="q1")- messages_service.enqueue_queued(conn, scope_id=scope_id, session_id=session_id, text="q2")+ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id=session_id,+ platform="avibe",+ author="user",+ source="user",+ message_type=messages_service.QUEUED_TYPE,+ text="q1",+ author_id="remote:user-a",+ metadata={"_web_push_user_key": "remote:user-a"},+ )+ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id=session_id,+ platform="avibe",+ author="user",+ source="user",+ message_type=messages_service.QUEUED_TYPE,+ text="q2",+ )controller.mark_turn_complete(ctx) # release each turn immediatelyreturn None@@ -575,6 +595,8 @@ def test_async_dispatch_flushes_queue_on_turn_end(monkeypatch, tmp_path):assert messages_service.list_queued(conn, session_id) == []transcript = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))assert [m["text"] for m in transcript["messages"]] == ["q1\nq2"], "the flush persisted one merged user row"+ assert transcript["messages"][0]["author_id"] == "remote:user-a"+ assert transcript["messages"][0]["metadata"]["_web_push_user_key"] == "remote:user-a"def test_cancel_does_not_flush_queue(monkeypatch, tmp_path):@@ -1024,6 +1046,53 @@ def test_flush_segments_user_then_scheduled_in_order(tmp_path, monkeypatch):assert runs[-1][2].platform_specific["suppress_delivery"] is True+def test_flush_mixed_owner_user_rows_preserves_owner_list(tmp_path, monkeypatch):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))++ from core.services import sessions as sessions_service+ from storage import messages_service+ from storage.db import create_sqlite_engine+ from storage.importer import ensure_sqlite_state+ from storage.settings_service import upsert_scope++ ensure_sqlite_state()+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = upsert_scope(+ conn, platform="avibe", scope_type="project", native_id="proj_mixed_owner", now="2026-05-31T00:00:00Z"+ )+ _seed_project_workdir(conn, scope_id, tmp_path)+ session = sessions_service.create_session(+ conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"+ )+ for text, owner in (("u1", "remote:user-a"), ("u2", "remote:user-b")):+ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id=session["id"],+ platform="avibe",+ author="user",+ source="user",+ message_type=messages_service.QUEUED_TYPE,+ text=text,+ author_id=owner,+ metadata={"_web_push_user_key": owner},+ )++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session["id"])) is True+ assert [(t, s) for t, s, _ in runs] == [("u1\nu2", SOURCE_HUMAN)]+ with engine.connect() as conn:+ transcript = messages_service.list_session_messages(conn, session_id=session["id"], types=("user",))+ assert transcript["messages"][0]["author_id"] is None+ assert transcript["messages"][0]["metadata"]["_web_push_user_keys"] == [+ "remote:user-a",+ "remote:user-b",+ ]+ assert "_web_push_user_key" not in transcript["messages"][0]["metadata"]++def test_capture_scheduled_provenance_keeps_delivery_drops_routing():"""capture_scheduled_provenance keeps the delivery / attribution keys — notablydelivery_override, the redirect MessageDispatcher._get_target_context uses — anddiff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.pyindex d5e3575c3..3109680a1 100644--- a/tests/test_ui_server_fastapi.py+++ b/tests/test_ui_server_fastapi.py@@ -235,13 +235,14 @@ def test_web_push_subscription_routes_roundtrip(monkeypatch, tmp_path):assert created_body["subscription"]["enabled"] is Trueassert created_body["subscription"]["device_label"] == "iPhone"- status = client.get("/api/web-push/status")+ status = client.post("/api/web-push/status", json={"endpoint": subscription["endpoint"]}, headers=headers)assert status.status_code == 200status_body = status.get_json()assert status_body["ok"] is Trueassert status_body["configured"] is Trueassert status_body["public_key"]assert status_body["subscription_count"] == 1+ assert status_body["current_subscription_enabled"] is Trueremoved = client.delete("/api/web-push/subscriptions",@@ -251,8 +252,9 @@ def test_web_push_subscription_routes_roundtrip(monkeypatch, tmp_path):assert removed.status_code == 200assert removed.get_json() == {"ok": True, "disabled": True}- status_after = client.get("/api/web-push/status")+ status_after = client.post("/api/web-push/status", json={"endpoint": subscription["endpoint"]}, headers=headers)assert status_after.get_json()["subscription_count"] == 0+ assert status_after.get_json()["current_subscription_enabled"] is Falsedef test_web_push_unsubscribe_is_scoped_to_current_user(monkeypatch, tmp_path):@@ -311,14 +313,22 @@ def test_web_push_test_route_sends_to_enabled_subscriptions(monkeypatch, tmp_pat},}- empty = client.post("/api/web-push/test", json={}, headers=headers)+ missing_endpoint = client.post("/api/web-push/test", json={}, headers=headers)+ assert missing_endpoint.status_code == 400+ assert missing_endpoint.get_json()["error"] == "endpoint_required"++ empty = client.post(+ "/api/web-push/test",+ json={"endpoint": subscription["endpoint"]},+ headers=headers,+ )assert empty.status_code == 404assert empty.get_json()["error"] == "no_subscription"client.post("/api/web-push/subscriptions", json={"subscription": subscription}, headers=headers)sent = client.post("/api/web-push/test",- json={"title": "Hello", "body": "World", "url": "/inbox"},+ json={"title": "Hello", "body": "World", "url": "/inbox", "endpoint": subscription["endpoint"]},headers=headers,)@@ -328,14 +338,53 @@ def test_web_push_test_route_sends_to_enabled_subscriptions(monkeypatch, tmp_patassert sends[0][1]["title"] == "Hello"-def test_sessions_create_stores_web_push_owner(monkeypatch, tmp_path):+def test_web_push_test_route_targets_current_endpoint_only(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ ensure_sqlite_state()++ sends = []+ monkeypatch.setattr(+ "core.web_push.send_web_push",+ lambda *, subscription, payload: sends.append((subscription, payload)),+ )++ client = app.test_client()+ headers = csrf_headers(client)+ subscriptions = [+ {+ "endpoint": "https://push.example.test/sub/desktop",+ "keys": {"p256dh": "desktop-key", "auth": "desktop-auth"},+ },+ {+ "endpoint": "https://push.example.test/sub/mobile",+ "keys": {"p256dh": "mobile-key", "auth": "mobile-auth"},+ },+ ]+ for subscription in subscriptions:+ client.post("/api/web-push/subscriptions", json={"subscription": subscription}, headers=headers)++ sent = client.post(+ "/api/web-push/test",+ json={+ "title": "Hello",+ "body": "World",+ "url": "/inbox",+ "endpoint": subscriptions[0]["endpoint"],+ },+ headers=headers,+ )++ assert sent.status_code == 200+ assert sent.get_json() == {"ok": True, "sent": 1, "failed": 0}+ assert [send[0]["endpoint"] for send in sends] == [subscriptions[0]["endpoint"]]+++def test_sessions_create_preserves_metadata_without_web_push_owner(monkeypatch, tmp_path):from storage.db import create_sqlite_enginefrom storage.projects_service import create_projectmonkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))ensure_sqlite_state()- monkeypatch.setattr(ui_server, "_web_push_user_key", lambda: "remote:user-a")-engine = create_sqlite_engine()project_dir = tmp_path / "project"project_dir.mkdir()@@ -352,4 +401,4 @@ def test_sessions_create_stores_web_push_owner(monkeypatch, tmp_path):assert response.status_code == 201metadata = response.get_json()["metadata"]assert metadata["client"] == "test"- assert metadata["_web_push_user_key"] == "remote:user-a"+ assert "_web_push_user_key" not in metadatadiff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.pyindex 4386884a2..450b8ee79 100644--- a/tests/test_ui_session_stream.py+++ b/tests/test_ui_session_stream.py@@ -89,17 +89,22 @@ def test_route_fire_and_forgets_dispatch(isolated_state, tmp_path):dispatch_mock = AsyncMock(return_value={"status_code": 202, "body": {"ok": True, "session_id": session_id}})- with patch("vibe.internal_client.dispatch_async", dispatch_mock):+ with (+ patch("vibe.internal_client.dispatch_async", dispatch_mock),+ patch("vibe.ui_server._web_push_user_key", return_value="remote:user-a"),+ ):client = app.test_client()headers = csrf_headers(client)response = client.post(f"/api/sessions/{session_id}/messages",- json={"text": "no stream"},+ json={"text": "no stream", "author_id": "remote:spoofed"},headers=headers,)assert response.status_code == 201payload = response.get_json()assert payload["author"] == "user"+ assert payload["author_id"] == "remote:user-a"+ assert payload["metadata"]["_web_push_user_key"] == "remote:user-a"assert payload["text"] == "no stream"# The turn was kicked off fire-and-forget with the session + text.dispatch_mock.assert_awaited_once()diff --git a/tests/test_web_push_notifications.py b/tests/test_web_push_notifications.pyindex 0b4174e96..f6e27bb06 100644--- a/tests/test_web_push_notifications.py+++ b/tests/test_web_push_notifications.py@@ -1,9 +1,9 @@from __future__ import annotationsfrom core import web_push_notifications-from storage.importer import ensure_sqlite_state-from storage import web_push_service+from storage import messages_service, web_push_servicefrom storage.db import create_sqlite_engine+from storage.importer import ensure_sqlite_statefrom storage.models import agent_sessionsfrom storage.settings_service import upsert_scope@@ -74,8 +74,22 @@ def test_maybe_notify_inbox_message_skips_non_notifiable(monkeypatch):assert calls == []+ web_push_notifications.maybe_notify_inbox_message(+ {+ "id": "msg_2",+ "platform": "avibe",+ "author": "agent",+ "type": "notify",+ "session_id": "ses_1",+ "text": "process log",+ },+ {"title": "Build fix"},+ )++ assert calls == []+-def test_send_to_enabled_subscriptions_uses_session_owner(monkeypatch, tmp_path):+def test_send_to_enabled_subscriptions_waits_then_sends_to_owner_devices(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))ensure_sqlite_state()engine = create_sqlite_engine()@@ -84,20 +98,42 @@ def test_send_to_enabled_subscriptions_uses_session_owner(monkeypatch, tmp_path)scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_x", now=now)conn.execute(agent_sessions.insert().values(- id="ses_owner",+ id="ses_push",scope_id=scope_id,agent_backend="claude",agent_variant="default",- session_anchor="ses_owner",+ session_anchor="ses_push",native_session_id="",- title="Owner",+ title="Push",status="active",- metadata_json='{"_web_push_user_key":"remote:user-a"}',+ metadata_json="{}",created_at=now,updated_at=now,last_active_at=now,))+ message = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_push",+ 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",+ )+ message = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_push",+ platform="avibe",+ author="agent",+ source="agent",+ message_type="result",+ text="Done",+ )web_push_service.upsert_subscription(conn,user_key="remote:user-a",@@ -115,26 +151,431 @@ def test_send_to_enabled_subscriptions_uses_session_owner(monkeypatch, tmp_path)},)+ sleeps = []sends = []+ monkeypatch.setattr(web_push_notifications.time, "sleep", lambda seconds: sleeps.append(seconds))monkeypatch.setattr("core.web_push.send_web_push",lambda *, subscription, payload: sends.append((subscription, payload)),)web_push_notifications._send_to_enabled_subscriptions(- {"title": "Owner", "body": "Done", "session_id": "ses_owner"}+ {"title": "Push", "body": "Done", "session_id": "ses_push", "message_id": message["id"]})- assert [send[0]["endpoint"] for send in sends] == ["https://push.example.test/a"]+ assert sleeps == [3.0]+ assert [send[0]["endpoint"] for send in sends] == [+ "https://push.example.test/a",+ ]+++def test_send_to_enabled_subscriptions_uses_legacy_session_owner(monkeypatch, tmp_path):+ 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_legacy", now=now)+ conn.execute(+ agent_sessions.insert().values(+ id="ses_legacy_owner",+ scope_id=scope_id,+ agent_backend="claude",+ agent_variant="default",+ session_anchor="ses_legacy_owner",+ native_session_id="",+ title="Legacy Owner",+ status="active",+ metadata_json='{"_web_push_user_key":"remote:user-a"}',+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )+ message = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_legacy_owner",+ platform="avibe",+ author="agent",+ source="agent",+ message_type="result",+ text="Done",+ )+ for key in ("remote:user-a", "remote:user-b"):+ web_push_service.upsert_subscription(+ conn,+ user_key=key,+ payload={+ "endpoint": f"https://push.example.test/{key}",+ "keys": {"p256dh": f"{key}-p256dh", "auth": f"{key}-auth"},+ },+ )++ sends = []+ monkeypatch.setattr(web_push_notifications.time, "sleep", lambda _seconds: None)+ monkeypatch.setattr(web_push_notifications, "_remote_access_enabled", lambda: True)+ monkeypatch.setattr(+ "core.web_push.send_web_push",+ lambda *, subscription, payload: sends.append((subscription, payload)),+ )++ web_push_notifications._send_to_enabled_subscriptions(+ {+ "title": "Legacy Owner",+ "body": "Done",+ "session_id": "ses_legacy_owner",+ "message_id": message["id"],+ }+ )++ assert [send[0]["endpoint"] for send in sends] == ["https://push.example.test/remote:user-a"]+++def test_send_to_enabled_subscriptions_prefers_message_owner_over_legacy_session(monkeypatch, tmp_path):+ 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_new_owner", now=now)+ conn.execute(+ agent_sessions.insert().values(+ id="ses_new_owner",+ scope_id=scope_id,+ agent_backend="claude",+ agent_variant="default",+ session_anchor="ses_new_owner",+ native_session_id="",+ title="New Owner",+ status="active",+ metadata_json='{"_web_push_user_key":"remote:user-a"}',+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )+ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_new_owner",+ platform="avibe",+ author="user",+ source="user",+ author_id="remote:user-b",+ metadata={"_web_push_user_key": "remote:user-b"},+ message_type="user",+ text="Please finish",+ )+ message = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_new_owner",+ platform="avibe",+ author="agent",+ source="agent",+ message_type="result",+ text="Done",+ )+ for key in ("remote:user-a", "remote:user-b"):+ web_push_service.upsert_subscription(+ conn,+ user_key=key,+ payload={+ "endpoint": f"https://push.example.test/{key}",+ "keys": {"p256dh": f"{key}-p256dh", "auth": f"{key}-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": "New Owner", "body": "Done", "session_id": "ses_new_owner", "message_id": message["id"]}+ )++ assert [send[0]["endpoint"] for send in sends] == ["https://push.example.test/remote:user-b"]+++def test_send_to_enabled_subscriptions_sends_to_merged_prompt_owners(monkeypatch, tmp_path):+ 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_multi_owner", now=now)+ conn.execute(+ agent_sessions.insert().values(+ id="ses_multi_owner",+ scope_id=scope_id,+ agent_backend="claude",+ agent_variant="default",+ session_anchor="ses_multi_owner",+ native_session_id="",+ title="Multi Owner",+ 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_multi_owner",+ platform="avibe",+ author="user",+ source="user",+ message_type="user",+ text="u1\nu2",+ metadata={"_web_push_user_keys": ["remote:user-a", "remote:user-b"]},+ )+ message = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_multi_owner",+ platform="avibe",+ author="agent",+ source="agent",+ message_type="result",+ text="Done",+ )+ for key in ("remote:user-a", "remote:user-b", "remote:user-c"):+ web_push_service.upsert_subscription(+ conn,+ user_key=key,+ payload={+ "endpoint": f"https://push.example.test/{key}",+ "keys": {"p256dh": f"{key}-p256dh", "auth": f"{key}-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": "Multi Owner", "body": "Done", "session_id": "ses_multi_owner", "message_id": message["id"]}+ )++ assert [send[0]["endpoint"] for send in sends] == [+ "https://push.example.test/remote:user-a",+ "https://push.example.test/remote:user-b",+ ]+++def test_send_to_enabled_subscriptions_ignores_untrusted_author_id(monkeypatch, tmp_path):+ 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_spoof", now=now)+ conn.execute(+ agent_sessions.insert().values(+ id="ses_spoof",+ scope_id=scope_id,+ agent_backend="claude",+ agent_variant="default",+ session_anchor="ses_spoof",+ native_session_id="",+ title="Spoof",+ 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_spoof",+ platform="avibe",+ author="user",+ source="user",+ author_id="remote:user-b",+ message_type="user",+ text="Spoof owner",+ )+ message = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_spoof",+ platform="avibe",+ author="agent",+ source="agent",+ message_type="result",+ text="Done",+ )+ for key in ("remote:user-a", "remote:user-b"):+ web_push_service.upsert_subscription(+ conn,+ user_key=key,+ payload={+ "endpoint": f"https://push.example.test/{key}",+ "keys": {"p256dh": f"{key}-p256dh", "auth": f"{key}-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": "Spoof", "body": "Done", "session_id": "ses_spoof", "message_id": message["id"]}+ )++ assert sends == []+++def test_send_to_enabled_subscriptions_ignores_queued_owner(monkeypatch, tmp_path):+ 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_queued", now=now)+ conn.execute(+ agent_sessions.insert().values(+ id="ses_queued_owner",+ scope_id=scope_id,+ agent_backend="claude",+ agent_variant="default",+ session_anchor="ses_queued_owner",+ native_session_id="",+ title="Queued Owner",+ 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_queued_owner",+ platform="avibe",+ author="user",+ source="user",+ message_type=messages_service.QUEUED_TYPE,+ metadata={"_web_push_user_key": "remote:user-b"},+ text="queued while prior turn runs",+ )+ message = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_queued_owner",+ platform="avibe",+ author="agent",+ source="agent",+ message_type="result",+ text="Prior turn result",+ )+ web_push_service.upsert_subscription(+ conn,+ user_key="remote:user-b",+ payload={+ "endpoint": "https://push.example.test/b",+ "keys": {"p256dh": "b-key", "auth": "b-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": "Queued Owner",+ "body": "Prior turn result",+ "session_id": "ses_queued_owner",+ "message_id": message["id"],+ }+ )++ assert sends == []-def test_send_to_enabled_subscriptions_uses_local_fallback_for_legacy_local_session(monkeypatch, tmp_path):+def test_send_to_enabled_subscriptions_skips_messages_marked_read_during_delay(monkeypatch, tmp_path):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_x", now=now)+ conn.execute(+ agent_sessions.insert().values(+ id="ses_read",+ scope_id=scope_id,+ agent_backend="claude",+ agent_variant="default",+ session_anchor="ses_read",+ native_session_id="",+ title="Read",+ status="active",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )+ message = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_read",+ platform="avibe",+ author="agent",+ source="agent",+ message_type="result",+ text="Done",+ )+ messages_service.mark_session_read(conn, "ses_read", until_message_id=message["id"])+ web_push_service.upsert_subscription(+ conn,+ user_key="local",+ payload={+ "endpoint": "https://push.example.test/local",+ "keys": {"p256dh": "local-key", "auth": "local-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": "Read", "body": "Done", "session_id": "ses_read", "message_id": message["id"]}+ )++ assert sends == []+++def test_send_to_enabled_subscriptions_skips_unowned_remote_single_owner(monkeypatch, tmp_path):+ 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_single", now=now)conn.execute(agent_sessions.insert().values(id="ses_legacy",@@ -151,6 +592,72 @@ def test_send_to_enabled_subscriptions_uses_local_fallback_for_legacy_local_sesslast_active_at=now,))+ message = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_legacy",+ platform="avibe",+ author="agent",+ source="agent",+ message_type="result",+ text="Done",+ )+ 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": "Legacy", "body": "Done", "session_id": "ses_legacy", "message_id": message["id"]}+ )++ assert sends == []+++def test_send_to_enabled_subscriptions_falls_back_to_local_owner(monkeypatch, tmp_path):+ 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_local", now=now)+ conn.execute(+ agent_sessions.insert().values(+ id="ses_local",+ scope_id=scope_id,+ agent_backend="claude",+ agent_variant="default",+ session_anchor="ses_local",+ native_session_id="",+ title="Local",+ status="active",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )+ message = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_local",+ platform="avibe",+ author="agent",+ source="agent",+ message_type="result",+ text="Done",+ )web_push_service.upsert_subscription(conn,user_key="local",@@ -161,35 +668,36 @@ def test_send_to_enabled_subscriptions_uses_local_fallback_for_legacy_local_sess)sends = []+ monkeypatch.setattr(web_push_notifications.time, "sleep", lambda _seconds: None)+ monkeypatch.setattr(web_push_notifications, "_remote_access_enabled", lambda: False)monkeypatch.setattr("core.web_push.send_web_push",lambda *, subscription, payload: sends.append((subscription, payload)),)- monkeypatch.setattr(web_push_notifications, "_local_fallback_user_key", lambda: "local")web_push_notifications._send_to_enabled_subscriptions(- {"title": "Legacy", "body": "Done", "session_id": "ses_legacy"}+ {"title": "Local", "body": "Done", "session_id": "ses_local", "message_id": message["id"]})assert [send[0]["endpoint"] for send in sends] == ["https://push.example.test/local"]-def test_send_to_enabled_subscriptions_skips_unknown_owner_when_remote_access_enabled(monkeypatch, tmp_path):+def test_send_to_enabled_subscriptions_skips_local_fallback_when_remote_access_enabled(monkeypatch, tmp_path):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_x", now=now)+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_remote", now=now)conn.execute(agent_sessions.insert().values(- id="ses_legacy",+ id="ses_remote_unowned",scope_id=scope_id,agent_backend="claude",agent_variant="default",- session_anchor="ses_legacy",+ session_anchor="ses_remote_unowned",native_session_id="",- title="Legacy",+ title="Remote",status="active",metadata_json="{}",created_at=now,@@ -197,6 +705,16 @@ def test_send_to_enabled_subscriptions_skips_unknown_owner_when_remote_access_enlast_active_at=now,))+ message = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_remote_unowned",+ platform="avibe",+ author="agent",+ source="agent",+ message_type="result",+ text="Done",+ )web_push_service.upsert_subscription(conn,user_key="local",@@ -207,14 +725,140 @@ def test_send_to_enabled_subscriptions_skips_unknown_owner_when_remote_access_en)sends = []+ monkeypatch.setattr(web_push_notifications.time, "sleep", lambda _seconds: None)+ monkeypatch.setattr(web_push_notifications, "_remote_access_enabled", lambda: True)+ monkeypatch.setattr(+ "core.web_push.send_web_push",+ lambda *, subscription, payload: sends.append((subscription, payload)),+ )++ web_push_notifications._send_to_enabled_subscriptions(+ {"title": "Remote", "body": "Done", "session_id": "ses_remote_unowned", "message_id": message["id"]}+ )++ assert sends == []+++def test_send_to_enabled_subscriptions_sends_terminal_error_with_owner(monkeypatch, tmp_path):+ 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_error", now=now)+ conn.execute(+ agent_sessions.insert().values(+ id="ses_error",+ scope_id=scope_id,+ agent_backend="claude",+ agent_variant="default",+ session_anchor="ses_error",+ native_session_id="",+ title="Error",+ 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_error",+ platform="avibe",+ author="user",+ source="user",+ message_type="user",+ text="Run it",+ metadata={"_web_push_user_key": "remote:user-a"},+ )+ message = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_error",+ platform="avibe",+ author="agent",+ source="agent",+ message_type="error",+ text="Failed",+ read_at=now,+ )+ 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": "Error", "body": "Failed", "session_id": "ses_error", "message_id": message["id"]}+ )++ assert [send[0]["endpoint"] for send in sends] == ["https://push.example.test/a"]+++def test_send_to_enabled_subscriptions_skips_ambiguous_legacy_owner(monkeypatch, tmp_path):+ 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_ambiguous", now=now)+ conn.execute(+ agent_sessions.insert().values(+ id="ses_ambiguous",+ scope_id=scope_id,+ agent_backend="claude",+ agent_variant="default",+ session_anchor="ses_ambiguous",+ native_session_id="",+ title="Ambiguous",+ status="active",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )+ message = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_ambiguous",+ platform="avibe",+ author="agent",+ source="agent",+ message_type="result",+ text="Done",+ )+ for key in ("remote:user-a", "remote:user-b"):+ web_push_service.upsert_subscription(+ conn,+ user_key=key,+ payload={+ "endpoint": f"https://push.example.test/{key}",+ "keys": {"p256dh": f"{key}-p256dh", "auth": f"{key}-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)),)- monkeypatch.setattr(web_push_notifications, "_local_fallback_user_key", lambda: None)web_push_notifications._send_to_enabled_subscriptions(- {"title": "Legacy", "body": "Done", "session_id": "ses_legacy"}+ {"title": "Ambiguous", "body": "Done", "session_id": "ses_ambiguous", "message_id": message["id"]})assert sends == []diff --git a/ui/src/components/workbench/InboxPage.tsx b/ui/src/components/workbench/InboxPage.tsxindex cca522bb0..d8b184a5e 100644--- a/ui/src/components/workbench/InboxPage.tsx+++ b/ui/src/components/workbench/InboxPage.tsx@@ -65,7 +65,7 @@ export const InboxPage: React.FC = () => {return (<div className="mx-auto flex w-full max-w-4xl flex-col gap-6 py-2">{/* Header */}- <div className="flex items-center gap-4">+ <div className="flex flex-wrap items-center gap-4"><div className="flex size-12 shrink-0 items-center justify-center rounded-2xl border border-mint/30 bg-mint/[0.08] text-mint shadow-[0_0_24px_-6px_rgba(91,255,160,0.5)]"><Inbox className="size-5" /></div>@@ -78,25 +78,27 @@ export const InboxPage: React.FC = () => {{t('workbench.inbox.headerCount', { unread: unreadSessions, total: inboxSessions.length })}</p></div>- <button- type="button"- onClick={() => refresh()}- disabled={loading}- className={clsx(- 'flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-[12px] font-medium transition',- loading- ? 'cursor-wait border-border bg-foreground/[0.02] text-muted'- : 'border-border-strong text-foreground hover:bg-foreground/[0.04]',- )}- >- <RefreshCw className={clsx('size-3.5', loading && 'animate-spin')} />- {t('workbench.inbox.refresh')}- </button>+ <div className="flex w-full justify-end sm:w-auto">+ <button+ type="button"+ onClick={() => refresh()}+ disabled={loading}+ className={clsx(+ 'flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-[12px] font-medium transition',+ loading+ ? 'cursor-wait border-border bg-foreground/[0.02] text-muted'+ : 'border-border-strong text-foreground hover:bg-foreground/[0.04]',+ )}+ >+ <RefreshCw className={clsx('size-3.5', loading && 'animate-spin')} />+ {t('workbench.inbox.refresh')}+ </button>+ </div></div>{/* Toolbar */}- <div className="flex items-center gap-2">- <div className="inline-flex items-center gap-1 rounded-lg border border-border-strong bg-surface-2 p-0.5">+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-2">+ <div className="inline-flex w-full items-center gap-1 rounded-lg border border-border-strong bg-surface-2 p-0.5 sm:w-auto">{([{ key: 'unread', label: t('workbench.inbox.filterUnread') },{ key: 'all', label: t('workbench.inbox.filterAll') },@@ -106,7 +108,7 @@ export const InboxPage: React.FC = () => {type="button"onClick={() => setFilter(key)}className={clsx(- 'flex items-center gap-1.5 rounded-md px-3 py-1.5 text-[12px] font-semibold transition',+ 'flex flex-1 items-center justify-center gap-1.5 rounded-md px-3 py-1.5 text-[12px] font-semibold transition sm:flex-none',filter === key? 'bg-mint/[0.10] text-mint shadow-[0_0_12px_-4px_rgba(91,255,160,0.5)]': 'text-muted hover:text-foreground',@@ -117,22 +119,23 @@ export const InboxPage: React.FC = () => {</button>))}</div>- <div className="flex-1" />- <WebPushControl />- <button- type="button"- onClick={onMarkAllRead}- disabled={totalUnread === 0}- className={clsx(- 'flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-[12px] font-semibold transition',- totalUnread === 0- ? 'cursor-not-allowed border-border bg-foreground/[0.02] text-muted'- : 'border-mint/30 bg-mint/[0.06] text-mint hover:bg-mint/[0.12]',- )}- >- <CheckCheck className="size-3.5" />- {t('workbench.inbox.markAllRead')}- </button>+ <div className="flex min-w-0 flex-wrap items-center gap-2 sm:ml-auto sm:justify-end">+ <WebPushControl />+ <button+ type="button"+ onClick={onMarkAllRead}+ disabled={totalUnread === 0}+ className={clsx(+ 'flex shrink-0 items-center gap-1.5 rounded-md border px-3 py-1.5 text-[12px] font-semibold transition',+ totalUnread === 0+ ? 'cursor-not-allowed border-border bg-foreground/[0.02] text-muted'+ : 'border-mint/30 bg-mint/[0.06] text-mint hover:bg-mint/[0.12]',+ )}+ >+ <CheckCheck className="size-3.5" />+ {t('workbench.inbox.markAllRead')}+ </button>+ </div></div>{/* Empty state */}diff --git a/ui/src/components/workbench/WebPushControl.tsx b/ui/src/components/workbench/WebPushControl.tsxindex 2c4466d4c..90e098206 100644--- a/ui/src/components/workbench/WebPushControl.tsx+++ b/ui/src/components/workbench/WebPushControl.tsx@@ -32,11 +32,9 @@ export const WebPushControl: React.FC = () => {setStatus(nextSupport.reason === 'ios_requires_standalone' ? 'needs_install' : 'unsupported');return;}- const [existing, serverStatus] = await Promise.all([- getExistingWebPushSubscription(),- api.getWebPushStatus().catch(() => null),- ]);- setStatus(existing && serverStatus && serverStatus.subscription_count > 0 ? 'enabled' : 'disabled');+ const existing = await getExistingWebPushSubscription();+ const serverStatus = await api.getWebPushStatus(existing?.endpoint).catch(() => null);+ setStatus(existing && serverStatus?.current_subscription_enabled ? 'enabled' : 'disabled');};useEffect(() => {@@ -69,10 +67,17 @@ export const WebPushControl: React.FC = () => {const onTest = async () => {setTesting(true);try {+ const subscription = await getExistingWebPushSubscription();+ if (!subscription?.endpoint) {+ showToast(t('workbench.inbox.notifications.testFailed', { count: 0 }), 'error');+ await refresh();+ return;+ }const result = await api.sendWebPushTest({title: t('workbench.inbox.notifications.testTitle'),body: t('workbench.inbox.notifications.testBody'),url: '/inbox',+ endpoint: subscription.endpoint,});if (result.ok) {showToast(t('workbench.inbox.notifications.testSent'), 'success');@@ -118,18 +123,34 @@ export const WebPushControl: React.FC = () => {if (status === 'enabled') {return (- <div className="flex items-center gap-2">- <Badge variant="success" className="h-8 rounded-lg px-3">+ <div className="flex min-w-0 flex-wrap items-center gap-2">+ <Badge variant="success" className="h-8 min-w-0 rounded-lg px-3"><Bell className="size-3" />- {support?.supported && support.requiresStandalone- ? t('workbench.inbox.notifications.enabledPwa')- : t('workbench.inbox.notifications.enabled')}+ <span className="truncate">+ {support?.supported && support.requiresStandalone+ ? t('workbench.inbox.notifications.enabledPwa')+ : t('workbench.inbox.notifications.enabled')}+ </span></Badge>- <Button type="button" variant="secondary" size="xs" onClick={onTest} disabled={testing || busy}>+ <Button+ type="button"+ variant="secondary"+ size="xs"+ onClick={onTest}+ disabled={testing || busy}+ className="shrink-0"+ >{testing ? <Loader2 className="animate-spin" /> : <Bell className="size-3.5" />}{t('workbench.inbox.notifications.test')}</Button>- <Button type="button" variant="ghost" size="xs" onClick={onDisable} disabled={busy || testing}>+ <Button+ type="button"+ variant="ghost"+ size="xs"+ onClick={onDisable}+ disabled={busy || testing}+ className="shrink-0"+ >{busy ? <Loader2 className="animate-spin" /> : <BellOff className="size-3.5" />}{t('workbench.inbox.notifications.disable')}</Button>diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 47f4785bf..f93a3f711 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -27,11 +27,11 @@ export type ApiContextType = {toggleAdmin: (userId: string, isAdmin: boolean, platform?: string) => Promise<any>;removeUser: (userId: string, platform?: string) => Promise<any>;getShowPages: () => Promise<any>;- getWebPushStatus: () => Promise<WebPushStatus>;+ getWebPushStatus: (endpoint?: string) => Promise<WebPushStatus>;getWebPushVapidPublicKey: () => Promise<{ ok: boolean; public_key: string }>;subscribeWebPush: (subscription: PushSubscriptionJSON, deviceLabel?: string) => Promise<WebPushSubscriptionResult>;unsubscribeWebPush: (endpoint: string) => Promise<{ ok: boolean; disabled: boolean }>;- sendWebPushTest: (payload?: { title?: string; body?: string; url?: string }) => Promise<WebPushTestResult>;+ sendWebPushTest: (payload?: { title?: string; body?: string; url?: string; endpoint?: string }) => Promise<WebPushTestResult>;setShowPageVisibility: (sessionId: string, visibility: string) => Promise<any>;rotateShowPageShare: (sessionId: string) => Promise<any>;getBindCodes: () => Promise<any>;@@ -985,6 +985,7 @@ export type WebPushStatus = {configured: boolean;public_key: string;subscription_count: number;+ current_subscription_enabled?: boolean;};export type WebPushSubscriptionResult = {@@ -1205,7 +1206,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrentoggleAdmin: (userId, isAdmin, platform) => postJson(`/api/users/${encodeURIComponent(userId)}/admin`, platform ? { is_admin: isAdmin, platform } : { is_admin: isAdmin }),removeUser: (userId, platform) => apiFetch(platform ? `/api/users/${encodeURIComponent(userId)}?platform=${encodeURIComponent(platform)}` : `/api/users/${encodeURIComponent(userId)}`, { method: 'DELETE' }).then(r => r.json()),getShowPages: () => getJson('/api/show-pages'),- getWebPushStatus: () => getJson('/api/web-push/status'),+ getWebPushStatus: (endpoint) =>+ endpoint ? postJson('/api/web-push/status', { endpoint }) : getJson('/api/web-push/status'),getWebPushVapidPublicKey: () => getJson('/api/web-push/vapid-public-key'),subscribeWebPush: (subscription, deviceLabel) =>postJson('/api/web-push/subscriptions', {diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 244e2abb3..3c81dac5e 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -1803,21 +1803,34 @@ def _web_push_user_key() -> str:return "local"[email protected]("/api/web-push/status", methods=["GET"])[email protected]("/api/web-push/status", methods=["GET", "POST"])def web_push_status():from core.web_push import load_or_create_vapid_keysfrom storage import web_push_servicekeys = load_or_create_vapid_keys()+ body = request.json if request.method == "POST" else {}+ endpoint = body.get("endpoint") if isinstance(body, dict) else None+ user_key = _web_push_user_key()engine = _projects_engine()with engine.connect() as conn:- subscription_count = web_push_service.count_enabled(conn, user_key=_web_push_user_key())+ subscription_count = web_push_service.count_enabled(conn, user_key=user_key)+ current_subscription = (+ web_push_service.get_enabled_by_endpoint(+ conn,+ endpoint=endpoint,+ user_key=user_key,+ )+ if isinstance(endpoint, str) and endpoint.strip()+ else None+ )return jsonify({"ok": True,"configured": True,"public_key": keys.public_key,"subscription_count": subscription_count,+ "current_subscription_enabled": current_subscription is not None,})@@ -1883,30 +1896,36 @@ def web_push_test():"url": payload.get("url") if isinstance(payload.get("url"), str) else "/inbox","tag": "web-push-test",}+ endpoint = payload.get("endpoint")+ if not isinstance(endpoint, str) or not endpoint.strip():+ return jsonify({"ok": False, "error": "endpoint_required"}), 400user_key = _web_push_user_key()engine = _projects_engine()sent = 0failed = 0with engine.connect() as conn:- subscriptions = web_push_service.list_enabled(conn, user_key=user_key)- if not subscriptions:+ subscription = web_push_service.get_enabled_by_endpoint(+ conn,+ endpoint=endpoint,+ user_key=user_key,+ )+ if not subscription:return jsonify({"ok": False, "error": "no_subscription"}), 404- for subscription in subscriptions:- try:- send_web_push(subscription=subscription, payload=notification)- with engine.begin() as conn:- web_push_service.mark_send_success(conn, endpoint=subscription["endpoint"])- sent += 1- except Exception as exc:- logger.warning("web push: test send failed", exc_info=True)- status_code = getattr(getattr(exc, "response", None), "status_code", None)- with engine.begin() as conn:- web_push_service.mark_send_failure(- conn,- endpoint=subscription["endpoint"],- disable=status_code in {404, 410},- )- failed += 1+ try:+ send_web_push(subscription=subscription, payload=notification)+ with engine.begin() as conn:+ web_push_service.mark_send_success(conn, endpoint=subscription["endpoint"])+ sent += 1+ except Exception as exc:+ logger.warning("web push: test send failed", exc_info=True)+ status_code = getattr(getattr(exc, "response", None), "status_code", None)+ with engine.begin() as conn:+ web_push_service.mark_send_failure(+ conn,+ endpoint=subscription["endpoint"],+ disable=status_code in {404, 410},+ )+ failed += 1return jsonify({"ok": failed == 0, "sent": sent, "failed": failed})@@ -3279,7 +3298,6 @@ def sessions_create():scope_id = _project_to_scope_id(project_id)metadata = payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {}- metadata = {**metadata, "_web_push_user_key": _web_push_user_key()}engine = _projects_engine()try:with engine.begin() as conn:@@ -3713,6 +3731,7 @@ async def sessions_messages_create(session_id: str):return jsonify({"error": "text or content is required"}), 400# A quick-reply click tags the row with the agent message it answers.quick_reply_for = (payload.get("metadata") or {}).get("quick_reply_for")+ web_push_user_key = _web_push_user_key()engine = _projects_engine()try:@@ -3766,8 +3785,11 @@ async def sessions_messages_create(session_id: str):message_type=messages_service.PENDING_TYPE,text=text if isinstance(text, str) else None,content=content if isinstance(content, dict) else None,- metadata=payload.get("metadata") or {},- author_id=payload.get("author_id"),+ metadata={+ **(payload.get("metadata") or {}),+ "_web_push_user_key": web_push_user_key,+ },+ author_id=web_push_user_key,author_name=payload.get("author_name"),)# A quick-reply click is a side action, not the user submitting their