import Foundation import Observation import SwiftUI /// Ask Base: the conversation, its jobs and cards and the turn in flight, /// kept as ask.js keeps them (internal/look/static/ask.js), so the apps /// draw the same thread the web draws from the same JSON and events. /// /// - `load()` reads `/ask/state` and starts the event stream after its /// cursor; `pause()` stops it; `resume()` is the app coming forward. /// - Events apply in place: a reply takes its thinking bubble's or draft's /// place; a job redraws in place and keeps its cards; a card of a job /// hangs under it while open and goes into its view once ended. /// - Writes carry idempotency keys: a message resent after a lost answer /// reuses its key, so Equipo does the work once. @MainActor @Observable public final class AskModel { // MARK: What the thread draws /// The Assistant's reply, streaming in. public struct Draft: Equatable, Sendable { public var turnID: String public var text: String /// Equipo's offsets count UTF-8 bytes. var bytes: Int /// The turn ended: no caret. public var settled: Bool } /// The bubble that sits where the reply will be while the Assistant /// works: three dots, then Equipo's glance or activity line. public struct Thinking: Equatable, Sendable { public var turnID: String public var line: String? var glanced: Bool } /// A job's pill, the open cards hanging under it, and the cards that /// have ended, listed in its view. public struct Job: Equatable, Sendable { public var card: AskCard public var open: [AskCard] public var ended: [AskCard] public var state: JobState { card.jobState ?? .working } public init(card: AskCard, open: [AskCard] = [], ended: [AskCard] = []) { self.card = card; self.open = open; self.ended = ended } } /// An open connect card, drawn as the Connect Oficina button; connected, /// a quiet line. public struct Offer: Equatable, Sendable { public var card: AskCard public var connected: Bool } public enum Entry: Equatable, Sendable, Identifiable { case message(AskMessage) case draft(Draft) case thinking(Thinking) case job(Job) case card(AskCard) case offer(Offer) public var id: String { switch self { case .message(let m): "m:" + m.id case .draft(let d): "d:" + d.turnID case .thinking(let t): "t:" + t.turnID case .job(let j): "j:" + j.card.id case .card(let c): "c:" + c.id case .offer(let o): "o:" + o.card.id } } } public private(set) var phase: AskPhase = .loading { didSet { if phase != oldValue, phase == .connect || phase == .reconnect { onNeedsSetup?() } } } /// Ask became connect or reconnect (a state read, a stream's state, a /// write's 409 reconnect): the session runs AskSetup. @ObservationIgnored public var onNeedsSetup: (@MainActor () -> Void)? public private(set) var entries: [Entry] = [] /// The person's turn in flight (never a quiet one): Stop shows while /// there is one. public private(set) var turn: AskTurn? /// The line under the conversation: a waiting turn's notice, a failure, /// an activity with no bubble to say it in. public private(set) var status = "" /// When Ask's Oficina ID key wants renewing (Task 7), and where Equipo is. public private(set) var renewAfter: Date? /// Base says the member disconnected Ask (nil: it doesn't say). public private(set) var disconnected: Bool? public private(set) var equipoOrigin: URL? /// The composer's text. public var text = "" public private(set) var sending = false /// Cards with an answer on its way, or a paused job's Carry on now: /// their buttons are disabled. public private(set) var answering: Set = [] /// Jobs whose Carry on now failed and can be tried again: the line /// their view shows under the button (job id to text). public private(set) var carryOnErrors: [String: String] = [:] /// Jobs waiting on the person (asking or stopped): the sidebar's badge. public var waitingJobs: Int { entries.reduce(0) { n, entry in if case .job(let j) = entry, j.state == .asking || j.state == .stopped { return n + 1 } return n } } /// The thread is empty: Ask's empty line shows. public var isEmpty: Bool { entries.isEmpty } // MARK: Wiring let client: BaseClient /// Runs `body` after `delay` (tests run it at once, or never). let schedule: @MainActor (Duration, @escaping @MainActor () -> Void) -> Void /// Says a line to VoiceOver once (a failed Carry on now's; tests record /// them). let announce: @MainActor (String) -> Void public init(client: BaseClient, schedule: @escaping @MainActor (Duration, @escaping @MainActor () -> Void) -> Void = AskModel.later, announce: @escaping @MainActor (String) -> Void = AskModel.announce) { self.client = client self.schedule = schedule self.announce = announce } /// Posts `line` as an accessibility announcement. public static func announce(_ line: String) { AccessibilityNotification.Announcement(line).post() } public static func later(_ delay: Duration, _ body: @escaping @MainActor () -> Void) { Task { @MainActor in try? await Task.sleep(for: delay) body() } } // Turns that have ended stay ended: the send's answer, carrying the // turn as it was queued, can come after the turn's events ended it. private var over: Set = [] private var quiet: Set = [] /// Each job's newest card, for its job to place when it is drawn. private var jobCards: [String: AskCard] = [:] /// The message in flight or of unknown outcome, and its key. private var pendingSend: (text: String, key: String)? private var answerKeys: [String: (signature: String, key: String)] = [:] private var carryOnKeys: [String: (revision: Int64, key: String)] = [:] private var cancelKey: (turn: String, key: String)? private var stream: Task? private var generation = 0 /// The newest event id the stream has seen: where a reconnect starts. public private(set) var cursor: Int64? // MARK: Loading and the stream /// Reads `/ask/state`, draws it, and listens for what comes after it. /// /// 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 do { snapshot = try await client.askState() } catch { guard generation == epoch else { return } if error != .unauthenticated { phase = .unavailable } return } guard generation == epoch, !Task.isCancelled else { return } apply(snapshot) if phase.chatting { listen(after: snapshot.cursor) } } /// The app came forward: read afresh and listen again. 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 } 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() } } func stopStream() { generation += 1 stream?.cancel() stream = nil } /// Listens from `cursor`. A stream Base ends cleanly reconnects from the /// newest id after its `retry:`; an offline one waits (two seconds /// more each time, up to twelve) then reads the state afresh; one Base /// 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 stream = Task { [weak self] in var failures = 0 // Each round holds the model only while it runs; between rounds // the task keeps no strong reference. (A helper method rather than // `guard let self` in this loop: Swift 6.4.2's release optimiser // crashes on the latter, in CopyPropagation.) while !Task.isCancelled { guard let model = self else { return } guard await model.streamRound(epoch: epoch, failures: &failures) else { return } } } } /// One connection to the event stream. Returns whether to keep going. private func streamRound(epoch: Int, failures: inout Int) async -> Bool { guard generation == epoch else { return false } let client = self.client do { try await client.events(after: cursor, onRetry: { [weak self] ms in await self?.retryAfter(ms) }) { [weak self] event, id in await self?.receive(event, id: id, epoch: epoch) } failures = 0 guard generation == epoch, phase.chatting else { return false } try? await Task.sleep(for: .milliseconds(max(500, retryMilliseconds))) return true } catch { guard generation == epoch, !Task.isCancelled else { return false } switch error as? BaseAPIError ?? .badResponse { case .unauthenticated: return false case .offline: failures = min(failures + 1, 6) try? await Task.sleep(for: .seconds(2 * failures)) guard generation == epoch, !Task.isCancelled else { return false } reload() return false default: reload() return false } } } /// The stream's `retry:` advice: how long to wait before reconnecting. private var retryMilliseconds = 3000 private func retryAfter(_ ms: Int) { retryMilliseconds = ms } /// Reads the state afresh from outside the stream's own task, which /// the load cancels as it stops the stream. private func reload() { Task { await self.load() } } private func receive(_ event: AskEvent, id: Int64?, epoch: Int) { guard generation == epoch else { return } if let id { cursor = id } apply(event) } // MARK: Writes /// Sends the composer's text. Its key is kept until the outcome is /// known, so sending the same text again after a lost answer is the same /// message to Equipo; different text gets a fresh key. public func send() async { let body = text.trimmingCharacters(in: .whitespacesAndNewlines) guard !body.isEmpty, !sending, turn == nil else { return } let key = pendingSend?.text == body ? pendingSend!.key : BaseClient.newKey() pendingSend = (body, key) sending = true defer { sending = false } do { let sent = try await client.send(body, key: key) pendingSend = nil text = "" status = "" if phase != .ready { phase = .ready } if let message = sent.message { add(message) } if let t = sent.turn { setTurn(t) } } catch { refusedWrite(error, keepsKey: { pendingSend = nil }) // The message's own failure line (copy review), in place of // the answers' and Stop's. if status == BaseText.text("ask.not_sent") { status = BaseText.text("native.ask.send.error") } } } /// Stop: cancels the turn in flight. public func stop() async { guard let turn else { return } let key = cancelKey?.turn == turn.id ? cancelKey!.key : BaseClient.newKey() cancelKey = (turn.id, key) do { try await client.cancel(turn: turn.id, key: key) cancelKey = nil } catch { refusedWrite(error, keepsKey: { cancelKey = nil }) } } /// One of a card's choices, bound to the revision the person saw. A 409 /// means the card moved on (a new revision, or answered elsewhere): the /// conversation is read afresh and the person chooses again; it is never /// resent. Without a runner that can answer, nothing was answered and /// the card stays open. public func answer(_ card: AskCard, _ option: AskCard.Option) async { guard card.isOpen, !answering.contains(card.id) else { return } let signature = "\(card.revision)|\(option.value)" let key = answerKeys[card.id]?.signature == signature ? answerKeys[card.id]!.key : BaseClient.newKey() answerKeys[card.id] = (signature, key) answering.insert(card.id) defer { answering.remove(card.id) } do { let out = try await client.answer(card: card.id, choice: option.value, revision: card.revision, key: key) answerKeys[card.id] = nil if phase != .ready { phase = .ready } if let c = out.card { add(c) } if let m = out.message { add(m) } if let t = out.turn { setTurn(t) } } catch { if case .server(409, _, let state) = error, state != "norunner", state != "oldrunner" { answerKeys[card.id] = nil await load() return } refusedWrite(error, keepsKey: { answerKeys[card.id] = nil }) } } /// A paused job's "Carry on now", bound to the revision the person /// saw (ask.js `carryOnNow`). Its key is kept until an answer settles /// the outcome, so pressing it again after a lost answer is the same /// request. A 409 (the job moved on, is no longer paused, no longer /// offers it, or is gone) or an answer with no card reads the /// conversation afresh; it is never resent. A failure that can be tried /// again says so in the job's view (`carryOnErrors`), as well as on the /// status line, which a sheet over the thread hides. public func carryOn(_ job: AskCard) async { guard job.offersCarryOn, !answering.contains(job.id) else { return } let key = carryOnKeys[job.id]?.revision == job.revision ? carryOnKeys[job.id]!.key : BaseClient.newKey() carryOnKeys[job.id] = (job.revision, key) answering.insert(job.id) carryOnErrors[job.id] = nil defer { answering.remove(job.id) } do { let out = try await client.carryOn(card: job.id, revision: job.revision, key: key) carryOnKeys[job.id] = nil if phase != .ready { phase = .ready } if let c = out.card { add(c) } else { await load() } } catch { if case .server(409, _, let state) = error, state != "norunner", state != "oldrunner" { carryOnKeys[job.id] = nil await load() return } refusedWrite(error, keepsKey: { carryOnKeys[job.id] = nil }) if Self.tryAgain(error) { // Shown under the button and said once: the status line // is no live region, and a sheet may cover it. carryOnErrors[job.id] = BaseText.text("ask.not_sent") announce(BaseText.text("ask.not_sent")) } } } /// Whether refusedWrite says to try again (ask.not_sent): no answer, /// an unreadable one, or a refusal that is not one of Ask's states. static func tryAgain(_ error: BaseAPIError) -> Bool { switch error { case .unauthenticated: false case .offline, .badResponse: true case .server(let code, _, let state): code != 409 && !(state.map { [.connect, .pending, .reconnect, .norunner, .oldrunner, .notLinked].contains(AskPhase(server: $0)) } ?? false) } } /// What a refused write shows (ask.js `post`): Ask's own states stand in /// for the conversation, or add their note; a 409 is stale (the next /// events show how things are); anything else asks to try again. The /// key is forgotten only once a readable answer settles the outcome: /// never after an offline failure, a 502, an unreadable answer or a /// cancellation. private func refusedWrite(_ error: BaseAPIError, keepsKey forget: () -> Void) { switch error { case .unauthenticated: forget() case .offline: status = BaseText.text("ask.not_sent") case .server(let code, _, let state): if code != 502 { forget() } let phase = state.map { AskPhase(server: $0) } if let phase, [.connect, .pending, .reconnect, .norunner, .oldrunner, .notLinked].contains(phase) { show(phase) } else if code != 409 { status = BaseText.text("ask.not_sent") } case .badResponse: // An unreadable answer (or the request cancelled once it may // have reached Base) leaves the outcome unknown: the key stays, // so sending again is the same write. status = BaseText.text("ask.not_sent") } } // MARK: Applying what Base says /// Draws `/ask/state` afresh (ask.js `load`). func apply(_ s: AskSnapshot) { disconnected = s.disconnected phase = s.state renewAfter = s.renewAfter if let origin = s.equipoOrigin { equipoOrigin = origin } guard phase.chatting else { return } entries = [] jobCards = [:] // ask.js load() clears its offers and their timers too. waitingOffers = [:] offerRevisions = [:] offerTimers = [] offerEpoch += 1 over = [] quiet = [] turn = nil status = "" for m in s.messages { add(m) } for j in s.jobs { add(j.card) for c in j.cards { add(c) } } for c in s.cards { add(c) } setTurn(s.turn, line: s.status) } /// Draws a state with no stream: previews and snapshots. public func applyForPreview(_ s: AskSnapshot) { apply(s) } /// One event from the stream (ask.js `listen`). public func apply(_ event: AskEvent) { switch event { case .message(let m): add(m) case .delta(let d): delta(d) case .card(let c): add(c) case .turn(let t): setTurn(t) case .glance(let g): glance(g) case .activity(let a): activity(a) case .state(let s): stopStream() phase = s } } private func index(_ id: String) -> Int? { entries.firstIndex { $0.id == id } } /// A message, once. The Assistant's reply takes its draft's or thinking /// bubble's place; open connect cards waiting for it follow it. func add(_ m: AskMessage) { guard index("m:" + m.id) == nil else { return } if !m.isPerson, !m.turnID.isEmpty, let at = index("d:" + m.turnID) ?? index("t:" + m.turnID) { entries[at] = .message(m) } else { entries.append(.message(m)) } if !m.isPerson { reoffer() } } /// A streamed word. The turn's thinking bubble becomes its draft; /// words whose offset isn't where the draft ends are dropped, as ask.js /// drops them. func delta(_ d: AskDelta) { if let at = index("t:" + d.turnID) { entries[at] = .draft(Draft(turnID: d.turnID, text: "", bytes: 0, settled: false)) } else if index("d:" + d.turnID) == nil { // Above the turn's connect button, should it already show. let draft = Entry.draft(Draft(turnID: d.turnID, text: "", bytes: 0, settled: false)) if let offer = entries.firstIndex(where: { if case .offer(let o) = $0 { o.card.turnID == d.turnID } else { false } }) { entries.insert(draft, at: offer) } else { entries.append(draft) } } guard let at = index("d:" + d.turnID), case .draft(var draft) = entries[at], d.offset == Int64(draft.bytes) else { return } draft.text += d.text draft.bytes += d.text.utf8.count entries[at] = .draft(draft) } /// Equipo's glance: one line on the turn in flight, before its words, /// in its thinking bubble; never kept. func glance(_ g: AskLine) { let text = g.text.trimmingCharacters(in: .whitespacesAndNewlines) guard !text.isEmpty, !quiet.contains(g.turnID), turn?.id == g.turnID, let at = index("t:" + g.turnID), case .thinking(var t) = entries[at], !t.glanced else { return } t.line = text t.glanced = true entries[at] = .thinking(t) } /// What the Assistant is doing: in its bubble unless a glance holds it, /// else in the status line. func activity(_ a: AskLine) { guard !a.text.isEmpty, !quiet.contains(a.turnID) else { return } if let at = index("t:" + a.turnID), case .thinking(var t) = entries[at] { guard !t.glanced else { return } t.line = a.text entries[at] = .thinking(t) } else if turn?.id == a.turnID { status = a.text } } /// A card or a job (ask.js `addCard`, `addJob`). func add(_ c: AskCard) { if c.isJob { addJob(c); return } if c.kind == "connect", c.connectLink != nil || index("o:" + c.id) != nil { offer(c) return } guard AskCard.drawnKinds.contains(c.kind), c.isOpen || !c.result.isEmpty else { remove(card: c.id) jobCards[c.id] = nil return } if let old = card(c.id), old.revision > c.revision { return } if !c.job.isEmpty { jobCards[c.id] = c } if !c.job.isEmpty, let at = index("j:" + c.job), case .job(var job) = entries[at] { removeLoose(c.id) job.open.removeAll { $0.id == c.id } job.ended.removeAll { $0.id == c.id } if c.isOpen { if let i = job.open.firstIndex(where: { $0.id == c.id }) { job.open[i] = c } else { job.open.append(c) } } else { job.ended.append(c) } entries[at] = .job(job) return } if let at = index("c:" + c.id) { entries[at] = .card(c) } else { entries.append(.card(c)) } } private func addJob(_ c: AskCard) { guard c.jobState != nil else { return } if let at = index("j:" + c.id), case .job(var job) = entries[at] { guard job.card.revision <= c.revision else { return } job.card = c entries[at] = .job(job) return } var job = Job(card: c, open: [], ended: []) // Its loose cards, drawn before it was, move under it, or into its view. for entry in entries { guard case .card(let loose) = entry, loose.job == c.id else { continue } let latest = jobCards[loose.id] ?? loose if latest.isOpen { job.open.append(latest) } else { job.ended.append(latest) } } entries.removeAll { if case .card(let loose) = $0 { loose.job == c.id } else { false } } entries.append(.job(job)) } private func card(_ id: String) -> AskCard? { for entry in entries { switch entry { case .card(let c) where c.id == id: return c case .job(let j): if let c = j.open.first(where: { $0.id == id }) ?? j.ended.first(where: { $0.id == id }) { return c } default: continue } } return nil } private func removeLoose(_ id: String) { entries.removeAll { $0.id == "c:" + id } } private func remove(card id: String) { removeLoose(id) for (at, entry) in entries.enumerated() { guard case .job(var job) = entry else { continue } let before = job.open.count + job.ended.count job.open.removeAll { $0.id == id } job.ended.removeAll { $0.id == id } if job.open.count + job.ended.count != before { entries[at] = .job(job) } } } /// An open connect card ends the Assistant's newest reply; one whose /// reply is still on its way waits for it (reoffer), and if no words /// come for `offerWait`, shows on its own (ask.js `wait`). Connected, /// it becomes a quiet line where it is. private var waitingOffers: [String: AskCard] = [:] /// The newest revision seen of each connect card, drawn, waiting or /// neither: an older one never replaces it (ask.js `offer`). private var offerRevisions: [String: Int64] = [:] /// Offers waiting on a timer, and the timers' generation: a fresh /// snapshot ends every timer. private var offerTimers: Set = [] private var offerEpoch = 0 static let offerWait: Duration = .seconds(3) private func offer(_ c: AskCard) { if let known = offerRevisions[c.id], known > c.revision { return } offerRevisions[c.id] = c.revision if !c.isOpen { waitingOffers[c.id] = nil if let at = index("o:" + c.id) { entries[at] = .offer(Offer(card: c, connected: true)) } return } guard c.connectLink != nil else { return } if onItsWay(c.turnID) { if index("o:" + c.id) == nil { waitingOffers[c.id] = c wait(c.id) } else if case .offer(var o)? = entries.first(where: { $0.id == "o:" + c.id }), let at = index("o:" + c.id) { o.card = c entries[at] = .offer(o) } return } waitingOffers[c.id] = nil put(c) } /// After `offerWait`: the reply's words are streaming, so wait again; /// otherwise show the offer on its own. private func wait(_ id: String) { guard !offerTimers.contains(id) else { return } offerTimers.insert(id) let epoch = offerEpoch schedule(Self.offerWait) { [weak self] in guard let self, self.offerEpoch == epoch else { return } self.offerTimers.remove(id) guard let c = self.waitingOffers[id] else { return } if self.index("d:" + c.turnID) != nil, self.onItsWay(c.turnID) { self.wait(id) } else if self.index("o:" + id) == nil { self.waitingOffers[id] = nil self.put(c) } } } private func onItsWay(_ turnID: String) -> Bool { guard !turnID.isEmpty else { return false } if entries.contains(where: { if case .message(let m) = $0 { !m.isPerson && m.turnID == turnID } else { false } }) { return false } return !over.contains(turnID) || index("t:" + turnID) != nil || index("d:" + turnID) != nil } private func reoffer() { for (id, c) in waitingOffers where !onItsWay(c.turnID) { waitingOffers[id] = nil put(c) } } /// After the newest reply, or at the end with none. private func put(_ c: AskCard) { entries.removeAll { $0.id == "o:" + c.id } let offer = Entry.offer(Offer(card: c, connected: false)) if let last = entries.lastIndex(where: { if case .message(let m) = $0 { !m.isPerson } else { false } }) { entries.insert(offer, at: last + 1) } else { entries.append(offer) } } // MARK: Turns /// A turn's state (ask.js `setTurn`). A quiet turn shows nothing. One in /// flight is the turn: waiting says so in the status line, else its /// thinking bubble shows. One that ends settles its bubble and drafts. func setTurn(_ t: AskTurn?, line: String = "") { if let t, t.id.isEmpty || over.contains(t.id) { return } if let t, t.ended { over.insert(t.id) } if let t, t.quiet { quiet.insert(t.id) if t.ended { settle(t) } return } if let t, !t.ended { turn = t if t.state == "waiting" { drop(t.id) status = line.isEmpty ? BaseText.text("ask.waiting") : line } else { status = "" think(t.id) } return } if let t { unthink(t) reoffer() } if let t, let current = turn, t.id != current.id { return } turn = nil status = t?.state == "failed" ? BaseText.text("ask.failed") : "" settle(t) } private func think(_ id: String) { guard index("t:" + id) == nil, index("d:" + id) == nil else { return } entries.append(.thinking(Thinking(turnID: id, line: nil, glanced: false))) } private func drop(_ id: String) { entries.removeAll { $0.id == "t:" + id } } /// A replied turn's bubble waits a little for its reply (it may come /// just after); otherwise, or if it never comes, it goes. private func unthink(_ t: AskTurn) { guard index("t:" + t.id) != nil else { return } if t.state == "replied", t.replyID.isEmpty || index("m:" + t.replyID) == nil { schedule(.seconds(5)) { [weak self] in self?.drop(t.id) self?.reoffer() } return } drop(t.id) } /// Ends turn `t`'s drafts (every draft with none): a cancelled or /// failed turn's go; the rest stay as written, without the caret. private func settle(_ t: AskTurn?) { let gone = t.map { $0.state == "cancelled" || $0.state == "failed" } ?? false entries = entries.compactMap { entry in guard case .draft(var d) = entry, t == nil || d.turnID == t!.id else { return entry } if gone { return nil } d.settled = true return .draft(d) } } }