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): address web push review round two

cyh526c8e83b973
diff --git a/core/web_push.py b/core/web_push.py
index bfa9ba11b..1df48a494 100644
--- a/core/web_push.py
+++ b/core/web_push.py
@@ -5,6 +5,9 @@ from __future__ import annotations
import base64
import json
import logging
+import os
+import tempfile
+import threading
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -19,6 +22,7 @@ logger = logging.getLogger(__name__)
_VAPID_FILE = "web_push_vapid.json"
DEFAULT_WEB_PUSH_TIMEOUT_SECONDS = 10.0
DEFAULT_WEB_PUSH_TTL_SECONDS = 12 * 60 * 60
+_VAPID_CREATE_LOCK = threading.Lock()
@dataclass(frozen=True)
@@ -35,17 +39,16 @@ 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)
+def _read_vapid_keys(key_path: Path) -> VapidKeys:
+ 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")
+
+
+def _generate_vapid_keys() -> VapidKeys:
private_key = ec.generate_private_key(ec.SECP256R1())
public_key = private_key.public_key()
public_numbers = public_key.public_numbers()
@@ -59,8 +62,11 @@ def load_or_create_vapid_keys(path: Path | None = None) -> VapidKeys:
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(
+ return VapidKeys(public_key=_b64url_no_padding(raw_public), private_key_pem=private_key_pem)
+
+
+def _write_vapid_keys_exclusive(key_path: Path, keys: VapidKeys) -> None:
+ payload = (
json.dumps(
{
"public_key": keys.public_key,
@@ -68,14 +74,46 @@ def load_or_create_vapid_keys(path: Path | None = None) -> VapidKeys:
},
indent=2,
)
- + "\n",
- encoding="utf-8",
+ + "\n"
)
+ tmp_path: Path | None = None
+ with tempfile.NamedTemporaryFile(
+ "w",
+ dir=key_path.parent,
+ encoding="utf-8",
+ prefix=f".{key_path.name}.",
+ delete=False,
+ ) as fp:
+ tmp_path = Path(fp.name)
+ fp.write(payload)
+ fp.flush()
+ os.fsync(fp.fileno())
+ tmp_path.chmod(0o600)
+ try:
+ os.link(tmp_path, key_path)
+ finally:
+ tmp_path.unlink(missing_ok=True)
try:
key_path.chmod(0o600)
except OSError:
logger.debug("Could not chmod VAPID key file %s", key_path, exc_info=True)
- return keys
+
+
+def load_or_create_vapid_keys(path: Path | None = None) -> VapidKeys:
+ key_path = path or vapid_key_path()
+ if key_path.exists():
+ return _read_vapid_keys(key_path)
+
+ with _VAPID_CREATE_LOCK:
+ if key_path.exists():
+ return _read_vapid_keys(key_path)
+ key_path.parent.mkdir(parents=True, exist_ok=True)
+ keys = _generate_vapid_keys()
+ try:
+ _write_vapid_keys_exclusive(key_path, keys)
+ except FileExistsError:
+ return _read_vapid_keys(key_path)
+ return keys
def send_web_push(
diff --git a/core/web_push_notifications.py b/core/web_push_notifications.py
index 92e06b5ce..cd23479bc 100644
--- a/core/web_push_notifications.py
+++ b/core/web_push_notifications.py
@@ -63,7 +63,23 @@ def _user_key_for_session(conn: Any, session_id: str | None) -> str | None:
except Exception:
return None
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 None
+ if isinstance(user_key, str) and user_key.strip():
+ return user_key
+ return _local_fallback_user_key()
+
+
+def _local_fallback_user_key() -> str | None:
+ try:
+ from core.services import settings as settings_service
+
+ config = settings_service.load_config()
+ except Exception:
+ logger.warning("web push: could not load config for local fallback", exc_info=True)
+ return None
+ cloud = getattr(getattr(config, "remote_access", None), "vibe_cloud", None)
+ if cloud is not None and getattr(cloud, "enabled", False):
+ return None
+ return "local"
def _send_to_enabled_subscriptions(payload: dict[str, Any]) -> None:
diff --git a/tests/test_web_push_notifications.py b/tests/test_web_push_notifications.py
index fb892b9b0..0b4174e96 100644
--- a/tests/test_web_push_notifications.py
+++ b/tests/test_web_push_notifications.py
@@ -128,7 +128,7 @@ def test_send_to_enabled_subscriptions_uses_session_owner(monkeypatch, tmp_path)
assert [send[0]["endpoint"] for send in sends] == ["https://push.example.test/a"]
-def test_send_to_enabled_subscriptions_skips_unknown_owner(monkeypatch, tmp_path):
+def test_send_to_enabled_subscriptions_uses_local_fallback_for_legacy_local_session(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
ensure_sqlite_state()
engine = create_sqlite_engine()
@@ -165,6 +165,53 @@ def test_send_to_enabled_subscriptions_skips_unknown_owner(monkeypatch, tmp_path
"core.web_push.send_web_push",
lambda *, subscription, payload: sends.append((subscription, payload)),
)
+ monkeypatch.setattr(web_push_notifications, "_local_fallback_user_key", lambda: "local")
+
+ web_push_notifications._send_to_enabled_subscriptions(
+ {"title": "Legacy", "body": "Done", "session_id": "ses_legacy"}
+ )
+
+ assert [send[0]["endpoint"] for send in sends] == ["https://push.example.test/local"]
+
+
+def test_send_to_enabled_subscriptions_skips_unknown_owner_when_remote_access_enabled(monkeypatch, tmp_path):
+ 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_legacy",
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor="ses_legacy",
+ native_session_id="",
+ title="Legacy",
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ web_push_service.upsert_subscription(
+ conn,
+ user_key="local",
+ payload={
+ "endpoint": "https://push.example.test/local",
+ "keys": {"p256dh": "local-key", "auth": "local-auth"},
+ },
+ )
+
+ sends = []
+ monkeypatch.setattr(
+ "core.web_push.send_web_push",
+ lambda *, subscription, payload: sends.append((subscription, payload)),
+ )
+ monkeypatch.setattr(web_push_notifications, "_local_fallback_user_key", lambda: None)
web_push_notifications._send_to_enabled_subscriptions(
{"title": "Legacy", "body": "Done", "session_id": "ses_legacy"}
diff --git a/tests/test_web_push_service.py b/tests/test_web_push_service.py
index edced0f77..bb5c652e4 100644
--- a/tests/test_web_push_service.py
+++ b/tests/test_web_push_service.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
+from concurrent.futures import ThreadPoolExecutor
import pytest
@@ -79,6 +80,18 @@ def test_vapid_keys_are_stable(tmp_path):
assert stored["public_key"] == first.public_key
+def test_vapid_keys_are_stable_under_concurrent_first_use(tmp_path):
+ key_path = tmp_path / "web_push_vapid.json"
+
+ with ThreadPoolExecutor(max_workers=8) as pool:
+ keys = list(pool.map(lambda _: load_or_create_vapid_keys(key_path), range(16)))
+
+ assert len({key.public_key for key in keys}) == 1
+ assert len({key.private_key_pem for key in keys}) == 1
+ stored = json.loads(key_path.read_text(encoding="utf-8"))
+ assert stored["public_key"] == keys[0].public_key
+
+
def test_send_web_push_passes_vapid_signer_and_timeout(monkeypatch, tmp_path):
keys = load_or_create_vapid_keys(tmp_path / "web_push_vapid.json")
calls = []
diff --git a/ui/public/push-sw.js b/ui/public/push-sw.js
index 4628ae913..a1045e062 100644
--- a/ui/public/push-sw.js
+++ b/ui/public/push-sw.js
@@ -27,8 +27,7 @@ self.addEventListener('notificationclick', (event) => {
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();
+ return client.navigate(targetUrl).then((navigatedClient) => (navigatedClient || client).focus());
}
}
if (self.clients.openWindow) {
diff --git a/ui/src/components/workbench/WebPushControl.tsx b/ui/src/components/workbench/WebPushControl.tsx
index 9d046b9fe..2c4466d4c 100644
--- a/ui/src/components/workbench/WebPushControl.tsx
+++ b/ui/src/components/workbench/WebPushControl.tsx
@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';
import { Bell, BellOff, Loader2, Smartphone } from 'lucide-react';
import { useApi } from '@/context/ApiContext';
+import { useToast } from '@/context/ToastContext';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import {
@@ -18,6 +19,7 @@ type Status = 'checking' | 'unsupported' | 'needs_install' | 'disabled' | 'enabl
export const WebPushControl: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
+ const { showToast } = useToast();
const [status, setStatus] = useState<Status>('checking');
const [busy, setBusy] = useState(false);
const [testing, setTesting] = useState(false);
@@ -67,11 +69,21 @@ export const WebPushControl: React.FC = () => {
const onTest = async () => {
setTesting(true);
try {
- await api.sendWebPushTest({
+ const result = await api.sendWebPushTest({
title: t('workbench.inbox.notifications.testTitle'),
body: t('workbench.inbox.notifications.testBody'),
url: '/inbox',
});
+ if (result.ok) {
+ showToast(t('workbench.inbox.notifications.testSent'), 'success');
+ } else {
+ showToast(
+ t('workbench.inbox.notifications.testFailed', { count: result.failed ?? 0 }),
+ 'error',
+ );
+ }
+ } catch {
+ showToast(t('workbench.inbox.notifications.testFailed', { count: 0 }), 'error');
} finally {
setTesting(false);
}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 806a6b3d0..61311ef9b 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -603,7 +603,9 @@
"disable": "Disable",
"test": "Test",
"testTitle": "Vibe Remote",
- "testBody": "Notifications are ready."
+ "testBody": "Notifications are ready.",
+ "testSent": "Test notification sent",
+ "testFailed": "Test notification failed"
}
},
"modules": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 4d5beb4f0..db61ed7ac 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -603,7 +603,9 @@
"disable": "关闭",
"test": "测试",
"testTitle": "Vibe Remote",
- "testBody": "通知已经准备好了。"
+ "testBody": "通知已经准备好了。",
+ "testSent": "测试通知已发送",
+ "testFailed": "测试通知发送失败"
}
},
"modules": {