From 480851c4440c92e0ca3b9af8fb4627bd84e3cda1 Mon Sep 17 00:00:00 2001 From: andreas-byfut <356109509+andreas-byfut@users.noreply.github.com> Date: Fri, 13 Nov 2026 07:46:36 +0100 Subject: [PATCH] feat(sessions): optionally close the session when the shell exits Add a setting, "Close the tab when the shell exits", off by default and included in config export/import. Off keeps the current behaviour: a clean end leaves a DISCONNECTED tab with its output readable and Reconnect available. A clean exit is the shell ending without a connection error: exit or logout, or the server closing the session. With the setting on, that closes the session, which also disconnects the transport and any jump hosts and lets the foreground service stop once nothing else is open. The output is gone with the tab. Closing the last session now always returns to the menu instead of an empty terminal, including when another screen such as the SFTP browser is open above it. This replaces the in-terminal "No open sessions" empty state. Closing the selected tab of several selects the first remaining one, and a script run waiting on a session that closes while connecting now reports an error instead of waiting forever. --- .../lordofpolls/shellwave/MainActivity.kt | 21 +++++++++++++ .../core/prefs/SessionPreferences.kt | 22 +++++++++++++ .../feature/scripts/ScriptRunController.kt | 10 +++--- .../feature/session/SessionsScreen.kt | 25 +++++++-------- .../feature/settings/ConfigExport.kt | 2 ++ .../feature/settings/ConfigImport.kt | 4 +++ .../feature/settings/SettingsScreen.kt | 11 +++++++ .../shellwave/ssh/SessionManager.kt | 16 +++++++--- .../shellwave/ssh/SshConnection.kt | 9 +++--- .../feature/settings/ConfigImportTest.kt | 3 ++ .../shellwave/ssh/SessionManagerTest.kt | 31 ++++++++++++++++++- 11 files changed, 127 insertions(+), 27 deletions(-) create mode 100644 app/src/main/java/io/github/lordofpolls/shellwave/core/prefs/SessionPreferences.kt diff --git a/app/src/main/java/io/github/lordofpolls/shellwave/MainActivity.kt b/app/src/main/java/io/github/lordofpolls/shellwave/MainActivity.kt index 527fd20..b7fce36 100644 --- a/app/src/main/java/io/github/lordofpolls/shellwave/MainActivity.kt +++ b/app/src/main/java/io/github/lordofpolls/shellwave/MainActivity.kt @@ -74,6 +74,7 @@ import io.github.lordofpolls.shellwave.core.net.sendMagicPacket import io.github.lordofpolls.shellwave.core.prefs.AppearancePreferences import io.github.lordofpolls.shellwave.core.prefs.AutomationPreferences import io.github.lordofpolls.shellwave.core.prefs.ReachabilityPreferences +import io.github.lordofpolls.shellwave.core.prefs.SessionPreferences import io.github.lordofpolls.shellwave.core.prefs.SupportPreferences import io.github.lordofpolls.shellwave.core.prefs.rememberPrefState import io.github.lordofpolls.shellwave.core.prefs.ThemeMode @@ -337,6 +338,7 @@ class MainActivity : FragmentActivity() { val colourTheme by rememberPrefState { AppearancePreferences.getColourTheme(it) } val themeMode by rememberPrefState { AppearancePreferences.getThemeMode(it) } val exactSchemeColours by rememberPrefState { AppearancePreferences.getExactSchemeColours(it) } + val closeSessionOnExit by rememberPrefState { SessionPreferences.getCloseOnExit(it) } // These three exist only to render the Settings controls and gate the indicator: each // setter writes the pref and calls start(), and the probe re-reads all of them on @@ -450,6 +452,18 @@ class MainActivity : FragmentActivity() { val scope = rememberCoroutineScope() val summaries by sessionManager.summaries.collectAsState() + // Leave the terminal for the menu once the last session closes, so the navigation + // chrome comes back instead of an empty terminal with no menu. Keyed on the terminal + // being on top and reading the flow itself, not the collected `summaries`: a session + // ending under a screen pushed above the terminal (the SFTP browser) is caught when + // that screen pops, and a session opened just before openTerminal() is seen as open + // rather than judged against a stale snapshot - see the save effect below. + val terminalOnTop = subStack.lastOrNull() == "terminal" + LaunchedEffect(terminalOnTop) { + if (!terminalOnTop) return@LaunchedEffect + sessionManager.summaries.first { it.isEmpty() } + popBack() + } val screen = when (subStack.lastOrNull()) { "addEdit" -> Screen.AddEditHost(editingHostId.takeIf { it >= 0 }) @@ -1049,6 +1063,13 @@ class MainActivity : FragmentActivity() { it ) }, + closeSessionOnExit = closeSessionOnExit, + onCloseSessionOnExitChange = { + SessionPreferences.setCloseOnExit( + this@MainActivity, + it + ) + }, // Each writes its pref and restarts the probe, which // re-reads all three. reachabilityEnabled = reachabilityEnabled, diff --git a/app/src/main/java/io/github/lordofpolls/shellwave/core/prefs/SessionPreferences.kt b/app/src/main/java/io/github/lordofpolls/shellwave/core/prefs/SessionPreferences.kt new file mode 100644 index 0000000..66ec559 --- /dev/null +++ b/app/src/main/java/io/github/lordofpolls/shellwave/core/prefs/SessionPreferences.kt @@ -0,0 +1,22 @@ +package io.github.lordofpolls.shellwave.core.prefs + +import android.content.Context + +private const val PREFS_NAME = "shellwave_prefs" +private const val KEY_CLOSE_ON_EXIT = "close_session_on_exit" + +/** + * What happens to a tab when its shell ends cleanly (`exit`, `logout`, the server closing the + * session). Off keeps the tab as DISCONNECTED, so the output stays readable and Reconnect is offered; + * on closes the session and drops that output. + */ +object SessionPreferences { + fun getCloseOnExit(context: Context): Boolean = + context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + .getBoolean(KEY_CLOSE_ON_EXIT, false) + + fun setCloseOnExit(context: Context, enabled: Boolean) { + context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit() + .putBoolean(KEY_CLOSE_ON_EXIT, enabled).apply() + } +} diff --git a/app/src/main/java/io/github/lordofpolls/shellwave/feature/scripts/ScriptRunController.kt b/app/src/main/java/io/github/lordofpolls/shellwave/feature/scripts/ScriptRunController.kt index 2cb3380..5f620ef 100644 --- a/app/src/main/java/io/github/lordofpolls/shellwave/feature/scripts/ScriptRunController.kt +++ b/app/src/main/java/io/github/lordofpolls/shellwave/feature/scripts/ScriptRunController.kt @@ -22,7 +22,6 @@ import io.github.lordofpolls.shellwave.ssh.SessionStatus import io.github.lordofpolls.shellwave.ssh.SshConnection import io.github.lordofpolls.shellwave.ssh.resolveConnectionSpec import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch @@ -274,12 +273,15 @@ internal constructor( val sessionId = sessionManager.openSession(spec) onSessionOpened(sessionId) val command = substituteParams(script.snippet, values) + // Null once the session is gone: closed by the user, or by a clean exit with the + // close-on-exit setting on. `first` on the non-null values alone would wait forever then. val summary = sessionManager.summaries .map { list -> list.firstOrNull { it.id == sessionId } } - .filterNotNull() - .first { it.status != SessionStatus.CONNECTING } - if (summary.status == SessionStatus.CONNECTED) { + .first { it == null || it.status != SessionStatus.CONNECTING } + if (summary == null) { + reportError("The session closed before the script could run") + } else if (summary.status == SessionStatus.CONNECTED) { summary.connection.write("$command\n") if (script.disconnectAfter) summary.connection.write("exit\n") } else { diff --git a/app/src/main/java/io/github/lordofpolls/shellwave/feature/session/SessionsScreen.kt b/app/src/main/java/io/github/lordofpolls/shellwave/feature/session/SessionsScreen.kt index 7258323..f32b7c7 100644 --- a/app/src/main/java/io/github/lordofpolls/shellwave/feature/session/SessionsScreen.kt +++ b/app/src/main/java/io/github/lordofpolls/shellwave/feature/session/SessionsScreen.kt @@ -94,7 +94,6 @@ import io.github.lordofpolls.shellwave.terminal.selectionHighlightColor import io.github.lordofpolls.shellwave.terminal.dragRows import io.github.lordofpolls.shellwave.terminal.terminalGestures import io.github.lordofpolls.shellwave.terminal.wheelButton -import io.github.lordofpolls.shellwave.ui.design.EmptyState import io.github.lordofpolls.shellwave.ui.design.MachineText import io.github.lordofpolls.shellwave.ui.design.SessionChipModel import io.github.lordofpolls.shellwave.ui.design.SessionChipRail @@ -149,17 +148,9 @@ fun SessionsScreen( modifier: Modifier = Modifier, ) { val summaries by sessionManager.summaries.collectAsState() - if (summaries.isEmpty()) { - // Was onEmpty(), which popped the screen away and made an empty Sessions tab unreachable - // rather than idle. Copy matches SessionsListScreen's empty state. - EmptyState( - message = "No open sessions.", - actionLabel = "Open Hosts", - onAction = onNewSession, - modifier = modifier.fillMaxSize(), - ) - return - } + // MainActivity leaves the terminal as soon as the last session closes; this covers the frame + // before that lands. + if (summaries.isEmpty()) return val view = LocalView.current DisposableEffect(view) { @@ -176,8 +167,10 @@ fun SessionsScreen( // Driven by the navigator's own destination; a second piece of state could drift from it. // Falls back to the first session once a target is known to exist, so a freshly-opened screen - // - or one whose selected session just closed - never shows an empty detail pane. - val selectedId = navigator.currentDestination?.contentKey + // - or one whose selected session just closed - never shows an empty detail pane. The + // navigator keeps the closed id as its content key, hence the membership check. + val navigatorKey = navigator.currentDestination?.contentKey + val selectedId = navigatorKey?.takeIf { key -> summaries.any { it.id == key } } ?: summaries.firstOrNull { it.id == initialSessionId }?.id ?: summaries.first().id // Keyed on the selected session, not shared screen-wide: switching tabs must not leave the @@ -188,6 +181,10 @@ fun SessionsScreen( scope.launch { navigator.navigateTo(ListDetailPaneScaffoldRole.Detail, id) } } + LaunchedEffect(navigatorKey, summaries) { + if (navigatorKey != null && summaries.none { it.id == navigatorKey }) selectSession(selectedId) + } + // Keyed on [initialSessionId] instead of `Unit`: the terminal is not always torn down between // two requests, since `openTerminal` is idempotent when it is already on top, so a session // opened while one is showing changes this parameter without recomposing the screen from diff --git a/app/src/main/java/io/github/lordofpolls/shellwave/feature/settings/ConfigExport.kt b/app/src/main/java/io/github/lordofpolls/shellwave/feature/settings/ConfigExport.kt index 6baa1d4..c7b2abb 100644 --- a/app/src/main/java/io/github/lordofpolls/shellwave/feature/settings/ConfigExport.kt +++ b/app/src/main/java/io/github/lordofpolls/shellwave/feature/settings/ConfigExport.kt @@ -16,6 +16,7 @@ import io.github.lordofpolls.shellwave.core.prefs.AutomationPreferences import io.github.lordofpolls.shellwave.core.prefs.BellPreferences import io.github.lordofpolls.shellwave.core.prefs.ReachabilityPreferences import io.github.lordofpolls.shellwave.core.prefs.SessionLayoutPreferences +import io.github.lordofpolls.shellwave.core.prefs.SessionPreferences import io.github.lordofpolls.shellwave.core.prefs.WidgetPreferences import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.first @@ -205,6 +206,7 @@ constructor( "themeMode" to AppearancePreferences.getThemeMode(context).name, "colourTheme" to AppearancePreferences.getColourTheme(context).name, "exactSchemeColours" to AppearancePreferences.getExactSchemeColours(context), + "closeSessionOnExit" to SessionPreferences.getCloseOnExit(context), "bellMode" to BellPreferences.get(context).name, "fullWidthTerminal" to SessionLayoutPreferences.getFullWidthTerminal(context), "reachabilityEnabled" to ReachabilityPreferences.isEnabled(context), diff --git a/app/src/main/java/io/github/lordofpolls/shellwave/feature/settings/ConfigImport.kt b/app/src/main/java/io/github/lordofpolls/shellwave/feature/settings/ConfigImport.kt index cc213e9..51d2603 100644 --- a/app/src/main/java/io/github/lordofpolls/shellwave/feature/settings/ConfigImport.kt +++ b/app/src/main/java/io/github/lordofpolls/shellwave/feature/settings/ConfigImport.kt @@ -23,6 +23,7 @@ import io.github.lordofpolls.shellwave.core.prefs.ColourTheme import io.github.lordofpolls.shellwave.core.prefs.ReachabilityInterval import io.github.lordofpolls.shellwave.core.prefs.ReachabilityPreferences import io.github.lordofpolls.shellwave.core.prefs.SessionLayoutPreferences +import io.github.lordofpolls.shellwave.core.prefs.SessionPreferences import io.github.lordofpolls.shellwave.core.prefs.ThemeMode import io.github.lordofpolls.shellwave.core.prefs.WidgetPreferences import io.github.lordofpolls.shellwave.feature.glance.ScriptWidget @@ -54,6 +55,7 @@ data class ImportedSettings( val themeMode: ThemeMode? = null, val colourTheme: ColourTheme? = null, val exactSchemeColours: Boolean? = null, + val closeSessionOnExit: Boolean? = null, val bellMode: BellMode? = null, val fullWidthTerminal: Boolean? = null, val reachabilityEnabled: Boolean? = null, @@ -234,6 +236,7 @@ private fun JSONObject?.toImportedSettings(): ImportedSettings { colourTheme = enumOrNull(stringOrNull("colourTheme")) ?: booleanOrNull("dynamicColour")?.let { if (it) ColourTheme.DYNAMIC else ColourTheme.SCHEMATIC }, exactSchemeColours = booleanOrNull("exactSchemeColours"), + closeSessionOnExit = booleanOrNull("closeSessionOnExit"), bellMode = enumOrNull(stringOrNull("bellMode")), fullWidthTerminal = booleanOrNull("fullWidthTerminal"), reachabilityEnabled = booleanOrNull("reachabilityEnabled"), @@ -382,6 +385,7 @@ constructor( settings.themeMode?.let { AppearancePreferences.setThemeMode(context, it) } settings.colourTheme?.let { AppearancePreferences.setColourTheme(context, it) } settings.exactSchemeColours?.let { AppearancePreferences.setExactSchemeColours(context, it) } + settings.closeSessionOnExit?.let { SessionPreferences.setCloseOnExit(context, it) } settings.bellMode?.let { BellPreferences.set(context, it) } settings.fullWidthTerminal?.let { SessionLayoutPreferences.setFullWidthTerminal(context, it) diff --git a/app/src/main/java/io/github/lordofpolls/shellwave/feature/settings/SettingsScreen.kt b/app/src/main/java/io/github/lordofpolls/shellwave/feature/settings/SettingsScreen.kt index b02ecb0..28bf73f 100644 --- a/app/src/main/java/io/github/lordofpolls/shellwave/feature/settings/SettingsScreen.kt +++ b/app/src/main/java/io/github/lordofpolls/shellwave/feature/settings/SettingsScreen.kt @@ -67,6 +67,8 @@ fun SettingsScreen( onThemeModeChange: (ThemeMode) -> Unit, exactSchemeColours: Boolean, onExactSchemeColoursChange: (Boolean) -> Unit, + closeSessionOnExit: Boolean, + onCloseSessionOnExitChange: (Boolean) -> Unit, reachabilityEnabled: Boolean, onReachabilityEnabledChange: (Boolean) -> Unit, reachabilityInterval: ReachabilityInterval, @@ -148,6 +150,15 @@ fun SettingsScreen( onClick = onOpenTerminalSettings, ) + SettingsSectionHeader("Sessions") + + SettingsSwitch( + title = "Close the tab when the shell exits", + description = "Applies when the shell ends without a connection error, such as exit or logout, or when the server closes the session. The tab closes and its output is gone. Off keeps the tab so you can read the output or reconnect.", + checked = closeSessionOnExit, + onCheckedChange = onCloseSessionOnExitChange, + ) + SettingsSectionHeader("Hosts") SettingsRow( diff --git a/app/src/main/java/io/github/lordofpolls/shellwave/ssh/SessionManager.kt b/app/src/main/java/io/github/lordofpolls/shellwave/ssh/SessionManager.kt index 4d2b496..65bd59e 100644 --- a/app/src/main/java/io/github/lordofpolls/shellwave/ssh/SessionManager.kt +++ b/app/src/main/java/io/github/lordofpolls/shellwave/ssh/SessionManager.kt @@ -14,6 +14,7 @@ import io.github.lordofpolls.shellwave.core.db.entities.ColorSchemeEntity import io.github.lordofpolls.shellwave.core.db.entities.PortForwardEntity import io.github.lordofpolls.shellwave.core.db.entities.PortForwardType import io.github.lordofpolls.shellwave.core.prefs.AppearancePreferences +import io.github.lordofpolls.shellwave.core.prefs.SessionPreferences import io.github.lordofpolls.shellwave.core.prefs.SupportPreferences import io.github.lordofpolls.shellwave.service.SessionAlerts import io.github.lordofpolls.shellwave.service.SessionService @@ -285,7 +286,7 @@ constructor( } /** - * Manual retry for a session sitting in DISCONNECTED or FAILED. + * Manual retry for a session sitting in DISCONNECTED (a clean exit with close-on-exit off) or FAILED. * * [SshConnection.stopAllForwards] runs synchronously here, before `disconnect()`, matching the * ordering [handleDisconnected] uses. Otherwise the old forwards are released only by @@ -504,8 +505,9 @@ constructor( // connect() starts the reader coroutine before it returns, so a shell that ends or a socket that // drops in that window can call handleDisconnected() concurrently, before this sets CONNECTED. - // Unguarded, that write lands after the DISCONNECTED one and overwrites it, leaving a dead - // session showing connected forever with no reader and no backoff. + // Unguarded, that write lands after the DISCONNECTED one (or, with close-on-exit on, outlives the + // closed entry) and overwrites it, leaving a dead session showing connected forever with no + // reader and no backoff. // // Reasoned from the code, not reproduced: hitting the window needs sub-millisecond timing that // typing `exit` into a connected shell doesn't exercise. myGeneration is snapshotted before @@ -635,6 +637,12 @@ constructor( private fun handleDisconnected(id: Long, clean: Boolean) { val entry = entries[id] ?: return entry.generation.incrementAndGet() // invalidate any attemptConnect() still unwinding for this connection - see its comment + // Closing tears down the forwards, tunnels and transport itself, so the steps below would + // only repeat that. + if (clean && SessionPreferences.getCloseOnExit(context)) { + closeSession(id) + return + } // Release every bound local port the moment a drop is detected, rather than waiting for // reconnectWithBackoff()'s own disconnect() before its first retry - otherwise the port // stays occupied and the next start fails. A local forward's ServerSocket is independent of @@ -643,7 +651,7 @@ constructor( entry.tunnels = emptyMap() // Not connected any more, so there is no uptime to show: see SessionSummary // .connectedAtElapsedRealtime. attemptConnect() clears this too, but a drop that never gets - // as far as a retry (a clean exit) has no attemptConnect() coming. + // as far as a retry (a clean exit with close-on-exit off) has no attemptConnect() coming. entry.connectedAtElapsedRealtime = null if (clean) { entry.status = SessionStatus.DISCONNECTED diff --git a/app/src/main/java/io/github/lordofpolls/shellwave/ssh/SshConnection.kt b/app/src/main/java/io/github/lordofpolls/shellwave/ssh/SshConnection.kt index 0e1d03f..18fc600 100644 --- a/app/src/main/java/io/github/lordofpolls/shellwave/ssh/SshConnection.kt +++ b/app/src/main/java/io/github/lordofpolls/shellwave/ssh/SshConnection.kt @@ -186,9 +186,9 @@ open class SshConnection( /** * Idempotent, and the one place every session-end path routes through: [disconnect] calls it * directly for an explicit close, and the reader loop's `finally` calls it again for a drop it - * detects itself - a clean EOF or an IOException - which never goes through [disconnect] at - * all (see [SessionManager.handleDisconnected]'s clean-exit branch). A log must not outlive the - * session it belongs to either way. + * detects itself - a clean EOF or an IOException. Neither goes through [disconnect] unless + * [SessionManager.handleDisconnected] then closes the session (clean exit with close-on-exit on). + * A log must not outlive the session it belongs to either way. */ private fun closeLogging() { val sink = logSink ?: return @@ -402,7 +402,8 @@ open class SshConnection( // Forget before cancelling, or a channel can arrive mid-teardown and start a loop nothing will // cancel. Cancelling a job cannot interrupt a loop blocked in a channel read, and a reader that - // ends on a clean EOF never reaches ssh.disconnect(), so the serve loops are ended here. + // ends on a clean EOF does not itself reach ssh.disconnect() (only a close-on-exit session + // close does, afterwards), so the serve loops are ended here. // Closing the input stream is a local EOF that frees the read at once; channel.close() alone // waits for the peer's reply, which a hostile server can withhold. If the server then sends more // on that channel, sshj fails the transport: harmless at teardown, and on the refusal path only a diff --git a/app/src/test/java/io/github/lordofpolls/shellwave/feature/settings/ConfigImportTest.kt b/app/src/test/java/io/github/lordofpolls/shellwave/feature/settings/ConfigImportTest.kt index 5ee55ed..4131a47 100644 --- a/app/src/test/java/io/github/lordofpolls/shellwave/feature/settings/ConfigImportTest.kt +++ b/app/src/test/java/io/github/lordofpolls/shellwave/feature/settings/ConfigImportTest.kt @@ -125,6 +125,7 @@ class ConfigImportTest { "themeMode" to "DARK", "colourTheme" to "NOTHING", "exactSchemeColours" to true, + "closeSessionOnExit" to true, "bellMode" to "SILENT", "fullWidthTerminal" to true, "reachabilityEnabled" to true, @@ -179,6 +180,7 @@ class ConfigImportTest { assertEquals(ThemeMode.DARK, settings.themeMode) assertEquals(ColourTheme.NOTHING, settings.colourTheme) assertEquals(true, settings.exactSchemeColours) + assertEquals(true, settings.closeSessionOnExit) assertEquals(BellMode.SILENT, settings.bellMode) assertEquals(true, settings.fullWidthTerminal) assertEquals(ReachabilityInterval.FIVE_MINUTES, settings.reachabilityInterval) @@ -194,6 +196,7 @@ class ConfigImportTest { parseConfigImport(export(settings = mapOf("themeMode" to "MIDNIGHT"))).settings assertNull(settings.themeMode) + assertNull(settings.closeSessionOnExit) assertNull(settings.bellMode) assertNull(settings.fullWidthTerminal) assertNull(settings.quickSettingsTileScriptId) diff --git a/app/src/test/java/io/github/lordofpolls/shellwave/ssh/SessionManagerTest.kt b/app/src/test/java/io/github/lordofpolls/shellwave/ssh/SessionManagerTest.kt index 8f36428..40dbcdf 100644 --- a/app/src/test/java/io/github/lordofpolls/shellwave/ssh/SessionManagerTest.kt +++ b/app/src/test/java/io/github/lordofpolls/shellwave/ssh/SessionManagerTest.kt @@ -14,6 +14,7 @@ import io.github.lordofpolls.shellwave.core.db.entities.HostEntity import io.github.lordofpolls.shellwave.core.db.entities.PortForwardEntity import io.github.lordofpolls.shellwave.core.db.entities.TerminalProfileEntity import io.github.lordofpolls.shellwave.core.prefs.FakeSharedPreferences +import io.github.lordofpolls.shellwave.core.prefs.SessionPreferences import io.github.lordofpolls.shellwave.service.SessionAlerts import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope @@ -196,8 +197,13 @@ class SessionManagerTest { private val notices = CopyOnWriteArrayList() - private fun newManager(tempDir: File, hostDao: EmptyHostDao = EmptyHostDao()): SessionManager { + private fun newManager( + tempDir: File, + hostDao: EmptyHostDao = EmptyHostDao(), + closeOnExit: Boolean = false, + ): SessionManager { val context = FakeContext(tempDir) + SessionPreferences.setCloseOnExit(context, closeOnExit) return SessionManager( context, hostDao, @@ -314,6 +320,29 @@ class SessionManagerTest { return listOf(AgentKey(pair.private, pair.public, "laptop")) } + @Test + fun cleanDrop_closesTheSessionWhenCloseOnExitIsOn() { + val tempDir = createTempDir() + val manager = newManager(tempDir, closeOnExit = true) + val connections = CopyOnWriteArrayList() + manager.connectionFactory = { _ -> + FakeSshConnection(CoroutineScope(SupervisorJob() + Dispatchers.Default), FakeContext(tempDir)) + .also { connections += it } + } + val id = manager.openSession(spec()) + manager.beginConnectIfNeeded(id, 80, 24, 8, 16) + waitUntil(message = "timed out waiting for connect() to be reached") { + connections.size >= 1 && connections[0].connectStarted + } + connections[0].connectGate.complete(Unit) + waitUntil(message = "timed out waiting for CONNECTED") { summaryOf(manager, id).status == SessionStatus.CONNECTED } + + handleDisconnected(manager, id, clean = true) + + assertTrue(manager.summaries.value.none { it.id == id }) + assertEquals(1, connections[0].disconnectCalls) + } + @Test fun agentMarker_showsOnlyForAConnectedSessionThatIsReallyForwarding() { val live = openForwarding(oneKey())