//! Clipboard sync agent (user-session half). //! //! Sunshine runs as LocalSystem in Session 0 and cannot reach the interactive //! desktop's clipboard. This Tauri-side module is the user-session agent: it //! pulls inbound clipboard events from the service over SSE and pushes local //! clipboard changes back to the service via HTTP. //! //! Wire format (v1, little-endian): //! //! ```text //! u8 version=1 //! u8 kind (1 = utf8 text, 2 = png image, 3 = blob ref JSON, //! 4 = file-transfer offer JSON) //! u32 token (echo-suppression nonce) //! u32 length //! bytes payload (length bytes) //! ``` //! //! kind=3 (REF) payload is a small UTF-8 JSON object: //! `{"id":"","mime":"image/png","size":12345}`. The actual blob is //! transferred out-of-band over HTTPS (`/api/v1/clipboard/blob[/]`) so we //! can move payloads larger than the single-packet 65 KB wire ceiling. //! //! Compound clipboard (no wire-format change): a clipboard change carrying //! BOTH text and an image is emitted as two consecutive frames sharing a //! non-zero token, text frame first, image frame second. Peers without //! aggregation apply the frames in order and end with the image — the exact //! v1 outcome — so no version negotiation is needed. This agent applies each //! frame as it arrives (zero added latency) and retains the text payload; //! when the image lands — inline or after its REF blob fetch — the clipboard //! is upgraded with one compound write carrying both flavors. Single-flavor //! changes keep the legacy token=0 single frame. Burst text is always inline //! (a REF text frame would race the image frame onto the wire and flip //! legacy peers' final state to text); the image frame may still use REF. //! Outbound compound text is deliberately limited to nonempty inline text: //! empty text is equivalent to no caption, and an oversized caption is omitted. //! This is a supported-content snapshot, not a lossless OS MIME-format mirror. //! A standalone inbound empty text frame remains valid as a remote clear. //! //! Echo suppression compares the complete current clipboard, including absent //! flavors. Reads and inbound writes share the state lock so a watcher cannot //! record an intermediate snapshot as a new local change. use std::collections::HashMap; use std::sync::{ atomic::{AtomicBool, AtomicI64, AtomicU8, Ordering}, Arc, Mutex, }; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use base64::Engine as _; use clipboard_rs::{ common::RustImage as _, Clipboard, ClipboardContext, ClipboardHandler, ClipboardWatcher, ClipboardWatcherContext, RustImageData, WatcherShutdown, }; use log::{debug, info, warn}; use serde::Serialize; use tauri::async_runtime::JoinHandle; use tokio::sync::Notify; use crate::clipboard_health as health; use crate::sunshine::{create_https_client, create_sse_https_client, get_sunshine_url}; const WIRE_VERSION: u8 = 1; const KIND_TEXT: u8 = 1; const KIND_PNG: u8 = 2; const KIND_REF: u8 = 3; const KIND_FILE_OFFER: u8 = 4; const MAX_TEXT_BYTES: usize = 1 * 1024 * 1024; const MAX_IMAGE_BYTES: usize = 50 * 1024 * 1024; // matches service blob cap const MAX_IMAGE_PIXELS: u64 = 32 * 1024 * 1024; /// Payload size at/above which we switch from inline (KIND_TEXT/KIND_PNG) /// to out-of-band blob transfer (KIND_REF). Single-packet wire ceiling is /// ~65525 bytes of payload, so 60000 leaves comfortable headroom. const INLINE_THRESHOLD: usize = 60_000; /// The service rejects /item bodies above 65500 bytes; a burst text frame /// (10-byte header + payload) must stay inline, so larger text degrades the /// change to image-only rather than racing a REF text frame. const BURST_TEXT_MAX_INLINE: usize = 65_490; /// How long burst text stays retained after its frame applied — purely a /// memory bound; application is immediate on arrival (see module docs). const BURST_RETENTION: Duration = Duration::from_secs(5); const MAX_PENDING_BURSTS: usize = 32; // The blob endpoint accepts MIME types without parameters. Wire text is UTF-8. const MIME_TEXT: &str = "text/plain"; const MIME_PNG: &str = "image/png"; /// A file offer too long for one control message travels as a blob of this type. pub(crate) const MIME_FILE_OFFER: &str = "application/vnd.sunshine.file-offer+json"; const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(15); const SSE_RECONNECT_BACKOFF: Duration = Duration::from_secs(3); // Supervisor cadence and stuck thresholds. The supervisor treats each child // (sse task / heartbeat task / watcher thread) as independently restartable: // a finished task or a wedged watcher is respawned in place, rate-limited by // RESPAWN_MIN_GAP so a crash-looping child degrades to periodic retries. const SUPERVISOR_INTERVAL: Duration = Duration::from_secs(10); const WATCHER_BUSY_STUCK: Duration = Duration::from_secs(60); const SSE_DISCONNECTED_STUCK: Duration = Duration::from_secs(180); const RESPAWN_MIN_GAP: Duration = Duration::from_secs(30); const TRANSPORT_STOPPED: u8 = 0; const TRANSPORT_CONNECTING: u8 = 1; const TRANSPORT_CONNECTED: u8 = 2; const TRANSPORT_DISCONNECTED: u8 = 3; static TRANSPORT_STATE: AtomicU8 = AtomicU8::new(TRANSPORT_STOPPED); static LAST_CONNECTED_AT_MS: AtomicI64 = AtomicI64::new(0); static LAST_TRANSPORT_ERROR: Mutex> = Mutex::new(None); /// Epoch ms since the transport entered (and continuously stayed in) /// TRANSPORT_DISCONNECTED; 0 when connected/connecting/stopped. static DISCONNECTED_SINCE_MS: AtomicI64 = AtomicI64::new(0); fn now_ms() -> i64 { SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_millis() as i64 } fn create_sse_client() -> Result { create_sse_https_client().map_err(|e| format!("创建 SSE HTTP 客户端失败: {}", e)) } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Kind { Text, Png, Ref, FileOffer, } impl Kind { fn from_byte(b: u8) -> Option { match b { KIND_TEXT => Some(Kind::Text), KIND_PNG => Some(Kind::Png), KIND_REF => Some(Kind::Ref), KIND_FILE_OFFER => Some(Kind::FileOffer), _ => None, } } fn to_byte(self) -> u8 { match self { Kind::Text => KIND_TEXT, Kind::Png => KIND_PNG, Kind::Ref => KIND_REF, Kind::FileOffer => KIND_FILE_OFFER, } } } struct Frame { kind: Kind, token: u32, payload: Vec, } #[derive(serde::Serialize, serde::Deserialize, Debug)] struct RefMeta { id: String, mime: String, size: u64, } fn encode_frame(f: &Frame) -> Vec { let mut out = Vec::with_capacity(10 + f.payload.len()); out.push(WIRE_VERSION); out.push(f.kind.to_byte()); out.extend_from_slice(&f.token.to_le_bytes()); out.extend_from_slice(&(f.payload.len() as u32).to_le_bytes()); out.extend_from_slice(&f.payload); out } fn decode_frame(bytes: &[u8]) -> Option { if bytes.len() < 10 || bytes[0] != WIRE_VERSION { return None; } let kind = Kind::from_byte(bytes[1])?; let token = u32::from_le_bytes(bytes[2..6].try_into().ok()?); let len = u32::from_le_bytes(bytes[6..10].try_into().ok()?) as usize; if bytes.len() < 10 + len { return None; } Some(Frame { kind, token, payload: bytes[10..10 + len].to_vec(), }) } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum ImageIdentity { Pixels(u64), Encoded(u64), } #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct ClipboardIdentity { text: Option, image: Option, } impl ClipboardIdentity { fn new(text: Option<&[u8]>, png: Option<&[u8]>, pixel_hash: Option) -> Self { Self { // Match the outbound/compound contract: empty text is no caption. // This also suppresses watcher echoes after a standalone clear. text: text.filter(|bytes| !bytes.is_empty()).map(hash_payload), image: png.map(|bytes| match pixel_hash { Some(hash) => ImageIdentity::Pixels(hash), None => ImageIdentity::Encoded(hash_payload(bytes)), }), } } } #[derive(Default)] struct EchoState { current: Option, } impl EchoState { fn observe(&mut self, identity: ClipboardIdentity) -> bool { let unchanged = self.current == Some(identity); self.current = Some(identity); unchanged } } fn hash_payload(bytes: &[u8]) -> u64 { use std::collections::hash_map::DefaultHasher; use std::hash::{Hash as _, Hasher as _}; let mut h = DefaultHasher::new(); bytes.hash(&mut h); h.finish() } /// Pixel identity of an image. The platform clipboard re-encodes image data /// on every write/read round trip (Windows stores CF_DIB and macOS /// synthesizes new flavors), so payload bytes are not a stable echo key for /// images; pixels survive those lossless conversions. fn hash_image_pixels(img: &RustImageData) -> Option { use std::collections::hash_map::DefaultHasher; use std::hash::{Hash as _, Hasher as _}; let rgba = img.to_rgba8().ok()?; let mut h = DefaultHasher::new(); rgba.dimensions().hash(&mut h); rgba.as_raw().hash(&mut h); Some(h.finish()) } #[derive(Default)] struct State { enabled: bool, sse_task: Option>, heartbeat_task: Option>, supervisor_task: Option>, /// Liveness of the spawned tasks. tauri's JoinHandle has no /// is_finished(), so each wrapper task clears its flag on exit. sse_alive: Arc, heartbeat_alive: Arc, watcher_shutdown: Option, watcher_thread: Option>, stop: Option>, echo: Arc>, busy: Option>, next_token: u32, } static AGENT: std::sync::LazyLock> = std::sync::LazyLock::new(|| Mutex::new(State::default())); #[derive(Serialize, Clone)] pub struct ClipboardStatus { /// Local user-session agent is running (watcher + SSE pump active). pub agent_active: bool, /// Panel-local preference. This is separate from Sunshine's host setting. pub local_enabled: bool, /// Sunshine service has clipboard sync allowed (config not force-disabled). pub service_allowed: Option, pub transport_state: &'static str, pub last_connected_at_ms: Option, #[serde(skip_serializing_if = "Option::is_none")] pub last_error: Option, /// The class of the last failure, as a fixed word ("none" while there is none). pub last_error_class: &'static str, /// What the host said in its last answer to the heartbeat: whether it counts this agent as alive, and how many streams it has. #[serde(skip_serializing_if = "Option::is_none")] pub host_gui_alive: Option, #[serde(skip_serializing_if = "Option::is_none")] pub host_session_count: Option, #[serde(skip_serializing_if = "Option::is_none")] pub last_heartbeat_ok_ms: Option, /// The class of the heartbeat's last failure ("none" when its last call worked). pub heartbeat_error: &'static str, /// Why the status could not ask the host about its setting ("none" when it could). With this word set, `service_allowed` is unknown, not "allowed". pub capability_error: &'static str, } fn set_transport_state(state: u8, error: Option) { let previous = TRANSPORT_STATE.swap(state, Ordering::AcqRel); if previous == TRANSPORT_CONNECTED && state != TRANSPORT_CONNECTED { health::left_connected(); } if state == TRANSPORT_CONNECTED && previous != TRANSPORT_CONNECTED { health::connected(); } *LAST_TRANSPORT_ERROR .lock() .unwrap_or_else(|e| e.into_inner()) = error; match state { TRANSPORT_CONNECTED | TRANSPORT_STOPPED => { DISCONNECTED_SINCE_MS.store(0, Ordering::Release) } TRANSPORT_DISCONNECTED => { // Keep the contiguous-disconnected window open across CONNECTING // retries; only a successful connect closes it. DISCONNECTED_SINCE_MS .compare_exchange(0, now_ms(), Ordering::AcqRel, Ordering::Acquire) .ok(); } _ => {} } if state == TRANSPORT_CONNECTED { LAST_CONNECTED_AT_MS.store(now_ms(), Ordering::Release); } } fn transport_state_name(state: u8) -> &'static str { match state { TRANSPORT_CONNECTING => "connecting", TRANSPORT_CONNECTED => "connected", TRANSPORT_DISCONNECTED => "disconnected", _ => "stopped", } } // ---------- Outbound watcher ---------- struct WatcherCallbacks { echo: Arc>, /// Epoch-ms timestamp of the in-flight snapshot; 0 = idle. Storing the /// time (instead of a bool) lets the supervisor detect a wedged watcher. busy: Arc, } impl ClipboardHandler for WatcherCallbacks { fn on_clipboard_change(&mut self) { // Coalesce: if we're already mid-snapshot drop additional fires. // Only claim the 0 -> now transition: refreshing the timestamp on // coalesced events would keep pushing the supervisor's stuck-detection // deadline forward forever while events keep arriving. if self .busy .compare_exchange(0, now_ms(), Ordering::AcqRel, Ordering::Acquire) .is_err() { return; } WATCHER_LAST_EVENT_MS.store(now_ms(), Ordering::Release); WATCHER_SNAPSHOT_COUNT.fetch_add(1, Ordering::Relaxed); let echo = self.echo.clone(); let busy = self.busy.clone(); // Do the (potentially blocking) clipboard read off the watcher thread // so we don't stall additional events. spawn_blocking is fine. tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn_blocking(move || snapshot_and_post(&echo)) .await .ok(); busy.store(0, Ordering::Release); }); } } fn snapshot_and_post(echo: &Arc>) { // Serialize the complete read with inbound writes. A historical per-flavor // cache loses A -> B -> A changes and splits compound clipboards. let mut st = echo.lock().unwrap_or_else(|e| e.into_inner()); let ctx = match ClipboardContext::new() { Ok(c) => c, Err(e) => { debug!("clipboard ctx open failed: {e}"); return; } }; // Read text and image BEFORE deciding on the file guard: QQ/WeChat // image-message copies attach a cache-file reference (CF_HDROP) AND the // real bitmap, and skipping every file clipboard silently dropped those // syncs. Explorer file copies carry no bitmap at all, so the guard only // needs to fire when nothing transferable came out — a pure file // clipboard must not leak its file names as text. let text = match ctx.get_text() { Ok(t) if !t.is_empty() => Some(t), _ => None, }; // A silent get_image failure here is indistinguishable from "the // clipboard had no bitmap" in the logs, which cost a full round of // host-side debugging; surface the distinction. let img = match ctx.get_image() { Ok(i) if !i.is_empty() => Some(i), Ok(_) => { debug!("clipboard snapshot: image flavor present but empty"); None } Err(e) => { debug!("clipboard snapshot: get_image failed: {e}"); None } }; // Bound the pixel count BEFORE encoding: to_png() on a stray huge // bitmap allocates the full encoded buffer only to fail the byte cap // below. Mirrors the inbound MAX_IMAGE_PIXELS guard. if let Some(i) = &img { let (w, h) = i.get_size(); if (w as u64) * (h as u64) > MAX_IMAGE_PIXELS { warn!( "local clipboard image {}x{} exceeds {} pixel cap; dropped", w, h, MAX_IMAGE_PIXELS ); return; } } let png_bytes = img.as_ref().and_then(|i| match i.to_png() { Ok(p) => { let bytes = p.get_bytes().to_vec(); if bytes.is_empty() { None } else { Some(bytes) } } Err(e) => { debug!("clipboard image to_png failed: {e}"); None } }); let pixel_hash = img.as_ref().and_then(hash_image_pixels); if let Some(pb) = &png_bytes { if pb.len() > MAX_IMAGE_BYTES { warn!( "local clipboard png {}B exceeds {}B cap; dropped", pb.len(), MAX_IMAGE_BYTES ); return; } } let text_bytes = match text { Some(t) => { let bytes = t.into_bytes(); if bytes.len() > MAX_TEXT_BYTES { warn!( "local clipboard text {}B exceeds {}B cap; dropped", bytes.len(), MAX_TEXT_BYTES ); return; } Some(bytes) } None => None, }; // File guard, evaluated with the payload in hand: skip only when the // file references came with nothing transferable (Explorer copies carry // no bitmap). QQ/WeChat image-message copies attach CF_HDROP + the real // bitmap and sync the bitmap below; inbound applies keep the strict // guard so remote content never clobbers a pending local file paste. if let Ok(files) = ctx.get_files() { if !files.is_empty() && text_bytes.is_none() && png_bytes.is_none() { st.current = None; // The names never travel as text; the files themselves are offered // for pasting through the file-transfer endpoints (kind 4). info!("local file clipboard: offering {} path(s) as files", files.len()); crate::file_transfer::offer_copied_files(files); return; } } if st.observe(ClipboardIdentity::new( text_bytes.as_deref(), png_bytes.as_deref(), pixel_hash, )) { return; } // A mixed clipboard (image + fallback text label from browsers/IM, or a // genuinely compound copy) is emitted as a compound burst: text frame // first, image second, one shared non-zero token. Peers without // aggregation apply the frames in order and keep the image — the exact // v1 outcome. Single-flavor changes keep the legacy token=0 single frame. match (text_bytes, png_bytes) { (Some(tb), Some(pb)) => { if tb.len() > BURST_TEXT_MAX_INLINE { // Burst text must stay inline (a REF text frame would race // the image frame onto the wire and flip legacy peers' // final state to text); degrade to image-only. info!( "clipboard burst text {}B exceeds inline cap; sending image only", tb.len() ); post_outbound(Kind::Png, pb, MIME_PNG); return; } post_burst(tb, pb); } (None, Some(pb)) => { post_outbound(Kind::Png, pb, MIME_PNG); } (Some(tb), None) => { post_outbound(Kind::Text, tb, MIME_TEXT); } (None, None) => { debug!("clipboard snapshot produced no text or image payload; nothing to sync"); } } } /// Emit a compound burst: one spawned task posting the text frame and then /// the image frame with sequential awaits — two independent HTTP POSTs have /// no ordering guarantee, and legacy peers rely on text-first ordering to /// end with the image. fn post_burst(text: Vec, png: Vec) { let token = next_token(); tauri::async_runtime::spawn(async move { let text_frame = encode_frame(&Frame { kind: Kind::Text, token, payload: text, }); if let Err(e) = post_item(text_frame).await { warn!("clipboard burst text POST failed: {e}"); return; } if png.len() <= INLINE_THRESHOLD { let frame = encode_frame(&Frame { kind: Kind::Png, token, payload: png, }); if let Err(e) = post_item(frame).await { warn!("clipboard burst image POST failed: {e}"); } } else if let Err(e) = upload_and_post_ref(png, MIME_PNG, token).await { warn!("clipboard burst blob transfer failed: {e}"); } }); } /// Decide inline vs out-of-band based on payload size, then dispatch. fn kind_name(kind: Kind) -> &'static str { match kind { Kind::Text => "text", Kind::Png => "image", Kind::Ref => "ref", Kind::FileOffer => "file-offer", } } fn post_outbound(kind: Kind, payload: Vec, mime: &'static str) { // One INFO line per posted change: user-driven copies are sparse, and // this is the only way to see the watcher working in the 30-entry // in-memory log buffer. info!( "clipboard watcher: posted {} ({}B)", kind_name(kind), payload.len() ); if payload.len() <= INLINE_THRESHOLD { post_inline(kind, payload); } else { post_via_blob(kind, payload, mime); } } fn post_inline(kind: Kind, payload: Vec) { // Single-flavor changes stay token=0: standalone frames apply // immediately on aggregating peers and are never coalesced. let body = encode_frame(&Frame { kind, token: 0, payload, }); tauri::async_runtime::spawn(async move { if let Err(e) = post_item(body).await { warn!("clipboard /item POST failed: {e}"); } }); } fn post_via_blob(kind: Kind, payload: Vec, mime: &'static str) { tauri::async_runtime::spawn(async move { if let Err(e) = upload_and_post_ref(payload, mime, 0).await { warn!("clipboard blob upload failed (kind={:?}): {e}", kind); } }); } /// Upload a payload as an out-of-band blob and post the KIND_REF descriptor /// frame. Used by single-flavor changes (token 0) and the image frame of a /// compound burst (the burst token, so aggregating peers can group it). async fn upload_and_post_ref(payload: Vec, mime: &str, token: u32) -> Result<(), String> { let size = payload.len() as u64; let id = upload_blob(payload, mime).await?; let meta = RefMeta { id, mime: mime.to_string(), size, }; let json = serde_json::to_vec(&meta).map_err(|e| format!("ref json encode failed: {e}"))?; let body = encode_frame(&Frame { kind: Kind::Ref, token, payload: json, }); post_item(body).await } fn next_token() -> u32 { let mut st = AGENT.lock().unwrap_or_else(|e| e.into_inner()); st.next_token = st.next_token.wrapping_add(1).max(1); st.next_token } async fn post_item(body: Vec) -> Result<(), String> { let result = post_item_inner(body).await; health::post(result.is_ok()); result } async fn post_item_inner(body: Vec) -> Result<(), String> { let url = get_sunshine_url().await?; let client = create_https_client()?; let resp = client .post(format!( "{}/api/v1/clipboard/item", url.trim_end_matches('/') )) .header("Content-Type", "application/octet-stream") .body(body) .send() .await .map_err(|e| e.to_string())?; if !resp.status().is_success() { return Err(format!("status {}", resp.status())); } Ok(()) } /// The two calls a file offer goes out through; tests record them instead. trait OfferTransport { async fn post_item(&self, body: Vec) -> Result<(), String>; async fn upload_blob(&self, bytes: Vec, mime: &str) -> Result; } struct HostTransport; impl OfferTransport for HostTransport { async fn post_item(&self, body: Vec) -> Result<(), String> { post_item(body).await } async fn upload_blob(&self, bytes: Vec, mime: &str) -> Result { upload_blob(bytes, mime).await } } /// Send a file offer to the clients: inline (kind 4) while it fits one /// control message, otherwise uploaded as a blob and announced with a /// KIND_REF frame of type MIME_FILE_OFFER (a folder of a thousand short /// names is already past the service's 65500-byte /item limit). An upload or /// post failure is returned to the caller. pub async fn post_file_offer_payload(payload: Vec) -> Result<(), String> { send_file_offer(&HostTransport, payload, next_token()).await } async fn send_file_offer( transport: &T, payload: Vec, token: u32, ) -> Result<(), String> { if payload.len() <= INLINE_THRESHOLD { let body = encode_frame(&Frame { kind: Kind::FileOffer, token, payload, }); return transport.post_item(body).await; } let size = payload.len() as u64; let id = transport.upload_blob(payload, MIME_FILE_OFFER).await?; let meta = RefMeta { id, mime: MIME_FILE_OFFER.to_string(), size, }; let json = serde_json::to_vec(&meta).map_err(|e| format!("ref json encode failed: {e}"))?; let body = encode_frame(&Frame { kind: Kind::Ref, token, payload: json, }); transport.post_item(body).await } /// What the host answers to the capability call (the heartbeat and the status read both make it). struct CapabilityAnswer { clipboard_sync: Option, gui_alive: Option, session_count: Option, } /// One capability call. An error carries the class of the failure (fixed words) and the text for the local log. async fn capability_call() -> Result { let url = get_sunshine_url() .await .map_err(|e| (health::classify_text(&e), e))?; let client = create_https_client().map_err(|e| (health::classify_text(&e), e))?; let resp = client .post(format!( "{}/api/v1/clipboard/capability", url.trim_end_matches('/') )) .send() .await .map_err(|e| (health::classify_reqwest(&e), e.to_string()))?; if !resp.status().is_success() { let class = health::classify_status(resp.status().as_u16()); return Err((class, format!("status {}", resp.status()))); } let json: serde_json::Value = resp .json() .await .map_err(|e| (health::ErrClass::Other, e.to_string()))?; Ok(CapabilityAnswer { clipboard_sync: json.get("clipboard_sync").and_then(|v| v.as_bool()), gui_alive: json.get("gui_alive").and_then(|v| v.as_bool()), session_count: json.get("session_count").and_then(|v| v.as_u64()), }) } async fn post_capability_once() -> Result<(), String> { match capability_call().await { Ok(answer) => { health::heartbeat_ok(answer.gui_alive, answer.session_count); Ok(()) } Err((class, text)) => { // a failure the classes do not name is still "the heartbeat failed" health::heartbeat_failed(if class == health::ErrClass::Other { health::ErrClass::Heartbeat } else { class }); Err(text) } } } /// POST /api/v1/clipboard/blob with raw bytes + X-Clipboard-Mime header. /// Returns the assigned blob id on success. async fn upload_blob(bytes: Vec, mime: &str) -> Result { let result = upload_blob_inner(bytes, mime).await; if result.is_err() { health::post(false); } result } async fn upload_blob_inner(bytes: Vec, mime: &str) -> Result { let url = get_sunshine_url().await?; let client = create_https_client()?; let resp = client .post(format!( "{}/api/v1/clipboard/blob", url.trim_end_matches('/') )) .header("Content-Type", "application/octet-stream") .header("X-Clipboard-Mime", mime) .body(bytes) .send() .await .map_err(|e| e.to_string())?; let status = resp.status(); if !status.is_success() { return Err(format!("upload status {}", status)); } let json: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?; json.get("id") .and_then(|v| v.as_str()) .map(|s| s.to_string()) .ok_or_else(|| "upload response missing id".to_string()) } /// GET /api/v1/clipboard/blob/. Returns (bytes, mime). async fn fetch_blob(id: &str) -> Result<(Vec, String), String> { let url = get_sunshine_url().await?; let client = create_https_client()?; let resp = client .get(format!( "{}/api/v1/clipboard/blob/{}", url.trim_end_matches('/'), id )) .send() .await .map_err(|e| e.to_string())?; if !resp.status().is_success() { return Err(format!("fetch status {}", resp.status())); } let mime = resp .headers() .get(reqwest::header::CONTENT_TYPE) .and_then(|v| v.to_str().ok()) .unwrap_or("application/octet-stream") .to_string(); let bytes = resp.bytes().await.map_err(|e| e.to_string())?.to_vec(); Ok((bytes, mime)) } // ---------- Inbound apply ---------- /// Retained text payloads of in-flight compound bursts (frames sharing a /// non-zero token). Text applies on arrival; the image later upgrades the /// clipboard to one compound write using the retained bytes. static BURSTS: std::sync::LazyLock, Instant)>>> = std::sync::LazyLock::new(|| Mutex::new(HashMap::new())); fn prune_bursts(map: &mut HashMap, Instant)>) { map.retain(|_, (_, ts)| ts.elapsed() < BURST_RETENTION); } fn retain_burst_text(token: u32, text: Vec) { let mut map = BURSTS.lock().unwrap_or_else(|e| e.into_inner()); prune_bursts(&mut map); if map.len() >= MAX_PENDING_BURSTS { // Defensive bound against a pathological sender. if let Some(oldest) = map.iter().min_by_key(|(_, (_, ts))| *ts).map(|(k, _)| *k) { map.remove(&oldest); } } map.insert(token, (text, Instant::now())); } fn take_burst_text(token: u32) -> Option> { let mut map = BURSTS.lock().unwrap_or_else(|e| e.into_inner()); prune_bursts(&mut map); map.remove(&token).map(|(text, _)| text) } /// Frames are applied synchronously here, in SSE stream order: the /// compound-upgrade logic relies on text-before-image processing, which /// per-frame spawns onto a thread pool cannot guarantee (and which, prior /// to this, could reorder plain v1 multi-frame applies too). fn handle_inbound_frame(frame: Frame, sid: Option, echo: &Arc>) { match frame.kind { Kind::Ref => { let echo = echo.clone(); tauri::async_runtime::spawn(async move { apply_inbound_ref(frame, sid, echo).await; }); } // A client copied files: put them on the host clipboard (file_transfer::inbound). Kind::FileOffer => crate::file_transfer::inbound::apply_client_offer(sid, &frame.payload), _ if frame.token == 0 => apply_inbound_inline(frame, echo), Kind::Text => { retain_burst_text(frame.token, frame.payload.clone()); apply_inbound_inline(frame, echo); } Kind::Png => { let token = frame.token; deliver_burst_png(token, &frame.payload, echo); } } } fn deliver_burst_png(token: u32, png: &[u8], echo: &Arc>) { match take_burst_text(token) { Some(text) => apply_compound(&text, png, echo), None => apply_inbound_inline( Frame { kind: Kind::Png, token, payload: png.to_vec(), }, echo, ), } } async fn apply_inbound_ref(frame: Frame, sid: Option, echo: Arc>) { let meta: RefMeta = match serde_json::from_slice(&frame.payload) { Ok(m) => m, Err(e) => { warn!("inbound REF: bad json: {e}"); return; } }; if meta.id.is_empty() || meta.id.len() > 128 { warn!("inbound REF: bad id length"); return; } let (bytes, _mime_from_header) = match fetch_blob(&meta.id).await { Ok(t) => t, Err(e) => { warn!("inbound REF: fetch_blob({}) failed: {e}", meta.id); health::apply(false); return; } }; // Trust the reference's mime (set by the original poster). let kind = match meta.mime.as_str() { m if m.starts_with("text/") => Kind::Text, "image/png" => Kind::Png, MIME_FILE_OFFER => Kind::FileOffer, other => { warn!("inbound REF: unsupported mime '{}'", other); return; } }; if kind == Kind::FileOffer { crate::file_transfer::inbound::apply_client_offer(sid, &bytes); return; } let token = frame.token; if token != 0 && matches!(kind, Kind::Text | Kind::Png) { // Blob payload of a compound burst: route through the aggregator so // the image can upgrade the already-applied text flavor. match kind { Kind::Text => { retain_burst_text(token, bytes.clone()); let _ = tauri::async_runtime::spawn_blocking(move || { apply_inbound_inline( Frame { kind: Kind::Text, token, payload: bytes, }, &echo, ) }) .await; } Kind::Png => { let _ = tauri::async_runtime::spawn_blocking(move || { deliver_burst_png(token, &bytes, &echo) }) .await; } _ => unreachable!(), } return; } let frame = Frame { kind, token, payload: bytes, }; let echo = echo.clone(); let _ = tauri::async_runtime::spawn_blocking(move || apply_inbound_inline(frame, &echo)).await; } /// Write text + image flavors in one clipboard transaction. Only remember a /// successful write, while excluding the watcher from intermediate states. fn apply_compound(text: &[u8], png: &[u8], echo: &Arc>) { // Preserve a pending local file paste (mirrors the inline-path guard). if let Ok(ctx) = ClipboardContext::new() { if let Ok(files) = ctx.get_files() { if !files.is_empty() { debug!("local file clipboard detected; inbound compound dropped"); return; } } } let text_str = match std::str::from_utf8(text) { Ok(s) if !s.is_empty() && !s.contains('\0') => s, _ => { warn!("inbound compound text unusable; applying image only"); apply_inbound_inline( Frame { kind: Kind::Png, token: 0, payload: png.to_vec(), }, echo, ); return; } }; // Bound decoded pixel count (mirrors the inline PNG path). let cursor = std::io::Cursor::new(png); if let Ok(reader) = image::ImageReader::new(cursor).with_guessed_format() { if let Ok((w, h)) = reader.into_dimensions() { if (w as u64) * (h as u64) > MAX_IMAGE_PIXELS { warn!( "inbound image {}x{} exceeds {} pixel cap; dropped", w, h, MAX_IMAGE_PIXELS ); return; } } } let img = match RustImageData::from_bytes(png) { Ok(i) => i, Err(e) => { warn!("RustImageData::from_bytes failed: {e}"); return; } }; let pixel_hash = hash_image_pixels(&img); let mut st = echo.lock().unwrap_or_else(|e| e.into_inner()); #[cfg(windows)] { match img.to_rgba8() { Ok(rgba) => match crate::win_clipboard::write_compound(text_str, &rgba, png) { Ok(()) => { st.current = Some(ClipboardIdentity::new(Some(text), Some(png), pixel_hash)); health::apply(true); debug!( "applied compound clipboard (text {}B + PNG {}B)", text.len(), png.len() ); return; } Err(e) => { warn!("compound clipboard write failed: {e}; falling back to image only"); } }, Err(e) => { warn!("compound rgba conversion failed: {e}; falling back to image only"); } } if let Ok(ctx) = ClipboardContext::new() { if ctx.set_image(img).is_ok() { st.current = Some(ClipboardIdentity::new(None, Some(png), pixel_hash)); health::apply(true); return; } } health::apply(false); return; } #[cfg(not(windows))] { // clipboard-rs has no compound write off-Windows; degrade to // sequential writes, image last (v1 outcome). if let Ok(ctx) = ClipboardContext::new() { if ctx.set_text(text_str.to_string()).is_ok() { st.current = Some(ClipboardIdentity::new(Some(text), None, None)); } health::apply(ctx.set_image(img).map(|()| { st.current = Some(ClipboardIdentity::new(None, Some(png), pixel_hash)); }).is_ok()); } debug!( "applied compound clipboard via sequential fallback (text {}B + PNG {}B)", text.len(), png.len() ); } } fn apply_inbound_inline(frame: Frame, echo: &Arc>) { // Preserve a local file clipboard: Explorer/Finder copies can carry a // thumbnail image, and overwriting them with remote content would // destroy the pending file paste. Mirrors the Qt client's guard. if let Ok(ctx) = ClipboardContext::new() { if let Ok(files) = ctx.get_files() { if !files.is_empty() { debug!("local file clipboard detected; inbound dropped"); return; } } } let mut st = echo.lock().unwrap_or_else(|e| e.into_inner()); let ctx = match ClipboardContext::new() { Ok(c) => c, Err(e) => { warn!("inbound: ClipboardContext::new failed: {e}"); health::apply(false); return; } }; match frame.kind { Kind::Text => { let identity = ClipboardIdentity::new(Some(&frame.payload), None, None); let text = match String::from_utf8(frame.payload) { Ok(s) => s, Err(_) => { warn!("inbound text not valid utf8; dropped"); return; } }; if let Err(e) = ctx.set_text(text) { warn!("inbound set_text failed: {e}"); health::apply(false); } else { st.current = Some(identity); health::apply(true); } } Kind::Png => { // Bound decoded pixel count. let cursor = std::io::Cursor::new(&frame.payload); if let Ok(reader) = image::ImageReader::new(cursor).with_guessed_format() { if let Ok((w, h)) = reader.into_dimensions() { if (w as u64) * (h as u64) > MAX_IMAGE_PIXELS { warn!( "inbound image {}x{} exceeds {} pixel cap; dropped", w, h, MAX_IMAGE_PIXELS ); return; } } } let img = match RustImageData::from_bytes(&frame.payload) { Ok(i) => i, Err(e) => { warn!("RustImageData::from_bytes failed: {e}"); return; } }; let identity = ClipboardIdentity::new(None, Some(&frame.payload), hash_image_pixels(&img)); if let Err(e) = ctx.set_image(img) { warn!("inbound set_image failed: {e}"); health::apply(false); } else { st.current = Some(identity); health::apply(true); } } Kind::Ref => { // Already unwrapped above; should never reach here. warn!("apply_inbound_inline got Kind::Ref; dropped"); } Kind::FileOffer => { // Host GUI currently only sends this to clients. If a client sends // one back, ignore it rather than writing arbitrary file metadata // to the host clipboard. warn!("inbound file offer on host GUI agent; dropped"); } } } // ---------- SSE pump ---------- async fn sse_pump(stop: Arc, echo: Arc>) { use futures_util::StreamExt as _; 'outer: loop { // Bail-out check. tokio::select! { _ = stop.notified() => return, _ = tokio::time::sleep(Duration::from_millis(0)) => {} } set_transport_state(TRANSPORT_CONNECTING, None); // the stream starts when the host is ready (proxy_server::host_ready), not by failing and asking again every backoff let _ = crate::proxy_server::host_ready(std::time::Duration::from_secs(30)).await; let url = match get_sunshine_url().await { Ok(u) => u, Err(e) => { warn!("clipboard SSE: get_sunshine_url: {e}"); health::note_error(health::classify_text(&e)); set_transport_state(TRANSPORT_DISCONNECTED, Some(e)); if wait_or_stop(&stop, SSE_RECONNECT_BACKOFF).await { return; } continue; } }; let endpoint = format!("{}/api/v1/clipboard/events", url.trim_end_matches('/')); let client = match create_sse_client() { Ok(c) => c, Err(e) => { warn!("clipboard SSE: client: {e}"); health::note_error(health::classify_text(&e)); set_transport_state(TRANSPORT_DISCONNECTED, Some(e)); if wait_or_stop(&stop, SSE_RECONNECT_BACKOFF).await { return; } continue; } }; let resp = match client .get(&endpoint) .header("Accept", "text/event-stream") .send() .await { Ok(r) => r, Err(e) => { // a failure to connect is the first thing to look at when the clipboard does not work: warning level, so the exported log keeps it warn!("clipboard SSE connect failed: {e}"); health::note_error(health::classify_reqwest(&e)); set_transport_state(TRANSPORT_DISCONNECTED, Some(e.to_string())); if wait_or_stop(&stop, SSE_RECONNECT_BACKOFF).await { return; } continue; } }; if resp.status() == reqwest::StatusCode::UNAUTHORIZED { // the host has published a credential and does not accept it yet (it was just started or reinstalled): it is not ready after all. Ask again at once, not after the backoff. debug!("clipboard SSE: the host does not accept its credential yet"); crate::proxy_server::host_not_ready(); health::note_error(health::ErrClass::Http401); set_transport_state(TRANSPORT_DISCONNECTED, Some("service returned 401".to_string())); if wait_or_stop(&stop, std::time::Duration::from_millis(400)).await { return; } continue; } if !resp.status().is_success() { let error = format!("service returned {}", resp.status()); warn!("clipboard SSE bad status: {}", resp.status()); health::note_error(health::classify_status(resp.status().as_u16())); set_transport_state(TRANSPORT_DISCONNECTED, Some(error)); if wait_or_stop(&stop, SSE_RECONNECT_BACKOFF).await { return; } continue; } info!("clipboard SSE connected"); set_transport_state(TRANSPORT_CONNECTED, None); let mut stream = resp.bytes_stream(); let mut buf = Vec::::new(); loop { tokio::select! { _ = stop.notified() => return, chunk = stream.next() => match chunk { Some(Ok(bytes)) => { buf.extend_from_slice(&bytes); // Parse \n\n-separated SSE events. while let Some(end) = find_event_end(&buf) { let raw = buf.drain(..end + 2).collect::>(); if let Some((frame, sid)) = parse_sse_event(&raw) { handle_inbound_frame(frame, sid, &echo); } } } Some(Err(e)) => { debug!("clipboard SSE read error: {e}"); health::note_error(health::classify_reqwest(&e)); set_transport_state(TRANSPORT_DISCONNECTED, Some(e.to_string())); break; } None => { debug!("clipboard SSE stream ended"); health::note_error(health::ErrClass::StreamEnded); set_transport_state( TRANSPORT_DISCONNECTED, Some("event stream ended".to_string()), ); break; } } } } if wait_or_stop(&stop, SSE_RECONNECT_BACKOFF).await { return; } // try reconnect continue 'outer; } } async fn wait_or_stop(stop: &Notify, dur: Duration) -> bool { tokio::select! { _ = stop.notified() => true, _ = tokio::time::sleep(dur) => false, } } fn find_event_end(buf: &[u8]) -> Option { buf.windows(2).position(|w| w == b"\n\n") } /// The frame and the id of the streaming session it came from (the event's /// "id:" line), which a client's file offer needs to be pasted. fn parse_sse_event(raw: &[u8]) -> Option<(Frame, Option)> { let s = std::str::from_utf8(raw).ok()?; let mut data_b64: Option = None; let mut sid: Option = None; for line in s.split('\n') { let line = line.trim_end_matches('\r'); if let Some(rest) = line.strip_prefix("id:") { sid = rest.trim().parse().ok(); } else if let Some(rest) = line.strip_prefix("data: ") { data_b64 = Some(rest.to_string()); } else if let Some(rest) = line.strip_prefix("data:") { data_b64 = Some(rest.trim_start().to_string()); } } let b64 = data_b64?; let bytes = base64::engine::general_purpose::STANDARD.decode(b64).ok()?; decode_frame(&bytes).map(|frame| (frame, sid)) } // ---------- Heartbeat ---------- async fn heartbeat_pump(stop: Arc) { loop { if let Err(e) = post_capability_once().await { // warning level, once per failure: the exported log must show that the host stopped hearing the agent warn!("clipboard heartbeat failed: {e}"); } if wait_or_stop(&stop, HEARTBEAT_INTERVAL).await { return; } } } // ---------- Supervisor ---------- // // Every child task/thread of the agent is fire-and-forget by nature: a panic // or a wedged blocking call produces no signal, and the failure modes are // silent (a dead heartbeat keeps transport_state CONNECTED while the service // expires gui_alive and drops Mac→host traffic; a wedged watcher snapshot // swallows every subsequent local change). The supervisor is the single // liveness owner: it periodically checks each child and respawns it in place, // rate-limited so a crash-looping child degrades to periodic retries. static LAST_SSE_RESPAWN_MS: AtomicI64 = AtomicI64::new(0); static LAST_HEARTBEAT_RESPAWN_MS: AtomicI64 = AtomicI64::new(0); static LAST_WATCHER_RESPAWN_MS: AtomicI64 = AtomicI64::new(0); /// Liveness evidence for the watcher: the OS clipboard sequence number at /// the last supervisor pass, the epoch-ms of the last delivered /// on_clipboard_change, and snapshots posted since the last heartbeat. static WATCHER_LAST_SEQ: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); static WATCHER_LAST_EVENT_MS: AtomicI64 = AtomicI64::new(0); static WATCHER_SNAPSHOT_COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); static LAST_WATCHER_HEARTBEAT_MS: AtomicI64 = AtomicI64::new(0); #[cfg(windows)] unsafe extern "system" { /// Plain Win32 import: does not require opening the clipboard and works /// even when the watcher's listener registration is dead. fn GetClipboardSequenceNumber() -> u32; } fn lock_agent() -> std::sync::MutexGuard<'static, State> { AGENT.lock().unwrap_or_else(|e| e.into_inner()) } fn respawn_allowed(now: i64, last: &AtomicI64) -> bool { let l = last.load(Ordering::Acquire); l == 0 || now.saturating_sub(l) >= RESPAWN_MIN_GAP.as_millis() as i64 } async fn supervisor(stop: Arc) { loop { if wait_or_stop(&stop, SUPERVISOR_INTERVAL).await { return; } supervise_once(); } } /// One supervision pass. Locks are taken briefly and never held across an /// await; at most one action runs per pass to keep respawn bookkeeping /// simple. fn supervise_once() { let now = now_ms(); let (sse_dead, hb_dead, watcher_dead) = { let st = lock_agent(); ( !st.sse_alive.load(Ordering::Acquire), !st.heartbeat_alive.load(Ordering::Acquire), st.watcher_thread .as_ref() .map(|t| t.is_finished()) // A missing thread (failed respawn) must count as dead, or // clipboard monitoring stops forever after one spawn error. .unwrap_or(true), ) }; // Dead tokio task = it panicked or exited outside the stop path. Respawn // a fresh one; abort() on an already-finished handle is a no-op. if sse_dead && respawn_allowed(now, &LAST_SSE_RESPAWN_MS) { warn!("clipboard supervisor: sse task died; respawning"); respawn_sse(now); return; } if hb_dead && respawn_allowed(now, &LAST_HEARTBEAT_RESPAWN_MS) { warn!("clipboard supervisor: heartbeat task died; respawning"); respawn_heartbeat(now); return; } if watcher_dead && respawn_allowed(now, &LAST_WATCHER_RESPAWN_MS) { warn!("clipboard supervisor: watcher thread died; respawning"); respawn_watcher(now); return; } // Wedged watcher: a snapshot that never returns swallows every // subsequent change. Read the flag in a short scope — the MutexGuard // temporary of an `if let` scrutinee would stay alive across the branch // body and deadlock respawn_watcher's own lock_agent() — then let // respawn_watcher re-validate `enabled` under its own lock. let busy_started = { let st = lock_agent(); st.busy .as_ref() .map(|b| b.load(Ordering::Acquire)) .unwrap_or(0) }; if busy_started != 0 && now.saturating_sub(busy_started) > WATCHER_BUSY_STUCK.as_millis() as i64 && respawn_allowed(now, &LAST_WATCHER_RESPAWN_MS) { warn!( "clipboard supervisor: watcher snapshot stuck {}ms; restarting watcher", now - busy_started ); respawn_watcher(now); return; } // a run that goes on for days sends its statistics record once a day (the end of the run sends the last one) if health::due(now) { health::mark_sent(); tauri::async_runtime::spawn(send_health_event()); } // Watcher heartbeat: one INFO line every 5 minutes proving the watcher // is cycling, so a silent watcher outage is visible in the 30-entry log // buffer at export time. let last_hb = LAST_WATCHER_HEARTBEAT_MS.load(Ordering::Acquire); if last_hb == 0 || now.saturating_sub(last_hb) > 300_000 { let snapshots = WATCHER_SNAPSHOT_COUNT.swap(0, Ordering::Relaxed); info!( "clipboard supervisor: watcher heartbeat ({} snapshots in the last 5m)", snapshots ); LAST_WATCHER_HEARTBEAT_MS.store(now, Ordering::Release); } // Transport wedged in DISCONNECTED while enabled: the sse task is alive // but its retry loop keeps failing. Recycle it for a fresh client stack. let since = DISCONNECTED_SINCE_MS.load(Ordering::Acquire); if since != 0 && now.saturating_sub(since) > SSE_DISCONNECTED_STUCK.as_millis() as i64 { if respawn_allowed(now, &LAST_SSE_RESPAWN_MS) { warn!( "clipboard supervisor: transport disconnected {}ms; recycling sse task", now - since ); respawn_sse(now); DISCONNECTED_SINCE_MS.store(now_ms(), Ordering::Release); } } // Watcher liveness (Windows): the OS clipboard sequence number moves on // every clipboard write — including our own inbound applies — but a dead // listener never delivers on_clipboard_change, which none of the checks // above can see (the thread is alive and busy is 0). If the sequence // number moved and nothing arrived within 15 s, rebuild the watcher. #[cfg(windows)] { let seq = unsafe { GetClipboardSequenceNumber() }; let last_seq = WATCHER_LAST_SEQ.load(Ordering::Acquire); let last_event = WATCHER_LAST_EVENT_MS.load(Ordering::Acquire); let busy = lock_agent() .busy .as_ref() .map(|b| b.load(Ordering::Acquire)) .unwrap_or(0); let seeded = last_seq != 0; if seeded && seq != last_seq && busy == 0 && (last_event == 0 || now.saturating_sub(last_event) > 15_000) && respawn_allowed(now, &LAST_WATCHER_RESPAWN_MS) { warn!( "clipboard supervisor: os clipboard seq moved {}->{} but no watcher event in {}ms; rebuilding watcher", last_seq, seq, now.saturating_sub(last_event.max(since.max(0))) ); respawn_watcher(now); } WATCHER_LAST_SEQ.store(seq, Ordering::Release); } } fn respawn_sse(now: i64) { let mut st = lock_agent(); if !st.enabled { return; } let Some(stop) = st.stop.clone() else { return; }; let echo = st.echo.clone(); // A fresh flag per generation: abort() cancels asynchronously, so the // dead generation's AliveGuard may drop AFTER the replacement stores // true — sharing the flag would let that late drop mark the healthy // new task as dead and loop the supervisor. let alive = Arc::new(AtomicBool::new(false)); if let Some(old) = st.sse_task.take() { old.abort(); } st.sse_alive = alive.clone(); st.sse_task = Some(spawn_sse_task(&stop, &echo, &alive)); LAST_SSE_RESPAWN_MS.store(now, Ordering::Release); } fn respawn_heartbeat(now: i64) { let mut st = lock_agent(); if !st.enabled { return; } let Some(stop) = st.stop.clone() else { return; }; // Fresh flag per generation (see respawn_sse). let alive = Arc::new(AtomicBool::new(false)); if let Some(old) = st.heartbeat_task.take() { old.abort(); } st.heartbeat_alive = alive.clone(); st.heartbeat_task = Some(spawn_heartbeat_task(&stop, &alive)); LAST_HEARTBEAT_RESPAWN_MS.store(now, Ordering::Release); } fn respawn_watcher(now: i64) { // One lock scope covers the enabled check, the take of the old handles // and the store of the new ones: a concurrent stop() can then never // strand a watcher rebuilt after the shutdown finished. let mut st = lock_agent(); if !st.enabled { return; } let echo = st.echo.clone(); // A fresh busy flag per generation: a wedged old snapshot keeps holding // the previous Arc with a stuck non-zero value, and sharing it would make // the new watcher's compare_exchange(0, ...) reject every event forever. let busy = Arc::new(AtomicI64::new(0)); // Signal the old watcher BEFORE building the replacement so the rebuild // window produces at most one in-flight duplicate snapshot (coalesced by // the generation-local busy flag). Signal only — joining here would // block while the AGENT lock is held. if let Some(sd) = st.watcher_shutdown.take() { sd.stop(); } st.busy = Some(busy.clone()); st.watcher_thread = None; match spawn_watcher_thread(&echo, &busy) { Ok((shutdown, handle)) => { st.watcher_shutdown = Some(shutdown); st.watcher_thread = Some(handle); LAST_WATCHER_RESPAWN_MS.store(now, Ordering::Release); } Err(e) => warn!("clipboard supervisor: watcher respawn failed: {e}"), } } // ---------- Public API: enable / disable / status ---------- /// Clears the owning task's alive flag on every exit path — normal return, /// panic unwind, or cancellation — so the supervisor can always detect death. /// A plain `store(false)` after the await misses panics and aborts, which are /// exactly the failure modes the supervisor exists to catch. struct AliveGuard(Arc); impl Drop for AliveGuard { fn drop(&mut self) { self.0.store(false, Ordering::Release); } } fn spawn_sse_task( stop: &Arc, echo: &Arc>, alive: &Arc, ) -> JoinHandle<()> { let stop = stop.clone(); let echo = echo.clone(); let alive = alive.clone(); alive.store(true, Ordering::Release); tauri::async_runtime::spawn(async move { let _alive = AliveGuard(alive); sse_pump(stop, echo).await; }) } fn spawn_heartbeat_task(stop: &Arc, alive: &Arc) -> JoinHandle<()> { let stop = stop.clone(); let alive = alive.clone(); alive.store(true, Ordering::Release); tauri::async_runtime::spawn(async move { let _alive = AliveGuard(alive); heartbeat_pump(stop).await; }) } fn spawn_watcher_thread( echo: &Arc>, busy: &Arc, ) -> Result<(WatcherShutdown, std::thread::JoinHandle<()>), String> { let mut watcher = ClipboardWatcherContext::new().map_err(|e| format!("ClipboardWatcherContext: {e}"))?; let shutdown = watcher .add_handler(WatcherCallbacks { echo: echo.clone(), busy: busy.clone(), }) .get_shutdown_channel(); let handle = std::thread::Builder::new() .name("clipboard-watcher".into()) .spawn(move || { watcher.start_watch(); }) .map_err(|e| format!("spawn watcher thread: {e}"))?; Ok((shutdown, handle)) } fn spawn_supervisor_task(stop: &Arc) -> JoinHandle<()> { let stop = stop.clone(); tauri::async_runtime::spawn(async move { supervisor(stop).await }) } pub fn start() -> Result<(), String> { let mut st = lock_agent(); if st.enabled { return Ok(()); } health::run_started(); set_transport_state(TRANSPORT_CONNECTING, None); let stop = Arc::new(Notify::new()); let busy = Arc::new(AtomicI64::new(0)); // Spawn watcher thread (blocking; the crate's start_watch() is sync). let (shutdown_tx, watcher_handle) = match spawn_watcher_thread(&st.echo, &busy) { Ok(handles) => handles, Err(e) => { // The run never came up: report disconnected instead of leaving a stuck CONNECTING state. set_transport_state(TRANSPORT_DISCONNECTED, Some(e.clone())); return Err(e); } }; let sse_alive = Arc::new(AtomicBool::new(false)); let heartbeat_alive = Arc::new(AtomicBool::new(false)); let sse_task = spawn_sse_task(&stop, &st.echo, &sse_alive); let heartbeat_task = spawn_heartbeat_task(&stop, &heartbeat_alive); let supervisor_task = spawn_supervisor_task(&stop); st.enabled = true; st.stop = Some(stop); st.busy = Some(busy); st.sse_alive = sse_alive; st.heartbeat_alive = heartbeat_alive; st.sse_task = Some(sse_task); st.heartbeat_task = Some(heartbeat_task); st.watcher_shutdown = Some(shutdown_tx); st.watcher_thread = Some(watcher_handle); st.supervisor_task = Some(supervisor_task); info!("clipboard sync agent started"); Ok(()) } pub fn stop() { let (stop_tx, sse, hb, sup, watcher_shutdown, watcher_thread) = { let mut st = lock_agent(); if !st.enabled { return; } st.enabled = false; st.busy = None; ( st.stop.take(), st.sse_task.take(), st.heartbeat_task.take(), st.supervisor_task.take(), st.watcher_shutdown.take(), st.watcher_thread.take(), ) }; if let Some(s) = &stop_tx { s.notify_waiters(); } if let Some(s) = watcher_shutdown { s.stop(); } if let Some(t) = watcher_thread { let _ = t.join(); } if let Some(t) = sse { t.abort(); } if let Some(t) = hb { t.abort(); } if let Some(t) = sup { t.abort(); } send_health_at_stop(); set_transport_state(TRANSPORT_STOPPED, None); info!("clipboard sync agent stopped"); } pub fn set_enabled(enabled: bool) -> Result<(), String> { if enabled { start() } else { stop(); Ok(()) } } /// The statistics record of the run (clipboard_health), through the host: its own sender owns the identity and the two choices, so a choice that is off sends nothing. async fn send_health_event() { health::mark_sent(); if !health::worth_sending() { return; } let body = serde_json::json!({ "product": "panel", "version": env!("CARGO_PKG_VERSION"), "events": [health::health_event()], }); let Ok(url) = get_sunshine_url().await else { return }; let Ok(client) = create_https_client() else { return }; let _ = client .post(format!("{}/api/telemetry/events", url.trim_end_matches('/'))) .json(&body) .send() .await; } /// The last record of a run, at its end: it waits at most 2 s, on a thread of its own (the caller may be inside a runtime). fn send_health_at_stop() { if !health::worth_sending() { return; } let (done_tx, done_rx) = std::sync::mpsc::channel::<()>(); std::thread::spawn(move || { tauri::async_runtime::block_on(async { let _ = tokio::time::timeout(Duration::from_secs(2), send_health_event()).await; }); let _ = done_tx.send(()); }); let _ = done_rx.recv_timeout(Duration::from_millis(2500)); } fn agent_active() -> bool { lock_agent().enabled } /// Start the agent in the background at app launch. The agent is harmless /// when the service has clipboard sync force-disabled: SSE will simply be /// rejected and outbound posts will 4xx, so we just keep retrying quietly. pub fn auto_start() { if let Err(e) = start() { health::note_error(health::ErrClass::Other); set_transport_state(TRANSPORT_DISCONNECTED, Some(e.clone())); warn!("clipboard auto-start failed: {e}"); } } // ---------- Tauri commands ---------- #[tauri::command] pub async fn clipboard_sync_status() -> ClipboardStatus { // the host's own answer: its setting, whether it has an agent subscribed right now, and a failure to ask is a word, not "allowed" let local_enabled = crate::desktop_settings::load_desktop_settings_from_disk().clipboard_sync_enabled; let (service_allowed, host_alive_now, session_count, capability_error) = if local_enabled { match capability_call().await { Ok(answer) => (answer.clipboard_sync, answer.gui_alive, answer.session_count, "none"), Err((class, _)) => (None, None, None, class.word()), } } else { (None, None, None, "none") }; // read after the call: it can take seconds, and the state, the time and the heartbeat facts may have moved meanwhile let local_agent_active = agent_active(); let now = health::now_ms(); let stream_state = transport_state_name(TRANSPORT_STATE.load(Ordering::Acquire)); let last_connected_at_ms = LAST_CONNECTED_AT_MS.load(Ordering::Acquire); let facts = health::status_facts(); let mut transport_state = health::effective_state(stream_state, last_connected_at_ms, facts.last_heartbeat_ok_ms.unwrap_or(0), now); // the stream is open on this side but the host says it has no subscriber: it does not count the agent, whatever this side thinks if transport_state == "connected" && host_alive_now == Some(false) { transport_state = "degraded"; } ClipboardStatus { agent_active: local_agent_active, local_enabled, service_allowed, transport_state, last_connected_at_ms: (last_connected_at_ms > 0).then_some(last_connected_at_ms), last_error: LAST_TRANSPORT_ERROR .lock() .unwrap_or_else(|e| e.into_inner()) .clone(), last_error_class: facts.last_error_class, host_gui_alive: host_alive_now.or(facts.host_gui_alive), host_session_count: session_count.or(facts.host_session_count), last_heartbeat_ok_ms: facts.last_heartbeat_ok_ms, heartbeat_error: facts.heartbeat_error, capability_error, } } #[cfg(test)] mod status_tests { use super::*; #[test] fn transport_state_names_cover_the_agent_lifecycle() { assert_eq!(transport_state_name(TRANSPORT_STOPPED), "stopped"); assert_eq!(transport_state_name(TRANSPORT_CONNECTING), "connecting"); assert_eq!(transport_state_name(TRANSPORT_CONNECTED), "connected"); assert_eq!(transport_state_name(TRANSPORT_DISCONNECTED), "disconnected"); } #[test] fn the_status_words_are_the_ones_the_page_knows() { // the page branches on these exact words (useTools.js showClipboardSyncStatus) let known = ["stopped", "connecting", "connected", "disconnected", "degraded"]; for state in [TRANSPORT_STOPPED, TRANSPORT_CONNECTING, TRANSPORT_CONNECTED, TRANSPORT_DISCONNECTED] { let word = transport_state_name(state); assert!(known.contains(&word)); let effective = health::effective_state(word, 1, 0, 1 + 10 * 60_000); assert!(known.contains(&effective)); } } } #[cfg(test)] mod echo_tests { use super::*; #[test] fn empty_caption_is_equivalent_to_absent_caption() { let image_only = ClipboardIdentity::new(None, Some(b"png"), Some(10)); let mut state = EchoState { current: Some(image_only), }; assert!(state.observe(ClipboardIdentity::new(Some(b""), Some(b"png"), Some(10)))); assert!(!state.observe(ClipboardIdentity::new( Some(b"caption"), Some(b"png"), Some(10) ))); assert!(!state.observe(image_only)); } #[test] fn standalone_empty_text_is_still_a_valid_clear_frame() { let frame = decode_frame(&encode_frame(&Frame { kind: Kind::Text, token: 0, payload: Vec::new(), })) .unwrap(); assert_eq!(frame.kind, Kind::Text); assert_eq!(frame.token, 0); assert!(frame.payload.is_empty()); let mut state = EchoState { current: Some(ClipboardIdentity::new(Some(b"before"), None, None)), }; assert!(!state.observe(ClipboardIdentity::new(Some(&frame.payload), None, None))); assert!(state.observe(ClipboardIdentity::new(None, None, None))); } #[test] fn a_b_a_is_not_suppressed_by_history() { let mut state = EchoState::default(); let a = ClipboardIdentity::new(Some(b"A"), None, None); let b = ClipboardIdentity::new(Some(b"B"), None, None); assert!(!state.observe(a)); assert!(state.observe(a)); assert!(!state.observe(b)); assert!(!state.observe(a)); } #[test] fn compound_changes_keep_both_flavors() { let mut state = EchoState::default(); let image = ClipboardIdentity::new(None, Some(b"png"), Some(10)); let caption_a = ClipboardIdentity::new(Some(b"A"), Some(b"png"), Some(10)); let caption_b = ClipboardIdentity::new(Some(b"B"), Some(b"png"), Some(10)); assert!(!state.observe(image)); assert!(!state.observe(caption_a)); // same image, newly added caption assert!(!state.observe(caption_b)); // same image, changed caption assert!(!state.observe(ClipboardIdentity::new( Some(b"B"), Some(b"new png"), Some(20) ))); assert!(!state.observe(caption_b)); // back to the earlier image assert!(state.observe(caption_b)); } #[test] fn removing_a_flavor_is_a_new_clipboard() { let compound = ClipboardIdentity::new(Some(b"caption"), Some(b"png"), Some(10)); let mut state = EchoState { current: Some(compound), }; assert!(!state.observe(ClipboardIdentity::new(Some(b"caption"), None, None))); assert!(!state.observe(compound)); assert!(!state.observe(ClipboardIdentity::new(None, Some(b"png"), Some(10)))); } #[test] fn applied_compound_does_not_echo_after_image_reencoding() { let applied = ClipboardIdentity::new(Some(b"caption"), Some(b"wire png"), Some(10)); let mut state = EchoState { current: Some(applied), }; let snapshot = ClipboardIdentity::new(Some(b"caption"), Some(b"reencoded png"), Some(10)); assert!(state.observe(snapshot)); // Byte hashing remains available when pixel conversion is unavailable. let encoded = ClipboardIdentity::new(None, Some(b"png"), None); assert!(!state.observe(encoded)); assert!(state.observe(encoded)); } } #[cfg(test)] mod file_offer_send_tests { use super::*; use std::sync::Mutex; #[derive(Default)] struct Recorder { items: Mutex>>, blobs: Mutex, String)>>, fail_upload: bool, } impl OfferTransport for Recorder { async fn post_item(&self, body: Vec) -> Result<(), String> { self.items.lock().unwrap().push(body); Ok(()) } async fn upload_blob(&self, bytes: Vec, mime: &str) -> Result { if self.fail_upload { return Err("upload status 507".to_string()); } self.blobs.lock().unwrap().push((bytes, mime.to_string())); Ok("b".repeat(32)) } } /// The offer JSON Sunshine makes for a folder of `n` one-byte files. fn offer_of(n: usize) -> Vec { let mut files = vec![serde_json::json!({"path": "bulk", "size": 0, "dir": true, "mtime": 0})]; for i in 0..n { files.push(serde_json::json!({ "path": format!("bulk/f{i:04}.txt"), "size": 1, "dir": false, "mtime": 1_790_000_000, })); } serde_json::to_vec(&serde_json::json!({ "version": 2, "id": "a".repeat(64), "type": "files", "source": "clipboard", "total_size": n, "expires_in": 3600, "files": files, })) .unwrap() } fn run(recorder: &Recorder, payload: Vec) -> Result<(), String> { tokio::runtime::Builder::new_current_thread() .build() .unwrap() .block_on(send_file_offer(recorder, payload, 7)) } #[test] fn a_short_offer_goes_inline() { let recorder = Recorder::default(); let payload = vec![b' '; INLINE_THRESHOLD]; run(&recorder, payload.clone()).unwrap(); assert!(recorder.blobs.lock().unwrap().is_empty()); let items = recorder.items.lock().unwrap(); assert_eq!(items.len(), 1); let frame = decode_frame(&items[0]).unwrap(); assert_eq!(frame.kind, Kind::FileOffer); assert_eq!(frame.token, 7); assert_eq!(frame.payload, payload); } #[test] fn a_long_offer_goes_as_a_blob_and_only_the_ref_is_posted() { let recorder = Recorder::default(); let payload = vec![b' '; INLINE_THRESHOLD + 1]; run(&recorder, payload.clone()).unwrap(); let blobs = recorder.blobs.lock().unwrap(); assert_eq!(blobs.len(), 1); assert_eq!(blobs[0].0, payload); assert_eq!(blobs[0].1, MIME_FILE_OFFER); let items = recorder.items.lock().unwrap(); assert_eq!(items.len(), 1); let frame = decode_frame(&items[0]).unwrap(); assert_eq!(frame.kind, Kind::Ref); assert_eq!(frame.token, 7); let meta: serde_json::Value = serde_json::from_slice(&frame.payload).unwrap(); assert_eq!(meta["mime"], MIME_FILE_OFFER); assert_eq!(meta["size"], payload.len() as u64); assert_eq!(meta["id"], "b".repeat(32)); } #[test] fn a_folder_of_1200_small_files_stays_under_the_item_limit() { let payload = offer_of(1200); assert!( payload.len() + 10 > 65_500, "the case the review measured: {} bytes", payload.len() ); let recorder = Recorder::default(); run(&recorder, payload.clone()).unwrap(); assert_eq!(recorder.blobs.lock().unwrap()[0].0, payload); let items = recorder.items.lock().unwrap(); assert!(items[0].len() <= 65_500); assert_eq!(decode_frame(&items[0]).unwrap().kind, Kind::Ref); } #[test] fn a_failed_upload_is_returned_and_nothing_is_posted() { let recorder = Recorder { fail_upload: true, ..Default::default() }; let err = run(&recorder, offer_of(1200)).unwrap_err(); assert!(err.contains("507"), "{err}"); assert!(recorder.items.lock().unwrap().is_empty()); } }