oficina / base Public

Own Ask's set-up, and let nothing late restart a paused Ask

Astra's Task 16 finding 3: a set-up started by a reconnect ran in an
untracked task; answering after a sign-out or with the app in the
background, it read the state and started a new stream on the old
client. The session now owns that task and cancels it on sign-out and in
the background; AskSetup checks the session's generation and Ask's
activity after every suspension before it shows or loads anything; and
a paused Ask refuses new loads and streams until the app comes forward
(resume), while a disposed one (signed out) refuses them for good.
Astra's sign-out and background probes are regressions.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev faded66c2a18c6665a9b6d90c2a2df741ec30118 parent ca79109
4 files changed, +121 −10
  • native/apple/Sources/BaseKit/Ask/AskModel.swift +28 −3
  • native/apple/Sources/BaseKit/Session/AskSetup.swift +13 −1
  • native/apple/Sources/BaseKit/Session/BaseSession.swift +24 −6
  • native/apple/Tests/BaseKitTests/SessionTests.swift +56 −0
diff --git a/native/apple/Sources/BaseKit/Ask/AskModel.swift b/native/apple/Sources/BaseKit/Ask/AskModel.swift
index 1c3e68e..cdf5fc7 100644
--- a/native/apple/Sources/BaseKit/Ask/AskModel.swift
+++ b/native/apple/Sources/BaseKit/Ask/AskModel.swift
@@ -144,6 +144,8 @@ import Observation
/// Pausing, or a newer load, while it reads wins: what this one reads
/// then lands on nothing and starts no stream.
public func load() async {
+ // Paused (the app went away) or disposed (signed out): no new work.
+ guard !paused, !disposed else { return }
stopStream()
let epoch = generation
let snapshot: AskSnapshot
@@ -160,13 +162,35 @@ import Observation
}
/// The app came forward: read afresh and listen again.
- public func resume() async { await load() }
+ public func resume() async {
+ guard !disposed else { return }
+ paused = false
+ await load()
+ }
+
+ /// The app went away: stop listening, and start nothing new (a late
+ /// load, a set-up's reload) until it comes forward again.
+ public func pause() {
+ stopStream()
+ paused = true
+ activity += 1
+ }
+
+ /// Signed out, or another account: this model is done for good.
+ public func dispose() {
+ pause()
+ disposed = true
+ }
- /// The app went away: stop listening.
- public func pause() { stopStream() }
+ public private(set) var paused = false
+ public private(set) var disposed = false
+ /// Bumped by every pause and dispose: work begun before (Ask's set-up)
+ /// checks it after each suspension and lands nothing if it moved.
+ public private(set) var activity = 0
/// Ask set itself up elsewhere (Task 12): its new state, before a load.
public func show(_ phase: AskPhase) {
+ guard !disposed else { return }
self.phase = phase
if !phase.chatting { stopStream() }
}
@@ -183,6 +207,7 @@ import Observation
/// refuses (a 410 `cursor_expired` from an old cursor, a 502) reads the
/// state afresh at once, as ask.js does. A `state` event ends it.
func listen(after start: Int64) {
+ guard !paused, !disposed else { return }
stopStream()
cursor = start
let epoch = generation
diff --git a/native/apple/Sources/BaseKit/Session/AskSetup.swift b/native/apple/Sources/BaseKit/Session/AskSetup.swift
index 9437c53..113fe2b 100644
--- a/native/apple/Sources/BaseKit/Session/AskSetup.swift
+++ b/native/apple/Sources/BaseKit/Session/AskSetup.swift
@@ -35,6 +35,9 @@ import RastrilloApple
let now: () -> Date
/// The Equipo Ask relays to, when `/ask/state` hasn't said yet.
var fallbackEquipo: () -> URL?
+ /// Whether the session that made this is still the one (the account
+ /// hasn't changed or signed out).
+ var isCurrent: () -> Bool = { true }
private(set) var lastAttempt: Date?
private(set) var running = false
/// Equipo answered not_linked: no more automatic attempts this session.
@@ -70,6 +73,10 @@ import RastrilloApple
defer { running = false }
lastAttempt = now()
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 }
var tries = 0
while tries < 2 {
tries += 1
@@ -81,25 +88,30 @@ import RastrilloApple
// failure to get a proof: nothing to show; next time.
return false
}
+ guard live() else { return false }
do {
let answer = try await client.connectAsk(assertion: proof.assertion, verifier: proof.verifier)
+ guard live() else { return false }
if answer.state == .notLinked { notLinked = true; ask.show(.notLinked); return false }
await ask.load()
return true
} catch .server(422, _, "failed") where tries < 2 {
+ guard live() else { return false }
continue
} catch .server(409, _, "not_linked") {
+ guard live() else { return false }
notLinked = true
ask.show(.notLinked)
return false
} catch {
// superseded, unavailable, Ask off, a refused session: Ask as
// Base says it is now.
+ guard live() else { return false }
await ask.load()
return false
}
}
- await ask.load()
+ if live() { await ask.load() }
return false
}
}
diff --git a/native/apple/Sources/BaseKit/Session/BaseSession.swift b/native/apple/Sources/BaseKit/Session/BaseSession.swift
index fcc6133..ced858f 100644
--- a/native/apple/Sources/BaseKit/Session/BaseSession.swift
+++ b/native/apple/Sources/BaseKit/Session/BaseSession.swift
@@ -67,6 +67,17 @@ import RastrilloApple
/// older generation publishes nothing.
@ObservationIgnored private(set) var generation = 0
@ObservationIgnored private(set) var refreshing: Task<Void, Never>?
+ /// Ask's set-up running on its own (a state or a write said reconnect):
+ /// the session owns it, and cancels it on sign-out and in the background.
+ @ObservationIgnored private(set) var settingUp: Task<Void, Never>?
+
+ func startSetup() {
+ guard let askSetup, settingUp == nil else { return }
+ settingUp = Task { [weak self] in
+ _ = await askSetup.runIfNeeded()
+ self?.settingUp = nil
+ }
+ }
/// An Oficina ID assertion addressed to `audience` (Equipo): the kit's.
@ObservationIgnored lazy var assertion: @MainActor (URL) async throws -> (assertion: String, verifier: String) = { [oficina] audience in
try await oficina.assertion(for: audience)
@@ -101,9 +112,10 @@ import RastrilloApple
guard let self, self.generation == epoch else { throw CancellationError() }
return try await self.assertion(equipo)
}, fallbackEquipo: { [weak self] in self?.me?.equipoOrigin })
- ask.onNeedsSetup = { [weak self, weak setup] in
- guard let self, self.generation == epoch, let setup else { return }
- Task { await setup.runIfNeeded() }
+ setup.isCurrent = { [weak self] in self?.generation == epoch }
+ ask.onNeedsSetup = { [weak self] in
+ guard let self, self.generation == epoch else { return }
+ self.startSetup()
}
self.ask = ask
askSetup = setup
@@ -116,7 +128,9 @@ import RastrilloApple
generation += 1
refreshing?.cancel()
refreshing = nil
- ask?.pause()
+ settingUp?.cancel()
+ settingUp = nil
+ ask?.dispose()
ask = nil; askSetup = nil; client = nil; transport = nil; account = nil
signedIn = nil; me = nil; home = nil
}
@@ -128,7 +142,7 @@ import RastrilloApple
let epoch = generation
async let me = try? client.me()
async let home = try? client.home()
- await ask?.load()
+ await ask?.resume()
let (newMe, newHome) = await (me, home)
guard generation == epoch, !Task.isCancelled else { return }
if let newMe { self.me = newMe }
@@ -147,7 +161,11 @@ import RastrilloApple
}
/// The app went away: Ask stops listening.
- public func background() { ask?.pause() }
+ public func background() {
+ settingUp?.cancel()
+ settingUp = nil
+ ask?.pause()
+ }
/// The session's transport, for what loads from Base's origin (icons).
public var iconTransport: NativeTransport? { transport }
diff --git a/native/apple/Tests/BaseKitTests/SessionTests.swift b/native/apple/Tests/BaseKitTests/SessionTests.swift
index 18675d3..9e88123 100644
--- a/native/apple/Tests/BaseKitTests/SessionTests.swift
+++ b/native/apple/Tests/BaseKitTests/SessionTests.swift
@@ -123,3 +123,59 @@ extension SessionTests {
XCTAssertEqual(session.signedIn?.origin.host, "\(other.label).base.invalid")
}
}
+
+extension SessionTests {
+ /// Astra's Task 16 finding 3 probes: Ask moves to reconnect, its set-up
+ /// 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())
+ 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("/api/v1/ask/oficina", #"{"state":"ready","renew_after":"2026-11-28T10:00:00Z"}"#)
+ for path in ["/api/v1/me", "/api/v1/home", "/ask/state"] { t.release(path) }
+ session.begin(identity: "id-alice", origin: URL(string: "https://alice.example")!, transport: t)
+ await session.refreshing?.value
+ let ask = try XCTUnwrap(session.ask)
+ try await waitUntil { t.calls.contains("/ask/events?after=7") }
+ ask.apply(.state(.reconnect))
+ try await waitUntil { t.calls.contains("/api/v1/ask/oficina") }
+ return (session, t, ask)
+ }
+
+ func testALateSetUpAfterSignOutStartsNothing() async throws {
+ let (session, t, ask) = try await setupHeldAtPost()
+ session.end()
+ t.release("/api/v1/ask/oficina")
+ try await Task.sleep(for: .milliseconds(300))
+ XCTAssertEqual(t.calls.filter { $0.hasPrefix("/ask/events") }.count, 1, "no stream after sign-out")
+ XCTAssertEqual(t.calls.filter { $0 == "/ask/state" }.count, 1, "no state read after sign-out")
+ XCTAssertTrue(ask.disposed)
+ }
+
+ func testALateSetUpInTheBackgroundStartsNothing() async throws {
+ let (session, t, ask) = try await setupHeldAtPost()
+ session.background()
+ t.release("/api/v1/ask/oficina")
+ try await Task.sleep(for: .milliseconds(300))
+ XCTAssertEqual(t.calls.filter { $0.hasPrefix("/ask/events") }.count, 1, "no stream in the background")
+ XCTAssertEqual(ask.phase, .reconnect)
+ // Coming forward reads and listens again, as it should.
+ await session.foreground()
+ try await waitUntil { t.calls.filter { $0.hasPrefix("/ask/events") }.count == 2 }
+ session.end()
+ }
+
+ /// A paused or disposed model refuses new listening work outright.
+ func testAPausedModelRefusesNewWork() async {
+ let t = GatedTransport()
+ let ask = AskModel(client: BaseClient(transport: t) {})
+ ask.pause()
+ await ask.load()
+ XCTAssertEqual(t.calls, [])
+ ask.dispose()
+ await ask.resume()
+ XCTAssertEqual(t.calls, [], "a disposed model never comes back")
+ }
+}