| 1 | import Foundation |
| 2 | import Observation |
| 3 | import RastrilloNative |
| 4 | |
| 5 | /// One signed-in team: what the screens show, kept current by the |
| 6 | /// conversation's event stream while the app is in front. Reads reconcile |
| 7 | /// by ID and revision; writes keep their idempotency key until they have a |
| 8 | /// result. |
| 9 | @MainActor @Observable |
| 10 | public final class EquipoSession { |
| 11 | public enum Status: Equatable, Sendable { case loading, ready, signedOut } |
| 12 | |
| 13 | /// Something this device is sending. It stays, with its key, until the |
| 14 | /// server has it; offline it waits, and is sent again as itself when the |
| 15 | /// team answers again or the person taps it. |
| 16 | public struct Outgoing: Identifiable, Equatable, Sendable { |
| 17 | public enum State: Equatable, Sendable { case sending, waiting, failed } |
| 18 | public let id: String |
| 19 | public let text: String |
| 20 | public let taskID: String? |
| 21 | public var attachments: [MessageAttachment] = [] |
| 22 | public var notice: String? = nil |
| 23 | public var projectName: String? = nil |
| 24 | public var state: State |
| 25 | var write: PendingWrite |
| 26 | var goneProject = false |
| 27 | } |
| 28 | |
| 29 | /// A departing session can never become current again, even if a read |
| 30 | /// or credential renewal ignores cancellation and completes later. |
| 31 | /// Local window identity, never sent or persisted as a credential. |
| 32 | public let presentationID = UUID() |
| 33 | public let lifetime: SignInLifetime |
| 34 | let settings = SettingsPresentation() |
| 35 | let previews = PreviewPresentation() |
| 36 | public let markdown = MarkdownTranscript() |
| 37 | private var questionDrafts: [String: QuestionAnswerDraft] = [:] |
| 38 | /// The zone this session told Equipo (paused work): sent once, and again |
| 39 | /// when the device's changes. |
| 40 | private var zoneSent: String? |
| 41 | public func questionDraft(for card: ThinCard) -> QuestionAnswerDraft { |
| 42 | if let draft = questionDrafts[card.id] { return draft } |
| 43 | let draft = QuestionAnswerDraft(card: card); questionDrafts[card.id] = draft |
| 44 | return draft |
| 45 | } |
| 46 | var isInvalidated: Bool { !lifetime.isActive } |
| 47 | public private(set) var status: Status = .loading |
| 48 | public private(set) var account: DeviceAccount |
| 49 | public private(set) var me: ThinMe? |
| 50 | public private(set) var drafts: [String: StreamedReply] = [:] |
| 51 | public private(set) var messages: [ThinMessage] = [] |
| 52 | public private(set) var turns: [ThinTurn] = [] |
| 53 | public private(set) var cards: [ThinCard] = [] |
| 54 | public private(set) var tasks: [ThinTask] = [] |
| 55 | /// nil until loaded: an unknown count is not zero. |
| 56 | public private(set) var needsYou: [ThinTask]? |
| 57 | /// The server inbox count, including set-aside rows. Unknown stays unknown. |
| 58 | public var needsYouCount: Int? { needsYou?.count } |
| 59 | public let attachments: AttachmentDraft |
| 60 | public let projectCatalog: ProjectCatalog |
| 61 | public var projects: [String: ThinProject] { projectCatalog.projects } |
| 62 | public private(set) var answerNotices: [String: String] = [:] |
| 63 | /// The latest activity of each live turn, from the event stream. |
| 64 | public private(set) var activity: [String: ThinActivity] = [:] |
| 65 | public private(set) var outgoing: [Outgoing] = [] |
| 66 | /// Turns this person asked to stop that are still running. |
| 67 | public private(set) var stopping: Set<String> = [] |
| 68 | public private(set) var refreshFailed = false |
| 69 | var needsReadGeneration: UInt64 = 0 |
| 70 | public private(set) var cursor: Int64 = 0 |
| 71 | |
| 72 | public private(set) var client: EquipoClient |
| 73 | private let accounts: DeviceAccounts |
| 74 | private var revocationTransport: EquipoTransport |
| 75 | private let runner = CoalescedRunner() |
| 76 | private var live: Task<Void, Never>? |
| 77 | /// Reads asked for by the stream: one runs at a time, and a burst |
| 78 | /// during it is answered by one more read after it. |
| 79 | private var pendingRead: Task<Void, Never>? |
| 80 | private var readAgain = false |
| 81 | /// Answers not yet known to have landed, by card, revision and choice: |
| 82 | /// another tap sends the same answer again, as itself. |
| 83 | private var unsettledAnswers: [String: PendingWrite] = [:] |
| 84 | /// Set aside and Undo not yet known to have landed, as answers are. |
| 85 | private var unsettledVisibility: [String: PendingWrite] = [:] |
| 86 | private let sleep: @Sendable (Duration) async throws -> Void |
| 87 | |
| 88 | public init(account: DeviceAccount, accounts: DeviceAccounts, transport: EquipoTransport? = nil, lifetime: SignInLifetime? = nil, |
| 89 | sleep: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }) { |
| 90 | self.account = account |
| 91 | self.accounts = accounts |
| 92 | self.sleep = sleep |
| 93 | let lifetime = lifetime ?? accounts.lifetimes.current |
| 94 | self.lifetime = lifetime |
| 95 | let transport = transport ?? URLSessionTransport(origin: account.origin) |
| 96 | self.revocationTransport = transport |
| 97 | let client = EquipoClient(transport: LifetimeTransport(inner: transport, lifetime: lifetime), token: account.credential?.token) |
| 98 | self.client = client |
| 99 | attachments = AttachmentDraft(client: client) |
| 100 | projectCatalog = ProjectCatalog(client: client, lifetime: lifetime) |
| 101 | if !account.isUsable() { status = .signedOut } |
| 102 | try? accounts.commit(.selectForSharing(account), lifetime: lifetime) |
| 103 | try? accounts.commit(.selectForNotifications(account), lifetime: lifetime) |
| 104 | } |
| 105 | |
| 106 | public var origin: URL { account.origin } |
| 107 | public var teamName: String { me?.teamName ?? account.teamName ?? origin.host ?? "" } |
| 108 | public func task(_ id: String) -> ThinTask? { tasks.first { $0.id == id } ?? needsYou?.first { $0.id == id } } |
| 109 | /// Whether the task waits on this person. The team's task list marks a |
| 110 | /// task that waits on its creator; Needs you is this person's own. |
| 111 | public func waitsOnYou(_ task: ThinTask) -> Bool { needsYou?.contains { $0.id == task.id } ?? false } |
| 112 | /// The person asked for the task (only they are offered Run now). |
| 113 | public func isMine(_ task: ThinTask) -> Bool { me.map { task.creator == $0.address } ?? false } |
| 114 | |
| 115 | /// Run now on a paused task (POST /api/v1/tasks/{id}/run-now): the held |
| 116 | /// step, at the revision its hold shows, on what the instance predicted. |
| 117 | /// The tap carries what the button showed; if Run now would now do |
| 118 | /// anything else it is refused (409 offer_changed). Either way the task |
| 119 | /// is read again, so the screen shows the offer as it is. |
| 120 | @discardableResult public func runNow(task id: String, _ run: TaskPause.RunNow) async -> String? { |
| 121 | guard lifetime.isActive else { return nil } |
| 122 | let message = await StoppedWorkActions.runNow(client: client, task: id, run: run) |
| 123 | await refresh() |
| 124 | return message |
| 125 | } |
| 126 | |
| 127 | /// Tells Equipo this device's time zone, so the times it words for the |
| 128 | /// person are theirs (paused work, decision 4). Once a session, and |
| 129 | /// again when the device's zone changes. |
| 130 | private func sendZone() async { |
| 131 | let zone = TimeZone.current.identifier |
| 132 | guard zone != zoneSent, lifetime.isActive else { return } |
| 133 | if (try? await client.setTimeZone(zone)) != nil { zoneSent = zone } |
| 134 | } |
| 135 | public func project(_ id: String) -> ThinProject? { projects[id] } |
| 136 | /// The coordinator's turn in flight, if any. |
| 137 | public var liveTurn: ThinTurn? { turns.filter(\.isLive).max { $0.createdAt < $1.createdAt } } |
| 138 | |
| 139 | // MARK: Reading |
| 140 | |
| 141 | /// Everything the screens show, once at a time: a burst of callers shares one pass. |
| 142 | public func refresh(retryNeeds: Bool = false) async { |
| 143 | guard status != .signedOut else { return } |
| 144 | await runner.run { [weak self] in await self?.refreshPass() } |
| 145 | if retryNeeds, !isInvalidated { needsReadGeneration &+= 1 } |
| 146 | } |
| 147 | |
| 148 | private func refreshPass() async { |
| 149 | guard !isInvalidated else { return } |
| 150 | let client = self.client |
| 151 | let projectGeneration = projectCatalog.snapshotGeneration |
| 152 | do { |
| 153 | async let snapshotRead = client.snapshot() |
| 154 | async let taskRead = client.tasks() |
| 155 | async let needsRead = client.needsYou() |
| 156 | let (snapshot, taskList, needsList) = try await (snapshotRead, taskRead, needsRead) |
| 157 | guard !isInvalidated else { return } |
| 158 | apply(snapshot, projectGeneration: projectGeneration) |
| 159 | tasks = taskList.items ?? [] |
| 160 | previews.observe(tasks) |
| 161 | needsYou = needsList.items ?? [] |
| 162 | status = .ready |
| 163 | refreshFailed = false |
| 164 | await sendZone() |
| 165 | // The team answers again: what was waiting goes now, as itself. |
| 166 | for item in outgoing where item.state == .waiting { |
| 167 | let id = item.id |
| 168 | outgoing[outgoing.firstIndex { $0.id == id }!].state = .sending |
| 169 | Task { await self.deliver(id) } |
| 170 | } |
| 171 | } catch let error as EquipoAPIError where error.endsSession { |
| 172 | guard !isInvalidated else { return } |
| 173 | endSession() |
| 174 | } catch is CancellationError { |
| 175 | } catch { |
| 176 | guard !isInvalidated else { return } |
| 177 | refreshFailed = true |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | func applyCard(_ card: ThinCard) { |
| 182 | guard !isInvalidated else { return } |
| 183 | cards = Self.merge(cards, [card]) |
| 184 | } |
| 185 | |
| 186 | func apply(_ snapshot: Snapshot, projectGeneration: Int? = nil) { |
| 187 | guard !isInvalidated else { return } |
| 188 | me = snapshot.me |
| 189 | messages = Self.merge(messages, snapshot.messages ?? []) |
| 190 | turns = Self.merge(turns, snapshot.turns ?? []) |
| 191 | cards = Self.merge(cards, snapshot.cards ?? []) |
| 192 | projectCatalog.applySnapshot(snapshot.projects ?? [], cursor: snapshot.cursor, generation: projectGeneration) |
| 193 | cursor = max(cursor, snapshot.cursor) |
| 194 | let liveIDs = Set(turns.filter(\.isLive).map(\.id)) |
| 195 | activity = activity.filter { liveIDs.contains($0.key) } |
| 196 | stopping.formIntersection(liveIDs) |
| 197 | let replied = Set(messages.filter { isFinalReply($0) }.map(\.turnId)) |
| 198 | drafts = drafts.filter { id, draft in |
| 199 | guard !replied.contains(id) else { return false } |
| 200 | // A read already in flight can predate the first delta. Keep it |
| 201 | // until a snapshot knows the turn, rather than losing byte zero. |
| 202 | guard let turn = turns.first(where: { $0.id == id }) else { return true } |
| 203 | return turn.isLive && (turn.attempt ?? 0) <= draft.attempt |
| 204 | } |
| 205 | markdown.retainMessages(Set(Feed.build(self).filter { $0.reply != nil }.map(\.id)), origin: origin) |
| 206 | if account.teamName != snapshot.me.teamName || account.address != snapshot.me.address { |
| 207 | account.teamName = snapshot.me.teamName; account.address = snapshot.me.address |
| 208 | try? accounts.commit(.save(account), lifetime: lifetime) |
| 209 | try? accounts.commit(.selectForSharing(account), lifetime: lifetime) |
| 210 | try? accounts.commit(.selectForNotifications(account), lifetime: lifetime) |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | private func isFinalReply(_ message: ThinMessage) -> Bool { |
| 215 | guard !message.isOwn else { return false } |
| 216 | guard let replyID = turns.first(where: { $0.id == message.turnId })?.replyId else { return true } |
| 217 | return replyID == message.id |
| 218 | } |
| 219 | |
| 220 | /// Reconciles by ID; the newer revision wins. |
| 221 | static func merge<T: Identifiable & Sendable>(_ old: [T], _ new: [T]) -> [T] where T.ID == String, T: Revisioned { |
| 222 | var byID = Dictionary(old.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) |
| 223 | for item in new where (byID[item.id]?.revision ?? -1) <= item.revision { byID[item.id] = item } |
| 224 | return byID.values.sorted { ($0.sortDate, $0.id) < ($1.sortDate, $1.id) } |
| 225 | } |
| 226 | |
| 227 | // MARK: Following the conversation |
| 228 | |
| 229 | /// Follows the event stream while the app is in front. An activity |
| 230 | /// updates the thinking line; anything else is read again through the |
| 231 | /// snapshot. A dropped stream reconnects with backoff. |
| 232 | public func startLive() { |
| 233 | guard !isInvalidated, live == nil else { return } |
| 234 | live = Task { [weak self] in |
| 235 | var backoff = Backoff() |
| 236 | while !Task.isCancelled { |
| 237 | guard let self, self.status != .signedOut else { return } |
| 238 | if self.status == .loading { await self.refresh() } |
| 239 | guard self.lifetime.isActive else { return } |
| 240 | do { |
| 241 | let lines = try await self.client.events(after: self.cursor) |
| 242 | backoff = Backoff() |
| 243 | for try await line in lines { |
| 244 | if Task.isCancelled { return } |
| 245 | await self.handle(line) |
| 246 | } |
| 247 | } catch let error as EquipoAPIError { |
| 248 | if error.endsSession { self.endSession(); return } |
| 249 | if error.code == "cursor_expired" { self.cursor = 0; await self.refresh() } |
| 250 | } catch {} |
| 251 | if Task.isCancelled { return } |
| 252 | try? await self.sleep(.seconds(backoff.next())) |
| 253 | await self.refresh() |
| 254 | } |
| 255 | } |
| 256 | } |
| 257 | public func stopLive() { live?.cancel(); live = nil } |
| 258 | |
| 259 | /// One line of the stream. A turn's activity moves the thinking line; |
| 260 | /// a change to something the screens show reads them again; the rest |
| 261 | /// (runners, connections, pings) is not this app's. |
| 262 | func handle(_ line: String) async { |
| 263 | guard lifetime.isActive, line.hasPrefix("data:") else { return } |
| 264 | let json = Data(line.dropFirst(5).trimmingCharacters(in: .whitespaces).utf8) |
| 265 | guard let event = try? EquipoJSON.decoder.decode(EventEnvelope.self, from: json) else { return } |
| 266 | if let c = event.cursor { cursor = max(cursor, c) } |
| 267 | if event.resource == "project", let project = event.project, let sequence = event.cursor { |
| 268 | projectCatalog.applyEvent(project, cursor: sequence) |
| 269 | Task { await projectCatalog.refresh() } |
| 270 | return |
| 271 | } |
| 272 | if event.type == "activity" { |
| 273 | if event.resource == "turn", let data = event.activity { activity[data.turnId] = data } |
| 274 | return |
| 275 | } |
| 276 | // Reply text as it streams: the finished message arrives as its own event. |
| 277 | if event.type == "delta" { |
| 278 | guard event.resource == "turn", let delta = event.delta, let attempt = event.attempt, |
| 279 | attempt > 0, delta.offset >= 0, !delta.text.isEmpty, |
| 280 | !messages.contains(where: { isFinalReply($0) && $0.turnId == delta.turnId }) else { return } |
| 281 | if let turn = turns.first(where: { $0.id == delta.turnId }), |
| 282 | !turn.isLive || attempt < (turn.attempt ?? 0) { return } |
| 283 | let old = drafts[delta.turnId] |
| 284 | guard attempt >= (old?.attempt ?? 0) else { return } |
| 285 | var draft = old?.attempt == attempt ? old! : StreamedReply(attempt: attempt, text: "") |
| 286 | guard delta.offset == draft.text.utf8.count else { return } |
| 287 | draft.text += delta.text |
| 288 | drafts[delta.turnId] = draft |
| 289 | if !turns.contains(where: { $0.id == delta.turnId }) { requestRefresh() } |
| 290 | return |
| 291 | } |
| 292 | guard Self.shown.contains(event.resource) else { return } |
| 293 | requestRefresh() |
| 294 | } |
| 295 | |
| 296 | /// Reads again soon, without holding up the stream. |
| 297 | func requestRefresh() { |
| 298 | guard lifetime.isActive else { return } |
| 299 | if pendingRead != nil { readAgain = true; return } |
| 300 | pendingRead = Task { [weak self] in |
| 301 | guard let self else { return } |
| 302 | repeat { |
| 303 | self.readAgain = false |
| 304 | await self.refresh() |
| 305 | } while self.readAgain && !Task.isCancelled |
| 306 | self.pendingRead = nil |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | /// Waits for reads and sends already under way (tests, and before a screen settles). |
| 311 | func settle() async { |
| 312 | for _ in 0..<50 { |
| 313 | await pendingRead?.value |
| 314 | await Task.yield() |
| 315 | if pendingRead == nil && !outgoing.contains(where: { $0.state == .sending }) { return } |
| 316 | try? await Task.sleep(for: .milliseconds(2)) |
| 317 | } |
| 318 | } |
| 319 | static let shown: Set<String> = ["message", "turn", "card", "task", "step", "project", "member"] |
| 320 | |
| 321 | struct EventEnvelope: Decodable { |
| 322 | var cursor: Int64? |
| 323 | var type: String |
| 324 | var resource: String |
| 325 | var activity: ThinActivity? |
| 326 | var project: ThinProject? |
| 327 | var attempt: Int64? |
| 328 | var delta: ReplyDelta? |
| 329 | struct ReplyDelta: Decodable { var turnId: String; var offset: Int; var text: String } |
| 330 | enum Keys: String, CodingKey { case cursor, type, resource, data, attempt } |
| 331 | init(from decoder: Decoder) throws { |
| 332 | let c = try decoder.container(keyedBy: Keys.self) |
| 333 | cursor = try c.decodeIfPresent(Int64.self, forKey: .cursor) |
| 334 | type = try c.decode(String.self, forKey: .type) |
| 335 | resource = try c.decodeIfPresent(String.self, forKey: .resource) ?? "" |
| 336 | attempt = try c.decodeIfPresent(Int64.self, forKey: .attempt) |
| 337 | project = resource == "project" ? try? c.decode(ThinProject.self, forKey: .data) : nil |
| 338 | delta = type == "delta" && resource == "turn" ? try? c.decode(ReplyDelta.self, forKey: .data) : nil |
| 339 | activity = type == "activity" && resource == "turn" ? try? c.decode(ThinActivity.self, forKey: .data) : nil |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | /// Reconnects quickly at first, then every half minute at most. |
| 344 | struct Backoff { |
| 345 | private var attempt = 0 |
| 346 | mutating func next() -> Int { |
| 347 | defer { attempt += 1 } |
| 348 | return min(30, [2, 4, 8, 15][min(attempt, 3)] * (attempt > 3 ? 2 : 1)) |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | // MARK: Sending |
| 353 | |
| 354 | public func sendFromComposer(_ text: String) -> Task<Void, Never> { |
| 355 | guard lifetime.isActive, attachments.canSend(text: text) else { return Task {} } |
| 356 | let files = attachments.readyAttachments |
| 357 | attachments.clear() |
| 358 | let projectID = projectCatalog.takeSelection() |
| 359 | return Task { await send(text, projectID: projectID, attachments: files) } |
| 360 | } |
| 361 | |
| 362 | public func send(_ text: String, inThreadOf taskID: String? = nil, projectID: String? = nil, attachments: [MessageAttachment] = []) async { |
| 363 | let text = text.trimmingCharacters(in: .whitespacesAndNewlines) |
| 364 | guard lifetime.isActive, !text.isEmpty || !attachments.isEmpty, taskID == nil || attachments.isEmpty, let write = try? EquipoClient.message(text, projectID: taskID == nil ? projectID : nil, attachments: attachments.map(\.id)) else { return } |
| 365 | outgoing.append(Outgoing(id: write.key, text: text, taskID: taskID, attachments: attachments, projectName: taskID == nil ? projectID.flatMap { projects[$0]?.displayName } : nil, state: .sending, write: write)) |
| 366 | await deliver(write.key) |
| 367 | } |
| 368 | |
| 369 | /// Sends one outgoing message again, as itself. |
| 370 | public func retry(_ id: String) async { |
| 371 | if let i = outgoing.firstIndex(where: { $0.id == id }), outgoing[i].goneProject { |
| 372 | // A definitive 404 rejected this send. A changed body is a new operation. |
| 373 | guard let write = try? EquipoClient.message(outgoing[i].text, attachments: outgoing[i].attachments.map(\.id)) else { return } |
| 374 | outgoing[i].write = write; outgoing[i].projectName = nil; outgoing[i].goneProject = false |
| 375 | } |
| 376 | await deliver(id) |
| 377 | } |
| 378 | |
| 379 | private func deliver(_ id: String) async { |
| 380 | guard lifetime.isActive, let index = outgoing.firstIndex(where: { $0.id == id }) else { return } |
| 381 | outgoing[index].state = .sending |
| 382 | let item = outgoing[index] |
| 383 | do { |
| 384 | if let taskID = item.taskID { |
| 385 | let entry = try await client.postThread(task: taskID, item.write) |
| 386 | guard lifetime.isActive else { return } |
| 387 | if let i = tasks.firstIndex(where: { $0.id == taskID }) { |
| 388 | var thread = tasks[i].thread ?? [] |
| 389 | if !thread.contains(where: { $0.id == entry.id }) { thread.append(entry) } |
| 390 | tasks[i].thread = thread |
| 391 | } |
| 392 | } else { |
| 393 | let sent = try await client.send(item.write) |
| 394 | guard lifetime.isActive else { return } |
| 395 | messages = Self.merge(messages, [sent.message]) |
| 396 | turns = Self.merge(turns, [sent.turn]) |
| 397 | } |
| 398 | outgoing.removeAll { $0.id == id } |
| 399 | await refresh() |
| 400 | } catch let error as EquipoAPIError { |
| 401 | guard lifetime.isActive else { return } |
| 402 | if error.endsSession { endSession(); return } |
| 403 | if let i = outgoing.firstIndex(where: { $0.id == id }) { |
| 404 | outgoing[i].state = error == .offline ? .waiting : .failed |
| 405 | outgoing[i].notice = ProjectNotice.knownText(error) |
| 406 | // This native conversation body references only one resource: its selected project. |
| 407 | // A proxy 404, another API code, or a missing task is not evidence about that project. |
| 408 | if case .server(404, let body) = error, body.code == "not_found", body.copyKey == "api.not_found", |
| 409 | item.taskID == nil, |
| 410 | let fields = try? JSONSerialization.jsonObject(with: item.write.body) as? [String: Any], |
| 411 | let project = fields["project_id"] as? String, !project.isEmpty { |
| 412 | outgoing[i].goneProject = true |
| 413 | outgoing[i].projectName = nil |
| 414 | outgoing[i].notice = EquipoStrings.text("projects.selection_lost") |
| 415 | projectCatalog.releaseSelection(project) |
| 416 | } |
| 417 | } |
| 418 | } catch { |
| 419 | guard lifetime.isActive else { return } |
| 420 | // Cancelled on the way: it may yet be sent, as itself. |
| 421 | if let i = outgoing.firstIndex(where: { $0.id == id }) { outgoing[i].state = error is CancellationError ? .waiting : .failed } |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | // MARK: Answering |
| 426 | |
| 427 | public enum AnswerOutcome: Equatable, Sendable { |
| 428 | case answered |
| 429 | /// The card changed or was already answered: show it as it is now; never resend. |
| 430 | case changed |
| 431 | case offline |
| 432 | case failed |
| 433 | } |
| 434 | |
| 435 | /// Answers a card as the person saw it, bound to that revision. A lost |
| 436 | /// answer is retried as itself; a stale one is never sent again. |
| 437 | public func answer(_ card: ThinCard, choice: String, note: String? = nil, rememberName: String? = nil) async -> AnswerOutcome { |
| 438 | guard lifetime.isActive else { return .failed } |
| 439 | guard card.isOpen else { return .changed } |
| 440 | let slot = "\(card.id)#\(card.revision)#\(choice)#\(note ?? "")#\(rememberName ?? "")" |
| 441 | answerNotices[card.id] = nil |
| 442 | guard let write = unsettledAnswers[slot] ?? (try? EquipoClient.answer(choice, note: note, rememberName: rememberName, to: card)) else { return .failed } |
| 443 | unsettledAnswers[slot] = write |
| 444 | var attempts = 0 |
| 445 | while true { |
| 446 | guard lifetime.isActive else { return .failed } |
| 447 | do { |
| 448 | let answered = try await client.answer(card: card.id, write) |
| 449 | guard lifetime.isActive else { return .failed } |
| 450 | unsettledAnswers[slot] = nil |
| 451 | cards = Self.merge(cards, [answered.card]) |
| 452 | await refresh() |
| 453 | return .answered |
| 454 | } catch let error as EquipoAPIError { |
| 455 | guard lifetime.isActive else { return .failed } |
| 456 | if error == .offline, attempts < 2 { attempts += 1; try? await sleep(.seconds(2)); continue } |
| 457 | // Offline: it may have landed; keep it to send again as itself. |
| 458 | if error != .offline { unsettledAnswers[slot] = nil } |
| 459 | if error.endsSession { endSession(); return .failed } |
| 460 | if case .card(_, let code, let current) = error { |
| 461 | cards = Self.merge(cards, [current]) |
| 462 | // Build with several options needs the person's note on |
| 463 | // which one: the card is still open, so say so (the |
| 464 | // instance's api.direction_note), never that it changed. |
| 465 | if code == "direction_note" { answerNotices[card.id] = EquipoStrings.text("api.direction_note"); return .failed } |
| 466 | return .changed |
| 467 | } |
| 468 | if error.isStale { await refresh(); return .changed } |
| 469 | answerNotices[card.id] = ProjectNotice.text(error) |
| 470 | return error == .offline ? .offline : .failed |
| 471 | } catch { unsettledAnswers[slot] = nil; return .failed } |
| 472 | } |
| 473 | } |
| 474 | |
| 475 | /// Sets a card aside, or brings it back (Undo), bound to the revision |
| 476 | /// the person saw. It never answers, cancels or starts anything: the |
| 477 | /// card stays in Needs you. `.answered` means the server took it; a |
| 478 | /// card that changed is shown as it is now and never sent again. |
| 479 | public func setAside(_ card: ThinCard, _ aside: Bool) async -> AnswerOutcome { |
| 480 | guard lifetime.isActive else { return .failed } |
| 481 | guard Feed.canSetAside(card) else { return .changed } |
| 482 | let slot = "\(card.id)#\(card.revision)#\(aside)" |
| 483 | guard let write = unsettledVisibility[slot] ?? (try? EquipoClient.visibility(aside: aside, of: card)) else { return .failed } |
| 484 | unsettledVisibility[slot] = write |
| 485 | var attempts = 0 |
| 486 | while true { |
| 487 | guard lifetime.isActive else { return .failed } |
| 488 | do { |
| 489 | let updated = try await client.setVisibility(card: card.id, write) |
| 490 | guard lifetime.isActive else { return .failed } |
| 491 | unsettledVisibility[slot] = nil |
| 492 | cards = Self.merge(cards, [updated]) |
| 493 | return .answered |
| 494 | } catch let error as EquipoAPIError { |
| 495 | guard lifetime.isActive else { return .failed } |
| 496 | if error == .offline, attempts < 2 { attempts += 1; try? await sleep(.seconds(2)); continue } |
| 497 | // Offline: it may have landed; keep it to send again as itself. |
| 498 | if error != .offline { unsettledVisibility[slot] = nil } |
| 499 | if error.endsSession { endSession(); return .failed } |
| 500 | if case .card(_, _, let current) = error { cards = Self.merge(cards, [current]); return .changed } |
| 501 | if error.isStale { await refresh(); return .changed } |
| 502 | answerNotices[card.id] = ProjectNotice.text(error) |
| 503 | return error == .offline ? .offline : .failed |
| 504 | } catch { unsettledVisibility[slot] = nil; return .failed } |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | /// Stops the coordinator's turn in flight: that turn only. |
| 509 | /// Says whether the server took it; on false, Stop is offered again. |
| 510 | @discardableResult |
| 511 | public func stop(_ turn: ThinTurn) async -> Bool { |
| 512 | guard lifetime.isActive else { return false } |
| 513 | guard !stopping.contains(turn.id) else { return true } |
| 514 | stopping.insert(turn.id) |
| 515 | do { try await client.cancelTurn(turn.id) } catch { stopping.remove(turn.id); return false } |
| 516 | guard lifetime.isActive else { return false } |
| 517 | await refresh() |
| 518 | return true |
| 519 | } |
| 520 | |
| 521 | /// A renewed Oficina ID credential keeps the conversation and pending |
| 522 | /// writes mounted. Every new request uses the replacement bearer. |
| 523 | func renew(_ account: DeviceAccount, transport: EquipoTransport) { |
| 524 | guard !isInvalidated else { return } |
| 525 | self.account = account |
| 526 | try? accounts.commit(.selectForSharing(account), lifetime: lifetime) |
| 527 | try? accounts.commit(.selectForNotifications(account), lifetime: lifetime) |
| 528 | revocationTransport = transport |
| 529 | client = EquipoClient(transport: LifetimeTransport(inner: transport, lifetime: lifetime), token: account.credential?.token) |
| 530 | projectCatalog.client = client |
| 531 | attachments.client = client |
| 532 | if status == .signedOut { status = .loading } |
| 533 | } |
| 534 | |
| 535 | // MARK: Signing out |
| 536 | |
| 537 | private func endSession() { |
| 538 | try? accounts.commit(.remove(account), lifetime: lifetime) |
| 539 | invalidate() |
| 540 | } |
| 541 | |
| 542 | /// Called before the app releases this session. Cancellation alone does |
| 543 | /// not prevent a completed network response from reaching persistence. |
| 544 | func invalidate() { |
| 545 | try? accounts.commit(.clearShareSelection(account), lifetime: lifetime) |
| 546 | try? accounts.commit(.clearNotificationSelection(account), lifetime: lifetime) |
| 547 | lifetime.end() |
| 548 | previews.invalidate() |
| 549 | attachments.clear() |
| 550 | markdown.removeAll() |
| 551 | status = .signedOut |
| 552 | drafts = [:] |
| 553 | stopLive() |
| 554 | pendingRead?.cancel(); pendingRead = nil |
| 555 | } |
| 556 | |
| 557 | /// Forgets this device immediately, then revokes it best effort. No |
| 558 | /// late cleanup may remove a newly signed-in account at the same origin. |
| 559 | public func signOut() async { |
| 560 | try? accounts.commit(.remove(account), lifetime: lifetime) |
| 561 | invalidate() |
| 562 | await DeviceRevocation.revoke(account, transport: revocationTransport) |
| 563 | } |
| 564 | } |
| 565 | |
| 566 | /// What `merge` needs to reconcile a resource. |
| 567 | protocol Revisioned { |
| 568 | var revision: Int64 { get } |
| 569 | var sortDate: Date { get } |
| 570 | } |
| 571 | extension ThinMessage: Revisioned { var sortDate: Date { createdAt } } |
| 572 | extension ThinTurn: Revisioned { var sortDate: Date { createdAt } } |
| 573 | extension ThinCard: Revisioned { var sortDate: Date { createdAt } } |
| 574 | |