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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(desktop): show the unread total on the macOS Dock badge (#2322)
Max0dcb3e2e9a16
diff --git a/desktop/README.md b/desktop/README.mdindex c27a1894b..b285d588e 100644--- a/desktop/README.md+++ b/desktop/README.md@@ -389,6 +389,19 @@ v1 uses OS-default notification activation; explicit cross-platform show/focusand session deep-link targets require follow-up work. See`../docs/plans/desktop-notifications-sse.md` for the frozen contract.+The same shell-owned connection keeps the app icon badge (the macOS Dock and+supported Linux docks) equal to the Runtime's Avibe inbox `unread_total`. Each+connect and each SSE frame, heartbeats included, schedules one+`GET /api/inbox?platform=avibe&limit=1`; reads are coalesced to at most one per+second, and a failed read keeps the current badge until the next frame. The+badge is state, not an interruption, so neither the Notifications toggle nor+window focus gates it. Zero clears it, and so does giving up the connection+(stopping, quitting, or losing the Runtime). The badge works without the WebView+because WebKit suspends page timers while the window is in the background. That+is also why the Workbench's own `navigator.setAppBadge` call, which only browsers+and PWAs implement, is not relied on here. Windows has no badge count in Tauri;+a taskbar overlay icon is follow-up work.+## MicrophoneWorkbench voice input records through `getUserMedia` inside the WebView. Ondiff --git a/desktop/runtime-host/src/notifications.rs b/desktop/runtime-host/src/notifications.rsindex d0ca6089b..ca66fe5b5 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::Semaphore;+use tokio::sync::{Notify, Semaphore};use tokio::task::JoinSet;use tokio::time::Instant;use url::Url;@@ -20,6 +20,9 @@ const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);const STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(45);const MAX_DETAIL_LOOKUPS: usize = 16;const MAX_PENDING_LOOKUPS: usize = 64;+/// Shortest gap between two unread reads. Events arriving inside it collapse+/// into one read after it, so a busy stream costs at most one read per gap.+pub const UNREAD_REFRESH_INTERVAL: Duration = Duration::from_secs(1);#[derive(Debug, PartialEq, Eq)]pub struct SseFrame {@@ -134,6 +137,9 @@ pub trait NotificationSink: Send + Sync {/// `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.+ fn show_unread(&self, total: u64);}#[derive(Default)]@@ -372,6 +378,7 @@ pub struct StreamError;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>;}pub struct HttpNotificationTransport {@@ -456,6 +463,22 @@ impl NotificationTransport for HttpNotificationTransport {}serde_json::from_value(detail.get("run")?.clone()).ok()}++ /// The same whole-account total the Workbench Inbox badges, counted by the+ /// Runtime: the shell never derives a count of its own.+ async fn unread_total(&self) -> Option<u64> {+ let mut url = self.url("/api/inbox");+ url.query_pairs_mut()+ .append_pair("platform", "avibe")+ .append_pair("limit", "1");+ let response = self.client.get(url).timeout(REQUEST_TIMEOUT).send().await.ok()?;+ if !response.status().is_success() {+ return None;+ }+ let bytes = bounded_detail_body(response).await?;+ let inbox: serde_json::Value = serde_json::from_slice(&bytes).ok()?;+ inbox.get("unread_total")?.as_u64()+ }}async fn bounded_detail_body(mut response: reqwest::Response) -> Option<Vec<u8>> {@@ -498,6 +521,13 @@ pub async fn run_notifications(sink: Arc<dyn NotificationSink>,) {let mut backoff = ReconnectBackoff::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+ // owns the rate. Dropping the set with this future stops it.+ let unread_changed = Arc::new(Notify::new());+ let mut unread = JoinSet::new();+ unread.spawn(follow_unread(transport.clone(), sink.clone(), unread_changed.clone()));// Detail reads run beside the stream, never inside it: a slow read must// not hold back the next chunk (and the approval it may carry). Dropping// the set with this future aborts whatever is still in flight.@@ -506,6 +536,7 @@ pub async fn run_notifications(loop {let connected_at = Instant::now();if let Ok(mut stream) = transport.connect().await {+ unread_changed.notify_one();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 {@@ -516,6 +547,7 @@ pub async fn run_notifications(// 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();let candidate = filter.lock().ok()@@ -564,6 +596,24 @@ pub async fn run_notifications(}}+/// 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+/// already shown until the next frame — at the latest the next heartbeat.+async fn follow_unread(+ transport: Arc<dyn NotificationTransport>,+ sink: Arc<dyn NotificationSink>,+ changed: Arc<Notify>,+) {+ loop {+ changed.notified().await;+ if let Some(total) = transport.unread_total().await {+ sink.show_unread(total);+ }+ tokio::time::sleep(UNREAD_REFRESH_INTERVAL).await;+ }+}+/// One bounded read per terminal run: it names the source and, when the event/// lacked stamps, decides whether the run was background work at all.async fn notify_run(diff --git a/desktop/runtime-host/tests/notification_http.rs b/desktop/runtime-host/tests/notification_http.rsindex c4f8e7aac..5cdee7e6c 100644--- a/desktop/runtime-host/tests/notification_http.rs+++ b/desktop/runtime-host/tests/notification_http.rs@@ -210,3 +210,35 @@ async fn identifiers_are_encoded_as_one_path_segment_not_runtime_selected_routesrequests[0].starts_with("GET /api/harness/runs/..%2Fsettings%3Ftoken=secret%23%E7%89%87%E6%AE%B5 HTTP/1.1\r\n"));}++#[tokio::test]+async fn unread_total_reads_the_runtime_inbox_total_and_fails_closed_on_anything_else() {+ 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#"{"sessions":[],"unread_total":0}"#),+ 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":[]}"#),+ response("200 OK", "text/html", b"<html>"),+ response("200 OK", "application/json", &vec![b' '; 300 * 1024]),+ ]);+ let transport = server.transport();+ assert_eq!(transport.unread_total().await, Some(3));+ assert_eq!(transport.unread_total().await, Some(0));+ for _ in 0..5 {+ assert_eq!(transport.unread_total().await, None);+ }+ let requests = server.requests.lock().unwrap();+ assert_eq!(requests.len(), 7);+ 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"));+ for forbidden in ["authorization:", "cookie:"] {+ assert!(!normalized.contains(forbidden));+ }+ }+}diff --git a/desktop/runtime-host/tests/notifications.rs b/desktop/runtime-host/tests/notifications.rsindex b1b65304c..f96761181 100644--- a/desktop/runtime-host/tests/notifications.rs+++ b/desktop/runtime-host/tests/notifications.rs@@ -7,7 +7,7 @@ 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,+ RETENTION, UNREAD_REFRESH_INTERVAL,};use serde_json::{json, Value};use tokio::time::Instant;@@ -15,12 +15,14 @@ use tokio::time::Instant;struct FakeStream {chunks: VecDeque<Vec<u8>>,drop_after: bool,+ gap: Duration,}#[async_trait]impl EventStream for FakeStream {async fn next_chunk(&mut self) -> Result<Option<Vec<u8>>, StreamError> {if let Some(chunk) = self.chunks.pop_front() {+ tokio::time::sleep(self.gap).await;return Ok(Some(chunk));}if self.drop_after {@@ -38,6 +40,8 @@ struct FakeTransport {details: Mutex<HashMap<String, RunDetail>>,refetched: Mutex<Vec<String>>,detail_delay: Duration,+ unread: Mutex<Option<u64>>,+ unread_reads: Mutex<Vec<Instant>>,}#[async_trait]@@ -57,13 +61,23 @@ impl NotificationTransport for FakeTransport {tokio::time::sleep(self.detail_delay).await;self.details.lock().unwrap().get(run_id).cloned()}++ async fn unread_total(&self) -> Option<u64> {+ self.unread_reads.lock().unwrap().push(Instant::now());+ *self.unread.lock().unwrap()+ }}impl FakeTransport {fn stream(&self, frames: impl IntoIterator<Item = Vec<u8>>, drop_after: bool) {+ self.paced_stream(frames, drop_after, Duration::ZERO);+ }++ fn paced_stream(&self, frames: impl IntoIterator<Item = Vec<u8>>, drop_after: bool, gap: Duration) {self.streams.lock().unwrap().push_back(FakeStream {chunks: frames.into_iter().collect(),drop_after,+ gap,});}}@@ -74,6 +88,7 @@ struct FakeSink {visible: AtomicBool,delivered: Mutex<Vec<NotificationIntent>>,sources: Mutex<Vec<Option<String>>>,+ unread: Mutex<Vec<u64>>,}impl Default for FakeSink {@@ -84,6 +99,7 @@ impl Default for FakeSink {visible: AtomicBool::new(true),delivered: Mutex::new(Vec::new()),sources: Mutex::new(Vec::new()),+ unread: Mutex::new(Vec::new()),}}}@@ -101,6 +117,10 @@ impl NotificationSink for FakeSink {self.delivered.lock().unwrap().push(intent);self.sources.lock().unwrap().push(source);}++ fn show_unread(&self, total: u64) {+ self.unread.lock().unwrap().push(total);+ }}fn stamps_only(stamps: RunTimestamps) -> RunDetail {@@ -788,3 +808,55 @@ async fn stopping_the_loop_cancels_detail_reads_in_flight() {settle().await;assert!(sink.delivered.lock().unwrap().is_empty());}++#[tokio::test(start_paused = true)]+async fn every_connection_and_frame_refreshes_the_runtime_unread_total_at_a_bounded_rate() {+ let transport = Arc::new(FakeTransport::default());+ let sink = Arc::new(FakeSink::default());+ // Gated off: the badge is state, not an interruption.+ sink.enabled.store(false, Ordering::SeqCst);+ sink.focused.store(true, Ordering::SeqCst);+ *transport.unread.lock().unwrap() = Some(3);+ let gap = UNREAD_REFRESH_INTERVAL / 10;+ let events = ["message.new", "session.activity", "invented.event", "heartbeat"];+ let frames: Vec<Vec<u8>> = (0..8).map(|i| frame(events[i % events.len()], json!({}))).collect();+ transport.paced_stream(frames, false, gap);+ let start = Instant::now();+ let task = spawn(transport.clone(), sink.clone());+ settle().await;+ // The connection itself reads the current total.+ assert_eq!(*sink.unread.lock().unwrap(), [3]);+ *transport.unread.lock().unwrap() = Some(0);+ for _ in 0..30 {+ tokio::time::advance(gap).await;+ settle().await;+ }+ // Eight frames of any type inside the cooldown collapse into one trailing+ // read, and that read happens after the last of them.+ assert_eq!(*sink.unread.lock().unwrap(), [3, 0]);+ let reads = transport.unread_reads.lock().unwrap().clone();+ assert_eq!(reads.len(), 2);+ assert!(reads[1] >= start + gap * 8);+ assert!(sink.delivered.lock().unwrap().is_empty());+ 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());+ let sink = Arc::new(FakeSink::default());+ *transport.unread.lock().unwrap() = Some(5);+ transport.stream([frame("heartbeat", json!({}))], true);+ transport.stream([frame("message.new", json!({}))], false);+ let task = spawn(transport.clone(), sink.clone());+ settle().await;+ *transport.unread.lock().unwrap() = None;+ // The first stream drops; the reconnect and its frame read and fail.+ for _ in 0..4 {+ tokio::time::advance(UNREAD_REFRESH_INTERVAL).await;+ settle().await;+ }+ assert!(transport.unread_reads.lock().unwrap().len() >= 2);+ assert_eq!(*sink.unread.lock().unwrap(), [5]);+ task.abort();+}diff --git a/desktop/src-tauri/src/notifications.rs b/desktop/src-tauri/src/notifications.rsindex 97a825bd1..2bd154626 100644--- a/desktop/src-tauri/src/notifications.rs+++ b/desktop/src-tauri/src/notifications.rs@@ -208,14 +208,41 @@ impl NotificationSink for NativeSink {}});}++ fn show_unread(&self, total: u64) {+ let sink = self.clone();+ let _ = self.app.run_on_main_thread(move || {+ // A total read for a connection that has since stopped or moved to+ // another Runtime describes nothing on screen.+ if sink.generation.load(Ordering::SeqCst) == sink.observed_generation {+ paint_badge(&sink.app, total);+ }+ });+ }+}++/// The Badging API's rule: zero clears. macOS would otherwise draw a literal+/// "0". Windows has no badge count, so the call is a no-op error there.+fn badge_count(total: u64) -> Option<i64> {+ (total > 0).then(|| i64::try_from(total).unwrap_or(i64::MAX))+}++fn paint_badge(app: &AppHandle, total: u64) {+ if let Some(window) = app.get_webview_window(MAIN_WINDOW) {+ let _ = window.set_badge_count(badge_count(total));+ }}pub fn start(app: &AppHandle, origin: LoopbackOrigin) {app.state::<Notifications>().start(app, origin);}+/// A stopped connection leaves no count it can vouch for. The clear queues+/// behind any paint already dispatched, which the generation bump voids.pub fn stop(app: &AppHandle) {app.state::<Notifications>().stop();+ let handle = app.clone();+ let _ = app.run_on_main_thread(move || paint_badge(&handle, 0));}#[cfg(test)]@@ -243,6 +270,14 @@ mod tests {}}+ #[test]+ fn zero_clears_the_badge_and_totals_saturate() {+ assert_eq!(badge_count(0), None);+ assert_eq!(badge_count(1), Some(1));+ assert_eq!(badge_count(42), Some(42));+ assert_eq!(badge_count(u64::MAX), Some(i64::MAX));+ }+#[test]fn preference_defaults_on_and_persists_the_tray_choice_across_restarts() {let directory = TestDirectory::new();diff --git a/docs/plans/desktop-notifications-sse.md b/docs/plans/desktop-notifications-sse.mdindex 1224808e6..de5c0b1a5 100644--- a/docs/plans/desktop-notifications-sse.md+++ b/docs/plans/desktop-notifications-sse.md@@ -297,6 +297,22 @@ Drive the filter with a fake SSE collaborator under tokio's virtualclock (same pattern as `runtime-host/tests/bootstrap.rs`) so the 30sthreshold is exercised in microseconds.+## Unread badge (follow-up)++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+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.+`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+implement `navigator.setAppBadge`. Windows lacks a Tauri badge count; an+overlay icon is follow-up work.+## Explicit non-goals (v1)- A new HTTP route or a Python "please notify" flag. (The run detail