| 1 | import Foundation |
| 2 | import Observation |
| 3 | import SwiftUI |
| 4 | |
| 5 | /// Ask Base: the conversation, its jobs and cards and the turn in flight, |
| 6 | /// kept as ask.js keeps them (internal/look/static/ask.js), so the apps |
| 7 | /// draw the same thread the web draws from the same JSON and events. |
| 8 | /// |
| 9 | /// - `load()` reads `/ask/state` and starts the event stream after its |
| 10 | /// cursor; `pause()` stops it; `resume()` is the app coming forward. |
| 11 | /// - Events apply in place: a reply takes its thinking bubble's or draft's |
| 12 | /// place; a job redraws in place and keeps its cards; a card of a job |
| 13 | /// hangs under it while open and goes into its view once ended. |
| 14 | /// - Writes carry idempotency keys: a message resent after a lost answer |
| 15 | /// reuses its key, so Equipo does the work once. |
| 16 | @MainActor @Observable public final class AskModel { |
| 17 | // MARK: What the thread draws |
| 18 | |
| 19 | /// The Assistant's reply, streaming in. |
| 20 | public struct Draft: Equatable, Sendable { |
| 21 | public var turnID: String |
| 22 | public var text: String |
| 23 | /// Equipo's offsets count UTF-8 bytes. |
| 24 | var bytes: Int |
| 25 | /// The turn ended: no caret. |
| 26 | public var settled: Bool |
| 27 | } |
| 28 | |
| 29 | /// The bubble that sits where the reply will be while the Assistant |
| 30 | /// works: three dots, then Equipo's glance or activity line. |
| 31 | public struct Thinking: Equatable, Sendable { |
| 32 | public var turnID: String |
| 33 | public var line: String? |
| 34 | var glanced: Bool |
| 35 | } |
| 36 | |
| 37 | /// A job's pill, the open cards hanging under it, and the cards that |
| 38 | /// have ended, listed in its view. |
| 39 | public struct Job: Equatable, Sendable { |
| 40 | public var card: AskCard |
| 41 | public var open: [AskCard] |
| 42 | public var ended: [AskCard] |
| 43 | public var state: JobState { card.jobState ?? .working } |
| 44 | public init(card: AskCard, open: [AskCard] = [], ended: [AskCard] = []) { self.card = card; self.open = open; self.ended = ended } |
| 45 | } |
| 46 | |
| 47 | /// An open connect card, drawn as the Connect Oficina button; connected, |
| 48 | /// a quiet line. |
| 49 | public struct Offer: Equatable, Sendable { |
| 50 | public var card: AskCard |
| 51 | public var connected: Bool |
| 52 | } |
| 53 | |
| 54 | public enum Entry: Equatable, Sendable, Identifiable { |
| 55 | case message(AskMessage) |
| 56 | case draft(Draft) |
| 57 | case thinking(Thinking) |
| 58 | case job(Job) |
| 59 | case card(AskCard) |
| 60 | case offer(Offer) |
| 61 | |
| 62 | public var id: String { |
| 63 | switch self { |
| 64 | case .message(let m): "m:" + m.id |
| 65 | case .draft(let d): "d:" + d.turnID |
| 66 | case .thinking(let t): "t:" + t.turnID |
| 67 | case .job(let j): "j:" + j.card.id |
| 68 | case .card(let c): "c:" + c.id |
| 69 | case .offer(let o): "o:" + o.card.id |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | public private(set) var phase: AskPhase = .loading { |
| 75 | didSet { if phase != oldValue, phase == .connect || phase == .reconnect { onNeedsSetup?() } } |
| 76 | } |
| 77 | /// Ask became connect or reconnect (a state read, a stream's state, a |
| 78 | /// write's 409 reconnect): the session runs AskSetup. |
| 79 | @ObservationIgnored public var onNeedsSetup: (@MainActor () -> Void)? |
| 80 | public private(set) var entries: [Entry] = [] |
| 81 | /// The person's turn in flight (never a quiet one): Stop shows while |
| 82 | /// there is one. |
| 83 | public private(set) var turn: AskTurn? |
| 84 | /// The line under the conversation: a waiting turn's notice, a failure, |
| 85 | /// an activity with no bubble to say it in. |
| 86 | public private(set) var status = "" |
| 87 | /// When Ask's Oficina ID key wants renewing (Task 7), and where Equipo is. |
| 88 | public private(set) var renewAfter: Date? |
| 89 | /// Base says the member disconnected Ask (nil: it doesn't say). |
| 90 | public private(set) var disconnected: Bool? |
| 91 | public private(set) var equipoOrigin: URL? |
| 92 | /// The composer's text. |
| 93 | public var text = "" |
| 94 | public private(set) var sending = false |
| 95 | /// Cards with an answer on its way, or a paused job's Carry on now: |
| 96 | /// their buttons are disabled. |
| 97 | public private(set) var answering: Set<String> = [] |
| 98 | /// Jobs whose Carry on now failed and can be tried again: the line |
| 99 | /// their view shows under the button (job id to text). |
| 100 | public private(set) var carryOnErrors: [String: String] = [:] |
| 101 | |
| 102 | /// Jobs waiting on the person (asking or stopped): the sidebar's badge. |
| 103 | public var waitingJobs: Int { |
| 104 | entries.reduce(0) { n, entry in |
| 105 | if case .job(let j) = entry, j.state == .asking || j.state == .stopped { return n + 1 } |
| 106 | return n |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | /// The thread is empty: Ask's empty line shows. |
| 111 | public var isEmpty: Bool { entries.isEmpty } |
| 112 | |
| 113 | // MARK: Wiring |
| 114 | |
| 115 | let client: BaseClient |
| 116 | /// Runs `body` after `delay` (tests run it at once, or never). |
| 117 | let schedule: @MainActor (Duration, @escaping @MainActor () -> Void) -> Void |
| 118 | /// Says a line to VoiceOver once (a failed Carry on now's; tests record |
| 119 | /// them). |
| 120 | let announce: @MainActor (String) -> Void |
| 121 | |
| 122 | public init(client: BaseClient, |
| 123 | schedule: @escaping @MainActor (Duration, @escaping @MainActor () -> Void) -> Void = AskModel.later, |
| 124 | announce: @escaping @MainActor (String) -> Void = AskModel.announce) { |
| 125 | self.client = client |
| 126 | self.schedule = schedule |
| 127 | self.announce = announce |
| 128 | } |
| 129 | |
| 130 | /// Posts `line` as an accessibility announcement. |
| 131 | public static func announce(_ line: String) { AccessibilityNotification.Announcement(line).post() } |
| 132 | |
| 133 | public static func later(_ delay: Duration, _ body: @escaping @MainActor () -> Void) { |
| 134 | Task { @MainActor in |
| 135 | try? await Task.sleep(for: delay) |
| 136 | body() |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | // Turns that have ended stay ended: the send's answer, carrying the |
| 141 | // turn as it was queued, can come after the turn's events ended it. |
| 142 | private var over: Set<String> = [] |
| 143 | private var quiet: Set<String> = [] |
| 144 | /// Each job's newest card, for its job to place when it is drawn. |
| 145 | private var jobCards: [String: AskCard] = [:] |
| 146 | /// The message in flight or of unknown outcome, and its key. |
| 147 | private var pendingSend: (text: String, key: String)? |
| 148 | private var answerKeys: [String: (signature: String, key: String)] = [:] |
| 149 | private var carryOnKeys: [String: (revision: Int64, key: String)] = [:] |
| 150 | private var cancelKey: (turn: String, key: String)? |
| 151 | private var stream: Task<Void, Never>? |
| 152 | private var generation = 0 |
| 153 | /// The newest event id the stream has seen: where a reconnect starts. |
| 154 | public private(set) var cursor: Int64? |
| 155 | |
| 156 | // MARK: Loading and the stream |
| 157 | |
| 158 | /// Reads `/ask/state`, draws it, and listens for what comes after it. |
| 159 | /// |
| 160 | /// Pausing, or a newer load, while it reads wins: what this one reads |
| 161 | /// then lands on nothing and starts no stream. |
| 162 | public func load() async { |
| 163 | // Paused (the app went away) or disposed (signed out): no new work. |
| 164 | guard !paused, !disposed else { return } |
| 165 | stopStream() |
| 166 | let epoch = generation |
| 167 | let snapshot: AskSnapshot |
| 168 | do { |
| 169 | snapshot = try await client.askState() |
| 170 | } catch { |
| 171 | guard generation == epoch else { return } |
| 172 | if error != .unauthenticated { phase = .unavailable } |
| 173 | return |
| 174 | } |
| 175 | guard generation == epoch, !Task.isCancelled else { return } |
| 176 | apply(snapshot) |
| 177 | if phase.chatting { listen(after: snapshot.cursor) } |
| 178 | } |
| 179 | |
| 180 | /// The app came forward: read afresh and listen again. |
| 181 | public func resume() async { |
| 182 | guard !disposed else { return } |
| 183 | paused = false |
| 184 | await load() |
| 185 | } |
| 186 | |
| 187 | /// The app went away: stop listening, and start nothing new (a late |
| 188 | /// load, a set-up's reload) until it comes forward again. |
| 189 | public func pause() { |
| 190 | stopStream() |
| 191 | paused = true |
| 192 | activity += 1 |
| 193 | } |
| 194 | |
| 195 | /// Signed out, or another account: this model is done for good. |
| 196 | public func dispose() { |
| 197 | pause() |
| 198 | disposed = true |
| 199 | } |
| 200 | |
| 201 | public private(set) var paused = false |
| 202 | public private(set) var disposed = false |
| 203 | /// Bumped by every pause and dispose: work begun before (Ask's set-up) |
| 204 | /// checks it after each suspension and lands nothing if it moved. |
| 205 | public private(set) var activity = 0 |
| 206 | |
| 207 | /// Ask set itself up elsewhere (Task 12): its new state, before a load. |
| 208 | public func show(_ phase: AskPhase) { |
| 209 | guard !disposed else { return } |
| 210 | self.phase = phase |
| 211 | if !phase.chatting { stopStream() } |
| 212 | } |
| 213 | |
| 214 | func stopStream() { |
| 215 | generation += 1 |
| 216 | stream?.cancel() |
| 217 | stream = nil |
| 218 | } |
| 219 | |
| 220 | /// Listens from `cursor`. A stream Base ends cleanly reconnects from the |
| 221 | /// newest id after its `retry:`; an offline one waits (two seconds |
| 222 | /// more each time, up to twelve) then reads the state afresh; one Base |
| 223 | /// refuses (a 410 `cursor_expired` from an old cursor, a 502) reads the |
| 224 | /// state afresh at once, as ask.js does. A `state` event ends it. |
| 225 | func listen(after start: Int64) { |
| 226 | guard !paused, !disposed else { return } |
| 227 | stopStream() |
| 228 | cursor = start |
| 229 | let epoch = generation |
| 230 | stream = Task { [weak self] in |
| 231 | var failures = 0 |
| 232 | // Each round holds the model only while it runs; between rounds |
| 233 | // the task keeps no strong reference. (A helper method rather than |
| 234 | // `guard let self` in this loop: Swift 6.4.2's release optimiser |
| 235 | // crashes on the latter, in CopyPropagation.) |
| 236 | while !Task.isCancelled { |
| 237 | guard let model = self else { return } |
| 238 | guard await model.streamRound(epoch: epoch, failures: &failures) else { return } |
| 239 | } |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | /// One connection to the event stream. Returns whether to keep going. |
| 244 | private func streamRound(epoch: Int, failures: inout Int) async -> Bool { |
| 245 | guard generation == epoch else { return false } |
| 246 | let client = self.client |
| 247 | do { |
| 248 | try await client.events(after: cursor, onRetry: { [weak self] ms in await self?.retryAfter(ms) }) { [weak self] event, id in |
| 249 | await self?.receive(event, id: id, epoch: epoch) |
| 250 | } |
| 251 | failures = 0 |
| 252 | guard generation == epoch, phase.chatting else { return false } |
| 253 | try? await Task.sleep(for: .milliseconds(max(500, retryMilliseconds))) |
| 254 | return true |
| 255 | } catch { |
| 256 | guard generation == epoch, !Task.isCancelled else { return false } |
| 257 | switch error as? BaseAPIError ?? .badResponse { |
| 258 | case .unauthenticated: |
| 259 | return false |
| 260 | case .offline: |
| 261 | failures = min(failures + 1, 6) |
| 262 | try? await Task.sleep(for: .seconds(2 * failures)) |
| 263 | guard generation == epoch, !Task.isCancelled else { return false } |
| 264 | reload() |
| 265 | return false |
| 266 | default: |
| 267 | reload() |
| 268 | return false |
| 269 | } |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | /// The stream's `retry:` advice: how long to wait before reconnecting. |
| 274 | private var retryMilliseconds = 3000 |
| 275 | private func retryAfter(_ ms: Int) { retryMilliseconds = ms } |
| 276 | |
| 277 | /// Reads the state afresh from outside the stream's own task, which |
| 278 | /// the load cancels as it stops the stream. |
| 279 | private func reload() { Task { await self.load() } } |
| 280 | |
| 281 | private func receive(_ event: AskEvent, id: Int64?, epoch: Int) { |
| 282 | guard generation == epoch else { return } |
| 283 | if let id { cursor = id } |
| 284 | apply(event) |
| 285 | } |
| 286 | |
| 287 | // MARK: Writes |
| 288 | |
| 289 | /// Sends the composer's text. Its key is kept until the outcome is |
| 290 | /// known, so sending the same text again after a lost answer is the same |
| 291 | /// message to Equipo; different text gets a fresh key. |
| 292 | public func send() async { |
| 293 | let body = text.trimmingCharacters(in: .whitespacesAndNewlines) |
| 294 | guard !body.isEmpty, !sending, turn == nil else { return } |
| 295 | let key = pendingSend?.text == body ? pendingSend!.key : BaseClient.newKey() |
| 296 | pendingSend = (body, key) |
| 297 | sending = true |
| 298 | defer { sending = false } |
| 299 | do { |
| 300 | let sent = try await client.send(body, key: key) |
| 301 | pendingSend = nil |
| 302 | text = "" |
| 303 | status = "" |
| 304 | if phase != .ready { phase = .ready } |
| 305 | if let message = sent.message { add(message) } |
| 306 | if let t = sent.turn { setTurn(t) } |
| 307 | } catch { |
| 308 | refusedWrite(error, keepsKey: { pendingSend = nil }) |
| 309 | // The message's own failure line (copy review), in place of |
| 310 | // the answers' and Stop's. |
| 311 | if status == BaseText.text("ask.not_sent") { status = BaseText.text("native.ask.send.error") } |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | /// Stop: cancels the turn in flight. |
| 316 | public func stop() async { |
| 317 | guard let turn else { return } |
| 318 | let key = cancelKey?.turn == turn.id ? cancelKey!.key : BaseClient.newKey() |
| 319 | cancelKey = (turn.id, key) |
| 320 | do { |
| 321 | try await client.cancel(turn: turn.id, key: key) |
| 322 | cancelKey = nil |
| 323 | } catch { |
| 324 | refusedWrite(error, keepsKey: { cancelKey = nil }) |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | /// One of a card's choices, bound to the revision the person saw. A 409 |
| 329 | /// means the card moved on (a new revision, or answered elsewhere): the |
| 330 | /// conversation is read afresh and the person chooses again; it is never |
| 331 | /// resent. Without a runner that can answer, nothing was answered and |
| 332 | /// the card stays open. |
| 333 | public func answer(_ card: AskCard, _ option: AskCard.Option) async { |
| 334 | guard card.isOpen, !answering.contains(card.id) else { return } |
| 335 | let signature = "\(card.revision)|\(option.value)" |
| 336 | let key = answerKeys[card.id]?.signature == signature ? answerKeys[card.id]!.key : BaseClient.newKey() |
| 337 | answerKeys[card.id] = (signature, key) |
| 338 | answering.insert(card.id) |
| 339 | defer { answering.remove(card.id) } |
| 340 | do { |
| 341 | let out = try await client.answer(card: card.id, choice: option.value, revision: card.revision, key: key) |
| 342 | answerKeys[card.id] = nil |
| 343 | if phase != .ready { phase = .ready } |
| 344 | if let c = out.card { add(c) } |
| 345 | if let m = out.message { add(m) } |
| 346 | if let t = out.turn { setTurn(t) } |
| 347 | } catch { |
| 348 | if case .server(409, _, let state) = error, state != "norunner", state != "oldrunner" { |
| 349 | answerKeys[card.id] = nil |
| 350 | await load() |
| 351 | return |
| 352 | } |
| 353 | refusedWrite(error, keepsKey: { answerKeys[card.id] = nil }) |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | /// A paused job's "Carry on now", bound to the revision the person |
| 358 | /// saw (ask.js `carryOnNow`). Its key is kept until an answer settles |
| 359 | /// the outcome, so pressing it again after a lost answer is the same |
| 360 | /// request. A 409 (the job moved on, is no longer paused, no longer |
| 361 | /// offers it, or is gone) or an answer with no card reads the |
| 362 | /// conversation afresh; it is never resent. A failure that can be tried |
| 363 | /// again says so in the job's view (`carryOnErrors`), as well as on the |
| 364 | /// status line, which a sheet over the thread hides. |
| 365 | public func carryOn(_ job: AskCard) async { |
| 366 | guard job.offersCarryOn, !answering.contains(job.id) else { return } |
| 367 | let key = carryOnKeys[job.id]?.revision == job.revision ? carryOnKeys[job.id]!.key : BaseClient.newKey() |
| 368 | carryOnKeys[job.id] = (job.revision, key) |
| 369 | answering.insert(job.id) |
| 370 | carryOnErrors[job.id] = nil |
| 371 | defer { answering.remove(job.id) } |
| 372 | do { |
| 373 | let out = try await client.carryOn(card: job.id, revision: job.revision, key: key) |
| 374 | carryOnKeys[job.id] = nil |
| 375 | if phase != .ready { phase = .ready } |
| 376 | if let c = out.card { add(c) } else { await load() } |
| 377 | } catch { |
| 378 | if case .server(409, _, let state) = error, state != "norunner", state != "oldrunner" { |
| 379 | carryOnKeys[job.id] = nil |
| 380 | await load() |
| 381 | return |
| 382 | } |
| 383 | refusedWrite(error, keepsKey: { carryOnKeys[job.id] = nil }) |
| 384 | if Self.tryAgain(error) { |
| 385 | // Shown under the button and said once: the status line |
| 386 | // is no live region, and a sheet may cover it. |
| 387 | carryOnErrors[job.id] = BaseText.text("ask.not_sent") |
| 388 | announce(BaseText.text("ask.not_sent")) |
| 389 | } |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | /// Whether refusedWrite says to try again (ask.not_sent): no answer, |
| 394 | /// an unreadable one, or a refusal that is not one of Ask's states. |
| 395 | static func tryAgain(_ error: BaseAPIError) -> Bool { |
| 396 | switch error { |
| 397 | case .unauthenticated: false |
| 398 | case .offline, .badResponse: true |
| 399 | case .server(let code, _, let state): |
| 400 | code != 409 && !(state.map { [.connect, .pending, .reconnect, .norunner, .oldrunner, .notLinked].contains(AskPhase(server: $0)) } ?? false) |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | /// What a refused write shows (ask.js `post`): Ask's own states stand in |
| 405 | /// for the conversation, or add their note; a 409 is stale (the next |
| 406 | /// events show how things are); anything else asks to try again. The |
| 407 | /// key is forgotten only once a readable answer settles the outcome: |
| 408 | /// never after an offline failure, a 502, an unreadable answer or a |
| 409 | /// cancellation. |
| 410 | private func refusedWrite(_ error: BaseAPIError, keepsKey forget: () -> Void) { |
| 411 | switch error { |
| 412 | case .unauthenticated: |
| 413 | forget() |
| 414 | case .offline: |
| 415 | status = BaseText.text("ask.not_sent") |
| 416 | case .server(let code, _, let state): |
| 417 | if code != 502 { forget() } |
| 418 | let phase = state.map { AskPhase(server: $0) } |
| 419 | if let phase, [.connect, .pending, .reconnect, .norunner, .oldrunner, .notLinked].contains(phase) { |
| 420 | show(phase) |
| 421 | } else if code != 409 { |
| 422 | status = BaseText.text("ask.not_sent") |
| 423 | } |
| 424 | case .badResponse: |
| 425 | // An unreadable answer (or the request cancelled once it may |
| 426 | // have reached Base) leaves the outcome unknown: the key stays, |
| 427 | // so sending again is the same write. |
| 428 | status = BaseText.text("ask.not_sent") |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | // MARK: Applying what Base says |
| 433 | |
| 434 | /// Draws `/ask/state` afresh (ask.js `load`). |
| 435 | func apply(_ s: AskSnapshot) { |
| 436 | disconnected = s.disconnected |
| 437 | phase = s.state |
| 438 | renewAfter = s.renewAfter |
| 439 | if let origin = s.equipoOrigin { equipoOrigin = origin } |
| 440 | guard phase.chatting else { return } |
| 441 | entries = [] |
| 442 | jobCards = [:] |
| 443 | // ask.js load() clears its offers and their timers too. |
| 444 | waitingOffers = [:] |
| 445 | offerRevisions = [:] |
| 446 | offerTimers = [] |
| 447 | offerEpoch += 1 |
| 448 | over = [] |
| 449 | quiet = [] |
| 450 | turn = nil |
| 451 | status = "" |
| 452 | for m in s.messages { add(m) } |
| 453 | for j in s.jobs { |
| 454 | add(j.card) |
| 455 | for c in j.cards { add(c) } |
| 456 | } |
| 457 | for c in s.cards { add(c) } |
| 458 | setTurn(s.turn, line: s.status) |
| 459 | } |
| 460 | |
| 461 | /// Draws a state with no stream: previews and snapshots. |
| 462 | public func applyForPreview(_ s: AskSnapshot) { apply(s) } |
| 463 | |
| 464 | /// One event from the stream (ask.js `listen`). |
| 465 | public func apply(_ event: AskEvent) { |
| 466 | switch event { |
| 467 | case .message(let m): add(m) |
| 468 | case .delta(let d): delta(d) |
| 469 | case .card(let c): add(c) |
| 470 | case .turn(let t): setTurn(t) |
| 471 | case .glance(let g): glance(g) |
| 472 | case .activity(let a): activity(a) |
| 473 | case .state(let s): |
| 474 | stopStream() |
| 475 | phase = s |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | private func index(_ id: String) -> Int? { entries.firstIndex { $0.id == id } } |
| 480 | |
| 481 | /// A message, once. The Assistant's reply takes its draft's or thinking |
| 482 | /// bubble's place; open connect cards waiting for it follow it. |
| 483 | func add(_ m: AskMessage) { |
| 484 | guard index("m:" + m.id) == nil else { return } |
| 485 | if !m.isPerson, !m.turnID.isEmpty, let at = index("d:" + m.turnID) ?? index("t:" + m.turnID) { |
| 486 | entries[at] = .message(m) |
| 487 | } else { |
| 488 | entries.append(.message(m)) |
| 489 | } |
| 490 | if !m.isPerson { reoffer() } |
| 491 | } |
| 492 | |
| 493 | /// A streamed word. The turn's thinking bubble becomes its draft; |
| 494 | /// words whose offset isn't where the draft ends are dropped, as ask.js |
| 495 | /// drops them. |
| 496 | func delta(_ d: AskDelta) { |
| 497 | if let at = index("t:" + d.turnID) { |
| 498 | entries[at] = .draft(Draft(turnID: d.turnID, text: "", bytes: 0, settled: false)) |
| 499 | } else if index("d:" + d.turnID) == nil { |
| 500 | // Above the turn's connect button, should it already show. |
| 501 | let draft = Entry.draft(Draft(turnID: d.turnID, text: "", bytes: 0, settled: false)) |
| 502 | if let offer = entries.firstIndex(where: { if case .offer(let o) = $0 { o.card.turnID == d.turnID } else { false } }) { |
| 503 | entries.insert(draft, at: offer) |
| 504 | } else { |
| 505 | entries.append(draft) |
| 506 | } |
| 507 | } |
| 508 | guard let at = index("d:" + d.turnID), case .draft(var draft) = entries[at], d.offset == Int64(draft.bytes) else { return } |
| 509 | draft.text += d.text |
| 510 | draft.bytes += d.text.utf8.count |
| 511 | entries[at] = .draft(draft) |
| 512 | } |
| 513 | |
| 514 | /// Equipo's glance: one line on the turn in flight, before its words, |
| 515 | /// in its thinking bubble; never kept. |
| 516 | func glance(_ g: AskLine) { |
| 517 | let text = g.text.trimmingCharacters(in: .whitespacesAndNewlines) |
| 518 | guard !text.isEmpty, !quiet.contains(g.turnID), turn?.id == g.turnID, |
| 519 | let at = index("t:" + g.turnID), case .thinking(var t) = entries[at], !t.glanced else { return } |
| 520 | t.line = text |
| 521 | t.glanced = true |
| 522 | entries[at] = .thinking(t) |
| 523 | } |
| 524 | |
| 525 | /// What the Assistant is doing: in its bubble unless a glance holds it, |
| 526 | /// else in the status line. |
| 527 | func activity(_ a: AskLine) { |
| 528 | guard !a.text.isEmpty, !quiet.contains(a.turnID) else { return } |
| 529 | if let at = index("t:" + a.turnID), case .thinking(var t) = entries[at] { |
| 530 | guard !t.glanced else { return } |
| 531 | t.line = a.text |
| 532 | entries[at] = .thinking(t) |
| 533 | } else if turn?.id == a.turnID { |
| 534 | status = a.text |
| 535 | } |
| 536 | } |
| 537 | |
| 538 | /// A card or a job (ask.js `addCard`, `addJob`). |
| 539 | func add(_ c: AskCard) { |
| 540 | if c.isJob { addJob(c); return } |
| 541 | if c.kind == "connect", c.connectLink != nil || index("o:" + c.id) != nil { |
| 542 | offer(c) |
| 543 | return |
| 544 | } |
| 545 | guard AskCard.drawnKinds.contains(c.kind), c.isOpen || !c.result.isEmpty else { |
| 546 | remove(card: c.id) |
| 547 | jobCards[c.id] = nil |
| 548 | return |
| 549 | } |
| 550 | if let old = card(c.id), old.revision > c.revision { return } |
| 551 | if !c.job.isEmpty { jobCards[c.id] = c } |
| 552 | if !c.job.isEmpty, let at = index("j:" + c.job), case .job(var job) = entries[at] { |
| 553 | removeLoose(c.id) |
| 554 | job.open.removeAll { $0.id == c.id } |
| 555 | job.ended.removeAll { $0.id == c.id } |
| 556 | if c.isOpen { |
| 557 | if let i = job.open.firstIndex(where: { $0.id == c.id }) { job.open[i] = c } else { job.open.append(c) } |
| 558 | } else { |
| 559 | job.ended.append(c) |
| 560 | } |
| 561 | entries[at] = .job(job) |
| 562 | return |
| 563 | } |
| 564 | if let at = index("c:" + c.id) { entries[at] = .card(c) } else { entries.append(.card(c)) } |
| 565 | } |
| 566 | |
| 567 | private func addJob(_ c: AskCard) { |
| 568 | guard c.jobState != nil else { return } |
| 569 | if let at = index("j:" + c.id), case .job(var job) = entries[at] { |
| 570 | guard job.card.revision <= c.revision else { return } |
| 571 | job.card = c |
| 572 | entries[at] = .job(job) |
| 573 | return |
| 574 | } |
| 575 | var job = Job(card: c, open: [], ended: []) |
| 576 | // Its loose cards, drawn before it was, move under it, or into its view. |
| 577 | for entry in entries { |
| 578 | guard case .card(let loose) = entry, loose.job == c.id else { continue } |
| 579 | let latest = jobCards[loose.id] ?? loose |
| 580 | if latest.isOpen { job.open.append(latest) } else { job.ended.append(latest) } |
| 581 | } |
| 582 | entries.removeAll { if case .card(let loose) = $0 { loose.job == c.id } else { false } } |
| 583 | entries.append(.job(job)) |
| 584 | } |
| 585 | |
| 586 | private func card(_ id: String) -> AskCard? { |
| 587 | for entry in entries { |
| 588 | switch entry { |
| 589 | case .card(let c) where c.id == id: return c |
| 590 | case .job(let j): |
| 591 | if let c = j.open.first(where: { $0.id == id }) ?? j.ended.first(where: { $0.id == id }) { return c } |
| 592 | default: continue |
| 593 | } |
| 594 | } |
| 595 | return nil |
| 596 | } |
| 597 | |
| 598 | private func removeLoose(_ id: String) { entries.removeAll { $0.id == "c:" + id } } |
| 599 | |
| 600 | private func remove(card id: String) { |
| 601 | removeLoose(id) |
| 602 | for (at, entry) in entries.enumerated() { |
| 603 | guard case .job(var job) = entry else { continue } |
| 604 | let before = job.open.count + job.ended.count |
| 605 | job.open.removeAll { $0.id == id } |
| 606 | job.ended.removeAll { $0.id == id } |
| 607 | if job.open.count + job.ended.count != before { entries[at] = .job(job) } |
| 608 | } |
| 609 | } |
| 610 | |
| 611 | /// An open connect card ends the Assistant's newest reply; one whose |
| 612 | /// reply is still on its way waits for it (reoffer), and if no words |
| 613 | /// come for `offerWait`, shows on its own (ask.js `wait`). Connected, |
| 614 | /// it becomes a quiet line where it is. |
| 615 | private var waitingOffers: [String: AskCard] = [:] |
| 616 | /// The newest revision seen of each connect card, drawn, waiting or |
| 617 | /// neither: an older one never replaces it (ask.js `offer`). |
| 618 | private var offerRevisions: [String: Int64] = [:] |
| 619 | /// Offers waiting on a timer, and the timers' generation: a fresh |
| 620 | /// snapshot ends every timer. |
| 621 | private var offerTimers: Set<String> = [] |
| 622 | private var offerEpoch = 0 |
| 623 | static let offerWait: Duration = .seconds(3) |
| 624 | |
| 625 | private func offer(_ c: AskCard) { |
| 626 | if let known = offerRevisions[c.id], known > c.revision { return } |
| 627 | offerRevisions[c.id] = c.revision |
| 628 | if !c.isOpen { |
| 629 | waitingOffers[c.id] = nil |
| 630 | if let at = index("o:" + c.id) { entries[at] = .offer(Offer(card: c, connected: true)) } |
| 631 | return |
| 632 | } |
| 633 | guard c.connectLink != nil else { return } |
| 634 | if onItsWay(c.turnID) { |
| 635 | if index("o:" + c.id) == nil { |
| 636 | waitingOffers[c.id] = c |
| 637 | wait(c.id) |
| 638 | } else if case .offer(var o)? = entries.first(where: { $0.id == "o:" + c.id }), let at = index("o:" + c.id) { |
| 639 | o.card = c |
| 640 | entries[at] = .offer(o) |
| 641 | } |
| 642 | return |
| 643 | } |
| 644 | waitingOffers[c.id] = nil |
| 645 | put(c) |
| 646 | } |
| 647 | |
| 648 | /// After `offerWait`: the reply's words are streaming, so wait again; |
| 649 | /// otherwise show the offer on its own. |
| 650 | private func wait(_ id: String) { |
| 651 | guard !offerTimers.contains(id) else { return } |
| 652 | offerTimers.insert(id) |
| 653 | let epoch = offerEpoch |
| 654 | schedule(Self.offerWait) { [weak self] in |
| 655 | guard let self, self.offerEpoch == epoch else { return } |
| 656 | self.offerTimers.remove(id) |
| 657 | guard let c = self.waitingOffers[id] else { return } |
| 658 | if self.index("d:" + c.turnID) != nil, self.onItsWay(c.turnID) { |
| 659 | self.wait(id) |
| 660 | } else if self.index("o:" + id) == nil { |
| 661 | self.waitingOffers[id] = nil |
| 662 | self.put(c) |
| 663 | } |
| 664 | } |
| 665 | } |
| 666 | |
| 667 | private func onItsWay(_ turnID: String) -> Bool { |
| 668 | guard !turnID.isEmpty else { return false } |
| 669 | if entries.contains(where: { if case .message(let m) = $0 { !m.isPerson && m.turnID == turnID } else { false } }) { return false } |
| 670 | return !over.contains(turnID) || index("t:" + turnID) != nil || index("d:" + turnID) != nil |
| 671 | } |
| 672 | |
| 673 | private func reoffer() { |
| 674 | for (id, c) in waitingOffers where !onItsWay(c.turnID) { |
| 675 | waitingOffers[id] = nil |
| 676 | put(c) |
| 677 | } |
| 678 | } |
| 679 | |
| 680 | /// After the newest reply, or at the end with none. |
| 681 | private func put(_ c: AskCard) { |
| 682 | entries.removeAll { $0.id == "o:" + c.id } |
| 683 | let offer = Entry.offer(Offer(card: c, connected: false)) |
| 684 | if let last = entries.lastIndex(where: { if case .message(let m) = $0 { !m.isPerson } else { false } }) { |
| 685 | entries.insert(offer, at: last + 1) |
| 686 | } else { |
| 687 | entries.append(offer) |
| 688 | } |
| 689 | } |
| 690 | |
| 691 | // MARK: Turns |
| 692 | |
| 693 | /// A turn's state (ask.js `setTurn`). A quiet turn shows nothing. One in |
| 694 | /// flight is the turn: waiting says so in the status line, else its |
| 695 | /// thinking bubble shows. One that ends settles its bubble and drafts. |
| 696 | func setTurn(_ t: AskTurn?, line: String = "") { |
| 697 | if let t, t.id.isEmpty || over.contains(t.id) { return } |
| 698 | if let t, t.ended { over.insert(t.id) } |
| 699 | if let t, t.quiet { |
| 700 | quiet.insert(t.id) |
| 701 | if t.ended { settle(t) } |
| 702 | return |
| 703 | } |
| 704 | if let t, !t.ended { |
| 705 | turn = t |
| 706 | if t.state == "waiting" { |
| 707 | drop(t.id) |
| 708 | status = line.isEmpty ? BaseText.text("ask.waiting") : line |
| 709 | } else { |
| 710 | status = "" |
| 711 | think(t.id) |
| 712 | } |
| 713 | return |
| 714 | } |
| 715 | if let t { |
| 716 | unthink(t) |
| 717 | reoffer() |
| 718 | } |
| 719 | if let t, let current = turn, t.id != current.id { return } |
| 720 | turn = nil |
| 721 | status = t?.state == "failed" ? BaseText.text("ask.failed") : "" |
| 722 | settle(t) |
| 723 | } |
| 724 | |
| 725 | private func think(_ id: String) { |
| 726 | guard index("t:" + id) == nil, index("d:" + id) == nil else { return } |
| 727 | entries.append(.thinking(Thinking(turnID: id, line: nil, glanced: false))) |
| 728 | } |
| 729 | |
| 730 | private func drop(_ id: String) { entries.removeAll { $0.id == "t:" + id } } |
| 731 | |
| 732 | /// A replied turn's bubble waits a little for its reply (it may come |
| 733 | /// just after); otherwise, or if it never comes, it goes. |
| 734 | private func unthink(_ t: AskTurn) { |
| 735 | guard index("t:" + t.id) != nil else { return } |
| 736 | if t.state == "replied", t.replyID.isEmpty || index("m:" + t.replyID) == nil { |
| 737 | schedule(.seconds(5)) { [weak self] in |
| 738 | self?.drop(t.id) |
| 739 | self?.reoffer() |
| 740 | } |
| 741 | return |
| 742 | } |
| 743 | drop(t.id) |
| 744 | } |
| 745 | |
| 746 | /// Ends turn `t`'s drafts (every draft with none): a cancelled or |
| 747 | /// failed turn's go; the rest stay as written, without the caret. |
| 748 | private func settle(_ t: AskTurn?) { |
| 749 | let gone = t.map { $0.state == "cancelled" || $0.state == "failed" } ?? false |
| 750 | entries = entries.compactMap { entry in |
| 751 | guard case .draft(var d) = entry, t == nil || d.turnID == t!.id else { return entry } |
| 752 | if gone { return nil } |
| 753 | d.settled = true |
| 754 | return .draft(d) |
| 755 | } |
| 756 | } |
| 757 | } |
| 758 | |