Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
b0c6a3b
test(remote): reproduce PTY hub start wedge
austinywang Jul 29, 2026
9de72b5
fix(remote): isolate persistent PTY session startup
austinywang Jul 29, 2026
66ee8bc
Merge remote-tracking branch 'origin/main' into issue-8750-integration
austinywang Jul 29, 2026
6aad22a
test: bound zero-progress SSH PTY reattach churn
austinywang Jul 29, 2026
7cc29bb
fix: stop zero-progress SSH PTY attach loops
austinywang Jul 29, 2026
3343a17
test: prove concurrent PTY starts coalesce
austinywang Jul 29, 2026
9b15833
Fix SSH PTY retry policy target ownership
austinywang Jul 29, 2026
4f7fca6
fix: bound managed SSH PTY retry churn
austinywang Jul 29, 2026
a541bf5
fix: isolate stalled remote PTY attaches
austinywang Jul 29, 2026
77e3de7
fix: close remote PTY attach teardown races
austinywang Jul 29, 2026
10aacca
fix: preserve remote PTY session generations
austinywang Jul 29, 2026
d96bc69
fix: harden remote PTY lifecycle handoffs
austinywang Jul 29, 2026
b39e24d
fix: bound PTY exit output draining
austinywang Jul 29, 2026
575da56
Merge remote-tracking branch 'origin/main' into issue-8750-cmuxd-remo…
austinywang Jul 29, 2026
390cdc3
test: preserve remote PTY capacity failures
austinywang Jul 29, 2026
35faab7
fix: retry remote PTY capacity failures
austinywang Jul 29, 2026
f334859
test: bound remote PTY capacity recovery
austinywang Jul 29, 2026
b717dd6
fix: bound remote PTY start waiters
austinywang Jul 29, 2026
3ce3f98
Merge remote-tracking branch 'origin/main' into issue-8750-cmuxd-remo…
austinywang Jul 29, 2026
fc4eea2
test: update persistent PTY retry contract
austinywang Jul 29, 2026
9cf8c9b
test(remote): hide retained fast-exit generations
austinywang Jul 29, 2026
a1109a0
fix(remote): separate retained and live PTY state
austinywang Jul 29, 2026
9b29245
test: preserve daemon transport after PTY attach timeout
austinywang Jul 29, 2026
20725e8
fix: isolate PTY attach call timeouts
austinywang Jul 29, 2026
4ff9ded
test: cancel timed-out remote PTY attaches
austinywang Jul 29, 2026
52fcbf8
fix(remote): cancel timed-out PTY attach requests
austinywang Jul 29, 2026
e63a9da
fix(remote): bound PTY attach cancellation writes
austinywang Jul 29, 2026
622b302
fix(remote): use cancellable attach timeout timers
austinywang Jul 29, 2026
3762e09
test(remote): pin canceled start publication race
austinywang Jul 29, 2026
05d4570
fix(remote): linearize PTY start waiter cancellation
austinywang Jul 29, 2026
e316f1a
test(remote): assert timeout cancellation ordering
austinywang Jul 29, 2026
92b2c32
test(remote): expose completed attachment context leak
austinywang Jul 29, 2026
0a7cefe
fix(remote): release completed attachment contexts
austinywang Jul 29, 2026
c0ea226
test(remote): advertise attach cancellation in bridge fixture
austinywang Jul 29, 2026
4f49ea2
test(remote): expose canceled anonymous PTY retention
austinywang Jul 29, 2026
a9f9783
fix(remote): terminate canceled anonymous PTY starts
austinywang Jul 29, 2026
edd2fba
test(remote): distinguish replay from live PTY output
austinywang Jul 29, 2026
a5dbe7b
fix(remote): exclude replay from attach progress
austinywang Jul 29, 2026
d6a3855
test(remote): require cancellable attachment identities
austinywang Jul 29, 2026
0a68c39
fix(remote): require cancellable attachment ids
austinywang Jul 29, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 51 additions & 4 deletions CLI/CMUXCLI+SSHPTYAttachBridge.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Darwin
import Foundation
import CmuxFoundation

