Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

Phone and tablet pairing: the core's part

Bee6a0bf1850b40
diff --git a/core/nectarlink-core/src/features.rs b/core/nectarlink-core/src/features.rs
index 624aa4f..f7a9e9b 100644
--- a/core/nectarlink-core/src/features.rs
+++ b/core/nectarlink-core/src/features.rs
@@ -74,6 +74,11 @@ pub enum Unlock {
pub enum Requirement {
/// The device in `role` announces capability `id` (protocol §6).
Cap { role: Role, id: &'static str, unlock: Unlock },
+ /// The other device of the pair announces capability `id` (for pairs of
+ /// Android devices, where both are phones).
+ Peer { id: &'static str, unlock: Unlock },
+ /// This device announces capability `id`.
+ Here { id: &'static str, unlock: Unlock },
/// The phone runs at this power level or higher.
PowerAtLeast(PowerLevel),
/// The phone runs this Android release or newer.
@@ -375,32 +380,52 @@ pub struct MatrixInputs<'a> {
pub toggles: &'a HashMap<String, bool>,
}
-/// Computes the state of every feature in [`FEATURES`] for one pair.
+/// Computes the state of every feature in [`FEATURES`] and
+/// [`ANDROID_PAIR_FEATURES`] for one pair: the first for a phone (or
+/// tablet) and a PC, the second for two Android devices; the other list is
+/// Unsupported for the pair.
pub fn compute(device: DeviceId, inputs: MatrixInputs<'_>) -> CapabilityMatrix {
- let pair = match (inputs.local.role(), inputs.peer.role()) {
- (Some(Role::Phone), Some(Role::Desktop)) => Some((inputs.local, inputs.peer)),
- (Some(Role::Desktop), Some(Role::Phone)) => Some((inputs.peer, inputs.local)),
+ let (local, peer) = (inputs.local, inputs.peer);
+ let pc_pair = match (local.role(), peer.role()) {
+ (Some(Role::Phone), Some(Role::Desktop)) => Some((local, peer)),
+ (Some(Role::Desktop), Some(Role::Phone)) => Some((peer, local)),
_ => None,
};
- let features = FEATURES
- .iter()
- .map(|def| {
- let state = match pair {
- Some((phone, desktop)) => {
- let ctx = Context { phone, desktop, paths: inputs.paths, toggles: inputs.toggles };
- evaluate(def, &ctx)
- }
- None => FeatureState::Unsupported { reason: UnsupportedReason::DeviceKinds },
- };
- (def.id, state)
- })
- .collect();
+ let android_pair = local.os == "android" && peer.os == "android";
+ let run = |list: &'static [FeatureDef], applies: Option<(&DeviceFacts, &DeviceFacts)>| {
+ list.iter()
+ .map(|def| {
+ let state = match applies {
+ Some((phone, desktop)) => {
+ let ctx = Context {
+ phone,
+ desktop,
+ local,
+ peer,
+ paths: inputs.paths,
+ toggles: inputs.toggles,
+ };
+ evaluate(def, &ctx)
+ }
+ None => FeatureState::Unsupported { reason: UnsupportedReason::DeviceKinds },
+ };
+ (def.id, state)
+ })
+ .collect::<Vec<_>>()
+ };
+ // In a pair of Android devices, "phone" requirements are about the
+ // other device (and its Android version).
+ let mut features = run(FEATURES, pc_pair);
+ features.extend(run(ANDROID_PAIR_FEATURES, android_pair.then_some((peer, local))));
+ let features = features.into_iter().collect();
CapabilityMatrix { device, features }
}
struct Context<'a> {
phone: &'a DeviceFacts,
desktop: &'a DeviceFacts,
+ local: &'a DeviceFacts,
+ peer: &'a DeviceFacts,
paths: &'a [ConnectionPath],
toggles: &'a HashMap<String, bool>,
}
@@ -441,6 +466,20 @@ fn check(req: &Requirement, ctx: &Context<'_>) -> Check {
Unlock::UpdateApp => Check::Unlockable(Upgrade::new(UpgradeAction::UpdateApp(role))),
}
}
+ Requirement::Peer { id, unlock } | Requirement::Here { id, unlock } => {
+ let facts = if matches!(req, Requirement::Peer { .. }) { ctx.peer } else { ctx.local };
+ if facts.caps.contains(id) {
+ return Check::Met;
+ }
+ let role = facts.role().unwrap_or(Role::Phone);
+ match unlock {
+ Unlock::Permission(p) => Check::Unlockable(Upgrade::new(UpgradeAction::GrantPermission(p))),
+ Unlock::Addon(addon) => Check::Unlockable(Upgrade::new(UpgradeAction::EnableAddon(addon))),
+ Unlock::Power(_) | Unlock::UpdateApp => {
+ Check::Unlockable(Upgrade::new(UpgradeAction::UpdateApp(role)))
+ }
+ }
+ }
Requirement::PowerAtLeast(level) => {
if power_rank(ctx.phone.power) >= power_rank(level) {
Check::Met
@@ -543,6 +582,63 @@ const fn desktop(id: &'static str, unlock: Unlock) -> Requirement {
}
const ELEVATED: Unlock = Unlock::Power(PowerLevel::Elevated);
+
+const fn peer(id: &'static str) -> Requirement {
+ Requirement::Peer { id, unlock: Unlock::UpdateApp }
+}
+
+const fn here(id: &'static str) -> Requirement {
+ Requirement::Here { id, unlock: Unlock::UpdateApp }
+}
+
+/// What a phone and a tablet (or two phones) do for each other, from this
+/// device's side: the other one's battery, ringing it, its notifications
+/// shown here, and sending it the clipboard, files and links.
+pub const ANDROID_PAIR_FEATURES: &[FeatureDef] = &[
+ FeatureDef {
+ id: "pair.battery",
+ group: FeatureGroup::Device,
+ requires: &[peer("device.battery")],
+ partial: None,
+ },
+ FeatureDef {
+ id: "pair.ring",
+ group: FeatureGroup::Device,
+ requires: &[peer("device.ring")],
+ partial: None,
+ },
+ FeatureDef {
+ id: "pair.notifications",
+ group: FeatureGroup::Notifications,
+ requires: &[
+ Requirement::Peer {
+ id: "notify.mirror",
+ unlock: Unlock::Permission(Permission::NotificationAccess),
+ },
+ here("notify.show"),
+ DeviceToggle("notifications"),
+ ],
+ partial: None,
+ },
+ FeatureDef {
+ id: "pair.clipboard",
+ group: FeatureGroup::Clipboard,
+ requires: &[peer("clip.write"), DeviceToggle("clipboard")],
+ partial: None,
+ },
+ FeatureDef {
+ id: "pair.files",
+ group: FeatureGroup::Files,
+ requires: &[peer("files.transfer"), DeviceToggle("files")],
+ partial: None,
+ },
+ FeatureDef {
+ id: "pair.links",
+ group: FeatureGroup::Device,
+ requires: &[peer("link.open")],
+ partial: None,
+ },
+];
const ASSIST: Unlock = Unlock::Power(PowerLevel::Assist);
const UPDATE: Unlock = Unlock::UpdateApp;
@@ -1260,4 +1356,78 @@ mod tests {
}
}
}
+
+ #[test]
+ fn a_phone_and_a_tablet_get_the_android_pair_features() {
+ let phone = facts(
+ DeviceKind::Phone,
+ "android",
+ "16",
+ PowerLevel::Basic,
+ &[
+ "device.ring",
+ "device.battery",
+ "notify.mirror",
+ "notify.show",
+ "clip.write",
+ "files.transfer",
+ "link.open",
+ ],
+ );
+ let tablet = facts(
+ DeviceKind::Tablet,
+ "android",
+ "15",
+ PowerLevel::Basic,
+ &["device.ring", "device.battery", "notify.show", "clip.write", "files.transfer", "link.open"],
+ );
+ let toggles = HashMap::new();
+ let paths = [ConnectionPath::Lan];
+ // On the tablet: the phone's notifications show here.
+ let on_tablet = compute(
+ DeviceId([1; 32]),
+ MatrixInputs { local: &tablet, peer: &phone, paths: &paths, toggles: &toggles },
+ );
+ for id in
+ ["pair.battery", "pair.ring", "pair.notifications", "pair.clipboard", "pair.files", "pair.links"]
+ {
+ assert_eq!(on_tablet.state(id), Some(FeatureState::Available), "{id}");
+ }
+ // PC features don't apply to two Android devices.
+ assert_eq!(
+ on_tablet.state("device.find_phone"),
+ Some(FeatureState::Unsupported { reason: UnsupportedReason::DeviceKinds })
+ );
+ // On the phone: the tablet doesn't share its notifications (no notification
+ // access there), so they can't show here until it's granted on the tablet.
+ let on_phone = compute(
+ DeviceId([2; 32]),
+ MatrixInputs { local: &phone, peer: &tablet, paths: &paths, toggles: &toggles },
+ );
+ assert!(matches!(
+ on_phone.state("pair.notifications"),
+ Some(FeatureState::Locked { upgrade }) if upgrade.action == UpgradeAction::GrantPermission(Permission::NotificationAccess)
+ ));
+ // Off for the device: locked behind its toggle.
+ let off = HashMap::from([("clipboard".to_owned(), false)]);
+ let no_clip = compute(
+ DeviceId([1; 32]),
+ MatrixInputs { local: &tablet, peer: &phone, paths: &paths, toggles: &off },
+ );
+ assert!(matches!(no_clip.state("pair.clipboard"), Some(FeatureState::Locked { .. })));
+ }
+
+ #[test]
+ fn a_phone_and_a_pc_have_no_android_pair_features() {
+ let matrix = matrix_with(
+ &facts(DeviceKind::Phone, "android", "16", PowerLevel::Basic, BASIC_PHONE),
+ &pc(),
+ &HashMap::new(),
+ );
+ assert_eq!(
+ matrix.state("pair.ring"),
+ Some(FeatureState::Unsupported { reason: UnsupportedReason::DeviceKinds })
+ );
+ assert_eq!(matrix.state("device.find_phone"), Some(FeatureState::Available));
+ }
}
diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rs
index 367808d..ae3afc0 100644
--- a/core/nectarlink-core/src/lib.rs
+++ b/core/nectarlink-core/src/lib.rs
@@ -139,7 +139,7 @@ pub use nectarlink_protocol::{
pairing::PairingUri,
};
pub use node::{DataRetentionCounts, Node, PeerDiagnostics};
-pub use notifications::NotificationError;
+pub use notifications::{NotificationError, SHOW as NOTIFY_SHOW};
pub use palette::{
ACHROMATIC_SEED_RGB, MAX_SAMPLE_SIDE, Palette as ThemePaletteMap, RolePalette, ThemeScheme,
achromatic_scheme, downsample_rgb, downsample_rgba, extract_artwork_scheme_rgb,
diff --git a/core/nectarlink-core/src/notifications.rs b/core/nectarlink-core/src/notifications.rs
index 795c2a1..9b5e78a 100644
--- a/core/nectarlink-core/src/notifications.rs
+++ b/core/nectarlink-core/src/notifications.rs
@@ -27,6 +27,8 @@ use crate::{
/// The device toggle that allows notifications for a device.
pub(crate) const TOGGLE: &str = "notifications";
+/// Offered by phones and tablets that show a paired device's notifications.
+pub const SHOW: &str = "notify.show";
/// A snapshot stays well under the 1 MiB frame limit (v0 §3).
const SNAPSHOT_BUDGET: usize = 768 * 1024;
@@ -203,12 +205,13 @@ impl Shared {
self.toggle_on(peer, TOGGLE)
}
- /// Sessions that should get this phone's notifications: connected PCs
- /// the user allows.
+ /// Sessions that should get this phone's notifications: connected
+ /// devices that show them (PCs, and phones or tablets that offer
+ /// `notify.show`) and 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))
+ .filter(|s| self.shows_notifications(&s.peer) && self.notifications_allowed(&s.peer))
.collect()
}
@@ -216,10 +219,20 @@ impl Shared {
self.store.get_peer(peer).ok().flatten().is_some_and(|p| role_of(&p.info) == Some(Role::Desktop))
}
+ /// Whether `peer` shows this device's notifications: a PC does, and a
+ /// phone or tablet that offers `notify.show`.
+ pub(crate) fn shows_notifications(&self, peer: &DeviceId) -> bool {
+ self.store
+ .get_peer(peer)
+ .ok()
+ .flatten()
+ .is_some_and(|p| role_of(&p.info) == Some(Role::Desktop) || p.caps.contains(SHOW))
+ }
+
/// 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) {
+ if !self.notifications.is_active() || !self.shows_notifications(&session.peer) {
return;
}
let snapshot = if self.notifications_allowed(&session.peer) {
diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rs
index 744fc64..03019f6 100644
--- a/core/nectarlink-core/tests/two_devices.rs
+++ b/core/nectarlink-core/tests/two_devices.rs
@@ -5759,3 +5759,60 @@ async fn a_pc_without_mic_listen_refuses_a_phones_microphone() {
pc.node.shutdown().await;
phone.node.shutdown().await;
}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_phones_notifications_show_on_a_paired_tablet_that_shows_them() {
+ let mut tablet = device_with("Tab", DeviceKind::Tablet, &[nectarlink_core::NOTIFY_SHOW]).await;
+ let mut phone = device("Pixel", DeviceKind::Phone).await;
+ pair_qr(&mut tablet, &mut phone).await;
+ let phone_id = phone.node.device_id();
+ grant_notification_access(&phone).await;
+
+ phone.node.notifications_reset(vec![note("a", "com.chat", "Sam", true)]).await;
+ let items = wait_for(&mut tablet, "snapshot", |e| match e {
+ NodeEvent::NotificationsReset { device, items } if *device == phone_id => Some(items.clone()),
+ _ => None,
+ })
+ .await;
+ assert_eq!(items.len(), 1);
+
+ phone.node.notification_posted(note("b", "com.chat", "Kim", true)).await;
+ let posted = wait_for(&mut tablet, "posted", |e| match e {
+ NodeEvent::NotificationPosted { device, notification } if *device == phone_id => {
+ Some(notification.key.clone())
+ }
+ _ => None,
+ })
+ .await;
+ assert_eq!(posted, "b");
+
+ // Dismissed on the tablet: gone on the phone too.
+ with_timeout("dismiss", tablet.node.dismiss_notification(phone_id, "b".into())).await.unwrap();
+
+ tablet.node.shutdown().await;
+ phone.node.shutdown().await;
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_phone_keeps_its_notifications_from_a_phone_that_doesnt_show_them() {
+ let mut other = device("Other phone", DeviceKind::Phone).await;
+ let mut phone = device("Pixel", DeviceKind::Phone).await;
+ pair_qr(&mut other, &mut phone).await;
+ grant_notification_access(&phone).await;
+ phone.node.notification_posted(note("a", "com.chat", "Sam", true)).await;
+ let got = tokio::time::timeout(Duration::from_millis(800), async {
+ loop {
+ match other.events.recv().await {
+ Ok(NodeEvent::NotificationPosted { .. } | NodeEvent::NotificationsReset { .. }) => {
+ return true;
+ }
+ Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
+ Err(_) => return false,
+ }
+ }
+ })
+ .await;
+ assert!(!matches!(got, Ok(true)), "notifications went to a phone that doesn't show them");
+ other.node.shutdown().await;
+ phone.node.shutdown().await;
+}
diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rs
index bc74ace..4e61d6a 100644
--- a/core/nectarlink-ffi/src/lib.rs
+++ b/core/nectarlink-ffi/src/lib.rs
@@ -3293,6 +3293,14 @@ impl NectarlinkNode {
self.run(async move { Ok(node.ring(id, on).await?) }).await
}
+ /// Dismisses a paired phone's or tablet's notification there, after it
+ /// was dismissed here (`notify.dismiss`).
+ pub async fn dismiss_peer_notification(&self, id: String, key: String) -> Result<()> {
+ let id = parse_id(&id)?;
+ let node = self.node.clone();
+ self.run(async move { Ok(node.dismiss_notification(id, key).await?) }).await
+ }
+
pub fn capabilities(&self, id: String) -> Result<Vec<Feature>> {
Ok(features(&self.node.capabilities(parse_id(&id)?)?))
}
diff --git a/docs/architecture/capabilities.md b/docs/architecture/capabilities.md
index ba6e489..79eb7c7 100644
--- a/docs/architecture/capabilities.md
+++ b/docs/architecture/capabilities.md
@@ -118,6 +118,16 @@ A pair that isn't one phone (or tablet) and one desktop (or laptop) has every
feature Unsupported (`DeviceKinds`). An `Unknown` device kind falls back to
the OS (`android` → phone, `windows`/`macos` → desktop).
+Two Android devices (a phone and a tablet, or two phones) get the features
+of `ANDROID_PAIR_FEATURES` instead, from this device's side: `pair.battery`
+and `pair.ring` (the other device's battery, and ringing it),
+`pair.notifications` (its notifications shown here: it offers
+`notify.mirror` and this device `notify.show`, toggle `notifications`),
+`pair.clipboard`, `pair.files` and `pair.links` (sending it the clipboard,
+files and links). Their requirements name the other device (`Peer`) and
+this one (`Here`) rather than a role. Every other pair has them
+Unsupported, as two Android devices have the PC features.
+
## Per-device toggles
`notifications`, `messages`, `calls`, `contacts`, `clipboard`, `files`,
diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.md
index d26d442..3199487 100644
--- a/docs/protocol/capabilities.md
+++ b/docs/protocol/capabilities.md
@@ -42,6 +42,7 @@ capability is missing.
| `notify.live` | Includes live progress, timer, and Android 16 Live Update metadata on mirrored notifications ([notifications service](notifications.md)) | notification access |
| `notify.reply` | Accepts inline replies and actions on notifications | notification access |
| `notify.sensitive` | Forwards notifications Android hides as sensitive (e.g. one-time codes) | Elevated |
+| `notify.show` | Shows a paired phone's or tablet's notifications ([notifications service](notifications.md)) | app update |
| `sms.read` | Lists conversations and messages ([messages](sms.md)) | SMS permission |
| `sms.send` | Sends texts when a PC asks ([messages](sms.md)) | SMS permission |
| `call.state` | Reports incoming and ongoing calls ([calls](calls.md)) | phone permission |
diff --git a/docs/protocol/notifications.md b/docs/protocol/notifications.md
index 7723567..8243ec0 100644
--- a/docs/protocol/notifications.md
+++ b/docs/protocol/notifications.md
@@ -4,7 +4,9 @@
> 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.
+and in a feed) and can dismiss them, reply to them and run their actions,
+and to paired phones and tablets that offer `notify.show`, which show them
+in their own notification shade and dismiss them there.
All messages travel on the **control stream** (v0 §4). Notifications are
small, latency matters more than throughput, and their order must be kept:
@@ -18,6 +20,7 @@ a `notify.removed` must never overtake the `notify.posted` it removes.
| `notify.live` | phone | Includes `live` metadata on ongoing progress, timer, and Android 16 Live Update notifications |
| `notify.reply` | phone | Handles `notify.dismiss` and `notify.action` |
| `notify.sensitive` | phone | Includes notifications Android hides from apps as sensitive (one-time codes) |
+| `notify.show` | phone, tablet | Shows a paired phone's or tablet's notifications; a phone sends them to it as to a PC (PCs needn't offer it) |
A PC that doesn't offer anything still receives these events; a peer that
doesn't know them ignores them (v0 §3.1).