Skip to content

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

Add the capability matrix (C5)

Beeaf06d9f15ede
diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rs
index 20a5a9b..8cf9f90 100644
--- a/core/nectarlink-cli/src/main.rs
+++ b/core/nectarlink-cli/src/main.rs
@@ -7,10 +7,11 @@
use std::{io::Write, net::SocketAddr, path::PathBuf, sync::Arc, time::Duration};
use anyhow::{Context, Result, bail};
-use clap::{Parser, Subcommand};
+use clap::{Parser, Subcommand, ValueEnum};
use nectarlink_core::{
- DeviceId, DeviceInfo, DeviceKind, LinkState, Node, NodeConfig, NodeEvent, PairedDevice, PairingEvent,
- Platform,
+ ConnectionPath, DeviceId, DeviceInfo, DeviceKind, FeatureState, LinkState, Node, NodeConfig, NodeEvent,
+ PairedDevice, PairingEvent, Platform, PowerLevel,
+ features::{Effort, FEATURES, Role, UnsupportedReason, Upgrade, UpgradeAction},
};
use tokio::sync::broadcast::error::RecvError;
@@ -32,6 +33,15 @@ struct Cli {
/// Allow connections through relay servers when away from home.
#[arg(long, global = true)]
away: bool,
+ /// Announce this client as an Android phone, to test a PC without one.
+ #[arg(long, global = true)]
+ as_phone: bool,
+ /// Power level to announce with --as-phone.
+ #[arg(long, global = true, value_enum, default_value_t = Power::Basic, requires = "as_phone")]
+ power: Power,
+ /// Extra capability to announce, e.g. clip.read.auto (repeatable).
+ #[arg(long = "offer", global = true, value_name = "CAPABILITY")]
+ offers: Vec<String>,
/// Log verbosity (error, warn, info, debug, trace).
#[arg(long, global = true, default_value = "warn")]
log: String,
@@ -77,10 +87,38 @@ enum Command {
},
/// Unpair a device.
Unpair { device: String },
+ /// Show which features work with a paired device, and how to unlock the rest.
+ Caps {
+ device: String,
+ /// Seconds to wait for the device to connect (0: use what's known).
+ #[arg(long, default_value_t = 3)]
+ wait: u64,
+ },
+ /// Show or change what a paired device is allowed to do.
+ Toggle {
+ device: String,
+ /// Toggle to change, e.g. "clipboard" (omit to list them).
+ name: Option<String>,
+ #[arg(requires = "name")]
+ state: Option<OnOff>,
+ },
/// Stay online and print events until Ctrl+C.
Run,
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
+enum Power {
+ Basic,
+ Assist,
+ Elevated,
+}
+
+#[derive(Debug, Clone, Copy, ValueEnum)]
+enum OnOff {
+ On,
+ Off,
+}
+
/// Rings by printing to the terminal (the CLI has no speaker access).
#[derive(Debug)]
struct TerminalPlatform;
@@ -116,19 +154,28 @@ async fn start_node(cli: &Cli) -> Result<Node> {
let name = cli.name.clone().unwrap_or_else(|| {
hostname::get().ok().and_then(|h| h.into_string().ok()).unwrap_or_else(|| "Nectarlink CLI".into())
});
- let device = DeviceInfo {
- name,
- kind: DeviceKind::Desktop,
- os: std::env::consts::OS.into(),
- os_ver: String::new(),
- model: None,
- accent: None,
+ let (kind, os, os_ver) = if cli.as_phone {
+ (DeviceKind::Phone, "android".into(), "16".into())
+ } else {
+ (DeviceKind::Desktop, std::env::consts::OS.into(), String::new())
+ };
+ let device = DeviceInfo { name, kind, os, os_ver, model: None, accent: None };
+ let power = match (cli.as_phone, cli.power) {
+ (false, _) => PowerLevel::NotApplicable,
+ (true, Power::Basic) => PowerLevel::Basic,
+ (true, Power::Assist) => PowerLevel::Assist,
+ (true, Power::Elevated) => PowerLevel::Elevated,
};
let mut config = NodeConfig::new(data_dir, device, env!("CARGO_PKG_VERSION"));
config.port = cli.port;
config.lan_discovery = !cli.no_lan;
config.away_mode = cli.away;
- Node::start(config, Arc::new(TerminalPlatform)).await.context("failed to start")
+ config.power = power;
+ let node = Node::start(config, Arc::new(TerminalPlatform)).await.context("failed to start")?;
+ if !cli.offers.is_empty() {
+ node.update_power(power, cli.offers.clone()).await;
+ }
+ Ok(node)
}
async fn run(cli: &Cli, node: &Node) -> Result<()> {
@@ -184,6 +231,37 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {
node.unpair(id).await?;
println!("✓ Unpaired.");
}
+ Command::Caps { device, wait } => {
+ let id = resolve(node, device)?;
+ if *wait > 0
+ && tokio::time::timeout(Duration::from_secs(*wait), wait_until_online(node, id))
+ .await
+ .is_err()
+ {
+ println!("(not connected; showing what the device offered last time)");
+ }
+ print_capabilities(node, id)?;
+ }
+ Command::Toggle { device, name: None, .. } => {
+ let id = resolve(node, device)?;
+ for (name, on) in node.device_toggles(id)? {
+ println!("{name:<16} {}", if on { "on" } else { "off" });
+ }
+ }
+ Command::Toggle { device, name: Some(name), state } => {
+ let id = resolve(node, device)?;
+ let current = node.device_toggles(id)?.into_iter().find(|(n, _)| n == name).map(|(_, on)| on);
+ let Some(current) = current else {
+ bail!("unknown toggle {name:?}; run without a name to list them")
+ };
+ let on = match state {
+ Some(OnOff::On) => true,
+ Some(OnOff::Off) => false,
+ None => !current,
+ };
+ node.set_device_toggle(id, name, on)?;
+ println!("{name} is now {}", if on { "on" } else { "off" });
+ }
Command::Run => watch(node).await?,
}
Ok(())
@@ -293,10 +371,76 @@ fn print_event(node: &Node, event: &NodeEvent) {
NodeEvent::Discovered(d) => {
println!("Found nearby: {} ({})", d.name.as_deref().unwrap_or("unnamed"), d.id.short())
}
+ NodeEvent::Capabilities(m) => {
+ let available = m.features.values().filter(|s| **s == FeatureState::Available).count();
+ println!("{}: {available} of {} features available", name(&m.device), m.features.len())
+ }
_ => {}
}
}
+fn print_capabilities(node: &Node, id: DeviceId) -> Result<()> {
+ let matrix = node.capabilities(id)?;
+ let mut group = None;
+ for def in FEATURES {
+ if group != Some(def.group) {
+ group = Some(def.group);
+ println!("\n{:?}", def.group);
+ }
+ let state = matrix.state(def.id).context("feature missing from the matrix")?;
+ println!(" {:<30} {}", def.id, describe_state(&state));
+ }
+ Ok(())
+}
+
+fn describe_state(state: &FeatureState) -> String {
+ match state {
+ FeatureState::Available => "✓ available".into(),
+ FeatureState::Partial { limit, upgrade: Some(u) } => {
+ format!("◐ partial ({limit}); unlock: {}", describe_upgrade(u))
+ }
+ FeatureState::Partial { limit, upgrade: None } => format!("◐ partial ({limit})"),
+ FeatureState::Locked { upgrade } => format!("🔒 {}", describe_upgrade(upgrade)),
+ FeatureState::Unsupported { reason } => format!("✗ {}", describe_reason(reason)),
+ }
+}
+
+fn describe_upgrade(upgrade: &Upgrade) -> String {
+ let action = match upgrade.action {
+ UpgradeAction::RaisePower(level) => format!("raise the phone to {}", power_name(level)),
+ UpgradeAction::GrantPermission(p) => format!("grant the {} permission on the phone", p.as_str()),
+ UpgradeAction::EnableAddon(addon) => format!("install the {addon} add-on"),
+ UpgradeAction::EnablePath(ConnectionPath::Relay) => "turn on Away mode".into(),
+ UpgradeAction::EnablePath(path) => format!("enable the {path:?} connection"),
+ UpgradeAction::EnableDeviceToggle(t) => format!("allow {t} (nectarlink toggle <device> {t} on)"),
+ UpgradeAction::UpdateApp(Role::Phone) => "update the app on the phone".into(),
+ UpgradeAction::UpdateApp(Role::Desktop) => "update the app on the PC".into(),
+ };
+ match upgrade.effort {
+ Effort::Instant => action,
+ Effort::Minutes(n) => format!("{action} · ~{n} min"),
+ }
+}
+
+fn describe_reason(reason: &UnsupportedReason) -> String {
+ match reason {
+ UnsupportedReason::DeviceKinds => "needs a phone paired with a PC".into(),
+ UnsupportedReason::AndroidTooOld { needs } => format!("needs Android {needs} or newer"),
+ UnsupportedReason::WindowsTooOld { needs_build } => {
+ format!("needs Windows build {needs_build} or newer")
+ }
+ UnsupportedReason::NotOnThisDevice => "not available on this phone".into(),
+ }
+}
+
+fn power_name(level: PowerLevel) -> &'static str {
+ match level {
+ PowerLevel::Assist => "Assist",
+ PowerLevel::Elevated => "Elevated",
+ _ => "Basic",
+ }
+}
+
fn print_device(d: &PairedDevice) {
println!("{:<24} {:<10} {} {}", d.info.name, format!("{:?}", d.info.kind), describe_link(&d.link), d.id);
}
diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rs
index b0b9b37..7503557 100644
--- a/core/nectarlink-core/src/events.rs
+++ b/core/nectarlink-core/src/events.rs
@@ -6,6 +6,8 @@ use nectarlink_protocol::{
messages::{Battery, DeviceInfo, PowerLevel},
};
+use crate::features::CapabilityMatrix;
+
/// How a session is currently carried.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConnectionPath {
@@ -73,11 +75,28 @@ pub enum PairingEvent {
pub enum NodeEvent {
DeviceAdded(PairedDevice),
DeviceRemoved(DeviceId),
- LinkChanged { device: DeviceId, link: LinkState },
- PeerInfoChanged { device: DeviceId, info: DeviceInfo },
- PeerPowerChanged { device: DeviceId, power: PowerLevel },
- Battery { device: DeviceId, battery: Battery },
- Ring { device: DeviceId, on: bool },
+ LinkChanged {
+ device: DeviceId,
+ link: LinkState,
+ },
+ PeerInfoChanged {
+ device: DeviceId,
+ info: DeviceInfo,
+ },
+ PeerPowerChanged {
+ device: DeviceId,
+ power: PowerLevel,
+ },
+ /// What works with a device changed (see `docs/architecture/capabilities.md`).
+ Capabilities(CapabilityMatrix),
+ Battery {
+ device: DeviceId,
+ battery: Battery,
+ },
+ Ring {
+ device: DeviceId,
+ on: bool,
+ },
Discovered(DiscoveredDevice),
DiscoveryExpired(DeviceId),
Pairing(PairingEvent),
diff --git a/core/nectarlink-core/src/features.rs b/core/nectarlink-core/src/features.rs
new file mode 100644
index 0000000..39c5f70
--- /dev/null
+++ b/core/nectarlink-core/src/features.rs
@@ -0,0 +1,896 @@
+// SPDX-License-Identifier: MPL-2.0
+//! The capability matrix (docs/architecture/capabilities.md): for every
+//! feature and paired device, whether the feature is available, partly
+//! available, locked behind something the user can do, or unsupported.
+//!
+//! Requirements name the **phone** and the **desktop**, never "local" and
+//! "peer", so both apps compute the same matrix for a pair and can never
+//! disagree about what works. Everything here is pure; [`crate::Node`]
+//! gathers the inputs and emits the result.
+
+use std::collections::{BTreeMap, BTreeSet, HashMap};
+
+use nectarlink_protocol::{
+ DeviceId,
+ messages::{DeviceInfo, DeviceKind, PowerLevel},
+};
+
+use crate::events::ConnectionPath;
+
+/// Which device of a pair a requirement is about.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum Role {
+ Phone,
+ Desktop,
+}
+
+/// An Android runtime permission (or special access) a feature needs.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum Permission {
+ NotificationAccess,
+ Sms,
+ Phone,
+ Contacts,
+ Photos,
+ Camera,
+ Microphone,
+}
+
+impl Permission {
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Permission::NotificationAccess => "notification_access",
+ Permission::Sms => "sms",
+ Permission::Phone => "phone",
+ Permission::Contacts => "contacts",
+ Permission::Photos => "photos",
+ Permission::Camera => "camera",
+ Permission::Microphone => "microphone",
+ }
+ }
+}
+
+/// How a missing capability can be obtained.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Unlock {
+ /// The phone offers it from this power level on.
+ Power(PowerLevel),
+ /// The phone offers it once this permission is granted.
+ Permission(Permission),
+ /// The desktop offers it once this add-on is installed.
+ Addon(&'static str),
+ /// Every current app version offers it, so the device's app is too old.
+ UpdateApp,
+}
+
+/// One condition a feature depends on.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Requirement {
+ /// The device in `role` announces capability `id` (protocol §6).
+ Cap { role: Role, id: &'static str, unlock: Unlock },
+ /// The phone runs at this power level or higher.
+ PowerAtLeast(PowerLevel),
+ /// The phone runs this Android release or newer.
+ AndroidAtLeast(u32),
+ /// The desktop runs this Windows build or newer.
+ WindowsBuildAtLeast(u32),
+ /// This connection path is enabled (e.g. Away mode for relays).
+ Path(ConnectionPath),
+ /// The user allows this for the device (see [`DEVICE_TOGGLES`]).
+ DeviceToggle(&'static str),
+}
+
+/// A weaker set of requirements that still gives a useful, limited feature.
+#[derive(Debug, Clone, Copy)]
+pub struct PartialDef {
+ pub requires: &'static [Requirement],
+ /// Translation key describing the limitation, e.g. `clipboard.limit.manual`.
+ pub limit: &'static str,
+}
+
+/// UI grouping of features.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum FeatureGroup {
+ Device,
+ Notifications,
+ Messages,
+ Calls,
+ Clipboard,
+ Files,
+ Mirroring,
+ Media,
+ Camera,
+ Input,
+ Remote,
+}
+
+/// A feature, declared once and shared by both apps.
+#[derive(Debug, Clone, Copy)]
+pub struct FeatureDef {
+ /// Stable ID, e.g. `clipboard.auto_phone_to_pc`.
+ pub id: &'static str,
+ pub group: FeatureGroup,
+ /// Every requirement must hold for the feature to be available.
+ pub requires: &'static [Requirement],
+ pub partial: Option<PartialDef>,
+}
+
+/// What the user can do to unlock a feature.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum UpgradeAction {
+ /// Open "Choose your power" at this level.
+ RaisePower(PowerLevel),
+ /// Ask for a permission on the phone.
+ GrantPermission(Permission),
+ /// Install a desktop add-on (e.g. the virtual camera).
+ EnableAddon(&'static str),
+ /// Turn on a connection path (e.g. Away mode).
+ EnablePath(ConnectionPath),
+ /// Allow something for this device.
+ EnableDeviceToggle(&'static str),
+ /// Update the app on that device.
+ UpdateApp(Role),
+}
+
+/// Roughly how long an upgrade takes, so the UI can say "~2 min".
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub enum Effort {
+ Instant,
+ Minutes(u8),
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Upgrade {
+ pub action: UpgradeAction,
+ pub effort: Effort,
+}
+
+impl Upgrade {
+ fn new(action: UpgradeAction) -> Self {
+ let effort = match action {
+ UpgradeAction::RaisePower(PowerLevel::Elevated) => Effort::Minutes(2),
+ UpgradeAction::RaisePower(_) => Effort::Minutes(1),
+ UpgradeAction::EnableAddon(_) => Effort::Minutes(1),
+ UpgradeAction::UpdateApp(_) => Effort::Minutes(2),
+ UpgradeAction::GrantPermission(_)
+ | UpgradeAction::EnablePath(_)
+ | UpgradeAction::EnableDeviceToggle(_) => Effort::Instant,
+ };
+ Upgrade { action, effort }
+ }
+}
+
+/// Why a feature can't work on this pair. Explained, not actionable.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum UnsupportedReason {
+ /// Features need one phone and one desktop.
+ DeviceKinds,
+ AndroidTooOld {
+ needs: u32,
+ },
+ WindowsTooOld {
+ needs_build: u32,
+ },
+ /// The phone has the needed power level but still doesn't offer the
+ /// capability (hardware or OEM limitation).
+ NotOnThisDevice,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum FeatureState {
+ Available,
+ /// Works, with a limitation shown inline, and how to remove it if possible.
+ Partial {
+ limit: &'static str,
+ upgrade: Option<Upgrade>,
+ },
+ /// Doesn't work yet, but the user can unlock it.
+ Locked {
+ upgrade: Upgrade,
+ },
+ Unsupported {
+ reason: UnsupportedReason,
+ },
+}
+
+/// Every feature's state for one paired device.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct CapabilityMatrix {
+ pub device: DeviceId,
+ pub features: BTreeMap<&'static str, FeatureState>,
+}
+
+impl CapabilityMatrix {
+ pub fn state(&self, feature: &str) -> Option<FeatureState> {
+ self.features.get(feature).copied()
+ }
+}
+
+/// What the matrix knows about one device of the pair.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct DeviceFacts {
+ pub kind: DeviceKind,
+ pub os: String,
+ pub os_ver: String,
+ pub caps: BTreeSet<String>,
+ pub power: PowerLevel,
+}
+
+impl DeviceFacts {
+ pub fn new(info: &DeviceInfo, caps: BTreeSet<String>, power: PowerLevel) -> Self {
+ DeviceFacts { kind: info.kind, os: info.os.clone(), os_ver: info.os_ver.clone(), caps, power }
+ }
+
+ 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,
+ },
+ }
+ }
+
+ /// The Android release (`"16"` → 16), if this is an Android device.
+ fn android_release(&self) -> Option<u32> {
+ (self.os == "android").then(|| leading_number(&self.os_ver)).flatten()
+ }
+
+ /// The Windows build (`"10.0.26200"` → 26200), if this is a Windows device.
+ fn windows_build(&self) -> Option<u32> {
+ (self.os == "windows").then(|| self.os_ver.split('.').nth(2).and_then(leading_number)).flatten()
+ }
+}
+
+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()
+}
+
+/// Most capabilities a device may announce; extra ones are ignored.
+const MAX_CAPABILITIES: usize = 256;
+const MAX_CAPABILITY_LEN: usize = 64;
+
+/// Keeps the well-formed capability IDs a peer announced (`[a-z0-9._-]`,
+/// bounded in length and count), so stored and displayed data stays sane.
+pub(crate) fn sanitize_capabilities(caps: impl IntoIterator<Item = String>) -> BTreeSet<String> {
+ caps.into_iter()
+ .filter(|c| {
+ (1..=MAX_CAPABILITY_LEN).contains(&c.len())
+ && c.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b))
+ })
+ .take(MAX_CAPABILITIES)
+ .collect()
+}
+
+/// Per-device permissions the user can switch, with their defaults.
+pub const DEVICE_TOGGLES: &[(&str, bool)] = &[
+ ("notifications", true),
+ ("messages", true),
+ ("calls", true),
+ ("clipboard", true),
+ ("photos", true),
+ ("pc_actions", true),
+ // Browsing the PC's files from anywhere is opt-in.
+ ("remote_files", false),
+];
+
+/// The default for a toggle, or `None` if no such toggle exists.
+pub fn toggle_default(toggle: &str) -> Option<bool> {
+ DEVICE_TOGGLES.iter().find(|(name, _)| *name == toggle).map(|(_, on)| *on)
+}
+
+/// Inputs for one pair.
+#[derive(Debug, Clone, Copy)]
+pub struct MatrixInputs<'a> {
+ pub local: &'a DeviceFacts,
+ pub peer: &'a DeviceFacts,
+ /// Connection paths that are enabled on this device.
+ pub paths: &'a [ConnectionPath],
+ /// The user's per-device toggles; missing ones use their default.
+ pub toggles: &'a HashMap<String, bool>,
+}
+
+/// Computes the state of every feature in [`FEATURES`] for one 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)),
+ _ => 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();
+ CapabilityMatrix { device, features }
+}
+
+struct Context<'a> {
+ phone: &'a DeviceFacts,
+ desktop: &'a DeviceFacts,
+ paths: &'a [ConnectionPath],
+ toggles: &'a HashMap<String, bool>,
+}
+
+/// The outcome of checking one requirement.
+enum Check {
+ Met,
+ Unlockable(Upgrade),
+ Impossible(UnsupportedReason),
+}
+
+/// Basic < Assist < Elevated. Desktops and unknown values count as Basic.
+fn power_rank(level: PowerLevel) -> u8 {
+ match level {
+ PowerLevel::Assist => 1,
+ PowerLevel::Elevated => 2,
+ PowerLevel::Basic | PowerLevel::NotApplicable | PowerLevel::Unknown => 0,
+ }
+}
+
+fn check(req: &Requirement, ctx: &Context<'_>) -> Check {
+ match *req {
+ Requirement::Cap { role, id, unlock } => {
+ let facts = match role {
+ Role::Phone => ctx.phone,
+ Role::Desktop => ctx.desktop,
+ };
+ if facts.caps.contains(id) {
+ return Check::Met;
+ }
+ match unlock {
+ Unlock::Power(level) if power_rank(ctx.phone.power) < power_rank(level) => {
+ Check::Unlockable(Upgrade::new(UpgradeAction::RaisePower(level)))
+ }
+ Unlock::Power(_) => Check::Impossible(UnsupportedReason::NotOnThisDevice),
+ Unlock::Permission(p) => Check::Unlockable(Upgrade::new(UpgradeAction::GrantPermission(p))),
+ Unlock::Addon(addon) => Check::Unlockable(Upgrade::new(UpgradeAction::EnableAddon(addon))),
+ Unlock::UpdateApp => Check::Unlockable(Upgrade::new(UpgradeAction::UpdateApp(role))),
+ }
+ }
+ Requirement::PowerAtLeast(level) => {
+ if power_rank(ctx.phone.power) >= power_rank(level) {
+ Check::Met
+ } else {
+ Check::Unlockable(Upgrade::new(UpgradeAction::RaisePower(level)))
+ }
+ }
+ // An unparseable version doesn't block a feature: the phone only
+ // advertises capabilities it can actually provide.
+ Requirement::AndroidAtLeast(needs) => match ctx.phone.android_release() {
+ Some(release) if release < needs => Check::Impossible(UnsupportedReason::AndroidTooOld { needs }),
+ _ => Check::Met,
+ },
+ Requirement::WindowsBuildAtLeast(needs_build) => match ctx.desktop.windows_build() {
+ Some(build) if build < needs_build => {
+ Check::Impossible(UnsupportedReason::WindowsTooOld { needs_build })
+ }
+ _ => Check::Met,
+ },
+ Requirement::Path(path) => {
+ if ctx.paths.contains(&path) {
+ Check::Met
+ } else {
+ Check::Unlockable(Upgrade::new(UpgradeAction::EnablePath(path)))
+ }
+ }
+ Requirement::DeviceToggle(toggle) => {
+ let on = ctx.toggles.get(toggle).copied().or_else(|| toggle_default(toggle)).unwrap_or(false);
+ if on {
+ Check::Met
+ } else {
+ Check::Unlockable(Upgrade::new(UpgradeAction::EnableDeviceToggle(toggle)))
+ }
+ }
+ }
+}
+
+/// Lowest-effort upgrade among unmet requirements, and the first reason the
+/// set can't be met at all.
+struct Summary {
+ met: bool,
+ upgrade: Option<Upgrade>,
+ impossible: Option<UnsupportedReason>,
+}
+
+fn summarize(requires: &[Requirement], ctx: &Context<'_>) -> Summary {
+ let mut summary = Summary { met: true, upgrade: None, impossible: None };
+ for req in requires {
+ match check(req, ctx) {
+ Check::Met => {}
+ Check::Unlockable(upgrade) => {
+ summary.met = false;
+ // Keep the first of equally easy upgrades (declaration order).
+ if summary.upgrade.is_none_or(|best| upgrade.effort < best.effort) {
+ summary.upgrade = Some(upgrade);
+ }
+ }
+ Check::Impossible(reason) => {
+ summary.met = false;
+ summary.impossible.get_or_insert(reason);
+ }
+ }
+ }
+ summary
+}
+
+/// Picks the state (docs/architecture/capabilities.md, "How a state is chosen"):
+/// Available if everything holds; else Partial if the weaker set holds (part
+/// of the feature works even if the rest never will); else Unsupported if
+/// something can't be met on this pair; else Locked with the easiest upgrade.
+fn evaluate(def: &FeatureDef, ctx: &Context<'_>) -> FeatureState {
+ let full = summarize(def.requires, ctx);
+ if full.met {
+ return FeatureState::Available;
+ }
+ if let Some(partial) = def.partial
+ && summarize(partial.requires, ctx).met
+ {
+ let upgrade = if full.impossible.is_some() { None } else { full.upgrade };
+ return FeatureState::Partial { limit: partial.limit, upgrade };
+ }
+ match (full.impossible, full.upgrade) {
+ (Some(reason), _) => FeatureState::Unsupported { reason },
+ (None, Some(upgrade)) => FeatureState::Locked { upgrade },
+ // Unreachable: an unmet set has an upgrade or a reason.
+ (None, None) => FeatureState::Unsupported { reason: UnsupportedReason::NotOnThisDevice },
+ }
+}
+
+// ---- The registry ----
+
+use Requirement::{AndroidAtLeast, DeviceToggle, Path, PowerAtLeast, WindowsBuildAtLeast};
+
+const fn phone(id: &'static str, unlock: Unlock) -> Requirement {
+ Requirement::Cap { role: Role::Phone, id, unlock }
+}
+
+const fn desktop(id: &'static str, unlock: Unlock) -> Requirement {
+ Requirement::Cap { role: Role::Desktop, id, unlock }
+}
+
+const ELEVATED: Unlock = Unlock::Power(PowerLevel::Elevated);
+const ASSIST: Unlock = Unlock::Power(PowerLevel::Assist);
+const UPDATE: Unlock = Unlock::UpdateApp;
+
+/// Every feature, in display order. Capability IDs are listed in
+/// docs/protocol/capabilities.md.
+pub const FEATURES: &[FeatureDef] = &[
+ // Device
+ FeatureDef {
+ id: "device.find_phone",
+ group: FeatureGroup::Device,
+ requires: &[phone("device.ring", UPDATE)],
+ partial: None,
+ },
+ FeatureDef {
+ id: "device.battery",
+ group: FeatureGroup::Device,
+ requires: &[phone("device.battery", UPDATE)],
+ partial: None,
+ },
+ FeatureDef {
+ id: "device.pc_actions",
+ group: FeatureGroup::Device,
+ requires: &[desktop("pc.power", UPDATE), DeviceToggle("pc_actions")],
+ partial: None,
+ },
+ // Notifications
+ FeatureDef {
+ id: "notifications.mirror",
+ group: FeatureGroup::Notifications,
+ requires: &[
+ phone("notify.mirror", Unlock::Permission(Permission::NotificationAccess)),
+ DeviceToggle("notifications"),
+ ],
+ partial: None,
+ },
+ FeatureDef {
+ id: "notifications.reply",
+ group: FeatureGroup::Notifications,
+ requires: &[
+ phone("notify.reply", Unlock::Permission(Permission::NotificationAccess)),
+ DeviceToggle("notifications"),
+ ],
+ partial: None,
+ },
+ FeatureDef {
+ id: "notifications.sensitive",
+ group: FeatureGroup::Notifications,
+ requires: &[phone("notify.sensitive", ELEVATED), DeviceToggle("notifications")],
+ partial: None,
+ },
+ // Messages & calls
+ FeatureDef {
+ id: "messages.sms",
+ group: FeatureGroup::Messages,
+ requires: &[
+ phone("sms.read", Unlock::Permission(Permission::Sms)),
+ phone("sms.send", Unlock::Permission(Permission::Sms)),
+ DeviceToggle("messages"),
+ ],
+ partial: None,
+ },
+ FeatureDef {
+ id: "calls.alerts",
+ group: FeatureGroup::Calls,
+ requires: &[phone("call.state", Unlock::Permission(Permission::Phone)), DeviceToggle("calls")],
+ partial: None,
+ },
+ // Clipboard
+ FeatureDef {
+ id: "clipboard.pc_to_phone",
+ group: FeatureGroup::Clipboard,
+ requires: &[phone("clip.write", UPDATE), DeviceToggle("clipboard")],
+ partial: None,
+ },
+ FeatureDef {
+ id: "clipboard.auto_phone_to_pc",
+ group: FeatureGroup::Clipboard,
+ requires: &[phone("clip.read.auto", ELEVATED), DeviceToggle("clipboard")],
+ partial: Some(PartialDef {
+ requires: &[phone("clip.share", UPDATE), DeviceToggle("clipboard")],
+ limit: "clipboard.limit.manual",
+ }),
+ },
+ // Files & photos
+ FeatureDef {
+ id: "files.send",
+ group: FeatureGroup::Files,
+ requires: &[phone("files.transfer", UPDATE), desktop("files.transfer", UPDATE)],
+ partial: None,
+ },
+ FeatureDef {
+ id: "files.recent_photos",
+ group: FeatureGroup::Files,
+ requires: &[phone("photos.read", Unlock::Permission(Permission::Photos)), DeviceToggle("photos")],
+ partial: None,
+ },
+ // Mirroring
+ FeatureDef {
+ id: "mirroring.view",
+ group: FeatureGroup::Mirroring,
+ requires: &[phone("mirror.capture", UPDATE)],
+ partial: None,
+ },
+ FeatureDef {
+ id: "mirroring.control",
+ group: FeatureGroup::Mirroring,
+ requires: &[phone("mirror.capture", UPDATE), phone("mirror.input", ASSIST)],
+ partial: None,
+ },
+ FeatureDef {
+ id: "mirroring.app_windows",
+ group: FeatureGroup::Mirroring,
+ requires: &[
+ phone("mirror.virtual_display", ELEVATED),
+ PowerAtLeast(PowerLevel::Elevated),
+ AndroidAtLeast(11),
+ ],
+ partial: None,
+ },
+ FeatureDef {
+ id: "mirroring.audio",
+ group: FeatureGroup::Mirroring,
+ requires: &[phone("mirror.audio", ELEVATED)],
+ partial: Some(PartialDef {
+ requires: &[phone("mirror.audio.playback", UPDATE)],
+ limit: "mirroring.limit.audio_some_apps",
+ }),
+ },
+ // Media
+ FeatureDef {
+ id: "media.phone_control",
+ group: FeatureGroup::Media,
+ requires: &[phone("media.control", Unlock::Permission(Permission::NotificationAccess))],
+ partial: None,
+ },
+ FeatureDef {
+ id: "media.pc_control",
+ group: FeatureGroup::Media,
+ requires: &[desktop("media.control", UPDATE)],
+ partial: None,
+ },
+ // Camera
+ FeatureDef {
+ id: "camera.webcam",
+ group: FeatureGroup::Camera,
+ requires: &[
+ phone("camera.stream", Unlock::Permission(Permission::Camera)),
+ desktop("addon.vcam", Unlock::Addon("vcam")),
+ WindowsBuildAtLeast(22000),
+ ],
+ partial: None,
+ },
+ // Input
+ FeatureDef {
+ id: "input.remote",
+ group: FeatureGroup::Input,
+ requires: &[desktop("input.inject", UPDATE)],
+ partial: None,
+ },
+ FeatureDef {
+ id: "input.deck",
+ group: FeatureGroup::Input,
+ requires: &[desktop("deck.actions", UPDATE)],
+ partial: None,
+ },
+ // Away
+ FeatureDef {
+ id: "remote.pc_files",
+ group: FeatureGroup::Remote,
+ requires: &[
+ desktop("files.browse", UPDATE),
+ Path(ConnectionPath::Relay),
+ DeviceToggle("remote_files"),
+ ],
+ partial: None,
+ },
+];
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn facts(kind: DeviceKind, os: &str, os_ver: &str, power: PowerLevel, caps: &[&str]) -> DeviceFacts {
+ DeviceFacts {
+ kind,
+ os: os.into(),
+ os_ver: os_ver.into(),
+ caps: caps.iter().map(|c| (*c).to_owned()).collect(),
+ power,
+ }
+ }
+
+ /// What a phone at Basic offers with every Basic permission granted.
+ const BASIC_PHONE: &[&str] = &[
+ "device.ring",
+ "device.battery",
+ "notify.mirror",
+ "notify.reply",
+ "sms.read",
+ "sms.send",
+ "call.state",
+ "clip.write",
+ "clip.share",
+ "files.transfer",
+ "photos.read",
+ "mirror.capture",
+ "mirror.audio.playback",
+ "media.control",
+ "camera.stream",
+ ];
+ const PC: &[&str] =
+ &["pc.power", "files.transfer", "files.browse", "media.control", "input.inject", "deck.actions"];
+
+ fn pc() -> DeviceFacts {
+ facts(DeviceKind::Laptop, "windows", "10.0.26200", PowerLevel::NotApplicable, PC)
+ }
+
+ fn matrix_with(
+ phone: &DeviceFacts,
+ pc: &DeviceFacts,
+ toggles: &HashMap<String, bool>,
+ ) -> CapabilityMatrix {
+ let paths = [ConnectionPath::Lan];
+ compute(DeviceId([7; 32]), MatrixInputs { local: pc, peer: phone, paths: &paths, toggles })
+ }
+
+ fn matrix(phone: &DeviceFacts) -> CapabilityMatrix {
+ matrix_with(phone, &pc(), &HashMap::new())
+ }
+
+ fn locked(action: UpgradeAction, effort: Effort) -> FeatureState {
+ FeatureState::Locked { upgrade: Upgrade { action, effort } }
+ }
+
+ #[test]
+ fn basic_phone_matches_the_documented_examples() {
+ let m = matrix(&facts(DeviceKind::Phone, "android", "16", PowerLevel::Basic, BASIC_PHONE));
+ assert_eq!(m.state("clipboard.pc_to_phone"), Some(FeatureState::Available));
+ assert_eq!(
+ m.state("clipboard.auto_phone_to_pc"),
+ Some(FeatureState::Partial {
+ limit: "clipboard.limit.manual",
+ upgrade: Some(Upgrade {
+ action: UpgradeAction::RaisePower(PowerLevel::Elevated),
+ effort: Effort::Minutes(2)
+ }),
+ })
+ );
+ assert_eq!(
+ m.state("notifications.sensitive"),
+ Some(locked(UpgradeAction::RaisePower(PowerLevel::Elevated), Effort::Minutes(2)))
+ );
+ assert_eq!(
+ m.state("mirroring.control"),
+ Some(locked(UpgradeAction::RaisePower(PowerLevel::Assist), Effort::Minutes(1)))
+ );
+ assert_eq!(
+ m.state("camera.webcam"),
+ Some(locked(UpgradeAction::EnableAddon("vcam"), Effort::Minutes(1)))
+ );
+ // Away mode is off and remote files are opt-in: both are instant fixes,
+ // the first one listed is offered.
+ assert_eq!(
+ m.state("remote.pc_files"),
+ Some(locked(UpgradeAction::EnablePath(ConnectionPath::Relay), Effort::Instant))
+ );
+ }
+
+ #[test]
+ fn elevated_phone_unlocks_everything_it_offers() {
+ let mut caps = BASIC_PHONE.to_vec();
+ caps.extend([
+ "notify.sensitive",
+ "clip.read.auto",
+ "mirror.input",
+ "mirror.virtual_display",
+ "mirror.audio",
+ ]);
+ let m = matrix(&facts(DeviceKind::Phone, "android", "16", PowerLevel::Elevated, &caps));
+ for id in [
+ "notifications.sensitive",
+ "clipboard.auto_phone_to_pc",
+ "mirroring.control",
+ "mirroring.app_windows",
+ "mirroring.audio",
+ ] {
+ assert_eq!(m.state(id), Some(FeatureState::Available), "{id}");
+ }
+ }
+
+ #[test]
+ fn missing_capability_at_the_right_power_is_unsupported() {
+ // Elevated, but this phone can't do auto clipboard: manual still works.
+ let m = matrix(&facts(DeviceKind::Phone, "android", "16", PowerLevel::Elevated, BASIC_PHONE));
+ assert_eq!(
+ m.state("clipboard.auto_phone_to_pc"),
+ Some(FeatureState::Partial { limit: "clipboard.limit.manual", upgrade: None })
+ );
+ assert_eq!(
+ m.state("notifications.sensitive"),
+ Some(FeatureState::Unsupported { reason: UnsupportedReason::NotOnThisDevice })
+ );
+ }
+
+ #[test]
+ fn missing_permission_offers_the_permission() {
+ let caps: Vec<&str> = BASIC_PHONE.iter().copied().filter(|c| *c != "notify.mirror").collect();
+ let m = matrix(&facts(DeviceKind::Phone, "android", "16", PowerLevel::Basic, &caps));
+ assert_eq!(
+ m.state("notifications.mirror"),
+ Some(locked(UpgradeAction::GrantPermission(Permission::NotificationAccess), Effort::Instant))
+ );
+ }
+
+ #[test]
+ fn the_easiest_upgrade_is_offered_first() {
+ // Webcam needs the camera permission (instant) and the add-on (~1 min).
+ let caps: Vec<&str> = BASIC_PHONE.iter().copied().filter(|c| *c != "camera.stream").collect();
+ let m = matrix(&facts(DeviceKind::Phone, "android", "16", PowerLevel::Basic, &caps));
+ assert_eq!(
+ m.state("camera.webcam"),
+ Some(locked(UpgradeAction::GrantPermission(Permission::Camera), Effort::Instant))
+ );
+ }
+
+ #[test]
+ fn toggles_lock_features_and_default_sensibly() {
+ let phone = facts(DeviceKind::Phone, "android", "16", PowerLevel::Basic, BASIC_PHONE);
+ let toggles = HashMap::from([("notifications".to_owned(), false)]);
+ let m = matrix_with(&phone, &pc(), &toggles);
+ assert_eq!(
+ m.state("notifications.mirror"),
+ Some(locked(UpgradeAction::EnableDeviceToggle("notifications"), Effort::Instant))
+ );
+ assert_eq!(m.state("messages.sms"), Some(FeatureState::Available));
+ }
+
+ #[test]
+ fn old_systems_are_unsupported() {
+ let phone =
+ facts(DeviceKind::Phone, "android", "10", PowerLevel::Elevated, &["mirror.virtual_display"]);
+ let win10 =
+ facts(DeviceKind::Desktop, "windows", "10.0.19045", PowerLevel::NotApplicable, &["addon.vcam"]);
+ let m = matrix_with(&phone, &win10, &HashMap::new());
+ assert_eq!(
+ m.state("mirroring.app_windows"),
+ Some(FeatureState::Unsupported { reason: UnsupportedReason::AndroidTooOld { needs: 11 } })
+ );
+ let mut caps = BASIC_PHONE.to_vec();
+ caps.push("camera.stream");
+ let m = matrix_with(
+ &facts(DeviceKind::Phone, "android", "16", PowerLevel::Basic, &caps),
+ &win10,
+ &HashMap::new(),
+ );
+ assert_eq!(
+ m.state("camera.webcam"),
+ Some(FeatureState::Unsupported {
+ reason: UnsupportedReason::WindowsTooOld { needs_build: 22000 }
+ })
+ );
+ }
+
+ #[test]
+ fn same_on_both_devices() {
+ let phone = facts(DeviceKind::Phone, "android", "16", PowerLevel::Basic, BASIC_PHONE);
+ let pc = pc();
+ let paths = [ConnectionPath::Lan];
+ let toggles = HashMap::new();
+ let on_pc = compute(
+ DeviceId([1; 32]),
+ MatrixInputs { local: &pc, peer: &phone, paths: &paths, toggles: &toggles },
+ );
+ let on_phone = compute(
+ DeviceId([1; 32]),
+ MatrixInputs { local: &phone, peer: &pc, paths: &paths, toggles: &toggles },
+ );
+ assert_eq!(on_pc, on_phone);
+ }
+
+ #[test]
+ fn pairs_without_a_phone_and_a_desktop_are_unsupported() {
+ let m = matrix_with(&pc(), &pc(), &HashMap::new());
+ assert!(
+ m.features
+ .values()
+ .all(|s| *s == FeatureState::Unsupported { reason: UnsupportedReason::DeviceKinds })
+ );
+ }
+
+ #[test]
+ fn unknown_kinds_fall_back_to_the_os() {
+ let phone = facts(DeviceKind::Unknown, "android", "16", PowerLevel::Basic, BASIC_PHONE);
+ assert_eq!(matrix(&phone).state("device.find_phone"), Some(FeatureState::Available));
+ }
+
+ #[test]
+ fn os_versions_parse() {
+ let f = facts(DeviceKind::Desktop, "windows", "10.0.26200.6584", PowerLevel::NotApplicable, &[]);
+ assert_eq!(f.windows_build(), Some(26200));
+ let f = facts(DeviceKind::Phone, "android", "12L", PowerLevel::Basic, &[]);
+ assert_eq!(f.android_release(), Some(12));
+ let f = facts(DeviceKind::Phone, "android", "beta", PowerLevel::Basic, &[]);
+ assert_eq!(f.android_release(), None);
+ }
+
+ #[test]
+ fn sanitizes_announced_capabilities() {
+ let caps = sanitize_capabilities(
+ ["clip.write", "", "Bad.Upper", "has space", "a,b", "mirror.audio-v2_x", &"x".repeat(65)]
+ .map(str::to_owned),
+ );
+ assert_eq!(caps.into_iter().collect::<Vec<_>>(), ["clip.write", "mirror.audio-v2_x"]);
+ assert_eq!(sanitize_capabilities((0..1000).map(|i| format!("c{i}"))).len(), MAX_CAPABILITIES);
+ }
+
+ #[test]
+ fn registry_is_consistent() {
+ let mut ids = BTreeSet::new();
+ for def in FEATURES {
+ assert!(ids.insert(def.id), "duplicate feature {}", def.id);
+ let partial = def.partial.map(|p| p.requires).unwrap_or(&[]);
+ for req in def.requires.iter().chain(partial) {
+ if let Requirement::DeviceToggle(t) = req {
+ assert!(toggle_default(t).is_some(), "{}: unknown toggle {t}", def.id);
+ }
+ if let Requirement::Cap { role: Role::Desktop, unlock: Unlock::Power(_), .. } = req {
+ panic!("{}: power levels only apply to phones", def.id);
+ }
+ }
+ }
+ }
+}
diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rs
index 969f4ba..9d3893b 100644
--- a/core/nectarlink-core/src/lib.rs
+++ b/core/nectarlink-core/src/lib.rs
@@ -9,6 +9,7 @@
mod config;
mod error;
mod events;
+pub mod features;
mod identity;
mod node;
mod pairing;
@@ -20,6 +21,7 @@ pub use error::{Error, Result, Side};
pub use events::{
ConnectionPath, DiscoveredDevice, LinkState, NodeEvent, PairedDevice, PairingEvent, PairingFailure,
};
+pub use features::{CapabilityMatrix, FeatureState};
pub use identity::{KeyProtector, PlainKeyProtector, default_protector};
pub use nectarlink_protocol::{
DeviceId,
diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rs
index 761666b..79d7204 100644
--- a/core/nectarlink-core/src/node.rs
+++ b/core/nectarlink-core/src/node.rs
@@ -27,7 +27,8 @@ use tokio_util::sync::CancellationToken;
use crate::{
Error, NodeConfig, Platform, Result,
- events::{DiscoveredDevice, LinkState, NodeEvent, PairedDevice, PairingEvent},
+ events::{ConnectionPath, DiscoveredDevice, LinkState, NodeEvent, PairedDevice, PairingEvent},
+ features::{self, CapabilityMatrix, DeviceFacts, MatrixInputs},
identity,
pairing::{self, PairingState},
session::{self, CLOSE_DUPLICATE, CLOSE_NORMAL, REQUEST_TIMEOUT, Session},
@@ -85,6 +86,9 @@ pub(crate) struct Shared {
links: Mutex<HashMap<DeviceId, LinkState>>,
supervisors: Mutex<HashMap<DeviceId, Supervisor>>,
discovered: Mutex<HashMap<DeviceId, DiscoveredDevice>>,
+ /// The last capability matrix emitted per device, to emit only changes.
+ matrices: Mutex<HashMap<DeviceId, CapabilityMatrix>>,
+ away_mode: bool,
memory: MemoryLookup,
}
@@ -147,6 +151,48 @@ impl Shared {
}
}
+ /// Computes the capability matrix for a paired device from its last known
+ /// capabilities, this device's state and the user's toggles.
+ pub fn capability_matrix(&self, peer: &DeviceId) -> Result<CapabilityMatrix> {
+ let record = self.store.get_peer(peer)?.ok_or(Error::NotPaired)?;
+ let toggles = self.store.toggles(peer)?;
+ let local = {
+ let local = self.local.read().unwrap_or_else(|e| e.into_inner());
+ DeviceFacts::new(&local.device, local.capabilities().into_iter().collect(), local.power)
+ };
+ let remote = DeviceFacts::new(&record.info, record.caps, record.power);
+ let paths: &[ConnectionPath] = if self.away_mode {
+ &[ConnectionPath::Lan, ConnectionPath::Relay]
+ } else {
+ &[ConnectionPath::Lan]
+ };
+ Ok(features::compute(*peer, MatrixInputs { local: &local, peer: &remote, paths, toggles: &toggles }))
+ }
+
+ /// Recomputes a device's capability matrix and emits it if it changed.
+ pub fn refresh_capabilities(&self, peer: &DeviceId) {
+ let matrix = match self.capability_matrix(peer) {
+ Ok(matrix) => matrix,
+ Err(Error::NotPaired) => return,
+ Err(e) => {
+ tracing::warn!(peer = %peer.short(), error = %e, "failed to compute capabilities");
+ return;
+ }
+ };
+ let changed = lock(&self.matrices).insert(*peer, matrix.clone()).as_ref() != Some(&matrix);
+ if changed {
+ self.emit(NodeEvent::Capabilities(matrix));
+ }
+ }
+
+ /// Recomputes every paired device's matrix (after a local change).
+ fn refresh_all_capabilities(&self) {
+ match self.store.list_peers() {
+ Ok(peers) => peers.iter().for_each(|p| self.refresh_capabilities(&p.id)),
+ Err(e) => tracing::warn!(error = %e, "failed to list peers"),
+ }
+ }
+
/// Stores a newly paired device and starts keeping it connected.
pub async fn complete_pairing(self: &Arc<Self>, peer: DeviceId, info: DeviceInfo) -> Result<()> {
let paired_at = crate::now_unix();
@@ -170,6 +216,7 @@ impl Shared {
session.close(CLOSE_NORMAL, b"unpaired");
}
lock(&self.links).remove(peer);
+ lock(&self.matrices).remove(peer);
if existed {
self.emit(NodeEvent::DeviceRemoved(*peer));
}
@@ -216,8 +263,13 @@ impl Shared {
if let Err(e) = self.store.update_info(&peer, &remote.device) {
tracing::warn!(error = %e, "failed to update peer info");
}
+ let caps = features::sanitize_capabilities(remote.caps);
+ if let Err(e) = self.store.update_capabilities(&peer, Some(&caps), Some(remote.power.effective())) {
+ tracing::warn!(error = %e, "failed to update peer capabilities");
+ }
self.emit(NodeEvent::PeerInfoChanged { device: peer, info: remote.device });
self.emit(NodeEvent::PeerPowerChanged { device: peer, power: remote.power.effective() });
+ self.refresh_capabilities(&peer);
self.publish_online(&session);
// Bring the peer up to date with state it may have missed.
@@ -469,6 +521,8 @@ impl Node {
links: Mutex::new(HashMap::new()),
supervisors: Mutex::new(HashMap::new()),
discovered: Mutex::new(HashMap::new()),
+ matrices: Mutex::new(HashMap::new()),
+ away_mode: config.away_mode,
memory,
});
@@ -625,6 +679,42 @@ impl Node {
self.shared.session(peer).ok_or(Error::Offline)
}
+ // ---- Capabilities ----
+
+ /// What works with a paired device, and how to unlock what doesn't.
+ /// Changes arrive as [`NodeEvent::Capabilities`]. Before the device has
+ /// connected once, its capabilities are unknown and most features show
+ /// as locked.
+ pub fn capabilities(&self, peer: DeviceId) -> Result<CapabilityMatrix> {
+ self.shared.capability_matrix(&peer)
+ }
+
+ /// The per-device toggles (see [`features::DEVICE_TOGGLES`]) with their
+ /// current values.
+ pub fn device_toggles(&self, peer: DeviceId) -> Result<Vec<(&'static str, bool)>> {
+ if !self.shared.store.is_paired(&peer)? {
+ return Err(Error::NotPaired);
+ }
+ let set = self.shared.store.toggles(&peer)?;
+ Ok(features::DEVICE_TOGGLES
+ .iter()
+ .map(|(name, default)| (*name, set.get(*name).copied().unwrap_or(*default)))
+ .collect())
+ }
+
+ /// Allows or disallows something for one device, e.g. `"clipboard"`.
+ pub fn set_device_toggle(&self, peer: DeviceId, toggle: &str, enabled: bool) -> Result<()> {
+ if features::toggle_default(toggle).is_none() {
+ return Err(Error::Unsupported);
+ }
+ if !self.shared.store.is_paired(&peer)? {
+ return Err(Error::NotPaired);
+ }
+ self.shared.store.set_toggle(&peer, toggle, enabled)?;
+ self.shared.refresh_capabilities(&peer);
+ Ok(())
+ }
+
// ---- Local state reported by the app ----
/// Reports this device's battery; forwarded to connected devices.
@@ -642,9 +732,11 @@ impl Node {
if let Ok(env) = Envelope::new(types::HELLO_UPDATE, &update) {
self.shared.broadcast(env).await;
}
+ self.shared.refresh_all_capabilities();
}
- /// Updates this device's power level and extra capabilities.
+ /// Updates this device's power level and the capabilities it offers
+ /// beyond the built-in ones (they depend on permissions and add-ons).
pub async fn update_power(&self, power: PowerLevel, extra_capabilities: Vec<String>) {
let caps = {
let mut local = self.shared.local.write().unwrap_or_else(|e| e.into_inner());
@@ -656,6 +748,7 @@ impl Node {
if let Ok(env) = Envelope::new(types::HELLO_UPDATE, &update) {
self.shared.broadcast(env).await;
}
+ self.shared.refresh_all_capabilities();
}
}
diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rs
index c578d02..512cbde 100644
--- a/core/nectarlink-core/src/session.rs
+++ b/core/nectarlink-core/src/session.rs
@@ -299,9 +299,15 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->
shared.store.update_info(&peer, &info)?;
shared.emit(NodeEvent::PeerInfoChanged { device: peer, info });
}
- if let Some(power) = update.power {
- shared.emit(NodeEvent::PeerPowerChanged { device: peer, power: power.effective() });
+ let caps = update.caps.map(crate::features::sanitize_capabilities);
+ let power = update.power.map(PowerLevel::effective);
+ if caps.is_some() || power.is_some() {
+ shared.store.update_capabilities(&peer, caps.as_ref(), power)?;
}
+ if let Some(power) = power {
+ shared.emit(NodeEvent::PeerPowerChanged { device: peer, power });
+ }
+ shared.refresh_capabilities(&peer);
}
types::DEVICE_RING => {
let ring: Ring = env.body()?;
diff --git a/core/nectarlink-core/src/store.rs b/core/nectarlink-core/src/store.rs
index 4e7ab3f..20917cb 100644
--- a/core/nectarlink-core/src/store.rs
+++ b/core/nectarlink-core/src/store.rs
@@ -1,12 +1,17 @@
// SPDX-License-Identifier: MPL-2.0
-//! SQLite storage: the trust store of paired devices and their last known
-//! addresses.
+//! SQLite storage: the trust store of paired devices, their last known
+//! addresses and capabilities, and per-device settings.
-use std::{net::SocketAddr, path::Path, sync::Mutex};
+use std::{
+ collections::{BTreeSet, HashMap},
+ net::SocketAddr,
+ path::Path,
+ sync::Mutex,
+};
use nectarlink_protocol::{
DeviceId,
- messages::{DeviceInfo, DeviceKind},
+ messages::{DeviceInfo, DeviceKind, PowerLevel},
};
use rusqlite::{Connection, OptionalExtension, params};
@@ -29,6 +34,16 @@ const MIGRATIONS: &[&str] = &[
last_seen INTEGER,
last_addrs TEXT NOT NULL DEFAULT ''
) STRICT;",
+ // v2: last known capabilities and power level (for the capability matrix
+ // while a device is offline), and per-device toggles.
+ "ALTER TABLE peers ADD COLUMN caps TEXT NOT NULL DEFAULT '';
+ ALTER TABLE peers ADD COLUMN power TEXT NOT NULL DEFAULT 'basic';
+ CREATE TABLE peer_toggles (
+ peer BLOB NOT NULL REFERENCES peers(id) ON DELETE CASCADE,
+ toggle TEXT NOT NULL,
+ enabled INTEGER NOT NULL CHECK (enabled IN (0, 1)),
+ PRIMARY KEY (peer, toggle)
+ ) STRICT;",
];
/// A paired device as stored on disk.
@@ -39,6 +54,9 @@ pub(crate) struct PeerRecord {
pub paired_at: i64,
pub last_seen: Option<i64>,
pub last_addrs: Vec<SocketAddr>,
+ /// Capabilities from the device's last `hello`.
+ pub caps: BTreeSet<String>,
+ pub power: PowerLevel,
}
#[derive(Debug)]
@@ -125,6 +143,47 @@ impl Store {
})
}
+ /// Records the capabilities and power level a device last announced.
+ /// `None` keeps the stored value.
+ pub fn update_capabilities(
+ &self,
+ id: &DeviceId,
+ caps: Option<&BTreeSet<String>>,
+ power: Option<PowerLevel>,
+ ) -> Result<()> {
+ let caps = caps.map(|c| c.iter().map(String::as_str).collect::<Vec<_>>().join(","));
+ self.with(|c| {
+ c.execute(
+ "UPDATE peers SET caps = coalesce(?2, caps), power = coalesce(?3, power) WHERE id = ?1",
+ params![id.as_bytes().as_slice(), caps, power.map(power_to_str)],
+ )
+ .map(drop)
+ })
+ }
+
+ /// The per-device toggles the user has set. Unset toggles are absent;
+ /// callers apply the defaults.
+ pub fn toggles(&self, id: &DeviceId) -> Result<HashMap<String, bool>> {
+ self.with(|c| {
+ let mut stmt = c.prepare("SELECT toggle, enabled FROM peer_toggles WHERE peer = ?1")?;
+ stmt.query_map([id.as_bytes().as_slice()], |r| {
+ Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)? != 0))
+ })?
+ .collect()
+ })
+ }
+
+ pub fn set_toggle(&self, id: &DeviceId, toggle: &str, enabled: bool) -> Result<()> {
+ self.with(|c| {
+ c.execute(
+ "INSERT INTO peer_toggles (peer, toggle, enabled) VALUES (?1, ?2, ?3)
+ ON CONFLICT(peer, toggle) DO UPDATE SET enabled = excluded.enabled",
+ params![id.as_bytes().as_slice(), toggle, i64::from(enabled)],
+ )
+ .map(drop)
+ })
+ }
+
/// Removes a device. Returns whether it existed.
pub fn remove_peer(&self, id: &DeviceId) -> Result<bool> {
self.with(|c| c.execute("DELETE FROM peers WHERE id = ?1", [id.as_bytes().as_slice()]).map(|n| n > 0))
@@ -149,8 +208,8 @@ impl Store {
}
}
-const SELECT: &str =
- "SELECT id, name, kind, os, os_ver, model, accent, paired_at, last_seen, last_addrs FROM peers";
+const SELECT: &str = "SELECT id, name, kind, os, os_ver, model, accent, paired_at, last_seen, last_addrs, \
+ caps, power FROM peers";
fn row_to_peer(row: &rusqlite::Row<'_>) -> rusqlite::Result<PeerRecord> {
let id: Vec<u8> = row.get(0)?;
@@ -160,6 +219,8 @@ fn row_to_peer(row: &rusqlite::Row<'_>) -> rusqlite::Result<PeerRecord> {
let kind: String = row.get(2)?;
let accent: Option<i64> = row.get(6)?;
let addrs: String = row.get(9)?;
+ let caps: String = row.get(10)?;
+ let power: String = row.get(11)?;
Ok(PeerRecord {
id: DeviceId(id),
info: DeviceInfo {
@@ -174,9 +235,29 @@ fn row_to_peer(row: &rusqlite::Row<'_>) -> rusqlite::Result<PeerRecord> {
last_seen: row.get(8)?,
// Skip entries that no longer parse instead of failing the whole read.
last_addrs: addrs.split(',').filter_map(|a| a.parse().ok()).collect(),
+ caps: caps.split(',').filter(|c| !c.is_empty()).map(str::to_owned).collect(),
+ power: power_from_str(&power),
})
}
+fn power_to_str(power: PowerLevel) -> &'static str {
+ match power {
+ PowerLevel::Basic | PowerLevel::Unknown => "basic",
+ PowerLevel::Assist => "assist",
+ PowerLevel::Elevated => "elevated",
+ PowerLevel::NotApplicable => "n/a",
+ }
+}
+
+fn power_from_str(power: &str) -> PowerLevel {
+ match power {
+ "assist" => PowerLevel::Assist,
+ "elevated" => PowerLevel::Elevated,
+ "n/a" => PowerLevel::NotApplicable,
+ _ => PowerLevel::Basic,
+ }
+}
+
fn kind_to_str(kind: DeviceKind) -> &'static str {
match kind {
DeviceKind::Phone => "phone",
@@ -258,6 +339,56 @@ mod tests {
assert!(store.list_peers().unwrap().is_empty());
}
+ #[test]
+ fn capabilities_and_toggles() {
+ let store = Store::in_memory().unwrap();
+ let id = DeviceId([3; 32]);
+ store.upsert_peer(&id, &info("Pixel"), 1).unwrap();
+ let peer = store.get_peer(&id).unwrap().unwrap();
+ assert!(peer.caps.is_empty());
+ assert_eq!(peer.power, PowerLevel::Basic);
+
+ let caps: BTreeSet<String> = ["clip.write".to_owned(), "device.ring".to_owned()].into();
+ store.update_capabilities(&id, Some(&caps), Some(PowerLevel::Elevated)).unwrap();
+ // None keeps what's stored.
+ store.update_capabilities(&id, None, None).unwrap();
+ let peer = store.get_peer(&id).unwrap().unwrap();
+ assert_eq!(peer.caps, caps);
+ assert_eq!(peer.power, PowerLevel::Elevated);
+ store.update_capabilities(&id, Some(&BTreeSet::new()), None).unwrap();
+ assert!(store.get_peer(&id).unwrap().unwrap().caps.is_empty());
+
+ assert!(store.toggles(&id).unwrap().is_empty());
+ store.set_toggle(&id, "clipboard", false).unwrap();
+ store.set_toggle(&id, "clipboard", true).unwrap();
+ store.set_toggle(&id, "photos", false).unwrap();
+ let toggles = store.toggles(&id).unwrap();
+ assert_eq!(toggles.len(), 2);
+ assert_eq!(toggles.get("clipboard"), Some(&true));
+ assert_eq!(toggles.get("photos"), Some(&false));
+
+ // Unpairing forgets the device's settings too.
+ store.remove_peer(&id).unwrap();
+ assert!(store.toggles(&id).unwrap().is_empty());
+ }
+
+ #[test]
+ fn upgrades_a_version_1_database() {
+ let conn = Connection::open_in_memory().unwrap();
+ conn.execute_batch(MIGRATIONS[0]).unwrap();
+ conn.pragma_update(None, "user_version", 1).unwrap();
+ conn.execute(
+ "INSERT INTO peers (id, name, kind, os, os_ver, paired_at) VALUES (?1, 'Old', 'phone', 'android', '15', 5)",
+ [[9u8; 32].as_slice()],
+ )
+ .unwrap();
+ let store = Store::init(conn).unwrap();
+ let peer = store.get_peer(&DeviceId([9; 32])).unwrap().unwrap();
+ assert_eq!(peer.info.name, "Old");
+ assert!(peer.caps.is_empty());
+ assert_eq!(peer.power, PowerLevel::Basic);
+ }
+
#[test]
fn lists_in_pairing_order_and_persists() {
let dir = tempfile::tempdir().unwrap();
diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rs
index a4a933c..a63c3f4 100644
--- a/core/nectarlink-core/tests/two_devices.rs
+++ b/core/nectarlink-core/tests/two_devices.rs
@@ -9,8 +9,9 @@ use std::{
};
use nectarlink_core::{
- Battery, DeviceInfo, DeviceKind, Error, LinkState, Node, NodeConfig, NodeEvent, PairingEvent,
- PairingFailure, PairingUri, PlainKeyProtector, Platform,
+ Battery, DeviceInfo, DeviceKind, Error, FeatureState, LinkState, Node, NodeConfig, NodeEvent,
+ PairingEvent, PairingFailure, PairingUri, PlainKeyProtector, Platform, PowerLevel,
+ features::{Effort, Upgrade, UpgradeAction},
};
use tempfile::TempDir;
use tokio::sync::broadcast::Receiver;
@@ -325,3 +326,67 @@ async fn reconnects_after_a_restart() {
wait_online(&mut pc, phone_id).await;
with_timeout("ring after reconnect", pc.node.ring(phone_id, true)).await.expect("ring works again");
}
+
+/// Waits for a capability matrix of `peer` whose `feature` is in a state
+/// matching `want`.
+async fn wait_feature(
+ dev: &mut TestDevice,
+ peer: nectarlink_core::DeviceId,
+ feature: &str,
+ want: impl Fn(&FeatureState) -> bool,
+) -> FeatureState {
+ wait_for(dev, feature, |e| match e {
+ NodeEvent::Capabilities(m) if m.device == peer => m.state(feature).filter(|s| want(s)),
+ _ => None,
+ })
+ .await
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn capabilities_follow_power_and_toggles() {
+ 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());
+
+ // Right after connecting, the PC knows what the phone offers.
+ let matrix = pc.node.capabilities(phone_id).unwrap();
+ assert_eq!(matrix.state("device.find_phone"), Some(FeatureState::Available));
+ let elevated =
+ Upgrade { action: UpgradeAction::RaisePower(PowerLevel::Elevated), effort: Effort::Minutes(2) };
+ assert_eq!(matrix.state("clipboard.auto_phone_to_pc"), Some(FeatureState::Locked { upgrade: elevated }));
+ // Both devices compute the same matrix for the pair.
+ assert_eq!(phone.node.capabilities(pc_id).unwrap().features, matrix.features);
+
+ // The phone is raised to Elevated and now offers automatic clipboard.
+ phone.node.update_power(PowerLevel::Elevated, vec!["clip.read.auto".into(), "clip.write".into()]).await;
+ wait_feature(&mut pc, phone_id, "clipboard.auto_phone_to_pc", |s| *s == FeatureState::Available).await;
+
+ // The PC user turns clipboard off for this phone.
+ pc.node.set_device_toggle(phone_id, "clipboard", false).unwrap();
+ let state =
+ wait_feature(&mut pc, phone_id, "clipboard.pc_to_phone", |s| *s != FeatureState::Available).await;
+ assert_eq!(
+ state,
+ FeatureState::Locked {
+ upgrade: Upgrade {
+ action: UpgradeAction::EnableDeviceToggle("clipboard"),
+ effort: Effort::Instant
+ }
+ }
+ );
+ let toggles = pc.node.device_toggles(phone_id).unwrap();
+ assert!(toggles.contains(&("clipboard", false)) && toggles.contains(&("photos", true)));
+ assert!(matches!(pc.node.set_device_toggle(phone_id, "no-such-toggle", true), Err(Error::Unsupported)));
+
+ // What the phone offered is remembered while it's offline.
+ phone.node.shutdown().await;
+ wait_for(&mut pc, "peer offline", |e| match e {
+ NodeEvent::LinkChanged { device, link: LinkState::Offline { .. } } if *device == phone_id => Some(()),
+ _ => None,
+ })
+ .await;
+ pc.node.set_device_toggle(phone_id, "clipboard", true).unwrap();
+ let matrix = pc.node.capabilities(phone_id).unwrap();
+ assert_eq!(matrix.state("clipboard.auto_phone_to_pc"), Some(FeatureState::Available));
+}
diff --git a/docs/architecture/capabilities.md b/docs/architecture/capabilities.md
index 4ed8f8a..a481b2e 100644
--- a/docs/architecture/capabilities.md
+++ b/docs/architecture/capabilities.md
@@ -3,30 +3,33 @@
The capability matrix decides, for every feature and every paired device,
whether the feature is **Available**, **Partial**, **Locked** or
**Unsupported**, and what the user can do about it. Both apps render their UI
-from the same matrix, computed by `nectarlink-core`, so the phone and PC can
-never disagree about what works.
+from the matrix, computed by `nectarlink-core` (`features.rs`), so the phone
+and PC agree about what works.
## Inputs
| Input | Source |
|---|---|
-| Peer capabilities | The peer's `hello.caps` (protocol §6) |
-| Local capabilities | This device's own state (permissions, add-ons, OS version) |
-| Power level | The phone's `hello.power` |
-| Connection paths | Which paths are active (LAN, USB, relay) |
-| Per-device permissions | The user's toggles for this paired device |
-| Feature registry | Static definitions compiled into the core (below) |
+| Capabilities of both devices | Each device's `hello.caps` / `hello.update` (protocol §6, registry in `docs/protocol/capabilities.md`); the peer's are stored, so the matrix also works while it is offline |
+| Phone power level | The phone's `hello.power` |
+| OS versions | `DeviceInfo.os_ver`: Android release (`"16"`), Windows build (`"10.0.26200"`) |
+| Enabled connection paths | LAN always; relay when Away mode is on |
+| Per-device toggles | The user's switches for this paired device (`DEVICE_TOGGLES`) |
+| Feature registry | Static definitions compiled into the core (`FEATURES`) |
-The matrix is recomputed whenever any input changes and is pushed to the UI
-as an event.
+The matrix is recomputed whenever an input changes and emitted as
+`NodeEvent::Capabilities` only when it actually changed. `Node::capabilities`
+returns it on demand.
## Feature definitions
-Each feature is declared once, in Rust, in `nectarlink-core::features`:
+Each feature is declared once, in Rust. Requirements name the **phone** and
+the **desktop**, never "local" and "peer": the same definitions evaluated on
+either device give the same answer.
```rust
pub struct FeatureDef {
- pub id: FeatureId, // e.g. "clipboard.auto_phone_to_pc"
+ pub id: &'static str, // e.g. "clipboard.auto_phone_to_pc"
pub group: FeatureGroup, // Notifications, Clipboard, Files, Mirroring…
/// Every requirement must hold for the feature to be Available.
pub requires: &'static [Requirement],
@@ -35,19 +38,26 @@ pub struct FeatureDef {
}
pub enum Requirement {
- PeerCap(&'static str), // peer offers a capability ID
- LocalCap(&'static str), // this device offers a capability ID
- PowerAtLeast(PowerLevel), // Basic < Assist < Elevated
- AndroidApiAtLeast(u32),
- WindowsBuildAtLeast(u32),
- Path(ConnectionPath), // e.g. Usb, Relay
+ /// The device in `role` (Phone or Desktop) announces capability `id`.
+ /// `unlock` says how a missing capability is obtained.
+ Cap { role: Role, id: &'static str, unlock: Unlock },
+ PowerAtLeast(PowerLevel), // phone: Basic < Assist < Elevated
+ AndroidAtLeast(u32), // phone's Android release
+ WindowsBuildAtLeast(u32), // desktop's Windows build
+ Path(ConnectionPath), // e.g. Relay (Away mode)
DeviceToggle(&'static str), // per-device user permission
- Addon(&'static str), // e.g. "vcam", "explorer", "hfp"
+}
+
+pub enum Unlock {
+ Power(PowerLevel), // the phone offers it from this level on
+ Permission(Permission), // … once this Android permission is granted
+ Addon(&'static str), // the desktop offers it once the add-on is installed
+ UpdateApp, // every current app offers it: that app is too old
}
pub struct PartialDef {
pub requires: &'static [Requirement],
- pub limit: &'static str, // translation key, e.g. "clip.partial.manual"
+ pub limit: &'static str, // translation key, e.g. "clipboard.limit.manual"
}
```
@@ -56,54 +66,82 @@ pub struct PartialDef {
```rust
pub enum FeatureState {
Available,
- /// Works, with a limitation shown inline, plus how to remove it.
- Partial { limit: MessageKey, upgrade: Option<Upgrade> },
+ /// Works, with a limitation shown inline, plus how to remove it (if possible).
+ Partial { limit: &'static str, upgrade: Option<Upgrade> },
/// Doesn't work yet, but the user can unlock it.
Locked { upgrade: Upgrade },
- /// Can't work on this device combination; explained, not actionable.
- Unsupported { reason: MessageKey },
+ /// Can't work on this device pair; explained, not actionable.
+ Unsupported { reason: UnsupportedReason },
}
-pub struct Upgrade {
- pub action: UpgradeAction, // which setup sheet to open
- pub effort: Effort, // e.g. Minutes(2), Instant
-}
+pub struct Upgrade { pub action: UpgradeAction, pub effort: Effort } // Effort: Instant | Minutes(n)
pub enum UpgradeAction {
- RaisePower(PowerLevel), // open "Choose your power" at that level
- GrantPermission(Permission), // e.g. notification access
- EnableAddon(&'static str), // e.g. install the virtual camera
- EnablePath(ConnectionPath), // e.g. turn on Away mode
- EnableDeviceToggle(&'static str), // flip a per-device permission
- UpdateApp(DeviceSide), // peer or local app too old
+ RaisePower(PowerLevel), // open "Choose your power" at that level (Assist ~1 min, Elevated ~2 min)
+ GrantPermission(Permission), // e.g. notification access (instant)
+ EnableAddon(&'static str), // e.g. install the virtual camera (~1 min)
+ EnablePath(ConnectionPath), // e.g. turn on Away mode (instant)
+ EnableDeviceToggle(&'static str), // flip a per-device permission (instant)
+ UpdateApp(Role), // that device's app is too old (~2 min)
+}
+
+pub enum UnsupportedReason {
+ DeviceKinds, // the pair isn't one phone + one desktop
+ AndroidTooOld { needs: u32 },
+ WindowsTooOld { needs_build: u32 },
+ NotOnThisDevice, // right power level, still not offered (hardware/OEM)
}
```
+### How each requirement is checked
+
+- `Cap`: met if announced. Otherwise, by `unlock`: `Power(level)` gives
+ `RaisePower(level)` if the phone is below that level, and
+ `NotOnThisDevice` if it already has it; the others give the matching
+ upgrade.
+- `AndroidAtLeast` / `WindowsBuildAtLeast`: an older OS can't be fixed, so the
+ requirement is impossible. An unparseable version doesn't block anything.
+- `Path`, `DeviceToggle`, `PowerAtLeast`: give the matching upgrade.
+
### How a state is chosen
-1. If any requirement is impossible on this device pair (OS version too old,
- hardware missing), the state is **Unsupported**.
-2. Else, if all `requires` hold: **Available**.
-3. Else, if a `partial` set holds: **Partial**, with an `upgrade` pointing at
- the first unmet requirement of the full set.
-4. Else: **Locked**, with an `upgrade` for the first unmet requirement. When
- several requirements are unmet, the one with the lowest effort is offered
- first.
+1. All `requires` hold: **Available**.
+2. Else, if a `partial` set holds: **Partial**. Part of the feature works, so
+ this wins even when the rest never will; `upgrade` is the easiest unmet
+ requirement of the full set, or none if one of them is impossible.
+3. Else, if any requirement is impossible: **Unsupported**, with the first
+ reason.
+4. Else: **Locked**, with the lowest-effort upgrade among the unmet
+ requirements (declaration order breaks ties).
+
+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).
+
+## Per-device toggles
-## Examples
+`notifications`, `messages`, `calls`, `clipboard`, `photos`, `pc_actions`
+(on by default) and `remote_files` (off by default). Toggles are this
+device's policy for that peer and are stored locally, so a feature the PC
+user switched off is Locked on the PC while the phone may still show it as
+Available. Everything else in the matrix is identical on both devices.
-| Feature | Requires | Partial | Typical state at Basic |
+## Examples (phone at Basic, all Basic permissions granted)
+
+| Feature | Requires | Partial | State |
|---|---|---|---|
-| `clipboard.pc_to_phone` | `PeerCap("clip.write")` | – | Available |
-| `clipboard.auto_phone_to_pc` | `PeerCap("clip.read.auto")` (needs Elevated) | `PeerCap("clip.share")` → "Manual: tap to send" | Partial, upgrade → Elevated · ~2 min |
-| `notifications.sensitive` | `PeerCap("notify.sensitive")` | – | Locked, upgrade → Elevated · ~2 min |
-| `mirroring.app_windows` | `PeerCap("mirror.virtual_display")`, `PowerAtLeast(Elevated)` | – | Locked |
-| `mirroring.control` | `PeerCap("mirror.input")` | – | Locked → Assist · ~1 min (or Elevated) |
-| `camera.webcam` | `PeerCap("camera.stream")`, `Addon("vcam")`, `WindowsBuildAtLeast(22000)` | – | Locked → install virtual camera |
+| `clipboard.pc_to_phone` | phone `clip.write`, toggle `clipboard` | – | Available |
+| `clipboard.auto_phone_to_pc` | phone `clip.read.auto` (Elevated), toggle | phone `clip.share` → "Manual: tap to send" | Partial, upgrade → Elevated · ~2 min |
+| `notifications.sensitive` | phone `notify.sensitive` (Elevated), toggle | – | Locked → Elevated · ~2 min |
+| `mirroring.control` | phone `mirror.capture`, `mirror.input` (Assist) | – | Locked → Assist · ~1 min |
+| `mirroring.app_windows` | phone `mirror.virtual_display` (Elevated), Elevated, Android ≥ 11 | – | Locked → Elevated |
+| `camera.webcam` | phone `camera.stream` (camera permission), desktop `addon.vcam`, Windows build ≥ 22000 | – | Locked → install virtual camera · ~1 min |
+
+The full registry is `FEATURES` in `core/nectarlink-core/src/features.rs`.
## UI contract
-- Both UIs receive `CapabilityMatrix { device_id, features: Map<FeatureId, FeatureState> }`.
+- Both UIs receive `CapabilityMatrix { device, features: Map<FeatureId, FeatureState> }`.
- **Available:** normal control.
- **Partial:** normal control plus an inline hint (`limit`) and, if present, an
"Unlock" affordance.
diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.md
new file mode 100644
index 0000000..ab6b5f3
--- /dev/null
+++ b/docs/protocol/capabilities.md
@@ -0,0 +1,56 @@
+# Capability registry
+
+Capability IDs a device may announce in `hello.caps` and `hello.update`
+(protocol §5–6). A device announces a capability only when it can provide it
+**right now**: with its current power level, permissions, add-ons and OS
+version.
+
+IDs are lowercase dotted strings (`[a-z0-9._-]`, at most 64 bytes). Receivers
+ignore malformed IDs, IDs they don't know, and anything beyond 256 entries.
+New IDs may be added in any release; an ID is never reused with a different
+meaning.
+
+The capability matrix (`docs/architecture/capabilities.md`) turns these into
+feature states. "Unlocked by" is what the matrix offers the user when the
+capability is missing.
+
+## Both devices
+
+| ID | Meaning | Unlocked by |
+|---|---|---|
+| `core.ping` | Answers `ping` | always offered |
+| `device.battery` | Sends `event.battery` | always offered |
+| `device.ring` | Rings on `device.ring`, even on silent | always offered |
+| `files.transfer` | Sends and receives files | app update |
+| `media.control` | Exposes its media sessions for remote control (phone: needs notification access) | phone: notification access · desktop: app update |
+
+## Phone
+
+| ID | Meaning | Unlocked by |
+|---|---|---|
+| `notify.mirror` | Forwards notifications | 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 |
+| `sms.read` | Reads SMS conversations | SMS permission |
+| `sms.send` | Sends SMS | SMS permission |
+| `call.state` | Reports incoming and ongoing calls | phone permission |
+| `clip.write` | Accepts clipboard content from the PC | app update |
+| `clip.share` | Sends the clipboard when the user taps "Send" | app update |
+| `clip.read.auto` | Sends clipboard changes automatically, in the background | Elevated |
+| `photos.read` | Lists and sends recent photos and screenshots | photos permission |
+| `mirror.capture` | Streams its screen (with the system's capture prompt at Basic) | app update |
+| `mirror.input` | Accepts touch, key and scroll input while mirrored | Assist |
+| `mirror.virtual_display` | Runs apps on a separate virtual display (app windows) | Elevated |
+| `mirror.audio` | Streams all audio while mirrored | Elevated |
+| `mirror.audio.playback` | Streams audio from apps that allow playback capture | app update |
+| `camera.stream` | Streams a camera for webcam use | camera permission |
+
+## Desktop
+
+| ID | Meaning | Unlocked by |
+|---|---|---|
+| `pc.power` | Locks, sleeps or shuts down on request | app update |
+| `files.browse` | Lets a paired phone browse and fetch its files | app update |
+| `input.inject` | Accepts pointer and keyboard input (touchpad, air mouse, voice typing) | app update |
+| `deck.actions` | Runs Deck actions | app update |
+| `addon.vcam` | The virtual camera add-on is installed | installing the add-on |
diff --git a/docs/protocol/v0.md b/docs/protocol/v0.md
index deca5c1..d269b6f 100644
--- a/docs/protocol/v0.md
+++ b/docs/protocol/v0.md
@@ -147,8 +147,9 @@ b = { caps: [text]?, power: text?, device: DeviceInfo? }
## 6. Capabilities
-A capability ID is a dotted string naming something a device *can offer*,
-for example:
+A capability ID is a lowercase dotted string (`[a-z0-9._-]`, at most 64
+bytes) naming something a device *can offer*. Receivers ignore malformed and
+unknown IDs and anything beyond 256 entries. Examples:
| Capability | Offered by | Meaning |
|---|---|---|
@@ -157,7 +158,7 @@ for example:
| `notify.mirror` | phone | Can forward notifications |
| `notify.sensitive` | phone | Can forward sensitive (OTP) notifications |
| `clip.read.auto` | phone | Can read the clipboard in the background |
-| `mirror.elevated` | phone | Prompt-free mirroring with full control |
+| `mirror.input` | phone | Accepts input while mirrored (Assist and up) |
Capabilities describe **what the device can do right now** given its power
level, OS version, permissions and add-ons. Each app combines both devices'