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() + } +}