extension CLIError {
init(message: String, exitCode: SSHPTYAttachExitCode) {
Expand All @@ -8,14 +9,50 @@ extension CLIError {
}

extension CMUXCLI {
/// True when a persistent attach wrapper owns retrying a 254|255 failure.
/// True when a persistent attach wrapper has another general retry available.
/// Persistent wrappers export `CMUX_SSH_PTY_ATTACH_WRAPPER_CAN_RETRY=1`;
/// direct invocations leave it unset, so failures there always clean up.
func sshPTYAttachWrapperRetryPending() -> Bool {
(ProcessInfo.processInfo.environment["CMUX_SSH_PTY_ATTACH_WRAPPER_CAN_RETRY"] ?? "")
.trimmingCharacters(in: .whitespacesAndNewlines) == "1"
}

func sshPTYAttachWrapperWillRetry(_ exitCode: SSHPTYAttachExitCode) -> Bool {
guard sshPTYAttachWrapperRetryPending() else { return false }
if exitCode == .bridgeClosedWithoutProgress {
let environment = ProcessInfo.processInfo.environment
guard let retry = Int(environment["CMUX_SSH_PTY_ATTACH_NO_PROGRESS_RETRY"] ?? ""),
retry >= 0,
let limit = Int(environment["CMUX_SSH_PTY_ATTACH_NO_PROGRESS_LIMIT"] ?? ""),
limit > 0 else {
return false
}
return SSHPTYAttachExitCode.hasNoProgressRetryRemaining(
currentRetry: retry,
limit: limit
)
}
return exitCode.isWrapperRetryable
}

func sshPTYAttachBridgeClosedExitCode(
receivedOutput: Bool,
readyUptime: TimeInterval
) -> SSHPTYAttachExitCode {
let environment = ProcessInfo.processInfo.environment
let bridgeUptime = ProcessInfo.processInfo.systemUptime - readyUptime
guard sshPTYAttachWrapperRetryPending(),
environment["CMUX_SSH_PTY_ATTACH_NO_PROGRESS_RETRY"] != nil,
environment["CMUX_SSH_PTY_ATTACH_NO_PROGRESS_LIMIT"] != nil,
SSHPTYAttachExitCode.bridgeClosureMadeNoProgress(
receivedOutput: receivedOutput,
bridgeUptime: bridgeUptime
) else {
return .bridgeClosedSessionRunning
}
return .bridgeClosedWithoutProgress
}

func cleanupFailedSSHPTYAttach(
client: SocketClient,
workspaceId: String,
Expand Down Expand Up @@ -93,7 +130,8 @@ extension CMUXCLI {
surfaceID: String?,
sessionID: String,
lifecycleID: String,
intentionalOnly: Bool
intentionalOnly: Bool,
sessionRunningExitCode: SSHPTYAttachExitCode = .bridgeClosedSessionRunning
) throws -> Bool {
let reconciliationFailure = "ssh-pty-attach: bridge closed before remote PTY exit could be confirmed"
let response: [String: Any]
Expand Down Expand Up @@ -144,9 +182,18 @@ extension CMUXCLI {
(($0["session_id"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "") == sessionID
}
if !intentionalCleanup, sessionStillRunning {
let message: String
if sessionRunningExitCode == .bridgeClosedWithoutProgress {
message = String(
localized: "cli.sshPtyAttach.bridgeClosedWithoutProgress",
defaultValue: "ssh-pty-attach: bridge closed without receiving output while the remote PTY session is still running"
)
} else {
message = "ssh-pty-attach: bridge closed while remote PTY session is still running"
}
throw CLIError(
message: "ssh-pty-attach: bridge closed while remote PTY session is still running",
exitCode: SSHPTYAttachExitCode.bridgeClosedSessionRunning
message: message,
exitCode: sessionRunningExitCode
)
}
guard let surfaceID else { return true }
Expand Down
68 changes: 0 additions & 68 deletions CLI/SSHPTYAttachExitCode.swift

This file was deleted.

85 changes: 50 additions & 35 deletions CLI/cmux.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10259,9 +10259,13 @@ struct CMUXCLI {
var authArguments = sshArgumentsOverridingHostRemoteCommand(baseSSHArguments(options))
authArguments += ["-T", options.destination, "true"]
let authCommand = authArguments.map(shellQuote).joined(separator: " ")
let attachScript = buildSSHPTYAttachScriptBody(
let attachAttemptScript = buildSSHPTYAttachScriptBody(
remoteShellCommand: remoteShellCommand
)
let attachAttemptCommand = "/bin/sh -c \(shellQuote(attachAttemptScript))"
let attachScript = SSHPTYAttachExitCode.noProgressRetryLoopLines(
command: attachAttemptCommand
).joined(separator: "\n")
var authScriptLines: [String] = []
let sharingOptions = SSHConnectionSharingOptions()
let authenticationLockPath = sharingOptions.foregroundAuthenticationLockPath(
Expand Down Expand Up @@ -12422,31 +12426,13 @@ struct CMUXCLI {
"trap 'cmux_ssh_attach_signal_exit 129' HUP",
"trap 'cmux_ssh_attach_signal_exit 130' INT",
"trap 'cmux_ssh_attach_signal_exit 143' TERM",
] + sshPTYAttachRetryLoopLines(command: attachCommand)).joined(separator: "\n")
] + SSHPTYAttachExitCode.retryLoopLines(
command: attachCommand,
reauthenticates: false
)).joined(separator: "\n")
return "/bin/sh -c \(shellQuote(script))"
}

private func sshPTYAttachRetryLoopLines(command: String) -> [String] {
// Retryable 254|255 is owned by SSHPTYAttachExitCode; keep in sync with SSHPTYAttachStartupCommandBuilder.retryingAttachLines.
[
"cmux_ssh_attach_reconnect_limit=\"${CMUX_SSH_RECONNECT_LIMIT:-}\"\ncase \"$cmux_ssh_attach_reconnect_limit\" in '') cmux_ssh_attach_reconnect_limit='∞'; cmux_ssh_attach_reconnect_unbounded=1 ;; *[!0-9]*) cmux_ssh_attach_reconnect_limit=20; cmux_ssh_attach_reconnect_unbounded=0 ;; *) cmux_ssh_attach_reconnect_unbounded=0 ;; esac",
"cmux_ssh_attach_reconnect_delay=\"${CMUX_SSH_RECONNECT_DELAY_SECONDS:-2}\"\ncase \"$cmux_ssh_attach_reconnect_delay\" in ''|*[!0-9]*|0*) cmux_ssh_attach_reconnect_delay=2 ;; esac",
"cmux_ssh_attach_reconnect_max_delay=\"${CMUX_SSH_RECONNECT_MAX_DELAY_SECONDS:-30}\"\ncase \"$cmux_ssh_attach_reconnect_max_delay\" in ''|*[!0-9]*|0*) cmux_ssh_attach_reconnect_max_delay=30 ;; esac",
"if [ \"$cmux_ssh_attach_reconnect_delay\" -gt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_max_delay\"; fi",
"cmux_ssh_attach_reconnect_initial_delay=\"$cmux_ssh_attach_reconnect_delay\"",
"cmux_ssh_attach_retry=0",
"while :; do",
" if [ \"$cmux_ssh_attach_reconnect_unbounded\" -eq 1 ] || [ \"$cmux_ssh_attach_retry\" -lt \"$cmux_ssh_attach_reconnect_limit\" ]; then cmux_ssh_attach_can_retry=1; else cmux_ssh_attach_can_retry=0; fi\n CMUX_SSH_PTY_ATTACH_WRAPPER_CAN_RETRY=\"$cmux_ssh_attach_can_retry\" \(command)",
" cmux_ssh_attach_status=$?",
" case \"$cmux_ssh_attach_status\" in 254) cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_initial_delay\" ;; 255) ;; *) exit \"$cmux_ssh_attach_status\" ;; esac\n if [ \"$cmux_ssh_attach_reconnect_unbounded\" -eq 0 ] && [ \"$cmux_ssh_attach_retry\" -ge \"$cmux_ssh_attach_reconnect_limit\" ]; then exit \"$cmux_ssh_attach_status\"; fi",
" cmux_ssh_attach_retry=$((cmux_ssh_attach_retry + 1))",
" if [ -t 2 ]; then printf '\\n\\033[33m[cmux] remote PTY bridge closed; reattaching (attempt %s/%s).\\033[0m\\n' \"$cmux_ssh_attach_retry\" \"$cmux_ssh_attach_reconnect_limit\" >&2 || true; fi",
" if [ \"$cmux_ssh_attach_reconnect_delay\" -gt 0 ]; then sleep \"$cmux_ssh_attach_reconnect_delay\"; fi",
" if [ \"$cmux_ssh_attach_reconnect_delay\" -lt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=$((cmux_ssh_attach_reconnect_delay * 2)); if [ \"$cmux_ssh_attach_reconnect_delay\" -gt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_max_delay\"; fi; fi",
"done",
]
}

private func sshSessionTargetParams(
commandName: String,
workspaceOpt: String?,
Expand Down Expand Up @@ -12514,18 +12500,28 @@ struct CMUXCLI {
var bridgeReachedReady = false
var sessionLostWillRespawn = false
var wrapperWillRetrySameSurface = false
var noProgressRetryExhausted = false
var attachFinished = false
var attachmentToken = ""
func reconcileBridgeEnd(intentionalOnly: Bool) throws -> Bool {
func reconcileBridgeEnd(
intentionalOnly: Bool,
sessionRunningExitCode: SSHPTYAttachExitCode = .bridgeClosedSessionRunning
) throws -> Bool {
do {
return try reconcileSSHPTYBridgeEnd(
client: client, workspaceId: workspaceId, surfaceID: surfaceID,
sessionID: sessionID, lifecycleID: lifecycleID, intentionalOnly: intentionalOnly
sessionID: sessionID,
lifecycleID: lifecycleID,
intentionalOnly: intentionalOnly,
sessionRunningExitCode: sessionRunningExitCode
)
} catch let error as CLIError {
if SSHPTYAttachExitCode(rawValue: error.exitCode)?.isWrapperRetryable == true,
sshPTYAttachWrapperRetryPending() {
wrapperWillRetrySameSurface = true
if let exitCode = SSHPTYAttachExitCode(rawValue: error.exitCode) {
if sshPTYAttachWrapperWillRetry(exitCode) {
wrapperWillRetrySameSurface = true
} else if exitCode == .bridgeClosedWithoutProgress {
noProgressRetryExhausted = true
}
}
throw error
}
Expand All @@ -12541,7 +12537,8 @@ struct CMUXCLI {
attachmentID: attachmentID,
attachmentToken: attachmentToken,
retireLifecycle: !sessionLostWillRespawn && !wrapperWillRetrySameSurface,
clearLocalSurface: !bridgeReachedReady && !sessionLostWillRespawn
clearLocalSurface: (!bridgeReachedReady || noProgressRetryExhausted)
&& !sessionLostWillRespawn
&& !wrapperWillRetrySameSurface
)
}
Expand Down Expand Up @@ -12579,7 +12576,7 @@ struct CMUXCLI {
exitCode = SSHPTYAttachExitCode.classifyBridgeEstablishmentFailure(String(describing: error))
}
let closedGeneration = (error as? CLIError)?.v2Code == "pty_lifecycle_closed"
if !closedGeneration, exitCode.isWrapperRetryable, sshPTYAttachWrapperRetryPending() {
if !closedGeneration, sshPTYAttachWrapperWillRetry(exitCode) {
wrapperWillRetrySameSurface = true
}
if closedGeneration {
Expand Down Expand Up @@ -12618,6 +12615,7 @@ struct CMUXCLI {
}
var connectedFD: Int32?
var bridgeHandshakeSize = Self.currentCLITerminalSize()
var bridgeReadyUptime: TimeInterval = 0
do {
let host = (bridge["host"] as? String) ?? "127.0.0.1"
guard let port = cliStrictInt(bridge["port"]), port > 0, port <= 65535 else {
Expand All @@ -12641,15 +12639,18 @@ struct CMUXCLI {
try Self.writeAll(fd: fd, data: handshakeData)
attachmentToken = try readSSHPTYBridgeReady(fd: fd)
bridgeReachedReady = true
bridgeReadyUptime = ProcessInfo.processInfo.systemUptime
} catch {
let sessionNotFound = requireExisting &&
(error as? CLIError)?.exitCode == SSHPTYAttachExitCode.sessionNotFound.rawValue
if sessionNotFound {
sessionLostWillRespawn = true
}
let preReadyRetryable = (error as? CLIError)
.flatMap { SSHPTYAttachExitCode(rawValue: $0.exitCode) }?.isWrapperRetryable == true
if preReadyRetryable, sshPTYAttachWrapperRetryPending() {
let preReadyExitCode = (error as? CLIError)
.flatMap { SSHPTYAttachExitCode(rawValue: $0.exitCode) }
let preReadyRetryable = preReadyExitCode?.isWrapperRetryable == true
if let preReadyExitCode,
sshPTYAttachWrapperWillRetry(preReadyExitCode) {
wrapperWillRetrySameSurface = true
}
if let connectedFD { Darwin.close(connectedFD) }
Expand Down Expand Up @@ -12697,22 +12698,36 @@ struct CMUXCLI {
throw CLIError(message: "ssh-pty-attach: bridge write failed")
}
var reconnectInputFilterStopRequested = false
var receivedOutput = false

var outputBuffer = [UInt8](repeating: 0, count: 32768)
while true {
let count = Darwin.read(fd, &outputBuffer, outputBuffer.count)
if count > 0 {
receivedOutput = true
reconnectInputFilterControl?.stopFilteringBeforeFirstOutput(unlessAlreadyRequested: &reconnectInputFilterStopRequested)
cliWriteStdout(Data(outputBuffer.prefix(count)))
} else if count == 0 {
resizeMonitor.cancel()
_ = try reconcileBridgeEnd(intentionalOnly: false)
_ = try reconcileBridgeEnd(
intentionalOnly: false,
sessionRunningExitCode: sshPTYAttachBridgeClosedExitCode(
receivedOutput: receivedOutput,
readyUptime: bridgeReadyUptime
)
)
attachFinished = true
return
} else if errno != EINTR {
if sshPTYBridgeReadErrorIsEOF(errno) {
resizeMonitor.cancel()
_ = try reconcileBridgeEnd(intentionalOnly: false)
_ = try reconcileBridgeEnd(
intentionalOnly: false,
sessionRunningExitCode: sshPTYAttachBridgeClosedExitCode(
receivedOutput: receivedOutput,
readyUptime: bridgeReadyUptime
)
)
attachFinished = true
return
}
Expand Down
Loading