From 1d094c81ae33975060a26208f59f2920221c38d0 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 18:23:39 -0700 Subject: [PATCH 01/25] test: cover remote SSH resume bindings --- cmux.xcodeproj/project.pbxproj | 4 + cmuxTests/RemoteResumeBindingTests.swift | 290 +++++++++++++++++++++++ 2 files changed, 294 insertions(+) create mode 100644 cmuxTests/RemoteResumeBindingTests.swift diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 383bf9ab377c..c2cf36356c27 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -1232,6 +1232,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 */; }; @@ -3282,6 +3283,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 = ""; }; @@ -5771,6 +5773,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B79500300000000000000002 /* PortScannerPublicationTests.swift */, B79500320000000000000002 /* PortScannerIdentityContinuityTests.swift */, F6572003A1B2C3D4E5F60718 /* SessionPersistenceResumeBindingTests.swift */, + 7989A0027989A0027989A002 /* RemoteResumeBindingTests.swift */, F6572013A1B2C3D4E5F60718 /* SurfaceResumeBindingCodexUpdateCheckTests.swift */, F5000001A1B2C3D4E5F60718 /* SessionPersistenceTests.swift */, 806600000000000000000001 /* SessionRestorableAgentSnapshotPermissionModeTests.swift */, @@ -8508,6 +8511,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A64610020000000000000001 /* QuitConfirmationAlertPresenterTests.swift in Sources */, A6D1F0400000000000000002 /* ReleasingWindowControllerTests.swift in Sources */, 791100030000000000000001 /* RemoteDisconnectLifecycleTests.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/RemoteResumeBindingTests.swift b/cmuxTests/RemoteResumeBindingTests.swift new file mode 100644 index 000000000000..c2682e58ba2b --- /dev/null +++ b/cmuxTests/RemoteResumeBindingTests.swift @@ -0,0 +1,290 @@ +import AppKit +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@Suite(.serialized) +@MainActor +struct RemoteResumeBindingTests { + private let relayPort = 64_089 + + @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.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, + workspaceID: restoredWorkspace.id, + surfaceID: restoredSurfaceID + ) + #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, + workspaceID: restoredWorkspace.id, + surfaceID: restoredSurfaceID + ) + } + + private func makeRelayedFixture() throws -> ( + snapshot: SessionWorkspaceSnapshot, + workspaceID: UUID, + surfaceID: UUID, + remotePTYSessionID: String, + localBinding: [String: Any], + 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]) + + 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, + remoteBinding + ) + } + + private func remoteConfiguration() -> WorkspaceRemoteConfiguration { + WorkspaceRemoteConfiguration( + 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: true, + persistentDaemonSlot: "ssh-issue-7989" + ) + } + + 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 v2Result(request: [String: Any]) throws -> [String: Any] { + var data = try JSONSerialization.data(withJSONObject: request) + data.append(0x0A) + return try v2Result(requestData: data) + } + + private func v2Result(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)) + let envelope = try #require( + JSONSerialization.jsonObject(with: responseData) as? [String: Any] + ) + #expect(envelope["ok"] as? Bool == true, "\(response)") + 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.init(base64Encoded:))) + return try #require(String(data: data, encoding: .utf8)) + } + + private func expectRemoteResumeBootstrap( + _ command: String, + workspaceID: UUID, + surfaceID: UUID + ) 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)") + #expect(command.contains("/srv/remote project"), "\(command)") + #expect(command.contains("REMOTE_FLAG=value with spaces"), "\(command)") + #expect(command.contains("session-remote-7989"), "\(command)") + #expect(!command.contains("ANTHROPIC_API_KEY"), "\(command)") + _ = workspaceID + _ = surfaceID + } + + 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 + } +} From cd31bb2d78b03b91fa1263d585eb9ef8b0694a7a Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 19:37:56 -0700 Subject: [PATCH 02/25] feat: add remote-aware SSH resume bindings --- .../ControlCommandCoordinator+Surface3.swift | 18 +- .../Surface/ControlSurfaceResumeBinding.swift | 20 ++ .../ControlSurfaceResumeSetInputs.swift | 10 +- ...moteInteractiveShellBootstrapBuilder.swift | 51 +++- .../SSHPTYAttachStartupCommandBuilder.swift | 8 +- Sources/SessionPersistence.swift | 20 +- ...ssionRemoteWorkspaceSnapshot+Restore.swift | 2 +- .../SurfaceResumeBindingSnapshot+Remote.swift | 49 ++++ Sources/SurfaceResumeLaunchFlavor.swift | 56 ++++ Sources/SurfaceResumeRemoteContext.swift | 35 +++ Sources/TabManager.swift | 2 +- ...inalController+ControlSurfaceContext.swift | 5 + ...nalController+ControlSurfaceContext4.swift | 12 +- ...orkspace+PersistentRemotePTYReattach.swift | 6 + .../Workspace+RemoteRelayCommandRewrite.swift | 176 ++++++++++++ .../Workspace+RemoteSessionLifecycle.swift | 2 +- ...Workspace+RemoteSurfaceResumeBinding.swift | 72 +++++ Sources/Workspace.swift | 267 +++++------------- .../WorkspaceRemoteRelayCommandRewriter.swift | 5 +- cmux.xcodeproj/project.pbxproj | 20 ++ 20 files changed, 616 insertions(+), 220 deletions(-) create mode 100644 Sources/SurfaceResumeBindingSnapshot+Remote.swift create mode 100644 Sources/SurfaceResumeLaunchFlavor.swift create mode 100644 Sources/SurfaceResumeRemoteContext.swift create mode 100644 Sources/Workspace+RemoteRelayCommandRewrite.swift create mode 100644 Sources/Workspace+RemoteSurfaceResumeBinding.swift 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 be34759a1cd0..ec3390f38e1b 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,8 @@ 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 ) return surfaceResumeResult( context?.controlSurfaceResumeSet( @@ -160,6 +172,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..4c6285915925 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,9 @@ 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 authenticated relay's owning remote workspace, when the request + /// entered through an SSH workspace relay. + public let remoteWorkspaceID: UUID? /// Creates resume-set inputs. /// @@ -37,6 +40,7 @@ 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. public init( name: String?, kind: String?, @@ -45,7 +49,8 @@ public struct ControlSurfaceResumeSetInputs: Sendable, Equatable { checkpointID: String?, source: String?, environment: [String: String]?, - autoResume: Bool + autoResume: Bool, + remoteWorkspaceID: UUID? ) { self.name = name self.kind = kind @@ -55,5 +60,6 @@ public struct ControlSurfaceResumeSetInputs: Sendable, Equatable { self.source = source self.environment = environment self.autoResume = autoResume + self.remoteWorkspaceID = remoteWorkspaceID } } diff --git a/Sources/RemoteInteractiveShellBootstrapBuilder.swift b/Sources/RemoteInteractiveShellBootstrapBuilder.swift index 1c788c7d1a72..e0067d3703ea 100644 --- a/Sources/RemoteInteractiveShellBootstrapBuilder.swift +++ b/Sources/RemoteInteractiveShellBootstrapBuilder.swift @@ -7,7 +7,8 @@ enum RemoteInteractiveShellBootstrapBuilder { terminfoSource: String? = nil, bundledZshIntegration: String? = nil, bundledBashIntegration: String? = nil, - bundledFishIntegration: String? = nil + bundledFishIntegration: String? = nil, + initialCommand: String? = nil ) -> String { let shellStateDir = shellStateDirForRemoteRelayPort(remoteRelayPort) let commonShellExportLines = commonShellLines( @@ -85,7 +86,7 @@ enum RemoteInteractiveShellBootstrapBuilder { outerLines += [ " export CMUX_REAL_ZDOTDIR=\"${ZDOTDIR:-$HOME}\"", " export ZDOTDIR=\"$cmux_shell_dir\"", - " exec \"$CMUX_LOGIN_SHELL\" -il", + loginShellLaunchLine(kind: .zsh, initialCommand: initialCommand), " ;;", " bash)", " cat > \"$cmux_shell_dir/.bashrc\" <<'CMUXBASHRC'", @@ -106,7 +107,7 @@ enum RemoteInteractiveShellBootstrapBuilder { ] outerLines.append(contentsOf: relayWarmupLines.map { " " + $0 }) outerLines += [ - " exec \"$CMUX_LOGIN_SHELL\" --rcfile \"$cmux_shell_dir/.bashrc\" -i", + loginShellLaunchLine(kind: .bash, initialCommand: initialCommand), " ;;", " fish)", ] @@ -114,13 +115,13 @@ enum RemoteInteractiveShellBootstrapBuilder { outerLines += [ " export CMUX_FISH_INTEGRATION_FILE=\"$cmux_shell_dir/fish/config.fish\"", " export CMUX_FISH_USER_CONFIG_ALREADY_LOADED=1", - " exec \"$CMUX_LOGIN_SHELL\" -il --init-command 'source \"$CMUX_FISH_INTEGRATION_FILE\"'", + loginShellLaunchLine(kind: .fish, initialCommand: initialCommand), " ;;", " *)", ] outerLines.append(contentsOf: relayWarmupLines) outerLines += [ - "exec \"$CMUX_LOGIN_SHELL\" -i", + loginShellLaunchLine(kind: .other, initialCommand: initialCommand), ";;", "esac", ] @@ -128,6 +129,46 @@ enum RemoteInteractiveShellBootstrapBuilder { return outerLines.joined(separator: "\n") } + private enum LoginShellKind { + case zsh + case bash + case fish + case other + } + + private static func loginShellLaunchLine( + kind: LoginShellKind, + initialCommand: String? + ) -> String { + let normalizedCommand = initialCommand?.trimmingCharacters(in: .whitespacesAndNewlines) + let resumeInvocation = normalizedCommand.flatMap { command in + command.isEmpty ? nil : "/bin/sh -c \(shellQuote(command))" + } + switch (kind, resumeInvocation) { + case (.zsh, .none): + return " exec \"$CMUX_LOGIN_SHELL\" -il" + case (.zsh, .some(let resumeInvocation)): + let command = resumeInvocation + "\nexec \"$CMUX_LOGIN_SHELL\" -il" + return " exec \"$CMUX_LOGIN_SHELL\" -ilc \(shellQuote(command))" + case (.bash, .none): + return " exec \"$CMUX_LOGIN_SHELL\" --rcfile \"$cmux_shell_dir/.bashrc\" -i" + case (.bash, .some(let resumeInvocation)): + let command = resumeInvocation + + "\nexec \"$CMUX_LOGIN_SHELL\" --rcfile \"$CMUX_SHELL_INTEGRATION_DIR/.bashrc\" -i" + return " exec \"$CMUX_LOGIN_SHELL\" --rcfile \"$cmux_shell_dir/.bashrc\" -ic \(shellQuote(command))" + case (.fish, .none): + return " exec \"$CMUX_LOGIN_SHELL\" -il --init-command 'source \"$CMUX_FISH_INTEGRATION_FILE\"'" + case (.fish, .some(let resumeInvocation)): + let command = "source \"$CMUX_FISH_INTEGRATION_FILE\"; \(resumeInvocation)" + return " exec \"$CMUX_LOGIN_SHELL\" -il --init-command \(shellQuote(command))" + case (.other, .none): + return "exec \"$CMUX_LOGIN_SHELL\" -i" + case (.other, .some(let resumeInvocation)): + let command = resumeInvocation + "\nexec \"$CMUX_LOGIN_SHELL\" -i" + return "exec \"$CMUX_LOGIN_SHELL\" -ic \(shellQuote(command))" + } + } + static func shellFeatures( environment: [String: String] = ProcessInfo.processInfo.environment ) -> String { diff --git a/Sources/SSHPTYAttachStartupCommandBuilder.swift b/Sources/SSHPTYAttachStartupCommandBuilder.swift index 866a62771d5c..afaa31194a5b 100644 --- a/Sources/SSHPTYAttachStartupCommandBuilder.swift +++ b/Sources/SSHPTYAttachStartupCommandBuilder.swift @@ -53,13 +53,17 @@ 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(), bundledZshIntegration: RemoteInteractiveShellBootstrapBuilder.bundledShellIntegrationScript(named: "cmux-zsh-integration.zsh"), bundledBashIntegration: RemoteInteractiveShellBootstrapBuilder.bundledShellIntegrationScript(named: "cmux-bash-integration.bash"), - bundledFishIntegration: RemoteInteractiveShellBootstrapBuilder.bundledShellIntegrationScript(named: "fish/config.fish") + bundledFishIntegration: RemoteInteractiveShellBootstrapBuilder.bundledShellIntegrationScript(named: "fish/config.fish"), + initialCommand: initialCommand ) } diff --git a/Sources/SessionPersistence.swift b/Sources/SessionPersistence.swift index f719b55e2242..b146d1edfa57 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,7 @@ struct SurfaceResumeBindingSnapshot: Codable, Equatable, Sendable { var autoResume: Bool? var approvalPolicy: SurfaceResumeApprovalPolicy? var approvalRecordId: String? + var launchFlavor: SurfaceResumeLaunchFlavor var updatedAt: TimeInterval init( @@ -295,6 +288,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,6 +308,7 @@ struct SurfaceResumeBindingSnapshot: Codable, Equatable, Sendable { self.autoResume = autoResume self.approvalPolicy = approvalPolicy self.approvalRecordId = Self.normalized(approvalRecordId) + self.launchFlavor = launchFlavor self.updatedAt = updatedAt } @@ -330,6 +325,7 @@ 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: try container.decodeIfPresent(SurfaceResumeLaunchFlavor.self, forKey: .launchFlavor) ?? .local, updatedAt: try container.decodeIfPresent(TimeInterval.self, forKey: .updatedAt) ?? Date().timeIntervalSince1970 ) @@ -374,10 +370,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 fd2d6aa20562..ec4b1f8588eb 100644 --- a/Sources/SessionRemoteWorkspaceSnapshot+Restore.swift +++ b/Sources/SessionRemoteWorkspaceSnapshot+Restore.swift @@ -88,7 +88,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..5b16f359ca25 --- /dev/null +++ b/Sources/SurfaceResumeBindingSnapshot+Remote.swift @@ -0,0 +1,49 @@ +import Foundation + +extension SurfaceResumeBindingSnapshot { + 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..bd3d46f89361 --- /dev/null +++ b/Sources/SurfaceResumeLaunchFlavor.swift @@ -0,0 +1,56 @@ +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 + } + + private enum Kind: String, Codable { + case local + case persistentSSH + } + + 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(Kind.self, forKey: .kind) { + case .local: + self = .local + case .persistentSSH: + self = .persistentSSH( + try container.decode(SurfaceResumeRemoteContext.self, forKey: .remoteContext) + ) + } + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + switch self { + case .local: + try container.encode(Kind.local, forKey: .kind) + case .persistentSSH(let context): + try container.encode(Kind.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..0193e6ac0a41 --- /dev/null +++ b/Sources/SurfaceResumeRemoteContext.swift @@ -0,0 +1,35 @@ +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 { + self.workspaceID == workspaceID && + self.surfaceID == surfaceID && + normalizedSessionID(self.persistentPTYSessionID) == normalizedSessionID(persistentPTYSessionID) + } + + 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 1eb8585463c7..e483a4e41042 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -5691,7 +5691,6 @@ extension TabManager { hasher.combine(false) return } - hasher.combine(true) hasher.combine(snapshot.kind.rawValue) hasher.combine(snapshot.sessionId) @@ -5760,6 +5759,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 1491ea8cc740..5cd3b0583683 100644 --- a/Sources/TerminalController+ControlSurfaceContext4.swift +++ b/Sources/TerminalController+ControlSurfaceContext4.swift @@ -188,7 +188,17 @@ extension TerminalController { ) else { return .surfaceNotFound } - let effectiveBinding = surfaceResumeBindingWithApproval(binding) + let locatedBinding: SurfaceResumeBindingSnapshot + if let remoteWorkspaceID = inputs.remoteWorkspaceID { + guard remoteWorkspaceID == target.workspace.id, + 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..a1efda788af8 --- /dev/null +++ b/Sources/Workspace+RemoteRelayCommandRewrite.swift @@ -0,0 +1,176 @@ +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 { + guard !workspaceAliases.isEmpty || !surfaceAliases.isEmpty || remoteWorkspaceID != nil, + 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 var params = request["params"] as? [String: Any] { + params = Self.remappedRemoteRelayValue( + params, + key: nil, + workspaceAliases: workspaceAliases, + surfaceAliases: surfaceAliases, + didRewrite: &didRewrite + ) as? [String: Any] ?? params + if request["method"] as? String == "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 + } + 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 + } +} diff --git a/Sources/Workspace+RemoteSessionLifecycle.swift b/Sources/Workspace+RemoteSessionLifecycle.swift index 8d0189893307..9c302ad4541c 100644 --- a/Sources/Workspace+RemoteSessionLifecycle.swift +++ b/Sources/Workspace+RemoteSessionLifecycle.swift @@ -115,7 +115,7 @@ extension Workspace { ), processRunner: processRunner, reachabilityProbe: RemoteHostReachabilityProbe(), - relayCommandRewriter: WorkspaceRemoteRelayCommandRewriter(), + relayCommandRewriter: WorkspaceRemoteRelayCommandRewriter(remoteWorkspaceID: id), 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..6bf2d8c86c39 --- /dev/null +++ b/Sources/Workspace+RemoteSurfaceResumeBinding.swift @@ -0,0 +1,72 @@ +import Foundation + +extension Workspace { + 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 0c4f0cf702e1..dd5bdc1df821 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -1287,18 +1287,47 @@ extension Workspace { let restoresRemoteWorkspaceTerminalSnapshot = remoteStartupCommand != nil && (snapshot.terminal?.isRemoteTerminal != false || shouldRestoreSingleDefaultCloudTerminal) - let restoredBindingLaunch: SurfaceResumeStartupLaunch? = if restoresRemoteWorkspaceTerminalSnapshot { - effectiveResumeBindingForStartup?.remoteStartupInputWithLauncherScript(allowLauncherScript: false) - .map(SurfaceResumeStartupLaunch.input) + 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 restoredPersistentSSHResumeCommand: String? = if let restoredRemotePTYSessionID, + let snapshotWorkspaceId { + persistentSSHResumeCommand( + for: effectiveResumeBindingForStartup, + expectedWorkspaceID: snapshotWorkspaceId, + 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) @@ -1372,24 +1401,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 @@ -1421,7 +1437,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 || @@ -1516,7 +1533,13 @@ extension Workspace { ) } if let storedResumeBinding = effectiveResumeBindingForStartup ?? resumeBinding { - surfaceResumeBindingsByPanelId[terminalPanel.id] = storedResumeBinding + surfaceResumeBindingsByPanelId[terminalPanel.id] = storedResumeBinding.retargetingRemoteOwner( + expectedWorkspaceID: snapshotWorkspaceId ?? id, + expectedSurfaceID: snapshot.id, + workspaceID: id, + surfaceID: terminalPanel.id, + persistentPTYSessionID: restoredRemotePTYSessionID + ) } else { surfaceResumeBindingsByPanelId.removeValue(forKey: terminalPanel.id) } @@ -5620,49 +5643,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, @@ -5727,133 +5707,11 @@ final class Workspace: Identifiable, ObservableObject { Self.rewriteRemoteRelayCommandLine( commandLine, workspaceAliases: remoteRelayWorkspaceIDAliases, - surfaceAliases: remoteRelaySurfaceIDAliases + surfaceAliases: remoteRelaySurfaceIDAliases, + remoteWorkspaceID: id ) } - 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 @@ -5890,18 +5748,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, @@ -5913,6 +5784,7 @@ final class Workspace: Identifiable, ObservableObject { return SSHPTYAttachStartupCommandBuilder.command( sessionID: sessionID, foregroundAuth: foregroundAuth, + remoteCommand: remoteCommand, requireExisting: requireExisting ) } @@ -9245,6 +9117,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..041e8f97d180 100644 --- a/Sources/WorkspaceRemoteRelayCommandRewriter.swift +++ b/Sources/WorkspaceRemoteRelayCommandRewriter.swift @@ -5,6 +5,8 @@ import Foundation /// workspace model's alias-aware static rewrite so the package never imports /// `Workspace`. struct WorkspaceRemoteRelayCommandRewriter: RemoteRelayCommandRewriting { + let remoteWorkspaceID: UUID + func rewriteRemoteRelayCommandLine( _ commandLine: Data, workspaceAliases: [UUID: UUID], @@ -13,7 +15,8 @@ struct WorkspaceRemoteRelayCommandRewriter: RemoteRelayCommandRewriting { Workspace.rewriteRemoteRelayCommandLine( commandLine, workspaceAliases: workspaceAliases, - surfaceAliases: surfaceAliases + surfaceAliases: surfaceAliases, + remoteWorkspaceID: remoteWorkspaceID ) } } diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index c2cf36356c27..8cca1555e741 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -1674,8 +1674,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 */; }; @@ -1961,7 +1964,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 */; }; @@ -3713,8 +3718,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 = ""; }; @@ -4000,7 +4008,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 = ""; }; @@ -4782,6 +4792,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 */, @@ -5403,6 +5415,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 */, @@ -7740,8 +7755,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 */, @@ -7969,7 +7987,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 */, From 50e237005406949d98eabe721361de2d1aac0bf5 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 19:55:06 -0700 Subject: [PATCH 03/25] fix: authenticate remote resume relay provenance --- .../ControlCommandCoordinator+Surface3.swift | 3 +- .../ControlSurfaceResumeSetInputs.swift | 10 ++- ...nalController+ControlSurfaceContext4.swift | 5 ++ .../Workspace+RemoteSessionLifecycle.swift | 5 +- Sources/Workspace.swift | 8 +- .../WorkspaceRemoteRelayCommandRewriter.swift | 88 ++++++++++++++++++- cmuxTests/RemoteResumeBindingTests.swift | 37 +++++++- 7 files changed, 146 insertions(+), 10 deletions(-) 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 ec3390f38e1b..c12f161cc042 100644 --- a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+Surface3.swift +++ b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+Surface3.swift @@ -67,7 +67,8 @@ extension ControlCommandCoordinator { source: source, environment: stringMap(params, "environment"), autoResume: source == "agent-hook" ? (bool(params, "auto_resume") ?? false) : false, - remoteWorkspaceID: remoteWorkspaceID + remoteWorkspaceID: remoteWorkspaceID, + remoteRelayParameters: remoteWorkspaceID == nil ? nil : params ) return surfaceResumeResult( context?.controlSurfaceResumeSet( diff --git a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceResumeSetInputs.swift b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceResumeSetInputs.swift index 4c6285915925..864e130b4851 100644 --- a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceResumeSetInputs.swift +++ b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceResumeSetInputs.swift @@ -25,9 +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 authenticated relay's owning remote workspace, when the request - /// entered through an SSH workspace relay. + /// 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. /// @@ -41,6 +42,7 @@ public struct ControlSurfaceResumeSetInputs: Sendable, Equatable { /// - 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?, @@ -50,7 +52,8 @@ public struct ControlSurfaceResumeSetInputs: Sendable, Equatable { source: String?, environment: [String: String]?, autoResume: Bool, - remoteWorkspaceID: UUID? + remoteWorkspaceID: UUID?, + remoteRelayParameters: [String: JSONValue]? ) { self.name = name self.kind = kind @@ -61,5 +64,6 @@ public struct ControlSurfaceResumeSetInputs: Sendable, Equatable { self.environment = environment self.autoResume = autoResume self.remoteWorkspaceID = remoteWorkspaceID + self.remoteRelayParameters = remoteRelayParameters } } diff --git a/Sources/TerminalController+ControlSurfaceContext4.swift b/Sources/TerminalController+ControlSurfaceContext4.swift index 5cd3b0583683..c233c413a779 100644 --- a/Sources/TerminalController+ControlSurfaceContext4.swift +++ b/Sources/TerminalController+ControlSurfaceContext4.swift @@ -191,6 +191,11 @@ extension TerminalController { 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 } diff --git a/Sources/Workspace+RemoteSessionLifecycle.swift b/Sources/Workspace+RemoteSessionLifecycle.swift index 9c302ad4541c..01f3edb68a0e 100644 --- a/Sources/Workspace+RemoteSessionLifecycle.swift +++ b/Sources/Workspace+RemoteSessionLifecycle.swift @@ -115,7 +115,10 @@ extension Workspace { ), processRunner: processRunner, reachabilityProbe: RemoteHostReachabilityProbe(), - relayCommandRewriter: WorkspaceRemoteRelayCommandRewriter(remoteWorkspaceID: id), + relayCommandRewriter: WorkspaceRemoteRelayCommandRewriter( + remoteWorkspaceID: id, + remoteRelayTokenHex: configuration.relayToken + ), buildInfo: WorkspaceRemoteSessionBuildInfo(), daemonStrings: RemoteDaemonStrings.appLocalized, strings: RemoteSessionStrings.appLocalized diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index dd5bdc1df821..55779c407358 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -5704,11 +5704,13 @@ final class Workspace: Identifiable, ObservableObject { } func rewriteRemoteRelayCommandLine(_ commandLine: Data) -> Data { - Self.rewriteRemoteRelayCommandLine( + WorkspaceRemoteRelayCommandRewriter( + remoteWorkspaceID: id, + remoteRelayTokenHex: remoteConfiguration?.relayToken ?? "" + ).rewriteRemoteRelayCommandLine( commandLine, workspaceAliases: remoteRelayWorkspaceIDAliases, - surfaceAliases: remoteRelaySurfaceIDAliases, - remoteWorkspaceID: id + surfaceAliases: remoteRelaySurfaceIDAliases ) } diff --git a/Sources/WorkspaceRemoteRelayCommandRewriter.swift b/Sources/WorkspaceRemoteRelayCommandRewriter.swift index 041e8f97d180..088fc2ae353c 100644 --- a/Sources/WorkspaceRemoteRelayCommandRewriter.swift +++ b/Sources/WorkspaceRemoteRelayCommandRewriter.swift @@ -1,22 +1,108 @@ 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.rewriteRemoteRelayCommandLine( commandLine, workspaceAliases: workspaceAliases, surfaceAliases: surfaceAliases, remoteWorkspaceID: remoteWorkspaceID ) + return authenticatedRemoteResumeCommandLine(rewritten) + } + + 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: C) -> String where C.Element == UInt8 { + let alphabet = Array("0123456789abcdef".utf8) + var encoded: [UInt8] = [] + encoded.reserveCapacity(bytes.count * 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/cmuxTests/RemoteResumeBindingTests.swift b/cmuxTests/RemoteResumeBindingTests.swift index c2682e58ba2b..878f54c9e374 100644 --- a/cmuxTests/RemoteResumeBindingTests.swift +++ b/cmuxTests/RemoteResumeBindingTests.swift @@ -19,6 +19,7 @@ struct RemoteResumeBindingTests { #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) @@ -103,6 +104,7 @@ struct RemoteResumeBindingTests { surfaceID: UUID, remotePTYSessionID: String, localBinding: [String: Any], + spoofedRelayRegistrationRejected: Bool, remoteBinding: [String: Any] ) { _ = NSApplication.shared @@ -145,6 +147,29 @@ struct RemoteResumeBindingTests { ) 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( @@ -178,6 +203,7 @@ struct RemoteResumeBindingTests { surfaceID, remotePTYSessionID, localBinding, + spoofedRelayRegistrationRejected, remoteBinding ) } @@ -222,9 +248,18 @@ struct RemoteResumeBindingTests { } 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] { var data = try JSONSerialization.data(withJSONObject: request) data.append(0x0A) - return try v2Result(requestData: data) + let requestLine = try #require(String(data: data, 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] { From aa7e0cca11f8c549c10de9237cbe02d466261a7a Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 20:02:56 -0700 Subject: [PATCH 04/25] fix: compile relay provenance authentication --- Sources/Workspace+RemoteSessionLifecycle.swift | 2 +- Sources/WorkspaceRemoteRelayCommandRewriter.swift | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/Workspace+RemoteSessionLifecycle.swift b/Sources/Workspace+RemoteSessionLifecycle.swift index 01f3edb68a0e..f93d8b687110 100644 --- a/Sources/Workspace+RemoteSessionLifecycle.swift +++ b/Sources/Workspace+RemoteSessionLifecycle.swift @@ -117,7 +117,7 @@ extension Workspace { reachabilityProbe: RemoteHostReachabilityProbe(), relayCommandRewriter: WorkspaceRemoteRelayCommandRewriter( remoteWorkspaceID: id, - remoteRelayTokenHex: configuration.relayToken + remoteRelayTokenHex: configuration.relayToken ?? "" ), buildInfo: WorkspaceRemoteSessionBuildInfo(), daemonStrings: RemoteDaemonStrings.appLocalized, diff --git a/Sources/WorkspaceRemoteRelayCommandRewriter.swift b/Sources/WorkspaceRemoteRelayCommandRewriter.swift index 088fc2ae353c..1fbea03207e4 100644 --- a/Sources/WorkspaceRemoteRelayCommandRewriter.swift +++ b/Sources/WorkspaceRemoteRelayCommandRewriter.swift @@ -95,10 +95,10 @@ struct WorkspaceRemoteRelayCommandRewriter: RemoteRelayCommandRewriting { } } - private static func hexString(_ bytes: C) -> String where C.Element == UInt8 { + private static func hexString(_ bytes: S) -> String where S.Element == UInt8 { let alphabet = Array("0123456789abcdef".utf8) var encoded: [UInt8] = [] - encoded.reserveCapacity(bytes.count * 2) + encoded.reserveCapacity(bytes.underestimatedCount * 2) for byte in bytes { encoded.append(alphabet[Int(byte >> 4)]) encoded.append(alphabet[Int(byte & 0x0f)]) From 35ab5de8c29db38a6d2903d9de65cf5430cb8d2d Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 20:07:16 -0700 Subject: [PATCH 05/25] fix: address remote resume review findings --- ...RemoteInteractiveShellBootstrapBuilder.swift | 1 + Sources/SurfaceResumeRemoteContext.swift | 10 +++++++--- .../WorkspaceRemoteRelayCommandRewriter.swift | 5 ++++- cmuxTests/RemoteResumeBindingTests.swift | 17 +++++++++++++++++ 4 files changed, 29 insertions(+), 4 deletions(-) diff --git a/Sources/RemoteInteractiveShellBootstrapBuilder.swift b/Sources/RemoteInteractiveShellBootstrapBuilder.swift index e0067d3703ea..05127654b9cf 100644 --- a/Sources/RemoteInteractiveShellBootstrapBuilder.swift +++ b/Sources/RemoteInteractiveShellBootstrapBuilder.swift @@ -153,6 +153,7 @@ enum RemoteInteractiveShellBootstrapBuilder { case (.bash, .none): return " exec \"$CMUX_LOGIN_SHELL\" --rcfile \"$cmux_shell_dir/.bashrc\" -i" case (.bash, .some(let resumeInvocation)): + // The resumed shell only inherits the exported integration-directory variable. let command = resumeInvocation + "\nexec \"$CMUX_LOGIN_SHELL\" --rcfile \"$CMUX_SHELL_INTEGRATION_DIR/.bashrc\" -i" return " exec \"$CMUX_LOGIN_SHELL\" --rcfile \"$cmux_shell_dir/.bashrc\" -ic \(shellQuote(command))" diff --git a/Sources/SurfaceResumeRemoteContext.swift b/Sources/SurfaceResumeRemoteContext.swift index 0193e6ac0a41..efa57f08727e 100644 --- a/Sources/SurfaceResumeRemoteContext.swift +++ b/Sources/SurfaceResumeRemoteContext.swift @@ -23,9 +23,13 @@ struct SurfaceResumeRemoteContext: Codable, Equatable, Hashable, Sendable { surfaceID: UUID, persistentPTYSessionID: String ) -> Bool { - self.workspaceID == workspaceID && - self.surfaceID == surfaceID && - normalizedSessionID(self.persistentPTYSessionID) == normalizedSessionID(persistentPTYSessionID) + 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? { diff --git a/Sources/WorkspaceRemoteRelayCommandRewriter.swift b/Sources/WorkspaceRemoteRelayCommandRewriter.swift index 1fbea03207e4..0c8e85658240 100644 --- a/Sources/WorkspaceRemoteRelayCommandRewriter.swift +++ b/Sources/WorkspaceRemoteRelayCommandRewriter.swift @@ -7,6 +7,7 @@ import Foundation /// `Workspace`. struct WorkspaceRemoteRelayCommandRewriter: RemoteRelayCommandRewriting { private static let authenticationCodeKey = "_cmux_remote_relay_authentication_code" + private static let remoteResumeMethodNeedle = Data(#""surface.resume.set""#.utf8) let remoteWorkspaceID: UUID let remoteRelayTokenHex: String @@ -16,12 +17,14 @@ struct WorkspaceRemoteRelayCommandRewriter: RemoteRelayCommandRewriting { workspaceAliases: [UUID: UUID], surfaceAliases: [UUID: UUID] ) -> Data { + let authenticatesRemoteResume = commandLine.range(of: Self.remoteResumeMethodNeedle) != nil let rewritten = Workspace.rewriteRemoteRelayCommandLine( commandLine, workspaceAliases: workspaceAliases, surfaceAliases: surfaceAliases, - remoteWorkspaceID: remoteWorkspaceID + remoteWorkspaceID: authenticatesRemoteResume ? remoteWorkspaceID : nil ) + guard authenticatesRemoteResume else { return rewritten } return authenticatedRemoteResumeCommandLine(rewritten) } diff --git a/cmuxTests/RemoteResumeBindingTests.swift b/cmuxTests/RemoteResumeBindingTests.swift index 878f54c9e374..a4f645c367aa 100644 --- a/cmuxTests/RemoteResumeBindingTests.swift +++ b/cmuxTests/RemoteResumeBindingTests.swift @@ -13,6 +13,23 @@ import Testing struct RemoteResumeBindingTests { private let relayPort = 64_089 + @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 relayedRegistrationUsesExplicitRemoteFlavorAfterAliasRewrite() throws { let fixture = try makeRelayedFixture() From dd629a60f7817e8c1ea61df902963ce6688d1cb1 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 20:12:03 -0700 Subject: [PATCH 06/25] refactor: satisfy remote resume file policy --- ...moteInteractiveShellBootstrapBuilder.swift | 70 +++++++++---------- Sources/SurfaceResumeLaunchFlavor.swift | 21 +++--- 2 files changed, 46 insertions(+), 45 deletions(-) diff --git a/Sources/RemoteInteractiveShellBootstrapBuilder.swift b/Sources/RemoteInteractiveShellBootstrapBuilder.swift index 05127654b9cf..ee8198458c92 100644 --- a/Sources/RemoteInteractiveShellBootstrapBuilder.swift +++ b/Sources/RemoteInteractiveShellBootstrapBuilder.swift @@ -86,7 +86,7 @@ enum RemoteInteractiveShellBootstrapBuilder { outerLines += [ " export CMUX_REAL_ZDOTDIR=\"${ZDOTDIR:-$HOME}\"", " export ZDOTDIR=\"$cmux_shell_dir\"", - loginShellLaunchLine(kind: .zsh, initialCommand: initialCommand), + zshLoginShellLaunchLine(initialCommand: initialCommand), " ;;", " bash)", " cat > \"$cmux_shell_dir/.bashrc\" <<'CMUXBASHRC'", @@ -107,7 +107,7 @@ enum RemoteInteractiveShellBootstrapBuilder { ] outerLines.append(contentsOf: relayWarmupLines.map { " " + $0 }) outerLines += [ - loginShellLaunchLine(kind: .bash, initialCommand: initialCommand), + bashLoginShellLaunchLine(initialCommand: initialCommand), " ;;", " fish)", ] @@ -115,13 +115,13 @@ enum RemoteInteractiveShellBootstrapBuilder { outerLines += [ " export CMUX_FISH_INTEGRATION_FILE=\"$cmux_shell_dir/fish/config.fish\"", " export CMUX_FISH_USER_CONFIG_ALREADY_LOADED=1", - loginShellLaunchLine(kind: .fish, initialCommand: initialCommand), + fishLoginShellLaunchLine(initialCommand: initialCommand), " ;;", " *)", ] outerLines.append(contentsOf: relayWarmupLines) outerLines += [ - loginShellLaunchLine(kind: .other, initialCommand: initialCommand), + otherLoginShellLaunchLine(initialCommand: initialCommand), ";;", "esac", ] @@ -129,45 +129,45 @@ enum RemoteInteractiveShellBootstrapBuilder { return outerLines.joined(separator: "\n") } - private enum LoginShellKind { - case zsh - case bash - case fish - case other - } - - private static func loginShellLaunchLine( - kind: LoginShellKind, - initialCommand: String? - ) -> String { + private static func resumeInvocation(_ initialCommand: String?) -> String? { let normalizedCommand = initialCommand?.trimmingCharacters(in: .whitespacesAndNewlines) - let resumeInvocation = normalizedCommand.flatMap { command in + return normalizedCommand.flatMap { command in command.isEmpty ? nil : "/bin/sh -c \(shellQuote(command))" } - switch (kind, resumeInvocation) { - case (.zsh, .none): + } + + private static func zshLoginShellLaunchLine(initialCommand: String?) -> String { + guard let resumeInvocation = resumeInvocation(initialCommand) else { return " exec \"$CMUX_LOGIN_SHELL\" -il" - case (.zsh, .some(let resumeInvocation)): - let command = resumeInvocation + "\nexec \"$CMUX_LOGIN_SHELL\" -il" - return " exec \"$CMUX_LOGIN_SHELL\" -ilc \(shellQuote(command))" - case (.bash, .none): + } + let command = resumeInvocation + "\nexec \"$CMUX_LOGIN_SHELL\" -il" + return " exec \"$CMUX_LOGIN_SHELL\" -ilc \(shellQuote(command))" + } + + private static func bashLoginShellLaunchLine(initialCommand: String?) -> String { + guard let resumeInvocation = resumeInvocation(initialCommand) else { return " exec \"$CMUX_LOGIN_SHELL\" --rcfile \"$cmux_shell_dir/.bashrc\" -i" - case (.bash, .some(let resumeInvocation)): - // The resumed shell only inherits the exported integration-directory variable. - let command = resumeInvocation + - "\nexec \"$CMUX_LOGIN_SHELL\" --rcfile \"$CMUX_SHELL_INTEGRATION_DIR/.bashrc\" -i" - return " exec \"$CMUX_LOGIN_SHELL\" --rcfile \"$cmux_shell_dir/.bashrc\" -ic \(shellQuote(command))" - case (.fish, .none): + } + // The resumed shell only inherits the exported integration-directory variable. + let command = resumeInvocation + + "\nexec \"$CMUX_LOGIN_SHELL\" --rcfile \"$CMUX_SHELL_INTEGRATION_DIR/.bashrc\" -i" + return " exec \"$CMUX_LOGIN_SHELL\" --rcfile \"$cmux_shell_dir/.bashrc\" -ic \(shellQuote(command))" + } + + private static func fishLoginShellLaunchLine(initialCommand: String?) -> String { + guard let resumeInvocation = resumeInvocation(initialCommand) else { return " exec \"$CMUX_LOGIN_SHELL\" -il --init-command 'source \"$CMUX_FISH_INTEGRATION_FILE\"'" - case (.fish, .some(let resumeInvocation)): - let command = "source \"$CMUX_FISH_INTEGRATION_FILE\"; \(resumeInvocation)" - return " exec \"$CMUX_LOGIN_SHELL\" -il --init-command \(shellQuote(command))" - case (.other, .none): + } + let command = "source \"$CMUX_FISH_INTEGRATION_FILE\"; \(resumeInvocation)" + return " exec \"$CMUX_LOGIN_SHELL\" -il --init-command \(shellQuote(command))" + } + + private static func otherLoginShellLaunchLine(initialCommand: String?) -> String { + guard let resumeInvocation = resumeInvocation(initialCommand) else { return "exec \"$CMUX_LOGIN_SHELL\" -i" - case (.other, .some(let resumeInvocation)): - let command = resumeInvocation + "\nexec \"$CMUX_LOGIN_SHELL\" -i" - return "exec \"$CMUX_LOGIN_SHELL\" -ic \(shellQuote(command))" } + let command = resumeInvocation + "\nexec \"$CMUX_LOGIN_SHELL\" -i" + return "exec \"$CMUX_LOGIN_SHELL\" -ic \(shellQuote(command))" } static func shellFeatures( diff --git a/Sources/SurfaceResumeLaunchFlavor.swift b/Sources/SurfaceResumeLaunchFlavor.swift index bd3d46f89361..8d83a64cd453 100644 --- a/Sources/SurfaceResumeLaunchFlavor.swift +++ b/Sources/SurfaceResumeLaunchFlavor.swift @@ -10,11 +10,6 @@ enum SurfaceResumeLaunchFlavor: Equatable, Hashable, Sendable { case remoteContext } - private enum Kind: String, Codable { - case local - case persistentSSH - } - var executionLocationRawValue: String { switch self { case .local: @@ -33,13 +28,19 @@ enum SurfaceResumeLaunchFlavor: Equatable, Hashable, Sendable { extension SurfaceResumeLaunchFlavor: Codable { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - switch try container.decode(Kind.self, forKey: .kind) { - case .local: + switch try container.decode(String.self, forKey: .kind) { + case "local": self = .local - case .persistentSSH: + 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" + ) } } @@ -47,9 +48,9 @@ extension SurfaceResumeLaunchFlavor: Codable { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case .local: - try container.encode(Kind.local, forKey: .kind) + try container.encode("local", forKey: .kind) case .persistentSSH(let context): - try container.encode(Kind.persistentSSH, forKey: .kind) + try container.encode("persistentSSH", forKey: .kind) try container.encode(context, forKey: .remoteContext) } } From 7a19f201d7d024f745ad48e2e396921861ff327b Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 20:42:37 -0700 Subject: [PATCH 07/25] test: cover legacy remote resume migration --- cmuxTests/RemoteResumeBindingTests.swift | 57 ++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/cmuxTests/RemoteResumeBindingTests.swift b/cmuxTests/RemoteResumeBindingTests.swift index a4f645c367aa..510239ebcce3 100644 --- a/cmuxTests/RemoteResumeBindingTests.swift +++ b/cmuxTests/RemoteResumeBindingTests.swift @@ -115,6 +115,44 @@ struct RemoteResumeBindingTests { ) } + @Test + func legacyRemoteSnapshotMigratesBindingIntoPersistentSSHContext() throws { + let fixture = try makeRelayedFixture() + let legacySnapshot = try snapshotWithoutLaunchFlavor(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, + workspaceID: restoredWorkspace.id, + surfaceID: restoredSurfaceID + ) + + 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) + } + private func makeRelayedFixture() throws -> ( snapshot: SessionWorkspaceSnapshot, workspaceID: UUID, @@ -301,6 +339,25 @@ struct RemoteResumeBindingTests { return try #require(String(data: data, encoding: .utf8)) } + private func snapshotWithoutLaunchFlavor( + _ snapshot: SessionWorkspaceSnapshot + ) 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]) + 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 expectRemoteResumeBootstrap( _ command: String, workspaceID: UUID, From 0f6324d9c06dec1b63846f0822d90d96c7a5c9ff Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 20:46:01 -0700 Subject: [PATCH 08/25] fix: migrate legacy remote resume bindings --- Sources/SessionPersistence.swift | 6 ++- .../SurfaceResumeBindingSnapshot+Remote.swift | 6 +++ ...Workspace+RemoteSurfaceResumeBinding.swift | 26 ++++++++++++ Sources/Workspace.swift | 40 +++++++++++-------- 4 files changed, 61 insertions(+), 17 deletions(-) diff --git a/Sources/SessionPersistence.swift b/Sources/SessionPersistence.swift index b146d1edfa57..36fa59cd5f0c 100644 --- a/Sources/SessionPersistence.swift +++ b/Sources/SessionPersistence.swift @@ -275,6 +275,8 @@ struct SurfaceResumeBindingSnapshot: Codable, Equatable, Sendable { 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( @@ -314,6 +316,7 @@ struct SurfaceResumeBindingSnapshot: Codable, Equatable, Sendable { 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), @@ -325,10 +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: try container.decodeIfPresent(SurfaceResumeLaunchFlavor.self, forKey: .launchFlavor) ?? .local, + launchFlavor: decodedLaunchFlavor ?? .local, updatedAt: try container.decodeIfPresent(TimeInterval.self, forKey: .updatedAt) ?? Date().timeIntervalSince1970 ) + wasDecodedWithoutLaunchFlavor = decodedLaunchFlavor == nil } var isProcessDetected: Bool { diff --git a/Sources/SurfaceResumeBindingSnapshot+Remote.swift b/Sources/SurfaceResumeBindingSnapshot+Remote.swift index 5b16f359ca25..8f7bc04d6198 100644 --- a/Sources/SurfaceResumeBindingSnapshot+Remote.swift +++ b/Sources/SurfaceResumeBindingSnapshot+Remote.swift @@ -1,6 +1,12 @@ 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)) } diff --git a/Sources/Workspace+RemoteSurfaceResumeBinding.swift b/Sources/Workspace+RemoteSurfaceResumeBinding.swift index 6bf2d8c86c39..c557df9e4d1e 100644 --- a/Sources/Workspace+RemoteSurfaceResumeBinding.swift +++ b/Sources/Workspace+RemoteSurfaceResumeBinding.swift @@ -1,6 +1,32 @@ 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 snapshotWorkspaceID, + 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, diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 55779c407358..1c3e36da6770 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -1258,13 +1258,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) @@ -1272,17 +1269,6 @@ 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 resumeBindingForStartup = - restoredHibernation != nil || - (resumeBinding?.isProcessDetected == true && resumeBinding?.autoResume != true) - ? nil - : resumeBinding - let effectiveResumeBindingForStartup = sessionRestorePolicy.approvedSurfaceResumeBinding( - resumeBindingForStartup, - autoResumeAgentSessions: shouldAutoResumeAgent, - promptForApproval: true, - approvalStoreURL: SurfaceResumeApprovalStore.defaultURL() - ) let remoteStartupCommand = remoteTerminalStartupCommand() let restoresRemoteWorkspaceTerminalSnapshot = remoteStartupCommand != nil && @@ -1303,6 +1289,28 @@ extension Workspace { } return Self.defaultSSHPTYSessionID(workspaceId: snapshotWorkspaceId ?? id, panelId: snapshot.id) }() + let locatedResumeBinding = migratingLegacyPersistentSSHResumeBinding( + persistedResumeBinding, + snapshotWorkspaceID: snapshotWorkspaceId, + snapshotSurfaceID: snapshot.id, + persistentPTYSessionID: restoredRemotePTYSessionID, + restoresRemoteTerminal: restoresRemoteWorkspaceTerminalSnapshot + ) + let resumeBinding = Self.resumeBindingForSessionRestore( + locatedResumeBinding, + restorableAgent: restorableAgent + ) + let resumeBindingForStartup = + restoredHibernation != nil || + (resumeBinding?.isProcessDetected == true && resumeBinding?.autoResume != true) + ? nil + : resumeBinding + let effectiveResumeBindingForStartup = sessionRestorePolicy.approvedSurfaceResumeBinding( + resumeBindingForStartup, + autoResumeAgentSessions: shouldAutoResumeAgent, + promptForApproval: true, + approvalStoreURL: SurfaceResumeApprovalStore.defaultURL() + ) let restoredPersistentSSHResumeCommand: String? = if let restoredRemotePTYSessionID, let snapshotWorkspaceId { persistentSSHResumeCommand( From 536f17a22a0fbf340e15f2d2e922a9d2d8d28ed9 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 20:49:21 -0700 Subject: [PATCH 09/25] test: cover workspace-id-free legacy resume --- cmuxTests/RemoteResumeBindingTests.swift | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/cmuxTests/RemoteResumeBindingTests.swift b/cmuxTests/RemoteResumeBindingTests.swift index 510239ebcce3..abff261b22e5 100644 --- a/cmuxTests/RemoteResumeBindingTests.swift +++ b/cmuxTests/RemoteResumeBindingTests.swift @@ -116,9 +116,9 @@ struct RemoteResumeBindingTests { } @Test - func legacyRemoteSnapshotMigratesBindingIntoPersistentSSHContext() throws { + func legacyRemoteSnapshotWithoutWorkspaceIDMigratesBindingIntoPersistentSSHContext() throws { let fixture = try makeRelayedFixture() - let legacySnapshot = try snapshotWithoutLaunchFlavor(fixture.snapshot) + 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) @@ -339,11 +339,12 @@ struct RemoteResumeBindingTests { return try #require(String(data: data, encoding: .utf8)) } - private func snapshotWithoutLaunchFlavor( + 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] From 81f5f5fab719199ed52bb714dbea0471c70e9b14 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 20:50:47 -0700 Subject: [PATCH 10/25] fix: recover legacy remote workspace identity --- Sources/Workspace+RemoteSurfaceResumeBinding.swift | 3 +-- Sources/Workspace.swift | 12 +++++++----- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/Sources/Workspace+RemoteSurfaceResumeBinding.swift b/Sources/Workspace+RemoteSurfaceResumeBinding.swift index c557df9e4d1e..aa1c01f8353c 100644 --- a/Sources/Workspace+RemoteSurfaceResumeBinding.swift +++ b/Sources/Workspace+RemoteSurfaceResumeBinding.swift @@ -4,14 +4,13 @@ extension Workspace { /// Migrates a legacy binding only when its saved terminal has authoritative persistent-SSH ownership. func migratingLegacyPersistentSSHResumeBinding( _ binding: SurfaceResumeBindingSnapshot?, - snapshotWorkspaceID: UUID?, + snapshotWorkspaceID: UUID, snapshotSurfaceID: UUID, persistentPTYSessionID: String?, restoresRemoteTerminal: Bool ) -> SurfaceResumeBindingSnapshot? { guard let binding, restoresRemoteTerminal, - let snapshotWorkspaceID, let persistentPTYSessionID = normalizedRemotePTYSessionID(persistentPTYSessionID), let configuration = remoteConfiguration, configuration.transport == .ssh, diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 1c3e36da6770..d3aff523bcb8 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -1289,9 +1289,12 @@ extension Workspace { } return Self.defaultSSHPTYSessionID(workspaceId: snapshotWorkspaceId ?? id, panelId: snapshot.id) }() + let restoredResumeSnapshotWorkspaceID = snapshotWorkspaceId + ?? restoredRemotePTYSessionID.flatMap { Self.parsedDefaultSSHPTYSessionID($0)?.workspaceId } + ?? id let locatedResumeBinding = migratingLegacyPersistentSSHResumeBinding( persistedResumeBinding, - snapshotWorkspaceID: snapshotWorkspaceId, + snapshotWorkspaceID: restoredResumeSnapshotWorkspaceID, snapshotSurfaceID: snapshot.id, persistentPTYSessionID: restoredRemotePTYSessionID, restoresRemoteTerminal: restoresRemoteWorkspaceTerminalSnapshot @@ -1311,11 +1314,10 @@ extension Workspace { promptForApproval: true, approvalStoreURL: SurfaceResumeApprovalStore.defaultURL() ) - let restoredPersistentSSHResumeCommand: String? = if let restoredRemotePTYSessionID, - let snapshotWorkspaceId { + let restoredPersistentSSHResumeCommand: String? = if let restoredRemotePTYSessionID { persistentSSHResumeCommand( for: effectiveResumeBindingForStartup, - expectedWorkspaceID: snapshotWorkspaceId, + expectedWorkspaceID: restoredResumeSnapshotWorkspaceID, expectedSurfaceID: snapshot.id, persistentPTYSessionID: restoredRemotePTYSessionID ) @@ -1542,7 +1544,7 @@ extension Workspace { } if let storedResumeBinding = effectiveResumeBindingForStartup ?? resumeBinding { surfaceResumeBindingsByPanelId[terminalPanel.id] = storedResumeBinding.retargetingRemoteOwner( - expectedWorkspaceID: snapshotWorkspaceId ?? id, + expectedWorkspaceID: restoredResumeSnapshotWorkspaceID, expectedSurfaceID: snapshot.id, workspaceID: id, surfaceID: terminalPanel.id, From 1bb3105c0a6909efe9bd6311021366e1e2c7fddb Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 21:05:35 -0700 Subject: [PATCH 11/25] test: remove unused remote resume helper inputs --- cmuxTests/RemoteResumeBindingTests.swift | 26 ++++-------------------- 1 file changed, 4 insertions(+), 22 deletions(-) diff --git a/cmuxTests/RemoteResumeBindingTests.swift b/cmuxTests/RemoteResumeBindingTests.swift index abff261b22e5..9fbfd5de1042 100644 --- a/cmuxTests/RemoteResumeBindingTests.swift +++ b/cmuxTests/RemoteResumeBindingTests.swift @@ -69,11 +69,7 @@ struct RemoteResumeBindingTests { #expect(liveFirstCommand.contains("ssh-pty-attach"), "\(liveFirstCommand)") #expect(liveFirstCommand.contains("--require-existing"), "\(liveFirstCommand)") let liveFirstRemoteCommand = try decodedRemoteCommand(from: liveFirstCommand) - try expectRemoteResumeBootstrap( - liveFirstRemoteCommand, - workspaceID: restoredWorkspace.id, - surfaceID: restoredSurfaceID - ) + try expectRemoteResumeBootstrap(liveFirstRemoteCommand) #expect(restoredPanel.surface.debugInitialInputForTesting() == nil) let roundTrip = restoredWorkspace.sessionSnapshot(includeScrollback: false) @@ -108,11 +104,7 @@ struct RemoteResumeBindingTests { ) #expect(!gonePTYCommand.contains("--require-existing"), "\(gonePTYCommand)") let gonePTYRemoteCommand = try decodedRemoteCommand(from: gonePTYCommand) - try expectRemoteResumeBootstrap( - gonePTYRemoteCommand, - workspaceID: restoredWorkspace.id, - surfaceID: restoredSurfaceID - ) + try expectRemoteResumeBootstrap(gonePTYRemoteCommand) } @Test @@ -134,11 +126,7 @@ struct RemoteResumeBindingTests { restoredWorkspace.terminalPanel(for: restoredSurfaceID)?.surface.debugInitialCommand() ) let remoteCommand = try decodedRemoteCommand(from: startupCommand) - try expectRemoteResumeBootstrap( - remoteCommand, - workspaceID: restoredWorkspace.id, - surfaceID: restoredSurfaceID - ) + try expectRemoteResumeBootstrap(remoteCommand) let roundTripBinding = try #require( restoredWorkspace.sessionSnapshot(includeScrollback: false) @@ -359,11 +347,7 @@ struct RemoteResumeBindingTests { return try JSONDecoder().decode(SessionWorkspaceSnapshot.self, from: legacyData) } - private func expectRemoteResumeBootstrap( - _ command: String, - workspaceID: UUID, - surfaceID: UUID - ) throws { + 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)") @@ -371,8 +355,6 @@ struct RemoteResumeBindingTests { #expect(command.contains("REMOTE_FLAG=value with spaces"), "\(command)") #expect(command.contains("session-remote-7989"), "\(command)") #expect(!command.contains("ANTHROPIC_API_KEY"), "\(command)") - _ = workspaceID - _ = surfaceID } private func reserveRemoteRestoreSocket() -> String { From 9e6e88043c42e21f6edc8de9da9196401c7e0194 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 21:08:57 -0700 Subject: [PATCH 12/25] test: cover resume with unsupported remote shell --- cmuxTests/ShellStartupMatrixTests.swift | 31 ++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/cmuxTests/ShellStartupMatrixTests.swift b/cmuxTests/ShellStartupMatrixTests.swift index d44801e5290c..de0792b341c6 100644 --- a/cmuxTests/ShellStartupMatrixTests.swift +++ b/cmuxTests/ShellStartupMatrixTests.swift @@ -176,6 +176,19 @@ struct ShellStartupMatrixTests { } } + @Test + func generatedSshBootstrapRunsResumeBeforeUnsupportedInteractiveShell() throws { + let result = try runGeneratedBootstrap( + shellName: "nu", + 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", "sh", "dash", "ksh", "tcsh", "csh"]) func generatedSshBootstrapStartupStaysUnderPerformanceBudget(shellName: String) throws { let result = try runGeneratedBootstrap(shellName: shellName) @@ -290,6 +303,7 @@ struct ShellStartupMatrixTests { private struct GeneratedBootstrapResult { let home: URL let capture: String + let resumeMarker: String let process: ProcessRunResult } @@ -298,7 +312,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)") @@ -320,7 +335,8 @@ struct ShellStartupMatrixTests { ]), bundledZshIntegration: "cmux_zsh_marker=1", bundledBashIntegration: "cmux_bash_marker=1", - bundledFishIntegration: "set -gx CMUX_FISH_MARKER 1" + bundledFishIntegration: "set -gx CMUX_FISH_MARKER 1", + initialCommand: initialCommand ) if let workspaceID { script = script.replacingOccurrences(of: "__CMUX_WORKSPACE_ID__", with: workspaceID) @@ -351,7 +367,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 { From c2ecafc5faa6623de890996bd0ac068fbb48e4a3 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 21:25:50 -0700 Subject: [PATCH 13/25] test: import remote configuration module --- cmuxTests/RemoteResumeBindingTests.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/cmuxTests/RemoteResumeBindingTests.swift b/cmuxTests/RemoteResumeBindingTests.swift index 9fbfd5de1042..9075e2c8b9ce 100644 --- a/cmuxTests/RemoteResumeBindingTests.swift +++ b/cmuxTests/RemoteResumeBindingTests.swift @@ -1,4 +1,5 @@ import AppKit +import CmuxCore import Foundation import Testing From f9ad1a6c4d7aef810b434a446c317c2a7bb70f64 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 21:37:56 -0700 Subject: [PATCH 14/25] test: disambiguate resume command decoding --- cmuxTests/RemoteResumeBindingTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmuxTests/RemoteResumeBindingTests.swift b/cmuxTests/RemoteResumeBindingTests.swift index 9075e2c8b9ce..bd4b0b50b217 100644 --- a/cmuxTests/RemoteResumeBindingTests.swift +++ b/cmuxTests/RemoteResumeBindingTests.swift @@ -324,7 +324,7 @@ struct RemoteResumeBindingTests { 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.init(base64Encoded:))) + let data = try #require(encoded.flatMap { Data(base64Encoded: $0) }) return try #require(String(data: data, encoding: .utf8)) } From a5e338a6de7dc2af7c9e166172efaf8142cfc15c Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 22:23:52 -0700 Subject: [PATCH 15/25] fix: resume before unsupported remote shells --- Sources/RemoteInteractiveShellBootstrapBuilder.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/RemoteInteractiveShellBootstrapBuilder.swift b/Sources/RemoteInteractiveShellBootstrapBuilder.swift index ee8198458c92..9817ebc55fa3 100644 --- a/Sources/RemoteInteractiveShellBootstrapBuilder.swift +++ b/Sources/RemoteInteractiveShellBootstrapBuilder.swift @@ -167,7 +167,7 @@ enum RemoteInteractiveShellBootstrapBuilder { return "exec \"$CMUX_LOGIN_SHELL\" -i" } let command = resumeInvocation + "\nexec \"$CMUX_LOGIN_SHELL\" -i" - return "exec \"$CMUX_LOGIN_SHELL\" -ic \(shellQuote(command))" + return "exec /bin/sh -c \(shellQuote(command))" } static func shellFeatures( From ca90da27c4b170a9b9ce83da1ba81a8d8edb2d7b Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 22:27:22 -0700 Subject: [PATCH 16/25] test: cover escaped remote resume method --- cmuxTests/RemoteResumeBindingTests.swift | 28 ++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/cmuxTests/RemoteResumeBindingTests.swift b/cmuxTests/RemoteResumeBindingTests.swift index bd4b0b50b217..cfd7c6cb40f0 100644 --- a/cmuxTests/RemoteResumeBindingTests.swift +++ b/cmuxTests/RemoteResumeBindingTests.swift @@ -31,6 +31,34 @@ struct RemoteResumeBindingTests { )) } + @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 relayedRegistrationUsesExplicitRemoteFlavorAfterAliasRewrite() throws { let fixture = try makeRelayedFixture() From 8b95fa29692b08c3c1ebcf166a46a22b6c17873a Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 22:40:52 -0700 Subject: [PATCH 17/25] fix: preserve unsupported remote login shells --- Sources/RemoteInteractiveShellBootstrapBuilder.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/RemoteInteractiveShellBootstrapBuilder.swift b/Sources/RemoteInteractiveShellBootstrapBuilder.swift index 9817ebc55fa3..f8d43f0ff396 100644 --- a/Sources/RemoteInteractiveShellBootstrapBuilder.swift +++ b/Sources/RemoteInteractiveShellBootstrapBuilder.swift @@ -166,8 +166,8 @@ enum RemoteInteractiveShellBootstrapBuilder { guard let resumeInvocation = resumeInvocation(initialCommand) else { return "exec \"$CMUX_LOGIN_SHELL\" -i" } - let command = resumeInvocation + "\nexec \"$CMUX_LOGIN_SHELL\" -i" - return "exec /bin/sh -c \(shellQuote(command))" + let command = resumeInvocation + "\nexec \"$1\" -i" + return "exec /bin/sh -c \(shellQuote(command)) cmux-resume \"$CMUX_LOGIN_SHELL\"" } static func shellFeatures( From 38585b7f7c24d982ff21a2af6099c996d2cddf85 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 22:40:56 -0700 Subject: [PATCH 18/25] fix: classify relayed resume methods structurally --- .../Workspace+RemoteRelayCommandRewrite.swift | 27 ++++++++++++++----- .../WorkspaceRemoteRelayCommandRewriter.swift | 11 ++++---- 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/Sources/Workspace+RemoteRelayCommandRewrite.swift b/Sources/Workspace+RemoteRelayCommandRewrite.swift index a1efda788af8..d425104f2511 100644 --- a/Sources/Workspace+RemoteRelayCommandRewrite.swift +++ b/Sources/Workspace+RemoteRelayCommandRewrite.swift @@ -50,16 +50,31 @@ extension Workspace { 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 + 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 + return (commandLine, nil) } + let method = request["method"] as? String var didRewrite = false if var params = request["params"] as? [String: Any] { @@ -70,7 +85,7 @@ extension Workspace { surfaceAliases: surfaceAliases, didRewrite: &didRewrite ) as? [String: Any] ?? params - if request["method"] as? String == "surface.resume.set", + if method == "surface.resume.set", let remoteWorkspaceID { params["_cmux_remote_workspace_id"] = remoteWorkspaceID.uuidString didRewrite = true @@ -81,12 +96,12 @@ extension Workspace { guard didRewrite, JSONSerialization.isValidJSONObject(request), let rewritten = try? JSONSerialization.data(withJSONObject: request, options: []) else { - return commandLine + return (commandLine, method) } if commandLine.last == 0x0A { - return rewritten + Data([0x0A]) + return (rewritten + Data([0x0A]), method) } - return rewritten + return (rewritten, method) } private nonisolated static func remappedRemoteRelayValue( diff --git a/Sources/WorkspaceRemoteRelayCommandRewriter.swift b/Sources/WorkspaceRemoteRelayCommandRewriter.swift index 0c8e85658240..b4f475375194 100644 --- a/Sources/WorkspaceRemoteRelayCommandRewriter.swift +++ b/Sources/WorkspaceRemoteRelayCommandRewriter.swift @@ -7,7 +7,6 @@ import Foundation /// `Workspace`. struct WorkspaceRemoteRelayCommandRewriter: RemoteRelayCommandRewriting { private static let authenticationCodeKey = "_cmux_remote_relay_authentication_code" - private static let remoteResumeMethodNeedle = Data(#""surface.resume.set""#.utf8) let remoteWorkspaceID: UUID let remoteRelayTokenHex: String @@ -17,15 +16,15 @@ struct WorkspaceRemoteRelayCommandRewriter: RemoteRelayCommandRewriting { workspaceAliases: [UUID: UUID], surfaceAliases: [UUID: UUID] ) -> Data { - let authenticatesRemoteResume = commandLine.range(of: Self.remoteResumeMethodNeedle) != nil - let rewritten = Workspace.rewriteRemoteRelayCommandLine( + let rewritten = Workspace.rewriteRemoteRelayCommandLineAndExtractMethod( commandLine, workspaceAliases: workspaceAliases, surfaceAliases: surfaceAliases, - remoteWorkspaceID: authenticatesRemoteResume ? remoteWorkspaceID : nil + remoteWorkspaceID: remoteWorkspaceID ) - guard authenticatesRemoteResume else { return rewritten } - return authenticatedRemoteResumeCommandLine(rewritten) + // 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( From 004d8de1561a5babb3c24011aa964f6e97b7ca0b Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Sat, 18 Jul 2026 22:43:04 -0700 Subject: [PATCH 19/25] test: remove unnecessary remote resume throws --- cmuxTests/RemoteResumeBindingTests.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cmuxTests/RemoteResumeBindingTests.swift b/cmuxTests/RemoteResumeBindingTests.swift index cfd7c6cb40f0..44487e7f5d98 100644 --- a/cmuxTests/RemoteResumeBindingTests.swift +++ b/cmuxTests/RemoteResumeBindingTests.swift @@ -98,7 +98,7 @@ struct RemoteResumeBindingTests { #expect(liveFirstCommand.contains("ssh-pty-attach"), "\(liveFirstCommand)") #expect(liveFirstCommand.contains("--require-existing"), "\(liveFirstCommand)") let liveFirstRemoteCommand = try decodedRemoteCommand(from: liveFirstCommand) - try expectRemoteResumeBootstrap(liveFirstRemoteCommand) + expectRemoteResumeBootstrap(liveFirstRemoteCommand) #expect(restoredPanel.surface.debugInitialInputForTesting() == nil) let roundTrip = restoredWorkspace.sessionSnapshot(includeScrollback: false) @@ -133,7 +133,7 @@ struct RemoteResumeBindingTests { ) #expect(!gonePTYCommand.contains("--require-existing"), "\(gonePTYCommand)") let gonePTYRemoteCommand = try decodedRemoteCommand(from: gonePTYCommand) - try expectRemoteResumeBootstrap(gonePTYRemoteCommand) + expectRemoteResumeBootstrap(gonePTYRemoteCommand) } @Test @@ -155,7 +155,7 @@ struct RemoteResumeBindingTests { restoredWorkspace.terminalPanel(for: restoredSurfaceID)?.surface.debugInitialCommand() ) let remoteCommand = try decodedRemoteCommand(from: startupCommand) - try expectRemoteResumeBootstrap(remoteCommand) + expectRemoteResumeBootstrap(remoteCommand) let roundTripBinding = try #require( restoredWorkspace.sessionSnapshot(includeScrollback: false) @@ -376,7 +376,7 @@ struct RemoteResumeBindingTests { return try JSONDecoder().decode(SessionWorkspaceSnapshot.self, from: legacyData) } - private func expectRemoteResumeBootstrap(_ command: String) throws { + private func expectRemoteResumeBootstrap(_ command: String) { #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)") From 5af83f7bf33fd78c907130a9581fa8f4f5e4311a Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Mon, 20 Jul 2026 15:26:46 -0700 Subject: [PATCH 20/25] fix: integrate remote resume bootstrap API --- Sources/SSHPTYAttachStartupCommandBuilder.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/SSHPTYAttachStartupCommandBuilder.swift b/Sources/SSHPTYAttachStartupCommandBuilder.swift index afaa31194a5b..753998d2766d 100644 --- a/Sources/SSHPTYAttachStartupCommandBuilder.swift +++ b/Sources/SSHPTYAttachStartupCommandBuilder.swift @@ -60,10 +60,10 @@ enum SSHPTYAttachStartupCommandBuilder { 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"), - initialCommand: initialCommand + bundledFishIntegration: RemoteInteractiveShellBootstrapBuilder.bundledShellIntegrationScript(named: "fish/config.fish") ) } From 1b9603c9fd048c4ffb70e392014b114c69bdbfbc Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Mon, 20 Jul 2026 15:36:44 -0700 Subject: [PATCH 21/25] test: fix merged remote transport coverage --- ...ssionRemoteWorkspaceMoshRestoreTests.swift | 29 ++++++++----------- .../ShellIntegrationSendTransportTests.swift | 18 ++++++------ cmuxTests/ShellStartupMatrixTests.swift | 4 +-- 3 files changed, 23 insertions(+), 28 deletions(-) diff --git a/cmuxTests/SessionRemoteWorkspaceMoshRestoreTests.swift b/cmuxTests/SessionRemoteWorkspaceMoshRestoreTests.swift index 1124e30c2add..9903a217fe01 100644 --- a/cmuxTests/SessionRemoteWorkspaceMoshRestoreTests.swift +++ b/cmuxTests/SessionRemoteWorkspaceMoshRestoreTests.swift @@ -1,4 +1,5 @@ import CmuxCore +import CmuxFoundation import Foundation import Testing @@ -38,24 +39,18 @@ struct SessionRemoteWorkspaceMoshRestoreTests { let readyURL = directory.appendingPathComponent("management.ready") let argumentsURL = directory.appendingPathComponent("mosh.args") - let options = CMUXCLI.SSHCommandOptions( + let command = MoshTerminalCommandBuilder( + capabilityProbeSSHArguments: [sshURL.path], + sessionSSHArguments: [sshURL.path], destination: "user@example.com", - port: nil, - identityFile: nil, - workspaceName: nil, - noFocus: true, - sshOptions: [], - extraArguments: ["printf", "remote command"], - terminalTransport: .mosh, - localSocketPath: "/tmp/cmux.sock", - remoteRelayPort: 52_001 - ) - let command = CMUXCLI(args: []).buildMoshTerminalStartupCommand( - options: options, - remoteBootstrapScript: nil, - localCommandScript: "printf ready > \"$READY_FILE\"", - sshFallbackCommand: "exit 90" - ) + 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] diff --git a/cmuxTests/ShellIntegrationSendTransportTests.swift b/cmuxTests/ShellIntegrationSendTransportTests.swift index 8d7fc2c1a600..6d06004e7a7a 100644 --- a/cmuxTests/ShellIntegrationSendTransportTests.swift +++ b/cmuxTests/ShellIntegrationSendTransportTests.swift @@ -106,10 +106,10 @@ struct ShellIntegrationSendTransportTests { let error = String(decoding: standardError.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) #expect(process.terminationStatus == 0, "\(error)\n\(output)") - #expect(output.contains("set-environment -g CMUX_SOCKET_PATH 127.0.0.1:64011"), output) - #expect(output.contains("set-environment -g CMUX_WORKSPACE_ID 11111111-1111-1111-1111-111111111111"), output) - #expect(output.contains("set-environment -gu CMUX_SURFACE_ID"), output) - #expect(output.contains("set-environment -gu CMUX_PANEL_ID"), output) + #expect(output.contains("set-environment -g CMUX_SOCKET_PATH 127.0.0.1:64011"), Comment(rawValue: output)) + #expect(output.contains("set-environment -g CMUX_WORKSPACE_ID 11111111-1111-1111-1111-111111111111"), Comment(rawValue: output)) + #expect(output.contains("set-environment -gu CMUX_SURFACE_ID"), Comment(rawValue: output)) + #expect(output.contains("set-environment -gu CMUX_PANEL_ID"), Comment(rawValue: output)) } @Test("reattached tmux zsh adopts the named session workspace binding") @@ -169,10 +169,10 @@ struct ShellIntegrationSendTransportTests { let error = String(decoding: standardError.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) #expect(process.terminationStatus == 0, "\(error)\n\(output)") - #expect(output.contains("workspace=current-workspace"), output) - #expect(output.contains("socket=127.0.0.1:55272"), output) - #expect(output.contains("surface="), output) - #expect(output.contains("panel="), output) + #expect(output.contains("workspace=current-workspace"), Comment(rawValue: output)) + #expect(output.contains("socket=127.0.0.1:55272"), Comment(rawValue: output)) + #expect(output.contains("surface="), Comment(rawValue: output)) + #expect(output.contains("panel="), Comment(rawValue: output)) } private func assertRemoteShellReportsGitMetadataThroughRelay( @@ -242,7 +242,7 @@ struct ShellIntegrationSendTransportTests { let surfaceField = surfaceID.map { ",\"surface_id\":\"\($0)\"" } ?? "" #expect(output.contains( #"rpc surface.report_git_branch {"workspace_id":"11111111-1111-1111-1111-111111111111","branch":"feature/mosh-parity"\#(surfaceField)}"# - ), output) + ), Comment(rawValue: output)) } /// End-to-end contract for `_cmux_send`: sourcing the bundled integration diff --git a/cmuxTests/ShellStartupMatrixTests.swift b/cmuxTests/ShellStartupMatrixTests.swift index de0792b341c6..882fe607e989 100644 --- a/cmuxTests/ShellStartupMatrixTests.swift +++ b/cmuxTests/ShellStartupMatrixTests.swift @@ -333,10 +333,10 @@ 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", - initialCommand: initialCommand + bundledFishIntegration: "set -gx CMUX_FISH_MARKER 1" ) if let workspaceID { script = script.replacingOccurrences(of: "__CMUX_WORKSPACE_ID__", with: workspaceID) From 4c6f88c8ba53e3dea5ba9b3a462dd415c0b20367 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Mon, 20 Jul 2026 15:39:02 -0700 Subject: [PATCH 22/25] test: fix remote prompt diagnostics --- cmuxTests/RemoteShellPromptRelayTests.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cmuxTests/RemoteShellPromptRelayTests.swift b/cmuxTests/RemoteShellPromptRelayTests.swift index 074129b787da..0c5e950c6ada 100644 --- a/cmuxTests/RemoteShellPromptRelayTests.swift +++ b/cmuxTests/RemoteShellPromptRelayTests.swift @@ -22,7 +22,7 @@ struct RemoteShellPromptRelayTests { #expect(output.contains( #"rpc surface.report_git_branch {"workspace_id":"11111111-1111-1111-1111-111111111111","branch":"feature/mosh-prompt","surface_id":"22222222-2222-2222-2222-222222222222"}"# - ), output) + ), Comment(rawValue: output)) } @Test("remote bash prompt reports Git metadata through the relay") @@ -38,7 +38,7 @@ struct RemoteShellPromptRelayTests { #expect(output.contains( #"rpc surface.report_git_branch {"workspace_id":"11111111-1111-1111-1111-111111111111","branch":"feature/mosh-prompt","surface_id":"22222222-2222-2222-2222-222222222222"}"# - ), output) + ), Comment(rawValue: output)) } @Test("remote tmux zsh prompt reports shell state through the workspace relay") @@ -54,7 +54,7 @@ struct RemoteShellPromptRelayTests { #expect(output.contains( #"rpc surface.report_shell_state {"workspace_id":"11111111-1111-1111-1111-111111111111","state":"prompt"}"# - ), output) + ), Comment(rawValue: output)) } @Test("remote tmux bash prompt reports shell state through the workspace relay") @@ -70,7 +70,7 @@ struct RemoteShellPromptRelayTests { #expect(output.contains( #"rpc surface.report_shell_state {"workspace_id":"11111111-1111-1111-1111-111111111111","state":"prompt"}"# - ), output) + ), Comment(rawValue: output)) } private func runPrompt( From 3888079052718fcb9ce4d0636cde914b1baa7779 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Mon, 20 Jul 2026 16:01:31 -0700 Subject: [PATCH 23/25] fix: run resume before unsupported remote shells --- Sources/RemoteInitialCommandBootstrap.swift | 58 +++++++------------ ...eInitialCommandBootstrapFailureTests.swift | 15 ++--- cmuxTests/RemoteResumeBindingTests.swift | 29 +++++++--- cmuxTests/ShellStartupMatrixTests.swift | 2 +- 4 files changed, 49 insertions(+), 55 deletions(-) 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/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 index 44487e7f5d98..e79766df50f0 100644 --- a/cmuxTests/RemoteResumeBindingTests.swift +++ b/cmuxTests/RemoteResumeBindingTests.swift @@ -98,7 +98,7 @@ struct RemoteResumeBindingTests { #expect(liveFirstCommand.contains("ssh-pty-attach"), "\(liveFirstCommand)") #expect(liveFirstCommand.contains("--require-existing"), "\(liveFirstCommand)") let liveFirstRemoteCommand = try decodedRemoteCommand(from: liveFirstCommand) - expectRemoteResumeBootstrap(liveFirstRemoteCommand) + try expectRemoteResumeBootstrap(liveFirstRemoteCommand) #expect(restoredPanel.surface.debugInitialInputForTesting() == nil) let roundTrip = restoredWorkspace.sessionSnapshot(includeScrollback: false) @@ -133,7 +133,7 @@ struct RemoteResumeBindingTests { ) #expect(!gonePTYCommand.contains("--require-existing"), "\(gonePTYCommand)") let gonePTYRemoteCommand = try decodedRemoteCommand(from: gonePTYCommand) - expectRemoteResumeBootstrap(gonePTYRemoteCommand) + try expectRemoteResumeBootstrap(gonePTYRemoteCommand) } @Test @@ -155,7 +155,7 @@ struct RemoteResumeBindingTests { restoredWorkspace.terminalPanel(for: restoredSurfaceID)?.surface.debugInitialCommand() ) let remoteCommand = try decodedRemoteCommand(from: startupCommand) - expectRemoteResumeBootstrap(remoteCommand) + try expectRemoteResumeBootstrap(remoteCommand) let roundTripBinding = try #require( restoredWorkspace.sessionSnapshot(includeScrollback: false) @@ -376,14 +376,27 @@ struct RemoteResumeBindingTests { return try JSONDecoder().decode(SessionWorkspaceSnapshot.self, from: legacyData) } - private func expectRemoteResumeBootstrap(_ command: String) { + 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)") - #expect(command.contains("/srv/remote project"), "\(command)") - #expect(command.contains("REMOTE_FLAG=value with spaces"), "\(command)") - #expect(command.contains("session-remote-7989"), "\(command)") - #expect(!command.contains("ANTHROPIC_API_KEY"), "\(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[.. String { diff --git a/cmuxTests/ShellStartupMatrixTests.swift b/cmuxTests/ShellStartupMatrixTests.swift index 882fe607e989..34e02f20acab 100644 --- a/cmuxTests/ShellStartupMatrixTests.swift +++ b/cmuxTests/ShellStartupMatrixTests.swift @@ -179,7 +179,7 @@ struct ShellStartupMatrixTests { @Test func generatedSshBootstrapRunsResumeBeforeUnsupportedInteractiveShell() throws { let result = try runGeneratedBootstrap( - shellName: "nu", + shellName: "xonsh", initialCommand: #"printf 'resumed\n' > "$HOME/.cmux-resume-marker""# ) From 6bd4b326b2d8547384c2c862e1eeeb6fd21eaf24 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Mon, 20 Jul 2026 17:44:44 -0700 Subject: [PATCH 24/25] Expand remote resume verification coverage --- cmuxTests/RemoteResumeBindingTests.swift | 770 ++++++++++++++++++++++- cmuxTests/ShellStartupMatrixTests.swift | 72 +++ 2 files changed, 829 insertions(+), 13 deletions(-) diff --git a/cmuxTests/RemoteResumeBindingTests.swift b/cmuxTests/RemoteResumeBindingTests.swift index e79766df50f0..1eb69efb79f7 100644 --- a/cmuxTests/RemoteResumeBindingTests.swift +++ b/cmuxTests/RemoteResumeBindingTests.swift @@ -1,5 +1,6 @@ import AppKit import CmuxCore +import Darwin import Foundation import Testing @@ -9,11 +10,135 @@ import Testing @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() @@ -59,6 +184,309 @@ struct RemoteResumeBindingTests { )) } + @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 = try hook.commands.compactMap { line -> [String: Any]? in + let request = try jsonRequest(Data(line.utf8)) + 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() @@ -136,6 +564,35 @@ struct RemoteResumeBindingTests { 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) + let remoteCommand = try decodedRemoteCommand(from: startupCommand) + #expect(!remoteCommand.contains("session-remote-7989"), "\(remoteCommand)") + #expect(!remoteCommand.contains("REMOTE_FLAG"), "\(remoteCommand)") + } + @Test func legacyRemoteSnapshotWithoutWorkspaceIDMigratesBindingIntoPersistentSSHContext() throws { let fixture = try makeRelayedFixture() @@ -170,6 +627,70 @@ struct RemoteResumeBindingTests { #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, @@ -280,8 +801,16 @@ struct RemoteResumeBindingTests { ) } - private func remoteConfiguration() -> WorkspaceRemoteConfiguration { + 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, @@ -292,8 +821,9 @@ struct RemoteResumeBindingTests { relayToken: String(repeating: "a", count: 64), localSocketPath: "/tmp/cmux-issue-7989.sock", terminalStartupCommand: SSHPTYAttachStartupCommandBuilder.command(requireExisting: false), - preserveAfterTerminalExit: true, - persistentDaemonSlot: "ssh-issue-7989" + preserveAfterTerminalExit: preserveAfterTerminalExit, + persistentDaemonSlot: persistentDaemonSlot, + skipDaemonBootstrap: skipDaemonBootstrap ) } @@ -319,6 +849,16 @@ struct RemoteResumeBindingTests { ] } + 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)") @@ -326,22 +866,19 @@ struct RemoteResumeBindingTests { } private func v2Envelope(request: [String: Any]) throws -> [String: Any] { - var data = try JSONSerialization.data(withJSONObject: request) - data.append(0x0A) - let requestLine = try #require(String(data: data, encoding: .utf8)) + 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 requestLine = try #require(String(data: requestData, encoding: .utf8)) - let response = TerminalController.shared.handleSocketLine(requestLine) - let responseData = try #require(response.data(using: .utf8)) - let envelope = try #require( - JSONSerialization.jsonObject(with: responseData) as? [String: Any] - ) - #expect(envelope["ok"] as? Bool == true, "\(response)") + let envelope = try v2Envelope(requestData: requestData) + #expect(envelope["ok"] as? Bool == true, "\(envelope)") return try #require(envelope["result"] as? [String: Any]) } @@ -376,6 +913,49 @@ struct RemoteResumeBindingTests { 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)") @@ -399,6 +979,170 @@ struct RemoteResumeBindingTests { return try #require(String(data: data, encoding: .utf8)) } + private func runBundledKiroSessionStart( + workspaceID: UUID, + surfaceID: UUID + ) throws -> 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" diff --git a/cmuxTests/ShellStartupMatrixTests.swift b/cmuxTests/ShellStartupMatrixTests.swift index 34e02f20acab..3674aeb33661 100644 --- a/cmuxTests/ShellStartupMatrixTests.swift +++ b/cmuxTests/ShellStartupMatrixTests.swift @@ -189,6 +189,62 @@ struct ShellStartupMatrixTests { 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) @@ -445,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], @@ -454,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 From fefcb08f8d5d28baac4826a5495d28c6d00dd358 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Mon, 20 Jul 2026 17:49:21 -0700 Subject: [PATCH 25/25] Fix remote resume verifier assertions --- cmuxTests/RemoteResumeBindingTests.swift | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/cmuxTests/RemoteResumeBindingTests.swift b/cmuxTests/RemoteResumeBindingTests.swift index 1eb69efb79f7..dc2c54fe1179 100644 --- a/cmuxTests/RemoteResumeBindingTests.swift +++ b/cmuxTests/RemoteResumeBindingTests.swift @@ -351,8 +351,12 @@ struct RemoteResumeBindingTests { ) #expect(!hook.timedOut, Comment(rawValue: hook.stderr)) #expect(hook.status == 0, Comment(rawValue: hook.stderr)) - let resumeRequests = try hook.commands.compactMap { line -> [String: Any]? in - let request = try jsonRequest(Data(line.utf8)) + 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)") @@ -588,9 +592,9 @@ struct RemoteResumeBindingTests { #expect(startupCommand.contains("ssh-pty-attach"), "\(startupCommand)") #expect(startupCommand.contains("--require-existing"), "\(startupCommand)") #expect(restoredPanel.surface.debugInitialInputForTesting() == nil) - let remoteCommand = try decodedRemoteCommand(from: startupCommand) - #expect(!remoteCommand.contains("session-remote-7989"), "\(remoteCommand)") - #expect(!remoteCommand.contains("REMOTE_FLAG"), "\(remoteCommand)") + #expect(!startupCommand.contains("--command-b64"), "\(startupCommand)") + #expect(!startupCommand.contains("session-remote-7989"), "\(startupCommand)") + #expect(!startupCommand.contains("REMOTE_FLAG"), "\(startupCommand)") } @Test