import Foundation import Observation import RastrilloNative /// One signed-in team: what the screens show, kept current by the /// conversation's event stream while the app is in front. Reads reconcile /// by ID and revision; writes keep their idempotency key until they have a /// result. @MainActor @Observable public final class EquipoSession { public enum Status: Equatable, Sendable { case loading, ready, signedOut } /// Something this device is sending. It stays, with its key, until the /// server has it; offline it waits, and is sent again as itself when the /// team answers again or the person taps it. public struct Outgoing: Identifiable, Equatable, Sendable { public enum State: Equatable, Sendable { case sending, waiting, failed } public let id: String public let text: String public let taskID: String? public var attachments: [MessageAttachment] = [] public var notice: String? = nil public var projectName: String? = nil public var state: State var write: PendingWrite var goneProject = false } /// A departing session can never become current again, even if a read /// or credential renewal ignores cancellation and completes later. /// Local window identity, never sent or persisted as a credential. public let presentationID = UUID() public let lifetime: SignInLifetime let settings = SettingsPresentation() let previews = PreviewPresentation() public let markdown = MarkdownTranscript() private var questionDrafts: [String: QuestionAnswerDraft] = [:] /// The zone this session told Equipo (paused work): sent once, and again /// when the device's changes. private var zoneSent: String? public func questionDraft(for card: ThinCard) -> QuestionAnswerDraft { if let draft = questionDrafts[card.id] { return draft } let draft = QuestionAnswerDraft(card: card); questionDrafts[card.id] = draft return draft } var isInvalidated: Bool { !lifetime.isActive } public private(set) var status: Status = .loading public private(set) var account: DeviceAccount public private(set) var me: ThinMe? public private(set) var drafts: [String: StreamedReply] = [:] public private(set) var messages: [ThinMessage] = [] public private(set) var turns: [ThinTurn] = [] public private(set) var cards: [ThinCard] = [] public private(set) var tasks: [ThinTask] = [] /// nil until loaded: an unknown count is not zero. public private(set) var needsYou: [ThinTask]? /// The server inbox count, including set-aside rows. Unknown stays unknown. public var needsYouCount: Int? { needsYou?.count } public let attachments: AttachmentDraft public let projectCatalog: ProjectCatalog public var projects: [String: ThinProject] { projectCatalog.projects } public private(set) var answerNotices: [String: String] = [:] /// The latest activity of each live turn, from the event stream. public private(set) var activity: [String: ThinActivity] = [:] public private(set) var outgoing: [Outgoing] = [] /// Turns this person asked to stop that are still running. public private(set) var stopping: Set = [] public private(set) var refreshFailed = false var needsReadGeneration: UInt64 = 0 public private(set) var cursor: Int64 = 0 public private(set) var client: EquipoClient private let accounts: DeviceAccounts private var revocationTransport: EquipoTransport private let runner = CoalescedRunner() private var live: Task? /// Reads asked for by the stream: one runs at a time, and a burst /// during it is answered by one more read after it. private var pendingRead: Task? private var readAgain = false /// Answers not yet known to have landed, by card, revision and choice: /// another tap sends the same answer again, as itself. private var unsettledAnswers: [String: PendingWrite] = [:] /// Set aside and Undo not yet known to have landed, as answers are. private var unsettledVisibility: [String: PendingWrite] = [:] private let sleep: @Sendable (Duration) async throws -> Void public init(account: DeviceAccount, accounts: DeviceAccounts, transport: EquipoTransport? = nil, lifetime: SignInLifetime? = nil, sleep: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }) { self.account = account self.accounts = accounts self.sleep = sleep let lifetime = lifetime ?? accounts.lifetimes.current self.lifetime = lifetime let transport = transport ?? URLSessionTransport(origin: account.origin) self.revocationTransport = transport let client = EquipoClient(transport: LifetimeTransport(inner: transport, lifetime: lifetime), token: account.credential?.token) self.client = client attachments = AttachmentDraft(client: client) projectCatalog = ProjectCatalog(client: client, lifetime: lifetime) if !account.isUsable() { status = .signedOut } try? accounts.commit(.selectForSharing(account), lifetime: lifetime) try? accounts.commit(.selectForNotifications(account), lifetime: lifetime) } public var origin: URL { account.origin } public var teamName: String { me?.teamName ?? account.teamName ?? origin.host ?? "" } public func task(_ id: String) -> ThinTask? { tasks.first { $0.id == id } ?? needsYou?.first { $0.id == id } } /// Whether the task waits on this person. The team's task list marks a /// task that waits on its creator; Needs you is this person's own. public func waitsOnYou(_ task: ThinTask) -> Bool { needsYou?.contains { $0.id == task.id } ?? false } /// The person asked for the task (only they are offered Run now). public func isMine(_ task: ThinTask) -> Bool { me.map { task.creator == $0.address } ?? false } /// Run now on a paused task (POST /api/v1/tasks/{id}/run-now): the held /// step, at the revision its hold shows, on what the instance predicted. /// The tap carries what the button showed; if Run now would now do /// anything else it is refused (409 offer_changed). Either way the task /// is read again, so the screen shows the offer as it is. @discardableResult public func runNow(task id: String, _ run: TaskPause.RunNow) async -> String? { guard lifetime.isActive else { return nil } let message = await StoppedWorkActions.runNow(client: client, task: id, run: run) await refresh() return message } /// Tells Equipo this device's time zone, so the times it words for the /// person are theirs (paused work, decision 4). Once a session, and /// again when the device's zone changes. private func sendZone() async { let zone = TimeZone.current.identifier guard zone != zoneSent, lifetime.isActive else { return } if (try? await client.setTimeZone(zone)) != nil { zoneSent = zone } } public func project(_ id: String) -> ThinProject? { projects[id] } /// The coordinator's turn in flight, if any. public var liveTurn: ThinTurn? { turns.filter(\.isLive).max { $0.createdAt < $1.createdAt } } // MARK: Reading /// Everything the screens show, once at a time: a burst of callers shares one pass. public func refresh(retryNeeds: Bool = false) async { guard status != .signedOut else { return } await runner.run { [weak self] in await self?.refreshPass() } if retryNeeds, !isInvalidated { needsReadGeneration &+= 1 } } private func refreshPass() async { guard !isInvalidated else { return } let client = self.client let projectGeneration = projectCatalog.snapshotGeneration do { async let snapshotRead = client.snapshot() async let taskRead = client.tasks() async let needsRead = client.needsYou() let (snapshot, taskList, needsList) = try await (snapshotRead, taskRead, needsRead) guard !isInvalidated else { return } apply(snapshot, projectGeneration: projectGeneration) tasks = taskList.items ?? [] previews.observe(tasks) needsYou = needsList.items ?? [] status = .ready refreshFailed = false await sendZone() // The team answers again: what was waiting goes now, as itself. for item in outgoing where item.state == .waiting { let id = item.id outgoing[outgoing.firstIndex { $0.id == id }!].state = .sending Task { await self.deliver(id) } } } catch let error as EquipoAPIError where error.endsSession { guard !isInvalidated else { return } endSession() } catch is CancellationError { } catch { guard !isInvalidated else { return } refreshFailed = true } } func applyCard(_ card: ThinCard) { guard !isInvalidated else { return } cards = Self.merge(cards, [card]) } func apply(_ snapshot: Snapshot, projectGeneration: Int? = nil) { guard !isInvalidated else { return } me = snapshot.me messages = Self.merge(messages, snapshot.messages ?? []) turns = Self.merge(turns, snapshot.turns ?? []) cards = Self.merge(cards, snapshot.cards ?? []) projectCatalog.applySnapshot(snapshot.projects ?? [], cursor: snapshot.cursor, generation: projectGeneration) cursor = max(cursor, snapshot.cursor) let liveIDs = Set(turns.filter(\.isLive).map(\.id)) activity = activity.filter { liveIDs.contains($0.key) } stopping.formIntersection(liveIDs) let replied = Set(messages.filter { isFinalReply($0) }.map(\.turnId)) drafts = drafts.filter { id, draft in guard !replied.contains(id) else { return false } // A read already in flight can predate the first delta. Keep it // until a snapshot knows the turn, rather than losing byte zero. guard let turn = turns.first(where: { $0.id == id }) else { return true } return turn.isLive && (turn.attempt ?? 0) <= draft.attempt } markdown.retainMessages(Set(Feed.build(self).filter { $0.reply != nil }.map(\.id)), origin: origin) if account.teamName != snapshot.me.teamName || account.address != snapshot.me.address { account.teamName = snapshot.me.teamName; account.address = snapshot.me.address try? accounts.commit(.save(account), lifetime: lifetime) try? accounts.commit(.selectForSharing(account), lifetime: lifetime) try? accounts.commit(.selectForNotifications(account), lifetime: lifetime) } } private func isFinalReply(_ message: ThinMessage) -> Bool { guard !message.isOwn else { return false } guard let replyID = turns.first(where: { $0.id == message.turnId })?.replyId else { return true } return replyID == message.id } /// Reconciles by ID; the newer revision wins. static func merge(_ old: [T], _ new: [T]) -> [T] where T.ID == String, T: Revisioned { var byID = Dictionary(old.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) for item in new where (byID[item.id]?.revision ?? -1) <= item.revision { byID[item.id] = item } return byID.values.sorted { ($0.sortDate, $0.id) < ($1.sortDate, $1.id) } } // MARK: Following the conversation /// Follows the event stream while the app is in front. An activity /// updates the thinking line; anything else is read again through the /// snapshot. A dropped stream reconnects with backoff. public func startLive() { guard !isInvalidated, live == nil else { return } live = Task { [weak self] in var backoff = Backoff() while !Task.isCancelled { guard let self, self.status != .signedOut else { return } if self.status == .loading { await self.refresh() } guard self.lifetime.isActive else { return } do { let lines = try await self.client.events(after: self.cursor) backoff = Backoff() for try await line in lines { if Task.isCancelled { return } await self.handle(line) } } catch let error as EquipoAPIError { if error.endsSession { self.endSession(); return } if error.code == "cursor_expired" { self.cursor = 0; await self.refresh() } } catch {} if Task.isCancelled { return } try? await self.sleep(.seconds(backoff.next())) await self.refresh() } } } public func stopLive() { live?.cancel(); live = nil } /// One line of the stream. A turn's activity moves the thinking line; /// a change to something the screens show reads them again; the rest /// (runners, connections, pings) is not this app's. func handle(_ line: String) async { guard lifetime.isActive, line.hasPrefix("data:") else { return } let json = Data(line.dropFirst(5).trimmingCharacters(in: .whitespaces).utf8) guard let event = try? EquipoJSON.decoder.decode(EventEnvelope.self, from: json) else { return } if let c = event.cursor { cursor = max(cursor, c) } if event.resource == "project", let project = event.project, let sequence = event.cursor { projectCatalog.applyEvent(project, cursor: sequence) Task { await projectCatalog.refresh() } return } if event.type == "activity" { if event.resource == "turn", let data = event.activity { activity[data.turnId] = data } return } // Reply text as it streams: the finished message arrives as its own event. if event.type == "delta" { guard event.resource == "turn", let delta = event.delta, let attempt = event.attempt, attempt > 0, delta.offset >= 0, !delta.text.isEmpty, !messages.contains(where: { isFinalReply($0) && $0.turnId == delta.turnId }) else { return } if let turn = turns.first(where: { $0.id == delta.turnId }), !turn.isLive || attempt < (turn.attempt ?? 0) { return } let old = drafts[delta.turnId] guard attempt >= (old?.attempt ?? 0) else { return } var draft = old?.attempt == attempt ? old! : StreamedReply(attempt: attempt, text: "") guard delta.offset == draft.text.utf8.count else { return } draft.text += delta.text drafts[delta.turnId] = draft if !turns.contains(where: { $0.id == delta.turnId }) { requestRefresh() } return } guard Self.shown.contains(event.resource) else { return } requestRefresh() } /// Reads again soon, without holding up the stream. func requestRefresh() { guard lifetime.isActive else { return } if pendingRead != nil { readAgain = true; return } pendingRead = Task { [weak self] in guard let self else { return } repeat { self.readAgain = false await self.refresh() } while self.readAgain && !Task.isCancelled self.pendingRead = nil } } /// Waits for reads and sends already under way (tests, and before a screen settles). func settle() async { for _ in 0..<50 { await pendingRead?.value await Task.yield() if pendingRead == nil && !outgoing.contains(where: { $0.state == .sending }) { return } try? await Task.sleep(for: .milliseconds(2)) } } static let shown: Set = ["message", "turn", "card", "task", "step", "project", "member"] struct EventEnvelope: Decodable { var cursor: Int64? var type: String var resource: String var activity: ThinActivity? var project: ThinProject? var attempt: Int64? var delta: ReplyDelta? struct ReplyDelta: Decodable { var turnId: String; var offset: Int; var text: String } enum Keys: String, CodingKey { case cursor, type, resource, data, attempt } init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: Keys.self) cursor = try c.decodeIfPresent(Int64.self, forKey: .cursor) type = try c.decode(String.self, forKey: .type) resource = try c.decodeIfPresent(String.self, forKey: .resource) ?? "" attempt = try c.decodeIfPresent(Int64.self, forKey: .attempt) project = resource == "project" ? try? c.decode(ThinProject.self, forKey: .data) : nil delta = type == "delta" && resource == "turn" ? try? c.decode(ReplyDelta.self, forKey: .data) : nil activity = type == "activity" && resource == "turn" ? try? c.decode(ThinActivity.self, forKey: .data) : nil } } /// Reconnects quickly at first, then every half minute at most. struct Backoff { private var attempt = 0 mutating func next() -> Int { defer { attempt += 1 } return min(30, [2, 4, 8, 15][min(attempt, 3)] * (attempt > 3 ? 2 : 1)) } } // MARK: Sending public func sendFromComposer(_ text: String) -> Task { guard lifetime.isActive, attachments.canSend(text: text) else { return Task {} } let files = attachments.readyAttachments attachments.clear() let projectID = projectCatalog.takeSelection() return Task { await send(text, projectID: projectID, attachments: files) } } public func send(_ text: String, inThreadOf taskID: String? = nil, projectID: String? = nil, attachments: [MessageAttachment] = []) async { let text = text.trimmingCharacters(in: .whitespacesAndNewlines) 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 } 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)) await deliver(write.key) } /// Sends one outgoing message again, as itself. public func retry(_ id: String) async { if let i = outgoing.firstIndex(where: { $0.id == id }), outgoing[i].goneProject { // A definitive 404 rejected this send. A changed body is a new operation. guard let write = try? EquipoClient.message(outgoing[i].text, attachments: outgoing[i].attachments.map(\.id)) else { return } outgoing[i].write = write; outgoing[i].projectName = nil; outgoing[i].goneProject = false } await deliver(id) } private func deliver(_ id: String) async { guard lifetime.isActive, let index = outgoing.firstIndex(where: { $0.id == id }) else { return } outgoing[index].state = .sending let item = outgoing[index] do { if let taskID = item.taskID { let entry = try await client.postThread(task: taskID, item.write) guard lifetime.isActive else { return } if let i = tasks.firstIndex(where: { $0.id == taskID }) { var thread = tasks[i].thread ?? [] if !thread.contains(where: { $0.id == entry.id }) { thread.append(entry) } tasks[i].thread = thread } } else { let sent = try await client.send(item.write) guard lifetime.isActive else { return } messages = Self.merge(messages, [sent.message]) turns = Self.merge(turns, [sent.turn]) } outgoing.removeAll { $0.id == id } await refresh() } catch let error as EquipoAPIError { guard lifetime.isActive else { return } if error.endsSession { endSession(); return } if let i = outgoing.firstIndex(where: { $0.id == id }) { outgoing[i].state = error == .offline ? .waiting : .failed outgoing[i].notice = ProjectNotice.knownText(error) // This native conversation body references only one resource: its selected project. // A proxy 404, another API code, or a missing task is not evidence about that project. if case .server(404, let body) = error, body.code == "not_found", body.copyKey == "api.not_found", item.taskID == nil, let fields = try? JSONSerialization.jsonObject(with: item.write.body) as? [String: Any], let project = fields["project_id"] as? String, !project.isEmpty { outgoing[i].goneProject = true outgoing[i].projectName = nil outgoing[i].notice = EquipoStrings.text("projects.selection_lost") projectCatalog.releaseSelection(project) } } } catch { guard lifetime.isActive else { return } // Cancelled on the way: it may yet be sent, as itself. if let i = outgoing.firstIndex(where: { $0.id == id }) { outgoing[i].state = error is CancellationError ? .waiting : .failed } } } // MARK: Answering public enum AnswerOutcome: Equatable, Sendable { case answered /// The card changed or was already answered: show it as it is now; never resend. case changed case offline case failed } /// Answers a card as the person saw it, bound to that revision. A lost /// answer is retried as itself; a stale one is never sent again. public func answer(_ card: ThinCard, choice: String, note: String? = nil, rememberName: String? = nil) async -> AnswerOutcome { guard lifetime.isActive else { return .failed } guard card.isOpen else { return .changed } let slot = "\(card.id)#\(card.revision)#\(choice)#\(note ?? "")#\(rememberName ?? "")" answerNotices[card.id] = nil guard let write = unsettledAnswers[slot] ?? (try? EquipoClient.answer(choice, note: note, rememberName: rememberName, to: card)) else { return .failed } unsettledAnswers[slot] = write var attempts = 0 while true { guard lifetime.isActive else { return .failed } do { let answered = try await client.answer(card: card.id, write) guard lifetime.isActive else { return .failed } unsettledAnswers[slot] = nil cards = Self.merge(cards, [answered.card]) await refresh() return .answered } catch let error as EquipoAPIError { guard lifetime.isActive else { return .failed } if error == .offline, attempts < 2 { attempts += 1; try? await sleep(.seconds(2)); continue } // Offline: it may have landed; keep it to send again as itself. if error != .offline { unsettledAnswers[slot] = nil } if error.endsSession { endSession(); return .failed } if case .card(_, let code, let current) = error { cards = Self.merge(cards, [current]) // Build with several options needs the person's note on // which one: the card is still open, so say so (the // instance's api.direction_note), never that it changed. if code == "direction_note" { answerNotices[card.id] = EquipoStrings.text("api.direction_note"); return .failed } return .changed } if error.isStale { await refresh(); return .changed } answerNotices[card.id] = ProjectNotice.text(error) return error == .offline ? .offline : .failed } catch { unsettledAnswers[slot] = nil; return .failed } } } /// Sets a card aside, or brings it back (Undo), bound to the revision /// the person saw. It never answers, cancels or starts anything: the /// card stays in Needs you. `.answered` means the server took it; a /// card that changed is shown as it is now and never sent again. public func setAside(_ card: ThinCard, _ aside: Bool) async -> AnswerOutcome { guard lifetime.isActive else { return .failed } guard Feed.canSetAside(card) else { return .changed } let slot = "\(card.id)#\(card.revision)#\(aside)" guard let write = unsettledVisibility[slot] ?? (try? EquipoClient.visibility(aside: aside, of: card)) else { return .failed } unsettledVisibility[slot] = write var attempts = 0 while true { guard lifetime.isActive else { return .failed } do { let updated = try await client.setVisibility(card: card.id, write) guard lifetime.isActive else { return .failed } unsettledVisibility[slot] = nil cards = Self.merge(cards, [updated]) return .answered } catch let error as EquipoAPIError { guard lifetime.isActive else { return .failed } if error == .offline, attempts < 2 { attempts += 1; try? await sleep(.seconds(2)); continue } // Offline: it may have landed; keep it to send again as itself. if error != .offline { unsettledVisibility[slot] = nil } if error.endsSession { endSession(); return .failed } if case .card(_, _, let current) = error { cards = Self.merge(cards, [current]); return .changed } if error.isStale { await refresh(); return .changed } answerNotices[card.id] = ProjectNotice.text(error) return error == .offline ? .offline : .failed } catch { unsettledVisibility[slot] = nil; return .failed } } } /// Stops the coordinator's turn in flight: that turn only. /// Says whether the server took it; on false, Stop is offered again. @discardableResult public func stop(_ turn: ThinTurn) async -> Bool { guard lifetime.isActive else { return false } guard !stopping.contains(turn.id) else { return true } stopping.insert(turn.id) do { try await client.cancelTurn(turn.id) } catch { stopping.remove(turn.id); return false } guard lifetime.isActive else { return false } await refresh() return true } /// A renewed Oficina ID credential keeps the conversation and pending /// writes mounted. Every new request uses the replacement bearer. func renew(_ account: DeviceAccount, transport: EquipoTransport) { guard !isInvalidated else { return } self.account = account try? accounts.commit(.selectForSharing(account), lifetime: lifetime) try? accounts.commit(.selectForNotifications(account), lifetime: lifetime) revocationTransport = transport client = EquipoClient(transport: LifetimeTransport(inner: transport, lifetime: lifetime), token: account.credential?.token) projectCatalog.client = client attachments.client = client if status == .signedOut { status = .loading } } // MARK: Signing out private func endSession() { try? accounts.commit(.remove(account), lifetime: lifetime) invalidate() } /// Called before the app releases this session. Cancellation alone does /// not prevent a completed network response from reaching persistence. func invalidate() { try? accounts.commit(.clearShareSelection(account), lifetime: lifetime) try? accounts.commit(.clearNotificationSelection(account), lifetime: lifetime) lifetime.end() previews.invalidate() attachments.clear() markdown.removeAll() status = .signedOut drafts = [:] stopLive() pendingRead?.cancel(); pendingRead = nil } /// Forgets this device immediately, then revokes it best effort. No /// late cleanup may remove a newly signed-in account at the same origin. public func signOut() async { try? accounts.commit(.remove(account), lifetime: lifetime) invalidate() await DeviceRevocation.revoke(account, transport: revocationTransport) } } /// What `merge` needs to reconcile a resource. protocol Revisioned { var revision: Int64 { get } var sortDate: Date { get } } extension ThinMessage: Revisioned { var sortDate: Date { createdAt } } extension ThinTurn: Revisioned { var sortDate: Date { createdAt } } extension ThinCard: Revisioned { var sortDate: Date { createdAt } }