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.

feat(ui): add PWA web push notifications

cyh7f853d3336d4
diff --git a/core/message_mirror.py b/core/message_mirror.py
index 7ab7f6502..a2e28be52 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -243,6 +243,12 @@ def persist_agent_message(
from core.inbox_events import bus
bus.publish("inbox.session.updated", inbox_row)
+ try:
+ from core.web_push_notifications import maybe_notify_inbox_message
+
+ maybe_notify_inbox_message(appended_row, inbox_row)
+ except Exception:
+ logger.debug("web push notification scheduling failed", exc_info=True)
except Exception:
logger.exception("persist_agent_message: failure on platform=%s", context.platform)
diff --git a/core/web_push.py b/core/web_push.py
new file mode 100644
index 000000000..6620307b3
--- /dev/null
+++ b/core/web_push.py
@@ -0,0 +1,107 @@
+"""Server-side Web Push primitives for the Workbench PWA."""
+
+from __future__ import annotations
+
+import base64
+import json
+import logging
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric import ec
+
+from config import paths
+
+logger = logging.getLogger(__name__)
+
+_VAPID_FILE = "web_push_vapid.json"
+
+
+@dataclass(frozen=True)
+class VapidKeys:
+ public_key: str
+ private_key_pem: str
+
+
+def _b64url_no_padding(data: bytes) -> str:
+ return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
+
+
+def vapid_key_path() -> Path:
+ return paths.get_state_dir() / _VAPID_FILE
+
+
+def load_or_create_vapid_keys(path: Path | None = None) -> VapidKeys:
+ key_path = path or vapid_key_path()
+ if key_path.exists():
+ payload = json.loads(key_path.read_text(encoding="utf-8"))
+ public_key = payload.get("public_key")
+ private_key_pem = payload.get("private_key_pem")
+ if isinstance(public_key, str) and isinstance(private_key_pem, str):
+ return VapidKeys(public_key=public_key, private_key_pem=private_key_pem)
+ raise ValueError("invalid_vapid_key_file")
+
+ key_path.parent.mkdir(parents=True, exist_ok=True)
+ private_key = ec.generate_private_key(ec.SECP256R1())
+ public_key = private_key.public_key()
+ public_numbers = public_key.public_numbers()
+ raw_public = (
+ b"\x04"
+ + public_numbers.x.to_bytes(32, "big")
+ + public_numbers.y.to_bytes(32, "big")
+ )
+ private_key_pem = private_key.private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.PKCS8,
+ encryption_algorithm=serialization.NoEncryption(),
+ ).decode("ascii")
+ keys = VapidKeys(public_key=_b64url_no_padding(raw_public), private_key_pem=private_key_pem)
+ key_path.write_text(
+ json.dumps(
+ {
+ "public_key": keys.public_key,
+ "private_key_pem": keys.private_key_pem,
+ },
+ indent=2,
+ )
+ + "\n",
+ encoding="utf-8",
+ )
+ try:
+ key_path.chmod(0o600)
+ except OSError:
+ logger.debug("Could not chmod VAPID key file %s", key_path, exc_info=True)
+ return keys
+
+
+def send_web_push(
+ *,
+ subscription: dict[str, Any],
+ payload: dict[str, Any],
+ vapid_keys: VapidKeys | None = None,
+ subject: str = "mailto:[email protected]",
+) -> None:
+ """Send one Web Push payload.
+
+ The pywebpush dependency is imported lazily so tests that only exercise key
+ generation or subscription APIs do not need network-capable setup.
+ """
+
+ from pywebpush import webpush
+
+ keys = vapid_keys or load_or_create_vapid_keys()
+ subscription_info = {
+ "endpoint": subscription["endpoint"],
+ "keys": {
+ "p256dh": subscription["p256dh"],
+ "auth": subscription["auth"],
+ },
+ }
+ webpush(
+ subscription_info=subscription_info,
+ data=json.dumps(payload, separators=(",", ":")),
+ vapid_private_key=keys.private_key_pem,
+ vapid_claims={"sub": subject},
+ )
diff --git a/core/web_push_notifications.py b/core/web_push_notifications.py
new file mode 100644
index 000000000..ec795b966
--- /dev/null
+++ b/core/web_push_notifications.py
@@ -0,0 +1,93 @@
+"""Notification dispatch from durable Workbench inbox events to Web Push."""
+
+from __future__ import annotations
+
+import logging
+import threading
+from typing import Any
+
+from sqlalchemy import select
+
+from storage import web_push_service
+from storage.models import agent_sessions
+
+logger = logging.getLogger(__name__)
+
+_NOTIFIABLE_TYPES = {"result", "notify", "error"}
+_LOCAL_USER_KEY = "local"
+
+
+def maybe_notify_inbox_message(message: dict[str, Any] | None, inbox_row: dict[str, Any] | None) -> None:
+ """Schedule Web Push for a newly persisted inbox-visible Workbench message.
+
+ Called after the message row and inbox row exist in the same durable write
+ path. Sending happens on a background thread with its own SQLite connection
+ so a slow push service never blocks message persistence or SSE fan-out.
+ """
+
+ if not message or not inbox_row:
+ return
+ if message.get("platform") != "avibe":
+ return
+ if message.get("author") != "agent":
+ return
+ if message.get("type") not in _NOTIFIABLE_TYPES:
+ return
+ if not message.get("session_id"):
+ return
+
+ payload = {
+ "title": inbox_row.get("title") or inbox_row.get("project_name") or "Vibe Remote",
+ "body": (message.get("text") or inbox_row.get("preview_text") or "").strip()[:240],
+ "url": f"/chat/{message['session_id']}",
+ "tag": f"session:{message['session_id']}",
+ "badge_count": inbox_row.get("unread_count") or 0,
+ "message_id": message.get("id"),
+ "session_id": message.get("session_id"),
+ }
+ thread = threading.Thread(target=_send_to_enabled_subscriptions, args=(payload,), daemon=True)
+ thread.start()
+
+
+def _user_key_for_session(conn: Any, session_id: str | None) -> str:
+ if not session_id:
+ return _LOCAL_USER_KEY
+ row = conn.execute(
+ select(agent_sessions.c.metadata_json).where(agent_sessions.c.id == session_id)
+ ).first()
+ if row is None:
+ return _LOCAL_USER_KEY
+ try:
+ import json
+
+ metadata = json.loads(row[0] or "{}")
+ except Exception:
+ return _LOCAL_USER_KEY
+ user_key = metadata.get("_web_push_user_key") if isinstance(metadata, dict) else None
+ return user_key if isinstance(user_key, str) and user_key.strip() else _LOCAL_USER_KEY
+
+
+def _send_to_enabled_subscriptions(payload: dict[str, Any]) -> None:
+ from core.web_push import send_web_push
+ from storage.db import create_sqlite_engine
+
+ engine = create_sqlite_engine()
+ try:
+ with engine.begin() as conn:
+ user_key = _user_key_for_session(conn, payload.get("session_id"))
+ subscriptions = web_push_service.list_enabled(conn, user_key=user_key)
+ for subscription in subscriptions:
+ try:
+ send_web_push(subscription=subscription, payload=payload)
+ web_push_service.mark_send_success(conn, endpoint=subscription["endpoint"])
+ except Exception as exc:
+ status_code = getattr(getattr(exc, "response", None), "status_code", None)
+ disable = status_code in {404, 410}
+ logger.warning("web push: send failed", exc_info=True)
+ web_push_service.mark_send_failure(
+ conn,
+ endpoint=subscription["endpoint"],
+ disable=disable,
+ )
+ finally:
+ engine.dispose()
diff --git a/docs/plans/pwa-web-push.md b/docs/plans/pwa-web-push.md
new file mode 100644
index 000000000..29dfd3f7d
--- /dev/null
+++ b/docs/plans/pwa-web-push.md
@@ -0,0 +1,399 @@
+# PWA Web Push for Workbench Inbox · Design Doc
+
+> **Branch**: `feature/pwa-web-push-plan`
+> **Status**: Implementation in progress
+> **Owner**: cyhhao
+
+## 1. Goal
+
+Add a first-class PWA Web Push notification path for the Workbench Inbox.
+
+The product goal is not to replace the existing in-app realtime feed. It is to
+reach the user when the Vibe Remote Web UI is installed as a mobile PWA and the
+page is not actively open. The active Web UI should continue to use the
+existing SSE realtime channel.
+
+This plan intentionally excludes email, IM, and native app push channels.
+
+## 2. Platform Feasibility
+
+PWA Web Push can reach the iOS notification shade when the following conditions
+are true:
+
+- iOS/iPadOS is 16.4 or newer.
+- The user has added the Web App to the Home Screen.
+- The user opens the app from the Home Screen.
+- The user grants notification permission from a direct user gesture.
+- A registered service worker receives push events and calls
+ `showNotification()`.
+
+The same implementation also covers Chromium/Android and modern desktop
+browsers through the standard Push API.
+
+Important iOS constraints:
+
+- Ordinary Safari tabs are not enough for iOS notification delivery. The app
+ must be a Home Screen Web App.
+- Permission prompts must be initiated by a user action.
+- Safari does not provide a useful invisible-push path for our use case. The
+ service worker should show a notification for every delivered push event.
+- Notifications are tied to each installed web app's origin. A subscription
+ should therefore be treated as a per-device/per-install endpoint, not a
+ global user preference.
+
+## 3. Current Code Facts
+
+### PWA shell
+
+The UI already ships a PWA manifest and iOS standalone metadata:
+
+- `ui/public/manifest.webmanifest`
+- `ui/index.html`
+
+The HTML currently says "No service worker on purpose" so frontend assets stay
+network-fresh. That means the app is installable but cannot yet receive Web
+Push.
+
+### In-app realtime
+
+Workbench realtime is already implemented and should stay as the active-page
+transport:
+
+- Frontend opens one `EventSource('/api/events')`.
+- `WorkbenchInboxContext` owns the shared inbox cache.
+- `inbox.session.updated` upserts/re-sorts a session card.
+- `inbox.unread.changed` refreshes unread state after mark-read.
+- The UI server exposes `/api/events` as an SSE stream with keep-alive pings.
+- `vibe.sse_broker.SSEBroker` fans events out to browser subscribers.
+- Controller-side agent replies publish through `core.inbox_events.bus`,
+ `GET /internal/events`, and `vibe.inbox_bridge` into the UI server broker.
+
+SSE is an in-memory fan-out, not a persistent event log. It is correct for
+open-page realtime and should not be used as the mobile background notification
+mechanism.
+
+## 4. Boundary Decision
+
+Keep two separate capabilities:
+
+| Capability | Runtime state | Transport | Responsibility |
+| --- | --- | --- | --- |
+| Active Web UI realtime | Page open | SSE `/api/events` | Update chat, inbox list, unread counts |
+| User reachability | Page closed/backgrounded | Web Push | Show OS notification and badge |
+
+The Web Push path should trigger from durable message/inbox write paths, not
+from browser SSE subscription state. A missing or disconnected browser should
+not affect whether a notification is sent.
+
+## 5. Data Model
+
+Add a SQLite table for PWA push subscriptions.
+
+Proposed table: `web_push_subscriptions`
+
+| Column | Purpose |
+| --- | --- |
+| `id` | Stable local UUID / token |
+| `user_key` | Local authenticated user key, or `"local"` when no remote user is known |
+| `endpoint` | Push endpoint URL; unique |
+| `p256dh` | Browser public encryption key |
+| `auth` | Browser auth secret |
+| `user_agent` | Optional client user agent snapshot |
+| `device_label` | Optional label shown in settings/debug UI |
+| `enabled` | Soft-disable without deleting history |
+| `last_success_at` | Last successful send |
+| `last_failure_at` | Last failed send |
+| `failure_count` | Consecutive failures |
+| `created_at` | Created timestamp |
+| `updated_at` | Updated timestamp |
+
+Why SQLite instead of V2 config:
+
+- Subscriptions are runtime/device state, not user-authored configuration.
+- A user may have multiple installed PWAs/devices.
+- Endpoints rotate or expire and need operational metadata.
+- The existing durable state model already owns messages, sessions, media, show
+ pages, and background runs.
+
+Migration work:
+
+- Add `storage.models.web_push_subscriptions`.
+- Add an Alembic migration after the current head.
+- Extend `storage.migrations` drift repair and `HEAD_TABLES`/required columns if
+ needed.
+- Add a small `storage/web_push_service.py` with CRUD and failure handling.
+
+## 6. VAPID Keys and Configuration
+
+Use standard Web Push with VAPID.
+
+Implementation choice:
+
+- Add Python dependency `pywebpush` unless a smaller maintained library is
+ preferred during implementation review.
+- Generate a local VAPID keypair automatically on first use and store it under
+ the Vibe Remote state directory, not in source.
+- Expose the public VAPID key through an authenticated API endpoint.
+
+Suggested storage:
+
+- Private key: `~/.vibe_remote/state/web_push_vapid.json`
+- Public key: returned by `GET /api/web-push/vapid-public-key`
+
+Rationale:
+
+- Self-hosted installs should work without external setup.
+- VAPID private key is secret runtime state and must not live in repo config.
+- Keeping a stable key preserves existing subscriptions across restarts.
+
+## 7. Backend API
+
+Add authenticated UI APIs:
+
+### `GET /api/web-push/status`
+
+Returns feature availability and current browser-independent server status:
+
+- `configured`
+- `public_key`
+- `subscription_count`
+
+### `GET /api/web-push/vapid-public-key`
+
+Returns the base64url public VAPID key for `PushManager.subscribe()`.
+
+### `POST /api/web-push/subscriptions`
+
+Accepts the browser `PushSubscription` JSON and upserts by endpoint.
+
+Input:
+
+```json
+{
+ "endpoint": "https://...",
+ "keys": {
+ "p256dh": "...",
+ "auth": "..."
+ },
+ "user_agent": "..."
+}
+```
+
+Validation:
+
+- `endpoint` must be a non-empty HTTPS URL.
+- `keys.p256dh` and `keys.auth` must be non-empty strings.
+- Reject malformed payloads with 400.
+
+### `DELETE /api/web-push/subscriptions`
+
+Accepts an endpoint and disables/removes that subscription.
+
+### `POST /api/web-push/test`
+
+Sends a test notification to the current subscription/device. This is necessary
+because iOS support must be validated on a real device after Home Screen install
+and permission grant.
+
+## 8. Frontend and Service Worker
+
+### Service worker
+
+Add `ui/public/push-sw.js` or equivalent static asset.
+
+Responsibilities:
+
+- Listen for `push`.
+- Parse payload defensively.
+- Call `self.registration.showNotification(title, options)`.
+- Update badge when supported (`navigator.setAppBadge` is page-side; service
+ worker support differs, so keep badge best-effort).
+- Listen for `notificationclick`.
+- Focus an existing client if available; otherwise open the target URL.
+
+Payload shape:
+
+```json
+{
+ "title": "Agent replied",
+ "body": "Short preview text",
+ "url": "/sessions/<session_id>",
+ "tag": "session:<session_id>",
+ "badge_count": 3
+}
+```
+
+### App registration
+
+Add a small frontend module, for example `ui/src/lib/webPush.ts`.
+
+Responsibilities:
+
+- Detect support:
+ - `serviceWorker` in `navigator`
+ - `PushManager` in `window`
+ - `Notification` in `window`
+- Detect standalone display where possible:
+ - `matchMedia('(display-mode: standalone)')`
+ - iOS `navigator.standalone`
+- Register service worker only when the user opts in.
+- Request permission only inside the click handler.
+- Subscribe with `userVisibleOnly: true` and the server public VAPID key.
+- Upsert the subscription to the backend.
+
+UX placement:
+
+- Put the first implementation in an existing Workbench/settings surface, not as
+ an aggressive global prompt.
+- Show the enable button only when the browser claims support.
+- On iOS Safari that is not standalone, show a concise blocked state: add to
+ Home Screen first, then open from the Home Screen.
+
+All user-visible copy must go through `ui/src/i18n/en.json` and
+`ui/src/i18n/zh.json`.
+
+## 9. Notification Trigger
+
+Trigger Web Push after durable inbox-relevant messages are persisted.
+
+Initial trigger rule:
+
+- Platform: `avibe`
+- Session-backed message
+- Message author: `agent`
+- Message type: `result` or terminal `notify`
+- Message is unread after persistence
+
+Preferred implementation boundary:
+
+- Add `core/web_push_notifications.py` as the notification dispatcher.
+- Call it from the same durable write paths that already compute/publish
+ `inbox.session.updated`.
+- Keep it non-blocking for agent turns: failures should be logged and recorded
+ on subscriptions but must not break message persistence or SSE realtime.
+
+The first implementation can be synchronous in a threadpool or fire-and-forget
+task, but it should have one clear service boundary so later batching/rate-limit
+logic can land without changing message persistence again.
+
+Deduping:
+
+- Use the persisted `message.id` as the logical notification id.
+- If needed, add a small `web_push_deliveries` table later. Do not add it in the
+ first pass unless duplicate sends appear in tests or runtime.
+
+## 10. In-App Realtime Check
+
+The current SSE path is good enough to remain the active UI realtime foundation.
+
+Recommended small hardening:
+
+- On `EventSource` `connected`, refresh the inbox snapshot. This reconciles any
+ events missed during reconnect.
+- On `visibilitychange` from hidden to visible, refresh the inbox snapshot.
+- Keep realtime events as fast incremental updates, but treat REST snapshots as
+ authoritative.
+
+This hardening belongs in `WorkbenchInboxContext`; it does not require a new
+transport.
+
+## 11. Test Plan
+
+Backend unit tests:
+
+- Subscription upsert validates required fields and endpoint uniqueness.
+- Disabled/expired subscription is skipped.
+- 410/404 Web Push response disables a subscription.
+- Inbox notification trigger sends only for avibe unread agent `result`/terminal
+ `notify` messages.
+- Message persistence still succeeds when Web Push send fails.
+
+Frontend tests/build:
+
+- `npm run build`.
+- Type-check service worker registration helper.
+- Verify i18n keys exist in English and Chinese.
+
+Manual device validation:
+
+1. Serve the branch through the regression or an isolated dev environment over
+ HTTPS.
+2. Open on iOS 16.4+ Safari.
+3. Add Vibe Remote to Home Screen.
+4. Open the Home Screen app.
+5. Tap "Enable notifications".
+6. Confirm the iOS permission prompt.
+7. Send `/api/web-push/test`.
+8. Lock the phone or leave the app.
+9. Confirm the notification appears in the iOS notification shade.
+10. Tap the notification and confirm it opens the intended Workbench session.
+
+Non-goals for the first validation:
+
+- Email fallback.
+- IM fallback.
+- Cross-device notification preference UI.
+- Full delivery analytics.
+
+## 12. Implementation Phases
+
+### Phase 1: Plan and skeleton
+
+- Land this plan.
+- Add storage service and migration for subscriptions.
+- Add VAPID key generation/loading.
+
+### Phase 2: API and service worker
+
+- Add authenticated Web Push APIs.
+- Add `push-sw.js`.
+- Add frontend helper and opt-in UI.
+- Add test notification endpoint.
+
+### Phase 3: Inbox trigger
+
+- Hook durable agent result/notify persistence into Web Push dispatcher.
+- Keep failures isolated from message persistence.
+- Add focused tests.
+
+### Phase 4: Realtime hardening
+
+- Refresh inbox on SSE connected/reconnected.
+- Refresh inbox on page visibility restore.
+
+### Phase 5: Device validation
+
+- Build UI.
+- Run focused Python tests.
+- Validate on a real iOS 16.4+ Home Screen PWA.
+
+## 13. Current Implementation Status
+
+Implemented in this branch:
+
+- SQLite `web_push_subscriptions` model, Alembic migration, and storage helpers.
+- Local VAPID key generation under the Vibe Remote state directory.
+- Authenticated Web Push status, subscribe, unsubscribe, public-key, and test-send APIs.
+- Static push service worker with `push` and `notificationclick` handling.
+- Inbox toolbar opt-in control with iOS standalone/PWA support detection.
+- Durable Workbench inbox trigger from agent `result` / `notify` / `error` messages.
+- Owner scoping: subscriptions are bound to the current remote user when known,
+ with local-install fallback for non-remote local UI.
+- Targeted backend tests, migration coverage, and frontend production build.
+
+Still pending before release:
+
+- Real iOS Home Screen PWA validation on an actual device.
+- Product decision on notification noise suppression when the same session is
+ actively open.
+- Optional settings surface for listing/removing multiple registered devices.
+
+## 14. Open Questions
+
+1. Should the first opt-in UI live in Settings or directly in the Inbox header?
+ Settings is less intrusive; Inbox is more discoverable.
+2. What should `user_key` be when remote access is disabled? The first pass can
+ use `"local"` and evolve once multi-user local Web UI is real.
+3. Should terminal `notify` messages push in v1? They are inbox-visible and can
+ represent failures that need attention, but regular progress notifications
+ should not wake the user.
diff --git a/pyproject.toml b/pyproject.toml
index be4c434ac..daef8cb2f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -67,6 +67,7 @@ dependencies = [
"packaging>=23.0",
"uvicorn[standard]>=0.27",
"imagesize>=1.4.1",
+ "pywebpush>=2.0.3",
]
[project.urls]
diff --git a/storage/alembic/versions/20260604_0016_web_push_subscriptions.py b/storage/alembic/versions/20260604_0016_web_push_subscriptions.py
new file mode 100644
index 000000000..e87c27479
--- /dev/null
+++ b/storage/alembic/versions/20260604_0016_web_push_subscriptions.py
@@ -0,0 +1,56 @@
+"""web_push_subscriptions for PWA notification endpoints
+
+Stores per-device Push API subscriptions for the Workbench PWA. A subscription
+is runtime state, not authored config: endpoints can rotate, expire, or be
+disabled independently across installed browser apps.
+
+Revision ID: 20260604_0016
+Revises: 20260604_0015
+Create Date: 2026-06-04
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20260604_0016"
+down_revision = "20260604_0015"
+branch_labels = None
+depends_on = None
+
+
+def _tables() -> set[str]:
+ bind = op.get_bind()
+ return {row[0] for row in bind.exec_driver_sql("select name from sqlite_master where type = 'table'")}
+
+
+def upgrade() -> None:
+ if "web_push_subscriptions" not in _tables():
+ op.create_table(
+ "web_push_subscriptions",
+ sa.Column("id", sa.String(), primary_key=True),
+ sa.Column("user_key", sa.String(), nullable=False),
+ sa.Column("endpoint", sa.Text(), nullable=False),
+ sa.Column("p256dh", sa.Text(), nullable=False),
+ sa.Column("auth", sa.Text(), nullable=False),
+ sa.Column("user_agent", sa.Text(), nullable=True),
+ sa.Column("device_label", sa.Text(), nullable=True),
+ sa.Column("enabled", sa.Integer(), nullable=False),
+ sa.Column("last_success_at", sa.String(), nullable=True),
+ sa.Column("last_failure_at", sa.String(), nullable=True),
+ sa.Column("failure_count", sa.Integer(), nullable=False),
+ sa.Column("created_at", sa.String(), nullable=False),
+ sa.Column("updated_at", sa.String(), nullable=False),
+ sa.UniqueConstraint("endpoint", name="uq_web_push_subscriptions_endpoint"),
+ )
+ op.create_index(
+ "ix_web_push_subscriptions_user_enabled",
+ "web_push_subscriptions",
+ ["user_key", "enabled"],
+ if_not_exists=True,
+ )
+
+
+def downgrade() -> None:
+ op.drop_table("web_push_subscriptions")
diff --git a/storage/migrations.py b/storage/migrations.py
index ef9c5362d..43c272aa6 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -12,7 +12,7 @@ from config import paths
from storage.db import create_sqlite_engine, sqlite_url
INITIAL_REVISION = "20260501_0001"
-LATEST_SCHEMA_REVISION = "20260531_0010"
+LATEST_SCHEMA_REVISION = "20260604_0016"
REMOVE_LEGACY_DEFAULT_AGENT_REVISION = "20260530_0008"
INITIAL_TABLES = {
"state_meta",
@@ -23,8 +23,21 @@ INITIAL_TABLES = {
"agent_sessions",
"runtime_records",
}
-HEAD_TABLES = INITIAL_TABLES | {"run_definitions", "agent_runs", "show_pages", "messages", "show_session_events"}
-PRE_SHOW_SESSION_EVENTS_HEAD_TABLES = HEAD_TABLES - {"show_session_events"}
+HEAD_TABLES = INITIAL_TABLES | {
+ "run_definitions",
+ "agent_runs",
+ "show_pages",
+ "messages",
+ "show_session_events",
+ "media_objects",
+ "web_push_subscriptions",
+}
+PRE_SHOW_SESSION_EVENTS_HEAD_TABLES = INITIAL_TABLES | {
+ "run_definitions",
+ "agent_runs",
+ "show_pages",
+ "messages",
+}
HEAD_REQUIRED_COLUMNS = {
"agents": {"enabled"},
"scope_settings": {"agent_name"},
diff --git a/storage/models.py b/storage/models.py
index 629d66648..3222a4956 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -361,6 +361,29 @@ media_objects = Table(
Index("ix_media_objects_dedup", "local_path", "size_bytes", "mtime_ns"),
)
+# Per-install browser Push API subscriptions for PWA Web Push. These are
+# runtime/device endpoints, not user-authored config: one user may install the
+# app on multiple devices, and endpoints can rotate or expire independently.
+web_push_subscriptions = Table(
+ "web_push_subscriptions",
+ metadata,
+ Column("id", String, primary_key=True),
+ Column("user_key", String, nullable=False),
+ Column("endpoint", Text, nullable=False),
+ Column("p256dh", Text, nullable=False),
+ Column("auth", Text, nullable=False),
+ Column("user_agent", Text, nullable=True),
+ Column("device_label", Text, nullable=True),
+ Column("enabled", Integer, nullable=False),
+ Column("last_success_at", String, nullable=True),
+ Column("last_failure_at", String, nullable=True),
+ Column("failure_count", Integer, nullable=False),
+ Column("created_at", String, nullable=False),
+ Column("updated_at", String, nullable=False),
+ UniqueConstraint("endpoint", name="uq_web_push_subscriptions_endpoint"),
+ Index("ix_web_push_subscriptions_user_enabled", "user_key", "enabled"),
+)
+
imported_state_tables = [
show_pages,
background_runs,
@@ -372,4 +395,5 @@ imported_state_tables = [
scopes,
messages,
show_session_events,
+ web_push_subscriptions,
]
diff --git a/storage/web_push_service.py b/storage/web_push_service.py
new file mode 100644
index 000000000..a5f7a27a4
--- /dev/null
+++ b/storage/web_push_service.py
@@ -0,0 +1,141 @@
+"""Persistence helpers for browser Web Push subscriptions."""
+
+from __future__ import annotations
+
+import secrets
+from datetime import datetime, timezone
+from typing import Any
+from urllib.parse import urlparse
+
+from sqlalchemy import func, select
+from sqlalchemy.dialects.sqlite import insert as sqlite_insert
+from sqlalchemy.engine import Connection
+
+from storage.models import web_push_subscriptions
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _new_id() -> str:
+ return "wps_" + secrets.token_urlsafe(16)
+
+
+def validate_subscription_payload(payload: dict[str, Any]) -> tuple[str, str, str]:
+ endpoint = payload.get("endpoint")
+ keys = payload.get("keys")
+ if not isinstance(endpoint, str) or not endpoint.strip():
+ raise ValueError("endpoint_required")
+ parsed = urlparse(endpoint)
+ if parsed.scheme != "https" or not parsed.netloc:
+ raise ValueError("endpoint_must_be_https")
+ if not isinstance(keys, dict):
+ raise ValueError("keys_required")
+ p256dh = keys.get("p256dh")
+ auth = keys.get("auth")
+ if not isinstance(p256dh, str) or not p256dh.strip():
+ raise ValueError("p256dh_required")
+ if not isinstance(auth, str) or not auth.strip():
+ raise ValueError("auth_required")
+ return endpoint.strip(), p256dh.strip(), auth.strip()
+
+
+def _row_to_dict(row: Any) -> dict[str, Any]:
+ data = dict(row)
+ data["enabled"] = bool(data.get("enabled"))
+ return data
+
+
+def upsert_subscription(
+ conn: Connection,
+ *,
+ user_key: str,
+ payload: dict[str, Any],
+ user_agent: str | None = None,
+ device_label: str | None = None,
+) -> dict[str, Any]:
+ endpoint, p256dh, auth = validate_subscription_payload(payload)
+ now = _utc_now_iso()
+ stmt = sqlite_insert(web_push_subscriptions).values(
+ id=_new_id(),
+ user_key=user_key,
+ endpoint=endpoint,
+ p256dh=p256dh,
+ auth=auth,
+ user_agent=user_agent,
+ device_label=device_label,
+ enabled=1,
+ failure_count=0,
+ created_at=now,
+ updated_at=now,
+ )
+ stmt = stmt.on_conflict_do_update(
+ index_elements=[web_push_subscriptions.c.endpoint],
+ set_={
+ "user_key": user_key,
+ "p256dh": p256dh,
+ "auth": auth,
+ "user_agent": user_agent,
+ "device_label": device_label,
+ "enabled": 1,
+ "failure_count": 0,
+ "updated_at": now,
+ },
+ )
+ conn.execute(stmt)
+ row = conn.execute(
+ select(web_push_subscriptions).where(web_push_subscriptions.c.endpoint == endpoint)
+ ).mappings().one()
+ return _row_to_dict(row)
+
+
+def disable_subscription(conn: Connection, *, endpoint: str) -> bool:
+ endpoint = endpoint.strip() if isinstance(endpoint, str) else ""
+ if not endpoint:
+ return False
+ now = _utc_now_iso()
+ result = conn.execute(
+ web_push_subscriptions.update()
+ .where(web_push_subscriptions.c.endpoint == endpoint)
+ .values(enabled=0, updated_at=now)
+ )
+ return bool(result.rowcount)
+
+
+def count_enabled(conn: Connection, *, user_key: str | None = None) -> int:
+ stmt = select(func.count()).select_from(web_push_subscriptions).where(web_push_subscriptions.c.enabled == 1)
+ if user_key is not None:
+ stmt = stmt.where(web_push_subscriptions.c.user_key == user_key)
+ return int(conn.execute(stmt).scalar_one())
+
+
+def list_enabled(conn: Connection, *, user_key: str | None = None) -> list[dict[str, Any]]:
+ stmt = select(web_push_subscriptions).where(web_push_subscriptions.c.enabled == 1)
+ if user_key is not None:
+ stmt = stmt.where(web_push_subscriptions.c.user_key == user_key)
+ rows = conn.execute(stmt).mappings().all()
+ return [_row_to_dict(row) for row in rows]
+
+
+def mark_send_success(conn: Connection, *, endpoint: str) -> None:
+ now = _utc_now_iso()
+ conn.execute(
+ web_push_subscriptions.update()
+ .where(web_push_subscriptions.c.endpoint == endpoint)
+ .values(last_success_at=now, last_failure_at=None, failure_count=0, updated_at=now)
+ )
+
+
+def mark_send_failure(conn: Connection, *, endpoint: str, disable: bool = False) -> None:
+ now = _utc_now_iso()
+ values = {
+ "last_failure_at": now,
+ "failure_count": web_push_subscriptions.c.failure_count + 1,
+ "updated_at": now,
+ }
+ if disable:
+ values["enabled"] = 0
+ conn.execute(
+ web_push_subscriptions.update().where(web_push_subscriptions.c.endpoint == endpoint).values(**values)
+ )
diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.py
index a83a582e3..fb1865d71 100644
--- a/tests/test_message_mirror.py
+++ b/tests/test_message_mirror.py
@@ -208,11 +208,19 @@ def test_persist_agent_publishes_message_and_inbox_for_avibe(isolated_state):
platform_specific={"agent_session_id": "ses_pub", "vibe_agent_name": "Atlas"},
)
+ notifications = []
+
+ def fake_notify(message, inbox_row):
+ notifications.append((message, inbox_row))
+
async def scenario():
sub_id, queue = inbox_events.bus.subscribe()
events = {}
try:
- persist_agent_message(ctx, "result", "final answer")
+ from unittest.mock import patch
+
+ with patch("core.web_push_notifications.maybe_notify_inbox_message", fake_notify):
+ persist_agent_message(ctx, "result", "final answer")
# Drain both events (order: message.new, then inbox.session.updated).
for _ in range(2):
event_type, data = await asyncio.wait_for(queue.get(), timeout=1.0)
@@ -235,6 +243,8 @@ def test_persist_agent_publishes_message_and_inbox_for_avibe(isolated_state):
assert card["session_id"] == "ses_pub"
assert card["preview_text"] == "final answer"
assert card["title"] == "Published"
+ assert notifications[0][0]["text"] == "final answer"
+ assert notifications[0][1]["session_id"] == "ses_pub"
# The row was persisted too (publish is in addition to, not instead of).
with engine.connect() as conn:
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index ceed4ba0e..b117bb77e 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -16,7 +16,7 @@ from storage.models import metadata
from storage.settings_service import SQLiteSettingsService
-HEAD_REVISION = "20260604_0015"
+HEAD_REVISION = "20260604_0016"
def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
@@ -41,6 +41,7 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
assert "show_pages" in tables
assert "show_session_events" in tables
assert "media_objects" in tables
+ assert "web_push_subscriptions" in tables
media_columns = {
row[1] for row in conn.execute("pragma table_info(media_objects)")
}
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 5e2bc38e0..1787ed681 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -1,5 +1,6 @@
import pytest
+from storage.importer import ensure_sqlite_state
from vibe.ui_compat import CompatApp, normalize_response, route_path_to_fastapi, run_maybe_async, request
from starlette.websockets import WebSocketDisconnect
@@ -130,3 +131,113 @@ def test_wechat_qr_poll_marks_bind_hint_and_schedules_managed_restart(monkeypatc
assert response.get_json()["status"] == "confirmed"
assert bound_users == ["wx-user"]
assert restart_calls == [True]
+
+
+def test_web_push_subscription_routes_roundtrip(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+
+ client = app.test_client()
+ headers = csrf_headers(client)
+ subscription = {
+ "endpoint": "https://push.example.test/sub/1",
+ "keys": {
+ "p256dh": "p256dh-key",
+ "auth": "auth-secret",
+ },
+ }
+
+ created = client.post(
+ "/api/web-push/subscriptions",
+ json={"subscription": subscription, "device_label": "iPhone"},
+ headers=headers,
+ )
+ assert created.status_code == 200
+ created_body = created.get_json()
+ assert created_body["ok"] is True
+ assert created_body["subscription"]["endpoint"] == subscription["endpoint"]
+ assert created_body["subscription"]["enabled"] is True
+ assert created_body["subscription"]["device_label"] == "iPhone"
+
+ status = client.get("/api/web-push/status")
+ assert status.status_code == 200
+ status_body = status.get_json()
+ assert status_body["ok"] is True
+ assert status_body["configured"] is True
+ assert status_body["public_key"]
+ assert status_body["subscription_count"] == 1
+
+ removed = client.delete(
+ "/api/web-push/subscriptions",
+ json={"endpoint": subscription["endpoint"]},
+ headers=headers,
+ )
+ assert removed.status_code == 200
+ assert removed.get_json() == {"ok": True, "disabled": True}
+
+ status_after = client.get("/api/web-push/status")
+ assert status_after.get_json()["subscription_count"] == 0
+
+
+def test_web_push_test_route_sends_to_enabled_subscriptions(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+
+ sends = []
+ monkeypatch.setattr(
+ "core.web_push.send_web_push",
+ lambda *, subscription, payload: sends.append((subscription, payload)),
+ )
+
+ client = app.test_client()
+ headers = csrf_headers(client)
+ subscription = {
+ "endpoint": "https://push.example.test/sub/1",
+ "keys": {
+ "p256dh": "p256dh-key",
+ "auth": "auth-secret",
+ },
+ }
+
+ empty = client.post("/api/web-push/test", json={}, headers=headers)
+ assert empty.status_code == 404
+ assert empty.get_json()["error"] == "no_subscription"
+
+ client.post("/api/web-push/subscriptions", json={"subscription": subscription}, headers=headers)
+ sent = client.post(
+ "/api/web-push/test",
+ json={"title": "Hello", "body": "World", "url": "/inbox"},
+ headers=headers,
+ )
+
+ assert sent.status_code == 200
+ assert sent.get_json() == {"ok": True, "sent": 1, "failed": 0}
+ assert sends[0][0]["endpoint"] == subscription["endpoint"]
+ assert sends[0][1]["title"] == "Hello"
+
+
+def test_sessions_create_stores_web_push_owner(monkeypatch, tmp_path):
+ from storage.db import create_sqlite_engine
+ from storage.projects_service import create_project
+
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ monkeypatch.setattr(ui_server, "_web_push_user_key", lambda: "remote:user-a")
+
+ engine = create_sqlite_engine()
+ project_dir = tmp_path / "project"
+ project_dir.mkdir()
+ with engine.begin() as conn:
+ project = create_project(conn, str(project_dir), display_name="Project")
+
+ client = app.test_client()
+ response = client.post(
+ "/api/sessions",
+ json={"project_id": project["id"], "metadata": {"client": "test"}},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 201
+ metadata = response.get_json()["metadata"]
+ assert metadata["client"] == "test"
+ assert metadata["_web_push_user_key"] == "remote:user-a"
diff --git a/tests/test_web_push_notifications.py b/tests/test_web_push_notifications.py
new file mode 100644
index 000000000..d08232511
--- /dev/null
+++ b/tests/test_web_push_notifications.py
@@ -0,0 +1,128 @@
+from __future__ import annotations
+
+from core import web_push_notifications
+from storage.importer import ensure_sqlite_state
+from storage import web_push_service
+from storage.db import create_sqlite_engine
+from storage.models import agent_sessions
+from storage.settings_service import upsert_scope
+
+
+def test_maybe_notify_inbox_message_schedules_agent_result(monkeypatch):
+ calls = []
+
+ class _Thread:
+ def __init__(self, *, target, args, daemon):
+ assert daemon is True
+ self.target = target
+ self.args = args
+
+ def start(self):
+ calls.append(self.args[0])
+
+ monkeypatch.setattr(web_push_notifications.threading, "Thread", _Thread)
+
+ web_push_notifications.maybe_notify_inbox_message(
+ {
+ "id": "msg_1",
+ "platform": "avibe",
+ "author": "agent",
+ "type": "result",
+ "session_id": "ses_1",
+ "text": "Done",
+ },
+ {
+ "title": "Build fix",
+ "project_name": "Vibe Remote",
+ "preview_text": "Done",
+ "unread_count": 2,
+ },
+ )
+
+ assert calls == [
+ {
+ "title": "Build fix",
+ "body": "Done",
+ "url": "/chat/ses_1",
+ "tag": "session:ses_1",
+ "badge_count": 2,
+ "message_id": "msg_1",
+ "session_id": "ses_1",
+ }
+ ]
+
+
+def test_maybe_notify_inbox_message_skips_non_notifiable(monkeypatch):
+ calls = []
+ monkeypatch.setattr(
+ web_push_notifications.threading,
+ "Thread",
+ lambda *args, **kwargs: calls.append((args, kwargs)),
+ )
+
+ web_push_notifications.maybe_notify_inbox_message(
+ {
+ "id": "msg_1",
+ "platform": "avibe",
+ "author": "agent",
+ "type": "assistant",
+ "session_id": "ses_1",
+ "text": "thinking",
+ },
+ {"title": "Build fix"},
+ )
+
+ assert calls == []
+
+
+def test_send_to_enabled_subscriptions_uses_session_owner(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-06-04T00:00:00Z"
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_x", now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_owner",
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor="ses_owner",
+ native_session_id="",
+ title="Owner",
+ status="active",
+ metadata_json='{"_web_push_user_key":"remote:user-a"}',
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload={
+ "endpoint": "https://push.example.test/a",
+ "keys": {"p256dh": "a-key", "auth": "a-auth"},
+ },
+ )
+ web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-b",
+ payload={
+ "endpoint": "https://push.example.test/b",
+ "keys": {"p256dh": "b-key", "auth": "b-auth"},
+ },
+ )
+
+ sends = []
+ monkeypatch.setattr(
+ "core.web_push.send_web_push",
+ lambda *, subscription, payload: sends.append((subscription, payload)),
+ )
+
+ web_push_notifications._send_to_enabled_subscriptions(
+ {"title": "Owner", "body": "Done", "session_id": "ses_owner"}
+ )
+
+ assert [send[0]["endpoint"] for send in sends] == ["https://push.example.test/a"]
diff --git a/tests/test_web_push_service.py b/tests/test_web_push_service.py
new file mode 100644
index 000000000..2bc3f2b4c
--- /dev/null
+++ b/tests/test_web_push_service.py
@@ -0,0 +1,67 @@
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from core.web_push import load_or_create_vapid_keys
+from storage import web_push_service
+from storage.db import create_sqlite_engine
+from storage.migrations import run_migrations
+
+
+def _payload(endpoint: str = "https://push.example.test/sub/1") -> dict:
+ return {
+ "endpoint": endpoint,
+ "keys": {
+ "p256dh": "p256dh-key",
+ "auth": "auth-secret",
+ },
+ }
+
+
+def test_subscription_upsert_and_disable(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ with engine.begin() as conn:
+ row = web_push_service.upsert_subscription(conn, user_key="local", payload=_payload(), user_agent="ua1")
+ assert row["enabled"] is True
+ assert row["user_agent"] == "ua1"
+ assert web_push_service.count_enabled(conn, user_key="local") == 1
+
+ updated = web_push_service.upsert_subscription(conn, user_key="local", payload=_payload(), user_agent="ua2")
+ assert updated["id"] == row["id"]
+ assert updated["user_agent"] == "ua2"
+ assert web_push_service.count_enabled(conn, user_key="local") == 1
+
+ assert web_push_service.disable_subscription(conn, endpoint=_payload()["endpoint"]) is True
+ assert web_push_service.count_enabled(conn, user_key="local") == 0
+
+
+ ("payload", "error"),
+ [
+ ({}, "endpoint_required"),
+ ({"endpoint": "http://example.test", "keys": {"p256dh": "x", "auth": "y"}}, "endpoint_must_be_https"),
+ ({"endpoint": "https://example.test", "keys": {}}, "p256dh_required"),
+ ({"endpoint": "https://example.test", "keys": {"p256dh": "x"}}, "auth_required"),
+ ],
+)
+def test_validate_subscription_payload_rejects_bad_input(payload, error):
+ with pytest.raises(ValueError, match=error):
+ web_push_service.validate_subscription_payload(payload)
+
+
+def test_vapid_keys_are_stable(tmp_path):
+ key_path = tmp_path / "web_push_vapid.json"
+
+ first = load_or_create_vapid_keys(key_path)
+ second = load_or_create_vapid_keys(key_path)
+
+ assert first == second
+ assert first.public_key
+ assert "PRIVATE KEY" in first.private_key_pem
+ stored = json.loads(key_path.read_text(encoding="utf-8"))
+ assert stored["public_key"] == first.public_key
diff --git a/ui/index.html b/ui/index.html
index daa6f5212..09924af0a 100644
--- a/ui/index.html
+++ b/ui/index.html
@@ -14,7 +14,8 @@
<!-- PWA / iOS standalone: "Add to Home Screen" launches a full-screen app
(no Safari chrome), which sidesteps the iOS keyboard whitespace/accessory
- bar issues. No service worker on purpose — assets stay network-fresh (Vite
+ bar issues. We register the push service worker only after the user
+ opts into notifications; app assets stay network-fresh (Vite
content-hashes JS/CSS), so frontend updates always land. -->
<!-- use-credentials: the manifest sits behind the remote-access auth cookie
(it's not in the public-exempt paths), so the browser must send creds or
diff --git a/ui/public/push-sw.js b/ui/public/push-sw.js
new file mode 100644
index 000000000..4628ae913
--- /dev/null
+++ b/ui/public/push-sw.js
@@ -0,0 +1,40 @@
+self.addEventListener('push', (event) => {
+ let payload = {};
+ try {
+ payload = event.data ? event.data.json() : {};
+ } catch {
+ payload = {};
+ }
+
+ const title = typeof payload.title === 'string' && payload.title ? payload.title : 'Vibe Remote';
+ const url = typeof payload.url === 'string' && payload.url ? payload.url : '/inbox';
+ const options = {
+ body: typeof payload.body === 'string' ? payload.body : '',
+ tag: typeof payload.tag === 'string' ? payload.tag : undefined,
+ data: { url },
+ icon: '/icon-192.png',
+ badge: '/icon-192.png',
+ };
+
+ event.waitUntil(self.registration.showNotification(title, options));
+});
+
+self.addEventListener('notificationclick', (event) => {
+ event.notification.close();
+ const targetUrl = new URL(event.notification.data?.url || '/inbox', self.location.origin).href;
+
+ event.waitUntil(
+ self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clients) => {
+ for (const client of clients) {
+ if ('focus' in client && new URL(client.url).origin === self.location.origin) {
+ client.navigate(targetUrl);
+ return client.focus();
+ }
+ }
+ if (self.clients.openWindow) {
+ return self.clients.openWindow(targetUrl);
+ }
+ return undefined;
+ }),
+ );
+});
diff --git a/ui/src/components/workbench/InboxPage.tsx b/ui/src/components/workbench/InboxPage.tsx
index 86ce42f46..f08e8c779 100644
--- a/ui/src/components/workbench/InboxPage.tsx
+++ b/ui/src/components/workbench/InboxPage.tsx
@@ -8,6 +8,7 @@ import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
import type { InboxSession } from '../../context/ApiContext';
import { formatRelativeTime } from '../../lib/relativeTime';
import { Markdown } from '../ui/markdown';
+import { WebPushControl } from './WebPushControl';
type FilterMode = 'unread' | 'all';
@@ -117,6 +118,7 @@ export const InboxPage: React.FC = () => {
))}
</div>
<div className="flex-1" />
+ <WebPushControl />
<button
type="button"
onClick={onMarkAllRead}
diff --git a/ui/src/components/workbench/WebPushControl.tsx b/ui/src/components/workbench/WebPushControl.tsx
new file mode 100644
index 000000000..c7b298ebe
--- /dev/null
+++ b/ui/src/components/workbench/WebPushControl.tsx
@@ -0,0 +1,131 @@
+import { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Bell, BellOff, Loader2, Smartphone } from 'lucide-react';
+
+import { useApi } from '@/context/ApiContext';
+import { Button } from '../ui/button';
+import { Badge } from '../ui/badge';
+import {
+ disableWebPush,
+ enableWebPush,
+ getExistingWebPushSubscription,
+ getWebPushSupportState,
+ type WebPushSupportState,
+} from '@/lib/webPush';
+
+type Status = 'checking' | 'unsupported' | 'needs_install' | 'disabled' | 'enabled';
+
+export const WebPushControl: React.FC = () => {
+ const { t } = useTranslation();
+ const api = useApi();
+ const [status, setStatus] = useState<Status>('checking');
+ const [busy, setBusy] = useState(false);
+ const [testing, setTesting] = useState(false);
+ const [support, setSupport] = useState<WebPushSupportState | null>(null);
+
+ const refresh = async () => {
+ const nextSupport = getWebPushSupportState();
+ setSupport(nextSupport);
+ if (!nextSupport.supported) {
+ setStatus(nextSupport.reason === 'ios_requires_standalone' ? 'needs_install' : 'unsupported');
+ return;
+ }
+ const existing = await getExistingWebPushSubscription();
+ setStatus(existing ? 'enabled' : 'disabled');
+ };
+
+ useEffect(() => {
+ void refresh();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const onEnable = async () => {
+ setBusy(true);
+ try {
+ await enableWebPush(api);
+ setStatus('enabled');
+ } catch {
+ await refresh();
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const onDisable = async () => {
+ setBusy(true);
+ try {
+ await disableWebPush(api);
+ setStatus('disabled');
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const onTest = async () => {
+ setTesting(true);
+ try {
+ await api.sendWebPushTest({
+ title: t('workbench.inbox.notifications.testTitle'),
+ body: t('workbench.inbox.notifications.testBody'),
+ url: '/inbox',
+ });
+ } finally {
+ setTesting(false);
+ }
+ };
+
+ if (status === 'checking') {
+ return (
+ <Badge variant="secondary" className="h-8 rounded-lg px-3">
+ <Loader2 className="size-3 animate-spin" />
+ {t('workbench.inbox.notifications.checking')}
+ </Badge>
+ );
+ }
+
+ if (status === 'unsupported') {
+ return (
+ <Badge variant="secondary" className="h-8 rounded-lg px-3">
+ <BellOff className="size-3" />
+ {t('workbench.inbox.notifications.unsupported')}
+ </Badge>
+ );
+ }
+
+ if (status === 'needs_install') {
+ return (
+ <Badge variant="warning" className="h-8 rounded-lg px-3">
+ <Smartphone className="size-3" />
+ {t('workbench.inbox.notifications.installFirst')}
+ </Badge>
+ );
+ }
+
+ if (status === 'enabled') {
+ return (
+ <div className="flex items-center gap-2">
+ <Badge variant="success" className="h-8 rounded-lg px-3">
+ <Bell className="size-3" />
+ {support?.supported && support.requiresStandalone
+ ? t('workbench.inbox.notifications.enabledPwa')
+ : t('workbench.inbox.notifications.enabled')}
+ </Badge>
+ <Button type="button" variant="secondary" size="xs" onClick={onTest} disabled={testing || busy}>
+ {testing ? <Loader2 className="animate-spin" /> : <Bell className="size-3.5" />}
+ {t('workbench.inbox.notifications.test')}
+ </Button>
+ <Button type="button" variant="ghost" size="xs" onClick={onDisable} disabled={busy || testing}>
+ {busy ? <Loader2 className="animate-spin" /> : <BellOff className="size-3.5" />}
+ {t('workbench.inbox.notifications.disable')}
+ </Button>
+ </div>
+ );
+ }
+
+ return (
+ <Button type="button" variant="outline-cyan" size="xs" onClick={onEnable} disabled={busy}>
+ {busy ? <Loader2 className="animate-spin" /> : <Bell className="size-3.5" />}
+ {t('workbench.inbox.notifications.enable')}
+ </Button>
+ );
+};
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 639290ca0..084790f93 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -27,6 +27,11 @@ export type ApiContextType = {
toggleAdmin: (userId: string, isAdmin: boolean, platform?: string) => Promise<any>;
removeUser: (userId: string, platform?: string) => Promise<any>;
getShowPages: () => Promise<any>;
+ getWebPushStatus: () => Promise<WebPushStatus>;
+ getWebPushVapidPublicKey: () => Promise<{ ok: boolean; public_key: string }>;
+ subscribeWebPush: (subscription: PushSubscriptionJSON, deviceLabel?: string) => Promise<WebPushSubscriptionResult>;
+ unsubscribeWebPush: (endpoint: string) => Promise<{ ok: boolean; disabled: boolean }>;
+ sendWebPushTest: (payload?: { title?: string; body?: string; url?: string }) => Promise<WebPushTestResult>;
setShowPageVisibility: (sessionId: string, visibility: string) => Promise<any>;
rotateShowPageShare: (sessionId: string) => Promise<any>;
getBindCodes: () => Promise<any>;
@@ -923,6 +928,32 @@ export type OpencodeMutationResult = {
default_provider?: string;
};
+export type WebPushStatus = {
+ ok: boolean;
+ configured: boolean;
+ public_key: string;
+ subscription_count: number;
+};
+
+export type WebPushSubscriptionResult = {
+ ok: boolean;
+ subscription: {
+ id: string;
+ user_key: string;
+ endpoint: string;
+ enabled: boolean;
+ user_agent?: string | null;
+ device_label?: string | null;
+ };
+};
+
+export type WebPushTestResult = {
+ ok: boolean;
+ sent?: number;
+ failed?: number;
+ error?: string;
+};
+
// Error thrown by the JSON helpers below when a request fails. Carries the
// HTTP status and the server's machine-readable ``error`` code (when the body
// includes one) so callers can branch on *why* a request failed instead of
@@ -1016,8 +1047,16 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
// ``getJson``/``postJson``. Legacy callers (removeUser, deleteBindCode)
// still call ``apiFetch().then(r => r.json())`` directly — that's a
// separate cleanup; new endpoints should use this helper.
- const deleteJson = async (path: string) => {
- const res = await apiFetch(path, { method: 'DELETE' });
+ const deleteJson = async (path: string, payload?: any) => {
+ const res = await apiFetch(path, {
+ method: 'DELETE',
+ ...(payload === undefined
+ ? {}
+ : {
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(payload),
+ }),
+ });
if (!res.ok) {
await handleApiError(res, path);
}
@@ -1114,6 +1153,15 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
toggleAdmin: (userId, isAdmin, platform) => postJson(`/api/users/${encodeURIComponent(userId)}/admin`, platform ? { is_admin: isAdmin, platform } : { is_admin: isAdmin }),
removeUser: (userId, platform) => apiFetch(platform ? `/api/users/${encodeURIComponent(userId)}?platform=${encodeURIComponent(platform)}` : `/api/users/${encodeURIComponent(userId)}`, { method: 'DELETE' }).then(r => r.json()),
getShowPages: () => getJson('/api/show-pages'),
+ getWebPushStatus: () => getJson('/api/web-push/status'),
+ getWebPushVapidPublicKey: () => getJson('/api/web-push/vapid-public-key'),
+ subscribeWebPush: (subscription, deviceLabel) =>
+ postJson('/api/web-push/subscriptions', {
+ subscription,
+ device_label: deviceLabel,
+ }),
+ unsubscribeWebPush: (endpoint) => deleteJson('/api/web-push/subscriptions', { endpoint }),
+ sendWebPushTest: (payload) => postJson('/api/web-push/test', payload ?? {}),
setShowPageVisibility: (sessionId, visibility) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/visibility`, { visibility }),
rotateShowPageShare: (sessionId) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/rotate-share`, {}),
getBindCodes: () => getJson('/api/bind-codes'),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index c9ef25109..806a6b3d0 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -592,7 +592,19 @@
"you": "You",
"replied": "Replied",
"loadMore": "Load more",
- "moreUnreadBeyond": "More unread sessions may be further down — load more to see them."
+ "moreUnreadBeyond": "More unread sessions may be further down — load more to see them.",
+ "notifications": {
+ "checking": "Checking notifications",
+ "unsupported": "Notifications unavailable",
+ "installFirst": "Add to Home Screen first",
+ "enable": "Enable notifications",
+ "enabled": "Notifications on",
+ "enabledPwa": "PWA notifications on",
+ "disable": "Disable",
+ "test": "Test",
+ "testTitle": "Vibe Remote",
+ "testBody": "Notifications are ready."
+ }
},
"modules": {
"comingSoonEyebrow": "Coming soon",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index c4ea59ab2..4d5beb4f0 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -592,7 +592,19 @@
"you": "我",
"replied": "已回复",
"loadMore": "加载更多",
- "moreUnreadBeyond": "还有未读会话在后面的分页里,点击「加载更多」查看。"
+ "moreUnreadBeyond": "还有未读会话在后面的分页里,点击「加载更多」查看。",
+ "notifications": {
+ "checking": "正在检查通知",
+ "unsupported": "当前不支持通知",
+ "installFirst": "先添加到主屏幕",
+ "enable": "开启通知",
+ "enabled": "通知已开启",
+ "enabledPwa": "PWA 通知已开启",
+ "disable": "关闭",
+ "test": "测试",
+ "testTitle": "Vibe Remote",
+ "testBody": "通知已经准备好了。"
+ }
},
"modules": {
"comingSoonEyebrow": "即将就位",
diff --git a/ui/src/lib/webPush.ts b/ui/src/lib/webPush.ts
new file mode 100644
index 000000000..c7be35c01
--- /dev/null
+++ b/ui/src/lib/webPush.ts
@@ -0,0 +1,71 @@
+import type { ApiContextType } from '@/context/ApiContext';
+import { isIosDevice, isStandalonePwa } from './platform';
+
+export type WebPushSupportState =
+ | { supported: true; standalone: boolean; requiresStandalone: boolean }
+ | { supported: false; reason: 'unsupported' | 'ios_requires_standalone' };
+
+function urlBase64ToArrayBuffer(value: string): ArrayBuffer {
+ const padding = '='.repeat((4 - (value.length % 4)) % 4);
+ const base64 = (value + padding).replace(/-/g, '+').replace(/_/g, '/');
+ const raw = window.atob(base64);
+ const output = new Uint8Array(raw.length);
+ for (let i = 0; i < raw.length; i += 1) output[i] = raw.charCodeAt(i);
+ return output.buffer;
+}
+
+export function getWebPushSupportState(): WebPushSupportState {
+ if (typeof window === 'undefined' || typeof navigator === 'undefined') {
+ return { supported: false, reason: 'unsupported' };
+ }
+ const hasApis = 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window;
+ if (!hasApis) return { supported: false, reason: 'unsupported' };
+ const standalone = isStandalonePwa();
+ if (isIosDevice() && !standalone) {
+ return { supported: false, reason: 'ios_requires_standalone' };
+ }
+ return { supported: true, standalone, requiresStandalone: isIosDevice() };
+}
+
+export async function getExistingWebPushSubscription(): Promise<PushSubscription | null> {
+ if (!('serviceWorker' in navigator)) return null;
+ const registration = await navigator.serviceWorker.getRegistration('/push-sw.js');
+ return registration?.pushManager.getSubscription() ?? null;
+}
+
+export async function enableWebPush(api: ApiContextType): Promise<PushSubscriptionJSON> {
+ const support = getWebPushSupportState();
+ if (!support.supported) {
+ throw new Error(support.reason);
+ }
+ const permission = await Notification.requestPermission();
+ if (permission !== 'granted') {
+ throw new Error('permission_denied');
+ }
+
+ const registration = await navigator.serviceWorker.register('/push-sw.js');
+ const existing = await registration.pushManager.getSubscription();
+ const subscription =
+ existing ??
+ (await registration.pushManager.subscribe({
+ userVisibleOnly: true,
+ applicationServerKey: urlBase64ToArrayBuffer((await api.getWebPushVapidPublicKey()).public_key),
+ }));
+
+ const json = subscription.toJSON();
+ await api.subscribeWebPush(json);
+ return json;
+}
+
+export async function disableWebPush(api: ApiContextType): Promise<boolean> {
+ const subscription = await getExistingWebPushSubscription();
+ const endpoint = subscription?.endpoint;
+ if (subscription) {
+ await subscription.unsubscribe();
+ }
+ if (endpoint) {
+ await api.unsubscribeWebPush(endpoint);
+ return true;
+ }
+ return false;
+}
diff --git a/uv.lock b/uv.lock
index dd019c1ae..48f373ae8 100644
--- a/uv.lock
+++ b/uv.lock
@@ -815,6 +815,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" },
]
+[[package]]
+name = "http-ece"
+version = "1.2.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cryptography" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/7c/af/249d1576653b69c20b9ac30e284b63bd94af6a175d72d87813235caf2482/http_ece-1.2.1.tar.gz", hash = "sha256:8c6ab23116bbf6affda894acfd5f2ca0fb8facbcbb72121c11c75c33e7ce8cff", size = 8830, upload-time = "2024-08-08T00:10:47.301Z" }
+
[[package]]
name = "httpcore"
version = "1.0.9"
@@ -1398,6 +1407,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" },
]
+[[package]]
+name = "py-vapid"
+version = "1.9.4"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cryptography" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/a3/ed/c648c8018fab319951764f4babe68ddcbbff7f2bbcd7ff7e531eac1788c8/py_vapid-1.9.4.tar.gz", hash = "sha256:a004023560cbc54e34fc06380a0580f04ffcc788e84fb6d19e9339eeb6551a28", size = 74750, upload-time = "2026-01-05T22:13:25.201Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7f/15/f9d0171e1ad863ca49e826d5afb6b50566f20dc9b4f76965096d3555ce9e/py_vapid-1.9.4-py2.py3-none-any.whl", hash = "sha256:f165a5bf90dcf966b226114f01f178f137579a09784c7f0628fa2f0a299741b6", size = 23912, upload-time = "2026-01-05T20:42:05.455Z" },
+]
+
[[package]]
name = "pycparser"
version = "2.23"
@@ -1662,6 +1683,22 @@ asyncio = [
{ name = "async-timeout", marker = "python_full_version < '3.11'" },
]
+[[package]]
+name = "pywebpush"
+version = "2.3.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "aiohttp" },
+ { name = "cryptography" },
+ { name = "http-ece" },
+ { name = "py-vapid" },
+ { name = "requests" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/87/d9/e497a24bc9f659bfc0e570382a41e6b2d6726fbcfa4d85aaa23fe9c81ba2/pywebpush-2.3.0.tar.gz", hash = "sha256:d1e27db8de9e6757c1875f67292554bd54c41874c36f4b5c4ebb5442dce204f2", size = 28489, upload-time = "2026-02-09T23:30:18.574Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/3d/d8/ac21241cf8007cb93255eabf318da4f425ec0f75d28c366992253aa8c1b2/pywebpush-2.3.0-py3-none-any.whl", hash = "sha256:3d97469fb14d4323c362319d438183737249a4115b50e146ce233e7f01e3cf98", size = 22851, upload-time = "2026-02-09T23:30:16.093Z" },
+]
+
[[package]]
name = "pywin32"
version = "311"
@@ -2223,6 +2260,7 @@ dependencies = [
{ name = "pyjwt", extra = ["crypto"] },
{ name = "python-multipart" },
{ name = "python-socks", extra = ["asyncio"] },
+ { name = "pywebpush" },
{ name = "pyyaml" },
{ name = "requests" },
{ name = "sentry-sdk" },
@@ -2257,6 +2295,7 @@ requires-dist = [
{ name = "pyjwt", extras = ["crypto"], specifier = ">=2.9.0" },
{ name = "python-multipart", specifier = ">=0.0.9" },
{ name = "python-socks", extras = ["asyncio"], specifier = ">=2.0.0" },
+ { name = "pywebpush", specifier = ">=2.0.3" },
{ name = "pyyaml", specifier = ">=6.0" },
{ name = "requests", specifier = ">=2.31.0" },
{ name = "sentry-sdk", specifier = ">=2.0.0" },
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 9fd1ac26d..81cc0de8c 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1781,6 +1781,129 @@ def csrf_token_get():
return response
+def _web_push_user_key() -> str:
+ """Best-effort local user key for browser push subscriptions.
+
+ 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.
+ """
+
+ config = _load_remote_access_config()
+ if config is not None:
+ try:
+ from vibe import remote_access
+
+ payload = remote_access.parse_session_cookie(
+ config, request.cookies.get(remote_access.SESSION_COOKIE_NAME)
+ )
+ 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"
+
+
[email protected]("/api/web-push/status", methods=["GET"])
+def web_push_status():
+ from core.web_push import load_or_create_vapid_keys
+ from storage import web_push_service
+
+ keys = load_or_create_vapid_keys()
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ subscription_count = web_push_service.count_enabled(conn, user_key=_web_push_user_key())
+ return jsonify(
+ {
+ "ok": True,
+ "configured": True,
+ "public_key": keys.public_key,
+ "subscription_count": subscription_count,
+ }
+ )
+
+
[email protected]("/api/web-push/vapid-public-key", methods=["GET"])
+def web_push_vapid_public_key():
+ from core.web_push import load_or_create_vapid_keys
+
+ keys = load_or_create_vapid_keys()
+ return jsonify({"ok": True, "public_key": keys.public_key})
+
+
[email protected]("/api/web-push/subscriptions", methods=["POST"])
+def web_push_subscribe():
+ from storage import web_push_service
+
+ payload = request.json or {}
+ user_agent = request.headers.get("User-Agent")
+ device_label = payload.get("device_label") if isinstance(payload.get("device_label"), str) else None
+ subscription = payload.get("subscription") if isinstance(payload.get("subscription"), dict) else payload
+ engine = _projects_engine()
+ try:
+ with engine.begin() as conn:
+ row = web_push_service.upsert_subscription(
+ conn,
+ user_key=_web_push_user_key(),
+ payload=subscription,
+ user_agent=user_agent,
+ device_label=device_label,
+ )
+ except ValueError as exc:
+ return jsonify({"ok": False, "error": str(exc)}), 400
+ return jsonify({"ok": True, "subscription": row})
+
+
[email protected]("/api/web-push/subscriptions", methods=["DELETE"])
+def web_push_unsubscribe():
+ from storage import web_push_service
+
+ payload = request.json or {}
+ endpoint = payload.get("endpoint")
+ if not isinstance(endpoint, str) or not endpoint.strip():
+ return jsonify({"ok": False, "error": "endpoint_required"}), 400
+ engine = _projects_engine()
+ with engine.begin() as conn:
+ disabled = web_push_service.disable_subscription(conn, endpoint=endpoint)
+ return jsonify({"ok": True, "disabled": disabled})
+
+
[email protected]("/api/web-push/test", methods=["POST"])
+def web_push_test():
+ from core.web_push import send_web_push
+ from storage import web_push_service
+
+ payload = request.json or {}
+ notification = {
+ "title": payload.get("title") if isinstance(payload.get("title"), str) else "Vibe Remote",
+ "body": payload.get("body") if isinstance(payload.get("body"), str) else "Test notification",
+ "url": payload.get("url") if isinstance(payload.get("url"), str) else "/inbox",
+ "tag": "web-push-test",
+ }
+ user_key = _web_push_user_key()
+ engine = _projects_engine()
+ sent = 0
+ failed = 0
+ with engine.begin() as conn:
+ subscriptions = web_push_service.list_enabled(conn, user_key=user_key)
+ if not subscriptions:
+ return jsonify({"ok": False, "error": "no_subscription"}), 404
+ for subscription in subscriptions:
+ try:
+ send_web_push(subscription=subscription, payload=notification)
+ web_push_service.mark_send_success(conn, endpoint=subscription["endpoint"])
+ sent += 1
+ except Exception as exc:
+ logger.warning("web push: test send failed", exc_info=True)
+ status_code = getattr(getattr(exc, "response", None), "status_code", None)
+ web_push_service.mark_send_failure(
+ conn,
+ endpoint=subscription["endpoint"],
+ disable=status_code in {404, 410},
+ )
+ failed += 1
+ return jsonify({"ok": failed == 0, "sent": sent, "failed": failed})
+
+
@app.route("/api/cli/detect")
def cli_detect():
from vibe import api
@@ -3149,6 +3272,8 @@ def sessions_create():
# Vibe Agent — including default_agent_name — at dispatch time.
scope_id = _project_to_scope_id(project_id)
+ metadata = payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {}
+ metadata = {**metadata, "_web_push_user_key": _web_push_user_key()}
engine = _projects_engine()
try:
with engine.begin() as conn:
@@ -3162,7 +3287,7 @@ def sessions_create():
model=payload.get("model"),
reasoning_effort=payload.get("reasoning_effort"),
title=payload.get("title"),
- metadata=payload.get("metadata"),
+ metadata=metadata,
)
except LookupError as err:
return jsonify({"error": str(err)}), 404