diff --git a/CLAUDE.md b/CLAUDE.md index 5f40fdc233..e7697cab41 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -73,6 +73,7 @@ A server is reached over SSH, the Monitor (HTTP), both, or is this device (`Spi. ## Rules - **Never run code formatters.** +- **Never classify errors by matching error strings** (`e.toString().contains(...)`, regexes on exception text, or `Result<_, String>` across FFI when Dart branches on the failure). Expose typed FRB error enums from `crates/sbm_ffi/src/api/` (`MoshBridgeError`, `RemoteDesktopBridgeError`, `MuxError`, …) and typed Dart `Err` / `Exception` / OS error codes (`osError?.errorCode`, `PathAccessException`), matching exhaustively by type (`lib/data/model/app/error.dart`). Text matching is permitted only for unstructured external CLI stdout/stderr (e.g. remote shell or `ProxyCommand` stderr) when no structured status code exists. - **No copy that narrates the interface** (the app, the panel, the website): nothing saying what a control does once used, where something loads from, or what a preview leaves out ("the video plays from YouTube once you start it"). The interface shows it. - Names come in through `use`, never as long paths inline: `use crate::api::json::{Json, Max};` then `Json>`, not `crate::api::json::Json>`. - Git LFS holds images, fonts, `.fsbt` and PDFs under `monitor/`, `docs/`, `website/`, `store/` only: F-Droid clones without LFS, so nothing the app's build or `fastlane/` reads goes there (`.gitattributes`). `scripts/check-lfs.sh` fails a build that finds a pointer. diff --git a/crates/sbm_ffi/src/api/mosh.rs b/crates/sbm_ffi/src/api/mosh.rs index a84b671bfd..c0d427b5c6 100644 --- a/crates/sbm_ffi/src/api/mosh.rs +++ b/crates/sbm_ffi/src/api/mosh.rs @@ -12,6 +12,7 @@ use flutter_rust_bridge::frb; use mosh_rs::bootstrap::{build_server_command, parse_mosh_connect, BootstrapOptions}; use mosh_rs::client::{CloseReason, MoshConfig, MoshEvent, MoshSession, MoshWriter}; use mosh_rs::crypto::SessionKey; +use mosh_rs::error::MoshError; use mosh_rs::predict::{PredictionMode, PredictionOverlay, TerminalCursorState}; use tokio::sync::{mpsc, Mutex}; use zeroize::Zeroizing; @@ -90,6 +91,44 @@ impl From for MoshPredictionOverlay { } } +/// Structured error returned by Mosh FFI operations so Dart classifies +/// failures exhaustively without matching diagnostic strings. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MoshBridgeError { + /// The session's run loop has already exited (remote exit or local close). + SessionClosed, + /// Unacknowledged outgoing terminal input exceeded the send buffer limit. + SendBufferFull { message: String }, + /// UDP handshake did not complete before the deadline. + HandshakeTimeout { message: String }, + /// Invalid key, host, or session configuration rejected before connecting. + InvalidConfig { message: String }, + /// Any other transport, DNS, or I/O failure. + Other { message: String }, +} + +impl From for MoshBridgeError { + fn from(err: MoshError) -> Self { + match err { + MoshError::SessionClosed => Self::SessionClosed, + MoshError::SendBufferFull => Self::SendBufferFull { + message: err.to_string(), + }, + MoshError::HandshakeTimeout => Self::HandshakeTimeout { + message: err.to_string(), + }, + MoshError::InvalidKey(_) | MoshError::InvalidBootstrapOption(_) => { + Self::InvalidConfig { + message: err.to_string(), + } + } + other => Self::Other { + message: other.to_string(), + }, + } + } +} + /// Events emitted by an active [`MoshBridgeSession`]. #[derive(Debug, Clone, PartialEq, Eq)] pub enum MoshBridgeEvent { @@ -122,7 +161,7 @@ pub fn mosh_build_server_command( bind_ssh_ip: bool, colors: u16, locale: Option, -) -> Result { +) -> Result { let mut opts = BootstrapOptions::default(); if let Some(bin) = server_binary { let trimmed = bin.trim(); @@ -143,13 +182,13 @@ pub fn mosh_build_server_command( if let Some(loc) = locale { opts.locale = loc; } - build_server_command(&opts).map_err(|e| e.to_string()) + build_server_command(&opts).map_err(MoshBridgeError::from) } /// Parses `MOSH CONNECT ` from `mosh-server` bootstrap output. #[frb(sync)] -pub fn mosh_parse_connect(output: String) -> Result, String> { - let parsed = parse_mosh_connect(&output).map_err(|e| e.to_string())?; +pub fn mosh_parse_connect(output: String) -> Result, MoshBridgeError> { + let parsed = parse_mosh_connect(&output).map_err(MoshBridgeError::from)?; Ok(parsed.map(|info| MoshConnectData { port: info.port, key: info.key.to_base64(), @@ -175,9 +214,9 @@ impl MoshBridgeSession { rows: u16, prediction_mode: MoshPredictionMode, handshake_timeout_ms: u32, - ) -> Result { + ) -> Result { let key = Zeroizing::new(key); - let session_key = SessionKey::from_base64(&key).map_err(|e| e.to_string())?; + let session_key = SessionKey::from_base64(&key).map_err(MoshBridgeError::from)?; drop(key); let total_timeout = if handshake_timeout_ms > 0 { @@ -188,11 +227,15 @@ impl MoshBridgeSession { let started = Instant::now(); let server_addr = tokio::time::timeout(total_timeout, resolve_udp_addr(&host, port)) .await - .map_err(|_| format!("timed out resolving Mosh host '{host}'"))??; + .map_err(|_| MoshBridgeError::Other { + message: format!("timed out resolving Mosh host '{host}'"), + })??; let remaining = total_timeout.saturating_sub(started.elapsed()); if remaining.is_zero() { - return Err("Mosh handshake timed out".to_string()); + return Err(MoshBridgeError::Other { + message: format!("timed out resolving Mosh host '{host}'"), + }); } let mut config = MoshConfig::new(server_addr, session_key, cols.max(1), rows.max(1)); @@ -201,7 +244,7 @@ impl MoshBridgeSession { let session = MoshSession::connect(config) .await - .map_err(|e| e.to_string())?; + .map_err(MoshBridgeError::from)?; let (writer, events) = session.split(); Ok(Self { writer, @@ -242,16 +285,16 @@ impl MoshBridgeSession { /// Sends raw terminal input bytes (synchronous, non-blocking). #[frb(sync)] - pub fn write(&self, data: Vec) -> Result<(), String> { - self.writer.write(data).map_err(|e| e.to_string()) + pub fn write(&self, data: Vec) -> Result<(), MoshBridgeError> { + self.writer.write(data).map_err(MoshBridgeError::from) } /// Sends a terminal viewport resize (synchronous, non-blocking). #[frb(sync)] - pub fn resize(&self, cols: u16, rows: u16) -> Result<(), String> { + pub fn resize(&self, cols: u16, rows: u16) -> Result<(), MoshBridgeError> { self.writer .resize(cols.max(1), rows.max(1)) - .map_err(|e| e.to_string()) + .map_err(MoshBridgeError::from) } /// Synchronizes authoritative terminal cursor & alt-screen state for prediction alignment. @@ -263,7 +306,7 @@ impl MoshBridgeSession { cols: u16, rows: u16, in_alt_screen: bool, - ) -> Result<(), String> { + ) -> Result<(), MoshBridgeError> { self.writer .sync_cursor(TerminalCursorState { row, @@ -272,21 +315,21 @@ impl MoshBridgeSession { rows: rows.max(1), in_alt_screen, }) - .map_err(|e| e.to_string()) + .map_err(MoshBridgeError::from) } /// Updates local echo prediction mode at runtime. #[frb(sync)] - pub fn set_prediction_mode(&self, mode: MoshPredictionMode) -> Result<(), String> { + pub fn set_prediction_mode(&self, mode: MoshPredictionMode) -> Result<(), MoshBridgeError> { self.writer .set_prediction_mode(mode.into()) - .map_err(|e| e.to_string()) + .map_err(MoshBridgeError::from) } /// Rebinds the UDP socket and transmits an immediate sync packet (roaming / resume). #[frb(sync)] - pub fn rebind(&self) -> Result<(), String> { - self.writer.rebind().map_err(|e| e.to_string()) + pub fn rebind(&self) -> Result<(), MoshBridgeError> { + self.writer.rebind().map_err(MoshBridgeError::from) } /// Requests graceful shutdown (non-blocking, never dropped under backpressure). @@ -296,20 +339,24 @@ impl MoshBridgeSession { } } -async fn resolve_udp_addr(host: &str, port: u16) -> Result { +async fn resolve_udp_addr(host: &str, port: u16) -> Result { let trimmed = host.trim().trim_start_matches('[').trim_end_matches(']'); if trimmed.is_empty() { - return Err("empty Mosh server host".to_string()); + return Err(MoshBridgeError::InvalidConfig { + message: "empty Mosh server host".to_string(), + }); } if let Ok(ip) = trimmed.parse::() { return Ok(SocketAddr::new(ip, port)); } let mut addrs = tokio::net::lookup_host((trimmed, port)) .await - .map_err(|e| format!("failed to resolve Mosh host '{trimmed}': {e}"))?; - addrs - .next() - .ok_or_else(|| format!("no IP addresses resolved for Mosh host '{trimmed}'")) + .map_err(|e| MoshBridgeError::Other { + message: format!("failed to resolve Mosh host '{trimmed}': {e}"), + })?; + addrs.next().ok_or_else(|| MoshBridgeError::Other { + message: format!("no IP addresses resolved for Mosh host '{trimmed}'"), + }) } #[cfg(test)] @@ -334,6 +381,34 @@ mod tests { #[test] fn invalid_server_binary_is_rejected() { let err = mosh_build_server_command(Some("mosh;id".into()), None, true, 256, None); - assert!(err.is_err()); + assert!(matches!(err, Err(MoshBridgeError::InvalidConfig { .. }))); + } + + #[test] + fn bridge_error_preserves_mosh_error_variants() { + assert_eq!( + MoshBridgeError::from(MoshError::SessionClosed), + MoshBridgeError::SessionClosed, + ); + assert!(matches!( + MoshBridgeError::from(MoshError::SendBufferFull), + MoshBridgeError::SendBufferFull { .. } + )); + assert!(matches!( + MoshBridgeError::from(MoshError::HandshakeTimeout), + MoshBridgeError::HandshakeTimeout { .. } + )); + assert!(matches!( + MoshBridgeError::from(MoshError::InvalidKey("bad")), + MoshBridgeError::InvalidConfig { .. } + )); + assert!(matches!( + MoshBridgeError::from(MoshError::InvalidBootstrapOption("bad")), + MoshBridgeError::InvalidConfig { .. } + )); + assert!(matches!( + MoshBridgeError::from(MoshError::Io(std::io::Error::other("boom"))), + MoshBridgeError::Other { .. } + )); } } diff --git a/crates/sbm_ffi/src/api/remote_desktop.rs b/crates/sbm_ffi/src/api/remote_desktop.rs index d666c4bd58..ef5badcd76 100644 --- a/crates/sbm_ffi/src/api/remote_desktop.rs +++ b/crates/sbm_ffi/src/api/remote_desktop.rs @@ -292,6 +292,13 @@ fn fold_into(queue: &mut VecDeque, command: &SessionCommand) -> } } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum CommandSendError { + Closed, + QueueFull, + Poisoned, +} + impl CommandQueue { fn new() -> Arc { Arc::new(Self { @@ -316,10 +323,10 @@ impl CommandQueue { /// a slow link a fast drag filled the queue, and then a release could be /// replaced by a scroll or dropped for a keystroke — leaving the remote /// button held, so every later touch dragged. - fn send(&self, command: SessionCommand) -> Result<(), ()> { - let mut queue = self.queue.lock().map_err(|_| ())?; - if *self.closed.lock().map_err(|_| ())? { - return Err(()); + fn send(&self, command: SessionCommand) -> Result<(), CommandSendError> { + let mut queue = self.queue.lock().map_err(|_| CommandSendError::Poisoned)?; + if *self.closed.lock().map_err(|_| CommandSendError::Poisoned)? { + return Err(CommandSendError::Closed); } if queue.len() >= CHANNEL_CAPACITY { if matches!(&command, SessionCommand::Close) { @@ -328,7 +335,7 @@ impl CommandQueue { self.notify.notify_one(); return Ok(()); } else if queue.len() >= COMMAND_QUEUE_LIMIT { - return Err(()); + return Err(CommandSendError::QueueFull); } } queue.push_back(command); @@ -493,6 +500,35 @@ impl EventSender { } } +/// Structured error returned by [`RemoteDesktopSessionHandle`] FFI calls so +/// Dart distinguishes closed-session races, backpressure saturation, and +/// permanent configuration errors without matching strings. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RemoteDesktopBridgeError { + /// The background worker thread has already closed its command channel. + SessionClosed, + /// The command queue reached its capacity limit because the session is not draining. + QueueFull, + /// Permanent session parameter validation error (do not auto-retry). + InvalidConfig { message: String }, + /// Failed to spawn the background worker thread. + WorkerSpawnFailed { message: String }, + /// Internal bridge failure (such as a poisoned mutex). + Internal { message: String }, +} + +impl From for RemoteDesktopBridgeError { + fn from(err: CommandSendError) -> Self { + match err { + CommandSendError::Closed => Self::SessionClosed, + CommandSendError::QueueFull => Self::QueueFull, + CommandSendError::Poisoned => Self::Internal { + message: "remote desktop command queue lock poisoned".to_owned(), + }, + } + } +} + /// Opaque native session. Only commands and one-at-a-time event reads cross FFI. #[flutter_rust_bridge::frb(opaque)] pub struct RemoteDesktopSessionHandle { @@ -502,33 +538,44 @@ pub struct RemoteDesktopSessionHandle { impl RemoteDesktopSessionHandle { #[flutter_rust_bridge::frb(sync)] - pub fn start_rdp(params: RdpSessionParams) -> Result { - validate_endpoint(¶ms.connect_host, params.connect_port)?; - validate_size(u32::from(params.width), u32::from(params.height))?; + pub fn start_rdp(params: RdpSessionParams) -> Result { + validate_endpoint(¶ms.connect_host, params.connect_port) + .map_err(|message| RemoteDesktopBridgeError::InvalidConfig { message })?; + validate_size(u32::from(params.width), u32::from(params.height)) + .map_err(|message| RemoteDesktopBridgeError::InvalidConfig { message })?; if params.server_name.trim().is_empty() { - return Err("RDP server name is empty".to_owned()); + return Err(RemoteDesktopBridgeError::InvalidConfig { + message: "RDP server name is empty".to_owned(), + }); } if params.server_port == 0 { - return Err("RDP server port must be non-zero".to_owned()); + return Err(RemoteDesktopBridgeError::InvalidConfig { + message: "RDP server port must be non-zero".to_owned(), + }); } if params.username.is_empty() { - return Err("RDP username is empty".to_owned()); + return Err(RemoteDesktopBridgeError::InvalidConfig { + message: "RDP username is empty".to_owned(), + }); } Self::spawn(move |commands, events| run_rdp(params, commands, events)) } #[flutter_rust_bridge::frb(sync)] - pub fn start_vnc(params: VncSessionParams) -> Result { - validate_endpoint(¶ms.connect_host, params.connect_port)?; + pub fn start_vnc(params: VncSessionParams) -> Result { + validate_endpoint(¶ms.connect_host, params.connect_port) + .map_err(|message| RemoteDesktopBridgeError::InvalidConfig { message })?; if let Some(password) = ¶ms.password { if sbm_parser::desktop::validate_vnc_password(password).is_err() { - return Err("VNC passwords must be ASCII".to_owned()); + return Err(RemoteDesktopBridgeError::InvalidConfig { + message: "VNC passwords must be ASCII".to_owned(), + }); } } Self::spawn(move |commands, events| run_vnc(params, commands, events)) } - fn spawn(run: F) -> Result + fn spawn(run: F) -> Result where F: FnOnce(Arc, EventSender) -> Fut + Send + 'static, Fut: std::future::Future + 'static, @@ -554,7 +601,9 @@ impl RemoteDesktopSessionHandle { worker_commands.close(); worker_events.close(); }) - .map_err(|error| format!("failed to start remote desktop worker: {error}"))?; + .map_err(|error| RemoteDesktopBridgeError::WorkerSpawnFailed { + message: format!("failed to start remote desktop worker: {error}"), + })?; Ok(Self { commands: command_tx, receiver: tokio::sync::Mutex::new(EventReceiver { @@ -636,10 +685,10 @@ impl RemoteDesktopSessionHandle { } #[flutter_rust_bridge::frb(sync)] - pub fn send_clipboard_text(&self, text: String) -> Result<(), String> { + pub fn send_clipboard_text(&self, text: String) -> Result<(), RemoteDesktopBridgeError> { self.commands .send(SessionCommand::Clipboard(text)) - .map_err(|_| "remote desktop session is closed".to_owned()) + .map_err(RemoteDesktopBridgeError::from) } #[flutter_rust_bridge::frb(sync)] @@ -650,8 +699,9 @@ impl RemoteDesktopSessionHandle { scale_factor: u32, physical_width_mm: Option, physical_height_mm: Option, - ) -> Result<(), String> { - validate_size(u32::from(width), u32::from(height))?; + ) -> Result<(), RemoteDesktopBridgeError> { + validate_size(u32::from(width), u32::from(height)) + .map_err(|message| RemoteDesktopBridgeError::InvalidConfig { message })?; self.commands .send(SessionCommand::Resize { width, @@ -660,7 +710,7 @@ impl RemoteDesktopSessionHandle { physical_width_mm, physical_height_mm, }) - .map_err(|_| "remote desktop session is closed".to_owned()) + .map_err(RemoteDesktopBridgeError::from) } #[flutter_rust_bridge::frb(sync)] @@ -2291,7 +2341,93 @@ mod tests { password: Some("密码".to_owned()), shared: true, }); - assert!(result.is_err()); + assert!(matches!( + result, + Err(RemoteDesktopBridgeError::InvalidConfig { .. }) + )); + } + + #[test] + fn closed_handle_reports_typed_session_closed_error() { + let commands = CommandQueue::new(); + let events = EventQueue::new(); + let (_frame_tx, frame_rx) = watch::channel(None); + commands.close(); + let handle = RemoteDesktopSessionHandle { + commands, + receiver: tokio::sync::Mutex::new(EventReceiver { + events, + frames: frame_rx, + }), + }; + assert_eq!( + handle.send_clipboard_text("hello".to_owned()), + Err(RemoteDesktopBridgeError::SessionClosed) + ); + assert_eq!( + handle.resize(800, 600, 100, None, None), + Err(RemoteDesktopBridgeError::SessionClosed) + ); + assert!(matches!( + handle.resize(0, 600, 100, None, None), + Err(RemoteDesktopBridgeError::InvalidConfig { .. }) + )); + } + + #[test] + fn saturated_and_poisoned_command_queues_do_not_report_session_closed() { + let commands = CommandQueue::new(); + let events = EventQueue::new(); + let (_frame_tx, frame_rx) = watch::channel(None); + for i in 0..COMMAND_QUEUE_LIMIT { + assert_eq!( + commands.send(SessionCommand::Key { + code: i as u32, + down: true, + extended: false, + }), + Ok(()) + ); + } + let handle = RemoteDesktopSessionHandle { + commands: commands.clone(), + receiver: tokio::sync::Mutex::new(EventReceiver { + events, + frames: frame_rx, + }), + }; + assert_eq!( + handle.send_clipboard_text("overflow".to_owned()), + Err(RemoteDesktopBridgeError::QueueFull) + ); + assert_eq!( + handle.resize(800, 600, 100, None, None), + Err(RemoteDesktopBridgeError::QueueFull) + ); + + let poisoned = CommandQueue::new(); + let poisoned_clone = poisoned.clone(); + let _ = std::thread::spawn(move || { + let _guard = poisoned_clone.queue.lock().unwrap(); + panic!("intentional poison"); + }) + .join(); + let (_frame_tx2, frame_rx2) = watch::channel(None); + let poisoned_handle = RemoteDesktopSessionHandle { + commands: poisoned, + receiver: tokio::sync::Mutex::new(EventReceiver { + events: EventQueue::new(), + frames: frame_rx2, + }), + }; + assert!(matches!( + poisoned_handle.send_clipboard_text("x".to_owned()), + Err(RemoteDesktopBridgeError::Internal { .. }) + )); + assert!(matches!( + poisoned_handle.resize(800, 600, 100, None, None), + Err(RemoteDesktopBridgeError::Internal { .. }) + )); } #[test] diff --git a/crates/sbm_ffi/src/frb_generated.rs b/crates/sbm_ffi/src/frb_generated.rs index ccbc254450..2959f3e236 100644 --- a/crates/sbm_ffi/src/frb_generated.rs +++ b/crates/sbm_ffi/src/frb_generated.rs @@ -27,13 +27,13 @@ // Section: imports +use crate::api::control_master::*; use crate::api::ssh_crypto::*; +use crate::api::virt::*; use crate::api::agent_pipe::*; use crate::api::pve::*; -use crate::api::virt::*; -use crate::api::control_master::*; -use crate::api::remote_desktop::*; use crate::api::mosh::*; +use crate::api::remote_desktop::*; use crate::api::bmc::*;use flutter_rust_bridge::{Handler, IntoIntoDart}; use flutter_rust_bridge::for_generated::{Lockable, transform_result_dco, Lifetimeable}; use flutter_rust_bridge::for_generated::byteorder::{NativeEndian, WriteBytesExt, ReadBytesExt}; @@ -492,7 +492,7 @@ let api_cols = ::sse_decode(&mut deserializer); let api_rows = ::sse_decode(&mut deserializer); let api_prediction_mode = ::sse_decode(&mut deserializer); let api_handshake_timeout_ms = ::sse_decode(&mut deserializer);deserializer.end(); move |context| async move { - transform_result_sse::<_, String>((move || async move { + transform_result_sse::<_, crate::api::mosh::MoshBridgeError>((move || async move { let output_ok = crate::api::mosh::MoshBridgeSession::connect(api_host, api_port, api_key, api_cols, api_rows, api_prediction_mode, api_handshake_timeout_ms).await?; std::result::Result::Ok(output_ok) })().await) } }) @@ -519,7 +519,7 @@ let decode_indices_ = flutter_rust_bridge::for_generated::lockable_compute_decod let message = unsafe { flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(ptr_, rust_vec_len_, data_len_) }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); let api_that = >>::sse_decode(&mut deserializer);deserializer.end(); - transform_result_sse::<_, String>((move || { + transform_result_sse::<_, crate::api::mosh::MoshBridgeError>((move || { let mut api_that_guard = None; let decode_indices_ = flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new(&api_that, 0, false)]); for i in decode_indices_ { @@ -538,7 +538,7 @@ let decode_indices_ = flutter_rust_bridge::for_generated::lockable_compute_decod let api_that = >>::sse_decode(&mut deserializer); let api_cols = ::sse_decode(&mut deserializer); let api_rows = ::sse_decode(&mut deserializer);deserializer.end(); - transform_result_sse::<_, String>((move || { + transform_result_sse::<_, crate::api::mosh::MoshBridgeError>((move || { let mut api_that_guard = None; let decode_indices_ = flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new(&api_that, 0, false)]); for i in decode_indices_ { @@ -556,7 +556,7 @@ let decode_indices_ = flutter_rust_bridge::for_generated::lockable_compute_decod let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); let api_that = >>::sse_decode(&mut deserializer); let api_mode = ::sse_decode(&mut deserializer);deserializer.end(); - transform_result_sse::<_, String>((move || { + transform_result_sse::<_, crate::api::mosh::MoshBridgeError>((move || { let mut api_that_guard = None; let decode_indices_ = flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new(&api_that, 0, false)]); for i in decode_indices_ { @@ -578,7 +578,7 @@ let api_col = ::sse_decode(&mut deserializer); let api_cols = ::sse_decode(&mut deserializer); let api_rows = ::sse_decode(&mut deserializer); let api_in_alt_screen = ::sse_decode(&mut deserializer);deserializer.end(); - transform_result_sse::<_, String>((move || { + transform_result_sse::<_, crate::api::mosh::MoshBridgeError>((move || { let mut api_that_guard = None; let decode_indices_ = flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new(&api_that, 0, false)]); for i in decode_indices_ { @@ -596,7 +596,7 @@ let decode_indices_ = flutter_rust_bridge::for_generated::lockable_compute_decod let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); let api_that = >>::sse_decode(&mut deserializer); let api_data = >::sse_decode(&mut deserializer);deserializer.end(); - transform_result_sse::<_, String>((move || { + transform_result_sse::<_, crate::api::mosh::MoshBridgeError>((move || { let mut api_that_guard = None; let decode_indices_ = flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new(&api_that, 0, false)]); for i in decode_indices_ { @@ -1790,7 +1790,7 @@ let api_height = ::sse_decode(&mut deserializer); let api_scale_factor = ::sse_decode(&mut deserializer); let api_physical_width_mm = >::sse_decode(&mut deserializer); let api_physical_height_mm = >::sse_decode(&mut deserializer);deserializer.end(); - transform_result_sse::<_, String>((move || { + transform_result_sse::<_, crate::api::remote_desktop::RemoteDesktopBridgeError>((move || { let mut api_that_guard = None; let decode_indices_ = flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new(&api_that, 0, false)]); for i in decode_indices_ { @@ -1808,7 +1808,7 @@ let decode_indices_ = flutter_rust_bridge::for_generated::lockable_compute_decod let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); let api_that = >>::sse_decode(&mut deserializer); let api_text = ::sse_decode(&mut deserializer);deserializer.end(); - transform_result_sse::<_, String>((move || { + transform_result_sse::<_, crate::api::remote_desktop::RemoteDesktopBridgeError>((move || { let mut api_that_guard = None; let decode_indices_ = flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new(&api_that, 0, false)]); for i in decode_indices_ { @@ -1922,7 +1922,7 @@ let decode_indices_ = flutter_rust_bridge::for_generated::lockable_compute_decod let message = unsafe { flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(ptr_, rust_vec_len_, data_len_) }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); let api_params = ::sse_decode(&mut deserializer);deserializer.end(); - transform_result_sse::<_, String>((move || { + transform_result_sse::<_, crate::api::remote_desktop::RemoteDesktopBridgeError>((move || { let output_ok = crate::api::remote_desktop::RemoteDesktopSessionHandle::start_rdp(api_params)?; std::result::Result::Ok(output_ok) })()) }) }fn wire__crate__api__remote_desktop__RemoteDesktopSessionHandle_start_vnc_impl(ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,rust_vec_len_: i32,data_len_: i32) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { @@ -1930,7 +1930,7 @@ let decode_indices_ = flutter_rust_bridge::for_generated::lockable_compute_decod let message = unsafe { flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(ptr_, rust_vec_len_, data_len_) }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); let api_params = ::sse_decode(&mut deserializer);deserializer.end(); - transform_result_sse::<_, String>((move || { + transform_result_sse::<_, crate::api::remote_desktop::RemoteDesktopBridgeError>((move || { let output_ok = crate::api::remote_desktop::RemoteDesktopSessionHandle::start_vnc(api_params)?; std::result::Result::Ok(output_ok) })()) }) }fn wire__crate__api__ssh_crypto__SshAead_new_impl(ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,rust_vec_len_: i32,data_len_: i32) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { @@ -3519,7 +3519,7 @@ let api_udp_port = >::sse_decode(&mut deserializer); let api_bind_ssh_ip = ::sse_decode(&mut deserializer); let api_colors = ::sse_decode(&mut deserializer); let api_locale = >::sse_decode(&mut deserializer);deserializer.end(); - transform_result_sse::<_, String>((move || { + transform_result_sse::<_, crate::api::mosh::MoshBridgeError>((move || { let output_ok = crate::api::mosh::mosh_build_server_command(api_server_binary, api_udp_port, api_bind_ssh_ip, api_colors, api_locale)?; std::result::Result::Ok(output_ok) })()) }) }fn wire__crate__api__mosh__mosh_parse_connect_impl(ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,rust_vec_len_: i32,data_len_: i32) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { @@ -3527,7 +3527,7 @@ let api_locale = >::sse_decode(&mut deserializer);deserializer.en let message = unsafe { flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(ptr_, rust_vec_len_, data_len_) }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); let api_output = ::sse_decode(&mut deserializer);deserializer.end(); - transform_result_sse::<_, String>((move || { + transform_result_sse::<_, crate::api::mosh::MoshBridgeError>((move || { let output_ok = crate::api::mosh::mosh_parse_connect(api_output)?; std::result::Result::Ok(output_ok) })()) }) }fn wire__crate__api__script__parse_custom_cmds_listing_impl(ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,rust_vec_len_: i32,data_len_: i32) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { @@ -9886,6 +9886,21 @@ let mut var_readOn = ::sse_decode(deserializer); return crate::api::script::MonitorReleasePage{newest: var_newest, read_on: var_readOn};} } + impl SseDecode for crate::api::mosh::MoshBridgeError { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {let mut tag_ = ::sse_decode(deserializer); + match tag_ {0 => { return crate::api::mosh::MoshBridgeError::SessionClosed; } +1 => { let mut var_message = ::sse_decode(deserializer); +return crate::api::mosh::MoshBridgeError::SendBufferFull{message: var_message}; } +2 => { let mut var_message = ::sse_decode(deserializer); +return crate::api::mosh::MoshBridgeError::HandshakeTimeout{message: var_message}; } +3 => { let mut var_message = ::sse_decode(deserializer); +return crate::api::mosh::MoshBridgeError::InvalidConfig{message: var_message}; } +4 => { let mut var_message = ::sse_decode(deserializer); +return crate::api::mosh::MoshBridgeError::Other{message: var_message}; } + _ => { unimplemented!(""); }}} + } + impl SseDecode for crate::api::mosh::MoshBridgeEvent { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {let mut tag_ = ::sse_decode(deserializer); @@ -11372,6 +11387,20 @@ let mut var_why = >::sse_decode(deserializer); return crate::api::storage::Refusal{status: var_status, error: var_error, device: var_device, why: var_why};} } + impl SseDecode for crate::api::remote_desktop::RemoteDesktopBridgeError { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {let mut tag_ = ::sse_decode(deserializer); + match tag_ {0 => { return crate::api::remote_desktop::RemoteDesktopBridgeError::SessionClosed; } +1 => { return crate::api::remote_desktop::RemoteDesktopBridgeError::QueueFull; } +2 => { let mut var_message = ::sse_decode(deserializer); +return crate::api::remote_desktop::RemoteDesktopBridgeError::InvalidConfig{message: var_message}; } +3 => { let mut var_message = ::sse_decode(deserializer); +return crate::api::remote_desktop::RemoteDesktopBridgeError::WorkerSpawnFailed{message: var_message}; } +4 => { let mut var_message = ::sse_decode(deserializer); +return crate::api::remote_desktop::RemoteDesktopBridgeError::Internal{message: var_message}; } + _ => { unimplemented!(""); }}} + } + impl SseDecode for crate::api::remote_desktop::RemoteDesktopConnectionState { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {let mut inner = ::sse_decode(deserializer); @@ -16778,6 +16807,27 @@ impl flutter_rust_bridge::IntoIntoDart f self } } +// Codec=Dco (DartCObject based), see doc to use other codecs + impl flutter_rust_bridge::IntoDart for crate::api::mosh::MoshBridgeError { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + match self {crate::api::mosh::MoshBridgeError::SessionClosed => { [0.into_dart()].into_dart() } +crate::api::mosh::MoshBridgeError::SendBufferFull{message} => { [1.into_dart(), +message.into_into_dart().into_dart()].into_dart() } +crate::api::mosh::MoshBridgeError::HandshakeTimeout{message} => { [2.into_dart(), +message.into_into_dart().into_dart()].into_dart() } +crate::api::mosh::MoshBridgeError::InvalidConfig{message} => { [3.into_dart(), +message.into_into_dart().into_dart()].into_dart() } +crate::api::mosh::MoshBridgeError::Other{message} => { [4.into_dart(), +message.into_into_dart().into_dart()].into_dart() } + _ => { unimplemented!(""); }} + } + } + impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::mosh::MoshBridgeError {} +impl flutter_rust_bridge::IntoIntoDart for crate::api::mosh::MoshBridgeError { + fn into_into_dart(self) -> crate::api::mosh::MoshBridgeError { + self + } + } // Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::api::mosh::MoshBridgeEvent { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { @@ -17837,6 +17887,26 @@ impl flutter_rust_bridge::IntoIntoDart> self.into() } } +// Codec=Dco (DartCObject based), see doc to use other codecs + impl flutter_rust_bridge::IntoDart for crate::api::remote_desktop::RemoteDesktopBridgeError { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + match self {crate::api::remote_desktop::RemoteDesktopBridgeError::SessionClosed => { [0.into_dart()].into_dart() } +crate::api::remote_desktop::RemoteDesktopBridgeError::QueueFull => { [1.into_dart()].into_dart() } +crate::api::remote_desktop::RemoteDesktopBridgeError::InvalidConfig{message} => { [2.into_dart(), +message.into_into_dart().into_dart()].into_dart() } +crate::api::remote_desktop::RemoteDesktopBridgeError::WorkerSpawnFailed{message} => { [3.into_dart(), +message.into_into_dart().into_dart()].into_dart() } +crate::api::remote_desktop::RemoteDesktopBridgeError::Internal{message} => { [4.into_dart(), +message.into_into_dart().into_dart()].into_dart() } + _ => { unimplemented!(""); }} + } + } + impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::remote_desktop::RemoteDesktopBridgeError {} +impl flutter_rust_bridge::IntoIntoDart for crate::api::remote_desktop::RemoteDesktopBridgeError { + fn into_into_dart(self) -> crate::api::remote_desktop::RemoteDesktopBridgeError { + self + } + } // Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::api::remote_desktop::RemoteDesktopConnectionState { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { @@ -23360,6 +23430,20 @@ crate::api::bmc::LogScope::Manager => { 1 } ::sse_encode(self.read_on, serializer);} } + impl SseEncode for crate::api::mosh::MoshBridgeError { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {match self {crate::api::mosh::MoshBridgeError::SessionClosed => { ::sse_encode(0, serializer); } +crate::api::mosh::MoshBridgeError::SendBufferFull{message} => { ::sse_encode(1, serializer); ::sse_encode(message, serializer); + } +crate::api::mosh::MoshBridgeError::HandshakeTimeout{message} => { ::sse_encode(2, serializer); ::sse_encode(message, serializer); + } +crate::api::mosh::MoshBridgeError::InvalidConfig{message} => { ::sse_encode(3, serializer); ::sse_encode(message, serializer); + } +crate::api::mosh::MoshBridgeError::Other{message} => { ::sse_encode(4, serializer); ::sse_encode(message, serializer); + } + _ => { unimplemented!(""); }}} + } + impl SseEncode for crate::api::mosh::MoshBridgeEvent { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {match self {crate::api::mosh::MoshBridgeEvent::Output{data} => { ::sse_encode(0, serializer); >::sse_encode(data, serializer); @@ -24665,6 +24749,19 @@ crate::api::bmc::RedfishFailure::Closed => { 12 } >::sse_encode(self.why, serializer);} } + impl SseEncode for crate::api::remote_desktop::RemoteDesktopBridgeError { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {match self {crate::api::remote_desktop::RemoteDesktopBridgeError::SessionClosed => { ::sse_encode(0, serializer); } +crate::api::remote_desktop::RemoteDesktopBridgeError::QueueFull => { ::sse_encode(1, serializer); } +crate::api::remote_desktop::RemoteDesktopBridgeError::InvalidConfig{message} => { ::sse_encode(2, serializer); ::sse_encode(message, serializer); + } +crate::api::remote_desktop::RemoteDesktopBridgeError::WorkerSpawnFailed{message} => { ::sse_encode(3, serializer); ::sse_encode(message, serializer); + } +crate::api::remote_desktop::RemoteDesktopBridgeError::Internal{message} => { ::sse_encode(4, serializer); ::sse_encode(message, serializer); + } + _ => { unimplemented!(""); }}} + } + impl SseEncode for crate::api::remote_desktop::RemoteDesktopConnectionState { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {::sse_encode(match self {crate::api::remote_desktop::RemoteDesktopConnectionState::Connecting => { 0 } @@ -26473,13 +26570,13 @@ crate::api::virt_libvirt::VirtResourceOp::NetDelete{name} => { ::sse_encode // Section: imports +use crate::api::control_master::*; use crate::api::ssh_crypto::*; +use crate::api::virt::*; use crate::api::agent_pipe::*; use crate::api::pve::*; -use crate::api::virt::*; -use crate::api::control_master::*; -use crate::api::remote_desktop::*; use crate::api::mosh::*; +use crate::api::remote_desktop::*; use crate::api::bmc::*;use flutter_rust_bridge::{Handler, IntoIntoDart}; use flutter_rust_bridge::for_generated::{Lockable, transform_result_dco, Lifetimeable}; use flutter_rust_bridge::for_generated::byteorder::{NativeEndian, WriteBytesExt, ReadBytesExt};use super::*; @@ -26647,13 +26744,13 @@ flutter_rust_bridge::frb_generated_boilerplate_io!(); // Section: imports +use crate::api::control_master::*; use crate::api::ssh_crypto::*; +use crate::api::virt::*; use crate::api::agent_pipe::*; use crate::api::pve::*; -use crate::api::virt::*; -use crate::api::control_master::*; -use crate::api::remote_desktop::*; use crate::api::mosh::*; +use crate::api::remote_desktop::*; use crate::api::bmc::*;use flutter_rust_bridge::{Handler, IntoIntoDart}; use flutter_rust_bridge::for_generated::{Lockable, transform_result_dco, Lifetimeable}; use flutter_rust_bridge::for_generated::byteorder::{NativeEndian, WriteBytesExt, ReadBytesExt};use super::*; diff --git a/lib/core/ssh/client.dart b/lib/core/ssh/client.dart index f840cab964..6d77519b8e 100644 --- a/lib/core/ssh/client.dart +++ b/lib/core/ssh/client.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:io'; import 'package:dartssh2/dartssh2.dart'; import 'package:fl_lib/fl_lib.dart'; @@ -22,6 +23,7 @@ import 'package:server_box/data/model/server/server_private_info.dart'; import 'package:server_box/data/model/server/ssh_credential.dart'; import 'package:server_box/data/model/server/ssh_proxy.dart'; import 'package:server_box/data/store/stores.dart'; +import 'package:server_box/src/rust/api/control_master.dart' show MuxError; enum GenSSHClientStatus { socket, key, pwd } @@ -246,7 +248,11 @@ Future genClient( if (proxy == null) { final message = 'SSH proxy not found for ${spi.name}: $proxyId'; Loggers.app.warning(message); - throw SSHErr(type: SSHErrType.connect, message: message); + throw SSHErr( + type: SSHErrType.connect, + message: message, + retryable: true, + ); } try { return await ProxySocket.connect( @@ -631,86 +637,49 @@ List _resolveJumpCandidates({ return candidates; } -final _authFailurePattern = RegExp( - r'\b(auth|authc|authn|authz|authenticat\w*|authoriz\w*|unauthenticat\w*|unauthoriz\w*)\b' - r'|permission denied|access denied|sshauth\w*', -); - -final _httpProxyStatusPattern = RegExp( - r'http proxy connect failed:\s*http/1\.[01]\s+(\d{3})\b', -); - /// Whether [error] is a proxy authentication/authorization denial (such as /// SOCKS5 auth or ruleset denial, or HTTP 401/403/407) that must not trigger /// `alterUrl` retries or jump-candidate failover. bool isProxyDenialError(Object error) { - if (error is SSHErr && error.type == SSHErrType.auth) { - return true; - } - final errStr = error.toString().toLowerCase(); - if (errStr.contains('connection not allowed by ruleset')) { - return true; - } - final httpMatch = _httpProxyStatusPattern.firstMatch(errStr); - if (httpMatch != null) { - final code = int.parse(httpMatch.group(1)!); - if (code == 401 || code == 403 || code == 407) return true; - } - return false; + return error is SSHErr && error.type == SSHErrType.auth; } bool isJumpFailoverError(Object error) { - if (isProxyDenialError(error)) { - return false; - } - if (error is SSHAuthFailError) { - return false; - } if (error is SSHAuthAbortError) { final reason = error.reason; if (reason == null) return false; return isJumpFailoverError(reason); } - if (error is SSHAuthError) { + if (isProxyDenialError(error)) { + return false; + } + if (error is SSHAuthFailError || + error is SSHAuthError || + error is SSHHostkeyError) { return false; } - final errStr = error.toString().toLowerCase(); - final httpMatch = _httpProxyStatusPattern.firstMatch(errStr); - if (httpMatch != null) { - final code = int.parse(httpMatch.group(1)!); - // 5xx is a proxy-side fault regardless of reason-phrase wording. - if (code >= 500 && code <= 599) return true; + if (error is SSHErr) { + if (error.cause case final cause?) { + return (error.retryable || error.type == SSHErrType.connect) && + isJumpFailoverError(cause); + } + return error.retryable; } - // A missing proxy on a jump candidate is a route fault regardless of whether - // the jump server's name contains words like "auth". - if (errStr.contains('ssh proxy not found')) { + if (error is SSHSocketError) { + final inner = error.error; + if (inner is SSHErr || inner is SSHAuthError || inner is SSHHostkeyError) { + return isJumpFailoverError(inner); + } return true; } - // Exclude genuine authentication failures (including "too many - // authentication failures") without matching unrelated words like "authority". - if (_authFailurePattern.hasMatch(errStr)) { - return false; - } - return errStr.contains('timed out') || - errStr.contains('timeout') || - errStr.contains('connection refused') || - errStr.contains('connection reset') || - errStr.contains('connection closed') || - errStr.contains('no route to host') || - errStr.contains('host unreachable') || - errStr.contains('network unreachable') || - errStr.contains('network is unreachable') || - errStr.contains('socketexception') || - errStr.contains('failed host lookup') || - errStr.contains('forwardlocal') || - errStr.contains('socks5 connect failed') || - errStr.contains('http proxy connect failed') || - errStr.contains('proxycommand exited') || - errStr.contains('proxycommand timed out') || - errStr.contains('channel open failed') || - errStr.contains('maxsessions') || - (errStr.contains('too many') && errStr.contains('session')) || - (errStr.contains('session') && errStr.contains('failed')); + return error is TimeoutException || + error is SocketException || + error is SSHHandshakeError || + error is SSHChannelOpenError || + error is SSHKeepAliveError || + error is SSHStateError || + error is MuxError || + error is ProcessException; } Future ensureKnownHostKey( diff --git a/lib/core/ssh/control_master.dart b/lib/core/ssh/control_master.dart index c13ba3fd2b..f3371cca86 100644 --- a/lib/core/ssh/control_master.dart +++ b/lib/core/ssh/control_master.dart @@ -91,6 +91,7 @@ Future openThroughMaster( type: SSHErrType.connect, message: 'OpenSSH master ${jump.name}: channel open failed: ${e.message}', cause: e, + retryable: true, ); } on SSHErr { rethrow; diff --git a/lib/core/ssh/iul_proxy_socket.dart b/lib/core/ssh/iul_proxy_socket.dart index ac1fb863b1..a51518fed3 100644 --- a/lib/core/ssh/iul_proxy_socket.dart +++ b/lib/core/ssh/iul_proxy_socket.dart @@ -181,12 +181,14 @@ final class IulProxySocket implements SSHSocket { try { final ready = socket._ready.future; await (timeout == null ? ready : ready.timeout(timeout)); - } on TimeoutException { + } on TimeoutException catch (e) { await socket.close(); throw SSHErr( type: SSHErrType.connect, message: 'ProxyCommand did not start within ${timeout!.inSeconds}s.', + cause: e, + retryable: true, ); } catch (_) { await socket.close(); @@ -353,23 +355,27 @@ final class IulProxySocket implements SSHSocket { final said = [_text(_preamble.toBytes()), stderr] .where((e) => e.isNotEmpty) .join('\n'); + final isAuthFailure = exitCode != 97 && isAuthFailureMessage(said); _ready.completeError( SSHErr( - type: SSHErrType.connect, + type: isAuthFailure ? SSHErrType.auth : SSHErrType.connect, message: exitCode == 97 ? 'ProxyCommand: the terminal could not be made raw.' : 'ProxyCommand exited before connecting' '${exitCode == null ? '' : ' ($exitCode)'}' '${said.isEmpty ? '.' : ': $said'}', + retryable: exitCode != 97 && !isAuthFailure, ), ); } else if (!_receivedAny && stderr.isNotEmpty) { // Said on the stream, where SSH reports it as the connection's failure, // rather than only in a log nobody reading the error will open. + final isAuthFailure = isAuthFailureMessage(stderr); _incoming.addError( SSHErr( - type: SSHErrType.connect, + type: isAuthFailure ? SSHErrType.auth : SSHErrType.connect, message: 'ProxyCommand exited: $stderr', + retryable: !isAuthFailure, ), ); } else if (stderr.isNotEmpty) { diff --git a/lib/core/ssh/mosh.dart b/lib/core/ssh/mosh.dart index 00e21d9bfb..ca2d834cfc 100644 --- a/lib/core/ssh/mosh.dart +++ b/lib/core/ssh/mosh.dart @@ -182,6 +182,94 @@ String redactMoshSecrets(String raw) => raw.replaceAll( 'MOSH CONNECT [REDACTED]', ); +String _moshBridgeErrorMessage(mosh_ffi.MoshBridgeError error) => + switch (error) { + mosh_ffi.MoshBridgeError_SessionClosed() => 'Mosh session closed.', + mosh_ffi.MoshBridgeError_SendBufferFull(:final message) || + mosh_ffi.MoshBridgeError_HandshakeTimeout(:final message) || + mosh_ffi.MoshBridgeError_InvalidConfig(:final message) || + mosh_ffi.MoshBridgeError_Other(:final message) => redactMoshSecrets( + message, + ), + }; + +/// Maps a typed Rust [mosh_ffi.MoshBridgeError] from `moshBuildServerCommand` +/// to a [MoshException]. +@visibleForTesting +MoshException classifyMoshBuildCommandError(mosh_ffi.MoshBridgeError error) => + switch (error) { + mosh_ffi.MoshBridgeError_InvalidConfig(:final message) => MoshException( + MoshErrType.invalidConfig, + redactMoshSecrets(message), + ), + mosh_ffi.MoshBridgeError_SessionClosed() || + mosh_ffi.MoshBridgeError_SendBufferFull() || + mosh_ffi.MoshBridgeError_HandshakeTimeout() || + mosh_ffi.MoshBridgeError_Other() => MoshException( + MoshErrType.connectFailed, + _moshBridgeErrorMessage(error), + ), + }; + +/// Maps a typed Rust [mosh_ffi.MoshBridgeError] from `MoshBridgeSession.connect` +/// to a user-facing [MoshException] without inspecting diagnostic strings. +@visibleForTesting +MoshException classifyMoshConnectError( + mosh_ffi.MoshBridgeError error, { + required String targetHost, + required int port, + String? moshPort, +}) { + final portHint = (moshPort == null || moshPort.trim().isEmpty) + ? '60000-61000' + : moshPort.trim(); + return switch (error) { + mosh_ffi.MoshBridgeError_HandshakeTimeout() => MoshException( + MoshErrType.udpTimeout, + 'UDP handshake to $targetHost:$port timed out. Check that UDP port $portHint is open on the server.', + ), + mosh_ffi.MoshBridgeError_InvalidConfig(:final message) => MoshException( + MoshErrType.invalidConfig, + redactMoshSecrets(message), + ), + mosh_ffi.MoshBridgeError_SendBufferFull(:final message) => MoshException( + MoshErrType.sendBufferFull, + redactMoshSecrets(message), + ), + mosh_ffi.MoshBridgeError_SessionClosed() => const MoshException( + MoshErrType.connectFailed, + 'Mosh session closed during handshake.', + ), + mosh_ffi.MoshBridgeError_Other(:final message) => MoshException( + MoshErrType.connectFailed, + redactMoshSecrets(message), + ), + }; +} + +/// Maps a typed Rust [mosh_ffi.MoshBridgeError] from `MoshBridgeSession.write` +/// to a [MoshException], or `null` for [mosh_ffi.MoshBridgeError_SessionClosed] +/// (expected while keystrokes race with a closing session). +@visibleForTesting +MoshException? classifyMoshWriteError(mosh_ffi.MoshBridgeError error) => + switch (error) { + mosh_ffi.MoshBridgeError_SessionClosed() => null, + mosh_ffi.MoshBridgeError_SendBufferFull(:final message) => MoshException( + MoshErrType.sendBufferFull, + redactMoshSecrets(message), + ), + mosh_ffi.MoshBridgeError_HandshakeTimeout(:final message) => + MoshException(MoshErrType.udpTimeout, redactMoshSecrets(message)), + mosh_ffi.MoshBridgeError_InvalidConfig(:final message) => MoshException( + MoshErrType.invalidConfig, + redactMoshSecrets(message), + ), + mosh_ffi.MoshBridgeError_Other(:final message) => MoshException( + MoshErrType.connectFailed, + redactMoshSecrets(message), + ), + }; + /// Extracts a UTF-8 locale assignment (`KEY=VALUE`) from [environment] if set. @visibleForTesting String? selectMoshLocaleFromEnv(Map? environment) { @@ -280,8 +368,13 @@ class MoshShellBackend implements ShellBackend { colors: 256, locale: localeArg, ); + } on mosh_ffi.MoshBridgeError catch (e) { + throw classifyMoshBuildCommandError(e); } catch (e) { - throw MoshException(MoshErrType.invalidConfig, e.toString()); + throw MoshException( + MoshErrType.connectFailed, + redactMoshSecrets(e.toString()), + ); } final bootstrap = await _runBootstrap(command, environment: environment); @@ -325,16 +418,18 @@ class MoshShellBackend implements ShellBackend { predictionMode: toFfiPredictionMode(ssh.moshPrediction), handshakeTimeoutMs: handshakeTimeout.inMilliseconds, ); + } on mosh_ffi.MoshBridgeError catch (e) { + throw classifyMoshConnectError( + e, + targetHost: targetHost, + port: connectInfo.port, + moshPort: ssh.moshPort, + ); } catch (e) { - final msg = redactMoshSecrets(e.toString()); - final lower = msg.toLowerCase(); - if (lower.contains('timeout') || lower.contains('timed out')) { - throw MoshException( - MoshErrType.udpTimeout, - 'UDP handshake to $targetHost:${connectInfo.port} timed out. Check that UDP port ${ssh.moshPort ?? '60000-61000'} is open on the server.', - ); - } - throw MoshException(MoshErrType.connectFailed, msg); + throw MoshException( + MoshErrType.connectFailed, + redactMoshSecrets(e.toString()), + ); } final session = MoshShellSession(bridge); @@ -359,6 +454,11 @@ class MoshShellBackend implements ShellBackend { final fromStdout = mosh_ffi.moshParseConnect(output: stdout); if (fromStdout != null) return fromStdout; return mosh_ffi.moshParseConnect(output: stderr); + } on mosh_ffi.MoshBridgeError catch (e) { + throw MoshException( + MoshErrType.connectFailed, + _moshBridgeErrorMessage(e), + ); } catch (e) { throw MoshException( MoshErrType.connectFailed, @@ -550,15 +650,17 @@ class MoshShellSession implements ShellSession { if (_closed || data.isEmpty) return; try { _bridge.write(data: data); + } on mosh_ffi.MoshBridgeError catch (e) { + if (_closed) return; + final err = classifyMoshWriteError(e); + if (err == null) return; + onWriteError?.call(err); + throw err; } catch (e) { if (_closed) return; - final msg = redactMoshSecrets(e.toString()); - final lower = msg.toLowerCase(); final err = MoshException( - lower.contains('buffer') || lower.contains('limit') - ? MoshErrType.sendBufferFull - : MoshErrType.connectFailed, - msg, + MoshErrType.connectFailed, + redactMoshSecrets(e.toString()), ); onWriteError?.call(err); throw err; @@ -573,6 +675,8 @@ class MoshShellSession implements ShellSession { cols: width.clamp(1, 65535), rows: height.clamp(1, 65535), ); + } on mosh_ffi.MoshBridgeError_SessionClosed { + return; } catch (e) { Loggers.app.info('Mosh resize ignored: $e'); } @@ -596,6 +700,8 @@ class MoshShellSession implements ShellSession { rows: rows.clamp(1, 65535), inAltScreen: inAltScreen, ); + } on mosh_ffi.MoshBridgeError_SessionClosed { + return; } catch (e) { Loggers.app.info('Mosh syncCursor ignored: $e'); } @@ -606,6 +712,8 @@ class MoshShellSession implements ShellSession { if (_closed) return; try { _bridge.setPredictionMode(mode: toFfiPredictionMode(mode)); + } on mosh_ffi.MoshBridgeError_SessionClosed { + return; } catch (e) { Loggers.app.info('Mosh setPredictionMode ignored: $e'); } @@ -617,6 +725,8 @@ class MoshShellSession implements ShellSession { if (_closed) return; try { _bridge.rebind(); + } on mosh_ffi.MoshBridgeError_SessionClosed { + return; } catch (e) { Loggers.app.info('Mosh rebind ignored: $e'); } diff --git a/lib/core/ssh/proxy_command_socket.dart b/lib/core/ssh/proxy_command_socket.dart index 3b29a16a44..bfb31e8b80 100644 --- a/lib/core/ssh/proxy_command_socket.dart +++ b/lib/core/ssh/proxy_command_socket.dart @@ -124,7 +124,7 @@ class ProxyCommandSocket implements SSHSocket { process = timeout == null ? await processFuture : await processFuture.timeout(timeout); - } on TimeoutException { + } on TimeoutException catch (e) { // Timing out this Future does not cancel process creation. Kill a child // that appears later instead of leaving a detached proxy behind — and // only then free the guest it was running in. @@ -140,6 +140,8 @@ class ProxyCommandSocket implements SSHSocket { type: SSHErrType.connect, message: 'ProxyCommand process start timed out after ${timeout!.inSeconds}s.', + cause: e, + retryable: true, ); } catch (_) { guest?.release(); diff --git a/lib/core/ssh/proxy_socket.dart b/lib/core/ssh/proxy_socket.dart index 5faa2eaee1..ef3105a1e7 100644 --- a/lib/core/ssh/proxy_socket.dart +++ b/lib/core/ssh/proxy_socket.dart @@ -163,6 +163,7 @@ class ProxySocket implements SSHSocket { throw SSHErr( type: SSHErrType.connect, message: 'Invalid SOCKS5 version: ${choice[0]}', + retryable: true, ); } switch (choice[1]) { @@ -194,6 +195,7 @@ class ProxySocket implements SSHSocket { throw SSHErr( type: SSHErrType.connect, message: 'Unsupported SOCKS5 authentication method: ${choice[1]}', + retryable: true, ); } @@ -215,13 +217,18 @@ class ProxySocket implements SSHSocket { throw SSHErr( type: SSHErrType.connect, message: 'Invalid SOCKS5 reply version: ${header[0]}', + retryable: true, ); } final rep = header[1]; if (rep != 0x00) { + final isPolicyDenial = rep == 0x02; throw SSHErr( - type: SSHErrType.connect, + // RFC 1928 §6: 0x02 is an explicit proxy policy/ruleset denial and + // must not trigger alterUrl retries or jump-candidate failover. + type: isPolicyDenial ? SSHErrType.auth : SSHErrType.connect, message: 'SOCKS5 CONNECT failed: ${_socks5ReplyMessage(rep)}', + retryable: !isPolicyDenial, ); } switch (header[3]) { @@ -236,6 +243,7 @@ class ProxySocket implements SSHSocket { throw SSHErr( type: SSHErrType.connect, message: 'Unsupported SOCKS5 reply address type: ${header[3]}', + retryable: true, ); } } @@ -273,6 +281,7 @@ class ProxySocket implements SSHSocket { type: SSHErrType.connect, message: 'HTTP proxy response header exceeded $_maxHttpHeaderBytes bytes', + retryable: true, ); } final Uint8List rawHeader; @@ -285,6 +294,7 @@ class ProxySocket implements SSHSocket { type: SSHErrType.connect, message: 'HTTP proxy response header exceeded $_maxHttpHeaderBytes bytes', + retryable: true, ); } remainingHeaderBytes -= rawHeader.length; @@ -299,6 +309,7 @@ class ProxySocket implements SSHSocket { throw SSHErr( type: SSHErrType.connect, message: 'Invalid HTTP proxy response: $safeStatus', + retryable: true, ); } final statusCode = int.parse(match.group(1)!); @@ -311,10 +322,17 @@ class ProxySocket implements SSHSocket { message: 'HTTP proxy authentication required (407)', ); } + if (statusCode == 401 || statusCode == 403) { + throw SSHErr( + type: SSHErrType.auth, + message: 'HTTP proxy CONNECT failed: $safeStatus', + ); + } if (statusCode < 200 || statusCode >= 300) { throw SSHErr( type: SSHErrType.connect, message: 'HTTP proxy CONNECT failed: $safeStatus', + retryable: true, ); } return; diff --git a/lib/core/ssh_discovery/ssh_config.dart b/lib/core/ssh_discovery/ssh_config.dart index 609149d928..e62010fdea 100644 --- a/lib/core/ssh_discovery/ssh_config.dart +++ b/lib/core/ssh_discovery/ssh_config.dart @@ -46,7 +46,7 @@ final class SshConfigDiscovery implements SshDiscovery { try { servers = await SSHConfig.parseConfig(input); } on FileSystemException catch (e) { - if (e is! PathAccessException && !'$e'.contains('not permitted')) { + if (!isPermissionDeniedError(e)) { rethrow; } throw SshDiscoveryException( @@ -58,6 +58,20 @@ final class SshConfigDiscovery implements SshDiscovery { return (hosts: hostsOf(servers), scope: input ?? _path); } + /// Whether [e] represents an OS-level permission error (`PathAccessException`, + /// POSIX `EPERM`/`EACCES`, or Windows `ERROR_ACCESS_DENIED`). + @visibleForTesting + static bool isPermissionDeniedError( + FileSystemException e, { + bool? isWindows, + }) { + if (e is PathAccessException) return true; + final code = e.osError?.errorCode; + if (code == null) return false; + final windows = isWindows ?? Platform.isWindows; + return windows ? code == 5 : (code == 1 || code == 13); + } + /// One host per server, each carrying the servers its jumps name. @visibleForTesting static List hostsOf(List servers) { diff --git a/lib/data/model/app/error.dart b/lib/data/model/app/error.dart index ecad83af3e..911648d28f 100644 --- a/lib/data/model/app/error.dart +++ b/lib/data/model/app/error.dart @@ -29,6 +29,28 @@ class RemoteBackupPasswordMissing implements Exception { String toString() => l10n.remoteBackupPasswordRequired; } +final _authFailurePattern = RegExp( + r'permission denied' + r'|access denied' + r'|too many authentication failures' + r'|no more authentication methods' + r'|\b(?:proxy\s+)?authenticat(?:ion|ed)\s+(?:failed|failure|error|required|rejected|refused|denied)' + r'|\bauthoriz(?:ation|ed)\s+(?:failed|failure|error|required|rejected|refused|denied)' + r'|\bauth\s+(?:failed|failure|error|required|rejected|refused|denied)' + r'|\b(?:failed|unable)\s+to\s+(?:authenticate|authorize)\b' + r'|\b(?:unauthenticated|unauthorized|not authenticated|not authorized)\b' + r'|\b(?:invalid|bad)\s+credentials\b' + r'|\blogin\s+failed\b', +); + +/// Whether unstructured external CLI stderr (such as `ProxyCommand` output +/// without a structured status code) reports an authentication failure. +/// +/// Matches specific failure phrases rather than isolated words like `auth` so +/// hostnames such as `auth.bastion.example` remain transport failures. +bool isAuthFailureMessage(String text) => + _authFailurePattern.hasMatch(text.toLowerCase()); + enum SSHErrType { unknown, connect, @@ -44,12 +66,22 @@ enum SSHErrType { } class SSHErr extends Err { - const SSHErr({required super.type, super.message, this.cause}); + const SSHErr({ + required super.type, + super.message, + this.cause, + this.retryable = false, + }); /// What was thrown, where there was something: kept for the log and the /// crash report, which a message alone does not let anyone trace. final Object? cause; + /// Whether retrying the connection or failing over to another jump candidate + /// may succeed. Defaults to `false` so permanent configuration, validation, + /// and rate-limit errors are never retried accidentally. + final bool retryable; + @override String? get solution => switch (type) { SSHErrType.auth => l10n.authFailTip, diff --git a/lib/data/model/server/connection_stat.dart b/lib/data/model/server/connection_stat.dart index 776d959ff9..665761d038 100644 --- a/lib/data/model/server/connection_stat.dart +++ b/lib/data/model/server/connection_stat.dart @@ -2,8 +2,11 @@ import 'dart:async'; import 'dart:io'; import 'package:dartssh2/dartssh2.dart'; +import 'package:dio/dio.dart'; import 'package:fl_lib/fl_lib.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:server_box/core/ssh/mosh.dart'; +import 'package:server_box/data/model/app/error.dart'; part 'connection_stat.freezed.dart'; part 'connection_stat.g.dart'; @@ -53,19 +56,105 @@ enum ConnectionResult { @JsonValue('unknown_error') unknownError; - /// What a failed connection attempt was. A dial that ran out of time is a - /// `SocketException` saying so, so the timeout is asked first. + static bool _mentionsTimeout(String text) { + final lower = text.toLowerCase(); + return lower.contains('timed out') || lower.contains('timeout'); + } + + static bool _isSocketTimeout(SocketException e) { + // POSIX ETIMEDOUT (macOS/BSD 60, Linux 110) and Windows WSAETIMEDOUT (10060). + final code = e.osError?.errorCode; + if (code == 60 || code == 110 || code == 10060) return true; + if (_mentionsTimeout(e.message)) return true; + final osMsg = e.osError?.message; + return osMsg != null && _mentionsTimeout(osMsg); + } + + /// What a failed connection attempt was. Known exception types are + /// classified directly before any text fallback so hostnames or error + /// details containing words like "auth" cannot misclassify transport errors. static ConnectionResult fromError(Object e) { + switch (e) { + case TimeoutException() || SSHKeepAliveError(): + return timeout; + case SSHAuthAbortError(:final message, :final reason): + if (reason != null) return fromError(reason); + return _mentionsTimeout(message) ? timeout : authFailed; + case SSHAuthError() || SSHHostkeyError(): + return authFailed; + case SSHErr(:final type, :final cause): + return switch (type) { + SSHErrType.auth || + SSHErrType.interactiveAuth || + SSHErrType.noPrivateKey => authFailed, + SSHErrType.connect => switch (cause != null + ? fromError(cause) + : networkError) { + unknownError => networkError, + final classified => classified, + }, + SSHErrType.agent || + SSHErrType.segments || + SSHErrType.writeScript || + SSHErrType.getStatus || + SSHErrType.unknown => cause != null ? fromError(cause) : unknownError, + }; + case MonitorHttpErr(:final type): + return switch (type) { + MonitorHttpErrType.auth || + MonitorHttpErrType.loginFailed || + MonitorHttpErrType.forbidden || + MonitorHttpErrType.reauth || + MonitorHttpErrType.notGranted || + MonitorHttpErrType.relayForbidden || + MonitorHttpErrType.sudoRefused => authFailed, + MonitorHttpErrType.net || + MonitorHttpErrType.targetUnreachable => networkError, + _ => unknownError, + }; + case DioException(:final type, :final response, :final error): + return switch (type) { + DioExceptionType.connectionTimeout || + DioExceptionType.sendTimeout || + DioExceptionType.receiveTimeout => timeout, + DioExceptionType.connectionError => networkError, + DioExceptionType.badResponse => switch (response?.statusCode) { + 401 || 403 => authFailed, + 408 || 504 => timeout, + _ => unknownError, + }, + DioExceptionType.unknown when error != null => fromError(error), + _ => unknownError, + }; + case MoshException(:final type): + return switch (type) { + MoshErrType.udpTimeout => timeout, + MoshErrType.sendBufferFull || + MoshErrType.connectFailed => networkError, + MoshErrType.serverNotFound || + MoshErrType.invalidConfig => unknownError, + }; + case SocketException(): + return _isSocketTimeout(e) ? timeout : networkError; + case SSHHandshakeError(:final message): + return _mentionsTimeout(message) ? timeout : networkError; + case SSHSocketError(:final error): + return switch (fromError(error)) { + unknownError => networkError, + final classified => classified, + }; + default: + break; + } + final said = e.toString().toLowerCase(); - if (e is TimeoutException || said.contains('timed out') || said.contains('timeout')) return timeout; - if (e is SSHAuthError || - said.contains('auth') || + if (_mentionsTimeout(said)) return timeout; + if (said.contains('auth') || said.contains('permission denied') || said.contains('access denied')) { return authFailed; } - if (e is SocketException || - said.contains('connection refused') || + if (said.contains('connection refused') || said.contains('no route to host') || said.contains('network') || said.contains('socket')) { diff --git a/lib/data/model/server/shell_backend.dart b/lib/data/model/server/shell_backend.dart index ebf14ee9f6..bfae847b34 100644 --- a/lib/data/model/server/shell_backend.dart +++ b/lib/data/model/server/shell_backend.dart @@ -65,6 +65,7 @@ class SshShellSession implements ShellSession { SshShellSession(this.session); final SSHSession session; + bool _closed = false; @override Stream? get stdout => session.stdout; @@ -73,11 +74,20 @@ class SshShellSession implements ShellSession { Stream? get stderr => session.stderr; @override - void write(List data) => + void write(List data) { + if (_closed || data.isEmpty) return; + try { session.write(data is Uint8List ? data : Uint8List.fromList(data)); + } on SSHStateError { + // Transport closed before `done` was observed; drop trailing input. + } on StateError { + // Stdin controller already closed during channel teardown. + } + } @override void resizeTerminal(int width, int height) { + if (_closed) return; try { session.resizeTerminal(width, height); } on SSHStateError { @@ -90,5 +100,13 @@ class SshShellSession implements ShellSession { Future get done => session.done; @override - void close() => session.close(); + void close() { + if (_closed) return; + _closed = true; + try { + session.close(); + } on SSHStateError { + // Transport already closed; nothing left to signal. + } + } } diff --git a/lib/data/provider/remote_desktop.dart b/lib/data/provider/remote_desktop.dart index ab12b8c218..ca6b92de73 100644 --- a/lib/data/provider/remote_desktop.dart +++ b/lib/data/provider/remote_desktop.dart @@ -586,7 +586,22 @@ class RemoteDesktopSessions extends _$RemoteDesktopSessions { final data = await Clipboard.getData(Clipboard.kTextPlain); final text = data?.text; if (text == null || text.isEmpty) return; - entry.handle?.sendClipboardText(text: text); + if (_disposed || !state.acceptsInput(id)) return; + final current = _entries[id]; + if (!identical(current, entry)) return; + try { + entry.handle?.sendClipboardText(text: text); + } on ffi.RemoteDesktopBridgeError_SessionClosed { + return; + } on ffi.RemoteDesktopBridgeError_QueueFull { + Loggers.app.warning( + 'Remote desktop clipboard dropped: command queue full', + ); + } on ffi.RemoteDesktopBridgeError catch (e) { + Loggers.app.warning('Remote desktop clipboard failed: $e'); + } catch (e) { + Loggers.app.info('Remote desktop clipboard send ignored: $e'); + } } void resize( @@ -604,13 +619,23 @@ class RemoteDesktopSessions extends _$RemoteDesktopSessions { entry.width = width.clamp(1, 8192); entry.height = height.clamp(1, 8192); entry.scaleFactor = scaleFactor.clamp(100, 500); - entry.handle?.resize( - width: entry.width, - height: entry.height, - scaleFactor: entry.scaleFactor, - physicalWidthMm: physicalWidthMm, - physicalHeightMm: physicalHeightMm, - ); + try { + entry.handle?.resize( + width: entry.width, + height: entry.height, + scaleFactor: entry.scaleFactor, + physicalWidthMm: physicalWidthMm, + physicalHeightMm: physicalHeightMm, + ); + } on ffi.RemoteDesktopBridgeError_SessionClosed { + return; + } on ffi.RemoteDesktopBridgeError_QueueFull { + Loggers.app.warning('Remote desktop resize dropped: command queue full'); + } on ffi.RemoteDesktopBridgeError catch (e) { + Loggers.app.warning('Remote desktop resize rejected: $e'); + } catch (e) { + Loggers.app.info('Remote desktop resize ignored: $e'); + } } void releaseAllKeys(String id) { @@ -707,17 +732,85 @@ class RemoteDesktopSessions extends _$RemoteDesktopSessions { 'error': Redact.error(error), }, ); + final classified = classifyConnectError(error); await _connectionEnded( entry, generation, - ffi.RemoteDesktopEndReason.transportError, - error.toString(), - hint: error is Err ? error.solution : null, - retryable: error is! ServerTcpErr || error.retryable, + classified.reason, + classified.message, + hint: classified.hint, + retryable: classified.retryable, ); } } + /// Classifies a synchronous or tunnel error from [_connect] by concrete type + /// so permanent FFI validation failures are reported as configuration errors + /// without entering the reconnect backoff loop. + @visibleForTesting + static ({ + ffi.RemoteDesktopEndReason reason, + String message, + String? hint, + bool retryable, + }) + classifyConnectError(Object error) => switch (error) { + ffi.RemoteDesktopBridgeError_InvalidConfig(:final message) => ( + reason: ffi.RemoteDesktopEndReason.configurationError, + message: message, + hint: null, + retryable: false, + ), + ffi.RemoteDesktopBridgeError_WorkerSpawnFailed(:final message) => ( + reason: ffi.RemoteDesktopEndReason.transportError, + message: message, + hint: null, + retryable: true, + ), + ffi.RemoteDesktopBridgeError_SessionClosed() => ( + reason: ffi.RemoteDesktopEndReason.transportError, + message: 'Remote desktop session closed', + hint: null, + retryable: true, + ), + ffi.RemoteDesktopBridgeError_QueueFull() => ( + reason: ffi.RemoteDesktopEndReason.transportError, + message: 'Remote desktop command queue full', + hint: null, + retryable: true, + ), + ffi.RemoteDesktopBridgeError_Internal(:final message) => ( + reason: ffi.RemoteDesktopEndReason.transportError, + message: message, + hint: null, + retryable: true, + ), + final ServerTcpErr tcp => ( + reason: ffi.RemoteDesktopEndReason.transportError, + message: tcp.toString(), + hint: tcp.solution, + retryable: tcp.retryable, + ), + final SSHErr ssh => ( + reason: ffi.RemoteDesktopEndReason.transportError, + message: ssh.toString(), + hint: ssh.solution, + retryable: ssh.retryable, + ), + final Err err => ( + reason: ffi.RemoteDesktopEndReason.transportError, + message: err.toString(), + hint: err.solution, + retryable: true, + ), + _ => ( + reason: ffi.RemoteDesktopEndReason.transportError, + message: error.toString(), + hint: null, + retryable: true, + ), + }; + /// The local loopback a session connects to, carried by whichever transport /// can reach the target — see [ServerTcpDialer], which owns the ordering and /// the fall-through between a server's two transports. diff --git a/lib/data/terminal/terminal_session.dart b/lib/data/terminal/terminal_session.dart index 6a5ae18240..30592d848d 100644 --- a/lib/data/terminal/terminal_session.dart +++ b/lib/data/terminal/terminal_session.dart @@ -605,6 +605,9 @@ class TerminalSession { Loggers.app.warning('Mosh write rejected: ${e.message}'); onMoshWriteError?.call(e); return; + } catch (e) { + Loggers.app.info('Terminal input not sent: $e'); + return; } // What the terminal answers on its own while output is being written — // a cursor position, a device attribute — is not typing, and sent to @@ -677,6 +680,8 @@ class TerminalSession { await session.done; if (!identical(_foreground, session)) return; _detachMoshCallbacks(); + terminal.onOutput = null; + terminal.onResize = null; _foreground = null; drainOutput(); status.shell.processExited(); @@ -690,6 +695,8 @@ class TerminalSession { /// is what a reconnect and a tmux switch both want. void unbindForeground() { _detachMoshCallbacks(); + terminal.onOutput = null; + terminal.onResize = null; _foreground = null; _cancelOutputSubscriptions(); } diff --git a/lib/data/terminal/tmux/tmux_command_executor.dart b/lib/data/terminal/tmux/tmux_command_executor.dart index baac1cb65e..2d9503ab51 100644 --- a/lib/data/terminal/tmux/tmux_command_executor.dart +++ b/lib/data/terminal/tmux/tmux_command_executor.dart @@ -33,7 +33,12 @@ final class TmuxCommandExecutor { } final completer = Completer(); _pending.add(completer); - _writeCommand(command); + try { + _writeCommand(command); + } catch (error, stackTrace) { + _pending.remove(completer); + return Future.error(error, stackTrace); + } return completer.future; } diff --git a/lib/data/terminal/tmux/tmux_control_client.dart b/lib/data/terminal/tmux/tmux_control_client.dart index 921ca3d5a3..bf95a0cc60 100644 --- a/lib/data/terminal/tmux/tmux_control_client.dart +++ b/lib/data/terminal/tmux/tmux_control_client.dart @@ -116,6 +116,7 @@ final class TmuxControlClient { /// Used on the resize path, where Flutter should not block a layout change /// on a round trip to the server. void send(String command) { + if (_commands.isClosed) return; unawaited( run(command).catchError((Object error) { onCommandError?.call(command, error); @@ -129,7 +130,7 @@ final class TmuxControlClient { /// Hex input avoids a second shell and avoids tmux command-parser quoting /// for arbitrary text. The pane receives exactly the bytes xterm produced. void sendInput(List data) { - if (data.isEmpty) return; + if (data.isEmpty || _commands.isClosed) return; final paneId = _snapshot?.activePaneId; if (paneId == null) return; @@ -655,6 +656,7 @@ final class TmuxControlClient { } void _resumePaneOutput(TmuxPaneId paneId) { + if (_commands.isClosed) return; unawaited( runRequired("refresh-client -A '$paneId:continue'").catchError(( Object error, diff --git a/lib/data/terminal/tmux/tmux_control_shell_session.dart b/lib/data/terminal/tmux/tmux_control_shell_session.dart index e55971c107..c274ba424b 100644 --- a/lib/data/terminal/tmux/tmux_control_shell_session.dart +++ b/lib/data/terminal/tmux/tmux_control_shell_session.dart @@ -36,6 +36,7 @@ final class TmuxControlShellSession implements ShellSession, RedrawingShell { StreamSubscription? _paneOutputSubscription; StreamSubscription? _snapshotSubscription; Future _done = Future.value(); + bool _ended = false; bool _closed = false; TmuxPaneId? _normalizedPaneId; @@ -65,13 +66,13 @@ final class TmuxControlShellSession implements ShellSession, RedrawingShell { @override void write(List data) { - if (_closed) return; + if (_ended || _closed) return; _client.sendInput(data); } @override void resizeTerminal(int width, int height) { - if (_closed) return; + if (_ended || _closed) return; _session.resizeTerminal(width, height); _client.resizeWindow(width, height); } @@ -83,6 +84,7 @@ final class TmuxControlShellSession implements ShellSession, RedrawingShell { void close() { if (_closed) return; _flushOutputNormalizer(); + _ended = true; _closed = true; unawaited(_client.dispose()); unawaited(_snapshotSubscription?.cancel()); @@ -97,7 +99,7 @@ final class TmuxControlShellSession implements ShellSession, RedrawingShell { } void _handlePaneOutput(TmuxControlPaneOutput event) { - if (_closed) return; + if (_ended || _closed) return; final activePane = _client.snapshot?.activePaneId; if (activePane == null || event.paneId != activePane) { _scanHiddenPane(event); @@ -129,6 +131,7 @@ final class TmuxControlShellSession implements ShellSession, RedrawingShell { } void _handleSnapshot(TmuxControlSnapshot snapshot) { + if (_ended || _closed) return; final panes = snapshot.paneWindows.keys; // An empty list is a refresh that could not read it, not a session // without panes: tmux has none of those. @@ -138,6 +141,7 @@ final class TmuxControlShellSession implements ShellSession, RedrawingShell { } void _handleDone() { + _ended = true; _flushOutputNormalizer(); if (_outputController.isClosed) return; _outputController.close(); diff --git a/lib/src/rust/api/mosh.dart b/lib/src/rust/api/mosh.dart index ef951a2043..25d74f046a 100644 --- a/lib/src/rust/api/mosh.dart +++ b/lib/src/rust/api/mosh.dart @@ -10,7 +10,7 @@ import 'package:freezed_annotation/freezed_annotation.dart' hide protected; part 'mosh.freezed.dart'; // These functions are ignored because they are not marked as `pub`: `resolve_udp_addr` -// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `clone`, `clone`, `clone`, `clone`, `clone`, `eq`, `eq`, `eq`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `from` +// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `from`, `from` /// Builds a shell-agnostic SSH command that starts `mosh-server`. String moshBuildServerCommand({ @@ -81,6 +81,30 @@ abstract class MoshBridgeSession implements RustOpaqueInterface { void write({required List data}); } +@freezed +sealed class MoshBridgeError with _$MoshBridgeError implements FrbException { + const MoshBridgeError._(); + + /// The session's run loop has already exited (remote exit or local close). + const factory MoshBridgeError.sessionClosed() = MoshBridgeError_SessionClosed; + + /// Unacknowledged outgoing terminal input exceeded the send buffer limit. + const factory MoshBridgeError.sendBufferFull({required String message}) = + MoshBridgeError_SendBufferFull; + + /// UDP handshake did not complete before the deadline. + const factory MoshBridgeError.handshakeTimeout({required String message}) = + MoshBridgeError_HandshakeTimeout; + + /// Invalid key, host, or session configuration rejected before connecting. + const factory MoshBridgeError.invalidConfig({required String message}) = + MoshBridgeError_InvalidConfig; + + /// Any other transport, DNS, or I/O failure. + const factory MoshBridgeError.other({required String message}) = + MoshBridgeError_Other; +} + @freezed sealed class MoshBridgeEvent with _$MoshBridgeEvent { const MoshBridgeEvent._(); diff --git a/lib/src/rust/api/mosh.freezed.dart b/lib/src/rust/api/mosh.freezed.dart index 5fb484b65a..f409c16f8b 100644 --- a/lib/src/rust/api/mosh.freezed.dart +++ b/lib/src/rust/api/mosh.freezed.dart @@ -12,6 +12,488 @@ part of 'mosh.dart'; // GENERATED CODE - DO NOT MODIFY BY HAND // dart format off T _$identity(T value) => value; +/// @nodoc +mixin _$MoshBridgeError { + + + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is MoshBridgeError); +} + + +@override +int get hashCode => runtimeType.hashCode; + +@override +String toString() { + return 'MoshBridgeError()'; +} + + +} + +/// @nodoc +class $MoshBridgeErrorCopyWith<$Res> { +$MoshBridgeErrorCopyWith(MoshBridgeError _, $Res Function(MoshBridgeError) __); +} + + +/// Adds pattern-matching-related methods to [MoshBridgeError]. +extension MoshBridgeErrorPatterns on MoshBridgeError { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap({TResult Function( MoshBridgeError_SessionClosed value)? sessionClosed,TResult Function( MoshBridgeError_SendBufferFull value)? sendBufferFull,TResult Function( MoshBridgeError_HandshakeTimeout value)? handshakeTimeout,TResult Function( MoshBridgeError_InvalidConfig value)? invalidConfig,TResult Function( MoshBridgeError_Other value)? other,required TResult orElse(),}){ +final _that = this; +switch (_that) { +case MoshBridgeError_SessionClosed() when sessionClosed != null: +return sessionClosed(_that);case MoshBridgeError_SendBufferFull() when sendBufferFull != null: +return sendBufferFull(_that);case MoshBridgeError_HandshakeTimeout() when handshakeTimeout != null: +return handshakeTimeout(_that);case MoshBridgeError_InvalidConfig() when invalidConfig != null: +return invalidConfig(_that);case MoshBridgeError_Other() when other != null: +return other(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map({required TResult Function( MoshBridgeError_SessionClosed value) sessionClosed,required TResult Function( MoshBridgeError_SendBufferFull value) sendBufferFull,required TResult Function( MoshBridgeError_HandshakeTimeout value) handshakeTimeout,required TResult Function( MoshBridgeError_InvalidConfig value) invalidConfig,required TResult Function( MoshBridgeError_Other value) other,}){ +final _that = this; +switch (_that) { +case MoshBridgeError_SessionClosed(): +return sessionClosed(_that);case MoshBridgeError_SendBufferFull(): +return sendBufferFull(_that);case MoshBridgeError_HandshakeTimeout(): +return handshakeTimeout(_that);case MoshBridgeError_InvalidConfig(): +return invalidConfig(_that);case MoshBridgeError_Other(): +return other(_that);} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull({TResult? Function( MoshBridgeError_SessionClosed value)? sessionClosed,TResult? Function( MoshBridgeError_SendBufferFull value)? sendBufferFull,TResult? Function( MoshBridgeError_HandshakeTimeout value)? handshakeTimeout,TResult? Function( MoshBridgeError_InvalidConfig value)? invalidConfig,TResult? Function( MoshBridgeError_Other value)? other,}){ +final _that = this; +switch (_that) { +case MoshBridgeError_SessionClosed() when sessionClosed != null: +return sessionClosed(_that);case MoshBridgeError_SendBufferFull() when sendBufferFull != null: +return sendBufferFull(_that);case MoshBridgeError_HandshakeTimeout() when handshakeTimeout != null: +return handshakeTimeout(_that);case MoshBridgeError_InvalidConfig() when invalidConfig != null: +return invalidConfig(_that);case MoshBridgeError_Other() when other != null: +return other(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen({TResult Function()? sessionClosed,TResult Function( String message)? sendBufferFull,TResult Function( String message)? handshakeTimeout,TResult Function( String message)? invalidConfig,TResult Function( String message)? other,required TResult orElse(),}) {final _that = this; +switch (_that) { +case MoshBridgeError_SessionClosed() when sessionClosed != null: +return sessionClosed();case MoshBridgeError_SendBufferFull() when sendBufferFull != null: +return sendBufferFull(_that.message);case MoshBridgeError_HandshakeTimeout() when handshakeTimeout != null: +return handshakeTimeout(_that.message);case MoshBridgeError_InvalidConfig() when invalidConfig != null: +return invalidConfig(_that.message);case MoshBridgeError_Other() when other != null: +return other(_that.message);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when({required TResult Function() sessionClosed,required TResult Function( String message) sendBufferFull,required TResult Function( String message) handshakeTimeout,required TResult Function( String message) invalidConfig,required TResult Function( String message) other,}) {final _that = this; +switch (_that) { +case MoshBridgeError_SessionClosed(): +return sessionClosed();case MoshBridgeError_SendBufferFull(): +return sendBufferFull(_that.message);case MoshBridgeError_HandshakeTimeout(): +return handshakeTimeout(_that.message);case MoshBridgeError_InvalidConfig(): +return invalidConfig(_that.message);case MoshBridgeError_Other(): +return other(_that.message);} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull({TResult? Function()? sessionClosed,TResult? Function( String message)? sendBufferFull,TResult? Function( String message)? handshakeTimeout,TResult? Function( String message)? invalidConfig,TResult? Function( String message)? other,}) {final _that = this; +switch (_that) { +case MoshBridgeError_SessionClosed() when sessionClosed != null: +return sessionClosed();case MoshBridgeError_SendBufferFull() when sendBufferFull != null: +return sendBufferFull(_that.message);case MoshBridgeError_HandshakeTimeout() when handshakeTimeout != null: +return handshakeTimeout(_that.message);case MoshBridgeError_InvalidConfig() when invalidConfig != null: +return invalidConfig(_that.message);case MoshBridgeError_Other() when other != null: +return other(_that.message);case _: + return null; + +} +} + +} + +/// @nodoc + + +class MoshBridgeError_SessionClosed extends MoshBridgeError { + const MoshBridgeError_SessionClosed(): super._(); + + + + + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is MoshBridgeError_SessionClosed); +} + + +@override +int get hashCode => runtimeType.hashCode; + +@override +String toString() { + return 'MoshBridgeError.sessionClosed()'; +} + + +} + + + + +/// @nodoc + + +class MoshBridgeError_SendBufferFull extends MoshBridgeError { + const MoshBridgeError_SendBufferFull({required this.message}): super._(); + + + final String message; + +/// Create a copy of MoshBridgeError +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$MoshBridgeError_SendBufferFullCopyWith get copyWith => _$MoshBridgeError_SendBufferFullCopyWithImpl(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is MoshBridgeError_SendBufferFull&&(identical(other.message, message) || other.message == message)); +} + + +@override +int get hashCode { + return Object.hash(runtimeType,message); +} + +@override +String toString() { + return 'MoshBridgeError.sendBufferFull(message: $message)'; +} + + +} + +/// @nodoc +abstract mixin class $MoshBridgeError_SendBufferFullCopyWith<$Res> implements $MoshBridgeErrorCopyWith<$Res> { + factory $MoshBridgeError_SendBufferFullCopyWith(MoshBridgeError_SendBufferFull value, $Res Function(MoshBridgeError_SendBufferFull) _then) = _$MoshBridgeError_SendBufferFullCopyWithImpl; +@useResult +$Res call({ + String message +}); + + + + +} +/// @nodoc +class _$MoshBridgeError_SendBufferFullCopyWithImpl<$Res> + implements $MoshBridgeError_SendBufferFullCopyWith<$Res> { + _$MoshBridgeError_SendBufferFullCopyWithImpl(this._self, this._then); + + final MoshBridgeError_SendBufferFull _self; + final $Res Function(MoshBridgeError_SendBufferFull) _then; + +/// Create a copy of MoshBridgeError +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') $Res call({Object? message = null,}) { + return _then(MoshBridgeError_SendBufferFull( +message: null == message ? _self.message : message // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + +/// @nodoc + + +class MoshBridgeError_HandshakeTimeout extends MoshBridgeError { + const MoshBridgeError_HandshakeTimeout({required this.message}): super._(); + + + final String message; + +/// Create a copy of MoshBridgeError +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$MoshBridgeError_HandshakeTimeoutCopyWith get copyWith => _$MoshBridgeError_HandshakeTimeoutCopyWithImpl(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is MoshBridgeError_HandshakeTimeout&&(identical(other.message, message) || other.message == message)); +} + + +@override +int get hashCode { + return Object.hash(runtimeType,message); +} + +@override +String toString() { + return 'MoshBridgeError.handshakeTimeout(message: $message)'; +} + + +} + +/// @nodoc +abstract mixin class $MoshBridgeError_HandshakeTimeoutCopyWith<$Res> implements $MoshBridgeErrorCopyWith<$Res> { + factory $MoshBridgeError_HandshakeTimeoutCopyWith(MoshBridgeError_HandshakeTimeout value, $Res Function(MoshBridgeError_HandshakeTimeout) _then) = _$MoshBridgeError_HandshakeTimeoutCopyWithImpl; +@useResult +$Res call({ + String message +}); + + + + +} +/// @nodoc +class _$MoshBridgeError_HandshakeTimeoutCopyWithImpl<$Res> + implements $MoshBridgeError_HandshakeTimeoutCopyWith<$Res> { + _$MoshBridgeError_HandshakeTimeoutCopyWithImpl(this._self, this._then); + + final MoshBridgeError_HandshakeTimeout _self; + final $Res Function(MoshBridgeError_HandshakeTimeout) _then; + +/// Create a copy of MoshBridgeError +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') $Res call({Object? message = null,}) { + return _then(MoshBridgeError_HandshakeTimeout( +message: null == message ? _self.message : message // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + +/// @nodoc + + +class MoshBridgeError_InvalidConfig extends MoshBridgeError { + const MoshBridgeError_InvalidConfig({required this.message}): super._(); + + + final String message; + +/// Create a copy of MoshBridgeError +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$MoshBridgeError_InvalidConfigCopyWith get copyWith => _$MoshBridgeError_InvalidConfigCopyWithImpl(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is MoshBridgeError_InvalidConfig&&(identical(other.message, message) || other.message == message)); +} + + +@override +int get hashCode { + return Object.hash(runtimeType,message); +} + +@override +String toString() { + return 'MoshBridgeError.invalidConfig(message: $message)'; +} + + +} + +/// @nodoc +abstract mixin class $MoshBridgeError_InvalidConfigCopyWith<$Res> implements $MoshBridgeErrorCopyWith<$Res> { + factory $MoshBridgeError_InvalidConfigCopyWith(MoshBridgeError_InvalidConfig value, $Res Function(MoshBridgeError_InvalidConfig) _then) = _$MoshBridgeError_InvalidConfigCopyWithImpl; +@useResult +$Res call({ + String message +}); + + + + +} +/// @nodoc +class _$MoshBridgeError_InvalidConfigCopyWithImpl<$Res> + implements $MoshBridgeError_InvalidConfigCopyWith<$Res> { + _$MoshBridgeError_InvalidConfigCopyWithImpl(this._self, this._then); + + final MoshBridgeError_InvalidConfig _self; + final $Res Function(MoshBridgeError_InvalidConfig) _then; + +/// Create a copy of MoshBridgeError +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') $Res call({Object? message = null,}) { + return _then(MoshBridgeError_InvalidConfig( +message: null == message ? _self.message : message // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + +/// @nodoc + + +class MoshBridgeError_Other extends MoshBridgeError { + const MoshBridgeError_Other({required this.message}): super._(); + + + final String message; + +/// Create a copy of MoshBridgeError +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$MoshBridgeError_OtherCopyWith get copyWith => _$MoshBridgeError_OtherCopyWithImpl(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is MoshBridgeError_Other&&(identical(other.message, message) || other.message == message)); +} + + +@override +int get hashCode { + return Object.hash(runtimeType,message); +} + +@override +String toString() { + return 'MoshBridgeError.other(message: $message)'; +} + + +} + +/// @nodoc +abstract mixin class $MoshBridgeError_OtherCopyWith<$Res> implements $MoshBridgeErrorCopyWith<$Res> { + factory $MoshBridgeError_OtherCopyWith(MoshBridgeError_Other value, $Res Function(MoshBridgeError_Other) _then) = _$MoshBridgeError_OtherCopyWithImpl; +@useResult +$Res call({ + String message +}); + + + + +} +/// @nodoc +class _$MoshBridgeError_OtherCopyWithImpl<$Res> + implements $MoshBridgeError_OtherCopyWith<$Res> { + _$MoshBridgeError_OtherCopyWithImpl(this._self, this._then); + + final MoshBridgeError_Other _self; + final $Res Function(MoshBridgeError_Other) _then; + +/// Create a copy of MoshBridgeError +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') $Res call({Object? message = null,}) { + return _then(MoshBridgeError_Other( +message: null == message ? _self.message : message // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + /// @nodoc mixin _$MoshBridgeEvent { diff --git a/lib/src/rust/api/remote_desktop.dart b/lib/src/rust/api/remote_desktop.dart index a3508739f1..d797b4145e 100644 --- a/lib/src/rust/api/remote_desktop.dart +++ b/lib/src/rust/api/remote_desktop.dart @@ -4,13 +4,14 @@ // ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import import '../frb_generated.dart'; + import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; import 'package:freezed_annotation/freezed_annotation.dart' hide protected; part 'remote_desktop.freezed.dart'; // These functions are ignored because they are not marked as `pub`: `apply_vnc_event`, `bgra_to_rgba`, `certificate_event`, `classify_rdp_failure`, `close`, `close`, `copy_rect`, `credssp_failure`, `draw_bgra`, `draw_jpeg`, `ensure_rect`, `event`, `failure_end_reason`, `finish_vnc_error`, `fold_into`, `format_endpoint`, `format_sha256`, `frame_len`, `frame_shared`, `frame`, `handle_rdp_command`, `handle_vnc_command`, `is_lifecycle`, `is_ready`, `new`, `new`, `parse_sha256_fingerprint`, `pinned_certificate`, `publish_latest_frame`, `rdp_connect_failure`, `rdp_pixels_to_bgra`, `rdp_session_end_failure`, `recv`, `recv`, `resize`, `run_rdp`, `run_vnc`, `send_rdp_fast_path`, `send_vnc_wheel`, `send`, `send`, `send`, `spawn`, `try_recv`, `validate_endpoint`, `validate_size`, `vnc_failure` -// These types are ignored because they are neither used by any `pub` functions nor (for structs and enums) marked `#[frb(unignore)]`: `CommandQueue`, `EventQueue`, `EventReceiver`, `EventSender`, `Frame`, `Framebuffer`, `RdpClipboardBackend`, `RdpClipboardState`, `SessionCommand` -// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `as_any_mut`, `as_any`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `client_capabilities`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `drop`, `eq`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `on_file_contents_request`, `on_file_contents_response`, `on_format_data_request`, `on_format_data_response`, `on_lock`, `on_process_negotiated_capabilities`, `on_ready`, `on_remote_copy`, `on_request_format_list`, `on_unlock`, `temporary_directory` +// These types are ignored because they are neither used by any `pub` functions nor (for structs and enums) marked `#[frb(unignore)]`: `CommandQueue`, `CommandSendError`, `EventQueue`, `EventReceiver`, `EventSender`, `Frame`, `Framebuffer`, `RdpClipboardBackend`, `RdpClipboardState`, `SessionCommand` +// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `as_any_mut`, `as_any`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `client_capabilities`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `drop`, `eq`, `eq`, `eq`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `on_file_contents_request`, `on_file_contents_response`, `on_format_data_request`, `on_format_data_response`, `on_lock`, `on_process_negotiated_capabilities`, `on_ready`, `on_remote_copy`, `on_request_format_list`, `on_unlock`, `temporary_directory` // These functions are ignored (category: IgnoreBecauseOwnerTyShouldIgnore): `default`, `default` // Rust type: RustOpaqueMoi> @@ -129,6 +130,35 @@ class RdpSessionParams { scaleFactor == other.scaleFactor; } +@freezed +sealed class RemoteDesktopBridgeError + with _$RemoteDesktopBridgeError + implements FrbException { + const RemoteDesktopBridgeError._(); + + /// The background worker thread has already closed its command channel. + const factory RemoteDesktopBridgeError.sessionClosed() = + RemoteDesktopBridgeError_SessionClosed; + + /// The command queue reached its capacity limit because the session is not draining. + const factory RemoteDesktopBridgeError.queueFull() = + RemoteDesktopBridgeError_QueueFull; + + /// Permanent session parameter validation error (do not auto-retry). + const factory RemoteDesktopBridgeError.invalidConfig({ + required String message, + }) = RemoteDesktopBridgeError_InvalidConfig; + + /// Failed to spawn the background worker thread. + const factory RemoteDesktopBridgeError.workerSpawnFailed({ + required String message, + }) = RemoteDesktopBridgeError_WorkerSpawnFailed; + + /// Internal bridge failure (such as a poisoned mutex). + const factory RemoteDesktopBridgeError.internal({required String message}) = + RemoteDesktopBridgeError_Internal; +} + enum RemoteDesktopConnectionState { connecting, connected, diff --git a/lib/src/rust/api/remote_desktop.freezed.dart b/lib/src/rust/api/remote_desktop.freezed.dart index 983e6842c0..1f5be2d8c8 100644 --- a/lib/src/rust/api/remote_desktop.freezed.dart +++ b/lib/src/rust/api/remote_desktop.freezed.dart @@ -12,6 +12,452 @@ part of 'remote_desktop.dart'; // GENERATED CODE - DO NOT MODIFY BY HAND // dart format off T _$identity(T value) => value; +/// @nodoc +mixin _$RemoteDesktopBridgeError { + + + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is RemoteDesktopBridgeError); +} + + +@override +int get hashCode => runtimeType.hashCode; + +@override +String toString() { + return 'RemoteDesktopBridgeError()'; +} + + +} + +/// @nodoc +class $RemoteDesktopBridgeErrorCopyWith<$Res> { +$RemoteDesktopBridgeErrorCopyWith(RemoteDesktopBridgeError _, $Res Function(RemoteDesktopBridgeError) __); +} + + +/// Adds pattern-matching-related methods to [RemoteDesktopBridgeError]. +extension RemoteDesktopBridgeErrorPatterns on RemoteDesktopBridgeError { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap({TResult Function( RemoteDesktopBridgeError_SessionClosed value)? sessionClosed,TResult Function( RemoteDesktopBridgeError_QueueFull value)? queueFull,TResult Function( RemoteDesktopBridgeError_InvalidConfig value)? invalidConfig,TResult Function( RemoteDesktopBridgeError_WorkerSpawnFailed value)? workerSpawnFailed,TResult Function( RemoteDesktopBridgeError_Internal value)? internal,required TResult orElse(),}){ +final _that = this; +switch (_that) { +case RemoteDesktopBridgeError_SessionClosed() when sessionClosed != null: +return sessionClosed(_that);case RemoteDesktopBridgeError_QueueFull() when queueFull != null: +return queueFull(_that);case RemoteDesktopBridgeError_InvalidConfig() when invalidConfig != null: +return invalidConfig(_that);case RemoteDesktopBridgeError_WorkerSpawnFailed() when workerSpawnFailed != null: +return workerSpawnFailed(_that);case RemoteDesktopBridgeError_Internal() when internal != null: +return internal(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map({required TResult Function( RemoteDesktopBridgeError_SessionClosed value) sessionClosed,required TResult Function( RemoteDesktopBridgeError_QueueFull value) queueFull,required TResult Function( RemoteDesktopBridgeError_InvalidConfig value) invalidConfig,required TResult Function( RemoteDesktopBridgeError_WorkerSpawnFailed value) workerSpawnFailed,required TResult Function( RemoteDesktopBridgeError_Internal value) internal,}){ +final _that = this; +switch (_that) { +case RemoteDesktopBridgeError_SessionClosed(): +return sessionClosed(_that);case RemoteDesktopBridgeError_QueueFull(): +return queueFull(_that);case RemoteDesktopBridgeError_InvalidConfig(): +return invalidConfig(_that);case RemoteDesktopBridgeError_WorkerSpawnFailed(): +return workerSpawnFailed(_that);case RemoteDesktopBridgeError_Internal(): +return internal(_that);} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull({TResult? Function( RemoteDesktopBridgeError_SessionClosed value)? sessionClosed,TResult? Function( RemoteDesktopBridgeError_QueueFull value)? queueFull,TResult? Function( RemoteDesktopBridgeError_InvalidConfig value)? invalidConfig,TResult? Function( RemoteDesktopBridgeError_WorkerSpawnFailed value)? workerSpawnFailed,TResult? Function( RemoteDesktopBridgeError_Internal value)? internal,}){ +final _that = this; +switch (_that) { +case RemoteDesktopBridgeError_SessionClosed() when sessionClosed != null: +return sessionClosed(_that);case RemoteDesktopBridgeError_QueueFull() when queueFull != null: +return queueFull(_that);case RemoteDesktopBridgeError_InvalidConfig() when invalidConfig != null: +return invalidConfig(_that);case RemoteDesktopBridgeError_WorkerSpawnFailed() when workerSpawnFailed != null: +return workerSpawnFailed(_that);case RemoteDesktopBridgeError_Internal() when internal != null: +return internal(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen({TResult Function()? sessionClosed,TResult Function()? queueFull,TResult Function( String message)? invalidConfig,TResult Function( String message)? workerSpawnFailed,TResult Function( String message)? internal,required TResult orElse(),}) {final _that = this; +switch (_that) { +case RemoteDesktopBridgeError_SessionClosed() when sessionClosed != null: +return sessionClosed();case RemoteDesktopBridgeError_QueueFull() when queueFull != null: +return queueFull();case RemoteDesktopBridgeError_InvalidConfig() when invalidConfig != null: +return invalidConfig(_that.message);case RemoteDesktopBridgeError_WorkerSpawnFailed() when workerSpawnFailed != null: +return workerSpawnFailed(_that.message);case RemoteDesktopBridgeError_Internal() when internal != null: +return internal(_that.message);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when({required TResult Function() sessionClosed,required TResult Function() queueFull,required TResult Function( String message) invalidConfig,required TResult Function( String message) workerSpawnFailed,required TResult Function( String message) internal,}) {final _that = this; +switch (_that) { +case RemoteDesktopBridgeError_SessionClosed(): +return sessionClosed();case RemoteDesktopBridgeError_QueueFull(): +return queueFull();case RemoteDesktopBridgeError_InvalidConfig(): +return invalidConfig(_that.message);case RemoteDesktopBridgeError_WorkerSpawnFailed(): +return workerSpawnFailed(_that.message);case RemoteDesktopBridgeError_Internal(): +return internal(_that.message);} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull({TResult? Function()? sessionClosed,TResult? Function()? queueFull,TResult? Function( String message)? invalidConfig,TResult? Function( String message)? workerSpawnFailed,TResult? Function( String message)? internal,}) {final _that = this; +switch (_that) { +case RemoteDesktopBridgeError_SessionClosed() when sessionClosed != null: +return sessionClosed();case RemoteDesktopBridgeError_QueueFull() when queueFull != null: +return queueFull();case RemoteDesktopBridgeError_InvalidConfig() when invalidConfig != null: +return invalidConfig(_that.message);case RemoteDesktopBridgeError_WorkerSpawnFailed() when workerSpawnFailed != null: +return workerSpawnFailed(_that.message);case RemoteDesktopBridgeError_Internal() when internal != null: +return internal(_that.message);case _: + return null; + +} +} + +} + +/// @nodoc + + +class RemoteDesktopBridgeError_SessionClosed extends RemoteDesktopBridgeError { + const RemoteDesktopBridgeError_SessionClosed(): super._(); + + + + + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is RemoteDesktopBridgeError_SessionClosed); +} + + +@override +int get hashCode => runtimeType.hashCode; + +@override +String toString() { + return 'RemoteDesktopBridgeError.sessionClosed()'; +} + + +} + + + + +/// @nodoc + + +class RemoteDesktopBridgeError_QueueFull extends RemoteDesktopBridgeError { + const RemoteDesktopBridgeError_QueueFull(): super._(); + + + + + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is RemoteDesktopBridgeError_QueueFull); +} + + +@override +int get hashCode => runtimeType.hashCode; + +@override +String toString() { + return 'RemoteDesktopBridgeError.queueFull()'; +} + + +} + + + + +/// @nodoc + + +class RemoteDesktopBridgeError_InvalidConfig extends RemoteDesktopBridgeError { + const RemoteDesktopBridgeError_InvalidConfig({required this.message}): super._(); + + + final String message; + +/// Create a copy of RemoteDesktopBridgeError +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$RemoteDesktopBridgeError_InvalidConfigCopyWith get copyWith => _$RemoteDesktopBridgeError_InvalidConfigCopyWithImpl(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is RemoteDesktopBridgeError_InvalidConfig&&(identical(other.message, message) || other.message == message)); +} + + +@override +int get hashCode { + return Object.hash(runtimeType,message); +} + +@override +String toString() { + return 'RemoteDesktopBridgeError.invalidConfig(message: $message)'; +} + + +} + +/// @nodoc +abstract mixin class $RemoteDesktopBridgeError_InvalidConfigCopyWith<$Res> implements $RemoteDesktopBridgeErrorCopyWith<$Res> { + factory $RemoteDesktopBridgeError_InvalidConfigCopyWith(RemoteDesktopBridgeError_InvalidConfig value, $Res Function(RemoteDesktopBridgeError_InvalidConfig) _then) = _$RemoteDesktopBridgeError_InvalidConfigCopyWithImpl; +@useResult +$Res call({ + String message +}); + + + + +} +/// @nodoc +class _$RemoteDesktopBridgeError_InvalidConfigCopyWithImpl<$Res> + implements $RemoteDesktopBridgeError_InvalidConfigCopyWith<$Res> { + _$RemoteDesktopBridgeError_InvalidConfigCopyWithImpl(this._self, this._then); + + final RemoteDesktopBridgeError_InvalidConfig _self; + final $Res Function(RemoteDesktopBridgeError_InvalidConfig) _then; + +/// Create a copy of RemoteDesktopBridgeError +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') $Res call({Object? message = null,}) { + return _then(RemoteDesktopBridgeError_InvalidConfig( +message: null == message ? _self.message : message // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + +/// @nodoc + + +class RemoteDesktopBridgeError_WorkerSpawnFailed extends RemoteDesktopBridgeError { + const RemoteDesktopBridgeError_WorkerSpawnFailed({required this.message}): super._(); + + + final String message; + +/// Create a copy of RemoteDesktopBridgeError +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$RemoteDesktopBridgeError_WorkerSpawnFailedCopyWith get copyWith => _$RemoteDesktopBridgeError_WorkerSpawnFailedCopyWithImpl(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is RemoteDesktopBridgeError_WorkerSpawnFailed&&(identical(other.message, message) || other.message == message)); +} + + +@override +int get hashCode { + return Object.hash(runtimeType,message); +} + +@override +String toString() { + return 'RemoteDesktopBridgeError.workerSpawnFailed(message: $message)'; +} + + +} + +/// @nodoc +abstract mixin class $RemoteDesktopBridgeError_WorkerSpawnFailedCopyWith<$Res> implements $RemoteDesktopBridgeErrorCopyWith<$Res> { + factory $RemoteDesktopBridgeError_WorkerSpawnFailedCopyWith(RemoteDesktopBridgeError_WorkerSpawnFailed value, $Res Function(RemoteDesktopBridgeError_WorkerSpawnFailed) _then) = _$RemoteDesktopBridgeError_WorkerSpawnFailedCopyWithImpl; +@useResult +$Res call({ + String message +}); + + + + +} +/// @nodoc +class _$RemoteDesktopBridgeError_WorkerSpawnFailedCopyWithImpl<$Res> + implements $RemoteDesktopBridgeError_WorkerSpawnFailedCopyWith<$Res> { + _$RemoteDesktopBridgeError_WorkerSpawnFailedCopyWithImpl(this._self, this._then); + + final RemoteDesktopBridgeError_WorkerSpawnFailed _self; + final $Res Function(RemoteDesktopBridgeError_WorkerSpawnFailed) _then; + +/// Create a copy of RemoteDesktopBridgeError +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') $Res call({Object? message = null,}) { + return _then(RemoteDesktopBridgeError_WorkerSpawnFailed( +message: null == message ? _self.message : message // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + +/// @nodoc + + +class RemoteDesktopBridgeError_Internal extends RemoteDesktopBridgeError { + const RemoteDesktopBridgeError_Internal({required this.message}): super._(); + + + final String message; + +/// Create a copy of RemoteDesktopBridgeError +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$RemoteDesktopBridgeError_InternalCopyWith get copyWith => _$RemoteDesktopBridgeError_InternalCopyWithImpl(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is RemoteDesktopBridgeError_Internal&&(identical(other.message, message) || other.message == message)); +} + + +@override +int get hashCode { + return Object.hash(runtimeType,message); +} + +@override +String toString() { + return 'RemoteDesktopBridgeError.internal(message: $message)'; +} + + +} + +/// @nodoc +abstract mixin class $RemoteDesktopBridgeError_InternalCopyWith<$Res> implements $RemoteDesktopBridgeErrorCopyWith<$Res> { + factory $RemoteDesktopBridgeError_InternalCopyWith(RemoteDesktopBridgeError_Internal value, $Res Function(RemoteDesktopBridgeError_Internal) _then) = _$RemoteDesktopBridgeError_InternalCopyWithImpl; +@useResult +$Res call({ + String message +}); + + + + +} +/// @nodoc +class _$RemoteDesktopBridgeError_InternalCopyWithImpl<$Res> + implements $RemoteDesktopBridgeError_InternalCopyWith<$Res> { + _$RemoteDesktopBridgeError_InternalCopyWithImpl(this._self, this._then); + + final RemoteDesktopBridgeError_Internal _self; + final $Res Function(RemoteDesktopBridgeError_Internal) _then; + +/// Create a copy of RemoteDesktopBridgeError +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') $Res call({Object? message = null,}) { + return _then(RemoteDesktopBridgeError_Internal( +message: null == message ? _self.message : message // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + /// @nodoc mixin _$RemoteDesktopEvent { diff --git a/lib/src/rust/frb_generated.dart b/lib/src/rust/frb_generated.dart index 5dad7dad31..d69b68c7f5 100644 --- a/lib/src/rust/frb_generated.dart +++ b/lib/src/rust/frb_generated.dart @@ -3100,7 +3100,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { codec: SseCodec( decodeSuccessData: sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMoshBridgeSession, - decodeErrorData: sse_decode_String, + decodeErrorData: sse_decode_mosh_bridge_error, ), constMeta: kCrateApiMoshMoshBridgeSessionConnectConstMeta, argValues: [ @@ -3181,7 +3181,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { }, codec: SseCodec( decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_String, + decodeErrorData: sse_decode_mosh_bridge_error, ), constMeta: kCrateApiMoshMoshBridgeSessionRebindConstMeta, argValues: [that], @@ -3216,7 +3216,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { }, codec: SseCodec( decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_String, + decodeErrorData: sse_decode_mosh_bridge_error, ), constMeta: kCrateApiMoshMoshBridgeSessionResizeConstMeta, argValues: [that, cols, rows], @@ -3249,7 +3249,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { }, codec: SseCodec( decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_String, + decodeErrorData: sse_decode_mosh_bridge_error, ), constMeta: kCrateApiMoshMoshBridgeSessionSetPredictionModeConstMeta, argValues: [that, mode], @@ -3290,7 +3290,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { }, codec: SseCodec( decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_String, + decodeErrorData: sse_decode_mosh_bridge_error, ), constMeta: kCrateApiMoshMoshBridgeSessionSyncCursorConstMeta, argValues: [that, row, col, cols, rows, inAltScreen], @@ -3323,7 +3323,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { }, codec: SseCodec( decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_String, + decodeErrorData: sse_decode_mosh_bridge_error, ), constMeta: kCrateApiMoshMoshBridgeSessionWriteConstMeta, argValues: [that, data], @@ -5702,7 +5702,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { }, codec: SseCodec( decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_String, + decodeErrorData: sse_decode_remote_desktop_bridge_error, ), constMeta: kCrateApiRemoteDesktopRemoteDesktopSessionHandleResizeConstMeta, @@ -5751,7 +5751,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { }, codec: SseCodec( decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_String, + decodeErrorData: sse_decode_remote_desktop_bridge_error, ), constMeta: kCrateApiRemoteDesktopRemoteDesktopSessionHandleSendClipboardTextConstMeta, @@ -5984,7 +5984,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { codec: SseCodec( decodeSuccessData: sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerRemoteDesktopSessionHandle, - decodeErrorData: sse_decode_String, + decodeErrorData: sse_decode_remote_desktop_bridge_error, ), constMeta: kCrateApiRemoteDesktopRemoteDesktopSessionHandleStartRdpConstMeta, @@ -6020,7 +6020,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { codec: SseCodec( decodeSuccessData: sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerRemoteDesktopSessionHandle, - decodeErrorData: sse_decode_String, + decodeErrorData: sse_decode_remote_desktop_bridge_error, ), constMeta: kCrateApiRemoteDesktopRemoteDesktopSessionHandleStartVncConstMeta, @@ -11541,7 +11541,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { }, codec: SseCodec( decodeSuccessData: sse_decode_String, - decodeErrorData: sse_decode_String, + decodeErrorData: sse_decode_mosh_bridge_error, ), constMeta: kCrateApiMoshMoshBuildServerCommandConstMeta, argValues: [serverBinary, udpPort, bindSshIp, colors, locale], @@ -11571,7 +11571,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { }, codec: SseCodec( decodeSuccessData: sse_decode_opt_box_autoadd_mosh_connect_data, - decodeErrorData: sse_decode_String, + decodeErrorData: sse_decode_mosh_bridge_error, ), constMeta: kCrateApiMoshMoshParseConnectConstMeta, argValues: [output], @@ -22548,6 +22548,31 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); } + @protected + MoshBridgeError dco_decode_mosh_bridge_error(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + switch (raw[0]) { + case 0: + return MoshBridgeError_SessionClosed(); + case 1: + return MoshBridgeError_SendBufferFull( + message: dco_decode_String(raw[1]), + ); + case 2: + return MoshBridgeError_HandshakeTimeout( + message: dco_decode_String(raw[1]), + ); + case 3: + return MoshBridgeError_InvalidConfig( + message: dco_decode_String(raw[1]), + ); + case 4: + return MoshBridgeError_Other(message: dco_decode_String(raw[1])); + default: + throw Exception("unreachable"); + } + } + @protected MoshBridgeEvent dco_decode_mosh_bridge_event(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -23937,6 +23962,31 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); } + @protected + RemoteDesktopBridgeError dco_decode_remote_desktop_bridge_error(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + switch (raw[0]) { + case 0: + return RemoteDesktopBridgeError_SessionClosed(); + case 1: + return RemoteDesktopBridgeError_QueueFull(); + case 2: + return RemoteDesktopBridgeError_InvalidConfig( + message: dco_decode_String(raw[1]), + ); + case 3: + return RemoteDesktopBridgeError_WorkerSpawnFailed( + message: dco_decode_String(raw[1]), + ); + case 4: + return RemoteDesktopBridgeError_Internal( + message: dco_decode_String(raw[1]), + ); + default: + throw Exception("unreachable"); + } + } + @protected RemoteDesktopConnectionState dco_decode_remote_desktop_connection_state( dynamic raw, @@ -32009,6 +32059,31 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return MonitorReleasePage(newest: var_newest, readOn: var_readOn); } + @protected + MoshBridgeError sse_decode_mosh_bridge_error(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var tag_ = sse_decode_i_32(deserializer); + switch (tag_) { + case 0: + return MoshBridgeError_SessionClosed(); + case 1: + var var_message = sse_decode_String(deserializer); + return MoshBridgeError_SendBufferFull(message: var_message); + case 2: + var var_message = sse_decode_String(deserializer); + return MoshBridgeError_HandshakeTimeout(message: var_message); + case 3: + var var_message = sse_decode_String(deserializer); + return MoshBridgeError_InvalidConfig(message: var_message); + case 4: + var var_message = sse_decode_String(deserializer); + return MoshBridgeError_Other(message: var_message); + default: + throw UnimplementedError(''); + } + } + @protected MoshBridgeEvent sse_decode_mosh_bridge_event(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -34024,6 +34099,32 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); } + @protected + RemoteDesktopBridgeError sse_decode_remote_desktop_bridge_error( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var tag_ = sse_decode_i_32(deserializer); + switch (tag_) { + case 0: + return RemoteDesktopBridgeError_SessionClosed(); + case 1: + return RemoteDesktopBridgeError_QueueFull(); + case 2: + var var_message = sse_decode_String(deserializer); + return RemoteDesktopBridgeError_InvalidConfig(message: var_message); + case 3: + var var_message = sse_decode_String(deserializer); + return RemoteDesktopBridgeError_WorkerSpawnFailed(message: var_message); + case 4: + var var_message = sse_decode_String(deserializer); + return RemoteDesktopBridgeError_Internal(message: var_message); + default: + throw UnimplementedError(''); + } + } + @protected RemoteDesktopConnectionState sse_decode_remote_desktop_connection_state( SseDeserializer deserializer, @@ -41947,6 +42048,30 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_bool(self.readOn, serializer); } + @protected + void sse_encode_mosh_bridge_error( + MoshBridgeError self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + switch (self) { + case MoshBridgeError_SessionClosed(): + sse_encode_i_32(0, serializer); + case MoshBridgeError_SendBufferFull(message: final message): + sse_encode_i_32(1, serializer); + sse_encode_String(message, serializer); + case MoshBridgeError_HandshakeTimeout(message: final message): + sse_encode_i_32(2, serializer); + sse_encode_String(message, serializer); + case MoshBridgeError_InvalidConfig(message: final message): + sse_encode_i_32(3, serializer); + sse_encode_String(message, serializer); + case MoshBridgeError_Other(message: final message): + sse_encode_i_32(4, serializer); + sse_encode_String(message, serializer); + } + } + @protected void sse_encode_mosh_bridge_event( MoshBridgeEvent self, @@ -43744,6 +43869,29 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_opt_String(self.why, serializer); } + @protected + void sse_encode_remote_desktop_bridge_error( + RemoteDesktopBridgeError self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + switch (self) { + case RemoteDesktopBridgeError_SessionClosed(): + sse_encode_i_32(0, serializer); + case RemoteDesktopBridgeError_QueueFull(): + sse_encode_i_32(1, serializer); + case RemoteDesktopBridgeError_InvalidConfig(message: final message): + sse_encode_i_32(2, serializer); + sse_encode_String(message, serializer); + case RemoteDesktopBridgeError_WorkerSpawnFailed(message: final message): + sse_encode_i_32(3, serializer); + sse_encode_String(message, serializer); + case RemoteDesktopBridgeError_Internal(message: final message): + sse_encode_i_32(4, serializer); + sse_encode_String(message, serializer); + } + } + @protected void sse_encode_remote_desktop_connection_state( RemoteDesktopConnectionState self, diff --git a/lib/src/rust/frb_generated.io.dart b/lib/src/rust/frb_generated.io.dart index 6c85ea3fdb..aec0c67ea8 100644 --- a/lib/src/rust/frb_generated.io.dart +++ b/lib/src/rust/frb_generated.io.dart @@ -1596,6 +1596,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected MonitorReleasePage dco_decode_monitor_release_page(dynamic raw); + @protected + MoshBridgeError dco_decode_mosh_bridge_error(dynamic raw); + @protected MoshBridgeEvent dco_decode_mosh_bridge_event(dynamic raw); @@ -2069,6 +2072,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected Refusal dco_decode_refusal(dynamic raw); + @protected + RemoteDesktopBridgeError dco_decode_remote_desktop_bridge_error(dynamic raw); + @protected RemoteDesktopConnectionState dco_decode_remote_desktop_connection_state( dynamic raw, @@ -4252,6 +4258,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseDeserializer deserializer, ); + @protected + MoshBridgeError sse_decode_mosh_bridge_error(SseDeserializer deserializer); + @protected MoshBridgeEvent sse_decode_mosh_bridge_event(SseDeserializer deserializer); @@ -4833,6 +4842,11 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected Refusal sse_decode_refusal(SseDeserializer deserializer); + @protected + RemoteDesktopBridgeError sse_decode_remote_desktop_bridge_error( + SseDeserializer deserializer, + ); + @protected RemoteDesktopConnectionState sse_decode_remote_desktop_connection_state( SseDeserializer deserializer, @@ -7523,6 +7537,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); + @protected + void sse_encode_mosh_bridge_error( + MoshBridgeError self, + SseSerializer serializer, + ); + @protected void sse_encode_mosh_bridge_event( MoshBridgeEvent self, @@ -8279,6 +8299,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_refusal(Refusal self, SseSerializer serializer); + @protected + void sse_encode_remote_desktop_bridge_error( + RemoteDesktopBridgeError self, + SseSerializer serializer, + ); + @protected void sse_encode_remote_desktop_connection_state( RemoteDesktopConnectionState self, diff --git a/lib/src/rust/frb_generated.web.dart b/lib/src/rust/frb_generated.web.dart index 5caaca4869..7d5febafa6 100644 --- a/lib/src/rust/frb_generated.web.dart +++ b/lib/src/rust/frb_generated.web.dart @@ -1598,6 +1598,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected MonitorReleasePage dco_decode_monitor_release_page(dynamic raw); + @protected + MoshBridgeError dco_decode_mosh_bridge_error(dynamic raw); + @protected MoshBridgeEvent dco_decode_mosh_bridge_event(dynamic raw); @@ -2071,6 +2074,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected Refusal dco_decode_refusal(dynamic raw); + @protected + RemoteDesktopBridgeError dco_decode_remote_desktop_bridge_error(dynamic raw); + @protected RemoteDesktopConnectionState dco_decode_remote_desktop_connection_state( dynamic raw, @@ -4254,6 +4260,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseDeserializer deserializer, ); + @protected + MoshBridgeError sse_decode_mosh_bridge_error(SseDeserializer deserializer); + @protected MoshBridgeEvent sse_decode_mosh_bridge_event(SseDeserializer deserializer); @@ -4835,6 +4844,11 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected Refusal sse_decode_refusal(SseDeserializer deserializer); + @protected + RemoteDesktopBridgeError sse_decode_remote_desktop_bridge_error( + SseDeserializer deserializer, + ); + @protected RemoteDesktopConnectionState sse_decode_remote_desktop_connection_state( SseDeserializer deserializer, @@ -7525,6 +7539,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); + @protected + void sse_encode_mosh_bridge_error( + MoshBridgeError self, + SseSerializer serializer, + ); + @protected void sse_encode_mosh_bridge_event( MoshBridgeEvent self, @@ -8281,6 +8301,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_refusal(Refusal self, SseSerializer serializer); + @protected + void sse_encode_remote_desktop_bridge_error( + RemoteDesktopBridgeError self, + SseSerializer serializer, + ); + @protected void sse_encode_remote_desktop_connection_state( RemoteDesktopConnectionState self, diff --git a/test/e2e/mosh_real_test.dart b/test/e2e/mosh_real_test.dart index f9c2336b96..22a81274c5 100644 --- a/test/e2e/mosh_real_test.dart +++ b/test/e2e/mosh_real_test.dart @@ -368,12 +368,7 @@ Subsystem sftp internal-sftp predictionMode: mosh_ffi.MoshPredictionMode.adaptive, handshakeTimeoutMs: 700, ), - throwsA( - predicate( - (e) => e.toString().toLowerCase().contains('timed out'), - 'contains timed out', - ), - ), + throwsA(isA()), ); sw.stop(); expect(sw.elapsedMilliseconds, lessThan(4000)); diff --git a/test/unit/remote_desktop/remote_desktop_sessions_test.dart b/test/unit/remote_desktop/remote_desktop_sessions_test.dart index f5712f9de7..afbce2095e 100644 --- a/test/unit/remote_desktop/remote_desktop_sessions_test.dart +++ b/test/unit/remote_desktop/remote_desktop_sessions_test.dart @@ -1,6 +1,7 @@ import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; +import 'package:server_box/data/model/app/error.dart'; import 'package:server_box/data/model/server/remote_desktop.dart'; import 'package:server_box/data/provider/remote_desktop.dart'; import 'package:server_box/src/rust/api/remote_desktop.dart' as ffi; @@ -109,4 +110,50 @@ void main() { expect(unnamed.failure, isNull); expect(ended.copyWith(clearEndReason: true).failure, isNull); }); + + test('classifyConnectError stops auto-retry on typed InvalidConfig errors', () { + final invalid = RemoteDesktopSessions.classifyConnectError( + const ffi.RemoteDesktopBridgeError.invalidConfig( + message: 'RDP username is empty', + ), + ); + expect(invalid.reason, ffi.RemoteDesktopEndReason.configurationError); + expect(invalid.message, 'RDP username is empty'); + expect(invalid.retryable, isFalse); + + final spawnFailed = RemoteDesktopSessions.classifyConnectError( + const ffi.RemoteDesktopBridgeError.workerSpawnFailed( + message: 'thread spawn failed', + ), + ); + expect(spawnFailed.reason, ffi.RemoteDesktopEndReason.transportError); + expect(spawnFailed.message, 'thread spawn failed'); + expect(spawnFailed.retryable, isTrue); + + final closed = RemoteDesktopSessions.classifyConnectError( + const ffi.RemoteDesktopBridgeError.sessionClosed(), + ); + expect(closed.reason, ffi.RemoteDesktopEndReason.transportError); + expect(closed.retryable, isTrue); + + final queueFull = RemoteDesktopSessions.classifyConnectError( + const ffi.RemoteDesktopBridgeError.queueFull(), + ); + expect(queueFull.reason, ffi.RemoteDesktopEndReason.transportError); + expect(queueFull.retryable, isTrue); + + final internal = RemoteDesktopSessions.classifyConnectError( + const ffi.RemoteDesktopBridgeError.internal( + message: 'remote desktop command queue lock poisoned', + ), + ); + expect(internal.reason, ffi.RemoteDesktopEndReason.transportError); + expect(internal.message, 'remote desktop command queue lock poisoned'); + expect(internal.retryable, isTrue); + + final nonRetryableSsh = RemoteDesktopSessions.classifyConnectError( + const SSHErr(type: SSHErrType.connect, message: 'config error'), + ); + expect(nonRetryableSsh.retryable, isFalse); + }); } diff --git a/test/unit/server/connection_result_test.dart b/test/unit/server/connection_result_test.dart index 97bae40a94..21bb90b2bd 100644 --- a/test/unit/server/connection_result_test.dart +++ b/test/unit/server/connection_result_test.dart @@ -1,7 +1,11 @@ import 'dart:async'; import 'dart:io'; +import 'package:dartssh2/dartssh2.dart'; +import 'package:dio/dio.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:server_box/core/ssh/mosh.dart'; +import 'package:server_box/data/model/app/error.dart'; import 'package:server_box/data/model/server/connection_stat.dart'; void main() { @@ -19,4 +23,111 @@ void main() { expect(ConnectionResult.fromError(Exception('Permission denied (publickey)')), ConnectionResult.authFailed); expect(ConnectionResult.fromError(StateError('odd')), ConnectionResult.unknownError); }); + + test('typed exceptions are classified before text fallbacks', () { + // Regression: hostname containing "auth" must not be misclassified as authFailed. + expect( + ConnectionResult.fromError( + const SocketException("Failed host lookup: 'auth.example.com'"), + ), + ConnectionResult.networkError, + ); + expect( + ConnectionResult.fromError( + SSHErr( + type: SSHErrType.connect, + cause: const SocketException("Failed host lookup: 'auth.example.com'"), + ), + ), + ConnectionResult.networkError, + ); + expect( + ConnectionResult.fromError( + const SSHErr(type: SSHErrType.auth, message: 'bad key'), + ), + ConnectionResult.authFailed, + ); + expect( + ConnectionResult.fromError( + SSHAuthAbortError( + 'aborted', + SSHHandshakeError("Connection reset by peer 'auth.example.com'"), + ), + ), + ConnectionResult.networkError, + ); + expect( + ConnectionResult.fromError( + const MonitorHttpErr(type: MonitorHttpErrType.net, message: 'auth host'), + ), + ConnectionResult.networkError, + ); + expect( + ConnectionResult.fromError( + const MonitorHttpErr(type: MonitorHttpErrType.auth, message: 'denied'), + ), + ConnectionResult.authFailed, + ); + expect( + ConnectionResult.fromError( + const MoshException(MoshErrType.udpTimeout, 'udp timeout'), + ), + ConnectionResult.timeout, + ); + expect( + ConnectionResult.fromError( + DioException( + requestOptions: RequestOptions(path: '/health'), + type: DioExceptionType.connectionTimeout, + ), + ), + ConnectionResult.timeout, + ); + expect( + ConnectionResult.fromError( + const SocketException( + 'Connection failed', + osError: OSError('Operation timed out', 60), + ), + ), + ConnectionResult.timeout, + ); + expect( + ConnectionResult.fromError(SSHHandshakeError('Handshake timed out')), + ConnectionResult.timeout, + ); + expect( + ConnectionResult.fromError(SSHAuthAbortError('Authentication timed out')), + ConnectionResult.timeout, + ); + expect( + ConnectionResult.fromError( + SSHSocketError(TimeoutException('socket timeout')), + ), + ConnectionResult.timeout, + ); + expect( + ConnectionResult.fromError( + DioException( + requestOptions: RequestOptions(path: '/health'), + type: DioExceptionType.badResponse, + response: Response( + requestOptions: RequestOptions(path: '/health'), + statusCode: 401, + ), + ), + ), + ConnectionResult.authFailed, + ); + expect( + ConnectionResult.fromError( + DioException( + requestOptions: RequestOptions(path: '/health'), + type: DioExceptionType.unknown, + error: const SocketException("Failed host lookup: 'auth.example.com'"), + ), + ), + ConnectionResult.networkError, + ); + }); } diff --git a/test/unit/ssh/iul_proxy_socket_test.dart b/test/unit/ssh/iul_proxy_socket_test.dart index e89ae5dd0b..7129bb24c8 100644 --- a/test/unit/ssh/iul_proxy_socket_test.dart +++ b/test/unit/ssh/iul_proxy_socket_test.dart @@ -3,7 +3,9 @@ import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; +import 'package:dartssh2/dartssh2.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:server_box/core/ssh/client.dart'; import 'package:server_box/core/ssh/iul_proxy_socket.dart'; import 'package:server_box/data/model/app/error.dart'; @@ -307,5 +309,108 @@ void main() { expect(flushDuringFinish, isNotNull); await flushDuringFinish!; }); + + test('auth failure stderr before readiness is non-retryable and does not fail over', () async { + final dir = await Directory.systemTemp.createTemp('iul_proxy_auth_pre_'); + addTearDown(() => dir.delete(recursive: true)); + final errFile = File('${dir.path}/proxy.err'); + await errFile.writeAsString('Permission denied (publickey).\n'); + + var closed = false; + final socket = IulProxySocket.forTesting( + errFile: errFile, + read: (_, {Duration timeout = Duration.zero}) => null, + tryWrite: (_, bytes) => bytes.length, + exitCode: (_) => closed ? 255 : null, + closeSession: (_) => closed = true, + ); + + Object? caught; + try { + await socket.ready; + } catch (e) { + caught = e; + } + expect(caught, isA()); + final sshErr = caught! as SSHErr; + expect(sshErr.type, SSHErrType.auth); + expect(sshErr.retryable, isFalse); + expect(isJumpFailoverError(sshErr), isFalse); + }); + + test('auth failure stderr after readiness is non-retryable and does not fail over', () async { + final dir = await Directory.systemTemp.createTemp('iul_proxy_auth_post_'); + addTearDown(() => dir.delete(recursive: true)); + final errFile = File('${dir.path}/proxy.err'); + await errFile.writeAsString('Authentication failed\n'); + + var call = 0; + var closed = false; + final socket = IulProxySocket.forTesting( + errFile: errFile, + read: (_, {Duration timeout = Duration.zero}) { + call++; + if (call == 1) { + return Uint8List.fromList(utf8.encode(IulProxySocket.readyMarker)); + } + return null; + }, + tryWrite: (_, bytes) => bytes.length, + exitCode: (_) => closed ? 255 : null, + closeSession: (_) => closed = true, + ); + + final streamErr = Completer(); + socket.stream.listen( + (_) {}, + onError: (Object error) { + if (!streamErr.isCompleted) streamErr.complete(error); + }, + ); + await socket.ready; + final err = await streamErr.future; + expect(err, isA()); + final sshErr = err as SSHErr; + expect(sshErr.type, SSHErrType.auth); + expect(sshErr.retryable, isFalse); + expect(isJumpFailoverError(sshErr), isFalse); + expect( + isJumpFailoverError( + SSHAuthAbortError('aborted', SSHSocketError(sshErr)), + ), + isFalse, + ); + await socket.done; + }); + + test('hostname containing auth in ProxyCommand stderr remains retryable transport error', () async { + final dir = await Directory.systemTemp.createTemp('iul_proxy_host_auth_'); + addTearDown(() => dir.delete(recursive: true)); + final errFile = File('${dir.path}/proxy.err'); + await errFile.writeAsString( + 'ssh: Could not resolve hostname auth.bastion.example: Name or service not known\n', + ); + + var closed = false; + final socket = IulProxySocket.forTesting( + errFile: errFile, + read: (_, {Duration timeout = Duration.zero}) => null, + tryWrite: (_, bytes) => bytes.length, + exitCode: (_) => closed ? 255 : null, + closeSession: (_) => closed = true, + ); + + Object? caught; + try { + await socket.ready; + } catch (e) { + caught = e; + } + expect(caught, isA()); + final sshErr = caught! as SSHErr; + expect(sshErr.type, SSHErrType.connect); + expect(sshErr.retryable, isTrue); + expect(isJumpFailoverError(sshErr), isTrue); + }); }); } diff --git a/test/unit/ssh/jump_failover_test.dart b/test/unit/ssh/jump_failover_test.dart index 0a7eb57d7f..b83b44743d 100644 --- a/test/unit/ssh/jump_failover_test.dart +++ b/test/unit/ssh/jump_failover_test.dart @@ -1,3 +1,6 @@ +import 'dart:async'; +import 'dart:io'; + import 'package:dartssh2/dartssh2.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:server_box/core/ssh/client.dart'; @@ -6,14 +9,35 @@ import 'package:server_box/data/model/app/error.dart'; void main() { group('Jump failover errors', () { test('network and non-auth proxy CONNECT errors can fail over', () { - expect(isJumpFailoverError('Connection refused'), isTrue); - expect(isJumpFailoverError('SocketException: timed out'), isTrue); - expect(isJumpFailoverError('forwardLocal failed'), isTrue); + expect( + isJumpFailoverError(const SocketException('Connection refused')), + isTrue, + ); + expect(isJumpFailoverError(TimeoutException('timed out')), isTrue); + expect( + isJumpFailoverError(SSHChannelOpenError(2, 'forwardLocal failed')), + isTrue, + ); + expect( + isJumpFailoverError(SSHKeepAliveError('keep-alive failed')), + isTrue, + ); + expect( + isJumpFailoverError( + SSHStateError('Connection closed while waiting for channel open'), + ), + isTrue, + ); + expect( + isJumpFailoverError(const ProcessException('ssh', [])), + isTrue, + ); expect( isJumpFailoverError( SSHErr( type: SSHErrType.connect, message: 'HTTP proxy CONNECT failed: HTTP/1.1 502 Bad Gateway', + retryable: true, ), ), isTrue, @@ -24,6 +48,7 @@ void main() { type: SSHErrType.connect, message: 'HTTP proxy CONNECT failed: HTTP/1.1 503 Non-Authoritative Service Unavailable', + retryable: true, ), ), isTrue, @@ -33,6 +58,7 @@ void main() { SSHErr( type: SSHErrType.connect, message: 'HTTP proxy CONNECT failed: HTTP/1.1 500 Bad Authority', + retryable: true, ), ), isTrue, @@ -42,6 +68,7 @@ void main() { SSHErr( type: SSHErrType.connect, message: 'HTTP proxy CONNECT failed: HTTP/1.1 400 Invalid Authority', + retryable: true, ), ), isTrue, @@ -51,6 +78,7 @@ void main() { SSHErr( type: SSHErrType.connect, message: 'SOCKS5 CONNECT failed: host unreachable', + retryable: true, ), ), isTrue, @@ -60,6 +88,7 @@ void main() { SSHErr( type: SSHErrType.connect, message: 'SOCKS5 CONNECT failed: connection refused', + retryable: true, ), ), isTrue, @@ -69,6 +98,7 @@ void main() { SSHErr( type: SSHErrType.connect, message: 'SSH proxy not found for bastion: p-missing', + retryable: true, ), ), isTrue, @@ -78,18 +108,46 @@ void main() { SSHErr( type: SSHErrType.connect, message: 'SSH proxy not found for auth-bastion: p-missing', + retryable: true, + ), + ), + isTrue, + ); + // Typed transport errors must still fail over even when the hostname + // contains "auth" (regression against _authFailurePattern false positive). + expect( + isJumpFailoverError( + const SocketException("Failed host lookup: 'auth.example.com'"), + ), + isTrue, + ); + expect( + isJumpFailoverError( + TimeoutException('Timed out connecting to auth.example.com'), + ), + isTrue, + ); + expect( + isJumpFailoverError(SSHChannelOpenError(2, 'connect failed')), + isTrue, + ); + expect( + isJumpFailoverError( + SSHAuthAbortError( + 'aborted', + SSHHandshakeError('Invalid version: Not allowed at this time'), ), ), isTrue, ); }); - test('auth and host key errors do not fail over', () { + test('auth, host key, untyped, and non-retryable config errors do not fail over', () { + expect(isJumpFailoverError('Connection refused'), isFalse); expect(isJumpFailoverError('Authentication failed'), isFalse); expect(isJumpFailoverError('Too many authentication failures'), isFalse); - expect(isJumpFailoverError('User rejected new SSH host key'), isFalse); - expect(isJumpFailoverError('Permission denied'), isFalse); - expect(isJumpFailoverError('Access denied'), isFalse); + expect(isJumpFailoverError(SSHHostkeyError('host key rejected')), isFalse); + expect(isJumpFailoverError(Exception('Permission denied')), isFalse); expect( isJumpFailoverError( SSHErr( @@ -102,7 +160,7 @@ void main() { expect( isJumpFailoverError( SSHErr( - type: SSHErrType.connect, + type: SSHErrType.auth, message: 'HTTP proxy CONNECT failed: HTTP/1.1 401 Unauthorized', ), ), @@ -111,8 +169,8 @@ void main() { expect( isJumpFailoverError( SSHErr( - type: SSHErrType.connect, - message: 'HTTP proxy CONNECT failed: HTTP/1.1 401', + type: SSHErrType.auth, + message: 'HTTP proxy CONNECT failed: HTTP/1.1 403 Forbidden', ), ), isFalse, @@ -120,17 +178,27 @@ void main() { expect( isJumpFailoverError( SSHErr( + type: SSHErrType.auth, + message: 'SOCKS5 CONNECT failed: connection not allowed by ruleset', + ), + ), + isFalse, + ); + // Permanent SSHErrType.connect errors default to retryable: false. + expect( + isJumpFailoverError( + const SSHErr( type: SSHErrType.connect, - message: 'HTTP proxy CONNECT failed: HTTP/1.1 403', + message: 'Reconnect limit reached for prod', ), ), isFalse, ); expect( isJumpFailoverError( - SSHErr( + const SSHErr( type: SSHErrType.connect, - message: 'HTTP proxy CONNECT failed: HTTP/1.1 407', + message: 'Invalid jump chain: cycle detected', ), ), isFalse, @@ -139,7 +207,8 @@ void main() { isJumpFailoverError( SSHErr( type: SSHErrType.connect, - message: 'SOCKS5 CONNECT failed: connection not allowed by ruleset', + message: 'wrapped auth failure', + cause: SSHAuthFailError('bad key'), ), ), isFalse, @@ -149,7 +218,7 @@ void main() { }); group('isProxyDenialError', () { - test('classifies proxy auth, SOCKS5 ruleset, and HTTP 401/403/407 denials', () { + test('classifies SSHErrType.auth as proxy denial', () { expect( isProxyDenialError( SSHErr( @@ -162,31 +231,21 @@ void main() { expect( isProxyDenialError( SSHErr( - type: SSHErrType.connect, + type: SSHErrType.auth, message: 'SOCKS5 CONNECT failed: connection not allowed by ruleset', ), ), isTrue, ); - for (final status in const [ - 'HTTP/1.1 401 Unauthorized', - 'HTTP/1.1 401', - 'HTTP/1.1 403 Forbidden', - 'HTTP/1.1 403', - 'HTTP/1.1 407 Proxy Authentication Required', - 'HTTP/1.1 407', - ]) { - expect( - isProxyDenialError( - SSHErr( - type: SSHErrType.connect, - message: 'HTTP proxy CONNECT failed: $status', - ), - ), - isTrue, - reason: status, - ); - } + expect( + isProxyDenialError( + SSHErr( + type: SSHErrType.auth, + message: 'HTTP proxy CONNECT failed: HTTP/1.1 403 Forbidden', + ), + ), + isTrue, + ); }); test('does not classify 5xx, 400, network, or missing-proxy errors as denials', () { @@ -222,4 +281,36 @@ void main() { } }); }); + + group('isAuthFailureMessage', () { + test('matches explicit authentication failure statements', () { + for (final msg in const [ + 'Permission denied (publickey).', + 'Authentication failed', + 'Too many authentication failures', + 'No more authentication methods to try', + 'Access denied', + 'HTTP/1.1 401 Unauthorized', + 'user is not authenticated', + 'Proxy authentication required', + 'cloudflared: failed to authenticate', + 'invalid credentials', + ]) { + expect(isAuthFailureMessage(msg), isTrue, reason: msg); + } + }); + + test('does not match isolated auth tokens in hostnames or non-auth text', () { + for (final msg in const [ + 'ssh: Could not resolve hostname auth.bastion.example: Name or service not known', + 'connect to host auth.example.com port 22: Connection refused', + 'nc: connect to auth-proxy.internal failed', + 'HTTP/1.1 503 Non-Authoritative Service Unavailable', + 'HTTP/1.1 500 Bad Authority', + 'authz.service.local: Connection timed out', + ]) { + expect(isAuthFailureMessage(msg), isFalse, reason: msg); + } + }); + }); } diff --git a/test/unit/ssh/mosh_test.dart b/test/unit/ssh/mosh_test.dart index 70ecb10ca3..855e8945ac 100644 --- a/test/unit/ssh/mosh_test.dart +++ b/test/unit/ssh/mosh_test.dart @@ -1,7 +1,79 @@ +import 'dart:async'; + import 'package:flutter_test/flutter_test.dart'; import 'package:server_box/core/ssh/mosh.dart'; import 'package:server_box/data/model/server/ssh_credential.dart'; import 'package:server_box/data/terminal/terminal_session.dart'; +import 'package:server_box/src/rust/api/mosh.dart' as mosh_ffi; + +class _FakeMoshBridgeSession implements mosh_ffi.MoshBridgeSession { + final _events = StreamController(); + late final StreamIterator _eventIter = + StreamIterator(_events.stream); + + Object? writeError; + Object? controlError; + bool _disposed = false; + bool closed = false; + + void emitEvent(mosh_ffi.MoshBridgeEvent? event) { + if (!_events.isClosed) _events.add(event); + } + + @override + Future nextEvent() async { + if (await _eventIter.moveNext()) { + return _eventIter.current; + } + return null; + } + + @override + void write({required List data}) { + if (writeError != null) throw writeError!; + } + + @override + void resize({required int cols, required int rows}) { + if (controlError != null) throw controlError!; + } + + @override + void syncCursor({ + required int row, + required int col, + required int cols, + required int rows, + required bool inAltScreen, + }) { + if (controlError != null) throw controlError!; + } + + @override + void setPredictionMode({required mosh_ffi.MoshPredictionMode mode}) { + if (controlError != null) throw controlError!; + } + + @override + void rebind() { + if (controlError != null) throw controlError!; + } + + @override + void close() { + closed = true; + if (!_events.isClosed) _events.close(); + } + + @override + void dispose() { + _disposed = true; + if (!_events.isClosed) _events.close(); + } + + @override + bool get isDisposed => _disposed; +} void main() { group('SshCredential Mosh fields', () { @@ -152,4 +224,205 @@ void main() { expect(const MoshLinkStatus(connected: false, lastContactMs: 0).isStale, isTrue); }); }); + + group('Typed MoshBridgeError classification', () { + test('classifyMoshWriteError maps variants without matching strings', () { + expect( + classifyMoshWriteError(const mosh_ffi.MoshBridgeError.sessionClosed()), + isNull, + ); + + final full = classifyMoshWriteError( + const mosh_ffi.MoshBridgeError.sendBufferFull( + message: 'limit hit MOSH CONNECT 60001 secretkey', + ), + ); + expect(full, isNotNull); + expect(full!.type, MoshErrType.sendBufferFull); + expect(full.message, 'limit hit MOSH CONNECT [REDACTED]'); + + final timeout = classifyMoshWriteError( + const mosh_ffi.MoshBridgeError.handshakeTimeout(message: 'timeout'), + ); + expect(timeout!.type, MoshErrType.udpTimeout); + + final invalid = classifyMoshWriteError( + const mosh_ffi.MoshBridgeError.invalidConfig(message: 'bad key'), + ); + expect(invalid!.type, MoshErrType.invalidConfig); + + // Variant drives classification even when the message mentions keywords + // that old string-matching logic used to inspect. + final other = classifyMoshWriteError( + const mosh_ffi.MoshBridgeError.other( + message: 'session closed / send buffer limit', + ), + ); + expect(other!.type, MoshErrType.connectFailed); + expect(other.message, 'session closed / send buffer limit'); + }); + + test('classifyMoshConnectError maps variants and port hints', () { + final timeoutDefault = classifyMoshConnectError( + const mosh_ffi.MoshBridgeError.handshakeTimeout(message: 'timed out'), + targetHost: '203.0.113.5', + port: 60001, + ); + expect(timeoutDefault.type, MoshErrType.udpTimeout); + expect(timeoutDefault.message, contains('203.0.113.5:60001')); + expect(timeoutDefault.message, contains('60000-61000')); + + final timeoutCustom = classifyMoshConnectError( + const mosh_ffi.MoshBridgeError.handshakeTimeout(message: 'timed out'), + targetHost: '203.0.113.5', + port: 60005, + moshPort: ' 60000:60010 ', + ); + expect(timeoutCustom.type, MoshErrType.udpTimeout); + expect(timeoutCustom.message, contains('60000:60010')); + + final timeoutBlankPort = classifyMoshConnectError( + const mosh_ffi.MoshBridgeError.handshakeTimeout(message: 'timed out'), + targetHost: '203.0.113.5', + port: 60005, + moshPort: ' ', + ); + expect(timeoutBlankPort.message, contains('60000-61000')); + + // DNS lookup timeout arrives as `Other` and must not be misclassified as + // a UDP firewall timeout. + final dnsTimeout = classifyMoshConnectError( + const mosh_ffi.MoshBridgeError.other( + message: "timed out resolving Mosh host 'example.invalid'", + ), + targetHost: 'example.invalid', + port: 60001, + ); + expect(dnsTimeout.type, MoshErrType.connectFailed); + + final invalid = classifyMoshConnectError( + const mosh_ffi.MoshBridgeError.invalidConfig( + message: 'bad MOSH CONNECT 60001 secretkey', + ), + targetHost: '203.0.113.5', + port: 60001, + ); + expect(invalid.type, MoshErrType.invalidConfig); + expect(invalid.message, 'bad MOSH CONNECT [REDACTED]'); + + final closed = classifyMoshConnectError( + const mosh_ffi.MoshBridgeError.sessionClosed(), + targetHost: '203.0.113.5', + port: 60001, + ); + expect(closed.type, MoshErrType.connectFailed); + }); + + test('classifyMoshBuildCommandError only maps InvalidConfig as invalidConfig', () { + final invalid = classifyMoshBuildCommandError( + const mosh_ffi.MoshBridgeError.invalidConfig( + message: 'invalid bootstrap option: unsafe binary', + ), + ); + expect(invalid.type, MoshErrType.invalidConfig); + expect(invalid.message, 'invalid bootstrap option: unsafe binary'); + + final other = classifyMoshBuildCommandError( + const mosh_ffi.MoshBridgeError.other(message: 'unexpected failure'), + ); + expect(other.type, MoshErrType.connectFailed); + expect(other.message, 'unexpected failure'); + }); + }); + + group('MoshShellSession typed write error handling', () { + test( + 'silently drops write racing with SessionClosed while preserving later Closed error', + () async { + final bridge = _FakeMoshBridgeSession() + ..writeError = const mosh_ffi.MoshBridgeError.sessionClosed() + ..controlError = const mosh_ffi.MoshBridgeError.sessionClosed(); + final session = MoshShellSession(bridge); + final reported = []; + session.onWriteError = reported.add; + + // Before the Closed event is drained, write/control calls hit + // SessionClosed and must not throw or notify onWriteError. + expect(() => session.write([0x61]), returnsNormally); + expect(() => session.resizeTerminal(80, 24), returnsNormally); + expect( + () => session.syncCursor( + row: 0, + col: 0, + cols: 80, + rows: 24, + inAltScreen: false, + ), + returnsNormally, + ); + expect( + () => session.setPredictionMode(MoshPrediction.never), + returnsNormally, + ); + expect(() => session.rebind(), returnsNormally); + expect(reported, isEmpty); + + // Real transport error still propagates through the Closed event. + bridge.emitEvent( + const mosh_ffi.MoshBridgeEvent.closed( + remoteExit: false, + error: 'udp fatal', + ), + ); + await session.done; + expect(session.isClosed, isTrue); + expect(session.closeReason, MoshCloseReason.error); + }, + ); + + test('surfaces SendBufferFull and Other errors via callback and throw', () async { + final bridge = _FakeMoshBridgeSession() + ..writeError = const mosh_ffi.MoshBridgeError.sendBufferFull( + message: 'unacknowledged send buffer limit exceeded', + ); + final session = MoshShellSession(bridge); + final reported = []; + session.onWriteError = reported.add; + + expect( + () => session.write([0x61]), + throwsA( + isA().having( + (e) => e.type, + 'type', + MoshErrType.sendBufferFull, + ), + ), + ); + expect(reported, hasLength(1)); + expect(reported.single.type, MoshErrType.sendBufferFull); + + bridge.writeError = const mosh_ffi.MoshBridgeError.other( + message: 'session closed text in other error', + ); + expect( + () => session.write([0x62]), + throwsA( + isA().having( + (e) => e.type, + 'type', + MoshErrType.connectFailed, + ), + ), + ); + expect(reported, hasLength(2)); + expect(reported.last.type, MoshErrType.connectFailed); + + bridge.emitEvent( + const mosh_ffi.MoshBridgeEvent.closed(remoteExit: true), + ); + await session.done; + expect(session.closeReason, MoshCloseReason.remoteExit); + }); + }); } diff --git a/test/unit/ssh/proxy_socket_test.dart b/test/unit/ssh/proxy_socket_test.dart index 017500a2f6..d7e0e54b88 100644 --- a/test/unit/ssh/proxy_socket_test.dart +++ b/test/unit/ssh/proxy_socket_test.dart @@ -878,5 +878,71 @@ void main() { ); }, ); + + test('maps HTTP 401/403 and SOCKS5 ruleset denial (0x02) to SSHErrType.auth', () async { + final httpServer = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + addTearDown(httpServer.close); + final statuses = ['HTTP/1.1 401 Unauthorized', 'HTTP/1.1 403 Forbidden']; + var httpIdx = 0; + final httpSub = httpServer.listen((client) async { + final head = SocketHead(client); + try { + await head.takeUntil(const [13, 10, 13, 10], maxBytes: 4096); + client.add(utf8.encode('${statuses[httpIdx++]}\r\n\r\n')); + await client.flush(); + } finally { + await head.cancel(); + client.destroy(); + } + }); + addTearDown(httpSub.cancel); + + final httpProxy = SshProxy( + id: 'p-http-deny', + name: 'http-deny', + type: SshProxyType.http, + host: InternetAddress.loopbackIPv4.address, + port: httpServer.port, + ); + for (final _ in statuses) { + await expectLater( + ProxySocket.connect(proxy: httpProxy, host: '10.0.0.1', port: 22), + throwsA(isA().having((e) => e.type, 'type', SSHErrType.auth)), + ); + } + + final socksServer = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + addTearDown(socksServer.close); + final socksSub = socksServer.listen((client) async { + final head = SocketHead(client); + try { + await head.take(3); + client.add(const [0x05, 0x00]); + await client.flush(); + final req = await head.take(4); + if (req[3] == 0x01) { + await head.take(6); + } + client.add(const [0x05, 0x02, 0x00, 0x01, 0, 0, 0, 0, 0, 0]); + await client.flush(); + } finally { + await head.cancel(); + client.destroy(); + } + }); + addTearDown(socksSub.cancel); + + final socksProxy = SshProxy( + id: 'p-s5-deny', + name: 's5-deny', + type: SshProxyType.socks5, + host: InternetAddress.loopbackIPv4.address, + port: socksServer.port, + ); + await expectLater( + ProxySocket.connect(proxy: socksProxy, host: '10.0.0.1', port: 22), + throwsA(isA().having((e) => e.type, 'type', SSHErrType.auth)), + ); + }); }); } diff --git a/test/unit/ssh/ssh_discovery_sources_test.dart b/test/unit/ssh/ssh_discovery_sources_test.dart index 9ff9ce598d..9e6bbe0491 100644 --- a/test/unit/ssh/ssh_discovery_sources_test.dart +++ b/test/unit/ssh/ssh_discovery_sources_test.dart @@ -1,4 +1,5 @@ import 'dart:convert'; +import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:server_box/core/ssh_discovery/cloudflare.dart'; @@ -169,4 +170,35 @@ void main() { ]); expect(hosts.last.detail, 'ProxyJump edge'); }); + + test('SshConfigDiscovery.isPermissionDeniedError uses PathAccessException and OS error codes', () { + expect( + SshConfigDiscovery.isPermissionDeniedError( + const PathAccessException('/Users/u/.ssh/config', OSError('denied', 13)), + isWindows: false, + ), + isTrue, + ); + expect( + SshConfigDiscovery.isPermissionDeniedError( + const FileSystemException('localized error', '/Users/u/.ssh/config', OSError('操作不被允许', 1)), + isWindows: false, + ), + isTrue, + ); + expect( + SshConfigDiscovery.isPermissionDeniedError( + const FileSystemException('denied', r'C:\.ssh\config', OSError('拒绝访问', 5)), + isWindows: true, + ), + isTrue, + ); + expect( + SshConfigDiscovery.isPermissionDeniedError( + const FileSystemException('not found', '/Users/u/.ssh/config', OSError('No such file', 2)), + isWindows: false, + ), + isFalse, + ); + }); } diff --git a/test/unit/ssh/ssh_shell_session_test.dart b/test/unit/ssh/ssh_shell_session_test.dart index 5ef2faed4a..4124558587 100644 --- a/test/unit/ssh/ssh_shell_session_test.dart +++ b/test/unit/ssh/ssh_shell_session_test.dart @@ -17,9 +17,29 @@ void main() { expect(() => session.resizeTerminal(-1, 24), throwsArgumentError); }); + + test('writing or closing a closed session does not throw', () { + final session = SshShellSession(_ClosedSession()); + + expect(() => session.write([0x61]), returnsNormally); + expect(() => session.close(), returnsNormally); + // Repeated writes/resizes after close are ignored without touching session. + expect(() => session.write([0x62]), returnsNormally); + expect(() => session.resizeTerminal(-1, 24), returnsNormally); + }); } final class _ClosedSession implements SSHSession { + @override + void write(data) { + throw StateError('Cannot add event after closing'); + } + + @override + void close() { + throw SSHStateError('Transport is closed'); + } + @override void resizeTerminal( int width, diff --git a/test/unit/terminal/tmux_command_executor_test.dart b/test/unit/terminal/tmux_command_executor_test.dart index 45e0df0c26..464a5966c1 100644 --- a/test/unit/terminal/tmux_command_executor_test.dart +++ b/test/unit/terminal/tmux_command_executor_test.dart @@ -80,5 +80,18 @@ void main() { ); expect(executor.isClosed, isTrue); }); + + test('synchronous write failure returns failed future without leaking pending entry', () async { + final executor = TmuxCommandExecutor( + writeCommand: (_) => throw StateError('transport closed'), + ); + executor.complete( + const TmuxControlCommandResult(lines: [], error: false), + ); + + final future = executor.run('send-keys'); + expect(executor.pendingCount, 0); + await expectLater(future, throwsA(isA())); + }); }); }