Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
14 changes: 14 additions & 0 deletions CLI/CMUXCLI+SSHPTYAttachBridge.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,20 @@ extension CMUXCLI {
return exitCode.isWrapperRetryable
}

/// True when the persistent attach wrapper will retry this failure itself.
///
/// The wrapper prints its own "reattaching (attempt n/limit)" notice, so
/// also printing `Error: ...` renders a recovered reconnect as a hard
/// failure in the user's terminal. Failures the wrapper will not retry
/// still print normally, and so does every non-attach command.
func attachWrapperReportsFailureItself(_ error: Error) -> Bool {
guard let cliError = error as? CLIError,
let exitCode = SSHPTYAttachExitCode(rawValue: cliError.exitCode) else {
return false
}
return sshPTYAttachWrapperWillRetry(exitCode)
}

func sshPTYAttachBridgeClosedExitCode(
receivedLiveOutput: Bool,
readyUptime: TimeInterval
Expand Down
4 changes: 3 additions & 1 deletion CLI/cmux.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36367,7 +36367,9 @@ struct CMUXTermMain {
do {
try cli.run()
} catch {
CMUXCLIOutput.writeStandardError("Error: \(error)\n")
if !cli.attachWrapperReportsFailureItself(error) {
CMUXCLIOutput.writeStandardError("Error: \(error)\n")
}
let exitCode = (error as? CLIError)?.exitCode ?? 1
exit(exitCode)
}
Expand Down
28 changes: 27 additions & 1 deletion Sources/Workspace.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2750,6 +2750,24 @@ final class Workspace: Identifiable, ObservableObject {
}
}

/// Retracts daemon errors that a later ready daemon resolved.
///
/// Call only once the daemon reports `.ready`: every daemon error recorded
/// before that point describes an outage the reconnect state machine has
/// since healed, so keeping it would leave a red sidebar entry as the last
/// word on a working workspace.
func clearResolvedRemoteDaemonSidebarArtifacts() {
// A ready daemon only proves the management lane recovered. When the
// workspace has no remote terminal session, its terminal has fallen
// back to a local shell while the row still reads "Connected", and
// retracting here would erase the only sign that anything went wrong.
// Keep the errors visible until a remote terminal is actually alive.
guard hasActiveRemoteTerminalSessions else { return }
logEntries.removeAll { entry in
entry.source == "remote-daemon" && entry.level == .error
}
Comment on lines +2760 to +2768

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

rg -n -C 8 --glob '*.swift' \
  'hasActiveRemoteTerminalSessions|activeRemoteTerminalSessionCount|activeRemoteTerminalSurfaceIds|trackRemoteTerminalSurface|markRemoteTerminalSessionLaunching|untrackRemoteTerminalSurface|applyRemoteDaemonStatusUpdate|clearResolvedRemoteDaemonSidebarArtifacts|clearProxyOnlyRemoteSidebarArtifacts' \
  Sources cmuxTests

Repository: manaflow-ai/cmux

Length of output: 50373


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

# Inspect focused declarations, lifecycle transitions, and cleanup call sites.
sed -n '1,220p' Sources/Workspace+RemoteTerminalLiveness.swift
printf '\n--- Workspace line ranges near declarations and helper ---\n'
sed -n '2650,2775p;5640,5652p;6050,6185p' Sources/Workspace.swift
printf '\n--- focused call sites ---\n'
rg -n -C 6 --glob '*.swift' \
  'clearResolvedRemoteDaemonSidebarArtifacts\(|clearProxyOnlyRemoteDaemonSidebarArtifacts\(|clearProxyOnlyRemoteSidebarArtifacts\(|markRemoteTerminalSessionLaunching\(|markRemoteTerminalSessionConnected\(|trackRemoteTerminalSurface\(|activeRemoteTerminalSessionCount =|hasActiveRemoteTerminalSessions' \
  Sources

Repository: manaflow-ai/cmux

Length of output: 50372


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

cat -n Sources/Workspace.swift | sed -n '6967,7005p'
printf '\n--- all Workspace calls to daemon/sidebar cleanup helpers ---\n'
rg -n -C 4 --glob '*.swift' \
  'clearResolvedRemoteDaemonSidebarArtifacts\(|clearProxyOnlyRemoteDaemonSidebarArtifacts\(\)|clearProxyOnlyRemoteSidebarArtifacts\(\)' Sources | sed -n '1,260p'
printf '\n--- active session count and surface phase update context ---\n'
cat -n Sources/Workspace.swift | sed -n '6660,6820p;6470,6535p'
printf '\n--- remote daemon status transition call sites ---\n'
rg -n -C 3 --glob '*.swift' 'remoteDaemonStatus \(.\)|WorkspaceRemoteDaemonStatus|remoteDaemonStatusUpdate|applyRemoteDaemonStatusUpdate' Sources

Repository: manaflow-ai/cmux

Length of output: 25510


Gate resolved daemon-error cleanup on a connected remote terminal, not just an active session count.

trackRemoteTerminalSurface adds the panel to activeRemoteTerminalSurfaceIds and increments activeRemoteTerminalSessionCount before markRemoteTerminalSessionLaunching records .launching. If remoteDaemonStatus changes to .ready before RemoteTerminalLiveness records .connected, clearResolvedRemoteDaemonSidebarArtifacts() removes daemon .error entries while no remote PTY is live. Use the authoritative .connected session state for this cleanup, or reapply cleanup on the later connect transition.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@Sources/Workspace.swift` around lines 2760 - 2768, Update
clearResolvedRemoteDaemonSidebarArtifacts so daemon error entries are removed
only when an authoritative remote terminal session is in the .connected state,
not merely when hasActiveRemoteTerminalSessions is true; alternatively, invoke
the cleanup again when RemoteTerminalLiveness records the later .connected
transition.

Sources: Path instructions, MCP tools

}

private func remoteNotificationCooldownKey(target: String) -> String? {
let rawTarget = (remoteConfiguration?.destination ?? target)
.trimmingCharacters(in: .whitespacesAndNewlines)
Expand Down Expand Up @@ -6955,7 +6973,15 @@ final class Workspace: Identifiable, ObservableObject {
// #8917: a transport bounce that re-bootstrapped successfully is
// not a workspace failure, so retract its sidebar error the same
// way the connection-state path retracts on `.connected`.
clearProxyOnlyRemoteDaemonSidebarArtifacts()
//
// A ready daemon has resolved every daemon error recorded before
// it, so retract all of them rather than only the proxy-only
// subset. Relay bounces publish `.error` details that already say
// "retrying in 2 seconds" and always schedule a reconnect; leaving
// those behind made a fully recovered reconnect read as a red
// failure in the sidebar. Errors the daemon never recovers from
// still persist, because this only runs on `.ready`.
clearResolvedRemoteDaemonSidebarArtifacts()
}
return
}
Expand Down
131 changes: 115 additions & 16 deletions cmuxTests/WorkspaceRemoteDaemonRecoveryTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,7 @@ struct WorkspaceRemoteDaemonRecoveryTests {
/// on the workspace's sidebar row.
@Test
func recoveredDaemonTransportBounceClearsSidebarDaemonError() {
let workspace = Workspace()
let config = WorkspaceRemoteConfiguration(
destination: "dev@example.com",
port: 22,
identityFile: nil,
sshOptions: [],
localProxyPort: nil,
relayPort: 64_021,
relayID: String(repeating: "c", count: 16),
relayToken: String(repeating: "d", count: 64),
localSocketPath: "/tmp/cmux-debug-test.sock",
terminalStartupCommand: "ssh dev@example.com",
preserveAfterTerminalExit: true,
skipDaemonBootstrap: true
)
workspace.configureRemoteConnection(config, autoConnect: false)
let workspace = makeRemoteWorkspace()

workspace.applyRemoteDaemonStatusUpdate(
WorkspaceRemoteDaemonStatus(state: .ready),
Expand Down Expand Up @@ -61,4 +46,118 @@ struct WorkspaceRemoteDaemonRecoveryTests {
"The workspace row must not keep rendering the recovered daemon error"
)
}

/// A reverse-relay bounce publishes a daemon error whose own detail says it
/// is retrying, and the reconnect state machine always schedules that retry.
/// Once the daemon reports ready again the workspace is healthy, so the
/// sidebar must not keep a red row for the outage that already healed.
@Test
func recoveredRelayBounceClearsSidebarDaemonError() {
let workspace = makeRemoteWorkspace()

for detail in [
"Remote SSH relay unavailable; retrying in 2 seconds",
"Remote SSH relay port unavailable; retrying in 2 seconds",
] {
workspace.applyRemoteDaemonStatusUpdate(
WorkspaceRemoteDaemonStatus(state: .error, detail: detail),
target: "dev@example.com"
)
}

#expect(
workspace.logEntries.contains { $0.source == "remote-daemon" && $0.level == .error },
"The relay bounce should be recorded while the daemon is still down"
)

workspace.applyRemoteDaemonStatusUpdate(
WorkspaceRemoteDaemonStatus(state: .ready),
target: "dev@example.com"
)

#expect(
workspace.logEntries.contains { $0.source == "remote-daemon" && $0.level == .error } == false,
"A relay bounce the daemon recovered from must not stay a sidebar error"
)
}

/// The retraction is tied to the daemon actually recovering, so an outage
/// that never reaches ready keeps its sidebar error.
@Test
func daemonErrorWithoutRecoveryKeepsSidebarEntry() {
let workspace = makeRemoteWorkspace()

workspace.applyRemoteDaemonStatusUpdate(
WorkspaceRemoteDaemonStatus(
state: .error,
detail: "Remote SSH relay unavailable; retrying in 2 seconds"
),
target: "dev@example.com"
)
workspace.applyRemoteDaemonStatusUpdate(
WorkspaceRemoteDaemonStatus(state: .bootstrapping, detail: "Reconnecting"),
target: "dev@example.com"
)

#expect(
workspace.logEntries.contains { $0.source == "remote-daemon" && $0.level == .error },
"An unrecovered daemon outage must keep reporting itself"
)
}

/// Retraction must not paper over a workspace whose remote terminal died:
/// the daemon can be ready while the surface has fallen back to a local
/// shell and the row still reads "Connected". The daemon error is then the
/// only visible sign that the workspace is not really remote.
@Test
func daemonReadyWithoutRemoteTerminalKeepsSidebarDaemonError() {
let workspace = makeRemoteWorkspace(withRemoteTerminal: false)

workspace.applyRemoteDaemonStatusUpdate(
WorkspaceRemoteDaemonStatus(
state: .error,
detail: "Remote SSH relay unavailable; retrying in 2 seconds"
),
target: "dev@example.com"
)
workspace.applyRemoteDaemonStatusUpdate(
WorkspaceRemoteDaemonStatus(state: .ready),
target: "dev@example.com"
)

#expect(
workspace.hasActiveRemoteTerminalSessions == false,
"This case is about a workspace with no live remote terminal"
)
#expect(
workspace.logEntries.contains { $0.source == "remote-daemon" && $0.level == .error },
"A ready daemon with no remote terminal session must not clear the error"
)
}

/// Builds a remote workspace. `withRemoteTerminal` mirrors a workspace whose
/// surface is actually attached to the remote host; without it the workspace
/// models the fallback case where the terminal is no longer remote.
private func makeRemoteWorkspace(withRemoteTerminal: Bool = true) -> Workspace {
let workspace = Workspace()
let config = WorkspaceRemoteConfiguration(
destination: "dev@example.com",
port: 22,
identityFile: nil,
sshOptions: [],
localProxyPort: nil,
relayPort: 64_021,
relayID: String(repeating: "c", count: 16),
relayToken: String(repeating: "d", count: 64),
localSocketPath: "/tmp/cmux-debug-test.sock",
terminalStartupCommand: "ssh dev@example.com",
preserveAfterTerminalExit: true,
skipDaemonBootstrap: true
)
workspace.configureRemoteConnection(config, autoConnect: false)
if withRemoteTerminal {
workspace.trackRemoteTerminalSurface(UUID())
}
return workspace
}
}