Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Mirror notifications in the core
Bee2538194c8f96
diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rsindex 4120a43..a0744da 100644--- a/core/nectarlink-core/src/config.rs+++ b/core/nectarlink-core/src/config.rs@@ -3,7 +3,7 @@ use std::{fmt, path::PathBuf};use nectarlink_protocol::messages::{DeviceInfo, PowerLevel};-use crate::identity::KeyProtector;+use crate::{identity::KeyProtector, notifications::NotificationError};/// Configuration for starting a [`Node`](crate::Node).#[derive(Clone)]@@ -67,6 +67,21 @@ pub trait Platform: Send + Sync + 'static {fn start_ringing(&self) {}/// Stop ringing.fn stop_ringing(&self) {}++ /// Dismiss one of this device's notifications (a PC dismissed it).+ fn dismiss_notification(&self, _key: &str) -> Result<(), NotificationError> {+ Err(NotificationError::Unsupported)+ }+ /// Run an action of one of this device's notifications; `reply` holds+ /// the text for a reply action.+ fn run_notification_action(+ &self,+ _key: &str,+ _action: &str,+ _reply: Option<&str>,+ ) -> Result<(), NotificationError> {+ Err(NotificationError::Unsupported)+ }}/// A platform that does nothing; useful for tests and headless tools.diff --git a/core/nectarlink-core/src/error.rs b/core/nectarlink-core/src/error.rsindex 4af5424..a76c41b 100644--- a/core/nectarlink-core/src/error.rs+++ b/core/nectarlink-core/src/error.rs@@ -26,6 +26,8 @@ pub enum Error {VersionTooOld { side: Side },#[error("not supported by the other device")]Unsupported,+ #[error("it no longer exists")]+ NotFound,#[error("no pairing in progress")]NotPairing,#[error("invalid pairing link: {0}")]@@ -51,6 +53,7 @@ impl From<ProtocolError> for Error {ErrorCode::Denied => Error::Denied,ErrorCode::Unpaired => Error::NotPaired,ErrorCode::Unsupported => Error::Unsupported,+ ErrorCode::NotFound => Error::NotFound,ErrorCode::VersionTooOld => Error::VersionTooOld { side: Side::Local },other => Error::Protocol(format!("{other}: {msg}")),},diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rsindex 7503557..3deda90 100644--- a/core/nectarlink-core/src/events.rs+++ b/core/nectarlink-core/src/events.rs@@ -3,7 +3,7 @@use nectarlink_protocol::{DeviceId,- messages::{Battery, DeviceInfo, PowerLevel},+ messages::{Battery, DeviceInfo, Notification, PowerLevel},};use crate::features::CapabilityMatrix;@@ -100,4 +100,19 @@ pub enum NodeEvent {Discovered(DiscoveredDevice),DiscoveryExpired(DeviceId),Pairing(PairingEvent),+ /// Everything a phone shows now, replacing what was known before (no+ /// alerts for these). Empty when the phone stopped sharing them.+ NotificationsReset {+ device: DeviceId,+ items: Vec<Notification>,+ },+ /// A new notification, or an update of the one with the same key.+ NotificationPosted {+ device: DeviceId,+ notification: Notification,+ },+ NotificationRemoved {+ device: DeviceId,+ key: String,+ },}diff --git a/core/nectarlink-core/src/features.rs b/core/nectarlink-core/src/features.rsindex aadb321..d21ac87 100644--- a/core/nectarlink-core/src/features.rs+++ b/core/nectarlink-core/src/features.rs@@ -270,15 +270,7 @@ impl DeviceFacts {}fn role(&self) -> Option<Role> {- match self.kind {- DeviceKind::Phone | DeviceKind::Tablet => Some(Role::Phone),- DeviceKind::Desktop | DeviceKind::Laptop => Some(Role::Desktop),- DeviceKind::Unknown => match self.os.as_str() {- "android" => Some(Role::Phone),- "windows" | "macos" => Some(Role::Desktop),- _ => None,- },- }+ role_from(self.kind, &self.os)}/// The Android release (`"16"` → 16), if this is an Android device.@@ -292,6 +284,24 @@ impl DeviceFacts {}}+/// Which role a device plays in a pair, from its kind (or OS when the kind+/// is unknown to this version).+pub(crate) fn role_of(info: &DeviceInfo) -> Option<Role> {+ role_from(info.kind, &info.os)+}++fn role_from(kind: DeviceKind, os: &str) -> Option<Role> {+ match kind {+ DeviceKind::Phone | DeviceKind::Tablet => Some(Role::Phone),+ DeviceKind::Desktop | DeviceKind::Laptop => Some(Role::Desktop),+ DeviceKind::Unknown => match os {+ "android" => Some(Role::Phone),+ "windows" | "macos" => Some(Role::Desktop),+ _ => None,+ },+ }+}+fn leading_number(s: &str) -> Option<u32> {let end = s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len());s[..end].parse().ok()diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rsindex 9d3893b..910a8f8 100644--- a/core/nectarlink-core/src/lib.rs+++ b/core/nectarlink-core/src/lib.rs@@ -12,6 +12,7 @@ mod events;pub mod features;mod identity;mod node;+mod notifications;mod pairing;mod session;mod store;@@ -25,10 +26,11 @@ pub use features::{CapabilityMatrix, FeatureState};pub use identity::{KeyProtector, PlainKeyProtector, default_protector};pub use nectarlink_protocol::{DeviceId,- messages::{Battery, DeviceInfo, DeviceKind, PowerLevel},+ messages::{Battery, DeviceInfo, DeviceKind, Notification, NotificationAction, PowerLevel},pairing::PairingUri,};pub use node::Node;+pub use notifications::NotificationError;pub(crate) fn device_id(key: &iroh::PublicKey) -> DeviceId {DeviceId(*key.as_bytes())diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rsindex 6abec51..08ecb4d 100644--- a/core/nectarlink-core/src/node.rs+++ b/core/nectarlink-core/src/node.rs@@ -19,7 +19,9 @@ use iroh::{use iroh_mdns_address_lookup::{DiscoveryEvent, MdnsAddressLookup};use nectarlink_protocol::{ALPN_PAIR, ALPN_SESSION, DeviceId, Envelope, ErrorCode,- messages::{Battery, DeviceInfo, HelloUpdate, PowerLevel, Ring, types},+ messages::{+ Battery, DeviceInfo, HelloUpdate, Notification, NotifyAction, NotifyKey, PowerLevel, Ring, types,+ },pairing::PairingUri,};use tokio::sync::{Notify, broadcast};@@ -30,6 +32,7 @@ use crate::{events::{ConnectionPath, DiscoveredDevice, LinkState, NodeEvent, PairedDevice, PairingEvent},features::{self, CapabilityMatrix, DeviceFacts, MatrixInputs},identity,+ notifications::{self, Feed},pairing::{self, PairingState},session::{self, CLOSE_DUPLICATE, CLOSE_NORMAL, REQUEST_TIMEOUT, Session},store::Store,@@ -95,6 +98,10 @@ pub(crate) struct Shared {matrices: Mutex<HashMap<DeviceId, CapabilityMatrix>>,away_mode: bool,memory: MemoryLookup,+ /// This device's notifications, when it mirrors them (phones).+ pub notifications: Feed,+ /// The node's runtime, for work started from non-async callers.+ runtime: tokio::runtime::Handle,}impl std::fmt::Debug for Shared {@@ -113,6 +120,16 @@ impl Shared {let _ = self.events.send(event);}+ /// Every connected device's session.+ pub fn live_sessions(&self) -> Vec<Arc<Session>> {+ lock(&self.sessions).values().filter(|s| s.is_alive()).cloned().collect()+ }++ /// The capabilities this device offers right now.+ pub fn local_capabilities(&self) -> Vec<String> {+ self.local.read().unwrap_or_else(|e| e.into_inner()).capabilities()+ }+pub fn session(&self, peer: &DeviceId) -> Option<Arc<Session>> {lock(&self.sessions).get(peer).filter(|s| s.is_alive()).cloned()}@@ -279,14 +296,16 @@ impl Shared {// Bring the peer up to date with state it may have missed.let battery = self.local.read().unwrap_or_else(|e| e.into_inner()).battery.clone();- if let Some(battery) = battery {- let s = session.clone();- tokio::spawn(async move {- if let Ok(env) = Envelope::new(types::EVENT_BATTERY, &battery) {- let _ = s.send(env).await;- }- });- }+ let shared = self.clone();+ let s = session.clone();+ tokio::spawn(async move {+ if let Some(battery) = battery+ && let Ok(env) = Envelope::new(types::EVENT_BATTERY, &battery)+ {+ let _ = s.send(env).await;+ }+ shared.send_notification_snapshot(&s).await;+ });Some(session)}@@ -337,8 +356,7 @@ impl Shared {/// Sends a message to every connected device.async fn broadcast(&self, env: Envelope) {- let sessions: Vec<_> = lock(&self.sessions).values().filter(|s| s.is_alive()).cloned().collect();- for session in sessions {+ for session in self.live_sessions() {if let Err(e) = session.send(env.clone()).await {tracing::debug!(peer = %session.peer.short(), error = %e, "broadcast failed");}@@ -528,6 +546,8 @@ impl Node {matrices: Mutex::new(HashMap::new()),away_mode: config.away_mode,memory,+ notifications: Feed::default(),+ runtime: tokio::runtime::Handle::current(),});if config.lan_discovery {@@ -726,6 +746,72 @@ impl Node {}self.shared.store.set_toggle(&peer, toggle, enabled)?;self.shared.refresh_capabilities(&peer);+ if toggle == notifications::TOGGLE {+ self.notifications_toggled(peer, enabled);+ }+ Ok(())+ }++ /// Brings both sides in line after the user allowed or stopped+ /// notifications for a device.+ fn notifications_toggled(&self, peer: DeviceId, enabled: bool) {+ let shared = &self.shared;+ if shared.notifications.is_active() {+ // This phone: send the PC everything, or clear it.+ if let Some(session) = shared.session(&peer) {+ let task = shared.clone();+ shared.runtime.spawn(async move { task.send_notification_snapshot(&session).await });+ }+ } else if enabled {+ // This PC: ask the phone for what it shows now.+ if let Some(session) = shared.session(&peer) {+ shared.runtime.spawn(async move {+ let _ = session.send(Envelope::empty(types::NOTIFY_SYNC)).await;+ });+ }+ } else {+ shared.emit(NodeEvent::NotificationsReset { device: peer, items: Vec::new() });+ }+ }++ // ---- Notifications (docs/protocol/notifications.md) ----++ /// A notification appeared or changed on this phone; sent to every+ /// connected PC the user allows. Include the app icon (PNG) each time:+ /// the core sends it once per PC and session.+ pub async fn notification_posted(&self, notification: Notification) {+ self.shared.notification_posted(notification).await;+ }++ /// A notification went away on this phone.+ pub async fn notification_removed(&self, key: String) {+ self.shared.notification_removed(key).await;+ }++ /// Everything this phone shows now (when the notification listener+ /// connects, or an empty list when access was revoked).+ pub async fn notifications_reset(&self, items: Vec<Notification>) {+ self.shared.notifications_reset(items).await;+ }++ /// Dismisses a phone's notification there.+ pub async fn dismiss_notification(&self, peer: DeviceId, key: String) -> Result<()> {+ let env = Envelope::new(types::NOTIFY_DISMISS, &NotifyKey { key })?;+ self.request(peer, env).await?.expect(types::OK)?;+ Ok(())+ }++ /// Runs an action of a phone's notification; `reply` is the text for a+ /// reply action.+ pub async fn run_notification_action(+ &self,+ peer: DeviceId,+ key: String,+ action: String,+ reply: Option<String>,+ ) -> Result<()> {+ let env = Envelope::new(types::NOTIFY_ACTION, &NotifyAction { key, action, reply })?;+ self.request(peer, env).await?.expect(types::OK)?;Ok(())}diff --git a/core/nectarlink-core/src/notifications.rs b/core/nectarlink-core/src/notifications.rsnew file mode 100644index 0000000..6be203e--- /dev/null+++ b/core/nectarlink-core/src/notifications.rs@@ -0,0 +1,327 @@+// SPDX-License-Identifier: MPL-2.0+//! Notification mirroring (docs/protocol/notifications.md).+//!+//! On the phone, [`Feed`] holds the notifications currently showing (as the+//! app reports them) and keeps every allowed PC in sync: a snapshot when a+//! session starts or the user changes what that PC may see, then each post+//! and removal. On the PC, incoming events become [`NodeEvent`]s, and the+//! user's dismissals, replies and actions go back as requests.++use std::{+ collections::{HashMap, HashSet},+ sync::{Arc, Mutex},+};++use nectarlink_protocol::{+ DeviceId, Envelope, ErrorCode,+ messages::{Notification, NotifyAction, NotifyKey, NotifySnapshot, notify_limits::SNAPSHOT_ITEMS, types},+};++use crate::{+ Result,+ events::NodeEvent,+ features::{Role, role_of},+ node::Shared,+ session::Session,+};++/// The device toggle that allows notifications for a device.+pub(crate) const TOGGLE: &str = "notifications";++/// A snapshot stays well under the 1 MiB frame limit (v0 §3).+const SNAPSHOT_BUDGET: usize = 768 * 1024;++/// Why the phone couldn't dismiss a notification or run its action.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum NotificationError {+ /// The notification or action no longer exists.+ NotFound,+ /// This device can't do it (e.g. no notification access).+ Unsupported,+ /// Anything else; the string is for logs and never holds content.+ Failed(String),+}++/// The phone's current notifications, plus app icons for sending once per+/// session.+#[derive(Default)]+pub(crate) struct Feed {+ inner: Mutex<FeedState>,+}++#[derive(Default)]+struct FeedState {+ /// Set once the app reports notifications: only a device that mirrors+ /// its notifications sends snapshots.+ active: bool,+ items: HashMap<String, Notification>,+ icons: HashMap<String, Vec<u8>>,+}++impl Feed {+ fn lock(&self) -> std::sync::MutexGuard<'_, FeedState> {+ self.inner.lock().unwrap_or_else(|e| e.into_inner())+ }++ pub fn is_active(&self) -> bool {+ self.lock().active+ }++ /// Stores a notification (its icon separately); returns it without the+ /// icon, sanitized, or `None` if it can't be shown.+ fn post(&self, notification: Notification) -> Option<Notification> {+ let mut n = notification.sanitized()?;+ let mut state = self.lock();+ state.active = true;+ if let Some(icon) = n.icon.take() {+ state.icons.insert(n.app.clone(), icon);+ }+ state.items.insert(n.key.clone(), n.clone());+ Some(n)+ }++ fn remove(&self, key: &str) -> bool {+ let mut state = self.lock();+ state.active = true;+ state.items.remove(key).is_some()+ }++ fn reset(&self, items: Vec<Notification>) {+ let mut state = self.lock();+ state.active = true;+ state.items.clear();+ for n in items.into_iter().filter_map(Notification::sanitized) {+ let mut n = n;+ if let Some(icon) = n.icon.take() {+ state.icons.insert(n.app.clone(), icon);+ }+ state.items.insert(n.key.clone(), n);+ }+ }++ /// The newest notifications that fit a frame, each app's icon attached+ /// once unless `session` already got it.+ fn snapshot(&self, session: &Session) -> NotifySnapshot {+ let state = self.lock();+ let mut items: Vec<&Notification> = state.items.values().collect();+ items.sort_by(|a, b| b.when.cmp(&a.when).then_with(|| a.key.cmp(&b.key)));+ let mut sent = session.sent_icons();+ let mut budget = SNAPSHOT_BUDGET;+ let mut out = Vec::new();+ for n in items.into_iter().take(SNAPSHOT_ITEMS) {+ let size = approx_size(n);+ if size > budget {+ break;+ }+ budget -= size;+ let mut n = n.clone();+ if !sent.contains(&n.app)+ && let Some(icon) = state.icons.get(&n.app)+ && icon.len() <= budget+ {+ budget -= icon.len();+ sent.insert(n.app.clone());+ n.icon = Some(icon.clone());+ }+ out.push(n);+ }+ NotifySnapshot { items: out }+ }++ /// `n` with its app icon attached if `session` hasn't had it yet.+ fn for_session(&self, n: &Notification, session: &Session) -> Notification {+ let mut n = n.clone();+ // Same lock order as `snapshot`: the feed, then the session.+ let icon = self.lock().icons.get(&n.app).cloned();+ if let Some(icon) = icon+ && session.sent_icons().insert(n.app.clone())+ {+ n.icon = Some(icon);+ }+ n+ }+}++/// Encoded size, roughly (text plus a little CBOR overhead per field).+fn approx_size(n: &Notification) -> usize {+ let text = [&n.title, &n.text, &n.sub].iter().map(|s| s.as_ref().map_or(0, String::len)).sum::<usize>();+ let actions = n.actions.iter().map(|a| a.id.len() + a.title.len() + 16).sum::<usize>();+ n.key.len() + n.app.len() + n.app_name.len() + text + actions + 64+}++impl Shared {+ /// Whether the user allows notifications for `peer` on this device.+ pub(crate) fn notifications_allowed(&self, peer: &DeviceId) -> bool {+ self.store+ .toggles(peer)+ .ok()+ .and_then(|t| t.get(TOGGLE).copied())+ .or_else(|| crate::features::toggle_default(TOGGLE))+ .unwrap_or(false)+ }++ /// Sessions that should get this phone's notifications: connected PCs+ /// the user allows.+ fn notification_targets(&self) -> Vec<Arc<Session>> {+ self.live_sessions()+ .into_iter()+ .filter(|s| self.is_desktop(&s.peer) && self.notifications_allowed(&s.peer))+ .collect()+ }++ fn is_desktop(&self, peer: &DeviceId) -> bool {+ self.store.get_peer(peer).ok().flatten().is_some_and(|p| role_of(&p.info) == Some(Role::Desktop))+ }++ /// Sends this phone's notifications to one PC: everything when the+ /// user allows it, an empty list (which clears the PC) when not.+ pub(crate) async fn send_notification_snapshot(&self, session: &Arc<Session>) {+ if !self.notifications.is_active() || !self.is_desktop(&session.peer) {+ return;+ }+ let snapshot = if self.notifications_allowed(&session.peer) {+ self.notifications.snapshot(session)+ } else {+ NotifySnapshot { items: Vec::new() }+ };+ if let Ok(env) = Envelope::new(types::NOTIFY_SNAPSHOT, &snapshot) {+ let _ = session.send(env).await;+ }+ }++ pub(crate) async fn notification_posted(&self, notification: Notification) {+ let Some(n) = self.notifications.post(notification) else { return };+ for session in self.notification_targets() {+ if let Ok(env) =+ Envelope::new(types::NOTIFY_POSTED, &self.notifications.for_session(&n, &session))+ {+ let _ = session.send(env).await;+ }+ }+ }++ pub(crate) async fn notification_removed(&self, key: String) {+ if !self.notifications.remove(&key) {+ return;+ }+ let Ok(env) = Envelope::new(types::NOTIFY_REMOVED, &NotifyKey { key }) else { return };+ for session in self.notification_targets() {+ let _ = session.send(env.clone()).await;+ }+ }++ pub(crate) async fn notifications_reset(&self, items: Vec<Notification>) {+ self.notifications.reset(items);+ for session in self.live_sessions() {+ self.send_notification_snapshot(&session).await;+ }+ }+}++/// Handles a `notify.*` message on a session. Returns false for other types.+pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Envelope) -> Result<bool> {+ let peer = session.peer;+ match env.t.as_str() {+ // ---- On the PC ----+ types::NOTIFY_SNAPSHOT => {+ if shared.notifications_allowed(&peer) {+ let snapshot: NotifySnapshot = env.body()?;+ let items = snapshot+ .items+ .into_iter()+ .filter_map(Notification::sanitized)+ .take(SNAPSHOT_ITEMS)+ .collect();+ shared.emit(NodeEvent::NotificationsReset { device: peer, items });+ }+ }+ types::NOTIFY_POSTED => {+ if shared.notifications_allowed(&peer)+ && let Some(notification) = env.body::<Notification>()?.sanitized()+ {+ shared.emit(NodeEvent::NotificationPosted { device: peer, notification });+ }+ }+ types::NOTIFY_REMOVED => {+ let NotifyKey { key } = env.body()?;+ shared.emit(NodeEvent::NotificationRemoved { device: peer, key });+ }+ // ---- On the phone ----+ types::NOTIFY_SYNC => shared.send_notification_snapshot(session).await,+ types::NOTIFY_DISMISS => {+ let NotifyKey { key } = env.body()?;+ let reply = match allowed(shared, &peer) {+ Err(reply) => reply,+ Ok(()) => {+ let platform = shared.platform.clone();+ match run_blocking(move || platform.dismiss_notification(&key)).await {+ // Already gone is what the PC wanted.+ Ok(()) | Err(NotificationError::NotFound) => Envelope::empty(types::OK),+ Err(e) => error_reply(e),+ }+ }+ };+ session.send(reply.reply_to(env.id)).await?;+ }+ types::NOTIFY_ACTION => {+ let NotifyAction { key, action, reply } = env.body()?;+ let reply = reply.map(|mut text| {+ if let Some((cut, _)) =+ text.char_indices().nth(nectarlink_protocol::messages::notify_limits::TEXT_CHARS)+ {+ text.truncate(cut);+ }+ text+ });+ let answer = match allowed(shared, &peer) {+ Err(answer) => answer,+ Ok(()) => {+ let platform = shared.platform.clone();+ match run_blocking(move || {+ platform.run_notification_action(&key, &action, reply.as_deref())+ })+ .await+ {+ Ok(()) => Envelope::empty(types::OK),+ Err(e) => error_reply(e),+ }+ }+ };+ session.send(answer.reply_to(env.id)).await?;+ }+ _ => return Ok(false),+ }+ Ok(true)+}++/// Whether a PC may act on this phone's notifications; the error reply if not.+fn allowed(shared: &Shared, peer: &DeviceId) -> std::result::Result<(), Envelope> {+ if !shared.local_capabilities().iter().any(|c| c == "notify.reply") {+ return Err(Envelope::error(ErrorCode::Unsupported, "notification actions are not available"));+ }+ if !shared.notifications_allowed(peer) {+ return Err(Envelope::error(ErrorCode::Denied, "notifications are off for this device"));+ }+ Ok(())+}++fn error_reply(e: NotificationError) -> Envelope {+ match e {+ NotificationError::NotFound => Envelope::error(ErrorCode::NotFound, "no longer exists"),+ NotificationError::Unsupported => Envelope::error(ErrorCode::Unsupported, "not available"),+ NotificationError::Failed(reason) => {+ tracing::warn!(reason, "notification action failed");+ Envelope::error(ErrorCode::Internal, "failed")+ }+ }+}++/// Platform calls may touch the OS; keep them off the async workers.+async fn run_blocking(+ f: impl FnOnce() -> std::result::Result<(), NotificationError> + Send + 'static,+) -> std::result::Result<(), NotificationError> {+ tokio::task::spawn_blocking(f).await.unwrap_or_else(|e| Err(NotificationError::Failed(e.to_string())))+}++/// Per-session record of which apps' icons were sent.+pub(crate) type SentIcons = Mutex<HashSet<String>>;diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rsindex 713aec0..94aae59 100644--- a/core/nectarlink-core/src/session.rs+++ b/core/nectarlink-core/src/session.rs@@ -112,6 +112,8 @@ pub(crate) struct Session {pending: Mutex<HashMap<u64, oneshot::Sender<Envelope>>>,next_id: AtomicU64,rtt_ms: AtomicU32,+ /// Apps whose notification icon this peer already got.+ sent_icons: crate::notifications::SentIcons,pub(crate) cancel: CancellationToken,}@@ -151,6 +153,7 @@ impl Session {pending: Mutex::new(HashMap::new()),next_id: AtomicU64::new(1),rtt_ms: AtomicU32::new(initial_rtt),+ sent_icons: Default::default(),cancel: shared.cancel.child_token(),});@@ -196,6 +199,10 @@ impl Session {.collect()}+ pub(crate) fn sent_icons(&self) -> std::sync::MutexGuard<'_, std::collections::HashSet<String>> {+ self.sent_icons.lock().unwrap_or_else(|e| e.into_inner())+ }+pub fn is_alive(&self) -> bool {!self.cancel.is_cancelled() && self.conn.close_reason().is_none()}@@ -330,6 +337,7 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->tracing::info!(peer = %peer.short(), "peer unpaired this device");shared.forget_peer(&peer).await?;}+ t if t.starts_with("notify.") && crate::notifications::handle(shared, session, &env).await? => {}other => {if env.id.is_some() {let reply = Envelope::error(ErrorCode::Unsupported, format!("unknown message type {other}"));diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rsindex 68cd5ae..539d6d1 100644--- a/core/nectarlink-core/tests/two_devices.rs+++ b/core/nectarlink-core/tests/two_devices.rs@@ -10,7 +10,8 @@ use std::{use nectarlink_core::{Battery, DeviceInfo, DeviceKind, Error, FeatureState, LinkState, Node, NodeConfig, NodeEvent,- PairingEvent, PairingFailure, PairingUri, PlainKeyProtector, Platform, PowerLevel,+ Notification, NotificationAction, NotificationError, PairingEvent, PairingFailure, PairingUri,+ PlainKeyProtector, Platform, PowerLevel,features::{Effort, Upgrade, UpgradeAction},};use tempfile::TempDir;@@ -21,6 +22,8 @@ const WAIT: Duration = Duration::from_secs(20);#[derive(Debug, Default)]struct RecordingPlatform {rings: Mutex<Vec<bool>>,+ dismissed: Mutex<Vec<String>>,+ actions: Mutex<Vec<(String, String, Option<String>)>>,}impl Platform for RecordingPlatform {@@ -30,6 +33,22 @@ impl Platform for RecordingPlatform {fn stop_ringing(&self) {self.rings.lock().unwrap().push(false);}+ fn dismiss_notification(&self, key: &str) -> Result<(), NotificationError> {+ self.dismissed.lock().unwrap().push(key.to_owned());+ Ok(())+ }+ fn run_notification_action(+ &self,+ key: &str,+ action: &str,+ reply: Option<&str>,+ ) -> Result<(), NotificationError> {+ if key == "gone" {+ return Err(NotificationError::NotFound);+ }+ self.actions.lock().unwrap().push((key.to_owned(), action.to_owned(), reply.map(str::to_owned)));+ Ok(())+ }}struct TestDevice {@@ -398,3 +417,117 @@ async fn capabilities_follow_power_and_toggles() {let matrix = pc.node.capabilities(phone_id).unwrap();assert_eq!(matrix.state("clipboard.auto_phone_to_pc"), Some(FeatureState::Available));}++fn note(key: &str, app: &str, title: &str, icon: bool) -> Notification {+ Notification {+ key: key.into(),+ app: app.into(),+ app_name: "Chat".into(),+ title: Some(title.into()),+ text: Some("Are you coming?".into()),+ sub: None,+ when: 1_760_000_000_000,+ actions: vec![+ NotificationAction { id: "0".into(), title: "Reply".into(), reply: true },+ NotificationAction { id: "1".into(), title: "Mark as read".into(), reply: false },+ ],+ silent: false,+ icon: icon.then(|| vec![0x89, b'P', b'N', b'G', 1, 2, 3]),+ }+}++/// A phone that mirrors notifications (notification access granted).+async fn grant_notification_access(phone: &TestDevice) {+ phone.node.update_power(PowerLevel::Basic, vec!["notify.mirror".into(), "notify.reply".into()]).await;+}++#[tokio::test(flavor = "multi_thread")]+async fn notifications_mirror_to_the_pc_and_actions_reach_the_phone() {+ let mut pc = device("Desktop", DeviceKind::Desktop).await;+ let mut phone = device("Pixel", DeviceKind::Phone).await;+ pair_qr(&mut pc, &mut phone).await;+ let phone_id = phone.node.device_id();+ grant_notification_access(&phone).await;++ // The listener connects: everything showing goes over as a snapshot,+ // with each app's icon once.+ phone+ .node+ .notifications_reset(vec![note("a", "com.chat", "Sam", true), note("b", "com.chat", "Alex", true)])+ .await;+ let items = wait_for(&mut pc, "snapshot", |e| match e {+ NodeEvent::NotificationsReset { device, items } if *device == phone_id => Some(items.clone()),+ _ => None,+ })+ .await;+ assert_eq!(items.len(), 2);+ assert_eq!(items.iter().filter(|n| n.icon.is_some()).count(), 1, "one icon per app and session");++ // A new one: the PC already has this app's icon.+ phone.node.notification_posted(note("c", "com.chat", "Kim", true)).await;+ let posted = wait_for(&mut pc, "posted", |e| match e {+ NodeEvent::NotificationPosted { device, notification } if *device == phone_id => {+ Some(notification.clone())+ }+ _ => None,+ })+ .await;+ assert_eq!(posted.key, "c");+ assert_eq!(posted.title.as_deref(), Some("Kim"));+ assert_eq!(posted.icon, None);++ phone.node.notification_removed("a".into()).await;+ let removed = wait_for(&mut pc, "removed", |e| match e {+ NodeEvent::NotificationRemoved { device, key } if *device == phone_id => Some(key.clone()),+ _ => None,+ })+ .await;+ assert_eq!(removed, "a");++ // The PC dismisses one and replies to another.+ with_timeout("dismiss", pc.node.dismiss_notification(phone_id, "b".into())).await.expect("dismissed");+ with_timeout(+ "reply",+ pc.node.run_notification_action(phone_id, "c".into(), "0".into(), Some("Yes!".into())),+ )+ .await+ .expect("replied");+ assert_eq!(*phone.platform.dismissed.lock().unwrap(), vec!["b".to_owned()]);+ assert_eq!(*phone.platform.actions.lock().unwrap(), vec![("c".into(), "0".into(), Some("Yes!".into()))]);++ let gone =+ with_timeout("gone", pc.node.run_notification_action(phone_id, "gone".into(), "1".into(), None))+ .await;+ assert!(matches!(gone, Err(Error::NotFound)), "{gone:?}");+}++#[tokio::test(flavor = "multi_thread")]+async fn notification_toggles_are_honored_on_both_devices() {+ let mut pc = device("Desktop", DeviceKind::Desktop).await;+ let mut phone = device("Pixel", DeviceKind::Phone).await;+ pair_qr(&mut pc, &mut phone).await;+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());+ grant_notification_access(&phone).await;+ phone.node.notifications_reset(vec![note("a", "com.chat", "Sam", false)]).await;+ let snapshot = |e: &NodeEvent| match e {+ NodeEvent::NotificationsReset { device, items } if *device == phone_id => Some(items.len()),+ _ => None,+ };+ assert_eq!(wait_for(&mut pc, "first snapshot", snapshot).await, 1);++ // The phone stops sharing with this PC: the PC is cleared, and actions+ // from it are refused.+ phone.node.set_device_toggle(pc_id, "notifications", false).unwrap();+ assert_eq!(wait_for(&mut pc, "cleared by the phone", snapshot).await, 0);+ let denied = with_timeout("denied", pc.node.dismiss_notification(phone_id, "a".into())).await;+ assert!(matches!(denied, Err(Error::Denied)), "{denied:?}");+ phone.node.set_device_toggle(pc_id, "notifications", true).unwrap();+ assert_eq!(wait_for(&mut pc, "shared again", snapshot).await, 1);++ // The PC hides this phone's notifications, then shows them again: it+ // asks the phone for what's showing.+ pc.node.set_device_toggle(phone_id, "notifications", false).unwrap();+ assert_eq!(wait_for(&mut pc, "hidden on the PC", snapshot).await, 0);+ pc.node.set_device_toggle(phone_id, "notifications", true).unwrap();+ assert_eq!(wait_for(&mut pc, "synced again", snapshot).await, 1);+}diff --git a/core/nectarlink-protocol/src/error.rs b/core/nectarlink-protocol/src/error.rsindex 120f902..1a41194 100644--- a/core/nectarlink-protocol/src/error.rs+++ b/core/nectarlink-protocol/src/error.rs@@ -14,6 +14,8 @@ pub enum ErrorCode {Denied,Busy,Internal,+ /// The thing the request names no longer exists.+ NotFound,/// A code this implementation doesn't know yet (forward compatibility).Other(String),}@@ -29,6 +31,7 @@ impl ErrorCode {ErrorCode::Denied => "DENIED",ErrorCode::Busy => "BUSY",ErrorCode::Internal => "INTERNAL",+ ErrorCode::NotFound => "NOT_FOUND",ErrorCode::Other(code) => code,}}@@ -43,6 +46,7 @@ impl ErrorCode {ErrorCode::BadMessage => 5,ErrorCode::Denied => 6,ErrorCode::Busy => 7,+ ErrorCode::NotFound => 9,ErrorCode::Internal | ErrorCode::Other(_) => 8,}}@@ -67,6 +71,7 @@ impl FromStr for ErrorCode {"DENIED" => ErrorCode::Denied,"BUSY" => ErrorCode::Busy,"INTERNAL" => ErrorCode::Internal,+ "NOT_FOUND" => ErrorCode::NotFound,other => ErrorCode::Other(other.to_owned()),})}@@ -124,7 +129,7 @@ mod tests {#[test]fn codes_round_trip_and_tolerate_unknown_values() {- for code in ["UNSUPPORTED", "UNPAIRED", "DENIED", "VERSION_TOO_OLD"] {+ for code in ["UNSUPPORTED", "UNPAIRED", "DENIED", "VERSION_TOO_OLD", "NOT_FOUND"] {assert_eq!(code.parse::<ErrorCode>().unwrap().as_str(), code);}assert_eq!("FUTURE_CODE".parse::<ErrorCode>().unwrap(), ErrorCode::Other("FUTURE_CODE".into()));diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsindex 941fb95..fc4a979 100644--- a/core/nectarlink-protocol/src/messages.rs+++ b/core/nectarlink-protocol/src/messages.rs@@ -26,6 +26,13 @@ pub mod types {pub const PAIR_CONFIRM: &str = "pair.confirm";pub const PAIR_DONE: &str = "pair.done";pub const PAIR_REVOKE: &str = "pair.revoke";++ pub const NOTIFY_SNAPSHOT: &str = "notify.snapshot";+ pub const NOTIFY_POSTED: &str = "notify.posted";+ pub const NOTIFY_REMOVED: &str = "notify.removed";+ pub const NOTIFY_SYNC: &str = "notify.sync";+ pub const NOTIFY_DISMISS: &str = "notify.dismiss";+ pub const NOTIFY_ACTION: &str = "notify.action";}/// What kind of device this is.@@ -174,6 +181,140 @@ pub struct PairReveal {pub n_a: Vec<u8>,}+// ---- Notifications (docs/protocol/notifications.md) ----++/// Size limits from the notifications spec (§2); senders and receivers both+/// enforce them with [`Notification::sanitized`].+pub mod notify_limits {+ pub const KEY_BYTES: usize = 256;+ pub const ACTION_ID_BYTES: usize = 64;+ pub const TITLE_CHARS: usize = 256;+ pub const TEXT_CHARS: usize = 4096;+ pub const ACTION_TITLE_CHARS: usize = 64;+ pub const ACTIONS: usize = 5;+ pub const ICON_BYTES: usize = 64 * 1024;+ pub const SNAPSHOT_ITEMS: usize = 100;+}++/// A button on a notification.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct NotificationAction {+ /// Opaque to the PC.+ pub id: String,+ pub title: String,+ /// Takes text: shown as an inline reply field.+ #[serde(default)]+ pub reply: bool,+}++/// A phone notification, as mirrored to a PC.+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Notification {+ /// The phone's ID for it.+ pub key: String,+ /// Package name, e.g. "com.whatsapp".+ pub app: String,+ /// User-visible app name.+ pub app_name: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub title: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub text: Option<String>,+ /// Secondary line, e.g. a conversation or account name.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub sub: Option<String>,+ /// When it was posted, Unix milliseconds.+ pub when: i64,+ #[serde(default)]+ pub actions: Vec<NotificationAction>,+ /// Arrived without sound or pop-up on the phone.+ #[serde(default)]+ pub silent: bool,+ /// The app's icon (PNG), sent with an app's first notification per+ /// session.+ #[serde(default, skip_serializing_if = "Option::is_none", with = "serde_bytes")]+ pub icon: Option<Vec<u8>>,+}++/// Never prints content: notification text must not reach logs (protocol+/// v0 §11).+impl std::fmt::Debug for Notification {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Notification")+ .field("app", &self.app)+ .field("actions", &self.actions.len())+ .field("silent", &self.silent)+ .finish_non_exhaustive()+ }+}++fn truncate_chars(s: &mut String, max: usize) {+ if let Some((cut, _)) = s.char_indices().nth(max) {+ s.truncate(cut);+ }+}++fn clean_text(s: Option<String>, max: usize) -> Option<String> {+ let mut s = s?.trim().to_owned();+ truncate_chars(&mut s, max);+ (!s.is_empty()).then_some(s)+}++impl Notification {+ /// Applies the spec's limits: truncates text, drops extra actions,+ /// oversized icons and malformed actions. `None` if the notification+ /// can't be shown at all (no key, or neither a title nor a text).+ pub fn sanitized(mut self) -> Option<Notification> {+ use notify_limits::*;+ if self.key.is_empty() || self.key.len() > KEY_BYTES {+ return None;+ }+ self.title = clean_text(self.title, TITLE_CHARS);+ self.text = clean_text(self.text, TEXT_CHARS);+ self.sub = clean_text(self.sub, TITLE_CHARS);+ if self.title.is_none() && self.text.is_none() {+ return None;+ }+ truncate_chars(&mut self.app, TITLE_CHARS);+ truncate_chars(&mut self.app_name, TITLE_CHARS);+ self.actions.retain_mut(|a| {+ truncate_chars(&mut a.title, ACTION_TITLE_CHARS);+ !a.id.is_empty() && a.id.len() <= ACTION_ID_BYTES && !a.title.trim().is_empty()+ });+ self.actions.truncate(ACTIONS);+ if self.icon.as_ref().is_some_and(|i| i.is_empty() || i.len() > ICON_BYTES) {+ self.icon = None;+ }+ Some(self)+ }+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct NotifySnapshot {+ pub items: Vec<Notification>,+}++/// Body of `notify.removed` and `notify.dismiss`.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct NotifyKey {+ pub key: String,+}++/// Body of `notify.action`.+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct NotifyAction {+ pub key: String,+ pub action: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reply: Option<String>,+}++impl std::fmt::Debug for NotifyAction {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("NotifyAction").field("action", &self.action).finish_non_exhaustive()+ }+}+/// A paired device identity as stored in trust stores and exchanged in tests.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct PeerIdentity {@@ -230,6 +371,71 @@ mod tests {assert_eq!(parsed.power.effective(), PowerLevel::Basic);}+ fn notification() -> Notification {+ Notification {+ key: "0|com.example|1|null|10123".into(),+ app: "com.example".into(),+ app_name: "Example".into(),+ title: Some("Sam".into()),+ text: Some("Lunch?".into()),+ sub: None,+ when: 1_760_000_000_000,+ actions: vec![NotificationAction { id: "0".into(), title: "Reply".into(), reply: true }],+ silent: false,+ icon: Some(vec![0x89, b'P', b'N', b'G']),+ }+ }++ #[test]+ fn notifications_round_trip_with_binary_icons() {+ let n = notification();+ let env = Envelope::new(types::NOTIFY_POSTED, &n).unwrap();+ // The icon travels as a CBOR byte string, not an array of numbers.+ let icon = match &env.b {+ Some(ciborium::Value::Map(fields)) => fields.iter().find(|(k, _)| k.as_text() == Some("icon")),+ _ => None,+ };+ assert!(matches!(icon, Some((_, ciborium::Value::Bytes(_)))));+ let back: Notification = Envelope::from_cbor(&env.to_cbor()).unwrap().body().unwrap();+ assert_eq!(back, n);+ }++ #[test]+ fn sanitizing_enforces_the_limits() {+ let mut n = notification();+ n.title = Some("é".repeat(300));+ n.text = Some(" ".into());+ n.actions = (0..8)+ .map(|i| NotificationAction { id: i.to_string(), title: "Go".into(), reply: false })+ .collect();+ n.actions.push(NotificationAction { id: String::new(), title: "No id".into(), reply: false });+ n.icon = Some(vec![0; notify_limits::ICON_BYTES + 1]);+ let n = n.sanitized().unwrap();+ assert_eq!(n.title.unwrap().chars().count(), notify_limits::TITLE_CHARS);+ assert_eq!(n.text, None, "blank text is dropped");+ assert_eq!(n.actions.len(), notify_limits::ACTIONS);+ assert_eq!(n.icon, None);+ }++ #[test]+ fn notifications_without_content_or_key_are_dropped() {+ let mut n = notification();+ n.title = None;+ n.text = Some(" ".into());+ assert_eq!(n.sanitized(), None);+ let mut n = notification();+ n.key = String::new();+ assert_eq!(n.sanitized(), None);+ }++ #[test]+ fn debug_output_hides_content() {+ let shown = format!("{:?}", notification());+ assert!(!shown.contains("Lunch") && !shown.contains("Sam"), "{shown}");+ let action = NotifyAction { key: "k".into(), action: "0".into(), reply: Some("secret".into()) };+ assert!(!format!("{action:?}").contains("secret"));+ }+#[test]fn power_level_wire_names() {let env = Envelope::new("x", &PowerLevel::NotApplicable).unwrap();diff --git a/docs/protocol/notifications.md b/docs/protocol/notifications.mdnew file mode 100644index 0000000..d70acf5--- /dev/null+++ b/docs/protocol/notifications.md@@ -0,0 +1,107 @@+# Notifications service (protocol v0)++> Status: **draft.** Builds on [protocol v0](v0.md); breaking changes are+> allowed until v1. License: CC BY 4.0.++A phone mirrors its notifications to paired PCs, which show them (as toasts+and in a feed) and can dismiss them, reply to them and run their actions.++All messages travel on the **control stream** (v0 §4). Notifications are+small, latency matters more than throughput, and their order must be kept:+a `notify.removed` must never overtake the `notify.posted` it removes.++## 1. Capabilities++| ID | Offered by | Meaning |+|---|---|---|+| `notify.mirror` | phone | Sends `notify.*` events. Offered once the user granted notification access |+| `notify.reply` | phone | Handles `notify.dismiss` and `notify.action` |+| `notify.sensitive` | phone | Includes notifications Android hides from apps as sensitive (one-time codes) |++A PC that doesn't offer anything still receives these events; a peer that+doesn't know them ignores them (v0 §3.1).++## 2. The notification++```+Notification = {+ key: text, // The phone's ID for it (Android: StatusBarNotification key), 1–256 bytes+ app: text, // Package name, e.g. "com.whatsapp"+ app_name: text, // User-visible app name, e.g. "WhatsApp"+ title: text?, // e.g. the sender+ text: text?, // The body, expanded if the app provides more+ sub: text?, // Secondary line, e.g. a conversation or account name+ when: int, // When it was posted, Unix milliseconds+ actions: [Action], // In display order, at most 5+ silent: bool, // Arrived without sound or pop-up on the phone; don't alert either+ icon: bytes?, // The app's icon, PNG, at most 64 KiB (see §2.1)+}++Action = {+ id: text, // Opaque to the PC, 1–64 bytes+ title: text, // Button label, e.g. "Mark as read"+ reply: bool, // Takes text (an inline reply field)+}+```++Text fields are plain text. Senders **MUST** truncate `title` and `sub` to 256+characters, `text` to 4,096 and action titles to 64; receivers **MUST**+enforce the same limits. A notification with neither `title` nor `text` is+not sent.++### 2.1 App icons++The icon of an app is sent with the **first** notification of that app in a+session (in `notify.posted` or `notify.snapshot`) and omitted afterwards.+Receivers keep the icons they got for the session's lifetime and may cache+them longer, keyed by package name.++## 3. Events (phone → PC)++```+t = "notify.snapshot" b = { items: [Notification] }+t = "notify.posted" b = Notification+t = "notify.removed" b = { key: text }+```++- **`notify.snapshot`** replaces everything the PC holds for this phone. The+ phone sends it right after a session is established, when the user turns+ notifications for that PC on or off (an empty list when off), and when its+ notification listener (re)connects. Items are newest first, at most 100.+ The PC **MUST NOT** alert for snapshot items.+- **`notify.posted`** adds a notification, or replaces the one with the same+ `key` (an update, such as a new message in the same conversation). The PC+ alerts unless `silent` is set.+- **`notify.removed`** removes it: the user or the app dismissed it on the+ phone. The PC removes its toast too.++## 4. Requests (PC → phone)++```+t = "notify.sync" // one-way+t = "notify.dismiss" id = n b = { key: text }+t = "notify.action" id = n b = { key: text, action: text, reply: text? }+t = "ok" re = n+```++- **`notify.sync`** asks for a fresh `notify.snapshot`, for example after the+ user turned notifications from this phone back on. A phone that doesn't+ mirror notifications ignores it.+- **`notify.dismiss`** dismisses the notification on the phone. Dismissing+ one that's already gone succeeds.+- **`notify.action`** runs an action. For a reply action, `reply` holds the+ text (at most 4,096 characters). The phone answers `ok` once the action ran,+ without waiting for its effect (the message being delivered, for example).++Errors: `DENIED` when the user turned notifications off for this PC,+`NOT_FOUND` when the notification or action no longer exists, `UNSUPPORTED`+when the phone doesn't offer `notify.reply`.++## 5. Privacy++- Notifications are sent only to PCs the user allows (the `notifications`+ device toggle on the phone) and shown only from phones the user allows (the+ same toggle on the PC).+- Apps that mark a notification as local-only (Android `FLAG_LOCAL_ONLY`) are+ respected: such notifications are never sent.+- Implementations **MUST NOT** log notification content (v0 §11).diff --git a/docs/protocol/v0.md b/docs/protocol/v0.mdindex d269b6f..e89a9ca 100644--- a/docs/protocol/v0.md+++ b/docs/protocol/v0.md@@ -6,9 +6,9 @@This document specifies how two Nectarlink devices find each other, pair,connect and exchange messages. Version 0 covers the Phase 0 scope: identity,pairing, the session handshake, capabilities, heartbeat and the first events-(device info, battery, ping). Feature services (notifications, files,-clipboard, mirroring…) are specified in separate documents that build on this-one.+(device info, battery, ping). Feature services are specified in separate+documents that build on this one: [notifications](notifications.md) so far;+files, clipboard and mirroring follow.Key words **MUST**, **SHOULD** and **MAY** are used as in RFC 2119.@@ -220,6 +220,7 @@ t = "error" re = n? b = { code: text, msg: text? }| `DENIED` | The user or a per-device permission denied the operation || `BUSY` | Temporarily unable; retry later || `INTERNAL` | Unexpected failure on the receiver |+| `NOT_FOUND` | The thing the request names no longer exists (e.g. a dismissed notification) |## 9. Pairing (`nectarlink-pair/0`)