Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 2 additions & 1 deletion App/CompositionRoot.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ final class CompositionRoot {
vault: vault, settings: { vncSettings.value }, scrollSpeed: { generalSettings.value.scrollSpeed }),
rdpDriver: FreeRDPSessionDriver(
vault: vault, trustStore: trustStore, settings: { rdpSettings.value },
scrollSpeed: { generalSettings.value.scrollSpeed }))
scrollSpeed: { generalSettings.value.scrollSpeed }),
remoteSessionEnd: { generalSettings.value.remoteSessionEnd })
} catch {
startupError = error.localizedDescription
}
Expand Down
43 changes: 35 additions & 8 deletions App/Sessions/SessionCoordinator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,13 @@ final class SessionCoordinator {
private let localDriver: any LocalTerminalDriving
private let vncDriver: (any VNCSessionDriving)?
private let rdpDriver: (any RDPSessionDriving)?
private let remoteSessionEnd: @MainActor () -> RemoteSessionEndBehavior
private var handles: [SessionID: LiveSession] = [:]
private var attempts: [SessionID: UUID] = [:]
private var reportedExitStatuses: [SessionID: Int32] = [:]
private var pendingConnectionFacts: [SessionID: ConnectionFacts] = [:]
/// Remote desktops the user disconnected, whose disconnected event is still to come.
private var requestedDisconnects: Set<SessionID> = []
private var workspaceSaveTask: Task<Void, Never>?

init(
Expand All @@ -69,14 +72,16 @@ final class SessionCoordinator {
driver: any SSHSessionDriving,
localDriver: any LocalTerminalDriving,
vncDriver: (any VNCSessionDriving)? = nil,
rdpDriver: (any RDPSessionDriving)? = nil
rdpDriver: (any RDPSessionDriving)? = nil,
remoteSessionEnd: @escaping @MainActor () -> RemoteSessionEndBehavior = { .keepTab }
) {
self.library = library
self.prober = prober
self.driver = driver
self.localDriver = localDriver
self.vncDriver = vncDriver
self.rdpDriver = rdpDriver
self.remoteSessionEnd = remoteSessionEnd
}

var selectedSession: SessionSummary? {
Expand Down Expand Up @@ -251,6 +256,7 @@ final class SessionCoordinator {
update(sessionID) { $0.state = .disconnected }
case .remoteDesktop(let session) where session.state.isLive:
// The desktop closes asynchronously; its disconnected event finishes this.
requestedDisconnects.insert(sessionID)
update(sessionID) { $0.state = .disconnecting }
session.disconnect()
case .remoteDesktop:
Expand All @@ -266,6 +272,7 @@ final class SessionCoordinator {
handles.removeValue(forKey: sessionID)?.close()
reportedExitStatuses.removeValue(forKey: sessionID)
pendingConnectionFacts.removeValue(forKey: sessionID)
requestedDisconnects.remove(sessionID)
guard let index = sessions.firstIndex(where: { $0.id == sessionID }) else { return }
let closing = sessions.remove(at: index)
if selectedSessionID == sessionID {
Expand Down Expand Up @@ -536,6 +543,7 @@ final class SessionCoordinator {
let attempt = UUID()
attempts[sessionID] = attempt
reportedExitStatuses.removeValue(forKey: sessionID)
requestedDisconnects.remove(sessionID)
guard let summary = sessions.first(where: { $0.id == sessionID }) else { return }

switch summary.target {
Expand Down Expand Up @@ -786,7 +794,11 @@ final class SessionCoordinator {
handle.finish()
pendingConnectionFacts.removeValue(forKey: sessionID)
if let code = reportedExitStatuses.removeValue(forKey: sessionID) {
update(sessionID) { $0.state = code == 0 ? .disconnected : .failed(.sshExited(code)) }
if code == 0 {
endRemoteSession(sessionID)
} else {
update(sessionID) { $0.state = .failed(.sshExited(code)) }
}
} else {
update(sessionID) { $0.state = .failed(.endedWithoutStatus) }
}
Expand Down Expand Up @@ -837,19 +849,34 @@ final class SessionCoordinator {
update(sessionID) { $0.state = .disconnecting }
case .disconnected(let failure):
handles.removeValue(forKey: sessionID)?.close()
update(sessionID) {
switch failure {
case nil: $0.state = .disconnected
case let failure? where failure.isAuthenticationFailure: $0.state = .failed(.authenticationFailed(failure.message))
case let failure?: $0.state = .failed(.remoteDesktop(failure.message))
}
let requested = requestedDisconnects.remove(sessionID) != nil
switch failure {
case nil where requested: update(sessionID) { $0.state = .disconnected }
case nil: endRemoteSession(sessionID)
case let failure? where failure.isAuthenticationFailure:
update(sessionID) { $0.state = .failed(.authenticationFailed(failure.message)) }
case let failure?: update(sessionID) { $0.state = .failed(.remoteDesktop(failure.message)) }
}
}
case .framebufferSizeChanged:
break
}
}

/// A remote session that ended cleanly from the remote side. The close
/// waits a turn: this runs inside the driver's own callback, and SSH's
/// terminal surface must not be freed from within it.
private func endRemoteSession(_ sessionID: SessionID) {
update(sessionID) { $0.state = .disconnected }
guard remoteSessionEnd() == .closeTab else { return }
let attempt = attempts[sessionID]
Task { @MainActor [weak self] in
// A reconnect or close in the meantime starts a new attempt.
guard let self, attempts[sessionID] == attempt else { return }
close(sessionID: sessionID)
}
}

private func fail(_ sessionID: SessionID, attempt: UUID, with failure: ConnectionFailure) {
guard attempts[sessionID] == attempt else { return }
pendingConnectionFacts.removeValue(forKey: sessionID)
Expand Down
17 changes: 17 additions & 0 deletions App/SettingsStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,23 @@ struct GeneralSettings: PersistedSettings {
/// Multiplies how far RDP and VNC sessions scroll; see
/// `ScrollWheelAccumulator.speedRange`.
var scrollSpeed = 1.0
var remoteSessionEnd: RemoteSessionEndBehavior = .keepTab
}

/// What a tab does when its remote session ends cleanly from the remote
/// side, such as `exit` over SSH or signing out of a desktop. Failures and
/// the Disconnect command always keep the tab.
enum RemoteSessionEndBehavior: String, Codable, CaseIterable, Sendable {
/// Leave the tab open with its Reconnect banner.
case keepTab
case closeTab

var displayName: String {
switch self {
case .keepTab: "Keep the tab open"
case .closeTab: "Close the tab"
}
}
}

typealias GeneralSettingsStore = SettingsStore<GeneralSettings>
Expand Down
14 changes: 14 additions & 0 deletions App/UI/SettingsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,20 @@ private struct GeneralSettingsView: View {
Text("Shows This Mac at the top of the machine list for opening local terminals.")
}

Section {
Picker("When a remote session ends", selection: Binding(
get: { settings.value.remoteSessionEnd },
set: { value in settings.update { $0.remoteSessionEnd = value } })) {
ForEach(RemoteSessionEndBehavior.allCases, id: \.self) { behavior in
Text(behavior.displayName).tag(behavior)
}
}
} header: {
Text("Sessions")
} footer: {
Text("Applies when the remote side ends the session, such as typing exit over SSH or signing out of a remote desktop. Sessions that fail or that you disconnect keep their tab.")
}

Section {
LabeledContent("Scroll speed") {
HStack {
Expand Down
4 changes: 3 additions & 1 deletion Tests/App/RemoteDesktopSettingsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@ struct GeneralSettingsTests {
let settings = GeneralSettingsStore(defaults: defaults)
#expect(settings.value.showsLocalMachine)
#expect(settings.value.scrollSpeed == 1)
settings.update { $0.showsLocalMachine = false; $0.scrollSpeed = 0.5 }
#expect(settings.value.remoteSessionEnd == .keepTab)
settings.update { $0.showsLocalMachine = false; $0.scrollSpeed = 0.5; $0.remoteSessionEnd = .closeTab }
let reloaded = GeneralSettingsStore(defaults: defaults).value
#expect(!reloaded.showsLocalMachine)
#expect(reloaded.scrollSpeed == 0.5)
#expect(reloaded.remoteSessionEnd == .closeTab)
}
}

Expand Down
88 changes: 84 additions & 4 deletions Tests/App/SessionCoordinatorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -626,7 +626,83 @@ struct SessionCoordinatorTests {
#expect(coordinator.sessions.first?.state == .failed(.unsupportedProtocol(.rdp)))
}

private func coordinatorWithVNCMachine(defaultDisplayMode: RemoteDesktopDisplayMode = .fit) async throws -> (SessionCoordinator, GRDBMachineLibrary, Machine, StubVNCDriver) {
@Test func cleanSSHExitKeepsTheTabByDefault() async throws {
let (coordinator, _, profile, driver) = try await coordinatorWithOneMachine()
let id = try await coordinator.open(profileID: profile.id)
let session = try #require(driver.sessions.last)

session.terminal.emit(.titleChanged("constellation-exit:\(session.exitStatusChannel.token):0"))
session.terminal.emit(.processExited(code: 0, runtime: .seconds(1)))
await settle()

#expect(coordinator.sessions.first(where: { $0.id == id })?.state == .disconnected)
}

@Test func cleanSSHExitClosesTheTabWhenChosen() async throws {
let (coordinator, _, profile, driver) = try await coordinatorWithOneMachine(remoteSessionEnd: .closeTab)
let id = try await coordinator.open(profileID: profile.id)
let session = try #require(driver.sessions.last)

session.terminal.emit(.titleChanged("constellation-exit:\(session.exitStatusChannel.token):0"))
session.terminal.emit(.processExited(code: 0, runtime: .seconds(1)))
await settle()

#expect(!coordinator.sessions.contains { $0.id == id })
#expect(session.terminal.isClosed)
}

@Test func failedSSHExitKeepsTheTabEvenWhenClosingIsChosen() async throws {
let (coordinator, _, profile, driver) = try await coordinatorWithOneMachine(remoteSessionEnd: .closeTab)
let id = try await coordinator.open(profileID: profile.id)
let session = try #require(driver.sessions.last)

session.terminal.emit(.titleChanged("constellation-exit:\(session.exitStatusChannel.token):255"))
session.terminal.emit(.processExited(code: 0, runtime: .seconds(1)))
await settle()

#expect(coordinator.sessions.first(where: { $0.id == id })?.state == .failed(.sshExited(255)))
}

@Test func remoteDesktopSignOutClosesTheTabButDisconnectKeepsIt() async throws {
let (coordinator, library, machine, vncDriver) = try await coordinatorWithVNCMachine(remoteSessionEnd: .closeTab)
let profile = try #require(await library.snapshot().profiles(for: machine.id).first)
let disconnected = try await coordinator.open(profileID: profile.id)
let signedOut = try await coordinator.open(profileID: profile.id)
let (first, second) = (vncDriver.sessions[0], vncDriver.sessions[1])
first.emit(.stateChanged(.connected))
second.emit(.stateChanged(.connected))

coordinator.disconnect(sessionID: disconnected)
first.emit(.stateChanged(.disconnected(nil)))
second.emit(.stateChanged(.disconnected(nil)))
await settle()

#expect(coordinator.sessions.map(\.id) == [disconnected])
#expect(coordinator.sessions.first?.state == .disconnected)
}

@Test func reconnectingBeforeTheTabClosesKeepsIt() async throws {
let (coordinator, _, profile, driver) = try await coordinatorWithOneMachine(remoteSessionEnd: .closeTab)
let id = try await coordinator.open(profileID: profile.id)
let session = try #require(driver.sessions.last)

session.terminal.emit(.titleChanged("constellation-exit:\(session.exitStatusChannel.token):0"))
session.terminal.emit(.processExited(code: 0, runtime: .seconds(1)))
try await coordinator.reconnect(sessionID: id)
await settle()

#expect(coordinator.sessions.first(where: { $0.id == id })?.state.isConnecting == true)
}

/// Lets the coordinator's deferred tab close run.
private func settle() async {
for _ in 0..<5 { await Task.yield() }
}

private func coordinatorWithVNCMachine(
defaultDisplayMode: RemoteDesktopDisplayMode = .fit,
remoteSessionEnd: RemoteSessionEndBehavior = .keepTab
) async throws -> (SessionCoordinator, GRDBMachineLibrary, Machine, StubVNCDriver) {
let library = try GRDBMachineLibrary.inMemory()
let machine = Machine(name: "screen")
let address = MachineAddress(machineID: machine.id, label: "", host: "vnc.box")
Expand All @@ -638,11 +714,14 @@ struct SessionCoordinatorTests {
prober: StubProber(results: ["vnc.box": true]),
driver: StubSSHDriver(),
localDriver: StubLocalTerminalDriver(),
vncDriver: vncDriver)
vncDriver: vncDriver,
remoteSessionEnd: { remoteSessionEnd })
return (coordinator, library, machine, vncDriver)
}

private func coordinatorWithOneMachine() async throws -> (SessionCoordinator, GRDBMachineLibrary, SSHProfile, StubSSHDriver) {
private func coordinatorWithOneMachine(
remoteSessionEnd: RemoteSessionEndBehavior = .keepTab
) async throws -> (SessionCoordinator, GRDBMachineLibrary, SSHProfile, StubSSHDriver) {
let library = try GRDBMachineLibrary.inMemory()
let machine = Machine(name: "box")
let address = MachineAddress(machineID: machine.id, label: "LAN", host: "box.local")
Expand All @@ -652,7 +731,8 @@ struct SessionCoordinatorTests {
return (
SessionCoordinator(
library: library, prober: StubProber(results: ["box.local": true]),
driver: driver, localDriver: StubLocalTerminalDriver()),
driver: driver, localDriver: StubLocalTerminalDriver(),
remoteSessionEnd: { remoteSessionEnd }),
library,
profile,
driver)
Expand Down
Loading