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(ui): dedupe Web Push subscriptions by device (#441)

Call White559cedc67244
diff --git a/storage/alembic/versions/20260604_0017_web_push_subscription_device_id.py b/storage/alembic/versions/20260604_0017_web_push_subscription_device_id.py
new file mode 100644
index 000000000..a0f807ddc
--- /dev/null
+++ b/storage/alembic/versions/20260604_0017_web_push_subscription_device_id.py
@@ -0,0 +1,36 @@
+"""add device_id to Web Push subscriptions
+
+Revision ID: 20260604_0017
+Revises: 20260604_0016
+Create Date: 2026-06-04
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20260604_0017"
+down_revision = "20260604_0016"
+branch_labels = None
+depends_on = None
+
+
+def _columns(table: str) -> set[str]:
+ bind = op.get_bind()
+ return {row[1] for row in bind.exec_driver_sql(f'pragma table_info("{table}")')}
+
+
+def upgrade() -> None:
+ if "device_id" not in _columns("web_push_subscriptions"):
+ op.add_column("web_push_subscriptions", sa.Column("device_id", sa.String(), nullable=True))
+ op.create_index(
+ "ix_web_push_subscriptions_user_device",
+ "web_push_subscriptions",
+ ["user_key", "device_id"],
+ if_not_exists=True,
+ )
+
+
+def downgrade() -> None:
+ op.drop_index("ix_web_push_subscriptions_user_device", table_name="web_push_subscriptions")
diff --git a/storage/migrations.py b/storage/migrations.py
index 43c272aa6..1d51ad74e 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 = "20260604_0016"
+LATEST_SCHEMA_REVISION = "20260604_0017"
REMOVE_LEGACY_DEFAULT_AGENT_REVISION = "20260530_0008"
INITIAL_TABLES = {
"state_meta",
@@ -72,6 +72,9 @@ HEAD_REQUIRED_COLUMNS = {
"cancel_requested_at",
},
}
+HEAD_ONLY_REQUIRED_COLUMNS = {
+ "web_push_subscriptions": {"device_id"},
+}
UNRELEASED_OLD_INITIAL_TABLES = [
"session_messages",
"chat_sessions",
@@ -279,7 +282,8 @@ def _column_names(conn: sqlite3.Connection, table: str) -> set[str]:
def _head_schema_ready(conn: sqlite3.Connection, tables: set[str]) -> bool:
if not HEAD_TABLES.issubset(tables):
return False
- return all(required_columns.issubset(_column_names(conn, table)) for table, required_columns in HEAD_REQUIRED_COLUMNS.items())
+ required = HEAD_REQUIRED_COLUMNS | HEAD_ONLY_REQUIRED_COLUMNS
+ return all(required_columns.issubset(_column_names(conn, table)) for table, required_columns in required.items())
def _pre_show_session_events_head_schema_ready(conn: sqlite3.Connection, tables: set[str]) -> bool:
@@ -387,6 +391,10 @@ def _repair_head_required_columns(conn: sqlite3.Connection, tables: set[str]) ->
)
changed = True
+ if "web_push_subscriptions" in tables and "device_id" not in _column_names(conn, "web_push_subscriptions"):
+ conn.execute('alter table "web_push_subscriptions" add column "device_id" VARCHAR')
+ changed = True
+
_ensure_new_background_indexes(conn)
return changed
@@ -468,7 +476,7 @@ def _ensure_new_background_indexes(conn: sqlite3.Connection) -> None:
def _missing_head_schema_description(conn: sqlite3.Connection, tables: set[str]) -> str:
missing_parts = [f"tables {', '.join(sorted(HEAD_TABLES - tables))}"] if not HEAD_TABLES.issubset(tables) else []
- for table, required_columns in HEAD_REQUIRED_COLUMNS.items():
+ for table, required_columns in (HEAD_REQUIRED_COLUMNS | HEAD_ONLY_REQUIRED_COLUMNS).items():
if table not in tables:
continue
missing_columns = required_columns - _column_names(conn, table)
diff --git a/storage/models.py b/storage/models.py
index 3222a4956..1ddb3e861 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -372,6 +372,7 @@ web_push_subscriptions = Table(
Column("endpoint", Text, nullable=False),
Column("p256dh", Text, nullable=False),
Column("auth", Text, nullable=False),
+ Column("device_id", String, nullable=True),
Column("user_agent", Text, nullable=True),
Column("device_label", Text, nullable=True),
Column("enabled", Integer, nullable=False),
@@ -382,6 +383,7 @@ web_push_subscriptions = Table(
Column("updated_at", String, nullable=False),
UniqueConstraint("endpoint", name="uq_web_push_subscriptions_endpoint"),
Index("ix_web_push_subscriptions_user_enabled", "user_key", "enabled"),
+ Index("ix_web_push_subscriptions_user_device", "user_key", "device_id"),
)
imported_state_tables = [
diff --git a/storage/web_push_service.py b/storage/web_push_service.py
index 87700f61b..ed1b53e47 100644
--- a/storage/web_push_service.py
+++ b/storage/web_push_service.py
@@ -47,6 +47,42 @@ def _row_to_dict(row: Any) -> dict[str, Any]:
return data
+def _normalize_previous_endpoints(previous_endpoints: list[str] | None, current_endpoint: str) -> list[str]:
+ if not previous_endpoints:
+ return []
+ endpoints: list[str] = []
+ seen: set[str] = {current_endpoint}
+ for endpoint in previous_endpoints:
+ if not isinstance(endpoint, str):
+ continue
+ endpoint = endpoint.strip()
+ if not endpoint or endpoint in seen:
+ continue
+ seen.add(endpoint)
+ endpoints.append(endpoint)
+ return endpoints
+
+
+def _disable_previous_endpoints(
+ conn: Connection,
+ *,
+ user_key: str,
+ endpoint: str,
+ previous_endpoints: list[str] | None,
+ now: str,
+) -> None:
+ endpoints = _normalize_previous_endpoints(previous_endpoints, endpoint)
+ if not endpoints:
+ return
+ conn.execute(
+ web_push_subscriptions.update()
+ .where(web_push_subscriptions.c.user_key == user_key)
+ .where(web_push_subscriptions.c.endpoint.in_(endpoints))
+ .where(web_push_subscriptions.c.enabled == 1)
+ .values(enabled=0, updated_at=now)
+ )
+
+
def upsert_subscription(
conn: Connection,
*,
@@ -54,15 +90,37 @@ def upsert_subscription(
payload: dict[str, Any],
user_agent: str | None = None,
device_label: str | None = None,
+ device_id: str | None = None,
+ previous_endpoints: list[str] | None = None,
) -> dict[str, Any]:
endpoint, p256dh, auth = validate_subscription_payload(payload)
+ device_id = device_id.strip() if isinstance(device_id, str) else None
+ if not device_id:
+ device_id = None
now = _utc_now_iso()
+ _disable_previous_endpoints(
+ conn,
+ user_key=user_key,
+ endpoint=endpoint,
+ previous_endpoints=previous_endpoints,
+ now=now,
+ )
+ if device_id is not None:
+ conn.execute(
+ web_push_subscriptions.update()
+ .where(web_push_subscriptions.c.user_key == user_key)
+ .where(web_push_subscriptions.c.device_id == device_id)
+ .where(web_push_subscriptions.c.endpoint != endpoint)
+ .where(web_push_subscriptions.c.enabled == 1)
+ .values(enabled=0, updated_at=now)
+ )
stmt = sqlite_insert(web_push_subscriptions).values(
id=_new_id(),
user_key=user_key,
endpoint=endpoint,
p256dh=p256dh,
auth=auth,
+ device_id=device_id,
user_agent=user_agent,
device_label=device_label,
enabled=1,
@@ -76,6 +134,7 @@ def upsert_subscription(
"user_key": user_key,
"p256dh": p256dh,
"auth": auth,
+ "device_id": device_id,
"user_agent": user_agent,
"device_label": device_label,
"enabled": 1,
@@ -90,6 +149,58 @@ def upsert_subscription(
return _row_to_dict(row)
+def attach_device_to_enabled_subscription(
+ conn: Connection,
+ *,
+ user_key: str,
+ payload: dict[str, Any],
+ user_agent: str | None = None,
+ device_label: str | None = None,
+ device_id: str | None = None,
+ previous_endpoints: list[str] | None = None,
+) -> dict[str, Any] | None:
+ endpoint, p256dh, auth = validate_subscription_payload(payload)
+ device_id = device_id.strip() if isinstance(device_id, str) else None
+ if not device_id:
+ return get_enabled_by_endpoint(conn, endpoint=endpoint, user_key=user_key)
+ now = _utc_now_iso()
+ _disable_previous_endpoints(
+ conn,
+ user_key=user_key,
+ endpoint=endpoint,
+ previous_endpoints=previous_endpoints,
+ now=now,
+ )
+ existing = get_enabled_by_endpoint(conn, endpoint=endpoint, user_key=user_key)
+ if existing is None:
+ return None
+ conn.execute(
+ web_push_subscriptions.update()
+ .where(web_push_subscriptions.c.user_key == user_key)
+ .where(web_push_subscriptions.c.device_id == device_id)
+ .where(web_push_subscriptions.c.endpoint != endpoint)
+ .where(web_push_subscriptions.c.enabled == 1)
+ .values(enabled=0, updated_at=now)
+ )
+ values = {
+ "p256dh": p256dh,
+ "auth": auth,
+ "device_id": device_id,
+ "user_agent": user_agent,
+ "updated_at": now,
+ }
+ if device_label is not None:
+ values["device_label"] = device_label
+ conn.execute(
+ web_push_subscriptions.update()
+ .where(web_push_subscriptions.c.endpoint == endpoint)
+ .where(web_push_subscriptions.c.user_key == user_key)
+ .where(web_push_subscriptions.c.enabled == 1)
+ .values(**values)
+ )
+ return get_enabled_by_endpoint(conn, endpoint=endpoint, user_key=user_key)
+
+
def disable_subscription(conn: Connection, *, endpoint: str, user_key: str | None = None) -> bool:
endpoint = endpoint.strip() if isinstance(endpoint, str) else ""
if not endpoint:
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index b117bb77e..fa21cb674 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_0016"
+HEAD_REVISION = "20260604_0017"
def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
@@ -163,9 +163,11 @@ def test_run_migrations_stamps_pre_show_events_head_schema_at_0008_then_upgrades
conn.execute("drop table show_session_events")
conn.execute("drop index if exists ix_show_session_events_session_created")
conn.execute("drop index if exists ix_show_session_events_type_created")
+ conn.execute("drop table web_push_subscriptions")
conn.commit()
assert conn.execute("select name from sqlite_master where name = 'alembic_version'").fetchone() is None
assert conn.execute("select name from sqlite_master where name = 'show_session_events'").fetchone() is None
+ assert conn.execute("select name from sqlite_master where name = 'web_push_subscriptions'").fetchone() is None
run_migrations(db_path)
run_migrations(db_path)
@@ -173,6 +175,7 @@ def test_run_migrations_stamps_pre_show_events_head_schema_at_0008_then_upgrades
with sqlite3.connect(db_path) as conn:
version = conn.execute("select version_num from alembic_version").fetchone()
show_events = conn.execute("select name from sqlite_master where name = 'show_session_events'").fetchone()
+ web_push_columns = {row[1] for row in conn.execute("pragma table_info(web_push_subscriptions)")}
background_tables = conn.execute("select count(*) from run_definitions").fetchone()
agents = dict(conn.execute("select name, backend from agents"))
default_pointer = conn.execute(
@@ -180,6 +183,7 @@ def test_run_migrations_stamps_pre_show_events_head_schema_at_0008_then_upgrades
).fetchone()[0]
assert version == (HEAD_REVISION,)
assert show_events == ("show_session_events",)
+ assert "device_id" in web_push_columns
assert background_tables == (0,)
assert "default" not in agents
assert agents["opencode"] == "opencode"
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 3109680a1..d0c609632 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -225,7 +225,7 @@ def test_web_push_subscription_routes_roundtrip(monkeypatch, tmp_path):
created = client.post(
"/api/web-push/subscriptions",
- json={"subscription": subscription, "device_label": "iPhone"},
+ json={"subscription": subscription, "device_label": "iPhone", "device_id": "device-1"},
headers=headers,
)
assert created.status_code == 200
@@ -234,6 +234,7 @@ def test_web_push_subscription_routes_roundtrip(monkeypatch, tmp_path):
assert created_body["subscription"]["endpoint"] == subscription["endpoint"]
assert created_body["subscription"]["enabled"] is True
assert created_body["subscription"]["device_label"] == "iPhone"
+ assert created_body["subscription"]["device_id"] == "device-1"
status = client.post("/api/web-push/status", json={"endpoint": subscription["endpoint"]}, headers=headers)
assert status.status_code == 200
@@ -257,6 +258,172 @@ def test_web_push_subscription_routes_roundtrip(monkeypatch, tmp_path):
assert status_after.get_json()["current_subscription_enabled"] is False
+def test_web_push_status_sync_disables_previous_endpoint_for_same_device(monkeypatch, tmp_path):
+ from storage import web_push_service
+ from storage.db import create_sqlite_engine
+
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+
+ client = app.test_client()
+ headers = csrf_headers(client)
+ old_subscription = {
+ "endpoint": "https://push.example.test/sub/old",
+ "keys": {"p256dh": "old-key", "auth": "old-auth"},
+ }
+ new_subscription = {
+ "endpoint": "https://push.example.test/sub/new",
+ "keys": {"p256dh": "new-key", "auth": "new-auth"},
+ }
+
+ created = client.post(
+ "/api/web-push/subscriptions",
+ json={"subscription": old_subscription, "device_id": "device-1"},
+ headers=headers,
+ )
+ assert created.status_code == 200
+ created = client.post(
+ "/api/web-push/subscriptions",
+ json={"subscription": new_subscription},
+ headers=headers,
+ )
+ assert created.status_code == 200
+
+ status = client.post(
+ "/api/web-push/status",
+ json={
+ "endpoint": new_subscription["endpoint"],
+ "subscription": new_subscription,
+ "device_id": "device-1",
+ },
+ headers=headers,
+ )
+
+ assert status.status_code == 200
+ assert status.get_json()["current_subscription_enabled"] is True
+ assert status.get_json()["subscription_count"] == 1
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=old_subscription["endpoint"],
+ user_key="local",
+ ) is None
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=new_subscription["endpoint"],
+ user_key="local",
+ ) is not None
+
+
+def test_web_push_status_sync_disables_client_known_previous_endpoint(monkeypatch, tmp_path):
+ from storage import web_push_service
+ from storage.db import create_sqlite_engine
+
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+
+ client = app.test_client()
+ headers = csrf_headers(client)
+ previous_subscription = {
+ "endpoint": "https://push.example.test/sub/previous",
+ "keys": {"p256dh": "previous-key", "auth": "previous-auth"},
+ }
+ current_subscription = {
+ "endpoint": "https://push.example.test/sub/current",
+ "keys": {"p256dh": "current-key", "auth": "current-auth"},
+ }
+ other_subscription = {
+ "endpoint": "https://push.example.test/sub/other",
+ "keys": {"p256dh": "other-key", "auth": "other-auth"},
+ }
+
+ for subscription in [previous_subscription, current_subscription, other_subscription]:
+ created = client.post(
+ "/api/web-push/subscriptions",
+ json={"subscription": subscription},
+ headers=headers,
+ )
+ assert created.status_code == 200
+
+ status = client.post(
+ "/api/web-push/status",
+ json={
+ "endpoint": current_subscription["endpoint"],
+ "subscription": current_subscription,
+ "device_id": "device-1",
+ "previous_endpoints": [previous_subscription["endpoint"]],
+ },
+ headers=headers,
+ )
+
+ assert status.status_code == 200
+ assert status.get_json()["current_subscription_enabled"] is True
+ assert status.get_json()["subscription_count"] == 2
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=previous_subscription["endpoint"],
+ user_key="local",
+ ) is None
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=current_subscription["endpoint"],
+ user_key="local",
+ ) is not None
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=other_subscription["endpoint"],
+ user_key="local",
+ ) is not None
+
+
+def test_web_push_status_sync_does_not_reenable_disabled_endpoint(monkeypatch, tmp_path):
+ from storage import web_push_service
+ from storage.db import create_sqlite_engine
+
+ 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/dead",
+ "keys": {"p256dh": "dead-key", "auth": "dead-auth"},
+ }
+ created = client.post(
+ "/api/web-push/subscriptions",
+ json={"subscription": subscription, "device_id": "device-1"},
+ headers=headers,
+ )
+ assert created.status_code == 200
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ web_push_service.mark_send_failure(conn, endpoint=subscription["endpoint"], disable=True)
+
+ status = client.post(
+ "/api/web-push/status",
+ json={
+ "endpoint": subscription["endpoint"],
+ "subscription": subscription,
+ "device_id": "device-1",
+ },
+ headers=headers,
+ )
+
+ assert status.status_code == 200
+ assert status.get_json()["subscription_count"] == 0
+ assert status.get_json()["current_subscription_enabled"] is False
+ with engine.connect() as conn:
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=subscription["endpoint"],
+ user_key="local",
+ ) is None
+
+
def test_web_push_unsubscribe_is_scoped_to_current_user(monkeypatch, tmp_path):
from storage import web_push_service
from storage.db import create_sqlite_engine
diff --git a/tests/test_web_push_service.py b/tests/test_web_push_service.py
index bb5c652e4..7f0902d86 100644
--- a/tests/test_web_push_service.py
+++ b/tests/test_web_push_service.py
@@ -53,6 +53,230 @@ def test_subscription_upsert_and_disable(tmp_path):
assert web_push_service.count_enabled(conn, user_key="local") == 0
+def test_subscription_upsert_disables_previous_endpoint_for_same_device(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ with engine.begin() as conn:
+ first = web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/old"),
+ device_id="device-1",
+ )
+ second = web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/new"),
+ device_id="device-1",
+ )
+ other_device = web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/other"),
+ device_id="device-2",
+ )
+
+ assert first["id"] != second["id"]
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=first["endpoint"],
+ user_key="remote:user-a",
+ ) is None
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=second["endpoint"],
+ user_key="remote:user-a",
+ ) is not None
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=other_device["endpoint"],
+ user_key="remote:user-a",
+ ) is not None
+ assert web_push_service.count_enabled(conn, user_key="remote:user-a") == 2
+
+
+def test_attach_device_to_enabled_subscription_does_not_reenable_disabled_endpoint(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="remote:user-a",
+ payload=_payload("https://push.example.test/sub/dead"),
+ device_id="device-1",
+ )
+ web_push_service.mark_send_failure(conn, endpoint=row["endpoint"], disable=True)
+
+ synced = web_push_service.attach_device_to_enabled_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/dead"),
+ device_id="device-1",
+ )
+
+ assert synced is None
+ assert web_push_service.count_enabled(conn, user_key="remote:user-a") == 0
+
+
+def test_attach_device_to_enabled_subscription_preserves_same_origin_legacy_rows(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ with engine.begin() as conn:
+ legacy_same_origin = web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/legacy"),
+ )
+ current = web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/current"),
+ )
+ other_device = web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/other-device"),
+ device_id="device-2",
+ )
+
+ synced = web_push_service.attach_device_to_enabled_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/current"),
+ device_id="device-1",
+ )
+
+ assert synced is not None
+ assert synced["device_id"] == "device-1"
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=legacy_same_origin["endpoint"],
+ user_key="remote:user-a",
+ ) is not None
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=current["endpoint"],
+ user_key="remote:user-a",
+ ) is not None
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=other_device["endpoint"],
+ user_key="remote:user-a",
+ ) is not None
+ assert web_push_service.count_enabled(conn, user_key="remote:user-a") == 3
+
+
+def test_attach_device_to_enabled_subscription_disables_client_known_previous_endpoints(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ with engine.begin() as conn:
+ previous = web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/previous"),
+ )
+ current = web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/current"),
+ )
+ other_legacy = web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/other-legacy"),
+ )
+
+ synced = web_push_service.attach_device_to_enabled_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/current"),
+ device_id="device-1",
+ previous_endpoints=[previous["endpoint"]],
+ )
+
+ assert synced is not None
+ assert synced["device_id"] == "device-1"
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=previous["endpoint"],
+ user_key="remote:user-a",
+ ) is None
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=current["endpoint"],
+ user_key="remote:user-a",
+ ) is not None
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=other_legacy["endpoint"],
+ user_key="remote:user-a",
+ ) is not None
+ assert web_push_service.count_enabled(conn, user_key="remote:user-a") == 2
+
+
+def test_attach_device_to_enabled_subscription_cleans_previous_endpoint_when_current_unknown(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ with engine.begin() as conn:
+ previous = web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/previous"),
+ )
+
+ synced = web_push_service.attach_device_to_enabled_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/current"),
+ device_id="device-1",
+ previous_endpoints=[previous["endpoint"]],
+ )
+
+ assert synced is None
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=previous["endpoint"],
+ user_key="remote:user-a",
+ ) is None
+ assert web_push_service.count_enabled(conn, user_key="remote:user-a") == 0
+
+
+def test_attach_device_to_enabled_subscription_preserves_existing_label_when_missing(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="remote:user-a",
+ payload=_payload("https://push.example.test/sub/current"),
+ device_label="iPhone",
+ device_id="device-1",
+ )
+
+ synced = web_push_service.attach_device_to_enabled_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/current"),
+ device_id="device-1",
+ )
+
+ assert synced is not None
+ assert synced["id"] == row["id"]
+ assert synced["device_label"] == "iPhone"
+
+
@pytest.mark.parametrize(
("payload", "error"),
[
diff --git a/ui/public/push-sw.js b/ui/public/push-sw.js
index a1045e062..5b748a886 100644
--- a/ui/public/push-sw.js
+++ b/ui/public/push-sw.js
@@ -11,6 +11,7 @@ self.addEventListener('push', (event) => {
const options = {
body: typeof payload.body === 'string' ? payload.body : '',
tag: typeof payload.tag === 'string' ? payload.tag : undefined,
+ renotify: typeof payload.tag === 'string' && payload.tag.length > 0,
data: { url },
icon: '/icon-192.png',
badge: '/icon-192.png',
diff --git a/ui/src/components/workbench/WebPushControl.tsx b/ui/src/components/workbench/WebPushControl.tsx
index 90e098206..518f1fe0a 100644
--- a/ui/src/components/workbench/WebPushControl.tsx
+++ b/ui/src/components/workbench/WebPushControl.tsx
@@ -9,8 +9,11 @@ import { Badge } from '../ui/badge';
import {
disableWebPush,
enableWebPush,
+ getWebPushDeviceId,
+ getRememberedWebPushEndpoints,
getExistingWebPushSubscription,
getWebPushSupportState,
+ rememberWebPushEndpoint,
type WebPushSupportState,
} from '@/lib/webPush';
@@ -33,7 +36,21 @@ export const WebPushControl: React.FC = () => {
return;
}
const existing = await getExistingWebPushSubscription();
- const serverStatus = await api.getWebPushStatus(existing?.endpoint).catch(() => null);
+ const serverStatus = await api
+ .getWebPushStatus(
+ existing
+ ? {
+ endpoint: existing.endpoint,
+ subscription: existing.toJSON(),
+ device_id: getWebPushDeviceId(),
+ previous_endpoints: getRememberedWebPushEndpoints(),
+ }
+ : undefined,
+ )
+ .catch(() => null);
+ if (existing && serverStatus?.current_subscription_enabled) {
+ rememberWebPushEndpoint(existing.endpoint);
+ }
setStatus(existing && serverStatus?.current_subscription_enabled ? 'enabled' : 'disabled');
};
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index f93a3f711..7e671ba0b 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -27,9 +27,14 @@ export type ApiContextType = {
toggleAdmin: (userId: string, isAdmin: boolean, platform?: string) => Promise<any>;
removeUser: (userId: string, platform?: string) => Promise<any>;
getShowPages: () => Promise<any>;
- getWebPushStatus: (endpoint?: string) => Promise<WebPushStatus>;
+ getWebPushStatus: (payload?: WebPushStatusPayload) => Promise<WebPushStatus>;
getWebPushVapidPublicKey: () => Promise<{ ok: boolean; public_key: string }>;
- subscribeWebPush: (subscription: PushSubscriptionJSON, deviceLabel?: string) => Promise<WebPushSubscriptionResult>;
+ subscribeWebPush: (
+ subscription: PushSubscriptionJSON,
+ deviceLabel?: string,
+ deviceId?: string,
+ previousEndpoints?: string[],
+ ) => Promise<WebPushSubscriptionResult>;
unsubscribeWebPush: (endpoint: string) => Promise<{ ok: boolean; disabled: boolean }>;
sendWebPushTest: (payload?: { title?: string; body?: string; url?: string; endpoint?: string }) => Promise<WebPushTestResult>;
setShowPageVisibility: (sessionId: string, visibility: string) => Promise<any>;
@@ -988,6 +993,14 @@ export type WebPushStatus = {
current_subscription_enabled?: boolean;
};
+export type WebPushStatusPayload = {
+ endpoint?: string;
+ subscription?: PushSubscriptionJSON;
+ device_id?: string;
+ device_label?: string;
+ previous_endpoints?: string[];
+};
+
export type WebPushSubscriptionResult = {
ok: boolean;
subscription: {
@@ -995,6 +1008,7 @@ export type WebPushSubscriptionResult = {
user_key: string;
endpoint: string;
enabled: boolean;
+ device_id?: string | null;
user_agent?: string | null;
device_label?: string | null;
};
@@ -1206,13 +1220,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: (endpoint) =>
- endpoint ? postJson('/api/web-push/status', { endpoint }) : getJson('/api/web-push/status'),
+ getWebPushStatus: (payload) =>
+ payload ? postJson('/api/web-push/status', payload) : getJson('/api/web-push/status'),
getWebPushVapidPublicKey: () => getJson('/api/web-push/vapid-public-key'),
- subscribeWebPush: (subscription, deviceLabel) =>
+ subscribeWebPush: (subscription, deviceLabel, deviceId, previousEndpoints) =>
postJson('/api/web-push/subscriptions', {
subscription,
device_label: deviceLabel,
+ device_id: deviceId,
+ previous_endpoints: previousEndpoints,
}),
unsubscribeWebPush: (endpoint) => deleteJson('/api/web-push/subscriptions', { endpoint }),
sendWebPushTest: (payload) => postJson('/api/web-push/test', payload ?? {}),
diff --git a/ui/src/lib/webPush.ts b/ui/src/lib/webPush.ts
index 3c4068fb1..5c15b4c78 100644
--- a/ui/src/lib/webPush.ts
+++ b/ui/src/lib/webPush.ts
@@ -1,6 +1,9 @@
import type { ApiContextType } from '@/context/ApiContext';
import { isIosDevice, isStandalonePwa } from './platform';
+const WEB_PUSH_DEVICE_ID_KEY = 'vibe.webPush.deviceId';
+const WEB_PUSH_ENDPOINTS_KEY = 'vibe.webPush.endpoints';
+
export type WebPushSupportState =
| { supported: true; standalone: boolean; requiresStandalone: boolean }
| { supported: false; reason: 'unsupported' | 'ios_requires_standalone' };
@@ -24,6 +27,48 @@ function arrayBuffersEqual(left: ArrayBuffer | null, right: ArrayBuffer): boolea
return true;
}
+export function getWebPushDeviceId(): string {
+ try {
+ const existing = window.localStorage.getItem(WEB_PUSH_DEVICE_ID_KEY);
+ if (existing) return existing;
+ } catch {
+ // Storage can be blocked in hardened browsers/WebViews; keep notification
+ // controls usable even if the id cannot persist across page loads.
+ }
+ const generated =
+ window.crypto?.randomUUID?.() ??
+ `device-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
+ try {
+ window.localStorage.setItem(WEB_PUSH_DEVICE_ID_KEY, generated);
+ } catch {
+ // Best-effort persistence only.
+ }
+ return generated;
+}
+
+export function getRememberedWebPushEndpoints(): string[] {
+ try {
+ const raw = window.localStorage.getItem(WEB_PUSH_ENDPOINTS_KEY);
+ const parsed = raw ? JSON.parse(raw) : [];
+ if (Array.isArray(parsed)) {
+ return parsed.filter((endpoint): endpoint is string => typeof endpoint === 'string' && endpoint.length > 0);
+ }
+ } catch {
+ // Best-effort cleanup hints only.
+ }
+ return [];
+}
+
+export function rememberWebPushEndpoint(endpoint: string | undefined): void {
+ if (!endpoint) return;
+ const endpoints = [endpoint, ...getRememberedWebPushEndpoints().filter((candidate) => candidate !== endpoint)].slice(0, 8);
+ try {
+ window.localStorage.setItem(WEB_PUSH_ENDPOINTS_KEY, JSON.stringify(endpoints));
+ } catch {
+ // Best-effort persistence only.
+ }
+}
+
export function getWebPushSupportState(): WebPushSupportState {
if (typeof window === 'undefined' || typeof navigator === 'undefined') {
return { supported: false, reason: 'unsupported' };
@@ -68,7 +113,9 @@ export async function enableWebPush(api: ApiContextType): Promise<PushSubscripti
}));
const json = subscription.toJSON();
- await api.subscribeWebPush(json);
+ const endpoint = typeof json.endpoint === 'string' ? json.endpoint : undefined;
+ await api.subscribeWebPush(json, undefined, getWebPushDeviceId(), getRememberedWebPushEndpoints());
+ rememberWebPushEndpoint(endpoint);
return json;
}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 3c81dac5e..cdb3d0943 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1811,9 +1811,28 @@ def web_push_status():
keys = load_or_create_vapid_keys()
body = request.json if request.method == "POST" else {}
endpoint = body.get("endpoint") if isinstance(body, dict) else None
+ subscription = body.get("subscription") if isinstance(body, dict) and isinstance(body.get("subscription"), dict) else None
+ device_id = body.get("device_id") if isinstance(body, dict) and isinstance(body.get("device_id"), str) else None
+ device_label = body.get("device_label") if isinstance(body, dict) and isinstance(body.get("device_label"), str) else None
+ previous_endpoints = body.get("previous_endpoints") if isinstance(body, dict) and isinstance(body.get("previous_endpoints"), list) else None
user_key = _web_push_user_key()
engine = _projects_engine()
- with engine.connect() as conn:
+ with engine.begin() as conn:
+ if subscription is not None:
+ try:
+ synced = web_push_service.attach_device_to_enabled_subscription(
+ conn,
+ user_key=user_key,
+ payload=subscription,
+ user_agent=request.headers.get("User-Agent"),
+ device_label=device_label,
+ device_id=device_id,
+ previous_endpoints=previous_endpoints,
+ )
+ if synced is not None:
+ endpoint = synced["endpoint"]
+ except ValueError:
+ logger.debug("web push: ignoring invalid status subscription payload", exc_info=True)
subscription_count = web_push_service.count_enabled(conn, user_key=user_key)
current_subscription = (
web_push_service.get_enabled_by_endpoint(
@@ -1850,6 +1869,8 @@ def web_push_subscribe():
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
+ device_id = payload.get("device_id") if isinstance(payload.get("device_id"), str) else None
+ previous_endpoints = payload.get("previous_endpoints") if isinstance(payload.get("previous_endpoints"), list) else None
subscription = payload.get("subscription") if isinstance(payload.get("subscription"), dict) else payload
engine = _projects_engine()
try:
@@ -1860,6 +1881,8 @@ def web_push_subscribe():
payload=subscription,
user_agent=user_agent,
device_label=device_label,
+ device_id=device_id,
+ previous_endpoints=previous_endpoints,
)
except ValueError as exc:
return jsonify({"ok": False, "error": str(exc)}), 400