diff --git a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+Surface3.swift b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+Surface3.swift index 38f3d48240ed..8938fa454123 100644 --- a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+Surface3.swift +++ b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+Surface3.swift @@ -46,6 +46,17 @@ extension ControlCommandCoordinator { } let source = publicResumeSource(params) + let remoteWorkspaceID = uuid(params, "_cmux_remote_workspace_id") + if hasNonNull(params, "_cmux_remote_workspace_id"), remoteWorkspaceID == nil { + return .err( + code: "invalid_params", + message: String( + localized: "socket.surfaceSplitOff.error.invalidWorkspaceId", + defaultValue: "Missing or invalid workspace_id" + ), + data: nil + ) + } let inputs = ControlSurfaceResumeSetInputs( name: optionalTrimmedRawString(params, "name"), kind: optionalTrimmedRawString(params, "kind"), @@ -55,7 +66,9 @@ extension ControlCommandCoordinator { ?? optionalTrimmedRawString(params, "checkpointId"), source: source, environment: stringMap(params, "environment"), - autoResume: source == "agent-hook" ? (bool(params, "auto_resume") ?? false) : false + autoResume: source == "agent-hook" ? (bool(params, "auto_resume") ?? false) : false, + remoteWorkspaceID: remoteWorkspaceID, + remoteRelayParameters: remoteWorkspaceID == nil ? nil : params ) return surfaceResumeResult( context?.controlSurfaceResumeSet( @@ -160,6 +173,10 @@ extension ControlCommandCoordinator { "auto_resume": .bool(binding.autoResume), "approval_policy": orNull(binding.approvalPolicyRawValue), "approval_record_id": orNull(binding.approvalRecordID), + "execution_location": .string(binding.executionLocationRawValue), + "remote_workspace_id": orNull(binding.remoteWorkspaceID?.uuidString), + "remote_surface_id": orNull(binding.remoteSurfaceID?.uuidString), + "remote_pty_session_id": orNull(binding.remotePTYSessionID), "updated_at": .double(binding.updatedAt), ]) } diff --git a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceResumeBinding.swift b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceResumeBinding.swift index 0801af91aea6..59470e7d564f 100644 --- a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceResumeBinding.swift +++ b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceResumeBinding.swift @@ -31,6 +31,14 @@ public struct ControlSurfaceResumeBinding: Sendable, Equatable { public let approvalPolicyRawValue: String? /// The approval record identifier, if any. public let approvalRecordID: String? + /// Where the saved command is allowed to execute (`local` or `remote_ssh`). + public let executionLocationRawValue: String + /// The owning remote workspace for a remote binding. + public let remoteWorkspaceID: UUID? + /// The owning remote surface for a remote binding. + public let remoteSurfaceID: UUID? + /// The persistent remote PTY session for a remote binding. + public let remotePTYSessionID: String? /// The last-updated timestamp (seconds since the epoch). public let updatedAt: Double @@ -47,6 +55,10 @@ public struct ControlSurfaceResumeBinding: Sendable, Equatable { /// - autoResume: Whether automatic resume is allowed. /// - approvalPolicyRawValue: The approval policy's raw value. /// - approvalRecordID: The approval record identifier. + /// - executionLocationRawValue: Where the command is allowed to execute. + /// - remoteWorkspaceID: The owning remote workspace. + /// - remoteSurfaceID: The owning remote surface. + /// - remotePTYSessionID: The persistent remote PTY session. /// - updatedAt: The last-updated timestamp. public init( name: String?, @@ -59,6 +71,10 @@ public struct ControlSurfaceResumeBinding: Sendable, Equatable { autoResume: Bool, approvalPolicyRawValue: String?, approvalRecordID: String?, + executionLocationRawValue: String, + remoteWorkspaceID: UUID?, + remoteSurfaceID: UUID?, + remotePTYSessionID: String?, updatedAt: Double ) { self.name = name @@ -71,6 +87,10 @@ public struct ControlSurfaceResumeBinding: Sendable, Equatable { self.autoResume = autoResume self.approvalPolicyRawValue = approvalPolicyRawValue self.approvalRecordID = approvalRecordID + self.executionLocationRawValue = executionLocationRawValue + self.remoteWorkspaceID = remoteWorkspaceID + self.remoteSurfaceID = remoteSurfaceID + self.remotePTYSessionID = remotePTYSessionID self.updatedAt = updatedAt } } diff --git a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceResumeSetInputs.swift b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceResumeSetInputs.swift index f950529a1ba5..864e130b4851 100644 --- a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceResumeSetInputs.swift +++ b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceResumeSetInputs.swift @@ -1,4 +1,4 @@ -internal import Foundation +public import Foundation /// The pre-parsed inputs for `surface.resume.set`, lifted from the legacy /// `v2SurfaceResumeSet` body's param parsing. @@ -25,6 +25,10 @@ public struct ControlSurfaceResumeSetInputs: Sendable, Equatable { /// Whether automatic resume is requested (already gated: `true` only for the /// `agent-hook` source with `auto_resume == true`). public let autoResume: Bool + /// The relay-claimed remote workspace, authenticated by the app context. + public let remoteWorkspaceID: UUID? + /// Raw relay parameters retained to authenticate their provenance. + public let remoteRelayParameters: [String: JSONValue]? /// Creates resume-set inputs. /// @@ -37,6 +41,8 @@ public struct ControlSurfaceResumeSetInputs: Sendable, Equatable { /// - source: The (already-mapped) binding source. /// - environment: The environment overrides. /// - autoResume: Whether automatic resume is requested. + /// - remoteWorkspaceID: The authenticated relay's owning workspace. + /// - remoteRelayParameters: Raw parameters carrying relay authentication. public init( name: String?, kind: String?, @@ -45,7 +51,9 @@ public struct ControlSurfaceResumeSetInputs: Sendable, Equatable { checkpointID: String?, source: String?, environment: [String: String]?, - autoResume: Bool + autoResume: Bool, + remoteWorkspaceID: UUID?, + remoteRelayParameters: [String: JSONValue]? ) { self.name = name self.kind = kind @@ -55,5 +63,7 @@ public struct ControlSurfaceResumeSetInputs: Sendable, Equatable { self.source = source self.environment = environment self.autoResume = autoResume + self.remoteWorkspaceID = remoteWorkspaceID + self.remoteRelayParameters = remoteRelayParameters } } diff --git a/Sources/RemoteInitialCommandBootstrap.swift b/Sources/RemoteInitialCommandBootstrap.swift index 9fd7bba48c30..9a6ef09d4a22 100644 --- a/Sources/RemoteInitialCommandBootstrap.swift +++ b/Sources/RemoteInitialCommandBootstrap.swift @@ -3,16 +3,10 @@ import Foundation /// Stages a remote workspace command for one execution by the first interactive shell. struct RemoteInitialCommandBootstrap { private let encodedCommand: String? - private let encodedUnsupportedShellMessage: String /// Embedded in the persisted bootstrap so reattaches reuse it while later workspaces do not. private let stateKey = UUID().uuidString.lowercased() init(command: String?) { - let unsupportedShellMessage = String( - localized: "cli.ssh.initialCommand.unsupportedShell", - defaultValue: "[cmux] Initial command was not run because cmux does not support initial commands for this remote login shell. Reconnect with a supported shell to retry it." - ) - encodedUnsupportedShellMessage = Data(unsupportedShellMessage.utf8).base64EncodedString() guard let command, !command.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { encodedCommand = nil @@ -95,43 +89,35 @@ struct RemoteInitialCommandBootstrap { ].joined(separator: "; ") } - /// Runs the command through verified execute-then-interactive shell adapters. + /// Runs the command through shell-specific adapters, with a POSIX wrapper for unknown shells. var fallbackShellLines: [String] { guard encodedCommand != nil else { return [] } return [ "cmux_initial_command_file=\"${CMUX_INITIAL_COMMAND_FILE:-}\"", "cmux_initial_command_started=\"$CMUX_SHELL_INTEGRATION_DIR/.initial-command.started.\(stateKey)\"", "unset cmux_initial_command_b64 cmux_initial_command cmux_initial_command_decode_status cmux_initial_command_file_status", - "case \"${CMUX_LOGIN_SHELL##*/}\" in", - " csh|tcsh|sh|dash|ksh|mksh|ash|yash|posh|nu|nushell|pwsh|powershell)", - " if [ -r \"$cmux_initial_command_file\" ]; then", - " cmux_initial_command_b64=$(cat -- \"$cmux_initial_command_file\" 2>/dev/null)", - " cmux_initial_command_file_status=$?", - " else", - " cmux_initial_command_file_status=1", - " fi", - " unset CMUX_INITIAL_COMMAND_FILE", - " if [ -n \"$cmux_initial_command_file\" ]; then rm -f -- \"$cmux_initial_command_file\" 2>/dev/null || true; fi", - " if [ \"$cmux_initial_command_file_status\" -eq 0 ] && [ -n \"$cmux_initial_command_b64\" ]; then", - " cmux_initial_command=$(printf %s \"$cmux_initial_command_b64\" | base64 -d 2>/dev/null || printf %s \"$cmux_initial_command_b64\" | base64 -D 2>/dev/null)", - " cmux_initial_command_decode_status=$?", - " if [ \"$cmux_initial_command_decode_status\" -eq 0 ]; then", - " case \"${CMUX_LOGIN_SHELL##*/}\" in", - " csh|tcsh) if mkdir \"$cmux_initial_command_started\" 2>/dev/null; then exec \"$CMUX_LOGIN_SHELL\" -i -c 'eval \"$argv[2]\"; exec \"$argv[1]\" -i' \"$CMUX_LOGIN_SHELL\" \"$cmux_initial_command\"; fi ;;", - " sh|dash|ksh|mksh|ash|yash|posh) if mkdir \"$cmux_initial_command_started\" 2>/dev/null; then exec \"$CMUX_LOGIN_SHELL\" -i -c 'eval \"$1\"; exec \"$0\" -i' \"$CMUX_LOGIN_SHELL\" \"$cmux_initial_command\"; fi ;;", + "if [ -r \"$cmux_initial_command_file\" ]; then", + " cmux_initial_command_b64=$(cat -- \"$cmux_initial_command_file\" 2>/dev/null)", + " cmux_initial_command_file_status=$?", + "else", + " cmux_initial_command_file_status=1", + "fi", + "unset CMUX_INITIAL_COMMAND_FILE", + "if [ -n \"$cmux_initial_command_file\" ]; then rm -f -- \"$cmux_initial_command_file\" 2>/dev/null || true; fi", + "if [ \"$cmux_initial_command_file_status\" -eq 0 ] && [ -n \"$cmux_initial_command_b64\" ]; then", + " cmux_initial_command=$(printf %s \"$cmux_initial_command_b64\" | base64 -d 2>/dev/null || printf %s \"$cmux_initial_command_b64\" | base64 -D 2>/dev/null)", + " cmux_initial_command_decode_status=$?", + " if [ \"$cmux_initial_command_decode_status\" -eq 0 ]; then", + " case \"${CMUX_LOGIN_SHELL##*/}\" in", + " csh|tcsh) if mkdir \"$cmux_initial_command_started\" 2>/dev/null; then exec \"$CMUX_LOGIN_SHELL\" -i -c 'eval \"$argv[2]\"; exec \"$argv[1]\" -i' \"$CMUX_LOGIN_SHELL\" \"$cmux_initial_command\"; fi ;;", + " sh|dash|ksh|mksh|ash|yash|posh) if mkdir \"$cmux_initial_command_started\" 2>/dev/null; then exec \"$CMUX_LOGIN_SHELL\" -i -c 'eval \"$1\"; exec \"$0\" -i' \"$CMUX_LOGIN_SHELL\" \"$cmux_initial_command\"; fi ;;", // Nushell src/command.rs: --execute runs then stays interactive; --commands exits. - " nu|nushell) if mkdir \"$cmux_initial_command_started\" 2>/dev/null; then exec \"$CMUX_LOGIN_SHELL\" --execute \"$cmux_initial_command\"; fi ;;", - " pwsh|powershell) if mkdir \"$cmux_initial_command_started\" 2>/dev/null; then exec \"$CMUX_LOGIN_SHELL\" -NoExit -Command \"$cmux_initial_command\"; fi ;;", - " esac", - " fi", - " fi", - " ;;", - " *)", - " unset CMUX_INITIAL_COMMAND_FILE", - " if [ -n \"$cmux_initial_command_file\" ]; then rm -f -- \"$cmux_initial_command_file\" 2>/dev/null || true; fi", - " printf %s '\(encodedUnsupportedShellMessage)' | base64 -d 1>&2 2>/dev/null || printf %s '\(encodedUnsupportedShellMessage)' | base64 -D 1>&2 2>/dev/null; printf '\\n' >&2", - " ;;", - "esac", + " nu|nushell) if mkdir \"$cmux_initial_command_started\" 2>/dev/null; then exec \"$CMUX_LOGIN_SHELL\" --execute \"$cmux_initial_command\"; fi ;;", + " pwsh|powershell) if mkdir \"$cmux_initial_command_started\" 2>/dev/null; then exec \"$CMUX_LOGIN_SHELL\" -NoExit -Command \"$cmux_initial_command\"; fi ;;", + " *) if mkdir \"$cmux_initial_command_started\" 2>/dev/null; then exec /bin/sh -c 'eval \"$1\"; exec \"$2\" -i' cmux-initial-command \"$cmux_initial_command\" \"$CMUX_LOGIN_SHELL\"; fi ;;", + " esac", + " fi", + "fi", "unset cmux_initial_command_b64 cmux_initial_command cmux_initial_command_decode_status cmux_initial_command_file_status cmux_initial_command_file cmux_initial_command_started", ] } diff --git a/Sources/SSHPTYAttachStartupCommandBuilder.swift b/Sources/SSHPTYAttachStartupCommandBuilder.swift index 866a62771d5c..753998d2766d 100644 --- a/Sources/SSHPTYAttachStartupCommandBuilder.swift +++ b/Sources/SSHPTYAttachStartupCommandBuilder.swift @@ -53,10 +53,14 @@ enum SSHPTYAttachStartupCommandBuilder { return "/bin/sh -c \(shellQuote(lines.joined(separator: "\n")))" } - static func restoredRemoteShellCommand(relayPort: Int) -> String { + static func restoredRemoteShellCommand( + relayPort: Int, + initialCommand: String? = nil + ) -> String { RemoteInteractiveShellBootstrapBuilder.script( remoteRelayPort: relayPort, shellFeatures: RemoteInteractiveShellBootstrapBuilder.shellFeatures(), + initialCommand: initialCommand, bundledZshIntegration: RemoteInteractiveShellBootstrapBuilder.bundledShellIntegrationScript(named: "cmux-zsh-integration.zsh"), bundledBashIntegration: RemoteInteractiveShellBootstrapBuilder.bundledShellIntegrationScript(named: "cmux-bash-integration.bash"), bundledFishIntegration: RemoteInteractiveShellBootstrapBuilder.bundledShellIntegrationScript(named: "fish/config.fish") diff --git a/Sources/SessionPersistence.swift b/Sources/SessionPersistence.swift index d64e3c1b0469..f7993517ce5f 100644 --- a/Sources/SessionPersistence.swift +++ b/Sources/SessionPersistence.swift @@ -259,17 +259,9 @@ enum SurfaceResumeApprovalPolicy: String, Codable, CaseIterable, Sendable { struct SurfaceResumeBindingSnapshot: Codable, Equatable, Sendable { private enum CodingKeys: String, CodingKey { - case name - case kind - case command - case cwd - case checkpointId - case source - case environment - case autoResume - case approvalPolicy - case approvalRecordId - case updatedAt + case name, kind, command, cwd, checkpointId, source + case environment, autoResume, approvalPolicy, approvalRecordId + case launchFlavor, updatedAt } var name: String? @@ -282,6 +274,9 @@ struct SurfaceResumeBindingSnapshot: Codable, Equatable, Sendable { var autoResume: Bool? var approvalPolicy: SurfaceResumeApprovalPolicy? var approvalRecordId: String? + var launchFlavor: SurfaceResumeLaunchFlavor + /// Whether decoding observed a legacy binding without an execution location. + private(set) var wasDecodedWithoutLaunchFlavor = false var updatedAt: TimeInterval init( @@ -295,6 +290,7 @@ struct SurfaceResumeBindingSnapshot: Codable, Equatable, Sendable { autoResume: Bool? = nil, approvalPolicy: SurfaceResumeApprovalPolicy? = nil, approvalRecordId: String? = nil, + launchFlavor: SurfaceResumeLaunchFlavor = .local, updatedAt: TimeInterval = Date().timeIntervalSince1970 ) { let normalizedCwd = Self.normalized(cwd) @@ -314,11 +310,13 @@ struct SurfaceResumeBindingSnapshot: Codable, Equatable, Sendable { self.autoResume = autoResume self.approvalPolicy = approvalPolicy self.approvalRecordId = Self.normalized(approvalRecordId) + self.launchFlavor = launchFlavor self.updatedAt = updatedAt } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) + let decodedLaunchFlavor = try container.decodeIfPresent(SurfaceResumeLaunchFlavor.self, forKey: .launchFlavor) self.init( name: try container.decodeIfPresent(String.self, forKey: .name), kind: try container.decodeIfPresent(String.self, forKey: .kind), @@ -330,9 +328,11 @@ struct SurfaceResumeBindingSnapshot: Codable, Equatable, Sendable { autoResume: try container.decodeIfPresent(Bool.self, forKey: .autoResume), approvalPolicy: try container.decodeIfPresent(SurfaceResumeApprovalPolicy.self, forKey: .approvalPolicy), approvalRecordId: try container.decodeIfPresent(String.self, forKey: .approvalRecordId), + launchFlavor: decodedLaunchFlavor ?? .local, updatedAt: try container.decodeIfPresent(TimeInterval.self, forKey: .updatedAt) ?? Date().timeIntervalSince1970 ) + wasDecodedWithoutLaunchFlavor = decodedLaunchFlavor == nil } var isProcessDetected: Bool { @@ -374,10 +374,10 @@ struct SurfaceResumeBindingSnapshot: Codable, Equatable, Sendable { autoResume: autoResume, approvalPolicy: approvalPolicy, approvalRecordId: approvalRecordId, + launchFlavor: launchFlavor, updatedAt: updatedAt ) } - static let maxInlineStartupInputBytes = SessionRestorableAgentSnapshot.maxInlineStartupInputBytes var startupInput: String? { diff --git a/Sources/SessionRemoteWorkspaceSnapshot+Restore.swift b/Sources/SessionRemoteWorkspaceSnapshot+Restore.swift index b8dc65ebf399..e63e75b93a91 100644 --- a/Sources/SessionRemoteWorkspaceSnapshot+Restore.swift +++ b/Sources/SessionRemoteWorkspaceSnapshot+Restore.swift @@ -108,7 +108,7 @@ extension SessionRemoteWorkspaceSnapshot { ? Self.restoreRelayTokenHex() : nil let restoredRemoteShellCommand = preservePTYSession - ? normalizedRelayPort.map(SSHPTYAttachStartupCommandBuilder.restoredRemoteShellCommand(relayPort:)) + ? normalizedRelayPort.map { SSHPTYAttachStartupCommandBuilder.restoredRemoteShellCommand(relayPort: $0) } : nil return WorkspaceRemoteConfiguration( transport: transport, diff --git a/Sources/SurfaceResumeBindingSnapshot+Remote.swift b/Sources/SurfaceResumeBindingSnapshot+Remote.swift new file mode 100644 index 000000000000..8f7bc04d6198 --- /dev/null +++ b/Sources/SurfaceResumeBindingSnapshot+Remote.swift @@ -0,0 +1,55 @@ +import Foundation + +extension SurfaceResumeBindingSnapshot { + /// Assigns trusted persistent-SSH ownership only to a legacy decoded binding. + func migratingLegacyPersistentSSH(_ context: SurfaceResumeRemoteContext) -> SurfaceResumeBindingSnapshot { + guard wasDecodedWithoutLaunchFlavor else { return self } + return registeredForPersistentSSH(context) + } + + func registeredForPersistentSSH(_ context: SurfaceResumeRemoteContext) -> SurfaceResumeBindingSnapshot { + replacingLaunchFlavor(.persistentSSH(context)) + } + + func retargetingRemoteOwner( + expectedWorkspaceID: UUID, + expectedSurfaceID: UUID, + workspaceID: UUID, + surfaceID: UUID, + persistentPTYSessionID: String? + ) -> SurfaceResumeBindingSnapshot { + guard case .persistentSSH(let context) = launchFlavor, + let persistentPTYSessionID, + context.matches( + workspaceID: expectedWorkspaceID, + surfaceID: expectedSurfaceID, + persistentPTYSessionID: persistentPTYSessionID + ) else { + return self + } + return replacingLaunchFlavor(.persistentSSH(context.retargeted( + workspaceID: workspaceID, + surfaceID: surfaceID, + persistentPTYSessionID: persistentPTYSessionID + ))) + } + + private func replacingLaunchFlavor( + _ launchFlavor: SurfaceResumeLaunchFlavor + ) -> SurfaceResumeBindingSnapshot { + SurfaceResumeBindingSnapshot( + name: name, + kind: kind, + command: command, + cwd: cwd, + checkpointId: checkpointId, + source: source, + environment: environment, + autoResume: autoResume, + approvalPolicy: approvalPolicy, + approvalRecordId: approvalRecordId, + launchFlavor: launchFlavor, + updatedAt: updatedAt + ) + } +} diff --git a/Sources/SurfaceResumeLaunchFlavor.swift b/Sources/SurfaceResumeLaunchFlavor.swift new file mode 100644 index 000000000000..8d83a64cd453 --- /dev/null +++ b/Sources/SurfaceResumeLaunchFlavor.swift @@ -0,0 +1,57 @@ +import Foundation + +/// Selects where a saved resume command is allowed to execute. +enum SurfaceResumeLaunchFlavor: Equatable, Hashable, Sendable { + case local + case persistentSSH(SurfaceResumeRemoteContext) + + private enum CodingKeys: String, CodingKey { + case kind + case remoteContext + } + + var executionLocationRawValue: String { + switch self { + case .local: + return "local" + case .persistentSSH: + return "remote_ssh" + } + } + + var remoteContext: SurfaceResumeRemoteContext? { + guard case .persistentSSH(let context) = self else { return nil } + return context + } +} + +extension SurfaceResumeLaunchFlavor: Codable { + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + switch try container.decode(String.self, forKey: .kind) { + case "local": + self = .local + case "persistentSSH": + self = .persistentSSH( + try container.decode(SurfaceResumeRemoteContext.self, forKey: .remoteContext) + ) + default: + throw DecodingError.dataCorruptedError( + forKey: .kind, + in: container, + debugDescription: "Unsupported surface resume launch flavor" + ) + } + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + switch self { + case .local: + try container.encode("local", forKey: .kind) + case .persistentSSH(let context): + try container.encode("persistentSSH", forKey: .kind) + try container.encode(context, forKey: .remoteContext) + } + } +} diff --git a/Sources/SurfaceResumeRemoteContext.swift b/Sources/SurfaceResumeRemoteContext.swift new file mode 100644 index 000000000000..efa57f08727e --- /dev/null +++ b/Sources/SurfaceResumeRemoteContext.swift @@ -0,0 +1,39 @@ +import Foundation + +/// Identifies the persistent SSH session that owns a remote resume binding. +struct SurfaceResumeRemoteContext: Codable, Equatable, Hashable, Sendable { + let workspaceID: UUID + let surfaceID: UUID + let persistentPTYSessionID: String + + func retargeted( + workspaceID: UUID, + surfaceID: UUID, + persistentPTYSessionID: String + ) -> SurfaceResumeRemoteContext { + SurfaceResumeRemoteContext( + workspaceID: workspaceID, + surfaceID: surfaceID, + persistentPTYSessionID: persistentPTYSessionID + ) + } + + func matches( + workspaceID: UUID, + surfaceID: UUID, + persistentPTYSessionID: String + ) -> Bool { + guard self.workspaceID == workspaceID, + self.surfaceID == surfaceID, + let storedSessionID = normalizedSessionID(self.persistentPTYSessionID), + let candidateSessionID = normalizedSessionID(persistentPTYSessionID) else { + return false + } + return storedSessionID == candidateSessionID + } + + private func normalizedSessionID(_ value: String) -> String? { + let normalized = value.trimmingCharacters(in: .whitespacesAndNewlines) + return normalized.isEmpty ? nil : normalized + } +} diff --git a/Sources/TabManager.swift b/Sources/TabManager.swift index 044a08de498a..ebbf85a616d3 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -5690,7 +5690,6 @@ extension TabManager { hasher.combine(false) return } - hasher.combine(true) hasher.combine(snapshot.kind.rawValue) hasher.combine(snapshot.sessionId) @@ -5759,6 +5758,7 @@ extension TabManager { hashOptionalString(snapshot.source, into: &hasher) hashStringMap(snapshot.environment, into: &hasher) hasher.combine(snapshot.allowsAutomaticResume) + hasher.combine(snapshot.launchFlavor) if snapshot.isProcessDetected { hasher.combine(false) } else { diff --git a/Sources/TerminalController+ControlSurfaceContext.swift b/Sources/TerminalController+ControlSurfaceContext.swift index ab39c42a5e3e..dd90b947d9f1 100644 --- a/Sources/TerminalController+ControlSurfaceContext.swift +++ b/Sources/TerminalController+ControlSurfaceContext.swift @@ -80,6 +80,7 @@ extension TerminalController: ControlSurfaceContext { ) -> ControlSurfaceResumeBinding? { guard let binding else { return nil } let effective = SurfaceResumeApprovalStore.applyingStoredApproval(to: binding) + let remoteContext = effective.launchFlavor.remoteContext return ControlSurfaceResumeBinding( name: effective.name, kind: effective.kind, @@ -91,6 +92,10 @@ extension TerminalController: ControlSurfaceContext { autoResume: effective.allowsAutomaticResume, approvalPolicyRawValue: effective.approvalPolicy?.rawValue, approvalRecordID: effective.approvalRecordId, + executionLocationRawValue: effective.launchFlavor.executionLocationRawValue, + remoteWorkspaceID: remoteContext?.workspaceID, + remoteSurfaceID: remoteContext?.surfaceID, + remotePTYSessionID: remoteContext?.persistentPTYSessionID, updatedAt: effective.updatedAt ) } diff --git a/Sources/TerminalController+ControlSurfaceContext4.swift b/Sources/TerminalController+ControlSurfaceContext4.swift index d6f0f74335d2..1f479bed019c 100644 --- a/Sources/TerminalController+ControlSurfaceContext4.swift +++ b/Sources/TerminalController+ControlSurfaceContext4.swift @@ -188,7 +188,22 @@ extension TerminalController { ) else { return .surfaceNotFound } - let effectiveBinding = surfaceResumeBindingWithApproval(binding) + let locatedBinding: SurfaceResumeBindingSnapshot + if let remoteWorkspaceID = inputs.remoteWorkspaceID { + guard remoteWorkspaceID == target.workspace.id, + let relayParameters = inputs.remoteRelayParameters, + WorkspaceRemoteRelayCommandRewriter.authenticatesRemoteResumeParameters( + relayParameters.mapValues(\.foundationObject), + remoteRelayTokenHex: target.workspace.remoteConfiguration?.relayToken + ), + let context = target.workspace.persistentSSHResumeContext(panelID: target.surfaceId) else { + return .setFailed + } + locatedBinding = binding.registeredForPersistentSSH(context) + } else { + locatedBinding = binding + } + let effectiveBinding = surfaceResumeBindingWithApproval(locatedBinding) guard target.workspace.setSurfaceResumeBinding(effectiveBinding, panelId: target.surfaceId) else { return .emptyResumeCommand } diff --git a/Sources/Workspace+PersistentRemotePTYReattach.swift b/Sources/Workspace+PersistentRemotePTYReattach.swift index 9d66c3ed2bed..888c44e744ab 100644 --- a/Sources/Workspace+PersistentRemotePTYReattach.swift +++ b/Sources/Workspace+PersistentRemotePTYReattach.swift @@ -58,8 +58,14 @@ extension Workspace { let usesPersistentSSHPTY = configuration.transport == .ssh && !configuration.skipDaemonBootstrap && configuration.persistentDaemonSlot != nil if usesPersistentSSHPTY { + let remoteResumeCommand = approvedPersistentSSHResumeCommand( + for: resumeBinding, + panelID: panelId, + persistentPTYSessionID: sessionID + ) command = remotePTYAttachStartupCommand( sessionID: sessionID, + remoteCommand: remoteResumeCommand, requireExisting: !sessionEnded ) } else { diff --git a/Sources/Workspace+RemoteRelayCommandRewrite.swift b/Sources/Workspace+RemoteRelayCommandRewrite.swift new file mode 100644 index 000000000000..d425104f2511 --- /dev/null +++ b/Sources/Workspace+RemoteRelayCommandRewrite.swift @@ -0,0 +1,191 @@ +import Foundation + +extension Workspace { + private nonisolated static let remoteRelayWorkspaceIDKeys: Set = [ + "workspace_id", + "preferred_workspace_id", + "selected_workspace_id", + "before_workspace_id", + "after_workspace_id", + "from_workspace_id", + "to_workspace_id", + ] + + private nonisolated static let remoteRelaySurfaceIDKeys: Set = [ + "panel_id", + "surface_id", + "preferred_panel_id", + "preferred_surface_id", + "target_panel_id", + "target_surface_id", + "created_panel_id", + "created_surface_id", + "before_panel_id", + "before_surface_id", + "after_panel_id", + "after_surface_id", + ] + + private nonisolated static let remoteRelayAmbiguousIDKeys: Set = [ + "tab_id", + ] + + private nonisolated static let remoteRelayWorkspaceIDArrayKeys: Set = [ + "workspace_ids", + ] + + private nonisolated static let remoteRelaySurfaceIDArrayKeys: Set = [ + "panel_ids", + "surface_ids", + ] + + private nonisolated static let remoteRelayAmbiguousIDArrayKeys: Set = [ + "tab_ids", + "tab_id_groups", + ] + + nonisolated static func rewriteRemoteRelayCommandLine( + _ commandLine: Data, + workspaceAliases: [UUID: UUID], + surfaceAliases: [UUID: UUID], + remoteWorkspaceID: UUID? = nil + ) -> Data { + rewriteRemoteRelayCommandLineAndExtractMethod( + commandLine, + workspaceAliases: workspaceAliases, + surfaceAliases: surfaceAliases, + remoteWorkspaceID: remoteWorkspaceID + ).commandLine + } + + nonisolated static func rewriteRemoteRelayCommandLineAndExtractMethod( + _ commandLine: Data, + workspaceAliases: [UUID: UUID], + surfaceAliases: [UUID: UUID], + remoteWorkspaceID: UUID? = nil + ) -> (commandLine: Data, method: String?) { + guard !workspaceAliases.isEmpty || !surfaceAliases.isEmpty || remoteWorkspaceID != nil, + let line = String(data: commandLine, encoding: .utf8) else { + return (commandLine, nil) + } + let trimmedLine = line.trimmingCharacters(in: .whitespacesAndNewlines) + guard trimmedLine.hasPrefix("{"), + let requestData = trimmedLine.data(using: .utf8), + var request = try? JSONSerialization.jsonObject(with: requestData) as? [String: Any] else { + return (commandLine, nil) + } + let method = request["method"] as? String + + var didRewrite = false + if var params = request["params"] as? [String: Any] { + params = Self.remappedRemoteRelayValue( + params, + key: nil, + workspaceAliases: workspaceAliases, + surfaceAliases: surfaceAliases, + didRewrite: &didRewrite + ) as? [String: Any] ?? params + if method == "surface.resume.set", + let remoteWorkspaceID { + params["_cmux_remote_workspace_id"] = remoteWorkspaceID.uuidString + didRewrite = true + } + request["params"] = params + } + + guard didRewrite, + JSONSerialization.isValidJSONObject(request), + let rewritten = try? JSONSerialization.data(withJSONObject: request, options: []) else { + return (commandLine, method) + } + if commandLine.last == 0x0A { + return (rewritten + Data([0x0A]), method) + } + return (rewritten, method) + } + + private nonisolated static func remappedRemoteRelayValue( + _ value: Any, + key: String?, + workspaceAliases: [UUID: UUID], + surfaceAliases: [UUID: UUID], + didRewrite: inout Bool + ) -> Any { + if let dictionary = value as? [String: Any] { + var result = dictionary + for (childKey, childValue) in dictionary { + result[childKey] = remappedRemoteRelayValue( + childValue, + key: childKey, + workspaceAliases: workspaceAliases, + surfaceAliases: surfaceAliases, + didRewrite: &didRewrite + ) + } + return result + } + + if let array = value as? [Any] { + let elementKey: String? + if let key, remoteRelayWorkspaceIDArrayKeys.contains(key) { + elementKey = "workspace_id" + } else if let key, remoteRelaySurfaceIDArrayKeys.contains(key) { + elementKey = "surface_id" + } else if let key, remoteRelayAmbiguousIDArrayKeys.contains(key) { + elementKey = "tab_id" + } else if let key, remoteRelayWorkspaceIDKeys.contains(key) + || remoteRelaySurfaceIDKeys.contains(key) + || remoteRelayAmbiguousIDKeys.contains(key) { + elementKey = key + } else { + elementKey = nil + } + return array.map { + remappedRemoteRelayValue( + $0, + key: elementKey, + workspaceAliases: workspaceAliases, + surfaceAliases: surfaceAliases, + didRewrite: &didRewrite + ) + } + } + + guard let id = value as? String else { + return value + } + + let trimmedID = id.trimmingCharacters(in: .whitespacesAndNewlines) + guard let uuid = UUID(uuidString: trimmedID) else { + return value + } + + guard let key else { + return value + } + if remoteRelaySurfaceIDKeys.contains(key), + let mapped = surfaceAliases[uuid] { + didRewrite = true + return mapped.uuidString + } + if remoteRelayWorkspaceIDKeys.contains(key), + let mapped = workspaceAliases[uuid] { + didRewrite = true + return mapped.uuidString + } + guard remoteRelayAmbiguousIDKeys.contains(key) else { + return value + } + + if let mapped = workspaceAliases[uuid] { + didRewrite = true + return mapped.uuidString + } + if let mapped = surfaceAliases[uuid] { + didRewrite = true + return mapped.uuidString + } + + return value + } +} diff --git a/Sources/Workspace+RemoteSessionLifecycle.swift b/Sources/Workspace+RemoteSessionLifecycle.swift index 8d0189893307..f93d8b687110 100644 --- a/Sources/Workspace+RemoteSessionLifecycle.swift +++ b/Sources/Workspace+RemoteSessionLifecycle.swift @@ -115,7 +115,10 @@ extension Workspace { ), processRunner: processRunner, reachabilityProbe: RemoteHostReachabilityProbe(), - relayCommandRewriter: WorkspaceRemoteRelayCommandRewriter(), + relayCommandRewriter: WorkspaceRemoteRelayCommandRewriter( + remoteWorkspaceID: id, + remoteRelayTokenHex: configuration.relayToken ?? "" + ), buildInfo: WorkspaceRemoteSessionBuildInfo(), daemonStrings: RemoteDaemonStrings.appLocalized, strings: RemoteSessionStrings.appLocalized diff --git a/Sources/Workspace+RemoteSurfaceResumeBinding.swift b/Sources/Workspace+RemoteSurfaceResumeBinding.swift new file mode 100644 index 000000000000..aa1c01f8353c --- /dev/null +++ b/Sources/Workspace+RemoteSurfaceResumeBinding.swift @@ -0,0 +1,97 @@ +import Foundation + +extension Workspace { + /// Migrates a legacy binding only when its saved terminal has authoritative persistent-SSH ownership. + func migratingLegacyPersistentSSHResumeBinding( + _ binding: SurfaceResumeBindingSnapshot?, + snapshotWorkspaceID: UUID, + snapshotSurfaceID: UUID, + persistentPTYSessionID: String?, + restoresRemoteTerminal: Bool + ) -> SurfaceResumeBindingSnapshot? { + guard let binding, + restoresRemoteTerminal, + let persistentPTYSessionID = normalizedRemotePTYSessionID(persistentPTYSessionID), + let configuration = remoteConfiguration, + configuration.transport == .ssh, + configuration.preserveAfterTerminalExit, + !configuration.skipDaemonBootstrap, + configuration.persistentDaemonSlot != nil else { + return binding + } + return binding.migratingLegacyPersistentSSH(SurfaceResumeRemoteContext( + workspaceID: snapshotWorkspaceID, + surfaceID: snapshotSurfaceID, + persistentPTYSessionID: persistentPTYSessionID + )) + } + + func persistentSSHResumeContext(panelID: UUID) -> SurfaceResumeRemoteContext? { + guard let configuration = remoteConfiguration, + configuration.transport == .ssh, + configuration.preserveAfterTerminalExit, + !configuration.skipDaemonBootstrap, + configuration.persistentDaemonSlot != nil, + activeRemoteTerminalSurfaceIds.contains(panelID) else { + return nil + } + let sessionID = normalizedRemotePTYSessionID(remotePTYSessionIDsByPanelId[panelID]) + ?? Self.defaultSSHPTYSessionID(workspaceId: id, panelId: panelID) + return SurfaceResumeRemoteContext( + workspaceID: id, + surfaceID: panelID, + persistentPTYSessionID: sessionID + ) + } + + func persistentSSHResumeCommand( + for binding: SurfaceResumeBindingSnapshot?, + expectedWorkspaceID: UUID, + expectedSurfaceID: UUID, + persistentPTYSessionID: String + ) -> String? { + guard let binding, + case .persistentSSH(let context) = binding.launchFlavor, + context.matches( + workspaceID: expectedWorkspaceID, + surfaceID: expectedSurfaceID, + persistentPTYSessionID: persistentPTYSessionID + ), + let configuration = remoteConfiguration, + configuration.transport == .ssh, + configuration.preserveAfterTerminalExit, + !configuration.skipDaemonBootstrap, + configuration.persistentDaemonSlot != nil, + let relayPort = configuration.relayPort, + let startupInput = binding.remoteStartupInputWithLauncherScript(allowLauncherScript: false) else { + return nil + } + return SSHPTYAttachStartupCommandBuilder.restoredRemoteShellCommand( + relayPort: relayPort, + initialCommand: startupInput + ) + } + + func approvedPersistentSSHResumeCommand( + for binding: SurfaceResumeBindingSnapshot?, + panelID: UUID, + persistentPTYSessionID: String + ) -> String? { + guard let binding else { return nil } + let effectiveBinding = SurfaceResumeApprovalStore.applyingStoredApproval(to: binding) + if effectiveBinding.isAgentHookBinding, + !AgentSessionAutoResumeSettings.isEnabled(defaults: agentSessionAutoResumeDefaults) { + return nil + } + guard !effectiveBinding.requiresPromptApproval, + effectiveBinding.allowsAutomaticResume else { + return nil + } + return persistentSSHResumeCommand( + for: effectiveBinding, + expectedWorkspaceID: id, + expectedSurfaceID: panelID, + persistentPTYSessionID: persistentPTYSessionID + ) + } +} diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index fb9019843c9a..367380f41372 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -1260,13 +1260,10 @@ extension Workspace { switch snapshot.type { case .terminal: let snapshotRestorableAgent = snapshot.terminal?.agent - let resumeBinding = Self.resumeBindingForSessionRestore( - snapshot.terminal?.resumeBinding, - restorableAgent: snapshotRestorableAgent - ) + let persistedResumeBinding = snapshot.terminal?.resumeBinding let restorableAgent = Self.restorableAgentForSessionRestore( snapshotRestorableAgent, - resumeBinding: resumeBinding + resumeBinding: persistedResumeBinding ) let restoredHibernation = restorableAgent != nil ? snapshot.terminal?.hibernation : nil let autoResumeAgentSessions = AgentSessionAutoResumeSettings.isEnabled(defaults: agentSessionAutoResumeDefaults) @@ -1274,6 +1271,40 @@ extension Workspace { // wasAgentRunning == nil means a legacy snapshot; treat as true for backwards compatibility. let agentWasRunningAtQuit = snapshot.terminal?.wasAgentRunning ?? true let shouldAutoResumeAgent = autoResumeAgentSessions && agentWasRunningAtQuit + let remoteStartupCommand = remoteTerminalStartupCommand() + let restoresRemoteWorkspaceTerminalSnapshot = + remoteStartupCommand != nil && + (snapshot.terminal?.isRemoteTerminal != false || shouldRestoreSingleDefaultCloudTerminal) + let restoredRemotePTYSessionID: String? = { + guard !isDefaultFreestyleSSHDRemoteWorkspace else { + return nil + } + guard remoteConfiguration?.preserveAfterTerminalExit == true, + remoteConfiguration?.persistentDaemonSlot != nil else { + return nil + } + if let remotePTYSessionID = normalizedRemotePTYSessionID(snapshot.terminal?.remotePTYSessionID) { + return remotePTYSessionID + } + guard snapshot.terminal?.isRemoteTerminal == true else { + return nil + } + return Self.defaultSSHPTYSessionID(workspaceId: snapshotWorkspaceId ?? id, panelId: snapshot.id) + }() + let restoredResumeSnapshotWorkspaceID = snapshotWorkspaceId + ?? restoredRemotePTYSessionID.flatMap { Self.parsedDefaultSSHPTYSessionID($0)?.workspaceId } + ?? id + let locatedResumeBinding = migratingLegacyPersistentSSHResumeBinding( + persistedResumeBinding, + snapshotWorkspaceID: restoredResumeSnapshotWorkspaceID, + snapshotSurfaceID: snapshot.id, + persistentPTYSessionID: restoredRemotePTYSessionID, + restoresRemoteTerminal: restoresRemoteWorkspaceTerminalSnapshot + ) + let resumeBinding = Self.resumeBindingForSessionRestore( + locatedResumeBinding, + restorableAgent: restorableAgent + ) let resumeBindingForStartup = restoredHibernation != nil || (resumeBinding?.isProcessDetected == true && resumeBinding?.autoResume != true) @@ -1285,22 +1316,30 @@ extension Workspace { promptForApproval: true, approvalStoreURL: SurfaceResumeApprovalStore.defaultURL() ) - let remoteStartupCommand = remoteTerminalStartupCommand() - let restoresRemoteWorkspaceTerminalSnapshot = - remoteStartupCommand != nil && - (snapshot.terminal?.isRemoteTerminal != false || shouldRestoreSingleDefaultCloudTerminal) - let restoredBindingLaunch: SurfaceResumeStartupLaunch? = if restoresRemoteWorkspaceTerminalSnapshot { - effectiveResumeBindingForStartup?.remoteStartupInputWithLauncherScript(allowLauncherScript: false) - .map(SurfaceResumeStartupLaunch.input) + let restoredPersistentSSHResumeCommand: String? = if let restoredRemotePTYSessionID { + persistentSSHResumeCommand( + for: effectiveResumeBindingForStartup, + expectedWorkspaceID: restoredResumeSnapshotWorkspaceID, + expectedSurfaceID: snapshot.id, + persistentPTYSessionID: restoredRemotePTYSessionID + ) } else { + nil + } + let restoredBindingLaunch: SurfaceResumeStartupLaunch? = if effectiveResumeBindingForStartup?.launchFlavor == .local, + !restoresRemoteWorkspaceTerminalSnapshot { effectiveResumeBindingForStartup.flatMap { sessionRestorePolicy.surfaceResumeStartupLaunch( forApprovedBinding: $0, allowLauncherScript: true ) } + } else { + nil } - let effectiveResumeBinding = restoredBindingLaunch == nil ? nil : resumeBinding + let effectiveResumeBinding = restoredBindingLaunch != nil || restoredPersistentSSHResumeCommand != nil + ? resumeBinding + : nil let savedWorkingDirectory = effectiveResumeBinding?.cwd ?? (restoresUntrustedSavedDirectory ? nil : snapshot.terminal?.workingDirectory) ?? (restoresUntrustedSavedDirectory ? nil : restorableAgent?.workingDirectory) @@ -1374,24 +1413,11 @@ extension Workspace { } return nil }() - let restoredRemotePTYSessionID: String? = { - guard !isDefaultFreestyleSSHDRemoteWorkspace else { - return nil - } - guard remoteConfiguration?.preserveAfterTerminalExit == true, - remoteConfiguration?.persistentDaemonSlot != nil else { - return nil - } - if let remotePTYSessionID = normalizedRemotePTYSessionID(snapshot.terminal?.remotePTYSessionID) { - return remotePTYSessionID - } - guard snapshot.terminal?.isRemoteTerminal == true else { - return nil - } - return Self.defaultSSHPTYSessionID(workspaceId: snapshotWorkspaceId ?? id, panelId: snapshot.id) - }() let restoredRemotePTYAttachCommand = restoredRemotePTYSessionID.map { - remotePTYAttachStartupCommand(sessionID: $0) + remotePTYAttachStartupCommand( + sessionID: $0, + remoteCommand: restoredPersistentSSHResumeCommand + ) } let restoredStartupCommand = restoredRemotePTYAttachCommand @@ -1423,7 +1449,8 @@ extension Workspace { localWorkingDirectory ?? (startupHandlesWorkingDirectory ? workingDirectory : nil) let restoredAgentWillRunStartupCommand = restorableAgent != nil && ( restoredAgentResumeLaunch?.initialCommand != nil || - (restoredBindingLaunch?.initialCommand != nil && resumeBinding?.isAgentHookBinding == true) + (restoredBindingLaunch?.initialCommand != nil && resumeBinding?.isAgentHookBinding == true) || + (restoredPersistentSSHResumeCommand != nil && resumeBinding?.isAgentHookBinding == true) ) let restoredAgentWillRunStartupInput = restoredAgentResumeLaunch?.initialInput != nil || @@ -1518,7 +1545,13 @@ extension Workspace { ) } if let storedResumeBinding = effectiveResumeBindingForStartup ?? resumeBinding { - surfaceResumeBindingsByPanelId[terminalPanel.id] = storedResumeBinding + surfaceResumeBindingsByPanelId[terminalPanel.id] = storedResumeBinding.retargetingRemoteOwner( + expectedWorkspaceID: restoredResumeSnapshotWorkspaceID, + expectedSurfaceID: snapshot.id, + workspaceID: id, + surfaceID: terminalPanel.id, + persistentPTYSessionID: restoredRemotePTYSessionID + ) } else { surfaceResumeBindingsByPanelId.removeValue(forKey: terminalPanel.id) } @@ -5625,49 +5658,6 @@ final class Workspace: Identifiable, ObservableObject { return trimmed } - private nonisolated static let remoteRelayWorkspaceIDKeys: Set = [ - "workspace_id", - "preferred_workspace_id", - "selected_workspace_id", - "before_workspace_id", - "after_workspace_id", - "from_workspace_id", - "to_workspace_id", - ] - - private nonisolated static let remoteRelaySurfaceIDKeys: Set = [ - "panel_id", - "surface_id", - "preferred_panel_id", - "preferred_surface_id", - "target_panel_id", - "target_surface_id", - "created_panel_id", - "created_surface_id", - "before_panel_id", - "before_surface_id", - "after_panel_id", - "after_surface_id", - ] - - private nonisolated static let remoteRelayAmbiguousIDKeys: Set = [ - "tab_id", - ] - - private nonisolated static let remoteRelayWorkspaceIDArrayKeys: Set = [ - "workspace_ids", - ] - - private nonisolated static let remoteRelaySurfaceIDArrayKeys: Set = [ - "panel_ids", - "surface_ids", - ] - - private nonisolated static let remoteRelayAmbiguousIDArrayKeys: Set = [ - "tab_ids", - "tab_id_groups", - ] - func syncRemoteRelayIDAliasesToController() { remoteSessionController?.updateRemoteRelayIDAliases( workspaceAliases: remoteRelayWorkspaceIDAliases, @@ -5729,136 +5719,16 @@ final class Workspace: Identifiable, ObservableObject { } func rewriteRemoteRelayCommandLine(_ commandLine: Data) -> Data { - Self.rewriteRemoteRelayCommandLine( + WorkspaceRemoteRelayCommandRewriter( + remoteWorkspaceID: id, + remoteRelayTokenHex: remoteConfiguration?.relayToken ?? "" + ).rewriteRemoteRelayCommandLine( commandLine, workspaceAliases: remoteRelayWorkspaceIDAliases, surfaceAliases: remoteRelaySurfaceIDAliases ) } - nonisolated static func rewriteRemoteRelayCommandLine( - _ commandLine: Data, - workspaceAliases: [UUID: UUID], - surfaceAliases: [UUID: UUID] - ) -> Data { - guard !workspaceAliases.isEmpty || !surfaceAliases.isEmpty, - let line = String(data: commandLine, encoding: .utf8) else { - return commandLine - } - let trimmedLine = line.trimmingCharacters(in: .whitespacesAndNewlines) - guard trimmedLine.hasPrefix("{"), - let requestData = trimmedLine.data(using: .utf8), - var request = try? JSONSerialization.jsonObject(with: requestData) as? [String: Any] else { - return commandLine - } - - var didRewrite = false - if let params = request["params"] as? [String: Any] { - request["params"] = Self.remappedRemoteRelayValue( - params, - key: nil, - workspaceAliases: workspaceAliases, - surfaceAliases: surfaceAliases, - didRewrite: &didRewrite - ) - } - - guard didRewrite, - JSONSerialization.isValidJSONObject(request), - let rewritten = try? JSONSerialization.data(withJSONObject: request, options: []) else { - return commandLine - } - if commandLine.last == 0x0A { - return rewritten + Data([0x0A]) - } - return rewritten - } - - private nonisolated static func remappedRemoteRelayValue( - _ value: Any, - key: String?, - workspaceAliases: [UUID: UUID], - surfaceAliases: [UUID: UUID], - didRewrite: inout Bool - ) -> Any { - if let dictionary = value as? [String: Any] { - var result = dictionary - for (childKey, childValue) in dictionary { - result[childKey] = remappedRemoteRelayValue( - childValue, - key: childKey, - workspaceAliases: workspaceAliases, - surfaceAliases: surfaceAliases, - didRewrite: &didRewrite - ) - } - return result - } - - if let array = value as? [Any] { - let elementKey: String? - if let key, remoteRelayWorkspaceIDArrayKeys.contains(key) { - elementKey = "workspace_id" - } else if let key, remoteRelaySurfaceIDArrayKeys.contains(key) { - elementKey = "surface_id" - } else if let key, remoteRelayAmbiguousIDArrayKeys.contains(key) { - elementKey = "tab_id" - } else if let key, remoteRelayWorkspaceIDKeys.contains(key) - || remoteRelaySurfaceIDKeys.contains(key) - || remoteRelayAmbiguousIDKeys.contains(key) { - elementKey = key - } else { - elementKey = nil - } - return array.map { - remappedRemoteRelayValue( - $0, - key: elementKey, - workspaceAliases: workspaceAliases, - surfaceAliases: surfaceAliases, - didRewrite: &didRewrite - ) - } - } - - guard let id = value as? String else { - return value - } - - let trimmedID = id.trimmingCharacters(in: .whitespacesAndNewlines) - guard let uuid = UUID(uuidString: trimmedID) else { - return value - } - - guard let key else { - return value - } - if remoteRelaySurfaceIDKeys.contains(key), - let mapped = surfaceAliases[uuid] { - didRewrite = true - return mapped.uuidString - } - if remoteRelayWorkspaceIDKeys.contains(key), - let mapped = workspaceAliases[uuid] { - didRewrite = true - return mapped.uuidString - } - guard remoteRelayAmbiguousIDKeys.contains(key) else { - return value - } - - if let mapped = workspaceAliases[uuid] { - didRewrite = true - return mapped.uuidString - } - if let mapped = surfaceAliases[uuid] { - didRewrite = true - return mapped.uuidString - } - - return value - } - private func remotePTYSessionIDForSnapshot(panelId: UUID) -> String? { guard remoteConfiguration?.preserveAfterTerminalExit == true else { return nil @@ -5895,18 +5765,31 @@ final class Workspace: Identifiable, ObservableObject { return (workspaceId, panelId) } - nonisolated static func sshPTYAttachStartupCommand(sessionID: String, requireExisting: Bool = true) -> String { - SSHPTYAttachStartupCommandBuilder.command(sessionID: sessionID, requireExisting: requireExisting) + nonisolated static func sshPTYAttachStartupCommand( + sessionID: String, + remoteCommand: String? = nil, + requireExisting: Bool = true + ) -> String { + SSHPTYAttachStartupCommandBuilder.command( + sessionID: sessionID, + remoteCommand: remoteCommand, + requireExisting: requireExisting + ) } func remotePTYAttachStartupCommand( sessionID: String, + remoteCommand: String? = nil, requireExisting: Bool = true ) -> String { guard let remoteConfiguration, remoteConfiguration.preserveAfterTerminalExit, let foregroundAuthToken = remoteConfiguration.foregroundAuthToken else { - return Self.sshPTYAttachStartupCommand(sessionID: sessionID, requireExisting: requireExisting) + return Self.sshPTYAttachStartupCommand( + sessionID: sessionID, + remoteCommand: remoteCommand, + requireExisting: requireExisting + ) } let foregroundAuth = SSHPTYAttachStartupCommandBuilder.ForegroundAuth( destination: remoteConfiguration.destination, @@ -5918,6 +5801,7 @@ final class Workspace: Identifiable, ObservableObject { return SSHPTYAttachStartupCommandBuilder.command( sessionID: sessionID, foregroundAuth: foregroundAuth, + remoteCommand: remoteCommand, requireExisting: requireExisting ) } @@ -9250,6 +9134,15 @@ final class Workspace: Identifiable, ObservableObject { detached.panelId, preserveTrustedRemoteDirectory: detached.directoryIsTrustedRemoteReport ) + if let resumeBinding = surfaceResumeBindingsByPanelId[detached.panelId] { + surfaceResumeBindingsByPanelId[detached.panelId] = resumeBinding.retargetingRemoteOwner( + expectedWorkspaceID: detached.sourceWorkspaceId, + expectedSurfaceID: detached.panelId, + workspaceID: id, + surfaceID: detached.panelId, + persistentPTYSessionID: remotePTYSessionIDsByPanelId[detached.panelId] + ) + } } if let cleanupConfiguration = detached.remoteCleanupConfiguration { if didAdoptWorkspaceRemoteTracking { diff --git a/Sources/WorkspaceRemoteRelayCommandRewriter.swift b/Sources/WorkspaceRemoteRelayCommandRewriter.swift index 62fd4d7e8779..b4f475375194 100644 --- a/Sources/WorkspaceRemoteRelayCommandRewriter.swift +++ b/Sources/WorkspaceRemoteRelayCommandRewriter.swift @@ -1,19 +1,110 @@ import CmuxRemoteWorkspace +import CryptoKit import Foundation /// App-side conformance to the relay's command-rewrite seam: forwards to the /// workspace model's alias-aware static rewrite so the package never imports /// `Workspace`. struct WorkspaceRemoteRelayCommandRewriter: RemoteRelayCommandRewriting { + private static let authenticationCodeKey = "_cmux_remote_relay_authentication_code" + + let remoteWorkspaceID: UUID + let remoteRelayTokenHex: String + func rewriteRemoteRelayCommandLine( _ commandLine: Data, workspaceAliases: [UUID: UUID], surfaceAliases: [UUID: UUID] ) -> Data { - Workspace.rewriteRemoteRelayCommandLine( + let rewritten = Workspace.rewriteRemoteRelayCommandLineAndExtractMethod( commandLine, workspaceAliases: workspaceAliases, - surfaceAliases: surfaceAliases + surfaceAliases: surfaceAliases, + remoteWorkspaceID: remoteWorkspaceID + ) + // Method classification is a trust boundary; decoded JSON honors escapes that raw bytes do not. + guard rewritten.method == "surface.resume.set" else { return rewritten.commandLine } + return authenticatedRemoteResumeCommandLine(rewritten.commandLine) + } + + static func authenticatesRemoteResumeParameters( + _ params: [String: Any], + remoteRelayTokenHex: String? + ) -> Bool { + guard let remoteRelayTokenHex, + let authenticationCode = params[authenticationCodeKey] as? String, + let payload = authenticationPayload(params), + let relayToken = hexData(remoteRelayTokenHex), + let receivedCode = hexData(authenticationCode) else { + return false + } + return HMAC.isValidAuthenticationCode( + receivedCode, + authenticating: payload, + using: SymmetricKey(data: relayToken) + ) + } + + private func authenticatedRemoteResumeCommandLine(_ commandLine: Data) -> Data { + guard let line = String(data: commandLine, encoding: .utf8), + let requestData = line.trimmingCharacters(in: .whitespacesAndNewlines).data(using: .utf8), + var request = try? JSONSerialization.jsonObject(with: requestData) as? [String: Any], + request["method"] as? String == "surface.resume.set", + var params = request["params"] as? [String: Any], + let payload = Self.authenticationPayload(params), + let relayToken = Self.hexData(remoteRelayTokenHex) else { + return commandLine + } + let authenticationCode = HMAC.authenticationCode( + for: payload, + using: SymmetricKey(data: relayToken) ) + params[Self.authenticationCodeKey] = Self.hexString(authenticationCode) + request["params"] = params + guard let authenticated = try? JSONSerialization.data(withJSONObject: request) else { + return commandLine + } + return commandLine.last == 0x0A ? authenticated + Data([0x0A]) : authenticated + } + + private static func authenticationPayload(_ params: [String: Any]) -> Data? { + var authenticatedParams = params + authenticatedParams.removeValue(forKey: authenticationCodeKey) + guard JSONSerialization.isValidJSONObject(authenticatedParams) else { return nil } + return try? JSONSerialization.data(withJSONObject: authenticatedParams, options: [.sortedKeys]) + } + + private static func hexData(_ value: String) -> Data? { + let bytes = Array(value.utf8) + guard !bytes.isEmpty, bytes.count.isMultiple(of: 2) else { return nil } + var decoded = Data(capacity: bytes.count / 2) + var index = 0 + while index < bytes.count { + guard let high = hexNibble(bytes[index]), + let low = hexNibble(bytes[index + 1]) else { return nil } + decoded.append((high << 4) | low) + index += 2 + } + return decoded + } + + private static func hexNibble(_ byte: UInt8) -> UInt8? { + switch byte { + case 48 ... 57: byte - 48 + case 65 ... 70: byte - 55 + case 97 ... 102: byte - 87 + default: nil + } + } + + private static func hexString(_ bytes: S) -> String where S.Element == UInt8 { + let alphabet = Array("0123456789abcdef".utf8) + var encoded: [UInt8] = [] + encoded.reserveCapacity(bytes.underestimatedCount * 2) + for byte in bytes { + encoded.append(alphabet[Int(byte >> 4)]) + encoded.append(alphabet[Int(byte & 0x0f)]) + } + return String(decoding: encoded, as: UTF8.self) } } diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 980118a18e3e..30d216c817a0 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -1261,6 +1261,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources E30790000000000000000004 /* RemotePTYBridgeStrings+App.swift in Sources */ = {isa = PBXBuildFile; fileRef = E30790000000000000000003 /* RemotePTYBridgeStrings+App.swift */; }; A5001640 /* RemoteRelayZshBootstrap.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001641 /* RemoteRelayZshBootstrap.swift */; }; B9000027A1B2C3D4E5F60719 /* RemoteRelayZshBootstrap.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001641 /* RemoteRelayZshBootstrap.swift */; }; + 7989A0017989A0017989A001 /* RemoteResumeBindingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7989A0027989A0027989A002 /* RemoteResumeBindingTests.swift */; }; REE0CA0000000000000000D2 /* RemoteRouteSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = REE0CA0000000000000000D1 /* RemoteRouteSpec.swift */; }; REE0CA0000000000000000A2 /* RemotesClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = REE0CA0000000000000000A1 /* RemotesClient.swift */; }; C1A070000000000000000007 /* RemotesClientError.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A070000000000000000017 /* RemotesClientError.swift */; }; @@ -1705,8 +1706,11 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources D7AB00000000000000B041 /* SupersededPhoneDismissBuffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB00000000000000B040 /* SupersededPhoneDismissBuffer.swift */; }; F6572012A1B2C3D4E5F60718 /* SurfaceResumeBindingCodexUpdateCheckTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6572013A1B2C3D4E5F60718 /* SurfaceResumeBindingCodexUpdateCheckTests.swift */; }; F0ACC0DE000000000000000F /* SurfaceResumeBindingIndex.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0ACC0DE0000000000000010 /* SurfaceResumeBindingIndex.swift */; }; + 7989B0017989B0017989B001 /* SurfaceResumeBindingSnapshot+Remote.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7989B1017989B1017989B101 /* SurfaceResumeBindingSnapshot+Remote.swift */; }; F6572010A1B2C3D4E5F60718 /* SurfaceResumeCommandCanonicalizer+CodexUpdateCheck.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6572011A1B2C3D4E5F60718 /* SurfaceResumeCommandCanonicalizer+CodexUpdateCheck.swift */; }; F6572000A1B2C3D4E5F60718 /* SurfaceResumeCommandCanonicalizer+PortableAgentExecutable.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6572001A1B2C3D4E5F60718 /* SurfaceResumeCommandCanonicalizer+PortableAgentExecutable.swift */; }; + 7989B0027989B0027989B002 /* SurfaceResumeLaunchFlavor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7989B1027989B1027989B102 /* SurfaceResumeLaunchFlavor.swift */; }; + 7989B0037989B0037989B003 /* SurfaceResumeRemoteContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7989B1037989B1037989B103 /* SurfaceResumeRemoteContext.swift */; }; A5001303 /* SurfaceSearchOverlay.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001301 /* SurfaceSearchOverlay.swift */; }; A7206A010000000000000001 /* SystemAppearanceObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7206A020000000000000001 /* SystemAppearanceObserver.swift */; }; A7206F010000000000000001 /* SystemAppearanceObserverEnvironment.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7206F020000000000000001 /* SystemAppearanceObserverEnvironment.swift */; }; @@ -2005,7 +2009,9 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources C3744E010000000000000001 /* Workspace+PanelLifecycle.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3744E020000000000000001 /* Workspace+PanelLifecycle.swift */; }; 797800030000000000000001 /* Workspace+PersistentRemotePTYReattach.swift in Sources */ = {isa = PBXBuildFile; fileRef = 797800030000000000000002 /* Workspace+PersistentRemotePTYReattach.swift */; }; 791100010000000000000001 /* Workspace+RemoteDisconnectPlaceholder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 791100020000000000000001 /* Workspace+RemoteDisconnectPlaceholder.swift */; }; + 7989B0057989B0057989B005 /* Workspace+RemoteRelayCommandRewrite.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7989B1057989B1057989B105 /* Workspace+RemoteRelayCommandRewrite.swift */; }; 806100010000000000000001 /* Workspace+RemoteSessionLifecycle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 806100010000000000000002 /* Workspace+RemoteSessionLifecycle.swift */; }; + 7989B0047989B0047989B004 /* Workspace+RemoteSurfaceResumeBinding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7989B1047989B1047989B104 /* Workspace+RemoteSurfaceResumeBinding.swift */; }; 7738C0037738C0037738C003 /* Workspace+RemoteTmuxControlTopology.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7738D0037738D0037738D003 /* Workspace+RemoteTmuxControlTopology.swift */; }; D77340010000000000000002 /* Workspace+RemoteTmuxTabOrder.swift in Sources */ = {isa = PBXBuildFile; fileRef = D77340010000000000000001 /* Workspace+RemoteTmuxTabOrder.swift */; }; C548600A000000000000001 /* Workspace+SessionRestoreIdentity.swift in Sources */ = {isa = PBXBuildFile; fileRef = C548600A000000000000002 /* Workspace+SessionRestoreIdentity.swift */; }; @@ -3361,6 +3367,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = D0C0D0C0D0C0D0C0D0C00004 /* RemoteLoopbackRuntimeBridge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteLoopbackRuntimeBridge.swift; sourceTree = ""; }; E30790000000000000000003 /* RemotePTYBridgeStrings+App.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RemotePTYBridgeStrings+App.swift"; sourceTree = ""; }; A5001641 /* RemoteRelayZshBootstrap.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteRelayZshBootstrap.swift; sourceTree = ""; }; + 7989A0027989A0027989A002 /* RemoteResumeBindingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteResumeBindingTests.swift; sourceTree = ""; }; REE0CA0000000000000000D1 /* RemoteRouteSpec.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = RemoteRouteSpec.swift; sourceTree = ""; }; REE0CA0000000000000000A1 /* RemotesClient.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = RemotesClient.swift; sourceTree = ""; }; C1A070000000000000000017 /* RemotesClientError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = RemotesClientError.swift; sourceTree = ""; }; @@ -3793,8 +3800,11 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = D7AB00000000000000B040 /* SupersededPhoneDismissBuffer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SupersededPhoneDismissBuffer.swift; sourceTree = ""; }; F6572013A1B2C3D4E5F60718 /* SurfaceResumeBindingCodexUpdateCheckTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SurfaceResumeBindingCodexUpdateCheckTests.swift; sourceTree = ""; }; F0ACC0DE0000000000000010 /* SurfaceResumeBindingIndex.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SurfaceResumeBindingIndex.swift; sourceTree = ""; }; + 7989B1017989B1017989B101 /* SurfaceResumeBindingSnapshot+Remote.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "SurfaceResumeBindingSnapshot+Remote.swift"; sourceTree = ""; }; F6572011A1B2C3D4E5F60718 /* SurfaceResumeCommandCanonicalizer+CodexUpdateCheck.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "SurfaceResumeCommandCanonicalizer+CodexUpdateCheck.swift"; sourceTree = ""; }; F6572001A1B2C3D4E5F60718 /* SurfaceResumeCommandCanonicalizer+PortableAgentExecutable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "SurfaceResumeCommandCanonicalizer+PortableAgentExecutable.swift"; sourceTree = ""; }; + 7989B1027989B1027989B102 /* SurfaceResumeLaunchFlavor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SurfaceResumeLaunchFlavor.swift; sourceTree = ""; }; + 7989B1037989B1037989B103 /* SurfaceResumeRemoteContext.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SurfaceResumeRemoteContext.swift; sourceTree = ""; }; A5001301 /* SurfaceSearchOverlay.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Find/SurfaceSearchOverlay.swift; sourceTree = ""; }; A7206A020000000000000001 /* SystemAppearanceObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SystemAppearanceObserver.swift; sourceTree = ""; }; A7206F020000000000000001 /* SystemAppearanceObserverEnvironment.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SystemAppearanceObserverEnvironment.swift; sourceTree = ""; }; @@ -4093,7 +4103,9 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C3744E020000000000000001 /* Workspace+PanelLifecycle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+PanelLifecycle.swift"; sourceTree = ""; }; 797800030000000000000002 /* Workspace+PersistentRemotePTYReattach.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+PersistentRemotePTYReattach.swift"; sourceTree = ""; }; 791100020000000000000001 /* Workspace+RemoteDisconnectPlaceholder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+RemoteDisconnectPlaceholder.swift"; sourceTree = ""; }; + 7989B1057989B1057989B105 /* Workspace+RemoteRelayCommandRewrite.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+RemoteRelayCommandRewrite.swift"; sourceTree = ""; }; 806100010000000000000002 /* Workspace+RemoteSessionLifecycle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+RemoteSessionLifecycle.swift"; sourceTree = ""; }; + 7989B1047989B1047989B104 /* Workspace+RemoteSurfaceResumeBinding.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+RemoteSurfaceResumeBinding.swift"; sourceTree = ""; }; 7738D0037738D0037738D003 /* Workspace+RemoteTmuxControlTopology.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+RemoteTmuxControlTopology.swift"; sourceTree = ""; }; D77340010000000000000001 /* Workspace+RemoteTmuxTabOrder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+RemoteTmuxTabOrder.swift"; sourceTree = ""; }; C548600A000000000000002 /* Workspace+SessionRestoreIdentity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+SessionRestoreIdentity.swift"; sourceTree = ""; }; @@ -4893,6 +4905,8 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 791100020000000000000001 /* Workspace+RemoteDisconnectPlaceholder.swift */, 797800030000000000000002 /* Workspace+PersistentRemotePTYReattach.swift */, 806100010000000000000002 /* Workspace+RemoteSessionLifecycle.swift */, + 7989B1057989B1057989B105 /* Workspace+RemoteRelayCommandRewrite.swift */, + 7989B1047989B1047989B104 /* Workspace+RemoteSurfaceResumeBinding.swift */, 8300A0030000000000000003 /* Workspace+SSHConnectionBroker.swift */, 791102020000000000000001 /* RemoteDisconnectPreparationService.swift */, C0DE43000000000000000008 /* Workspace+AgentChat.swift */, @@ -5530,6 +5544,9 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = CD0CFE6300000000CD0CFE63 /* HostSettingsActions.swift */, F6572001A1B2C3D4E5F60718 /* SurfaceResumeCommandCanonicalizer+PortableAgentExecutable.swift */, F6572011A1B2C3D4E5F60718 /* SurfaceResumeCommandCanonicalizer+CodexUpdateCheck.swift */, + 7989B1017989B1017989B101 /* SurfaceResumeBindingSnapshot+Remote.swift */, + 7989B1027989B1027989B102 /* SurfaceResumeLaunchFlavor.swift */, + 7989B1037989B1037989B103 /* SurfaceResumeRemoteContext.swift */, A74770010000000000000006 /* SessionConfigFrameEntry.swift */, A74770010000000000000008 /* SessionConfigFrameRing.swift */, A74770010000000000000004 /* SessionDisplaySnapshot.swift */, @@ -5907,6 +5924,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B79500300000000000000002 /* PortScannerPublicationTests.swift */, B79500320000000000000002 /* PortScannerIdentityContinuityTests.swift */, F6572003A1B2C3D4E5F60718 /* SessionPersistenceResumeBindingTests.swift */, + 7989A0027989A0027989A002 /* RemoteResumeBindingTests.swift */, 812600000000000000000004 /* SessionRemoteWorkspaceMoshRestoreTests.swift */, F6572013A1B2C3D4E5F60718 /* SurfaceResumeBindingCodexUpdateCheckTests.swift */, F5000001A1B2C3D4E5F60718 /* SessionPersistenceTests.swift */, @@ -7904,8 +7922,11 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = D35B71010000000000000001 /* StartupBreadcrumbLog.swift in Sources */, D7AB00000000000000B041 /* SupersededPhoneDismissBuffer.swift in Sources */, F0ACC0DE000000000000000F /* SurfaceResumeBindingIndex.swift in Sources */, + 7989B0017989B0017989B001 /* SurfaceResumeBindingSnapshot+Remote.swift in Sources */, F6572010A1B2C3D4E5F60718 /* SurfaceResumeCommandCanonicalizer+CodexUpdateCheck.swift in Sources */, F6572000A1B2C3D4E5F60718 /* SurfaceResumeCommandCanonicalizer+PortableAgentExecutable.swift in Sources */, + 7989B0027989B0027989B002 /* SurfaceResumeLaunchFlavor.swift in Sources */, + 7989B0037989B0037989B003 /* SurfaceResumeRemoteContext.swift in Sources */, A5001303 /* SurfaceSearchOverlay.swift in Sources */, A7206A010000000000000001 /* SystemAppearanceObserver.swift in Sources */, A7206F010000000000000001 /* SystemAppearanceObserverEnvironment.swift in Sources */, @@ -8146,7 +8167,9 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C3744E010000000000000001 /* Workspace+PanelLifecycle.swift in Sources */, 797800030000000000000001 /* Workspace+PersistentRemotePTYReattach.swift in Sources */, 791100010000000000000001 /* Workspace+RemoteDisconnectPlaceholder.swift in Sources */, + 7989B0057989B0057989B005 /* Workspace+RemoteRelayCommandRewrite.swift in Sources */, 806100010000000000000001 /* Workspace+RemoteSessionLifecycle.swift in Sources */, + 7989B0047989B0047989B004 /* Workspace+RemoteSurfaceResumeBinding.swift in Sources */, 7738C0037738C0037738C003 /* Workspace+RemoteTmuxControlTopology.swift in Sources */, D77340010000000000000002 /* Workspace+RemoteTmuxTabOrder.swift in Sources */, C548600A000000000000001 /* Workspace+SessionRestoreIdentity.swift in Sources */, @@ -8701,6 +8724,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 791100030000000000000001 /* RemoteDisconnectLifecycleTests.swift in Sources */, 835000000000000000000006 /* RemoteInitialCommandBootstrapFailureTests.swift in Sources */, 835000000000000000000004 /* RemoteInitialCommandBootstrapTests.swift in Sources */, + 7989A0017989A0017989A001 /* RemoteResumeBindingTests.swift in Sources */, REE0CA0000000000000000B2 /* RemotesClientTests.swift in Sources */, 806100020000000000000001 /* RemoteSessionCleanupLifecycleTests.swift in Sources */, C0F674600000000000000001 /* RemoteShellCWDRelayTests.swift in Sources */, diff --git a/cmuxTests/RemoteInitialCommandBootstrapFailureTests.swift b/cmuxTests/RemoteInitialCommandBootstrapFailureTests.swift index 87c2b717780b..50731a0e14aa 100644 --- a/cmuxTests/RemoteInitialCommandBootstrapFailureTests.swift +++ b/cmuxTests/RemoteInitialCommandBootstrapFailureTests.swift @@ -132,7 +132,7 @@ struct RemoteInitialCommandBootstrapFailureTests { } @Test - func unsupportedShellDoesNotRunOrConsumeCommand() throws { + func unsupportedShellRunsAndConsumesCommandOnlyOnce() throws { let fileManager = FileManager.default let root = fileManager.temporaryDirectory .appendingPathComponent("cmux-remote-initial-command-unsupported-shell-\(UUID().uuidString)") @@ -171,17 +171,12 @@ struct RemoteInitialCommandBootstrapFailureTests { let unsupported = try runShell(script, environment: unsupportedEnvironment) #expect(unsupported.status == 0, Comment(rawValue: unsupported.stderr)) #expect(try String(contentsOf: invocations, encoding: .utf8) == "1\n-i\n") - #expect(!fileManager.fileExists(atPath: output.path)) - #expect(try initialCommandMarkerCount(home: home) == 0) - let warning = String( - localized: "cli.ssh.initialCommand.unsupportedShell", - defaultValue: "[cmux] Initial command was not run because cmux does not support initial commands for this remote login shell. Reconnect with a supported shell to retry it." - ) - #expect(unsupported.stderr.contains(warning), Comment(rawValue: unsupported.stderr)) + #expect(try String(contentsOf: output, encoding: .utf8) == "must wait\n") + #expect(try initialCommandMarkerCount(home: home) == 1) - let supportedEnvironment = unsupportedEnvironment.merging(["SHELL": "/bin/sh"]) { _, new in new } - let retry = try runShell(script, environment: supportedEnvironment) + let retry = try runShell(script, environment: unsupportedEnvironment) #expect(retry.status == 0, Comment(rawValue: retry.stderr)) + let supportedEnvironment = unsupportedEnvironment.merging(["SHELL": "/bin/sh"]) { _, new in new } let reattach = try runShell(script, environment: supportedEnvironment) #expect(reattach.status == 0, Comment(rawValue: reattach.stderr)) diff --git a/cmuxTests/RemoteResumeBindingTests.swift b/cmuxTests/RemoteResumeBindingTests.swift new file mode 100644 index 000000000000..dc2c54fe1179 --- /dev/null +++ b/cmuxTests/RemoteResumeBindingTests.swift @@ -0,0 +1,1172 @@ +import AppKit +import CmuxCore +import Darwin +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +private final class RemoteResumeHookCapture: @unchecked Sendable { + private let lock = NSLock() + private var commands: [String] = [] + + func append(_ command: String) { + lock.lock() + commands.append(command) + lock.unlock() + } + + func snapshot() -> [String] { + lock.lock() + defer { lock.unlock() } + return commands + } +} + +private enum RemoteResumeHookSocketServer { + static func start( + listenerFD: Int32, + capture: RemoteResumeHookCapture, + surfaceID: UUID + ) -> DispatchSemaphore { + let finished = DispatchSemaphore(value: 0) + DispatchQueue.global(qos: .userInitiated).async { + defer { finished.signal() } + var clientAddress = sockaddr_un() + var clientAddressLength = socklen_t(MemoryLayout.size) + let clientFD = withUnsafeMutablePointer(to: &clientAddress) { pointer in + pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { socketAddress in + Darwin.accept(listenerFD, socketAddress, &clientAddressLength) + } + } + guard clientFD >= 0 else { return } + defer { Darwin.close(clientFD) } + + var pending = Data() + var buffer = [UInt8](repeating: 0, count: 4_096) + while true { + let count = Darwin.read(clientFD, &buffer, buffer.count) + if count < 0 { + if errno == EINTR { continue } + return + } + if count == 0 { return } + pending.append(buffer, count: count) + + while let newline = pending.firstIndex(of: 0x0A) { + let lineData = pending.subdata(in: 0.. String { + guard let data = line.data(using: .utf8), + let request = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let id = request["id"] as? String, + let method = request["method"] as? String else { + return "OK" + } + let result: [String: Any] + switch method { + case "surface.list": + result = [ + "id": id, + "ok": true, + "result": [ + "surfaces": [[ + "id": surfaceID.uuidString, + "ref": "surface:1", + "index": 1, + "focused": true, + ]], + ], + ] + case "surface.resume.set", "feed.push": + result = ["id": id, "ok": true, "result": ["ok": true]] + default: + result = [ + "id": id, + "ok": false, + "error": [ + "code": "unrecognized_method", + "message": "unexpected method: \(method)", + ], + ] + } + let responseData = (try? JSONSerialization.data(withJSONObject: result)) ?? Data("{}".utf8) + return String(decoding: responseData, as: UTF8.self) + } + + private static func write(_ response: String, to fileDescriptor: Int32) { + let bytes = Array((response + "\n").utf8) + bytes.withUnsafeBytes { rawBuffer in + guard var cursor = rawBuffer.bindMemory(to: UInt8.self).baseAddress else { return } + var remaining = rawBuffer.count + while remaining > 0 { + let count = Darwin.write(fileDescriptor, cursor, remaining) + if count > 0 { + cursor = cursor.advanced(by: count) + remaining -= count + } else if count < 0, errno == EINTR { + continue + } else { + return + } + } + } + } +} + +@Suite(.serialized) +@MainActor +struct RemoteResumeBindingTests { + private let relayPort = 64_089 + + private struct HookRunResult { + let status: Int32 + let stderr: String + let timedOut: Bool + let commands: [String] + } + + @Test + func emptyPersistentSessionIDsNeverMatch() { + let workspaceID = UUID() + let surfaceID = UUID() + let context = SurfaceResumeRemoteContext( + workspaceID: workspaceID, + surfaceID: surfaceID, + persistentPTYSessionID: "" + ) + + #expect(!context.matches( + workspaceID: workspaceID, + surfaceID: surfaceID, + persistentPTYSessionID: " " + )) + } + + @Test + func escapedResumeMethodRetainsAuthenticatedRemoteProvenance() throws { + let workspaceID = UUID() + let relayToken = String(repeating: "b", count: 64) + let commandLine = Data( + #"{"id":"escaped-resume","method":"surface.resume\u002eset","params":{"command":"codex resume escaped-session"}}"#.utf8 + ) + + let rewritten = WorkspaceRemoteRelayCommandRewriter( + remoteWorkspaceID: workspaceID, + remoteRelayTokenHex: relayToken + ).rewriteRemoteRelayCommandLine( + commandLine, + workspaceAliases: [:], + surfaceAliases: [:] + ) + let request = try #require( + JSONSerialization.jsonObject(with: rewritten) as? [String: Any] + ) + let params = try #require(request["params"] as? [String: Any]) + + #expect(params["_cmux_remote_workspace_id"] as? String == workspaceID.uuidString) + #expect(WorkspaceRemoteRelayCommandRewriter.authenticatesRemoteResumeParameters( + params, + remoteRelayTokenHex: relayToken + )) + } + + @Test + func remoteResumeProvenanceRequiresExactMethodAndUntamperedAuthentication() throws { + let workspaceID = UUID() + let relayToken = String(repeating: "c", count: 64) + let rewriter = WorkspaceRemoteRelayCommandRewriter( + remoteWorkspaceID: workspaceID, + remoteRelayTokenHex: relayToken + ) + let request: [String: Any] = [ + "id": "authenticated-resume", + "method": "surface.resume.set", + "params": [ + "workspace_id": workspaceID.uuidString, + "surface_id": UUID().uuidString, + "command": "codex resume authenticated-session", + ], + ] + let rewritten = rewriter.rewriteRemoteRelayCommandLine( + try requestData(request), + workspaceAliases: [:], + surfaceAliases: [:] + ) + let rewrittenRequest = try jsonRequest(rewritten) + let authenticatedParams = try #require(rewrittenRequest["params"] as? [String: Any]) + + #expect(authenticatedParams["_cmux_remote_workspace_id"] as? String == workspaceID.uuidString) + #expect(WorkspaceRemoteRelayCommandRewriter.authenticatesRemoteResumeParameters( + authenticatedParams, + remoteRelayTokenHex: relayToken + )) + + for authenticationCode in [nil, "", "0", "not-hex", String(repeating: "0", count: 64)] as [String?] { + var invalidParams = authenticatedParams + invalidParams["_cmux_remote_relay_authentication_code"] = authenticationCode + #expect(!WorkspaceRemoteRelayCommandRewriter.authenticatesRemoteResumeParameters( + invalidParams, + remoteRelayTokenHex: relayToken + )) + } + + var missingProvenance = authenticatedParams + missingProvenance.removeValue(forKey: "_cmux_remote_workspace_id") + #expect(!WorkspaceRemoteRelayCommandRewriter.authenticatesRemoteResumeParameters( + missingProvenance, + remoteRelayTokenHex: relayToken + )) + + var tampered = authenticatedParams + tampered["command"] = "codex resume attacker-session" + #expect(!WorkspaceRemoteRelayCommandRewriter.authenticatesRemoteResumeParameters( + tampered, + remoteRelayTokenHex: relayToken + )) + + for method in ["surface.resume.get", "surface.resume.set.backup", "surface.resume.setter", "custom.surface.resume.set"] { + let unrelated: [String: Any] = [ + "id": "unrelated-\(method)", + "method": method, + "params": ["command": "must remain unauthenticated"], + ] + let original = try requestData(unrelated) + let unrelatedResult = rewriter.rewriteRemoteRelayCommandLine( + original, + workspaceAliases: [:], + surfaceAliases: [:] + ) + #expect(unrelatedResult == original) + let unrelatedParams = try #require(try jsonRequest(unrelatedResult)["params"] as? [String: Any]) + #expect(unrelatedParams["_cmux_remote_workspace_id"] == nil) + #expect(unrelatedParams["_cmux_remote_relay_authentication_code"] == nil) + } + } + + @Test + func remoteContextRejectsWrongOwnersAndBlankPersistentSessions() { + let workspaceID = UUID() + let surfaceID = UUID() + let context = SurfaceResumeRemoteContext( + workspaceID: workspaceID, + surfaceID: surfaceID, + persistentPTYSessionID: "session-owned" + ) + + #expect(context.matches( + workspaceID: workspaceID, + surfaceID: surfaceID, + persistentPTYSessionID: " session-owned\n" + )) + #expect(!context.matches( + workspaceID: UUID(), + surfaceID: surfaceID, + persistentPTYSessionID: "session-owned" + )) + #expect(!context.matches( + workspaceID: workspaceID, + surfaceID: UUID(), + persistentPTYSessionID: "session-owned" + )) + #expect(!context.matches( + workspaceID: workspaceID, + surfaceID: surfaceID, + persistentPTYSessionID: "session-other" + )) + #expect(!context.matches( + workspaceID: workspaceID, + surfaceID: surfaceID, + persistentPTYSessionID: " \t\n " + )) + let blankStoredContext = SurfaceResumeRemoteContext( + workspaceID: workspaceID, + surfaceID: surfaceID, + persistentPTYSessionID: " \t\n " + ) + #expect(!blankStoredContext.matches( + workspaceID: workspaceID, + surfaceID: surfaceID, + persistentPTYSessionID: "session-owned" + )) + } + + @Test + func bundledKiroSessionStartRegistersAuthenticatedRemoteBinding() throws { + _ = NSApplication.shared + let previousAppDelegate = AppDelegate.shared + let app = AppDelegate() + let windowID = UUID() + let window = makeMainWindow(id: windowID) + defer { + TerminalController.shared.setActiveTabManager(nil) + app.unregisterMainWindowContextForTesting(windowId: windowID) + AppDelegate.shared = previousAppDelegate + window.orderOut(nil) + } + + let manager = TabManager(autoWelcomeIfNeeded: false) + app.registerMainWindow( + window, + windowId: windowID, + tabManager: manager, + sidebarState: SidebarState(), + sidebarSelectionState: SidebarSelectionState(), + fileExplorerState: FileExplorerState() + ) + TerminalController.shared.setActiveTabManager(manager) + + let workspace = try #require(manager.selectedWorkspace) + let surfaceID = try #require(workspace.focusedPanelId) + workspace.configureRemoteConnection(remoteConfiguration(), autoConnect: false) + + let relayedWorkspaceID = UUID() + let relayedSurfaceID = UUID() + let remotePTYSessionID = Workspace.defaultSSHPTYSessionID( + workspaceId: relayedWorkspaceID, + panelId: relayedSurfaceID + ) + workspace.remotePTYSessionIDsByPanelId[surfaceID] = remotePTYSessionID + workspace.registerRemoteRelayIDAliases( + remotePTYSessionID: remotePTYSessionID, + restoredPanelId: surfaceID + ) + + let hook = try runBundledKiroSessionStart( + workspaceID: relayedWorkspaceID, + surfaceID: relayedSurfaceID + ) + #expect(!hook.timedOut, Comment(rawValue: hook.stderr)) + #expect(hook.status == 0, Comment(rawValue: hook.stderr)) + let resumeRequests = hook.commands.compactMap { line -> [String: Any]? in + guard let data = line.data(using: .utf8), + let request = try? JSONSerialization.jsonObject(with: data) as? [String: Any] + else { + return nil + } + return request["method"] as? String == "surface.resume.set" ? request : nil + } + #expect(resumeRequests.count == 1, "\(hook.commands)") + let resumeRequest = try #require(resumeRequests.first) + let hookParams = try #require(resumeRequest["params"] as? [String: Any]) + #expect(hookParams["workspace_id"] as? String == relayedWorkspaceID.uuidString) + #expect(hookParams["surface_id"] as? String == relayedSurfaceID.uuidString) + #expect(hookParams["source"] as? String == "agent-hook") + #expect(hookParams["kind"] as? String == "kiro") + #expect(hookParams["checkpoint_id"] as? String == "kiro-remote-session") + #expect(hookParams["auto_resume"] as? Bool == true) + + let relayedData = workspace.rewriteRemoteRelayCommandLine(try requestData(resumeRequest)) + let remoteResult = try v2Result(requestData: relayedData) + let remoteBinding = try #require(remoteResult["resume_binding"] as? [String: Any]) + #expect(remoteBinding["execution_location"] as? String == "remote_ssh") + #expect(remoteBinding["remote_workspace_id"] as? String == workspace.id.uuidString) + #expect(remoteBinding["remote_surface_id"] as? String == surfaceID.uuidString) + #expect(remoteBinding["remote_pty_session_id"] as? String == remotePTYSessionID) + #expect((remoteBinding["command"] as? String)?.contains("kiro-remote-session") == true) + } + + @Test + func remoteRegistrationRejectsMissingProvenanceAndInvalidPersistentOwnership() throws { + _ = NSApplication.shared + let previousAppDelegate = AppDelegate.shared + let app = AppDelegate() + let windowID = UUID() + let window = makeMainWindow(id: windowID) + defer { + TerminalController.shared.setActiveTabManager(nil) + app.unregisterMainWindowContextForTesting(windowId: windowID) + AppDelegate.shared = previousAppDelegate + window.orderOut(nil) + } + + let manager = TabManager(autoWelcomeIfNeeded: false) + app.registerMainWindow( + window, + windowId: windowID, + tabManager: manager, + sidebarState: SidebarState(), + sidebarSelectionState: SidebarSelectionState(), + fileExplorerState: FileExplorerState() + ) + TerminalController.shared.setActiveTabManager(manager) + + let workspace = try #require(manager.selectedWorkspace) + let surfaceID = try #require(workspace.focusedPanelId) + workspace.configureRemoteConnection(remoteConfiguration(), autoConnect: false) + let relayToken = try #require(workspace.remoteConfiguration?.relayToken) + + var missingAuthenticationParams = remoteResumeParams( + workspaceID: workspace.id, + surfaceID: surfaceID, + command: "codex resume missing-authentication" + ) + missingAuthenticationParams["_cmux_remote_workspace_id"] = workspace.id.uuidString + let missingAuthentication = try v2Envelope(request: [ + "id": "missing-authentication", + "method": "surface.resume.set", + "params": missingAuthenticationParams, + ]) + #expect(missingAuthentication["ok"] as? Bool == false) + + var malformedProvenanceParams = remoteResumeParams( + workspaceID: workspace.id, + surfaceID: surfaceID, + command: "codex resume malformed-provenance" + ) + malformedProvenanceParams["_cmux_remote_workspace_id"] = "not-a-workspace-id" + malformedProvenanceParams["_cmux_remote_relay_authentication_code"] = String(repeating: "0", count: 64) + let malformedProvenance = try v2Envelope(request: [ + "id": "malformed-provenance", + "method": "surface.resume.set", + "params": malformedProvenanceParams, + ]) + #expect(malformedProvenance["ok"] as? Bool == false) + + let wrongClaimRequest: [String: Any] = [ + "id": "wrong-remote-owner", + "method": "surface.resume.set", + "params": remoteResumeParams( + workspaceID: workspace.id, + surfaceID: surfaceID, + command: "codex resume wrong-owner" + ), + ] + let wrongClaimData = WorkspaceRemoteRelayCommandRewriter( + remoteWorkspaceID: UUID(), + remoteRelayTokenHex: relayToken + ).rewriteRemoteRelayCommandLine( + try requestData(wrongClaimRequest), + workspaceAliases: [:], + surfaceAliases: [:] + ) + let wrongClaim = try v2Envelope(requestData: wrongClaimData) + #expect(wrongClaim["ok"] as? Bool == false) + + workspace.configureRemoteConnection( + remoteConfiguration(preserveAfterTerminalExit: false, persistentDaemonSlot: nil), + autoConnect: false + ) + let nonPersistentRequest: [String: Any] = [ + "id": "non-persistent-owner", + "method": "surface.resume.set", + "params": remoteResumeParams( + workspaceID: workspace.id, + surfaceID: surfaceID, + command: "codex resume non-persistent" + ), + ] + let nonPersistentData = WorkspaceRemoteRelayCommandRewriter( + remoteWorkspaceID: workspace.id, + remoteRelayTokenHex: relayToken + ).rewriteRemoteRelayCommandLine( + try requestData(nonPersistentRequest), + workspaceAliases: [:], + surfaceAliases: [:] + ) + let nonPersistent = try v2Envelope(requestData: nonPersistentData) + #expect(nonPersistent["ok"] as? Bool == false) + + let bindingAfterRejectedRegistrations = try v2Result(request: [ + "id": "binding-after-rejections", + "method": "surface.resume.get", + "params": [ + "workspace_id": workspace.id.uuidString, + "surface_id": surfaceID.uuidString, + ], + ])["resume_binding"] + #expect(bindingAfterRejectedRegistrations is NSNull) + } + + @Test + func relayedRegistrationUsesExplicitRemoteFlavorAfterAliasRewrite() throws { + let fixture = try makeRelayedFixture() + + #expect(fixture.localBinding["execution_location"] as? String == "local") + #expect(fixture.localBinding["remote_workspace_id"] is NSNull) + #expect(fixture.spoofedRelayRegistrationRejected) + #expect(fixture.remoteBinding["execution_location"] as? String == "remote_ssh") + #expect(fixture.remoteBinding["remote_workspace_id"] as? String == fixture.workspaceID.uuidString) + #expect(fixture.remoteBinding["remote_surface_id"] as? String == fixture.surfaceID.uuidString) + #expect(fixture.remoteBinding["remote_pty_session_id"] as? String == fixture.remotePTYSessionID) + #expect(fixture.remoteBinding["cwd"] as? String == "/srv/remote project") + #expect(fixture.remoteBinding["auto_resume"] as? Bool == true) + + let environment = try #require(fixture.remoteBinding["environment"] as? [String: Any]) + #expect(environment["REMOTE_FLAG"] as? String == "value with spaces") + #expect(environment["ANTHROPIC_API_KEY"] == nil) + } + + @Test + func persistentRestoreRunsRemoteResumeOnlyWhenSessionMustBeCreated() throws { + let fixture = try makeRelayedFixture() + let suiteName = "cmux-remote-resume-binding-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defaults.set(true, forKey: AgentSessionAutoResumeSettings.autoResumeAgentSessionsKey) + defer { defaults.removePersistentDomain(forName: suiteName) } + + let socketPath = reserveRemoteRestoreSocket() + defer { cleanupRemoteRestoreSocket(socketPath) } + + let restoredWorkspace = Workspace(agentSessionAutoResumeDefaults: defaults) + let restoredIDs = restoredWorkspace.restoreSessionSnapshot(fixture.snapshot) + let restoredSurfaceID = try #require(restoredIDs[fixture.surfaceID]) + let restoredPanel = try #require(restoredWorkspace.terminalPanel(for: restoredSurfaceID)) + let liveFirstCommand = try #require(restoredPanel.surface.debugInitialCommand()) + + #expect(liveFirstCommand.contains("ssh-pty-attach"), "\(liveFirstCommand)") + #expect(liveFirstCommand.contains("--require-existing"), "\(liveFirstCommand)") + let liveFirstRemoteCommand = try decodedRemoteCommand(from: liveFirstCommand) + try expectRemoteResumeBootstrap(liveFirstRemoteCommand) + #expect(restoredPanel.surface.debugInitialInputForTesting() == nil) + + let roundTrip = restoredWorkspace.sessionSnapshot(includeScrollback: false) + let roundTripBinding = try #require( + roundTrip.panels.first { $0.id == restoredSurfaceID }?.terminal?.resumeBinding + ) + let encodedBinding = try JSONEncoder().encode(roundTripBinding) + let bindingObject = try #require( + JSONSerialization.jsonObject(with: encodedBinding) as? [String: Any] + ) + let launchFlavor = try #require(bindingObject["launchFlavor"] as? [String: Any]) + #expect(launchFlavor["kind"] as? String == "persistentSSH") + let remoteContext = try #require(launchFlavor["remoteContext"] as? [String: Any]) + #expect(remoteContext["workspaceID"] as? String == restoredWorkspace.id.uuidString) + #expect(remoteContext["surfaceID"] as? String == restoredSurfaceID.uuidString) + #expect(remoteContext["persistentPTYSessionID"] as? String == fixture.remotePTYSessionID) + + let ended = restoredWorkspace.markRemotePTYAttachEnded( + surfaceId: restoredSurfaceID, + sessionID: fixture.remotePTYSessionID + ) + #expect(ended.clearedRemotePTYSession) + restoredWorkspace.markPersistentRemotePTYAttachFailed(surfaceId: restoredSurfaceID) + let restarted = restoredWorkspace.reattachPersistentRemotePTYPanels( + requestedSurfaceId: restoredSurfaceID, + restartEndedSessions: true + ) + #expect(restarted == [restoredSurfaceID]) + + let gonePTYCommand = try #require( + restoredWorkspace.terminalPanel(for: restoredSurfaceID)?.surface.debugInitialCommand() + ) + #expect(!gonePTYCommand.contains("--require-existing"), "\(gonePTYCommand)") + let gonePTYRemoteCommand = try decodedRemoteCommand(from: gonePTYCommand) + try expectRemoteResumeBootstrap(gonePTYRemoteCommand) + } + + @Test + func mismatchedRemoteBindingNeverFallsBackToLocalExecution() throws { + let fixture = try makeRelayedFixture() + let mismatchedSnapshot = try snapshotByReplacingRemoteContext( + fixture.snapshot, + persistentPTYSessionID: "different-persistent-session" + ) + let suiteName = "cmux-mismatched-remote-resume-binding-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defaults.set(true, forKey: AgentSessionAutoResumeSettings.autoResumeAgentSessionsKey) + defer { defaults.removePersistentDomain(forName: suiteName) } + + let socketPath = reserveRemoteRestoreSocket() + defer { cleanupRemoteRestoreSocket(socketPath) } + + let restoredWorkspace = Workspace(agentSessionAutoResumeDefaults: defaults) + let restoredIDs = restoredWorkspace.restoreSessionSnapshot(mismatchedSnapshot) + let restoredSurfaceID = try #require(restoredIDs[fixture.surfaceID]) + let restoredPanel = try #require(restoredWorkspace.terminalPanel(for: restoredSurfaceID)) + let startupCommand = try #require(restoredPanel.surface.debugInitialCommand()) + + #expect(startupCommand.contains("ssh-pty-attach"), "\(startupCommand)") + #expect(startupCommand.contains("--require-existing"), "\(startupCommand)") + #expect(restoredPanel.surface.debugInitialInputForTesting() == nil) + #expect(!startupCommand.contains("--command-b64"), "\(startupCommand)") + #expect(!startupCommand.contains("session-remote-7989"), "\(startupCommand)") + #expect(!startupCommand.contains("REMOTE_FLAG"), "\(startupCommand)") + } + + @Test + func legacyRemoteSnapshotWithoutWorkspaceIDMigratesBindingIntoPersistentSSHContext() throws { + let fixture = try makeRelayedFixture() + let legacySnapshot = try snapshotWithoutLaunchFlavorOrWorkspaceID(fixture.snapshot) + let suiteName = "cmux-legacy-remote-resume-binding-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defaults.set(true, forKey: AgentSessionAutoResumeSettings.autoResumeAgentSessionsKey) + defer { defaults.removePersistentDomain(forName: suiteName) } + + let socketPath = reserveRemoteRestoreSocket() + defer { cleanupRemoteRestoreSocket(socketPath) } + + let restoredWorkspace = Workspace(agentSessionAutoResumeDefaults: defaults) + let restoredIDs = restoredWorkspace.restoreSessionSnapshot(legacySnapshot) + let restoredSurfaceID = try #require(restoredIDs[fixture.surfaceID]) + let startupCommand = try #require( + restoredWorkspace.terminalPanel(for: restoredSurfaceID)?.surface.debugInitialCommand() + ) + let remoteCommand = try decodedRemoteCommand(from: startupCommand) + try expectRemoteResumeBootstrap(remoteCommand) + + let roundTripBinding = try #require( + restoredWorkspace.sessionSnapshot(includeScrollback: false) + .panels.first { $0.id == restoredSurfaceID }?.terminal?.resumeBinding + ) + guard case .persistentSSH(let context) = roundTripBinding.launchFlavor else { + Issue.record("Legacy remote binding was not migrated to persistent SSH") + return + } + #expect(context.workspaceID == restoredWorkspace.id) + #expect(context.surfaceID == restoredSurfaceID) + #expect(context.persistentPTYSessionID == fixture.remotePTYSessionID) + } + + @Test + func legacyBindingMigrationStopsAtPersistentSSHOwnershipBoundaries() throws { + let binding = try legacyLocalBinding() + #expect(binding.wasDecodedWithoutLaunchFlavor) + let snapshotWorkspaceID = UUID() + let snapshotSurfaceID = UUID() + let sessionID = Workspace.defaultSSHPTYSessionID( + workspaceId: snapshotWorkspaceID, + panelId: snapshotSurfaceID + ) + + let localWorkspace = Workspace() + let nonPersistentSSH = Workspace() + nonPersistentSSH.configureRemoteConnection( + remoteConfiguration(preserveAfterTerminalExit: false, persistentDaemonSlot: nil), + autoConnect: false + ) + let missingDaemonSlot = Workspace() + missingDaemonSlot.configureRemoteConnection( + remoteConfiguration(preserveAfterTerminalExit: true, persistentDaemonSlot: nil), + autoConnect: false + ) + let freestyleBakedDaemon = Workspace() + freestyleBakedDaemon.configureRemoteConnection( + remoteConfiguration(skipDaemonBootstrap: true), + autoConnect: false + ) + let websocketCloud = Workspace() + websocketCloud.configureRemoteConnection( + remoteConfiguration(transport: .websocket), + autoConnect: false + ) + let moshTerminal = Workspace() + moshTerminal.configureRemoteConnection( + remoteConfiguration(terminalTransport: .mosh), + autoConnect: false + ) + let eligiblePersistentSSH = Workspace() + eligiblePersistentSSH.configureRemoteConnection(remoteConfiguration(), autoConnect: false) + + let cases: [(name: String, workspace: Workspace, sessionID: String?, restoresRemoteTerminal: Bool)] = [ + ("local workspace", localWorkspace, sessionID, true), + ("non-persistent SSH", nonPersistentSSH, sessionID, true), + ("missing daemon slot", missingDaemonSlot, sessionID, true), + ("Freestyle baked daemon", freestyleBakedDaemon, sessionID, true), + ("WebSocket Cloud VM", websocketCloud, sessionID, true), + ("Mosh terminal", moshTerminal, sessionID, true), + ("local terminal inside persistent SSH workspace", eligiblePersistentSSH, sessionID, false), + ("missing persistent PTY", eligiblePersistentSSH, nil, true), + ("blank persistent PTY", eligiblePersistentSSH, " \t\n ", true), + ] + + for item in cases { + let migrated = item.workspace.migratingLegacyPersistentSSHResumeBinding( + binding, + snapshotWorkspaceID: snapshotWorkspaceID, + snapshotSurfaceID: snapshotSurfaceID, + persistentPTYSessionID: item.sessionID, + restoresRemoteTerminal: item.restoresRemoteTerminal + ) + #expect(migrated?.launchFlavor == .local, Comment(rawValue: item.name)) + } + } + + private func makeRelayedFixture() throws -> ( + snapshot: SessionWorkspaceSnapshot, + workspaceID: UUID, + surfaceID: UUID, + remotePTYSessionID: String, + localBinding: [String: Any], + spoofedRelayRegistrationRejected: Bool, + remoteBinding: [String: Any] + ) { + _ = NSApplication.shared + let previousAppDelegate = AppDelegate.shared + let app = AppDelegate() + let windowID = UUID() + let window = makeMainWindow(id: windowID) + defer { + TerminalController.shared.setActiveTabManager(nil) + app.unregisterMainWindowContextForTesting(windowId: windowID) + AppDelegate.shared = previousAppDelegate + window.orderOut(nil) + } + + let manager = TabManager(autoWelcomeIfNeeded: false) + app.registerMainWindow( + window, + windowId: windowID, + tabManager: manager, + sidebarState: SidebarState(), + sidebarSelectionState: SidebarSelectionState(), + fileExplorerState: FileExplorerState() + ) + TerminalController.shared.setActiveTabManager(manager) + + let workspace = try #require(manager.selectedWorkspace) + let surfaceID = try #require(workspace.focusedPanelId) + workspace.configureRemoteConnection(remoteConfiguration(), autoConnect: false) + + let localResult = try v2Result( + request: [ + "id": "local-resume-set", + "method": "surface.resume.set", + "params": remoteResumeParams( + workspaceID: workspace.id, + surfaceID: surfaceID, + command: "codex resume local-session" + ), + ] + ) + let localBinding = try #require(localResult["resume_binding"] as? [String: Any]) + + var spoofedParams = remoteResumeParams( + workspaceID: workspace.id, + surfaceID: surfaceID, + command: "codex resume forged-local-request" + ) + spoofedParams["_cmux_remote_workspace_id"] = workspace.id.uuidString + spoofedParams["_cmux_remote_relay_authentication_code"] = String(repeating: "0", count: 64) + let spoofedEnvelope = try v2Envelope(request: [ + "id": "spoofed-relay-resume-set", + "method": "surface.resume.set", + "params": spoofedParams, + ]) + let bindingAfterSpoof = try v2Result(request: [ + "id": "resume-get-after-spoof", + "method": "surface.resume.get", + "params": [ + "workspace_id": workspace.id.uuidString, + "surface_id": surfaceID.uuidString, + ], + ])["resume_binding"] as? [String: Any] + let spoofedRelayRegistrationRejected = spoofedEnvelope["ok"] as? Bool == false + && (bindingAfterSpoof?["command"] as? String) == (localBinding["command"] as? String) + + let staleWorkspaceID = UUID() + let staleSurfaceID = UUID() + let remotePTYSessionID = Workspace.defaultSSHPTYSessionID( + workspaceId: staleWorkspaceID, + panelId: staleSurfaceID + ) + workspace.remotePTYSessionIDsByPanelId[surfaceID] = remotePTYSessionID + workspace.registerRemoteRelayIDAliases( + remotePTYSessionID: remotePTYSessionID, + restoredPanelId: surfaceID + ) + + let relayedRequest: [String: Any] = [ + "id": "relayed-resume-set", + "method": "surface.resume.set", + "params": remoteResumeParams( + workspaceID: staleWorkspaceID, + surfaceID: staleSurfaceID, + command: "cd '/srv/remote project' && '/home/dev/.nvm/versions/node/v24/bin/codex' resume session-remote-7989" + ), + ] + var relayedData = try JSONSerialization.data(withJSONObject: relayedRequest) + relayedData.append(0x0A) + let rewrittenData = workspace.rewriteRemoteRelayCommandLine(relayedData) + let remoteResult = try v2Result(requestData: rewrittenData) + let remoteBinding = try #require(remoteResult["resume_binding"] as? [String: Any]) + + return ( + workspace.sessionSnapshot(includeScrollback: false), + workspace.id, + surfaceID, + remotePTYSessionID, + localBinding, + spoofedRelayRegistrationRejected, + remoteBinding + ) + } + + private func remoteConfiguration( + transport: WorkspaceRemoteTransport = .ssh, + terminalTransport: WorkspaceRemoteTerminalTransport = .ssh, + preserveAfterTerminalExit: Bool = true, + persistentDaemonSlot: String? = "ssh-issue-7989", + skipDaemonBootstrap: Bool = false + ) -> WorkspaceRemoteConfiguration { + WorkspaceRemoteConfiguration( + transport: transport, + terminalTransport: terminalTransport, + destination: "dev@example.com", + port: 22, + identityFile: nil, + sshOptions: ["StrictHostKeyChecking=accept-new"], + localProxyPort: nil, + relayPort: relayPort, + relayID: "relay-issue-7989", + relayToken: String(repeating: "a", count: 64), + localSocketPath: "/tmp/cmux-issue-7989.sock", + terminalStartupCommand: SSHPTYAttachStartupCommandBuilder.command(requireExisting: false), + preserveAfterTerminalExit: preserveAfterTerminalExit, + persistentDaemonSlot: persistentDaemonSlot, + skipDaemonBootstrap: skipDaemonBootstrap + ) + } + + private func remoteResumeParams( + workspaceID: UUID, + surfaceID: UUID, + command: String + ) -> [String: Any] { + [ + "workspace_id": workspaceID.uuidString, + "surface_id": surfaceID.uuidString, + "name": "Codex", + "kind": "codex", + "checkpoint_id": "session-remote-7989", + "source": "agent-hook", + "command": command, + "cwd": "/srv/remote project", + "environment": [ + "REMOTE_FLAG": "value with spaces", + "ANTHROPIC_API_KEY": "must-not-persist", + ], + "auto_resume": true, + ] + } + + private func requestData(_ request: [String: Any]) throws -> Data { + var data = try JSONSerialization.data(withJSONObject: request) + data.append(0x0A) + return data + } + + private func jsonRequest(_ data: Data) throws -> [String: Any] { + try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + + private func v2Result(request: [String: Any]) throws -> [String: Any] { + let envelope = try v2Envelope(request: request) + #expect(envelope["ok"] as? Bool == true, "\(envelope)") + return try #require(envelope["result"] as? [String: Any]) + } + + private func v2Envelope(request: [String: Any]) throws -> [String: Any] { + try v2Envelope(requestData: requestData(request)) + } + + private func v2Envelope(requestData: Data) throws -> [String: Any] { + let requestLine = try #require(String(data: requestData, encoding: .utf8)) + let response = TerminalController.shared.handleSocketLine(requestLine) + let responseData = try #require(response.data(using: .utf8)) + return try #require(JSONSerialization.jsonObject(with: responseData) as? [String: Any]) + } + + private func v2Result(requestData: Data) throws -> [String: Any] { + let envelope = try v2Envelope(requestData: requestData) + #expect(envelope["ok"] as? Bool == true, "\(envelope)") + return try #require(envelope["result"] as? [String: Any]) + } + + private func decodedRemoteCommand(from startupCommand: String) throws -> String { + let words = TerminalStartupWorkingDirectoryPrefix.shellWordRanges(startupCommand).map(\.value) + let script = try #require(words.dropFirst(2).first) + let range = try #require( + script.range(of: #"--command-b64 [A-Za-z0-9+/=]+"#, options: .regularExpression) + ) + let encoded = String(script[range]).split(separator: " ", maxSplits: 1).last.map(String.init) + let data = try #require(encoded.flatMap { Data(base64Encoded: $0) }) + return try #require(String(data: data, encoding: .utf8)) + } + + private func snapshotWithoutLaunchFlavorOrWorkspaceID( + _ snapshot: SessionWorkspaceSnapshot + ) throws -> SessionWorkspaceSnapshot { + let encoded = try JSONEncoder().encode(snapshot) + var object = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) + object.removeValue(forKey: "workspaceId") + var panels = try #require(object["panels"] as? [[String: Any]]) + let panelIndex = try #require(panels.firstIndex { $0["terminal"] != nil }) + var panel = panels[panelIndex] + var terminal = try #require(panel["terminal"] as? [String: Any]) + var binding = try #require(terminal["resumeBinding"] as? [String: Any]) + binding.removeValue(forKey: "launchFlavor") + terminal["resumeBinding"] = binding + panel["terminal"] = terminal + panels[panelIndex] = panel + object["panels"] = panels + let legacyData = try JSONSerialization.data(withJSONObject: object) + return try JSONDecoder().decode(SessionWorkspaceSnapshot.self, from: legacyData) + } + + private func snapshotByReplacingRemoteContext( + _ snapshot: SessionWorkspaceSnapshot, + persistentPTYSessionID: String + ) throws -> SessionWorkspaceSnapshot { + let encoded = try JSONEncoder().encode(snapshot) + var object = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) + var panels = try #require(object["panels"] as? [[String: Any]]) + let panelIndex = try #require(panels.firstIndex { $0["terminal"] != nil }) + var panel = panels[panelIndex] + var terminal = try #require(panel["terminal"] as? [String: Any]) + var binding = try #require(terminal["resumeBinding"] as? [String: Any]) + var launchFlavor = try #require(binding["launchFlavor"] as? [String: Any]) + var remoteContext = try #require(launchFlavor["remoteContext"] as? [String: Any]) + remoteContext["persistentPTYSessionID"] = persistentPTYSessionID + launchFlavor["remoteContext"] = remoteContext + binding["launchFlavor"] = launchFlavor + terminal["resumeBinding"] = binding + panel["terminal"] = terminal + panels[panelIndex] = panel + object["panels"] = panels + return try JSONDecoder().decode( + SessionWorkspaceSnapshot.self, + from: JSONSerialization.data(withJSONObject: object) + ) + } + + private func legacyLocalBinding() throws -> SurfaceResumeBindingSnapshot { + let object: [String: Any] = [ + "name": "Codex", + "kind": "codex", + "command": "codex resume legacy-session", + "cwd": "/tmp/legacy-project", + "checkpointId": "legacy-session", + "source": "agent-hook", + "autoResume": true, + "updatedAt": 10.0, + ] + return try JSONDecoder().decode( + SurfaceResumeBindingSnapshot.self, + from: JSONSerialization.data(withJSONObject: object) + ) + } + + private func expectRemoteResumeBootstrap(_ command: String) throws { + #expect(command.contains("export CMUX_SOCKET_PATH=127.0.0.1:\(relayPort)"), "\(command)") + #expect(command.contains("__CMUX_WORKSPACE_ID__"), "\(command)") + #expect(command.contains("__CMUX_SURFACE_ID__"), "\(command)") + let initialCommand = try decodedInitialCommand(from: command) + #expect(initialCommand.contains("/srv/remote project"), "\(initialCommand)") + #expect(initialCommand.contains("REMOTE_FLAG=value with spaces"), "\(initialCommand)") + #expect(initialCommand.contains("session-remote-7989"), "\(initialCommand)") + #expect(!initialCommand.contains("ANTHROPIC_API_KEY"), "\(initialCommand)") + } + + private func decodedInitialCommand(from bootstrap: String) throws -> String { + let payloadLine = try #require(bootstrap.split(separator: "\n").first { line in + line.contains("printf %s '") && line.contains("> \"$cmux_initial_command_tmp\"") + }) + let prefixRange = try #require(payloadLine.range(of: "printf %s '")) + let encodedSuffix = payloadLine[prefixRange.upperBound...] + let closingQuote = try #require(encodedSuffix.firstIndex(of: "'")) + let encodedCommand = String(encodedSuffix[.. HookRunResult { + let cliPath = try BundledCLITestSupport.bundledCLIPath(for: BundledCLILinkageTests.self) + let fileManager = FileManager.default + let root = fileManager.temporaryDirectory + .appendingPathComponent("cmux-remote-kiro-hook-\(UUID().uuidString)", isDirectory: true) + let workingDirectory = root.appendingPathComponent("remote project", isDirectory: true) + let socketPath = "/tmp/rb-\(UUID().uuidString.prefix(8)).sock" + try fileManager.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + let listenerFD = try bindHookSocket(at: socketPath) + let capture = RemoteResumeHookCapture() + let serverFinished = RemoteResumeHookSocketServer.start( + listenerFD: listenerFD, + capture: capture, + surfaceID: surfaceID + ) + defer { + Darwin.close(listenerFD) + unlink(socketPath) + try? fileManager.removeItem(at: root) + } + + let executable = "/Users/example/.cargo/bin/kiro-cli" + let launchArguments = [ + executable, + "chat", + "--agent", + "cmux", + "--trust-tools", + "fs_read,fs_write", + ] + let environment: [String: String] = [ + "HOME": root.path, + "PATH": "/usr/bin:/bin:/usr/sbin:/sbin", + "PWD": workingDirectory.path, + "CMUX_SOCKET_PATH": socketPath, + "CMUX_WORKSPACE_ID": workspaceID.uuidString, + "CMUX_SURFACE_ID": surfaceID.uuidString, + "CMUX_AGENT_HOOK_STATE_DIR": root.path, + "CMUX_AGENT_LAUNCH_KIND": "kiro", + "CMUX_AGENT_LAUNCH_EXECUTABLE": executable, + "CMUX_AGENT_LAUNCH_ARGV_B64": base64NULSeparated(launchArguments), + "CMUX_AGENT_LAUNCH_CWD": workingDirectory.path, + "CMUX_CLI_SENTRY_DISABLED": "1", + ] + let inputObject: [String: Any] = [ + "session_id": "kiro-remote-session", + "cwd": workingDirectory.path, + "hook_event_name": "SessionStart", + ] + let input = String( + decoding: try JSONSerialization.data(withJSONObject: inputObject), + as: UTF8.self + ) + let processResult = runHookProcess( + executablePath: cliPath, + arguments: ["hooks", "kiro", "session-start"], + environment: environment, + standardInput: input, + timeout: 5 + ) + _ = serverFinished.wait(timeout: .now() + 5) + return HookRunResult( + status: processResult.status, + stderr: processResult.stderr, + timedOut: processResult.timedOut, + commands: capture.snapshot() + ) + } + + private func bindHookSocket(at path: String) throws -> Int32 { + unlink(path) + let fileDescriptor = Darwin.socket(AF_UNIX, SOCK_STREAM, 0) + guard fileDescriptor >= 0 else { + throw POSIXError(.init(rawValue: errno) ?? .EIO) + } + + var address = sockaddr_un() + address.sun_family = sa_family_t(AF_UNIX) + let pathBytes = Array(path.utf8) + let pathCapacity = MemoryLayout.size(ofValue: address.sun_path) + guard pathBytes.count < pathCapacity else { + Darwin.close(fileDescriptor) + throw POSIXError(.ENAMETOOLONG) + } + _ = withUnsafeMutablePointer(to: &address.sun_path) { pointer in + pointer.withMemoryRebound(to: CChar.self, capacity: pathCapacity) { buffer in + for index in pathBytes.indices { + buffer[index] = CChar(bitPattern: pathBytes[index]) + } + buffer[pathBytes.count] = 0 + } + } + let bindResult = withUnsafePointer(to: &address) { pointer in + pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { socketAddress in + Darwin.bind( + fileDescriptor, + socketAddress, + socklen_t(MemoryLayout.size) + ) + } + } + guard bindResult == 0, Darwin.listen(fileDescriptor, 1) == 0 else { + let error = POSIXError(.init(rawValue: errno) ?? .EIO) + Darwin.close(fileDescriptor) + throw error + } + return fileDescriptor + } + + private func base64NULSeparated(_ values: [String]) -> String { + var data = Data() + for value in values { + data.append(contentsOf: value.utf8) + data.append(0) + } + return data.base64EncodedString() + } + + private func runHookProcess( + executablePath: String, + arguments: [String], + environment: [String: String], + standardInput: String, + timeout: TimeInterval + ) -> (status: Int32, stderr: String, timedOut: Bool) { + let process = Process() + let inputPipe = Pipe() + let outputPipe = Pipe() + let errorPipe = Pipe() + process.executableURL = URL(fileURLWithPath: executablePath) + process.arguments = arguments + process.environment = environment + process.standardInput = inputPipe + process.standardOutput = outputPipe + process.standardError = errorPipe + + do { + try process.run() + } catch { + return (-1, String(describing: error), false) + } + inputPipe.fileHandleForWriting.write(Data(standardInput.utf8)) + try? inputPipe.fileHandleForWriting.close() + + let deadline = Date().addingTimeInterval(timeout) + while process.isRunning, Date() < deadline { + Thread.sleep(forTimeInterval: 0.02) + } + let timedOut = process.isRunning + if timedOut { + process.terminate() + } + process.waitUntilExit() + _ = outputPipe.fileHandleForReading.readDataToEndOfFile() + let stderr = String( + decoding: errorPipe.fileHandleForReading.readDataToEndOfFile(), + as: UTF8.self + ) + return (process.terminationStatus, stderr, timedOut) + } + + private func reserveRemoteRestoreSocket() -> String { + TerminalController.shared.stop() + let requestedPath = "/tmp/cmux-remote-resume-\(UUID().uuidString).sock" + return TerminalController.shared.reserveStartupSocketPath(requestedPath) + } + + private func cleanupRemoteRestoreSocket(_ path: String) { + TerminalController.shared.stop() + try? FileManager.default.removeItem(atPath: path) + try? FileManager.default.removeItem(atPath: path + ".lock") + } + + private func makeMainWindow(id: UUID) -> NSWindow { + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 500, height: 320), + styleMask: [.titled, .closable], + backing: .buffered, + defer: false + ) + window.identifier = NSUserInterfaceItemIdentifier("cmux.main.\(id.uuidString)") + return window + } +} diff --git a/cmuxTests/SessionRemoteWorkspaceMoshRestoreTests.swift b/cmuxTests/SessionRemoteWorkspaceMoshRestoreTests.swift index 77c30bf9c2ca..9903a217fe01 100644 --- a/cmuxTests/SessionRemoteWorkspaceMoshRestoreTests.swift +++ b/cmuxTests/SessionRemoteWorkspaceMoshRestoreTests.swift @@ -11,6 +11,64 @@ import Testing @Suite("Mosh remote workspace session restore") struct SessionRemoteWorkspaceMoshRestoreTests { + @Test("starts the SSH management lane before handing the terminal to Mosh") + func startsManagementLaneBeforeMosh() throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-mosh-management-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + + let sshURL = directory.appendingPathComponent("ssh") + try """ + #!/bin/sh + exit 0 + """.write(to: sshURL, atomically: true, encoding: .utf8) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: sshURL.path) + + let moshURL = directory.appendingPathComponent("mosh") + try """ + #!/bin/sh + if [ "${1:-}" = "--help" ]; then + printf '%s\n' ' --experimental-remote-ip=(local|remote|proxy)' + exit 0 + fi + [ -f "$READY_FILE" ] || exit 71 + printf '%s\n' "$@" > "$MOSH_ARGS_FILE" + """.write(to: moshURL, atomically: true, encoding: .utf8) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: moshURL.path) + + let readyURL = directory.appendingPathComponent("management.ready") + let argumentsURL = directory.appendingPathComponent("mosh.args") + let command = MoshTerminalCommandBuilder( + capabilityProbeSSHArguments: [sshURL.path], + sessionSSHArguments: [sshURL.path], + destination: "user@example.com", + remoteCommandArguments: ["printf", "remote command"], + managementReadyShellScript: "printf ready > \"$READY_FILE\"", + sshFallbackCommand: "exit 90", + localMoshMissingMessage: "local Mosh missing", + localMoshUnsupportedMessage: "local Mosh unsupported", + remoteMoshMissingMessage: "remote Mosh missing", + remoteMoshProbeFailedMessage: "remote Mosh probe failed" + ).command() + let process = Process() + process.executableURL = URL(fileURLWithPath: "/bin/sh") + process.arguments = ["-c", command] + process.environment = [ + "HOME": directory.path, + "MOSH_ARGS_FILE": argumentsURL.path, + "PATH": directory.path, + "READY_FILE": readyURL.path, + ] + try process.run() + process.waitUntilExit() + + #expect(process.terminationStatus == 0) + #expect(FileManager.default.fileExists(atPath: readyURL.path)) + let moshArguments = try String(contentsOf: argumentsURL, encoding: .utf8) + #expect(!moshArguments.contains("READY_FILE"), "\(moshArguments)") + } + @Test("restores the Mosh terminal preference with SSH fallback") func restoresMoshTerminalCommand() throws { let snapshot = SessionRemoteWorkspaceSnapshot( diff --git a/cmuxTests/ShellStartupMatrixTests.swift b/cmuxTests/ShellStartupMatrixTests.swift index d44801e5290c..3674aeb33661 100644 --- a/cmuxTests/ShellStartupMatrixTests.swift +++ b/cmuxTests/ShellStartupMatrixTests.swift @@ -176,6 +176,75 @@ struct ShellStartupMatrixTests { } } + @Test + func generatedSshBootstrapRunsResumeBeforeUnsupportedInteractiveShell() throws { + let result = try runGeneratedBootstrap( + shellName: "xonsh", + initialCommand: #"printf 'resumed\n' > "$HOME/.cmux-resume-marker""# + ) + + expectEqual(result.process.status, 0, result.process.stderr) + expectFalse(result.process.timedOut, result.process.stderr) + expectTrue(result.capture.contains("ARGS=-i"), result.capture) + expectEqual(result.resumeMarker, "resumed\n") + } + + @Test(arguments: ["zsh", "bash", "fish"]) + func generatedSshBootstrapRunsInitialCommandOnceInSelectedSupportedShell(shellName: String) throws { + guard let shell = Self.supportedShellExecutable(named: shellName) else { + return + } + + let fileManager = FileManager.default + let root = fileManager.temporaryDirectory + .appendingPathComponent("cmux-supported-shell-resume-\(UUID().uuidString)") + let home = root.appendingPathComponent("home") + let marker = home.appendingPathComponent(".cmux-resume-marker") + try fileManager.createDirectory(at: home, withIntermediateDirectories: true) + defer { try? fileManager.removeItem(at: root) } + + let script = RemoteInteractiveShellBootstrapBuilder.script( + remoteRelayPort: 64_123, + shellFeatures: "ssh-env,ssh-terminfo", + initialCommand: #"printf '%s\n' "$SHELL" >> "$HOME/.cmux-resume-marker""#, + bundledZshIntegration: ":", + bundledBashIntegration: ":", + bundledFishIntegration: "true" + ) + let arguments = [ + "HOME=\(home.path)", + "SHELL=\(shell)", + "PATH=/usr/bin:/bin:/usr/sbin:/sbin", + "TERM=xterm-256color", + "XDG_CONFIG_HOME=\(home.appendingPathComponent(".config").path)", + "/bin/sh", + "-c", + script, + ] + + let first = runProcess( + executablePath: "/usr/bin/env", + arguments: arguments, + timeout: 5 + ) + expectEqual(first.status, 0, first.stderr) + expectFalse(first.timedOut, first.stderr) + expectEqual(try String(contentsOf: marker, encoding: .utf8), "\(shell)\n") + + let reattach = runProcess( + executablePath: "/usr/bin/env", + arguments: arguments, + timeout: 5 + ) + expectEqual(reattach.status, 0, reattach.stderr) + expectFalse(reattach.timedOut, reattach.stderr) + expectEqual( + try String(contentsOf: marker, encoding: .utf8), + "\(shell)\n", + "The selected \(shellName) shell must consume the resume payload exactly once" + ) + } + @Test(arguments: ["zsh", "bash", "fish", "sh", "dash", "ksh", "tcsh", "csh"]) func generatedSshBootstrapStartupStaysUnderPerformanceBudget(shellName: String) throws { let result = try runGeneratedBootstrap(shellName: shellName) @@ -290,6 +359,7 @@ struct ShellStartupMatrixTests { private struct GeneratedBootstrapResult { let home: URL let capture: String + let resumeMarker: String let process: ProcessRunResult } @@ -298,7 +368,8 @@ struct ShellStartupMatrixTests { fakeCmuxDelay: TimeInterval? = nil, workspaceID: String? = nil, surfaceID: String? = nil, - bootstrapTTY: String? = nil + bootstrapTTY: String? = nil, + initialCommand: String? = nil ) throws -> GeneratedBootstrapResult { let fileManager = FileManager.default let root = fileManager.temporaryDirectory.appendingPathComponent("cmux-shell-matrix-\(UUID().uuidString)") @@ -318,6 +389,7 @@ struct ShellStartupMatrixTests { shellFeatures: RemoteInteractiveShellBootstrapBuilder.shellFeatures(environment: [ "GHOSTTY_SHELL_FEATURES": "existing-feature" ]), + initialCommand: initialCommand, bundledZshIntegration: "cmux_zsh_marker=1", bundledBashIntegration: "cmux_bash_marker=1", bundledFishIntegration: "set -gx CMUX_FISH_MARKER 1" @@ -351,7 +423,16 @@ struct ShellStartupMatrixTests { timeout: 5 ) let capture = (try? String(contentsOf: capturePath, encoding: .utf8)) ?? "" - return GeneratedBootstrapResult(home: home, capture: capture, process: process) + let resumeMarker = (try? String( + contentsOf: home.appendingPathComponent(".cmux-resume-marker"), + encoding: .utf8 + )) ?? "" + return GeneratedBootstrapResult( + home: home, + capture: capture, + resumeMarker: resumeMarker, + process: process + ) } private func writeExecutableShellFile(at url: URL, capturePath: URL) throws { @@ -420,6 +501,21 @@ struct ShellStartupMatrixTests { String(format: "%.3fs", value) } + private static func supportedShellExecutable(named shellName: String) -> String? { + let candidates: [String] + switch shellName { + case "zsh": + candidates = ["/bin/zsh", "/usr/bin/zsh"] + case "bash": + candidates = ["/bin/bash", "/usr/bin/bash"] + case "fish": + candidates = ["/opt/homebrew/bin/fish", "/usr/local/bin/fish", "/usr/bin/fish", "/bin/fish"] + default: + return nil + } + return candidates.first { FileManager.default.isExecutableFile(atPath: $0) } + } + private func runProcess( executablePath: String, arguments: [String], @@ -429,6 +525,7 @@ struct ShellStartupMatrixTests { let start = Date() process.executableURL = URL(fileURLWithPath: executablePath) process.arguments = arguments + process.standardInput = FileHandle.nullDevice let stdout = Pipe() let stderr = Pipe() process.standardOutput = stdout