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): name the project and session in run notifications (#2227)
Max1e13deebabb8
diff --git a/desktop/README.md b/desktop/README.mdindex 064bd741c..5d080ce35 100644--- a/desktop/README.md+++ b/desktop/README.md@@ -328,9 +328,13 @@ The native tray's Notifications toggle is on by default and persists acrossapp restarts. While the main window is unfocused or hidden, the shell consumesthe existing Workbench SSE stream for pending Vault approvals and qualifyingterminal background runs. The connection belongs to the shell, not the WebView;-SSE reconnection is independent of the readiness monitor. Copy comes only from-the native locale catalog, and no notification capability is granted to web-content. OS notification permissions and Do Not Disturb remain OS-managed.+SSE reconnection is independent of the readiness monitor. Outcome text comes+only from the native locale catalog. A run banner's title names its source+(`Project · Session`, the IM channel, or the task/watch name) from the run+detail; those Runtime labels pass one sanitizer (`RunDetail::source`) that+strips control, bidi, and zero-width formatting characters and bounds length,+and the SSE payload itself is never shown. No notification capability is+granted to web content. OS notification permissions and Do Not Disturb remain OS-managed.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.diff --git a/desktop/runtime-host/Cargo.toml b/desktop/runtime-host/Cargo.tomlindex d93234444..9469cba5d 100644--- a/desktop/runtime-host/Cargo.toml+++ b/desktop/runtime-host/Cargo.toml@@ -17,7 +17,7 @@ serde.workspace = trueserde_json.workspace = truesha2.workspace = truethiserror.workspace = true-tokio.workspace = true+tokio = { workspace = true, features = ["sync"] }url.workspace = truezip.workspace = truediff --git a/desktop/runtime-host/src/notifications.rs b/desktop/runtime-host/src/notifications.rsindex b55d9578a..d0ca6089b 100644--- a/desktop/runtime-host/src/notifications.rs+++ b/desktop/runtime-host/src/notifications.rs@@ -5,6 +5,8 @@ use std::time::Duration;use async_trait::async_trait;use chrono::DateTime;use serde::Deserialize;+use tokio::sync::Semaphore;+use tokio::task::JoinSet;use tokio::time::Instant;use url::Url;@@ -16,6 +18,8 @@ const MAX_EVENT_BYTES: usize = 64 * 1024;const MAX_DETAIL_BYTES: usize = 256 * 1024;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;#[derive(Debug, PartialEq, Eq)]pub struct SseFrame {@@ -127,7 +131,9 @@ impl NotificationGate {pub trait NotificationSink: Send + Sync {fn gate(&self) -> NotificationGate;- fn deliver(&self, intent: NotificationIntent);+ /// `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>);}#[derive(Default)]@@ -212,6 +218,81 @@ impl RunTimestamps {}}+/// The run detail the shell reads back after a terminal event: the stamps+/// that decide whether it is background work, plus the labels that say where+/// it ran. Every label is Runtime text on its way to an OS surface, so it only+/// leaves through [`RunDetail::source`].+#[derive(Clone, Default, Deserialize)]+pub struct RunDetail {+ #[serde(flatten)]+ pub stamps: RunTimestamps,+ pub session_project_name: Option<String>,+ pub session_label: Option<String>,+ pub definition_name: Option<String>,+}++const SOURCE_PART_CHARS: usize = 48;++/// Invisible formatting a single-line title has no use for: bidi marks,+/// embeddings, overrides and isolates (which let a label render its own text+/// backwards), zero-width space, word joiner, BOM, and the private-use area.+/// ZWNJ, ZWJ and variation selectors stay: they spell real words and emoji and+/// cannot reorder text. Same set as `core/citations.py::_CONTROL_RE`.+fn is_invisible_format(character: char) -> bool {+ matches!(+ character,+ '\u{061c}'+ | '\u{200b}'+ | '\u{200e}'+ | '\u{200f}'+ | '\u{202a}'..='\u{202e}'+ | '\u{2060}'+ | '\u{2066}'..='\u{2069}'+ | '\u{feff}'+ | '\u{e000}'..='\u{f8ff}'+ )+}++fn clean_label(value: Option<&str>) -> Option<String> {+ let words = value?+ .chars()+ .filter(|character| !is_invisible_format(*character))+ .map(|character| {+ if character.is_control() || matches!(character, '\u{2028}' | '\u{2029}') {+ ' '+ } else {+ character+ }+ })+ .collect::<String>();+ let collapsed = words.split_whitespace().collect::<Vec<_>>().join(" ");+ if collapsed.is_empty() {+ return None;+ }+ if collapsed.chars().count() <= SOURCE_PART_CHARS {+ return Some(collapsed);+ }+ let mut truncated = collapsed.chars().take(SOURCE_PART_CHARS - 1).collect::<String>();+ truncated.truncate(truncated.trim_end().len());+ truncated.push('…');+ Some(truncated)+}++impl RunDetail {+ /// "Project · Session" for a Workbench session, the channel for an IM+ /// session, and the task or watch name when no session resolved. Control+ /// characters and invisible bidi/zero-width formatting are removed,+ /// whitespace collapsed, and each part bounded.+ pub fn source(&self) -> Option<String> {+ let project = clean_label(self.session_project_name.as_deref());+ let place = clean_label(self.session_label.as_deref()).or_else(|| clean_label(self.definition_name.as_deref()));+ match (project, place) {+ (Some(project), Some(place)) if project != place => Some(format!("{project} · {place}")),+ (project, place) => place.or(project),+ }+ }+}+#[derive(Deserialize)]struct RunEvent {run_id: String,@@ -222,11 +303,14 @@ struct RunEvent {}enum Candidate {- Ready(NotificationIntent),- Refetch {+ Approval,+ Run {run_id: String,stamps: RunTimestamps,intent: NotificationIntent,+ /// Already background work by type or by the event's own stamps; the+ /// detail read only supplies the source label.+ background: bool,},}@@ -251,7 +335,7 @@ impl NotificationFilter {return self.approvals.insert(&approval.request_id, now)- .then_some(Candidate::Ready(NotificationIntent::ApprovalRequested));+ .then_some(Candidate::Approval);}let run: RunEvent = serde_json::from_value(envelope.data).ok()?;if run.run_id.is_empty() {@@ -266,13 +350,12 @@ impl NotificationFilter {if !self.runs.insert(&run.run_id, now) {return None;}- if matches!(run.run_type.as_deref(), Some("scheduled" | "watch")) || run.stamps.is_long_running() {- return Some(Candidate::Ready(intent));- }- run.stamps.missing().then_some(Candidate::Refetch {+ let background = matches!(run.run_type.as_deref(), Some("scheduled" | "watch")) || run.stamps.is_long_running();+ (background || run.stamps.missing()).then_some(Candidate::Run {run_id: run.run_id,stamps: run.stamps,intent,+ background,})}}@@ -288,7 +371,7 @@ pub struct StreamError;#[async_trait]pub trait NotificationTransport: Send + Sync {async fn connect(&self) -> Result<Box<dyn EventStream>, StreamError>;- async fn run_timestamps(&self, run_id: &str) -> Option<RunTimestamps>;+ async fn run_detail(&self, run_id: &str) -> Option<RunDetail>;}pub struct HttpNotificationTransport {@@ -356,7 +439,7 @@ impl NotificationTransport for HttpNotificationTransport {Ok(Box::new(HttpEventStream(response)))}- async fn run_timestamps(&self, run_id: &str) -> Option<RunTimestamps> {+ async fn run_detail(&self, run_id: &str) -> Option<RunDetail> {if matches!(run_id, "" | "." | "..") {return None;}@@ -410,11 +493,16 @@ impl ReconnectBackoff {}pub async fn run_notifications(- transport: &dyn NotificationTransport,+ transport: Arc<dyn NotificationTransport>,filter: Arc<Mutex<NotificationFilter>>,- sink: &dyn NotificationSink,+ sink: Arc<dyn NotificationSink>,) {let mut backoff = ReconnectBackoff::default();+ // 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.+ let mut lookups = JoinSet::new();+ let slots = Arc::new(Semaphore::new(MAX_DETAIL_LOOKUPS));loop {let connected_at = Instant::now();if let Ok(mut stream) = transport.connect().await {@@ -423,38 +511,51 @@ pub async fn run_notifications(if Instant::now().duration_since(connected_at) >= STREAM_IDLE_TIMEOUT {backoff.reset();}+ 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();- let candidates = decoder- .push(&chunk)- .into_iter()- .filter_map(|frame| {- filter- .lock()- .ok()- .and_then(|mut filter| filter.consider(frame, Instant::now()))- })- .collect::<Vec<_>>();- for candidate in candidates.into_iter().filter(|_| allowed_at_receipt) {- let intent = match candidate {- Candidate::Ready(intent) => Some(intent),- Candidate::Refetch {+ for frame in decoder.push(&chunk) {+ let candidate = filter+ .lock()+ .ok()+ .and_then(|mut filter| filter.consider(frame, Instant::now()))+ .filter(|_| allowed_at_receipt);+ match candidate {+ None => {}+ Some(Candidate::Approval) => {+ if sink.gate().allows() {+ sink.deliver(NotificationIntent::ApprovalRequested, None);+ }+ }+ Some(Candidate::Run {run_id,- mut stamps,+ stamps,intent,- } => {- if !sink.gate().allows() {+ background,+ }) => {+ while lookups.try_join_next().is_some() {}+ if lookups.len() >= MAX_PENDING_LOOKUPS {+ // Overloaded: the backlog is bounded. Work the+ // event already qualifies notifies now with+ // generic copy; a run only its read could+ // qualify fails closed.+ if background && sink.gate().allows() {+ sink.deliver(intent, None);+ }continue;}- if let Ok(Some(detail)) =- tokio::time::timeout(REQUEST_TIMEOUT, transport.run_timestamps(&run_id)).await- {- stamps.fill_missing(detail);- }- stamps.is_long_running().then_some(intent)+ let (transport, sink, slots) = (transport.clone(), sink.clone(), slots.clone());+ lookups.spawn(async move {+ // Queue behind the request limit rather than+ // drop: a run without stamps is only decided+ // by its read.+ let Ok(_slot) = slots.acquire_owned().await else {+ return;+ };+ notify_run(transport, sink, run_id, stamps, intent, background).await;+ });}- };- if let Some(intent) = intent.filter(|_| sink.gate().allows()) {- sink.deliver(intent);}}}@@ -463,6 +564,29 @@ pub async fn run_notifications(}}+/// 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(+ transport: Arc<dyn NotificationTransport>,+ sink: Arc<dyn NotificationSink>,+ run_id: String,+ mut stamps: RunTimestamps,+ intent: NotificationIntent,+ background: bool,+) {+ let detail = tokio::time::timeout(REQUEST_TIMEOUT, transport.run_detail(&run_id))+ .await+ .ok()+ .flatten();+ let source = detail.as_ref().and_then(RunDetail::source);+ if let Some(detail) = detail {+ stamps.fill_missing(detail.stamps);+ }+ if (background || stamps.is_long_running()) && sink.gate().allows() {+ sink.deliver(intent, source);+ }+}+#[cfg(test)]mod tests {use super::*;diff --git a/desktop/runtime-host/tests/notification_http.rs b/desktop/runtime-host/tests/notification_http.rsindex 677545299..c4f8e7aac 100644--- a/desktop/runtime-host/tests/notification_http.rs+++ b/desktop/runtime-host/tests/notification_http.rs@@ -146,7 +146,7 @@ async fn stream_and_detail_redirects_never_delegate_trust_to_another_origin() {let server = FakeServer::start([redirect.clone(), redirect]);let transport = server.transport();assert!(transport.connect().await.is_err());- assert!(transport.run_timestamps("run").await.is_none());+ assert!(transport.run_detail("run").await.is_none());assert!(target.requests.lock().unwrap().is_empty());assert_eq!(server.requests.lock().unwrap().len(), 2);}@@ -167,6 +167,7 @@ async fn stream_requires_a_successful_sse_response_not_an_arbitrary_live_http_enasync 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",+ "session_project_name": "avibe-app", "session_label": "桌面版检查更新", "definition_name": null,}});let server = FakeServer::start([response("200 OK", "application/json", valid.to_string().as_bytes()),@@ -182,11 +183,12 @@ async fn refetch_requires_the_requested_run_and_bounds_untrusted_detail_bodies().to_vec(),]);let transport = server.transport();- let detail = transport.run_timestamps("run").await.unwrap();- assert_eq!(detail.started_at, Some("2026-09-10T12:00:00Z".into()));- assert_eq!(detail.updated_at, Some("2026-09-10T12:00:30Z".into()));+ 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.source(), Some("avibe-app · 桌面版检查更新".into()));for _ in 0..5 {- assert!(transport.run_timestamps("run").await.is_none());+ assert!(transport.run_detail("run").await.is_none());}for request in server.requests.lock().unwrap().iter() {assert!(request.starts_with("GET /api/harness/runs/run HTTP/1.1\r\n"));@@ -198,13 +200,10 @@ async fn identifiers_are_encoded_as_one_path_segment_not_runtime_selected_routeslet server = FakeServer::start([response("404 Not Found", "application/json", b"{}")]);let transport = server.transport();for key in ["", ".", ".."] {- assert!(transport.run_timestamps(key).await.is_none());+ assert!(transport.run_detail(key).await.is_none());}assert!(server.requests.lock().unwrap().is_empty());- assert!(transport- .run_timestamps("../settings?token=secret#片段")- .await- .is_none());+ assert!(transport.run_detail("../settings?token=secret#片段").await.is_none());let requests = server.requests.lock().unwrap();assert_eq!(requests.len(), 1);assert!(diff --git a/desktop/runtime-host/tests/notifications.rs b/desktop/runtime-host/tests/notifications.rsindex 364d527f0..b1b65304c 100644--- a/desktop/runtime-host/tests/notifications.rs+++ b/desktop/runtime-host/tests/notifications.rs@@ -6,7 +6,8 @@ use std::time::Duration;use async_trait::async_trait;use avibe_runtime_host::notifications::{run_notifications, EventStream, NotificationFilter, NotificationGate, NotificationIntent, NotificationSink,- NotificationTransport, ReconnectBackoff, RunTimestamps, SseDecoder, StreamError, RETAINED_KEYS, RETENTION,+ NotificationTransport, ReconnectBackoff, RunDetail, RunTimestamps, SseDecoder, StreamError, RETAINED_KEYS,+ RETENTION,};use serde_json::{json, Value};use tokio::time::Instant;@@ -34,7 +35,7 @@ impl EventStream for FakeStream {struct FakeTransport {streams: Mutex<VecDeque<FakeStream>>,connected_at: Mutex<Vec<Instant>>,- details: Mutex<HashMap<String, RunTimestamps>>,+ details: Mutex<HashMap<String, RunDetail>>,refetched: Mutex<Vec<String>>,detail_delay: Duration,}@@ -51,7 +52,7 @@ impl NotificationTransport for FakeTransport {.ok_or(StreamError)}- async fn run_timestamps(&self, run_id: &str) -> Option<RunTimestamps> {+ async fn run_detail(&self, run_id: &str) -> Option<RunDetail> {self.refetched.lock().unwrap().push(run_id.to_owned());tokio::time::sleep(self.detail_delay).await;self.details.lock().unwrap().get(run_id).cloned()@@ -72,6 +73,7 @@ struct FakeSink {focused: AtomicBool,visible: AtomicBool,delivered: Mutex<Vec<NotificationIntent>>,+ sources: Mutex<Vec<Option<String>>>,}impl Default for FakeSink {@@ -81,6 +83,7 @@ impl Default for FakeSink {focused: AtomicBool::new(false),visible: AtomicBool::new(true),delivered: Mutex::new(Vec::new()),+ sources: Mutex::new(Vec::new()),}}}@@ -94,8 +97,16 @@ impl NotificationSink for FakeSink {}}- fn deliver(&self, intent: NotificationIntent) {+ fn deliver(&self, intent: NotificationIntent, source: Option<String>) {self.delivered.lock().unwrap().push(intent);+ self.sources.lock().unwrap().push(source);+ }+}++fn stamps_only(stamps: RunTimestamps) -> RunDetail {+ RunDetail {+ stamps,+ ..RunDetail::default()}}@@ -127,7 +138,7 @@ fn run(run_id: impl ToString, run_type: &str, seconds: u64) -> Vec<u8> {fn spawn(transport: Arc<FakeTransport>, sink: Arc<FakeSink>) -> tokio::task::JoinHandle<()> {tokio::spawn(async move {- run_notifications(&*transport, Arc::new(Mutex::new(NotificationFilter::default())), &*sink).await;+ run_notifications(transport, Arc::new(Mutex::new(NotificationFilter::default())), sink).await;})}@@ -292,7 +303,9 @@ async fn durable_duration_not_arrival_or_attach_time_controls_all_other_run_kind*sink.delivered.lock().unwrap(),vec![NotificationIntent::RunSucceeded; expected]);- assert!(transport.refetched.lock().unwrap().is_empty());+ // Only runs that notify are read back, once each, for their source label;+ // an unavailable detail never withholds one the event already qualified.+ assert_eq!(transport.refetched.lock().unwrap().len(), expected);task.abort();}@@ -332,7 +345,7 @@ async fn terminal_stamps_cover_offsets_updated_at_precision_and_fail_closed_valu*sink.delivered.lock().unwrap(),vec![NotificationIntent::RunFailed; expected]);- assert!(transport.refetched.lock().unwrap().is_empty());+ assert_eq!(transport.refetched.lock().unwrap().len(), expected);task.abort();}@@ -362,7 +375,11 @@ async fn missing_stamps_refetch_once_per_retained_terminal_and_then_fail_closed(.enumerate(){let key = index.to_string();- transport.details.lock().unwrap().insert(key.clone(), stamps);+ transport+ .details+ .lock()+ .unwrap()+ .insert(key.clone(), stamps_only(stamps));let event = frame("runs.updated",json!({"run_id": key, "status": "canceled", "run_type": "agent_run"}),@@ -375,7 +392,11 @@ async fn missing_stamps_refetch_once_per_retained_terminal_and_then_fail_closed(("fill-start", json!({"completed_at": "2026-09-10T12:00:30Z"})),("fill-end", json!({"started_at": "2026-09-10T12:00:00Z"})),] {- transport.details.lock().unwrap().insert(key.into(), complete.clone());+ transport+ .details+ .lock()+ .unwrap()+ .insert(key.into(), stamps_only(complete.clone()));let mut data = data;data["run_id"] = json!(key);data["status"] = json!("canceled");@@ -429,7 +450,7 @@ async fn both_key_classes_expire_after_24_hours_despite_missing_transitions() {transport.stream([approval("same", "pending"), run("same", "watch", 0)], false);let retained = filter.clone();let output = sink.clone();- let task = tokio::spawn(async move { run_notifications(&*transport, retained, &*output).await });+ let task = tokio::spawn(async move { run_notifications(transport, retained, output).await });settle().await;assert_eq!(sink.delivered.lock().unwrap().len(), expected);task.abort();@@ -474,11 +495,11 @@ async fn focus_is_rechecked_after_refetch_without_deferring_the_notification() {let sink = Arc::new(FakeSink::default());transport.details.lock().unwrap().insert("run".into(),- RunTimestamps {+ stamps_only(RunTimestamps {started_at: Some("2026-09-10T12:00:00Z".into()),completed_at: Some("2026-09-10T12:01:00Z".into()),..RunTimestamps::default()- },+ }),);transport.stream([frame("runs.updated", json!({"run_id": "run", "status": "succeeded"}))],@@ -578,3 +599,192 @@ fn reconnect_backoff_is_positive_capped_and_resettable() {backoff.reset();assert_eq!(backoff.next_delay(), Duration::from_secs(1));}++#[tokio::test(start_paused = true)]+async fn run_notifications_name_their_source_from_sanitized_detail_labels() {+ let transport = Arc::new(FakeTransport::default());+ let sink = Arc::new(FakeSink::default());+ let label = |project: Option<&str>, session: Option<&str>, definition: Option<&str>| RunDetail {+ session_project_name: project.map(Into::into),+ session_label: session.map(Into::into),+ definition_name: definition.map(Into::into),+ ..RunDetail::default()+ };+ let long = "长".repeat(80);+ let cases = [+ (+ label(Some("avibe-app"), Some("桌面版检查更新"), Some("rc21 release run")),+ Some("avibe-app · 桌面版检查更新".to_owned()),+ ),+ (label(None, Some("#dev-ops"), None), Some("#dev-ops".to_owned())),+ (+ label(None, None, Some("nightly audit")),+ Some("nightly audit".to_owned()),+ ),+ (label(Some("solo"), Some("solo"), None), Some("solo".to_owned())),+ (+ label(Some(" \u{1b}[31mproj\n"), Some("line\r\nbreak\u{7}\t here"), None),+ Some("[31mproj · line break here".to_owned()),+ ),+ (label(Some(&long), None, None), Some(format!("{}…", "长".repeat(47)))),+ (label(Some(" "), Some("\n"), None), None),+ (+ label(+ Some("inv\u{202e}oice\u{2066}\u{200b}"),+ Some("a\u{2028}b\u{feff}\u{e001}"),+ None,+ ),+ Some("invoice · a b".to_owned()),+ ),+ (+ label(None, Some("👨\u{200d}👩 नम\u{200c}स्ते"), None),+ Some("👨\u{200d}👩 नम\u{200c}स्ते".to_owned()),+ ),+ (+ label(Some("\u{202e}\u{2069}"), None, Some("audit")),+ Some("audit".to_owned()),+ ),+ (RunDetail::default(), None),+ ];+ let mut chunks = Vec::new();+ let mut expected = Vec::new();+ for (index, (detail, source)) in cases.into_iter().enumerate() {+ transport.details.lock().unwrap().insert(index.to_string(), detail);+ chunks.push(run(index, "watch", 0));+ expected.push(source);+ }+ // A detail that cannot be read keeps the generic copy rather than the run.+ chunks.push(run("unreadable", "scheduled", 0));+ expected.push(None);+ transport.stream(chunks, false);+ let task = spawn(transport, sink.clone());+ settle().await;+ assert_eq!(*sink.sources.lock().unwrap(), expected);+ assert_eq!(sink.delivered.lock().unwrap().len(), expected.len());+ task.abort();+}++#[tokio::test(start_paused = true)]+async fn slow_detail_reads_never_hold_back_the_stream_or_its_approvals() {+ // Same chunk, and one event per chunk (the Runtime's usual shape).+ let chunked = |separate: bool| {+ let mut frames = (0..5).map(|index| run(index, "watch", 0)).collect::<Vec<_>>();+ frames.push(approval("request", "pending"));+ if separate {+ frames+ } else {+ vec![frames.concat()]+ }+ };+ for separate in [false, true] {+ let transport = Arc::new(FakeTransport {+ detail_delay: Duration::from_secs(60),+ ..FakeTransport::default()+ });+ let sink = Arc::new(FakeSink::default());+ transport.stream(chunked(separate), false);+ let task = spawn(transport.clone(), sink.clone());+ settle().await;+ assert_eq!(*sink.delivered.lock().unwrap(), [NotificationIntent::ApprovalRequested]);+ assert_eq!(transport.refetched.lock().unwrap().len(), 5);+ tokio::time::advance(Duration::from_secs(5)).await;+ settle().await;+ let mut expected = vec![NotificationIntent::ApprovalRequested];+ expected.extend([NotificationIntent::RunSucceeded; 5]);+ assert_eq!(*sink.delivered.lock().unwrap(), expected);+ assert_eq!(*sink.sources.lock().unwrap(), vec![None; 6]);+ task.abort();+ }+}++#[tokio::test(start_paused = true)]+async fn runs_beyond_the_lookup_limit_queue_instead_of_being_dropped() {+ let transport = Arc::new(FakeTransport {+ detail_delay: Duration::from_secs(1),+ ..FakeTransport::default()+ });+ // Foreground runs without stamps: only their detail can qualify them.+ for index in 0..40 {+ transport.details.lock().unwrap().insert(+ format!("run-{index}"),+ stamps_only(RunTimestamps {+ started_at: Some("2026-09-10T12:00:00Z".into()),+ completed_at: Some("2026-09-10T12:00:45Z".into()),+ ..RunTimestamps::default()+ }),+ );+ }+ let sink = Arc::new(FakeSink::default());+ transport.stream(+ (0..40).map(|index| {+ frame(+ "runs.updated",+ json!({"run_id": format!("run-{index}"), "status": "succeeded"}),+ )+ }),+ false,+ );+ let task = spawn(transport.clone(), sink.clone());+ settle().await;+ assert_eq!(transport.refetched.lock().unwrap().len(), 16);+ for _ in 0..3 {+ tokio::time::advance(Duration::from_secs(1)).await;+ settle().await;+ }+ assert_eq!(transport.refetched.lock().unwrap().len(), 40);+ assert_eq!(+ *sink.delivered.lock().unwrap(),+ vec![NotificationIntent::RunSucceeded; 40]+ );+ task.abort();+}++#[tokio::test(start_paused = true)]+async fn an_overloaded_backlog_is_bounded_and_falls_back_to_generic_copy() {+ let transport = Arc::new(FakeTransport {+ detail_delay: Duration::from_secs(60),+ ..FakeTransport::default()+ });+ let sink = Arc::new(FakeSink::default());+ let mut frames = (0..100).map(|index| run(index, "watch", 0)).collect::<Vec<_>>();+ frames.push(frame(+ "runs.updated",+ json!({"run_id": "unstamped", "status": "succeeded"}),+ ));+ transport.stream(frames, false);+ let task = spawn(transport.clone(), sink.clone());+ settle().await;+ // 64 are pending (16 reading); the other 36 known-background runs notify+ // at once without a source, and the unstamped overflow fails closed.+ assert_eq!(transport.refetched.lock().unwrap().len(), 16);+ assert_eq!(sink.delivered.lock().unwrap().len(), 36);+ for _ in 0..4 {+ tokio::time::advance(Duration::from_secs(5)).await;+ settle().await;+ }+ assert_eq!(transport.refetched.lock().unwrap().len(), 64);+ assert_eq!(+ *sink.delivered.lock().unwrap(),+ vec![NotificationIntent::RunSucceeded; 100]+ );+ assert!(!transport.refetched.lock().unwrap().contains(&"unstamped".to_owned()));+ task.abort();+}++#[tokio::test(start_paused = true)]+async fn stopping_the_loop_cancels_detail_reads_in_flight() {+ let transport = Arc::new(FakeTransport {+ detail_delay: Duration::from_secs(1),+ ..FakeTransport::default()+ });+ let sink = Arc::new(FakeSink::default());+ transport.stream([run("slow", "watch", 0)], false);+ let task = spawn(transport.clone(), sink.clone());+ settle().await;+ assert_eq!(*transport.refetched.lock().unwrap(), ["slow"]);+ task.abort();+ assert!(task.await.unwrap_err().is_cancelled());+ tokio::time::advance(Duration::from_secs(5)).await;+ settle().await;+ assert!(sink.delivered.lock().unwrap().is_empty());+}diff --git a/desktop/src-tauri/src/notifications.rs b/desktop/src-tauri/src/notifications.rsindex 1c604b78b..97a825bd1 100644--- a/desktop/src-tauri/src/notifications.rs+++ b/desktop/src-tauri/src/notifications.rs@@ -41,6 +41,20 @@ impl NativeNotificationCatalog {}.clone()}++ /// With a known source the banner reads like a mail notification: where it+ /// happened as the title, the outcome as the body. Without one it keeps the+ /// generic sentence, which is all the shell can honestly say.+ fn render(&self, intent: NotificationIntent, source: Option<String>) -> NotificationCopy {+ let copy = self.copy(intent);+ match source {+ Some(source) => NotificationCopy {+ title: source,+ body: copy.title,+ },+ None => copy,+ }+ }}#[derive(Deserialize, Serialize)]@@ -135,7 +149,7 @@ impl Notifications {*connection = Some(Connection {origin,task: tauri::async_runtime::spawn(async move {- run_notifications(&transport, filter, &sink).await;+ run_notifications(Arc::new(transport), filter, Arc::new(sink)).await;}),});}@@ -172,7 +186,7 @@ impl NotificationSink for NativeSink {}}- fn deliver(&self, intent: NotificationIntent) {+ fn deliver(&self, intent: NotificationIntent, source: Option<String>) {let sink = self.clone();let _ = self.app.run_on_main_thread(move || {if !sink.gate().allows() {@@ -180,7 +194,7 @@ impl NotificationSink for NativeSink {}let copy = native_catalog_for_locales(sys_locale::get_locales()).notifications- .copy(intent);+ .render(intent, source);if sink.app.notification()@@ -271,6 +285,11 @@ mod tests {let copy = catalog.copy(intent);assert!(!copy.title.is_empty() && !copy.body.is_empty());assert!(!copy.body.contains("{{"));+ let sourced = catalog.render(intent, Some("avibe-app · 发布检查".into()));+ assert_eq!(sourced.title, "avibe-app · 发布检查");+ assert_eq!(sourced.body, copy.title);+ let generic = catalog.render(intent, None);+ assert_eq!((generic.title, generic.body), (copy.title, copy.body));}}}diff --git a/docs/plans/desktop-notifications-sse.md b/docs/plans/desktop-notifications-sse.mdindex 16d093362..1224808e6 100644--- a/docs/plans/desktop-notifications-sse.md+++ b/docs/plans/desktop-notifications-sse.md@@ -167,7 +167,8 @@ System DND / Focus is the OS's problem.### Copy lives in the shell, keyed by class + localeExisting SSE payloads are refetch hints (`run_id` / `request_id`), not-finished user copy. The shell therefore owns notification title/body,+finished user copy. The shell therefore owns the notification outcome+text (and, for run banners, sanitizes the source label described below),using the same locale catalog pattern as the tray (`sys-locale` →`desktopBootstrap` keys in `ui/src/i18n/{en,zh}.json`, verified by`npm run test:i18n`).@@ -184,10 +185,39 @@ v1 keys (names frozen; wording is i18n content, not contract):- `desktopBootstrap.notifications.runCanceled.body`- `desktopBootstrap.notifications.toggle` (tray menu label)-Bodies may include the `session_id` / `run_id` as a short suffix when-present; they must not interpolate unsanitized Runtime strings into-the OS notification (the payload is untrusted process output on its-way to a privileged surface, same rule as refused origins).+### Run notifications name their source++A run banner says where the work happened, the way a mail notification+names the sender: the **title** is the source and the **body** is the+outcome (the catalog's run `title`, e.g. "Run completed"). The source+comes from the run detail the shell already reads+(`GET /api/harness/runs/<id>`), in precedence order:++1. `session_project_name · session_label` — a Workbench session in a+ Project (`session_project_name` is the Project display name, projected+ by the same session summary that produces `session_label`);+2. `session_label` alone — an IM session reads as its channel name;+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+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+loop cancels them, so a slow Runtime never delays the next event.++These labels are Runtime strings on their way to a privileged OS+surface, so they leave only through one sanitizer+(`RunDetail::source`): control characters and invisible bidi /+zero-width formatting removed (the same set as `core/citations.py`;+ZWJ, ZWNJ and variation selectors kept), whitespace collapsed, each+part bounded to 48 characters. The SSE payload itself+is still never interpolated.### Plugin and permission@@ -269,7 +299,9 @@ threshold is exercised in microseconds.## Explicit non-goals (v1)-- A new HTTP route or a Python "please notify" flag.+- 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.)- Deep-link click targets (G5).- Notifying on every chat message, every `session.activity`, orforeground turns that finish quickly.diff --git a/storage/background.py b/storage/background.pyindex 8923ea2ee..dffb46d3a 100644--- a/storage/background.py+++ b/storage/background.py@@ -9320,6 +9320,7 @@ class SQLiteBackgroundTaskStore:"session_platform": None,"session_scope_kind": None,"session_label": None,+ "session_project_name": None,"session_is_workbench": False,"session_openable": False,}@@ -9410,6 +9411,9 @@ class SQLiteBackgroundTaskStore:"session_platform": platform or None,"session_scope_kind": scope_type or None,"session_label": row["title"] if is_workbench else (row["display_name"] or row["native_id"]),+ # The Project a workbench session lives in, so a surface without the+ # Workbench around it (a desktop notification) can say where it was.+ "session_project_name": (row["display_name"] or None) if scope_type == "project" else None,"session_is_workbench": is_workbench,"session_openable": session_openable_in_chat(session_id=row["id"], scope_native_type=row["native_type"]@@ -9502,6 +9506,7 @@ class SQLiteBackgroundTaskStore:"session_platform": platform,"session_scope_kind": scope_type,"session_label": display_name or native_id,+ "session_project_name": None,"session_is_workbench": False,# A delivery key names a channel, not a session; there is no id to# open even though the label reads like one.diff --git a/tests/test_harness_run_projection.py b/tests/test_harness_run_projection.pyindex 9c5720a01..e5bb68b1d 100644--- a/tests/test_harness_run_projection.py+++ b/tests/test_harness_run_projection.py@@ -36,8 +36,12 @@ def _build_schema(db_path: Path) -> None:SQLiteSessionsService(db_path).close()-def _make_workbench_session(conn, tmp_path: Path, native_id: str, title: str) -> str:- scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id=native_id, now=NOW)+def _make_workbench_session(+ conn, tmp_path: Path, native_id: str, title: str, project_name: str | None = None+) -> str:+ scope_id = upsert_scope(+ conn, platform="avibe", scope_type="project", native_id=native_id, now=NOW, display_name=project_name+ )conn.execute(scope_settings.insert().values(scope_id=scope_id,@@ -99,7 +103,7 @@ def test_run_payload_resolves_every_session_state(tmp_path: Path) -> None:engine = create_sqlite_engine(db_path)try:with engine.begin() as conn:- workbench_id = _make_workbench_session(conn, tmp_path, "proj_runs", "重构鉴权模块")+ workbench_id = _make_workbench_session(conn, tmp_path, "proj_runs", "重构鉴权模块", "鉴权服务")upsert_scope(conn, platform="slack", scope_type="channel", native_id="C0123", now=NOW, display_name="#dev-ops")@@ -122,6 +126,7 @@ def test_run_payload_resolves_every_session_state(tmp_path: Path) -> None:assert workbench["session_label"] == "重构鉴权模块"assert workbench["session_platform"] == "avibe"assert workbench["session_scope_kind"] == "project"+ assert workbench["session_project_name"] == "鉴权服务"im = runs["run_im"]assert im["session_is_workbench"] is False # reads as a channel, not as a session title@@ -132,6 +137,7 @@ def test_run_payload_resolves_every_session_state(tmp_path: Path) -> None:assert im["session_openable"] is Falseassert im["session_platform"] == "slack"assert im["session_label"] == "#dev-ops" # display name, not the raw channel id+ assert im["session_project_name"] is None # a channel is not a Project# A run outlives its session. The summary stays all-null so the UI can say# "session deleted" instead of printing an id that opens nothing.@@ -438,7 +444,7 @@ def test_every_projected_label_is_searchable(tmp_path: Path) -> None:engine = create_sqlite_engine(db_path)try:with engine.begin() as conn:- bound = _make_workbench_session(conn, tmp_path, "proj_probe", "重构鉴权模块")+ bound = _make_workbench_session(conn, tmp_path, "proj_probe", "重构鉴权模块", "鉴权服务")reporter = _make_workbench_session(conn, tmp_path, "proj_reporter", "编排调度会话")upsert_scope(conn, platform="slack", scope_type="channel", native_id="C0123", now=NOW, display_name="#dev-ops"@@ -484,7 +490,7 @@ def test_every_projected_label_is_searchable(tmp_path: Path) -> None:# The walk is not vacuous: it reached every site, including the nested one.# Asserted against the fixture's values, not against field names, so this# keeps holding when a site is renamed or a new one appears.- planted = {"重构鉴权模块", "编排调度会话", "磁盘水位巡检", "#dev-ops"}+ planted = {"重构鉴权模块", "鉴权服务", "编排调度会话", "磁盘水位巡检", "#dev-ops"}seen = {value for fields in projected.values() for value in fields.values()}assert planted <= seen, f"projection walk missed {planted - seen}"