Keep the person's Disconnect
Astra's Task 16 finding 4: after Settings' Disconnect, the state read said connect and Ask set itself up again at once (or at the next foreground). Disconnect is now recorded for the account and kept across launches; while it stands no set-up runs by itself, only the person's own Set up or Set it up again (which clears it), or a fresh sign-in after signing out. Disconnect also cancels and invalidates a set-up already running, so its answer can't undo it. The regressions drive the session's disconnectAsk(), the call Settings' button makes. Tests now keep their defaults apart from each other and from later runs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+116
−16
native/apple/Sources/BaseKit/Session/AskSetup.swift+11 −2native/apple/Sources/BaseKit/Session/BaseSession.swift+30 −4native/apple/Tests/BaseKitTests/SessionTests.swift+62 −7native/apple/Tests/BaseKitTests/Support.swift+13 −3
diff --git a/native/apple/Sources/BaseKit/Session/AskSetup.swift b/native/apple/Sources/BaseKit/Session/AskSetup.swift| index 113fe2b..73adc33 100644 |
| --- a/native/apple/Sources/BaseKit/Session/AskSetup.swift |
| +++ b/native/apple/Sources/BaseKit/Session/AskSetup.swift |
| @@ -38,6 +38,14 @@ import RastrilloApple |
| /// Whether the session that made this is still the one (the account |
| /// hasn't changed or signed out). |
| var isCurrent: () -> Bool = { true } |
| + /// The person disconnected Ask: no set-up by itself until they set it |
| + /// up again (`force`) or sign in afresh. |
| + var heldOff: () -> Bool = { false } |
| + /// Bumped by `invalidate()`: a set-up already running lands nothing. |
| + private var epoch = 0 |
| + |
| + /// Disconnect: whatever set-up is running must not undo it. |
| + public func invalidate() { epoch += 1 } |
| private(set) var lastAttempt: Date? |
| private(set) var running = false |
| /// Equipo answered not_linked: no more automatic attempts this session. |
| @@ -62,6 +70,7 @@ import RastrilloApple |
| @discardableResult |
| public func runIfNeeded(force: Bool = false) async -> Bool { |
| // Base still says connect after not_linked: Ask keeps saying why. |
| + if !force, heldOff() { return false } |
| if notLinked, !force, ask.phase == .connect || ask.phase == .reconnect { ask.show(.notLinked); return false } |
| guard !running, wanted || (force && ask.phase != .loading) else { return false } |
| if !force { |
| @@ -75,8 +84,8 @@ import RastrilloApple |
| notLinked = false |
| // After every suspension: the account, Ask's activity (a pause, a |
| // sign-out) and this task must all be as they were, or nothing lands. |
| - let activity = ask.activity |
| - func live() -> Bool { isCurrent() && ask.activity == activity && !ask.paused && !ask.disposed && !Task.isCancelled } |
| + let activity = ask.activity, started = epoch |
| + func live() -> Bool { isCurrent() && epoch == started && ask.activity == activity && !ask.paused && !ask.disposed && !Task.isCancelled } |
| var tries = 0 |
| while tries < 2 { |
| tries += 1 |
diff --git a/native/apple/Sources/BaseKit/Session/BaseSession.swift b/native/apple/Sources/BaseKit/Session/BaseSession.swift| index ced858f..9479745 100644 |
| --- a/native/apple/Sources/BaseKit/Session/BaseSession.swift |
| +++ b/native/apple/Sources/BaseKit/Session/BaseSession.swift |
| @@ -37,8 +37,12 @@ import RastrilloApple |
| @ObservationIgnored private var transport: SwappableTransport? |
| @ObservationIgnored private var watching: AnyCancellable? |
| - public init(oficina: OficinaIDModel) { |
| + /// Where the person's Disconnect is kept, per account. |
| + let defaults: UserDefaults |
| + |
| + public init(oficina: OficinaIDModel, defaults: UserDefaults = .standard) { |
| self.oficina = oficina |
| + self.defaults = defaults |
| watching = oficina.$step.sink { [weak self] step in |
| Task { @MainActor in self?.stepChanged(step) } |
| } |
| @@ -113,6 +117,7 @@ import RastrilloApple |
| return try await self.assertion(equipo) |
| }, fallbackEquipo: { [weak self] in self?.me?.equipoOrigin }) |
| setup.isCurrent = { [weak self] in self?.generation == epoch } |
| + setup.heldOff = { [weak self] in self?.askDisconnected ?? true } |
| ask.onNeedsSetup = { [weak self] in |
| guard let self, self.generation == epoch else { return } |
| self.startSetup() |
| @@ -152,7 +157,10 @@ import RastrilloApple |
| } |
| /// Set it up (the person pressed the button): now, whatever the minute. |
| - public func setUpAsk() async { await askSetup?.runIfNeeded(force: true) } |
| + public func setUpAsk() async { |
| + askDisconnected = false |
| + await askSetup?.runIfNeeded(force: true) |
| + } |
| /// The app came forward. |
| public func foreground() async { |
| @@ -183,9 +191,23 @@ import RastrilloApple |
| } |
| } |
| - /// Settings' Disconnect for Ask, then Ask as it is now. |
| + /// The person disconnected Ask on this account (Settings' Disconnect). |
| + /// It sticks, across launches: no set-up runs by itself until they set |
| + /// Ask up again or sign in afresh. |
| + var askDisconnected: Bool { |
| + get { account.map { defaults.bool(forKey: Self.disconnectedKey($0)) } ?? false } |
| + set { if let account { defaults.set(newValue, forKey: Self.disconnectedKey(account)) } } |
| + } |
| + static func disconnectedKey(_ account: Account) -> String { "askDisconnected:\(account.identity)@\(account.origin.absoluteString)" } |
| + |
| + /// Settings' Disconnect for Ask, then Ask as it is now. It stops any |
| + /// set-up running, and keeps one from running again by itself. |
| public func disconnectAsk() async { |
| guard let client else { return } |
| + askDisconnected = true |
| + settingUp?.cancel() |
| + settingUp = nil |
| + askSetup?.invalidate() |
| let epoch = generation |
| try? await client.disconnectAsk() |
| guard generation == epoch else { return } |
| @@ -210,7 +232,11 @@ import RastrilloApple |
| /// Sign out (confirmed by the caller): the kit's sign-out of this |
| /// Oficina ID, everywhere on this device. |
| - public func signOut() { oficina.signOut() } |
| + public func signOut() { |
| + // The next sign-in is a fresh one: Ask may set itself up again. |
| + askDisconnected = false |
| + oficina.signOut() |
| + } |
| } |
| /// A transport whose session can be replaced under the requests that use |
diff --git a/native/apple/Tests/BaseKitTests/SessionTests.swift b/native/apple/Tests/BaseKitTests/SessionTests.swift| index 9e88123..2525e28 100644 |
| --- a/native/apple/Tests/BaseKitTests/SessionTests.swift |
| +++ b/native/apple/Tests/BaseKitTests/SessionTests.swift |
| @@ -22,7 +22,7 @@ import XCTest |
| } |
| func testAnOldAccountsAnswersNeverLandInTheNext() async { |
| - let session = BaseSession(oficina: memoryOficina()) |
| + let session = BaseSession(oficina: memoryOficina(), defaults: freshDefaults()) |
| let alice = gated("alice", "Alice's", "Hello Alice") |
| session.begin(identity: "id-alice", origin: URL(string: "https://alice.example")!, transport: alice) |
| let aliceRefresh = session.refreshing |
| @@ -39,7 +39,7 @@ import XCTest |
| } |
| func testNothingLandsAfterSigningOut() async { |
| - let session = BaseSession(oficina: memoryOficina()) |
| + let session = BaseSession(oficina: memoryOficina(), defaults: freshDefaults()) |
| let alice = gated("alice", "Alice's", "Hello Alice") |
| session.begin(identity: "id-alice", origin: URL(string: "https://alice.example")!, transport: alice) |
| let refresh = session.refreshing |
| @@ -52,7 +52,7 @@ import XCTest |
| } |
| func testTheSameAccountKeepsItsModelsWhenItsSessionIsRenewed() async { |
| - let session = BaseSession(oficina: memoryOficina()) |
| + let session = BaseSession(oficina: memoryOficina(), defaults: freshDefaults()) |
| let first = gated("alice", "Alice's", "Hello Alice") |
| for path in ["/api/v1/me", "/api/v1/home", "/ask/state"] { first.release(path) } |
| let origin = URL(string: "https://alice.example")! |
| @@ -68,7 +68,7 @@ import XCTest |
| extension SessionTests { |
| /// An old account's 401, arriving late, doesn't sign the new one in again. |
| func testAnOldAccountsRefusalIsNotTheNewOnes() async throws { |
| - let session = BaseSession(oficina: memoryOficina()) |
| + let session = BaseSession(oficina: memoryOficina(), defaults: freshDefaults()) |
| var rejections = 0 |
| session.rejected = { rejections += 1 } |
| let alice = ScriptedTransport([json(401, #"{"code":"unauthenticated"}"#)]) |
| @@ -89,7 +89,7 @@ extension SessionTests { |
| /// Task 12: signing in sets Ask up when /ask/state says connect, with |
| /// an assertion addressed to Equipo, and reads the state again. |
| func testSigningInSetsAskUp() async { |
| - let session = BaseSession(oficina: memoryOficina()) |
| + let session = BaseSession(oficina: memoryOficina(), defaults: freshDefaults()) |
| var audiences: [URL] = [] |
| session.assertion = { audiences.append($0); return ("a", "v") } |
| let t = gated("alice", "Alice's", "Hello Alice") |
| @@ -111,7 +111,7 @@ extension SessionTests { |
| /// other team signs Base in there. |
| func testSwitchTeamListsTheCachedTeamsAndSwitches() async throws { |
| let (oficina, teams) = try await signedInOficina() |
| - let session = BaseSession(oficina: oficina) |
| + let session = BaseSession(oficina: oficina, defaults: freshDefaults()) |
| try await waitUntil { session.signedIn != nil } |
| let first = await session.teams() |
| XCTAssertEqual(first.map(\.sqid), teams.map(\.sqid), "the cached teams, though the cache is fresh") |
| @@ -129,7 +129,7 @@ extension SessionTests { |
| /// posts, then the person signs out (or the app goes away) before the |
| /// answer: the late answer starts no stream and changes nothing. |
| func setupHeldAtPost() async throws -> (BaseSession, GatedTransport, AskModel) { |
| - let session = BaseSession(oficina: memoryOficina()) |
| + let session = BaseSession(oficina: memoryOficina(), defaults: freshDefaults()) |
| session.assertion = { _ in ("a", "v") } |
| let t = gated("alice", "Alice's", "Hello") |
| t.answer("/ask/state", #"{"state":"ready","messages":[],"jobs":[],"cards":[],"turn":null,"status":"","cursor":7,"equipo_origin":"https://equipo.alice.example"}"#) |
| @@ -179,3 +179,58 @@ extension SessionTests { |
| XCTAssertEqual(t.calls, [], "a disposed model never comes back") |
| } |
| } |
| + |
| +extension SessionTests { |
| + /// Astra's Task 16 finding 4: Settings' Disconnect sticks. Its state |
| + /// read says connect, and nothing sets Ask up again by itself: not that |
| + /// read, not coming forward, not the next launch. The person's own Set |
| + /// it up does. |
| + func testDisconnectSticks() async throws { |
| + let defaults = UserDefaults(suiteName: "SessionTests.\(UUID().uuidString)")! |
| + let origin = URL(string: "https://alice.example")! |
| + let session = BaseSession(oficina: memoryOficina(), defaults: defaults) |
| + session.assertion = { _ in ("a", "v") } |
| + let t = gated("alice", "Alice's", "Hello") |
| + t.answer("/ask/state", #"{"state":"ready","messages":[],"jobs":[],"cards":[],"turn":null,"status":"","cursor":7,"equipo_origin":"https://equipo.alice.example"}"#) |
| + t.answer("/ask/disconnect", status: 303, headers: ["location": "/settings"], "") |
| + t.answer("/api/v1/ask/oficina", #"{"state":"ready"}"#) |
| + for path in ["/api/v1/me", "/api/v1/home", "/ask/state", "/ask/disconnect", "/api/v1/ask/oficina"] { t.release(path) } |
| + session.begin(identity: "id-alice", origin: origin, transport: t) |
| + await session.refreshing?.value |
| + // Disconnected: Base says connect from now on. |
| + t.answer("/ask/state", #"{"state":"connect","messages":[],"jobs":[],"cards":[],"turn":null,"status":"","cursor":0,"equipo_origin":"https://equipo.alice.example"}"#) |
| + await session.disconnectAsk() |
| + XCTAssertTrue(t.calls.contains("/ask/disconnect")) |
| + XCTAssertEqual(session.ask?.phase, .connect) |
| + try await Task.sleep(for: .milliseconds(100)) |
| + await session.foreground() |
| + XCTAssertFalse(t.calls.contains("/api/v1/ask/oficina"), "nothing set Ask up again by itself") |
| + // The next launch, the same account: still held off. |
| + let relaunched = BaseSession(oficina: memoryOficina(), defaults: defaults) |
| + relaunched.assertion = { _ in ("a", "v") } |
| + relaunched.begin(identity: "id-alice", origin: origin, transport: t) |
| + await relaunched.refreshing?.value |
| + XCTAssertFalse(t.calls.contains("/api/v1/ask/oficina")) |
| + relaunched.end() |
| + // The person's own Set it up: it runs, and Ask may renew by itself again. |
| + await session.setUpAsk() |
| + XCTAssertEqual(t.calls.filter { $0 == "/api/v1/ask/oficina" }.count, 1) |
| + XCTAssertFalse(session.askDisconnected) |
| + session.end() |
| + } |
| + |
| + /// Disconnect while a set-up is running: its answer doesn't undo it. |
| + func testDisconnectInvalidatesARunningSetUp() async throws { |
| + let (session, t, ask) = try await setupHeldAtPost() |
| + t.answer("/ask/disconnect", status: 303, headers: ["location": "/settings"], "") |
| + t.release("/ask/disconnect") |
| + t.answer("/ask/state", #"{"state":"connect","messages":[],"jobs":[],"cards":[],"turn":null,"status":"","cursor":0}"#) |
| + await session.disconnectAsk() |
| + let reads = t.calls.filter { $0 == "/ask/state" }.count |
| + t.release("/api/v1/ask/oficina") |
| + try await Task.sleep(for: .milliseconds(300)) |
| + XCTAssertEqual(t.calls.filter { $0 == "/ask/state" }.count, reads, "the old set-up read nothing after Disconnect") |
| + XCTAssertEqual(ask.phase, .connect) |
| + session.end() |
| + } |
| +} |
diff --git a/native/apple/Tests/BaseKitTests/Support.swift b/native/apple/Tests/BaseKitTests/Support.swift| index 5ebae48..569318b 100644 |
| --- a/native/apple/Tests/BaseKitTests/Support.swift |
| +++ b/native/apple/Tests/BaseKitTests/Support.swift |
| @@ -90,6 +90,7 @@ final class GatedTransport: NativeTransport, @unchecked Sendable { |
| let origin: URL |
| private let lock = NSLock() |
| private var answers: [String: (Int, Data)] = [:] |
| + private var headers: [String: [String: String]] = [:] |
| private var waiting: [String: [CheckedContinuation<Void, Never>]] = [:] |
| private var released: Set<String> = [] |
| private var seen: [String] = [] |
| @@ -97,7 +98,9 @@ final class GatedTransport: NativeTransport, @unchecked Sendable { |
| var calls: [String] { lock.withLock { seen } } |
| /// What `path` answers once released. |
| - func answer(_ path: String, status: Int = 200, _ body: String) { lock.withLock { answers[path] = (status, Data(body.utf8)) } } |
| + func answer(_ path: String, status: Int = 200, headers: [String: String] = [:], _ body: String) { |
| + lock.withLock { answers[path] = (status, Data(body.utf8)); self.headers[path] = headers } |
| + } |
| func release(_ path: String) { |
| let ready = lock.withLock { () -> [CheckedContinuation<Void, Never>] in |
| released.insert(path) |
| @@ -116,8 +119,11 @@ final class GatedTransport: NativeTransport, @unchecked Sendable { |
| } |
| if go { c.resume() } |
| } |
| - let (status, data) = lock.withLock { answers[path] ?? (404, Data()) } |
| - return NativeResponse(data: data, status: status, headers: [:]) |
| + let (status, data, head) = lock.withLock { () -> (Int, Data, [String: String]) in |
| + let (s, d) = answers[path] ?? (404, Data()) |
| + return (s, d, headers[path] ?? [:]) |
| + } |
| + return NativeResponse(data: data, status: status, headers: head) |
| } |
| func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { |
| lock.withLock { seen.append(path) } |
| @@ -161,3 +167,7 @@ final class GatedTransport: NativeTransport, @unchecked Sendable { |
| guard case .signedIn = model.step else { throw XCTSkip("the fake sign-in did not complete: \(model.step)") } |
| return (model, teams) |
| } |
| + |
| +/// Defaults of its own for each test: nothing a test keeps (a Disconnect) |
| +/// reaches another, or the next run. |
| +func freshDefaults() -> UserDefaults { UserDefaults(suiteName: "BaseKitTests.\(UUID().uuidString)")! } |