diff --git a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/Link/SSHTuiConnection.swift b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/Link/SSHTuiConnection.swift index a15accdf2933..03c0dab317c7 100644 --- a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/Link/SSHTuiConnection.swift +++ b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/Link/SSHTuiConnection.swift @@ -55,10 +55,18 @@ public struct SSHTuiConnection: Sendable { "-o", "RemoteCommand=none", "-o", "RequestTTY=no"] if let port = configuration.port { arguments += ["-p", String(port)] } if let identity = configuration.identityFile { arguments += ["-i", identity] } - for option in configuration.sshOptions { arguments += ["-o", option] } + for option in sshOptions { arguments += ["-o", option] } return arguments } + /// The caller's options plus cmux's shared ControlMaster, as 0.64.25's + /// connection broker used for every connect. Snapshots drop control + /// options, so without this a restored carrier opens its own connection, + /// which batch mode can't log in on a password-only host. + private var sshOptions: [String] { + SSHConnectionSharingOptions().mergingDefaults(into: configuration.sshOptions) + } + /// The daemon owns the login shell and therefore keeps it alive when SSH disconnects. public var shellCommand: [String] { if let restored = configuration.restoredSSHSession, @@ -86,7 +94,7 @@ public struct SSHTuiConnection: Sendable { var sshArguments = ["-o", "BatchMode=yes", "-o", "RequestTTY=no", "-o", "RemoteCommand=none"] if let port = configuration.port { sshArguments += ["-p", String(port)] } if let identity = configuration.identityFile { sshArguments += ["-i", identity] } - for option in configuration.sshOptions { sshArguments += ["-o", option] } + for option in sshOptions { sshArguments += ["-o", option] } // The carrier is a headless exec channel that reconnects for its whole // lifetime. Batch mode turns a prompt it cannot answer into OpenSSH's // own failure. Interactive authentication and host-key prompts precede diff --git a/Packages/macOS/CmuxCloudTui/Sources/CmuxCloudTui/CloudTuiManualIOCommand.swift b/Packages/macOS/CmuxCloudTui/Sources/CmuxCloudTui/CloudTuiManualIOCommand.swift index 3ba3b1c1c21e..55d4beb03698 100644 --- a/Packages/macOS/CmuxCloudTui/Sources/CmuxCloudTui/CloudTuiManualIOCommand.swift +++ b/Packages/macOS/CmuxCloudTui/Sources/CmuxCloudTui/CloudTuiManualIOCommand.swift @@ -106,13 +106,15 @@ public struct CloudTuiManualIOCommand: Sendable { return command } - /// Writes raw input bytes to the remote PTY. + /// Writes raw input bytes to the remote PTY. Input asks for no reply, so a + /// relay can carry it as compact one-way input. public func input(surfaceID: UInt64, bytes: Data, requestID: UInt64 = 1) -> [String: Any] { [ "id": requestID, "cmd": "send", "surface": surfaceID, "bytes": bytes.base64EncodedString(), + "no_reply": true, ] } diff --git a/Packages/macOS/CmuxCloudTui/Sources/CmuxCloudTui/CloudTuiManualIOConnection.swift b/Packages/macOS/CmuxCloudTui/Sources/CmuxCloudTui/CloudTuiManualIOConnection.swift index 7ef3532f42c1..a45cf5d1a3dd 100644 --- a/Packages/macOS/CmuxCloudTui/Sources/CmuxCloudTui/CloudTuiManualIOConnection.swift +++ b/Packages/macOS/CmuxCloudTui/Sources/CmuxCloudTui/CloudTuiManualIOConnection.swift @@ -265,6 +265,9 @@ public final class CloudTuiManualIOConnection: @unchecked Sendable { pendingLineSearchOffset = 0 guard !line.isEmpty, let frame = deliversJSONMessages ? CloudTuiManualIOFrame.message(line) : CloudTuiManualIOFrameDecoder().decode(line) else { continue } + // Id zero is untracked input. A daemon that still answers it + // must not cost the consumer a turn ahead of the echo. + if case let .response(requestID, _, _, _, _, _, _) = frame, requestID == 0 { continue } let continuation = nextFrameContinuation nextFrameContinuation = nil suspendReadSourceLocked() diff --git a/Sources/Cloud/CloudTuiManualMirrorSession.swift b/Sources/Cloud/CloudTuiManualMirrorSession.swift index 2250b0887990..3059eeece9ba 100644 --- a/Sources/Cloud/CloudTuiManualMirrorSession.swift +++ b/Sources/Cloud/CloudTuiManualMirrorSession.swift @@ -430,6 +430,13 @@ final class CloudTuiManualMirrorSession { claimUnsupported = false sendClaimIfNeeded() } + /// Called for each explicit keystroke or paste in this pane. The pane the + /// user is typing in must be the authoritative geometry owner. An owner + /// already confirmed, or a server without claims, sends its keys alone. + func noteExplicitInput() { + guard (!geometryClaimed && !claimUnsupported) || geometryClaimBlockedByPeer else { return } + claimGeometry() + } /// Permanently tears down this view's attachment without closing the remote /// terminal. Closing the control socket is the cleanup fence for old /// servers; newer servers additionally retire the lease with the same close. diff --git a/Sources/Surfaces/CmuxTuiSurfaceProvider+ManualMirror.swift b/Sources/Surfaces/CmuxTuiSurfaceProvider+ManualMirror.swift index 42ff24e25a94..0c02575b6d5a 100644 --- a/Sources/Surfaces/CmuxTuiSurfaceProvider+ManualMirror.swift +++ b/Sources/Surfaces/CmuxTuiSurfaceProvider+ManualMirror.swift @@ -133,7 +133,7 @@ extension CmuxTuiSurfaceProvider { let existingExplicitInput = created.surface.onExplicitInput created.surface.onExplicitInput = { [weak session] in existingExplicitInput?() - session?.claimGeometry() + session?.noteExplicitInput() } manualMirrorSessions[created.panelID] = session session.reconnect(socketPath: connected.socketPath) diff --git a/Sources/Surfaces/Workspace+CloudManualMirror.swift b/Sources/Surfaces/Workspace+CloudManualMirror.swift index c4067c50f8d4..c1303e75e481 100644 --- a/Sources/Surfaces/Workspace+CloudManualMirror.swift +++ b/Sources/Surfaces/Workspace+CloudManualMirror.swift @@ -207,6 +207,8 @@ extension Workspace { ) throws -> UUID { let previousPane = bonsplitController.focusedPaneId let previousTab = previousPane.flatMap { bonsplitController.selectedTab(inPane: $0)?.id } + // Bonsplit moves focus into the new pane, so capture the source terminal first. + let previousHostedView = focusedTerminalInputTarget()?.panel.hostedView panels[panel.id] = panel panelTitles[panel.id] = Self.cloudManualMirrorTabTitle let tab = Bonsplit.Tab( @@ -238,7 +240,7 @@ extension Workspace { rememberTerminalConfigInheritanceSource(panel) panel.surface.flushPendingManualSizeReportIfAttached() if focus { - focusPanel(panel.id) + focusNewSplitPanel(panel.id, previousHostedView: previousHostedView, reason: "workspace.cloudSplitReparent") } else if let previousPane { bonsplitController.focusPane(previousPane) if let previousTab { bonsplitController.selectTab(previousTab) } diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 8f19077cf1ba..2d8fa55404eb 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -9064,15 +9064,8 @@ final class Workspace: Identifiable, ObservableObject, FilePreviewTabMetadataHos ) #endif - // Suppress the old view's becomeFirstResponder side-effects during SwiftUI reparenting. - // Without this, reparenting triggers onFocus + ghostty_surface_set_focus on the old view, - // stealing focus from the new panel and creating model/surface divergence. if focus { - suppressReparentFocusUntilLayoutFollowUp( - previousHostedView, - reason: "workspace.terminalSplitReparent" - ) - focusPanel(newPanel.id, previousHostedView: previousHostedView) + focusNewSplitPanel(newPanel.id, previousHostedView: previousHostedView, reason: "workspace.terminalSplitReparent") } else { preserveFocusAfterNonFocusSplit( preferredPanelId: previousFocusedPanelId, @@ -11431,6 +11424,16 @@ final class Workspace: Identifiable, ObservableObject, FilePreviewTabMetadataHos } // MARK: - Focus Management + /// Focuses a panel a split just created. `previousHostedView` is the terminal that + /// had focus before Bonsplit moved it. SwiftUI reparents that view into the new + /// split, which would trigger onFocus + ghostty_surface_set_focus on it and steal + /// focus back from the new panel, so its becomeFirstResponder side effects stay + /// suppressed until the layout follow-up. + func focusNewSplitPanel(_ panelId: UUID, previousHostedView: GhosttySurfaceScrollView?, reason: String) { + suppressReparentFocusUntilLayoutFollowUp(previousHostedView, reason: reason) + focusPanel(panelId, previousHostedView: previousHostedView) + } + func preserveFocusAfterNonFocusSplit( preferredPanelId: UUID?, splitPanelId: UUID, diff --git a/cmux-tui/Cargo.lock b/cmux-tui/Cargo.lock index 4d33064188aa..b85555f8d375 100644 --- a/cmux-tui/Cargo.lock +++ b/cmux-tui/Cargo.lock @@ -701,6 +701,7 @@ dependencies = [ "cmux-tui-source-watch", "cmux-wg", "diffy", + "flate2", "fs4", "futures-util", "getrandom 0.3.4", diff --git a/cmux-tui/crates/cmux-remote/Cargo.toml b/cmux-tui/crates/cmux-remote/Cargo.toml index b1b62155128b..ff13a90b0052 100644 --- a/cmux-tui/crates/cmux-remote/Cargo.toml +++ b/cmux-tui/crates/cmux-remote/Cargo.toml @@ -27,6 +27,7 @@ cmux-remote-protocol.workspace = true cmux-tui-core.workspace = true cmux-wg = { workspace = true, optional = true } diffy.workspace = true +flate2.workspace = true fs4.workspace = true futures-util.workspace = true getrandom.workspace = true diff --git a/cmux-tui/crates/cmux-remote/src/ssh_bootstrap.rs b/cmux-tui/crates/cmux-remote/src/ssh_bootstrap.rs index 0bd0c710f1c3..393e79e5ff3d 100644 --- a/cmux-tui/crates/cmux-remote/src/ssh_bootstrap.rs +++ b/cmux-tui/crates/cmux-remote/src/ssh_bootstrap.rs @@ -7,12 +7,17 @@ use std::sync::{Arc, Mutex as StdMutex, OnceLock, Weak}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use cmux_remote_protocol::REMOTE_PROTOCOL_VERSION; +use flate2::Compression; +use flate2::read::GzEncoder; use serde::{Deserialize, Serialize}; -use tokio::io::AsyncReadExt; -use tokio::process::{Child, Command}; -use tokio::sync::Mutex; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::process::{Child, ChildStdin, Command}; +use tokio::sync::{Mutex, mpsc}; const SSH_BOOTSTRAP_OUTPUT_LIMIT: usize = 4_096; +/// Printed by the staging command when the remote can decompress an upload. +const GZIP_UPLOAD_MARKER: &str = "cmux-upload:gzip"; +const UPLOAD_CHUNK_BYTES: usize = 256 * 1024; // Cleanup must not turn a bounded bootstrap timeout into an unbounded wait. const SSH_BOOTSTRAP_REAP_TIMEOUT: Duration = Duration::from_secs(2); // A process-wide counter prevents concurrent unpublished uploads from @@ -278,9 +283,9 @@ impl SshBootstrapper { // allowed only after this command reports success, which proves that // this upload owns the staging directory. A failed or timed-out mkdir // is intentionally left untouched because ownership is unknown. - self.create_remote_staging(parent, &temporary_dir).await?; - let command = upload_command(parent, &temporary_dir, &temporary); - let output = match self.run_remote_with_input(&command, source).await { + let encoding = self.create_remote_staging(parent, &temporary_dir).await?; + let command = upload_command(&temporary, encoding); + let output = match self.run_remote_with_input(&command, source, encoding).await { Ok(output) => output, Err(error) => { self.cleanup_remote_staging(&temporary_dir, deadline).await; @@ -315,10 +320,13 @@ impl SshBootstrapper { protocol: probe.remote_protocol, }); } - let output = match self - .run_remote(["mv", "-f", "--", temporary.as_str(), self.config.remote_binary.as_str()]) - .await - { + // The move also removes the now-empty staging directory, so a + // successful install spends no extra round trip on cleanup. + let command = format!( + "mv -f -- {temporary} {} && {{ rmdir -- {temporary_dir} 2>/dev/null || true; }}", + self.config.remote_binary + ); + let output = match self.run_remote([command.as_str()]).await { Ok(output) => output, Err(error) => { self.cleanup_remote_staging(&temporary_dir, deadline).await; @@ -332,28 +340,18 @@ impl SshBootstrapper { stderr: sanitize(&String::from_utf8_lossy(&output.stderr)), }); } - let probe = match self.probe().await { - Ok(Some(probe)) => probe, - Ok(None) => { - self.cleanup_remote_staging(&temporary_dir, deadline).await; - return Err(BootstrapError::Install { - status: 0, - stderr: "upload completed but the remote binary is absent".into(), - }); - } - Err(error) => { - self.cleanup_remote_staging(&temporary_dir, deadline).await; - return Err(error); - } + let Some(probe) = self.probe().await? else { + return Err(BootstrapError::Install { + status: 0, + stderr: "upload completed but the remote binary is absent".into(), + }); }; if !self.compatible(&probe) { - self.cleanup_remote_staging(&temporary_dir, deadline).await; return Err(BootstrapError::Incompatible { version: probe.version, protocol: probe.remote_protocol, }); } - self.cleanup_remote_staging(&temporary_dir, deadline).await; Ok(BootstrapOutcome::Installed) } @@ -364,26 +362,30 @@ impl SshBootstrapper { format!("{}.cmux-upload-{}-{now}-{nonce}", self.config.remote_binary, std::process::id()) } + /// Creates the parent and the exclusive staging directory in one round + /// trip and reports whether the remote can decompress a gzip upload. The + /// status is zero only when this command created the staging directory: + /// the decompressor check cannot fail. async fn create_remote_staging( &self, parent: &str, temporary_dir: &str, - ) -> Result<(), BootstrapError> { - let parent_output = self.run_remote(["mkdir", "-p", "--", parent]).await?; - if parent_output.status != 0 { - return Err(BootstrapError::Install { - status: parent_output.status, - stderr: sanitize(&String::from_utf8_lossy(&parent_output.stderr)), - }); - } - let output = self.run_remote(["mkdir", "-m", "700", "--", temporary_dir]).await?; + ) -> Result { + let command = format!( + "mkdir -p -- {parent} && mkdir -m 700 -- {temporary_dir} && \ + {{ command -v gzip >/dev/null 2>&1 && echo {GZIP_UPLOAD_MARKER}; true; }}" + ); + let output = self.run_remote([command.as_str()]).await?; if output.status != 0 { return Err(BootstrapError::Install { status: output.status, stderr: sanitize(&String::from_utf8_lossy(&output.stderr)), }); } - Ok(()) + let gzip = String::from_utf8_lossy(&output.stdout) + .lines() + .any(|line| line.trim() == GZIP_UPLOAD_MARKER); + Ok(if gzip { UploadEncoding::Gzip } else { UploadEncoding::Raw }) } async fn cleanup_remote_staging(&self, path: &str, deadline: Instant) { @@ -519,7 +521,7 @@ impl SshBootstrapper { command.arg(argument); } command.stdin(Stdio::null()); - self.run_child_with_timeout(command, timeout).await + self.run_child_with_timeout(command, timeout, None).await } fn configure_ssh_command(&self, command: &mut Command) { @@ -530,15 +532,18 @@ impl SshBootstrapper { command.args(&self.config.extra_args).arg(&self.config.destination); } - async fn run_child(&self, command: Command) -> Result { - self.run_child_with_timeout(command, self.config.timeout).await - } - + /// Runs one ssh command. With `compressed_input`, that file is gzipped + /// on a blocking thread and streamed to the command's stdin while the + /// upload is in flight. async fn run_child_with_timeout( &self, mut command: Command, timeout: Duration, + compressed_input: Option<&Path>, ) -> Result { + if compressed_input.is_some() { + command.stdin(Stdio::piped()); + } let mut child = command .stdout(Stdio::piped()) .stderr(Stdio::piped()) @@ -563,6 +568,7 @@ impl SshBootstrapper { ))); } }; + let input = compressed_input.map(|path| (child.stdin.take(), compress_upload(path))); let started = Instant::now(); let completion = tokio::time::timeout(timeout, async { // Drain both pipes concurrently so either stream can fill without @@ -570,11 +576,12 @@ impl SshBootstrapper { tokio::try_join!( read_bounded(stdout, "stdout"), read_bounded(stderr, "stderr"), + write_upload(input), async { child.wait().await.map_err(BootstrapError::Io) }, ) }) .await; - let (stdout, stderr, status) = match completion { + let (stdout, stderr, sent, status) = match completion { Ok(Ok(result)) => result, Ok(Err(error)) => { terminate_and_reap(&mut child).await; @@ -593,31 +600,120 @@ impl SshBootstrapper { return Err(BootstrapError::Timeout); } }; - Ok(RemoteOutput { status: status.code().unwrap_or(255), stdout, stderr }) + let status = status.code().unwrap_or(255); + // A command that exits cleanly without reading the whole upload must + // not pass for an install. A failed one reports its own status. + if status == 0 && !sent { + return Err(BootstrapError::Io(std::io::Error::other( + "SSH closed the upload before the payload was sent", + ))); + } + Ok(RemoteOutput { status, stdout, stderr }) } async fn run_remote_with_input( &self, remote_command: &str, source: &Path, + encoding: UploadEncoding, ) -> Result { - let source = std::fs::File::open(source).map_err(BootstrapError::Io)?; let mut command = Command::new(&self.config.ssh_binary); self.configure_ssh_command(&mut command); - command.arg(remote_command).stdin(Stdio::from(source)); - self.run_child(command).await + command.arg(remote_command); + match encoding { + UploadEncoding::Raw => { + let source = std::fs::File::open(source).map_err(BootstrapError::Io)?; + command.stdin(Stdio::from(source)); + self.run_child_with_timeout(command, self.config.timeout, None).await + } + UploadEncoding::Gzip => { + self.run_child_with_timeout(command, self.config.timeout, Some(source)).await + } + } } } +/// How the payload travels to the remote staging file. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum UploadEncoding { + Raw, + /// gzip stream, decompressed remotely. The binary is about 2.5 times + /// smaller on the wire, and gzip's CRC rejects a truncated upload. + Gzip, +} + /// Build the remote upload command after the caller has created the staging /// directory exclusively with mode 0700. `set -C` plus an explicit descriptor /// opens the payload with no-clobber semantics, so a same-UID process cannot /// redirect the stream through a planted payload symlink. -fn upload_command(_parent: &str, _temporary_dir: &str, temporary: &str) -> String { +fn upload_command(temporary: &str, encoding: UploadEncoding) -> String { + let writer = match encoding { + UploadEncoding::Raw => "cat", + UploadEncoding::Gzip => "gzip -dc", + }; // The validated temporary path is rooted under the configured remote // binary directory and cannot begin with `-`. macOS chmod does not accept // the GNU `--` separator, so keep this command portable across Unix hosts. - format!("umask 077; (set -C; exec 3> {temporary} && cat >&3) && chmod 755 {temporary}") + format!("umask 077; (set -C; exec 3> {temporary} && {writer} >&3) && chmod 755 {temporary}") +} + +/// Compressed upload bytes, in order, or the read error that ended them. +type UploadChunks = mpsc::Receiver>>; + +/// Compresses `source` on a blocking thread into bounded chunks. Dropping the +/// receiver stops the compressor at its next chunk. +fn compress_upload(source: &Path) -> UploadChunks { + let (sender, receiver) = mpsc::channel(4); + let source = source.to_path_buf(); + tokio::task::spawn_blocking(move || { + use std::io::Read; + + let file = match std::fs::File::open(&source) { + Ok(file) => file, + Err(error) => { + let _ = sender.blocking_send(Err(error)); + return; + } + }; + let mut encoder = GzEncoder::new(std::io::BufReader::new(file), Compression::default()); + loop { + let mut chunk = Vec::with_capacity(UPLOAD_CHUNK_BYTES); + match (&mut encoder).take(UPLOAD_CHUNK_BYTES as u64).read_to_end(&mut chunk) { + Ok(0) => return, + Ok(_) => { + if sender.blocking_send(Ok(chunk)).is_err() { + return; + } + } + Err(error) => { + let _ = sender.blocking_send(Err(error)); + return; + } + } + } + }); + receiver +} + +/// Writes a compressed upload to ssh's stdin and closes it. Reports whether +/// every byte was written: a remote that exits early closes the pipe, and its +/// own status and stderr then explain the failure better than the write error. +async fn write_upload( + input: Option<(Option, UploadChunks)>, +) -> Result { + let Some((stdin, mut chunks)) = input else { + return Ok(true); + }; + let Some(mut stdin) = stdin else { + return Err(BootstrapError::Io(std::io::Error::other("SSH stdin pipe is unavailable"))); + }; + while let Some(chunk) = chunks.recv().await { + let chunk = chunk.map_err(BootstrapError::Io)?; + if stdin.write_all(&chunk).await.is_err() { + return Ok(false); + } + } + Ok(stdin.shutdown().await.is_ok()) } #[derive(Debug, Clone, PartialEq, Eq)] @@ -821,15 +917,16 @@ mod tests { #[test] fn upload_command_writes_only_after_exclusive_directory_creation() { - let command = upload_command( - "~/.local/bin", - "~/.local/bin/.cmux-upload-test", - "~/.local/bin/.cmux-upload-test/payload", - ); + let payload = "~/.local/bin/.cmux-upload-test/payload"; + let command = upload_command(payload, UploadEncoding::Raw); assert!(command.contains("set -C; exec 3> ~/.local/bin/.cmux-upload-test/payload")); assert!(command.contains("cat >&3")); assert!(command.contains("chmod 755 ~/.local/bin/.cmux-upload-test/payload")); assert!(!command.contains("cat > ~/.local/bin")); + let command = upload_command(payload, UploadEncoding::Gzip); + assert!(command.contains("set -C; exec 3> ~/.local/bin/.cmux-upload-test/payload")); + assert!(command.contains("gzip -dc >&3")); + assert!(command.contains("chmod 755 ~/.local/bin/.cmux-upload-test/payload")); } #[test] @@ -1032,6 +1129,68 @@ mod tests { assert_eq!(fs::read(installed).unwrap(), b"exact unpublished build"); } + /// A first connect uploads tens of megabytes over the user's own link, so + /// the payload must travel compressed when the remote can decompress it, + /// and the install must not spend a round trip per shell step. + #[cfg(unix)] + #[tokio::test] + async fn raw_build_streams_a_compressed_upload_in_few_round_trips() { + use std::fs; + use std::os::unix::fs::PermissionsExt; + + let directory = tempfile::tempdir().unwrap(); + let script = directory.path().join("ssh"); + let installed = directory.path().join("installed"); + let staged = directory.path().join("staged"); + let wire = directory.path().join("wire"); + let commands = directory.path().join("commands"); + let source = directory.path().join("cmux-tui"); + let payload = b"compressible unpublished build\n".repeat(64 * 1024); + fs::write(&source, &payload).unwrap(); + let uname_os = if std::env::consts::OS == "macos" { "Darwin" } else { "Linux" }; + let uname_arch = + if std::env::consts::ARCH == "aarch64" { "arm64" } else { std::env::consts::ARCH }; + let probe = serde_json::json!({ + "app": "cmux-tui", + "version": DISTRIBUTION_VERSION, + "distribution_version": DISTRIBUTION_VERSION, + "build_identity": BUILD_IDENTITY, + "remote_protocol": REMOTE_PROTOCOL_VERSION, + "os": std::env::consts::OS, + "arch": std::env::consts::ARCH, + }); + fs::write( + &script, + format!( + "#!/bin/sh\nprintf '%s\\n' \"$*\" >>'{commands}'\ncase \"$*\" in\n *\"uname -s -m\"*) printf '%s\\n' '{uname_os} {uname_arch}' ;;\n *\"mkdir -p \"*|*\"mkdir -m 700 \"*) command -v gzip >/dev/null 2>&1 && printf '%s\\n' 'cmux-upload:gzip' ;;\n *\".cmux-upload-\"*\" remote-probe --json\"*)\n [ -f '{staged}' ] || exit 127\n printf '%s' '{probe}'\n ;;\n *\"remote-probe --json\"*)\n [ -f '{installed}' ] || exit 127\n printf '%s' '{probe}'\n ;;\n *\"exec 3> \"*\".cmux-upload-\"*\"gzip -dc\"*) tee '{wire}' | gzip -dc >'{staged}' ;;\n *\"exec 3> \"*\".cmux-upload-\"*) tee '{wire}' >'{staged}' ;;\n *\"mv -f \"*\".cmux-upload-\"*) mv '{staged}' '{installed}' ;;\n *\"rm -f \"*\".cmux-upload-\"*) rm -f '{staged}' ;;\n *\"rmdir \"*\".cmux-upload-\"*) exit 0 ;;\n *) exit 2 ;;\nesac\n", + commands = commands.display(), + installed = installed.display(), + staged = staged.display(), + wire = wire.display(), + ), + ) + .unwrap(); + fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap(); + + let mut config = SshBootstrapConfig::defaults("host"); + config.ssh_binary = script.to_string_lossy().into_owned(); + config.package_installable = false; + config.local_binary = Some(source); + config.remote_binary = "~/.local/bin/cmux-upload".into(); + + assert_eq!( + SshBootstrapper::new(config).unwrap().ensure_installed().await.unwrap(), + BootstrapOutcome::Installed + ); + assert_eq!(fs::read(installed).unwrap(), payload); + let sent = fs::read(wire).unwrap(); + assert_eq!(sent.get(..2), Some(&[0x1f, 0x8b][..]), "upload was not gzip"); + assert!(sent.len() * 10 < payload.len(), "upload sent {} bytes", sent.len()); + // probe, platform, staging, upload, staged probe, move, final probe. + let commands = fs::read_to_string(commands).unwrap(); + assert!(commands.lines().count() <= 7, "install ran:\n{commands}"); + } + #[cfg(unix)] #[tokio::test] async fn raw_build_keeps_existing_remote_binary_when_staged_probe_is_incompatible() { diff --git a/cmuxTests/CloudManualMirrorSocketFixture.swift b/cmuxTests/CloudManualMirrorSocketFixture.swift index 28144a156372..a0d9c7e47f91 100644 --- a/cmuxTests/CloudManualMirrorSocketFixture.swift +++ b/cmuxTests/CloudManualMirrorSocketFixture.swift @@ -21,6 +21,7 @@ struct CloudManualMirrorFixtureCommand: Sendable { let offset: Int? let imageBytes: Data? let hasDestinationPath: Bool + let noReply: Bool init?(_ object: [String: Any]) { guard let cmd = object["cmd"] as? String else { return nil } @@ -41,6 +42,7 @@ struct CloudManualMirrorFixtureCommand: Sendable { offset = object["offset"] as? Int imageBytes = (object["data"] as? String).flatMap { Data(base64Encoded: $0) } hasDestinationPath = object["path"] != nil + noReply = object["no_reply"] as? Bool == true } } diff --git a/cmuxTests/CloudRestoreReplayFixture.swift b/cmuxTests/CloudRestoreReplayFixture.swift index c66eed9c682a..5ee03736e978 100644 --- a/cmuxTests/CloudRestoreReplayFixture.swift +++ b/cmuxTests/CloudRestoreReplayFixture.swift @@ -83,6 +83,12 @@ final class CloudRestoreReplayFixture { func focus() { session.claimGeometry() } + /// One explicit keystroke, through the hook and router a real key uses. + func type(_ text: String) { + session.noteExplicitInput() + session.inputRouter.send(.bytes(Data(text.utf8))) + } + func seedLocalOutput(_ bytes: Data, marker: String) async throws { surface.processRemoteOutput(bytes) try await waitUntil { self.surface.readText(region: .screen)?.contains(marker) == true } diff --git a/cmuxTests/CloudRestoreReplayGridTests.swift b/cmuxTests/CloudRestoreReplayGridTests.swift index 319f051cf28a..b8dec5e68033 100644 --- a/cmuxTests/CloudRestoreReplayGridTests.swift +++ b/cmuxTests/CloudRestoreReplayGridTests.swift @@ -107,4 +107,71 @@ struct CloudRestoreReplayGridTests { fixture.socket.send(["id": claim.id, "ok": true, "data": [:]]) try await fixture.expectInputAfterPendingResponses(marker: "CLAIM_APPLIED") } + + @Test + func typingIntoTheGeometryOwnerSendsOnlyOneWayInput() async throws { + let fixture = try CloudRestoreReplayFixture() + defer { fixture.close() } + try await fixture.setGrid(columns: 99, rows: 35) + fixture.setVisible(true) + fixture.setVisible(false) + try await fixture.attach(replay: Data("STATUS_READY".utf8)) + fixture.setVisible(true) + + let report = try #require(await fixture.socket.nextCommand(timeout: .seconds(5))) + #expect(report.cmd == "resize-surface") + fixture.socket.send(["id": report.id, "ok": true, "data": ["accepted": true, "outcome": "applied"]]) + let claim = try #require(await fixture.socket.nextCommand(timeout: .seconds(5))) + #expect(claim.cmd == "set-client-sizing") + fixture.socket.send([ + "event": "resized", "surface": 17, "cols": 99, "rows": 35, + "replay": Data("OWNER_GRID".utf8).base64EncodedString() + ]) + fixture.socket.send(["id": claim.id, "ok": true, "data": [:]]) + try await fixture.expectInputAfterPendingResponses(marker: "OWNER_CONFIRMED") + + // Each keystroke used to re-claim geometry first, which put a + // set-client-sizing round trip ahead of every key. The owner's keys + // go out alone and ask for no reply, so a relay can send them as + // compact one-way input. + for key in ["l", "s", "\r"] { + fixture.type(key) + let input = try #require(await fixture.socket.nextCommand(timeout: .seconds(5))) + #expect(input.cmd == "send", "The confirmed owner re-claimed geometry for a keystroke") + #expect(input.inputBytes == Data(key.utf8)) + #expect(input.noReply) + } + } + + @Test + func typingIntoAPaneAnotherClientSizesReclaimsTheGridFirst() async throws { + let fixture = try CloudRestoreReplayFixture(initiallyClaimsGeometry: false) + defer { fixture.close() } + try await fixture.setGrid(columns: 99, rows: 35) + fixture.setVisible(true) + fixture.setVisible(false) + try await fixture.attach(replay: Data("STATUS_READY".utf8)) + fixture.setVisible(true) + + let report = try #require(await fixture.socket.nextCommand(timeout: .seconds(5))) + #expect(report.cmd == "resize-surface") + fixture.socket.send(["id": report.id, "ok": true, "data": ["outcome": "passive", "accepted": false]]) + try await fixture.expectInputAfterPendingResponses(marker: "PEER_OWNS_GRID") + + // Another client sizes the terminal. The pane the user types into + // takes the grid back before its first key goes out. + fixture.type("l") + let claim = try #require(await fixture.socket.nextCommand(timeout: .seconds(5))) + #expect(claim.cmd == "set-client-sizing", "A key went out before the pane reclaimed the grid") + #expect(claim.surface == 17) + fixture.socket.send([ + "event": "resized", "surface": 17, "cols": 99, "rows": 35, + "replay": Data("RECLAIMED_GRID".utf8).base64EncodedString() + ]) + fixture.socket.send(["id": claim.id, "ok": true, "data": [:]]) + let input = try #require(await fixture.socket.nextCommand(timeout: .seconds(5))) + #expect(input.cmd == "send") + #expect(input.inputBytes == Data("l".utf8)) + #expect(input.noReply) + } } diff --git a/cmuxTests/CloudTuiManualIOConnectionTests.swift b/cmuxTests/CloudTuiManualIOConnectionTests.swift index bb6bf4d73192..559cd8f35ab4 100644 --- a/cmuxTests/CloudTuiManualIOConnectionTests.swift +++ b/cmuxTests/CloudTuiManualIOConnectionTests.swift @@ -122,6 +122,19 @@ import Testing } } + @Test func oneWayInputRepliesNeverReachTheConsumer() async throws { + try await Self.withConnection { connection, peer in + // Request id zero marks untracked input. A daemon that still + // answers it must not cost the session a turn before the echo. + try Self.write(peer, Data("{\"id\":0,\"ok\":true}\n{\"id\":0,\"ok\":false,\"error\":\"gone\"}\n".utf8) + + Self.outputLine(Data("echo".utf8))) + shutdown(peer, SHUT_WR) + var iterator = connection.events.makeAsyncIterator() + #expect(await iterator.next() == .output(surfaceID: 1, bytes: Data("echo".utf8))) + #expect(await iterator.next() == nil) + } + } + @Test func persistentRequestsShareOneSocketAndMatchOutOfOrderResponses() async throws { try await Self.withResourceConnection { channel, peer in async let one = channel.request(CloudTuiRequest("session.ping")) diff --git a/cmuxTests/SSHTuiMigrationTests.swift b/cmuxTests/SSHTuiMigrationTests.swift index 5b7a349d691a..9af79bd30906 100644 --- a/cmuxTests/SSHTuiMigrationTests.swift +++ b/cmuxTests/SSHTuiMigrationTests.swift @@ -118,6 +118,48 @@ struct SSHTuiMigrationTests { #expect(SSHTuiConnection(configuration: original).id == SSHTuiConnection(configuration: restored).id) } + @Test("A restored carrier logs in through the ControlMaster its open shared") + func restoredCarrierSharesTheOpensControlMaster() throws { + // `cmux ssh` opens with cmux's sharing defaults. The restored carrier + // runs in batch mode, so on a password-only host the live master is + // its only way in. + let opened = configuration(options: SSHConnectionSharingOptions().mergingDefaults(into: ["ProxyJump=bastion"])) + let snapshot = try #require(opened.sessionSnapshot()) + let persisted = try JSONEncoder().encode(snapshot) + let restored = try #require(try JSONDecoder().decode(SessionRemoteWorkspaceSnapshot.self, from: persisted).workspaceConfiguration()) + let openedCarrier = try resolvedControlSettings(SSHTuiConnection(configuration: opened)) + #expect(openedCarrier["controlmaster"] == "auto") + #expect(openedCarrier["controlpath"]?.hasPrefix("/tmp/cmux-ssh-") == true) + #expect(try resolvedControlSettings(SSHTuiConnection(configuration: restored)) == openedCarrier) + } + + /// The control settings OpenSSH resolves for the carrier's own ssh arguments. + private func resolvedControlSettings(_ connection: SSHTuiConnection) throws -> [String: String] { + let arguments = connection.arguments(stateDirectory: "/tmp/cmux-tui-client", deviceName: "test") + let sshArguments = arguments.indices.compactMap { index -> String? in + guard index > 0, arguments[index - 1] == "--ssh-arg" else { return nil } + return arguments[index] + } + let process = Process() + let output = Pipe() + process.executableURL = URL(fileURLWithPath: "/usr/bin/ssh") + process.arguments = ["-G", "-F", "/dev/null"] + sshArguments + [connection.configuration.destination] + process.standardOutput = output + process.standardError = FileHandle.nullDevice + process.standardInput = FileHandle.nullDevice + try process.run() + let data = output.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + try #require(process.terminationStatus == 0) + var settings: [String: String] = [:] + for line in String(decoding: data, as: UTF8.self).split(separator: "\n") { + let parts = line.split(separator: " ", maxSplits: 1) + guard parts.count == 2, ["controlmaster", "controlpath", "controlpersist"].contains(parts[0]) else { continue } + settings[String(parts[0])] = String(parts[1]) + } + return settings + } + @Test("Legacy persistent SSH snapshots are not claimed by the TUI owner") func legacySnapshotDoesNotBecomeTuiSession() throws { let legacy = SessionRemoteWorkspaceSnapshot(transport: .ssh, destination: "fixture@host", diff --git a/cmuxTests/SSHTuiOpenTests.swift b/cmuxTests/SSHTuiOpenTests.swift index 588c034f8463..da3d9645a96f 100644 --- a/cmuxTests/SSHTuiOpenTests.swift +++ b/cmuxTests/SSHTuiOpenTests.swift @@ -143,7 +143,14 @@ struct SSHTuiOpenTests { /// A link manager whose SSH route is a ProxyCommand running `route`. private func linkManager(route: String, client: URL, root: URL) -> (links: SSHTuiLinkManager, machineID: String) { - let connection = SSHTuiConnection(configuration: configuration(options: ["ProxyCommand=/bin/sh -c \"\(route)\""])) + // Any ControlPath with ControlPersist, cmux's or one from + // ~/.ssh/config, sends the ProxyCommand's stderr to /dev/null, and a + // matching master would skip the route entirely. Both would hide the + // refusal the route stands in for. A real host's refusal comes from + // ssh itself and stays visible. + let connection = SSHTuiConnection(configuration: configuration( + options: ["ProxyCommand=/bin/sh -c \"\(route)\"", "ControlMaster=no", "ControlPath=none"] + )) let links = SSHTuiLinkManager(connection: connection, clientURL: client, paths: CloudTuiClientPaths(home: root), isEnabled: { true }) return (links, connection.id) diff --git a/cmuxTests/SSHTuiPreflightTests.swift b/cmuxTests/SSHTuiPreflightTests.swift index 2bbf46fe26db..979799986540 100644 --- a/cmuxTests/SSHTuiPreflightTests.swift +++ b/cmuxTests/SSHTuiPreflightTests.swift @@ -20,8 +20,11 @@ struct SSHTuiPreflightTests { let call = try #require(await commands.calls.first) #expect(call.executable == "/usr/bin/ssh") #expect(call.timeout == 7) + // The caller's ControlPath wins; cmux fills in the rest of its + // shared-master defaults, as the carrier does. #expect(call.arguments == ["-T", "-o", "BatchMode=yes", "-o", "RemoteCommand=none", "-o", "RequestTTY=no", "-p", "2222", "-i", "/tmp/key", "-o", "ControlPath=/tmp/cm", "-o", "ConnectTimeout=5", + "-o", "ControlMaster=auto", "-o", "ControlPersist=600", "-o", "ConnectTimeout=15", "alice@example.invalid", "true"]) } diff --git a/cmuxTests/SurfacePaneFactoryFocusTests.swift b/cmuxTests/SurfacePaneFactoryFocusTests.swift index e2e8147ff67f..cece5c546a90 100644 --- a/cmuxTests/SurfacePaneFactoryFocusTests.swift +++ b/cmuxTests/SurfacePaneFactoryFocusTests.swift @@ -616,6 +616,31 @@ import SwiftUI #expect(workspace.paneId(forPanelId: created.panelID) != paneID) } + /// A focused Cloud split hands focus over like a local Cmd+D. SwiftUI reparents + /// the source terminal into the new split; unless that reparent is suppressed, + /// the source takes focus back and the new pane shows a hollow cursor. + @Test func focusedCloudSplitKeepsTheSourceFromTakingFocusBack() throws { + let harness = try Harness() + defer { harness.tearDown() } + let workspace = harness.workspace + let paneID = try #require(workspace.bonsplitController.focusedPaneId) + let source = try #require(workspace.focusedPanelId.flatMap { workspace.terminalPanel(for: $0) }) + let panel = try #require(workspace.makeRemoteTmuxPanePanel(onInput: { _ in })) + + _ = try workspace.insertCloudManualMirrorPanel( + panel, + at: .split(workspaceID: workspace.id, paneID: paneID.id.uuidString, direction: .right), + focus: true, + isLoading: false + ) + + #expect(workspace.focusedPanelId == panel.id) + #expect(workspace.paneId(forPanelId: panel.id) != paneID) +#if DEBUG + #expect(source.hostedView.debugIsSuppressingReparentFocusForTesting()) +#endif + } + /// A projected browser (VM desktop or port preview) goes through the same create /// handler as a terminal; `focus: true` must select it too. @Test func focusedBrowserTabIsSelected() throws {