diff --git a/CLI/CMUXCLI+ClaudeHookWorkspaceRouting.swift b/CLI/CMUXCLI+ClaudeHookWorkspaceRouting.swift index fd6358dc9733..d134b135c6da 100644 --- a/CLI/CMUXCLI+ClaudeHookWorkspaceRouting.swift +++ b/CLI/CMUXCLI+ClaudeHookWorkspaceRouting.swift @@ -76,15 +76,25 @@ extension CMUXCLI { client: SocketClient, includeAmbientTTY: Bool = true ) -> CallerTerminalBinding? { - guard let ttyName = resolveCallerTTYName(includeAmbientTTY: includeAmbientTTY), - let payload = try? client.sendV2(method: "debug.terminals") else { + guard let ttyName = resolveCallerTTYName(includeAmbientTTY: includeAmbientTTY) else { return nil } + return uniqueCallerTerminalBindingByTTY(ttyName: ttyName, client: client) + } + + func uniqueCallerTerminalBindingByTTY( + ttyName: String, + client: SocketClient, + workspaceId: String? = nil + ) -> CallerTerminalBinding? { + guard let payload = try? client.sendV2(method: "debug.terminals") else { return nil } let terminals = payload["terminals"] as? [[String: Any]] ?? [] + let scopedWorkspaceId = normalizedHandleValue(workspaceId) var matched: [CallerTerminalBinding] = [] for terminal in terminals { guard normalizedTTYName(terminal["tty"] as? String) == ttyName, let workspaceId = normalizedHandleValue(terminal["workspace_id"] as? String), + scopedWorkspaceId == nil || workspaceId == scopedWorkspaceId, let surfaceId = normalizedHandleValue(terminal["surface_id"] as? String) else { continue } diff --git a/CLI/CMUXCLI+Restore.swift b/CLI/CMUXCLI+Restore.swift index affe89e57e37..d06160baca19 100644 --- a/CLI/CMUXCLI+Restore.swift +++ b/CLI/CMUXCLI+Restore.swift @@ -1,4 +1,5 @@ import CMUXAgentLaunch +import Darwin import Foundation extension CMUXCLI { @@ -53,23 +54,13 @@ extension CMUXCLI { } params["surface_id"] = surfaceID } else if selector.usesCurrentSurface, - let surfaceID = processEnvironment["CMUX_SURFACE_ID"], - !surfaceID.isEmpty { - params["surface_id"] = surfaceID - } else if selector.usesCurrentSurface, - let ttyName = resolveCallerTTYName(), - let caller = resolveTerminalBinding( - ttyName: ttyName, - client: client + let surfaceID = try currentRestoreSurfaceID( + client: client, + processEnvironment: processEnvironment ) { - params["surface_id"] = caller.surfaceId + params["surface_id"] = surfaceID } else { - throw CLIError( - message: String( - localized: "cli.restore.error.currentSurfaceUnknown", - defaultValue: "restore: the current cmux surface could not be identified. Retry from this terminal or pass --surface ." - ) - ) + throw currentRestoreSurfaceUnknownError() } let payload = try client.sendV2(method: "surface.resume.get", params: params) @@ -190,6 +181,155 @@ extension CMUXCLI { ) } + private func currentRestoreSurfaceID( + client: SocketClient, + processEnvironment: [String: String] + ) throws -> String? { + // The remote relay and the local CLI do not share a PID namespace. + if client.isRelayBacked { + return try relayRestoreSurfaceID( + client: client, + processEnvironment: processEnvironment + ) + } + + let resolution = AgentProcessBindingResolution.controllingTTY.rawValue + do { + let payload = try client.sendV2( + method: "agent.resolve_delivery_target", + params: [ + "pid": Int(ProcessInfo.processInfo.processIdentifier), + "pid_resolution": resolution, + ] + ) + guard payload["source"] as? String == "pid", + payload["pid_resolution"] as? String == resolution, + let workspaceID = normalizedHandleValue(payload["workspace_id"] as? String), + isUUID(workspaceID), + let surfaceID = normalizedHandleValue(payload["surface_id"] as? String), + isUUID(surfaceID) else { + throw currentRestoreSurfaceUnknownError() + } + return surfaceID + } catch let error as CLIError { + switch error.v2Code { + case "not_found": + client.close() + throw currentRestoreSurfaceUnknownError() + case "method_not_found", "unrecognized_method": + // These protocol replies were consumed in full, so the socket + // remains synchronized for the legacy discovery request. + return legacyRestoreSurfaceID( + client: client, + workspaceID: nil + ) + default: + client.close() + throw error + } + } catch { + client.close() + throw error + } + } + + private func relayRestoreSurfaceID( + client: SocketClient, + processEnvironment: [String: String] + ) throws -> String? { + let ttyName = resolveCallerDescriptorTTYName() + ?? resolveCallerTTYName(includeAmbientTTY: false) + guard let ttyName else { return nil } + + let resolution = AgentTTYBindingResolution.reportedTTY.rawValue + let workspaceID = normalizedHandleValue(processEnvironment["CMUX_WORKSPACE_ID"]) + var params: [String: Any] = [ + "tty_name": ttyName, + "tty_resolution": resolution, + ] + if let workspaceID { + // Lets an older app identify this probe as an unsupported + // workspace-only resolution. The authenticated relay rewrites + // aliases and separately stamps its authoritative owner id. + params["workspace_id"] = workspaceID + } + + do { + let payload = try client.sendV2( + method: "agent.resolve_delivery_target", + params: params + ) + if payload["source"] as? String == "workspace", + payload["surface_id"] == nil || payload["surface_id"] is NSNull, + let resolvedWorkspaceID = normalizedHandleValue(payload["workspace_id"] as? String), + isUUID(resolvedWorkspaceID) { + // Previous app versions ignore the TTY probe and resolve + // only workspace_id. Use their alias-rewritten result to + // scope the legacy terminal list, not the stale remote + // shell environment value that produced the request. + return legacyRestoreSurfaceID( + client: client, + workspaceID: resolvedWorkspaceID + ) + } + guard payload["source"] as? String == "tty", + payload["tty_resolution"] as? String == resolution, + let resolvedWorkspaceID = normalizedHandleValue(payload["workspace_id"] as? String), + isUUID(resolvedWorkspaceID), + let surfaceID = normalizedHandleValue(payload["surface_id"] as? String), + isUUID(surfaceID) else { + throw currentRestoreSurfaceUnknownError() + } + return surfaceID + } catch let error as CLIError { + switch error.v2Code { + case "not_found": + client.close() + throw currentRestoreSurfaceUnknownError() + case "method_not_found", "unrecognized_method": + guard let workspaceID, isUUID(workspaceID) else { return nil } + return legacyRestoreSurfaceID( + client: client, + workspaceID: workspaceID + ) + default: + client.close() + throw error + } + } catch { + client.close() + throw error + } + } + + private func legacyRestoreSurfaceID( + client: SocketClient, + workspaceID: String? + ) -> String? { + // Prefer the live descriptors. Generic TTY variables can be inherited + // across nested shells, so only dedicated cmux hints are a fallback. + let ttyName = resolveCallerDescriptorTTYName() + ?? resolveCallerTTYName(includeAmbientTTY: false) + guard let ttyName, + let binding = uniqueCallerTerminalBindingByTTY( + ttyName: ttyName, + client: client, + workspaceId: workspaceID + ) else { + return nil + } + return binding.surfaceId + } + + private func currentRestoreSurfaceUnknownError() -> CLIError { + CLIError( + message: String( + localized: "cli.restore.error.currentSurfaceUnknown", + defaultValue: "restore: the current cmux surface could not be identified. Retry from this terminal or pass --surface ." + ) + ) + } + private func restoreSelector(_ arguments: [String]) throws -> RestoreSelector { if arguments.first == "--surface" { if arguments.count == 1 { diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 329a9404f802..70eb8906cf11 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -10234,10 +10234,10 @@ struct CMUXCLI { " cmux_relay_cli=\"$HOME/.cmux/bin/cmux\"", " if [ ! -x \"$cmux_relay_cli\" ]; then cmux_relay_cli=\"$(command -v cmux 2>/dev/null || true)\"; fi", " if [ -n \"$cmux_relay_cli\" ]; then", - " ( cmux_relay_report_tty='{\"workspace_id\":\"__CMUX_WORKSPACE_ID__\",\"tty_name\":\"'$cmux_bootstrap_tty'\"}'", + " ( cmux_relay_report_tty='{\"workspace_id\":\"__CMUX_WORKSPACE_ID__\",\"tty_name\":\"'$cmux_bootstrap_tty'\",\"terminal_lifecycle_id\":\"__CMUX_TERMINAL_LIFECYCLE_ID__\",\"attempt_id\":\"__CMUX_SSH_ATTEMPT_ID__\"}'", " cmux_relay_ports_kick='{\"workspace_id\":\"__CMUX_WORKSPACE_ID__\",\"reason\":\"command\"}'", " if [ -n \"__CMUX_SURFACE_ID__\" ]; then", - " cmux_relay_report_tty='{\"workspace_id\":\"__CMUX_WORKSPACE_ID__\",\"surface_id\":\"__CMUX_SURFACE_ID__\",\"tty_name\":\"'$cmux_bootstrap_tty'\"}'", + " cmux_relay_report_tty='{\"workspace_id\":\"__CMUX_WORKSPACE_ID__\",\"surface_id\":\"__CMUX_SURFACE_ID__\",\"tty_name\":\"'$cmux_bootstrap_tty'\",\"terminal_lifecycle_id\":\"__CMUX_TERMINAL_LIFECYCLE_ID__\",\"attempt_id\":\"__CMUX_SSH_ATTEMPT_ID__\"}'", " cmux_relay_ports_kick='{\"workspace_id\":\"__CMUX_WORKSPACE_ID__\",\"surface_id\":\"__CMUX_SURFACE_ID__\",\"reason\":\"command\"}'", " fi", " env -u CMUX_SOCKET CMUX_SOCKET_PATH=\"127.0.0.1:\(remoteRelayPort)\" \"$cmux_relay_cli\" rpc surface.report_tty \"$cmux_relay_report_tty\" >/dev/null 2>&1 || true", 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 6beda80c9574..3db9a1190799 100644 --- a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+Surface3.swift +++ b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+Surface3.swift @@ -325,52 +325,6 @@ extension ControlCommandCoordinator { } } - // MARK: - report_tty - - /// `surface.report_tty` — record a reported TTY name. - func surfaceReportTTY(_ params: [String: JSONValue]) -> ControlCallResult { - guard let workspaceID = uuid(params, "workspace_id") else { - return .err(code: "invalid_params", message: "Missing or invalid workspace_id", data: nil) - } - let requestedSurfaceID = uuid(params, "surface_id") - if hasNonNull(params, "surface_id"), requestedSurfaceID == nil { - return .err(code: "invalid_params", message: "Missing or invalid surface_id", data: nil) - } - guard let ttyName = rawString(params, "tty_name")? - .trimmingCharacters(in: .whitespacesAndNewlines), !ttyName.isEmpty else { - return .err(code: "invalid_params", message: "Missing tty_name", data: nil) - } - - let resolution = context?.controlSurfaceReportTTY( - workspaceID: workspaceID, - requestedSurfaceID: requestedSurfaceID, - ttyName: ttyName - ) ?? .workspaceNotFound - let requestedSurfaceData = surfaceReportSurfaceFields( - workspaceID: workspaceID, - requestedSurfaceID: requestedSurfaceID - ) - switch resolution { - case .workspaceNotFound: - return .err(code: "not_found", message: "Workspace not found", data: .object(requestedSurfaceData)) - case .surfaceNotFound: - return .err(code: "not_found", message: "Surface not found", data: .object(requestedSurfaceData)) - case .pending: - var payload = requestedSurfaceData - payload["tty_name"] = .string(ttyName) - payload["pending"] = .bool(true) - return .ok(.object(payload)) - case .recorded(let surfaceID): - return .ok(.object([ - "workspace_id": .string(workspaceID.uuidString), - "workspace_ref": ref(.workspace, workspaceID), - "surface_id": .string(surfaceID.uuidString), - "surface_ref": ref(.surface, surfaceID), - "tty_name": .string(ttyName), - ])) - } - } - // MARK: - report_pwd /// `surface.report_pwd` — record a surface's current working directory. diff --git a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+SurfaceReportTTY.swift b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+SurfaceReportTTY.swift new file mode 100644 index 000000000000..ce8c20c58b77 --- /dev/null +++ b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+SurfaceReportTTY.swift @@ -0,0 +1,70 @@ +internal import Foundation + +/// The authenticated `surface.report_tty` write path. Kept separate because +/// remote reports carry terminal-runtime identity in addition to surface scope. +extension ControlCommandCoordinator { + func surfaceReportTTY(_ params: [String: JSONValue]) -> ControlCallResult { + guard let workspaceID = uuid(params, "workspace_id") else { + return .err(code: "invalid_params", message: "Missing or invalid workspace_id", data: nil) + } + let requestedSurfaceID = uuid(params, "surface_id") + if hasNonNull(params, "surface_id"), requestedSurfaceID == nil { + return .err(code: "invalid_params", message: "Missing or invalid surface_id", data: nil) + } + guard let ttyName = rawString(params, "tty_name")? + .trimmingCharacters(in: .whitespacesAndNewlines), !ttyName.isEmpty else { + return .err(code: "invalid_params", message: "Missing tty_name", data: nil) + } + + let authenticatedRemoteWorkspaceID = string( + params, + "_cmux_remote_workspace_id" + ).flatMap(UUID.init(uuidString:)) + let terminalLifecycleID = string(params, "terminal_lifecycle_id") + .flatMap(UUID.init(uuidString:)) + let attemptID = string(params, "attempt_id").flatMap(UUID.init(uuidString:)) + for (key, value) in [ + ("_cmux_remote_workspace_id", authenticatedRemoteWorkspaceID), + ("terminal_lifecycle_id", terminalLifecycleID), + ("attempt_id", attemptID), + ] where hasNonNull(params, key) && value == nil { + return .err( + code: "invalid_params", + message: "Missing or invalid \(key)", + data: nil + ) + } + + let resolution = context?.controlSurfaceReportTTY( + workspaceID: workspaceID, + requestedSurfaceID: requestedSurfaceID, + ttyName: ttyName, + authenticatedRemoteWorkspaceID: authenticatedRemoteWorkspaceID, + terminalLifecycleID: terminalLifecycleID, + attemptID: attemptID + ) ?? .workspaceNotFound + let requestedSurfaceData = surfaceReportSurfaceFields( + workspaceID: workspaceID, + requestedSurfaceID: requestedSurfaceID + ) + switch resolution { + case .workspaceNotFound: + return .err(code: "not_found", message: "Workspace not found", data: .object(requestedSurfaceData)) + case .surfaceNotFound: + return .err(code: "not_found", message: "Surface not found", data: .object(requestedSurfaceData)) + case .pending: + var payload = requestedSurfaceData + payload["tty_name"] = .string(ttyName) + payload["pending"] = .bool(true) + return .ok(.object(payload)) + case .recorded(let surfaceID): + return .ok(.object([ + "workspace_id": .string(workspaceID.uuidString), + "workspace_ref": ref(.workspace, workspaceID), + "surface_id": .string(surfaceID.uuidString), + "surface_ref": ref(.surface, surfaceID), + "tty_name": .string(ttyName), + ])) + } + } +} diff --git a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceContext.swift b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceContext.swift index 8f7938b57f10..810e7f1f98e0 100644 --- a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceContext.swift +++ b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceContext.swift @@ -287,11 +287,17 @@ public protocol ControlSurfaceContext: AnyObject { /// - workspaceID: The target workspace. /// - requestedSurfaceID: The explicit `surface_id`, or `nil` to resolve. /// - ttyName: The reported (trimmed, non-empty) TTY name. + /// - authenticatedRemoteWorkspaceID: Relay-authenticated origin, when remote. + /// - terminalLifecycleID: Runtime lifecycle carried by a remote report. + /// - attemptID: Attach attempt carried by a remote report. /// - Returns: The report resolution. func controlSurfaceReportTTY( workspaceID: UUID, requestedSurfaceID: UUID?, - ttyName: String + ttyName: String, + authenticatedRemoteWorkspaceID: UUID?, + terminalLifecycleID: UUID?, + attemptID: UUID? ) -> ControlSurfaceReportTTYResolution /// Records a reported current working directory for `surface.report_pwd`. diff --git a/Packages/macOS/CmuxControlSocket/Tests/CmuxControlSocketTests/ControlCommandContextTestStubs.swift b/Packages/macOS/CmuxControlSocket/Tests/CmuxControlSocketTests/ControlCommandContextTestStubs.swift index 3f2b980db477..c3302a8a9c7d 100644 --- a/Packages/macOS/CmuxControlSocket/Tests/CmuxControlSocketTests/ControlCommandContextTestStubs.swift +++ b/Packages/macOS/CmuxControlSocket/Tests/CmuxControlSocketTests/ControlCommandContextTestStubs.swift @@ -515,7 +515,14 @@ extension ControlSurfaceContext { nonisolated func controlSurfaceParseShellActivityState(_ rawState: String) -> String? { nil } nonisolated func controlSurfaceParsePortScanKickReason(_ rawReason: String) -> String? { nil } - func controlSurfaceReportTTY(workspaceID: UUID, requestedSurfaceID: UUID?, ttyName: String) + func controlSurfaceReportTTY( + workspaceID: UUID, + requestedSurfaceID: UUID?, + ttyName: String, + authenticatedRemoteWorkspaceID: UUID?, + terminalLifecycleID: UUID?, + attemptID: UUID? + ) -> ControlSurfaceReportTTYResolution { .workspaceNotFound } func controlSurfaceReportPWD(workspaceID: UUID, requestedSurfaceID: UUID?, path: String) -> ControlSurfaceReportPWDResolution { .workspaceNotFound } diff --git a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/MoshTerminalCommandBuilder.swift b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/MoshTerminalCommandBuilder.swift index 590c7d54b72e..6de38d3e3558 100644 --- a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/MoshTerminalCommandBuilder.swift +++ b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/MoshTerminalCommandBuilder.swift @@ -135,6 +135,10 @@ public struct MoshTerminalCommandBuilder: Sendable { "fi", "unset cmux_mosh_probe_status", ] + let reportsTerminalLifecycle = remoteRelayPort.map { (1...65_535).contains($0) } ?? false + if reportsTerminalLifecycle { + script += terminalLifecycleAttemptShellLines() + } if let preparationShellScript = preparationShellScript? .trimmingCharacters(in: .whitespacesAndNewlines), !preparationShellScript.isEmpty { @@ -153,9 +157,8 @@ public struct MoshTerminalCommandBuilder: Sendable { !managementReadyShellScript.isEmpty { script.append(managementReadyShellScript) } - if let remoteRelayPort, - (1...65_535).contains(remoteRelayPort) { - script += terminalLifecycleLaunchingShellLines() + if reportsTerminalLifecycle { + script += terminalLifecycleRegistrationShellLines() } // Mosh exposes no reliable post-UDP-handshake callback, so this // pre-exec launcher must not claim authoritative connected readiness. @@ -163,13 +166,18 @@ public struct MoshTerminalCommandBuilder: Sendable { return "/bin/sh -c \(script.joined(separator: "\n").remoteCommandShellQuoted)" } - private func terminalLifecycleLaunchingShellLines() -> [String] { + private func terminalLifecycleAttemptShellLines() -> [String] { + [ + "CMUX_SSH_ATTEMPT_ID=$(/usr/bin/uuidgen | /usr/bin/tr '[:upper:]' '[:lower:]') || cmux_mosh_fallback", + "export CMUX_SSH_ATTEMPT_ID", + ] + } + + private func terminalLifecycleRegistrationShellLines() -> [String] { [ "cmux_mosh_lifecycle_cli=\"${CMUX_BUNDLED_CLI_PATH:-}\"", "if [ -z \"$cmux_mosh_lifecycle_cli\" ] || [ ! -x \"$cmux_mosh_lifecycle_cli\" ]; then cmux_mosh_lifecycle_cli=\"$(command -v cmux 2>/dev/null || true)\"; fi", "if [ -z \"$cmux_mosh_lifecycle_cli\" ] || [ -z \"${CMUX_SOCKET_PATH:-}\" ] || [ -z \"${CMUX_WORKSPACE_ID:-}\" ] || [ -z \"${CMUX_SURFACE_ID:-}\" ] || [ -z \"${CMUX_TERMINAL_LIFECYCLE_ID:-}\" ]; then cmux_mosh_fallback; fi", - "CMUX_SSH_ATTEMPT_ID=$(/usr/bin/uuidgen | /usr/bin/tr '[:upper:]' '[:lower:]') || cmux_mosh_fallback", - "export CMUX_SSH_ATTEMPT_ID", "cmux_mosh_lifecycle_rpc() { cmux_mosh_lifecycle_method=\"$1\"; cmux_mosh_lifecycle_payload=\"$2\"; cmux_mosh_lifecycle_retry=0; while ! CMUXTERM_CLI_RESPONSE_TIMEOUT_SEC=2 \"$cmux_mosh_lifecycle_cli\" --socket \"$CMUX_SOCKET_PATH\" rpc \"$cmux_mosh_lifecycle_method\" \"$cmux_mosh_lifecycle_payload\" >/dev/null 2>&1; do cmux_mosh_lifecycle_retry=$((cmux_mosh_lifecycle_retry + 1)); if [ \"$cmux_mosh_lifecycle_retry\" -ge 4 ]; then return 1; fi; /bin/sleep 0.1; done; }", "cmux_mosh_launch_payload=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"surface_id\\\":\\\"$CMUX_SURFACE_ID\\\",\\\"terminal_lifecycle_id\\\":\\\"$CMUX_TERMINAL_LIFECYCLE_ID\\\",\\\"attempt_id\\\":\\\"$CMUX_SSH_ATTEMPT_ID\\\"}\"", "cmux_mosh_lifecycle_rpc workspace.remote.terminal_session_launching \"$cmux_mosh_launch_payload\" || cmux_mosh_fallback", diff --git a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/RemoteBootstrapStagingCommandBuilder.swift b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/RemoteBootstrapStagingCommandBuilder.swift index 5e48c707977f..34878d53530c 100644 --- a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/RemoteBootstrapStagingCommandBuilder.swift +++ b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/RemoteBootstrapStagingCommandBuilder.swift @@ -52,16 +52,18 @@ public struct RemoteBootstrapStagingCommandBuilder: Sendable { "cmux_workspace_id=\"${CMUX_WORKSPACE_ID:-}\"", "cmux_surface_id=\"${CMUX_SURFACE_ID:-}\"", "cmux_terminal_lifecycle_id=\"${CMUX_TERMINAL_LIFECYCLE_ID:-}\"", + "cmux_ssh_attempt_id=\"${CMUX_SSH_ATTEMPT_ID:-}\"", "cmux_remote_bootstrap_b64=\(encodedBootstrapScript.remoteCommandShellQuoted)", "cmux_remote_bootstrap=\"$(printf %s \"$cmux_remote_bootstrap_b64\" | base64 -d 2>/dev/null || printf %s \"$cmux_remote_bootstrap_b64\" | base64 -D 2>/dev/null)\"", "cmux_sed_escape() { printf '%s' \"$1\" | sed 's/[\\/&\\\\]/\\\\&/g'; }", "cmux_workspace_id_escaped=\"$(cmux_sed_escape \"$cmux_workspace_id\")\"", "cmux_surface_id_escaped=\"$(cmux_sed_escape \"$cmux_surface_id\")\"", "cmux_terminal_lifecycle_id_escaped=\"$(cmux_sed_escape \"$cmux_terminal_lifecycle_id\")\"", - "cmux_remote_bootstrap=\"$(printf '%s' \"$cmux_remote_bootstrap\" | sed \"s/__CMUX_WORKSPACE_ID__/$cmux_workspace_id_escaped/g; s/__CMUX_SURFACE_ID__/$cmux_surface_id_escaped/g; s/__CMUX_TERMINAL_LIFECYCLE_ID__/$cmux_terminal_lifecycle_id_escaped/g\")\"", + "cmux_ssh_attempt_id_escaped=\"$(cmux_sed_escape \"$cmux_ssh_attempt_id\")\"", + "cmux_remote_bootstrap=\"$(printf '%s' \"$cmux_remote_bootstrap\" | sed \"s/__CMUX_WORKSPACE_ID__/$cmux_workspace_id_escaped/g; s/__CMUX_SURFACE_ID__/$cmux_surface_id_escaped/g; s/__CMUX_TERMINAL_LIFECYCLE_ID__/$cmux_terminal_lifecycle_id_escaped/g; s/__CMUX_SSH_ATTEMPT_ID__/$cmux_ssh_attempt_id_escaped/g\")\"", "printf '%s' \"$cmux_remote_bootstrap\" | command \(sshPrefix) -T \(destination.remoteCommandShellQuoted) \(installCommand.remoteCommandShellQuoted)", "cmux_remote_install_status=$?", - "unset cmux_remote_bootstrap cmux_remote_bootstrap_b64 cmux_workspace_id cmux_surface_id cmux_terminal_lifecycle_id cmux_workspace_id_escaped cmux_surface_id_escaped cmux_terminal_lifecycle_id_escaped", + "unset cmux_remote_bootstrap cmux_remote_bootstrap_b64 cmux_workspace_id cmux_surface_id cmux_terminal_lifecycle_id cmux_ssh_attempt_id cmux_workspace_id_escaped cmux_surface_id_escaped cmux_terminal_lifecycle_id_escaped cmux_ssh_attempt_id_escaped", "(exit \"$cmux_remote_install_status\")", ].joined(separator: "\n") } diff --git a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/RemoteTmuxSessionCommandBuilder.swift b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/RemoteTmuxSessionCommandBuilder.swift index a934b9d5a6d5..c6a974c595ea 100644 --- a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/RemoteTmuxSessionCommandBuilder.swift +++ b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/RemoteTmuxSessionCommandBuilder.swift @@ -64,7 +64,9 @@ public struct RemoteTmuxSessionCommandBuilder: Sendable { "CMUX_SHELL_INTEGRATION", "CMUX_SHELL_INTEGRATION_DIR", "CMUX_SOCKET_PATH", + "CMUX_SSH_ATTEMPT_ID", "CMUX_TAB_ID", + "CMUX_TERMINAL_LIFECYCLE_ID", "CMUX_WORKSPACE_ID", ] diff --git a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/MoshTerminalCommandBuilderTests.swift b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/MoshTerminalCommandBuilderTests.swift index 1f0fbdb78a9b..6e6a2d502686 100644 --- a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/MoshTerminalCommandBuilderTests.swift +++ b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/MoshTerminalCommandBuilderTests.swift @@ -192,6 +192,30 @@ struct MoshTerminalCommandBuilderTests { } } + @Test("creates the attach attempt before staging the remote bootstrap") + func preparationSeesCurrentAttempt() throws { + try withFakeCommands(sshStatus: 0) { directory, environment in + let attemptFile = directory.appendingPathComponent("staged-attempt") + let result = try run( + builder( + preparationShellScript: + "printf '%s' \"$CMUX_SSH_ATTEMPT_ID\" > '\(attemptFile.path)'", + remoteRelayPort: 64_007 + ), + environment: environment + ) + let stagedAttempt = try String(contentsOf: attemptFile, encoding: .utf8) + let lifecycleCalls = try String( + contentsOf: directory.appendingPathComponent("cmux.args"), + encoding: .utf8 + ) + + #expect(result.status == 0) + #expect(UUID(uuidString: stagedAttempt) != nil) + #expect(lifecycleCalls.contains(#""attempt_id":"\#(stagedAttempt)""#)) + } + } + @Test("does not report connected before the Mosh transport establishes") func failedMoshDoesNotReportConnected() throws { try withFakeCommands(sshStatus: 0, moshStatus: 71) { directory, environment in diff --git a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteBootstrapStagingCommandBuilderTests.swift b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteBootstrapStagingCommandBuilderTests.swift index 4b9e20741dd0..e25e37857103 100644 --- a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteBootstrapStagingCommandBuilderTests.swift +++ b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteBootstrapStagingCommandBuilderTests.swift @@ -27,7 +27,7 @@ struct RemoteBootstrapStagingCommandBuilderTests { let padding = String(repeating: "# bootstrap padding 0123456789\n", count: 20_000) let bootstrap = """ - printf '%s\\n' 'workspace=__CMUX_WORKSPACE_ID__ surface=__CMUX_SURFACE_ID__ lifecycle=__CMUX_TERMINAL_LIFECYCLE_ID__' + printf '%s\\n' 'workspace=__CMUX_WORKSPACE_ID__ surface=__CMUX_SURFACE_ID__ lifecycle=__CMUX_TERMINAL_LIFECYCLE_ID__ attempt=__CMUX_SSH_ATTEMPT_ID__' \(padding) """ let builder = try #require(RemoteBootstrapStagingCommandBuilder( @@ -41,6 +41,7 @@ struct RemoteBootstrapStagingCommandBuilderTests { "CMUX_WORKSPACE_ID": "workspace-123", "CMUX_SURFACE_ID": "surface-456", "CMUX_TERMINAL_LIFECYCLE_ID": "lifecycle-789", + "CMUX_SSH_ATTEMPT_ID": "attempt-012", "CMUX_REMOTE_HOME": remoteHome.path, "CMUX_SSH_ARGUMENTS": directory.appendingPathComponent("ssh.args").path, ] @@ -56,11 +57,12 @@ struct RemoteBootstrapStagingCommandBuilderTests { let stagedURL = remoteHome.appendingPathComponent(".cmux/relay/52261.bootstrap.sh") let staged = String(decoding: try Data(contentsOf: stagedURL), as: UTF8.self) #expect(staged.contains( - "workspace=workspace-123 surface=surface-456 lifecycle=lifecycle-789" + "workspace=workspace-123 surface=surface-456 lifecycle=lifecycle-789 attempt=attempt-012" )) #expect(!staged.contains("__CMUX_WORKSPACE_ID__")) #expect(!staged.contains("__CMUX_SURFACE_ID__")) #expect(!staged.contains("__CMUX_TERMINAL_LIFECYCLE_ID__")) + #expect(!staged.contains("__CMUX_SSH_ATTEMPT_ID__")) #expect(staged.utf8.count > 500_000) let sshArguments = String( @@ -82,7 +84,7 @@ struct RemoteBootstrapStagingCommandBuilderTests { #expect(execution.status == 0) #expect( execution.stdout == - "workspace=workspace-123 surface=surface-456 lifecycle=lifecycle-789\n" + "workspace=workspace-123 surface=surface-456 lifecycle=lifecycle-789 attempt=attempt-012\n" ) #expect(execution.stderr.isEmpty) } diff --git a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteTmuxSessionCommandBuilderTests.swift b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteTmuxSessionCommandBuilderTests.swift index 3591cdf7cc44..01723cd96b95 100644 --- a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteTmuxSessionCommandBuilderTests.swift +++ b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteTmuxSessionCommandBuilderTests.swift @@ -25,7 +25,9 @@ struct RemoteTmuxSessionCommandBuilderTests { "-e", "CMUX_SHELL_INTEGRATION=", "-e", "CMUX_SHELL_INTEGRATION_DIR=", "-e", "CMUX_SOCKET_PATH=", + "-e", "CMUX_SSH_ATTEMPT_ID=", "-e", "CMUX_TAB_ID=", + "-e", "CMUX_TERMINAL_LIFECYCLE_ID=", "-e", "CMUX_WORKSPACE_ID=", "-e", "CMUX_INITIAL_COMMAND_FILE=", "-e", "CMUX_PANEL_ID=", @@ -37,7 +39,9 @@ struct RemoteTmuxSessionCommandBuilderTests { ["set-environment", "-t", "=agent main", "-u", "CMUX_SHELL_INTEGRATION"], ["set-environment", "-t", "=agent main", "-u", "CMUX_SHELL_INTEGRATION_DIR"], ["set-environment", "-t", "=agent main", "-u", "CMUX_SOCKET_PATH"], + ["set-environment", "-t", "=agent main", "-u", "CMUX_SSH_ATTEMPT_ID"], ["set-environment", "-t", "=agent main", "-u", "CMUX_TAB_ID"], + ["set-environment", "-t", "=agent main", "-u", "CMUX_TERMINAL_LIFECYCLE_ID"], ["set-environment", "-t", "=agent main", "-u", "CMUX_WORKSPACE_ID"], ["set-environment", "-t", "=agent main", "-u", "CMUX_INITIAL_COMMAND_FILE"], ["set-environment", "-t", "=agent main", "-u", "CMUX_PANEL_ID"], @@ -86,7 +90,9 @@ struct RemoteTmuxSessionCommandBuilderTests { "-e", "CMUX_SHELL_INTEGRATION=1", "-e", "CMUX_SHELL_INTEGRATION_DIR=/home/dev/.cmux/relay/55272.shell", "-e", "CMUX_SOCKET_PATH=\(currentSocket)", + "-e", "CMUX_SSH_ATTEMPT_ID=", "-e", "CMUX_TAB_ID=\(currentWorkspace)", + "-e", "CMUX_TERMINAL_LIFECYCLE_ID=", "-e", "CMUX_WORKSPACE_ID=\(currentWorkspace)", "-e", "CMUX_INITIAL_COMMAND_FILE=", "-e", "CMUX_PANEL_ID=", @@ -148,14 +154,18 @@ struct RemoteTmuxSessionCommandBuilderTests { ) let currentWorkspace = "11111111-1111-1111-1111-111111111111" let currentSocket = "127.0.0.1:55272" + let currentLifecycle = "33333333-3333-3333-3333-333333333333" + let currentAttempt = "44444444-4444-4444-4444-444444444444" let result = try run(builder.remoteShellCommand, environment: environment.merging([ "CMUX_BUNDLED_CLI_PATH": "/home/dev/.cmux/bin/cmux", "CMUX_PERSISTENT_PTY_EXEC_HELPER": "/home/dev/.cmux/bin/cmux", "CMUX_PANEL_ID": "22222222-2222-2222-2222-222222222222", "CMUX_SHELL_INTEGRATION_DIR": "/home/dev/.cmux/relay/55272.shell", "CMUX_SOCKET_PATH": currentSocket, + "CMUX_SSH_ATTEMPT_ID": currentAttempt, "CMUX_SURFACE_ID": "22222222-2222-2222-2222-222222222222", "CMUX_TAB_ID": currentWorkspace, + "CMUX_TERMINAL_LIFECYCLE_ID": currentLifecycle, "CMUX_WORKSPACE_ID": currentWorkspace, ]) { _, current in current }) @@ -168,7 +178,9 @@ struct RemoteTmuxSessionCommandBuilderTests { ["set-environment", "-t", "=existing", "CMUX_PERSISTENT_PTY_EXEC_HELPER", "/home/dev/.cmux/bin/cmux"], ["set-environment", "-t", "=existing", "CMUX_SHELL_INTEGRATION_DIR", "/home/dev/.cmux/relay/55272.shell"], ["set-environment", "-t", "=existing", "CMUX_SOCKET_PATH", currentSocket], + ["set-environment", "-t", "=existing", "CMUX_SSH_ATTEMPT_ID", currentAttempt], ["set-environment", "-t", "=existing", "CMUX_TAB_ID", currentWorkspace], + ["set-environment", "-t", "=existing", "CMUX_TERMINAL_LIFECYCLE_ID", currentLifecycle], ["set-environment", "-t", "=existing", "CMUX_WORKSPACE_ID", currentWorkspace], ["set-environment", "-t", "=existing", "-u", "CMUX_PANEL_ID"], ["set-environment", "-t", "=existing", "-u", "CMUX_SURFACE_ID"], diff --git a/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+Debug.swift b/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+Debug.swift index 9caaa0de3fbd..98ecc8a1e5e6 100644 --- a/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+Debug.swift +++ b/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+Debug.swift @@ -235,6 +235,7 @@ extension TerminalSurface { surface = runtimeSurface portalLifecycleState = .live runtimeSurfaceFreedOutOfBandForTesting = false + cacheControllingTTYIdentity(for: runtimeSurface) installFontSizeActionObservation( on: runtimeSurface, callbackContext: callbackContext diff --git a/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+ProcessInfo.swift b/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+ProcessInfo.swift index d2a58706afaf..1cf99e9971ea 100644 --- a/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+ProcessInfo.swift +++ b/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+ProcessInfo.swift @@ -1,3 +1,4 @@ +internal import Darwin public import Foundation public import GhosttyKit @@ -16,22 +17,58 @@ extension TerminalSurface { return pid > 0 ? Int(pid) : nil } - /// The controlling TTY device name (e.g. `/dev/ttys003`) for this surface's - /// PTY, or `nil` when there is no live runtime surface or the runtime has no - /// tty yet. Every process in the pane (shell + descendants + background jobs) - /// shares this controlling tty, so it is the attribution key the guardrail - /// sums process-tree memory by. + /// The controlling TTY device name (e.g. `/dev/ttys003`) captured for this + /// surface's current PTY lifecycle, or `nil` when there is no live runtime + /// surface or the runtime has no TTY. Every process in the pane (shell, + /// descendants, and background jobs) shares this controlling TTY. @MainActor public func controllingTTYName() -> String? { - guard let surface = liveSurfaceForGhosttyAccess(reason: "memGuard.ttyName") else { + guard let surface = liveSurfaceForGhosttyAccess(reason: "processInfo.ttyName") else { return nil } + if runtimeControllingTTYName == nil { + // Ghostty starts its PTY on the IO thread, so the eager lookup at + // runtime installation can race before the device exists. Retry + // only until the lifecycle acquires a TTY, then serve the cache. + cacheControllingTTYIdentity(for: surface) + } + return runtimeControllingTTYName + } + + /// The character-device identifier captured for the current PTY lifecycle. + /// + /// The identifier is resolved once Ghostty's asynchronous PTY startup makes + /// it available, so delivery-time process routing can compare devices without + /// repeatedly allocating a TTY name or accessing the filesystem. + @MainActor + public var controllingTTYDeviceIdentifier: Int64? { + guard let surface = liveSurfaceForGhosttyAccess(reason: "processInfo.ttyDevice") else { + return nil + } + if runtimeControllingTTYName == nil { + cacheControllingTTYIdentity(for: surface) + } + return runtimeControllingTTYDeviceIdentifier + } + + @MainActor + func cacheControllingTTYIdentity(for surface: ghostty_surface_t) { + guard runtimeControllingTTYName == nil else { return } let exported = ghostty_surface_tty_name(surface) defer { ghostty_string_free(exported) } - guard let ptr = exported.ptr, exported.len > 0 else { return nil } + guard let ptr = exported.ptr, exported.len > 0 else { return } let data = Data(bytes: ptr, count: Int(exported.len)) - guard let decoded = String(data: data, encoding: .utf8) else { return nil } + guard let decoded = String(data: data, encoding: .utf8) else { return } let name = decoded.trimmingCharacters(in: .whitespacesAndNewlines) - return name.isEmpty ? nil : name + guard !name.isEmpty else { return } + runtimeControllingTTYName = name + runtimeControllingTTYDeviceIdentifier = ttyDeviceIdentifier(for: name) + } + + private func ttyDeviceIdentifier(for ttyName: String) -> Int64? { + let path = ttyName.hasPrefix("/dev/") ? ttyName : "/dev/\(ttyName)" + var statInfo = stat() + guard stat(path, &statInfo) == 0 else { return nil } + return Int64(statInfo.st_rdev) } } diff --git a/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+RuntimeLifecycle.swift b/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+RuntimeLifecycle.swift index 7e66bed32266..c3a1f3b6766c 100644 --- a/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+RuntimeLifecycle.swift +++ b/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+RuntimeLifecycle.swift @@ -697,6 +697,7 @@ extension TerminalSurface { requiresRestoreSpawnPacing = false } registry.registerRuntimeSurface(createdSurface, ownerId: id) + cacheControllingTTYIdentity(for: createdSurface) recordRuntimeSurfaceCreation() // Install the shared PTY tee so output consumers receive every byte // the read thread produces, in order, before the VT parser runs. diff --git a/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface.swift b/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface.swift index b4807d1d8c8c..5456f35f8673 100644 --- a/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface.swift +++ b/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface.swift @@ -57,12 +57,16 @@ public final class TerminalSurface: Identifiable, ObservableObject { public typealias CodexCommandShim = TerminalSurfaceCodexCommandShim public typealias CmuxContextEnvironment = TerminalSurfaceCmuxContextEnvironment private var runtimeSurface: ghostty_surface_t? + var runtimeControllingTTYName: String? + var runtimeControllingTTYDeviceIdentifier: Int64? /// The live runtime surface pointer, or nil before creation/after teardown. public internal(set) var surface: ghostty_surface_t? { get { runtimeSurface } set { guard runtimeSurface != newValue else { return } runtimeSurface = newValue + runtimeControllingTTYName = nil + runtimeControllingTTYDeviceIdentifier = nil runtimeSurfaceGeneration &+= 1 } } diff --git a/Packages/macOS/CmuxTerminal/Tests/CmuxTerminalTests/TerminalSurfaceCloseConfirmationTests.swift b/Packages/macOS/CmuxTerminal/Tests/CmuxTerminalTests/TerminalSurfaceCloseConfirmationTests.swift index 589c7983d632..9decc2d9b318 100644 --- a/Packages/macOS/CmuxTerminal/Tests/CmuxTerminalTests/TerminalSurfaceCloseConfirmationTests.swift +++ b/Packages/macOS/CmuxTerminal/Tests/CmuxTerminalTests/TerminalSurfaceCloseConfirmationTests.swift @@ -9,8 +9,37 @@ private func resetGhosttyRuntimeStubs() @_silgen_name("cmux_test_ghostty_runtime_stubs_set_close_state") private func setGhosttyCloseState(_ needsConfirm: Bool, _ foregroundPID: UInt64, _ ttyName: UnsafePointer?) +@_silgen_name("cmux_test_ghostty_tty_name_call_count") +private func ghosttyTTYNameCallCount() -> UInt32 + @MainActor @Suite(.serialized) struct TerminalSurfaceCloseConfirmationTests { + @Test func controllingTTYNameIsReadOncePerRuntimeLifecycle() { + let registry = FakeSurfaceRegistry() + let surface = makeSurface(registry: registry) + let runtimeSurface = UnsafeMutableRawPointer.allocate(byteCount: 8, alignment: 8) + registry.registerRuntimeSurface(runtimeSurface, ownerId: surface.id) + resetGhosttyRuntimeStubs() + defer { + resetGhosttyRuntimeStubs() + surface.releaseSurfaceForTesting() + runtimeSurface.deallocate() + } + + "/dev/null".withCString { ttyName in + setGhosttyCloseState(false, 0, ttyName) + surface.installRuntimeSurfaceForTesting(runtimeSurface) + + #expect(surface.controllingTTYName() == "/dev/null") + #expect(surface.controllingTTYName() == "/dev/null") + } + + #expect( + ghosttyTTYNameCallCount() == 1, + "PID routing must reuse terminal-lifecycle TTY identity instead of probing every surface" + ) + } + @Test func liveSurfaceWithoutPidOrTtyDoesNotRequireConfirmation() { let surface = makeSurface() let runtimeSurface = fakeRuntimeSurface() @@ -84,7 +113,10 @@ private func setGhosttyCloseState(_ needsConfirm: Bool, _ foregroundPID: UInt64, #expect(reusedPointerLifetime == releasedLifetime &+ 1) } - private func makeSurface(initialCommand: String? = nil) -> TerminalSurface { + private func makeSurface( + initialCommand: String? = nil, + registry: FakeSurfaceRegistry = FakeSurfaceRegistry() + ) -> TerminalSurface { let nativeView = FakeTerminalSurfaceNativeView(frame: NSRect(x: 0, y: 0, width: 800, height: 600)) let paneHost = FakeTerminalSurfacePaneHost(surfaceView: nativeView) return TerminalSurface( @@ -93,7 +125,7 @@ private func setGhosttyCloseState(_ needsConfirm: Bool, _ foregroundPID: UInt64, configTemplate: nil, initialCommand: initialCommand, dependencies: TerminalSurfaceRuntimeDependencies( - registry: FakeSurfaceRegistry(), + registry: registry, engine: FakeTerminalEngine(), viewProvider: FakeTerminalSurfaceViewProvider(surfaceView: nativeView, paneHost: paneHost), spawnPolicy: FakeSpawnPolicyProvider(), diff --git a/Packages/macOS/CmuxTerminal/Tests/GhosttyRuntimeTestStubs/GhosttyRuntimeTestStubs.c b/Packages/macOS/CmuxTerminal/Tests/GhosttyRuntimeTestStubs/GhosttyRuntimeTestStubs.c index 359794375f1c..e2d309aff596 100644 --- a/Packages/macOS/CmuxTerminal/Tests/GhosttyRuntimeTestStubs/GhosttyRuntimeTestStubs.c +++ b/Packages/macOS/CmuxTerminal/Tests/GhosttyRuntimeTestStubs/GhosttyRuntimeTestStubs.c @@ -18,6 +18,7 @@ typedef struct { static bool cmux_test_needs_confirm_quit = false; static uint64_t cmux_test_foreground_pid = 0; static const char* cmux_test_tty_name = NULL; +static uint32_t cmux_test_tty_name_call_count = 0; static void* cmux_test_renderer_realized_target = NULL; static bool cmux_test_renderer_realized_calls[16]; static uint32_t cmux_test_renderer_realized_call_count = 0; @@ -39,6 +40,7 @@ void cmux_test_ghostty_runtime_stubs_reset(void) { cmux_test_needs_confirm_quit = false; cmux_test_foreground_pid = 0; cmux_test_tty_name = NULL; + cmux_test_tty_name_call_count = 0; } void cmux_test_ghostty_renderer_realized_begin(void* surface) { @@ -320,12 +322,17 @@ void ghostty_surface_update_config(void *surface, void *raw_config) { } ghostty_string_s ghostty_surface_tty_name(void *surface) { (void)surface; + cmux_test_tty_name_call_count++; if (cmux_test_tty_name == NULL) { return (ghostty_string_s){0}; } return (ghostty_string_s){.ptr = cmux_test_tty_name, .len = strlen(cmux_test_tty_name), .sentinel = false}; } +uint32_t cmux_test_ghostty_tty_name_call_count(void) { + return cmux_test_tty_name_call_count; +} + bool cmux_test_ghostty_surface_was_updated(void *surface) { return surface == cmux_test_last_updated_surface; } diff --git a/Packages/macOS/CmuxTerminal/Tests/GhosttyRuntimeTestStubs/include/GhosttyRuntimeTestStubs.h b/Packages/macOS/CmuxTerminal/Tests/GhosttyRuntimeTestStubs/include/GhosttyRuntimeTestStubs.h index 90f9b53cba57..920eaff9c3fa 100644 --- a/Packages/macOS/CmuxTerminal/Tests/GhosttyRuntimeTestStubs/include/GhosttyRuntimeTestStubs.h +++ b/Packages/macOS/CmuxTerminal/Tests/GhosttyRuntimeTestStubs/include/GhosttyRuntimeTestStubs.h @@ -92,6 +92,7 @@ ghostty_string_s ghostty_surface_tty_name(void *surface); void cmux_test_ghostty_runtime_stubs_reset(void); void cmux_test_ghostty_runtime_stubs_set_close_state(bool needs_confirm, uint64_t foreground_pid, const char* tty_name); +uint32_t cmux_test_ghostty_tty_name_call_count(void); void cmux_test_ghostty_renderer_realized_begin(void *surface); void cmux_test_ghostty_renderer_realized_reset(void); uint32_t cmux_test_ghostty_renderer_realized_call_count(void); diff --git a/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift index cc0dd432084b..a89cd08ed904 100644 --- a/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift +++ b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift @@ -50,6 +50,18 @@ public final class SurfaceRegistryModel { /// routing never performs per-surface filesystem work on the main actor. public var surfaceTTYDevices: [UUID: Int64] = [:] + /// Surface ids whose TTY name was reported by the current terminal + /// runtime. Persisted names stay out of this set until `report_tty` + /// arrives, including when the current runtime reuses the same name. + public var runtimeReportedTTYSurfaceIDs: Set = [] + + /// Native runtime generation that emitted each current TTY report. + public var runtimeReportedTTYSurfaceGenerations: [UUID: UInt64] = [:] + + /// Authenticated remote workspace that originated each live TTY report. + /// This provenance follows a remote terminal through container moves. + public var remoteTTYReportOriginWorkspaceIDs: [UUID: UUID] = [:] + /// The shell-activity classification reported for each terminal panel, /// keyed by panel id (legacy `Workspace.panelShellActivityStates`). public var panelShellActivityStates: [UUID: PanelShellActivityState] = [:] diff --git a/Resources/shell-integration/cmux-bash-integration.bash b/Resources/shell-integration/cmux-bash-integration.bash index 75d6ac47227e..8626bb5dce03 100644 --- a/Resources/shell-integration/cmux-bash-integration.bash +++ b/Resources/shell-integration/cmux-bash-integration.bash @@ -159,10 +159,11 @@ _cmux_report_tty_via_relay() { local workspace_id="" workspace_id="$(_cmux_relay_workspace_id)" || return 1 [[ -n "$_CMUX_TTY_NAME" ]] || return 1 + [[ -n "$CMUX_TERMINAL_LIFECYCLE_ID" && -n "$CMUX_SSH_ATTEMPT_ID" ]] || return 1 local tty_name_json params tty_name_json="$(_cmux_json_escape "$_CMUX_TTY_NAME")" - params="{\"workspace_id\":\"$workspace_id\",\"tty_name\":\"$tty_name_json\"" + params="{\"workspace_id\":\"$workspace_id\",\"tty_name\":\"$tty_name_json\",\"terminal_lifecycle_id\":\"$CMUX_TERMINAL_LIFECYCLE_ID\",\"attempt_id\":\"$CMUX_SSH_ATTEMPT_ID\"" if [[ -n "$CMUX_PANEL_ID" ]]; then params+=",\"surface_id\":\"$CMUX_PANEL_ID\"" fi @@ -466,8 +467,10 @@ _CMUX_TMUX_SYNC_KEYS=( CMUX_SOCKET_ENABLE CMUX_SOCKET_MODE CMUX_SOCKET_PATH + CMUX_SSH_ATTEMPT_ID CMUX_TAB_ID CMUX_TAG + CMUX_TERMINAL_LIFECYCLE_ID CMUX_WORKSPACE_ID ) _CMUX_TMUX_SURFACE_SCOPED_KEYS=( diff --git a/Resources/shell-integration/cmux-zsh-integration.zsh b/Resources/shell-integration/cmux-zsh-integration.zsh index 80e60632811e..574ee3660cf2 100644 --- a/Resources/shell-integration/cmux-zsh-integration.zsh +++ b/Resources/shell-integration/cmux-zsh-integration.zsh @@ -169,10 +169,11 @@ _cmux_report_tty_via_relay() { local workspace_id="" workspace_id="$(_cmux_relay_workspace_id)" || return 1 [[ -n "$_CMUX_TTY_NAME" ]] || return 1 + [[ -n "$CMUX_TERMINAL_LIFECYCLE_ID" && -n "$CMUX_SSH_ATTEMPT_ID" ]] || return 1 local tty_name_json params tty_name_json="$(_cmux_json_escape "$_CMUX_TTY_NAME")" - params="{\"workspace_id\":\"$workspace_id\",\"tty_name\":\"$tty_name_json\"" + params="{\"workspace_id\":\"$workspace_id\",\"tty_name\":\"$tty_name_json\",\"terminal_lifecycle_id\":\"$CMUX_TERMINAL_LIFECYCLE_ID\",\"attempt_id\":\"$CMUX_SSH_ATTEMPT_ID\"" if [[ -n "$CMUX_PANEL_ID" ]]; then params+=",\"surface_id\":\"$CMUX_PANEL_ID\"" fi @@ -503,8 +504,10 @@ typeset -ga _CMUX_TMUX_SYNC_KEYS=( CMUX_SOCKET_ENABLE CMUX_SOCKET_MODE CMUX_SOCKET_PATH + CMUX_SSH_ATTEMPT_ID CMUX_TAB_ID CMUX_TAG + CMUX_TERMINAL_LIFECYCLE_ID CMUX_WORKSPACE_ID ) typeset -ga _CMUX_TMUX_SURFACE_SCOPED_KEYS=( diff --git a/Resources/shell-integration/fish/config.fish b/Resources/shell-integration/fish/config.fish index 884f651d1b19..d44476321d24 100644 --- a/Resources/shell-integration/fish/config.fish +++ b/Resources/shell-integration/fish/config.fish @@ -41,8 +41,10 @@ if test "$_cmux_integration_enabled" != 0 CMUX_SOCKET_ENABLE \ CMUX_SOCKET_MODE \ CMUX_SOCKET_PATH \ + CMUX_SSH_ATTEMPT_ID \ CMUX_TAB_ID \ CMUX_TAG \ + CMUX_TERMINAL_LIFECYCLE_ID \ CMUX_WORKSPACE_ID set -g _CMUX_TMUX_SURFACE_SCOPED_KEYS CMUX_PANEL_ID CMUX_SURFACE_ID @@ -240,17 +242,30 @@ if test "$_cmux_integration_enabled" != 0 "$relay_cli" rpc "$method" "$params" >/dev/null 2>&1 & end + function _cmux_relay_rpc --argument-names method params + _cmux_socket_uses_remote_relay; or return 1 + set -l relay_cli (_cmux_relay_cli_path) + test -n "$relay_cli"; or return 1 + set -l response ("$relay_cli" rpc "$method" "$params" 2>/dev/null); or return 1 + set response (string join '' -- $response) + string match -q '*"ok":false*' -- "$response"; and return 1 + string match -q '*"ok": false*' -- "$response"; and return 1 + return 0 + end + function _cmux_report_tty_via_relay _cmux_socket_uses_remote_relay; or return 1 test -n "$_CMUX_TTY_NAME"; or return 1 + test -n "$CMUX_TERMINAL_LIFECYCLE_ID"; or return 1 + test -n "$CMUX_SSH_ATTEMPT_ID"; or return 1 set -l workspace_id (_cmux_relay_workspace_id); or return 1 set -l tty_name_json (_cmux_json_escape "$_CMUX_TTY_NAME") - set -l params "{\"workspace_id\":\"$workspace_id\",\"tty_name\":\"$tty_name_json\"" + set -l params "{\"workspace_id\":\"$workspace_id\",\"tty_name\":\"$tty_name_json\",\"terminal_lifecycle_id\":\"$CMUX_TERMINAL_LIFECYCLE_ID\",\"attempt_id\":\"$CMUX_SSH_ATTEMPT_ID\"" if test -n "$CMUX_PANEL_ID" set params "$params,\"surface_id\":\"$CMUX_PANEL_ID\"" end set params "$params}" - _cmux_relay_rpc_bg surface.report_tty "$params" + _cmux_relay_rpc surface.report_tty "$params" end function _cmux_report_pwd_via_relay --argument-names pwd @@ -416,8 +431,10 @@ if test "$_cmux_integration_enabled" != 0 set -g _CMUX_TTY_REPORTED 1 _cmux_send_bg "report_tty $_CMUX_TTY_NAME --tab=$CMUX_TAB_ID --panel=$CMUX_PANEL_ID" else if _cmux_socket_uses_remote_relay + # Treat the first relay report as a readiness barrier. Latch only + # after acknowledgement so later prompts retry transient failures. + _cmux_report_tty_via_relay; or return 0 set -g _CMUX_TTY_REPORTED 1 - _cmux_report_tty_via_relay end end diff --git a/Sources/AgentDeliveryTargetResolution.swift b/Sources/AgentDeliveryTargetResolution.swift index db35d70ed41f..459a454ae7ec 100644 --- a/Sources/AgentDeliveryTargetResolution.swift +++ b/Sources/AgentDeliveryTargetResolution.swift @@ -13,10 +13,10 @@ import Foundation /// /// Two lookups implement this: /// - pid → surface: the agent process's controlling tty device -/// (`proc_bsdinfo.e_tdev`) matched against every live surface's reported -/// tty. A pane's pty device is fixed for the pane's lifetime and the -/// process's controlling terminal is a live kernel fact, so a unique match -/// is authoritative regardless of where the pane has been moved. +/// (`proc_bsdinfo.e_tdev`) matched against every live Ghostty PTY plus fresh +/// runtime TTY reports. A pane's pty device is fixed for the pane's lifetime, +/// and the process's controlling terminal is a live kernel fact, so a unique +/// match is authoritative regardless of where the pane has been moved. /// - surface → notification owner: `AppDelegate.notificationSurfaceOwner`, /// which finds the workspace or Dock that CURRENTLY owns the panel (issue /// #5781 pane moves and Dock transfers). @@ -78,32 +78,112 @@ nonisolated func agentLiveProcessIdentity(pid: pid_t) -> (ttyDevice: Int64?, sco @MainActor extension Workspace { - /// Reported TTY names and their device-id index share one mutation path so - /// live agent resolution never stats every surface on the main actor. + /// TTY metadata writes preserve runtime provenance only when the value is + /// unchanged. Only ``registerReportedSurfaceTTYName(_:panelId:)`` may + /// establish current-runtime evidence. var surfaceTTYNames: [UUID: String] { get { surfaceRegistry.surfaceTTYNames } set { let previous = surfaceRegistry.surfaceTTYNames - var devices = surfaceRegistry.surfaceTTYDevices.filter { newValue[$0.key] != nil } - for (panelId, ttyName) in newValue where previous[panelId] != ttyName { - devices[panelId] = CmuxTopProcessSnapshot.deviceIdentifier(forTTYName: ttyName) - } + let unchangedPanelIds = Set(newValue.compactMap { panelId, ttyName in + previous[panelId] == ttyName ? panelId : nil + }) surfaceRegistry.surfaceTTYNames = newValue - surfaceRegistry.surfaceTTYDevices = devices + surfaceRegistry.surfaceTTYDevices = surfaceRegistry.surfaceTTYDevices.filter { + unchangedPanelIds.contains($0.key) + } + surfaceRegistry.runtimeReportedTTYSurfaceIDs.formIntersection(unchangedPanelIds) + surfaceRegistry.runtimeReportedTTYSurfaceGenerations = + surfaceRegistry.runtimeReportedTTYSurfaceGenerations.filter { + unchangedPanelIds.contains($0.key) + } } } - /// Cached TTY character-device ids, updated with ``surfaceTTYNames``. + /// Cached character-device ids from explicit current-runtime TTY reports. var surfaceTTYDevices: [UUID: Int64] { surfaceRegistry.surfaceTTYDevices } + /// Records an explicit `report_tty` from the current terminal runtime. + /// This stays distinct from dictionary metadata writes because a restored + /// runtime can legitimately report the same TTY name as its predecessor. + func registerReportedSurfaceTTYName(_ ttyName: String, panelId: UUID) { + surfaceTTYNames[panelId] = ttyName + guard let terminal = panels[panelId] as? TerminalPanel else { + invalidateReportedSurfaceTTYRuntime(panelId: panelId) + return + } + surfaceRegistry.surfaceTTYDevices[panelId] = CmuxTopProcessSnapshot.deviceIdentifier(forTTYName: ttyName) + surfaceRegistry.runtimeReportedTTYSurfaceIDs.insert(panelId) + surfaceRegistry.runtimeReportedTTYSurfaceGenerations[panelId] = + terminal.surface.runtimeSurfaceGeneration + } + + /// Restores display/port-scan metadata without treating the previous + /// process's PTY as evidence about the newly created terminal runtime. + /// A subsequent `report_tty`, even with the same name, populates the live + /// device index through ``surfaceTTYNames``. + func restorePersistedSurfaceTTYName(_ ttyName: String?, panelId: UUID) { + surfaceRegistry.surfaceTTYNames[panelId] = ttyName + invalidateReportedSurfaceTTYRuntime(panelId: panelId) + } + + /// Discards live-process evidence while preserving display-only TTY metadata. + func invalidateReportedSurfaceTTYRuntime(panelId: UUID) { + surfaceRegistry.surfaceTTYDevices.removeValue(forKey: panelId) + surfaceRegistry.runtimeReportedTTYSurfaceIDs.remove(panelId) + surfaceRegistry.runtimeReportedTTYSurfaceGenerations.removeValue(forKey: panelId) + } + + func hasCurrentRuntimeReportedTTY(panelId: UUID, terminal: TerminalPanel) -> Bool { + surfaceRegistry.runtimeReportedTTYSurfaceIDs.contains(panelId) + && surfaceRegistry.runtimeReportedTTYSurfaceGenerations[panelId] + == terminal.surface.runtimeSurfaceGeneration + } + + func adoptTransferredSurfaceTTYName(from transfer: DetachedSurfaceTransfer) { + guard let ttyName = transfer.ttyName?.trimmingCharacters(in: .whitespacesAndNewlines), + !ttyName.isEmpty else { + surfaceTTYNames.removeValue(forKey: transfer.panelId) + return + } + if transfer.ttyNameWasReportedByCurrentRuntime, + let terminal = panels[transfer.panelId] as? TerminalPanel, + transfer.ttyReportRuntimeSurfaceGeneration == + terminal.surface.runtimeSurfaceGeneration { + registerReportedSurfaceTTYName(ttyName, panelId: transfer.panelId) + } else { + restorePersistedSurfaceTTYName(ttyName, panelId: transfer.panelId) + } + } + + func restoreTransferredSurfaceTTYRuntimeProofIfNeeded(from transfer: DetachedSurfaceTransfer) { + guard transfer.ttyNameWasReportedByCurrentRuntime, + !surfaceRegistry.runtimeReportedTTYSurfaceIDs.contains(transfer.panelId) else { + return + } + adoptTransferredSurfaceTTYName(from: transfer) + } + /// Host-local TTY bindings eligible to identify a process running on this /// Mac. Remote workspaces and remote terminal surfaces use a different /// `/dev` namespace and must never participate in local device matching. var localAgentDeliveryTTYDevices: [(surfaceId: UUID, ttyDevice: Int64)] { guard !isRemoteWorkspace, !isRemoteTmuxMirror else { return [] } - return surfaceTTYDevices.compactMap { panelId, device in - guard panels[panelId] != nil, !isRemoteTerminalSurface(panelId) else { return nil } - return (panelId, device) + return panels.flatMap { panelId, panel -> [(surfaceId: UUID, ttyDevice: Int64)] in + guard let terminal = panel as? TerminalPanel, + !isRemoteTerminalSurface(panelId) else { + return [] + } + var devices: [Int64] = [] + if let liveDevice = terminal.surface.controllingTTYDeviceIdentifier { + devices.append(liveDevice) + } + if hasCurrentRuntimeReportedTTY(panelId: panelId, terminal: terminal), + let reportedDevice = surfaceTTYDevices[panelId], + !devices.contains(reportedDevice) { + devices.append(reportedDevice) + } + return devices.map { (panelId, $0) } } } } @@ -114,22 +194,29 @@ extension DockSplitStore { /// /// A surface transfer removes the panel from its Workspace registry, so /// live PID attribution must inspect Dock ownership separately. Prefer the - /// terminal's current Ghostty PTY and fall back to the TTY preserved with - /// the transfer while the live surface is being reattached. + /// terminal's current Ghostty PTY and include a fresh reported TTY as the + /// nested-PTY fallback. var localAgentDeliveryTTYDevices: [(surfaceId: UUID, ttyDevice: Int64)] { - panels.compactMap { panelId, panel in + panels.flatMap { panelId, panel -> [(surfaceId: UUID, ttyDevice: Int64)] in guard let terminal = panel as? TerminalPanel, detachedSurfaceTransfersByPanelId[panelId]?.isRemoteTerminal != true else { - return nil + return [] } - let liveDevice = terminal.surface.controllingTTYName().flatMap { - CmuxTopProcessSnapshot.deviceIdentifier(forTTYName: $0) + var devices: [Int64] = [] + if let liveDevice = terminal.surface.controllingTTYDeviceIdentifier { + devices.append(liveDevice) } - let preservedDevice = detachedSurfaceTransfersByPanelId[panelId]?.ttyName.flatMap { - CmuxTopProcessSnapshot.deviceIdentifier(forTTYName: $0) + if let transfer = detachedSurfaceTransfersByPanelId[panelId], + transfer.ttyNameWasReportedByCurrentRuntime, + transfer.ttyReportRuntimeSurfaceGeneration + == terminal.surface.runtimeSurfaceGeneration, + let reportedDevice = transfer.ttyName.flatMap( + CmuxTopProcessSnapshot.deviceIdentifier(forTTYName:) + ), + !devices.contains(reportedDevice) { + devices.append(reportedDevice) } - guard let ttyDevice = liveDevice ?? preservedDevice else { return nil } - return (panelId, ttyDevice) + return devices.map { (panelId, $0) } } } } @@ -150,9 +237,8 @@ extension AppDelegate { var ttyTarget: AgentDeliveryTargetCandidate? if let ttyDevice = identity.ttyDevice { - // TTY device ids are indexed when each surface reports or moves, - // so hook delivery only walks in-memory bindings on MainActor. It - // never stats every live surface while UI work is serialized. + // Read the lifecycle-cached Ghostty PTY so shell integration is not + // required; fresh runtime reports remain a nested-PTY fallback. ttyTarget = agentDeliveryTargetMatchingTTYDevice( ttyDevice, surfaceTTYDevices: liveAgentDeliveryTTYBindings() @@ -237,7 +323,7 @@ extension AppDelegate { return (owner.tabID, owner.surfaceID) } - private func agentDeliveryTabManagers() -> [TabManager] { + func agentDeliveryTabManagers() -> [TabManager] { var managers: [TabManager] = [] func append(_ manager: TabManager?) { guard let manager, !managers.contains(where: { $0 === manager }) else { return } @@ -258,6 +344,8 @@ extension TerminalController { /// - `{surface_id, workspace_id?}`: the workspace that currently hosts a /// known surface (`source: "surface"`), re-homing moved panes. /// - `{workspace_id}`: existence check only (`source: "workspace"`). + /// - `{tty_name, tty_resolution: "reported_tty"}`: a relay-authenticated + /// remote workspace's unique fresh TTY report (`source: "tty"`). func v2AgentResolveDeliveryTarget(params: [String: Any]) -> V2CallResult { let claimedWorkspaceId = v2UUID(params, "workspace_id") let claimedSurfaceId = v2UUID(params, "surface_id") @@ -288,6 +376,34 @@ extension TerminalController { data: nil ) } + if params.keys.contains("tty_name") { + let ttyResolution = AgentTTYBindingResolution.reportedTTY.rawValue + guard params["tty_resolution"] as? String == ttyResolution, + let ttyName = params["tty_name"] as? String, + TerminalCallerTTYResolver.normalizedName(ttyName) != nil, + let remoteWorkspaceId = v2UUID(params, "_cmux_remote_workspace_id"), + let authenticatedWorkspace = controlTabForSidebarMutation(id: remoteWorkspaceId), + authenticatedWorkspace.isRemoteWorkspace, + let target = appDelegate.liveRelayAgentDeliveryTarget( + authenticatedWorkspaceID: remoteWorkspaceId, + ttyName: ttyName + ) else { + return .err( + code: "not_found", + message: String( + localized: "agent.deliveryTarget.error.notFound", + defaultValue: "No live delivery target" + ), + data: nil + ) + } + return .ok([ + "workspace_id": target.workspaceId.uuidString, + "surface_id": target.surfaceId.uuidString, + "source": "tty", + "tty_resolution": ttyResolution, + ]) + } if params.keys.contains("pid") { // A socket caller controls both the value and its JSON type. Do // not coerce fractional/lossy NSNumber values, trap while diff --git a/Sources/AgentProcessBindingResolution.swift b/Sources/AgentProcessBindingResolution.swift index fdd34fc919e2..208d536b3d0b 100644 --- a/Sources/AgentProcessBindingResolution.swift +++ b/Sources/AgentProcessBindingResolution.swift @@ -2,3 +2,7 @@ enum AgentProcessBindingResolution: String, Sendable { case corroborated case controllingTTY = "controlling_tty" } + +enum AgentTTYBindingResolution: String, Sendable { + case reportedTTY = "reported_tty" +} diff --git a/Sources/AgentRelayTTYTargetResolution.swift b/Sources/AgentRelayTTYTargetResolution.swift new file mode 100644 index 000000000000..46a8729e5425 --- /dev/null +++ b/Sources/AgentRelayTTYTargetResolution.swift @@ -0,0 +1,141 @@ +import Foundation + +@MainActor +extension Workspace { + /// Records a fresh report only when this workspace owns the surface for + /// the relay-authenticated workspace that originally launched it. + func registerRelayReportedTTY( + _ ttyName: String, + panelID: UUID, + authenticatedWorkspaceID: UUID, + terminalLifecycleID: UUID, + attemptID: UUID + ) -> Bool { + guard let terminal = panels[panelID] as? TerminalPanel, + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[panelID] == + authenticatedWorkspaceID, + terminal.surface.terminalLifecycleId == terminalLifecycleID, + remoteTerminalAttemptIDsBySurfaceId[panelID] == attemptID else { + return false + } + registerReportedSurfaceTTYName(ttyName, panelId: panelID) + if isRemoteWorkspace { + syncRemotePortScanTTYs() + _ = applyPendingRemoteSurfacePortKickIfNeeded(to: panelID) + } + return true + } + + /// Fresh remote TTY reports whose authenticated relay origin matches the + /// requested workspace. The binding points at the surface's current owner. + func runtimeReportedRemoteTTYCandidates( + authenticatedWorkspaceID: UUID + ) -> [(binding: TerminalCallerTTYBinding, ttyName: String)] { + surfaceRegistry.runtimeReportedTTYSurfaceIDs.compactMap { surfaceID in + guard let terminal = panels[surfaceID] as? TerminalPanel, + hasCurrentRuntimeReportedTTY(panelId: surfaceID, terminal: terminal), + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[surfaceID] == + authenticatedWorkspaceID, + let ttyName = surfaceRegistry.surfaceTTYNames[surfaceID] else { + return nil + } + return ( + binding: TerminalCallerTTYBinding( + workspaceId: id, + surfaceId: surfaceID + ), + ttyName: ttyName + ) + } + } + + /// Resolves one authenticated remote workspace without inspecting another + /// relay's TTY namespace. + func agentDeliveryTarget(forReportedTTYName ttyName: String) -> AgentDeliveryTargetCandidate? { + guard isRemoteWorkspace else { return nil } + var candidates = runtimeReportedRemoteTTYCandidates( + authenticatedWorkspaceID: id + ) + for dock in DockSplitStore.liveRemoteTerminalStores( + presentationWorkspaceID: id + ) { + candidates.append(contentsOf: dock.runtimeReportedRemoteTTYCandidates( + presentationWorkspaceID: id + )) + } + let resolver = TerminalCallerTTYResolver(reportedCandidates: candidates) + guard let binding = resolver.binding(for: ttyName) else { return nil } + return AgentDeliveryTargetCandidate( + workspaceId: binding.workspaceId, + surfaceId: binding.surfaceId + ) + } + + /// Keeps the launch attempt with a live remote terminal even when its new + /// container is an ordinary workspace with no remote configuration. + func restoreTransferredRelayTTYIdentity(from transfer: DetachedSurfaceTransfer) { + guard transfer.isRemoteTerminal, + transfer.remoteTerminalSessionPhase != .ended, + let attemptID = transfer.remoteTerminalAttemptID else { + remoteTerminalAttemptIDsBySurfaceId.removeValue(forKey: transfer.panelId) + return + } + remoteTerminalAttemptIDsBySurfaceId[transfer.panelId] = attemptID + } +} + +@MainActor +extension AppDelegate { + /// Routes a fresh relay report to the unique live Workspace owner without + /// allowing the authenticated origin to change during a container move. + func registerLiveRelayReportedTTY( + _ ttyName: String, + panelID: UUID, + authenticatedWorkspaceID: UUID, + terminalLifecycleID: UUID, + attemptID: UUID + ) -> Bool { + let owners = agentDeliveryTabManagers().flatMap(\.tabs).filter { + $0.panels[panelID] != nil + && $0.surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[panelID] == + authenticatedWorkspaceID + } + guard owners.count == 1 else { return false } + return owners[0].registerRelayReportedTTY( + ttyName, + panelID: panelID, + authenticatedWorkspaceID: authenticatedWorkspaceID, + terminalLifecycleID: terminalLifecycleID, + attemptID: attemptID + ) + } + + /// Resolves a relay-authenticated TTY across the live containers that may + /// now own a surface launched by that remote workspace. + func liveRelayAgentDeliveryTarget( + authenticatedWorkspaceID: UUID, + ttyName: String + ) -> AgentDeliveryTargetCandidate? { + var candidates: [(binding: TerminalCallerTTYBinding, ttyName: String)] = [] + for manager in agentDeliveryTabManagers() { + for workspace in manager.tabs { + candidates.append(contentsOf: workspace.runtimeReportedRemoteTTYCandidates( + authenticatedWorkspaceID: authenticatedWorkspaceID + )) + } + } + for dock in DockSplitStore.liveRemoteTerminalStores( + presentationWorkspaceID: authenticatedWorkspaceID + ) { + candidates.append(contentsOf: dock.runtimeReportedRemoteTTYCandidates( + presentationWorkspaceID: authenticatedWorkspaceID + )) + } + let resolver = TerminalCallerTTYResolver(reportedCandidates: candidates) + guard let binding = resolver.binding(for: ttyName) else { return nil } + return AgentDeliveryTargetCandidate( + workspaceId: binding.workspaceId, + surfaceId: binding.surfaceId + ) + } +} diff --git a/Sources/DockSplitStore+RemoteTerminalLiveness.swift b/Sources/DockSplitStore+RemoteTerminalLiveness.swift index 425c36367176..eb4a69ee1c85 100644 --- a/Sources/DockSplitStore+RemoteTerminalLiveness.swift +++ b/Sources/DockSplitStore+RemoteTerminalLiveness.swift @@ -63,9 +63,17 @@ extension DockSplitStore { transfer.remoteTerminalLifecycleID == terminalLifecycleID { return false } + let beginsNewRuntime = + transfer.remoteTerminalLifecycleID != terminalLifecycleID || + (transfer.remoteTerminalAttemptID != attemptID && + transfer.remoteTerminalAuthority?.preservesRemotePTYAcrossAttachAttempts != true) transfer.remoteTerminalSessionPhase = .launching transfer.remoteTerminalLifecycleID = terminalLifecycleID transfer.remoteTerminalAttemptID = attemptID + if beginsNewRuntime { + transfer.ttyNameWasReportedByCurrentRuntime = false + transfer.ttyReportRuntimeSurfaceGeneration = nil + } setDetachedSurfaceTransfer(transfer, forPanelID: panelId) return true } @@ -108,6 +116,82 @@ extension DockSplitStore { return transfer.sessionRestoreWorkspaceId == presentationWorkspaceID } + static func registerReportedRemoteSurfaceTTYName( + _ ttyName: String, + panelId: UUID, + presentationWorkspaceID: UUID, + authenticatedWorkspaceID: UUID, + terminalLifecycleID: UUID, + attemptID: UUID + ) -> Bool { + let owners = liveRemoteTerminalStores( + presentationWorkspaceID: presentationWorkspaceID + ).filter { + $0.ownsRemoteTerminalTransfer( + panelId: panelId, + presentationWorkspaceID: presentationWorkspaceID + ) + } + guard owners.count == 1 else { return false } + return owners[0].registerReportedRemoteSurfaceTTYName( + ttyName, + panelId: panelId, + presentationWorkspaceID: presentationWorkspaceID, + authenticatedWorkspaceID: authenticatedWorkspaceID, + terminalLifecycleID: terminalLifecycleID, + attemptID: attemptID + ) + } + + func runtimeReportedRemoteTTYCandidates( + presentationWorkspaceID: UUID + ) -> [(binding: TerminalCallerTTYBinding, ttyName: String)] { + detachedSurfaceTransfersByPanelId.compactMap { panelId, transfer in + guard panels[panelId] != nil, + transfer.isRemoteTerminal, + transfer.sessionRestoreWorkspaceId == presentationWorkspaceID, + transfer.remoteTerminalSessionPhase != .ended, + transfer.ttyNameWasReportedByCurrentRuntime, + transfer.ttyReportRuntimeSurfaceGeneration + == (panels[panelId] as? TerminalPanel)?.surface.runtimeSurfaceGeneration, + let ttyName = transfer.ttyName else { + return nil + } + return ( + binding: TerminalCallerTTYBinding( + workspaceId: workspaceId, + surfaceId: panelId + ), + ttyName: ttyName + ) + } + } + + private func registerReportedRemoteSurfaceTTYName( + _ ttyName: String, + panelId: UUID, + presentationWorkspaceID: UUID, + authenticatedWorkspaceID: UUID, + terminalLifecycleID: UUID, + attemptID: UUID + ) -> Bool { + guard let terminal = panels[panelId] as? TerminalPanel, + var transfer = detachedSurfaceTransfersByPanelId[panelId], + transfer.isRemoteTerminal, + transfer.sessionRestoreWorkspaceId == presentationWorkspaceID, + transfer.sessionRestoreWorkspaceId == authenticatedWorkspaceID, + transfer.remoteTerminalSessionPhase != .ended, + terminal.surface.terminalLifecycleId == terminalLifecycleID, + transfer.remoteTerminalAttemptID == attemptID else { + return false + } + transfer.ttyName = ttyName + transfer.ttyNameWasReportedByCurrentRuntime = true + transfer.ttyReportRuntimeSurfaceGeneration = terminal.surface.runtimeSurfaceGeneration + setDetachedSurfaceTransfer(transfer, forPanelID: panelId) + return true + } + func markRemoteTerminalSessionEnded(panelId: UUID, relayPort: Int?) -> Bool { guard let relayPort, relayPort > 0 else { return false } return markRemoteTerminalSessionEnded( @@ -152,6 +236,8 @@ extension DockSplitStore { transfer.remoteTerminalLifecycleID = terminalLifecycleID ?? transfer.remoteTerminalLifecycleID transfer.remoteTerminalAttemptID = nil + transfer.ttyNameWasReportedByCurrentRuntime = false + transfer.ttyReportRuntimeSurfaceGeneration = nil setDetachedSurfaceTransfer(transfer, forPanelID: panelId) return true } diff --git a/Sources/DockSplitStore+SurfaceTransfer.swift b/Sources/DockSplitStore+SurfaceTransfer.swift index 27613ca4ceb5..2cc7e7294e02 100644 --- a/Sources/DockSplitStore+SurfaceTransfer.swift +++ b/Sources/DockSplitStore+SurfaceTransfer.swift @@ -276,6 +276,8 @@ extension DockSplitStore { ? preservedTransfer?.directoryDisplayLabel : nil, ttyName: preservedTransfer?.ttyName, + ttyNameWasReportedByCurrentRuntime: preservedTransfer?.ttyNameWasReportedByCurrentRuntime ?? false, + ttyReportRuntimeSurfaceGeneration: preservedTransfer?.ttyReportRuntimeSurfaceGeneration, cachedTitle: panel.displayTitle, customTitle: preservedTransfer?.customTitle, customTitleSource: preservedTransfer?.customTitleSource, @@ -295,6 +297,7 @@ extension DockSplitStore { remoteTerminalLifecycleID: preservedTransfer?.remoteTerminalLifecycleID, remoteTerminalAttemptID: preservedTransfer?.remoteTerminalAttemptID, remoteRelayPort: preservedTransfer?.remoteRelayPort, + remoteRelayNamespaceConfiguration: preservedTransfer?.remoteRelayNamespaceConfiguration, remotePTYSessionID: preservedTransfer?.remotePTYSessionID, remoteCleanupConfiguration: preservedTransfer?.remoteCleanupConfiguration ) diff --git a/Sources/RemoteInteractiveShellBootstrapBuilder.swift b/Sources/RemoteInteractiveShellBootstrapBuilder.swift index 29f53e1ed22b..fd50b6af960a 100644 --- a/Sources/RemoteInteractiveShellBootstrapBuilder.swift +++ b/Sources/RemoteInteractiveShellBootstrapBuilder.swift @@ -265,7 +265,9 @@ enum RemoteInteractiveShellBootstrapBuilder { "case \"$cmux_surface_id\" in \"\"|'__CMUX_''SURFACE_ID__') ;; *) export CMUX_SURFACE_ID=\"$cmux_surface_id\"; export CMUX_PANEL_ID=\"$cmux_surface_id\" ;; esac", "cmux_terminal_lifecycle_id='__CMUX_TERMINAL_LIFECYCLE_ID__'", "case \"$cmux_terminal_lifecycle_id\" in \"\"|'__CMUX_''TERMINAL_LIFECYCLE_ID__') ;; *) export CMUX_TERMINAL_LIFECYCLE_ID=\"$cmux_terminal_lifecycle_id\" ;; esac", - "unset cmux_workspace_id cmux_surface_id cmux_terminal_lifecycle_id", + "cmux_ssh_attempt_id='__CMUX_SSH_ATTEMPT_ID__'", + "case \"$cmux_ssh_attempt_id\" in \"\"|'__CMUX_''SSH_ATTEMPT_ID__') ;; *) export CMUX_SSH_ATTEMPT_ID=\"$cmux_ssh_attempt_id\" ;; esac", + "unset cmux_workspace_id cmux_surface_id cmux_terminal_lifecycle_id cmux_ssh_attempt_id", "hash -r >/dev/null 2>&1 || true", "rehash >/dev/null 2>&1 || true", ]) @@ -373,17 +375,15 @@ enum RemoteInteractiveShellBootstrapBuilder { " mkdir -p \"$HOME/.cmux/relay\" >/dev/null 2>&1 || true", " printf '%s' \"$cmux_relay_tty\" > \"$HOME/.cmux/relay/\(remoteRelayPort).tty\" 2>/dev/null || true", "fi", - "if [ -n \"$cmux_relay_cli\" ] && [ -n \"$CMUX_WORKSPACE_ID\" ] && [ -n \"$cmux_relay_tty\" ] && [ \"$cmux_relay_tty\" != \"not a tty\" ]; then", - " (", - " cmux_relay_report_tty=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"tty_name\\\":\\\"$cmux_relay_tty\\\"}\"", - " cmux_relay_ports_kick=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"reason\\\":\\\"command\\\"}\"", - " if [ -n \"$CMUX_SURFACE_ID\" ]; then", - " cmux_relay_report_tty=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"surface_id\\\":\\\"$CMUX_SURFACE_ID\\\",\\\"tty_name\\\":\\\"$cmux_relay_tty\\\"}\"", - " cmux_relay_ports_kick=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"surface_id\\\":\\\"$CMUX_SURFACE_ID\\\",\\\"reason\\\":\\\"command\\\"}\"", - " fi", - " \"$cmux_relay_cli\" rpc surface.report_tty \"$cmux_relay_report_tty\" >/dev/null 2>&1 || true", - " \"$cmux_relay_cli\" rpc surface.ports_kick \"$cmux_relay_ports_kick\" >/dev/null 2>&1 || true", - " ) /dev/null 2>&1 &", + "if [ -n \"$cmux_relay_cli\" ] && [ -n \"$CMUX_WORKSPACE_ID\" ] && [ -n \"$CMUX_TERMINAL_LIFECYCLE_ID\" ] && [ -n \"$CMUX_SSH_ATTEMPT_ID\" ] && [ -n \"$cmux_relay_tty\" ] && [ \"$cmux_relay_tty\" != \"not a tty\" ]; then", + " cmux_relay_report_tty=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"tty_name\\\":\\\"$cmux_relay_tty\\\",\\\"terminal_lifecycle_id\\\":\\\"$CMUX_TERMINAL_LIFECYCLE_ID\\\",\\\"attempt_id\\\":\\\"$CMUX_SSH_ATTEMPT_ID\\\"}\"", + " cmux_relay_ports_kick=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"reason\\\":\\\"command\\\"}\"", + " if [ -n \"$CMUX_SURFACE_ID\" ]; then", + " cmux_relay_report_tty=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"surface_id\\\":\\\"$CMUX_SURFACE_ID\\\",\\\"tty_name\\\":\\\"$cmux_relay_tty\\\",\\\"terminal_lifecycle_id\\\":\\\"$CMUX_TERMINAL_LIFECYCLE_ID\\\",\\\"attempt_id\\\":\\\"$CMUX_SSH_ATTEMPT_ID\\\"}\"", + " cmux_relay_ports_kick=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"surface_id\\\":\\\"$CMUX_SURFACE_ID\\\",\\\"reason\\\":\\\"command\\\"}\"", + " fi", + " \"$cmux_relay_cli\" rpc surface.report_tty \"$cmux_relay_report_tty\" >/dev/null 2>&1 || true", + " ( \"$cmux_relay_cli\" rpc surface.ports_kick \"$cmux_relay_ports_kick\" >/dev/null 2>&1 || true ) /dev/null 2>&1 &", "fi", "unset CMUX_BOOTSTRAP_TTY cmux_relay_cli cmux_relay_tty cmux_relay_report_tty cmux_relay_ports_kick", ] diff --git a/Sources/TerminalController+ControlSidebarContext2.swift b/Sources/TerminalController+ControlSidebarContext2.swift index 7a652ed99ff7..741e8133ba95 100644 --- a/Sources/TerminalController+ControlSidebarContext2.swift +++ b/Sources/TerminalController+ControlSidebarContext2.swift @@ -291,7 +291,7 @@ extension TerminalController { let validSurfaceIds = Set(tab.panels.keys) tab.pruneSurfaceMetadata(validSurfaceIds: validSurfaceIds) guard validSurfaceIds.contains(scope.panelID) else { return } - tab.surfaceTTYNames[scope.panelID] = ttyName + tab.registerReportedSurfaceTTYName(ttyName, panelId: scope.panelID) if tab.isRemoteWorkspace { tab.syncRemotePortScanTTYs() _ = tab.applyPendingRemoteSurfacePortKickIfNeeded(to: scope.panelID) @@ -308,7 +308,7 @@ extension TerminalController { prune: false, requireLiveSurface: true ) { tab, surfaceId in - tab.surfaceTTYNames[surfaceId] = ttyName + tab.registerReportedSurfaceTTYName(ttyName, panelId: surfaceId) if tab.isRemoteWorkspace { tab.syncRemotePortScanTTYs() _ = tab.applyPendingRemoteSurfacePortKickIfNeeded(to: surfaceId) diff --git a/Sources/TerminalController+ControlSurfaceContext4.swift b/Sources/TerminalController+ControlSurfaceContext4.swift index 7f154ec97aaf..1d80579bf3ae 100644 --- a/Sources/TerminalController+ControlSurfaceContext4.swift +++ b/Sources/TerminalController+ControlSurfaceContext4.swift @@ -25,13 +25,48 @@ extension TerminalController { func controlSurfaceReportTTY( workspaceID: UUID, requestedSurfaceID: UUID?, - ttyName: String + ttyName: String, + authenticatedRemoteWorkspaceID: UUID?, + terminalLifecycleID: UUID?, + attemptID: UUID? ) -> ControlSurfaceReportTTYResolution { guard let tab = controlTabForSidebarMutation(id: workspaceID) else { return .workspaceNotFound } + let relayIdentity = authenticatedRemoteWorkspaceID.flatMap { workspaceID in + terminalLifecycleID.flatMap { lifecycleID in + attemptID.map { (workspaceID, lifecycleID, $0) } + } + } + let hasRelayIdentity = authenticatedRemoteWorkspaceID != nil || + terminalLifecycleID != nil || attemptID != nil let validSurfaceIds = Set(tab.panels.keys) tab.pruneSurfaceMetadata(validSurfaceIds: validSurfaceIds) + if let requestedSurfaceID, + !validSurfaceIds.contains(requestedSurfaceID), + let relayIdentity, + DockSplitStore.registerReportedRemoteSurfaceTTYName( + ttyName, + panelId: requestedSurfaceID, + presentationWorkspaceID: workspaceID, + authenticatedWorkspaceID: relayIdentity.0, + terminalLifecycleID: relayIdentity.1, + attemptID: relayIdentity.2 + ) { + return .recorded(surfaceID: requestedSurfaceID) + } + if let requestedSurfaceID, + !validSurfaceIds.contains(requestedSurfaceID), + let relayIdentity, + AppDelegate.shared?.registerLiveRelayReportedTTY( + ttyName, + panelID: requestedSurfaceID, + authenticatedWorkspaceID: relayIdentity.0, + terminalLifecycleID: relayIdentity.1, + attemptID: relayIdentity.2 + ) == true { + return .recorded(surfaceID: requestedSurfaceID) + } let surfaceId = controlResolveReportedSurfaceId( in: tab, @@ -39,18 +74,24 @@ extension TerminalController { validSurfaceIds: validSurfaceIds ) guard let surfaceId, validSurfaceIds.contains(surfaceId) else { - if tab.isRemoteWorkspace, validSurfaceIds.isEmpty { - tab.rememberPendingRemoteSurfaceTTY(ttyName, requestedSurfaceId: requestedSurfaceID) - return .pending - } return .surfaceNotFound } - tab.surfaceTTYNames[surfaceId] = ttyName - if tab.isRemoteWorkspace { - tab.syncRemotePortScanTTYs() - _ = tab.applyPendingRemoteSurfacePortKickIfNeeded(to: surfaceId) + if tab.isRemoteWorkspace || + tab.surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[surfaceId] != nil || + hasRelayIdentity { + guard let relayIdentity else { return .surfaceNotFound } + guard tab.registerRelayReportedTTY( + ttyName, + panelID: surfaceId, + authenticatedWorkspaceID: relayIdentity.0, + terminalLifecycleID: relayIdentity.1, + attemptID: relayIdentity.2 + ) else { + return .surfaceNotFound + } } else { + tab.registerReportedSurfaceTTYName(ttyName, panelId: surfaceId) PortScanner.shared.registerTTY(workspaceId: workspaceID, panelId: surfaceId, ttyName: ttyName) } return .recorded(surfaceID: surfaceId) diff --git a/Sources/Workspace+DetachedSurfaceTransfer.swift b/Sources/Workspace+DetachedSurfaceTransfer.swift index 150b8f2ffa6a..1165f0209f2d 100644 --- a/Sources/Workspace+DetachedSurfaceTransfer.swift +++ b/Sources/Workspace+DetachedSurfaceTransfer.swift @@ -36,7 +36,9 @@ extension Workspace { let directory: String? let directoryIsTrustedRemoteReport: Bool let directoryDisplayLabel: String? - let ttyName: String? + var ttyName: String? + var ttyNameWasReportedByCurrentRuntime: Bool = false + var ttyReportRuntimeSurfaceGeneration: UInt64? = nil let cachedTitle: String? let customTitle: String? let customTitleSource: Workspace.CustomTitleSource? @@ -58,6 +60,7 @@ extension Workspace { var remoteTerminalLifecycleID: UUID? = nil var remoteTerminalAttemptID: UUID? = nil let remoteRelayPort: Int? + var remoteRelayNamespaceConfiguration: WorkspaceRemoteConfiguration? = nil let remotePTYSessionID: String? let remoteCleanupConfiguration: WorkspaceRemoteConfiguration? @@ -89,6 +92,8 @@ extension Workspace { directoryIsTrustedRemoteReport: directoryIsTrustedRemoteReport, directoryDisplayLabel: directoryDisplayLabel, ttyName: ttyName, + ttyNameWasReportedByCurrentRuntime: ttyNameWasReportedByCurrentRuntime, + ttyReportRuntimeSurfaceGeneration: ttyReportRuntimeSurfaceGeneration, cachedTitle: cachedTitle, customTitle: customTitle, customTitleSource: customTitleSource, @@ -108,6 +113,7 @@ extension Workspace { remoteTerminalLifecycleID: remoteTerminalLifecycleID, remoteTerminalAttemptID: remoteTerminalAttemptID, remoteRelayPort: remoteRelayPort, + remoteRelayNamespaceConfiguration: remoteRelayNamespaceConfiguration, remotePTYSessionID: remotePTYSessionID, remoteCleanupConfiguration: configuration ) diff --git a/Sources/Workspace+RemoteRelayCommandRewrite.swift b/Sources/Workspace+RemoteRelayCommandRewrite.swift index d425104f2511..b71a65060612 100644 --- a/Sources/Workspace+RemoteRelayCommandRewrite.swift +++ b/Sources/Workspace+RemoteRelayCommandRewrite.swift @@ -85,7 +85,8 @@ extension Workspace { surfaceAliases: surfaceAliases, didRewrite: &didRewrite ) as? [String: Any] ?? params - if method == "surface.resume.set", + if method == "surface.resume.set" || method == "surface.report_tty" || + method == "agent.resolve_delivery_target", let remoteWorkspaceID { params["_cmux_remote_workspace_id"] = remoteWorkspaceID.uuidString didRewrite = true diff --git a/Sources/Workspace+RemoteTerminalLiveness.swift b/Sources/Workspace+RemoteTerminalLiveness.swift index 6171de456d85..bfd71912518a 100644 --- a/Sources/Workspace+RemoteTerminalLiveness.swift +++ b/Sources/Workspace+RemoteTerminalLiveness.swift @@ -14,6 +14,11 @@ enum WorkspaceRemoteTerminalAuthority: Equatable, Sendable { case relayPort(Int) case persistentTransport(String) + var preservesRemotePTYAcrossAttachAttempts: Bool { + if case .persistentTransport = self { return true } + return false + } + init?(configuration: WorkspaceRemoteConfiguration) { if configuration.preserveAfterTerminalExit { self = .persistentTransport(configuration.proxyBrokerTransportKey) @@ -94,6 +99,10 @@ extension Workspace { if terminalLifecycleID != nil { endedRemoteTerminalLifecycleIDsBySurfaceId.removeValue(forKey: surfaceId) } + let previousState = remoteTerminalSessionStatesBySurfaceId[surfaceId] + if previousState == nil || previousState?.terminalLifecycleID != terminalLifecycleID { + invalidateReportedSurfaceTTYRuntime(panelId: surfaceId) + } remoteTerminalSessionStatesBySurfaceId[surfaceId] = WorkspaceRemoteTerminalSessionState( phase: .launching, authority: authority, @@ -113,6 +122,13 @@ extension Workspace { return false } endedRemoteTerminalLifecycleIDsBySurfaceId.removeValue(forKey: surfaceId) + if remoteTerminalAttemptIDsBySurfaceId[surfaceId] != attemptID, + (activeRemoteTerminalSurfaceIds.contains(surfaceId) + ? remoteConfiguration + : transferredRemoteCleanupConfigurationsByPanelId[surfaceId])? + .preserveAfterTerminalExit != true { + invalidateReportedSurfaceTTYRuntime(panelId: surfaceId) + } remoteTerminalAttemptIDsBySurfaceId[surfaceId] = attemptID markRemoteTerminalSessionLaunching(surfaceId: surfaceId) applyRemoteTerminalLaunchingPresentation() @@ -438,11 +454,20 @@ extension Workspace { } func clearRemoteTerminalSessionPhase(surfaceId: UUID) { + invalidateReportedSurfaceTTYRuntime(panelId: surfaceId) + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs.removeValue(forKey: surfaceId) remoteTerminalSessionStatesBySurfaceId.removeValue(forKey: surfaceId) pendingRemoteTerminalConnectionsBySurfaceId.removeValue(forKey: surfaceId) remoteTerminalAttemptIDsBySurfaceId.removeValue(forKey: surfaceId) } + func clearActiveRemoteTerminalSessionPhases() { + for surfaceId in activeRemoteTerminalSurfaceIds { + clearRemoteTerminalSessionPhase(surfaceId: surfaceId) + } + activeRemoteTerminalSurfaceIds.removeAll() + } + func restoreRemoteTerminalSessionPhase( _ phase: WorkspaceRemoteTerminalSessionPhase?, authority: WorkspaceRemoteTerminalAuthority?, diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 2d6399e91330..85f5eb8334e7 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -1879,9 +1879,9 @@ extension Workspace { surfaceListeningPorts[panelId] = Array(Set(snapshot.listeningPorts)).sorted() if let ttyName = snapshot.ttyName?.trimmingCharacters(in: .whitespacesAndNewlines), !ttyName.isEmpty { - surfaceTTYNames[panelId] = ttyName + restorePersistedSurfaceTTYName(ttyName, panelId: panelId) } else { - surfaceTTYNames.removeValue(forKey: panelId) + restorePersistedSurfaceTTYName(nil, panelId: panelId) } syncRemotePortScanTTYs() @@ -5330,6 +5330,10 @@ final class Workspace: Identifiable, ObservableObject { manualUnreadMarkedAt = manualUnreadMarkedAt.filter { validSurfaceIds.contains($0.key) } surfaceListeningPorts = surfaceListeningPorts.filter { validSurfaceIds.contains($0.key) } surfaceTTYNames = surfaceTTYNames.filter { validSurfaceIds.contains($0.key) } + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs = + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs.filter { + validSurfaceIds.contains($0.key) + } restoredGuardedWorkingDirectoriesByPanelId = restoredGuardedWorkingDirectoriesByPanelId.filter { validSurfaceIds.contains($0.key) } @@ -5924,7 +5928,7 @@ final class Workspace: Identifiable, ObservableObject { ) cancelPendingRemoteControlMasterAdoption() remoteDisconnectPlaceholderPanelIds.formUnion(activeRemoteTerminalSurfaceIds) - activeRemoteTerminalSurfaceIds.removeAll() + clearActiveRemoteTerminalSessionPhases() remoteTerminalSessionStatesBySurfaceId.removeAll() pendingRemoteTerminalConnectionsBySurfaceId.removeAll() remoteTerminalAttemptIDsBySurfaceId.removeAll() @@ -6006,6 +6010,7 @@ final class Workspace: Identifiable, ObservableObject { } func trackRemoteTerminalSurface(_ panelId: UUID, preserveTrustedRemoteDirectory: Bool = false) { + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[panelId] = id let previousPresentedDirectory = presentedCurrentDirectory let existingDirectory = panelDirectories[panelId]?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" let removedTrustedDirectory: Bool @@ -6517,7 +6522,7 @@ final class Workspace: Identifiable, ObservableObject { if let requestedSurfaceId = pendingRemoteSurfaceTTYSurfaceId, requestedSurfaceId != panelId { return } - surfaceTTYNames[panelId] = ttyName + registerReportedSurfaceTTYName(ttyName, panelId: panelId) pendingRemoteSurfaceTTYName = nil pendingRemoteSurfaceTTYSurfaceId = nil syncRemotePortScanTTYs() @@ -6567,7 +6572,7 @@ final class Workspace: Identifiable, ObservableObject { return } - surfaceTTYNames[candidateSurfaceId] = trimmedTTY + registerReportedSurfaceTTYName(trimmedTTY, panelId: candidateSurfaceId) syncRemotePortScanTTYs() if !applyPendingRemoteSurfacePortKickIfNeeded(to: candidateSurfaceId) { kickRemotePortScan(panelId: candidateSurfaceId, reason: .command) @@ -6690,6 +6695,8 @@ final class Workspace: Identifiable, ObservableObject { endedPendingConnection = nil } if cleanupTransferredRemoteConnectionIfNeeded(surfaceId: surfaceId, relayPort: relayPort) { + invalidateReportedSurfaceTTYRuntime(panelId: surfaceId) + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs.removeValue(forKey: surfaceId) return true } guard let configuration = remoteConfiguration, @@ -6699,8 +6706,14 @@ final class Workspace: Identifiable, ObservableObject { configuration: configuration, allowUntracked: allowUntracked ) else { - return endedPendingConnection != nil || recordedLifecycleTombstone + let didEnd = endedPendingConnection != nil || recordedLifecycleTombstone + if didEnd { + invalidateReportedSurfaceTTYRuntime(panelId: surfaceId) + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs.removeValue(forKey: surfaceId) + } + return didEnd } + invalidateReportedSurfaceTTYRuntime(panelId: surfaceId) let preservesRemotePTYSession = configuration.preserveAfterTerminalExit let previousPresentedDirectory = presentedCurrentDirectory if !preservesRemotePTYSession { @@ -9620,11 +9633,7 @@ final class Workspace: Identifiable, ObservableObject { } else { panelDirectoryDisplayLabels.removeValue(forKey: detached.panelId) } - if let ttyName = detached.ttyName?.trimmingCharacters(in: .whitespacesAndNewlines), !ttyName.isEmpty { - surfaceTTYNames[detached.panelId] = ttyName - } else { - surfaceTTYNames.removeValue(forKey: detached.panelId) - } + adoptTransferredSurfaceTTYName(from: detached) syncRemotePortScanTTYs() if let cachedTitle = detached.cachedTitle { panelTitles[detached.panelId] = cachedTitle @@ -9804,6 +9813,14 @@ final class Workspace: Identifiable, ObservableObject { ) } } + if detached.isRemoteTerminal, detached.remoteTerminalSessionPhase != .ended { + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[detached.panelId] = + didAdoptWorkspaceRemoteTracking ? id : detached.sessionRestoreWorkspaceId + } else { + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs.removeValue(forKey: detached.panelId) + } + restoreTransferredRelayTTYIdentity(from: detached) + restoreTransferredSurfaceTTYRuntimeProofIfNeeded(from: detached) if let cleanupConfiguration = detached.remoteCleanupConfiguration { if didAdoptWorkspaceRemoteTracking { transferredRemoteCleanupConfigurationsByPanelId.removeValue(forKey: detached.panelId) @@ -9844,13 +9861,11 @@ final class Workspace: Identifiable, ObservableObject { private func shouldAdoptDetachedWorkspaceRemoteTracking(_ detached: DetachedSurfaceTransfer) -> Bool { guard detached.isRemoteTerminal, detached.remoteTerminalSessionPhase != .ended else { return false } if detached.sourceWorkspaceId == id { return true } - guard let detachedRelayPort = detached.remoteRelayPort, - detachedRelayPort > 0, - let currentRelayPort = remoteConfiguration?.relayPort, - currentRelayPort > 0 else { + guard let destinationConfiguration = remoteConfiguration, + let originConfiguration = detached.remoteRelayNamespaceConfiguration else { return false } - return detachedRelayPort == currentRelayPort + return destinationConfiguration.hasSameRemoteRelayNamespace(as: originConfiguration) } // MARK: - Focus Management @@ -12475,9 +12490,16 @@ extension Workspace: BonsplitDelegate { ) let agentRuntime = agentRuntimeState(forPanelId: panelId) let panelDirectory = panelDirectories[panelId] + let remoteTTYReportOriginWorkspaceID = + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[panelId] + let isRemoteTerminal = activeRemoteTerminalSurfaceIds.contains(panelId) + || remoteTTYReportOriginWorkspaceID != nil + let remoteRelayNamespaceConfiguration = activeRemoteTerminalSurfaceIds.contains(panelId) + ? remoteConfiguration + : transferredRemoteCleanupConfiguration splitLayout.storeDetachedTransfer(DetachedSurfaceTransfer( sourceWorkspaceId: id, - sessionRestoreSourceWorkspaceId: id, + sessionRestoreSourceWorkspaceId: remoteTTYReportOriginWorkspaceID ?? id, panelId: panelId, panel: panel, title: resolvedPanelTitle(panelId: panelId, fallback: transferFallbackTitle), @@ -12490,6 +12512,9 @@ extension Workspace: BonsplitDelegate { directoryIsTrustedRemoteReport: panelDirectory != nil && remoteDirectoryReportPanelIds.contains(panelId), directoryDisplayLabel: panelDirectoryDisplayLabels[panelId], ttyName: surfaceTTYNames[panelId], + ttyNameWasReportedByCurrentRuntime: surfaceRegistry.runtimeReportedTTYSurfaceIDs.contains(panelId), + ttyReportRuntimeSurfaceGeneration: + surfaceRegistry.runtimeReportedTTYSurfaceGenerations[panelId], cachedTitle: cachedTitle, customTitle: panelCustomTitles[panelId], customTitleSource: panelCustomTitles[panelId] != nil @@ -12507,15 +12532,14 @@ extension Workspace: BonsplitDelegate { $0.hasCompleteManagedSessionIdentity ? $0 : nil }, agentRuntime: agentRuntime, - isRemoteTerminal: activeRemoteTerminalSurfaceIds.contains(panelId), + isRemoteTerminal: isRemoteTerminal, remoteTerminalSessionPhase: remoteTerminalSessionStatesBySurfaceId[panelId]?.phase, remoteTerminalAuthority: remoteTerminalSessionStatesBySurfaceId[panelId]?.authority, remoteTerminalLifecycleID: remoteTerminalSessionStatesBySurfaceId[panelId]? .terminalLifecycleID, remoteTerminalAttemptID: remoteTerminalAttemptIDsBySurfaceId[panelId], - remoteRelayPort: activeRemoteTerminalSurfaceIds.contains(panelId) - ? remoteConfiguration?.relayPort - : nil, + remoteRelayPort: remoteRelayNamespaceConfiguration?.relayPort, + remoteRelayNamespaceConfiguration: remoteRelayNamespaceConfiguration, remotePTYSessionID: remotePTYSessionIDForSnapshot(panelId: panelId), remoteCleanupConfiguration: transferredRemoteCleanupConfiguration ), for: tabId) diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 6e7386cb79d4..385bea103c40 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -45,6 +45,7 @@ ACA7C4A7000000000000000B /* AgentChatTranscriptService.swift in Sources */ = {isa = PBXBuildFile; fileRef = ACA7C4A7000000000000000C /* AgentChatTranscriptService.swift */; }; ACA7C4A70000000000000009 /* AgentChatTranscriptTailer.swift in Sources */ = {isa = PBXBuildFile; fileRef = ACA7C4A7000000000000000A /* AgentChatTranscriptTailer.swift */; }; 79390005AA11BB22CC33DD05 /* AgentDeliveryTargetResolution.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79390006AA11BB22CC33DD06 /* AgentDeliveryTargetResolution.swift */; }; + 93800001AA11BB22CC33EE01 /* AgentDeliveryTTYBindingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93800002AA11BB22CC33EE02 /* AgentDeliveryTTYBindingTests.swift */; }; A9F200000000000000000001 /* AgentExecutableResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9F100000000000000000001 /* AgentExecutableResolver.swift */; }; A9F200000000000000000002 /* AgentExecutableResolverError.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9F100000000000000000002 /* AgentExecutableResolverError.swift */; }; A9E020000000000000000005 /* AgentExecutableResolverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9E010000000000000000005 /* AgentExecutableResolverTests.swift */; }; @@ -132,6 +133,8 @@ 89930002AABBCCDDEEFF0001 /* AgentProcessBindingResolution.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89930002AABBCCDDEEFF0003 /* AgentProcessBindingResolution.swift */; }; 89930002AABBCCDDEEFF0002 /* AgentProcessBindingResolution.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89930002AABBCCDDEEFF0003 /* AgentProcessBindingResolution.swift */; }; 0A1107110000000000000012 /* AgentRelaunchCommandBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A1107110000000000000013 /* AgentRelaunchCommandBuilder.swift */; }; + 93840005AA11BB22CC33EE05 /* AgentRelayTTYOwnershipTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93840006AA11BB22CC33EE06 /* AgentRelayTTYOwnershipTests.swift */; }; + 93840003AA11BB22CC33EE03 /* AgentRelayTTYTargetResolution.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93840004AA11BB22CC33EE04 /* AgentRelayTTYTargetResolution.swift */; }; 0A1107110000000000000014 /* AgentRestoreMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A1107110000000000000015 /* AgentRestoreMode.swift */; }; D8DFFAEC2DBC3ACCF87D563E /* AgentResumeLaunchGuard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5977EB347EF8D7692B3759E2 /* AgentResumeLaunchGuard.swift */; }; E8DF7FD45DA2E55E4DA65B38 /* AgentResumeLaunchGuardTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21EBB654187F880170B92ED9 /* AgentResumeLaunchGuardTests.swift */; }; @@ -2715,6 +2718,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources ACA7C4A7000000000000000C /* AgentChatTranscriptService.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptService.swift"; sourceTree = ""; }; ACA7C4A7000000000000000A /* AgentChatTranscriptTailer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptTailer.swift"; sourceTree = ""; }; 79390006AA11BB22CC33DD06 /* AgentDeliveryTargetResolution.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentDeliveryTargetResolution.swift; sourceTree = ""; }; + 93800002AA11BB22CC33EE02 /* AgentDeliveryTTYBindingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentDeliveryTTYBindingTests.swift; sourceTree = ""; }; A9F100000000000000000001 /* AgentExecutableResolver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentExecutableResolver.swift; sourceTree = ""; }; A9F100000000000000000002 /* AgentExecutableResolverError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentExecutableResolverError.swift; sourceTree = ""; }; A9E010000000000000000005 /* AgentExecutableResolverTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentExecutableResolverTests.swift; sourceTree = ""; }; @@ -2799,6 +2803,8 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources B79500110000000000000002 /* AgentPortTrackingState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentPortTrackingState.swift; sourceTree = ""; }; 89930002AABBCCDDEEFF0003 /* AgentProcessBindingResolution.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentProcessBindingResolution.swift; sourceTree = ""; }; 0A1107110000000000000013 /* AgentRelaunchCommandBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentRelaunchCommandBuilder.swift; sourceTree = ""; }; + 93840006AA11BB22CC33EE06 /* AgentRelayTTYOwnershipTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentRelayTTYOwnershipTests.swift; sourceTree = ""; }; + 93840004AA11BB22CC33EE04 /* AgentRelayTTYTargetResolution.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentRelayTTYTargetResolution.swift; sourceTree = ""; }; 0A1107110000000000000015 /* AgentRestoreMode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentRestoreMode.swift; sourceTree = ""; }; 5977EB347EF8D7692B3759E2 /* AgentResumeLaunchGuard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentResumeLaunchGuard.swift; sourceTree = ""; }; 21EBB654187F880170B92ED9 /* AgentResumeLaunchGuardTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentResumeLaunchGuardTests.swift; sourceTree = ""; }; @@ -6505,6 +6511,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = F1A0C0DE0000000000000001 /* FindTextFieldSupport.swift */, A5A5A502A1B2C3D4E5F60718 /* TerminalNotificationQueue.swift */, 79390006AA11BB22CC33DD06 /* AgentDeliveryTargetResolution.swift */, + 93840004AA11BB22CC33EE04 /* AgentRelayTTYTargetResolution.swift */, 89930002AABBCCDDEEFF0003 /* AgentProcessBindingResolution.swift */, 8362A0020000000000000002 /* TerminalCallerTTYResolver.swift */, 8362A0040000000000000004 /* TerminalCallerTTYBinding.swift */, @@ -7810,6 +7817,8 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 79390004AA11BB22CC33DD04 /* AgentNotificationLiveRetargetTests.swift */, 79390010AA11BB22CC33DD10 /* AgentNotificationMoveRaceTests.swift */, 79460002AA11BB22CC33EE02 /* AgentNotificationMutationBoundaryTests.swift */, + 93800002AA11BB22CC33EE02 /* AgentDeliveryTTYBindingTests.swift */, + 93840006AA11BB22CC33EE06 /* AgentRelayTTYOwnershipTests.swift */, 79390012AA11BB22CC33DD12 /* ClaudeHookPIDAuthenticationTests.swift */, C7A534000000000000000001 /* ClaudeHookFeedTelemetrySwiftTests.swift */, A5D41223A1B2C3D4E5F60718 /* ClaudeNotificationStatusLifecycleTests.swift */, @@ -8476,6 +8485,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B79500110000000000000001 /* AgentPortTrackingState.swift in Sources */, 89930002AABBCCDDEEFF0001 /* AgentProcessBindingResolution.swift in Sources */, 0A1107110000000000000012 /* AgentRelaunchCommandBuilder.swift in Sources */, + 93840003AA11BB22CC33EE03 /* AgentRelayTTYTargetResolution.swift in Sources */, 0A1107110000000000000014 /* AgentRestoreMode.swift in Sources */, D8DFFAEC2DBC3ACCF87D563E /* AgentResumeLaunchGuard.swift in Sources */, CC2D14DFE13EFF544A25BEAF /* AgentResumeLiveness.swift in Sources */, @@ -10260,6 +10270,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C7A51E000000000000000002 /* AgentChatSessionRegistryLifecycleTests.swift in Sources */, C7A51D100000000000000002 /* AgentChatSessionRegistryObservationReviewRegressionTests.swift in Sources */, C7A51D000000000000000002 /* AgentChatSessionRegistryObservationTests.swift in Sources */, + 93800001AA11BB22CC33EE01 /* AgentDeliveryTTYBindingTests.swift in Sources */, A9E020000000000000000005 /* AgentExecutableResolverTests.swift in Sources */, 8740E0018740E0018740E001 /* AgentHibernationEvaluationSchedulingTests.swift in Sources */, 9090E0039090E0039090E003 /* AgentHibernationPanelCloseCleanupTests.swift in Sources */, @@ -10282,6 +10293,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 79390003AA11BB22CC33DD03 /* AgentNotificationLiveRetargetTests.swift in Sources */, 7939000FAA11BB22CC33DD0F /* AgentNotificationMoveRaceTests.swift in Sources */, 79460001AA11BB22CC33EE01 /* AgentNotificationMutationBoundaryTests.swift in Sources */, + 93840005AA11BB22CC33EE05 /* AgentRelayTTYOwnershipTests.swift in Sources */, E8DF7FD45DA2E55E4DA65B38 /* AgentResumeLaunchGuardTests.swift in Sources */, B679CCBA4CF56982C8564009 /* AgentResumeLivenessTests.swift in Sources */, 8837A0010000000000000001 /* AgentResumeReturnShellStartupTests.swift in Sources */, diff --git a/cmuxTests/AgentDeliveryTTYBindingTests.swift b/cmuxTests/AgentDeliveryTTYBindingTests.swift new file mode 100644 index 000000000000..33851a5e90cf --- /dev/null +++ b/cmuxTests/AgentDeliveryTTYBindingTests.swift @@ -0,0 +1,481 @@ +import AppKit +import CmuxCore +import Foundation +import Testing +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +extension AgentNotificationRegressionTests { + @Test("Local PID bindings use the live Ghostty TTY without a shell report") + func localTTYBindingsUseLiveGhosttyTTYWithoutShellReport() async throws { + let fixture = try makeFixture() + defer { fixture.restore() } + let terminal = try #require(fixture.source.panels[fixture.panelId] as? TerminalPanel) + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 640, height: 480), + styleMask: [.borderless], + backing: .buffered, + defer: false + ) + let contentView = try #require(window.contentView) + let hostedView = terminal.hostedView + hostedView.frame = contentView.bounds + hostedView.autoresizingMask = [.width, .height] + contentView.addSubview(hostedView) + window.orderFront(nil) + window.displayIfNeeded() + defer { + hostedView.removeFromSuperview() + window.orderOut(nil) + } + let liveTTYName = try #require(await waitForControllingTTYName(for: terminal)) + let liveTTYDevice = try #require( + CmuxTopProcessSnapshot.deviceIdentifier(forTTYName: liveTTYName) + ) + + fixture.source.restorePersistedSurfaceTTYName(nil, panelId: fixture.panelId) + + #expect(fixture.source.surfaceTTYNames[fixture.panelId] == nil) + #expect( + fixture.source.localAgentDeliveryTTYDevices.contains { + $0.surfaceId == fixture.panelId && $0.ttyDevice == liveTTYDevice + }, + "A live terminal must remain PID-routable when shell integration is disabled" + ) + } + + @Test("Generic TTY metadata changes do not become runtime reports") + func genericTTYMetadataDoesNotBecomeRuntimeReport() throws { + let workspace = Workspace() + let panelID = try #require(workspace.focusedPanelId) + workspace.remoteConfiguration = deliveryTargetRemoteConfiguration() + workspace.trackRemoteTerminalSurface(panelID) + workspace.registerReportedSurfaceTTYName("pts/0", panelId: panelID) + #expect(workspace.agentDeliveryTarget(forReportedTTYName: "pts/0") != nil) + + workspace.surfaceTTYNames[panelID] = "pts/1" + + #expect( + workspace.agentDeliveryTarget(forReportedTTYName: "pts/1") == nil, + "Only an explicit report_tty call may establish runtime provenance" + ) + } + + @Test("Relay TTY resolution follows a freshly reported surface into a Dock") + func relayTTYResolutionFollowsFreshReportIntoDock() throws { + let fixture = try makeFixture() + let dock = DockSplitStore(workspaceId: UUID(), baseDirectoryProvider: { nil }) + defer { + dock.closeAllPanels() + fixture.restore() + } + fixture.source.remoteConfiguration = deliveryTargetRemoteConfiguration() + let terminal = try #require(fixture.source.panels[fixture.panelId] as? TerminalPanel) + let attemptID = UUID() + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + #expect(fixture.source.markRemoteTerminalSessionLaunching( + surfaceId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID + )) + #expect( + TerminalController.shared.controlSurfaceReportTTY( + workspaceID: fixture.source.id, + requestedSurfaceID: fixture.panelId, + ttyName: "pts/2", + authenticatedRemoteWorkspaceID: fixture.source.id, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID + ) == .recorded(surfaceID: fixture.panelId) + ) + + try moveRemoteSurface(fixture, into: dock) + + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/2", + expectedWorkspaceID: dock.workspaceId, + expectedSurfaceID: fixture.panelId + ) + } + + @Test("Relay TTY resolution follows a freshly reported surface into another workspace") + func relayTTYResolutionFollowsFreshReportIntoWorkspace() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + let configuration = deliveryTargetRemoteConfiguration(relayPort: 64_007) + fixture.source.remoteConfiguration = configuration + fixture.destination.remoteConfiguration = configuration + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + fixture.source.registerReportedSurfaceTTYName("pts/4", panelId: fixture.panelId) + + try movePanel(fixture) + + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.destination.id, + ttyName: "pts/4", + expectedWorkspaceID: fixture.destination.id, + expectedSurfaceID: fixture.panelId + ) + } + + @Test("Relay TTY resolution follows a surface into a newly created ordinary workspace") + func relayTTYResolutionFollowsSurfaceIntoNewOrdinaryWorkspace() throws { + let fixture = try makeFixture() + var destinationWorkspaceID: UUID? + defer { + if let destinationWorkspaceID, + let destination = fixture.manager.tabs.first(where: { $0.id == destinationWorkspaceID }) { + fixture.manager.closeWorkspace(destination) + } + fixture.restore() + } + fixture.source.remoteConfiguration = deliveryTargetRemoteConfiguration(relayPort: 64_007) + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + fixture.source.registerReportedSurfaceTTYName("pts/7", panelId: fixture.panelId) + let paneID = try #require(fixture.source.bonsplitController.allPaneIds.first) + _ = try #require(fixture.source.newTerminalSurface(inPane: paneID, focus: false)) + + let move = try #require(fixture.appDelegate.moveSurfaceToNewWorkspace( + panelId: fixture.panelId, + focus: false, + focusWindow: false + )) + destinationWorkspaceID = move.destinationWorkspaceId + let destination = try #require( + fixture.manager.tabs.first(where: { $0.id == move.destinationWorkspaceId }) + ) + #expect(!destination.isRemoteWorkspace) + + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/7", + expectedWorkspaceID: destination.id, + expectedSurfaceID: fixture.panelId + ) + } + + @Test("A runtime TTY report refreshes a remote surface already in a Dock") + func runtimeTTYReportRefreshesRemoteSurfaceAlreadyInDock() throws { + let fixture = try makeFixture() + let dock = DockSplitStore(workspaceId: UUID(), baseDirectoryProvider: { nil }) + defer { + dock.closeAllPanels() + fixture.restore() + } + fixture.source.remoteConfiguration = deliveryTargetRemoteConfiguration() + let terminal = try #require(fixture.source.panels[fixture.panelId] as? TerminalPanel) + let attemptID = UUID() + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + #expect(fixture.source.markRemoteTerminalSessionLaunching( + surfaceId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID + )) + try moveRemoteSurface(fixture, into: dock) + + #expect( + TerminalController.shared.controlSurfaceReportTTY( + workspaceID: fixture.source.id, + requestedSurfaceID: fixture.panelId, + ttyName: "pts/3", + authenticatedRemoteWorkspaceID: fixture.source.id, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID + ) == .recorded(surfaceID: fixture.panelId) + ) + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/3", + expectedWorkspaceID: dock.workspaceId, + expectedSurfaceID: fixture.panelId + ) + } + + @Test("An ended workspace remote terminal cannot resolve a reused TTY") + func endedWorkspaceRemoteTerminalDoesNotResolveReportedTTY() throws { + let workspace = Workspace() + let panelID = try #require(workspace.focusedPanelId) + workspace.remoteConfiguration = deliveryTargetRemoteConfiguration(relayPort: 64_007) + workspace.trackRemoteTerminalSurface(panelID) + workspace.registerReportedSurfaceTTYName("pts/0", panelId: panelID) + #expect(workspace.agentDeliveryTarget(forReportedTTYName: "pts/0") != nil) + + #expect( + workspace.markRemoteTerminalSessionEnded( + surfaceId: panelID, + relayPort: 64_007 + ) + ) + + #expect( + workspace.agentDeliveryTarget(forReportedTTYName: "pts/0") == nil, + "A TTY report from an ended lifecycle must not identify a future remote process" + ) + } + + @Test("An ended Dock remote terminal cannot resolve a reused TTY") + func endedDockRemoteTerminalDoesNotResolveReportedTTY() throws { + let fixture = try makeFixture() + let dock = DockSplitStore(workspaceId: UUID(), baseDirectoryProvider: { nil }) + defer { + dock.closeAllPanels() + fixture.restore() + } + fixture.source.remoteConfiguration = deliveryTargetRemoteConfiguration(relayPort: 64_007) + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + fixture.source.registerReportedSurfaceTTYName("pts/0", panelId: fixture.panelId) + try moveRemoteSurface(fixture, into: dock) + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/0", + expectedWorkspaceID: dock.workspaceId, + expectedSurfaceID: fixture.panelId + ) + + #expect( + dock.markRemoteTerminalSessionEnded( + panelId: fixture.panelId, + relayPort: 64_007 + ) + ) + + assertNoRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/0" + ) + } + + @Test("A workspace reconnect invalidates the previous attempt's TTY report") + func workspaceReconnectInvalidatesReportedTTY() throws { + let workspace = Workspace() + let panelID = try #require(workspace.focusedPanelId) + let terminal = try #require(workspace.panels[panelID] as? TerminalPanel) + workspace.remoteConfiguration = deliveryTargetRemoteConfiguration() + workspace.trackRemoteTerminalSurface(panelID) + #expect( + workspace.markRemoteTerminalSessionLaunching( + surfaceId: panelID, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + workspace.registerReportedSurfaceTTYName("pts/0", panelId: panelID) + #expect(workspace.agentDeliveryTarget(forReportedTTYName: "pts/0") != nil) + + #expect( + workspace.markRemoteTerminalSessionLaunching( + surfaceId: panelID, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + + #expect( + workspace.agentDeliveryTarget(forReportedTTYName: "pts/0") == nil, + "A new attach attempt must wait for its own report_tty before becoming routable" + ) + } + + @Test("A persistent workspace bridge retry preserves the remote PTY's TTY report") + func persistentWorkspaceRetryPreservesReportedTTY() throws { + let workspace = Workspace() + let panelID = try #require(workspace.focusedPanelId) + let terminal = try #require(workspace.panels[panelID] as? TerminalPanel) + workspace.remoteConfiguration = deliveryTargetRemoteConfiguration( + preserveAfterTerminalExit: true + ) + workspace.trackRemoteTerminalSurface(panelID) + #expect( + workspace.markRemoteTerminalSessionLaunching( + surfaceId: panelID, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + workspace.registerReportedSurfaceTTYName("pts/5", panelId: panelID) + + #expect( + workspace.markRemoteTerminalSessionLaunching( + surfaceId: panelID, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + + #expect( + workspace.agentDeliveryTarget(forReportedTTYName: "pts/5") != nil, + "A bridge retry for the same persistent PTY must keep its report-once shell proof" + ) + } + + @Test("A Dock reconnect invalidates the previous attempt's TTY report") + func dockReconnectInvalidatesReportedTTY() throws { + let fixture = try makeFixture() + let dock = DockSplitStore(workspaceId: UUID(), baseDirectoryProvider: { nil }) + defer { + dock.closeAllPanels() + fixture.restore() + } + let terminal = try #require(fixture.source.panels[fixture.panelId] as? TerminalPanel) + fixture.source.remoteConfiguration = deliveryTargetRemoteConfiguration() + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + fixture.source.registerReportedSurfaceTTYName("pts/0", panelId: fixture.panelId) + try moveRemoteSurface(fixture, into: dock) + let attemptID = UUID() + #expect( + dock.markRemoteTerminalSessionLaunching( + panelId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID + ) + ) + #expect( + TerminalController.shared.controlSurfaceReportTTY( + workspaceID: fixture.source.id, + requestedSurfaceID: fixture.panelId, + ttyName: "pts/0", + authenticatedRemoteWorkspaceID: fixture.source.id, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID + ) == .recorded(surfaceID: fixture.panelId) + ) + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/0", + expectedWorkspaceID: dock.workspaceId, + expectedSurfaceID: fixture.panelId + ) + + #expect( + dock.markRemoteTerminalSessionLaunching( + panelId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + + assertNoRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/0" + ) + } + + @Test("A persistent Dock bridge retry preserves the remote PTY's TTY report") + func persistentDockRetryPreservesReportedTTY() throws { + let fixture = try makeFixture() + let dock = DockSplitStore(workspaceId: UUID(), baseDirectoryProvider: { nil }) + defer { + dock.closeAllPanels() + fixture.restore() + } + let terminal = try #require(fixture.source.panels[fixture.panelId] as? TerminalPanel) + fixture.source.remoteConfiguration = deliveryTargetRemoteConfiguration( + preserveAfterTerminalExit: true + ) + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + #expect( + fixture.source.markRemoteTerminalSessionLaunching( + surfaceId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + fixture.source.registerReportedSurfaceTTYName("pts/6", panelId: fixture.panelId) + try moveRemoteSurface(fixture, into: dock) + + #expect( + dock.markRemoteTerminalSessionLaunching( + panelId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/6", + expectedWorkspaceID: dock.workspaceId, + expectedSurfaceID: fixture.panelId + ) + } + + private func moveRemoteSurface(_ fixture: Fixture, into dock: DockSplitStore) throws { + let transfer = try #require(fixture.source.detachSurface(panelId: fixture.panelId)) + let rootPane = try #require(dock.bonsplitController.allPaneIds.first) + #expect( + dock.attachDetachedSurface(transfer, inPane: rootPane, focus: false) + == fixture.panelId + ) + } + + private func waitForControllingTTYName(for terminal: TerminalPanel) async -> String? { + let deadline = ContinuousClock.now + .seconds(15) + while ContinuousClock.now < deadline { + if let ttyName = terminal.surface.controllingTTYName() { + return ttyName + } + try? await Task.sleep(for: .milliseconds(10)) + } + return terminal.surface.controllingTTYName() + } + + private func assertRelayTTYTarget( + authenticatedWorkspaceID: UUID, + ttyName: String, + expectedWorkspaceID: UUID, + expectedSurfaceID: UUID + ) { + let result = TerminalController.shared.v2AgentResolveDeliveryTarget(params: [ + "tty_name": ttyName, + "tty_resolution": "reported_tty", + "_cmux_remote_workspace_id": authenticatedWorkspaceID.uuidString, + ]) + guard case .ok(let payload) = result, + let target = payload as? [String: Any] else { + Issue.record("Expected authenticated relay TTY resolution, got \(result)") + return + } + #expect(target["workspace_id"] as? String == expectedWorkspaceID.uuidString) + #expect(target["surface_id"] as? String == expectedSurfaceID.uuidString) + } + + private func assertNoRelayTTYTarget( + authenticatedWorkspaceID: UUID, + ttyName: String + ) { + let result = TerminalController.shared.v2AgentResolveDeliveryTarget(params: [ + "tty_name": ttyName, + "tty_resolution": "reported_tty", + "_cmux_remote_workspace_id": authenticatedWorkspaceID.uuidString, + ]) + guard case .err(let code, _, _) = result else { + Issue.record("Expected ended relay TTY resolution to fail, got \(result)") + return + } + #expect(code == "not_found") + } + + private func deliveryTargetRemoteConfiguration( + relayPort: Int? = nil, + preserveAfterTerminalExit: Bool = false + ) -> WorkspaceRemoteConfiguration { + WorkspaceRemoteConfiguration( + destination: "example.invalid", + port: nil, + identityFile: nil, + sshOptions: [], + localProxyPort: nil, + relayPort: relayPort, + relayID: nil, + relayToken: nil, + localSocketPath: nil, + terminalStartupCommand: nil, + preserveAfterTerminalExit: preserveAfterTerminalExit, + persistentDaemonSlot: preserveAfterTerminalExit ? "delivery-target-test" : nil + ) + } +} diff --git a/cmuxTests/AgentNotificationLiveRetargetTests.swift b/cmuxTests/AgentNotificationLiveRetargetTests.swift index 20eaccd152f6..288d4b29460f 100644 --- a/cmuxTests/AgentNotificationLiveRetargetTests.swift +++ b/cmuxTests/AgentNotificationLiveRetargetTests.swift @@ -1,5 +1,6 @@ import AppKit import CmuxControlSocket +import CmuxCore import Testing #if canImport(cmux_DEV) @testable import cmux_DEV @@ -175,6 +176,48 @@ extension AgentNotificationRegressionTests { #expect(code == "invalid_params") } + @Test + func testRelayTTYResolutionStaysInsideAuthenticatedWorkspace() throws { + let fixture = try makeLiveRetargetFixture() + defer { fixture.restore() } + + let remoteConfiguration = WorkspaceRemoteConfiguration( + destination: "example.invalid", + port: nil, + identityFile: nil, + sshOptions: [], + localProxyPort: nil, + relayPort: nil, + relayID: nil, + relayToken: nil, + localSocketPath: nil, + terminalStartupCommand: nil + ) + fixture.claimedWorkspace.remoteConfiguration = remoteConfiguration + fixture.owningWorkspace.remoteConfiguration = remoteConfiguration + let siblingPanelID = try #require(fixture.claimedWorkspace.focusedPanelId) + fixture.claimedWorkspace.trackRemoteTerminalSurface(siblingPanelID) + fixture.owningWorkspace.trackRemoteTerminalSurface(fixture.panelId) + fixture.claimedWorkspace.registerReportedSurfaceTTYName("0", panelId: siblingPanelID) + fixture.owningWorkspace.registerReportedSurfaceTTYName("0", panelId: fixture.panelId) + + let result = TerminalController.shared.v2AgentResolveDeliveryTarget(params: [ + "tty_name": "0", + "tty_resolution": "reported_tty", + "workspace_id": fixture.claimedWorkspace.id.uuidString, + "_cmux_remote_workspace_id": fixture.owningWorkspace.id.uuidString, + ]) + guard case .ok(let payload) = result, + let target = payload as? [String: Any] else { + Issue.record("Expected authenticated relay TTY resolution, got \(result)") + return + } + #expect(target["source"] as? String == "tty") + #expect(target["tty_resolution"] as? String == "reported_tty") + #expect(target["workspace_id"] as? String == fixture.owningWorkspace.id.uuidString) + #expect(target["surface_id"] as? String == fixture.panelId.uuidString) + } + @Test func testSurfaceScopedClearDiscardsStaleKeyedPendingNotification() throws { let fixture = try makeLiveRetargetFixture() @@ -464,7 +507,7 @@ extension AgentNotificationRegressionTests { @Test func testTTYDeviceMatchRequiresUniqueSurface() throws { let workspace = Workspace(), panel = try #require(workspace.focusedPanelId) - workspace.surfaceTTYNames[panel] = "/dev/null" + workspace.registerReportedSurfaceTTYName("/dev/null", panelId: panel) #expect(workspace.surfaceTTYDevices[panel] == CmuxTopProcessSnapshot.deviceIdentifier(forTTYName: "/dev/null")) let w1 = UUID(), s1 = UUID(), w2 = UUID(), s2 = UUID() let bindings: [(workspaceId: UUID, surfaceId: UUID, ttyDevice: Int64)] = [ diff --git a/cmuxTests/AgentNotificationMutationBoundaryTests.swift b/cmuxTests/AgentNotificationMutationBoundaryTests.swift index c72910c96652..de307e367dcf 100644 --- a/cmuxTests/AgentNotificationMutationBoundaryTests.swift +++ b/cmuxTests/AgentNotificationMutationBoundaryTests.swift @@ -87,7 +87,7 @@ extension AgentNotificationRegressionTests { func localTTYBindingsExcludeRemoteDeviceNamespaces() throws { let workspace = Workspace() let panelId = try #require(workspace.focusedPanelId) - workspace.surfaceTTYNames[panelId] = "/dev/null" + workspace.registerReportedSurfaceTTYName("/dev/null", panelId: panelId) #expect(workspace.localAgentDeliveryTTYDevices.map(\.surfaceId) == [panelId]) workspace.remoteConfiguration = WorkspaceRemoteConfiguration( @@ -105,6 +105,45 @@ extension AgentNotificationRegressionTests { #expect(workspace.localAgentDeliveryTTYDevices.isEmpty) } + @Test("Restored TTY metadata requires a fresh runtime registration") + func restoredTTYMetadataRequiresFreshRuntimeRegistration() throws { + let workspace = Workspace() + let panelId = try #require(workspace.focusedPanelId) + let snapshot = SessionPanelSnapshot( + id: panelId, + type: .terminal, + title: "Restored terminal", + customTitle: nil, + directory: nil, + isPinned: false, + isManuallyUnread: false, + listeningPorts: [], + ttyName: "/dev/null", + terminal: SessionTerminalPanelSnapshot(), + browser: nil, + markdown: nil, + filePreview: nil, + rightSidebarTool: nil + ) + + workspace.applySessionPanelMetadata(snapshot, toPanelId: panelId) + + #expect(workspace.surfaceTTYNames[panelId] == "/dev/null") + #expect( + workspace.localAgentDeliveryTTYDevices.isEmpty, + "Persisted TTY metadata is not evidence from the current terminal runtime" + ) + + workspace.pruneSurfaceMetadata(validSurfaceIds: [panelId]) + #expect( + workspace.localAgentDeliveryTTYDevices.isEmpty, + "Metadata pruning must not promote a persisted TTY into live evidence" + ) + + workspace.registerReportedSurfaceTTYName("/dev/null", panelId: panelId) + #expect(workspace.localAgentDeliveryTTYDevices.map(\.surfaceId) == [panelId]) + } + @Test("Live PID routing and runtime mutations include a Dock-owned terminal") func liveTTYBindingsAndRuntimeMutationsIncludeDockOwnedTerminal() throws { let fixture = try makeFixture() @@ -116,7 +155,7 @@ extension AgentNotificationRegressionTests { } let dockOwnerId = UUID() let dock = DockSplitStore(workspaceId: dockOwnerId, baseDirectoryProvider: { nil }) - fixture.source.surfaceTTYNames[fixture.panelId] = "/dev/null" + fixture.source.registerReportedSurfaceTTYName("/dev/null", panelId: fixture.panelId) fixture.source.setAgentLifecycle( key: "manual:workspace-loader", panelId: fixture.panelId, diff --git a/cmuxTests/AgentRelayTTYOwnershipTests.swift b/cmuxTests/AgentRelayTTYOwnershipTests.swift new file mode 100644 index 000000000000..79d4484ab433 --- /dev/null +++ b/cmuxTests/AgentRelayTTYOwnershipTests.swift @@ -0,0 +1,471 @@ +import AppKit +import CmuxControlSocket +import CmuxCore +import Foundation +import Testing +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +extension AgentNotificationRegressionTests { + @Test("Relay provenance does not cross remote hosts sharing a port") + func relayTTYProvenanceDoesNotCrossRemoteHostsSharingPort() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + fixture.source.remoteConfiguration = relayConfiguration( + destination: "source.example.invalid", + relayPort: 64_007 + ) + fixture.destination.remoteConfiguration = relayConfiguration( + destination: "destination.example.invalid", + relayPort: 64_007 + ) + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + fixture.source.registerReportedSurfaceTTYName("pts/20", panelId: fixture.panelId) + + try movePanel(fixture) + + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/20", + expectedWorkspaceID: fixture.destination.id, + expectedSurfaceID: fixture.panelId + ) + assertNoRelayTTYTarget( + authenticatedWorkspaceID: fixture.destination.id, + ttyName: "pts/20" + ) + } + + @Test("A fresh TTY report follows a remote surface into an ordinary workspace") + func freshRelayTTYReportFollowsSurfaceIntoOrdinaryWorkspace() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + fixture.source.remoteConfiguration = relayConfiguration( + destination: "source.example.invalid", + relayPort: 64_007 + ) + let terminal = try #require(fixture.source.panels[fixture.panelId] as? TerminalPanel) + let attemptID = UUID() + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + #expect(fixture.source.markRemoteTerminalSessionLaunching( + surfaceId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID + )) + fixture.source.registerReportedSurfaceTTYName("pts/21", panelId: fixture.panelId) + let paneID = try #require(fixture.source.bonsplitController.allPaneIds.first) + _ = try #require(fixture.source.newTerminalSurface(inPane: paneID, focus: false)) + + try movePanel(fixture) + + #expect( + TerminalController.shared.controlSurfaceReportTTY( + workspaceID: fixture.source.id, + requestedSurfaceID: fixture.panelId, + ttyName: "pts/22", + authenticatedRemoteWorkspaceID: fixture.source.id, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID + ) == .recorded(surfaceID: fixture.panelId) + ) + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/22", + expectedWorkspaceID: fixture.destination.id, + expectedSurfaceID: fixture.panelId + ) + assertNoRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/21" + ) + } + + @Test("A disconnected remote terminal cannot resolve or register another TTY") + func disconnectedRemoteTerminalCannotResolveOrRegisterTTY() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + fixture.source.remoteConfiguration = relayConfiguration( + destination: "source.example.invalid", + relayPort: 64_007 + ) + let terminal = try #require(fixture.source.panels[fixture.panelId] as? TerminalPanel) + let attemptID = UUID() + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + #expect(fixture.source.markRemoteTerminalSessionLaunching( + surfaceId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID + )) + fixture.source.registerReportedSurfaceTTYName("pts/23", panelId: fixture.panelId) + + fixture.source.disconnectRemoteConnection() + + assertNoRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/23" + ) + #expect( + TerminalController.shared.controlSurfaceReportTTY( + workspaceID: fixture.source.id, + requestedSurfaceID: fixture.panelId, + ttyName: "pts/24", + authenticatedRemoteWorkspaceID: fixture.source.id, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID + ) == .surfaceNotFound + ) + assertNoRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/24" + ) + } + + @Test("A delayed TTY report cannot revive an ended remote terminal") + func delayedTTYReportCannotReviveEndedRemoteTerminal() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + fixture.source.remoteConfiguration = relayConfiguration( + destination: "source.example.invalid", + relayPort: 64_007 + ) + let terminal = try #require(fixture.source.panels[fixture.panelId] as? TerminalPanel) + let attemptID = UUID() + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + #expect(fixture.source.markRemoteTerminalSessionLaunching( + surfaceId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID + )) + fixture.source.registerReportedSurfaceTTYName("pts/25", panelId: fixture.panelId) + #expect( + fixture.source.markRemoteTerminalSessionEnded( + surfaceId: fixture.panelId, + relayPort: 64_007 + ) + ) + + #expect( + TerminalController.shared.controlSurfaceReportTTY( + workspaceID: fixture.source.id, + requestedSurfaceID: fixture.panelId, + ttyName: "pts/26", + authenticatedRemoteWorkspaceID: fixture.source.id, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID + ) == .surfaceNotFound + ) + assertNoRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/26" + ) + } + + @Test("Relay provenance survives repeated ordinary workspace moves") + func relayTTYProvenanceSurvivesRepeatedOrdinaryWorkspaceMoves() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + fixture.source.remoteConfiguration = relayConfiguration( + destination: "source.example.invalid", + relayPort: 64_007 + ) + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + fixture.source.registerReportedSurfaceTTYName("pts/27", panelId: fixture.panelId) + + try movePanel(fixture) + let secondDestination = fixture.manager.addWorkspace(select: false) + defer { + if fixture.manager.tabs.contains(where: { $0.id == secondDestination.id }) { + fixture.manager.closeWorkspace(secondDestination) + } + } + let transfer = try #require( + fixture.destination.detachSurface(panelId: fixture.panelId) + ) + let destinationPaneID = try #require( + secondDestination.bonsplitController.allPaneIds.first + ) + #expect( + secondDestination.attachDetachedSurface( + transfer, + inPane: destinationPaneID, + focus: false + ) == fixture.panelId + ) + + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/27", + expectedWorkspaceID: secondDestination.id, + expectedSurfaceID: fixture.panelId + ) + } + + @Test("A persistent retry after an ordinary workspace move preserves TTY proof") + func persistentRetryAfterOrdinaryWorkspaceMovePreservesTTYProof() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + let terminal = try #require( + fixture.source.panels[fixture.panelId] as? TerminalPanel + ) + fixture.source.remoteConfiguration = relayConfiguration( + destination: "source.example.invalid", + relayPort: 64_007, + preserveAfterTerminalExit: true + ) + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + #expect( + fixture.source.markRemoteTerminalSessionLaunching( + surfaceId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + fixture.source.registerReportedSurfaceTTYName("pts/28", panelId: fixture.panelId) + + try movePanel(fixture) + #expect( + fixture.destination.markRemoteTerminalSessionLaunching( + surfaceId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/28", + expectedWorkspaceID: fixture.destination.id, + expectedSurfaceID: fixture.panelId + ) + } + + @Test("The relay stamps its owner onto TTY reports") + func relayTTYReportProvenanceOverridesSpoofedWorkspace() throws { + let authenticatedWorkspaceID = UUID() + let spoofedWorkspaceID = UUID() + let request: [String: Any] = [ + "id": "relay-tty-report", + "method": "surface.report_tty", + "params": [ + "workspace_id": spoofedWorkspaceID.uuidString, + "surface_id": UUID().uuidString, + "tty_name": "pts/29", + "_cmux_remote_workspace_id": spoofedWorkspaceID.uuidString, + ], + ] + let commandLine = try JSONSerialization.data(withJSONObject: request) + + let rewritten = WorkspaceRemoteRelayCommandRewriter( + remoteWorkspaceID: authenticatedWorkspaceID, + remoteRelayTokenHex: String(repeating: "a", count: 64) + ).rewriteRemoteRelayCommandLine( + commandLine, + workspaceAliases: [:], + surfaceAliases: [:] + ) + let rewrittenRequest = try #require( + JSONSerialization.jsonObject(with: rewritten) as? [String: Any] + ) + let params = try #require(rewrittenRequest["params"] as? [String: Any]) + + #expect( + params["_cmux_remote_workspace_id"] as? String + == authenticatedWorkspaceID.uuidString + ) + } + + @Test("Relay TTY reports require the authenticated owner and current attempt") + func relayTTYReportsRejectSpoofedOwnerAndStaleAttempt() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + fixture.source.remoteConfiguration = relayConfiguration( + destination: "source.example.invalid", + relayPort: 64_007 + ) + fixture.destination.remoteConfiguration = relayConfiguration( + destination: "destination.example.invalid", + relayPort: 64_008 + ) + let sourceTerminal = try #require( + fixture.source.panels[fixture.panelId] as? TerminalPanel + ) + let destinationPanelID = try #require(fixture.destination.focusedPanelId) + let destinationTerminal = try #require( + fixture.destination.panels[destinationPanelID] as? TerminalPanel + ) + let sourceAttemptID = UUID() + let destinationAttemptID = UUID() + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + fixture.destination.trackRemoteTerminalSurface(destinationPanelID) + #expect( + fixture.source.markRemoteTerminalSessionLaunching( + surfaceId: fixture.panelId, + terminalLifecycleID: sourceTerminal.surface.terminalLifecycleId, + attemptID: sourceAttemptID + ) + ) + #expect( + fixture.destination.markRemoteTerminalSessionLaunching( + surfaceId: destinationPanelID, + terminalLifecycleID: destinationTerminal.surface.terminalLifecycleId, + attemptID: destinationAttemptID + ) + ) + let coordinator = ControlCommandCoordinator(context: TerminalController.shared) + + assertTTYReportRejected(coordinator.handle(ControlRequest( + id: .string("spoofed-owner"), + method: "surface.report_tty", + params: [ + "workspace_id": .string(fixture.destination.id.uuidString), + "surface_id": .string(destinationPanelID.uuidString), + "tty_name": .string("pts/30"), + "_cmux_remote_workspace_id": .string(fixture.source.id.uuidString), + "terminal_lifecycle_id": .string( + destinationTerminal.surface.terminalLifecycleId.uuidString + ), + "attempt_id": .string(destinationAttemptID.uuidString), + ] + ))) + #expect( + !fixture.destination.surfaceRegistry.runtimeReportedTTYSurfaceIDs + .contains(destinationPanelID) + ) + + assertTTYReportRejected(coordinator.handle(ControlRequest( + id: .string("stale-attempt"), + method: "surface.report_tty", + params: [ + "workspace_id": .string(fixture.source.id.uuidString), + "surface_id": .string(fixture.panelId.uuidString), + "tty_name": .string("pts/31"), + "_cmux_remote_workspace_id": .string(fixture.source.id.uuidString), + "terminal_lifecycle_id": .string( + sourceTerminal.surface.terminalLifecycleId.uuidString + ), + "attempt_id": .string(UUID().uuidString), + ] + ))) + #expect( + !fixture.source.surfaceRegistry.runtimeReportedTTYSurfaceIDs + .contains(fixture.panelId) + ) + } + + @Test("A local TTY report expires when its runtime generation changes") + func localTTYReportExpiresAfterRuntimeGenerationChanges() async throws { + let fixture = try makeFixture() + defer { fixture.restore() } + let terminal = try #require( + fixture.source.panels[fixture.panelId] as? TerminalPanel + ) + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 640, height: 480), + styleMask: [.borderless], + backing: .buffered, + defer: false + ) + let contentView = try #require(window.contentView) + let hostedView = terminal.hostedView + hostedView.frame = contentView.bounds + hostedView.autoresizingMask = [.width, .height] + contentView.addSubview(hostedView) + window.orderFront(nil) + window.displayIfNeeded() + defer { + hostedView.removeFromSuperview() + window.orderOut(nil) + } + let ttyName = try #require(await waitForControllingTTYName(for: terminal)) + fixture.source.registerReportedSurfaceTTYName( + ttyName, + panelId: fixture.panelId + ) + #expect(!fixture.source.localAgentDeliveryTTYDevices.isEmpty) + let reportedGeneration = terminal.surface.runtimeSurfaceGeneration + + terminal.surface.releaseSurfaceForTesting() + + #expect(terminal.surface.runtimeSurfaceGeneration != reportedGeneration) + #expect(fixture.source.localAgentDeliveryTTYDevices.isEmpty) + } + + private func relayConfiguration( + destination: String, + relayPort: Int, + preserveAfterTerminalExit: Bool = false + ) -> WorkspaceRemoteConfiguration { + WorkspaceRemoteConfiguration( + destination: destination, + port: nil, + identityFile: nil, + sshOptions: [], + localProxyPort: nil, + relayPort: relayPort, + relayID: nil, + relayToken: nil, + localSocketPath: nil, + terminalStartupCommand: nil, + preserveAfterTerminalExit: preserveAfterTerminalExit, + persistentDaemonSlot: preserveAfterTerminalExit ? "relay-tty-test" : nil + ) + } + + private func assertRelayTTYTarget( + authenticatedWorkspaceID: UUID, + ttyName: String, + expectedWorkspaceID: UUID, + expectedSurfaceID: UUID + ) { + let result = TerminalController.shared.v2AgentResolveDeliveryTarget(params: [ + "tty_name": ttyName, + "tty_resolution": "reported_tty", + "_cmux_remote_workspace_id": authenticatedWorkspaceID.uuidString, + ]) + guard case .ok(let payload) = result, + let target = payload as? [String: Any] else { + Issue.record("Expected authenticated relay TTY resolution, got \(result)") + return + } + #expect(target["workspace_id"] as? String == expectedWorkspaceID.uuidString) + #expect(target["surface_id"] as? String == expectedSurfaceID.uuidString) + } + + private func assertNoRelayTTYTarget( + authenticatedWorkspaceID: UUID, + ttyName: String + ) { + let result = TerminalController.shared.v2AgentResolveDeliveryTarget(params: [ + "tty_name": ttyName, + "tty_resolution": "reported_tty", + "_cmux_remote_workspace_id": authenticatedWorkspaceID.uuidString, + ]) + guard case .err(let code, _, _) = result else { + Issue.record("Expected relay TTY resolution to fail, got \(result)") + return + } + #expect(code == "not_found") + } + + private func assertTTYReportRejected(_ result: ControlCallResult?) { + guard case .err(let code, _, _) = result else { + Issue.record("Expected relay TTY report rejection, got \(String(describing: result))") + return + } + #expect(code == "not_found") + } + + private func waitForControllingTTYName(for terminal: TerminalPanel) async -> String? { + let deadline = ContinuousClock.now + .seconds(15) + while ContinuousClock.now < deadline { + if let ttyName = terminal.surface.controllingTTYName() { + return ttyName + } + try? await Task.sleep(for: .milliseconds(10)) + } + return terminal.surface.controllingTTYName() + } +} diff --git a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift index 42d218d362ee..990013bbd8ec 100644 --- a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift +++ b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift @@ -112,28 +112,32 @@ import Testing let arguments = [executable.path, "space value", "quote'\"", "日本語", String(repeating: "x", count: 4_000)] let surfaceID = UUID().uuidString.lowercased() let workspaceID = UUID().uuidString.lowercased() - let response = try jsonResponse(result: [ - "terminals": [[ - "tty": "ttys9258", - "workspace_id": workspaceID, - "surface_id": surfaceID, - ]], - "restore_record": [ - "mode": "direct", - "kind": "custom", - "checkpoint_id": checkpointID, - "source": "test", - "working_directory": workingDirectory.path, - "environment": ["RESTORE_VALUE": "値 with spaces"], - "launch_command": [ - "arguments": arguments, - "executable_path": executable.path, + let response = try restoreResponse( + result: [ + "terminals": [[ + "tty": "ttys9258", + "workspace_id": workspaceID, + "surface_id": surfaceID, + ]], + "restore_record": [ + "mode": "direct", + "kind": "custom", + "checkpoint_id": checkpointID, + "source": "test", "working_directory": workingDirectory.path, "environment": ["RESTORE_VALUE": "値 with spaces"], + "launch_command": [ + "arguments": arguments, + "executable_path": executable.path, + "working_directory": workingDirectory.path, + "environment": ["RESTORE_VALUE": "値 with spaces"], + ], + "prepared_arguments": arguments, ], - "prepared_arguments": arguments, ], - ]) + workspaceID: workspaceID, + surfaceID: surfaceID + ) let socketPath = "/tmp/cmux-restore-\(UUID().uuidString.prefix(8)).sock" let responder = try UnixSocketResponder(path: socketPath, response: response) defer { responder.stop() } @@ -166,7 +170,7 @@ import Testing ) return try XCTUnwrap(object["method"] as? String) } - XCTAssertEqual(methods, ["debug.terminals", "surface.resume.get"]) + XCTAssertEqual(methods, ["agent.resolve_delivery_target", "surface.resume.get"]) } @Test func testRestoreDoesNotResolveBareExecutableFromEmptyPATHComponent() throws { @@ -188,7 +192,7 @@ import Testing defer { try? FileManager.default.removeItem(at: root) } let checkpointID = "path-\(UUID().uuidString)" - let response = try jsonResponse(result: [ + let response = try restoreResponse(result: [ "restore_record": [ "mode": "direct", "kind": "custom", @@ -259,7 +263,7 @@ import Testing let checkpointID = "preflight-\(UUID().uuidString)" let launchEnvironment = ["CUSTOM_BASE_URL": "https://codex.example.test/v1"] - let response = try jsonResponse(result: [ + let response = try restoreResponse(result: [ "restore_record": [ "mode": "resumeAgent", "kind": "hermes-agent", @@ -342,7 +346,7 @@ import Testing "--session", checkpointID, ] - let response = try jsonResponse(result: [ + let response = try restoreResponse(result: [ "restore_record": [ "mode": "resumeAgent", "kind": "cwd-agent", @@ -392,7 +396,7 @@ import Testing defer { try? FileManager.default.removeItem(at: root) } let checkpointID = "legacy-\(UUID().uuidString)" - let response = try jsonResponse(result: [ + let response = try restoreResponse(result: [ "restore_record": [ "mode": "resumeAgent", "kind": "codex", @@ -434,7 +438,7 @@ import Testing defer { try? FileManager.default.removeItem(at: root) } let checkpointID = "fallback-\(UUID().uuidString)" - let response = try jsonResponse(result: [ + let response = try restoreResponse(result: [ "restore_record": [ "mode": "relaunchAgent", "kind": "custom-relaunch", @@ -504,7 +508,7 @@ import Testing @Test func testRestorePositionalFormFailsClosedWhenBindingIdentityDrifts() throws { let cliPath = try bundledCLIPath() let currentCheckpointID = UUID().uuidString.lowercased() - let response = try jsonResponse(result: [ + let response = try restoreResponse(result: [ "restore_record": [ "mode": "direct", "kind": "codex", @@ -586,7 +590,7 @@ import Testing @Test func testRestoreWaitsForControlSocketDuringAppStartup() throws { let cliPath = try bundledCLIPath() let checkpointID = UUID().uuidString.lowercased() - let response = try jsonResponse(result: [ + let response = try restoreResponse(result: [ "restore_record": [ "mode": "direct", "kind": "custom", @@ -629,7 +633,539 @@ import Testing let requiredResponder = try #require(responder) XCTAssertFalse(result.timedOut, result.stdout) XCTAssertEqual(result.status, 0, result.stdout) - XCTAssertEqual(requiredResponder.receivedRequests.count, 1) + XCTAssertEqual(requiredResponder.receivedRequests.count, 2) + } + + @Test(arguments: ["pi", "grok"]) + func testRestorePrefersLiveProcessTargetOverStaleAmbientRouting(kind: String) throws { + let cliPath = try bundledCLIPath() + let checkpointID = "\(kind)-\(UUID().uuidString.lowercased())" + let staleSurfaceID = UUID().uuidString + let staleTTYSurfaceID = UUID().uuidString + let currentSurfaceID = UUID().uuidString + let workspaceID = UUID().uuidString + let callerTargetResponse = try jsonResponse(result: [ + "terminals": [[ + "tty": "ttys9380", + "workspace_id": UUID().uuidString, + "surface_id": staleTTYSurfaceID, + ]], + "source": "pid", + "pid_resolution": "controlling_tty", + "workspace_id": workspaceID, + "surface_id": currentSurfaceID, + ]) + let restoreResponse = try restoreResponse(result: [ + "restore_record": [ + "mode": "direct", + "kind": kind, + "checkpoint_id": checkpointID, + "environment": [:], + "launch_command": [ + "arguments": ["/usr/bin/true"], + "executable_path": "/usr/bin/true", + ], + "prepared_arguments": ["/usr/bin/true"], + ], + ]) + let socketPath = "/tmp/cmux-restore-stale-\(UUID().uuidString.prefix(8)).sock" + let responder = try UnixSocketResponder( + path: socketPath, + responses: [callerTargetResponse, restoreResponse] + ) + defer { responder.stop() } + var environment = ProcessInfo.processInfo.environment + for key in Array(environment.keys) where key.hasPrefix("CMUX_") { + environment.removeValue(forKey: key) + } + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + environment["CMUX_SOCKET_PATH"] = socketPath + environment["CMUX_SURFACE_ID"] = staleSurfaceID + environment["TTY"] = "/dev/ttys9380" + + let result = runProcess( + executablePath: cliPath, + arguments: ["restore", kind, checkpointID], + environment: environment, + timeout: 5 + ) + + #expect(!result.timedOut, Comment(rawValue: result.stdout)) + #expect(result.status == 0, Comment(rawValue: result.stdout)) + let requests = try responder.receivedRequests.map { request in + let data = try #require(request.data(using: .utf8)) + return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + #expect(requests.compactMap { $0["method"] as? String } == [ + "agent.resolve_delivery_target", + "surface.resume.get", + ]) + let callerTargetRequest = try #require(requests.first) + let callerTargetParams = try #require(callerTargetRequest["params"] as? [String: Any]) + #expect((callerTargetParams["pid"] as? Int).map { $0 > 0 } == true) + #expect(callerTargetParams["pid_resolution"] as? String == "controlling_tty") + let restoreRequest = try #require(requests.last) + let restoreParams = try #require(restoreRequest["params"] as? [String: Any]) + #expect(restoreParams["surface_id"] as? String == currentSurfaceID) + #expect(restoreParams["surface_id"] as? String != staleSurfaceID) + #expect(restoreParams["surface_id"] as? String != staleTTYSurfaceID) + } + + @Test func testRelayRestoreFailsClosedOnFirstMissingTTYTarget() throws { + let cliPath = try bundledCLIPath() + let checkpointID = "pi-\(UUID().uuidString.lowercased())" + let workspaceID = UUID().uuidString + let notFoundResponse = try jsonErrorResponse( + code: "not_found", + message: "No live delivery target" + ) + let relayID = "relay-\(UUID().uuidString.lowercased())" + let responder = try RelaySocketResponder( + relayID: relayID, + responses: [notFoundResponse] + ) + defer { responder.stop() } + var environment = ProcessInfo.processInfo.environment + for key in Array(environment.keys) where key.hasPrefix("CMUX_") { + environment.removeValue(forKey: key) + } + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + environment["CMUX_SOCKET_PATH"] = responder.endpoint + environment["CMUX_RELAY_ID"] = relayID + environment["CMUX_RELAY_TOKEN"] = String(repeating: "11", count: 32) + environment["CMUX_WORKSPACE_ID"] = workspaceID + environment["CMUX_CLI_TTY_NAME"] = "0" + + let result = runProcess( + executablePath: cliPath, + arguments: ["restore", "pi", checkpointID], + environment: environment, + timeout: 5 + ) + + #expect(!result.timedOut, Comment(rawValue: result.stdout)) + #expect(result.status != 0, Comment(rawValue: result.stdout)) + #expect( + result.stdout.contains("the current cmux surface could not be identified"), + Comment(rawValue: result.stdout) + ) + let requests = try responder.receivedRequests.map { request in + let data = try #require(request.data(using: .utf8)) + return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + #expect( + requests.compactMap { $0["method"] as? String } == [ + "agent.resolve_delivery_target" + ] + ) + let params = try #require(requests.first?["params"] as? [String: Any]) + #expect(params["tty_name"] as? String == "0") + #expect(params["tty_resolution"] as? String == "reported_tty") + #expect(params["workspace_id"] as? String == workspaceID) + } + + @Test func testRestoreFailsClosedWhenLiveProcessTargetIsNotFound() throws { + let cliPath = try bundledCLIPath() + let checkpointID = "pi-\(UUID().uuidString.lowercased())" + let staleSurfaceID = UUID().uuidString + let callerTargetResponse = try jsonErrorResponse( + code: "not_found", + message: "No live delivery target" + ) + let socketPath = "/tmp/cmux-restore-ambiguous-\(UUID().uuidString.prefix(8)).sock" + let responder = try UnixSocketResponder( + path: socketPath, + response: callerTargetResponse + ) + defer { responder.stop() } + var environment = ProcessInfo.processInfo.environment + for key in Array(environment.keys) where key.hasPrefix("CMUX_") { + environment.removeValue(forKey: key) + } + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + environment["CMUX_SOCKET_PATH"] = socketPath + environment["CMUX_SURFACE_ID"] = staleSurfaceID + environment["TTY"] = "/dev/ttys9380" + + let result = runProcess( + executablePath: cliPath, + arguments: ["restore", "pi", checkpointID], + environment: environment, + timeout: 5 + ) + + #expect(!result.timedOut, Comment(rawValue: result.stdout)) + #expect(result.status != 0, Comment(rawValue: result.stdout)) + #expect( + result.stdout.contains("the current cmux surface could not be identified"), + Comment(rawValue: result.stdout) + ) + let requests = try responder.receivedRequests.map { request in + let data = try #require(request.data(using: .utf8)) + return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + #expect( + requests.compactMap { $0["method"] as? String } == [ + "agent.resolve_delivery_target" + ] + ) + } + + @Test func testRestoreUsesUniqueTTYBindingWhenLiveTargetMethodIsUnsupported() throws { + let cliPath = try bundledCLIPath() + let checkpointID = "pi-\(UUID().uuidString.lowercased())" + let workspaceID = UUID().uuidString + let surfaceID = UUID().uuidString + let callerTargetResponse = try jsonErrorResponse( + code: "method_not_found", + message: "Unknown method" + ) + let terminalsResponse = try jsonResponse(result: [ + "terminals": [[ + "tty": "ttys9380", + "workspace_id": workspaceID, + "surface_id": surfaceID, + ]], + ]) + let restoreResponse = try restoreResponse(result: [ + "restore_record": [ + "mode": "direct", + "kind": "pi", + "checkpoint_id": checkpointID, + "environment": [:], + "launch_command": [ + "arguments": ["/usr/bin/true"], + "executable_path": "/usr/bin/true", + ], + "prepared_arguments": ["/usr/bin/true"], + ], + ]) + let socketPath = "/tmp/cmux-restore-legacy-\(UUID().uuidString.prefix(8)).sock" + let responder = try UnixSocketResponder( + path: socketPath, + responses: [callerTargetResponse, terminalsResponse, restoreResponse] + ) + defer { responder.stop() } + var environment = ProcessInfo.processInfo.environment + for key in Array(environment.keys) where key.hasPrefix("CMUX_") { + environment.removeValue(forKey: key) + } + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + environment["CMUX_SOCKET_PATH"] = socketPath + environment["CMUX_CLI_TTY_NAME"] = "ttys9380" + environment["TTY"] = "/dev/ttys-stale" + + let result = runProcess( + executablePath: cliPath, + arguments: ["restore", "pi", checkpointID], + environment: environment, + timeout: 5 + ) + + #expect(!result.timedOut, Comment(rawValue: result.stdout)) + #expect(result.status == 0, Comment(rawValue: result.stdout)) + let requests = try responder.receivedRequests.map { request in + let data = try #require(request.data(using: .utf8)) + return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + #expect(requests.compactMap { $0["method"] as? String } == [ + "agent.resolve_delivery_target", + "debug.terminals", + "surface.resume.get", + ]) + let restoreRequest = try #require(requests.last) + let restoreParams = try #require(restoreRequest["params"] as? [String: Any]) + #expect(restoreParams["surface_id"] as? String == surfaceID) + } + + @Test func testRestoreScopesRelayTTYResolutionToAuthenticatedWorkspace() throws { + let cliPath = try bundledCLIPath() + let checkpointID = "pi-\(UUID().uuidString.lowercased())" + let workspaceID = UUID().uuidString + let surfaceID = UUID().uuidString + let siblingWorkspaceID = UUID().uuidString + let siblingSurfaceID = UUID().uuidString + let liveTargetResponse = try jsonResponse(result: [ + "terminals": [ + [ + "tty": "0", + "workspace_id": workspaceID, + "surface_id": surfaceID, + ], + [ + "tty": "0", + "workspace_id": siblingWorkspaceID, + "surface_id": siblingSurfaceID, + ], + ], + "source": "tty", + "tty_resolution": "reported_tty", + "workspace_id": workspaceID, + "surface_id": surfaceID, + ]) + let recordResponse = try jsonResponse(result: [ + "restore_record": [ + "mode": "direct", + "kind": "pi", + "checkpoint_id": checkpointID, + "environment": [:], + "launch_command": [ + "arguments": ["/usr/bin/true"], + "executable_path": "/usr/bin/true", + ], + "prepared_arguments": ["/usr/bin/true"], + ], + ]) + let relayID = "relay-\(UUID().uuidString.lowercased())" + let responder = try RelaySocketResponder( + relayID: relayID, + responses: [liveTargetResponse, recordResponse] + ) + defer { responder.stop() } + var environment = ProcessInfo.processInfo.environment + for key in Array(environment.keys) where key.hasPrefix("CMUX_") { + environment.removeValue(forKey: key) + } + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + environment["CMUX_SOCKET_PATH"] = responder.endpoint + environment["CMUX_RELAY_ID"] = relayID + environment["CMUX_RELAY_TOKEN"] = String(repeating: "11", count: 32) + environment["CMUX_WORKSPACE_ID"] = workspaceID + environment["CMUX_CLI_TTY_NAME"] = "0" + + let result = runProcess( + executablePath: cliPath, + arguments: ["restore", "pi", checkpointID], + environment: environment, + timeout: 5 + ) + + #expect(!result.timedOut, Comment(rawValue: result.stdout)) + #expect(result.status == 0, Comment(rawValue: result.stdout)) + let requests = try responder.receivedRequests.map { request in + let data = try #require(request.data(using: .utf8)) + return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + #expect(requests.compactMap { $0["method"] as? String } == [ + "agent.resolve_delivery_target", + "surface.resume.get", + ]) + let targetParams = try #require(requests.first?["params"] as? [String: Any]) + #expect(targetParams["tty_name"] as? String == "0") + #expect(targetParams["tty_resolution"] as? String == "reported_tty") + let restoreParams = try #require(requests.last?["params"] as? [String: Any]) + #expect(restoreParams["surface_id"] as? String == surfaceID) + #expect(restoreParams["surface_id"] as? String != siblingSurfaceID) + } + + @Test func testRestoreScopesLegacyRelayTTYFallbackToResolvedWorkspace() throws { + let cliPath = try bundledCLIPath() + let checkpointID = "pi-\(UUID().uuidString.lowercased())" + let staleWorkspaceID = UUID().uuidString + let workspaceID = UUID().uuidString + let surfaceID = UUID().uuidString + let siblingWorkspaceID = UUID().uuidString + let siblingSurfaceID = UUID().uuidString + let workspaceResponse = try jsonResponse(result: [ + "source": "workspace", + "workspace_id": workspaceID, + "surface_id": NSNull(), + ]) + let terminalsResponse = try jsonResponse(result: [ + "terminals": [ + [ + "tty": "0", + "workspace_id": workspaceID, + "surface_id": surfaceID, + ], + [ + "tty": "0", + "workspace_id": siblingWorkspaceID, + "surface_id": siblingSurfaceID, + ], + ], + ]) + let recordResponse = try jsonResponse(result: [ + "restore_record": [ + "mode": "direct", + "kind": "pi", + "checkpoint_id": checkpointID, + "environment": [:], + "launch_command": [ + "arguments": ["/usr/bin/true"], + "executable_path": "/usr/bin/true", + ], + "prepared_arguments": ["/usr/bin/true"], + ], + ]) + let relayID = "relay-\(UUID().uuidString.lowercased())" + let responder = try RelaySocketResponder( + relayID: relayID, + responses: [workspaceResponse, terminalsResponse, recordResponse] + ) + defer { responder.stop() } + var environment = ProcessInfo.processInfo.environment + for key in Array(environment.keys) where key.hasPrefix("CMUX_") { + environment.removeValue(forKey: key) + } + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + environment["CMUX_SOCKET_PATH"] = responder.endpoint + environment["CMUX_RELAY_ID"] = relayID + environment["CMUX_RELAY_TOKEN"] = String(repeating: "11", count: 32) + environment["CMUX_WORKSPACE_ID"] = staleWorkspaceID + environment["CMUX_CLI_TTY_NAME"] = "0" + + let result = runProcess( + executablePath: cliPath, + arguments: ["restore", "pi", checkpointID], + environment: environment, + timeout: 5 + ) + + #expect(!result.timedOut, Comment(rawValue: result.stdout)) + #expect(result.status == 0, Comment(rawValue: result.stdout)) + let requests = try responder.receivedRequests.map { request in + let data = try #require(request.data(using: .utf8)) + return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + #expect(requests.compactMap { $0["method"] as? String } == [ + "agent.resolve_delivery_target", + "debug.terminals", + "surface.resume.get", + ]) + let targetParams = try #require(requests.first?["params"] as? [String: Any]) + #expect(targetParams["workspace_id"] as? String == staleWorkspaceID) + let restoreParams = try #require(requests.last?["params"] as? [String: Any]) + #expect(restoreParams["surface_id"] as? String == surfaceID) + #expect(restoreParams["surface_id"] as? String != siblingSurfaceID) + } + + @Test func testRestoreRejectsMalformedLiveProcessTargetWithoutFallingBack() throws { + let cliPath = try bundledCLIPath() + let checkpointID = "pi-\(UUID().uuidString.lowercased())" + let callerTargetResponse = try jsonResponse(result: [ + "terminals": [], + "source": "pid", + "pid_resolution": "controlling_tty", + "workspace_id": UUID().uuidString, + "surface_id": "not-a-surface-id", + ]) + let restoreResponse = try restoreResponse(result: [ + "restore_record": [ + "mode": "direct", + "kind": "pi", + "checkpoint_id": checkpointID, + "environment": [:], + "launch_command": [ + "arguments": ["/usr/bin/true"], + "executable_path": "/usr/bin/true", + ], + "prepared_arguments": ["/usr/bin/true"], + ], + ]) + let socketPath = "/tmp/cmux-restore-malformed-\(UUID().uuidString.prefix(8)).sock" + let responder = try UnixSocketResponder( + path: socketPath, + responses: [callerTargetResponse, restoreResponse] + ) + defer { responder.stop() } + var environment = ProcessInfo.processInfo.environment + for key in Array(environment.keys) where key.hasPrefix("CMUX_") { + environment.removeValue(forKey: key) + } + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + environment["CMUX_SOCKET_PATH"] = socketPath + environment["CMUX_SURFACE_ID"] = UUID().uuidString + environment["TTY"] = "/dev/ttys9380" + + let result = runProcess( + executablePath: cliPath, + arguments: ["restore", "pi", checkpointID], + environment: environment, + timeout: 5 + ) + + #expect(!result.timedOut, Comment(rawValue: result.stdout)) + #expect(result.status != 0, Comment(rawValue: result.stdout)) + #expect( + result.stdout.contains("the current cmux surface could not be identified"), + Comment(rawValue: result.stdout) + ) + let requests = try responder.receivedRequests.map { request in + let data = try #require(request.data(using: .utf8)) + return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + #expect(requests.compactMap { $0["method"] as? String } == [ + "agent.resolve_delivery_target", + ]) + } + + @Test func testRestoreDoesNotReuseSocketAfterCallerTargetTimeout() throws { + let cliPath = try bundledCLIPath() + let checkpointID = "pi-\(UUID().uuidString.lowercased())" + let currentSurfaceID = UUID().uuidString + let callerTargetResponse = try jsonResponse(result: [ + "terminals": [[ + "tty": "ttys9380", + "workspace_id": UUID().uuidString, + "surface_id": currentSurfaceID, + ]], + "source": "pid", + "pid_resolution": "controlling_tty", + "workspace_id": UUID().uuidString, + "surface_id": currentSurfaceID, + ]) + let restoreResponse = try restoreResponse(result: [ + "restore_record": [ + "mode": "direct", + "kind": "pi", + "checkpoint_id": checkpointID, + "environment": [:], + "launch_command": [ + "arguments": ["/usr/bin/true"], + "executable_path": "/usr/bin/true", + ], + "prepared_arguments": ["/usr/bin/true"], + ], + ]) + let socketPath = "/tmp/cmux-restore-timeout-\(UUID().uuidString.prefix(8)).sock" + let responder = try UnixSocketResponder( + path: socketPath, + responses: [callerTargetResponse, restoreResponse], + responseDelay: 0.3 + ) + defer { responder.stop() } + var environment = ProcessInfo.processInfo.environment + for key in Array(environment.keys) where key.hasPrefix("CMUX_") { + environment.removeValue(forKey: key) + } + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + environment["CMUX_SOCKET_PATH"] = socketPath + environment["CMUX_SURFACE_ID"] = UUID().uuidString + environment["CMUXTERM_CLI_RESPONSE_TIMEOUT_SEC"] = "0.2" + environment["TTY"] = "/dev/ttys9380" + + let result = runProcess( + executablePath: cliPath, + arguments: ["restore", "pi", checkpointID], + environment: environment, + timeout: 5 + ) + + #expect(!result.timedOut, Comment(rawValue: result.stdout)) + #expect(result.status != 0, Comment(rawValue: result.stdout)) + #expect(result.stdout.contains("Command timed out"), Comment(rawValue: result.stdout)) + #expect( + !result.stdout.contains("this session has nothing to restore"), + Comment(rawValue: result.stdout) + ) + let requests = try responder.receivedRequests.map { request in + let data = try #require(request.data(using: .utf8)) + return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + #expect(requests.compactMap { $0["method"] as? String } == [ + "agent.resolve_delivery_target", + ]) } @Test func testBundledCLIInTaggedDebugAppPrefersItsOwnSocketWithoutEnvironmentOverride() throws { @@ -1871,6 +2407,33 @@ import Testing return try XCTUnwrap(String(data: data, encoding: .utf8)) } + private func restoreResponse( + result: [String: Any], + workspaceID: String? = nil, + surfaceID: String? = nil + ) throws -> String { + var result = result + result["source"] = "pid" + result["pid_resolution"] = "controlling_tty" + result["workspace_id"] = workspaceID ?? UUID().uuidString + result["surface_id"] = surfaceID ?? UUID().uuidString + return try jsonResponse(result: result) + } + + private func jsonErrorResponse(code: String, message: String) throws -> String { + let data = try JSONSerialization.data( + withJSONObject: [ + "ok": false, + "error": [ + "code": code, + "message": message, + ], + ], + options: [] + ) + return try XCTUnwrap(String(data: data, encoding: .utf8)) + } + /// The stable control-socket path under an injected (temp) home, resolved via /// the canonical ``CmuxStateDirectory`` so the test exercises the real layout. private func stableSocketURL(home: URL) throws -> URL { @@ -2094,7 +2657,7 @@ import Testing final class UnixSocketResponder { let path: String - private let response: String + private let responses: [String] private let responseDelay: TimeInterval private let queue = DispatchQueue(label: "com.cmux.tests.unix-socket-responder") private let lock = NSLock() @@ -2102,9 +2665,20 @@ final class UnixSocketResponder { private var requests: [String] = [] private var listenerFD: Int32 = -1 - init(path: String, response: String, responseDelay: TimeInterval = 0) throws { + convenience init(path: String, response: String, responseDelay: TimeInterval = 0) throws { + try self.init(path: path, responses: [response], responseDelay: responseDelay) + } + + init(path: String, responses: [String], responseDelay: TimeInterval = 0) throws { + guard !responses.isEmpty else { + throw NSError( + domain: NSCocoaErrorDomain, + code: CocoaError.validationMissingMandatoryProperty.rawValue, + userInfo: [NSLocalizedDescriptionKey: "At least one socket response is required"] + ) + } self.path = path - self.response = response + self.responses = responses self.responseDelay = responseDelay unlink(path) @@ -2202,6 +2776,16 @@ final class UnixSocketResponder { private func handle(clientFD: Int32) { defer { close(clientFD) } + var noSigPipe: Int32 = 1 + _ = withUnsafePointer(to: &noSigPipe) { pointer in + setsockopt( + clientFD, + SOL_SOCKET, + SO_NOSIGPIPE, + pointer, + socklen_t(MemoryLayout.size) + ) + } while true { var request = Data() while true { @@ -2215,15 +2799,18 @@ final class UnixSocketResponder { break } } + var responseIndex = 0 if let line = String(data: request, encoding: .utf8)? .trimmingCharacters(in: .whitespacesAndNewlines) { lock.lock() + responseIndex = requests.count requests.append(line) lock.unlock() } if responseDelay > 0 { Thread.sleep(forTimeInterval: responseDelay) } + let response = responses[min(responseIndex, responses.count - 1)] let payload = response + "\n" payload.withCString { pointer in _ = write(clientFD, pointer, strlen(pointer)) @@ -2239,3 +2826,164 @@ final class UnixSocketResponder { ) } } + +final class RelaySocketResponder { + let endpoint: String + private let relayID: String + private let responses: [String] + private let queue = DispatchQueue(label: "com.cmux.tests.relay-socket-responder") + private let lock = NSLock() + private var stopped = false + private var requests: [String] = [] + private var listenerFD: Int32 = -1 + + init(relayID: String, responses: [String]) throws { + guard !responses.isEmpty else { + throw NSError( + domain: NSCocoaErrorDomain, + code: CocoaError.validationMissingMandatoryProperty.rawValue, + userInfo: [NSLocalizedDescriptionKey: "At least one relay response is required"] + ) + } + self.relayID = relayID + self.responses = responses + + let fd = socket(AF_INET, SOCK_STREAM, 0) + guard fd >= 0 else { throw Self.posixError("socket") } + var reuse: Int32 = 1 + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, socklen_t(MemoryLayout.size)) + + var address = sockaddr_in() + address.sin_len = UInt8(MemoryLayout.size) + address.sin_family = sa_family_t(AF_INET) + address.sin_port = 0 + address.sin_addr = in_addr(s_addr: inet_addr("127.0.0.1")) + let bindResult = withUnsafePointer(to: &address) { pointer in + pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { socketPointer in + Darwin.bind(fd, socketPointer, socklen_t(MemoryLayout.size)) + } + } + guard bindResult == 0, listen(fd, 8) == 0 else { + let error = Self.posixError("bind/listen") + close(fd) + throw error + } + + var boundAddress = sockaddr_in() + var boundLength = socklen_t(MemoryLayout.size) + let nameResult = withUnsafeMutablePointer(to: &boundAddress) { pointer in + pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { socketPointer in + getsockname(fd, socketPointer, &boundLength) + } + } + guard nameResult == 0 else { + let error = Self.posixError("getsockname") + close(fd) + throw error + } + + listenerFD = fd + endpoint = "127.0.0.1:\(UInt16(bigEndian: boundAddress.sin_port))" + queue.async { [weak self] in + self?.acceptLoop(listenerFD: fd) + } + } + + deinit { + stop() + } + + var receivedRequests: [String] { + lock.lock() + defer { lock.unlock() } + return requests + } + + func stop() { + lock.lock() + guard !stopped else { + lock.unlock() + return + } + stopped = true + let fd = listenerFD + listenerFD = -1 + lock.unlock() + if fd >= 0 { close(fd) } + } + + private var isStopped: Bool { + lock.lock() + defer { lock.unlock() } + return stopped + } + + private func acceptLoop(listenerFD: Int32) { + while !isStopped { + let clientFD = accept(listenerFD, nil, nil) + if clientFD < 0 { + if isStopped { return } + continue + } + handle(clientFD: clientFD) + } + } + + private func handle(clientFD: Int32) { + defer { close(clientFD) } + var noSigPipe: Int32 = 1 + setsockopt( + clientFD, + SOL_SOCKET, + SO_NOSIGPIPE, + &noSigPipe, + socklen_t(MemoryLayout.size) + ) + let challenge = #"{"protocol":"cmux-relay-auth","version":1,"relay_id":"\#(relayID)","nonce":"test-nonce"}"# + guard writeLine(challenge, to: clientFD), readLine(from: clientFD) != nil else { return } + guard writeLine(#"{"ok":true}"#, to: clientFD), + let request = readLine(from: clientFD) else { return } + + lock.lock() + let responseIndex = requests.count + requests.append(request) + lock.unlock() + _ = writeLine(responses[min(responseIndex, responses.count - 1)], to: clientFD) + } + + private func readLine(from fd: Int32) -> String? { + var data = Data() + while true { + var byte: UInt8 = 0 + let count = read(fd, &byte, 1) + if count < 0, errno == EINTR { continue } + guard count > 0 else { return nil } + if byte == 0x0A { return String(data: data, encoding: .utf8) } + data.append(byte) + } + } + + private func writeLine(_ line: String, to fd: Int32) -> Bool { + let data = Data((line + "\n").utf8) + return data.withUnsafeBytes { rawBuffer in + guard var pointer = rawBuffer.bindMemory(to: UInt8.self).baseAddress else { return false } + var remaining = rawBuffer.count + while remaining > 0 { + let count = write(fd, pointer, remaining) + if count < 0, errno == EINTR { continue } + guard count > 0 else { return false } + pointer = pointer.advanced(by: count) + remaining -= count + } + return true + } + } + + private static func posixError(_ operation: String) -> NSError { + NSError( + domain: NSPOSIXErrorDomain, + code: Int(errno), + userInfo: [NSLocalizedDescriptionKey: "\(operation) failed: \(String(cString: strerror(errno)))"] + ) + } +} diff --git a/cmuxTests/FishShellIntegrationTests.swift b/cmuxTests/FishShellIntegrationTests.swift index 6251be2f1b53..ff891ae1282c 100644 --- a/cmuxTests/FishShellIntegrationTests.swift +++ b/cmuxTests/FishShellIntegrationTests.swift @@ -222,15 +222,15 @@ struct FishShellIntegrationTests { function tmux if test "$argv[1]" = show-environment if test "$argv[2]" = -g - printf '%s\\n' 'CMUX_SOCKET_PATH=127.0.0.1:63135' 'CMUX_TAB_ID=stale-workspace' 'CMUX_WORKSPACE_ID=stale-workspace' + printf '%s\\n' 'CMUX_SOCKET_PATH=127.0.0.1:63135' 'CMUX_SSH_ATTEMPT_ID=stale-attempt' 'CMUX_TAB_ID=stale-workspace' 'CMUX_TERMINAL_LIFECYCLE_ID=stale-lifecycle' 'CMUX_WORKSPACE_ID=stale-workspace' else - printf '%s\\n' 'CMUX_SOCKET_PATH=127.0.0.1:55272' 'CMUX_TAB_ID=current-workspace' 'CMUX_WORKSPACE_ID=current-workspace' + printf '%s\\n' 'CMUX_SOCKET_PATH=127.0.0.1:55272' 'CMUX_SSH_ATTEMPT_ID=current-attempt' 'CMUX_TAB_ID=current-workspace' 'CMUX_TERMINAL_LIFECYCLE_ID=current-lifecycle' 'CMUX_WORKSPACE_ID=current-workspace' end end end _cmux_tmux_sync_cmux_environment - printf 'workspace=%s\\nsocket=%s\\nsurface=%s\\npanel=%s\\n' \ - "$CMUX_WORKSPACE_ID" "$CMUX_SOCKET_PATH" \ + printf 'workspace=%s\\nsocket=%s\\nlifecycle=%s\\nattempt=%s\\nsurface=%s\\npanel=%s\\n' \ + "$CMUX_WORKSPACE_ID" "$CMUX_SOCKET_PATH" "$CMUX_TERMINAL_LIFECYCLE_ID" "$CMUX_SSH_ATTEMPT_ID" \ (set -q CMUX_SURFACE_ID; and printf %s "$CMUX_SURFACE_ID"; or printf %s '') \ (set -q CMUX_PANEL_ID; and printf %s "$CMUX_PANEL_ID"; or printf %s '') """, @@ -239,6 +239,8 @@ struct FishShellIntegrationTests { "CMUX_SOCKET_PATH": "127.0.0.1:63135", "CMUX_SURFACE_ID": "stale-surface", "CMUX_TAB_ID": "stale-workspace", + "CMUX_TERMINAL_LIFECYCLE_ID": "stale-lifecycle", + "CMUX_SSH_ATTEMPT_ID": "stale-attempt", "CMUX_WORKSPACE_ID": "stale-workspace", "TMUX": "/tmp/tmux-test,1,0", ] @@ -246,6 +248,8 @@ struct FishShellIntegrationTests { expectTrue(result.stdout.contains("workspace=current-workspace"), result.stdout) expectTrue(result.stdout.contains("socket=127.0.0.1:55272"), result.stdout) + expectTrue(result.stdout.contains("lifecycle=current-lifecycle"), result.stdout) + expectTrue(result.stdout.contains("attempt=current-attempt"), result.stdout) expectTrue(result.stdout.contains("surface="), result.stdout) expectTrue(result.stdout.contains("panel="), result.stdout) } diff --git a/cmuxTests/GhosttyConfigTests.swift b/cmuxTests/GhosttyConfigTests.swift index fc229a5fe0b6..8b7891310a25 100644 --- a/cmuxTests/GhosttyConfigTests.swift +++ b/cmuxTests/GhosttyConfigTests.swift @@ -5070,11 +5070,13 @@ final class ZshShellIntegrationHandoffTests: XCTestCase { "CMUX_WORKSPACE_ID": "11111111-1111-1111-1111-111111111111", "CMUX_TAB_ID": "22222222-2222-2222-2222-222222222222", "CMUX_PANEL_ID": "22222222-2222-2222-2222-222222222222", + "CMUX_TERMINAL_LIFECYCLE_ID": "33333333-3333-3333-3333-333333333333", + "CMUX_SSH_ATTEMPT_ID": "44444444-4444-4444-4444-444444444444", ] ) XCTAssertTrue( - output.contains(#"rpc surface.report_tty {"workspace_id":"11111111-1111-1111-1111-111111111111","tty_name":"ttys777","surface_id":"22222222-2222-2222-2222-222222222222"}"#), + output.contains(#"rpc surface.report_tty {"workspace_id":"11111111-1111-1111-1111-111111111111","tty_name":"ttys777","terminal_lifecycle_id":"33333333-3333-3333-3333-333333333333","attempt_id":"44444444-4444-4444-4444-444444444444","surface_id":"22222222-2222-2222-2222-222222222222"}"#), output ) } @@ -5207,11 +5209,13 @@ final class ZshShellIntegrationHandoffTests: XCTestCase { "CMUX_WORKSPACE_ID": "11111111-1111-1111-1111-111111111111", "CMUX_TAB_ID": "22222222-2222-2222-2222-222222222222", "CMUX_PANEL_ID": "22222222-2222-2222-2222-222222222222", + "CMUX_TERMINAL_LIFECYCLE_ID": "33333333-3333-3333-3333-333333333333", + "CMUX_SSH_ATTEMPT_ID": "44444444-4444-4444-4444-444444444444", ] ) XCTAssertTrue( - result.stdout.contains(#"rpc surface.report_tty {"workspace_id":"11111111-1111-1111-1111-111111111111","tty_name":"ttys888","surface_id":"22222222-2222-2222-2222-222222222222"}"#), + result.stdout.contains(#"rpc surface.report_tty {"workspace_id":"11111111-1111-1111-1111-111111111111","tty_name":"ttys888","terminal_lifecycle_id":"33333333-3333-3333-3333-333333333333","attempt_id":"44444444-4444-4444-4444-444444444444","surface_id":"22222222-2222-2222-2222-222222222222"}"#), result.stdout ) } @@ -5254,11 +5258,13 @@ final class ZshShellIntegrationHandoffTests: XCTestCase { "CMUX_WORKSPACE_ID": "11111111-1111-1111-1111-111111111111", "CMUX_TAB_ID": "22222222-2222-2222-2222-222222222222", "CMUX_PANEL_ID": "", + "CMUX_TERMINAL_LIFECYCLE_ID": "33333333-3333-3333-3333-333333333333", + "CMUX_SSH_ATTEMPT_ID": "44444444-4444-4444-4444-444444444444", ] ) XCTAssertTrue( - result.stdout.contains(#"rpc surface.report_tty {"workspace_id":"11111111-1111-1111-1111-111111111111","tty_name":"ttys889"}"#), + result.stdout.contains(#"rpc surface.report_tty {"workspace_id":"11111111-1111-1111-1111-111111111111","tty_name":"ttys889","terminal_lifecycle_id":"33333333-3333-3333-3333-333333333333","attempt_id":"44444444-4444-4444-4444-444444444444"}"#), result.stdout ) XCTAssertTrue( diff --git a/cmuxTests/RemoteInitialCommandBootstrapTests.swift b/cmuxTests/RemoteInitialCommandBootstrapTests.swift index 690aa0e3ad3b..1010f116f986 100644 --- a/cmuxTests/RemoteInitialCommandBootstrapTests.swift +++ b/cmuxTests/RemoteInitialCommandBootstrapTests.swift @@ -334,6 +334,73 @@ struct RemoteInitialCommandBootstrapTests { #expect(recordedInvocations == "execute|\(home.path)|remote-only\ninteractive\ninteractive\n") } + @Test("relay TTY registration completes before the interactive shell starts") + func relayTTYRegistrationCompletesBeforeInteractiveShellStarts() throws { + let fileManager = FileManager.default + let root = fileManager.temporaryDirectory + .appendingPathComponent("cmux-relay-ready-bootstrap-\(UUID().uuidString)") + let home = root.appendingPathComponent("home") + let bin = root.appendingPathComponent("bin") + let cmuxBin = home.appendingPathComponent(".cmux/bin") + let fakeCmux = cmuxBin.appendingPathComponent("cmux") + let fakeShell = bin.appendingPathComponent("test-shell") + let reportStatus = root.appendingPathComponent("report-status") + let shellStarted = root.appendingPathComponent("shell-started") + try fileManager.createDirectory(at: cmuxBin, withIntermediateDirectories: true) + try fileManager.createDirectory(at: bin, withIntermediateDirectories: true) + defer { try? fileManager.removeItem(at: root) } + + let persistentPTYExecHelper = try writePersistentPTYExecHelper(to: bin) + try """ + #!/bin/sh + if [ "${1:-}" = rpc ] && [ "${2:-}" = surface.report_tty ]; then + cmux_wait_count=0 + while [ "$cmux_wait_count" -lt 100 ] && [ ! -e "$CMUX_TEST_SHELL_STARTED" ]; do + cmux_wait_count=$((cmux_wait_count + 1)) + sleep 0.01 + done + if [ -e "$CMUX_TEST_SHELL_STARTED" ]; then + printf raced > "$CMUX_TEST_REPORT_STATUS" + else + printf ready > "$CMUX_TEST_REPORT_STATUS" + fi + fi + printf '{"ok":true}\\n' + """.write(to: fakeCmux, atomically: true, encoding: .utf8) + try fileManager.setAttributes([.posixPermissions: 0o700], ofItemAtPath: fakeCmux.path) + try """ + #!/bin/sh + : > "$CMUX_TEST_SHELL_STARTED" + cmux_wait_count=0 + while [ "$cmux_wait_count" -lt 100 ] && [ ! -s "$CMUX_TEST_REPORT_STATUS" ]; do + cmux_wait_count=$((cmux_wait_count + 1)) + sleep 0.01 + done + cat "$CMUX_TEST_REPORT_STATUS" + """.write(to: fakeShell, atomically: true, encoding: .utf8) + try fileManager.setAttributes([.posixPermissions: 0o700], ofItemAtPath: fakeShell.path) + + let script = RemoteInteractiveShellBootstrapBuilder.script( + remoteRelayPort: 64011, + shellFeatures: "ssh-env,ssh-terminfo" + ) + let result = try runShell(script, environment: [ + "CMUX_BOOTSTRAP_TTY": "ttys990", + "CMUX_PERSISTENT_PTY_EXEC_HELPER": persistentPTYExecHelper.path, + "CMUX_SSH_ATTEMPT_ID": "44444444-4444-4444-4444-444444444444", + "CMUX_TERMINAL_LIFECYCLE_ID": "33333333-3333-3333-3333-333333333333", + "CMUX_TEST_REPORT_STATUS": reportStatus.path, + "CMUX_TEST_SHELL_STARTED": shellStarted.path, + "CMUX_WORKSPACE_ID": "11111111-1111-1111-1111-111111111111", + "HOME": home.path, + "PATH": "\(bin.path):/usr/bin:/bin", + "SHELL": fakeShell.path, + ]) + + #expect(result.status == 0, "stdout: \(result.stdout)\nstderr: \(result.stderr)") + #expect(result.stdout == "ready") + } + @Test func whitespaceOnlyCommandDoesNotAddBootstrapWork() { let bootstrap = RemoteInitialCommandBootstrap(command: " \n\t ") diff --git a/cmuxTests/RemoteResumeBindingTests.swift b/cmuxTests/RemoteResumeBindingTests.swift index dc2c54fe1179..4d733c67972e 100644 --- a/cmuxTests/RemoteResumeBindingTests.swift +++ b/cmuxTests/RemoteResumeBindingTests.swift @@ -184,6 +184,36 @@ struct RemoteResumeBindingTests { )) } + @Test + func relayDeliveryTargetProvenanceOverridesSpoofedWorkspace() throws { + let workspaceID = UUID() + let spoofedWorkspaceID = UUID() + let request: [String: Any] = [ + "id": "relay-delivery-target", + "method": "agent.resolve_delivery_target", + "params": [ + "tty_name": "0", + "tty_resolution": "reported_tty", + "_cmux_remote_workspace_id": spoofedWorkspaceID.uuidString, + ], + ] + + let rewritten = WorkspaceRemoteRelayCommandRewriter( + remoteWorkspaceID: workspaceID, + remoteRelayTokenHex: String(repeating: "a", count: 64) + ).rewriteRemoteRelayCommandLine( + try requestData(request), + workspaceAliases: [:], + surfaceAliases: [:] + ) + let rewrittenRequest = try jsonRequest(rewritten) + let params = try #require(rewrittenRequest["params"] as? [String: Any]) + + #expect(params["_cmux_remote_workspace_id"] as? String == workspaceID.uuidString) + #expect(params["tty_name"] as? String == "0") + #expect(params["tty_resolution"] as? String == "reported_tty") + } + @Test func remoteResumeProvenanceRequiresExactMethodAndUntamperedAuthentication() throws { let workspaceID = UUID() diff --git a/cmuxTests/RemoteShellPromptRelayTests.swift b/cmuxTests/RemoteShellPromptRelayTests.swift index 0c5e950c6ada..2165ed6b7825 100644 --- a/cmuxTests/RemoteShellPromptRelayTests.swift +++ b/cmuxTests/RemoteShellPromptRelayTests.swift @@ -8,6 +8,13 @@ import Testing @testable import cmux #endif +private let remoteShellPromptFishExecutablePath = [ + "/opt/homebrew/bin/fish", + "/usr/local/bin/fish", + "/usr/bin/fish", + "/bin/fish", +].first { FileManager.default.isExecutableFile(atPath: $0) } + struct RemoteShellPromptRelayTests { @Test("remote zsh prompt reports Git metadata through the relay") func remoteZshPromptReportsGitMetadataThroughRelay() throws { @@ -73,6 +80,79 @@ struct RemoteShellPromptRelayTests { ), Comment(rawValue: output)) } + @Test( + "remote fish retries TTY registration until the relay acknowledges it", + .enabled(if: remoteShellPromptFishExecutablePath != nil) + ) + func remoteFishRetriesTTYRegistrationUntilAcknowledged() throws { + let fish = try #require(remoteShellPromptFishExecutablePath) + let integration = try #require( + RemoteInteractiveShellBootstrapBuilder.bundledShellIntegrationScript(named: "fish/config.fish") + ) + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-fish-relay-tty-\(UUID().uuidString)", isDirectory: true) + let binDirectory = directory.appendingPathComponent("bin", isDirectory: true) + let integrationFile = directory.appendingPathComponent("config.fish") + let cmuxFile = binDirectory.appendingPathComponent("cmux") + let logFile = directory.appendingPathComponent("relay.log") + try FileManager.default.createDirectory(at: binDirectory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + + try integration.write(to: integrationFile, atomically: true, encoding: .utf8) + try Data().write(to: logFile) + try """ + #!/bin/sh + if [ "${1:-}" = rpc ] && [ "${2:-}" = surface.report_tty ]; then + printf 'call\\n' >> "$CMUX_TEST_LOG" + [ "$(/usr/bin/wc -l < "$CMUX_TEST_LOG")" -gt 1 ] || exit 1 + fi + printf '{"ok":true}\\n' + """.write(to: cmuxFile, atomically: true, encoding: .utf8) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: cmuxFile.path) + + let process = Process() + let standardOutput = Pipe() + let standardError = Pipe() + process.executableURL = URL(fileURLWithPath: fish) + process.arguments = [ + "-c", + """ + source '\(integrationFile.path)' + set -g _CMUX_TTY_NAME ttys990 + set -g _CMUX_TTY_REPORTED 0 + _cmux_report_tty_once + _cmux_report_tty_once + for _cmux_i in (seq 1 20) + test -s "$CMUX_TEST_LOG"; and break + sleep 0.05 + end + printf 'calls=%s\\nreported=%s\\n' (count (cat "$CMUX_TEST_LOG")) "$_CMUX_TTY_REPORTED" + """, + ] + process.environment = [ + "CMUX_BUNDLED_CLI_PATH": cmuxFile.path, + "CMUX_SOCKET_PATH": "127.0.0.1:64011", + "CMUX_SSH_ATTEMPT_ID": "44444444-4444-4444-4444-444444444444", + "CMUX_TAB_ID": "11111111-1111-1111-1111-111111111111", + "CMUX_TERMINAL_LIFECYCLE_ID": "33333333-3333-3333-3333-333333333333", + "CMUX_TEST_LOG": logFile.path, + "CMUX_WORKSPACE_ID": "11111111-1111-1111-1111-111111111111", + "HOME": directory.path, + "PATH": "\(binDirectory.path):/usr/bin:/bin", + "TERM": "xterm-256color", + ] + process.standardOutput = standardOutput + process.standardError = standardError + try process.run() + process.waitUntilExit() + let output = String(decoding: standardOutput.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + let error = String(decoding: standardError.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + + #expect(process.terminationStatus == 0, "\(error)\n\(output)") + #expect(output.contains("calls=2"), Comment(rawValue: output)) + #expect(output.contains("reported=1"), Comment(rawValue: output)) + } + private func runPrompt( shell: String, integrationName: String, diff --git a/cmuxTests/ShellIntegrationSendTransportTests.swift b/cmuxTests/ShellIntegrationSendTransportTests.swift index 2c569e38aae6..6a6448a296c0 100644 --- a/cmuxTests/ShellIntegrationSendTransportTests.swift +++ b/cmuxTests/ShellIntegrationSendTransportTests.swift @@ -161,6 +161,8 @@ struct ShellIntegrationSendTransportTests { "CMUX_SOCKET_PATH": "127.0.0.1:63135", "CMUX_SURFACE_ID": "stale-surface", "CMUX_TAB_ID": "stale-workspace", + "CMUX_TERMINAL_LIFECYCLE_ID": "stale-lifecycle", + "CMUX_SSH_ATTEMPT_ID": "stale-attempt", "CMUX_WORKSPACE_ID": "stale-workspace", "HOME": directory.path, "PATH": "/usr/bin:/bin", @@ -177,6 +179,8 @@ struct ShellIntegrationSendTransportTests { #expect(process.terminationStatus == 0, "\(error)\n\(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("lifecycle=current-lifecycle"), Comment(rawValue: output)) + #expect(output.contains("attempt=current-attempt"), Comment(rawValue: output)) #expect(output.contains("surface="), Comment(rawValue: output)) #expect(output.contains("panel="), Comment(rawValue: output)) } @@ -361,15 +365,16 @@ struct ShellIntegrationSendTransportTests { tmux() { if [ "$1" = show-environment ]; then if [ "${2:-}" = -g ]; then - printf '%s\\n' 'CMUX_SOCKET_PATH=127.0.0.1:63135' 'CMUX_TAB_ID=stale-workspace' 'CMUX_WORKSPACE_ID=stale-workspace' + printf '%s\\n' 'CMUX_SOCKET_PATH=127.0.0.1:63135' 'CMUX_SSH_ATTEMPT_ID=stale-attempt' 'CMUX_TAB_ID=stale-workspace' 'CMUX_TERMINAL_LIFECYCLE_ID=stale-lifecycle' 'CMUX_WORKSPACE_ID=stale-workspace' else - printf '%s\\n' 'CMUX_SOCKET_PATH=127.0.0.1:55272' 'CMUX_TAB_ID=current-workspace' 'CMUX_WORKSPACE_ID=current-workspace' + printf '%s\\n' 'CMUX_SOCKET_PATH=127.0.0.1:55272' 'CMUX_SSH_ATTEMPT_ID=current-attempt' 'CMUX_TAB_ID=current-workspace' 'CMUX_TERMINAL_LIFECYCLE_ID=current-lifecycle' 'CMUX_WORKSPACE_ID=current-workspace' fi fi } _cmux_tmux_sync_cmux_environment - printf 'workspace=%s\\nsocket=%s\\nsurface=%s\\npanel=%s\\n' \ + printf 'workspace=%s\\nsocket=%s\\nlifecycle=%s\\nattempt=%s\\nsurface=%s\\npanel=%s\\n' \ "${CMUX_WORKSPACE_ID:-}" "${CMUX_SOCKET_PATH:-}" \ + "${CMUX_TERMINAL_LIFECYCLE_ID:-}" "${CMUX_SSH_ATTEMPT_ID:-}" \ "${CMUX_SURFACE_ID:-}" "${CMUX_PANEL_ID:-}" """ }