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// Paused work (spec 2026-11-24-paused-work-design.md), the minimum the
4// apps need so a held step is never a false green: the web's pauseOf
5// (pause_view.go) for the reasons that carry on by themselves, a stopped
6// step, and the amber ones only the person can move. Times are this
7// device's own zone and locale; the words are the web's, by key
8// (check-parity.py holds them to copy.go).
9
10/// Why a task waits or stopped, and the one action.
11public struct TaskPause: Sendable, Equatable {
12 /// paused (indigo, carries on by itself), warning (only you can move
13 /// it) or negative (it failed).
14 public var tone: StageTone
15 /// The stepper's current stop: Paused, Needs you or Stopped.
16 public var stop: String
17 /// The lead's bold part and the rest of it; what happens next.
18 public var strong: String
19 public var rest: String
20 public var next: String
21 /// Run now, as the instance predicts it, for the task's creator.
22 public var runNow: RunNow?
23 public var note: String?
24 public var canRetry = false
25 public var canRecover = false
26 public var settingsPath: String?
27 public var settingsLabel: String?
28 public var resumeStep: ThinStep?
29
30 public struct RunNow: Sendable, Equatable {
31 public var label: String
32 public var step: String
33 public var revision: Int64
34 /// What the button shows (the offer's connection, or "plain"): the
35 /// instance refuses the tap if Run now would now do anything else.
36 public var offer: String = ""
37 }
38}
39
40extension TaskPause {
41 /// The task's pause at now in zone, nil while nothing waits. mine: the
42 /// person is the task's creator (only they are offered Run now).
43 public init?(_ task: ThinTask, mine: Bool, now: Date = Date(), zone: TimeZone = .current, locale: Locale = .current) {
44 if let triage = task.triage, ["retrying", "rebasing", "rechecking"].contains(triage.kind) || triage.kind == "waiting" && triage.reason == "merge_unborn_default" { return nil }
45 let final = ["done", "cancelled"].contains(task.stage)
46 guard !final, task.moving != true, task.stopping != true, task.copyHold != true, task.copyCanSkip != true else { return nil }
47 let step = (task.steps ?? []).last(where: { !["preview", "research", "publish"].contains($0.specialist) })
48 if !task.needsYou.isEmpty && !["retry", "held"].contains(task.needsYou) {
49 let key = "work.needs." + task.needsYou
50 let lead = String(localized: String.LocalizationValue(key), bundle: .module)
51 guard lead != key else { return nil }
52 self.init(tone: .warning, stop: EquipoStrings.text("work.stage.needs_you"), lead: Self.format(lead), next: "")
53 canRetry = mine && step?.state == "failed" && step?.terminated == true
54 canRecover = mine && step?.state == "failed" && step?.reason == "machine_removed" && step?.terminated != true
55 return
56 }
57 guard let step else { return nil }
58 let words = TimeWords(now: now, zone: zone, locale: locale)
59 if step.state == "failed" {
60 // A runner too old for the step waits for its update (amber),
61 // as on the web; anything else stopped, in red. The stop
62 // reasons' words are the web's; the task page there says which.
63 if ["runner_outdated", "runner_too_old", "copy_update_required", "research_unsupported"].contains(step.reason), let machine = step.runnerLabel, !machine.isEmpty {
64 self.init(tone: .warning, stop: EquipoStrings.text("work.stage.needs_you"), lead: Self.format(EquipoStrings.text("work.pause.lead.too_old"), machine), next: EquipoStrings.text("work.pause.next.update"))
65 if mine { settingsPath = "/conversation/settings/machines"; settingsLabel = EquipoStrings.text("work.pause.update_runner") }
66 return
67 }
68 if step.reason == "machine_removed" && step.terminated != true {
69 self.init(tone: .warning, stop: EquipoStrings.text("work.stage.needs_you"), lead: EquipoStrings.text("work.needs.machine_removed"), next: "")
70 canRecover = mine
71 return
72 }
73 var reason = step.reason
74 if reason == "no_changes", (task.steps ?? []).prefix(while: { $0.id != step.id }).contains(where: { $0.pushed == true && !($0.candidateSha ?? "").isEmpty && ($0.specialist == "engineering" || $0.specialist == "copy" && $0.state == "done") }) { reason = "no_further_changes" }
75 self.init(tone: .negative, stop: EquipoStrings.text("work.stage.stopped"), lead: Self.format(EquipoStrings.text("work.pause.lead.stopped"), words.clockOrDay(step.finishedAt ?? now), StoppedReason.words(reason)), next: EquipoStrings.text("work.pause.next.try_again"))
76 canRetry = mine && step.terminated == true
77 return
78 }
79 guard ["queued", "running"].contains(step.state) else { return nil }
80 if step.paused?.offline == true {
81 defer { if mine { settingsPath = "/conversation/settings/machines"; settingsLabel = EquipoStrings.text("work.pause.check_machine") } }
82 guard let machine = step.runnerLabel, !machine.isEmpty else {
83 self.init(tone: .paused, stop: EquipoStrings.text("work.stage.paused"), lead: "", next: "")
84 return
85 }
86 let reason = String(format: EquipoStrings.text("work.pause.reason.offline"), machine)
87 let lead = step.paused?.since.map { Self.format(EquipoStrings.text("work.pause.since"), words.clockOrDay($0), reason) } ?? Self.format(EquipoStrings.text("work.pause.moment"), reason)
88 self.init(tone: .paused, stop: EquipoStrings.text("work.stage.paused"), lead: lead, next: String(format: EquipoStrings.text("work.pause.next.online"), machine))
89 return
90 }
91 guard let hold = step.hold else { return nil }
92 let name = ProviderNames.name(hold.provider ?? "")
93 let paused = EquipoStrings.text("work.stage.paused"), needs = EquipoStrings.text("work.stage.needs_you")
94 switch hold.reason {
95 case _ where hold.needsPerson == "no_connection" || hold.reason == "no_connection":
96 self.init(tone: .warning, stop: needs, lead: EquipoStrings.text("work.pause.lead.no_connection"), next: EquipoStrings.text("work.pause.next.choose"))
97 if mine { settingsPath = "/conversation/settings/connections/add"; settingsLabel = EquipoStrings.text("work.pause.connect") }
98 case "spend_unknown":
99 let next = String(format: EquipoStrings.text("work.pause.next.spend_unknown"), name, name)
100 self.init(tone: .warning, stop: needs, lead: Self.format(EquipoStrings.text("work.pause.lead.spend_unknown"), name), next: next)
101 if mine { resumeStep = step }
102 return
103 case _ where !(hold.needsPerson ?? "").isEmpty:
104 self.init(tone: .warning, stop: needs, lead: Self.splitLead(HeldLead.words(hold, name: name, due: task.priority?.by, words: words)), next: EquipoStrings.text("work.pause.next.choose"))
105 if hold.reason == "budget" {
106 if mine { settingsPath = "/conversation/settings/connections"; settingsLabel = EquipoStrings.text("work.hold.raise_budget") }
107 return
108 }
109 case "budget":
110 self.init(tone: .paused, stop: paused, lead: Self.until(hold.wakeAt, since: step.paused?.since, reason: String(format: EquipoStrings.text("work.pause.reason.budget"), name), words: words), next: EquipoStrings.text("work.pause.next.budget"))
111 if mine { settingsPath = "/conversation/settings/connections"; settingsLabel = EquipoStrings.text("work.hold.raise_budget") }
112 return
113 case "busy":
114 self.init(tone: .paused, stop: paused, lead: Self.format(EquipoStrings.text("work.pause.moment"), String(format: EquipoStrings.text("work.pause.reason.busy"), name)), next: EquipoStrings.text("work.pause.next.busy"))
115 return
116 default:
117 var reason = String(format: EquipoStrings.text("work.pause.reason.headroom_out"), name)
118 if let used = step.paused?.usedPercent, used < 100 {
119 reason = String(format: EquipoStrings.text("work.pause.reason.headroom_saving"), name, Int32(used))
120 }
121 let at = hold.resetsAt ?? hold.wakeAt
122 let next = at.map { $0 > now } == true ? EquipoStrings.text("work.pause.next.by_itself") : ""
123 self.init(tone: .paused, stop: paused, lead: Self.until(at, since: step.paused?.since, reason: reason, words: words), next: next)
124 }
125 if mine, let offer = step.paused?.runNow {
126 let label: String
127 switch (offer.billing ?? "", offer.same ?? false) {
128 case _ where offer.plain == true:
129 // An older runner cannot be held to one connection: no promise,
130 // and said when a connection that bills per use could take it.
131 label = EquipoStrings.text("work.hold.run_now")
132 if offer.mayBill == true { note = EquipoStrings.text("work.pause.run_now_may_bill") }
133 case ("metered", _):
134 label = String(format: EquipoStrings.text("work.pause.run_now_with"), offer.name ?? "")
135 note = String(format: EquipoStrings.text("work.pause.run_now_metered"), offer.name ?? "")
136 case (_, true):
137 label = String(format: EquipoStrings.text("work.pause.run_now_on"), offer.name ?? "")
138 if let left = offer.leftPercent, left > 0 { note = String(format: EquipoStrings.text("work.pause.run_now_last"), Int32(left)) }
139 default:
140 label = String(format: EquipoStrings.text("work.pause.run_now_with"), offer.name ?? "")
141 note = String(format: EquipoStrings.text("work.pause.run_now_room"), offer.name ?? "")
142 }
143 runNow = RunNow(label: label, step: step.id, revision: hold.stepRevision, offer: offer.plain == true ? "plain" : offer.connection ?? "")
144 }
145 }
146
147 static func splitLead(_ words: String) -> (String, String) {
148 guard let colon = words.firstIndex(of: ":") else { return ("", words) }
149 return (String(words[...colon]), String(words[words.index(after: colon)...]))
150 }
151
152 private init(tone: StageTone, stop: String, lead: (String, String), next: String) {
153 self.init(tone: tone, stop: stop, strong: lead.0, rest: lead.1, next: next)
154 }
155 private init(tone: StageTone, stop: String, lead: String, next: String) {
156 self.init(tone: tone, stop: stop, strong: "", rest: lead, next: next)
157 }
158
159 /// "Paused until 21:00 tonight (in 9 hours): …", else since when it
160 /// was held, else for a moment.
161 private static func until(_ at: Date?, since: Date?, reason: String, words: TimeWords) -> (String, String) {
162 if let at, at > words.now { return format(EquipoStrings.text("work.pause.until"), words.when(at), words.inWords(at.timeIntervalSince(words.now)), reason) }
163 if let since { return format(EquipoStrings.text("work.pause.since"), words.clockOrDay(since), reason) }
164 return format(EquipoStrings.text("work.pause.moment"), reason)
165 }
166
167 /// The copy at key with args, split where its bold part ends: at its
168 /// first colon (kept) or its first " (" (not kept), as pause.Lead does.
169 static func format(_ template: String, _ args: String...) -> (String, String) {
170 var cut = template.endIndex, keep = false
171 if let colon = template.firstIndex(of: ":") { cut = colon; keep = true }
172 if let paren = template.range(of: " (")?.lowerBound, paren < cut { cut = paren; keep = false }
173 guard cut != template.endIndex else { return ("", String(format: template, arguments: args)) }
174 let split = keep ? template.index(after: cut) : cut
175 let head = String(template[..<split]), tail = String(template[split...])
176 let n = head.components(separatedBy: "%@").count - 1
177 return (String(format: head, arguments: Array(args.prefix(n))), String(format: tail, arguments: Array(args.dropFirst(n))))
178 }
179}
180
181/// How the apps name a provider, as the web's chat.ProviderName does.
182enum ProviderNames {
183 static func name(_ provider: String) -> String {
184 switch provider {
185 case "claude": return "Claude"
186 case "codex": return "Codex"
187 case "tensorx": return "TensorX"
188 case "opencode_go": return "OpenCode Go"
189 default: return provider.prefix(1).uppercased() + provider.dropFirst()
190 }
191 }
192}
193
194/// When paused work carries on, in words (internal/equipo/pause): the
195/// device's zone and locale, relative to now.
196struct TimeWords {
197 let now: Date
198 let zone: TimeZone
199 let locale: Locale
200 static let evening = 18
201
202 private var calendar: Calendar { var c = Calendar(identifier: .gregorian); c.timeZone = zone; return c }
203 private func clock(_ at: Date) -> String {
204 var style = Date.FormatStyle(date: .omitted, time: .shortened, locale: locale, calendar: calendar, timeZone: zone)
205 style.timeZone = zone
206 let hourPattern = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: locale) ?? ""
207 if hourPattern.contains("H") || hourPattern.contains("k") {
208 style = style.hour(.twoDigits(amPM: .omitted)).minute(.twoDigits)
209 }
210 return at.formatted(style)
211 }
212 private func days(_ at: Date) -> Int {
213 calendar.dateComponents([.day], from: calendar.startOfDay(for: now), to: calendar.startOfDay(for: at)).day ?? 0
214 }
215 /// "today at 15:00", "21:00 tonight", "midnight", "tomorrow at 09:00",
216 /// else the day and the time.
217 func when(_ at: Date) -> String {
218 let parts = calendar.dateComponents([.hour, .minute], from: at)
219 switch days(at) {
220 case 1 where parts.hour == 0 && parts.minute == 0: return EquipoStrings.text("time.midnight")
221 case 0 where (parts.hour ?? 0) >= Self.evening: return String(format: EquipoStrings.text("time.tonight"), clock(at))
222 case 0: return String(format: EquipoStrings.text("time.today_at"), clock(at))
223 case 1: return String(format: EquipoStrings.text("time.tomorrow_at"), clock(at))
224 default:
225 var style = Date.FormatStyle(locale: locale, calendar: calendar, timeZone: zone).weekday(.abbreviated)
226 style.timeZone = zone
227 return at.formatted(style) + " " + clock(at)
228 }
229 }
230 /// "in 40 minutes", "in 9 hours", "in 2 days".
231 func inWords(_ seconds: TimeInterval) -> String {
232 let minutes = Int((seconds / 60).rounded(.up))
233 if minutes <= 1 { return EquipoStrings.text("time.in_minutes.one") }
234 if minutes < 60 { return String(format: EquipoStrings.text("time.in_minutes"), Int32(minutes)) }
235 if seconds < 24 * 3600 {
236 let hours = Int((seconds / 3600).rounded())
237 return hours > 1 ? String(format: EquipoStrings.text("time.in_hours"), Int32(hours)) : EquipoStrings.text("time.in_hours.one")
238 }
239 let days = Int((seconds / 86400).rounded())
240 return days > 1 ? String(format: EquipoStrings.text("time.in_days"), Int32(days)) : EquipoStrings.text("time.in_days.one")
241 }
242 /// The clock today, the day and the clock before.
243 func clockOrDay(_ at: Date) -> String {
244 if days(at) == 0 { return clock(at) }
245 var style = Date.FormatStyle(locale: locale, calendar: calendar, timeZone: zone).weekday(.abbreviated)
246 style.timeZone = zone
247 return at.formatted(style) + " " + clock(at)
248 }
249}
250