Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>` / `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<T, Max<N>>`, not `crate::api::json::Json<T, crate::api::json::Max<N>>`.
- 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.
Expand Down
127 changes: 101 additions & 26 deletions crates/sbm_ffi/src/api/mosh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -90,6 +91,44 @@ impl From<PredictionOverlay> 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<MoshError> 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 {
Expand Down Expand Up @@ -122,7 +161,7 @@ pub fn mosh_build_server_command(
bind_ssh_ip: bool,
colors: u16,
locale: Option<String>,
) -> Result<String, String> {
) -> Result<String, MoshBridgeError> {
let mut opts = BootstrapOptions::default();
if let Some(bin) = server_binary {
let trimmed = bin.trim();
Expand All @@ -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 <port> <key>` from `mosh-server` bootstrap output.
#[frb(sync)]
pub fn mosh_parse_connect(output: String) -> Result<Option<MoshConnectData>, String> {
let parsed = parse_mosh_connect(&output).map_err(|e| e.to_string())?;
pub fn mosh_parse_connect(output: String) -> Result<Option<MoshConnectData>, MoshBridgeError> {
let parsed = parse_mosh_connect(&output).map_err(MoshBridgeError::from)?;
Ok(parsed.map(|info| MoshConnectData {
port: info.port,
key: info.key.to_base64(),
Expand All @@ -175,9 +214,9 @@ impl MoshBridgeSession {
rows: u16,
prediction_mode: MoshPredictionMode,
handshake_timeout_ms: u32,
) -> Result<MoshBridgeSession, String> {
) -> Result<MoshBridgeSession, MoshBridgeError> {
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 {
Expand All @@ -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));
Expand All @@ -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,
Expand Down Expand Up @@ -242,16 +285,16 @@ impl MoshBridgeSession {

/// Sends raw terminal input bytes (synchronous, non-blocking).
#[frb(sync)]
pub fn write(&self, data: Vec<u8>) -> Result<(), String> {
self.writer.write(data).map_err(|e| e.to_string())
pub fn write(&self, data: Vec<u8>) -> 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.
Expand All @@ -263,7 +306,7 @@ impl MoshBridgeSession {
cols: u16,
rows: u16,
in_alt_screen: bool,
) -> Result<(), String> {
) -> Result<(), MoshBridgeError> {
self.writer
.sync_cursor(TerminalCursorState {
row,
Expand All @@ -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).
Expand All @@ -296,20 +339,24 @@ impl MoshBridgeSession {
}
}

async fn resolve_udp_addr(host: &str, port: u16) -> Result<SocketAddr, String> {
async fn resolve_udp_addr(host: &str, port: u16) -> Result<SocketAddr, MoshBridgeError> {
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::<IpAddr>() {
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)]
Expand All @@ -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 { .. }
));
}
}
Loading
Loading