Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(push): decouple normal PWA delivery from expiring prompt auth snapshots (#1441)

Call White1feac2ae5ae8
diff --git a/core/web_push_notifications.py b/core/web_push_notifications.py
index d892f23f9..4e86e1e3c 100644
--- a/core/web_push_notifications.py
+++ b/core/web_push_notifications.py
@@ -2,11 +2,14 @@
from __future__ import annotations
+import collections
import json
import logging
import threading
import time
-from typing import Any
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from typing import Any, Mapping
from sqlalchemy import and_, or_, select
@@ -27,6 +30,481 @@ WEB_PUSH_USER_KEY_METADATA = "_web_push_user_key"
WEB_PUSH_USER_KEYS_METADATA = "_web_push_user_keys"
WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA = "_web_push_authorization_contexts"
+# Structured authorization/delivery dispositions shared by the normal delivery
+# path and the Web Push test/status diagnostics surface (#1434). A disposition
+# names the gate that made one delivery decision; it never carries notification
+# content or credentials.
+WEB_PUSH_DISPOSITION_SENT = "sent"
+WEB_PUSH_DISPOSITION_NO_OWNER = "no_owner"
+WEB_PUSH_DISPOSITION_AUTHORIZATION_REFRESH_REQUIRED = "authorization_refresh_required"
+WEB_PUSH_DISPOSITION_REVISION_UNAVAILABLE = "revision_unavailable"
+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_CONFIG_UNAVAILABLE = "config_unavailable"
+
+_ORGANIZATION_REVISION_DISPOSITIONS = {
+ "unsigned": (
+ WEB_PUSH_DISPOSITION_AUTHORIZATION_REFRESH_REQUIRED,
+ "organization claims lack a signed authorization revision",
+ ),
+ "unavailable": (
+ WEB_PUSH_DISPOSITION_REVISION_UNAVAILABLE,
+ "organization authorization revision unavailable after one bounded retry",
+ ),
+ "mismatch": (
+ WEB_PUSH_DISPOSITION_REVOKED,
+ "signed authorization revision is no longer current",
+ ),
+}
+
+_RECENT_DELIVERY_DISPOSITIONS: collections.deque[dict[str, Any]] = collections.deque(maxlen=64)
+_RECENT_DELIVERY_LOCK = threading.Lock()
+_DELIVERY_DISPOSITIONS_STATE_KEY = "web_push.recent_delivery_dispositions"
+WEB_PUSH_AUTHORIZATION_SYNC_WAIT_SECONDS = 5.0
+
+
+@dataclass(frozen=True)
+class OwnerAuthorizationDecision:
+ """One subscription owner's notification authorization decision."""
+
+ user_key: str
+ policy: str
+ context: AuthorizationContext | None
+ authorized: bool
+ disposition: str | None
+ reason: str
+
+
+def _load_notification_config() -> tuple[Any, bool]:
+ """Return ``(config, load_failed)`` for the paired notification config.
+
+ ``FileNotFoundError`` means the installation is genuinely unpaired and is
+ not a failure; any other error means an existing configuration could not
+ be read, which callers must treat as fail-closed for remote records.
+ """
+
+ try:
+ from core.services import settings as settings_service
+
+ return settings_service.load_config(), False
+ except FileNotFoundError:
+ return None, False
+ except Exception:
+ logger.debug("web push: could not load authorization config", exc_info=True)
+ return None, True
+
+
+def _notification_policy_for_record(config: Any, record: Mapping[str, Any]) -> str:
+ """Select the notification authorization policy for one persisted record.
+
+ Policy selection follows the paired Instance kind (#1433): Personal and
+ Organization notification authorization are independent policies. Legacy
+ pairings with an unknown kind fall back to the record's own claim shape —
+ claims issued through Organization membership follow the Organization
+ policy, everything else follows the Personal policy.
+ """
+
+ cloud = getattr(getattr(config, "remote_access", None), "vibe_cloud", None)
+ instance_kind = str(getattr(cloud, "instance_kind", "") or "")
+ if instance_kind == "organization":
+ return "organization"
+ if instance_kind == "personal":
+ return "personal"
+ organization_id = record.get("vibe_organization_id")
+ if (isinstance(organization_id, str) and organization_id) or (
+ record.get("vibe_instance_access_source") == "organization_group"
+ ):
+ return "organization"
+ return "personal"
+
+
+def _paired_instance_id(config: Any) -> str | None:
+ cloud = getattr(getattr(config, "remote_access", None), "vibe_cloud", None)
+ if cloud is None or not cloud.enabled:
+ return None
+ instance_id = str(getattr(cloud, "instance_id", "") or "").strip()
+ return instance_id or None
+
+
+def _retry_authorization_revision_sync(config: Any) -> None:
+ """Refresh the device watermark once, bounded by the device request timeout.
+
+ When the 15-second poller is already mid-sync the request returns
+ ``authorization_revision_sync_in_progress`` immediately; instead of
+ discarding that, boundedly wait for the in-flight refresh to land so a
+ watermark that is about to refresh does not fail this delivery.
+ """
+
+ from vibe import remote_access
+
+ result: Any = None
+ try:
+ result = remote_access.sync_authorization_revision_once(config)
+ except Exception:
+ logger.debug("web push: authorization revision sync retry failed", exc_info=True)
+ return
+ if not isinstance(result, dict) or (
+ result.get("error") != "authorization_revision_sync_in_progress"
+ ):
+ return
+ deadline = time.monotonic() + WEB_PUSH_AUTHORIZATION_SYNC_WAIT_SECONDS
+ while time.monotonic() < deadline:
+ if config is None:
+ config, _config_load_failed = _load_notification_config()
+ if config is not None:
+ try:
+ if remote_access.current_authorization_revision(config) is not None:
+ return
+ except Exception:
+ logger.debug("web push: in-flight sync wait check failed", exc_info=True)
+ return
+ time.sleep(0.25)
+
+
+def _evaluate_record_authorization(
+ config: Any,
+ user_key: str,
+ record: Mapping[str, Any],
+ *,
+ config_load_failed: bool = False,
+ allow_sync_retry: bool = True,
+) -> OwnerAuthorizationDecision:
+ """Authorize one persisted prompt snapshot under its notification policy.
+
+ Personal policy: the installed PWA's subscription is durable state, so
+ delivery follows the persisted signed snapshot. It is not gated on the
+ interactive authorization refresh cutoff or on Organization membership,
+ group, or authorization-revision state, and ordinary Personal
+ sliding-session renewal never strands the subscription (#1433/#1434).
+
+ Organization policy: current access is resolved at delivery time through
+ the instance authorization revision watermark. A confirmed change (signed
+ revision no longer current) stops delivery, while temporary revision or
+ control-plane unavailability gets exactly one bounded retry and is never
+ treated as confirmed revocation.
+ """
+
+ from vibe import remote_access
+
+ policy = _notification_policy_for_record(config, record)
+ cloud = getattr(getattr(config, "remote_access", None), "vibe_cloud", None)
+ if cloud is not None and not cloud.enabled:
+ # Disabling remote access is a confirmed, deliberate removal of every
+ # remote principal's reach: no remote record may keep authorizing
+ # delivery while the connector is off, regardless of pairing state.
+ return OwnerAuthorizationDecision(
+ user_key=user_key,
+ policy=policy,
+ context=None,
+ authorized=False,
+ disposition=WEB_PUSH_DISPOSITION_REVOKED,
+ reason="remote access is disabled on this installation",
+ )
+ if config_load_failed:
+ # The paired configuration exists but could not be read: the record's
+ # instance binding cannot be validated for any remote owner, so fail
+ # closed for this delivery instead of guessing. The next delivery
+ # retries the read.
+ return OwnerAuthorizationDecision(
+ user_key=user_key,
+ policy=policy,
+ context=None,
+ authorized=False,
+ disposition=WEB_PUSH_DISPOSITION_CONFIG_UNAVAILABLE,
+ reason="paired configuration could not be read; instance binding cannot be validated",
+ )
+ context = context_from_session_payload(record)
+ if not (
+ context.subject
+ and user_key == f"remote:{context.subject}"
+ and context.can_read_instance
+ ):
+ return OwnerAuthorizationDecision(
+ user_key=user_key,
+ policy=policy,
+ context=None,
+ authorized=False,
+ disposition=WEB_PUSH_DISPOSITION_AUTHORIZATION_REFRESH_REQUIRED,
+ reason="persisted snapshot does not carry a readable instance role for this owner",
+ )
+ paired_instance_id = _paired_instance_id(config)
+ record_instance_id = record.get("vibe_instance_id")
+ if (
+ paired_instance_id
+ and isinstance(record_instance_id, str)
+ and record_instance_id
+ and record_instance_id != paired_instance_id
+ ):
+ # Re-pairing this installation to another instance does not clear
+ # subscriptions or old prompt snapshots; a snapshot minted by the
+ # previous instance must never authorize delivery on this one, under
+ # either policy.
+ return OwnerAuthorizationDecision(
+ user_key=user_key,
+ policy=policy,
+ context=None,
+ authorized=False,
+ disposition=WEB_PUSH_DISPOSITION_REVOKED,
+ reason="persisted snapshot was issued for a different paired instance",
+ )
+ if policy == "personal":
+ return OwnerAuthorizationDecision(
+ user_key=user_key,
+ policy=policy,
+ context=context,
+ authorized=True,
+ disposition=None,
+ reason="personal access resolved from the persisted signed snapshot",
+ )
+ if not _record_carries_signed_revision(record):
+ # Organization delivery-time verification is only possible against a
+ # signed revision; unsigned claims can never be confirmed current,
+ # whether or not revision sync is configured right now.
+ return OwnerAuthorizationDecision(
+ user_key=user_key,
+ policy=policy,
+ context=context,
+ authorized=False,
+ disposition=WEB_PUSH_DISPOSITION_AUTHORIZATION_REFRESH_REQUIRED,
+ reason="organization claims lack a signed authorization revision",
+ )
+ revision_state = remote_access.session_authorization_revision_state(config, record)
+ if revision_state == "not_configured":
+ # A revision-signed Organization snapshot proves the instance was
+ # revision-synced when the snapshot was minted. Being unable to check
+ # the watermark now — missing, unreadable, or unpaired local config —
+ # is unavailability, not evidence that no sync ever applied, and must
+ # not authorize delivery of protected output.
+ revision_state = "unavailable"
+ if revision_state == "unavailable" and allow_sync_retry:
+ _retry_authorization_revision_sync(config)
+ revision_state = remote_access.session_authorization_revision_state(config, record)
+ if revision_state == "not_configured":
+ revision_state = "unavailable"
+ if revision_state == "current":
+ return OwnerAuthorizationDecision(
+ user_key=user_key,
+ policy=policy,
+ context=context,
+ authorized=True,
+ disposition=None,
+ reason="organization access current at delivery time",
+ )
+ disposition, reason = _ORGANIZATION_REVISION_DISPOSITIONS.get(
+ revision_state,
+ (WEB_PUSH_DISPOSITION_AUTHORIZATION_REFRESH_REQUIRED, "unknown revision state"),
+ )
+ return OwnerAuthorizationDecision(
+ user_key=user_key,
+ policy=policy,
+ context=context,
+ authorized=False,
+ disposition=disposition,
+ reason=reason,
+ )
+
+
+def _record_carries_signed_revision(record: Mapping[str, Any]) -> bool:
+ value = record.get("vibe_instance_authorization_revision")
+ return isinstance(value, int) and not isinstance(value, bool) and value >= 0
+
+
+def _resolve_owner_authorization_decisions(
+ metadata: dict[str, Any],
+ *,
+ allow_sync_retry: bool = True,
+) -> dict[str, OwnerAuthorizationDecision]:
+ """Resolve per-owner notification authorization from persisted records.
+
+ The bounded watermark refresh is shared by the whole owner set: one merged
+ prompt with several Organization owners performs at most one synchronous
+ sync request per delivery, never one request timeout per owner.
+ """
+
+ raw_contexts = metadata.get(WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA)
+ if not isinstance(raw_contexts, list):
+ return {}
+ records: list[tuple[str, dict[str, Any]]] = []
+ seen_user_keys: set[str] = set()
+ for raw_context in raw_contexts:
+ if not isinstance(raw_context, dict):
+ continue
+ user_key = raw_context.get("user_key")
+ if not isinstance(user_key, str) or not user_key.startswith("remote:"):
+ continue
+ if user_key in seen_user_keys:
+ continue
+ seen_user_keys.add(user_key)
+ records.append((user_key, raw_context))
+ if not records:
+ return {}
+ config, config_load_failed = _load_notification_config()
+ if (
+ allow_sync_retry
+ and not config_load_failed
+ and any(
+ _notification_policy_for_record(config, record) == "organization"
+ for _user_key, record in records
+ )
+ ):
+ from vibe import remote_access
+
+ if config is None or remote_access.current_authorization_revision(config) is None:
+ _retry_authorization_revision_sync(config)
+ config, config_load_failed = _load_notification_config()
+ return {
+ user_key: _evaluate_record_authorization(
+ config,
+ user_key,
+ record,
+ config_load_failed=config_load_failed,
+ allow_sync_retry=False,
+ )
+ for user_key, record in records
+ }
+
+
+def _stored_delivery_dispositions() -> list[dict[str, Any]] | None:
+ """Read the durable disposition ring from ``state_meta``.
+
+ Normal delivery runs in the controller process while the Web Push
+ test/status surface runs in the UI process, so the ring is persisted in
+ SQLite rather than kept only in memory. Returns ``None`` when storage is
+ unavailable so callers can fall back to the process-local deque.
+ """
+
+ try:
+ from core.chat_discovery import get_state_meta
+
+ stored = get_state_meta(_DELIVERY_DISPOSITIONS_STATE_KEY)
+ except Exception:
+ logger.debug("web push: could not read stored delivery dispositions", exc_info=True)
+ return None
+ return stored if isinstance(stored, list) else []
+
+
+def _store_delivery_dispositions(entries: list[dict[str, Any]]) -> None:
+ try:
+ from core.chat_discovery import set_state_meta
+
+ set_state_meta(_DELIVERY_DISPOSITIONS_STATE_KEY, entries[-_RECENT_DELIVERY_DISPOSITIONS.maxlen :])
+ except Exception:
+ logger.debug("web push: could not store delivery dispositions", exc_info=True)
+
+
+def recent_delivery_dispositions(
+ user_key: str | None = None,
+ *,
+ limit: int = 20,
+) -> list[dict[str, Any]]:
+ """Return recent delivery dispositions, newest first.
+
+ ``user_key`` scopes the report to attempts that considered that owner, so
+ the test/status surface explains only the calling owner's deliveries.
+ Reads the durable ``state_meta`` ring so deliveries recorded by the
+ controller process are visible to the UI-process status surface.
+ """
+
+ stored = _stored_delivery_dispositions()
+ if stored is None:
+ with _RECENT_DELIVERY_LOCK:
+ stored = list(_RECENT_DELIVERY_DISPOSITIONS)
+ scoped: list[dict[str, Any]] = []
+ for entry in stored:
+ owners = entry.get("owners", {})
+ if user_key is None:
+ scoped.append(entry)
+ elif user_key in owners:
+ # One owner's diagnostics must not disclose the other merged
+ # recipients or their authorization reasons.
+ scoped.append({**entry, "owners": {user_key: owners[user_key]}})
+ return list(reversed(scoped[-limit:]))
+
+
+def evaluate_delivery_authorization_for_context(
+ user_key: str,
+ context: AuthorizationContext | None,
+) -> dict[str, Any]:
+ """Explain whether normal delivery would currently reach one owner.
+
+ Shared by the Web Push test/status surface so a successful test send can
+ be compared against the authorization gates only the normal path applies.
+ Read-only: it never retries the revision sync and never delivers anything.
+ """
+
+ if user_key == "local":
+ return {
+ "user_key": user_key,
+ "policy": "local",
+ "authorized": True,
+ "disposition": None,
+ "reason": "local install namespace; no remote authorization gates apply",
+ }
+ record = web_push_authorization_context_record(user_key, context)
+ if record is None:
+ return {
+ "user_key": user_key,
+ "policy": "unknown",
+ "authorized": False,
+ "disposition": WEB_PUSH_DISPOSITION_AUTHORIZATION_REFRESH_REQUIRED,
+ "reason": "no usable authorization snapshot for this owner",
+ }
+ config, config_load_failed = _load_notification_config()
+ decision = _evaluate_record_authorization(
+ config,
+ user_key,
+ record,
+ config_load_failed=config_load_failed,
+ allow_sync_retry=False,
+ )
+ evaluation: dict[str, Any] = {
+ "user_key": user_key,
+ "policy": decision.policy,
+ "authorized": decision.authorized,
+ "disposition": decision.disposition,
+ "reason": decision.reason,
+ }
+ if decision.policy == "organization" and config is not None:
+ from vibe import remote_access
+
+ evaluation["revision_state"] = remote_access.session_authorization_revision_state(
+ config,
+ record,
+ )
+ return evaluation
+
+
+def _new_delivery_attempt(payload: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
+ "message_id": payload.get("message_id"),
+ "session_id": payload.get("session_id"),
+ "owners": {},
+ "disposition": None,
+ }
+
+
+def _finish_delivery_attempt(attempt: dict[str, Any], disposition: str) -> None:
+ attempt["disposition"] = disposition
+ # The deque snapshot and the durable `state_meta` write stay inside one
+ # lock-held critical section: two concurrent delivery threads could
+ # otherwise let the older snapshot overwrite the newer persisted entry.
+ # The deque is hydrated from the persisted ring first so a process restart
+ # (empty deque, stored history intact) appends instead of truncating.
+ with _RECENT_DELIVERY_LOCK:
+ if not _RECENT_DELIVERY_DISPOSITIONS:
+ stored = _stored_delivery_dispositions()
+ if stored:
+ _RECENT_DELIVERY_DISPOSITIONS.extend(
+ stored[-_RECENT_DELIVERY_DISPOSITIONS.maxlen :]
+ )
+ _RECENT_DELIVERY_DISPOSITIONS.append(attempt)
+ entries = list(_RECENT_DELIVERY_DISPOSITIONS)
+ _store_delivery_dispositions(entries)
+
def _is_notifiable_message(message_type: Any, metadata: Any = None) -> bool:
normalized_type = str(message_type or "").strip()
@@ -165,40 +643,11 @@ def web_push_authorization_context_record(
def _metadata_authorization_contexts(metadata: dict[str, Any]) -> dict[str, AuthorizationContext]:
- from vibe import remote_access
-
- raw_contexts = metadata.get(WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA)
- if not isinstance(raw_contexts, list):
- return {}
- try:
- from core.services import settings as settings_service
-
- config = settings_service.load_config()
- except FileNotFoundError:
- config = None
- except Exception:
- logger.debug("web push: could not load authorization revision config", exc_info=True)
- return {}
- contexts: dict[str, AuthorizationContext] = {}
- for raw_context in raw_contexts:
- if not isinstance(raw_context, dict):
- continue
- user_key = raw_context.get("user_key")
- if not isinstance(user_key, str) or not user_key.startswith("remote:"):
- continue
- if remote_access.session_needs_authorization_refresh(raw_context):
- continue
- if config is not None:
- if not remote_access.session_authorization_is_current(config, raw_context):
- continue
- elif raw_context.get("vibe_instance_authorization_revision") is not None:
- # A signed revision cannot be validated without the paired-device
- # configuration and fresh local watermark.
- continue
- context = context_from_session_payload(raw_context)
- if context.subject and user_key == f"remote:{context.subject}" and context.can_read_instance:
- contexts[user_key] = context
- return contexts
+ return {
+ user_key: decision.context
+ for user_key, decision in _resolve_owner_authorization_decisions(metadata).items()
+ if decision.authorized and decision.context is not None
+ }
def _web_push_owner_metadata_for_message(
@@ -287,15 +736,11 @@ def _filter_project_authorized_user_keys(
conn: Any,
*,
session_id: str | None,
- metadata: dict[str, Any],
user_keys: list[str],
+ contexts: dict[str, AuthorizationContext],
) -> list[str]:
"""Recheck delayed remote deliveries against the current Project policy."""
- if not user_keys:
- return user_keys
-
- contexts = _metadata_authorization_contexts(metadata)
user_keys = [
user_key
for user_key in user_keys
@@ -382,46 +827,148 @@ def _send_to_enabled_subscriptions(payload: dict[str, Any]) -> None:
if delay:
time.sleep(delay)
+ attempt = _new_delivery_attempt(payload)
engine = create_sqlite_engine()
try:
with engine.connect() as conn:
- if not _message_still_unread(conn, payload.get("message_id")):
- logger.debug("web push: skip notification for message already read or missing")
- return
session_id, owner_metadata = _web_push_owner_metadata_for_message(
conn,
payload.get("message_id"),
)
- user_keys = _filter_project_authorized_user_keys(
+
+ def _finish_suppressed_read() -> None:
+ # Attribute the suppression to the resolved owners so the
+ # scoped status surface can still explain this outcome.
+ logger.debug("web push: skip notification for message already read or missing")
+ for user_key in _metadata_user_keys(owner_metadata):
+ attempt["owners"][user_key] = {
+ "policy": "local" if user_key == "local" else "unknown",
+ "disposition": WEB_PUSH_DISPOSITION_SUPPRESSED_READ,
+ "reason": "message was read or missing before the delivery delay elapsed",
+ }
+ _finish_delivery_attempt(attempt, WEB_PUSH_DISPOSITION_SUPPRESSED_READ)
+
+ if not _message_still_unread(conn, payload.get("message_id")):
+ _finish_suppressed_read()
+ return
+ decisions = _resolve_owner_authorization_decisions(owner_metadata)
+ if not _message_still_unread(conn, payload.get("message_id")):
+ # The authorization resolution may block for a bounded sync
+ # retry; a message opened meanwhile must not still notify.
+ _finish_suppressed_read()
+ return
+ user_keys = _metadata_user_keys(owner_metadata)
+ for user_key in user_keys:
+ decision = decisions.get(user_key)
+ if user_key == "local":
+ attempt["owners"][user_key] = {
+ "policy": "local",
+ "disposition": None,
+ "reason": "local install namespace; no remote authorization gates apply",
+ }
+ continue
+ if decision is None:
+ attempt["owners"][user_key] = {
+ "policy": "unknown",
+ "disposition": WEB_PUSH_DISPOSITION_AUTHORIZATION_REFRESH_REQUIRED,
+ "reason": "no persisted authorization snapshot for this owner",
+ }
+ else:
+ attempt["owners"][user_key] = {
+ "policy": decision.policy,
+ "disposition": decision.disposition,
+ "reason": decision.reason,
+ }
+ if decision is not None and not decision.authorized:
+ logger.warning(
+ "web push: skipping owner %s under %s policy: %s",
+ user_key,
+ decision.policy,
+ decision.reason,
+ )
+ contexts = {
+ user_key: decision.context
+ for user_key, decision in decisions.items()
+ if decision.authorized and decision.context is not None
+ }
+ authorized_keys = [
+ user_key
+ for user_key in user_keys
+ if user_key == "local"
+ or (decisions.get(user_key) is not None and decisions[user_key].authorized)
+ ]
+ project_authorized_keys = _filter_project_authorized_user_keys(
conn,
session_id=session_id,
- metadata=owner_metadata,
- user_keys=_metadata_user_keys(owner_metadata),
+ user_keys=authorized_keys,
+ contexts=contexts,
)
- 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")
+ for user_key in authorized_keys:
+ if user_key not in project_authorized_keys:
+ attempt["owners"][user_key] = {
+ "policy": attempt["owners"].get(user_key, {}).get("policy") or "unknown",
+ "disposition": WEB_PUSH_DISPOSITION_REVOKED,
+ "reason": "current Project access policy no longer includes this owner",
+ }
+ logger.warning(
+ "web push: skipping owner %s: current Project access policy excludes it",
+ user_key,
+ )
+ authorized_keys = project_authorized_keys
+ if not authorized_keys and not _remote_access_enabled():
+ authorized_keys = ["local"] if web_push_service.has_enabled_user_key(conn, user_key="local") else []
+ if authorized_keys == ["local"] and "local" not in attempt["owners"]:
+ attempt["owners"]["local"] = {
+ "policy": "local",
+ "disposition": None,
+ "reason": "local fallback with remote access disabled",
+ }
+ if not authorized_keys:
+ disposition = next(
+ (
+ owner["disposition"]
+ for owner in attempt["owners"].values()
+ if owner.get("disposition")
+ ),
+ WEB_PUSH_DISPOSITION_NO_OWNER,
+ )
+ _finish_delivery_attempt(attempt, disposition)
+ logger.info(
+ "web push: notification for message %s skipped: %s",
+ payload.get("message_id"),
+ disposition,
+ )
return
- contexts = _metadata_authorization_contexts(owner_metadata)
badge_counts = {
user_key: _badge_count_for_user_key(
conn,
user_key=user_key,
contexts=contexts,
)
- for user_key in user_keys
+ for user_key in authorized_keys
}
deliveries = []
seen_endpoints: set[str] = set()
- for user_key in user_keys:
+ for user_key in authorized_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)
- deliveries.append((subscription, badge_counts[user_key]))
- for subscription, badge_count in deliveries:
+ deliveries.append((subscription, badge_counts[user_key], user_key))
+ if not deliveries:
+ _mark_owners_without_delivery(attempt, [])
+ _finish_delivery_attempt(attempt, WEB_PUSH_DISPOSITION_NO_SUBSCRIPTION)
+ logger.info(
+ "web push: notification for message %s skipped: no enabled subscription",
+ payload.get("message_id"),
+ )
+ return
+ sent_count = 0
+ failed_count = 0
+ owner_sent_counts: dict[str, int] = {}
+ owner_failed_counts: dict[str, int] = {}
+ for subscription, badge_count, delivery_owner in deliveries:
try:
send_web_push(
subscription=subscription,
@@ -429,6 +976,8 @@ def _send_to_enabled_subscriptions(payload: dict[str, Any]) -> None:
)
with engine.begin() as conn:
web_push_service.mark_send_success(conn, endpoint=subscription["endpoint"])
+ sent_count += 1
+ owner_sent_counts[delivery_owner] = owner_sent_counts.get(delivery_owner, 0) + 1
except Exception as exc:
status_code = getattr(getattr(exc, "response", None), "status_code", None)
disable = status_code in {404, 410}
@@ -439,5 +988,33 @@ def _send_to_enabled_subscriptions(payload: dict[str, Any]) -> None:
endpoint=subscription["endpoint"],
disable=disable,
)
+ failed_count += 1
+ owner_failed_counts[delivery_owner] = owner_failed_counts.get(delivery_owner, 0) + 1
+ # Provider outcomes are per owner: in a merged delivery the owner whose
+ # endpoint failed must not be told the attempt was sent, and an
+ # authorized owner with no enabled endpoint is told so explicitly.
+ _mark_owners_without_delivery(attempt, [owner for _s, _b, owner in deliveries])
+ for delivery_owner in {owner for _s, _b, owner in deliveries}:
+ owner_entry = attempt["owners"].setdefault(
+ delivery_owner,
+ {"policy": "unknown", "disposition": None, "reason": ""},
+ )
+ if owner_sent_counts.get(delivery_owner):
+ owner_entry["disposition"] = WEB_PUSH_DISPOSITION_SENT
+ elif owner_failed_counts.get(delivery_owner):
+ owner_entry["disposition"] = WEB_PUSH_DISPOSITION_PROVIDER_FAILURE
+ _finish_delivery_attempt(
+ attempt,
+ WEB_PUSH_DISPOSITION_SENT if sent_count else WEB_PUSH_DISPOSITION_PROVIDER_FAILURE,
+ )
finally:
engine.dispose()
+
+
+def _mark_owners_without_delivery(attempt: dict[str, Any], delivered_owners: list[str]) -> None:
+ """Label authorized owners that received no endpoint delivery."""
+
+ delivered = set(delivered_owners)
+ for user_key, owner_entry in attempt["owners"].items():
+ if user_key not in delivered and owner_entry.get("disposition") is None:
+ owner_entry["disposition"] = WEB_PUSH_DISPOSITION_NO_SUBSCRIPTION
diff --git a/docs/plans/web-push-authorization-policy.md b/docs/plans/web-push-authorization-policy.md
new file mode 100644
index 000000000..9fe8560af
--- /dev/null
+++ b/docs/plans/web-push-authorization-policy.md
@@ -0,0 +1,114 @@
+# Web Push notification authorization policy split
+
+Issue: #1434 (related auth-policy issue: #1433).
+
+## Background
+
+On iOS PWA, a Web Push test notification arrives while normal agent-result
+notifications are silently missing. The test endpoint (`POST /api/web-push/test`)
+resolves the current subscription and calls the provider directly. The normal
+inbox delivery path instead re-validated the persisted prompt authorization
+snapshot (`_web_push_authorization_contexts` message metadata) and discarded the
+recipient when either:
+
+- `session_needs_authorization_refresh(...)` was true — the 12-hour
+ Organization-style interactive refresh cutoff introduced with commit
+ `9177928` ("fix(auth): expire persisted push claims"); or
+- `session_authorization_is_current(...)` could not accept the stored revision —
+ which also treated a stale/missing device watermark (control-plane outage)
+ as if it were confirmed revocation.
+
+Normal reachability therefore depended on recent interactive Web use, and the
+skip was only logged at debug level.
+
+## Goal
+
+- Personal and Organization notification authorization use independent
+ policies, consistent with the #1433 direction.
+- Personal: no 12-hour refresh cutoff, no Organization membership/group/revision
+ gates; the installed PWA's subscription is durable state across
+ sliding-session renewal.
+- Organization: resolve current access at delivery time; confirmed revocation
+ stops delivery; temporary revision/control-plane unavailability is never
+ treated as confirmed revocation and gets a bounded retry plus an explicit,
+ visible disposition.
+- Test/status surface reports the same structured authorization state so a
+ successful test send can be explained against the normal-only gates.
+
+## Solution
+
+- `vibe/remote_access.py`: new public `session_authorization_revision_state()`
+ returns the tri-state classification `not_configured` / `unsigned` /
+ `unavailable` / `current` / `mismatch`; `session_authorization_is_current()`
+ delegates to it (same truth table as before).
+- `core/web_push_notifications.py`:
+ - Policy selection per persisted record: paired `instance_kind` selects the
+ policy; unknown (legacy) kinds fall back to the record's claim shape
+ (organization-group claims → Organization, else Personal).
+ - Personal policy authorizes from the persisted signed snapshot alone.
+ - Organization policy maps `mismatch` → `revoked` (skip), `unsigned` →
+ `authorization_refresh_required` (skip), `unavailable` → one bounded
+ `sync_authorization_revision_once()` retry, then skip with
+ `revision_unavailable` if still unavailable. Per-delivery decision only:
+ subscriptions stay enabled and the next message retries.
+ - Structured dispositions (`sent`, `no_owner`,
+ `authorization_refresh_required`, `revision_unavailable`, `revoked`,
+ `no_subscription`, `provider_failure`, `suppressed_read`) recorded in a
+ bounded ring persisted to `state_meta`
+ (`web_push.recent_delivery_dispositions`) so entries written by the
+ controller-process delivery worker are visible to the UI-process
+ test/status surface, and surfaced through
+ `recent_delivery_dispositions()` / `evaluate_delivery_authorization_for_context()`.
+ - Authorization skips now log at warning/info instead of debug.
+ - Review round 1 hardening (Codex findings): a revision-signed Organization
+ snapshot with missing/unreadable config is `revision_unavailable`, never
+ authorized (the snapshot proves the instance was revision-synced when it
+ was minted); the single bounded watermark retry is shared across all
+ merged owners of one delivery; local owners are labeled with the `local`
+ policy instead of a bogus remote refresh disposition; the disposition
+ ring is persisted to `state_meta` so UI-process diagnostics see
+ controller-process deliveries.
+ - Review round 2 hardening (Codex findings): a persisted snapshot minted by
+ a different (pre-re-pairing) instance is rejected as `revoked` before
+ either policy applies; the bounded watermark retry waits for an in-flight
+ poller sync instead of discarding `authorization_revision_sync_in_progress`;
+ the durable disposition write is serialized inside the writer lock;
+ provider outcomes are recorded per owner in merged deliveries; scoped
+ disposition reads redact other merged owners.
+ - Review round 3 hardening (Codex findings): the disposition deque hydrates
+ from the persisted ring so a delivery-process restart appends instead of
+ truncating history; authorized owners without an enabled endpoint are
+ labeled `no_subscription` in merged deliveries; read-suppressed attempts
+ resolve and attribute their owners so the scoped surface can explain the
+ suppression.
+ - Review round 4 hardening (Codex findings): Organization records require a
+ signed revision even when revision sync is not currently configured; a
+ config read failure (distinct from a genuinely unpaired install) fails
+ closed for all remote records with a `config_unavailable` disposition;
+ the unread state is rechecked after the potentially blocking
+ authorization resolution; the Web UI Web Push control consumes the
+ `normal_delivery` evaluation and surfaces a localized warning when the
+ test channel works but normal delivery is currently gated.
+ - Review round 5 hardening (Codex finding): a paired installation with
+ remote access disabled rejects every remote record (`revoked`, "remote
+ access is disabled") — disabling the connector is a confirmed removal of
+ remote reach, and the local install fallback still delivers.
+- `vibe/ui_server.py`:
+ - `_web_push_user_key()` no longer applies the 12-hour refresh cutoff;
+ `parse_session_cookie` still enforces signature, expiry, and confirmed
+ revision revocation.
+ - `/api/web-push/status` and `/api/web-push/test` return a
+ `normal_delivery` evaluation (policy, authorized, disposition, reason,
+ revision state, recent per-owner deliveries) for the calling owner.
+
+## Todo / follow-ups
+
+- [x] Core policy split, dispositions, bounded retry.
+- [x] Test/status diagnostics surface.
+- [x] Regression tests: 12-hour boundary, Personal/Organization isolation
+ (including unknown-kind fallback), confirmed revocation, revision
+ unavailability (recovery and skip), unsigned organization claims,
+ no-subscription disposition, provider delivery.
+- [ ] #1433 remains the owner of the interactive session-surface policy split;
+ once its policy owners land, the push-path selection here should delegate
+ to them instead of reading `instance_kind` directly.
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 1b776b797..8b6ebae66 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -25,6 +25,14 @@ from tests.test_api_save_config_merge import _full_config_payload
from tests.ui_server_test_helpers import csrf_headers
[email protected](autouse=True)
+def _clear_web_push_delivery_dispositions():
+ from core import web_push_notifications
+
+ web_push_notifications._RECENT_DELIVERY_DISPOSITIONS.clear()
+ yield
+
+
def _raw_client_get(client, path: str, *, headers: dict[str, str] | None = None):
request_headers = {TEST_REMOTE_ADDR_HEADER: "127.0.0.1"}
request_headers.update(headers or {})
@@ -3303,9 +3311,79 @@ def test_web_push_test_route_sends_to_enabled_subscriptions(monkeypatch, tmp_pat
)
assert sent.status_code == 200
- assert sent.get_json() == {"ok": True, "sent": 1, "failed": 0}
+ sent_body = sent.get_json()
+ assert sent_body["ok"] is True
+ assert sent_body["sent"] == 1
+ assert sent_body["failed"] == 0
assert sends[0][0]["endpoint"] == subscription["endpoint"]
assert sends[0][1]["title"] == "Hello"
+ # The test surface carries the same authorization evaluation the normal
+ # path applies, so a successful test send can be compared against the
+ # normal-only gates (#1434). A local install has no remote gates.
+ normal_delivery = sent_body["normal_delivery"]
+ assert normal_delivery["user_key"] == "local"
+ assert normal_delivery["policy"] == "local"
+ assert normal_delivery["authorized"] is True
+ assert normal_delivery["recent_deliveries"] == []
+
+
+def test_web_push_status_reports_normal_delivery_diagnostics(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+
+ client = app.test_client()
+ headers = csrf_headers(client)
+
+ status = client.post("/api/web-push/status", json={}, headers=headers)
+ assert status.status_code == 200
+ body = status.get_json()
+ assert body["ok"] is True
+ normal_delivery = body["normal_delivery"]
+ assert normal_delivery["user_key"] == "local"
+ assert normal_delivery["policy"] == "local"
+ assert normal_delivery["authorized"] is True
+ assert normal_delivery["disposition"] is None
+ assert normal_delivery["recent_deliveries"] == []
+
+
+def test_web_push_status_reads_cross_process_delivery_dispositions(monkeypatch, tmp_path):
+ """The status surface reads dispositions persisted by the delivery process.
+
+ Normal delivery runs in the controller process while this endpoint runs in
+ the UI process, so the disposition ring must round-trip through storage.
+ """
+
+ from core import web_push_notifications
+ from core.chat_discovery import set_state_meta
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ controller_entry = {
+ "at": "2026-08-14T00:00:00Z",
+ "message_id": "msg_controller",
+ "session_id": "ses_controller",
+ "owners": {"local": {"policy": "local", "disposition": "sent", "reason": ""}},
+ "disposition": "sent",
+ }
+ other_entry = {
+ "at": "2026-08-14T00:01:00Z",
+ "message_id": "msg_other",
+ "session_id": "ses_other",
+ "owners": {"remote:user-a": {"policy": "personal", "disposition": None, "reason": ""}},
+ "disposition": "sent",
+ }
+ set_state_meta(
+ web_push_notifications._DELIVERY_DISPOSITIONS_STATE_KEY,
+ [controller_entry, other_entry],
+ )
+
+ client = app.test_client()
+ status = client.post("/api/web-push/status", json={}, headers=csrf_headers(client))
+ assert status.status_code == 200
+ normal_delivery = status.get_json()["normal_delivery"]
+ # Newest first, scoped to the calling local owner: the remote entry stays
+ # private to its own owner's diagnostics.
+ assert normal_delivery["recent_deliveries"] == [controller_entry]
def test_web_push_test_route_targets_current_endpoint_only(monkeypatch, tmp_path):
@@ -3345,7 +3423,9 @@ def test_web_push_test_route_targets_current_endpoint_only(monkeypatch, tmp_path
)
assert sent.status_code == 200
- assert sent.get_json() == {"ok": True, "sent": 1, "failed": 0}
+ assert sent.get_json()["ok"] is True
+ assert sent.get_json()["sent"] == 1
+ assert sent.get_json()["failed"] == 0
assert [send[0]["endpoint"] for send in sends] == [subscriptions[0]["endpoint"]]
diff --git a/tests/test_web_push_notifications.py b/tests/test_web_push_notifications.py
index 00c613cb8..72500dd27 100644
--- a/tests/test_web_push_notifications.py
+++ b/tests/test_web_push_notifications.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+import pytest
+
from core import web_push_notifications
from storage import message_deliveries, messages_service, project_access_service, web_push_service
from storage.db import create_sqlite_engine
@@ -10,7 +12,20 @@ from vibe import remote_access
from vibe.authorization import AuthorizationContext
-def _remote_authorization_record(user_key: str) -> dict:
[email protected](autouse=True)
+def _clear_recent_delivery_dispositions():
+ web_push_notifications._RECENT_DELIVERY_DISPOSITIONS.clear()
+ yield
+
+
+def _remote_authorization_record(
+ user_key: str,
+ *,
+ claims_age_seconds: int = 0,
+ authorization_revision: int | None = None,
+ instance_access_source: str = "email",
+ organization: bool = False,
+) -> dict:
subject = user_key.removeprefix("remote:")
record = web_push_notifications.web_push_authorization_context_record(
user_key,
@@ -18,8 +33,12 @@ def _remote_authorization_record(user_key: str) -> dict:
instance_role="editor",
subject=subject,
email=f"{subject}@example.com",
- instance_access_source="email",
- claims_issued_at=int(web_push_notifications.time.time()),
+ instance_access_source=instance_access_source,
+ claims_issued_at=int(web_push_notifications.time.time()) - claims_age_seconds,
+ authorization_revision=authorization_revision,
+ organization_id="org_1" if organization else None,
+ organization_member_id="member_1" if organization else None,
+ organization_role="member" if organization else None,
is_remote=True,
),
)
@@ -27,7 +46,7 @@ def _remote_authorization_record(user_key: str) -> dict:
return record
-def _paired_revision_config(revision: int):
+def _paired_revision_config(revision: int, *, instance_kind: str = ""):
from core.services.settings import default_config
config = default_config()
@@ -36,6 +55,7 @@ def _paired_revision_config(revision: int):
cloud.instance_id = "inst-push"
cloud.instance_secret = "device-secret"
cloud.backend_url = "https://backend.test"
+ cloud.instance_kind = instance_kind
config.save()
remote_access._clear_authorization_revision_cache()
remote_access._replace_authorization_revision(config, revision)
@@ -416,8 +436,17 @@ def test_send_to_enabled_subscriptions_waits_then_sends_to_owner_devices(monkeyp
"message_id": expired_message["id"],
}
)
+ # The persisted Personal prompt snapshot aging past the interactive
+ # authorization refresh cutoff must not silently drop the recipient: the
+ # PWA subscription is durable state (#1434).
assert [send[0]["endpoint"] for send in sends] == [
"https://push.example.test/a",
+ "https://push.example.test/a",
+ ]
+ recent = web_push_notifications.recent_delivery_dispositions()
+ assert [entry["disposition"] for entry in recent] == [
+ web_push_notifications.WEB_PUSH_DISPOSITION_SENT,
+ web_push_notifications.WEB_PUSH_DISPOSITION_SENT,
]
@@ -426,7 +455,7 @@ def test_send_to_enabled_subscriptions_rejects_stale_instance_authorization_revi
tmp_path,
):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = _paired_revision_config(41)
+ config = _paired_revision_config(41, instance_kind="organization")
ensure_sqlite_state()
engine = create_sqlite_engine()
now = "2026-08-04T00:00:00Z"
@@ -437,7 +466,12 @@ def test_send_to_enabled_subscriptions_rejects_stale_instance_authorization_revi
subject="user-a",
instance_access_source="email",
- claims_issued_at=int(web_push_notifications.time.time()),
+ # Claims issued well before the interactive refresh cutoff: claim
+ # age alone must not drop the recipient on an Organization instance
+ # either; only a confirmed revision change may.
+ claims_issued_at=int(web_push_notifications.time.time())
+ - remote_access.SESSION_AUTHORIZATION_REFRESH_SECONDS
+ - 3600,
authorization_revision=41,
is_remote=True,
),
@@ -540,7 +574,1552 @@ def test_send_to_enabled_subscriptions_rejects_stale_instance_authorization_revi
}
)
+ # A confirmed authorization change (fresh revision differs from the signed
+ # one) stops protected delivery for the Organization policy.
+ assert len(sends) == 1
+ recent = web_push_notifications.recent_delivery_dispositions()
+ assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_REVOKED
+ assert recent[0]["owners"]["remote:user-a"]["policy"] == "organization"
+ engine.dispose()
+
+
+def test_personal_policy_ignores_revision_state_and_refresh_cutoff(monkeypatch, tmp_path):
+ """Personal notification authorization is isolated from Organization gates."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_revision_config(41, instance_kind="personal")
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-04T00:00:00Z"
+ authorization_record = _remote_authorization_record(
+ "remote:user-a",
+ claims_age_seconds=remote_access.SESSION_AUTHORIZATION_REFRESH_SECONDS + 3600,
+ authorization_revision=41,
+ )
+
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_push_personal",
+ now=now,
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_push_personal",
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="ses_push_personal",
+ native_session_id="",
+ title="Personal Push",
+ 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_push_personal",
+ platform="avibe",
+ author="user",
+ source="user",
+ author_id="remote:user-a",
+ metadata={
+ "_web_push_user_key": "remote:user-a",
+ "_web_push_authorization_contexts": [authorization_record],
+ },
+ message_type="user",
+ text="Please finish",
+ )
+ web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload={
+ "endpoint": "https://push.example.test/personal",
+ "keys": {"p256dh": "personal-key", "auth": "personal-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)),
+ )
+
+ def _result_message() -> str:
+ with engine.begin() as conn:
+ row = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_personal",
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="result",
+ text="Done",
+ )
+ return row["id"]
+
+ first_message = _result_message()
+ web_push_notifications._send_to_enabled_subscriptions(
+ {"title": "Personal Push", "body": "Done", "session_id": "ses_push_personal", "message_id": first_message}
+ )
+ assert len(sends) == 1
+
+ # An instance-wide revision bump is Organization authorization state: it
+ # must not strand a Personal owner's subscription.
+ remote_access._replace_authorization_revision(config, 42)
+ second_message = _result_message()
+ web_push_notifications._send_to_enabled_subscriptions(
+ {"title": "Personal Push", "body": "Done again", "session_id": "ses_push_personal", "message_id": second_message}
+ )
+ assert len(sends) == 2
+ recent = web_push_notifications.recent_delivery_dispositions()
+ assert all(
+ entry["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_SENT
+ for entry in recent
+ )
+ assert all(
+ entry["owners"]["remote:user-a"]["policy"] == "personal" for entry in recent
+ )
+ engine.dispose()
+
+
+def test_unknown_instance_kind_selects_policy_from_record_claim_shape(monkeypatch, tmp_path):
+ """Legacy pairings without a known kind fall back to the record's claims."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_revision_config(41)
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-04T00:00:00Z"
+ personal_record = _remote_authorization_record("remote:user-personal", authorization_revision=41)
+ organization_record = _remote_authorization_record(
+ "remote:user-org",
+ authorization_revision=41,
+ instance_access_source="organization_group",
+ organization=True,
+ )
+
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_push_unknown_kind",
+ now=now,
+ )
+ for session_id, user_key, record in (
+ ("ses_push_unknown_personal", "remote:user-personal", personal_record),
+ ("ses_push_unknown_org", "remote:user-org", organization_record),
+ ):
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor=session_id,
+ native_session_id="",
+ title=session_id,
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ author_id=user_key,
+ metadata={
+ "_web_push_user_key": user_key,
+ "_web_push_authorization_contexts": [record],
+ },
+ message_type="user",
+ text="Please finish",
+ )
+ web_push_service.upsert_subscription(
+ conn,
+ user_key=user_key,
+ payload={
+ "endpoint": f"https://push.example.test/{user_key}",
+ "keys": {"p256dh": f"{user_key}-p256dh", "auth": f"{user_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)),
+ )
+
+ def _result_message(session_id: str) -> str:
+ with engine.begin() as conn:
+ row = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="result",
+ text="Done",
+ )
+ return row["id"]
+
+ personal_message = _result_message("ses_push_unknown_personal")
+ web_push_notifications._send_to_enabled_subscriptions(
+ {"title": "Unknown kind", "body": "Done", "session_id": "ses_push_unknown_personal", "message_id": personal_message}
+ )
assert len(sends) == 1
+
+ remote_access._replace_authorization_revision(config, 42)
+
+ personal_after = _result_message("ses_push_unknown_personal")
+ web_push_notifications._send_to_enabled_subscriptions(
+ {"title": "Unknown kind", "body": "Done again", "session_id": "ses_push_unknown_personal", "message_id": personal_after}
+ )
+ org_after = _result_message("ses_push_unknown_org")
+ web_push_notifications._send_to_enabled_subscriptions(
+ {"title": "Unknown kind", "body": "Done org", "session_id": "ses_push_unknown_org", "message_id": org_after}
+ )
+
+ # The email-shaped owner keeps receiving; the organization-group owner is
+ # blocked by the confirmed revision change.
+ assert [send[0]["endpoint"] for send in sends] == [
+ "https://push.example.test/remote:user-personal",
+ "https://push.example.test/remote:user-personal",
+ ]
+ recent = web_push_notifications.recent_delivery_dispositions()
+ org_entry = next(
+ entry
+ for entry in recent
+ if "remote:user-org" in entry["owners"]
+ )
+ assert org_entry["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_REVOKED
+ assert org_entry["owners"]["remote:user-org"]["policy"] == "organization"
+ engine.dispose()
+
+
+def _push_session_fixture(conn, *, scope_native_id: str, session_id: str, title: str, now: str):
+ from storage.settings_service import upsert_scope as _upsert_scope
+
+ scope_id = _upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id=scope_native_id,
+ now=now,
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor=session_id,
+ native_session_id="",
+ title=title,
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ return scope_id
+
+
+def _append_user_prompt(conn, *, scope_id: str, session_id: str, user_keys, records, now=None):
+ metadata: dict = {}
+ if len(user_keys) == 1:
+ metadata["_web_push_user_key"] = user_keys[0]
+ else:
+ metadata["_web_push_user_keys"] = list(user_keys)
+ metadata["_web_push_authorization_contexts"] = records
+ return messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ author_id=user_keys[0],
+ metadata=metadata,
+ message_type="user",
+ text="Please finish",
+ )
+
+
+def _append_result(conn, *, scope_id: str, session_id: str, text: str = "Done"):
+ return messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="result",
+ text=text,
+ )
+
+
+def _upsert_subscriptions(conn, *user_keys: str):
+ for user_key in user_keys:
+ web_push_service.upsert_subscription(
+ conn,
+ user_key=user_key,
+ payload={
+ "endpoint": f"https://push.example.test/{user_key}",
+ "keys": {"p256dh": f"{user_key}-p256dh", "auth": f"{user_key}-auth"},
+ },
+ )
+
+
+def test_snapshot_from_previous_paired_instance_is_rejected(monkeypatch, tmp_path):
+ """Re-pairing must not let the previous instance's snapshots deliver here."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ # Paired as a Personal instance "inst-push"; the persisted snapshot was
+ # minted by a DIFFERENT instance ("inst-previous").
+ _paired_revision_config(41, instance_kind="personal")
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-14T00:00:00Z"
+ stale_instance_record = web_push_notifications.web_push_authorization_context_record(
+ "remote:user-a",
+ AuthorizationContext(
+ instance_role="editor",
+ subject="user-a",
+ instance_access_source="email",
+ instance_id="inst-previous",
+ claims_issued_at=int(web_push_notifications.time.time()),
+ is_remote=True,
+ ),
+ )
+ assert stale_instance_record["vibe_instance_id"] == "inst-previous"
+
+ with engine.begin() as conn:
+ scope_id = _push_session_fixture(
+ conn,
+ scope_native_id="proj_push_repaired",
+ session_id="ses_push_repaired",
+ title="Re-paired Push",
+ now=now,
+ )
+ _append_user_prompt(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_repaired",
+ user_keys=["remote:user-a"],
+ records=[stale_instance_record],
+ )
+ message = _append_result(conn, scope_id=scope_id, session_id="ses_push_repaired")
+ _upsert_subscriptions(conn, "remote:user-a")
+
+ 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": "Re-paired Push",
+ "body": "Done",
+ "session_id": "ses_push_repaired",
+ "message_id": message["id"],
+ }
+ )
+
+ assert sends == []
+ recent = web_push_notifications.recent_delivery_dispositions()
+ assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_REVOKED
+ assert recent[0]["owners"]["remote:user-a"]["reason"] == (
+ "persisted snapshot was issued for a different paired instance"
+ )
+ engine.dispose()
+
+
+def test_in_flight_authorization_sync_wait_recovers_watermark(monkeypatch, tmp_path):
+ """An in-flight poller sync is awaited instead of failing the delivery."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _paired_revision_config(41, instance_kind="organization")
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-14T00:00:00Z"
+ authorization_record = _remote_authorization_record(
+ "remote:user-a",
+ authorization_revision=41,
+ )
+
+ with engine.begin() as conn:
+ scope_id = _push_session_fixture(
+ conn,
+ scope_native_id="proj_push_inflight_sync",
+ session_id="ses_push_inflight_sync",
+ title="In-flight Sync",
+ now=now,
+ )
+ _append_user_prompt(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_inflight_sync",
+ user_keys=["remote:user-a"],
+ records=[authorization_record],
+ )
+ message = _append_result(conn, scope_id=scope_id, session_id="ses_push_inflight_sync")
+ _upsert_subscriptions(conn, "remote:user-a")
+
+ watermark_reads = []
+
+ def _current_revision(config, *, now=None):
+ watermark_reads.append(now)
+ # First read (resolver pre-check) sees the stale watermark; the
+ # in-flight poller refresh lands right after.
+ return 41 if len(watermark_reads) > 1 else None
+
+ monkeypatch.setattr(remote_access, "current_authorization_revision", _current_revision)
+ sync_calls = []
+ monkeypatch.setattr(
+ remote_access,
+ "sync_authorization_revision_once",
+ lambda config=None, **kwargs: sync_calls.append(config)
+ or {"ok": False, "error": "authorization_revision_sync_in_progress"},
+ )
+
+ 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": "In-flight Sync",
+ "body": "Done",
+ "session_id": "ses_push_inflight_sync",
+ "message_id": message["id"],
+ }
+ )
+
+ assert len(sync_calls) == 1
+ assert [send[0]["endpoint"] for send in sends] == ["https://push.example.test/remote:user-a"]
+ recent = web_push_notifications.recent_delivery_dispositions()
+ assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_SENT
+ engine.dispose()
+
+
+def test_merged_delivery_reports_provider_failure_per_owner(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-14T00:00:00Z"
+
+ with engine.begin() as conn:
+ scope_id = _push_session_fixture(
+ conn,
+ scope_native_id="proj_push_partial_failure",
+ session_id="ses_push_partial_failure",
+ title="Partial Failure",
+ now=now,
+ )
+ _append_user_prompt(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_partial_failure",
+ user_keys=["remote:user-a", "remote:user-b"],
+ records=[
+ _remote_authorization_record("remote:user-a"),
+ _remote_authorization_record("remote:user-b"),
+ ],
+ )
+ message = _append_result(conn, scope_id=scope_id, session_id="ses_push_partial_failure")
+ _upsert_subscriptions(conn, "remote:user-a", "remote:user-b")
+
+ def _send(*, subscription, payload):
+ if subscription["endpoint"].endswith("remote:user-b"):
+ raise RuntimeError("push provider rejected endpoint")
+
+ monkeypatch.setattr(web_push_notifications.time, "sleep", lambda _seconds: None)
+ monkeypatch.setattr("core.web_push.send_web_push", _send)
+
+ web_push_notifications._send_to_enabled_subscriptions(
+ {
+ "title": "Partial Failure",
+ "body": "Done",
+ "session_id": "ses_push_partial_failure",
+ "message_id": message["id"],
+ }
+ )
+
+ recent = web_push_notifications.recent_delivery_dispositions()
+ assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_SENT
+ owners = recent[0]["owners"]
+ assert owners["remote:user-a"]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_SENT
+ assert owners["remote:user-b"]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_PROVIDER_FAILURE
+ engine.dispose()
+
+
+def test_persisted_ring_survives_delivery_process_restart(monkeypatch, tmp_path):
+ """A fresh delivery process hydrates the stored ring instead of truncating it."""
+
+ from core.chat_discovery import get_state_meta, set_state_meta
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-15T00:00:00Z"
+ pre_restart_entry = {
+ "at": "2026-08-15T00:00:00Z",
+ "message_id": "msg_before_restart",
+ "session_id": "ses_push_hydrate",
+ "owners": {
+ "remote:user-a": {"policy": "personal", "disposition": "sent", "reason": ""}
+ },
+ "disposition": "sent",
+ }
+ set_state_meta(
+ web_push_notifications._DELIVERY_DISPOSITIONS_STATE_KEY,
+ [pre_restart_entry],
+ )
+
+ with engine.begin() as conn:
+ scope_id = _push_session_fixture(
+ conn,
+ scope_native_id="proj_push_hydrate",
+ session_id="ses_push_hydrate",
+ title="Hydrate Push",
+ now=now,
+ )
+ _append_user_prompt(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_hydrate",
+ user_keys=["remote:user-a"],
+ records=[_remote_authorization_record("remote:user-a")],
+ )
+ message = _append_result(conn, scope_id=scope_id, session_id="ses_push_hydrate")
+ _upsert_subscriptions(conn, "remote:user-a")
+
+ 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": "Hydrate Push",
+ "body": "Done",
+ "session_id": "ses_push_hydrate",
+ "message_id": message["id"],
+ }
+ )
+
+ stored = get_state_meta(web_push_notifications._DELIVERY_DISPOSITIONS_STATE_KEY)
+ assert [entry["message_id"] for entry in stored] == [
+ "msg_before_restart",
+ message["id"],
+ ]
+ engine.dispose()
+
+
+def test_merged_owner_without_endpoint_reports_no_subscription(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-15T00:00:00Z"
+
+ with engine.begin() as conn:
+ scope_id = _push_session_fixture(
+ conn,
+ scope_native_id="proj_push_owner_no_endpoint",
+ session_id="ses_push_owner_no_endpoint",
+ title="Owner No Endpoint",
+ now=now,
+ )
+ _append_user_prompt(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_owner_no_endpoint",
+ user_keys=["remote:user-a", "remote:user-b"],
+ records=[
+ _remote_authorization_record("remote:user-a"),
+ _remote_authorization_record("remote:user-b"),
+ ],
+ )
+ message = _append_result(conn, scope_id=scope_id, session_id="ses_push_owner_no_endpoint")
+ # Only user-a has an enabled subscription.
+ _upsert_subscriptions(conn, "remote:user-a")
+
+ 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": "Owner No Endpoint",
+ "body": "Done",
+ "session_id": "ses_push_owner_no_endpoint",
+ "message_id": message["id"],
+ }
+ )
+
+ assert len(sends) == 1
+ recent = web_push_notifications.recent_delivery_dispositions()
+ assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_SENT
+ owners = recent[0]["owners"]
+ assert owners["remote:user-a"]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_SENT
+ assert (
+ owners["remote:user-b"]["disposition"]
+ == web_push_notifications.WEB_PUSH_DISPOSITION_NO_SUBSCRIPTION
+ )
+ engine.dispose()
+
+
+def test_read_suppressed_attempt_is_attributed_to_its_owners(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-15T00:00:00Z"
+
+ with engine.begin() as conn:
+ scope_id = _push_session_fixture(
+ conn,
+ scope_native_id="proj_push_suppressed",
+ session_id="ses_push_suppressed",
+ title="Suppressed Push",
+ now=now,
+ )
+ _append_user_prompt(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_suppressed",
+ user_keys=["remote:user-a"],
+ records=[_remote_authorization_record("remote:user-a")],
+ )
+ message = _append_result(conn, scope_id=scope_id, session_id="ses_push_suppressed")
+ messages_service.mark_session_read(conn, "ses_push_suppressed", until_message_id=message["id"])
+ _upsert_subscriptions(conn, "remote:user-a")
+
+ 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": "Suppressed Push",
+ "body": "Done",
+ "session_id": "ses_push_suppressed",
+ "message_id": message["id"],
+ }
+ )
+
+ assert sends == []
+ scoped = web_push_notifications.recent_delivery_dispositions(user_key="remote:user-a")
+ assert len(scoped) == 1
+ assert scoped[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_SUPPRESSED_READ
+ assert (
+ scoped[0]["owners"]["remote:user-a"]["disposition"]
+ == web_push_notifications.WEB_PUSH_DISPOSITION_SUPPRESSED_READ
+ )
+ engine.dispose()
+
+
+def test_unsigned_organization_snapshot_without_config_is_rejected(monkeypatch, tmp_path):
+ """Organization delivery needs a signed revision even with no paired config."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ # No `_paired_revision_config`: this AVIBE_HOME has no paired config at all.
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-15T00:00:00Z"
+ unsigned_record = _remote_authorization_record(
+ "remote:user-a",
+ instance_access_source="organization_group",
+ organization=True,
+ )
+ assert "vibe_instance_authorization_revision" not in unsigned_record
+
+ with engine.begin() as conn:
+ scope_id = _push_session_fixture(
+ conn,
+ scope_native_id="proj_push_unsigned_no_config",
+ session_id="ses_push_unsigned_no_config",
+ title="Unsigned No Config",
+ now=now,
+ )
+ _append_user_prompt(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_unsigned_no_config",
+ user_keys=["remote:user-a"],
+ records=[unsigned_record],
+ )
+ message = _append_result(conn, scope_id=scope_id, session_id="ses_push_unsigned_no_config")
+ _upsert_subscriptions(conn, "remote:user-a")
+
+ 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": "Unsigned No Config",
+ "body": "Done",
+ "session_id": "ses_push_unsigned_no_config",
+ "message_id": message["id"],
+ }
+ )
+
+ assert sends == []
+ recent = web_push_notifications.recent_delivery_dispositions()
+ assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_AUTHORIZATION_REFRESH_REQUIRED
+ assert recent[0]["owners"]["remote:user-a"]["policy"] == "organization"
+ engine.dispose()
+
+
+def test_config_read_failure_fails_closed_for_remote_owners(monkeypatch, tmp_path):
+ """An unreadable paired config must not authorize any remote snapshot."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-15T00:00:00Z"
+
+ def _broken_load_config():
+ raise RuntimeError("config read failed")
+
+ monkeypatch.setattr("core.services.settings.load_config", _broken_load_config)
+
+ with engine.begin() as conn:
+ scope_id = _push_session_fixture(
+ conn,
+ scope_native_id="proj_push_config_failure",
+ session_id="ses_push_config_failure",
+ title="Config Failure",
+ now=now,
+ )
+ _append_user_prompt(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_config_failure",
+ user_keys=["remote:user-a"],
+ records=[_remote_authorization_record("remote:user-a")],
+ )
+ message = _append_result(conn, scope_id=scope_id, session_id="ses_push_config_failure")
+ _upsert_subscriptions(conn, "remote:user-a")
+
+ 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": "Config Failure",
+ "body": "Done",
+ "session_id": "ses_push_config_failure",
+ "message_id": message["id"],
+ }
+ )
+
+ assert sends == []
+ recent = web_push_notifications.recent_delivery_dispositions()
+ assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_CONFIG_UNAVAILABLE
+ owner = recent[0]["owners"]["remote:user-a"]
+ assert owner["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_CONFIG_UNAVAILABLE
+ engine.dispose()
+
+
+def test_message_read_during_authorization_retry_is_not_sent(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _paired_revision_config(41, instance_kind="organization")
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-15T00:00:00Z"
+
+ with engine.begin() as conn:
+ scope_id = _push_session_fixture(
+ conn,
+ scope_native_id="proj_push_read_during_retry",
+ session_id="ses_push_read_during_retry",
+ title="Read During Retry",
+ now=now,
+ )
+ _append_user_prompt(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_read_during_retry",
+ user_keys=["remote:user-a"],
+ records=[_remote_authorization_record("remote:user-a", authorization_revision=41)],
+ )
+ message = _append_result(conn, scope_id=scope_id, session_id="ses_push_read_during_retry")
+ _upsert_subscriptions(conn, "remote:user-a")
+
+ def _open_message_during_retry(config):
+ # The user opens the message while the bounded watermark retry blocks.
+ with engine.begin() as conn:
+ messages_service.mark_session_read(
+ conn,
+ "ses_push_read_during_retry",
+ until_message_id=message["id"],
+ )
+
+ monkeypatch.setattr(
+ remote_access,
+ "current_authorization_revision",
+ lambda config, *, now=None: None,
+ )
+ monkeypatch.setattr(
+ web_push_notifications,
+ "_retry_authorization_revision_sync",
+ _open_message_during_retry,
+ )
+
+ 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 During Retry",
+ "body": "Done",
+ "session_id": "ses_push_read_during_retry",
+ "message_id": message["id"],
+ }
+ )
+
+ assert sends == []
+ scoped = web_push_notifications.recent_delivery_dispositions(user_key="remote:user-a")
+ assert scoped[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_SUPPRESSED_READ
+ engine.dispose()
+
+
+def test_disabling_remote_access_stops_remote_delivery(monkeypatch, tmp_path):
+ """A paired-but-disabled remote access must not authorize remote records."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_revision_config(41, instance_kind="personal")
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-15T00:00:00Z"
+
+ with engine.begin() as conn:
+ scope_id = _push_session_fixture(
+ conn,
+ scope_native_id="proj_push_disabled_remote",
+ session_id="ses_push_disabled_remote",
+ title="Disabled Remote",
+ now=now,
+ )
+ _append_user_prompt(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_disabled_remote",
+ user_keys=["remote:user-a"],
+ records=[_remote_authorization_record("remote:user-a")],
+ )
+ message = _append_result(conn, scope_id=scope_id, session_id="ses_push_disabled_remote")
+ _upsert_subscriptions(conn, "remote:user-a", "local")
+
+ config.remote_access.vibe_cloud.enabled = False
+ config.save()
+
+ 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": "Disabled Remote",
+ "body": "Done",
+ "session_id": "ses_push_disabled_remote",
+ "message_id": message["id"],
+ }
+ )
+
+ # The remote owner is rejected; the local install fallback still delivers.
+ assert [send[0]["endpoint"] for send in sends] == ["https://push.example.test/local"]
+ recent = web_push_notifications.recent_delivery_dispositions()
+ assert recent[0]["owners"]["remote:user-a"]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_REVOKED
+ assert recent[0]["owners"]["remote:user-a"]["reason"] == (
+ "remote access is disabled on this installation"
+ )
+ assert recent[0]["owners"]["local"]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_SENT
+ engine.dispose()
+
+
+def test_scoped_dispositions_redact_other_owners(monkeypatch, tmp_path):
+ from core.chat_discovery import set_state_meta
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ entry = {
+ "at": "2026-08-14T00:00:00Z",
+ "message_id": "msg_multi",
+ "session_id": "ses_multi",
+ "owners": {
+ "remote:user-a": {"policy": "personal", "disposition": "sent", "reason": ""},
+ "remote:user-b": {"policy": "organization", "disposition": "revoked", "reason": "signed authorization revision is no longer current"},
+ },
+ "disposition": "sent",
+ }
+ set_state_meta(web_push_notifications._DELIVERY_DISPOSITIONS_STATE_KEY, [entry])
+
+ scoped = web_push_notifications.recent_delivery_dispositions(user_key="remote:user-a")
+
+ assert len(scoped) == 1
+ assert scoped[0]["owners"] == {
+ "remote:user-a": {"policy": "personal", "disposition": "sent", "reason": ""}
+ }
+ assert "remote:user-b" not in scoped[0]["owners"]
+
+
+def test_organization_signed_snapshot_without_config_records_unavailable(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ # No `_paired_revision_config`: this AVIBE_HOME has no paired config at all.
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-04T00:00:00Z"
+ authorization_record = _remote_authorization_record(
+ "remote:user-a",
+ authorization_revision=41,
+ instance_access_source="organization_group",
+ organization=True,
+ )
+ assert authorization_record["vibe_instance_authorization_revision"] == 41
+
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_push_no_config",
+ now=now,
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_push_no_config",
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="ses_push_no_config",
+ native_session_id="",
+ title="No Config Push",
+ 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_push_no_config",
+ platform="avibe",
+ author="user",
+ source="user",
+ author_id="remote:user-a",
+ metadata={
+ "_web_push_user_key": "remote:user-a",
+ "_web_push_authorization_contexts": [authorization_record],
+ },
+ message_type="user",
+ text="Please finish",
+ )
+ message = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_no_config",
+ 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/no-config",
+ "keys": {"p256dh": "no-config-key", "auth": "no-config-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": "No Config Push",
+ "body": "Done",
+ "session_id": "ses_push_no_config",
+ "message_id": message["id"],
+ }
+ )
+
+ assert sends == []
+ recent = web_push_notifications.recent_delivery_dispositions()
+ assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_REVISION_UNAVAILABLE
+ assert recent[0]["owners"]["remote:user-a"]["policy"] == "organization"
+ engine.dispose()
+
+
+def test_organization_revision_unavailable_retries_once_then_recovers(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _paired_revision_config(41, instance_kind="organization")
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-04T00:00:00Z"
+ authorization_record = _remote_authorization_record(
+ "remote:user-a",
+ authorization_revision=41,
+ )
+
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_push_unavailable_retry",
+ now=now,
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_push_unavailable_retry",
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="ses_push_unavailable_retry",
+ native_session_id="",
+ title="Unavailable Retry",
+ 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_push_unavailable_retry",
+ platform="avibe",
+ author="user",
+ source="user",
+ author_id="remote:user-a",
+ metadata={
+ "_web_push_user_key": "remote:user-a",
+ "_web_push_authorization_contexts": [authorization_record],
+ },
+ message_type="user",
+ text="Please finish",
+ )
+ message = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_unavailable_retry",
+ 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/unavailable-retry",
+ "keys": {"p256dh": "retry-key", "auth": "retry-auth"},
+ },
+ )
+
+ # The fresh watermark reads as unavailable exactly once (stale snapshot or
+ # control-plane outage); the bounded sync retry refreshes it.
+ watermark_reads = []
+
+ def _current_revision(config, *, now=None):
+ watermark_reads.append(now)
+ return 41 if len(watermark_reads) > 1 else None
+
+ monkeypatch.setattr(remote_access, "current_authorization_revision", _current_revision)
+ sync_calls = []
+ monkeypatch.setattr(
+ web_push_notifications,
+ "_retry_authorization_revision_sync",
+ lambda config: sync_calls.append(config),
+ )
+
+ 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": "Unavailable Retry",
+ "body": "Done",
+ "session_id": "ses_push_unavailable_retry",
+ "message_id": message["id"],
+ }
+ )
+
+ assert len(sync_calls) == 1
+ assert [send[0]["endpoint"] for send in sends] == [
+ "https://push.example.test/unavailable-retry"
+ ]
+ recent = web_push_notifications.recent_delivery_dispositions()
+ assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_SENT
+ engine.dispose()
+
+
+def test_organization_revision_unavailable_after_bounded_retry_skips_with_disposition(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _paired_revision_config(41, instance_kind="organization")
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-04T00:00:00Z"
+ authorization_record = _remote_authorization_record(
+ "remote:user-a",
+ authorization_revision=41,
+ )
+
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_push_unavailable",
+ now=now,
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_push_unavailable",
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="ses_push_unavailable",
+ native_session_id="",
+ title="Unavailable Push",
+ 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_push_unavailable",
+ platform="avibe",
+ author="user",
+ source="user",
+ author_id="remote:user-a",
+ metadata={
+ "_web_push_user_key": "remote:user-a",
+ "_web_push_authorization_contexts": [authorization_record],
+ },
+ message_type="user",
+ text="Please finish",
+ )
+ message = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_unavailable",
+ 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/unavailable",
+ "keys": {"p256dh": "unavailable-key", "auth": "unavailable-auth"},
+ },
+ )
+
+ monkeypatch.setattr(
+ remote_access,
+ "current_authorization_revision",
+ lambda config, *, now=None: None,
+ )
+ sync_calls = []
+ monkeypatch.setattr(
+ web_push_notifications,
+ "_retry_authorization_revision_sync",
+ lambda config: sync_calls.append(config),
+ )
+
+ 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": "Unavailable Push",
+ "body": "Done",
+ "session_id": "ses_push_unavailable",
+ "message_id": message["id"],
+ }
+ )
+
+ # Temporary unavailability is a per-delivery decision, not confirmed
+ # revocation and not permanent loss: exactly one bounded retry, an explicit
+ # disposition, and the subscription stays enabled for the next attempt.
+ assert sends == []
+ assert len(sync_calls) == 1
+ recent = web_push_notifications.recent_delivery_dispositions()
+ assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_REVISION_UNAVAILABLE
+ owner = recent[0]["owners"]["remote:user-a"]
+ assert owner["policy"] == "organization"
+ assert owner["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_REVISION_UNAVAILABLE
+ with engine.connect() as conn:
+ assert web_push_service.count_enabled(conn, user_key="remote:user-a") == 1
+ engine.dispose()
+
+
+def test_organization_unavailable_retry_is_shared_across_merged_owners(monkeypatch, tmp_path):
+ """One merged prompt with several Organization owners retries the watermark once."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _paired_revision_config(41, instance_kind="organization")
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-04T00:00:00Z"
+
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_push_shared_retry",
+ now=now,
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_push_shared_retry",
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="ses_push_shared_retry",
+ native_session_id="",
+ title="Shared Retry",
+ 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_push_shared_retry",
+ platform="avibe",
+ author="user",
+ source="user",
+ author_id="remote:user-a",
+ metadata={
+ "_web_push_user_keys": ["remote:user-a", "remote:user-b"],
+ "_web_push_authorization_contexts": [
+ _remote_authorization_record("remote:user-a", authorization_revision=41),
+ _remote_authorization_record("remote:user-b", authorization_revision=41),
+ ],
+ },
+ message_type="user",
+ text="Please finish",
+ )
+ message = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_shared_retry",
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="result",
+ text="Done",
+ )
+ for user_key in ("remote:user-a", "remote:user-b"):
+ web_push_service.upsert_subscription(
+ conn,
+ user_key=user_key,
+ payload={
+ "endpoint": f"https://push.example.test/shared-{user_key}",
+ "keys": {"p256dh": f"{user_key}-key", "auth": f"{user_key}-auth"},
+ },
+ )
+
+ monkeypatch.setattr(
+ remote_access,
+ "current_authorization_revision",
+ lambda config, *, now=None: None,
+ )
+ sync_calls = []
+ monkeypatch.setattr(
+ web_push_notifications,
+ "_retry_authorization_revision_sync",
+ lambda config: sync_calls.append(config),
+ )
+
+ 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": "Shared Retry",
+ "body": "Done",
+ "session_id": "ses_push_shared_retry",
+ "message_id": message["id"],
+ }
+ )
+
+ # One control-plane outage costs one bounded sync request for the whole
+ # owner set, not one request timeout per merged owner.
+ assert sends == []
+ assert len(sync_calls) == 1
+ recent = web_push_notifications.recent_delivery_dispositions()
+ assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_REVISION_UNAVAILABLE
+ assert set(recent[0]["owners"]) == {"remote:user-a", "remote:user-b"}
+ engine.dispose()
+
+
+def test_organization_unsigned_record_reports_refresh_required(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _paired_revision_config(41, instance_kind="organization")
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-04T00:00:00Z"
+ authorization_record = _remote_authorization_record("remote:user-a")
+
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_push_unsigned",
+ now=now,
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_push_unsigned",
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="ses_push_unsigned",
+ native_session_id="",
+ title="Unsigned Push",
+ 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_push_unsigned",
+ platform="avibe",
+ author="user",
+ source="user",
+ author_id="remote:user-a",
+ metadata={
+ "_web_push_user_key": "remote:user-a",
+ "_web_push_authorization_contexts": [authorization_record],
+ },
+ message_type="user",
+ text="Please finish",
+ )
+ message = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_unsigned",
+ 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/unsigned",
+ "keys": {"p256dh": "unsigned-key", "auth": "unsigned-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": "Unsigned Push",
+ "body": "Done",
+ "session_id": "ses_push_unsigned",
+ "message_id": message["id"],
+ }
+ )
+
+ # Organization claims that predate revision signing cannot be confirmed
+ # current at delivery time; skip them with an explicit, visible reason.
+ assert sends == []
+ recent = web_push_notifications.recent_delivery_dispositions()
+ assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_AUTHORIZATION_REFRESH_REQUIRED
+ assert recent[0]["owners"]["remote:user-a"]["policy"] == "organization"
+ engine.dispose()
+
+
+def test_authorized_owner_without_subscription_records_no_subscription(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-04T00:00:00Z"
+ authorization_record = _remote_authorization_record("remote:user-a")
+
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_push_no_sub",
+ now=now,
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_push_no_sub",
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="ses_push_no_sub",
+ native_session_id="",
+ title="No Subscription",
+ 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_push_no_sub",
+ platform="avibe",
+ author="user",
+ source="user",
+ author_id="remote:user-a",
+ metadata={
+ "_web_push_user_key": "remote:user-a",
+ "_web_push_authorization_contexts": [authorization_record],
+ },
+ message_type="user",
+ text="Please finish",
+ )
+ message = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_no_sub",
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="result",
+ text="Done",
+ )
+ web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-b",
+ payload={
+ "endpoint": "https://push.example.test/other",
+ "keys": {"p256dh": "other-key", "auth": "other-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": "No Subscription",
+ "body": "Done",
+ "session_id": "ses_push_no_sub",
+ "message_id": message["id"],
+ }
+ )
+
+ assert sends == []
+ recent = web_push_notifications.recent_delivery_dispositions(user_key="remote:user-a")
+ assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_NO_SUBSCRIPTION
+ assert (
+ recent[0]["owners"]["remote:user-a"]["disposition"]
+ == web_push_notifications.WEB_PUSH_DISPOSITION_NO_SUBSCRIPTION
+ )
engine.dispose()
@@ -1367,6 +2946,15 @@ def test_send_to_enabled_subscriptions_falls_back_to_local_owner(monkeypatch, tm
)
assert [send[0]["endpoint"] for send in sends] == ["https://push.example.test/local"]
+ recent = web_push_notifications.recent_delivery_dispositions()
+ assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_SENT
+ # A local owner is locally authorized — never labeled as needing a remote
+ # authorization refresh — and reports its own provider outcome.
+ assert recent[0]["owners"]["local"] == {
+ "policy": "local",
+ "disposition": web_push_notifications.WEB_PUSH_DISPOSITION_SENT,
+ "reason": "local fallback with remote access disabled",
+ }
def test_send_to_enabled_subscriptions_skips_local_fallback_when_remote_access_enabled(monkeypatch, tmp_path):
diff --git a/ui/src/components/workbench/WebPushControl.tsx b/ui/src/components/workbench/WebPushControl.tsx
index 31c16ec20..652191f62 100644
--- a/ui/src/components/workbench/WebPushControl.tsx
+++ b/ui/src/components/workbench/WebPushControl.tsx
@@ -101,7 +101,23 @@ export const WebPushControl: React.FC = () => {
endpoint: subscription.endpoint,
});
if (result.ok) {
- showToast(t('workbench.inbox.notifications.testSent'), 'success');
+ const blocked = result.normal_delivery;
+ if (blocked && blocked.authorized === false) {
+ // The channel works, but the normal-path authorization gate would
+ // currently skip this owner — explain which gate decided.
+ showToast(
+ `${t('workbench.inbox.notifications.testSent')} — ${t(
+ 'workbench.inbox.notifications.normalBlocked',
+ {
+ disposition: blocked.disposition ?? 'unknown',
+ policy: blocked.policy ?? 'unknown',
+ },
+ )}`,
+ 'warning',
+ );
+ } else {
+ showToast(t('workbench.inbox.notifications.testSent'), 'success');
+ }
} else {
showToast(
t('workbench.inbox.notifications.testFailed', { count: result.failed ?? 0 }),
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 424135643..df3a0d055 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -2469,12 +2469,38 @@ export type OpencodeMutationResult = {
};
};
+export type WebPushNormalDeliveryOwner = {
+ policy?: string;
+ disposition?: string | null;
+ reason?: string;
+};
+
+export type WebPushNormalDeliveryRecent = {
+ at?: string;
+ message_id?: string | null;
+ session_id?: string | null;
+ owners?: Record<string, WebPushNormalDeliveryOwner>;
+ disposition?: string | null;
+};
+
+/** Normal-path authorization evaluation shared by the test/status surface. */
+export type WebPushNormalDelivery = {
+ user_key?: string;
+ policy?: string;
+ authorized?: boolean | null;
+ disposition?: string | null;
+ reason?: string;
+ revision_state?: string;
+ recent_deliveries?: WebPushNormalDeliveryRecent[];
+};
+
export type WebPushStatus = {
ok: boolean;
configured: boolean;
public_key: string;
subscription_count: number;
current_subscription_enabled?: boolean;
+ normal_delivery?: WebPushNormalDelivery;
};
export type WebPushStatusPayload = {
@@ -2503,6 +2529,7 @@ export type WebPushTestResult = {
sent?: number;
failed?: number;
error?: string;
+ normal_delivery?: WebPushNormalDelivery;
};
// Error thrown by the JSON helpers below when a request fails. Carries the
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 78b456a39..90bcd9066 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2057,7 +2057,8 @@
"testTitle": "Avibe",
"testBody": "Notifications are ready.",
"testSent": "Test notification sent",
- "testFailed": "Test notification failed"
+ "testFailed": "Test notification failed",
+ "normalBlocked": "normal notifications are currently skipped for you ({{policy}} policy: {{disposition}})"
}
},
"modules": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 15eff596c..fb6a5b442 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2057,7 +2057,8 @@
"testTitle": "Avibe",
"testBody": "通知已经准备好了。",
"testSent": "测试通知已发送",
- "testFailed": "测试通知发送失败"
+ "testFailed": "测试通知发送失败",
+ "normalBlocked": "但普通通知当前会跳过你({{policy}} 策略:{{disposition}})"
}
},
"modules": {
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index 9586903e6..78851a796 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -4288,26 +4288,46 @@ def session_claims_from_oidc(config: V2Config, claims: Mapping[str, Any]) -> dic
return session_claims
-def session_authorization_is_current(
+def session_authorization_revision_state(
config: V2Config,
payload: Mapping[str, Any],
*,
now: float | None = None,
-) -> bool:
- """Return whether signed remote claims match the fresh device watermark."""
+) -> str:
+ """Classify signed remote claims against the fresh device watermark.
+
+ Returns one of ``not_configured`` (no paired revision sync), ``unsigned``
+ (the claims carry no usable revision), ``unavailable`` (the fresh device
+ watermark could not be read — a recoverable connectivity state, not
+ evidence that authorization changed), ``current``, or ``mismatch``.
+ """
if not _authorization_revision_sync_configured(config):
- return True
- current_revision = current_authorization_revision(config, now=now)
- if current_revision is None:
- return False
+ return "not_configured"
try:
signed_revision = _normalize_authorization_revision(
payload.get(_AUTHORIZATION_REVISION_KEY)
)
except ValueError:
- return False
- return signed_revision == current_revision
+ return "unsigned"
+ current_revision = current_authorization_revision(config, now=now)
+ if current_revision is None:
+ return "unavailable"
+ return "current" if signed_revision == current_revision else "mismatch"
+
+
+def session_authorization_is_current(
+ config: V2Config,
+ payload: Mapping[str, Any],
+ *,
+ now: float | None = None,
+) -> bool:
+ """Return whether signed remote claims match the fresh device watermark."""
+
+ return session_authorization_revision_state(config, payload, now=now) in {
+ "current",
+ "not_configured",
+ }
def _encode_session_cookie(secret: str, payload: Mapping[str, Any]) -> str:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 3c4cda1ad..bef03e2bb 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -5502,6 +5502,12 @@ def _web_push_user_key() -> str:
Remote-access sessions carry a subject claim; purely local UI sessions do
not yet have a user identity, so they share the local install namespace.
+ Subscription identity is durable (#1434): a still-valid session cookie
+ keeps attributing subscriptions and test sends to its subject across
+ sliding-session renewal. Confirmed revocation is enforced by
+ ``parse_session_cookie`` itself (signature, expiry, and current
+ authorization revision), so no separate interactive-refresh cutoff is
+ applied here.
"""
config = _load_remote_access_config()
@@ -5512,17 +5518,49 @@ def _web_push_user_key() -> str:
payload = remote_access.parse_session_cookie(
config, request.cookies.get(remote_access.SESSION_COOKIE_NAME)
)
- if (
- payload
- and not remote_access.session_needs_authorization_refresh(payload)
- and payload.get("sub")
- ):
+ if payload and payload.get("sub"):
return f"remote:{payload['sub']}"
except Exception:
logger.debug("web push: could not resolve remote user key", exc_info=True)
return "local"
+def _web_push_normal_delivery_diagnostics() -> dict:
+ """Explain the normal-path authorization gates for the calling owner.
+
+ The Web Push test send skips the authorization gates that normal inbox
+ delivery applies. Reporting the same evaluation here lets a user see why a
+ test notification arrives while a normal one does not, without exposing
+ protected content or credentials.
+ """
+
+ from core import web_push_notifications
+
+ user_key = _web_push_user_key()
+ try:
+ evaluation = web_push_notifications.evaluate_delivery_authorization_for_context(
+ user_key,
+ getattr(g, "authorization_context", None),
+ )
+ except Exception:
+ logger.debug("web push: normal delivery evaluation failed", exc_info=True)
+ evaluation = {
+ "user_key": user_key,
+ "policy": "unknown",
+ "authorized": None,
+ "disposition": None,
+ "reason": "evaluation_unavailable",
+ }
+ try:
+ evaluation["recent_deliveries"] = web_push_notifications.recent_delivery_dispositions(
+ user_key=user_key,
+ )
+ except Exception:
+ logger.debug("web push: recent delivery lookup failed", exc_info=True)
+ evaluation["recent_deliveries"] = []
+ return evaluation
+
+
def _workbench_memory_user_id() -> str | None:
"""Resolve only identities that may use scoped Memory commands."""
@@ -5591,6 +5629,7 @@ def web_push_status():
"public_key": keys.public_key,
"subscription_count": subscription_count,
"current_subscription_enabled": current_subscription is not None,
+ "normal_delivery": _web_push_normal_delivery_diagnostics(),
}
)
@@ -5690,7 +5729,14 @@ def web_push_test():
disable=status_code in {404, 410},
)
failed += 1
- return jsonify({"ok": failed == 0, "sent": sent, "failed": failed})
+ return jsonify(
+ {
+ "ok": failed == 0,
+ "sent": sent,
+ "failed": failed,
+ "normal_delivery": _web_push_normal_delivery_diagnostics(),
+ }
+ )
@app.route("/api/cli/detect")