oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2
3// Roster (the web's conversation design: chat.html, chat_roster.go) fed by
4// the conversation engine's own data. Rules match chat_roster.go:
5// rosterAuthor (who speaks), rosterTone (amber waits on you, red only for a
6// failure), rosterTrack (five stops) and Compact (a report beside its open
7// decision is one line).
8
9public struct RosterByline: Sendable, Equatable {
10 public var who: Specialist
11 public var verb: String
12 public var project: String?
13 public var time: Date?
14 public init(who: Specialist, verb: String, project: String?, time: Date?) {
15 self.who = who; self.verb = verb; self.project = project; self.time = time
16 }
17 /// The coordinator shows its bare mark; its name is for VoiceOver only.
18 public var showsName: Bool { who != .coordinator }
19 public var timeText: String? { time.map { $0.formatted(date: .omitted, time: .shortened) } }
20 public var spoken: String { [who.name, verb, project, timeText].compactMap { $0 }.joined(separator: " ") }
21}
22
23// MARK: - Stages
24
25public struct RosterFact: Identifiable, Sendable, Equatable {
26 public var label: String
27 public var value: String
28 public var detail: String?
29 public var code = false
30 public var id: String { label }
31}
32
33/// A task as Roster reports it.
34public struct TaskReport: Sendable, Equatable {
35 public var task: ThinTask
36 public var title: String { task.title }
37 public var stage: Stage? { Stage(wire: task.stage) }
38 public var cancelled: Bool { task.stage == "cancelled" }
39 /// Waits on this person (their Needs you), not merely on its creator.
40 public var needsYou: Bool
41 /// The person asked for it: only they are offered Run now.
42 public var mine: Bool
43 /// Why it waits or stopped, and Run now (paused work); nil while it moves.
44 public var pause: TaskPause?
45
46 public init(_ task: ThinTask, needsYou: Bool, mine: Bool = false, now: Date = Date()) {
47 self.task = task; self.needsYou = needsYou; self.mine = mine
48 self.pause = TaskPause(task, mine: mine, now: now)
49 }
50
51 /// chat_roster.go rosterTone.
52 public var tone: StageTone {
53 if task.checks == "failed" || task.verdict == "changes_requested" { return .negative }
54 return needsYou ? .warning : .positive
55 }
56 public var eyebrow: String {
57 if cancelled { return String(localized: "stage.cancelled", bundle: .module) }
58 return stage?.label ?? task.stage
59 }
60 /// chat_roster.go rosterTrack: five stops, merging sits on Ready to merge.
61 public var track: [TrackStop] {
62 var stops = Stage.track(at: stage, tone: tone)
63 if let pause, let i = stops.firstIndex(where: { $0.state == .current }) {
64 stops[i].tone = pause.tone
65 stops[i].label = pause.stop
66 }
67 return stops
68 }
69 /// The specialist reporting now: the running or last finished step.
70 public var specialist: Specialist {
71 let steps = task.steps ?? []
72 let active = steps.last { $0.state == "running" || $0.state == "queued" } ?? steps.last { $0.state == "done" }
73 // No running or finished step (the first attempt failed or was
74 // cancelled): the task's maker, then Engineering.
75 return active.map { Specialist(category: $0.who) } ?? task.maker.map { Specialist(category: $0.category) } ?? .engineering
76 }
77 /// chat_roster.go RosterChecks, RosterReview and their details, in the web's words.
78 public var facts: [RosterFact] {
79 var out: [RosterFact] = []
80 let steps = task.steps ?? []
81 let active = steps.last { $0.state == "running" || $0.state == "queued" }
82 let checksRunning = active?.specialist == "checks"
83 if checksRunning || !task.checks.isEmpty {
84 let value = checksRunning ? "checks.running" : "checks." + task.checks
85 var detail: String?
86 switch task.checks {
87 case "cannot_run":
88 detail = EquipoStrings.text(.init(["needs_macos": "checks.needs_macos", "needs_network": "checks.needs_network",
89 "checks_timeout": "checks.timeout"][task.checksReason] ?? "checks.unavailable"))
90 case "passed", "failed":
91 if let ran = steps.last(where: { $0.specialist == "checks" && $0.state == "done" && $0.candidateSha == task.candidateSha }), !ran.gate.isEmpty {
92 detail = ran.gate
93 if task.checks == "failed", let code = ran.exitCode {
94 detail = String(localized: "checks.exit \(ran.gate) \(String(code))", bundle: .module)
95 }
96 }
97 default: break
98 }
99 if Self.known.contains(value) {
100 out.append(RosterFact(label: String(localized: "fact.checks", bundle: .module), value: EquipoStrings.text(.init(value)), detail: checksRunning ? nil : detail))
101 }
102 }
103 let reviewRunning = active?.specialist == "review"
104 if reviewRunning || !task.verdict.isEmpty {
105 let value = reviewRunning ? "review.running" : "review." + task.verdict
106 let detail = ["other_family", "same_family", "same_account"].contains(task.reviewLabel) ? EquipoStrings.text(.init("review." + task.reviewLabel)) : nil
107 if Self.known.contains(value) {
108 out.append(RosterFact(label: String(localized: "fact.review", bundle: .module), value: EquipoStrings.text(.init(value)), detail: reviewRunning ? nil : detail))
109 }
110 }
111 if !task.branch.isEmpty {
112 out.append(RosterFact(label: String(localized: "fact.branch", bundle: .module), value: task.branch,
113 detail: task.candidateSha.isEmpty ? nil : String(task.candidateSha.prefix(7)), code: true))
114 }
115 return out
116 }
117 /// Values with words; anything else is left out, never invented.
118 static let known: Set<String> = ["checks.passed", "checks.failed", "checks.none", "checks.cannot_run", "checks.running",
119 "review.approve", "review.changes_requested", "review.running"]
120 public var amadanURL: URL? { URL(string: task.url).flatMap { $0.scheme == "https" ? $0 : nil } }
121}
122
123// MARK: - The feed
124
125/// One thing in the conversation.
126public enum FeedItem: Identifiable, Sendable, Equatable {
127 case draft(ThinTurn, text: String)
128 public var reply: TranscriptReply? {
129 switch self {
130 case .coordinator(let message), .notice(let message): return TranscriptReply(text: message.text, date: message.createdAt, draft: false)
131 case .draft(let turn, let text): return TranscriptReply(text: text, date: turn.createdAt, draft: true)
132 default: return nil
133 }
134 }
135 case own(ThinMessage)
136 case coordinator(ThinMessage)
137 case notice(ThinMessage)
138 case outgoing(EquipoSession.Outgoing)
139 /// A task the conversation reports on; compact while its decision is open.
140 case report(ThinCard, RosterByline, TaskReport, compact: Bool)
141 /// A question the coordinator asks, answered here.
142 case question(ThinCard, RosterByline)
143 /// A decision: merges and the rest. Slice 1 shows it and opens the web.
144 case decision(ThinCard, RosterByline)
145 /// A one-line receipt: a project added, a home set.
146 case receipt(ThinCard, RosterByline)
147 /// The coordinator at work: what it is doing and for how long.
148 case thinking(ThinTurn, activity: String?)
149
150 public var id: String {
151 switch self {
152 case .own(let m), .notice(let m): return m.id
153 case .coordinator(let m): return m.turnId.isEmpty ? m.id : "reply-" + m.turnId
154 case .draft(let t, _): return "reply-" + t.id
155 case .outgoing(let o): return "outgoing-" + o.id
156 case .report(let c, _, _, _), .question(let c, _), .decision(let c, _), .receipt(let c, _): return c.id
157 case .thinking(let t, _): return "thinking-" + t.id
158 }
159 }
160}
161
162public enum Feed {
163 /// The conversation in time order, as Roster lays it out.
164 @MainActor public static func build(_ session: EquipoSession) -> [FeedItem] {
165 // A card set aside no longer holds its report to one line (chat_roster.go).
166 let deciding = Set(session.cards.filter { $0.isOpen && !$0.isAside && $0.kind != "task" && !$0.taskId.isEmpty }.map(\.taskId))
167 var timed: [(Date, Int, FeedItem)] = []
168 for (i, m) in session.messages.enumerated() {
169 let item: FeedItem
170 if m.isOwn { item = .own(m) }
171 else if let turn = session.turns.first(where: { $0.id == m.turnId }), let replyID = turn.replyId, replyID != m.id { item = .notice(m) }
172 else { item = .coordinator(m) }
173 timed.append((m.createdAt, i, item))
174 }
175 for (i, card) in session.cards.enumerated() {
176 let project = session.project(card.projectId)?.displayName
177 let at = card.createdAt
178 let n = session.messages.count + i
179 if card.kind == "task" {
180 guard let task = session.task(card.taskId) else { continue }
181 let report = TaskReport(task, needsYou: session.waitsOnYou(task), mine: session.isMine(task))
182 let byline = RosterByline(who: report.specialist, verb: String(localized: "byline.reports", bundle: .module), project: project, time: at)
183 timed.append((at, n, .report(card, byline, report, compact: deciding.contains(task.id))))
184 } else if isReceipt(card) {
185 timed.append((at, n, .receipt(card, RosterByline(who: .coordinator, verb: "", project: project, time: at))))
186 } else if card.kind == "question" {
187 timed.append((at, n, .question(card, RosterByline(who: .coordinator, verb: String(localized: "byline.asks", bundle: .module), project: project, time: at))))
188 } else {
189 timed.append((at, n, .decision(card, RosterByline(who: .coordinator, verb: String(localized: "byline.asks", bundle: .module), project: project, time: at))))
190 }
191 }
192 var items = timed.sorted { ($0.0, $0.1) < ($1.0, $1.1) }.map(\.2)
193 items += session.outgoing.filter { $0.taskID == nil }.map { .outgoing($0) }
194 if let turn = session.liveTurn {
195 if let draft = session.drafts[turn.id] { items.append(.draft(turn, text: draft.text)) }
196 items.append(.thinking(turn, activity: session.activity[turn.id]?.label))
197 }
198 return items
199 }
200
201 /// The card on the web: the conversation, at the card, linked as the
202 /// web links it (work_needs.html), so an older card is found too.
203 public static func webURL(for card: ThinCard, origin: URL) -> URL {
204 var c = URLComponents(url: origin.appendingPathComponent("conversation"), resolvingAgainstBaseURL: false)!
205 c.queryItems = [URLQueryItem(name: "card", value: card.id)]
206 c.fragment = "card-" + card.id
207 return c.url!
208 }
209
210 /// A receipt's line, in the web's words (chat.card.*).
211 public static func receiptLine(_ card: ThinCard) -> String {
212 switch (card.kind, card.state) {
213 case ("project", "added"): return String(localized: "receipt.added \(card.name)", bundle: .module)
214 case ("project", "created"): return String(localized: "receipt.created \(card.name)", bundle: .module)
215 case ("project", "removed"): return String(localized: "receipt.removed \(card.name)", bundle: .module)
216 case ("project", "changed"): return String(localized: "receipt.changed \(card.choice)", bundle: .module)
217 case ("project", _): return String(localized: "receipt.working \(card.name)", bundle: .module)
218 case ("home", _) where card.name.isEmpty: return String(localized: "receipt.home_cleared", bundle: .module)
219 case ("home", _): return String(localized: "receipt.home \(card.name)", bundle: .module)
220 default: return card.question.isEmpty ? card.name : card.question
221 }
222 }
223
224 /// A set-aside card's one line, as chat_roster.go AsideTitle: its
225 /// task's title, else its name, else what kind of card it is.
226 public static func asideTitle(_ card: ThinCard, task: ThinTask?) -> String {
227 if let title = task?.title, !title.isEmpty { return title }
228 if !card.name.isEmpty { return card.name }
229 return card.kind == "question" ? EquipoStrings.text("roster.question") : EquipoStrings.text("roster.decision")
230 }
231
232 /// Set aside and Undo are offered on a card that still waits on the
233 /// person (chat_roster.go Interactive): never a receipt or a report.
234 public static func canSetAside(_ card: ThinCard) -> Bool {
235 card.isOpen && card.kind != "task" && !isReceipt(card)
236 }
237
238 /// Needs you, with the tasks whose every open card is set aside under
239 /// Set aside. They still wait on the person and still count.
240 public static func needsGroups(needs: [ThinTask], cards: [ThinCard]) -> (waiting: [ThinTask], setAside: [ThinTask]) {
241 var waiting: [ThinTask] = [], setAside: [ThinTask] = []
242 for task in needs {
243 let open = cards.filter { $0.taskId == task.id && canSetAside($0) }
244 if !open.isEmpty && open.allSatisfy(\.isAside) { setAside.append(task) } else { waiting.append(task) }
245 }
246 return (waiting, setAside)
247 }
248
249 /// A receipt is a line, not a decision: a project added, a home set.
250 static func isReceipt(_ card: ThinCard) -> Bool {
251 card.kind == "project" || (card.kind == "home" && card.state != "ask")
252 }
253}
254
255// MARK: - Decisions answered here
256
257/// A decision card the device answers itself: merges and "Does main ship?",
258/// laid out exactly as the web's chat_page.go cardView and chat.html do
259/// (parity row R-02, must_match). Labels and outcome lines use the web's own
260/// copy keys (`chat.card.*`, `work.tl.*`); native/scripts/check-parity.py
261/// fails if their words differ from copy.go.
262public struct DecisionView: Sendable, Equatable {
263 public struct Choice: Sendable, Equatable, Identifiable {
264 public var value: String
265 public var label: String
266 public var primary: Bool
267 public var id: String { value }
268 }
269 public var line: String
270 public var open: Bool
271 public var choices: [Choice]
272 /// What was decided, once it was; the web's note.
273 public var note: String?
274 /// The candidate has a preview. It opens through the web's own page
275 /// (Feed.previewURL), never at the address the card carries.
276 public var hasPreview: Bool
277 /// A closed card with an outcome shows only that line, as chat.html's
278 /// equipo-card-done does: no question, no link.
279 public var showsOnlyNote: Bool { !open && note != nil }
280}
281
282/// A conflict's "This item has changed" stays until the card moves past
283/// the revision the conflict returned, so a stale tap is never followed by
284/// a silent second one.
285public enum AnswerFeedback {
286 public static func stillChanged(conflictAt: Int64, now: Int64) -> Bool { now <= conflictAt }
287}
288
289extension Feed {
290 /// nil sends the card to the web: any other kind, or a choice with no words.
291 public static func decision(_ card: ThinCard, task: ThinTask?) -> DecisionView? {
292 let primary: String, chose: String, resolved: String
293 var open = card.state == "open"
294 switch card.kind {
295 case "merge":
296 primary = "merge"; chose = "chat.card.merge_chose_"; resolved = "chat.card.merge_resolved"
297 case "merge_ships":
298 primary = "not_ships"; chose = "chat.card.ships_chose_"; resolved = "chat.card.merge_policy_stale"
299 open = open && !(card.options ?? []).isEmpty
300 default:
301 return nil
302 }
303 var choices: [DecisionView.Choice] = []
304 for value in card.options ?? [] {
305 guard let label = webText("chat.card." + value) else { return nil }
306 choices.append(.init(value: value, label: label, primary: value == primary))
307 }
308 var note: String?
309 if card.kind == "merge", task?.kind == "explore" {
310 // From before the task became an exploration: it never merges.
311 open = false; note = webText("work.tl.merge_dropped")
312 } else if card.state == "answered" {
313 note = webText(chose + card.choice)
314 } else if card.state == "resolved" {
315 note = webText(resolved)
316 }
317 // chat_page.go links a preview only on an open merge card, and always
318 // through /tasks/<id>/preview (the sandboxed, checked wrapper).
319 let preview = card.kind == "merge" && open && !(card.previewUrl ?? "").isEmpty
320 return DecisionView(line: card.question, open: open, choices: open ? choices : [], note: note, hasPreview: preview)
321 }
322
323 /// The web's preview page for a card's task: Equipo's own wrapper, which
324 /// refuses unsafe addresses and expired candidates.
325 public static func previewURL(_ card: ThinCard, origin: URL) -> URL {
326 origin.appendingPathComponent("tasks").appendingPathComponent(card.taskId).appendingPathComponent("preview")
327 }
328
329 /// A web copy key's words in the catalog, or nil when the catalog has none.
330 static func webText(_ key: String) -> String? {
331 let text = EquipoStrings.text(.init(key))
332 return text == key ? nil : text
333 }
334}
335