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(desktop): honor account notification categories and badge totals (#3128)

Call White0df62ba2eb09
diff --git a/desktop/runtime-host/src/notifications.rs b/desktop/runtime-host/src/notifications.rs
index 647e0b00c..3d8a603eb 100644
--- a/desktop/runtime-host/src/notifications.rs
+++ b/desktop/runtime-host/src/notifications.rs
@@ -5,7 +5,7 @@ use std::time::Duration;
use async_trait::async_trait;
use chrono::DateTime;
use serde::Deserialize;
-use tokio::sync::{Notify, Semaphore};
+use tokio::sync::{Notify, RwLock, Semaphore};
use tokio::task::JoinSet;
use tokio::time::Instant;
use url::Url;
@@ -132,13 +132,49 @@ impl NotificationGate {
}
}
+/// Account preferences are independent of the shell's device/focus gate.
+#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
+pub struct NotificationPreferences {
+ pub enabled: bool,
+ pub bots: bool,
+ pub sessions: bool,
+}
+
+impl Default for NotificationPreferences {
+ fn default() -> Self {
+ Self {
+ enabled: true,
+ bots: true,
+ sessions: true,
+ }
+ }
+}
+
+impl NotificationPreferences {
+ fn allows_run(self, category: Option<&str>) -> bool {
+ self.enabled
+ && match category {
+ Some("bot") => self.bots,
+ Some("session") => self.sessions,
+ // Old servers, failed details, and overload have no trustworthy
+ // category. Generic copy must not bypass a quiet category.
+ _ => self.bots && self.sessions,
+ }
+ }
+}
+
+struct RunPreferences {
+ current: Arc<RwLock<NotificationPreferences>>,
+ at_receipt: NotificationPreferences,
+}
+
pub trait NotificationSink: Send + Sync {
fn gate(&self) -> NotificationGate;
/// `source` names where a run happened ("Project · Session"), already
/// sanitized by [`RunDetail::source`]; `None` keeps the generic copy.
fn deliver(&self, intent: NotificationIntent, source: Option<String>);
- /// The Runtime's unread total, for the app icon badge. It is state rather
- /// than an interruption, so neither the toggle nor focus gates it.
+ /// The Runtime's badge total (loud-category unread), for the app icon.
+ /// It is state rather than an interruption: no device/focus gate applies.
fn show_unread(&self, total: u64);
/// A remote desktop update event is only a nudge. The shell must re-read
/// and validate its request file; the SSE payload never reaches this API.
@@ -238,6 +274,7 @@ pub struct RunDetail {
pub session_project_name: Option<String>,
pub session_label: Option<String>,
pub definition_name: Option<String>,
+ pub notification_category: Option<String>,
}
const SOURCE_PART_CHARS: usize = 48;
@@ -382,6 +419,7 @@ pub trait NotificationTransport: Send + Sync {
async fn connect(&self) -> Result<Box<dyn EventStream>, StreamError>;
async fn run_detail(&self, run_id: &str) -> Option<RunDetail>;
async fn unread_total(&self) -> Option<u64>;
+ async fn preferences(&self) -> Option<NotificationPreferences>;
}
pub struct HttpNotificationTransport {
@@ -480,7 +518,28 @@ impl NotificationTransport for HttpNotificationTransport {
}
let bytes = bounded_detail_body(response).await?;
let inbox: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
- inbox.get("unread_total")?.as_u64()
+ // Fall back only when absent, not when malformed: an explicit zero
+ // must never turn into the raw (possibly quiet-category) unread count.
+ inbox.get("badge_total").or_else(|| inbox.get("unread_total"))?.as_u64()
+ }
+
+ async fn preferences(&self) -> Option<NotificationPreferences> {
+ let response = self
+ .client
+ .get(self.url("/api/notifications/preferences"))
+ .timeout(REQUEST_TIMEOUT)
+ .send()
+ .await
+ .ok()?;
+ if !response.status().is_success() {
+ return None;
+ }
+ let bytes = bounded_detail_body(response).await?;
+ let document: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
+ if !document.get("ok")?.as_bool()? {
+ return None;
+ }
+ serde_json::from_value(document.get("preferences")?.clone()).ok()
}
}
@@ -524,6 +583,7 @@ pub async fn run_notifications(
sink: Arc<dyn NotificationSink>,
) {
let mut backoff = ReconnectBackoff::default();
+ let preferences = Arc::new(RwLock::new(NotificationPreferences::default()));
// Any frame may follow an unread change, and listing the event types that
// can would miss the next one added, so every connection and every frame
// (the 15-second heartbeat included) asks for a fresh total. The reader
@@ -540,6 +600,7 @@ pub async fn run_notifications(
let connected_at = Instant::now();
if let Ok(mut stream) = transport.connect().await {
unread_changed.notify_one();
+ refresh_preferences(&transport, &preferences).await;
let mut decoder = SseDecoder::new();
while let Ok(Ok(Some(chunk))) = tokio::time::timeout(STREAM_IDLE_TIMEOUT, stream.next_chunk()).await {
if Instant::now().duration_since(connected_at) >= STREAM_IDLE_TIMEOUT {
@@ -548,9 +609,15 @@ pub async fn run_notifications(
while lookups.try_join_next().is_some() {}
// Suppression is not a queue: frames still reach the filter so
// its de-duplication stays current, then are dropped.
- let allowed_at_receipt = sink.gate().allows();
for frame in decoder.push(&chunk) {
unread_changed.notify_one();
+ if frame.event == "notifications.preferences.updated" {
+ // Only a nudge: never trust preferences from the SSE payload.
+ refresh_preferences(&transport, &preferences).await;
+ continue;
+ }
+ let at_receipt = *preferences.read().await;
+ let allowed_at_receipt = sink.gate().allows() && at_receipt.enabled;
if frame.event == "desktop.update.requested" {
sink.desktop_update_requested();
continue;
@@ -579,12 +646,16 @@ pub async fn run_notifications(
// event already qualifies notifies now with
// generic copy; a run only its read could
// qualify fails closed.
- if background && sink.gate().allows() {
+ if background && at_receipt.allows_run(None) && sink.gate().allows() {
sink.deliver(intent, None);
}
continue;
}
let (transport, sink, slots) = (transport.clone(), sink.clone(), slots.clone());
+ let preferences = RunPreferences {
+ current: preferences.clone(),
+ at_receipt,
+ };
lookups.spawn(async move {
// Queue behind the request limit rather than
// drop: a run without stamps is only decided
@@ -592,7 +663,7 @@ pub async fn run_notifications(
let Ok(_slot) = slots.acquire_owned().await else {
return;
};
- notify_run(transport, sink, run_id, stamps, intent, background).await;
+ notify_run(transport, sink, run_id, stamps, intent, background, preferences).await;
});
}
}
@@ -603,6 +674,19 @@ pub async fn run_notifications(
}
}
+/// Refresh before consuming further frames. The bounded write lock also holds
+/// in-flight run deliveries until the new preference snapshot is known. On a
+/// failed/old-server read, keep the last valid value (initially all on).
+async fn refresh_preferences(
+ transport: &Arc<dyn NotificationTransport>,
+ preferences: &RwLock<NotificationPreferences>,
+) {
+ let mut current = preferences.write().await;
+ if let Ok(Some(fresh)) = tokio::time::timeout(REQUEST_TIMEOUT, transport.preferences()).await {
+ *current = fresh;
+ }
+}
+
/// Reads the total after each signal, then waits out the refresh interval.
/// `Notify` keeps at most one stored signal, so any number of events during a
/// read or a wait become exactly one more read. A failed read keeps the badge
@@ -630,12 +714,20 @@ async fn notify_run(
mut stamps: RunTimestamps,
intent: NotificationIntent,
background: bool,
+ preferences: RunPreferences,
) {
let detail = tokio::time::timeout(REQUEST_TIMEOUT, transport.run_detail(&run_id))
.await
.ok()
.flatten();
let source = detail.as_ref().and_then(RunDetail::source);
+ let category = detail
+ .as_ref()
+ .and_then(|detail| detail.notification_category.as_deref());
+ let current = preferences.current.read().await;
+ if !preferences.at_receipt.allows_run(category) || !current.allows_run(category) {
+ return;
+ }
if let Some(detail) = detail {
stamps.fill_missing(detail.stamps);
}
diff --git a/desktop/runtime-host/tests/notification_http.rs b/desktop/runtime-host/tests/notification_http.rs
index 5cdee7e6c..0e04c836b 100644
--- a/desktop/runtime-host/tests/notification_http.rs
+++ b/desktop/runtime-host/tests/notification_http.rs
@@ -5,7 +5,9 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
-use avibe_runtime_host::notifications::{HttpNotificationTransport, NotificationTransport, SseDecoder};
+use avibe_runtime_host::notifications::{
+ HttpNotificationTransport, NotificationPreferences, NotificationTransport, SseDecoder,
+};
use avibe_runtime_host::LoopbackOrigin;
use serde_json::json;
@@ -143,12 +145,14 @@ async fn stream_and_detail_redirects_never_delegate_trust_to_another_origin() {
target.origin.as_str()
)
.into_bytes();
- let server = FakeServer::start([redirect.clone(), redirect]);
+ let server = FakeServer::start([redirect.clone(), redirect.clone(), redirect.clone(), redirect]);
let transport = server.transport();
assert!(transport.connect().await.is_err());
assert!(transport.run_detail("run").await.is_none());
+ assert!(transport.unread_total().await.is_none());
+ assert!(transport.preferences().await.is_none());
assert!(target.requests.lock().unwrap().is_empty());
- assert_eq!(server.requests.lock().unwrap().len(), 2);
+ assert_eq!(server.requests.lock().unwrap().len(), 4);
}
#[tokio::test]
@@ -167,6 +171,7 @@ async fn stream_requires_a_successful_sse_response_not_an_arbitrary_live_http_en
async fn refetch_requires_the_requested_run_and_bounds_untrusted_detail_bodies() {
let valid = json!({"ok": true, "run": {
"id": "run", "started_at": "2026-09-10T12:00:00Z", "updated_at": "2026-09-10T12:00:30Z",
+ "notification_category": "bot",
"session_project_name": "avibe-app", "session_label": "桌面版检查更新", "definition_name": null,
}});
let server = FakeServer::start([
@@ -186,6 +191,7 @@ async fn refetch_requires_the_requested_run_and_bounds_untrusted_detail_bodies()
let detail = transport.run_detail("run").await.unwrap();
assert_eq!(detail.stamps.started_at, Some("2026-09-10T12:00:00Z".into()));
assert_eq!(detail.stamps.updated_at, Some("2026-09-10T12:00:30Z".into()));
+ assert_eq!(detail.notification_category.as_deref(), Some("bot"));
assert_eq!(detail.source(), Some("avibe-app · 桌面版检查更新".into()));
for _ in 0..5 {
assert!(transport.run_detail("run").await.is_none());
@@ -212,14 +218,73 @@ async fn identifiers_are_encoded_as_one_path_segment_not_runtime_selected_routes
}
#[tokio::test]
-async fn unread_total_reads_the_runtime_inbox_total_and_fails_closed_on_anything_else() {
+async fn preferences_require_a_complete_valid_snapshot_on_the_adopted_origin() {
+ let server = FakeServer::start([
+ response(
+ "200 OK",
+ "application/json",
+ br#"{"ok":true,"preferences":{"enabled":true,"bots":false,"sessions":true,"future":[]}}"#,
+ ),
+ response("404 Not Found", "application/json", b"{}"),
+ response(
+ "200 OK",
+ "application/json",
+ br#"{"ok":false,"preferences":{"enabled":true,"bots":true,"sessions":true}}"#,
+ ),
+ response(
+ "200 OK",
+ "application/json",
+ br#"{"ok":true,"preferences":{"enabled":true}}"#,
+ ),
+ response(
+ "200 OK",
+ "application/json",
+ br#"{"ok":true,"preferences":{"enabled":true,"bots":"false","sessions":true}}"#,
+ ),
+ response("200 OK", "application/json", b"not-json"),
+ response("200 OK", "application/json", &vec![b' '; 256 * 1024 + 1]),
+ ]);
+ let transport = server.transport();
+ assert_eq!(
+ transport.preferences().await,
+ Some(NotificationPreferences {
+ enabled: true,
+ bots: false,
+ sessions: true
+ })
+ );
+ for _ in 0..6 {
+ assert_eq!(transport.preferences().await, None);
+ }
+ let requests = server.requests.lock().unwrap();
+ assert_eq!(requests.len(), 7);
+ for request in requests.iter() {
+ assert!(request.starts_with("GET /api/notifications/preferences HTTP/1.1\r\n"));
+ for forbidden in ["authorization:", "cookie:"] {
+ assert!(!request.to_ascii_lowercase().contains(forbidden));
+ }
+ }
+}
+
+#[tokio::test]
+async fn unread_total_prefers_loud_badge_total_and_only_falls_back_when_absent() {
let server = FakeServer::start([
response(
"200 OK",
"application/json",
br#"{"sessions":[],"unread_by_session":{"a":2,"b":1},"unread_total":3}"#,
),
+ response("200 OK", "application/json", br#"{"unread_total":9,"badge_total":2}"#),
+ response("200 OK", "application/json", br#"{"unread_total":9,"badge_total":0}"#),
+ response("200 OK", "application/json", br#"{"badge_total":4}"#),
response("200 OK", "application/json", br#"{"sessions":[],"unread_total":0}"#),
+ response("200 OK", "application/json", br#"{"unread_total":9,"badge_total":-1}"#),
+ response(
+ "200 OK",
+ "application/json",
+ br#"{"unread_total":9,"badge_total":null}"#,
+ ),
+ response("200 OK", "application/json", br#"{"unread_total":9,"badge_total":"2"}"#),
response("401 Unauthorized", "application/json", br#"{"unread_total":9}"#),
response("200 OK", "application/json", br#"{"unread_total":-1}"#),
response("200 OK", "application/json", br#"{"sessions":[]}"#),
@@ -228,12 +293,15 @@ async fn unread_total_reads_the_runtime_inbox_total_and_fails_closed_on_anything
]);
let transport = server.transport();
assert_eq!(transport.unread_total().await, Some(3));
+ assert_eq!(transport.unread_total().await, Some(2));
assert_eq!(transport.unread_total().await, Some(0));
- for _ in 0..5 {
+ assert_eq!(transport.unread_total().await, Some(4));
+ assert_eq!(transport.unread_total().await, Some(0));
+ for _ in 0..8 {
assert_eq!(transport.unread_total().await, None);
}
let requests = server.requests.lock().unwrap();
- assert_eq!(requests.len(), 7);
+ assert_eq!(requests.len(), 13);
for request in requests.iter() {
let normalized = request.to_ascii_lowercase();
assert!(request.starts_with("GET /api/inbox?platform=avibe&limit=1 HTTP/1.1\r\n"));
diff --git a/desktop/runtime-host/tests/notifications.rs b/desktop/runtime-host/tests/notifications.rs
index 51144409a..37cdc97d9 100644
--- a/desktop/runtime-host/tests/notifications.rs
+++ b/desktop/runtime-host/tests/notifications.rs
@@ -5,9 +5,9 @@ use std::time::Duration;
use async_trait::async_trait;
use avibe_runtime_host::notifications::{
- run_notifications, EventStream, NotificationFilter, NotificationGate, NotificationIntent, NotificationSink,
- NotificationTransport, ReconnectBackoff, RunDetail, RunTimestamps, SseDecoder, StreamError, RETAINED_KEYS,
- RETENTION, UNREAD_REFRESH_INTERVAL,
+ run_notifications, EventStream, NotificationFilter, NotificationGate, NotificationIntent, NotificationPreferences,
+ NotificationSink, NotificationTransport, ReconnectBackoff, RunDetail, RunTimestamps, SseDecoder, StreamError,
+ RETAINED_KEYS, RETENTION, UNREAD_REFRESH_INTERVAL,
};
use serde_json::{json, Value};
use tokio::time::Instant;
@@ -42,6 +42,9 @@ struct FakeTransport {
detail_delay: Duration,
unread: Mutex<Option<u64>>,
unread_reads: Mutex<Vec<Instant>>,
+ preferences: Mutex<VecDeque<Option<NotificationPreferences>>>,
+ preference_reads: AtomicUsize,
+ preference_delay: Duration,
}
#[async_trait]
@@ -62,6 +65,12 @@ impl NotificationTransport for FakeTransport {
self.details.lock().unwrap().get(run_id).cloned()
}
+ async fn preferences(&self) -> Option<NotificationPreferences> {
+ self.preference_reads.fetch_add(1, Ordering::SeqCst);
+ tokio::time::sleep(self.preference_delay).await;
+ self.preferences.lock().unwrap().pop_front().flatten()
+ }
+
async fn unread_total(&self) -> Option<u64> {
self.unread_reads.lock().unwrap().push(Instant::now());
*self.unread.lock().unwrap()
@@ -871,6 +880,267 @@ async fn every_connection_and_frame_refreshes_the_runtime_unread_total_at_a_boun
task.abort();
}
+#[tokio::test(start_paused = true)]
+async fn account_switches_gate_run_categories_but_only_master_gates_vault() {
+ for enabled in [false, true] {
+ for bots in [false, true] {
+ for sessions in [false, true] {
+ let transport = Arc::new(FakeTransport::default());
+ let sink = Arc::new(FakeSink::default());
+ transport
+ .preferences
+ .lock()
+ .unwrap()
+ .push_back(Some(NotificationPreferences {
+ enabled,
+ bots,
+ sessions,
+ }));
+ let mut chunks = vec![approval("request", "pending")];
+ for category in [Some("bot"), Some("session"), Some("future"), None] {
+ let id = format!("{category:?}");
+ transport.details.lock().unwrap().insert(
+ id.clone(),
+ RunDetail {
+ notification_category: category.map(Into::into),
+ ..RunDetail::default()
+ },
+ );
+ chunks.push(run(id, "watch", 1));
+ }
+ // Neither an unreadable detail nor a forged event category may
+ // bypass a quiet category; the HTTP detail is the authority.
+ chunks.push(frame(
+ "runs.updated",
+ json!({
+ "run_id": "unreadable", "status": "succeeded", "run_type": "watch",
+ "notification_category": "session",
+ }),
+ ));
+ *transport.unread.lock().unwrap() = Some(9);
+ transport.stream(chunks, false);
+ let task = spawn(transport.clone(), sink.clone());
+ settle().await;
+ let delivered = sink.delivered.lock().unwrap().clone();
+ assert_eq!(
+ delivered
+ .iter()
+ .filter(|&&intent| intent == NotificationIntent::ApprovalRequested)
+ .count(),
+ usize::from(enabled)
+ );
+ let runs = if enabled {
+ usize::from(bots) + usize::from(sessions) + 3 * usize::from(bots && sessions)
+ } else {
+ 0
+ };
+ assert_eq!(
+ delivered
+ .iter()
+ .filter(|&&intent| intent == NotificationIntent::RunSucceeded)
+ .count(),
+ runs
+ );
+ assert_eq!(*sink.unread.lock().unwrap(), [9]);
+ assert_eq!(transport.preference_reads.load(Ordering::SeqCst), 1);
+ task.abort();
+ }
+ }
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn preference_events_refetch_not_trust_payload_keep_last_valid_and_do_not_replay() {
+ let transport = Arc::new(FakeTransport::default());
+ let sink = Arc::new(FakeSink::default());
+ transport.preferences.lock().unwrap().extend([
+ Some(NotificationPreferences {
+ enabled: false,
+ ..NotificationPreferences::default()
+ }),
+ None, // failed refresh must not restore defaults
+ Some(NotificationPreferences::default()),
+ ]);
+ transport.stream(
+ [
+ approval("quiet", "pending"),
+ run("quiet", "watch", 0),
+ frame(
+ "notifications.preferences.updated",
+ json!({"preferences": {"enabled": true}}),
+ ),
+ approval("still-quiet", "pending"),
+ run("still-quiet", "watch", 0),
+ ],
+ true,
+ );
+ // Reconnect re-reads the preferences even if its update event was missed.
+ transport.stream(
+ [
+ approval("quiet", "pending"),
+ run("quiet", "watch", 0),
+ approval("still-quiet", "pending"),
+ run("still-quiet", "watch", 0),
+ approval("fresh", "pending"),
+ run("fresh", "watch", 0),
+ ],
+ false,
+ );
+ let task = spawn(transport.clone(), sink.clone());
+ settle().await;
+ assert!(sink.delivered.lock().unwrap().is_empty());
+ tokio::time::advance(Duration::from_secs(1)).await;
+ settle().await;
+ assert_eq!(
+ *sink.delivered.lock().unwrap(),
+ [NotificationIntent::ApprovalRequested, NotificationIntent::RunSucceeded]
+ );
+ assert_eq!(transport.preference_reads.load(Ordering::SeqCst), 3);
+ task.abort();
+}
+
+#[tokio::test(start_paused = true)]
+async fn run_category_must_be_loud_at_receipt_and_after_the_detail_lookup() {
+ for initially_loud in [false, true] {
+ let transport = Arc::new(FakeTransport {
+ detail_delay: Duration::from_secs(2),
+ ..FakeTransport::default()
+ });
+ let sink = Arc::new(FakeSink::default());
+ transport
+ .preferences
+ .lock()
+ .unwrap()
+ .extend([initially_loud, !initially_loud].map(|bots| {
+ Some(NotificationPreferences {
+ bots,
+ ..NotificationPreferences::default()
+ })
+ }));
+ transport.details.lock().unwrap().insert(
+ "run".into(),
+ RunDetail {
+ notification_category: Some("bot".into()),
+ ..RunDetail::default()
+ },
+ );
+ transport.paced_stream(
+ [
+ run("run", "watch", 0),
+ frame(
+ "notifications.preferences.updated",
+ json!({"preferences": {"bots": initially_loud}}),
+ ),
+ approval("vault", "pending"),
+ ],
+ false,
+ Duration::from_secs(1),
+ );
+ let task = spawn(transport.clone(), sink.clone());
+ settle().await;
+ for _ in 0..4 {
+ tokio::time::advance(Duration::from_secs(1)).await;
+ settle().await;
+ }
+ assert_eq!(*transport.refetched.lock().unwrap(), ["run"]);
+ assert_eq!(*sink.delivered.lock().unwrap(), [NotificationIntent::ApprovalRequested]);
+ task.abort();
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn in_flight_run_delivery_waits_for_an_account_refresh() {
+ let transport = Arc::new(FakeTransport {
+ preference_delay: Duration::from_secs(2),
+ detail_delay: Duration::from_secs(2),
+ ..FakeTransport::default()
+ });
+ let sink = Arc::new(FakeSink::default());
+ transport.preferences.lock().unwrap().extend([
+ Some(NotificationPreferences::default()),
+ Some(NotificationPreferences {
+ enabled: false,
+ ..NotificationPreferences::default()
+ }),
+ ]);
+ transport.details.lock().unwrap().insert(
+ "run".into(),
+ RunDetail {
+ notification_category: Some("session".into()),
+ ..RunDetail::default()
+ },
+ );
+ transport.paced_stream(
+ [
+ run("run", "watch", 0),
+ frame("notifications.preferences.updated", json!({})),
+ approval("vault", "pending"),
+ ],
+ false,
+ Duration::from_secs(1),
+ );
+ let task = spawn(transport.clone(), sink.clone());
+ settle().await;
+ // Startup read ends at t=2, run arrives at t=3, refresh at t=4.
+ // Detail completes at t=5, before the master-off read finishes at t=6.
+ for _ in 0..8 {
+ tokio::time::advance(Duration::from_secs(1)).await;
+ settle().await;
+ assert!(sink.delivered.lock().unwrap().is_empty());
+ }
+ assert_eq!(*transport.refetched.lock().unwrap(), ["run"]);
+ assert_eq!(transport.preference_reads.load(Ordering::SeqCst), 2);
+ task.abort();
+}
+
+#[tokio::test(start_paused = true)]
+async fn unread_and_stream_survive_a_bounded_preference_timeout() {
+ let transport = Arc::new(FakeTransport {
+ preference_delay: Duration::from_secs(60),
+ ..FakeTransport::default()
+ });
+ let sink = Arc::new(FakeSink::default());
+ *transport.unread.lock().unwrap() = Some(4);
+ transport.stream([approval("request", "pending")], false);
+ let task = spawn(transport.clone(), sink.clone());
+ settle().await;
+ assert_eq!(*sink.unread.lock().unwrap(), [4]);
+ tokio::time::advance(Duration::from_secs(5)).await;
+ settle().await;
+ assert_eq!(*sink.delivered.lock().unwrap(), [NotificationIntent::ApprovalRequested]);
+ assert_eq!(transport.connected_at.lock().unwrap().len(), 1);
+ task.abort();
+}
+
+#[tokio::test(start_paused = true)]
+async fn overloaded_runs_cannot_bypass_a_quiet_category() {
+ let transport = Arc::new(FakeTransport {
+ detail_delay: Duration::from_secs(60),
+ ..FakeTransport::default()
+ });
+ let sink = Arc::new(FakeSink::default());
+ transport
+ .preferences
+ .lock()
+ .unwrap()
+ .push_back(Some(NotificationPreferences {
+ bots: false,
+ ..NotificationPreferences::default()
+ }));
+ let mut frames = (0..100).map(|index| run(index, "watch", 0)).collect::<Vec<_>>();
+ frames.push(approval("request", "pending"));
+ transport.stream(frames, false);
+ let task = spawn(transport.clone(), sink.clone());
+ settle().await;
+ assert_eq!(transport.refetched.lock().unwrap().len(), 16);
+ for _ in 0..4 {
+ tokio::time::advance(Duration::from_secs(5)).await;
+ settle().await;
+ }
+ assert_eq!(*sink.delivered.lock().unwrap(), [NotificationIntent::ApprovalRequested]);
+ task.abort();
+}
+
#[tokio::test(start_paused = true)]
async fn a_failed_unread_read_keeps_the_last_total_until_the_next_frame() {
let transport = Arc::new(FakeTransport::default());
diff --git a/docs/plans/desktop-notifications-sse.md b/docs/plans/desktop-notifications-sse.md
index de5c0b1a5..5a9d0f9ca 100644
--- a/docs/plans/desktop-notifications-sse.md
+++ b/docs/plans/desktop-notifications-sse.md
@@ -9,6 +9,8 @@ the Runtime is already settled; this contract does not reopen it).
Owner: Avibe core
Date: 2026-09-10
Baseline: `desktop` branch after #1975 / #1977 (tray + start-receipt).
+Account/category extension: 2026-11-02, consuming #3127's merged preferences
+and Inbox badge contract (`workbench-refinements.md`).
## Product outcome
@@ -22,8 +24,9 @@ need them to look:
longer than ~30 seconds.
Default on. The tray has a checkable "Notifications" item that persists
-the preference. System Focus / Do Not Disturb is left to the OS; Avibe
-does not reimplement it.
+this device's preference. Account-wide `enabled`, `bots`, and `sessions`
+preferences provide a separate gate, described below. System Focus / Do
+Not Disturb is left to the OS; Avibe does not reimplement it.
Notification activation follows the OS-default behavior described in
**Click** below. Deep-link navigation into a specific session
@@ -106,8 +109,10 @@ v1 filter (exact event type strings, already published):
Every other event (`message.new`, `session.activity`, `queue.updated`,
`inbox.unread.changed`, `show.event`, keep-alives, unknown types) is
-ignored by the notification path. The filter is an allow-list: a new
-event type never becomes a notification by accident.
+ignored by the notification path. `notifications.preferences.updated`
+is a refetch hint, never an OS notification or an authoritative preference
+snapshot. The filter is an allow-list: a new event type never becomes a
+notification by accident.
### "Background" for `run.terminal`
@@ -158,10 +163,45 @@ notify" flag, no `visibility` field in v1.
A notification is suppressed (not queued) when:
- the Avibe window is focused and visible; or
-- the tray "Notifications" item is unchecked.
+- the tray "Notifications" item is unchecked; or
+- the account-wide `enabled` preference is false; or
+- for `run.terminal` only, its account category is quiet.
System DND / Focus is the OS's problem.
+### Account preferences and run categories
+
+The shell reads `GET /api/notifications/preferences` on every successful
+SSE connection and on `notifications.preferences.updated`. Both use the
+adopted loopback origin, with no redirects or new credentials. Only an
+`ok: true` response containing all three boolean fields under `preferences`
+is accepted; unknown fields are ignored. The event payload is never trusted.
+Failed, malformed, or old-server reads keep the last valid snapshot; before
+any valid snapshot the defaults are all on. Each read is bounded to five
+seconds and 256 KiB. Refresh finishes before the next frame is processed;
+in-flight run deliveries wait for that snapshot too. Badge reads continue
+independently during a preference read.
+
+- `enabled=false` suppresses all OS notification classes, including Vault.
+- `bots=false` suppresses Bot `run.terminal` banners only.
+- `sessions=false` suppresses ordinary Session `run.terminal` banners only.
+- Vault approvals ignore both category switches, while still honoring
+ master, device, and focus/visibility gates.
+
+`GET /api/harness/runs/<id>` provides `notification_category: "bot" | "session"`
+from the same current Bot registry expression as Inbox. Scope, Project
+membership, and run kind never imply a category. A run without a concrete
+Bot permanent Session is `session`. The shell uses this detail field, not
+an event-supplied category. A run must be loud both at receipt and at
+delivery: re-enabling a category does not replay quiet events, and muting
+while a detail read is pending suppresses its eventual delivery.
+
+An unavailable detail, missing/unknown category on an older Runtime, or
+an overloaded lookup backlog is allowed to use generic copy only when
+both categories are loud. Otherwise it is dropped, so failure cannot
+bypass quiet-category intent. Existing background-duration rules still
+apply; preferences never turn a short foreground run into a banner.
+
## Frozen presentation
### Copy lives in the shell, keyed by class + locale
@@ -200,15 +240,16 @@ comes from the run detail the shell already reads
3. `definition_name` — the task or watch, when no session resolved.
A terminal run that qualifies as background work is read back once for
-its label; an unreadable or label-less detail keeps the generic catalog
-title and body rather than withholding the notification. Approval
+its label and category; an unreadable or label-less detail keeps the generic
+catalog title and body if both categories are loud (a known loud category
+also permits a missing label). Approval
banners keep generic copy. Detail reads run beside the SSE reader, never
inside it: each is bounded by the request timeout, at most 16 are in
flight, and at most 64 are pending (later runs queue for a slot, since
a run without stamps is only qualified by its read). Past that backlog
the shell is overloaded: runs the event already qualifies notify at once
-with generic copy, and a run only its read could qualify fails closed.
-Stopping the
+with generic copy only when both categories are loud; otherwise they are
+dropped. A run only its read could qualify fails closed. Stopping the
loop cancels them, so a slow Runtime never delays the next event.
These labels are Runtime strings on their way to a privileged OS
@@ -284,6 +325,13 @@ plugin and reads window-focus / tray-pref state.
- Dedup bound: both approval and run key sets stay within 512
entries / 24h; inserting past the bound drops the oldest, and a
later duplicate of a dropped key may notify again.
+- Account preferences: master gates both classes, category switches gate
+ only their run categories, never Vault; receipt and delivery both honor
+ quiet categories. Preference hints refetch, failed reads preserve the
+ last valid value, reconnect refreshes, and suppression never replays.
+- Old-server/overload fallback: unknown run category can notify only if
+ both categories are loud. Badge reads prefer `badge_total`, including
+ zero, and fall back only when it is absent.
- Focus gate: window focused + visible → no intent even on a matching
event.
- Reconnect: stream drop then restore does not panic, does not
@@ -302,11 +350,16 @@ threshold is exercised in microseconds.
The app icon badge is the second consumer of the shell-owned connection,
not a second connection. Each connect and each decoded frame, of any
type, schedules a read of `GET /api/inbox?platform=avibe&limit=1` and
-paints its `unread_total`. A trailing-edge coalescer allows at most one
+paints its `badge_total` (unread in loud categories). Only when that field
+is absent on an older Runtime does the shell fall back to `unread_total`;
+an explicit zero or malformed field never falls through to the raw count.
+A trailing-edge coalescer allows at most one
read per second. Triggering on every frame instead of an allowlist means
the badge never depends on knowing which events change unread state, and
the 15s heartbeat bounds staleness after a failed read. The badge is
-state, so the Notifications toggle and the focus gate do not apply.
+state, so the device Notifications toggle and the focus gate do not apply.
+Account preferences affect the server's `badge_total`, not whether the
+shell stays connected or refreshes the count.
`stop` clears it on the main thread, behind any paint the voided
generation queued. The WebView cannot own the badge: WebKit suspends
page timers while the window is backgrounded, and WKWebView does not
@@ -316,8 +369,9 @@ overlay icon is follow-up work.
## Explicit non-goals (v1)
- A new HTTP route or a Python "please notify" flag. (The run detail
- gained one additive projected field, `session_project_name`, on the
- existing route.)
+ gained additive projected fields `session_project_name` and
+ `notification_category` on its existing route; preferences reuse #3127's
+ account endpoint.)
- Deep-link click targets (G5).
- Notifying on every chat message, every `session.activity`, or
foreground turns that finish quickly.
diff --git a/storage/background.py b/storage/background.py
index f97fa094b..7d4dbb1fb 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -5137,11 +5137,21 @@ class SQLiteBackgroundTaskStore:
return counts
def get_run(self, run_id: str) -> Optional[dict[str, Any]]:
+ from core.notification_categories import category_expression
+
with self.engine.connect() as conn:
- row = conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().first()
+ row = conn.execute(
+ select(agent_runs, category_expression(agent_runs.c.session_id).label("notification_category"))
+ .where(agent_runs.c.id == run_id)
+ .limit(1)
+ ).mappings().first()
if row is None:
return None
- return self._enrich_runs([self._run_from_row(row)], conn)[0]
+ run = self._run_from_row(row)
+ # The shell consumes the same registry-backed category as Inbox,
+ # never a scope heuristic. No concrete Bot Session means session.
+ run["notification_category"] = row["notification_category"]
+ return self._enrich_runs([run], conn)[0]
def get_unsettled_watch_run(self, definition_id: str) -> Optional[dict[str, Any]]:
"""Return the oldest queued/running Agent follow-up owned by one Watch."""
diff --git a/tests/test_notification_categories.py b/tests/test_notification_categories.py
index 2f8c0d20c..4dbf105dd 100644
--- a/tests/test_notification_categories.py
+++ b/tests/test_notification_categories.py
@@ -190,6 +190,46 @@ def test_inbox_categories_filters_and_badge_total_follow_registry_and_preference
engine.dispose()
+def test_run_detail_category_uses_current_bot_registry_not_scope(isolated_state):
+ """Desktop reads the detail category, not the Inbox row or a scope heuristic."""
+ from core.bots import BotService
+ from storage.background import SQLiteBackgroundTaskStore
+ from storage.projects_service import create_project
+
+ with BotService() as service:
+ bot = service.create_bot(display_name="Desktop test", handle="desktop-category")
+ store = SQLiteBackgroundTaskStore()
+ try:
+ with store.engine.begin() as conn:
+ project_dir = isolated_state / "desktop-category-project"
+ project_dir.mkdir()
+ project = create_project(conn, str(project_dir), display_name="Project")
+ _seed_session(conn, "ses_project", scope_id=project["scope_id"], title="Project Session")
+ _seed_session(conn, "ses_scopeless", scope_id=None, title="No scope, not a Bot")
+ client = app.test_client()
+ for run_id, session_id, category in (
+ ("bot", bot.session_id, "bot"),
+ ("project", "ses_project", "session"),
+ ("scopeless", "ses_scopeless", "session"),
+ ("no-session", None, "session"),
+ ):
+ store.enqueue_run({
+ "id": run_id, "run_type": "watch", "status": "succeeded",
+ "session_id": session_id, "created_at": "2026-09-10T12:00:00Z",
+ "updated_at": "2026-09-10T12:01:00Z",
+ })
+ response = client.get(f"/api/harness/runs/{run_id}", base_url="http://127.0.0.1:5123")
+ assert response.status_code == 200
+ assert response.get_json()["run"]["notification_category"] == category
+ with BotService() as service:
+ service.remove_bot(bot.handle)
+ # Removing the role keeps the Session but changes its category, just
+ # like Inbox; no category is frozen onto the historical run row.
+ assert client.get("/api/harness/runs/bot").get_json()["run"]["notification_category"] == "session"
+ finally:
+ store.close()
+
+
def test_member_cannot_turn_owner_bot_session_into_a_session_category(isolated_state):
from core.bots import BotService, hidden_bot_session_ids
from storage import messages_service