Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
2219e55
test: cover authoritative SSH terminal liveness
Jul 28, 2026
daa6739
fix: derive SSH status from terminal liveness
Jul 28, 2026
a671d84
fix: close SSH terminal lifecycle races
Jul 28, 2026
4a36c33
fix: authenticate SSH terminal readiness
Jul 28, 2026
28e95a4
Merge remote-tracking branch 'origin/main' into issue-9068-stale-ssh-…
Jul 28, 2026
40843eb
fix: bind SSH liveness to terminal authority
Jul 29, 2026
1e7c376
Merge remote-tracking branch 'origin/main' into issue-9068-stale-ssh-…
Jul 29, 2026
79679f2
fix: make Dock SSH readiness transactional
Jul 29, 2026
d8442e1
Merge remote-tracking branch 'origin/main' into issue-9068-stale-ssh-…
Jul 29, 2026
69835ec
test: assert remote terminal end acceptance
Jul 29, 2026
32099ee
test: reject retired PTY lifecycle readiness
Jul 29, 2026
f68c6e3
fix: revalidate PTY lifecycle at readiness commit
Jul 29, 2026
71faa1d
Merge remote-tracking branch 'origin/main' into issue-9068-stale-ssh-…
Jul 29, 2026
f222eb5
test: cover remote readiness lifecycle races
Jul 29, 2026
990c896
fix: harden remote terminal lifecycle ownership
Jul 29, 2026
0df2518
Merge remote-tracking branch 'origin/main' into issue-9068-stale-ssh-…
Jul 29, 2026
d21edba
test: cover stale remote terminal generations
Jul 29, 2026
ee64a06
fix: authenticate remote terminal lifecycle callbacks
Jul 29, 2026
34a04cc
Merge remote-tracking branch 'origin/main' into issue-9068-stale-ssh-…
Jul 29, 2026
48b78ba
fix: bound remote lifecycle commit side effects
Jul 29, 2026
8d33f12
chore: document remote lifecycle ownership boundaries
Jul 29, 2026
c2df39c
test: cover reordered remote readiness callbacks
Jul 29, 2026
b8c00ed
fix: order remote terminal lifecycle callbacks
Jul 29, 2026
bc3c755
test: cover remaining SSH lifecycle ordering gaps
Jul 29, 2026
4bb94f1
fix: close remaining SSH lifecycle ordering gaps
Jul 29, 2026
14ae938
test: cover lossy SSH liveness reconciliation
Jul 29, 2026
d29b50e
fix: make SSH liveness reconciliation resilient
Jul 29, 2026
f2c694e
test: cover remaining SSH liveness races
Jul 29, 2026
23eb81e
fix: close remaining SSH liveness races
Jul 29, 2026
e2292a1
test: cover Mosh and transient SSH readiness
Jul 29, 2026
8256a14
fix: make terminal readiness authoritative
Jul 29, 2026
e40c75f
Merge remote-tracking branch 'origin/main' into issue-9068-stale-ssh-…
Jul 29, 2026
376fdbb
test: cover premature terminal readiness
Jul 29, 2026
30958ff
fix: require proven terminal readiness
Jul 29, 2026
b932a0b
Merge remote-tracking branch 'origin/main' into issue-9068-stale-ssh-…
Jul 29, 2026
506827d
test: pass Dock readiness attempt generation
Jul 29, 2026
5f5f178
test: cover remote lifecycle review regressions
Jul 29, 2026
47adc66
fix: preserve remote lifecycle routing
Jul 29, 2026
32676ec
Merge remote-tracking branch 'origin/main' into issue-9068-stale-ssh-…
Jul 29, 2026
3fb4237
fix: retire orphaned remote lifecycles
Jul 29, 2026
67b1646
test: cover raw SSH readiness gating
Jul 29, 2026
f4003be
fix: decouple raw SSH readiness reporting
Jul 29, 2026
ad45ff6
test: cover restored SSH lifecycle reporting
Jul 29, 2026
8dfe003
fix: restore SSH lifecycle authority
Jul 29, 2026
b6866f7
test: cover SSH lifecycle review regressions
Jul 29, 2026
90f158b
fix: close SSH lifecycle review gaps
Jul 29, 2026
ad80a66
test: cover bounded SSH readiness lifecycle
Jul 29, 2026
0d8775f
fix: bound persistent SSH readiness retries
Jul 29, 2026
f200aef
test: expose queued SSH readiness duplicates
Jul 29, 2026
7559341
fix: coalesce persistent SSH readiness delivery
Jul 29, 2026
aa067d2
Merge remote-tracking branch 'origin/main' into issue-9068-stale-ssh-…
Jul 29, 2026
2aef5ee
fix: compile remote lifecycle app adapters
Jul 29, 2026
c2d7bc5
Merge branch 'main' of https://github.com/manaflow-ai/cmux into issue…
Jul 30, 2026
168910a
fix: satisfy ssh readiness closeout policy
Jul 30, 2026
b7d8b52
Merge branch 'main' of https://github.com/manaflow-ai/cmux into issue…
Jul 30, 2026
5ac19c1
Merge branch 'main' of https://github.com/manaflow-ai/cmux into issue…
Jul 30, 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
33 changes: 13 additions & 20 deletions CLI/cmux.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9236,13 +9236,8 @@ struct CMUXCLI {
localCLIPath: resolvedExecutableURL()?.path,
foregroundAuthToken: deferredRemoteReconnectToken
)
let sshConnectionTimingCommandScript = sshConnectionTimingLocalCommandScript(
target: sshOptions.displayDestination,
relayPort: sshOptions.remoteRelayPort
)
let combinedLocalCommandScript = combinedLocalShellScript([
deferredRemoteReconnectCommandScript,
sshConnectionTimingCommandScript,
])
let configuredForegroundAuthToken = deferredRemoteReconnectCommandScript == nil
? nil
Expand Down Expand Up @@ -10050,9 +10045,11 @@ struct CMUXCLI {
" 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_terminal_connected='{\"workspace_id\":\"__CMUX_WORKSPACE_ID__\",\"surface_id\":\"__CMUX_SURFACE_ID__\",\"relay_port\":\(remoteRelayPort)}'",
" 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",
" if [ -n \"${cmux_relay_terminal_connected:-}\" ]; then env -u CMUX_SOCKET CMUX_SOCKET_PATH=\"127.0.0.1:\(remoteRelayPort)\" \"$cmux_relay_cli\" rpc workspace.remote.terminal_session_connected \"$cmux_relay_terminal_connected\" >/dev/null 2>&1 || true; fi",
" env -u CMUX_SOCKET CMUX_SOCKET_PATH=\"127.0.0.1:\(remoteRelayPort)\" \"$cmux_relay_cli\" rpc surface.ports_kick \"$cmux_relay_ports_kick\" >/dev/null 2>&1 || true",
" ) </dev/null >/dev/null 2>&1 & unset cmux_relay_cli",
" fi",
Expand Down Expand Up @@ -12641,6 +12638,17 @@ struct CMUXCLI {
try Self.writeAll(fd: fd, data: handshakeData)
attachmentToken = try readSSHPTYBridgeReady(fd: fd)
bridgeReachedReady = true
if let surfaceID {
_ = try? client.sendV2(
method: "workspace.remote.terminal_session_connected",
params: [
"workspace_id": workspaceId,
"surface_id": surfaceID,
"session_id": sessionID,
"lifecycle_id": lifecycleID,
]
)
}
} catch {
let sessionNotFound = requireExisting &&
(error as? CLIError)?.exitCode == SSHPTYAttachExitCode.sessionNotFound.rawValue
Expand Down Expand Up @@ -12990,21 +12998,6 @@ struct CMUXCLI {
].joined(separator: " ")
}

private func sshConnectionTimingLocalCommandScript(target: String, relayPort: Int) -> String {
let escapedTarget = target
.replacingOccurrences(of: "\\", with: "\\\\")
.replacingOccurrences(of: "\"", with: "\\\"")
return [
"cmux_ssh_log_path=\"\";",
"if [ -r /tmp/cmux-last-debug-log-path ]; then cmux_ssh_log_path=\"$(tr -d '\\r\\n' < /tmp/cmux-last-debug-log-path 2>/dev/null || true)\"; fi;",
"if [ -n \"$cmux_ssh_log_path\" ]; then",
"cmux_ssh_ts=\"$(python3 -c 'from datetime import datetime, timezone; print(datetime.now(timezone.utc).isoformat(timespec=\"milliseconds\").replace(\"+00:00\", \"Z\"))' 2>/dev/null || date -u +%Y-%m-%dT%H:%M:%SZ)\";",
"printf '%s [cmux-cli] cli.ssh.handshake target=\(escapedTarget) relayPort=\(relayPort) stage=ssh.connected workspace=%s surface=%s\\n' \"$cmux_ssh_ts\" \"${CMUX_WORKSPACE_ID:-nil}\" \"${CMUX_SURFACE_ID:-nil}\" >> \"$cmux_ssh_log_path\";",
"fi;",
"unset cmux_ssh_log_path cmux_ssh_ts;",
].joined(separator: " ")
}

private func shouldDeferRemoteReconnect(in options: [String]) -> Bool {
sshOptionsSupportReusableForegroundAuth(options)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,16 @@ internal import Foundation
/// Sendable enum the app maps.
extension ControlCommandCoordinator {
/// `v2RawString`: the raw string value, untrimmed, or `nil`.
func rawString(_ params: [String: JSONValue], _ key: String) -> String? {
nonisolated func rawString(_ params: [String: JSONValue], _ key: String) -> String? {
guard case .string(let value)? = params[key] else { return nil }
return value
}

/// `v2OptionalTrimmedRawString`: trimmed raw string, `nil` when empty.
func optionalTrimmedRawString(_ params: [String: JSONValue], _ key: String) -> String? {
nonisolated func optionalTrimmedRawString(
_ params: [String: JSONValue],
_ key: String
) -> String? {
let trimmed = rawString(params, key)?.trimmingCharacters(in: .whitespacesAndNewlines)
return (trimmed?.isEmpty == false) ? trimmed : nil
}
Expand Down Expand Up @@ -146,12 +149,12 @@ extension ControlCommandCoordinator {

/// `v2StrictInt`: an exact integer only — a non-boolean integral number or a
/// parsable integer string; fractional or non-finite numbers are rejected.
func strictInt(_ params: [String: JSONValue], _ key: String) -> Int? {
nonisolated func strictInt(_ params: [String: JSONValue], _ key: String) -> Int? {
strictIntValue(params[key])
}

/// `v2StrictIntAny`: the strict-int rule for a single JSON value.
func strictIntValue(_ raw: JSONValue?) -> Int? {
nonisolated func strictIntValue(_ raw: JSONValue?) -> Int? {
switch raw {
case .int(let value):
return Int(value)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,11 @@ public final class ControlCommandCoordinator {
return workspaceList(request.params, context: context)
case "workspace.current":
return workspaceCurrent(request.params, context: context)
case "workspace.remote.terminal_session_connected":
return workspaceRemoteTerminalSessionConnected(
request.params,
context: context
)
case "window.list":
return windowList(context: context)
case "window.current":
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,112 @@
internal import Foundation

extension ControlCommandCoordinator {
/// `workspace.remote.terminal_session_connected` — record the terminal's
/// successful SSH/PTY handshake independently of auxiliary proxy state.
///
/// Persistent lifecycle authentication starts on the socket worker because
/// the broker owns that state on its serial queue. The exact generation is
/// retained and revalidated inside the command's single main-actor hop,
/// immediately before the workspace mutation.
nonisolated func workspaceRemoteTerminalSessionConnected(
_ params: [String: JSONValue],
context: (any ControlCommandContext)?
) -> ControlCallResult {
guard let workspaceID = string(params, "workspace_id").flatMap(UUID.init(uuidString:)) else {
return .err(code: "invalid_params", message: "Missing or invalid workspace_id", data: nil)
}
guard let surfaceID = string(params, "surface_id").flatMap(UUID.init(uuidString:)) else {
return .err(code: "invalid_params", message: "Missing or invalid surface_id", data: nil)
}
let relayPort = strictInt(params, "relay_port")
let sessionID = optionalTrimmedRawString(params, "session_id")
let lifecycleID = optionalTrimmedRawString(params, "lifecycle_id")
let invalidRelayPort = relayPort.map { $0 <= 0 || $0 > 65535 } ?? false
let hasRelayAuthority = relayPort != nil
let hasPersistentAuthority = sessionID != nil && lifecycleID != nil
if invalidRelayPort ||
(params["relay_port"] != nil && relayPort == nil) ||
(sessionID == nil) != (lifecycleID == nil) ||
hasRelayAuthority == hasPersistentAuthority {
return .err(
code: "invalid_params",
message: "Provide exactly one terminal authority: relay_port or session_id with lifecycle_id",
data: nil
)
}

guard let context else {
return .err(code: "unavailable", message: "Workspace context not available", data: nil)
}
let authority: ControlWorkspaceRemoteTerminalAuthority?
if let relayPort {
authority = .relayPort(relayPort)
} else if let sessionID,
let lifecycleID,
let owner = context.controlCurrentRemotePTYLifecycleOwner(
sessionID: sessionID,
lifecycleID: lifecycleID
),
owner.attachmentID == surfaceID.uuidString {
authority = .persistentTransport(owner.transportKey)
} else {
authority = nil
}

return context.controlResolveOnMain { seam in
let resolution: ControlWorkspaceRemoteTerminalSessionConnectedResolution
if let authority {
let authorityIsCurrent: Bool
switch authority {
case .relayPort:
authorityIsCurrent = true
case .persistentTransport(let transportKey):
if let sessionID, let lifecycleID {
authorityIsCurrent = seam.controlCurrentRemotePTYLifecycleOwner(
sessionID: sessionID,
lifecycleID: lifecycleID
) == ControlRemotePTYLifecycleOwner(
transportKey: transportKey,
attachmentID: surfaceID.uuidString
)
} else {
authorityIsCurrent = false
}
}
resolution = authorityIsCurrent
? seam.controlWorkspaceRemoteTerminalSessionConnected(
workspaceID: workspaceID,
surfaceID: surfaceID,
authority: authority
)
: .notFound
} else {
resolution = .notFound
}
switch resolution {
case .notFound:
return .err(code: "not_found", message: "Workspace not found", data: .object([
"workspace_id": .string(workspaceID.uuidString),
"workspace_ref": self.ref(.workspace, workspaceID),
"surface_id": .string(surfaceID.uuidString),
"surface_ref": self.ref(.surface, surfaceID),
"relay_port": relayPort.map { .int(Int64($0)) } ?? .null,
]))
case .resolved(let windowID, let resolvedWorkspaceID, let remoteStatus):
return .ok(.object([
"window_id": self.orNull(windowID?.uuidString),
"window_ref": self.ref(.window, windowID),
"workspace_id": self.orNull(resolvedWorkspaceID?.uuidString),
"workspace_ref": self.ref(.workspace, resolvedWorkspaceID),
"surface_id": .string(surfaceID.uuidString),
"surface_ref": self.ref(.surface, surfaceID),
"relay_port": relayPort.map { .int(Int64($0)) } ?? .null,
"remote": remoteStatus,
]))
}
}
}

/// `workspace.remote.terminal_session_end` — retire any persistent PTY
/// generation owned by the wrapper, then optionally record terminal end.
func workspaceRemoteTerminalSessionEnd(_ params: [String: JSONValue]) -> ControlCallResult {
Expand Down Expand Up @@ -43,7 +149,7 @@ extension ControlCommandCoordinator {
return .ok(.object([
"window_id": orNull(windowID?.uuidString),
"window_ref": ref(.window, windowID),
"workspace_id": .string(resolvedWorkspaceID.uuidString),
"workspace_id": orNull(resolvedWorkspaceID?.uuidString),
"workspace_ref": ref(.workspace, resolvedWorkspaceID),
"surface_id": .string(surfaceID.uuidString),
"surface_ref": ref(.surface, surfaceID),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/// The broker-owned transport attachment for one current PTY lifecycle.
public struct ControlRemotePTYLifecycleOwner: Sendable, Equatable {
/// The broker transport identity that owns the lifecycle.
public let transportKey: String
/// The exact attachment identifier registered for the lifecycle.
public let attachmentID: String

/// Creates a lifecycle owner snapshot.
///
/// - Parameters:
/// - transportKey: The broker transport identity.
/// - attachmentID: The exact registered attachment identifier.
public init(transportKey: String, attachmentID: String) {
self.transportKey = transportKey
self.attachmentID = attachmentID
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,35 @@ public protocol ControlWorkspaceContext: AnyObject {
sessionID: String
) -> ControlWorkspaceRemotePTYAttachEndResolution

/// Reads the broker-owned attachment for a persistent wrapper generation.
///
/// This requirement is nonisolated so worker-lane readiness validation
/// completes before the command's single main-actor mutation hop.
///
/// - Parameters:
/// - sessionID: The persistent PTY session.
/// - lifecycleID: The wrapper lifecycle generation.
/// - Returns: The current owner, or `nil` for an unknown or stale generation.
nonisolated func controlCurrentRemotePTYLifecycleOwner(
sessionID: String,
lifecycleID: String
) -> ControlRemotePTYLifecycleOwner?

/// Records an authoritative terminal handshake for
/// `workspace.remote.terminal_session_connected`.
///
/// - Parameters:
/// - workspaceID: The workspace id captured when the terminal launched.
/// - surfaceID: The connected terminal surface id.
/// - authority: The relay or broker transport authority already validated
/// on the socket worker.
/// - Returns: The connected-session resolution.
func controlWorkspaceRemoteTerminalSessionConnected(
workspaceID: UUID,
surfaceID: UUID,
authority: ControlWorkspaceRemoteTerminalAuthority
) -> ControlWorkspaceRemoteTerminalSessionConnectedResolution
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/// Records a remote terminal session-end for
/// `workspace.remote.terminal_session_end`.
///
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/// Authenticated authority for a terminal readiness report.
public enum ControlWorkspaceRemoteTerminalAuthority: Sendable, Equatable {
/// A non-persistent relay generation identified by its listening port.
case relayPort(Int)
/// A persistent PTY generation authenticated by its broker transport.
case persistentTransport(String)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
public import Foundation

/// The outcome of `workspace.remote.terminal_session_connected`, after the
/// coordinator has validated the workspace, surface, and optional relay port.
public enum ControlWorkspaceRemoteTerminalSessionConnectedResolution: Sendable, Equatable {
/// No tracked remote terminal matches the requested workspace and surface.
case notFound
/// The terminal handshake was recorded. `workspaceID` is absent when a
/// window-scoped Dock owns the terminal after its launch workspace closed.
case resolved(windowID: UUID?, workspaceID: UUID?, remoteStatus: JSONValue)
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ public enum ControlWorkspaceRemoteTerminalSessionEndResolution: Sendable, Equata
/// The workspace was not found (legacy `not_found` / "Workspace not found",
/// data carries workspace + surface + relay_port).
case notFound
/// The session end was recorded. Carries the owning window id (may be
/// absent), the resolved workspace id, and the bridged
/// `remoteStatusPayload()`.
case resolved(windowID: UUID?, workspaceID: UUID, remoteStatus: JSONValue)
/// The session end was recorded. `workspaceID` is absent when a
/// window-scoped Dock owns the terminal after its launch workspace closed.
case resolved(windowID: UUID?, workspaceID: UUID?, remoteStatus: JSONValue)
}
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,12 @@ public enum ControlCommandExecutionPolicy: Sendable, Equatable {
"workspace.remote.pty_detach",
"workspace.remote.pty_bridge",
"workspace.remote.pty_resize",
// Persistent readiness authenticates against broker-owned lifecycle
// state. The broker serializes that state on its own queue, so this
// command must never make the main actor wait behind tunnel work.
// Parsing and authentication run here; the final workspace/Dock
// mutation takes one synchronous controlResolveOnMain hop.
"workspace.remote.terminal_session_connected",
"remote.tmux.sessions",
"remote.tmux.attach",
"remote.tmux.detach",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,17 @@ extension ControlWorkspaceContext {
sessionID: String
) -> ControlWorkspaceRemotePTYAttachEndResolution { .notFound }

nonisolated func controlCurrentRemotePTYLifecycleOwner(
sessionID: String,
lifecycleID: String
) -> ControlRemotePTYLifecycleOwner? { nil }

func controlWorkspaceRemoteTerminalSessionConnected(
workspaceID: UUID,
surfaceID: UUID,
authority: ControlWorkspaceRemoteTerminalAuthority
) -> ControlWorkspaceRemoteTerminalSessionConnectedResolution { .notFound }

func controlWorkspaceRemoteTerminalSessionEnd(
workspaceID: UUID,
surfaceID: UUID,
Expand Down
Loading