From fd3bdede59613fefd25293944b8946ed4a025466 Mon Sep 17 00:00:00 2001 From: Samarth Rajesh Lad <142334685+samyyy2311@users.noreply.github.com> Date: Thu, 8 Oct 2026 03:18:44 +0530 Subject: [PATCH 01/14] Add continuity capabilities, device telemetry, and pairing tools - Add media control, handoff, and telemetry protocol definitions and session dispatchers. - Add continuity camera capture framing and DIBV5 format translation. - Add 4-word verification phrase derivation (SAS) for pairing confirmation. - Add offline transfer queue for staging transfers destined for unreachable peers. - Add lockdown mode in permissions store to immediately deny all grants when active. - Add notification actions for extracted OTPs and inbound camera photos. - Add LocalSend v2 discovery and upload bridge. - Add connection doctor network diagnostics and wireless debugging discovery. --- Cargo.lock | 9 + Cargo.toml | 1 + crates/clipboard/src/context.rs | 175 +++++++++ crates/clipboard/src/error.rs | 3 + crates/clipboard/src/guard.rs | 56 +++ crates/clipboard/src/lib.rs | 4 + crates/clipboard/src/sync.rs | 23 ++ crates/discovery/Cargo.toml | 2 + crates/discovery/src/adb_browser.rs | 88 +++++ crates/discovery/src/doctor.rs | 170 ++++++++ crates/discovery/src/lib.rs | 14 + crates/discovery/src/localsend.rs | 102 +++++ crates/limits/src/lib.rs | 18 + crates/notifications/src/lib.rs | 9 + crates/notifications/src/media_push.rs | 130 ++++++ crates/notifications/src/otp.rs | 92 +++++ crates/notifications/src/task.rs | 88 +++++ crates/pairing/Cargo.toml | 9 +- crates/pairing/src/adb_pairing.rs | 284 ++++++++++++++ crates/pairing/src/error.rs | 9 + crates/pairing/src/lib.rs | 4 + crates/pairing/src/words.rs | 131 +++++++ crates/permissions/src/store.rs | 77 +++- crates/protocol/build.rs | 4 + crates/protocol/src/capability.rs | 8 + crates/sessions/src/capabilities_router.rs | 165 ++++++++ crates/sessions/src/error.rs | 12 + crates/sessions/src/handoff.rs | 324 +++++++++++++++ crates/sessions/src/lib.rs | 6 + crates/sessions/src/media_control.rs | 274 +++++++++++++ crates/sessions/src/telemetry.rs | 221 +++++++++++ crates/transfer/Cargo.toml | 5 +- crates/transfer/src/capture.rs | 348 +++++++++++++++++ crates/transfer/src/error.rs | 18 + crates/transfer/src/lib.rs | 13 + crates/transfer/src/localsend_bridge.rs | 235 +++++++++++ crates/transfer/src/queue.rs | 434 +++++++++++++++++++++ crates/transfer/tests/capture_e2e.rs | 178 +++++++++ proto/handoff.proto | 46 +++ proto/media_capture.proto | 54 +++ proto/media_control.proto | 61 +++ proto/telemetry.proto | 46 +++ 42 files changed, 3947 insertions(+), 3 deletions(-) create mode 100644 crates/clipboard/src/context.rs create mode 100644 crates/clipboard/src/guard.rs create mode 100644 crates/discovery/src/adb_browser.rs create mode 100644 crates/discovery/src/doctor.rs create mode 100644 crates/discovery/src/localsend.rs create mode 100644 crates/notifications/src/media_push.rs create mode 100644 crates/notifications/src/otp.rs create mode 100644 crates/notifications/src/task.rs create mode 100644 crates/pairing/src/adb_pairing.rs create mode 100644 crates/pairing/src/words.rs create mode 100644 crates/sessions/src/handoff.rs create mode 100644 crates/sessions/src/media_control.rs create mode 100644 crates/sessions/src/telemetry.rs create mode 100644 crates/transfer/src/capture.rs create mode 100644 crates/transfer/src/localsend_bridge.rs create mode 100644 crates/transfer/src/queue.rs create mode 100644 crates/transfer/tests/capture_e2e.rs create mode 100644 proto/handoff.proto create mode 100644 proto/media_capture.proto create mode 100644 proto/media_control.proto create mode 100644 proto/telemetry.proto diff --git a/Cargo.lock b/Cargo.lock index 4327583..f52dcd4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -583,6 +583,8 @@ dependencies = [ "limits", "mdns-sd", "rand 0.8.8", + "serde", + "serde_json", "thiserror 1.0.69", "tokio", "tracing", @@ -1225,13 +1227,17 @@ dependencies = [ "base64", "crypto", "ed25519-dalek", + "hkdf", "identity", "limits", "protocol", "quinn", "rand 0.8.8", "rusqlite", + "sha2", + "subtle", "thiserror 1.0.69", + "tokio", "transport", "x25519-dalek", "zeroize", @@ -2310,6 +2316,7 @@ dependencies = [ name = "transfer" version = "0.1.0" dependencies = [ + "bytes", "hex", "limits", "protocol", @@ -2317,6 +2324,8 @@ dependencies = [ "rand 0.8.8", "rcgen", "rustls", + "serde", + "serde_json", "sha2", "thiserror 1.0.69", "tokio", diff --git a/Cargo.toml b/Cargo.toml index 75b5478..b6aa7a0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -66,6 +66,7 @@ rusqlite = { version = "0.31", features = ["bundled"] } # Serialization serde = { version = "1", features = ["derive"] } +serde_json = "1" # Error handling thiserror = "1" diff --git a/crates/clipboard/src/context.rs b/crates/clipboard/src/context.rs new file mode 100644 index 0000000..88aaab1 --- /dev/null +++ b/crates/clipboard/src/context.rs @@ -0,0 +1,175 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ContextAction { + OpenUrl(String), + CopyOtp(String), + CallPhone(String), + TrackPackage { carrier: &'static str, tracking_number: String }, +} + +pub fn classify_context(text: &str) -> Option { + let trimmed = text.trim(); + if trimmed.is_empty() || trimmed.len() > 1024 { + return None; + } + + if let Some(url) = detect_url(trimmed) { + return Some(ContextAction::OpenUrl(url)); + } + + if let Some(tracking) = detect_tracking(trimmed) { + return Some(tracking); + } + + if let Some(otp) = detect_otp(trimmed) { + return Some(ContextAction::CopyOtp(otp)); + } + + if let Some(phone) = detect_phone(trimmed) { + return Some(ContextAction::CallPhone(phone)); + } + + None +} + +fn detect_url(s: &str) -> Option { + if (s.starts_with("http://") || s.starts_with("https://")) && !s.contains(' ') { + let host = s.split_once("://")?.1; + if host.contains('.') && !host.starts_with('.') { + return Some(s.to_string()); + } + } + None +} + +fn detect_tracking(s: &str) -> Option { + let raw: String = s.chars().filter(|c| !c.is_whitespace() && *c != '-').collect(); + + if raw.len() == 18 + && raw[..2].eq_ignore_ascii_case("1Z") + && raw[2..].chars().all(|c| c.is_ascii_alphanumeric()) + { + return Some(ContextAction::TrackPackage { + carrier: "UPS", + tracking_number: raw.to_ascii_uppercase(), + }); + } + + if (raw.len() == 12 || raw.len() == 15) && raw.chars().all(|c| c.is_ascii_digit()) { + return Some(ContextAction::TrackPackage { + carrier: "FedEx", + tracking_number: raw, + }); + } + + if (raw.len() == 20 || raw.len() == 22) + && (raw.starts_with("94") || raw.starts_with("92") || raw.starts_with("93")) + && raw.chars().all(|c| c.is_ascii_digit()) + { + return Some(ContextAction::TrackPackage { + carrier: "USPS", + tracking_number: raw, + }); + } + + None +} + +fn detect_otp(s: &str) -> Option { + let digits: String = s.chars().filter(|c| c.is_ascii_digit()).collect(); + + if s.chars().all(|c| c.is_ascii_digit() || c == '-' || c.is_whitespace()) + && digits.len() >= 4 + && digits.len() <= 8 + { + return Some(digits); + } + + let lower = s.to_ascii_lowercase(); + let has_keyword = ["code", "otp", "verification", "passcode"] + .iter() + .any(|kw| lower.contains(kw)); + + if has_keyword { + for token in s.split(|c: char| c.is_whitespace() || c == ':' || c == '.' || c == ',') { + let token_digits: String = token.chars().filter(|c| c.is_ascii_digit()).collect(); + if token_digits.len() >= 4 && token_digits.len() <= 8 && token_digits == token.trim_matches(|c: char| !c.is_ascii_digit()) { + return Some(token_digits); + } + } + } + + None +} + +fn detect_phone(s: &str) -> Option { + let valid_start = s.starts_with('+') || s.starts_with('(') || s.chars().next().is_some_and(|c| c.is_ascii_digit()); + if !valid_start { + return None; + } + + let digits = s.chars().filter(|c| c.is_ascii_digit()).count(); + let valid_chars = s.chars().all(|c| c.is_ascii_digit() || c == '+' || c == '-' || c == '(' || c == ')' || c == '.' || c.is_whitespace()); + + if valid_chars && (7..=15).contains(&digits) && s.len() <= 24 { + return Some(s.to_string()); + } + + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn classifies_urls() { + assert_eq!( + classify_context("https://github.com/thtbee/nectarlink"), + Some(ContextAction::OpenUrl("https://github.com/thtbee/nectarlink".to_string())) + ); + } + + #[test] + fn classifies_otp() { + assert_eq!( + classify_context("849201"), + Some(ContextAction::CopyOtp("849201".to_string())) + ); + assert_eq!( + classify_context("582-194"), + Some(ContextAction::CopyOtp("582194".to_string())) + ); + assert_eq!( + classify_context("Your verification code is 492019"), + Some(ContextAction::CopyOtp("492019".to_string())) + ); + } + + #[test] + fn classifies_tracking() { + assert_eq!( + classify_context("1z9999999999999999"), + Some(ContextAction::TrackPackage { + carrier: "UPS", + tracking_number: "1Z9999999999999999".to_string(), + }) + ); + } + + #[test] + fn classifies_phone() { + assert_eq!( + classify_context("+1 (555) 234-5678"), + Some(ContextAction::CallPhone("+1 (555) 234-5678".to_string())) + ); + } + + #[test] + fn ignores_regular_text() { + assert_eq!(classify_context("Regular sentence without actionable tokens."), None); + assert_eq!(classify_context(""), None); + } +} diff --git a/crates/clipboard/src/error.rs b/crates/clipboard/src/error.rs index 23b14c2..4152b67 100644 --- a/crates/clipboard/src/error.rs +++ b/crates/clipboard/src/error.rs @@ -23,6 +23,9 @@ pub enum ClipboardError { #[error("Rejected by peer: {0}")] Rejected(String), + #[error("Clipboard content excluded from synchronization")] + SensitiveExcluded, + #[error("I/O error: {0}")] Io(#[from] std::io::Error), } diff --git a/crates/clipboard/src/guard.rs b/crates/clipboard/src/guard.rs new file mode 100644 index 0000000..07b06ae --- /dev/null +++ b/crates/clipboard/src/guard.rs @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +const SENSITIVE_FORMATS: &[&str] = &[ + "ExcludeClipboardContentFromMonitorProcessing", + "Clipboard Viewer Ignore", +]; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SensitiveGuardDecision { + Allow, + DropSensitive, +} + +pub fn evaluate_clipboard_formats(available_formats: I) -> SensitiveGuardDecision +where + I: IntoIterator, + S: AsRef, +{ + for format in available_formats { + let name = format.as_ref(); + if SENSITIVE_FORMATS.iter().any(|&s| name.eq_ignore_ascii_case(s)) { + return SensitiveGuardDecision::DropSensitive; + } + } + SensitiveGuardDecision::Allow +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn allows_regular_formats() { + assert_eq!( + evaluate_clipboard_formats(["CF_UNICODETEXT", "CF_TEXT"]), + SensitiveGuardDecision::Allow + ); + } + + #[test] + fn drops_sensitive_formats() { + assert_eq!( + evaluate_clipboard_formats(["CF_UNICODETEXT", "Clipboard Viewer Ignore"]), + SensitiveGuardDecision::DropSensitive + ); + assert_eq!( + evaluate_clipboard_formats(["ExcludeClipboardContentFromMonitorProcessing"]), + SensitiveGuardDecision::DropSensitive + ); + assert_eq!( + evaluate_clipboard_formats(["clipboard viewer ignore"]), + SensitiveGuardDecision::DropSensitive + ); + } +} diff --git a/crates/clipboard/src/lib.rs b/crates/clipboard/src/lib.rs index 62e9110..d67e630 100644 --- a/crates/clipboard/src/lib.rs +++ b/crates/clipboard/src/lib.rs @@ -1,9 +1,13 @@ // SPDX-FileCopyrightText: Contributors to the Continue project // SPDX-License-Identifier: Apache-2.0 +pub mod context; pub mod error; +pub mod guard; pub mod sync; +pub use context::{classify_context, ContextAction}; pub use error::ClipboardError; +pub use guard::{evaluate_clipboard_formats, SensitiveGuardDecision}; pub use protocol::v1::{ClipboardAck, ClipboardFormat, ClipboardUpdate}; pub use sync::ClipboardSynchronizer; diff --git a/crates/clipboard/src/sync.rs b/crates/clipboard/src/sync.rs index cfc9251..c17ad24 100644 --- a/crates/clipboard/src/sync.rs +++ b/crates/clipboard/src/sync.rs @@ -50,6 +50,29 @@ impl ClipboardSynchronizer { lock.contains(hash) } + pub async fn send_guarded_update( + &self, + stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + format: ClipboardFormat, + payload: Vec, + available_formats: I, + query: &CapabilityQuery, + ) -> Result + where + I: IntoIterator, + S: AsRef, + { + if matches!( + crate::guard::evaluate_clipboard_formats(available_formats), + crate::guard::SensitiveGuardDecision::DropSensitive + ) { + return Err(ClipboardError::SensitiveExcluded); + } + + self.send_update(stream, recv_stream, format, payload, query).await + } + pub async fn send_update( &self, stream: &mut quinn::SendStream, diff --git a/crates/discovery/Cargo.toml b/crates/discovery/Cargo.toml index a25b31c..73fbd17 100644 --- a/crates/discovery/Cargo.toml +++ b/crates/discovery/Cargo.toml @@ -13,3 +13,5 @@ rand = { workspace = true } hex = { workspace = true } thiserror = { workspace = true } tracing = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } diff --git a/crates/discovery/src/adb_browser.rs b/crates/discovery/src/adb_browser.rs new file mode 100644 index 0000000..a3c2b99 --- /dev/null +++ b/crates/discovery/src/adb_browser.rs @@ -0,0 +1,88 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use mdns_sd::{Receiver, ServiceDaemon, ServiceEvent, ServiceInfo}; +use std::collections::HashSet; +use std::net::{IpAddr, SocketAddr}; + +use crate::error::DiscoveryError; + +pub const ADB_TLS_PAIRING_SERVICE: &str = "_adb-tls-pairing._tcp.local."; +pub const ADB_TLS_CONNECT_SERVICE: &str = "_adb-tls-connect._tcp.local."; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AdbServiceType { + Pairing, + Connect, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DiscoveredAdbService { + pub service_type: AdbServiceType, + pub instance_name: String, + pub addresses: Vec, + pub port: u16, +} + +pub struct AdbDiscoveryBrowser { + daemon: ServiceDaemon, + receiver: Receiver, + service_type: AdbServiceType, +} + +impl AdbDiscoveryBrowser { + pub fn start(service_type: AdbServiceType) -> Result { + let service_name = match service_type { + AdbServiceType::Pairing => ADB_TLS_PAIRING_SERVICE, + AdbServiceType::Connect => ADB_TLS_CONNECT_SERVICE, + }; + let daemon = ServiceDaemon::new()?; + let receiver = daemon.browse(service_name)?; + Ok(Self { + daemon, + receiver, + service_type, + }) + } + + pub async fn next_service(&self) -> Option { + loop { + match self.receiver.recv_async().await { + Ok(ServiceEvent::ServiceResolved(info)) => { + return Some(DiscoveredAdbService::from_service_info( + &info, + self.service_type, + )) + } + Ok(_) => continue, + Err(_) => return None, + } + } + } +} + +impl Drop for AdbDiscoveryBrowser { + fn drop(&mut self) { + let _ = self.daemon.shutdown(); + } +} + +impl DiscoveredAdbService { + pub fn from_service_info(info: &ServiceInfo, service_type: AdbServiceType) -> Self { + let port = info.get_port(); + let addresses: Vec = info + .get_addresses() + .iter() + .map(|ip: &IpAddr| SocketAddr::new(*ip, port)) + .collect::>() + .into_iter() + .collect(); + + Self { + service_type, + instance_name: info.get_fullname().to_string(), + addresses, + port, + } + } +} diff --git a/crates/discovery/src/doctor.rs b/crates/discovery/src/doctor.rs new file mode 100644 index 0000000..f7b478c --- /dev/null +++ b/crates/discovery/src/doctor.rs @@ -0,0 +1,170 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use std::net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InterfaceKind { + Loopback, + PrivateLan, + LinkLocal, + VirtualOrVpn, + Public, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct InterfaceReport { + pub ip: IpAddr, + pub kind: InterfaceKind, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum NetworkIssue { + NoActiveLanInterface, + PortUnavailable { port: u16 }, + SubnetMismatch { peer_ip: IpAddr }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NetworkDiagnostic { + pub interfaces: Vec, + pub issues: Vec, +} + +pub fn classify_ip(ip: IpAddr) -> InterfaceKind { + match ip { + IpAddr::V4(v4) => { + if v4.is_loopback() { + InterfaceKind::Loopback + } else if v4.is_link_local() { + InterfaceKind::LinkLocal + } else if is_common_virtual_subnet(v4) { + // WSL2, Hyper-V, and Docker routinely allocate 172.17-172.31 ranges, + // which isolate virtual bridges from the host Wi-Fi adapter. + InterfaceKind::VirtualOrVpn + } else if v4.is_private() { + InterfaceKind::PrivateLan + } else { + InterfaceKind::Public + } + } + IpAddr::V6(v6) => { + if v6.is_loopback() { + InterfaceKind::Loopback + } else if (v6.segments()[0] & 0xffc0) == 0xfe80 { + InterfaceKind::LinkLocal + } else { + InterfaceKind::PrivateLan + } + } + } +} + +fn is_common_virtual_subnet(v4: Ipv4Addr) -> bool { + let octets = v4.octets(); + // Docker default bridge: 172.17.0.0/16 + // WSL2 / Hyper-V vEthernet: dynamic assignments within 172.18.0.0/16 - 172.31.0.0/16 + octets[0] == 172 && (17..=31).contains(&octets[1]) +} + +fn is_same_class_c_subnet(a: Ipv4Addr, b: Ipv4Addr) -> bool { + let o1 = a.octets(); + let o2 = b.octets(); + o1[0] == o2[0] && o1[1] == o2[1] && o1[2] == o2[2] +} + +pub fn probe_port_bindable(port: u16) -> bool { + let addr = SocketAddr::from(([0, 0, 0, 0], port)); + UdpSocket::bind(addr).is_ok() +} + +pub fn diagnose_network( + detected_ips: &[IpAddr], + peer_ip: Option, + listen_port: u16, +) -> NetworkDiagnostic { + let mut interfaces = Vec::with_capacity(detected_ips.len()); + let mut issues = Vec::new(); + + let mut has_lan = false; + + for &ip in detected_ips { + let kind = classify_ip(ip); + if kind == InterfaceKind::PrivateLan { + has_lan = true; + } + interfaces.push(InterfaceReport { ip, kind }); + } + + if !has_lan { + issues.push(NetworkIssue::NoActiveLanInterface); + } + + if !probe_port_bindable(listen_port) { + issues.push(NetworkIssue::PortUnavailable { port: listen_port }); + } + + if let (Some(IpAddr::V4(peer_v4)), true) = (peer_ip, has_lan) { + let matches_any = interfaces.iter().any(|iface| match iface.ip { + IpAddr::V4(local_v4) if iface.kind == InterfaceKind::PrivateLan => { + is_same_class_c_subnet(local_v4, peer_v4) + } + _ => false, + }); + + if !matches_any { + issues.push(NetworkIssue::SubnetMismatch { + peer_ip: IpAddr::V4(peer_v4), + }); + } + } + + NetworkDiagnostic { interfaces, issues } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn classifies_interface_kinds() { + assert_eq!(classify_ip(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))), InterfaceKind::Loopback); + assert_eq!(classify_ip(IpAddr::V4(Ipv4Addr::new(169, 254, 1, 2))), InterfaceKind::LinkLocal); + assert_eq!(classify_ip(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 50))), InterfaceKind::PrivateLan); + assert_eq!(classify_ip(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 15))), InterfaceKind::PrivateLan); + assert_eq!(classify_ip(IpAddr::V4(Ipv4Addr::new(172, 28, 0, 1))), InterfaceKind::VirtualOrVpn); + assert_eq!(classify_ip(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8))), InterfaceKind::Public); + } + + #[test] + fn detects_missing_lan_interface() { + let ips = [ + IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), + IpAddr::V4(Ipv4Addr::new(172, 28, 0, 1)), + ]; + let report = diagnose_network(&ips, None, 0); + assert!(report.issues.contains(&NetworkIssue::NoActiveLanInterface)); + } + + #[test] + fn detects_subnet_mismatch() { + let ips = [IpAddr::V4(Ipv4Addr::new(192, 168, 2, 100))]; + let peer = Some(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 50))); + let report = diagnose_network(&ips, peer, 0); + + assert_eq!( + report.issues, + vec![NetworkIssue::SubnetMismatch { + peer_ip: IpAddr::V4(Ipv4Addr::new(192, 168, 1, 50)) + }] + ); + } + + #[test] + fn passes_healthy_network() { + let ips = [IpAddr::V4(Ipv4Addr::new(192, 168, 1, 10))]; + let peer = Some(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 50))); + let report = diagnose_network(&ips, peer, 0); + assert!(report.issues.is_empty()); + } +} diff --git a/crates/discovery/src/lib.rs b/crates/discovery/src/lib.rs index 245729b..1f640be 100644 --- a/crates/discovery/src/lib.rs +++ b/crates/discovery/src/lib.rs @@ -1,12 +1,26 @@ // SPDX-FileCopyrightText: Contributors to the Continue project // SPDX-License-Identifier: Apache-2.0 +pub mod adb_browser; pub mod advertiser; pub mod browser; +pub mod doctor; pub mod ephemeral; pub mod error; +pub mod localsend; +pub use adb_browser::{ + AdbDiscoveryBrowser, AdbServiceType, DiscoveredAdbService, ADB_TLS_CONNECT_SERVICE, + ADB_TLS_PAIRING_SERVICE, +}; pub use advertiser::{advertise, DiscoveryAdvertiser, RESTART_DELAY, SERVICE_TYPE}; pub use browser::{DiscoveredPeer, DiscoveryBrowser}; +pub use doctor::{ + classify_ip, diagnose_network, InterfaceKind, InterfaceReport, NetworkDiagnostic, NetworkIssue, +}; pub use ephemeral::{EphemeralDiscoveryId, ROTATION_PERIOD}; pub use error::DiscoveryError; +pub use localsend::{ + LocalSendAnnouncement, LOCALSEND_DEFAULT_PORT, LOCALSEND_MULTICAST_IPV4, + LOCALSEND_PROTOCOL_VERSION, +}; diff --git a/crates/discovery/src/localsend.rs b/crates/discovery/src/localsend.rs new file mode 100644 index 0000000..fa5eed1 --- /dev/null +++ b/crates/discovery/src/localsend.rs @@ -0,0 +1,102 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use serde::{Deserialize, Serialize}; + +pub const LOCALSEND_MULTICAST_IPV4: &str = "224.0.0.167"; +pub const LOCALSEND_DEFAULT_PORT: u16 = 53317; +pub const LOCALSEND_PROTOCOL_VERSION: &str = "2.0"; + +fn default_port() -> u16 { + LOCALSEND_DEFAULT_PORT +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct LocalSendAnnouncement { + pub alias: String, + pub version: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub device_model: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub device_type: Option, + pub fingerprint: String, + #[serde(default = "default_port")] + pub port: u16, + pub protocol: String, + #[serde(default)] + pub download: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub announcement: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub announce: Option, +} + +impl LocalSendAnnouncement { + pub fn new(alias: impl Into, fingerprint: impl Into, port: u16, is_desktop: bool) -> Self { + Self { + alias: alias.into(), + version: LOCALSEND_PROTOCOL_VERSION.to_string(), + device_model: Some(if is_desktop { "Desktop PC".into() } else { "Mobile Device".into() }), + device_type: Some(if is_desktop { "desktop".into() } else { "mobile".into() }), + fingerprint: fingerprint.into(), + port, + protocol: "https".to_string(), + download: false, + announcement: Some(true), + announce: Some(true), + } + } + + pub fn to_bytes(&self) -> Result, serde_json::Error> { + serde_json::to_vec(self) + } + + pub fn from_bytes(bytes: &[u8]) -> Result { + serde_json::from_slice(bytes) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn announcement_roundtrip_matches_localsend_v2_spec() { + let announcement = LocalSendAnnouncement::new("Continue-Desktop", "continue-fp-01", 53317, true); + let bytes = announcement.to_bytes().expect("serialize"); + + let json_str = std::str::from_utf8(&bytes).unwrap(); + assert!(json_str.contains("\"alias\":\"Continue-Desktop\"")); + assert!(json_str.contains("\"version\":\"2.0\"")); + assert!(json_str.contains("\"port\":53317")); + assert!(json_str.contains("\"deviceType\":\"desktop\"")); + + let decoded = LocalSendAnnouncement::from_bytes(&bytes).expect("deserialize"); + assert_eq!(decoded.alias, "Continue-Desktop"); + assert_eq!(decoded.fingerprint, "continue-fp-01"); + assert_eq!(decoded.port, 53317); + assert_eq!(decoded.device_type.as_deref(), Some("desktop")); + } + + #[test] + fn parses_external_localsend_json_payload() { + let external_json = r#"{ + "alias": "Alice's iPhone", + "version": "2.0", + "deviceModel": "iPhone 15 Pro", + "deviceType": "mobile", + "fingerprint": "ls-ios-8821", + "port": 53317, + "protocol": "https", + "download": false, + "announcement": true + }"#; + + let decoded = LocalSendAnnouncement::from_bytes(external_json.as_bytes()).expect("parse"); + assert_eq!(decoded.alias, "Alice's iPhone"); + assert_eq!(decoded.device_model.as_deref(), Some("iPhone 15 Pro")); + assert_eq!(decoded.device_type.as_deref(), Some("mobile")); + assert_eq!(decoded.fingerprint, "ls-ios-8821"); + } +} diff --git a/crates/limits/src/lib.rs b/crates/limits/src/lib.rs index 53d414f..76c3339 100644 --- a/crates/limits/src/lib.rs +++ b/crates/limits/src/lib.rs @@ -60,6 +60,24 @@ pub const MAX_FRAME_CLIPBOARD_BYTES: usize = 1024 * 1024; /// Notification messages. pub const MAX_FRAME_NOTIFICATION_BYTES: usize = 64 * 1024; +/// Media capture control messages. +pub const MAX_FRAME_MEDIA_CAPTURE_BYTES: usize = 64 * 1024; + +/// Media control messages (commands, metadata, artwork). +pub const MAX_FRAME_MEDIA_CONTROL_BYTES: usize = 256 * 1024; + +/// Handoff continuity messages (URI, state, document context). +pub const MAX_FRAME_HANDOFF_BYTES: usize = 64 * 1024; + +/// Maximum UTF-8 byte length for a handoff target URI. +pub const MAX_HANDOFF_URI_BYTES: usize = 4 * 1024; + +/// Maximum UTF-8 byte length for a handoff title. +pub const MAX_HANDOFF_TITLE_BYTES: usize = 512; + +/// Telemetry messages (battery, radio state). +pub const MAX_FRAME_TELEMETRY_BYTES: usize = 16 * 1024; + // File transfer /// Maximum UTF-8 byte length of a transfer filename. diff --git a/crates/notifications/src/lib.rs b/crates/notifications/src/lib.rs index 2287662..aa35896 100644 --- a/crates/notifications/src/lib.rs +++ b/crates/notifications/src/lib.rs @@ -3,10 +3,19 @@ pub mod dispatcher; pub mod error; +pub mod media_push; +pub mod otp; +pub mod task; pub use dispatcher::{acknowledge, read, send}; pub use error::NotificationError; +pub use media_push::{ + parse_media_push_action, MediaOrigin, MediaPushAction, MediaPushItem, + ACTION_COPY_MEDIA_CLIPBOARD, ACTION_SAVE_MEDIA_DOWNLOADS, MEDIA_PUSH_PACKAGE, +}; +pub use otp::{enrich_with_otp_action, extract_otp, ACTION_COPY_OTP}; pub use protocol::v1::notification_message::Body; pub use protocol::v1::{ NotificationAction, NotificationActionInvoke, NotificationDismiss, NotificationPost, }; +pub use task::TaskCompletionReport; diff --git a/crates/notifications/src/media_push.rs b/crates/notifications/src/media_push.rs new file mode 100644 index 0000000..c9fa44a --- /dev/null +++ b/crates/notifications/src/media_push.rs @@ -0,0 +1,130 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use protocol::v1::{NotificationAction, NotificationPost}; + +pub const MEDIA_PUSH_PACKAGE: &str = "continue.media.push"; +pub const ACTION_COPY_MEDIA_CLIPBOARD: &str = "copy_media_clipboard"; +pub const ACTION_SAVE_MEDIA_DOWNLOADS: &str = "save_media_downloads"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MediaOrigin { + CameraPhoto, + Screenshot, + SavedImage, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MediaPushItem { + pub media_id: String, + pub file_name: String, + pub mime_type: String, + pub file_size_bytes: u64, + pub origin: MediaOrigin, + pub timestamp_ms: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MediaPushAction { + CopyToClipboard, + SaveToDownloads, +} + +impl MediaPushItem { + pub fn to_notification_post(&self) -> NotificationPost { + let (title, default_prefix) = match self.origin { + MediaOrigin::Screenshot => ("New screenshot captured", "Screenshot"), + MediaOrigin::CameraPhoto => ("New photo captured", "Photo"), + MediaOrigin::SavedImage => ("New image saved", "Image"), + }; + + let size_str = format_byte_size(self.file_size_bytes); + let body = if self.file_name.is_empty() { + format!("{default_prefix} ({size_str})") + } else { + format!("{} ({size_str})", self.file_name) + }; + + NotificationPost { + notification_id: format!("media_{}", self.media_id), + package_name: MEDIA_PUSH_PACKAGE.to_string(), + app_name: "Instant Media".to_string(), + title: title.to_string(), + body, + timestamp: self.timestamp_ms, + actions: vec![ + NotificationAction { + action_id: format!("{}:{}", ACTION_COPY_MEDIA_CLIPBOARD, self.media_id), + label: "Copy to Clipboard".to_string(), + is_reply: false, + }, + NotificationAction { + action_id: format!("{}:{}", ACTION_SAVE_MEDIA_DOWNLOADS, self.media_id), + label: "Save to Downloads".to_string(), + is_reply: false, + }, + ], + } + } +} + +pub fn parse_media_push_action(action_id: &str) -> Option<(MediaPushAction, &str)> { + if let Some(media_id) = action_id.strip_prefix(&format!("{}:", ACTION_COPY_MEDIA_CLIPBOARD)) { + Some((MediaPushAction::CopyToClipboard, media_id)) + } else if let Some(media_id) = action_id.strip_prefix(&format!("{}:", ACTION_SAVE_MEDIA_DOWNLOADS)) { + Some((MediaPushAction::SaveToDownloads, media_id)) + } else { + None + } +} + +fn format_byte_size(bytes: u64) -> String { + const KB: u64 = 1024; + const MB: u64 = 1024 * KB; + + if bytes >= MB { + format!("{:.1} MB", bytes as f64 / MB as f64) + } else if bytes >= KB { + format!("{} KB", bytes / KB) + } else { + format!("{bytes} B") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn screenshot_push_creates_notification_with_actions() { + let item = MediaPushItem { + media_id: "sc-123".into(), + file_name: "Screenshot_20261008.png".into(), + mime_type: "image/png".into(), + file_size_bytes: 2 * 1024 * 1024 + 512 * 1024, + origin: MediaOrigin::Screenshot, + timestamp_ms: 1700000000, + }; + + let post = item.to_notification_post(); + assert_eq!(post.notification_id, "media_sc-123"); + assert_eq!(post.package_name, MEDIA_PUSH_PACKAGE); + assert_eq!(post.title, "New screenshot captured"); + assert_eq!(post.body, "Screenshot_20261008.png (2.5 MB)"); + assert_eq!(post.actions.len(), 2); + assert_eq!(post.actions[0].action_id, "copy_media_clipboard:sc-123"); + assert_eq!(post.actions[1].action_id, "save_media_downloads:sc-123"); + } + + #[test] + fn parses_media_push_action_payload() { + let parsed_copy = parse_media_push_action("copy_media_clipboard:sc-123"); + assert_eq!(parsed_copy, Some((MediaPushAction::CopyToClipboard, "sc-123"))); + + let parsed_save = parse_media_push_action("save_media_downloads:img-99"); + assert_eq!(parsed_save, Some((MediaPushAction::SaveToDownloads, "img-99"))); + + let parsed_unknown = parse_media_push_action("unrelated_action:sc-123"); + assert_eq!(parsed_unknown, None); + } +} diff --git a/crates/notifications/src/otp.rs b/crates/notifications/src/otp.rs new file mode 100644 index 0000000..72fdc8d --- /dev/null +++ b/crates/notifications/src/otp.rs @@ -0,0 +1,92 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use protocol::v1::{NotificationAction, NotificationPost}; + +pub const ACTION_COPY_OTP: &str = "copy_otp"; + +const OTP_KEYWORDS: &[&str] = &[ + "code", + "otp", + "verification", + "passcode", + "security code", + "auth code", + "pin", +]; + +pub fn extract_otp(title: &str, body: &str) -> Option { + let combined = format!("{} {}", title, body).to_ascii_lowercase(); + + let has_keyword = OTP_KEYWORDS.iter().any(|&kw| combined.contains(kw)); + if !has_keyword { + return None; + } + + for token in body.split(|c: char| c.is_whitespace() || c == ':' || c == '.' || c == ',' || c == '#' || c == '-') { + let trimmed = token.trim_matches(|c: char| !c.is_ascii_digit()); + if trimmed.len() >= 4 && trimmed.len() <= 8 && trimmed.chars().all(|c| c.is_ascii_digit()) { + return Some(trimmed.to_string()); + } + } + + None +} + +pub fn enrich_with_otp_action(mut post: NotificationPost) -> NotificationPost { + if let Some(code) = extract_otp(&post.title, &post.body) { + if !post.actions.iter().any(|a| a.action_id == ACTION_COPY_OTP) { + post.actions.insert( + 0, + NotificationAction { + action_id: ACTION_COPY_OTP.to_string(), + label: format!("Copy {}", code), + is_reply: false, + }, + ); + } + } + post +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn extracts_verification_code() { + let code = extract_otp("Google", "G-839201 is your verification code."); + assert_eq!(code, Some("839201".to_string())); + + let code2 = extract_otp("Bank Alert", "Your one-time OTP is 582194 for account login."); + assert_eq!(code2, Some("582194".to_string())); + } + + #[test] + fn ignores_non_otp_notifications() { + let code = extract_otp("WhatsApp", "Hey, are you free for a call tonight?"); + assert_eq!(code, None); + } + + #[test] + fn enriches_notification_with_copy_action() { + let post = NotificationPost { + notification_id: "notif-1".to_string(), + package_name: "com.example.bank".to_string(), + app_name: "Bank".to_string(), + title: "Security Verification".to_string(), + body: "Your login passcode is 948123.".to_string(), + timestamp: 1000, + actions: vec![NotificationAction { + action_id: "dismiss".to_string(), + label: "Dismiss".to_string(), + is_reply: false, + }], + }; + + let enriched = enrich_with_otp_action(post); + assert_eq!(enriched.actions.len(), 2); + assert_eq!(enriched.actions[0].action_id, ACTION_COPY_OTP); + assert_eq!(enriched.actions[0].label, "Copy 948123"); + } +} diff --git a/crates/notifications/src/task.rs b/crates/notifications/src/task.rs new file mode 100644 index 0000000..b5c0235 --- /dev/null +++ b/crates/notifications/src/task.rs @@ -0,0 +1,88 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use protocol::v1::NotificationPost; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TaskCompletionReport { + pub task_name: String, + pub duration: Duration, + pub success: bool, + pub exit_code: Option, +} + +impl TaskCompletionReport { + pub fn new(task_name: impl Into, duration: Duration, success: bool, exit_code: Option) -> Self { + Self { + task_name: task_name.into(), + duration, + success, + exit_code, + } + } + + pub fn to_notification_post(&self) -> NotificationPost { + let status_desc = if self.success { "succeeded" } else { "failed" }; + let code_desc = match self.exit_code { + Some(code) => format!("code {}", code), + None => "terminated".to_string(), + }; + + let body = format!( + "{} in {:.1}s ({})", + status_desc, + self.duration.as_secs_f32(), + code_desc + ); + + let now_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0); + + NotificationPost { + notification_id: format!("task-{}", now_ms), + package_name: "dev.continue.tasks".to_string(), + app_name: "Task Monitor".to_string(), + title: format!("Task: {}", self.task_name), + body, + timestamp: now_ms, + actions: Vec::new(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn formats_successful_task_notification() { + let report = TaskCompletionReport::new( + "cargo build", + Duration::from_millis(4200), + true, + Some(0), + ); + + let post = report.to_notification_post(); + assert_eq!(post.title, "Task: cargo build"); + assert!(post.body.contains("succeeded in 4.2s (code 0)")); + assert_eq!(post.package_name, "dev.continue.tasks"); + } + + #[test] + fn formats_failed_task_notification() { + let report = TaskCompletionReport::new( + "test suite", + Duration::from_millis(1500), + false, + Some(1), + ); + + let post = report.to_notification_post(); + assert_eq!(post.title, "Task: test suite"); + assert!(post.body.contains("failed in 1.5s (code 1)")); + } +} diff --git a/crates/pairing/Cargo.toml b/crates/pairing/Cargo.toml index a3c6f6a..3dbff8a 100644 --- a/crates/pairing/Cargo.toml +++ b/crates/pairing/Cargo.toml @@ -18,6 +18,13 @@ ed25519-dalek = { workspace = true } x25519-dalek = { workspace = true } zeroize = { workspace = true } thiserror = { workspace = true } +tokio = { workspace = true, features = ["net", "io-util", "sync", "time"] } +sha2 = { workspace = true } +hkdf = { workspace = true } +rand = { workspace = true } +subtle = "2" [dev-dependencies] -rand = { workspace = true } +tokio = { workspace = true, features = ["full"] } + + diff --git a/crates/pairing/src/adb_pairing.rs b/crates/pairing/src/adb_pairing.rs new file mode 100644 index 0000000..0513515 --- /dev/null +++ b/crates/pairing/src/adb_pairing.rs @@ -0,0 +1,284 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use hkdf::Hkdf; +use rand::{rngs::OsRng, RngCore}; +use sha2::Sha256; +use subtle::ConstantTimeEq; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +use crate::error::PairingError; + +pub const ADB_PACKET_TYPE_SPAKE2: u8 = 0; +pub const ADB_PACKET_TYPE_PEER_INFO: u8 = 1; +pub const MAX_ADB_PACKET_PAYLOAD: usize = 64 * 1024; + +const TOKEN_LEN: usize = 32; +const TAG_LEN: usize = 32; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AdbPeerCredentials { + pub name: String, + pub key: Vec, +} + +pub async fn write_adb_packet( + writer: &mut W, + packet_type: u8, + payload: &[u8], +) -> Result<(), PairingError> { + if payload.len() > MAX_ADB_PACKET_PAYLOAD { + return Err(PairingError::AdbPairingFailed(format!( + "Payload length {} exceeds limit {}", + payload.len(), + MAX_ADB_PACKET_PAYLOAD + ))); + } + + writer.write_u8(packet_type).await?; + writer.write_u32(payload.len() as u32).await?; + writer.write_all(payload).await?; + writer.flush().await?; + Ok(()) +} + +pub async fn read_adb_packet( + reader: &mut R, +) -> Result<(u8, Vec), PairingError> { + let packet_type = reader.read_u8().await?; + let len = reader.read_u32().await? as usize; + + if len > MAX_ADB_PACKET_PAYLOAD { + return Err(PairingError::AdbPairingFailed(format!( + "Payload length {} exceeds limit {}", + len, MAX_ADB_PACKET_PAYLOAD + ))); + } + + let mut payload = vec![0u8; len]; + reader.read_exact(&mut payload).await?; + Ok((packet_type, payload)) +} + +fn derive_keys( + pin: &str, + client_token: &[u8; TOKEN_LEN], + server_token: &[u8; TOKEN_LEN], +) -> Result<([u8; 32], [u8; 32]), PairingError> { + let mut salt = [0u8; TOKEN_LEN * 2]; + salt[..TOKEN_LEN].copy_from_slice(client_token); + salt[TOKEN_LEN..].copy_from_slice(server_token); + + let hk = Hkdf::::new(Some(&salt), pin.as_bytes()); + + let mut client_auth = [0u8; 32]; + let mut server_auth = [0u8; 32]; + hk.expand(b"adb-tls-pairing-client-auth", &mut client_auth) + .map_err(|e| PairingError::AdbPairingFailed(e.to_string()))?; + hk.expand(b"adb-tls-pairing-server-auth", &mut server_auth) + .map_err(|e| PairingError::AdbPairingFailed(e.to_string()))?; + + Ok((client_auth, server_auth)) +} + +pub async fn pair_client( + stream: &mut S, + pin: &str, + client_name: &str, + client_key: &[u8], +) -> Result { + if pin.len() != 6 || !pin.chars().all(|c| c.is_ascii_digit()) { + return Err(PairingError::AdbPairingFailed( + "PIN must be a 6-digit numeric string".into(), + )); + } + + let mut client_token = [0u8; TOKEN_LEN]; + OsRng.fill_bytes(&mut client_token); + + let mut initial_payload = Vec::with_capacity(TOKEN_LEN); + initial_payload.extend_from_slice(&client_token); + + write_adb_packet(stream, ADB_PACKET_TYPE_SPAKE2, &initial_payload).await?; + + let (packet_type, server_spake) = read_adb_packet(stream).await?; + if packet_type != ADB_PACKET_TYPE_SPAKE2 || server_spake.len() < TOKEN_LEN + TAG_LEN { + return Err(PairingError::AdbPairingFailed( + "Malformed SPAKE2 response from server".into(), + )); + } + + let mut server_token = [0u8; TOKEN_LEN]; + server_token.copy_from_slice(&server_spake[..TOKEN_LEN]); + let server_tag = &server_spake[TOKEN_LEN..TOKEN_LEN + TAG_LEN]; + + let (client_auth, expected_server_auth) = derive_keys(pin, &client_token, &server_token)?; + + if !bool::from(server_tag.ct_eq(&expected_server_auth)) { + let _ = stream.shutdown().await; + return Err(PairingError::AdbPinMismatch); + } + + write_adb_packet(stream, ADB_PACKET_TYPE_SPAKE2, &client_auth).await?; + + let mut info_payload = Vec::with_capacity(4 + client_name.len() + client_key.len()); + info_payload.extend_from_slice(&(client_name.len() as u32).to_be_bytes()); + info_payload.extend_from_slice(client_name.as_bytes()); + info_payload.extend_from_slice(client_key); + + write_adb_packet(stream, ADB_PACKET_TYPE_PEER_INFO, &info_payload).await?; + + let (packet_type, server_info) = read_adb_packet(stream).await?; + if packet_type != ADB_PACKET_TYPE_PEER_INFO || server_info.len() < 4 { + return Err(PairingError::AdbPairingFailed( + "Malformed PeerInfo from server".into(), + )); + } + + let name_len = u32::from_be_bytes(server_info[0..4].try_into().unwrap()) as usize; + if server_info.len() < 4 + name_len { + return Err(PairingError::AdbPairingFailed( + "PeerInfo payload truncated".into(), + )); + } + + let peer_name = String::from_utf8(server_info[4..4 + name_len].to_vec()) + .map_err(|e| PairingError::AdbPairingFailed(e.to_string()))?; + let peer_key = server_info[4 + name_len..].to_vec(); + + Ok(AdbPeerCredentials { + name: peer_name, + key: peer_key, + }) +} + +pub async fn pair_server( + stream: &mut S, + pin: &str, + server_name: &str, + server_key: &[u8], +) -> Result { + if pin.len() != 6 || !pin.chars().all(|c| c.is_ascii_digit()) { + return Err(PairingError::AdbPairingFailed( + "PIN must be a 6-digit numeric string".into(), + )); + } + + let (packet_type, client_spake) = read_adb_packet(stream).await?; + if packet_type != ADB_PACKET_TYPE_SPAKE2 || client_spake.len() < TOKEN_LEN { + return Err(PairingError::AdbPairingFailed( + "Malformed SPAKE2 packet from client".into(), + )); + } + + let mut client_token = [0u8; TOKEN_LEN]; + client_token.copy_from_slice(&client_spake[..TOKEN_LEN]); + + let mut server_token = [0u8; TOKEN_LEN]; + OsRng.fill_bytes(&mut server_token); + + let (expected_client_auth, server_auth) = derive_keys(pin, &client_token, &server_token)?; + + let mut resp = Vec::with_capacity(TOKEN_LEN + TAG_LEN); + resp.extend_from_slice(&server_token); + resp.extend_from_slice(&server_auth); + + write_adb_packet(stream, ADB_PACKET_TYPE_SPAKE2, &resp).await?; + + let (packet_type, client_tag) = read_adb_packet(stream).await?; + if packet_type != ADB_PACKET_TYPE_SPAKE2 || client_tag.len() != TAG_LEN { + return Err(PairingError::AdbPairingFailed( + "Malformed client auth tag".into(), + )); + } + + if !bool::from(client_tag.as_slice().ct_eq(&expected_client_auth)) { + let _ = stream.shutdown().await; + return Err(PairingError::AdbPinMismatch); + } + + let (packet_type, client_info) = read_adb_packet(stream).await?; + if packet_type != ADB_PACKET_TYPE_PEER_INFO || client_info.len() < 4 { + return Err(PairingError::AdbPairingFailed( + "Malformed PeerInfo from client".into(), + )); + } + + let name_len = u32::from_be_bytes(client_info[0..4].try_into().unwrap()) as usize; + if client_info.len() < 4 + name_len { + return Err(PairingError::AdbPairingFailed( + "PeerInfo payload truncated".into(), + )); + } + + let peer_name = String::from_utf8(client_info[4..4 + name_len].to_vec()) + .map_err(|e| PairingError::AdbPairingFailed(e.to_string()))?; + let peer_key = client_info[4 + name_len..].to_vec(); + + let mut info_payload = Vec::with_capacity(4 + server_name.len() + server_key.len()); + info_payload.extend_from_slice(&(server_name.len() as u32).to_be_bytes()); + info_payload.extend_from_slice(server_name.as_bytes()); + info_payload.extend_from_slice(server_key); + + write_adb_packet(stream, ADB_PACKET_TYPE_PEER_INFO, &info_payload).await?; + + Ok(AdbPeerCredentials { + name: peer_name, + key: peer_key, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn adb_pairing_roundtrip_success() { + let (mut client_io, mut server_io) = tokio::io::duplex(4096); + let pin = "492813"; + + let server_task = tokio::spawn(async move { + pair_server(&mut server_io, pin, "Android Device", b"device_adb_pubkey").await + }); + + let client_creds = pair_client( + &mut client_io, + pin, + "Continue Desktop", + b"desktop_adb_pubkey", + ) + .await + .expect("client pairs"); + + let server_creds = server_task.await.unwrap().expect("server pairs"); + + assert_eq!(client_creds.name, "Android Device"); + assert_eq!(client_creds.key, b"device_adb_pubkey"); + + assert_eq!(server_creds.name, "Continue Desktop"); + assert_eq!(server_creds.key, b"desktop_adb_pubkey"); + } + + #[tokio::test] + async fn adb_pairing_fails_on_pin_mismatch() { + let (mut client_io, mut server_io) = tokio::io::duplex(4096); + + let server_task = tokio::spawn(async move { + pair_server(&mut server_io, "111111", "Android Device", b"device_key").await + }); + + let client_res = pair_client(&mut client_io, "222222", "Desktop", b"desktop_key").await; + drop(client_io); + + let server_res = server_task.await.unwrap(); + assert!(matches!(client_res, Err(PairingError::AdbPinMismatch))); + assert!(server_res.is_err()); + } + + #[tokio::test] + async fn adb_pairing_rejects_invalid_pin_format() { + let (mut client_io, _server_io) = tokio::io::duplex(4096); + let res = pair_client(&mut client_io, "12ab", "Desktop", b"key").await; + assert!(matches!(res, Err(PairingError::AdbPairingFailed(_)))); + } +} diff --git a/crates/pairing/src/error.rs b/crates/pairing/src/error.rs index 1b7b899..2c27196 100644 --- a/crates/pairing/src/error.rs +++ b/crates/pairing/src/error.rs @@ -43,4 +43,13 @@ pub enum PairingError { #[error("Protocol framing error: {0}")] Protocol(#[from] protocol::ProtocolError), + + #[error("ADB pairing failed: {0}")] + AdbPairingFailed(String), + + #[error("ADB pairing PIN mismatch or authentication failed")] + AdbPinMismatch, + + #[error("I/O error: {0}")] + Io(#[from] std::io::Error), } diff --git a/crates/pairing/src/lib.rs b/crates/pairing/src/lib.rs index e92f7f6..11daf1b 100644 --- a/crates/pairing/src/lib.rs +++ b/crates/pairing/src/lib.rs @@ -1,16 +1,20 @@ // SPDX-FileCopyrightText: Contributors to the Continue project // SPDX-License-Identifier: Apache-2.0 +pub mod adb_pairing; pub mod error; pub mod flow; pub mod keys; pub mod qr; pub mod replay; pub mod trust_store; +pub mod words; +pub use adb_pairing::{pair_client, pair_server, AdbPeerCredentials}; pub use error::PairingError; pub use flow::{InitiatorPairing, ResponderPairing}; pub use keys::DeviceKeys; pub use qr::{QrPayload, QR_FORMAT_VERSION, QR_ROLE_INITIATOR}; pub use replay::ReplayCache; pub use trust_store::{TrustStore, TrustedPeer}; +pub use words::{derive_verification_words, format_verification_phrase, WORDLIST}; diff --git a/crates/pairing/src/words.rs b/crates/pairing/src/words.rs new file mode 100644 index 0000000..462f565 --- /dev/null +++ b/crates/pairing/src/words.rs @@ -0,0 +1,131 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use hkdf::Hkdf; +use sha2::Sha256; + +const SAS_INFO_LABEL: &[u8] = b"CONTINUE_SAS_WORDS_V1"; + +/// 256 phonetically distinct words for visual Short Authentication String (SAS) verification. +pub const WORDLIST: [&str; 256] = [ + "acorn", "action", "anchor", "anthem", "apron", "archer", "arrow", "artist", + "atlas", "atom", "author", "badge", "baker", "bamboo", "banner", "bark", + "beacon", "beetle", "bell", "berry", "bison", "blade", "blanket", "blaze", + "blossom", "bonfire", "book", "bottle", "boulder", "breeze", "brick", "bridge", + "brook", "bucket", "cabin", "cactus", "canyon", "canvas", "cargo", "castle", + "cedar", "celery", "chalk", "charm", "cherry", "chest", "chimney", "cider", + "circle", "cliff", "cloak", "clover", "cobalt", "comet", "compass", "copper", + "coral", "corner", "cotton", "crater", "creek", "cricket", "crystal", "curtain", + "daisy", "dancer", "delta", "desert", "diamond", "dolphin", "dragon", "drift", + "drum", "eagle", "earth", "echo", "ember", "engine", "falcon", "feather", + "fern", "ferry", "field", "filter", "finch", "finger", "fire", "flame", + "flint", "flower", "forest", "fountain", "fox", "frost", "garden", "garlic", + "gateway", "gecko", "geyser", "ginger", "glacier", "globe", "glow", "goblet", + "granite", "grape", "grass", "gravel", "grove", "guitar", "harbor", "harvest", + "haven", "hawk", "hazel", "helmet", "hero", "heron", "honey", "horizon", + "humming", "hunter", "husky", "igloo", "island", "jacket", "jaguar", "jasper", + "jelly", "jigsaw", "jungle", "jupiter", "kettle", "key", "kite", "kiwi", + "knight", "ladder", "lagoon", "lantern", "lark", "laurel", "lava", "leaf", + "lemon", "leopard", "lighthouse", "lily", "lion", "lizard", "llama", "lobster", + "lotus", "lumber", "lunar", "magnet", "magpie", "mallet", "mango", "mantle", + "maple", "marble", "marsh", "meadow", "melon", "meteor", "mirror", "monarch", + "moon", "moss", "mountain", "muffin", "nebula", "nectar", "needle", "nest", + "nickel", "night", "ninja", "north", "novel", "oasis", "ocean", "olive", + "onyx", "opal", "orange", "orbit", "orchid", "otter", "owl", "paddle", + "palace", "panther", "papaya", "parrot", "path", "peach", "peacock", "pebble", + "pelican", "pepper", "petal", "phoenix", "pillow", "pilot", "pine", "planet", + "plasma", "plaza", "polar", "poplar", "prism", "puzzle", "quartz", "quiver", + "rabbit", "radar", "rainbow", "raven", "reef", "relay", "ridge", "river", + "robin", "rocket", "ruby", "saddle", "safari", "sail", "salmon", "sand", + "sapphire", "saturn", "scale", "scarlet", "scout", "shadow", "shield", "sierra", + "silver", "skater", "sky", "solar", "sparrow", "sphere", "spider", "spire", + "spring", "spruce", "star", "summit", "sun", "surf", "swan", "timber", +]; + +/// Derives 4 visual verification words from the pairing shared secret and transcript. +/// +/// Both peers calculate these words independently. Comparing them out-of-band allows +/// users to visually confirm that no machine-in-the-middle has intercepted or altered +/// the pairing exchange. +pub fn derive_verification_words(shared_secret: &[u8], transcript: &[u8]) -> [&'static str; 4] { + let hk = Hkdf::::new(Some(transcript), shared_secret); + let mut indices = [0u8; 4]; + hk.expand(SAS_INFO_LABEL, &mut indices) + .expect("4 bytes is within valid HKDF expansion limit"); + + [ + WORDLIST[indices[0] as usize], + WORDLIST[indices[1] as usize], + WORDLIST[indices[2] as usize], + WORDLIST[indices[3] as usize], + ] +} + +/// Formats 4 verification words as a hyphen-delimited string (e.g. "acorn-blade-copper-eagle"). +pub fn format_verification_phrase(words: &[&str; 4]) -> String { + words.join("-") +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashSet; + + #[test] + fn wordlist_has_256_unique_entries() { + assert_eq!(WORDLIST.len(), 256); + let mut seen = HashSet::new(); + for &word in &WORDLIST { + assert!(!word.is_empty(), "word cannot be empty"); + assert!( + seen.insert(word), + "wordlist contains duplicate entry: {word}" + ); + } + } + + #[test] + fn deterministic_derivation() { + let secret = [42u8; 32]; + let transcript = b"sample_pairing_transcript_initiator_responder_v1"; + + let words1 = derive_verification_words(&secret, transcript); + let words2 = derive_verification_words(&secret, transcript); + + assert_eq!(words1, words2); + assert_eq!(format_verification_phrase(&words1), format_verification_phrase(&words2)); + } + + #[test] + fn transcript_variation_alters_words() { + let secret = [7u8; 32]; + let transcript1 = b"transcript_session_alpha"; + let transcript2 = b"transcript_session_beta"; + + let words1 = derive_verification_words(&secret, transcript1); + let words2 = derive_verification_words(&secret, transcript2); + + assert_ne!(words1, words2); + } + + #[test] + fn secret_variation_alters_words() { + let secret1 = [1u8; 32]; + let secret2 = [2u8; 32]; + let transcript = b"identical_transcript"; + + let words1 = derive_verification_words(&secret1, transcript); + let words2 = derive_verification_words(&secret2, transcript); + + assert_ne!(words1, words2); + } + + #[test] + fn phrase_formatting() { + let words = ["anchor", "beacon", "falcon", "planet"]; + assert_eq!( + format_verification_phrase(&words), + "anchor-beacon-falcon-planet" + ); + } +} diff --git a/crates/permissions/src/store.rs b/crates/permissions/src/store.rs index 6e930ef..b46dd34 100644 --- a/crates/permissions/src/store.rs +++ b/crates/permissions/src/store.rs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 use std::collections::HashSet; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{SystemTime, UNIX_EPOCH}; @@ -23,6 +24,7 @@ fn current_timestamp() -> u64 { pub struct PermissionStore { conn: Arc>, allow_once_grants: Arc>>, + lockdown: Arc, } impl PermissionStore { @@ -30,6 +32,7 @@ impl PermissionStore { let store = Self { conn: Arc::new(Mutex::new(conn)), allow_once_grants: Arc::new(Mutex::new(HashSet::new())), + lockdown: Arc::new(AtomicBool::new(false)), }; store.init_schema()?; Ok(store) @@ -142,18 +145,35 @@ impl PermissionStore { set.retain(|(peer, _)| peer != peer_fingerprint); } + /// Enables or disables global lockdown mode. + /// When active, all permission queries evaluate to `Deny` regardless of stored grants. + pub fn set_lockdown(&self, active: bool) { + self.lockdown.store(active, Ordering::SeqCst); + } + + /// Returns true if global lockdown mode is currently active. + pub fn is_locked_down(&self) -> bool { + self.lockdown.load(Ordering::SeqCst) + } + /// Uses up a one-use grant, if there is one. pub fn consume_if_allow_once(&self, peer_fingerprint: &str, capability: CapabilityId) -> bool { + if self.is_locked_down() { + return false; + } let mut set = self.allow_once_grants.lock().unwrap(); set.remove(&(peer_fingerprint.to_string(), capability.raw())) } - /// What the peer may do now: a one-use grant first, then the saved grant, else `Ask`. + /// What the peer may do now: Deny if lockdown is active, a one-use grant first, then the saved grant, else `Ask`. pub fn query_state( &self, peer_fingerprint: &str, capability: CapabilityId, ) -> Result { + if self.is_locked_down() { + return Ok(PermissionState::Deny); + } let allowed_once = self .allow_once_grants .lock() @@ -205,4 +225,59 @@ mod tests { PermissionState::Allow ); } + + #[test] + fn lockdown_overrides_grants_and_resets() { + let store = PermissionStore::in_memory().unwrap(); + let peer = "device-fingerprint-xyz"; + let cap = CapabilityId::FILE_TRANSFER; + + store + .set_persisted_grant(peer, cap, 1, PersistedGrant::Allow) + .unwrap(); + assert_eq!( + store.query_state(peer, cap).unwrap(), + PermissionState::Allow + ); + + store.grant_allow_once(peer, CapabilityId::CLIPBOARD); + assert_eq!( + store.query_state(peer, CapabilityId::CLIPBOARD).unwrap(), + PermissionState::AllowOnce + ); + + store.set_lockdown(true); + assert!(store.is_locked_down()); + + assert_eq!( + store.query_state(peer, cap).unwrap(), + PermissionState::Deny + ); + assert_eq!( + store.query_state(peer, CapabilityId::CLIPBOARD).unwrap(), + PermissionState::Deny + ); + assert!(!store.consume_if_allow_once(peer, CapabilityId::CLIPBOARD)); + + // Shared across clones + let store_clone = store.clone(); + assert!(store_clone.is_locked_down()); + assert_eq!( + store_clone.query_state(peer, cap).unwrap(), + PermissionState::Deny + ); + + // Deactivating lockdown restores configured grants + store.set_lockdown(false); + assert!(!store.is_locked_down()); + assert_eq!( + store.query_state(peer, cap).unwrap(), + PermissionState::Allow + ); + assert_eq!( + store.query_state(peer, CapabilityId::CLIPBOARD).unwrap(), + PermissionState::AllowOnce + ); + assert!(store.consume_if_allow_once(peer, CapabilityId::CLIPBOARD)); + } } diff --git a/crates/protocol/build.rs b/crates/protocol/build.rs index a7ee589..733efd8 100644 --- a/crates/protocol/build.rs +++ b/crates/protocol/build.rs @@ -17,6 +17,10 @@ fn main() { proto_dir.join("transfer.proto"), proto_dir.join("clipboard.proto"), proto_dir.join("notification.proto"), + proto_dir.join("media_capture.proto"), + proto_dir.join("media_control.proto"), + proto_dir.join("handoff.proto"), + proto_dir.join("telemetry.proto"), ]; for file in &proto_files { diff --git a/crates/protocol/src/capability.rs b/crates/protocol/src/capability.rs index 261f064..4438783 100644 --- a/crates/protocol/src/capability.rs +++ b/crates/protocol/src/capability.rs @@ -15,6 +15,10 @@ impl CapabilityId { pub const FILE_TRANSFER: Self = Self(1); pub const CLIPBOARD: Self = Self(2); pub const NOTIFICATIONS: Self = Self(3); + pub const MEDIA_CAPTURE: Self = Self(4); + pub const MEDIA_CONTROL: Self = Self(5); + pub const HANDOFF: Self = Self(6); + pub const TELEMETRY: Self = Self(7); pub const fn new(id: u32) -> Self { Self(id) @@ -30,6 +34,10 @@ impl CapabilityId { Self::FILE_TRANSFER => Some("file_transfer"), Self::CLIPBOARD => Some("clipboard"), Self::NOTIFICATIONS => Some("notifications"), + Self::MEDIA_CAPTURE => Some("media_capture"), + Self::MEDIA_CONTROL => Some("media_control"), + Self::HANDOFF => Some("handoff"), + Self::TELEMETRY => Some("telemetry"), _ => None, } } diff --git a/crates/sessions/src/capabilities_router.rs b/crates/sessions/src/capabilities_router.rs index f2ba328..b7c8324 100644 --- a/crates/sessions/src/capabilities_router.rs +++ b/crates/sessions/src/capabilities_router.rs @@ -14,8 +14,11 @@ use protocol::CapabilityId; use transfer::{receive_file, send_file, ReceivedFile}; use crate::device::{PeerDevice, ThisDevice}; +use crate::handoff::HandoffDispatcher; use crate::incoming::{IncomingFiles, SaveFolder}; +use crate::media_control::MediaControlDispatcher; use crate::multiplexer::{OnPeerUpdate, PeerUpdate, SessionMultiplexer}; +use crate::telemetry::TelemetryDispatcher; /// How long a question waits for the user before it counts as declined. pub const PROMPT_TIMEOUT: Duration = Duration::from_secs(30); @@ -47,17 +50,30 @@ pub type PermissionPrompt = /// Called with the sender's fingerprint and what it sent. pub type OnReceived = Arc; +pub type MediaCommandHandler = Arc< + dyn Fn(&str, protocol::v1::MediaCommandRequest) -> protocol::v1::MediaCommandResponse + + Send + + Sync, +>; /// Callbacks and configuration for active capabilities over a multiplexed session. #[derive(Clone)] pub struct SessionCapabilityHandlers { pub save_folder: SaveFolder, pub incoming: IncomingFiles, + pub media_control_dispatcher: Arc, + pub handoff_dispatcher: Arc, + pub telemetry_dispatcher: Arc, pub on_file_received: Option>, pub on_clipboard_received: Option>, /// Called with notifications the peer shows here, and with replies to and dismissals of /// the ones this device sent it. pub on_notification: Option>, + pub on_media_status_received: Option>, + pub on_media_command_received: Option, + pub on_handoff_received: Option>, + pub on_handoff_dismissed: Option>, + pub on_telemetry_received: Option>, /// How this device introduces itself to peers. pub this_device: ThisDevice, /// Called with what a peer says about itself each time a session starts. @@ -76,9 +92,17 @@ impl SessionCapabilityHandlers { Self { save_folder: SaveFolder::new(save_folder), incoming: IncomingFiles::default(), + media_control_dispatcher: Arc::new(MediaControlDispatcher::new()), + handoff_dispatcher: Arc::new(HandoffDispatcher::new()), + telemetry_dispatcher: Arc::new(TelemetryDispatcher::new()), on_file_received: None, on_clipboard_received: None, on_notification: None, + on_media_status_received: None, + on_media_command_received: None, + on_handoff_received: None, + on_handoff_dismissed: None, + on_telemetry_received: None, this_device: ThisDevice::default(), on_device_info: None, on_device_status: None, @@ -339,6 +363,114 @@ pub fn spawn_capabilities_dispatcher( } let _ = notifications::acknowledge(&mut stream.send_stream, allowed).await; } + CapabilityId::MEDIA_CONTROL => { + debug!("Handling incoming media control stream from {peer_fp}"); + let is_permitted = + permitted(&handlers, &peer_fp, CapabilityId::MEDIA_CONTROL, None).await; + + let query = + CapabilityQuery::negotiated(CapabilityId::MEDIA_CONTROL, is_permitted); + + let on_status = handlers.on_media_status_received.clone(); + let on_command = handlers.on_media_command_received.clone(); + let peer = peer_fp.clone(); + + let result = handlers + .media_control_dispatcher + .receive_envelope( + &mut stream.send_stream, + &mut stream.recv_stream, + &query, + |cmd| { + if let Some(ref cb) = on_command { + cb(&peer, cmd) + } else { + protocol::v1::MediaCommandResponse { + command_id: cmd.command_id, + success: false, + error_message: "Media command not handled".into(), + } + } + }, + |stat| { + if let Some(ref cb) = on_status { + cb(&peer, stat); + } + }, + ) + .await; + + if let Err(e) = result { + error!("Failed to process media control stream from {peer_fp}: {e}"); + } + } + CapabilityId::HANDOFF => { + debug!("Handling incoming handoff stream from {peer_fp}"); + let is_permitted = + permitted(&handlers, &peer_fp, CapabilityId::HANDOFF, None).await; + + let query = + CapabilityQuery::negotiated(CapabilityId::HANDOFF, is_permitted); + + let on_received = handlers.on_handoff_received.clone(); + let on_dismissed = handlers.on_handoff_dismissed.clone(); + let peer = peer_fp.clone(); + + let result = handlers + .handoff_dispatcher + .receive_envelope( + &mut stream.send_stream, + &mut stream.recv_stream, + &query, + |item| { + if let Some(ref cb) = on_received { + cb(&peer, item); + } + Ok(()) + }, + |dismiss_id| { + if let Some(ref cb) = on_dismissed { + cb(&peer, dismiss_id); + } + Ok(()) + }, + ) + .await; + + if let Err(e) = result { + error!("Failed to process handoff stream from {peer_fp}: {e}"); + } + } + CapabilityId::TELEMETRY => { + debug!("Handling incoming telemetry stream from {peer_fp}"); + let is_permitted = + permitted(&handlers, &peer_fp, CapabilityId::TELEMETRY, None).await; + + let query = + CapabilityQuery::negotiated(CapabilityId::TELEMETRY, is_permitted); + + let on_received = handlers.on_telemetry_received.clone(); + let peer = peer_fp.clone(); + + let result = handlers + .telemetry_dispatcher + .receive_envelope( + &mut stream.send_stream, + &mut stream.recv_stream, + &query, + |telemetry| { + if let Some(ref cb) = on_received { + cb(&peer, telemetry); + } + Ok(()) + }, + ) + .await; + + if let Err(e) = result { + error!("Failed to process telemetry stream from {peer_fp}: {e}"); + } + } unknown => { debug!("Received unsupported capability stream {unknown:?} from {peer_fp}"); } @@ -395,4 +527,37 @@ impl SessionMultiplexer { notifications::send(&mut send, &mut recv, body, query).await } + + pub async fn send_media_command_to_peer( + &self, + command: protocol::v1::MediaCommandRequest, + query: &CapabilityQuery, + ) -> Result { + let (mut send, mut recv) = self + .open_stream(CapabilityId::MEDIA_CONTROL) + .await + .map_err(crate::error::SessionError::Transport)?; + + let dispatcher = MediaControlDispatcher::new(); + dispatcher + .send_command(&mut send, &mut recv, command, query) + .await + } + + pub async fn publish_media_status_to_peer( + &self, + update: protocol::v1::MediaStatusUpdate, + query: &CapabilityQuery, + ) -> Result { + let (mut send, mut recv) = self + .open_stream(CapabilityId::MEDIA_CONTROL) + .await + .map_err(crate::error::SessionError::Transport)?; + + let dispatcher = MediaControlDispatcher::new(); + dispatcher + .publish_status(&mut send, &mut recv, update, query) + .await + } } + diff --git a/crates/sessions/src/error.rs b/crates/sessions/src/error.rs index 8971d17..5a2455f 100644 --- a/crates/sessions/src/error.rs +++ b/crates/sessions/src/error.rs @@ -22,4 +22,16 @@ pub enum SessionError { #[error("Unexpected session envelope payload")] UnexpectedMessage, + + #[error("Capability error: {0}")] + Capability(#[from] capabilities::CapabilityError), + + #[error("Media control rejected: {0}")] + MediaControlRejected(String), + + #[error("Handoff rejected: {0}")] + HandoffRejected(String), + + #[error("Handoff validation failed: {0}")] + HandoffValidation(String), } diff --git a/crates/sessions/src/handoff.rs b/crates/sessions/src/handoff.rs new file mode 100644 index 0000000..137c9e4 --- /dev/null +++ b/crates/sessions/src/handoff.rs @@ -0,0 +1,324 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use capabilities::{evaluate_capability, CapabilityQuery}; +use limits::{MAX_FRAME_HANDOFF_BYTES, MAX_HANDOFF_TITLE_BYTES, MAX_HANDOFF_URI_BYTES}; +use protocol::v1::{ + handoff_envelope::Payload, HandoffAck, HandoffBroadcast, HandoffDismiss, HandoffEnvelope, + HandoffItem, +}; +use transport::{read_msg, write_msg}; + +use crate::error::SessionError; + +#[derive(Default)] +pub struct HandoffDispatcher; + +impl HandoffDispatcher { + pub fn new() -> Self { + Self + } + + pub fn validate_item(item: &HandoffItem) -> Result<(), SessionError> { + if item.uri.len() > MAX_HANDOFF_URI_BYTES { + return Err(SessionError::HandoffValidation(format!( + "Handoff URI exceeds maximum allowed length of {} bytes", + MAX_HANDOFF_URI_BYTES + ))); + } + + if item.title.len() > MAX_HANDOFF_TITLE_BYTES { + return Err(SessionError::HandoffValidation(format!( + "Handoff title exceeds maximum allowed length of {} bytes", + MAX_HANDOFF_TITLE_BYTES + ))); + } + + Ok(()) + } + + pub async fn broadcast_handoff( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + item: HandoffItem, + query: &CapabilityQuery, + ) -> Result { + evaluate_capability(query)?; + Self::validate_item(&item)?; + + let envelope = HandoffEnvelope { + payload: Some(Payload::Broadcast(HandoffBroadcast { item: Some(item) })), + }; + + write_msg(send_stream, &envelope, MAX_FRAME_HANDOFF_BYTES).await?; + let ack: HandoffAck = read_msg(recv_stream, MAX_FRAME_HANDOFF_BYTES).await?; + + if !ack.success { + return Err(SessionError::HandoffRejected(ack.error_message)); + } + + Ok(ack) + } + + pub async fn dismiss_handoff( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + handoff_id: String, + query: &CapabilityQuery, + ) -> Result { + evaluate_capability(query)?; + + let envelope = HandoffEnvelope { + payload: Some(Payload::Dismiss(HandoffDismiss { + handoff_id: handoff_id.clone(), + })), + }; + + write_msg(send_stream, &envelope, MAX_FRAME_HANDOFF_BYTES).await?; + let ack: HandoffAck = read_msg(recv_stream, MAX_FRAME_HANDOFF_BYTES).await?; + + if !ack.success { + return Err(SessionError::HandoffRejected(ack.error_message)); + } + + Ok(ack) + } + + pub async fn receive_envelope( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + query: &CapabilityQuery, + mut on_broadcast: HB, + mut on_dismiss: HD, + ) -> Result + where + HB: FnMut(HandoffItem) -> Result<(), String>, + HD: FnMut(String) -> Result<(), String>, + { + evaluate_capability(query)?; + + let envelope: HandoffEnvelope = read_msg(recv_stream, MAX_FRAME_HANDOFF_BYTES).await?; + + match envelope.payload.clone() { + Some(Payload::Broadcast(broadcast)) => { + let item = broadcast.item.ok_or(SessionError::UnexpectedMessage)?; + let handoff_id = item.handoff_id.clone(); + let ack = match on_broadcast(item) { + Ok(()) => HandoffAck { + handoff_id, + success: true, + error_message: String::new(), + }, + Err(err) => HandoffAck { + handoff_id, + success: false, + error_message: err, + }, + }; + write_msg(send_stream, &ack, MAX_FRAME_HANDOFF_BYTES).await?; + } + Some(Payload::Dismiss(dismiss)) => { + let handoff_id = dismiss.handoff_id; + let ack = match on_dismiss(handoff_id.clone()) { + Ok(()) => HandoffAck { + handoff_id, + success: true, + error_message: String::new(), + }, + Err(err) => HandoffAck { + handoff_id, + success: false, + error_message: err, + }, + }; + write_msg(send_stream, &ack, MAX_FRAME_HANDOFF_BYTES).await?; + } + Some(Payload::Ack(_)) | None => { + return Err(SessionError::UnexpectedMessage); + } + } + + Ok(envelope) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashSet; + use protocol::CapabilityId; + use protocol::v1::HandoffType; + use transport::{create_client_endpoint, create_server_endpoint, TransportCertificate}; + + fn test_query(authorized: bool) -> CapabilityQuery { + let mut caps = HashSet::new(); + caps.insert(CapabilityId::HANDOFF); + CapabilityQuery { + capability: CapabilityId::HANDOFF, + is_os_available: true, + is_app_permitted: true, + is_peer_authorized: authorized, + negotiated_session_capabilities: caps, + } + } + + #[tokio::test] + async fn handoff_broadcast_roundtrip() { + let server_cert = TransportCertificate::generate().unwrap(); + let client_cert = TransportCertificate::generate().unwrap(); + + let server_tls = server_cert + .build_pinned_server_tls(client_cert.spki_hash) + .unwrap(); + let client_tls = client_cert + .build_pinned_client_tls(server_cert.spki_hash) + .unwrap(); + + let server = create_server_endpoint("127.0.0.1:0".parse().unwrap(), server_tls).unwrap(); + let server_addr = server.local_addr().unwrap(); + let client = create_client_endpoint("127.0.0.1:0".parse().unwrap(), client_tls).unwrap(); + + let server_task = tokio::spawn(async move { + let incoming = server.accept().await.unwrap(); + let conn = incoming.await.unwrap(); + let (mut send, mut recv) = conn.accept_bi().await.unwrap(); + + let dispatcher = HandoffDispatcher::new(); + let q = test_query(true); + + let res = dispatcher + .receive_envelope( + &mut send, + &mut recv, + &q, + |item| { + assert_eq!(item.handoff_id, "h-1"); + assert_eq!(item.uri, "https://github.com/continue/project"); + assert_eq!(item.handoff_type, HandoffType::Url as i32); + Ok(()) + }, + |_| Ok(()), + ) + .await; + + (res, conn) + }); + + let conn = client + .connect(server_addr, "continue-device") + .unwrap() + .await + .unwrap(); + let (mut send, mut recv) = conn.open_bi().await.unwrap(); + + let dispatcher = HandoffDispatcher::new(); + let q = test_query(true); + + let item = HandoffItem { + handoff_id: "h-1".into(), + source_device_id: "phone-1".into(), + handoff_type: HandoffType::Url as i32, + title: "Continue Project".into(), + uri: "https://github.com/continue/project".into(), + scroll_ratio: 0.42, + cursor_position: 128, + timestamp_ms: 1700000000, + extra_payload: Vec::new(), + }; + + let ack = dispatcher + .broadcast_handoff(&mut send, &mut recv, item, &q) + .await + .expect("broadcast delivered"); + + assert_eq!(ack.handoff_id, "h-1"); + assert!(ack.success); + + let (server_res, _server_conn) = server_task.await.unwrap(); + server_res.unwrap(); + } + + #[tokio::test] + async fn handoff_dismiss_roundtrip() { + let server_cert = TransportCertificate::generate().unwrap(); + let client_cert = TransportCertificate::generate().unwrap(); + + let server_tls = server_cert + .build_pinned_server_tls(client_cert.spki_hash) + .unwrap(); + let client_tls = client_cert + .build_pinned_client_tls(server_cert.spki_hash) + .unwrap(); + + let server = create_server_endpoint("127.0.0.1:0".parse().unwrap(), server_tls).unwrap(); + let server_addr = server.local_addr().unwrap(); + let client = create_client_endpoint("127.0.0.1:0".parse().unwrap(), client_tls).unwrap(); + + let server_task = tokio::spawn(async move { + let incoming = server.accept().await.unwrap(); + let conn = incoming.await.unwrap(); + let (mut send, mut recv) = conn.accept_bi().await.unwrap(); + + let dispatcher = HandoffDispatcher::new(); + let q = test_query(true); + + let res = dispatcher + .receive_envelope( + &mut send, + &mut recv, + &q, + |_| Ok(()), + |handoff_id| { + assert_eq!(handoff_id, "h-42"); + Ok(()) + }, + ) + .await; + + (res, conn) + }); + + let conn = client + .connect(server_addr, "continue-device") + .unwrap() + .await + .unwrap(); + let (mut send, mut recv) = conn.open_bi().await.unwrap(); + + let dispatcher = HandoffDispatcher::new(); + let q = test_query(true); + + let ack = dispatcher + .dismiss_handoff(&mut send, &mut recv, "h-42".into(), &q) + .await + .expect("dismiss delivered"); + + assert_eq!(ack.handoff_id, "h-42"); + assert!(ack.success); + + let (server_res, _server_conn) = server_task.await.unwrap(); + server_res.unwrap(); + } + + #[test] + fn handoff_validation_rejects_oversized_uri() { + let oversized_uri = "https://example.com/".repeat(300); // > 4096 bytes + let item = HandoffItem { + handoff_id: "h-overflow".into(), + source_device_id: "src".into(), + handoff_type: HandoffType::Url as i32, + title: "Test".into(), + uri: oversized_uri, + scroll_ratio: 0.0, + cursor_position: 0, + timestamp_ms: 0, + extra_payload: Vec::new(), + }; + + let result = HandoffDispatcher::validate_item(&item); + assert!(result.is_err()); + } +} diff --git a/crates/sessions/src/lib.rs b/crates/sessions/src/lib.rs index cedcbc9..6feeb9e 100644 --- a/crates/sessions/src/lib.rs +++ b/crates/sessions/src/lib.rs @@ -6,13 +6,16 @@ pub mod backoff; pub mod capabilities_router; pub mod device; pub mod error; +pub mod handoff; pub mod incoming; pub mod keepalive; pub mod listener; +pub mod media_control; pub mod multiplexer; pub mod registry; pub mod session; pub mod state; +pub mod telemetry; pub use auto_connect::connect_paired_peers; pub use backoff::ReconnectPolicy; @@ -22,9 +25,11 @@ pub use capabilities_router::{ }; pub use device::{clean_name, this_platform, PeerDevice, ThisDevice}; pub use error::SessionError; +pub use handoff::HandoffDispatcher; pub use incoming::{IncomingEvent, IncomingFile, IncomingFiles, IncomingListener, SaveFolder}; pub use keepalive::KeepaliveTracker; pub use listener::{accept_peers, listen_for_peers, remember_peer_address, DEFAULT_LISTEN_PORT}; +pub use media_control::MediaControlDispatcher; pub use multiplexer::{ close_code, open_capability_stream, read_capability_stream_header, IncomingCapabilityStream, SessionMultiplexer, @@ -32,3 +37,4 @@ pub use multiplexer::{ pub use registry::{Direction, RegistryConfig, SessionRegistry, StateListener, RESEND_WAIT}; pub use session::Session; pub use state::SessionState; +pub use telemetry::{TelemetryAlertEvaluator, TelemetryDispatcher}; diff --git a/crates/sessions/src/media_control.rs b/crates/sessions/src/media_control.rs new file mode 100644 index 0000000..89f2c6a --- /dev/null +++ b/crates/sessions/src/media_control.rs @@ -0,0 +1,274 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use capabilities::{evaluate_capability, CapabilityQuery}; +use limits::MAX_FRAME_MEDIA_CONTROL_BYTES; +use protocol::v1::{ + media_control_envelope::Payload, MediaCommandRequest, MediaCommandResponse, + MediaControlEnvelope, MediaStatusUpdate, +}; +use transport::{read_msg, write_msg}; + +use crate::error::SessionError; + +#[derive(Default)] +pub struct MediaControlDispatcher; + +impl MediaControlDispatcher { + pub fn new() -> Self { + Self + } + + pub async fn send_command( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + request: MediaCommandRequest, + query: &CapabilityQuery, + ) -> Result { + evaluate_capability(query)?; + + let envelope = MediaControlEnvelope { + payload: Some(Payload::CommandRequest(request)), + }; + + write_msg(send_stream, &envelope, MAX_FRAME_MEDIA_CONTROL_BYTES).await?; + let response: MediaCommandResponse = + read_msg(recv_stream, MAX_FRAME_MEDIA_CONTROL_BYTES).await?; + + if !response.success { + return Err(SessionError::MediaControlRejected(response.error_message)); + } + + Ok(response) + } + + pub async fn publish_status( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + update: MediaStatusUpdate, + query: &CapabilityQuery, + ) -> Result { + evaluate_capability(query)?; + + let envelope = MediaControlEnvelope { + payload: Some(Payload::StatusUpdate(update)), + }; + + write_msg(send_stream, &envelope, MAX_FRAME_MEDIA_CONTROL_BYTES).await?; + let ack: MediaCommandResponse = + read_msg(recv_stream, MAX_FRAME_MEDIA_CONTROL_BYTES).await?; + + Ok(ack) + } + + pub async fn receive_envelope( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + query: &CapabilityQuery, + mut on_command: HC, + mut on_status: HS, + ) -> Result + where + HC: FnMut(MediaCommandRequest) -> MediaCommandResponse, + HS: FnMut(MediaStatusUpdate), + { + evaluate_capability(query)?; + + let envelope: MediaControlEnvelope = + read_msg(recv_stream, MAX_FRAME_MEDIA_CONTROL_BYTES).await?; + + match envelope.payload.clone() { + Some(Payload::CommandRequest(req)) => { + let resp = on_command(req); + write_msg(send_stream, &resp, MAX_FRAME_MEDIA_CONTROL_BYTES).await?; + } + Some(Payload::StatusUpdate(stat)) => { + on_status(stat); + let ack = MediaCommandResponse { + command_id: String::new(), + success: true, + error_message: String::new(), + }; + write_msg(send_stream, &ack, MAX_FRAME_MEDIA_CONTROL_BYTES).await?; + } + None => { + return Err(SessionError::UnexpectedMessage); + } + } + + Ok(envelope) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use protocol::CapabilityId; + use protocol::v1::{MediaMetadata, MediaPlaybackCommand, MediaPlaybackState}; + use transport::{create_client_endpoint, create_server_endpoint, TransportCertificate}; + use std::collections::HashSet; + + fn test_query(authorized: bool) -> CapabilityQuery { + let mut caps = HashSet::new(); + caps.insert(CapabilityId::MEDIA_CONTROL); + CapabilityQuery { + capability: CapabilityId::MEDIA_CONTROL, + is_os_available: true, + is_app_permitted: true, + is_peer_authorized: authorized, + negotiated_session_capabilities: caps, + } + } + + #[tokio::test] + async fn media_control_command_roundtrip() { + let server_cert = TransportCertificate::generate().unwrap(); + let client_cert = TransportCertificate::generate().unwrap(); + + let server_tls = server_cert + .build_pinned_server_tls(client_cert.spki_hash) + .unwrap(); + let client_tls = client_cert + .build_pinned_client_tls(server_cert.spki_hash) + .unwrap(); + + let server = create_server_endpoint("127.0.0.1:0".parse().unwrap(), server_tls).unwrap(); + let server_addr = server.local_addr().unwrap(); + let client = create_client_endpoint("127.0.0.1:0".parse().unwrap(), client_tls).unwrap(); + + let server_task = tokio::spawn(async move { + let incoming = server.accept().await.unwrap(); + let conn = incoming.await.unwrap(); + let (mut send, mut recv) = conn.accept_bi().await.unwrap(); + + let dispatcher = MediaControlDispatcher::new(); + let q = test_query(true); + + let result = dispatcher + .receive_envelope( + &mut send, + &mut recv, + &q, + |cmd| { + assert_eq!(cmd.command, MediaPlaybackCommand::Play as i32); + MediaCommandResponse { + command_id: cmd.command_id, + success: true, + error_message: String::new(), + } + }, + |_| {}, + ) + .await; + + (result, conn) + }); + + let conn = client + .connect(server_addr, "continue-device") + .unwrap() + .await + .unwrap(); + let (mut send, mut recv) = conn.open_bi().await.unwrap(); + + let dispatcher = MediaControlDispatcher::new(); + let q = test_query(true); + + let req = MediaCommandRequest { + command_id: "cmd-1".into(), + command: MediaPlaybackCommand::Play as i32, + seek_position_ms: 0, + volume: 1.0, + }; + + let resp = dispatcher + .send_command(&mut send, &mut recv, req, &q) + .await + .expect("command delivered"); + + assert_eq!(resp.command_id, "cmd-1"); + assert!(resp.success); + + let (server_res, _server_conn) = server_task.await.unwrap(); + server_res.unwrap(); + } + + #[tokio::test] + async fn media_control_status_update_roundtrip() { + let server_cert = TransportCertificate::generate().unwrap(); + let client_cert = TransportCertificate::generate().unwrap(); + + let server_tls = server_cert + .build_pinned_server_tls(client_cert.spki_hash) + .unwrap(); + let client_tls = client_cert + .build_pinned_client_tls(server_cert.spki_hash) + .unwrap(); + + let server = create_server_endpoint("127.0.0.1:0".parse().unwrap(), server_tls).unwrap(); + let server_addr = server.local_addr().unwrap(); + let client = create_client_endpoint("127.0.0.1:0".parse().unwrap(), client_tls).unwrap(); + + let server_task = tokio::spawn(async move { + let incoming = server.accept().await.unwrap(); + let conn = incoming.await.unwrap(); + let (mut send, mut recv) = conn.accept_bi().await.unwrap(); + + let dispatcher = MediaControlDispatcher::new(); + let q = test_query(true); + + let result = dispatcher + .receive_envelope( + &mut send, + &mut recv, + &q, + |_| unreachable!(), + |stat| { + let meta = stat.metadata.unwrap(); + assert_eq!(meta.title, "Track One"); + assert_eq!(meta.artist, "Artist Name"); + }, + ) + .await; + + (result, conn) + }); + + let conn = client + .connect(server_addr, "continue-device") + .unwrap() + .await + .unwrap(); + let (mut send, mut recv) = conn.open_bi().await.unwrap(); + + let dispatcher = MediaControlDispatcher::new(); + let q = test_query(true); + + let update = MediaStatusUpdate { + metadata: Some(MediaMetadata { + title: "Track One".into(), + artist: "Artist Name".into(), + album: "Album Name".into(), + duration_ms: 210000, + position_ms: 45000, + state: MediaPlaybackState::Playing as i32, + volume: 0.8, + artwork_thumbnail: Vec::new(), + }), + timestamp_ms: 1000, + }; + + let ack = dispatcher + .publish_status(&mut send, &mut recv, update, &q) + .await + .expect("status published"); + + assert!(ack.success); + + let (server_res, _server_conn) = server_task.await.unwrap(); + server_res.unwrap(); + } +} diff --git a/crates/sessions/src/telemetry.rs b/crates/sessions/src/telemetry.rs new file mode 100644 index 0000000..3f099de --- /dev/null +++ b/crates/sessions/src/telemetry.rs @@ -0,0 +1,221 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use capabilities::{evaluate_capability, CapabilityQuery}; +use limits::MAX_FRAME_TELEMETRY_BYTES; +use protocol::v1::{ + telemetry_envelope::Payload, DeviceTelemetry, TelemetryAck, TelemetryEnvelope, +}; +use transport::{read_msg, write_msg}; + +use crate::error::SessionError; + +pub const DEFAULT_LOW_BATTERY_THRESHOLD_PERCENT: u32 = 15; + +#[derive(Default)] +pub struct TelemetryDispatcher; + +impl TelemetryDispatcher { + pub fn new() -> Self { + Self + } + + pub async fn publish_telemetry( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + telemetry: DeviceTelemetry, + query: &CapabilityQuery, + ) -> Result { + evaluate_capability(query)?; + + let envelope = TelemetryEnvelope { + payload: Some(Payload::Telemetry(telemetry)), + }; + + write_msg(send_stream, &envelope, MAX_FRAME_TELEMETRY_BYTES).await?; + let ack: TelemetryAck = read_msg(recv_stream, MAX_FRAME_TELEMETRY_BYTES).await?; + + Ok(ack) + } + + pub async fn receive_envelope( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + query: &CapabilityQuery, + mut on_telemetry: H, + ) -> Result + where + H: FnMut(DeviceTelemetry) -> Result<(), String>, + { + evaluate_capability(query)?; + + let envelope: TelemetryEnvelope = read_msg(recv_stream, MAX_FRAME_TELEMETRY_BYTES).await?; + + match envelope.payload { + Some(Payload::Telemetry(telemetry)) => { + let success = on_telemetry(telemetry.clone()).is_ok(); + let ack = TelemetryAck { success }; + write_msg(send_stream, &ack, MAX_FRAME_TELEMETRY_BYTES).await?; + Ok(telemetry) + } + Some(Payload::Ack(_)) | None => Err(SessionError::UnexpectedMessage), + } + } +} + +pub struct TelemetryAlertEvaluator { + pub low_battery_threshold: u32, + alerted_low_battery: bool, +} + +impl Default for TelemetryAlertEvaluator { + fn default() -> Self { + Self { + low_battery_threshold: DEFAULT_LOW_BATTERY_THRESHOLD_PERCENT, + alerted_low_battery: false, + } + } +} + +impl TelemetryAlertEvaluator { + pub fn new(threshold: u32) -> Self { + Self { + low_battery_threshold: threshold, + alerted_low_battery: false, + } + } + + pub fn evaluate_low_battery(&mut self, level: u32, is_charging: bool) -> bool { + if is_charging || level > self.low_battery_threshold { + self.alerted_low_battery = false; + return false; + } + + if !self.alerted_low_battery && level <= self.low_battery_threshold { + self.alerted_low_battery = true; + return true; + } + + false + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashSet; + use protocol::CapabilityId; + use protocol::v1::{BatteryState, ChargingType, RadioState}; + use transport::{create_client_endpoint, create_server_endpoint, TransportCertificate}; + + fn test_query(authorized: bool) -> CapabilityQuery { + let mut caps = HashSet::new(); + caps.insert(CapabilityId::TELEMETRY); + CapabilityQuery { + capability: CapabilityId::TELEMETRY, + is_os_available: true, + is_app_permitted: true, + is_peer_authorized: authorized, + negotiated_session_capabilities: caps, + } + } + + #[tokio::test] + async fn telemetry_publish_receive_roundtrip() { + let server_cert = TransportCertificate::generate().unwrap(); + let client_cert = TransportCertificate::generate().unwrap(); + + let server_tls = server_cert + .build_pinned_server_tls(client_cert.spki_hash) + .unwrap(); + let client_tls = client_cert + .build_pinned_client_tls(server_cert.spki_hash) + .unwrap(); + + let server = create_server_endpoint("127.0.0.1:0".parse().unwrap(), server_tls).unwrap(); + let server_addr = server.local_addr().unwrap(); + let client = create_client_endpoint("127.0.0.1:0".parse().unwrap(), client_tls).unwrap(); + + let server_task = tokio::spawn(async move { + let incoming = server.accept().await.unwrap(); + let conn = incoming.await.unwrap(); + let (mut send, mut recv) = conn.accept_bi().await.unwrap(); + + let dispatcher = TelemetryDispatcher::new(); + let q = test_query(true); + + let res = dispatcher + .receive_envelope(&mut send, &mut recv, &q, |t| { + let bat = t.battery.unwrap(); + assert_eq!(bat.level_percent, 85); + assert!(bat.is_charging); + assert_eq!(bat.charging_type, ChargingType::Ac as i32); + Ok(()) + }) + .await; + + (res, conn) + }); + + let conn = client + .connect(server_addr, "continue-device") + .unwrap() + .await + .unwrap(); + let (mut send, mut recv) = conn.open_bi().await.unwrap(); + + let dispatcher = TelemetryDispatcher::new(); + let q = test_query(true); + + let telemetry = DeviceTelemetry { + device_id: "phone-42".into(), + timestamp_ms: 1000, + battery: Some(BatteryState { + level_percent: 85, + is_charging: true, + charging_type: ChargingType::Ac as i32, + is_low_power: false, + }), + radio: Some(RadioState { + wifi_connected: true, + wifi_ssid: "HomeNet".into(), + wifi_rssi_dbm: -55, + cellular_connected: true, + cellular_signal_level: 4, + cellular_operator: "Carrier".into(), + }), + }; + + let ack = dispatcher + .publish_telemetry(&mut send, &mut recv, telemetry, &q) + .await + .expect("telemetry published"); + + assert!(ack.success); + + let (server_res, _server_conn) = server_task.await.unwrap(); + server_res.unwrap(); + } + + #[test] + fn low_battery_evaluator_fires_once_and_resets_on_charge() { + let mut evaluator = TelemetryAlertEvaluator::new(15); + + // 20% discharging: no alert + assert!(!evaluator.evaluate_low_battery(20, false)); + + // Drops to 15% discharging: fires once + assert!(evaluator.evaluate_low_battery(15, false)); + + // Stays at 14% discharging: does not fire repeatedly + assert!(!evaluator.evaluate_low_battery(14, false)); + + // Plugged into charger: resets state + assert!(!evaluator.evaluate_low_battery(14, true)); + + // Unplugged at 14%: fires again + assert!(evaluator.evaluate_low_battery(14, false)); + } +} diff --git a/crates/transfer/Cargo.toml b/crates/transfer/Cargo.toml index 6dc8b54..a8a9f10 100644 --- a/crates/transfer/Cargo.toml +++ b/crates/transfer/Cargo.toml @@ -12,11 +12,14 @@ transport = { path = "../transport" } quinn = { workspace = true } tokio = { workspace = true, features = ["fs", "io-util", "sync", "rt", "macros"] } sha2 = { workspace = true } +bytes = { workspace = true } hex = { workspace = true } thiserror = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +rand = { workspace = true } [dev-dependencies] rustls = { workspace = true } rcgen = { workspace = true } -rand = { workspace = true } tokio = { workspace = true, features = ["full"] } diff --git a/crates/transfer/src/capture.rs b/crates/transfer/src/capture.rs new file mode 100644 index 0000000..ca291bf --- /dev/null +++ b/crates/transfer/src/capture.rs @@ -0,0 +1,348 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use sha2::{Digest, Sha256}; +use std::future::Future; +use std::path::{Path, PathBuf}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +use limits::{MAX_FRAME_MEDIA_CAPTURE_BYTES, TRANSFER_CHUNK_BYTES}; +use protocol::v1::{ + CameraCaptureAck, CameraCaptureDestination, CameraCaptureMode, CameraCaptureRequest, + CameraCaptureResponse, CameraCaptureStatus, +}; +use transport::{read_msg, write_msg}; + +use crate::error::TransferError; +use crate::sanitizer::sanitize_filename; +use crate::sender::compute_file_sha256; + +const BITMAPV5_HEADER_SIZE: usize = 124; +const BI_BITFIELDS: u32 = 3; +const LCS_SRGB: u32 = 0x7352_4742; +const LCS_GM_IMAGES: u32 = 4; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CapturedMedia { + pub capture_id: String, + pub mode: CameraCaptureMode, + pub destination: CameraCaptureDestination, + pub file_name: String, + pub path: PathBuf, + pub mime_type: String, + pub bytes_received: u64, + pub sha256_checksum: [u8; 32], + pub width: u32, + pub height: u32, +} + +#[derive(Debug, Clone)] +pub struct CameraCaptureSource { + pub file_path: PathBuf, + pub mime_type: String, + pub width: u32, + pub height: u32, +} + +/// Formats raw BGRA uncompressed pixel buffers into the Windows CF_DIBV5 layout. +pub fn format_as_clipboard_dibv5( + width: u32, + height: u32, + bgra_pixels: &[u8], +) -> Result, TransferError> { + let expected_len = (width as usize) + .checked_mul(height as usize) + .and_then(|pixels| pixels.checked_mul(4)) + .ok_or_else(|| { + TransferError::InvalidFilename("Dimensions exceed addressable bounds".to_string()) + })?; + + if bgra_pixels.len() != expected_len { + return Err(TransferError::SizeMismatch { + expected: expected_len as u64, + actual: bgra_pixels.len() as u64, + }); + } + + let mut out = Vec::with_capacity(BITMAPV5_HEADER_SIZE + expected_len); + + out.extend_from_slice(&(BITMAPV5_HEADER_SIZE as u32).to_le_bytes()); + out.extend_from_slice(&(width as i32).to_le_bytes()); + // Negative height signals a top-down DIB so rows need no vertical flip. + out.extend_from_slice(&(-(height as i32)).to_le_bytes()); + out.extend_from_slice(&1u16.to_le_bytes()); + out.extend_from_slice(&32u16.to_le_bytes()); + out.extend_from_slice(&BI_BITFIELDS.to_le_bytes()); + out.extend_from_slice(&(expected_len as u32).to_le_bytes()); + out.extend_from_slice(&0i32.to_le_bytes()); + out.extend_from_slice(&0i32.to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); + + // Color channel masks + out.extend_from_slice(&0x00FF_0000u32.to_le_bytes()); + out.extend_from_slice(&0x0000_FF00u32.to_le_bytes()); + out.extend_from_slice(&0x0000_00FFu32.to_le_bytes()); + out.extend_from_slice(&0xFF00_0000u32.to_le_bytes()); + + // Color space and endpoints + out.extend_from_slice(&LCS_SRGB.to_le_bytes()); + out.extend_from_slice(&[0u8; 36]); // CIEXYZTRIPLE endpoints + out.extend_from_slice(&0u32.to_le_bytes()); // Gamma red + out.extend_from_slice(&0u32.to_le_bytes()); // Gamma green + out.extend_from_slice(&0u32.to_le_bytes()); // Gamma blue + out.extend_from_slice(&LCS_GM_IMAGES.to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); + + debug_assert_eq!(out.len(), BITMAPV5_HEADER_SIZE); + out.extend_from_slice(bgra_pixels); + + Ok(out) +} + +pub async fn request_camera_capture( + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + destination_dir: &Path, + request: CameraCaptureRequest, +) -> Result { + write_msg(send_stream, &request, MAX_FRAME_MEDIA_CAPTURE_BYTES).await?; + + let mut carry = bytes::BytesMut::with_capacity(TRANSFER_CHUNK_BYTES); + let resp: CameraCaptureResponse = loop { + if let Some(msg) = protocol::decode_frame_from_buf::( + &mut carry, + MAX_FRAME_MEDIA_CAPTURE_BYTES, + )? { + break msg; + } + let mut chunk = [0u8; 4096]; + match recv_stream.read(&mut chunk).await? { + Some(n) if n > 0 => carry.extend_from_slice(&chunk[..n]), + _ => return Err(TransferError::UnexpectedResponse), + } + }; + + match CameraCaptureStatus::try_from(resp.status) { + Ok(CameraCaptureStatus::Success) => {} + Ok(CameraCaptureStatus::Declined) => { + return Err(TransferError::CaptureRejected(resp.reason)); + } + Ok(CameraCaptureStatus::Busy) => return Err(TransferError::CaptureBusy), + Ok(CameraCaptureStatus::Unsupported) => return Err(TransferError::CaptureUnsupported), + Ok(CameraCaptureStatus::Error) => return Err(TransferError::CaptureRejected(resp.reason)), + _ => return Err(TransferError::UnexpectedResponse), + } + + let default_ext = if resp.mime_type.contains("pdf") { + "pdf" + } else { + "jpg" + }; + + let raw_name = if resp.file_name.is_empty() { + format!("{}_{}.{}", match CameraCaptureMode::try_from(request.mode) { + Ok(CameraCaptureMode::DocumentScan) => "scan", + _ => "photo", + }, resp.capture_id, default_ext) + } else { + resp.file_name + }; + + let file_name = sanitize_filename(&raw_name)?; + tokio::fs::create_dir_all(destination_dir).await?; + + let final_path = destination_dir.join(&file_name); + let part_path = destination_dir.join(format!("{}.part", file_name)); + + let mut part_file = tokio::fs::File::create(&part_path).await?; + let mut hasher = Sha256::new(); + let mut total_received = 0u64; + + if !carry.is_empty() { + let initial_chunk = carry.freeze(); + hasher.update(&initial_chunk); + part_file.write_all(&initial_chunk).await?; + total_received += initial_chunk.len() as u64; + } + + while total_received < resp.file_size { + let to_read = std::cmp::min( + (resp.file_size - total_received) as usize, + TRANSFER_CHUNK_BYTES, + ); + let mut buf = vec![0u8; to_read]; + let n = match recv_stream.read(&mut buf).await? { + Some(n) if n > 0 => n, + _ => { + let _ = tokio::fs::remove_file(&part_path).await; + return Err(TransferError::SizeMismatch { + expected: resp.file_size, + actual: total_received, + }); + } + }; + + hasher.update(&buf[..n]); + part_file.write_all(&buf[..n]).await?; + total_received += n as u64; + } + + part_file.flush().await?; + drop(part_file); + + let actual_sha: [u8; 32] = hasher.finalize().into(); + if actual_sha.as_slice() != resp.sha256_checksum.as_slice() { + let _ = tokio::fs::remove_file(&part_path).await; + return Err(TransferError::ChecksumMismatch { + expected: hex::encode(&resp.sha256_checksum), + actual: hex::encode(actual_sha), + }); + } + + tokio::fs::rename(&part_path, &final_path).await?; + + let ack = CameraCaptureAck { + capture_id: resp.capture_id.clone(), + bytes_received: total_received, + verified: true, + }; + write_msg(send_stream, &ack, MAX_FRAME_MEDIA_CAPTURE_BYTES).await?; + send_stream.flush().await?; + + let mode = CameraCaptureMode::try_from(request.mode).unwrap_or(CameraCaptureMode::Unspecified); + let destination = CameraCaptureDestination::try_from(request.destination) + .unwrap_or(CameraCaptureDestination::Unspecified); + + Ok(CapturedMedia { + capture_id: resp.capture_id, + mode, + destination, + file_name, + path: final_path, + mime_type: resp.mime_type, + bytes_received: total_received, + sha256_checksum: actual_sha, + width: resp.width, + height: resp.height, + }) +} + +pub async fn respond_camera_capture( + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + provider: P, +) -> Result<(), TransferError> +where + P: FnOnce(CameraCaptureRequest) -> Fut, + Fut: Future>, +{ + let req: CameraCaptureRequest = + read_msg(recv_stream, MAX_FRAME_MEDIA_CAPTURE_BYTES).await?; + + let source = match provider(req.clone()).await { + Ok(source) => source, + Err(e) => { + let (status, reason) = match &e { + TransferError::CaptureBusy => (CameraCaptureStatus::Busy, "Camera is busy".into()), + TransferError::CaptureUnsupported => { + (CameraCaptureStatus::Unsupported, "Camera unavailable".into()) + } + TransferError::CaptureRejected(r) => (CameraCaptureStatus::Declined, r.clone()), + other => (CameraCaptureStatus::Error, other.to_string()), + }; + let resp = CameraCaptureResponse { + capture_id: req.capture_id, + status: status as i32, + reason, + mime_type: String::new(), + file_size: 0, + sha256_checksum: Vec::new(), + width: 0, + height: 0, + file_name: String::new(), + }; + write_msg(send_stream, &resp, MAX_FRAME_MEDIA_CAPTURE_BYTES).await?; + return Err(e); + } + }; + + let mut file = tokio::fs::File::open(&source.file_path).await?; + let meta = file.metadata().await?; + let file_size = meta.len(); + let sha256_bytes = compute_file_sha256(&source.file_path).await?; + + let file_name = source + .file_path + .file_name() + .and_then(|n| n.to_str()) + .map(|s| s.to_string()) + .unwrap_or_default(); + + let resp = CameraCaptureResponse { + capture_id: req.capture_id.clone(), + status: CameraCaptureStatus::Success as i32, + reason: String::new(), + mime_type: source.mime_type, + file_size, + sha256_checksum: sha256_bytes.to_vec(), + width: source.width, + height: source.height, + file_name, + }; + write_msg(send_stream, &resp, MAX_FRAME_MEDIA_CAPTURE_BYTES).await?; + + let mut buf = vec![0u8; TRANSFER_CHUNK_BYTES]; + loop { + let n = file.read(&mut buf).await?; + if n == 0 { + break; + } + send_stream.write_all(&buf[..n]).await?; + } + send_stream.flush().await?; + + let ack: CameraCaptureAck = read_msg(recv_stream, MAX_FRAME_MEDIA_CAPTURE_BYTES).await?; + if !ack.verified { + return Err(TransferError::UnexpectedResponse); + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn format_dibv5_validates_dimensions_and_packs_header() { + let width = 2; + let height = 2; + let pixels = vec![255u8; 16]; // 2 * 2 * 4 bytes + + let dib = format_as_clipboard_dibv5(width, height, &pixels).unwrap(); + assert_eq!(dib.len(), BITMAPV5_HEADER_SIZE + 16); + + // Check header size field + let header_size = u32::from_le_bytes(dib[0..4].try_into().unwrap()); + assert_eq!(header_size, BITMAPV5_HEADER_SIZE as u32); + + // Check width and top-down height + let w = i32::from_le_bytes(dib[4..8].try_into().unwrap()); + let h = i32::from_le_bytes(dib[8..12].try_into().unwrap()); + assert_eq!(w, 2); + assert_eq!(h, -2); + } + + #[test] + fn format_dibv5_rejects_mismatched_pixel_buffer() { + let width = 2; + let height = 2; + let pixels = vec![0u8; 12]; // Needs 16 bytes + + let err = format_as_clipboard_dibv5(width, height, &pixels).unwrap_err(); + assert!(matches!(err, TransferError::SizeMismatch { .. })); + } +} diff --git a/crates/transfer/src/error.rs b/crates/transfer/src/error.rs index a524fae..14be917 100644 --- a/crates/transfer/src/error.rs +++ b/crates/transfer/src/error.rs @@ -26,6 +26,9 @@ pub enum TransferError { #[error("Protocol error: {0}")] Protocol(#[from] protocol::ProtocolError), + #[error("Frame error: {0}")] + Frame(#[from] protocol::FrameError), + #[error("Invalid filename: {0}")] InvalidFilename(String), @@ -49,4 +52,19 @@ pub enum TransferError { #[error("Not connected to that device")] NotConnected, + + #[error("Media capture rejected: {0}")] + CaptureRejected(String), + + #[error("Media capture unsupported on remote device")] + CaptureUnsupported, + + #[error("Media capture device is busy")] + CaptureBusy, + + #[error("Bridge session error: {0}")] + BridgeSession(String), + + #[error("Transfer queue full: {0}")] + QueueFull(String), } diff --git a/crates/transfer/src/lib.rs b/crates/transfer/src/lib.rs index 642574c..048cb81 100644 --- a/crates/transfer/src/lib.rs +++ b/crates/transfer/src/lib.rs @@ -3,13 +3,26 @@ //! Streaming file transfer, one QUIC stream per file. +pub mod capture; pub mod error; +pub mod localsend_bridge; mod partial; +pub mod queue; pub mod receiver; pub mod sanitizer; pub mod sender; +pub use capture::{ + format_as_clipboard_dibv5, request_camera_capture, respond_camera_capture, CameraCaptureSource, + CapturedMedia, +}; pub use error::TransferError; +pub use localsend_bridge::{ + LocalSendActiveSession, LocalSendBridgeSessionManager, LocalSendFileMetadata, + LocalSendPrepareRequest, LocalSendPrepareResponse, LocalSendSanitizedFile, LocalSendSenderInfo, +}; +pub use queue::{OfflineTransferQueue, QueuedPayload, QueuedTransfer}; pub use receiver::{receive_file, ReceivedFile}; pub use sanitizer::sanitize_filename; pub use sender::{compute_file_sha256, send_file}; + diff --git a/crates/transfer/src/localsend_bridge.rs b/crates/transfer/src/localsend_bridge.rs new file mode 100644 index 0000000..ef259d0 --- /dev/null +++ b/crates/transfer/src/localsend_bridge.rs @@ -0,0 +1,235 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use std::collections::HashMap; +use serde::{Deserialize, Serialize}; + +use crate::error::TransferError; +use crate::sanitizer::sanitize_filename; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct LocalSendSenderInfo { + pub alias: String, + pub version: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub device_model: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub device_type: Option, + pub fingerprint: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct LocalSendFileMetadata { + pub id: String, + pub file_name: String, + pub size: u64, + pub file_type: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub sha256: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct LocalSendPrepareRequest { + pub info: LocalSendSenderInfo, + pub files: HashMap, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct LocalSendPrepareResponse { + pub session_id: String, + pub files: HashMap, +} + +#[derive(Debug, Clone)] +pub struct LocalSendSanitizedFile { + pub id: String, + pub sanitized_name: String, + pub size: u64, + pub file_type: String, + pub token: String, + pub completed: bool, +} + +#[derive(Debug, Clone)] +pub struct LocalSendActiveSession { + pub session_id: String, + pub sender: LocalSendSenderInfo, + pub files: HashMap, +} + +#[derive(Default)] +pub struct LocalSendBridgeSessionManager { + sessions: HashMap, +} + +impl LocalSendBridgeSessionManager { + pub fn new() -> Self { + Self::default() + } + + pub fn prepare_upload( + &mut self, + req: LocalSendPrepareRequest, + ) -> Result { + let session_id = format!("ls-sess-{}", rand::random::()); + let mut response_files = HashMap::new(); + let mut session_files = HashMap::new(); + + for (file_id, meta) in req.files { + let sanitized_name = sanitize_filename(&meta.file_name)?; + let token = format!("tok-{}", rand::random::()); + + response_files.insert(file_id.clone(), token.clone()); + session_files.insert( + file_id.clone(), + LocalSendSanitizedFile { + id: file_id, + sanitized_name, + size: meta.size, + file_type: meta.file_type, + token, + completed: false, + }, + ); + } + + let session = LocalSendActiveSession { + session_id: session_id.clone(), + sender: req.info, + files: session_files, + }; + + self.sessions.insert(session_id.clone(), session); + + Ok(LocalSendPrepareResponse { + session_id, + files: response_files, + }) + } + + pub fn verify_upload( + &self, + session_id: &str, + file_id: &str, + token: &str, + ) -> Result<&LocalSendSanitizedFile, TransferError> { + let session = self + .sessions + .get(session_id) + .ok_or_else(|| TransferError::BridgeSession("Session not found".into()))?; + + let file = session + .files + .get(file_id) + .ok_or_else(|| TransferError::BridgeSession("File ID not found in session".into()))?; + + if file.token != token { + return Err(TransferError::BridgeSession("Invalid upload token".into())); + } + + Ok(file) + } + + pub fn mark_completed( + &mut self, + session_id: &str, + file_id: &str, + ) -> Result<(), TransferError> { + let session = self + .sessions + .get_mut(session_id) + .ok_or_else(|| TransferError::BridgeSession("Session not found".into()))?; + + let file = session + .files + .get_mut(file_id) + .ok_or_else(|| TransferError::BridgeSession("File ID not found in session".into()))?; + + file.completed = true; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn prepare_upload_sanitizes_filenames_and_issues_tokens() { + let mut manager = LocalSendBridgeSessionManager::new(); + + let mut files = HashMap::new(); + files.insert( + "f1".into(), + LocalSendFileMetadata { + id: "f1".into(), + file_name: "../../../evil/payload.sh".into(), + size: 1024, + file_type: "text/x-sh".into(), + sha256: None, + }, + ); + + let req = LocalSendPrepareRequest { + info: LocalSendSenderInfo { + alias: "iPhone".into(), + version: "2.0".into(), + device_model: Some("iPhone 15".into()), + device_type: Some("mobile".into()), + fingerprint: "ls-iphone-1".into(), + }, + files, + }; + + let resp = manager.prepare_upload(req).expect("prepare success"); + assert!(resp.files.contains_key("f1")); + let token = resp.files.get("f1").unwrap(); + + let verified = manager.verify_upload(&resp.session_id, "f1", token).unwrap(); + // Filename traversal components stripped to safe basename + assert_eq!(verified.sanitized_name, "payload.sh"); + assert_eq!(verified.size, 1024); + + // Verification fails with invalid token + assert!(manager.verify_upload(&resp.session_id, "f1", "bad-tok").is_err()); + } + + #[test] + fn marks_file_upload_completed() { + let mut manager = LocalSendBridgeSessionManager::new(); + + let mut files = HashMap::new(); + files.insert( + "img-01".into(), + LocalSendFileMetadata { + id: "img-01".into(), + file_name: "photo.jpg".into(), + size: 2048, + file_type: "image/jpeg".into(), + sha256: None, + }, + ); + + let req = LocalSendPrepareRequest { + info: LocalSendSenderInfo { + alias: "MacBook".into(), + version: "2.0".into(), + device_model: Some("MacBook Pro".into()), + device_type: Some("desktop".into()), + fingerprint: "ls-mac-1".into(), + }, + files, + }; + + let resp = manager.prepare_upload(req).unwrap(); + manager.mark_completed(&resp.session_id, "img-01").unwrap(); + + let verified = manager + .verify_upload(&resp.session_id, "img-01", resp.files.get("img-01").unwrap()) + .unwrap(); + assert!(verified.completed); + } +} diff --git a/crates/transfer/src/queue.rs b/crates/transfer/src/queue.rs new file mode 100644 index 0000000..a548245 --- /dev/null +++ b/crates/transfer/src/queue.rs @@ -0,0 +1,434 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use std::collections::{HashMap, VecDeque}; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; + +use crate::error::TransferError; + +pub const DEFAULT_MAX_ITEMS_PER_PEER: usize = 50; +pub const DEFAULT_MAX_TOTAL_ITEMS: usize = 500; + +fn current_timestamp() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +fn generate_item_id() -> String { + use rand::Rng; + let mut rng = rand::thread_rng(); + let rand_num: u64 = rng.gen(); + format!("{:016x}", rand_num) +} + +/// Payload stored in the offline queue awaiting peer connection. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum QueuedPayload { + /// File stored locally to send when peer is reachable. + File { + path: PathBuf, + relative_name: String, + mime_type: Option, + }, + /// Clipboard content to sync. + Clipboard { + content: Vec, + mime_type: String, + }, + /// Handoff item (e.g. active tab URL). + Handoff { + uri: String, + title: Option, + }, +} + +/// Individual item held in the offline queue. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct QueuedTransfer { + pub id: String, + pub peer_fingerprint: String, + pub payload: QueuedPayload, + pub queued_at: u64, +} + +#[derive(Debug, Default)] +struct QueueInner { + queues: HashMap>, + total_count: usize, +} + +/// Thread-safe in-memory queue for staging transfers destined for currently unreachable peers. +#[derive(Debug, Clone)] +pub struct OfflineTransferQueue { + inner: Arc>, + max_items_per_peer: usize, + max_total_items: usize, +} + +impl Default for OfflineTransferQueue { + fn default() -> Self { + Self::new() + } +} + +impl OfflineTransferQueue { + pub fn new() -> Self { + Self::with_capacities(DEFAULT_MAX_ITEMS_PER_PEER, DEFAULT_MAX_TOTAL_ITEMS) + } + + pub fn with_capacities(max_items_per_peer: usize, max_total_items: usize) -> Self { + Self { + inner: Arc::new(Mutex::new(QueueInner::default())), + max_items_per_peer, + max_total_items, + } + } + + /// Enqueues a payload for the given peer fingerprint. + pub fn enqueue( + &self, + peer_fingerprint: &str, + payload: QueuedPayload, + ) -> Result { + let mut inner = self.inner.lock().unwrap(); + + if inner.total_count >= self.max_total_items { + return Err(TransferError::QueueFull(format!( + "Total offline queue capacity ({}) exceeded", + self.max_total_items + ))); + } + + let peer_queue = inner + .queues + .entry(peer_fingerprint.to_string()) + .or_default(); + + if peer_queue.len() >= self.max_items_per_peer { + return Err(TransferError::QueueFull(format!( + "Peer offline queue capacity ({}) exceeded for {}", + self.max_items_per_peer, peer_fingerprint + ))); + } + + let id = generate_item_id(); + let item = QueuedTransfer { + id: id.clone(), + peer_fingerprint: peer_fingerprint.to_string(), + payload, + queued_at: current_timestamp(), + }; + + peer_queue.push_back(item); + inner.total_count += 1; + + Ok(id) + } + + /// Drains all queued transfers for the specified peer in FIFO order. + pub fn drain_for_peer(&self, peer_fingerprint: &str) -> Vec { + let mut inner = self.inner.lock().unwrap(); + if let Some(queue) = inner.queues.remove(peer_fingerprint) { + inner.total_count = inner.total_count.saturating_sub(queue.len()); + queue.into() + } else { + Vec::new() + } + } + + /// Returns a snapshot of queued transfers for the peer without removing them. + pub fn peek_for_peer(&self, peer_fingerprint: &str) -> Vec { + let inner = self.inner.lock().unwrap(); + inner + .queues + .get(peer_fingerprint) + .map(|q| q.iter().cloned().collect()) + .unwrap_or_default() + } + + /// Cancels and removes a specific queued item by ID. + pub fn remove_item(&self, peer_fingerprint: &str, item_id: &str) -> bool { + let mut inner = self.inner.lock().unwrap(); + let (removed, is_empty) = if let Some(queue) = inner.queues.get_mut(peer_fingerprint) { + let removed = if let Some(idx) = queue.iter().position(|item| item.id == item_id) { + queue.remove(idx); + true + } else { + false + }; + (removed, queue.is_empty()) + } else { + (false, false) + }; + + if removed { + inner.total_count = inner.total_count.saturating_sub(1); + } + if is_empty { + inner.queues.remove(peer_fingerprint); + } + + removed + } + + /// Clears all queued items for a peer. + pub fn clear_peer(&self, peer_fingerprint: &str) -> usize { + let mut inner = self.inner.lock().unwrap(); + if let Some(queue) = inner.queues.remove(peer_fingerprint) { + let count = queue.len(); + inner.total_count = inner.total_count.saturating_sub(count); + count + } else { + 0 + } + } + + /// Number of items pending for a specific peer. + pub fn pending_count_for_peer(&self, peer_fingerprint: &str) -> usize { + let inner = self.inner.lock().unwrap(); + inner + .queues + .get(peer_fingerprint) + .map_or(0, |q| q.len()) + } + + /// Total items pending across all peers. + pub fn total_pending_count(&self) -> usize { + let inner = self.inner.lock().unwrap(); + inner.total_count + } + + /// List of peer fingerprints that currently have items pending in the queue. + pub fn peers_with_pending(&self) -> Vec { + let inner = self.inner.lock().unwrap(); + inner.queues.keys().cloned().collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn enqueue_and_drain_fifo_order() { + let queue = OfflineTransferQueue::new(); + let peer = "peer-alpha"; + + let id1 = queue + .enqueue( + peer, + QueuedPayload::Handoff { + uri: "https://example.com/item1".to_string(), + title: Some("Item 1".to_string()), + }, + ) + .unwrap(); + + let id2 = queue + .enqueue( + peer, + QueuedPayload::Clipboard { + content: b"clipboard text".to_vec(), + mime_type: "text/plain".to_string(), + }, + ) + .unwrap(); + + assert_eq!(queue.pending_count_for_peer(peer), 2); + assert_eq!(queue.total_pending_count(), 2); + + let drained = queue.drain_for_peer(peer); + assert_eq!(drained.len(), 2); + assert_eq!(drained[0].id, id1); + assert_eq!(drained[1].id, id2); + + assert_eq!(queue.pending_count_for_peer(peer), 0); + assert_eq!(queue.total_pending_count(), 0); + } + + #[test] + fn peer_isolation() { + let queue = OfflineTransferQueue::new(); + let peer1 = "peer-1"; + let peer2 = "peer-2"; + + queue + .enqueue( + peer1, + QueuedPayload::Handoff { + uri: "https://continue.dev".to_string(), + title: None, + }, + ) + .unwrap(); + + assert_eq!(queue.pending_count_for_peer(peer1), 1); + assert_eq!(queue.pending_count_for_peer(peer2), 0); + + let drained_p2 = queue.drain_for_peer(peer2); + assert!(drained_p2.is_empty()); + + let drained_p1 = queue.drain_for_peer(peer1); + assert_eq!(drained_p1.len(), 1); + } + + #[test] + fn peek_does_not_consume() { + let queue = OfflineTransferQueue::new(); + let peer = "peer-beta"; + + queue + .enqueue( + peer, + QueuedPayload::Clipboard { + content: b"snippet".to_vec(), + mime_type: "text/plain".to_string(), + }, + ) + .unwrap(); + + let peeked = queue.peek_for_peer(peer); + assert_eq!(peeked.len(), 1); + assert_eq!(queue.pending_count_for_peer(peer), 1); + + let drained = queue.drain_for_peer(peer); + assert_eq!(drained.len(), 1); + } + + #[test] + fn remove_item_by_id() { + let queue = OfflineTransferQueue::new(); + let peer = "peer-gamma"; + + let id1 = queue + .enqueue( + peer, + QueuedPayload::File { + path: PathBuf::from("photo.png"), + relative_name: "photo.png".to_string(), + mime_type: Some("image/png".to_string()), + }, + ) + .unwrap(); + + let id2 = queue + .enqueue( + peer, + QueuedPayload::Handoff { + uri: "https://example.com".to_string(), + title: None, + }, + ) + .unwrap(); + + assert_eq!(queue.total_pending_count(), 2); + assert!(queue.remove_item(peer, &id1)); + assert_eq!(queue.total_pending_count(), 1); + assert_eq!(queue.pending_count_for_peer(peer), 1); + + let remaining = queue.drain_for_peer(peer); + assert_eq!(remaining.len(), 1); + assert_eq!(remaining[0].id, id2); + } + + #[test] + fn capacity_limits_enforced() { + let queue = OfflineTransferQueue::with_capacities(2, 3); + let peer_a = "peer-a"; + let peer_b = "peer-b"; + + assert!(queue + .enqueue( + peer_a, + QueuedPayload::Clipboard { + content: vec![1], + mime_type: "text/plain".to_string(), + } + ) + .is_ok()); + assert!(queue + .enqueue( + peer_a, + QueuedPayload::Clipboard { + content: vec![2], + mime_type: "text/plain".to_string(), + } + ) + .is_ok()); + + // Peer limit reached + assert!(matches!( + queue.enqueue( + peer_a, + QueuedPayload::Clipboard { + content: vec![3], + mime_type: "text/plain".to_string(), + } + ), + Err(TransferError::QueueFull(_)) + )); + + // Another peer can enqueue up to total capacity + assert!(queue + .enqueue( + peer_b, + QueuedPayload::Clipboard { + content: vec![4], + mime_type: "text/plain".to_string(), + } + ) + .is_ok()); + + // Total limit reached (3 items) + assert!(matches!( + queue.enqueue( + peer_b, + QueuedPayload::Clipboard { + content: vec![5], + mime_type: "text/plain".to_string(), + } + ), + Err(TransferError::QueueFull(_)) + )); + } + + #[test] + fn clear_peer_and_peers_with_pending() { + let queue = OfflineTransferQueue::new(); + let peer1 = "peer-1"; + let peer2 = "peer-2"; + + queue + .enqueue( + peer1, + QueuedPayload::Clipboard { + content: vec![1], + mime_type: "text/plain".to_string(), + }, + ) + .unwrap(); + queue + .enqueue( + peer2, + QueuedPayload::Clipboard { + content: vec![2], + mime_type: "text/plain".to_string(), + }, + ) + .unwrap(); + + let mut peers = queue.peers_with_pending(); + peers.sort(); + assert_eq!(peers, vec!["peer-1".to_string(), "peer-2".to_string()]); + + assert_eq!(queue.clear_peer(peer1), 1); + assert_eq!(queue.peers_with_pending(), vec!["peer-2".to_string()]); + assert_eq!(queue.total_pending_count(), 1); + } +} diff --git a/crates/transfer/tests/capture_e2e.rs b/crates/transfer/tests/capture_e2e.rs new file mode 100644 index 0000000..5bac068 --- /dev/null +++ b/crates/transfer/tests/capture_e2e.rs @@ -0,0 +1,178 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use std::net::SocketAddr; +use transport::{create_client_endpoint, create_server_endpoint, TransportCertificate}; + +use protocol::v1::{ + CameraCaptureDestination, CameraCaptureMode, CameraCaptureRequest, +}; +use transfer::{ + format_as_clipboard_dibv5, request_camera_capture, respond_camera_capture, + CameraCaptureSource, TransferError, +}; + +#[tokio::test] +async fn camera_capture_e2e_photo_success() { + let temp_dir = std::env::temp_dir().join(format!("continue_capture_test_{}", rand::random::())); + let phone_dir = temp_dir.join("phone"); + let pc_dir = temp_dir.join("pc"); + tokio::fs::create_dir_all(&phone_dir).await.unwrap(); + tokio::fs::create_dir_all(&pc_dir).await.unwrap(); + + let captured_image = phone_dir.join("IMG_20261008_013000.jpg"); + let image_data = vec![0xEEu8; 96 * 1024]; + tokio::fs::write(&captured_image, &image_data).await.unwrap(); + + let server_cert = TransportCertificate::generate().unwrap(); + let client_cert = TransportCertificate::generate().unwrap(); + + let server_tls = server_cert + .build_pinned_server_tls(client_cert.spki_hash) + .unwrap(); + let client_tls = client_cert + .build_pinned_client_tls(server_cert.spki_hash) + .unwrap(); + + let server_addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); + let server_endpoint = create_server_endpoint(server_addr, server_tls).unwrap(); + let bound_addr = server_endpoint.local_addr().unwrap(); + + let client_addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); + let client_endpoint = create_client_endpoint(client_addr, client_tls).unwrap(); + + let image_path_clone = captured_image.clone(); + let phone_handle = tokio::spawn(async move { + let incoming = server_endpoint.accept().await.expect("accept"); + let conn = incoming.await.expect("connect"); + let (mut send_stream, mut recv_stream) = conn.accept_bi().await.expect("bi stream"); + + let result = respond_camera_capture( + &mut send_stream, + &mut recv_stream, + |_req: CameraCaptureRequest| async move { + Ok(CameraCaptureSource { + file_path: image_path_clone, + mime_type: "image/jpeg".to_string(), + width: 1920, + height: 1080, + }) + }, + ) + .await; + + (result, conn) + }); + + let client_conn = client_endpoint + .connect(bound_addr, "continue-device") + .unwrap() + .await + .unwrap(); + let (mut send_stream, mut recv_stream) = client_conn.open_bi().await.unwrap(); + + let req = CameraCaptureRequest { + capture_id: "req-capture-42".to_string(), + mode: CameraCaptureMode::Photo as i32, + destination: CameraCaptureDestination::Both as i32, + flash_enabled: false, + max_width: 1920, + max_height: 1080, + }; + + let captured = request_camera_capture(&mut send_stream, &mut recv_stream, &pc_dir, req) + .await + .expect("capture success"); + + let (phone_result, _phone_conn) = phone_handle.await.unwrap(); + phone_result.expect("phone success"); + + assert_eq!(captured.capture_id, "req-capture-42"); + assert_eq!(captured.mode, CameraCaptureMode::Photo); + assert_eq!(captured.destination, CameraCaptureDestination::Both); + assert_eq!(captured.mime_type, "image/jpeg"); + assert_eq!(captured.bytes_received, image_data.len() as u64); + assert_eq!(captured.width, 1920); + assert_eq!(captured.height, 1080); + assert!(captured.path.exists()); + + let saved_bytes = tokio::fs::read(&captured.path).await.unwrap(); + assert_eq!(saved_bytes, image_data); + + let _ = tokio::fs::remove_dir_all(&temp_dir).await; +} + +#[tokio::test] +async fn camera_capture_handles_remote_busy() { + let temp_dir = std::env::temp_dir().join(format!("continue_capture_test_{}", rand::random::())); + tokio::fs::create_dir_all(&temp_dir).await.unwrap(); + + let server_cert = TransportCertificate::generate().unwrap(); + let client_cert = TransportCertificate::generate().unwrap(); + + let server_tls = server_cert + .build_pinned_server_tls(client_cert.spki_hash) + .unwrap(); + let client_tls = client_cert + .build_pinned_client_tls(server_cert.spki_hash) + .unwrap(); + + let server_endpoint = create_server_endpoint("127.0.0.1:0".parse().unwrap(), server_tls).unwrap(); + let bound_addr = server_endpoint.local_addr().unwrap(); + + let client_endpoint = create_client_endpoint("127.0.0.1:0".parse().unwrap(), client_tls).unwrap(); + + let phone_handle = tokio::spawn(async move { + let incoming = server_endpoint.accept().await.expect("accept"); + let conn = incoming.await.expect("connect"); + let (mut send_stream, mut recv_stream) = conn.accept_bi().await.expect("bi stream"); + + let result = respond_camera_capture( + &mut send_stream, + &mut recv_stream, + |_req: CameraCaptureRequest| async move { + Err(TransferError::CaptureBusy) + }, + ) + .await; + + (result, conn) + }); + + let client_conn = client_endpoint + .connect(bound_addr, "continue-device") + .unwrap() + .await + .unwrap(); + let (mut send_stream, mut recv_stream) = client_conn.open_bi().await.unwrap(); + + let req = CameraCaptureRequest { + capture_id: "busy-req-1".to_string(), + mode: CameraCaptureMode::Photo as i32, + destination: CameraCaptureDestination::SaveFile as i32, + flash_enabled: false, + max_width: 0, + max_height: 0, + }; + + let err = request_camera_capture(&mut send_stream, &mut recv_stream, &temp_dir, req) + .await + .expect_err("should fail with busy"); + + assert!(matches!(err, TransferError::CaptureBusy)); + + let (phone_result, _conn) = phone_handle.await.unwrap(); + assert!(matches!(phone_result, Err(TransferError::CaptureBusy))); + + let _ = tokio::fs::remove_dir_all(&temp_dir).await; +} + +#[test] +fn dibv5_conversion_matches_windows_format() { + let width = 4; + let height = 3; + let raw_bgra = vec![0x7F; 4 * 3 * 4]; + + let dib = format_as_clipboard_dibv5(width, height, &raw_bgra).expect("formats dibv5"); + assert_eq!(dib.len(), 124 + raw_bgra.len()); +} diff --git a/proto/handoff.proto b/proto/handoff.proto new file mode 100644 index 0000000..b38f0a9 --- /dev/null +++ b/proto/handoff.proto @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 +syntax = "proto3"; + +package continue.v1; + +enum HandoffType { + HANDOFF_TYPE_UNSPECIFIED = 0; + HANDOFF_TYPE_URL = 1; + HANDOFF_TYPE_DOCUMENT = 2; + HANDOFF_TYPE_MAP = 3; +} + +message HandoffItem { + string handoff_id = 1; + string source_device_id = 2; + HandoffType handoff_type = 3; + string title = 4; + string uri = 5; + float scroll_ratio = 6; + uint64 cursor_position = 7; + uint64 timestamp_ms = 8; + bytes extra_payload = 9; +} + +message HandoffBroadcast { + HandoffItem item = 1; +} + +message HandoffDismiss { + string handoff_id = 1; +} + +message HandoffAck { + string handoff_id = 1; + bool success = 2; + string error_message = 3; +} + +message HandoffEnvelope { + oneof payload { + HandoffBroadcast broadcast = 1; + HandoffDismiss dismiss = 2; + HandoffAck ack = 3; + } +} diff --git a/proto/media_capture.proto b/proto/media_capture.proto new file mode 100644 index 0000000..4c33c2b --- /dev/null +++ b/proto/media_capture.proto @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 +syntax = "proto3"; + +package continue.v1; + +enum CameraCaptureMode { + CAMERA_CAPTURE_MODE_UNSPECIFIED = 0; + CAMERA_CAPTURE_MODE_PHOTO = 1; + CAMERA_CAPTURE_MODE_DOCUMENT_SCAN = 2; +} + +enum CameraCaptureDestination { + CAMERA_CAPTURE_DESTINATION_UNSPECIFIED = 0; + CAMERA_CAPTURE_DESTINATION_SAVE_FILE = 1; + CAMERA_CAPTURE_DESTINATION_CLIPBOARD = 2; + CAMERA_CAPTURE_DESTINATION_BOTH = 3; +} + +message CameraCaptureRequest { + string capture_id = 1; + CameraCaptureMode mode = 2; + CameraCaptureDestination destination = 3; + bool flash_enabled = 4; + uint32 max_width = 5; + uint32 max_height = 6; +} + +enum CameraCaptureStatus { + CAMERA_CAPTURE_STATUS_UNSPECIFIED = 0; + CAMERA_CAPTURE_STATUS_SUCCESS = 1; + CAMERA_CAPTURE_STATUS_DECLINED = 2; + CAMERA_CAPTURE_STATUS_BUSY = 3; + CAMERA_CAPTURE_STATUS_UNSUPPORTED = 4; + CAMERA_CAPTURE_STATUS_ERROR = 5; +} + +message CameraCaptureResponse { + string capture_id = 1; + CameraCaptureStatus status = 2; + string reason = 3; + string mime_type = 4; + uint64 file_size = 5; + bytes sha256_checksum = 6; + uint32 width = 7; + uint32 height = 8; + string file_name = 9; +} + +message CameraCaptureAck { + string capture_id = 1; + uint64 bytes_received = 2; + bool verified = 3; +} diff --git a/proto/media_control.proto b/proto/media_control.proto new file mode 100644 index 0000000..10029e4 --- /dev/null +++ b/proto/media_control.proto @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 +syntax = "proto3"; + +package continue.v1; + +enum MediaPlaybackState { + MEDIA_PLAYBACK_STATE_UNSPECIFIED = 0; + MEDIA_PLAYBACK_STATE_PLAYING = 1; + MEDIA_PLAYBACK_STATE_PAUSED = 2; + MEDIA_PLAYBACK_STATE_STOPPED = 3; + MEDIA_PLAYBACK_STATE_BUFFERING = 4; +} + +enum MediaPlaybackCommand { + MEDIA_PLAYBACK_COMMAND_UNSPECIFIED = 0; + MEDIA_PLAYBACK_COMMAND_PLAY = 1; + MEDIA_PLAYBACK_COMMAND_PAUSE = 2; + MEDIA_PLAYBACK_COMMAND_PLAY_PAUSE = 3; + MEDIA_PLAYBACK_COMMAND_NEXT = 4; + MEDIA_PLAYBACK_COMMAND_PREVIOUS = 5; + MEDIA_PLAYBACK_COMMAND_STOP = 6; + MEDIA_PLAYBACK_COMMAND_SEEK = 7; + MEDIA_PLAYBACK_COMMAND_SET_VOLUME = 8; +} + +message MediaMetadata { + string title = 1; + string artist = 2; + string album = 3; + uint64 duration_ms = 4; + uint64 position_ms = 5; + MediaPlaybackState state = 6; + float volume = 7; + bytes artwork_thumbnail = 8; +} + +message MediaCommandRequest { + string command_id = 1; + MediaPlaybackCommand command = 2; + uint64 seek_position_ms = 3; + float volume = 4; +} + +message MediaCommandResponse { + string command_id = 1; + bool success = 2; + string error_message = 3; +} + +message MediaStatusUpdate { + MediaMetadata metadata = 1; + uint64 timestamp_ms = 2; +} + +message MediaControlEnvelope { + oneof payload { + MediaCommandRequest command_request = 1; + MediaStatusUpdate status_update = 2; + } +} diff --git a/proto/telemetry.proto b/proto/telemetry.proto new file mode 100644 index 0000000..6252aca --- /dev/null +++ b/proto/telemetry.proto @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 +syntax = "proto3"; + +package continue.v1; + +enum ChargingType { + CHARGING_TYPE_NONE = 0; + CHARGING_TYPE_AC = 1; + CHARGING_TYPE_USB = 2; + CHARGING_TYPE_WIRELESS = 3; +} + +message BatteryState { + uint32 level_percent = 1; + bool is_charging = 2; + ChargingType charging_type = 3; + bool is_low_power = 4; +} + +message RadioState { + bool wifi_connected = 1; + string wifi_ssid = 2; + int32 wifi_rssi_dbm = 3; + bool cellular_connected = 4; + uint32 cellular_signal_level = 5; + string cellular_operator = 6; +} + +message DeviceTelemetry { + string device_id = 1; + uint64 timestamp_ms = 2; + BatteryState battery = 3; + RadioState radio = 4; +} + +message TelemetryAck { + bool success = 1; +} + +message TelemetryEnvelope { + oneof payload { + DeviceTelemetry telemetry = 1; + TelemetryAck ack = 2; + } +} From 95d2fefafc20f80858bb44af355bc34f15929c1e Mon Sep 17 00:00:00 2001 From: Samarth Rajesh Lad <142334685+samyyy2311@users.noreply.github.com> Date: Thu, 8 Oct 2026 10:45:52 +0530 Subject: [PATCH 02/14] Format code with cargo fmt --- crates/clipboard/src/context.rs | 41 ++- crates/clipboard/src/guard.rs | 5 +- crates/clipboard/src/sync.rs | 3 +- crates/discovery/src/doctor.rs | 30 ++- crates/discovery/src/localsend.rs | 22 +- crates/notifications/src/media_push.rs | 14 +- crates/notifications/src/otp.rs | 9 +- crates/notifications/src/task.rs | 25 +- crates/pairing/src/words.rs | 293 ++++++++++++++++++--- crates/permissions/src/store.rs | 5 +- crates/sessions/src/capabilities_router.rs | 1 - crates/sessions/src/handoff.rs | 4 +- crates/sessions/src/media_control.rs | 4 +- crates/sessions/src/telemetry.rs | 8 +- crates/transfer/src/capture.rs | 23 +- crates/transfer/src/lib.rs | 1 - crates/transfer/src/localsend_bridge.rs | 22 +- crates/transfer/src/queue.rs | 15 +- crates/transfer/tests/capture_e2e.rs | 28 +- 19 files changed, 423 insertions(+), 130 deletions(-) diff --git a/crates/clipboard/src/context.rs b/crates/clipboard/src/context.rs index 88aaab1..8be74fc 100644 --- a/crates/clipboard/src/context.rs +++ b/crates/clipboard/src/context.rs @@ -6,7 +6,10 @@ pub enum ContextAction { OpenUrl(String), CopyOtp(String), CallPhone(String), - TrackPackage { carrier: &'static str, tracking_number: String }, + TrackPackage { + carrier: &'static str, + tracking_number: String, + }, } pub fn classify_context(text: &str) -> Option { @@ -45,7 +48,10 @@ fn detect_url(s: &str) -> Option { } fn detect_tracking(s: &str) -> Option { - let raw: String = s.chars().filter(|c| !c.is_whitespace() && *c != '-').collect(); + let raw: String = s + .chars() + .filter(|c| !c.is_whitespace() && *c != '-') + .collect(); if raw.len() == 18 && raw[..2].eq_ignore_ascii_case("1Z") @@ -80,7 +86,8 @@ fn detect_tracking(s: &str) -> Option { fn detect_otp(s: &str) -> Option { let digits: String = s.chars().filter(|c| c.is_ascii_digit()).collect(); - if s.chars().all(|c| c.is_ascii_digit() || c == '-' || c.is_whitespace()) + if s.chars() + .all(|c| c.is_ascii_digit() || c == '-' || c.is_whitespace()) && digits.len() >= 4 && digits.len() <= 8 { @@ -95,7 +102,10 @@ fn detect_otp(s: &str) -> Option { if has_keyword { for token in s.split(|c: char| c.is_whitespace() || c == ':' || c == '.' || c == ',') { let token_digits: String = token.chars().filter(|c| c.is_ascii_digit()).collect(); - if token_digits.len() >= 4 && token_digits.len() <= 8 && token_digits == token.trim_matches(|c: char| !c.is_ascii_digit()) { + if token_digits.len() >= 4 + && token_digits.len() <= 8 + && token_digits == token.trim_matches(|c: char| !c.is_ascii_digit()) + { return Some(token_digits); } } @@ -105,13 +115,23 @@ fn detect_otp(s: &str) -> Option { } fn detect_phone(s: &str) -> Option { - let valid_start = s.starts_with('+') || s.starts_with('(') || s.chars().next().is_some_and(|c| c.is_ascii_digit()); + let valid_start = s.starts_with('+') + || s.starts_with('(') + || s.chars().next().is_some_and(|c| c.is_ascii_digit()); if !valid_start { return None; } let digits = s.chars().filter(|c| c.is_ascii_digit()).count(); - let valid_chars = s.chars().all(|c| c.is_ascii_digit() || c == '+' || c == '-' || c == '(' || c == ')' || c == '.' || c.is_whitespace()); + let valid_chars = s.chars().all(|c| { + c.is_ascii_digit() + || c == '+' + || c == '-' + || c == '(' + || c == ')' + || c == '.' + || c.is_whitespace() + }); if valid_chars && (7..=15).contains(&digits) && s.len() <= 24 { return Some(s.to_string()); @@ -128,7 +148,9 @@ mod tests { fn classifies_urls() { assert_eq!( classify_context("https://github.com/thtbee/nectarlink"), - Some(ContextAction::OpenUrl("https://github.com/thtbee/nectarlink".to_string())) + Some(ContextAction::OpenUrl( + "https://github.com/thtbee/nectarlink".to_string() + )) ); } @@ -169,7 +191,10 @@ mod tests { #[test] fn ignores_regular_text() { - assert_eq!(classify_context("Regular sentence without actionable tokens."), None); + assert_eq!( + classify_context("Regular sentence without actionable tokens."), + None + ); assert_eq!(classify_context(""), None); } } diff --git a/crates/clipboard/src/guard.rs b/crates/clipboard/src/guard.rs index 07b06ae..752140c 100644 --- a/crates/clipboard/src/guard.rs +++ b/crates/clipboard/src/guard.rs @@ -19,7 +19,10 @@ where { for format in available_formats { let name = format.as_ref(); - if SENSITIVE_FORMATS.iter().any(|&s| name.eq_ignore_ascii_case(s)) { + if SENSITIVE_FORMATS + .iter() + .any(|&s| name.eq_ignore_ascii_case(s)) + { return SensitiveGuardDecision::DropSensitive; } } diff --git a/crates/clipboard/src/sync.rs b/crates/clipboard/src/sync.rs index c17ad24..ef2e94b 100644 --- a/crates/clipboard/src/sync.rs +++ b/crates/clipboard/src/sync.rs @@ -70,7 +70,8 @@ impl ClipboardSynchronizer { return Err(ClipboardError::SensitiveExcluded); } - self.send_update(stream, recv_stream, format, payload, query).await + self.send_update(stream, recv_stream, format, payload, query) + .await } pub async fn send_update( diff --git a/crates/discovery/src/doctor.rs b/crates/discovery/src/doctor.rs index f7b478c..fbd91a5 100644 --- a/crates/discovery/src/doctor.rs +++ b/crates/discovery/src/doctor.rs @@ -128,12 +128,30 @@ mod tests { #[test] fn classifies_interface_kinds() { - assert_eq!(classify_ip(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))), InterfaceKind::Loopback); - assert_eq!(classify_ip(IpAddr::V4(Ipv4Addr::new(169, 254, 1, 2))), InterfaceKind::LinkLocal); - assert_eq!(classify_ip(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 50))), InterfaceKind::PrivateLan); - assert_eq!(classify_ip(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 15))), InterfaceKind::PrivateLan); - assert_eq!(classify_ip(IpAddr::V4(Ipv4Addr::new(172, 28, 0, 1))), InterfaceKind::VirtualOrVpn); - assert_eq!(classify_ip(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8))), InterfaceKind::Public); + assert_eq!( + classify_ip(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))), + InterfaceKind::Loopback + ); + assert_eq!( + classify_ip(IpAddr::V4(Ipv4Addr::new(169, 254, 1, 2))), + InterfaceKind::LinkLocal + ); + assert_eq!( + classify_ip(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 50))), + InterfaceKind::PrivateLan + ); + assert_eq!( + classify_ip(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 15))), + InterfaceKind::PrivateLan + ); + assert_eq!( + classify_ip(IpAddr::V4(Ipv4Addr::new(172, 28, 0, 1))), + InterfaceKind::VirtualOrVpn + ); + assert_eq!( + classify_ip(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8))), + InterfaceKind::Public + ); } #[test] diff --git a/crates/discovery/src/localsend.rs b/crates/discovery/src/localsend.rs index fa5eed1..55c0e71 100644 --- a/crates/discovery/src/localsend.rs +++ b/crates/discovery/src/localsend.rs @@ -33,12 +33,25 @@ pub struct LocalSendAnnouncement { } impl LocalSendAnnouncement { - pub fn new(alias: impl Into, fingerprint: impl Into, port: u16, is_desktop: bool) -> Self { + pub fn new( + alias: impl Into, + fingerprint: impl Into, + port: u16, + is_desktop: bool, + ) -> Self { Self { alias: alias.into(), version: LOCALSEND_PROTOCOL_VERSION.to_string(), - device_model: Some(if is_desktop { "Desktop PC".into() } else { "Mobile Device".into() }), - device_type: Some(if is_desktop { "desktop".into() } else { "mobile".into() }), + device_model: Some(if is_desktop { + "Desktop PC".into() + } else { + "Mobile Device".into() + }), + device_type: Some(if is_desktop { + "desktop".into() + } else { + "mobile".into() + }), fingerprint: fingerprint.into(), port, protocol: "https".to_string(), @@ -63,7 +76,8 @@ mod tests { #[test] fn announcement_roundtrip_matches_localsend_v2_spec() { - let announcement = LocalSendAnnouncement::new("Continue-Desktop", "continue-fp-01", 53317, true); + let announcement = + LocalSendAnnouncement::new("Continue-Desktop", "continue-fp-01", 53317, true); let bytes = announcement.to_bytes().expect("serialize"); let json_str = std::str::from_utf8(&bytes).unwrap(); diff --git a/crates/notifications/src/media_push.rs b/crates/notifications/src/media_push.rs index c9fa44a..e1858a1 100644 --- a/crates/notifications/src/media_push.rs +++ b/crates/notifications/src/media_push.rs @@ -71,7 +71,9 @@ impl MediaPushItem { pub fn parse_media_push_action(action_id: &str) -> Option<(MediaPushAction, &str)> { if let Some(media_id) = action_id.strip_prefix(&format!("{}:", ACTION_COPY_MEDIA_CLIPBOARD)) { Some((MediaPushAction::CopyToClipboard, media_id)) - } else if let Some(media_id) = action_id.strip_prefix(&format!("{}:", ACTION_SAVE_MEDIA_DOWNLOADS)) { + } else if let Some(media_id) = + action_id.strip_prefix(&format!("{}:", ACTION_SAVE_MEDIA_DOWNLOADS)) + { Some((MediaPushAction::SaveToDownloads, media_id)) } else { None @@ -119,10 +121,16 @@ mod tests { #[test] fn parses_media_push_action_payload() { let parsed_copy = parse_media_push_action("copy_media_clipboard:sc-123"); - assert_eq!(parsed_copy, Some((MediaPushAction::CopyToClipboard, "sc-123"))); + assert_eq!( + parsed_copy, + Some((MediaPushAction::CopyToClipboard, "sc-123")) + ); let parsed_save = parse_media_push_action("save_media_downloads:img-99"); - assert_eq!(parsed_save, Some((MediaPushAction::SaveToDownloads, "img-99"))); + assert_eq!( + parsed_save, + Some((MediaPushAction::SaveToDownloads, "img-99")) + ); let parsed_unknown = parse_media_push_action("unrelated_action:sc-123"); assert_eq!(parsed_unknown, None); diff --git a/crates/notifications/src/otp.rs b/crates/notifications/src/otp.rs index 72fdc8d..1c80036 100644 --- a/crates/notifications/src/otp.rs +++ b/crates/notifications/src/otp.rs @@ -23,7 +23,9 @@ pub fn extract_otp(title: &str, body: &str) -> Option { return None; } - for token in body.split(|c: char| c.is_whitespace() || c == ':' || c == '.' || c == ',' || c == '#' || c == '-') { + for token in body.split(|c: char| { + c.is_whitespace() || c == ':' || c == '.' || c == ',' || c == '#' || c == '-' + }) { let trimmed = token.trim_matches(|c: char| !c.is_ascii_digit()); if trimmed.len() >= 4 && trimmed.len() <= 8 && trimmed.chars().all(|c| c.is_ascii_digit()) { return Some(trimmed.to_string()); @@ -58,7 +60,10 @@ mod tests { let code = extract_otp("Google", "G-839201 is your verification code."); assert_eq!(code, Some("839201".to_string())); - let code2 = extract_otp("Bank Alert", "Your one-time OTP is 582194 for account login."); + let code2 = extract_otp( + "Bank Alert", + "Your one-time OTP is 582194 for account login.", + ); assert_eq!(code2, Some("582194".to_string())); } diff --git a/crates/notifications/src/task.rs b/crates/notifications/src/task.rs index b5c0235..b556e7d 100644 --- a/crates/notifications/src/task.rs +++ b/crates/notifications/src/task.rs @@ -1,8 +1,8 @@ // SPDX-FileCopyrightText: Contributors to the Continue project // SPDX-License-Identifier: Apache-2.0 -use std::time::{Duration, SystemTime, UNIX_EPOCH}; use protocol::v1::NotificationPost; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct TaskCompletionReport { @@ -13,7 +13,12 @@ pub struct TaskCompletionReport { } impl TaskCompletionReport { - pub fn new(task_name: impl Into, duration: Duration, success: bool, exit_code: Option) -> Self { + pub fn new( + task_name: impl Into, + duration: Duration, + success: bool, + exit_code: Option, + ) -> Self { Self { task_name: task_name.into(), duration, @@ -59,12 +64,8 @@ mod tests { #[test] fn formats_successful_task_notification() { - let report = TaskCompletionReport::new( - "cargo build", - Duration::from_millis(4200), - true, - Some(0), - ); + let report = + TaskCompletionReport::new("cargo build", Duration::from_millis(4200), true, Some(0)); let post = report.to_notification_post(); assert_eq!(post.title, "Task: cargo build"); @@ -74,12 +75,8 @@ mod tests { #[test] fn formats_failed_task_notification() { - let report = TaskCompletionReport::new( - "test suite", - Duration::from_millis(1500), - false, - Some(1), - ); + let report = + TaskCompletionReport::new("test suite", Duration::from_millis(1500), false, Some(1)); let post = report.to_notification_post(); assert_eq!(post.title, "Task: test suite"); diff --git a/crates/pairing/src/words.rs b/crates/pairing/src/words.rs index 462f565..19f20ba 100644 --- a/crates/pairing/src/words.rs +++ b/crates/pairing/src/words.rs @@ -8,38 +8,262 @@ const SAS_INFO_LABEL: &[u8] = b"CONTINUE_SAS_WORDS_V1"; /// 256 phonetically distinct words for visual Short Authentication String (SAS) verification. pub const WORDLIST: [&str; 256] = [ - "acorn", "action", "anchor", "anthem", "apron", "archer", "arrow", "artist", - "atlas", "atom", "author", "badge", "baker", "bamboo", "banner", "bark", - "beacon", "beetle", "bell", "berry", "bison", "blade", "blanket", "blaze", - "blossom", "bonfire", "book", "bottle", "boulder", "breeze", "brick", "bridge", - "brook", "bucket", "cabin", "cactus", "canyon", "canvas", "cargo", "castle", - "cedar", "celery", "chalk", "charm", "cherry", "chest", "chimney", "cider", - "circle", "cliff", "cloak", "clover", "cobalt", "comet", "compass", "copper", - "coral", "corner", "cotton", "crater", "creek", "cricket", "crystal", "curtain", - "daisy", "dancer", "delta", "desert", "diamond", "dolphin", "dragon", "drift", - "drum", "eagle", "earth", "echo", "ember", "engine", "falcon", "feather", - "fern", "ferry", "field", "filter", "finch", "finger", "fire", "flame", - "flint", "flower", "forest", "fountain", "fox", "frost", "garden", "garlic", - "gateway", "gecko", "geyser", "ginger", "glacier", "globe", "glow", "goblet", - "granite", "grape", "grass", "gravel", "grove", "guitar", "harbor", "harvest", - "haven", "hawk", "hazel", "helmet", "hero", "heron", "honey", "horizon", - "humming", "hunter", "husky", "igloo", "island", "jacket", "jaguar", "jasper", - "jelly", "jigsaw", "jungle", "jupiter", "kettle", "key", "kite", "kiwi", - "knight", "ladder", "lagoon", "lantern", "lark", "laurel", "lava", "leaf", - "lemon", "leopard", "lighthouse", "lily", "lion", "lizard", "llama", "lobster", - "lotus", "lumber", "lunar", "magnet", "magpie", "mallet", "mango", "mantle", - "maple", "marble", "marsh", "meadow", "melon", "meteor", "mirror", "monarch", - "moon", "moss", "mountain", "muffin", "nebula", "nectar", "needle", "nest", - "nickel", "night", "ninja", "north", "novel", "oasis", "ocean", "olive", - "onyx", "opal", "orange", "orbit", "orchid", "otter", "owl", "paddle", - "palace", "panther", "papaya", "parrot", "path", "peach", "peacock", "pebble", - "pelican", "pepper", "petal", "phoenix", "pillow", "pilot", "pine", "planet", - "plasma", "plaza", "polar", "poplar", "prism", "puzzle", "quartz", "quiver", - "rabbit", "radar", "rainbow", "raven", "reef", "relay", "ridge", "river", - "robin", "rocket", "ruby", "saddle", "safari", "sail", "salmon", "sand", - "sapphire", "saturn", "scale", "scarlet", "scout", "shadow", "shield", "sierra", - "silver", "skater", "sky", "solar", "sparrow", "sphere", "spider", "spire", - "spring", "spruce", "star", "summit", "sun", "surf", "swan", "timber", + "acorn", + "action", + "anchor", + "anthem", + "apron", + "archer", + "arrow", + "artist", + "atlas", + "atom", + "author", + "badge", + "baker", + "bamboo", + "banner", + "bark", + "beacon", + "beetle", + "bell", + "berry", + "bison", + "blade", + "blanket", + "blaze", + "blossom", + "bonfire", + "book", + "bottle", + "boulder", + "breeze", + "brick", + "bridge", + "brook", + "bucket", + "cabin", + "cactus", + "canyon", + "canvas", + "cargo", + "castle", + "cedar", + "celery", + "chalk", + "charm", + "cherry", + "chest", + "chimney", + "cider", + "circle", + "cliff", + "cloak", + "clover", + "cobalt", + "comet", + "compass", + "copper", + "coral", + "corner", + "cotton", + "crater", + "creek", + "cricket", + "crystal", + "curtain", + "daisy", + "dancer", + "delta", + "desert", + "diamond", + "dolphin", + "dragon", + "drift", + "drum", + "eagle", + "earth", + "echo", + "ember", + "engine", + "falcon", + "feather", + "fern", + "ferry", + "field", + "filter", + "finch", + "finger", + "fire", + "flame", + "flint", + "flower", + "forest", + "fountain", + "fox", + "frost", + "garden", + "garlic", + "gateway", + "gecko", + "geyser", + "ginger", + "glacier", + "globe", + "glow", + "goblet", + "granite", + "grape", + "grass", + "gravel", + "grove", + "guitar", + "harbor", + "harvest", + "haven", + "hawk", + "hazel", + "helmet", + "hero", + "heron", + "honey", + "horizon", + "humming", + "hunter", + "husky", + "igloo", + "island", + "jacket", + "jaguar", + "jasper", + "jelly", + "jigsaw", + "jungle", + "jupiter", + "kettle", + "key", + "kite", + "kiwi", + "knight", + "ladder", + "lagoon", + "lantern", + "lark", + "laurel", + "lava", + "leaf", + "lemon", + "leopard", + "lighthouse", + "lily", + "lion", + "lizard", + "llama", + "lobster", + "lotus", + "lumber", + "lunar", + "magnet", + "magpie", + "mallet", + "mango", + "mantle", + "maple", + "marble", + "marsh", + "meadow", + "melon", + "meteor", + "mirror", + "monarch", + "moon", + "moss", + "mountain", + "muffin", + "nebula", + "nectar", + "needle", + "nest", + "nickel", + "night", + "ninja", + "north", + "novel", + "oasis", + "ocean", + "olive", + "onyx", + "opal", + "orange", + "orbit", + "orchid", + "otter", + "owl", + "paddle", + "palace", + "panther", + "papaya", + "parrot", + "path", + "peach", + "peacock", + "pebble", + "pelican", + "pepper", + "petal", + "phoenix", + "pillow", + "pilot", + "pine", + "planet", + "plasma", + "plaza", + "polar", + "poplar", + "prism", + "puzzle", + "quartz", + "quiver", + "rabbit", + "radar", + "rainbow", + "raven", + "reef", + "relay", + "ridge", + "river", + "robin", + "rocket", + "ruby", + "saddle", + "safari", + "sail", + "salmon", + "sand", + "sapphire", + "saturn", + "scale", + "scarlet", + "scout", + "shadow", + "shield", + "sierra", + "silver", + "skater", + "sky", + "solar", + "sparrow", + "sphere", + "spider", + "spire", + "spring", + "spruce", + "star", + "summit", + "sun", + "surf", + "swan", + "timber", ]; /// Derives 4 visual verification words from the pairing shared secret and transcript. @@ -93,7 +317,10 @@ mod tests { let words2 = derive_verification_words(&secret, transcript); assert_eq!(words1, words2); - assert_eq!(format_verification_phrase(&words1), format_verification_phrase(&words2)); + assert_eq!( + format_verification_phrase(&words1), + format_verification_phrase(&words2) + ); } #[test] diff --git a/crates/permissions/src/store.rs b/crates/permissions/src/store.rs index b46dd34..1540471 100644 --- a/crates/permissions/src/store.rs +++ b/crates/permissions/src/store.rs @@ -249,10 +249,7 @@ mod tests { store.set_lockdown(true); assert!(store.is_locked_down()); - assert_eq!( - store.query_state(peer, cap).unwrap(), - PermissionState::Deny - ); + assert_eq!(store.query_state(peer, cap).unwrap(), PermissionState::Deny); assert_eq!( store.query_state(peer, CapabilityId::CLIPBOARD).unwrap(), PermissionState::Deny diff --git a/crates/sessions/src/capabilities_router.rs b/crates/sessions/src/capabilities_router.rs index b7c8324..78ccb73 100644 --- a/crates/sessions/src/capabilities_router.rs +++ b/crates/sessions/src/capabilities_router.rs @@ -560,4 +560,3 @@ impl SessionMultiplexer { .await } } - diff --git a/crates/sessions/src/handoff.rs b/crates/sessions/src/handoff.rs index 137c9e4..fddb454 100644 --- a/crates/sessions/src/handoff.rs +++ b/crates/sessions/src/handoff.rs @@ -148,9 +148,9 @@ impl HandoffDispatcher { #[cfg(test)] mod tests { use super::*; - use std::collections::HashSet; - use protocol::CapabilityId; use protocol::v1::HandoffType; + use protocol::CapabilityId; + use std::collections::HashSet; use transport::{create_client_endpoint, create_server_endpoint, TransportCertificate}; fn test_query(authorized: bool) -> CapabilityQuery { diff --git a/crates/sessions/src/media_control.rs b/crates/sessions/src/media_control.rs index 89f2c6a..58248bd 100644 --- a/crates/sessions/src/media_control.rs +++ b/crates/sessions/src/media_control.rs @@ -106,10 +106,10 @@ impl MediaControlDispatcher { #[cfg(test)] mod tests { use super::*; - use protocol::CapabilityId; use protocol::v1::{MediaMetadata, MediaPlaybackCommand, MediaPlaybackState}; - use transport::{create_client_endpoint, create_server_endpoint, TransportCertificate}; + use protocol::CapabilityId; use std::collections::HashSet; + use transport::{create_client_endpoint, create_server_endpoint, TransportCertificate}; fn test_query(authorized: bool) -> CapabilityQuery { let mut caps = HashSet::new(); diff --git a/crates/sessions/src/telemetry.rs b/crates/sessions/src/telemetry.rs index 3f099de..f1a723b 100644 --- a/crates/sessions/src/telemetry.rs +++ b/crates/sessions/src/telemetry.rs @@ -3,9 +3,7 @@ use capabilities::{evaluate_capability, CapabilityQuery}; use limits::MAX_FRAME_TELEMETRY_BYTES; -use protocol::v1::{ - telemetry_envelope::Payload, DeviceTelemetry, TelemetryAck, TelemetryEnvelope, -}; +use protocol::v1::{telemetry_envelope::Payload, DeviceTelemetry, TelemetryAck, TelemetryEnvelope}; use transport::{read_msg, write_msg}; use crate::error::SessionError; @@ -105,9 +103,9 @@ impl TelemetryAlertEvaluator { #[cfg(test)] mod tests { use super::*; - use std::collections::HashSet; - use protocol::CapabilityId; use protocol::v1::{BatteryState, ChargingType, RadioState}; + use protocol::CapabilityId; + use std::collections::HashSet; use transport::{create_client_endpoint, create_server_endpoint, TransportCertificate}; fn test_query(authorized: bool) -> CapabilityQuery { diff --git a/crates/transfer/src/capture.rs b/crates/transfer/src/capture.rs index ca291bf..d95c683 100644 --- a/crates/transfer/src/capture.rs +++ b/crates/transfer/src/capture.rs @@ -143,10 +143,15 @@ pub async fn request_camera_capture( }; let raw_name = if resp.file_name.is_empty() { - format!("{}_{}.{}", match CameraCaptureMode::try_from(request.mode) { - Ok(CameraCaptureMode::DocumentScan) => "scan", - _ => "photo", - }, resp.capture_id, default_ext) + format!( + "{}_{}.{}", + match CameraCaptureMode::try_from(request.mode) { + Ok(CameraCaptureMode::DocumentScan) => "scan", + _ => "photo", + }, + resp.capture_id, + default_ext + ) } else { resp.file_name }; @@ -239,17 +244,17 @@ where P: FnOnce(CameraCaptureRequest) -> Fut, Fut: Future>, { - let req: CameraCaptureRequest = - read_msg(recv_stream, MAX_FRAME_MEDIA_CAPTURE_BYTES).await?; + let req: CameraCaptureRequest = read_msg(recv_stream, MAX_FRAME_MEDIA_CAPTURE_BYTES).await?; let source = match provider(req.clone()).await { Ok(source) => source, Err(e) => { let (status, reason) = match &e { TransferError::CaptureBusy => (CameraCaptureStatus::Busy, "Camera is busy".into()), - TransferError::CaptureUnsupported => { - (CameraCaptureStatus::Unsupported, "Camera unavailable".into()) - } + TransferError::CaptureUnsupported => ( + CameraCaptureStatus::Unsupported, + "Camera unavailable".into(), + ), TransferError::CaptureRejected(r) => (CameraCaptureStatus::Declined, r.clone()), other => (CameraCaptureStatus::Error, other.to_string()), }; diff --git a/crates/transfer/src/lib.rs b/crates/transfer/src/lib.rs index 048cb81..decebff 100644 --- a/crates/transfer/src/lib.rs +++ b/crates/transfer/src/lib.rs @@ -25,4 +25,3 @@ pub use queue::{OfflineTransferQueue, QueuedPayload, QueuedTransfer}; pub use receiver::{receive_file, ReceivedFile}; pub use sanitizer::sanitize_filename; pub use sender::{compute_file_sha256, send_file}; - diff --git a/crates/transfer/src/localsend_bridge.rs b/crates/transfer/src/localsend_bridge.rs index ef259d0..409ab0e 100644 --- a/crates/transfer/src/localsend_bridge.rs +++ b/crates/transfer/src/localsend_bridge.rs @@ -1,8 +1,8 @@ // SPDX-FileCopyrightText: Contributors to the Continue project // SPDX-License-Identifier: Apache-2.0 -use std::collections::HashMap; use serde::{Deserialize, Serialize}; +use std::collections::HashMap; use crate::error::TransferError; use crate::sanitizer::sanitize_filename; @@ -133,11 +133,7 @@ impl LocalSendBridgeSessionManager { Ok(file) } - pub fn mark_completed( - &mut self, - session_id: &str, - file_id: &str, - ) -> Result<(), TransferError> { + pub fn mark_completed(&mut self, session_id: &str, file_id: &str) -> Result<(), TransferError> { let session = self .sessions .get_mut(session_id) @@ -188,13 +184,17 @@ mod tests { assert!(resp.files.contains_key("f1")); let token = resp.files.get("f1").unwrap(); - let verified = manager.verify_upload(&resp.session_id, "f1", token).unwrap(); + let verified = manager + .verify_upload(&resp.session_id, "f1", token) + .unwrap(); // Filename traversal components stripped to safe basename assert_eq!(verified.sanitized_name, "payload.sh"); assert_eq!(verified.size, 1024); // Verification fails with invalid token - assert!(manager.verify_upload(&resp.session_id, "f1", "bad-tok").is_err()); + assert!(manager + .verify_upload(&resp.session_id, "f1", "bad-tok") + .is_err()); } #[test] @@ -228,7 +228,11 @@ mod tests { manager.mark_completed(&resp.session_id, "img-01").unwrap(); let verified = manager - .verify_upload(&resp.session_id, "img-01", resp.files.get("img-01").unwrap()) + .verify_upload( + &resp.session_id, + "img-01", + resp.files.get("img-01").unwrap(), + ) .unwrap(); assert!(verified.completed); } diff --git a/crates/transfer/src/queue.rs b/crates/transfer/src/queue.rs index a548245..02c24a7 100644 --- a/crates/transfer/src/queue.rs +++ b/crates/transfer/src/queue.rs @@ -37,15 +37,9 @@ pub enum QueuedPayload { mime_type: Option, }, /// Clipboard content to sync. - Clipboard { - content: Vec, - mime_type: String, - }, + Clipboard { content: Vec, mime_type: String }, /// Handoff item (e.g. active tab URL). - Handoff { - uri: String, - title: Option, - }, + Handoff { uri: String, title: Option }, } /// Individual item held in the offline queue. @@ -192,10 +186,7 @@ impl OfflineTransferQueue { /// Number of items pending for a specific peer. pub fn pending_count_for_peer(&self, peer_fingerprint: &str) -> usize { let inner = self.inner.lock().unwrap(); - inner - .queues - .get(peer_fingerprint) - .map_or(0, |q| q.len()) + inner.queues.get(peer_fingerprint).map_or(0, |q| q.len()) } /// Total items pending across all peers. diff --git a/crates/transfer/tests/capture_e2e.rs b/crates/transfer/tests/capture_e2e.rs index 5bac068..5087d9c 100644 --- a/crates/transfer/tests/capture_e2e.rs +++ b/crates/transfer/tests/capture_e2e.rs @@ -4,17 +4,16 @@ use std::net::SocketAddr; use transport::{create_client_endpoint, create_server_endpoint, TransportCertificate}; -use protocol::v1::{ - CameraCaptureDestination, CameraCaptureMode, CameraCaptureRequest, -}; +use protocol::v1::{CameraCaptureDestination, CameraCaptureMode, CameraCaptureRequest}; use transfer::{ - format_as_clipboard_dibv5, request_camera_capture, respond_camera_capture, - CameraCaptureSource, TransferError, + format_as_clipboard_dibv5, request_camera_capture, respond_camera_capture, CameraCaptureSource, + TransferError, }; #[tokio::test] async fn camera_capture_e2e_photo_success() { - let temp_dir = std::env::temp_dir().join(format!("continue_capture_test_{}", rand::random::())); + let temp_dir = + std::env::temp_dir().join(format!("continue_capture_test_{}", rand::random::())); let phone_dir = temp_dir.join("phone"); let pc_dir = temp_dir.join("pc"); tokio::fs::create_dir_all(&phone_dir).await.unwrap(); @@ -22,7 +21,9 @@ async fn camera_capture_e2e_photo_success() { let captured_image = phone_dir.join("IMG_20261008_013000.jpg"); let image_data = vec![0xEEu8; 96 * 1024]; - tokio::fs::write(&captured_image, &image_data).await.unwrap(); + tokio::fs::write(&captured_image, &image_data) + .await + .unwrap(); let server_cert = TransportCertificate::generate().unwrap(); let client_cert = TransportCertificate::generate().unwrap(); @@ -104,7 +105,8 @@ async fn camera_capture_e2e_photo_success() { #[tokio::test] async fn camera_capture_handles_remote_busy() { - let temp_dir = std::env::temp_dir().join(format!("continue_capture_test_{}", rand::random::())); + let temp_dir = + std::env::temp_dir().join(format!("continue_capture_test_{}", rand::random::())); tokio::fs::create_dir_all(&temp_dir).await.unwrap(); let server_cert = TransportCertificate::generate().unwrap(); @@ -117,10 +119,12 @@ async fn camera_capture_handles_remote_busy() { .build_pinned_client_tls(server_cert.spki_hash) .unwrap(); - let server_endpoint = create_server_endpoint("127.0.0.1:0".parse().unwrap(), server_tls).unwrap(); + let server_endpoint = + create_server_endpoint("127.0.0.1:0".parse().unwrap(), server_tls).unwrap(); let bound_addr = server_endpoint.local_addr().unwrap(); - let client_endpoint = create_client_endpoint("127.0.0.1:0".parse().unwrap(), client_tls).unwrap(); + let client_endpoint = + create_client_endpoint("127.0.0.1:0".parse().unwrap(), client_tls).unwrap(); let phone_handle = tokio::spawn(async move { let incoming = server_endpoint.accept().await.expect("accept"); @@ -130,9 +134,7 @@ async fn camera_capture_handles_remote_busy() { let result = respond_camera_capture( &mut send_stream, &mut recv_stream, - |_req: CameraCaptureRequest| async move { - Err(TransferError::CaptureBusy) - }, + |_req: CameraCaptureRequest| async move { Err(TransferError::CaptureBusy) }, ) .await; From dc85a0a639a4b75fc599f03c881e6080a5e79593 Mon Sep 17 00:00:00 2001 From: Samarth Rajesh Lad <142334685+samyyy2311@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:07:43 +0530 Subject: [PATCH 03/14] feat: add Find My Phone ring, PC control actions, and Wake-on-LAN - Define CapabilityId::RING_DEVICE (8) and CapabilityId::PC_CONTROL (9) - Add protobuf schemas for ring and pc_control envelopes - Implement RingDispatcher and PcControlDispatcher with QUIC roundtrip tests - Implement Wake-on-LAN magic packet creation and UDP broadcasting in discovery::wol - Integrate ring and PC control dispatchers into SessionCapabilityHandlers and SessionMultiplexer --- crates/discovery/src/lib.rs | 2 + crates/discovery/src/wol.rs | 146 ++++++++++++++++++ crates/limits/src/lib.rs | 6 + crates/protocol/build.rs | 2 + crates/protocol/src/capability.rs | 4 + crates/sessions/src/capabilities_router.rs | 127 ++++++++++++++++ crates/sessions/src/lib.rs | 9 +- crates/sessions/src/pc_control.rs | 165 +++++++++++++++++++++ crates/sessions/src/ring.rs | 157 ++++++++++++++++++++ proto/pc_control.proto | 30 ++++ proto/ring.proto | 24 +++ 11 files changed, 670 insertions(+), 2 deletions(-) create mode 100644 crates/discovery/src/wol.rs create mode 100644 crates/sessions/src/pc_control.rs create mode 100644 crates/sessions/src/ring.rs create mode 100644 proto/pc_control.proto create mode 100644 proto/ring.proto diff --git a/crates/discovery/src/lib.rs b/crates/discovery/src/lib.rs index 1f640be..10957dc 100644 --- a/crates/discovery/src/lib.rs +++ b/crates/discovery/src/lib.rs @@ -8,6 +8,7 @@ pub mod doctor; pub mod ephemeral; pub mod error; pub mod localsend; +pub mod wol; pub use adb_browser::{ AdbDiscoveryBrowser, AdbServiceType, DiscoveredAdbService, ADB_TLS_CONNECT_SERVICE, @@ -24,3 +25,4 @@ pub use localsend::{ LocalSendAnnouncement, LOCALSEND_DEFAULT_PORT, LOCALSEND_MULTICAST_IPV4, LOCALSEND_PROTOCOL_VERSION, }; +pub use wol::{create_magic_packet, parse_mac_address, send_wake_on_lan, WolError}; diff --git a/crates/discovery/src/wol.rs b/crates/discovery/src/wol.rs new file mode 100644 index 0000000..e3d882f --- /dev/null +++ b/crates/discovery/src/wol.rs @@ -0,0 +1,146 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use std::net::{SocketAddr, UdpSocket}; +use thiserror::Error; + +pub const WOL_PACKET_LEN: usize = 102; +pub const DEFAULT_WOL_PORT: u16 = 9; + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum WolError { + #[error("Invalid MAC address length: expected 6 bytes, found {0}")] + InvalidLength(usize), + + #[error("Invalid MAC address string: {0}")] + InvalidFormat(String), + + #[error("Network I/O error: {0}")] + Io(String), +} + +/// Parses a MAC address from a string using either colon or hyphen delimiters (e.g. "AA:BB:CC:DD:EE:FF" or "aa-bb-cc-dd-ee-ff"). +pub fn parse_mac_address(mac_str: &str) -> Result<[u8; 6], WolError> { + let clean = mac_str.trim(); + let parts: Vec<&str> = if clean.contains(':') { + clean.split(':').collect() + } else if clean.contains('-') { + clean.split('-').collect() + } else { + return Err(WolError::InvalidFormat(mac_str.to_string())); + }; + + if parts.len() != 6 { + return Err(WolError::InvalidLength(parts.len())); + } + + let mut mac = [0u8; 6]; + for (i, part) in parts.iter().enumerate() { + if part.len() != 2 { + return Err(WolError::InvalidFormat(mac_str.to_string())); + } + mac[i] = u8::from_str_radix(part, 16) + .map_err(|_| WolError::InvalidFormat(mac_str.to_string()))?; + } + + Ok(mac) +} + +/// Constructs a 102-byte Wake-on-LAN magic packet consisting of 6 synchronization bytes (0xFF) +/// followed by 16 repetitions of the target device's MAC address. +pub fn create_magic_packet(mac: &[u8; 6]) -> [u8; WOL_PACKET_LEN] { + let mut packet = [0u8; WOL_PACKET_LEN]; + packet[..6].fill(0xFF); + + for i in 0..16 { + let start = 6 + i * 6; + packet[start..start + 6].copy_from_slice(mac); + } + + packet +} + +/// Broadcasts a Wake-on-LAN magic packet across the local network to wake a sleeping host. +pub fn send_wake_on_lan(mac: &[u8; 6], broadcast_addr: Option) -> Result<(), WolError> { + let target_addr: SocketAddr = broadcast_addr.unwrap_or_else(|| { + "255.255.255.255:9" + .parse() + .expect("Valid default broadcast address") + }); + + let socket = UdpSocket::bind("0.0.0.0:0") + .map_err(|e| WolError::Io(format!("Failed to bind UDP socket: {e}")))?; + + socket + .set_broadcast(true) + .map_err(|e| WolError::Io(format!("Failed to enable broadcast on UDP socket: {e}")))?; + + let packet = create_magic_packet(mac); + + socket + .send_to(&packet, target_addr) + .map_err(|e| WolError::Io(format!("Failed to broadcast magic packet: {e}")))?; + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_mac_address_colon_and_hyphen() { + let colon = "AA:BB:CC:11:22:33"; + let parsed_colon = parse_mac_address(colon).unwrap(); + assert_eq!(parsed_colon, [0xAA, 0xBB, 0xCC, 0x11, 0x22, 0x33]); + + let hyphen = "aa-bb-cc-11-22-33"; + let parsed_hyphen = parse_mac_address(hyphen).unwrap(); + assert_eq!(parsed_hyphen, [0xAA, 0xBB, 0xCC, 0x11, 0x22, 0x33]); + } + + #[test] + fn parse_mac_address_rejects_invalid() { + assert!(matches!( + parse_mac_address("AA:BB:CC:DD"), + Err(WolError::InvalidLength(4)) + )); + assert!(matches!( + parse_mac_address("not_a_mac_address"), + Err(WolError::InvalidFormat(_)) + )); + assert!(matches!( + parse_mac_address("AA:BB:CC:DD:EE:GG"), + Err(WolError::InvalidFormat(_)) + )); + } + + #[test] + fn magic_packet_structure() { + let mac = [0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC]; + let packet = create_magic_packet(&mac); + + assert_eq!(packet.len(), 102); + assert_eq!(&packet[..6], &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]); + + for i in 0..16 { + let offset = 6 + i * 6; + assert_eq!(&packet[offset..offset + 6], &mac); + } + } + + #[test] + fn send_wake_on_lan_loopback() { + let receiver = UdpSocket::bind("127.0.0.1:0").unwrap(); + let receiver_addr = receiver.local_addr().unwrap(); + + let mac = [0xDE, 0xAD, 0xBE, 0xEF, 0x01, 0x02]; + send_wake_on_lan(&mac, Some(receiver_addr)).unwrap(); + + let mut buf = [0u8; 256]; + let (len, _) = receiver.recv_from(&mut buf).unwrap(); + + assert_eq!(len, 102); + assert_eq!(&buf[..102], &create_magic_packet(&mac)); + } +} diff --git a/crates/limits/src/lib.rs b/crates/limits/src/lib.rs index 76c3339..053d054 100644 --- a/crates/limits/src/lib.rs +++ b/crates/limits/src/lib.rs @@ -78,6 +78,12 @@ pub const MAX_HANDOFF_TITLE_BYTES: usize = 512; /// Telemetry messages (battery, radio state). pub const MAX_FRAME_TELEMETRY_BYTES: usize = 16 * 1024; +/// Ring device / Find My Phone control messages. +pub const MAX_FRAME_RING_BYTES: usize = 16 * 1024; + +/// PC remote control actions and response messages. +pub const MAX_FRAME_PC_CONTROL_BYTES: usize = 16 * 1024; + // File transfer /// Maximum UTF-8 byte length of a transfer filename. diff --git a/crates/protocol/build.rs b/crates/protocol/build.rs index 733efd8..9815c36 100644 --- a/crates/protocol/build.rs +++ b/crates/protocol/build.rs @@ -21,6 +21,8 @@ fn main() { proto_dir.join("media_control.proto"), proto_dir.join("handoff.proto"), proto_dir.join("telemetry.proto"), + proto_dir.join("ring.proto"), + proto_dir.join("pc_control.proto"), ]; for file in &proto_files { diff --git a/crates/protocol/src/capability.rs b/crates/protocol/src/capability.rs index 4438783..6c971ec 100644 --- a/crates/protocol/src/capability.rs +++ b/crates/protocol/src/capability.rs @@ -19,6 +19,8 @@ impl CapabilityId { pub const MEDIA_CONTROL: Self = Self(5); pub const HANDOFF: Self = Self(6); pub const TELEMETRY: Self = Self(7); + pub const RING_DEVICE: Self = Self(8); + pub const PC_CONTROL: Self = Self(9); pub const fn new(id: u32) -> Self { Self(id) @@ -38,6 +40,8 @@ impl CapabilityId { Self::MEDIA_CONTROL => Some("media_control"), Self::HANDOFF => Some("handoff"), Self::TELEMETRY => Some("telemetry"), + Self::RING_DEVICE => Some("ring_device"), + Self::PC_CONTROL => Some("pc_control"), _ => None, } } diff --git a/crates/sessions/src/capabilities_router.rs b/crates/sessions/src/capabilities_router.rs index 78ccb73..7752426 100644 --- a/crates/sessions/src/capabilities_router.rs +++ b/crates/sessions/src/capabilities_router.rs @@ -18,6 +18,8 @@ use crate::handoff::HandoffDispatcher; use crate::incoming::{IncomingFiles, SaveFolder}; use crate::media_control::MediaControlDispatcher; use crate::multiplexer::{OnPeerUpdate, PeerUpdate, SessionMultiplexer}; +use crate::pc_control::PcControlDispatcher; +use crate::ring::RingDispatcher; use crate::telemetry::TelemetryDispatcher; /// How long a question waits for the user before it counts as declined. @@ -55,6 +57,11 @@ pub type MediaCommandHandler = Arc< + Send + Sync, >; +pub type RingHandler = + Arc protocol::v1::RingAck + Send + Sync>; +pub type PcActionHandler = Arc< + dyn Fn(&str, protocol::v1::PcActionRequest) -> protocol::v1::PcActionResponse + Send + Sync, +>; /// Callbacks and configuration for active capabilities over a multiplexed session. #[derive(Clone)] @@ -64,6 +71,8 @@ pub struct SessionCapabilityHandlers { pub media_control_dispatcher: Arc, pub handoff_dispatcher: Arc, pub telemetry_dispatcher: Arc, + pub ring_dispatcher: Arc, + pub pc_control_dispatcher: Arc, pub on_file_received: Option>, pub on_clipboard_received: Option>, /// Called with notifications the peer shows here, and with replies to and dismissals of @@ -74,6 +83,8 @@ pub struct SessionCapabilityHandlers { pub on_handoff_received: Option>, pub on_handoff_dismissed: Option>, pub on_telemetry_received: Option>, + pub on_ring_requested: Option, + pub on_pc_action_requested: Option, /// How this device introduces itself to peers. pub this_device: ThisDevice, /// Called with what a peer says about itself each time a session starts. @@ -95,6 +106,8 @@ impl SessionCapabilityHandlers { media_control_dispatcher: Arc::new(MediaControlDispatcher::new()), handoff_dispatcher: Arc::new(HandoffDispatcher::new()), telemetry_dispatcher: Arc::new(TelemetryDispatcher::new()), + ring_dispatcher: Arc::new(RingDispatcher::new()), + pc_control_dispatcher: Arc::new(PcControlDispatcher::new()), on_file_received: None, on_clipboard_received: None, on_notification: None, @@ -103,6 +116,8 @@ impl SessionCapabilityHandlers { on_handoff_received: None, on_handoff_dismissed: None, on_telemetry_received: None, + on_ring_requested: None, + on_pc_action_requested: None, this_device: ThisDevice::default(), on_device_info: None, on_device_status: None, @@ -471,6 +486,86 @@ pub fn spawn_capabilities_dispatcher( error!("Failed to process telemetry stream from {peer_fp}: {e}"); } } + CapabilityId::RING_DEVICE => { + debug!("Handling incoming ring device stream from {peer_fp}"); + let is_permitted = + permitted(&handlers, &peer_fp, CapabilityId::RING_DEVICE, None).await; + + if is_permitted { + if let Some(store) = &handlers.permission_store { + store.consume_if_allow_once(&peer_fp, CapabilityId::RING_DEVICE); + } + } + + let query = + CapabilityQuery::negotiated(CapabilityId::RING_DEVICE, is_permitted); + + let on_ring = handlers.on_ring_requested.clone(); + let peer = peer_fp.clone(); + + let result = handlers + .ring_dispatcher + .receive_envelope( + &mut stream.send_stream, + &mut stream.recv_stream, + &query, + |req| { + if let Some(ref cb) = on_ring { + cb(&peer, req) + } else { + protocol::v1::RingAck { + is_ringing: false, + status_message: "Ring request not handled".into(), + } + } + }, + ) + .await; + + if let Err(e) = result { + error!("Failed to process ring stream from {peer_fp}: {e}"); + } + } + CapabilityId::PC_CONTROL => { + debug!("Handling incoming PC control stream from {peer_fp}"); + let is_permitted = + permitted(&handlers, &peer_fp, CapabilityId::PC_CONTROL, None).await; + + if is_permitted { + if let Some(store) = &handlers.permission_store { + store.consume_if_allow_once(&peer_fp, CapabilityId::PC_CONTROL); + } + } + + let query = + CapabilityQuery::negotiated(CapabilityId::PC_CONTROL, is_permitted); + + let on_action = handlers.on_pc_action_requested.clone(); + let peer = peer_fp.clone(); + + let result = handlers + .pc_control_dispatcher + .receive_envelope( + &mut stream.send_stream, + &mut stream.recv_stream, + &query, + |req| { + if let Some(ref cb) = on_action { + cb(&peer, req) + } else { + protocol::v1::PcActionResponse { + success: false, + error_message: "PC control action not handled".into(), + } + } + }, + ) + .await; + + if let Err(e) = result { + error!("Failed to process PC control stream from {peer_fp}: {e}"); + } + } unknown => { debug!("Received unsupported capability stream {unknown:?} from {peer_fp}"); } @@ -559,4 +654,36 @@ impl SessionMultiplexer { .publish_status(&mut send, &mut recv, update, query) .await } + + pub async fn trigger_ring_on_peer( + &self, + request: protocol::v1::RingRequest, + query: &CapabilityQuery, + ) -> Result { + let (mut send, mut recv) = self + .open_stream(CapabilityId::RING_DEVICE) + .await + .map_err(crate::error::SessionError::Transport)?; + + let dispatcher = RingDispatcher::new(); + dispatcher + .trigger_ring(&mut send, &mut recv, request, query) + .await + } + + pub async fn send_pc_action_to_peer( + &self, + request: protocol::v1::PcActionRequest, + query: &CapabilityQuery, + ) -> Result { + let (mut send, mut recv) = self + .open_stream(CapabilityId::PC_CONTROL) + .await + .map_err(crate::error::SessionError::Transport)?; + + let dispatcher = PcControlDispatcher::new(); + dispatcher + .send_action(&mut send, &mut recv, request, query) + .await + } } diff --git a/crates/sessions/src/lib.rs b/crates/sessions/src/lib.rs index 6feeb9e..19b2387 100644 --- a/crates/sessions/src/lib.rs +++ b/crates/sessions/src/lib.rs @@ -12,7 +12,9 @@ pub mod keepalive; pub mod listener; pub mod media_control; pub mod multiplexer; +pub mod pc_control; pub mod registry; +pub mod ring; pub mod session; pub mod state; pub mod telemetry; @@ -20,8 +22,9 @@ pub mod telemetry; pub use auto_connect::connect_paired_peers; pub use backoff::ReconnectPolicy; pub use capabilities_router::{ - spawn_capabilities_dispatcher, OnReceived, PermissionDecision, PermissionPrompt, - PermissionRequest, SessionCapabilityHandlers, PROMPT_TIMEOUT, + spawn_capabilities_dispatcher, MediaCommandHandler, OnReceived, PcActionHandler, + PermissionDecision, PermissionPrompt, PermissionRequest, RingHandler, + SessionCapabilityHandlers, PROMPT_TIMEOUT, }; pub use device::{clean_name, this_platform, PeerDevice, ThisDevice}; pub use error::SessionError; @@ -34,7 +37,9 @@ pub use multiplexer::{ close_code, open_capability_stream, read_capability_stream_header, IncomingCapabilityStream, SessionMultiplexer, }; +pub use pc_control::PcControlDispatcher; pub use registry::{Direction, RegistryConfig, SessionRegistry, StateListener, RESEND_WAIT}; +pub use ring::{RingDispatcher, DEFAULT_RING_DURATION_SECS}; pub use session::Session; pub use state::SessionState; pub use telemetry::{TelemetryAlertEvaluator, TelemetryDispatcher}; diff --git a/crates/sessions/src/pc_control.rs b/crates/sessions/src/pc_control.rs new file mode 100644 index 0000000..426e2be --- /dev/null +++ b/crates/sessions/src/pc_control.rs @@ -0,0 +1,165 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use capabilities::{evaluate_capability, CapabilityQuery}; +use limits::MAX_FRAME_PC_CONTROL_BYTES; +use protocol::v1::{ + pc_control_envelope::Payload, PcActionRequest, PcActionResponse, PcControlEnvelope, +}; +use transport::{read_msg, write_msg}; + +use crate::error::SessionError; + +#[derive(Default, Clone)] +pub struct PcControlDispatcher; + +impl PcControlDispatcher { + pub fn new() -> Self { + Self + } + + /// Sends a remote PC action request to the workstation and awaits the response. + pub async fn send_action( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + request: PcActionRequest, + query: &CapabilityQuery, + ) -> Result { + evaluate_capability(query)?; + + let envelope = PcControlEnvelope { + payload: Some(Payload::Request(request)), + }; + + write_msg(send_stream, &envelope, MAX_FRAME_PC_CONTROL_BYTES).await?; + let response: PcActionResponse = read_msg(recv_stream, MAX_FRAME_PC_CONTROL_BYTES).await?; + + Ok(response) + } + + /// Receives a remote PC action request, evaluates capability permissions, delegates to handler, and responds. + pub async fn receive_envelope( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + query: &CapabilityQuery, + mut on_action: H, + ) -> Result + where + H: FnMut(PcActionRequest) -> PcActionResponse, + { + evaluate_capability(query)?; + + let envelope: PcControlEnvelope = read_msg(recv_stream, MAX_FRAME_PC_CONTROL_BYTES).await?; + + match envelope.payload { + Some(Payload::Request(request)) => { + let response = on_action(request); + write_msg(send_stream, &response, MAX_FRAME_PC_CONTROL_BYTES).await?; + Ok(request) + } + Some(Payload::Response(_)) | None => Err(SessionError::UnexpectedMessage), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use protocol::v1::PcAction; + use protocol::CapabilityId; + use transport::{create_client_endpoint, create_server_endpoint, TransportCertificate}; + + #[tokio::test] + async fn pc_control_roundtrip() { + let server_cert = TransportCertificate::generate().unwrap(); + let client_cert = TransportCertificate::generate().unwrap(); + + let server_tls = server_cert + .build_pinned_server_tls(client_cert.spki_hash) + .unwrap(); + let client_tls = client_cert + .build_pinned_client_tls(server_cert.spki_hash) + .unwrap(); + + let server_endpoint = + create_server_endpoint("127.0.0.1:0".parse().unwrap(), server_tls).unwrap(); + let bound_addr = server_endpoint.local_addr().unwrap(); + + let client_endpoint = + create_client_endpoint("127.0.0.1:0".parse().unwrap(), client_tls).unwrap(); + + let server_task = tokio::spawn(async move { + let incoming = server_endpoint.accept().await.unwrap(); + let conn = incoming.await.unwrap(); + let (mut send_stream, mut recv_stream) = conn.accept_bi().await.unwrap(); + + let dispatcher = PcControlDispatcher::new(); + let query = CapabilityQuery::negotiated(CapabilityId::PC_CONTROL, true); + + let req = dispatcher + .receive_envelope(&mut send_stream, &mut recv_stream, &query, |req| { + if req.action == (PcAction::LockWorkstation as i32) { + PcActionResponse { + success: true, + error_message: String::new(), + } + } else { + PcActionResponse { + success: false, + error_message: "Unsupported action".into(), + } + } + }) + .await; + + (req, conn) + }); + + let conn = client_endpoint + .connect(bound_addr, "localhost") + .unwrap() + .await + .unwrap(); + let (mut send_stream, mut recv_stream) = conn.open_bi().await.unwrap(); + + let dispatcher = PcControlDispatcher::new(); + let query = CapabilityQuery::negotiated(CapabilityId::PC_CONTROL, true); + + let req = PcActionRequest { + action: PcAction::LockWorkstation as i32, + force: true, + }; + + let resp = dispatcher + .send_action(&mut send_stream, &mut recv_stream, req, &query) + .await + .unwrap(); + + assert!(resp.success); + assert!(resp.error_message.is_empty()); + + let (mut unneg_send, mut unneg_recv) = conn.open_bi().await.unwrap(); + let unnegotiated_query = CapabilityQuery::negotiated(CapabilityId::PC_CONTROL, false); + let err = dispatcher + .send_action( + &mut unneg_send, + &mut unneg_recv, + PcActionRequest::default(), + &unnegotiated_query, + ) + .await; + assert!(matches!( + err, + Err(SessionError::Capability( + capabilities::CapabilityError::PeerDenied(_) + )) + )); + + let (server_res, _server_conn) = server_task.await.unwrap(); + let req = server_res.unwrap(); + assert_eq!(req.action, PcAction::LockWorkstation as i32); + assert!(req.force); + } +} diff --git a/crates/sessions/src/ring.rs b/crates/sessions/src/ring.rs new file mode 100644 index 0000000..3c8ccbf --- /dev/null +++ b/crates/sessions/src/ring.rs @@ -0,0 +1,157 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use capabilities::{evaluate_capability, CapabilityQuery}; +use limits::MAX_FRAME_RING_BYTES; +use protocol::v1::{ring_envelope::Payload, RingAck, RingEnvelope, RingRequest}; +use transport::{read_msg, write_msg}; + +use crate::error::SessionError; + +pub const DEFAULT_RING_DURATION_SECS: u32 = 30; + +#[derive(Default, Clone)] +pub struct RingDispatcher; + +impl RingDispatcher { + pub fn new() -> Self { + Self + } + + /// Sends a ring device request to the remote peer over the QUIC stream and awaits confirmation. + pub async fn trigger_ring( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + request: RingRequest, + query: &CapabilityQuery, + ) -> Result { + evaluate_capability(query)?; + + let envelope = RingEnvelope { + payload: Some(Payload::Request(request)), + }; + + write_msg(send_stream, &envelope, MAX_FRAME_RING_BYTES).await?; + let ack: RingAck = read_msg(recv_stream, MAX_FRAME_RING_BYTES).await?; + + Ok(ack) + } + + /// Receives a ring request from the remote peer, delegates to the handler, and writes back confirmation. + pub async fn receive_envelope( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + query: &CapabilityQuery, + mut on_ring: H, + ) -> Result + where + H: FnMut(RingRequest) -> RingAck, + { + evaluate_capability(query)?; + + let envelope: RingEnvelope = read_msg(recv_stream, MAX_FRAME_RING_BYTES).await?; + + match envelope.payload { + Some(Payload::Request(request)) => { + let ack = on_ring(request); + write_msg(send_stream, &ack, MAX_FRAME_RING_BYTES).await?; + Ok(request) + } + Some(Payload::Ack(_)) | None => Err(SessionError::UnexpectedMessage), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use protocol::CapabilityId; + use transport::{create_client_endpoint, create_server_endpoint, TransportCertificate}; + + #[tokio::test] + async fn ring_trigger_and_receive_roundtrip() { + let server_cert = TransportCertificate::generate().unwrap(); + let client_cert = TransportCertificate::generate().unwrap(); + + let server_tls = server_cert + .build_pinned_server_tls(client_cert.spki_hash) + .unwrap(); + let client_tls = client_cert + .build_pinned_client_tls(server_cert.spki_hash) + .unwrap(); + + let server_endpoint = + create_server_endpoint("127.0.0.1:0".parse().unwrap(), server_tls).unwrap(); + let bound_addr = server_endpoint.local_addr().unwrap(); + + let client_endpoint = + create_client_endpoint("127.0.0.1:0".parse().unwrap(), client_tls).unwrap(); + + let server_task = tokio::spawn(async move { + let incoming = server_endpoint.accept().await.unwrap(); + let conn = incoming.await.unwrap(); + let (mut send_stream, mut recv_stream) = conn.accept_bi().await.unwrap(); + + let dispatcher = RingDispatcher::new(); + let query = CapabilityQuery::negotiated(CapabilityId::RING_DEVICE, true); + + let req = dispatcher + .receive_envelope(&mut send_stream, &mut recv_stream, &query, |req| RingAck { + is_ringing: req.active, + status_message: "Alarm playing".into(), + }) + .await; + + (req, conn) + }); + + let conn = client_endpoint + .connect(bound_addr, "localhost") + .unwrap() + .await + .unwrap(); + let (mut send_stream, mut recv_stream) = conn.open_bi().await.unwrap(); + + let dispatcher = RingDispatcher::new(); + let query = CapabilityQuery::negotiated(CapabilityId::RING_DEVICE, true); + + let req = RingRequest { + active: true, + duration_secs: 15, + force_max_volume: true, + }; + + let ack = dispatcher + .trigger_ring(&mut send_stream, &mut recv_stream, req, &query) + .await + .unwrap(); + + assert!(ack.is_ringing); + assert_eq!(ack.status_message, "Alarm playing"); + + let (mut unneg_send, mut unneg_recv) = conn.open_bi().await.unwrap(); + let unnegotiated_query = CapabilityQuery::negotiated(CapabilityId::RING_DEVICE, false); + let err = dispatcher + .trigger_ring( + &mut unneg_send, + &mut unneg_recv, + RingRequest::default(), + &unnegotiated_query, + ) + .await; + assert!(matches!( + err, + Err(SessionError::Capability( + capabilities::CapabilityError::PeerDenied(_) + )) + )); + + let (server_res, _server_conn) = server_task.await.unwrap(); + let req = server_res.unwrap(); + assert!(req.active); + assert_eq!(req.duration_secs, 15); + assert!(req.force_max_volume); + } +} diff --git a/proto/pc_control.proto b/proto/pc_control.proto new file mode 100644 index 0000000..a0de139 --- /dev/null +++ b/proto/pc_control.proto @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +package continue.v1; + +enum PcAction { + PC_ACTION_LOCK_WORKSTATION = 0; + PC_ACTION_SLEEP_SYSTEM = 1; + PC_ACTION_SHUTDOWN_SYSTEM = 2; + PC_ACTION_TOGGLE_MUTE = 3; +} + +message PcActionRequest { + PcAction action = 1; + bool force = 2; +} + +message PcActionResponse { + bool success = 1; + string error_message = 2; +} + +message PcControlEnvelope { + oneof payload { + PcActionRequest request = 1; + PcActionResponse response = 2; + } +} diff --git a/proto/ring.proto b/proto/ring.proto new file mode 100644 index 0000000..4e440f9 --- /dev/null +++ b/proto/ring.proto @@ -0,0 +1,24 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +package continue.v1; + +message RingRequest { + bool active = 1; + uint32 duration_secs = 2; + bool force_max_volume = 3; +} + +message RingAck { + bool is_ringing = 1; + string status_message = 2; +} + +message RingEnvelope { + oneof payload { + RingRequest request = 1; + RingAck ack = 2; + } +} From de1395dd2f6043478b448683a1a0c6e34f236cd9 Mon Sep 17 00:00:00 2001 From: Samarth Rajesh Lad <142334685+samyyy2311@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:50:38 +0530 Subject: [PATCH 04/14] feat: add remote dictation input stream and macro deck capabilities - Define CapabilityId::REMOTE_INPUT (10) and CapabilityId::DECK (11) - Add protobuf schemas for TextInputChunk and DeckEnvelope - Implement RemoteInputDispatcher and DeckDispatcher with validation and QUIC roundtrip tests - Wire remote input and deck into SessionCapabilityHandlers and SessionMultiplexer --- crates/limits/src/lib.rs | 18 ++ crates/protocol/build.rs | 2 + crates/protocol/src/capability.rs | 4 + crates/sessions/src/capabilities_router.rs | 156 +++++++++ crates/sessions/src/deck.rs | 359 +++++++++++++++++++++ crates/sessions/src/error.rs | 6 + crates/sessions/src/lib.rs | 10 +- crates/sessions/src/remote_input.rs | 192 +++++++++++ proto/deck.proto | 34 ++ proto/remote_input.proto | 24 ++ 10 files changed, 802 insertions(+), 3 deletions(-) create mode 100644 crates/sessions/src/deck.rs create mode 100644 crates/sessions/src/remote_input.rs create mode 100644 proto/deck.proto create mode 100644 proto/remote_input.proto diff --git a/crates/limits/src/lib.rs b/crates/limits/src/lib.rs index 053d054..25093f9 100644 --- a/crates/limits/src/lib.rs +++ b/crates/limits/src/lib.rs @@ -84,6 +84,24 @@ pub const MAX_FRAME_RING_BYTES: usize = 16 * 1024; /// PC remote control actions and response messages. pub const MAX_FRAME_PC_CONTROL_BYTES: usize = 16 * 1024; +/// Remote input (dictation / text typing) message frame size. +pub const MAX_FRAME_REMOTE_INPUT_BYTES: usize = 16 * 1024; + +/// Maximum UTF-8 byte length for a single remote text input chunk. +pub const MAX_REMOTE_INPUT_TEXT_BYTES: usize = 8 * 1024; + +/// Deck configuration and layout sync message frame size. +pub const MAX_FRAME_DECK_BYTES: usize = 64 * 1024; + +/// Maximum number of tiles supported in a deck layout. +pub const MAX_DECK_TILES: usize = 64; + +/// Maximum UTF-8 byte length for a deck tile ID. +pub const MAX_DECK_TILE_ID_BYTES: usize = 128; + +/// Maximum UTF-8 byte length for a deck tile label. +pub const MAX_DECK_LABEL_BYTES: usize = 256; + // File transfer /// Maximum UTF-8 byte length of a transfer filename. diff --git a/crates/protocol/build.rs b/crates/protocol/build.rs index 9815c36..74014d4 100644 --- a/crates/protocol/build.rs +++ b/crates/protocol/build.rs @@ -23,6 +23,8 @@ fn main() { proto_dir.join("telemetry.proto"), proto_dir.join("ring.proto"), proto_dir.join("pc_control.proto"), + proto_dir.join("remote_input.proto"), + proto_dir.join("deck.proto"), ]; for file in &proto_files { diff --git a/crates/protocol/src/capability.rs b/crates/protocol/src/capability.rs index 6c971ec..1a8f1cb 100644 --- a/crates/protocol/src/capability.rs +++ b/crates/protocol/src/capability.rs @@ -21,6 +21,8 @@ impl CapabilityId { pub const TELEMETRY: Self = Self(7); pub const RING_DEVICE: Self = Self(8); pub const PC_CONTROL: Self = Self(9); + pub const REMOTE_INPUT: Self = Self(10); + pub const DECK: Self = Self(11); pub const fn new(id: u32) -> Self { Self(id) @@ -42,6 +44,8 @@ impl CapabilityId { Self::TELEMETRY => Some("telemetry"), Self::RING_DEVICE => Some("ring_device"), Self::PC_CONTROL => Some("pc_control"), + Self::REMOTE_INPUT => Some("remote_input"), + Self::DECK => Some("deck"), _ => None, } } diff --git a/crates/sessions/src/capabilities_router.rs b/crates/sessions/src/capabilities_router.rs index 7752426..31189d8 100644 --- a/crates/sessions/src/capabilities_router.rs +++ b/crates/sessions/src/capabilities_router.rs @@ -13,12 +13,14 @@ use notifications::Body as NotificationBody; use protocol::CapabilityId; use transfer::{receive_file, send_file, ReceivedFile}; +use crate::deck::DeckDispatcher; use crate::device::{PeerDevice, ThisDevice}; use crate::handoff::HandoffDispatcher; use crate::incoming::{IncomingFiles, SaveFolder}; use crate::media_control::MediaControlDispatcher; use crate::multiplexer::{OnPeerUpdate, PeerUpdate, SessionMultiplexer}; use crate::pc_control::PcControlDispatcher; +use crate::remote_input::RemoteInputDispatcher; use crate::ring::RingDispatcher; use crate::telemetry::TelemetryDispatcher; @@ -62,6 +64,12 @@ pub type RingHandler = pub type PcActionHandler = Arc< dyn Fn(&str, protocol::v1::PcActionRequest) -> protocol::v1::PcActionResponse + Send + Sync, >; +pub type RemoteInputHandler = + Arc protocol::v1::RemoteInputAck + Send + Sync>; +pub type DeckLayoutHandler = + Arc protocol::v1::DeckAck + Send + Sync>; +pub type DeckTriggerHandler = + Arc protocol::v1::DeckAck + Send + Sync>; /// Callbacks and configuration for active capabilities over a multiplexed session. #[derive(Clone)] @@ -73,6 +81,8 @@ pub struct SessionCapabilityHandlers { pub telemetry_dispatcher: Arc, pub ring_dispatcher: Arc, pub pc_control_dispatcher: Arc, + pub remote_input_dispatcher: Arc, + pub deck_dispatcher: Arc, pub on_file_received: Option>, pub on_clipboard_received: Option>, /// Called with notifications the peer shows here, and with replies to and dismissals of @@ -85,6 +95,9 @@ pub struct SessionCapabilityHandlers { pub on_telemetry_received: Option>, pub on_ring_requested: Option, pub on_pc_action_requested: Option, + pub on_remote_input: Option, + pub on_deck_layout_synced: Option, + pub on_deck_tile_triggered: Option, /// How this device introduces itself to peers. pub this_device: ThisDevice, /// Called with what a peer says about itself each time a session starts. @@ -108,6 +121,8 @@ impl SessionCapabilityHandlers { telemetry_dispatcher: Arc::new(TelemetryDispatcher::new()), ring_dispatcher: Arc::new(RingDispatcher::new()), pc_control_dispatcher: Arc::new(PcControlDispatcher::new()), + remote_input_dispatcher: Arc::new(RemoteInputDispatcher::new()), + deck_dispatcher: Arc::new(DeckDispatcher::new()), on_file_received: None, on_clipboard_received: None, on_notification: None, @@ -118,6 +133,9 @@ impl SessionCapabilityHandlers { on_telemetry_received: None, on_ring_requested: None, on_pc_action_requested: None, + on_remote_input: None, + on_deck_layout_synced: None, + on_deck_tile_triggered: None, this_device: ThisDevice::default(), on_device_info: None, on_device_status: None, @@ -566,6 +584,96 @@ pub fn spawn_capabilities_dispatcher( error!("Failed to process PC control stream from {peer_fp}: {e}"); } } + CapabilityId::REMOTE_INPUT => { + debug!("Handling incoming remote input stream from {peer_fp}"); + let is_permitted = + permitted(&handlers, &peer_fp, CapabilityId::REMOTE_INPUT, None).await; + + if is_permitted { + if let Some(store) = &handlers.permission_store { + store.consume_if_allow_once(&peer_fp, CapabilityId::REMOTE_INPUT); + } + } + + let query = + CapabilityQuery::negotiated(CapabilityId::REMOTE_INPUT, is_permitted); + + let on_chunk = handlers.on_remote_input.clone(); + let peer = peer_fp.clone(); + + let result = handlers + .remote_input_dispatcher + .receive_envelope( + &mut stream.send_stream, + &mut stream.recv_stream, + &query, + |chunk| { + if let Some(ref cb) = on_chunk { + cb(&peer, chunk) + } else { + protocol::v1::RemoteInputAck { + success: false, + error_message: "Remote input not handled".into(), + } + } + }, + ) + .await; + + if let Err(e) = result { + error!("Failed to process remote input stream from {peer_fp}: {e}"); + } + } + CapabilityId::DECK => { + debug!("Handling incoming deck stream from {peer_fp}"); + let is_permitted = + permitted(&handlers, &peer_fp, CapabilityId::DECK, None).await; + + if is_permitted { + if let Some(store) = &handlers.permission_store { + store.consume_if_allow_once(&peer_fp, CapabilityId::DECK); + } + } + + let query = CapabilityQuery::negotiated(CapabilityId::DECK, is_permitted); + + let on_layout = handlers.on_deck_layout_synced.clone(); + let on_trigger = handlers.on_deck_tile_triggered.clone(); + let peer = peer_fp.clone(); + + let result = handlers + .deck_dispatcher + .receive_envelope( + &mut stream.send_stream, + &mut stream.recv_stream, + &query, + |layout| { + if let Some(ref cb) = on_layout { + cb(&peer, layout) + } else { + protocol::v1::DeckAck { + success: false, + error_message: "Deck layout sync not handled".into(), + } + } + }, + |trigger| { + if let Some(ref cb) = on_trigger { + cb(&peer, trigger) + } else { + protocol::v1::DeckAck { + success: false, + error_message: "Deck tile trigger not handled".into(), + } + } + }, + ) + .await; + + if let Err(e) = result { + error!("Failed to process deck stream from {peer_fp}: {e}"); + } + } unknown => { debug!("Received unsupported capability stream {unknown:?} from {peer_fp}"); } @@ -686,4 +794,52 @@ impl SessionMultiplexer { .send_action(&mut send, &mut recv, request, query) .await } + + pub async fn send_remote_input_chunk_to_peer( + &self, + chunk: protocol::v1::TextInputChunk, + query: &CapabilityQuery, + ) -> Result { + let (mut send, mut recv) = self + .open_stream(CapabilityId::REMOTE_INPUT) + .await + .map_err(crate::error::SessionError::Transport)?; + + let dispatcher = RemoteInputDispatcher::new(); + dispatcher + .send_chunk(&mut send, &mut recv, chunk, query) + .await + } + + pub async fn sync_deck_layout_to_peer( + &self, + layout: protocol::v1::DeckLayoutSync, + query: &CapabilityQuery, + ) -> Result { + let (mut send, mut recv) = self + .open_stream(CapabilityId::DECK) + .await + .map_err(crate::error::SessionError::Transport)?; + + let dispatcher = DeckDispatcher::new(); + dispatcher + .sync_layout(&mut send, &mut recv, layout, query) + .await + } + + pub async fn trigger_deck_tile_on_peer( + &self, + trigger: protocol::v1::DeckTriggerEvent, + query: &CapabilityQuery, + ) -> Result { + let (mut send, mut recv) = self + .open_stream(CapabilityId::DECK) + .await + .map_err(crate::error::SessionError::Transport)?; + + let dispatcher = DeckDispatcher::new(); + dispatcher + .trigger_tile(&mut send, &mut recv, trigger, query) + .await + } } diff --git a/crates/sessions/src/deck.rs b/crates/sessions/src/deck.rs new file mode 100644 index 0000000..7be06de --- /dev/null +++ b/crates/sessions/src/deck.rs @@ -0,0 +1,359 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use capabilities::{evaluate_capability, CapabilityQuery}; +use limits::{MAX_DECK_LABEL_BYTES, MAX_DECK_TILES, MAX_DECK_TILE_ID_BYTES, MAX_FRAME_DECK_BYTES}; +use protocol::v1::{ + deck_envelope::Payload, DeckAck, DeckEnvelope, DeckLayoutSync, DeckTileConfig, DeckTriggerEvent, +}; +use transport::{read_msg, write_msg}; + +use crate::error::SessionError; + +#[derive(Default, Clone)] +pub struct DeckDispatcher; + +impl DeckDispatcher { + pub fn new() -> Self { + Self + } + + pub fn validate_layout(layout: &DeckLayoutSync) -> Result<(), SessionError> { + if layout.tiles.len() > MAX_DECK_TILES { + return Err(SessionError::DeckValidation(format!( + "Tile count {} exceeds maximum allowed of {}", + layout.tiles.len(), + MAX_DECK_TILES + ))); + } + + for tile in &layout.tiles { + Self::validate_tile(tile)?; + } + + Ok(()) + } + + pub fn validate_tile(tile: &DeckTileConfig) -> Result<(), SessionError> { + if tile.tile_id.is_empty() { + return Err(SessionError::DeckValidation( + "Deck tile ID cannot be empty".into(), + )); + } + + if tile.tile_id.len() > MAX_DECK_TILE_ID_BYTES { + return Err(SessionError::DeckValidation(format!( + "Tile ID length {} exceeds maximum allowed of {} bytes", + tile.tile_id.len(), + MAX_DECK_TILE_ID_BYTES + ))); + } + + if tile.label.len() > MAX_DECK_LABEL_BYTES { + return Err(SessionError::DeckValidation(format!( + "Tile label length {} exceeds maximum allowed of {} bytes", + tile.label.len(), + MAX_DECK_LABEL_BYTES + ))); + } + + Ok(()) + } + + pub fn validate_trigger(trigger: &DeckTriggerEvent) -> Result<(), SessionError> { + if trigger.tile_id.is_empty() { + return Err(SessionError::DeckValidation( + "Deck trigger tile ID cannot be empty".into(), + )); + } + + if trigger.tile_id.len() > MAX_DECK_TILE_ID_BYTES { + return Err(SessionError::DeckValidation(format!( + "Trigger tile ID length {} exceeds maximum allowed of {} bytes", + trigger.tile_id.len(), + MAX_DECK_TILE_ID_BYTES + ))); + } + + Ok(()) + } + + /// Pushes a deck layout from the host to the connected peer device. + pub async fn sync_layout( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + layout: DeckLayoutSync, + query: &CapabilityQuery, + ) -> Result { + evaluate_capability(query)?; + Self::validate_layout(&layout)?; + + let envelope = DeckEnvelope { + payload: Some(Payload::Layout(layout)), + }; + + write_msg(send_stream, &envelope, MAX_FRAME_DECK_BYTES).await?; + let ack: DeckAck = read_msg(recv_stream, MAX_FRAME_DECK_BYTES).await?; + + Ok(ack) + } + + /// Sends a tile button press/trigger event from the peer to the host workstation. + pub async fn trigger_tile( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + trigger: DeckTriggerEvent, + query: &CapabilityQuery, + ) -> Result { + evaluate_capability(query)?; + Self::validate_trigger(&trigger)?; + + let envelope = DeckEnvelope { + payload: Some(Payload::Trigger(trigger)), + }; + + write_msg(send_stream, &envelope, MAX_FRAME_DECK_BYTES).await?; + let ack: DeckAck = read_msg(recv_stream, MAX_FRAME_DECK_BYTES).await?; + + Ok(ack) + } + + /// Receives a deck envelope, delegates layout or trigger handling, and replies with an ack. + pub async fn receive_envelope( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + query: &CapabilityQuery, + mut on_layout: L, + mut on_trigger: T, + ) -> Result + where + L: FnMut(DeckLayoutSync) -> DeckAck, + T: FnMut(DeckTriggerEvent) -> DeckAck, + { + evaluate_capability(query)?; + + let envelope: DeckEnvelope = read_msg(recv_stream, MAX_FRAME_DECK_BYTES).await?; + + match envelope.payload { + Some(Payload::Layout(ref layout)) => { + Self::validate_layout(layout)?; + let ack = on_layout(layout.clone()); + write_msg(send_stream, &ack, MAX_FRAME_DECK_BYTES).await?; + Ok(envelope) + } + Some(Payload::Trigger(ref trigger)) => { + Self::validate_trigger(trigger)?; + let ack = on_trigger(trigger.clone()); + write_msg(send_stream, &ack, MAX_FRAME_DECK_BYTES).await?; + Ok(envelope) + } + Some(Payload::Ack(_)) | None => Err(SessionError::UnexpectedMessage), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use protocol::CapabilityId; + use transport::{create_client_endpoint, create_server_endpoint, TransportCertificate}; + + #[tokio::test] + async fn deck_sync_layout_roundtrip() { + let server_cert = TransportCertificate::generate().unwrap(); + let client_cert = TransportCertificate::generate().unwrap(); + + let server_tls = server_cert + .build_pinned_server_tls(client_cert.spki_hash) + .unwrap(); + let client_tls = client_cert + .build_pinned_client_tls(server_cert.spki_hash) + .unwrap(); + + let server_endpoint = + create_server_endpoint("127.0.0.1:0".parse().unwrap(), server_tls).unwrap(); + let bound_addr = server_endpoint.local_addr().unwrap(); + let client_endpoint = + create_client_endpoint("127.0.0.1:0".parse().unwrap(), client_tls).unwrap(); + + let server_task = tokio::spawn(async move { + let incoming = server_endpoint.accept().await.unwrap(); + let conn = incoming.await.unwrap(); + let (mut send_stream, mut recv_stream) = conn.accept_bi().await.unwrap(); + + let dispatcher = DeckDispatcher::new(); + let query = CapabilityQuery::negotiated(CapabilityId::DECK, true); + + let res = dispatcher + .receive_envelope( + &mut send_stream, + &mut recv_stream, + &query, + |layout| DeckAck { + success: layout.tiles.len() == 2, + error_message: String::new(), + }, + |_| unreachable!(), + ) + .await; + + (res, conn) + }); + + let conn = client_endpoint + .connect(bound_addr, "localhost") + .unwrap() + .await + .unwrap(); + let (mut send_stream, mut recv_stream) = conn.open_bi().await.unwrap(); + + let dispatcher = DeckDispatcher::new(); + let query = CapabilityQuery::negotiated(CapabilityId::DECK, true); + + let layout = DeckLayoutSync { + tiles: vec![ + DeckTileConfig { + tile_id: "mute_mic".into(), + label: "Mute Mic".into(), + icon: "mic-off".into(), + action_command: "toggle_mic".into(), + }, + DeckTileConfig { + tile_id: "screen_lock".into(), + label: "Lock PC".into(), + icon: "lock".into(), + action_command: "lock".into(), + }, + ], + }; + + let ack = dispatcher + .sync_layout(&mut send_stream, &mut recv_stream, layout, &query) + .await + .unwrap(); + + assert!(ack.success); + + let (mut unneg_send, mut unneg_recv) = conn.open_bi().await.unwrap(); + let unnegotiated_query = CapabilityQuery::negotiated(CapabilityId::DECK, false); + let err = dispatcher + .sync_layout( + &mut unneg_send, + &mut unneg_recv, + DeckLayoutSync::default(), + &unnegotiated_query, + ) + .await; + assert!(matches!( + err, + Err(SessionError::Capability( + capabilities::CapabilityError::PeerDenied(_) + )) + )); + + let (server_res, _server_conn) = server_task.await.unwrap(); + let env = server_res.unwrap(); + assert!(matches!(env.payload, Some(Payload::Layout(_)))); + } + + #[tokio::test] + async fn deck_trigger_roundtrip() { + let server_cert = TransportCertificate::generate().unwrap(); + let client_cert = TransportCertificate::generate().unwrap(); + + let server_tls = server_cert + .build_pinned_server_tls(client_cert.spki_hash) + .unwrap(); + let client_tls = client_cert + .build_pinned_client_tls(server_cert.spki_hash) + .unwrap(); + + let server_endpoint = + create_server_endpoint("127.0.0.1:0".parse().unwrap(), server_tls).unwrap(); + let bound_addr = server_endpoint.local_addr().unwrap(); + let client_endpoint = + create_client_endpoint("127.0.0.1:0".parse().unwrap(), client_tls).unwrap(); + + let server_task = tokio::spawn(async move { + let incoming = server_endpoint.accept().await.unwrap(); + let conn = incoming.await.unwrap(); + let (mut send_stream, mut recv_stream) = conn.accept_bi().await.unwrap(); + + let dispatcher = DeckDispatcher::new(); + let query = CapabilityQuery::negotiated(CapabilityId::DECK, true); + + let res = dispatcher + .receive_envelope( + &mut send_stream, + &mut recv_stream, + &query, + |_| unreachable!(), + |trigger| DeckAck { + success: trigger.tile_id == "play_pause", + error_message: String::new(), + }, + ) + .await; + + (res, conn) + }); + + let conn = client_endpoint + .connect(bound_addr, "localhost") + .unwrap() + .await + .unwrap(); + let (mut send_stream, mut recv_stream) = conn.open_bi().await.unwrap(); + + let dispatcher = DeckDispatcher::new(); + let query = CapabilityQuery::negotiated(CapabilityId::DECK, true); + + let trigger = DeckTriggerEvent { + tile_id: "play_pause".into(), + }; + + let ack = dispatcher + .trigger_tile(&mut send_stream, &mut recv_stream, trigger, &query) + .await + .unwrap(); + + assert!(ack.success); + + let (server_res, _server_conn) = server_task.await.unwrap(); + let env = server_res.unwrap(); + assert!(matches!(env.payload, Some(Payload::Trigger(_)))); + } + + #[test] + fn validates_tile_and_trigger_constraints() { + let empty_trigger = DeckTriggerEvent { + tile_id: String::new(), + }; + assert!(matches!( + DeckDispatcher::validate_trigger(&empty_trigger), + Err(SessionError::DeckValidation(_)) + )); + + let valid_tile = DeckTileConfig { + tile_id: "tile_1".into(), + label: "Action".into(), + icon: "star".into(), + action_command: "cmd".into(), + }; + assert!(DeckDispatcher::validate_tile(&valid_tile).is_ok()); + + let oversized_label_tile = DeckTileConfig { + tile_id: "tile_1".into(), + label: "x".repeat(MAX_DECK_LABEL_BYTES + 1), + icon: "star".into(), + action_command: "cmd".into(), + }; + assert!(matches!( + DeckDispatcher::validate_tile(&oversized_label_tile), + Err(SessionError::DeckValidation(_)) + )); + } +} diff --git a/crates/sessions/src/error.rs b/crates/sessions/src/error.rs index 5a2455f..648f914 100644 --- a/crates/sessions/src/error.rs +++ b/crates/sessions/src/error.rs @@ -34,4 +34,10 @@ pub enum SessionError { #[error("Handoff validation failed: {0}")] HandoffValidation(String), + + #[error("Remote input validation failed: {0}")] + RemoteInputValidation(String), + + #[error("Deck validation failed: {0}")] + DeckValidation(String), } diff --git a/crates/sessions/src/lib.rs b/crates/sessions/src/lib.rs index 19b2387..42c033f 100644 --- a/crates/sessions/src/lib.rs +++ b/crates/sessions/src/lib.rs @@ -4,6 +4,7 @@ pub mod auto_connect; pub mod backoff; pub mod capabilities_router; +pub mod deck; pub mod device; pub mod error; pub mod handoff; @@ -14,6 +15,7 @@ pub mod media_control; pub mod multiplexer; pub mod pc_control; pub mod registry; +pub mod remote_input; pub mod ring; pub mod session; pub mod state; @@ -22,10 +24,11 @@ pub mod telemetry; pub use auto_connect::connect_paired_peers; pub use backoff::ReconnectPolicy; pub use capabilities_router::{ - spawn_capabilities_dispatcher, MediaCommandHandler, OnReceived, PcActionHandler, - PermissionDecision, PermissionPrompt, PermissionRequest, RingHandler, - SessionCapabilityHandlers, PROMPT_TIMEOUT, + spawn_capabilities_dispatcher, DeckLayoutHandler, DeckTriggerHandler, MediaCommandHandler, + OnReceived, PcActionHandler, PermissionDecision, PermissionPrompt, PermissionRequest, + RemoteInputHandler, RingHandler, SessionCapabilityHandlers, PROMPT_TIMEOUT, }; +pub use deck::DeckDispatcher; pub use device::{clean_name, this_platform, PeerDevice, ThisDevice}; pub use error::SessionError; pub use handoff::HandoffDispatcher; @@ -39,6 +42,7 @@ pub use multiplexer::{ }; pub use pc_control::PcControlDispatcher; pub use registry::{Direction, RegistryConfig, SessionRegistry, StateListener, RESEND_WAIT}; +pub use remote_input::RemoteInputDispatcher; pub use ring::{RingDispatcher, DEFAULT_RING_DURATION_SECS}; pub use session::Session; pub use state::SessionState; diff --git a/crates/sessions/src/remote_input.rs b/crates/sessions/src/remote_input.rs new file mode 100644 index 0000000..085baa6 --- /dev/null +++ b/crates/sessions/src/remote_input.rs @@ -0,0 +1,192 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use capabilities::{evaluate_capability, CapabilityQuery}; +use limits::{MAX_FRAME_REMOTE_INPUT_BYTES, MAX_REMOTE_INPUT_TEXT_BYTES}; +use protocol::v1::{ + remote_input_envelope::Payload, RemoteInputAck, RemoteInputEnvelope, TextInputChunk, +}; +use transport::{read_msg, write_msg}; + +use crate::error::SessionError; + +#[derive(Default, Clone)] +pub struct RemoteInputDispatcher; + +impl RemoteInputDispatcher { + pub fn new() -> Self { + Self + } + + pub fn validate_chunk(chunk: &TextInputChunk) -> Result<(), SessionError> { + if chunk.text.len() > MAX_REMOTE_INPUT_TEXT_BYTES { + return Err(SessionError::RemoteInputValidation(format!( + "Text chunk length {} exceeds maximum allowed of {} bytes", + chunk.text.len(), + MAX_REMOTE_INPUT_TEXT_BYTES + ))); + } + Ok(()) + } + + /// Sends a text chunk (dictation or keyboard input) to the remote peer. + pub async fn send_chunk( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + chunk: TextInputChunk, + query: &CapabilityQuery, + ) -> Result { + evaluate_capability(query)?; + Self::validate_chunk(&chunk)?; + + let envelope = RemoteInputEnvelope { + payload: Some(Payload::Chunk(chunk)), + }; + + write_msg(send_stream, &envelope, MAX_FRAME_REMOTE_INPUT_BYTES).await?; + let ack: RemoteInputAck = read_msg(recv_stream, MAX_FRAME_REMOTE_INPUT_BYTES).await?; + + Ok(ack) + } + + /// Receives a text input envelope, passes the chunk to the handler, and writes back an acknowledgment. + pub async fn receive_envelope( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + query: &CapabilityQuery, + mut on_chunk: H, + ) -> Result + where + H: FnMut(TextInputChunk) -> RemoteInputAck, + { + evaluate_capability(query)?; + + let envelope: RemoteInputEnvelope = + read_msg(recv_stream, MAX_FRAME_REMOTE_INPUT_BYTES).await?; + + match envelope.payload { + Some(Payload::Chunk(chunk)) => { + Self::validate_chunk(&chunk)?; + let ack = on_chunk(chunk.clone()); + write_msg(send_stream, &ack, MAX_FRAME_REMOTE_INPUT_BYTES).await?; + Ok(chunk) + } + Some(Payload::Ack(_)) | None => Err(SessionError::UnexpectedMessage), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use protocol::CapabilityId; + use transport::{create_client_endpoint, create_server_endpoint, TransportCertificate}; + + #[tokio::test] + async fn remote_input_roundtrip() { + let server_cert = TransportCertificate::generate().unwrap(); + let client_cert = TransportCertificate::generate().unwrap(); + + let server_tls = server_cert + .build_pinned_server_tls(client_cert.spki_hash) + .unwrap(); + let client_tls = client_cert + .build_pinned_client_tls(server_cert.spki_hash) + .unwrap(); + + let server_endpoint = + create_server_endpoint("127.0.0.1:0".parse().unwrap(), server_tls).unwrap(); + let bound_addr = server_endpoint.local_addr().unwrap(); + + let client_endpoint = + create_client_endpoint("127.0.0.1:0".parse().unwrap(), client_tls).unwrap(); + + let server_task = tokio::spawn(async move { + let incoming = server_endpoint.accept().await.unwrap(); + let conn = incoming.await.unwrap(); + let (mut send_stream, mut recv_stream) = conn.accept_bi().await.unwrap(); + + let dispatcher = RemoteInputDispatcher::new(); + let query = CapabilityQuery::negotiated(CapabilityId::REMOTE_INPUT, true); + + let chunk = dispatcher + .receive_envelope(&mut send_stream, &mut recv_stream, &query, |chunk| { + RemoteInputAck { + success: chunk.commit, + error_message: String::new(), + } + }) + .await; + + (chunk, conn) + }); + + let conn = client_endpoint + .connect(bound_addr, "localhost") + .unwrap() + .await + .unwrap(); + let (mut send_stream, mut recv_stream) = conn.open_bi().await.unwrap(); + + let dispatcher = RemoteInputDispatcher::new(); + let query = CapabilityQuery::negotiated(CapabilityId::REMOTE_INPUT, true); + + let chunk = TextInputChunk { + text: "Hello from phone dictation".into(), + commit: true, + sequence: 1, + }; + + let ack = dispatcher + .send_chunk(&mut send_stream, &mut recv_stream, chunk, &query) + .await + .unwrap(); + + assert!(ack.success); + + let (mut unneg_send, mut unneg_recv) = conn.open_bi().await.unwrap(); + let unnegotiated_query = CapabilityQuery::negotiated(CapabilityId::REMOTE_INPUT, false); + let err = dispatcher + .send_chunk( + &mut unneg_send, + &mut unneg_recv, + TextInputChunk::default(), + &unnegotiated_query, + ) + .await; + assert!(matches!( + err, + Err(SessionError::Capability( + capabilities::CapabilityError::PeerDenied(_) + )) + )); + + let (server_res, _server_conn) = server_task.await.unwrap(); + let received = server_res.unwrap(); + assert_eq!(received.text, "Hello from phone dictation"); + assert!(received.commit); + assert_eq!(received.sequence, 1); + } + + #[test] + fn validates_chunk_length() { + let ok_chunk = TextInputChunk { + text: "Valid text".into(), + commit: false, + sequence: 0, + }; + assert!(RemoteInputDispatcher::validate_chunk(&ok_chunk).is_ok()); + + let oversized_chunk = TextInputChunk { + text: "a".repeat(MAX_REMOTE_INPUT_TEXT_BYTES + 1), + commit: true, + sequence: 1, + }; + assert!(matches!( + RemoteInputDispatcher::validate_chunk(&oversized_chunk), + Err(SessionError::RemoteInputValidation(_)) + )); + } +} diff --git a/proto/deck.proto b/proto/deck.proto new file mode 100644 index 0000000..e025dbc --- /dev/null +++ b/proto/deck.proto @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +package continue.v1; + +message DeckTileConfig { + string tile_id = 1; + string label = 2; + string icon = 3; + string action_command = 4; +} + +message DeckLayoutSync { + repeated DeckTileConfig tiles = 1; +} + +message DeckTriggerEvent { + string tile_id = 1; +} + +message DeckAck { + bool success = 1; + string error_message = 2; +} + +message DeckEnvelope { + oneof payload { + DeckLayoutSync layout = 1; + DeckTriggerEvent trigger = 2; + DeckAck ack = 3; + } +} diff --git a/proto/remote_input.proto b/proto/remote_input.proto new file mode 100644 index 0000000..ca54556 --- /dev/null +++ b/proto/remote_input.proto @@ -0,0 +1,24 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +package continue.v1; + +message TextInputChunk { + string text = 1; + bool commit = 2; + uint64 sequence = 3; +} + +message RemoteInputAck { + bool success = 1; + string error_message = 2; +} + +message RemoteInputEnvelope { + oneof payload { + TextInputChunk chunk = 1; + RemoteInputAck ack = 2; + } +} From 88ba12b91f9a347f2a323c6293865f4c64c4ae47 Mon Sep 17 00:00:00 2001 From: Samarth Rajesh Lad <142334685+samyyy2311@users.noreply.github.com> Date: Thu, 8 Oct 2026 13:21:21 +0530 Subject: [PATCH 05/14] feat: add clipboard history, drop folder sync, and remote catalog browsing --- Cargo.lock | 1 + crates/clipboard/Cargo.toml | 1 + crates/clipboard/src/error.rs | 3 + crates/clipboard/src/history.rs | 446 +++++++++++++++++++++ crates/clipboard/src/lib.rs | 2 + crates/limits/src/lib.rs | 14 + crates/protocol/build.rs | 1 + crates/protocol/src/capability.rs | 2 + crates/sessions/src/capabilities_router.rs | 98 +++++ crates/sessions/src/catalog.rs | 313 +++++++++++++++ crates/sessions/src/error.rs | 3 + crates/sessions/src/lib.rs | 9 +- crates/transfer/src/drop_folder.rs | 279 +++++++++++++ crates/transfer/src/lib.rs | 2 + proto/catalog.proto | 55 +++ 15 files changed, 1226 insertions(+), 3 deletions(-) create mode 100644 crates/clipboard/src/history.rs create mode 100644 crates/sessions/src/catalog.rs create mode 100644 crates/transfer/src/drop_folder.rs create mode 100644 proto/catalog.proto diff --git a/Cargo.lock b/Cargo.lock index f52dcd4..105b6dd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -384,6 +384,7 @@ dependencies = [ "protocol", "quinn", "rcgen", + "rusqlite", "rustls", "sha2", "thiserror 1.0.69", diff --git a/crates/clipboard/Cargo.toml b/crates/clipboard/Cargo.toml index a30292f..5d52525 100644 --- a/crates/clipboard/Cargo.toml +++ b/crates/clipboard/Cargo.toml @@ -11,6 +11,7 @@ protocol = { path = "../protocol" } capabilities = { path = "../capabilities" } transport = { path = "../transport" } quinn = { workspace = true } +rusqlite = { workspace = true } sha2 = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true, features = ["net", "sync", "time"] } diff --git a/crates/clipboard/src/error.rs b/crates/clipboard/src/error.rs index 4152b67..8c5052e 100644 --- a/crates/clipboard/src/error.rs +++ b/crates/clipboard/src/error.rs @@ -26,6 +26,9 @@ pub enum ClipboardError { #[error("Clipboard content excluded from synchronization")] SensitiveExcluded, + #[error("Database error: {0}")] + Database(#[from] rusqlite::Error), + #[error("I/O error: {0}")] Io(#[from] std::io::Error), } diff --git a/crates/clipboard/src/history.rs b/crates/clipboard/src/history.rs new file mode 100644 index 0000000..64a9524 --- /dev/null +++ b/crates/clipboard/src/history.rs @@ -0,0 +1,446 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use std::sync::{Arc, Mutex}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use protocol::v1::ClipboardFormat; +use rusqlite::{params, Connection}; + +use crate::error::ClipboardError; +use crate::guard::{evaluate_clipboard_formats, SensitiveGuardDecision}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ClipboardHistoryEntry { + pub id: i64, + pub timestamp_ms: u64, + pub format: ClipboardFormat, + pub content: String, + pub is_pinned: bool, + pub origin_device: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ClipboardSnippet { + pub id: i64, + pub title: String, + pub content: String, + pub shortcut: Option, + pub created_at_ms: u64, +} + +#[derive(Clone)] +pub struct ClipboardHistoryStore { + conn: Arc>, +} + +impl ClipboardHistoryStore { + pub fn open>(path: P) -> Result { + Self::new(Connection::open(path)?) + } + + pub fn in_memory() -> Result { + Self::new(Connection::open_in_memory()?) + } + + fn new(conn: Connection) -> Result { + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS clipboard_history ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + timestamp_ms INTEGER NOT NULL, + format INTEGER NOT NULL, + content TEXT NOT NULL, + is_pinned INTEGER NOT NULL DEFAULT 0, + origin_device TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_clipboard_history_ts ON clipboard_history(timestamp_ms DESC); + CREATE INDEX IF NOT EXISTS idx_clipboard_history_pinned ON clipboard_history(is_pinned); + + CREATE TABLE IF NOT EXISTS clipboard_snippets ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL, + content TEXT NOT NULL, + shortcut TEXT, + created_at_ms INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_clipboard_snippets_shortcut ON clipboard_snippets(shortcut);", + )?; + Ok(Self { + conn: Arc::new(Mutex::new(conn)), + }) + } + + pub fn record_clip( + &self, + format: ClipboardFormat, + content: &str, + origin_device: &str, + available_formats: Option, + ) -> Result, ClipboardError> + where + I: IntoIterator, + S: AsRef, + { + if let Some(formats) = available_formats { + if matches!( + evaluate_clipboard_formats(formats), + SensitiveGuardDecision::DropSensitive + ) { + return Ok(None); + } + } + + if content.is_empty() || format == ClipboardFormat::Unspecified { + return Ok(None); + } + + let format_id = format as i32; + let ts = now_ms(); + let conn = self.conn.lock().unwrap(); + + let mut stmt = conn.prepare( + "SELECT id, content, format, is_pinned FROM clipboard_history ORDER BY id DESC LIMIT 1;", + )?; + let mut rows = stmt.query([])?; + if let Some(row) = rows.next()? { + let last_id: i64 = row.get(0)?; + let last_content: String = row.get(1)?; + let last_format: i32 = row.get(2)?; + let is_pinned: bool = row.get::<_, i64>(3)? != 0; + + if !is_pinned && last_format == format_id && last_content == content { + conn.execute( + "UPDATE clipboard_history SET timestamp_ms = ?1, origin_device = ?2 WHERE id = ?3;", + params![ts as i64, origin_device, last_id], + )?; + return Ok(Some(last_id)); + } + } + + conn.execute( + "INSERT INTO clipboard_history (timestamp_ms, format, content, is_pinned, origin_device) + VALUES (?1, ?2, ?3, 0, ?4);", + params![ts as i64, format_id, content, origin_device], + )?; + Ok(Some(conn.last_insert_rowid())) + } + + pub fn pin_clip(&self, id: i64, pinned: bool) -> Result { + let rows_affected = self.conn.lock().unwrap().execute( + "UPDATE clipboard_history SET is_pinned = ?1 WHERE id = ?2;", + params![if pinned { 1 } else { 0 }, id], + )?; + Ok(rows_affected > 0) + } + + pub fn delete_clip(&self, id: i64) -> Result { + let rows_affected = self + .conn + .lock() + .unwrap() + .execute("DELETE FROM clipboard_history WHERE id = ?1;", params![id])?; + Ok(rows_affected > 0) + } + + pub fn clear_unpinned(&self) -> Result { + let rows_affected = self + .conn + .lock() + .unwrap() + .execute("DELETE FROM clipboard_history WHERE is_pinned = 0;", [])?; + Ok(rows_affected) + } + + pub fn cleanup_expired( + &self, + max_age_ms: u64, + max_unpinned: u32, + ) -> Result { + let now = now_ms(); + let cutoff = now.saturating_sub(max_age_ms); + let conn = self.conn.lock().unwrap(); + + let mut deleted = conn.execute( + "DELETE FROM clipboard_history WHERE is_pinned = 0 AND timestamp_ms < ?1;", + params![cutoff as i64], + )?; + + let mut count_stmt = + conn.prepare("SELECT COUNT(*) FROM clipboard_history WHERE is_pinned = 0;")?; + let unpinned_count: u32 = count_stmt.query_row([], |row| row.get(0))?; + + if unpinned_count > max_unpinned { + let excess = unpinned_count - max_unpinned; + let trimmed = conn.execute( + "DELETE FROM clipboard_history WHERE id IN ( + SELECT id FROM clipboard_history WHERE is_pinned = 0 ORDER BY timestamp_ms ASC LIMIT ?1 + );", + params![excess], + )?; + deleted += trimmed; + } + + Ok(deleted) + } + + pub fn list_clips(&self, limit: u32) -> Result, ClipboardError> { + let conn = self.conn.lock().unwrap(); + let mut stmt = conn.prepare( + "SELECT id, timestamp_ms, format, content, is_pinned, origin_device + FROM clipboard_history ORDER BY is_pinned DESC, timestamp_ms DESC LIMIT ?1;", + )?; + let entries = stmt + .query_map(params![limit], Self::map_entry_row)? + .collect::>()?; + Ok(entries) + } + + pub fn search_clips( + &self, + query: &str, + limit: u32, + ) -> Result, ClipboardError> { + let pattern = format!("%{query}%"); + let conn = self.conn.lock().unwrap(); + let mut stmt = conn.prepare( + "SELECT id, timestamp_ms, format, content, is_pinned, origin_device + FROM clipboard_history + WHERE content LIKE ?1 + ORDER BY is_pinned DESC, timestamp_ms DESC + LIMIT ?2;", + )?; + let entries = stmt + .query_map(params![pattern, limit], Self::map_entry_row)? + .collect::>()?; + Ok(entries) + } + + pub fn add_snippet( + &self, + title: &str, + content: &str, + shortcut: Option<&str>, + ) -> Result { + let ts = now_ms(); + let conn = self.conn.lock().unwrap(); + conn.execute( + "INSERT INTO clipboard_snippets (title, content, shortcut, created_at_ms) + VALUES (?1, ?2, ?3, ?4);", + params![title, content, shortcut, ts as i64], + )?; + Ok(conn.last_insert_rowid()) + } + + pub fn list_snippets(&self) -> Result, ClipboardError> { + let conn = self.conn.lock().unwrap(); + let mut stmt = conn.prepare( + "SELECT id, title, content, shortcut, created_at_ms + FROM clipboard_snippets ORDER BY id ASC;", + )?; + let snippets = stmt + .query_map([], |row| { + Ok(ClipboardSnippet { + id: row.get(0)?, + title: row.get(1)?, + content: row.get(2)?, + shortcut: row.get(3)?, + created_at_ms: row.get::<_, i64>(4)? as u64, + }) + })? + .collect::>()?; + Ok(snippets) + } + + pub fn find_snippet_by_shortcut( + &self, + shortcut: &str, + ) -> Result, ClipboardError> { + let conn = self.conn.lock().unwrap(); + let mut stmt = conn.prepare( + "SELECT id, title, content, shortcut, created_at_ms + FROM clipboard_snippets WHERE shortcut = ?1 LIMIT 1;", + )?; + let mut rows = stmt.query(params![shortcut])?; + if let Some(row) = rows.next()? { + Ok(Some(ClipboardSnippet { + id: row.get(0)?, + title: row.get(1)?, + content: row.get(2)?, + shortcut: row.get(3)?, + created_at_ms: row.get::<_, i64>(4)? as u64, + })) + } else { + Ok(None) + } + } + + pub fn delete_snippet(&self, id: i64) -> Result { + let rows_affected = self + .conn + .lock() + .unwrap() + .execute("DELETE FROM clipboard_snippets WHERE id = ?1;", params![id])?; + Ok(rows_affected > 0) + } + + fn map_entry_row(row: &rusqlite::Row<'_>) -> Result { + let format_raw: i32 = row.get(2)?; + let format = match format_raw { + 1 => ClipboardFormat::TextPlain, + 2 => ClipboardFormat::TextHtml, + 3 => ClipboardFormat::ImagePng, + _ => ClipboardFormat::Unspecified, + }; + Ok(ClipboardHistoryEntry { + id: row.get(0)?, + timestamp_ms: row.get::<_, i64>(1)? as u64, + format, + content: row.get(3)?, + is_pinned: row.get::<_, i64>(4)? != 0, + origin_device: row.get(5)?, + }) + } +} + +fn now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn records_and_lists_clips() { + let store = ClipboardHistoryStore::in_memory().unwrap(); + let id1 = store + .record_clip::<[&str; 0], _>(ClipboardFormat::TextPlain, "first clip", "phone", None) + .unwrap(); + assert!(id1.is_some()); + + let id2 = store + .record_clip::<[&str; 0], _>(ClipboardFormat::TextPlain, "second clip", "pc", None) + .unwrap(); + assert!(id2.is_some()); + + let clips = store.list_clips(10).unwrap(); + assert_eq!(clips.len(), 2); + assert_eq!(clips[0].content, "second clip"); + assert_eq!(clips[1].content, "first clip"); + } + + #[test] + fn sensitive_formats_are_excluded() { + let store = ClipboardHistoryStore::in_memory().unwrap(); + let guard_formats = ["CF_UNICODETEXT", "Clipboard Viewer Ignore"]; + let result = store + .record_clip( + ClipboardFormat::TextPlain, + "super_secret_password", + "pc", + Some(guard_formats.as_slice()), + ) + .unwrap(); + assert_eq!(result, None); + + let clips = store.list_clips(10).unwrap(); + assert!(clips.is_empty()); + } + + #[test] + fn consecutive_duplicate_updates_timestamp() { + let store = ClipboardHistoryStore::in_memory().unwrap(); + let id1 = store + .record_clip::<[&str; 0], _>(ClipboardFormat::TextPlain, "duplicate", "pc", None) + .unwrap() + .unwrap(); + let id2 = store + .record_clip::<[&str; 0], _>(ClipboardFormat::TextPlain, "duplicate", "pc", None) + .unwrap() + .unwrap(); + assert_eq!(id1, id2); + + let clips = store.list_clips(10).unwrap(); + assert_eq!(clips.len(), 1); + } + + #[test] + fn pinning_preserves_across_clear_and_cleanup() { + let store = ClipboardHistoryStore::in_memory().unwrap(); + let _id1 = store + .record_clip::<[&str; 0], _>(ClipboardFormat::TextPlain, "temp clip", "pc", None) + .unwrap() + .unwrap(); + let id2 = store + .record_clip::<[&str; 0], _>(ClipboardFormat::TextPlain, "pinned clip", "pc", None) + .unwrap() + .unwrap(); + + assert!(store.pin_clip(id2, true).unwrap()); + + let removed = store.clear_unpinned().unwrap(); + assert_eq!(removed, 1); + + let remaining = store.list_clips(10).unwrap(); + assert_eq!(remaining.len(), 1); + assert_eq!(remaining[0].id, id2); + assert!(remaining[0].is_pinned); + assert_eq!(remaining[0].content, "pinned clip"); + + // Verify unpinning and deleting + assert!(store.pin_clip(id2, false).unwrap()); + assert!(store.delete_clip(id2).unwrap()); + assert!(store.list_clips(10).unwrap().is_empty()); + } + + #[test] + fn search_clips_filters_by_substring() { + let store = ClipboardHistoryStore::in_memory().unwrap(); + store + .record_clip::<[&str; 0], _>( + ClipboardFormat::TextPlain, + "http://example.com/login", + "phone", + None, + ) + .unwrap(); + store + .record_clip::<[&str; 0], _>( + ClipboardFormat::TextPlain, + "meeting at 3pm", + "phone", + None, + ) + .unwrap(); + + let matches = store.search_clips("example.com", 10).unwrap(); + assert_eq!(matches.len(), 1); + assert_eq!(matches[0].content, "http://example.com/login"); + + let empty = store.search_clips("nonexistent", 10).unwrap(); + assert!(empty.is_empty()); + } + + #[test] + fn snippets_lifecycle_and_shortcut_lookup() { + let store = ClipboardHistoryStore::in_memory().unwrap(); + let snippet_id = store + .add_snippet("Home Address", "123 Main St, Springfield", Some("/addr")) + .unwrap(); + + let list = store.list_snippets().unwrap(); + assert_eq!(list.len(), 1); + assert_eq!(list[0].title, "Home Address"); + + let found = store.find_snippet_by_shortcut("/addr").unwrap(); + assert!(found.is_some()); + let found = found.unwrap(); + assert_eq!(found.content, "123 Main St, Springfield"); + + assert!(store.delete_snippet(snippet_id).unwrap()); + assert!(store.list_snippets().unwrap().is_empty()); + } +} diff --git a/crates/clipboard/src/lib.rs b/crates/clipboard/src/lib.rs index d67e630..58d0862 100644 --- a/crates/clipboard/src/lib.rs +++ b/crates/clipboard/src/lib.rs @@ -4,10 +4,12 @@ pub mod context; pub mod error; pub mod guard; +pub mod history; pub mod sync; pub use context::{classify_context, ContextAction}; pub use error::ClipboardError; pub use guard::{evaluate_clipboard_formats, SensitiveGuardDecision}; +pub use history::{ClipboardHistoryEntry, ClipboardHistoryStore, ClipboardSnippet}; pub use protocol::v1::{ClipboardAck, ClipboardFormat, ClipboardUpdate}; pub use sync::ClipboardSynchronizer; diff --git a/crates/limits/src/lib.rs b/crates/limits/src/lib.rs index 25093f9..5191cbe 100644 --- a/crates/limits/src/lib.rs +++ b/crates/limits/src/lib.rs @@ -102,6 +102,20 @@ pub const MAX_DECK_TILE_ID_BYTES: usize = 128; /// Maximum UTF-8 byte length for a deck tile label. pub const MAX_DECK_LABEL_BYTES: usize = 256; +// File catalog & thumbnails + +/// File catalog query and response message frame size. +pub const MAX_FRAME_CATALOG_BYTES: usize = 256 * 1024; + +/// Thumbnail image response message frame size. +pub const MAX_FRAME_THUMBNAIL_BYTES: usize = 1024 * 1024; + +/// Maximum items returned in a single catalog query page. +pub const MAX_CATALOG_PAGE_SIZE: u32 = 250; + +/// Maximum UTF-8 byte length for a catalog item ID. +pub const MAX_CATALOG_ITEM_ID_BYTES: usize = 128; + // File transfer /// Maximum UTF-8 byte length of a transfer filename. diff --git a/crates/protocol/build.rs b/crates/protocol/build.rs index 74014d4..a619719 100644 --- a/crates/protocol/build.rs +++ b/crates/protocol/build.rs @@ -25,6 +25,7 @@ fn main() { proto_dir.join("pc_control.proto"), proto_dir.join("remote_input.proto"), proto_dir.join("deck.proto"), + proto_dir.join("catalog.proto"), ]; for file in &proto_files { diff --git a/crates/protocol/src/capability.rs b/crates/protocol/src/capability.rs index 1a8f1cb..83146db 100644 --- a/crates/protocol/src/capability.rs +++ b/crates/protocol/src/capability.rs @@ -23,6 +23,7 @@ impl CapabilityId { pub const PC_CONTROL: Self = Self(9); pub const REMOTE_INPUT: Self = Self(10); pub const DECK: Self = Self(11); + pub const FILE_CATALOG: Self = Self(12); pub const fn new(id: u32) -> Self { Self(id) @@ -46,6 +47,7 @@ impl CapabilityId { Self::PC_CONTROL => Some("pc_control"), Self::REMOTE_INPUT => Some("remote_input"), Self::DECK => Some("deck"), + Self::FILE_CATALOG => Some("file_catalog"), _ => None, } } diff --git a/crates/sessions/src/capabilities_router.rs b/crates/sessions/src/capabilities_router.rs index 31189d8..5f36bbd 100644 --- a/crates/sessions/src/capabilities_router.rs +++ b/crates/sessions/src/capabilities_router.rs @@ -13,6 +13,7 @@ use notifications::Body as NotificationBody; use protocol::CapabilityId; use transfer::{receive_file, send_file, ReceivedFile}; +use crate::catalog::CatalogDispatcher; use crate::deck::DeckDispatcher; use crate::device::{PeerDevice, ThisDevice}; use crate::handoff::HandoffDispatcher; @@ -70,6 +71,11 @@ pub type DeckLayoutHandler = Arc protocol::v1::DeckAck + Send + Sync>; pub type DeckTriggerHandler = Arc protocol::v1::DeckAck + Send + Sync>; +pub type CatalogQueryHandler = + Arc protocol::v1::CatalogResponse + Send + Sync>; +pub type ThumbnailRequestHandler = Arc< + dyn Fn(&str, protocol::v1::ThumbnailRequest) -> protocol::v1::ThumbnailResponse + Send + Sync, +>; /// Callbacks and configuration for active capabilities over a multiplexed session. #[derive(Clone)] @@ -83,6 +89,7 @@ pub struct SessionCapabilityHandlers { pub pc_control_dispatcher: Arc, pub remote_input_dispatcher: Arc, pub deck_dispatcher: Arc, + pub catalog_dispatcher: Arc, pub on_file_received: Option>, pub on_clipboard_received: Option>, /// Called with notifications the peer shows here, and with replies to and dismissals of @@ -98,6 +105,8 @@ pub struct SessionCapabilityHandlers { pub on_remote_input: Option, pub on_deck_layout_synced: Option, pub on_deck_tile_triggered: Option, + pub on_catalog_query: Option, + pub on_thumbnail_request: Option, /// How this device introduces itself to peers. pub this_device: ThisDevice, /// Called with what a peer says about itself each time a session starts. @@ -123,6 +132,7 @@ impl SessionCapabilityHandlers { pc_control_dispatcher: Arc::new(PcControlDispatcher::new()), remote_input_dispatcher: Arc::new(RemoteInputDispatcher::new()), deck_dispatcher: Arc::new(DeckDispatcher::new()), + catalog_dispatcher: Arc::new(CatalogDispatcher::new()), on_file_received: None, on_clipboard_received: None, on_notification: None, @@ -136,6 +146,8 @@ impl SessionCapabilityHandlers { on_remote_input: None, on_deck_layout_synced: None, on_deck_tile_triggered: None, + on_catalog_query: None, + on_thumbnail_request: None, this_device: ThisDevice::default(), on_device_info: None, on_device_status: None, @@ -674,6 +686,60 @@ pub fn spawn_capabilities_dispatcher( error!("Failed to process deck stream from {peer_fp}: {e}"); } } + CapabilityId::FILE_CATALOG => { + debug!("Handling incoming file catalog stream from {peer_fp}"); + let is_permitted = + permitted(&handlers, &peer_fp, CapabilityId::FILE_CATALOG, None).await; + + if is_permitted { + if let Some(store) = &handlers.permission_store { + store.consume_if_allow_once(&peer_fp, CapabilityId::FILE_CATALOG); + } + } + + let query = + CapabilityQuery::negotiated(CapabilityId::FILE_CATALOG, is_permitted); + + let on_query = handlers.on_catalog_query.clone(); + let on_thumb = handlers.on_thumbnail_request.clone(); + let peer = peer_fp.clone(); + + let result = handlers + .catalog_dispatcher + .receive_envelope( + &mut stream.send_stream, + &mut stream.recv_stream, + &query, + |q| { + if let Some(ref cb) = on_query { + cb(&peer, q) + } else { + protocol::v1::CatalogResponse { + items: Vec::new(), + total_count: 0, + } + } + }, + |req| { + if let Some(ref cb) = on_thumb { + cb(&peer, req) + } else { + protocol::v1::ThumbnailResponse { + item_id: req.item_id, + image_data: Vec::new(), + mime_type: String::new(), + success: false, + error_message: "Thumbnail requests not handled".into(), + } + } + }, + ) + .await; + + if let Err(e) = result { + error!("Failed to process file catalog stream from {peer_fp}: {e}"); + } + } unknown => { debug!("Received unsupported capability stream {unknown:?} from {peer_fp}"); } @@ -842,4 +908,36 @@ impl SessionMultiplexer { .trigger_tile(&mut send, &mut recv, trigger, query) .await } + + pub async fn query_file_catalog_from_peer( + &self, + query: protocol::v1::CatalogQuery, + capability_query: &CapabilityQuery, + ) -> Result { + let (mut send, mut recv) = self + .open_stream(CapabilityId::FILE_CATALOG) + .await + .map_err(crate::error::SessionError::Transport)?; + + let dispatcher = CatalogDispatcher::new(); + dispatcher + .query_catalog(&mut send, &mut recv, query, capability_query) + .await + } + + pub async fn request_thumbnail_from_peer( + &self, + req: protocol::v1::ThumbnailRequest, + capability_query: &CapabilityQuery, + ) -> Result { + let (mut send, mut recv) = self + .open_stream(CapabilityId::FILE_CATALOG) + .await + .map_err(crate::error::SessionError::Transport)?; + + let dispatcher = CatalogDispatcher::new(); + dispatcher + .request_thumbnail(&mut send, &mut recv, req, capability_query) + .await + } } diff --git a/crates/sessions/src/catalog.rs b/crates/sessions/src/catalog.rs new file mode 100644 index 0000000..7f0b234 --- /dev/null +++ b/crates/sessions/src/catalog.rs @@ -0,0 +1,313 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use capabilities::{evaluate_capability, CapabilityQuery}; +use limits::{ + MAX_CATALOG_ITEM_ID_BYTES, MAX_CATALOG_PAGE_SIZE, MAX_FRAME_CATALOG_BYTES, + MAX_FRAME_THUMBNAIL_BYTES, +}; +use protocol::v1::{ + catalog_envelope::Payload, CatalogEnvelope, CatalogQuery, CatalogResponse, ThumbnailRequest, + ThumbnailResponse, +}; +use transport::{read_msg, write_msg}; + +use crate::error::SessionError; + +#[derive(Default, Clone)] +pub struct CatalogDispatcher; + +impl CatalogDispatcher { + pub fn new() -> Self { + Self + } + + pub fn validate_query(query: &CatalogQuery) -> Result<(), SessionError> { + if query.limit > MAX_CATALOG_PAGE_SIZE { + return Err(SessionError::CatalogValidation(format!( + "Catalog query limit {} exceeds maximum page size of {}", + query.limit, MAX_CATALOG_PAGE_SIZE + ))); + } + Ok(()) + } + + pub fn validate_thumbnail_request(req: &ThumbnailRequest) -> Result<(), SessionError> { + if req.item_id.is_empty() { + return Err(SessionError::CatalogValidation( + "Thumbnail item ID cannot be empty".into(), + )); + } + + if req.item_id.len() > MAX_CATALOG_ITEM_ID_BYTES { + return Err(SessionError::CatalogValidation(format!( + "Thumbnail item ID length {} exceeds maximum allowed of {} bytes", + req.item_id.len(), + MAX_CATALOG_ITEM_ID_BYTES + ))); + } + + Ok(()) + } + + /// Sends a catalog query request and awaits the remote peer's catalog response. + pub async fn query_catalog( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + query: CatalogQuery, + capability_query: &CapabilityQuery, + ) -> Result { + evaluate_capability(capability_query)?; + Self::validate_query(&query)?; + + let envelope = CatalogEnvelope { + payload: Some(Payload::Query(query)), + }; + + write_msg(send_stream, &envelope, MAX_FRAME_CATALOG_BYTES).await?; + let resp_env: CatalogEnvelope = read_msg(recv_stream, MAX_FRAME_CATALOG_BYTES).await?; + + match resp_env.payload { + Some(Payload::Response(resp)) => Ok(resp), + _ => Err(SessionError::UnexpectedMessage), + } + } + + /// Sends a thumbnail request and awaits the remote peer's thumbnail response. + pub async fn request_thumbnail( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + req: ThumbnailRequest, + capability_query: &CapabilityQuery, + ) -> Result { + evaluate_capability(capability_query)?; + Self::validate_thumbnail_request(&req)?; + + let envelope = CatalogEnvelope { + payload: Some(Payload::ThumbReq(req)), + }; + + write_msg(send_stream, &envelope, MAX_FRAME_CATALOG_BYTES).await?; + let resp_env: CatalogEnvelope = read_msg(recv_stream, MAX_FRAME_THUMBNAIL_BYTES).await?; + + match resp_env.payload { + Some(Payload::ThumbResp(resp)) => Ok(resp), + _ => Err(SessionError::UnexpectedMessage), + } + } + + /// Receives a catalog envelope, delegates to query or thumbnail handler, and replies. + pub async fn receive_envelope( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + capability_query: &CapabilityQuery, + mut on_query: Q, + mut on_thumb: T, + ) -> Result + where + Q: FnMut(CatalogQuery) -> CatalogResponse, + T: FnMut(ThumbnailRequest) -> ThumbnailResponse, + { + evaluate_capability(capability_query)?; + + let envelope: CatalogEnvelope = read_msg(recv_stream, MAX_FRAME_CATALOG_BYTES).await?; + + match envelope.payload { + Some(Payload::Query(ref query)) => { + Self::validate_query(query)?; + let resp = on_query(*query); + let resp_env = CatalogEnvelope { + payload: Some(Payload::Response(resp)), + }; + write_msg(send_stream, &resp_env, MAX_FRAME_CATALOG_BYTES).await?; + Ok(envelope) + } + Some(Payload::ThumbReq(ref req)) => { + Self::validate_thumbnail_request(req)?; + let resp = on_thumb(req.clone()); + let resp_env = CatalogEnvelope { + payload: Some(Payload::ThumbResp(resp)), + }; + write_msg(send_stream, &resp_env, MAX_FRAME_THUMBNAIL_BYTES).await?; + Ok(envelope) + } + Some(Payload::Response(_)) | Some(Payload::ThumbResp(_)) | None => { + Err(SessionError::UnexpectedMessage) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use protocol::v1::{CatalogCategory, CatalogItem}; + use protocol::CapabilityId; + use transport::{create_client_endpoint, create_server_endpoint, TransportCertificate}; + + #[tokio::test] + async fn catalog_query_roundtrip() { + let server_cert = TransportCertificate::generate().unwrap(); + let client_cert = TransportCertificate::generate().unwrap(); + + let server_tls = server_cert + .build_pinned_server_tls(client_cert.spki_hash) + .unwrap(); + let client_tls = client_cert + .build_pinned_client_tls(server_cert.spki_hash) + .unwrap(); + + let server_ep = create_server_endpoint("127.0.0.1:0".parse().unwrap(), server_tls).unwrap(); + let server_addr = server_ep.local_addr().unwrap(); + let client_ep = create_client_endpoint("0.0.0.0:0".parse().unwrap(), client_tls).unwrap(); + + let server_task = tokio::spawn(async move { + server_ep.wait_idle().await; + let conn = server_ep.accept().await.unwrap().await.unwrap(); + let (mut send, mut recv) = conn.accept_bi().await.unwrap(); + + let query = CapabilityQuery::negotiated(CapabilityId::FILE_CATALOG, true); + let dispatcher = CatalogDispatcher::new(); + let result = dispatcher + .receive_envelope( + &mut send, + &mut recv, + &query, + |q| { + assert_eq!(q.category, CatalogCategory::Photos as i32); + CatalogResponse { + items: vec![CatalogItem { + item_id: "photo_001".into(), + file_name: "sunset.jpg".into(), + size_bytes: 2048576, + timestamp: 1700000000, + mime_type: "image/jpeg".into(), + }], + total_count: 1, + } + }, + |_| panic!("Unexpected thumbnail request"), + ) + .await; + (result, conn) + }); + + let conn = client_ep + .connect(server_addr, "localhost") + .unwrap() + .await + .unwrap(); + let (mut send, mut recv) = conn.open_bi().await.unwrap(); + + let query = CapabilityQuery::negotiated(CapabilityId::FILE_CATALOG, true); + let dispatcher = CatalogDispatcher::new(); + let response = dispatcher + .query_catalog( + &mut send, + &mut recv, + CatalogQuery { + category: CatalogCategory::Photos as i32, + limit: 50, + offset: 0, + }, + &query, + ) + .await + .unwrap(); + + assert_eq!(response.items.len(), 1); + assert_eq!(response.items[0].file_name, "sunset.jpg"); + assert_eq!(response.items[0].size_bytes, 2048576); + + let (server_res, _conn) = server_task.await.unwrap(); + assert!(server_res.is_ok()); + } + + #[tokio::test] + async fn thumbnail_request_roundtrip() { + let server_cert = TransportCertificate::generate().unwrap(); + let client_cert = TransportCertificate::generate().unwrap(); + + let server_tls = server_cert + .build_pinned_server_tls(client_cert.spki_hash) + .unwrap(); + let client_tls = client_cert + .build_pinned_client_tls(server_cert.spki_hash) + .unwrap(); + + let server_ep = create_server_endpoint("127.0.0.1:0".parse().unwrap(), server_tls).unwrap(); + let server_addr = server_ep.local_addr().unwrap(); + let client_ep = create_client_endpoint("0.0.0.0:0".parse().unwrap(), client_tls).unwrap(); + + let server_task = tokio::spawn(async move { + server_ep.wait_idle().await; + let conn = server_ep.accept().await.unwrap().await.unwrap(); + let (mut send, mut recv) = conn.accept_bi().await.unwrap(); + + let query = CapabilityQuery::negotiated(CapabilityId::FILE_CATALOG, true); + let dispatcher = CatalogDispatcher::new(); + let result = dispatcher + .receive_envelope( + &mut send, + &mut recv, + &query, + |_| panic!("Unexpected catalog query"), + |req| { + assert_eq!(req.item_id, "photo_001"); + ThumbnailResponse { + item_id: req.item_id, + image_data: vec![0xFF, 0xD8, 0xFF, 0xE0], + mime_type: "image/jpeg".into(), + success: true, + error_message: String::new(), + } + }, + ) + .await; + (result, conn) + }); + + let conn = client_ep + .connect(server_addr, "localhost") + .unwrap() + .await + .unwrap(); + let (mut send, mut recv) = conn.open_bi().await.unwrap(); + + let query = CapabilityQuery::negotiated(CapabilityId::FILE_CATALOG, true); + let dispatcher = CatalogDispatcher::new(); + let response = dispatcher + .request_thumbnail( + &mut send, + &mut recv, + ThumbnailRequest { + item_id: "photo_001".into(), + max_dimension: 256, + }, + &query, + ) + .await + .unwrap(); + + assert!(response.success); + assert_eq!(response.item_id, "photo_001"); + assert_eq!(response.image_data, vec![0xFF, 0xD8, 0xFF, 0xE0]); + + let (server_res, _conn) = server_task.await.unwrap(); + assert!(server_res.is_ok()); + } + + #[tokio::test] + async fn catalog_validation_rejects_oversized_limit() { + let query = CatalogQuery { + category: CatalogCategory::Unspecified as i32, + limit: MAX_CATALOG_PAGE_SIZE + 10, + offset: 0, + }; + let err = CatalogDispatcher::validate_query(&query).unwrap_err(); + assert!(matches!(err, SessionError::CatalogValidation(_))); + } +} diff --git a/crates/sessions/src/error.rs b/crates/sessions/src/error.rs index 648f914..b1346e6 100644 --- a/crates/sessions/src/error.rs +++ b/crates/sessions/src/error.rs @@ -40,4 +40,7 @@ pub enum SessionError { #[error("Deck validation failed: {0}")] DeckValidation(String), + + #[error("Catalog validation failed: {0}")] + CatalogValidation(String), } diff --git a/crates/sessions/src/lib.rs b/crates/sessions/src/lib.rs index 42c033f..cb13845 100644 --- a/crates/sessions/src/lib.rs +++ b/crates/sessions/src/lib.rs @@ -4,6 +4,7 @@ pub mod auto_connect; pub mod backoff; pub mod capabilities_router; +pub mod catalog; pub mod deck; pub mod device; pub mod error; @@ -24,10 +25,12 @@ pub mod telemetry; pub use auto_connect::connect_paired_peers; pub use backoff::ReconnectPolicy; pub use capabilities_router::{ - spawn_capabilities_dispatcher, DeckLayoutHandler, DeckTriggerHandler, MediaCommandHandler, - OnReceived, PcActionHandler, PermissionDecision, PermissionPrompt, PermissionRequest, - RemoteInputHandler, RingHandler, SessionCapabilityHandlers, PROMPT_TIMEOUT, + spawn_capabilities_dispatcher, CatalogQueryHandler, DeckLayoutHandler, DeckTriggerHandler, + MediaCommandHandler, OnReceived, PcActionHandler, PermissionDecision, PermissionPrompt, + PermissionRequest, RemoteInputHandler, RingHandler, SessionCapabilityHandlers, + ThumbnailRequestHandler, PROMPT_TIMEOUT, }; +pub use catalog::CatalogDispatcher; pub use deck::DeckDispatcher; pub use device::{clean_name, this_platform, PeerDevice, ThisDevice}; pub use error::SessionError; diff --git a/crates/transfer/src/drop_folder.rs b/crates/transfer/src/drop_folder.rs new file mode 100644 index 0000000..d3f156d --- /dev/null +++ b/crates/transfer/src/drop_folder.rs @@ -0,0 +1,279 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use std::collections::HashMap; +use std::fs; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant, SystemTime}; + +use crate::error::TransferError; +use crate::queue::{OfflineTransferQueue, QueuedPayload, QueuedTransfer}; + +#[derive(Debug, Clone)] +pub struct DropFolderConfig { + pub watch_dir: PathBuf, + pub target_peer: String, + pub debounce_duration: Duration, + pub delete_after_enqueue: bool, +} + +impl DropFolderConfig { + pub fn new(watch_dir: PathBuf, target_peer: impl Into) -> Self { + Self { + watch_dir, + target_peer: target_peer.into(), + debounce_duration: Duration::from_millis(500), + delete_after_enqueue: false, + } + } +} + +pub fn is_ignorable_file(file_name: &str) -> bool { + if file_name.starts_with('.') || file_name.starts_with("~$") { + return true; + } + + let lower = file_name.to_ascii_lowercase(); + const IGNORED_EXTENSIONS: &[&str] = &[ + ".tmp", + ".crdownload", + ".part", + ".partial", + ".download", + ".swp", + ".bak", + ]; + + IGNORED_EXTENSIONS.iter().any(|ext| lower.ends_with(ext)) +} + +pub fn guess_mime_type(file_name: &str) -> Option { + let lower = file_name.to_ascii_lowercase(); + if lower.ends_with(".jpg") || lower.ends_with(".jpeg") { + Some("image/jpeg".to_string()) + } else if lower.ends_with(".png") { + Some("image/png".to_string()) + } else if lower.ends_with(".gif") { + Some("image/gif".to_string()) + } else if lower.ends_with(".webp") { + Some("image/webp".to_string()) + } else if lower.ends_with(".pdf") { + Some("application/pdf".to_string()) + } else if lower.ends_with(".txt") { + Some("text/plain".to_string()) + } else if lower.ends_with(".mp4") { + Some("video/mp4".to_string()) + } else if lower.ends_with(".zip") { + Some("application/zip".to_string()) + } else { + None + } +} + +#[derive(Debug, Clone)] +struct TrackedFile { + last_size: u64, + last_modified: SystemTime, + last_change: Instant, + enqueued: bool, +} + +pub struct DropFolderWatcher { + config: DropFolderConfig, + queue: Arc, + tracked: Mutex>, +} + +impl DropFolderWatcher { + pub fn new(config: DropFolderConfig, queue: Arc) -> Self { + Self { + config, + queue, + tracked: Mutex::new(HashMap::new()), + } + } + + pub fn scan_directory(&self) -> Result, TransferError> { + let watch_dir = &self.config.watch_dir; + if !watch_dir.exists() { + return Ok(Vec::new()); + } + + let entries = fs::read_dir(watch_dir)?; + let mut now_seen_paths = Vec::new(); + let mut newly_enqueued = Vec::new(); + let now = Instant::now(); + + let mut tracked = self.tracked.lock().unwrap(); + + for entry_res in entries { + let entry = entry_res?; + let path = entry.path(); + + if !path.is_file() { + continue; + } + + let file_name = match path.file_name().and_then(|n| n.to_str()) { + Some(name) => name.to_string(), + None => continue, + }; + + if is_ignorable_file(&file_name) { + continue; + } + + let metadata = match fs::metadata(&path) { + Ok(m) => m, + Err(_) => continue, + }; + + let size = metadata.len(); + let modified = metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH); + + now_seen_paths.push(path.clone()); + + let entry_state = tracked.entry(path.clone()).or_insert_with(|| TrackedFile { + last_size: size, + last_modified: modified, + last_change: now, + enqueued: false, + }); + + if entry_state.last_size != size || entry_state.last_modified != modified { + entry_state.last_size = size; + entry_state.last_modified = modified; + entry_state.last_change = now; + continue; + } + + if !entry_state.enqueued + && now.duration_since(entry_state.last_change) >= self.config.debounce_duration + { + let mime_type = guess_mime_type(&file_name); + let payload = QueuedPayload::File { + path: path.clone(), + relative_name: file_name, + mime_type, + }; + + let item_id = self.queue.enqueue(&self.config.target_peer, payload)?; + entry_state.enqueued = true; + newly_enqueued.push(QueuedTransfer { + id: item_id, + peer_fingerprint: self.config.target_peer.clone(), + payload: QueuedPayload::File { + path: path.clone(), + relative_name: path.file_name().unwrap().to_string_lossy().into_owned(), + mime_type: guess_mime_type(&path.file_name().unwrap().to_string_lossy()), + }, + queued_at: SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0), + }); + + if self.config.delete_after_enqueue { + let _ = fs::remove_file(&path); + } + } + } + + tracked.retain(|p, _| now_seen_paths.contains(p)); + + Ok(newly_enqueued) + } + + pub async fn run_polling( + self: Arc, + poll_interval: Duration, + mut stop_rx: tokio::sync::watch::Receiver, + ) { + let mut interval = tokio::time::interval(poll_interval); + loop { + tokio::select! { + _ = interval.tick() => { + let _ = self.scan_directory(); + } + changed = stop_rx.changed() => { + if changed.is_err() || *stop_rx.borrow() { + break; + } + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct TestDir { + path: PathBuf, + } + + impl TestDir { + fn new(name: &str) -> Self { + let path = std::env::temp_dir().join(format!( + "continue_test_{}_{}", + name, + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let _ = fs::create_dir_all(&path); + Self { path } + } + } + + impl Drop for TestDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + #[test] + fn ignorable_files_filtered() { + assert!(is_ignorable_file(".hidden")); + assert!(is_ignorable_file(".DS_Store")); + assert!(is_ignorable_file("~$doc.docx")); + assert!(is_ignorable_file("large.iso.crdownload")); + assert!(is_ignorable_file("download.part")); + assert!(is_ignorable_file("temp_file.tmp")); + assert!(!is_ignorable_file("vacation.jpg")); + assert!(!is_ignorable_file("document.pdf")); + } + + #[test] + fn debounces_and_enqueues_stable_file() { + let dir = TestDir::new("drop_debounce"); + let queue = Arc::new(OfflineTransferQueue::with_capacities(10, 100)); + let mut config = DropFolderConfig::new(dir.path.clone(), "pixel_phone"); + config.debounce_duration = Duration::from_millis(100); + + let watcher = DropFolderWatcher::new(config, queue.clone()); + + let file_path = dir.path.join("report.pdf"); + fs::write(&file_path, b"Test content for file transfer").unwrap(); + + // Immediate scan before debounce elapsed should not enqueue yet + let enqueued_first = watcher.scan_directory().unwrap(); + assert!(enqueued_first.is_empty()); + assert_eq!(queue.peek_for_peer("pixel_phone").len(), 0); + + // Wait for debounce period to pass + std::thread::sleep(Duration::from_millis(150)); + + let enqueued_second = watcher.scan_directory().unwrap(); + assert_eq!(enqueued_second.len(), 1); + assert_eq!(queue.peek_for_peer("pixel_phone").len(), 1); + + // Subsequent scan does not duplicate enqueue + let enqueued_third = watcher.scan_directory().unwrap(); + assert!(enqueued_third.is_empty()); + assert_eq!(queue.peek_for_peer("pixel_phone").len(), 1); + } +} diff --git a/crates/transfer/src/lib.rs b/crates/transfer/src/lib.rs index decebff..9b23184 100644 --- a/crates/transfer/src/lib.rs +++ b/crates/transfer/src/lib.rs @@ -4,6 +4,7 @@ //! Streaming file transfer, one QUIC stream per file. pub mod capture; +pub mod drop_folder; pub mod error; pub mod localsend_bridge; mod partial; @@ -16,6 +17,7 @@ pub use capture::{ format_as_clipboard_dibv5, request_camera_capture, respond_camera_capture, CameraCaptureSource, CapturedMedia, }; +pub use drop_folder::{guess_mime_type, is_ignorable_file, DropFolderConfig, DropFolderWatcher}; pub use error::TransferError; pub use localsend_bridge::{ LocalSendActiveSession, LocalSendBridgeSessionManager, LocalSendFileMetadata, diff --git a/proto/catalog.proto b/proto/catalog.proto new file mode 100644 index 0000000..d1f3bef --- /dev/null +++ b/proto/catalog.proto @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +package continue.v1; + +enum CatalogCategory { + CATALOG_CATEGORY_UNSPECIFIED = 0; + CATALOG_CATEGORY_PHOTOS = 1; + CATALOG_CATEGORY_SCREENSHOTS = 2; + CATALOG_CATEGORY_DOWNLOADS = 3; + CATALOG_CATEGORY_DOCUMENTS = 4; +} + +message CatalogQuery { + CatalogCategory category = 1; + uint32 limit = 2; + uint32 offset = 3; +} + +message CatalogItem { + string item_id = 1; + string file_name = 2; + uint64 size_bytes = 3; + uint64 timestamp = 4; + string mime_type = 5; +} + +message CatalogResponse { + repeated CatalogItem items = 1; + uint32 total_count = 2; +} + +message ThumbnailRequest { + string item_id = 1; + uint32 max_dimension = 2; +} + +message ThumbnailResponse { + string item_id = 1; + bytes image_data = 2; + string mime_type = 3; + bool success = 4; + string error_message = 5; +} + +message CatalogEnvelope { + oneof payload { + CatalogQuery query = 1; + CatalogResponse response = 2; + ThumbnailRequest thumb_req = 3; + ThumbnailResponse thumb_resp = 4; + } +} From 0b6b8d97af710f886a501504d07bc842ddeae638 Mon Sep 17 00:00:00 2001 From: Samarth Rajesh Lad <142334685+samyyy2311@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:21:20 +0530 Subject: [PATCH 06/14] chore: replace legacy em dashes with standard punctuation across crates --- crates/crypto/src/pairing.rs | 2 +- crates/identity/src/fingerprint.rs | 2 +- crates/limits/src/lib.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/crypto/src/pairing.rs b/crates/crypto/src/pairing.rs index f631c44..d862c3b 100644 --- a/crates/crypto/src/pairing.rs +++ b/crates/crypto/src/pairing.rs @@ -15,7 +15,7 @@ use crate::error::CryptoError; type HmacSha256 = Hmac; -// Domain separators — ASCII, fixed length, version-tagged. +// Domain separators: ASCII, fixed length, version-tagged. // Role separation prevents reflection attacks. const DOMAIN_INIT: &[u8] = b"PAIRING_V1_INIT"; const DOMAIN_RESP: &[u8] = b"PAIRING_V1_RESP"; diff --git a/crates/identity/src/fingerprint.rs b/crates/identity/src/fingerprint.rs index be0738f..888c935 100644 --- a/crates/identity/src/fingerprint.rs +++ b/crates/identity/src/fingerprint.rs @@ -7,7 +7,7 @@ //! It is 43 characters long and URL-safe. //! //! The fingerprint is used in the trust store and logs. Full fingerprints -//! are never logged by default — use `Fingerprint::diagnostic()` for log output. +//! are never logged by default; use `Fingerprint::diagnostic()` for log output. use std::fmt; diff --git a/crates/limits/src/lib.rs b/crates/limits/src/lib.rs index 5191cbe..4fd8d93 100644 --- a/crates/limits/src/lib.rs +++ b/crates/limits/src/lib.rs @@ -27,7 +27,7 @@ pub const MAX_DEVICE_NAME_BYTES: usize = 64; /// Byte length of the pairing session token. /// -/// Distinct from SHA256_DIGEST_LEN — this is 16 bytes, not 32. +/// Distinct from SHA256_DIGEST_LEN: this is 16 bytes, not 32. pub const SESSION_TOKEN_LEN: usize = 16; /// Maximum active pairing session lifetime in seconds. From ac5005358d6e549141c9e5e2a64b0201bfec669c Mon Sep 17 00:00:00 2001 From: Samarth Rajesh Lad <142334685+samyyy2311@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:43:17 +0530 Subject: [PATCH 07/14] feat: add Windows Cloud Files API placeholder sync root engine --- crates/transfer/src/cloud_files.rs | 1096 +++++++++++++++++++++ crates/transfer/src/error.rs | 6 + crates/transfer/src/lib.rs | 4 + crates/transfer/tests/cloud_files_test.rs | 87 ++ 4 files changed, 1193 insertions(+) create mode 100644 crates/transfer/src/cloud_files.rs create mode 100644 crates/transfer/tests/cloud_files_test.rs diff --git a/crates/transfer/src/cloud_files.rs b/crates/transfer/src/cloud_files.rs new file mode 100644 index 0000000..3c2c409 --- /dev/null +++ b/crates/transfer/src/cloud_files.rs @@ -0,0 +1,1096 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +//! Windows Cloud Files API (Cloud Filter API / cldapi) integration. +//! +//! Mounts remote phone catalogs into Windows File Explorer as native cloud placeholders. +//! Placeholders show file names, sizes, and cloud sync icons with zero physical disk usage +//! until hydrated on-demand when opened or copied by the user. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use crate::error::TransferError; + +/// Configuration for a cloud files sync root. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CloudFilesConfig { + /// Local directory where placeholder files will be placed. + pub sync_root_path: PathBuf, + /// Human-readable provider name shown in File Explorer (e.g. "Continue"). + pub provider_name: String, + /// Provider version string. + pub provider_version: String, + /// Name of the paired phone (e.g. "Pixel 8"). + pub device_name: String, + /// Unique identifier for the paired phone. + pub device_id: String, +} + +impl CloudFilesConfig { + pub fn new>( + sync_root_path: P, + provider_name: impl Into, + device_name: impl Into, + device_id: impl Into, + ) -> Self { + Self { + sync_root_path: sync_root_path.into(), + provider_name: provider_name.into(), + provider_version: "1.0.0".to_string(), + device_name: device_name.into(), + device_id: device_id.into(), + } + } +} + +/// Metadata describing a remote item to present as a local placeholder. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CloudFilesEntry { + /// Relative path inside the sync root (e.g. "Photos/vacation.jpg"). + pub relative_path: PathBuf, + /// Size of the file in bytes (0 for directories). + pub file_size: u64, + /// Whether this entry represents a directory. + pub is_directory: bool, + /// Creation or modification timestamp in milliseconds since UNIX epoch. + pub modified_time_ms: u64, + /// Remote identifier used to request content from the peer. + pub file_identity: Vec, +} + +impl CloudFilesEntry { + pub fn file>( + relative_path: P, + file_size: u64, + modified_time_ms: u64, + file_identity: impl Into>, + ) -> Self { + Self { + relative_path: relative_path.into(), + file_size, + is_directory: false, + modified_time_ms, + file_identity: file_identity.into(), + } + } + + pub fn directory>( + relative_path: P, + modified_time_ms: u64, + file_identity: impl Into>, + ) -> Self { + Self { + relative_path: relative_path.into(), + file_size: 0, + is_directory: true, + modified_time_ms, + file_identity: file_identity.into(), + } + } +} + +/// Request passed to the fetch data callback when Windows needs file content. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FetchDataRequest { + /// Remote identifier specified when creating the placeholder. + pub file_identity: Vec, + /// Relative path within the sync root. + pub relative_path: PathBuf, + /// Byte offset requested by the reading process. + pub offset: u64, + /// Number of bytes requested. + pub length: u64, +} + +/// Hydration state of a placeholder file on disk. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HydrationState { + /// Placeholder exists on disk but contains no data (cloud icon). + Unhydrated, + /// File content is partially cached locally. + PartiallyHydrated, + /// Full file content is cached locally (green checkmark). + FullyHydrated, + /// Path does not exist or is not a cloud placeholder. + NotAPlaceholder, +} + +#[cfg(windows)] +#[allow(clippy::upper_case_acronyms)] +mod win32 { + use std::ffi::c_void; + + pub type HRESULT = i32; + pub const S_OK: HRESULT = 0; + + #[repr(C)] + #[derive(Copy, Clone, Default)] + pub struct GUID { + pub data1: u32, + pub data2: u16, + pub data3: u16, + pub data4: [u8; 8], + } + + #[repr(C)] + pub struct CF_SYNC_REGISTRATION { + pub struct_size: u32, + pub provider_name: *const u16, + pub provider_version: *const u16, + pub sync_root_identity: *const c_void, + pub sync_root_identity_length: u32, + pub file_identity: *const c_void, + pub file_identity_length: u32, + pub provider_id: GUID, + } + + #[repr(C)] + #[derive(Copy, Clone)] + pub struct CF_HYDRATION_POLICY { + pub primary: u16, + pub modifier: u16, + } + + #[repr(C)] + #[derive(Copy, Clone)] + pub struct CF_POPULATION_POLICY { + pub primary: u16, + pub modifier: u16, + } + + #[repr(C)] + pub struct CF_SYNC_POLICIES { + pub struct_size: u32, + pub hydration: CF_HYDRATION_POLICY, + pub population: CF_POPULATION_POLICY, + pub in_sync: u32, + pub hard_link: u32, + pub placeholder_management: u32, + } + + pub const CF_HYDRATION_POLICY_PRIMARY_PARTIAL: u16 = 0; + pub const CF_POPULATION_POLICY_PRIMARY_PARTIAL: u16 = 0; + pub const CF_INSYNC_POLICY_NONE: u32 = 0; + pub const CF_HARDLINK_POLICY_NONE: u32 = 0; + pub const CF_PLACEHOLDER_MANAGEMENT_POLICY_DEFAULT: u32 = 0; + + pub const CF_REGISTER_FLAG_UPDATE: u32 = 1; + pub const CF_CONNECT_FLAG_REQUIRE_FULL_FILE_PATH: u32 = 2; + + pub const CF_CALLBACK_TYPE_FETCH_DATA: u32 = 0; + pub const CF_CALLBACK_TYPE_CANCEL_FETCH_DATA: u32 = 2; + pub const CF_CALLBACK_TYPE_NONE: u32 = 0xFFFFFFFF; + + #[repr(C)] + pub struct CF_CALLBACK_INFO { + pub struct_size: u32, + pub connection_key: i64, + pub callback_context: *mut c_void, + pub volume_guid_name: *const u16, + pub volume_dos_name: *const u16, + pub volume_serial_number: u32, + pub sync_root_file_id: i64, + pub sync_root_identity: *const c_void, + pub sync_root_identity_length: u32, + pub file_id: i64, + pub file_size: i64, + pub file_identity: *const c_void, + pub file_identity_length: u32, + pub normalized_path: *const u16, + pub transfer_key: i64, + pub priority_hint: u8, + pub correlation_vector: *const c_void, + pub process_info: *const c_void, + pub request_key: i64, + } + + #[repr(C)] + pub struct CF_CALLBACK_PARAMETERS { + pub param_size: u32, + pub required_file_offset: i64, + pub required_length: i64, + pub optional_file_offset: i64, + pub optional_length: i64, + pub last_dehydration_time: i64, + pub last_dehydration_reason: u32, + } + + pub type CfCallbackFn = unsafe extern "system" fn( + callback_info: *const CF_CALLBACK_INFO, + callback_parameters: *const c_void, + ); + + #[repr(C)] + pub struct CF_CALLBACK_REGISTRATION { + pub callback_type: u32, + pub callback: Option, + } + + #[repr(C)] + #[derive(Copy, Clone, Default)] + pub struct FILE_BASIC_INFO { + pub creation_time: i64, + pub last_access_time: i64, + pub last_write_time: i64, + pub change_time: i64, + pub file_attributes: u32, + } + + #[repr(C)] + pub struct CF_FS_METADATA { + pub basic_info: FILE_BASIC_INFO, + pub file_size: i64, + } + + #[repr(C)] + pub struct CF_PLACEHOLDER_CREATE_INFO { + pub relative_file_name: *const u16, + pub fs_metadata: CF_FS_METADATA, + pub file_identity: *const c_void, + pub file_identity_length: u32, + pub flags: u32, + pub result: HRESULT, + pub create_usn: i64, + } + + pub const CF_PLACEHOLDER_CREATE_FLAG_MARK_IN_SYNC: u32 = 4; + pub const CF_CREATE_FLAG_NONE: u32 = 0; + + pub const CF_OPERATION_TYPE_TRANSFER_DATA: u32 = 0; + + #[repr(C)] + #[derive(Copy, Clone)] + pub struct CF_OPERATION_TRANSFER_DATA { + pub flags: u32, + pub completion_status: HRESULT, + pub buffer: *const c_void, + pub offset: i64, + pub length: i64, + } + + #[repr(C)] + pub struct CF_OPERATION_PARAMETERS { + pub param_size: u32, + pub op_type: u32, + pub connection_key: i64, + pub transfer_key: i64, + pub correlation_vector: *const c_void, + pub sync_status: *const c_void, + pub request_completion_status: HRESULT, + pub transfer_data: CF_OPERATION_TRANSFER_DATA, + } + + pub const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x00000010; + pub const FILE_ATTRIBUTE_NORMAL: u32 = 0x00000080; + + pub const CF_PIN_STATE_PINNED: u32 = 1; + pub const CF_PIN_STATE_UNPINNED: u32 = 2; + + pub const CF_PLACEHOLDER_STATE_PLACEHOLDER: u32 = 0x00000001; + pub const CF_PLACEHOLDER_STATE_PARTIALLY_ON_DISK: u32 = 0x00000010; + pub const CF_PLACEHOLDER_STATE_COMPLETELY_FULL: u32 = 0x00000020; + + pub const HKEY_CURRENT_USER: isize = 0x80000001u32 as i32 as isize; + pub const KEY_WRITE: u32 = 0x00020006; + pub const REG_SZ: u32 = 1; + pub const REG_MULTI_SZ: u32 = 7; + + extern "system" { + pub fn LoadLibraryW(lpLibFileName: *const u16) -> isize; + pub fn GetProcAddress(hModule: isize, lpProcName: *const u8) -> *const c_void; + pub fn FreeLibrary(hLibModule: isize) -> i32; + pub fn CreateFileW( + lpFileName: *const u16, + dwDesiredAccess: u32, + dwShareMode: u32, + lpSecurityAttributes: *const c_void, + dwCreationDisposition: u32, + dwFlagsAndAttributes: u32, + hTemplateFile: isize, + ) -> isize; + pub fn CloseHandle(hObject: isize) -> i32; + pub fn RegCreateKeyExW( + hKey: isize, + lpSubKey: *const u16, + Reserved: u32, + lpClass: *const u16, + dwOptions: u32, + samDesired: u32, + lpSecurityAttributes: *const c_void, + phkResult: *mut isize, + lpdwDisposition: *mut u32, + ) -> i32; + pub fn RegSetValueExW( + hKey: isize, + lpValueName: *const u16, + Reserved: u32, + dwType: u32, + lpData: *const u8, + cbData: u32, + ) -> i32; + pub fn RegCloseKey(hKey: isize) -> i32; + pub fn RegDeleteKeyW(hKey: isize, lpSubKey: *const u16) -> i32; + } +} + +#[cfg(windows)] +fn to_wide(s: &str) -> Vec { + s.encode_utf16().chain(std::iter::once(0)).collect() +} + +#[cfg(windows)] +fn unix_ms_to_filetime(ms: u64) -> i64 { + // 100-nanosecond intervals between January 1, 1601 and January 1, 1970 + const UNIX_EPOCH_DELTA: i64 = 116_444_736_000_000_000; + let intervals = (ms as i64).saturating_mul(10_000); + intervals.saturating_add(UNIX_EPOCH_DELTA) +} + +#[cfg(windows)] +struct CldApi { + hmodule: isize, + register_sync_root: unsafe extern "system" fn( + sync_root_path: *const u16, + registration: *const win32::CF_SYNC_REGISTRATION, + policies: *const win32::CF_SYNC_POLICIES, + register_flags: u32, + ) -> win32::HRESULT, + unregister_sync_root: unsafe extern "system" fn(sync_root_path: *const u16) -> win32::HRESULT, + connect_sync_root: unsafe extern "system" fn( + sync_root_path: *const u16, + callback_table: *const win32::CF_CALLBACK_REGISTRATION, + callback_context: *const std::ffi::c_void, + connect_flags: u32, + connection_key: *mut i64, + ) -> win32::HRESULT, + disconnect_sync_root: unsafe extern "system" fn(connection_key: i64) -> win32::HRESULT, + create_placeholders: unsafe extern "system" fn( + sync_root_path: *const u16, + placeholder_array: *mut win32::CF_PLACEHOLDER_CREATE_INFO, + placeholder_count: u32, + create_flags: u32, + entries_processed: *mut u32, + ) -> win32::HRESULT, + execute: unsafe extern "system" fn( + op_params: *const win32::CF_OPERATION_PARAMETERS, + ) -> win32::HRESULT, + set_pin_state: unsafe extern "system" fn( + file_handle: isize, + pin_state: u32, + pin_flags: u32, + pin_usn: *mut i64, + ) -> win32::HRESULT, + get_placeholder_state_from_attribute_tag: + unsafe extern "system" fn(file_attributes: u32, reparse_tag: u32) -> u32, +} + +#[cfg(windows)] +impl CldApi { + fn load() -> Option { + let name = to_wide("cldapi.dll"); + let hmodule = unsafe { win32::LoadLibraryW(name.as_ptr()) }; + if hmodule == 0 { + return None; + } + + macro_rules! resolve { + ($sym:expr, $ty:ty) => { + match unsafe { win32::GetProcAddress(hmodule, concat!($sym, "\0").as_ptr()) } { + p if !p.is_null() => unsafe { + std::mem::transmute::<*const std::ffi::c_void, $ty>(p) + }, + _ => { + unsafe { win32::FreeLibrary(hmodule) }; + return None; + } + } + }; + } + + let api = Self { + hmodule, + register_sync_root: resolve!( + "CfRegisterSyncRoot", + unsafe extern "system" fn( + *const u16, + *const win32::CF_SYNC_REGISTRATION, + *const win32::CF_SYNC_POLICIES, + u32, + ) -> win32::HRESULT + ), + unregister_sync_root: resolve!( + "CfUnregisterSyncRoot", + unsafe extern "system" fn(*const u16) -> win32::HRESULT + ), + connect_sync_root: resolve!( + "CfConnectSyncRoot", + unsafe extern "system" fn( + *const u16, + *const win32::CF_CALLBACK_REGISTRATION, + *const std::ffi::c_void, + u32, + *mut i64, + ) -> win32::HRESULT + ), + disconnect_sync_root: resolve!( + "CfDisconnectSyncRoot", + unsafe extern "system" fn(i64) -> win32::HRESULT + ), + create_placeholders: resolve!( + "CfCreatePlaceholders", + unsafe extern "system" fn( + *const u16, + *mut win32::CF_PLACEHOLDER_CREATE_INFO, + u32, + u32, + *mut u32, + ) -> win32::HRESULT + ), + execute: resolve!( + "CfExecute", + unsafe extern "system" fn(*const win32::CF_OPERATION_PARAMETERS) -> win32::HRESULT + ), + set_pin_state: resolve!( + "CfSetPinState", + unsafe extern "system" fn(isize, u32, u32, *mut i64) -> win32::HRESULT + ), + get_placeholder_state_from_attribute_tag: resolve!( + "CfGetPlaceholderStateFromAttributeTag", + unsafe extern "system" fn(u32, u32) -> u32 + ), + }; + + Some(api) + } +} + +#[cfg(windows)] +impl Drop for CldApi { + fn drop(&mut self) { + if self.hmodule != 0 { + unsafe { win32::FreeLibrary(self.hmodule) }; + self.hmodule = 0; + } + } +} + +#[cfg(windows)] +struct MountContext { + cldapi: Arc, + fetch_handler: Box Result, TransferError> + Send + Sync>, +} + +#[cfg(windows)] +unsafe extern "system" fn fetch_data_callback( + callback_info: *const win32::CF_CALLBACK_INFO, + callback_parameters: *const std::ffi::c_void, +) { + if callback_info.is_null() || callback_parameters.is_null() { + return; + } + let info = &*callback_info; + let params = &*(callback_parameters as *const win32::CF_CALLBACK_PARAMETERS); + if info.callback_context.is_null() { + return; + } + let ctx = &*(info.callback_context as *const MountContext); + + let file_identity = if !info.file_identity.is_null() && info.file_identity_length > 0 { + std::slice::from_raw_parts( + info.file_identity as *const u8, + info.file_identity_length as usize, + ) + .to_vec() + } else { + Vec::new() + }; + + let relative_path = if !info.normalized_path.is_null() { + let mut len = 0; + while *info.normalized_path.add(len) != 0 { + len += 1; + } + let slice = std::slice::from_raw_parts(info.normalized_path, len); + PathBuf::from(String::from_utf16_lossy(slice)) + } else { + PathBuf::new() + }; + + let request = FetchDataRequest { + file_identity, + relative_path, + offset: params.required_file_offset.max(0) as u64, + length: params.required_length.max(0) as u64, + }; + + let mut op_params = win32::CF_OPERATION_PARAMETERS { + param_size: std::mem::size_of::() as u32, + op_type: win32::CF_OPERATION_TYPE_TRANSFER_DATA, + connection_key: info.connection_key, + transfer_key: info.transfer_key, + correlation_vector: std::ptr::null(), + sync_status: std::ptr::null(), + request_completion_status: win32::S_OK, + transfer_data: win32::CF_OPERATION_TRANSFER_DATA { + flags: 0, + completion_status: win32::S_OK, + buffer: std::ptr::null(), + offset: params.required_file_offset, + length: params.required_length, + }, + }; + + match (ctx.fetch_handler)(request) { + Ok(data) => { + op_params.transfer_data.buffer = data.as_ptr() as *const std::ffi::c_void; + op_params.transfer_data.length = data.len() as i64; + op_params.transfer_data.completion_status = win32::S_OK; + (ctx.cldapi.execute)(&op_params); + } + Err(_) => { + // ERROR_FILE_NOT_FOUND (0x80070002) + op_params.transfer_data.completion_status = -2147024894; + op_params.request_completion_status = -2147024894; + (ctx.cldapi.execute)(&op_params); + } + } +} + +#[cfg(windows)] +unsafe extern "system" fn cancel_fetch_data_callback( + _callback_info: *const win32::CF_CALLBACK_INFO, + _callback_parameters: *const std::ffi::c_void, +) { + // Cancellation acknowledged +} + +#[cfg(windows)] +struct WindowsMountState { + connection_key: i64, + cldapi: Arc, + raw_context: *mut MountContext, +} + +#[cfg(windows)] +unsafe impl Send for WindowsMountState {} +#[cfg(windows)] +unsafe impl Sync for WindowsMountState {} + +/// Mounts remote phone storage into the operating system filesystem. +pub struct CloudFilesMount { + config: CloudFilesConfig, + #[cfg(windows)] + state: std::sync::Mutex>, +} + +impl CloudFilesMount { + pub fn new(config: CloudFilesConfig) -> Self { + Self { + config, + #[cfg(windows)] + state: std::sync::Mutex::new(None), + } + } + + pub fn config(&self) -> &CloudFilesConfig { + &self.config + } + + /// Checks if the host operating system provides cloud filter placeholder support. + pub fn is_supported() -> bool { + #[cfg(windows)] + { + CldApi::load().is_some() + } + #[cfg(not(windows))] + { + false + } + } + + /// Registers the local directory as a cloud sync root with Windows. + pub fn register(&self) -> Result<(), TransferError> { + #[cfg(windows)] + { + let cldapi = CldApi::load().ok_or_else(|| TransferError::UnsupportedPlatform)?; + + std::fs::create_dir_all(&self.config.sync_root_path)?; + + let sync_root_w = to_wide(&self.config.sync_root_path.to_string_lossy()); + let provider_name_w = to_wide(&self.config.provider_name); + let provider_version_w = to_wide(&self.config.provider_version); + + let registration = win32::CF_SYNC_REGISTRATION { + struct_size: std::mem::size_of::() as u32, + provider_name: provider_name_w.as_ptr(), + provider_version: provider_version_w.as_ptr(), + sync_root_identity: std::ptr::null(), + sync_root_identity_length: 0, + file_identity: std::ptr::null(), + file_identity_length: 0, + provider_id: win32::GUID::default(), + }; + + let policies = win32::CF_SYNC_POLICIES { + struct_size: std::mem::size_of::() as u32, + hydration: win32::CF_HYDRATION_POLICY { + primary: win32::CF_HYDRATION_POLICY_PRIMARY_PARTIAL, + modifier: 0, + }, + population: win32::CF_POPULATION_POLICY { + primary: win32::CF_POPULATION_POLICY_PRIMARY_PARTIAL, + modifier: 0, + }, + in_sync: win32::CF_INSYNC_POLICY_NONE, + hard_link: win32::CF_HARDLINK_POLICY_NONE, + placeholder_management: win32::CF_PLACEHOLDER_MANAGEMENT_POLICY_DEFAULT, + }; + + let hr = unsafe { + (cldapi.register_sync_root)( + sync_root_w.as_ptr(), + ®istration, + &policies, + win32::CF_REGISTER_FLAG_UPDATE, + ) + }; + + if hr != win32::S_OK { + return Err(TransferError::CloudFiles(format!( + "CfRegisterSyncRoot failed with HRESULT 0x{hr:08X}" + ))); + } + + // Register with Windows Explorer navigation pane + let _ = register_sync_root_registry(&self.config); + + Ok(()) + } + #[cfg(not(windows))] + { + Err(TransferError::UnsupportedPlatform) + } + } + + /// Unregisters the local directory from the operating system cloud filter driver. + pub fn unregister(&self) -> Result<(), TransferError> { + #[cfg(windows)] + { + let cldapi = CldApi::load().ok_or_else(|| TransferError::UnsupportedPlatform)?; + self.disconnect()?; + + let sync_root_w = to_wide(&self.config.sync_root_path.to_string_lossy()); + let hr = unsafe { (cldapi.unregister_sync_root)(sync_root_w.as_ptr()) }; + + let _ = unregister_sync_root_registry(&self.config); + + if hr != win32::S_OK { + return Err(TransferError::CloudFiles(format!( + "CfUnregisterSyncRoot failed with HRESULT 0x{hr:08X}" + ))); + } + + Ok(()) + } + #[cfg(not(windows))] + { + Err(TransferError::UnsupportedPlatform) + } + } + + /// Connects to the cloud sync root, enabling live on-demand hydration callbacks. + pub fn connect(&self, fetch_handler: F) -> Result<(), TransferError> + where + F: Fn(FetchDataRequest) -> Result, TransferError> + Send + Sync + 'static, + { + #[cfg(windows)] + { + let mut state_lock = self.state.lock().unwrap(); + if state_lock.is_some() { + return Ok(()); + } + + let cldapi = + Arc::new(CldApi::load().ok_or_else(|| TransferError::UnsupportedPlatform)?); + + let context = Box::into_raw(Box::new(MountContext { + cldapi: Arc::clone(&cldapi), + fetch_handler: Box::new(fetch_handler), + })); + + let callbacks = [ + win32::CF_CALLBACK_REGISTRATION { + callback_type: win32::CF_CALLBACK_TYPE_FETCH_DATA, + callback: Some(fetch_data_callback), + }, + win32::CF_CALLBACK_REGISTRATION { + callback_type: win32::CF_CALLBACK_TYPE_CANCEL_FETCH_DATA, + callback: Some(cancel_fetch_data_callback), + }, + win32::CF_CALLBACK_REGISTRATION { + callback_type: win32::CF_CALLBACK_TYPE_NONE, + callback: None, + }, + ]; + + let sync_root_w = to_wide(&self.config.sync_root_path.to_string_lossy()); + let mut connection_key: i64 = 0; + + let hr = unsafe { + (cldapi.connect_sync_root)( + sync_root_w.as_ptr(), + callbacks.as_ptr(), + context as *const std::ffi::c_void, + win32::CF_CONNECT_FLAG_REQUIRE_FULL_FILE_PATH, + &mut connection_key, + ) + }; + + if hr != win32::S_OK { + unsafe { drop(Box::from_raw(context)) }; + return Err(TransferError::CloudFiles(format!( + "CfConnectSyncRoot failed with HRESULT 0x{hr:08X}" + ))); + } + + *state_lock = Some(WindowsMountState { + connection_key, + cldapi, + raw_context: context, + }); + + Ok(()) + } + #[cfg(not(windows))] + { + let _ = fetch_handler; + Err(TransferError::UnsupportedPlatform) + } + } + + /// Disconnects from the sync root callback pipeline. + pub fn disconnect(&self) -> Result<(), TransferError> { + #[cfg(windows)] + { + let mut state_lock = self.state.lock().unwrap(); + if let Some(state) = state_lock.take() { + unsafe { + (state.cldapi.disconnect_sync_root)(state.connection_key); + if !state.raw_context.is_null() { + drop(Box::from_raw(state.raw_context)); + } + } + } + Ok(()) + } + #[cfg(not(windows))] + { + Ok(()) + } + } + + /// Creates placeholder files and directories inside the sync root. + pub fn create_placeholders(&self, entries: &[CloudFilesEntry]) -> Result { + #[cfg(windows)] + { + if entries.is_empty() { + return Ok(0); + } + + let cldapi = CldApi::load().ok_or_else(|| TransferError::UnsupportedPlatform)?; + + let sync_root_w = to_wide(&self.config.sync_root_path.to_string_lossy()); + + // Ensure parent directories exist before creating child placeholders + for entry in entries { + let full_path = self.config.sync_root_path.join(&entry.relative_path); + if let Some(parent) = full_path.parent() { + let _ = std::fs::create_dir_all(parent); + } + } + + let wide_names: Vec> = entries + .iter() + .map(|e| to_wide(&e.relative_path.to_string_lossy())) + .collect(); + + let mut create_infos: Vec = entries + .iter() + .enumerate() + .map(|(i, entry)| { + let ft = unix_ms_to_filetime(entry.modified_time_ms); + let attributes = if entry.is_directory { + win32::FILE_ATTRIBUTE_DIRECTORY + } else { + win32::FILE_ATTRIBUTE_NORMAL + }; + + win32::CF_PLACEHOLDER_CREATE_INFO { + relative_file_name: wide_names[i].as_ptr(), + fs_metadata: win32::CF_FS_METADATA { + basic_info: win32::FILE_BASIC_INFO { + creation_time: ft, + last_access_time: ft, + last_write_time: ft, + change_time: ft, + file_attributes: attributes, + }, + file_size: entry.file_size as i64, + }, + file_identity: entry.file_identity.as_ptr() as *const std::ffi::c_void, + file_identity_length: entry.file_identity.len() as u32, + flags: win32::CF_PLACEHOLDER_CREATE_FLAG_MARK_IN_SYNC, + result: 0, + create_usn: 0, + } + }) + .collect(); + + let mut processed: u32 = 0; + let hr = unsafe { + (cldapi.create_placeholders)( + sync_root_w.as_ptr(), + create_infos.as_mut_ptr(), + create_infos.len() as u32, + win32::CF_CREATE_FLAG_NONE, + &mut processed, + ) + }; + + if hr != win32::S_OK && processed == 0 { + return Err(TransferError::CloudFiles(format!( + "CfCreatePlaceholders failed with HRESULT 0x{hr:08X}" + ))); + } + + Ok(processed) + } + #[cfg(not(windows))] + { + let _ = entries; + Err(TransferError::UnsupportedPlatform) + } + } + + /// Sets the pin state of a placeholder file (pinned keeps local copy, unpinned permits dehydration). + pub fn set_pin_state>( + &self, + relative_path: P, + pinned: bool, + ) -> Result<(), TransferError> { + #[cfg(windows)] + { + let cldapi = CldApi::load().ok_or_else(|| TransferError::UnsupportedPlatform)?; + let full_path = self.config.sync_root_path.join(relative_path); + let path_w = to_wide(&full_path.to_string_lossy()); + + // FILE_WRITE_ATTRIBUTES (0x0100), FILE_SHARE_READ | FILE_SHARE_WRITE (3), OPEN_EXISTING (3) + // FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT (0x02200000) + let handle = unsafe { + win32::CreateFileW( + path_w.as_ptr(), + 0x0100, + 3, + std::ptr::null(), + 3, + 0x02200000, + 0, + ) + }; + + if handle == -1 || handle == 0 { + return Err(TransferError::CloudFiles( + "Unable to open placeholder file handle for pin state update".to_string(), + )); + } + + let pin_state = if pinned { + win32::CF_PIN_STATE_PINNED + } else { + win32::CF_PIN_STATE_UNPINNED + }; + + let hr = unsafe { + let res = (cldapi.set_pin_state)(handle, pin_state, 0, std::ptr::null_mut()); + win32::CloseHandle(handle); + res + }; + + if hr != win32::S_OK { + return Err(TransferError::CloudFiles(format!( + "CfSetPinState failed with HRESULT 0x{hr:08X}" + ))); + } + + Ok(()) + } + #[cfg(not(windows))] + { + let _ = relative_path; + let _ = pinned; + Err(TransferError::UnsupportedPlatform) + } + } + + /// Queries the current hydration state of a file inside the sync root. + pub fn get_hydration_state>( + &self, + relative_path: P, + ) -> Result { + #[cfg(windows)] + { + let cldapi = CldApi::load().ok_or_else(|| TransferError::UnsupportedPlatform)?; + let full_path = self.config.sync_root_path.join(relative_path); + if !full_path.exists() { + return Ok(HydrationState::NotAPlaceholder); + } + + use std::os::windows::fs::MetadataExt; + let metadata = std::fs::symlink_metadata(&full_path)?; + let attributes = metadata.file_attributes(); + + // Reparse tag for Cloud Filter placeholders is IO_REPARSE_TAG_CLOUD (0x9000001A) + const IO_REPARSE_TAG_CLOUD: u32 = 0x9000001A; + let state_flags = unsafe { + (cldapi.get_placeholder_state_from_attribute_tag)(attributes, IO_REPARSE_TAG_CLOUD) + }; + + if (state_flags & win32::CF_PLACEHOLDER_STATE_COMPLETELY_FULL) != 0 { + Ok(HydrationState::FullyHydrated) + } else if (state_flags & win32::CF_PLACEHOLDER_STATE_PARTIALLY_ON_DISK) != 0 { + Ok(HydrationState::PartiallyHydrated) + } else if (state_flags & win32::CF_PLACEHOLDER_STATE_PLACEHOLDER) != 0 { + Ok(HydrationState::Unhydrated) + } else { + Ok(HydrationState::NotAPlaceholder) + } + } + #[cfg(not(windows))] + { + let _ = relative_path; + Err(TransferError::UnsupportedPlatform) + } + } +} + +impl Drop for CloudFilesMount { + fn drop(&mut self) { + let _ = self.disconnect(); + } +} + +/// Registers the sync root in the Windows Registry to display it in File Explorer's sidebar. +#[cfg(windows)] +pub fn register_sync_root_registry(config: &CloudFilesConfig) -> Result<(), TransferError> { + let subkey = format!( + "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\SyncRootManager\\{}!{}", + config.provider_name, config.device_id + ); + let subkey_w = to_wide(&subkey); + let mut hkey: isize = 0; + let mut disposition: u32 = 0; + + unsafe { + let res = win32::RegCreateKeyExW( + win32::HKEY_CURRENT_USER, + subkey_w.as_ptr(), + 0, + std::ptr::null(), + 0, + win32::KEY_WRITE, + std::ptr::null(), + &mut hkey, + &mut disposition, + ); + if res != 0 { + return Err(TransferError::CloudFiles(format!( + "RegCreateKeyExW failed with code {res}" + ))); + } + + let display_name = format!("{} ({})", config.provider_name, config.device_name); + let display_name_w = to_wide(&display_name); + win32::RegSetValueExW( + hkey, + to_wide("DisplayName").as_ptr(), + 0, + win32::REG_SZ, + display_name_w.as_ptr() as *const u8, + (display_name_w.len() * 2) as u32, + ); + + let path_str = config.sync_root_path.to_string_lossy().to_string(); + let mut multi_sz = to_wide(&path_str); + multi_sz.push(0); // Double null termination for REG_MULTI_SZ + win32::RegSetValueExW( + hkey, + to_wide("UserSyncRoots").as_ptr(), + 0, + win32::REG_MULTI_SZ, + multi_sz.as_ptr() as *const u8, + (multi_sz.len() * 2) as u32, + ); + + win32::RegCloseKey(hkey); + } + Ok(()) +} + +/// Removes the sync root entry from the Windows Registry. +#[cfg(windows)] +pub fn unregister_sync_root_registry(config: &CloudFilesConfig) -> Result<(), TransferError> { + let subkey = format!( + "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\SyncRootManager\\{}!{}", + config.provider_name, config.device_id + ); + let subkey_w = to_wide(&subkey); + unsafe { + win32::RegDeleteKeyW(win32::HKEY_CURRENT_USER, subkey_w.as_ptr()); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn config_initialization() { + let config = CloudFilesConfig::new( + PathBuf::from(r"C:\Users\test\Continue\Pixel8"), + "Continue", + "Pixel 8", + "pixel-8-unique-id", + ); + assert_eq!(config.provider_name, "Continue"); + assert_eq!(config.device_name, "Pixel 8"); + assert_eq!(config.provider_version, "1.0.0"); + } + + #[test] + fn entry_constructors() { + let file_entry = + CloudFilesEntry::file("Photos/test.jpg", 1024, 1700000000, b"id-1".to_vec()); + assert_eq!(file_entry.file_size, 1024); + assert!(!file_entry.is_directory); + assert_eq!(file_entry.file_identity, b"id-1"); + + let dir_entry = CloudFilesEntry::directory("Photos", 1700000000, b"dir-1".to_vec()); + assert_eq!(dir_entry.file_size, 0); + assert!(dir_entry.is_directory); + } + + #[test] + fn platform_support_detection() { + let supported = CloudFilesMount::is_supported(); + if cfg!(windows) { + assert!( + supported, + "cldapi.dll should be supported on modern Windows" + ); + } else { + assert!(!supported); + } + } +} diff --git a/crates/transfer/src/error.rs b/crates/transfer/src/error.rs index 14be917..2df3981 100644 --- a/crates/transfer/src/error.rs +++ b/crates/transfer/src/error.rs @@ -67,4 +67,10 @@ pub enum TransferError { #[error("Transfer queue full: {0}")] QueueFull(String), + + #[error("Cloud files provider error: {0}")] + CloudFiles(String), + + #[error("Cloud files not supported on this platform")] + UnsupportedPlatform, } diff --git a/crates/transfer/src/lib.rs b/crates/transfer/src/lib.rs index 9b23184..40d781a 100644 --- a/crates/transfer/src/lib.rs +++ b/crates/transfer/src/lib.rs @@ -4,6 +4,7 @@ //! Streaming file transfer, one QUIC stream per file. pub mod capture; +pub mod cloud_files; pub mod drop_folder; pub mod error; pub mod localsend_bridge; @@ -17,6 +18,9 @@ pub use capture::{ format_as_clipboard_dibv5, request_camera_capture, respond_camera_capture, CameraCaptureSource, CapturedMedia, }; +pub use cloud_files::{ + CloudFilesConfig, CloudFilesEntry, CloudFilesMount, FetchDataRequest, HydrationState, +}; pub use drop_folder::{guess_mime_type, is_ignorable_file, DropFolderConfig, DropFolderWatcher}; pub use error::TransferError; pub use localsend_bridge::{ diff --git a/crates/transfer/tests/cloud_files_test.rs b/crates/transfer/tests/cloud_files_test.rs new file mode 100644 index 0000000..e622f5d --- /dev/null +++ b/crates/transfer/tests/cloud_files_test.rs @@ -0,0 +1,87 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + +use transfer::{ + CloudFilesConfig, CloudFilesEntry, CloudFilesMount, FetchDataRequest, HydrationState, +}; + +#[test] +fn cloud_files_config_and_entry_model() { + let temp_dir = std::env::temp_dir().join(format!("continue_cf_test_{}", rand::random::())); + let config = CloudFilesConfig::new(&temp_dir, "Continue", "Galaxy S24", "s24-device-id"); + + assert_eq!(config.sync_root_path, temp_dir); + assert_eq!(config.device_name, "Galaxy S24"); + assert_eq!(config.device_id, "s24-device-id"); + + let entries = vec![ + CloudFilesEntry::directory("Documents", 1710000000, b"doc-dir".to_vec()), + CloudFilesEntry::file("Documents/report.pdf", 4096, 1710000100, b"doc-1".to_vec()), + CloudFilesEntry::file("photo.jpg", 123456, 1710000200, b"photo-1".to_vec()), + ]; + + assert_eq!(entries.len(), 3); + assert!(entries[0].is_directory); + assert_eq!(entries[0].file_size, 0); + assert!(!entries[1].is_directory); + assert_eq!(entries[1].file_size, 4096); + assert_eq!(entries[2].file_identity, b"photo-1"); +} + +#[test] +fn cloud_files_mount_lifecycle_and_placeholders() { + if !CloudFilesMount::is_supported() { + return; + } + + let temp_dir = + std::env::temp_dir().join(format!("continue_cf_mount_{}", rand::random::())); + let config = CloudFilesConfig::new(&temp_dir, "ContinueTest", "Test Phone", "test-phone-id"); + let mount = CloudFilesMount::new(config); + + let reg_result = mount.register(); + if let Err(e) = reg_result { + // In restricted environments or CI containers, registering sync roots may be disallowed. + eprintln!("Cloud files register returned: {e}"); + return; + } + + let fetch_called = Arc::new(AtomicBool::new(false)); + let fetch_called_clone = Arc::clone(&fetch_called); + + let connect_res = mount.connect(move |req: FetchDataRequest| { + fetch_called_clone.store(true, Ordering::SeqCst); + assert!(!req.file_identity.is_empty()); + Ok(vec![0xAA; req.length.min(1024) as usize]) + }); + + if let Ok(()) = connect_res { + let entries = vec![CloudFilesEntry::file( + "sample.txt", + 1024, + 1710000000, + b"sample-id".to_vec(), + )]; + + let created = mount.create_placeholders(&entries); + if let Ok(count) = created { + assert!(count >= 1); + let state = mount.get_hydration_state("sample.txt"); + if let Ok(hydr) = state { + assert!( + hydr == HydrationState::Unhydrated + || hydr == HydrationState::FullyHydrated + || hydr == HydrationState::NotAPlaceholder + ); + } + } + + let _ = mount.disconnect(); + } + + let _ = mount.unregister(); + let _ = std::fs::remove_dir_all(&temp_dir); +} From c47f39e19f6b025cb7f8c316b32450911d85cb69 Mon Sep 17 00:00:00 2001 From: Samarth Rajesh Lad <142334685+samyyy2311@users.noreply.github.com> Date: Thu, 8 Oct 2026 16:22:03 +0530 Subject: [PATCH 08/14] feat: add desktop UI integration for continuity suite and explorer mount --- apps/desktop/src-tauri/Cargo.lock | 17 ++ apps/desktop/src-tauri/Cargo.toml | 3 + apps/desktop/src-tauri/src/main.rs | 318 +++++++++++++++++++- apps/desktop/src/App.tsx | 119 +++++++- apps/desktop/src/CatalogDialog.tsx | 248 +++++++++++++++ apps/desktop/src/ClipboardHistoryDialog.tsx | 205 +++++++++++++ apps/desktop/src/api.ts | 50 +++ apps/desktop/src/types.ts | 34 +++ 8 files changed, 986 insertions(+), 8 deletions(-) create mode 100644 apps/desktop/src/CatalogDialog.tsx create mode 100644 apps/desktop/src/ClipboardHistoryDialog.tsx diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index da8efce..07573ea 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -648,6 +648,7 @@ dependencies = [ "limits", "protocol", "quinn", + "rusqlite", "sha2", "thiserror 1.0.69", "tokio", @@ -717,11 +718,15 @@ checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" name = "continue-desktop" version = "0.1.0" dependencies = [ + "base64 0.22.1", + "capabilities", + "clipboard", "clipboard-rs", "device", "history", "identity", "keyring", + "notifications", "pairing", "parking_lot", "percent-encoding", @@ -1074,6 +1079,7 @@ dependencies = [ "discovery", "history", "identity", + "notifications", "pairing", "permissions", "protocol", @@ -1135,6 +1141,8 @@ dependencies = [ "limits", "mdns-sd", "rand 0.8.8", + "serde", + "serde_json", "thiserror 1.0.69", "tokio", "tracing", @@ -3304,12 +3312,17 @@ dependencies = [ "base64 0.22.1", "crypto", "ed25519-dalek", + "hkdf", "identity", "limits", "protocol", "quinn", + "rand 0.8.8", "rusqlite", + "sha2", + "subtle", "thiserror 1.0.69", + "tokio", "transport", "x25519-dalek", "zeroize", @@ -5639,10 +5652,14 @@ dependencies = [ name = "transfer" version = "0.1.0" dependencies = [ + "bytes", "hex", "limits", "protocol", "quinn", + "rand 0.8.8", + "serde", + "serde_json", "sha2", "thiserror 1.0.69", "tokio", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 7fbc1c0..e0b5124 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -32,6 +32,9 @@ notifications = { path = "../../../crates/notifications" } history = { path = "../../../crates/history" } device = { path = "../../../crates/device" } transfer = { path = "../../../crates/transfer" } +clipboard = { path = "../../../crates/clipboard" } +capabilities = { path = "../../../crates/capabilities" } +base64 = "0.22" parking_lot = "0.12" zeroize = "1" tracing = "0.1" diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index b353ab8..7f8fcc7 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -20,10 +20,13 @@ use tauri_plugin_autostart::ManagerExt; use tauri_plugin_notification::NotificationExt; use tauri_plugin_opener::OpenerExt; +use capabilities::CapabilityQuery; +use clipboard::history::ClipboardHistoryStore; use device::{ConnectError, Device, PairError, SendError, Stores}; use history::{Direction, HistoryStore, Kind}; use pairing::DeviceKeys; use permissions::PermissionState; +use protocol::v1::{CatalogQuery, PcAction, PcActionRequest, RingRequest, ThumbnailRequest}; use protocol::CapabilityId; use sessions::{PermissionDecision, SessionState}; use transfer::TransferError; @@ -107,6 +110,8 @@ pub struct DesktopRuntimeState { incoming: sessions::IncomingFiles, clipboard: ClipboardSync, batteries: Batteries, + clipboard_history: Arc, + cloud_mounts: Arc>>>, } #[derive(Serialize)] @@ -325,6 +330,7 @@ fn session_handlers( stores: &Stores, pending_answers: PendingAnswers, clipboard: ClipboardSync, + clipboard_history: Arc, app_handle: &AppHandle, ) -> sessions::SessionCapabilityHandlers { let mut handlers = sessions::SessionCapabilityHandlers::new(download_dir) @@ -365,11 +371,17 @@ fn session_handlers( ); })); - let (app, texts) = (app_handle.clone(), stores.clone()); + let (app, texts, history_store) = (app_handle.clone(), stores.clone(), clipboard_history); handlers.on_clipboard_received = Some(Arc::new(move |peer, update| { let text = String::from_utf8_lossy(&update.payload).into_owned(); clipboard.write(text.clone()); let name = texts.received_text(peer, &text).peer_name; + let _ = history_store.record_clip( + protocol::v1::ClipboardFormat::TextPlain, + &text, + &name, + None::<[&str; 0]>, + ); notify_if_away( &app, &format!("Copied text from {}", shown_name(name.clone())), @@ -847,7 +859,14 @@ struct SyncedTextDto { /// Sends what was just copied here to every connected device. fn send_copied_text(app: &AppHandle, text: String) { - let device = app.state::().device.clone(); + let state = app.state::(); + let _ = state.clipboard_history.record_clip( + protocol::v1::ClipboardFormat::TextPlain, + &text, + "This PC", + None::<[&str; 0]>, + ); + let device = state.device.clone(); let peers = device.stores.trust.list_peers().unwrap_or_default(); for peer in peers .into_iter() @@ -937,6 +956,282 @@ async fn push_text(device: &Device, peer: &str, text: String) -> Result<(), Stri } } +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CatalogItemDto { + pub id: String, + pub name: String, + pub size_bytes: u64, + pub timestamp: u64, + pub mime_type: String, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CatalogResponseDto { + pub items: Vec, + pub total_count: u32, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ClipboardHistoryEntryDto { + pub id: i64, + pub timestamp_ms: u64, + pub content: String, + pub is_pinned: bool, + pub origin_device: String, +} + +#[tauri::command] +async fn ring_peer( + state: State<'_, DesktopRuntimeState>, + peer_fingerprint: String, + active: bool, +) -> Result { + let mux = state + .device + .sessions + .get(&peer_fingerprint) + .ok_or_else(|| NOT_CONNECTED.to_string())?; + let query = CapabilityQuery::negotiated(CapabilityId::RING_DEVICE, true); + let request = RingRequest { + active, + duration_secs: 30, + force_max_volume: true, + }; + let ack = mux + .trigger_ring_on_peer(request, &query) + .await + .map_err(user_error("Couldn't ring device."))?; + Ok(ack.is_ringing) +} + +#[tauri::command] +async fn send_pc_action( + state: State<'_, DesktopRuntimeState>, + peer_fingerprint: String, + action: i32, +) -> Result { + let pc_action = match action { + 0 => PcAction::LockWorkstation, + 1 => PcAction::SleepSystem, + 2 => PcAction::ShutdownSystem, + 3 => PcAction::ToggleMute, + _ => return Err("Invalid PC action".to_string()), + }; + let mux = state + .device + .sessions + .get(&peer_fingerprint) + .ok_or_else(|| NOT_CONNECTED.to_string())?; + let query = CapabilityQuery::negotiated(CapabilityId::PC_CONTROL, true); + let request = PcActionRequest { + action: pc_action as i32, + force: false, + }; + let resp = mux + .send_pc_action_to_peer(request, &query) + .await + .map_err(user_error("Couldn't execute PC action."))?; + Ok(resp.success) +} + +#[tauri::command] +async fn query_file_catalog( + state: State<'_, DesktopRuntimeState>, + peer_fingerprint: String, + category: i32, + limit: u32, + offset: u32, +) -> Result { + let mux = state + .device + .sessions + .get(&peer_fingerprint) + .ok_or_else(|| NOT_CONNECTED.to_string())?; + let query = CapabilityQuery::negotiated(CapabilityId::FILE_CATALOG, true); + let req = CatalogQuery { + category, + limit, + offset, + }; + let resp = mux + .query_file_catalog_from_peer(req, &query) + .await + .map_err(user_error("Couldn't browse files on device."))?; + Ok(CatalogResponseDto { + items: resp + .items + .into_iter() + .map(|item| CatalogItemDto { + id: item.item_id, + name: item.file_name, + size_bytes: item.size_bytes, + timestamp: item.timestamp, + mime_type: item.mime_type, + }) + .collect(), + total_count: resp.total_count, + }) +} + +#[tauri::command] +async fn get_catalog_thumbnail( + state: State<'_, DesktopRuntimeState>, + peer_fingerprint: String, + item_id: String, + max_edge: u32, +) -> Result { + let mux = state + .device + .sessions + .get(&peer_fingerprint) + .ok_or_else(|| NOT_CONNECTED.to_string())?; + let query = CapabilityQuery::negotiated(CapabilityId::FILE_CATALOG, true); + let req = ThumbnailRequest { + item_id, + max_dimension: max_edge, + }; + let resp = mux + .request_thumbnail_from_peer(req, &query) + .await + .map_err(user_error("Couldn't load thumbnail."))?; + use base64::engine::general_purpose::STANDARD as BASE64; + use base64::Engine; + let b64 = BASE64.encode(&resp.image_data); + let mime = if resp.mime_type.is_empty() { + "image/jpeg" + } else { + &resp.mime_type + }; + Ok(format!("data:{mime};base64,{b64}")) +} + +#[tauri::command] +async fn mount_cloud_files( + app: AppHandle, + state: State<'_, DesktopRuntimeState>, + peer_fingerprint: String, +) -> Result { + let peer_name = state.device.stores.peer_name(&peer_fingerprint); + let base_dir = std::env::var("USERPROFILE") + .map(PathBuf::from) + .or_else(|_| app.path().home_dir()) + .unwrap_or_else(|_| PathBuf::from(".")); + let mount_path = base_dir + .join("Continue") + .join(shown_name(peer_name.clone())); + let _ = std::fs::create_dir_all(&mount_path); + + let config = transfer::CloudFilesConfig::new( + &mount_path, + "Continue", + shown_name(peer_name), + &peer_fingerprint, + ); + + let mount = Arc::new(transfer::CloudFilesMount::new(config)); + if transfer::CloudFilesMount::is_supported() { + let _ = mount.register(); + + if let Some(mux) = state.device.sessions.get(&peer_fingerprint) { + let query = CapabilityQuery::negotiated(CapabilityId::FILE_CATALOG, true); + let req = CatalogQuery { + category: 0, + limit: 100, + offset: 0, + }; + if let Ok(catalog) = mux.query_file_catalog_from_peer(req, &query).await { + let entries: Vec = catalog + .items + .into_iter() + .map(|item| { + transfer::CloudFilesEntry::file( + item.file_name, + item.size_bytes, + item.timestamp, + item.item_id.into_bytes(), + ) + }) + .collect(); + let _ = mount.create_placeholders(&entries); + } + } + } + + state.cloud_mounts.lock().insert(peer_fingerprint, mount); + let path_str = mount_path.to_string_lossy().into_owned(); + let _ = app.opener().open_path(&path_str, None::<&str>); + Ok(path_str) +} + +#[tauri::command] +fn open_cloud_files_folder( + app: AppHandle, + state: State, + peer_fingerprint: String, +) -> Result<(), String> { + let peer_name = state.device.stores.peer_name(&peer_fingerprint); + let base_dir = std::env::var("USERPROFILE") + .map(PathBuf::from) + .or_else(|_| app.path().home_dir()) + .unwrap_or_else(|_| PathBuf::from(".")); + let mount_path = base_dir.join("Continue").join(shown_name(peer_name)); + app.opener() + .open_path(mount_path.to_string_lossy(), None::<&str>) + .map_err(user_error("Couldn't open folder.")) +} + +#[tauri::command] +fn get_clipboard_history( + state: State, + limit: u32, +) -> Result, String> { + let clips = state + .clipboard_history + .list_clips(limit.max(1)) + .map_err(user_error("Couldn't load clipboard history."))?; + Ok(clips + .into_iter() + .map(|c| ClipboardHistoryEntryDto { + id: c.id, + timestamp_ms: c.timestamp_ms, + content: c.content, + is_pinned: c.is_pinned, + origin_device: c.origin_device, + }) + .collect()) +} + +#[tauri::command] +fn pin_clipboard_clip( + state: State, + id: i64, + pinned: bool, +) -> Result { + state + .clipboard_history + .pin_clip(id, pinned) + .map_err(user_error("Couldn't pin clip.")) +} + +#[tauri::command] +fn delete_clipboard_clip(state: State, id: i64) -> Result { + state + .clipboard_history + .delete_clip(id) + .map_err(user_error("Couldn't delete clip.")) +} + +#[tauri::command] +fn clear_clipboard_history(state: State) -> Result { + state + .clipboard_history + .clear_unpinned() + .map_err(user_error("Couldn't clear clipboard history.")) +} + fn initialize_desktop_runtime( app_handle: &AppHandle, db_path: &Path, @@ -946,6 +1241,10 @@ fn initialize_desktop_runtime( ) -> Result> { let stores = Stores::open(db_path)?; let keys = DeviceKeys::load_or_create(&secrets::device_key_store(secrets_dir)?)?; + let clipboard_history = Arc::new(ClipboardHistoryStore::open( + db_path.with_file_name("continue_clipboard.db"), + )?); + let cloud_mounts = Arc::new(Mutex::new(HashMap::new())); let pending_answers = PendingAnswers::default(); let connected = Arc::new(tray::Connected::default()); @@ -954,6 +1253,7 @@ fn initialize_desktop_runtime( &stores, pending_answers.clone(), clipboard.clone(), + clipboard_history.clone(), app_handle, ); handlers.on_device_info = Some(device_info_listener( @@ -979,6 +1279,8 @@ fn initialize_desktop_runtime( incoming, clipboard, batteries, + clipboard_history, + cloud_mounts, }) } @@ -1085,7 +1387,17 @@ fn main() { send_file_to_peer, send_clipboard_text, press_notification_button, - dismiss_notification + dismiss_notification, + ring_peer, + send_pc_action, + query_file_catalog, + get_catalog_thumbnail, + mount_cloud_files, + open_cloud_files_folder, + get_clipboard_history, + pin_clipboard_clip, + delete_clipboard_clip, + clear_clipboard_history ]) // Closing the window keeps Continue in the tray, still receiving. Quit is in the tray menu. .on_window_event(|window, event| { diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index eff44fa..fa848e7 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -4,6 +4,8 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { ArrowUp, + Bell, + BellOff, Check, CheckCheck, CircleAlert, @@ -59,6 +61,7 @@ import { onNotificationRemoved, openLink, openReceived, + ringPeer, savePastedFile, setAutostart, setSaveFolder, @@ -76,6 +79,8 @@ import { getFileCategory, linkIn, } from "./format.ts"; +import { CatalogDialog } from "./CatalogDialog.tsx"; +import { ClipboardHistoryDialog } from "./ClipboardHistoryDialog.tsx"; import { NotificationList } from "./Notifications.tsx"; import { PairDialog } from "./PairDialog.tsx"; import { @@ -215,6 +220,9 @@ export default function App() { // The last device picked is picked again next time. const [selectedPeerId, setSelectedPeerId] = useState(() => readStored(PEER_KEY)); const [showPairDialog, setShowPairDialog] = useState(false); + const [showCatalogDialog, setShowCatalogDialog] = useState(false); + const [showClipboardDialog, setShowClipboardDialog] = useState(false); + const [isRinging, setIsRinging] = useState(false); const [activity, setActivity] = useState([]); const [connecting, setConnecting] = useState(null); const [toast, setToast] = useState(null); @@ -230,6 +238,24 @@ export default function App() { const showError = useCallback((message: string) => showToast(message, "error"), [showToast]); + const handleToggleRing = async () => { + if (!selectedPeer) return; + try { + const next = !isRinging; + const active = await ringPeer(selectedPeer.fingerprint, next); + setIsRinging(active); + if (active) { + showToast(`Ringing ${selectedPeer.displayName}...`); + } + } catch (err) { + showError(errorMessage(err)); + } + }; + + useEffect(() => { + setIsRinging(false); + }, [selectedPeerId]); + useEffect(() => { if (!toast) return; const timer = window.setTimeout(() => setToast(null), toast.tone === "error" ? 5000 : 2600); @@ -763,6 +789,10 @@ export default function App() { onOpenPair={() => setShowPairDialog(true)} onChooseFiles={chooseFiles} onSendClipboard={handleSendClipboard} + onOpenCatalog={() => setShowCatalogDialog(true)} + onOpenClipboardHistory={() => setShowClipboardDialog(true)} + isRinging={isRinging} + onToggleRing={handleToggleRing} textInput={textInput} onTextInputChange={setTextInput} onSendText={handleSendText} @@ -809,6 +839,7 @@ export default function App() { onAccentChange={setAccent} clipboardSync={clipboardSync} onClipboardSyncChange={setClipboardSync} + onOpenClipboardHistory={() => setShowClipboardDialog(true)} onError={showError} onOpenFolder={(folder) => rowActions.open(folder, false)} /> @@ -832,6 +863,21 @@ export default function App() { {showPairDialog && setShowPairDialog(false)} />} + {showCatalogDialog && selectedPeer && ( + setShowCatalogDialog(false)} + onError={showError} + /> + )} + + {showClipboardDialog && ( + setShowClipboardDialog(false)} + onError={showError} + /> + )} + {toast && (
{toast.tone === "error" ? : } @@ -940,6 +986,10 @@ interface HomeViewProps { onOpenPair: () => void; onChooseFiles: () => void; onSendClipboard: () => void; + onOpenCatalog: () => void; + onOpenClipboardHistory: () => void; + isRinging: boolean; + onToggleRing: () => void; textInput: string; onTextInputChange: (val: string) => void; onSendText: () => void; @@ -956,7 +1006,19 @@ interface HomeViewProps { } function HomeView(props: HomeViewProps) { - const { peer, peers, onSelectPeer, onOpenPair, onChooseFiles, onSendClipboard, textInput } = props; + const { + peer, + peers, + onSelectPeer, + onOpenPair, + onChooseFiles, + onSendClipboard, + onOpenCatalog, + onOpenClipboardHistory, + isRinging, + onToggleRing, + textInput, + } = props; const { onTextInputChange, onSendText, onConnect, onReconnect, onDisconnect, isConnecting } = props; const { activeTransfers, recentActivity, rowActions, onNavigateHistory, notifications, onError } = props; @@ -992,9 +1054,20 @@ function HomeView(props: HomeViewProps) {

{online ? ( - + <> + + + ) : ( Send clipboard + +
)}
void; + onOpenClipboardHistory: () => void; onError: (message: string) => void; onOpenFolder: (folder: string) => void; theme: Theme; @@ -1370,7 +1460,17 @@ const THEME_OPTIONS = [ ] as const; function SettingsView(props: SettingsViewProps) { - const { identity, theme, accent, onThemeChange, onAccentChange, clipboardSync, onClipboardSyncChange, onError } = props; + const { + identity, + theme, + accent, + onThemeChange, + onAccentChange, + clipboardSync, + onClipboardSyncChange, + onOpenClipboardHistory, + onError, + } = props; const { onOpenFolder } = props; const [appVersion, setAppVersion] = useState(""); const [startAtLogin, setStartAtLogin] = useState(false); @@ -1492,6 +1592,15 @@ function SettingsView(props: SettingsViewProps) {
+
  • +
    + History + View, search, and pin saved clipboard snippets +
    + +
  • {identity && ( diff --git a/apps/desktop/src/CatalogDialog.tsx b/apps/desktop/src/CatalogDialog.tsx new file mode 100644 index 0000000..238b48a --- /dev/null +++ b/apps/desktop/src/CatalogDialog.tsx @@ -0,0 +1,248 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +import { useEffect, useState } from "react"; +import { FolderOpen, FolderSync, HardDrive, Image as ImageIcon, Loader, X } from "lucide-react"; +import { + errorMessage, + getCatalogThumbnail, + mountCloudFiles, + queryFileCatalog, +} from "./api.ts"; +import { formatBytes, formatRelativeTime } from "./format.ts"; +import { + CatalogCategory, + type CatalogItem, + type TrustedPeer, +} from "./types.ts"; + +interface CatalogDialogProps { + peer: TrustedPeer; + onClose: () => void; + onError: (message: string) => void; +} + +const CATEGORIES: { id: CatalogCategory; label: string }[] = [ + { id: CatalogCategory.Photos, label: "Photos" }, + { id: CatalogCategory.Screenshots, label: "Screenshots" }, + { id: CatalogCategory.Downloads, label: "Downloads" }, + { id: CatalogCategory.Documents, label: "Documents" }, +]; + +export function CatalogDialog({ peer, onClose, onError }: CatalogDialogProps) { + const [activeCategory, setActiveCategory] = useState(CatalogCategory.Photos); + const [items, setItems] = useState([]); + const [loading, setLoading] = useState(false); + const [mounting, setMounting] = useState(false); + const [mountedPath, setMountedPath] = useState(null); + const [thumbnails, setThumbnails] = useState>({}); + + useEffect(() => { + const handleKey = (e: KeyboardEvent) => { + if (e.key === "Escape") onClose(); + }; + window.addEventListener("keydown", handleKey); + return () => window.removeEventListener("keydown", handleKey); + }, [onClose]); + + useEffect(() => { + let active = true; + setLoading(true); + queryFileCatalog(peer.fingerprint, activeCategory, 60, 0) + .then((resp) => { + if (!active) return; + setItems(resp.items); + setLoading(false); + }) + .catch((err) => { + if (!active) return; + setLoading(false); + onError(errorMessage(err)); + }); + return () => { + active = false; + }; + }, [peer.fingerprint, activeCategory, onError]); + + useEffect(() => { + if (activeCategory !== CatalogCategory.Photos && activeCategory !== CatalogCategory.Screenshots) { + return; + } + const toLoad = items.slice(0, 16).filter((it) => !thumbnails[it.id]); + for (const item of toLoad) { + getCatalogThumbnail(peer.fingerprint, item.id, 128) + .then((thumb) => { + setThumbnails((prev) => ({ ...prev, [item.id]: thumb })); + }) + .catch(() => {}); + } + }, [peer.fingerprint, activeCategory, items, thumbnails]); + + const handleMount = async () => { + setMounting(true); + try { + const path = await mountCloudFiles(peer.fingerprint); + setMountedPath(path); + } catch (err) { + onError(errorMessage(err)); + } finally { + setMounting(false); + } + }; + + const isVisual = + activeCategory === CatalogCategory.Photos || activeCategory === CatalogCategory.Screenshots; + + return ( +
    +
    e.stopPropagation()} + style={{ maxWidth: 720 }} + > +
    +
    +

    + Browse {peer.displayName} +

    +

    Explore remote photos, downloads, and files.

    +
    + +
    + +
    +
    + {CATEGORIES.map((cat) => ( + + ))} +
    + + +
    + + {loading ? ( +
    + + + Loading items from {peer.displayName} + +
    + ) : items.length === 0 ? ( +
    + +

    No files found in this category.

    +
    + ) : isVisual ? ( +
    + {items.map((item) => { + const thumb = thumbnails[item.id]; + return ( +
    +
    + {thumb ? ( + {item.name} + ) : ( + + )} +
    +
    + + {item.name} + + + {formatBytes(item.sizeBytes)} + +
    +
    + ); + })} +
    + ) : ( +
      + {items.map((item) => ( +
    • + + + +
      + + {item.name} + + + {formatBytes(item.sizeBytes)}, {formatRelativeTime(item.timestamp)} + +
      +
    • + ))} +
    + )} +
    +
    + ); +} diff --git a/apps/desktop/src/ClipboardHistoryDialog.tsx b/apps/desktop/src/ClipboardHistoryDialog.tsx new file mode 100644 index 0000000..9c4301c --- /dev/null +++ b/apps/desktop/src/ClipboardHistoryDialog.tsx @@ -0,0 +1,205 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +import { useEffect, useState } from "react"; +import { Check, Copy, Pin, PinOff, Search, Trash2, X } from "lucide-react"; +import { + clearClipboardHistory, + deleteClipboardClip, + errorMessage, + getClipboardHistory, + pinClipboardClip, +} from "./api.ts"; +import { formatRelativeTime } from "./format.ts"; +import type { ClipboardHistoryItem } from "./types.ts"; + +interface ClipboardHistoryDialogProps { + onClose: () => void; + onError: (message: string) => void; +} + +export function ClipboardHistoryDialog({ onClose, onError }: ClipboardHistoryDialogProps) { + const [clips, setClips] = useState([]); + const [search, setSearch] = useState(""); + const [copiedId, setCopiedId] = useState(null); + + useEffect(() => { + const handleKey = (e: KeyboardEvent) => { + if (e.key === "Escape") onClose(); + }; + window.addEventListener("keydown", handleKey); + return () => window.removeEventListener("keydown", handleKey); + }, [onClose]); + + const refresh = () => { + getClipboardHistory(100) + .then(setClips) + .catch((err) => onError(errorMessage(err))); + }; + + useEffect(() => { + refresh(); + }, []); + + const handleCopy = async (clip: ClipboardHistoryItem) => { + try { + await navigator.clipboard.writeText(clip.content); + setCopiedId(clip.id); + window.setTimeout(() => setCopiedId(null), 1500); + } catch { + onError("Couldn't copy text to clipboard."); + } + }; + + const handleTogglePin = async (clip: ClipboardHistoryItem) => { + try { + await pinClipboardClip(clip.id, !clip.isPinned); + setClips((prev) => + prev.map((c) => (c.id === clip.id ? { ...c, isPinned: !c.isPinned } : c)), + ); + } catch (err) { + onError(errorMessage(err)); + } + }; + + const handleDelete = async (id: number) => { + try { + await deleteClipboardClip(id); + setClips((prev) => prev.filter((c) => c.id !== id)); + } catch (err) { + onError(errorMessage(err)); + } + }; + + const handleClear = async () => { + try { + await clearClipboardHistory(); + refresh(); + } catch (err) { + onError(errorMessage(err)); + } + }; + + const filtered = clips.filter((c) => + c.content.toLowerCase().includes(search.toLowerCase()), + ); + + return ( +
    +
    e.stopPropagation()} + style={{ maxWidth: 640 }} + > +
    +
    +

    + Clipboard History +

    +

    Recent clips synced across your devices.

    +
    + +
    + +
    + + + +
    + + {filtered.length === 0 ? ( +
    +

    + {search ? `Nothing matches "${search}".` : "No clipboard history yet."} +

    +
    + ) : ( +
      + {filtered.map((clip) => { + const isCopied = copiedId === clip.id; + return ( +
    • +
      + + {clip.content} + + + {clip.originDevice} · {formatRelativeTime(clip.timestampMs)} + {clip.isPinned && " · Pinned"} + +
      + +
      + + + +
      +
    • + ); + })} +
    + )} +
    +
    + ); +} diff --git a/apps/desktop/src/api.ts b/apps/desktop/src/api.ts index bebce2c..dab8c9a 100644 --- a/apps/desktop/src/api.ts +++ b/apps/desktop/src/api.ts @@ -4,6 +4,8 @@ import { Channel, invoke } from "@tauri-apps/api/core"; import { listen, type UnlistenFn } from "@tauri-apps/api/event"; import type { + CatalogResponse, + ClipboardHistoryItem, DeviceIdentity, Grant, HistoryEntry, @@ -135,6 +137,54 @@ export const pressNotificationButton = (peerFingerprint: string, notificationId: export const dismissNotification = (peerFingerprint: string, notificationId: string) => invoke("dismiss_notification", { peerFingerprint, notificationId }); +export const ringPeer = (peerFingerprint: string, active: boolean) => + invoke("ring_peer", { peerFingerprint, active }); + +export const sendPcAction = (peerFingerprint: string, action: number) => + invoke("send_pc_action", { peerFingerprint, action }); + +export const queryFileCatalog = ( + peerFingerprint: string, + category: number, + limit: number = 50, + offset: number = 0, +) => + invoke("query_file_catalog", { + peerFingerprint, + category, + limit, + offset, + }); + +export const getCatalogThumbnail = ( + peerFingerprint: string, + itemId: string, + maxEdge: number = 256, +) => + invoke("get_catalog_thumbnail", { + peerFingerprint, + itemId, + maxEdge, + }); + +export const mountCloudFiles = (peerFingerprint: string) => + invoke("mount_cloud_files", { peerFingerprint }); + +export const openCloudFilesFolder = (peerFingerprint: string) => + invoke("open_cloud_files_folder", { peerFingerprint }); + +export const getClipboardHistory = (limit: number = 50) => + invoke("get_clipboard_history", { limit }); + +export const pinClipboardClip = (id: number, pinned: boolean) => + invoke("pin_clipboard_clip", { id, pinned }); + +export const deleteClipboardClip = (id: number) => + invoke("delete_clipboard_clip", { id }); + +export const clearClipboardHistory = () => + invoke("clear_clipboard_history"); + /** Commands reject with the backend's error string; anything else is unexpected. */ export function errorMessage(error: unknown): string { if (typeof error === "string") return error; diff --git a/apps/desktop/src/types.ts b/apps/desktop/src/types.ts index 46ae0a8..74d4d46 100644 --- a/apps/desktop/src/types.ts +++ b/apps/desktop/src/types.ts @@ -112,6 +112,11 @@ export const PERMISSIONS: Record 1: { label: "Files", description: "Send files to this computer" }, 2: { label: "Text", description: "Send copied text and links" }, 3: { label: "Notifications", description: "Show its notifications here" }, + 8: { label: "Ring device", description: "Sound alarm to locate misplaced device" }, + 9: { label: "PC control", description: "Remote lock, sleep, or mute control" }, + 10: { label: "Remote typing", description: "Dictation and keyboard input from phone" }, + 11: { label: "Macro deck", description: "Custom quick action shortcuts from phone" }, + 12: { label: "File catalog", description: "Browse photos, documents, and mount files" }, }; /** A notification from the phone, to read and act on here. */ @@ -138,3 +143,32 @@ export const isMac = export const MOD_KEY = isMac ? "⌘" : "Ctrl+"; export const MOD_SHIFT_KEY = isMac ? "⌘⇧" : "Ctrl+Shift+"; +export enum CatalogCategory { + Unspecified = 0, + Photos = 1, + Screenshots = 2, + Downloads = 3, + Documents = 4, +} + +export interface CatalogItem { + id: string; + name: string; + sizeBytes: number; + timestamp: number; + mimeType: string; +} + +export interface CatalogResponse { + items: CatalogItem[]; + totalCount: number; +} + +export interface ClipboardHistoryItem { + id: number; + timestampMs: number; + content: string; + isPinned: boolean; + originDevice: string; +} + From 3b47f5b4c223d37c9e4c5c514bc53e5279d43fd6 Mon Sep 17 00:00:00 2001 From: Samarth Rajesh Lad <142334685+samyyy2311@users.noreply.github.com> Date: Thu, 8 Oct 2026 18:27:09 +0530 Subject: [PATCH 09/14] feat: add Handoff support for active browser tabs and reading positions --- apps/desktop/src-tauri/src/main.rs | 122 ++++++++++++++++++++- apps/desktop/src/App.tsx | 121 +++++++++++++++++++- apps/desktop/src/HandoffCard.tsx | 102 +++++++++++++++++ apps/desktop/src/api.ts | 35 ++++++ apps/desktop/src/types.ts | 20 ++++ crates/sessions/src/capabilities_router.rs | 32 ++++++ 6 files changed, 426 insertions(+), 6 deletions(-) create mode 100644 apps/desktop/src/HandoffCard.tsx diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index 7f8fcc7..440ec98 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -112,6 +112,21 @@ pub struct DesktopRuntimeState { batteries: Batteries, clipboard_history: Arc, cloud_mounts: Arc>>>, + active_handoffs: Arc>>, +} + +#[derive(Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct HandoffItemDto { + pub handoff_id: String, + pub peer_id: String, + pub source_device_id: String, + pub handoff_type: i32, + pub title: String, + pub uri: String, + pub scroll_ratio: f32, + pub cursor_position: u64, + pub timestamp_ms: u64, } #[derive(Serialize)] @@ -331,6 +346,7 @@ fn session_handlers( pending_answers: PendingAnswers, clipboard: ClipboardSync, clipboard_history: Arc, + active_handoffs: Arc>>, app_handle: &AppHandle, ) -> sessions::SessionCapabilityHandlers { let mut handlers = sessions::SessionCapabilityHandlers::new(download_dir) @@ -429,6 +445,29 @@ fn session_handlers( notifications::Body::Action(_) => {} })); + let (app, handoffs_store) = (app_handle.clone(), active_handoffs.clone()); + handlers.on_handoff_received = Some(Arc::new(move |peer, item| { + let dto = HandoffItemDto { + handoff_id: item.handoff_id.clone(), + peer_id: peer.to_string(), + source_device_id: item.source_device_id, + handoff_type: item.handoff_type, + title: item.title, + uri: item.uri, + scroll_ratio: item.scroll_ratio, + cursor_position: item.cursor_position, + timestamp_ms: item.timestamp_ms, + }; + handoffs_store.lock().insert(item.handoff_id.clone(), dto.clone()); + let _ = app.emit("handoff-received", dto); + })); + + let (app, handoffs_store) = (app_handle.clone(), active_handoffs); + handlers.on_handoff_dismissed = Some(Arc::new(move |_peer, handoff_id| { + handoffs_store.lock().remove(&handoff_id); + let _ = app.emit("handoff-dismissed", handoff_id); + })); + handlers } @@ -1232,6 +1271,80 @@ fn clear_clipboard_history(state: State) -> Result) -> Vec { + state.active_handoffs.lock().values().cloned().collect() +} + +#[tauri::command] +async fn broadcast_handoff( + state: State<'_, DesktopRuntimeState>, + peer_fingerprint: String, + title: String, + uri: String, + handoff_type: i32, + scroll_ratio: f32, +) -> Result { + let mux = state + .device + .sessions + .get(&peer_fingerprint) + .ok_or_else(|| NOT_CONNECTED.to_string())?; + let query = CapabilityQuery::negotiated(CapabilityId::HANDOFF, true); + let now_ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0); + let handoff_id = format!("h-{now_ms}"); + let item = protocol::v1::HandoffItem { + handoff_id, + source_device_id: computer_name(), + handoff_type, + title, + uri, + scroll_ratio, + cursor_position: 0, + timestamp_ms: now_ms, + extra_payload: Vec::new(), + }; + let ack = mux + .broadcast_handoff_to_peer(item, &query) + .await + .map_err(user_error("Couldn't send handoff to device."))?; + Ok(ack.success) +} + +#[tauri::command] +async fn dismiss_handoff( + state: State<'_, DesktopRuntimeState>, + peer_fingerprint: String, + handoff_id: String, +) -> Result { + state.active_handoffs.lock().remove(&handoff_id); + if let Some(mux) = state.device.sessions.get(&peer_fingerprint) { + let query = CapabilityQuery::negotiated(CapabilityId::HANDOFF, true); + let _ = mux.dismiss_handoff_on_peer(handoff_id, &query).await; + } + Ok(true) +} + +#[tauri::command] +async fn open_handoff( + app: AppHandle, + state: State<'_, DesktopRuntimeState>, + peer_fingerprint: String, + handoff_id: String, + uri: String, +) -> Result<(), String> { + state.active_handoffs.lock().remove(&handoff_id); + let _ = app.opener().open_url(&uri, None::<&str>); + if let Some(mux) = state.device.sessions.get(&peer_fingerprint) { + let query = CapabilityQuery::negotiated(CapabilityId::HANDOFF, true); + let _ = mux.dismiss_handoff_on_peer(handoff_id, &query).await; + } + Ok(()) +} + fn initialize_desktop_runtime( app_handle: &AppHandle, db_path: &Path, @@ -1245,6 +1358,7 @@ fn initialize_desktop_runtime( db_path.with_file_name("continue_clipboard.db"), )?); let cloud_mounts = Arc::new(Mutex::new(HashMap::new())); + let active_handoffs = Arc::new(Mutex::new(HashMap::new())); let pending_answers = PendingAnswers::default(); let connected = Arc::new(tray::Connected::default()); @@ -1254,6 +1368,7 @@ fn initialize_desktop_runtime( pending_answers.clone(), clipboard.clone(), clipboard_history.clone(), + active_handoffs.clone(), app_handle, ); handlers.on_device_info = Some(device_info_listener( @@ -1281,6 +1396,7 @@ fn initialize_desktop_runtime( batteries, clipboard_history, cloud_mounts, + active_handoffs, }) } @@ -1397,7 +1513,11 @@ fn main() { get_clipboard_history, pin_clipboard_clip, delete_clipboard_clip, - clear_clipboard_history + clear_clipboard_history, + get_active_handoffs, + broadcast_handoff, + dismiss_handoff, + open_handoff ]) // Closing the window keeps Continue in the tray, still receiving. Quit is in the tray menu. .on_window_event(|window, event| { diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index fa848e7..3a3d122 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -42,12 +42,15 @@ import { open as openFileDialog } from "@tauri-apps/plugin-dialog"; import "./App.css"; import { ButtonGroup, ConnectionStatus, ProgressBar, Switch } from "./components.tsx"; import { + broadcastHandoff, cancelIncoming, clearHistory, connectToPeer, disconnectPeer, + dismissHandoff, reconnectPeer, errorMessage, + getActiveHandoffs, getAutostart, getDeviceIdentity, getHistory, @@ -55,10 +58,13 @@ import { getPermissions, getTrustedPeers, listIncoming, + onHandoffDismissed, + onHandoffReceived, onIncomingEnded, onIncomingProgress, onNotificationPosted, onNotificationRemoved, + openHandoff, openLink, openReceived, ringPeer, @@ -81,6 +87,7 @@ import { } from "./format.ts"; import { CatalogDialog } from "./CatalogDialog.tsx"; import { ClipboardHistoryDialog } from "./ClipboardHistoryDialog.tsx"; +import { HandoffCard } from "./HandoffCard.tsx"; import { NotificationList } from "./Notifications.tsx"; import { PairDialog } from "./PairDialog.tsx"; import { @@ -91,6 +98,7 @@ import { type HistoryEntry, GRANT_OPTIONS, type Grant, + type HandoffItem, type HistoryFilter, type IncomingTransfer, isMac, @@ -229,6 +237,7 @@ export default function App() { const [dragCount, setDragCount] = useState(null); const [textInput, setTextInput] = useState(""); const [notifications, setNotifications] = useState([]); + const [handoffs, setHandoffs] = useState([]); const selectedPeer = peers?.find((p) => p.fingerprint === selectedPeerId) ?? peers?.[0] ?? null; @@ -309,11 +318,12 @@ export default function App() { return; } let active = true; - Promise.all([getDeviceIdentity(), getTrustedPeers(), getHistory()]) - .then(([loadedIdentity, loadedPeers, history]) => { + Promise.all([getDeviceIdentity(), getTrustedPeers(), getHistory(), getActiveHandoffs()]) + .then(([loadedIdentity, loadedPeers, history, loadedHandoffs]) => { if (!active) return; setIdentity(loadedIdentity); setPeers(loadedPeers); + setHandoffs(loadedHandoffs); // Anything sent or coming in since the window opened stays on top. setActivity((live) => [...live, ...history.map(fromHistory)]); }) @@ -440,6 +450,17 @@ export default function App() { }), ); keep(unSynced); + + const unHandoffRecv = await onHandoffReceived((item) => { + setHandoffs((prev) => [item, ...prev.filter((h) => h.handoffId !== item.handoffId)]); + showToast(`Continue from ${item.sourceDeviceId || "device"}`); + }); + keep(unHandoffRecv); + + const unHandoffDismiss = await onHandoffDismissed((handoffId) => { + setHandoffs((prev) => prev.filter((h) => h.handoffId !== handoffId)); + }); + keep(unHandoffDismiss); } catch (error) { showError(errorMessage(error)); } @@ -662,12 +683,45 @@ export default function App() { } }; + const handleOpenHandoff = async (item: HandoffItem) => { + try { + const peerId = item.peerId || selectedPeer?.fingerprint || ""; + await openHandoff(peerId, item.handoffId, item.uri); + setHandoffs((prev) => prev.filter((h) => h.handoffId !== item.handoffId)); + showToast("Opened in browser"); + } catch (error) { + showError(errorMessage(error)); + } + }; + + const handleDismissHandoff = async (item: HandoffItem) => { + try { + const peerId = item.peerId || selectedPeer?.fingerprint || ""; + await dismissHandoff(peerId, item.handoffId); + setHandoffs((prev) => prev.filter((h) => h.handoffId !== item.handoffId)); + } catch (error) { + showError(errorMessage(error)); + } + }; + + const handleBroadcastHandoff = async (url: string) => { + const peer = readyPeer(); + if (!peer) return; + try { + await broadcastHandoff(peer.fingerprint, url, url, 1, 0); + showToast(`Sent to ${peer.displayName} to continue reading`); + } catch (error) { + showError(errorMessage(error)); + } + }; + const rowActions: RowActions = { retry: retryItem, copy: copyToClipboard, open: (path, reveal) => openReceived(path, reveal).catch((error) => showError(errorMessage(error))), openLink: (url) => openLink(url).catch((error) => showError(errorMessage(error))), cancelIncoming: (transferId) => cancelIncoming(transferId).catch((error) => showError(errorMessage(error))), + handoffLink: handleBroadcastHandoff, }; const chooseFilesRef = useRef(chooseFiles); @@ -796,6 +850,10 @@ export default function App() { textInput={textInput} onTextInputChange={setTextInput} onSendText={handleSendText} + handoffs={handoffs.filter((h) => !h.peerId || !selectedPeer || h.peerId === selectedPeer.fingerprint)} + onOpenHandoff={handleOpenHandoff} + onDismissHandoff={handleDismissHandoff} + onBroadcastHandoff={handleBroadcastHandoff} onConnect={(address) => selectedPeer && handleConnect(selectedPeer, address)} onReconnect={() => selectedPeer && handleReconnect(selectedPeer)} onDisconnect={() => selectedPeer && handleDisconnect(selectedPeer)} @@ -895,6 +953,7 @@ interface RowActions { open: (path: string, reveal: boolean) => void; openLink: (url: string) => void; cancelIncoming: (transferId: string) => void; + handoffLink?: (url: string) => void; } /** Under a day heading (`underDay`), older rows show the time rather than repeat the day. */ @@ -970,9 +1029,21 @@ function ActivityRow(props: { item: Activity; actions: RowActions; underDay?: bo )} {link && ( - + <> + + {actions.handoffLink && ( + + )} + )} @@ -993,6 +1064,10 @@ interface HomeViewProps { textInput: string; onTextInputChange: (val: string) => void; onSendText: () => void; + handoffs: HandoffItem[]; + onOpenHandoff: (item: HandoffItem) => void; + onDismissHandoff: (item: HandoffItem) => void; + onBroadcastHandoff: (url: string) => void; onConnect: (address: string) => void; onReconnect: () => void; onDisconnect: () => void; @@ -1018,6 +1093,10 @@ function HomeView(props: HomeViewProps) { isRinging, onToggleRing, textInput, + handoffs, + onOpenHandoff, + onDismissHandoff, + onBroadcastHandoff, } = props; const { onTextInputChange, onSendText, onConnect, onReconnect, onDisconnect, isConnecting } = props; const { activeTransfers, recentActivity, rowActions, onNavigateHistory, notifications, onError } = props; @@ -1097,6 +1176,22 @@ function HomeView(props: HomeViewProps) {
    + {online && handoffs.length > 0 && ( +
    +
    + {handoffs.map((item) => ( + + ))} +
    +
    + )} +
    {online && (
    @@ -1145,6 +1240,22 @@ function HomeView(props: HomeViewProps) { aria-label="Text to send" disabled={!online} /> + {online && linkIn(textInput) && ( + + )} diff --git a/apps/desktop/src/HandoffCard.tsx b/apps/desktop/src/HandoffCard.tsx new file mode 100644 index 0000000..04f1361 --- /dev/null +++ b/apps/desktop/src/HandoffCard.tsx @@ -0,0 +1,102 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +import { ExternalLink, FileText, Globe, MapPin, X } from "lucide-react"; +import { formatRelativeTime } from "./format.ts"; +import { HandoffType, type HandoffItem } from "./types.ts"; + +interface HandoffCardProps { + item: HandoffItem; + peerName: string; + onOpen: (item: HandoffItem) => void; + onDismiss: (item: HandoffItem) => void; +} + +export function HandoffCard({ item, peerName, onOpen, onDismiss }: HandoffCardProps) { + const getIcon = () => { + switch (item.handoffType) { + case HandoffType.Document: + return ; + case HandoffType.Map: + return ; + default: + return ; + } + }; + + const getDomain = (uri: string) => { + try { + return new URL(uri).hostname; + } catch { + return uri; + } + }; + + return ( +
    +
    +
    + {getIcon()} +
    + +
    + + Continue from {peerName} · {formatRelativeTime(item.timestampMs)} + + + {item.title || getDomain(item.uri)} + + + {getDomain(item.uri)} + +
    +
    + +
    + + +
    +
    + ); +} diff --git a/apps/desktop/src/api.ts b/apps/desktop/src/api.ts index dab8c9a..01218bb 100644 --- a/apps/desktop/src/api.ts +++ b/apps/desktop/src/api.ts @@ -8,6 +8,7 @@ import type { ClipboardHistoryItem, DeviceIdentity, Grant, + HandoffItem, HistoryEntry, IncomingTransfer, PeerPermission, @@ -185,6 +186,40 @@ export const deleteClipboardClip = (id: number) => export const clearClipboardHistory = () => invoke("clear_clipboard_history"); +export const getActiveHandoffs = () => + invoke("get_active_handoffs"); + +export const broadcastHandoff = ( + peerFingerprint: string, + title: string, + uri: string, + handoffType: number = 1, + scrollRatio: number = 0, +) => + invoke("broadcast_handoff", { + peerFingerprint, + title, + uri, + handoffType, + scrollRatio, + }); + +export const dismissHandoff = (peerFingerprint: string, handoffId: string) => + invoke("dismiss_handoff", { peerFingerprint, handoffId }); + +export const openHandoff = ( + peerFingerprint: string, + handoffId: string, + uri: string, +) => + invoke("open_handoff", { peerFingerprint, handoffId, uri }); + +export const onHandoffReceived = (handler: (item: HandoffItem) => void): Promise => + listen("handoff-received", (event) => handler(event.payload)); + +export const onHandoffDismissed = (handler: (handoffId: string) => void): Promise => + listen("handoff-dismissed", (event) => handler(event.payload)); + /** Commands reject with the backend's error string; anything else is unexpected. */ export function errorMessage(error: unknown): string { if (typeof error === "string") return error; diff --git a/apps/desktop/src/types.ts b/apps/desktop/src/types.ts index 74d4d46..b6d9010 100644 --- a/apps/desktop/src/types.ts +++ b/apps/desktop/src/types.ts @@ -112,6 +112,7 @@ export const PERMISSIONS: Record 1: { label: "Files", description: "Send files to this computer" }, 2: { label: "Text", description: "Send copied text and links" }, 3: { label: "Notifications", description: "Show its notifications here" }, + 6: { label: "Handoff", description: "Pick up open tabs, links, and documents" }, 8: { label: "Ring device", description: "Sound alarm to locate misplaced device" }, 9: { label: "PC control", description: "Remote lock, sleep, or mute control" }, 10: { label: "Remote typing", description: "Dictation and keyboard input from phone" }, @@ -172,3 +173,22 @@ export interface ClipboardHistoryItem { originDevice: string; } +export enum HandoffType { + Unspecified = 0, + Url = 1, + Document = 2, + Map = 3, +} + +export interface HandoffItem { + handoffId: string; + peerId: string; + sourceDeviceId: string; + handoffType: HandoffType; + title: string; + uri: string; + scrollRatio: number; + cursorPosition: number; + timestampMs: number; +} + diff --git a/crates/sessions/src/capabilities_router.rs b/crates/sessions/src/capabilities_router.rs index 5f36bbd..3bdd066 100644 --- a/crates/sessions/src/capabilities_router.rs +++ b/crates/sessions/src/capabilities_router.rs @@ -940,4 +940,36 @@ impl SessionMultiplexer { .request_thumbnail(&mut send, &mut recv, req, capability_query) .await } + + pub async fn broadcast_handoff_to_peer( + &self, + item: protocol::v1::HandoffItem, + query: &CapabilityQuery, + ) -> Result { + let (mut send, mut recv) = self + .open_stream(CapabilityId::HANDOFF) + .await + .map_err(crate::error::SessionError::Transport)?; + + let dispatcher = HandoffDispatcher::new(); + dispatcher + .broadcast_handoff(&mut send, &mut recv, item, query) + .await + } + + pub async fn dismiss_handoff_on_peer( + &self, + handoff_id: String, + query: &CapabilityQuery, + ) -> Result { + let (mut send, mut recv) = self + .open_stream(CapabilityId::HANDOFF) + .await + .map_err(crate::error::SessionError::Transport)?; + + let dispatcher = HandoffDispatcher::new(); + dispatcher + .dismiss_handoff(&mut send, &mut recv, handoff_id, query) + .await + } } From 4c0cbf9f27ed8c212656a322149222e3726c8569 Mon Sep 17 00:00:00 2001 From: Samarth Rajesh Lad <142334685+samyyy2311@users.noreply.github.com> Date: Thu, 8 Oct 2026 18:58:13 +0530 Subject: [PATCH 10/14] feat: add Send Later offline queue, one-tap lockdown mode, and drop folder sync --- apps/desktop/src-tauri/src/main.rs | 274 +++++++++++++++++++++- apps/desktop/src/App.tsx | 353 ++++++++++++++++++++++++++--- apps/desktop/src/api.ts | 34 +++ apps/desktop/src/types.ts | 8 + 4 files changed, 641 insertions(+), 28 deletions(-) diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index 440ec98..7fd8f54 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -29,6 +29,8 @@ use permissions::PermissionState; use protocol::v1::{CatalogQuery, PcAction, PcActionRequest, RingRequest, ThumbnailRequest}; use protocol::CapabilityId; use sessions::{PermissionDecision, SessionState}; +use transfer::drop_folder::{DropFolderConfig, DropFolderWatcher}; +use transfer::queue::{OfflineTransferQueue, QueuedPayload, QueuedTransfer}; use transfer::TransferError; /// Logs what actually went wrong and gives the UI a sentence a person can act on. @@ -113,6 +115,8 @@ pub struct DesktopRuntimeState { clipboard_history: Arc, cloud_mounts: Arc>>>, active_handoffs: Arc>>, + offline_queue: Arc, + drop_folder: Arc>>, } #[derive(Serialize, Deserialize, Clone)] @@ -609,6 +613,56 @@ fn pending_permission_questions(state: State) -> Vec { + let location = Some(path.to_string_lossy().into_owned()); + let _ = state + .device + .send_file(peer_fingerprint, &path, location, None::) + .await; + } + QueuedPayload::Clipboard { content, .. } => { + if let Ok(text) = String::from_utf8(content) { + let _ = push_text(&state.device, peer_fingerprint, text).await; + } + } + QueuedPayload::Handoff { uri, title } => { + if let Some(mux) = state.device.sessions.get(peer_fingerprint) { + let query = CapabilityQuery::negotiated(CapabilityId::HANDOFF, true); + let now_ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0); + let handoff_item = protocol::v1::HandoffItem { + handoff_id: format!("h-{now_ms}"), + source_device_id: computer_name(), + handoff_type: 1, + title: title.unwrap_or_else(|| uri.clone()), + uri, + scroll_ratio: 0.0, + cursor_position: 0, + timestamp_ms: now_ms, + extra_payload: Vec::new(), + }; + let _ = mux.broadcast_handoff_to_peer(handoff_item, &query).await; + } + } + } + } + let _ = app.emit("queued-transfers-changed", peer_fingerprint); +} + fn session_state_listener( app_handle: AppHandle, stores: Stores, @@ -633,6 +687,14 @@ fn session_state_listener( "displayName": name, }), ); + let app = app_handle.clone(); + let peer_fp = peer.to_string(); + tokio::spawn(async move { + tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; + if let Some(state) = app.try_state::() { + flush_offline_transfers(&app, &state, &peer_fp).await; + } + }); } }) } @@ -1345,6 +1407,159 @@ async fn open_handoff( Ok(()) } +#[derive(Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct QueuedTransferDto { + pub id: String, + pub peer_id: String, + pub kind: String, + pub label: String, + pub queued_at: u64, +} + +impl From<&QueuedTransfer> for QueuedTransferDto { + fn from(q: &QueuedTransfer) -> Self { + let (kind, label) = match &q.payload { + QueuedPayload::File { relative_name, .. } => { + ("file".to_string(), relative_name.clone()) + } + QueuedPayload::Clipboard { content, .. } => { + let text = String::from_utf8_lossy(content).to_string(); + ("text".to_string(), text) + } + QueuedPayload::Handoff { uri, title } => { + ("handoff".to_string(), title.clone().unwrap_or_else(|| uri.clone())) + } + }; + Self { + id: q.id.clone(), + peer_id: q.peer_fingerprint.clone(), + kind, + label, + queued_at: q.queued_at, + } + } +} + +#[tauri::command] +fn queue_offline_file( + app: AppHandle, + state: State<'_, DesktopRuntimeState>, + peer_fingerprint: String, + file_path: String, +) -> Result { + let path = PathBuf::from(&file_path); + let relative_name = path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("file") + .to_string(); + let payload = QueuedPayload::File { + path, + relative_name, + mime_type: None, + }; + let id = state + .offline_queue + .enqueue(&peer_fingerprint, payload) + .map_err(|e| e.to_string())?; + let _ = app.emit("queued-transfers-changed", &peer_fingerprint); + Ok(id) +} + +#[tauri::command] +fn queue_offline_text( + app: AppHandle, + state: State<'_, DesktopRuntimeState>, + peer_fingerprint: String, + text: String, +) -> Result { + let payload = QueuedPayload::Clipboard { + content: text.into_bytes(), + mime_type: "text/plain".to_string(), + }; + let id = state + .offline_queue + .enqueue(&peer_fingerprint, payload) + .map_err(|e| e.to_string())?; + let _ = app.emit("queued-transfers-changed", &peer_fingerprint); + Ok(id) +} + +#[tauri::command] +fn get_queued_transfers( + state: State<'_, DesktopRuntimeState>, + peer_fingerprint: String, +) -> Vec { + state + .offline_queue + .peek_for_peer(&peer_fingerprint) + .iter() + .map(QueuedTransferDto::from) + .collect() +} + +#[tauri::command] +fn remove_queued_transfer( + app: AppHandle, + state: State<'_, DesktopRuntimeState>, + peer_fingerprint: String, + item_id: String, +) -> bool { + let removed = state.offline_queue.remove_item(&peer_fingerprint, &item_id); + if removed { + let _ = app.emit("queued-transfers-changed", &peer_fingerprint); + } + removed +} + +#[tauri::command] +fn clear_queued_transfers( + app: AppHandle, + state: State<'_, DesktopRuntimeState>, + peer_fingerprint: String, +) -> usize { + let cleared = state.offline_queue.clear_peer(&peer_fingerprint); + if cleared > 0 { + let _ = app.emit("queued-transfers-changed", &peer_fingerprint); + } + cleared +} + +#[tauri::command] +fn set_lockdown_mode( + app: AppHandle, + state: State<'_, DesktopRuntimeState>, + active: bool, +) { + state.device.stores.permissions.set_lockdown(active); + let _ = app.emit("lockdown-changed", active); +} + +#[tauri::command] +fn is_lockdown_mode(state: State<'_, DesktopRuntimeState>) -> bool { + state.device.stores.permissions.is_locked_down() +} + +#[tauri::command] +fn get_drop_folder(state: State<'_, DesktopRuntimeState>) -> Option { + state + .drop_folder + .lock() + .as_ref() + .map(|p| p.to_string_lossy().into_owned()) +} + +#[tauri::command] +fn set_drop_folder( + state: State<'_, DesktopRuntimeState>, + folder_path: Option, +) -> Result<(), String> { + let mut lock = state.drop_folder.lock(); + *lock = folder_path.map(PathBuf::from); + Ok(()) +} + fn initialize_desktop_runtime( app_handle: &AppHandle, db_path: &Path, @@ -1359,6 +1574,52 @@ fn initialize_desktop_runtime( )?); let cloud_mounts = Arc::new(Mutex::new(HashMap::new())); let active_handoffs = Arc::new(Mutex::new(HashMap::new())); + let offline_queue = Arc::new(OfflineTransferQueue::new()); + let drop_folder: Arc>> = Arc::new(Mutex::new(None)); + + let (offline_queue_for_drop, drop_folder_for_loop, app_for_drop) = ( + offline_queue.clone(), + drop_folder.clone(), + app_handle.clone(), + ); + tokio::spawn(async move { + loop { + tokio::time::sleep(tokio::time::Duration::from_secs(3)).await; + let folder_opt = drop_folder_for_loop.lock().clone(); + if let Some(folder) = folder_opt { + if folder.is_dir() { + if let Some(state) = app_for_drop.try_state::() { + let connected_peer = state + .device + .stores + .trust + .list_peers() + .ok() + .and_then(|peers| { + peers + .into_iter() + .find(|p| state.device.sessions.get(&p.fingerprint).is_some()) + }); + if let Some(peer) = connected_peer { + let config = DropFolderConfig::new( + folder.clone(), + peer.fingerprint.clone(), + ); + let watcher = DropFolderWatcher::new( + config, + offline_queue_for_drop.clone(), + ); + if let Ok(enqueued) = watcher.scan_directory() { + if !enqueued.is_empty() { + flush_offline_transfers(&app_for_drop, &state, &peer.fingerprint).await; + } + } + } + } + } + } + } + }); let pending_answers = PendingAnswers::default(); let connected = Arc::new(tray::Connected::default()); @@ -1397,6 +1658,8 @@ fn initialize_desktop_runtime( clipboard_history, cloud_mounts, active_handoffs, + offline_queue, + drop_folder, }) } @@ -1517,7 +1780,16 @@ fn main() { get_active_handoffs, broadcast_handoff, dismiss_handoff, - open_handoff + open_handoff, + queue_offline_file, + queue_offline_text, + get_queued_transfers, + remove_queued_transfer, + clear_queued_transfers, + set_lockdown_mode, + is_lockdown_mode, + get_drop_folder, + set_drop_folder ]) // Closing the window keeps Continue in the tray, still receiving. Quit is in the tray menu. .on_window_event(|window, event| { diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index 3a3d122..8d6ef53 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -10,6 +10,7 @@ import { CheckCheck, CircleAlert, ClipboardPaste, + Clock, Code, Copy, File, @@ -29,6 +30,7 @@ import { Search, Send, Settings, + ShieldAlert, Smartphone, Trash2, Type, @@ -45,6 +47,7 @@ import { broadcastHandoff, cancelIncoming, clearHistory, + clearQueuedTransfers, connectToPeer, disconnectPeer, dismissHandoff, @@ -53,23 +56,32 @@ import { getActiveHandoffs, getAutostart, getDeviceIdentity, + getDropFolder, getHistory, + getQueuedTransfers, getSaveFolder, getPermissions, getTrustedPeers, + isLockdownMode, listIncoming, onHandoffDismissed, onHandoffReceived, onIncomingEnded, onIncomingProgress, + onLockdownChanged, onNotificationPosted, onNotificationRemoved, + onQueuedTransfersChanged, openHandoff, openLink, openReceived, + queueOfflineFile, + queueOfflineText, ringPeer, savePastedFile, setAutostart, + setDropFolder, + setLockdownMode, setSaveFolder, setClipboardSyncEnabled, removeTrustedPeer, @@ -107,6 +119,7 @@ import { type PeerPermission, type PhoneNotification, PERMISSIONS, + type QueuedTransfer, type Theme, type Toast, type TrustedPeer, @@ -238,6 +251,9 @@ export default function App() { const [textInput, setTextInput] = useState(""); const [notifications, setNotifications] = useState([]); const [handoffs, setHandoffs] = useState([]); + const [isLockdown, setIsLockdown] = useState(false); + const [dropFolder, setDropFolderState] = useState(null); + const [queuedTransfers, setQueuedTransfers] = useState([]); const selectedPeer = peers?.find((p) => p.fingerprint === selectedPeerId) ?? peers?.[0] ?? null; @@ -318,12 +334,21 @@ export default function App() { return; } let active = true; - Promise.all([getDeviceIdentity(), getTrustedPeers(), getHistory(), getActiveHandoffs()]) - .then(([loadedIdentity, loadedPeers, history, loadedHandoffs]) => { + Promise.all([ + getDeviceIdentity(), + getTrustedPeers(), + getHistory(), + getActiveHandoffs(), + isLockdownMode(), + getDropFolder(), + ]) + .then(([loadedIdentity, loadedPeers, history, loadedHandoffs, lockdownState, folderState]) => { if (!active) return; setIdentity(loadedIdentity); setPeers(loadedPeers); setHandoffs(loadedHandoffs); + setIsLockdown(lockdownState); + setDropFolderState(folderState); // Anything sent or coming in since the window opened stays on top. setActivity((live) => [...live, ...history.map(fromHistory)]); }) @@ -333,6 +358,14 @@ export default function App() { }; }, []); + useEffect(() => { + if (selectedPeer) { + getQueuedTransfers(selectedPeer.fingerprint).then(setQueuedTransfers).catch(() => {}); + } else { + setQueuedTransfers([]); + } + }, [selectedPeer?.fingerprint]); + useEffect(() => { if (!isTauri()) return; const cleanups: (() => void)[] = []; @@ -461,6 +494,16 @@ export default function App() { setHandoffs((prev) => prev.filter((h) => h.handoffId !== handoffId)); }); keep(unHandoffDismiss); + + const unLockdown = await onLockdownChanged((active) => setIsLockdown(active)); + keep(unLockdown); + + const unQueue = await onQueuedTransfersChanged((peerId) => { + if (selectedPeerId === peerId) { + getQueuedTransfers(peerId).then(setQueuedTransfers).catch(() => {}); + } + }); + keep(unQueue); } catch (error) { showError(errorMessage(error)); } @@ -612,30 +655,65 @@ export default function App() { setDragCount(null); if (payload.type === "drop" && payload.paths.length > 0) { setView("transfer"); - sendFilesRef.current(payload.paths); + if (selectedPeer?.isConnected) { + sendFilesRef.current(payload.paths); + } else if (selectedPeer) { + const peer = selectedPeer; + (async () => { + for (const p of payload.paths) { + await queueOfflineFile(peer.fingerprint, p); + } + const updated = await getQueuedTransfers(peer.fingerprint); + setQueuedTransfers(updated); + showToast(`Queued ${payload.paths.length} file(s) for ${peer.displayName}`); + })(); + } } }); return () => { unlisten.then((fn) => fn()); }; - }, []); + }, [selectedPeer]); const chooseFiles = async () => { - if (!readyPeer()) return; + if (!selectedPeer) { + showError("Pair your phone first."); + return; + } const picked = await openFileDialog({ multiple: true, directory: false }); if (picked) { const paths = Array.isArray(picked) ? picked : [picked]; - sendFiles(paths); + if (selectedPeer.isConnected) { + sendFiles(paths); + } else { + for (const p of paths) { + await queueOfflineFile(selectedPeer.fingerprint, p); + } + const updated = await getQueuedTransfers(selectedPeer.fingerprint); + setQueuedTransfers(updated); + showToast(`Queued ${paths.length} file(s) for ${selectedPeer.displayName}`); + } } }; const handleSendText = async () => { const text = textInput.trim(); - const peer = readyPeer(); - if (!peer || !text) return; + if (!selectedPeer || !text) return; setTextInput(""); - const sent = await sendText(peer, text); - if (!sent) setTextInput(text); + if (selectedPeer.isConnected) { + const sent = await sendText(selectedPeer, text); + if (!sent) setTextInput(text); + } else { + try { + await queueOfflineText(selectedPeer.fingerprint, text); + const updated = await getQueuedTransfers(selectedPeer.fingerprint); + setQueuedTransfers(updated); + showToast(`Queued text for ${selectedPeer.displayName}`); + } catch (error) { + showError(errorMessage(error)); + setTextInput(text); + } + } }; const handleSendClipboard = async () => { @@ -659,18 +737,79 @@ export default function App() { const files = Array.from(data.files); const text = data.getData("text/plain").trim(); if (files.length === 0 && !text) return; - const peer = readyPeer(); - if (!peer) return; - if (files.length === 0) { - await sendText(peer, text); - return; + if (!selectedPeer) return; + if (selectedPeer.isConnected) { + if (files.length === 0) { + await sendText(selectedPeer, text); + return; + } + for (const file of files) { + try { + await sendFile(selectedPeer, await savePastedFile(file, pastedName(file))); + } catch (error) { + showError(errorMessage(error)); + } + } + } else { + if (text) { + await queueOfflineText(selectedPeer.fingerprint, text); + } + for (const file of files) { + try { + const saved = await savePastedFile(file, pastedName(file)); + await queueOfflineFile(selectedPeer.fingerprint, saved); + } catch (error) { + showError(errorMessage(error)); + } + } + const updated = await getQueuedTransfers(selectedPeer.fingerprint); + setQueuedTransfers(updated); + showToast(`Queued for ${selectedPeer.displayName}`); } - for (const file of files) { - try { - await sendFile(peer, await savePastedFile(file, pastedName(file))); - } catch (error) { - showError(errorMessage(error)); + }; + + const handleClearQueuedTransfers = async () => { + if (!selectedPeer) return; + try { + await clearQueuedTransfers(selectedPeer.fingerprint); + setQueuedTransfers([]); + showToast("Cleared queued transfers"); + } catch (error) { + showError(errorMessage(error)); + } + }; + + const handleToggleLockdown = async () => { + try { + const next = !isLockdown; + await setLockdownMode(next); + setIsLockdown(next); + showToast(next ? "Lockdown active: all capabilities paused" : "Lockdown turned off"); + } catch (error) { + showError(errorMessage(error)); + } + }; + + const handleChooseDropFolder = async () => { + try { + const picked = await openFileDialog({ directory: true, multiple: false }); + if (typeof picked === "string") { + await setDropFolder(picked); + setDropFolderState(picked); + showToast("Drop folder configured"); } + } catch (error) { + showError(errorMessage(error)); + } + }; + + const handleClearDropFolder = async () => { + try { + await setDropFolder(null); + setDropFolderState(null); + showToast("Drop folder disabled"); + } catch (error) { + showError(errorMessage(error)); } }; @@ -864,6 +1003,10 @@ export default function App() { onError={showError} rowActions={rowActions} onNavigateHistory={() => setView("history")} + isLockdown={isLockdown} + onToggleLockdown={handleToggleLockdown} + queuedTransfers={queuedTransfers} + onClearQueuedTransfers={handleClearQueuedTransfers} /> )} @@ -900,6 +1043,11 @@ export default function App() { onOpenClipboardHistory={() => setShowClipboardDialog(true)} onError={showError} onOpenFolder={(folder) => rowActions.open(folder, false)} + isLockdown={isLockdown} + onToggleLockdown={handleToggleLockdown} + dropFolder={dropFolder} + onChooseDropFolder={handleChooseDropFolder} + onClearDropFolder={handleClearDropFolder} /> )}
    @@ -910,9 +1058,13 @@ export default function App() {

    - {selectedPeer?.isConnected ? `Drop to send to ${selectedPeer.displayName}` : "Connect your phone first"} + {selectedPeer + ? selectedPeer.isConnected + ? `Drop to send to ${selectedPeer.displayName}` + : `Drop to queue for ${selectedPeer.displayName}` + : "Connect your phone first"}

    - {selectedPeer?.isConnected && dragCount > 0 && ( + {selectedPeer && dragCount > 0 && (

    {dragCount === 1 ? "1 file" : `${dragCount} files`}

    )}
    @@ -1078,6 +1230,10 @@ interface HomeViewProps { onNavigateHistory: () => void; notifications: PhoneNotification[]; onError: (message: string) => void; + isLockdown: boolean; + onToggleLockdown: () => void; + queuedTransfers: QueuedTransfer[]; + onClearQueuedTransfers: () => void; } function HomeView(props: HomeViewProps) { @@ -1097,6 +1253,10 @@ function HomeView(props: HomeViewProps) { onOpenHandoff, onDismissHandoff, onBroadcastHandoff, + isLockdown, + onToggleLockdown, + queuedTransfers, + onClearQueuedTransfers, } = props; const { onTextInputChange, onSendText, onConnect, onReconnect, onDisconnect, isConnecting } = props; const { activeTransfers, recentActivity, rowActions, onNavigateHistory, notifications, onError } = props; @@ -1176,6 +1336,80 @@ function HomeView(props: HomeViewProps) {
    + {isLockdown && ( +
    +
    +
    + +
    + + Lockdown mode active + + + All permissions and transfers are paused. + +
    +
    + +
    +
    + )} + + {queuedTransfers.length > 0 && ( +
    +
    +
    + +
    + + {queuedTransfers.length === 1 + ? "1 item queued" + : `${queuedTransfers.length} items queued`} + + + Will send automatically when {peer.displayName} connects. + +
    +
    + +
    +
    + )} + {online && handoffs.length > 0 && (
    @@ -1193,7 +1427,7 @@ function HomeView(props: HomeViewProps) { )}
    - {online && ( + {online ? (
    + ) : ( +
    + +
    )} { e.preventDefault(); onSendText(); @@ -1236,9 +1477,8 @@ function HomeView(props: HomeViewProps) { onTextInputChange(e.target.value)} - placeholder={online ? `Send text to ${peer.displayName}` : "Connect to send text"} + placeholder={online ? `Send text to ${peer.displayName}` : `Queue text for ${peer.displayName}`} aria-label="Text to send" - disabled={!online} /> {online && linkIn(textInput) && ( @@ -1562,6 +1802,11 @@ interface SettingsViewProps { accent: AccentName; onThemeChange: (theme: Theme) => void; onAccentChange: (accent: AccentName) => void; + isLockdown: boolean; + onToggleLockdown: () => void; + dropFolder: string | null; + onChooseDropFolder: () => void; + onClearDropFolder: () => void; } const THEME_OPTIONS = [ @@ -1581,6 +1826,11 @@ function SettingsView(props: SettingsViewProps) { onClipboardSyncChange, onOpenClipboardHistory, onError, + isLockdown, + onToggleLockdown, + dropFolder, + onChooseDropFolder, + onClearDropFolder, } = props; const { onOpenFolder } = props; const [appVersion, setAppVersion] = useState(""); @@ -1687,6 +1937,55 @@ function SettingsView(props: SettingsViewProps) {
    +
  • +
    + Drop folder + + {dropFolder + ? dropFolder + : "Files added to this folder are sent automatically to connected devices."} + +
    +
    + {dropFolder ? ( + <> + + + + + ) : ( + + )} +
    +
  • + + +

    Privacy & security

    +
      +
    • +
      + + Lockdown mode + + + Pause all incoming and outgoing transfers and capability requests immediately. + +
      + +

    Clipboard

    diff --git a/apps/desktop/src/api.ts b/apps/desktop/src/api.ts index 01218bb..7395352 100644 --- a/apps/desktop/src/api.ts +++ b/apps/desktop/src/api.ts @@ -15,6 +15,7 @@ import type { PermissionAnswer, PermissionQuestion, PhoneNotification, + QueuedTransfer, TrustedPeer, } from "./types.ts"; @@ -220,6 +221,39 @@ export const onHandoffReceived = (handler: (item: HandoffItem) => void): Promise export const onHandoffDismissed = (handler: (handoffId: string) => void): Promise => listen("handoff-dismissed", (event) => handler(event.payload)); +export const queueOfflineFile = (peerFingerprint: string, filePath: string) => + invoke("queue_offline_file", { peerFingerprint, filePath }); + +export const queueOfflineText = (peerFingerprint: string, text: string) => + invoke("queue_offline_text", { peerFingerprint, text }); + +export const getQueuedTransfers = (peerFingerprint: string) => + invoke("get_queued_transfers", { peerFingerprint }); + +export const removeQueuedTransfer = (peerFingerprint: string, itemId: string) => + invoke("remove_queued_transfer", { peerFingerprint, itemId }); + +export const clearQueuedTransfers = (peerFingerprint: string) => + invoke("clear_queued_transfers", { peerFingerprint }); + +export const setLockdownMode = (active: boolean) => + invoke("set_lockdown_mode", { active }); + +export const isLockdownMode = () => + invoke("is_lockdown_mode"); + +export const getDropFolder = () => + invoke("get_drop_folder"); + +export const setDropFolder = (folderPath: string | null) => + invoke("set_drop_folder", { folderPath }); + +export const onQueuedTransfersChanged = (handler: (peerId: string) => void): Promise => + listen("queued-transfers-changed", (event) => handler(event.payload)); + +export const onLockdownChanged = (handler: (active: boolean) => void): Promise => + listen("lockdown-changed", (event) => handler(event.payload)); + /** Commands reject with the backend's error string; anything else is unexpected. */ export function errorMessage(error: unknown): string { if (typeof error === "string") return error; diff --git a/apps/desktop/src/types.ts b/apps/desktop/src/types.ts index b6d9010..ecc1c4e 100644 --- a/apps/desktop/src/types.ts +++ b/apps/desktop/src/types.ts @@ -192,3 +192,11 @@ export interface HandoffItem { timestampMs: number; } +export interface QueuedTransfer { + id: string; + peerId: string; + kind: "file" | "text" | "handoff"; + label: string; + queuedAt: number; +} + From 07bb11269be79cd9952f9afa3b7ce3d1e11c6a74 Mon Sep 17 00:00:00 2001 From: Samarth Rajesh Lad <142334685+samyyy2311@users.noreply.github.com> Date: Thu, 8 Oct 2026 23:14:57 +0530 Subject: [PATCH 11/14] feat: add DeX-on-PC desktop and app streaming capability (CapabilityId 13) --- apps/desktop/src-tauri/src/main.rs | 262 +++++++++++++- apps/desktop/src/App.tsx | 22 ++ apps/desktop/src/DesktopStreamDialog.tsx | 379 +++++++++++++++++++++ apps/desktop/src/api.ts | 42 +++ apps/desktop/src/types.ts | 31 ++ crates/limits/src/lib.rs | 11 + crates/protocol/build.rs | 1 + crates/protocol/src/capability.rs | 2 + crates/sessions/src/capabilities_router.rs | 162 +++++++++ crates/sessions/src/desktop_stream.rs | 321 +++++++++++++++++ crates/sessions/src/error.rs | 3 + crates/sessions/src/lib.rs | 9 +- proto/desktop_stream.proto | 105 ++++++ 13 files changed, 1346 insertions(+), 4 deletions(-) create mode 100644 apps/desktop/src/DesktopStreamDialog.tsx create mode 100644 crates/sessions/src/desktop_stream.rs create mode 100644 proto/desktop_stream.proto diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index 7fd8f54..6ac3fc8 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -117,6 +117,43 @@ pub struct DesktopRuntimeState { active_handoffs: Arc>>, offline_queue: Arc, drop_folder: Arc>>, + active_desktop_streams: Arc>>, +} + +#[derive(Clone)] +pub struct DesktopStreamSession { + pub session_id: String, + pub peer_fingerprint: String, + pub package_name: Option, + pub width: u32, + pub height: u32, + pub dpi: u32, +} + +#[derive(Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct DesktopStreamInfoDto { + pub session_id: String, + pub peer_fingerprint: String, + pub package_name: Option, + pub width: u32, + pub height: u32, + pub dpi: u32, + pub status: String, +} + +#[derive(Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct DesktopInputDto { + pub session_id: String, + pub event_type: String, + pub x: u32, + pub y: u32, + pub button: Option, + pub key_code: Option, + pub scroll_dx: Option, + pub scroll_dy: Option, + pub key_text: Option, } #[derive(Serialize, Deserialize, Clone)] @@ -344,6 +381,7 @@ fn shown_name(name: String) -> String { } } +#[allow(clippy::too_many_arguments)] fn session_handlers( download_dir: PathBuf, stores: &Stores, @@ -351,6 +389,7 @@ fn session_handlers( clipboard: ClipboardSync, clipboard_history: Arc, active_handoffs: Arc>>, + active_desktop_streams: Arc>>, app_handle: &AppHandle, ) -> sessions::SessionCapabilityHandlers { let mut handlers = sessions::SessionCapabilityHandlers::new(download_dir) @@ -472,6 +511,35 @@ fn session_handlers( let _ = app.emit("handoff-dismissed", handoff_id); })); + let (streams_for_ctl, app_for_ctl) = (active_desktop_streams.clone(), app_handle.clone()); + handlers.on_desktop_control = Some(Arc::new(move |_peer, ctl| { + if ctl.action == protocol::v1::DesktopControlAction::DesktopControlStop as i32 { + streams_for_ctl.lock().remove(&ctl.session_id); + let _ = app_for_ctl.emit("desktop-stream-stopped", &ctl.session_id); + } + protocol::v1::DesktopStreamAck { + session_id: ctl.session_id, + success: true, + error_message: String::new(), + } + })); + + let app_for_frame = app_handle.clone(); + handlers.on_desktop_frame = Some(Arc::new(move |_peer, frame| { + use base64::Engine; + let b64 = base64::engine::general_purpose::STANDARD.encode(&frame.data); + let _ = app_for_frame.emit( + "desktop-stream-frame", + serde_json::json!({ + "sessionId": frame.session_id, + "frameIndex": frame.frame_index, + "timestampUs": frame.timestamp_us, + "isKeyframe": frame.is_keyframe, + "data": b64, + }), + ); + })); + handlers } @@ -829,6 +897,7 @@ fn get_permissions( CapabilityId::FILE_TRANSFER, CapabilityId::CLIPBOARD, CapabilityId::NOTIFICATIONS, + CapabilityId::DESKTOP_STREAM, ] .into_iter() .map(|capability| { @@ -1560,6 +1629,189 @@ fn set_drop_folder( Ok(()) } +#[tauri::command] +async fn start_desktop_stream( + app: AppHandle, + state: State<'_, DesktopRuntimeState>, + peer_fingerprint: String, + package_name: Option, + width: u32, + height: u32, + dpi: u32, +) -> Result { + let mux = state + .device + .sessions + .get(&peer_fingerprint) + .ok_or_else(|| "Peer is not connected".to_string())?; + + if state.device.stores.permissions.is_locked_down() { + return Err("Device is in lockdown mode".into()); + } + let grant = state + .device + .stores + .permissions + .query_state(&peer_fingerprint, CapabilityId::DESKTOP_STREAM) + .unwrap_or(PermissionState::Allow); + if grant == PermissionState::Deny { + return Err("Desktop streaming capability is blocked for this peer".into()); + } + + let now_ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis()) + .unwrap_or(0); + let session_id = format!("dstream-{now_ms}"); + + let req = protocol::v1::DesktopStreamStartRequest { + session_id: session_id.clone(), + target_package_name: package_name.clone().unwrap_or_default(), + requested_width: width, + requested_height: height, + requested_dpi: dpi, + max_fps: 60, + preferred_codec: protocol::v1::StreamCodec::H264 as i32, + }; + + let query = CapabilityQuery::negotiated(CapabilityId::DESKTOP_STREAM, true); + let resp = mux + .start_desktop_stream_on_peer(req, &query) + .await + .map_err(|e| e.to_string())?; + + let info = DesktopStreamInfoDto { + session_id: session_id.clone(), + peer_fingerprint: peer_fingerprint.clone(), + package_name: package_name.clone(), + width: if resp.actual_width > 0 { + resp.actual_width + } else { + width + }, + height: if resp.actual_height > 0 { + resp.actual_height + } else { + height + }, + dpi: if resp.actual_dpi > 0 { + resp.actual_dpi + } else { + dpi + }, + status: "active".into(), + }; + + let session = DesktopStreamSession { + session_id: session_id.clone(), + peer_fingerprint, + package_name, + width: info.width, + height: info.height, + dpi: info.dpi, + }; + + state.active_desktop_streams.lock().insert(session_id, session); + let _ = app.emit("desktop-stream-started", &info); + + Ok(info) +} + +#[tauri::command] +async fn stop_desktop_stream( + app: AppHandle, + state: State<'_, DesktopRuntimeState>, + session_id: String, +) -> Result<(), String> { + let session = state.active_desktop_streams.lock().remove(&session_id); + + if let Some(sess) = session { + if let Some(mux) = state.device.sessions.get(&sess.peer_fingerprint) { + let ctl = protocol::v1::DesktopStreamControl { + session_id: session_id.clone(), + action: protocol::v1::DesktopControlAction::DesktopControlStop as i32, + new_width: 0, + new_height: 0, + new_dpi: 0, + }; + let query = CapabilityQuery::negotiated(CapabilityId::DESKTOP_STREAM, true); + let _ = mux.send_desktop_control_to_peer(ctl, &query).await; + } + let _ = app.emit("desktop-stream-stopped", &session_id); + } + + Ok(()) +} + +#[tauri::command] +async fn send_desktop_input( + state: State<'_, DesktopRuntimeState>, + event: DesktopInputDto, +) -> Result<(), String> { + let peer_fingerprint = { + let lock = state.active_desktop_streams.lock(); + let sess = lock + .get(&event.session_id) + .ok_or("Stream session not found")?; + sess.peer_fingerprint.clone() + }; + + let mux = state + .device + .sessions + .get(&peer_fingerprint) + .ok_or_else(|| "Peer is not connected".to_string())?; + + let event_type = match event.event_type.as_str() { + "pointer_down" => protocol::v1::DesktopInputEventType::DesktopInputPointerDown as i32, + "pointer_up" => protocol::v1::DesktopInputEventType::DesktopInputPointerUp as i32, + "pointer_move" => protocol::v1::DesktopInputEventType::DesktopInputPointerMove as i32, + "scroll" => protocol::v1::DesktopInputEventType::DesktopInputScroll as i32, + "key_down" => protocol::v1::DesktopInputEventType::DesktopInputKeyDown as i32, + "key_up" => protocol::v1::DesktopInputEventType::DesktopInputKeyUp as i32, + _ => protocol::v1::DesktopInputEventType::DesktopInputUnspecified as i32, + }; + + let input_event = protocol::v1::DesktopInputEvent { + session_id: event.session_id, + event_type, + x: event.x, + y: event.y, + button: event.button.unwrap_or(0), + key_code: event.key_code.unwrap_or(0), + scroll_dx: event.scroll_dx.unwrap_or(0), + scroll_dy: event.scroll_dy.unwrap_or(0), + key_text: event.key_text.unwrap_or_default(), + }; + + let query = CapabilityQuery::negotiated(CapabilityId::DESKTOP_STREAM, true); + mux.send_desktop_input_to_peer(input_event, &query) + .await + .map_err(|e| e.to_string())?; + + Ok(()) +} + +#[tauri::command] +fn get_active_desktop_streams( + state: State<'_, DesktopRuntimeState>, +) -> Vec { + state + .active_desktop_streams + .lock() + .values() + .map(|s| DesktopStreamInfoDto { + session_id: s.session_id.clone(), + peer_fingerprint: s.peer_fingerprint.clone(), + package_name: s.package_name.clone(), + width: s.width, + height: s.height, + dpi: s.dpi, + status: "active".into(), + }) + .collect() +} + fn initialize_desktop_runtime( app_handle: &AppHandle, db_path: &Path, @@ -1576,6 +1828,8 @@ fn initialize_desktop_runtime( let active_handoffs = Arc::new(Mutex::new(HashMap::new())); let offline_queue = Arc::new(OfflineTransferQueue::new()); let drop_folder: Arc>> = Arc::new(Mutex::new(None)); + let active_desktop_streams: Arc>> = + Arc::new(Mutex::new(HashMap::new())); let (offline_queue_for_drop, drop_folder_for_loop, app_for_drop) = ( offline_queue.clone(), @@ -1630,6 +1884,7 @@ fn initialize_desktop_runtime( clipboard.clone(), clipboard_history.clone(), active_handoffs.clone(), + active_desktop_streams.clone(), app_handle, ); handlers.on_device_info = Some(device_info_listener( @@ -1660,6 +1915,7 @@ fn initialize_desktop_runtime( active_handoffs, offline_queue, drop_folder, + active_desktop_streams, }) } @@ -1789,7 +2045,11 @@ fn main() { set_lockdown_mode, is_lockdown_mode, get_drop_folder, - set_drop_folder + set_drop_folder, + start_desktop_stream, + stop_desktop_stream, + send_desktop_input, + get_active_desktop_streams ]) // Closing the window keeps Continue in the tray, still receiving. Quit is in the tray menu. .on_window_event(|window, event| { diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index 8d6ef53..6d2e41b 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -26,6 +26,7 @@ import { Info, Laptop, Loader, + Monitor, Plus, Search, Send, @@ -99,6 +100,7 @@ import { } from "./format.ts"; import { CatalogDialog } from "./CatalogDialog.tsx"; import { ClipboardHistoryDialog } from "./ClipboardHistoryDialog.tsx"; +import { DesktopStreamDialog } from "./DesktopStreamDialog.tsx"; import { HandoffCard } from "./HandoffCard.tsx"; import { NotificationList } from "./Notifications.tsx"; import { PairDialog } from "./PairDialog.tsx"; @@ -243,6 +245,7 @@ export default function App() { const [showPairDialog, setShowPairDialog] = useState(false); const [showCatalogDialog, setShowCatalogDialog] = useState(false); const [showClipboardDialog, setShowClipboardDialog] = useState(false); + const [showDesktopStreamDialog, setShowDesktopStreamDialog] = useState(false); const [isRinging, setIsRinging] = useState(false); const [activity, setActivity] = useState([]); const [connecting, setConnecting] = useState(null); @@ -984,6 +987,7 @@ export default function App() { onSendClipboard={handleSendClipboard} onOpenCatalog={() => setShowCatalogDialog(true)} onOpenClipboardHistory={() => setShowClipboardDialog(true)} + onOpenDesktopStream={() => setShowDesktopStreamDialog(true)} isRinging={isRinging} onToggleRing={handleToggleRing} textInput={textInput} @@ -1081,6 +1085,14 @@ export default function App() { /> )} + {showDesktopStreamDialog && selectedPeer && ( + setShowDesktopStreamDialog(false)} + onError={showError} + /> + )} + {showClipboardDialog && ( setShowClipboardDialog(false)} @@ -1211,6 +1223,7 @@ interface HomeViewProps { onSendClipboard: () => void; onOpenCatalog: () => void; onOpenClipboardHistory: () => void; + onOpenDesktopStream: () => void; isRinging: boolean; onToggleRing: () => void; textInput: string; @@ -1246,6 +1259,7 @@ function HomeView(props: HomeViewProps) { onSendClipboard, onOpenCatalog, onOpenClipboardHistory, + onOpenDesktopStream, isRinging, onToggleRing, textInput, @@ -1458,6 +1472,14 @@ function HomeView(props: HomeViewProps) { Clipboard history +
    ) : (
    diff --git a/apps/desktop/src/DesktopStreamDialog.tsx b/apps/desktop/src/DesktopStreamDialog.tsx new file mode 100644 index 0000000..c415d23 --- /dev/null +++ b/apps/desktop/src/DesktopStreamDialog.tsx @@ -0,0 +1,379 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +import { useEffect, useRef, useState, useCallback } from "react"; +import { Loader, Maximize2, Minimize2, Monitor, RefreshCw, Square, X } from "lucide-react"; +import { + errorMessage, + onDesktopStreamFrame, + onDesktopStreamStopped, + sendDesktopInput, + startDesktopStream, + stopDesktopStream, +} from "./api.ts"; +import type { DesktopInputEventDto, DesktopStreamInfo, TrustedPeer } from "./types.ts"; + +interface DesktopStreamDialogProps { + peer: TrustedPeer; + onClose: () => void; + onError: (message: string) => void; +} + +const PRESETS = [ + { label: "1080p (FHD)", width: 1920, height: 1080, dpi: 240 }, + { label: "720p (HD)", width: 1280, height: 720, dpi: 160 }, + { label: "Phone Native", width: 1080, height: 2400, dpi: 420 }, +]; + +export function DesktopStreamDialog({ peer, onClose, onError }: DesktopStreamDialogProps) { + const [session, setSession] = useState(null); + const [connecting, setConnecting] = useState(false); + const [presetIndex, setPresetIndex] = useState(0); + const [fps, setFps] = useState(0); + const [frameData, setFrameData] = useState(null); + const [isFullscreen, setIsFullscreen] = useState(false); + + const containerRef = useRef(null); + const viewportRef = useRef(null); + const sessionRef = useRef(null); + sessionRef.current = session; + + const frameCounterRef = useRef(0); + const lastFpsCalcRef = useRef(Date.now()); + + const stopActiveStream = useCallback(async () => { + const cur = sessionRef.current; + if (cur) { + try { + await stopDesktopStream(cur.sessionId); + } catch (err) { + console.error("Failed to stop stream:", err); + } + } + }, []); + + const handleClose = useCallback(async () => { + await stopActiveStream(); + onClose(); + }, [stopActiveStream, onClose]); + + const startStream = useCallback(async () => { + setConnecting(true); + const preset = PRESETS[presetIndex]; + try { + const info = await startDesktopStream( + peer.fingerprint, + undefined, + preset.width, + preset.height, + preset.dpi, + ); + setSession(info); + setFrameData(null); + frameCounterRef.current = 0; + lastFpsCalcRef.current = Date.now(); + } catch (err) { + onError(errorMessage(err)); + } finally { + setConnecting(false); + } + }, [peer.fingerprint, presetIndex, onError]); + + useEffect(() => { + startStream(); + return () => { + stopActiveStream(); + }; + }, [startStream, stopActiveStream]); + + useEffect(() => { + let unlistenFrame: (() => void) | null = null; + let unlistenStopped: (() => void) | null = null; + + onDesktopStreamFrame((frame) => { + if (sessionRef.current && frame.sessionId === sessionRef.current.sessionId) { + setFrameData(`data:image/jpeg;base64,${frame.data}`); + frameCounterRef.current += 1; + + const now = Date.now(); + const elapsed = now - lastFpsCalcRef.current; + if (elapsed >= 1000) { + setFps(Math.round((frameCounterRef.current * 1000) / elapsed)); + frameCounterRef.current = 0; + lastFpsCalcRef.current = now; + } + } + }).then((un) => { + unlistenFrame = un; + }); + + onDesktopStreamStopped((stoppedId) => { + if (sessionRef.current && stoppedId === sessionRef.current.sessionId) { + setSession(null); + setFrameData(null); + } + }).then((un) => { + unlistenStopped = un; + }); + + return () => { + if (unlistenFrame) unlistenFrame(); + if (unlistenStopped) unlistenStopped(); + }; + }, []); + + useEffect(() => { + const handleKey = (e: KeyboardEvent) => { + if (e.key === "Escape") { + if (isFullscreen) { + setIsFullscreen(false); + } else { + handleClose(); + } + } + }; + window.addEventListener("keydown", handleKey); + return () => window.removeEventListener("keydown", handleKey); + }, [isFullscreen, handleClose]); + + const mapCoordinates = (clientX: number, clientY: number): { x: number; y: number } | null => { + const el = viewportRef.current; + const cur = sessionRef.current; + if (!el || !cur) return null; + const rect = el.getBoundingClientRect(); + if (rect.width <= 0 || rect.height <= 0) return null; + + const relX = Math.max(0, Math.min(clientX - rect.left, rect.width)); + const relY = Math.max(0, Math.min(clientY - rect.top, rect.height)); + + const targetWidth = cur.width || 1920; + const targetHeight = cur.height || 1080; + + return { + x: Math.round((relX / rect.width) * targetWidth), + y: Math.round((relY / rect.height) * targetHeight), + }; + }; + + const dispatchInput = ( + eventType: DesktopInputEventDto["eventType"], + clientX: number, + clientY: number, + opts: Partial = {}, + ) => { + const cur = sessionRef.current; + if (!cur) return; + const coords = mapCoordinates(clientX, clientY); + if (!coords) return; + + sendDesktopInput({ + sessionId: cur.sessionId, + eventType, + x: coords.x, + y: coords.y, + ...opts, + }).catch(() => {}); + }; + + const handlePointerDown = (e: React.PointerEvent) => { + viewportRef.current?.focus(); + dispatchInput("pointer_down", e.clientX, e.clientY, { button: e.button }); + }; + + const handlePointerUp = (e: React.PointerEvent) => { + dispatchInput("pointer_up", e.clientX, e.clientY, { button: e.button }); + }; + + const handlePointerMove = (e: React.PointerEvent) => { + if (e.buttons > 0) { + dispatchInput("pointer_move", e.clientX, e.clientY, { button: e.button }); + } + }; + + const handleWheel = (e: React.WheelEvent) => { + e.preventDefault(); + dispatchInput("scroll", e.clientX, e.clientY, { + scrollDx: Math.round(e.deltaX), + scrollDy: Math.round(e.deltaY), + }); + }; + + const handleKeyDown = (e: React.KeyboardEvent) => { + if (e.key === "Escape") return; + const cur = sessionRef.current; + if (!cur) return; + sendDesktopInput({ + sessionId: cur.sessionId, + eventType: "key_down", + x: 0, + y: 0, + keyCode: e.keyCode, + keyText: e.key, + }).catch(() => {}); + }; + + const handleKeyUp = (e: React.KeyboardEvent) => { + if (e.key === "Escape") return; + const cur = sessionRef.current; + if (!cur) return; + sendDesktopInput({ + sessionId: cur.sessionId, + eventType: "key_up", + x: 0, + y: 0, + keyCode: e.keyCode, + keyText: e.key, + }).catch(() => {}); + }; + + return ( +
    +
    e.stopPropagation()} + style={{ + width: isFullscreen ? "98vw" : "min(960px, 96vw)", + maxWidth: "none", + height: isFullscreen ? "96vh" : "auto", + }} + > +
    +
    +

    + + Desktop Mode: {peer.displayName} +

    +

    + Interactive Android desktop workspace and app streaming. +

    +
    +
    + + +
    +
    + +
    +
    + {PRESETS.map((p, idx) => ( + + ))} +
    + +
    + {session && ( + + {session.width}x{session.height} @ {fps} FPS + + )} + {session ? ( + + ) : ( + + )} +
    +
    + +
    e.preventDefault()} + style={{ + position: "relative", + width: "100%", + aspectRatio: session ? `${session.width} / ${session.height}` : "16 / 9", + maxHeight: isFullscreen ? "calc(88vh - 120px)" : "60vh", + backgroundColor: "#0d1117", + borderRadius: 16, + overflow: "hidden", + display: "flex", + alignItems: "center", + justifyContent: "center", + cursor: session ? "crosshair" : "default", + outline: "none", + border: "1px solid var(--line)", + userSelect: "none", + }} + > + {frameData ? ( + Remote Desktop Workspace + ) : connecting ? ( +
    + + Initializing remote desktop display... +
    + ) : ( +
    + + Desktop stream inactive. Click Start to begin. +
    + )} +
    + +
    + + Forwarding keyboard, mouse, and touch input directly to remote Android session. + + +
    +
    +
    + ); +} diff --git a/apps/desktop/src/api.ts b/apps/desktop/src/api.ts index 7395352..18223ff 100644 --- a/apps/desktop/src/api.ts +++ b/apps/desktop/src/api.ts @@ -6,6 +6,9 @@ import { listen, type UnlistenFn } from "@tauri-apps/api/event"; import type { CatalogResponse, ClipboardHistoryItem, + DesktopInputEventDto, + DesktopStreamFrameEvent, + DesktopStreamInfo, DeviceIdentity, Grant, HandoffItem, @@ -254,6 +257,45 @@ export const onQueuedTransfersChanged = (handler: (peerId: string) => void): Pro export const onLockdownChanged = (handler: (active: boolean) => void): Promise => listen("lockdown-changed", (event) => handler(event.payload)); +export const startDesktopStream = ( + peerFingerprint: string, + packageName?: string, + width: number = 1920, + height: number = 1080, + dpi: number = 240, +) => + invoke("start_desktop_stream", { + peerFingerprint, + packageName, + width, + height, + dpi, + }); + +export const stopDesktopStream = (sessionId: string) => + invoke("stop_desktop_stream", { sessionId }); + +export const sendDesktopInput = (event: DesktopInputEventDto) => + invoke("send_desktop_input", { event }); + +export const getActiveDesktopStreams = () => + invoke("get_active_desktop_streams"); + +export const onDesktopStreamStarted = ( + handler: (info: DesktopStreamInfo) => void, +): Promise => + listen("desktop-stream-started", (event) => handler(event.payload)); + +export const onDesktopStreamStopped = ( + handler: (sessionId: string) => void, +): Promise => + listen("desktop-stream-stopped", (event) => handler(event.payload)); + +export const onDesktopStreamFrame = ( + handler: (frame: DesktopStreamFrameEvent) => void, +): Promise => + listen("desktop-stream-frame", (event) => handler(event.payload)); + /** Commands reject with the backend's error string; anything else is unexpected. */ export function errorMessage(error: unknown): string { if (typeof error === "string") return error; diff --git a/apps/desktop/src/types.ts b/apps/desktop/src/types.ts index ecc1c4e..eacdf2a 100644 --- a/apps/desktop/src/types.ts +++ b/apps/desktop/src/types.ts @@ -118,8 +118,39 @@ export const PERMISSIONS: Record 10: { label: "Remote typing", description: "Dictation and keyboard input from phone" }, 11: { label: "Macro deck", description: "Custom quick action shortcuts from phone" }, 12: { label: "File catalog", description: "Browse photos, documents, and mount files" }, + 13: { label: "Desktop stream", description: "Stream phone apps or desktop workspace to PC" }, }; +export interface DesktopStreamInfo { + sessionId: string; + peerFingerprint: string; + packageName?: string; + width: number; + height: number; + dpi: number; + status: string; +} + +export interface DesktopInputEventDto { + sessionId: string; + eventType: "pointer_down" | "pointer_up" | "pointer_move" | "scroll" | "key_down" | "key_up"; + x: number; + y: number; + button?: number; + keyCode?: number; + scrollDx?: number; + scrollDy?: number; + keyText?: string; +} + +export interface DesktopStreamFrameEvent { + sessionId: string; + frameIndex: number; + timestampUs: number; + isKeyframe: boolean; + data: string; +} + /** A notification from the phone, to read and act on here. */ export interface PhoneNotification { peerId: string; diff --git a/crates/limits/src/lib.rs b/crates/limits/src/lib.rs index 4fd8d93..0618315 100644 --- a/crates/limits/src/lib.rs +++ b/crates/limits/src/lib.rs @@ -116,6 +116,17 @@ pub const MAX_CATALOG_PAGE_SIZE: u32 = 250; /// Maximum UTF-8 byte length for a catalog item ID. pub const MAX_CATALOG_ITEM_ID_BYTES: usize = 128; +// Desktop & App Streaming + +/// Maximum frame size for desktop streaming envelopes (frames, input, controls). +pub const MAX_FRAME_DESKTOP_STREAM_BYTES: usize = 2 * 1024 * 1024; + +/// Maximum UTF-8 byte length for a stream session ID. +pub const MAX_STREAM_SESSION_ID_BYTES: usize = 64; + +/// Maximum UTF-8 byte length for a target package name. +pub const MAX_STREAM_PACKAGE_NAME_BYTES: usize = 256; + // File transfer /// Maximum UTF-8 byte length of a transfer filename. diff --git a/crates/protocol/build.rs b/crates/protocol/build.rs index a619719..f8b2694 100644 --- a/crates/protocol/build.rs +++ b/crates/protocol/build.rs @@ -26,6 +26,7 @@ fn main() { proto_dir.join("remote_input.proto"), proto_dir.join("deck.proto"), proto_dir.join("catalog.proto"), + proto_dir.join("desktop_stream.proto"), ]; for file in &proto_files { diff --git a/crates/protocol/src/capability.rs b/crates/protocol/src/capability.rs index 83146db..ef9bea3 100644 --- a/crates/protocol/src/capability.rs +++ b/crates/protocol/src/capability.rs @@ -24,6 +24,7 @@ impl CapabilityId { pub const REMOTE_INPUT: Self = Self(10); pub const DECK: Self = Self(11); pub const FILE_CATALOG: Self = Self(12); + pub const DESKTOP_STREAM: Self = Self(13); pub const fn new(id: u32) -> Self { Self(id) @@ -48,6 +49,7 @@ impl CapabilityId { Self::REMOTE_INPUT => Some("remote_input"), Self::DECK => Some("deck"), Self::FILE_CATALOG => Some("file_catalog"), + Self::DESKTOP_STREAM => Some("desktop_stream"), _ => None, } } diff --git a/crates/sessions/src/capabilities_router.rs b/crates/sessions/src/capabilities_router.rs index 3bdd066..eba3454 100644 --- a/crates/sessions/src/capabilities_router.rs +++ b/crates/sessions/src/capabilities_router.rs @@ -15,6 +15,7 @@ use transfer::{receive_file, send_file, ReceivedFile}; use crate::catalog::CatalogDispatcher; use crate::deck::DeckDispatcher; +use crate::desktop_stream::DesktopStreamDispatcher; use crate::device::{PeerDevice, ThisDevice}; use crate::handoff::HandoffDispatcher; use crate::incoming::{IncomingFiles, SaveFolder}; @@ -76,6 +77,27 @@ pub type CatalogQueryHandler = pub type ThumbnailRequestHandler = Arc< dyn Fn(&str, protocol::v1::ThumbnailRequest) -> protocol::v1::ThumbnailResponse + Send + Sync, >; +pub type DesktopStreamStartHandler = Arc< + dyn Fn( + &str, + protocol::v1::DesktopStreamStartRequest, + ) -> protocol::v1::DesktopStreamStartResponse + + Send + + Sync, +>; +pub type DesktopInputHandler = Arc< + dyn Fn(&str, protocol::v1::DesktopInputEvent) -> protocol::v1::DesktopStreamAck + + Send + + Sync, +>; +pub type DesktopControlHandler = Arc< + dyn Fn(&str, protocol::v1::DesktopStreamControl) -> protocol::v1::DesktopStreamAck + + Send + + Sync, +>; +pub type DesktopStreamFrameHandler = Arc< + dyn Fn(&str, protocol::v1::DesktopStreamFrame) + Send + Sync, +>; /// Callbacks and configuration for active capabilities over a multiplexed session. #[derive(Clone)] @@ -90,6 +112,7 @@ pub struct SessionCapabilityHandlers { pub remote_input_dispatcher: Arc, pub deck_dispatcher: Arc, pub catalog_dispatcher: Arc, + pub desktop_stream_dispatcher: Arc, pub on_file_received: Option>, pub on_clipboard_received: Option>, /// Called with notifications the peer shows here, and with replies to and dismissals of @@ -107,6 +130,10 @@ pub struct SessionCapabilityHandlers { pub on_deck_tile_triggered: Option, pub on_catalog_query: Option, pub on_thumbnail_request: Option, + pub on_desktop_stream_start: Option, + pub on_desktop_input: Option, + pub on_desktop_control: Option, + pub on_desktop_frame: Option, /// How this device introduces itself to peers. pub this_device: ThisDevice, /// Called with what a peer says about itself each time a session starts. @@ -133,6 +160,7 @@ impl SessionCapabilityHandlers { remote_input_dispatcher: Arc::new(RemoteInputDispatcher::new()), deck_dispatcher: Arc::new(DeckDispatcher::new()), catalog_dispatcher: Arc::new(CatalogDispatcher::new()), + desktop_stream_dispatcher: Arc::new(DesktopStreamDispatcher::new()), on_file_received: None, on_clipboard_received: None, on_notification: None, @@ -148,6 +176,10 @@ impl SessionCapabilityHandlers { on_deck_tile_triggered: None, on_catalog_query: None, on_thumbnail_request: None, + on_desktop_stream_start: None, + on_desktop_input: None, + on_desktop_control: None, + on_desktop_frame: None, this_device: ThisDevice::default(), on_device_info: None, on_device_status: None, @@ -740,6 +772,88 @@ pub fn spawn_capabilities_dispatcher( error!("Failed to process file catalog stream from {peer_fp}: {e}"); } } + CapabilityId::DESKTOP_STREAM => { + debug!("Handling incoming desktop stream from {peer_fp}"); + let is_permitted = + permitted(&handlers, &peer_fp, CapabilityId::DESKTOP_STREAM, None) + .await; + + if is_permitted { + if let Some(store) = &handlers.permission_store { + store.consume_if_allow_once(&peer_fp, CapabilityId::DESKTOP_STREAM); + } + } + + let query = CapabilityQuery::negotiated( + CapabilityId::DESKTOP_STREAM, + is_permitted, + ); + + let on_start = handlers.on_desktop_stream_start.clone(); + let on_input = handlers.on_desktop_input.clone(); + let on_ctl = handlers.on_desktop_control.clone(); + let on_frame = handlers.on_desktop_frame.clone(); + let peer = peer_fp.clone(); + + let result = handlers + .desktop_stream_dispatcher + .receive_envelope( + &mut stream.send_stream, + &mut stream.recv_stream, + &query, + |req| { + if let Some(ref cb) = on_start { + cb(&peer, req) + } else { + protocol::v1::DesktopStreamStartResponse { + session_id: req.session_id, + status: protocol::v1::DesktopStreamStatus::Unsupported + as i32, + error_message: + "Desktop streaming not supported on this host" + .into(), + actual_width: 0, + actual_height: 0, + actual_dpi: 0, + selected_codec: 0, + display_id: 0, + } + } + }, + |input| { + if let Some(ref cb) = on_input { + cb(&peer, input) + } else { + protocol::v1::DesktopStreamAck { + session_id: input.session_id, + success: false, + error_message: "Desktop input not handled".into(), + } + } + }, + |ctl| { + if let Some(ref cb) = on_ctl { + cb(&peer, ctl) + } else { + protocol::v1::DesktopStreamAck { + session_id: ctl.session_id, + success: false, + error_message: "Desktop control not handled".into(), + } + } + }, + |frame| { + if let Some(ref cb) = on_frame { + cb(&peer, frame); + } + }, + ) + .await; + + if let Err(e) = result { + error!("Failed to process desktop stream from {peer_fp}: {e}"); + } + } unknown => { debug!("Received unsupported capability stream {unknown:?} from {peer_fp}"); } @@ -972,4 +1086,52 @@ impl SessionMultiplexer { .dismiss_handoff(&mut send, &mut recv, handoff_id, query) .await } + + pub async fn start_desktop_stream_on_peer( + &self, + req: protocol::v1::DesktopStreamStartRequest, + capability_query: &CapabilityQuery, + ) -> Result { + let (mut send, mut recv) = self + .open_stream(CapabilityId::DESKTOP_STREAM) + .await + .map_err(crate::error::SessionError::Transport)?; + + let dispatcher = DesktopStreamDispatcher::new(); + dispatcher + .start_stream(&mut send, &mut recv, req, capability_query) + .await + } + + pub async fn send_desktop_input_to_peer( + &self, + event: protocol::v1::DesktopInputEvent, + capability_query: &CapabilityQuery, + ) -> Result { + let (mut send, mut recv) = self + .open_stream(CapabilityId::DESKTOP_STREAM) + .await + .map_err(crate::error::SessionError::Transport)?; + + let dispatcher = DesktopStreamDispatcher::new(); + dispatcher + .send_input_event(&mut send, &mut recv, event, capability_query) + .await + } + + pub async fn send_desktop_control_to_peer( + &self, + ctl: protocol::v1::DesktopStreamControl, + capability_query: &CapabilityQuery, + ) -> Result { + let (mut send, mut recv) = self + .open_stream(CapabilityId::DESKTOP_STREAM) + .await + .map_err(crate::error::SessionError::Transport)?; + + let dispatcher = DesktopStreamDispatcher::new(); + dispatcher + .send_control(&mut send, &mut recv, ctl, capability_query) + .await + } } diff --git a/crates/sessions/src/desktop_stream.rs b/crates/sessions/src/desktop_stream.rs new file mode 100644 index 0000000..8e96ff3 --- /dev/null +++ b/crates/sessions/src/desktop_stream.rs @@ -0,0 +1,321 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 + +use capabilities::{evaluate_capability, CapabilityQuery}; +use limits::{ + MAX_FRAME_DESKTOP_STREAM_BYTES, MAX_STREAM_PACKAGE_NAME_BYTES, MAX_STREAM_SESSION_ID_BYTES, +}; +use protocol::v1::{ + desktop_stream_envelope::Payload, DesktopInputEvent, DesktopStreamAck, DesktopStreamControl, + DesktopStreamEnvelope, DesktopStreamFrame, DesktopStreamStartRequest, + DesktopStreamStartResponse, DesktopStreamStatus, +}; +use transport::{read_msg, write_msg}; + +use crate::error::SessionError; + +#[derive(Default, Clone)] +pub struct DesktopStreamDispatcher; + +impl DesktopStreamDispatcher { + pub fn new() -> Self { + Self + } + + pub fn validate_session_id(session_id: &str) -> Result<(), SessionError> { + if session_id.is_empty() { + return Err(SessionError::DesktopStreamValidation( + "Session ID cannot be empty".into(), + )); + } + if session_id.len() > MAX_STREAM_SESSION_ID_BYTES { + return Err(SessionError::DesktopStreamValidation(format!( + "Session ID length {} exceeds limit {}", + session_id.len(), + MAX_STREAM_SESSION_ID_BYTES + ))); + } + Ok(()) + } + + pub fn validate_start_request(req: &DesktopStreamStartRequest) -> Result<(), SessionError> { + Self::validate_session_id(&req.session_id)?; + + if req.target_package_name.len() > MAX_STREAM_PACKAGE_NAME_BYTES { + return Err(SessionError::DesktopStreamValidation(format!( + "Package name length {} exceeds limit {}", + req.target_package_name.len(), + MAX_STREAM_PACKAGE_NAME_BYTES + ))); + } + + if req.requested_width == 0 || req.requested_height == 0 { + return Err(SessionError::DesktopStreamValidation( + "Requested dimensions must be greater than zero".into(), + )); + } + + if req.requested_width > 7680 || req.requested_height > 4320 { + return Err(SessionError::DesktopStreamValidation( + "Requested dimensions exceed 8K boundary".into(), + )); + } + + Ok(()) + } + + pub fn validate_input_event(event: &DesktopInputEvent) -> Result<(), SessionError> { + Self::validate_session_id(&event.session_id)?; + Ok(()) + } + + pub fn validate_control(control: &DesktopStreamControl) -> Result<(), SessionError> { + Self::validate_session_id(&control.session_id)?; + Ok(()) + } + + /// Sends a desktop streaming start request to peer and waits for its response. + pub async fn start_stream( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + request: DesktopStreamStartRequest, + query: &CapabilityQuery, + ) -> Result { + evaluate_capability(query)?; + Self::validate_start_request(&request)?; + + let envelope = DesktopStreamEnvelope { + payload: Some(Payload::StartRequest(request)), + }; + + write_msg(send_stream, &envelope, MAX_FRAME_DESKTOP_STREAM_BYTES).await?; + let resp_envelope: DesktopStreamEnvelope = + read_msg(recv_stream, MAX_FRAME_DESKTOP_STREAM_BYTES).await?; + + match resp_envelope.payload { + Some(Payload::StartResponse(resp)) => Ok(resp), + _ => Err(SessionError::UnexpectedMessage), + } + } + + /// Sends an input event (pointer or key) to the active desktop stream. + pub async fn send_input_event( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + event: DesktopInputEvent, + query: &CapabilityQuery, + ) -> Result { + evaluate_capability(query)?; + Self::validate_input_event(&event)?; + + let envelope = DesktopStreamEnvelope { + payload: Some(Payload::InputEvent(event)), + }; + + write_msg(send_stream, &envelope, MAX_FRAME_DESKTOP_STREAM_BYTES).await?; + let resp: DesktopStreamEnvelope = + read_msg(recv_stream, MAX_FRAME_DESKTOP_STREAM_BYTES).await?; + + match resp.payload { + Some(Payload::Ack(ack)) => Ok(ack), + _ => Err(SessionError::UnexpectedMessage), + } + } + + /// Sends stream control action (stop, request keyframe, or resize). + pub async fn send_control( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + control: DesktopStreamControl, + query: &CapabilityQuery, + ) -> Result { + evaluate_capability(query)?; + Self::validate_control(&control)?; + + let envelope = DesktopStreamEnvelope { + payload: Some(Payload::Control(control)), + }; + + write_msg(send_stream, &envelope, MAX_FRAME_DESKTOP_STREAM_BYTES).await?; + let resp: DesktopStreamEnvelope = + read_msg(recv_stream, MAX_FRAME_DESKTOP_STREAM_BYTES).await?; + + match resp.payload { + Some(Payload::Ack(ack)) => Ok(ack), + _ => Err(SessionError::UnexpectedMessage), + } + } + + /// Receives and processes a desktop stream envelope on an incoming capability stream. + #[allow(clippy::too_many_arguments)] + pub async fn receive_envelope( + &self, + send_stream: &mut quinn::SendStream, + recv_stream: &mut quinn::RecvStream, + query: &CapabilityQuery, + on_start: FStart, + mut on_input: FInput, + mut on_control: FControl, + mut on_frame: FFrame, + ) -> Result<(), SessionError> + where + FStart: FnOnce(DesktopStreamStartRequest) -> DesktopStreamStartResponse, + FInput: FnMut(DesktopInputEvent) -> DesktopStreamAck, + FControl: FnMut(DesktopStreamControl) -> DesktopStreamAck, + FFrame: FnMut(DesktopStreamFrame), + { + evaluate_capability(query)?; + + let envelope: DesktopStreamEnvelope = + read_msg(recv_stream, MAX_FRAME_DESKTOP_STREAM_BYTES).await?; + + match envelope.payload { + Some(Payload::StartRequest(req)) => { + let resp = if let Err(e) = Self::validate_start_request(&req) { + DesktopStreamStartResponse { + session_id: req.session_id, + status: DesktopStreamStatus::Error as i32, + error_message: e.to_string(), + actual_width: 0, + actual_height: 0, + actual_dpi: 0, + selected_codec: 0, + display_id: 0, + } + } else { + on_start(req) + }; + + let resp_env = DesktopStreamEnvelope { + payload: Some(Payload::StartResponse(resp)), + }; + write_msg(send_stream, &resp_env, MAX_FRAME_DESKTOP_STREAM_BYTES).await?; + } + Some(Payload::InputEvent(input)) => { + let ack = if let Err(e) = Self::validate_input_event(&input) { + DesktopStreamAck { + session_id: input.session_id, + success: false, + error_message: e.to_string(), + } + } else { + on_input(input) + }; + + let resp_env = DesktopStreamEnvelope { + payload: Some(Payload::Ack(ack)), + }; + write_msg(send_stream, &resp_env, MAX_FRAME_DESKTOP_STREAM_BYTES).await?; + } + Some(Payload::Control(ctl)) => { + let ack = if let Err(e) = Self::validate_control(&ctl) { + DesktopStreamAck { + session_id: ctl.session_id, + success: false, + error_message: e.to_string(), + } + } else { + on_control(ctl) + }; + + let resp_env = DesktopStreamEnvelope { + payload: Some(Payload::Ack(ack)), + }; + write_msg(send_stream, &resp_env, MAX_FRAME_DESKTOP_STREAM_BYTES).await?; + } + Some(Payload::Frame(frame)) => { + on_frame(frame); + } + _ => return Err(SessionError::UnexpectedMessage), + } + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use protocol::CapabilityId; + + #[test] + fn validates_start_request_parameters() { + let valid = DesktopStreamStartRequest { + session_id: "stream-123".into(), + target_package_name: "".into(), + requested_width: 1920, + requested_height: 1080, + requested_dpi: 240, + max_fps: 60, + preferred_codec: 1, + }; + assert!(DesktopStreamDispatcher::validate_start_request(&valid).is_ok()); + + let empty_id = DesktopStreamStartRequest { + session_id: "".into(), + ..valid.clone() + }; + assert!(DesktopStreamDispatcher::validate_start_request(&empty_id).is_err()); + + let zero_dim = DesktopStreamStartRequest { + requested_width: 0, + ..valid.clone() + }; + assert!(DesktopStreamDispatcher::validate_start_request(&zero_dim).is_err()); + + let oversized_dim = DesktopStreamStartRequest { + requested_width: 8000, + ..valid.clone() + }; + assert!(DesktopStreamDispatcher::validate_start_request(&oversized_dim).is_err()); + + let long_package = DesktopStreamStartRequest { + target_package_name: "a".repeat(300), + ..valid + }; + assert!(DesktopStreamDispatcher::validate_start_request(&long_package).is_err()); + } + + #[test] + fn validates_input_events() { + let valid = DesktopInputEvent { + session_id: "stream-123".into(), + event_type: 1, + x: 100, + y: 200, + button: 0, + key_code: 0, + scroll_dx: 0, + scroll_dy: 0, + key_text: "".into(), + }; + assert!(DesktopStreamDispatcher::validate_input_event(&valid).is_ok()); + + let empty = DesktopInputEvent { + session_id: "".into(), + ..valid + }; + assert!(DesktopStreamDispatcher::validate_input_event(&empty).is_err()); + } + + #[test] + fn capability_denied_aborts() { + let query = CapabilityQuery::negotiated(CapabilityId::DESKTOP_STREAM, false); + let req = DesktopStreamStartRequest { + session_id: "s-1".into(), + target_package_name: "".into(), + requested_width: 1280, + requested_height: 720, + requested_dpi: 160, + max_fps: 30, + preferred_codec: 1, + }; + + // Validate directly fails on capability gate + assert!(evaluate_capability(&query).is_err()); + assert!(DesktopStreamDispatcher::validate_session_id(&req.session_id).is_ok()); + } +} diff --git a/crates/sessions/src/error.rs b/crates/sessions/src/error.rs index b1346e6..609fb80 100644 --- a/crates/sessions/src/error.rs +++ b/crates/sessions/src/error.rs @@ -43,4 +43,7 @@ pub enum SessionError { #[error("Catalog validation failed: {0}")] CatalogValidation(String), + + #[error("Desktop stream validation failed: {0}")] + DesktopStreamValidation(String), } diff --git a/crates/sessions/src/lib.rs b/crates/sessions/src/lib.rs index cb13845..b3b7fc3 100644 --- a/crates/sessions/src/lib.rs +++ b/crates/sessions/src/lib.rs @@ -6,6 +6,7 @@ pub mod backoff; pub mod capabilities_router; pub mod catalog; pub mod deck; +pub mod desktop_stream; pub mod device; pub mod error; pub mod handoff; @@ -26,12 +27,14 @@ pub use auto_connect::connect_paired_peers; pub use backoff::ReconnectPolicy; pub use capabilities_router::{ spawn_capabilities_dispatcher, CatalogQueryHandler, DeckLayoutHandler, DeckTriggerHandler, - MediaCommandHandler, OnReceived, PcActionHandler, PermissionDecision, PermissionPrompt, - PermissionRequest, RemoteInputHandler, RingHandler, SessionCapabilityHandlers, - ThumbnailRequestHandler, PROMPT_TIMEOUT, + DesktopControlHandler, DesktopInputHandler, DesktopStreamFrameHandler, + DesktopStreamStartHandler, MediaCommandHandler, OnReceived, PcActionHandler, PermissionDecision, + PermissionPrompt, PermissionRequest, RemoteInputHandler, RingHandler, + SessionCapabilityHandlers, ThumbnailRequestHandler, PROMPT_TIMEOUT, }; pub use catalog::CatalogDispatcher; pub use deck::DeckDispatcher; +pub use desktop_stream::DesktopStreamDispatcher; pub use device::{clean_name, this_platform, PeerDevice, ThisDevice}; pub use error::SessionError; pub use handoff::HandoffDispatcher; diff --git a/proto/desktop_stream.proto b/proto/desktop_stream.proto new file mode 100644 index 0000000..2214711 --- /dev/null +++ b/proto/desktop_stream.proto @@ -0,0 +1,105 @@ +// SPDX-FileCopyrightText: Contributors to the Continue project +// SPDX-License-Identifier: Apache-2.0 +syntax = "proto3"; + +package continue.v1; + +enum DesktopStreamStatus { + DESKTOP_STREAM_STATUS_UNSPECIFIED = 0; + DESKTOP_STREAM_STATUS_ACTIVE = 1; + DESKTOP_STREAM_STATUS_DECLINED = 2; + DESKTOP_STREAM_STATUS_BUSY = 3; + DESKTOP_STREAM_STATUS_UNSUPPORTED = 4; + DESKTOP_STREAM_STATUS_STOPPED = 5; + DESKTOP_STREAM_STATUS_ERROR = 6; +} + +enum StreamCodec { + STREAM_CODEC_UNSPECIFIED = 0; + STREAM_CODEC_H264 = 1; + STREAM_CODEC_VP8 = 2; + STREAM_CODEC_RAW_RGBA = 3; +} + +message DesktopStreamStartRequest { + string session_id = 1; + string target_package_name = 2; + uint32 requested_width = 3; + uint32 requested_height = 4; + uint32 requested_dpi = 5; + uint32 max_fps = 6; + StreamCodec preferred_codec = 7; +} + +message DesktopStreamStartResponse { + string session_id = 1; + DesktopStreamStatus status = 2; + string error_message = 3; + uint32 actual_width = 4; + uint32 actual_height = 5; + uint32 actual_dpi = 6; + StreamCodec selected_codec = 7; + uint32 display_id = 8; +} + +enum DesktopInputEventType { + DESKTOP_INPUT_UNSPECIFIED = 0; + DESKTOP_INPUT_POINTER_DOWN = 1; + DESKTOP_INPUT_POINTER_UP = 2; + DESKTOP_INPUT_POINTER_MOVE = 3; + DESKTOP_INPUT_SCROLL = 4; + DESKTOP_INPUT_KEY_DOWN = 5; + DESKTOP_INPUT_KEY_UP = 6; +} + +message DesktopInputEvent { + string session_id = 1; + DesktopInputEventType event_type = 2; + uint32 x = 3; + uint32 y = 4; + uint32 button = 5; + uint32 key_code = 6; + int32 scroll_dx = 7; + int32 scroll_dy = 8; + string key_text = 9; +} + +enum DesktopControlAction { + DESKTOP_CONTROL_UNSPECIFIED = 0; + DESKTOP_CONTROL_STOP = 1; + DESKTOP_CONTROL_REQUEST_KEYFRAME = 2; + DESKTOP_CONTROL_RESIZE = 3; +} + +message DesktopStreamControl { + string session_id = 1; + DesktopControlAction action = 2; + uint32 new_width = 3; + uint32 new_height = 4; + uint32 new_dpi = 5; +} + +message DesktopStreamFrame { + string session_id = 1; + uint64 frame_index = 2; + uint64 timestamp_us = 3; + bool is_keyframe = 4; + bytes data = 5; +} + +message DesktopStreamAck { + string session_id = 1; + bool success = 2; + string error_message = 3; +} + +message DesktopStreamEnvelope { + oneof payload { + DesktopStreamStartRequest start_request = 1; + DesktopStreamStartResponse start_response = 2; + DesktopInputEvent input_event = 3; + DesktopStreamControl control = 4; + DesktopStreamFrame frame = 5; + DesktopStreamAck ack = 6; + } +} From e31cfd35556aff80461f0d0c352c3b4af637b915 Mon Sep 17 00:00:00 2001 From: Samarth Rajesh Lad <142334685+samyyy2311@users.noreply.github.com> Date: Thu, 8 Oct 2026 23:29:56 +0530 Subject: [PATCH 12/14] feat: redesign desktop UI with focused native utility design system and antislop craftsmanship --- DESIGN.md | 41 ++ apps/desktop/src/App.css | 725 +++++++++++++++++++------------ apps/desktop/src/App.tsx | 239 +++++----- apps/desktop/src/HandoffCard.tsx | 10 +- 4 files changed, 646 insertions(+), 369 deletions(-) create mode 100644 DESIGN.md diff --git a/DESIGN.md b/DESIGN.md new file mode 100644 index 0000000..3211195 --- /dev/null +++ b/DESIGN.md @@ -0,0 +1,41 @@ +# Design Direction: Continue (Focused Native Utility) + +## 1. Identity & Purpose +Continue is an open, private, cross-device local continuity companion between desktop and mobile devices. It facilitates seamless file transfers, clipboard synchronization, handoff, remote desktop streaming, and device actions without third-party cloud intermediaries. + +## 2. Personality & Mood +- **Calm & Unobtrusive**: Sits quietly in the system tray and desktop workspace. Does not scream for attention with decorative AI slop, neon glows, or endless pulsing dots. +- **Direct & Functional**: Every control, card, button, and indicator exists for a concrete operational action. +- **Native Precision**: Feels like a first-party platform utility on Windows and macOS. Restrained spacing, crisp borders, genuine elevation, and predictable touch/click feedback. + +## 3. Typography & Hierarchy +- **Font Family**: `Instrument Sans` with fallback to native system fonts (`-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`). +- **Data & Telemetry**: Monospace for network addresses, file sizes, fingerprint hashes, and fps/bitrate counters (`ui-monospace, "Cascadia Code", monospace`). +- **Type Scale**: + - Display: 28px, 600 weight, -0.02em letter spacing. + - Headline: 20px, 600 weight. + - Title: 16px, 600 weight. + - Body: 14px, 400 weight, 1.4 line height. + - Caption / Detail: 12px, 500 weight. + - Monospace Data: 12px / 13px. + +## 4. Color System & Contrast (WCAG AA Compliant) +- **Surfaces**: + - Light mode: Base `#f8fafc`, Surface `#ffffff`, Raised `#f1f5f9`, Border `#e2e8f0`. + - Dark mode: Base `#0b0f17`, Surface `#131924`, Raised `#1c2433`, Border `#2d3748`. +- **Text & Foreground**: + - Primary text: `#0f172a` (light) / `#f1f5f9` (dark) (Contrast > 14:1). + - Secondary text: `#475569` (light) / `#94a3b8` (dark) (Contrast > 4.8:1, passes WCAG AA). + - Borders & Dividers: High-definition 1px line tokens with 3:1 non-text contrast against surfaces. +- **Accent**: + - One deliberate accent at key moments (primary send button, active navigation selection). + - Configurable palette from existing `ACCENT_PALETTE`, defaulting to Cobalt. +- **Status Signals**: + - Online / Active: Emerald `#16a34a` (light) / `#22c55e` (dark) with clear text label. + - Warning / Ask: Amber `#d97706` (light) / `#f59e0b` (dark). + - Error / Lockdown: Crimson `#dc2626` (light) / `#ef4444` (dark). + +## 5. Dials +- **ENERGY**: 2 (Balanced, functional focus) +- **RHYTHM**: 2 (Structured, clear spatial hierarchy between devices, transfer queue, and capabilities) +- **MOTION**: 2 (Functional state feedback only; 120-180ms ease-out transitions on hover/focus/active; zero perpetual pulsing or floating animations) diff --git a/apps/desktop/src/App.css b/apps/desktop/src/App.css index 714dbe7..065fef1 100644 --- a/apps/desktop/src/App.css +++ b/apps/desktop/src/App.css @@ -1,8 +1,8 @@ /* SPDX-FileCopyrightText: Contributors to the Continue project */ /* SPDX-License-Identifier: Apache-2.0 */ -/* Same typeface and colours as the Android app (ui/theme/Theme.kt). Every text colour meets - WCAG AA on the background it sits on. */ +/* Continue Desktop Design System: Focused Native Utility (DESIGN.md) + All color pairings satisfy WCAG AA (4.5:1 for body text, 3:1 for large text and UI boundaries). */ @font-face { font-family: "Instrument Sans"; @@ -12,44 +12,75 @@ } :root { - --brand: #2457d6; + --brand: #2563eb; --on-brand: #ffffff; --accent: var(--brand); --on-accent: var(--on-brand); - --accent-soft: color-mix(in srgb, var(--accent) 12%, transparent); + --accent-soft: rgba(37, 99, 235, 0.1); + --accent-hover: #1d4ed8; - --bg: #ffffff; + --bg: #f8fafc; + --surface: #ffffff; --raised: #ffffff; - --fill: #f1f2f4; - --fill-hover: #e7e9ec; - --hover: rgba(0, 0, 0, 0.05); - --line: #e4e6ea; - --text: #111418; - --text-2: #5a616b; - --success: #1e7a45; - --error: #b3261e; - - --font: "Instrument Sans", system-ui, sans-serif; - --mono: ui-monospace, "SF Mono", "Cascadia Mono", Menlo, Consolas, monospace; - --ease: cubic-bezier(0.2, 0, 0, 1); + --fill: #f1f5f9; + --fill-hover: #e2e8f0; + --hover: rgba(15, 23, 42, 0.05); + --line: #e2e8f0; + --line-strong: #cbd5e1; + --text: #0f172a; + --text-2: #475569; + --text-3: #64748b; + --success: #16a34a; + --success-soft: rgba(22, 163, 74, 0.1); + --error: #dc2626; + --error-soft: rgba(220, 38, 38, 0.1); + --warning: #d97706; + + --radius-xs: 4px; + --radius-sm: 6px; + --radius-md: 10px; + --radius-lg: 14px; + --radius-xl: 18px; + + --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05); + --shadow-card: 0 1px 3px 0 rgba(15, 23, 42, 0.06), 0 1px 2px -1px rgba(15, 23, 42, 0.04); + --shadow-dialog: 0 20px 25px -5px rgba(15, 23, 42, 0.18), 0 8px 10px -6px rgba(15, 23, 42, 0.1); + + --font: "Instrument Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + --mono: ui-monospace, "SF Mono", "Cascadia Code", Menlo, Consolas, monospace; + --ease: cubic-bezier(0.16, 1, 0.3, 1); color-scheme: light; } :root[data-theme="dark"] { - --brand: #a8bfff; - --on-brand: #0b1b45; - - --bg: #000000; - --raised: #111214; - --fill: #16171a; - --fill-hover: #1f2024; - --hover: rgba(255, 255, 255, 0.06); - --line: #222428; - --text: #f1f2f4; - --text-2: #9ca1a9; - --success: #6cc795; - --error: #f2877e; + --brand: #3b82f6; + --on-brand: #ffffff; + --accent: var(--brand); + --on-accent: var(--on-brand); + --accent-soft: rgba(59, 130, 246, 0.15); + --accent-hover: #60a5fa; + + --bg: #0d1117; + --surface: #161b22; + --raised: #21262d; + --fill: #161b22; + --fill-hover: #262c36; + --hover: rgba(240, 246, 252, 0.06); + --line: #30363d; + --line-strong: #484f58; + --text: #f0f6fc; + --text-2: #8b949e; + --text-3: #6e7681; + --success: #22c55e; + --success-soft: rgba(34, 197, 94, 0.15); + --error: #ef4444; + --error-soft: rgba(239, 68, 68, 0.15); + --warning: #f59e0b; + + --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.25); + --shadow-card: 0 1px 3px 0 rgba(0, 0, 0, 0.3), 0 1px 2px -1px rgba(0, 0, 0, 0.2); + --shadow-dialog: 0 20px 25px -5px rgba(0, 0, 0, 0.5), 0 8px 10px -6px rgba(0, 0, 0, 0.4); color-scheme: dark; } @@ -62,11 +93,12 @@ body { font-family: var(--font); - font-size: 15px; + font-size: 14px; line-height: 1.5; color: var(--text); background: var(--bg); -webkit-font-smoothing: antialiased; + overflow: hidden; } button, @@ -83,7 +115,7 @@ button { } button:disabled { - cursor: default; + cursor: not-allowed; } ul, @@ -97,50 +129,54 @@ ol { } ::placeholder { - color: var(--text-2); + color: var(--text-3); } -/* Type */ +/* Typography Hierarchy */ .display { - font-size: 32px; + font-size: 28px; font-weight: 600; - line-height: 1.15; + line-height: 1.2; letter-spacing: -0.02em; } .headline { font-size: 20px; font-weight: 600; - line-height: 1.25; + line-height: 1.3; letter-spacing: -0.01em; } .title { - font-size: 17px; + font-size: 16px; font-weight: 600; + line-height: 1.35; } .label { - margin-top: 8px; + margin-top: 4px; color: var(--text-2); - font-size: 14px; + font-size: 13px; font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.04em; } .label + .list { - margin-top: -12px; + margin-top: 4px; } .supporting { color: var(--text-2); - max-width: 52ch; + max-width: 56ch; + font-size: 14px; } .mono, .font-mono { font-family: var(--mono); - font-size: 13px; + font-size: 12px; } .text-muted { @@ -156,7 +192,7 @@ ol { } .spin { - animation: spin 1s linear infinite; + animation: spin 0.9s linear infinite; } @keyframes spin { @@ -165,81 +201,109 @@ ol { } } -/* Shell */ +/* App Shell */ .shell { display: flex; height: 100vh; + background: var(--bg); } .rail { display: flex; flex-direction: column; align-items: center; - gap: 28px; - width: 88px; + justify-content: space-between; + width: 76px; padding: 20px 0; + background: var(--surface); + border-right: 1px solid var(--line); flex-shrink: 0; + z-index: 10; +} + +.rail-top { + display: flex; + flex-direction: column; + align-items: center; + gap: 24px; + width: 100%; } .rail-logo { - width: 32px; - height: 32px; + display: grid; + place-items: center; + width: 38px; + height: 38px; + border-radius: var(--radius-md); + background: var(--fill); + border: 1px solid var(--line); + color: var(--accent); } .rail-items { display: flex; flex-direction: column; - gap: 12px; + align-items: center; + gap: 8px; + width: 100%; + padding: 0 8px; } .rail-item { display: flex; flex-direction: column; align-items: center; + justify-content: center; gap: 4px; + width: 100%; + padding: 8px 0; + border-radius: var(--radius-md); color: var(--text-2); + transition: all 0.15s var(--ease); +} + +.rail-item:hover { + background: var(--hover); + color: var(--text); } .rail-indicator { position: relative; display: grid; place-items: center; - width: 56px; + width: 32px; height: 32px; - border-radius: 999px; - transition: background 0.2s var(--ease); -} - -.rail-item:hover .rail-indicator { - background: var(--hover); + border-radius: var(--radius-sm); + transition: all 0.15s var(--ease); } .rail-item[aria-current] { color: var(--text); + background: var(--fill); } .rail-item[aria-current] .rail-indicator { - background: var(--accent-soft); color: var(--accent); } .rail-label { - font-size: 12px; + font-size: 11px; font-weight: 600; + letter-spacing: 0.01em; } .rail-badge { position: absolute; - top: 0; - right: 8px; + top: -2px; + right: -6px; min-width: 16px; height: 16px; padding: 0 4px; - border-radius: 999px; + border-radius: var(--radius-xs); background: var(--accent); color: var(--on-accent); - font-size: 11px; + font-size: 10px; font-weight: 700; line-height: 16px; } @@ -247,19 +311,20 @@ ol { .pane { flex: 1; min-width: 0; + height: 100vh; } .pane-scroll { height: 100%; overflow-y: auto; - padding: 40px 48px 64px 24px; + padding: 32px 40px 48px; } .page { display: flex; flex-direction: column; gap: 24px; - max-width: 760px; + max-width: 840px; } .page-head { @@ -267,12 +332,13 @@ ol { align-items: center; justify-content: space-between; gap: 16px; + padding-bottom: 4px; } .section { display: flex; flex-direction: column; - gap: 8px; + gap: 12px; } .section-head { @@ -281,53 +347,136 @@ ol { justify-content: space-between; } -/* Home: the device on the left, what to do with it on the right. */ +/* Home Layout: Device Overview & Continuity Workspace */ .home { display: grid; - grid-template-columns: minmax(220px, 280px) minmax(0, 1fr); - gap: 64px; + grid-template-columns: 280px minmax(0, 1fr); + gap: 32px; max-width: 1080px; } -.home-device, -.home-main { +.home-device { + position: sticky; + top: 0; + align-self: start; display: flex; flex-direction: column; gap: 16px; - min-width: 0; + padding: 20px; + background: var(--surface); + border: 1px solid var(--line); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-card); } .home-main { - gap: 32px; -} - -.home-device { - position: sticky; - top: 0; - align-self: start; + display: flex; + flex-direction: column; + gap: 24px; + min-width: 0; } .device-icon { + display: grid; + place-items: center; + width: 48px; + height: 48px; + border-radius: var(--radius-md); + background: var(--fill); + border: 1px solid var(--line); color: var(--text-2); - margin-bottom: 8px; } .device-icon.online { - color: var(--accent); + color: var(--success); + background: var(--success-soft); + border-color: color-mix(in srgb, var(--success) 30%, transparent); +} + +.device-actions { + display: flex; + flex-direction: column; + gap: 8px; + margin-top: 4px; +} + +/* Continuity Capabilities Deck */ + +.continuity-hub { + display: flex; + flex-direction: column; + gap: 12px; +} + +.continuity-deck { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); + gap: 10px; +} + +.capability-card { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 8px; + padding: 14px 16px; + border-radius: var(--radius-md); + background: var(--surface); + border: 1px solid var(--line); + box-shadow: var(--shadow-sm); + text-align: left; + transition: all 0.15s var(--ease); +} + +.capability-card:hover:not(:disabled) { + border-color: var(--line-strong); + background: var(--raised); + transform: translateY(-1px); +} + +.capability-card:active:not(:disabled) { + transform: translateY(0); +} + +.capability-card:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.capability-icon { + display: grid; + place-items: center; + width: 32px; + height: 32px; + border-radius: var(--radius-sm); + background: var(--fill); + color: var(--text); + flex-shrink: 0; +} + +.capability-title { + font-size: 14px; + font-weight: 600; + color: var(--text); +} + +.capability-sub { + font-size: 12px; + color: var(--text-2); + line-height: 1.3; } -.device-actions, .send-actions { display: flex; flex-wrap: wrap; - gap: 8px; + gap: 10px; } -@media (max-width: 900px) { +@media (max-width: 880px) { .home { grid-template-columns: 1fr; - gap: 40px; + gap: 24px; } .home-device { @@ -335,42 +484,61 @@ ol { } } -/* Buttons. Pills that squeeze a little while pressed. */ +@media (max-width: 640px) { + .pane-scroll { + padding: 20px 16px 32px; + } + + .rail { + width: 60px; + } + + .rail-label { + display: none; + } +} + +/* Buttons */ .btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; - height: 40px; - padding: 0 20px; - border-radius: 999px; + height: 38px; + padding: 0 16px; + border-radius: var(--radius-md); font-size: 14px; font-weight: 600; white-space: nowrap; - transition: - background 0.2s var(--ease), - border-radius 0.2s var(--ease); + border: 1px solid transparent; + transition: all 0.15s var(--ease); +} + +.btn:hover:not(:disabled) { + filter: brightness(1.02); } .btn:active:not(:disabled) { - border-radius: 12px; + transform: translateY(1px); } .btn:disabled { - opacity: 0.4; + opacity: 0.45; + cursor: not-allowed; } .btn-large { - height: 52px; - padding: 0 26px; - font-size: 15px; + height: 44px; + padding: 0 20px; + font-size: 14px; } .btn-small { height: 32px; - padding: 0 14px; + padding: 0 12px; font-size: 13px; + border-radius: var(--radius-sm); } .btn-filled { @@ -379,20 +547,24 @@ ol { } .btn-filled:hover:not(:disabled) { - background: color-mix(in srgb, var(--accent) 88%, var(--text)); + background: var(--accent-hover); } .btn-tonal { background: var(--fill); + color: var(--text); + border-color: var(--line); } .btn-tonal:hover:not(:disabled) { background: var(--fill-hover); + border-color: var(--line-strong); } .btn-text { - padding: 0 12px; + padding: 0 10px; color: var(--accent); + background: none; } .btn-text:hover:not(:disabled) { @@ -404,22 +576,23 @@ ol { } .btn-text.danger:hover { - background: color-mix(in srgb, var(--error) 12%, transparent); + background: var(--error-soft); } .btn-danger { background: var(--error); - color: var(--bg); + color: #ffffff; } .icon-btn { display: grid; place-items: center; - width: 36px; - height: 36px; - border-radius: 999px; + width: 32px; + height: 32px; + border-radius: var(--radius-sm); color: var(--text-2); flex-shrink: 0; + transition: all 0.15s var(--ease); } .icon-btn:hover:not(:disabled) { @@ -429,16 +602,17 @@ ol { .icon-btn:disabled { opacity: 0.4; + cursor: not-allowed; } -/* Status */ +/* Status Indicators */ .status { display: inline-flex; align-items: center; gap: 8px; color: var(--text-2); - font-size: 14px; + font-size: 13px; font-weight: 600; } @@ -447,7 +621,8 @@ ol { width: 8px; height: 8px; border-radius: 50%; - background: var(--text-2); + background: var(--text-3); + flex-shrink: 0; } .status.online { @@ -465,18 +640,27 @@ ol { margin-left: 6px; color: var(--text-2); font-weight: 500; + font-size: 12px; } -/* Text box */ +/* Quick Text Composer */ .composer { display: flex; align-items: center; gap: 8px; - height: 52px; - padding: 0 6px 0 20px; - border-radius: 999px; - background: var(--fill); + height: 46px; + padding: 0 6px 0 14px; + border-radius: var(--radius-md); + background: var(--surface); + border: 1px solid var(--line); + box-shadow: var(--shadow-sm); + transition: border-color 0.15s var(--ease); +} + +.composer:focus-within { + border-color: var(--accent); + box-shadow: 0 0 0 1px var(--accent); } .composer.disabled { @@ -489,66 +673,67 @@ ol { border: none; outline: none; background: none; + font-size: 14px; } .composer-send { display: grid; place-items: center; - width: 40px; - height: 40px; - border-radius: 999px; + width: 34px; + height: 34px; + border-radius: var(--radius-sm); background: var(--accent); color: var(--on-accent); flex-shrink: 0; + transition: all 0.15s var(--ease); } -.composer-send:disabled { - background: none; - color: var(--text-2); -} - -/* Empty and error screens */ - -.empty, -.standalone { - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - gap: 16px; - min-height: 70vh; - text-align: center; +.composer-send:hover:not(:disabled) { + background: var(--accent-hover); } -.standalone { - min-height: 100vh; - padding: 24px; +.composer-send:disabled { + background: var(--fill); + color: var(--text-3); } -/* Lists. Rows sit on the page, divided by a hairline. */ +/* Lists & Rows */ .list { display: flex; flex-direction: column; + background: var(--surface); + border: 1px solid var(--line); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-card); + overflow: hidden; } .list-item { display: flex; align-items: center; - gap: 16px; - min-height: 64px; - padding: 12px 0; + gap: 14px; + min-height: 56px; + padding: 10px 16px; border-top: 1px solid var(--line); + transition: background 0.15s var(--ease); } .list-item:first-child { border-top: none; } +.list-item:hover { + background: var(--hover); +} + .list-leading { display: grid; place-items: center; - width: 24px; + width: 32px; + height: 32px; + border-radius: var(--radius-sm); + background: var(--fill); color: var(--text-2); flex-shrink: 0; } @@ -564,7 +749,9 @@ ol { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; + font-size: 14px; font-weight: 500; + color: var(--text); } .list-sub { @@ -572,7 +759,7 @@ ol { text-overflow: ellipsis; white-space: nowrap; color: var(--text-2); - font-size: 13px; + font-size: 12px; } .list-sub.wrap { @@ -582,7 +769,7 @@ ol { .list-trailing { display: flex; align-items: center; - gap: 4px; + gap: 6px; flex-shrink: 0; } @@ -592,7 +779,7 @@ ol { .status-text { color: var(--text-2); - font-size: 13px; + font-size: 12px; font-weight: 600; } @@ -603,33 +790,36 @@ ol { .day { display: flex; flex-direction: column; - gap: 4px; + gap: 6px; } .day-label { color: var(--text-2); - font-size: 13px; + font-size: 12px; font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.03em; + padding: 0 4px; } .notification-buttons { display: flex; flex-wrap: wrap; - gap: 8px; - margin-top: 10px; + gap: 6px; + margin-top: 8px; } .notification .composer { - height: 44px; - margin-top: 10px; + height: 40px; + margin-top: 8px; } -/* Progress */ +/* Progress Indicators */ .progress { - height: 4px; + height: 5px; margin: 6px 0 4px; - border-radius: 999px; + border-radius: var(--radius-xs); background: var(--fill); overflow: hidden; } @@ -660,23 +850,24 @@ ol { .switch { position: relative; - width: 52px; - height: 32px; - border-radius: 999px; - background: var(--fill-hover); + width: 44px; + height: 26px; + border-radius: var(--radius-md); + background: var(--line-strong); flex-shrink: 0; - transition: background 0.2s var(--ease); + transition: background 0.15s var(--ease); } .switch span { position: absolute; - top: 8px; - left: 8px; - width: 16px; - height: 16px; - border-radius: 50%; - background: var(--text-2); - transition: all 0.2s var(--ease); + top: 3px; + left: 3px; + width: 20px; + height: 20px; + border-radius: var(--radius-sm); + background: var(--surface); + box-shadow: var(--shadow-sm); + transition: all 0.15s var(--ease); } .switch[aria-checked="true"] { @@ -684,16 +875,16 @@ ol { } .switch[aria-checked="true"] span { - top: 4px; - left: 24px; - width: 24px; - height: 24px; - background: var(--on-accent); + left: 21px; } .button-group { display: inline-flex; - gap: 2px; + gap: 1px; + padding: 2px; + background: var(--fill); + border-radius: var(--radius-md); + border: 1px solid var(--line); flex-shrink: 0; } @@ -701,59 +892,59 @@ ol { display: inline-flex; align-items: center; gap: 6px; - height: 36px; - padding: 0 14px; - background: var(--fill); + height: 30px; + padding: 0 12px; + background: none; font-size: 13px; - font-weight: 600; - transition: background 0.2s var(--ease); -} - -.button-group button:first-child { - border-radius: 999px 6px 6px 999px; -} - -.button-group button:last-child { - border-radius: 6px 999px 999px 6px; + font-weight: 500; + color: var(--text-2); + border-radius: var(--radius-sm); + transition: all 0.15s var(--ease); } .button-group button:hover { - background: var(--fill-hover); + color: var(--text); } .button-group button[aria-checked="true"] { - background: var(--accent); - color: var(--on-accent); + background: var(--surface); + color: var(--text); + box-shadow: var(--shadow-sm); + font-weight: 600; } .chips { display: flex; flex-wrap: wrap; - gap: 8px; + gap: 6px; } .chip { display: inline-flex; align-items: center; gap: 6px; - height: 32px; - padding: 0 14px; - border-radius: 999px; + height: 30px; + padding: 0 12px; + border-radius: var(--radius-sm); border: 1px solid var(--line); + background: var(--surface); color: var(--text-2); - font-size: 13px; - font-weight: 600; + font-size: 12px; + font-weight: 500; + transition: all 0.15s var(--ease); } .chip:hover { background: var(--hover); + color: var(--text); } .chip[aria-checked="true"], .chip[aria-selected="true"] { - border-color: transparent; + border-color: var(--accent); background: var(--accent-soft); color: var(--accent); + font-weight: 600; } .toolbar { @@ -768,19 +959,21 @@ ol { display: flex; align-items: center; gap: 8px; - height: 40px; - padding: 0 16px; - border-radius: 999px; + height: 36px; + padding: 0 12px; + border-radius: var(--radius-sm); background: var(--fill); + border: 1px solid var(--line); color: var(--text-2); } .search input { - width: 180px; + width: 200px; border: none; outline: none; background: none; color: var(--text); + font-size: 13px; } .swatches { @@ -791,29 +984,35 @@ ol { .swatch { display: grid; place-items: center; - width: 28px; - height: 28px; - border-radius: 50%; + width: 26px; + height: 26px; + border-radius: var(--radius-sm); + border: 1px solid rgba(0, 0, 0, 0.1); + transition: transform 0.15s var(--ease); } .swatch[aria-checked="true"] { - outline: 2px solid var(--text); + outline: 2px solid var(--accent); outline-offset: 2px; + transform: scale(1.1); } .field, .input-textarea { width: 100%; - padding: 12px 16px; - border: none; - border-radius: 14px; + padding: 10px 14px; + border: 1px solid var(--line); + border-radius: var(--radius-md); outline: none; - background: var(--fill); + background: var(--surface); + font-size: 14px; + transition: border-color 0.15s var(--ease); } .field:focus, .input-textarea:focus { - box-shadow: inset 0 0 0 2px var(--accent); + border-color: var(--accent); + box-shadow: 0 0 0 1px var(--accent); } .input-textarea { @@ -827,50 +1026,43 @@ ol { } .address-form .field { - border-radius: 999px; - height: 40px; - padding: 0 16px; + height: 36px; + padding: 0 12px; } .error-banner { color: var(--error); - font-size: 14px; + font-size: 13px; } -/* Devices */ +/* Devices Tab */ .device { display: flex; flex-direction: column; gap: 12px; - padding-top: 24px; - border-top: 1px solid var(--line); -} - -.device:first-of-type { - border-top: none; - padding-top: 0; + padding: 16px 20px; + background: var(--surface); + border: 1px solid var(--line); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-card); } .device-head { display: flex; align-items: center; - gap: 16px; -} - -.device-head .list-text { - gap: 2px; + gap: 14px; } -/* Dropping files */ +/* Drop Target Scrim */ .drop-scrim { position: fixed; inset: 0; display: grid; place-items: center; - background: color-mix(in srgb, var(--bg) 88%, transparent); - backdrop-filter: blur(6px); + background: rgba(15, 23, 42, 0.4); + backdrop-filter: blur(4px); pointer-events: none; z-index: 20; } @@ -880,13 +1072,15 @@ ol { flex-direction: column; align-items: center; gap: 12px; - padding: 56px 72px; + padding: 48px 64px; border: 2px dashed var(--accent); - border-radius: 28px; + border-radius: var(--radius-xl); + background: var(--surface); + box-shadow: var(--shadow-dialog); text-align: center; } -/* Dialogs. The one raised surface, since they sit over the page. */ +/* Dialog Windows */ .scrim { position: fixed; @@ -894,30 +1088,24 @@ ol { display: grid; place-items: center; padding: 24px; - background: rgba(0, 0, 0, 0.5); + background: rgba(15, 23, 42, 0.55); + backdrop-filter: blur(6px); z-index: 30; } .dialog { display: flex; flex-direction: column; - gap: 20px; + gap: 18px; width: min(640px, 100%); max-height: calc(100vh - 48px); overflow-y: auto; - padding: 28px; + padding: 24px; border: 1px solid var(--line); - border-radius: 28px; - background: var(--raised); + border-radius: var(--radius-xl); + background: var(--surface); color: var(--text); -} - -dialog.dialog { - margin: auto; -} - -dialog.dialog::backdrop { - background: rgba(0, 0, 0, 0.5); + box-shadow: var(--shadow-dialog); } .dialog-small { @@ -929,17 +1117,21 @@ dialog.dialog::backdrop { align-items: flex-start; justify-content: space-between; gap: 16px; + border-bottom: 1px solid var(--line); + padding-bottom: 14px; } .dialog-title { - font-size: 22px; + font-size: 18px; font-weight: 600; letter-spacing: -0.01em; + color: var(--text); } .dialog-subtitle { - margin-top: 4px; + margin-top: 2px; color: var(--text-2); + font-size: 13px; } .dialog-detail { @@ -948,22 +1140,25 @@ dialog.dialog::backdrop { .dialog-actions { display: flex; + align-items: center; justify-content: flex-end; flex-wrap: wrap; gap: 8px; + border-top: 1px solid var(--line); + padding-top: 14px; } .pair-show { display: grid; grid-template-columns: 1fr auto; align-items: center; - gap: 32px; + gap: 28px; } .steps { display: flex; flex-direction: column; - gap: 14px; + gap: 12px; counter-reset: step; } @@ -972,18 +1167,19 @@ dialog.dialog::backdrop { align-items: center; gap: 12px; counter-increment: step; + font-size: 14px; } .steps li::before { content: counter(step); display: grid; place-items: center; - width: 28px; - height: 28px; - border-radius: 50%; + width: 24px; + height: 24px; + border-radius: var(--radius-xs); background: var(--accent-soft); color: var(--accent); - font-size: 13px; + font-size: 12px; font-weight: 700; flex-shrink: 0; } @@ -991,11 +1187,12 @@ dialog.dialog::backdrop { .qr { display: grid; place-items: center; - width: 220px; - height: 220px; - padding: 12px; - border-radius: 20px; + width: 200px; + height: 200px; + padding: 10px; + border-radius: var(--radius-md); background: #ffffff; + border: 1px solid var(--line); color: var(--text-2); } @@ -1009,7 +1206,7 @@ dialog.dialog::backdrop { align-items: center; gap: 8px; color: var(--text-2); - font-size: 14px; + font-size: 13px; } .waiting::before { @@ -1018,16 +1215,9 @@ dialog.dialog::backdrop { height: 8px; border-radius: 50%; background: var(--accent); - animation: pulse 1.6s var(--ease) infinite; } -@keyframes pulse { - 50% { - opacity: 0.3; - } -} - -/* Snackbar */ +/* Snackbar Notification Toast */ .snackbar { position: fixed; @@ -1037,13 +1227,14 @@ dialog.dialog::backdrop { display: flex; align-items: center; gap: 10px; - max-width: min(560px, calc(100vw - 48px)); - padding: 14px 20px; - border-radius: 999px; + max-width: min(520px, calc(100vw - 48px)); + padding: 10px 16px; + border-radius: var(--radius-md); background: var(--text); color: var(--bg); - font-size: 14px; + font-size: 13px; font-weight: 500; + box-shadow: var(--shadow-dialog); z-index: 40; } diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index 6d2e41b..fd596b8 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -954,24 +954,28 @@ export default function App() { return (
    @@ -1297,30 +1301,29 @@ function HomeView(props: HomeViewProps) { return (
    @@ -1440,55 +1447,30 @@ function HomeView(props: HomeViewProps) {
    )} -
    - {online ? ( -
    - +
    +
    + + {online && ( - - - -
    - ) : ( -
    - -
    - )} + )} +
    +
    { @@ -1499,7 +1481,7 @@ function HomeView(props: HomeViewProps) { onTextInputChange(e.target.value)} - placeholder={online ? `Send text to ${peer.displayName}` : `Queue text for ${peer.displayName}`} + placeholder={online ? `Send text or link to ${peer.displayName}...` : `Queue text for ${peer.displayName}...`} aria-label="Text to send" /> {online && linkIn(textInput) && ( @@ -1513,17 +1495,80 @@ function HomeView(props: HomeViewProps) { onTextInputChange(""); } }} - title="Send link to continue on phone" + title="Send as active browser tab on phone" > Handoff )}
    + {online && ( +
    + Continuity Suite +
    + + + + + + + +
    +
    + )} + {online && notifications.length > 0 && (

    Notifications

    diff --git a/apps/desktop/src/HandoffCard.tsx b/apps/desktop/src/HandoffCard.tsx index 04f1361..890afbb 100644 --- a/apps/desktop/src/HandoffCard.tsx +++ b/apps/desktop/src/HandoffCard.tsx @@ -40,9 +40,9 @@ export function HandoffCard({ item, peerName, onOpen, onDismiss }: HandoffCardPr justifyContent: "space-between", gap: 16, padding: "16px 20px", - borderRadius: 20, + borderRadius: "var(--radius-lg)", background: "var(--accent-soft)", - border: "1px solid color-mix(in srgb, var(--accent) 30%, transparent)", + border: "1px solid color-mix(in srgb, var(--accent) 25%, transparent)", }} >
    @@ -50,9 +50,9 @@ export function HandoffCard({ item, peerName, onOpen, onDismiss }: HandoffCardPr style={{ display: "grid", placeItems: "center", - width: 40, - height: 40, - borderRadius: 12, + width: 36, + height: 36, + borderRadius: "var(--radius-sm)", background: "var(--accent)", color: "var(--on-accent)", flexShrink: 0, From bc49e9416df8d2ba15dce009ecad81e4141a874a Mon Sep 17 00:00:00 2001 From: Samarth Rajesh Lad <142334685+samyyy2311@users.noreply.github.com> Date: Thu, 8 Oct 2026 23:45:59 +0530 Subject: [PATCH 13/14] fix(desktop): use tauri async runtime spawn in runtime init and dev npm scripts --- apps/desktop/src-tauri/src/main.rs | 6 +++--- apps/desktop/src-tauri/tauri.conf.json | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index 6ac3fc8..1329089 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -638,7 +638,7 @@ fn permission_prompt( let _ = app_handle.emit("permission-request", question); let (pending, app) = (pending_answers.clone(), app_handle.clone()); - tokio::spawn(async move { + tauri::async_runtime::spawn(async move { tokio::time::sleep_until(request.deadline).await; if pending.lock().remove(&id).is_some() { let _ = app.emit("permission-request-closed", id); @@ -757,7 +757,7 @@ fn session_state_listener( ); let app = app_handle.clone(); let peer_fp = peer.to_string(); - tokio::spawn(async move { + tauri::async_runtime::spawn(async move { tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; if let Some(state) = app.try_state::() { flush_offline_transfers(&app, &state, &peer_fp).await; @@ -1836,7 +1836,7 @@ fn initialize_desktop_runtime( drop_folder.clone(), app_handle.clone(), ); - tokio::spawn(async move { + tauri::async_runtime::spawn(async move { loop { tokio::time::sleep(tokio::time::Duration::from_secs(3)).await; let folder_opt = drop_folder_for_loop.lock().clone(); diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index b6b6ab1..12747df 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -4,9 +4,9 @@ "version": "0.1.0", "identifier": "in.caffeinelabs.continue.desktop", "build": { - "beforeDevCommand": "pnpm dev", + "beforeDevCommand": "npm run dev", "devUrl": "http://localhost:1420", - "beforeBuildCommand": "pnpm build", + "beforeBuildCommand": "npm run build", "frontendDist": "../dist" }, "app": { From 1afa7f1db6e2e20ac94b6abb4113da32aa928f4c Mon Sep 17 00:00:00 2001 From: Samarth Rajesh Lad <142334685+samyyy2311@users.noreply.github.com> Date: Fri, 9 Oct 2026 00:12:46 +0530 Subject: [PATCH 14/14] fix(desktop): ensure window visible by default and add window show fallbacks --- apps/desktop/src-tauri/src/main.rs | 8 +++++++- apps/desktop/src-tauri/src/tray.rs | 17 ++++++++++++++--- apps/desktop/src-tauri/tauri.conf.json | 3 ++- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index 1329089..6255e74 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -1988,7 +1988,13 @@ fn main() { tracing::warn!("No tray icon, so closing the window will quit: {error}"); } start_at_login_by_default(app.handle(), &app_data); - if !std::env::args().any(|arg| arg == BACKGROUND_ARG) { + if std::env::args().any(|arg| arg == BACKGROUND_ARG) { + tracing::info!("Startup: in background mode (--background)"); + if let Some(window) = app.get_webview_window("main") { + let _ = window.hide(); + } + } else { + tracing::info!("Startup: in foreground mode, calling tray::show_window"); tray::show_window(app.handle()); } Ok(()) diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rs index b03432d..69618ef 100644 --- a/apps/desktop/src-tauri/src/tray.rs +++ b/apps/desktop/src-tauri/src/tray.rs @@ -50,9 +50,20 @@ pub fn exists(app: &AppHandle) -> bool { pub fn show_window(app: &AppHandle) { if let Some(window) = app.get_webview_window("main") { - let _ = window.show(); - let _ = window.unminimize(); - let _ = window.set_focus(); + tracing::info!("show_window: found 'main' window; showing, unminimizing, and setting focus"); + let r1 = window.show(); + let r2 = window.unminimize(); + let r3 = window.set_focus(); + tracing::info!("show_window results: show={r1:?}, unminimize={r2:?}, focus={r3:?}"); + } else { + let windows = app.webview_windows(); + tracing::warn!("show_window: 'main' window not found! Total webview windows count = {}", windows.len()); + for (label, window) in windows { + tracing::info!("show_window: showing window with label: '{label}'"); + let _ = window.show(); + let _ = window.unminimize(); + let _ = window.set_focus(); + } } } diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 12747df..8933029 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -12,6 +12,7 @@ "app": { "windows": [ { + "label": "main", "title": "Continue", "width": 1040, "height": 720, @@ -19,7 +20,7 @@ "minHeight": 520, "resizable": true, "fullscreen": false, - "visible": false + "visible": true } ], "security": {