import Foundation // Roster (the web's conversation design: chat.html, chat_roster.go) fed by // the conversation engine's own data. Rules match chat_roster.go: // rosterAuthor (who speaks), rosterTone (amber waits on you, red only for a // failure), rosterTrack (five stops) and Compact (a report beside its open // decision is one line). public struct RosterByline: Sendable, Equatable { public var who: Specialist public var verb: String public var project: String? public var time: Date? public init(who: Specialist, verb: String, project: String?, time: Date?) { self.who = who; self.verb = verb; self.project = project; self.time = time } /// The coordinator shows its bare mark; its name is for VoiceOver only. public var showsName: Bool { who != .coordinator } public var timeText: String? { time.map { $0.formatted(date: .omitted, time: .shortened) } } public var spoken: String { [who.name, verb, project, timeText].compactMap { $0 }.joined(separator: " ") } } // MARK: - Stages public struct RosterFact: Identifiable, Sendable, Equatable { public var label: String public var value: String public var detail: String? public var code = false public var id: String { label } } /// A task as Roster reports it. public struct TaskReport: Sendable, Equatable { public var task: ThinTask public var title: String { task.title } public var stage: Stage? { Stage(wire: task.stage) } public var cancelled: Bool { task.stage == "cancelled" } /// Waits on this person (their Needs you), not merely on its creator. public var needsYou: Bool /// The person asked for it: only they are offered Run now. public var mine: Bool /// Why it waits or stopped, and Run now (paused work); nil while it moves. public var pause: TaskPause? public init(_ task: ThinTask, needsYou: Bool, mine: Bool = false, now: Date = Date()) { self.task = task; self.needsYou = needsYou; self.mine = mine self.pause = TaskPause(task, mine: mine, now: now) } /// chat_roster.go rosterTone. public var tone: StageTone { if task.checks == "failed" || task.verdict == "changes_requested" { return .negative } return needsYou ? .warning : .positive } public var eyebrow: String { if cancelled { return String(localized: "stage.cancelled", bundle: .module) } return stage?.label ?? task.stage } /// chat_roster.go rosterTrack: five stops, merging sits on Ready to merge. public var track: [TrackStop] { var stops = Stage.track(at: stage, tone: tone) if let pause, let i = stops.firstIndex(where: { $0.state == .current }) { stops[i].tone = pause.tone stops[i].label = pause.stop } return stops } /// The specialist reporting now: the running or last finished step. public var specialist: Specialist { let steps = task.steps ?? [] let active = steps.last { $0.state == "running" || $0.state == "queued" } ?? steps.last { $0.state == "done" } // No running or finished step (the first attempt failed or was // cancelled): the task's maker, then Engineering. return active.map { Specialist(category: $0.who) } ?? task.maker.map { Specialist(category: $0.category) } ?? .engineering } /// chat_roster.go RosterChecks, RosterReview and their details, in the web's words. public var facts: [RosterFact] { var out: [RosterFact] = [] let steps = task.steps ?? [] let active = steps.last { $0.state == "running" || $0.state == "queued" } let checksRunning = active?.specialist == "checks" if checksRunning || !task.checks.isEmpty { let value = checksRunning ? "checks.running" : "checks." + task.checks var detail: String? switch task.checks { case "cannot_run": detail = EquipoStrings.text(.init(["needs_macos": "checks.needs_macos", "needs_network": "checks.needs_network", "checks_timeout": "checks.timeout"][task.checksReason] ?? "checks.unavailable")) case "passed", "failed": if let ran = steps.last(where: { $0.specialist == "checks" && $0.state == "done" && $0.candidateSha == task.candidateSha }), !ran.gate.isEmpty { detail = ran.gate if task.checks == "failed", let code = ran.exitCode { detail = String(localized: "checks.exit \(ran.gate) \(String(code))", bundle: .module) } } default: break } if Self.known.contains(value) { out.append(RosterFact(label: String(localized: "fact.checks", bundle: .module), value: EquipoStrings.text(.init(value)), detail: checksRunning ? nil : detail)) } } let reviewRunning = active?.specialist == "review" if reviewRunning || !task.verdict.isEmpty { let value = reviewRunning ? "review.running" : "review." + task.verdict let detail = ["other_family", "same_family", "same_account"].contains(task.reviewLabel) ? EquipoStrings.text(.init("review." + task.reviewLabel)) : nil if Self.known.contains(value) { out.append(RosterFact(label: String(localized: "fact.review", bundle: .module), value: EquipoStrings.text(.init(value)), detail: reviewRunning ? nil : detail)) } } if !task.branch.isEmpty { out.append(RosterFact(label: String(localized: "fact.branch", bundle: .module), value: task.branch, detail: task.candidateSha.isEmpty ? nil : String(task.candidateSha.prefix(7)), code: true)) } return out } /// Values with words; anything else is left out, never invented. static let known: Set = ["checks.passed", "checks.failed", "checks.none", "checks.cannot_run", "checks.running", "review.approve", "review.changes_requested", "review.running"] public var amadanURL: URL? { URL(string: task.url).flatMap { $0.scheme == "https" ? $0 : nil } } } // MARK: - The feed /// One thing in the conversation. public enum FeedItem: Identifiable, Sendable, Equatable { case draft(ThinTurn, text: String) public var reply: TranscriptReply? { switch self { case .coordinator(let message), .notice(let message): return TranscriptReply(text: message.text, date: message.createdAt, draft: false) case .draft(let turn, let text): return TranscriptReply(text: text, date: turn.createdAt, draft: true) default: return nil } } case own(ThinMessage) case coordinator(ThinMessage) case notice(ThinMessage) case outgoing(EquipoSession.Outgoing) /// A task the conversation reports on; compact while its decision is open. case report(ThinCard, RosterByline, TaskReport, compact: Bool) /// A question the coordinator asks, answered here. case question(ThinCard, RosterByline) /// A decision: merges and the rest. Slice 1 shows it and opens the web. case decision(ThinCard, RosterByline) /// A one-line receipt: a project added, a home set. case receipt(ThinCard, RosterByline) /// The coordinator at work: what it is doing and for how long. case thinking(ThinTurn, activity: String?) public var id: String { switch self { case .own(let m), .notice(let m): return m.id case .coordinator(let m): return m.turnId.isEmpty ? m.id : "reply-" + m.turnId case .draft(let t, _): return "reply-" + t.id case .outgoing(let o): return "outgoing-" + o.id case .report(let c, _, _, _), .question(let c, _), .decision(let c, _), .receipt(let c, _): return c.id case .thinking(let t, _): return "thinking-" + t.id } } } public enum Feed { /// The conversation in time order, as Roster lays it out. @MainActor public static func build(_ session: EquipoSession) -> [FeedItem] { // A card set aside no longer holds its report to one line (chat_roster.go). let deciding = Set(session.cards.filter { $0.isOpen && !$0.isAside && $0.kind != "task" && !$0.taskId.isEmpty }.map(\.taskId)) var timed: [(Date, Int, FeedItem)] = [] for (i, m) in session.messages.enumerated() { let item: FeedItem if m.isOwn { item = .own(m) } else if let turn = session.turns.first(where: { $0.id == m.turnId }), let replyID = turn.replyId, replyID != m.id { item = .notice(m) } else { item = .coordinator(m) } timed.append((m.createdAt, i, item)) } for (i, card) in session.cards.enumerated() { let project = session.project(card.projectId)?.displayName let at = card.createdAt let n = session.messages.count + i if card.kind == "task" { guard let task = session.task(card.taskId) else { continue } let report = TaskReport(task, needsYou: session.waitsOnYou(task), mine: session.isMine(task)) let byline = RosterByline(who: report.specialist, verb: String(localized: "byline.reports", bundle: .module), project: project, time: at) timed.append((at, n, .report(card, byline, report, compact: deciding.contains(task.id)))) } else if isReceipt(card) { timed.append((at, n, .receipt(card, RosterByline(who: .coordinator, verb: "", project: project, time: at)))) } else if card.kind == "question" { timed.append((at, n, .question(card, RosterByline(who: .coordinator, verb: String(localized: "byline.asks", bundle: .module), project: project, time: at)))) } else { timed.append((at, n, .decision(card, RosterByline(who: .coordinator, verb: String(localized: "byline.asks", bundle: .module), project: project, time: at)))) } } var items = timed.sorted { ($0.0, $0.1) < ($1.0, $1.1) }.map(\.2) items += session.outgoing.filter { $0.taskID == nil }.map { .outgoing($0) } if let turn = session.liveTurn { if let draft = session.drafts[turn.id] { items.append(.draft(turn, text: draft.text)) } items.append(.thinking(turn, activity: session.activity[turn.id]?.label)) } return items } /// The card on the web: the conversation, at the card, linked as the /// web links it (work_needs.html), so an older card is found too. public static func webURL(for card: ThinCard, origin: URL) -> URL { var c = URLComponents(url: origin.appendingPathComponent("conversation"), resolvingAgainstBaseURL: false)! c.queryItems = [URLQueryItem(name: "card", value: card.id)] c.fragment = "card-" + card.id return c.url! } /// A receipt's line, in the web's words (chat.card.*). public static func receiptLine(_ card: ThinCard) -> String { switch (card.kind, card.state) { case ("project", "added"): return String(localized: "receipt.added \(card.name)", bundle: .module) case ("project", "created"): return String(localized: "receipt.created \(card.name)", bundle: .module) case ("project", "removed"): return String(localized: "receipt.removed \(card.name)", bundle: .module) case ("project", "changed"): return String(localized: "receipt.changed \(card.choice)", bundle: .module) case ("project", _): return String(localized: "receipt.working \(card.name)", bundle: .module) case ("home", _) where card.name.isEmpty: return String(localized: "receipt.home_cleared", bundle: .module) case ("home", _): return String(localized: "receipt.home \(card.name)", bundle: .module) default: return card.question.isEmpty ? card.name : card.question } } /// A set-aside card's one line, as chat_roster.go AsideTitle: its /// task's title, else its name, else what kind of card it is. public static func asideTitle(_ card: ThinCard, task: ThinTask?) -> String { if let title = task?.title, !title.isEmpty { return title } if !card.name.isEmpty { return card.name } return card.kind == "question" ? EquipoStrings.text("roster.question") : EquipoStrings.text("roster.decision") } /// Set aside and Undo are offered on a card that still waits on the /// person (chat_roster.go Interactive): never a receipt or a report. public static func canSetAside(_ card: ThinCard) -> Bool { card.isOpen && card.kind != "task" && !isReceipt(card) } /// Needs you, with the tasks whose every open card is set aside under /// Set aside. They still wait on the person and still count. public static func needsGroups(needs: [ThinTask], cards: [ThinCard]) -> (waiting: [ThinTask], setAside: [ThinTask]) { var waiting: [ThinTask] = [], setAside: [ThinTask] = [] for task in needs { let open = cards.filter { $0.taskId == task.id && canSetAside($0) } if !open.isEmpty && open.allSatisfy(\.isAside) { setAside.append(task) } else { waiting.append(task) } } return (waiting, setAside) } /// A receipt is a line, not a decision: a project added, a home set. static func isReceipt(_ card: ThinCard) -> Bool { card.kind == "project" || (card.kind == "home" && card.state != "ask") } } // MARK: - Decisions answered here /// A decision card the device answers itself: merges and "Does main ship?", /// laid out exactly as the web's chat_page.go cardView and chat.html do /// (parity row R-02, must_match). Labels and outcome lines use the web's own /// copy keys (`chat.card.*`, `work.tl.*`); native/scripts/check-parity.py /// fails if their words differ from copy.go. public struct DecisionView: Sendable, Equatable { public struct Choice: Sendable, Equatable, Identifiable { public var value: String public var label: String public var primary: Bool public var id: String { value } } public var line: String public var open: Bool public var choices: [Choice] /// What was decided, once it was; the web's note. public var note: String? /// The candidate has a preview. It opens through the web's own page /// (Feed.previewURL), never at the address the card carries. public var hasPreview: Bool /// A closed card with an outcome shows only that line, as chat.html's /// equipo-card-done does: no question, no link. public var showsOnlyNote: Bool { !open && note != nil } } /// A conflict's "This item has changed" stays until the card moves past /// the revision the conflict returned, so a stale tap is never followed by /// a silent second one. public enum AnswerFeedback { public static func stillChanged(conflictAt: Int64, now: Int64) -> Bool { now <= conflictAt } } extension Feed { /// nil sends the card to the web: any other kind, or a choice with no words. public static func decision(_ card: ThinCard, task: ThinTask?) -> DecisionView? { let primary: String, chose: String, resolved: String var open = card.state == "open" switch card.kind { case "merge": primary = "merge"; chose = "chat.card.merge_chose_"; resolved = "chat.card.merge_resolved" case "merge_ships": primary = "not_ships"; chose = "chat.card.ships_chose_"; resolved = "chat.card.merge_policy_stale" open = open && !(card.options ?? []).isEmpty default: return nil } var choices: [DecisionView.Choice] = [] for value in card.options ?? [] { guard let label = webText("chat.card." + value) else { return nil } choices.append(.init(value: value, label: label, primary: value == primary)) } var note: String? if card.kind == "merge", task?.kind == "explore" { // From before the task became an exploration: it never merges. open = false; note = webText("work.tl.merge_dropped") } else if card.state == "answered" { note = webText(chose + card.choice) } else if card.state == "resolved" { note = webText(resolved) } // chat_page.go links a preview only on an open merge card, and always // through /tasks//preview (the sandboxed, checked wrapper). let preview = card.kind == "merge" && open && !(card.previewUrl ?? "").isEmpty return DecisionView(line: card.question, open: open, choices: open ? choices : [], note: note, hasPreview: preview) } /// The web's preview page for a card's task: Equipo's own wrapper, which /// refuses unsafe addresses and expired candidates. public static func previewURL(_ card: ThinCard, origin: URL) -> URL { origin.appendingPathComponent("tasks").appendingPathComponent(card.taskId).appendingPathComponent("preview") } /// A web copy key's words in the catalog, or nil when the catalog has none. static func webText(_ key: String) -> String? { let text = EquipoStrings.text(.init(key)) return text == key ? nil : text } }