From 00560197148cbf460048c00124729906cf0c1039 Mon Sep 17 00:00:00 2001 From: m96-chan Date: Tue, 15 Sep 2026 14:30:34 +0900 Subject: [PATCH] fix(session): ask iOS not to suspend the app while a shell is open (#46) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Locking the screen or leaving the app drops the SSH session. Nothing in the app hangs up — `enterBackground()` keeps the shell, the parser state and the credentials, and `checkRetainedConnection` reuses the same PTY on return when it answers. The session dies because iOS suspends the process, and a suspended process cannot service its socket. The app was not asking for any time before that happened. There is no `beginBackgroundTask` in it, so the system is free to suspend the moment the scene goes to the background. It now holds an assertion, which is worth about thirty seconds and covers the cases most likely to be behind the report: - glancing at another app and coming straight back - pressing the power button and unlocking a few seconds later - pulling down a notification Those survive today only by luck. With the assertion held, the probe on return finds a live transport instead of a dead one. Taken only when a session is connected or being checked. Asking the system to stay awake with nothing to keep alive is wasted battery and the kind of thing that gets noticed. This does not make the app stay connected in the background, and is not meant to. No entitlement iOS grants an SSH client holds a TCP session open indefinitely — the categories are audio, location, VoIP, external accessory and `NEAppPushProvider`, and a terminal is none of them. `README.md` already points at a remote multiplexer for continuity across a real disconnection, and #39 is where the one legitimate route to not being suspended is tracked. The assertion is injectable because the failure worth testing is not taking one — it is failing to give one back, which is how iOS kills an app. Four tests cover the paths that matter: not asking with nothing connected, giving it back on return, giving it back from the expiry handler, and not double-ending it afterwards. Co-Authored-By: Claude Opus 5 (1M context) --- App/WorkspaceSessionStore.swift | 46 ++++++++++++ AppTests/WorkspaceSessionStoreTests.swift | 91 +++++++++++++++++++++++ 2 files changed, 137 insertions(+) diff --git a/App/WorkspaceSessionStore.swift b/App/WorkspaceSessionStore.swift index 1455e04..ac45b25 100644 --- a/App/WorkspaceSessionStore.swift +++ b/App/WorkspaceSessionStore.swift @@ -2,6 +2,20 @@ import Foundation import Observation import SSHCore import TerminalCore +import UIKit + +/// How the store asks iOS for the time it needs, and gives it back. +@MainActor struct BackgroundAssertions { + var begin: @MainActor (@escaping @MainActor () -> Void) -> UIBackgroundTaskIdentifier + var end: @MainActor (UIBackgroundTaskIdentifier) -> Void + + static let live = BackgroundAssertions( + begin: { expired in + UIApplication.shared.beginBackgroundTask(withName: "Keep the SSH session open", expirationHandler: expired) + }, + end: { UIApplication.shared.endBackgroundTask($0) } + ) +} /// Owns live shells independently of navigation, sheet presentation, and window size. @MainActor @Observable @@ -16,6 +30,10 @@ final class WorkspaceSessionStore { @ObservationIgnored private let makeConnection: @MainActor (SSHHost) -> ConnectionModel @ObservationIgnored private var selectionHistory: [UUID] = [] @ObservationIgnored private var isInBackground = false + @ObservationIgnored private var backgroundAssertion = UIBackgroundTaskIdentifier.invalid + /// Injected so a test can watch the assertion without a real one: failing to end one is how + /// an app gets killed, so "it was ended" is the part worth asserting on. + @ObservationIgnored var backgroundAssertions: BackgroundAssertions = .live init(maximumSessions: Int = 4, makeConnection: (@MainActor (SSHHost) -> ConnectionModel)? = nil) { @@ -72,9 +90,37 @@ final class WorkspaceSessionStore { func enterBackground() { isInBackground = true sessions.forEach { $0.enterBackground() } + holdBackgroundAssertion() + } + + /// Asks iOS not to suspend the app immediately, so a live shell survives a glance at another + /// app, a notification, or a lock and unlock a few seconds later (#46). + /// + /// A suspended process cannot service its socket, which is how the session dies — nothing + /// here hangs up. The assertion buys around thirty seconds, which is not a fix for leaving + /// the app for an hour and is not meant to be: no entitlement iOS grants an SSH client keeps + /// a TCP session alive indefinitely, and `README.md` already points at a remote multiplexer + /// for continuity across a real disconnection. + /// + /// Taken only when there is something to keep alive. Asking for background time to do + /// nothing is both wasteful and the kind of thing that gets noticed. + private func holdBackgroundAssertion() { + guard backgroundAssertion == .invalid, + sessions.contains(where: { $0.phase == .connected || $0.phase == .checking }) else { return } + backgroundAssertion = backgroundAssertions.begin { [weak self] in + // iOS calls this when the time is up and will kill the app if the task is still held. + self?.releaseBackgroundAssertion() + } + } + + private func releaseBackgroundAssertion() { + guard backgroundAssertion != .invalid else { return } + backgroundAssertions.end(backgroundAssertion) + backgroundAssertion = .invalid } func enterForeground() { + releaseBackgroundAssertion() isInBackground = false sessions.forEach { $0.enterForeground() } } diff --git a/AppTests/WorkspaceSessionStoreTests.swift b/AppTests/WorkspaceSessionStoreTests.swift index 62beef9..bfb8873 100644 --- a/AppTests/WorkspaceSessionStoreTests.swift +++ b/AppTests/WorkspaceSessionStoreTests.swift @@ -1,6 +1,7 @@ import Foundation import Testing import SSHCore +import UIKit @testable import iOSSH @MainActor @@ -190,3 +191,93 @@ struct WorkspaceSessionStoreTests { #expect(store.sessions.count == 1) } } + +/// #46: what the app asks iOS for when it goes to the background. +/// +/// A suspended process cannot service its socket, which is how a session dies while the app is +/// away — nothing in the app hangs up. A background task assertion delays suspension by about +/// thirty seconds, which is what a glance at another app or a quick lock and unlock needs. +@MainActor +struct BackgroundAssertionTests { + private final class Recorder { + var begun = 0 + var ended: [UIBackgroundTaskIdentifier] = [] + var expire: (@MainActor () -> Void)? + var next = 1 + } + + private func assertions(_ recorder: Recorder) -> BackgroundAssertions { + BackgroundAssertions( + begin: { expired in + recorder.begun += 1 + recorder.expire = expired + defer { recorder.next += 1 } + return UIBackgroundTaskIdentifier(rawValue: recorder.next) + }, + end: { recorder.ended.append($0) } + ) + } + + private func host(_ name: String) -> SSHHost { + SSHHost(name: name, hostname: "\(name).example.test", username: "tester") + } + + @Test func nothingIsAskedForWhenNoSessionIsConnected() async { + let fixture = WorkspaceFixture() + let store = fixture.makeStore() + let recorder = Recorder() + store.backgroundAssertions = assertions(recorder) + store.open(host: host("idle")) + store.enterBackground() + // The app is asking the system to stay awake. Doing that with nothing to keep alive is + // both wasted battery and the kind of thing that gets noticed. + #expect(recorder.begun == 0) + } + + @Test func theAssertionIsGivenBackWhenTheAppReturns() async { + let fixture = WorkspaceFixture() + let store = fixture.makeStore() + let recorder = Recorder() + store.backgroundAssertions = assertions(recorder) + store.open(host: host("live")) + await connect(store.selectedSession, fixture) + store.enterBackground() + #expect(recorder.begun == 1) + store.enterForeground() + #expect(recorder.ended == [UIBackgroundTaskIdentifier(rawValue: 1)]) + } + + @Test func theAssertionIsGivenBackWhenTheTimeRunsOut() async { + let fixture = WorkspaceFixture() + let store = fixture.makeStore() + let recorder = Recorder() + store.backgroundAssertions = assertions(recorder) + store.open(host: host("live")) + await connect(store.selectedSession, fixture) + store.enterBackground() + // iOS kills an app that is still holding an assertion when its expiry handler has run. + recorder.expire?() + #expect(recorder.ended == [UIBackgroundTaskIdentifier(rawValue: 1)]) + // Returning afterwards must not end it a second time. + store.enterForeground() + #expect(recorder.ended.count == 1) + } + + @Test func goingToTheBackgroundTwiceHoldsOneAssertion() async { + let fixture = WorkspaceFixture() + let store = fixture.makeStore() + let recorder = Recorder() + store.backgroundAssertions = assertions(recorder) + store.open(host: host("live")) + await connect(store.selectedSession, fixture) + store.enterBackground() + store.enterBackground() + #expect(recorder.begun == 1) + } + + private func connect(_ model: ConnectionModel?, _ fixture: WorkspaceFixture) async { + guard let model else { return } + fixture.transports.last?.isConnected = true + await model.connect() + } +}