Skip to content
Open
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
21 changes: 21 additions & 0 deletions app/src/main/java/io/github/lordofpolls/shellwave/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 })
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand All @@ -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
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -234,6 +236,7 @@ private fun JSONObject?.toImportedSettings(): ImportedSettings {
colourTheme = enumOrNull<ColourTheme>(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"),
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down
Loading
Loading